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