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