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