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