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