1 // SPDX-License-Identifier: GPL-2.0
3 * drivers/base/core.c - core driver model code (device registration, etc)
5 * Copyright (c) 2002-3 Patrick Mochel
6 * Copyright (c) 2002-3 Open Source Development Labs
7 * Copyright (c) 2006 Greg Kroah-Hartman <gregkh@suse.de>
8 * Copyright (c) 2006 Novell, Inc.
11 #include <linux/acpi.h>
12 #include <linux/cpufreq.h>
13 #include <linux/device.h>
14 #include <linux/err.h>
15 #include <linux/fwnode.h>
16 #include <linux/init.h>
17 #include <linux/module.h>
18 #include <linux/slab.h>
19 #include <linux/string.h>
20 #include <linux/kdev_t.h>
21 #include <linux/notifier.h>
23 #include <linux/of_device.h>
24 #include <linux/genhd.h>
25 #include <linux/mutex.h>
26 #include <linux/pm_runtime.h>
27 #include <linux/netdevice.h>
28 #include <linux/sched/signal.h>
29 #include <linux/sched/mm.h>
30 #include <linux/sysfs.h>
33 #include "power/power.h"
35 #ifdef CONFIG_SYSFS_DEPRECATED
36 #ifdef CONFIG_SYSFS_DEPRECATED_V2
37 long sysfs_deprecated = 1;
39 long sysfs_deprecated = 0;
41 static int __init sysfs_deprecated_setup(char *arg)
43 return kstrtol(arg, 10, &sysfs_deprecated);
45 early_param("sysfs.deprecated", sysfs_deprecated_setup);
48 /* Device links support. */
49 static LIST_HEAD(wait_for_suppliers);
50 static DEFINE_MUTEX(wfs_lock);
51 static LIST_HEAD(deferred_sync);
52 static unsigned int defer_sync_state_count = 1;
53 static unsigned int defer_fw_devlink_count;
54 static LIST_HEAD(deferred_fw_devlink);
55 static DEFINE_MUTEX(defer_fw_devlink_lock);
56 static bool fw_devlink_is_permissive(void);
59 static DEFINE_MUTEX(device_links_lock);
60 DEFINE_STATIC_SRCU(device_links_srcu);
62 static inline void device_links_write_lock(void)
64 mutex_lock(&device_links_lock);
67 static inline void device_links_write_unlock(void)
69 mutex_unlock(&device_links_lock);
72 int device_links_read_lock(void) __acquires(&device_links_srcu)
74 return srcu_read_lock(&device_links_srcu);
77 void device_links_read_unlock(int idx) __releases(&device_links_srcu)
79 srcu_read_unlock(&device_links_srcu, idx);
82 int device_links_read_lock_held(void)
84 return srcu_read_lock_held(&device_links_srcu);
87 static void device_link_synchronize_removal(void)
89 synchronize_srcu(&device_links_srcu);
91 #else /* !CONFIG_SRCU */
92 static DECLARE_RWSEM(device_links_lock);
94 static inline void device_links_write_lock(void)
96 down_write(&device_links_lock);
99 static inline void device_links_write_unlock(void)
101 up_write(&device_links_lock);
104 int device_links_read_lock(void)
106 down_read(&device_links_lock);
110 void device_links_read_unlock(int not_used)
112 up_read(&device_links_lock);
115 #ifdef CONFIG_DEBUG_LOCK_ALLOC
116 int device_links_read_lock_held(void)
118 return lockdep_is_held(&device_links_lock);
122 static inline void device_link_synchronize_removal(void)
125 #endif /* !CONFIG_SRCU */
127 static bool device_is_ancestor(struct device *dev, struct device *target)
129 while (target->parent) {
130 target = target->parent;
138 * device_is_dependent - Check if one device depends on another one
139 * @dev: Device to check dependencies for.
140 * @target: Device to check against.
142 * Check if @target depends on @dev or any device dependent on it (its child or
143 * its consumer etc). Return 1 if that is the case or 0 otherwise.
145 int device_is_dependent(struct device *dev, void *target)
147 struct device_link *link;
151 * The "ancestors" check is needed to catch the case when the target
152 * device has not been completely initialized yet and it is still
153 * missing from the list of children of its parent device.
155 if (dev == target || device_is_ancestor(dev, target))
158 ret = device_for_each_child(dev, target, device_is_dependent);
162 list_for_each_entry(link, &dev->links.consumers, s_node) {
163 if (link->flags == (DL_FLAG_SYNC_STATE_ONLY | DL_FLAG_MANAGED))
166 if (link->consumer == target)
169 ret = device_is_dependent(link->consumer, target);
176 static void device_link_init_status(struct device_link *link,
177 struct device *consumer,
178 struct device *supplier)
180 switch (supplier->links.status) {
182 switch (consumer->links.status) {
185 * A consumer driver can create a link to a supplier
186 * that has not completed its probing yet as long as it
187 * knows that the supplier is already functional (for
188 * example, it has just acquired some resources from the
191 link->status = DL_STATE_CONSUMER_PROBE;
194 link->status = DL_STATE_DORMANT;
198 case DL_DEV_DRIVER_BOUND:
199 switch (consumer->links.status) {
201 link->status = DL_STATE_CONSUMER_PROBE;
203 case DL_DEV_DRIVER_BOUND:
204 link->status = DL_STATE_ACTIVE;
207 link->status = DL_STATE_AVAILABLE;
211 case DL_DEV_UNBINDING:
212 link->status = DL_STATE_SUPPLIER_UNBIND;
215 link->status = DL_STATE_DORMANT;
220 static int device_reorder_to_tail(struct device *dev, void *not_used)
222 struct device_link *link;
225 * Devices that have not been registered yet will be put to the ends
226 * of the lists during the registration, so skip them here.
228 if (device_is_registered(dev))
229 devices_kset_move_last(dev);
231 if (device_pm_initialized(dev))
232 device_pm_move_last(dev);
234 device_for_each_child(dev, NULL, device_reorder_to_tail);
235 list_for_each_entry(link, &dev->links.consumers, s_node) {
236 if (link->flags == (DL_FLAG_SYNC_STATE_ONLY | DL_FLAG_MANAGED))
238 device_reorder_to_tail(link->consumer, NULL);
245 * device_pm_move_to_tail - Move set of devices to the end of device lists
246 * @dev: Device to move
248 * This is a device_reorder_to_tail() wrapper taking the requisite locks.
250 * It moves the @dev along with all of its children and all of its consumers
251 * to the ends of the device_kset and dpm_list, recursively.
253 void device_pm_move_to_tail(struct device *dev)
257 idx = device_links_read_lock();
259 device_reorder_to_tail(dev, NULL);
261 device_links_read_unlock(idx);
264 #define to_devlink(dev) container_of((dev), struct device_link, link_dev)
266 static ssize_t status_show(struct device *dev,
267 struct device_attribute *attr, char *buf)
271 switch (to_devlink(dev)->status) {
273 output = "not tracked";
275 case DL_STATE_DORMANT:
278 case DL_STATE_AVAILABLE:
279 output = "available";
281 case DL_STATE_CONSUMER_PROBE:
282 output = "consumer probing";
284 case DL_STATE_ACTIVE:
287 case DL_STATE_SUPPLIER_UNBIND:
288 output = "supplier unbinding";
295 return sysfs_emit(buf, "%s\n", output);
297 static DEVICE_ATTR_RO(status);
299 static ssize_t auto_remove_on_show(struct device *dev,
300 struct device_attribute *attr, char *buf)
302 struct device_link *link = to_devlink(dev);
305 if (link->flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
306 output = "supplier unbind";
307 else if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER)
308 output = "consumer unbind";
312 return sysfs_emit(buf, "%s\n", output);
314 static DEVICE_ATTR_RO(auto_remove_on);
316 static ssize_t runtime_pm_show(struct device *dev,
317 struct device_attribute *attr, char *buf)
319 struct device_link *link = to_devlink(dev);
321 return sysfs_emit(buf, "%d\n", !!(link->flags & DL_FLAG_PM_RUNTIME));
323 static DEVICE_ATTR_RO(runtime_pm);
325 static ssize_t sync_state_only_show(struct device *dev,
326 struct device_attribute *attr, char *buf)
328 struct device_link *link = to_devlink(dev);
330 return sysfs_emit(buf, "%d\n",
331 !!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
333 static DEVICE_ATTR_RO(sync_state_only);
335 static struct attribute *devlink_attrs[] = {
336 &dev_attr_status.attr,
337 &dev_attr_auto_remove_on.attr,
338 &dev_attr_runtime_pm.attr,
339 &dev_attr_sync_state_only.attr,
342 ATTRIBUTE_GROUPS(devlink);
344 static void device_link_release_fn(struct work_struct *work)
346 struct device_link *link = container_of(work, struct device_link, rm_work);
348 /* Ensure that all references to the link object have been dropped. */
349 device_link_synchronize_removal();
351 pm_runtime_release_supplier(link);
352 pm_request_idle(link->supplier);
354 put_device(link->consumer);
355 put_device(link->supplier);
359 static void devlink_dev_release(struct device *dev)
361 struct device_link *link = to_devlink(dev);
363 INIT_WORK(&link->rm_work, device_link_release_fn);
365 * It may take a while to complete this work because of the SRCU
366 * synchronization in device_link_release_fn() and if the consumer or
367 * supplier devices get deleted when it runs, so put it into the "long"
370 queue_work(system_long_wq, &link->rm_work);
373 static struct class devlink_class = {
375 .owner = THIS_MODULE,
376 .dev_groups = devlink_groups,
377 .dev_release = devlink_dev_release,
380 static int devlink_add_symlinks(struct device *dev,
381 struct class_interface *class_intf)
385 struct device_link *link = to_devlink(dev);
386 struct device *sup = link->supplier;
387 struct device *con = link->consumer;
390 len = max(strlen(dev_bus_name(sup)) + strlen(dev_name(sup)),
391 strlen(dev_bus_name(con)) + strlen(dev_name(con)));
393 len += strlen("supplier:") + 1;
394 buf = kzalloc(len, GFP_KERNEL);
398 ret = sysfs_create_link(&link->link_dev.kobj, &sup->kobj, "supplier");
402 ret = sysfs_create_link(&link->link_dev.kobj, &con->kobj, "consumer");
406 snprintf(buf, len, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
407 ret = sysfs_create_link(&sup->kobj, &link->link_dev.kobj, buf);
411 snprintf(buf, len, "supplier:%s:%s", dev_bus_name(sup), dev_name(sup));
412 ret = sysfs_create_link(&con->kobj, &link->link_dev.kobj, buf);
419 snprintf(buf, len, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
420 sysfs_remove_link(&sup->kobj, buf);
422 sysfs_remove_link(&link->link_dev.kobj, "consumer");
424 sysfs_remove_link(&link->link_dev.kobj, "supplier");
430 static void devlink_remove_symlinks(struct device *dev,
431 struct class_interface *class_intf)
433 struct device_link *link = to_devlink(dev);
435 struct device *sup = link->supplier;
436 struct device *con = link->consumer;
439 sysfs_remove_link(&link->link_dev.kobj, "consumer");
440 sysfs_remove_link(&link->link_dev.kobj, "supplier");
442 len = max(strlen(dev_bus_name(sup)) + strlen(dev_name(sup)),
443 strlen(dev_bus_name(con)) + strlen(dev_name(con)));
445 len += strlen("supplier:") + 1;
446 buf = kzalloc(len, GFP_KERNEL);
448 WARN(1, "Unable to properly free device link symlinks!\n");
452 if (device_is_registered(con)) {
453 snprintf(buf, len, "supplier:%s:%s", dev_bus_name(sup), dev_name(sup));
454 sysfs_remove_link(&con->kobj, buf);
456 snprintf(buf, len, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
457 sysfs_remove_link(&sup->kobj, buf);
461 static struct class_interface devlink_class_intf = {
462 .class = &devlink_class,
463 .add_dev = devlink_add_symlinks,
464 .remove_dev = devlink_remove_symlinks,
467 static int __init devlink_class_init(void)
471 ret = class_register(&devlink_class);
475 ret = class_interface_register(&devlink_class_intf);
477 class_unregister(&devlink_class);
481 postcore_initcall(devlink_class_init);
483 #define DL_MANAGED_LINK_FLAGS (DL_FLAG_AUTOREMOVE_CONSUMER | \
484 DL_FLAG_AUTOREMOVE_SUPPLIER | \
485 DL_FLAG_AUTOPROBE_CONSUMER | \
486 DL_FLAG_SYNC_STATE_ONLY)
488 #define DL_ADD_VALID_FLAGS (DL_MANAGED_LINK_FLAGS | DL_FLAG_STATELESS | \
489 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE)
492 * device_link_add - Create a link between two devices.
493 * @consumer: Consumer end of the link.
494 * @supplier: Supplier end of the link.
495 * @flags: Link flags.
497 * The caller is responsible for the proper synchronization of the link creation
498 * with runtime PM. First, setting the DL_FLAG_PM_RUNTIME flag will cause the
499 * runtime PM framework to take the link into account. Second, if the
500 * DL_FLAG_RPM_ACTIVE flag is set in addition to it, the supplier devices will
501 * be forced into the active metastate and reference-counted upon the creation
502 * of the link. If DL_FLAG_PM_RUNTIME is not set, DL_FLAG_RPM_ACTIVE will be
505 * If DL_FLAG_STATELESS is set in @flags, the caller of this function is
506 * expected to release the link returned by it directly with the help of either
507 * device_link_del() or device_link_remove().
509 * If that flag is not set, however, the caller of this function is handing the
510 * management of the link over to the driver core entirely and its return value
511 * can only be used to check whether or not the link is present. In that case,
512 * the DL_FLAG_AUTOREMOVE_CONSUMER and DL_FLAG_AUTOREMOVE_SUPPLIER device link
513 * flags can be used to indicate to the driver core when the link can be safely
514 * deleted. Namely, setting one of them in @flags indicates to the driver core
515 * that the link is not going to be used (by the given caller of this function)
516 * after unbinding the consumer or supplier driver, respectively, from its
517 * device, so the link can be deleted at that point. If none of them is set,
518 * the link will be maintained until one of the devices pointed to by it (either
519 * the consumer or the supplier) is unregistered.
521 * Also, if DL_FLAG_STATELESS, DL_FLAG_AUTOREMOVE_CONSUMER and
522 * DL_FLAG_AUTOREMOVE_SUPPLIER are not set in @flags (that is, a persistent
523 * managed device link is being added), the DL_FLAG_AUTOPROBE_CONSUMER flag can
524 * be used to request the driver core to automaticall probe for a consmer
525 * driver after successfully binding a driver to the supplier device.
527 * The combination of DL_FLAG_STATELESS and one of DL_FLAG_AUTOREMOVE_CONSUMER,
528 * DL_FLAG_AUTOREMOVE_SUPPLIER, or DL_FLAG_AUTOPROBE_CONSUMER set in @flags at
529 * the same time is invalid and will cause NULL to be returned upfront.
530 * However, if a device link between the given @consumer and @supplier pair
531 * exists already when this function is called for them, the existing link will
532 * be returned regardless of its current type and status (the link's flags may
533 * be modified then). The caller of this function is then expected to treat
534 * the link as though it has just been created, so (in particular) if
535 * DL_FLAG_STATELESS was passed in @flags, the link needs to be released
536 * explicitly when not needed any more (as stated above).
538 * A side effect of the link creation is re-ordering of dpm_list and the
539 * devices_kset list by moving the consumer device and all devices depending
540 * on it to the ends of these lists (that does not happen to devices that have
541 * not been registered when this function is called).
543 * The supplier device is required to be registered when this function is called
544 * and NULL will be returned if that is not the case. The consumer device need
545 * not be registered, however.
547 struct device_link *device_link_add(struct device *consumer,
548 struct device *supplier, u32 flags)
550 struct device_link *link;
552 if (!consumer || !supplier || consumer == supplier ||
553 flags & ~DL_ADD_VALID_FLAGS ||
554 (flags & DL_FLAG_STATELESS && flags & DL_MANAGED_LINK_FLAGS) ||
555 (flags & DL_FLAG_SYNC_STATE_ONLY &&
556 flags != DL_FLAG_SYNC_STATE_ONLY) ||
557 (flags & DL_FLAG_AUTOPROBE_CONSUMER &&
558 flags & (DL_FLAG_AUTOREMOVE_CONSUMER |
559 DL_FLAG_AUTOREMOVE_SUPPLIER)))
562 if (flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) {
563 if (pm_runtime_get_sync(supplier) < 0) {
564 pm_runtime_put_noidle(supplier);
569 if (!(flags & DL_FLAG_STATELESS))
570 flags |= DL_FLAG_MANAGED;
572 device_links_write_lock();
576 * If the supplier has not been fully registered yet or there is a
577 * reverse (non-SYNC_STATE_ONLY) dependency between the consumer and
578 * the supplier already in the graph, return NULL. If the link is a
579 * SYNC_STATE_ONLY link, we don't check for reverse dependencies
580 * because it only affects sync_state() callbacks.
582 if (!device_pm_initialized(supplier)
583 || (!(flags & DL_FLAG_SYNC_STATE_ONLY) &&
584 device_is_dependent(consumer, supplier))) {
590 * DL_FLAG_AUTOREMOVE_SUPPLIER indicates that the link will be needed
591 * longer than for DL_FLAG_AUTOREMOVE_CONSUMER and setting them both
592 * together doesn't make sense, so prefer DL_FLAG_AUTOREMOVE_SUPPLIER.
594 if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
595 flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
597 list_for_each_entry(link, &supplier->links.consumers, s_node) {
598 if (link->consumer != consumer)
601 if (flags & DL_FLAG_PM_RUNTIME) {
602 if (!(link->flags & DL_FLAG_PM_RUNTIME)) {
603 pm_runtime_new_link(consumer);
604 link->flags |= DL_FLAG_PM_RUNTIME;
606 if (flags & DL_FLAG_RPM_ACTIVE)
607 refcount_inc(&link->rpm_active);
610 if (flags & DL_FLAG_STATELESS) {
611 kref_get(&link->kref);
612 if (link->flags & DL_FLAG_SYNC_STATE_ONLY &&
613 !(link->flags & DL_FLAG_STATELESS)) {
614 link->flags |= DL_FLAG_STATELESS;
617 link->flags |= DL_FLAG_STATELESS;
623 * If the life time of the link following from the new flags is
624 * longer than indicated by the flags of the existing link,
625 * update the existing link to stay around longer.
627 if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER) {
628 if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER) {
629 link->flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
630 link->flags |= DL_FLAG_AUTOREMOVE_SUPPLIER;
632 } else if (!(flags & DL_FLAG_AUTOREMOVE_CONSUMER)) {
633 link->flags &= ~(DL_FLAG_AUTOREMOVE_CONSUMER |
634 DL_FLAG_AUTOREMOVE_SUPPLIER);
636 if (!(link->flags & DL_FLAG_MANAGED)) {
637 kref_get(&link->kref);
638 link->flags |= DL_FLAG_MANAGED;
639 device_link_init_status(link, consumer, supplier);
641 if (link->flags & DL_FLAG_SYNC_STATE_ONLY &&
642 !(flags & DL_FLAG_SYNC_STATE_ONLY)) {
643 link->flags &= ~DL_FLAG_SYNC_STATE_ONLY;
650 link = kzalloc(sizeof(*link), GFP_KERNEL);
654 refcount_set(&link->rpm_active, 1);
656 get_device(supplier);
657 link->supplier = supplier;
658 INIT_LIST_HEAD(&link->s_node);
659 get_device(consumer);
660 link->consumer = consumer;
661 INIT_LIST_HEAD(&link->c_node);
663 kref_init(&link->kref);
665 link->link_dev.class = &devlink_class;
666 device_set_pm_not_required(&link->link_dev);
667 dev_set_name(&link->link_dev, "%s:%s--%s:%s",
668 dev_bus_name(supplier), dev_name(supplier),
669 dev_bus_name(consumer), dev_name(consumer));
670 if (device_register(&link->link_dev)) {
671 put_device(&link->link_dev);
676 if (flags & DL_FLAG_PM_RUNTIME) {
677 if (flags & DL_FLAG_RPM_ACTIVE)
678 refcount_inc(&link->rpm_active);
680 pm_runtime_new_link(consumer);
683 /* Determine the initial link state. */
684 if (flags & DL_FLAG_STATELESS)
685 link->status = DL_STATE_NONE;
687 device_link_init_status(link, consumer, supplier);
690 * Some callers expect the link creation during consumer driver probe to
691 * resume the supplier even without DL_FLAG_RPM_ACTIVE.
693 if (link->status == DL_STATE_CONSUMER_PROBE &&
694 flags & DL_FLAG_PM_RUNTIME)
695 pm_runtime_resume(supplier);
697 list_add_tail_rcu(&link->s_node, &supplier->links.consumers);
698 list_add_tail_rcu(&link->c_node, &consumer->links.suppliers);
700 if (flags & DL_FLAG_SYNC_STATE_ONLY) {
702 "Linked as a sync state only consumer to %s\n",
709 * Move the consumer and all of the devices depending on it to the end
710 * of dpm_list and the devices_kset list.
712 * It is necessary to hold dpm_list locked throughout all that or else
713 * we may end up suspending with a wrong ordering of it.
715 device_reorder_to_tail(consumer, NULL);
717 dev_dbg(consumer, "Linked as a consumer to %s\n", dev_name(supplier));
721 device_links_write_unlock();
723 if ((flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) && !link)
724 pm_runtime_put(supplier);
728 EXPORT_SYMBOL_GPL(device_link_add);
731 * device_link_wait_for_supplier - Add device to wait_for_suppliers list
732 * @consumer: Consumer device
734 * Marks the @consumer device as waiting for suppliers to become available by
735 * adding it to the wait_for_suppliers list. The consumer device will never be
736 * probed until it's removed from the wait_for_suppliers list.
738 * The caller is responsible for adding the links to the supplier devices once
739 * they are available and removing the @consumer device from the
740 * wait_for_suppliers list once links to all the suppliers have been created.
742 * This function is NOT meant to be called from the probe function of the
743 * consumer but rather from code that creates/adds the consumer device.
745 static void device_link_wait_for_supplier(struct device *consumer,
748 mutex_lock(&wfs_lock);
749 list_add_tail(&consumer->links.needs_suppliers, &wait_for_suppliers);
750 consumer->links.need_for_probe = need_for_probe;
751 mutex_unlock(&wfs_lock);
754 static void device_link_wait_for_mandatory_supplier(struct device *consumer)
756 device_link_wait_for_supplier(consumer, true);
759 static void device_link_wait_for_optional_supplier(struct device *consumer)
761 device_link_wait_for_supplier(consumer, false);
765 * device_link_add_missing_supplier_links - Add links from consumer devices to
766 * supplier devices, leaving any
767 * consumer with inactive suppliers on
768 * the wait_for_suppliers list
770 * Loops through all consumers waiting on suppliers and tries to add all their
771 * supplier links. If that succeeds, the consumer device is removed from
772 * wait_for_suppliers list. Otherwise, they are left in the wait_for_suppliers
773 * list. Devices left on the wait_for_suppliers list will not be probed.
775 * The fwnode add_links callback is expected to return 0 if it has found and
776 * added all the supplier links for the consumer device. It should return an
777 * error if it isn't able to do so.
779 * The caller of device_link_wait_for_supplier() is expected to call this once
780 * it's aware of potential suppliers becoming available.
782 static void device_link_add_missing_supplier_links(void)
784 struct device *dev, *tmp;
786 mutex_lock(&wfs_lock);
787 list_for_each_entry_safe(dev, tmp, &wait_for_suppliers,
788 links.needs_suppliers) {
789 int ret = fwnode_call_int_op(dev->fwnode, add_links, dev);
791 list_del_init(&dev->links.needs_suppliers);
792 else if (ret != -ENODEV || fw_devlink_is_permissive())
793 dev->links.need_for_probe = false;
795 mutex_unlock(&wfs_lock);
799 static void __device_link_del(struct kref *kref)
801 struct device_link *link = container_of(kref, struct device_link, kref);
803 dev_dbg(link->consumer, "Dropping the link to %s\n",
804 dev_name(link->supplier));
806 pm_runtime_drop_link(link);
808 list_del_rcu(&link->s_node);
809 list_del_rcu(&link->c_node);
810 device_unregister(&link->link_dev);
812 #else /* !CONFIG_SRCU */
813 static void __device_link_del(struct kref *kref)
815 struct device_link *link = container_of(kref, struct device_link, kref);
817 dev_info(link->consumer, "Dropping the link to %s\n",
818 dev_name(link->supplier));
820 pm_runtime_drop_link(link);
822 list_del(&link->s_node);
823 list_del(&link->c_node);
824 device_unregister(&link->link_dev);
826 #endif /* !CONFIG_SRCU */
828 static void device_link_put_kref(struct device_link *link)
830 if (link->flags & DL_FLAG_STATELESS)
831 kref_put(&link->kref, __device_link_del);
833 WARN(1, "Unable to drop a managed device link reference\n");
837 * device_link_del - Delete a stateless link between two devices.
838 * @link: Device link to delete.
840 * The caller must ensure proper synchronization of this function with runtime
841 * PM. If the link was added multiple times, it needs to be deleted as often.
842 * Care is required for hotplugged devices: Their links are purged on removal
843 * and calling device_link_del() is then no longer allowed.
845 void device_link_del(struct device_link *link)
847 device_links_write_lock();
848 device_link_put_kref(link);
849 device_links_write_unlock();
851 EXPORT_SYMBOL_GPL(device_link_del);
854 * device_link_remove - Delete a stateless link between two devices.
855 * @consumer: Consumer end of the link.
856 * @supplier: Supplier end of the link.
858 * The caller must ensure proper synchronization of this function with runtime
861 void device_link_remove(void *consumer, struct device *supplier)
863 struct device_link *link;
865 if (WARN_ON(consumer == supplier))
868 device_links_write_lock();
870 list_for_each_entry(link, &supplier->links.consumers, s_node) {
871 if (link->consumer == consumer) {
872 device_link_put_kref(link);
877 device_links_write_unlock();
879 EXPORT_SYMBOL_GPL(device_link_remove);
881 static void device_links_missing_supplier(struct device *dev)
883 struct device_link *link;
885 list_for_each_entry(link, &dev->links.suppliers, c_node) {
886 if (link->status != DL_STATE_CONSUMER_PROBE)
889 if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
890 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
892 WARN_ON(!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
893 WRITE_ONCE(link->status, DL_STATE_DORMANT);
899 * device_links_check_suppliers - Check presence of supplier drivers.
900 * @dev: Consumer device.
902 * Check links from this device to any suppliers. Walk the list of the device's
903 * links to suppliers and see if all of them are available. If not, simply
904 * return -EPROBE_DEFER.
906 * We need to guarantee that the supplier will not go away after the check has
907 * been positive here. It only can go away in __device_release_driver() and
908 * that function checks the device's links to consumers. This means we need to
909 * mark the link as "consumer probe in progress" to make the supplier removal
910 * wait for us to complete (or bad things may happen).
912 * Links without the DL_FLAG_MANAGED flag set are ignored.
914 int device_links_check_suppliers(struct device *dev)
916 struct device_link *link;
920 * Device waiting for supplier to become available is not allowed to
923 mutex_lock(&wfs_lock);
924 if (!list_empty(&dev->links.needs_suppliers) &&
925 dev->links.need_for_probe) {
926 mutex_unlock(&wfs_lock);
927 return -EPROBE_DEFER;
929 mutex_unlock(&wfs_lock);
931 device_links_write_lock();
933 list_for_each_entry(link, &dev->links.suppliers, c_node) {
934 if (!(link->flags & DL_FLAG_MANAGED))
937 if (link->status != DL_STATE_AVAILABLE &&
938 !(link->flags & DL_FLAG_SYNC_STATE_ONLY)) {
939 device_links_missing_supplier(dev);
943 WRITE_ONCE(link->status, DL_STATE_CONSUMER_PROBE);
945 dev->links.status = DL_DEV_PROBING;
947 device_links_write_unlock();
952 * __device_links_queue_sync_state - Queue a device for sync_state() callback
953 * @dev: Device to call sync_state() on
954 * @list: List head to queue the @dev on
956 * Queues a device for a sync_state() callback when the device links write lock
957 * isn't held. This allows the sync_state() execution flow to use device links
958 * APIs. The caller must ensure this function is called with
959 * device_links_write_lock() held.
961 * This function does a get_device() to make sure the device is not freed while
964 * So the caller must also ensure that device_links_flush_sync_list() is called
965 * as soon as the caller releases device_links_write_lock(). This is necessary
966 * to make sure the sync_state() is called in a timely fashion and the
967 * put_device() is called on this device.
969 static void __device_links_queue_sync_state(struct device *dev,
970 struct list_head *list)
972 struct device_link *link;
974 if (!dev_has_sync_state(dev))
976 if (dev->state_synced)
979 list_for_each_entry(link, &dev->links.consumers, s_node) {
980 if (!(link->flags & DL_FLAG_MANAGED))
982 if (link->status != DL_STATE_ACTIVE)
987 * Set the flag here to avoid adding the same device to a list more
988 * than once. This can happen if new consumers get added to the device
989 * and probed before the list is flushed.
991 dev->state_synced = true;
993 if (WARN_ON(!list_empty(&dev->links.defer_hook)))
997 list_add_tail(&dev->links.defer_hook, list);
1001 * device_links_flush_sync_list - Call sync_state() on a list of devices
1002 * @list: List of devices to call sync_state() on
1003 * @dont_lock_dev: Device for which lock is already held by the caller
1005 * Calls sync_state() on all the devices that have been queued for it. This
1006 * function is used in conjunction with __device_links_queue_sync_state(). The
1007 * @dont_lock_dev parameter is useful when this function is called from a
1008 * context where a device lock is already held.
1010 static void device_links_flush_sync_list(struct list_head *list,
1011 struct device *dont_lock_dev)
1013 struct device *dev, *tmp;
1015 list_for_each_entry_safe(dev, tmp, list, links.defer_hook) {
1016 list_del_init(&dev->links.defer_hook);
1018 if (dev != dont_lock_dev)
1021 if (dev->bus->sync_state)
1022 dev->bus->sync_state(dev);
1023 else if (dev->driver && dev->driver->sync_state)
1024 dev->driver->sync_state(dev);
1026 if (dev != dont_lock_dev)
1033 void device_links_supplier_sync_state_pause(void)
1035 device_links_write_lock();
1036 defer_sync_state_count++;
1037 device_links_write_unlock();
1040 void device_links_supplier_sync_state_resume(void)
1042 struct device *dev, *tmp;
1043 LIST_HEAD(sync_list);
1045 device_links_write_lock();
1046 if (!defer_sync_state_count) {
1047 WARN(true, "Unmatched sync_state pause/resume!");
1050 defer_sync_state_count--;
1051 if (defer_sync_state_count)
1054 list_for_each_entry_safe(dev, tmp, &deferred_sync, links.defer_hook) {
1056 * Delete from deferred_sync list before queuing it to
1057 * sync_list because defer_hook is used for both lists.
1059 list_del_init(&dev->links.defer_hook);
1060 __device_links_queue_sync_state(dev, &sync_list);
1063 device_links_write_unlock();
1065 device_links_flush_sync_list(&sync_list, NULL);
1068 static int sync_state_resume_initcall(void)
1070 device_links_supplier_sync_state_resume();
1073 late_initcall(sync_state_resume_initcall);
1075 static void __device_links_supplier_defer_sync(struct device *sup)
1077 if (list_empty(&sup->links.defer_hook) && dev_has_sync_state(sup))
1078 list_add_tail(&sup->links.defer_hook, &deferred_sync);
1081 static void device_link_drop_managed(struct device_link *link)
1083 link->flags &= ~DL_FLAG_MANAGED;
1084 WRITE_ONCE(link->status, DL_STATE_NONE);
1085 kref_put(&link->kref, __device_link_del);
1088 static ssize_t waiting_for_supplier_show(struct device *dev,
1089 struct device_attribute *attr,
1095 mutex_lock(&wfs_lock);
1096 val = !list_empty(&dev->links.needs_suppliers)
1097 && dev->links.need_for_probe;
1098 mutex_unlock(&wfs_lock);
1100 return sysfs_emit(buf, "%u\n", val);
1102 static DEVICE_ATTR_RO(waiting_for_supplier);
1105 * device_links_driver_bound - Update device links after probing its driver.
1106 * @dev: Device to update the links for.
1108 * The probe has been successful, so update links from this device to any
1109 * consumers by changing their status to "available".
1111 * Also change the status of @dev's links to suppliers to "active".
1113 * Links without the DL_FLAG_MANAGED flag set are ignored.
1115 void device_links_driver_bound(struct device *dev)
1117 struct device_link *link, *ln;
1118 LIST_HEAD(sync_list);
1121 * If a device probes successfully, it's expected to have created all
1122 * the device links it needs to or make new device links as it needs
1123 * them. So, it no longer needs to wait on any suppliers.
1125 mutex_lock(&wfs_lock);
1126 list_del_init(&dev->links.needs_suppliers);
1127 mutex_unlock(&wfs_lock);
1128 device_remove_file(dev, &dev_attr_waiting_for_supplier);
1130 device_links_write_lock();
1132 list_for_each_entry(link, &dev->links.consumers, s_node) {
1133 if (!(link->flags & DL_FLAG_MANAGED))
1137 * Links created during consumer probe may be in the "consumer
1138 * probe" state to start with if the supplier is still probing
1139 * when they are created and they may become "active" if the
1140 * consumer probe returns first. Skip them here.
1142 if (link->status == DL_STATE_CONSUMER_PROBE ||
1143 link->status == DL_STATE_ACTIVE)
1146 WARN_ON(link->status != DL_STATE_DORMANT);
1147 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1149 if (link->flags & DL_FLAG_AUTOPROBE_CONSUMER)
1150 driver_deferred_probe_add(link->consumer);
1153 if (defer_sync_state_count)
1154 __device_links_supplier_defer_sync(dev);
1156 __device_links_queue_sync_state(dev, &sync_list);
1158 list_for_each_entry_safe(link, ln, &dev->links.suppliers, c_node) {
1159 struct device *supplier;
1161 if (!(link->flags & DL_FLAG_MANAGED))
1164 supplier = link->supplier;
1165 if (link->flags & DL_FLAG_SYNC_STATE_ONLY) {
1167 * When DL_FLAG_SYNC_STATE_ONLY is set, it means no
1168 * other DL_MANAGED_LINK_FLAGS have been set. So, it's
1169 * save to drop the managed link completely.
1171 device_link_drop_managed(link);
1173 WARN_ON(link->status != DL_STATE_CONSUMER_PROBE);
1174 WRITE_ONCE(link->status, DL_STATE_ACTIVE);
1178 * This needs to be done even for the deleted
1179 * DL_FLAG_SYNC_STATE_ONLY device link in case it was the last
1180 * device link that was preventing the supplier from getting a
1181 * sync_state() call.
1183 if (defer_sync_state_count)
1184 __device_links_supplier_defer_sync(supplier);
1186 __device_links_queue_sync_state(supplier, &sync_list);
1189 dev->links.status = DL_DEV_DRIVER_BOUND;
1191 device_links_write_unlock();
1193 device_links_flush_sync_list(&sync_list, dev);
1197 * __device_links_no_driver - Update links of a device without a driver.
1198 * @dev: Device without a drvier.
1200 * Delete all non-persistent links from this device to any suppliers.
1202 * Persistent links stay around, but their status is changed to "available",
1203 * unless they already are in the "supplier unbind in progress" state in which
1204 * case they need not be updated.
1206 * Links without the DL_FLAG_MANAGED flag set are ignored.
1208 static void __device_links_no_driver(struct device *dev)
1210 struct device_link *link, *ln;
1212 list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1213 if (!(link->flags & DL_FLAG_MANAGED))
1216 if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER) {
1217 device_link_drop_managed(link);
1221 if (link->status != DL_STATE_CONSUMER_PROBE &&
1222 link->status != DL_STATE_ACTIVE)
1225 if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
1226 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1228 WARN_ON(!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
1229 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1233 dev->links.status = DL_DEV_NO_DRIVER;
1237 * device_links_no_driver - Update links after failing driver probe.
1238 * @dev: Device whose driver has just failed to probe.
1240 * Clean up leftover links to consumers for @dev and invoke
1241 * %__device_links_no_driver() to update links to suppliers for it as
1244 * Links without the DL_FLAG_MANAGED flag set are ignored.
1246 void device_links_no_driver(struct device *dev)
1248 struct device_link *link;
1250 device_links_write_lock();
1252 list_for_each_entry(link, &dev->links.consumers, s_node) {
1253 if (!(link->flags & DL_FLAG_MANAGED))
1257 * The probe has failed, so if the status of the link is
1258 * "consumer probe" or "active", it must have been added by
1259 * a probing consumer while this device was still probing.
1260 * Change its state to "dormant", as it represents a valid
1261 * relationship, but it is not functionally meaningful.
1263 if (link->status == DL_STATE_CONSUMER_PROBE ||
1264 link->status == DL_STATE_ACTIVE)
1265 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1268 __device_links_no_driver(dev);
1270 device_links_write_unlock();
1274 * device_links_driver_cleanup - Update links after driver removal.
1275 * @dev: Device whose driver has just gone away.
1277 * Update links to consumers for @dev by changing their status to "dormant" and
1278 * invoke %__device_links_no_driver() to update links to suppliers for it as
1281 * Links without the DL_FLAG_MANAGED flag set are ignored.
1283 void device_links_driver_cleanup(struct device *dev)
1285 struct device_link *link, *ln;
1287 device_links_write_lock();
1289 list_for_each_entry_safe(link, ln, &dev->links.consumers, s_node) {
1290 if (!(link->flags & DL_FLAG_MANAGED))
1293 WARN_ON(link->flags & DL_FLAG_AUTOREMOVE_CONSUMER);
1294 WARN_ON(link->status != DL_STATE_SUPPLIER_UNBIND);
1297 * autoremove the links between this @dev and its consumer
1298 * devices that are not active, i.e. where the link state
1299 * has moved to DL_STATE_SUPPLIER_UNBIND.
1301 if (link->status == DL_STATE_SUPPLIER_UNBIND &&
1302 link->flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
1303 device_link_drop_managed(link);
1305 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1308 list_del_init(&dev->links.defer_hook);
1309 __device_links_no_driver(dev);
1311 device_links_write_unlock();
1315 * device_links_busy - Check if there are any busy links to consumers.
1316 * @dev: Device to check.
1318 * Check each consumer of the device and return 'true' if its link's status
1319 * is one of "consumer probe" or "active" (meaning that the given consumer is
1320 * probing right now or its driver is present). Otherwise, change the link
1321 * state to "supplier unbind" to prevent the consumer from being probed
1322 * successfully going forward.
1324 * Return 'false' if there are no probing or active consumers.
1326 * Links without the DL_FLAG_MANAGED flag set are ignored.
1328 bool device_links_busy(struct device *dev)
1330 struct device_link *link;
1333 device_links_write_lock();
1335 list_for_each_entry(link, &dev->links.consumers, s_node) {
1336 if (!(link->flags & DL_FLAG_MANAGED))
1339 if (link->status == DL_STATE_CONSUMER_PROBE
1340 || link->status == DL_STATE_ACTIVE) {
1344 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1347 dev->links.status = DL_DEV_UNBINDING;
1349 device_links_write_unlock();
1354 * device_links_unbind_consumers - Force unbind consumers of the given device.
1355 * @dev: Device to unbind the consumers of.
1357 * Walk the list of links to consumers for @dev and if any of them is in the
1358 * "consumer probe" state, wait for all device probes in progress to complete
1361 * If that's not the case, change the status of the link to "supplier unbind"
1362 * and check if the link was in the "active" state. If so, force the consumer
1363 * driver to unbind and start over (the consumer will not re-probe as we have
1364 * changed the state of the link already).
1366 * Links without the DL_FLAG_MANAGED flag set are ignored.
1368 void device_links_unbind_consumers(struct device *dev)
1370 struct device_link *link;
1373 device_links_write_lock();
1375 list_for_each_entry(link, &dev->links.consumers, s_node) {
1376 enum device_link_state status;
1378 if (!(link->flags & DL_FLAG_MANAGED) ||
1379 link->flags & DL_FLAG_SYNC_STATE_ONLY)
1382 status = link->status;
1383 if (status == DL_STATE_CONSUMER_PROBE) {
1384 device_links_write_unlock();
1386 wait_for_device_probe();
1389 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1390 if (status == DL_STATE_ACTIVE) {
1391 struct device *consumer = link->consumer;
1393 get_device(consumer);
1395 device_links_write_unlock();
1397 device_release_driver_internal(consumer, NULL,
1399 put_device(consumer);
1404 device_links_write_unlock();
1408 * device_links_purge - Delete existing links to other devices.
1409 * @dev: Target device.
1411 static void device_links_purge(struct device *dev)
1413 struct device_link *link, *ln;
1415 if (dev->class == &devlink_class)
1418 mutex_lock(&wfs_lock);
1419 list_del_init(&dev->links.needs_suppliers);
1420 mutex_unlock(&wfs_lock);
1423 * Delete all of the remaining links from this device to any other
1424 * devices (either consumers or suppliers).
1426 device_links_write_lock();
1428 list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1429 WARN_ON(link->status == DL_STATE_ACTIVE);
1430 __device_link_del(&link->kref);
1433 list_for_each_entry_safe_reverse(link, ln, &dev->links.consumers, s_node) {
1434 WARN_ON(link->status != DL_STATE_DORMANT &&
1435 link->status != DL_STATE_NONE);
1436 __device_link_del(&link->kref);
1439 device_links_write_unlock();
1442 static u32 fw_devlink_flags = DL_FLAG_SYNC_STATE_ONLY;
1443 static int __init fw_devlink_setup(char *arg)
1448 if (strcmp(arg, "off") == 0) {
1449 fw_devlink_flags = 0;
1450 } else if (strcmp(arg, "permissive") == 0) {
1451 fw_devlink_flags = DL_FLAG_SYNC_STATE_ONLY;
1452 } else if (strcmp(arg, "on") == 0) {
1453 fw_devlink_flags = DL_FLAG_AUTOPROBE_CONSUMER;
1454 } else if (strcmp(arg, "rpm") == 0) {
1455 fw_devlink_flags = DL_FLAG_AUTOPROBE_CONSUMER |
1460 early_param("fw_devlink", fw_devlink_setup);
1462 u32 fw_devlink_get_flags(void)
1464 return fw_devlink_flags;
1467 static bool fw_devlink_is_permissive(void)
1469 return fw_devlink_flags == DL_FLAG_SYNC_STATE_ONLY;
1472 static void fw_devlink_link_device(struct device *dev)
1476 if (!fw_devlink_flags)
1479 mutex_lock(&defer_fw_devlink_lock);
1480 if (!defer_fw_devlink_count)
1481 device_link_add_missing_supplier_links();
1484 * The device's fwnode not having add_links() doesn't affect if other
1485 * consumers can find this device as a supplier. So, this check is
1486 * intentionally placed after device_link_add_missing_supplier_links().
1488 if (!fwnode_has_op(dev->fwnode, add_links))
1492 * If fw_devlink is being deferred, assume all devices have mandatory
1493 * suppliers they need to link to later. Then, when the fw_devlink is
1494 * resumed, all these devices will get a chance to try and link to any
1495 * suppliers they have.
1497 if (!defer_fw_devlink_count) {
1498 fw_ret = fwnode_call_int_op(dev->fwnode, add_links, dev);
1499 if (fw_ret == -ENODEV && fw_devlink_is_permissive())
1504 * defer_hook is not used to add device to deferred_sync list
1505 * until device is bound. Since deferred fw devlink also blocks
1506 * probing, same list hook can be used for deferred_fw_devlink.
1508 list_add_tail(&dev->links.defer_hook, &deferred_fw_devlink);
1511 if (fw_ret == -ENODEV)
1512 device_link_wait_for_mandatory_supplier(dev);
1514 device_link_wait_for_optional_supplier(dev);
1517 mutex_unlock(&defer_fw_devlink_lock);
1521 * fw_devlink_pause - Pause parsing of fwnode to create device links
1523 * Calling this function defers any fwnode parsing to create device links until
1524 * fw_devlink_resume() is called. Both these functions are ref counted and the
1525 * caller needs to match the calls.
1527 * While fw_devlink is paused:
1528 * - Any device that is added won't have its fwnode parsed to create device
1530 * - The probe of the device will also be deferred during this period.
1531 * - Any devices that were already added, but waiting for suppliers won't be
1532 * able to link to newly added devices.
1534 * Once fw_devlink_resume():
1535 * - All the fwnodes that was not parsed will be parsed.
1536 * - All the devices that were deferred probing will be reattempted if they
1537 * aren't waiting for any more suppliers.
1539 * This pair of functions, is mainly meant to optimize the parsing of fwnodes
1540 * when a lot of devices that need to link to each other are added in a short
1541 * interval of time. For example, adding all the top level devices in a system.
1543 * For example, if N devices are added and:
1544 * - All the consumers are added before their suppliers
1545 * - All the suppliers of the N devices are part of the N devices
1549 * - With the use of fw_devlink_pause() and fw_devlink_resume(), each device
1550 * will only need one parsing of its fwnode because it is guaranteed to find
1551 * all the supplier devices already registered and ready to link to. It won't
1552 * have to do another pass later to find one or more suppliers it couldn't
1553 * find in the first parse of the fwnode. So, we'll only need O(N) fwnode
1556 * - Without the use of fw_devlink_pause() and fw_devlink_resume(), we would
1557 * end up doing O(N^2) parses of fwnodes because every device that's added is
1558 * guaranteed to trigger a parse of the fwnode of every device added before
1559 * it. This O(N^2) parse is made worse by the fact that when a fwnode of a
1560 * device is parsed, all it descendant devices might need to have their
1561 * fwnodes parsed too (even if the devices themselves aren't added).
1563 void fw_devlink_pause(void)
1565 mutex_lock(&defer_fw_devlink_lock);
1566 defer_fw_devlink_count++;
1567 mutex_unlock(&defer_fw_devlink_lock);
1570 /** fw_devlink_resume - Resume parsing of fwnode to create device links
1572 * This function is used in conjunction with fw_devlink_pause() and is ref
1573 * counted. See documentation for fw_devlink_pause() for more details.
1575 void fw_devlink_resume(void)
1577 struct device *dev, *tmp;
1578 LIST_HEAD(probe_list);
1580 mutex_lock(&defer_fw_devlink_lock);
1581 if (!defer_fw_devlink_count) {
1582 WARN(true, "Unmatched fw_devlink pause/resume!");
1586 defer_fw_devlink_count--;
1587 if (defer_fw_devlink_count)
1590 device_link_add_missing_supplier_links();
1591 list_splice_tail_init(&deferred_fw_devlink, &probe_list);
1593 mutex_unlock(&defer_fw_devlink_lock);
1596 * bus_probe_device() can cause new devices to get added and they'll
1597 * try to grab defer_fw_devlink_lock. So, this needs to be done outside
1598 * the defer_fw_devlink_lock.
1600 list_for_each_entry_safe(dev, tmp, &probe_list, links.defer_hook) {
1601 list_del_init(&dev->links.defer_hook);
1602 bus_probe_device(dev);
1605 /* Device links support end. */
1607 int (*platform_notify)(struct device *dev) = NULL;
1608 int (*platform_notify_remove)(struct device *dev) = NULL;
1609 static struct kobject *dev_kobj;
1610 struct kobject *sysfs_dev_char_kobj;
1611 struct kobject *sysfs_dev_block_kobj;
1613 static DEFINE_MUTEX(device_hotplug_lock);
1615 void lock_device_hotplug(void)
1617 mutex_lock(&device_hotplug_lock);
1620 void unlock_device_hotplug(void)
1622 mutex_unlock(&device_hotplug_lock);
1625 int lock_device_hotplug_sysfs(void)
1627 if (mutex_trylock(&device_hotplug_lock))
1630 /* Avoid busy looping (5 ms of sleep should do). */
1632 return restart_syscall();
1636 static inline int device_is_not_partition(struct device *dev)
1638 return !(dev->type == &part_type);
1641 static inline int device_is_not_partition(struct device *dev)
1648 device_platform_notify(struct device *dev, enum kobject_action action)
1652 ret = acpi_platform_notify(dev, action);
1656 ret = software_node_notify(dev, action);
1660 if (platform_notify && action == KOBJ_ADD)
1661 platform_notify(dev);
1662 else if (platform_notify_remove && action == KOBJ_REMOVE)
1663 platform_notify_remove(dev);
1668 * dev_driver_string - Return a device's driver name, if at all possible
1669 * @dev: struct device to get the name of
1671 * Will return the device's driver's name if it is bound to a device. If
1672 * the device is not bound to a driver, it will return the name of the bus
1673 * it is attached to. If it is not attached to a bus either, an empty
1674 * string will be returned.
1676 const char *dev_driver_string(const struct device *dev)
1678 struct device_driver *drv;
1680 /* dev->driver can change to NULL underneath us because of unbinding,
1681 * so be careful about accessing it. dev->bus and dev->class should
1682 * never change once they are set, so they don't need special care.
1684 drv = READ_ONCE(dev->driver);
1685 return drv ? drv->name : dev_bus_name(dev);
1687 EXPORT_SYMBOL(dev_driver_string);
1689 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
1691 static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
1694 struct device_attribute *dev_attr = to_dev_attr(attr);
1695 struct device *dev = kobj_to_dev(kobj);
1699 ret = dev_attr->show(dev, dev_attr, buf);
1700 if (ret >= (ssize_t)PAGE_SIZE) {
1701 printk("dev_attr_show: %pS returned bad count\n",
1707 static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
1708 const char *buf, size_t count)
1710 struct device_attribute *dev_attr = to_dev_attr(attr);
1711 struct device *dev = kobj_to_dev(kobj);
1714 if (dev_attr->store)
1715 ret = dev_attr->store(dev, dev_attr, buf, count);
1719 static const struct sysfs_ops dev_sysfs_ops = {
1720 .show = dev_attr_show,
1721 .store = dev_attr_store,
1724 #define to_ext_attr(x) container_of(x, struct dev_ext_attribute, attr)
1726 ssize_t device_store_ulong(struct device *dev,
1727 struct device_attribute *attr,
1728 const char *buf, size_t size)
1730 struct dev_ext_attribute *ea = to_ext_attr(attr);
1734 ret = kstrtoul(buf, 0, &new);
1737 *(unsigned long *)(ea->var) = new;
1738 /* Always return full write size even if we didn't consume all */
1741 EXPORT_SYMBOL_GPL(device_store_ulong);
1743 ssize_t device_show_ulong(struct device *dev,
1744 struct device_attribute *attr,
1747 struct dev_ext_attribute *ea = to_ext_attr(attr);
1748 return sysfs_emit(buf, "%lx\n", *(unsigned long *)(ea->var));
1750 EXPORT_SYMBOL_GPL(device_show_ulong);
1752 ssize_t device_store_int(struct device *dev,
1753 struct device_attribute *attr,
1754 const char *buf, size_t size)
1756 struct dev_ext_attribute *ea = to_ext_attr(attr);
1760 ret = kstrtol(buf, 0, &new);
1764 if (new > INT_MAX || new < INT_MIN)
1766 *(int *)(ea->var) = new;
1767 /* Always return full write size even if we didn't consume all */
1770 EXPORT_SYMBOL_GPL(device_store_int);
1772 ssize_t device_show_int(struct device *dev,
1773 struct device_attribute *attr,
1776 struct dev_ext_attribute *ea = to_ext_attr(attr);
1778 return sysfs_emit(buf, "%d\n", *(int *)(ea->var));
1780 EXPORT_SYMBOL_GPL(device_show_int);
1782 ssize_t device_store_bool(struct device *dev, struct device_attribute *attr,
1783 const char *buf, size_t size)
1785 struct dev_ext_attribute *ea = to_ext_attr(attr);
1787 if (strtobool(buf, ea->var) < 0)
1792 EXPORT_SYMBOL_GPL(device_store_bool);
1794 ssize_t device_show_bool(struct device *dev, struct device_attribute *attr,
1797 struct dev_ext_attribute *ea = to_ext_attr(attr);
1799 return sysfs_emit(buf, "%d\n", *(bool *)(ea->var));
1801 EXPORT_SYMBOL_GPL(device_show_bool);
1804 * device_release - free device structure.
1805 * @kobj: device's kobject.
1807 * This is called once the reference count for the object
1808 * reaches 0. We forward the call to the device's release
1809 * method, which should handle actually freeing the structure.
1811 static void device_release(struct kobject *kobj)
1813 struct device *dev = kobj_to_dev(kobj);
1814 struct device_private *p = dev->p;
1817 * Some platform devices are driven without driver attached
1818 * and managed resources may have been acquired. Make sure
1819 * all resources are released.
1821 * Drivers still can add resources into device after device
1822 * is deleted but alive, so release devres here to avoid
1823 * possible memory leak.
1825 devres_release_all(dev);
1827 kfree(dev->dma_range_map);
1831 else if (dev->type && dev->type->release)
1832 dev->type->release(dev);
1833 else if (dev->class && dev->class->dev_release)
1834 dev->class->dev_release(dev);
1836 WARN(1, KERN_ERR "Device '%s' does not have a release() function, it is broken and must be fixed. See Documentation/core-api/kobject.rst.\n",
1841 static const void *device_namespace(struct kobject *kobj)
1843 struct device *dev = kobj_to_dev(kobj);
1844 const void *ns = NULL;
1846 if (dev->class && dev->class->ns_type)
1847 ns = dev->class->namespace(dev);
1852 static void device_get_ownership(struct kobject *kobj, kuid_t *uid, kgid_t *gid)
1854 struct device *dev = kobj_to_dev(kobj);
1856 if (dev->class && dev->class->get_ownership)
1857 dev->class->get_ownership(dev, uid, gid);
1860 static struct kobj_type device_ktype = {
1861 .release = device_release,
1862 .sysfs_ops = &dev_sysfs_ops,
1863 .namespace = device_namespace,
1864 .get_ownership = device_get_ownership,
1868 static int dev_uevent_filter(struct kset *kset, struct kobject *kobj)
1870 struct kobj_type *ktype = get_ktype(kobj);
1872 if (ktype == &device_ktype) {
1873 struct device *dev = kobj_to_dev(kobj);
1882 static const char *dev_uevent_name(struct kset *kset, struct kobject *kobj)
1884 struct device *dev = kobj_to_dev(kobj);
1887 return dev->bus->name;
1889 return dev->class->name;
1893 static int dev_uevent(struct kset *kset, struct kobject *kobj,
1894 struct kobj_uevent_env *env)
1896 struct device *dev = kobj_to_dev(kobj);
1899 /* add device node properties if present */
1900 if (MAJOR(dev->devt)) {
1904 kuid_t uid = GLOBAL_ROOT_UID;
1905 kgid_t gid = GLOBAL_ROOT_GID;
1907 add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt));
1908 add_uevent_var(env, "MINOR=%u", MINOR(dev->devt));
1909 name = device_get_devnode(dev, &mode, &uid, &gid, &tmp);
1911 add_uevent_var(env, "DEVNAME=%s", name);
1913 add_uevent_var(env, "DEVMODE=%#o", mode & 0777);
1914 if (!uid_eq(uid, GLOBAL_ROOT_UID))
1915 add_uevent_var(env, "DEVUID=%u", from_kuid(&init_user_ns, uid));
1916 if (!gid_eq(gid, GLOBAL_ROOT_GID))
1917 add_uevent_var(env, "DEVGID=%u", from_kgid(&init_user_ns, gid));
1922 if (dev->type && dev->type->name)
1923 add_uevent_var(env, "DEVTYPE=%s", dev->type->name);
1926 add_uevent_var(env, "DRIVER=%s", dev->driver->name);
1928 /* Add common DT information about the device */
1929 of_device_uevent(dev, env);
1931 /* have the bus specific function add its stuff */
1932 if (dev->bus && dev->bus->uevent) {
1933 retval = dev->bus->uevent(dev, env);
1935 pr_debug("device: '%s': %s: bus uevent() returned %d\n",
1936 dev_name(dev), __func__, retval);
1939 /* have the class specific function add its stuff */
1940 if (dev->class && dev->class->dev_uevent) {
1941 retval = dev->class->dev_uevent(dev, env);
1943 pr_debug("device: '%s': %s: class uevent() "
1944 "returned %d\n", dev_name(dev),
1948 /* have the device type specific function add its stuff */
1949 if (dev->type && dev->type->uevent) {
1950 retval = dev->type->uevent(dev, env);
1952 pr_debug("device: '%s': %s: dev_type uevent() "
1953 "returned %d\n", dev_name(dev),
1960 static const struct kset_uevent_ops device_uevent_ops = {
1961 .filter = dev_uevent_filter,
1962 .name = dev_uevent_name,
1963 .uevent = dev_uevent,
1966 static ssize_t uevent_show(struct device *dev, struct device_attribute *attr,
1969 struct kobject *top_kobj;
1971 struct kobj_uevent_env *env = NULL;
1976 /* search the kset, the device belongs to */
1977 top_kobj = &dev->kobj;
1978 while (!top_kobj->kset && top_kobj->parent)
1979 top_kobj = top_kobj->parent;
1980 if (!top_kobj->kset)
1983 kset = top_kobj->kset;
1984 if (!kset->uevent_ops || !kset->uevent_ops->uevent)
1987 /* respect filter */
1988 if (kset->uevent_ops && kset->uevent_ops->filter)
1989 if (!kset->uevent_ops->filter(kset, &dev->kobj))
1992 env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
1996 /* let the kset specific function add its keys */
1997 retval = kset->uevent_ops->uevent(kset, &dev->kobj, env);
2001 /* copy keys to file */
2002 for (i = 0; i < env->envp_idx; i++)
2003 len += sysfs_emit_at(buf, len, "%s\n", env->envp[i]);
2009 static ssize_t uevent_store(struct device *dev, struct device_attribute *attr,
2010 const char *buf, size_t count)
2014 rc = kobject_synth_uevent(&dev->kobj, buf, count);
2017 dev_err(dev, "uevent: failed to send synthetic uevent\n");
2023 static DEVICE_ATTR_RW(uevent);
2025 static ssize_t online_show(struct device *dev, struct device_attribute *attr,
2031 val = !dev->offline;
2033 return sysfs_emit(buf, "%u\n", val);
2036 static ssize_t online_store(struct device *dev, struct device_attribute *attr,
2037 const char *buf, size_t count)
2042 ret = strtobool(buf, &val);
2046 ret = lock_device_hotplug_sysfs();
2050 ret = val ? device_online(dev) : device_offline(dev);
2051 unlock_device_hotplug();
2052 return ret < 0 ? ret : count;
2054 static DEVICE_ATTR_RW(online);
2056 int device_add_groups(struct device *dev, const struct attribute_group **groups)
2058 return sysfs_create_groups(&dev->kobj, groups);
2060 EXPORT_SYMBOL_GPL(device_add_groups);
2062 void device_remove_groups(struct device *dev,
2063 const struct attribute_group **groups)
2065 sysfs_remove_groups(&dev->kobj, groups);
2067 EXPORT_SYMBOL_GPL(device_remove_groups);
2069 union device_attr_group_devres {
2070 const struct attribute_group *group;
2071 const struct attribute_group **groups;
2074 static int devm_attr_group_match(struct device *dev, void *res, void *data)
2076 return ((union device_attr_group_devres *)res)->group == data;
2079 static void devm_attr_group_remove(struct device *dev, void *res)
2081 union device_attr_group_devres *devres = res;
2082 const struct attribute_group *group = devres->group;
2084 dev_dbg(dev, "%s: removing group %p\n", __func__, group);
2085 sysfs_remove_group(&dev->kobj, group);
2088 static void devm_attr_groups_remove(struct device *dev, void *res)
2090 union device_attr_group_devres *devres = res;
2091 const struct attribute_group **groups = devres->groups;
2093 dev_dbg(dev, "%s: removing groups %p\n", __func__, groups);
2094 sysfs_remove_groups(&dev->kobj, groups);
2098 * devm_device_add_group - given a device, create a managed attribute group
2099 * @dev: The device to create the group for
2100 * @grp: The attribute group to create
2102 * This function creates a group for the first time. It will explicitly
2103 * warn and error if any of the attribute files being created already exist.
2105 * Returns 0 on success or error code on failure.
2107 int devm_device_add_group(struct device *dev, const struct attribute_group *grp)
2109 union device_attr_group_devres *devres;
2112 devres = devres_alloc(devm_attr_group_remove,
2113 sizeof(*devres), GFP_KERNEL);
2117 error = sysfs_create_group(&dev->kobj, grp);
2119 devres_free(devres);
2123 devres->group = grp;
2124 devres_add(dev, devres);
2127 EXPORT_SYMBOL_GPL(devm_device_add_group);
2130 * devm_device_remove_group: remove a managed group from a device
2131 * @dev: device to remove the group from
2132 * @grp: group to remove
2134 * This function removes a group of attributes from a device. The attributes
2135 * previously have to have been created for this group, otherwise it will fail.
2137 void devm_device_remove_group(struct device *dev,
2138 const struct attribute_group *grp)
2140 WARN_ON(devres_release(dev, devm_attr_group_remove,
2141 devm_attr_group_match,
2142 /* cast away const */ (void *)grp));
2144 EXPORT_SYMBOL_GPL(devm_device_remove_group);
2147 * devm_device_add_groups - create a bunch of managed attribute groups
2148 * @dev: The device to create the group for
2149 * @groups: The attribute groups to create, NULL terminated
2151 * This function creates a bunch of managed attribute groups. If an error
2152 * occurs when creating a group, all previously created groups will be
2153 * removed, unwinding everything back to the original state when this
2154 * function was called. It will explicitly warn and error if any of the
2155 * attribute files being created already exist.
2157 * Returns 0 on success or error code from sysfs_create_group on failure.
2159 int devm_device_add_groups(struct device *dev,
2160 const struct attribute_group **groups)
2162 union device_attr_group_devres *devres;
2165 devres = devres_alloc(devm_attr_groups_remove,
2166 sizeof(*devres), GFP_KERNEL);
2170 error = sysfs_create_groups(&dev->kobj, groups);
2172 devres_free(devres);
2176 devres->groups = groups;
2177 devres_add(dev, devres);
2180 EXPORT_SYMBOL_GPL(devm_device_add_groups);
2183 * devm_device_remove_groups - remove a list of managed groups
2185 * @dev: The device for the groups to be removed from
2186 * @groups: NULL terminated list of groups to be removed
2188 * If groups is not NULL, remove the specified groups from the device.
2190 void devm_device_remove_groups(struct device *dev,
2191 const struct attribute_group **groups)
2193 WARN_ON(devres_release(dev, devm_attr_groups_remove,
2194 devm_attr_group_match,
2195 /* cast away const */ (void *)groups));
2197 EXPORT_SYMBOL_GPL(devm_device_remove_groups);
2199 static int device_add_attrs(struct device *dev)
2201 struct class *class = dev->class;
2202 const struct device_type *type = dev->type;
2206 error = device_add_groups(dev, class->dev_groups);
2212 error = device_add_groups(dev, type->groups);
2214 goto err_remove_class_groups;
2217 error = device_add_groups(dev, dev->groups);
2219 goto err_remove_type_groups;
2221 if (device_supports_offline(dev) && !dev->offline_disabled) {
2222 error = device_create_file(dev, &dev_attr_online);
2224 goto err_remove_dev_groups;
2227 if (fw_devlink_flags && !fw_devlink_is_permissive()) {
2228 error = device_create_file(dev, &dev_attr_waiting_for_supplier);
2230 goto err_remove_dev_online;
2235 err_remove_dev_online:
2236 device_remove_file(dev, &dev_attr_online);
2237 err_remove_dev_groups:
2238 device_remove_groups(dev, dev->groups);
2239 err_remove_type_groups:
2241 device_remove_groups(dev, type->groups);
2242 err_remove_class_groups:
2244 device_remove_groups(dev, class->dev_groups);
2249 static void device_remove_attrs(struct device *dev)
2251 struct class *class = dev->class;
2252 const struct device_type *type = dev->type;
2254 device_remove_file(dev, &dev_attr_waiting_for_supplier);
2255 device_remove_file(dev, &dev_attr_online);
2256 device_remove_groups(dev, dev->groups);
2259 device_remove_groups(dev, type->groups);
2262 device_remove_groups(dev, class->dev_groups);
2265 static ssize_t dev_show(struct device *dev, struct device_attribute *attr,
2268 return print_dev_t(buf, dev->devt);
2270 static DEVICE_ATTR_RO(dev);
2273 struct kset *devices_kset;
2276 * devices_kset_move_before - Move device in the devices_kset's list.
2277 * @deva: Device to move.
2278 * @devb: Device @deva should come before.
2280 static void devices_kset_move_before(struct device *deva, struct device *devb)
2284 pr_debug("devices_kset: Moving %s before %s\n",
2285 dev_name(deva), dev_name(devb));
2286 spin_lock(&devices_kset->list_lock);
2287 list_move_tail(&deva->kobj.entry, &devb->kobj.entry);
2288 spin_unlock(&devices_kset->list_lock);
2292 * devices_kset_move_after - Move device in the devices_kset's list.
2293 * @deva: Device to move
2294 * @devb: Device @deva should come after.
2296 static void devices_kset_move_after(struct device *deva, struct device *devb)
2300 pr_debug("devices_kset: Moving %s after %s\n",
2301 dev_name(deva), dev_name(devb));
2302 spin_lock(&devices_kset->list_lock);
2303 list_move(&deva->kobj.entry, &devb->kobj.entry);
2304 spin_unlock(&devices_kset->list_lock);
2308 * devices_kset_move_last - move the device to the end of devices_kset's list.
2309 * @dev: device to move
2311 void devices_kset_move_last(struct device *dev)
2315 pr_debug("devices_kset: Moving %s to end of list\n", dev_name(dev));
2316 spin_lock(&devices_kset->list_lock);
2317 list_move_tail(&dev->kobj.entry, &devices_kset->list);
2318 spin_unlock(&devices_kset->list_lock);
2322 * device_create_file - create sysfs attribute file for device.
2324 * @attr: device attribute descriptor.
2326 int device_create_file(struct device *dev,
2327 const struct device_attribute *attr)
2332 WARN(((attr->attr.mode & S_IWUGO) && !attr->store),
2333 "Attribute %s: write permission without 'store'\n",
2335 WARN(((attr->attr.mode & S_IRUGO) && !attr->show),
2336 "Attribute %s: read permission without 'show'\n",
2338 error = sysfs_create_file(&dev->kobj, &attr->attr);
2343 EXPORT_SYMBOL_GPL(device_create_file);
2346 * device_remove_file - remove sysfs attribute file.
2348 * @attr: device attribute descriptor.
2350 void device_remove_file(struct device *dev,
2351 const struct device_attribute *attr)
2354 sysfs_remove_file(&dev->kobj, &attr->attr);
2356 EXPORT_SYMBOL_GPL(device_remove_file);
2359 * device_remove_file_self - remove sysfs attribute file from its own method.
2361 * @attr: device attribute descriptor.
2363 * See kernfs_remove_self() for details.
2365 bool device_remove_file_self(struct device *dev,
2366 const struct device_attribute *attr)
2369 return sysfs_remove_file_self(&dev->kobj, &attr->attr);
2373 EXPORT_SYMBOL_GPL(device_remove_file_self);
2376 * device_create_bin_file - create sysfs binary attribute file for device.
2378 * @attr: device binary attribute descriptor.
2380 int device_create_bin_file(struct device *dev,
2381 const struct bin_attribute *attr)
2383 int error = -EINVAL;
2385 error = sysfs_create_bin_file(&dev->kobj, attr);
2388 EXPORT_SYMBOL_GPL(device_create_bin_file);
2391 * device_remove_bin_file - remove sysfs binary attribute file
2393 * @attr: device binary attribute descriptor.
2395 void device_remove_bin_file(struct device *dev,
2396 const struct bin_attribute *attr)
2399 sysfs_remove_bin_file(&dev->kobj, attr);
2401 EXPORT_SYMBOL_GPL(device_remove_bin_file);
2403 static void klist_children_get(struct klist_node *n)
2405 struct device_private *p = to_device_private_parent(n);
2406 struct device *dev = p->device;
2411 static void klist_children_put(struct klist_node *n)
2413 struct device_private *p = to_device_private_parent(n);
2414 struct device *dev = p->device;
2420 * device_initialize - init device structure.
2423 * This prepares the device for use by other layers by initializing
2425 * It is the first half of device_register(), if called by
2426 * that function, though it can also be called separately, so one
2427 * may use @dev's fields. In particular, get_device()/put_device()
2428 * may be used for reference counting of @dev after calling this
2431 * All fields in @dev must be initialized by the caller to 0, except
2432 * for those explicitly set to some other value. The simplest
2433 * approach is to use kzalloc() to allocate the structure containing
2436 * NOTE: Use put_device() to give up your reference instead of freeing
2437 * @dev directly once you have called this function.
2439 void device_initialize(struct device *dev)
2441 dev->kobj.kset = devices_kset;
2442 kobject_init(&dev->kobj, &device_ktype);
2443 INIT_LIST_HEAD(&dev->dma_pools);
2444 mutex_init(&dev->mutex);
2445 #ifdef CONFIG_PROVE_LOCKING
2446 mutex_init(&dev->lockdep_mutex);
2448 lockdep_set_novalidate_class(&dev->mutex);
2449 spin_lock_init(&dev->devres_lock);
2450 INIT_LIST_HEAD(&dev->devres_head);
2451 device_pm_init(dev);
2452 set_dev_node(dev, -1);
2453 #ifdef CONFIG_GENERIC_MSI_IRQ
2454 raw_spin_lock_init(&dev->msi_lock);
2455 INIT_LIST_HEAD(&dev->msi_list);
2457 INIT_LIST_HEAD(&dev->links.consumers);
2458 INIT_LIST_HEAD(&dev->links.suppliers);
2459 INIT_LIST_HEAD(&dev->links.needs_suppliers);
2460 INIT_LIST_HEAD(&dev->links.defer_hook);
2461 dev->links.status = DL_DEV_NO_DRIVER;
2463 EXPORT_SYMBOL_GPL(device_initialize);
2465 struct kobject *virtual_device_parent(struct device *dev)
2467 static struct kobject *virtual_dir = NULL;
2470 virtual_dir = kobject_create_and_add("virtual",
2471 &devices_kset->kobj);
2477 struct kobject kobj;
2478 struct class *class;
2481 #define to_class_dir(obj) container_of(obj, struct class_dir, kobj)
2483 static void class_dir_release(struct kobject *kobj)
2485 struct class_dir *dir = to_class_dir(kobj);
2490 struct kobj_ns_type_operations *class_dir_child_ns_type(struct kobject *kobj)
2492 struct class_dir *dir = to_class_dir(kobj);
2493 return dir->class->ns_type;
2496 static struct kobj_type class_dir_ktype = {
2497 .release = class_dir_release,
2498 .sysfs_ops = &kobj_sysfs_ops,
2499 .child_ns_type = class_dir_child_ns_type
2502 static struct kobject *
2503 class_dir_create_and_add(struct class *class, struct kobject *parent_kobj)
2505 struct class_dir *dir;
2508 dir = kzalloc(sizeof(*dir), GFP_KERNEL);
2510 return ERR_PTR(-ENOMEM);
2513 kobject_init(&dir->kobj, &class_dir_ktype);
2515 dir->kobj.kset = &class->p->glue_dirs;
2517 retval = kobject_add(&dir->kobj, parent_kobj, "%s", class->name);
2519 kobject_put(&dir->kobj);
2520 return ERR_PTR(retval);
2525 static DEFINE_MUTEX(gdp_mutex);
2527 static struct kobject *get_device_parent(struct device *dev,
2528 struct device *parent)
2531 struct kobject *kobj = NULL;
2532 struct kobject *parent_kobj;
2536 /* block disks show up in /sys/block */
2537 if (sysfs_deprecated && dev->class == &block_class) {
2538 if (parent && parent->class == &block_class)
2539 return &parent->kobj;
2540 return &block_class.p->subsys.kobj;
2545 * If we have no parent, we live in "virtual".
2546 * Class-devices with a non class-device as parent, live
2547 * in a "glue" directory to prevent namespace collisions.
2550 parent_kobj = virtual_device_parent(dev);
2551 else if (parent->class && !dev->class->ns_type)
2552 return &parent->kobj;
2554 parent_kobj = &parent->kobj;
2556 mutex_lock(&gdp_mutex);
2558 /* find our class-directory at the parent and reference it */
2559 spin_lock(&dev->class->p->glue_dirs.list_lock);
2560 list_for_each_entry(k, &dev->class->p->glue_dirs.list, entry)
2561 if (k->parent == parent_kobj) {
2562 kobj = kobject_get(k);
2565 spin_unlock(&dev->class->p->glue_dirs.list_lock);
2567 mutex_unlock(&gdp_mutex);
2571 /* or create a new class-directory at the parent device */
2572 k = class_dir_create_and_add(dev->class, parent_kobj);
2573 /* do not emit an uevent for this simple "glue" directory */
2574 mutex_unlock(&gdp_mutex);
2578 /* subsystems can specify a default root directory for their devices */
2579 if (!parent && dev->bus && dev->bus->dev_root)
2580 return &dev->bus->dev_root->kobj;
2583 return &parent->kobj;
2587 static inline bool live_in_glue_dir(struct kobject *kobj,
2590 if (!kobj || !dev->class ||
2591 kobj->kset != &dev->class->p->glue_dirs)
2596 static inline struct kobject *get_glue_dir(struct device *dev)
2598 return dev->kobj.parent;
2602 * make sure cleaning up dir as the last step, we need to make
2603 * sure .release handler of kobject is run with holding the
2606 static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir)
2610 /* see if we live in a "glue" directory */
2611 if (!live_in_glue_dir(glue_dir, dev))
2614 mutex_lock(&gdp_mutex);
2616 * There is a race condition between removing glue directory
2617 * and adding a new device under the glue directory.
2622 * get_device_parent()
2623 * class_dir_create_and_add()
2624 * kobject_add_internal()
2625 * create_dir() // create glue_dir
2628 * get_device_parent()
2629 * kobject_get() // get glue_dir
2632 * cleanup_glue_dir()
2633 * kobject_del(glue_dir)
2636 * kobject_add_internal()
2637 * create_dir() // in glue_dir
2638 * sysfs_create_dir_ns()
2639 * kernfs_create_dir_ns(sd)
2641 * sysfs_remove_dir() // glue_dir->sd=NULL
2642 * sysfs_put() // free glue_dir->sd
2645 * kernfs_new_node(sd)
2646 * kernfs_get(glue_dir)
2650 * Before CPU1 remove last child device under glue dir, if CPU2 add
2651 * a new device under glue dir, the glue_dir kobject reference count
2652 * will be increase to 2 in kobject_get(k). And CPU2 has been called
2653 * kernfs_create_dir_ns(). Meanwhile, CPU1 call sysfs_remove_dir()
2654 * and sysfs_put(). This result in glue_dir->sd is freed.
2656 * Then the CPU2 will see a stale "empty" but still potentially used
2657 * glue dir around in kernfs_new_node().
2659 * In order to avoid this happening, we also should make sure that
2660 * kernfs_node for glue_dir is released in CPU1 only when refcount
2661 * for glue_dir kobj is 1.
2663 ref = kref_read(&glue_dir->kref);
2664 if (!kobject_has_children(glue_dir) && !--ref)
2665 kobject_del(glue_dir);
2666 kobject_put(glue_dir);
2667 mutex_unlock(&gdp_mutex);
2670 static int device_add_class_symlinks(struct device *dev)
2672 struct device_node *of_node = dev_of_node(dev);
2676 error = sysfs_create_link(&dev->kobj, of_node_kobj(of_node), "of_node");
2678 dev_warn(dev, "Error %d creating of_node link\n",error);
2679 /* An error here doesn't warrant bringing down the device */
2685 error = sysfs_create_link(&dev->kobj,
2686 &dev->class->p->subsys.kobj,
2691 if (dev->parent && device_is_not_partition(dev)) {
2692 error = sysfs_create_link(&dev->kobj, &dev->parent->kobj,
2699 /* /sys/block has directories and does not need symlinks */
2700 if (sysfs_deprecated && dev->class == &block_class)
2704 /* link in the class directory pointing to the device */
2705 error = sysfs_create_link(&dev->class->p->subsys.kobj,
2706 &dev->kobj, dev_name(dev));
2713 sysfs_remove_link(&dev->kobj, "device");
2716 sysfs_remove_link(&dev->kobj, "subsystem");
2718 sysfs_remove_link(&dev->kobj, "of_node");
2722 static void device_remove_class_symlinks(struct device *dev)
2724 if (dev_of_node(dev))
2725 sysfs_remove_link(&dev->kobj, "of_node");
2730 if (dev->parent && device_is_not_partition(dev))
2731 sysfs_remove_link(&dev->kobj, "device");
2732 sysfs_remove_link(&dev->kobj, "subsystem");
2734 if (sysfs_deprecated && dev->class == &block_class)
2737 sysfs_delete_link(&dev->class->p->subsys.kobj, &dev->kobj, dev_name(dev));
2741 * dev_set_name - set a device name
2743 * @fmt: format string for the device's name
2745 int dev_set_name(struct device *dev, const char *fmt, ...)
2750 va_start(vargs, fmt);
2751 err = kobject_set_name_vargs(&dev->kobj, fmt, vargs);
2755 EXPORT_SYMBOL_GPL(dev_set_name);
2758 * device_to_dev_kobj - select a /sys/dev/ directory for the device
2761 * By default we select char/ for new entries. Setting class->dev_obj
2762 * to NULL prevents an entry from being created. class->dev_kobj must
2763 * be set (or cleared) before any devices are registered to the class
2764 * otherwise device_create_sys_dev_entry() and
2765 * device_remove_sys_dev_entry() will disagree about the presence of
2768 static struct kobject *device_to_dev_kobj(struct device *dev)
2770 struct kobject *kobj;
2773 kobj = dev->class->dev_kobj;
2775 kobj = sysfs_dev_char_kobj;
2780 static int device_create_sys_dev_entry(struct device *dev)
2782 struct kobject *kobj = device_to_dev_kobj(dev);
2787 format_dev_t(devt_str, dev->devt);
2788 error = sysfs_create_link(kobj, &dev->kobj, devt_str);
2794 static void device_remove_sys_dev_entry(struct device *dev)
2796 struct kobject *kobj = device_to_dev_kobj(dev);
2800 format_dev_t(devt_str, dev->devt);
2801 sysfs_remove_link(kobj, devt_str);
2805 static int device_private_init(struct device *dev)
2807 dev->p = kzalloc(sizeof(*dev->p), GFP_KERNEL);
2810 dev->p->device = dev;
2811 klist_init(&dev->p->klist_children, klist_children_get,
2812 klist_children_put);
2813 INIT_LIST_HEAD(&dev->p->deferred_probe);
2818 * device_add - add device to device hierarchy.
2821 * This is part 2 of device_register(), though may be called
2822 * separately _iff_ device_initialize() has been called separately.
2824 * This adds @dev to the kobject hierarchy via kobject_add(), adds it
2825 * to the global and sibling lists for the device, then
2826 * adds it to the other relevant subsystems of the driver model.
2828 * Do not call this routine or device_register() more than once for
2829 * any device structure. The driver model core is not designed to work
2830 * with devices that get unregistered and then spring back to life.
2831 * (Among other things, it's very hard to guarantee that all references
2832 * to the previous incarnation of @dev have been dropped.) Allocate
2833 * and register a fresh new struct device instead.
2835 * NOTE: _Never_ directly free @dev after calling this function, even
2836 * if it returned an error! Always use put_device() to give up your
2837 * reference instead.
2839 * Rule of thumb is: if device_add() succeeds, you should call
2840 * device_del() when you want to get rid of it. If device_add() has
2841 * *not* succeeded, use *only* put_device() to drop the reference
2844 int device_add(struct device *dev)
2846 struct device *parent;
2847 struct kobject *kobj;
2848 struct class_interface *class_intf;
2849 int error = -EINVAL;
2850 struct kobject *glue_dir = NULL;
2852 dev = get_device(dev);
2857 error = device_private_init(dev);
2863 * for statically allocated devices, which should all be converted
2864 * some day, we need to initialize the name. We prevent reading back
2865 * the name, and force the use of dev_name()
2867 if (dev->init_name) {
2868 dev_set_name(dev, "%s", dev->init_name);
2869 dev->init_name = NULL;
2872 /* subsystems can specify simple device enumeration */
2873 if (!dev_name(dev) && dev->bus && dev->bus->dev_name)
2874 dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
2876 if (!dev_name(dev)) {
2881 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
2883 parent = get_device(dev->parent);
2884 kobj = get_device_parent(dev, parent);
2886 error = PTR_ERR(kobj);
2890 dev->kobj.parent = kobj;
2892 /* use parent numa_node */
2893 if (parent && (dev_to_node(dev) == NUMA_NO_NODE))
2894 set_dev_node(dev, dev_to_node(parent));
2896 /* first, register with generic layer. */
2897 /* we require the name to be set before, and pass NULL */
2898 error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
2900 glue_dir = get_glue_dir(dev);
2904 /* notify platform of device entry */
2905 error = device_platform_notify(dev, KOBJ_ADD);
2907 goto platform_error;
2909 error = device_create_file(dev, &dev_attr_uevent);
2913 error = device_add_class_symlinks(dev);
2916 error = device_add_attrs(dev);
2919 error = bus_add_device(dev);
2922 error = dpm_sysfs_add(dev);
2927 if (MAJOR(dev->devt)) {
2928 error = device_create_file(dev, &dev_attr_dev);
2932 error = device_create_sys_dev_entry(dev);
2936 devtmpfs_create_node(dev);
2939 /* Notify clients of device addition. This call must come
2940 * after dpm_sysfs_add() and before kobject_uevent().
2943 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
2944 BUS_NOTIFY_ADD_DEVICE, dev);
2946 kobject_uevent(&dev->kobj, KOBJ_ADD);
2949 * Check if any of the other devices (consumers) have been waiting for
2950 * this device (supplier) to be added so that they can create a device
2953 * This needs to happen after device_pm_add() because device_link_add()
2954 * requires the supplier be registered before it's called.
2956 * But this also needs to happen before bus_probe_device() to make sure
2957 * waiting consumers can link to it before the driver is bound to the
2958 * device and the driver sync_state callback is called for this device.
2960 if (dev->fwnode && !dev->fwnode->dev) {
2961 dev->fwnode->dev = dev;
2962 fw_devlink_link_device(dev);
2965 bus_probe_device(dev);
2967 klist_add_tail(&dev->p->knode_parent,
2968 &parent->p->klist_children);
2971 mutex_lock(&dev->class->p->mutex);
2972 /* tie the class to the device */
2973 klist_add_tail(&dev->p->knode_class,
2974 &dev->class->p->klist_devices);
2976 /* notify any interfaces that the device is here */
2977 list_for_each_entry(class_intf,
2978 &dev->class->p->interfaces, node)
2979 if (class_intf->add_dev)
2980 class_intf->add_dev(dev, class_intf);
2981 mutex_unlock(&dev->class->p->mutex);
2987 if (MAJOR(dev->devt))
2988 device_remove_file(dev, &dev_attr_dev);
2990 device_pm_remove(dev);
2991 dpm_sysfs_remove(dev);
2993 bus_remove_device(dev);
2995 device_remove_attrs(dev);
2997 device_remove_class_symlinks(dev);
2999 device_remove_file(dev, &dev_attr_uevent);
3001 device_platform_notify(dev, KOBJ_REMOVE);
3003 kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3004 glue_dir = get_glue_dir(dev);
3005 kobject_del(&dev->kobj);
3007 cleanup_glue_dir(dev, glue_dir);
3015 EXPORT_SYMBOL_GPL(device_add);
3018 * device_register - register a device with the system.
3019 * @dev: pointer to the device structure
3021 * This happens in two clean steps - initialize the device
3022 * and add it to the system. The two steps can be called
3023 * separately, but this is the easiest and most common.
3024 * I.e. you should only call the two helpers separately if
3025 * have a clearly defined need to use and refcount the device
3026 * before it is added to the hierarchy.
3028 * For more information, see the kerneldoc for device_initialize()
3031 * NOTE: _Never_ directly free @dev after calling this function, even
3032 * if it returned an error! Always use put_device() to give up the
3033 * reference initialized in this function instead.
3035 int device_register(struct device *dev)
3037 device_initialize(dev);
3038 return device_add(dev);
3040 EXPORT_SYMBOL_GPL(device_register);
3043 * get_device - increment reference count for device.
3046 * This simply forwards the call to kobject_get(), though
3047 * we do take care to provide for the case that we get a NULL
3048 * pointer passed in.
3050 struct device *get_device(struct device *dev)
3052 return dev ? kobj_to_dev(kobject_get(&dev->kobj)) : NULL;
3054 EXPORT_SYMBOL_GPL(get_device);
3057 * put_device - decrement reference count.
3058 * @dev: device in question.
3060 void put_device(struct device *dev)
3062 /* might_sleep(); */
3064 kobject_put(&dev->kobj);
3066 EXPORT_SYMBOL_GPL(put_device);
3068 bool kill_device(struct device *dev)
3071 * Require the device lock and set the "dead" flag to guarantee that
3072 * the update behavior is consistent with the other bitfields near
3073 * it and that we cannot have an asynchronous probe routine trying
3074 * to run while we are tearing out the bus/class/sysfs from
3075 * underneath the device.
3077 lockdep_assert_held(&dev->mutex);
3081 dev->p->dead = true;
3084 EXPORT_SYMBOL_GPL(kill_device);
3087 * device_del - delete device from system.
3090 * This is the first part of the device unregistration
3091 * sequence. This removes the device from the lists we control
3092 * from here, has it removed from the other driver model
3093 * subsystems it was added to in device_add(), and removes it
3094 * from the kobject hierarchy.
3096 * NOTE: this should be called manually _iff_ device_add() was
3097 * also called manually.
3099 void device_del(struct device *dev)
3101 struct device *parent = dev->parent;
3102 struct kobject *glue_dir = NULL;
3103 struct class_interface *class_intf;
3104 unsigned int noio_flag;
3110 if (dev->fwnode && dev->fwnode->dev == dev)
3111 dev->fwnode->dev = NULL;
3113 /* Notify clients of device removal. This call must come
3114 * before dpm_sysfs_remove().
3116 noio_flag = memalloc_noio_save();
3118 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
3119 BUS_NOTIFY_DEL_DEVICE, dev);
3121 dpm_sysfs_remove(dev);
3123 klist_del(&dev->p->knode_parent);
3124 if (MAJOR(dev->devt)) {
3125 devtmpfs_delete_node(dev);
3126 device_remove_sys_dev_entry(dev);
3127 device_remove_file(dev, &dev_attr_dev);
3130 device_remove_class_symlinks(dev);
3132 mutex_lock(&dev->class->p->mutex);
3133 /* notify any interfaces that the device is now gone */
3134 list_for_each_entry(class_intf,
3135 &dev->class->p->interfaces, node)
3136 if (class_intf->remove_dev)
3137 class_intf->remove_dev(dev, class_intf);
3138 /* remove the device from the class list */
3139 klist_del(&dev->p->knode_class);
3140 mutex_unlock(&dev->class->p->mutex);
3142 device_remove_file(dev, &dev_attr_uevent);
3143 device_remove_attrs(dev);
3144 bus_remove_device(dev);
3145 device_pm_remove(dev);
3146 driver_deferred_probe_del(dev);
3147 device_platform_notify(dev, KOBJ_REMOVE);
3148 device_remove_properties(dev);
3149 device_links_purge(dev);
3152 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
3153 BUS_NOTIFY_REMOVED_DEVICE, dev);
3154 kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3155 glue_dir = get_glue_dir(dev);
3156 kobject_del(&dev->kobj);
3157 cleanup_glue_dir(dev, glue_dir);
3158 memalloc_noio_restore(noio_flag);
3161 EXPORT_SYMBOL_GPL(device_del);
3164 * device_unregister - unregister device from system.
3165 * @dev: device going away.
3167 * We do this in two parts, like we do device_register(). First,
3168 * we remove it from all the subsystems with device_del(), then
3169 * we decrement the reference count via put_device(). If that
3170 * is the final reference count, the device will be cleaned up
3171 * via device_release() above. Otherwise, the structure will
3172 * stick around until the final reference to the device is dropped.
3174 void device_unregister(struct device *dev)
3176 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3180 EXPORT_SYMBOL_GPL(device_unregister);
3182 static struct device *prev_device(struct klist_iter *i)
3184 struct klist_node *n = klist_prev(i);
3185 struct device *dev = NULL;
3186 struct device_private *p;
3189 p = to_device_private_parent(n);
3195 static struct device *next_device(struct klist_iter *i)
3197 struct klist_node *n = klist_next(i);
3198 struct device *dev = NULL;
3199 struct device_private *p;
3202 p = to_device_private_parent(n);
3209 * device_get_devnode - path of device node file
3211 * @mode: returned file access mode
3212 * @uid: returned file owner
3213 * @gid: returned file group
3214 * @tmp: possibly allocated string
3216 * Return the relative path of a possible device node.
3217 * Non-default names may need to allocate a memory to compose
3218 * a name. This memory is returned in tmp and needs to be
3219 * freed by the caller.
3221 const char *device_get_devnode(struct device *dev,
3222 umode_t *mode, kuid_t *uid, kgid_t *gid,
3229 /* the device type may provide a specific name */
3230 if (dev->type && dev->type->devnode)
3231 *tmp = dev->type->devnode(dev, mode, uid, gid);
3235 /* the class may provide a specific name */
3236 if (dev->class && dev->class->devnode)
3237 *tmp = dev->class->devnode(dev, mode);
3241 /* return name without allocation, tmp == NULL */
3242 if (strchr(dev_name(dev), '!') == NULL)
3243 return dev_name(dev);
3245 /* replace '!' in the name with '/' */
3246 s = kstrdup(dev_name(dev), GFP_KERNEL);
3249 strreplace(s, '!', '/');
3254 * device_for_each_child - device child iterator.
3255 * @parent: parent struct device.
3256 * @fn: function to be called for each device.
3257 * @data: data for the callback.
3259 * Iterate over @parent's child devices, and call @fn for each,
3262 * We check the return of @fn each time. If it returns anything
3263 * other than 0, we break out and return that value.
3265 int device_for_each_child(struct device *parent, void *data,
3266 int (*fn)(struct device *dev, void *data))
3268 struct klist_iter i;
3269 struct device *child;
3275 klist_iter_init(&parent->p->klist_children, &i);
3276 while (!error && (child = next_device(&i)))
3277 error = fn(child, data);
3278 klist_iter_exit(&i);
3281 EXPORT_SYMBOL_GPL(device_for_each_child);
3284 * device_for_each_child_reverse - device child iterator in reversed order.
3285 * @parent: parent struct device.
3286 * @fn: function to be called for each device.
3287 * @data: data for the callback.
3289 * Iterate over @parent's child devices, and call @fn for each,
3292 * We check the return of @fn each time. If it returns anything
3293 * other than 0, we break out and return that value.
3295 int device_for_each_child_reverse(struct device *parent, void *data,
3296 int (*fn)(struct device *dev, void *data))
3298 struct klist_iter i;
3299 struct device *child;
3305 klist_iter_init(&parent->p->klist_children, &i);
3306 while ((child = prev_device(&i)) && !error)
3307 error = fn(child, data);
3308 klist_iter_exit(&i);
3311 EXPORT_SYMBOL_GPL(device_for_each_child_reverse);
3314 * device_find_child - device iterator for locating a particular device.
3315 * @parent: parent struct device
3316 * @match: Callback function to check device
3317 * @data: Data to pass to match function
3319 * This is similar to the device_for_each_child() function above, but it
3320 * returns a reference to a device that is 'found' for later use, as
3321 * determined by the @match callback.
3323 * The callback should return 0 if the device doesn't match and non-zero
3324 * if it does. If the callback returns non-zero and a reference to the
3325 * current device can be obtained, this function will return to the caller
3326 * and not iterate over any more devices.
3328 * NOTE: you will need to drop the reference with put_device() after use.
3330 struct device *device_find_child(struct device *parent, void *data,
3331 int (*match)(struct device *dev, void *data))
3333 struct klist_iter i;
3334 struct device *child;
3339 klist_iter_init(&parent->p->klist_children, &i);
3340 while ((child = next_device(&i)))
3341 if (match(child, data) && get_device(child))
3343 klist_iter_exit(&i);
3346 EXPORT_SYMBOL_GPL(device_find_child);
3349 * device_find_child_by_name - device iterator for locating a child device.
3350 * @parent: parent struct device
3351 * @name: name of the child device
3353 * This is similar to the device_find_child() function above, but it
3354 * returns a reference to a device that has the name @name.
3356 * NOTE: you will need to drop the reference with put_device() after use.
3358 struct device *device_find_child_by_name(struct device *parent,
3361 struct klist_iter i;
3362 struct device *child;
3367 klist_iter_init(&parent->p->klist_children, &i);
3368 while ((child = next_device(&i)))
3369 if (sysfs_streq(dev_name(child), name) && get_device(child))
3371 klist_iter_exit(&i);
3374 EXPORT_SYMBOL_GPL(device_find_child_by_name);
3376 int __init devices_init(void)
3378 devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
3381 dev_kobj = kobject_create_and_add("dev", NULL);
3384 sysfs_dev_block_kobj = kobject_create_and_add("block", dev_kobj);
3385 if (!sysfs_dev_block_kobj)
3386 goto block_kobj_err;
3387 sysfs_dev_char_kobj = kobject_create_and_add("char", dev_kobj);
3388 if (!sysfs_dev_char_kobj)
3394 kobject_put(sysfs_dev_block_kobj);
3396 kobject_put(dev_kobj);
3398 kset_unregister(devices_kset);
3402 static int device_check_offline(struct device *dev, void *not_used)
3406 ret = device_for_each_child(dev, NULL, device_check_offline);
3410 return device_supports_offline(dev) && !dev->offline ? -EBUSY : 0;
3414 * device_offline - Prepare the device for hot-removal.
3415 * @dev: Device to be put offline.
3417 * Execute the device bus type's .offline() callback, if present, to prepare
3418 * the device for a subsequent hot-removal. If that succeeds, the device must
3419 * not be used until either it is removed or its bus type's .online() callback
3422 * Call under device_hotplug_lock.
3424 int device_offline(struct device *dev)
3428 if (dev->offline_disabled)
3431 ret = device_for_each_child(dev, NULL, device_check_offline);
3436 if (device_supports_offline(dev)) {
3440 ret = dev->bus->offline(dev);
3442 kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
3443 dev->offline = true;
3453 * device_online - Put the device back online after successful device_offline().
3454 * @dev: Device to be put back online.
3456 * If device_offline() has been successfully executed for @dev, but the device
3457 * has not been removed subsequently, execute its bus type's .online() callback
3458 * to indicate that the device can be used again.
3460 * Call under device_hotplug_lock.
3462 int device_online(struct device *dev)
3467 if (device_supports_offline(dev)) {
3469 ret = dev->bus->online(dev);
3471 kobject_uevent(&dev->kobj, KOBJ_ONLINE);
3472 dev->offline = false;
3483 struct root_device {
3485 struct module *owner;
3488 static inline struct root_device *to_root_device(struct device *d)
3490 return container_of(d, struct root_device, dev);
3493 static void root_device_release(struct device *dev)
3495 kfree(to_root_device(dev));
3499 * __root_device_register - allocate and register a root device
3500 * @name: root device name
3501 * @owner: owner module of the root device, usually THIS_MODULE
3503 * This function allocates a root device and registers it
3504 * using device_register(). In order to free the returned
3505 * device, use root_device_unregister().
3507 * Root devices are dummy devices which allow other devices
3508 * to be grouped under /sys/devices. Use this function to
3509 * allocate a root device and then use it as the parent of
3510 * any device which should appear under /sys/devices/{name}
3512 * The /sys/devices/{name} directory will also contain a
3513 * 'module' symlink which points to the @owner directory
3516 * Returns &struct device pointer on success, or ERR_PTR() on error.
3518 * Note: You probably want to use root_device_register().
3520 struct device *__root_device_register(const char *name, struct module *owner)
3522 struct root_device *root;
3525 root = kzalloc(sizeof(struct root_device), GFP_KERNEL);
3527 return ERR_PTR(err);
3529 err = dev_set_name(&root->dev, "%s", name);
3532 return ERR_PTR(err);
3535 root->dev.release = root_device_release;
3537 err = device_register(&root->dev);
3539 put_device(&root->dev);
3540 return ERR_PTR(err);
3543 #ifdef CONFIG_MODULES /* gotta find a "cleaner" way to do this */
3545 struct module_kobject *mk = &owner->mkobj;
3547 err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module");
3549 device_unregister(&root->dev);
3550 return ERR_PTR(err);
3552 root->owner = owner;
3558 EXPORT_SYMBOL_GPL(__root_device_register);
3561 * root_device_unregister - unregister and free a root device
3562 * @dev: device going away
3564 * This function unregisters and cleans up a device that was created by
3565 * root_device_register().
3567 void root_device_unregister(struct device *dev)
3569 struct root_device *root = to_root_device(dev);
3572 sysfs_remove_link(&root->dev.kobj, "module");
3574 device_unregister(dev);
3576 EXPORT_SYMBOL_GPL(root_device_unregister);
3579 static void device_create_release(struct device *dev)
3581 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3585 static __printf(6, 0) struct device *
3586 device_create_groups_vargs(struct class *class, struct device *parent,
3587 dev_t devt, void *drvdata,
3588 const struct attribute_group **groups,
3589 const char *fmt, va_list args)
3591 struct device *dev = NULL;
3592 int retval = -ENODEV;
3594 if (class == NULL || IS_ERR(class))
3597 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3603 device_initialize(dev);
3606 dev->parent = parent;
3607 dev->groups = groups;
3608 dev->release = device_create_release;
3609 dev_set_drvdata(dev, drvdata);
3611 retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
3615 retval = device_add(dev);
3623 return ERR_PTR(retval);
3627 * device_create - creates a device and registers it with sysfs
3628 * @class: pointer to the struct class that this device should be registered to
3629 * @parent: pointer to the parent struct device of this new device, if any
3630 * @devt: the dev_t for the char device to be added
3631 * @drvdata: the data to be added to the device for callbacks
3632 * @fmt: string for the device's name
3634 * This function can be used by char device classes. A struct device
3635 * will be created in sysfs, registered to the specified class.
3637 * A "dev" file will be created, showing the dev_t for the device, if
3638 * the dev_t is not 0,0.
3639 * If a pointer to a parent struct device is passed in, the newly created
3640 * struct device will be a child of that device in sysfs.
3641 * The pointer to the struct device will be returned from the call.
3642 * Any further sysfs files that might be required can be created using this
3645 * Returns &struct device pointer on success, or ERR_PTR() on error.
3647 * Note: the struct class passed to this function must have previously
3648 * been created with a call to class_create().
3650 struct device *device_create(struct class *class, struct device *parent,
3651 dev_t devt, void *drvdata, const char *fmt, ...)
3656 va_start(vargs, fmt);
3657 dev = device_create_groups_vargs(class, parent, devt, drvdata, NULL,
3662 EXPORT_SYMBOL_GPL(device_create);
3665 * device_create_with_groups - creates a device and registers it with sysfs
3666 * @class: pointer to the struct class that this device should be registered to
3667 * @parent: pointer to the parent struct device of this new device, if any
3668 * @devt: the dev_t for the char device to be added
3669 * @drvdata: the data to be added to the device for callbacks
3670 * @groups: NULL-terminated list of attribute groups to be created
3671 * @fmt: string for the device's name
3673 * This function can be used by char device classes. A struct device
3674 * will be created in sysfs, registered to the specified class.
3675 * Additional attributes specified in the groups parameter will also
3676 * be created automatically.
3678 * A "dev" file will be created, showing the dev_t for the device, if
3679 * the dev_t is not 0,0.
3680 * If a pointer to a parent struct device is passed in, the newly created
3681 * struct device will be a child of that device in sysfs.
3682 * The pointer to the struct device will be returned from the call.
3683 * Any further sysfs files that might be required can be created using this
3686 * Returns &struct device pointer on success, or ERR_PTR() on error.
3688 * Note: the struct class passed to this function must have previously
3689 * been created with a call to class_create().
3691 struct device *device_create_with_groups(struct class *class,
3692 struct device *parent, dev_t devt,
3694 const struct attribute_group **groups,
3695 const char *fmt, ...)
3700 va_start(vargs, fmt);
3701 dev = device_create_groups_vargs(class, parent, devt, drvdata, groups,
3706 EXPORT_SYMBOL_GPL(device_create_with_groups);
3709 * device_destroy - removes a device that was created with device_create()
3710 * @class: pointer to the struct class that this device was registered with
3711 * @devt: the dev_t of the device that was previously registered
3713 * This call unregisters and cleans up a device that was created with a
3714 * call to device_create().
3716 void device_destroy(struct class *class, dev_t devt)
3720 dev = class_find_device_by_devt(class, devt);
3723 device_unregister(dev);
3726 EXPORT_SYMBOL_GPL(device_destroy);
3729 * device_rename - renames a device
3730 * @dev: the pointer to the struct device to be renamed
3731 * @new_name: the new name of the device
3733 * It is the responsibility of the caller to provide mutual
3734 * exclusion between two different calls of device_rename
3735 * on the same device to ensure that new_name is valid and
3736 * won't conflict with other devices.
3738 * Note: Don't call this function. Currently, the networking layer calls this
3739 * function, but that will change. The following text from Kay Sievers offers
3742 * Renaming devices is racy at many levels, symlinks and other stuff are not
3743 * replaced atomically, and you get a "move" uevent, but it's not easy to
3744 * connect the event to the old and new device. Device nodes are not renamed at
3745 * all, there isn't even support for that in the kernel now.
3747 * In the meantime, during renaming, your target name might be taken by another
3748 * driver, creating conflicts. Or the old name is taken directly after you
3749 * renamed it -- then you get events for the same DEVPATH, before you even see
3750 * the "move" event. It's just a mess, and nothing new should ever rely on
3751 * kernel device renaming. Besides that, it's not even implemented now for
3752 * other things than (driver-core wise very simple) network devices.
3754 * We are currently about to change network renaming in udev to completely
3755 * disallow renaming of devices in the same namespace as the kernel uses,
3756 * because we can't solve the problems properly, that arise with swapping names
3757 * of multiple interfaces without races. Means, renaming of eth[0-9]* will only
3758 * be allowed to some other name than eth[0-9]*, for the aforementioned
3761 * Make up a "real" name in the driver before you register anything, or add
3762 * some other attributes for userspace to find the device, or use udev to add
3763 * symlinks -- but never rename kernel devices later, it's a complete mess. We
3764 * don't even want to get into that and try to implement the missing pieces in
3765 * the core. We really have other pieces to fix in the driver core mess. :)
3767 int device_rename(struct device *dev, const char *new_name)
3769 struct kobject *kobj = &dev->kobj;
3770 char *old_device_name = NULL;
3773 dev = get_device(dev);
3777 dev_dbg(dev, "renaming to %s\n", new_name);
3779 old_device_name = kstrdup(dev_name(dev), GFP_KERNEL);
3780 if (!old_device_name) {
3786 error = sysfs_rename_link_ns(&dev->class->p->subsys.kobj,
3787 kobj, old_device_name,
3788 new_name, kobject_namespace(kobj));
3793 error = kobject_rename(kobj, new_name);
3800 kfree(old_device_name);
3804 EXPORT_SYMBOL_GPL(device_rename);
3806 static int device_move_class_links(struct device *dev,
3807 struct device *old_parent,
3808 struct device *new_parent)
3813 sysfs_remove_link(&dev->kobj, "device");
3815 error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
3821 * device_move - moves a device to a new parent
3822 * @dev: the pointer to the struct device to be moved
3823 * @new_parent: the new parent of the device (can be NULL)
3824 * @dpm_order: how to reorder the dpm_list
3826 int device_move(struct device *dev, struct device *new_parent,
3827 enum dpm_order dpm_order)
3830 struct device *old_parent;
3831 struct kobject *new_parent_kobj;
3833 dev = get_device(dev);
3838 new_parent = get_device(new_parent);
3839 new_parent_kobj = get_device_parent(dev, new_parent);
3840 if (IS_ERR(new_parent_kobj)) {
3841 error = PTR_ERR(new_parent_kobj);
3842 put_device(new_parent);
3846 pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev),
3847 __func__, new_parent ? dev_name(new_parent) : "<NULL>");
3848 error = kobject_move(&dev->kobj, new_parent_kobj);
3850 cleanup_glue_dir(dev, new_parent_kobj);
3851 put_device(new_parent);
3854 old_parent = dev->parent;
3855 dev->parent = new_parent;
3857 klist_remove(&dev->p->knode_parent);
3859 klist_add_tail(&dev->p->knode_parent,
3860 &new_parent->p->klist_children);
3861 set_dev_node(dev, dev_to_node(new_parent));
3865 error = device_move_class_links(dev, old_parent, new_parent);
3867 /* We ignore errors on cleanup since we're hosed anyway... */
3868 device_move_class_links(dev, new_parent, old_parent);
3869 if (!kobject_move(&dev->kobj, &old_parent->kobj)) {
3871 klist_remove(&dev->p->knode_parent);
3872 dev->parent = old_parent;
3874 klist_add_tail(&dev->p->knode_parent,
3875 &old_parent->p->klist_children);
3876 set_dev_node(dev, dev_to_node(old_parent));
3879 cleanup_glue_dir(dev, new_parent_kobj);
3880 put_device(new_parent);
3884 switch (dpm_order) {
3885 case DPM_ORDER_NONE:
3887 case DPM_ORDER_DEV_AFTER_PARENT:
3888 device_pm_move_after(dev, new_parent);
3889 devices_kset_move_after(dev, new_parent);
3891 case DPM_ORDER_PARENT_BEFORE_DEV:
3892 device_pm_move_before(new_parent, dev);
3893 devices_kset_move_before(new_parent, dev);
3895 case DPM_ORDER_DEV_LAST:
3896 device_pm_move_last(dev);
3897 devices_kset_move_last(dev);
3901 put_device(old_parent);
3907 EXPORT_SYMBOL_GPL(device_move);
3909 static int device_attrs_change_owner(struct device *dev, kuid_t kuid,
3912 struct kobject *kobj = &dev->kobj;
3913 struct class *class = dev->class;
3914 const struct device_type *type = dev->type;
3919 * Change the device groups of the device class for @dev to
3922 error = sysfs_groups_change_owner(kobj, class->dev_groups, kuid,
3930 * Change the device groups of the device type for @dev to
3933 error = sysfs_groups_change_owner(kobj, type->groups, kuid,
3939 /* Change the device groups of @dev to @kuid/@kgid. */
3940 error = sysfs_groups_change_owner(kobj, dev->groups, kuid, kgid);
3944 if (device_supports_offline(dev) && !dev->offline_disabled) {
3945 /* Change online device attributes of @dev to @kuid/@kgid. */
3946 error = sysfs_file_change_owner(kobj, dev_attr_online.attr.name,
3956 * device_change_owner - change the owner of an existing device.
3958 * @kuid: new owner's kuid
3959 * @kgid: new owner's kgid
3961 * This changes the owner of @dev and its corresponding sysfs entries to
3962 * @kuid/@kgid. This function closely mirrors how @dev was added via driver
3965 * Returns 0 on success or error code on failure.
3967 int device_change_owner(struct device *dev, kuid_t kuid, kgid_t kgid)
3970 struct kobject *kobj = &dev->kobj;
3972 dev = get_device(dev);
3977 * Change the kobject and the default attributes and groups of the
3978 * ktype associated with it to @kuid/@kgid.
3980 error = sysfs_change_owner(kobj, kuid, kgid);
3985 * Change the uevent file for @dev to the new owner. The uevent file
3986 * was created in a separate step when @dev got added and we mirror
3989 error = sysfs_file_change_owner(kobj, dev_attr_uevent.attr.name, kuid,
3995 * Change the device groups, the device groups associated with the
3996 * device class, and the groups associated with the device type of @dev
3999 error = device_attrs_change_owner(dev, kuid, kgid);
4003 error = dpm_sysfs_change_owner(dev, kuid, kgid);
4008 if (sysfs_deprecated && dev->class == &block_class)
4013 * Change the owner of the symlink located in the class directory of
4014 * the device class associated with @dev which points to the actual
4015 * directory entry for @dev to @kuid/@kgid. This ensures that the
4016 * symlink shows the same permissions as its target.
4018 error = sysfs_link_change_owner(&dev->class->p->subsys.kobj, &dev->kobj,
4019 dev_name(dev), kuid, kgid);
4027 EXPORT_SYMBOL_GPL(device_change_owner);
4030 * device_shutdown - call ->shutdown() on each device to shutdown.
4032 void device_shutdown(void)
4034 struct device *dev, *parent;
4036 wait_for_device_probe();
4037 device_block_probing();
4041 spin_lock(&devices_kset->list_lock);
4043 * Walk the devices list backward, shutting down each in turn.
4044 * Beware that device unplug events may also start pulling
4045 * devices offline, even as the system is shutting down.
4047 while (!list_empty(&devices_kset->list)) {
4048 dev = list_entry(devices_kset->list.prev, struct device,
4052 * hold reference count of device's parent to
4053 * prevent it from being freed because parent's
4054 * lock is to be held
4056 parent = get_device(dev->parent);
4059 * Make sure the device is off the kset list, in the
4060 * event that dev->*->shutdown() doesn't remove it.
4062 list_del_init(&dev->kobj.entry);
4063 spin_unlock(&devices_kset->list_lock);
4065 /* hold lock to avoid race with probe/release */
4067 device_lock(parent);
4070 /* Don't allow any more runtime suspends */
4071 pm_runtime_get_noresume(dev);
4072 pm_runtime_barrier(dev);
4074 if (dev->class && dev->class->shutdown_pre) {
4076 dev_info(dev, "shutdown_pre\n");
4077 dev->class->shutdown_pre(dev);
4079 if (dev->bus && dev->bus->shutdown) {
4081 dev_info(dev, "shutdown\n");
4082 dev->bus->shutdown(dev);
4083 } else if (dev->driver && dev->driver->shutdown) {
4085 dev_info(dev, "shutdown\n");
4086 dev->driver->shutdown(dev);
4091 device_unlock(parent);
4096 spin_lock(&devices_kset->list_lock);
4098 spin_unlock(&devices_kset->list_lock);
4102 * Device logging functions
4105 #ifdef CONFIG_PRINTK
4107 set_dev_info(const struct device *dev, struct dev_printk_info *dev_info)
4111 memset(dev_info, 0, sizeof(*dev_info));
4114 subsys = dev->class->name;
4116 subsys = dev->bus->name;
4120 strscpy(dev_info->subsystem, subsys, sizeof(dev_info->subsystem));
4123 * Add device identifier DEVICE=:
4127 * +sound:card0 subsystem:devname
4129 if (MAJOR(dev->devt)) {
4132 if (strcmp(subsys, "block") == 0)
4137 snprintf(dev_info->device, sizeof(dev_info->device),
4138 "%c%u:%u", c, MAJOR(dev->devt), MINOR(dev->devt));
4139 } else if (strcmp(subsys, "net") == 0) {
4140 struct net_device *net = to_net_dev(dev);
4142 snprintf(dev_info->device, sizeof(dev_info->device),
4143 "n%u", net->ifindex);
4145 snprintf(dev_info->device, sizeof(dev_info->device),
4146 "+%s:%s", subsys, dev_name(dev));
4150 int dev_vprintk_emit(int level, const struct device *dev,
4151 const char *fmt, va_list args)
4153 struct dev_printk_info dev_info;
4155 set_dev_info(dev, &dev_info);
4157 return vprintk_emit(0, level, &dev_info, fmt, args);
4159 EXPORT_SYMBOL(dev_vprintk_emit);
4161 int dev_printk_emit(int level, const struct device *dev, const char *fmt, ...)
4166 va_start(args, fmt);
4168 r = dev_vprintk_emit(level, dev, fmt, args);
4174 EXPORT_SYMBOL(dev_printk_emit);
4176 static void __dev_printk(const char *level, const struct device *dev,
4177 struct va_format *vaf)
4180 dev_printk_emit(level[1] - '0', dev, "%s %s: %pV",
4181 dev_driver_string(dev), dev_name(dev), vaf);
4183 printk("%s(NULL device *): %pV", level, vaf);
4186 void dev_printk(const char *level, const struct device *dev,
4187 const char *fmt, ...)
4189 struct va_format vaf;
4192 va_start(args, fmt);
4197 __dev_printk(level, dev, &vaf);
4201 EXPORT_SYMBOL(dev_printk);
4203 #define define_dev_printk_level(func, kern_level) \
4204 void func(const struct device *dev, const char *fmt, ...) \
4206 struct va_format vaf; \
4209 va_start(args, fmt); \
4214 __dev_printk(kern_level, dev, &vaf); \
4218 EXPORT_SYMBOL(func);
4220 define_dev_printk_level(_dev_emerg, KERN_EMERG);
4221 define_dev_printk_level(_dev_alert, KERN_ALERT);
4222 define_dev_printk_level(_dev_crit, KERN_CRIT);
4223 define_dev_printk_level(_dev_err, KERN_ERR);
4224 define_dev_printk_level(_dev_warn, KERN_WARNING);
4225 define_dev_printk_level(_dev_notice, KERN_NOTICE);
4226 define_dev_printk_level(_dev_info, KERN_INFO);
4231 * dev_err_probe - probe error check and log helper
4232 * @dev: the pointer to the struct device
4233 * @err: error value to test
4234 * @fmt: printf-style format string
4235 * @...: arguments as specified in the format string
4237 * This helper implements common pattern present in probe functions for error
4238 * checking: print debug or error message depending if the error value is
4239 * -EPROBE_DEFER and propagate error upwards.
4240 * In case of -EPROBE_DEFER it sets also defer probe reason, which can be
4241 * checked later by reading devices_deferred debugfs attribute.
4242 * It replaces code sequence::
4244 * if (err != -EPROBE_DEFER)
4245 * dev_err(dev, ...);
4247 * dev_dbg(dev, ...);
4252 * return dev_err_probe(dev, err, ...);
4257 int dev_err_probe(const struct device *dev, int err, const char *fmt, ...)
4259 struct va_format vaf;
4262 va_start(args, fmt);
4266 if (err != -EPROBE_DEFER) {
4267 dev_err(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
4269 device_set_deferred_probe_reason(dev, &vaf);
4270 dev_dbg(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
4277 EXPORT_SYMBOL_GPL(dev_err_probe);
4279 static inline bool fwnode_is_primary(struct fwnode_handle *fwnode)
4281 return fwnode && !IS_ERR(fwnode->secondary);
4285 * set_primary_fwnode - Change the primary firmware node of a given device.
4286 * @dev: Device to handle.
4287 * @fwnode: New primary firmware node of the device.
4289 * Set the device's firmware node pointer to @fwnode, but if a secondary
4290 * firmware node of the device is present, preserve it.
4292 void set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
4294 struct device *parent = dev->parent;
4295 struct fwnode_handle *fn = dev->fwnode;
4298 if (fwnode_is_primary(fn))
4302 WARN_ON(fwnode->secondary);
4303 fwnode->secondary = fn;
4305 dev->fwnode = fwnode;
4307 if (fwnode_is_primary(fn)) {
4308 dev->fwnode = fn->secondary;
4309 if (!(parent && fn == parent->fwnode))
4310 fn->secondary = NULL;
4316 EXPORT_SYMBOL_GPL(set_primary_fwnode);
4319 * set_secondary_fwnode - Change the secondary firmware node of a given device.
4320 * @dev: Device to handle.
4321 * @fwnode: New secondary firmware node of the device.
4323 * If a primary firmware node of the device is present, set its secondary
4324 * pointer to @fwnode. Otherwise, set the device's firmware node pointer to
4327 void set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
4330 fwnode->secondary = ERR_PTR(-ENODEV);
4332 if (fwnode_is_primary(dev->fwnode))
4333 dev->fwnode->secondary = fwnode;
4335 dev->fwnode = fwnode;
4337 EXPORT_SYMBOL_GPL(set_secondary_fwnode);
4340 * device_set_of_node_from_dev - reuse device-tree node of another device
4341 * @dev: device whose device-tree node is being set
4342 * @dev2: device whose device-tree node is being reused
4344 * Takes another reference to the new device-tree node after first dropping
4345 * any reference held to the old node.
4347 void device_set_of_node_from_dev(struct device *dev, const struct device *dev2)
4349 of_node_put(dev->of_node);
4350 dev->of_node = of_node_get(dev2->of_node);
4351 dev->of_node_reused = true;
4353 EXPORT_SYMBOL_GPL(device_set_of_node_from_dev);
4355 int device_match_name(struct device *dev, const void *name)
4357 return sysfs_streq(dev_name(dev), name);
4359 EXPORT_SYMBOL_GPL(device_match_name);
4361 int device_match_of_node(struct device *dev, const void *np)
4363 return dev->of_node == np;
4365 EXPORT_SYMBOL_GPL(device_match_of_node);
4367 int device_match_fwnode(struct device *dev, const void *fwnode)
4369 return dev_fwnode(dev) == fwnode;
4371 EXPORT_SYMBOL_GPL(device_match_fwnode);
4373 int device_match_devt(struct device *dev, const void *pdevt)
4375 return dev->devt == *(dev_t *)pdevt;
4377 EXPORT_SYMBOL_GPL(device_match_devt);
4379 int device_match_acpi_dev(struct device *dev, const void *adev)
4381 return ACPI_COMPANION(dev) == adev;
4383 EXPORT_SYMBOL(device_match_acpi_dev);
4385 int device_match_any(struct device *dev, const void *unused)
4389 EXPORT_SYMBOL_GPL(device_match_any);