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