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