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