xref: /linux/drivers/base/dd.c (revision 8a1ed14ebf8c4e916fac8cb34b1eebbe60624db4)
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 <gregkh@suse.de>
16  * Copyright (c) 2007-2009 Novell Inc.
17  */
18 
19 #include <linux/device.h>
20 #include <linux/delay.h>
21 #include <linux/dma-mapping.h>
22 #include <linux/init.h>
23 #include <linux/module.h>
24 #include <linux/kthread.h>
25 #include <linux/wait.h>
26 #include <linux/async.h>
27 #include <linux/pm_runtime.h>
28 #include <linux/pinctrl/devinfo.h>
29 
30 #include "base.h"
31 #include "power/power.h"
32 
33 /*
34  * Deferred Probe infrastructure.
35  *
36  * Sometimes driver probe order matters, but the kernel doesn't always have
37  * dependency information which means some drivers will get probed before a
38  * resource it depends on is available.  For example, an SDHCI driver may
39  * first need a GPIO line from an i2c GPIO controller before it can be
40  * initialized.  If a required resource is not available yet, a driver can
41  * request probing to be deferred by returning -EPROBE_DEFER from its probe hook
42  *
43  * Deferred probe maintains two lists of devices, a pending list and an active
44  * list.  A driver returning -EPROBE_DEFER causes the device to be added to the
45  * pending list.  A successful driver probe will trigger moving all devices
46  * from the pending to the active list so that the workqueue will eventually
47  * retry them.
48  *
49  * The deferred_probe_mutex must be held any time the deferred_probe_*_list
50  * of the (struct device*)->p->deferred_probe pointers are manipulated
51  */
52 static DEFINE_MUTEX(deferred_probe_mutex);
53 static LIST_HEAD(deferred_probe_pending_list);
54 static LIST_HEAD(deferred_probe_active_list);
55 static atomic_t deferred_trigger_count = ATOMIC_INIT(0);
56 
57 /*
58  * In some cases, like suspend to RAM or hibernation, It might be reasonable
59  * to prohibit probing of devices as it could be unsafe.
60  * Once defer_all_probes is true all drivers probes will be forcibly deferred.
61  */
62 static bool defer_all_probes;
63 
64 /*
65  * deferred_probe_work_func() - Retry probing devices in the active list.
66  */
67 static void deferred_probe_work_func(struct work_struct *work)
68 {
69 	struct device *dev;
70 	struct device_private *private;
71 	/*
72 	 * This block processes every device in the deferred 'active' list.
73 	 * Each device is removed from the active list and passed to
74 	 * bus_probe_device() to re-attempt the probe.  The loop continues
75 	 * until every device in the active list is removed and retried.
76 	 *
77 	 * Note: Once the device is removed from the list and the mutex is
78 	 * released, it is possible for the device get freed by another thread
79 	 * and cause a illegal pointer dereference.  This code uses
80 	 * get/put_device() to ensure the device structure cannot disappear
81 	 * from under our feet.
82 	 */
83 	mutex_lock(&deferred_probe_mutex);
84 	while (!list_empty(&deferred_probe_active_list)) {
85 		private = list_first_entry(&deferred_probe_active_list,
86 					typeof(*dev->p), deferred_probe);
87 		dev = private->device;
88 		list_del_init(&private->deferred_probe);
89 
90 		get_device(dev);
91 
92 		/*
93 		 * Drop the mutex while probing each device; the probe path may
94 		 * manipulate the deferred list
95 		 */
96 		mutex_unlock(&deferred_probe_mutex);
97 
98 		/*
99 		 * Force the device to the end of the dpm_list since
100 		 * the PM code assumes that the order we add things to
101 		 * the list is a good order for suspend but deferred
102 		 * probe makes that very unsafe.
103 		 */
104 		device_pm_move_to_tail(dev);
105 
106 		dev_dbg(dev, "Retrying from deferred list\n");
107 		bus_probe_device(dev);
108 		mutex_lock(&deferred_probe_mutex);
109 
110 		put_device(dev);
111 	}
112 	mutex_unlock(&deferred_probe_mutex);
113 }
114 static DECLARE_WORK(deferred_probe_work, deferred_probe_work_func);
115 
116 static void driver_deferred_probe_add(struct device *dev)
117 {
118 	mutex_lock(&deferred_probe_mutex);
119 	if (list_empty(&dev->p->deferred_probe)) {
120 		dev_dbg(dev, "Added to deferred list\n");
121 		list_add_tail(&dev->p->deferred_probe, &deferred_probe_pending_list);
122 	}
123 	mutex_unlock(&deferred_probe_mutex);
124 }
125 
126 void driver_deferred_probe_del(struct device *dev)
127 {
128 	mutex_lock(&deferred_probe_mutex);
129 	if (!list_empty(&dev->p->deferred_probe)) {
130 		dev_dbg(dev, "Removed from deferred list\n");
131 		list_del_init(&dev->p->deferred_probe);
132 	}
133 	mutex_unlock(&deferred_probe_mutex);
134 }
135 
136 static bool driver_deferred_probe_enable = false;
137 /**
138  * driver_deferred_probe_trigger() - Kick off re-probing deferred devices
139  *
140  * This functions moves all devices from the pending list to the active
141  * list and schedules the deferred probe workqueue to process them.  It
142  * should be called anytime a driver is successfully bound to a device.
143  *
144  * Note, there is a race condition in multi-threaded probe. In the case where
145  * more than one device is probing at the same time, it is possible for one
146  * probe to complete successfully while another is about to defer. If the second
147  * depends on the first, then it will get put on the pending list after the
148  * trigger event has already occurred and will be stuck there.
149  *
150  * The atomic 'deferred_trigger_count' is used to determine if a successful
151  * trigger has occurred in the midst of probing a driver. If the trigger count
152  * changes in the midst of a probe, then deferred processing should be triggered
153  * again.
154  */
155 static void driver_deferred_probe_trigger(void)
156 {
157 	if (!driver_deferred_probe_enable)
158 		return;
159 
160 	/*
161 	 * A successful probe means that all the devices in the pending list
162 	 * should be triggered to be reprobed.  Move all the deferred devices
163 	 * into the active list so they can be retried by the workqueue
164 	 */
165 	mutex_lock(&deferred_probe_mutex);
166 	atomic_inc(&deferred_trigger_count);
167 	list_splice_tail_init(&deferred_probe_pending_list,
168 			      &deferred_probe_active_list);
169 	mutex_unlock(&deferred_probe_mutex);
170 
171 	/*
172 	 * Kick the re-probe thread.  It may already be scheduled, but it is
173 	 * safe to kick it again.
174 	 */
175 	schedule_work(&deferred_probe_work);
176 }
177 
178 /**
179  * device_block_probing() - Block/defere device's probes
180  *
181  *	It will disable probing of devices and defer their probes instead.
182  */
183 void device_block_probing(void)
184 {
185 	defer_all_probes = true;
186 	/* sync with probes to avoid races. */
187 	wait_for_device_probe();
188 }
189 
190 /**
191  * device_unblock_probing() - Unblock/enable device's probes
192  *
193  *	It will restore normal behavior and trigger re-probing of deferred
194  * devices.
195  */
196 void device_unblock_probing(void)
197 {
198 	defer_all_probes = false;
199 	driver_deferred_probe_trigger();
200 }
201 
202 /**
203  * deferred_probe_initcall() - Enable probing of deferred devices
204  *
205  * We don't want to get in the way when the bulk of drivers are getting probed.
206  * Instead, this initcall makes sure that deferred probing is delayed until
207  * late_initcall time.
208  */
209 static int deferred_probe_initcall(void)
210 {
211 	driver_deferred_probe_enable = true;
212 	driver_deferred_probe_trigger();
213 	/* Sort as many dependencies as possible before exiting initcalls */
214 	flush_work(&deferred_probe_work);
215 	return 0;
216 }
217 late_initcall(deferred_probe_initcall);
218 
219 /**
220  * device_is_bound() - Check if device is bound to a driver
221  * @dev: device to check
222  *
223  * Returns true if passed device has already finished probing successfully
224  * against a driver.
225  *
226  * This function must be called with the device lock held.
227  */
228 bool device_is_bound(struct device *dev)
229 {
230 	return dev->p && klist_node_attached(&dev->p->knode_driver);
231 }
232 
233 static void driver_bound(struct device *dev)
234 {
235 	if (device_is_bound(dev)) {
236 		printk(KERN_WARNING "%s: device %s already bound\n",
237 			__func__, kobject_name(&dev->kobj));
238 		return;
239 	}
240 
241 	pr_debug("driver: '%s': %s: bound to device '%s'\n", dev->driver->name,
242 		 __func__, dev_name(dev));
243 
244 	klist_add_tail(&dev->p->knode_driver, &dev->driver->p->klist_devices);
245 	device_links_driver_bound(dev);
246 
247 	device_pm_check_callbacks(dev);
248 
249 	/*
250 	 * Make sure the device is no longer in one of the deferred lists and
251 	 * kick off retrying all pending devices
252 	 */
253 	driver_deferred_probe_del(dev);
254 	driver_deferred_probe_trigger();
255 
256 	if (dev->bus)
257 		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
258 					     BUS_NOTIFY_BOUND_DRIVER, dev);
259 
260 	kobject_uevent(&dev->kobj, KOBJ_BIND);
261 }
262 
263 static ssize_t coredump_store(struct device *dev, struct device_attribute *attr,
264 			    const char *buf, size_t count)
265 {
266 	device_lock(dev);
267 	dev->driver->coredump(dev);
268 	device_unlock(dev);
269 
270 	return count;
271 }
272 static DEVICE_ATTR_WO(coredump);
273 
274 static int driver_sysfs_add(struct device *dev)
275 {
276 	int ret;
277 
278 	if (dev->bus)
279 		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
280 					     BUS_NOTIFY_BIND_DRIVER, dev);
281 
282 	ret = sysfs_create_link(&dev->driver->p->kobj, &dev->kobj,
283 				kobject_name(&dev->kobj));
284 	if (ret)
285 		goto fail;
286 
287 	ret = sysfs_create_link(&dev->kobj, &dev->driver->p->kobj,
288 				"driver");
289 	if (ret)
290 		goto rm_dev;
291 
292 	if (!IS_ENABLED(CONFIG_DEV_COREDUMP) || !dev->driver->coredump ||
293 	    !device_create_file(dev, &dev_attr_coredump))
294 		return 0;
295 
296 	sysfs_remove_link(&dev->kobj, "driver");
297 
298 rm_dev:
299 	sysfs_remove_link(&dev->driver->p->kobj,
300 			  kobject_name(&dev->kobj));
301 
302 fail:
303 	return ret;
304 }
305 
306 static void driver_sysfs_remove(struct device *dev)
307 {
308 	struct device_driver *drv = dev->driver;
309 
310 	if (drv) {
311 		if (drv->coredump)
312 			device_remove_file(dev, &dev_attr_coredump);
313 		sysfs_remove_link(&drv->p->kobj, kobject_name(&dev->kobj));
314 		sysfs_remove_link(&dev->kobj, "driver");
315 	}
316 }
317 
318 /**
319  * device_bind_driver - bind a driver to one device.
320  * @dev: device.
321  *
322  * Allow manual attachment of a driver to a device.
323  * Caller must have already set @dev->driver.
324  *
325  * Note that this does not modify the bus reference count
326  * nor take the bus's rwsem. Please verify those are accounted
327  * for before calling this. (It is ok to call with no other effort
328  * from a driver's probe() method.)
329  *
330  * This function must be called with the device lock held.
331  */
332 int device_bind_driver(struct device *dev)
333 {
334 	int ret;
335 
336 	ret = driver_sysfs_add(dev);
337 	if (!ret)
338 		driver_bound(dev);
339 	else if (dev->bus)
340 		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
341 					     BUS_NOTIFY_DRIVER_NOT_BOUND, dev);
342 	return ret;
343 }
344 EXPORT_SYMBOL_GPL(device_bind_driver);
345 
346 static atomic_t probe_count = ATOMIC_INIT(0);
347 static DECLARE_WAIT_QUEUE_HEAD(probe_waitqueue);
348 
349 static void driver_deferred_probe_add_trigger(struct device *dev,
350 					      int local_trigger_count)
351 {
352 	driver_deferred_probe_add(dev);
353 	/* Did a trigger occur while probing? Need to re-trigger if yes */
354 	if (local_trigger_count != atomic_read(&deferred_trigger_count))
355 		driver_deferred_probe_trigger();
356 }
357 
358 static int really_probe(struct device *dev, struct device_driver *drv)
359 {
360 	int ret = -EPROBE_DEFER;
361 	int local_trigger_count = atomic_read(&deferred_trigger_count);
362 	bool test_remove = IS_ENABLED(CONFIG_DEBUG_TEST_DRIVER_REMOVE) &&
363 			   !drv->suppress_bind_attrs;
364 
365 	if (defer_all_probes) {
366 		/*
367 		 * Value of defer_all_probes can be set only by
368 		 * device_defer_all_probes_enable() which, in turn, will call
369 		 * wait_for_device_probe() right after that to avoid any races.
370 		 */
371 		dev_dbg(dev, "Driver %s force probe deferral\n", drv->name);
372 		driver_deferred_probe_add(dev);
373 		return ret;
374 	}
375 
376 	ret = device_links_check_suppliers(dev);
377 	if (ret == -EPROBE_DEFER)
378 		driver_deferred_probe_add_trigger(dev, local_trigger_count);
379 	if (ret)
380 		return ret;
381 
382 	atomic_inc(&probe_count);
383 	pr_debug("bus: '%s': %s: probing driver %s with device %s\n",
384 		 drv->bus->name, __func__, drv->name, dev_name(dev));
385 	WARN_ON(!list_empty(&dev->devres_head));
386 
387 re_probe:
388 	dev->driver = drv;
389 
390 	/* If using pinctrl, bind pins now before probing */
391 	ret = pinctrl_bind_pins(dev);
392 	if (ret)
393 		goto pinctrl_bind_failed;
394 
395 	ret = dma_configure(dev);
396 	if (ret)
397 		goto dma_failed;
398 
399 	if (driver_sysfs_add(dev)) {
400 		printk(KERN_ERR "%s: driver_sysfs_add(%s) failed\n",
401 			__func__, dev_name(dev));
402 		goto probe_failed;
403 	}
404 
405 	if (dev->pm_domain && dev->pm_domain->activate) {
406 		ret = dev->pm_domain->activate(dev);
407 		if (ret)
408 			goto probe_failed;
409 	}
410 
411 	/*
412 	 * Ensure devices are listed in devices_kset in correct order
413 	 * It's important to move Dev to the end of devices_kset before
414 	 * calling .probe, because it could be recursive and parent Dev
415 	 * should always go first
416 	 */
417 	devices_kset_move_last(dev);
418 
419 	if (dev->bus->probe) {
420 		ret = dev->bus->probe(dev);
421 		if (ret)
422 			goto probe_failed;
423 	} else if (drv->probe) {
424 		ret = drv->probe(dev);
425 		if (ret)
426 			goto probe_failed;
427 	}
428 
429 	if (test_remove) {
430 		test_remove = false;
431 
432 		if (dev->bus->remove)
433 			dev->bus->remove(dev);
434 		else if (drv->remove)
435 			drv->remove(dev);
436 
437 		devres_release_all(dev);
438 		driver_sysfs_remove(dev);
439 		dev->driver = NULL;
440 		dev_set_drvdata(dev, NULL);
441 		if (dev->pm_domain && dev->pm_domain->dismiss)
442 			dev->pm_domain->dismiss(dev);
443 		pm_runtime_reinit(dev);
444 
445 		goto re_probe;
446 	}
447 
448 	pinctrl_init_done(dev);
449 
450 	if (dev->pm_domain && dev->pm_domain->sync)
451 		dev->pm_domain->sync(dev);
452 
453 	driver_bound(dev);
454 	ret = 1;
455 	pr_debug("bus: '%s': %s: bound device %s to driver %s\n",
456 		 drv->bus->name, __func__, dev_name(dev), drv->name);
457 	goto done;
458 
459 probe_failed:
460 	dma_deconfigure(dev);
461 dma_failed:
462 	if (dev->bus)
463 		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
464 					     BUS_NOTIFY_DRIVER_NOT_BOUND, dev);
465 pinctrl_bind_failed:
466 	device_links_no_driver(dev);
467 	devres_release_all(dev);
468 	driver_sysfs_remove(dev);
469 	dev->driver = NULL;
470 	dev_set_drvdata(dev, NULL);
471 	if (dev->pm_domain && dev->pm_domain->dismiss)
472 		dev->pm_domain->dismiss(dev);
473 	pm_runtime_reinit(dev);
474 	dev_pm_set_driver_flags(dev, 0);
475 
476 	switch (ret) {
477 	case -EPROBE_DEFER:
478 		/* Driver requested deferred probing */
479 		dev_dbg(dev, "Driver %s requests probe deferral\n", drv->name);
480 		driver_deferred_probe_add_trigger(dev, local_trigger_count);
481 		break;
482 	case -ENODEV:
483 	case -ENXIO:
484 		pr_debug("%s: probe of %s rejects match %d\n",
485 			 drv->name, dev_name(dev), ret);
486 		break;
487 	default:
488 		/* driver matched but the probe failed */
489 		printk(KERN_WARNING
490 		       "%s: probe of %s failed with error %d\n",
491 		       drv->name, dev_name(dev), ret);
492 	}
493 	/*
494 	 * Ignore errors returned by ->probe so that the next driver can try
495 	 * its luck.
496 	 */
497 	ret = 0;
498 done:
499 	atomic_dec(&probe_count);
500 	wake_up(&probe_waitqueue);
501 	return ret;
502 }
503 
504 /*
505  * For initcall_debug, show the driver probe time.
506  */
507 static int really_probe_debug(struct device *dev, struct device_driver *drv)
508 {
509 	ktime_t calltime, delta, rettime;
510 	int ret;
511 
512 	calltime = ktime_get();
513 	ret = really_probe(dev, drv);
514 	rettime = ktime_get();
515 	delta = ktime_sub(rettime, calltime);
516 	printk(KERN_DEBUG "probe of %s returned %d after %lld usecs\n",
517 	       dev_name(dev), ret, (s64) ktime_to_us(delta));
518 	return ret;
519 }
520 
521 /**
522  * driver_probe_done
523  * Determine if the probe sequence is finished or not.
524  *
525  * Should somehow figure out how to use a semaphore, not an atomic variable...
526  */
527 int driver_probe_done(void)
528 {
529 	pr_debug("%s: probe_count = %d\n", __func__,
530 		 atomic_read(&probe_count));
531 	if (atomic_read(&probe_count))
532 		return -EBUSY;
533 	return 0;
534 }
535 
536 /**
537  * wait_for_device_probe
538  * Wait for device probing to be completed.
539  */
540 void wait_for_device_probe(void)
541 {
542 	/* wait for the deferred probe workqueue to finish */
543 	flush_work(&deferred_probe_work);
544 
545 	/* wait for the known devices to complete their probing */
546 	wait_event(probe_waitqueue, atomic_read(&probe_count) == 0);
547 	async_synchronize_full();
548 }
549 EXPORT_SYMBOL_GPL(wait_for_device_probe);
550 
551 /**
552  * driver_probe_device - attempt to bind device & driver together
553  * @drv: driver to bind a device to
554  * @dev: device to try to bind to the driver
555  *
556  * This function returns -ENODEV if the device is not registered,
557  * 1 if the device is bound successfully and 0 otherwise.
558  *
559  * This function must be called with @dev lock held.  When called for a
560  * USB interface, @dev->parent lock must be held as well.
561  *
562  * If the device has a parent, runtime-resume the parent before driver probing.
563  */
564 int driver_probe_device(struct device_driver *drv, struct device *dev)
565 {
566 	int ret = 0;
567 
568 	if (!device_is_registered(dev))
569 		return -ENODEV;
570 
571 	pr_debug("bus: '%s': %s: matched device %s with driver %s\n",
572 		 drv->bus->name, __func__, dev_name(dev), drv->name);
573 
574 	pm_runtime_get_suppliers(dev);
575 	if (dev->parent)
576 		pm_runtime_get_sync(dev->parent);
577 
578 	pm_runtime_barrier(dev);
579 	if (initcall_debug)
580 		ret = really_probe_debug(dev, drv);
581 	else
582 		ret = really_probe(dev, drv);
583 	pm_request_idle(dev);
584 
585 	if (dev->parent)
586 		pm_runtime_put(dev->parent);
587 
588 	pm_runtime_put_suppliers(dev);
589 	return ret;
590 }
591 
592 bool driver_allows_async_probing(struct device_driver *drv)
593 {
594 	switch (drv->probe_type) {
595 	case PROBE_PREFER_ASYNCHRONOUS:
596 		return true;
597 
598 	case PROBE_FORCE_SYNCHRONOUS:
599 		return false;
600 
601 	default:
602 		if (module_requested_async_probing(drv->owner))
603 			return true;
604 
605 		return false;
606 	}
607 }
608 
609 struct device_attach_data {
610 	struct device *dev;
611 
612 	/*
613 	 * Indicates whether we are are considering asynchronous probing or
614 	 * not. Only initial binding after device or driver registration
615 	 * (including deferral processing) may be done asynchronously, the
616 	 * rest is always synchronous, as we expect it is being done by
617 	 * request from userspace.
618 	 */
619 	bool check_async;
620 
621 	/*
622 	 * Indicates if we are binding synchronous or asynchronous drivers.
623 	 * When asynchronous probing is enabled we'll execute 2 passes
624 	 * over drivers: first pass doing synchronous probing and second
625 	 * doing asynchronous probing (if synchronous did not succeed -
626 	 * most likely because there was no driver requiring synchronous
627 	 * probing - and we found asynchronous driver during first pass).
628 	 * The 2 passes are done because we can't shoot asynchronous
629 	 * probe for given device and driver from bus_for_each_drv() since
630 	 * driver pointer is not guaranteed to stay valid once
631 	 * bus_for_each_drv() iterates to the next driver on the bus.
632 	 */
633 	bool want_async;
634 
635 	/*
636 	 * We'll set have_async to 'true' if, while scanning for matching
637 	 * driver, we'll encounter one that requests asynchronous probing.
638 	 */
639 	bool have_async;
640 };
641 
642 static int __device_attach_driver(struct device_driver *drv, void *_data)
643 {
644 	struct device_attach_data *data = _data;
645 	struct device *dev = data->dev;
646 	bool async_allowed;
647 	int ret;
648 
649 	/*
650 	 * Check if device has already been claimed. This may
651 	 * happen with driver loading, device discovery/registration,
652 	 * and deferred probe processing happens all at once with
653 	 * multiple threads.
654 	 */
655 	if (dev->driver)
656 		return -EBUSY;
657 
658 	ret = driver_match_device(drv, dev);
659 	if (ret == 0) {
660 		/* no match */
661 		return 0;
662 	} else if (ret == -EPROBE_DEFER) {
663 		dev_dbg(dev, "Device match requests probe deferral\n");
664 		driver_deferred_probe_add(dev);
665 	} else if (ret < 0) {
666 		dev_dbg(dev, "Bus failed to match device: %d", ret);
667 		return ret;
668 	} /* ret > 0 means positive match */
669 
670 	async_allowed = driver_allows_async_probing(drv);
671 
672 	if (async_allowed)
673 		data->have_async = true;
674 
675 	if (data->check_async && async_allowed != data->want_async)
676 		return 0;
677 
678 	return driver_probe_device(drv, dev);
679 }
680 
681 static void __device_attach_async_helper(void *_dev, async_cookie_t cookie)
682 {
683 	struct device *dev = _dev;
684 	struct device_attach_data data = {
685 		.dev		= dev,
686 		.check_async	= true,
687 		.want_async	= true,
688 	};
689 
690 	device_lock(dev);
691 
692 	if (dev->parent)
693 		pm_runtime_get_sync(dev->parent);
694 
695 	bus_for_each_drv(dev->bus, NULL, &data, __device_attach_driver);
696 	dev_dbg(dev, "async probe completed\n");
697 
698 	pm_request_idle(dev);
699 
700 	if (dev->parent)
701 		pm_runtime_put(dev->parent);
702 
703 	device_unlock(dev);
704 
705 	put_device(dev);
706 }
707 
708 static int __device_attach(struct device *dev, bool allow_async)
709 {
710 	int ret = 0;
711 
712 	device_lock(dev);
713 	if (dev->driver) {
714 		if (device_is_bound(dev)) {
715 			ret = 1;
716 			goto out_unlock;
717 		}
718 		ret = device_bind_driver(dev);
719 		if (ret == 0)
720 			ret = 1;
721 		else {
722 			dev->driver = NULL;
723 			ret = 0;
724 		}
725 	} else {
726 		struct device_attach_data data = {
727 			.dev = dev,
728 			.check_async = allow_async,
729 			.want_async = false,
730 		};
731 
732 		if (dev->parent)
733 			pm_runtime_get_sync(dev->parent);
734 
735 		ret = bus_for_each_drv(dev->bus, NULL, &data,
736 					__device_attach_driver);
737 		if (!ret && allow_async && data.have_async) {
738 			/*
739 			 * If we could not find appropriate driver
740 			 * synchronously and we are allowed to do
741 			 * async probes and there are drivers that
742 			 * want to probe asynchronously, we'll
743 			 * try them.
744 			 */
745 			dev_dbg(dev, "scheduling asynchronous probe\n");
746 			get_device(dev);
747 			async_schedule(__device_attach_async_helper, dev);
748 		} else {
749 			pm_request_idle(dev);
750 		}
751 
752 		if (dev->parent)
753 			pm_runtime_put(dev->parent);
754 	}
755 out_unlock:
756 	device_unlock(dev);
757 	return ret;
758 }
759 
760 /**
761  * device_attach - try to attach device to a driver.
762  * @dev: device.
763  *
764  * Walk the list of drivers that the bus has and call
765  * driver_probe_device() for each pair. If a compatible
766  * pair is found, break out and return.
767  *
768  * Returns 1 if the device was bound to a driver;
769  * 0 if no matching driver was found;
770  * -ENODEV if the device is not registered.
771  *
772  * When called for a USB interface, @dev->parent lock must be held.
773  */
774 int device_attach(struct device *dev)
775 {
776 	return __device_attach(dev, false);
777 }
778 EXPORT_SYMBOL_GPL(device_attach);
779 
780 void device_initial_probe(struct device *dev)
781 {
782 	__device_attach(dev, true);
783 }
784 
785 static int __driver_attach(struct device *dev, void *data)
786 {
787 	struct device_driver *drv = data;
788 	int ret;
789 
790 	/*
791 	 * Lock device and try to bind to it. We drop the error
792 	 * here and always return 0, because we need to keep trying
793 	 * to bind to devices and some drivers will return an error
794 	 * simply if it didn't support the device.
795 	 *
796 	 * driver_probe_device() will spit a warning if there
797 	 * is an error.
798 	 */
799 
800 	ret = driver_match_device(drv, dev);
801 	if (ret == 0) {
802 		/* no match */
803 		return 0;
804 	} else if (ret == -EPROBE_DEFER) {
805 		dev_dbg(dev, "Device match requests probe deferral\n");
806 		driver_deferred_probe_add(dev);
807 	} else if (ret < 0) {
808 		dev_dbg(dev, "Bus failed to match device: %d", ret);
809 		return ret;
810 	} /* ret > 0 means positive match */
811 
812 	if (dev->parent && dev->bus->need_parent_lock)
813 		device_lock(dev->parent);
814 	device_lock(dev);
815 	if (!dev->driver)
816 		driver_probe_device(drv, dev);
817 	device_unlock(dev);
818 	if (dev->parent && dev->bus->need_parent_lock)
819 		device_unlock(dev->parent);
820 
821 	return 0;
822 }
823 
824 /**
825  * driver_attach - try to bind driver to devices.
826  * @drv: driver.
827  *
828  * Walk the list of devices that the bus has on it and try to
829  * match the driver with each one.  If driver_probe_device()
830  * returns 0 and the @dev->driver is set, we've found a
831  * compatible pair.
832  */
833 int driver_attach(struct device_driver *drv)
834 {
835 	return bus_for_each_dev(drv->bus, NULL, drv, __driver_attach);
836 }
837 EXPORT_SYMBOL_GPL(driver_attach);
838 
839 /*
840  * __device_release_driver() must be called with @dev lock held.
841  * When called for a USB interface, @dev->parent lock must be held as well.
842  */
843 static void __device_release_driver(struct device *dev, struct device *parent)
844 {
845 	struct device_driver *drv;
846 
847 	drv = dev->driver;
848 	if (drv) {
849 		if (driver_allows_async_probing(drv))
850 			async_synchronize_full();
851 
852 		while (device_links_busy(dev)) {
853 			device_unlock(dev);
854 			if (parent)
855 				device_unlock(parent);
856 
857 			device_links_unbind_consumers(dev);
858 			if (parent)
859 				device_lock(parent);
860 
861 			device_lock(dev);
862 			/*
863 			 * A concurrent invocation of the same function might
864 			 * have released the driver successfully while this one
865 			 * was waiting, so check for that.
866 			 */
867 			if (dev->driver != drv)
868 				return;
869 		}
870 
871 		pm_runtime_get_sync(dev);
872 		pm_runtime_clean_up_links(dev);
873 
874 		driver_sysfs_remove(dev);
875 
876 		if (dev->bus)
877 			blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
878 						     BUS_NOTIFY_UNBIND_DRIVER,
879 						     dev);
880 
881 		pm_runtime_put_sync(dev);
882 
883 		if (dev->bus && dev->bus->remove)
884 			dev->bus->remove(dev);
885 		else if (drv->remove)
886 			drv->remove(dev);
887 
888 		device_links_driver_cleanup(dev);
889 		dma_deconfigure(dev);
890 
891 		devres_release_all(dev);
892 		dev->driver = NULL;
893 		dev_set_drvdata(dev, NULL);
894 		if (dev->pm_domain && dev->pm_domain->dismiss)
895 			dev->pm_domain->dismiss(dev);
896 		pm_runtime_reinit(dev);
897 		dev_pm_set_driver_flags(dev, 0);
898 
899 		klist_remove(&dev->p->knode_driver);
900 		device_pm_check_callbacks(dev);
901 		if (dev->bus)
902 			blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
903 						     BUS_NOTIFY_UNBOUND_DRIVER,
904 						     dev);
905 
906 		kobject_uevent(&dev->kobj, KOBJ_UNBIND);
907 	}
908 }
909 
910 void device_release_driver_internal(struct device *dev,
911 				    struct device_driver *drv,
912 				    struct device *parent)
913 {
914 	if (parent && dev->bus->need_parent_lock)
915 		device_lock(parent);
916 
917 	device_lock(dev);
918 	if (!drv || drv == dev->driver)
919 		__device_release_driver(dev, parent);
920 
921 	device_unlock(dev);
922 	if (parent && dev->bus->need_parent_lock)
923 		device_unlock(parent);
924 }
925 
926 /**
927  * device_release_driver - manually detach device from driver.
928  * @dev: device.
929  *
930  * Manually detach device from driver.
931  * When called for a USB interface, @dev->parent lock must be held.
932  *
933  * If this function is to be called with @dev->parent lock held, ensure that
934  * the device's consumers are unbound in advance or that their locks can be
935  * acquired under the @dev->parent lock.
936  */
937 void device_release_driver(struct device *dev)
938 {
939 	/*
940 	 * If anyone calls device_release_driver() recursively from
941 	 * within their ->remove callback for the same device, they
942 	 * will deadlock right here.
943 	 */
944 	device_release_driver_internal(dev, NULL, NULL);
945 }
946 EXPORT_SYMBOL_GPL(device_release_driver);
947 
948 /**
949  * driver_detach - detach driver from all devices it controls.
950  * @drv: driver.
951  */
952 void driver_detach(struct device_driver *drv)
953 {
954 	struct device_private *dev_prv;
955 	struct device *dev;
956 
957 	for (;;) {
958 		spin_lock(&drv->p->klist_devices.k_lock);
959 		if (list_empty(&drv->p->klist_devices.k_list)) {
960 			spin_unlock(&drv->p->klist_devices.k_lock);
961 			break;
962 		}
963 		dev_prv = list_entry(drv->p->klist_devices.k_list.prev,
964 				     struct device_private,
965 				     knode_driver.n_node);
966 		dev = dev_prv->device;
967 		get_device(dev);
968 		spin_unlock(&drv->p->klist_devices.k_lock);
969 		device_release_driver_internal(dev, drv, dev->parent);
970 		put_device(dev);
971 	}
972 }
973