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