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