xref: /linux/drivers/base/core.c (revision 024480bf8d75bd16894c5b0eb6082b6e6dae4970)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * drivers/base/core.c - core driver model code (device registration, etc)
4  *
5  * Copyright (c) 2002-3 Patrick Mochel
6  * Copyright (c) 2002-3 Open Source Development Labs
7  * Copyright (c) 2006 Greg Kroah-Hartman <gregkh@suse.de>
8  * Copyright (c) 2006 Novell, Inc.
9  */
10 
11 #include <linux/acpi.h>
12 #include <linux/blkdev.h>
13 #include <linux/cleanup.h>
14 #include <linux/cpufreq.h>
15 #include <linux/device.h>
16 #include <linux/dma-map-ops.h> /* for dma_default_coherent */
17 #include <linux/err.h>
18 #include <linux/fwnode.h>
19 #include <linux/init.h>
20 #include <linux/kdev_t.h>
21 #include <linux/kstrtox.h>
22 #include <linux/module.h>
23 #include <linux/mutex.h>
24 #include <linux/netdevice.h>
25 #include <linux/notifier.h>
26 #include <linux/of.h>
27 #include <linux/of_device.h>
28 #include <linux/pm_runtime.h>
29 #include <linux/sched/mm.h>
30 #include <linux/sched/signal.h>
31 #include <linux/slab.h>
32 #include <linux/string_helpers.h>
33 #include <linux/swiotlb.h>
34 #include <linux/sysfs.h>
35 
36 #include "base.h"
37 #include "physical_location.h"
38 #include "power/power.h"
39 
40 /* Device links support. */
41 static LIST_HEAD(deferred_sync);
42 static unsigned int defer_sync_state_count = 1;
43 static DEFINE_MUTEX(fwnode_link_lock);
44 static bool fw_devlink_is_permissive(void);
45 static void __fw_devlink_link_to_consumers(struct device *dev);
46 static bool fw_devlink_drv_reg_done;
47 static bool fw_devlink_best_effort;
48 static struct workqueue_struct *device_link_wq;
49 
50 /**
51  * __fwnode_link_add - Create a link between two fwnode_handles.
52  * @con: Consumer end of the link.
53  * @sup: Supplier end of the link.
54  * @flags: Link flags.
55  *
56  * Create a fwnode link between fwnode handles @con and @sup. The fwnode link
57  * represents the detail that the firmware lists @sup fwnode as supplying a
58  * resource to @con.
59  *
60  * The driver core will use the fwnode link to create a device link between the
61  * two device objects corresponding to @con and @sup when they are created. The
62  * driver core will automatically delete the fwnode link between @con and @sup
63  * after doing that.
64  *
65  * Attempts to create duplicate links between the same pair of fwnode handles
66  * are ignored and there is no reference counting.
67  */
68 static int __fwnode_link_add(struct fwnode_handle *con,
69 			     struct fwnode_handle *sup, u8 flags)
70 {
71 	struct fwnode_link *link;
72 
73 	list_for_each_entry(link, &sup->consumers, s_hook)
74 		if (link->consumer == con) {
75 			link->flags |= flags;
76 			return 0;
77 		}
78 
79 	link = kzalloc_obj(*link);
80 	if (!link)
81 		return -ENOMEM;
82 
83 	link->supplier = sup;
84 	INIT_LIST_HEAD(&link->s_hook);
85 	link->consumer = con;
86 	INIT_LIST_HEAD(&link->c_hook);
87 	link->flags = flags;
88 
89 	list_add(&link->s_hook, &sup->consumers);
90 	list_add(&link->c_hook, &con->suppliers);
91 	pr_debug("%pfwf Linked as a fwnode consumer to %pfwf\n",
92 		 con, sup);
93 
94 	return 0;
95 }
96 
97 int fwnode_link_add(struct fwnode_handle *con, struct fwnode_handle *sup,
98 		    u8 flags)
99 {
100 	guard(mutex)(&fwnode_link_lock);
101 
102 	return __fwnode_link_add(con, sup, flags);
103 }
104 
105 /**
106  * __fwnode_link_del - Delete a link between two fwnode_handles.
107  * @link: the fwnode_link to be deleted
108  *
109  * The fwnode_link_lock needs to be held when this function is called.
110  */
111 static void __fwnode_link_del(struct fwnode_link *link)
112 {
113 	pr_debug("%pfwf Dropping the fwnode link to %pfwf\n",
114 		 link->consumer, link->supplier);
115 	list_del(&link->s_hook);
116 	list_del(&link->c_hook);
117 	kfree(link);
118 }
119 
120 /**
121  * __fwnode_link_cycle - Mark a fwnode link as being part of a cycle.
122  * @link: the fwnode_link to be marked
123  *
124  * The fwnode_link_lock needs to be held when this function is called.
125  */
126 static void __fwnode_link_cycle(struct fwnode_link *link)
127 {
128 	pr_debug("%pfwf: cycle: depends on %pfwf\n",
129 		 link->consumer, link->supplier);
130 	link->flags |= FWLINK_FLAG_CYCLE;
131 }
132 
133 /**
134  * fwnode_links_purge_suppliers - Delete all supplier links of fwnode_handle.
135  * @fwnode: fwnode whose supplier links need to be deleted
136  *
137  * Deletes all supplier links connecting directly to @fwnode.
138  */
139 static void fwnode_links_purge_suppliers(struct fwnode_handle *fwnode)
140 {
141 	struct fwnode_link *link, *tmp;
142 
143 	guard(mutex)(&fwnode_link_lock);
144 
145 	list_for_each_entry_safe(link, tmp, &fwnode->suppliers, c_hook)
146 		__fwnode_link_del(link);
147 }
148 
149 /**
150  * fwnode_links_purge_consumers - Delete all consumer links of fwnode_handle.
151  * @fwnode: fwnode whose consumer links need to be deleted
152  *
153  * Deletes all consumer links connecting directly to @fwnode.
154  */
155 static void fwnode_links_purge_consumers(struct fwnode_handle *fwnode)
156 {
157 	struct fwnode_link *link, *tmp;
158 
159 	guard(mutex)(&fwnode_link_lock);
160 
161 	list_for_each_entry_safe(link, tmp, &fwnode->consumers, s_hook)
162 		__fwnode_link_del(link);
163 }
164 
165 /**
166  * fwnode_links_purge - Delete all links connected to a fwnode_handle.
167  * @fwnode: fwnode whose links needs to be deleted
168  *
169  * Deletes all links connecting directly to a fwnode.
170  */
171 void fwnode_links_purge(struct fwnode_handle *fwnode)
172 {
173 	fwnode_links_purge_suppliers(fwnode);
174 	fwnode_links_purge_consumers(fwnode);
175 }
176 
177 void fw_devlink_purge_absent_suppliers(struct fwnode_handle *fwnode)
178 {
179 	struct fwnode_handle *child;
180 
181 	/* Don't purge consumer links of an added child */
182 	if (fwnode->dev)
183 		return;
184 
185 	fwnode_set_flag(fwnode, FWNODE_FLAG_NOT_DEVICE);
186 	fwnode_links_purge_consumers(fwnode);
187 
188 	fwnode_for_each_available_child_node(fwnode, child)
189 		fw_devlink_purge_absent_suppliers(child);
190 }
191 EXPORT_SYMBOL_GPL(fw_devlink_purge_absent_suppliers);
192 
193 /**
194  * __fwnode_links_move_consumers - Move consumer from @from to @to fwnode_handle
195  * @from: move consumers away from this fwnode
196  * @to: move consumers to this fwnode
197  *
198  * Move all consumer links from @from fwnode to @to fwnode.
199  */
200 static void __fwnode_links_move_consumers(struct fwnode_handle *from,
201 					  struct fwnode_handle *to)
202 {
203 	struct fwnode_link *link, *tmp;
204 
205 	list_for_each_entry_safe(link, tmp, &from->consumers, s_hook) {
206 		__fwnode_link_add(link->consumer, to, link->flags);
207 		__fwnode_link_del(link);
208 	}
209 }
210 
211 /**
212  * __fw_devlink_pickup_dangling_consumers - Pick up dangling consumers
213  * @fwnode: fwnode from which to pick up dangling consumers
214  * @new_sup: fwnode of new supplier
215  *
216  * If the @fwnode has a corresponding struct device and the device supports
217  * probing (that is, added to a bus), then we want to let fw_devlink create
218  * MANAGED device links to this device, so leave @fwnode and its descendant's
219  * fwnode links alone.
220  *
221  * Otherwise, move its consumers to the new supplier @new_sup.
222  */
223 static void __fw_devlink_pickup_dangling_consumers(struct fwnode_handle *fwnode,
224 						   struct fwnode_handle *new_sup)
225 {
226 	struct fwnode_handle *child;
227 
228 	if (fwnode->dev && fwnode->dev->bus)
229 		return;
230 
231 	fwnode_set_flag(fwnode, FWNODE_FLAG_NOT_DEVICE);
232 	__fwnode_links_move_consumers(fwnode, new_sup);
233 
234 	fwnode_for_each_available_child_node(fwnode, child)
235 		__fw_devlink_pickup_dangling_consumers(child, new_sup);
236 }
237 
238 static void fw_devlink_pickup_dangling_consumers(struct device *dev)
239 {
240 	struct fwnode_handle *child;
241 
242 	guard(mutex)(&fwnode_link_lock);
243 
244 	fwnode_for_each_available_child_node(dev->fwnode, child)
245 		__fw_devlink_pickup_dangling_consumers(child, dev->fwnode);
246 	__fw_devlink_link_to_consumers(dev);
247 }
248 
249 /**
250  * fw_devlink_refresh_fwnode - Recheck the tree under this firmware node
251  * @fwnode: The fwnode under which the fwnode tree has changed
252  *
253  * This function is mainly meant to adjust the supplier/consumer dependencies
254  * after a fwnode tree overlay has occurred.
255  */
256 void fw_devlink_refresh_fwnode(struct fwnode_handle *fwnode)
257 {
258 	struct device *dev;
259 
260 	/*
261 	 * Find the closest ancestor fwnode that has been converted to a device
262 	 * that can bind to a driver (bus device).
263 	 */
264 	fwnode_handle_get(fwnode);
265 	do {
266 		if (fwnode_test_flag(fwnode, FWNODE_FLAG_NOT_DEVICE))
267 			continue;
268 
269 		dev = get_dev_from_fwnode(fwnode);
270 		if (!dev)
271 			continue;
272 
273 		if (dev->bus)
274 			break;
275 
276 		put_device(dev);
277 	} while ((fwnode = fwnode_get_next_parent(fwnode)));
278 
279 	/*
280 	 * If none of the ancestor fwnodes have (yet) been converted to a device
281 	 * that can bind to a driver, there's nothing to fix up.
282 	 */
283 	if (!fwnode)
284 		return;
285 
286 	WARN(device_is_bound(dev) && dev->links.status != DL_DEV_DRIVER_BOUND,
287 	     "Don't multithread overlaying and probing the same device!\n");
288 
289 	/*
290 	 * If the device has already bound to a driver, then we need to redo
291 	 * some of the work that was done after the device was bound to a
292 	 * driver. If the device hasn't bound to a driver, running things too
293 	 * soon would incorrectly pick up consumers that it shouldn't.
294 	 */
295 	if (dev->links.status == DL_DEV_DRIVER_BOUND) {
296 		fw_devlink_pickup_dangling_consumers(dev);
297 		/*
298 		 * Some of dangling consumers could have been put previously in
299 		 * the deferred probe list due to the unavailability of their
300 		 * suppliers. Those consumers have been picked up and some of
301 		 * their suppliers links have been updated. Time to re-try their
302 		 * probe sequence.
303 		 */
304 		driver_deferred_probe_trigger();
305 	}
306 
307 	put_device(dev);
308 	fwnode_handle_put(fwnode);
309 }
310 
311 static DEFINE_MUTEX(device_links_lock);
312 DEFINE_STATIC_SRCU(device_links_srcu);
313 
314 static inline void device_links_write_lock(void)
315 {
316 	mutex_lock(&device_links_lock);
317 }
318 
319 static inline void device_links_write_unlock(void)
320 {
321 	mutex_unlock(&device_links_lock);
322 }
323 
324 int device_links_read_lock(void) __acquires(&device_links_srcu)
325 {
326 	return srcu_read_lock(&device_links_srcu);
327 }
328 
329 void device_links_read_unlock(int idx) __releases(&device_links_srcu)
330 {
331 	srcu_read_unlock(&device_links_srcu, idx);
332 }
333 
334 int device_links_read_lock_held(void)
335 {
336 	return srcu_read_lock_held(&device_links_srcu);
337 }
338 
339 static void device_link_synchronize_removal(void)
340 {
341 	synchronize_srcu(&device_links_srcu);
342 }
343 
344 static void device_link_remove_from_lists(struct device_link *link)
345 {
346 	list_del_rcu(&link->s_node);
347 	list_del_rcu(&link->c_node);
348 }
349 
350 static bool device_is_ancestor(struct device *dev, struct device *target)
351 {
352 	while (target->parent) {
353 		target = target->parent;
354 		if (dev == target)
355 			return true;
356 	}
357 	return false;
358 }
359 
360 #define DL_MARKER_FLAGS		(DL_FLAG_INFERRED | \
361 				 DL_FLAG_CYCLE | \
362 				 DL_FLAG_MANAGED)
363 bool device_link_flag_is_sync_state_only(u32 flags)
364 {
365 	return (flags & ~DL_MARKER_FLAGS) == DL_FLAG_SYNC_STATE_ONLY;
366 }
367 
368 /**
369  * device_is_dependent - Check if one device depends on another one
370  * @dev: Device to check dependencies for.
371  * @target: Device to check against.
372  *
373  * Check if @target depends on @dev or any device dependent on it (its child or
374  * its consumer etc).  Return 1 if that is the case or 0 otherwise.
375  */
376 static int device_is_dependent(struct device *dev, void *target)
377 {
378 	struct device_link *link;
379 	int ret;
380 
381 	/*
382 	 * The "ancestors" check is needed to catch the case when the target
383 	 * device has not been completely initialized yet and it is still
384 	 * missing from the list of children of its parent device.
385 	 */
386 	if (dev == target || device_is_ancestor(dev, target))
387 		return 1;
388 
389 	ret = device_for_each_child(dev, target, device_is_dependent);
390 	if (ret)
391 		return ret;
392 
393 	list_for_each_entry(link, &dev->links.consumers, s_node) {
394 		if (device_link_flag_is_sync_state_only(link->flags))
395 			continue;
396 
397 		if (link->consumer == target)
398 			return 1;
399 
400 		ret = device_is_dependent(link->consumer, target);
401 		if (ret)
402 			break;
403 	}
404 	return ret;
405 }
406 
407 static void device_link_init_status(struct device_link *link,
408 				    struct device *consumer,
409 				    struct device *supplier)
410 {
411 	switch (supplier->links.status) {
412 	case DL_DEV_PROBING:
413 		switch (consumer->links.status) {
414 		case DL_DEV_PROBING:
415 			/*
416 			 * A consumer driver can create a link to a supplier
417 			 * that has not completed its probing yet as long as it
418 			 * knows that the supplier is already functional (for
419 			 * example, it has just acquired some resources from the
420 			 * supplier).
421 			 */
422 			link->status = DL_STATE_CONSUMER_PROBE;
423 			break;
424 		default:
425 			link->status = DL_STATE_DORMANT;
426 			break;
427 		}
428 		break;
429 	case DL_DEV_DRIVER_BOUND:
430 		switch (consumer->links.status) {
431 		case DL_DEV_PROBING:
432 			link->status = DL_STATE_CONSUMER_PROBE;
433 			break;
434 		case DL_DEV_DRIVER_BOUND:
435 			link->status = DL_STATE_ACTIVE;
436 			break;
437 		default:
438 			link->status = DL_STATE_AVAILABLE;
439 			break;
440 		}
441 		break;
442 	case DL_DEV_UNBINDING:
443 		link->status = DL_STATE_SUPPLIER_UNBIND;
444 		break;
445 	default:
446 		link->status = DL_STATE_DORMANT;
447 		break;
448 	}
449 }
450 
451 static int device_reorder_to_tail(struct device *dev, void *not_used)
452 {
453 	struct device_link *link;
454 
455 	/*
456 	 * Devices that have not been registered yet will be put to the ends
457 	 * of the lists during the registration, so skip them here.
458 	 */
459 	if (device_is_registered(dev))
460 		devices_kset_move_last(dev);
461 
462 	if (device_pm_initialized(dev))
463 		device_pm_move_last(dev);
464 
465 	device_for_each_child(dev, NULL, device_reorder_to_tail);
466 	list_for_each_entry(link, &dev->links.consumers, s_node) {
467 		if (device_link_flag_is_sync_state_only(link->flags))
468 			continue;
469 		device_reorder_to_tail(link->consumer, NULL);
470 	}
471 
472 	return 0;
473 }
474 
475 /**
476  * device_pm_move_to_tail - Move set of devices to the end of device lists
477  * @dev: Device to move
478  *
479  * This is a device_reorder_to_tail() wrapper taking the requisite locks.
480  *
481  * It moves the @dev along with all of its children and all of its consumers
482  * to the ends of the device_kset and dpm_list, recursively.
483  */
484 void device_pm_move_to_tail(struct device *dev)
485 {
486 	int idx;
487 
488 	idx = device_links_read_lock();
489 	device_pm_lock();
490 	device_reorder_to_tail(dev, NULL);
491 	device_pm_unlock();
492 	device_links_read_unlock(idx);
493 }
494 
495 #define to_devlink(dev)	container_of((dev), struct device_link, link_dev)
496 
497 static ssize_t status_show(struct device *dev,
498 			   const struct device_attribute *attr, char *buf)
499 {
500 	const char *output;
501 
502 	switch (to_devlink(dev)->status) {
503 	case DL_STATE_NONE:
504 		output = "not tracked";
505 		break;
506 	case DL_STATE_DORMANT:
507 		output = "dormant";
508 		break;
509 	case DL_STATE_AVAILABLE:
510 		output = "available";
511 		break;
512 	case DL_STATE_CONSUMER_PROBE:
513 		output = "consumer probing";
514 		break;
515 	case DL_STATE_ACTIVE:
516 		output = "active";
517 		break;
518 	case DL_STATE_SUPPLIER_UNBIND:
519 		output = "supplier unbinding";
520 		break;
521 	default:
522 		output = "unknown";
523 		break;
524 	}
525 
526 	return sysfs_emit(buf, "%s\n", output);
527 }
528 static const DEVICE_ATTR_RO(status);
529 
530 static ssize_t auto_remove_on_show(struct device *dev,
531 				   const struct device_attribute *attr, char *buf)
532 {
533 	struct device_link *link = to_devlink(dev);
534 	const char *output;
535 
536 	if (device_link_test(link, DL_FLAG_AUTOREMOVE_SUPPLIER))
537 		output = "supplier unbind";
538 	else if (device_link_test(link, DL_FLAG_AUTOREMOVE_CONSUMER))
539 		output = "consumer unbind";
540 	else
541 		output = "never";
542 
543 	return sysfs_emit(buf, "%s\n", output);
544 }
545 static const DEVICE_ATTR_RO(auto_remove_on);
546 
547 static ssize_t runtime_pm_show(struct device *dev,
548 			       const struct device_attribute *attr, char *buf)
549 {
550 	struct device_link *link = to_devlink(dev);
551 
552 	return sysfs_emit(buf, "%d\n", device_link_test(link, DL_FLAG_PM_RUNTIME));
553 }
554 static const DEVICE_ATTR_RO(runtime_pm);
555 
556 static ssize_t sync_state_only_show(struct device *dev,
557 				    const struct device_attribute *attr, char *buf)
558 {
559 	struct device_link *link = to_devlink(dev);
560 
561 	return sysfs_emit(buf, "%d\n", device_link_test(link, DL_FLAG_SYNC_STATE_ONLY));
562 }
563 static const DEVICE_ATTR_RO(sync_state_only);
564 
565 static const struct attribute *const devlink_attrs[] = {
566 	&dev_attr_status.attr,
567 	&dev_attr_auto_remove_on.attr,
568 	&dev_attr_runtime_pm.attr,
569 	&dev_attr_sync_state_only.attr,
570 	NULL,
571 };
572 ATTRIBUTE_GROUPS(devlink);
573 
574 static void device_link_release_fn(struct work_struct *work)
575 {
576 	struct device_link *link = container_of(work, struct device_link, rm_work);
577 
578 	/* Ensure that all references to the link object have been dropped. */
579 	device_link_synchronize_removal();
580 
581 	pm_runtime_release_supplier(link);
582 	/*
583 	 * If supplier_preactivated is set, the link has been dropped between
584 	 * the pm_runtime_get_suppliers() and pm_runtime_put_suppliers() calls
585 	 * in __driver_probe_device().  In that case, drop the supplier's
586 	 * PM-runtime usage counter to remove the reference taken by
587 	 * pm_runtime_get_suppliers().
588 	 */
589 	if (link->supplier_preactivated)
590 		pm_runtime_put_noidle(link->supplier);
591 
592 	pm_request_idle(link->supplier);
593 
594 	put_device(link->consumer);
595 	put_device(link->supplier);
596 	kfree(link);
597 }
598 
599 static void devlink_dev_release(struct device *dev)
600 {
601 	struct device_link *link = to_devlink(dev);
602 
603 	INIT_WORK(&link->rm_work, device_link_release_fn);
604 	/*
605 	 * It may take a while to complete this work because of the SRCU
606 	 * synchronization in device_link_release_fn() and if the consumer or
607 	 * supplier devices get deleted when it runs, so put it into the
608 	 * dedicated workqueue.
609 	 */
610 	queue_work(device_link_wq, &link->rm_work);
611 }
612 
613 /**
614  * device_link_wait_removal - Wait for ongoing devlink removal jobs to terminate
615  */
616 void device_link_wait_removal(void)
617 {
618 	/*
619 	 * devlink removal jobs are queued in the dedicated work queue.
620 	 * To be sure that all removal jobs are terminated, ensure that any
621 	 * scheduled work has run to completion.
622 	 */
623 	flush_workqueue(device_link_wq);
624 }
625 EXPORT_SYMBOL_GPL(device_link_wait_removal);
626 
627 static const struct class devlink_class = {
628 	.name = "devlink",
629 	.dev_groups = devlink_groups,
630 	.dev_release = devlink_dev_release,
631 };
632 
633 static int devlink_add_symlinks(struct device *dev)
634 {
635 	char *buf_con __free(kfree) = NULL, *buf_sup __free(kfree) = NULL;
636 	int ret;
637 	struct device_link *link = to_devlink(dev);
638 	struct device *sup = link->supplier;
639 	struct device *con = link->consumer;
640 
641 	ret = sysfs_create_link(&link->link_dev.kobj, &sup->kobj, "supplier");
642 	if (ret)
643 		goto out;
644 
645 	ret = sysfs_create_link(&link->link_dev.kobj, &con->kobj, "consumer");
646 	if (ret)
647 		goto err_con;
648 
649 	buf_con = kasprintf(GFP_KERNEL, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
650 	if (!buf_con) {
651 		ret = -ENOMEM;
652 		goto err_con_dev;
653 	}
654 
655 	ret = sysfs_create_link(&sup->kobj, &link->link_dev.kobj, buf_con);
656 	if (ret)
657 		goto err_con_dev;
658 
659 	buf_sup = kasprintf(GFP_KERNEL, "supplier:%s:%s", dev_bus_name(sup), dev_name(sup));
660 	if (!buf_sup) {
661 		ret = -ENOMEM;
662 		goto err_sup_dev;
663 	}
664 
665 	ret = sysfs_create_link(&con->kobj, &link->link_dev.kobj, buf_sup);
666 	if (ret)
667 		goto err_sup_dev;
668 
669 	goto out;
670 
671 err_sup_dev:
672 	sysfs_remove_link(&sup->kobj, buf_con);
673 err_con_dev:
674 	sysfs_remove_link(&link->link_dev.kobj, "consumer");
675 err_con:
676 	sysfs_remove_link(&link->link_dev.kobj, "supplier");
677 out:
678 	return ret;
679 }
680 
681 static void devlink_remove_symlinks(struct device *dev)
682 {
683 	char *buf_con __free(kfree) = NULL, *buf_sup __free(kfree) = NULL;
684 	struct device_link *link = to_devlink(dev);
685 	struct device *sup = link->supplier;
686 	struct device *con = link->consumer;
687 
688 	sysfs_remove_link(&link->link_dev.kobj, "consumer");
689 	sysfs_remove_link(&link->link_dev.kobj, "supplier");
690 
691 	if (device_is_registered(con)) {
692 		buf_sup = kasprintf(GFP_KERNEL, "supplier:%s:%s", dev_bus_name(sup), dev_name(sup));
693 		if (!buf_sup)
694 			goto out;
695 		sysfs_remove_link(&con->kobj, buf_sup);
696 	}
697 
698 	buf_con = kasprintf(GFP_KERNEL, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
699 	if (!buf_con)
700 		goto out;
701 	sysfs_remove_link(&sup->kobj, buf_con);
702 
703 	return;
704 
705 out:
706 	WARN(1, "Unable to properly free device link symlinks!\n");
707 }
708 
709 static struct class_interface devlink_class_intf = {
710 	.class = &devlink_class,
711 	.add_dev = devlink_add_symlinks,
712 	.remove_dev = devlink_remove_symlinks,
713 };
714 
715 static int __init devlink_class_init(void)
716 {
717 	int ret;
718 
719 	ret = class_register(&devlink_class);
720 	if (ret)
721 		return ret;
722 
723 	ret = class_interface_register(&devlink_class_intf);
724 	if (ret)
725 		class_unregister(&devlink_class);
726 
727 	return ret;
728 }
729 postcore_initcall(devlink_class_init);
730 
731 #define DL_MANAGED_LINK_FLAGS (DL_FLAG_AUTOREMOVE_CONSUMER | \
732 			       DL_FLAG_AUTOREMOVE_SUPPLIER | \
733 			       DL_FLAG_AUTOPROBE_CONSUMER  | \
734 			       DL_FLAG_SYNC_STATE_ONLY | \
735 			       DL_FLAG_INFERRED | \
736 			       DL_FLAG_CYCLE)
737 
738 #define DL_ADD_VALID_FLAGS (DL_MANAGED_LINK_FLAGS | DL_FLAG_STATELESS | \
739 			    DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE)
740 
741 /**
742  * device_link_add - Create a link between two devices.
743  * @consumer: Consumer end of the link.
744  * @supplier: Supplier end of the link.
745  * @flags: Link flags.
746  *
747  * Return: On success, a device_link struct will be returned.
748  *         On error or invalid flag settings, NULL will be returned.
749  *
750  * The caller is responsible for the proper synchronization of the link creation
751  * with runtime PM.  First, setting the DL_FLAG_PM_RUNTIME flag will cause the
752  * runtime PM framework to take the link into account.  Second, if the
753  * DL_FLAG_RPM_ACTIVE flag is set in addition to it, the supplier devices will
754  * be forced into the active meta state and reference-counted upon the creation
755  * of the link.  If DL_FLAG_PM_RUNTIME is not set, DL_FLAG_RPM_ACTIVE will be
756  * ignored.
757  *
758  * If DL_FLAG_STATELESS is set in @flags, the caller of this function is
759  * expected to release the link returned by it directly with the help of either
760  * device_link_del() or device_link_remove().
761  *
762  * If that flag is not set, however, the caller of this function is handing the
763  * management of the link over to the driver core entirely and its return value
764  * can only be used to check whether or not the link is present.  In that case,
765  * the DL_FLAG_AUTOREMOVE_CONSUMER and DL_FLAG_AUTOREMOVE_SUPPLIER device link
766  * flags can be used to indicate to the driver core when the link can be safely
767  * deleted.  Namely, setting one of them in @flags indicates to the driver core
768  * that the link is not going to be used (by the given caller of this function)
769  * after unbinding the consumer or supplier driver, respectively, from its
770  * device, so the link can be deleted at that point.  If none of them is set,
771  * the link will be maintained until one of the devices pointed to by it (either
772  * the consumer or the supplier) is unregistered.
773  *
774  * Also, if DL_FLAG_STATELESS, DL_FLAG_AUTOREMOVE_CONSUMER and
775  * DL_FLAG_AUTOREMOVE_SUPPLIER are not set in @flags (that is, a persistent
776  * managed device link is being added), the DL_FLAG_AUTOPROBE_CONSUMER flag can
777  * be used to request the driver core to automatically probe for a consumer
778  * driver after successfully binding a driver to the supplier device.
779  *
780  * The combination of DL_FLAG_STATELESS and one of DL_FLAG_AUTOREMOVE_CONSUMER,
781  * DL_FLAG_AUTOREMOVE_SUPPLIER, or DL_FLAG_AUTOPROBE_CONSUMER set in @flags at
782  * the same time is invalid and will cause NULL to be returned upfront.
783  * However, if a device link between the given @consumer and @supplier pair
784  * exists already when this function is called for them, the existing link will
785  * be returned regardless of its current type and status (the link's flags may
786  * be modified then).  The caller of this function is then expected to treat
787  * the link as though it has just been created, so (in particular) if
788  * DL_FLAG_STATELESS was passed in @flags, the link needs to be released
789  * explicitly when not needed any more (as stated above).
790  *
791  * A side effect of the link creation is re-ordering of dpm_list and the
792  * devices_kset list by moving the consumer device and all devices depending
793  * on it to the ends of these lists (that does not happen to devices that have
794  * not been registered when this function is called).
795  *
796  * The supplier device is required to be registered when this function is called
797  * and NULL will be returned if that is not the case.  The consumer device need
798  * not be registered, however.
799  */
800 struct device_link *device_link_add(struct device *consumer,
801 				    struct device *supplier, u32 flags)
802 {
803 	struct device_link *link;
804 
805 	if (!consumer || !supplier || consumer == supplier ||
806 	    flags & ~DL_ADD_VALID_FLAGS ||
807 	    (flags & DL_FLAG_STATELESS && flags & DL_MANAGED_LINK_FLAGS) ||
808 	    (flags & DL_FLAG_AUTOPROBE_CONSUMER &&
809 	     flags & (DL_FLAG_AUTOREMOVE_CONSUMER |
810 		      DL_FLAG_AUTOREMOVE_SUPPLIER)))
811 		return NULL;
812 
813 	if (flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) {
814 		if (pm_runtime_get_sync(supplier) < 0) {
815 			pm_runtime_put_noidle(supplier);
816 			return NULL;
817 		}
818 	}
819 
820 	if (!(flags & DL_FLAG_STATELESS))
821 		flags |= DL_FLAG_MANAGED;
822 
823 	if (flags & DL_FLAG_SYNC_STATE_ONLY &&
824 	    !device_link_flag_is_sync_state_only(flags))
825 		return NULL;
826 
827 	device_links_write_lock();
828 	device_pm_lock();
829 
830 	/*
831 	 * If the supplier has not been fully registered yet or there is a
832 	 * reverse (non-SYNC_STATE_ONLY) dependency between the consumer and
833 	 * the supplier already in the graph, return NULL. If the link is a
834 	 * SYNC_STATE_ONLY link, we don't check for reverse dependencies
835 	 * because it only affects sync_state() callbacks.
836 	 */
837 	if (!device_pm_initialized(supplier)
838 	    || (!(flags & DL_FLAG_SYNC_STATE_ONLY) &&
839 		  device_is_dependent(consumer, supplier))) {
840 		link = NULL;
841 		goto out;
842 	}
843 
844 	/*
845 	 * SYNC_STATE_ONLY links are useless once a consumer device has probed.
846 	 * So, only create it if the consumer hasn't probed yet.
847 	 */
848 	if (flags & DL_FLAG_SYNC_STATE_ONLY &&
849 	    consumer->links.status != DL_DEV_NO_DRIVER &&
850 	    consumer->links.status != DL_DEV_PROBING) {
851 		link = NULL;
852 		goto out;
853 	}
854 
855 	/*
856 	 * DL_FLAG_AUTOREMOVE_SUPPLIER indicates that the link will be needed
857 	 * longer than for DL_FLAG_AUTOREMOVE_CONSUMER and setting them both
858 	 * together doesn't make sense, so prefer DL_FLAG_AUTOREMOVE_SUPPLIER.
859 	 */
860 	if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
861 		flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
862 
863 	list_for_each_entry(link, &supplier->links.consumers, s_node) {
864 		if (link->consumer != consumer)
865 			continue;
866 
867 		if (device_link_test(link, DL_FLAG_INFERRED) &&
868 		    !(flags & DL_FLAG_INFERRED))
869 			link->flags &= ~DL_FLAG_INFERRED;
870 
871 		if (flags & DL_FLAG_PM_RUNTIME) {
872 			if (!device_link_test(link, DL_FLAG_PM_RUNTIME)) {
873 				pm_runtime_new_link(consumer);
874 				link->flags |= DL_FLAG_PM_RUNTIME;
875 			}
876 			if (flags & DL_FLAG_RPM_ACTIVE)
877 				refcount_inc(&link->rpm_active);
878 		}
879 
880 		if (flags & DL_FLAG_STATELESS) {
881 			kref_get(&link->kref);
882 			if (device_link_test(link, DL_FLAG_SYNC_STATE_ONLY) &&
883 			    !device_link_test(link, DL_FLAG_STATELESS)) {
884 				link->flags |= DL_FLAG_STATELESS;
885 				goto reorder;
886 			} else {
887 				link->flags |= DL_FLAG_STATELESS;
888 				goto out;
889 			}
890 		}
891 
892 		/*
893 		 * If the life time of the link following from the new flags is
894 		 * longer than indicated by the flags of the existing link,
895 		 * update the existing link to stay around longer.
896 		 */
897 		if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER) {
898 			if (device_link_test(link, DL_FLAG_AUTOREMOVE_CONSUMER)) {
899 				link->flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
900 				link->flags |= DL_FLAG_AUTOREMOVE_SUPPLIER;
901 			}
902 		} else if (!(flags & DL_FLAG_AUTOREMOVE_CONSUMER)) {
903 			link->flags &= ~(DL_FLAG_AUTOREMOVE_CONSUMER |
904 					 DL_FLAG_AUTOREMOVE_SUPPLIER);
905 		}
906 		if (!device_link_test(link, DL_FLAG_MANAGED)) {
907 			kref_get(&link->kref);
908 			link->flags |= DL_FLAG_MANAGED;
909 			device_link_init_status(link, consumer, supplier);
910 		}
911 		if (device_link_test(link, DL_FLAG_SYNC_STATE_ONLY) &&
912 		    !(flags & DL_FLAG_SYNC_STATE_ONLY)) {
913 			link->flags &= ~DL_FLAG_SYNC_STATE_ONLY;
914 			goto reorder;
915 		}
916 
917 		goto out;
918 	}
919 
920 	link = kzalloc_obj(*link);
921 	if (!link)
922 		goto out;
923 
924 	refcount_set(&link->rpm_active, 1);
925 
926 	get_device(supplier);
927 	link->supplier = supplier;
928 	INIT_LIST_HEAD(&link->s_node);
929 	get_device(consumer);
930 	link->consumer = consumer;
931 	INIT_LIST_HEAD(&link->c_node);
932 	link->flags = flags;
933 	kref_init(&link->kref);
934 
935 	link->link_dev.class = &devlink_class;
936 	device_set_pm_not_required(&link->link_dev);
937 	dev_set_name(&link->link_dev, "%s:%s--%s:%s",
938 		     dev_bus_name(supplier), dev_name(supplier),
939 		     dev_bus_name(consumer), dev_name(consumer));
940 	if (device_register(&link->link_dev)) {
941 		put_device(&link->link_dev);
942 		link = NULL;
943 		goto out;
944 	}
945 
946 	if (flags & DL_FLAG_PM_RUNTIME) {
947 		if (flags & DL_FLAG_RPM_ACTIVE)
948 			refcount_inc(&link->rpm_active);
949 
950 		pm_runtime_new_link(consumer);
951 	}
952 
953 	/* Determine the initial link state. */
954 	if (flags & DL_FLAG_STATELESS)
955 		link->status = DL_STATE_NONE;
956 	else
957 		device_link_init_status(link, consumer, supplier);
958 
959 	/*
960 	 * Some callers expect the link creation during consumer driver probe to
961 	 * resume the supplier even without DL_FLAG_RPM_ACTIVE.
962 	 */
963 	if (link->status == DL_STATE_CONSUMER_PROBE &&
964 	    flags & DL_FLAG_PM_RUNTIME)
965 		pm_runtime_resume(supplier);
966 
967 	list_add_tail_rcu(&link->s_node, &supplier->links.consumers);
968 	list_add_tail_rcu(&link->c_node, &consumer->links.suppliers);
969 
970 	if (flags & DL_FLAG_SYNC_STATE_ONLY) {
971 		dev_dbg(consumer,
972 			"Linked as a sync state only consumer to %s\n",
973 			dev_name(supplier));
974 		goto out;
975 	}
976 
977 reorder:
978 	/*
979 	 * Move the consumer and all of the devices depending on it to the end
980 	 * of dpm_list and the devices_kset list.
981 	 *
982 	 * It is necessary to hold dpm_list locked throughout all that or else
983 	 * we may end up suspending with a wrong ordering of it.
984 	 */
985 	device_reorder_to_tail(consumer, NULL);
986 
987 	dev_dbg(consumer, "Linked as a consumer to %s\n", dev_name(supplier));
988 
989 out:
990 	device_pm_unlock();
991 	device_links_write_unlock();
992 
993 	if ((flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) && !link)
994 		pm_runtime_put(supplier);
995 
996 	return link;
997 }
998 EXPORT_SYMBOL_GPL(device_link_add);
999 
1000 static void __device_link_del(struct kref *kref)
1001 {
1002 	struct device_link *link = container_of(kref, struct device_link, kref);
1003 
1004 	dev_dbg(link->consumer, "Dropping the link to %s\n",
1005 		dev_name(link->supplier));
1006 
1007 	pm_runtime_drop_link(link);
1008 
1009 	device_link_remove_from_lists(link);
1010 	device_unregister(&link->link_dev);
1011 }
1012 
1013 static void device_link_put_kref(struct device_link *link)
1014 {
1015 	if (device_link_test(link, DL_FLAG_STATELESS))
1016 		kref_put(&link->kref, __device_link_del);
1017 	else if (!device_is_registered(link->consumer))
1018 		__device_link_del(&link->kref);
1019 	else
1020 		WARN(1, "Unable to drop a managed device link reference\n");
1021 }
1022 
1023 /**
1024  * device_link_del - Delete a stateless link between two devices.
1025  * @link: Device link to delete.
1026  *
1027  * The caller must ensure proper synchronization of this function with runtime
1028  * PM.  If the link was added multiple times, it needs to be deleted as often.
1029  * Care is required for hotplugged devices:  Their links are purged on removal
1030  * and calling device_link_del() is then no longer allowed.
1031  */
1032 void device_link_del(struct device_link *link)
1033 {
1034 	device_links_write_lock();
1035 	device_link_put_kref(link);
1036 	device_links_write_unlock();
1037 }
1038 EXPORT_SYMBOL_GPL(device_link_del);
1039 
1040 /**
1041  * device_link_remove - Delete a stateless link between two devices.
1042  * @consumer: Consumer end of the link.
1043  * @supplier: Supplier end of the link.
1044  *
1045  * The caller must ensure proper synchronization of this function with runtime
1046  * PM.
1047  */
1048 void device_link_remove(void *consumer, struct device *supplier)
1049 {
1050 	struct device_link *link;
1051 
1052 	if (WARN_ON(consumer == supplier))
1053 		return;
1054 
1055 	device_links_write_lock();
1056 
1057 	list_for_each_entry(link, &supplier->links.consumers, s_node) {
1058 		if (link->consumer == consumer) {
1059 			device_link_put_kref(link);
1060 			break;
1061 		}
1062 	}
1063 
1064 	device_links_write_unlock();
1065 }
1066 EXPORT_SYMBOL_GPL(device_link_remove);
1067 
1068 static void device_links_missing_supplier(struct device *dev)
1069 {
1070 	struct device_link *link;
1071 
1072 	list_for_each_entry(link, &dev->links.suppliers, c_node) {
1073 		if (link->status != DL_STATE_CONSUMER_PROBE)
1074 			continue;
1075 
1076 		if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
1077 			WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1078 		} else {
1079 			WARN_ON(!device_link_test(link, DL_FLAG_SYNC_STATE_ONLY));
1080 			WRITE_ONCE(link->status, DL_STATE_DORMANT);
1081 		}
1082 	}
1083 }
1084 
1085 static bool dev_is_best_effort(struct device *dev)
1086 {
1087 	return (fw_devlink_best_effort && dev_can_match(dev)) ||
1088 		(dev->fwnode && fwnode_test_flag(dev->fwnode, FWNODE_FLAG_BEST_EFFORT));
1089 }
1090 
1091 static struct fwnode_handle *fwnode_links_check_suppliers(
1092 						struct fwnode_handle *fwnode)
1093 {
1094 	struct fwnode_link *link;
1095 
1096 	if (!fwnode || fw_devlink_is_permissive())
1097 		return NULL;
1098 
1099 	list_for_each_entry(link, &fwnode->suppliers, c_hook)
1100 		if (!(link->flags &
1101 		      (FWLINK_FLAG_CYCLE | FWLINK_FLAG_IGNORE)))
1102 			return link->supplier;
1103 
1104 	return NULL;
1105 }
1106 
1107 /**
1108  * device_links_check_suppliers - Check presence of supplier drivers.
1109  * @dev: Consumer device.
1110  *
1111  * Check links from this device to any suppliers.  Walk the list of the device's
1112  * links to suppliers and see if all of them are available.  If not, simply
1113  * return -EPROBE_DEFER.
1114  *
1115  * We need to guarantee that the supplier will not go away after the check has
1116  * been positive here.  It only can go away in __device_release_driver() and
1117  * that function  checks the device's links to consumers.  This means we need to
1118  * mark the link as "consumer probe in progress" to make the supplier removal
1119  * wait for us to complete (or bad things may happen).
1120  *
1121  * Links without the DL_FLAG_MANAGED flag set are ignored.
1122  */
1123 int device_links_check_suppliers(struct device *dev)
1124 {
1125 	struct device_link *link;
1126 	int ret = 0, fwnode_ret = 0;
1127 	struct fwnode_handle *sup_fw;
1128 
1129 	/*
1130 	 * Device waiting for supplier to become available is not allowed to
1131 	 * probe.
1132 	 */
1133 	scoped_guard(mutex, &fwnode_link_lock) {
1134 		sup_fw = fwnode_links_check_suppliers(dev->fwnode);
1135 		if (sup_fw) {
1136 			if (dev_is_best_effort(dev))
1137 				fwnode_ret = -EAGAIN;
1138 			else
1139 				return dev_err_probe(dev, -EPROBE_DEFER,
1140 						     "wait for supplier %pfwf\n", sup_fw);
1141 		}
1142 	}
1143 
1144 	device_links_write_lock();
1145 
1146 	list_for_each_entry(link, &dev->links.suppliers, c_node) {
1147 		if (!device_link_test(link, DL_FLAG_MANAGED))
1148 			continue;
1149 
1150 		if (link->status != DL_STATE_AVAILABLE &&
1151 		    !device_link_test(link, DL_FLAG_SYNC_STATE_ONLY)) {
1152 
1153 			if (dev_is_best_effort(dev) &&
1154 			    device_link_test(link, DL_FLAG_INFERRED) &&
1155 			    !dev_can_match(link->supplier)) {
1156 				ret = -EAGAIN;
1157 				continue;
1158 			}
1159 
1160 			device_links_missing_supplier(dev);
1161 			ret = dev_err_probe(dev, -EPROBE_DEFER,
1162 					    "supplier %s not ready\n", dev_name(link->supplier));
1163 			break;
1164 		}
1165 		WRITE_ONCE(link->status, DL_STATE_CONSUMER_PROBE);
1166 	}
1167 	dev->links.status = DL_DEV_PROBING;
1168 
1169 	device_links_write_unlock();
1170 
1171 	return ret ? ret : fwnode_ret;
1172 }
1173 
1174 /**
1175  * __device_links_queue_sync_state - Queue a device for sync_state() callback
1176  * @dev: Device to call sync_state() on
1177  * @list: List head to queue the @dev on
1178  *
1179  * Queues a device for a sync_state() callback when the device links write lock
1180  * isn't held. This allows the sync_state() execution flow to use device links
1181  * APIs.  The caller must ensure this function is called with
1182  * device_links_write_lock() held.
1183  *
1184  * This function does a get_device() to make sure the device is not freed while
1185  * on this list.
1186  *
1187  * So the caller must also ensure that device_links_flush_sync_list() is called
1188  * as soon as the caller releases device_links_write_lock().  This is necessary
1189  * to make sure the sync_state() is called in a timely fashion and the
1190  * put_device() is called on this device.
1191  */
1192 static void __device_links_queue_sync_state(struct device *dev,
1193 					    struct list_head *list)
1194 {
1195 	struct device_link *link;
1196 
1197 	if (!dev_has_sync_state(dev))
1198 		return;
1199 	if (dev_state_synced(dev))
1200 		return;
1201 
1202 	list_for_each_entry(link, &dev->links.consumers, s_node) {
1203 		if (!device_link_test(link, DL_FLAG_MANAGED))
1204 			continue;
1205 		if (link->status != DL_STATE_ACTIVE)
1206 			return;
1207 	}
1208 
1209 	/*
1210 	 * Set the flag here to avoid adding the same device to a list more
1211 	 * than once. This can happen if new consumers get added to the device
1212 	 * and probed before the list is flushed.
1213 	 */
1214 	dev_set_state_synced(dev);
1215 
1216 	if (WARN_ON(!list_empty(&dev->links.defer_sync)))
1217 		return;
1218 
1219 	get_device(dev);
1220 	list_add_tail(&dev->links.defer_sync, list);
1221 }
1222 
1223 /**
1224  * device_links_flush_sync_list - Call sync_state() on a list of devices
1225  * @list: List of devices to call sync_state() on
1226  * @dont_lock_dev: Device for which lock is already held by the caller
1227  *
1228  * Calls sync_state() on all the devices that have been queued for it. This
1229  * function is used in conjunction with __device_links_queue_sync_state(). The
1230  * @dont_lock_dev parameter is useful when this function is called from a
1231  * context where a device lock is already held.
1232  */
1233 static void device_links_flush_sync_list(struct list_head *list,
1234 					 struct device *dont_lock_dev)
1235 {
1236 	struct device *dev, *tmp;
1237 
1238 	list_for_each_entry_safe(dev, tmp, list, links.defer_sync) {
1239 		list_del_init(&dev->links.defer_sync);
1240 
1241 		if (dev != dont_lock_dev)
1242 			device_lock(dev);
1243 
1244 		dev_sync_state(dev);
1245 
1246 		if (dev != dont_lock_dev)
1247 			device_unlock(dev);
1248 
1249 		put_device(dev);
1250 	}
1251 }
1252 
1253 void device_links_supplier_sync_state_pause(void)
1254 {
1255 	device_links_write_lock();
1256 	defer_sync_state_count++;
1257 	device_links_write_unlock();
1258 }
1259 
1260 void device_links_supplier_sync_state_resume(void)
1261 {
1262 	struct device *dev, *tmp;
1263 	LIST_HEAD(sync_list);
1264 
1265 	device_links_write_lock();
1266 	if (!defer_sync_state_count) {
1267 		WARN(true, "Unmatched sync_state pause/resume!");
1268 		goto out;
1269 	}
1270 	defer_sync_state_count--;
1271 	if (defer_sync_state_count)
1272 		goto out;
1273 
1274 	list_for_each_entry_safe(dev, tmp, &deferred_sync, links.defer_sync) {
1275 		/*
1276 		 * Delete from deferred_sync list before queuing it to
1277 		 * sync_list because defer_sync is used for both lists.
1278 		 */
1279 		list_del_init(&dev->links.defer_sync);
1280 		__device_links_queue_sync_state(dev, &sync_list);
1281 	}
1282 out:
1283 	device_links_write_unlock();
1284 
1285 	device_links_flush_sync_list(&sync_list, NULL);
1286 }
1287 
1288 static int sync_state_resume_initcall(void)
1289 {
1290 	device_links_supplier_sync_state_resume();
1291 	return 0;
1292 }
1293 late_initcall(sync_state_resume_initcall);
1294 
1295 static void __device_links_supplier_defer_sync(struct device *sup)
1296 {
1297 	if (list_empty(&sup->links.defer_sync) && dev_has_sync_state(sup))
1298 		list_add_tail(&sup->links.defer_sync, &deferred_sync);
1299 }
1300 
1301 static void device_link_drop_managed(struct device_link *link)
1302 {
1303 	link->flags &= ~DL_FLAG_MANAGED;
1304 	WRITE_ONCE(link->status, DL_STATE_NONE);
1305 	kref_put(&link->kref, __device_link_del);
1306 }
1307 
1308 static ssize_t waiting_for_supplier_show(struct device *dev,
1309 					 const struct device_attribute *attr,
1310 					 char *buf)
1311 {
1312 	bool val;
1313 
1314 	device_lock(dev);
1315 	scoped_guard(mutex, &fwnode_link_lock)
1316 		val = !!fwnode_links_check_suppliers(dev->fwnode);
1317 	device_unlock(dev);
1318 	return sysfs_emit(buf, "%u\n", val);
1319 }
1320 static const DEVICE_ATTR_RO(waiting_for_supplier);
1321 
1322 /**
1323  * device_links_force_bind - Prepares device to be force bound
1324  * @dev: Consumer device.
1325  *
1326  * device_bind_driver() force binds a device to a driver without calling any
1327  * driver probe functions. So the consumer really isn't going to wait for any
1328  * supplier before it's bound to the driver. We still want the device link
1329  * states to be sensible when this happens.
1330  *
1331  * In preparation for device_bind_driver(), this function goes through each
1332  * supplier device links and checks if the supplier is bound. If it is, then
1333  * the device link status is set to CONSUMER_PROBE. Otherwise, the device link
1334  * is dropped. Links without the DL_FLAG_MANAGED flag set are ignored.
1335  */
1336 void device_links_force_bind(struct device *dev)
1337 {
1338 	struct device_link *link, *ln;
1339 
1340 	device_links_write_lock();
1341 
1342 	list_for_each_entry_safe(link, ln, &dev->links.suppliers, c_node) {
1343 		if (!device_link_test(link, DL_FLAG_MANAGED))
1344 			continue;
1345 
1346 		if (link->status != DL_STATE_AVAILABLE) {
1347 			device_link_drop_managed(link);
1348 			continue;
1349 		}
1350 		WRITE_ONCE(link->status, DL_STATE_CONSUMER_PROBE);
1351 	}
1352 	dev->links.status = DL_DEV_PROBING;
1353 
1354 	device_links_write_unlock();
1355 }
1356 
1357 /**
1358  * device_links_driver_bound - Update device links after probing its driver.
1359  * @dev: Device to update the links for.
1360  *
1361  * The probe has been successful, so update links from this device to any
1362  * consumers by changing their status to "available".
1363  *
1364  * Also change the status of @dev's links to suppliers to "active".
1365  *
1366  * Links without the DL_FLAG_MANAGED flag set are ignored.
1367  */
1368 void device_links_driver_bound(struct device *dev)
1369 {
1370 	struct device_link *link, *ln;
1371 	LIST_HEAD(sync_list);
1372 
1373 	/*
1374 	 * If a device binds successfully, it's expected to have created all
1375 	 * the device links it needs to or make new device links as it needs
1376 	 * them. So, fw_devlink no longer needs to create device links to any
1377 	 * of the device's suppliers.
1378 	 *
1379 	 * Also, if a child firmware node of this bound device is not added as a
1380 	 * device by now, assume it is never going to be added. Make this bound
1381 	 * device the fallback supplier to the dangling consumers of the child
1382 	 * firmware node because this bound device is probably implementing the
1383 	 * child firmware node functionality and we don't want the dangling
1384 	 * consumers to defer probe indefinitely waiting for a device for the
1385 	 * child firmware node.
1386 	 */
1387 	if (dev->fwnode && dev->fwnode->dev == dev) {
1388 		fwnode_links_purge_suppliers(dev->fwnode);
1389 		fw_devlink_pickup_dangling_consumers(dev);
1390 	}
1391 	device_remove_file(dev, &dev_attr_waiting_for_supplier);
1392 
1393 	device_links_write_lock();
1394 
1395 	list_for_each_entry(link, &dev->links.consumers, s_node) {
1396 		if (!device_link_test(link, DL_FLAG_MANAGED))
1397 			continue;
1398 
1399 		/*
1400 		 * Links created during consumer probe may be in the "consumer
1401 		 * probe" state to start with if the supplier is still probing
1402 		 * when they are created and they may become "active" if the
1403 		 * consumer probe returns first.  Skip them here.
1404 		 */
1405 		if (link->status == DL_STATE_CONSUMER_PROBE ||
1406 		    link->status == DL_STATE_ACTIVE)
1407 			continue;
1408 
1409 		WARN_ON(link->status != DL_STATE_DORMANT);
1410 		WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1411 
1412 		if (device_link_test(link, DL_FLAG_AUTOPROBE_CONSUMER))
1413 			driver_deferred_probe_add(link->consumer);
1414 	}
1415 
1416 	if (defer_sync_state_count)
1417 		__device_links_supplier_defer_sync(dev);
1418 	else
1419 		__device_links_queue_sync_state(dev, &sync_list);
1420 
1421 	list_for_each_entry_safe(link, ln, &dev->links.suppliers, c_node) {
1422 		struct device *supplier;
1423 
1424 		if (!device_link_test(link, DL_FLAG_MANAGED))
1425 			continue;
1426 
1427 		supplier = link->supplier;
1428 		if (device_link_test(link, DL_FLAG_SYNC_STATE_ONLY)) {
1429 			/*
1430 			 * When DL_FLAG_SYNC_STATE_ONLY is set, it means no
1431 			 * other DL_MANAGED_LINK_FLAGS have been set. So, it's
1432 			 * save to drop the managed link completely.
1433 			 */
1434 			device_link_drop_managed(link);
1435 		} else if (dev_is_best_effort(dev) &&
1436 			   device_link_test(link, DL_FLAG_INFERRED) &&
1437 			   link->status != DL_STATE_CONSUMER_PROBE &&
1438 			   !dev_can_match(link->supplier)) {
1439 			/*
1440 			 * When dev_is_best_effort() is true, we ignore device
1441 			 * links to suppliers that don't have a driver.  If the
1442 			 * consumer device still managed to probe, there's no
1443 			 * point in maintaining a device link in a weird state
1444 			 * (consumer probed before supplier). So delete it.
1445 			 */
1446 			device_link_drop_managed(link);
1447 		} else {
1448 			WARN_ON(link->status != DL_STATE_CONSUMER_PROBE);
1449 			WRITE_ONCE(link->status, DL_STATE_ACTIVE);
1450 		}
1451 
1452 		/*
1453 		 * This needs to be done even for the deleted
1454 		 * DL_FLAG_SYNC_STATE_ONLY device link in case it was the last
1455 		 * device link that was preventing the supplier from getting a
1456 		 * sync_state() call.
1457 		 */
1458 		if (defer_sync_state_count)
1459 			__device_links_supplier_defer_sync(supplier);
1460 		else
1461 			__device_links_queue_sync_state(supplier, &sync_list);
1462 	}
1463 
1464 	dev->links.status = DL_DEV_DRIVER_BOUND;
1465 
1466 	device_links_write_unlock();
1467 
1468 	device_links_flush_sync_list(&sync_list, dev);
1469 }
1470 
1471 /**
1472  * __device_links_no_driver - Update links of a device without a driver.
1473  * @dev: Device without a drvier.
1474  *
1475  * Delete all non-persistent links from this device to any suppliers.
1476  *
1477  * Persistent links stay around, but their status is changed to "available",
1478  * unless they already are in the "supplier unbind in progress" state in which
1479  * case they need not be updated.
1480  *
1481  * Links without the DL_FLAG_MANAGED flag set are ignored.
1482  */
1483 static void __device_links_no_driver(struct device *dev)
1484 {
1485 	struct device_link *link, *ln;
1486 
1487 	list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1488 		if (!device_link_test(link, DL_FLAG_MANAGED))
1489 			continue;
1490 
1491 		if (device_link_test(link, DL_FLAG_AUTOREMOVE_CONSUMER)) {
1492 			device_link_drop_managed(link);
1493 			continue;
1494 		}
1495 
1496 		if (link->status != DL_STATE_CONSUMER_PROBE &&
1497 		    link->status != DL_STATE_ACTIVE)
1498 			continue;
1499 
1500 		if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
1501 			WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1502 		} else {
1503 			WARN_ON(link->supplier->links.status != DL_DEV_UNBINDING &&
1504 				!device_link_test(link, DL_FLAG_SYNC_STATE_ONLY));
1505 			WRITE_ONCE(link->status, DL_STATE_DORMANT);
1506 		}
1507 	}
1508 
1509 	dev->links.status = DL_DEV_NO_DRIVER;
1510 }
1511 
1512 /**
1513  * device_links_no_driver - Update links after failing driver probe.
1514  * @dev: Device whose driver has just failed to probe.
1515  *
1516  * Clean up leftover links to consumers for @dev and invoke
1517  * %__device_links_no_driver() to update links to suppliers for it as
1518  * appropriate.
1519  *
1520  * Links without the DL_FLAG_MANAGED flag set are ignored.
1521  */
1522 void device_links_no_driver(struct device *dev)
1523 {
1524 	struct device_link *link;
1525 
1526 	device_links_write_lock();
1527 
1528 	list_for_each_entry(link, &dev->links.consumers, s_node) {
1529 		if (!device_link_test(link, DL_FLAG_MANAGED))
1530 			continue;
1531 
1532 		/*
1533 		 * The probe has failed, so if the status of the link is
1534 		 * "consumer probe" or "active", it must have been added by
1535 		 * a probing consumer while this device was still probing.
1536 		 * Change its state to "dormant", as it represents a valid
1537 		 * relationship, but it is not functionally meaningful.
1538 		 */
1539 		if (link->status == DL_STATE_CONSUMER_PROBE ||
1540 		    link->status == DL_STATE_ACTIVE)
1541 			WRITE_ONCE(link->status, DL_STATE_DORMANT);
1542 	}
1543 
1544 	__device_links_no_driver(dev);
1545 
1546 	device_links_write_unlock();
1547 }
1548 
1549 /**
1550  * device_links_driver_cleanup - Update links after driver removal.
1551  * @dev: Device whose driver has just gone away.
1552  *
1553  * Update links to consumers for @dev by changing their status to "dormant" and
1554  * invoke %__device_links_no_driver() to update links to suppliers for it as
1555  * appropriate.
1556  *
1557  * Links without the DL_FLAG_MANAGED flag set are ignored.
1558  */
1559 void device_links_driver_cleanup(struct device *dev)
1560 {
1561 	struct device_link *link, *ln;
1562 
1563 	device_links_write_lock();
1564 
1565 	list_for_each_entry_safe(link, ln, &dev->links.consumers, s_node) {
1566 		if (!device_link_test(link, DL_FLAG_MANAGED))
1567 			continue;
1568 
1569 		WARN_ON(device_link_test(link, DL_FLAG_AUTOREMOVE_CONSUMER));
1570 		WARN_ON(link->status != DL_STATE_SUPPLIER_UNBIND);
1571 
1572 		/*
1573 		 * autoremove the links between this @dev and its consumer
1574 		 * devices that are not active, i.e. where the link state
1575 		 * has moved to DL_STATE_SUPPLIER_UNBIND.
1576 		 */
1577 		if (link->status == DL_STATE_SUPPLIER_UNBIND &&
1578 		    device_link_test(link, DL_FLAG_AUTOREMOVE_SUPPLIER))
1579 			device_link_drop_managed(link);
1580 
1581 		WRITE_ONCE(link->status, DL_STATE_DORMANT);
1582 	}
1583 
1584 	list_del_init(&dev->links.defer_sync);
1585 	__device_links_no_driver(dev);
1586 
1587 	device_links_write_unlock();
1588 }
1589 
1590 /**
1591  * device_links_busy - Check if there are any busy links to consumers.
1592  * @dev: Device to check.
1593  *
1594  * Check each consumer of the device and return 'true' if its link's status
1595  * is one of "consumer probe" or "active" (meaning that the given consumer is
1596  * probing right now or its driver is present).  Otherwise, change the link
1597  * state to "supplier unbind" to prevent the consumer from being probed
1598  * successfully going forward.
1599  *
1600  * Return 'false' if there are no probing or active consumers.
1601  *
1602  * Links without the DL_FLAG_MANAGED flag set are ignored.
1603  */
1604 bool device_links_busy(struct device *dev)
1605 {
1606 	struct device_link *link;
1607 	bool ret = false;
1608 
1609 	device_links_write_lock();
1610 
1611 	list_for_each_entry(link, &dev->links.consumers, s_node) {
1612 		if (!device_link_test(link, DL_FLAG_MANAGED))
1613 			continue;
1614 
1615 		if (link->status == DL_STATE_CONSUMER_PROBE
1616 		    || link->status == DL_STATE_ACTIVE) {
1617 			ret = true;
1618 			break;
1619 		}
1620 		WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1621 	}
1622 
1623 	dev->links.status = DL_DEV_UNBINDING;
1624 
1625 	device_links_write_unlock();
1626 	return ret;
1627 }
1628 
1629 /**
1630  * device_links_unbind_consumers - Force unbind consumers of the given device.
1631  * @dev: Device to unbind the consumers of.
1632  *
1633  * Walk the list of links to consumers for @dev and if any of them is in the
1634  * "consumer probe" state, wait for all device probes in progress to complete
1635  * and start over.
1636  *
1637  * If that's not the case, change the status of the link to "supplier unbind"
1638  * and check if the link was in the "active" state.  If so, force the consumer
1639  * driver to unbind and start over (the consumer will not re-probe as we have
1640  * changed the state of the link already).
1641  *
1642  * Links without the DL_FLAG_MANAGED flag set are ignored.
1643  */
1644 void device_links_unbind_consumers(struct device *dev)
1645 {
1646 	struct device_link *link;
1647 
1648  start:
1649 	device_links_write_lock();
1650 
1651 	list_for_each_entry(link, &dev->links.consumers, s_node) {
1652 		enum device_link_state status;
1653 
1654 		if (!device_link_test(link, DL_FLAG_MANAGED) ||
1655 		    device_link_test(link, DL_FLAG_SYNC_STATE_ONLY))
1656 			continue;
1657 
1658 		status = link->status;
1659 		if (status == DL_STATE_CONSUMER_PROBE) {
1660 			device_links_write_unlock();
1661 
1662 			wait_for_device_probe();
1663 			goto start;
1664 		}
1665 		WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1666 		if (status == DL_STATE_ACTIVE) {
1667 			struct device *consumer = link->consumer;
1668 
1669 			get_device(consumer);
1670 
1671 			device_links_write_unlock();
1672 
1673 			device_release_driver_internal(consumer, NULL,
1674 						       consumer->parent);
1675 			put_device(consumer);
1676 			goto start;
1677 		}
1678 	}
1679 
1680 	device_links_write_unlock();
1681 }
1682 
1683 /**
1684  * device_links_purge - Delete existing links to other devices.
1685  * @dev: Target device.
1686  */
1687 static void device_links_purge(struct device *dev)
1688 {
1689 	struct device_link *link, *ln;
1690 
1691 	if (dev->class == &devlink_class)
1692 		return;
1693 
1694 	/*
1695 	 * Delete all of the remaining links from this device to any other
1696 	 * devices (either consumers or suppliers).
1697 	 */
1698 	device_links_write_lock();
1699 
1700 	list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1701 		WARN_ON(link->status == DL_STATE_ACTIVE);
1702 		__device_link_del(&link->kref);
1703 	}
1704 
1705 	list_for_each_entry_safe_reverse(link, ln, &dev->links.consumers, s_node) {
1706 		WARN_ON(link->status != DL_STATE_DORMANT &&
1707 			link->status != DL_STATE_NONE);
1708 		__device_link_del(&link->kref);
1709 	}
1710 
1711 	device_links_write_unlock();
1712 }
1713 
1714 #define FW_DEVLINK_FLAGS_PERMISSIVE	(DL_FLAG_INFERRED | \
1715 					 DL_FLAG_SYNC_STATE_ONLY)
1716 #define FW_DEVLINK_FLAGS_ON		(DL_FLAG_INFERRED | \
1717 					 DL_FLAG_AUTOPROBE_CONSUMER)
1718 #define FW_DEVLINK_FLAGS_RPM		(FW_DEVLINK_FLAGS_ON | \
1719 					 DL_FLAG_PM_RUNTIME)
1720 
1721 static u32 fw_devlink_flags = FW_DEVLINK_FLAGS_RPM;
1722 static int __init fw_devlink_setup(char *arg)
1723 {
1724 	if (!arg)
1725 		return -EINVAL;
1726 
1727 	if (strcmp(arg, "off") == 0) {
1728 		fw_devlink_flags = 0;
1729 	} else if (strcmp(arg, "permissive") == 0) {
1730 		fw_devlink_flags = FW_DEVLINK_FLAGS_PERMISSIVE;
1731 	} else if (strcmp(arg, "on") == 0) {
1732 		fw_devlink_flags = FW_DEVLINK_FLAGS_ON;
1733 	} else if (strcmp(arg, "rpm") == 0) {
1734 		fw_devlink_flags = FW_DEVLINK_FLAGS_RPM;
1735 	}
1736 	return 0;
1737 }
1738 early_param("fw_devlink", fw_devlink_setup);
1739 
1740 static bool fw_devlink_strict;
1741 static int __init fw_devlink_strict_setup(char *arg)
1742 {
1743 	return kstrtobool(arg, &fw_devlink_strict);
1744 }
1745 early_param("fw_devlink.strict", fw_devlink_strict_setup);
1746 
1747 #define FW_DEVLINK_SYNC_STATE_STRICT	0
1748 #define FW_DEVLINK_SYNC_STATE_TIMEOUT	1
1749 
1750 #ifndef CONFIG_FW_DEVLINK_SYNC_STATE_TIMEOUT
1751 static int fw_devlink_sync_state;
1752 #else
1753 static int fw_devlink_sync_state = FW_DEVLINK_SYNC_STATE_TIMEOUT;
1754 #endif
1755 
1756 static int __init fw_devlink_sync_state_setup(char *arg)
1757 {
1758 	if (!arg)
1759 		return -EINVAL;
1760 
1761 	if (strcmp(arg, "strict") == 0) {
1762 		fw_devlink_sync_state = FW_DEVLINK_SYNC_STATE_STRICT;
1763 		return 0;
1764 	} else if (strcmp(arg, "timeout") == 0) {
1765 		fw_devlink_sync_state = FW_DEVLINK_SYNC_STATE_TIMEOUT;
1766 		return 0;
1767 	}
1768 	return -EINVAL;
1769 }
1770 early_param("fw_devlink.sync_state", fw_devlink_sync_state_setup);
1771 
1772 static inline u32 fw_devlink_get_flags(u8 fwlink_flags)
1773 {
1774 	if (fwlink_flags & FWLINK_FLAG_CYCLE)
1775 		return FW_DEVLINK_FLAGS_PERMISSIVE | DL_FLAG_CYCLE;
1776 
1777 	return fw_devlink_flags;
1778 }
1779 
1780 static bool fw_devlink_is_permissive(void)
1781 {
1782 	return fw_devlink_flags == FW_DEVLINK_FLAGS_PERMISSIVE;
1783 }
1784 
1785 bool fw_devlink_is_strict(void)
1786 {
1787 	return fw_devlink_strict && !fw_devlink_is_permissive();
1788 }
1789 
1790 static void fw_devlink_parse_fwnode(struct fwnode_handle *fwnode)
1791 {
1792 	if (fwnode_test_flag(fwnode, FWNODE_FLAG_LINKS_ADDED))
1793 		return;
1794 
1795 	fwnode_call_int_op(fwnode, add_links);
1796 	fwnode_set_flag(fwnode, FWNODE_FLAG_LINKS_ADDED);
1797 }
1798 
1799 static void fw_devlink_parse_fwtree(struct fwnode_handle *fwnode)
1800 {
1801 	struct fwnode_handle *child = NULL;
1802 
1803 	fw_devlink_parse_fwnode(fwnode);
1804 
1805 	while ((child = fwnode_get_next_available_child_node(fwnode, child)))
1806 		fw_devlink_parse_fwtree(child);
1807 }
1808 
1809 static void fw_devlink_relax_link(struct device_link *link)
1810 {
1811 	if (!device_link_test(link, DL_FLAG_INFERRED))
1812 		return;
1813 
1814 	if (device_link_flag_is_sync_state_only(link->flags))
1815 		return;
1816 
1817 	pm_runtime_drop_link(link);
1818 	link->flags = DL_FLAG_MANAGED | FW_DEVLINK_FLAGS_PERMISSIVE;
1819 	dev_dbg(link->consumer, "Relaxing link with %s\n",
1820 		dev_name(link->supplier));
1821 }
1822 
1823 static int fw_devlink_no_driver(struct device *dev, void *data)
1824 {
1825 	struct device_link *link = to_devlink(dev);
1826 
1827 	if (!dev_can_match(link->supplier))
1828 		fw_devlink_relax_link(link);
1829 
1830 	return 0;
1831 }
1832 
1833 void fw_devlink_drivers_done(void)
1834 {
1835 	fw_devlink_drv_reg_done = true;
1836 	device_links_write_lock();
1837 	class_for_each_device(&devlink_class, NULL, NULL,
1838 			      fw_devlink_no_driver);
1839 	device_links_write_unlock();
1840 }
1841 
1842 static int fw_devlink_dev_sync_state(struct device *dev, void *data)
1843 {
1844 	struct device_link *link = to_devlink(dev);
1845 	struct device *sup = link->supplier;
1846 
1847 	if (!device_link_test(link, DL_FLAG_MANAGED) ||
1848 	    link->status == DL_STATE_ACTIVE || dev_state_synced(sup) ||
1849 	    !dev_has_sync_state(sup))
1850 		return 0;
1851 
1852 	if (fw_devlink_sync_state == FW_DEVLINK_SYNC_STATE_STRICT) {
1853 		dev_info(sup, "sync_state() pending due to %s\n",
1854 			 dev_name(link->consumer));
1855 		return 0;
1856 	}
1857 
1858 	if (!list_empty(&sup->links.defer_sync))
1859 		return 0;
1860 
1861 	dev_warn(sup, "Timed out. Forcing sync_state()\n");
1862 	dev_set_state_synced(sup);
1863 	get_device(sup);
1864 	list_add_tail(&sup->links.defer_sync, data);
1865 
1866 	return 0;
1867 }
1868 
1869 void fw_devlink_probing_done(void)
1870 {
1871 	LIST_HEAD(sync_list);
1872 
1873 	device_links_write_lock();
1874 	class_for_each_device(&devlink_class, NULL, &sync_list,
1875 			      fw_devlink_dev_sync_state);
1876 	device_links_write_unlock();
1877 	device_links_flush_sync_list(&sync_list, NULL);
1878 }
1879 
1880 /**
1881  * wait_for_init_devices_probe - Try to probe any device needed for init
1882  *
1883  * Some devices might need to be probed and bound successfully before the kernel
1884  * boot sequence can finish and move on to init/userspace. For example, a
1885  * network interface might need to be bound to be able to mount a NFS rootfs.
1886  *
1887  * With fw_devlink=on by default, some of these devices might be blocked from
1888  * probing because they are waiting on a optional supplier that doesn't have a
1889  * driver. While fw_devlink will eventually identify such devices and unblock
1890  * the probing automatically, it might be too late by the time it unblocks the
1891  * probing of devices. For example, the IP4 autoconfig might timeout before
1892  * fw_devlink unblocks probing of the network interface.
1893  *
1894  * This function is available to temporarily try and probe all devices that have
1895  * a driver even if some of their suppliers haven't been added or don't have
1896  * drivers.
1897  *
1898  * The drivers can then decide which of the suppliers are optional vs mandatory
1899  * and probe the device if possible. By the time this function returns, all such
1900  * "best effort" probes are guaranteed to be completed. If a device successfully
1901  * probes in this mode, we delete all fw_devlink discovered dependencies of that
1902  * device where the supplier hasn't yet probed successfully because they have to
1903  * be optional dependencies.
1904  *
1905  * Any devices that didn't successfully probe go back to being treated as if
1906  * this function was never called.
1907  *
1908  * This also means that some devices that aren't needed for init and could have
1909  * waited for their optional supplier to probe (when the supplier's module is
1910  * loaded later on) would end up probing prematurely with limited functionality.
1911  * So call this function only when boot would fail without it.
1912  */
1913 void __init wait_for_init_devices_probe(void)
1914 {
1915 	if (!fw_devlink_flags || fw_devlink_is_permissive())
1916 		return;
1917 
1918 	/*
1919 	 * Wait for all ongoing probes to finish so that the "best effort" is
1920 	 * only applied to devices that can't probe otherwise.
1921 	 */
1922 	wait_for_device_probe();
1923 
1924 	pr_info("Trying to probe devices needed for running init ...\n");
1925 	fw_devlink_best_effort = true;
1926 	driver_deferred_probe_trigger();
1927 
1928 	/*
1929 	 * Wait for all "best effort" probes to finish before going back to
1930 	 * normal enforcement.
1931 	 */
1932 	wait_for_device_probe();
1933 	fw_devlink_best_effort = false;
1934 }
1935 
1936 static void fw_devlink_unblock_consumers(struct device *dev)
1937 {
1938 	struct device_link *link;
1939 
1940 	if (!fw_devlink_flags || fw_devlink_is_permissive())
1941 		return;
1942 
1943 	device_links_write_lock();
1944 	list_for_each_entry(link, &dev->links.consumers, s_node)
1945 		fw_devlink_relax_link(link);
1946 	device_links_write_unlock();
1947 }
1948 
1949 static bool fwnode_init_without_drv(struct fwnode_handle *fwnode)
1950 {
1951 	struct device *dev;
1952 	bool ret;
1953 
1954 	if (!fwnode_test_flag(fwnode, FWNODE_FLAG_INITIALIZED))
1955 		return false;
1956 
1957 	dev = get_dev_from_fwnode(fwnode);
1958 	ret = !dev || dev->links.status == DL_DEV_NO_DRIVER;
1959 	put_device(dev);
1960 
1961 	return ret;
1962 }
1963 
1964 static bool fwnode_ancestor_init_without_drv(struct fwnode_handle *fwnode)
1965 {
1966 	struct fwnode_handle *parent;
1967 
1968 	fwnode_for_each_parent_node(fwnode, parent) {
1969 		if (fwnode_init_without_drv(parent)) {
1970 			fwnode_handle_put(parent);
1971 			return true;
1972 		}
1973 	}
1974 
1975 	return false;
1976 }
1977 
1978 /**
1979  * fwnode_is_ancestor_of - Test if @ancestor is ancestor of @child
1980  * @ancestor: Firmware which is tested for being an ancestor
1981  * @child: Firmware which is tested for being the child
1982  *
1983  * A node is considered an ancestor of itself too.
1984  *
1985  * Return: true if @ancestor is an ancestor of @child. Otherwise, returns false.
1986  */
1987 static bool fwnode_is_ancestor_of(const struct fwnode_handle *ancestor,
1988 				  const struct fwnode_handle *child)
1989 {
1990 	struct fwnode_handle *parent;
1991 
1992 	if (IS_ERR_OR_NULL(ancestor))
1993 		return false;
1994 
1995 	if (child == ancestor)
1996 		return true;
1997 
1998 	fwnode_for_each_parent_node(child, parent) {
1999 		if (parent == ancestor) {
2000 			fwnode_handle_put(parent);
2001 			return true;
2002 		}
2003 	}
2004 	return false;
2005 }
2006 
2007 /**
2008  * fwnode_get_next_parent_dev - Find device of closest ancestor fwnode
2009  * @fwnode: firmware node
2010  *
2011  * Given a firmware node (@fwnode), this function finds its closest ancestor
2012  * firmware node that has a corresponding struct device and returns that struct
2013  * device.
2014  *
2015  * The caller is responsible for calling put_device() on the returned device
2016  * pointer.
2017  *
2018  * Return: a pointer to the device of the @fwnode's closest ancestor.
2019  */
2020 static struct device *fwnode_get_next_parent_dev(const struct fwnode_handle *fwnode)
2021 {
2022 	struct fwnode_handle *parent;
2023 	struct device *dev;
2024 
2025 	fwnode_for_each_parent_node(fwnode, parent) {
2026 		dev = get_dev_from_fwnode(parent);
2027 		if (dev) {
2028 			fwnode_handle_put(parent);
2029 			return dev;
2030 		}
2031 	}
2032 	return NULL;
2033 }
2034 
2035 /**
2036  * __fw_devlink_relax_cycles - Relax and mark dependency cycles.
2037  * @con_handle: Potential consumer device fwnode.
2038  * @sup_handle: Potential supplier's fwnode.
2039  *
2040  * Needs to be called with fwnode_lock and device link lock held.
2041  *
2042  * Check if @sup_handle or any of its ancestors or suppliers direct/indirectly
2043  * depend on @con. This function can detect multiple cyles between @sup_handle
2044  * and @con. When such dependency cycles are found, convert all device links
2045  * created solely by fw_devlink into SYNC_STATE_ONLY device links. Also, mark
2046  * all fwnode links in the cycle with FWLINK_FLAG_CYCLE so that when they are
2047  * converted into a device link in the future, they are created as
2048  * SYNC_STATE_ONLY device links. This is the equivalent of doing
2049  * fw_devlink=permissive just between the devices in the cycle. We need to do
2050  * this because, at this point, fw_devlink can't tell which of these
2051  * dependencies is not a real dependency.
2052  *
2053  * Return true if one or more cycles were found. Otherwise, return false.
2054  */
2055 static bool __fw_devlink_relax_cycles(struct fwnode_handle *con_handle,
2056 				 struct fwnode_handle *sup_handle)
2057 {
2058 	struct device *sup_dev = NULL, *par_dev = NULL, *con_dev = NULL;
2059 	struct fwnode_link *link;
2060 	struct device_link *dev_link;
2061 	bool ret = false;
2062 
2063 	if (!sup_handle)
2064 		return false;
2065 
2066 	/*
2067 	 * We aren't trying to find all cycles. Just a cycle between con and
2068 	 * sup_handle.
2069 	 */
2070 	if (fwnode_test_flag(sup_handle, FWNODE_FLAG_VISITED))
2071 		return false;
2072 
2073 	fwnode_set_flag(sup_handle, FWNODE_FLAG_VISITED);
2074 
2075 	/* Termination condition. */
2076 	if (sup_handle == con_handle) {
2077 		pr_debug("----- cycle: start -----\n");
2078 		ret = true;
2079 		goto out;
2080 	}
2081 
2082 	sup_dev = get_dev_from_fwnode(sup_handle);
2083 	con_dev = get_dev_from_fwnode(con_handle);
2084 	/*
2085 	 * If sup_dev is bound to a driver and @con hasn't started binding to a
2086 	 * driver, sup_dev can't be a consumer of @con. So, no need to check
2087 	 * further.
2088 	 */
2089 	if (sup_dev && sup_dev->links.status ==  DL_DEV_DRIVER_BOUND &&
2090 	    con_dev && con_dev->links.status == DL_DEV_NO_DRIVER) {
2091 		ret = false;
2092 		goto out;
2093 	}
2094 
2095 	list_for_each_entry(link, &sup_handle->suppliers, c_hook) {
2096 		if (link->flags & FWLINK_FLAG_IGNORE)
2097 			continue;
2098 
2099 		if (__fw_devlink_relax_cycles(con_handle, link->supplier)) {
2100 			__fwnode_link_cycle(link);
2101 			ret = true;
2102 		}
2103 	}
2104 
2105 	/*
2106 	 * Give priority to device parent over fwnode parent to account for any
2107 	 * quirks in how fwnodes are converted to devices.
2108 	 */
2109 	if (sup_dev)
2110 		par_dev = get_device(sup_dev->parent);
2111 	else
2112 		par_dev = fwnode_get_next_parent_dev(sup_handle);
2113 
2114 	if (par_dev && __fw_devlink_relax_cycles(con_handle, par_dev->fwnode)) {
2115 		pr_debug("%pfwf: cycle: child of %pfwf\n", sup_handle,
2116 			 par_dev->fwnode);
2117 		ret = true;
2118 	}
2119 
2120 	if (!sup_dev)
2121 		goto out;
2122 
2123 	list_for_each_entry(dev_link, &sup_dev->links.suppliers, c_node) {
2124 		/*
2125 		 * Ignore a SYNC_STATE_ONLY flag only if it wasn't marked as
2126 		 * such due to a cycle.
2127 		 */
2128 		if (device_link_flag_is_sync_state_only(dev_link->flags) &&
2129 		    !device_link_test(dev_link, DL_FLAG_CYCLE))
2130 			continue;
2131 
2132 		if (__fw_devlink_relax_cycles(con_handle,
2133 					      dev_link->supplier->fwnode)) {
2134 			pr_debug("%pfwf: cycle: depends on %pfwf\n", sup_handle,
2135 				 dev_link->supplier->fwnode);
2136 			fw_devlink_relax_link(dev_link);
2137 			dev_link->flags |= DL_FLAG_CYCLE;
2138 			ret = true;
2139 		}
2140 	}
2141 
2142 out:
2143 	fwnode_clear_flag(sup_handle, FWNODE_FLAG_VISITED);
2144 	put_device(sup_dev);
2145 	put_device(con_dev);
2146 	put_device(par_dev);
2147 	return ret;
2148 }
2149 
2150 /**
2151  * fw_devlink_create_devlink - Create a device link from a consumer to fwnode
2152  * @con: consumer device for the device link
2153  * @sup_handle: fwnode handle of supplier
2154  * @link: fwnode link that's being converted to a device link
2155  *
2156  * This function will try to create a device link between the consumer device
2157  * @con and the supplier device represented by @sup_handle.
2158  *
2159  * The supplier has to be provided as a fwnode because incorrect cycles in
2160  * fwnode links can sometimes cause the supplier device to never be created.
2161  * This function detects such cases and returns an error if it cannot create a
2162  * device link from the consumer to a missing supplier.
2163  *
2164  * Returns,
2165  * 0 on successfully creating a device link
2166  * -EINVAL if the device link cannot be created as expected
2167  * -EAGAIN if the device link cannot be created right now, but it may be
2168  *  possible to do that in the future
2169  */
2170 static int fw_devlink_create_devlink(struct device *con,
2171 				     struct fwnode_handle *sup_handle,
2172 				     struct fwnode_link *link)
2173 {
2174 	struct device *sup_dev;
2175 	int ret = 0;
2176 	u32 flags;
2177 
2178 	if (link->flags & FWLINK_FLAG_IGNORE)
2179 		return 0;
2180 
2181 	/*
2182 	 * In some cases, a device P might also be a supplier to its child node
2183 	 * C. However, this would defer the probe of C until the probe of P
2184 	 * completes successfully. This is perfectly fine in the device driver
2185 	 * model. device_add() doesn't guarantee probe completion of the device
2186 	 * by the time it returns.
2187 	 *
2188 	 * However, there are a few drivers that assume C will finish probing
2189 	 * as soon as it's added and before P finishes probing. So, we provide
2190 	 * a flag to let fw_devlink know not to delay the probe of C until the
2191 	 * probe of P completes successfully.
2192 	 *
2193 	 * When such a flag is set, we can't create device links where P is the
2194 	 * supplier of C as that would delay the probe of C.
2195 	 */
2196 	if (fwnode_test_flag(sup_handle, FWNODE_FLAG_NEEDS_CHILD_BOUND_ON_ADD) &&
2197 	    fwnode_is_ancestor_of(sup_handle, con->fwnode))
2198 		return -EINVAL;
2199 
2200 	/*
2201 	 * Don't try to optimize by not calling the cycle detection logic under
2202 	 * certain conditions. There's always some corner case that won't get
2203 	 * detected.
2204 	 */
2205 	device_links_write_lock();
2206 	if (__fw_devlink_relax_cycles(link->consumer, sup_handle)) {
2207 		__fwnode_link_cycle(link);
2208 		pr_debug("----- cycle: end -----\n");
2209 		pr_info("%pfwf: Fixed dependency cycle(s) with %pfwf\n",
2210 			link->consumer, sup_handle);
2211 	}
2212 	device_links_write_unlock();
2213 
2214 	if (con->fwnode == link->consumer)
2215 		flags = fw_devlink_get_flags(link->flags);
2216 	else
2217 		flags = FW_DEVLINK_FLAGS_PERMISSIVE;
2218 
2219 	if (fwnode_test_flag(sup_handle, FWNODE_FLAG_NOT_DEVICE))
2220 		sup_dev = fwnode_get_next_parent_dev(sup_handle);
2221 	else
2222 		sup_dev = get_dev_from_fwnode(sup_handle);
2223 
2224 	if (sup_dev) {
2225 		/*
2226 		 * If it's one of those drivers that don't actually bind to
2227 		 * their device using driver core, then don't wait on this
2228 		 * supplier device indefinitely.
2229 		 */
2230 		if (sup_dev->links.status == DL_DEV_NO_DRIVER &&
2231 		    fwnode_test_flag(sup_handle, FWNODE_FLAG_INITIALIZED)) {
2232 			dev_dbg(con,
2233 				"Not linking %pfwf - dev might never probe\n",
2234 				sup_handle);
2235 			ret = -EINVAL;
2236 			goto out;
2237 		}
2238 
2239 		if (con != sup_dev && !device_link_add(con, sup_dev, flags)) {
2240 			dev_err(con, "Failed to create device link (0x%x) with supplier %s for %pfwf\n",
2241 				flags, dev_name(sup_dev), link->consumer);
2242 			ret = -EINVAL;
2243 		}
2244 
2245 		goto out;
2246 	}
2247 
2248 	/*
2249 	 * Supplier or supplier's ancestor already initialized without a struct
2250 	 * device or being probed by a driver.
2251 	 */
2252 	if (fwnode_init_without_drv(sup_handle) ||
2253 	    fwnode_ancestor_init_without_drv(sup_handle)) {
2254 		dev_dbg(con, "Not linking %pfwf - might never become dev\n",
2255 			sup_handle);
2256 		return -EINVAL;
2257 	}
2258 
2259 	ret = -EAGAIN;
2260 out:
2261 	put_device(sup_dev);
2262 	return ret;
2263 }
2264 
2265 /**
2266  * __fw_devlink_link_to_consumers - Create device links to consumers of a device
2267  * @dev: Device that needs to be linked to its consumers
2268  *
2269  * This function looks at all the consumer fwnodes of @dev and creates device
2270  * links between the consumer device and @dev (supplier).
2271  *
2272  * If the consumer device has not been added yet, then this function creates a
2273  * SYNC_STATE_ONLY link between @dev (supplier) and the closest ancestor device
2274  * of the consumer fwnode. This is necessary to make sure @dev doesn't get a
2275  * sync_state() callback before the real consumer device gets to be added and
2276  * then probed.
2277  *
2278  * Once device links are created from the real consumer to @dev (supplier), the
2279  * fwnode links are deleted.
2280  */
2281 static void __fw_devlink_link_to_consumers(struct device *dev)
2282 {
2283 	struct fwnode_handle *fwnode = dev->fwnode;
2284 	struct fwnode_link *link, *tmp;
2285 
2286 	list_for_each_entry_safe(link, tmp, &fwnode->consumers, s_hook) {
2287 		struct device *con_dev;
2288 		bool own_link = true;
2289 		int ret;
2290 
2291 		con_dev = get_dev_from_fwnode(link->consumer);
2292 		/*
2293 		 * If consumer device is not available yet, make a "proxy"
2294 		 * SYNC_STATE_ONLY link from the consumer's parent device to
2295 		 * the supplier device. This is necessary to make sure the
2296 		 * supplier doesn't get a sync_state() callback before the real
2297 		 * consumer can create a device link to the supplier.
2298 		 *
2299 		 * This proxy link step is needed to handle the case where the
2300 		 * consumer's parent device is added before the supplier.
2301 		 */
2302 		if (!con_dev) {
2303 			con_dev = fwnode_get_next_parent_dev(link->consumer);
2304 			/*
2305 			 * However, if the consumer's parent device is also the
2306 			 * parent of the supplier, don't create a
2307 			 * consumer-supplier link from the parent to its child
2308 			 * device. Such a dependency is impossible.
2309 			 */
2310 			if (con_dev &&
2311 			    fwnode_is_ancestor_of(con_dev->fwnode, fwnode)) {
2312 				put_device(con_dev);
2313 				con_dev = NULL;
2314 			} else {
2315 				own_link = false;
2316 			}
2317 		}
2318 
2319 		if (!con_dev)
2320 			continue;
2321 
2322 		ret = fw_devlink_create_devlink(con_dev, fwnode, link);
2323 		put_device(con_dev);
2324 		if (!own_link || ret == -EAGAIN)
2325 			continue;
2326 
2327 		__fwnode_link_del(link);
2328 	}
2329 }
2330 
2331 /**
2332  * __fw_devlink_link_to_suppliers - Create device links to suppliers of a device
2333  * @dev: The consumer device that needs to be linked to its suppliers
2334  * @fwnode: Root of the fwnode tree that is used to create device links
2335  *
2336  * This function looks at all the supplier fwnodes of fwnode tree rooted at
2337  * @fwnode and creates device links between @dev (consumer) and all the
2338  * supplier devices of the entire fwnode tree at @fwnode.
2339  *
2340  * The function creates normal (non-SYNC_STATE_ONLY) device links between @dev
2341  * and the real suppliers of @dev. Once these device links are created, the
2342  * fwnode links are deleted.
2343  *
2344  * In addition, it also looks at all the suppliers of the entire fwnode tree
2345  * because some of the child devices of @dev that have not been added yet
2346  * (because @dev hasn't probed) might already have their suppliers added to
2347  * driver core. So, this function creates SYNC_STATE_ONLY device links between
2348  * @dev (consumer) and these suppliers to make sure they don't execute their
2349  * sync_state() callbacks before these child devices have a chance to create
2350  * their device links. The fwnode links that correspond to the child devices
2351  * aren't delete because they are needed later to create the device links
2352  * between the real consumer and supplier devices.
2353  */
2354 static void __fw_devlink_link_to_suppliers(struct device *dev,
2355 					   struct fwnode_handle *fwnode)
2356 {
2357 	bool own_link = (dev->fwnode == fwnode);
2358 	struct fwnode_link *link, *tmp;
2359 	struct fwnode_handle *child = NULL;
2360 
2361 	list_for_each_entry_safe(link, tmp, &fwnode->suppliers, c_hook) {
2362 		int ret;
2363 		struct fwnode_handle *sup = link->supplier;
2364 
2365 		ret = fw_devlink_create_devlink(dev, sup, link);
2366 		if (!own_link || ret == -EAGAIN)
2367 			continue;
2368 
2369 		__fwnode_link_del(link);
2370 	}
2371 
2372 	/*
2373 	 * Make "proxy" SYNC_STATE_ONLY device links to represent the needs of
2374 	 * all the descendants. This proxy link step is needed to handle the
2375 	 * case where the supplier is added before the consumer's parent device
2376 	 * (@dev).
2377 	 */
2378 	while ((child = fwnode_get_next_available_child_node(fwnode, child)))
2379 		__fw_devlink_link_to_suppliers(dev, child);
2380 }
2381 
2382 static void fw_devlink_link_device(struct device *dev)
2383 {
2384 	struct fwnode_handle *fwnode = dev->fwnode;
2385 
2386 	if (!fw_devlink_flags)
2387 		return;
2388 
2389 	fw_devlink_parse_fwtree(fwnode);
2390 
2391 	guard(mutex)(&fwnode_link_lock);
2392 
2393 	__fw_devlink_link_to_consumers(dev);
2394 	__fw_devlink_link_to_suppliers(dev, fwnode);
2395 }
2396 
2397 /* Device links support end. */
2398 
2399 static struct kobject *dev_kobj;
2400 
2401 /* /sys/dev/char */
2402 static struct kobject *sysfs_dev_char_kobj;
2403 
2404 /* /sys/dev/block */
2405 static struct kobject *sysfs_dev_block_kobj;
2406 
2407 static DEFINE_MUTEX(device_hotplug_lock);
2408 
2409 void lock_device_hotplug(void)
2410 {
2411 	mutex_lock(&device_hotplug_lock);
2412 }
2413 
2414 void unlock_device_hotplug(void)
2415 {
2416 	mutex_unlock(&device_hotplug_lock);
2417 }
2418 
2419 int lock_device_hotplug_sysfs(void)
2420 {
2421 	if (mutex_trylock(&device_hotplug_lock))
2422 		return 0;
2423 
2424 	/* Avoid busy looping (5 ms of sleep should do). */
2425 	msleep(5);
2426 	return restart_syscall();
2427 }
2428 
2429 #ifdef CONFIG_BLOCK
2430 static inline int device_is_not_partition(struct device *dev)
2431 {
2432 	return !(dev->type == &part_type);
2433 }
2434 #else
2435 static inline int device_is_not_partition(struct device *dev)
2436 {
2437 	return 1;
2438 }
2439 #endif
2440 
2441 static void device_platform_notify(struct device *dev)
2442 {
2443 	acpi_device_notify(dev);
2444 
2445 	software_node_notify(dev);
2446 }
2447 
2448 static void device_platform_notify_remove(struct device *dev)
2449 {
2450 	software_node_notify_remove(dev);
2451 
2452 	acpi_device_notify_remove(dev);
2453 }
2454 
2455 /**
2456  * dev_driver_string - Return a device's driver name, if at all possible
2457  * @dev: struct device to get the name of
2458  *
2459  * Will return the device's driver's name if it is bound to a device.  If
2460  * the device is not bound to a driver, it will return the name of the bus
2461  * it is attached to.  If it is not attached to a bus either, an empty
2462  * string will be returned.
2463  */
2464 const char *dev_driver_string(const struct device *dev)
2465 {
2466 	struct device_driver *drv;
2467 
2468 	/* dev->driver can change to NULL underneath us because of unbinding,
2469 	 * so be careful about accessing it.  dev->bus and dev->class should
2470 	 * never change once they are set, so they don't need special care.
2471 	 */
2472 	drv = READ_ONCE(dev->driver);
2473 	return drv ? drv->name : dev_bus_name(dev);
2474 }
2475 EXPORT_SYMBOL(dev_driver_string);
2476 
2477 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
2478 
2479 static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
2480 			     char *buf)
2481 {
2482 	struct device_attribute *dev_attr = to_dev_attr(attr);
2483 	struct device *dev = kobj_to_dev(kobj);
2484 	ssize_t ret = -EIO;
2485 
2486 	if (dev_attr->show)
2487 		ret = dev_attr->show(dev, dev_attr, buf);
2488 	else if (dev_attr->show_const)
2489 		ret = dev_attr->show_const(dev, dev_attr, buf);
2490 	if (ret >= (ssize_t)PAGE_SIZE) {
2491 		printk("dev_attr_show: %pS/%pS returned bad count\n",
2492 				dev_attr->show, dev_attr->show_const);
2493 	}
2494 	return ret;
2495 }
2496 
2497 static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
2498 			      const char *buf, size_t count)
2499 {
2500 	struct device_attribute *dev_attr = to_dev_attr(attr);
2501 	struct device *dev = kobj_to_dev(kobj);
2502 	ssize_t ret = -EIO;
2503 
2504 	if (dev_attr->store)
2505 		ret = dev_attr->store(dev, dev_attr, buf, count);
2506 	else if (dev_attr->store_const)
2507 		ret = dev_attr->store_const(dev, dev_attr, buf, count);
2508 	return ret;
2509 }
2510 
2511 static const struct sysfs_ops dev_sysfs_ops = {
2512 	.show	= dev_attr_show,
2513 	.store	= dev_attr_store,
2514 };
2515 
2516 #define to_ext_attr(x) container_of(x, struct dev_ext_attribute, attr)
2517 
2518 ssize_t device_store_ulong(struct device *dev,
2519 			   struct device_attribute *attr,
2520 			   const char *buf, size_t size)
2521 {
2522 	struct dev_ext_attribute *ea = to_ext_attr(attr);
2523 	int ret;
2524 	unsigned long new;
2525 
2526 	ret = kstrtoul(buf, 0, &new);
2527 	if (ret)
2528 		return ret;
2529 	*(unsigned long *)(ea->var) = new;
2530 	/* Always return full write size even if we didn't consume all */
2531 	return size;
2532 }
2533 EXPORT_SYMBOL_GPL(device_store_ulong);
2534 
2535 ssize_t device_show_ulong(struct device *dev,
2536 			  struct device_attribute *attr,
2537 			  char *buf)
2538 {
2539 	struct dev_ext_attribute *ea = to_ext_attr(attr);
2540 	return sysfs_emit(buf, "%lx\n", *(unsigned long *)(ea->var));
2541 }
2542 EXPORT_SYMBOL_GPL(device_show_ulong);
2543 
2544 ssize_t device_store_int(struct device *dev,
2545 			 struct device_attribute *attr,
2546 			 const char *buf, size_t size)
2547 {
2548 	struct dev_ext_attribute *ea = to_ext_attr(attr);
2549 	int ret;
2550 	long new;
2551 
2552 	ret = kstrtol(buf, 0, &new);
2553 	if (ret)
2554 		return ret;
2555 
2556 	if (new > INT_MAX || new < INT_MIN)
2557 		return -EINVAL;
2558 	*(int *)(ea->var) = new;
2559 	/* Always return full write size even if we didn't consume all */
2560 	return size;
2561 }
2562 EXPORT_SYMBOL_GPL(device_store_int);
2563 
2564 ssize_t device_show_int(struct device *dev,
2565 			struct device_attribute *attr,
2566 			char *buf)
2567 {
2568 	struct dev_ext_attribute *ea = to_ext_attr(attr);
2569 
2570 	return sysfs_emit(buf, "%d\n", *(int *)(ea->var));
2571 }
2572 EXPORT_SYMBOL_GPL(device_show_int);
2573 
2574 ssize_t device_store_bool(struct device *dev, struct device_attribute *attr,
2575 			  const char *buf, size_t size)
2576 {
2577 	struct dev_ext_attribute *ea = to_ext_attr(attr);
2578 
2579 	if (kstrtobool(buf, ea->var) < 0)
2580 		return -EINVAL;
2581 
2582 	return size;
2583 }
2584 EXPORT_SYMBOL_GPL(device_store_bool);
2585 
2586 ssize_t device_show_bool(struct device *dev, struct device_attribute *attr,
2587 			 char *buf)
2588 {
2589 	struct dev_ext_attribute *ea = to_ext_attr(attr);
2590 
2591 	return sysfs_emit(buf, "%d\n", *(bool *)(ea->var));
2592 }
2593 EXPORT_SYMBOL_GPL(device_show_bool);
2594 
2595 ssize_t device_show_string(struct device *dev,
2596 			   struct device_attribute *attr, char *buf)
2597 {
2598 	struct dev_ext_attribute *ea = to_ext_attr(attr);
2599 
2600 	return sysfs_emit(buf, "%s\n", (char *)ea->var);
2601 }
2602 EXPORT_SYMBOL_GPL(device_show_string);
2603 
2604 /**
2605  * device_release - free device structure.
2606  * @kobj: device's kobject.
2607  *
2608  * This is called once the reference count for the object
2609  * reaches 0. We forward the call to the device's release
2610  * method, which should handle actually freeing the structure.
2611  */
2612 static void device_release(struct kobject *kobj)
2613 {
2614 	struct device *dev = kobj_to_dev(kobj);
2615 	struct device_private *p = dev->p;
2616 
2617 	/*
2618 	 * Some platform devices are driven without driver attached
2619 	 * and managed resources may have been acquired.  Make sure
2620 	 * all resources are released.
2621 	 *
2622 	 * Drivers still can add resources into device after device
2623 	 * is deleted but alive, so release devres here to avoid
2624 	 * possible memory leak.
2625 	 */
2626 	devres_release_all(dev);
2627 
2628 	kfree(dev->dma_range_map);
2629 	kfree(dev->driver_override.name);
2630 
2631 	if (dev->release)
2632 		dev->release(dev);
2633 	else if (dev->type && dev->type->release)
2634 		dev->type->release(dev);
2635 	else if (dev->class && dev->class->dev_release)
2636 		dev->class->dev_release(dev);
2637 	else
2638 		WARN(1, KERN_ERR "Device '%s' does not have a release() function, it is broken and must be fixed. See Documentation/core-api/kobject.rst.\n",
2639 			dev_name(dev));
2640 	kfree(p);
2641 }
2642 
2643 static const struct ns_common *device_namespace(const struct kobject *kobj)
2644 {
2645 	const struct device *dev = kobj_to_dev(kobj);
2646 
2647 	if (dev->class && dev->class->namespace)
2648 		return dev->class->namespace(dev);
2649 
2650 	return NULL;
2651 }
2652 
2653 static void device_get_ownership(const struct kobject *kobj, kuid_t *uid, kgid_t *gid)
2654 {
2655 	const struct device *dev = kobj_to_dev(kobj);
2656 
2657 	if (dev->class && dev->class->get_ownership)
2658 		dev->class->get_ownership(dev, uid, gid);
2659 }
2660 
2661 static const struct kobj_type device_ktype = {
2662 	.release	= device_release,
2663 	.sysfs_ops	= &dev_sysfs_ops,
2664 	.namespace	= device_namespace,
2665 	.get_ownership	= device_get_ownership,
2666 };
2667 
2668 
2669 static int dev_uevent_filter(const struct kobject *kobj)
2670 {
2671 	const struct kobj_type *ktype = get_ktype(kobj);
2672 
2673 	if (ktype == &device_ktype) {
2674 		const struct device *dev = kobj_to_dev(kobj);
2675 		if (dev->bus)
2676 			return 1;
2677 		if (dev->class)
2678 			return 1;
2679 	}
2680 	return 0;
2681 }
2682 
2683 static const char *dev_uevent_name(const struct kobject *kobj)
2684 {
2685 	const struct device *dev = kobj_to_dev(kobj);
2686 
2687 	if (dev->bus)
2688 		return dev->bus->name;
2689 	if (dev->class)
2690 		return dev->class->name;
2691 	return NULL;
2692 }
2693 
2694 /*
2695  * Try filling "DRIVER=<name>" uevent variable for a device. Because this
2696  * function may race with binding and unbinding the device from a driver,
2697  * we need to be careful. Binding is generally safe, at worst we miss the
2698  * fact that the device is already bound to a driver (but the driver
2699  * information that is delivered through uevents is best-effort, it may
2700  * become obsolete as soon as it is generated anyways). Unbinding is more
2701  * risky as driver pointer is transitioning to NULL, so READ_ONCE() should
2702  * be used to make sure we are dealing with the same pointer, and to
2703  * ensure that driver structure is not going to disappear from under us
2704  * we take bus' drivers klist lock. The assumption that only registered
2705  * driver can be bound to a device, and to unregister a driver bus code
2706  * will take the same lock.
2707  */
2708 static void dev_driver_uevent(const struct device *dev, struct kobj_uevent_env *env)
2709 {
2710 	struct subsys_private *sp = bus_to_subsys(dev->bus);
2711 
2712 	if (sp) {
2713 		scoped_guard(spinlock, &sp->klist_drivers.k_lock) {
2714 			struct device_driver *drv = READ_ONCE(dev->driver);
2715 			if (drv)
2716 				add_uevent_var(env, "DRIVER=%s", drv->name);
2717 		}
2718 
2719 		subsys_put(sp);
2720 	}
2721 }
2722 
2723 static int dev_uevent(const struct kobject *kobj, struct kobj_uevent_env *env)
2724 {
2725 	const struct device *dev = kobj_to_dev(kobj);
2726 	int retval = 0;
2727 
2728 	/* add device node properties if present */
2729 	if (MAJOR(dev->devt)) {
2730 		const char *tmp;
2731 		const char *name;
2732 		umode_t mode = 0;
2733 		kuid_t uid = GLOBAL_ROOT_UID;
2734 		kgid_t gid = GLOBAL_ROOT_GID;
2735 
2736 		add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt));
2737 		add_uevent_var(env, "MINOR=%u", MINOR(dev->devt));
2738 		name = device_get_devnode(dev, &mode, &uid, &gid, &tmp);
2739 		if (name) {
2740 			add_uevent_var(env, "DEVNAME=%s", name);
2741 			if (mode)
2742 				add_uevent_var(env, "DEVMODE=%#o", mode & 0777);
2743 			if (!uid_eq(uid, GLOBAL_ROOT_UID))
2744 				add_uevent_var(env, "DEVUID=%u", from_kuid(&init_user_ns, uid));
2745 			if (!gid_eq(gid, GLOBAL_ROOT_GID))
2746 				add_uevent_var(env, "DEVGID=%u", from_kgid(&init_user_ns, gid));
2747 			kfree(tmp);
2748 		}
2749 	}
2750 
2751 	if (dev->type && dev->type->name)
2752 		add_uevent_var(env, "DEVTYPE=%s", dev->type->name);
2753 
2754 	/* Add "DRIVER=%s" variable if the device is bound to a driver */
2755 	dev_driver_uevent(dev, env);
2756 
2757 	/* Add common DT information about the device */
2758 	of_device_uevent(dev, env);
2759 
2760 	/* have the bus specific function add its stuff */
2761 	if (dev->bus && dev->bus->uevent) {
2762 		retval = dev->bus->uevent(dev, env);
2763 		if (retval)
2764 			pr_debug("device: '%s': %s: bus uevent() returned %d\n",
2765 				 dev_name(dev), __func__, retval);
2766 	}
2767 
2768 	/* have the class specific function add its stuff */
2769 	if (dev->class && dev->class->dev_uevent) {
2770 		retval = dev->class->dev_uevent(dev, env);
2771 		if (retval)
2772 			pr_debug("device: '%s': %s: class uevent() "
2773 				 "returned %d\n", dev_name(dev),
2774 				 __func__, retval);
2775 	}
2776 
2777 	/* have the device type specific function add its stuff */
2778 	if (dev->type && dev->type->uevent) {
2779 		retval = dev->type->uevent(dev, env);
2780 		if (retval)
2781 			pr_debug("device: '%s': %s: dev_type uevent() "
2782 				 "returned %d\n", dev_name(dev),
2783 				 __func__, retval);
2784 	}
2785 
2786 	return retval;
2787 }
2788 
2789 static const struct kset_uevent_ops device_uevent_ops = {
2790 	.filter =	dev_uevent_filter,
2791 	.name =		dev_uevent_name,
2792 	.uevent =	dev_uevent,
2793 };
2794 
2795 static ssize_t uevent_show(struct device *dev, const struct device_attribute *attr,
2796 			   char *buf)
2797 {
2798 	struct kobject *top_kobj;
2799 	struct kset *kset;
2800 	struct kobj_uevent_env *env = NULL;
2801 	int i;
2802 	int len = 0;
2803 	int retval;
2804 
2805 	/* search the kset, the device belongs to */
2806 	top_kobj = &dev->kobj;
2807 	while (!top_kobj->kset && top_kobj->parent)
2808 		top_kobj = top_kobj->parent;
2809 	if (!top_kobj->kset)
2810 		goto out;
2811 
2812 	kset = top_kobj->kset;
2813 	if (!kset->uevent_ops || !kset->uevent_ops->uevent)
2814 		goto out;
2815 
2816 	/* respect filter */
2817 	if (kset->uevent_ops && kset->uevent_ops->filter)
2818 		if (!kset->uevent_ops->filter(&dev->kobj))
2819 			goto out;
2820 
2821 	env = kzalloc_obj(struct kobj_uevent_env);
2822 	if (!env)
2823 		return -ENOMEM;
2824 
2825 	/* let the kset specific function add its keys */
2826 	retval = kset->uevent_ops->uevent(&dev->kobj, env);
2827 	if (retval)
2828 		goto out;
2829 
2830 	/* copy keys to file */
2831 	for (i = 0; i < env->envp_idx; i++)
2832 		len += sysfs_emit_at(buf, len, "%s\n", env->envp[i]);
2833 out:
2834 	kfree(env);
2835 	return len;
2836 }
2837 
2838 static ssize_t uevent_store(struct device *dev, const struct device_attribute *attr,
2839 			    const char *buf, size_t count)
2840 {
2841 	int rc;
2842 
2843 	rc = kobject_synth_uevent(&dev->kobj, buf, count);
2844 
2845 	if (rc) {
2846 		dev_err(dev, "uevent: failed to send synthetic uevent: %d\n", rc);
2847 		return rc;
2848 	}
2849 
2850 	return count;
2851 }
2852 static const DEVICE_ATTR_RW(uevent);
2853 
2854 static ssize_t online_show(struct device *dev, const struct device_attribute *attr,
2855 			   char *buf)
2856 {
2857 	bool val;
2858 
2859 	device_lock(dev);
2860 	val = !dev_offline(dev);
2861 	device_unlock(dev);
2862 	return sysfs_emit(buf, "%u\n", val);
2863 }
2864 
2865 static ssize_t online_store(struct device *dev, const struct device_attribute *attr,
2866 			    const char *buf, size_t count)
2867 {
2868 	bool val;
2869 	int ret;
2870 
2871 	ret = kstrtobool(buf, &val);
2872 	if (ret < 0)
2873 		return ret;
2874 
2875 	ret = lock_device_hotplug_sysfs();
2876 	if (ret)
2877 		return ret;
2878 
2879 	ret = val ? device_online(dev) : device_offline(dev);
2880 	unlock_device_hotplug();
2881 	return ret < 0 ? ret : count;
2882 }
2883 static const DEVICE_ATTR_RW(online);
2884 
2885 static ssize_t removable_show(struct device *dev, const struct device_attribute *attr,
2886 			      char *buf)
2887 {
2888 	const char *loc;
2889 
2890 	switch (dev->removable) {
2891 	case DEVICE_REMOVABLE:
2892 		loc = "removable";
2893 		break;
2894 	case DEVICE_FIXED:
2895 		loc = "fixed";
2896 		break;
2897 	default:
2898 		loc = "unknown";
2899 	}
2900 	return sysfs_emit(buf, "%s\n", loc);
2901 }
2902 static const DEVICE_ATTR_RO(removable);
2903 
2904 int device_add_groups(struct device *dev,
2905 		      const struct attribute_group *const *groups)
2906 {
2907 	return sysfs_create_groups(&dev->kobj, groups);
2908 }
2909 EXPORT_SYMBOL_GPL(device_add_groups);
2910 
2911 void device_remove_groups(struct device *dev,
2912 			  const struct attribute_group *const *groups)
2913 {
2914 	sysfs_remove_groups(&dev->kobj, groups);
2915 }
2916 EXPORT_SYMBOL_GPL(device_remove_groups);
2917 
2918 union device_attr_group_devres {
2919 	const struct attribute_group *group;
2920 	const struct attribute_group **groups;
2921 };
2922 
2923 static void devm_attr_group_remove(struct device *dev, void *res)
2924 {
2925 	union device_attr_group_devres *devres = res;
2926 	const struct attribute_group *group = devres->group;
2927 
2928 	dev_dbg(dev, "%s: removing group %p\n", __func__, group);
2929 	sysfs_remove_group(&dev->kobj, group);
2930 }
2931 
2932 /**
2933  * devm_device_add_group - given a device, create a managed attribute group
2934  * @dev:	The device to create the group for
2935  * @grp:	The attribute group to create
2936  *
2937  * This function creates a group for the first time.  It will explicitly
2938  * warn and error if any of the attribute files being created already exist.
2939  *
2940  * Returns 0 on success or error code on failure.
2941  */
2942 int devm_device_add_group(struct device *dev, const struct attribute_group *grp)
2943 {
2944 	union device_attr_group_devres *devres;
2945 	int error;
2946 
2947 	devres = devres_alloc(devm_attr_group_remove,
2948 			      sizeof(*devres), GFP_KERNEL);
2949 	if (!devres)
2950 		return -ENOMEM;
2951 
2952 	error = sysfs_create_group(&dev->kobj, grp);
2953 	if (error) {
2954 		devres_free(devres);
2955 		return error;
2956 	}
2957 
2958 	devres->group = grp;
2959 	devres_add(dev, devres);
2960 	return 0;
2961 }
2962 EXPORT_SYMBOL_GPL(devm_device_add_group);
2963 
2964 static int device_add_attrs(struct device *dev)
2965 {
2966 	const struct class *class = dev->class;
2967 	const struct device_type *type = dev->type;
2968 	int error;
2969 
2970 	if (class) {
2971 		error = device_add_groups(dev, class->dev_groups);
2972 		if (error)
2973 			return error;
2974 	}
2975 
2976 	if (type) {
2977 		error = device_add_groups(dev, type->groups);
2978 		if (error)
2979 			goto err_remove_class_groups;
2980 	}
2981 
2982 	error = device_add_groups(dev, dev->groups);
2983 	if (error)
2984 		goto err_remove_type_groups;
2985 
2986 	if (device_supports_offline(dev) && !dev_offline_disabled(dev)) {
2987 		error = device_create_file(dev, &dev_attr_online);
2988 		if (error)
2989 			goto err_remove_dev_groups;
2990 	}
2991 
2992 	if (fw_devlink_flags && !fw_devlink_is_permissive() && dev->fwnode) {
2993 		error = device_create_file(dev, &dev_attr_waiting_for_supplier);
2994 		if (error)
2995 			goto err_remove_dev_online;
2996 	}
2997 
2998 	if (dev_removable_is_valid(dev)) {
2999 		error = device_create_file(dev, &dev_attr_removable);
3000 		if (error)
3001 			goto err_remove_dev_waiting_for_supplier;
3002 	}
3003 
3004 	if (dev_add_physical_location(dev)) {
3005 		error = device_add_group(dev,
3006 			&dev_attr_physical_location_group);
3007 		if (error)
3008 			goto err_remove_dev_removable;
3009 	}
3010 
3011 	return 0;
3012 
3013  err_remove_dev_removable:
3014 	device_remove_file(dev, &dev_attr_removable);
3015  err_remove_dev_waiting_for_supplier:
3016 	device_remove_file(dev, &dev_attr_waiting_for_supplier);
3017  err_remove_dev_online:
3018 	device_remove_file(dev, &dev_attr_online);
3019  err_remove_dev_groups:
3020 	device_remove_groups(dev, dev->groups);
3021  err_remove_type_groups:
3022 	if (type)
3023 		device_remove_groups(dev, type->groups);
3024  err_remove_class_groups:
3025 	if (class)
3026 		device_remove_groups(dev, class->dev_groups);
3027 
3028 	return error;
3029 }
3030 
3031 static void device_remove_attrs(struct device *dev)
3032 {
3033 	const struct class *class = dev->class;
3034 	const struct device_type *type = dev->type;
3035 
3036 	if (dev->physical_location) {
3037 		device_remove_group(dev, &dev_attr_physical_location_group);
3038 		kfree(dev->physical_location);
3039 	}
3040 
3041 	device_remove_file(dev, &dev_attr_removable);
3042 	device_remove_file(dev, &dev_attr_waiting_for_supplier);
3043 	device_remove_file(dev, &dev_attr_online);
3044 	device_remove_groups(dev, dev->groups);
3045 
3046 	if (type)
3047 		device_remove_groups(dev, type->groups);
3048 
3049 	if (class)
3050 		device_remove_groups(dev, class->dev_groups);
3051 }
3052 
3053 static ssize_t dev_show(struct device *dev, const struct device_attribute *attr,
3054 			char *buf)
3055 {
3056 	return print_dev_t(buf, dev->devt);
3057 }
3058 static const DEVICE_ATTR_RO(dev);
3059 
3060 /* /sys/devices/ */
3061 struct kset *devices_kset;
3062 
3063 /**
3064  * devices_kset_move_before - Move device in the devices_kset's list.
3065  * @deva: Device to move.
3066  * @devb: Device @deva should come before.
3067  */
3068 static void devices_kset_move_before(struct device *deva, struct device *devb)
3069 {
3070 	if (!devices_kset)
3071 		return;
3072 	pr_debug("devices_kset: Moving %s before %s\n",
3073 		 dev_name(deva), dev_name(devb));
3074 	spin_lock(&devices_kset->list_lock);
3075 	list_move_tail(&deva->kobj.entry, &devb->kobj.entry);
3076 	spin_unlock(&devices_kset->list_lock);
3077 }
3078 
3079 /**
3080  * devices_kset_move_after - Move device in the devices_kset's list.
3081  * @deva: Device to move
3082  * @devb: Device @deva should come after.
3083  */
3084 static void devices_kset_move_after(struct device *deva, struct device *devb)
3085 {
3086 	if (!devices_kset)
3087 		return;
3088 	pr_debug("devices_kset: Moving %s after %s\n",
3089 		 dev_name(deva), dev_name(devb));
3090 	spin_lock(&devices_kset->list_lock);
3091 	list_move(&deva->kobj.entry, &devb->kobj.entry);
3092 	spin_unlock(&devices_kset->list_lock);
3093 }
3094 
3095 /**
3096  * devices_kset_move_last - move the device to the end of devices_kset's list.
3097  * @dev: device to move
3098  */
3099 void devices_kset_move_last(struct device *dev)
3100 {
3101 	if (!devices_kset)
3102 		return;
3103 	pr_debug("devices_kset: Moving %s to end of list\n", dev_name(dev));
3104 	spin_lock(&devices_kset->list_lock);
3105 	list_move_tail(&dev->kobj.entry, &devices_kset->list);
3106 	spin_unlock(&devices_kset->list_lock);
3107 }
3108 
3109 /**
3110  * device_create_file - create sysfs attribute file for device.
3111  * @dev: device.
3112  * @attr: device attribute descriptor.
3113  */
3114 int device_create_file(struct device *dev,
3115 		       const struct device_attribute *attr)
3116 {
3117 	int error = 0;
3118 
3119 	if (dev) {
3120 		WARN(((attr->attr.mode & S_IWUGO) && !(attr->store || attr->store_const)),
3121 			"Attribute %s: write permission without 'store'\n",
3122 			attr->attr.name);
3123 		WARN(((attr->attr.mode & S_IRUGO) && !(attr->show || attr->show_const)),
3124 			"Attribute %s: read permission without 'show'\n",
3125 			attr->attr.name);
3126 		error = sysfs_create_file(&dev->kobj, &attr->attr);
3127 	}
3128 
3129 	return error;
3130 }
3131 EXPORT_SYMBOL_GPL(device_create_file);
3132 
3133 /**
3134  * device_remove_file - remove sysfs attribute file.
3135  * @dev: device.
3136  * @attr: device attribute descriptor.
3137  */
3138 void device_remove_file(struct device *dev,
3139 			const struct device_attribute *attr)
3140 {
3141 	if (dev)
3142 		sysfs_remove_file(&dev->kobj, &attr->attr);
3143 }
3144 EXPORT_SYMBOL_GPL(device_remove_file);
3145 
3146 /**
3147  * device_remove_file_self - remove sysfs attribute file from its own method.
3148  * @dev: device.
3149  * @attr: device attribute descriptor.
3150  *
3151  * See kernfs_remove_self() for details.
3152  */
3153 bool device_remove_file_self(struct device *dev,
3154 			     const struct device_attribute *attr)
3155 {
3156 	if (dev)
3157 		return sysfs_remove_file_self(&dev->kobj, &attr->attr);
3158 	else
3159 		return false;
3160 }
3161 EXPORT_SYMBOL_GPL(device_remove_file_self);
3162 
3163 /**
3164  * device_create_bin_file - create sysfs binary attribute file for device.
3165  * @dev: device.
3166  * @attr: device binary attribute descriptor.
3167  */
3168 int device_create_bin_file(struct device *dev,
3169 			   const struct bin_attribute *attr)
3170 {
3171 	int error = -EINVAL;
3172 	if (dev)
3173 		error = sysfs_create_bin_file(&dev->kobj, attr);
3174 	return error;
3175 }
3176 EXPORT_SYMBOL_GPL(device_create_bin_file);
3177 
3178 /**
3179  * device_remove_bin_file - remove sysfs binary attribute file
3180  * @dev: device.
3181  * @attr: device binary attribute descriptor.
3182  */
3183 void device_remove_bin_file(struct device *dev,
3184 			    const struct bin_attribute *attr)
3185 {
3186 	if (dev)
3187 		sysfs_remove_bin_file(&dev->kobj, attr);
3188 }
3189 EXPORT_SYMBOL_GPL(device_remove_bin_file);
3190 
3191 static void klist_children_get(struct klist_node *n)
3192 {
3193 	struct device_private *p = to_device_private_parent(n);
3194 	struct device *dev = p->device;
3195 
3196 	get_device(dev);
3197 }
3198 
3199 static void klist_children_put(struct klist_node *n)
3200 {
3201 	struct device_private *p = to_device_private_parent(n);
3202 	struct device *dev = p->device;
3203 
3204 	put_device(dev);
3205 }
3206 
3207 /**
3208  * device_initialize - init device structure.
3209  * @dev: device.
3210  *
3211  * This prepares the device for use by other layers by initializing
3212  * its fields.
3213  * It is the first half of device_register(), if called by
3214  * that function, though it can also be called separately, so one
3215  * may use @dev's fields. In particular, get_device()/put_device()
3216  * may be used for reference counting of @dev after calling this
3217  * function.
3218  *
3219  * All fields in @dev must be initialized by the caller to 0, except
3220  * for those explicitly set to some other value.  The simplest
3221  * approach is to use kzalloc() to allocate the structure containing
3222  * @dev.
3223  *
3224  * NOTE: Use put_device() to give up your reference instead of freeing
3225  * @dev directly once you have called this function.
3226  */
3227 void device_initialize(struct device *dev)
3228 {
3229 	dev->kobj.kset = devices_kset;
3230 	kobject_init(&dev->kobj, &device_ktype);
3231 	INIT_LIST_HEAD(&dev->dma_pools);
3232 	mutex_init(&dev->mutex);
3233 	spin_lock_init(&dev->driver_override.lock);
3234 	lockdep_set_novalidate_class(&dev->mutex);
3235 	spin_lock_init(&dev->devres_lock);
3236 	INIT_LIST_HEAD(&dev->devres_head);
3237 	device_pm_init(dev);
3238 	set_dev_node(dev, NUMA_NO_NODE);
3239 	INIT_LIST_HEAD(&dev->links.consumers);
3240 	INIT_LIST_HEAD(&dev->links.suppliers);
3241 	INIT_LIST_HEAD(&dev->links.defer_sync);
3242 	dev->links.status = DL_DEV_NO_DRIVER;
3243 	dev_assign_dma_coherent(dev, dma_default_coherent);
3244 	swiotlb_dev_init(dev);
3245 }
3246 EXPORT_SYMBOL_GPL(device_initialize);
3247 
3248 struct kobject *virtual_device_parent(void)
3249 {
3250 	static struct kobject *virtual_dir = NULL;
3251 
3252 	if (!virtual_dir)
3253 		virtual_dir = kobject_create_and_add("virtual",
3254 						     &devices_kset->kobj);
3255 
3256 	return virtual_dir;
3257 }
3258 
3259 struct class_dir {
3260 	struct kobject kobj;
3261 	const struct class *class;
3262 };
3263 
3264 #define to_class_dir(obj) container_of(obj, struct class_dir, kobj)
3265 
3266 static void class_dir_release(struct kobject *kobj)
3267 {
3268 	struct class_dir *dir = to_class_dir(kobj);
3269 	kfree(dir);
3270 }
3271 
3272 static const
3273 struct kobj_ns_type_operations *class_dir_child_ns_type(const struct kobject *kobj)
3274 {
3275 	const struct class_dir *dir = to_class_dir(kobj);
3276 	return dir->class->ns_type;
3277 }
3278 
3279 static const struct kobj_type class_dir_ktype = {
3280 	.release	= class_dir_release,
3281 	.sysfs_ops	= &kobj_sysfs_ops,
3282 	.child_ns_type	= class_dir_child_ns_type
3283 };
3284 
3285 static struct kobject *class_dir_create_and_add(struct subsys_private *sp,
3286 						struct kobject *parent_kobj)
3287 {
3288 	struct class_dir *dir;
3289 	int retval;
3290 
3291 	dir = kzalloc_obj(*dir);
3292 	if (!dir)
3293 		return ERR_PTR(-ENOMEM);
3294 
3295 	dir->class = sp->class;
3296 	kobject_init(&dir->kobj, &class_dir_ktype);
3297 
3298 	dir->kobj.kset = &sp->glue_dirs;
3299 
3300 	retval = kobject_add(&dir->kobj, parent_kobj, "%s", sp->class->name);
3301 	if (retval < 0) {
3302 		kobject_put(&dir->kobj);
3303 		return ERR_PTR(retval);
3304 	}
3305 	return &dir->kobj;
3306 }
3307 
3308 static DEFINE_MUTEX(gdp_mutex);
3309 
3310 static struct kobject *get_device_parent(struct device *dev,
3311 					 struct device *parent)
3312 {
3313 	struct subsys_private *sp = class_to_subsys(dev->class);
3314 	struct kobject *kobj = NULL;
3315 
3316 	if (sp) {
3317 		struct kobject *parent_kobj;
3318 		struct kobject *k;
3319 
3320 		/*
3321 		 * If we have no parent, we live in "virtual".
3322 		 * Class-devices with a non class-device as parent, live
3323 		 * in a "glue" directory to prevent namespace collisions.
3324 		 */
3325 		if (parent == NULL)
3326 			parent_kobj = virtual_device_parent();
3327 		else if (parent->class && !dev->class->ns_type) {
3328 			subsys_put(sp);
3329 			return &parent->kobj;
3330 		} else {
3331 			parent_kobj = &parent->kobj;
3332 		}
3333 
3334 		mutex_lock(&gdp_mutex);
3335 
3336 		/* find our class-directory at the parent and reference it */
3337 		spin_lock(&sp->glue_dirs.list_lock);
3338 		list_for_each_entry(k, &sp->glue_dirs.list, entry)
3339 			if (k->parent == parent_kobj) {
3340 				kobj = kobject_get(k);
3341 				break;
3342 			}
3343 		spin_unlock(&sp->glue_dirs.list_lock);
3344 		if (kobj) {
3345 			mutex_unlock(&gdp_mutex);
3346 			subsys_put(sp);
3347 			return kobj;
3348 		}
3349 
3350 		/* or create a new class-directory at the parent device */
3351 		k = class_dir_create_and_add(sp, parent_kobj);
3352 		/* do not emit an uevent for this simple "glue" directory */
3353 		mutex_unlock(&gdp_mutex);
3354 		subsys_put(sp);
3355 		return k;
3356 	}
3357 
3358 	/* subsystems can specify a default root directory for their devices */
3359 	if (!parent && dev->bus) {
3360 		struct device *dev_root = bus_get_dev_root(dev->bus);
3361 
3362 		if (dev_root) {
3363 			kobj = &dev_root->kobj;
3364 			put_device(dev_root);
3365 			return kobj;
3366 		}
3367 	}
3368 
3369 	if (parent)
3370 		return &parent->kobj;
3371 	return NULL;
3372 }
3373 
3374 static inline bool live_in_glue_dir(struct kobject *kobj,
3375 				    struct device *dev)
3376 {
3377 	struct subsys_private *sp;
3378 	bool retval;
3379 
3380 	if (!kobj || !dev->class)
3381 		return false;
3382 
3383 	sp = class_to_subsys(dev->class);
3384 	if (!sp)
3385 		return false;
3386 
3387 	if (kobj->kset == &sp->glue_dirs)
3388 		retval = true;
3389 	else
3390 		retval = false;
3391 
3392 	subsys_put(sp);
3393 	return retval;
3394 }
3395 
3396 static inline struct kobject *get_glue_dir(struct device *dev)
3397 {
3398 	return dev->kobj.parent;
3399 }
3400 
3401 /**
3402  * kobject_has_children - Returns whether a kobject has children.
3403  * @kobj: the object to test
3404  *
3405  * This will return whether a kobject has other kobjects as children.
3406  *
3407  * It does NOT account for the presence of attribute files, only sub
3408  * directories. It also assumes there is no concurrent addition or
3409  * removal of such children, and thus relies on external locking.
3410  */
3411 static inline bool kobject_has_children(struct kobject *kobj)
3412 {
3413 	WARN_ON_ONCE(kref_read(&kobj->kref) == 0);
3414 
3415 	return kobj->sd && kobj->sd->dir.subdirs;
3416 }
3417 
3418 /*
3419  * make sure cleaning up dir as the last step, we need to make
3420  * sure .release handler of kobject is run with holding the
3421  * global lock
3422  */
3423 static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir)
3424 {
3425 	unsigned int ref;
3426 
3427 	/* see if we live in a "glue" directory */
3428 	if (!live_in_glue_dir(glue_dir, dev))
3429 		return;
3430 
3431 	mutex_lock(&gdp_mutex);
3432 	/**
3433 	 * There is a race condition between removing glue directory
3434 	 * and adding a new device under the glue directory.
3435 	 *
3436 	 * CPU1:                                         CPU2:
3437 	 *
3438 	 * device_add()
3439 	 *   get_device_parent()
3440 	 *     class_dir_create_and_add()
3441 	 *       kobject_add_internal()
3442 	 *         create_dir()    // create glue_dir
3443 	 *
3444 	 *                                               device_add()
3445 	 *                                                 get_device_parent()
3446 	 *                                                   kobject_get() // get glue_dir
3447 	 *
3448 	 * device_del()
3449 	 *   cleanup_glue_dir()
3450 	 *     kobject_del(glue_dir)
3451 	 *
3452 	 *                                               kobject_add()
3453 	 *                                                 kobject_add_internal()
3454 	 *                                                   create_dir() // in glue_dir
3455 	 *                                                     sysfs_create_dir_ns()
3456 	 *                                                       kernfs_create_dir_ns(sd)
3457 	 *
3458 	 *       sysfs_remove_dir() // glue_dir->sd=NULL
3459 	 *       sysfs_put()        // free glue_dir->sd
3460 	 *
3461 	 *                                                         // sd is freed
3462 	 *                                                         kernfs_new_node(sd)
3463 	 *                                                           kernfs_get(glue_dir)
3464 	 *                                                           kernfs_add_one()
3465 	 *                                                           kernfs_put()
3466 	 *
3467 	 * Before CPU1 remove last child device under glue dir, if CPU2 add
3468 	 * a new device under glue dir, the glue_dir kobject reference count
3469 	 * will be increase to 2 in kobject_get(k). And CPU2 has been called
3470 	 * kernfs_create_dir_ns(). Meanwhile, CPU1 call sysfs_remove_dir()
3471 	 * and sysfs_put(). This result in glue_dir->sd is freed.
3472 	 *
3473 	 * Then the CPU2 will see a stale "empty" but still potentially used
3474 	 * glue dir around in kernfs_new_node().
3475 	 *
3476 	 * In order to avoid this happening, we also should make sure that
3477 	 * kernfs_node for glue_dir is released in CPU1 only when refcount
3478 	 * for glue_dir kobj is 1.
3479 	 */
3480 	ref = kref_read(&glue_dir->kref);
3481 	if (!kobject_has_children(glue_dir) && !--ref)
3482 		kobject_del(glue_dir);
3483 	kobject_put(glue_dir);
3484 	mutex_unlock(&gdp_mutex);
3485 }
3486 
3487 static int device_add_class_symlinks(struct device *dev)
3488 {
3489 	struct device_node *of_node = dev_of_node(dev);
3490 	struct subsys_private *sp;
3491 	int error;
3492 
3493 	if (of_node) {
3494 		error = sysfs_create_link(&dev->kobj, of_node_kobj(of_node), "of_node");
3495 		if (error)
3496 			dev_warn(dev, "Error %d creating of_node link\n",error);
3497 		/* An error here doesn't warrant bringing down the device */
3498 	}
3499 
3500 	sp = class_to_subsys(dev->class);
3501 	if (!sp)
3502 		return 0;
3503 
3504 	error = sysfs_create_link(&dev->kobj, &sp->subsys.kobj, "subsystem");
3505 	if (error)
3506 		goto out_devnode;
3507 
3508 	if (dev->parent && device_is_not_partition(dev)) {
3509 		error = sysfs_create_link(&dev->kobj, &dev->parent->kobj,
3510 					  "device");
3511 		if (error)
3512 			goto out_subsys;
3513 	}
3514 
3515 	/* link in the class directory pointing to the device */
3516 	error = sysfs_create_link(&sp->subsys.kobj, &dev->kobj, dev_name(dev));
3517 	if (error)
3518 		goto out_device;
3519 	goto exit;
3520 
3521 out_device:
3522 	sysfs_remove_link(&dev->kobj, "device");
3523 out_subsys:
3524 	sysfs_remove_link(&dev->kobj, "subsystem");
3525 out_devnode:
3526 	sysfs_remove_link(&dev->kobj, "of_node");
3527 exit:
3528 	subsys_put(sp);
3529 	return error;
3530 }
3531 
3532 static void device_remove_class_symlinks(struct device *dev)
3533 {
3534 	struct subsys_private *sp = class_to_subsys(dev->class);
3535 
3536 	if (dev_of_node(dev))
3537 		sysfs_remove_link(&dev->kobj, "of_node");
3538 
3539 	if (!sp)
3540 		return;
3541 
3542 	if (dev->parent && device_is_not_partition(dev))
3543 		sysfs_remove_link(&dev->kobj, "device");
3544 	sysfs_remove_link(&dev->kobj, "subsystem");
3545 	sysfs_delete_link(&sp->subsys.kobj, &dev->kobj, dev_name(dev));
3546 	subsys_put(sp);
3547 }
3548 
3549 /**
3550  * dev_set_name - set a device name
3551  * @dev: device
3552  * @fmt: format string for the device's name
3553  */
3554 int dev_set_name(struct device *dev, const char *fmt, ...)
3555 {
3556 	va_list vargs;
3557 	int err;
3558 
3559 	va_start(vargs, fmt);
3560 	err = kobject_set_name_vargs(&dev->kobj, fmt, vargs);
3561 	va_end(vargs);
3562 	return err;
3563 }
3564 EXPORT_SYMBOL_GPL(dev_set_name);
3565 
3566 /* select a /sys/dev/ directory for the device */
3567 static struct kobject *device_to_dev_kobj(struct device *dev)
3568 {
3569 	if (is_blockdev(dev))
3570 		return sysfs_dev_block_kobj;
3571 	else
3572 		return sysfs_dev_char_kobj;
3573 }
3574 
3575 static int device_create_sys_dev_entry(struct device *dev)
3576 {
3577 	struct kobject *kobj = device_to_dev_kobj(dev);
3578 	int error = 0;
3579 	char devt_str[15];
3580 
3581 	if (kobj) {
3582 		format_dev_t(devt_str, dev->devt);
3583 		error = sysfs_create_link(kobj, &dev->kobj, devt_str);
3584 	}
3585 
3586 	return error;
3587 }
3588 
3589 static void device_remove_sys_dev_entry(struct device *dev)
3590 {
3591 	struct kobject *kobj = device_to_dev_kobj(dev);
3592 	char devt_str[15];
3593 
3594 	if (kobj) {
3595 		format_dev_t(devt_str, dev->devt);
3596 		sysfs_remove_link(kobj, devt_str);
3597 	}
3598 }
3599 
3600 static int device_private_init(struct device *dev)
3601 {
3602 	dev->p = kzalloc_obj(*dev->p);
3603 	if (!dev->p)
3604 		return -ENOMEM;
3605 	dev->p->device = dev;
3606 	klist_init(&dev->p->klist_children, klist_children_get,
3607 		   klist_children_put);
3608 	INIT_LIST_HEAD(&dev->p->deferred_probe);
3609 	return 0;
3610 }
3611 
3612 /**
3613  * device_add - add device to device hierarchy.
3614  * @dev: device.
3615  *
3616  * This is part 2 of device_register(), though may be called
3617  * separately _iff_ device_initialize() has been called separately.
3618  *
3619  * This adds @dev to the kobject hierarchy via kobject_add(), adds it
3620  * to the global and sibling lists for the device, then
3621  * adds it to the other relevant subsystems of the driver model.
3622  *
3623  * Do not call this routine or device_register() more than once for
3624  * any device structure.  The driver model core is not designed to work
3625  * with devices that get unregistered and then spring back to life.
3626  * (Among other things, it's very hard to guarantee that all references
3627  * to the previous incarnation of @dev have been dropped.)  Allocate
3628  * and register a fresh new struct device instead.
3629  *
3630  * NOTE: _Never_ directly free @dev after calling this function, even
3631  * if it returned an error! Always use put_device() to give up your
3632  * reference instead.
3633  *
3634  * Rule of thumb is: if device_add() succeeds, you should call
3635  * device_del() when you want to get rid of it. If device_add() has
3636  * *not* succeeded, use *only* put_device() to drop the reference
3637  * count.
3638  */
3639 int device_add(struct device *dev)
3640 {
3641 	struct subsys_private *sp;
3642 	struct device *parent;
3643 	struct kobject *kobj;
3644 	struct class_interface *class_intf;
3645 	int error = -EINVAL;
3646 	struct kobject *glue_dir = NULL;
3647 
3648 	dev = get_device(dev);
3649 	if (!dev)
3650 		goto done;
3651 
3652 	if (!dev->p) {
3653 		error = device_private_init(dev);
3654 		if (error)
3655 			goto done;
3656 	}
3657 
3658 	/*
3659 	 * for statically allocated devices, which should all be converted
3660 	 * some day, we need to initialize the name. We prevent reading back
3661 	 * the name, and force the use of dev_name()
3662 	 */
3663 	if (dev->init_name) {
3664 		error = dev_set_name(dev, "%s", dev->init_name);
3665 		dev->init_name = NULL;
3666 	}
3667 
3668 	if (dev_name(dev))
3669 		error = 0;
3670 	/* subsystems can specify simple device enumeration */
3671 	else if (dev->bus && dev->bus->dev_name)
3672 		error = dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
3673 	else
3674 		error = -EINVAL;
3675 	if (error)
3676 		goto name_error;
3677 
3678 	pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3679 
3680 	parent = get_device(dev->parent);
3681 	kobj = get_device_parent(dev, parent);
3682 	if (IS_ERR(kobj)) {
3683 		error = PTR_ERR(kobj);
3684 		goto parent_error;
3685 	}
3686 	if (kobj)
3687 		dev->kobj.parent = kobj;
3688 
3689 	/* use parent numa_node */
3690 	if (parent && (dev_to_node(dev) == NUMA_NO_NODE))
3691 		set_dev_node(dev, dev_to_node(parent));
3692 
3693 	/* first, register with generic layer. */
3694 	/* we require the name to be set before, and pass NULL */
3695 	error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
3696 	if (error) {
3697 		glue_dir = kobj;
3698 		goto Error;
3699 	}
3700 
3701 	/* notify platform of device entry */
3702 	device_platform_notify(dev);
3703 
3704 	error = device_create_file(dev, &dev_attr_uevent);
3705 	if (error)
3706 		goto attrError;
3707 
3708 	error = device_add_class_symlinks(dev);
3709 	if (error)
3710 		goto SymlinkError;
3711 	error = device_add_attrs(dev);
3712 	if (error)
3713 		goto AttrsError;
3714 	error = bus_add_device(dev);
3715 	if (error)
3716 		goto BusError;
3717 	error = dpm_sysfs_add(dev);
3718 	if (error)
3719 		goto DPMError;
3720 	device_pm_add(dev);
3721 
3722 	if (MAJOR(dev->devt)) {
3723 		error = device_create_file(dev, &dev_attr_dev);
3724 		if (error)
3725 			goto DevAttrError;
3726 
3727 		error = device_create_sys_dev_entry(dev);
3728 		if (error)
3729 			goto SysEntryError;
3730 
3731 		devtmpfs_create_node(dev);
3732 	}
3733 
3734 	/* Notify clients of device addition.  This call must come
3735 	 * after dpm_sysfs_add() and before kobject_uevent().
3736 	 */
3737 	bus_notify(dev, BUS_NOTIFY_ADD_DEVICE);
3738 	kobject_uevent(&dev->kobj, KOBJ_ADD);
3739 
3740 	/*
3741 	 * Check if any of the other devices (consumers) have been waiting for
3742 	 * this device (supplier) to be added so that they can create a device
3743 	 * link to it.
3744 	 *
3745 	 * This needs to happen after device_pm_add() because device_link_add()
3746 	 * requires the supplier be registered before it's called.
3747 	 *
3748 	 * But this also needs to happen before bus_probe_device() to make sure
3749 	 * waiting consumers can link to it before the driver is bound to the
3750 	 * device and the driver sync_state callback is called for this device.
3751 	 */
3752 	if (dev->fwnode && !dev->fwnode->dev) {
3753 		dev->fwnode->dev = dev;
3754 		fw_devlink_link_device(dev);
3755 	}
3756 
3757 	/*
3758 	 * The moment the device was linked into the bus's "klist_devices" in
3759 	 * bus_add_device() then it's possible that probe could have been
3760 	 * attempted in a different thread via userspace loading a driver
3761 	 * matching the device. "ready_to_probe" being unset would have
3762 	 * blocked those attempts. Now that all of the above initialization has
3763 	 * happened, unblock probe. If probe happens through another thread
3764 	 * after this point but before bus_probe_device() runs then it's fine.
3765 	 * bus_probe_device() -> device_initial_probe() -> __device_attach()
3766 	 * will notice (under device_lock) that the device is already bound.
3767 	 */
3768 	device_lock(dev);
3769 	dev_set_ready_to_probe(dev);
3770 	device_unlock(dev);
3771 
3772 	bus_probe_device(dev);
3773 
3774 	/*
3775 	 * If all driver registration is done and a newly added device doesn't
3776 	 * match with any driver, don't block its consumers from probing in
3777 	 * case the consumer device is able to operate without this supplier.
3778 	 */
3779 	if (dev->fwnode && fw_devlink_drv_reg_done && !dev_can_match(dev))
3780 		fw_devlink_unblock_consumers(dev);
3781 
3782 	if (parent)
3783 		klist_add_tail(&dev->p->knode_parent,
3784 			       &parent->p->klist_children);
3785 
3786 	sp = class_to_subsys(dev->class);
3787 	if (sp) {
3788 		mutex_lock(&sp->mutex);
3789 		/* tie the class to the device */
3790 		klist_add_tail(&dev->p->knode_class, &sp->klist_devices);
3791 
3792 		/* notify any interfaces that the device is here */
3793 		list_for_each_entry(class_intf, &sp->interfaces, node)
3794 			if (class_intf->add_dev)
3795 				class_intf->add_dev(dev);
3796 		mutex_unlock(&sp->mutex);
3797 		subsys_put(sp);
3798 	}
3799 done:
3800 	put_device(dev);
3801 	return error;
3802  SysEntryError:
3803 	if (MAJOR(dev->devt))
3804 		device_remove_file(dev, &dev_attr_dev);
3805  DevAttrError:
3806 	device_pm_remove(dev);
3807 	dpm_sysfs_remove(dev);
3808  DPMError:
3809 	device_set_driver(dev, NULL);
3810 	bus_remove_device(dev);
3811  BusError:
3812 	device_remove_attrs(dev);
3813  AttrsError:
3814 	device_remove_class_symlinks(dev);
3815  SymlinkError:
3816 	device_remove_file(dev, &dev_attr_uevent);
3817  attrError:
3818 	device_platform_notify_remove(dev);
3819 	kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3820 	glue_dir = get_glue_dir(dev);
3821 	kobject_del(&dev->kobj);
3822  Error:
3823 	cleanup_glue_dir(dev, glue_dir);
3824 parent_error:
3825 	put_device(parent);
3826 name_error:
3827 	kfree(dev->p);
3828 	dev->p = NULL;
3829 	goto done;
3830 }
3831 EXPORT_SYMBOL_GPL(device_add);
3832 
3833 /**
3834  * device_register - register a device with the system.
3835  * @dev: pointer to the device structure
3836  *
3837  * This happens in two clean steps - initialize the device
3838  * and add it to the system. The two steps can be called
3839  * separately, but this is the easiest and most common.
3840  * I.e. you should only call the two helpers separately if
3841  * have a clearly defined need to use and refcount the device
3842  * before it is added to the hierarchy.
3843  *
3844  * For more information, see the kerneldoc for device_initialize()
3845  * and device_add().
3846  *
3847  * NOTE: _Never_ directly free @dev after calling this function, even
3848  * if it returned an error! Always use put_device() to give up the
3849  * reference initialized in this function instead.
3850  */
3851 int device_register(struct device *dev)
3852 {
3853 	device_initialize(dev);
3854 	return device_add(dev);
3855 }
3856 EXPORT_SYMBOL_GPL(device_register);
3857 
3858 /**
3859  * get_device - increment reference count for device.
3860  * @dev: device.
3861  *
3862  * This simply forwards the call to kobject_get(), though
3863  * we do take care to provide for the case that we get a NULL
3864  * pointer passed in.
3865  */
3866 struct device *get_device(struct device *dev)
3867 {
3868 	return dev ? kobj_to_dev(kobject_get(&dev->kobj)) : NULL;
3869 }
3870 EXPORT_SYMBOL_GPL(get_device);
3871 
3872 /**
3873  * put_device - decrement reference count.
3874  * @dev: device in question.
3875  */
3876 void put_device(struct device *dev)
3877 {
3878 	/* might_sleep(); */
3879 	if (dev)
3880 		kobject_put(&dev->kobj);
3881 }
3882 EXPORT_SYMBOL_GPL(put_device);
3883 
3884 bool kill_device(struct device *dev)
3885 {
3886 	/*
3887 	 * Require the device lock and set the "dead" flag to guarantee that
3888 	 * the update behavior is consistent with the other bitfields near
3889 	 * it and that we cannot have an asynchronous probe routine trying
3890 	 * to run while we are tearing out the bus/class/sysfs from
3891 	 * underneath the device.
3892 	 */
3893 	device_lock_assert(dev);
3894 
3895 	if (dev->p->dead)
3896 		return false;
3897 	dev->p->dead = true;
3898 	return true;
3899 }
3900 EXPORT_SYMBOL_GPL(kill_device);
3901 
3902 /**
3903  * device_del - delete device from system.
3904  * @dev: device.
3905  *
3906  * This is the first part of the device unregistration
3907  * sequence. This removes the device from the lists we control
3908  * from here, has it removed from the other driver model
3909  * subsystems it was added to in device_add(), and removes it
3910  * from the kobject hierarchy.
3911  *
3912  * NOTE: this should be called manually _iff_ device_add() was
3913  * also called manually.
3914  */
3915 void device_del(struct device *dev)
3916 {
3917 	struct subsys_private *sp;
3918 	struct device *parent = dev->parent;
3919 	struct kobject *glue_dir = NULL;
3920 	struct class_interface *class_intf;
3921 	unsigned int noio_flag;
3922 
3923 	device_lock(dev);
3924 	kill_device(dev);
3925 	device_unlock(dev);
3926 
3927 	if (dev->fwnode && dev->fwnode->dev == dev)
3928 		dev->fwnode->dev = NULL;
3929 
3930 	/* Notify clients of device removal.  This call must come
3931 	 * before dpm_sysfs_remove().
3932 	 */
3933 	noio_flag = memalloc_noio_save();
3934 	bus_notify(dev, BUS_NOTIFY_DEL_DEVICE);
3935 
3936 	dpm_sysfs_remove(dev);
3937 	if (parent)
3938 		klist_del(&dev->p->knode_parent);
3939 	if (MAJOR(dev->devt)) {
3940 		devtmpfs_delete_node(dev);
3941 		device_remove_sys_dev_entry(dev);
3942 		device_remove_file(dev, &dev_attr_dev);
3943 	}
3944 
3945 	sp = class_to_subsys(dev->class);
3946 	if (sp) {
3947 		device_remove_class_symlinks(dev);
3948 
3949 		mutex_lock(&sp->mutex);
3950 		/* notify any interfaces that the device is now gone */
3951 		list_for_each_entry(class_intf, &sp->interfaces, node)
3952 			if (class_intf->remove_dev)
3953 				class_intf->remove_dev(dev);
3954 		/* remove the device from the class list */
3955 		klist_del(&dev->p->knode_class);
3956 		mutex_unlock(&sp->mutex);
3957 		subsys_put(sp);
3958 	}
3959 	device_remove_file(dev, &dev_attr_uevent);
3960 	device_remove_attrs(dev);
3961 	bus_remove_device(dev);
3962 	device_pm_remove(dev);
3963 	driver_deferred_probe_del(dev);
3964 	device_platform_notify_remove(dev);
3965 	device_links_purge(dev);
3966 
3967 	/*
3968 	 * If a device does not have a driver attached, we need to clean
3969 	 * up any managed resources. We do this in device_release(), but
3970 	 * it's never called (and we leak the device) if a managed
3971 	 * resource holds a reference to the device. So release all
3972 	 * managed resources here, like we do in driver_detach(). We
3973 	 * still need to do so again in device_release() in case someone
3974 	 * adds a new resource after this point, though.
3975 	 */
3976 	devres_release_all(dev);
3977 
3978 	bus_notify(dev, BUS_NOTIFY_REMOVED_DEVICE);
3979 	kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3980 	glue_dir = get_glue_dir(dev);
3981 	kobject_del(&dev->kobj);
3982 	cleanup_glue_dir(dev, glue_dir);
3983 	memalloc_noio_restore(noio_flag);
3984 	put_device(parent);
3985 }
3986 EXPORT_SYMBOL_GPL(device_del);
3987 
3988 /**
3989  * device_unregister - unregister device from system.
3990  * @dev: device going away.
3991  *
3992  * We do this in two parts, like we do device_register(). First,
3993  * we remove it from all the subsystems with device_del(), then
3994  * we decrement the reference count via put_device(). If that
3995  * is the final reference count, the device will be cleaned up
3996  * via device_release() above. Otherwise, the structure will
3997  * stick around until the final reference to the device is dropped.
3998  */
3999 void device_unregister(struct device *dev)
4000 {
4001 	pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
4002 	device_del(dev);
4003 	put_device(dev);
4004 }
4005 EXPORT_SYMBOL_GPL(device_unregister);
4006 
4007 static struct device *prev_device(struct klist_iter *i)
4008 {
4009 	struct klist_node *n = klist_prev(i);
4010 	struct device *dev = NULL;
4011 	struct device_private *p;
4012 
4013 	if (n) {
4014 		p = to_device_private_parent(n);
4015 		dev = p->device;
4016 	}
4017 	return dev;
4018 }
4019 
4020 static struct device *next_device(struct klist_iter *i)
4021 {
4022 	struct klist_node *n = klist_next(i);
4023 	struct device *dev = NULL;
4024 	struct device_private *p;
4025 
4026 	if (n) {
4027 		p = to_device_private_parent(n);
4028 		dev = p->device;
4029 	}
4030 	return dev;
4031 }
4032 
4033 /**
4034  * device_get_devnode - path of device node file
4035  * @dev: device
4036  * @mode: returned file access mode
4037  * @uid: returned file owner
4038  * @gid: returned file group
4039  * @tmp: possibly allocated string
4040  *
4041  * Return the relative path of a possible device node.
4042  * Non-default names may need to allocate a memory to compose
4043  * a name. This memory is returned in tmp and needs to be
4044  * freed by the caller.
4045  */
4046 const char *device_get_devnode(const struct device *dev,
4047 			       umode_t *mode, kuid_t *uid, kgid_t *gid,
4048 			       const char **tmp)
4049 {
4050 	char *s;
4051 
4052 	*tmp = NULL;
4053 
4054 	/* the device type may provide a specific name */
4055 	if (dev->type && dev->type->devnode)
4056 		*tmp = dev->type->devnode(dev, mode, uid, gid);
4057 	if (*tmp)
4058 		return *tmp;
4059 
4060 	/* the class may provide a specific name */
4061 	if (dev->class && dev->class->devnode)
4062 		*tmp = dev->class->devnode(dev, mode);
4063 	if (*tmp)
4064 		return *tmp;
4065 
4066 	/* return name without allocation, tmp == NULL */
4067 	if (strchr(dev_name(dev), '!') == NULL)
4068 		return dev_name(dev);
4069 
4070 	/* replace '!' in the name with '/' */
4071 	s = kstrdup_and_replace(dev_name(dev), '!', '/', GFP_KERNEL);
4072 	if (!s)
4073 		return NULL;
4074 	return *tmp = s;
4075 }
4076 
4077 /**
4078  * device_for_each_child - device child iterator.
4079  * @parent: parent struct device.
4080  * @data: data for the callback.
4081  * @fn: function to be called for each device.
4082  *
4083  * Iterate over @parent's child devices, and call @fn for each,
4084  * passing it @data.
4085  *
4086  * We check the return of @fn each time. If it returns anything
4087  * other than 0, we break out and return that value.
4088  */
4089 int device_for_each_child(struct device *parent, void *data,
4090 			  device_iter_t fn)
4091 {
4092 	struct klist_iter i;
4093 	struct device *child;
4094 	int error = 0;
4095 
4096 	if (!parent || !parent->p)
4097 		return 0;
4098 
4099 	klist_iter_init(&parent->p->klist_children, &i);
4100 	while (!error && (child = next_device(&i)))
4101 		error = fn(child, data);
4102 	klist_iter_exit(&i);
4103 	return error;
4104 }
4105 EXPORT_SYMBOL_GPL(device_for_each_child);
4106 
4107 /**
4108  * device_for_each_child_reverse - device child iterator in reversed order.
4109  * @parent: parent struct device.
4110  * @data: data for the callback.
4111  * @fn: function to be called for each device.
4112  *
4113  * Iterate over @parent's child devices, and call @fn for each,
4114  * passing it @data.
4115  *
4116  * We check the return of @fn each time. If it returns anything
4117  * other than 0, we break out and return that value.
4118  */
4119 int device_for_each_child_reverse(struct device *parent, void *data,
4120 				  device_iter_t fn)
4121 {
4122 	struct klist_iter i;
4123 	struct device *child;
4124 	int error = 0;
4125 
4126 	if (!parent || !parent->p)
4127 		return 0;
4128 
4129 	klist_iter_init(&parent->p->klist_children, &i);
4130 	while ((child = prev_device(&i)) && !error)
4131 		error = fn(child, data);
4132 	klist_iter_exit(&i);
4133 	return error;
4134 }
4135 EXPORT_SYMBOL_GPL(device_for_each_child_reverse);
4136 
4137 /**
4138  * device_for_each_child_reverse_from - device child iterator in reversed order.
4139  * @parent: parent struct device.
4140  * @from: optional starting point in child list
4141  * @data: data for the callback.
4142  * @fn: function to be called for each device.
4143  *
4144  * Iterate over @parent's child devices, starting at @from, and call @fn
4145  * for each, passing it @data. This helper is identical to
4146  * device_for_each_child_reverse() when @from is NULL.
4147  *
4148  * @fn is checked each iteration. If it returns anything other than 0,
4149  * iteration stop and that value is returned to the caller of
4150  * device_for_each_child_reverse_from();
4151  */
4152 int device_for_each_child_reverse_from(struct device *parent,
4153 				       struct device *from, void *data,
4154 				       device_iter_t fn)
4155 {
4156 	struct klist_iter i;
4157 	struct device *child;
4158 	int error = 0;
4159 
4160 	if (!parent || !parent->p)
4161 		return 0;
4162 
4163 	klist_iter_init_node(&parent->p->klist_children, &i,
4164 			     (from ? &from->p->knode_parent : NULL));
4165 	while ((child = prev_device(&i)) && !error)
4166 		error = fn(child, data);
4167 	klist_iter_exit(&i);
4168 	return error;
4169 }
4170 EXPORT_SYMBOL_GPL(device_for_each_child_reverse_from);
4171 
4172 /**
4173  * device_find_child - device iterator for locating a particular device.
4174  * @parent: parent struct device
4175  * @data: Data to pass to match function
4176  * @match: Callback function to check device
4177  *
4178  * This is similar to the device_for_each_child() function above, but it
4179  * returns a reference to a device that is 'found' for later use, as
4180  * determined by the @match callback.
4181  *
4182  * The callback should return 0 if the device doesn't match and non-zero
4183  * if it does.  If the callback returns non-zero and a reference to the
4184  * current device can be obtained, this function will return to the caller
4185  * and not iterate over any more devices.
4186  *
4187  * NOTE: you will need to drop the reference with put_device() after use.
4188  */
4189 struct device *device_find_child(struct device *parent, const void *data,
4190 				 device_match_t match)
4191 {
4192 	struct klist_iter i;
4193 	struct device *child;
4194 
4195 	if (!parent || !parent->p)
4196 		return NULL;
4197 
4198 	klist_iter_init(&parent->p->klist_children, &i);
4199 	while ((child = next_device(&i))) {
4200 		if (match(child, data)) {
4201 			get_device(child);
4202 			break;
4203 		}
4204 	}
4205 	klist_iter_exit(&i);
4206 	return child;
4207 }
4208 EXPORT_SYMBOL_GPL(device_find_child);
4209 
4210 int __init devices_init(void)
4211 {
4212 	devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
4213 	if (!devices_kset)
4214 		return -ENOMEM;
4215 	dev_kobj = kobject_create_and_add("dev", NULL);
4216 	if (!dev_kobj)
4217 		goto dev_kobj_err;
4218 	sysfs_dev_block_kobj = kobject_create_and_add("block", dev_kobj);
4219 	if (!sysfs_dev_block_kobj)
4220 		goto block_kobj_err;
4221 	sysfs_dev_char_kobj = kobject_create_and_add("char", dev_kobj);
4222 	if (!sysfs_dev_char_kobj)
4223 		goto char_kobj_err;
4224 	device_link_wq = alloc_workqueue("device_link_wq", WQ_PERCPU, 0);
4225 	if (!device_link_wq)
4226 		goto wq_err;
4227 
4228 	return 0;
4229 
4230  wq_err:
4231 	kobject_put(sysfs_dev_char_kobj);
4232  char_kobj_err:
4233 	kobject_put(sysfs_dev_block_kobj);
4234  block_kobj_err:
4235 	kobject_put(dev_kobj);
4236  dev_kobj_err:
4237 	kset_unregister(devices_kset);
4238 	return -ENOMEM;
4239 }
4240 
4241 static int device_check_offline(struct device *dev, void *not_used)
4242 {
4243 	int ret;
4244 
4245 	ret = device_for_each_child(dev, NULL, device_check_offline);
4246 	if (ret)
4247 		return ret;
4248 
4249 	return device_supports_offline(dev) && !dev_offline(dev) ? -EBUSY : 0;
4250 }
4251 
4252 /**
4253  * device_offline - Prepare the device for hot-removal.
4254  * @dev: Device to be put offline.
4255  *
4256  * Execute the device bus type's .offline() callback, if present, to prepare
4257  * the device for a subsequent hot-removal.  If that succeeds, the device must
4258  * not be used until either it is removed or its bus type's .online() callback
4259  * is executed.
4260  *
4261  * Call under device_hotplug_lock.
4262  */
4263 int device_offline(struct device *dev)
4264 {
4265 	int ret;
4266 
4267 	if (dev_offline_disabled(dev))
4268 		return -EPERM;
4269 
4270 	ret = device_for_each_child(dev, NULL, device_check_offline);
4271 	if (ret)
4272 		return ret;
4273 
4274 	device_lock(dev);
4275 	if (device_supports_offline(dev)) {
4276 		if (dev_offline(dev)) {
4277 			ret = 1;
4278 		} else {
4279 			ret = dev->bus->offline(dev);
4280 			if (!ret) {
4281 				kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
4282 				dev_set_offline(dev);
4283 			}
4284 		}
4285 	}
4286 	device_unlock(dev);
4287 
4288 	return ret;
4289 }
4290 
4291 /**
4292  * device_online - Put the device back online after successful device_offline().
4293  * @dev: Device to be put back online.
4294  *
4295  * If device_offline() has been successfully executed for @dev, but the device
4296  * has not been removed subsequently, execute its bus type's .online() callback
4297  * to indicate that the device can be used again.
4298  *
4299  * Call under device_hotplug_lock.
4300  */
4301 int device_online(struct device *dev)
4302 {
4303 	int ret = 0;
4304 
4305 	device_lock(dev);
4306 	if (device_supports_offline(dev)) {
4307 		if (dev_offline(dev)) {
4308 			ret = dev->bus->online(dev);
4309 			if (!ret) {
4310 				kobject_uevent(&dev->kobj, KOBJ_ONLINE);
4311 				dev_clear_offline(dev);
4312 			}
4313 		} else {
4314 			ret = 1;
4315 		}
4316 	}
4317 	device_unlock(dev);
4318 
4319 	return ret;
4320 }
4321 
4322 struct root_device {
4323 	struct device dev;
4324 	struct module *owner;
4325 };
4326 
4327 static inline struct root_device *to_root_device(struct device *d)
4328 {
4329 	return container_of(d, struct root_device, dev);
4330 }
4331 
4332 static void root_device_release(struct device *dev)
4333 {
4334 	kfree(to_root_device(dev));
4335 }
4336 
4337 /**
4338  * __root_device_register - allocate and register a root device
4339  * @name: root device name
4340  * @owner: owner module of the root device, usually THIS_MODULE
4341  *
4342  * This function allocates a root device and registers it
4343  * using device_register(). In order to free the returned
4344  * device, use root_device_unregister().
4345  *
4346  * Root devices are dummy devices which allow other devices
4347  * to be grouped under /sys/devices. Use this function to
4348  * allocate a root device and then use it as the parent of
4349  * any device which should appear under /sys/devices/{name}
4350  *
4351  * The /sys/devices/{name} directory will also contain a
4352  * 'module' symlink which points to the @owner directory
4353  * in sysfs.
4354  *
4355  * Returns &struct device pointer on success, or ERR_PTR() on error.
4356  *
4357  * Note: You probably want to use root_device_register().
4358  */
4359 struct device *__root_device_register(const char *name, struct module *owner)
4360 {
4361 	struct root_device *root;
4362 	int err = -ENOMEM;
4363 
4364 	root = kzalloc_obj(struct root_device);
4365 	if (!root)
4366 		return ERR_PTR(err);
4367 
4368 	err = dev_set_name(&root->dev, "%s", name);
4369 	if (err) {
4370 		kfree(root);
4371 		return ERR_PTR(err);
4372 	}
4373 
4374 	root->dev.release = root_device_release;
4375 
4376 	err = device_register(&root->dev);
4377 	if (err) {
4378 		put_device(&root->dev);
4379 		return ERR_PTR(err);
4380 	}
4381 
4382 #ifdef CONFIG_MODULES	/* gotta find a "cleaner" way to do this */
4383 	if (owner) {
4384 		struct module_kobject *mk = &owner->mkobj;
4385 
4386 		err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module");
4387 		if (err) {
4388 			device_unregister(&root->dev);
4389 			return ERR_PTR(err);
4390 		}
4391 		root->owner = owner;
4392 	}
4393 #endif
4394 
4395 	return &root->dev;
4396 }
4397 EXPORT_SYMBOL_GPL(__root_device_register);
4398 
4399 /**
4400  * root_device_unregister - unregister and free a root device
4401  * @dev: device going away
4402  *
4403  * This function unregisters and cleans up a device that was created by
4404  * root_device_register().
4405  */
4406 void root_device_unregister(struct device *dev)
4407 {
4408 	struct root_device *root = to_root_device(dev);
4409 
4410 	if (root->owner)
4411 		sysfs_remove_link(&root->dev.kobj, "module");
4412 
4413 	device_unregister(dev);
4414 }
4415 EXPORT_SYMBOL_GPL(root_device_unregister);
4416 
4417 
4418 static void device_create_release(struct device *dev)
4419 {
4420 	pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
4421 	kfree(dev);
4422 }
4423 
4424 static __printf(6, 0) struct device *
4425 device_create_groups_vargs(const struct class *class, struct device *parent,
4426 			   dev_t devt, void *drvdata,
4427 			   const struct attribute_group **groups,
4428 			   const char *fmt, va_list args)
4429 {
4430 	struct device *dev = NULL;
4431 	int retval = -ENODEV;
4432 
4433 	if (IS_ERR_OR_NULL(class))
4434 		goto error;
4435 
4436 	dev = kzalloc_obj(*dev);
4437 	if (!dev) {
4438 		retval = -ENOMEM;
4439 		goto error;
4440 	}
4441 
4442 	device_initialize(dev);
4443 	dev->devt = devt;
4444 	dev->class = class;
4445 	dev->parent = parent;
4446 	dev->groups = groups;
4447 	dev->release = device_create_release;
4448 	dev_set_drvdata(dev, drvdata);
4449 
4450 	retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
4451 	if (retval)
4452 		goto error;
4453 
4454 	retval = device_add(dev);
4455 	if (retval)
4456 		goto error;
4457 
4458 	return dev;
4459 
4460 error:
4461 	put_device(dev);
4462 	return ERR_PTR(retval);
4463 }
4464 
4465 /**
4466  * device_create - creates a device and registers it with sysfs
4467  * @class: pointer to the struct class that this device should be registered to
4468  * @parent: pointer to the parent struct device of this new device, if any
4469  * @devt: the dev_t for the char device to be added
4470  * @drvdata: the data to be added to the device for callbacks
4471  * @fmt: string for the device's name
4472  *
4473  * This function can be used by char device classes.  A struct device
4474  * will be created in sysfs, registered to the specified class.
4475  *
4476  * A "dev" file will be created, showing the dev_t for the device, if
4477  * the dev_t is not 0,0.
4478  * If a pointer to a parent struct device is passed in, the newly created
4479  * struct device will be a child of that device in sysfs.
4480  * The pointer to the struct device will be returned from the call.
4481  * Any further sysfs files that might be required can be created using this
4482  * pointer.
4483  *
4484  * Returns &struct device pointer on success, or ERR_PTR() on error.
4485  */
4486 struct device *device_create(const struct class *class, struct device *parent,
4487 			     dev_t devt, void *drvdata, const char *fmt, ...)
4488 {
4489 	va_list vargs;
4490 	struct device *dev;
4491 
4492 	va_start(vargs, fmt);
4493 	dev = device_create_groups_vargs(class, parent, devt, drvdata, NULL,
4494 					  fmt, vargs);
4495 	va_end(vargs);
4496 	return dev;
4497 }
4498 EXPORT_SYMBOL_GPL(device_create);
4499 
4500 /**
4501  * device_create_with_groups - creates a device and registers it with sysfs
4502  * @class: pointer to the struct class that this device should be registered to
4503  * @parent: pointer to the parent struct device of this new device, if any
4504  * @devt: the dev_t for the char device to be added
4505  * @drvdata: the data to be added to the device for callbacks
4506  * @groups: NULL-terminated list of attribute groups to be created
4507  * @fmt: string for the device's name
4508  *
4509  * This function can be used by char device classes.  A struct device
4510  * will be created in sysfs, registered to the specified class.
4511  * Additional attributes specified in the groups parameter will also
4512  * be created automatically.
4513  *
4514  * A "dev" file will be created, showing the dev_t for the device, if
4515  * the dev_t is not 0,0.
4516  * If a pointer to a parent struct device is passed in, the newly created
4517  * struct device will be a child of that device in sysfs.
4518  * The pointer to the struct device will be returned from the call.
4519  * Any further sysfs files that might be required can be created using this
4520  * pointer.
4521  *
4522  * Returns &struct device pointer on success, or ERR_PTR() on error.
4523  */
4524 struct device *device_create_with_groups(const struct class *class,
4525 					 struct device *parent, dev_t devt,
4526 					 void *drvdata,
4527 					 const struct attribute_group **groups,
4528 					 const char *fmt, ...)
4529 {
4530 	va_list vargs;
4531 	struct device *dev;
4532 
4533 	va_start(vargs, fmt);
4534 	dev = device_create_groups_vargs(class, parent, devt, drvdata, groups,
4535 					 fmt, vargs);
4536 	va_end(vargs);
4537 	return dev;
4538 }
4539 EXPORT_SYMBOL_GPL(device_create_with_groups);
4540 
4541 /**
4542  * device_destroy - removes a device that was created with device_create()
4543  * @class: pointer to the struct class that this device was registered with
4544  * @devt: the dev_t of the device that was previously registered
4545  *
4546  * This call unregisters and cleans up a device that was created with a
4547  * call to device_create().
4548  */
4549 void device_destroy(const struct class *class, dev_t devt)
4550 {
4551 	struct device *dev;
4552 
4553 	dev = class_find_device_by_devt(class, devt);
4554 	if (dev) {
4555 		put_device(dev);
4556 		device_unregister(dev);
4557 	}
4558 }
4559 EXPORT_SYMBOL_GPL(device_destroy);
4560 
4561 /**
4562  * device_rename - renames a device
4563  * @dev: the pointer to the struct device to be renamed
4564  * @new_name: the new name of the device
4565  *
4566  * It is the responsibility of the caller to provide mutual
4567  * exclusion between two different calls of device_rename
4568  * on the same device to ensure that new_name is valid and
4569  * won't conflict with other devices.
4570  *
4571  * Note: given that some subsystems (networking and infiniband) use this
4572  * function, with no immediate plans for this to change, we cannot assume or
4573  * require that this function not be called at all.
4574  *
4575  * However, if you're writing new code, do not call this function. The following
4576  * text from Kay Sievers offers some insight:
4577  *
4578  * Renaming devices is racy at many levels, symlinks and other stuff are not
4579  * replaced atomically, and you get a "move" uevent, but it's not easy to
4580  * connect the event to the old and new device. Device nodes are not renamed at
4581  * all, there isn't even support for that in the kernel now.
4582  *
4583  * In the meantime, during renaming, your target name might be taken by another
4584  * driver, creating conflicts. Or the old name is taken directly after you
4585  * renamed it -- then you get events for the same DEVPATH, before you even see
4586  * the "move" event. It's just a mess, and nothing new should ever rely on
4587  * kernel device renaming. Besides that, it's not even implemented now for
4588  * other things than (driver-core wise very simple) network devices.
4589  *
4590  * Make up a "real" name in the driver before you register anything, or add
4591  * some other attributes for userspace to find the device, or use udev to add
4592  * symlinks -- but never rename kernel devices later, it's a complete mess. We
4593  * don't even want to get into that and try to implement the missing pieces in
4594  * the core. We really have other pieces to fix in the driver core mess. :)
4595  */
4596 int device_rename(struct device *dev, const char *new_name)
4597 {
4598 	struct subsys_private *sp = NULL;
4599 	struct kobject *kobj = &dev->kobj;
4600 	char *old_device_name = NULL;
4601 	int error;
4602 	bool is_link_renamed = false;
4603 
4604 	dev = get_device(dev);
4605 	if (!dev)
4606 		return -EINVAL;
4607 
4608 	dev_dbg(dev, "renaming to %s\n", new_name);
4609 
4610 	old_device_name = kstrdup(dev_name(dev), GFP_KERNEL);
4611 	if (!old_device_name) {
4612 		error = -ENOMEM;
4613 		goto out;
4614 	}
4615 
4616 	if (dev->class) {
4617 		sp = class_to_subsys(dev->class);
4618 
4619 		if (!sp) {
4620 			error = -EINVAL;
4621 			goto out;
4622 		}
4623 
4624 		error = sysfs_rename_link_ns(&sp->subsys.kobj, kobj, old_device_name,
4625 					     new_name, kobject_namespace(kobj));
4626 		if (error)
4627 			goto out;
4628 
4629 		is_link_renamed = true;
4630 	}
4631 
4632 	error = kobject_rename(kobj, new_name);
4633 out:
4634 	if (error && is_link_renamed)
4635 		sysfs_rename_link_ns(&sp->subsys.kobj, kobj, new_name,
4636 				     old_device_name, kobject_namespace(kobj));
4637 	subsys_put(sp);
4638 
4639 	put_device(dev);
4640 
4641 	kfree(old_device_name);
4642 
4643 	return error;
4644 }
4645 EXPORT_SYMBOL_GPL(device_rename);
4646 
4647 static int device_move_class_links(struct device *dev,
4648 				   struct device *old_parent,
4649 				   struct device *new_parent)
4650 {
4651 	int error = 0;
4652 
4653 	if (old_parent)
4654 		sysfs_remove_link(&dev->kobj, "device");
4655 	if (new_parent)
4656 		error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
4657 					  "device");
4658 	return error;
4659 }
4660 
4661 /**
4662  * device_move - moves a device to a new parent
4663  * @dev: the pointer to the struct device to be moved
4664  * @new_parent: the new parent of the device (can be NULL)
4665  * @dpm_order: how to reorder the dpm_list
4666  */
4667 int device_move(struct device *dev, struct device *new_parent,
4668 		enum dpm_order dpm_order)
4669 {
4670 	int error;
4671 	struct device *old_parent;
4672 	struct kobject *new_parent_kobj;
4673 
4674 	dev = get_device(dev);
4675 	if (!dev)
4676 		return -EINVAL;
4677 
4678 	device_pm_lock();
4679 	new_parent = get_device(new_parent);
4680 	new_parent_kobj = get_device_parent(dev, new_parent);
4681 	if (IS_ERR(new_parent_kobj)) {
4682 		error = PTR_ERR(new_parent_kobj);
4683 		put_device(new_parent);
4684 		goto out;
4685 	}
4686 
4687 	pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev),
4688 		 __func__, new_parent ? dev_name(new_parent) : "<NULL>");
4689 	error = kobject_move(&dev->kobj, new_parent_kobj);
4690 	if (error) {
4691 		cleanup_glue_dir(dev, new_parent_kobj);
4692 		put_device(new_parent);
4693 		goto out;
4694 	}
4695 	old_parent = dev->parent;
4696 	dev->parent = new_parent;
4697 	if (old_parent)
4698 		klist_remove(&dev->p->knode_parent);
4699 	if (new_parent) {
4700 		klist_add_tail(&dev->p->knode_parent,
4701 			       &new_parent->p->klist_children);
4702 		set_dev_node(dev, dev_to_node(new_parent));
4703 	}
4704 
4705 	if (dev->class) {
4706 		error = device_move_class_links(dev, old_parent, new_parent);
4707 		if (error) {
4708 			/* We ignore errors on cleanup since we're hosed anyway... */
4709 			device_move_class_links(dev, new_parent, old_parent);
4710 			if (!kobject_move(&dev->kobj, &old_parent->kobj)) {
4711 				if (new_parent)
4712 					klist_remove(&dev->p->knode_parent);
4713 				dev->parent = old_parent;
4714 				if (old_parent) {
4715 					klist_add_tail(&dev->p->knode_parent,
4716 						       &old_parent->p->klist_children);
4717 					set_dev_node(dev, dev_to_node(old_parent));
4718 				}
4719 			}
4720 			cleanup_glue_dir(dev, new_parent_kobj);
4721 			put_device(new_parent);
4722 			goto out;
4723 		}
4724 	}
4725 	switch (dpm_order) {
4726 	case DPM_ORDER_NONE:
4727 		break;
4728 	case DPM_ORDER_DEV_AFTER_PARENT:
4729 		device_pm_move_after(dev, new_parent);
4730 		devices_kset_move_after(dev, new_parent);
4731 		break;
4732 	case DPM_ORDER_PARENT_BEFORE_DEV:
4733 		device_pm_move_before(new_parent, dev);
4734 		devices_kset_move_before(new_parent, dev);
4735 		break;
4736 	case DPM_ORDER_DEV_LAST:
4737 		device_pm_move_last(dev);
4738 		devices_kset_move_last(dev);
4739 		break;
4740 	}
4741 
4742 	put_device(old_parent);
4743 out:
4744 	device_pm_unlock();
4745 	put_device(dev);
4746 	return error;
4747 }
4748 EXPORT_SYMBOL_GPL(device_move);
4749 
4750 static int device_attrs_change_owner(struct device *dev, kuid_t kuid,
4751 				     kgid_t kgid)
4752 {
4753 	struct kobject *kobj = &dev->kobj;
4754 	const struct class *class = dev->class;
4755 	const struct device_type *type = dev->type;
4756 	int error;
4757 
4758 	if (class) {
4759 		/*
4760 		 * Change the device groups of the device class for @dev to
4761 		 * @kuid/@kgid.
4762 		 */
4763 		error = sysfs_groups_change_owner(kobj, class->dev_groups, kuid,
4764 						  kgid);
4765 		if (error)
4766 			return error;
4767 	}
4768 
4769 	if (type) {
4770 		/*
4771 		 * Change the device groups of the device type for @dev to
4772 		 * @kuid/@kgid.
4773 		 */
4774 		error = sysfs_groups_change_owner(kobj, type->groups, kuid,
4775 						  kgid);
4776 		if (error)
4777 			return error;
4778 	}
4779 
4780 	/* Change the device groups of @dev to @kuid/@kgid. */
4781 	error = sysfs_groups_change_owner(kobj, dev->groups, kuid, kgid);
4782 	if (error)
4783 		return error;
4784 
4785 	if (device_supports_offline(dev) && !dev_offline_disabled(dev)) {
4786 		/* Change online device attributes of @dev to @kuid/@kgid. */
4787 		error = sysfs_file_change_owner(kobj, dev_attr_online.attr.name,
4788 						kuid, kgid);
4789 		if (error)
4790 			return error;
4791 	}
4792 
4793 	return 0;
4794 }
4795 
4796 /**
4797  * device_change_owner - change the owner of an existing device.
4798  * @dev: device.
4799  * @kuid: new owner's kuid
4800  * @kgid: new owner's kgid
4801  *
4802  * This changes the owner of @dev and its corresponding sysfs entries to
4803  * @kuid/@kgid. This function closely mirrors how @dev was added via driver
4804  * core.
4805  *
4806  * Returns 0 on success or error code on failure.
4807  */
4808 int device_change_owner(struct device *dev, kuid_t kuid, kgid_t kgid)
4809 {
4810 	int error;
4811 	struct kobject *kobj = &dev->kobj;
4812 	struct subsys_private *sp;
4813 
4814 	dev = get_device(dev);
4815 	if (!dev)
4816 		return -EINVAL;
4817 
4818 	/*
4819 	 * Change the kobject and the default attributes and groups of the
4820 	 * ktype associated with it to @kuid/@kgid.
4821 	 */
4822 	error = sysfs_change_owner(kobj, kuid, kgid);
4823 	if (error)
4824 		goto out;
4825 
4826 	/*
4827 	 * Change the uevent file for @dev to the new owner. The uevent file
4828 	 * was created in a separate step when @dev got added and we mirror
4829 	 * that step here.
4830 	 */
4831 	error = sysfs_file_change_owner(kobj, dev_attr_uevent.attr.name, kuid,
4832 					kgid);
4833 	if (error)
4834 		goto out;
4835 
4836 	/*
4837 	 * Change the device groups, the device groups associated with the
4838 	 * device class, and the groups associated with the device type of @dev
4839 	 * to @kuid/@kgid.
4840 	 */
4841 	error = device_attrs_change_owner(dev, kuid, kgid);
4842 	if (error)
4843 		goto out;
4844 
4845 	error = dpm_sysfs_change_owner(dev, kuid, kgid);
4846 	if (error)
4847 		goto out;
4848 
4849 	/*
4850 	 * Change the owner of the symlink located in the class directory of
4851 	 * the device class associated with @dev which points to the actual
4852 	 * directory entry for @dev to @kuid/@kgid. This ensures that the
4853 	 * symlink shows the same permissions as its target.
4854 	 */
4855 	sp = class_to_subsys(dev->class);
4856 	if (!sp) {
4857 		error = -EINVAL;
4858 		goto out;
4859 	}
4860 	error = sysfs_link_change_owner(&sp->subsys.kobj, &dev->kobj, dev_name(dev), kuid, kgid);
4861 	subsys_put(sp);
4862 
4863 out:
4864 	put_device(dev);
4865 	return error;
4866 }
4867 
4868 /**
4869  * device_shutdown - call ->shutdown() on each device to shutdown.
4870  */
4871 void device_shutdown(void)
4872 {
4873 	struct device *dev, *parent;
4874 
4875 	wait_for_device_probe();
4876 	device_block_probing();
4877 
4878 	cpufreq_suspend();
4879 
4880 	spin_lock(&devices_kset->list_lock);
4881 	/*
4882 	 * Walk the devices list backward, shutting down each in turn.
4883 	 * Beware that device unplug events may also start pulling
4884 	 * devices offline, even as the system is shutting down.
4885 	 */
4886 	while (!list_empty(&devices_kset->list)) {
4887 		dev = list_entry(devices_kset->list.prev, struct device,
4888 				kobj.entry);
4889 
4890 		/*
4891 		 * hold reference count of device's parent to
4892 		 * prevent it from being freed because parent's
4893 		 * lock is to be held
4894 		 */
4895 		parent = get_device(dev->parent);
4896 		get_device(dev);
4897 		/*
4898 		 * Make sure the device is off the kset list, in the
4899 		 * event that dev->*->shutdown() doesn't remove it.
4900 		 */
4901 		list_del_init(&dev->kobj.entry);
4902 		spin_unlock(&devices_kset->list_lock);
4903 
4904 		/* hold lock to avoid race with probe/release */
4905 		if (parent)
4906 			device_lock(parent);
4907 		device_lock(dev);
4908 
4909 		/* Don't allow any more runtime suspends */
4910 		pm_runtime_get_noresume(dev);
4911 		pm_runtime_barrier(dev);
4912 
4913 		if (dev->class && dev->class->shutdown_pre) {
4914 			if (initcall_debug)
4915 				dev_info(dev, "shutdown_pre\n");
4916 			dev->class->shutdown_pre(dev);
4917 		}
4918 		if (dev->bus && dev->bus->shutdown) {
4919 			if (initcall_debug)
4920 				dev_info(dev, "shutdown\n");
4921 			dev->bus->shutdown(dev);
4922 		} else if (dev->driver && dev->driver->shutdown) {
4923 			if (initcall_debug)
4924 				dev_info(dev, "shutdown\n");
4925 			dev->driver->shutdown(dev);
4926 		}
4927 
4928 		device_unlock(dev);
4929 		if (parent)
4930 			device_unlock(parent);
4931 
4932 		put_device(dev);
4933 		put_device(parent);
4934 
4935 		spin_lock(&devices_kset->list_lock);
4936 	}
4937 	spin_unlock(&devices_kset->list_lock);
4938 }
4939 
4940 /*
4941  * Device logging functions
4942  */
4943 
4944 #ifdef CONFIG_PRINTK
4945 static void
4946 set_dev_info(const struct device *dev, struct dev_printk_info *dev_info)
4947 {
4948 	const char *subsys;
4949 
4950 	memset(dev_info, 0, sizeof(*dev_info));
4951 
4952 	if (dev->class)
4953 		subsys = dev->class->name;
4954 	else if (dev->bus)
4955 		subsys = dev->bus->name;
4956 	else
4957 		return;
4958 
4959 	strscpy(dev_info->subsystem, subsys);
4960 
4961 	/*
4962 	 * Add device identifier DEVICE=:
4963 	 *   b12:8         block dev_t
4964 	 *   c127:3        char dev_t
4965 	 *   n8            netdev ifindex
4966 	 *   +sound:card0  subsystem:devname
4967 	 */
4968 	if (MAJOR(dev->devt)) {
4969 		char c;
4970 
4971 		if (strcmp(subsys, "block") == 0)
4972 			c = 'b';
4973 		else
4974 			c = 'c';
4975 
4976 		snprintf(dev_info->device, sizeof(dev_info->device),
4977 			 "%c%u:%u", c, MAJOR(dev->devt), MINOR(dev->devt));
4978 	} else if (strcmp(subsys, "net") == 0) {
4979 		struct net_device *net = to_net_dev(dev);
4980 
4981 		snprintf(dev_info->device, sizeof(dev_info->device),
4982 			 "n%u", net->ifindex);
4983 	} else {
4984 		snprintf(dev_info->device, sizeof(dev_info->device),
4985 			 "+%s:%s", subsys, dev_name(dev));
4986 	}
4987 }
4988 
4989 int dev_vprintk_emit(int level, const struct device *dev,
4990 		     const char *fmt, va_list args)
4991 {
4992 	struct dev_printk_info dev_info;
4993 
4994 	set_dev_info(dev, &dev_info);
4995 
4996 	return vprintk_emit(0, level, &dev_info, fmt, args);
4997 }
4998 EXPORT_SYMBOL(dev_vprintk_emit);
4999 
5000 int dev_printk_emit(int level, const struct device *dev, const char *fmt, ...)
5001 {
5002 	va_list args;
5003 	int r;
5004 
5005 	va_start(args, fmt);
5006 
5007 	r = dev_vprintk_emit(level, dev, fmt, args);
5008 
5009 	va_end(args);
5010 
5011 	return r;
5012 }
5013 EXPORT_SYMBOL(dev_printk_emit);
5014 
5015 static void __dev_printk(const char *level, const struct device *dev,
5016 			struct va_format *vaf)
5017 {
5018 	if (dev)
5019 		dev_printk_emit(level[1] - '0', dev, "%s %s: %pV",
5020 				dev_driver_string(dev), dev_name(dev), vaf);
5021 	else
5022 		printk("%s(NULL device *): %pV", level, vaf);
5023 }
5024 
5025 void _dev_printk(const char *level, const struct device *dev,
5026 		 const char *fmt, ...)
5027 {
5028 	struct va_format vaf;
5029 	va_list args;
5030 
5031 	va_start(args, fmt);
5032 
5033 	vaf.fmt = fmt;
5034 	vaf.va = &args;
5035 
5036 	__dev_printk(level, dev, &vaf);
5037 
5038 	va_end(args);
5039 }
5040 EXPORT_SYMBOL(_dev_printk);
5041 
5042 #define define_dev_printk_level(func, kern_level)		\
5043 void func(const struct device *dev, const char *fmt, ...)	\
5044 {								\
5045 	struct va_format vaf;					\
5046 	va_list args;						\
5047 								\
5048 	va_start(args, fmt);					\
5049 								\
5050 	vaf.fmt = fmt;						\
5051 	vaf.va = &args;						\
5052 								\
5053 	__dev_printk(kern_level, dev, &vaf);			\
5054 								\
5055 	va_end(args);						\
5056 }								\
5057 EXPORT_SYMBOL(func);
5058 
5059 define_dev_printk_level(_dev_emerg, KERN_EMERG);
5060 define_dev_printk_level(_dev_alert, KERN_ALERT);
5061 define_dev_printk_level(_dev_crit, KERN_CRIT);
5062 define_dev_printk_level(_dev_err, KERN_ERR);
5063 define_dev_printk_level(_dev_warn, KERN_WARNING);
5064 define_dev_printk_level(_dev_notice, KERN_NOTICE);
5065 define_dev_printk_level(_dev_info, KERN_INFO);
5066 
5067 #endif
5068 
5069 static void __dev_probe_failed(const struct device *dev, int err, bool fatal,
5070 			       const char *fmt, va_list vargsp)
5071 {
5072 	struct va_format vaf;
5073 	va_list vargs;
5074 
5075 	/*
5076 	 * On x86_64 and possibly on other architectures, va_list is actually a
5077 	 * size-1 array containing a structure.  As a result, function parameter
5078 	 * vargsp decays from T[1] to T*, and &vargsp has type T** rather than
5079 	 * T(*)[1], which is expected by its assignment to vaf.va below.
5080 	 *
5081 	 * One standard way to solve this mess is by creating a copy in a local
5082 	 * variable of type va_list and then using a pointer to that local copy
5083 	 * instead, which is the approach employed here.
5084 	 */
5085 	va_copy(vargs, vargsp);
5086 
5087 	vaf.fmt = fmt;
5088 	vaf.va = &vargs;
5089 
5090 	switch (err) {
5091 	case -EPROBE_DEFER:
5092 		device_set_deferred_probe_reason(dev, &vaf);
5093 		dev_dbg(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
5094 		break;
5095 
5096 	case -ENOMEM:
5097 		/* Don't print anything on -ENOMEM, there's already enough output */
5098 		break;
5099 
5100 	default:
5101 		/* Log fatal final failures as errors, otherwise produce warnings */
5102 		if (fatal)
5103 			dev_err(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
5104 		else
5105 			dev_warn(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
5106 		break;
5107 	}
5108 
5109 	va_end(vargs);
5110 }
5111 
5112 /**
5113  * dev_err_probe - probe error check and log helper
5114  * @dev: the pointer to the struct device
5115  * @err: error value to test
5116  * @fmt: printf-style format string
5117  * @...: arguments as specified in the format string
5118  *
5119  * This helper implements common pattern present in probe functions for error
5120  * checking: print debug or error message depending if the error value is
5121  * -EPROBE_DEFER and propagate error upwards.
5122  * In case of -EPROBE_DEFER it sets also defer probe reason, which can be
5123  * checked later by reading devices_deferred debugfs attribute.
5124  * It replaces the following code sequence::
5125  *
5126  * 	if (err != -EPROBE_DEFER)
5127  * 		dev_err(dev, ...);
5128  * 	else
5129  * 		dev_dbg(dev, ...);
5130  * 	return err;
5131  *
5132  * with::
5133  *
5134  * 	return dev_err_probe(dev, err, ...);
5135  *
5136  * Using this helper in your probe function is totally fine even if @err
5137  * is known to never be -EPROBE_DEFER.
5138  * The benefit compared to a normal dev_err() is the standardized format
5139  * of the error code, which is emitted symbolically (i.e. you get "EAGAIN"
5140  * instead of "-35"), and having the error code returned allows more
5141  * compact error paths.
5142  *
5143  * Returns @err.
5144  */
5145 int dev_err_probe(const struct device *dev, int err, const char *fmt, ...)
5146 {
5147 	va_list vargs;
5148 
5149 	va_start(vargs, fmt);
5150 
5151 	/* Use dev_err() for logging when err doesn't equal -EPROBE_DEFER */
5152 	__dev_probe_failed(dev, err, true, fmt, vargs);
5153 
5154 	va_end(vargs);
5155 
5156 	return err;
5157 }
5158 EXPORT_SYMBOL_GPL(dev_err_probe);
5159 
5160 /**
5161  * dev_warn_probe - probe error check and log helper
5162  * @dev: the pointer to the struct device
5163  * @err: error value to test
5164  * @fmt: printf-style format string
5165  * @...: arguments as specified in the format string
5166  *
5167  * This helper implements common pattern present in probe functions for error
5168  * checking: print debug or warning message depending if the error value is
5169  * -EPROBE_DEFER and propagate error upwards.
5170  * In case of -EPROBE_DEFER it sets also defer probe reason, which can be
5171  * checked later by reading devices_deferred debugfs attribute.
5172  * It replaces the following code sequence::
5173  *
5174  * 	if (err != -EPROBE_DEFER)
5175  * 		dev_warn(dev, ...);
5176  * 	else
5177  * 		dev_dbg(dev, ...);
5178  * 	return err;
5179  *
5180  * with::
5181  *
5182  * 	return dev_warn_probe(dev, err, ...);
5183  *
5184  * Using this helper in your probe function is totally fine even if @err
5185  * is known to never be -EPROBE_DEFER.
5186  * The benefit compared to a normal dev_warn() is the standardized format
5187  * of the error code, which is emitted symbolically (i.e. you get "EAGAIN"
5188  * instead of "-35"), and having the error code returned allows more
5189  * compact error paths.
5190  *
5191  * Returns @err.
5192  */
5193 int dev_warn_probe(const struct device *dev, int err, const char *fmt, ...)
5194 {
5195 	va_list vargs;
5196 
5197 	va_start(vargs, fmt);
5198 
5199 	/* Use dev_warn() for logging when err doesn't equal -EPROBE_DEFER */
5200 	__dev_probe_failed(dev, err, false, fmt, vargs);
5201 
5202 	va_end(vargs);
5203 
5204 	return err;
5205 }
5206 EXPORT_SYMBOL_GPL(dev_warn_probe);
5207 
5208 static inline bool fwnode_is_primary(struct fwnode_handle *fwnode)
5209 {
5210 	return fwnode && !IS_ERR(fwnode->secondary);
5211 }
5212 
5213 /**
5214  * set_primary_fwnode - Change the primary firmware node of a given device.
5215  * @dev: Device to handle.
5216  * @fwnode: New primary firmware node of the device.
5217  *
5218  * Set the device's firmware node pointer to @fwnode, but if a secondary
5219  * firmware node of the device is present, preserve it.
5220  *
5221  * Valid fwnode cases are:
5222  *  - primary --> secondary --> -ENODEV
5223  *  - primary --> NULL
5224  *  - secondary --> -ENODEV
5225  *  - NULL
5226  */
5227 void set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
5228 {
5229 	struct device *parent = dev->parent;
5230 	struct fwnode_handle *fn = dev->fwnode;
5231 
5232 	if (fwnode) {
5233 		if (fwnode_is_primary(fn))
5234 			fn = fn->secondary;
5235 
5236 		if (fn) {
5237 			WARN_ON(fwnode->secondary);
5238 			fwnode->secondary = fn;
5239 		}
5240 		dev->fwnode = fwnode;
5241 	} else {
5242 		if (fwnode_is_primary(fn)) {
5243 			dev->fwnode = fn->secondary;
5244 
5245 			/* Skip nullifying fn->secondary if the primary is shared */
5246 			if (parent && fn == parent->fwnode)
5247 				return;
5248 
5249 			/* Set fn->secondary = NULL, so fn remains the primary fwnode */
5250 			fn->secondary = NULL;
5251 		} else {
5252 			dev->fwnode = NULL;
5253 		}
5254 	}
5255 }
5256 EXPORT_SYMBOL_GPL(set_primary_fwnode);
5257 
5258 /**
5259  * set_secondary_fwnode - Change the secondary firmware node of a given device.
5260  * @dev: Device to handle.
5261  * @fwnode: New secondary firmware node of the device.
5262  *
5263  * If a primary firmware node of the device is present, set its secondary
5264  * pointer to @fwnode.  Otherwise, set the device's firmware node pointer to
5265  * @fwnode.
5266  */
5267 void set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
5268 {
5269 	if (fwnode)
5270 		fwnode->secondary = ERR_PTR(-ENODEV);
5271 
5272 	if (fwnode_is_primary(dev->fwnode))
5273 		dev->fwnode->secondary = fwnode;
5274 	else
5275 		dev->fwnode = fwnode;
5276 }
5277 EXPORT_SYMBOL_GPL(set_secondary_fwnode);
5278 
5279 /**
5280  * device_remove_of_node - Remove an of_node from a device
5281  * @dev: device whose device tree node is being removed
5282  */
5283 void device_remove_of_node(struct device *dev)
5284 {
5285 	dev = get_device(dev);
5286 	if (!dev)
5287 		return;
5288 
5289 	if (!dev->of_node)
5290 		goto end;
5291 
5292 	if (dev->fwnode == of_fwnode_handle(dev->of_node))
5293 		dev->fwnode = NULL;
5294 
5295 	of_node_put(dev->of_node);
5296 	dev->of_node = NULL;
5297 
5298 end:
5299 	put_device(dev);
5300 }
5301 EXPORT_SYMBOL_GPL(device_remove_of_node);
5302 
5303 /**
5304  * device_add_of_node - Add an of_node to an existing device
5305  * @dev: device whose device tree node is being added
5306  * @of_node: of_node to add
5307  *
5308  * Return: 0 on success or error code on failure.
5309  */
5310 int device_add_of_node(struct device *dev, struct device_node *of_node)
5311 {
5312 	int ret;
5313 
5314 	if (!of_node)
5315 		return -EINVAL;
5316 
5317 	dev = get_device(dev);
5318 	if (!dev)
5319 		return -EINVAL;
5320 
5321 	if (dev->of_node) {
5322 		dev_err(dev, "Cannot replace node %pOF with %pOF\n",
5323 			dev->of_node, of_node);
5324 		ret = -EBUSY;
5325 		goto end;
5326 	}
5327 
5328 	dev->of_node = of_node_get(of_node);
5329 
5330 	if (!dev->fwnode)
5331 		dev->fwnode = of_fwnode_handle(of_node);
5332 
5333 	ret = 0;
5334 end:
5335 	put_device(dev);
5336 	return ret;
5337 }
5338 EXPORT_SYMBOL_GPL(device_add_of_node);
5339 
5340 /**
5341  * device_set_of_node_from_dev - reuse device-tree node of another device
5342  * @dev: device whose device-tree node is being set
5343  * @dev2: device whose device-tree node is being reused
5344  *
5345  * Takes another reference to the new device-tree node after first dropping
5346  * any reference held to the old node.
5347  */
5348 void device_set_of_node_from_dev(struct device *dev, const struct device *dev2)
5349 {
5350 	of_node_put(dev->of_node);
5351 	dev->of_node = of_node_get(dev2->of_node);
5352 	dev_set_of_node_reused(dev);
5353 }
5354 EXPORT_SYMBOL_GPL(device_set_of_node_from_dev);
5355 
5356 void device_set_node(struct device *dev, struct fwnode_handle *fwnode)
5357 {
5358 	dev->fwnode = fwnode;
5359 	dev->of_node = to_of_node(fwnode);
5360 }
5361 EXPORT_SYMBOL_GPL(device_set_node);
5362 
5363 /**
5364  * get_dev_from_fwnode - Obtain a reference count of the struct device the
5365  * struct fwnode_handle is associated with.
5366  * @fwnode: The pointer to the struct fwnode_handle to obtain the struct device
5367  * reference count of.
5368  *
5369  * This function obtains a reference count of the device the device pointer
5370  * embedded in the struct fwnode_handle points to.
5371  *
5372  * Note that the struct device pointer embedded in struct fwnode_handle does
5373  * *not* have a reference count of the struct device itself.
5374  *
5375  * Hence, it is a UAF (and thus a bug) to call this function if the caller can't
5376  * guarantee that the last reference count of the corresponding struct device is
5377  * not dropped concurrently.
5378  *
5379  * This is possible since struct fwnode_handle has its own reference count and
5380  * hence can out-live the struct device it is associated with.
5381  */
5382 struct device *get_dev_from_fwnode(struct fwnode_handle *fwnode)
5383 {
5384 	return get_device((fwnode)->dev);
5385 }
5386 EXPORT_SYMBOL_GPL(get_dev_from_fwnode);
5387 
5388 int device_match_name(struct device *dev, const void *name)
5389 {
5390 	return sysfs_streq(dev_name(dev), name);
5391 }
5392 EXPORT_SYMBOL_GPL(device_match_name);
5393 
5394 int device_match_type(struct device *dev, const void *type)
5395 {
5396 	return dev->type == type;
5397 }
5398 EXPORT_SYMBOL_GPL(device_match_type);
5399 
5400 int device_match_of_node(struct device *dev, const void *np)
5401 {
5402 	return np && dev->of_node == np;
5403 }
5404 EXPORT_SYMBOL_GPL(device_match_of_node);
5405 
5406 int device_match_fwnode(struct device *dev, const void *fwnode)
5407 {
5408 	return fwnode && dev_fwnode(dev) == fwnode;
5409 }
5410 EXPORT_SYMBOL_GPL(device_match_fwnode);
5411 
5412 int device_match_devt(struct device *dev, const void *pdevt)
5413 {
5414 	return dev->devt == *(dev_t *)pdevt;
5415 }
5416 EXPORT_SYMBOL_GPL(device_match_devt);
5417 
5418 int device_match_acpi_dev(struct device *dev, const void *adev)
5419 {
5420 	return adev && ACPI_COMPANION(dev) == adev;
5421 }
5422 EXPORT_SYMBOL(device_match_acpi_dev);
5423 
5424 int device_match_acpi_handle(struct device *dev, const void *handle)
5425 {
5426 	return handle && ACPI_HANDLE(dev) == handle;
5427 }
5428 EXPORT_SYMBOL(device_match_acpi_handle);
5429 
5430 int device_match_any(struct device *dev, const void *unused)
5431 {
5432 	return 1;
5433 }
5434 EXPORT_SYMBOL_GPL(device_match_any);
5435