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