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