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