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
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/kstrtox.h>
18 #include <linux/module.h>
19 #include <linux/slab.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/rcupdate.h>
29 #include <linux/sched/signal.h>
30 #include <linux/sched/mm.h>
31 #include <linux/string_helpers.h>
32 #include <linux/swiotlb.h>
33 #include <linux/sysfs.h>
34 #include <linux/dma-map-ops.h> /* for dma_default_coherent */
37 #include "physical_location.h"
38 #include "power/power.h"
40 /* Device links support. */
41 static LIST_HEAD(deferred_sync);
42 static unsigned int defer_sync_state_count = 1;
43 static DEFINE_MUTEX(fwnode_link_lock);
44 static bool fw_devlink_is_permissive(void);
45 static void __fw_devlink_link_to_consumers(struct device *dev);
46 static bool fw_devlink_drv_reg_done;
47 static bool fw_devlink_best_effort;
48 static struct workqueue_struct *device_link_wq;
51 * __fwnode_link_add - Create a link between two fwnode_handles.
52 * @con: Consumer end of the link.
53 * @sup: Supplier end of the link.
56 * Create a fwnode link between fwnode handles @con and @sup. The fwnode link
57 * represents the detail that the firmware lists @sup fwnode as supplying a
60 * The driver core will use the fwnode link to create a device link between the
61 * two device objects corresponding to @con and @sup when they are created. The
62 * driver core will automatically delete the fwnode link between @con and @sup
65 * Attempts to create duplicate links between the same pair of fwnode handles
66 * are ignored and there is no reference counting.
68 static int __fwnode_link_add(struct fwnode_handle *con,
69 struct fwnode_handle *sup, u8 flags)
71 struct fwnode_link *link;
73 list_for_each_entry(link, &sup->consumers, s_hook)
74 if (link->consumer == con) {
79 link = kzalloc(sizeof(*link), GFP_KERNEL);
84 INIT_LIST_HEAD(&link->s_hook);
86 INIT_LIST_HEAD(&link->c_hook);
89 list_add(&link->s_hook, &sup->consumers);
90 list_add(&link->c_hook, &con->suppliers);
91 pr_debug("%pfwf Linked as a fwnode consumer to %pfwf\n",
97 int fwnode_link_add(struct fwnode_handle *con, struct fwnode_handle *sup,
102 mutex_lock(&fwnode_link_lock);
103 ret = __fwnode_link_add(con, sup, flags);
104 mutex_unlock(&fwnode_link_lock);
109 * __fwnode_link_del - Delete a link between two fwnode_handles.
110 * @link: the fwnode_link to be deleted
112 * The fwnode_link_lock needs to be held when this function is called.
114 static void __fwnode_link_del(struct fwnode_link *link)
116 pr_debug("%pfwf Dropping the fwnode link to %pfwf\n",
117 link->consumer, link->supplier);
118 list_del(&link->s_hook);
119 list_del(&link->c_hook);
124 * __fwnode_link_cycle - Mark a fwnode link as being part of a cycle.
125 * @link: the fwnode_link to be marked
127 * The fwnode_link_lock needs to be held when this function is called.
129 static void __fwnode_link_cycle(struct fwnode_link *link)
131 pr_debug("%pfwf: cycle: depends on %pfwf\n",
132 link->consumer, link->supplier);
133 link->flags |= FWLINK_FLAG_CYCLE;
137 * fwnode_links_purge_suppliers - Delete all supplier links of fwnode_handle.
138 * @fwnode: fwnode whose supplier links need to be deleted
140 * Deletes all supplier links connecting directly to @fwnode.
142 static void fwnode_links_purge_suppliers(struct fwnode_handle *fwnode)
144 struct fwnode_link *link, *tmp;
146 mutex_lock(&fwnode_link_lock);
147 list_for_each_entry_safe(link, tmp, &fwnode->suppliers, c_hook)
148 __fwnode_link_del(link);
149 mutex_unlock(&fwnode_link_lock);
153 * fwnode_links_purge_consumers - Delete all consumer links of fwnode_handle.
154 * @fwnode: fwnode whose consumer links need to be deleted
156 * Deletes all consumer links connecting directly to @fwnode.
158 static void fwnode_links_purge_consumers(struct fwnode_handle *fwnode)
160 struct fwnode_link *link, *tmp;
162 mutex_lock(&fwnode_link_lock);
163 list_for_each_entry_safe(link, tmp, &fwnode->consumers, s_hook)
164 __fwnode_link_del(link);
165 mutex_unlock(&fwnode_link_lock);
169 * fwnode_links_purge - Delete all links connected to a fwnode_handle.
170 * @fwnode: fwnode whose links needs to be deleted
172 * Deletes all links connecting directly to a fwnode.
174 void fwnode_links_purge(struct fwnode_handle *fwnode)
176 fwnode_links_purge_suppliers(fwnode);
177 fwnode_links_purge_consumers(fwnode);
180 void fw_devlink_purge_absent_suppliers(struct fwnode_handle *fwnode)
182 struct fwnode_handle *child;
184 /* Don't purge consumer links of an added child */
188 fwnode->flags |= FWNODE_FLAG_NOT_DEVICE;
189 fwnode_links_purge_consumers(fwnode);
191 fwnode_for_each_available_child_node(fwnode, child)
192 fw_devlink_purge_absent_suppliers(child);
194 EXPORT_SYMBOL_GPL(fw_devlink_purge_absent_suppliers);
197 * __fwnode_links_move_consumers - Move consumer from @from to @to fwnode_handle
198 * @from: move consumers away from this fwnode
199 * @to: move consumers to this fwnode
201 * Move all consumer links from @from fwnode to @to fwnode.
203 static void __fwnode_links_move_consumers(struct fwnode_handle *from,
204 struct fwnode_handle *to)
206 struct fwnode_link *link, *tmp;
208 list_for_each_entry_safe(link, tmp, &from->consumers, s_hook) {
209 __fwnode_link_add(link->consumer, to, link->flags);
210 __fwnode_link_del(link);
215 * __fw_devlink_pickup_dangling_consumers - Pick up dangling consumers
216 * @fwnode: fwnode from which to pick up dangling consumers
217 * @new_sup: fwnode of new supplier
219 * If the @fwnode has a corresponding struct device and the device supports
220 * probing (that is, added to a bus), then we want to let fw_devlink create
221 * MANAGED device links to this device, so leave @fwnode and its descendant's
222 * fwnode links alone.
224 * Otherwise, move its consumers to the new supplier @new_sup.
226 static void __fw_devlink_pickup_dangling_consumers(struct fwnode_handle *fwnode,
227 struct fwnode_handle *new_sup)
229 struct fwnode_handle *child;
231 if (fwnode->dev && fwnode->dev->bus)
234 fwnode->flags |= FWNODE_FLAG_NOT_DEVICE;
235 __fwnode_links_move_consumers(fwnode, new_sup);
237 fwnode_for_each_available_child_node(fwnode, child)
238 __fw_devlink_pickup_dangling_consumers(child, new_sup);
241 static DEFINE_MUTEX(device_links_lock);
242 DEFINE_STATIC_SRCU(device_links_srcu);
244 static inline void device_links_write_lock(void)
246 mutex_lock(&device_links_lock);
249 static inline void device_links_write_unlock(void)
251 mutex_unlock(&device_links_lock);
254 int device_links_read_lock(void) __acquires(&device_links_srcu)
256 return srcu_read_lock(&device_links_srcu);
259 void device_links_read_unlock(int idx) __releases(&device_links_srcu)
261 srcu_read_unlock(&device_links_srcu, idx);
264 int device_links_read_lock_held(void)
266 return srcu_read_lock_held(&device_links_srcu);
269 static void device_link_synchronize_removal(void)
271 synchronize_srcu(&device_links_srcu);
274 static void device_link_remove_from_lists(struct device_link *link)
276 list_del_rcu(&link->s_node);
277 list_del_rcu(&link->c_node);
280 static bool device_is_ancestor(struct device *dev, struct device *target)
282 while (target->parent) {
283 target = target->parent;
290 #define DL_MARKER_FLAGS (DL_FLAG_INFERRED | \
293 static inline bool device_link_flag_is_sync_state_only(u32 flags)
295 return (flags & ~DL_MARKER_FLAGS) == DL_FLAG_SYNC_STATE_ONLY;
299 * device_is_dependent - Check if one device depends on another one
300 * @dev: Device to check dependencies for.
301 * @target: Device to check against.
303 * Check if @target depends on @dev or any device dependent on it (its child or
304 * its consumer etc). Return 1 if that is the case or 0 otherwise.
306 static int device_is_dependent(struct device *dev, void *target)
308 struct device_link *link;
312 * The "ancestors" check is needed to catch the case when the target
313 * device has not been completely initialized yet and it is still
314 * missing from the list of children of its parent device.
316 if (dev == target || device_is_ancestor(dev, target))
319 ret = device_for_each_child(dev, target, device_is_dependent);
323 list_for_each_entry(link, &dev->links.consumers, s_node) {
324 if (device_link_flag_is_sync_state_only(link->flags))
327 if (link->consumer == target)
330 ret = device_is_dependent(link->consumer, target);
337 static void device_link_init_status(struct device_link *link,
338 struct device *consumer,
339 struct device *supplier)
341 switch (supplier->links.status) {
343 switch (consumer->links.status) {
346 * A consumer driver can create a link to a supplier
347 * that has not completed its probing yet as long as it
348 * knows that the supplier is already functional (for
349 * example, it has just acquired some resources from the
352 link->status = DL_STATE_CONSUMER_PROBE;
355 link->status = DL_STATE_DORMANT;
359 case DL_DEV_DRIVER_BOUND:
360 switch (consumer->links.status) {
362 link->status = DL_STATE_CONSUMER_PROBE;
364 case DL_DEV_DRIVER_BOUND:
365 link->status = DL_STATE_ACTIVE;
368 link->status = DL_STATE_AVAILABLE;
372 case DL_DEV_UNBINDING:
373 link->status = DL_STATE_SUPPLIER_UNBIND;
376 link->status = DL_STATE_DORMANT;
381 static int device_reorder_to_tail(struct device *dev, void *not_used)
383 struct device_link *link;
386 * Devices that have not been registered yet will be put to the ends
387 * of the lists during the registration, so skip them here.
389 if (device_is_registered(dev))
390 devices_kset_move_last(dev);
392 if (device_pm_initialized(dev))
393 device_pm_move_last(dev);
395 device_for_each_child(dev, NULL, device_reorder_to_tail);
396 list_for_each_entry(link, &dev->links.consumers, s_node) {
397 if (device_link_flag_is_sync_state_only(link->flags))
399 device_reorder_to_tail(link->consumer, NULL);
406 * device_pm_move_to_tail - Move set of devices to the end of device lists
407 * @dev: Device to move
409 * This is a device_reorder_to_tail() wrapper taking the requisite locks.
411 * It moves the @dev along with all of its children and all of its consumers
412 * to the ends of the device_kset and dpm_list, recursively.
414 void device_pm_move_to_tail(struct device *dev)
418 idx = device_links_read_lock();
420 device_reorder_to_tail(dev, NULL);
422 device_links_read_unlock(idx);
425 #define to_devlink(dev) container_of((dev), struct device_link, link_dev)
427 static ssize_t status_show(struct device *dev,
428 struct device_attribute *attr, char *buf)
432 switch (to_devlink(dev)->status) {
434 output = "not tracked";
436 case DL_STATE_DORMANT:
439 case DL_STATE_AVAILABLE:
440 output = "available";
442 case DL_STATE_CONSUMER_PROBE:
443 output = "consumer probing";
445 case DL_STATE_ACTIVE:
448 case DL_STATE_SUPPLIER_UNBIND:
449 output = "supplier unbinding";
456 return sysfs_emit(buf, "%s\n", output);
458 static DEVICE_ATTR_RO(status);
460 static ssize_t auto_remove_on_show(struct device *dev,
461 struct device_attribute *attr, char *buf)
463 struct device_link *link = to_devlink(dev);
466 if (link->flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
467 output = "supplier unbind";
468 else if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER)
469 output = "consumer unbind";
473 return sysfs_emit(buf, "%s\n", output);
475 static DEVICE_ATTR_RO(auto_remove_on);
477 static ssize_t runtime_pm_show(struct device *dev,
478 struct device_attribute *attr, char *buf)
480 struct device_link *link = to_devlink(dev);
482 return sysfs_emit(buf, "%d\n", !!(link->flags & DL_FLAG_PM_RUNTIME));
484 static DEVICE_ATTR_RO(runtime_pm);
486 static ssize_t sync_state_only_show(struct device *dev,
487 struct device_attribute *attr, char *buf)
489 struct device_link *link = to_devlink(dev);
491 return sysfs_emit(buf, "%d\n",
492 !!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
494 static DEVICE_ATTR_RO(sync_state_only);
496 static struct attribute *devlink_attrs[] = {
497 &dev_attr_status.attr,
498 &dev_attr_auto_remove_on.attr,
499 &dev_attr_runtime_pm.attr,
500 &dev_attr_sync_state_only.attr,
503 ATTRIBUTE_GROUPS(devlink);
505 static void device_link_release_fn(struct work_struct *work)
507 struct device_link *link = container_of(work, struct device_link, rm_work);
509 /* Ensure that all references to the link object have been dropped. */
510 device_link_synchronize_removal();
512 pm_runtime_release_supplier(link);
514 * If supplier_preactivated is set, the link has been dropped between
515 * the pm_runtime_get_suppliers() and pm_runtime_put_suppliers() calls
516 * in __driver_probe_device(). In that case, drop the supplier's
517 * PM-runtime usage counter to remove the reference taken by
518 * pm_runtime_get_suppliers().
520 if (link->supplier_preactivated)
521 pm_runtime_put_noidle(link->supplier);
523 pm_request_idle(link->supplier);
525 put_device(link->consumer);
526 put_device(link->supplier);
530 static void devlink_dev_release(struct device *dev)
532 struct device_link *link = to_devlink(dev);
534 INIT_WORK(&link->rm_work, device_link_release_fn);
536 * It may take a while to complete this work because of the SRCU
537 * synchronization in device_link_release_fn() and if the consumer or
538 * supplier devices get deleted when it runs, so put it into the
539 * dedicated workqueue.
541 queue_work(device_link_wq, &link->rm_work);
545 * device_link_wait_removal - Wait for ongoing devlink removal jobs to terminate
547 void device_link_wait_removal(void)
550 * devlink removal jobs are queued in the dedicated work queue.
551 * To be sure that all removal jobs are terminated, ensure that any
552 * scheduled work has run to completion.
554 flush_workqueue(device_link_wq);
556 EXPORT_SYMBOL_GPL(device_link_wait_removal);
558 static struct class devlink_class = {
560 .dev_groups = devlink_groups,
561 .dev_release = devlink_dev_release,
564 static int devlink_add_symlinks(struct device *dev)
568 struct device_link *link = to_devlink(dev);
569 struct device *sup = link->supplier;
570 struct device *con = link->consumer;
573 len = max(strlen(dev_bus_name(sup)) + strlen(dev_name(sup)),
574 strlen(dev_bus_name(con)) + strlen(dev_name(con)));
576 len += strlen("supplier:") + 1;
577 buf = kzalloc(len, GFP_KERNEL);
581 ret = sysfs_create_link(&link->link_dev.kobj, &sup->kobj, "supplier");
585 ret = sysfs_create_link(&link->link_dev.kobj, &con->kobj, "consumer");
589 snprintf(buf, len, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
590 ret = sysfs_create_link(&sup->kobj, &link->link_dev.kobj, buf);
594 snprintf(buf, len, "supplier:%s:%s", dev_bus_name(sup), dev_name(sup));
595 ret = sysfs_create_link(&con->kobj, &link->link_dev.kobj, buf);
602 snprintf(buf, len, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
603 sysfs_remove_link(&sup->kobj, buf);
605 sysfs_remove_link(&link->link_dev.kobj, "consumer");
607 sysfs_remove_link(&link->link_dev.kobj, "supplier");
613 static void devlink_remove_symlinks(struct device *dev)
615 struct device_link *link = to_devlink(dev);
617 struct device *sup = link->supplier;
618 struct device *con = link->consumer;
621 sysfs_remove_link(&link->link_dev.kobj, "consumer");
622 sysfs_remove_link(&link->link_dev.kobj, "supplier");
624 len = max(strlen(dev_bus_name(sup)) + strlen(dev_name(sup)),
625 strlen(dev_bus_name(con)) + strlen(dev_name(con)));
627 len += strlen("supplier:") + 1;
628 buf = kzalloc(len, GFP_KERNEL);
630 WARN(1, "Unable to properly free device link symlinks!\n");
634 if (device_is_registered(con)) {
635 snprintf(buf, len, "supplier:%s:%s", dev_bus_name(sup), dev_name(sup));
636 sysfs_remove_link(&con->kobj, buf);
638 snprintf(buf, len, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
639 sysfs_remove_link(&sup->kobj, buf);
643 static struct class_interface devlink_class_intf = {
644 .class = &devlink_class,
645 .add_dev = devlink_add_symlinks,
646 .remove_dev = devlink_remove_symlinks,
649 static int __init devlink_class_init(void)
653 ret = class_register(&devlink_class);
657 ret = class_interface_register(&devlink_class_intf);
659 class_unregister(&devlink_class);
663 postcore_initcall(devlink_class_init);
665 #define DL_MANAGED_LINK_FLAGS (DL_FLAG_AUTOREMOVE_CONSUMER | \
666 DL_FLAG_AUTOREMOVE_SUPPLIER | \
667 DL_FLAG_AUTOPROBE_CONSUMER | \
668 DL_FLAG_SYNC_STATE_ONLY | \
672 #define DL_ADD_VALID_FLAGS (DL_MANAGED_LINK_FLAGS | DL_FLAG_STATELESS | \
673 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE)
676 * device_link_add - Create a link between two devices.
677 * @consumer: Consumer end of the link.
678 * @supplier: Supplier end of the link.
679 * @flags: Link flags.
681 * The caller is responsible for the proper synchronization of the link creation
682 * with runtime PM. First, setting the DL_FLAG_PM_RUNTIME flag will cause the
683 * runtime PM framework to take the link into account. Second, if the
684 * DL_FLAG_RPM_ACTIVE flag is set in addition to it, the supplier devices will
685 * be forced into the active meta state and reference-counted upon the creation
686 * of the link. If DL_FLAG_PM_RUNTIME is not set, DL_FLAG_RPM_ACTIVE will be
689 * If DL_FLAG_STATELESS is set in @flags, the caller of this function is
690 * expected to release the link returned by it directly with the help of either
691 * device_link_del() or device_link_remove().
693 * If that flag is not set, however, the caller of this function is handing the
694 * management of the link over to the driver core entirely and its return value
695 * can only be used to check whether or not the link is present. In that case,
696 * the DL_FLAG_AUTOREMOVE_CONSUMER and DL_FLAG_AUTOREMOVE_SUPPLIER device link
697 * flags can be used to indicate to the driver core when the link can be safely
698 * deleted. Namely, setting one of them in @flags indicates to the driver core
699 * that the link is not going to be used (by the given caller of this function)
700 * after unbinding the consumer or supplier driver, respectively, from its
701 * device, so the link can be deleted at that point. If none of them is set,
702 * the link will be maintained until one of the devices pointed to by it (either
703 * the consumer or the supplier) is unregistered.
705 * Also, if DL_FLAG_STATELESS, DL_FLAG_AUTOREMOVE_CONSUMER and
706 * DL_FLAG_AUTOREMOVE_SUPPLIER are not set in @flags (that is, a persistent
707 * managed device link is being added), the DL_FLAG_AUTOPROBE_CONSUMER flag can
708 * be used to request the driver core to automatically probe for a consumer
709 * driver after successfully binding a driver to the supplier device.
711 * The combination of DL_FLAG_STATELESS and one of DL_FLAG_AUTOREMOVE_CONSUMER,
712 * DL_FLAG_AUTOREMOVE_SUPPLIER, or DL_FLAG_AUTOPROBE_CONSUMER set in @flags at
713 * the same time is invalid and will cause NULL to be returned upfront.
714 * However, if a device link between the given @consumer and @supplier pair
715 * exists already when this function is called for them, the existing link will
716 * be returned regardless of its current type and status (the link's flags may
717 * be modified then). The caller of this function is then expected to treat
718 * the link as though it has just been created, so (in particular) if
719 * DL_FLAG_STATELESS was passed in @flags, the link needs to be released
720 * explicitly when not needed any more (as stated above).
722 * A side effect of the link creation is re-ordering of dpm_list and the
723 * devices_kset list by moving the consumer device and all devices depending
724 * on it to the ends of these lists (that does not happen to devices that have
725 * not been registered when this function is called).
727 * The supplier device is required to be registered when this function is called
728 * and NULL will be returned if that is not the case. The consumer device need
729 * not be registered, however.
731 struct device_link *device_link_add(struct device *consumer,
732 struct device *supplier, u32 flags)
734 struct device_link *link;
736 if (!consumer || !supplier || consumer == supplier ||
737 flags & ~DL_ADD_VALID_FLAGS ||
738 (flags & DL_FLAG_STATELESS && flags & DL_MANAGED_LINK_FLAGS) ||
739 (flags & DL_FLAG_AUTOPROBE_CONSUMER &&
740 flags & (DL_FLAG_AUTOREMOVE_CONSUMER |
741 DL_FLAG_AUTOREMOVE_SUPPLIER)))
744 if (flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) {
745 if (pm_runtime_get_sync(supplier) < 0) {
746 pm_runtime_put_noidle(supplier);
751 if (!(flags & DL_FLAG_STATELESS))
752 flags |= DL_FLAG_MANAGED;
754 if (flags & DL_FLAG_SYNC_STATE_ONLY &&
755 !device_link_flag_is_sync_state_only(flags))
758 device_links_write_lock();
762 * If the supplier has not been fully registered yet or there is a
763 * reverse (non-SYNC_STATE_ONLY) dependency between the consumer and
764 * the supplier already in the graph, return NULL. If the link is a
765 * SYNC_STATE_ONLY link, we don't check for reverse dependencies
766 * because it only affects sync_state() callbacks.
768 if (!device_pm_initialized(supplier)
769 || (!(flags & DL_FLAG_SYNC_STATE_ONLY) &&
770 device_is_dependent(consumer, supplier))) {
776 * SYNC_STATE_ONLY links are useless once a consumer device has probed.
777 * So, only create it if the consumer hasn't probed yet.
779 if (flags & DL_FLAG_SYNC_STATE_ONLY &&
780 consumer->links.status != DL_DEV_NO_DRIVER &&
781 consumer->links.status != DL_DEV_PROBING) {
787 * DL_FLAG_AUTOREMOVE_SUPPLIER indicates that the link will be needed
788 * longer than for DL_FLAG_AUTOREMOVE_CONSUMER and setting them both
789 * together doesn't make sense, so prefer DL_FLAG_AUTOREMOVE_SUPPLIER.
791 if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
792 flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
794 list_for_each_entry(link, &supplier->links.consumers, s_node) {
795 if (link->consumer != consumer)
798 if (link->flags & DL_FLAG_INFERRED &&
799 !(flags & DL_FLAG_INFERRED))
800 link->flags &= ~DL_FLAG_INFERRED;
802 if (flags & DL_FLAG_PM_RUNTIME) {
803 if (!(link->flags & DL_FLAG_PM_RUNTIME)) {
804 pm_runtime_new_link(consumer);
805 link->flags |= DL_FLAG_PM_RUNTIME;
807 if (flags & DL_FLAG_RPM_ACTIVE)
808 refcount_inc(&link->rpm_active);
811 if (flags & DL_FLAG_STATELESS) {
812 kref_get(&link->kref);
813 if (link->flags & DL_FLAG_SYNC_STATE_ONLY &&
814 !(link->flags & DL_FLAG_STATELESS)) {
815 link->flags |= DL_FLAG_STATELESS;
818 link->flags |= DL_FLAG_STATELESS;
824 * If the life time of the link following from the new flags is
825 * longer than indicated by the flags of the existing link,
826 * update the existing link to stay around longer.
828 if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER) {
829 if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER) {
830 link->flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
831 link->flags |= DL_FLAG_AUTOREMOVE_SUPPLIER;
833 } else if (!(flags & DL_FLAG_AUTOREMOVE_CONSUMER)) {
834 link->flags &= ~(DL_FLAG_AUTOREMOVE_CONSUMER |
835 DL_FLAG_AUTOREMOVE_SUPPLIER);
837 if (!(link->flags & DL_FLAG_MANAGED)) {
838 kref_get(&link->kref);
839 link->flags |= DL_FLAG_MANAGED;
840 device_link_init_status(link, consumer, supplier);
842 if (link->flags & DL_FLAG_SYNC_STATE_ONLY &&
843 !(flags & DL_FLAG_SYNC_STATE_ONLY)) {
844 link->flags &= ~DL_FLAG_SYNC_STATE_ONLY;
851 link = kzalloc(sizeof(*link), GFP_KERNEL);
855 refcount_set(&link->rpm_active, 1);
857 get_device(supplier);
858 link->supplier = supplier;
859 INIT_LIST_HEAD(&link->s_node);
860 get_device(consumer);
861 link->consumer = consumer;
862 INIT_LIST_HEAD(&link->c_node);
864 kref_init(&link->kref);
866 link->link_dev.class = &devlink_class;
867 device_set_pm_not_required(&link->link_dev);
868 dev_set_name(&link->link_dev, "%s:%s--%s:%s",
869 dev_bus_name(supplier), dev_name(supplier),
870 dev_bus_name(consumer), dev_name(consumer));
871 if (device_register(&link->link_dev)) {
872 put_device(&link->link_dev);
877 if (flags & DL_FLAG_PM_RUNTIME) {
878 if (flags & DL_FLAG_RPM_ACTIVE)
879 refcount_inc(&link->rpm_active);
881 pm_runtime_new_link(consumer);
884 /* Determine the initial link state. */
885 if (flags & DL_FLAG_STATELESS)
886 link->status = DL_STATE_NONE;
888 device_link_init_status(link, consumer, supplier);
891 * Some callers expect the link creation during consumer driver probe to
892 * resume the supplier even without DL_FLAG_RPM_ACTIVE.
894 if (link->status == DL_STATE_CONSUMER_PROBE &&
895 flags & DL_FLAG_PM_RUNTIME)
896 pm_runtime_resume(supplier);
898 list_add_tail_rcu(&link->s_node, &supplier->links.consumers);
899 list_add_tail_rcu(&link->c_node, &consumer->links.suppliers);
901 if (flags & DL_FLAG_SYNC_STATE_ONLY) {
903 "Linked as a sync state only consumer to %s\n",
910 * Move the consumer and all of the devices depending on it to the end
911 * of dpm_list and the devices_kset list.
913 * It is necessary to hold dpm_list locked throughout all that or else
914 * we may end up suspending with a wrong ordering of it.
916 device_reorder_to_tail(consumer, NULL);
918 dev_dbg(consumer, "Linked as a consumer to %s\n", dev_name(supplier));
922 device_links_write_unlock();
924 if ((flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) && !link)
925 pm_runtime_put(supplier);
929 EXPORT_SYMBOL_GPL(device_link_add);
931 static void __device_link_del(struct kref *kref)
933 struct device_link *link = container_of(kref, struct device_link, kref);
935 dev_dbg(link->consumer, "Dropping the link to %s\n",
936 dev_name(link->supplier));
938 pm_runtime_drop_link(link);
940 device_link_remove_from_lists(link);
941 device_unregister(&link->link_dev);
944 static void device_link_put_kref(struct device_link *link)
946 if (link->flags & DL_FLAG_STATELESS)
947 kref_put(&link->kref, __device_link_del);
948 else if (!device_is_registered(link->consumer))
949 __device_link_del(&link->kref);
951 WARN(1, "Unable to drop a managed device link reference\n");
955 * device_link_del - Delete a stateless link between two devices.
956 * @link: Device link to delete.
958 * The caller must ensure proper synchronization of this function with runtime
959 * PM. If the link was added multiple times, it needs to be deleted as often.
960 * Care is required for hotplugged devices: Their links are purged on removal
961 * and calling device_link_del() is then no longer allowed.
963 void device_link_del(struct device_link *link)
965 device_links_write_lock();
966 device_link_put_kref(link);
967 device_links_write_unlock();
969 EXPORT_SYMBOL_GPL(device_link_del);
972 * device_link_remove - Delete a stateless link between two devices.
973 * @consumer: Consumer end of the link.
974 * @supplier: Supplier end of the link.
976 * The caller must ensure proper synchronization of this function with runtime
979 void device_link_remove(void *consumer, struct device *supplier)
981 struct device_link *link;
983 if (WARN_ON(consumer == supplier))
986 device_links_write_lock();
988 list_for_each_entry(link, &supplier->links.consumers, s_node) {
989 if (link->consumer == consumer) {
990 device_link_put_kref(link);
995 device_links_write_unlock();
997 EXPORT_SYMBOL_GPL(device_link_remove);
999 static void device_links_missing_supplier(struct device *dev)
1001 struct device_link *link;
1003 list_for_each_entry(link, &dev->links.suppliers, c_node) {
1004 if (link->status != DL_STATE_CONSUMER_PROBE)
1007 if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
1008 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1010 WARN_ON(!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
1011 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1016 static bool dev_is_best_effort(struct device *dev)
1018 return (fw_devlink_best_effort && dev->can_match) ||
1019 (dev->fwnode && (dev->fwnode->flags & FWNODE_FLAG_BEST_EFFORT));
1022 static struct fwnode_handle *fwnode_links_check_suppliers(
1023 struct fwnode_handle *fwnode)
1025 struct fwnode_link *link;
1027 if (!fwnode || fw_devlink_is_permissive())
1030 list_for_each_entry(link, &fwnode->suppliers, c_hook)
1032 (FWLINK_FLAG_CYCLE | FWLINK_FLAG_IGNORE)))
1033 return link->supplier;
1039 * device_links_check_suppliers - Check presence of supplier drivers.
1040 * @dev: Consumer device.
1042 * Check links from this device to any suppliers. Walk the list of the device's
1043 * links to suppliers and see if all of them are available. If not, simply
1044 * return -EPROBE_DEFER.
1046 * We need to guarantee that the supplier will not go away after the check has
1047 * been positive here. It only can go away in __device_release_driver() and
1048 * that function checks the device's links to consumers. This means we need to
1049 * mark the link as "consumer probe in progress" to make the supplier removal
1050 * wait for us to complete (or bad things may happen).
1052 * Links without the DL_FLAG_MANAGED flag set are ignored.
1054 int device_links_check_suppliers(struct device *dev)
1056 struct device_link *link;
1057 int ret = 0, fwnode_ret = 0;
1058 struct fwnode_handle *sup_fw;
1061 * Device waiting for supplier to become available is not allowed to
1064 mutex_lock(&fwnode_link_lock);
1065 sup_fw = fwnode_links_check_suppliers(dev->fwnode);
1067 if (!dev_is_best_effort(dev)) {
1068 fwnode_ret = -EPROBE_DEFER;
1069 dev_err_probe(dev, -EPROBE_DEFER,
1070 "wait for supplier %pfwf\n", sup_fw);
1072 fwnode_ret = -EAGAIN;
1075 mutex_unlock(&fwnode_link_lock);
1076 if (fwnode_ret == -EPROBE_DEFER)
1079 device_links_write_lock();
1081 list_for_each_entry(link, &dev->links.suppliers, c_node) {
1082 if (!(link->flags & DL_FLAG_MANAGED))
1085 if (link->status != DL_STATE_AVAILABLE &&
1086 !(link->flags & DL_FLAG_SYNC_STATE_ONLY)) {
1088 if (dev_is_best_effort(dev) &&
1089 link->flags & DL_FLAG_INFERRED &&
1090 !link->supplier->can_match) {
1095 device_links_missing_supplier(dev);
1096 dev_err_probe(dev, -EPROBE_DEFER,
1097 "supplier %s not ready\n",
1098 dev_name(link->supplier));
1099 ret = -EPROBE_DEFER;
1102 WRITE_ONCE(link->status, DL_STATE_CONSUMER_PROBE);
1104 dev->links.status = DL_DEV_PROBING;
1106 device_links_write_unlock();
1108 return ret ? ret : fwnode_ret;
1112 * __device_links_queue_sync_state - Queue a device for sync_state() callback
1113 * @dev: Device to call sync_state() on
1114 * @list: List head to queue the @dev on
1116 * Queues a device for a sync_state() callback when the device links write lock
1117 * isn't held. This allows the sync_state() execution flow to use device links
1118 * APIs. The caller must ensure this function is called with
1119 * device_links_write_lock() held.
1121 * This function does a get_device() to make sure the device is not freed while
1124 * So the caller must also ensure that device_links_flush_sync_list() is called
1125 * as soon as the caller releases device_links_write_lock(). This is necessary
1126 * to make sure the sync_state() is called in a timely fashion and the
1127 * put_device() is called on this device.
1129 static void __device_links_queue_sync_state(struct device *dev,
1130 struct list_head *list)
1132 struct device_link *link;
1134 if (!dev_has_sync_state(dev))
1136 if (dev->state_synced)
1139 list_for_each_entry(link, &dev->links.consumers, s_node) {
1140 if (!(link->flags & DL_FLAG_MANAGED))
1142 if (link->status != DL_STATE_ACTIVE)
1147 * Set the flag here to avoid adding the same device to a list more
1148 * than once. This can happen if new consumers get added to the device
1149 * and probed before the list is flushed.
1151 dev->state_synced = true;
1153 if (WARN_ON(!list_empty(&dev->links.defer_sync)))
1157 list_add_tail(&dev->links.defer_sync, list);
1161 * device_links_flush_sync_list - Call sync_state() on a list of devices
1162 * @list: List of devices to call sync_state() on
1163 * @dont_lock_dev: Device for which lock is already held by the caller
1165 * Calls sync_state() on all the devices that have been queued for it. This
1166 * function is used in conjunction with __device_links_queue_sync_state(). The
1167 * @dont_lock_dev parameter is useful when this function is called from a
1168 * context where a device lock is already held.
1170 static void device_links_flush_sync_list(struct list_head *list,
1171 struct device *dont_lock_dev)
1173 struct device *dev, *tmp;
1175 list_for_each_entry_safe(dev, tmp, list, links.defer_sync) {
1176 list_del_init(&dev->links.defer_sync);
1178 if (dev != dont_lock_dev)
1181 dev_sync_state(dev);
1183 if (dev != dont_lock_dev)
1190 void device_links_supplier_sync_state_pause(void)
1192 device_links_write_lock();
1193 defer_sync_state_count++;
1194 device_links_write_unlock();
1197 void device_links_supplier_sync_state_resume(void)
1199 struct device *dev, *tmp;
1200 LIST_HEAD(sync_list);
1202 device_links_write_lock();
1203 if (!defer_sync_state_count) {
1204 WARN(true, "Unmatched sync_state pause/resume!");
1207 defer_sync_state_count--;
1208 if (defer_sync_state_count)
1211 list_for_each_entry_safe(dev, tmp, &deferred_sync, links.defer_sync) {
1213 * Delete from deferred_sync list before queuing it to
1214 * sync_list because defer_sync is used for both lists.
1216 list_del_init(&dev->links.defer_sync);
1217 __device_links_queue_sync_state(dev, &sync_list);
1220 device_links_write_unlock();
1222 device_links_flush_sync_list(&sync_list, NULL);
1225 static int sync_state_resume_initcall(void)
1227 device_links_supplier_sync_state_resume();
1230 late_initcall(sync_state_resume_initcall);
1232 static void __device_links_supplier_defer_sync(struct device *sup)
1234 if (list_empty(&sup->links.defer_sync) && dev_has_sync_state(sup))
1235 list_add_tail(&sup->links.defer_sync, &deferred_sync);
1238 static void device_link_drop_managed(struct device_link *link)
1240 link->flags &= ~DL_FLAG_MANAGED;
1241 WRITE_ONCE(link->status, DL_STATE_NONE);
1242 kref_put(&link->kref, __device_link_del);
1245 static ssize_t waiting_for_supplier_show(struct device *dev,
1246 struct device_attribute *attr,
1252 mutex_lock(&fwnode_link_lock);
1253 val = !!fwnode_links_check_suppliers(dev->fwnode);
1254 mutex_unlock(&fwnode_link_lock);
1256 return sysfs_emit(buf, "%u\n", val);
1258 static DEVICE_ATTR_RO(waiting_for_supplier);
1261 * device_links_force_bind - Prepares device to be force bound
1262 * @dev: Consumer device.
1264 * device_bind_driver() force binds a device to a driver without calling any
1265 * driver probe functions. So the consumer really isn't going to wait for any
1266 * supplier before it's bound to the driver. We still want the device link
1267 * states to be sensible when this happens.
1269 * In preparation for device_bind_driver(), this function goes through each
1270 * supplier device links and checks if the supplier is bound. If it is, then
1271 * the device link status is set to CONSUMER_PROBE. Otherwise, the device link
1272 * is dropped. Links without the DL_FLAG_MANAGED flag set are ignored.
1274 void device_links_force_bind(struct device *dev)
1276 struct device_link *link, *ln;
1278 device_links_write_lock();
1280 list_for_each_entry_safe(link, ln, &dev->links.suppliers, c_node) {
1281 if (!(link->flags & DL_FLAG_MANAGED))
1284 if (link->status != DL_STATE_AVAILABLE) {
1285 device_link_drop_managed(link);
1288 WRITE_ONCE(link->status, DL_STATE_CONSUMER_PROBE);
1290 dev->links.status = DL_DEV_PROBING;
1292 device_links_write_unlock();
1296 * device_links_driver_bound - Update device links after probing its driver.
1297 * @dev: Device to update the links for.
1299 * The probe has been successful, so update links from this device to any
1300 * consumers by changing their status to "available".
1302 * Also change the status of @dev's links to suppliers to "active".
1304 * Links without the DL_FLAG_MANAGED flag set are ignored.
1306 void device_links_driver_bound(struct device *dev)
1308 struct device_link *link, *ln;
1309 LIST_HEAD(sync_list);
1312 * If a device binds successfully, it's expected to have created all
1313 * the device links it needs to or make new device links as it needs
1314 * them. So, fw_devlink no longer needs to create device links to any
1315 * of the device's suppliers.
1317 * Also, if a child firmware node of this bound device is not added as a
1318 * device by now, assume it is never going to be added. Make this bound
1319 * device the fallback supplier to the dangling consumers of the child
1320 * firmware node because this bound device is probably implementing the
1321 * child firmware node functionality and we don't want the dangling
1322 * consumers to defer probe indefinitely waiting for a device for the
1323 * child firmware node.
1325 if (dev->fwnode && dev->fwnode->dev == dev) {
1326 struct fwnode_handle *child;
1327 fwnode_links_purge_suppliers(dev->fwnode);
1328 mutex_lock(&fwnode_link_lock);
1329 fwnode_for_each_available_child_node(dev->fwnode, child)
1330 __fw_devlink_pickup_dangling_consumers(child,
1332 __fw_devlink_link_to_consumers(dev);
1333 mutex_unlock(&fwnode_link_lock);
1335 device_remove_file(dev, &dev_attr_waiting_for_supplier);
1337 device_links_write_lock();
1339 list_for_each_entry(link, &dev->links.consumers, s_node) {
1340 if (!(link->flags & DL_FLAG_MANAGED))
1344 * Links created during consumer probe may be in the "consumer
1345 * probe" state to start with if the supplier is still probing
1346 * when they are created and they may become "active" if the
1347 * consumer probe returns first. Skip them here.
1349 if (link->status == DL_STATE_CONSUMER_PROBE ||
1350 link->status == DL_STATE_ACTIVE)
1353 WARN_ON(link->status != DL_STATE_DORMANT);
1354 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1356 if (link->flags & DL_FLAG_AUTOPROBE_CONSUMER)
1357 driver_deferred_probe_add(link->consumer);
1360 if (defer_sync_state_count)
1361 __device_links_supplier_defer_sync(dev);
1363 __device_links_queue_sync_state(dev, &sync_list);
1365 list_for_each_entry_safe(link, ln, &dev->links.suppliers, c_node) {
1366 struct device *supplier;
1368 if (!(link->flags & DL_FLAG_MANAGED))
1371 supplier = link->supplier;
1372 if (link->flags & DL_FLAG_SYNC_STATE_ONLY) {
1374 * When DL_FLAG_SYNC_STATE_ONLY is set, it means no
1375 * other DL_MANAGED_LINK_FLAGS have been set. So, it's
1376 * save to drop the managed link completely.
1378 device_link_drop_managed(link);
1379 } else if (dev_is_best_effort(dev) &&
1380 link->flags & DL_FLAG_INFERRED &&
1381 link->status != DL_STATE_CONSUMER_PROBE &&
1382 !link->supplier->can_match) {
1384 * When dev_is_best_effort() is true, we ignore device
1385 * links to suppliers that don't have a driver. If the
1386 * consumer device still managed to probe, there's no
1387 * point in maintaining a device link in a weird state
1388 * (consumer probed before supplier). So delete it.
1390 device_link_drop_managed(link);
1392 WARN_ON(link->status != DL_STATE_CONSUMER_PROBE);
1393 WRITE_ONCE(link->status, DL_STATE_ACTIVE);
1397 * This needs to be done even for the deleted
1398 * DL_FLAG_SYNC_STATE_ONLY device link in case it was the last
1399 * device link that was preventing the supplier from getting a
1400 * sync_state() call.
1402 if (defer_sync_state_count)
1403 __device_links_supplier_defer_sync(supplier);
1405 __device_links_queue_sync_state(supplier, &sync_list);
1408 dev->links.status = DL_DEV_DRIVER_BOUND;
1410 device_links_write_unlock();
1412 device_links_flush_sync_list(&sync_list, dev);
1416 * __device_links_no_driver - Update links of a device without a driver.
1417 * @dev: Device without a drvier.
1419 * Delete all non-persistent links from this device to any suppliers.
1421 * Persistent links stay around, but their status is changed to "available",
1422 * unless they already are in the "supplier unbind in progress" state in which
1423 * case they need not be updated.
1425 * Links without the DL_FLAG_MANAGED flag set are ignored.
1427 static void __device_links_no_driver(struct device *dev)
1429 struct device_link *link, *ln;
1431 list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1432 if (!(link->flags & DL_FLAG_MANAGED))
1435 if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER) {
1436 device_link_drop_managed(link);
1440 if (link->status != DL_STATE_CONSUMER_PROBE &&
1441 link->status != DL_STATE_ACTIVE)
1444 if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
1445 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1447 WARN_ON(!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
1448 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1452 dev->links.status = DL_DEV_NO_DRIVER;
1456 * device_links_no_driver - Update links after failing driver probe.
1457 * @dev: Device whose driver has just failed to probe.
1459 * Clean up leftover links to consumers for @dev and invoke
1460 * %__device_links_no_driver() to update links to suppliers for it as
1463 * Links without the DL_FLAG_MANAGED flag set are ignored.
1465 void device_links_no_driver(struct device *dev)
1467 struct device_link *link;
1469 device_links_write_lock();
1471 list_for_each_entry(link, &dev->links.consumers, s_node) {
1472 if (!(link->flags & DL_FLAG_MANAGED))
1476 * The probe has failed, so if the status of the link is
1477 * "consumer probe" or "active", it must have been added by
1478 * a probing consumer while this device was still probing.
1479 * Change its state to "dormant", as it represents a valid
1480 * relationship, but it is not functionally meaningful.
1482 if (link->status == DL_STATE_CONSUMER_PROBE ||
1483 link->status == DL_STATE_ACTIVE)
1484 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1487 __device_links_no_driver(dev);
1489 device_links_write_unlock();
1493 * device_links_driver_cleanup - Update links after driver removal.
1494 * @dev: Device whose driver has just gone away.
1496 * Update links to consumers for @dev by changing their status to "dormant" and
1497 * invoke %__device_links_no_driver() to update links to suppliers for it as
1500 * Links without the DL_FLAG_MANAGED flag set are ignored.
1502 void device_links_driver_cleanup(struct device *dev)
1504 struct device_link *link, *ln;
1506 device_links_write_lock();
1508 list_for_each_entry_safe(link, ln, &dev->links.consumers, s_node) {
1509 if (!(link->flags & DL_FLAG_MANAGED))
1512 WARN_ON(link->flags & DL_FLAG_AUTOREMOVE_CONSUMER);
1513 WARN_ON(link->status != DL_STATE_SUPPLIER_UNBIND);
1516 * autoremove the links between this @dev and its consumer
1517 * devices that are not active, i.e. where the link state
1518 * has moved to DL_STATE_SUPPLIER_UNBIND.
1520 if (link->status == DL_STATE_SUPPLIER_UNBIND &&
1521 link->flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
1522 device_link_drop_managed(link);
1524 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1527 list_del_init(&dev->links.defer_sync);
1528 __device_links_no_driver(dev);
1530 device_links_write_unlock();
1534 * device_links_busy - Check if there are any busy links to consumers.
1535 * @dev: Device to check.
1537 * Check each consumer of the device and return 'true' if its link's status
1538 * is one of "consumer probe" or "active" (meaning that the given consumer is
1539 * probing right now or its driver is present). Otherwise, change the link
1540 * state to "supplier unbind" to prevent the consumer from being probed
1541 * successfully going forward.
1543 * Return 'false' if there are no probing or active consumers.
1545 * Links without the DL_FLAG_MANAGED flag set are ignored.
1547 bool device_links_busy(struct device *dev)
1549 struct device_link *link;
1552 device_links_write_lock();
1554 list_for_each_entry(link, &dev->links.consumers, s_node) {
1555 if (!(link->flags & DL_FLAG_MANAGED))
1558 if (link->status == DL_STATE_CONSUMER_PROBE
1559 || link->status == DL_STATE_ACTIVE) {
1563 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1566 dev->links.status = DL_DEV_UNBINDING;
1568 device_links_write_unlock();
1573 * device_links_unbind_consumers - Force unbind consumers of the given device.
1574 * @dev: Device to unbind the consumers of.
1576 * Walk the list of links to consumers for @dev and if any of them is in the
1577 * "consumer probe" state, wait for all device probes in progress to complete
1580 * If that's not the case, change the status of the link to "supplier unbind"
1581 * and check if the link was in the "active" state. If so, force the consumer
1582 * driver to unbind and start over (the consumer will not re-probe as we have
1583 * changed the state of the link already).
1585 * Links without the DL_FLAG_MANAGED flag set are ignored.
1587 void device_links_unbind_consumers(struct device *dev)
1589 struct device_link *link;
1592 device_links_write_lock();
1594 list_for_each_entry(link, &dev->links.consumers, s_node) {
1595 enum device_link_state status;
1597 if (!(link->flags & DL_FLAG_MANAGED) ||
1598 link->flags & DL_FLAG_SYNC_STATE_ONLY)
1601 status = link->status;
1602 if (status == DL_STATE_CONSUMER_PROBE) {
1603 device_links_write_unlock();
1605 wait_for_device_probe();
1608 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1609 if (status == DL_STATE_ACTIVE) {
1610 struct device *consumer = link->consumer;
1612 get_device(consumer);
1614 device_links_write_unlock();
1616 device_release_driver_internal(consumer, NULL,
1618 put_device(consumer);
1623 device_links_write_unlock();
1627 * device_links_purge - Delete existing links to other devices.
1628 * @dev: Target device.
1630 static void device_links_purge(struct device *dev)
1632 struct device_link *link, *ln;
1634 if (dev->class == &devlink_class)
1638 * Delete all of the remaining links from this device to any other
1639 * devices (either consumers or suppliers).
1641 device_links_write_lock();
1643 list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1644 WARN_ON(link->status == DL_STATE_ACTIVE);
1645 __device_link_del(&link->kref);
1648 list_for_each_entry_safe_reverse(link, ln, &dev->links.consumers, s_node) {
1649 WARN_ON(link->status != DL_STATE_DORMANT &&
1650 link->status != DL_STATE_NONE);
1651 __device_link_del(&link->kref);
1654 device_links_write_unlock();
1657 #define FW_DEVLINK_FLAGS_PERMISSIVE (DL_FLAG_INFERRED | \
1658 DL_FLAG_SYNC_STATE_ONLY)
1659 #define FW_DEVLINK_FLAGS_ON (DL_FLAG_INFERRED | \
1660 DL_FLAG_AUTOPROBE_CONSUMER)
1661 #define FW_DEVLINK_FLAGS_RPM (FW_DEVLINK_FLAGS_ON | \
1664 static u32 fw_devlink_flags = FW_DEVLINK_FLAGS_RPM;
1665 static int __init fw_devlink_setup(char *arg)
1670 if (strcmp(arg, "off") == 0) {
1671 fw_devlink_flags = 0;
1672 } else if (strcmp(arg, "permissive") == 0) {
1673 fw_devlink_flags = FW_DEVLINK_FLAGS_PERMISSIVE;
1674 } else if (strcmp(arg, "on") == 0) {
1675 fw_devlink_flags = FW_DEVLINK_FLAGS_ON;
1676 } else if (strcmp(arg, "rpm") == 0) {
1677 fw_devlink_flags = FW_DEVLINK_FLAGS_RPM;
1681 early_param("fw_devlink", fw_devlink_setup);
1683 static bool fw_devlink_strict;
1684 static int __init fw_devlink_strict_setup(char *arg)
1686 return kstrtobool(arg, &fw_devlink_strict);
1688 early_param("fw_devlink.strict", fw_devlink_strict_setup);
1690 #define FW_DEVLINK_SYNC_STATE_STRICT 0
1691 #define FW_DEVLINK_SYNC_STATE_TIMEOUT 1
1693 #ifndef CONFIG_FW_DEVLINK_SYNC_STATE_TIMEOUT
1694 static int fw_devlink_sync_state;
1696 static int fw_devlink_sync_state = FW_DEVLINK_SYNC_STATE_TIMEOUT;
1699 static int __init fw_devlink_sync_state_setup(char *arg)
1704 if (strcmp(arg, "strict") == 0) {
1705 fw_devlink_sync_state = FW_DEVLINK_SYNC_STATE_STRICT;
1707 } else if (strcmp(arg, "timeout") == 0) {
1708 fw_devlink_sync_state = FW_DEVLINK_SYNC_STATE_TIMEOUT;
1713 early_param("fw_devlink.sync_state", fw_devlink_sync_state_setup);
1715 static inline u32 fw_devlink_get_flags(u8 fwlink_flags)
1717 if (fwlink_flags & FWLINK_FLAG_CYCLE)
1718 return FW_DEVLINK_FLAGS_PERMISSIVE | DL_FLAG_CYCLE;
1720 return fw_devlink_flags;
1723 static bool fw_devlink_is_permissive(void)
1725 return fw_devlink_flags == FW_DEVLINK_FLAGS_PERMISSIVE;
1728 bool fw_devlink_is_strict(void)
1730 return fw_devlink_strict && !fw_devlink_is_permissive();
1733 static void fw_devlink_parse_fwnode(struct fwnode_handle *fwnode)
1735 if (fwnode->flags & FWNODE_FLAG_LINKS_ADDED)
1738 fwnode_call_int_op(fwnode, add_links);
1739 fwnode->flags |= FWNODE_FLAG_LINKS_ADDED;
1742 static void fw_devlink_parse_fwtree(struct fwnode_handle *fwnode)
1744 struct fwnode_handle *child = NULL;
1746 fw_devlink_parse_fwnode(fwnode);
1748 while ((child = fwnode_get_next_available_child_node(fwnode, child)))
1749 fw_devlink_parse_fwtree(child);
1752 static void fw_devlink_relax_link(struct device_link *link)
1754 if (!(link->flags & DL_FLAG_INFERRED))
1757 if (device_link_flag_is_sync_state_only(link->flags))
1760 pm_runtime_drop_link(link);
1761 link->flags = DL_FLAG_MANAGED | FW_DEVLINK_FLAGS_PERMISSIVE;
1762 dev_dbg(link->consumer, "Relaxing link with %s\n",
1763 dev_name(link->supplier));
1766 static int fw_devlink_no_driver(struct device *dev, void *data)
1768 struct device_link *link = to_devlink(dev);
1770 if (!link->supplier->can_match)
1771 fw_devlink_relax_link(link);
1776 void fw_devlink_drivers_done(void)
1778 fw_devlink_drv_reg_done = true;
1779 device_links_write_lock();
1780 class_for_each_device(&devlink_class, NULL, NULL,
1781 fw_devlink_no_driver);
1782 device_links_write_unlock();
1785 static int fw_devlink_dev_sync_state(struct device *dev, void *data)
1787 struct device_link *link = to_devlink(dev);
1788 struct device *sup = link->supplier;
1790 if (!(link->flags & DL_FLAG_MANAGED) ||
1791 link->status == DL_STATE_ACTIVE || sup->state_synced ||
1792 !dev_has_sync_state(sup))
1795 if (fw_devlink_sync_state == FW_DEVLINK_SYNC_STATE_STRICT) {
1796 dev_warn(sup, "sync_state() pending due to %s\n",
1797 dev_name(link->consumer));
1801 if (!list_empty(&sup->links.defer_sync))
1804 dev_warn(sup, "Timed out. Forcing sync_state()\n");
1805 sup->state_synced = true;
1807 list_add_tail(&sup->links.defer_sync, data);
1812 void fw_devlink_probing_done(void)
1814 LIST_HEAD(sync_list);
1816 device_links_write_lock();
1817 class_for_each_device(&devlink_class, NULL, &sync_list,
1818 fw_devlink_dev_sync_state);
1819 device_links_write_unlock();
1820 device_links_flush_sync_list(&sync_list, NULL);
1824 * wait_for_init_devices_probe - Try to probe any device needed for init
1826 * Some devices might need to be probed and bound successfully before the kernel
1827 * boot sequence can finish and move on to init/userspace. For example, a
1828 * network interface might need to be bound to be able to mount a NFS rootfs.
1830 * With fw_devlink=on by default, some of these devices might be blocked from
1831 * probing because they are waiting on a optional supplier that doesn't have a
1832 * driver. While fw_devlink will eventually identify such devices and unblock
1833 * the probing automatically, it might be too late by the time it unblocks the
1834 * probing of devices. For example, the IP4 autoconfig might timeout before
1835 * fw_devlink unblocks probing of the network interface.
1837 * This function is available to temporarily try and probe all devices that have
1838 * a driver even if some of their suppliers haven't been added or don't have
1841 * The drivers can then decide which of the suppliers are optional vs mandatory
1842 * and probe the device if possible. By the time this function returns, all such
1843 * "best effort" probes are guaranteed to be completed. If a device successfully
1844 * probes in this mode, we delete all fw_devlink discovered dependencies of that
1845 * device where the supplier hasn't yet probed successfully because they have to
1846 * be optional dependencies.
1848 * Any devices that didn't successfully probe go back to being treated as if
1849 * this function was never called.
1851 * This also means that some devices that aren't needed for init and could have
1852 * waited for their optional supplier to probe (when the supplier's module is
1853 * loaded later on) would end up probing prematurely with limited functionality.
1854 * So call this function only when boot would fail without it.
1856 void __init wait_for_init_devices_probe(void)
1858 if (!fw_devlink_flags || fw_devlink_is_permissive())
1862 * Wait for all ongoing probes to finish so that the "best effort" is
1863 * only applied to devices that can't probe otherwise.
1865 wait_for_device_probe();
1867 pr_info("Trying to probe devices needed for running init ...\n");
1868 fw_devlink_best_effort = true;
1869 driver_deferred_probe_trigger();
1872 * Wait for all "best effort" probes to finish before going back to
1873 * normal enforcement.
1875 wait_for_device_probe();
1876 fw_devlink_best_effort = false;
1879 static void fw_devlink_unblock_consumers(struct device *dev)
1881 struct device_link *link;
1883 if (!fw_devlink_flags || fw_devlink_is_permissive())
1886 device_links_write_lock();
1887 list_for_each_entry(link, &dev->links.consumers, s_node)
1888 fw_devlink_relax_link(link);
1889 device_links_write_unlock();
1892 #define get_dev_from_fwnode(fwnode) get_device((fwnode)->dev)
1894 static bool fwnode_init_without_drv(struct fwnode_handle *fwnode)
1899 if (!(fwnode->flags & FWNODE_FLAG_INITIALIZED))
1902 dev = get_dev_from_fwnode(fwnode);
1903 ret = !dev || dev->links.status == DL_DEV_NO_DRIVER;
1909 static bool fwnode_ancestor_init_without_drv(struct fwnode_handle *fwnode)
1911 struct fwnode_handle *parent;
1913 fwnode_for_each_parent_node(fwnode, parent) {
1914 if (fwnode_init_without_drv(parent)) {
1915 fwnode_handle_put(parent);
1924 * fwnode_is_ancestor_of - Test if @ancestor is ancestor of @child
1925 * @ancestor: Firmware which is tested for being an ancestor
1926 * @child: Firmware which is tested for being the child
1928 * A node is considered an ancestor of itself too.
1930 * Return: true if @ancestor is an ancestor of @child. Otherwise, returns false.
1932 static bool fwnode_is_ancestor_of(const struct fwnode_handle *ancestor,
1933 const struct fwnode_handle *child)
1935 struct fwnode_handle *parent;
1937 if (IS_ERR_OR_NULL(ancestor))
1940 if (child == ancestor)
1943 fwnode_for_each_parent_node(child, parent) {
1944 if (parent == ancestor) {
1945 fwnode_handle_put(parent);
1953 * fwnode_get_next_parent_dev - Find device of closest ancestor fwnode
1954 * @fwnode: firmware node
1956 * Given a firmware node (@fwnode), this function finds its closest ancestor
1957 * firmware node that has a corresponding struct device and returns that struct
1960 * The caller is responsible for calling put_device() on the returned device
1963 * Return: a pointer to the device of the @fwnode's closest ancestor.
1965 static struct device *fwnode_get_next_parent_dev(const struct fwnode_handle *fwnode)
1967 struct fwnode_handle *parent;
1970 fwnode_for_each_parent_node(fwnode, parent) {
1971 dev = get_dev_from_fwnode(parent);
1973 fwnode_handle_put(parent);
1981 * __fw_devlink_relax_cycles - Relax and mark dependency cycles.
1982 * @con: Potential consumer device.
1983 * @sup_handle: Potential supplier's fwnode.
1985 * Needs to be called with fwnode_lock and device link lock held.
1987 * Check if @sup_handle or any of its ancestors or suppliers direct/indirectly
1988 * depend on @con. This function can detect multiple cyles between @sup_handle
1989 * and @con. When such dependency cycles are found, convert all device links
1990 * created solely by fw_devlink into SYNC_STATE_ONLY device links. Also, mark
1991 * all fwnode links in the cycle with FWLINK_FLAG_CYCLE so that when they are
1992 * converted into a device link in the future, they are created as
1993 * SYNC_STATE_ONLY device links. This is the equivalent of doing
1994 * fw_devlink=permissive just between the devices in the cycle. We need to do
1995 * this because, at this point, fw_devlink can't tell which of these
1996 * dependencies is not a real dependency.
1998 * Return true if one or more cycles were found. Otherwise, return false.
2000 static bool __fw_devlink_relax_cycles(struct device *con,
2001 struct fwnode_handle *sup_handle)
2003 struct device *sup_dev = NULL, *par_dev = NULL;
2004 struct fwnode_link *link;
2005 struct device_link *dev_link;
2012 * We aren't trying to find all cycles. Just a cycle between con and
2015 if (sup_handle->flags & FWNODE_FLAG_VISITED)
2018 sup_handle->flags |= FWNODE_FLAG_VISITED;
2020 sup_dev = get_dev_from_fwnode(sup_handle);
2022 /* Termination condition. */
2023 if (sup_dev == con) {
2024 pr_debug("----- cycle: start -----\n");
2030 * If sup_dev is bound to a driver and @con hasn't started binding to a
2031 * driver, sup_dev can't be a consumer of @con. So, no need to check
2034 if (sup_dev && sup_dev->links.status == DL_DEV_DRIVER_BOUND &&
2035 con->links.status == DL_DEV_NO_DRIVER) {
2040 list_for_each_entry(link, &sup_handle->suppliers, c_hook) {
2041 if (link->flags & FWLINK_FLAG_IGNORE)
2044 if (__fw_devlink_relax_cycles(con, link->supplier)) {
2045 __fwnode_link_cycle(link);
2051 * Give priority to device parent over fwnode parent to account for any
2052 * quirks in how fwnodes are converted to devices.
2055 par_dev = get_device(sup_dev->parent);
2057 par_dev = fwnode_get_next_parent_dev(sup_handle);
2059 if (par_dev && __fw_devlink_relax_cycles(con, par_dev->fwnode)) {
2060 pr_debug("%pfwf: cycle: child of %pfwf\n", sup_handle,
2068 list_for_each_entry(dev_link, &sup_dev->links.suppliers, c_node) {
2070 * Ignore a SYNC_STATE_ONLY flag only if it wasn't marked as
2071 * such due to a cycle.
2073 if (device_link_flag_is_sync_state_only(dev_link->flags) &&
2074 !(dev_link->flags & DL_FLAG_CYCLE))
2077 if (__fw_devlink_relax_cycles(con,
2078 dev_link->supplier->fwnode)) {
2079 pr_debug("%pfwf: cycle: depends on %pfwf\n", sup_handle,
2080 dev_link->supplier->fwnode);
2081 fw_devlink_relax_link(dev_link);
2082 dev_link->flags |= DL_FLAG_CYCLE;
2088 sup_handle->flags &= ~FWNODE_FLAG_VISITED;
2089 put_device(sup_dev);
2090 put_device(par_dev);
2095 * fw_devlink_create_devlink - Create a device link from a consumer to fwnode
2096 * @con: consumer device for the device link
2097 * @sup_handle: fwnode handle of supplier
2098 * @link: fwnode link that's being converted to a device link
2100 * This function will try to create a device link between the consumer device
2101 * @con and the supplier device represented by @sup_handle.
2103 * The supplier has to be provided as a fwnode because incorrect cycles in
2104 * fwnode links can sometimes cause the supplier device to never be created.
2105 * This function detects such cases and returns an error if it cannot create a
2106 * device link from the consumer to a missing supplier.
2109 * 0 on successfully creating a device link
2110 * -EINVAL if the device link cannot be created as expected
2111 * -EAGAIN if the device link cannot be created right now, but it may be
2112 * possible to do that in the future
2114 static int fw_devlink_create_devlink(struct device *con,
2115 struct fwnode_handle *sup_handle,
2116 struct fwnode_link *link)
2118 struct device *sup_dev;
2122 if (link->flags & FWLINK_FLAG_IGNORE)
2125 if (con->fwnode == link->consumer)
2126 flags = fw_devlink_get_flags(link->flags);
2128 flags = FW_DEVLINK_FLAGS_PERMISSIVE;
2131 * In some cases, a device P might also be a supplier to its child node
2132 * C. However, this would defer the probe of C until the probe of P
2133 * completes successfully. This is perfectly fine in the device driver
2134 * model. device_add() doesn't guarantee probe completion of the device
2135 * by the time it returns.
2137 * However, there are a few drivers that assume C will finish probing
2138 * as soon as it's added and before P finishes probing. So, we provide
2139 * a flag to let fw_devlink know not to delay the probe of C until the
2140 * probe of P completes successfully.
2142 * When such a flag is set, we can't create device links where P is the
2143 * supplier of C as that would delay the probe of C.
2145 if (sup_handle->flags & FWNODE_FLAG_NEEDS_CHILD_BOUND_ON_ADD &&
2146 fwnode_is_ancestor_of(sup_handle, con->fwnode))
2150 * SYNC_STATE_ONLY device links don't block probing and supports cycles.
2151 * So, one might expect that cycle detection isn't necessary for them.
2152 * However, if the device link was marked as SYNC_STATE_ONLY because
2153 * it's part of a cycle, then we still need to do cycle detection. This
2154 * is because the consumer and supplier might be part of multiple cycles
2155 * and we need to detect all those cycles.
2157 if (!device_link_flag_is_sync_state_only(flags) ||
2158 flags & DL_FLAG_CYCLE) {
2159 device_links_write_lock();
2160 if (__fw_devlink_relax_cycles(con, sup_handle)) {
2161 __fwnode_link_cycle(link);
2162 flags = fw_devlink_get_flags(link->flags);
2163 pr_debug("----- cycle: end -----\n");
2164 dev_info(con, "Fixed dependency cycle(s) with %pfwf\n",
2167 device_links_write_unlock();
2170 if (sup_handle->flags & FWNODE_FLAG_NOT_DEVICE)
2171 sup_dev = fwnode_get_next_parent_dev(sup_handle);
2173 sup_dev = get_dev_from_fwnode(sup_handle);
2177 * If it's one of those drivers that don't actually bind to
2178 * their device using driver core, then don't wait on this
2179 * supplier device indefinitely.
2181 if (sup_dev->links.status == DL_DEV_NO_DRIVER &&
2182 sup_handle->flags & FWNODE_FLAG_INITIALIZED) {
2184 "Not linking %pfwf - dev might never probe\n",
2190 if (con != sup_dev && !device_link_add(con, sup_dev, flags)) {
2191 dev_err(con, "Failed to create device link (0x%x) with %s\n",
2192 flags, dev_name(sup_dev));
2200 * Supplier or supplier's ancestor already initialized without a struct
2201 * device or being probed by a driver.
2203 if (fwnode_init_without_drv(sup_handle) ||
2204 fwnode_ancestor_init_without_drv(sup_handle)) {
2205 dev_dbg(con, "Not linking %pfwf - might never become dev\n",
2212 put_device(sup_dev);
2217 * __fw_devlink_link_to_consumers - Create device links to consumers of a device
2218 * @dev: Device that needs to be linked to its consumers
2220 * This function looks at all the consumer fwnodes of @dev and creates device
2221 * links between the consumer device and @dev (supplier).
2223 * If the consumer device has not been added yet, then this function creates a
2224 * SYNC_STATE_ONLY link between @dev (supplier) and the closest ancestor device
2225 * of the consumer fwnode. This is necessary to make sure @dev doesn't get a
2226 * sync_state() callback before the real consumer device gets to be added and
2229 * Once device links are created from the real consumer to @dev (supplier), the
2230 * fwnode links are deleted.
2232 static void __fw_devlink_link_to_consumers(struct device *dev)
2234 struct fwnode_handle *fwnode = dev->fwnode;
2235 struct fwnode_link *link, *tmp;
2237 list_for_each_entry_safe(link, tmp, &fwnode->consumers, s_hook) {
2238 struct device *con_dev;
2239 bool own_link = true;
2242 con_dev = get_dev_from_fwnode(link->consumer);
2244 * If consumer device is not available yet, make a "proxy"
2245 * SYNC_STATE_ONLY link from the consumer's parent device to
2246 * the supplier device. This is necessary to make sure the
2247 * supplier doesn't get a sync_state() callback before the real
2248 * consumer can create a device link to the supplier.
2250 * This proxy link step is needed to handle the case where the
2251 * consumer's parent device is added before the supplier.
2254 con_dev = fwnode_get_next_parent_dev(link->consumer);
2256 * However, if the consumer's parent device is also the
2257 * parent of the supplier, don't create a
2258 * consumer-supplier link from the parent to its child
2259 * device. Such a dependency is impossible.
2262 fwnode_is_ancestor_of(con_dev->fwnode, fwnode)) {
2263 put_device(con_dev);
2273 ret = fw_devlink_create_devlink(con_dev, fwnode, link);
2274 put_device(con_dev);
2275 if (!own_link || ret == -EAGAIN)
2278 __fwnode_link_del(link);
2283 * __fw_devlink_link_to_suppliers - Create device links to suppliers of a device
2284 * @dev: The consumer device that needs to be linked to its suppliers
2285 * @fwnode: Root of the fwnode tree that is used to create device links
2287 * This function looks at all the supplier fwnodes of fwnode tree rooted at
2288 * @fwnode and creates device links between @dev (consumer) and all the
2289 * supplier devices of the entire fwnode tree at @fwnode.
2291 * The function creates normal (non-SYNC_STATE_ONLY) device links between @dev
2292 * and the real suppliers of @dev. Once these device links are created, the
2293 * fwnode links are deleted.
2295 * In addition, it also looks at all the suppliers of the entire fwnode tree
2296 * because some of the child devices of @dev that have not been added yet
2297 * (because @dev hasn't probed) might already have their suppliers added to
2298 * driver core. So, this function creates SYNC_STATE_ONLY device links between
2299 * @dev (consumer) and these suppliers to make sure they don't execute their
2300 * sync_state() callbacks before these child devices have a chance to create
2301 * their device links. The fwnode links that correspond to the child devices
2302 * aren't delete because they are needed later to create the device links
2303 * between the real consumer and supplier devices.
2305 static void __fw_devlink_link_to_suppliers(struct device *dev,
2306 struct fwnode_handle *fwnode)
2308 bool own_link = (dev->fwnode == fwnode);
2309 struct fwnode_link *link, *tmp;
2310 struct fwnode_handle *child = NULL;
2312 list_for_each_entry_safe(link, tmp, &fwnode->suppliers, c_hook) {
2314 struct fwnode_handle *sup = link->supplier;
2316 ret = fw_devlink_create_devlink(dev, sup, link);
2317 if (!own_link || ret == -EAGAIN)
2320 __fwnode_link_del(link);
2324 * Make "proxy" SYNC_STATE_ONLY device links to represent the needs of
2325 * all the descendants. This proxy link step is needed to handle the
2326 * case where the supplier is added before the consumer's parent device
2329 while ((child = fwnode_get_next_available_child_node(fwnode, child)))
2330 __fw_devlink_link_to_suppliers(dev, child);
2333 static void fw_devlink_link_device(struct device *dev)
2335 struct fwnode_handle *fwnode = dev->fwnode;
2337 if (!fw_devlink_flags)
2340 fw_devlink_parse_fwtree(fwnode);
2342 mutex_lock(&fwnode_link_lock);
2343 __fw_devlink_link_to_consumers(dev);
2344 __fw_devlink_link_to_suppliers(dev, fwnode);
2345 mutex_unlock(&fwnode_link_lock);
2348 /* Device links support end. */
2350 static struct kobject *dev_kobj;
2353 static struct kobject *sysfs_dev_char_kobj;
2355 /* /sys/dev/block */
2356 static struct kobject *sysfs_dev_block_kobj;
2358 static DEFINE_MUTEX(device_hotplug_lock);
2360 void lock_device_hotplug(void)
2362 mutex_lock(&device_hotplug_lock);
2365 void unlock_device_hotplug(void)
2367 mutex_unlock(&device_hotplug_lock);
2370 int lock_device_hotplug_sysfs(void)
2372 if (mutex_trylock(&device_hotplug_lock))
2375 /* Avoid busy looping (5 ms of sleep should do). */
2377 return restart_syscall();
2381 static inline int device_is_not_partition(struct device *dev)
2383 return !(dev->type == &part_type);
2386 static inline int device_is_not_partition(struct device *dev)
2392 static void device_platform_notify(struct device *dev)
2394 acpi_device_notify(dev);
2396 software_node_notify(dev);
2399 static void device_platform_notify_remove(struct device *dev)
2401 software_node_notify_remove(dev);
2403 acpi_device_notify_remove(dev);
2407 * dev_driver_string - Return a device's driver name, if at all possible
2408 * @dev: struct device to get the name of
2410 * Will return the device's driver's name if it is bound to a device. If
2411 * the device is not bound to a driver, it will return the name of the bus
2412 * it is attached to. If it is not attached to a bus either, an empty
2413 * string will be returned.
2415 const char *dev_driver_string(const struct device *dev)
2417 struct device_driver *drv;
2419 /* dev->driver can change to NULL underneath us because of unbinding,
2420 * so be careful about accessing it. dev->bus and dev->class should
2421 * never change once they are set, so they don't need special care.
2423 drv = READ_ONCE(dev->driver);
2424 return drv ? drv->name : dev_bus_name(dev);
2426 EXPORT_SYMBOL(dev_driver_string);
2428 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
2430 static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
2433 struct device_attribute *dev_attr = to_dev_attr(attr);
2434 struct device *dev = kobj_to_dev(kobj);
2438 ret = dev_attr->show(dev, dev_attr, buf);
2439 if (ret >= (ssize_t)PAGE_SIZE) {
2440 printk("dev_attr_show: %pS returned bad count\n",
2446 static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
2447 const char *buf, size_t count)
2449 struct device_attribute *dev_attr = to_dev_attr(attr);
2450 struct device *dev = kobj_to_dev(kobj);
2453 if (dev_attr->store)
2454 ret = dev_attr->store(dev, dev_attr, buf, count);
2458 static const struct sysfs_ops dev_sysfs_ops = {
2459 .show = dev_attr_show,
2460 .store = dev_attr_store,
2463 #define to_ext_attr(x) container_of(x, struct dev_ext_attribute, attr)
2465 ssize_t device_store_ulong(struct device *dev,
2466 struct device_attribute *attr,
2467 const char *buf, size_t size)
2469 struct dev_ext_attribute *ea = to_ext_attr(attr);
2473 ret = kstrtoul(buf, 0, &new);
2476 *(unsigned long *)(ea->var) = new;
2477 /* Always return full write size even if we didn't consume all */
2480 EXPORT_SYMBOL_GPL(device_store_ulong);
2482 ssize_t device_show_ulong(struct device *dev,
2483 struct device_attribute *attr,
2486 struct dev_ext_attribute *ea = to_ext_attr(attr);
2487 return sysfs_emit(buf, "%lx\n", *(unsigned long *)(ea->var));
2489 EXPORT_SYMBOL_GPL(device_show_ulong);
2491 ssize_t device_store_int(struct device *dev,
2492 struct device_attribute *attr,
2493 const char *buf, size_t size)
2495 struct dev_ext_attribute *ea = to_ext_attr(attr);
2499 ret = kstrtol(buf, 0, &new);
2503 if (new > INT_MAX || new < INT_MIN)
2505 *(int *)(ea->var) = new;
2506 /* Always return full write size even if we didn't consume all */
2509 EXPORT_SYMBOL_GPL(device_store_int);
2511 ssize_t device_show_int(struct device *dev,
2512 struct device_attribute *attr,
2515 struct dev_ext_attribute *ea = to_ext_attr(attr);
2517 return sysfs_emit(buf, "%d\n", *(int *)(ea->var));
2519 EXPORT_SYMBOL_GPL(device_show_int);
2521 ssize_t device_store_bool(struct device *dev, struct device_attribute *attr,
2522 const char *buf, size_t size)
2524 struct dev_ext_attribute *ea = to_ext_attr(attr);
2526 if (kstrtobool(buf, ea->var) < 0)
2531 EXPORT_SYMBOL_GPL(device_store_bool);
2533 ssize_t device_show_bool(struct device *dev, struct device_attribute *attr,
2536 struct dev_ext_attribute *ea = to_ext_attr(attr);
2538 return sysfs_emit(buf, "%d\n", *(bool *)(ea->var));
2540 EXPORT_SYMBOL_GPL(device_show_bool);
2542 ssize_t device_show_string(struct device *dev,
2543 struct device_attribute *attr, char *buf)
2545 struct dev_ext_attribute *ea = to_ext_attr(attr);
2547 return sysfs_emit(buf, "%s\n", (char *)ea->var);
2549 EXPORT_SYMBOL_GPL(device_show_string);
2552 * device_release - free device structure.
2553 * @kobj: device's kobject.
2555 * This is called once the reference count for the object
2556 * reaches 0. We forward the call to the device's release
2557 * method, which should handle actually freeing the structure.
2559 static void device_release(struct kobject *kobj)
2561 struct device *dev = kobj_to_dev(kobj);
2562 struct device_private *p = dev->p;
2565 * Some platform devices are driven without driver attached
2566 * and managed resources may have been acquired. Make sure
2567 * all resources are released.
2569 * Drivers still can add resources into device after device
2570 * is deleted but alive, so release devres here to avoid
2571 * possible memory leak.
2573 devres_release_all(dev);
2575 kfree(dev->dma_range_map);
2579 else if (dev->type && dev->type->release)
2580 dev->type->release(dev);
2581 else if (dev->class && dev->class->dev_release)
2582 dev->class->dev_release(dev);
2584 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",
2589 static const void *device_namespace(const struct kobject *kobj)
2591 const struct device *dev = kobj_to_dev(kobj);
2592 const void *ns = NULL;
2594 if (dev->class && dev->class->ns_type)
2595 ns = dev->class->namespace(dev);
2600 static void device_get_ownership(const struct kobject *kobj, kuid_t *uid, kgid_t *gid)
2602 const struct device *dev = kobj_to_dev(kobj);
2604 if (dev->class && dev->class->get_ownership)
2605 dev->class->get_ownership(dev, uid, gid);
2608 static const struct kobj_type device_ktype = {
2609 .release = device_release,
2610 .sysfs_ops = &dev_sysfs_ops,
2611 .namespace = device_namespace,
2612 .get_ownership = device_get_ownership,
2616 static int dev_uevent_filter(const struct kobject *kobj)
2618 const struct kobj_type *ktype = get_ktype(kobj);
2620 if (ktype == &device_ktype) {
2621 const struct device *dev = kobj_to_dev(kobj);
2630 static const char *dev_uevent_name(const struct kobject *kobj)
2632 const struct device *dev = kobj_to_dev(kobj);
2635 return dev->bus->name;
2637 return dev->class->name;
2641 static int dev_uevent(const struct kobject *kobj, struct kobj_uevent_env *env)
2643 const struct device *dev = kobj_to_dev(kobj);
2644 struct device_driver *driver;
2647 /* add device node properties if present */
2648 if (MAJOR(dev->devt)) {
2652 kuid_t uid = GLOBAL_ROOT_UID;
2653 kgid_t gid = GLOBAL_ROOT_GID;
2655 add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt));
2656 add_uevent_var(env, "MINOR=%u", MINOR(dev->devt));
2657 name = device_get_devnode(dev, &mode, &uid, &gid, &tmp);
2659 add_uevent_var(env, "DEVNAME=%s", name);
2661 add_uevent_var(env, "DEVMODE=%#o", mode & 0777);
2662 if (!uid_eq(uid, GLOBAL_ROOT_UID))
2663 add_uevent_var(env, "DEVUID=%u", from_kuid(&init_user_ns, uid));
2664 if (!gid_eq(gid, GLOBAL_ROOT_GID))
2665 add_uevent_var(env, "DEVGID=%u", from_kgid(&init_user_ns, gid));
2670 if (dev->type && dev->type->name)
2671 add_uevent_var(env, "DEVTYPE=%s", dev->type->name);
2673 /* Synchronize with module_remove_driver() */
2675 driver = READ_ONCE(dev->driver);
2677 add_uevent_var(env, "DRIVER=%s", driver->name);
2680 /* Add common DT information about the device */
2681 of_device_uevent(dev, env);
2683 /* have the bus specific function add its stuff */
2684 if (dev->bus && dev->bus->uevent) {
2685 retval = dev->bus->uevent(dev, env);
2687 pr_debug("device: '%s': %s: bus uevent() returned %d\n",
2688 dev_name(dev), __func__, retval);
2691 /* have the class specific function add its stuff */
2692 if (dev->class && dev->class->dev_uevent) {
2693 retval = dev->class->dev_uevent(dev, env);
2695 pr_debug("device: '%s': %s: class uevent() "
2696 "returned %d\n", dev_name(dev),
2700 /* have the device type specific function add its stuff */
2701 if (dev->type && dev->type->uevent) {
2702 retval = dev->type->uevent(dev, env);
2704 pr_debug("device: '%s': %s: dev_type uevent() "
2705 "returned %d\n", dev_name(dev),
2712 static const struct kset_uevent_ops device_uevent_ops = {
2713 .filter = dev_uevent_filter,
2714 .name = dev_uevent_name,
2715 .uevent = dev_uevent,
2718 static ssize_t uevent_show(struct device *dev, struct device_attribute *attr,
2721 struct kobject *top_kobj;
2723 struct kobj_uevent_env *env = NULL;
2728 /* search the kset, the device belongs to */
2729 top_kobj = &dev->kobj;
2730 while (!top_kobj->kset && top_kobj->parent)
2731 top_kobj = top_kobj->parent;
2732 if (!top_kobj->kset)
2735 kset = top_kobj->kset;
2736 if (!kset->uevent_ops || !kset->uevent_ops->uevent)
2739 /* respect filter */
2740 if (kset->uevent_ops && kset->uevent_ops->filter)
2741 if (!kset->uevent_ops->filter(&dev->kobj))
2744 env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
2748 /* let the kset specific function add its keys */
2749 retval = kset->uevent_ops->uevent(&dev->kobj, env);
2753 /* copy keys to file */
2754 for (i = 0; i < env->envp_idx; i++)
2755 len += sysfs_emit_at(buf, len, "%s\n", env->envp[i]);
2761 static ssize_t uevent_store(struct device *dev, struct device_attribute *attr,
2762 const char *buf, size_t count)
2766 rc = kobject_synth_uevent(&dev->kobj, buf, count);
2769 dev_err(dev, "uevent: failed to send synthetic uevent: %d\n", rc);
2775 static DEVICE_ATTR_RW(uevent);
2777 static ssize_t online_show(struct device *dev, struct device_attribute *attr,
2783 val = !dev->offline;
2785 return sysfs_emit(buf, "%u\n", val);
2788 static ssize_t online_store(struct device *dev, struct device_attribute *attr,
2789 const char *buf, size_t count)
2794 ret = kstrtobool(buf, &val);
2798 ret = lock_device_hotplug_sysfs();
2802 ret = val ? device_online(dev) : device_offline(dev);
2803 unlock_device_hotplug();
2804 return ret < 0 ? ret : count;
2806 static DEVICE_ATTR_RW(online);
2808 static ssize_t removable_show(struct device *dev, struct device_attribute *attr,
2813 switch (dev->removable) {
2814 case DEVICE_REMOVABLE:
2823 return sysfs_emit(buf, "%s\n", loc);
2825 static DEVICE_ATTR_RO(removable);
2827 int device_add_groups(struct device *dev, const struct attribute_group **groups)
2829 return sysfs_create_groups(&dev->kobj, groups);
2831 EXPORT_SYMBOL_GPL(device_add_groups);
2833 void device_remove_groups(struct device *dev,
2834 const struct attribute_group **groups)
2836 sysfs_remove_groups(&dev->kobj, groups);
2838 EXPORT_SYMBOL_GPL(device_remove_groups);
2840 union device_attr_group_devres {
2841 const struct attribute_group *group;
2842 const struct attribute_group **groups;
2845 static void devm_attr_group_remove(struct device *dev, void *res)
2847 union device_attr_group_devres *devres = res;
2848 const struct attribute_group *group = devres->group;
2850 dev_dbg(dev, "%s: removing group %p\n", __func__, group);
2851 sysfs_remove_group(&dev->kobj, group);
2855 * devm_device_add_group - given a device, create a managed attribute group
2856 * @dev: The device to create the group for
2857 * @grp: The attribute group to create
2859 * This function creates a group for the first time. It will explicitly
2860 * warn and error if any of the attribute files being created already exist.
2862 * Returns 0 on success or error code on failure.
2864 int devm_device_add_group(struct device *dev, const struct attribute_group *grp)
2866 union device_attr_group_devres *devres;
2869 devres = devres_alloc(devm_attr_group_remove,
2870 sizeof(*devres), GFP_KERNEL);
2874 error = sysfs_create_group(&dev->kobj, grp);
2876 devres_free(devres);
2880 devres->group = grp;
2881 devres_add(dev, devres);
2884 EXPORT_SYMBOL_GPL(devm_device_add_group);
2886 static int device_add_attrs(struct device *dev)
2888 const struct class *class = dev->class;
2889 const struct device_type *type = dev->type;
2893 error = device_add_groups(dev, class->dev_groups);
2899 error = device_add_groups(dev, type->groups);
2901 goto err_remove_class_groups;
2904 error = device_add_groups(dev, dev->groups);
2906 goto err_remove_type_groups;
2908 if (device_supports_offline(dev) && !dev->offline_disabled) {
2909 error = device_create_file(dev, &dev_attr_online);
2911 goto err_remove_dev_groups;
2914 if (fw_devlink_flags && !fw_devlink_is_permissive() && dev->fwnode) {
2915 error = device_create_file(dev, &dev_attr_waiting_for_supplier);
2917 goto err_remove_dev_online;
2920 if (dev_removable_is_valid(dev)) {
2921 error = device_create_file(dev, &dev_attr_removable);
2923 goto err_remove_dev_waiting_for_supplier;
2926 if (dev_add_physical_location(dev)) {
2927 error = device_add_group(dev,
2928 &dev_attr_physical_location_group);
2930 goto err_remove_dev_removable;
2935 err_remove_dev_removable:
2936 device_remove_file(dev, &dev_attr_removable);
2937 err_remove_dev_waiting_for_supplier:
2938 device_remove_file(dev, &dev_attr_waiting_for_supplier);
2939 err_remove_dev_online:
2940 device_remove_file(dev, &dev_attr_online);
2941 err_remove_dev_groups:
2942 device_remove_groups(dev, dev->groups);
2943 err_remove_type_groups:
2945 device_remove_groups(dev, type->groups);
2946 err_remove_class_groups:
2948 device_remove_groups(dev, class->dev_groups);
2953 static void device_remove_attrs(struct device *dev)
2955 const struct class *class = dev->class;
2956 const struct device_type *type = dev->type;
2958 if (dev->physical_location) {
2959 device_remove_group(dev, &dev_attr_physical_location_group);
2960 kfree(dev->physical_location);
2963 device_remove_file(dev, &dev_attr_removable);
2964 device_remove_file(dev, &dev_attr_waiting_for_supplier);
2965 device_remove_file(dev, &dev_attr_online);
2966 device_remove_groups(dev, dev->groups);
2969 device_remove_groups(dev, type->groups);
2972 device_remove_groups(dev, class->dev_groups);
2975 static ssize_t dev_show(struct device *dev, struct device_attribute *attr,
2978 return print_dev_t(buf, dev->devt);
2980 static DEVICE_ATTR_RO(dev);
2983 struct kset *devices_kset;
2986 * devices_kset_move_before - Move device in the devices_kset's list.
2987 * @deva: Device to move.
2988 * @devb: Device @deva should come before.
2990 static void devices_kset_move_before(struct device *deva, struct device *devb)
2994 pr_debug("devices_kset: Moving %s before %s\n",
2995 dev_name(deva), dev_name(devb));
2996 spin_lock(&devices_kset->list_lock);
2997 list_move_tail(&deva->kobj.entry, &devb->kobj.entry);
2998 spin_unlock(&devices_kset->list_lock);
3002 * devices_kset_move_after - Move device in the devices_kset's list.
3003 * @deva: Device to move
3004 * @devb: Device @deva should come after.
3006 static void devices_kset_move_after(struct device *deva, struct device *devb)
3010 pr_debug("devices_kset: Moving %s after %s\n",
3011 dev_name(deva), dev_name(devb));
3012 spin_lock(&devices_kset->list_lock);
3013 list_move(&deva->kobj.entry, &devb->kobj.entry);
3014 spin_unlock(&devices_kset->list_lock);
3018 * devices_kset_move_last - move the device to the end of devices_kset's list.
3019 * @dev: device to move
3021 void devices_kset_move_last(struct device *dev)
3025 pr_debug("devices_kset: Moving %s to end of list\n", dev_name(dev));
3026 spin_lock(&devices_kset->list_lock);
3027 list_move_tail(&dev->kobj.entry, &devices_kset->list);
3028 spin_unlock(&devices_kset->list_lock);
3032 * device_create_file - create sysfs attribute file for device.
3034 * @attr: device attribute descriptor.
3036 int device_create_file(struct device *dev,
3037 const struct device_attribute *attr)
3042 WARN(((attr->attr.mode & S_IWUGO) && !attr->store),
3043 "Attribute %s: write permission without 'store'\n",
3045 WARN(((attr->attr.mode & S_IRUGO) && !attr->show),
3046 "Attribute %s: read permission without 'show'\n",
3048 error = sysfs_create_file(&dev->kobj, &attr->attr);
3053 EXPORT_SYMBOL_GPL(device_create_file);
3056 * device_remove_file - remove sysfs attribute file.
3058 * @attr: device attribute descriptor.
3060 void device_remove_file(struct device *dev,
3061 const struct device_attribute *attr)
3064 sysfs_remove_file(&dev->kobj, &attr->attr);
3066 EXPORT_SYMBOL_GPL(device_remove_file);
3069 * device_remove_file_self - remove sysfs attribute file from its own method.
3071 * @attr: device attribute descriptor.
3073 * See kernfs_remove_self() for details.
3075 bool device_remove_file_self(struct device *dev,
3076 const struct device_attribute *attr)
3079 return sysfs_remove_file_self(&dev->kobj, &attr->attr);
3083 EXPORT_SYMBOL_GPL(device_remove_file_self);
3086 * device_create_bin_file - create sysfs binary attribute file for device.
3088 * @attr: device binary attribute descriptor.
3090 int device_create_bin_file(struct device *dev,
3091 const struct bin_attribute *attr)
3093 int error = -EINVAL;
3095 error = sysfs_create_bin_file(&dev->kobj, attr);
3098 EXPORT_SYMBOL_GPL(device_create_bin_file);
3101 * device_remove_bin_file - remove sysfs binary attribute file
3103 * @attr: device binary attribute descriptor.
3105 void device_remove_bin_file(struct device *dev,
3106 const struct bin_attribute *attr)
3109 sysfs_remove_bin_file(&dev->kobj, attr);
3111 EXPORT_SYMBOL_GPL(device_remove_bin_file);
3113 static void klist_children_get(struct klist_node *n)
3115 struct device_private *p = to_device_private_parent(n);
3116 struct device *dev = p->device;
3121 static void klist_children_put(struct klist_node *n)
3123 struct device_private *p = to_device_private_parent(n);
3124 struct device *dev = p->device;
3130 * device_initialize - init device structure.
3133 * This prepares the device for use by other layers by initializing
3135 * It is the first half of device_register(), if called by
3136 * that function, though it can also be called separately, so one
3137 * may use @dev's fields. In particular, get_device()/put_device()
3138 * may be used for reference counting of @dev after calling this
3141 * All fields in @dev must be initialized by the caller to 0, except
3142 * for those explicitly set to some other value. The simplest
3143 * approach is to use kzalloc() to allocate the structure containing
3146 * NOTE: Use put_device() to give up your reference instead of freeing
3147 * @dev directly once you have called this function.
3149 void device_initialize(struct device *dev)
3151 dev->kobj.kset = devices_kset;
3152 kobject_init(&dev->kobj, &device_ktype);
3153 INIT_LIST_HEAD(&dev->dma_pools);
3154 mutex_init(&dev->mutex);
3155 lockdep_set_novalidate_class(&dev->mutex);
3156 spin_lock_init(&dev->devres_lock);
3157 INIT_LIST_HEAD(&dev->devres_head);
3158 device_pm_init(dev);
3159 set_dev_node(dev, NUMA_NO_NODE);
3160 INIT_LIST_HEAD(&dev->links.consumers);
3161 INIT_LIST_HEAD(&dev->links.suppliers);
3162 INIT_LIST_HEAD(&dev->links.defer_sync);
3163 dev->links.status = DL_DEV_NO_DRIVER;
3164 #if defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_DEVICE) || \
3165 defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_CPU) || \
3166 defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_CPU_ALL)
3167 dev->dma_coherent = dma_default_coherent;
3169 swiotlb_dev_init(dev);
3171 EXPORT_SYMBOL_GPL(device_initialize);
3173 struct kobject *virtual_device_parent(struct device *dev)
3175 static struct kobject *virtual_dir = NULL;
3178 virtual_dir = kobject_create_and_add("virtual",
3179 &devices_kset->kobj);
3185 struct kobject kobj;
3186 const struct class *class;
3189 #define to_class_dir(obj) container_of(obj, struct class_dir, kobj)
3191 static void class_dir_release(struct kobject *kobj)
3193 struct class_dir *dir = to_class_dir(kobj);
3198 struct kobj_ns_type_operations *class_dir_child_ns_type(const struct kobject *kobj)
3200 const struct class_dir *dir = to_class_dir(kobj);
3201 return dir->class->ns_type;
3204 static const struct kobj_type class_dir_ktype = {
3205 .release = class_dir_release,
3206 .sysfs_ops = &kobj_sysfs_ops,
3207 .child_ns_type = class_dir_child_ns_type
3210 static struct kobject *class_dir_create_and_add(struct subsys_private *sp,
3211 struct kobject *parent_kobj)
3213 struct class_dir *dir;
3216 dir = kzalloc(sizeof(*dir), GFP_KERNEL);
3218 return ERR_PTR(-ENOMEM);
3220 dir->class = sp->class;
3221 kobject_init(&dir->kobj, &class_dir_ktype);
3223 dir->kobj.kset = &sp->glue_dirs;
3225 retval = kobject_add(&dir->kobj, parent_kobj, "%s", sp->class->name);
3227 kobject_put(&dir->kobj);
3228 return ERR_PTR(retval);
3233 static DEFINE_MUTEX(gdp_mutex);
3235 static struct kobject *get_device_parent(struct device *dev,
3236 struct device *parent)
3238 struct subsys_private *sp = class_to_subsys(dev->class);
3239 struct kobject *kobj = NULL;
3242 struct kobject *parent_kobj;
3246 * If we have no parent, we live in "virtual".
3247 * Class-devices with a non class-device as parent, live
3248 * in a "glue" directory to prevent namespace collisions.
3251 parent_kobj = virtual_device_parent(dev);
3252 else if (parent->class && !dev->class->ns_type) {
3254 return &parent->kobj;
3256 parent_kobj = &parent->kobj;
3259 mutex_lock(&gdp_mutex);
3261 /* find our class-directory at the parent and reference it */
3262 spin_lock(&sp->glue_dirs.list_lock);
3263 list_for_each_entry(k, &sp->glue_dirs.list, entry)
3264 if (k->parent == parent_kobj) {
3265 kobj = kobject_get(k);
3268 spin_unlock(&sp->glue_dirs.list_lock);
3270 mutex_unlock(&gdp_mutex);
3275 /* or create a new class-directory at the parent device */
3276 k = class_dir_create_and_add(sp, parent_kobj);
3277 /* do not emit an uevent for this simple "glue" directory */
3278 mutex_unlock(&gdp_mutex);
3283 /* subsystems can specify a default root directory for their devices */
3284 if (!parent && dev->bus) {
3285 struct device *dev_root = bus_get_dev_root(dev->bus);
3288 kobj = &dev_root->kobj;
3289 put_device(dev_root);
3295 return &parent->kobj;
3299 static inline bool live_in_glue_dir(struct kobject *kobj,
3302 struct subsys_private *sp;
3305 if (!kobj || !dev->class)
3308 sp = class_to_subsys(dev->class);
3312 if (kobj->kset == &sp->glue_dirs)
3321 static inline struct kobject *get_glue_dir(struct device *dev)
3323 return dev->kobj.parent;
3327 * kobject_has_children - Returns whether a kobject has children.
3328 * @kobj: the object to test
3330 * This will return whether a kobject has other kobjects as children.
3332 * It does NOT account for the presence of attribute files, only sub
3333 * directories. It also assumes there is no concurrent addition or
3334 * removal of such children, and thus relies on external locking.
3336 static inline bool kobject_has_children(struct kobject *kobj)
3338 WARN_ON_ONCE(kref_read(&kobj->kref) == 0);
3340 return kobj->sd && kobj->sd->dir.subdirs;
3344 * make sure cleaning up dir as the last step, we need to make
3345 * sure .release handler of kobject is run with holding the
3348 static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir)
3352 /* see if we live in a "glue" directory */
3353 if (!live_in_glue_dir(glue_dir, dev))
3356 mutex_lock(&gdp_mutex);
3358 * There is a race condition between removing glue directory
3359 * and adding a new device under the glue directory.
3364 * get_device_parent()
3365 * class_dir_create_and_add()
3366 * kobject_add_internal()
3367 * create_dir() // create glue_dir
3370 * get_device_parent()
3371 * kobject_get() // get glue_dir
3374 * cleanup_glue_dir()
3375 * kobject_del(glue_dir)
3378 * kobject_add_internal()
3379 * create_dir() // in glue_dir
3380 * sysfs_create_dir_ns()
3381 * kernfs_create_dir_ns(sd)
3383 * sysfs_remove_dir() // glue_dir->sd=NULL
3384 * sysfs_put() // free glue_dir->sd
3387 * kernfs_new_node(sd)
3388 * kernfs_get(glue_dir)
3392 * Before CPU1 remove last child device under glue dir, if CPU2 add
3393 * a new device under glue dir, the glue_dir kobject reference count
3394 * will be increase to 2 in kobject_get(k). And CPU2 has been called
3395 * kernfs_create_dir_ns(). Meanwhile, CPU1 call sysfs_remove_dir()
3396 * and sysfs_put(). This result in glue_dir->sd is freed.
3398 * Then the CPU2 will see a stale "empty" but still potentially used
3399 * glue dir around in kernfs_new_node().
3401 * In order to avoid this happening, we also should make sure that
3402 * kernfs_node for glue_dir is released in CPU1 only when refcount
3403 * for glue_dir kobj is 1.
3405 ref = kref_read(&glue_dir->kref);
3406 if (!kobject_has_children(glue_dir) && !--ref)
3407 kobject_del(glue_dir);
3408 kobject_put(glue_dir);
3409 mutex_unlock(&gdp_mutex);
3412 static int device_add_class_symlinks(struct device *dev)
3414 struct device_node *of_node = dev_of_node(dev);
3415 struct subsys_private *sp;
3419 error = sysfs_create_link(&dev->kobj, of_node_kobj(of_node), "of_node");
3421 dev_warn(dev, "Error %d creating of_node link\n",error);
3422 /* An error here doesn't warrant bringing down the device */
3425 sp = class_to_subsys(dev->class);
3429 error = sysfs_create_link(&dev->kobj, &sp->subsys.kobj, "subsystem");
3433 if (dev->parent && device_is_not_partition(dev)) {
3434 error = sysfs_create_link(&dev->kobj, &dev->parent->kobj,
3440 /* link in the class directory pointing to the device */
3441 error = sysfs_create_link(&sp->subsys.kobj, &dev->kobj, dev_name(dev));
3447 sysfs_remove_link(&dev->kobj, "device");
3449 sysfs_remove_link(&dev->kobj, "subsystem");
3451 sysfs_remove_link(&dev->kobj, "of_node");
3457 static void device_remove_class_symlinks(struct device *dev)
3459 struct subsys_private *sp = class_to_subsys(dev->class);
3461 if (dev_of_node(dev))
3462 sysfs_remove_link(&dev->kobj, "of_node");
3467 if (dev->parent && device_is_not_partition(dev))
3468 sysfs_remove_link(&dev->kobj, "device");
3469 sysfs_remove_link(&dev->kobj, "subsystem");
3470 sysfs_delete_link(&sp->subsys.kobj, &dev->kobj, dev_name(dev));
3475 * dev_set_name - set a device name
3477 * @fmt: format string for the device's name
3479 int dev_set_name(struct device *dev, const char *fmt, ...)
3484 va_start(vargs, fmt);
3485 err = kobject_set_name_vargs(&dev->kobj, fmt, vargs);
3489 EXPORT_SYMBOL_GPL(dev_set_name);
3491 /* select a /sys/dev/ directory for the device */
3492 static struct kobject *device_to_dev_kobj(struct device *dev)
3494 if (is_blockdev(dev))
3495 return sysfs_dev_block_kobj;
3497 return sysfs_dev_char_kobj;
3500 static int device_create_sys_dev_entry(struct device *dev)
3502 struct kobject *kobj = device_to_dev_kobj(dev);
3507 format_dev_t(devt_str, dev->devt);
3508 error = sysfs_create_link(kobj, &dev->kobj, devt_str);
3514 static void device_remove_sys_dev_entry(struct device *dev)
3516 struct kobject *kobj = device_to_dev_kobj(dev);
3520 format_dev_t(devt_str, dev->devt);
3521 sysfs_remove_link(kobj, devt_str);
3525 static int device_private_init(struct device *dev)
3527 dev->p = kzalloc(sizeof(*dev->p), GFP_KERNEL);
3530 dev->p->device = dev;
3531 klist_init(&dev->p->klist_children, klist_children_get,
3532 klist_children_put);
3533 INIT_LIST_HEAD(&dev->p->deferred_probe);
3538 * device_add - add device to device hierarchy.
3541 * This is part 2 of device_register(), though may be called
3542 * separately _iff_ device_initialize() has been called separately.
3544 * This adds @dev to the kobject hierarchy via kobject_add(), adds it
3545 * to the global and sibling lists for the device, then
3546 * adds it to the other relevant subsystems of the driver model.
3548 * Do not call this routine or device_register() more than once for
3549 * any device structure. The driver model core is not designed to work
3550 * with devices that get unregistered and then spring back to life.
3551 * (Among other things, it's very hard to guarantee that all references
3552 * to the previous incarnation of @dev have been dropped.) Allocate
3553 * and register a fresh new struct device instead.
3555 * NOTE: _Never_ directly free @dev after calling this function, even
3556 * if it returned an error! Always use put_device() to give up your
3557 * reference instead.
3559 * Rule of thumb is: if device_add() succeeds, you should call
3560 * device_del() when you want to get rid of it. If device_add() has
3561 * *not* succeeded, use *only* put_device() to drop the reference
3564 int device_add(struct device *dev)
3566 struct subsys_private *sp;
3567 struct device *parent;
3568 struct kobject *kobj;
3569 struct class_interface *class_intf;
3570 int error = -EINVAL;
3571 struct kobject *glue_dir = NULL;
3573 dev = get_device(dev);
3578 error = device_private_init(dev);
3584 * for statically allocated devices, which should all be converted
3585 * some day, we need to initialize the name. We prevent reading back
3586 * the name, and force the use of dev_name()
3588 if (dev->init_name) {
3589 error = dev_set_name(dev, "%s", dev->init_name);
3590 dev->init_name = NULL;
3595 /* subsystems can specify simple device enumeration */
3596 else if (dev->bus && dev->bus->dev_name)
3597 error = dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
3603 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3605 parent = get_device(dev->parent);
3606 kobj = get_device_parent(dev, parent);
3608 error = PTR_ERR(kobj);
3612 dev->kobj.parent = kobj;
3614 /* use parent numa_node */
3615 if (parent && (dev_to_node(dev) == NUMA_NO_NODE))
3616 set_dev_node(dev, dev_to_node(parent));
3618 /* first, register with generic layer. */
3619 /* we require the name to be set before, and pass NULL */
3620 error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
3626 /* notify platform of device entry */
3627 device_platform_notify(dev);
3629 error = device_create_file(dev, &dev_attr_uevent);
3633 error = device_add_class_symlinks(dev);
3636 error = device_add_attrs(dev);
3639 error = bus_add_device(dev);
3642 error = dpm_sysfs_add(dev);
3647 if (MAJOR(dev->devt)) {
3648 error = device_create_file(dev, &dev_attr_dev);
3652 error = device_create_sys_dev_entry(dev);
3656 devtmpfs_create_node(dev);
3659 /* Notify clients of device addition. This call must come
3660 * after dpm_sysfs_add() and before kobject_uevent().
3662 bus_notify(dev, BUS_NOTIFY_ADD_DEVICE);
3663 kobject_uevent(&dev->kobj, KOBJ_ADD);
3666 * Check if any of the other devices (consumers) have been waiting for
3667 * this device (supplier) to be added so that they can create a device
3670 * This needs to happen after device_pm_add() because device_link_add()
3671 * requires the supplier be registered before it's called.
3673 * But this also needs to happen before bus_probe_device() to make sure
3674 * waiting consumers can link to it before the driver is bound to the
3675 * device and the driver sync_state callback is called for this device.
3677 if (dev->fwnode && !dev->fwnode->dev) {
3678 dev->fwnode->dev = dev;
3679 fw_devlink_link_device(dev);
3682 bus_probe_device(dev);
3685 * If all driver registration is done and a newly added device doesn't
3686 * match with any driver, don't block its consumers from probing in
3687 * case the consumer device is able to operate without this supplier.
3689 if (dev->fwnode && fw_devlink_drv_reg_done && !dev->can_match)
3690 fw_devlink_unblock_consumers(dev);
3693 klist_add_tail(&dev->p->knode_parent,
3694 &parent->p->klist_children);
3696 sp = class_to_subsys(dev->class);
3698 mutex_lock(&sp->mutex);
3699 /* tie the class to the device */
3700 klist_add_tail(&dev->p->knode_class, &sp->klist_devices);
3702 /* notify any interfaces that the device is here */
3703 list_for_each_entry(class_intf, &sp->interfaces, node)
3704 if (class_intf->add_dev)
3705 class_intf->add_dev(dev);
3706 mutex_unlock(&sp->mutex);
3713 if (MAJOR(dev->devt))
3714 device_remove_file(dev, &dev_attr_dev);
3716 device_pm_remove(dev);
3717 dpm_sysfs_remove(dev);
3720 bus_remove_device(dev);
3722 device_remove_attrs(dev);
3724 device_remove_class_symlinks(dev);
3726 device_remove_file(dev, &dev_attr_uevent);
3728 device_platform_notify_remove(dev);
3729 kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3730 glue_dir = get_glue_dir(dev);
3731 kobject_del(&dev->kobj);
3733 cleanup_glue_dir(dev, glue_dir);
3741 EXPORT_SYMBOL_GPL(device_add);
3744 * device_register - register a device with the system.
3745 * @dev: pointer to the device structure
3747 * This happens in two clean steps - initialize the device
3748 * and add it to the system. The two steps can be called
3749 * separately, but this is the easiest and most common.
3750 * I.e. you should only call the two helpers separately if
3751 * have a clearly defined need to use and refcount the device
3752 * before it is added to the hierarchy.
3754 * For more information, see the kerneldoc for device_initialize()
3757 * NOTE: _Never_ directly free @dev after calling this function, even
3758 * if it returned an error! Always use put_device() to give up the
3759 * reference initialized in this function instead.
3761 int device_register(struct device *dev)
3763 device_initialize(dev);
3764 return device_add(dev);
3766 EXPORT_SYMBOL_GPL(device_register);
3769 * get_device - increment reference count for device.
3772 * This simply forwards the call to kobject_get(), though
3773 * we do take care to provide for the case that we get a NULL
3774 * pointer passed in.
3776 struct device *get_device(struct device *dev)
3778 return dev ? kobj_to_dev(kobject_get(&dev->kobj)) : NULL;
3780 EXPORT_SYMBOL_GPL(get_device);
3783 * put_device - decrement reference count.
3784 * @dev: device in question.
3786 void put_device(struct device *dev)
3788 /* might_sleep(); */
3790 kobject_put(&dev->kobj);
3792 EXPORT_SYMBOL_GPL(put_device);
3794 bool kill_device(struct device *dev)
3797 * Require the device lock and set the "dead" flag to guarantee that
3798 * the update behavior is consistent with the other bitfields near
3799 * it and that we cannot have an asynchronous probe routine trying
3800 * to run while we are tearing out the bus/class/sysfs from
3801 * underneath the device.
3803 device_lock_assert(dev);
3807 dev->p->dead = true;
3810 EXPORT_SYMBOL_GPL(kill_device);
3813 * device_del - delete device from system.
3816 * This is the first part of the device unregistration
3817 * sequence. This removes the device from the lists we control
3818 * from here, has it removed from the other driver model
3819 * subsystems it was added to in device_add(), and removes it
3820 * from the kobject hierarchy.
3822 * NOTE: this should be called manually _iff_ device_add() was
3823 * also called manually.
3825 void device_del(struct device *dev)
3827 struct subsys_private *sp;
3828 struct device *parent = dev->parent;
3829 struct kobject *glue_dir = NULL;
3830 struct class_interface *class_intf;
3831 unsigned int noio_flag;
3837 if (dev->fwnode && dev->fwnode->dev == dev)
3838 dev->fwnode->dev = NULL;
3840 /* Notify clients of device removal. This call must come
3841 * before dpm_sysfs_remove().
3843 noio_flag = memalloc_noio_save();
3844 bus_notify(dev, BUS_NOTIFY_DEL_DEVICE);
3846 dpm_sysfs_remove(dev);
3848 klist_del(&dev->p->knode_parent);
3849 if (MAJOR(dev->devt)) {
3850 devtmpfs_delete_node(dev);
3851 device_remove_sys_dev_entry(dev);
3852 device_remove_file(dev, &dev_attr_dev);
3855 sp = class_to_subsys(dev->class);
3857 device_remove_class_symlinks(dev);
3859 mutex_lock(&sp->mutex);
3860 /* notify any interfaces that the device is now gone */
3861 list_for_each_entry(class_intf, &sp->interfaces, node)
3862 if (class_intf->remove_dev)
3863 class_intf->remove_dev(dev);
3864 /* remove the device from the class list */
3865 klist_del(&dev->p->knode_class);
3866 mutex_unlock(&sp->mutex);
3869 device_remove_file(dev, &dev_attr_uevent);
3870 device_remove_attrs(dev);
3871 bus_remove_device(dev);
3872 device_pm_remove(dev);
3873 driver_deferred_probe_del(dev);
3874 device_platform_notify_remove(dev);
3875 device_links_purge(dev);
3878 * If a device does not have a driver attached, we need to clean
3879 * up any managed resources. We do this in device_release(), but
3880 * it's never called (and we leak the device) if a managed
3881 * resource holds a reference to the device. So release all
3882 * managed resources here, like we do in driver_detach(). We
3883 * still need to do so again in device_release() in case someone
3884 * adds a new resource after this point, though.
3886 devres_release_all(dev);
3888 bus_notify(dev, BUS_NOTIFY_REMOVED_DEVICE);
3889 kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3890 glue_dir = get_glue_dir(dev);
3891 kobject_del(&dev->kobj);
3892 cleanup_glue_dir(dev, glue_dir);
3893 memalloc_noio_restore(noio_flag);
3896 EXPORT_SYMBOL_GPL(device_del);
3899 * device_unregister - unregister device from system.
3900 * @dev: device going away.
3902 * We do this in two parts, like we do device_register(). First,
3903 * we remove it from all the subsystems with device_del(), then
3904 * we decrement the reference count via put_device(). If that
3905 * is the final reference count, the device will be cleaned up
3906 * via device_release() above. Otherwise, the structure will
3907 * stick around until the final reference to the device is dropped.
3909 void device_unregister(struct device *dev)
3911 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3915 EXPORT_SYMBOL_GPL(device_unregister);
3917 static struct device *prev_device(struct klist_iter *i)
3919 struct klist_node *n = klist_prev(i);
3920 struct device *dev = NULL;
3921 struct device_private *p;
3924 p = to_device_private_parent(n);
3930 static struct device *next_device(struct klist_iter *i)
3932 struct klist_node *n = klist_next(i);
3933 struct device *dev = NULL;
3934 struct device_private *p;
3937 p = to_device_private_parent(n);
3944 * device_get_devnode - path of device node file
3946 * @mode: returned file access mode
3947 * @uid: returned file owner
3948 * @gid: returned file group
3949 * @tmp: possibly allocated string
3951 * Return the relative path of a possible device node.
3952 * Non-default names may need to allocate a memory to compose
3953 * a name. This memory is returned in tmp and needs to be
3954 * freed by the caller.
3956 const char *device_get_devnode(const struct device *dev,
3957 umode_t *mode, kuid_t *uid, kgid_t *gid,
3964 /* the device type may provide a specific name */
3965 if (dev->type && dev->type->devnode)
3966 *tmp = dev->type->devnode(dev, mode, uid, gid);
3970 /* the class may provide a specific name */
3971 if (dev->class && dev->class->devnode)
3972 *tmp = dev->class->devnode(dev, mode);
3976 /* return name without allocation, tmp == NULL */
3977 if (strchr(dev_name(dev), '!') == NULL)
3978 return dev_name(dev);
3980 /* replace '!' in the name with '/' */
3981 s = kstrdup_and_replace(dev_name(dev), '!', '/', GFP_KERNEL);
3988 * device_for_each_child - device child iterator.
3989 * @parent: parent struct device.
3990 * @fn: function to be called for each device.
3991 * @data: data for the callback.
3993 * Iterate over @parent's child devices, and call @fn for each,
3996 * We check the return of @fn each time. If it returns anything
3997 * other than 0, we break out and return that value.
3999 int device_for_each_child(struct device *parent, void *data,
4000 int (*fn)(struct device *dev, void *data))
4002 struct klist_iter i;
4003 struct device *child;
4009 klist_iter_init(&parent->p->klist_children, &i);
4010 while (!error && (child = next_device(&i)))
4011 error = fn(child, data);
4012 klist_iter_exit(&i);
4015 EXPORT_SYMBOL_GPL(device_for_each_child);
4018 * device_for_each_child_reverse - device child iterator in reversed order.
4019 * @parent: parent struct device.
4020 * @fn: function to be called for each device.
4021 * @data: data for the callback.
4023 * Iterate over @parent's child devices, and call @fn for each,
4026 * We check the return of @fn each time. If it returns anything
4027 * other than 0, we break out and return that value.
4029 int device_for_each_child_reverse(struct device *parent, void *data,
4030 int (*fn)(struct device *dev, void *data))
4032 struct klist_iter i;
4033 struct device *child;
4039 klist_iter_init(&parent->p->klist_children, &i);
4040 while ((child = prev_device(&i)) && !error)
4041 error = fn(child, data);
4042 klist_iter_exit(&i);
4045 EXPORT_SYMBOL_GPL(device_for_each_child_reverse);
4048 * device_find_child - device iterator for locating a particular device.
4049 * @parent: parent struct device
4050 * @match: Callback function to check device
4051 * @data: Data to pass to match function
4053 * This is similar to the device_for_each_child() function above, but it
4054 * returns a reference to a device that is 'found' for later use, as
4055 * determined by the @match callback.
4057 * The callback should return 0 if the device doesn't match and non-zero
4058 * if it does. If the callback returns non-zero and a reference to the
4059 * current device can be obtained, this function will return to the caller
4060 * and not iterate over any more devices.
4062 * NOTE: you will need to drop the reference with put_device() after use.
4064 struct device *device_find_child(struct device *parent, void *data,
4065 int (*match)(struct device *dev, void *data))
4067 struct klist_iter i;
4068 struct device *child;
4073 klist_iter_init(&parent->p->klist_children, &i);
4074 while ((child = next_device(&i)))
4075 if (match(child, data) && get_device(child))
4077 klist_iter_exit(&i);
4080 EXPORT_SYMBOL_GPL(device_find_child);
4083 * device_find_child_by_name - device iterator for locating a child device.
4084 * @parent: parent struct device
4085 * @name: name of the child device
4087 * This is similar to the device_find_child() function above, but it
4088 * returns a reference to a device that has the name @name.
4090 * NOTE: you will need to drop the reference with put_device() after use.
4092 struct device *device_find_child_by_name(struct device *parent,
4095 struct klist_iter i;
4096 struct device *child;
4101 klist_iter_init(&parent->p->klist_children, &i);
4102 while ((child = next_device(&i)))
4103 if (sysfs_streq(dev_name(child), name) && get_device(child))
4105 klist_iter_exit(&i);
4108 EXPORT_SYMBOL_GPL(device_find_child_by_name);
4110 static int match_any(struct device *dev, void *unused)
4116 * device_find_any_child - device iterator for locating a child device, if any.
4117 * @parent: parent struct device
4119 * This is similar to the device_find_child() function above, but it
4120 * returns a reference to a child device, if any.
4122 * NOTE: you will need to drop the reference with put_device() after use.
4124 struct device *device_find_any_child(struct device *parent)
4126 return device_find_child(parent, NULL, match_any);
4128 EXPORT_SYMBOL_GPL(device_find_any_child);
4130 int __init devices_init(void)
4132 devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
4135 dev_kobj = kobject_create_and_add("dev", NULL);
4138 sysfs_dev_block_kobj = kobject_create_and_add("block", dev_kobj);
4139 if (!sysfs_dev_block_kobj)
4140 goto block_kobj_err;
4141 sysfs_dev_char_kobj = kobject_create_and_add("char", dev_kobj);
4142 if (!sysfs_dev_char_kobj)
4144 device_link_wq = alloc_workqueue("device_link_wq", 0, 0);
4145 if (!device_link_wq)
4151 kobject_put(sysfs_dev_char_kobj);
4153 kobject_put(sysfs_dev_block_kobj);
4155 kobject_put(dev_kobj);
4157 kset_unregister(devices_kset);
4161 static int device_check_offline(struct device *dev, void *not_used)
4165 ret = device_for_each_child(dev, NULL, device_check_offline);
4169 return device_supports_offline(dev) && !dev->offline ? -EBUSY : 0;
4173 * device_offline - Prepare the device for hot-removal.
4174 * @dev: Device to be put offline.
4176 * Execute the device bus type's .offline() callback, if present, to prepare
4177 * the device for a subsequent hot-removal. If that succeeds, the device must
4178 * not be used until either it is removed or its bus type's .online() callback
4181 * Call under device_hotplug_lock.
4183 int device_offline(struct device *dev)
4187 if (dev->offline_disabled)
4190 ret = device_for_each_child(dev, NULL, device_check_offline);
4195 if (device_supports_offline(dev)) {
4199 ret = dev->bus->offline(dev);
4201 kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
4202 dev->offline = true;
4212 * device_online - Put the device back online after successful device_offline().
4213 * @dev: Device to be put back online.
4215 * If device_offline() has been successfully executed for @dev, but the device
4216 * has not been removed subsequently, execute its bus type's .online() callback
4217 * to indicate that the device can be used again.
4219 * Call under device_hotplug_lock.
4221 int device_online(struct device *dev)
4226 if (device_supports_offline(dev)) {
4228 ret = dev->bus->online(dev);
4230 kobject_uevent(&dev->kobj, KOBJ_ONLINE);
4231 dev->offline = false;
4242 struct root_device {
4244 struct module *owner;
4247 static inline struct root_device *to_root_device(struct device *d)
4249 return container_of(d, struct root_device, dev);
4252 static void root_device_release(struct device *dev)
4254 kfree(to_root_device(dev));
4258 * __root_device_register - allocate and register a root device
4259 * @name: root device name
4260 * @owner: owner module of the root device, usually THIS_MODULE
4262 * This function allocates a root device and registers it
4263 * using device_register(). In order to free the returned
4264 * device, use root_device_unregister().
4266 * Root devices are dummy devices which allow other devices
4267 * to be grouped under /sys/devices. Use this function to
4268 * allocate a root device and then use it as the parent of
4269 * any device which should appear under /sys/devices/{name}
4271 * The /sys/devices/{name} directory will also contain a
4272 * 'module' symlink which points to the @owner directory
4275 * Returns &struct device pointer on success, or ERR_PTR() on error.
4277 * Note: You probably want to use root_device_register().
4279 struct device *__root_device_register(const char *name, struct module *owner)
4281 struct root_device *root;
4284 root = kzalloc(sizeof(struct root_device), GFP_KERNEL);
4286 return ERR_PTR(err);
4288 err = dev_set_name(&root->dev, "%s", name);
4291 return ERR_PTR(err);
4294 root->dev.release = root_device_release;
4296 err = device_register(&root->dev);
4298 put_device(&root->dev);
4299 return ERR_PTR(err);
4302 #ifdef CONFIG_MODULES /* gotta find a "cleaner" way to do this */
4304 struct module_kobject *mk = &owner->mkobj;
4306 err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module");
4308 device_unregister(&root->dev);
4309 return ERR_PTR(err);
4311 root->owner = owner;
4317 EXPORT_SYMBOL_GPL(__root_device_register);
4320 * root_device_unregister - unregister and free a root device
4321 * @dev: device going away
4323 * This function unregisters and cleans up a device that was created by
4324 * root_device_register().
4326 void root_device_unregister(struct device *dev)
4328 struct root_device *root = to_root_device(dev);
4331 sysfs_remove_link(&root->dev.kobj, "module");
4333 device_unregister(dev);
4335 EXPORT_SYMBOL_GPL(root_device_unregister);
4338 static void device_create_release(struct device *dev)
4340 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
4344 static __printf(6, 0) struct device *
4345 device_create_groups_vargs(const struct class *class, struct device *parent,
4346 dev_t devt, void *drvdata,
4347 const struct attribute_group **groups,
4348 const char *fmt, va_list args)
4350 struct device *dev = NULL;
4351 int retval = -ENODEV;
4353 if (IS_ERR_OR_NULL(class))
4356 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
4362 device_initialize(dev);
4365 dev->parent = parent;
4366 dev->groups = groups;
4367 dev->release = device_create_release;
4368 dev_set_drvdata(dev, drvdata);
4370 retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
4374 retval = device_add(dev);
4382 return ERR_PTR(retval);
4386 * device_create - creates a device and registers it with sysfs
4387 * @class: pointer to the struct class that this device should be registered to
4388 * @parent: pointer to the parent struct device of this new device, if any
4389 * @devt: the dev_t for the char device to be added
4390 * @drvdata: the data to be added to the device for callbacks
4391 * @fmt: string for the device's name
4393 * This function can be used by char device classes. A struct device
4394 * will be created in sysfs, registered to the specified class.
4396 * A "dev" file will be created, showing the dev_t for the device, if
4397 * the dev_t is not 0,0.
4398 * If a pointer to a parent struct device is passed in, the newly created
4399 * struct device will be a child of that device in sysfs.
4400 * The pointer to the struct device will be returned from the call.
4401 * Any further sysfs files that might be required can be created using this
4404 * Returns &struct device pointer on success, or ERR_PTR() on error.
4406 struct device *device_create(const struct class *class, struct device *parent,
4407 dev_t devt, void *drvdata, const char *fmt, ...)
4412 va_start(vargs, fmt);
4413 dev = device_create_groups_vargs(class, parent, devt, drvdata, NULL,
4418 EXPORT_SYMBOL_GPL(device_create);
4421 * device_create_with_groups - creates a device and registers it with sysfs
4422 * @class: pointer to the struct class that this device should be registered to
4423 * @parent: pointer to the parent struct device of this new device, if any
4424 * @devt: the dev_t for the char device to be added
4425 * @drvdata: the data to be added to the device for callbacks
4426 * @groups: NULL-terminated list of attribute groups to be created
4427 * @fmt: string for the device's name
4429 * This function can be used by char device classes. A struct device
4430 * will be created in sysfs, registered to the specified class.
4431 * Additional attributes specified in the groups parameter will also
4432 * be created automatically.
4434 * A "dev" file will be created, showing the dev_t for the device, if
4435 * the dev_t is not 0,0.
4436 * If a pointer to a parent struct device is passed in, the newly created
4437 * struct device will be a child of that device in sysfs.
4438 * The pointer to the struct device will be returned from the call.
4439 * Any further sysfs files that might be required can be created using this
4442 * Returns &struct device pointer on success, or ERR_PTR() on error.
4444 struct device *device_create_with_groups(const struct class *class,
4445 struct device *parent, dev_t devt,
4447 const struct attribute_group **groups,
4448 const char *fmt, ...)
4453 va_start(vargs, fmt);
4454 dev = device_create_groups_vargs(class, parent, devt, drvdata, groups,
4459 EXPORT_SYMBOL_GPL(device_create_with_groups);
4462 * device_destroy - removes a device that was created with device_create()
4463 * @class: pointer to the struct class that this device was registered with
4464 * @devt: the dev_t of the device that was previously registered
4466 * This call unregisters and cleans up a device that was created with a
4467 * call to device_create().
4469 void device_destroy(const struct class *class, dev_t devt)
4473 dev = class_find_device_by_devt(class, devt);
4476 device_unregister(dev);
4479 EXPORT_SYMBOL_GPL(device_destroy);
4482 * device_rename - renames a device
4483 * @dev: the pointer to the struct device to be renamed
4484 * @new_name: the new name of the device
4486 * It is the responsibility of the caller to provide mutual
4487 * exclusion between two different calls of device_rename
4488 * on the same device to ensure that new_name is valid and
4489 * won't conflict with other devices.
4491 * Note: given that some subsystems (networking and infiniband) use this
4492 * function, with no immediate plans for this to change, we cannot assume or
4493 * require that this function not be called at all.
4495 * However, if you're writing new code, do not call this function. The following
4496 * text from Kay Sievers offers some insight:
4498 * Renaming devices is racy at many levels, symlinks and other stuff are not
4499 * replaced atomically, and you get a "move" uevent, but it's not easy to
4500 * connect the event to the old and new device. Device nodes are not renamed at
4501 * all, there isn't even support for that in the kernel now.
4503 * In the meantime, during renaming, your target name might be taken by another
4504 * driver, creating conflicts. Or the old name is taken directly after you
4505 * renamed it -- then you get events for the same DEVPATH, before you even see
4506 * the "move" event. It's just a mess, and nothing new should ever rely on
4507 * kernel device renaming. Besides that, it's not even implemented now for
4508 * other things than (driver-core wise very simple) network devices.
4510 * Make up a "real" name in the driver before you register anything, or add
4511 * some other attributes for userspace to find the device, or use udev to add
4512 * symlinks -- but never rename kernel devices later, it's a complete mess. We
4513 * don't even want to get into that and try to implement the missing pieces in
4514 * the core. We really have other pieces to fix in the driver core mess. :)
4516 int device_rename(struct device *dev, const char *new_name)
4518 struct kobject *kobj = &dev->kobj;
4519 char *old_device_name = NULL;
4522 dev = get_device(dev);
4526 dev_dbg(dev, "renaming to %s\n", new_name);
4528 old_device_name = kstrdup(dev_name(dev), GFP_KERNEL);
4529 if (!old_device_name) {
4535 struct subsys_private *sp = class_to_subsys(dev->class);
4542 error = sysfs_rename_link_ns(&sp->subsys.kobj, kobj, old_device_name,
4543 new_name, kobject_namespace(kobj));
4549 error = kobject_rename(kobj, new_name);
4556 kfree(old_device_name);
4560 EXPORT_SYMBOL_GPL(device_rename);
4562 static int device_move_class_links(struct device *dev,
4563 struct device *old_parent,
4564 struct device *new_parent)
4569 sysfs_remove_link(&dev->kobj, "device");
4571 error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
4577 * device_move - moves a device to a new parent
4578 * @dev: the pointer to the struct device to be moved
4579 * @new_parent: the new parent of the device (can be NULL)
4580 * @dpm_order: how to reorder the dpm_list
4582 int device_move(struct device *dev, struct device *new_parent,
4583 enum dpm_order dpm_order)
4586 struct device *old_parent;
4587 struct kobject *new_parent_kobj;
4589 dev = get_device(dev);
4594 new_parent = get_device(new_parent);
4595 new_parent_kobj = get_device_parent(dev, new_parent);
4596 if (IS_ERR(new_parent_kobj)) {
4597 error = PTR_ERR(new_parent_kobj);
4598 put_device(new_parent);
4602 pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev),
4603 __func__, new_parent ? dev_name(new_parent) : "<NULL>");
4604 error = kobject_move(&dev->kobj, new_parent_kobj);
4606 cleanup_glue_dir(dev, new_parent_kobj);
4607 put_device(new_parent);
4610 old_parent = dev->parent;
4611 dev->parent = new_parent;
4613 klist_remove(&dev->p->knode_parent);
4615 klist_add_tail(&dev->p->knode_parent,
4616 &new_parent->p->klist_children);
4617 set_dev_node(dev, dev_to_node(new_parent));
4621 error = device_move_class_links(dev, old_parent, new_parent);
4623 /* We ignore errors on cleanup since we're hosed anyway... */
4624 device_move_class_links(dev, new_parent, old_parent);
4625 if (!kobject_move(&dev->kobj, &old_parent->kobj)) {
4627 klist_remove(&dev->p->knode_parent);
4628 dev->parent = old_parent;
4630 klist_add_tail(&dev->p->knode_parent,
4631 &old_parent->p->klist_children);
4632 set_dev_node(dev, dev_to_node(old_parent));
4635 cleanup_glue_dir(dev, new_parent_kobj);
4636 put_device(new_parent);
4640 switch (dpm_order) {
4641 case DPM_ORDER_NONE:
4643 case DPM_ORDER_DEV_AFTER_PARENT:
4644 device_pm_move_after(dev, new_parent);
4645 devices_kset_move_after(dev, new_parent);
4647 case DPM_ORDER_PARENT_BEFORE_DEV:
4648 device_pm_move_before(new_parent, dev);
4649 devices_kset_move_before(new_parent, dev);
4651 case DPM_ORDER_DEV_LAST:
4652 device_pm_move_last(dev);
4653 devices_kset_move_last(dev);
4657 put_device(old_parent);
4663 EXPORT_SYMBOL_GPL(device_move);
4665 static int device_attrs_change_owner(struct device *dev, kuid_t kuid,
4668 struct kobject *kobj = &dev->kobj;
4669 const struct class *class = dev->class;
4670 const struct device_type *type = dev->type;
4675 * Change the device groups of the device class for @dev to
4678 error = sysfs_groups_change_owner(kobj, class->dev_groups, kuid,
4686 * Change the device groups of the device type for @dev to
4689 error = sysfs_groups_change_owner(kobj, type->groups, kuid,
4695 /* Change the device groups of @dev to @kuid/@kgid. */
4696 error = sysfs_groups_change_owner(kobj, dev->groups, kuid, kgid);
4700 if (device_supports_offline(dev) && !dev->offline_disabled) {
4701 /* Change online device attributes of @dev to @kuid/@kgid. */
4702 error = sysfs_file_change_owner(kobj, dev_attr_online.attr.name,
4712 * device_change_owner - change the owner of an existing device.
4714 * @kuid: new owner's kuid
4715 * @kgid: new owner's kgid
4717 * This changes the owner of @dev and its corresponding sysfs entries to
4718 * @kuid/@kgid. This function closely mirrors how @dev was added via driver
4721 * Returns 0 on success or error code on failure.
4723 int device_change_owner(struct device *dev, kuid_t kuid, kgid_t kgid)
4726 struct kobject *kobj = &dev->kobj;
4727 struct subsys_private *sp;
4729 dev = get_device(dev);
4734 * Change the kobject and the default attributes and groups of the
4735 * ktype associated with it to @kuid/@kgid.
4737 error = sysfs_change_owner(kobj, kuid, kgid);
4742 * Change the uevent file for @dev to the new owner. The uevent file
4743 * was created in a separate step when @dev got added and we mirror
4746 error = sysfs_file_change_owner(kobj, dev_attr_uevent.attr.name, kuid,
4752 * Change the device groups, the device groups associated with the
4753 * device class, and the groups associated with the device type of @dev
4756 error = device_attrs_change_owner(dev, kuid, kgid);
4760 error = dpm_sysfs_change_owner(dev, kuid, kgid);
4765 * Change the owner of the symlink located in the class directory of
4766 * the device class associated with @dev which points to the actual
4767 * directory entry for @dev to @kuid/@kgid. This ensures that the
4768 * symlink shows the same permissions as its target.
4770 sp = class_to_subsys(dev->class);
4775 error = sysfs_link_change_owner(&sp->subsys.kobj, &dev->kobj, dev_name(dev), kuid, kgid);
4782 EXPORT_SYMBOL_GPL(device_change_owner);
4785 * device_shutdown - call ->shutdown() on each device to shutdown.
4787 void device_shutdown(void)
4789 struct device *dev, *parent;
4791 wait_for_device_probe();
4792 device_block_probing();
4796 spin_lock(&devices_kset->list_lock);
4798 * Walk the devices list backward, shutting down each in turn.
4799 * Beware that device unplug events may also start pulling
4800 * devices offline, even as the system is shutting down.
4802 while (!list_empty(&devices_kset->list)) {
4803 dev = list_entry(devices_kset->list.prev, struct device,
4807 * hold reference count of device's parent to
4808 * prevent it from being freed because parent's
4809 * lock is to be held
4811 parent = get_device(dev->parent);
4814 * Make sure the device is off the kset list, in the
4815 * event that dev->*->shutdown() doesn't remove it.
4817 list_del_init(&dev->kobj.entry);
4818 spin_unlock(&devices_kset->list_lock);
4820 /* hold lock to avoid race with probe/release */
4822 device_lock(parent);
4825 /* Don't allow any more runtime suspends */
4826 pm_runtime_get_noresume(dev);
4827 pm_runtime_barrier(dev);
4829 if (dev->class && dev->class->shutdown_pre) {
4831 dev_info(dev, "shutdown_pre\n");
4832 dev->class->shutdown_pre(dev);
4834 if (dev->bus && dev->bus->shutdown) {
4836 dev_info(dev, "shutdown\n");
4837 dev->bus->shutdown(dev);
4838 } else if (dev->driver && dev->driver->shutdown) {
4840 dev_info(dev, "shutdown\n");
4841 dev->driver->shutdown(dev);
4846 device_unlock(parent);
4851 spin_lock(&devices_kset->list_lock);
4853 spin_unlock(&devices_kset->list_lock);
4857 * Device logging functions
4860 #ifdef CONFIG_PRINTK
4862 set_dev_info(const struct device *dev, struct dev_printk_info *dev_info)
4866 memset(dev_info, 0, sizeof(*dev_info));
4869 subsys = dev->class->name;
4871 subsys = dev->bus->name;
4875 strscpy(dev_info->subsystem, subsys, sizeof(dev_info->subsystem));
4878 * Add device identifier DEVICE=:
4882 * +sound:card0 subsystem:devname
4884 if (MAJOR(dev->devt)) {
4887 if (strcmp(subsys, "block") == 0)
4892 snprintf(dev_info->device, sizeof(dev_info->device),
4893 "%c%u:%u", c, MAJOR(dev->devt), MINOR(dev->devt));
4894 } else if (strcmp(subsys, "net") == 0) {
4895 struct net_device *net = to_net_dev(dev);
4897 snprintf(dev_info->device, sizeof(dev_info->device),
4898 "n%u", net->ifindex);
4900 snprintf(dev_info->device, sizeof(dev_info->device),
4901 "+%s:%s", subsys, dev_name(dev));
4905 int dev_vprintk_emit(int level, const struct device *dev,
4906 const char *fmt, va_list args)
4908 struct dev_printk_info dev_info;
4910 set_dev_info(dev, &dev_info);
4912 return vprintk_emit(0, level, &dev_info, fmt, args);
4914 EXPORT_SYMBOL(dev_vprintk_emit);
4916 int dev_printk_emit(int level, const struct device *dev, const char *fmt, ...)
4921 va_start(args, fmt);
4923 r = dev_vprintk_emit(level, dev, fmt, args);
4929 EXPORT_SYMBOL(dev_printk_emit);
4931 static void __dev_printk(const char *level, const struct device *dev,
4932 struct va_format *vaf)
4935 dev_printk_emit(level[1] - '0', dev, "%s %s: %pV",
4936 dev_driver_string(dev), dev_name(dev), vaf);
4938 printk("%s(NULL device *): %pV", level, vaf);
4941 void _dev_printk(const char *level, const struct device *dev,
4942 const char *fmt, ...)
4944 struct va_format vaf;
4947 va_start(args, fmt);
4952 __dev_printk(level, dev, &vaf);
4956 EXPORT_SYMBOL(_dev_printk);
4958 #define define_dev_printk_level(func, kern_level) \
4959 void func(const struct device *dev, const char *fmt, ...) \
4961 struct va_format vaf; \
4964 va_start(args, fmt); \
4969 __dev_printk(kern_level, dev, &vaf); \
4973 EXPORT_SYMBOL(func);
4975 define_dev_printk_level(_dev_emerg, KERN_EMERG);
4976 define_dev_printk_level(_dev_alert, KERN_ALERT);
4977 define_dev_printk_level(_dev_crit, KERN_CRIT);
4978 define_dev_printk_level(_dev_err, KERN_ERR);
4979 define_dev_printk_level(_dev_warn, KERN_WARNING);
4980 define_dev_printk_level(_dev_notice, KERN_NOTICE);
4981 define_dev_printk_level(_dev_info, KERN_INFO);
4986 * dev_err_probe - probe error check and log helper
4987 * @dev: the pointer to the struct device
4988 * @err: error value to test
4989 * @fmt: printf-style format string
4990 * @...: arguments as specified in the format string
4992 * This helper implements common pattern present in probe functions for error
4993 * checking: print debug or error message depending if the error value is
4994 * -EPROBE_DEFER and propagate error upwards.
4995 * In case of -EPROBE_DEFER it sets also defer probe reason, which can be
4996 * checked later by reading devices_deferred debugfs attribute.
4997 * It replaces code sequence::
4999 * if (err != -EPROBE_DEFER)
5000 * dev_err(dev, ...);
5002 * dev_dbg(dev, ...);
5007 * return dev_err_probe(dev, err, ...);
5009 * Using this helper in your probe function is totally fine even if @err is
5010 * known to never be -EPROBE_DEFER.
5011 * The benefit compared to a normal dev_err() is the standardized format
5012 * of the error code, it being emitted symbolically (i.e. you get "EAGAIN"
5013 * instead of "-35") and the fact that the error code is returned which allows
5014 * more compact error paths.
5018 int dev_err_probe(const struct device *dev, int err, const char *fmt, ...)
5020 struct va_format vaf;
5023 va_start(args, fmt);
5029 device_set_deferred_probe_reason(dev, &vaf);
5030 dev_dbg(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
5035 * We don't print anything on -ENOMEM, there is already enough
5041 dev_err(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
5049 EXPORT_SYMBOL_GPL(dev_err_probe);
5051 static inline bool fwnode_is_primary(struct fwnode_handle *fwnode)
5053 return fwnode && !IS_ERR(fwnode->secondary);
5057 * set_primary_fwnode - Change the primary firmware node of a given device.
5058 * @dev: Device to handle.
5059 * @fwnode: New primary firmware node of the device.
5061 * Set the device's firmware node pointer to @fwnode, but if a secondary
5062 * firmware node of the device is present, preserve it.
5064 * Valid fwnode cases are:
5065 * - primary --> secondary --> -ENODEV
5066 * - primary --> NULL
5067 * - secondary --> -ENODEV
5070 void set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
5072 struct device *parent = dev->parent;
5073 struct fwnode_handle *fn = dev->fwnode;
5076 if (fwnode_is_primary(fn))
5080 WARN_ON(fwnode->secondary);
5081 fwnode->secondary = fn;
5083 dev->fwnode = fwnode;
5085 if (fwnode_is_primary(fn)) {
5086 dev->fwnode = fn->secondary;
5088 /* Skip nullifying fn->secondary if the primary is shared */
5089 if (parent && fn == parent->fwnode)
5092 /* Set fn->secondary = NULL, so fn remains the primary fwnode */
5093 fn->secondary = NULL;
5099 EXPORT_SYMBOL_GPL(set_primary_fwnode);
5102 * set_secondary_fwnode - Change the secondary firmware node of a given device.
5103 * @dev: Device to handle.
5104 * @fwnode: New secondary firmware node of the device.
5106 * If a primary firmware node of the device is present, set its secondary
5107 * pointer to @fwnode. Otherwise, set the device's firmware node pointer to
5110 void set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
5113 fwnode->secondary = ERR_PTR(-ENODEV);
5115 if (fwnode_is_primary(dev->fwnode))
5116 dev->fwnode->secondary = fwnode;
5118 dev->fwnode = fwnode;
5120 EXPORT_SYMBOL_GPL(set_secondary_fwnode);
5123 * device_set_of_node_from_dev - reuse device-tree node of another device
5124 * @dev: device whose device-tree node is being set
5125 * @dev2: device whose device-tree node is being reused
5127 * Takes another reference to the new device-tree node after first dropping
5128 * any reference held to the old node.
5130 void device_set_of_node_from_dev(struct device *dev, const struct device *dev2)
5132 of_node_put(dev->of_node);
5133 dev->of_node = of_node_get(dev2->of_node);
5134 dev->of_node_reused = true;
5136 EXPORT_SYMBOL_GPL(device_set_of_node_from_dev);
5138 void device_set_node(struct device *dev, struct fwnode_handle *fwnode)
5140 dev->fwnode = fwnode;
5141 dev->of_node = to_of_node(fwnode);
5143 EXPORT_SYMBOL_GPL(device_set_node);
5145 int device_match_name(struct device *dev, const void *name)
5147 return sysfs_streq(dev_name(dev), name);
5149 EXPORT_SYMBOL_GPL(device_match_name);
5151 int device_match_of_node(struct device *dev, const void *np)
5153 return dev->of_node == np;
5155 EXPORT_SYMBOL_GPL(device_match_of_node);
5157 int device_match_fwnode(struct device *dev, const void *fwnode)
5159 return dev_fwnode(dev) == fwnode;
5161 EXPORT_SYMBOL_GPL(device_match_fwnode);
5163 int device_match_devt(struct device *dev, const void *pdevt)
5165 return dev->devt == *(dev_t *)pdevt;
5167 EXPORT_SYMBOL_GPL(device_match_devt);
5169 int device_match_acpi_dev(struct device *dev, const void *adev)
5171 return ACPI_COMPANION(dev) == adev;
5173 EXPORT_SYMBOL(device_match_acpi_dev);
5175 int device_match_acpi_handle(struct device *dev, const void *handle)
5177 return ACPI_HANDLE(dev) == handle;
5179 EXPORT_SYMBOL(device_match_acpi_handle);
5181 int device_match_any(struct device *dev, const void *unused)
5185 EXPORT_SYMBOL_GPL(device_match_any);