xref: /freebsd/sys/kern/subr_bus.c (revision b8b5cc330490810fc28621ac16d8147d9c53c276)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 1997,1998,2003 Doug Rabson
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 #include "opt_bus.h"
31 #include "opt_ddb.h"
32 #include "opt_iommu.h"
33 
34 #include <sys/param.h>
35 #include <sys/conf.h>
36 #include <sys/domainset.h>
37 #include <sys/eventhandler.h>
38 #include <sys/jail.h>
39 #include <sys/lock.h>
40 #include <sys/kernel.h>
41 #include <sys/limits.h>
42 #include <sys/malloc.h>
43 #include <sys/module.h>
44 #include <sys/mutex.h>
45 #include <sys/priv.h>
46 #include <machine/bus.h>
47 #include <sys/random.h>
48 #include <sys/refcount.h>
49 #include <sys/rman.h>
50 #include <sys/sbuf.h>
51 #include <sys/smp.h>
52 #include <sys/sysctl.h>
53 #include <sys/systm.h>
54 #include <sys/taskqueue.h>
55 #include <sys/bus.h>
56 #include <sys/cpuset.h>
57 #ifdef INTRNG
58 #include <sys/intr.h>
59 #endif
60 
61 #include <net/vnet.h>
62 
63 #include <machine/cpu.h>
64 #include <machine/stdarg.h>
65 
66 #include <vm/uma.h>
67 #include <vm/vm.h>
68 
69 #include <dev/iommu/iommu.h>
70 
71 #include <ddb/ddb.h>
72 
73 SYSCTL_NODE(_hw, OID_AUTO, bus, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
74     NULL);
75 SYSCTL_ROOT_NODE(OID_AUTO, dev, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
76     NULL);
77 
78 static bool disable_failed_devs = false;
79 SYSCTL_BOOL(_hw_bus, OID_AUTO, disable_failed_devices, CTLFLAG_RWTUN, &disable_failed_devs,
80     0, "Do not retry attaching devices that return an error from DEVICE_ATTACH the first time");
81 
82 /*
83  * Used to attach drivers to devclasses.
84  */
85 typedef struct driverlink *driverlink_t;
86 struct driverlink {
87 	kobj_class_t	driver;
88 	TAILQ_ENTRY(driverlink) link;	/* list of drivers in devclass */
89 	int		pass;
90 	int		flags;
91 #define DL_DEFERRED_PROBE	1	/* Probe deferred on this */
92 	TAILQ_ENTRY(driverlink) passlink;
93 };
94 
95 /*
96  * Forward declarations
97  */
98 typedef TAILQ_HEAD(devclass_list, devclass) devclass_list_t;
99 typedef TAILQ_HEAD(driver_list, driverlink) driver_list_t;
100 typedef TAILQ_HEAD(device_list, _device) device_list_t;
101 
102 struct devclass {
103 	TAILQ_ENTRY(devclass) link;
104 	devclass_t	parent;		/* parent in devclass hierarchy */
105 	driver_list_t	drivers;	/* bus devclasses store drivers for bus */
106 	char		*name;
107 	device_t	*devices;	/* array of devices indexed by unit */
108 	int		maxunit;	/* size of devices array */
109 	int		flags;
110 #define DC_HAS_CHILDREN		1
111 
112 	struct sysctl_ctx_list sysctl_ctx;
113 	struct sysctl_oid *sysctl_tree;
114 };
115 
116 struct device_prop_elm {
117 	const char *name;
118 	void *val;
119 	void *dtr_ctx;
120 	device_prop_dtr_t dtr;
121 	LIST_ENTRY(device_prop_elm) link;
122 };
123 
124 TASKQUEUE_DEFINE_THREAD(bus);
125 
126 static void device_destroy_props(device_t dev);
127 
128 /**
129  * @brief Implementation of _device.
130  *
131  * The structure is named "_device" instead of "device" to avoid type confusion
132  * caused by other subsystems defining a (struct device).
133  */
134 struct _device {
135 	/*
136 	 * A device is a kernel object. The first field must be the
137 	 * current ops table for the object.
138 	 */
139 	KOBJ_FIELDS;
140 
141 	/*
142 	 * Device hierarchy.
143 	 */
144 	TAILQ_ENTRY(_device)	link;	/**< list of devices in parent */
145 	TAILQ_ENTRY(_device)	devlink; /**< global device list membership */
146 	device_t	parent;		/**< parent of this device  */
147 	device_list_t	children;	/**< list of child devices */
148 
149 	/*
150 	 * Details of this device.
151 	 */
152 	driver_t	*driver;	/**< current driver */
153 	devclass_t	devclass;	/**< current device class */
154 	int		unit;		/**< current unit number */
155 	char*		nameunit;	/**< name+unit e.g. foodev0 */
156 	char*		desc;		/**< driver specific description */
157 	u_int		busy;		/**< count of calls to device_busy() */
158 	device_state_t	state;		/**< current device state  */
159 	uint32_t	devflags;	/**< api level flags for device_get_flags() */
160 	u_int		flags;		/**< internal device flags  */
161 	u_int	order;			/**< order from device_add_child_ordered() */
162 	void	*ivars;			/**< instance variables  */
163 	void	*softc;			/**< current driver's variables  */
164 	LIST_HEAD(, device_prop_elm) props;
165 
166 	struct sysctl_ctx_list sysctl_ctx; /**< state for sysctl variables  */
167 	struct sysctl_oid *sysctl_tree;	/**< state for sysctl variables */
168 };
169 
170 static MALLOC_DEFINE(M_BUS, "bus", "Bus data structures");
171 static MALLOC_DEFINE(M_BUS_SC, "bus-sc", "Bus data structures, softc");
172 
173 EVENTHANDLER_LIST_DEFINE(device_attach);
174 EVENTHANDLER_LIST_DEFINE(device_detach);
175 EVENTHANDLER_LIST_DEFINE(device_nomatch);
176 EVENTHANDLER_LIST_DEFINE(dev_lookup);
177 
178 static void devctl2_init(void);
179 static bool device_frozen;
180 
181 #define DRIVERNAME(d)	((d)? d->name : "no driver")
182 #define DEVCLANAME(d)	((d)? d->name : "no devclass")
183 
184 #ifdef BUS_DEBUG
185 
186 static int bus_debug = 1;
187 SYSCTL_INT(_debug, OID_AUTO, bus_debug, CTLFLAG_RWTUN, &bus_debug, 0,
188     "Bus debug level");
189 #define PDEBUG(a)	if (bus_debug) {printf("%s:%d: ", __func__, __LINE__), printf a; printf("\n");}
190 #define DEVICENAME(d)	((d)? device_get_name(d): "no device")
191 
192 /**
193  * Produce the indenting, indent*2 spaces plus a '.' ahead of that to
194  * prevent syslog from deleting initial spaces
195  */
196 #define indentprintf(p)	do { int iJ; printf("."); for (iJ=0; iJ<indent; iJ++) printf("  "); printf p ; } while (0)
197 
198 static void print_device_short(device_t dev, int indent);
199 static void print_device(device_t dev, int indent);
200 void print_device_tree_short(device_t dev, int indent);
201 void print_device_tree(device_t dev, int indent);
202 static void print_driver_short(driver_t *driver, int indent);
203 static void print_driver(driver_t *driver, int indent);
204 static void print_driver_list(driver_list_t drivers, int indent);
205 static void print_devclass_short(devclass_t dc, int indent);
206 static void print_devclass(devclass_t dc, int indent);
207 void print_devclass_list_short(void);
208 void print_devclass_list(void);
209 
210 #else
211 /* Make the compiler ignore the function calls */
212 #define PDEBUG(a)			/* nop */
213 #define DEVICENAME(d)			/* nop */
214 
215 #define print_device_short(d,i)		/* nop */
216 #define print_device(d,i)		/* nop */
217 #define print_device_tree_short(d,i)	/* nop */
218 #define print_device_tree(d,i)		/* nop */
219 #define print_driver_short(d,i)		/* nop */
220 #define print_driver(d,i)		/* nop */
221 #define print_driver_list(d,i)		/* nop */
222 #define print_devclass_short(d,i)	/* nop */
223 #define print_devclass(d,i)		/* nop */
224 #define print_devclass_list_short()	/* nop */
225 #define print_devclass_list()		/* nop */
226 #endif
227 
228 /*
229  * dev sysctl tree
230  */
231 
232 enum {
233 	DEVCLASS_SYSCTL_PARENT,
234 };
235 
236 static int
devclass_sysctl_handler(SYSCTL_HANDLER_ARGS)237 devclass_sysctl_handler(SYSCTL_HANDLER_ARGS)
238 {
239 	devclass_t dc = (devclass_t)arg1;
240 	const char *value;
241 
242 	switch (arg2) {
243 	case DEVCLASS_SYSCTL_PARENT:
244 		value = dc->parent ? dc->parent->name : "";
245 		break;
246 	default:
247 		return (EINVAL);
248 	}
249 	return (SYSCTL_OUT_STR(req, value));
250 }
251 
252 static void
devclass_sysctl_init(devclass_t dc)253 devclass_sysctl_init(devclass_t dc)
254 {
255 	if (dc->sysctl_tree != NULL)
256 		return;
257 	sysctl_ctx_init(&dc->sysctl_ctx);
258 	dc->sysctl_tree = SYSCTL_ADD_NODE(&dc->sysctl_ctx,
259 	    SYSCTL_STATIC_CHILDREN(_dev), OID_AUTO, dc->name,
260 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "");
261 	SYSCTL_ADD_PROC(&dc->sysctl_ctx, SYSCTL_CHILDREN(dc->sysctl_tree),
262 	    OID_AUTO, "%parent",
263 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
264 	    dc, DEVCLASS_SYSCTL_PARENT, devclass_sysctl_handler, "A",
265 	    "parent class");
266 }
267 
268 enum {
269 	DEVICE_SYSCTL_DESC,
270 	DEVICE_SYSCTL_DRIVER,
271 	DEVICE_SYSCTL_LOCATION,
272 	DEVICE_SYSCTL_PNPINFO,
273 	DEVICE_SYSCTL_PARENT,
274 	DEVICE_SYSCTL_IOMMU,
275 };
276 
277 static int
device_sysctl_handler(SYSCTL_HANDLER_ARGS)278 device_sysctl_handler(SYSCTL_HANDLER_ARGS)
279 {
280 	struct sbuf sb;
281 	device_t dev = (device_t)arg1;
282 	device_t iommu;
283 	int error;
284 	uint16_t rid;
285 	const char *c;
286 
287 	sbuf_new_for_sysctl(&sb, NULL, 1024, req);
288 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
289 	bus_topo_lock();
290 	switch (arg2) {
291 	case DEVICE_SYSCTL_DESC:
292 		sbuf_cat(&sb, dev->desc ? dev->desc : "");
293 		break;
294 	case DEVICE_SYSCTL_DRIVER:
295 		sbuf_cat(&sb, dev->driver ? dev->driver->name : "");
296 		break;
297 	case DEVICE_SYSCTL_LOCATION:
298 		bus_child_location(dev, &sb);
299 		break;
300 	case DEVICE_SYSCTL_PNPINFO:
301 		bus_child_pnpinfo(dev, &sb);
302 		break;
303 	case DEVICE_SYSCTL_PARENT:
304 		sbuf_cat(&sb, dev->parent ? dev->parent->nameunit : "");
305 		break;
306 	case DEVICE_SYSCTL_IOMMU:
307 		iommu = NULL;
308 		error = device_get_prop(dev, DEV_PROP_NAME_IOMMU,
309 		    (void **)&iommu);
310 		c = "";
311 		if (error == 0 && iommu != NULL) {
312 			sbuf_printf(&sb, "unit=%s", device_get_nameunit(iommu));
313 			c = " ";
314 		}
315 		rid = 0;
316 #ifdef IOMMU
317 		iommu_get_requester(dev, &rid);
318 #endif
319 		if (rid != 0)
320 			sbuf_printf(&sb, "%srid=%#x", c, rid);
321 		break;
322 	default:
323 		error = EINVAL;
324 		goto out;
325 	}
326 	error = sbuf_finish(&sb);
327 out:
328 	bus_topo_unlock();
329 	sbuf_delete(&sb);
330 	return (error);
331 }
332 
333 static void
device_sysctl_init(device_t dev)334 device_sysctl_init(device_t dev)
335 {
336 	devclass_t dc = dev->devclass;
337 	int domain;
338 
339 	if (dev->sysctl_tree != NULL)
340 		return;
341 	devclass_sysctl_init(dc);
342 	sysctl_ctx_init(&dev->sysctl_ctx);
343 	dev->sysctl_tree = SYSCTL_ADD_NODE_WITH_LABEL(&dev->sysctl_ctx,
344 	    SYSCTL_CHILDREN(dc->sysctl_tree), OID_AUTO,
345 	    dev->nameunit + strlen(dc->name),
346 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "", "device_index");
347 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
348 	    OID_AUTO, "%desc", CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
349 	    dev, DEVICE_SYSCTL_DESC, device_sysctl_handler, "A",
350 	    "device description");
351 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
352 	    OID_AUTO, "%driver",
353 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
354 	    dev, DEVICE_SYSCTL_DRIVER, device_sysctl_handler, "A",
355 	    "device driver name");
356 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
357 	    OID_AUTO, "%location",
358 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
359 	    dev, DEVICE_SYSCTL_LOCATION, device_sysctl_handler, "A",
360 	    "device location relative to parent");
361 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
362 	    OID_AUTO, "%pnpinfo",
363 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
364 	    dev, DEVICE_SYSCTL_PNPINFO, device_sysctl_handler, "A",
365 	    "device identification");
366 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
367 	    OID_AUTO, "%parent",
368 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
369 	    dev, DEVICE_SYSCTL_PARENT, device_sysctl_handler, "A",
370 	    "parent device");
371 	SYSCTL_ADD_PROC(&dev->sysctl_ctx, SYSCTL_CHILDREN(dev->sysctl_tree),
372 	    OID_AUTO, "%iommu",
373 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
374 	    dev, DEVICE_SYSCTL_IOMMU, device_sysctl_handler, "A",
375 	    "iommu unit handling the device requests");
376 	if (bus_get_domain(dev, &domain) == 0)
377 		SYSCTL_ADD_INT(&dev->sysctl_ctx,
378 		    SYSCTL_CHILDREN(dev->sysctl_tree), OID_AUTO, "%domain",
379 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, domain, "NUMA domain");
380 }
381 
382 static void
device_sysctl_update(device_t dev)383 device_sysctl_update(device_t dev)
384 {
385 	devclass_t dc = dev->devclass;
386 
387 	if (dev->sysctl_tree == NULL)
388 		return;
389 	sysctl_rename_oid(dev->sysctl_tree, dev->nameunit + strlen(dc->name));
390 }
391 
392 static void
device_sysctl_fini(device_t dev)393 device_sysctl_fini(device_t dev)
394 {
395 	if (dev->sysctl_tree == NULL)
396 		return;
397 	sysctl_ctx_free(&dev->sysctl_ctx);
398 	dev->sysctl_tree = NULL;
399 }
400 
401 static struct device_list bus_data_devices;
402 static int bus_data_generation = 1;
403 
404 static kobj_method_t null_methods[] = {
405 	KOBJMETHOD_END
406 };
407 
408 DEFINE_CLASS(null, null_methods, 0);
409 
410 void
bus_topo_assert(void)411 bus_topo_assert(void)
412 {
413 
414 	GIANT_REQUIRED;
415 }
416 
417 struct mtx *
bus_topo_mtx(void)418 bus_topo_mtx(void)
419 {
420 
421 	return (&Giant);
422 }
423 
424 void
bus_topo_lock(void)425 bus_topo_lock(void)
426 {
427 
428 	mtx_lock(bus_topo_mtx());
429 }
430 
431 void
bus_topo_unlock(void)432 bus_topo_unlock(void)
433 {
434 
435 	mtx_unlock(bus_topo_mtx());
436 }
437 
438 /*
439  * Bus pass implementation
440  */
441 
442 static driver_list_t passes = TAILQ_HEAD_INITIALIZER(passes);
443 static int bus_current_pass = BUS_PASS_ROOT;
444 
445 /**
446  * @internal
447  * @brief Register the pass level of a new driver attachment
448  *
449  * Register a new driver attachment's pass level.  If no driver
450  * attachment with the same pass level has been added, then @p new
451  * will be added to the global passes list.
452  *
453  * @param new		the new driver attachment
454  */
455 static void
driver_register_pass(struct driverlink * new)456 driver_register_pass(struct driverlink *new)
457 {
458 	struct driverlink *dl;
459 
460 	/* We only consider pass numbers during boot. */
461 	if (bus_current_pass == BUS_PASS_DEFAULT)
462 		return;
463 
464 	/*
465 	 * Walk the passes list.  If we already know about this pass
466 	 * then there is nothing to do.  If we don't, then insert this
467 	 * driver link into the list.
468 	 */
469 	TAILQ_FOREACH(dl, &passes, passlink) {
470 		if (dl->pass < new->pass)
471 			continue;
472 		if (dl->pass == new->pass)
473 			return;
474 		TAILQ_INSERT_BEFORE(dl, new, passlink);
475 		return;
476 	}
477 	TAILQ_INSERT_TAIL(&passes, new, passlink);
478 }
479 
480 /**
481  * @brief Retrieve the current bus pass
482  *
483  * Retrieves the current bus pass level.  Call the BUS_NEW_PASS()
484  * method on the root bus to kick off a new device tree scan for each
485  * new pass level that has at least one driver.
486  */
487 int
bus_get_pass(void)488 bus_get_pass(void)
489 {
490 
491 	return (bus_current_pass);
492 }
493 
494 /**
495  * @brief Raise the current bus pass
496  *
497  * Raise the current bus pass level to @p pass.  Call the BUS_NEW_PASS()
498  * method on the root bus to kick off a new device tree scan for each
499  * new pass level that has at least one driver.
500  */
501 static void
bus_set_pass(int pass)502 bus_set_pass(int pass)
503 {
504 	struct driverlink *dl;
505 
506 	if (bus_current_pass > pass)
507 		panic("Attempt to lower bus pass level");
508 
509 	TAILQ_FOREACH(dl, &passes, passlink) {
510 		/* Skip pass values below the current pass level. */
511 		if (dl->pass <= bus_current_pass)
512 			continue;
513 
514 		/*
515 		 * Bail once we hit a driver with a pass level that is
516 		 * too high.
517 		 */
518 		if (dl->pass > pass)
519 			break;
520 
521 		/*
522 		 * Raise the pass level to the next level and rescan
523 		 * the tree.
524 		 */
525 		bus_current_pass = dl->pass;
526 		BUS_NEW_PASS(root_bus);
527 	}
528 
529 	/*
530 	 * If there isn't a driver registered for the requested pass,
531 	 * then bus_current_pass might still be less than 'pass'.  Set
532 	 * it to 'pass' in that case.
533 	 */
534 	if (bus_current_pass < pass)
535 		bus_current_pass = pass;
536 	KASSERT(bus_current_pass == pass, ("Failed to update bus pass level"));
537 }
538 
539 /*
540  * Devclass implementation
541  */
542 
543 static devclass_list_t devclasses = TAILQ_HEAD_INITIALIZER(devclasses);
544 
545 /**
546  * @internal
547  * @brief Find or create a device class
548  *
549  * If a device class with the name @p classname exists, return it,
550  * otherwise if @p create is non-zero create and return a new device
551  * class.
552  *
553  * If @p parentname is non-NULL, the parent of the devclass is set to
554  * the devclass of that name.
555  *
556  * @param classname	the devclass name to find or create
557  * @param parentname	the parent devclass name or @c NULL
558  * @param create	non-zero to create a devclass
559  */
560 static devclass_t
devclass_find_internal(const char * classname,const char * parentname,int create)561 devclass_find_internal(const char *classname, const char *parentname,
562 		       int create)
563 {
564 	devclass_t dc;
565 
566 	PDEBUG(("looking for %s", classname));
567 	if (!classname)
568 		return (NULL);
569 
570 	TAILQ_FOREACH(dc, &devclasses, link) {
571 		if (!strcmp(dc->name, classname))
572 			break;
573 	}
574 
575 	if (create && !dc) {
576 		PDEBUG(("creating %s", classname));
577 		dc = malloc(sizeof(struct devclass) + strlen(classname) + 1,
578 		    M_BUS, M_WAITOK | M_ZERO);
579 		dc->parent = NULL;
580 		dc->name = (char*) (dc + 1);
581 		strcpy(dc->name, classname);
582 		TAILQ_INIT(&dc->drivers);
583 		TAILQ_INSERT_TAIL(&devclasses, dc, link);
584 
585 		bus_data_generation_update();
586 	}
587 
588 	/*
589 	 * If a parent class is specified, then set that as our parent so
590 	 * that this devclass will support drivers for the parent class as
591 	 * well.  If the parent class has the same name don't do this though
592 	 * as it creates a cycle that can trigger an infinite loop in
593 	 * device_probe_child() if a device exists for which there is no
594 	 * suitable driver.
595 	 */
596 	if (parentname && dc && !dc->parent &&
597 	    strcmp(classname, parentname) != 0) {
598 		dc->parent = devclass_find_internal(parentname, NULL, TRUE);
599 		dc->parent->flags |= DC_HAS_CHILDREN;
600 	}
601 
602 	return (dc);
603 }
604 
605 /**
606  * @brief Create a device class
607  *
608  * If a device class with the name @p classname exists, return it,
609  * otherwise create and return a new device class.
610  *
611  * @param classname	the devclass name to find or create
612  */
613 devclass_t
devclass_create(const char * classname)614 devclass_create(const char *classname)
615 {
616 	return (devclass_find_internal(classname, NULL, TRUE));
617 }
618 
619 /**
620  * @brief Find a device class
621  *
622  * If a device class with the name @p classname exists, return it,
623  * otherwise return @c NULL.
624  *
625  * @param classname	the devclass name to find
626  */
627 devclass_t
devclass_find(const char * classname)628 devclass_find(const char *classname)
629 {
630 	return (devclass_find_internal(classname, NULL, FALSE));
631 }
632 
633 /**
634  * @brief Register that a device driver has been added to a devclass
635  *
636  * Register that a device driver has been added to a devclass.  This
637  * is called by devclass_add_driver to accomplish the recursive
638  * notification of all the children classes of dc, as well as dc.
639  * Each layer will have BUS_DRIVER_ADDED() called for all instances of
640  * the devclass.
641  *
642  * We do a full search here of the devclass list at each iteration
643  * level to save storing children-lists in the devclass structure.  If
644  * we ever move beyond a few dozen devices doing this, we may need to
645  * reevaluate...
646  *
647  * @param dc		the devclass to edit
648  * @param driver	the driver that was just added
649  */
650 static void
devclass_driver_added(devclass_t dc,driver_t * driver)651 devclass_driver_added(devclass_t dc, driver_t *driver)
652 {
653 	devclass_t parent;
654 	int i;
655 
656 	/*
657 	 * Call BUS_DRIVER_ADDED for any existing buses in this class.
658 	 */
659 	for (i = 0; i < dc->maxunit; i++)
660 		if (dc->devices[i] && device_is_attached(dc->devices[i]))
661 			BUS_DRIVER_ADDED(dc->devices[i], driver);
662 
663 	/*
664 	 * Walk through the children classes.  Since we only keep a
665 	 * single parent pointer around, we walk the entire list of
666 	 * devclasses looking for children.  We set the
667 	 * DC_HAS_CHILDREN flag when a child devclass is created on
668 	 * the parent, so we only walk the list for those devclasses
669 	 * that have children.
670 	 */
671 	if (!(dc->flags & DC_HAS_CHILDREN))
672 		return;
673 	parent = dc;
674 	TAILQ_FOREACH(dc, &devclasses, link) {
675 		if (dc->parent == parent)
676 			devclass_driver_added(dc, driver);
677 	}
678 }
679 
680 static void
device_handle_nomatch(device_t dev)681 device_handle_nomatch(device_t dev)
682 {
683 	BUS_PROBE_NOMATCH(dev->parent, dev);
684 	EVENTHANDLER_DIRECT_INVOKE(device_nomatch, dev);
685 	dev->flags |= DF_DONENOMATCH;
686 }
687 
688 /**
689  * @brief Add a device driver to a device class
690  *
691  * Add a device driver to a devclass. This is normally called
692  * automatically by DRIVER_MODULE(). The BUS_DRIVER_ADDED() method of
693  * all devices in the devclass will be called to allow them to attempt
694  * to re-probe any unmatched children.
695  *
696  * @param dc		the devclass to edit
697  * @param driver	the driver to register
698  */
699 int
devclass_add_driver(devclass_t dc,driver_t * driver,int pass,devclass_t * dcp)700 devclass_add_driver(devclass_t dc, driver_t *driver, int pass, devclass_t *dcp)
701 {
702 	driverlink_t dl;
703 	devclass_t child_dc;
704 	const char *parentname;
705 
706 	PDEBUG(("%s", DRIVERNAME(driver)));
707 
708 	/* Don't allow invalid pass values. */
709 	if (pass <= BUS_PASS_ROOT)
710 		return (EINVAL);
711 
712 	dl = malloc(sizeof *dl, M_BUS, M_WAITOK|M_ZERO);
713 
714 	/*
715 	 * Compile the driver's methods. Also increase the reference count
716 	 * so that the class doesn't get freed when the last instance
717 	 * goes. This means we can safely use static methods and avoids a
718 	 * double-free in devclass_delete_driver.
719 	 */
720 	kobj_class_compile((kobj_class_t) driver);
721 
722 	/*
723 	 * If the driver has any base classes, make the
724 	 * devclass inherit from the devclass of the driver's
725 	 * first base class. This will allow the system to
726 	 * search for drivers in both devclasses for children
727 	 * of a device using this driver.
728 	 */
729 	if (driver->baseclasses)
730 		parentname = driver->baseclasses[0]->name;
731 	else
732 		parentname = NULL;
733 	child_dc = devclass_find_internal(driver->name, parentname, TRUE);
734 	if (dcp != NULL)
735 		*dcp = child_dc;
736 
737 	dl->driver = driver;
738 	TAILQ_INSERT_TAIL(&dc->drivers, dl, link);
739 	driver->refs++;		/* XXX: kobj_mtx */
740 	dl->pass = pass;
741 	driver_register_pass(dl);
742 
743 	if (device_frozen) {
744 		dl->flags |= DL_DEFERRED_PROBE;
745 	} else {
746 		devclass_driver_added(dc, driver);
747 	}
748 	bus_data_generation_update();
749 	return (0);
750 }
751 
752 /**
753  * @brief Register that a device driver has been deleted from a devclass
754  *
755  * Register that a device driver has been removed from a devclass.
756  * This is called by devclass_delete_driver to accomplish the
757  * recursive notification of all the children classes of busclass, as
758  * well as busclass.  Each layer will attempt to detach the driver
759  * from any devices that are children of the bus's devclass.  The function
760  * will return an error if a device fails to detach.
761  *
762  * We do a full search here of the devclass list at each iteration
763  * level to save storing children-lists in the devclass structure.  If
764  * we ever move beyond a few dozen devices doing this, we may need to
765  * reevaluate...
766  *
767  * @param busclass	the devclass of the parent bus
768  * @param dc		the devclass of the driver being deleted
769  * @param driver	the driver being deleted
770  */
771 static int
devclass_driver_deleted(devclass_t busclass,devclass_t dc,driver_t * driver)772 devclass_driver_deleted(devclass_t busclass, devclass_t dc, driver_t *driver)
773 {
774 	devclass_t parent;
775 	device_t dev;
776 	int error, i;
777 
778 	/*
779 	 * Disassociate from any devices.  We iterate through all the
780 	 * devices in the devclass of the driver and detach any which are
781 	 * using the driver and which have a parent in the devclass which
782 	 * we are deleting from.
783 	 *
784 	 * Note that since a driver can be in multiple devclasses, we
785 	 * should not detach devices which are not children of devices in
786 	 * the affected devclass.
787 	 *
788 	 * If we're frozen, we don't generate NOMATCH events. Mark to
789 	 * generate later.
790 	 */
791 	for (i = 0; i < dc->maxunit; i++) {
792 		if (dc->devices[i]) {
793 			dev = dc->devices[i];
794 			if (dev->driver == driver && dev->parent &&
795 			    dev->parent->devclass == busclass) {
796 				if ((error = device_detach(dev)) != 0)
797 					return (error);
798 				if (device_frozen) {
799 					dev->flags &= ~DF_DONENOMATCH;
800 					dev->flags |= DF_NEEDNOMATCH;
801 				} else {
802 					device_handle_nomatch(dev);
803 				}
804 			}
805 		}
806 	}
807 
808 	/*
809 	 * Walk through the children classes.  Since we only keep a
810 	 * single parent pointer around, we walk the entire list of
811 	 * devclasses looking for children.  We set the
812 	 * DC_HAS_CHILDREN flag when a child devclass is created on
813 	 * the parent, so we only walk the list for those devclasses
814 	 * that have children.
815 	 */
816 	if (!(busclass->flags & DC_HAS_CHILDREN))
817 		return (0);
818 	parent = busclass;
819 	TAILQ_FOREACH(busclass, &devclasses, link) {
820 		if (busclass->parent == parent) {
821 			error = devclass_driver_deleted(busclass, dc, driver);
822 			if (error)
823 				return (error);
824 		}
825 	}
826 	return (0);
827 }
828 
829 /**
830  * @brief Delete a device driver from a device class
831  *
832  * Delete a device driver from a devclass. This is normally called
833  * automatically by DRIVER_MODULE().
834  *
835  * If the driver is currently attached to any devices,
836  * devclass_delete_driver() will first attempt to detach from each
837  * device. If one of the detach calls fails, the driver will not be
838  * deleted.
839  *
840  * @param dc		the devclass to edit
841  * @param driver	the driver to unregister
842  */
843 int
devclass_delete_driver(devclass_t busclass,driver_t * driver)844 devclass_delete_driver(devclass_t busclass, driver_t *driver)
845 {
846 	devclass_t dc = devclass_find(driver->name);
847 	driverlink_t dl;
848 	int error;
849 
850 	PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
851 
852 	if (!dc)
853 		return (0);
854 
855 	/*
856 	 * Find the link structure in the bus' list of drivers.
857 	 */
858 	TAILQ_FOREACH(dl, &busclass->drivers, link) {
859 		if (dl->driver == driver)
860 			break;
861 	}
862 
863 	if (!dl) {
864 		PDEBUG(("%s not found in %s list", driver->name,
865 		    busclass->name));
866 		return (ENOENT);
867 	}
868 
869 	error = devclass_driver_deleted(busclass, dc, driver);
870 	if (error != 0)
871 		return (error);
872 
873 	TAILQ_REMOVE(&busclass->drivers, dl, link);
874 	free(dl, M_BUS);
875 
876 	/* XXX: kobj_mtx */
877 	driver->refs--;
878 	if (driver->refs == 0)
879 		kobj_class_free((kobj_class_t) driver);
880 
881 	bus_data_generation_update();
882 	return (0);
883 }
884 
885 /**
886  * @brief Quiesces a set of device drivers from a device class
887  *
888  * Quiesce a device driver from a devclass. This is normally called
889  * automatically by DRIVER_MODULE().
890  *
891  * If the driver is currently attached to any devices,
892  * devclass_quiesece_driver() will first attempt to quiesce each
893  * device.
894  *
895  * @param dc		the devclass to edit
896  * @param driver	the driver to unregister
897  */
898 static int
devclass_quiesce_driver(devclass_t busclass,driver_t * driver)899 devclass_quiesce_driver(devclass_t busclass, driver_t *driver)
900 {
901 	devclass_t dc = devclass_find(driver->name);
902 	driverlink_t dl;
903 	device_t dev;
904 	int i;
905 	int error;
906 
907 	PDEBUG(("%s from devclass %s", driver->name, DEVCLANAME(busclass)));
908 
909 	if (!dc)
910 		return (0);
911 
912 	/*
913 	 * Find the link structure in the bus' list of drivers.
914 	 */
915 	TAILQ_FOREACH(dl, &busclass->drivers, link) {
916 		if (dl->driver == driver)
917 			break;
918 	}
919 
920 	if (!dl) {
921 		PDEBUG(("%s not found in %s list", driver->name,
922 		    busclass->name));
923 		return (ENOENT);
924 	}
925 
926 	/*
927 	 * Quiesce all devices.  We iterate through all the devices in
928 	 * the devclass of the driver and quiesce any which are using
929 	 * the driver and which have a parent in the devclass which we
930 	 * are quiescing.
931 	 *
932 	 * Note that since a driver can be in multiple devclasses, we
933 	 * should not quiesce devices which are not children of
934 	 * devices in the affected devclass.
935 	 */
936 	for (i = 0; i < dc->maxunit; i++) {
937 		if (dc->devices[i]) {
938 			dev = dc->devices[i];
939 			if (dev->driver == driver && dev->parent &&
940 			    dev->parent->devclass == busclass) {
941 				if ((error = device_quiesce(dev)) != 0)
942 					return (error);
943 			}
944 		}
945 	}
946 
947 	return (0);
948 }
949 
950 /**
951  * @internal
952  */
953 static driverlink_t
devclass_find_driver_internal(devclass_t dc,const char * classname)954 devclass_find_driver_internal(devclass_t dc, const char *classname)
955 {
956 	driverlink_t dl;
957 
958 	PDEBUG(("%s in devclass %s", classname, DEVCLANAME(dc)));
959 
960 	TAILQ_FOREACH(dl, &dc->drivers, link) {
961 		if (!strcmp(dl->driver->name, classname))
962 			return (dl);
963 	}
964 
965 	PDEBUG(("not found"));
966 	return (NULL);
967 }
968 
969 /**
970  * @brief Return the name of the devclass
971  */
972 const char *
devclass_get_name(devclass_t dc)973 devclass_get_name(devclass_t dc)
974 {
975 	return (dc->name);
976 }
977 
978 /**
979  * @brief Find a device given a unit number
980  *
981  * @param dc		the devclass to search
982  * @param unit		the unit number to search for
983  *
984  * @returns		the device with the given unit number or @c
985  *			NULL if there is no such device
986  */
987 device_t
devclass_get_device(devclass_t dc,int unit)988 devclass_get_device(devclass_t dc, int unit)
989 {
990 	if (dc == NULL || unit < 0 || unit >= dc->maxunit)
991 		return (NULL);
992 	return (dc->devices[unit]);
993 }
994 
995 /**
996  * @brief Find the softc field of a device given a unit number
997  *
998  * @param dc		the devclass to search
999  * @param unit		the unit number to search for
1000  *
1001  * @returns		the softc field of the device with the given
1002  *			unit number or @c NULL if there is no such
1003  *			device
1004  */
1005 void *
devclass_get_softc(devclass_t dc,int unit)1006 devclass_get_softc(devclass_t dc, int unit)
1007 {
1008 	device_t dev;
1009 
1010 	dev = devclass_get_device(dc, unit);
1011 	if (!dev)
1012 		return (NULL);
1013 
1014 	return (device_get_softc(dev));
1015 }
1016 
1017 /**
1018  * @brief Get a list of devices in the devclass
1019  *
1020  * An array containing a list of all the devices in the given devclass
1021  * is allocated and returned in @p *devlistp. The number of devices
1022  * in the array is returned in @p *devcountp. The caller should free
1023  * the array using @c free(p, M_TEMP), even if @p *devcountp is 0.
1024  *
1025  * @param dc		the devclass to examine
1026  * @param devlistp	points at location for array pointer return
1027  *			value
1028  * @param devcountp	points at location for array size return value
1029  *
1030  * @retval 0		success
1031  * @retval ENOMEM	the array allocation failed
1032  */
1033 int
devclass_get_devices(devclass_t dc,device_t ** devlistp,int * devcountp)1034 devclass_get_devices(devclass_t dc, device_t **devlistp, int *devcountp)
1035 {
1036 	int count, i;
1037 	device_t *list;
1038 
1039 	count = devclass_get_count(dc);
1040 	list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
1041 	if (!list)
1042 		return (ENOMEM);
1043 
1044 	count = 0;
1045 	for (i = 0; i < dc->maxunit; i++) {
1046 		if (dc->devices[i]) {
1047 			list[count] = dc->devices[i];
1048 			count++;
1049 		}
1050 	}
1051 
1052 	*devlistp = list;
1053 	*devcountp = count;
1054 
1055 	return (0);
1056 }
1057 
1058 /**
1059  * @brief Get a list of drivers in the devclass
1060  *
1061  * An array containing a list of pointers to all the drivers in the
1062  * given devclass is allocated and returned in @p *listp.  The number
1063  * of drivers in the array is returned in @p *countp. The caller should
1064  * free the array using @c free(p, M_TEMP).
1065  *
1066  * @param dc		the devclass to examine
1067  * @param listp		gives location for array pointer return value
1068  * @param countp	gives location for number of array elements
1069  *			return value
1070  *
1071  * @retval 0		success
1072  * @retval ENOMEM	the array allocation failed
1073  */
1074 int
devclass_get_drivers(devclass_t dc,driver_t *** listp,int * countp)1075 devclass_get_drivers(devclass_t dc, driver_t ***listp, int *countp)
1076 {
1077 	driverlink_t dl;
1078 	driver_t **list;
1079 	int count;
1080 
1081 	count = 0;
1082 	TAILQ_FOREACH(dl, &dc->drivers, link)
1083 		count++;
1084 	list = malloc(count * sizeof(driver_t *), M_TEMP, M_NOWAIT);
1085 	if (list == NULL)
1086 		return (ENOMEM);
1087 
1088 	count = 0;
1089 	TAILQ_FOREACH(dl, &dc->drivers, link) {
1090 		list[count] = dl->driver;
1091 		count++;
1092 	}
1093 	*listp = list;
1094 	*countp = count;
1095 
1096 	return (0);
1097 }
1098 
1099 /**
1100  * @brief Get the number of devices in a devclass
1101  *
1102  * @param dc		the devclass to examine
1103  */
1104 int
devclass_get_count(devclass_t dc)1105 devclass_get_count(devclass_t dc)
1106 {
1107 	int count, i;
1108 
1109 	count = 0;
1110 	for (i = 0; i < dc->maxunit; i++)
1111 		if (dc->devices[i])
1112 			count++;
1113 	return (count);
1114 }
1115 
1116 /**
1117  * @brief Get the maximum unit number used in a devclass
1118  *
1119  * Note that this is one greater than the highest currently-allocated unit.  If
1120  * @p dc is NULL, @c -1 is returned to indicate that not even the devclass has
1121  * been allocated yet.
1122  *
1123  * @param dc		the devclass to examine
1124  */
1125 int
devclass_get_maxunit(devclass_t dc)1126 devclass_get_maxunit(devclass_t dc)
1127 {
1128 	if (dc == NULL)
1129 		return (-1);
1130 	return (dc->maxunit);
1131 }
1132 
1133 /**
1134  * @brief Find a free unit number in a devclass
1135  *
1136  * This function searches for the first unused unit number greater
1137  * that or equal to @p unit. Note: This can return INT_MAX which
1138  * may be rejected elsewhere.
1139  *
1140  * @param dc		the devclass to examine
1141  * @param unit		the first unit number to check
1142  */
1143 int
devclass_find_free_unit(devclass_t dc,int unit)1144 devclass_find_free_unit(devclass_t dc, int unit)
1145 {
1146 	if (dc == NULL)
1147 		return (unit);
1148 	while (unit < dc->maxunit && dc->devices[unit] != NULL)
1149 		unit++;
1150 	return (unit);
1151 }
1152 
1153 /**
1154  * @brief Set the parent of a devclass
1155  *
1156  * The parent class is normally initialised automatically by
1157  * DRIVER_MODULE().
1158  *
1159  * @param dc		the devclass to edit
1160  * @param pdc		the new parent devclass
1161  */
1162 void
devclass_set_parent(devclass_t dc,devclass_t pdc)1163 devclass_set_parent(devclass_t dc, devclass_t pdc)
1164 {
1165 	dc->parent = pdc;
1166 }
1167 
1168 /**
1169  * @brief Get the parent of a devclass
1170  *
1171  * @param dc		the devclass to examine
1172  */
1173 devclass_t
devclass_get_parent(devclass_t dc)1174 devclass_get_parent(devclass_t dc)
1175 {
1176 	return (dc->parent);
1177 }
1178 
1179 struct sysctl_ctx_list *
devclass_get_sysctl_ctx(devclass_t dc)1180 devclass_get_sysctl_ctx(devclass_t dc)
1181 {
1182 	return (&dc->sysctl_ctx);
1183 }
1184 
1185 struct sysctl_oid *
devclass_get_sysctl_tree(devclass_t dc)1186 devclass_get_sysctl_tree(devclass_t dc)
1187 {
1188 	return (dc->sysctl_tree);
1189 }
1190 
1191 /**
1192  * @internal
1193  * @brief Allocate a unit number
1194  *
1195  * On entry, @p *unitp is the desired unit number (or @c DEVICE_UNIT_ANY if any
1196  * will do). The allocated unit number is returned in @p *unitp.
1197  *
1198  * @param dc		the devclass to allocate from
1199  * @param unitp		points at the location for the allocated unit
1200  *			number
1201  *
1202  * @retval 0		success
1203  * @retval EEXIST	the requested unit number is already allocated
1204  * @retval ENOMEM	memory allocation failure
1205  * @retval EINVAL	unit is negative or we've run out of units
1206  */
1207 static int
devclass_alloc_unit(devclass_t dc,device_t dev,int * unitp)1208 devclass_alloc_unit(devclass_t dc, device_t dev, int *unitp)
1209 {
1210 	const char *s;
1211 	int unit = *unitp;
1212 
1213 	PDEBUG(("unit %d in devclass %s", unit, DEVCLANAME(dc)));
1214 
1215 	/* Ask the parent bus if it wants to wire this device. */
1216 	if (unit == DEVICE_UNIT_ANY)
1217 		BUS_HINT_DEVICE_UNIT(device_get_parent(dev), dev, dc->name,
1218 		    &unit);
1219 
1220 	/* Unit numbers are either DEVICE_UNIT_ANY or in [0,INT_MAX) */
1221 	if ((unit < 0 && unit != DEVICE_UNIT_ANY) || unit == INT_MAX)
1222 		return (EINVAL);
1223 
1224 	/* If we were given a wired unit number, check for existing device */
1225 	if (unit != DEVICE_UNIT_ANY) {
1226 		if (unit < dc->maxunit && dc->devices[unit] != NULL) {
1227 			if (bootverbose)
1228 				printf("%s: %s%d already exists; skipping it\n",
1229 				    dc->name, dc->name, *unitp);
1230 			return (EEXIST);
1231 		}
1232 	} else {
1233 		/* Unwired device, find the next available slot for it */
1234 		unit = 0;
1235 		for (unit = 0; unit < INT_MAX; unit++) {
1236 			/* If this device slot is already in use, skip it. */
1237 			if (unit < dc->maxunit && dc->devices[unit] != NULL)
1238 				continue;
1239 
1240 			/* If there is an "at" hint for a unit then skip it. */
1241 			if (resource_string_value(dc->name, unit, "at", &s) ==
1242 			    0)
1243 				continue;
1244 
1245 			break;
1246 		}
1247 	}
1248 
1249 	/*
1250 	 * Unit numbers must be in the range [0, INT_MAX), so exclude INT_MAX as
1251 	 * too large. We constrain maxunit below to be <= INT_MAX. This means we
1252 	 * can treat unit and maxunit as normal integers with normal math
1253 	 * everywhere and we only have to flag INT_MAX as invalid.
1254 	 */
1255 	if (unit == INT_MAX)
1256 		return (EINVAL);
1257 
1258 	/*
1259 	 * We've selected a unit beyond the length of the table, so let's extend
1260 	 * the table to make room for all units up to and including this one.
1261 	 */
1262 	if (unit >= dc->maxunit) {
1263 		int newsize;
1264 
1265 		newsize = unit + 1;
1266 		dc->devices = reallocf(dc->devices,
1267 		    newsize * sizeof(*dc->devices), M_BUS, M_WAITOK);
1268 		memset(dc->devices + dc->maxunit, 0,
1269 		    sizeof(device_t) * (newsize - dc->maxunit));
1270 		dc->maxunit = newsize;
1271 	}
1272 	PDEBUG(("now: unit %d in devclass %s", unit, DEVCLANAME(dc)));
1273 
1274 	*unitp = unit;
1275 	return (0);
1276 }
1277 
1278 /**
1279  * @internal
1280  * @brief Add a device to a devclass
1281  *
1282  * A unit number is allocated for the device (using the device's
1283  * preferred unit number if any) and the device is registered in the
1284  * devclass. This allows the device to be looked up by its unit
1285  * number, e.g. by decoding a dev_t minor number.
1286  *
1287  * @param dc		the devclass to add to
1288  * @param dev		the device to add
1289  *
1290  * @retval 0		success
1291  * @retval EEXIST	the requested unit number is already allocated
1292  * @retval ENOMEM	memory allocation failure
1293  * @retval EINVAL	Unit number invalid or too many units
1294  */
1295 static int
devclass_add_device(devclass_t dc,device_t dev)1296 devclass_add_device(devclass_t dc, device_t dev)
1297 {
1298 	int buflen, error;
1299 
1300 	PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
1301 
1302 	buflen = snprintf(NULL, 0, "%s%d$", dc->name, INT_MAX);
1303 	if (buflen < 0)
1304 		return (ENOMEM);
1305 	dev->nameunit = malloc(buflen, M_BUS, M_WAITOK|M_ZERO);
1306 
1307 	if ((error = devclass_alloc_unit(dc, dev, &dev->unit)) != 0) {
1308 		free(dev->nameunit, M_BUS);
1309 		dev->nameunit = NULL;
1310 		return (error);
1311 	}
1312 	dc->devices[dev->unit] = dev;
1313 	dev->devclass = dc;
1314 	snprintf(dev->nameunit, buflen, "%s%d", dc->name, dev->unit);
1315 
1316 	return (0);
1317 }
1318 
1319 /**
1320  * @internal
1321  * @brief Delete a device from a devclass
1322  *
1323  * The device is removed from the devclass's device list and its unit
1324  * number is freed.
1325 
1326  * @param dc		the devclass to delete from
1327  * @param dev		the device to delete
1328  *
1329  * @retval 0		success
1330  */
1331 static int
devclass_delete_device(devclass_t dc,device_t dev)1332 devclass_delete_device(devclass_t dc, device_t dev)
1333 {
1334 	if (!dc || !dev)
1335 		return (0);
1336 
1337 	PDEBUG(("%s in devclass %s", DEVICENAME(dev), DEVCLANAME(dc)));
1338 
1339 	if (dev->devclass != dc || dc->devices[dev->unit] != dev)
1340 		panic("devclass_delete_device: inconsistent device class");
1341 	dc->devices[dev->unit] = NULL;
1342 	if (dev->flags & DF_WILDCARD)
1343 		dev->unit = DEVICE_UNIT_ANY;
1344 	dev->devclass = NULL;
1345 	free(dev->nameunit, M_BUS);
1346 	dev->nameunit = NULL;
1347 
1348 	return (0);
1349 }
1350 
1351 /**
1352  * @internal
1353  * @brief Make a new device and add it as a child of @p parent
1354  *
1355  * @param parent	the parent of the new device
1356  * @param name		the devclass name of the new device or @c NULL
1357  *			to leave the devclass unspecified
1358  * @parem unit		the unit number of the new device of @c DEVICE_UNIT_ANY
1359  *			to leave the unit number unspecified
1360  *
1361  * @returns the new device
1362  */
1363 static device_t
make_device(device_t parent,const char * name,int unit)1364 make_device(device_t parent, const char *name, int unit)
1365 {
1366 	device_t dev;
1367 	devclass_t dc;
1368 
1369 	PDEBUG(("%s at %s as unit %d", name, DEVICENAME(parent), unit));
1370 
1371 	if (name) {
1372 		dc = devclass_find_internal(name, NULL, TRUE);
1373 		if (!dc) {
1374 			printf("make_device: can't find device class %s\n",
1375 			    name);
1376 			return (NULL);
1377 		}
1378 	} else {
1379 		dc = NULL;
1380 	}
1381 
1382 	dev = malloc(sizeof(*dev), M_BUS, M_WAITOK|M_ZERO);
1383 	dev->parent = parent;
1384 	TAILQ_INIT(&dev->children);
1385 	kobj_init((kobj_t) dev, &null_class);
1386 	dev->driver = NULL;
1387 	dev->devclass = NULL;
1388 	dev->unit = unit;
1389 	dev->nameunit = NULL;
1390 	dev->desc = NULL;
1391 	dev->busy = 0;
1392 	dev->devflags = 0;
1393 	dev->flags = DF_ENABLED;
1394 	dev->order = 0;
1395 	if (unit == DEVICE_UNIT_ANY)
1396 		dev->flags |= DF_WILDCARD;
1397 	if (name) {
1398 		dev->flags |= DF_FIXEDCLASS;
1399 		if (devclass_add_device(dc, dev)) {
1400 			kobj_delete((kobj_t) dev, M_BUS);
1401 			return (NULL);
1402 		}
1403 	}
1404 	if (parent != NULL && device_has_quiet_children(parent))
1405 		dev->flags |= DF_QUIET | DF_QUIET_CHILDREN;
1406 	dev->ivars = NULL;
1407 	dev->softc = NULL;
1408 	LIST_INIT(&dev->props);
1409 
1410 	dev->state = DS_NOTPRESENT;
1411 
1412 	TAILQ_INSERT_TAIL(&bus_data_devices, dev, devlink);
1413 	bus_data_generation_update();
1414 
1415 	return (dev);
1416 }
1417 
1418 /**
1419  * @internal
1420  * @brief Print a description of a device.
1421  */
1422 static int
device_print_child(device_t dev,device_t child)1423 device_print_child(device_t dev, device_t child)
1424 {
1425 	int retval = 0;
1426 
1427 	if (device_is_alive(child))
1428 		retval += BUS_PRINT_CHILD(dev, child);
1429 	else
1430 		retval += device_printf(child, " not found\n");
1431 
1432 	return (retval);
1433 }
1434 
1435 /**
1436  * @brief Create a new device
1437  *
1438  * This creates a new device and adds it as a child of an existing
1439  * parent device. The new device will be added after the last existing
1440  * child with order zero.
1441  *
1442  * @param dev		the device which will be the parent of the
1443  *			new child device
1444  * @param name		devclass name for new device or @c NULL if not
1445  *			specified
1446  * @param unit		unit number for new device or @c DEVICE_UNIT_ANY if not
1447  *			specified
1448  *
1449  * @returns		the new device
1450  */
1451 device_t
device_add_child(device_t dev,const char * name,int unit)1452 device_add_child(device_t dev, const char *name, int unit)
1453 {
1454 	return (device_add_child_ordered(dev, 0, name, unit));
1455 }
1456 
1457 /**
1458  * @brief Create a new device
1459  *
1460  * This creates a new device and adds it as a child of an existing
1461  * parent device. The new device will be added after the last existing
1462  * child with the same order.
1463  *
1464  * @param dev		the device which will be the parent of the
1465  *			new child device
1466  * @param order		a value which is used to partially sort the
1467  *			children of @p dev - devices created using
1468  *			lower values of @p order appear first in @p
1469  *			dev's list of children
1470  * @param name		devclass name for new device or @c NULL if not
1471  *			specified
1472  * @param unit		unit number for new device or @c DEVICE_UNIT_ANY if not
1473  *			specified
1474  *
1475  * @returns		the new device
1476  */
1477 device_t
device_add_child_ordered(device_t dev,u_int order,const char * name,int unit)1478 device_add_child_ordered(device_t dev, u_int order, const char *name, int unit)
1479 {
1480 	device_t child;
1481 	device_t place;
1482 
1483 	PDEBUG(("%s at %s with order %u as unit %d",
1484 	    name, DEVICENAME(dev), order, unit));
1485 	KASSERT(name != NULL || unit == DEVICE_UNIT_ANY,
1486 	    ("child device with wildcard name and specific unit number"));
1487 
1488 	child = make_device(dev, name, unit);
1489 	if (child == NULL)
1490 		return (child);
1491 	child->order = order;
1492 
1493 	TAILQ_FOREACH(place, &dev->children, link) {
1494 		if (place->order > order)
1495 			break;
1496 	}
1497 
1498 	if (place) {
1499 		/*
1500 		 * The device 'place' is the first device whose order is
1501 		 * greater than the new child.
1502 		 */
1503 		TAILQ_INSERT_BEFORE(place, child, link);
1504 	} else {
1505 		/*
1506 		 * The new child's order is greater or equal to the order of
1507 		 * any existing device. Add the child to the tail of the list.
1508 		 */
1509 		TAILQ_INSERT_TAIL(&dev->children, child, link);
1510 	}
1511 
1512 	bus_data_generation_update();
1513 	return (child);
1514 }
1515 
1516 /**
1517  * @brief Delete a device
1518  *
1519  * This function deletes a device along with all of its children. If
1520  * the device currently has a driver attached to it, the device is
1521  * detached first using device_detach().
1522  *
1523  * @param dev		the parent device
1524  * @param child		the device to delete
1525  *
1526  * @retval 0		success
1527  * @retval non-zero	a unit error code describing the error
1528  */
1529 int
device_delete_child(device_t dev,device_t child)1530 device_delete_child(device_t dev, device_t child)
1531 {
1532 	int error;
1533 	device_t grandchild;
1534 
1535 	PDEBUG(("%s from %s", DEVICENAME(child), DEVICENAME(dev)));
1536 
1537 	/*
1538 	 * Detach child.  Ideally this cleans up any grandchild
1539 	 * devices.
1540 	 */
1541 	if ((error = device_detach(child)) != 0)
1542 		return (error);
1543 
1544 	/* Delete any grandchildren left after detach. */
1545 	while ((grandchild = TAILQ_FIRST(&child->children)) != NULL) {
1546 		error = device_delete_child(child, grandchild);
1547 		if (error)
1548 			return (error);
1549 	}
1550 
1551 	device_destroy_props(dev);
1552 	if (child->devclass)
1553 		devclass_delete_device(child->devclass, child);
1554 	if (child->parent)
1555 		BUS_CHILD_DELETED(dev, child);
1556 	TAILQ_REMOVE(&dev->children, child, link);
1557 	TAILQ_REMOVE(&bus_data_devices, child, devlink);
1558 	kobj_delete((kobj_t) child, M_BUS);
1559 
1560 	bus_data_generation_update();
1561 	return (0);
1562 }
1563 
1564 /**
1565  * @brief Delete all children devices of the given device, if any.
1566  *
1567  * This function deletes all children devices of the given device, if
1568  * any, using the device_delete_child() function for each device it
1569  * finds. If a child device cannot be deleted, this function will
1570  * return an error code.
1571  *
1572  * @param dev		the parent device
1573  *
1574  * @retval 0		success
1575  * @retval non-zero	a device would not detach
1576  */
1577 int
device_delete_children(device_t dev)1578 device_delete_children(device_t dev)
1579 {
1580 	device_t child;
1581 	int error;
1582 
1583 	PDEBUG(("Deleting all children of %s", DEVICENAME(dev)));
1584 
1585 	error = 0;
1586 
1587 	while ((child = TAILQ_FIRST(&dev->children)) != NULL) {
1588 		error = device_delete_child(dev, child);
1589 		if (error) {
1590 			PDEBUG(("Failed deleting %s", DEVICENAME(child)));
1591 			break;
1592 		}
1593 	}
1594 	return (error);
1595 }
1596 
1597 /**
1598  * @brief Find a device given a unit number
1599  *
1600  * This is similar to devclass_get_devices() but only searches for
1601  * devices which have @p dev as a parent.
1602  *
1603  * @param dev		the parent device to search
1604  * @param unit		the unit number to search for.  If the unit is
1605  *			@c DEVICE_UNIT_ANY, return the first child of @p dev
1606  *			which has name @p classname (that is, the one with the
1607  *			lowest unit.)
1608  *
1609  * @returns		the device with the given unit number or @c
1610  *			NULL if there is no such device
1611  */
1612 device_t
device_find_child(device_t dev,const char * classname,int unit)1613 device_find_child(device_t dev, const char *classname, int unit)
1614 {
1615 	devclass_t dc;
1616 	device_t child;
1617 
1618 	dc = devclass_find(classname);
1619 	if (!dc)
1620 		return (NULL);
1621 
1622 	if (unit != DEVICE_UNIT_ANY) {
1623 		child = devclass_get_device(dc, unit);
1624 		if (child && child->parent == dev)
1625 			return (child);
1626 	} else {
1627 		for (unit = 0; unit < devclass_get_maxunit(dc); unit++) {
1628 			child = devclass_get_device(dc, unit);
1629 			if (child && child->parent == dev)
1630 				return (child);
1631 		}
1632 	}
1633 	return (NULL);
1634 }
1635 
1636 /**
1637  * @internal
1638  */
1639 static driverlink_t
first_matching_driver(devclass_t dc,device_t dev)1640 first_matching_driver(devclass_t dc, device_t dev)
1641 {
1642 	if (dev->devclass)
1643 		return (devclass_find_driver_internal(dc, dev->devclass->name));
1644 	return (TAILQ_FIRST(&dc->drivers));
1645 }
1646 
1647 /**
1648  * @internal
1649  */
1650 static driverlink_t
next_matching_driver(devclass_t dc,device_t dev,driverlink_t last)1651 next_matching_driver(devclass_t dc, device_t dev, driverlink_t last)
1652 {
1653 	if (dev->devclass) {
1654 		driverlink_t dl;
1655 		for (dl = TAILQ_NEXT(last, link); dl; dl = TAILQ_NEXT(dl, link))
1656 			if (!strcmp(dev->devclass->name, dl->driver->name))
1657 				return (dl);
1658 		return (NULL);
1659 	}
1660 	return (TAILQ_NEXT(last, link));
1661 }
1662 
1663 /**
1664  * @internal
1665  */
1666 int
device_probe_child(device_t dev,device_t child)1667 device_probe_child(device_t dev, device_t child)
1668 {
1669 	devclass_t dc;
1670 	driverlink_t best = NULL;
1671 	driverlink_t dl;
1672 	int result, pri = 0;
1673 	/* We should preserve the devclass (or lack of) set by the bus. */
1674 	int hasclass = (child->devclass != NULL);
1675 
1676 	bus_topo_assert();
1677 
1678 	dc = dev->devclass;
1679 	if (!dc)
1680 		panic("device_probe_child: parent device has no devclass");
1681 
1682 	/*
1683 	 * If the state is already probed, then return.
1684 	 */
1685 	if (child->state == DS_ALIVE)
1686 		return (0);
1687 
1688 	for (; dc; dc = dc->parent) {
1689 		for (dl = first_matching_driver(dc, child);
1690 		     dl;
1691 		     dl = next_matching_driver(dc, child, dl)) {
1692 			/* If this driver's pass is too high, then ignore it. */
1693 			if (dl->pass > bus_current_pass)
1694 				continue;
1695 
1696 			PDEBUG(("Trying %s", DRIVERNAME(dl->driver)));
1697 			result = device_set_driver(child, dl->driver);
1698 			if (result == ENOMEM)
1699 				return (result);
1700 			else if (result != 0)
1701 				continue;
1702 			if (!hasclass) {
1703 				if (device_set_devclass(child,
1704 				    dl->driver->name) != 0) {
1705 					char const * devname =
1706 					    device_get_name(child);
1707 					if (devname == NULL)
1708 						devname = "(unknown)";
1709 					printf("driver bug: Unable to set "
1710 					    "devclass (class: %s "
1711 					    "devname: %s)\n",
1712 					    dl->driver->name,
1713 					    devname);
1714 					(void)device_set_driver(child, NULL);
1715 					continue;
1716 				}
1717 			}
1718 
1719 			/* Fetch any flags for the device before probing. */
1720 			resource_int_value(dl->driver->name, child->unit,
1721 			    "flags", &child->devflags);
1722 
1723 			result = DEVICE_PROBE(child);
1724 
1725 			/*
1726 			 * If probe returns 0, this is the driver that wins this
1727 			 * device.
1728 			 */
1729 			if (result == 0) {
1730 				best = dl;
1731 				pri = 0;
1732 				goto exact_match;	/* C doesn't have break 2 */
1733 			}
1734 
1735 			/* Reset flags and devclass before the next probe. */
1736 			child->devflags = 0;
1737 			if (!hasclass)
1738 				(void)device_set_devclass(child, NULL);
1739 
1740 			/*
1741 			 * Reset DF_QUIET in case this driver doesn't
1742 			 * end up as the best driver.
1743 			 */
1744 			device_verbose(child);
1745 
1746 			/*
1747 			 * Probes that return BUS_PROBE_NOWILDCARD or lower
1748 			 * only match on devices whose driver was explicitly
1749 			 * specified.
1750 			 */
1751 			if (result <= BUS_PROBE_NOWILDCARD &&
1752 			    !(child->flags & DF_FIXEDCLASS)) {
1753 				result = ENXIO;
1754 			}
1755 
1756 			/*
1757 			 * The driver returned an error so it
1758 			 * certainly doesn't match.
1759 			 */
1760 			if (result > 0) {
1761 				(void)device_set_driver(child, NULL);
1762 				continue;
1763 			}
1764 
1765 			/*
1766 			 * A priority lower than SUCCESS, remember the
1767 			 * best matching driver. Initialise the value
1768 			 * of pri for the first match.
1769 			 */
1770 			if (best == NULL || result > pri) {
1771 				best = dl;
1772 				pri = result;
1773 				continue;
1774 			}
1775 		}
1776 	}
1777 
1778 	if (best == NULL)
1779 		return (ENXIO);
1780 
1781 	/*
1782 	 * If we found a driver, change state and initialise the devclass.
1783 	 * Set the winning driver, devclass, and flags.
1784 	 */
1785 	result = device_set_driver(child, best->driver);
1786 	if (result != 0)
1787 		return (result);
1788 	if (!child->devclass) {
1789 		result = device_set_devclass(child, best->driver->name);
1790 		if (result != 0) {
1791 			(void)device_set_driver(child, NULL);
1792 			return (result);
1793 		}
1794 	}
1795 	resource_int_value(best->driver->name, child->unit,
1796 	    "flags", &child->devflags);
1797 
1798 	/*
1799 	 * A bit bogus. Call the probe method again to make sure that we have
1800 	 * the right description for the device.
1801 	 */
1802 	result = DEVICE_PROBE(child);
1803 	if (result > 0) {
1804 		if (!hasclass)
1805 			(void)device_set_devclass(child, NULL);
1806 		(void)device_set_driver(child, NULL);
1807 		return (result);
1808 	}
1809 
1810 exact_match:
1811 	child->state = DS_ALIVE;
1812 	bus_data_generation_update();
1813 	return (0);
1814 }
1815 
1816 /**
1817  * @brief Return the parent of a device
1818  */
1819 device_t
device_get_parent(device_t dev)1820 device_get_parent(device_t dev)
1821 {
1822 	return (dev->parent);
1823 }
1824 
1825 /**
1826  * @brief Get a list of children of a device
1827  *
1828  * An array containing a list of all the children of the given device
1829  * is allocated and returned in @p *devlistp. The number of devices
1830  * in the array is returned in @p *devcountp. The caller should free
1831  * the array using @c free(p, M_TEMP).
1832  *
1833  * @param dev		the device to examine
1834  * @param devlistp	points at location for array pointer return
1835  *			value
1836  * @param devcountp	points at location for array size return value
1837  *
1838  * @retval 0		success
1839  * @retval ENOMEM	the array allocation failed
1840  */
1841 int
device_get_children(device_t dev,device_t ** devlistp,int * devcountp)1842 device_get_children(device_t dev, device_t **devlistp, int *devcountp)
1843 {
1844 	int count;
1845 	device_t child;
1846 	device_t *list;
1847 
1848 	count = 0;
1849 	TAILQ_FOREACH(child, &dev->children, link) {
1850 		count++;
1851 	}
1852 	if (count == 0) {
1853 		*devlistp = NULL;
1854 		*devcountp = 0;
1855 		return (0);
1856 	}
1857 
1858 	list = malloc(count * sizeof(device_t), M_TEMP, M_NOWAIT|M_ZERO);
1859 	if (!list)
1860 		return (ENOMEM);
1861 
1862 	count = 0;
1863 	TAILQ_FOREACH(child, &dev->children, link) {
1864 		list[count] = child;
1865 		count++;
1866 	}
1867 
1868 	*devlistp = list;
1869 	*devcountp = count;
1870 
1871 	return (0);
1872 }
1873 
1874 /**
1875  * @brief Return the current driver for the device or @c NULL if there
1876  * is no driver currently attached
1877  */
1878 driver_t *
device_get_driver(device_t dev)1879 device_get_driver(device_t dev)
1880 {
1881 	return (dev->driver);
1882 }
1883 
1884 /**
1885  * @brief Return the current devclass for the device or @c NULL if
1886  * there is none.
1887  */
1888 devclass_t
device_get_devclass(device_t dev)1889 device_get_devclass(device_t dev)
1890 {
1891 	return (dev->devclass);
1892 }
1893 
1894 /**
1895  * @brief Return the name of the device's devclass or @c NULL if there
1896  * is none.
1897  */
1898 const char *
device_get_name(device_t dev)1899 device_get_name(device_t dev)
1900 {
1901 	if (dev != NULL && dev->devclass)
1902 		return (devclass_get_name(dev->devclass));
1903 	return (NULL);
1904 }
1905 
1906 /**
1907  * @brief Return a string containing the device's devclass name
1908  * followed by an ascii representation of the device's unit number
1909  * (e.g. @c "foo2").
1910  */
1911 const char *
device_get_nameunit(device_t dev)1912 device_get_nameunit(device_t dev)
1913 {
1914 	return (dev->nameunit);
1915 }
1916 
1917 /**
1918  * @brief Return the device's unit number.
1919  */
1920 int
device_get_unit(device_t dev)1921 device_get_unit(device_t dev)
1922 {
1923 	return (dev->unit);
1924 }
1925 
1926 /**
1927  * @brief Return the device's description string
1928  */
1929 const char *
device_get_desc(device_t dev)1930 device_get_desc(device_t dev)
1931 {
1932 	return (dev->desc);
1933 }
1934 
1935 /**
1936  * @brief Return the device's flags
1937  */
1938 uint32_t
device_get_flags(device_t dev)1939 device_get_flags(device_t dev)
1940 {
1941 	return (dev->devflags);
1942 }
1943 
1944 struct sysctl_ctx_list *
device_get_sysctl_ctx(device_t dev)1945 device_get_sysctl_ctx(device_t dev)
1946 {
1947 	return (&dev->sysctl_ctx);
1948 }
1949 
1950 struct sysctl_oid *
device_get_sysctl_tree(device_t dev)1951 device_get_sysctl_tree(device_t dev)
1952 {
1953 	return (dev->sysctl_tree);
1954 }
1955 
1956 /**
1957  * @brief Print the name of the device followed by a colon and a space
1958  *
1959  * @returns the number of characters printed
1960  */
1961 int
device_print_prettyname(device_t dev)1962 device_print_prettyname(device_t dev)
1963 {
1964 	const char *name = device_get_name(dev);
1965 
1966 	if (name == NULL)
1967 		return (printf("unknown: "));
1968 	return (printf("%s%d: ", name, device_get_unit(dev)));
1969 }
1970 
1971 /**
1972  * @brief Print the name of the device followed by a colon, a space
1973  * and the result of calling vprintf() with the value of @p fmt and
1974  * the following arguments.
1975  *
1976  * @returns the number of characters printed
1977  */
1978 int
device_printf(device_t dev,const char * fmt,...)1979 device_printf(device_t dev, const char * fmt, ...)
1980 {
1981 	char buf[128];
1982 	struct sbuf sb;
1983 	const char *name;
1984 	va_list ap;
1985 	size_t retval;
1986 
1987 	retval = 0;
1988 
1989 	sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
1990 	sbuf_set_drain(&sb, sbuf_printf_drain, &retval);
1991 
1992 	name = device_get_name(dev);
1993 
1994 	if (name == NULL)
1995 		sbuf_cat(&sb, "unknown: ");
1996 	else
1997 		sbuf_printf(&sb, "%s%d: ", name, device_get_unit(dev));
1998 
1999 	va_start(ap, fmt);
2000 	sbuf_vprintf(&sb, fmt, ap);
2001 	va_end(ap);
2002 
2003 	sbuf_finish(&sb);
2004 	sbuf_delete(&sb);
2005 
2006 	return (retval);
2007 }
2008 
2009 /**
2010  * @brief Print the name of the device followed by a colon, a space
2011  * and the result of calling log() with the value of @p fmt and
2012  * the following arguments.
2013  *
2014  * @returns the number of characters printed
2015  */
2016 int
device_log(device_t dev,int pri,const char * fmt,...)2017 device_log(device_t dev, int pri, const char * fmt, ...)
2018 {
2019 	char buf[128];
2020 	struct sbuf sb;
2021 	const char *name;
2022 	va_list ap;
2023 	size_t retval;
2024 
2025 	retval = 0;
2026 
2027 	sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN);
2028 
2029 	name = device_get_name(dev);
2030 
2031 	if (name == NULL)
2032 		sbuf_cat(&sb, "unknown: ");
2033 	else
2034 		sbuf_printf(&sb, "%s%d: ", name, device_get_unit(dev));
2035 
2036 	va_start(ap, fmt);
2037 	sbuf_vprintf(&sb, fmt, ap);
2038 	va_end(ap);
2039 
2040 	sbuf_finish(&sb);
2041 
2042 	log(pri, "%.*s", (int) sbuf_len(&sb), sbuf_data(&sb));
2043 	retval = sbuf_len(&sb);
2044 
2045 	sbuf_delete(&sb);
2046 
2047 	return (retval);
2048 }
2049 
2050 /**
2051  * @internal
2052  */
2053 static void
device_set_desc_internal(device_t dev,const char * desc,bool allocated)2054 device_set_desc_internal(device_t dev, const char *desc, bool allocated)
2055 {
2056 	if (dev->desc && (dev->flags & DF_DESCMALLOCED)) {
2057 		free(dev->desc, M_BUS);
2058 		dev->flags &= ~DF_DESCMALLOCED;
2059 		dev->desc = NULL;
2060 	}
2061 
2062 	if (allocated && desc)
2063 		dev->flags |= DF_DESCMALLOCED;
2064 	dev->desc = __DECONST(char *, desc);
2065 
2066 	bus_data_generation_update();
2067 }
2068 
2069 /**
2070  * @brief Set the device's description
2071  *
2072  * The value of @c desc should be a string constant that will not
2073  * change (at least until the description is changed in a subsequent
2074  * call to device_set_desc() or device_set_desc_copy()).
2075  */
2076 void
device_set_desc(device_t dev,const char * desc)2077 device_set_desc(device_t dev, const char *desc)
2078 {
2079 	device_set_desc_internal(dev, desc, false);
2080 }
2081 
2082 /**
2083  * @brief Set the device's description
2084  *
2085  * A printf-like version of device_set_desc().
2086  */
2087 void
device_set_descf(device_t dev,const char * fmt,...)2088 device_set_descf(device_t dev, const char *fmt, ...)
2089 {
2090 	va_list ap;
2091 	char *buf = NULL;
2092 
2093 	va_start(ap, fmt);
2094 	vasprintf(&buf, M_BUS, fmt, ap);
2095 	va_end(ap);
2096 	device_set_desc_internal(dev, buf, true);
2097 }
2098 
2099 /**
2100  * @brief Set the device's description
2101  *
2102  * The string pointed to by @c desc is copied. Use this function if
2103  * the device description is generated, (e.g. with sprintf()).
2104  */
2105 void
device_set_desc_copy(device_t dev,const char * desc)2106 device_set_desc_copy(device_t dev, const char *desc)
2107 {
2108 	char *buf;
2109 
2110 	buf = strdup_flags(desc, M_BUS, M_WAITOK);
2111 	device_set_desc_internal(dev, buf, true);
2112 }
2113 
2114 /**
2115  * @brief Set the device's flags
2116  */
2117 void
device_set_flags(device_t dev,uint32_t flags)2118 device_set_flags(device_t dev, uint32_t flags)
2119 {
2120 	dev->devflags = flags;
2121 }
2122 
2123 /**
2124  * @brief Return the device's softc field
2125  *
2126  * The softc is allocated and zeroed when a driver is attached, based
2127  * on the size field of the driver.
2128  */
2129 void *
device_get_softc(device_t dev)2130 device_get_softc(device_t dev)
2131 {
2132 	return (dev->softc);
2133 }
2134 
2135 /**
2136  * @brief Set the device's softc field
2137  *
2138  * Most drivers do not need to use this since the softc is allocated
2139  * automatically when the driver is attached.
2140  */
2141 void
device_set_softc(device_t dev,void * softc)2142 device_set_softc(device_t dev, void *softc)
2143 {
2144 	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC))
2145 		free(dev->softc, M_BUS_SC);
2146 	dev->softc = softc;
2147 	if (dev->softc)
2148 		dev->flags |= DF_EXTERNALSOFTC;
2149 	else
2150 		dev->flags &= ~DF_EXTERNALSOFTC;
2151 }
2152 
2153 /**
2154  * @brief Free claimed softc
2155  *
2156  * Most drivers do not need to use this since the softc is freed
2157  * automatically when the driver is detached.
2158  */
2159 void
device_free_softc(void * softc)2160 device_free_softc(void *softc)
2161 {
2162 	free(softc, M_BUS_SC);
2163 }
2164 
2165 /**
2166  * @brief Claim softc
2167  *
2168  * This function can be used to let the driver free the automatically
2169  * allocated softc using "device_free_softc()". This function is
2170  * useful when the driver is refcounting the softc and the softc
2171  * cannot be freed when the "device_detach" method is called.
2172  */
2173 void
device_claim_softc(device_t dev)2174 device_claim_softc(device_t dev)
2175 {
2176 	if (dev->softc)
2177 		dev->flags |= DF_EXTERNALSOFTC;
2178 	else
2179 		dev->flags &= ~DF_EXTERNALSOFTC;
2180 }
2181 
2182 /**
2183  * @brief Get the device's ivars field
2184  *
2185  * The ivars field is used by the parent device to store per-device
2186  * state (e.g. the physical location of the device or a list of
2187  * resources).
2188  */
2189 void *
device_get_ivars(device_t dev)2190 device_get_ivars(device_t dev)
2191 {
2192 	KASSERT(dev != NULL, ("device_get_ivars(NULL, ...)"));
2193 	return (dev->ivars);
2194 }
2195 
2196 /**
2197  * @brief Set the device's ivars field
2198  */
2199 void
device_set_ivars(device_t dev,void * ivars)2200 device_set_ivars(device_t dev, void * ivars)
2201 {
2202 	KASSERT(dev != NULL, ("device_set_ivars(NULL, ...)"));
2203 	dev->ivars = ivars;
2204 }
2205 
2206 /**
2207  * @brief Return the device's state
2208  */
2209 device_state_t
device_get_state(device_t dev)2210 device_get_state(device_t dev)
2211 {
2212 	return (dev->state);
2213 }
2214 
2215 /**
2216  * @brief Set the DF_ENABLED flag for the device
2217  */
2218 void
device_enable(device_t dev)2219 device_enable(device_t dev)
2220 {
2221 	dev->flags |= DF_ENABLED;
2222 }
2223 
2224 /**
2225  * @brief Clear the DF_ENABLED flag for the device
2226  */
2227 void
device_disable(device_t dev)2228 device_disable(device_t dev)
2229 {
2230 	dev->flags &= ~DF_ENABLED;
2231 }
2232 
2233 /**
2234  * @brief Increment the busy counter for the device
2235  */
2236 void
device_busy(device_t dev)2237 device_busy(device_t dev)
2238 {
2239 
2240 	/*
2241 	 * Mark the device as busy, recursively up the tree if this busy count
2242 	 * goes 0->1.
2243 	 */
2244 	if (refcount_acquire(&dev->busy) == 0 && dev->parent != NULL)
2245 		device_busy(dev->parent);
2246 }
2247 
2248 /**
2249  * @brief Decrement the busy counter for the device
2250  */
2251 void
device_unbusy(device_t dev)2252 device_unbusy(device_t dev)
2253 {
2254 
2255 	/*
2256 	 * Mark the device as unbsy, recursively if this is the last busy count.
2257 	 */
2258 	if (refcount_release(&dev->busy) && dev->parent != NULL)
2259 		device_unbusy(dev->parent);
2260 }
2261 
2262 /**
2263  * @brief Set the DF_QUIET flag for the device
2264  */
2265 void
device_quiet(device_t dev)2266 device_quiet(device_t dev)
2267 {
2268 	dev->flags |= DF_QUIET;
2269 }
2270 
2271 /**
2272  * @brief Set the DF_QUIET_CHILDREN flag for the device
2273  */
2274 void
device_quiet_children(device_t dev)2275 device_quiet_children(device_t dev)
2276 {
2277 	dev->flags |= DF_QUIET_CHILDREN;
2278 }
2279 
2280 /**
2281  * @brief Clear the DF_QUIET flag for the device
2282  */
2283 void
device_verbose(device_t dev)2284 device_verbose(device_t dev)
2285 {
2286 	dev->flags &= ~DF_QUIET;
2287 }
2288 
2289 ssize_t
device_get_property(device_t dev,const char * prop,void * val,size_t sz,device_property_type_t type)2290 device_get_property(device_t dev, const char *prop, void *val, size_t sz,
2291     device_property_type_t type)
2292 {
2293 	device_t bus = device_get_parent(dev);
2294 
2295 	switch (type) {
2296 	case DEVICE_PROP_ANY:
2297 	case DEVICE_PROP_BUFFER:
2298 	case DEVICE_PROP_HANDLE:	/* Size checks done in implementation. */
2299 		break;
2300 	case DEVICE_PROP_UINT32:
2301 		if (sz % 4 != 0)
2302 			return (-1);
2303 		break;
2304 	case DEVICE_PROP_UINT64:
2305 		if (sz % 8 != 0)
2306 			return (-1);
2307 		break;
2308 	default:
2309 		return (-1);
2310 	}
2311 
2312 	return (BUS_GET_PROPERTY(bus, dev, prop, val, sz, type));
2313 }
2314 
2315 bool
device_has_property(device_t dev,const char * prop)2316 device_has_property(device_t dev, const char *prop)
2317 {
2318 	return (device_get_property(dev, prop, NULL, 0, DEVICE_PROP_ANY) >= 0);
2319 }
2320 
2321 /**
2322  * @brief Return non-zero if the DF_QUIET_CHIDLREN flag is set on the device
2323  */
2324 int
device_has_quiet_children(device_t dev)2325 device_has_quiet_children(device_t dev)
2326 {
2327 	return ((dev->flags & DF_QUIET_CHILDREN) != 0);
2328 }
2329 
2330 /**
2331  * @brief Return non-zero if the DF_QUIET flag is set on the device
2332  */
2333 int
device_is_quiet(device_t dev)2334 device_is_quiet(device_t dev)
2335 {
2336 	return ((dev->flags & DF_QUIET) != 0);
2337 }
2338 
2339 /**
2340  * @brief Return non-zero if the DF_ENABLED flag is set on the device
2341  */
2342 int
device_is_enabled(device_t dev)2343 device_is_enabled(device_t dev)
2344 {
2345 	return ((dev->flags & DF_ENABLED) != 0);
2346 }
2347 
2348 /**
2349  * @brief Return non-zero if the device was successfully probed
2350  */
2351 int
device_is_alive(device_t dev)2352 device_is_alive(device_t dev)
2353 {
2354 	return (dev->state >= DS_ALIVE);
2355 }
2356 
2357 /**
2358  * @brief Return non-zero if the device currently has a driver
2359  * attached to it
2360  */
2361 int
device_is_attached(device_t dev)2362 device_is_attached(device_t dev)
2363 {
2364 	return (dev->state >= DS_ATTACHED);
2365 }
2366 
2367 /**
2368  * @brief Return non-zero if the device is currently suspended.
2369  */
2370 int
device_is_suspended(device_t dev)2371 device_is_suspended(device_t dev)
2372 {
2373 	return ((dev->flags & DF_SUSPENDED) != 0);
2374 }
2375 
2376 /**
2377  * @brief Set the devclass of a device
2378  * @see devclass_add_device().
2379  */
2380 int
device_set_devclass(device_t dev,const char * classname)2381 device_set_devclass(device_t dev, const char *classname)
2382 {
2383 	devclass_t dc;
2384 	int error;
2385 
2386 	if (!classname) {
2387 		if (dev->devclass)
2388 			devclass_delete_device(dev->devclass, dev);
2389 		return (0);
2390 	}
2391 
2392 	if (dev->devclass) {
2393 		printf("device_set_devclass: device class already set\n");
2394 		return (EINVAL);
2395 	}
2396 
2397 	dc = devclass_find_internal(classname, NULL, TRUE);
2398 	if (!dc)
2399 		return (ENOMEM);
2400 
2401 	error = devclass_add_device(dc, dev);
2402 
2403 	bus_data_generation_update();
2404 	return (error);
2405 }
2406 
2407 /**
2408  * @brief Set the devclass of a device and mark the devclass fixed.
2409  * @see device_set_devclass()
2410  */
2411 int
device_set_devclass_fixed(device_t dev,const char * classname)2412 device_set_devclass_fixed(device_t dev, const char *classname)
2413 {
2414 	int error;
2415 
2416 	if (classname == NULL)
2417 		return (EINVAL);
2418 
2419 	error = device_set_devclass(dev, classname);
2420 	if (error)
2421 		return (error);
2422 	dev->flags |= DF_FIXEDCLASS;
2423 	return (0);
2424 }
2425 
2426 /**
2427  * @brief Query the device to determine if it's of a fixed devclass
2428  * @see device_set_devclass_fixed()
2429  */
2430 bool
device_is_devclass_fixed(device_t dev)2431 device_is_devclass_fixed(device_t dev)
2432 {
2433 	return ((dev->flags & DF_FIXEDCLASS) != 0);
2434 }
2435 
2436 /**
2437  * @brief Set the driver of a device
2438  *
2439  * @retval 0		success
2440  * @retval EBUSY	the device already has a driver attached
2441  * @retval ENOMEM	a memory allocation failure occurred
2442  */
2443 int
device_set_driver(device_t dev,driver_t * driver)2444 device_set_driver(device_t dev, driver_t *driver)
2445 {
2446 	int domain;
2447 	struct domainset *policy;
2448 
2449 	if (dev->state >= DS_ATTACHED)
2450 		return (EBUSY);
2451 
2452 	if (dev->driver == driver)
2453 		return (0);
2454 
2455 	if (dev->softc && !(dev->flags & DF_EXTERNALSOFTC)) {
2456 		free(dev->softc, M_BUS_SC);
2457 		dev->softc = NULL;
2458 	}
2459 	device_set_desc(dev, NULL);
2460 	kobj_delete((kobj_t) dev, NULL);
2461 	dev->driver = driver;
2462 	if (driver) {
2463 		kobj_init((kobj_t) dev, (kobj_class_t) driver);
2464 		if (!(dev->flags & DF_EXTERNALSOFTC) && driver->size > 0) {
2465 			if (bus_get_domain(dev, &domain) == 0)
2466 				policy = DOMAINSET_PREF(domain);
2467 			else
2468 				policy = DOMAINSET_RR();
2469 			dev->softc = malloc_domainset(driver->size, M_BUS_SC,
2470 			    policy, M_WAITOK | M_ZERO);
2471 		}
2472 	} else {
2473 		kobj_init((kobj_t) dev, &null_class);
2474 	}
2475 
2476 	bus_data_generation_update();
2477 	return (0);
2478 }
2479 
2480 /**
2481  * @brief Probe a device, and return this status.
2482  *
2483  * This function is the core of the device autoconfiguration
2484  * system. Its purpose is to select a suitable driver for a device and
2485  * then call that driver to initialise the hardware appropriately. The
2486  * driver is selected by calling the DEVICE_PROBE() method of a set of
2487  * candidate drivers and then choosing the driver which returned the
2488  * best value. This driver is then attached to the device using
2489  * device_attach().
2490  *
2491  * The set of suitable drivers is taken from the list of drivers in
2492  * the parent device's devclass. If the device was originally created
2493  * with a specific class name (see device_add_child()), only drivers
2494  * with that name are probed, otherwise all drivers in the devclass
2495  * are probed. If no drivers return successful probe values in the
2496  * parent devclass, the search continues in the parent of that
2497  * devclass (see devclass_get_parent()) if any.
2498  *
2499  * @param dev		the device to initialise
2500  *
2501  * @retval 0		success
2502  * @retval ENXIO	no driver was found
2503  * @retval ENOMEM	memory allocation failure
2504  * @retval non-zero	some other unix error code
2505  * @retval -1		Device already attached
2506  */
2507 int
device_probe(device_t dev)2508 device_probe(device_t dev)
2509 {
2510 	int error;
2511 
2512 	bus_topo_assert();
2513 
2514 	if (dev->state >= DS_ALIVE)
2515 		return (-1);
2516 
2517 	if (!(dev->flags & DF_ENABLED)) {
2518 		if (bootverbose && device_get_name(dev) != NULL) {
2519 			device_print_prettyname(dev);
2520 			printf("not probed (disabled)\n");
2521 		}
2522 		return (-1);
2523 	}
2524 	if ((error = device_probe_child(dev->parent, dev)) != 0) {
2525 		if (bus_current_pass == BUS_PASS_DEFAULT &&
2526 		    !(dev->flags & DF_DONENOMATCH)) {
2527 			device_handle_nomatch(dev);
2528 		}
2529 		return (error);
2530 	}
2531 	return (0);
2532 }
2533 
2534 /**
2535  * @brief Probe a device and attach a driver if possible
2536  *
2537  * calls device_probe() and attaches if that was successful.
2538  */
2539 int
device_probe_and_attach(device_t dev)2540 device_probe_and_attach(device_t dev)
2541 {
2542 	int error;
2543 
2544 	bus_topo_assert();
2545 
2546 	error = device_probe(dev);
2547 	if (error == -1)
2548 		return (0);
2549 	else if (error != 0)
2550 		return (error);
2551 
2552 	return (device_attach(dev));
2553 }
2554 
2555 /**
2556  * @brief Attach a device driver to a device
2557  *
2558  * This function is a wrapper around the DEVICE_ATTACH() driver
2559  * method. In addition to calling DEVICE_ATTACH(), it initialises the
2560  * device's sysctl tree, optionally prints a description of the device
2561  * and queues a notification event for user-based device management
2562  * services.
2563  *
2564  * Normally this function is only called internally from
2565  * device_probe_and_attach().
2566  *
2567  * @param dev		the device to initialise
2568  *
2569  * @retval 0		success
2570  * @retval ENXIO	no driver was found
2571  * @retval ENOMEM	memory allocation failure
2572  * @retval non-zero	some other unix error code
2573  */
2574 int
device_attach(device_t dev)2575 device_attach(device_t dev)
2576 {
2577 	uint64_t attachtime;
2578 	uint16_t attachentropy;
2579 	int error;
2580 
2581 	if (resource_disabled(dev->driver->name, dev->unit)) {
2582 		/*
2583 		 * Mostly detach the device, but leave it attached to
2584 		 * the devclass to reserve the name and unit.
2585 		 */
2586 		device_disable(dev);
2587 		(void)device_set_driver(dev, NULL);
2588 		dev->state = DS_NOTPRESENT;
2589 		if (bootverbose)
2590 			 device_printf(dev, "disabled via hints entry\n");
2591 		return (ENXIO);
2592 	}
2593 
2594 	KASSERT(IS_DEFAULT_VNET(TD_TO_VNET(curthread)),
2595 	    ("device_attach: curthread is not in default vnet"));
2596 	CURVNET_SET_QUIET(TD_TO_VNET(curthread));
2597 
2598 	device_sysctl_init(dev);
2599 	if (!device_is_quiet(dev))
2600 		device_print_child(dev->parent, dev);
2601 	attachtime = get_cyclecount();
2602 	dev->state = DS_ATTACHING;
2603 	if ((error = DEVICE_ATTACH(dev)) != 0) {
2604 		printf("device_attach: %s%d attach returned %d\n",
2605 		    dev->driver->name, dev->unit, error);
2606 		BUS_CHILD_DETACHED(dev->parent, dev);
2607 		if (disable_failed_devs) {
2608 			/*
2609 			 * When the user has asked to disable failed devices, we
2610 			 * directly disable the device, but leave it in the
2611 			 * attaching state. It will not try to probe/attach the
2612 			 * device further. This leaves the device numbering
2613 			 * intact for other similar devices in the system. It
2614 			 * can be removed from this state with devctl.
2615 			 */
2616 			device_disable(dev);
2617 		} else {
2618 			/*
2619 			 * Otherwise, when attach fails, tear down the state
2620 			 * around that so we can retry when, for example, new
2621 			 * drivers are loaded.
2622 			 */
2623 			if (!(dev->flags & DF_FIXEDCLASS))
2624 				devclass_delete_device(dev->devclass, dev);
2625 			(void)device_set_driver(dev, NULL);
2626 			device_sysctl_fini(dev);
2627 			KASSERT(dev->busy == 0, ("attach failed but busy"));
2628 			dev->state = DS_NOTPRESENT;
2629 		}
2630 		CURVNET_RESTORE();
2631 		return (error);
2632 	}
2633 	CURVNET_RESTORE();
2634 	dev->flags |= DF_ATTACHED_ONCE;
2635 	/*
2636 	 * We only need the low bits of this time, but ranges from tens to thousands
2637 	 * have been seen, so keep 2 bytes' worth.
2638 	 */
2639 	attachentropy = (uint16_t)(get_cyclecount() - attachtime);
2640 	random_harvest_direct(&attachentropy, sizeof(attachentropy), RANDOM_ATTACH);
2641 	device_sysctl_update(dev);
2642 	dev->state = DS_ATTACHED;
2643 	dev->flags &= ~DF_DONENOMATCH;
2644 	EVENTHANDLER_DIRECT_INVOKE(device_attach, dev);
2645 	return (0);
2646 }
2647 
2648 /**
2649  * @brief Detach a driver from a device
2650  *
2651  * This function is a wrapper around the DEVICE_DETACH() driver
2652  * method. If the call to DEVICE_DETACH() succeeds, it calls
2653  * BUS_CHILD_DETACHED() for the parent of @p dev, queues a
2654  * notification event for user-based device management services and
2655  * cleans up the device's sysctl tree.
2656  *
2657  * @param dev		the device to un-initialise
2658  *
2659  * @retval 0		success
2660  * @retval ENXIO	no driver was found
2661  * @retval ENOMEM	memory allocation failure
2662  * @retval non-zero	some other unix error code
2663  */
2664 int
device_detach(device_t dev)2665 device_detach(device_t dev)
2666 {
2667 	int error;
2668 
2669 	bus_topo_assert();
2670 
2671 	PDEBUG(("%s", DEVICENAME(dev)));
2672 	if (dev->busy > 0)
2673 		return (EBUSY);
2674 	if (dev->state == DS_ATTACHING) {
2675 		device_printf(dev, "device in attaching state! Deferring detach.\n");
2676 		return (EBUSY);
2677 	}
2678 	if (dev->state != DS_ATTACHED)
2679 		return (0);
2680 
2681 	EVENTHANDLER_DIRECT_INVOKE(device_detach, dev, EVHDEV_DETACH_BEGIN);
2682 	if ((error = DEVICE_DETACH(dev)) != 0) {
2683 		EVENTHANDLER_DIRECT_INVOKE(device_detach, dev,
2684 		    EVHDEV_DETACH_FAILED);
2685 		return (error);
2686 	} else {
2687 		EVENTHANDLER_DIRECT_INVOKE(device_detach, dev,
2688 		    EVHDEV_DETACH_COMPLETE);
2689 	}
2690 	if (!device_is_quiet(dev))
2691 		device_printf(dev, "detached\n");
2692 	if (dev->parent)
2693 		BUS_CHILD_DETACHED(dev->parent, dev);
2694 
2695 	if (!(dev->flags & DF_FIXEDCLASS))
2696 		devclass_delete_device(dev->devclass, dev);
2697 
2698 	device_verbose(dev);
2699 	dev->state = DS_NOTPRESENT;
2700 	(void)device_set_driver(dev, NULL);
2701 	device_sysctl_fini(dev);
2702 
2703 	return (0);
2704 }
2705 
2706 /**
2707  * @brief Tells a driver to quiesce itself.
2708  *
2709  * This function is a wrapper around the DEVICE_QUIESCE() driver
2710  * method. If the call to DEVICE_QUIESCE() succeeds.
2711  *
2712  * @param dev		the device to quiesce
2713  *
2714  * @retval 0		success
2715  * @retval ENXIO	no driver was found
2716  * @retval ENOMEM	memory allocation failure
2717  * @retval non-zero	some other unix error code
2718  */
2719 int
device_quiesce(device_t dev)2720 device_quiesce(device_t dev)
2721 {
2722 	PDEBUG(("%s", DEVICENAME(dev)));
2723 	if (dev->busy > 0)
2724 		return (EBUSY);
2725 	if (dev->state != DS_ATTACHED)
2726 		return (0);
2727 
2728 	return (DEVICE_QUIESCE(dev));
2729 }
2730 
2731 /**
2732  * @brief Notify a device of system shutdown
2733  *
2734  * This function calls the DEVICE_SHUTDOWN() driver method if the
2735  * device currently has an attached driver.
2736  *
2737  * @returns the value returned by DEVICE_SHUTDOWN()
2738  */
2739 int
device_shutdown(device_t dev)2740 device_shutdown(device_t dev)
2741 {
2742 	if (dev->state < DS_ATTACHED)
2743 		return (0);
2744 	return (DEVICE_SHUTDOWN(dev));
2745 }
2746 
2747 /**
2748  * @brief Set the unit number of a device
2749  *
2750  * This function can be used to override the unit number used for a
2751  * device (e.g. to wire a device to a pre-configured unit number).
2752  */
2753 int
device_set_unit(device_t dev,int unit)2754 device_set_unit(device_t dev, int unit)
2755 {
2756 	devclass_t dc;
2757 	int err;
2758 
2759 	if (unit == dev->unit)
2760 		return (0);
2761 	dc = device_get_devclass(dev);
2762 	if (unit < dc->maxunit && dc->devices[unit])
2763 		return (EBUSY);
2764 	err = devclass_delete_device(dc, dev);
2765 	if (err)
2766 		return (err);
2767 	dev->unit = unit;
2768 	err = devclass_add_device(dc, dev);
2769 	if (err)
2770 		return (err);
2771 
2772 	bus_data_generation_update();
2773 	return (0);
2774 }
2775 
2776 /*======================================*/
2777 /*
2778  * Some useful method implementations to make life easier for bus drivers.
2779  */
2780 
2781 /**
2782  * @brief Initialize a resource mapping request
2783  *
2784  * This is the internal implementation of the public API
2785  * resource_init_map_request.  Callers may be using a different layout
2786  * of struct resource_map_request than the kernel, so callers pass in
2787  * the size of the structure they are using to identify the structure
2788  * layout.
2789  */
2790 void
resource_init_map_request_impl(struct resource_map_request * args,size_t sz)2791 resource_init_map_request_impl(struct resource_map_request *args, size_t sz)
2792 {
2793 	bzero(args, sz);
2794 	args->size = sz;
2795 	args->memattr = VM_MEMATTR_DEVICE;
2796 }
2797 
2798 /**
2799  * @brief Validate a resource mapping request
2800  *
2801  * Translate a device driver's mapping request (@p in) to a struct
2802  * resource_map_request using the current structure layout (@p out).
2803  * In addition, validate the offset and length from the mapping
2804  * request against the bounds of the resource @p r.  If the offset or
2805  * length are invalid, fail with EINVAL.  If the offset and length are
2806  * valid, the absolute starting address of the requested mapping is
2807  * returned in @p startp and the length of the requested mapping is
2808  * returned in @p lengthp.
2809  */
2810 int
resource_validate_map_request(struct resource * r,struct resource_map_request * in,struct resource_map_request * out,rman_res_t * startp,rman_res_t * lengthp)2811 resource_validate_map_request(struct resource *r,
2812     struct resource_map_request *in, struct resource_map_request *out,
2813     rman_res_t *startp, rman_res_t *lengthp)
2814 {
2815 	rman_res_t end, length, start;
2816 
2817 	/*
2818 	 * This assumes that any callers of this function are compiled
2819 	 * into the kernel and use the same version of the structure
2820 	 * as this file.
2821 	 */
2822 	MPASS(out->size == sizeof(struct resource_map_request));
2823 
2824 	if (in != NULL)
2825 		bcopy(in, out, imin(in->size, out->size));
2826 	start = rman_get_start(r) + out->offset;
2827 	if (out->length == 0)
2828 		length = rman_get_size(r);
2829 	else
2830 		length = out->length;
2831 	end = start + length - 1;
2832 	if (start > rman_get_end(r) || start < rman_get_start(r))
2833 		return (EINVAL);
2834 	if (end > rman_get_end(r) || end < start)
2835 		return (EINVAL);
2836 	*lengthp = length;
2837 	*startp = start;
2838 	return (0);
2839 }
2840 
2841 /**
2842  * @brief Initialise a resource list.
2843  *
2844  * @param rl		the resource list to initialise
2845  */
2846 void
resource_list_init(struct resource_list * rl)2847 resource_list_init(struct resource_list *rl)
2848 {
2849 	STAILQ_INIT(rl);
2850 }
2851 
2852 /**
2853  * @brief Reclaim memory used by a resource list.
2854  *
2855  * This function frees the memory for all resource entries on the list
2856  * (if any).
2857  *
2858  * @param rl		the resource list to free
2859  */
2860 void
resource_list_free(struct resource_list * rl)2861 resource_list_free(struct resource_list *rl)
2862 {
2863 	struct resource_list_entry *rle;
2864 
2865 	while ((rle = STAILQ_FIRST(rl)) != NULL) {
2866 		if (rle->res)
2867 			panic("resource_list_free: resource entry is busy");
2868 		STAILQ_REMOVE_HEAD(rl, link);
2869 		free(rle, M_BUS);
2870 	}
2871 }
2872 
2873 /**
2874  * @brief Add a resource entry.
2875  *
2876  * This function adds a resource entry using the given @p type, @p
2877  * start, @p end and @p count values. A rid value is chosen by
2878  * searching sequentially for the first unused rid starting at zero.
2879  *
2880  * @param rl		the resource list to edit
2881  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2882  * @param start		the start address of the resource
2883  * @param end		the end address of the resource
2884  * @param count		XXX end-start+1
2885  */
2886 int
resource_list_add_next(struct resource_list * rl,int type,rman_res_t start,rman_res_t end,rman_res_t count)2887 resource_list_add_next(struct resource_list *rl, int type, rman_res_t start,
2888     rman_res_t end, rman_res_t count)
2889 {
2890 	int rid;
2891 
2892 	rid = 0;
2893 	while (resource_list_find(rl, type, rid) != NULL)
2894 		rid++;
2895 	resource_list_add(rl, type, rid, start, end, count);
2896 	return (rid);
2897 }
2898 
2899 /**
2900  * @brief Add or modify a resource entry.
2901  *
2902  * If an existing entry exists with the same type and rid, it will be
2903  * modified using the given values of @p start, @p end and @p
2904  * count. If no entry exists, a new one will be created using the
2905  * given values.  The resource list entry that matches is then returned.
2906  *
2907  * @param rl		the resource list to edit
2908  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2909  * @param rid		the resource identifier
2910  * @param start		the start address of the resource
2911  * @param end		the end address of the resource
2912  * @param count		XXX end-start+1
2913  */
2914 struct resource_list_entry *
resource_list_add(struct resource_list * rl,int type,int rid,rman_res_t start,rman_res_t end,rman_res_t count)2915 resource_list_add(struct resource_list *rl, int type, int rid,
2916     rman_res_t start, rman_res_t end, rman_res_t count)
2917 {
2918 	struct resource_list_entry *rle;
2919 
2920 	rle = resource_list_find(rl, type, rid);
2921 	if (!rle) {
2922 		rle = malloc(sizeof(struct resource_list_entry), M_BUS,
2923 		    M_WAITOK);
2924 		STAILQ_INSERT_TAIL(rl, rle, link);
2925 		rle->type = type;
2926 		rle->rid = rid;
2927 		rle->res = NULL;
2928 		rle->flags = 0;
2929 	}
2930 
2931 	if (rle->res)
2932 		panic("resource_list_add: resource entry is busy");
2933 
2934 	rle->start = start;
2935 	rle->end = end;
2936 	rle->count = count;
2937 	return (rle);
2938 }
2939 
2940 /**
2941  * @brief Determine if a resource entry is busy.
2942  *
2943  * Returns true if a resource entry is busy meaning that it has an
2944  * associated resource that is not an unallocated "reserved" resource.
2945  *
2946  * @param rl		the resource list to search
2947  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2948  * @param rid		the resource identifier
2949  *
2950  * @returns Non-zero if the entry is busy, zero otherwise.
2951  */
2952 int
resource_list_busy(struct resource_list * rl,int type,int rid)2953 resource_list_busy(struct resource_list *rl, int type, int rid)
2954 {
2955 	struct resource_list_entry *rle;
2956 
2957 	rle = resource_list_find(rl, type, rid);
2958 	if (rle == NULL || rle->res == NULL)
2959 		return (0);
2960 	if ((rle->flags & (RLE_RESERVED | RLE_ALLOCATED)) == RLE_RESERVED) {
2961 		KASSERT(!(rman_get_flags(rle->res) & RF_ACTIVE),
2962 		    ("reserved resource is active"));
2963 		return (0);
2964 	}
2965 	return (1);
2966 }
2967 
2968 /**
2969  * @brief Determine if a resource entry is reserved.
2970  *
2971  * Returns true if a resource entry is reserved meaning that it has an
2972  * associated "reserved" resource.  The resource can either be
2973  * allocated or unallocated.
2974  *
2975  * @param rl		the resource list to search
2976  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2977  * @param rid		the resource identifier
2978  *
2979  * @returns Non-zero if the entry is reserved, zero otherwise.
2980  */
2981 int
resource_list_reserved(struct resource_list * rl,int type,int rid)2982 resource_list_reserved(struct resource_list *rl, int type, int rid)
2983 {
2984 	struct resource_list_entry *rle;
2985 
2986 	rle = resource_list_find(rl, type, rid);
2987 	if (rle != NULL && rle->flags & RLE_RESERVED)
2988 		return (1);
2989 	return (0);
2990 }
2991 
2992 /**
2993  * @brief Find a resource entry by type and rid.
2994  *
2995  * @param rl		the resource list to search
2996  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
2997  * @param rid		the resource identifier
2998  *
2999  * @returns the resource entry pointer or NULL if there is no such
3000  * entry.
3001  */
3002 struct resource_list_entry *
resource_list_find(struct resource_list * rl,int type,int rid)3003 resource_list_find(struct resource_list *rl, int type, int rid)
3004 {
3005 	struct resource_list_entry *rle;
3006 
3007 	STAILQ_FOREACH(rle, rl, link) {
3008 		if (rle->type == type && rle->rid == rid)
3009 			return (rle);
3010 	}
3011 	return (NULL);
3012 }
3013 
3014 /**
3015  * @brief Delete a resource entry.
3016  *
3017  * @param rl		the resource list to edit
3018  * @param type		the resource entry type (e.g. SYS_RES_MEMORY)
3019  * @param rid		the resource identifier
3020  */
3021 void
resource_list_delete(struct resource_list * rl,int type,int rid)3022 resource_list_delete(struct resource_list *rl, int type, int rid)
3023 {
3024 	struct resource_list_entry *rle = resource_list_find(rl, type, rid);
3025 
3026 	if (rle) {
3027 		if (rle->res != NULL)
3028 			panic("resource_list_delete: resource has not been released");
3029 		STAILQ_REMOVE(rl, rle, resource_list_entry, link);
3030 		free(rle, M_BUS);
3031 	}
3032 }
3033 
3034 /**
3035  * @brief Allocate a reserved resource
3036  *
3037  * This can be used by buses to force the allocation of resources
3038  * that are always active in the system even if they are not allocated
3039  * by a driver (e.g. PCI BARs).  This function is usually called when
3040  * adding a new child to the bus.  The resource is allocated from the
3041  * parent bus when it is reserved.  The resource list entry is marked
3042  * with RLE_RESERVED to note that it is a reserved resource.
3043  *
3044  * Subsequent attempts to allocate the resource with
3045  * resource_list_alloc() will succeed the first time and will set
3046  * RLE_ALLOCATED to note that it has been allocated.  When a reserved
3047  * resource that has been allocated is released with
3048  * resource_list_release() the resource RLE_ALLOCATED is cleared, but
3049  * the actual resource remains allocated.  The resource can be released to
3050  * the parent bus by calling resource_list_unreserve().
3051  *
3052  * @param rl		the resource list to allocate from
3053  * @param bus		the parent device of @p child
3054  * @param child		the device for which the resource is being reserved
3055  * @param type		the type of resource to allocate
3056  * @param rid		a pointer to the resource identifier
3057  * @param start		hint at the start of the resource range - pass
3058  *			@c 0 for any start address
3059  * @param end		hint at the end of the resource range - pass
3060  *			@c ~0 for any end address
3061  * @param count		hint at the size of range required - pass @c 1
3062  *			for any size
3063  * @param flags		any extra flags to control the resource
3064  *			allocation - see @c RF_XXX flags in
3065  *			<sys/rman.h> for details
3066  *
3067  * @returns		the resource which was allocated or @c NULL if no
3068  *			resource could be allocated
3069  */
3070 struct resource *
resource_list_reserve(struct resource_list * rl,device_t bus,device_t child,int type,int * rid,rman_res_t start,rman_res_t end,rman_res_t count,u_int flags)3071 resource_list_reserve(struct resource_list *rl, device_t bus, device_t child,
3072     int type, int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
3073 {
3074 	struct resource_list_entry *rle = NULL;
3075 	int passthrough = (device_get_parent(child) != bus);
3076 	struct resource *r;
3077 
3078 	if (passthrough)
3079 		panic(
3080     "resource_list_reserve() should only be called for direct children");
3081 	if (flags & RF_ACTIVE)
3082 		panic(
3083     "resource_list_reserve() should only reserve inactive resources");
3084 
3085 	r = resource_list_alloc(rl, bus, child, type, rid, start, end, count,
3086 	    flags);
3087 	if (r != NULL) {
3088 		rle = resource_list_find(rl, type, *rid);
3089 		rle->flags |= RLE_RESERVED;
3090 	}
3091 	return (r);
3092 }
3093 
3094 /**
3095  * @brief Helper function for implementing BUS_ALLOC_RESOURCE()
3096  *
3097  * Implement BUS_ALLOC_RESOURCE() by looking up a resource from the list
3098  * and passing the allocation up to the parent of @p bus. This assumes
3099  * that the first entry of @c device_get_ivars(child) is a struct
3100  * resource_list. This also handles 'passthrough' allocations where a
3101  * child is a remote descendant of bus by passing the allocation up to
3102  * the parent of bus.
3103  *
3104  * Typically, a bus driver would store a list of child resources
3105  * somewhere in the child device's ivars (see device_get_ivars()) and
3106  * its implementation of BUS_ALLOC_RESOURCE() would find that list and
3107  * then call resource_list_alloc() to perform the allocation.
3108  *
3109  * @param rl		the resource list to allocate from
3110  * @param bus		the parent device of @p child
3111  * @param child		the device which is requesting an allocation
3112  * @param type		the type of resource to allocate
3113  * @param rid		a pointer to the resource identifier
3114  * @param start		hint at the start of the resource range - pass
3115  *			@c 0 for any start address
3116  * @param end		hint at the end of the resource range - pass
3117  *			@c ~0 for any end address
3118  * @param count		hint at the size of range required - pass @c 1
3119  *			for any size
3120  * @param flags		any extra flags to control the resource
3121  *			allocation - see @c RF_XXX flags in
3122  *			<sys/rman.h> for details
3123  *
3124  * @returns		the resource which was allocated or @c NULL if no
3125  *			resource could be allocated
3126  */
3127 struct resource *
resource_list_alloc(struct resource_list * rl,device_t bus,device_t child,int type,int * rid,rman_res_t start,rman_res_t end,rman_res_t count,u_int flags)3128 resource_list_alloc(struct resource_list *rl, device_t bus, device_t child,
3129     int type, int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
3130 {
3131 	struct resource_list_entry *rle = NULL;
3132 	int passthrough = (device_get_parent(child) != bus);
3133 	int isdefault = RMAN_IS_DEFAULT_RANGE(start, end);
3134 
3135 	if (passthrough) {
3136 		return (BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
3137 		    type, rid, start, end, count, flags));
3138 	}
3139 
3140 	rle = resource_list_find(rl, type, *rid);
3141 
3142 	if (!rle)
3143 		return (NULL);		/* no resource of that type/rid */
3144 
3145 	if (rle->res) {
3146 		if (rle->flags & RLE_RESERVED) {
3147 			if (rle->flags & RLE_ALLOCATED)
3148 				return (NULL);
3149 			if ((flags & RF_ACTIVE) &&
3150 			    bus_activate_resource(child, type, *rid,
3151 			    rle->res) != 0)
3152 				return (NULL);
3153 			rle->flags |= RLE_ALLOCATED;
3154 			return (rle->res);
3155 		}
3156 		device_printf(bus,
3157 		    "resource entry %#x type %d for child %s is busy\n", *rid,
3158 		    type, device_get_nameunit(child));
3159 		return (NULL);
3160 	}
3161 
3162 	if (isdefault) {
3163 		start = rle->start;
3164 		count = ulmax(count, rle->count);
3165 		end = ulmax(rle->end, start + count - 1);
3166 	}
3167 
3168 	rle->res = BUS_ALLOC_RESOURCE(device_get_parent(bus), child,
3169 	    type, rid, start, end, count, flags);
3170 
3171 	/*
3172 	 * Record the new range.
3173 	 */
3174 	if (rle->res) {
3175 		rle->start = rman_get_start(rle->res);
3176 		rle->end = rman_get_end(rle->res);
3177 		rle->count = count;
3178 	}
3179 
3180 	return (rle->res);
3181 }
3182 
3183 /**
3184  * @brief Helper function for implementing BUS_RELEASE_RESOURCE()
3185  *
3186  * Implement BUS_RELEASE_RESOURCE() using a resource list. Normally
3187  * used with resource_list_alloc().
3188  *
3189  * @param rl		the resource list which was allocated from
3190  * @param bus		the parent device of @p child
3191  * @param child		the device which is requesting a release
3192  * @param res		the resource to release
3193  *
3194  * @retval 0		success
3195  * @retval non-zero	a standard unix error code indicating what
3196  *			error condition prevented the operation
3197  */
3198 int
resource_list_release(struct resource_list * rl,device_t bus,device_t child,struct resource * res)3199 resource_list_release(struct resource_list *rl, device_t bus, device_t child,
3200     struct resource *res)
3201 {
3202 	struct resource_list_entry *rle = NULL;
3203 	int passthrough = (device_get_parent(child) != bus);
3204 	int error;
3205 
3206 	if (passthrough) {
3207 		return (BUS_RELEASE_RESOURCE(device_get_parent(bus), child,
3208 		    res));
3209 	}
3210 
3211 	rle = resource_list_find(rl, rman_get_type(res), rman_get_rid(res));
3212 
3213 	if (!rle)
3214 		panic("resource_list_release: can't find resource");
3215 	if (!rle->res)
3216 		panic("resource_list_release: resource entry is not busy");
3217 	if (rle->flags & RLE_RESERVED) {
3218 		if (rle->flags & RLE_ALLOCATED) {
3219 			if (rman_get_flags(res) & RF_ACTIVE) {
3220 				error = bus_deactivate_resource(child, res);
3221 				if (error)
3222 					return (error);
3223 			}
3224 			rle->flags &= ~RLE_ALLOCATED;
3225 			return (0);
3226 		}
3227 		return (EINVAL);
3228 	}
3229 
3230 	error = BUS_RELEASE_RESOURCE(device_get_parent(bus), child, res);
3231 	if (error)
3232 		return (error);
3233 
3234 	rle->res = NULL;
3235 	return (0);
3236 }
3237 
3238 /**
3239  * @brief Release all active resources of a given type
3240  *
3241  * Release all active resources of a specified type.  This is intended
3242  * to be used to cleanup resources leaked by a driver after detach or
3243  * a failed attach.
3244  *
3245  * @param rl		the resource list which was allocated from
3246  * @param bus		the parent device of @p child
3247  * @param child		the device whose active resources are being released
3248  * @param type		the type of resources to release
3249  *
3250  * @retval 0		success
3251  * @retval EBUSY	at least one resource was active
3252  */
3253 int
resource_list_release_active(struct resource_list * rl,device_t bus,device_t child,int type)3254 resource_list_release_active(struct resource_list *rl, device_t bus,
3255     device_t child, int type)
3256 {
3257 	struct resource_list_entry *rle;
3258 	int error, retval;
3259 
3260 	retval = 0;
3261 	STAILQ_FOREACH(rle, rl, link) {
3262 		if (rle->type != type)
3263 			continue;
3264 		if (rle->res == NULL)
3265 			continue;
3266 		if ((rle->flags & (RLE_RESERVED | RLE_ALLOCATED)) ==
3267 		    RLE_RESERVED)
3268 			continue;
3269 		retval = EBUSY;
3270 		error = resource_list_release(rl, bus, child, rle->res);
3271 		if (error != 0)
3272 			device_printf(bus,
3273 			    "Failed to release active resource: %d\n", error);
3274 	}
3275 	return (retval);
3276 }
3277 
3278 /**
3279  * @brief Fully release a reserved resource
3280  *
3281  * Fully releases a resource reserved via resource_list_reserve().
3282  *
3283  * @param rl		the resource list which was allocated from
3284  * @param bus		the parent device of @p child
3285  * @param child		the device whose reserved resource is being released
3286  * @param type		the type of resource to release
3287  * @param rid		the resource identifier
3288  * @param res		the resource to release
3289  *
3290  * @retval 0		success
3291  * @retval non-zero	a standard unix error code indicating what
3292  *			error condition prevented the operation
3293  */
3294 int
resource_list_unreserve(struct resource_list * rl,device_t bus,device_t child,int type,int rid)3295 resource_list_unreserve(struct resource_list *rl, device_t bus, device_t child,
3296     int type, int rid)
3297 {
3298 	struct resource_list_entry *rle = NULL;
3299 	int passthrough = (device_get_parent(child) != bus);
3300 
3301 	if (passthrough)
3302 		panic(
3303     "resource_list_unreserve() should only be called for direct children");
3304 
3305 	rle = resource_list_find(rl, type, rid);
3306 
3307 	if (!rle)
3308 		panic("resource_list_unreserve: can't find resource");
3309 	if (!(rle->flags & RLE_RESERVED))
3310 		return (EINVAL);
3311 	if (rle->flags & RLE_ALLOCATED)
3312 		return (EBUSY);
3313 	rle->flags &= ~RLE_RESERVED;
3314 	return (resource_list_release(rl, bus, child, rle->res));
3315 }
3316 
3317 /**
3318  * @brief Print a description of resources in a resource list
3319  *
3320  * Print all resources of a specified type, for use in BUS_PRINT_CHILD().
3321  * The name is printed if at least one resource of the given type is available.
3322  * The format is used to print resource start and end.
3323  *
3324  * @param rl		the resource list to print
3325  * @param name		the name of @p type, e.g. @c "memory"
3326  * @param type		type type of resource entry to print
3327  * @param format	printf(9) format string to print resource
3328  *			start and end values
3329  *
3330  * @returns		the number of characters printed
3331  */
3332 int
resource_list_print_type(struct resource_list * rl,const char * name,int type,const char * format)3333 resource_list_print_type(struct resource_list *rl, const char *name, int type,
3334     const char *format)
3335 {
3336 	struct resource_list_entry *rle;
3337 	int printed, retval;
3338 
3339 	printed = 0;
3340 	retval = 0;
3341 	/* Yes, this is kinda cheating */
3342 	STAILQ_FOREACH(rle, rl, link) {
3343 		if (rle->type == type) {
3344 			if (printed == 0)
3345 				retval += printf(" %s ", name);
3346 			else
3347 				retval += printf(",");
3348 			printed++;
3349 			retval += printf(format, rle->start);
3350 			if (rle->count > 1) {
3351 				retval += printf("-");
3352 				retval += printf(format, rle->start +
3353 						 rle->count - 1);
3354 			}
3355 		}
3356 	}
3357 	return (retval);
3358 }
3359 
3360 /**
3361  * @brief Releases all the resources in a list.
3362  *
3363  * @param rl		The resource list to purge.
3364  *
3365  * @returns		nothing
3366  */
3367 void
resource_list_purge(struct resource_list * rl)3368 resource_list_purge(struct resource_list *rl)
3369 {
3370 	struct resource_list_entry *rle;
3371 
3372 	while ((rle = STAILQ_FIRST(rl)) != NULL) {
3373 		if (rle->res)
3374 			bus_release_resource(rman_get_device(rle->res),
3375 			    rle->type, rle->rid, rle->res);
3376 		STAILQ_REMOVE_HEAD(rl, link);
3377 		free(rle, M_BUS);
3378 	}
3379 }
3380 
3381 device_t
bus_generic_add_child(device_t dev,u_int order,const char * name,int unit)3382 bus_generic_add_child(device_t dev, u_int order, const char *name, int unit)
3383 {
3384 	return (device_add_child_ordered(dev, order, name, unit));
3385 }
3386 
3387 /**
3388  * @brief Helper function for implementing DEVICE_PROBE()
3389  *
3390  * This function can be used to help implement the DEVICE_PROBE() for
3391  * a bus (i.e. a device which has other devices attached to it). It
3392  * calls the DEVICE_IDENTIFY() method of each driver in the device's
3393  * devclass.
3394  */
3395 int
bus_generic_probe(device_t dev)3396 bus_generic_probe(device_t dev)
3397 {
3398 	bus_identify_children(dev);
3399 	return (0);
3400 }
3401 
3402 /**
3403  * @brief Ask drivers to add child devices of the given device.
3404  *
3405  * This function allows drivers for child devices of a bus to identify
3406  * child devices and add them as children of the given device.  NB:
3407  * The driver for @param dev must implement the BUS_ADD_CHILD method.
3408  *
3409  * @param dev		the parent device
3410  */
3411 void
bus_identify_children(device_t dev)3412 bus_identify_children(device_t dev)
3413 {
3414 	devclass_t dc = dev->devclass;
3415 	driverlink_t dl;
3416 
3417 	TAILQ_FOREACH(dl, &dc->drivers, link) {
3418 		/*
3419 		 * If this driver's pass is too high, then ignore it.
3420 		 * For most drivers in the default pass, this will
3421 		 * never be true.  For early-pass drivers they will
3422 		 * only call the identify routines of eligible drivers
3423 		 * when this routine is called.  Drivers for later
3424 		 * passes should have their identify routines called
3425 		 * on early-pass buses during BUS_NEW_PASS().
3426 		 */
3427 		if (dl->pass > bus_current_pass)
3428 			continue;
3429 		DEVICE_IDENTIFY(dl->driver, dev);
3430 	}
3431 }
3432 
3433 /**
3434  * @brief Helper function for implementing DEVICE_ATTACH()
3435  *
3436  * This function can be used to help implement the DEVICE_ATTACH() for
3437  * a bus. It calls device_probe_and_attach() for each of the device's
3438  * children.
3439  */
3440 int
bus_generic_attach(device_t dev)3441 bus_generic_attach(device_t dev)
3442 {
3443 	bus_attach_children(dev);
3444 	return (0);
3445 }
3446 
3447 /**
3448  * @brief Probe and attach all children of the given device
3449  *
3450  * This function attempts to attach a device driver to each unattached
3451  * child of the given device using device_probe_and_attach().  If an
3452  * individual child fails to attach this function continues attaching
3453  * other children.
3454  *
3455  * @param dev		the parent device
3456  */
3457 void
bus_attach_children(device_t dev)3458 bus_attach_children(device_t dev)
3459 {
3460 	device_t child;
3461 
3462 	TAILQ_FOREACH(child, &dev->children, link) {
3463 		device_probe_and_attach(child);
3464 	}
3465 }
3466 
3467 /**
3468  * @brief Helper function for delaying attaching children
3469  *
3470  * Many buses can't run transactions on the bus which children need to probe and
3471  * attach until after interrupts and/or timers are running.  This function
3472  * delays their attach until interrupts and timers are enabled.
3473  */
3474 void
bus_delayed_attach_children(device_t dev)3475 bus_delayed_attach_children(device_t dev)
3476 {
3477 	/* Probe and attach the bus children when interrupts are available */
3478 	config_intrhook_oneshot((ich_func_t)bus_attach_children, dev);
3479 }
3480 
3481 /**
3482  * @brief Helper function for implementing DEVICE_DETACH()
3483  *
3484  * This function can be used to help implement the DEVICE_DETACH() for
3485  * a bus.  It detaches and deletes all children.  If an individual
3486  * child fails to detach, this function stops and returns an error.
3487  *
3488  * @param dev		the parent device
3489  *
3490  * @retval 0		success
3491  * @retval non-zero	a device would not detach
3492  */
3493 int
bus_generic_detach(device_t dev)3494 bus_generic_detach(device_t dev)
3495 {
3496 	int error;
3497 
3498 	error = bus_detach_children(dev);
3499 	if (error != 0)
3500 		return (error);
3501 
3502 	return (device_delete_children(dev));
3503 }
3504 
3505 /**
3506  * @brief Detach drivers from all children of a device
3507  *
3508  * This function attempts to detach a device driver from each attached
3509  * child of the given device using device_detach().  If an individual
3510  * child fails to detach this function stops and returns an error.
3511  * NB: Children that were successfully detached are not re-attached if
3512  * an error occurs.
3513  *
3514  * @param dev		the parent device
3515  *
3516  * @retval 0		success
3517  * @retval non-zero	a device would not detach
3518  */
3519 int
bus_detach_children(device_t dev)3520 bus_detach_children(device_t dev)
3521 {
3522 	device_t child;
3523 	int error;
3524 
3525 	/*
3526 	 * Detach children in the reverse order.
3527 	 * See bus_generic_suspend for details.
3528 	 */
3529 	TAILQ_FOREACH_REVERSE(child, &dev->children, device_list, link) {
3530 		if ((error = device_detach(child)) != 0)
3531 			return (error);
3532 	}
3533 
3534 	return (0);
3535 }
3536 
3537 /**
3538  * @brief Helper function for implementing DEVICE_SHUTDOWN()
3539  *
3540  * This function can be used to help implement the DEVICE_SHUTDOWN()
3541  * for a bus. It calls device_shutdown() for each of the device's
3542  * children.
3543  */
3544 int
bus_generic_shutdown(device_t dev)3545 bus_generic_shutdown(device_t dev)
3546 {
3547 	device_t child;
3548 
3549 	/*
3550 	 * Shut down children in the reverse order.
3551 	 * See bus_generic_suspend for details.
3552 	 */
3553 	TAILQ_FOREACH_REVERSE(child, &dev->children, device_list, link) {
3554 		device_shutdown(child);
3555 	}
3556 
3557 	return (0);
3558 }
3559 
3560 /**
3561  * @brief Default function for suspending a child device.
3562  *
3563  * This function is to be used by a bus's DEVICE_SUSPEND_CHILD().
3564  */
3565 int
bus_generic_suspend_child(device_t dev,device_t child)3566 bus_generic_suspend_child(device_t dev, device_t child)
3567 {
3568 	int	error;
3569 
3570 	error = DEVICE_SUSPEND(child);
3571 
3572 	if (error == 0) {
3573 		child->flags |= DF_SUSPENDED;
3574 	} else {
3575 		printf("DEVICE_SUSPEND(%s) failed: %d\n",
3576 		    device_get_nameunit(child), error);
3577 	}
3578 
3579 	return (error);
3580 }
3581 
3582 /**
3583  * @brief Default function for resuming a child device.
3584  *
3585  * This function is to be used by a bus's DEVICE_RESUME_CHILD().
3586  */
3587 int
bus_generic_resume_child(device_t dev,device_t child)3588 bus_generic_resume_child(device_t dev, device_t child)
3589 {
3590 	DEVICE_RESUME(child);
3591 	child->flags &= ~DF_SUSPENDED;
3592 
3593 	return (0);
3594 }
3595 
3596 /**
3597  * @brief Helper function for implementing DEVICE_SUSPEND()
3598  *
3599  * This function can be used to help implement the DEVICE_SUSPEND()
3600  * for a bus. It calls DEVICE_SUSPEND() for each of the device's
3601  * children. If any call to DEVICE_SUSPEND() fails, the suspend
3602  * operation is aborted and any devices which were suspended are
3603  * resumed immediately by calling their DEVICE_RESUME() methods.
3604  */
3605 int
bus_generic_suspend(device_t dev)3606 bus_generic_suspend(device_t dev)
3607 {
3608 	int		error;
3609 	device_t	child;
3610 
3611 	/*
3612 	 * Suspend children in the reverse order.
3613 	 * For most buses all children are equal, so the order does not matter.
3614 	 * Other buses, such as acpi, carefully order their child devices to
3615 	 * express implicit dependencies between them.  For such buses it is
3616 	 * safer to bring down devices in the reverse order.
3617 	 */
3618 	TAILQ_FOREACH_REVERSE(child, &dev->children, device_list, link) {
3619 		error = BUS_SUSPEND_CHILD(dev, child);
3620 		if (error != 0) {
3621 			child = TAILQ_NEXT(child, link);
3622 			if (child != NULL) {
3623 				TAILQ_FOREACH_FROM(child, &dev->children, link)
3624 					BUS_RESUME_CHILD(dev, child);
3625 			}
3626 			return (error);
3627 		}
3628 	}
3629 	return (0);
3630 }
3631 
3632 /**
3633  * @brief Helper function for implementing DEVICE_RESUME()
3634  *
3635  * This function can be used to help implement the DEVICE_RESUME() for
3636  * a bus. It calls DEVICE_RESUME() on each of the device's children.
3637  */
3638 int
bus_generic_resume(device_t dev)3639 bus_generic_resume(device_t dev)
3640 {
3641 	device_t	child;
3642 
3643 	TAILQ_FOREACH(child, &dev->children, link) {
3644 		BUS_RESUME_CHILD(dev, child);
3645 		/* if resume fails, there's nothing we can usefully do... */
3646 	}
3647 	return (0);
3648 }
3649 
3650 /**
3651  * @brief Helper function for implementing BUS_RESET_POST
3652  *
3653  * Bus can use this function to implement common operations of
3654  * re-attaching or resuming the children after the bus itself was
3655  * reset, and after restoring bus-unique state of children.
3656  *
3657  * @param dev	The bus
3658  * #param flags	DEVF_RESET_*
3659  */
3660 int
bus_helper_reset_post(device_t dev,int flags)3661 bus_helper_reset_post(device_t dev, int flags)
3662 {
3663 	device_t child;
3664 	int error, error1;
3665 
3666 	error = 0;
3667 	TAILQ_FOREACH(child, &dev->children,link) {
3668 		BUS_RESET_POST(dev, child);
3669 		error1 = (flags & DEVF_RESET_DETACH) != 0 ?
3670 		    device_probe_and_attach(child) :
3671 		    BUS_RESUME_CHILD(dev, child);
3672 		if (error == 0 && error1 != 0)
3673 			error = error1;
3674 	}
3675 	return (error);
3676 }
3677 
3678 static void
bus_helper_reset_prepare_rollback(device_t dev,device_t child,int flags)3679 bus_helper_reset_prepare_rollback(device_t dev, device_t child, int flags)
3680 {
3681 	child = TAILQ_NEXT(child, link);
3682 	if (child == NULL)
3683 		return;
3684 	TAILQ_FOREACH_FROM(child, &dev->children,link) {
3685 		BUS_RESET_POST(dev, child);
3686 		if ((flags & DEVF_RESET_DETACH) != 0)
3687 			device_probe_and_attach(child);
3688 		else
3689 			BUS_RESUME_CHILD(dev, child);
3690 	}
3691 }
3692 
3693 /**
3694  * @brief Helper function for implementing BUS_RESET_PREPARE
3695  *
3696  * Bus can use this function to implement common operations of
3697  * detaching or suspending the children before the bus itself is
3698  * reset, and then save bus-unique state of children that must
3699  * persists around reset.
3700  *
3701  * @param dev	The bus
3702  * #param flags	DEVF_RESET_*
3703  */
3704 int
bus_helper_reset_prepare(device_t dev,int flags)3705 bus_helper_reset_prepare(device_t dev, int flags)
3706 {
3707 	device_t child;
3708 	int error;
3709 
3710 	if (dev->state != DS_ATTACHED)
3711 		return (EBUSY);
3712 
3713 	TAILQ_FOREACH_REVERSE(child, &dev->children, device_list, link) {
3714 		if ((flags & DEVF_RESET_DETACH) != 0) {
3715 			error = device_get_state(child) == DS_ATTACHED ?
3716 			    device_detach(child) : 0;
3717 		} else {
3718 			error = BUS_SUSPEND_CHILD(dev, child);
3719 		}
3720 		if (error == 0) {
3721 			error = BUS_RESET_PREPARE(dev, child);
3722 			if (error != 0) {
3723 				if ((flags & DEVF_RESET_DETACH) != 0)
3724 					device_probe_and_attach(child);
3725 				else
3726 					BUS_RESUME_CHILD(dev, child);
3727 			}
3728 		}
3729 		if (error != 0) {
3730 			bus_helper_reset_prepare_rollback(dev, child, flags);
3731 			return (error);
3732 		}
3733 	}
3734 	return (0);
3735 }
3736 
3737 /**
3738  * @brief Helper function for implementing BUS_PRINT_CHILD().
3739  *
3740  * This function prints the first part of the ascii representation of
3741  * @p child, including its name, unit and description (if any - see
3742  * device_set_desc()).
3743  *
3744  * @returns the number of characters printed
3745  */
3746 int
bus_print_child_header(device_t dev,device_t child)3747 bus_print_child_header(device_t dev, device_t child)
3748 {
3749 	int	retval = 0;
3750 
3751 	if (device_get_desc(child)) {
3752 		retval += device_printf(child, "<%s>", device_get_desc(child));
3753 	} else {
3754 		retval += printf("%s", device_get_nameunit(child));
3755 	}
3756 
3757 	return (retval);
3758 }
3759 
3760 /**
3761  * @brief Helper function for implementing BUS_PRINT_CHILD().
3762  *
3763  * This function prints the last part of the ascii representation of
3764  * @p child, which consists of the string @c " on " followed by the
3765  * name and unit of the @p dev.
3766  *
3767  * @returns the number of characters printed
3768  */
3769 int
bus_print_child_footer(device_t dev,device_t child)3770 bus_print_child_footer(device_t dev, device_t child)
3771 {
3772 	return (printf(" on %s\n", device_get_nameunit(dev)));
3773 }
3774 
3775 /**
3776  * @brief Helper function for implementing BUS_PRINT_CHILD().
3777  *
3778  * This function prints out the VM domain for the given device.
3779  *
3780  * @returns the number of characters printed
3781  */
3782 int
bus_print_child_domain(device_t dev,device_t child)3783 bus_print_child_domain(device_t dev, device_t child)
3784 {
3785 	int domain;
3786 
3787 	/* No domain? Don't print anything */
3788 	if (BUS_GET_DOMAIN(dev, child, &domain) != 0)
3789 		return (0);
3790 
3791 	return (printf(" numa-domain %d", domain));
3792 }
3793 
3794 /**
3795  * @brief Helper function for implementing BUS_PRINT_CHILD().
3796  *
3797  * This function simply calls bus_print_child_header() followed by
3798  * bus_print_child_footer().
3799  *
3800  * @returns the number of characters printed
3801  */
3802 int
bus_generic_print_child(device_t dev,device_t child)3803 bus_generic_print_child(device_t dev, device_t child)
3804 {
3805 	int	retval = 0;
3806 
3807 	retval += bus_print_child_header(dev, child);
3808 	retval += bus_print_child_domain(dev, child);
3809 	retval += bus_print_child_footer(dev, child);
3810 
3811 	return (retval);
3812 }
3813 
3814 /**
3815  * @brief Stub function for implementing BUS_READ_IVAR().
3816  *
3817  * @returns ENOENT
3818  */
3819 int
bus_generic_read_ivar(device_t dev,device_t child,int index,uintptr_t * result)3820 bus_generic_read_ivar(device_t dev, device_t child, int index,
3821     uintptr_t * result)
3822 {
3823 	return (ENOENT);
3824 }
3825 
3826 /**
3827  * @brief Stub function for implementing BUS_WRITE_IVAR().
3828  *
3829  * @returns ENOENT
3830  */
3831 int
bus_generic_write_ivar(device_t dev,device_t child,int index,uintptr_t value)3832 bus_generic_write_ivar(device_t dev, device_t child, int index,
3833     uintptr_t value)
3834 {
3835 	return (ENOENT);
3836 }
3837 
3838 /**
3839  * @brief Helper function for implementing BUS_GET_PROPERTY().
3840  *
3841  * This simply calls the BUS_GET_PROPERTY of the parent of dev,
3842  * until a non-default implementation is found.
3843  */
3844 ssize_t
bus_generic_get_property(device_t dev,device_t child,const char * propname,void * propvalue,size_t size,device_property_type_t type)3845 bus_generic_get_property(device_t dev, device_t child, const char *propname,
3846     void *propvalue, size_t size, device_property_type_t type)
3847 {
3848 	if (device_get_parent(dev) != NULL)
3849 		return (BUS_GET_PROPERTY(device_get_parent(dev), child,
3850 		    propname, propvalue, size, type));
3851 
3852 	return (-1);
3853 }
3854 
3855 /**
3856  * @brief Helper function for implementing BUS_DRIVER_ADDED().
3857  *
3858  * This implementation of BUS_DRIVER_ADDED() simply calls the driver's
3859  * DEVICE_IDENTIFY() method to allow it to add new children to the bus
3860  * and then calls device_probe_and_attach() for each unattached child.
3861  */
3862 void
bus_generic_driver_added(device_t dev,driver_t * driver)3863 bus_generic_driver_added(device_t dev, driver_t *driver)
3864 {
3865 	device_t child;
3866 
3867 	DEVICE_IDENTIFY(driver, dev);
3868 	TAILQ_FOREACH(child, &dev->children, link) {
3869 		if (child->state == DS_NOTPRESENT)
3870 			device_probe_and_attach(child);
3871 	}
3872 }
3873 
3874 /**
3875  * @brief Helper function for implementing BUS_NEW_PASS().
3876  *
3877  * This implementing of BUS_NEW_PASS() first calls the identify
3878  * routines for any drivers that probe at the current pass.  Then it
3879  * walks the list of devices for this bus.  If a device is already
3880  * attached, then it calls BUS_NEW_PASS() on that device.  If the
3881  * device is not already attached, it attempts to attach a driver to
3882  * it.
3883  */
3884 void
bus_generic_new_pass(device_t dev)3885 bus_generic_new_pass(device_t dev)
3886 {
3887 	driverlink_t dl;
3888 	devclass_t dc;
3889 	device_t child;
3890 
3891 	dc = dev->devclass;
3892 	TAILQ_FOREACH(dl, &dc->drivers, link) {
3893 		if (dl->pass == bus_current_pass)
3894 			DEVICE_IDENTIFY(dl->driver, dev);
3895 	}
3896 	TAILQ_FOREACH(child, &dev->children, link) {
3897 		if (child->state >= DS_ATTACHED)
3898 			BUS_NEW_PASS(child);
3899 		else if (child->state == DS_NOTPRESENT)
3900 			device_probe_and_attach(child);
3901 	}
3902 }
3903 
3904 /**
3905  * @brief Helper function for implementing BUS_SETUP_INTR().
3906  *
3907  * This simple implementation of BUS_SETUP_INTR() simply calls the
3908  * BUS_SETUP_INTR() method of the parent of @p dev.
3909  */
3910 int
bus_generic_setup_intr(device_t dev,device_t child,struct resource * irq,int flags,driver_filter_t * filter,driver_intr_t * intr,void * arg,void ** cookiep)3911 bus_generic_setup_intr(device_t dev, device_t child, struct resource *irq,
3912     int flags, driver_filter_t *filter, driver_intr_t *intr, void *arg,
3913     void **cookiep)
3914 {
3915 	/* Propagate up the bus hierarchy until someone handles it. */
3916 	if (dev->parent)
3917 		return (BUS_SETUP_INTR(dev->parent, child, irq, flags,
3918 		    filter, intr, arg, cookiep));
3919 	return (EINVAL);
3920 }
3921 
3922 /**
3923  * @brief Helper function for implementing BUS_TEARDOWN_INTR().
3924  *
3925  * This simple implementation of BUS_TEARDOWN_INTR() simply calls the
3926  * BUS_TEARDOWN_INTR() method of the parent of @p dev.
3927  */
3928 int
bus_generic_teardown_intr(device_t dev,device_t child,struct resource * irq,void * cookie)3929 bus_generic_teardown_intr(device_t dev, device_t child, struct resource *irq,
3930     void *cookie)
3931 {
3932 	/* Propagate up the bus hierarchy until someone handles it. */
3933 	if (dev->parent)
3934 		return (BUS_TEARDOWN_INTR(dev->parent, child, irq, cookie));
3935 	return (EINVAL);
3936 }
3937 
3938 /**
3939  * @brief Helper function for implementing BUS_SUSPEND_INTR().
3940  *
3941  * This simple implementation of BUS_SUSPEND_INTR() simply calls the
3942  * BUS_SUSPEND_INTR() method of the parent of @p dev.
3943  */
3944 int
bus_generic_suspend_intr(device_t dev,device_t child,struct resource * irq)3945 bus_generic_suspend_intr(device_t dev, device_t child, struct resource *irq)
3946 {
3947 	/* Propagate up the bus hierarchy until someone handles it. */
3948 	if (dev->parent)
3949 		return (BUS_SUSPEND_INTR(dev->parent, child, irq));
3950 	return (EINVAL);
3951 }
3952 
3953 /**
3954  * @brief Helper function for implementing BUS_RESUME_INTR().
3955  *
3956  * This simple implementation of BUS_RESUME_INTR() simply calls the
3957  * BUS_RESUME_INTR() method of the parent of @p dev.
3958  */
3959 int
bus_generic_resume_intr(device_t dev,device_t child,struct resource * irq)3960 bus_generic_resume_intr(device_t dev, device_t child, struct resource *irq)
3961 {
3962 	/* Propagate up the bus hierarchy until someone handles it. */
3963 	if (dev->parent)
3964 		return (BUS_RESUME_INTR(dev->parent, child, irq));
3965 	return (EINVAL);
3966 }
3967 
3968 /**
3969  * @brief Helper function for implementing BUS_ADJUST_RESOURCE().
3970  *
3971  * This simple implementation of BUS_ADJUST_RESOURCE() simply calls the
3972  * BUS_ADJUST_RESOURCE() method of the parent of @p dev.
3973  */
3974 int
bus_generic_adjust_resource(device_t dev,device_t child,struct resource * r,rman_res_t start,rman_res_t end)3975 bus_generic_adjust_resource(device_t dev, device_t child, struct resource *r,
3976     rman_res_t start, rman_res_t end)
3977 {
3978 	/* Propagate up the bus hierarchy until someone handles it. */
3979 	if (dev->parent)
3980 		return (BUS_ADJUST_RESOURCE(dev->parent, child, r, start, end));
3981 	return (EINVAL);
3982 }
3983 
3984 /*
3985  * @brief Helper function for implementing BUS_TRANSLATE_RESOURCE().
3986  *
3987  * This simple implementation of BUS_TRANSLATE_RESOURCE() simply calls the
3988  * BUS_TRANSLATE_RESOURCE() method of the parent of @p dev.  If there is no
3989  * parent, no translation happens.
3990  */
3991 int
bus_generic_translate_resource(device_t dev,int type,rman_res_t start,rman_res_t * newstart)3992 bus_generic_translate_resource(device_t dev, int type, rman_res_t start,
3993     rman_res_t *newstart)
3994 {
3995 	if (dev->parent)
3996 		return (BUS_TRANSLATE_RESOURCE(dev->parent, type, start,
3997 		    newstart));
3998 	*newstart = start;
3999 	return (0);
4000 }
4001 
4002 /**
4003  * @brief Helper function for implementing BUS_ALLOC_RESOURCE().
4004  *
4005  * This simple implementation of BUS_ALLOC_RESOURCE() simply calls the
4006  * BUS_ALLOC_RESOURCE() method of the parent of @p dev.
4007  */
4008 struct resource *
bus_generic_alloc_resource(device_t dev,device_t child,int type,int * rid,rman_res_t start,rman_res_t end,rman_res_t count,u_int flags)4009 bus_generic_alloc_resource(device_t dev, device_t child, int type, int *rid,
4010     rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
4011 {
4012 	/* Propagate up the bus hierarchy until someone handles it. */
4013 	if (dev->parent)
4014 		return (BUS_ALLOC_RESOURCE(dev->parent, child, type, rid,
4015 		    start, end, count, flags));
4016 	return (NULL);
4017 }
4018 
4019 /**
4020  * @brief Helper function for implementing BUS_RELEASE_RESOURCE().
4021  *
4022  * This simple implementation of BUS_RELEASE_RESOURCE() simply calls the
4023  * BUS_RELEASE_RESOURCE() method of the parent of @p dev.
4024  */
4025 int
bus_generic_release_resource(device_t dev,device_t child,struct resource * r)4026 bus_generic_release_resource(device_t dev, device_t child, struct resource *r)
4027 {
4028 	/* Propagate up the bus hierarchy until someone handles it. */
4029 	if (dev->parent)
4030 		return (BUS_RELEASE_RESOURCE(dev->parent, child, r));
4031 	return (EINVAL);
4032 }
4033 
4034 /**
4035  * @brief Helper function for implementing BUS_ACTIVATE_RESOURCE().
4036  *
4037  * This simple implementation of BUS_ACTIVATE_RESOURCE() simply calls the
4038  * BUS_ACTIVATE_RESOURCE() method of the parent of @p dev.
4039  */
4040 int
bus_generic_activate_resource(device_t dev,device_t child,struct resource * r)4041 bus_generic_activate_resource(device_t dev, device_t child, struct resource *r)
4042 {
4043 	/* Propagate up the bus hierarchy until someone handles it. */
4044 	if (dev->parent)
4045 		return (BUS_ACTIVATE_RESOURCE(dev->parent, child, r));
4046 	return (EINVAL);
4047 }
4048 
4049 /**
4050  * @brief Helper function for implementing BUS_DEACTIVATE_RESOURCE().
4051  *
4052  * This simple implementation of BUS_DEACTIVATE_RESOURCE() simply calls the
4053  * BUS_DEACTIVATE_RESOURCE() method of the parent of @p dev.
4054  */
4055 int
bus_generic_deactivate_resource(device_t dev,device_t child,struct resource * r)4056 bus_generic_deactivate_resource(device_t dev, device_t child,
4057     struct resource *r)
4058 {
4059 	/* Propagate up the bus hierarchy until someone handles it. */
4060 	if (dev->parent)
4061 		return (BUS_DEACTIVATE_RESOURCE(dev->parent, child, r));
4062 	return (EINVAL);
4063 }
4064 
4065 /**
4066  * @brief Helper function for implementing BUS_MAP_RESOURCE().
4067  *
4068  * This simple implementation of BUS_MAP_RESOURCE() simply calls the
4069  * BUS_MAP_RESOURCE() method of the parent of @p dev.
4070  */
4071 int
bus_generic_map_resource(device_t dev,device_t child,struct resource * r,struct resource_map_request * args,struct resource_map * map)4072 bus_generic_map_resource(device_t dev, device_t child, struct resource *r,
4073     struct resource_map_request *args, struct resource_map *map)
4074 {
4075 	/* Propagate up the bus hierarchy until someone handles it. */
4076 	if (dev->parent)
4077 		return (BUS_MAP_RESOURCE(dev->parent, child, r, args, map));
4078 	return (EINVAL);
4079 }
4080 
4081 /**
4082  * @brief Helper function for implementing BUS_UNMAP_RESOURCE().
4083  *
4084  * This simple implementation of BUS_UNMAP_RESOURCE() simply calls the
4085  * BUS_UNMAP_RESOURCE() method of the parent of @p dev.
4086  */
4087 int
bus_generic_unmap_resource(device_t dev,device_t child,struct resource * r,struct resource_map * map)4088 bus_generic_unmap_resource(device_t dev, device_t child, struct resource *r,
4089     struct resource_map *map)
4090 {
4091 	/* Propagate up the bus hierarchy until someone handles it. */
4092 	if (dev->parent)
4093 		return (BUS_UNMAP_RESOURCE(dev->parent, child, r, map));
4094 	return (EINVAL);
4095 }
4096 
4097 /**
4098  * @brief Helper function for implementing BUS_BIND_INTR().
4099  *
4100  * This simple implementation of BUS_BIND_INTR() simply calls the
4101  * BUS_BIND_INTR() method of the parent of @p dev.
4102  */
4103 int
bus_generic_bind_intr(device_t dev,device_t child,struct resource * irq,int cpu)4104 bus_generic_bind_intr(device_t dev, device_t child, struct resource *irq,
4105     int cpu)
4106 {
4107 	/* Propagate up the bus hierarchy until someone handles it. */
4108 	if (dev->parent)
4109 		return (BUS_BIND_INTR(dev->parent, child, irq, cpu));
4110 	return (EINVAL);
4111 }
4112 
4113 /**
4114  * @brief Helper function for implementing BUS_CONFIG_INTR().
4115  *
4116  * This simple implementation of BUS_CONFIG_INTR() simply calls the
4117  * BUS_CONFIG_INTR() method of the parent of @p dev.
4118  */
4119 int
bus_generic_config_intr(device_t dev,int irq,enum intr_trigger trig,enum intr_polarity pol)4120 bus_generic_config_intr(device_t dev, int irq, enum intr_trigger trig,
4121     enum intr_polarity pol)
4122 {
4123 	/* Propagate up the bus hierarchy until someone handles it. */
4124 	if (dev->parent)
4125 		return (BUS_CONFIG_INTR(dev->parent, irq, trig, pol));
4126 	return (EINVAL);
4127 }
4128 
4129 /**
4130  * @brief Helper function for implementing BUS_DESCRIBE_INTR().
4131  *
4132  * This simple implementation of BUS_DESCRIBE_INTR() simply calls the
4133  * BUS_DESCRIBE_INTR() method of the parent of @p dev.
4134  */
4135 int
bus_generic_describe_intr(device_t dev,device_t child,struct resource * irq,void * cookie,const char * descr)4136 bus_generic_describe_intr(device_t dev, device_t child, struct resource *irq,
4137     void *cookie, const char *descr)
4138 {
4139 	/* Propagate up the bus hierarchy until someone handles it. */
4140 	if (dev->parent)
4141 		return (BUS_DESCRIBE_INTR(dev->parent, child, irq, cookie,
4142 		    descr));
4143 	return (EINVAL);
4144 }
4145 
4146 /**
4147  * @brief Helper function for implementing BUS_GET_CPUS().
4148  *
4149  * This simple implementation of BUS_GET_CPUS() simply calls the
4150  * BUS_GET_CPUS() method of the parent of @p dev.
4151  */
4152 int
bus_generic_get_cpus(device_t dev,device_t child,enum cpu_sets op,size_t setsize,cpuset_t * cpuset)4153 bus_generic_get_cpus(device_t dev, device_t child, enum cpu_sets op,
4154     size_t setsize, cpuset_t *cpuset)
4155 {
4156 	/* Propagate up the bus hierarchy until someone handles it. */
4157 	if (dev->parent != NULL)
4158 		return (BUS_GET_CPUS(dev->parent, child, op, setsize, cpuset));
4159 	return (EINVAL);
4160 }
4161 
4162 /**
4163  * @brief Helper function for implementing BUS_GET_DMA_TAG().
4164  *
4165  * This simple implementation of BUS_GET_DMA_TAG() simply calls the
4166  * BUS_GET_DMA_TAG() method of the parent of @p dev.
4167  */
4168 bus_dma_tag_t
bus_generic_get_dma_tag(device_t dev,device_t child)4169 bus_generic_get_dma_tag(device_t dev, device_t child)
4170 {
4171 	/* Propagate up the bus hierarchy until someone handles it. */
4172 	if (dev->parent != NULL)
4173 		return (BUS_GET_DMA_TAG(dev->parent, child));
4174 	return (NULL);
4175 }
4176 
4177 /**
4178  * @brief Helper function for implementing BUS_GET_BUS_TAG().
4179  *
4180  * This simple implementation of BUS_GET_BUS_TAG() simply calls the
4181  * BUS_GET_BUS_TAG() method of the parent of @p dev.
4182  */
4183 bus_space_tag_t
bus_generic_get_bus_tag(device_t dev,device_t child)4184 bus_generic_get_bus_tag(device_t dev, device_t child)
4185 {
4186 	/* Propagate up the bus hierarchy until someone handles it. */
4187 	if (dev->parent != NULL)
4188 		return (BUS_GET_BUS_TAG(dev->parent, child));
4189 	return ((bus_space_tag_t)0);
4190 }
4191 
4192 /**
4193  * @brief Helper function for implementing BUS_GET_RESOURCE().
4194  *
4195  * This implementation of BUS_GET_RESOURCE() uses the
4196  * resource_list_find() function to do most of the work. It calls
4197  * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
4198  * search.
4199  */
4200 int
bus_generic_rl_get_resource(device_t dev,device_t child,int type,int rid,rman_res_t * startp,rman_res_t * countp)4201 bus_generic_rl_get_resource(device_t dev, device_t child, int type, int rid,
4202     rman_res_t *startp, rman_res_t *countp)
4203 {
4204 	struct resource_list *		rl = NULL;
4205 	struct resource_list_entry *	rle = NULL;
4206 
4207 	rl = BUS_GET_RESOURCE_LIST(dev, child);
4208 	if (!rl)
4209 		return (EINVAL);
4210 
4211 	rle = resource_list_find(rl, type, rid);
4212 	if (!rle)
4213 		return (ENOENT);
4214 
4215 	if (startp)
4216 		*startp = rle->start;
4217 	if (countp)
4218 		*countp = rle->count;
4219 
4220 	return (0);
4221 }
4222 
4223 /**
4224  * @brief Helper function for implementing BUS_SET_RESOURCE().
4225  *
4226  * This implementation of BUS_SET_RESOURCE() uses the
4227  * resource_list_add() function to do most of the work. It calls
4228  * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
4229  * edit.
4230  */
4231 int
bus_generic_rl_set_resource(device_t dev,device_t child,int type,int rid,rman_res_t start,rman_res_t count)4232 bus_generic_rl_set_resource(device_t dev, device_t child, int type, int rid,
4233     rman_res_t start, rman_res_t count)
4234 {
4235 	struct resource_list *		rl = NULL;
4236 
4237 	rl = BUS_GET_RESOURCE_LIST(dev, child);
4238 	if (!rl)
4239 		return (EINVAL);
4240 
4241 	resource_list_add(rl, type, rid, start, (start + count - 1), count);
4242 
4243 	return (0);
4244 }
4245 
4246 /**
4247  * @brief Helper function for implementing BUS_DELETE_RESOURCE().
4248  *
4249  * This implementation of BUS_DELETE_RESOURCE() uses the
4250  * resource_list_delete() function to do most of the work. It calls
4251  * BUS_GET_RESOURCE_LIST() to find a suitable resource list to
4252  * edit.
4253  */
4254 void
bus_generic_rl_delete_resource(device_t dev,device_t child,int type,int rid)4255 bus_generic_rl_delete_resource(device_t dev, device_t child, int type, int rid)
4256 {
4257 	struct resource_list *		rl = NULL;
4258 
4259 	rl = BUS_GET_RESOURCE_LIST(dev, child);
4260 	if (!rl)
4261 		return;
4262 
4263 	resource_list_delete(rl, type, rid);
4264 
4265 	return;
4266 }
4267 
4268 /**
4269  * @brief Helper function for implementing BUS_RELEASE_RESOURCE().
4270  *
4271  * This implementation of BUS_RELEASE_RESOURCE() uses the
4272  * resource_list_release() function to do most of the work. It calls
4273  * BUS_GET_RESOURCE_LIST() to find a suitable resource list.
4274  */
4275 int
bus_generic_rl_release_resource(device_t dev,device_t child,struct resource * r)4276 bus_generic_rl_release_resource(device_t dev, device_t child,
4277     struct resource *r)
4278 {
4279 	struct resource_list *		rl = NULL;
4280 
4281 	if (device_get_parent(child) != dev)
4282 		return (BUS_RELEASE_RESOURCE(device_get_parent(dev), child, r));
4283 
4284 	rl = BUS_GET_RESOURCE_LIST(dev, child);
4285 	if (!rl)
4286 		return (EINVAL);
4287 
4288 	return (resource_list_release(rl, dev, child, r));
4289 }
4290 
4291 /**
4292  * @brief Helper function for implementing BUS_ALLOC_RESOURCE().
4293  *
4294  * This implementation of BUS_ALLOC_RESOURCE() uses the
4295  * resource_list_alloc() function to do most of the work. It calls
4296  * BUS_GET_RESOURCE_LIST() to find a suitable resource list.
4297  */
4298 struct resource *
bus_generic_rl_alloc_resource(device_t dev,device_t child,int type,int * rid,rman_res_t start,rman_res_t end,rman_res_t count,u_int flags)4299 bus_generic_rl_alloc_resource(device_t dev, device_t child, int type,
4300     int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
4301 {
4302 	struct resource_list *		rl = NULL;
4303 
4304 	if (device_get_parent(child) != dev)
4305 		return (BUS_ALLOC_RESOURCE(device_get_parent(dev), child,
4306 		    type, rid, start, end, count, flags));
4307 
4308 	rl = BUS_GET_RESOURCE_LIST(dev, child);
4309 	if (!rl)
4310 		return (NULL);
4311 
4312 	return (resource_list_alloc(rl, dev, child, type, rid,
4313 	    start, end, count, flags));
4314 }
4315 
4316 /**
4317  * @brief Helper function for implementing BUS_ALLOC_RESOURCE().
4318  *
4319  * This implementation of BUS_ALLOC_RESOURCE() allocates a
4320  * resource from a resource manager.  It uses BUS_GET_RMAN()
4321  * to obtain the resource manager.
4322  */
4323 struct resource *
bus_generic_rman_alloc_resource(device_t dev,device_t child,int type,int * rid,rman_res_t start,rman_res_t end,rman_res_t count,u_int flags)4324 bus_generic_rman_alloc_resource(device_t dev, device_t child, int type,
4325     int *rid, rman_res_t start, rman_res_t end, rman_res_t count, u_int flags)
4326 {
4327 	struct resource *r;
4328 	struct rman *rm;
4329 
4330 	rm = BUS_GET_RMAN(dev, type, flags);
4331 	if (rm == NULL)
4332 		return (NULL);
4333 
4334 	r = rman_reserve_resource(rm, start, end, count, flags & ~RF_ACTIVE,
4335 	    child);
4336 	if (r == NULL)
4337 		return (NULL);
4338 	rman_set_rid(r, *rid);
4339 	rman_set_type(r, type);
4340 
4341 	if (flags & RF_ACTIVE) {
4342 		if (bus_activate_resource(child, type, *rid, r) != 0) {
4343 			rman_release_resource(r);
4344 			return (NULL);
4345 		}
4346 	}
4347 
4348 	return (r);
4349 }
4350 
4351 /**
4352  * @brief Helper function for implementing BUS_ADJUST_RESOURCE().
4353  *
4354  * This implementation of BUS_ADJUST_RESOURCE() adjusts resources only
4355  * if they were allocated from the resource manager returned by
4356  * BUS_GET_RMAN().
4357  */
4358 int
bus_generic_rman_adjust_resource(device_t dev,device_t child,struct resource * r,rman_res_t start,rman_res_t end)4359 bus_generic_rman_adjust_resource(device_t dev, device_t child,
4360     struct resource *r, rman_res_t start, rman_res_t end)
4361 {
4362 	struct rman *rm;
4363 
4364 	rm = BUS_GET_RMAN(dev, rman_get_type(r), rman_get_flags(r));
4365 	if (rm == NULL)
4366 		return (ENXIO);
4367 	if (!rman_is_region_manager(r, rm))
4368 		return (EINVAL);
4369 	return (rman_adjust_resource(r, start, end));
4370 }
4371 
4372 /**
4373  * @brief Helper function for implementing BUS_RELEASE_RESOURCE().
4374  *
4375  * This implementation of BUS_RELEASE_RESOURCE() releases resources
4376  * allocated by bus_generic_rman_alloc_resource.
4377  */
4378 int
bus_generic_rman_release_resource(device_t dev,device_t child,struct resource * r)4379 bus_generic_rman_release_resource(device_t dev, device_t child,
4380     struct resource *r)
4381 {
4382 #ifdef INVARIANTS
4383 	struct rman *rm;
4384 #endif
4385 	int error;
4386 
4387 #ifdef INVARIANTS
4388 	rm = BUS_GET_RMAN(dev, rman_get_type(r), rman_get_flags(r));
4389 	KASSERT(rman_is_region_manager(r, rm),
4390 	    ("%s: rman %p doesn't match for resource %p", __func__, rm, r));
4391 #endif
4392 
4393 	if (rman_get_flags(r) & RF_ACTIVE) {
4394 		error = bus_deactivate_resource(child, r);
4395 		if (error != 0)
4396 			return (error);
4397 	}
4398 	return (rman_release_resource(r));
4399 }
4400 
4401 /**
4402  * @brief Helper function for implementing BUS_ACTIVATE_RESOURCE().
4403  *
4404  * This implementation of BUS_ACTIVATE_RESOURCE() activates resources
4405  * allocated by bus_generic_rman_alloc_resource.
4406  */
4407 int
bus_generic_rman_activate_resource(device_t dev,device_t child,struct resource * r)4408 bus_generic_rman_activate_resource(device_t dev, device_t child,
4409     struct resource *r)
4410 {
4411 	struct resource_map map;
4412 #ifdef INVARIANTS
4413 	struct rman *rm;
4414 #endif
4415 	int error, type;
4416 
4417 	type = rman_get_type(r);
4418 #ifdef INVARIANTS
4419 	rm = BUS_GET_RMAN(dev, type, rman_get_flags(r));
4420 	KASSERT(rman_is_region_manager(r, rm),
4421 	    ("%s: rman %p doesn't match for resource %p", __func__, rm, r));
4422 #endif
4423 
4424 	error = rman_activate_resource(r);
4425 	if (error != 0)
4426 		return (error);
4427 
4428 	switch (type) {
4429 	case SYS_RES_IOPORT:
4430 	case SYS_RES_MEMORY:
4431 		if ((rman_get_flags(r) & RF_UNMAPPED) == 0) {
4432 			error = BUS_MAP_RESOURCE(dev, child, r, NULL, &map);
4433 			if (error != 0)
4434 				break;
4435 
4436 			rman_set_mapping(r, &map);
4437 		}
4438 		break;
4439 #ifdef INTRNG
4440 	case SYS_RES_IRQ:
4441 		error = intr_activate_irq(child, r);
4442 		break;
4443 #endif
4444 	}
4445 	if (error != 0)
4446 		rman_deactivate_resource(r);
4447 	return (error);
4448 }
4449 
4450 /**
4451  * @brief Helper function for implementing BUS_DEACTIVATE_RESOURCE().
4452  *
4453  * This implementation of BUS_DEACTIVATE_RESOURCE() deactivates
4454  * resources allocated by bus_generic_rman_alloc_resource.
4455  */
4456 int
bus_generic_rman_deactivate_resource(device_t dev,device_t child,struct resource * r)4457 bus_generic_rman_deactivate_resource(device_t dev, device_t child,
4458     struct resource *r)
4459 {
4460 	struct resource_map map;
4461 #ifdef INVARIANTS
4462 	struct rman *rm;
4463 #endif
4464 	int error, type;
4465 
4466 	type = rman_get_type(r);
4467 #ifdef INVARIANTS
4468 	rm = BUS_GET_RMAN(dev, type, rman_get_flags(r));
4469 	KASSERT(rman_is_region_manager(r, rm),
4470 	    ("%s: rman %p doesn't match for resource %p", __func__, rm, r));
4471 #endif
4472 
4473 	error = rman_deactivate_resource(r);
4474 	if (error != 0)
4475 		return (error);
4476 
4477 	switch (type) {
4478 	case SYS_RES_IOPORT:
4479 	case SYS_RES_MEMORY:
4480 		if ((rman_get_flags(r) & RF_UNMAPPED) == 0) {
4481 			rman_get_mapping(r, &map);
4482 			BUS_UNMAP_RESOURCE(dev, child, r, &map);
4483 		}
4484 		break;
4485 #ifdef INTRNG
4486 	case SYS_RES_IRQ:
4487 		intr_deactivate_irq(child, r);
4488 		break;
4489 #endif
4490 	}
4491 	return (0);
4492 }
4493 
4494 /**
4495  * @brief Helper function for implementing BUS_CHILD_PRESENT().
4496  *
4497  * This simple implementation of BUS_CHILD_PRESENT() simply calls the
4498  * BUS_CHILD_PRESENT() method of the parent of @p dev.
4499  */
4500 int
bus_generic_child_present(device_t dev,device_t child)4501 bus_generic_child_present(device_t dev, device_t child)
4502 {
4503 	return (BUS_CHILD_PRESENT(device_get_parent(dev), dev));
4504 }
4505 
4506 /**
4507  * @brief Helper function for implementing BUS_GET_DOMAIN().
4508  *
4509  * This simple implementation of BUS_GET_DOMAIN() calls the
4510  * BUS_GET_DOMAIN() method of the parent of @p dev.  If @p dev
4511  * does not have a parent, the function fails with ENOENT.
4512  */
4513 int
bus_generic_get_domain(device_t dev,device_t child,int * domain)4514 bus_generic_get_domain(device_t dev, device_t child, int *domain)
4515 {
4516 	if (dev->parent)
4517 		return (BUS_GET_DOMAIN(dev->parent, dev, domain));
4518 
4519 	return (ENOENT);
4520 }
4521 
4522 /**
4523  * @brief Helper function to implement normal BUS_GET_DEVICE_PATH()
4524  *
4525  * This function knows how to (a) pass the request up the tree if there's
4526  * a parent and (b) Knows how to supply a FreeBSD locator.
4527  *
4528  * @param bus		bus in the walk up the tree
4529  * @param child		leaf node to print information about
4530  * @param locator	BUS_LOCATOR_xxx string for locator
4531  * @param sb		Buffer to print information into
4532  */
4533 int
bus_generic_get_device_path(device_t bus,device_t child,const char * locator,struct sbuf * sb)4534 bus_generic_get_device_path(device_t bus, device_t child, const char *locator,
4535     struct sbuf *sb)
4536 {
4537 	int rv = 0;
4538 	device_t parent;
4539 
4540 	/*
4541 	 * We don't recurse on ACPI since either we know the handle for the
4542 	 * device or we don't. And if we're in the generic routine, we don't
4543 	 * have a ACPI override. All other locators build up a path by having
4544 	 * their parents create a path and then adding the path element for this
4545 	 * node. That's why we recurse with parent, bus rather than the typical
4546 	 * parent, child: each spot in the tree is independent of what our child
4547 	 * will do with this path.
4548 	 */
4549 	parent = device_get_parent(bus);
4550 	if (parent != NULL && strcmp(locator, BUS_LOCATOR_ACPI) != 0) {
4551 		rv = BUS_GET_DEVICE_PATH(parent, bus, locator, sb);
4552 	}
4553 	if (strcmp(locator, BUS_LOCATOR_FREEBSD) == 0) {
4554 		if (rv == 0) {
4555 			sbuf_printf(sb, "/%s", device_get_nameunit(child));
4556 		}
4557 		return (rv);
4558 	}
4559 	/*
4560 	 * Don't know what to do. So assume we do nothing. Not sure that's
4561 	 * the right thing, but keeps us from having a big list here.
4562 	 */
4563 	return (0);
4564 }
4565 
4566 
4567 /**
4568  * @brief Helper function for implementing BUS_RESCAN().
4569  *
4570  * This null implementation of BUS_RESCAN() always fails to indicate
4571  * the bus does not support rescanning.
4572  */
4573 int
bus_null_rescan(device_t dev)4574 bus_null_rescan(device_t dev)
4575 {
4576 	return (ENODEV);
4577 }
4578 
4579 /*
4580  * Some convenience functions to make it easier for drivers to use the
4581  * resource-management functions.  All these really do is hide the
4582  * indirection through the parent's method table, making for slightly
4583  * less-wordy code.  In the future, it might make sense for this code
4584  * to maintain some sort of a list of resources allocated by each device.
4585  */
4586 
4587 int
bus_alloc_resources(device_t dev,struct resource_spec * rs,struct resource ** res)4588 bus_alloc_resources(device_t dev, struct resource_spec *rs,
4589     struct resource **res)
4590 {
4591 	int i;
4592 
4593 	for (i = 0; rs[i].type != -1; i++)
4594 		res[i] = NULL;
4595 	for (i = 0; rs[i].type != -1; i++) {
4596 		res[i] = bus_alloc_resource_any(dev,
4597 		    rs[i].type, &rs[i].rid, rs[i].flags);
4598 		if (res[i] == NULL && !(rs[i].flags & RF_OPTIONAL)) {
4599 			bus_release_resources(dev, rs, res);
4600 			return (ENXIO);
4601 		}
4602 	}
4603 	return (0);
4604 }
4605 
4606 void
bus_release_resources(device_t dev,const struct resource_spec * rs,struct resource ** res)4607 bus_release_resources(device_t dev, const struct resource_spec *rs,
4608     struct resource **res)
4609 {
4610 	int i;
4611 
4612 	for (i = 0; rs[i].type != -1; i++)
4613 		if (res[i] != NULL) {
4614 			bus_release_resource(
4615 			    dev, rs[i].type, rs[i].rid, res[i]);
4616 			res[i] = NULL;
4617 		}
4618 }
4619 
4620 /**
4621  * @brief Wrapper function for BUS_ALLOC_RESOURCE().
4622  *
4623  * This function simply calls the BUS_ALLOC_RESOURCE() method of the
4624  * parent of @p dev.
4625  */
4626 struct resource *
bus_alloc_resource(device_t dev,int type,int * rid,rman_res_t start,rman_res_t end,rman_res_t count,u_int flags)4627 bus_alloc_resource(device_t dev, int type, int *rid, rman_res_t start,
4628     rman_res_t end, rman_res_t count, u_int flags)
4629 {
4630 	struct resource *res;
4631 
4632 	if (dev->parent == NULL)
4633 		return (NULL);
4634 	res = BUS_ALLOC_RESOURCE(dev->parent, dev, type, rid, start, end,
4635 	    count, flags);
4636 	return (res);
4637 }
4638 
4639 /**
4640  * @brief Wrapper function for BUS_ADJUST_RESOURCE().
4641  *
4642  * This function simply calls the BUS_ADJUST_RESOURCE() method of the
4643  * parent of @p dev.
4644  */
4645 int
bus_adjust_resource(device_t dev,struct resource * r,rman_res_t start,rman_res_t end)4646 bus_adjust_resource(device_t dev, struct resource *r, rman_res_t start,
4647     rman_res_t end)
4648 {
4649 	if (dev->parent == NULL)
4650 		return (EINVAL);
4651 	return (BUS_ADJUST_RESOURCE(dev->parent, dev, r, start, end));
4652 }
4653 
4654 int
bus_adjust_resource_old(device_t dev,int type __unused,struct resource * r,rman_res_t start,rman_res_t end)4655 bus_adjust_resource_old(device_t dev, int type __unused, struct resource *r,
4656     rman_res_t start, rman_res_t end)
4657 {
4658 	return (bus_adjust_resource(dev, r, start, end));
4659 }
4660 
4661 /**
4662  * @brief Wrapper function for BUS_TRANSLATE_RESOURCE().
4663  *
4664  * This function simply calls the BUS_TRANSLATE_RESOURCE() method of the
4665  * parent of @p dev.
4666  */
4667 int
bus_translate_resource(device_t dev,int type,rman_res_t start,rman_res_t * newstart)4668 bus_translate_resource(device_t dev, int type, rman_res_t start,
4669     rman_res_t *newstart)
4670 {
4671 	if (dev->parent == NULL)
4672 		return (EINVAL);
4673 	return (BUS_TRANSLATE_RESOURCE(dev->parent, type, start, newstart));
4674 }
4675 
4676 /**
4677  * @brief Wrapper function for BUS_ACTIVATE_RESOURCE().
4678  *
4679  * This function simply calls the BUS_ACTIVATE_RESOURCE() method of the
4680  * parent of @p dev.
4681  */
4682 int
bus_activate_resource(device_t dev,struct resource * r)4683 bus_activate_resource(device_t dev, struct resource *r)
4684 {
4685 	if (dev->parent == NULL)
4686 		return (EINVAL);
4687 	return (BUS_ACTIVATE_RESOURCE(dev->parent, dev, r));
4688 }
4689 
4690 int
bus_activate_resource_old(device_t dev,int type,int rid,struct resource * r)4691 bus_activate_resource_old(device_t dev, int type, int rid, struct resource *r)
4692 {
4693 	return (bus_activate_resource(dev, r));
4694 }
4695 
4696 /**
4697  * @brief Wrapper function for BUS_DEACTIVATE_RESOURCE().
4698  *
4699  * This function simply calls the BUS_DEACTIVATE_RESOURCE() method of the
4700  * parent of @p dev.
4701  */
4702 int
bus_deactivate_resource(device_t dev,struct resource * r)4703 bus_deactivate_resource(device_t dev, struct resource *r)
4704 {
4705 	if (dev->parent == NULL)
4706 		return (EINVAL);
4707 	return (BUS_DEACTIVATE_RESOURCE(dev->parent, dev, r));
4708 }
4709 
4710 int
bus_deactivate_resource_old(device_t dev,int type,int rid,struct resource * r)4711 bus_deactivate_resource_old(device_t dev, int type, int rid, struct resource *r)
4712 {
4713 	return (bus_deactivate_resource(dev, r));
4714 }
4715 
4716 /**
4717  * @brief Wrapper function for BUS_MAP_RESOURCE().
4718  *
4719  * This function simply calls the BUS_MAP_RESOURCE() method of the
4720  * parent of @p dev.
4721  */
4722 int
bus_map_resource(device_t dev,struct resource * r,struct resource_map_request * args,struct resource_map * map)4723 bus_map_resource(device_t dev, struct resource *r,
4724     struct resource_map_request *args, struct resource_map *map)
4725 {
4726 	if (dev->parent == NULL)
4727 		return (EINVAL);
4728 	return (BUS_MAP_RESOURCE(dev->parent, dev, r, args, map));
4729 }
4730 
4731 int
bus_map_resource_old(device_t dev,int type,struct resource * r,struct resource_map_request * args,struct resource_map * map)4732 bus_map_resource_old(device_t dev, int type, struct resource *r,
4733     struct resource_map_request *args, struct resource_map *map)
4734 {
4735 	return (bus_map_resource(dev, r, args, map));
4736 }
4737 
4738 /**
4739  * @brief Wrapper function for BUS_UNMAP_RESOURCE().
4740  *
4741  * This function simply calls the BUS_UNMAP_RESOURCE() method of the
4742  * parent of @p dev.
4743  */
4744 int
bus_unmap_resource(device_t dev,struct resource * r,struct resource_map * map)4745 bus_unmap_resource(device_t dev, struct resource *r, struct resource_map *map)
4746 {
4747 	if (dev->parent == NULL)
4748 		return (EINVAL);
4749 	return (BUS_UNMAP_RESOURCE(dev->parent, dev, r, map));
4750 }
4751 
4752 int
bus_unmap_resource_old(device_t dev,int type,struct resource * r,struct resource_map * map)4753 bus_unmap_resource_old(device_t dev, int type, struct resource *r,
4754     struct resource_map *map)
4755 {
4756 	return (bus_unmap_resource(dev, r, map));
4757 }
4758 
4759 /**
4760  * @brief Wrapper function for BUS_RELEASE_RESOURCE().
4761  *
4762  * This function simply calls the BUS_RELEASE_RESOURCE() method of the
4763  * parent of @p dev.
4764  */
4765 int
bus_release_resource(device_t dev,struct resource * r)4766 bus_release_resource(device_t dev, struct resource *r)
4767 {
4768 	int rv;
4769 
4770 	if (dev->parent == NULL)
4771 		return (EINVAL);
4772 	rv = BUS_RELEASE_RESOURCE(dev->parent, dev, r);
4773 	return (rv);
4774 }
4775 
4776 int
bus_release_resource_old(device_t dev,int type,int rid,struct resource * r)4777 bus_release_resource_old(device_t dev, int type, int rid, struct resource *r)
4778 {
4779 	return (bus_release_resource(dev, r));
4780 }
4781 
4782 /**
4783  * @brief Wrapper function for BUS_SETUP_INTR().
4784  *
4785  * This function simply calls the BUS_SETUP_INTR() method of the
4786  * parent of @p dev.
4787  */
4788 int
bus_setup_intr(device_t dev,struct resource * r,int flags,driver_filter_t filter,driver_intr_t handler,void * arg,void ** cookiep)4789 bus_setup_intr(device_t dev, struct resource *r, int flags,
4790     driver_filter_t filter, driver_intr_t handler, void *arg, void **cookiep)
4791 {
4792 	int error;
4793 
4794 	if (dev->parent == NULL)
4795 		return (EINVAL);
4796 	error = BUS_SETUP_INTR(dev->parent, dev, r, flags, filter, handler,
4797 	    arg, cookiep);
4798 	if (error != 0)
4799 		return (error);
4800 	if (handler != NULL && !(flags & INTR_MPSAFE))
4801 		device_printf(dev, "[GIANT-LOCKED]\n");
4802 	return (0);
4803 }
4804 
4805 /**
4806  * @brief Wrapper function for BUS_TEARDOWN_INTR().
4807  *
4808  * This function simply calls the BUS_TEARDOWN_INTR() method of the
4809  * parent of @p dev.
4810  */
4811 int
bus_teardown_intr(device_t dev,struct resource * r,void * cookie)4812 bus_teardown_intr(device_t dev, struct resource *r, void *cookie)
4813 {
4814 	if (dev->parent == NULL)
4815 		return (EINVAL);
4816 	return (BUS_TEARDOWN_INTR(dev->parent, dev, r, cookie));
4817 }
4818 
4819 /**
4820  * @brief Wrapper function for BUS_SUSPEND_INTR().
4821  *
4822  * This function simply calls the BUS_SUSPEND_INTR() method of the
4823  * parent of @p dev.
4824  */
4825 int
bus_suspend_intr(device_t dev,struct resource * r)4826 bus_suspend_intr(device_t dev, struct resource *r)
4827 {
4828 	if (dev->parent == NULL)
4829 		return (EINVAL);
4830 	return (BUS_SUSPEND_INTR(dev->parent, dev, r));
4831 }
4832 
4833 /**
4834  * @brief Wrapper function for BUS_RESUME_INTR().
4835  *
4836  * This function simply calls the BUS_RESUME_INTR() method of the
4837  * parent of @p dev.
4838  */
4839 int
bus_resume_intr(device_t dev,struct resource * r)4840 bus_resume_intr(device_t dev, struct resource *r)
4841 {
4842 	if (dev->parent == NULL)
4843 		return (EINVAL);
4844 	return (BUS_RESUME_INTR(dev->parent, dev, r));
4845 }
4846 
4847 /**
4848  * @brief Wrapper function for BUS_BIND_INTR().
4849  *
4850  * This function simply calls the BUS_BIND_INTR() method of the
4851  * parent of @p dev.
4852  */
4853 int
bus_bind_intr(device_t dev,struct resource * r,int cpu)4854 bus_bind_intr(device_t dev, struct resource *r, int cpu)
4855 {
4856 	if (dev->parent == NULL)
4857 		return (EINVAL);
4858 	return (BUS_BIND_INTR(dev->parent, dev, r, cpu));
4859 }
4860 
4861 /**
4862  * @brief Wrapper function for BUS_DESCRIBE_INTR().
4863  *
4864  * This function first formats the requested description into a
4865  * temporary buffer and then calls the BUS_DESCRIBE_INTR() method of
4866  * the parent of @p dev.
4867  */
4868 int
bus_describe_intr(device_t dev,struct resource * irq,void * cookie,const char * fmt,...)4869 bus_describe_intr(device_t dev, struct resource *irq, void *cookie,
4870     const char *fmt, ...)
4871 {
4872 	va_list ap;
4873 	char descr[MAXCOMLEN + 1];
4874 
4875 	if (dev->parent == NULL)
4876 		return (EINVAL);
4877 	va_start(ap, fmt);
4878 	vsnprintf(descr, sizeof(descr), fmt, ap);
4879 	va_end(ap);
4880 	return (BUS_DESCRIBE_INTR(dev->parent, dev, irq, cookie, descr));
4881 }
4882 
4883 /**
4884  * @brief Wrapper function for BUS_SET_RESOURCE().
4885  *
4886  * This function simply calls the BUS_SET_RESOURCE() method of the
4887  * parent of @p dev.
4888  */
4889 int
bus_set_resource(device_t dev,int type,int rid,rman_res_t start,rman_res_t count)4890 bus_set_resource(device_t dev, int type, int rid,
4891     rman_res_t start, rman_res_t count)
4892 {
4893 	return (BUS_SET_RESOURCE(device_get_parent(dev), dev, type, rid,
4894 	    start, count));
4895 }
4896 
4897 /**
4898  * @brief Wrapper function for BUS_GET_RESOURCE().
4899  *
4900  * This function simply calls the BUS_GET_RESOURCE() method of the
4901  * parent of @p dev.
4902  */
4903 int
bus_get_resource(device_t dev,int type,int rid,rman_res_t * startp,rman_res_t * countp)4904 bus_get_resource(device_t dev, int type, int rid,
4905     rman_res_t *startp, rman_res_t *countp)
4906 {
4907 	return (BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
4908 	    startp, countp));
4909 }
4910 
4911 /**
4912  * @brief Wrapper function for BUS_GET_RESOURCE().
4913  *
4914  * This function simply calls the BUS_GET_RESOURCE() method of the
4915  * parent of @p dev and returns the start value.
4916  */
4917 rman_res_t
bus_get_resource_start(device_t dev,int type,int rid)4918 bus_get_resource_start(device_t dev, int type, int rid)
4919 {
4920 	rman_res_t start;
4921 	rman_res_t count;
4922 	int error;
4923 
4924 	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
4925 	    &start, &count);
4926 	if (error)
4927 		return (0);
4928 	return (start);
4929 }
4930 
4931 /**
4932  * @brief Wrapper function for BUS_GET_RESOURCE().
4933  *
4934  * This function simply calls the BUS_GET_RESOURCE() method of the
4935  * parent of @p dev and returns the count value.
4936  */
4937 rman_res_t
bus_get_resource_count(device_t dev,int type,int rid)4938 bus_get_resource_count(device_t dev, int type, int rid)
4939 {
4940 	rman_res_t start;
4941 	rman_res_t count;
4942 	int error;
4943 
4944 	error = BUS_GET_RESOURCE(device_get_parent(dev), dev, type, rid,
4945 	    &start, &count);
4946 	if (error)
4947 		return (0);
4948 	return (count);
4949 }
4950 
4951 /**
4952  * @brief Wrapper function for BUS_DELETE_RESOURCE().
4953  *
4954  * This function simply calls the BUS_DELETE_RESOURCE() method of the
4955  * parent of @p dev.
4956  */
4957 void
bus_delete_resource(device_t dev,int type,int rid)4958 bus_delete_resource(device_t dev, int type, int rid)
4959 {
4960 	BUS_DELETE_RESOURCE(device_get_parent(dev), dev, type, rid);
4961 }
4962 
4963 /**
4964  * @brief Wrapper function for BUS_CHILD_PRESENT().
4965  *
4966  * This function simply calls the BUS_CHILD_PRESENT() method of the
4967  * parent of @p dev.
4968  */
4969 int
bus_child_present(device_t child)4970 bus_child_present(device_t child)
4971 {
4972 	return (BUS_CHILD_PRESENT(device_get_parent(child), child));
4973 }
4974 
4975 /**
4976  * @brief Wrapper function for BUS_CHILD_PNPINFO().
4977  *
4978  * This function simply calls the BUS_CHILD_PNPINFO() method of the parent of @p
4979  * dev.
4980  */
4981 int
bus_child_pnpinfo(device_t child,struct sbuf * sb)4982 bus_child_pnpinfo(device_t child, struct sbuf *sb)
4983 {
4984 	device_t parent;
4985 
4986 	parent = device_get_parent(child);
4987 	if (parent == NULL)
4988 		return (0);
4989 	return (BUS_CHILD_PNPINFO(parent, child, sb));
4990 }
4991 
4992 /**
4993  * @brief Generic implementation that does nothing for bus_child_pnpinfo
4994  *
4995  * This function has the right signature and returns 0 since the sbuf is passed
4996  * to us to append to.
4997  */
4998 int
bus_generic_child_pnpinfo(device_t dev,device_t child,struct sbuf * sb)4999 bus_generic_child_pnpinfo(device_t dev, device_t child, struct sbuf *sb)
5000 {
5001 	return (0);
5002 }
5003 
5004 /**
5005  * @brief Wrapper function for BUS_CHILD_LOCATION().
5006  *
5007  * This function simply calls the BUS_CHILD_LOCATION() method of the parent of
5008  * @p dev.
5009  */
5010 int
bus_child_location(device_t child,struct sbuf * sb)5011 bus_child_location(device_t child, struct sbuf *sb)
5012 {
5013 	device_t parent;
5014 
5015 	parent = device_get_parent(child);
5016 	if (parent == NULL)
5017 		return (0);
5018 	return (BUS_CHILD_LOCATION(parent, child, sb));
5019 }
5020 
5021 /**
5022  * @brief Generic implementation that does nothing for bus_child_location
5023  *
5024  * This function has the right signature and returns 0 since the sbuf is passed
5025  * to us to append to.
5026  */
5027 int
bus_generic_child_location(device_t dev,device_t child,struct sbuf * sb)5028 bus_generic_child_location(device_t dev, device_t child, struct sbuf *sb)
5029 {
5030 	return (0);
5031 }
5032 
5033 /**
5034  * @brief Wrapper function for BUS_GET_CPUS().
5035  *
5036  * This function simply calls the BUS_GET_CPUS() method of the
5037  * parent of @p dev.
5038  */
5039 int
bus_get_cpus(device_t dev,enum cpu_sets op,size_t setsize,cpuset_t * cpuset)5040 bus_get_cpus(device_t dev, enum cpu_sets op, size_t setsize, cpuset_t *cpuset)
5041 {
5042 	device_t parent;
5043 
5044 	parent = device_get_parent(dev);
5045 	if (parent == NULL)
5046 		return (EINVAL);
5047 	return (BUS_GET_CPUS(parent, dev, op, setsize, cpuset));
5048 }
5049 
5050 /**
5051  * @brief Wrapper function for BUS_GET_DMA_TAG().
5052  *
5053  * This function simply calls the BUS_GET_DMA_TAG() method of the
5054  * parent of @p dev.
5055  */
5056 bus_dma_tag_t
bus_get_dma_tag(device_t dev)5057 bus_get_dma_tag(device_t dev)
5058 {
5059 	device_t parent;
5060 
5061 	parent = device_get_parent(dev);
5062 	if (parent == NULL)
5063 		return (NULL);
5064 	return (BUS_GET_DMA_TAG(parent, dev));
5065 }
5066 
5067 /**
5068  * @brief Wrapper function for BUS_GET_BUS_TAG().
5069  *
5070  * This function simply calls the BUS_GET_BUS_TAG() method of the
5071  * parent of @p dev.
5072  */
5073 bus_space_tag_t
bus_get_bus_tag(device_t dev)5074 bus_get_bus_tag(device_t dev)
5075 {
5076 	device_t parent;
5077 
5078 	parent = device_get_parent(dev);
5079 	if (parent == NULL)
5080 		return ((bus_space_tag_t)0);
5081 	return (BUS_GET_BUS_TAG(parent, dev));
5082 }
5083 
5084 /**
5085  * @brief Wrapper function for BUS_GET_DOMAIN().
5086  *
5087  * This function simply calls the BUS_GET_DOMAIN() method of the
5088  * parent of @p dev.
5089  */
5090 int
bus_get_domain(device_t dev,int * domain)5091 bus_get_domain(device_t dev, int *domain)
5092 {
5093 	return (BUS_GET_DOMAIN(device_get_parent(dev), dev, domain));
5094 }
5095 
5096 /* Resume all devices and then notify userland that we're up again. */
5097 static int
root_resume(device_t dev)5098 root_resume(device_t dev)
5099 {
5100 	int error;
5101 
5102 	error = bus_generic_resume(dev);
5103 	if (error == 0) {
5104 		devctl_notify("kernel", "power", "resume", NULL);
5105 	}
5106 	return (error);
5107 }
5108 
5109 static int
root_print_child(device_t dev,device_t child)5110 root_print_child(device_t dev, device_t child)
5111 {
5112 	int	retval = 0;
5113 
5114 	retval += bus_print_child_header(dev, child);
5115 	retval += printf("\n");
5116 
5117 	return (retval);
5118 }
5119 
5120 static int
root_setup_intr(device_t dev,device_t child,struct resource * irq,int flags,driver_filter_t * filter,driver_intr_t * intr,void * arg,void ** cookiep)5121 root_setup_intr(device_t dev, device_t child, struct resource *irq, int flags,
5122     driver_filter_t *filter, driver_intr_t *intr, void *arg, void **cookiep)
5123 {
5124 	/*
5125 	 * If an interrupt mapping gets to here something bad has happened.
5126 	 */
5127 	panic("root_setup_intr");
5128 }
5129 
5130 /*
5131  * If we get here, assume that the device is permanent and really is
5132  * present in the system.  Removable bus drivers are expected to intercept
5133  * this call long before it gets here.  We return -1 so that drivers that
5134  * really care can check vs -1 or some ERRNO returned higher in the food
5135  * chain.
5136  */
5137 static int
root_child_present(device_t dev,device_t child)5138 root_child_present(device_t dev, device_t child)
5139 {
5140 	return (-1);
5141 }
5142 
5143 static int
root_get_cpus(device_t dev,device_t child,enum cpu_sets op,size_t setsize,cpuset_t * cpuset)5144 root_get_cpus(device_t dev, device_t child, enum cpu_sets op, size_t setsize,
5145     cpuset_t *cpuset)
5146 {
5147 	switch (op) {
5148 	case INTR_CPUS:
5149 		/* Default to returning the set of all CPUs. */
5150 		if (setsize != sizeof(cpuset_t))
5151 			return (EINVAL);
5152 		*cpuset = all_cpus;
5153 		return (0);
5154 	default:
5155 		return (EINVAL);
5156 	}
5157 }
5158 
5159 static kobj_method_t root_methods[] = {
5160 	/* Device interface */
5161 	KOBJMETHOD(device_shutdown,	bus_generic_shutdown),
5162 	KOBJMETHOD(device_suspend,	bus_generic_suspend),
5163 	KOBJMETHOD(device_resume,	root_resume),
5164 
5165 	/* Bus interface */
5166 	KOBJMETHOD(bus_print_child,	root_print_child),
5167 	KOBJMETHOD(bus_read_ivar,	bus_generic_read_ivar),
5168 	KOBJMETHOD(bus_write_ivar,	bus_generic_write_ivar),
5169 	KOBJMETHOD(bus_setup_intr,	root_setup_intr),
5170 	KOBJMETHOD(bus_child_present,	root_child_present),
5171 	KOBJMETHOD(bus_get_cpus,	root_get_cpus),
5172 
5173 	KOBJMETHOD_END
5174 };
5175 
5176 static driver_t root_driver = {
5177 	"root",
5178 	root_methods,
5179 	1,			/* no softc */
5180 };
5181 
5182 device_t	root_bus;
5183 devclass_t	root_devclass;
5184 
5185 static int
root_bus_module_handler(module_t mod,int what,void * arg)5186 root_bus_module_handler(module_t mod, int what, void* arg)
5187 {
5188 	switch (what) {
5189 	case MOD_LOAD:
5190 		TAILQ_INIT(&bus_data_devices);
5191 		kobj_class_compile((kobj_class_t) &root_driver);
5192 		root_bus = make_device(NULL, "root", 0);
5193 		root_bus->desc = "System root bus";
5194 		kobj_init((kobj_t) root_bus, (kobj_class_t) &root_driver);
5195 		root_bus->driver = &root_driver;
5196 		root_bus->state = DS_ATTACHED;
5197 		root_devclass = devclass_find_internal("root", NULL, FALSE);
5198 		devctl2_init();
5199 		return (0);
5200 
5201 	case MOD_SHUTDOWN:
5202 		device_shutdown(root_bus);
5203 		return (0);
5204 	default:
5205 		return (EOPNOTSUPP);
5206 	}
5207 
5208 	return (0);
5209 }
5210 
5211 static moduledata_t root_bus_mod = {
5212 	"rootbus",
5213 	root_bus_module_handler,
5214 	NULL
5215 };
5216 DECLARE_MODULE(rootbus, root_bus_mod, SI_SUB_DRIVERS, SI_ORDER_FIRST);
5217 
5218 /**
5219  * @brief Automatically configure devices
5220  *
5221  * This function begins the autoconfiguration process by calling
5222  * device_probe_and_attach() for each child of the @c root0 device.
5223  */
5224 void
root_bus_configure(void)5225 root_bus_configure(void)
5226 {
5227 	PDEBUG(("."));
5228 
5229 	/* Eventually this will be split up, but this is sufficient for now. */
5230 	bus_set_pass(BUS_PASS_DEFAULT);
5231 }
5232 
5233 /**
5234  * @brief Module handler for registering device drivers
5235  *
5236  * This module handler is used to automatically register device
5237  * drivers when modules are loaded. If @p what is MOD_LOAD, it calls
5238  * devclass_add_driver() for the driver described by the
5239  * driver_module_data structure pointed to by @p arg
5240  */
5241 int
driver_module_handler(module_t mod,int what,void * arg)5242 driver_module_handler(module_t mod, int what, void *arg)
5243 {
5244 	struct driver_module_data *dmd;
5245 	devclass_t bus_devclass;
5246 	kobj_class_t driver;
5247 	int error, pass;
5248 
5249 	dmd = (struct driver_module_data *)arg;
5250 	bus_devclass = devclass_find_internal(dmd->dmd_busname, NULL, TRUE);
5251 	error = 0;
5252 
5253 	switch (what) {
5254 	case MOD_LOAD:
5255 		if (dmd->dmd_chainevh)
5256 			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
5257 
5258 		pass = dmd->dmd_pass;
5259 		driver = dmd->dmd_driver;
5260 		PDEBUG(("Loading module: driver %s on bus %s (pass %d)",
5261 		    DRIVERNAME(driver), dmd->dmd_busname, pass));
5262 		error = devclass_add_driver(bus_devclass, driver, pass,
5263 		    dmd->dmd_devclass);
5264 		break;
5265 
5266 	case MOD_UNLOAD:
5267 		PDEBUG(("Unloading module: driver %s from bus %s",
5268 		    DRIVERNAME(dmd->dmd_driver),
5269 		    dmd->dmd_busname));
5270 		error = devclass_delete_driver(bus_devclass,
5271 		    dmd->dmd_driver);
5272 
5273 		if (!error && dmd->dmd_chainevh)
5274 			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
5275 		break;
5276 	case MOD_QUIESCE:
5277 		PDEBUG(("Quiesce module: driver %s from bus %s",
5278 		    DRIVERNAME(dmd->dmd_driver),
5279 		    dmd->dmd_busname));
5280 		error = devclass_quiesce_driver(bus_devclass,
5281 		    dmd->dmd_driver);
5282 
5283 		if (!error && dmd->dmd_chainevh)
5284 			error = dmd->dmd_chainevh(mod,what,dmd->dmd_chainarg);
5285 		break;
5286 	default:
5287 		error = EOPNOTSUPP;
5288 		break;
5289 	}
5290 
5291 	return (error);
5292 }
5293 
5294 /**
5295  * @brief Enumerate all hinted devices for this bus.
5296  *
5297  * Walks through the hints for this bus and calls the bus_hinted_child
5298  * routine for each one it fines.  It searches first for the specific
5299  * bus that's being probed for hinted children (eg isa0), and then for
5300  * generic children (eg isa).
5301  *
5302  * @param	dev	bus device to enumerate
5303  */
5304 void
bus_enumerate_hinted_children(device_t bus)5305 bus_enumerate_hinted_children(device_t bus)
5306 {
5307 	int i;
5308 	const char *dname, *busname;
5309 	int dunit;
5310 
5311 	/*
5312 	 * enumerate all devices on the specific bus
5313 	 */
5314 	busname = device_get_nameunit(bus);
5315 	i = 0;
5316 	while (resource_find_match(&i, &dname, &dunit, "at", busname) == 0)
5317 		BUS_HINTED_CHILD(bus, dname, dunit);
5318 
5319 	/*
5320 	 * and all the generic ones.
5321 	 */
5322 	busname = device_get_name(bus);
5323 	i = 0;
5324 	while (resource_find_match(&i, &dname, &dunit, "at", busname) == 0)
5325 		BUS_HINTED_CHILD(bus, dname, dunit);
5326 }
5327 
5328 #ifdef BUS_DEBUG
5329 
5330 /* the _short versions avoid iteration by not calling anything that prints
5331  * more than oneliners. I love oneliners.
5332  */
5333 
5334 static void
print_device_short(device_t dev,int indent)5335 print_device_short(device_t dev, int indent)
5336 {
5337 	if (!dev)
5338 		return;
5339 
5340 	indentprintf(("device %d: <%s> %sparent,%schildren,%s%s%s%s%s,%sivars,%ssoftc,busy=%d\n",
5341 	    dev->unit, dev->desc,
5342 	    (dev->parent? "":"no "),
5343 	    (TAILQ_EMPTY(&dev->children)? "no ":""),
5344 	    (dev->flags&DF_ENABLED? "enabled,":"disabled,"),
5345 	    (dev->flags&DF_FIXEDCLASS? "fixed,":""),
5346 	    (dev->flags&DF_WILDCARD? "wildcard,":""),
5347 	    (dev->flags&DF_DESCMALLOCED? "descmalloced,":""),
5348 	    (dev->flags&DF_SUSPENDED? "suspended,":""),
5349 	    (dev->ivars? "":"no "),
5350 	    (dev->softc? "":"no "),
5351 	    dev->busy));
5352 }
5353 
5354 static void
print_device(device_t dev,int indent)5355 print_device(device_t dev, int indent)
5356 {
5357 	if (!dev)
5358 		return;
5359 
5360 	print_device_short(dev, indent);
5361 
5362 	indentprintf(("Parent:\n"));
5363 	print_device_short(dev->parent, indent+1);
5364 	indentprintf(("Driver:\n"));
5365 	print_driver_short(dev->driver, indent+1);
5366 	indentprintf(("Devclass:\n"));
5367 	print_devclass_short(dev->devclass, indent+1);
5368 }
5369 
5370 void
print_device_tree_short(device_t dev,int indent)5371 print_device_tree_short(device_t dev, int indent)
5372 /* print the device and all its children (indented) */
5373 {
5374 	device_t child;
5375 
5376 	if (!dev)
5377 		return;
5378 
5379 	print_device_short(dev, indent);
5380 
5381 	TAILQ_FOREACH(child, &dev->children, link) {
5382 		print_device_tree_short(child, indent+1);
5383 	}
5384 }
5385 
5386 void
print_device_tree(device_t dev,int indent)5387 print_device_tree(device_t dev, int indent)
5388 /* print the device and all its children (indented) */
5389 {
5390 	device_t child;
5391 
5392 	if (!dev)
5393 		return;
5394 
5395 	print_device(dev, indent);
5396 
5397 	TAILQ_FOREACH(child, &dev->children, link) {
5398 		print_device_tree(child, indent+1);
5399 	}
5400 }
5401 
5402 static void
print_driver_short(driver_t * driver,int indent)5403 print_driver_short(driver_t *driver, int indent)
5404 {
5405 	if (!driver)
5406 		return;
5407 
5408 	indentprintf(("driver %s: softc size = %zd\n",
5409 	    driver->name, driver->size));
5410 }
5411 
5412 static void
print_driver(driver_t * driver,int indent)5413 print_driver(driver_t *driver, int indent)
5414 {
5415 	if (!driver)
5416 		return;
5417 
5418 	print_driver_short(driver, indent);
5419 }
5420 
5421 static void
print_driver_list(driver_list_t drivers,int indent)5422 print_driver_list(driver_list_t drivers, int indent)
5423 {
5424 	driverlink_t driver;
5425 
5426 	TAILQ_FOREACH(driver, &drivers, link) {
5427 		print_driver(driver->driver, indent);
5428 	}
5429 }
5430 
5431 static void
print_devclass_short(devclass_t dc,int indent)5432 print_devclass_short(devclass_t dc, int indent)
5433 {
5434 	if ( !dc )
5435 		return;
5436 
5437 	indentprintf(("devclass %s: max units = %d\n", dc->name, dc->maxunit));
5438 }
5439 
5440 static void
print_devclass(devclass_t dc,int indent)5441 print_devclass(devclass_t dc, int indent)
5442 {
5443 	int i;
5444 
5445 	if ( !dc )
5446 		return;
5447 
5448 	print_devclass_short(dc, indent);
5449 	indentprintf(("Drivers:\n"));
5450 	print_driver_list(dc->drivers, indent+1);
5451 
5452 	indentprintf(("Devices:\n"));
5453 	for (i = 0; i < dc->maxunit; i++)
5454 		if (dc->devices[i])
5455 			print_device(dc->devices[i], indent+1);
5456 }
5457 
5458 void
print_devclass_list_short(void)5459 print_devclass_list_short(void)
5460 {
5461 	devclass_t dc;
5462 
5463 	printf("Short listing of devclasses, drivers & devices:\n");
5464 	TAILQ_FOREACH(dc, &devclasses, link) {
5465 		print_devclass_short(dc, 0);
5466 	}
5467 }
5468 
5469 void
print_devclass_list(void)5470 print_devclass_list(void)
5471 {
5472 	devclass_t dc;
5473 
5474 	printf("Full listing of devclasses, drivers & devices:\n");
5475 	TAILQ_FOREACH(dc, &devclasses, link) {
5476 		print_devclass(dc, 0);
5477 	}
5478 }
5479 
5480 #endif
5481 
5482 /*
5483  * User-space access to the device tree.
5484  *
5485  * We implement a small set of nodes:
5486  *
5487  * hw.bus			Single integer read method to obtain the
5488  *				current generation count.
5489  * hw.bus.devices		Reads the entire device tree in flat space.
5490  * hw.bus.rman			Resource manager interface
5491  *
5492  * We might like to add the ability to scan devclasses and/or drivers to
5493  * determine what else is currently loaded/available.
5494  */
5495 
5496 static int
sysctl_bus_info(SYSCTL_HANDLER_ARGS)5497 sysctl_bus_info(SYSCTL_HANDLER_ARGS)
5498 {
5499 	struct u_businfo	ubus;
5500 
5501 	ubus.ub_version = BUS_USER_VERSION;
5502 	ubus.ub_generation = bus_data_generation;
5503 
5504 	return (SYSCTL_OUT(req, &ubus, sizeof(ubus)));
5505 }
5506 SYSCTL_PROC(_hw_bus, OID_AUTO, info, CTLTYPE_STRUCT | CTLFLAG_RD |
5507     CTLFLAG_MPSAFE, NULL, 0, sysctl_bus_info, "S,u_businfo",
5508     "bus-related data");
5509 
5510 static int
sysctl_devices(SYSCTL_HANDLER_ARGS)5511 sysctl_devices(SYSCTL_HANDLER_ARGS)
5512 {
5513 	struct sbuf		sb;
5514 	int			*name = (int *)arg1;
5515 	u_int			namelen = arg2;
5516 	int			index;
5517 	device_t		dev;
5518 	struct u_device		*udev;
5519 	int			error;
5520 
5521 	if (namelen != 2)
5522 		return (EINVAL);
5523 
5524 	if (bus_data_generation_check(name[0]))
5525 		return (EINVAL);
5526 
5527 	index = name[1];
5528 
5529 	/*
5530 	 * Scan the list of devices, looking for the requested index.
5531 	 */
5532 	TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
5533 		if (index-- == 0)
5534 			break;
5535 	}
5536 	if (dev == NULL)
5537 		return (ENOENT);
5538 
5539 	/*
5540 	 * Populate the return item, careful not to overflow the buffer.
5541 	 */
5542 	udev = malloc(sizeof(*udev), M_BUS, M_WAITOK | M_ZERO);
5543 	udev->dv_handle = (uintptr_t)dev;
5544 	udev->dv_parent = (uintptr_t)dev->parent;
5545 	udev->dv_devflags = dev->devflags;
5546 	udev->dv_flags = dev->flags;
5547 	udev->dv_state = dev->state;
5548 	sbuf_new(&sb, udev->dv_fields, sizeof(udev->dv_fields), SBUF_FIXEDLEN);
5549 	if (dev->nameunit != NULL)
5550 		sbuf_cat(&sb, dev->nameunit);
5551 	sbuf_putc(&sb, '\0');
5552 	if (dev->desc != NULL)
5553 		sbuf_cat(&sb, dev->desc);
5554 	sbuf_putc(&sb, '\0');
5555 	if (dev->driver != NULL)
5556 		sbuf_cat(&sb, dev->driver->name);
5557 	sbuf_putc(&sb, '\0');
5558 	bus_child_pnpinfo(dev, &sb);
5559 	sbuf_putc(&sb, '\0');
5560 	bus_child_location(dev, &sb);
5561 	sbuf_putc(&sb, '\0');
5562 	error = sbuf_finish(&sb);
5563 	if (error == 0)
5564 		error = SYSCTL_OUT(req, udev, sizeof(*udev));
5565 	sbuf_delete(&sb);
5566 	free(udev, M_BUS);
5567 	return (error);
5568 }
5569 
5570 SYSCTL_NODE(_hw_bus, OID_AUTO, devices,
5571     CTLFLAG_RD | CTLFLAG_NEEDGIANT, sysctl_devices,
5572     "system device tree");
5573 
5574 int
bus_data_generation_check(int generation)5575 bus_data_generation_check(int generation)
5576 {
5577 	if (generation != bus_data_generation)
5578 		return (1);
5579 
5580 	/* XXX generate optimised lists here? */
5581 	return (0);
5582 }
5583 
5584 void
bus_data_generation_update(void)5585 bus_data_generation_update(void)
5586 {
5587 	atomic_add_int(&bus_data_generation, 1);
5588 }
5589 
5590 int
bus_free_resource(device_t dev,int type,struct resource * r)5591 bus_free_resource(device_t dev, int type, struct resource *r)
5592 {
5593 	if (r == NULL)
5594 		return (0);
5595 	return (bus_release_resource(dev, type, rman_get_rid(r), r));
5596 }
5597 
5598 device_t
device_lookup_by_name(const char * name)5599 device_lookup_by_name(const char *name)
5600 {
5601 	device_t dev;
5602 
5603 	TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
5604 		if (dev->nameunit != NULL && strcmp(dev->nameunit, name) == 0)
5605 			return (dev);
5606 	}
5607 	return (NULL);
5608 }
5609 
5610 /*
5611  * /dev/devctl2 implementation.  The existing /dev/devctl device has
5612  * implicit semantics on open, so it could not be reused for this.
5613  * Another option would be to call this /dev/bus?
5614  */
5615 static int
find_device(struct devreq * req,device_t * devp)5616 find_device(struct devreq *req, device_t *devp)
5617 {
5618 	device_t dev;
5619 
5620 	/*
5621 	 * First, ensure that the name is nul terminated.
5622 	 */
5623 	if (memchr(req->dr_name, '\0', sizeof(req->dr_name)) == NULL)
5624 		return (EINVAL);
5625 
5626 	/*
5627 	 * Second, try to find an attached device whose name matches
5628 	 * 'name'.
5629 	 */
5630 	dev = device_lookup_by_name(req->dr_name);
5631 	if (dev != NULL) {
5632 		*devp = dev;
5633 		return (0);
5634 	}
5635 
5636 	/* Finally, give device enumerators a chance. */
5637 	dev = NULL;
5638 	EVENTHANDLER_DIRECT_INVOKE(dev_lookup, req->dr_name, &dev);
5639 	if (dev == NULL)
5640 		return (ENOENT);
5641 	*devp = dev;
5642 	return (0);
5643 }
5644 
5645 static bool
driver_exists(device_t bus,const char * driver)5646 driver_exists(device_t bus, const char *driver)
5647 {
5648 	devclass_t dc;
5649 
5650 	for (dc = bus->devclass; dc != NULL; dc = dc->parent) {
5651 		if (devclass_find_driver_internal(dc, driver) != NULL)
5652 			return (true);
5653 	}
5654 	return (false);
5655 }
5656 
5657 static void
device_gen_nomatch(device_t dev)5658 device_gen_nomatch(device_t dev)
5659 {
5660 	device_t child;
5661 
5662 	if (dev->flags & DF_NEEDNOMATCH &&
5663 	    dev->state == DS_NOTPRESENT) {
5664 		device_handle_nomatch(dev);
5665 	}
5666 	dev->flags &= ~DF_NEEDNOMATCH;
5667 	TAILQ_FOREACH(child, &dev->children, link) {
5668 		device_gen_nomatch(child);
5669 	}
5670 }
5671 
5672 static void
device_do_deferred_actions(void)5673 device_do_deferred_actions(void)
5674 {
5675 	devclass_t dc;
5676 	driverlink_t dl;
5677 
5678 	/*
5679 	 * Walk through the devclasses to find all the drivers we've tagged as
5680 	 * deferred during the freeze and call the driver added routines. They
5681 	 * have already been added to the lists in the background, so the driver
5682 	 * added routines that trigger a probe will have all the right bidders
5683 	 * for the probe auction.
5684 	 */
5685 	TAILQ_FOREACH(dc, &devclasses, link) {
5686 		TAILQ_FOREACH(dl, &dc->drivers, link) {
5687 			if (dl->flags & DL_DEFERRED_PROBE) {
5688 				devclass_driver_added(dc, dl->driver);
5689 				dl->flags &= ~DL_DEFERRED_PROBE;
5690 			}
5691 		}
5692 	}
5693 
5694 	/*
5695 	 * We also defer no-match events during a freeze. Walk the tree and
5696 	 * generate all the pent-up events that are still relevant.
5697 	 */
5698 	device_gen_nomatch(root_bus);
5699 	bus_data_generation_update();
5700 }
5701 
5702 static int
device_get_path(device_t dev,const char * locator,struct sbuf * sb)5703 device_get_path(device_t dev, const char *locator, struct sbuf *sb)
5704 {
5705 	device_t parent;
5706 	int error;
5707 
5708 	KASSERT(sb != NULL, ("sb is NULL"));
5709 	parent = device_get_parent(dev);
5710 	if (parent == NULL) {
5711 		error = sbuf_putc(sb, '/');
5712 	} else {
5713 		error = BUS_GET_DEVICE_PATH(parent, dev, locator, sb);
5714 		if (error == 0) {
5715 			error = sbuf_error(sb);
5716 			if (error == 0 && sbuf_len(sb) <= 1)
5717 				error = EIO;
5718 		}
5719 	}
5720 	sbuf_finish(sb);
5721 	return (error);
5722 }
5723 
5724 static int
devctl2_ioctl(struct cdev * cdev,u_long cmd,caddr_t data,int fflag,struct thread * td)5725 devctl2_ioctl(struct cdev *cdev, u_long cmd, caddr_t data, int fflag,
5726     struct thread *td)
5727 {
5728 	struct devreq *req;
5729 	device_t dev;
5730 	int error, old;
5731 
5732 	/* Locate the device to control. */
5733 	bus_topo_lock();
5734 	req = (struct devreq *)data;
5735 	switch (cmd) {
5736 	case DEV_ATTACH:
5737 	case DEV_DETACH:
5738 	case DEV_ENABLE:
5739 	case DEV_DISABLE:
5740 	case DEV_SUSPEND:
5741 	case DEV_RESUME:
5742 	case DEV_SET_DRIVER:
5743 	case DEV_CLEAR_DRIVER:
5744 	case DEV_RESCAN:
5745 	case DEV_DELETE:
5746 	case DEV_RESET:
5747 		error = priv_check(td, PRIV_DRIVER);
5748 		if (error == 0)
5749 			error = find_device(req, &dev);
5750 		break;
5751 	case DEV_FREEZE:
5752 	case DEV_THAW:
5753 		error = priv_check(td, PRIV_DRIVER);
5754 		break;
5755 	case DEV_GET_PATH:
5756 		error = find_device(req, &dev);
5757 		break;
5758 	default:
5759 		error = ENOTTY;
5760 		break;
5761 	}
5762 	if (error) {
5763 		bus_topo_unlock();
5764 		return (error);
5765 	}
5766 
5767 	/* Perform the requested operation. */
5768 	switch (cmd) {
5769 	case DEV_ATTACH:
5770 		if (device_is_attached(dev))
5771 			error = EBUSY;
5772 		else if (!device_is_enabled(dev))
5773 			error = ENXIO;
5774 		else
5775 			error = device_probe_and_attach(dev);
5776 		break;
5777 	case DEV_DETACH:
5778 		if (!device_is_attached(dev)) {
5779 			error = ENXIO;
5780 			break;
5781 		}
5782 		if (!(req->dr_flags & DEVF_FORCE_DETACH)) {
5783 			error = device_quiesce(dev);
5784 			if (error)
5785 				break;
5786 		}
5787 		error = device_detach(dev);
5788 		break;
5789 	case DEV_ENABLE:
5790 		if (device_is_enabled(dev)) {
5791 			error = EBUSY;
5792 			break;
5793 		}
5794 
5795 		/*
5796 		 * If the device has been probed but not attached (e.g.
5797 		 * when it has been disabled by a loader hint), just
5798 		 * attach the device rather than doing a full probe.
5799 		 */
5800 		device_enable(dev);
5801 		if (dev->devclass != NULL) {
5802 			/*
5803 			 * If the device was disabled via a hint, clear
5804 			 * the hint.
5805 			 */
5806 			if (resource_disabled(dev->devclass->name, dev->unit))
5807 				resource_unset_value(dev->devclass->name,
5808 				    dev->unit, "disabled");
5809 
5810 			/* Allow any drivers to rebid. */
5811 			if (!(dev->flags & DF_FIXEDCLASS))
5812 				devclass_delete_device(dev->devclass, dev);
5813 		}
5814 		error = device_probe_and_attach(dev);
5815 		break;
5816 	case DEV_DISABLE:
5817 		if (!device_is_enabled(dev)) {
5818 			error = ENXIO;
5819 			break;
5820 		}
5821 
5822 		if (!(req->dr_flags & DEVF_FORCE_DETACH)) {
5823 			error = device_quiesce(dev);
5824 			if (error)
5825 				break;
5826 		}
5827 
5828 		/*
5829 		 * Force DF_FIXEDCLASS on around detach to preserve
5830 		 * the existing name.
5831 		 */
5832 		old = dev->flags;
5833 		dev->flags |= DF_FIXEDCLASS;
5834 		error = device_detach(dev);
5835 		if (!(old & DF_FIXEDCLASS))
5836 			dev->flags &= ~DF_FIXEDCLASS;
5837 		if (error == 0)
5838 			device_disable(dev);
5839 		break;
5840 	case DEV_SUSPEND:
5841 		if (device_is_suspended(dev)) {
5842 			error = EBUSY;
5843 			break;
5844 		}
5845 		if (device_get_parent(dev) == NULL) {
5846 			error = EINVAL;
5847 			break;
5848 		}
5849 		error = BUS_SUSPEND_CHILD(device_get_parent(dev), dev);
5850 		break;
5851 	case DEV_RESUME:
5852 		if (!device_is_suspended(dev)) {
5853 			error = EINVAL;
5854 			break;
5855 		}
5856 		if (device_get_parent(dev) == NULL) {
5857 			error = EINVAL;
5858 			break;
5859 		}
5860 		error = BUS_RESUME_CHILD(device_get_parent(dev), dev);
5861 		break;
5862 	case DEV_SET_DRIVER: {
5863 		devclass_t dc;
5864 		char driver[128];
5865 
5866 		error = copyinstr(req->dr_data, driver, sizeof(driver), NULL);
5867 		if (error)
5868 			break;
5869 		if (driver[0] == '\0') {
5870 			error = EINVAL;
5871 			break;
5872 		}
5873 		if (dev->devclass != NULL &&
5874 		    strcmp(driver, dev->devclass->name) == 0)
5875 			/* XXX: Could possibly force DF_FIXEDCLASS on? */
5876 			break;
5877 
5878 		/*
5879 		 * Scan drivers for this device's bus looking for at
5880 		 * least one matching driver.
5881 		 */
5882 		if (dev->parent == NULL) {
5883 			error = EINVAL;
5884 			break;
5885 		}
5886 		if (!driver_exists(dev->parent, driver)) {
5887 			error = ENOENT;
5888 			break;
5889 		}
5890 		dc = devclass_create(driver);
5891 		if (dc == NULL) {
5892 			error = ENOMEM;
5893 			break;
5894 		}
5895 
5896 		/* Detach device if necessary. */
5897 		if (device_is_attached(dev)) {
5898 			if (req->dr_flags & DEVF_SET_DRIVER_DETACH)
5899 				error = device_detach(dev);
5900 			else
5901 				error = EBUSY;
5902 			if (error)
5903 				break;
5904 		}
5905 
5906 		/* Clear any previously-fixed device class and unit. */
5907 		if (dev->flags & DF_FIXEDCLASS)
5908 			devclass_delete_device(dev->devclass, dev);
5909 		dev->flags |= DF_WILDCARD;
5910 		dev->unit = DEVICE_UNIT_ANY;
5911 
5912 		/* Force the new device class. */
5913 		error = devclass_add_device(dc, dev);
5914 		if (error)
5915 			break;
5916 		dev->flags |= DF_FIXEDCLASS;
5917 		error = device_probe_and_attach(dev);
5918 		break;
5919 	}
5920 	case DEV_CLEAR_DRIVER:
5921 		if (!(dev->flags & DF_FIXEDCLASS)) {
5922 			error = 0;
5923 			break;
5924 		}
5925 		if (device_is_attached(dev)) {
5926 			if (req->dr_flags & DEVF_CLEAR_DRIVER_DETACH)
5927 				error = device_detach(dev);
5928 			else
5929 				error = EBUSY;
5930 			if (error)
5931 				break;
5932 		}
5933 
5934 		dev->flags &= ~DF_FIXEDCLASS;
5935 		dev->flags |= DF_WILDCARD;
5936 		devclass_delete_device(dev->devclass, dev);
5937 		error = device_probe_and_attach(dev);
5938 		break;
5939 	case DEV_RESCAN:
5940 		if (!device_is_attached(dev)) {
5941 			error = ENXIO;
5942 			break;
5943 		}
5944 		error = BUS_RESCAN(dev);
5945 		break;
5946 	case DEV_DELETE: {
5947 		device_t parent;
5948 
5949 		parent = device_get_parent(dev);
5950 		if (parent == NULL) {
5951 			error = EINVAL;
5952 			break;
5953 		}
5954 		if (!(req->dr_flags & DEVF_FORCE_DELETE)) {
5955 			if (bus_child_present(dev) != 0) {
5956 				error = EBUSY;
5957 				break;
5958 			}
5959 		}
5960 
5961 		error = device_delete_child(parent, dev);
5962 		break;
5963 	}
5964 	case DEV_FREEZE:
5965 		if (device_frozen)
5966 			error = EBUSY;
5967 		else
5968 			device_frozen = true;
5969 		break;
5970 	case DEV_THAW:
5971 		if (!device_frozen)
5972 			error = EBUSY;
5973 		else {
5974 			device_do_deferred_actions();
5975 			device_frozen = false;
5976 		}
5977 		break;
5978 	case DEV_RESET:
5979 		if ((req->dr_flags & ~(DEVF_RESET_DETACH)) != 0) {
5980 			error = EINVAL;
5981 			break;
5982 		}
5983 		if (device_get_parent(dev) == NULL) {
5984 			error = EINVAL;
5985 			break;
5986 		}
5987 		error = BUS_RESET_CHILD(device_get_parent(dev), dev,
5988 		    req->dr_flags);
5989 		break;
5990 	case DEV_GET_PATH: {
5991 		struct sbuf *sb;
5992 		char locator[64];
5993 		ssize_t len;
5994 
5995 		error = copyinstr(req->dr_buffer.buffer, locator,
5996 		    sizeof(locator), NULL);
5997 		if (error != 0)
5998 			break;
5999 		sb = sbuf_new(NULL, NULL, 0, SBUF_AUTOEXTEND |
6000 		    SBUF_INCLUDENUL /* | SBUF_WAITOK */);
6001 		error = device_get_path(dev, locator, sb);
6002 		if (error == 0) {
6003 			len = sbuf_len(sb);
6004 			if (req->dr_buffer.length < len) {
6005 				error = ENAMETOOLONG;
6006 			} else {
6007 				error = copyout(sbuf_data(sb),
6008 				    req->dr_buffer.buffer, len);
6009 			}
6010 			req->dr_buffer.length = len;
6011 		}
6012 		sbuf_delete(sb);
6013 		break;
6014 	}
6015 	}
6016 	bus_topo_unlock();
6017 	return (error);
6018 }
6019 
6020 static struct cdevsw devctl2_cdevsw = {
6021 	.d_version =	D_VERSION,
6022 	.d_ioctl =	devctl2_ioctl,
6023 	.d_name =	"devctl2",
6024 };
6025 
6026 static void
devctl2_init(void)6027 devctl2_init(void)
6028 {
6029 	make_dev_credf(MAKEDEV_ETERNAL, &devctl2_cdevsw, 0, NULL,
6030 	    UID_ROOT, GID_WHEEL, 0644, "devctl2");
6031 }
6032 
6033 /*
6034  * For maintaining device 'at' location info to avoid recomputing it
6035  */
6036 struct device_location_node {
6037 	const char *dln_locator;
6038 	const char *dln_path;
6039 	TAILQ_ENTRY(device_location_node) dln_link;
6040 };
6041 typedef TAILQ_HEAD(device_location_list, device_location_node) device_location_list_t;
6042 
6043 struct device_location_cache {
6044 	device_location_list_t dlc_list;
6045 };
6046 
6047 
6048 /*
6049  * Location cache for wired devices.
6050  */
6051 device_location_cache_t *
dev_wired_cache_init(void)6052 dev_wired_cache_init(void)
6053 {
6054 	device_location_cache_t *dcp;
6055 
6056 	dcp = malloc(sizeof(*dcp), M_BUS, M_WAITOK | M_ZERO);
6057 	TAILQ_INIT(&dcp->dlc_list);
6058 
6059 	return (dcp);
6060 }
6061 
6062 void
dev_wired_cache_fini(device_location_cache_t * dcp)6063 dev_wired_cache_fini(device_location_cache_t *dcp)
6064 {
6065 	struct device_location_node *dln, *tdln;
6066 
6067 	TAILQ_FOREACH_SAFE(dln, &dcp->dlc_list, dln_link, tdln) {
6068 		free(dln, M_BUS);
6069 	}
6070 	free(dcp, M_BUS);
6071 }
6072 
6073 static struct device_location_node *
dev_wired_cache_lookup(device_location_cache_t * dcp,const char * locator)6074 dev_wired_cache_lookup(device_location_cache_t *dcp, const char *locator)
6075 {
6076 	struct device_location_node *dln;
6077 
6078 	TAILQ_FOREACH(dln, &dcp->dlc_list, dln_link) {
6079 		if (strcmp(locator, dln->dln_locator) == 0)
6080 			return (dln);
6081 	}
6082 
6083 	return (NULL);
6084 }
6085 
6086 static struct device_location_node *
dev_wired_cache_add(device_location_cache_t * dcp,const char * locator,const char * path)6087 dev_wired_cache_add(device_location_cache_t *dcp, const char *locator, const char *path)
6088 {
6089 	struct device_location_node *dln;
6090 	size_t loclen, pathlen;
6091 
6092 	loclen = strlen(locator) + 1;
6093 	pathlen = strlen(path) + 1;
6094 	dln = malloc(sizeof(*dln) + loclen + pathlen, M_BUS, M_WAITOK | M_ZERO);
6095 	dln->dln_locator = (char *)(dln + 1);
6096 	memcpy(__DECONST(char *, dln->dln_locator), locator, loclen);
6097 	dln->dln_path = dln->dln_locator + loclen;
6098 	memcpy(__DECONST(char *, dln->dln_path), path, pathlen);
6099 	TAILQ_INSERT_HEAD(&dcp->dlc_list, dln, dln_link);
6100 
6101 	return (dln);
6102 }
6103 
6104 bool
dev_wired_cache_match(device_location_cache_t * dcp,device_t dev,const char * at)6105 dev_wired_cache_match(device_location_cache_t *dcp, device_t dev,
6106     const char *at)
6107 {
6108 	struct sbuf *sb;
6109 	const char *cp;
6110 	char locator[32];
6111 	int error, len;
6112 	struct device_location_node *res;
6113 
6114 	cp = strchr(at, ':');
6115 	if (cp == NULL)
6116 		return (false);
6117 	len = cp - at;
6118 	if (len > sizeof(locator) - 1)	/* Skip too long locator */
6119 		return (false);
6120 	memcpy(locator, at, len);
6121 	locator[len] = '\0';
6122 	cp++;
6123 
6124 	error = 0;
6125 	/* maybe cache this inside device_t and look that up, but not yet */
6126 	res = dev_wired_cache_lookup(dcp, locator);
6127 	if (res == NULL) {
6128 		sb = sbuf_new(NULL, NULL, 0, SBUF_AUTOEXTEND |
6129 		    SBUF_INCLUDENUL | SBUF_NOWAIT);
6130 		if (sb != NULL) {
6131 			error = device_get_path(dev, locator, sb);
6132 			if (error == 0) {
6133 				res = dev_wired_cache_add(dcp, locator,
6134 				    sbuf_data(sb));
6135 			}
6136 			sbuf_delete(sb);
6137 		}
6138 	}
6139 	if (error != 0 || res == NULL || res->dln_path == NULL)
6140 		return (false);
6141 
6142 	return (strcmp(res->dln_path, cp) == 0);
6143 }
6144 
6145 static struct device_prop_elm *
device_prop_find(device_t dev,const char * name)6146 device_prop_find(device_t dev, const char *name)
6147 {
6148 	struct device_prop_elm *e;
6149 
6150 	bus_topo_assert();
6151 
6152 	LIST_FOREACH(e, &dev->props, link) {
6153 		if (strcmp(name, e->name) == 0)
6154 			return (e);
6155 	}
6156 	return (NULL);
6157 }
6158 
6159 int
device_set_prop(device_t dev,const char * name,void * val,device_prop_dtr_t dtr,void * dtr_ctx)6160 device_set_prop(device_t dev, const char *name, void *val,
6161     device_prop_dtr_t dtr, void *dtr_ctx)
6162 {
6163 	struct device_prop_elm *e, *e1;
6164 
6165 	bus_topo_assert();
6166 
6167 	e = device_prop_find(dev, name);
6168 	if (e != NULL)
6169 		goto found;
6170 
6171 	e1 = malloc(sizeof(*e), M_BUS, M_WAITOK);
6172 	e = device_prop_find(dev, name);
6173 	if (e != NULL) {
6174 		free(e1, M_BUS);
6175 		goto found;
6176 	}
6177 
6178 	e1->name = name;
6179 	e1->val = val;
6180 	e1->dtr = dtr;
6181 	e1->dtr_ctx = dtr_ctx;
6182 	LIST_INSERT_HEAD(&dev->props, e1, link);
6183 	return (0);
6184 
6185 found:
6186 	LIST_REMOVE(e, link);
6187 	if (e->dtr != NULL)
6188 		e->dtr(dev, name, e->val, e->dtr_ctx);
6189 	e->val = val;
6190 	e->dtr = dtr;
6191 	e->dtr_ctx = dtr_ctx;
6192 	LIST_INSERT_HEAD(&dev->props, e, link);
6193 	return (EEXIST);
6194 }
6195 
6196 int
device_get_prop(device_t dev,const char * name,void ** valp)6197 device_get_prop(device_t dev, const char *name, void **valp)
6198 {
6199 	struct device_prop_elm *e;
6200 
6201 	bus_topo_assert();
6202 
6203 	e = device_prop_find(dev, name);
6204 	if (e == NULL)
6205 		return (ENOENT);
6206 	*valp = e->val;
6207 	return (0);
6208 }
6209 
6210 int
device_clear_prop(device_t dev,const char * name)6211 device_clear_prop(device_t dev, const char *name)
6212 {
6213 	struct device_prop_elm *e;
6214 
6215 	bus_topo_assert();
6216 
6217 	e = device_prop_find(dev, name);
6218 	if (e == NULL)
6219 		return (ENOENT);
6220 	LIST_REMOVE(e, link);
6221 	if (e->dtr != NULL)
6222 		e->dtr(dev, e->name, e->val, e->dtr_ctx);
6223 	free(e, M_BUS);
6224 	return (0);
6225 }
6226 
6227 static void
device_destroy_props(device_t dev)6228 device_destroy_props(device_t dev)
6229 {
6230 	struct device_prop_elm *e;
6231 
6232 	bus_topo_assert();
6233 
6234 	while ((e = LIST_FIRST(&dev->props)) != NULL) {
6235 		LIST_REMOVE_HEAD(&dev->props, link);
6236 		if (e->dtr != NULL)
6237 			e->dtr(dev, e->name, e->val, e->dtr_ctx);
6238 		free(e, M_BUS);
6239 	}
6240 }
6241 
6242 void
device_clear_prop_alldev(const char * name)6243 device_clear_prop_alldev(const char *name)
6244 {
6245 	device_t dev;
6246 
6247 	TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
6248 		device_clear_prop(dev, name);
6249 	}
6250 }
6251 
6252 /*
6253  * APIs to manage deprecation and obsolescence.
6254  */
6255 static int obsolete_panic = 0;
6256 SYSCTL_INT(_debug, OID_AUTO, obsolete_panic, CTLFLAG_RWTUN, &obsolete_panic, 0,
6257     "Panic when obsolete features are used (0 = never, 1 = if obsolete, "
6258     "2 = if deprecated)");
6259 
6260 static void
gone_panic(int major,int running,const char * msg)6261 gone_panic(int major, int running, const char *msg)
6262 {
6263 	switch (obsolete_panic)
6264 	{
6265 	case 0:
6266 		return;
6267 	case 1:
6268 		if (running < major)
6269 			return;
6270 		/* FALLTHROUGH */
6271 	default:
6272 		panic("%s", msg);
6273 	}
6274 }
6275 
6276 void
_gone_in(int major,const char * msg)6277 _gone_in(int major, const char *msg)
6278 {
6279 	gone_panic(major, P_OSREL_MAJOR(__FreeBSD_version), msg);
6280 	if (P_OSREL_MAJOR(__FreeBSD_version) >= major)
6281 		printf("Obsolete code will be removed soon: %s\n", msg);
6282 	else
6283 		printf("Deprecated code (to be removed in FreeBSD %d): %s\n",
6284 		    major, msg);
6285 }
6286 
6287 void
_gone_in_dev(device_t dev,int major,const char * msg)6288 _gone_in_dev(device_t dev, int major, const char *msg)
6289 {
6290 	gone_panic(major, P_OSREL_MAJOR(__FreeBSD_version), msg);
6291 	if (P_OSREL_MAJOR(__FreeBSD_version) >= major)
6292 		device_printf(dev,
6293 		    "Obsolete code will be removed soon: %s\n", msg);
6294 	else
6295 		device_printf(dev,
6296 		    "Deprecated code (to be removed in FreeBSD %d): %s\n",
6297 		    major, msg);
6298 }
6299 
6300 #ifdef DDB
DB_SHOW_COMMAND(device,db_show_device)6301 DB_SHOW_COMMAND(device, db_show_device)
6302 {
6303 	device_t dev;
6304 
6305 	if (!have_addr)
6306 		return;
6307 
6308 	dev = (device_t)addr;
6309 
6310 	db_printf("name:    %s\n", device_get_nameunit(dev));
6311 	db_printf("  driver:  %s\n", DRIVERNAME(dev->driver));
6312 	db_printf("  class:   %s\n", DEVCLANAME(dev->devclass));
6313 	db_printf("  addr:    %p\n", dev);
6314 	db_printf("  parent:  %p\n", dev->parent);
6315 	db_printf("  softc:   %p\n", dev->softc);
6316 	db_printf("  ivars:   %p\n", dev->ivars);
6317 }
6318 
DB_SHOW_ALL_COMMAND(devices,db_show_all_devices)6319 DB_SHOW_ALL_COMMAND(devices, db_show_all_devices)
6320 {
6321 	device_t dev;
6322 
6323 	TAILQ_FOREACH(dev, &bus_data_devices, devlink) {
6324 		db_show_device((db_expr_t)dev, true, count, modif);
6325 	}
6326 }
6327 #endif
6328