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