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