xref: /linux-6.15/drivers/base/dd.c (revision 7f2fac70)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * drivers/base/dd.c - The core device/driver interactions.
4  *
5  * This file contains the (sometimes tricky) code that controls the
6  * interactions between devices and drivers, which primarily includes
7  * driver binding and unbinding.
8  *
9  * All of this code used to exist in drivers/base/bus.c, but was
10  * relocated to here in the name of compartmentalization (since it wasn't
11  * strictly code just for the 'struct bus_type'.
12  *
13  * Copyright (c) 2002-5 Patrick Mochel
14  * Copyright (c) 2002-3 Open Source Development Labs
15  * Copyright (c) 2007-2009 Greg Kroah-Hartman <[email protected]>
16  * Copyright (c) 2007-2009 Novell Inc.
17  */
18 
19 #include <linux/debugfs.h>
20 #include <linux/device.h>
21 #include <linux/delay.h>
22 #include <linux/dma-map-ops.h>
23 #include <linux/init.h>
24 #include <linux/module.h>
25 #include <linux/kthread.h>
26 #include <linux/wait.h>
27 #include <linux/async.h>
28 #include <linux/pm_runtime.h>
29 #include <linux/pinctrl/devinfo.h>
30 #include <linux/slab.h>
31 
32 #include "base.h"
33 #include "power/power.h"
34 
35 /*
36  * Deferred Probe infrastructure.
37  *
38  * Sometimes driver probe order matters, but the kernel doesn't always have
39  * dependency information which means some drivers will get probed before a
40  * resource it depends on is available.  For example, an SDHCI driver may
41  * first need a GPIO line from an i2c GPIO controller before it can be
42  * initialized.  If a required resource is not available yet, a driver can
43  * request probing to be deferred by returning -EPROBE_DEFER from its probe hook
44  *
45  * Deferred probe maintains two lists of devices, a pending list and an active
46  * list.  A driver returning -EPROBE_DEFER causes the device to be added to the
47  * pending list.  A successful driver probe will trigger moving all devices
48  * from the pending to the active list so that the workqueue will eventually
49  * retry them.
50  *
51  * The deferred_probe_mutex must be held any time the deferred_probe_*_list
52  * of the (struct device*)->p->deferred_probe pointers are manipulated
53  */
54 static DEFINE_MUTEX(deferred_probe_mutex);
55 static LIST_HEAD(deferred_probe_pending_list);
56 static LIST_HEAD(deferred_probe_active_list);
57 static atomic_t deferred_trigger_count = ATOMIC_INIT(0);
58 static bool initcalls_done;
59 
60 /* Save the async probe drivers' name from kernel cmdline */
61 #define ASYNC_DRV_NAMES_MAX_LEN	256
62 static char async_probe_drv_names[ASYNC_DRV_NAMES_MAX_LEN];
63 
64 /*
65  * In some cases, like suspend to RAM or hibernation, It might be reasonable
66  * to prohibit probing of devices as it could be unsafe.
67  * Once defer_all_probes is true all drivers probes will be forcibly deferred.
68  */
69 static bool defer_all_probes;
70 
71 /*
72  * deferred_probe_work_func() - Retry probing devices in the active list.
73  */
74 static void deferred_probe_work_func(struct work_struct *work)
75 {
76 	struct device *dev;
77 	struct device_private *private;
78 	/*
79 	 * This block processes every device in the deferred 'active' list.
80 	 * Each device is removed from the active list and passed to
81 	 * bus_probe_device() to re-attempt the probe.  The loop continues
82 	 * until every device in the active list is removed and retried.
83 	 *
84 	 * Note: Once the device is removed from the list and the mutex is
85 	 * released, it is possible for the device get freed by another thread
86 	 * and cause a illegal pointer dereference.  This code uses
87 	 * get/put_device() to ensure the device structure cannot disappear
88 	 * from under our feet.
89 	 */
90 	mutex_lock(&deferred_probe_mutex);
91 	while (!list_empty(&deferred_probe_active_list)) {
92 		private = list_first_entry(&deferred_probe_active_list,
93 					typeof(*dev->p), deferred_probe);
94 		dev = private->device;
95 		list_del_init(&private->deferred_probe);
96 
97 		get_device(dev);
98 
99 		/*
100 		 * Drop the mutex while probing each device; the probe path may
101 		 * manipulate the deferred list
102 		 */
103 		mutex_unlock(&deferred_probe_mutex);
104 
105 		/*
106 		 * Force the device to the end of the dpm_list since
107 		 * the PM code assumes that the order we add things to
108 		 * the list is a good order for suspend but deferred
109 		 * probe makes that very unsafe.
110 		 */
111 		device_pm_move_to_tail(dev);
112 
113 		dev_dbg(dev, "Retrying from deferred list\n");
114 		bus_probe_device(dev);
115 		mutex_lock(&deferred_probe_mutex);
116 
117 		put_device(dev);
118 	}
119 	mutex_unlock(&deferred_probe_mutex);
120 }
121 static DECLARE_WORK(deferred_probe_work, deferred_probe_work_func);
122 
123 void driver_deferred_probe_add(struct device *dev)
124 {
125 	if (!dev->can_match)
126 		return;
127 
128 	mutex_lock(&deferred_probe_mutex);
129 	if (list_empty(&dev->p->deferred_probe)) {
130 		dev_dbg(dev, "Added to deferred list\n");
131 		list_add_tail(&dev->p->deferred_probe, &deferred_probe_pending_list);
132 	}
133 	mutex_unlock(&deferred_probe_mutex);
134 }
135 
136 void driver_deferred_probe_del(struct device *dev)
137 {
138 	mutex_lock(&deferred_probe_mutex);
139 	if (!list_empty(&dev->p->deferred_probe)) {
140 		dev_dbg(dev, "Removed from deferred list\n");
141 		list_del_init(&dev->p->deferred_probe);
142 		kfree(dev->p->deferred_probe_reason);
143 		dev->p->deferred_probe_reason = NULL;
144 	}
145 	mutex_unlock(&deferred_probe_mutex);
146 }
147 
148 static bool driver_deferred_probe_enable = false;
149 /**
150  * driver_deferred_probe_trigger() - Kick off re-probing deferred devices
151  *
152  * This functions moves all devices from the pending list to the active
153  * list and schedules the deferred probe workqueue to process them.  It
154  * should be called anytime a driver is successfully bound to a device.
155  *
156  * Note, there is a race condition in multi-threaded probe. In the case where
157  * more than one device is probing at the same time, it is possible for one
158  * probe to complete successfully while another is about to defer. If the second
159  * depends on the first, then it will get put on the pending list after the
160  * trigger event has already occurred and will be stuck there.
161  *
162  * The atomic 'deferred_trigger_count' is used to determine if a successful
163  * trigger has occurred in the midst of probing a driver. If the trigger count
164  * changes in the midst of a probe, then deferred processing should be triggered
165  * again.
166  */
167 static void driver_deferred_probe_trigger(void)
168 {
169 	if (!driver_deferred_probe_enable)
170 		return;
171 
172 	/*
173 	 * A successful probe means that all the devices in the pending list
174 	 * should be triggered to be reprobed.  Move all the deferred devices
175 	 * into the active list so they can be retried by the workqueue
176 	 */
177 	mutex_lock(&deferred_probe_mutex);
178 	atomic_inc(&deferred_trigger_count);
179 	list_splice_tail_init(&deferred_probe_pending_list,
180 			      &deferred_probe_active_list);
181 	mutex_unlock(&deferred_probe_mutex);
182 
183 	/*
184 	 * Kick the re-probe thread.  It may already be scheduled, but it is
185 	 * safe to kick it again.
186 	 */
187 	schedule_work(&deferred_probe_work);
188 }
189 
190 /**
191  * device_block_probing() - Block/defer device's probes
192  *
193  *	It will disable probing of devices and defer their probes instead.
194  */
195 void device_block_probing(void)
196 {
197 	defer_all_probes = true;
198 	/* sync with probes to avoid races. */
199 	wait_for_device_probe();
200 }
201 
202 /**
203  * device_unblock_probing() - Unblock/enable device's probes
204  *
205  *	It will restore normal behavior and trigger re-probing of deferred
206  * devices.
207  */
208 void device_unblock_probing(void)
209 {
210 	defer_all_probes = false;
211 	driver_deferred_probe_trigger();
212 }
213 
214 /**
215  * device_set_deferred_probe_reason() - Set defer probe reason message for device
216  * @dev: the pointer to the struct device
217  * @vaf: the pointer to va_format structure with message
218  */
219 void device_set_deferred_probe_reason(const struct device *dev, struct va_format *vaf)
220 {
221 	const char *drv = dev_driver_string(dev);
222 
223 	mutex_lock(&deferred_probe_mutex);
224 
225 	kfree(dev->p->deferred_probe_reason);
226 	dev->p->deferred_probe_reason = kasprintf(GFP_KERNEL, "%s: %pV", drv, vaf);
227 
228 	mutex_unlock(&deferred_probe_mutex);
229 }
230 
231 /*
232  * deferred_devs_show() - Show the devices in the deferred probe pending list.
233  */
234 static int deferred_devs_show(struct seq_file *s, void *data)
235 {
236 	struct device_private *curr;
237 
238 	mutex_lock(&deferred_probe_mutex);
239 
240 	list_for_each_entry(curr, &deferred_probe_pending_list, deferred_probe)
241 		seq_printf(s, "%s\t%s", dev_name(curr->device),
242 			   curr->device->p->deferred_probe_reason ?: "\n");
243 
244 	mutex_unlock(&deferred_probe_mutex);
245 
246 	return 0;
247 }
248 DEFINE_SHOW_ATTRIBUTE(deferred_devs);
249 
250 int driver_deferred_probe_timeout;
251 EXPORT_SYMBOL_GPL(driver_deferred_probe_timeout);
252 static DECLARE_WAIT_QUEUE_HEAD(probe_timeout_waitqueue);
253 
254 static int __init deferred_probe_timeout_setup(char *str)
255 {
256 	int timeout;
257 
258 	if (!kstrtoint(str, 10, &timeout))
259 		driver_deferred_probe_timeout = timeout;
260 	return 1;
261 }
262 __setup("deferred_probe_timeout=", deferred_probe_timeout_setup);
263 
264 /**
265  * driver_deferred_probe_check_state() - Check deferred probe state
266  * @dev: device to check
267  *
268  * Return:
269  * -ENODEV if initcalls have completed and modules are disabled.
270  * -ETIMEDOUT if the deferred probe timeout was set and has expired
271  *  and modules are enabled.
272  * -EPROBE_DEFER in other cases.
273  *
274  * Drivers or subsystems can opt-in to calling this function instead of directly
275  * returning -EPROBE_DEFER.
276  */
277 int driver_deferred_probe_check_state(struct device *dev)
278 {
279 	if (!IS_ENABLED(CONFIG_MODULES) && initcalls_done) {
280 		dev_warn(dev, "ignoring dependency for device, assuming no driver\n");
281 		return -ENODEV;
282 	}
283 
284 	if (!driver_deferred_probe_timeout && initcalls_done) {
285 		dev_warn(dev, "deferred probe timeout, ignoring dependency\n");
286 		return -ETIMEDOUT;
287 	}
288 
289 	return -EPROBE_DEFER;
290 }
291 
292 static void deferred_probe_timeout_work_func(struct work_struct *work)
293 {
294 	struct device_private *private, *p;
295 
296 	driver_deferred_probe_timeout = 0;
297 	driver_deferred_probe_trigger();
298 	flush_work(&deferred_probe_work);
299 
300 	list_for_each_entry_safe(private, p, &deferred_probe_pending_list, deferred_probe)
301 		dev_info(private->device, "deferred probe pending\n");
302 	wake_up_all(&probe_timeout_waitqueue);
303 }
304 static DECLARE_DELAYED_WORK(deferred_probe_timeout_work, deferred_probe_timeout_work_func);
305 
306 /**
307  * deferred_probe_initcall() - Enable probing of deferred devices
308  *
309  * We don't want to get in the way when the bulk of drivers are getting probed.
310  * Instead, this initcall makes sure that deferred probing is delayed until
311  * late_initcall time.
312  */
313 static int deferred_probe_initcall(void)
314 {
315 	debugfs_create_file("devices_deferred", 0444, NULL, NULL,
316 			    &deferred_devs_fops);
317 
318 	driver_deferred_probe_enable = true;
319 	driver_deferred_probe_trigger();
320 	/* Sort as many dependencies as possible before exiting initcalls */
321 	flush_work(&deferred_probe_work);
322 	initcalls_done = true;
323 
324 	/*
325 	 * Trigger deferred probe again, this time we won't defer anything
326 	 * that is optional
327 	 */
328 	driver_deferred_probe_trigger();
329 	flush_work(&deferred_probe_work);
330 
331 	if (driver_deferred_probe_timeout > 0) {
332 		schedule_delayed_work(&deferred_probe_timeout_work,
333 			driver_deferred_probe_timeout * HZ);
334 	}
335 	return 0;
336 }
337 late_initcall(deferred_probe_initcall);
338 
339 static void __exit deferred_probe_exit(void)
340 {
341 	debugfs_remove_recursive(debugfs_lookup("devices_deferred", NULL));
342 }
343 __exitcall(deferred_probe_exit);
344 
345 /**
346  * device_is_bound() - Check if device is bound to a driver
347  * @dev: device to check
348  *
349  * Returns true if passed device has already finished probing successfully
350  * against a driver.
351  *
352  * This function must be called with the device lock held.
353  */
354 bool device_is_bound(struct device *dev)
355 {
356 	return dev->p && klist_node_attached(&dev->p->knode_driver);
357 }
358 
359 static void driver_bound(struct device *dev)
360 {
361 	if (device_is_bound(dev)) {
362 		pr_warn("%s: device %s already bound\n",
363 			__func__, kobject_name(&dev->kobj));
364 		return;
365 	}
366 
367 	pr_debug("driver: '%s': %s: bound to device '%s'\n", dev->driver->name,
368 		 __func__, dev_name(dev));
369 
370 	klist_add_tail(&dev->p->knode_driver, &dev->driver->p->klist_devices);
371 	device_links_driver_bound(dev);
372 
373 	device_pm_check_callbacks(dev);
374 
375 	/*
376 	 * Make sure the device is no longer in one of the deferred lists and
377 	 * kick off retrying all pending devices
378 	 */
379 	driver_deferred_probe_del(dev);
380 	driver_deferred_probe_trigger();
381 
382 	if (dev->bus)
383 		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
384 					     BUS_NOTIFY_BOUND_DRIVER, dev);
385 
386 	kobject_uevent(&dev->kobj, KOBJ_BIND);
387 }
388 
389 static ssize_t coredump_store(struct device *dev, struct device_attribute *attr,
390 			    const char *buf, size_t count)
391 {
392 	device_lock(dev);
393 	dev->driver->coredump(dev);
394 	device_unlock(dev);
395 
396 	return count;
397 }
398 static DEVICE_ATTR_WO(coredump);
399 
400 static int driver_sysfs_add(struct device *dev)
401 {
402 	int ret;
403 
404 	if (dev->bus)
405 		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
406 					     BUS_NOTIFY_BIND_DRIVER, dev);
407 
408 	ret = sysfs_create_link(&dev->driver->p->kobj, &dev->kobj,
409 				kobject_name(&dev->kobj));
410 	if (ret)
411 		goto fail;
412 
413 	ret = sysfs_create_link(&dev->kobj, &dev->driver->p->kobj,
414 				"driver");
415 	if (ret)
416 		goto rm_dev;
417 
418 	if (!IS_ENABLED(CONFIG_DEV_COREDUMP) || !dev->driver->coredump ||
419 	    !device_create_file(dev, &dev_attr_coredump))
420 		return 0;
421 
422 	sysfs_remove_link(&dev->kobj, "driver");
423 
424 rm_dev:
425 	sysfs_remove_link(&dev->driver->p->kobj,
426 			  kobject_name(&dev->kobj));
427 
428 fail:
429 	return ret;
430 }
431 
432 static void driver_sysfs_remove(struct device *dev)
433 {
434 	struct device_driver *drv = dev->driver;
435 
436 	if (drv) {
437 		if (drv->coredump)
438 			device_remove_file(dev, &dev_attr_coredump);
439 		sysfs_remove_link(&drv->p->kobj, kobject_name(&dev->kobj));
440 		sysfs_remove_link(&dev->kobj, "driver");
441 	}
442 }
443 
444 /**
445  * device_bind_driver - bind a driver to one device.
446  * @dev: device.
447  *
448  * Allow manual attachment of a driver to a device.
449  * Caller must have already set @dev->driver.
450  *
451  * Note that this does not modify the bus reference count.
452  * Please verify that is accounted for before calling this.
453  * (It is ok to call with no other effort from a driver's probe() method.)
454  *
455  * This function must be called with the device lock held.
456  */
457 int device_bind_driver(struct device *dev)
458 {
459 	int ret;
460 
461 	ret = driver_sysfs_add(dev);
462 	if (!ret) {
463 		device_links_force_bind(dev);
464 		driver_bound(dev);
465 	}
466 	else if (dev->bus)
467 		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
468 					     BUS_NOTIFY_DRIVER_NOT_BOUND, dev);
469 	return ret;
470 }
471 EXPORT_SYMBOL_GPL(device_bind_driver);
472 
473 static atomic_t probe_count = ATOMIC_INIT(0);
474 static DECLARE_WAIT_QUEUE_HEAD(probe_waitqueue);
475 
476 static void driver_deferred_probe_add_trigger(struct device *dev,
477 					      int local_trigger_count)
478 {
479 	driver_deferred_probe_add(dev);
480 	/* Did a trigger occur while probing? Need to re-trigger if yes */
481 	if (local_trigger_count != atomic_read(&deferred_trigger_count))
482 		driver_deferred_probe_trigger();
483 }
484 
485 static ssize_t state_synced_show(struct device *dev,
486 				 struct device_attribute *attr, char *buf)
487 {
488 	bool val;
489 
490 	device_lock(dev);
491 	val = dev->state_synced;
492 	device_unlock(dev);
493 
494 	return sysfs_emit(buf, "%u\n", val);
495 }
496 static DEVICE_ATTR_RO(state_synced);
497 
498 static int really_probe(struct device *dev, struct device_driver *drv)
499 {
500 	int ret = -EPROBE_DEFER;
501 	int local_trigger_count = atomic_read(&deferred_trigger_count);
502 	bool test_remove = IS_ENABLED(CONFIG_DEBUG_TEST_DRIVER_REMOVE) &&
503 			   !drv->suppress_bind_attrs;
504 
505 	if (defer_all_probes) {
506 		/*
507 		 * Value of defer_all_probes can be set only by
508 		 * device_block_probing() which, in turn, will call
509 		 * wait_for_device_probe() right after that to avoid any races.
510 		 */
511 		dev_dbg(dev, "Driver %s force probe deferral\n", drv->name);
512 		driver_deferred_probe_add(dev);
513 		return ret;
514 	}
515 
516 	ret = device_links_check_suppliers(dev);
517 	if (ret == -EPROBE_DEFER)
518 		driver_deferred_probe_add_trigger(dev, local_trigger_count);
519 	if (ret)
520 		return ret;
521 
522 	atomic_inc(&probe_count);
523 	pr_debug("bus: '%s': %s: probing driver %s with device %s\n",
524 		 drv->bus->name, __func__, drv->name, dev_name(dev));
525 	if (!list_empty(&dev->devres_head)) {
526 		dev_crit(dev, "Resources present before probing\n");
527 		ret = -EBUSY;
528 		goto done;
529 	}
530 
531 re_probe:
532 	dev->driver = drv;
533 
534 	/* If using pinctrl, bind pins now before probing */
535 	ret = pinctrl_bind_pins(dev);
536 	if (ret)
537 		goto pinctrl_bind_failed;
538 
539 	if (dev->bus->dma_configure) {
540 		ret = dev->bus->dma_configure(dev);
541 		if (ret)
542 			goto probe_failed;
543 	}
544 
545 	if (driver_sysfs_add(dev)) {
546 		pr_err("%s: driver_sysfs_add(%s) failed\n",
547 		       __func__, dev_name(dev));
548 		goto probe_failed;
549 	}
550 
551 	if (dev->pm_domain && dev->pm_domain->activate) {
552 		ret = dev->pm_domain->activate(dev);
553 		if (ret)
554 			goto probe_failed;
555 	}
556 
557 	if (dev->bus->probe) {
558 		ret = dev->bus->probe(dev);
559 		if (ret)
560 			goto probe_failed;
561 	} else if (drv->probe) {
562 		ret = drv->probe(dev);
563 		if (ret)
564 			goto probe_failed;
565 	}
566 
567 	if (device_add_groups(dev, drv->dev_groups)) {
568 		dev_err(dev, "device_add_groups() failed\n");
569 		goto dev_groups_failed;
570 	}
571 
572 	if (dev_has_sync_state(dev) &&
573 	    device_create_file(dev, &dev_attr_state_synced)) {
574 		dev_err(dev, "state_synced sysfs add failed\n");
575 		goto dev_sysfs_state_synced_failed;
576 	}
577 
578 	if (test_remove) {
579 		test_remove = false;
580 
581 		device_remove_file(dev, &dev_attr_state_synced);
582 		device_remove_groups(dev, drv->dev_groups);
583 
584 		if (dev->bus->remove)
585 			dev->bus->remove(dev);
586 		else if (drv->remove)
587 			drv->remove(dev);
588 
589 		devres_release_all(dev);
590 		driver_sysfs_remove(dev);
591 		dev->driver = NULL;
592 		dev_set_drvdata(dev, NULL);
593 		if (dev->pm_domain && dev->pm_domain->dismiss)
594 			dev->pm_domain->dismiss(dev);
595 		pm_runtime_reinit(dev);
596 
597 		goto re_probe;
598 	}
599 
600 	pinctrl_init_done(dev);
601 
602 	if (dev->pm_domain && dev->pm_domain->sync)
603 		dev->pm_domain->sync(dev);
604 
605 	driver_bound(dev);
606 	ret = 1;
607 	pr_debug("bus: '%s': %s: bound device %s to driver %s\n",
608 		 drv->bus->name, __func__, dev_name(dev), drv->name);
609 	goto done;
610 
611 dev_sysfs_state_synced_failed:
612 	device_remove_groups(dev, drv->dev_groups);
613 dev_groups_failed:
614 	if (dev->bus->remove)
615 		dev->bus->remove(dev);
616 	else if (drv->remove)
617 		drv->remove(dev);
618 probe_failed:
619 	kfree(dev->dma_range_map);
620 	dev->dma_range_map = NULL;
621 	if (dev->bus)
622 		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
623 					     BUS_NOTIFY_DRIVER_NOT_BOUND, dev);
624 pinctrl_bind_failed:
625 	device_links_no_driver(dev);
626 	devres_release_all(dev);
627 	arch_teardown_dma_ops(dev);
628 	driver_sysfs_remove(dev);
629 	dev->driver = NULL;
630 	dev_set_drvdata(dev, NULL);
631 	if (dev->pm_domain && dev->pm_domain->dismiss)
632 		dev->pm_domain->dismiss(dev);
633 	pm_runtime_reinit(dev);
634 	dev_pm_set_driver_flags(dev, 0);
635 
636 	switch (ret) {
637 	case -EPROBE_DEFER:
638 		/* Driver requested deferred probing */
639 		dev_dbg(dev, "Driver %s requests probe deferral\n", drv->name);
640 		driver_deferred_probe_add_trigger(dev, local_trigger_count);
641 		break;
642 	case -ENODEV:
643 	case -ENXIO:
644 		pr_debug("%s: probe of %s rejects match %d\n",
645 			 drv->name, dev_name(dev), ret);
646 		break;
647 	default:
648 		/* driver matched but the probe failed */
649 		pr_warn("%s: probe of %s failed with error %d\n",
650 			drv->name, dev_name(dev), ret);
651 	}
652 	/*
653 	 * Ignore errors returned by ->probe so that the next driver can try
654 	 * its luck.
655 	 */
656 	ret = 0;
657 done:
658 	atomic_dec(&probe_count);
659 	wake_up_all(&probe_waitqueue);
660 	return ret;
661 }
662 
663 /*
664  * For initcall_debug, show the driver probe time.
665  */
666 static int really_probe_debug(struct device *dev, struct device_driver *drv)
667 {
668 	ktime_t calltime, rettime;
669 	int ret;
670 
671 	calltime = ktime_get();
672 	ret = really_probe(dev, drv);
673 	rettime = ktime_get();
674 	pr_debug("probe of %s returned %d after %lld usecs\n",
675 		 dev_name(dev), ret, ktime_us_delta(rettime, calltime));
676 	return ret;
677 }
678 
679 /**
680  * driver_probe_done
681  * Determine if the probe sequence is finished or not.
682  *
683  * Should somehow figure out how to use a semaphore, not an atomic variable...
684  */
685 int driver_probe_done(void)
686 {
687 	int local_probe_count = atomic_read(&probe_count);
688 
689 	pr_debug("%s: probe_count = %d\n", __func__, local_probe_count);
690 	if (local_probe_count)
691 		return -EBUSY;
692 	return 0;
693 }
694 
695 /**
696  * wait_for_device_probe
697  * Wait for device probing to be completed.
698  */
699 void wait_for_device_probe(void)
700 {
701 	/* wait for probe timeout */
702 	wait_event(probe_timeout_waitqueue, !driver_deferred_probe_timeout);
703 
704 	/* wait for the deferred probe workqueue to finish */
705 	flush_work(&deferred_probe_work);
706 
707 	/* wait for the known devices to complete their probing */
708 	wait_event(probe_waitqueue, atomic_read(&probe_count) == 0);
709 	async_synchronize_full();
710 }
711 EXPORT_SYMBOL_GPL(wait_for_device_probe);
712 
713 /**
714  * driver_probe_device - attempt to bind device & driver together
715  * @drv: driver to bind a device to
716  * @dev: device to try to bind to the driver
717  *
718  * This function returns -ENODEV if the device is not registered,
719  * 1 if the device is bound successfully and 0 otherwise.
720  *
721  * This function must be called with @dev lock held.  When called for a
722  * USB interface, @dev->parent lock must be held as well.
723  *
724  * If the device has a parent, runtime-resume the parent before driver probing.
725  */
726 static int driver_probe_device(struct device_driver *drv, struct device *dev)
727 {
728 	int ret = 0;
729 
730 	if (!device_is_registered(dev))
731 		return -ENODEV;
732 
733 	dev->can_match = true;
734 	pr_debug("bus: '%s': %s: matched device %s with driver %s\n",
735 		 drv->bus->name, __func__, dev_name(dev), drv->name);
736 
737 	pm_runtime_get_suppliers(dev);
738 	if (dev->parent)
739 		pm_runtime_get_sync(dev->parent);
740 
741 	pm_runtime_barrier(dev);
742 	if (initcall_debug)
743 		ret = really_probe_debug(dev, drv);
744 	else
745 		ret = really_probe(dev, drv);
746 	pm_request_idle(dev);
747 
748 	if (dev->parent)
749 		pm_runtime_put(dev->parent);
750 
751 	pm_runtime_put_suppliers(dev);
752 	return ret;
753 }
754 
755 static inline bool cmdline_requested_async_probing(const char *drv_name)
756 {
757 	return parse_option_str(async_probe_drv_names, drv_name);
758 }
759 
760 /* The option format is "driver_async_probe=drv_name1,drv_name2,..." */
761 static int __init save_async_options(char *buf)
762 {
763 	if (strlen(buf) >= ASYNC_DRV_NAMES_MAX_LEN)
764 		pr_warn("Too long list of driver names for 'driver_async_probe'!\n");
765 
766 	strlcpy(async_probe_drv_names, buf, ASYNC_DRV_NAMES_MAX_LEN);
767 	return 0;
768 }
769 __setup("driver_async_probe=", save_async_options);
770 
771 bool driver_allows_async_probing(struct device_driver *drv)
772 {
773 	switch (drv->probe_type) {
774 	case PROBE_PREFER_ASYNCHRONOUS:
775 		return true;
776 
777 	case PROBE_FORCE_SYNCHRONOUS:
778 		return false;
779 
780 	default:
781 		if (cmdline_requested_async_probing(drv->name))
782 			return true;
783 
784 		if (module_requested_async_probing(drv->owner))
785 			return true;
786 
787 		return false;
788 	}
789 }
790 
791 struct device_attach_data {
792 	struct device *dev;
793 
794 	/*
795 	 * Indicates whether we are are considering asynchronous probing or
796 	 * not. Only initial binding after device or driver registration
797 	 * (including deferral processing) may be done asynchronously, the
798 	 * rest is always synchronous, as we expect it is being done by
799 	 * request from userspace.
800 	 */
801 	bool check_async;
802 
803 	/*
804 	 * Indicates if we are binding synchronous or asynchronous drivers.
805 	 * When asynchronous probing is enabled we'll execute 2 passes
806 	 * over drivers: first pass doing synchronous probing and second
807 	 * doing asynchronous probing (if synchronous did not succeed -
808 	 * most likely because there was no driver requiring synchronous
809 	 * probing - and we found asynchronous driver during first pass).
810 	 * The 2 passes are done because we can't shoot asynchronous
811 	 * probe for given device and driver from bus_for_each_drv() since
812 	 * driver pointer is not guaranteed to stay valid once
813 	 * bus_for_each_drv() iterates to the next driver on the bus.
814 	 */
815 	bool want_async;
816 
817 	/*
818 	 * We'll set have_async to 'true' if, while scanning for matching
819 	 * driver, we'll encounter one that requests asynchronous probing.
820 	 */
821 	bool have_async;
822 };
823 
824 static int __device_attach_driver(struct device_driver *drv, void *_data)
825 {
826 	struct device_attach_data *data = _data;
827 	struct device *dev = data->dev;
828 	bool async_allowed;
829 	int ret;
830 
831 	ret = driver_match_device(drv, dev);
832 	if (ret == 0) {
833 		/* no match */
834 		return 0;
835 	} else if (ret == -EPROBE_DEFER) {
836 		dev_dbg(dev, "Device match requests probe deferral\n");
837 		dev->can_match = true;
838 		driver_deferred_probe_add(dev);
839 	} else if (ret < 0) {
840 		dev_dbg(dev, "Bus failed to match device: %d\n", ret);
841 		return ret;
842 	} /* ret > 0 means positive match */
843 
844 	async_allowed = driver_allows_async_probing(drv);
845 
846 	if (async_allowed)
847 		data->have_async = true;
848 
849 	if (data->check_async && async_allowed != data->want_async)
850 		return 0;
851 
852 	return driver_probe_device(drv, dev);
853 }
854 
855 static void __device_attach_async_helper(void *_dev, async_cookie_t cookie)
856 {
857 	struct device *dev = _dev;
858 	struct device_attach_data data = {
859 		.dev		= dev,
860 		.check_async	= true,
861 		.want_async	= true,
862 	};
863 
864 	device_lock(dev);
865 
866 	/*
867 	 * Check if device has already been removed or claimed. This may
868 	 * happen with driver loading, device discovery/registration,
869 	 * and deferred probe processing happens all at once with
870 	 * multiple threads.
871 	 */
872 	if (dev->p->dead || dev->driver)
873 		goto out_unlock;
874 
875 	if (dev->parent)
876 		pm_runtime_get_sync(dev->parent);
877 
878 	bus_for_each_drv(dev->bus, NULL, &data, __device_attach_driver);
879 	dev_dbg(dev, "async probe completed\n");
880 
881 	pm_request_idle(dev);
882 
883 	if (dev->parent)
884 		pm_runtime_put(dev->parent);
885 out_unlock:
886 	device_unlock(dev);
887 
888 	put_device(dev);
889 }
890 
891 static int __device_attach(struct device *dev, bool allow_async)
892 {
893 	int ret = 0;
894 
895 	device_lock(dev);
896 	if (dev->p->dead) {
897 		goto out_unlock;
898 	} else if (dev->driver) {
899 		if (device_is_bound(dev)) {
900 			ret = 1;
901 			goto out_unlock;
902 		}
903 		ret = device_bind_driver(dev);
904 		if (ret == 0)
905 			ret = 1;
906 		else {
907 			dev->driver = NULL;
908 			ret = 0;
909 		}
910 	} else {
911 		struct device_attach_data data = {
912 			.dev = dev,
913 			.check_async = allow_async,
914 			.want_async = false,
915 		};
916 
917 		if (dev->parent)
918 			pm_runtime_get_sync(dev->parent);
919 
920 		ret = bus_for_each_drv(dev->bus, NULL, &data,
921 					__device_attach_driver);
922 		if (!ret && allow_async && data.have_async) {
923 			/*
924 			 * If we could not find appropriate driver
925 			 * synchronously and we are allowed to do
926 			 * async probes and there are drivers that
927 			 * want to probe asynchronously, we'll
928 			 * try them.
929 			 */
930 			dev_dbg(dev, "scheduling asynchronous probe\n");
931 			get_device(dev);
932 			async_schedule_dev(__device_attach_async_helper, dev);
933 		} else {
934 			pm_request_idle(dev);
935 		}
936 
937 		if (dev->parent)
938 			pm_runtime_put(dev->parent);
939 	}
940 out_unlock:
941 	device_unlock(dev);
942 	return ret;
943 }
944 
945 /**
946  * device_attach - try to attach device to a driver.
947  * @dev: device.
948  *
949  * Walk the list of drivers that the bus has and call
950  * driver_probe_device() for each pair. If a compatible
951  * pair is found, break out and return.
952  *
953  * Returns 1 if the device was bound to a driver;
954  * 0 if no matching driver was found;
955  * -ENODEV if the device is not registered.
956  *
957  * When called for a USB interface, @dev->parent lock must be held.
958  */
959 int device_attach(struct device *dev)
960 {
961 	return __device_attach(dev, false);
962 }
963 EXPORT_SYMBOL_GPL(device_attach);
964 
965 void device_initial_probe(struct device *dev)
966 {
967 	__device_attach(dev, true);
968 }
969 
970 /*
971  * __device_driver_lock - acquire locks needed to manipulate dev->drv
972  * @dev: Device we will update driver info for
973  * @parent: Parent device. Needed if the bus requires parent lock
974  *
975  * This function will take the required locks for manipulating dev->drv.
976  * Normally this will just be the @dev lock, but when called for a USB
977  * interface, @parent lock will be held as well.
978  */
979 static void __device_driver_lock(struct device *dev, struct device *parent)
980 {
981 	if (parent && dev->bus->need_parent_lock)
982 		device_lock(parent);
983 	device_lock(dev);
984 }
985 
986 /*
987  * __device_driver_unlock - release locks needed to manipulate dev->drv
988  * @dev: Device we will update driver info for
989  * @parent: Parent device. Needed if the bus requires parent lock
990  *
991  * This function will release the required locks for manipulating dev->drv.
992  * Normally this will just be the the @dev lock, but when called for a
993  * USB interface, @parent lock will be released as well.
994  */
995 static void __device_driver_unlock(struct device *dev, struct device *parent)
996 {
997 	device_unlock(dev);
998 	if (parent && dev->bus->need_parent_lock)
999 		device_unlock(parent);
1000 }
1001 
1002 /**
1003  * device_driver_attach - attach a specific driver to a specific device
1004  * @drv: Driver to attach
1005  * @dev: Device to attach it to
1006  *
1007  * Manually attach driver to a device. Will acquire both @dev lock and
1008  * @dev->parent lock if needed.
1009  */
1010 int device_driver_attach(struct device_driver *drv, struct device *dev)
1011 {
1012 	int ret = 0;
1013 
1014 	__device_driver_lock(dev, dev->parent);
1015 
1016 	/*
1017 	 * If device has been removed or someone has already successfully
1018 	 * bound a driver before us just skip the driver probe call.
1019 	 */
1020 	if (!dev->p->dead && !dev->driver)
1021 		ret = driver_probe_device(drv, dev);
1022 
1023 	__device_driver_unlock(dev, dev->parent);
1024 
1025 	return ret;
1026 }
1027 
1028 static void __driver_attach_async_helper(void *_dev, async_cookie_t cookie)
1029 {
1030 	struct device *dev = _dev;
1031 	struct device_driver *drv;
1032 	int ret = 0;
1033 
1034 	__device_driver_lock(dev, dev->parent);
1035 
1036 	drv = dev->p->async_driver;
1037 
1038 	/*
1039 	 * If device has been removed or someone has already successfully
1040 	 * bound a driver before us just skip the driver probe call.
1041 	 */
1042 	if (!dev->p->dead && !dev->driver)
1043 		ret = driver_probe_device(drv, dev);
1044 
1045 	__device_driver_unlock(dev, dev->parent);
1046 
1047 	dev_dbg(dev, "driver %s async attach completed: %d\n", drv->name, ret);
1048 
1049 	put_device(dev);
1050 }
1051 
1052 static int __driver_attach(struct device *dev, void *data)
1053 {
1054 	struct device_driver *drv = data;
1055 	int ret;
1056 
1057 	/*
1058 	 * Lock device and try to bind to it. We drop the error
1059 	 * here and always return 0, because we need to keep trying
1060 	 * to bind to devices and some drivers will return an error
1061 	 * simply if it didn't support the device.
1062 	 *
1063 	 * driver_probe_device() will spit a warning if there
1064 	 * is an error.
1065 	 */
1066 
1067 	ret = driver_match_device(drv, dev);
1068 	if (ret == 0) {
1069 		/* no match */
1070 		return 0;
1071 	} else if (ret == -EPROBE_DEFER) {
1072 		dev_dbg(dev, "Device match requests probe deferral\n");
1073 		dev->can_match = true;
1074 		driver_deferred_probe_add(dev);
1075 	} else if (ret < 0) {
1076 		dev_dbg(dev, "Bus failed to match device: %d\n", ret);
1077 		return ret;
1078 	} /* ret > 0 means positive match */
1079 
1080 	if (driver_allows_async_probing(drv)) {
1081 		/*
1082 		 * Instead of probing the device synchronously we will
1083 		 * probe it asynchronously to allow for more parallelism.
1084 		 *
1085 		 * We only take the device lock here in order to guarantee
1086 		 * that the dev->driver and async_driver fields are protected
1087 		 */
1088 		dev_dbg(dev, "probing driver %s asynchronously\n", drv->name);
1089 		device_lock(dev);
1090 		if (!dev->driver) {
1091 			get_device(dev);
1092 			dev->p->async_driver = drv;
1093 			async_schedule_dev(__driver_attach_async_helper, dev);
1094 		}
1095 		device_unlock(dev);
1096 		return 0;
1097 	}
1098 
1099 	device_driver_attach(drv, dev);
1100 
1101 	return 0;
1102 }
1103 
1104 /**
1105  * driver_attach - try to bind driver to devices.
1106  * @drv: driver.
1107  *
1108  * Walk the list of devices that the bus has on it and try to
1109  * match the driver with each one.  If driver_probe_device()
1110  * returns 0 and the @dev->driver is set, we've found a
1111  * compatible pair.
1112  */
1113 int driver_attach(struct device_driver *drv)
1114 {
1115 	return bus_for_each_dev(drv->bus, NULL, drv, __driver_attach);
1116 }
1117 EXPORT_SYMBOL_GPL(driver_attach);
1118 
1119 /*
1120  * __device_release_driver() must be called with @dev lock held.
1121  * When called for a USB interface, @dev->parent lock must be held as well.
1122  */
1123 static void __device_release_driver(struct device *dev, struct device *parent)
1124 {
1125 	struct device_driver *drv;
1126 
1127 	drv = dev->driver;
1128 	if (drv) {
1129 		pm_runtime_get_sync(dev);
1130 
1131 		while (device_links_busy(dev)) {
1132 			__device_driver_unlock(dev, parent);
1133 
1134 			device_links_unbind_consumers(dev);
1135 
1136 			__device_driver_lock(dev, parent);
1137 			/*
1138 			 * A concurrent invocation of the same function might
1139 			 * have released the driver successfully while this one
1140 			 * was waiting, so check for that.
1141 			 */
1142 			if (dev->driver != drv) {
1143 				pm_runtime_put(dev);
1144 				return;
1145 			}
1146 		}
1147 
1148 		driver_sysfs_remove(dev);
1149 
1150 		if (dev->bus)
1151 			blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
1152 						     BUS_NOTIFY_UNBIND_DRIVER,
1153 						     dev);
1154 
1155 		pm_runtime_put_sync(dev);
1156 
1157 		device_remove_file(dev, &dev_attr_state_synced);
1158 		device_remove_groups(dev, drv->dev_groups);
1159 
1160 		if (dev->bus && dev->bus->remove)
1161 			dev->bus->remove(dev);
1162 		else if (drv->remove)
1163 			drv->remove(dev);
1164 
1165 		device_links_driver_cleanup(dev);
1166 
1167 		devres_release_all(dev);
1168 		arch_teardown_dma_ops(dev);
1169 		dev->driver = NULL;
1170 		dev_set_drvdata(dev, NULL);
1171 		if (dev->pm_domain && dev->pm_domain->dismiss)
1172 			dev->pm_domain->dismiss(dev);
1173 		pm_runtime_reinit(dev);
1174 		dev_pm_set_driver_flags(dev, 0);
1175 
1176 		klist_remove(&dev->p->knode_driver);
1177 		device_pm_check_callbacks(dev);
1178 		if (dev->bus)
1179 			blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
1180 						     BUS_NOTIFY_UNBOUND_DRIVER,
1181 						     dev);
1182 
1183 		kobject_uevent(&dev->kobj, KOBJ_UNBIND);
1184 	}
1185 }
1186 
1187 void device_release_driver_internal(struct device *dev,
1188 				    struct device_driver *drv,
1189 				    struct device *parent)
1190 {
1191 	__device_driver_lock(dev, parent);
1192 
1193 	if (!drv || drv == dev->driver)
1194 		__device_release_driver(dev, parent);
1195 
1196 	__device_driver_unlock(dev, parent);
1197 }
1198 
1199 /**
1200  * device_release_driver - manually detach device from driver.
1201  * @dev: device.
1202  *
1203  * Manually detach device from driver.
1204  * When called for a USB interface, @dev->parent lock must be held.
1205  *
1206  * If this function is to be called with @dev->parent lock held, ensure that
1207  * the device's consumers are unbound in advance or that their locks can be
1208  * acquired under the @dev->parent lock.
1209  */
1210 void device_release_driver(struct device *dev)
1211 {
1212 	/*
1213 	 * If anyone calls device_release_driver() recursively from
1214 	 * within their ->remove callback for the same device, they
1215 	 * will deadlock right here.
1216 	 */
1217 	device_release_driver_internal(dev, NULL, NULL);
1218 }
1219 EXPORT_SYMBOL_GPL(device_release_driver);
1220 
1221 /**
1222  * device_driver_detach - detach driver from a specific device
1223  * @dev: device to detach driver from
1224  *
1225  * Detach driver from device. Will acquire both @dev lock and @dev->parent
1226  * lock if needed.
1227  */
1228 void device_driver_detach(struct device *dev)
1229 {
1230 	device_release_driver_internal(dev, NULL, dev->parent);
1231 }
1232 
1233 /**
1234  * driver_detach - detach driver from all devices it controls.
1235  * @drv: driver.
1236  */
1237 void driver_detach(struct device_driver *drv)
1238 {
1239 	struct device_private *dev_prv;
1240 	struct device *dev;
1241 
1242 	if (driver_allows_async_probing(drv))
1243 		async_synchronize_full();
1244 
1245 	for (;;) {
1246 		spin_lock(&drv->p->klist_devices.k_lock);
1247 		if (list_empty(&drv->p->klist_devices.k_list)) {
1248 			spin_unlock(&drv->p->klist_devices.k_lock);
1249 			break;
1250 		}
1251 		dev_prv = list_last_entry(&drv->p->klist_devices.k_list,
1252 				     struct device_private,
1253 				     knode_driver.n_node);
1254 		dev = dev_prv->device;
1255 		get_device(dev);
1256 		spin_unlock(&drv->p->klist_devices.k_lock);
1257 		device_release_driver_internal(dev, drv, dev->parent);
1258 		put_device(dev);
1259 	}
1260 }
1261