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/blkdev.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/swiotlb.h>
31 #include <linux/sysfs.h>
32 #include <linux/dma-map-ops.h> /* for dma_default_coherent */
35 #include "physical_location.h"
36 #include "power/power.h"
38 #ifdef CONFIG_SYSFS_DEPRECATED
39 #ifdef CONFIG_SYSFS_DEPRECATED_V2
40 long sysfs_deprecated = 1;
42 long sysfs_deprecated = 0;
44 static int __init sysfs_deprecated_setup(char *arg)
46 return kstrtol(arg, 10, &sysfs_deprecated);
48 early_param("sysfs.deprecated", sysfs_deprecated_setup);
51 /* Device links support. */
52 static LIST_HEAD(deferred_sync);
53 static unsigned int defer_sync_state_count = 1;
54 static DEFINE_MUTEX(fwnode_link_lock);
55 static bool fw_devlink_is_permissive(void);
56 static void __fw_devlink_link_to_consumers(struct device *dev);
57 static bool fw_devlink_drv_reg_done;
58 static bool fw_devlink_best_effort;
61 * __fwnode_link_add - Create a link between two fwnode_handles.
62 * @con: Consumer end of the link.
63 * @sup: Supplier end of the link.
65 * Create a fwnode link between fwnode handles @con and @sup. The fwnode link
66 * represents the detail that the firmware lists @sup fwnode as supplying a
69 * The driver core will use the fwnode link to create a device link between the
70 * two device objects corresponding to @con and @sup when they are created. The
71 * driver core will automatically delete the fwnode link between @con and @sup
74 * Attempts to create duplicate links between the same pair of fwnode handles
75 * are ignored and there is no reference counting.
77 static int __fwnode_link_add(struct fwnode_handle *con,
78 struct fwnode_handle *sup, u8 flags)
80 struct fwnode_link *link;
82 list_for_each_entry(link, &sup->consumers, s_hook)
83 if (link->consumer == con) {
88 link = kzalloc(sizeof(*link), GFP_KERNEL);
93 INIT_LIST_HEAD(&link->s_hook);
95 INIT_LIST_HEAD(&link->c_hook);
98 list_add(&link->s_hook, &sup->consumers);
99 list_add(&link->c_hook, &con->suppliers);
100 pr_debug("%pfwP Linked as a fwnode consumer to %pfwP\n",
106 int fwnode_link_add(struct fwnode_handle *con, struct fwnode_handle *sup)
110 mutex_lock(&fwnode_link_lock);
111 ret = __fwnode_link_add(con, sup, 0);
112 mutex_unlock(&fwnode_link_lock);
117 * __fwnode_link_del - Delete a link between two fwnode_handles.
118 * @link: the fwnode_link to be deleted
120 * The fwnode_link_lock needs to be held when this function is called.
122 static void __fwnode_link_del(struct fwnode_link *link)
124 pr_debug("%pfwP Dropping the fwnode link to %pfwP\n",
125 link->consumer, link->supplier);
126 list_del(&link->s_hook);
127 list_del(&link->c_hook);
132 * __fwnode_link_cycle - Mark a fwnode link as being part of a cycle.
133 * @link: the fwnode_link to be marked
135 * The fwnode_link_lock needs to be held when this function is called.
137 static void __fwnode_link_cycle(struct fwnode_link *link)
139 pr_debug("%pfwf: Relaxing link with %pfwf\n",
140 link->consumer, link->supplier);
141 link->flags |= FWLINK_FLAG_CYCLE;
145 * fwnode_links_purge_suppliers - Delete all supplier links of fwnode_handle.
146 * @fwnode: fwnode whose supplier links need to be deleted
148 * Deletes all supplier links connecting directly to @fwnode.
150 static void fwnode_links_purge_suppliers(struct fwnode_handle *fwnode)
152 struct fwnode_link *link, *tmp;
154 mutex_lock(&fwnode_link_lock);
155 list_for_each_entry_safe(link, tmp, &fwnode->suppliers, c_hook)
156 __fwnode_link_del(link);
157 mutex_unlock(&fwnode_link_lock);
161 * fwnode_links_purge_consumers - Delete all consumer links of fwnode_handle.
162 * @fwnode: fwnode whose consumer links need to be deleted
164 * Deletes all consumer links connecting directly to @fwnode.
166 static void fwnode_links_purge_consumers(struct fwnode_handle *fwnode)
168 struct fwnode_link *link, *tmp;
170 mutex_lock(&fwnode_link_lock);
171 list_for_each_entry_safe(link, tmp, &fwnode->consumers, s_hook)
172 __fwnode_link_del(link);
173 mutex_unlock(&fwnode_link_lock);
177 * fwnode_links_purge - Delete all links connected to a fwnode_handle.
178 * @fwnode: fwnode whose links needs to be deleted
180 * Deletes all links connecting directly to a fwnode.
182 void fwnode_links_purge(struct fwnode_handle *fwnode)
184 fwnode_links_purge_suppliers(fwnode);
185 fwnode_links_purge_consumers(fwnode);
188 void fw_devlink_purge_absent_suppliers(struct fwnode_handle *fwnode)
190 struct fwnode_handle *child;
192 /* Don't purge consumer links of an added child */
196 fwnode->flags |= FWNODE_FLAG_NOT_DEVICE;
197 fwnode_links_purge_consumers(fwnode);
199 fwnode_for_each_available_child_node(fwnode, child)
200 fw_devlink_purge_absent_suppliers(child);
202 EXPORT_SYMBOL_GPL(fw_devlink_purge_absent_suppliers);
205 * __fwnode_links_move_consumers - Move consumer from @from to @to fwnode_handle
206 * @from: move consumers away from this fwnode
207 * @to: move consumers to this fwnode
209 * Move all consumer links from @from fwnode to @to fwnode.
211 static void __fwnode_links_move_consumers(struct fwnode_handle *from,
212 struct fwnode_handle *to)
214 struct fwnode_link *link, *tmp;
216 list_for_each_entry_safe(link, tmp, &from->consumers, s_hook) {
217 __fwnode_link_add(link->consumer, to, link->flags);
218 __fwnode_link_del(link);
223 * __fw_devlink_pickup_dangling_consumers - Pick up dangling consumers
224 * @fwnode: fwnode from which to pick up dangling consumers
225 * @new_sup: fwnode of new supplier
227 * If the @fwnode has a corresponding struct device and the device supports
228 * probing (that is, added to a bus), then we want to let fw_devlink create
229 * MANAGED device links to this device, so leave @fwnode and its descendant's
230 * fwnode links alone.
232 * Otherwise, move its consumers to the new supplier @new_sup.
234 static void __fw_devlink_pickup_dangling_consumers(struct fwnode_handle *fwnode,
235 struct fwnode_handle *new_sup)
237 struct fwnode_handle *child;
239 if (fwnode->dev && fwnode->dev->bus)
242 fwnode->flags |= FWNODE_FLAG_NOT_DEVICE;
243 __fwnode_links_move_consumers(fwnode, new_sup);
245 fwnode_for_each_available_child_node(fwnode, child)
246 __fw_devlink_pickup_dangling_consumers(child, new_sup);
250 static DEFINE_MUTEX(device_links_lock);
251 DEFINE_STATIC_SRCU(device_links_srcu);
253 static inline void device_links_write_lock(void)
255 mutex_lock(&device_links_lock);
258 static inline void device_links_write_unlock(void)
260 mutex_unlock(&device_links_lock);
263 int device_links_read_lock(void) __acquires(&device_links_srcu)
265 return srcu_read_lock(&device_links_srcu);
268 void device_links_read_unlock(int idx) __releases(&device_links_srcu)
270 srcu_read_unlock(&device_links_srcu, idx);
273 int device_links_read_lock_held(void)
275 return srcu_read_lock_held(&device_links_srcu);
278 static void device_link_synchronize_removal(void)
280 synchronize_srcu(&device_links_srcu);
283 static void device_link_remove_from_lists(struct device_link *link)
285 list_del_rcu(&link->s_node);
286 list_del_rcu(&link->c_node);
288 #else /* !CONFIG_SRCU */
289 static DECLARE_RWSEM(device_links_lock);
291 static inline void device_links_write_lock(void)
293 down_write(&device_links_lock);
296 static inline void device_links_write_unlock(void)
298 up_write(&device_links_lock);
301 int device_links_read_lock(void)
303 down_read(&device_links_lock);
307 void device_links_read_unlock(int not_used)
309 up_read(&device_links_lock);
312 #ifdef CONFIG_DEBUG_LOCK_ALLOC
313 int device_links_read_lock_held(void)
315 return lockdep_is_held(&device_links_lock);
319 static inline void device_link_synchronize_removal(void)
323 static void device_link_remove_from_lists(struct device_link *link)
325 list_del(&link->s_node);
326 list_del(&link->c_node);
328 #endif /* !CONFIG_SRCU */
330 static bool device_is_ancestor(struct device *dev, struct device *target)
332 while (target->parent) {
333 target = target->parent;
340 static inline bool device_link_flag_is_sync_state_only(u32 flags)
342 return (flags & ~(DL_FLAG_INFERRED | DL_FLAG_CYCLE)) ==
343 (DL_FLAG_SYNC_STATE_ONLY | DL_FLAG_MANAGED);
347 * device_is_dependent - Check if one device depends on another one
348 * @dev: Device to check dependencies for.
349 * @target: Device to check against.
351 * Check if @target depends on @dev or any device dependent on it (its child or
352 * its consumer etc). Return 1 if that is the case or 0 otherwise.
354 int device_is_dependent(struct device *dev, void *target)
356 struct device_link *link;
360 * The "ancestors" check is needed to catch the case when the target
361 * device has not been completely initialized yet and it is still
362 * missing from the list of children of its parent device.
364 if (dev == target || device_is_ancestor(dev, target))
367 ret = device_for_each_child(dev, target, device_is_dependent);
371 list_for_each_entry(link, &dev->links.consumers, s_node) {
372 if (device_link_flag_is_sync_state_only(link->flags))
375 if (link->consumer == target)
378 ret = device_is_dependent(link->consumer, target);
385 static void device_link_init_status(struct device_link *link,
386 struct device *consumer,
387 struct device *supplier)
389 switch (supplier->links.status) {
391 switch (consumer->links.status) {
394 * A consumer driver can create a link to a supplier
395 * that has not completed its probing yet as long as it
396 * knows that the supplier is already functional (for
397 * example, it has just acquired some resources from the
400 link->status = DL_STATE_CONSUMER_PROBE;
403 link->status = DL_STATE_DORMANT;
407 case DL_DEV_DRIVER_BOUND:
408 switch (consumer->links.status) {
410 link->status = DL_STATE_CONSUMER_PROBE;
412 case DL_DEV_DRIVER_BOUND:
413 link->status = DL_STATE_ACTIVE;
416 link->status = DL_STATE_AVAILABLE;
420 case DL_DEV_UNBINDING:
421 link->status = DL_STATE_SUPPLIER_UNBIND;
424 link->status = DL_STATE_DORMANT;
429 static int device_reorder_to_tail(struct device *dev, void *not_used)
431 struct device_link *link;
434 * Devices that have not been registered yet will be put to the ends
435 * of the lists during the registration, so skip them here.
437 if (device_is_registered(dev))
438 devices_kset_move_last(dev);
440 if (device_pm_initialized(dev))
441 device_pm_move_last(dev);
443 device_for_each_child(dev, NULL, device_reorder_to_tail);
444 list_for_each_entry(link, &dev->links.consumers, s_node) {
445 if (device_link_flag_is_sync_state_only(link->flags))
447 device_reorder_to_tail(link->consumer, NULL);
454 * device_pm_move_to_tail - Move set of devices to the end of device lists
455 * @dev: Device to move
457 * This is a device_reorder_to_tail() wrapper taking the requisite locks.
459 * It moves the @dev along with all of its children and all of its consumers
460 * to the ends of the device_kset and dpm_list, recursively.
462 void device_pm_move_to_tail(struct device *dev)
466 idx = device_links_read_lock();
468 device_reorder_to_tail(dev, NULL);
470 device_links_read_unlock(idx);
473 #define to_devlink(dev) container_of((dev), struct device_link, link_dev)
475 static ssize_t status_show(struct device *dev,
476 struct device_attribute *attr, char *buf)
480 switch (to_devlink(dev)->status) {
482 output = "not tracked";
484 case DL_STATE_DORMANT:
487 case DL_STATE_AVAILABLE:
488 output = "available";
490 case DL_STATE_CONSUMER_PROBE:
491 output = "consumer probing";
493 case DL_STATE_ACTIVE:
496 case DL_STATE_SUPPLIER_UNBIND:
497 output = "supplier unbinding";
504 return sysfs_emit(buf, "%s\n", output);
506 static DEVICE_ATTR_RO(status);
508 static ssize_t auto_remove_on_show(struct device *dev,
509 struct device_attribute *attr, char *buf)
511 struct device_link *link = to_devlink(dev);
514 if (link->flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
515 output = "supplier unbind";
516 else if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER)
517 output = "consumer unbind";
521 return sysfs_emit(buf, "%s\n", output);
523 static DEVICE_ATTR_RO(auto_remove_on);
525 static ssize_t runtime_pm_show(struct device *dev,
526 struct device_attribute *attr, char *buf)
528 struct device_link *link = to_devlink(dev);
530 return sysfs_emit(buf, "%d\n", !!(link->flags & DL_FLAG_PM_RUNTIME));
532 static DEVICE_ATTR_RO(runtime_pm);
534 static ssize_t sync_state_only_show(struct device *dev,
535 struct device_attribute *attr, char *buf)
537 struct device_link *link = to_devlink(dev);
539 return sysfs_emit(buf, "%d\n",
540 !!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
542 static DEVICE_ATTR_RO(sync_state_only);
544 static struct attribute *devlink_attrs[] = {
545 &dev_attr_status.attr,
546 &dev_attr_auto_remove_on.attr,
547 &dev_attr_runtime_pm.attr,
548 &dev_attr_sync_state_only.attr,
551 ATTRIBUTE_GROUPS(devlink);
553 static void device_link_release_fn(struct work_struct *work)
555 struct device_link *link = container_of(work, struct device_link, rm_work);
557 /* Ensure that all references to the link object have been dropped. */
558 device_link_synchronize_removal();
560 pm_runtime_release_supplier(link);
562 * If supplier_preactivated is set, the link has been dropped between
563 * the pm_runtime_get_suppliers() and pm_runtime_put_suppliers() calls
564 * in __driver_probe_device(). In that case, drop the supplier's
565 * PM-runtime usage counter to remove the reference taken by
566 * pm_runtime_get_suppliers().
568 if (link->supplier_preactivated)
569 pm_runtime_put_noidle(link->supplier);
571 pm_request_idle(link->supplier);
573 put_device(link->consumer);
574 put_device(link->supplier);
578 static void devlink_dev_release(struct device *dev)
580 struct device_link *link = to_devlink(dev);
582 INIT_WORK(&link->rm_work, device_link_release_fn);
584 * It may take a while to complete this work because of the SRCU
585 * synchronization in device_link_release_fn() and if the consumer or
586 * supplier devices get deleted when it runs, so put it into the "long"
589 queue_work(system_long_wq, &link->rm_work);
592 static struct class devlink_class = {
594 .owner = THIS_MODULE,
595 .dev_groups = devlink_groups,
596 .dev_release = devlink_dev_release,
599 static int devlink_add_symlinks(struct device *dev,
600 struct class_interface *class_intf)
604 struct device_link *link = to_devlink(dev);
605 struct device *sup = link->supplier;
606 struct device *con = link->consumer;
609 len = max(strlen(dev_bus_name(sup)) + strlen(dev_name(sup)),
610 strlen(dev_bus_name(con)) + strlen(dev_name(con)));
612 len += strlen("supplier:") + 1;
613 buf = kzalloc(len, GFP_KERNEL);
617 ret = sysfs_create_link(&link->link_dev.kobj, &sup->kobj, "supplier");
621 ret = sysfs_create_link(&link->link_dev.kobj, &con->kobj, "consumer");
625 snprintf(buf, len, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
626 ret = sysfs_create_link(&sup->kobj, &link->link_dev.kobj, buf);
630 snprintf(buf, len, "supplier:%s:%s", dev_bus_name(sup), dev_name(sup));
631 ret = sysfs_create_link(&con->kobj, &link->link_dev.kobj, buf);
638 snprintf(buf, len, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
639 sysfs_remove_link(&sup->kobj, buf);
641 sysfs_remove_link(&link->link_dev.kobj, "consumer");
643 sysfs_remove_link(&link->link_dev.kobj, "supplier");
649 static void devlink_remove_symlinks(struct device *dev,
650 struct class_interface *class_intf)
652 struct device_link *link = to_devlink(dev);
654 struct device *sup = link->supplier;
655 struct device *con = link->consumer;
658 sysfs_remove_link(&link->link_dev.kobj, "consumer");
659 sysfs_remove_link(&link->link_dev.kobj, "supplier");
661 len = max(strlen(dev_bus_name(sup)) + strlen(dev_name(sup)),
662 strlen(dev_bus_name(con)) + strlen(dev_name(con)));
664 len += strlen("supplier:") + 1;
665 buf = kzalloc(len, GFP_KERNEL);
667 WARN(1, "Unable to properly free device link symlinks!\n");
671 if (device_is_registered(con)) {
672 snprintf(buf, len, "supplier:%s:%s", dev_bus_name(sup), dev_name(sup));
673 sysfs_remove_link(&con->kobj, buf);
675 snprintf(buf, len, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
676 sysfs_remove_link(&sup->kobj, buf);
680 static struct class_interface devlink_class_intf = {
681 .class = &devlink_class,
682 .add_dev = devlink_add_symlinks,
683 .remove_dev = devlink_remove_symlinks,
686 static int __init devlink_class_init(void)
690 ret = class_register(&devlink_class);
694 ret = class_interface_register(&devlink_class_intf);
696 class_unregister(&devlink_class);
700 postcore_initcall(devlink_class_init);
702 #define DL_MANAGED_LINK_FLAGS (DL_FLAG_AUTOREMOVE_CONSUMER | \
703 DL_FLAG_AUTOREMOVE_SUPPLIER | \
704 DL_FLAG_AUTOPROBE_CONSUMER | \
705 DL_FLAG_SYNC_STATE_ONLY | \
709 #define DL_ADD_VALID_FLAGS (DL_MANAGED_LINK_FLAGS | DL_FLAG_STATELESS | \
710 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE)
713 * device_link_add - Create a link between two devices.
714 * @consumer: Consumer end of the link.
715 * @supplier: Supplier end of the link.
716 * @flags: Link flags.
718 * The caller is responsible for the proper synchronization of the link creation
719 * with runtime PM. First, setting the DL_FLAG_PM_RUNTIME flag will cause the
720 * runtime PM framework to take the link into account. Second, if the
721 * DL_FLAG_RPM_ACTIVE flag is set in addition to it, the supplier devices will
722 * be forced into the active meta state and reference-counted upon the creation
723 * of the link. If DL_FLAG_PM_RUNTIME is not set, DL_FLAG_RPM_ACTIVE will be
726 * If DL_FLAG_STATELESS is set in @flags, the caller of this function is
727 * expected to release the link returned by it directly with the help of either
728 * device_link_del() or device_link_remove().
730 * If that flag is not set, however, the caller of this function is handing the
731 * management of the link over to the driver core entirely and its return value
732 * can only be used to check whether or not the link is present. In that case,
733 * the DL_FLAG_AUTOREMOVE_CONSUMER and DL_FLAG_AUTOREMOVE_SUPPLIER device link
734 * flags can be used to indicate to the driver core when the link can be safely
735 * deleted. Namely, setting one of them in @flags indicates to the driver core
736 * that the link is not going to be used (by the given caller of this function)
737 * after unbinding the consumer or supplier driver, respectively, from its
738 * device, so the link can be deleted at that point. If none of them is set,
739 * the link will be maintained until one of the devices pointed to by it (either
740 * the consumer or the supplier) is unregistered.
742 * Also, if DL_FLAG_STATELESS, DL_FLAG_AUTOREMOVE_CONSUMER and
743 * DL_FLAG_AUTOREMOVE_SUPPLIER are not set in @flags (that is, a persistent
744 * managed device link is being added), the DL_FLAG_AUTOPROBE_CONSUMER flag can
745 * be used to request the driver core to automatically probe for a consumer
746 * driver after successfully binding a driver to the supplier device.
748 * The combination of DL_FLAG_STATELESS and one of DL_FLAG_AUTOREMOVE_CONSUMER,
749 * DL_FLAG_AUTOREMOVE_SUPPLIER, or DL_FLAG_AUTOPROBE_CONSUMER set in @flags at
750 * the same time is invalid and will cause NULL to be returned upfront.
751 * However, if a device link between the given @consumer and @supplier pair
752 * exists already when this function is called for them, the existing link will
753 * be returned regardless of its current type and status (the link's flags may
754 * be modified then). The caller of this function is then expected to treat
755 * the link as though it has just been created, so (in particular) if
756 * DL_FLAG_STATELESS was passed in @flags, the link needs to be released
757 * explicitly when not needed any more (as stated above).
759 * A side effect of the link creation is re-ordering of dpm_list and the
760 * devices_kset list by moving the consumer device and all devices depending
761 * on it to the ends of these lists (that does not happen to devices that have
762 * not been registered when this function is called).
764 * The supplier device is required to be registered when this function is called
765 * and NULL will be returned if that is not the case. The consumer device need
766 * not be registered, however.
768 struct device_link *device_link_add(struct device *consumer,
769 struct device *supplier, u32 flags)
771 struct device_link *link;
773 if (!consumer || !supplier || consumer == supplier ||
774 flags & ~DL_ADD_VALID_FLAGS ||
775 (flags & DL_FLAG_STATELESS && flags & DL_MANAGED_LINK_FLAGS) ||
776 (flags & DL_FLAG_AUTOPROBE_CONSUMER &&
777 flags & (DL_FLAG_AUTOREMOVE_CONSUMER |
778 DL_FLAG_AUTOREMOVE_SUPPLIER)))
781 if (flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) {
782 if (pm_runtime_get_sync(supplier) < 0) {
783 pm_runtime_put_noidle(supplier);
788 if (!(flags & DL_FLAG_STATELESS))
789 flags |= DL_FLAG_MANAGED;
791 if (flags & DL_FLAG_SYNC_STATE_ONLY &&
792 !device_link_flag_is_sync_state_only(flags))
795 device_links_write_lock();
799 * If the supplier has not been fully registered yet or there is a
800 * reverse (non-SYNC_STATE_ONLY) dependency between the consumer and
801 * the supplier already in the graph, return NULL. If the link is a
802 * SYNC_STATE_ONLY link, we don't check for reverse dependencies
803 * because it only affects sync_state() callbacks.
805 if (!device_pm_initialized(supplier)
806 || (!(flags & DL_FLAG_SYNC_STATE_ONLY) &&
807 device_is_dependent(consumer, supplier))) {
813 * SYNC_STATE_ONLY links are useless once a consumer device has probed.
814 * So, only create it if the consumer hasn't probed yet.
816 if (flags & DL_FLAG_SYNC_STATE_ONLY &&
817 consumer->links.status != DL_DEV_NO_DRIVER &&
818 consumer->links.status != DL_DEV_PROBING) {
824 * DL_FLAG_AUTOREMOVE_SUPPLIER indicates that the link will be needed
825 * longer than for DL_FLAG_AUTOREMOVE_CONSUMER and setting them both
826 * together doesn't make sense, so prefer DL_FLAG_AUTOREMOVE_SUPPLIER.
828 if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
829 flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
831 list_for_each_entry(link, &supplier->links.consumers, s_node) {
832 if (link->consumer != consumer)
835 if (link->flags & DL_FLAG_INFERRED &&
836 !(flags & DL_FLAG_INFERRED))
837 link->flags &= ~DL_FLAG_INFERRED;
839 if (flags & DL_FLAG_PM_RUNTIME) {
840 if (!(link->flags & DL_FLAG_PM_RUNTIME)) {
841 pm_runtime_new_link(consumer);
842 link->flags |= DL_FLAG_PM_RUNTIME;
844 if (flags & DL_FLAG_RPM_ACTIVE)
845 refcount_inc(&link->rpm_active);
848 if (flags & DL_FLAG_STATELESS) {
849 kref_get(&link->kref);
850 if (link->flags & DL_FLAG_SYNC_STATE_ONLY &&
851 !(link->flags & DL_FLAG_STATELESS)) {
852 link->flags |= DL_FLAG_STATELESS;
855 link->flags |= DL_FLAG_STATELESS;
861 * If the life time of the link following from the new flags is
862 * longer than indicated by the flags of the existing link,
863 * update the existing link to stay around longer.
865 if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER) {
866 if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER) {
867 link->flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
868 link->flags |= DL_FLAG_AUTOREMOVE_SUPPLIER;
870 } else if (!(flags & DL_FLAG_AUTOREMOVE_CONSUMER)) {
871 link->flags &= ~(DL_FLAG_AUTOREMOVE_CONSUMER |
872 DL_FLAG_AUTOREMOVE_SUPPLIER);
874 if (!(link->flags & DL_FLAG_MANAGED)) {
875 kref_get(&link->kref);
876 link->flags |= DL_FLAG_MANAGED;
877 device_link_init_status(link, consumer, supplier);
879 if (link->flags & DL_FLAG_SYNC_STATE_ONLY &&
880 !(flags & DL_FLAG_SYNC_STATE_ONLY)) {
881 link->flags &= ~DL_FLAG_SYNC_STATE_ONLY;
888 link = kzalloc(sizeof(*link), GFP_KERNEL);
892 refcount_set(&link->rpm_active, 1);
894 get_device(supplier);
895 link->supplier = supplier;
896 INIT_LIST_HEAD(&link->s_node);
897 get_device(consumer);
898 link->consumer = consumer;
899 INIT_LIST_HEAD(&link->c_node);
901 kref_init(&link->kref);
903 link->link_dev.class = &devlink_class;
904 device_set_pm_not_required(&link->link_dev);
905 dev_set_name(&link->link_dev, "%s:%s--%s:%s",
906 dev_bus_name(supplier), dev_name(supplier),
907 dev_bus_name(consumer), dev_name(consumer));
908 if (device_register(&link->link_dev)) {
909 put_device(&link->link_dev);
914 if (flags & DL_FLAG_PM_RUNTIME) {
915 if (flags & DL_FLAG_RPM_ACTIVE)
916 refcount_inc(&link->rpm_active);
918 pm_runtime_new_link(consumer);
921 /* Determine the initial link state. */
922 if (flags & DL_FLAG_STATELESS)
923 link->status = DL_STATE_NONE;
925 device_link_init_status(link, consumer, supplier);
928 * Some callers expect the link creation during consumer driver probe to
929 * resume the supplier even without DL_FLAG_RPM_ACTIVE.
931 if (link->status == DL_STATE_CONSUMER_PROBE &&
932 flags & DL_FLAG_PM_RUNTIME)
933 pm_runtime_resume(supplier);
935 list_add_tail_rcu(&link->s_node, &supplier->links.consumers);
936 list_add_tail_rcu(&link->c_node, &consumer->links.suppliers);
938 if (flags & DL_FLAG_SYNC_STATE_ONLY) {
940 "Linked as a sync state only consumer to %s\n",
947 * Move the consumer and all of the devices depending on it to the end
948 * of dpm_list and the devices_kset list.
950 * It is necessary to hold dpm_list locked throughout all that or else
951 * we may end up suspending with a wrong ordering of it.
953 device_reorder_to_tail(consumer, NULL);
955 dev_dbg(consumer, "Linked as a consumer to %s\n", dev_name(supplier));
959 device_links_write_unlock();
961 if ((flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) && !link)
962 pm_runtime_put(supplier);
966 EXPORT_SYMBOL_GPL(device_link_add);
968 static void __device_link_del(struct kref *kref)
970 struct device_link *link = container_of(kref, struct device_link, kref);
972 dev_dbg(link->consumer, "Dropping the link to %s\n",
973 dev_name(link->supplier));
975 pm_runtime_drop_link(link);
977 device_link_remove_from_lists(link);
978 device_unregister(&link->link_dev);
981 static void device_link_put_kref(struct device_link *link)
983 if (link->flags & DL_FLAG_STATELESS)
984 kref_put(&link->kref, __device_link_del);
985 else if (!device_is_registered(link->consumer))
986 __device_link_del(&link->kref);
988 WARN(1, "Unable to drop a managed device link reference\n");
992 * device_link_del - Delete a stateless link between two devices.
993 * @link: Device link to delete.
995 * The caller must ensure proper synchronization of this function with runtime
996 * PM. If the link was added multiple times, it needs to be deleted as often.
997 * Care is required for hotplugged devices: Their links are purged on removal
998 * and calling device_link_del() is then no longer allowed.
1000 void device_link_del(struct device_link *link)
1002 device_links_write_lock();
1003 device_link_put_kref(link);
1004 device_links_write_unlock();
1006 EXPORT_SYMBOL_GPL(device_link_del);
1009 * device_link_remove - Delete a stateless link between two devices.
1010 * @consumer: Consumer end of the link.
1011 * @supplier: Supplier end of the link.
1013 * The caller must ensure proper synchronization of this function with runtime
1016 void device_link_remove(void *consumer, struct device *supplier)
1018 struct device_link *link;
1020 if (WARN_ON(consumer == supplier))
1023 device_links_write_lock();
1025 list_for_each_entry(link, &supplier->links.consumers, s_node) {
1026 if (link->consumer == consumer) {
1027 device_link_put_kref(link);
1032 device_links_write_unlock();
1034 EXPORT_SYMBOL_GPL(device_link_remove);
1036 static void device_links_missing_supplier(struct device *dev)
1038 struct device_link *link;
1040 list_for_each_entry(link, &dev->links.suppliers, c_node) {
1041 if (link->status != DL_STATE_CONSUMER_PROBE)
1044 if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
1045 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1047 WARN_ON(!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
1048 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1053 static bool dev_is_best_effort(struct device *dev)
1055 return (fw_devlink_best_effort && dev->can_match) ||
1056 (dev->fwnode && (dev->fwnode->flags & FWNODE_FLAG_BEST_EFFORT));
1059 static struct fwnode_handle *fwnode_links_check_suppliers(
1060 struct fwnode_handle *fwnode)
1062 struct fwnode_link *link;
1064 if (!fwnode || fw_devlink_is_permissive())
1067 list_for_each_entry(link, &fwnode->suppliers, c_hook)
1068 if (!(link->flags & FWLINK_FLAG_CYCLE))
1069 return link->supplier;
1075 * device_links_check_suppliers - Check presence of supplier drivers.
1076 * @dev: Consumer device.
1078 * Check links from this device to any suppliers. Walk the list of the device's
1079 * links to suppliers and see if all of them are available. If not, simply
1080 * return -EPROBE_DEFER.
1082 * We need to guarantee that the supplier will not go away after the check has
1083 * been positive here. It only can go away in __device_release_driver() and
1084 * that function checks the device's links to consumers. This means we need to
1085 * mark the link as "consumer probe in progress" to make the supplier removal
1086 * wait for us to complete (or bad things may happen).
1088 * Links without the DL_FLAG_MANAGED flag set are ignored.
1090 int device_links_check_suppliers(struct device *dev)
1092 struct device_link *link;
1093 int ret = 0, fwnode_ret = 0;
1094 struct fwnode_handle *sup_fw;
1097 * Device waiting for supplier to become available is not allowed to
1100 mutex_lock(&fwnode_link_lock);
1101 sup_fw = fwnode_links_check_suppliers(dev->fwnode);
1103 if (!dev_is_best_effort(dev)) {
1104 fwnode_ret = -EPROBE_DEFER;
1105 dev_err_probe(dev, -EPROBE_DEFER,
1106 "wait for supplier %pfwP\n", sup_fw);
1108 fwnode_ret = -EAGAIN;
1111 mutex_unlock(&fwnode_link_lock);
1112 if (fwnode_ret == -EPROBE_DEFER)
1115 device_links_write_lock();
1117 list_for_each_entry(link, &dev->links.suppliers, c_node) {
1118 if (!(link->flags & DL_FLAG_MANAGED))
1121 if (link->status != DL_STATE_AVAILABLE &&
1122 !(link->flags & DL_FLAG_SYNC_STATE_ONLY)) {
1124 if (dev_is_best_effort(dev) &&
1125 link->flags & DL_FLAG_INFERRED &&
1126 !link->supplier->can_match) {
1131 device_links_missing_supplier(dev);
1132 dev_err_probe(dev, -EPROBE_DEFER,
1133 "supplier %s not ready\n",
1134 dev_name(link->supplier));
1135 ret = -EPROBE_DEFER;
1138 WRITE_ONCE(link->status, DL_STATE_CONSUMER_PROBE);
1140 dev->links.status = DL_DEV_PROBING;
1142 device_links_write_unlock();
1144 return ret ? ret : fwnode_ret;
1148 * __device_links_queue_sync_state - Queue a device for sync_state() callback
1149 * @dev: Device to call sync_state() on
1150 * @list: List head to queue the @dev on
1152 * Queues a device for a sync_state() callback when the device links write lock
1153 * isn't held. This allows the sync_state() execution flow to use device links
1154 * APIs. The caller must ensure this function is called with
1155 * device_links_write_lock() held.
1157 * This function does a get_device() to make sure the device is not freed while
1160 * So the caller must also ensure that device_links_flush_sync_list() is called
1161 * as soon as the caller releases device_links_write_lock(). This is necessary
1162 * to make sure the sync_state() is called in a timely fashion and the
1163 * put_device() is called on this device.
1165 static void __device_links_queue_sync_state(struct device *dev,
1166 struct list_head *list)
1168 struct device_link *link;
1170 if (!dev_has_sync_state(dev))
1172 if (dev->state_synced)
1175 list_for_each_entry(link, &dev->links.consumers, s_node) {
1176 if (!(link->flags & DL_FLAG_MANAGED))
1178 if (link->status != DL_STATE_ACTIVE)
1183 * Set the flag here to avoid adding the same device to a list more
1184 * than once. This can happen if new consumers get added to the device
1185 * and probed before the list is flushed.
1187 dev->state_synced = true;
1189 if (WARN_ON(!list_empty(&dev->links.defer_sync)))
1193 list_add_tail(&dev->links.defer_sync, list);
1197 * device_links_flush_sync_list - Call sync_state() on a list of devices
1198 * @list: List of devices to call sync_state() on
1199 * @dont_lock_dev: Device for which lock is already held by the caller
1201 * Calls sync_state() on all the devices that have been queued for it. This
1202 * function is used in conjunction with __device_links_queue_sync_state(). The
1203 * @dont_lock_dev parameter is useful when this function is called from a
1204 * context where a device lock is already held.
1206 static void device_links_flush_sync_list(struct list_head *list,
1207 struct device *dont_lock_dev)
1209 struct device *dev, *tmp;
1211 list_for_each_entry_safe(dev, tmp, list, links.defer_sync) {
1212 list_del_init(&dev->links.defer_sync);
1214 if (dev != dont_lock_dev)
1217 if (dev->bus->sync_state)
1218 dev->bus->sync_state(dev);
1219 else if (dev->driver && dev->driver->sync_state)
1220 dev->driver->sync_state(dev);
1222 if (dev != dont_lock_dev)
1229 void device_links_supplier_sync_state_pause(void)
1231 device_links_write_lock();
1232 defer_sync_state_count++;
1233 device_links_write_unlock();
1236 void device_links_supplier_sync_state_resume(void)
1238 struct device *dev, *tmp;
1239 LIST_HEAD(sync_list);
1241 device_links_write_lock();
1242 if (!defer_sync_state_count) {
1243 WARN(true, "Unmatched sync_state pause/resume!");
1246 defer_sync_state_count--;
1247 if (defer_sync_state_count)
1250 list_for_each_entry_safe(dev, tmp, &deferred_sync, links.defer_sync) {
1252 * Delete from deferred_sync list before queuing it to
1253 * sync_list because defer_sync is used for both lists.
1255 list_del_init(&dev->links.defer_sync);
1256 __device_links_queue_sync_state(dev, &sync_list);
1259 device_links_write_unlock();
1261 device_links_flush_sync_list(&sync_list, NULL);
1264 static int sync_state_resume_initcall(void)
1266 device_links_supplier_sync_state_resume();
1269 late_initcall(sync_state_resume_initcall);
1271 static void __device_links_supplier_defer_sync(struct device *sup)
1273 if (list_empty(&sup->links.defer_sync) && dev_has_sync_state(sup))
1274 list_add_tail(&sup->links.defer_sync, &deferred_sync);
1277 static void device_link_drop_managed(struct device_link *link)
1279 link->flags &= ~DL_FLAG_MANAGED;
1280 WRITE_ONCE(link->status, DL_STATE_NONE);
1281 kref_put(&link->kref, __device_link_del);
1284 static ssize_t waiting_for_supplier_show(struct device *dev,
1285 struct device_attribute *attr,
1291 mutex_lock(&fwnode_link_lock);
1292 val = !!fwnode_links_check_suppliers(dev->fwnode);
1293 mutex_unlock(&fwnode_link_lock);
1295 return sysfs_emit(buf, "%u\n", val);
1297 static DEVICE_ATTR_RO(waiting_for_supplier);
1300 * device_links_force_bind - Prepares device to be force bound
1301 * @dev: Consumer device.
1303 * device_bind_driver() force binds a device to a driver without calling any
1304 * driver probe functions. So the consumer really isn't going to wait for any
1305 * supplier before it's bound to the driver. We still want the device link
1306 * states to be sensible when this happens.
1308 * In preparation for device_bind_driver(), this function goes through each
1309 * supplier device links and checks if the supplier is bound. If it is, then
1310 * the device link status is set to CONSUMER_PROBE. Otherwise, the device link
1311 * is dropped. Links without the DL_FLAG_MANAGED flag set are ignored.
1313 void device_links_force_bind(struct device *dev)
1315 struct device_link *link, *ln;
1317 device_links_write_lock();
1319 list_for_each_entry_safe(link, ln, &dev->links.suppliers, c_node) {
1320 if (!(link->flags & DL_FLAG_MANAGED))
1323 if (link->status != DL_STATE_AVAILABLE) {
1324 device_link_drop_managed(link);
1327 WRITE_ONCE(link->status, DL_STATE_CONSUMER_PROBE);
1329 dev->links.status = DL_DEV_PROBING;
1331 device_links_write_unlock();
1335 * device_links_driver_bound - Update device links after probing its driver.
1336 * @dev: Device to update the links for.
1338 * The probe has been successful, so update links from this device to any
1339 * consumers by changing their status to "available".
1341 * Also change the status of @dev's links to suppliers to "active".
1343 * Links without the DL_FLAG_MANAGED flag set are ignored.
1345 void device_links_driver_bound(struct device *dev)
1347 struct device_link *link, *ln;
1348 LIST_HEAD(sync_list);
1351 * If a device binds successfully, it's expected to have created all
1352 * the device links it needs to or make new device links as it needs
1353 * them. So, fw_devlink no longer needs to create device links to any
1354 * of the device's suppliers.
1356 * Also, if a child firmware node of this bound device is not added as a
1357 * device by now, assume it is never going to be added. Make this bound
1358 * device the fallback supplier to the dangling consumers of the child
1359 * firmware node because this bound device is probably implementing the
1360 * child firmware node functionality and we don't want the dangling
1361 * consumers to defer probe indefinitely waiting for a device for the
1362 * child firmware node.
1364 if (dev->fwnode && dev->fwnode->dev == dev) {
1365 struct fwnode_handle *child;
1366 fwnode_links_purge_suppliers(dev->fwnode);
1367 mutex_lock(&fwnode_link_lock);
1368 fwnode_for_each_available_child_node(dev->fwnode, child)
1369 __fw_devlink_pickup_dangling_consumers(child,
1371 __fw_devlink_link_to_consumers(dev);
1372 mutex_unlock(&fwnode_link_lock);
1374 device_remove_file(dev, &dev_attr_waiting_for_supplier);
1376 device_links_write_lock();
1378 list_for_each_entry(link, &dev->links.consumers, s_node) {
1379 if (!(link->flags & DL_FLAG_MANAGED))
1383 * Links created during consumer probe may be in the "consumer
1384 * probe" state to start with if the supplier is still probing
1385 * when they are created and they may become "active" if the
1386 * consumer probe returns first. Skip them here.
1388 if (link->status == DL_STATE_CONSUMER_PROBE ||
1389 link->status == DL_STATE_ACTIVE)
1392 WARN_ON(link->status != DL_STATE_DORMANT);
1393 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1395 if (link->flags & DL_FLAG_AUTOPROBE_CONSUMER)
1396 driver_deferred_probe_add(link->consumer);
1399 if (defer_sync_state_count)
1400 __device_links_supplier_defer_sync(dev);
1402 __device_links_queue_sync_state(dev, &sync_list);
1404 list_for_each_entry_safe(link, ln, &dev->links.suppliers, c_node) {
1405 struct device *supplier;
1407 if (!(link->flags & DL_FLAG_MANAGED))
1410 supplier = link->supplier;
1411 if (link->flags & DL_FLAG_SYNC_STATE_ONLY) {
1413 * When DL_FLAG_SYNC_STATE_ONLY is set, it means no
1414 * other DL_MANAGED_LINK_FLAGS have been set. So, it's
1415 * save to drop the managed link completely.
1417 device_link_drop_managed(link);
1418 } else if (dev_is_best_effort(dev) &&
1419 link->flags & DL_FLAG_INFERRED &&
1420 link->status != DL_STATE_CONSUMER_PROBE &&
1421 !link->supplier->can_match) {
1423 * When dev_is_best_effort() is true, we ignore device
1424 * links to suppliers that don't have a driver. If the
1425 * consumer device still managed to probe, there's no
1426 * point in maintaining a device link in a weird state
1427 * (consumer probed before supplier). So delete it.
1429 device_link_drop_managed(link);
1431 WARN_ON(link->status != DL_STATE_CONSUMER_PROBE);
1432 WRITE_ONCE(link->status, DL_STATE_ACTIVE);
1436 * This needs to be done even for the deleted
1437 * DL_FLAG_SYNC_STATE_ONLY device link in case it was the last
1438 * device link that was preventing the supplier from getting a
1439 * sync_state() call.
1441 if (defer_sync_state_count)
1442 __device_links_supplier_defer_sync(supplier);
1444 __device_links_queue_sync_state(supplier, &sync_list);
1447 dev->links.status = DL_DEV_DRIVER_BOUND;
1449 device_links_write_unlock();
1451 device_links_flush_sync_list(&sync_list, dev);
1455 * __device_links_no_driver - Update links of a device without a driver.
1456 * @dev: Device without a drvier.
1458 * Delete all non-persistent links from this device to any suppliers.
1460 * Persistent links stay around, but their status is changed to "available",
1461 * unless they already are in the "supplier unbind in progress" state in which
1462 * case they need not be updated.
1464 * Links without the DL_FLAG_MANAGED flag set are ignored.
1466 static void __device_links_no_driver(struct device *dev)
1468 struct device_link *link, *ln;
1470 list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1471 if (!(link->flags & DL_FLAG_MANAGED))
1474 if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER) {
1475 device_link_drop_managed(link);
1479 if (link->status != DL_STATE_CONSUMER_PROBE &&
1480 link->status != DL_STATE_ACTIVE)
1483 if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
1484 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1486 WARN_ON(!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
1487 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1491 dev->links.status = DL_DEV_NO_DRIVER;
1495 * device_links_no_driver - Update links after failing driver probe.
1496 * @dev: Device whose driver has just failed to probe.
1498 * Clean up leftover links to consumers for @dev and invoke
1499 * %__device_links_no_driver() to update links to suppliers for it as
1502 * Links without the DL_FLAG_MANAGED flag set are ignored.
1504 void device_links_no_driver(struct device *dev)
1506 struct device_link *link;
1508 device_links_write_lock();
1510 list_for_each_entry(link, &dev->links.consumers, s_node) {
1511 if (!(link->flags & DL_FLAG_MANAGED))
1515 * The probe has failed, so if the status of the link is
1516 * "consumer probe" or "active", it must have been added by
1517 * a probing consumer while this device was still probing.
1518 * Change its state to "dormant", as it represents a valid
1519 * relationship, but it is not functionally meaningful.
1521 if (link->status == DL_STATE_CONSUMER_PROBE ||
1522 link->status == DL_STATE_ACTIVE)
1523 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1526 __device_links_no_driver(dev);
1528 device_links_write_unlock();
1532 * device_links_driver_cleanup - Update links after driver removal.
1533 * @dev: Device whose driver has just gone away.
1535 * Update links to consumers for @dev by changing their status to "dormant" and
1536 * invoke %__device_links_no_driver() to update links to suppliers for it as
1539 * Links without the DL_FLAG_MANAGED flag set are ignored.
1541 void device_links_driver_cleanup(struct device *dev)
1543 struct device_link *link, *ln;
1545 device_links_write_lock();
1547 list_for_each_entry_safe(link, ln, &dev->links.consumers, s_node) {
1548 if (!(link->flags & DL_FLAG_MANAGED))
1551 WARN_ON(link->flags & DL_FLAG_AUTOREMOVE_CONSUMER);
1552 WARN_ON(link->status != DL_STATE_SUPPLIER_UNBIND);
1555 * autoremove the links between this @dev and its consumer
1556 * devices that are not active, i.e. where the link state
1557 * has moved to DL_STATE_SUPPLIER_UNBIND.
1559 if (link->status == DL_STATE_SUPPLIER_UNBIND &&
1560 link->flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
1561 device_link_drop_managed(link);
1563 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1566 list_del_init(&dev->links.defer_sync);
1567 __device_links_no_driver(dev);
1569 device_links_write_unlock();
1573 * device_links_busy - Check if there are any busy links to consumers.
1574 * @dev: Device to check.
1576 * Check each consumer of the device and return 'true' if its link's status
1577 * is one of "consumer probe" or "active" (meaning that the given consumer is
1578 * probing right now or its driver is present). Otherwise, change the link
1579 * state to "supplier unbind" to prevent the consumer from being probed
1580 * successfully going forward.
1582 * Return 'false' if there are no probing or active consumers.
1584 * Links without the DL_FLAG_MANAGED flag set are ignored.
1586 bool device_links_busy(struct device *dev)
1588 struct device_link *link;
1591 device_links_write_lock();
1593 list_for_each_entry(link, &dev->links.consumers, s_node) {
1594 if (!(link->flags & DL_FLAG_MANAGED))
1597 if (link->status == DL_STATE_CONSUMER_PROBE
1598 || link->status == DL_STATE_ACTIVE) {
1602 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1605 dev->links.status = DL_DEV_UNBINDING;
1607 device_links_write_unlock();
1612 * device_links_unbind_consumers - Force unbind consumers of the given device.
1613 * @dev: Device to unbind the consumers of.
1615 * Walk the list of links to consumers for @dev and if any of them is in the
1616 * "consumer probe" state, wait for all device probes in progress to complete
1619 * If that's not the case, change the status of the link to "supplier unbind"
1620 * and check if the link was in the "active" state. If so, force the consumer
1621 * driver to unbind and start over (the consumer will not re-probe as we have
1622 * changed the state of the link already).
1624 * Links without the DL_FLAG_MANAGED flag set are ignored.
1626 void device_links_unbind_consumers(struct device *dev)
1628 struct device_link *link;
1631 device_links_write_lock();
1633 list_for_each_entry(link, &dev->links.consumers, s_node) {
1634 enum device_link_state status;
1636 if (!(link->flags & DL_FLAG_MANAGED) ||
1637 link->flags & DL_FLAG_SYNC_STATE_ONLY)
1640 status = link->status;
1641 if (status == DL_STATE_CONSUMER_PROBE) {
1642 device_links_write_unlock();
1644 wait_for_device_probe();
1647 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1648 if (status == DL_STATE_ACTIVE) {
1649 struct device *consumer = link->consumer;
1651 get_device(consumer);
1653 device_links_write_unlock();
1655 device_release_driver_internal(consumer, NULL,
1657 put_device(consumer);
1662 device_links_write_unlock();
1666 * device_links_purge - Delete existing links to other devices.
1667 * @dev: Target device.
1669 static void device_links_purge(struct device *dev)
1671 struct device_link *link, *ln;
1673 if (dev->class == &devlink_class)
1677 * Delete all of the remaining links from this device to any other
1678 * devices (either consumers or suppliers).
1680 device_links_write_lock();
1682 list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1683 WARN_ON(link->status == DL_STATE_ACTIVE);
1684 __device_link_del(&link->kref);
1687 list_for_each_entry_safe_reverse(link, ln, &dev->links.consumers, s_node) {
1688 WARN_ON(link->status != DL_STATE_DORMANT &&
1689 link->status != DL_STATE_NONE);
1690 __device_link_del(&link->kref);
1693 device_links_write_unlock();
1696 #define FW_DEVLINK_FLAGS_PERMISSIVE (DL_FLAG_INFERRED | \
1697 DL_FLAG_SYNC_STATE_ONLY)
1698 #define FW_DEVLINK_FLAGS_ON (DL_FLAG_INFERRED | \
1699 DL_FLAG_AUTOPROBE_CONSUMER)
1700 #define FW_DEVLINK_FLAGS_RPM (FW_DEVLINK_FLAGS_ON | \
1703 static u32 fw_devlink_flags = FW_DEVLINK_FLAGS_ON;
1704 static int __init fw_devlink_setup(char *arg)
1709 if (strcmp(arg, "off") == 0) {
1710 fw_devlink_flags = 0;
1711 } else if (strcmp(arg, "permissive") == 0) {
1712 fw_devlink_flags = FW_DEVLINK_FLAGS_PERMISSIVE;
1713 } else if (strcmp(arg, "on") == 0) {
1714 fw_devlink_flags = FW_DEVLINK_FLAGS_ON;
1715 } else if (strcmp(arg, "rpm") == 0) {
1716 fw_devlink_flags = FW_DEVLINK_FLAGS_RPM;
1720 early_param("fw_devlink", fw_devlink_setup);
1722 static bool fw_devlink_strict;
1723 static int __init fw_devlink_strict_setup(char *arg)
1725 return strtobool(arg, &fw_devlink_strict);
1727 early_param("fw_devlink.strict", fw_devlink_strict_setup);
1729 static inline u32 fw_devlink_get_flags(u8 fwlink_flags)
1731 if (fwlink_flags & FWLINK_FLAG_CYCLE)
1732 return FW_DEVLINK_FLAGS_PERMISSIVE | DL_FLAG_CYCLE;
1734 return fw_devlink_flags;
1737 static bool fw_devlink_is_permissive(void)
1739 return fw_devlink_flags == FW_DEVLINK_FLAGS_PERMISSIVE;
1742 bool fw_devlink_is_strict(void)
1744 return fw_devlink_strict && !fw_devlink_is_permissive();
1747 static void fw_devlink_parse_fwnode(struct fwnode_handle *fwnode)
1749 if (fwnode->flags & FWNODE_FLAG_LINKS_ADDED)
1752 fwnode_call_int_op(fwnode, add_links);
1753 fwnode->flags |= FWNODE_FLAG_LINKS_ADDED;
1756 static void fw_devlink_parse_fwtree(struct fwnode_handle *fwnode)
1758 struct fwnode_handle *child = NULL;
1760 fw_devlink_parse_fwnode(fwnode);
1762 while ((child = fwnode_get_next_available_child_node(fwnode, child)))
1763 fw_devlink_parse_fwtree(child);
1766 static void fw_devlink_relax_link(struct device_link *link)
1768 if (!(link->flags & DL_FLAG_INFERRED))
1771 if (device_link_flag_is_sync_state_only(link->flags))
1774 pm_runtime_drop_link(link);
1775 link->flags = DL_FLAG_MANAGED | FW_DEVLINK_FLAGS_PERMISSIVE;
1776 dev_dbg(link->consumer, "Relaxing link with %s\n",
1777 dev_name(link->supplier));
1780 static int fw_devlink_no_driver(struct device *dev, void *data)
1782 struct device_link *link = to_devlink(dev);
1784 if (!link->supplier->can_match)
1785 fw_devlink_relax_link(link);
1790 void fw_devlink_drivers_done(void)
1792 fw_devlink_drv_reg_done = true;
1793 device_links_write_lock();
1794 class_for_each_device(&devlink_class, NULL, NULL,
1795 fw_devlink_no_driver);
1796 device_links_write_unlock();
1800 * wait_for_init_devices_probe - Try to probe any device needed for init
1802 * Some devices might need to be probed and bound successfully before the kernel
1803 * boot sequence can finish and move on to init/userspace. For example, a
1804 * network interface might need to be bound to be able to mount a NFS rootfs.
1806 * With fw_devlink=on by default, some of these devices might be blocked from
1807 * probing because they are waiting on a optional supplier that doesn't have a
1808 * driver. While fw_devlink will eventually identify such devices and unblock
1809 * the probing automatically, it might be too late by the time it unblocks the
1810 * probing of devices. For example, the IP4 autoconfig might timeout before
1811 * fw_devlink unblocks probing of the network interface.
1813 * This function is available to temporarily try and probe all devices that have
1814 * a driver even if some of their suppliers haven't been added or don't have
1817 * The drivers can then decide which of the suppliers are optional vs mandatory
1818 * and probe the device if possible. By the time this function returns, all such
1819 * "best effort" probes are guaranteed to be completed. If a device successfully
1820 * probes in this mode, we delete all fw_devlink discovered dependencies of that
1821 * device where the supplier hasn't yet probed successfully because they have to
1822 * be optional dependencies.
1824 * Any devices that didn't successfully probe go back to being treated as if
1825 * this function was never called.
1827 * This also means that some devices that aren't needed for init and could have
1828 * waited for their optional supplier to probe (when the supplier's module is
1829 * loaded later on) would end up probing prematurely with limited functionality.
1830 * So call this function only when boot would fail without it.
1832 void __init wait_for_init_devices_probe(void)
1834 if (!fw_devlink_flags || fw_devlink_is_permissive())
1838 * Wait for all ongoing probes to finish so that the "best effort" is
1839 * only applied to devices that can't probe otherwise.
1841 wait_for_device_probe();
1843 pr_info("Trying to probe devices needed for running init ...\n");
1844 fw_devlink_best_effort = true;
1845 driver_deferred_probe_trigger();
1848 * Wait for all "best effort" probes to finish before going back to
1849 * normal enforcement.
1851 wait_for_device_probe();
1852 fw_devlink_best_effort = false;
1855 static void fw_devlink_unblock_consumers(struct device *dev)
1857 struct device_link *link;
1859 if (!fw_devlink_flags || fw_devlink_is_permissive())
1862 device_links_write_lock();
1863 list_for_each_entry(link, &dev->links.consumers, s_node)
1864 fw_devlink_relax_link(link);
1865 device_links_write_unlock();
1869 static bool fwnode_init_without_drv(struct fwnode_handle *fwnode)
1874 if (!(fwnode->flags & FWNODE_FLAG_INITIALIZED))
1877 dev = get_dev_from_fwnode(fwnode);
1878 ret = !dev || dev->links.status == DL_DEV_NO_DRIVER;
1884 static bool fwnode_ancestor_init_without_drv(struct fwnode_handle *fwnode)
1886 struct fwnode_handle *parent;
1888 fwnode_for_each_parent_node(fwnode, parent) {
1889 if (fwnode_init_without_drv(parent)) {
1890 fwnode_handle_put(parent);
1899 * __fw_devlink_relax_cycles - Relax and mark dependency cycles.
1900 * @con: Potential consumer device.
1901 * @sup_handle: Potential supplier's fwnode.
1903 * Needs to be called with fwnode_lock and device link lock held.
1905 * Check if @sup_handle or any of its ancestors or suppliers direct/indirectly
1906 * depend on @con. This function can detect multiple cyles between @sup_handle
1907 * and @con. When such dependency cycles are found, convert all device links
1908 * created solely by fw_devlink into SYNC_STATE_ONLY device links. Also, mark
1909 * all fwnode links in the cycle with FWLINK_FLAG_CYCLE so that when they are
1910 * converted into a device link in the future, they are created as
1911 * SYNC_STATE_ONLY device links. This is the equivalent of doing
1912 * fw_devlink=permissive just between the devices in the cycle. We need to do
1913 * this because, at this point, fw_devlink can't tell which of these
1914 * dependencies is not a real dependency.
1916 * Return true if one or more cycles were found. Otherwise, return false.
1918 static bool __fw_devlink_relax_cycles(struct device *con,
1919 struct fwnode_handle *sup_handle)
1921 struct device *sup_dev = NULL, *par_dev = NULL;
1922 struct fwnode_link *link;
1923 struct device_link *dev_link;
1930 * We aren't trying to find all cycles. Just a cycle between con and
1933 if (sup_handle->flags & FWNODE_FLAG_VISITED)
1936 sup_handle->flags |= FWNODE_FLAG_VISITED;
1938 sup_dev = get_dev_from_fwnode(sup_handle);
1940 /* Termination condition. */
1941 if (sup_dev == con) {
1947 * If sup_dev is bound to a driver and @con hasn't started binding to a
1948 * driver, sup_dev can't be a consumer of @con. So, no need to check
1951 if (sup_dev && sup_dev->links.status == DL_DEV_DRIVER_BOUND &&
1952 con->links.status == DL_DEV_NO_DRIVER) {
1957 list_for_each_entry(link, &sup_handle->suppliers, c_hook) {
1958 if (__fw_devlink_relax_cycles(con, link->supplier)) {
1959 __fwnode_link_cycle(link);
1965 * Give priority to device parent over fwnode parent to account for any
1966 * quirks in how fwnodes are converted to devices.
1969 par_dev = get_device(sup_dev->parent);
1971 par_dev = fwnode_get_next_parent_dev(sup_handle);
1973 if (par_dev && __fw_devlink_relax_cycles(con, par_dev->fwnode))
1979 list_for_each_entry(dev_link, &sup_dev->links.suppliers, c_node) {
1981 * Ignore a SYNC_STATE_ONLY flag only if it wasn't marked as
1982 * such due to a cycle.
1984 if (device_link_flag_is_sync_state_only(dev_link->flags) &&
1985 !(dev_link->flags & DL_FLAG_CYCLE))
1988 if (__fw_devlink_relax_cycles(con,
1989 dev_link->supplier->fwnode)) {
1990 fw_devlink_relax_link(dev_link);
1991 dev_link->flags |= DL_FLAG_CYCLE;
1997 sup_handle->flags &= ~FWNODE_FLAG_VISITED;
1998 put_device(sup_dev);
1999 put_device(par_dev);
2004 * fw_devlink_create_devlink - Create a device link from a consumer to fwnode
2005 * @con: consumer device for the device link
2006 * @sup_handle: fwnode handle of supplier
2007 * @link: fwnode link that's being converted to a device link
2009 * This function will try to create a device link between the consumer device
2010 * @con and the supplier device represented by @sup_handle.
2012 * The supplier has to be provided as a fwnode because incorrect cycles in
2013 * fwnode links can sometimes cause the supplier device to never be created.
2014 * This function detects such cases and returns an error if it cannot create a
2015 * device link from the consumer to a missing supplier.
2018 * 0 on successfully creating a device link
2019 * -EINVAL if the device link cannot be created as expected
2020 * -EAGAIN if the device link cannot be created right now, but it may be
2021 * possible to do that in the future
2023 static int fw_devlink_create_devlink(struct device *con,
2024 struct fwnode_handle *sup_handle,
2025 struct fwnode_link *link)
2027 struct device *sup_dev;
2031 if (con->fwnode == link->consumer)
2032 flags = fw_devlink_get_flags(link->flags);
2034 flags = FW_DEVLINK_FLAGS_PERMISSIVE;
2037 * In some cases, a device P might also be a supplier to its child node
2038 * C. However, this would defer the probe of C until the probe of P
2039 * completes successfully. This is perfectly fine in the device driver
2040 * model. device_add() doesn't guarantee probe completion of the device
2041 * by the time it returns.
2043 * However, there are a few drivers that assume C will finish probing
2044 * as soon as it's added and before P finishes probing. So, we provide
2045 * a flag to let fw_devlink know not to delay the probe of C until the
2046 * probe of P completes successfully.
2048 * When such a flag is set, we can't create device links where P is the
2049 * supplier of C as that would delay the probe of C.
2051 if (sup_handle->flags & FWNODE_FLAG_NEEDS_CHILD_BOUND_ON_ADD &&
2052 fwnode_is_ancestor_of(sup_handle, con->fwnode))
2056 * SYNC_STATE_ONLY device links don't block probing and supports cycles.
2057 * So cycle detection isn't necessary and shouldn't be done.
2059 if (!(flags & DL_FLAG_SYNC_STATE_ONLY)) {
2060 device_links_write_lock();
2061 if (__fw_devlink_relax_cycles(con, sup_handle)) {
2062 __fwnode_link_cycle(link);
2063 flags = fw_devlink_get_flags(link->flags);
2064 dev_info(con, "Fixed dependency cycle(s) with %pfwf\n",
2067 device_links_write_unlock();
2070 if (sup_handle->flags & FWNODE_FLAG_NOT_DEVICE)
2071 sup_dev = fwnode_get_next_parent_dev(sup_handle);
2073 sup_dev = get_dev_from_fwnode(sup_handle);
2077 * If it's one of those drivers that don't actually bind to
2078 * their device using driver core, then don't wait on this
2079 * supplier device indefinitely.
2081 if (sup_dev->links.status == DL_DEV_NO_DRIVER &&
2082 sup_handle->flags & FWNODE_FLAG_INITIALIZED) {
2084 "Not linking %pfwf - dev might never probe\n",
2090 if (con != sup_dev && !device_link_add(con, sup_dev, flags)) {
2091 dev_err(con, "Failed to create device link (0x%x) with %s\n",
2092 flags, dev_name(sup_dev));
2100 * Supplier or supplier's ancestor already initialized without a struct
2101 * device or being probed by a driver.
2103 if (fwnode_init_without_drv(sup_handle) ||
2104 fwnode_ancestor_init_without_drv(sup_handle)) {
2105 dev_dbg(con, "Not linking %pfwf - might never become dev\n",
2112 put_device(sup_dev);
2117 * __fw_devlink_link_to_consumers - Create device links to consumers of a device
2118 * @dev: Device that needs to be linked to its consumers
2120 * This function looks at all the consumer fwnodes of @dev and creates device
2121 * links between the consumer device and @dev (supplier).
2123 * If the consumer device has not been added yet, then this function creates a
2124 * SYNC_STATE_ONLY link between @dev (supplier) and the closest ancestor device
2125 * of the consumer fwnode. This is necessary to make sure @dev doesn't get a
2126 * sync_state() callback before the real consumer device gets to be added and
2129 * Once device links are created from the real consumer to @dev (supplier), the
2130 * fwnode links are deleted.
2132 static void __fw_devlink_link_to_consumers(struct device *dev)
2134 struct fwnode_handle *fwnode = dev->fwnode;
2135 struct fwnode_link *link, *tmp;
2137 list_for_each_entry_safe(link, tmp, &fwnode->consumers, s_hook) {
2138 struct device *con_dev;
2139 bool own_link = true;
2142 con_dev = get_dev_from_fwnode(link->consumer);
2144 * If consumer device is not available yet, make a "proxy"
2145 * SYNC_STATE_ONLY link from the consumer's parent device to
2146 * the supplier device. This is necessary to make sure the
2147 * supplier doesn't get a sync_state() callback before the real
2148 * consumer can create a device link to the supplier.
2150 * This proxy link step is needed to handle the case where the
2151 * consumer's parent device is added before the supplier.
2154 con_dev = fwnode_get_next_parent_dev(link->consumer);
2156 * However, if the consumer's parent device is also the
2157 * parent of the supplier, don't create a
2158 * consumer-supplier link from the parent to its child
2159 * device. Such a dependency is impossible.
2162 fwnode_is_ancestor_of(con_dev->fwnode, fwnode)) {
2163 put_device(con_dev);
2173 ret = fw_devlink_create_devlink(con_dev, fwnode, link);
2174 put_device(con_dev);
2175 if (!own_link || ret == -EAGAIN)
2178 __fwnode_link_del(link);
2183 * __fw_devlink_link_to_suppliers - Create device links to suppliers of a device
2184 * @dev: The consumer device that needs to be linked to its suppliers
2185 * @fwnode: Root of the fwnode tree that is used to create device links
2187 * This function looks at all the supplier fwnodes of fwnode tree rooted at
2188 * @fwnode and creates device links between @dev (consumer) and all the
2189 * supplier devices of the entire fwnode tree at @fwnode.
2191 * The function creates normal (non-SYNC_STATE_ONLY) device links between @dev
2192 * and the real suppliers of @dev. Once these device links are created, the
2193 * fwnode links are deleted.
2195 * In addition, it also looks at all the suppliers of the entire fwnode tree
2196 * because some of the child devices of @dev that have not been added yet
2197 * (because @dev hasn't probed) might already have their suppliers added to
2198 * driver core. So, this function creates SYNC_STATE_ONLY device links between
2199 * @dev (consumer) and these suppliers to make sure they don't execute their
2200 * sync_state() callbacks before these child devices have a chance to create
2201 * their device links. The fwnode links that correspond to the child devices
2202 * aren't delete because they are needed later to create the device links
2203 * between the real consumer and supplier devices.
2205 static void __fw_devlink_link_to_suppliers(struct device *dev,
2206 struct fwnode_handle *fwnode)
2208 bool own_link = (dev->fwnode == fwnode);
2209 struct fwnode_link *link, *tmp;
2210 struct fwnode_handle *child = NULL;
2212 list_for_each_entry_safe(link, tmp, &fwnode->suppliers, c_hook) {
2214 struct fwnode_handle *sup = link->supplier;
2216 ret = fw_devlink_create_devlink(dev, sup, link);
2217 if (!own_link || ret == -EAGAIN)
2220 __fwnode_link_del(link);
2224 * Make "proxy" SYNC_STATE_ONLY device links to represent the needs of
2225 * all the descendants. This proxy link step is needed to handle the
2226 * case where the supplier is added before the consumer's parent device
2229 while ((child = fwnode_get_next_available_child_node(fwnode, child)))
2230 __fw_devlink_link_to_suppliers(dev, child);
2233 static void fw_devlink_link_device(struct device *dev)
2235 struct fwnode_handle *fwnode = dev->fwnode;
2237 if (!fw_devlink_flags)
2240 fw_devlink_parse_fwtree(fwnode);
2242 mutex_lock(&fwnode_link_lock);
2243 __fw_devlink_link_to_consumers(dev);
2244 __fw_devlink_link_to_suppliers(dev, fwnode);
2245 mutex_unlock(&fwnode_link_lock);
2248 /* Device links support end. */
2250 int (*platform_notify)(struct device *dev) = NULL;
2251 int (*platform_notify_remove)(struct device *dev) = NULL;
2252 static struct kobject *dev_kobj;
2253 struct kobject *sysfs_dev_char_kobj;
2254 struct kobject *sysfs_dev_block_kobj;
2256 static DEFINE_MUTEX(device_hotplug_lock);
2258 void lock_device_hotplug(void)
2260 mutex_lock(&device_hotplug_lock);
2263 void unlock_device_hotplug(void)
2265 mutex_unlock(&device_hotplug_lock);
2268 int lock_device_hotplug_sysfs(void)
2270 if (mutex_trylock(&device_hotplug_lock))
2273 /* Avoid busy looping (5 ms of sleep should do). */
2275 return restart_syscall();
2279 static inline int device_is_not_partition(struct device *dev)
2281 return !(dev->type == &part_type);
2284 static inline int device_is_not_partition(struct device *dev)
2290 static void device_platform_notify(struct device *dev)
2292 acpi_device_notify(dev);
2294 software_node_notify(dev);
2296 if (platform_notify)
2297 platform_notify(dev);
2300 static void device_platform_notify_remove(struct device *dev)
2302 acpi_device_notify_remove(dev);
2304 software_node_notify_remove(dev);
2306 if (platform_notify_remove)
2307 platform_notify_remove(dev);
2311 * dev_driver_string - Return a device's driver name, if at all possible
2312 * @dev: struct device to get the name of
2314 * Will return the device's driver's name if it is bound to a device. If
2315 * the device is not bound to a driver, it will return the name of the bus
2316 * it is attached to. If it is not attached to a bus either, an empty
2317 * string will be returned.
2319 const char *dev_driver_string(const struct device *dev)
2321 struct device_driver *drv;
2323 /* dev->driver can change to NULL underneath us because of unbinding,
2324 * so be careful about accessing it. dev->bus and dev->class should
2325 * never change once they are set, so they don't need special care.
2327 drv = READ_ONCE(dev->driver);
2328 return drv ? drv->name : dev_bus_name(dev);
2330 EXPORT_SYMBOL(dev_driver_string);
2332 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
2334 static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
2337 struct device_attribute *dev_attr = to_dev_attr(attr);
2338 struct device *dev = kobj_to_dev(kobj);
2342 ret = dev_attr->show(dev, dev_attr, buf);
2343 if (ret >= (ssize_t)PAGE_SIZE) {
2344 printk("dev_attr_show: %pS returned bad count\n",
2350 static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
2351 const char *buf, size_t count)
2353 struct device_attribute *dev_attr = to_dev_attr(attr);
2354 struct device *dev = kobj_to_dev(kobj);
2357 if (dev_attr->store)
2358 ret = dev_attr->store(dev, dev_attr, buf, count);
2362 static const struct sysfs_ops dev_sysfs_ops = {
2363 .show = dev_attr_show,
2364 .store = dev_attr_store,
2367 #define to_ext_attr(x) container_of(x, struct dev_ext_attribute, attr)
2369 ssize_t device_store_ulong(struct device *dev,
2370 struct device_attribute *attr,
2371 const char *buf, size_t size)
2373 struct dev_ext_attribute *ea = to_ext_attr(attr);
2377 ret = kstrtoul(buf, 0, &new);
2380 *(unsigned long *)(ea->var) = new;
2381 /* Always return full write size even if we didn't consume all */
2384 EXPORT_SYMBOL_GPL(device_store_ulong);
2386 ssize_t device_show_ulong(struct device *dev,
2387 struct device_attribute *attr,
2390 struct dev_ext_attribute *ea = to_ext_attr(attr);
2391 return sysfs_emit(buf, "%lx\n", *(unsigned long *)(ea->var));
2393 EXPORT_SYMBOL_GPL(device_show_ulong);
2395 ssize_t device_store_int(struct device *dev,
2396 struct device_attribute *attr,
2397 const char *buf, size_t size)
2399 struct dev_ext_attribute *ea = to_ext_attr(attr);
2403 ret = kstrtol(buf, 0, &new);
2407 if (new > INT_MAX || new < INT_MIN)
2409 *(int *)(ea->var) = new;
2410 /* Always return full write size even if we didn't consume all */
2413 EXPORT_SYMBOL_GPL(device_store_int);
2415 ssize_t device_show_int(struct device *dev,
2416 struct device_attribute *attr,
2419 struct dev_ext_attribute *ea = to_ext_attr(attr);
2421 return sysfs_emit(buf, "%d\n", *(int *)(ea->var));
2423 EXPORT_SYMBOL_GPL(device_show_int);
2425 ssize_t device_store_bool(struct device *dev, struct device_attribute *attr,
2426 const char *buf, size_t size)
2428 struct dev_ext_attribute *ea = to_ext_attr(attr);
2430 if (strtobool(buf, ea->var) < 0)
2435 EXPORT_SYMBOL_GPL(device_store_bool);
2437 ssize_t device_show_bool(struct device *dev, struct device_attribute *attr,
2440 struct dev_ext_attribute *ea = to_ext_attr(attr);
2442 return sysfs_emit(buf, "%d\n", *(bool *)(ea->var));
2444 EXPORT_SYMBOL_GPL(device_show_bool);
2447 * device_release - free device structure.
2448 * @kobj: device's kobject.
2450 * This is called once the reference count for the object
2451 * reaches 0. We forward the call to the device's release
2452 * method, which should handle actually freeing the structure.
2454 static void device_release(struct kobject *kobj)
2456 struct device *dev = kobj_to_dev(kobj);
2457 struct device_private *p = dev->p;
2460 * Some platform devices are driven without driver attached
2461 * and managed resources may have been acquired. Make sure
2462 * all resources are released.
2464 * Drivers still can add resources into device after device
2465 * is deleted but alive, so release devres here to avoid
2466 * possible memory leak.
2468 devres_release_all(dev);
2470 kfree(dev->dma_range_map);
2474 else if (dev->type && dev->type->release)
2475 dev->type->release(dev);
2476 else if (dev->class && dev->class->dev_release)
2477 dev->class->dev_release(dev);
2479 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",
2484 static const void *device_namespace(struct kobject *kobj)
2486 struct device *dev = kobj_to_dev(kobj);
2487 const void *ns = NULL;
2489 if (dev->class && dev->class->ns_type)
2490 ns = dev->class->namespace(dev);
2495 static void device_get_ownership(struct kobject *kobj, kuid_t *uid, kgid_t *gid)
2497 struct device *dev = kobj_to_dev(kobj);
2499 if (dev->class && dev->class->get_ownership)
2500 dev->class->get_ownership(dev, uid, gid);
2503 static struct kobj_type device_ktype = {
2504 .release = device_release,
2505 .sysfs_ops = &dev_sysfs_ops,
2506 .namespace = device_namespace,
2507 .get_ownership = device_get_ownership,
2511 static int dev_uevent_filter(struct kobject *kobj)
2513 const struct kobj_type *ktype = get_ktype(kobj);
2515 if (ktype == &device_ktype) {
2516 struct device *dev = kobj_to_dev(kobj);
2525 static const char *dev_uevent_name(struct kobject *kobj)
2527 struct device *dev = kobj_to_dev(kobj);
2530 return dev->bus->name;
2532 return dev->class->name;
2536 static int dev_uevent(struct kobject *kobj, struct kobj_uevent_env *env)
2538 struct device *dev = kobj_to_dev(kobj);
2541 /* add device node properties if present */
2542 if (MAJOR(dev->devt)) {
2546 kuid_t uid = GLOBAL_ROOT_UID;
2547 kgid_t gid = GLOBAL_ROOT_GID;
2549 add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt));
2550 add_uevent_var(env, "MINOR=%u", MINOR(dev->devt));
2551 name = device_get_devnode(dev, &mode, &uid, &gid, &tmp);
2553 add_uevent_var(env, "DEVNAME=%s", name);
2555 add_uevent_var(env, "DEVMODE=%#o", mode & 0777);
2556 if (!uid_eq(uid, GLOBAL_ROOT_UID))
2557 add_uevent_var(env, "DEVUID=%u", from_kuid(&init_user_ns, uid));
2558 if (!gid_eq(gid, GLOBAL_ROOT_GID))
2559 add_uevent_var(env, "DEVGID=%u", from_kgid(&init_user_ns, gid));
2564 if (dev->type && dev->type->name)
2565 add_uevent_var(env, "DEVTYPE=%s", dev->type->name);
2568 add_uevent_var(env, "DRIVER=%s", dev->driver->name);
2570 /* Add common DT information about the device */
2571 of_device_uevent(dev, env);
2573 /* have the bus specific function add its stuff */
2574 if (dev->bus && dev->bus->uevent) {
2575 retval = dev->bus->uevent(dev, env);
2577 pr_debug("device: '%s': %s: bus uevent() returned %d\n",
2578 dev_name(dev), __func__, retval);
2581 /* have the class specific function add its stuff */
2582 if (dev->class && dev->class->dev_uevent) {
2583 retval = dev->class->dev_uevent(dev, env);
2585 pr_debug("device: '%s': %s: class uevent() "
2586 "returned %d\n", dev_name(dev),
2590 /* have the device type specific function add its stuff */
2591 if (dev->type && dev->type->uevent) {
2592 retval = dev->type->uevent(dev, env);
2594 pr_debug("device: '%s': %s: dev_type uevent() "
2595 "returned %d\n", dev_name(dev),
2602 static const struct kset_uevent_ops device_uevent_ops = {
2603 .filter = dev_uevent_filter,
2604 .name = dev_uevent_name,
2605 .uevent = dev_uevent,
2608 static ssize_t uevent_show(struct device *dev, struct device_attribute *attr,
2611 struct kobject *top_kobj;
2613 struct kobj_uevent_env *env = NULL;
2618 /* search the kset, the device belongs to */
2619 top_kobj = &dev->kobj;
2620 while (!top_kobj->kset && top_kobj->parent)
2621 top_kobj = top_kobj->parent;
2622 if (!top_kobj->kset)
2625 kset = top_kobj->kset;
2626 if (!kset->uevent_ops || !kset->uevent_ops->uevent)
2629 /* respect filter */
2630 if (kset->uevent_ops && kset->uevent_ops->filter)
2631 if (!kset->uevent_ops->filter(&dev->kobj))
2634 env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
2638 /* let the kset specific function add its keys */
2639 retval = kset->uevent_ops->uevent(&dev->kobj, env);
2643 /* copy keys to file */
2644 for (i = 0; i < env->envp_idx; i++)
2645 len += sysfs_emit_at(buf, len, "%s\n", env->envp[i]);
2651 static ssize_t uevent_store(struct device *dev, struct device_attribute *attr,
2652 const char *buf, size_t count)
2656 rc = kobject_synth_uevent(&dev->kobj, buf, count);
2659 dev_err(dev, "uevent: failed to send synthetic uevent: %d\n", rc);
2665 static DEVICE_ATTR_RW(uevent);
2667 static ssize_t online_show(struct device *dev, struct device_attribute *attr,
2673 val = !dev->offline;
2675 return sysfs_emit(buf, "%u\n", val);
2678 static ssize_t online_store(struct device *dev, struct device_attribute *attr,
2679 const char *buf, size_t count)
2684 ret = strtobool(buf, &val);
2688 ret = lock_device_hotplug_sysfs();
2692 ret = val ? device_online(dev) : device_offline(dev);
2693 unlock_device_hotplug();
2694 return ret < 0 ? ret : count;
2696 static DEVICE_ATTR_RW(online);
2698 static ssize_t removable_show(struct device *dev, struct device_attribute *attr,
2703 switch (dev->removable) {
2704 case DEVICE_REMOVABLE:
2713 return sysfs_emit(buf, "%s\n", loc);
2715 static DEVICE_ATTR_RO(removable);
2717 int device_add_groups(struct device *dev, const struct attribute_group **groups)
2719 return sysfs_create_groups(&dev->kobj, groups);
2721 EXPORT_SYMBOL_GPL(device_add_groups);
2723 void device_remove_groups(struct device *dev,
2724 const struct attribute_group **groups)
2726 sysfs_remove_groups(&dev->kobj, groups);
2728 EXPORT_SYMBOL_GPL(device_remove_groups);
2730 union device_attr_group_devres {
2731 const struct attribute_group *group;
2732 const struct attribute_group **groups;
2735 static int devm_attr_group_match(struct device *dev, void *res, void *data)
2737 return ((union device_attr_group_devres *)res)->group == data;
2740 static void devm_attr_group_remove(struct device *dev, void *res)
2742 union device_attr_group_devres *devres = res;
2743 const struct attribute_group *group = devres->group;
2745 dev_dbg(dev, "%s: removing group %p\n", __func__, group);
2746 sysfs_remove_group(&dev->kobj, group);
2749 static void devm_attr_groups_remove(struct device *dev, void *res)
2751 union device_attr_group_devres *devres = res;
2752 const struct attribute_group **groups = devres->groups;
2754 dev_dbg(dev, "%s: removing groups %p\n", __func__, groups);
2755 sysfs_remove_groups(&dev->kobj, groups);
2759 * devm_device_add_group - given a device, create a managed attribute group
2760 * @dev: The device to create the group for
2761 * @grp: The attribute group to create
2763 * This function creates a group for the first time. It will explicitly
2764 * warn and error if any of the attribute files being created already exist.
2766 * Returns 0 on success or error code on failure.
2768 int devm_device_add_group(struct device *dev, const struct attribute_group *grp)
2770 union device_attr_group_devres *devres;
2773 devres = devres_alloc(devm_attr_group_remove,
2774 sizeof(*devres), GFP_KERNEL);
2778 error = sysfs_create_group(&dev->kobj, grp);
2780 devres_free(devres);
2784 devres->group = grp;
2785 devres_add(dev, devres);
2788 EXPORT_SYMBOL_GPL(devm_device_add_group);
2791 * devm_device_remove_group: remove a managed group from a device
2792 * @dev: device to remove the group from
2793 * @grp: group to remove
2795 * This function removes a group of attributes from a device. The attributes
2796 * previously have to have been created for this group, otherwise it will fail.
2798 void devm_device_remove_group(struct device *dev,
2799 const struct attribute_group *grp)
2801 WARN_ON(devres_release(dev, devm_attr_group_remove,
2802 devm_attr_group_match,
2803 /* cast away const */ (void *)grp));
2805 EXPORT_SYMBOL_GPL(devm_device_remove_group);
2808 * devm_device_add_groups - create a bunch of managed attribute groups
2809 * @dev: The device to create the group for
2810 * @groups: The attribute groups to create, NULL terminated
2812 * This function creates a bunch of managed attribute groups. If an error
2813 * occurs when creating a group, all previously created groups will be
2814 * removed, unwinding everything back to the original state when this
2815 * function was called. It will explicitly warn and error if any of the
2816 * attribute files being created already exist.
2818 * Returns 0 on success or error code from sysfs_create_group on failure.
2820 int devm_device_add_groups(struct device *dev,
2821 const struct attribute_group **groups)
2823 union device_attr_group_devres *devres;
2826 devres = devres_alloc(devm_attr_groups_remove,
2827 sizeof(*devres), GFP_KERNEL);
2831 error = sysfs_create_groups(&dev->kobj, groups);
2833 devres_free(devres);
2837 devres->groups = groups;
2838 devres_add(dev, devres);
2841 EXPORT_SYMBOL_GPL(devm_device_add_groups);
2844 * devm_device_remove_groups - remove a list of managed groups
2846 * @dev: The device for the groups to be removed from
2847 * @groups: NULL terminated list of groups to be removed
2849 * If groups is not NULL, remove the specified groups from the device.
2851 void devm_device_remove_groups(struct device *dev,
2852 const struct attribute_group **groups)
2854 WARN_ON(devres_release(dev, devm_attr_groups_remove,
2855 devm_attr_group_match,
2856 /* cast away const */ (void *)groups));
2858 EXPORT_SYMBOL_GPL(devm_device_remove_groups);
2860 static int device_add_attrs(struct device *dev)
2862 struct class *class = dev->class;
2863 const struct device_type *type = dev->type;
2867 error = device_add_groups(dev, class->dev_groups);
2873 error = device_add_groups(dev, type->groups);
2875 goto err_remove_class_groups;
2878 error = device_add_groups(dev, dev->groups);
2880 goto err_remove_type_groups;
2882 if (device_supports_offline(dev) && !dev->offline_disabled) {
2883 error = device_create_file(dev, &dev_attr_online);
2885 goto err_remove_dev_groups;
2888 if (fw_devlink_flags && !fw_devlink_is_permissive() && dev->fwnode) {
2889 error = device_create_file(dev, &dev_attr_waiting_for_supplier);
2891 goto err_remove_dev_online;
2894 if (dev_removable_is_valid(dev)) {
2895 error = device_create_file(dev, &dev_attr_removable);
2897 goto err_remove_dev_waiting_for_supplier;
2900 if (dev_add_physical_location(dev)) {
2901 error = device_add_group(dev,
2902 &dev_attr_physical_location_group);
2904 goto err_remove_dev_removable;
2909 err_remove_dev_removable:
2910 device_remove_file(dev, &dev_attr_removable);
2911 err_remove_dev_waiting_for_supplier:
2912 device_remove_file(dev, &dev_attr_waiting_for_supplier);
2913 err_remove_dev_online:
2914 device_remove_file(dev, &dev_attr_online);
2915 err_remove_dev_groups:
2916 device_remove_groups(dev, dev->groups);
2917 err_remove_type_groups:
2919 device_remove_groups(dev, type->groups);
2920 err_remove_class_groups:
2922 device_remove_groups(dev, class->dev_groups);
2927 static void device_remove_attrs(struct device *dev)
2929 struct class *class = dev->class;
2930 const struct device_type *type = dev->type;
2932 if (dev->physical_location) {
2933 device_remove_group(dev, &dev_attr_physical_location_group);
2934 kfree(dev->physical_location);
2937 device_remove_file(dev, &dev_attr_removable);
2938 device_remove_file(dev, &dev_attr_waiting_for_supplier);
2939 device_remove_file(dev, &dev_attr_online);
2940 device_remove_groups(dev, dev->groups);
2943 device_remove_groups(dev, type->groups);
2946 device_remove_groups(dev, class->dev_groups);
2949 static ssize_t dev_show(struct device *dev, struct device_attribute *attr,
2952 return print_dev_t(buf, dev->devt);
2954 static DEVICE_ATTR_RO(dev);
2957 struct kset *devices_kset;
2960 * devices_kset_move_before - Move device in the devices_kset's list.
2961 * @deva: Device to move.
2962 * @devb: Device @deva should come before.
2964 static void devices_kset_move_before(struct device *deva, struct device *devb)
2968 pr_debug("devices_kset: Moving %s before %s\n",
2969 dev_name(deva), dev_name(devb));
2970 spin_lock(&devices_kset->list_lock);
2971 list_move_tail(&deva->kobj.entry, &devb->kobj.entry);
2972 spin_unlock(&devices_kset->list_lock);
2976 * devices_kset_move_after - Move device in the devices_kset's list.
2977 * @deva: Device to move
2978 * @devb: Device @deva should come after.
2980 static void devices_kset_move_after(struct device *deva, struct device *devb)
2984 pr_debug("devices_kset: Moving %s after %s\n",
2985 dev_name(deva), dev_name(devb));
2986 spin_lock(&devices_kset->list_lock);
2987 list_move(&deva->kobj.entry, &devb->kobj.entry);
2988 spin_unlock(&devices_kset->list_lock);
2992 * devices_kset_move_last - move the device to the end of devices_kset's list.
2993 * @dev: device to move
2995 void devices_kset_move_last(struct device *dev)
2999 pr_debug("devices_kset: Moving %s to end of list\n", dev_name(dev));
3000 spin_lock(&devices_kset->list_lock);
3001 list_move_tail(&dev->kobj.entry, &devices_kset->list);
3002 spin_unlock(&devices_kset->list_lock);
3006 * device_create_file - create sysfs attribute file for device.
3008 * @attr: device attribute descriptor.
3010 int device_create_file(struct device *dev,
3011 const struct device_attribute *attr)
3016 WARN(((attr->attr.mode & S_IWUGO) && !attr->store),
3017 "Attribute %s: write permission without 'store'\n",
3019 WARN(((attr->attr.mode & S_IRUGO) && !attr->show),
3020 "Attribute %s: read permission without 'show'\n",
3022 error = sysfs_create_file(&dev->kobj, &attr->attr);
3027 EXPORT_SYMBOL_GPL(device_create_file);
3030 * device_remove_file - remove sysfs attribute file.
3032 * @attr: device attribute descriptor.
3034 void device_remove_file(struct device *dev,
3035 const struct device_attribute *attr)
3038 sysfs_remove_file(&dev->kobj, &attr->attr);
3040 EXPORT_SYMBOL_GPL(device_remove_file);
3043 * device_remove_file_self - remove sysfs attribute file from its own method.
3045 * @attr: device attribute descriptor.
3047 * See kernfs_remove_self() for details.
3049 bool device_remove_file_self(struct device *dev,
3050 const struct device_attribute *attr)
3053 return sysfs_remove_file_self(&dev->kobj, &attr->attr);
3057 EXPORT_SYMBOL_GPL(device_remove_file_self);
3060 * device_create_bin_file - create sysfs binary attribute file for device.
3062 * @attr: device binary attribute descriptor.
3064 int device_create_bin_file(struct device *dev,
3065 const struct bin_attribute *attr)
3067 int error = -EINVAL;
3069 error = sysfs_create_bin_file(&dev->kobj, attr);
3072 EXPORT_SYMBOL_GPL(device_create_bin_file);
3075 * device_remove_bin_file - remove sysfs binary attribute file
3077 * @attr: device binary attribute descriptor.
3079 void device_remove_bin_file(struct device *dev,
3080 const struct bin_attribute *attr)
3083 sysfs_remove_bin_file(&dev->kobj, attr);
3085 EXPORT_SYMBOL_GPL(device_remove_bin_file);
3087 static void klist_children_get(struct klist_node *n)
3089 struct device_private *p = to_device_private_parent(n);
3090 struct device *dev = p->device;
3095 static void klist_children_put(struct klist_node *n)
3097 struct device_private *p = to_device_private_parent(n);
3098 struct device *dev = p->device;
3104 * device_initialize - init device structure.
3107 * This prepares the device for use by other layers by initializing
3109 * It is the first half of device_register(), if called by
3110 * that function, though it can also be called separately, so one
3111 * may use @dev's fields. In particular, get_device()/put_device()
3112 * may be used for reference counting of @dev after calling this
3115 * All fields in @dev must be initialized by the caller to 0, except
3116 * for those explicitly set to some other value. The simplest
3117 * approach is to use kzalloc() to allocate the structure containing
3120 * NOTE: Use put_device() to give up your reference instead of freeing
3121 * @dev directly once you have called this function.
3123 void device_initialize(struct device *dev)
3125 dev->kobj.kset = devices_kset;
3126 kobject_init(&dev->kobj, &device_ktype);
3127 INIT_LIST_HEAD(&dev->dma_pools);
3128 mutex_init(&dev->mutex);
3129 lockdep_set_novalidate_class(&dev->mutex);
3130 spin_lock_init(&dev->devres_lock);
3131 INIT_LIST_HEAD(&dev->devres_head);
3132 device_pm_init(dev);
3133 set_dev_node(dev, NUMA_NO_NODE);
3134 INIT_LIST_HEAD(&dev->links.consumers);
3135 INIT_LIST_HEAD(&dev->links.suppliers);
3136 INIT_LIST_HEAD(&dev->links.defer_sync);
3137 dev->links.status = DL_DEV_NO_DRIVER;
3138 #if defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_DEVICE) || \
3139 defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_CPU) || \
3140 defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_CPU_ALL)
3141 dev->dma_coherent = dma_default_coherent;
3143 #ifdef CONFIG_SWIOTLB
3144 dev->dma_io_tlb_mem = &io_tlb_default_mem;
3147 EXPORT_SYMBOL_GPL(device_initialize);
3149 struct kobject *virtual_device_parent(struct device *dev)
3151 static struct kobject *virtual_dir = NULL;
3154 virtual_dir = kobject_create_and_add("virtual",
3155 &devices_kset->kobj);
3161 struct kobject kobj;
3162 struct class *class;
3165 #define to_class_dir(obj) container_of(obj, struct class_dir, kobj)
3167 static void class_dir_release(struct kobject *kobj)
3169 struct class_dir *dir = to_class_dir(kobj);
3174 struct kobj_ns_type_operations *class_dir_child_ns_type(struct kobject *kobj)
3176 struct class_dir *dir = to_class_dir(kobj);
3177 return dir->class->ns_type;
3180 static struct kobj_type class_dir_ktype = {
3181 .release = class_dir_release,
3182 .sysfs_ops = &kobj_sysfs_ops,
3183 .child_ns_type = class_dir_child_ns_type
3186 static struct kobject *
3187 class_dir_create_and_add(struct class *class, struct kobject *parent_kobj)
3189 struct class_dir *dir;
3192 dir = kzalloc(sizeof(*dir), GFP_KERNEL);
3194 return ERR_PTR(-ENOMEM);
3197 kobject_init(&dir->kobj, &class_dir_ktype);
3199 dir->kobj.kset = &class->p->glue_dirs;
3201 retval = kobject_add(&dir->kobj, parent_kobj, "%s", class->name);
3203 kobject_put(&dir->kobj);
3204 return ERR_PTR(retval);
3209 static DEFINE_MUTEX(gdp_mutex);
3211 static struct kobject *get_device_parent(struct device *dev,
3212 struct device *parent)
3215 struct kobject *kobj = NULL;
3216 struct kobject *parent_kobj;
3220 /* block disks show up in /sys/block */
3221 if (sysfs_deprecated && dev->class == &block_class) {
3222 if (parent && parent->class == &block_class)
3223 return &parent->kobj;
3224 return &block_class.p->subsys.kobj;
3229 * If we have no parent, we live in "virtual".
3230 * Class-devices with a non class-device as parent, live
3231 * in a "glue" directory to prevent namespace collisions.
3234 parent_kobj = virtual_device_parent(dev);
3235 else if (parent->class && !dev->class->ns_type)
3236 return &parent->kobj;
3238 parent_kobj = &parent->kobj;
3240 mutex_lock(&gdp_mutex);
3242 /* find our class-directory at the parent and reference it */
3243 spin_lock(&dev->class->p->glue_dirs.list_lock);
3244 list_for_each_entry(k, &dev->class->p->glue_dirs.list, entry)
3245 if (k->parent == parent_kobj) {
3246 kobj = kobject_get(k);
3249 spin_unlock(&dev->class->p->glue_dirs.list_lock);
3251 mutex_unlock(&gdp_mutex);
3255 /* or create a new class-directory at the parent device */
3256 k = class_dir_create_and_add(dev->class, parent_kobj);
3257 /* do not emit an uevent for this simple "glue" directory */
3258 mutex_unlock(&gdp_mutex);
3262 /* subsystems can specify a default root directory for their devices */
3263 if (!parent && dev->bus && dev->bus->dev_root)
3264 return &dev->bus->dev_root->kobj;
3267 return &parent->kobj;
3271 static inline bool live_in_glue_dir(struct kobject *kobj,
3274 if (!kobj || !dev->class ||
3275 kobj->kset != &dev->class->p->glue_dirs)
3280 static inline struct kobject *get_glue_dir(struct device *dev)
3282 return dev->kobj.parent;
3286 * kobject_has_children - Returns whether a kobject has children.
3287 * @kobj: the object to test
3289 * This will return whether a kobject has other kobjects as children.
3291 * It does NOT account for the presence of attribute files, only sub
3292 * directories. It also assumes there is no concurrent addition or
3293 * removal of such children, and thus relies on external locking.
3295 static inline bool kobject_has_children(struct kobject *kobj)
3297 WARN_ON_ONCE(kref_read(&kobj->kref) == 0);
3299 return kobj->sd && kobj->sd->dir.subdirs;
3303 * make sure cleaning up dir as the last step, we need to make
3304 * sure .release handler of kobject is run with holding the
3307 static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir)
3311 /* see if we live in a "glue" directory */
3312 if (!live_in_glue_dir(glue_dir, dev))
3315 mutex_lock(&gdp_mutex);
3317 * There is a race condition between removing glue directory
3318 * and adding a new device under the glue directory.
3323 * get_device_parent()
3324 * class_dir_create_and_add()
3325 * kobject_add_internal()
3326 * create_dir() // create glue_dir
3329 * get_device_parent()
3330 * kobject_get() // get glue_dir
3333 * cleanup_glue_dir()
3334 * kobject_del(glue_dir)
3337 * kobject_add_internal()
3338 * create_dir() // in glue_dir
3339 * sysfs_create_dir_ns()
3340 * kernfs_create_dir_ns(sd)
3342 * sysfs_remove_dir() // glue_dir->sd=NULL
3343 * sysfs_put() // free glue_dir->sd
3346 * kernfs_new_node(sd)
3347 * kernfs_get(glue_dir)
3351 * Before CPU1 remove last child device under glue dir, if CPU2 add
3352 * a new device under glue dir, the glue_dir kobject reference count
3353 * will be increase to 2 in kobject_get(k). And CPU2 has been called
3354 * kernfs_create_dir_ns(). Meanwhile, CPU1 call sysfs_remove_dir()
3355 * and sysfs_put(). This result in glue_dir->sd is freed.
3357 * Then the CPU2 will see a stale "empty" but still potentially used
3358 * glue dir around in kernfs_new_node().
3360 * In order to avoid this happening, we also should make sure that
3361 * kernfs_node for glue_dir is released in CPU1 only when refcount
3362 * for glue_dir kobj is 1.
3364 ref = kref_read(&glue_dir->kref);
3365 if (!kobject_has_children(glue_dir) && !--ref)
3366 kobject_del(glue_dir);
3367 kobject_put(glue_dir);
3368 mutex_unlock(&gdp_mutex);
3371 static int device_add_class_symlinks(struct device *dev)
3373 struct device_node *of_node = dev_of_node(dev);
3377 error = sysfs_create_link(&dev->kobj, of_node_kobj(of_node), "of_node");
3379 dev_warn(dev, "Error %d creating of_node link\n",error);
3380 /* An error here doesn't warrant bringing down the device */
3386 error = sysfs_create_link(&dev->kobj,
3387 &dev->class->p->subsys.kobj,
3392 if (dev->parent && device_is_not_partition(dev)) {
3393 error = sysfs_create_link(&dev->kobj, &dev->parent->kobj,
3400 /* /sys/block has directories and does not need symlinks */
3401 if (sysfs_deprecated && dev->class == &block_class)
3405 /* link in the class directory pointing to the device */
3406 error = sysfs_create_link(&dev->class->p->subsys.kobj,
3407 &dev->kobj, dev_name(dev));
3414 sysfs_remove_link(&dev->kobj, "device");
3417 sysfs_remove_link(&dev->kobj, "subsystem");
3419 sysfs_remove_link(&dev->kobj, "of_node");
3423 static void device_remove_class_symlinks(struct device *dev)
3425 if (dev_of_node(dev))
3426 sysfs_remove_link(&dev->kobj, "of_node");
3431 if (dev->parent && device_is_not_partition(dev))
3432 sysfs_remove_link(&dev->kobj, "device");
3433 sysfs_remove_link(&dev->kobj, "subsystem");
3435 if (sysfs_deprecated && dev->class == &block_class)
3438 sysfs_delete_link(&dev->class->p->subsys.kobj, &dev->kobj, dev_name(dev));
3442 * dev_set_name - set a device name
3444 * @fmt: format string for the device's name
3446 int dev_set_name(struct device *dev, const char *fmt, ...)
3451 va_start(vargs, fmt);
3452 err = kobject_set_name_vargs(&dev->kobj, fmt, vargs);
3456 EXPORT_SYMBOL_GPL(dev_set_name);
3459 * device_to_dev_kobj - select a /sys/dev/ directory for the device
3462 * By default we select char/ for new entries. Setting class->dev_obj
3463 * to NULL prevents an entry from being created. class->dev_kobj must
3464 * be set (or cleared) before any devices are registered to the class
3465 * otherwise device_create_sys_dev_entry() and
3466 * device_remove_sys_dev_entry() will disagree about the presence of
3469 static struct kobject *device_to_dev_kobj(struct device *dev)
3471 struct kobject *kobj;
3474 kobj = dev->class->dev_kobj;
3476 kobj = sysfs_dev_char_kobj;
3481 static int device_create_sys_dev_entry(struct device *dev)
3483 struct kobject *kobj = device_to_dev_kobj(dev);
3488 format_dev_t(devt_str, dev->devt);
3489 error = sysfs_create_link(kobj, &dev->kobj, devt_str);
3495 static void device_remove_sys_dev_entry(struct device *dev)
3497 struct kobject *kobj = device_to_dev_kobj(dev);
3501 format_dev_t(devt_str, dev->devt);
3502 sysfs_remove_link(kobj, devt_str);
3506 static int device_private_init(struct device *dev)
3508 dev->p = kzalloc(sizeof(*dev->p), GFP_KERNEL);
3511 dev->p->device = dev;
3512 klist_init(&dev->p->klist_children, klist_children_get,
3513 klist_children_put);
3514 INIT_LIST_HEAD(&dev->p->deferred_probe);
3519 * device_add - add device to device hierarchy.
3522 * This is part 2 of device_register(), though may be called
3523 * separately _iff_ device_initialize() has been called separately.
3525 * This adds @dev to the kobject hierarchy via kobject_add(), adds it
3526 * to the global and sibling lists for the device, then
3527 * adds it to the other relevant subsystems of the driver model.
3529 * Do not call this routine or device_register() more than once for
3530 * any device structure. The driver model core is not designed to work
3531 * with devices that get unregistered and then spring back to life.
3532 * (Among other things, it's very hard to guarantee that all references
3533 * to the previous incarnation of @dev have been dropped.) Allocate
3534 * and register a fresh new struct device instead.
3536 * NOTE: _Never_ directly free @dev after calling this function, even
3537 * if it returned an error! Always use put_device() to give up your
3538 * reference instead.
3540 * Rule of thumb is: if device_add() succeeds, you should call
3541 * device_del() when you want to get rid of it. If device_add() has
3542 * *not* succeeded, use *only* put_device() to drop the reference
3545 int device_add(struct device *dev)
3547 struct device *parent;
3548 struct kobject *kobj;
3549 struct class_interface *class_intf;
3550 int error = -EINVAL;
3551 struct kobject *glue_dir = NULL;
3553 dev = get_device(dev);
3558 error = device_private_init(dev);
3564 * for statically allocated devices, which should all be converted
3565 * some day, we need to initialize the name. We prevent reading back
3566 * the name, and force the use of dev_name()
3568 if (dev->init_name) {
3569 dev_set_name(dev, "%s", dev->init_name);
3570 dev->init_name = NULL;
3573 /* subsystems can specify simple device enumeration */
3574 if (!dev_name(dev) && dev->bus && dev->bus->dev_name)
3575 dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
3577 if (!dev_name(dev)) {
3582 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3584 parent = get_device(dev->parent);
3585 kobj = get_device_parent(dev, parent);
3587 error = PTR_ERR(kobj);
3591 dev->kobj.parent = kobj;
3593 /* use parent numa_node */
3594 if (parent && (dev_to_node(dev) == NUMA_NO_NODE))
3595 set_dev_node(dev, dev_to_node(parent));
3597 /* first, register with generic layer. */
3598 /* we require the name to be set before, and pass NULL */
3599 error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
3605 /* notify platform of device entry */
3606 device_platform_notify(dev);
3608 error = device_create_file(dev, &dev_attr_uevent);
3612 error = device_add_class_symlinks(dev);
3615 error = device_add_attrs(dev);
3618 error = bus_add_device(dev);
3621 error = dpm_sysfs_add(dev);
3626 if (MAJOR(dev->devt)) {
3627 error = device_create_file(dev, &dev_attr_dev);
3631 error = device_create_sys_dev_entry(dev);
3635 devtmpfs_create_node(dev);
3638 /* Notify clients of device addition. This call must come
3639 * after dpm_sysfs_add() and before kobject_uevent().
3642 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
3643 BUS_NOTIFY_ADD_DEVICE, dev);
3645 kobject_uevent(&dev->kobj, KOBJ_ADD);
3648 * Check if any of the other devices (consumers) have been waiting for
3649 * this device (supplier) to be added so that they can create a device
3652 * This needs to happen after device_pm_add() because device_link_add()
3653 * requires the supplier be registered before it's called.
3655 * But this also needs to happen before bus_probe_device() to make sure
3656 * waiting consumers can link to it before the driver is bound to the
3657 * device and the driver sync_state callback is called for this device.
3659 if (dev->fwnode && !dev->fwnode->dev) {
3660 dev->fwnode->dev = dev;
3661 fw_devlink_link_device(dev);
3664 bus_probe_device(dev);
3667 * If all driver registration is done and a newly added device doesn't
3668 * match with any driver, don't block its consumers from probing in
3669 * case the consumer device is able to operate without this supplier.
3671 if (dev->fwnode && fw_devlink_drv_reg_done && !dev->can_match)
3672 fw_devlink_unblock_consumers(dev);
3675 klist_add_tail(&dev->p->knode_parent,
3676 &parent->p->klist_children);
3679 mutex_lock(&dev->class->p->mutex);
3680 /* tie the class to the device */
3681 klist_add_tail(&dev->p->knode_class,
3682 &dev->class->p->klist_devices);
3684 /* notify any interfaces that the device is here */
3685 list_for_each_entry(class_intf,
3686 &dev->class->p->interfaces, node)
3687 if (class_intf->add_dev)
3688 class_intf->add_dev(dev, class_intf);
3689 mutex_unlock(&dev->class->p->mutex);
3695 if (MAJOR(dev->devt))
3696 device_remove_file(dev, &dev_attr_dev);
3698 device_pm_remove(dev);
3699 dpm_sysfs_remove(dev);
3702 bus_remove_device(dev);
3704 device_remove_attrs(dev);
3706 device_remove_class_symlinks(dev);
3708 device_remove_file(dev, &dev_attr_uevent);
3710 device_platform_notify_remove(dev);
3711 kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3712 glue_dir = get_glue_dir(dev);
3713 kobject_del(&dev->kobj);
3715 cleanup_glue_dir(dev, glue_dir);
3723 EXPORT_SYMBOL_GPL(device_add);
3726 * device_register - register a device with the system.
3727 * @dev: pointer to the device structure
3729 * This happens in two clean steps - initialize the device
3730 * and add it to the system. The two steps can be called
3731 * separately, but this is the easiest and most common.
3732 * I.e. you should only call the two helpers separately if
3733 * have a clearly defined need to use and refcount the device
3734 * before it is added to the hierarchy.
3736 * For more information, see the kerneldoc for device_initialize()
3739 * NOTE: _Never_ directly free @dev after calling this function, even
3740 * if it returned an error! Always use put_device() to give up the
3741 * reference initialized in this function instead.
3743 int device_register(struct device *dev)
3745 device_initialize(dev);
3746 return device_add(dev);
3748 EXPORT_SYMBOL_GPL(device_register);
3751 * get_device - increment reference count for device.
3754 * This simply forwards the call to kobject_get(), though
3755 * we do take care to provide for the case that we get a NULL
3756 * pointer passed in.
3758 struct device *get_device(struct device *dev)
3760 return dev ? kobj_to_dev(kobject_get(&dev->kobj)) : NULL;
3762 EXPORT_SYMBOL_GPL(get_device);
3765 * put_device - decrement reference count.
3766 * @dev: device in question.
3768 void put_device(struct device *dev)
3770 /* might_sleep(); */
3772 kobject_put(&dev->kobj);
3774 EXPORT_SYMBOL_GPL(put_device);
3776 bool kill_device(struct device *dev)
3779 * Require the device lock and set the "dead" flag to guarantee that
3780 * the update behavior is consistent with the other bitfields near
3781 * it and that we cannot have an asynchronous probe routine trying
3782 * to run while we are tearing out the bus/class/sysfs from
3783 * underneath the device.
3785 device_lock_assert(dev);
3789 dev->p->dead = true;
3792 EXPORT_SYMBOL_GPL(kill_device);
3795 * device_del - delete device from system.
3798 * This is the first part of the device unregistration
3799 * sequence. This removes the device from the lists we control
3800 * from here, has it removed from the other driver model
3801 * subsystems it was added to in device_add(), and removes it
3802 * from the kobject hierarchy.
3804 * NOTE: this should be called manually _iff_ device_add() was
3805 * also called manually.
3807 void device_del(struct device *dev)
3809 struct device *parent = dev->parent;
3810 struct kobject *glue_dir = NULL;
3811 struct class_interface *class_intf;
3812 unsigned int noio_flag;
3818 if (dev->fwnode && dev->fwnode->dev == dev)
3819 dev->fwnode->dev = NULL;
3821 /* Notify clients of device removal. This call must come
3822 * before dpm_sysfs_remove().
3824 noio_flag = memalloc_noio_save();
3826 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
3827 BUS_NOTIFY_DEL_DEVICE, dev);
3829 dpm_sysfs_remove(dev);
3831 klist_del(&dev->p->knode_parent);
3832 if (MAJOR(dev->devt)) {
3833 devtmpfs_delete_node(dev);
3834 device_remove_sys_dev_entry(dev);
3835 device_remove_file(dev, &dev_attr_dev);
3838 device_remove_class_symlinks(dev);
3840 mutex_lock(&dev->class->p->mutex);
3841 /* notify any interfaces that the device is now gone */
3842 list_for_each_entry(class_intf,
3843 &dev->class->p->interfaces, node)
3844 if (class_intf->remove_dev)
3845 class_intf->remove_dev(dev, class_intf);
3846 /* remove the device from the class list */
3847 klist_del(&dev->p->knode_class);
3848 mutex_unlock(&dev->class->p->mutex);
3850 device_remove_file(dev, &dev_attr_uevent);
3851 device_remove_attrs(dev);
3852 bus_remove_device(dev);
3853 device_pm_remove(dev);
3854 driver_deferred_probe_del(dev);
3855 device_platform_notify_remove(dev);
3856 device_links_purge(dev);
3859 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
3860 BUS_NOTIFY_REMOVED_DEVICE, dev);
3861 kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3862 glue_dir = get_glue_dir(dev);
3863 kobject_del(&dev->kobj);
3864 cleanup_glue_dir(dev, glue_dir);
3865 memalloc_noio_restore(noio_flag);
3868 EXPORT_SYMBOL_GPL(device_del);
3871 * device_unregister - unregister device from system.
3872 * @dev: device going away.
3874 * We do this in two parts, like we do device_register(). First,
3875 * we remove it from all the subsystems with device_del(), then
3876 * we decrement the reference count via put_device(). If that
3877 * is the final reference count, the device will be cleaned up
3878 * via device_release() above. Otherwise, the structure will
3879 * stick around until the final reference to the device is dropped.
3881 void device_unregister(struct device *dev)
3883 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3887 EXPORT_SYMBOL_GPL(device_unregister);
3889 static struct device *prev_device(struct klist_iter *i)
3891 struct klist_node *n = klist_prev(i);
3892 struct device *dev = NULL;
3893 struct device_private *p;
3896 p = to_device_private_parent(n);
3902 static struct device *next_device(struct klist_iter *i)
3904 struct klist_node *n = klist_next(i);
3905 struct device *dev = NULL;
3906 struct device_private *p;
3909 p = to_device_private_parent(n);
3916 * device_get_devnode - path of device node file
3918 * @mode: returned file access mode
3919 * @uid: returned file owner
3920 * @gid: returned file group
3921 * @tmp: possibly allocated string
3923 * Return the relative path of a possible device node.
3924 * Non-default names may need to allocate a memory to compose
3925 * a name. This memory is returned in tmp and needs to be
3926 * freed by the caller.
3928 const char *device_get_devnode(struct device *dev,
3929 umode_t *mode, kuid_t *uid, kgid_t *gid,
3936 /* the device type may provide a specific name */
3937 if (dev->type && dev->type->devnode)
3938 *tmp = dev->type->devnode(dev, mode, uid, gid);
3942 /* the class may provide a specific name */
3943 if (dev->class && dev->class->devnode)
3944 *tmp = dev->class->devnode(dev, mode);
3948 /* return name without allocation, tmp == NULL */
3949 if (strchr(dev_name(dev), '!') == NULL)
3950 return dev_name(dev);
3952 /* replace '!' in the name with '/' */
3953 s = kstrdup(dev_name(dev), GFP_KERNEL);
3956 strreplace(s, '!', '/');
3961 * device_for_each_child - device child iterator.
3962 * @parent: parent struct device.
3963 * @fn: function to be called for each device.
3964 * @data: data for the callback.
3966 * Iterate over @parent's child devices, and call @fn for each,
3969 * We check the return of @fn each time. If it returns anything
3970 * other than 0, we break out and return that value.
3972 int device_for_each_child(struct device *parent, void *data,
3973 int (*fn)(struct device *dev, void *data))
3975 struct klist_iter i;
3976 struct device *child;
3982 klist_iter_init(&parent->p->klist_children, &i);
3983 while (!error && (child = next_device(&i)))
3984 error = fn(child, data);
3985 klist_iter_exit(&i);
3988 EXPORT_SYMBOL_GPL(device_for_each_child);
3991 * device_for_each_child_reverse - device child iterator in reversed order.
3992 * @parent: parent struct device.
3993 * @fn: function to be called for each device.
3994 * @data: data for the callback.
3996 * Iterate over @parent's child devices, and call @fn for each,
3999 * We check the return of @fn each time. If it returns anything
4000 * other than 0, we break out and return that value.
4002 int device_for_each_child_reverse(struct device *parent, void *data,
4003 int (*fn)(struct device *dev, void *data))
4005 struct klist_iter i;
4006 struct device *child;
4012 klist_iter_init(&parent->p->klist_children, &i);
4013 while ((child = prev_device(&i)) && !error)
4014 error = fn(child, data);
4015 klist_iter_exit(&i);
4018 EXPORT_SYMBOL_GPL(device_for_each_child_reverse);
4021 * device_find_child - device iterator for locating a particular device.
4022 * @parent: parent struct device
4023 * @match: Callback function to check device
4024 * @data: Data to pass to match function
4026 * This is similar to the device_for_each_child() function above, but it
4027 * returns a reference to a device that is 'found' for later use, as
4028 * determined by the @match callback.
4030 * The callback should return 0 if the device doesn't match and non-zero
4031 * if it does. If the callback returns non-zero and a reference to the
4032 * current device can be obtained, this function will return to the caller
4033 * and not iterate over any more devices.
4035 * NOTE: you will need to drop the reference with put_device() after use.
4037 struct device *device_find_child(struct device *parent, void *data,
4038 int (*match)(struct device *dev, void *data))
4040 struct klist_iter i;
4041 struct device *child;
4046 klist_iter_init(&parent->p->klist_children, &i);
4047 while ((child = next_device(&i)))
4048 if (match(child, data) && get_device(child))
4050 klist_iter_exit(&i);
4053 EXPORT_SYMBOL_GPL(device_find_child);
4056 * device_find_child_by_name - device iterator for locating a child device.
4057 * @parent: parent struct device
4058 * @name: name of the child device
4060 * This is similar to the device_find_child() function above, but it
4061 * returns a reference to a device that has the name @name.
4063 * NOTE: you will need to drop the reference with put_device() after use.
4065 struct device *device_find_child_by_name(struct device *parent,
4068 struct klist_iter i;
4069 struct device *child;
4074 klist_iter_init(&parent->p->klist_children, &i);
4075 while ((child = next_device(&i)))
4076 if (sysfs_streq(dev_name(child), name) && get_device(child))
4078 klist_iter_exit(&i);
4081 EXPORT_SYMBOL_GPL(device_find_child_by_name);
4083 static int match_any(struct device *dev, void *unused)
4089 * device_find_any_child - device iterator for locating a child device, if any.
4090 * @parent: parent struct device
4092 * This is similar to the device_find_child() function above, but it
4093 * returns a reference to a child device, if any.
4095 * NOTE: you will need to drop the reference with put_device() after use.
4097 struct device *device_find_any_child(struct device *parent)
4099 return device_find_child(parent, NULL, match_any);
4101 EXPORT_SYMBOL_GPL(device_find_any_child);
4103 int __init devices_init(void)
4105 devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
4108 dev_kobj = kobject_create_and_add("dev", NULL);
4111 sysfs_dev_block_kobj = kobject_create_and_add("block", dev_kobj);
4112 if (!sysfs_dev_block_kobj)
4113 goto block_kobj_err;
4114 sysfs_dev_char_kobj = kobject_create_and_add("char", dev_kobj);
4115 if (!sysfs_dev_char_kobj)
4121 kobject_put(sysfs_dev_block_kobj);
4123 kobject_put(dev_kobj);
4125 kset_unregister(devices_kset);
4129 static int device_check_offline(struct device *dev, void *not_used)
4133 ret = device_for_each_child(dev, NULL, device_check_offline);
4137 return device_supports_offline(dev) && !dev->offline ? -EBUSY : 0;
4141 * device_offline - Prepare the device for hot-removal.
4142 * @dev: Device to be put offline.
4144 * Execute the device bus type's .offline() callback, if present, to prepare
4145 * the device for a subsequent hot-removal. If that succeeds, the device must
4146 * not be used until either it is removed or its bus type's .online() callback
4149 * Call under device_hotplug_lock.
4151 int device_offline(struct device *dev)
4155 if (dev->offline_disabled)
4158 ret = device_for_each_child(dev, NULL, device_check_offline);
4163 if (device_supports_offline(dev)) {
4167 ret = dev->bus->offline(dev);
4169 kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
4170 dev->offline = true;
4180 * device_online - Put the device back online after successful device_offline().
4181 * @dev: Device to be put back online.
4183 * If device_offline() has been successfully executed for @dev, but the device
4184 * has not been removed subsequently, execute its bus type's .online() callback
4185 * to indicate that the device can be used again.
4187 * Call under device_hotplug_lock.
4189 int device_online(struct device *dev)
4194 if (device_supports_offline(dev)) {
4196 ret = dev->bus->online(dev);
4198 kobject_uevent(&dev->kobj, KOBJ_ONLINE);
4199 dev->offline = false;
4210 struct root_device {
4212 struct module *owner;
4215 static inline struct root_device *to_root_device(struct device *d)
4217 return container_of(d, struct root_device, dev);
4220 static void root_device_release(struct device *dev)
4222 kfree(to_root_device(dev));
4226 * __root_device_register - allocate and register a root device
4227 * @name: root device name
4228 * @owner: owner module of the root device, usually THIS_MODULE
4230 * This function allocates a root device and registers it
4231 * using device_register(). In order to free the returned
4232 * device, use root_device_unregister().
4234 * Root devices are dummy devices which allow other devices
4235 * to be grouped under /sys/devices. Use this function to
4236 * allocate a root device and then use it as the parent of
4237 * any device which should appear under /sys/devices/{name}
4239 * The /sys/devices/{name} directory will also contain a
4240 * 'module' symlink which points to the @owner directory
4243 * Returns &struct device pointer on success, or ERR_PTR() on error.
4245 * Note: You probably want to use root_device_register().
4247 struct device *__root_device_register(const char *name, struct module *owner)
4249 struct root_device *root;
4252 root = kzalloc(sizeof(struct root_device), GFP_KERNEL);
4254 return ERR_PTR(err);
4256 err = dev_set_name(&root->dev, "%s", name);
4259 return ERR_PTR(err);
4262 root->dev.release = root_device_release;
4264 err = device_register(&root->dev);
4266 put_device(&root->dev);
4267 return ERR_PTR(err);
4270 #ifdef CONFIG_MODULES /* gotta find a "cleaner" way to do this */
4272 struct module_kobject *mk = &owner->mkobj;
4274 err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module");
4276 device_unregister(&root->dev);
4277 return ERR_PTR(err);
4279 root->owner = owner;
4285 EXPORT_SYMBOL_GPL(__root_device_register);
4288 * root_device_unregister - unregister and free a root device
4289 * @dev: device going away
4291 * This function unregisters and cleans up a device that was created by
4292 * root_device_register().
4294 void root_device_unregister(struct device *dev)
4296 struct root_device *root = to_root_device(dev);
4299 sysfs_remove_link(&root->dev.kobj, "module");
4301 device_unregister(dev);
4303 EXPORT_SYMBOL_GPL(root_device_unregister);
4306 static void device_create_release(struct device *dev)
4308 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
4312 static __printf(6, 0) struct device *
4313 device_create_groups_vargs(struct class *class, struct device *parent,
4314 dev_t devt, void *drvdata,
4315 const struct attribute_group **groups,
4316 const char *fmt, va_list args)
4318 struct device *dev = NULL;
4319 int retval = -ENODEV;
4321 if (IS_ERR_OR_NULL(class))
4324 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
4330 device_initialize(dev);
4333 dev->parent = parent;
4334 dev->groups = groups;
4335 dev->release = device_create_release;
4336 dev_set_drvdata(dev, drvdata);
4338 retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
4342 retval = device_add(dev);
4350 return ERR_PTR(retval);
4354 * device_create - creates a device and registers it with sysfs
4355 * @class: pointer to the struct class that this device should be registered to
4356 * @parent: pointer to the parent struct device of this new device, if any
4357 * @devt: the dev_t for the char device to be added
4358 * @drvdata: the data to be added to the device for callbacks
4359 * @fmt: string for the device's name
4361 * This function can be used by char device classes. A struct device
4362 * will be created in sysfs, registered to the specified class.
4364 * A "dev" file will be created, showing the dev_t for the device, if
4365 * the dev_t is not 0,0.
4366 * If a pointer to a parent struct device is passed in, the newly created
4367 * struct device will be a child of that device in sysfs.
4368 * The pointer to the struct device will be returned from the call.
4369 * Any further sysfs files that might be required can be created using this
4372 * Returns &struct device pointer on success, or ERR_PTR() on error.
4374 * Note: the struct class passed to this function must have previously
4375 * been created with a call to class_create().
4377 struct device *device_create(struct class *class, struct device *parent,
4378 dev_t devt, void *drvdata, const char *fmt, ...)
4383 va_start(vargs, fmt);
4384 dev = device_create_groups_vargs(class, parent, devt, drvdata, NULL,
4389 EXPORT_SYMBOL_GPL(device_create);
4392 * device_create_with_groups - creates a device and registers it with sysfs
4393 * @class: pointer to the struct class that this device should be registered to
4394 * @parent: pointer to the parent struct device of this new device, if any
4395 * @devt: the dev_t for the char device to be added
4396 * @drvdata: the data to be added to the device for callbacks
4397 * @groups: NULL-terminated list of attribute groups to be created
4398 * @fmt: string for the device's name
4400 * This function can be used by char device classes. A struct device
4401 * will be created in sysfs, registered to the specified class.
4402 * Additional attributes specified in the groups parameter will also
4403 * be created automatically.
4405 * A "dev" file will be created, showing the dev_t for the device, if
4406 * the dev_t is not 0,0.
4407 * If a pointer to a parent struct device is passed in, the newly created
4408 * struct device will be a child of that device in sysfs.
4409 * The pointer to the struct device will be returned from the call.
4410 * Any further sysfs files that might be required can be created using this
4413 * Returns &struct device pointer on success, or ERR_PTR() on error.
4415 * Note: the struct class passed to this function must have previously
4416 * been created with a call to class_create().
4418 struct device *device_create_with_groups(struct class *class,
4419 struct device *parent, dev_t devt,
4421 const struct attribute_group **groups,
4422 const char *fmt, ...)
4427 va_start(vargs, fmt);
4428 dev = device_create_groups_vargs(class, parent, devt, drvdata, groups,
4433 EXPORT_SYMBOL_GPL(device_create_with_groups);
4436 * device_destroy - removes a device that was created with device_create()
4437 * @class: pointer to the struct class that this device was registered with
4438 * @devt: the dev_t of the device that was previously registered
4440 * This call unregisters and cleans up a device that was created with a
4441 * call to device_create().
4443 void device_destroy(struct class *class, dev_t devt)
4447 dev = class_find_device_by_devt(class, devt);
4450 device_unregister(dev);
4453 EXPORT_SYMBOL_GPL(device_destroy);
4456 * device_rename - renames a device
4457 * @dev: the pointer to the struct device to be renamed
4458 * @new_name: the new name of the device
4460 * It is the responsibility of the caller to provide mutual
4461 * exclusion between two different calls of device_rename
4462 * on the same device to ensure that new_name is valid and
4463 * won't conflict with other devices.
4465 * Note: Don't call this function. Currently, the networking layer calls this
4466 * function, but that will change. The following text from Kay Sievers offers
4469 * Renaming devices is racy at many levels, symlinks and other stuff are not
4470 * replaced atomically, and you get a "move" uevent, but it's not easy to
4471 * connect the event to the old and new device. Device nodes are not renamed at
4472 * all, there isn't even support for that in the kernel now.
4474 * In the meantime, during renaming, your target name might be taken by another
4475 * driver, creating conflicts. Or the old name is taken directly after you
4476 * renamed it -- then you get events for the same DEVPATH, before you even see
4477 * the "move" event. It's just a mess, and nothing new should ever rely on
4478 * kernel device renaming. Besides that, it's not even implemented now for
4479 * other things than (driver-core wise very simple) network devices.
4481 * We are currently about to change network renaming in udev to completely
4482 * disallow renaming of devices in the same namespace as the kernel uses,
4483 * because we can't solve the problems properly, that arise with swapping names
4484 * of multiple interfaces without races. Means, renaming of eth[0-9]* will only
4485 * be allowed to some other name than eth[0-9]*, for the aforementioned
4488 * Make up a "real" name in the driver before you register anything, or add
4489 * some other attributes for userspace to find the device, or use udev to add
4490 * symlinks -- but never rename kernel devices later, it's a complete mess. We
4491 * don't even want to get into that and try to implement the missing pieces in
4492 * the core. We really have other pieces to fix in the driver core mess. :)
4494 int device_rename(struct device *dev, const char *new_name)
4496 struct kobject *kobj = &dev->kobj;
4497 char *old_device_name = NULL;
4500 dev = get_device(dev);
4504 dev_dbg(dev, "renaming to %s\n", new_name);
4506 old_device_name = kstrdup(dev_name(dev), GFP_KERNEL);
4507 if (!old_device_name) {
4513 error = sysfs_rename_link_ns(&dev->class->p->subsys.kobj,
4514 kobj, old_device_name,
4515 new_name, kobject_namespace(kobj));
4520 error = kobject_rename(kobj, new_name);
4527 kfree(old_device_name);
4531 EXPORT_SYMBOL_GPL(device_rename);
4533 static int device_move_class_links(struct device *dev,
4534 struct device *old_parent,
4535 struct device *new_parent)
4540 sysfs_remove_link(&dev->kobj, "device");
4542 error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
4548 * device_move - moves a device to a new parent
4549 * @dev: the pointer to the struct device to be moved
4550 * @new_parent: the new parent of the device (can be NULL)
4551 * @dpm_order: how to reorder the dpm_list
4553 int device_move(struct device *dev, struct device *new_parent,
4554 enum dpm_order dpm_order)
4557 struct device *old_parent;
4558 struct kobject *new_parent_kobj;
4560 dev = get_device(dev);
4565 new_parent = get_device(new_parent);
4566 new_parent_kobj = get_device_parent(dev, new_parent);
4567 if (IS_ERR(new_parent_kobj)) {
4568 error = PTR_ERR(new_parent_kobj);
4569 put_device(new_parent);
4573 pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev),
4574 __func__, new_parent ? dev_name(new_parent) : "<NULL>");
4575 error = kobject_move(&dev->kobj, new_parent_kobj);
4577 cleanup_glue_dir(dev, new_parent_kobj);
4578 put_device(new_parent);
4581 old_parent = dev->parent;
4582 dev->parent = new_parent;
4584 klist_remove(&dev->p->knode_parent);
4586 klist_add_tail(&dev->p->knode_parent,
4587 &new_parent->p->klist_children);
4588 set_dev_node(dev, dev_to_node(new_parent));
4592 error = device_move_class_links(dev, old_parent, new_parent);
4594 /* We ignore errors on cleanup since we're hosed anyway... */
4595 device_move_class_links(dev, new_parent, old_parent);
4596 if (!kobject_move(&dev->kobj, &old_parent->kobj)) {
4598 klist_remove(&dev->p->knode_parent);
4599 dev->parent = old_parent;
4601 klist_add_tail(&dev->p->knode_parent,
4602 &old_parent->p->klist_children);
4603 set_dev_node(dev, dev_to_node(old_parent));
4606 cleanup_glue_dir(dev, new_parent_kobj);
4607 put_device(new_parent);
4611 switch (dpm_order) {
4612 case DPM_ORDER_NONE:
4614 case DPM_ORDER_DEV_AFTER_PARENT:
4615 device_pm_move_after(dev, new_parent);
4616 devices_kset_move_after(dev, new_parent);
4618 case DPM_ORDER_PARENT_BEFORE_DEV:
4619 device_pm_move_before(new_parent, dev);
4620 devices_kset_move_before(new_parent, dev);
4622 case DPM_ORDER_DEV_LAST:
4623 device_pm_move_last(dev);
4624 devices_kset_move_last(dev);
4628 put_device(old_parent);
4634 EXPORT_SYMBOL_GPL(device_move);
4636 static int device_attrs_change_owner(struct device *dev, kuid_t kuid,
4639 struct kobject *kobj = &dev->kobj;
4640 struct class *class = dev->class;
4641 const struct device_type *type = dev->type;
4646 * Change the device groups of the device class for @dev to
4649 error = sysfs_groups_change_owner(kobj, class->dev_groups, kuid,
4657 * Change the device groups of the device type for @dev to
4660 error = sysfs_groups_change_owner(kobj, type->groups, kuid,
4666 /* Change the device groups of @dev to @kuid/@kgid. */
4667 error = sysfs_groups_change_owner(kobj, dev->groups, kuid, kgid);
4671 if (device_supports_offline(dev) && !dev->offline_disabled) {
4672 /* Change online device attributes of @dev to @kuid/@kgid. */
4673 error = sysfs_file_change_owner(kobj, dev_attr_online.attr.name,
4683 * device_change_owner - change the owner of an existing device.
4685 * @kuid: new owner's kuid
4686 * @kgid: new owner's kgid
4688 * This changes the owner of @dev and its corresponding sysfs entries to
4689 * @kuid/@kgid. This function closely mirrors how @dev was added via driver
4692 * Returns 0 on success or error code on failure.
4694 int device_change_owner(struct device *dev, kuid_t kuid, kgid_t kgid)
4697 struct kobject *kobj = &dev->kobj;
4699 dev = get_device(dev);
4704 * Change the kobject and the default attributes and groups of the
4705 * ktype associated with it to @kuid/@kgid.
4707 error = sysfs_change_owner(kobj, kuid, kgid);
4712 * Change the uevent file for @dev to the new owner. The uevent file
4713 * was created in a separate step when @dev got added and we mirror
4716 error = sysfs_file_change_owner(kobj, dev_attr_uevent.attr.name, kuid,
4722 * Change the device groups, the device groups associated with the
4723 * device class, and the groups associated with the device type of @dev
4726 error = device_attrs_change_owner(dev, kuid, kgid);
4730 error = dpm_sysfs_change_owner(dev, kuid, kgid);
4735 if (sysfs_deprecated && dev->class == &block_class)
4740 * Change the owner of the symlink located in the class directory of
4741 * the device class associated with @dev which points to the actual
4742 * directory entry for @dev to @kuid/@kgid. This ensures that the
4743 * symlink shows the same permissions as its target.
4745 error = sysfs_link_change_owner(&dev->class->p->subsys.kobj, &dev->kobj,
4746 dev_name(dev), kuid, kgid);
4754 EXPORT_SYMBOL_GPL(device_change_owner);
4757 * device_shutdown - call ->shutdown() on each device to shutdown.
4759 void device_shutdown(void)
4761 struct device *dev, *parent;
4763 wait_for_device_probe();
4764 device_block_probing();
4768 spin_lock(&devices_kset->list_lock);
4770 * Walk the devices list backward, shutting down each in turn.
4771 * Beware that device unplug events may also start pulling
4772 * devices offline, even as the system is shutting down.
4774 while (!list_empty(&devices_kset->list)) {
4775 dev = list_entry(devices_kset->list.prev, struct device,
4779 * hold reference count of device's parent to
4780 * prevent it from being freed because parent's
4781 * lock is to be held
4783 parent = get_device(dev->parent);
4786 * Make sure the device is off the kset list, in the
4787 * event that dev->*->shutdown() doesn't remove it.
4789 list_del_init(&dev->kobj.entry);
4790 spin_unlock(&devices_kset->list_lock);
4792 /* hold lock to avoid race with probe/release */
4794 device_lock(parent);
4797 /* Don't allow any more runtime suspends */
4798 pm_runtime_get_noresume(dev);
4799 pm_runtime_barrier(dev);
4801 if (dev->class && dev->class->shutdown_pre) {
4803 dev_info(dev, "shutdown_pre\n");
4804 dev->class->shutdown_pre(dev);
4806 if (dev->bus && dev->bus->shutdown) {
4808 dev_info(dev, "shutdown\n");
4809 dev->bus->shutdown(dev);
4810 } else if (dev->driver && dev->driver->shutdown) {
4812 dev_info(dev, "shutdown\n");
4813 dev->driver->shutdown(dev);
4818 device_unlock(parent);
4823 spin_lock(&devices_kset->list_lock);
4825 spin_unlock(&devices_kset->list_lock);
4829 * Device logging functions
4832 #ifdef CONFIG_PRINTK
4834 set_dev_info(const struct device *dev, struct dev_printk_info *dev_info)
4838 memset(dev_info, 0, sizeof(*dev_info));
4841 subsys = dev->class->name;
4843 subsys = dev->bus->name;
4847 strscpy(dev_info->subsystem, subsys, sizeof(dev_info->subsystem));
4850 * Add device identifier DEVICE=:
4854 * +sound:card0 subsystem:devname
4856 if (MAJOR(dev->devt)) {
4859 if (strcmp(subsys, "block") == 0)
4864 snprintf(dev_info->device, sizeof(dev_info->device),
4865 "%c%u:%u", c, MAJOR(dev->devt), MINOR(dev->devt));
4866 } else if (strcmp(subsys, "net") == 0) {
4867 struct net_device *net = to_net_dev(dev);
4869 snprintf(dev_info->device, sizeof(dev_info->device),
4870 "n%u", net->ifindex);
4872 snprintf(dev_info->device, sizeof(dev_info->device),
4873 "+%s:%s", subsys, dev_name(dev));
4877 int dev_vprintk_emit(int level, const struct device *dev,
4878 const char *fmt, va_list args)
4880 struct dev_printk_info dev_info;
4882 set_dev_info(dev, &dev_info);
4884 return vprintk_emit(0, level, &dev_info, fmt, args);
4886 EXPORT_SYMBOL(dev_vprintk_emit);
4888 int dev_printk_emit(int level, const struct device *dev, const char *fmt, ...)
4893 va_start(args, fmt);
4895 r = dev_vprintk_emit(level, dev, fmt, args);
4901 EXPORT_SYMBOL(dev_printk_emit);
4903 static void __dev_printk(const char *level, const struct device *dev,
4904 struct va_format *vaf)
4907 dev_printk_emit(level[1] - '0', dev, "%s %s: %pV",
4908 dev_driver_string(dev), dev_name(dev), vaf);
4910 printk("%s(NULL device *): %pV", level, vaf);
4913 void _dev_printk(const char *level, const struct device *dev,
4914 const char *fmt, ...)
4916 struct va_format vaf;
4919 va_start(args, fmt);
4924 __dev_printk(level, dev, &vaf);
4928 EXPORT_SYMBOL(_dev_printk);
4930 #define define_dev_printk_level(func, kern_level) \
4931 void func(const struct device *dev, const char *fmt, ...) \
4933 struct va_format vaf; \
4936 va_start(args, fmt); \
4941 __dev_printk(kern_level, dev, &vaf); \
4945 EXPORT_SYMBOL(func);
4947 define_dev_printk_level(_dev_emerg, KERN_EMERG);
4948 define_dev_printk_level(_dev_alert, KERN_ALERT);
4949 define_dev_printk_level(_dev_crit, KERN_CRIT);
4950 define_dev_printk_level(_dev_err, KERN_ERR);
4951 define_dev_printk_level(_dev_warn, KERN_WARNING);
4952 define_dev_printk_level(_dev_notice, KERN_NOTICE);
4953 define_dev_printk_level(_dev_info, KERN_INFO);
4958 * dev_err_probe - probe error check and log helper
4959 * @dev: the pointer to the struct device
4960 * @err: error value to test
4961 * @fmt: printf-style format string
4962 * @...: arguments as specified in the format string
4964 * This helper implements common pattern present in probe functions for error
4965 * checking: print debug or error message depending if the error value is
4966 * -EPROBE_DEFER and propagate error upwards.
4967 * In case of -EPROBE_DEFER it sets also defer probe reason, which can be
4968 * checked later by reading devices_deferred debugfs attribute.
4969 * It replaces code sequence::
4971 * if (err != -EPROBE_DEFER)
4972 * dev_err(dev, ...);
4974 * dev_dbg(dev, ...);
4979 * return dev_err_probe(dev, err, ...);
4981 * Note that it is deemed acceptable to use this function for error
4982 * prints during probe even if the @err is known to never be -EPROBE_DEFER.
4983 * The benefit compared to a normal dev_err() is the standardized format
4984 * of the error code and the fact that the error code is returned.
4989 int dev_err_probe(const struct device *dev, int err, const char *fmt, ...)
4991 struct va_format vaf;
4994 va_start(args, fmt);
4998 if (err != -EPROBE_DEFER) {
4999 dev_err(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
5001 device_set_deferred_probe_reason(dev, &vaf);
5002 dev_dbg(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
5009 EXPORT_SYMBOL_GPL(dev_err_probe);
5011 static inline bool fwnode_is_primary(struct fwnode_handle *fwnode)
5013 return fwnode && !IS_ERR(fwnode->secondary);
5017 * set_primary_fwnode - Change the primary firmware node of a given device.
5018 * @dev: Device to handle.
5019 * @fwnode: New primary firmware node of the device.
5021 * Set the device's firmware node pointer to @fwnode, but if a secondary
5022 * firmware node of the device is present, preserve it.
5024 * Valid fwnode cases are:
5025 * - primary --> secondary --> -ENODEV
5026 * - primary --> NULL
5027 * - secondary --> -ENODEV
5030 void set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
5032 struct device *parent = dev->parent;
5033 struct fwnode_handle *fn = dev->fwnode;
5036 if (fwnode_is_primary(fn))
5040 WARN_ON(fwnode->secondary);
5041 fwnode->secondary = fn;
5043 dev->fwnode = fwnode;
5045 if (fwnode_is_primary(fn)) {
5046 dev->fwnode = fn->secondary;
5047 /* Set fn->secondary = NULL, so fn remains the primary fwnode */
5048 if (!(parent && fn == parent->fwnode))
5049 fn->secondary = NULL;
5055 EXPORT_SYMBOL_GPL(set_primary_fwnode);
5058 * set_secondary_fwnode - Change the secondary firmware node of a given device.
5059 * @dev: Device to handle.
5060 * @fwnode: New secondary firmware node of the device.
5062 * If a primary firmware node of the device is present, set its secondary
5063 * pointer to @fwnode. Otherwise, set the device's firmware node pointer to
5066 void set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
5069 fwnode->secondary = ERR_PTR(-ENODEV);
5071 if (fwnode_is_primary(dev->fwnode))
5072 dev->fwnode->secondary = fwnode;
5074 dev->fwnode = fwnode;
5076 EXPORT_SYMBOL_GPL(set_secondary_fwnode);
5079 * device_set_of_node_from_dev - reuse device-tree node of another device
5080 * @dev: device whose device-tree node is being set
5081 * @dev2: device whose device-tree node is being reused
5083 * Takes another reference to the new device-tree node after first dropping
5084 * any reference held to the old node.
5086 void device_set_of_node_from_dev(struct device *dev, const struct device *dev2)
5088 of_node_put(dev->of_node);
5089 dev->of_node = of_node_get(dev2->of_node);
5090 dev->of_node_reused = true;
5092 EXPORT_SYMBOL_GPL(device_set_of_node_from_dev);
5094 void device_set_node(struct device *dev, struct fwnode_handle *fwnode)
5096 dev->fwnode = fwnode;
5097 dev->of_node = to_of_node(fwnode);
5099 EXPORT_SYMBOL_GPL(device_set_node);
5101 int device_match_name(struct device *dev, const void *name)
5103 return sysfs_streq(dev_name(dev), name);
5105 EXPORT_SYMBOL_GPL(device_match_name);
5107 int device_match_of_node(struct device *dev, const void *np)
5109 return dev->of_node == np;
5111 EXPORT_SYMBOL_GPL(device_match_of_node);
5113 int device_match_fwnode(struct device *dev, const void *fwnode)
5115 return dev_fwnode(dev) == fwnode;
5117 EXPORT_SYMBOL_GPL(device_match_fwnode);
5119 int device_match_devt(struct device *dev, const void *pdevt)
5121 return dev->devt == *(dev_t *)pdevt;
5123 EXPORT_SYMBOL_GPL(device_match_devt);
5125 int device_match_acpi_dev(struct device *dev, const void *adev)
5127 return ACPI_COMPANION(dev) == adev;
5129 EXPORT_SYMBOL(device_match_acpi_dev);
5131 int device_match_acpi_handle(struct device *dev, const void *handle)
5133 return ACPI_HANDLE(dev) == handle;
5135 EXPORT_SYMBOL(device_match_acpi_handle);
5137 int device_match_any(struct device *dev, const void *unused)
5141 EXPORT_SYMBOL_GPL(device_match_any);