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