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