xref: /openbmc/linux/drivers/base/core.c (revision 5a170e9e)
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/device.h>
13 #include <linux/err.h>
14 #include <linux/fwnode.h>
15 #include <linux/init.h>
16 #include <linux/module.h>
17 #include <linux/slab.h>
18 #include <linux/string.h>
19 #include <linux/kdev_t.h>
20 #include <linux/notifier.h>
21 #include <linux/of.h>
22 #include <linux/of_device.h>
23 #include <linux/genhd.h>
24 #include <linux/mutex.h>
25 #include <linux/pm_runtime.h>
26 #include <linux/netdevice.h>
27 #include <linux/sched/signal.h>
28 #include <linux/sysfs.h>
29 
30 #include "base.h"
31 #include "power/power.h"
32 
33 #ifdef CONFIG_SYSFS_DEPRECATED
34 #ifdef CONFIG_SYSFS_DEPRECATED_V2
35 long sysfs_deprecated = 1;
36 #else
37 long sysfs_deprecated = 0;
38 #endif
39 static int __init sysfs_deprecated_setup(char *arg)
40 {
41 	return kstrtol(arg, 10, &sysfs_deprecated);
42 }
43 early_param("sysfs.deprecated", sysfs_deprecated_setup);
44 #endif
45 
46 /* Device links support. */
47 
48 #ifdef CONFIG_SRCU
49 static DEFINE_MUTEX(device_links_lock);
50 DEFINE_STATIC_SRCU(device_links_srcu);
51 
52 static inline void device_links_write_lock(void)
53 {
54 	mutex_lock(&device_links_lock);
55 }
56 
57 static inline void device_links_write_unlock(void)
58 {
59 	mutex_unlock(&device_links_lock);
60 }
61 
62 int device_links_read_lock(void)
63 {
64 	return srcu_read_lock(&device_links_srcu);
65 }
66 
67 void device_links_read_unlock(int idx)
68 {
69 	srcu_read_unlock(&device_links_srcu, idx);
70 }
71 #else /* !CONFIG_SRCU */
72 static DECLARE_RWSEM(device_links_lock);
73 
74 static inline void device_links_write_lock(void)
75 {
76 	down_write(&device_links_lock);
77 }
78 
79 static inline void device_links_write_unlock(void)
80 {
81 	up_write(&device_links_lock);
82 }
83 
84 int device_links_read_lock(void)
85 {
86 	down_read(&device_links_lock);
87 	return 0;
88 }
89 
90 void device_links_read_unlock(int not_used)
91 {
92 	up_read(&device_links_lock);
93 }
94 #endif /* !CONFIG_SRCU */
95 
96 /**
97  * device_is_dependent - Check if one device depends on another one
98  * @dev: Device to check dependencies for.
99  * @target: Device to check against.
100  *
101  * Check if @target depends on @dev or any device dependent on it (its child or
102  * its consumer etc).  Return 1 if that is the case or 0 otherwise.
103  */
104 static int device_is_dependent(struct device *dev, void *target)
105 {
106 	struct device_link *link;
107 	int ret;
108 
109 	if (dev == target)
110 		return 1;
111 
112 	ret = device_for_each_child(dev, target, device_is_dependent);
113 	if (ret)
114 		return ret;
115 
116 	list_for_each_entry(link, &dev->links.consumers, s_node) {
117 		if (link->consumer == target)
118 			return 1;
119 
120 		ret = device_is_dependent(link->consumer, target);
121 		if (ret)
122 			break;
123 	}
124 	return ret;
125 }
126 
127 static int device_reorder_to_tail(struct device *dev, void *not_used)
128 {
129 	struct device_link *link;
130 
131 	/*
132 	 * Devices that have not been registered yet will be put to the ends
133 	 * of the lists during the registration, so skip them here.
134 	 */
135 	if (device_is_registered(dev))
136 		devices_kset_move_last(dev);
137 
138 	if (device_pm_initialized(dev))
139 		device_pm_move_last(dev);
140 
141 	device_for_each_child(dev, NULL, device_reorder_to_tail);
142 	list_for_each_entry(link, &dev->links.consumers, s_node)
143 		device_reorder_to_tail(link->consumer, NULL);
144 
145 	return 0;
146 }
147 
148 /**
149  * device_pm_move_to_tail - Move set of devices to the end of device lists
150  * @dev: Device to move
151  *
152  * This is a device_reorder_to_tail() wrapper taking the requisite locks.
153  *
154  * It moves the @dev along with all of its children and all of its consumers
155  * to the ends of the device_kset and dpm_list, recursively.
156  */
157 void device_pm_move_to_tail(struct device *dev)
158 {
159 	int idx;
160 
161 	idx = device_links_read_lock();
162 	device_pm_lock();
163 	device_reorder_to_tail(dev, NULL);
164 	device_pm_unlock();
165 	device_links_read_unlock(idx);
166 }
167 
168 /**
169  * device_link_add - Create a link between two devices.
170  * @consumer: Consumer end of the link.
171  * @supplier: Supplier end of the link.
172  * @flags: Link flags.
173  *
174  * The caller is responsible for the proper synchronization of the link creation
175  * with runtime PM.  First, setting the DL_FLAG_PM_RUNTIME flag will cause the
176  * runtime PM framework to take the link into account.  Second, if the
177  * DL_FLAG_RPM_ACTIVE flag is set in addition to it, the supplier devices will
178  * be forced into the active metastate and reference-counted upon the creation
179  * of the link.  If DL_FLAG_PM_RUNTIME is not set, DL_FLAG_RPM_ACTIVE will be
180  * ignored.
181  *
182  * If the DL_FLAG_AUTOREMOVE_CONSUMER is set, the link will be removed
183  * automatically when the consumer device driver unbinds from it.
184  * The combination of both DL_FLAG_AUTOREMOVE_CONSUMER and DL_FLAG_STATELESS
185  * set is invalid and will cause NULL to be returned.
186  *
187  * A side effect of the link creation is re-ordering of dpm_list and the
188  * devices_kset list by moving the consumer device and all devices depending
189  * on it to the ends of these lists (that does not happen to devices that have
190  * not been registered when this function is called).
191  *
192  * The supplier device is required to be registered when this function is called
193  * and NULL will be returned if that is not the case.  The consumer device need
194  * not be registered, however.
195  */
196 struct device_link *device_link_add(struct device *consumer,
197 				    struct device *supplier, u32 flags)
198 {
199 	struct device_link *link;
200 
201 	if (!consumer || !supplier ||
202 	    ((flags & DL_FLAG_STATELESS) &&
203 	     (flags & DL_FLAG_AUTOREMOVE_CONSUMER)))
204 		return NULL;
205 
206 	device_links_write_lock();
207 	device_pm_lock();
208 
209 	/*
210 	 * If the supplier has not been fully registered yet or there is a
211 	 * reverse dependency between the consumer and the supplier already in
212 	 * the graph, return NULL.
213 	 */
214 	if (!device_pm_initialized(supplier)
215 	    || device_is_dependent(consumer, supplier)) {
216 		link = NULL;
217 		goto out;
218 	}
219 
220 	list_for_each_entry(link, &supplier->links.consumers, s_node)
221 		if (link->consumer == consumer) {
222 			kref_get(&link->kref);
223 			goto out;
224 		}
225 
226 	link = kzalloc(sizeof(*link), GFP_KERNEL);
227 	if (!link)
228 		goto out;
229 
230 	if (flags & DL_FLAG_PM_RUNTIME) {
231 		if (flags & DL_FLAG_RPM_ACTIVE) {
232 			if (pm_runtime_get_sync(supplier) < 0) {
233 				pm_runtime_put_noidle(supplier);
234 				kfree(link);
235 				link = NULL;
236 				goto out;
237 			}
238 			link->rpm_active = true;
239 		}
240 		pm_runtime_new_link(consumer);
241 		/*
242 		 * If the link is being added by the consumer driver at probe
243 		 * time, balance the decrementation of the supplier's runtime PM
244 		 * usage counter after consumer probe in driver_probe_device().
245 		 */
246 		if (consumer->links.status == DL_DEV_PROBING)
247 			pm_runtime_get_noresume(supplier);
248 	}
249 	get_device(supplier);
250 	link->supplier = supplier;
251 	INIT_LIST_HEAD(&link->s_node);
252 	get_device(consumer);
253 	link->consumer = consumer;
254 	INIT_LIST_HEAD(&link->c_node);
255 	link->flags = flags;
256 	kref_init(&link->kref);
257 
258 	/* Determine the initial link state. */
259 	if (flags & DL_FLAG_STATELESS) {
260 		link->status = DL_STATE_NONE;
261 	} else {
262 		switch (supplier->links.status) {
263 		case DL_DEV_DRIVER_BOUND:
264 			switch (consumer->links.status) {
265 			case DL_DEV_PROBING:
266 				/*
267 				 * Some callers expect the link creation during
268 				 * consumer driver probe to resume the supplier
269 				 * even without DL_FLAG_RPM_ACTIVE.
270 				 */
271 				if (flags & DL_FLAG_PM_RUNTIME)
272 					pm_runtime_resume(supplier);
273 
274 				link->status = DL_STATE_CONSUMER_PROBE;
275 				break;
276 			case DL_DEV_DRIVER_BOUND:
277 				link->status = DL_STATE_ACTIVE;
278 				break;
279 			default:
280 				link->status = DL_STATE_AVAILABLE;
281 				break;
282 			}
283 			break;
284 		case DL_DEV_UNBINDING:
285 			link->status = DL_STATE_SUPPLIER_UNBIND;
286 			break;
287 		default:
288 			link->status = DL_STATE_DORMANT;
289 			break;
290 		}
291 	}
292 
293 	/*
294 	 * Move the consumer and all of the devices depending on it to the end
295 	 * of dpm_list and the devices_kset list.
296 	 *
297 	 * It is necessary to hold dpm_list locked throughout all that or else
298 	 * we may end up suspending with a wrong ordering of it.
299 	 */
300 	device_reorder_to_tail(consumer, NULL);
301 
302 	list_add_tail_rcu(&link->s_node, &supplier->links.consumers);
303 	list_add_tail_rcu(&link->c_node, &consumer->links.suppliers);
304 
305 	dev_info(consumer, "Linked as a consumer to %s\n", dev_name(supplier));
306 
307  out:
308 	device_pm_unlock();
309 	device_links_write_unlock();
310 	return link;
311 }
312 EXPORT_SYMBOL_GPL(device_link_add);
313 
314 static void device_link_free(struct device_link *link)
315 {
316 	put_device(link->consumer);
317 	put_device(link->supplier);
318 	kfree(link);
319 }
320 
321 #ifdef CONFIG_SRCU
322 static void __device_link_free_srcu(struct rcu_head *rhead)
323 {
324 	device_link_free(container_of(rhead, struct device_link, rcu_head));
325 }
326 
327 static void __device_link_del(struct kref *kref)
328 {
329 	struct device_link *link = container_of(kref, struct device_link, kref);
330 
331 	dev_info(link->consumer, "Dropping the link to %s\n",
332 		 dev_name(link->supplier));
333 
334 	if (link->flags & DL_FLAG_PM_RUNTIME)
335 		pm_runtime_drop_link(link->consumer);
336 
337 	list_del_rcu(&link->s_node);
338 	list_del_rcu(&link->c_node);
339 	call_srcu(&device_links_srcu, &link->rcu_head, __device_link_free_srcu);
340 }
341 #else /* !CONFIG_SRCU */
342 static void __device_link_del(struct kref *kref)
343 {
344 	struct device_link *link = container_of(kref, struct device_link, kref);
345 
346 	dev_info(link->consumer, "Dropping the link to %s\n",
347 		 dev_name(link->supplier));
348 
349 	if (link->flags & DL_FLAG_PM_RUNTIME)
350 		pm_runtime_drop_link(link->consumer);
351 
352 	list_del(&link->s_node);
353 	list_del(&link->c_node);
354 	device_link_free(link);
355 }
356 #endif /* !CONFIG_SRCU */
357 
358 /**
359  * device_link_del - Delete a link between two devices.
360  * @link: Device link to delete.
361  *
362  * The caller must ensure proper synchronization of this function with runtime
363  * PM.  If the link was added multiple times, it needs to be deleted as often.
364  * Care is required for hotplugged devices:  Their links are purged on removal
365  * and calling device_link_del() is then no longer allowed.
366  */
367 void device_link_del(struct device_link *link)
368 {
369 	device_links_write_lock();
370 	device_pm_lock();
371 	kref_put(&link->kref, __device_link_del);
372 	device_pm_unlock();
373 	device_links_write_unlock();
374 }
375 EXPORT_SYMBOL_GPL(device_link_del);
376 
377 /**
378  * device_link_remove - remove a link between two devices.
379  * @consumer: Consumer end of the link.
380  * @supplier: Supplier end of the link.
381  *
382  * The caller must ensure proper synchronization of this function with runtime
383  * PM.
384  */
385 void device_link_remove(void *consumer, struct device *supplier)
386 {
387 	struct device_link *link;
388 
389 	if (WARN_ON(consumer == supplier))
390 		return;
391 
392 	device_links_write_lock();
393 	device_pm_lock();
394 
395 	list_for_each_entry(link, &supplier->links.consumers, s_node) {
396 		if (link->consumer == consumer) {
397 			kref_put(&link->kref, __device_link_del);
398 			break;
399 		}
400 	}
401 
402 	device_pm_unlock();
403 	device_links_write_unlock();
404 }
405 EXPORT_SYMBOL_GPL(device_link_remove);
406 
407 static void device_links_missing_supplier(struct device *dev)
408 {
409 	struct device_link *link;
410 
411 	list_for_each_entry(link, &dev->links.suppliers, c_node)
412 		if (link->status == DL_STATE_CONSUMER_PROBE)
413 			WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
414 }
415 
416 /**
417  * device_links_check_suppliers - Check presence of supplier drivers.
418  * @dev: Consumer device.
419  *
420  * Check links from this device to any suppliers.  Walk the list of the device's
421  * links to suppliers and see if all of them are available.  If not, simply
422  * return -EPROBE_DEFER.
423  *
424  * We need to guarantee that the supplier will not go away after the check has
425  * been positive here.  It only can go away in __device_release_driver() and
426  * that function  checks the device's links to consumers.  This means we need to
427  * mark the link as "consumer probe in progress" to make the supplier removal
428  * wait for us to complete (or bad things may happen).
429  *
430  * Links with the DL_FLAG_STATELESS flag set are ignored.
431  */
432 int device_links_check_suppliers(struct device *dev)
433 {
434 	struct device_link *link;
435 	int ret = 0;
436 
437 	device_links_write_lock();
438 
439 	list_for_each_entry(link, &dev->links.suppliers, c_node) {
440 		if (link->flags & DL_FLAG_STATELESS)
441 			continue;
442 
443 		if (link->status != DL_STATE_AVAILABLE) {
444 			device_links_missing_supplier(dev);
445 			ret = -EPROBE_DEFER;
446 			break;
447 		}
448 		WRITE_ONCE(link->status, DL_STATE_CONSUMER_PROBE);
449 	}
450 	dev->links.status = DL_DEV_PROBING;
451 
452 	device_links_write_unlock();
453 	return ret;
454 }
455 
456 /**
457  * device_links_driver_bound - Update device links after probing its driver.
458  * @dev: Device to update the links for.
459  *
460  * The probe has been successful, so update links from this device to any
461  * consumers by changing their status to "available".
462  *
463  * Also change the status of @dev's links to suppliers to "active".
464  *
465  * Links with the DL_FLAG_STATELESS flag set are ignored.
466  */
467 void device_links_driver_bound(struct device *dev)
468 {
469 	struct device_link *link;
470 
471 	device_links_write_lock();
472 
473 	list_for_each_entry(link, &dev->links.consumers, s_node) {
474 		if (link->flags & DL_FLAG_STATELESS)
475 			continue;
476 
477 		WARN_ON(link->status != DL_STATE_DORMANT);
478 		WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
479 	}
480 
481 	list_for_each_entry(link, &dev->links.suppliers, c_node) {
482 		if (link->flags & DL_FLAG_STATELESS)
483 			continue;
484 
485 		WARN_ON(link->status != DL_STATE_CONSUMER_PROBE);
486 		WRITE_ONCE(link->status, DL_STATE_ACTIVE);
487 	}
488 
489 	dev->links.status = DL_DEV_DRIVER_BOUND;
490 
491 	device_links_write_unlock();
492 }
493 
494 /**
495  * __device_links_no_driver - Update links of a device without a driver.
496  * @dev: Device without a drvier.
497  *
498  * Delete all non-persistent links from this device to any suppliers.
499  *
500  * Persistent links stay around, but their status is changed to "available",
501  * unless they already are in the "supplier unbind in progress" state in which
502  * case they need not be updated.
503  *
504  * Links with the DL_FLAG_STATELESS flag set are ignored.
505  */
506 static void __device_links_no_driver(struct device *dev)
507 {
508 	struct device_link *link, *ln;
509 
510 	list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
511 		if (link->flags & DL_FLAG_STATELESS)
512 			continue;
513 
514 		if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER)
515 			kref_put(&link->kref, __device_link_del);
516 		else if (link->status != DL_STATE_SUPPLIER_UNBIND)
517 			WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
518 	}
519 
520 	dev->links.status = DL_DEV_NO_DRIVER;
521 }
522 
523 void device_links_no_driver(struct device *dev)
524 {
525 	device_links_write_lock();
526 	__device_links_no_driver(dev);
527 	device_links_write_unlock();
528 }
529 
530 /**
531  * device_links_driver_cleanup - Update links after driver removal.
532  * @dev: Device whose driver has just gone away.
533  *
534  * Update links to consumers for @dev by changing their status to "dormant" and
535  * invoke %__device_links_no_driver() to update links to suppliers for it as
536  * appropriate.
537  *
538  * Links with the DL_FLAG_STATELESS flag set are ignored.
539  */
540 void device_links_driver_cleanup(struct device *dev)
541 {
542 	struct device_link *link;
543 
544 	device_links_write_lock();
545 
546 	list_for_each_entry(link, &dev->links.consumers, s_node) {
547 		if (link->flags & DL_FLAG_STATELESS)
548 			continue;
549 
550 		WARN_ON(link->flags & DL_FLAG_AUTOREMOVE_CONSUMER);
551 		WARN_ON(link->status != DL_STATE_SUPPLIER_UNBIND);
552 
553 		/*
554 		 * autoremove the links between this @dev and its consumer
555 		 * devices that are not active, i.e. where the link state
556 		 * has moved to DL_STATE_SUPPLIER_UNBIND.
557 		 */
558 		if (link->status == DL_STATE_SUPPLIER_UNBIND &&
559 		    link->flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
560 			kref_put(&link->kref, __device_link_del);
561 
562 		WRITE_ONCE(link->status, DL_STATE_DORMANT);
563 	}
564 
565 	__device_links_no_driver(dev);
566 
567 	device_links_write_unlock();
568 }
569 
570 /**
571  * device_links_busy - Check if there are any busy links to consumers.
572  * @dev: Device to check.
573  *
574  * Check each consumer of the device and return 'true' if its link's status
575  * is one of "consumer probe" or "active" (meaning that the given consumer is
576  * probing right now or its driver is present).  Otherwise, change the link
577  * state to "supplier unbind" to prevent the consumer from being probed
578  * successfully going forward.
579  *
580  * Return 'false' if there are no probing or active consumers.
581  *
582  * Links with the DL_FLAG_STATELESS flag set are ignored.
583  */
584 bool device_links_busy(struct device *dev)
585 {
586 	struct device_link *link;
587 	bool ret = false;
588 
589 	device_links_write_lock();
590 
591 	list_for_each_entry(link, &dev->links.consumers, s_node) {
592 		if (link->flags & DL_FLAG_STATELESS)
593 			continue;
594 
595 		if (link->status == DL_STATE_CONSUMER_PROBE
596 		    || link->status == DL_STATE_ACTIVE) {
597 			ret = true;
598 			break;
599 		}
600 		WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
601 	}
602 
603 	dev->links.status = DL_DEV_UNBINDING;
604 
605 	device_links_write_unlock();
606 	return ret;
607 }
608 
609 /**
610  * device_links_unbind_consumers - Force unbind consumers of the given device.
611  * @dev: Device to unbind the consumers of.
612  *
613  * Walk the list of links to consumers for @dev and if any of them is in the
614  * "consumer probe" state, wait for all device probes in progress to complete
615  * and start over.
616  *
617  * If that's not the case, change the status of the link to "supplier unbind"
618  * and check if the link was in the "active" state.  If so, force the consumer
619  * driver to unbind and start over (the consumer will not re-probe as we have
620  * changed the state of the link already).
621  *
622  * Links with the DL_FLAG_STATELESS flag set are ignored.
623  */
624 void device_links_unbind_consumers(struct device *dev)
625 {
626 	struct device_link *link;
627 
628  start:
629 	device_links_write_lock();
630 
631 	list_for_each_entry(link, &dev->links.consumers, s_node) {
632 		enum device_link_state status;
633 
634 		if (link->flags & DL_FLAG_STATELESS)
635 			continue;
636 
637 		status = link->status;
638 		if (status == DL_STATE_CONSUMER_PROBE) {
639 			device_links_write_unlock();
640 
641 			wait_for_device_probe();
642 			goto start;
643 		}
644 		WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
645 		if (status == DL_STATE_ACTIVE) {
646 			struct device *consumer = link->consumer;
647 
648 			get_device(consumer);
649 
650 			device_links_write_unlock();
651 
652 			device_release_driver_internal(consumer, NULL,
653 						       consumer->parent);
654 			put_device(consumer);
655 			goto start;
656 		}
657 	}
658 
659 	device_links_write_unlock();
660 }
661 
662 /**
663  * device_links_purge - Delete existing links to other devices.
664  * @dev: Target device.
665  */
666 static void device_links_purge(struct device *dev)
667 {
668 	struct device_link *link, *ln;
669 
670 	/*
671 	 * Delete all of the remaining links from this device to any other
672 	 * devices (either consumers or suppliers).
673 	 */
674 	device_links_write_lock();
675 
676 	list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
677 		WARN_ON(link->status == DL_STATE_ACTIVE);
678 		__device_link_del(&link->kref);
679 	}
680 
681 	list_for_each_entry_safe_reverse(link, ln, &dev->links.consumers, s_node) {
682 		WARN_ON(link->status != DL_STATE_DORMANT &&
683 			link->status != DL_STATE_NONE);
684 		__device_link_del(&link->kref);
685 	}
686 
687 	device_links_write_unlock();
688 }
689 
690 /* Device links support end. */
691 
692 int (*platform_notify)(struct device *dev) = NULL;
693 int (*platform_notify_remove)(struct device *dev) = NULL;
694 static struct kobject *dev_kobj;
695 struct kobject *sysfs_dev_char_kobj;
696 struct kobject *sysfs_dev_block_kobj;
697 
698 static DEFINE_MUTEX(device_hotplug_lock);
699 
700 void lock_device_hotplug(void)
701 {
702 	mutex_lock(&device_hotplug_lock);
703 }
704 
705 void unlock_device_hotplug(void)
706 {
707 	mutex_unlock(&device_hotplug_lock);
708 }
709 
710 int lock_device_hotplug_sysfs(void)
711 {
712 	if (mutex_trylock(&device_hotplug_lock))
713 		return 0;
714 
715 	/* Avoid busy looping (5 ms of sleep should do). */
716 	msleep(5);
717 	return restart_syscall();
718 }
719 
720 #ifdef CONFIG_BLOCK
721 static inline int device_is_not_partition(struct device *dev)
722 {
723 	return !(dev->type == &part_type);
724 }
725 #else
726 static inline int device_is_not_partition(struct device *dev)
727 {
728 	return 1;
729 }
730 #endif
731 
732 static int
733 device_platform_notify(struct device *dev, enum kobject_action action)
734 {
735 	int ret;
736 
737 	ret = acpi_platform_notify(dev, action);
738 	if (ret)
739 		return ret;
740 
741 	ret = software_node_notify(dev, action);
742 	if (ret)
743 		return ret;
744 
745 	if (platform_notify && action == KOBJ_ADD)
746 		platform_notify(dev);
747 	else if (platform_notify_remove && action == KOBJ_REMOVE)
748 		platform_notify_remove(dev);
749 	return 0;
750 }
751 
752 /**
753  * dev_driver_string - Return a device's driver name, if at all possible
754  * @dev: struct device to get the name of
755  *
756  * Will return the device's driver's name if it is bound to a device.  If
757  * the device is not bound to a driver, it will return the name of the bus
758  * it is attached to.  If it is not attached to a bus either, an empty
759  * string will be returned.
760  */
761 const char *dev_driver_string(const struct device *dev)
762 {
763 	struct device_driver *drv;
764 
765 	/* dev->driver can change to NULL underneath us because of unbinding,
766 	 * so be careful about accessing it.  dev->bus and dev->class should
767 	 * never change once they are set, so they don't need special care.
768 	 */
769 	drv = READ_ONCE(dev->driver);
770 	return drv ? drv->name :
771 			(dev->bus ? dev->bus->name :
772 			(dev->class ? dev->class->name : ""));
773 }
774 EXPORT_SYMBOL(dev_driver_string);
775 
776 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
777 
778 static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
779 			     char *buf)
780 {
781 	struct device_attribute *dev_attr = to_dev_attr(attr);
782 	struct device *dev = kobj_to_dev(kobj);
783 	ssize_t ret = -EIO;
784 
785 	if (dev_attr->show)
786 		ret = dev_attr->show(dev, dev_attr, buf);
787 	if (ret >= (ssize_t)PAGE_SIZE) {
788 		printk("dev_attr_show: %pS returned bad count\n",
789 				dev_attr->show);
790 	}
791 	return ret;
792 }
793 
794 static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
795 			      const char *buf, size_t count)
796 {
797 	struct device_attribute *dev_attr = to_dev_attr(attr);
798 	struct device *dev = kobj_to_dev(kobj);
799 	ssize_t ret = -EIO;
800 
801 	if (dev_attr->store)
802 		ret = dev_attr->store(dev, dev_attr, buf, count);
803 	return ret;
804 }
805 
806 static const struct sysfs_ops dev_sysfs_ops = {
807 	.show	= dev_attr_show,
808 	.store	= dev_attr_store,
809 };
810 
811 #define to_ext_attr(x) container_of(x, struct dev_ext_attribute, attr)
812 
813 ssize_t device_store_ulong(struct device *dev,
814 			   struct device_attribute *attr,
815 			   const char *buf, size_t size)
816 {
817 	struct dev_ext_attribute *ea = to_ext_attr(attr);
818 	int ret;
819 	unsigned long new;
820 
821 	ret = kstrtoul(buf, 0, &new);
822 	if (ret)
823 		return ret;
824 	*(unsigned long *)(ea->var) = new;
825 	/* Always return full write size even if we didn't consume all */
826 	return size;
827 }
828 EXPORT_SYMBOL_GPL(device_store_ulong);
829 
830 ssize_t device_show_ulong(struct device *dev,
831 			  struct device_attribute *attr,
832 			  char *buf)
833 {
834 	struct dev_ext_attribute *ea = to_ext_attr(attr);
835 	return snprintf(buf, PAGE_SIZE, "%lx\n", *(unsigned long *)(ea->var));
836 }
837 EXPORT_SYMBOL_GPL(device_show_ulong);
838 
839 ssize_t device_store_int(struct device *dev,
840 			 struct device_attribute *attr,
841 			 const char *buf, size_t size)
842 {
843 	struct dev_ext_attribute *ea = to_ext_attr(attr);
844 	int ret;
845 	long new;
846 
847 	ret = kstrtol(buf, 0, &new);
848 	if (ret)
849 		return ret;
850 
851 	if (new > INT_MAX || new < INT_MIN)
852 		return -EINVAL;
853 	*(int *)(ea->var) = new;
854 	/* Always return full write size even if we didn't consume all */
855 	return size;
856 }
857 EXPORT_SYMBOL_GPL(device_store_int);
858 
859 ssize_t device_show_int(struct device *dev,
860 			struct device_attribute *attr,
861 			char *buf)
862 {
863 	struct dev_ext_attribute *ea = to_ext_attr(attr);
864 
865 	return snprintf(buf, PAGE_SIZE, "%d\n", *(int *)(ea->var));
866 }
867 EXPORT_SYMBOL_GPL(device_show_int);
868 
869 ssize_t device_store_bool(struct device *dev, struct device_attribute *attr,
870 			  const char *buf, size_t size)
871 {
872 	struct dev_ext_attribute *ea = to_ext_attr(attr);
873 
874 	if (strtobool(buf, ea->var) < 0)
875 		return -EINVAL;
876 
877 	return size;
878 }
879 EXPORT_SYMBOL_GPL(device_store_bool);
880 
881 ssize_t device_show_bool(struct device *dev, struct device_attribute *attr,
882 			 char *buf)
883 {
884 	struct dev_ext_attribute *ea = to_ext_attr(attr);
885 
886 	return snprintf(buf, PAGE_SIZE, "%d\n", *(bool *)(ea->var));
887 }
888 EXPORT_SYMBOL_GPL(device_show_bool);
889 
890 /**
891  * device_release - free device structure.
892  * @kobj: device's kobject.
893  *
894  * This is called once the reference count for the object
895  * reaches 0. We forward the call to the device's release
896  * method, which should handle actually freeing the structure.
897  */
898 static void device_release(struct kobject *kobj)
899 {
900 	struct device *dev = kobj_to_dev(kobj);
901 	struct device_private *p = dev->p;
902 
903 	/*
904 	 * Some platform devices are driven without driver attached
905 	 * and managed resources may have been acquired.  Make sure
906 	 * all resources are released.
907 	 *
908 	 * Drivers still can add resources into device after device
909 	 * is deleted but alive, so release devres here to avoid
910 	 * possible memory leak.
911 	 */
912 	devres_release_all(dev);
913 
914 	if (dev->release)
915 		dev->release(dev);
916 	else if (dev->type && dev->type->release)
917 		dev->type->release(dev);
918 	else if (dev->class && dev->class->dev_release)
919 		dev->class->dev_release(dev);
920 	else
921 		WARN(1, KERN_ERR "Device '%s' does not have a release() function, it is broken and must be fixed. See Documentation/kobject.txt.\n",
922 			dev_name(dev));
923 	kfree(p);
924 }
925 
926 static const void *device_namespace(struct kobject *kobj)
927 {
928 	struct device *dev = kobj_to_dev(kobj);
929 	const void *ns = NULL;
930 
931 	if (dev->class && dev->class->ns_type)
932 		ns = dev->class->namespace(dev);
933 
934 	return ns;
935 }
936 
937 static void device_get_ownership(struct kobject *kobj, kuid_t *uid, kgid_t *gid)
938 {
939 	struct device *dev = kobj_to_dev(kobj);
940 
941 	if (dev->class && dev->class->get_ownership)
942 		dev->class->get_ownership(dev, uid, gid);
943 }
944 
945 static struct kobj_type device_ktype = {
946 	.release	= device_release,
947 	.sysfs_ops	= &dev_sysfs_ops,
948 	.namespace	= device_namespace,
949 	.get_ownership	= device_get_ownership,
950 };
951 
952 
953 static int dev_uevent_filter(struct kset *kset, struct kobject *kobj)
954 {
955 	struct kobj_type *ktype = get_ktype(kobj);
956 
957 	if (ktype == &device_ktype) {
958 		struct device *dev = kobj_to_dev(kobj);
959 		if (dev->bus)
960 			return 1;
961 		if (dev->class)
962 			return 1;
963 	}
964 	return 0;
965 }
966 
967 static const char *dev_uevent_name(struct kset *kset, struct kobject *kobj)
968 {
969 	struct device *dev = kobj_to_dev(kobj);
970 
971 	if (dev->bus)
972 		return dev->bus->name;
973 	if (dev->class)
974 		return dev->class->name;
975 	return NULL;
976 }
977 
978 static int dev_uevent(struct kset *kset, struct kobject *kobj,
979 		      struct kobj_uevent_env *env)
980 {
981 	struct device *dev = kobj_to_dev(kobj);
982 	int retval = 0;
983 
984 	/* add device node properties if present */
985 	if (MAJOR(dev->devt)) {
986 		const char *tmp;
987 		const char *name;
988 		umode_t mode = 0;
989 		kuid_t uid = GLOBAL_ROOT_UID;
990 		kgid_t gid = GLOBAL_ROOT_GID;
991 
992 		add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt));
993 		add_uevent_var(env, "MINOR=%u", MINOR(dev->devt));
994 		name = device_get_devnode(dev, &mode, &uid, &gid, &tmp);
995 		if (name) {
996 			add_uevent_var(env, "DEVNAME=%s", name);
997 			if (mode)
998 				add_uevent_var(env, "DEVMODE=%#o", mode & 0777);
999 			if (!uid_eq(uid, GLOBAL_ROOT_UID))
1000 				add_uevent_var(env, "DEVUID=%u", from_kuid(&init_user_ns, uid));
1001 			if (!gid_eq(gid, GLOBAL_ROOT_GID))
1002 				add_uevent_var(env, "DEVGID=%u", from_kgid(&init_user_ns, gid));
1003 			kfree(tmp);
1004 		}
1005 	}
1006 
1007 	if (dev->type && dev->type->name)
1008 		add_uevent_var(env, "DEVTYPE=%s", dev->type->name);
1009 
1010 	if (dev->driver)
1011 		add_uevent_var(env, "DRIVER=%s", dev->driver->name);
1012 
1013 	/* Add common DT information about the device */
1014 	of_device_uevent(dev, env);
1015 
1016 	/* have the bus specific function add its stuff */
1017 	if (dev->bus && dev->bus->uevent) {
1018 		retval = dev->bus->uevent(dev, env);
1019 		if (retval)
1020 			pr_debug("device: '%s': %s: bus uevent() returned %d\n",
1021 				 dev_name(dev), __func__, retval);
1022 	}
1023 
1024 	/* have the class specific function add its stuff */
1025 	if (dev->class && dev->class->dev_uevent) {
1026 		retval = dev->class->dev_uevent(dev, env);
1027 		if (retval)
1028 			pr_debug("device: '%s': %s: class uevent() "
1029 				 "returned %d\n", dev_name(dev),
1030 				 __func__, retval);
1031 	}
1032 
1033 	/* have the device type specific function add its stuff */
1034 	if (dev->type && dev->type->uevent) {
1035 		retval = dev->type->uevent(dev, env);
1036 		if (retval)
1037 			pr_debug("device: '%s': %s: dev_type uevent() "
1038 				 "returned %d\n", dev_name(dev),
1039 				 __func__, retval);
1040 	}
1041 
1042 	return retval;
1043 }
1044 
1045 static const struct kset_uevent_ops device_uevent_ops = {
1046 	.filter =	dev_uevent_filter,
1047 	.name =		dev_uevent_name,
1048 	.uevent =	dev_uevent,
1049 };
1050 
1051 static ssize_t uevent_show(struct device *dev, struct device_attribute *attr,
1052 			   char *buf)
1053 {
1054 	struct kobject *top_kobj;
1055 	struct kset *kset;
1056 	struct kobj_uevent_env *env = NULL;
1057 	int i;
1058 	size_t count = 0;
1059 	int retval;
1060 
1061 	/* search the kset, the device belongs to */
1062 	top_kobj = &dev->kobj;
1063 	while (!top_kobj->kset && top_kobj->parent)
1064 		top_kobj = top_kobj->parent;
1065 	if (!top_kobj->kset)
1066 		goto out;
1067 
1068 	kset = top_kobj->kset;
1069 	if (!kset->uevent_ops || !kset->uevent_ops->uevent)
1070 		goto out;
1071 
1072 	/* respect filter */
1073 	if (kset->uevent_ops && kset->uevent_ops->filter)
1074 		if (!kset->uevent_ops->filter(kset, &dev->kobj))
1075 			goto out;
1076 
1077 	env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
1078 	if (!env)
1079 		return -ENOMEM;
1080 
1081 	/* let the kset specific function add its keys */
1082 	retval = kset->uevent_ops->uevent(kset, &dev->kobj, env);
1083 	if (retval)
1084 		goto out;
1085 
1086 	/* copy keys to file */
1087 	for (i = 0; i < env->envp_idx; i++)
1088 		count += sprintf(&buf[count], "%s\n", env->envp[i]);
1089 out:
1090 	kfree(env);
1091 	return count;
1092 }
1093 
1094 static ssize_t uevent_store(struct device *dev, struct device_attribute *attr,
1095 			    const char *buf, size_t count)
1096 {
1097 	int rc;
1098 
1099 	rc = kobject_synth_uevent(&dev->kobj, buf, count);
1100 
1101 	if (rc) {
1102 		dev_err(dev, "uevent: failed to send synthetic uevent\n");
1103 		return rc;
1104 	}
1105 
1106 	return count;
1107 }
1108 static DEVICE_ATTR_RW(uevent);
1109 
1110 static ssize_t online_show(struct device *dev, struct device_attribute *attr,
1111 			   char *buf)
1112 {
1113 	bool val;
1114 
1115 	device_lock(dev);
1116 	val = !dev->offline;
1117 	device_unlock(dev);
1118 	return sprintf(buf, "%u\n", val);
1119 }
1120 
1121 static ssize_t online_store(struct device *dev, struct device_attribute *attr,
1122 			    const char *buf, size_t count)
1123 {
1124 	bool val;
1125 	int ret;
1126 
1127 	ret = strtobool(buf, &val);
1128 	if (ret < 0)
1129 		return ret;
1130 
1131 	ret = lock_device_hotplug_sysfs();
1132 	if (ret)
1133 		return ret;
1134 
1135 	ret = val ? device_online(dev) : device_offline(dev);
1136 	unlock_device_hotplug();
1137 	return ret < 0 ? ret : count;
1138 }
1139 static DEVICE_ATTR_RW(online);
1140 
1141 int device_add_groups(struct device *dev, const struct attribute_group **groups)
1142 {
1143 	return sysfs_create_groups(&dev->kobj, groups);
1144 }
1145 EXPORT_SYMBOL_GPL(device_add_groups);
1146 
1147 void device_remove_groups(struct device *dev,
1148 			  const struct attribute_group **groups)
1149 {
1150 	sysfs_remove_groups(&dev->kobj, groups);
1151 }
1152 EXPORT_SYMBOL_GPL(device_remove_groups);
1153 
1154 union device_attr_group_devres {
1155 	const struct attribute_group *group;
1156 	const struct attribute_group **groups;
1157 };
1158 
1159 static int devm_attr_group_match(struct device *dev, void *res, void *data)
1160 {
1161 	return ((union device_attr_group_devres *)res)->group == data;
1162 }
1163 
1164 static void devm_attr_group_remove(struct device *dev, void *res)
1165 {
1166 	union device_attr_group_devres *devres = res;
1167 	const struct attribute_group *group = devres->group;
1168 
1169 	dev_dbg(dev, "%s: removing group %p\n", __func__, group);
1170 	sysfs_remove_group(&dev->kobj, group);
1171 }
1172 
1173 static void devm_attr_groups_remove(struct device *dev, void *res)
1174 {
1175 	union device_attr_group_devres *devres = res;
1176 	const struct attribute_group **groups = devres->groups;
1177 
1178 	dev_dbg(dev, "%s: removing groups %p\n", __func__, groups);
1179 	sysfs_remove_groups(&dev->kobj, groups);
1180 }
1181 
1182 /**
1183  * devm_device_add_group - given a device, create a managed attribute group
1184  * @dev:	The device to create the group for
1185  * @grp:	The attribute group to create
1186  *
1187  * This function creates a group for the first time.  It will explicitly
1188  * warn and error if any of the attribute files being created already exist.
1189  *
1190  * Returns 0 on success or error code on failure.
1191  */
1192 int devm_device_add_group(struct device *dev, const struct attribute_group *grp)
1193 {
1194 	union device_attr_group_devres *devres;
1195 	int error;
1196 
1197 	devres = devres_alloc(devm_attr_group_remove,
1198 			      sizeof(*devres), GFP_KERNEL);
1199 	if (!devres)
1200 		return -ENOMEM;
1201 
1202 	error = sysfs_create_group(&dev->kobj, grp);
1203 	if (error) {
1204 		devres_free(devres);
1205 		return error;
1206 	}
1207 
1208 	devres->group = grp;
1209 	devres_add(dev, devres);
1210 	return 0;
1211 }
1212 EXPORT_SYMBOL_GPL(devm_device_add_group);
1213 
1214 /**
1215  * devm_device_remove_group: remove a managed group from a device
1216  * @dev:	device to remove the group from
1217  * @grp:	group to remove
1218  *
1219  * This function removes a group of attributes from a device. The attributes
1220  * previously have to have been created for this group, otherwise it will fail.
1221  */
1222 void devm_device_remove_group(struct device *dev,
1223 			      const struct attribute_group *grp)
1224 {
1225 	WARN_ON(devres_release(dev, devm_attr_group_remove,
1226 			       devm_attr_group_match,
1227 			       /* cast away const */ (void *)grp));
1228 }
1229 EXPORT_SYMBOL_GPL(devm_device_remove_group);
1230 
1231 /**
1232  * devm_device_add_groups - create a bunch of managed attribute groups
1233  * @dev:	The device to create the group for
1234  * @groups:	The attribute groups to create, NULL terminated
1235  *
1236  * This function creates a bunch of managed attribute groups.  If an error
1237  * occurs when creating a group, all previously created groups will be
1238  * removed, unwinding everything back to the original state when this
1239  * function was called.  It will explicitly warn and error if any of the
1240  * attribute files being created already exist.
1241  *
1242  * Returns 0 on success or error code from sysfs_create_group on failure.
1243  */
1244 int devm_device_add_groups(struct device *dev,
1245 			   const struct attribute_group **groups)
1246 {
1247 	union device_attr_group_devres *devres;
1248 	int error;
1249 
1250 	devres = devres_alloc(devm_attr_groups_remove,
1251 			      sizeof(*devres), GFP_KERNEL);
1252 	if (!devres)
1253 		return -ENOMEM;
1254 
1255 	error = sysfs_create_groups(&dev->kobj, groups);
1256 	if (error) {
1257 		devres_free(devres);
1258 		return error;
1259 	}
1260 
1261 	devres->groups = groups;
1262 	devres_add(dev, devres);
1263 	return 0;
1264 }
1265 EXPORT_SYMBOL_GPL(devm_device_add_groups);
1266 
1267 /**
1268  * devm_device_remove_groups - remove a list of managed groups
1269  *
1270  * @dev:	The device for the groups to be removed from
1271  * @groups:	NULL terminated list of groups to be removed
1272  *
1273  * If groups is not NULL, remove the specified groups from the device.
1274  */
1275 void devm_device_remove_groups(struct device *dev,
1276 			       const struct attribute_group **groups)
1277 {
1278 	WARN_ON(devres_release(dev, devm_attr_groups_remove,
1279 			       devm_attr_group_match,
1280 			       /* cast away const */ (void *)groups));
1281 }
1282 EXPORT_SYMBOL_GPL(devm_device_remove_groups);
1283 
1284 static int device_add_attrs(struct device *dev)
1285 {
1286 	struct class *class = dev->class;
1287 	const struct device_type *type = dev->type;
1288 	int error;
1289 
1290 	if (class) {
1291 		error = device_add_groups(dev, class->dev_groups);
1292 		if (error)
1293 			return error;
1294 	}
1295 
1296 	if (type) {
1297 		error = device_add_groups(dev, type->groups);
1298 		if (error)
1299 			goto err_remove_class_groups;
1300 	}
1301 
1302 	error = device_add_groups(dev, dev->groups);
1303 	if (error)
1304 		goto err_remove_type_groups;
1305 
1306 	if (device_supports_offline(dev) && !dev->offline_disabled) {
1307 		error = device_create_file(dev, &dev_attr_online);
1308 		if (error)
1309 			goto err_remove_dev_groups;
1310 	}
1311 
1312 	return 0;
1313 
1314  err_remove_dev_groups:
1315 	device_remove_groups(dev, dev->groups);
1316  err_remove_type_groups:
1317 	if (type)
1318 		device_remove_groups(dev, type->groups);
1319  err_remove_class_groups:
1320 	if (class)
1321 		device_remove_groups(dev, class->dev_groups);
1322 
1323 	return error;
1324 }
1325 
1326 static void device_remove_attrs(struct device *dev)
1327 {
1328 	struct class *class = dev->class;
1329 	const struct device_type *type = dev->type;
1330 
1331 	device_remove_file(dev, &dev_attr_online);
1332 	device_remove_groups(dev, dev->groups);
1333 
1334 	if (type)
1335 		device_remove_groups(dev, type->groups);
1336 
1337 	if (class)
1338 		device_remove_groups(dev, class->dev_groups);
1339 }
1340 
1341 static ssize_t dev_show(struct device *dev, struct device_attribute *attr,
1342 			char *buf)
1343 {
1344 	return print_dev_t(buf, dev->devt);
1345 }
1346 static DEVICE_ATTR_RO(dev);
1347 
1348 /* /sys/devices/ */
1349 struct kset *devices_kset;
1350 
1351 /**
1352  * devices_kset_move_before - Move device in the devices_kset's list.
1353  * @deva: Device to move.
1354  * @devb: Device @deva should come before.
1355  */
1356 static void devices_kset_move_before(struct device *deva, struct device *devb)
1357 {
1358 	if (!devices_kset)
1359 		return;
1360 	pr_debug("devices_kset: Moving %s before %s\n",
1361 		 dev_name(deva), dev_name(devb));
1362 	spin_lock(&devices_kset->list_lock);
1363 	list_move_tail(&deva->kobj.entry, &devb->kobj.entry);
1364 	spin_unlock(&devices_kset->list_lock);
1365 }
1366 
1367 /**
1368  * devices_kset_move_after - Move device in the devices_kset's list.
1369  * @deva: Device to move
1370  * @devb: Device @deva should come after.
1371  */
1372 static void devices_kset_move_after(struct device *deva, struct device *devb)
1373 {
1374 	if (!devices_kset)
1375 		return;
1376 	pr_debug("devices_kset: Moving %s after %s\n",
1377 		 dev_name(deva), dev_name(devb));
1378 	spin_lock(&devices_kset->list_lock);
1379 	list_move(&deva->kobj.entry, &devb->kobj.entry);
1380 	spin_unlock(&devices_kset->list_lock);
1381 }
1382 
1383 /**
1384  * devices_kset_move_last - move the device to the end of devices_kset's list.
1385  * @dev: device to move
1386  */
1387 void devices_kset_move_last(struct device *dev)
1388 {
1389 	if (!devices_kset)
1390 		return;
1391 	pr_debug("devices_kset: Moving %s to end of list\n", dev_name(dev));
1392 	spin_lock(&devices_kset->list_lock);
1393 	list_move_tail(&dev->kobj.entry, &devices_kset->list);
1394 	spin_unlock(&devices_kset->list_lock);
1395 }
1396 
1397 /**
1398  * device_create_file - create sysfs attribute file for device.
1399  * @dev: device.
1400  * @attr: device attribute descriptor.
1401  */
1402 int device_create_file(struct device *dev,
1403 		       const struct device_attribute *attr)
1404 {
1405 	int error = 0;
1406 
1407 	if (dev) {
1408 		WARN(((attr->attr.mode & S_IWUGO) && !attr->store),
1409 			"Attribute %s: write permission without 'store'\n",
1410 			attr->attr.name);
1411 		WARN(((attr->attr.mode & S_IRUGO) && !attr->show),
1412 			"Attribute %s: read permission without 'show'\n",
1413 			attr->attr.name);
1414 		error = sysfs_create_file(&dev->kobj, &attr->attr);
1415 	}
1416 
1417 	return error;
1418 }
1419 EXPORT_SYMBOL_GPL(device_create_file);
1420 
1421 /**
1422  * device_remove_file - remove sysfs attribute file.
1423  * @dev: device.
1424  * @attr: device attribute descriptor.
1425  */
1426 void device_remove_file(struct device *dev,
1427 			const struct device_attribute *attr)
1428 {
1429 	if (dev)
1430 		sysfs_remove_file(&dev->kobj, &attr->attr);
1431 }
1432 EXPORT_SYMBOL_GPL(device_remove_file);
1433 
1434 /**
1435  * device_remove_file_self - remove sysfs attribute file from its own method.
1436  * @dev: device.
1437  * @attr: device attribute descriptor.
1438  *
1439  * See kernfs_remove_self() for details.
1440  */
1441 bool device_remove_file_self(struct device *dev,
1442 			     const struct device_attribute *attr)
1443 {
1444 	if (dev)
1445 		return sysfs_remove_file_self(&dev->kobj, &attr->attr);
1446 	else
1447 		return false;
1448 }
1449 EXPORT_SYMBOL_GPL(device_remove_file_self);
1450 
1451 /**
1452  * device_create_bin_file - create sysfs binary attribute file for device.
1453  * @dev: device.
1454  * @attr: device binary attribute descriptor.
1455  */
1456 int device_create_bin_file(struct device *dev,
1457 			   const struct bin_attribute *attr)
1458 {
1459 	int error = -EINVAL;
1460 	if (dev)
1461 		error = sysfs_create_bin_file(&dev->kobj, attr);
1462 	return error;
1463 }
1464 EXPORT_SYMBOL_GPL(device_create_bin_file);
1465 
1466 /**
1467  * device_remove_bin_file - remove sysfs binary attribute file
1468  * @dev: device.
1469  * @attr: device binary attribute descriptor.
1470  */
1471 void device_remove_bin_file(struct device *dev,
1472 			    const struct bin_attribute *attr)
1473 {
1474 	if (dev)
1475 		sysfs_remove_bin_file(&dev->kobj, attr);
1476 }
1477 EXPORT_SYMBOL_GPL(device_remove_bin_file);
1478 
1479 static void klist_children_get(struct klist_node *n)
1480 {
1481 	struct device_private *p = to_device_private_parent(n);
1482 	struct device *dev = p->device;
1483 
1484 	get_device(dev);
1485 }
1486 
1487 static void klist_children_put(struct klist_node *n)
1488 {
1489 	struct device_private *p = to_device_private_parent(n);
1490 	struct device *dev = p->device;
1491 
1492 	put_device(dev);
1493 }
1494 
1495 /**
1496  * device_initialize - init device structure.
1497  * @dev: device.
1498  *
1499  * This prepares the device for use by other layers by initializing
1500  * its fields.
1501  * It is the first half of device_register(), if called by
1502  * that function, though it can also be called separately, so one
1503  * may use @dev's fields. In particular, get_device()/put_device()
1504  * may be used for reference counting of @dev after calling this
1505  * function.
1506  *
1507  * All fields in @dev must be initialized by the caller to 0, except
1508  * for those explicitly set to some other value.  The simplest
1509  * approach is to use kzalloc() to allocate the structure containing
1510  * @dev.
1511  *
1512  * NOTE: Use put_device() to give up your reference instead of freeing
1513  * @dev directly once you have called this function.
1514  */
1515 void device_initialize(struct device *dev)
1516 {
1517 	dev->kobj.kset = devices_kset;
1518 	kobject_init(&dev->kobj, &device_ktype);
1519 	INIT_LIST_HEAD(&dev->dma_pools);
1520 	mutex_init(&dev->mutex);
1521 	lockdep_set_novalidate_class(&dev->mutex);
1522 	spin_lock_init(&dev->devres_lock);
1523 	INIT_LIST_HEAD(&dev->devres_head);
1524 	device_pm_init(dev);
1525 	set_dev_node(dev, -1);
1526 #ifdef CONFIG_GENERIC_MSI_IRQ
1527 	INIT_LIST_HEAD(&dev->msi_list);
1528 #endif
1529 	INIT_LIST_HEAD(&dev->links.consumers);
1530 	INIT_LIST_HEAD(&dev->links.suppliers);
1531 	dev->links.status = DL_DEV_NO_DRIVER;
1532 }
1533 EXPORT_SYMBOL_GPL(device_initialize);
1534 
1535 struct kobject *virtual_device_parent(struct device *dev)
1536 {
1537 	static struct kobject *virtual_dir = NULL;
1538 
1539 	if (!virtual_dir)
1540 		virtual_dir = kobject_create_and_add("virtual",
1541 						     &devices_kset->kobj);
1542 
1543 	return virtual_dir;
1544 }
1545 
1546 struct class_dir {
1547 	struct kobject kobj;
1548 	struct class *class;
1549 };
1550 
1551 #define to_class_dir(obj) container_of(obj, struct class_dir, kobj)
1552 
1553 static void class_dir_release(struct kobject *kobj)
1554 {
1555 	struct class_dir *dir = to_class_dir(kobj);
1556 	kfree(dir);
1557 }
1558 
1559 static const
1560 struct kobj_ns_type_operations *class_dir_child_ns_type(struct kobject *kobj)
1561 {
1562 	struct class_dir *dir = to_class_dir(kobj);
1563 	return dir->class->ns_type;
1564 }
1565 
1566 static struct kobj_type class_dir_ktype = {
1567 	.release	= class_dir_release,
1568 	.sysfs_ops	= &kobj_sysfs_ops,
1569 	.child_ns_type	= class_dir_child_ns_type
1570 };
1571 
1572 static struct kobject *
1573 class_dir_create_and_add(struct class *class, struct kobject *parent_kobj)
1574 {
1575 	struct class_dir *dir;
1576 	int retval;
1577 
1578 	dir = kzalloc(sizeof(*dir), GFP_KERNEL);
1579 	if (!dir)
1580 		return ERR_PTR(-ENOMEM);
1581 
1582 	dir->class = class;
1583 	kobject_init(&dir->kobj, &class_dir_ktype);
1584 
1585 	dir->kobj.kset = &class->p->glue_dirs;
1586 
1587 	retval = kobject_add(&dir->kobj, parent_kobj, "%s", class->name);
1588 	if (retval < 0) {
1589 		kobject_put(&dir->kobj);
1590 		return ERR_PTR(retval);
1591 	}
1592 	return &dir->kobj;
1593 }
1594 
1595 static DEFINE_MUTEX(gdp_mutex);
1596 
1597 static struct kobject *get_device_parent(struct device *dev,
1598 					 struct device *parent)
1599 {
1600 	if (dev->class) {
1601 		struct kobject *kobj = NULL;
1602 		struct kobject *parent_kobj;
1603 		struct kobject *k;
1604 
1605 #ifdef CONFIG_BLOCK
1606 		/* block disks show up in /sys/block */
1607 		if (sysfs_deprecated && dev->class == &block_class) {
1608 			if (parent && parent->class == &block_class)
1609 				return &parent->kobj;
1610 			return &block_class.p->subsys.kobj;
1611 		}
1612 #endif
1613 
1614 		/*
1615 		 * If we have no parent, we live in "virtual".
1616 		 * Class-devices with a non class-device as parent, live
1617 		 * in a "glue" directory to prevent namespace collisions.
1618 		 */
1619 		if (parent == NULL)
1620 			parent_kobj = virtual_device_parent(dev);
1621 		else if (parent->class && !dev->class->ns_type)
1622 			return &parent->kobj;
1623 		else
1624 			parent_kobj = &parent->kobj;
1625 
1626 		mutex_lock(&gdp_mutex);
1627 
1628 		/* find our class-directory at the parent and reference it */
1629 		spin_lock(&dev->class->p->glue_dirs.list_lock);
1630 		list_for_each_entry(k, &dev->class->p->glue_dirs.list, entry)
1631 			if (k->parent == parent_kobj) {
1632 				kobj = kobject_get(k);
1633 				break;
1634 			}
1635 		spin_unlock(&dev->class->p->glue_dirs.list_lock);
1636 		if (kobj) {
1637 			mutex_unlock(&gdp_mutex);
1638 			return kobj;
1639 		}
1640 
1641 		/* or create a new class-directory at the parent device */
1642 		k = class_dir_create_and_add(dev->class, parent_kobj);
1643 		/* do not emit an uevent for this simple "glue" directory */
1644 		mutex_unlock(&gdp_mutex);
1645 		return k;
1646 	}
1647 
1648 	/* subsystems can specify a default root directory for their devices */
1649 	if (!parent && dev->bus && dev->bus->dev_root)
1650 		return &dev->bus->dev_root->kobj;
1651 
1652 	if (parent)
1653 		return &parent->kobj;
1654 	return NULL;
1655 }
1656 
1657 static inline bool live_in_glue_dir(struct kobject *kobj,
1658 				    struct device *dev)
1659 {
1660 	if (!kobj || !dev->class ||
1661 	    kobj->kset != &dev->class->p->glue_dirs)
1662 		return false;
1663 	return true;
1664 }
1665 
1666 static inline struct kobject *get_glue_dir(struct device *dev)
1667 {
1668 	return dev->kobj.parent;
1669 }
1670 
1671 /*
1672  * make sure cleaning up dir as the last step, we need to make
1673  * sure .release handler of kobject is run with holding the
1674  * global lock
1675  */
1676 static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir)
1677 {
1678 	/* see if we live in a "glue" directory */
1679 	if (!live_in_glue_dir(glue_dir, dev))
1680 		return;
1681 
1682 	mutex_lock(&gdp_mutex);
1683 	if (!kobject_has_children(glue_dir))
1684 		kobject_del(glue_dir);
1685 	kobject_put(glue_dir);
1686 	mutex_unlock(&gdp_mutex);
1687 }
1688 
1689 static int device_add_class_symlinks(struct device *dev)
1690 {
1691 	struct device_node *of_node = dev_of_node(dev);
1692 	int error;
1693 
1694 	if (of_node) {
1695 		error = sysfs_create_link(&dev->kobj, of_node_kobj(of_node), "of_node");
1696 		if (error)
1697 			dev_warn(dev, "Error %d creating of_node link\n",error);
1698 		/* An error here doesn't warrant bringing down the device */
1699 	}
1700 
1701 	if (!dev->class)
1702 		return 0;
1703 
1704 	error = sysfs_create_link(&dev->kobj,
1705 				  &dev->class->p->subsys.kobj,
1706 				  "subsystem");
1707 	if (error)
1708 		goto out_devnode;
1709 
1710 	if (dev->parent && device_is_not_partition(dev)) {
1711 		error = sysfs_create_link(&dev->kobj, &dev->parent->kobj,
1712 					  "device");
1713 		if (error)
1714 			goto out_subsys;
1715 	}
1716 
1717 #ifdef CONFIG_BLOCK
1718 	/* /sys/block has directories and does not need symlinks */
1719 	if (sysfs_deprecated && dev->class == &block_class)
1720 		return 0;
1721 #endif
1722 
1723 	/* link in the class directory pointing to the device */
1724 	error = sysfs_create_link(&dev->class->p->subsys.kobj,
1725 				  &dev->kobj, dev_name(dev));
1726 	if (error)
1727 		goto out_device;
1728 
1729 	return 0;
1730 
1731 out_device:
1732 	sysfs_remove_link(&dev->kobj, "device");
1733 
1734 out_subsys:
1735 	sysfs_remove_link(&dev->kobj, "subsystem");
1736 out_devnode:
1737 	sysfs_remove_link(&dev->kobj, "of_node");
1738 	return error;
1739 }
1740 
1741 static void device_remove_class_symlinks(struct device *dev)
1742 {
1743 	if (dev_of_node(dev))
1744 		sysfs_remove_link(&dev->kobj, "of_node");
1745 
1746 	if (!dev->class)
1747 		return;
1748 
1749 	if (dev->parent && device_is_not_partition(dev))
1750 		sysfs_remove_link(&dev->kobj, "device");
1751 	sysfs_remove_link(&dev->kobj, "subsystem");
1752 #ifdef CONFIG_BLOCK
1753 	if (sysfs_deprecated && dev->class == &block_class)
1754 		return;
1755 #endif
1756 	sysfs_delete_link(&dev->class->p->subsys.kobj, &dev->kobj, dev_name(dev));
1757 }
1758 
1759 /**
1760  * dev_set_name - set a device name
1761  * @dev: device
1762  * @fmt: format string for the device's name
1763  */
1764 int dev_set_name(struct device *dev, const char *fmt, ...)
1765 {
1766 	va_list vargs;
1767 	int err;
1768 
1769 	va_start(vargs, fmt);
1770 	err = kobject_set_name_vargs(&dev->kobj, fmt, vargs);
1771 	va_end(vargs);
1772 	return err;
1773 }
1774 EXPORT_SYMBOL_GPL(dev_set_name);
1775 
1776 /**
1777  * device_to_dev_kobj - select a /sys/dev/ directory for the device
1778  * @dev: device
1779  *
1780  * By default we select char/ for new entries.  Setting class->dev_obj
1781  * to NULL prevents an entry from being created.  class->dev_kobj must
1782  * be set (or cleared) before any devices are registered to the class
1783  * otherwise device_create_sys_dev_entry() and
1784  * device_remove_sys_dev_entry() will disagree about the presence of
1785  * the link.
1786  */
1787 static struct kobject *device_to_dev_kobj(struct device *dev)
1788 {
1789 	struct kobject *kobj;
1790 
1791 	if (dev->class)
1792 		kobj = dev->class->dev_kobj;
1793 	else
1794 		kobj = sysfs_dev_char_kobj;
1795 
1796 	return kobj;
1797 }
1798 
1799 static int device_create_sys_dev_entry(struct device *dev)
1800 {
1801 	struct kobject *kobj = device_to_dev_kobj(dev);
1802 	int error = 0;
1803 	char devt_str[15];
1804 
1805 	if (kobj) {
1806 		format_dev_t(devt_str, dev->devt);
1807 		error = sysfs_create_link(kobj, &dev->kobj, devt_str);
1808 	}
1809 
1810 	return error;
1811 }
1812 
1813 static void device_remove_sys_dev_entry(struct device *dev)
1814 {
1815 	struct kobject *kobj = device_to_dev_kobj(dev);
1816 	char devt_str[15];
1817 
1818 	if (kobj) {
1819 		format_dev_t(devt_str, dev->devt);
1820 		sysfs_remove_link(kobj, devt_str);
1821 	}
1822 }
1823 
1824 static int device_private_init(struct device *dev)
1825 {
1826 	dev->p = kzalloc(sizeof(*dev->p), GFP_KERNEL);
1827 	if (!dev->p)
1828 		return -ENOMEM;
1829 	dev->p->device = dev;
1830 	klist_init(&dev->p->klist_children, klist_children_get,
1831 		   klist_children_put);
1832 	INIT_LIST_HEAD(&dev->p->deferred_probe);
1833 	return 0;
1834 }
1835 
1836 /**
1837  * device_add - add device to device hierarchy.
1838  * @dev: device.
1839  *
1840  * This is part 2 of device_register(), though may be called
1841  * separately _iff_ device_initialize() has been called separately.
1842  *
1843  * This adds @dev to the kobject hierarchy via kobject_add(), adds it
1844  * to the global and sibling lists for the device, then
1845  * adds it to the other relevant subsystems of the driver model.
1846  *
1847  * Do not call this routine or device_register() more than once for
1848  * any device structure.  The driver model core is not designed to work
1849  * with devices that get unregistered and then spring back to life.
1850  * (Among other things, it's very hard to guarantee that all references
1851  * to the previous incarnation of @dev have been dropped.)  Allocate
1852  * and register a fresh new struct device instead.
1853  *
1854  * NOTE: _Never_ directly free @dev after calling this function, even
1855  * if it returned an error! Always use put_device() to give up your
1856  * reference instead.
1857  */
1858 int device_add(struct device *dev)
1859 {
1860 	struct device *parent;
1861 	struct kobject *kobj;
1862 	struct class_interface *class_intf;
1863 	int error = -EINVAL;
1864 	struct kobject *glue_dir = NULL;
1865 
1866 	dev = get_device(dev);
1867 	if (!dev)
1868 		goto done;
1869 
1870 	if (!dev->p) {
1871 		error = device_private_init(dev);
1872 		if (error)
1873 			goto done;
1874 	}
1875 
1876 	/*
1877 	 * for statically allocated devices, which should all be converted
1878 	 * some day, we need to initialize the name. We prevent reading back
1879 	 * the name, and force the use of dev_name()
1880 	 */
1881 	if (dev->init_name) {
1882 		dev_set_name(dev, "%s", dev->init_name);
1883 		dev->init_name = NULL;
1884 	}
1885 
1886 	/* subsystems can specify simple device enumeration */
1887 	if (!dev_name(dev) && dev->bus && dev->bus->dev_name)
1888 		dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
1889 
1890 	if (!dev_name(dev)) {
1891 		error = -EINVAL;
1892 		goto name_error;
1893 	}
1894 
1895 	pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
1896 
1897 	parent = get_device(dev->parent);
1898 	kobj = get_device_parent(dev, parent);
1899 	if (IS_ERR(kobj)) {
1900 		error = PTR_ERR(kobj);
1901 		goto parent_error;
1902 	}
1903 	if (kobj)
1904 		dev->kobj.parent = kobj;
1905 
1906 	/* use parent numa_node */
1907 	if (parent && (dev_to_node(dev) == NUMA_NO_NODE))
1908 		set_dev_node(dev, dev_to_node(parent));
1909 
1910 	/* first, register with generic layer. */
1911 	/* we require the name to be set before, and pass NULL */
1912 	error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
1913 	if (error) {
1914 		glue_dir = get_glue_dir(dev);
1915 		goto Error;
1916 	}
1917 
1918 	/* notify platform of device entry */
1919 	error = device_platform_notify(dev, KOBJ_ADD);
1920 	if (error)
1921 		goto platform_error;
1922 
1923 	error = device_create_file(dev, &dev_attr_uevent);
1924 	if (error)
1925 		goto attrError;
1926 
1927 	error = device_add_class_symlinks(dev);
1928 	if (error)
1929 		goto SymlinkError;
1930 	error = device_add_attrs(dev);
1931 	if (error)
1932 		goto AttrsError;
1933 	error = bus_add_device(dev);
1934 	if (error)
1935 		goto BusError;
1936 	error = dpm_sysfs_add(dev);
1937 	if (error)
1938 		goto DPMError;
1939 	device_pm_add(dev);
1940 
1941 	if (MAJOR(dev->devt)) {
1942 		error = device_create_file(dev, &dev_attr_dev);
1943 		if (error)
1944 			goto DevAttrError;
1945 
1946 		error = device_create_sys_dev_entry(dev);
1947 		if (error)
1948 			goto SysEntryError;
1949 
1950 		devtmpfs_create_node(dev);
1951 	}
1952 
1953 	/* Notify clients of device addition.  This call must come
1954 	 * after dpm_sysfs_add() and before kobject_uevent().
1955 	 */
1956 	if (dev->bus)
1957 		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
1958 					     BUS_NOTIFY_ADD_DEVICE, dev);
1959 
1960 	kobject_uevent(&dev->kobj, KOBJ_ADD);
1961 	bus_probe_device(dev);
1962 	if (parent)
1963 		klist_add_tail(&dev->p->knode_parent,
1964 			       &parent->p->klist_children);
1965 
1966 	if (dev->class) {
1967 		mutex_lock(&dev->class->p->mutex);
1968 		/* tie the class to the device */
1969 		klist_add_tail(&dev->knode_class,
1970 			       &dev->class->p->klist_devices);
1971 
1972 		/* notify any interfaces that the device is here */
1973 		list_for_each_entry(class_intf,
1974 				    &dev->class->p->interfaces, node)
1975 			if (class_intf->add_dev)
1976 				class_intf->add_dev(dev, class_intf);
1977 		mutex_unlock(&dev->class->p->mutex);
1978 	}
1979 done:
1980 	put_device(dev);
1981 	return error;
1982  SysEntryError:
1983 	if (MAJOR(dev->devt))
1984 		device_remove_file(dev, &dev_attr_dev);
1985  DevAttrError:
1986 	device_pm_remove(dev);
1987 	dpm_sysfs_remove(dev);
1988  DPMError:
1989 	bus_remove_device(dev);
1990  BusError:
1991 	device_remove_attrs(dev);
1992  AttrsError:
1993 	device_remove_class_symlinks(dev);
1994  SymlinkError:
1995 	device_remove_file(dev, &dev_attr_uevent);
1996  attrError:
1997 	device_platform_notify(dev, KOBJ_REMOVE);
1998 platform_error:
1999 	kobject_uevent(&dev->kobj, KOBJ_REMOVE);
2000 	glue_dir = get_glue_dir(dev);
2001 	kobject_del(&dev->kobj);
2002  Error:
2003 	cleanup_glue_dir(dev, glue_dir);
2004 parent_error:
2005 	put_device(parent);
2006 name_error:
2007 	kfree(dev->p);
2008 	dev->p = NULL;
2009 	goto done;
2010 }
2011 EXPORT_SYMBOL_GPL(device_add);
2012 
2013 /**
2014  * device_register - register a device with the system.
2015  * @dev: pointer to the device structure
2016  *
2017  * This happens in two clean steps - initialize the device
2018  * and add it to the system. The two steps can be called
2019  * separately, but this is the easiest and most common.
2020  * I.e. you should only call the two helpers separately if
2021  * have a clearly defined need to use and refcount the device
2022  * before it is added to the hierarchy.
2023  *
2024  * For more information, see the kerneldoc for device_initialize()
2025  * and device_add().
2026  *
2027  * NOTE: _Never_ directly free @dev after calling this function, even
2028  * if it returned an error! Always use put_device() to give up the
2029  * reference initialized in this function instead.
2030  */
2031 int device_register(struct device *dev)
2032 {
2033 	device_initialize(dev);
2034 	return device_add(dev);
2035 }
2036 EXPORT_SYMBOL_GPL(device_register);
2037 
2038 /**
2039  * get_device - increment reference count for device.
2040  * @dev: device.
2041  *
2042  * This simply forwards the call to kobject_get(), though
2043  * we do take care to provide for the case that we get a NULL
2044  * pointer passed in.
2045  */
2046 struct device *get_device(struct device *dev)
2047 {
2048 	return dev ? kobj_to_dev(kobject_get(&dev->kobj)) : NULL;
2049 }
2050 EXPORT_SYMBOL_GPL(get_device);
2051 
2052 /**
2053  * put_device - decrement reference count.
2054  * @dev: device in question.
2055  */
2056 void put_device(struct device *dev)
2057 {
2058 	/* might_sleep(); */
2059 	if (dev)
2060 		kobject_put(&dev->kobj);
2061 }
2062 EXPORT_SYMBOL_GPL(put_device);
2063 
2064 /**
2065  * device_del - delete device from system.
2066  * @dev: device.
2067  *
2068  * This is the first part of the device unregistration
2069  * sequence. This removes the device from the lists we control
2070  * from here, has it removed from the other driver model
2071  * subsystems it was added to in device_add(), and removes it
2072  * from the kobject hierarchy.
2073  *
2074  * NOTE: this should be called manually _iff_ device_add() was
2075  * also called manually.
2076  */
2077 void device_del(struct device *dev)
2078 {
2079 	struct device *parent = dev->parent;
2080 	struct kobject *glue_dir = NULL;
2081 	struct class_interface *class_intf;
2082 
2083 	/* Notify clients of device removal.  This call must come
2084 	 * before dpm_sysfs_remove().
2085 	 */
2086 	if (dev->bus)
2087 		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
2088 					     BUS_NOTIFY_DEL_DEVICE, dev);
2089 
2090 	dpm_sysfs_remove(dev);
2091 	if (parent)
2092 		klist_del(&dev->p->knode_parent);
2093 	if (MAJOR(dev->devt)) {
2094 		devtmpfs_delete_node(dev);
2095 		device_remove_sys_dev_entry(dev);
2096 		device_remove_file(dev, &dev_attr_dev);
2097 	}
2098 	if (dev->class) {
2099 		device_remove_class_symlinks(dev);
2100 
2101 		mutex_lock(&dev->class->p->mutex);
2102 		/* notify any interfaces that the device is now gone */
2103 		list_for_each_entry(class_intf,
2104 				    &dev->class->p->interfaces, node)
2105 			if (class_intf->remove_dev)
2106 				class_intf->remove_dev(dev, class_intf);
2107 		/* remove the device from the class list */
2108 		klist_del(&dev->knode_class);
2109 		mutex_unlock(&dev->class->p->mutex);
2110 	}
2111 	device_remove_file(dev, &dev_attr_uevent);
2112 	device_remove_attrs(dev);
2113 	bus_remove_device(dev);
2114 	device_pm_remove(dev);
2115 	driver_deferred_probe_del(dev);
2116 	device_platform_notify(dev, KOBJ_REMOVE);
2117 	device_remove_properties(dev);
2118 	device_links_purge(dev);
2119 
2120 	if (dev->bus)
2121 		blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
2122 					     BUS_NOTIFY_REMOVED_DEVICE, dev);
2123 	kobject_uevent(&dev->kobj, KOBJ_REMOVE);
2124 	glue_dir = get_glue_dir(dev);
2125 	kobject_del(&dev->kobj);
2126 	cleanup_glue_dir(dev, glue_dir);
2127 	put_device(parent);
2128 }
2129 EXPORT_SYMBOL_GPL(device_del);
2130 
2131 /**
2132  * device_unregister - unregister device from system.
2133  * @dev: device going away.
2134  *
2135  * We do this in two parts, like we do device_register(). First,
2136  * we remove it from all the subsystems with device_del(), then
2137  * we decrement the reference count via put_device(). If that
2138  * is the final reference count, the device will be cleaned up
2139  * via device_release() above. Otherwise, the structure will
2140  * stick around until the final reference to the device is dropped.
2141  */
2142 void device_unregister(struct device *dev)
2143 {
2144 	pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
2145 	device_del(dev);
2146 	put_device(dev);
2147 }
2148 EXPORT_SYMBOL_GPL(device_unregister);
2149 
2150 static struct device *prev_device(struct klist_iter *i)
2151 {
2152 	struct klist_node *n = klist_prev(i);
2153 	struct device *dev = NULL;
2154 	struct device_private *p;
2155 
2156 	if (n) {
2157 		p = to_device_private_parent(n);
2158 		dev = p->device;
2159 	}
2160 	return dev;
2161 }
2162 
2163 static struct device *next_device(struct klist_iter *i)
2164 {
2165 	struct klist_node *n = klist_next(i);
2166 	struct device *dev = NULL;
2167 	struct device_private *p;
2168 
2169 	if (n) {
2170 		p = to_device_private_parent(n);
2171 		dev = p->device;
2172 	}
2173 	return dev;
2174 }
2175 
2176 /**
2177  * device_get_devnode - path of device node file
2178  * @dev: device
2179  * @mode: returned file access mode
2180  * @uid: returned file owner
2181  * @gid: returned file group
2182  * @tmp: possibly allocated string
2183  *
2184  * Return the relative path of a possible device node.
2185  * Non-default names may need to allocate a memory to compose
2186  * a name. This memory is returned in tmp and needs to be
2187  * freed by the caller.
2188  */
2189 const char *device_get_devnode(struct device *dev,
2190 			       umode_t *mode, kuid_t *uid, kgid_t *gid,
2191 			       const char **tmp)
2192 {
2193 	char *s;
2194 
2195 	*tmp = NULL;
2196 
2197 	/* the device type may provide a specific name */
2198 	if (dev->type && dev->type->devnode)
2199 		*tmp = dev->type->devnode(dev, mode, uid, gid);
2200 	if (*tmp)
2201 		return *tmp;
2202 
2203 	/* the class may provide a specific name */
2204 	if (dev->class && dev->class->devnode)
2205 		*tmp = dev->class->devnode(dev, mode);
2206 	if (*tmp)
2207 		return *tmp;
2208 
2209 	/* return name without allocation, tmp == NULL */
2210 	if (strchr(dev_name(dev), '!') == NULL)
2211 		return dev_name(dev);
2212 
2213 	/* replace '!' in the name with '/' */
2214 	s = kstrdup(dev_name(dev), GFP_KERNEL);
2215 	if (!s)
2216 		return NULL;
2217 	strreplace(s, '!', '/');
2218 	return *tmp = s;
2219 }
2220 
2221 /**
2222  * device_for_each_child - device child iterator.
2223  * @parent: parent struct device.
2224  * @fn: function to be called for each device.
2225  * @data: data for the callback.
2226  *
2227  * Iterate over @parent's child devices, and call @fn for each,
2228  * passing it @data.
2229  *
2230  * We check the return of @fn each time. If it returns anything
2231  * other than 0, we break out and return that value.
2232  */
2233 int device_for_each_child(struct device *parent, void *data,
2234 			  int (*fn)(struct device *dev, void *data))
2235 {
2236 	struct klist_iter i;
2237 	struct device *child;
2238 	int error = 0;
2239 
2240 	if (!parent->p)
2241 		return 0;
2242 
2243 	klist_iter_init(&parent->p->klist_children, &i);
2244 	while (!error && (child = next_device(&i)))
2245 		error = fn(child, data);
2246 	klist_iter_exit(&i);
2247 	return error;
2248 }
2249 EXPORT_SYMBOL_GPL(device_for_each_child);
2250 
2251 /**
2252  * device_for_each_child_reverse - device child iterator in reversed order.
2253  * @parent: parent struct device.
2254  * @fn: function to be called for each device.
2255  * @data: data for the callback.
2256  *
2257  * Iterate over @parent's child devices, and call @fn for each,
2258  * passing it @data.
2259  *
2260  * We check the return of @fn each time. If it returns anything
2261  * other than 0, we break out and return that value.
2262  */
2263 int device_for_each_child_reverse(struct device *parent, void *data,
2264 				  int (*fn)(struct device *dev, void *data))
2265 {
2266 	struct klist_iter i;
2267 	struct device *child;
2268 	int error = 0;
2269 
2270 	if (!parent->p)
2271 		return 0;
2272 
2273 	klist_iter_init(&parent->p->klist_children, &i);
2274 	while ((child = prev_device(&i)) && !error)
2275 		error = fn(child, data);
2276 	klist_iter_exit(&i);
2277 	return error;
2278 }
2279 EXPORT_SYMBOL_GPL(device_for_each_child_reverse);
2280 
2281 /**
2282  * device_find_child - device iterator for locating a particular device.
2283  * @parent: parent struct device
2284  * @match: Callback function to check device
2285  * @data: Data to pass to match function
2286  *
2287  * This is similar to the device_for_each_child() function above, but it
2288  * returns a reference to a device that is 'found' for later use, as
2289  * determined by the @match callback.
2290  *
2291  * The callback should return 0 if the device doesn't match and non-zero
2292  * if it does.  If the callback returns non-zero and a reference to the
2293  * current device can be obtained, this function will return to the caller
2294  * and not iterate over any more devices.
2295  *
2296  * NOTE: you will need to drop the reference with put_device() after use.
2297  */
2298 struct device *device_find_child(struct device *parent, void *data,
2299 				 int (*match)(struct device *dev, void *data))
2300 {
2301 	struct klist_iter i;
2302 	struct device *child;
2303 
2304 	if (!parent)
2305 		return NULL;
2306 
2307 	klist_iter_init(&parent->p->klist_children, &i);
2308 	while ((child = next_device(&i)))
2309 		if (match(child, data) && get_device(child))
2310 			break;
2311 	klist_iter_exit(&i);
2312 	return child;
2313 }
2314 EXPORT_SYMBOL_GPL(device_find_child);
2315 
2316 int __init devices_init(void)
2317 {
2318 	devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
2319 	if (!devices_kset)
2320 		return -ENOMEM;
2321 	dev_kobj = kobject_create_and_add("dev", NULL);
2322 	if (!dev_kobj)
2323 		goto dev_kobj_err;
2324 	sysfs_dev_block_kobj = kobject_create_and_add("block", dev_kobj);
2325 	if (!sysfs_dev_block_kobj)
2326 		goto block_kobj_err;
2327 	sysfs_dev_char_kobj = kobject_create_and_add("char", dev_kobj);
2328 	if (!sysfs_dev_char_kobj)
2329 		goto char_kobj_err;
2330 
2331 	return 0;
2332 
2333  char_kobj_err:
2334 	kobject_put(sysfs_dev_block_kobj);
2335  block_kobj_err:
2336 	kobject_put(dev_kobj);
2337  dev_kobj_err:
2338 	kset_unregister(devices_kset);
2339 	return -ENOMEM;
2340 }
2341 
2342 static int device_check_offline(struct device *dev, void *not_used)
2343 {
2344 	int ret;
2345 
2346 	ret = device_for_each_child(dev, NULL, device_check_offline);
2347 	if (ret)
2348 		return ret;
2349 
2350 	return device_supports_offline(dev) && !dev->offline ? -EBUSY : 0;
2351 }
2352 
2353 /**
2354  * device_offline - Prepare the device for hot-removal.
2355  * @dev: Device to be put offline.
2356  *
2357  * Execute the device bus type's .offline() callback, if present, to prepare
2358  * the device for a subsequent hot-removal.  If that succeeds, the device must
2359  * not be used until either it is removed or its bus type's .online() callback
2360  * is executed.
2361  *
2362  * Call under device_hotplug_lock.
2363  */
2364 int device_offline(struct device *dev)
2365 {
2366 	int ret;
2367 
2368 	if (dev->offline_disabled)
2369 		return -EPERM;
2370 
2371 	ret = device_for_each_child(dev, NULL, device_check_offline);
2372 	if (ret)
2373 		return ret;
2374 
2375 	device_lock(dev);
2376 	if (device_supports_offline(dev)) {
2377 		if (dev->offline) {
2378 			ret = 1;
2379 		} else {
2380 			ret = dev->bus->offline(dev);
2381 			if (!ret) {
2382 				kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
2383 				dev->offline = true;
2384 			}
2385 		}
2386 	}
2387 	device_unlock(dev);
2388 
2389 	return ret;
2390 }
2391 
2392 /**
2393  * device_online - Put the device back online after successful device_offline().
2394  * @dev: Device to be put back online.
2395  *
2396  * If device_offline() has been successfully executed for @dev, but the device
2397  * has not been removed subsequently, execute its bus type's .online() callback
2398  * to indicate that the device can be used again.
2399  *
2400  * Call under device_hotplug_lock.
2401  */
2402 int device_online(struct device *dev)
2403 {
2404 	int ret = 0;
2405 
2406 	device_lock(dev);
2407 	if (device_supports_offline(dev)) {
2408 		if (dev->offline) {
2409 			ret = dev->bus->online(dev);
2410 			if (!ret) {
2411 				kobject_uevent(&dev->kobj, KOBJ_ONLINE);
2412 				dev->offline = false;
2413 			}
2414 		} else {
2415 			ret = 1;
2416 		}
2417 	}
2418 	device_unlock(dev);
2419 
2420 	return ret;
2421 }
2422 
2423 struct root_device {
2424 	struct device dev;
2425 	struct module *owner;
2426 };
2427 
2428 static inline struct root_device *to_root_device(struct device *d)
2429 {
2430 	return container_of(d, struct root_device, dev);
2431 }
2432 
2433 static void root_device_release(struct device *dev)
2434 {
2435 	kfree(to_root_device(dev));
2436 }
2437 
2438 /**
2439  * __root_device_register - allocate and register a root device
2440  * @name: root device name
2441  * @owner: owner module of the root device, usually THIS_MODULE
2442  *
2443  * This function allocates a root device and registers it
2444  * using device_register(). In order to free the returned
2445  * device, use root_device_unregister().
2446  *
2447  * Root devices are dummy devices which allow other devices
2448  * to be grouped under /sys/devices. Use this function to
2449  * allocate a root device and then use it as the parent of
2450  * any device which should appear under /sys/devices/{name}
2451  *
2452  * The /sys/devices/{name} directory will also contain a
2453  * 'module' symlink which points to the @owner directory
2454  * in sysfs.
2455  *
2456  * Returns &struct device pointer on success, or ERR_PTR() on error.
2457  *
2458  * Note: You probably want to use root_device_register().
2459  */
2460 struct device *__root_device_register(const char *name, struct module *owner)
2461 {
2462 	struct root_device *root;
2463 	int err = -ENOMEM;
2464 
2465 	root = kzalloc(sizeof(struct root_device), GFP_KERNEL);
2466 	if (!root)
2467 		return ERR_PTR(err);
2468 
2469 	err = dev_set_name(&root->dev, "%s", name);
2470 	if (err) {
2471 		kfree(root);
2472 		return ERR_PTR(err);
2473 	}
2474 
2475 	root->dev.release = root_device_release;
2476 
2477 	err = device_register(&root->dev);
2478 	if (err) {
2479 		put_device(&root->dev);
2480 		return ERR_PTR(err);
2481 	}
2482 
2483 #ifdef CONFIG_MODULES	/* gotta find a "cleaner" way to do this */
2484 	if (owner) {
2485 		struct module_kobject *mk = &owner->mkobj;
2486 
2487 		err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module");
2488 		if (err) {
2489 			device_unregister(&root->dev);
2490 			return ERR_PTR(err);
2491 		}
2492 		root->owner = owner;
2493 	}
2494 #endif
2495 
2496 	return &root->dev;
2497 }
2498 EXPORT_SYMBOL_GPL(__root_device_register);
2499 
2500 /**
2501  * root_device_unregister - unregister and free a root device
2502  * @dev: device going away
2503  *
2504  * This function unregisters and cleans up a device that was created by
2505  * root_device_register().
2506  */
2507 void root_device_unregister(struct device *dev)
2508 {
2509 	struct root_device *root = to_root_device(dev);
2510 
2511 	if (root->owner)
2512 		sysfs_remove_link(&root->dev.kobj, "module");
2513 
2514 	device_unregister(dev);
2515 }
2516 EXPORT_SYMBOL_GPL(root_device_unregister);
2517 
2518 
2519 static void device_create_release(struct device *dev)
2520 {
2521 	pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
2522 	kfree(dev);
2523 }
2524 
2525 static __printf(6, 0) struct device *
2526 device_create_groups_vargs(struct class *class, struct device *parent,
2527 			   dev_t devt, void *drvdata,
2528 			   const struct attribute_group **groups,
2529 			   const char *fmt, va_list args)
2530 {
2531 	struct device *dev = NULL;
2532 	int retval = -ENODEV;
2533 
2534 	if (class == NULL || IS_ERR(class))
2535 		goto error;
2536 
2537 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2538 	if (!dev) {
2539 		retval = -ENOMEM;
2540 		goto error;
2541 	}
2542 
2543 	device_initialize(dev);
2544 	dev->devt = devt;
2545 	dev->class = class;
2546 	dev->parent = parent;
2547 	dev->groups = groups;
2548 	dev->release = device_create_release;
2549 	dev_set_drvdata(dev, drvdata);
2550 
2551 	retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
2552 	if (retval)
2553 		goto error;
2554 
2555 	retval = device_add(dev);
2556 	if (retval)
2557 		goto error;
2558 
2559 	return dev;
2560 
2561 error:
2562 	put_device(dev);
2563 	return ERR_PTR(retval);
2564 }
2565 
2566 /**
2567  * device_create_vargs - creates a device and registers it with sysfs
2568  * @class: pointer to the struct class that this device should be registered to
2569  * @parent: pointer to the parent struct device of this new device, if any
2570  * @devt: the dev_t for the char device to be added
2571  * @drvdata: the data to be added to the device for callbacks
2572  * @fmt: string for the device's name
2573  * @args: va_list for the device's name
2574  *
2575  * This function can be used by char device classes.  A struct device
2576  * will be created in sysfs, registered to the specified class.
2577  *
2578  * A "dev" file will be created, showing the dev_t for the device, if
2579  * the dev_t is not 0,0.
2580  * If a pointer to a parent struct device is passed in, the newly created
2581  * struct device will be a child of that device in sysfs.
2582  * The pointer to the struct device will be returned from the call.
2583  * Any further sysfs files that might be required can be created using this
2584  * pointer.
2585  *
2586  * Returns &struct device pointer on success, or ERR_PTR() on error.
2587  *
2588  * Note: the struct class passed to this function must have previously
2589  * been created with a call to class_create().
2590  */
2591 struct device *device_create_vargs(struct class *class, struct device *parent,
2592 				   dev_t devt, void *drvdata, const char *fmt,
2593 				   va_list args)
2594 {
2595 	return device_create_groups_vargs(class, parent, devt, drvdata, NULL,
2596 					  fmt, args);
2597 }
2598 EXPORT_SYMBOL_GPL(device_create_vargs);
2599 
2600 /**
2601  * device_create - creates a device and registers it with sysfs
2602  * @class: pointer to the struct class that this device should be registered to
2603  * @parent: pointer to the parent struct device of this new device, if any
2604  * @devt: the dev_t for the char device to be added
2605  * @drvdata: the data to be added to the device for callbacks
2606  * @fmt: string for the device's name
2607  *
2608  * This function can be used by char device classes.  A struct device
2609  * will be created in sysfs, registered to the specified class.
2610  *
2611  * A "dev" file will be created, showing the dev_t for the device, if
2612  * the dev_t is not 0,0.
2613  * If a pointer to a parent struct device is passed in, the newly created
2614  * struct device will be a child of that device in sysfs.
2615  * The pointer to the struct device will be returned from the call.
2616  * Any further sysfs files that might be required can be created using this
2617  * pointer.
2618  *
2619  * Returns &struct device pointer on success, or ERR_PTR() on error.
2620  *
2621  * Note: the struct class passed to this function must have previously
2622  * been created with a call to class_create().
2623  */
2624 struct device *device_create(struct class *class, struct device *parent,
2625 			     dev_t devt, void *drvdata, const char *fmt, ...)
2626 {
2627 	va_list vargs;
2628 	struct device *dev;
2629 
2630 	va_start(vargs, fmt);
2631 	dev = device_create_vargs(class, parent, devt, drvdata, fmt, vargs);
2632 	va_end(vargs);
2633 	return dev;
2634 }
2635 EXPORT_SYMBOL_GPL(device_create);
2636 
2637 /**
2638  * device_create_with_groups - creates a device and registers it with sysfs
2639  * @class: pointer to the struct class that this device should be registered to
2640  * @parent: pointer to the parent struct device of this new device, if any
2641  * @devt: the dev_t for the char device to be added
2642  * @drvdata: the data to be added to the device for callbacks
2643  * @groups: NULL-terminated list of attribute groups to be created
2644  * @fmt: string for the device's name
2645  *
2646  * This function can be used by char device classes.  A struct device
2647  * will be created in sysfs, registered to the specified class.
2648  * Additional attributes specified in the groups parameter will also
2649  * be created automatically.
2650  *
2651  * A "dev" file will be created, showing the dev_t for the device, if
2652  * the dev_t is not 0,0.
2653  * If a pointer to a parent struct device is passed in, the newly created
2654  * struct device will be a child of that device in sysfs.
2655  * The pointer to the struct device will be returned from the call.
2656  * Any further sysfs files that might be required can be created using this
2657  * pointer.
2658  *
2659  * Returns &struct device pointer on success, or ERR_PTR() on error.
2660  *
2661  * Note: the struct class passed to this function must have previously
2662  * been created with a call to class_create().
2663  */
2664 struct device *device_create_with_groups(struct class *class,
2665 					 struct device *parent, dev_t devt,
2666 					 void *drvdata,
2667 					 const struct attribute_group **groups,
2668 					 const char *fmt, ...)
2669 {
2670 	va_list vargs;
2671 	struct device *dev;
2672 
2673 	va_start(vargs, fmt);
2674 	dev = device_create_groups_vargs(class, parent, devt, drvdata, groups,
2675 					 fmt, vargs);
2676 	va_end(vargs);
2677 	return dev;
2678 }
2679 EXPORT_SYMBOL_GPL(device_create_with_groups);
2680 
2681 static int __match_devt(struct device *dev, const void *data)
2682 {
2683 	const dev_t *devt = data;
2684 
2685 	return dev->devt == *devt;
2686 }
2687 
2688 /**
2689  * device_destroy - removes a device that was created with device_create()
2690  * @class: pointer to the struct class that this device was registered with
2691  * @devt: the dev_t of the device that was previously registered
2692  *
2693  * This call unregisters and cleans up a device that was created with a
2694  * call to device_create().
2695  */
2696 void device_destroy(struct class *class, dev_t devt)
2697 {
2698 	struct device *dev;
2699 
2700 	dev = class_find_device(class, NULL, &devt, __match_devt);
2701 	if (dev) {
2702 		put_device(dev);
2703 		device_unregister(dev);
2704 	}
2705 }
2706 EXPORT_SYMBOL_GPL(device_destroy);
2707 
2708 /**
2709  * device_rename - renames a device
2710  * @dev: the pointer to the struct device to be renamed
2711  * @new_name: the new name of the device
2712  *
2713  * It is the responsibility of the caller to provide mutual
2714  * exclusion between two different calls of device_rename
2715  * on the same device to ensure that new_name is valid and
2716  * won't conflict with other devices.
2717  *
2718  * Note: Don't call this function.  Currently, the networking layer calls this
2719  * function, but that will change.  The following text from Kay Sievers offers
2720  * some insight:
2721  *
2722  * Renaming devices is racy at many levels, symlinks and other stuff are not
2723  * replaced atomically, and you get a "move" uevent, but it's not easy to
2724  * connect the event to the old and new device. Device nodes are not renamed at
2725  * all, there isn't even support for that in the kernel now.
2726  *
2727  * In the meantime, during renaming, your target name might be taken by another
2728  * driver, creating conflicts. Or the old name is taken directly after you
2729  * renamed it -- then you get events for the same DEVPATH, before you even see
2730  * the "move" event. It's just a mess, and nothing new should ever rely on
2731  * kernel device renaming. Besides that, it's not even implemented now for
2732  * other things than (driver-core wise very simple) network devices.
2733  *
2734  * We are currently about to change network renaming in udev to completely
2735  * disallow renaming of devices in the same namespace as the kernel uses,
2736  * because we can't solve the problems properly, that arise with swapping names
2737  * of multiple interfaces without races. Means, renaming of eth[0-9]* will only
2738  * be allowed to some other name than eth[0-9]*, for the aforementioned
2739  * reasons.
2740  *
2741  * Make up a "real" name in the driver before you register anything, or add
2742  * some other attributes for userspace to find the device, or use udev to add
2743  * symlinks -- but never rename kernel devices later, it's a complete mess. We
2744  * don't even want to get into that and try to implement the missing pieces in
2745  * the core. We really have other pieces to fix in the driver core mess. :)
2746  */
2747 int device_rename(struct device *dev, const char *new_name)
2748 {
2749 	struct kobject *kobj = &dev->kobj;
2750 	char *old_device_name = NULL;
2751 	int error;
2752 
2753 	dev = get_device(dev);
2754 	if (!dev)
2755 		return -EINVAL;
2756 
2757 	dev_dbg(dev, "renaming to %s\n", new_name);
2758 
2759 	old_device_name = kstrdup(dev_name(dev), GFP_KERNEL);
2760 	if (!old_device_name) {
2761 		error = -ENOMEM;
2762 		goto out;
2763 	}
2764 
2765 	if (dev->class) {
2766 		error = sysfs_rename_link_ns(&dev->class->p->subsys.kobj,
2767 					     kobj, old_device_name,
2768 					     new_name, kobject_namespace(kobj));
2769 		if (error)
2770 			goto out;
2771 	}
2772 
2773 	error = kobject_rename(kobj, new_name);
2774 	if (error)
2775 		goto out;
2776 
2777 out:
2778 	put_device(dev);
2779 
2780 	kfree(old_device_name);
2781 
2782 	return error;
2783 }
2784 EXPORT_SYMBOL_GPL(device_rename);
2785 
2786 static int device_move_class_links(struct device *dev,
2787 				   struct device *old_parent,
2788 				   struct device *new_parent)
2789 {
2790 	int error = 0;
2791 
2792 	if (old_parent)
2793 		sysfs_remove_link(&dev->kobj, "device");
2794 	if (new_parent)
2795 		error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
2796 					  "device");
2797 	return error;
2798 }
2799 
2800 /**
2801  * device_move - moves a device to a new parent
2802  * @dev: the pointer to the struct device to be moved
2803  * @new_parent: the new parent of the device (can be NULL)
2804  * @dpm_order: how to reorder the dpm_list
2805  */
2806 int device_move(struct device *dev, struct device *new_parent,
2807 		enum dpm_order dpm_order)
2808 {
2809 	int error;
2810 	struct device *old_parent;
2811 	struct kobject *new_parent_kobj;
2812 
2813 	dev = get_device(dev);
2814 	if (!dev)
2815 		return -EINVAL;
2816 
2817 	device_pm_lock();
2818 	new_parent = get_device(new_parent);
2819 	new_parent_kobj = get_device_parent(dev, new_parent);
2820 	if (IS_ERR(new_parent_kobj)) {
2821 		error = PTR_ERR(new_parent_kobj);
2822 		put_device(new_parent);
2823 		goto out;
2824 	}
2825 
2826 	pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev),
2827 		 __func__, new_parent ? dev_name(new_parent) : "<NULL>");
2828 	error = kobject_move(&dev->kobj, new_parent_kobj);
2829 	if (error) {
2830 		cleanup_glue_dir(dev, new_parent_kobj);
2831 		put_device(new_parent);
2832 		goto out;
2833 	}
2834 	old_parent = dev->parent;
2835 	dev->parent = new_parent;
2836 	if (old_parent)
2837 		klist_remove(&dev->p->knode_parent);
2838 	if (new_parent) {
2839 		klist_add_tail(&dev->p->knode_parent,
2840 			       &new_parent->p->klist_children);
2841 		set_dev_node(dev, dev_to_node(new_parent));
2842 	}
2843 
2844 	if (dev->class) {
2845 		error = device_move_class_links(dev, old_parent, new_parent);
2846 		if (error) {
2847 			/* We ignore errors on cleanup since we're hosed anyway... */
2848 			device_move_class_links(dev, new_parent, old_parent);
2849 			if (!kobject_move(&dev->kobj, &old_parent->kobj)) {
2850 				if (new_parent)
2851 					klist_remove(&dev->p->knode_parent);
2852 				dev->parent = old_parent;
2853 				if (old_parent) {
2854 					klist_add_tail(&dev->p->knode_parent,
2855 						       &old_parent->p->klist_children);
2856 					set_dev_node(dev, dev_to_node(old_parent));
2857 				}
2858 			}
2859 			cleanup_glue_dir(dev, new_parent_kobj);
2860 			put_device(new_parent);
2861 			goto out;
2862 		}
2863 	}
2864 	switch (dpm_order) {
2865 	case DPM_ORDER_NONE:
2866 		break;
2867 	case DPM_ORDER_DEV_AFTER_PARENT:
2868 		device_pm_move_after(dev, new_parent);
2869 		devices_kset_move_after(dev, new_parent);
2870 		break;
2871 	case DPM_ORDER_PARENT_BEFORE_DEV:
2872 		device_pm_move_before(new_parent, dev);
2873 		devices_kset_move_before(new_parent, dev);
2874 		break;
2875 	case DPM_ORDER_DEV_LAST:
2876 		device_pm_move_last(dev);
2877 		devices_kset_move_last(dev);
2878 		break;
2879 	}
2880 
2881 	put_device(old_parent);
2882 out:
2883 	device_pm_unlock();
2884 	put_device(dev);
2885 	return error;
2886 }
2887 EXPORT_SYMBOL_GPL(device_move);
2888 
2889 /**
2890  * device_shutdown - call ->shutdown() on each device to shutdown.
2891  */
2892 void device_shutdown(void)
2893 {
2894 	struct device *dev, *parent;
2895 
2896 	wait_for_device_probe();
2897 	device_block_probing();
2898 
2899 	spin_lock(&devices_kset->list_lock);
2900 	/*
2901 	 * Walk the devices list backward, shutting down each in turn.
2902 	 * Beware that device unplug events may also start pulling
2903 	 * devices offline, even as the system is shutting down.
2904 	 */
2905 	while (!list_empty(&devices_kset->list)) {
2906 		dev = list_entry(devices_kset->list.prev, struct device,
2907 				kobj.entry);
2908 
2909 		/*
2910 		 * hold reference count of device's parent to
2911 		 * prevent it from being freed because parent's
2912 		 * lock is to be held
2913 		 */
2914 		parent = get_device(dev->parent);
2915 		get_device(dev);
2916 		/*
2917 		 * Make sure the device is off the kset list, in the
2918 		 * event that dev->*->shutdown() doesn't remove it.
2919 		 */
2920 		list_del_init(&dev->kobj.entry);
2921 		spin_unlock(&devices_kset->list_lock);
2922 
2923 		/* hold lock to avoid race with probe/release */
2924 		if (parent)
2925 			device_lock(parent);
2926 		device_lock(dev);
2927 
2928 		/* Don't allow any more runtime suspends */
2929 		pm_runtime_get_noresume(dev);
2930 		pm_runtime_barrier(dev);
2931 
2932 		if (dev->class && dev->class->shutdown_pre) {
2933 			if (initcall_debug)
2934 				dev_info(dev, "shutdown_pre\n");
2935 			dev->class->shutdown_pre(dev);
2936 		}
2937 		if (dev->bus && dev->bus->shutdown) {
2938 			if (initcall_debug)
2939 				dev_info(dev, "shutdown\n");
2940 			dev->bus->shutdown(dev);
2941 		} else if (dev->driver && dev->driver->shutdown) {
2942 			if (initcall_debug)
2943 				dev_info(dev, "shutdown\n");
2944 			dev->driver->shutdown(dev);
2945 		}
2946 
2947 		device_unlock(dev);
2948 		if (parent)
2949 			device_unlock(parent);
2950 
2951 		put_device(dev);
2952 		put_device(parent);
2953 
2954 		spin_lock(&devices_kset->list_lock);
2955 	}
2956 	spin_unlock(&devices_kset->list_lock);
2957 }
2958 
2959 /*
2960  * Device logging functions
2961  */
2962 
2963 #ifdef CONFIG_PRINTK
2964 static int
2965 create_syslog_header(const struct device *dev, char *hdr, size_t hdrlen)
2966 {
2967 	const char *subsys;
2968 	size_t pos = 0;
2969 
2970 	if (dev->class)
2971 		subsys = dev->class->name;
2972 	else if (dev->bus)
2973 		subsys = dev->bus->name;
2974 	else
2975 		return 0;
2976 
2977 	pos += snprintf(hdr + pos, hdrlen - pos, "SUBSYSTEM=%s", subsys);
2978 	if (pos >= hdrlen)
2979 		goto overflow;
2980 
2981 	/*
2982 	 * Add device identifier DEVICE=:
2983 	 *   b12:8         block dev_t
2984 	 *   c127:3        char dev_t
2985 	 *   n8            netdev ifindex
2986 	 *   +sound:card0  subsystem:devname
2987 	 */
2988 	if (MAJOR(dev->devt)) {
2989 		char c;
2990 
2991 		if (strcmp(subsys, "block") == 0)
2992 			c = 'b';
2993 		else
2994 			c = 'c';
2995 		pos++;
2996 		pos += snprintf(hdr + pos, hdrlen - pos,
2997 				"DEVICE=%c%u:%u",
2998 				c, MAJOR(dev->devt), MINOR(dev->devt));
2999 	} else if (strcmp(subsys, "net") == 0) {
3000 		struct net_device *net = to_net_dev(dev);
3001 
3002 		pos++;
3003 		pos += snprintf(hdr + pos, hdrlen - pos,
3004 				"DEVICE=n%u", net->ifindex);
3005 	} else {
3006 		pos++;
3007 		pos += snprintf(hdr + pos, hdrlen - pos,
3008 				"DEVICE=+%s:%s", subsys, dev_name(dev));
3009 	}
3010 
3011 	if (pos >= hdrlen)
3012 		goto overflow;
3013 
3014 	return pos;
3015 
3016 overflow:
3017 	dev_WARN(dev, "device/subsystem name too long");
3018 	return 0;
3019 }
3020 
3021 int dev_vprintk_emit(int level, const struct device *dev,
3022 		     const char *fmt, va_list args)
3023 {
3024 	char hdr[128];
3025 	size_t hdrlen;
3026 
3027 	hdrlen = create_syslog_header(dev, hdr, sizeof(hdr));
3028 
3029 	return vprintk_emit(0, level, hdrlen ? hdr : NULL, hdrlen, fmt, args);
3030 }
3031 EXPORT_SYMBOL(dev_vprintk_emit);
3032 
3033 int dev_printk_emit(int level, const struct device *dev, const char *fmt, ...)
3034 {
3035 	va_list args;
3036 	int r;
3037 
3038 	va_start(args, fmt);
3039 
3040 	r = dev_vprintk_emit(level, dev, fmt, args);
3041 
3042 	va_end(args);
3043 
3044 	return r;
3045 }
3046 EXPORT_SYMBOL(dev_printk_emit);
3047 
3048 static void __dev_printk(const char *level, const struct device *dev,
3049 			struct va_format *vaf)
3050 {
3051 	if (dev)
3052 		dev_printk_emit(level[1] - '0', dev, "%s %s: %pV",
3053 				dev_driver_string(dev), dev_name(dev), vaf);
3054 	else
3055 		printk("%s(NULL device *): %pV", level, vaf);
3056 }
3057 
3058 void dev_printk(const char *level, const struct device *dev,
3059 		const char *fmt, ...)
3060 {
3061 	struct va_format vaf;
3062 	va_list args;
3063 
3064 	va_start(args, fmt);
3065 
3066 	vaf.fmt = fmt;
3067 	vaf.va = &args;
3068 
3069 	__dev_printk(level, dev, &vaf);
3070 
3071 	va_end(args);
3072 }
3073 EXPORT_SYMBOL(dev_printk);
3074 
3075 #define define_dev_printk_level(func, kern_level)		\
3076 void func(const struct device *dev, const char *fmt, ...)	\
3077 {								\
3078 	struct va_format vaf;					\
3079 	va_list args;						\
3080 								\
3081 	va_start(args, fmt);					\
3082 								\
3083 	vaf.fmt = fmt;						\
3084 	vaf.va = &args;						\
3085 								\
3086 	__dev_printk(kern_level, dev, &vaf);			\
3087 								\
3088 	va_end(args);						\
3089 }								\
3090 EXPORT_SYMBOL(func);
3091 
3092 define_dev_printk_level(_dev_emerg, KERN_EMERG);
3093 define_dev_printk_level(_dev_alert, KERN_ALERT);
3094 define_dev_printk_level(_dev_crit, KERN_CRIT);
3095 define_dev_printk_level(_dev_err, KERN_ERR);
3096 define_dev_printk_level(_dev_warn, KERN_WARNING);
3097 define_dev_printk_level(_dev_notice, KERN_NOTICE);
3098 define_dev_printk_level(_dev_info, KERN_INFO);
3099 
3100 #endif
3101 
3102 static inline bool fwnode_is_primary(struct fwnode_handle *fwnode)
3103 {
3104 	return fwnode && !IS_ERR(fwnode->secondary);
3105 }
3106 
3107 /**
3108  * set_primary_fwnode - Change the primary firmware node of a given device.
3109  * @dev: Device to handle.
3110  * @fwnode: New primary firmware node of the device.
3111  *
3112  * Set the device's firmware node pointer to @fwnode, but if a secondary
3113  * firmware node of the device is present, preserve it.
3114  */
3115 void set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
3116 {
3117 	if (fwnode) {
3118 		struct fwnode_handle *fn = dev->fwnode;
3119 
3120 		if (fwnode_is_primary(fn))
3121 			fn = fn->secondary;
3122 
3123 		if (fn) {
3124 			WARN_ON(fwnode->secondary);
3125 			fwnode->secondary = fn;
3126 		}
3127 		dev->fwnode = fwnode;
3128 	} else {
3129 		dev->fwnode = fwnode_is_primary(dev->fwnode) ?
3130 			dev->fwnode->secondary : NULL;
3131 	}
3132 }
3133 EXPORT_SYMBOL_GPL(set_primary_fwnode);
3134 
3135 /**
3136  * set_secondary_fwnode - Change the secondary firmware node of a given device.
3137  * @dev: Device to handle.
3138  * @fwnode: New secondary firmware node of the device.
3139  *
3140  * If a primary firmware node of the device is present, set its secondary
3141  * pointer to @fwnode.  Otherwise, set the device's firmware node pointer to
3142  * @fwnode.
3143  */
3144 void set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
3145 {
3146 	if (fwnode)
3147 		fwnode->secondary = ERR_PTR(-ENODEV);
3148 
3149 	if (fwnode_is_primary(dev->fwnode))
3150 		dev->fwnode->secondary = fwnode;
3151 	else
3152 		dev->fwnode = fwnode;
3153 }
3154 
3155 /**
3156  * device_set_of_node_from_dev - reuse device-tree node of another device
3157  * @dev: device whose device-tree node is being set
3158  * @dev2: device whose device-tree node is being reused
3159  *
3160  * Takes another reference to the new device-tree node after first dropping
3161  * any reference held to the old node.
3162  */
3163 void device_set_of_node_from_dev(struct device *dev, const struct device *dev2)
3164 {
3165 	of_node_put(dev->of_node);
3166 	dev->of_node = of_node_get(dev2->of_node);
3167 	dev->of_node_reused = true;
3168 }
3169 EXPORT_SYMBOL_GPL(device_set_of_node_from_dev);
3170