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/blkdev.h>
13 #include <linux/cleanup.h>
14 #include <linux/cpufreq.h>
15 #include <linux/device.h>
16 #include <linux/dma-map-ops.h> /* for dma_default_coherent */
17 #include <linux/err.h>
18 #include <linux/fwnode.h>
19 #include <linux/init.h>
20 #include <linux/kdev_t.h>
21 #include <linux/kstrtox.h>
22 #include <linux/module.h>
23 #include <linux/mutex.h>
24 #include <linux/netdevice.h>
25 #include <linux/notifier.h>
27 #include <linux/of_device.h>
28 #include <linux/pm_runtime.h>
29 #include <linux/rcupdate.h>
30 #include <linux/sched/mm.h>
31 #include <linux/sched/signal.h>
32 #include <linux/slab.h>
33 #include <linux/string_helpers.h>
34 #include <linux/swiotlb.h>
35 #include <linux/sysfs.h>
38 #include "physical_location.h"
39 #include "power/power.h"
41 /* Device links support. */
42 static LIST_HEAD(deferred_sync);
43 static unsigned int defer_sync_state_count = 1;
44 static DEFINE_MUTEX(fwnode_link_lock);
45 static bool fw_devlink_is_permissive(void);
46 static void __fw_devlink_link_to_consumers(struct device *dev);
47 static bool fw_devlink_drv_reg_done;
48 static bool fw_devlink_best_effort;
49 static struct workqueue_struct *device_link_wq;
52 * __fwnode_link_add - Create a link between two fwnode_handles.
53 * @con: Consumer end of the link.
54 * @sup: Supplier end of the link.
57 * Create a fwnode link between fwnode handles @con and @sup. The fwnode link
58 * represents the detail that the firmware lists @sup fwnode as supplying a
61 * The driver core will use the fwnode link to create a device link between the
62 * two device objects corresponding to @con and @sup when they are created. The
63 * driver core will automatically delete the fwnode link between @con and @sup
66 * Attempts to create duplicate links between the same pair of fwnode handles
67 * are ignored and there is no reference counting.
69 static int __fwnode_link_add(struct fwnode_handle *con,
70 struct fwnode_handle *sup, u8 flags)
72 struct fwnode_link *link;
74 list_for_each_entry(link, &sup->consumers, s_hook)
75 if (link->consumer == con) {
80 link = kzalloc(sizeof(*link), GFP_KERNEL);
85 INIT_LIST_HEAD(&link->s_hook);
87 INIT_LIST_HEAD(&link->c_hook);
90 list_add(&link->s_hook, &sup->consumers);
91 list_add(&link->c_hook, &con->suppliers);
92 pr_debug("%pfwf Linked as a fwnode consumer to %pfwf\n",
98 int fwnode_link_add(struct fwnode_handle *con, struct fwnode_handle *sup,
101 guard(mutex)(&fwnode_link_lock);
103 return __fwnode_link_add(con, sup, flags);
107 * __fwnode_link_del - Delete a link between two fwnode_handles.
108 * @link: the fwnode_link to be deleted
110 * The fwnode_link_lock needs to be held when this function is called.
112 static void __fwnode_link_del(struct fwnode_link *link)
114 pr_debug("%pfwf Dropping the fwnode link to %pfwf\n",
115 link->consumer, link->supplier);
116 list_del(&link->s_hook);
117 list_del(&link->c_hook);
122 * __fwnode_link_cycle - Mark a fwnode link as being part of a cycle.
123 * @link: the fwnode_link to be marked
125 * The fwnode_link_lock needs to be held when this function is called.
127 static void __fwnode_link_cycle(struct fwnode_link *link)
129 pr_debug("%pfwf: cycle: depends on %pfwf\n",
130 link->consumer, link->supplier);
131 link->flags |= FWLINK_FLAG_CYCLE;
135 * fwnode_links_purge_suppliers - Delete all supplier links of fwnode_handle.
136 * @fwnode: fwnode whose supplier links need to be deleted
138 * Deletes all supplier links connecting directly to @fwnode.
140 static void fwnode_links_purge_suppliers(struct fwnode_handle *fwnode)
142 struct fwnode_link *link, *tmp;
144 guard(mutex)(&fwnode_link_lock);
146 list_for_each_entry_safe(link, tmp, &fwnode->suppliers, c_hook)
147 __fwnode_link_del(link);
151 * fwnode_links_purge_consumers - Delete all consumer links of fwnode_handle.
152 * @fwnode: fwnode whose consumer links need to be deleted
154 * Deletes all consumer links connecting directly to @fwnode.
156 static void fwnode_links_purge_consumers(struct fwnode_handle *fwnode)
158 struct fwnode_link *link, *tmp;
160 guard(mutex)(&fwnode_link_lock);
162 list_for_each_entry_safe(link, tmp, &fwnode->consumers, s_hook)
163 __fwnode_link_del(link);
167 * fwnode_links_purge - Delete all links connected to a fwnode_handle.
168 * @fwnode: fwnode whose links needs to be deleted
170 * Deletes all links connecting directly to a fwnode.
172 void fwnode_links_purge(struct fwnode_handle *fwnode)
174 fwnode_links_purge_suppliers(fwnode);
175 fwnode_links_purge_consumers(fwnode);
178 void fw_devlink_purge_absent_suppliers(struct fwnode_handle *fwnode)
180 struct fwnode_handle *child;
182 /* Don't purge consumer links of an added child */
186 fwnode->flags |= FWNODE_FLAG_NOT_DEVICE;
187 fwnode_links_purge_consumers(fwnode);
189 fwnode_for_each_available_child_node(fwnode, child)
190 fw_devlink_purge_absent_suppliers(child);
192 EXPORT_SYMBOL_GPL(fw_devlink_purge_absent_suppliers);
195 * __fwnode_links_move_consumers - Move consumer from @from to @to fwnode_handle
196 * @from: move consumers away from this fwnode
197 * @to: move consumers to this fwnode
199 * Move all consumer links from @from fwnode to @to fwnode.
201 static void __fwnode_links_move_consumers(struct fwnode_handle *from,
202 struct fwnode_handle *to)
204 struct fwnode_link *link, *tmp;
206 list_for_each_entry_safe(link, tmp, &from->consumers, s_hook) {
207 __fwnode_link_add(link->consumer, to, link->flags);
208 __fwnode_link_del(link);
213 * __fw_devlink_pickup_dangling_consumers - Pick up dangling consumers
214 * @fwnode: fwnode from which to pick up dangling consumers
215 * @new_sup: fwnode of new supplier
217 * If the @fwnode has a corresponding struct device and the device supports
218 * probing (that is, added to a bus), then we want to let fw_devlink create
219 * MANAGED device links to this device, so leave @fwnode and its descendant's
220 * fwnode links alone.
222 * Otherwise, move its consumers to the new supplier @new_sup.
224 static void __fw_devlink_pickup_dangling_consumers(struct fwnode_handle *fwnode,
225 struct fwnode_handle *new_sup)
227 struct fwnode_handle *child;
229 if (fwnode->dev && fwnode->dev->bus)
232 fwnode->flags |= FWNODE_FLAG_NOT_DEVICE;
233 __fwnode_links_move_consumers(fwnode, new_sup);
235 fwnode_for_each_available_child_node(fwnode, child)
236 __fw_devlink_pickup_dangling_consumers(child, new_sup);
239 static DEFINE_MUTEX(device_links_lock);
240 DEFINE_STATIC_SRCU(device_links_srcu);
242 static inline void device_links_write_lock(void)
244 mutex_lock(&device_links_lock);
247 static inline void device_links_write_unlock(void)
249 mutex_unlock(&device_links_lock);
252 int device_links_read_lock(void) __acquires(&device_links_srcu)
254 return srcu_read_lock(&device_links_srcu);
257 void device_links_read_unlock(int idx) __releases(&device_links_srcu)
259 srcu_read_unlock(&device_links_srcu, idx);
262 int device_links_read_lock_held(void)
264 return srcu_read_lock_held(&device_links_srcu);
267 static void device_link_synchronize_removal(void)
269 synchronize_srcu(&device_links_srcu);
272 static void device_link_remove_from_lists(struct device_link *link)
274 list_del_rcu(&link->s_node);
275 list_del_rcu(&link->c_node);
278 static bool device_is_ancestor(struct device *dev, struct device *target)
280 while (target->parent) {
281 target = target->parent;
288 #define DL_MARKER_FLAGS (DL_FLAG_INFERRED | \
291 static inline bool device_link_flag_is_sync_state_only(u32 flags)
293 return (flags & ~DL_MARKER_FLAGS) == DL_FLAG_SYNC_STATE_ONLY;
297 * device_is_dependent - Check if one device depends on another one
298 * @dev: Device to check dependencies for.
299 * @target: Device to check against.
301 * Check if @target depends on @dev or any device dependent on it (its child or
302 * its consumer etc). Return 1 if that is the case or 0 otherwise.
304 static int device_is_dependent(struct device *dev, void *target)
306 struct device_link *link;
310 * The "ancestors" check is needed to catch the case when the target
311 * device has not been completely initialized yet and it is still
312 * missing from the list of children of its parent device.
314 if (dev == target || device_is_ancestor(dev, target))
317 ret = device_for_each_child(dev, target, device_is_dependent);
321 list_for_each_entry(link, &dev->links.consumers, s_node) {
322 if (device_link_flag_is_sync_state_only(link->flags))
325 if (link->consumer == target)
328 ret = device_is_dependent(link->consumer, target);
335 static void device_link_init_status(struct device_link *link,
336 struct device *consumer,
337 struct device *supplier)
339 switch (supplier->links.status) {
341 switch (consumer->links.status) {
344 * A consumer driver can create a link to a supplier
345 * that has not completed its probing yet as long as it
346 * knows that the supplier is already functional (for
347 * example, it has just acquired some resources from the
350 link->status = DL_STATE_CONSUMER_PROBE;
353 link->status = DL_STATE_DORMANT;
357 case DL_DEV_DRIVER_BOUND:
358 switch (consumer->links.status) {
360 link->status = DL_STATE_CONSUMER_PROBE;
362 case DL_DEV_DRIVER_BOUND:
363 link->status = DL_STATE_ACTIVE;
366 link->status = DL_STATE_AVAILABLE;
370 case DL_DEV_UNBINDING:
371 link->status = DL_STATE_SUPPLIER_UNBIND;
374 link->status = DL_STATE_DORMANT;
379 static int device_reorder_to_tail(struct device *dev, void *not_used)
381 struct device_link *link;
384 * Devices that have not been registered yet will be put to the ends
385 * of the lists during the registration, so skip them here.
387 if (device_is_registered(dev))
388 devices_kset_move_last(dev);
390 if (device_pm_initialized(dev))
391 device_pm_move_last(dev);
393 device_for_each_child(dev, NULL, device_reorder_to_tail);
394 list_for_each_entry(link, &dev->links.consumers, s_node) {
395 if (device_link_flag_is_sync_state_only(link->flags))
397 device_reorder_to_tail(link->consumer, NULL);
404 * device_pm_move_to_tail - Move set of devices to the end of device lists
405 * @dev: Device to move
407 * This is a device_reorder_to_tail() wrapper taking the requisite locks.
409 * It moves the @dev along with all of its children and all of its consumers
410 * to the ends of the device_kset and dpm_list, recursively.
412 void device_pm_move_to_tail(struct device *dev)
416 idx = device_links_read_lock();
418 device_reorder_to_tail(dev, NULL);
420 device_links_read_unlock(idx);
423 #define to_devlink(dev) container_of((dev), struct device_link, link_dev)
425 static ssize_t status_show(struct device *dev,
426 struct device_attribute *attr, char *buf)
430 switch (to_devlink(dev)->status) {
432 output = "not tracked";
434 case DL_STATE_DORMANT:
437 case DL_STATE_AVAILABLE:
438 output = "available";
440 case DL_STATE_CONSUMER_PROBE:
441 output = "consumer probing";
443 case DL_STATE_ACTIVE:
446 case DL_STATE_SUPPLIER_UNBIND:
447 output = "supplier unbinding";
454 return sysfs_emit(buf, "%s\n", output);
456 static DEVICE_ATTR_RO(status);
458 static ssize_t auto_remove_on_show(struct device *dev,
459 struct device_attribute *attr, char *buf)
461 struct device_link *link = to_devlink(dev);
464 if (link->flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
465 output = "supplier unbind";
466 else if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER)
467 output = "consumer unbind";
471 return sysfs_emit(buf, "%s\n", output);
473 static DEVICE_ATTR_RO(auto_remove_on);
475 static ssize_t runtime_pm_show(struct device *dev,
476 struct device_attribute *attr, char *buf)
478 struct device_link *link = to_devlink(dev);
480 return sysfs_emit(buf, "%d\n", !!(link->flags & DL_FLAG_PM_RUNTIME));
482 static DEVICE_ATTR_RO(runtime_pm);
484 static ssize_t sync_state_only_show(struct device *dev,
485 struct device_attribute *attr, char *buf)
487 struct device_link *link = to_devlink(dev);
489 return sysfs_emit(buf, "%d\n",
490 !!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
492 static DEVICE_ATTR_RO(sync_state_only);
494 static struct attribute *devlink_attrs[] = {
495 &dev_attr_status.attr,
496 &dev_attr_auto_remove_on.attr,
497 &dev_attr_runtime_pm.attr,
498 &dev_attr_sync_state_only.attr,
501 ATTRIBUTE_GROUPS(devlink);
503 static void device_link_release_fn(struct work_struct *work)
505 struct device_link *link = container_of(work, struct device_link, rm_work);
507 /* Ensure that all references to the link object have been dropped. */
508 device_link_synchronize_removal();
510 pm_runtime_release_supplier(link);
512 * If supplier_preactivated is set, the link has been dropped between
513 * the pm_runtime_get_suppliers() and pm_runtime_put_suppliers() calls
514 * in __driver_probe_device(). In that case, drop the supplier's
515 * PM-runtime usage counter to remove the reference taken by
516 * pm_runtime_get_suppliers().
518 if (link->supplier_preactivated)
519 pm_runtime_put_noidle(link->supplier);
521 pm_request_idle(link->supplier);
523 put_device(link->consumer);
524 put_device(link->supplier);
528 static void devlink_dev_release(struct device *dev)
530 struct device_link *link = to_devlink(dev);
532 INIT_WORK(&link->rm_work, device_link_release_fn);
534 * It may take a while to complete this work because of the SRCU
535 * synchronization in device_link_release_fn() and if the consumer or
536 * supplier devices get deleted when it runs, so put it into the
537 * dedicated workqueue.
539 queue_work(device_link_wq, &link->rm_work);
543 * device_link_wait_removal - Wait for ongoing devlink removal jobs to terminate
545 void device_link_wait_removal(void)
548 * devlink removal jobs are queued in the dedicated work queue.
549 * To be sure that all removal jobs are terminated, ensure that any
550 * scheduled work has run to completion.
552 flush_workqueue(device_link_wq);
554 EXPORT_SYMBOL_GPL(device_link_wait_removal);
556 static struct class devlink_class = {
558 .dev_groups = devlink_groups,
559 .dev_release = devlink_dev_release,
562 static int devlink_add_symlinks(struct device *dev)
564 char *buf_con __free(kfree) = NULL, *buf_sup __free(kfree) = NULL;
566 struct device_link *link = to_devlink(dev);
567 struct device *sup = link->supplier;
568 struct device *con = link->consumer;
570 ret = sysfs_create_link(&link->link_dev.kobj, &sup->kobj, "supplier");
574 ret = sysfs_create_link(&link->link_dev.kobj, &con->kobj, "consumer");
578 buf_con = kasprintf(GFP_KERNEL, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
584 ret = sysfs_create_link(&sup->kobj, &link->link_dev.kobj, buf_con);
588 buf_sup = kasprintf(GFP_KERNEL, "supplier:%s:%s", dev_bus_name(sup), dev_name(sup));
594 ret = sysfs_create_link(&con->kobj, &link->link_dev.kobj, buf_sup);
601 sysfs_remove_link(&sup->kobj, buf_con);
603 sysfs_remove_link(&link->link_dev.kobj, "consumer");
605 sysfs_remove_link(&link->link_dev.kobj, "supplier");
610 static void devlink_remove_symlinks(struct device *dev)
612 char *buf_con __free(kfree) = NULL, *buf_sup __free(kfree) = NULL;
613 struct device_link *link = to_devlink(dev);
614 struct device *sup = link->supplier;
615 struct device *con = link->consumer;
617 sysfs_remove_link(&link->link_dev.kobj, "consumer");
618 sysfs_remove_link(&link->link_dev.kobj, "supplier");
620 if (device_is_registered(con)) {
621 buf_sup = kasprintf(GFP_KERNEL, "supplier:%s:%s", dev_bus_name(sup), dev_name(sup));
624 sysfs_remove_link(&con->kobj, buf_sup);
627 buf_con = kasprintf(GFP_KERNEL, "consumer:%s:%s", dev_bus_name(con), dev_name(con));
630 sysfs_remove_link(&sup->kobj, buf_con);
635 WARN(1, "Unable to properly free device link symlinks!\n");
638 static struct class_interface devlink_class_intf = {
639 .class = &devlink_class,
640 .add_dev = devlink_add_symlinks,
641 .remove_dev = devlink_remove_symlinks,
644 static int __init devlink_class_init(void)
648 ret = class_register(&devlink_class);
652 ret = class_interface_register(&devlink_class_intf);
654 class_unregister(&devlink_class);
658 postcore_initcall(devlink_class_init);
660 #define DL_MANAGED_LINK_FLAGS (DL_FLAG_AUTOREMOVE_CONSUMER | \
661 DL_FLAG_AUTOREMOVE_SUPPLIER | \
662 DL_FLAG_AUTOPROBE_CONSUMER | \
663 DL_FLAG_SYNC_STATE_ONLY | \
667 #define DL_ADD_VALID_FLAGS (DL_MANAGED_LINK_FLAGS | DL_FLAG_STATELESS | \
668 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE)
671 * device_link_add - Create a link between two devices.
672 * @consumer: Consumer end of the link.
673 * @supplier: Supplier end of the link.
674 * @flags: Link flags.
676 * Return: On success, a device_link struct will be returned.
677 * On error or invalid flag settings, NULL will be returned.
679 * The caller is responsible for the proper synchronization of the link creation
680 * with runtime PM. First, setting the DL_FLAG_PM_RUNTIME flag will cause the
681 * runtime PM framework to take the link into account. Second, if the
682 * DL_FLAG_RPM_ACTIVE flag is set in addition to it, the supplier devices will
683 * be forced into the active meta state and reference-counted upon the creation
684 * of the link. If DL_FLAG_PM_RUNTIME is not set, DL_FLAG_RPM_ACTIVE will be
687 * If DL_FLAG_STATELESS is set in @flags, the caller of this function is
688 * expected to release the link returned by it directly with the help of either
689 * device_link_del() or device_link_remove().
691 * If that flag is not set, however, the caller of this function is handing the
692 * management of the link over to the driver core entirely and its return value
693 * can only be used to check whether or not the link is present. In that case,
694 * the DL_FLAG_AUTOREMOVE_CONSUMER and DL_FLAG_AUTOREMOVE_SUPPLIER device link
695 * flags can be used to indicate to the driver core when the link can be safely
696 * deleted. Namely, setting one of them in @flags indicates to the driver core
697 * that the link is not going to be used (by the given caller of this function)
698 * after unbinding the consumer or supplier driver, respectively, from its
699 * device, so the link can be deleted at that point. If none of them is set,
700 * the link will be maintained until one of the devices pointed to by it (either
701 * the consumer or the supplier) is unregistered.
703 * Also, if DL_FLAG_STATELESS, DL_FLAG_AUTOREMOVE_CONSUMER and
704 * DL_FLAG_AUTOREMOVE_SUPPLIER are not set in @flags (that is, a persistent
705 * managed device link is being added), the DL_FLAG_AUTOPROBE_CONSUMER flag can
706 * be used to request the driver core to automatically probe for a consumer
707 * driver after successfully binding a driver to the supplier device.
709 * The combination of DL_FLAG_STATELESS and one of DL_FLAG_AUTOREMOVE_CONSUMER,
710 * DL_FLAG_AUTOREMOVE_SUPPLIER, or DL_FLAG_AUTOPROBE_CONSUMER set in @flags at
711 * the same time is invalid and will cause NULL to be returned upfront.
712 * However, if a device link between the given @consumer and @supplier pair
713 * exists already when this function is called for them, the existing link will
714 * be returned regardless of its current type and status (the link's flags may
715 * be modified then). The caller of this function is then expected to treat
716 * the link as though it has just been created, so (in particular) if
717 * DL_FLAG_STATELESS was passed in @flags, the link needs to be released
718 * explicitly when not needed any more (as stated above).
720 * A side effect of the link creation is re-ordering of dpm_list and the
721 * devices_kset list by moving the consumer device and all devices depending
722 * on it to the ends of these lists (that does not happen to devices that have
723 * not been registered when this function is called).
725 * The supplier device is required to be registered when this function is called
726 * and NULL will be returned if that is not the case. The consumer device need
727 * not be registered, however.
729 struct device_link *device_link_add(struct device *consumer,
730 struct device *supplier, u32 flags)
732 struct device_link *link;
734 if (!consumer || !supplier || consumer == supplier ||
735 flags & ~DL_ADD_VALID_FLAGS ||
736 (flags & DL_FLAG_STATELESS && flags & DL_MANAGED_LINK_FLAGS) ||
737 (flags & DL_FLAG_AUTOPROBE_CONSUMER &&
738 flags & (DL_FLAG_AUTOREMOVE_CONSUMER |
739 DL_FLAG_AUTOREMOVE_SUPPLIER)))
742 if (flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) {
743 if (pm_runtime_get_sync(supplier) < 0) {
744 pm_runtime_put_noidle(supplier);
749 if (!(flags & DL_FLAG_STATELESS))
750 flags |= DL_FLAG_MANAGED;
752 if (flags & DL_FLAG_SYNC_STATE_ONLY &&
753 !device_link_flag_is_sync_state_only(flags))
756 device_links_write_lock();
760 * If the supplier has not been fully registered yet or there is a
761 * reverse (non-SYNC_STATE_ONLY) dependency between the consumer and
762 * the supplier already in the graph, return NULL. If the link is a
763 * SYNC_STATE_ONLY link, we don't check for reverse dependencies
764 * because it only affects sync_state() callbacks.
766 if (!device_pm_initialized(supplier)
767 || (!(flags & DL_FLAG_SYNC_STATE_ONLY) &&
768 device_is_dependent(consumer, supplier))) {
774 * SYNC_STATE_ONLY links are useless once a consumer device has probed.
775 * So, only create it if the consumer hasn't probed yet.
777 if (flags & DL_FLAG_SYNC_STATE_ONLY &&
778 consumer->links.status != DL_DEV_NO_DRIVER &&
779 consumer->links.status != DL_DEV_PROBING) {
785 * DL_FLAG_AUTOREMOVE_SUPPLIER indicates that the link will be needed
786 * longer than for DL_FLAG_AUTOREMOVE_CONSUMER and setting them both
787 * together doesn't make sense, so prefer DL_FLAG_AUTOREMOVE_SUPPLIER.
789 if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
790 flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
792 list_for_each_entry(link, &supplier->links.consumers, s_node) {
793 if (link->consumer != consumer)
796 if (link->flags & DL_FLAG_INFERRED &&
797 !(flags & DL_FLAG_INFERRED))
798 link->flags &= ~DL_FLAG_INFERRED;
800 if (flags & DL_FLAG_PM_RUNTIME) {
801 if (!(link->flags & DL_FLAG_PM_RUNTIME)) {
802 pm_runtime_new_link(consumer);
803 link->flags |= DL_FLAG_PM_RUNTIME;
805 if (flags & DL_FLAG_RPM_ACTIVE)
806 refcount_inc(&link->rpm_active);
809 if (flags & DL_FLAG_STATELESS) {
810 kref_get(&link->kref);
811 if (link->flags & DL_FLAG_SYNC_STATE_ONLY &&
812 !(link->flags & DL_FLAG_STATELESS)) {
813 link->flags |= DL_FLAG_STATELESS;
816 link->flags |= DL_FLAG_STATELESS;
822 * If the life time of the link following from the new flags is
823 * longer than indicated by the flags of the existing link,
824 * update the existing link to stay around longer.
826 if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER) {
827 if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER) {
828 link->flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
829 link->flags |= DL_FLAG_AUTOREMOVE_SUPPLIER;
831 } else if (!(flags & DL_FLAG_AUTOREMOVE_CONSUMER)) {
832 link->flags &= ~(DL_FLAG_AUTOREMOVE_CONSUMER |
833 DL_FLAG_AUTOREMOVE_SUPPLIER);
835 if (!(link->flags & DL_FLAG_MANAGED)) {
836 kref_get(&link->kref);
837 link->flags |= DL_FLAG_MANAGED;
838 device_link_init_status(link, consumer, supplier);
840 if (link->flags & DL_FLAG_SYNC_STATE_ONLY &&
841 !(flags & DL_FLAG_SYNC_STATE_ONLY)) {
842 link->flags &= ~DL_FLAG_SYNC_STATE_ONLY;
849 link = kzalloc(sizeof(*link), GFP_KERNEL);
853 refcount_set(&link->rpm_active, 1);
855 get_device(supplier);
856 link->supplier = supplier;
857 INIT_LIST_HEAD(&link->s_node);
858 get_device(consumer);
859 link->consumer = consumer;
860 INIT_LIST_HEAD(&link->c_node);
862 kref_init(&link->kref);
864 link->link_dev.class = &devlink_class;
865 device_set_pm_not_required(&link->link_dev);
866 dev_set_name(&link->link_dev, "%s:%s--%s:%s",
867 dev_bus_name(supplier), dev_name(supplier),
868 dev_bus_name(consumer), dev_name(consumer));
869 if (device_register(&link->link_dev)) {
870 put_device(&link->link_dev);
875 if (flags & DL_FLAG_PM_RUNTIME) {
876 if (flags & DL_FLAG_RPM_ACTIVE)
877 refcount_inc(&link->rpm_active);
879 pm_runtime_new_link(consumer);
882 /* Determine the initial link state. */
883 if (flags & DL_FLAG_STATELESS)
884 link->status = DL_STATE_NONE;
886 device_link_init_status(link, consumer, supplier);
889 * Some callers expect the link creation during consumer driver probe to
890 * resume the supplier even without DL_FLAG_RPM_ACTIVE.
892 if (link->status == DL_STATE_CONSUMER_PROBE &&
893 flags & DL_FLAG_PM_RUNTIME)
894 pm_runtime_resume(supplier);
896 list_add_tail_rcu(&link->s_node, &supplier->links.consumers);
897 list_add_tail_rcu(&link->c_node, &consumer->links.suppliers);
899 if (flags & DL_FLAG_SYNC_STATE_ONLY) {
901 "Linked as a sync state only consumer to %s\n",
908 * Move the consumer and all of the devices depending on it to the end
909 * of dpm_list and the devices_kset list.
911 * It is necessary to hold dpm_list locked throughout all that or else
912 * we may end up suspending with a wrong ordering of it.
914 device_reorder_to_tail(consumer, NULL);
916 dev_dbg(consumer, "Linked as a consumer to %s\n", dev_name(supplier));
920 device_links_write_unlock();
922 if ((flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) && !link)
923 pm_runtime_put(supplier);
927 EXPORT_SYMBOL_GPL(device_link_add);
929 static void __device_link_del(struct kref *kref)
931 struct device_link *link = container_of(kref, struct device_link, kref);
933 dev_dbg(link->consumer, "Dropping the link to %s\n",
934 dev_name(link->supplier));
936 pm_runtime_drop_link(link);
938 device_link_remove_from_lists(link);
939 device_unregister(&link->link_dev);
942 static void device_link_put_kref(struct device_link *link)
944 if (link->flags & DL_FLAG_STATELESS)
945 kref_put(&link->kref, __device_link_del);
946 else if (!device_is_registered(link->consumer))
947 __device_link_del(&link->kref);
949 WARN(1, "Unable to drop a managed device link reference\n");
953 * device_link_del - Delete a stateless link between two devices.
954 * @link: Device link to delete.
956 * The caller must ensure proper synchronization of this function with runtime
957 * PM. If the link was added multiple times, it needs to be deleted as often.
958 * Care is required for hotplugged devices: Their links are purged on removal
959 * and calling device_link_del() is then no longer allowed.
961 void device_link_del(struct device_link *link)
963 device_links_write_lock();
964 device_link_put_kref(link);
965 device_links_write_unlock();
967 EXPORT_SYMBOL_GPL(device_link_del);
970 * device_link_remove - Delete a stateless link between two devices.
971 * @consumer: Consumer end of the link.
972 * @supplier: Supplier end of the link.
974 * The caller must ensure proper synchronization of this function with runtime
977 void device_link_remove(void *consumer, struct device *supplier)
979 struct device_link *link;
981 if (WARN_ON(consumer == supplier))
984 device_links_write_lock();
986 list_for_each_entry(link, &supplier->links.consumers, s_node) {
987 if (link->consumer == consumer) {
988 device_link_put_kref(link);
993 device_links_write_unlock();
995 EXPORT_SYMBOL_GPL(device_link_remove);
997 static void device_links_missing_supplier(struct device *dev)
999 struct device_link *link;
1001 list_for_each_entry(link, &dev->links.suppliers, c_node) {
1002 if (link->status != DL_STATE_CONSUMER_PROBE)
1005 if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
1006 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1008 WARN_ON(!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
1009 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1014 static bool dev_is_best_effort(struct device *dev)
1016 return (fw_devlink_best_effort && dev->can_match) ||
1017 (dev->fwnode && (dev->fwnode->flags & FWNODE_FLAG_BEST_EFFORT));
1020 static struct fwnode_handle *fwnode_links_check_suppliers(
1021 struct fwnode_handle *fwnode)
1023 struct fwnode_link *link;
1025 if (!fwnode || fw_devlink_is_permissive())
1028 list_for_each_entry(link, &fwnode->suppliers, c_hook)
1030 (FWLINK_FLAG_CYCLE | FWLINK_FLAG_IGNORE)))
1031 return link->supplier;
1037 * device_links_check_suppliers - Check presence of supplier drivers.
1038 * @dev: Consumer device.
1040 * Check links from this device to any suppliers. Walk the list of the device's
1041 * links to suppliers and see if all of them are available. If not, simply
1042 * return -EPROBE_DEFER.
1044 * We need to guarantee that the supplier will not go away after the check has
1045 * been positive here. It only can go away in __device_release_driver() and
1046 * that function checks the device's links to consumers. This means we need to
1047 * mark the link as "consumer probe in progress" to make the supplier removal
1048 * wait for us to complete (or bad things may happen).
1050 * Links without the DL_FLAG_MANAGED flag set are ignored.
1052 int device_links_check_suppliers(struct device *dev)
1054 struct device_link *link;
1055 int ret = 0, fwnode_ret = 0;
1056 struct fwnode_handle *sup_fw;
1059 * Device waiting for supplier to become available is not allowed to
1062 scoped_guard(mutex, &fwnode_link_lock) {
1063 sup_fw = fwnode_links_check_suppliers(dev->fwnode);
1065 if (dev_is_best_effort(dev))
1066 fwnode_ret = -EAGAIN;
1068 return dev_err_probe(dev, -EPROBE_DEFER,
1069 "wait for supplier %pfwf\n", sup_fw);
1073 device_links_write_lock();
1075 list_for_each_entry(link, &dev->links.suppliers, c_node) {
1076 if (!(link->flags & DL_FLAG_MANAGED))
1079 if (link->status != DL_STATE_AVAILABLE &&
1080 !(link->flags & DL_FLAG_SYNC_STATE_ONLY)) {
1082 if (dev_is_best_effort(dev) &&
1083 link->flags & DL_FLAG_INFERRED &&
1084 !link->supplier->can_match) {
1089 device_links_missing_supplier(dev);
1090 ret = dev_err_probe(dev, -EPROBE_DEFER,
1091 "supplier %s not ready\n", dev_name(link->supplier));
1094 WRITE_ONCE(link->status, DL_STATE_CONSUMER_PROBE);
1096 dev->links.status = DL_DEV_PROBING;
1098 device_links_write_unlock();
1100 return ret ? ret : fwnode_ret;
1104 * __device_links_queue_sync_state - Queue a device for sync_state() callback
1105 * @dev: Device to call sync_state() on
1106 * @list: List head to queue the @dev on
1108 * Queues a device for a sync_state() callback when the device links write lock
1109 * isn't held. This allows the sync_state() execution flow to use device links
1110 * APIs. The caller must ensure this function is called with
1111 * device_links_write_lock() held.
1113 * This function does a get_device() to make sure the device is not freed while
1116 * So the caller must also ensure that device_links_flush_sync_list() is called
1117 * as soon as the caller releases device_links_write_lock(). This is necessary
1118 * to make sure the sync_state() is called in a timely fashion and the
1119 * put_device() is called on this device.
1121 static void __device_links_queue_sync_state(struct device *dev,
1122 struct list_head *list)
1124 struct device_link *link;
1126 if (!dev_has_sync_state(dev))
1128 if (dev->state_synced)
1131 list_for_each_entry(link, &dev->links.consumers, s_node) {
1132 if (!(link->flags & DL_FLAG_MANAGED))
1134 if (link->status != DL_STATE_ACTIVE)
1139 * Set the flag here to avoid adding the same device to a list more
1140 * than once. This can happen if new consumers get added to the device
1141 * and probed before the list is flushed.
1143 dev->state_synced = true;
1145 if (WARN_ON(!list_empty(&dev->links.defer_sync)))
1149 list_add_tail(&dev->links.defer_sync, list);
1153 * device_links_flush_sync_list - Call sync_state() on a list of devices
1154 * @list: List of devices to call sync_state() on
1155 * @dont_lock_dev: Device for which lock is already held by the caller
1157 * Calls sync_state() on all the devices that have been queued for it. This
1158 * function is used in conjunction with __device_links_queue_sync_state(). The
1159 * @dont_lock_dev parameter is useful when this function is called from a
1160 * context where a device lock is already held.
1162 static void device_links_flush_sync_list(struct list_head *list,
1163 struct device *dont_lock_dev)
1165 struct device *dev, *tmp;
1167 list_for_each_entry_safe(dev, tmp, list, links.defer_sync) {
1168 list_del_init(&dev->links.defer_sync);
1170 if (dev != dont_lock_dev)
1173 dev_sync_state(dev);
1175 if (dev != dont_lock_dev)
1182 void device_links_supplier_sync_state_pause(void)
1184 device_links_write_lock();
1185 defer_sync_state_count++;
1186 device_links_write_unlock();
1189 void device_links_supplier_sync_state_resume(void)
1191 struct device *dev, *tmp;
1192 LIST_HEAD(sync_list);
1194 device_links_write_lock();
1195 if (!defer_sync_state_count) {
1196 WARN(true, "Unmatched sync_state pause/resume!");
1199 defer_sync_state_count--;
1200 if (defer_sync_state_count)
1203 list_for_each_entry_safe(dev, tmp, &deferred_sync, links.defer_sync) {
1205 * Delete from deferred_sync list before queuing it to
1206 * sync_list because defer_sync is used for both lists.
1208 list_del_init(&dev->links.defer_sync);
1209 __device_links_queue_sync_state(dev, &sync_list);
1212 device_links_write_unlock();
1214 device_links_flush_sync_list(&sync_list, NULL);
1217 static int sync_state_resume_initcall(void)
1219 device_links_supplier_sync_state_resume();
1222 late_initcall(sync_state_resume_initcall);
1224 static void __device_links_supplier_defer_sync(struct device *sup)
1226 if (list_empty(&sup->links.defer_sync) && dev_has_sync_state(sup))
1227 list_add_tail(&sup->links.defer_sync, &deferred_sync);
1230 static void device_link_drop_managed(struct device_link *link)
1232 link->flags &= ~DL_FLAG_MANAGED;
1233 WRITE_ONCE(link->status, DL_STATE_NONE);
1234 kref_put(&link->kref, __device_link_del);
1237 static ssize_t waiting_for_supplier_show(struct device *dev,
1238 struct device_attribute *attr,
1244 scoped_guard(mutex, &fwnode_link_lock)
1245 val = !!fwnode_links_check_suppliers(dev->fwnode);
1247 return sysfs_emit(buf, "%u\n", val);
1249 static DEVICE_ATTR_RO(waiting_for_supplier);
1252 * device_links_force_bind - Prepares device to be force bound
1253 * @dev: Consumer device.
1255 * device_bind_driver() force binds a device to a driver without calling any
1256 * driver probe functions. So the consumer really isn't going to wait for any
1257 * supplier before it's bound to the driver. We still want the device link
1258 * states to be sensible when this happens.
1260 * In preparation for device_bind_driver(), this function goes through each
1261 * supplier device links and checks if the supplier is bound. If it is, then
1262 * the device link status is set to CONSUMER_PROBE. Otherwise, the device link
1263 * is dropped. Links without the DL_FLAG_MANAGED flag set are ignored.
1265 void device_links_force_bind(struct device *dev)
1267 struct device_link *link, *ln;
1269 device_links_write_lock();
1271 list_for_each_entry_safe(link, ln, &dev->links.suppliers, c_node) {
1272 if (!(link->flags & DL_FLAG_MANAGED))
1275 if (link->status != DL_STATE_AVAILABLE) {
1276 device_link_drop_managed(link);
1279 WRITE_ONCE(link->status, DL_STATE_CONSUMER_PROBE);
1281 dev->links.status = DL_DEV_PROBING;
1283 device_links_write_unlock();
1287 * device_links_driver_bound - Update device links after probing its driver.
1288 * @dev: Device to update the links for.
1290 * The probe has been successful, so update links from this device to any
1291 * consumers by changing their status to "available".
1293 * Also change the status of @dev's links to suppliers to "active".
1295 * Links without the DL_FLAG_MANAGED flag set are ignored.
1297 void device_links_driver_bound(struct device *dev)
1299 struct device_link *link, *ln;
1300 LIST_HEAD(sync_list);
1303 * If a device binds successfully, it's expected to have created all
1304 * the device links it needs to or make new device links as it needs
1305 * them. So, fw_devlink no longer needs to create device links to any
1306 * of the device's suppliers.
1308 * Also, if a child firmware node of this bound device is not added as a
1309 * device by now, assume it is never going to be added. Make this bound
1310 * device the fallback supplier to the dangling consumers of the child
1311 * firmware node because this bound device is probably implementing the
1312 * child firmware node functionality and we don't want the dangling
1313 * consumers to defer probe indefinitely waiting for a device for the
1314 * child firmware node.
1316 if (dev->fwnode && dev->fwnode->dev == dev) {
1317 struct fwnode_handle *child;
1319 fwnode_links_purge_suppliers(dev->fwnode);
1321 guard(mutex)(&fwnode_link_lock);
1323 fwnode_for_each_available_child_node(dev->fwnode, child)
1324 __fw_devlink_pickup_dangling_consumers(child,
1326 __fw_devlink_link_to_consumers(dev);
1328 device_remove_file(dev, &dev_attr_waiting_for_supplier);
1330 device_links_write_lock();
1332 list_for_each_entry(link, &dev->links.consumers, s_node) {
1333 if (!(link->flags & DL_FLAG_MANAGED))
1337 * Links created during consumer probe may be in the "consumer
1338 * probe" state to start with if the supplier is still probing
1339 * when they are created and they may become "active" if the
1340 * consumer probe returns first. Skip them here.
1342 if (link->status == DL_STATE_CONSUMER_PROBE ||
1343 link->status == DL_STATE_ACTIVE)
1346 WARN_ON(link->status != DL_STATE_DORMANT);
1347 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1349 if (link->flags & DL_FLAG_AUTOPROBE_CONSUMER)
1350 driver_deferred_probe_add(link->consumer);
1353 if (defer_sync_state_count)
1354 __device_links_supplier_defer_sync(dev);
1356 __device_links_queue_sync_state(dev, &sync_list);
1358 list_for_each_entry_safe(link, ln, &dev->links.suppliers, c_node) {
1359 struct device *supplier;
1361 if (!(link->flags & DL_FLAG_MANAGED))
1364 supplier = link->supplier;
1365 if (link->flags & DL_FLAG_SYNC_STATE_ONLY) {
1367 * When DL_FLAG_SYNC_STATE_ONLY is set, it means no
1368 * other DL_MANAGED_LINK_FLAGS have been set. So, it's
1369 * save to drop the managed link completely.
1371 device_link_drop_managed(link);
1372 } else if (dev_is_best_effort(dev) &&
1373 link->flags & DL_FLAG_INFERRED &&
1374 link->status != DL_STATE_CONSUMER_PROBE &&
1375 !link->supplier->can_match) {
1377 * When dev_is_best_effort() is true, we ignore device
1378 * links to suppliers that don't have a driver. If the
1379 * consumer device still managed to probe, there's no
1380 * point in maintaining a device link in a weird state
1381 * (consumer probed before supplier). So delete it.
1383 device_link_drop_managed(link);
1385 WARN_ON(link->status != DL_STATE_CONSUMER_PROBE);
1386 WRITE_ONCE(link->status, DL_STATE_ACTIVE);
1390 * This needs to be done even for the deleted
1391 * DL_FLAG_SYNC_STATE_ONLY device link in case it was the last
1392 * device link that was preventing the supplier from getting a
1393 * sync_state() call.
1395 if (defer_sync_state_count)
1396 __device_links_supplier_defer_sync(supplier);
1398 __device_links_queue_sync_state(supplier, &sync_list);
1401 dev->links.status = DL_DEV_DRIVER_BOUND;
1403 device_links_write_unlock();
1405 device_links_flush_sync_list(&sync_list, dev);
1409 * __device_links_no_driver - Update links of a device without a driver.
1410 * @dev: Device without a drvier.
1412 * Delete all non-persistent links from this device to any suppliers.
1414 * Persistent links stay around, but their status is changed to "available",
1415 * unless they already are in the "supplier unbind in progress" state in which
1416 * case they need not be updated.
1418 * Links without the DL_FLAG_MANAGED flag set are ignored.
1420 static void __device_links_no_driver(struct device *dev)
1422 struct device_link *link, *ln;
1424 list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1425 if (!(link->flags & DL_FLAG_MANAGED))
1428 if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER) {
1429 device_link_drop_managed(link);
1433 if (link->status != DL_STATE_CONSUMER_PROBE &&
1434 link->status != DL_STATE_ACTIVE)
1437 if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
1438 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1440 WARN_ON(!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
1441 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1445 dev->links.status = DL_DEV_NO_DRIVER;
1449 * device_links_no_driver - Update links after failing driver probe.
1450 * @dev: Device whose driver has just failed to probe.
1452 * Clean up leftover links to consumers for @dev and invoke
1453 * %__device_links_no_driver() to update links to suppliers for it as
1456 * Links without the DL_FLAG_MANAGED flag set are ignored.
1458 void device_links_no_driver(struct device *dev)
1460 struct device_link *link;
1462 device_links_write_lock();
1464 list_for_each_entry(link, &dev->links.consumers, s_node) {
1465 if (!(link->flags & DL_FLAG_MANAGED))
1469 * The probe has failed, so if the status of the link is
1470 * "consumer probe" or "active", it must have been added by
1471 * a probing consumer while this device was still probing.
1472 * Change its state to "dormant", as it represents a valid
1473 * relationship, but it is not functionally meaningful.
1475 if (link->status == DL_STATE_CONSUMER_PROBE ||
1476 link->status == DL_STATE_ACTIVE)
1477 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1480 __device_links_no_driver(dev);
1482 device_links_write_unlock();
1486 * device_links_driver_cleanup - Update links after driver removal.
1487 * @dev: Device whose driver has just gone away.
1489 * Update links to consumers for @dev by changing their status to "dormant" and
1490 * invoke %__device_links_no_driver() to update links to suppliers for it as
1493 * Links without the DL_FLAG_MANAGED flag set are ignored.
1495 void device_links_driver_cleanup(struct device *dev)
1497 struct device_link *link, *ln;
1499 device_links_write_lock();
1501 list_for_each_entry_safe(link, ln, &dev->links.consumers, s_node) {
1502 if (!(link->flags & DL_FLAG_MANAGED))
1505 WARN_ON(link->flags & DL_FLAG_AUTOREMOVE_CONSUMER);
1506 WARN_ON(link->status != DL_STATE_SUPPLIER_UNBIND);
1509 * autoremove the links between this @dev and its consumer
1510 * devices that are not active, i.e. where the link state
1511 * has moved to DL_STATE_SUPPLIER_UNBIND.
1513 if (link->status == DL_STATE_SUPPLIER_UNBIND &&
1514 link->flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
1515 device_link_drop_managed(link);
1517 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1520 list_del_init(&dev->links.defer_sync);
1521 __device_links_no_driver(dev);
1523 device_links_write_unlock();
1527 * device_links_busy - Check if there are any busy links to consumers.
1528 * @dev: Device to check.
1530 * Check each consumer of the device and return 'true' if its link's status
1531 * is one of "consumer probe" or "active" (meaning that the given consumer is
1532 * probing right now or its driver is present). Otherwise, change the link
1533 * state to "supplier unbind" to prevent the consumer from being probed
1534 * successfully going forward.
1536 * Return 'false' if there are no probing or active consumers.
1538 * Links without the DL_FLAG_MANAGED flag set are ignored.
1540 bool device_links_busy(struct device *dev)
1542 struct device_link *link;
1545 device_links_write_lock();
1547 list_for_each_entry(link, &dev->links.consumers, s_node) {
1548 if (!(link->flags & DL_FLAG_MANAGED))
1551 if (link->status == DL_STATE_CONSUMER_PROBE
1552 || link->status == DL_STATE_ACTIVE) {
1556 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1559 dev->links.status = DL_DEV_UNBINDING;
1561 device_links_write_unlock();
1566 * device_links_unbind_consumers - Force unbind consumers of the given device.
1567 * @dev: Device to unbind the consumers of.
1569 * Walk the list of links to consumers for @dev and if any of them is in the
1570 * "consumer probe" state, wait for all device probes in progress to complete
1573 * If that's not the case, change the status of the link to "supplier unbind"
1574 * and check if the link was in the "active" state. If so, force the consumer
1575 * driver to unbind and start over (the consumer will not re-probe as we have
1576 * changed the state of the link already).
1578 * Links without the DL_FLAG_MANAGED flag set are ignored.
1580 void device_links_unbind_consumers(struct device *dev)
1582 struct device_link *link;
1585 device_links_write_lock();
1587 list_for_each_entry(link, &dev->links.consumers, s_node) {
1588 enum device_link_state status;
1590 if (!(link->flags & DL_FLAG_MANAGED) ||
1591 link->flags & DL_FLAG_SYNC_STATE_ONLY)
1594 status = link->status;
1595 if (status == DL_STATE_CONSUMER_PROBE) {
1596 device_links_write_unlock();
1598 wait_for_device_probe();
1601 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1602 if (status == DL_STATE_ACTIVE) {
1603 struct device *consumer = link->consumer;
1605 get_device(consumer);
1607 device_links_write_unlock();
1609 device_release_driver_internal(consumer, NULL,
1611 put_device(consumer);
1616 device_links_write_unlock();
1620 * device_links_purge - Delete existing links to other devices.
1621 * @dev: Target device.
1623 static void device_links_purge(struct device *dev)
1625 struct device_link *link, *ln;
1627 if (dev->class == &devlink_class)
1631 * Delete all of the remaining links from this device to any other
1632 * devices (either consumers or suppliers).
1634 device_links_write_lock();
1636 list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1637 WARN_ON(link->status == DL_STATE_ACTIVE);
1638 __device_link_del(&link->kref);
1641 list_for_each_entry_safe_reverse(link, ln, &dev->links.consumers, s_node) {
1642 WARN_ON(link->status != DL_STATE_DORMANT &&
1643 link->status != DL_STATE_NONE);
1644 __device_link_del(&link->kref);
1647 device_links_write_unlock();
1650 #define FW_DEVLINK_FLAGS_PERMISSIVE (DL_FLAG_INFERRED | \
1651 DL_FLAG_SYNC_STATE_ONLY)
1652 #define FW_DEVLINK_FLAGS_ON (DL_FLAG_INFERRED | \
1653 DL_FLAG_AUTOPROBE_CONSUMER)
1654 #define FW_DEVLINK_FLAGS_RPM (FW_DEVLINK_FLAGS_ON | \
1657 static u32 fw_devlink_flags = FW_DEVLINK_FLAGS_RPM;
1658 static int __init fw_devlink_setup(char *arg)
1663 if (strcmp(arg, "off") == 0) {
1664 fw_devlink_flags = 0;
1665 } else if (strcmp(arg, "permissive") == 0) {
1666 fw_devlink_flags = FW_DEVLINK_FLAGS_PERMISSIVE;
1667 } else if (strcmp(arg, "on") == 0) {
1668 fw_devlink_flags = FW_DEVLINK_FLAGS_ON;
1669 } else if (strcmp(arg, "rpm") == 0) {
1670 fw_devlink_flags = FW_DEVLINK_FLAGS_RPM;
1674 early_param("fw_devlink", fw_devlink_setup);
1676 static bool fw_devlink_strict;
1677 static int __init fw_devlink_strict_setup(char *arg)
1679 return kstrtobool(arg, &fw_devlink_strict);
1681 early_param("fw_devlink.strict", fw_devlink_strict_setup);
1683 #define FW_DEVLINK_SYNC_STATE_STRICT 0
1684 #define FW_DEVLINK_SYNC_STATE_TIMEOUT 1
1686 #ifndef CONFIG_FW_DEVLINK_SYNC_STATE_TIMEOUT
1687 static int fw_devlink_sync_state;
1689 static int fw_devlink_sync_state = FW_DEVLINK_SYNC_STATE_TIMEOUT;
1692 static int __init fw_devlink_sync_state_setup(char *arg)
1697 if (strcmp(arg, "strict") == 0) {
1698 fw_devlink_sync_state = FW_DEVLINK_SYNC_STATE_STRICT;
1700 } else if (strcmp(arg, "timeout") == 0) {
1701 fw_devlink_sync_state = FW_DEVLINK_SYNC_STATE_TIMEOUT;
1706 early_param("fw_devlink.sync_state", fw_devlink_sync_state_setup);
1708 static inline u32 fw_devlink_get_flags(u8 fwlink_flags)
1710 if (fwlink_flags & FWLINK_FLAG_CYCLE)
1711 return FW_DEVLINK_FLAGS_PERMISSIVE | DL_FLAG_CYCLE;
1713 return fw_devlink_flags;
1716 static bool fw_devlink_is_permissive(void)
1718 return fw_devlink_flags == FW_DEVLINK_FLAGS_PERMISSIVE;
1721 bool fw_devlink_is_strict(void)
1723 return fw_devlink_strict && !fw_devlink_is_permissive();
1726 static void fw_devlink_parse_fwnode(struct fwnode_handle *fwnode)
1728 if (fwnode->flags & FWNODE_FLAG_LINKS_ADDED)
1731 fwnode_call_int_op(fwnode, add_links);
1732 fwnode->flags |= FWNODE_FLAG_LINKS_ADDED;
1735 static void fw_devlink_parse_fwtree(struct fwnode_handle *fwnode)
1737 struct fwnode_handle *child = NULL;
1739 fw_devlink_parse_fwnode(fwnode);
1741 while ((child = fwnode_get_next_available_child_node(fwnode, child)))
1742 fw_devlink_parse_fwtree(child);
1745 static void fw_devlink_relax_link(struct device_link *link)
1747 if (!(link->flags & DL_FLAG_INFERRED))
1750 if (device_link_flag_is_sync_state_only(link->flags))
1753 pm_runtime_drop_link(link);
1754 link->flags = DL_FLAG_MANAGED | FW_DEVLINK_FLAGS_PERMISSIVE;
1755 dev_dbg(link->consumer, "Relaxing link with %s\n",
1756 dev_name(link->supplier));
1759 static int fw_devlink_no_driver(struct device *dev, void *data)
1761 struct device_link *link = to_devlink(dev);
1763 if (!link->supplier->can_match)
1764 fw_devlink_relax_link(link);
1769 void fw_devlink_drivers_done(void)
1771 fw_devlink_drv_reg_done = true;
1772 device_links_write_lock();
1773 class_for_each_device(&devlink_class, NULL, NULL,
1774 fw_devlink_no_driver);
1775 device_links_write_unlock();
1778 static int fw_devlink_dev_sync_state(struct device *dev, void *data)
1780 struct device_link *link = to_devlink(dev);
1781 struct device *sup = link->supplier;
1783 if (!(link->flags & DL_FLAG_MANAGED) ||
1784 link->status == DL_STATE_ACTIVE || sup->state_synced ||
1785 !dev_has_sync_state(sup))
1788 if (fw_devlink_sync_state == FW_DEVLINK_SYNC_STATE_STRICT) {
1789 dev_warn(sup, "sync_state() pending due to %s\n",
1790 dev_name(link->consumer));
1794 if (!list_empty(&sup->links.defer_sync))
1797 dev_warn(sup, "Timed out. Forcing sync_state()\n");
1798 sup->state_synced = true;
1800 list_add_tail(&sup->links.defer_sync, data);
1805 void fw_devlink_probing_done(void)
1807 LIST_HEAD(sync_list);
1809 device_links_write_lock();
1810 class_for_each_device(&devlink_class, NULL, &sync_list,
1811 fw_devlink_dev_sync_state);
1812 device_links_write_unlock();
1813 device_links_flush_sync_list(&sync_list, NULL);
1817 * wait_for_init_devices_probe - Try to probe any device needed for init
1819 * Some devices might need to be probed and bound successfully before the kernel
1820 * boot sequence can finish and move on to init/userspace. For example, a
1821 * network interface might need to be bound to be able to mount a NFS rootfs.
1823 * With fw_devlink=on by default, some of these devices might be blocked from
1824 * probing because they are waiting on a optional supplier that doesn't have a
1825 * driver. While fw_devlink will eventually identify such devices and unblock
1826 * the probing automatically, it might be too late by the time it unblocks the
1827 * probing of devices. For example, the IP4 autoconfig might timeout before
1828 * fw_devlink unblocks probing of the network interface.
1830 * This function is available to temporarily try and probe all devices that have
1831 * a driver even if some of their suppliers haven't been added or don't have
1834 * The drivers can then decide which of the suppliers are optional vs mandatory
1835 * and probe the device if possible. By the time this function returns, all such
1836 * "best effort" probes are guaranteed to be completed. If a device successfully
1837 * probes in this mode, we delete all fw_devlink discovered dependencies of that
1838 * device where the supplier hasn't yet probed successfully because they have to
1839 * be optional dependencies.
1841 * Any devices that didn't successfully probe go back to being treated as if
1842 * this function was never called.
1844 * This also means that some devices that aren't needed for init and could have
1845 * waited for their optional supplier to probe (when the supplier's module is
1846 * loaded later on) would end up probing prematurely with limited functionality.
1847 * So call this function only when boot would fail without it.
1849 void __init wait_for_init_devices_probe(void)
1851 if (!fw_devlink_flags || fw_devlink_is_permissive())
1855 * Wait for all ongoing probes to finish so that the "best effort" is
1856 * only applied to devices that can't probe otherwise.
1858 wait_for_device_probe();
1860 pr_info("Trying to probe devices needed for running init ...\n");
1861 fw_devlink_best_effort = true;
1862 driver_deferred_probe_trigger();
1865 * Wait for all "best effort" probes to finish before going back to
1866 * normal enforcement.
1868 wait_for_device_probe();
1869 fw_devlink_best_effort = false;
1872 static void fw_devlink_unblock_consumers(struct device *dev)
1874 struct device_link *link;
1876 if (!fw_devlink_flags || fw_devlink_is_permissive())
1879 device_links_write_lock();
1880 list_for_each_entry(link, &dev->links.consumers, s_node)
1881 fw_devlink_relax_link(link);
1882 device_links_write_unlock();
1885 #define get_dev_from_fwnode(fwnode) get_device((fwnode)->dev)
1887 static bool fwnode_init_without_drv(struct fwnode_handle *fwnode)
1892 if (!(fwnode->flags & FWNODE_FLAG_INITIALIZED))
1895 dev = get_dev_from_fwnode(fwnode);
1896 ret = !dev || dev->links.status == DL_DEV_NO_DRIVER;
1902 static bool fwnode_ancestor_init_without_drv(struct fwnode_handle *fwnode)
1904 struct fwnode_handle *parent;
1906 fwnode_for_each_parent_node(fwnode, parent) {
1907 if (fwnode_init_without_drv(parent)) {
1908 fwnode_handle_put(parent);
1917 * fwnode_is_ancestor_of - Test if @ancestor is ancestor of @child
1918 * @ancestor: Firmware which is tested for being an ancestor
1919 * @child: Firmware which is tested for being the child
1921 * A node is considered an ancestor of itself too.
1923 * Return: true if @ancestor is an ancestor of @child. Otherwise, returns false.
1925 static bool fwnode_is_ancestor_of(const struct fwnode_handle *ancestor,
1926 const struct fwnode_handle *child)
1928 struct fwnode_handle *parent;
1930 if (IS_ERR_OR_NULL(ancestor))
1933 if (child == ancestor)
1936 fwnode_for_each_parent_node(child, parent) {
1937 if (parent == ancestor) {
1938 fwnode_handle_put(parent);
1946 * fwnode_get_next_parent_dev - Find device of closest ancestor fwnode
1947 * @fwnode: firmware node
1949 * Given a firmware node (@fwnode), this function finds its closest ancestor
1950 * firmware node that has a corresponding struct device and returns that struct
1953 * The caller is responsible for calling put_device() on the returned device
1956 * Return: a pointer to the device of the @fwnode's closest ancestor.
1958 static struct device *fwnode_get_next_parent_dev(const struct fwnode_handle *fwnode)
1960 struct fwnode_handle *parent;
1963 fwnode_for_each_parent_node(fwnode, parent) {
1964 dev = get_dev_from_fwnode(parent);
1966 fwnode_handle_put(parent);
1974 * __fw_devlink_relax_cycles - Relax and mark dependency cycles.
1975 * @con: Potential consumer device.
1976 * @sup_handle: Potential supplier's fwnode.
1978 * Needs to be called with fwnode_lock and device link lock held.
1980 * Check if @sup_handle or any of its ancestors or suppliers direct/indirectly
1981 * depend on @con. This function can detect multiple cyles between @sup_handle
1982 * and @con. When such dependency cycles are found, convert all device links
1983 * created solely by fw_devlink into SYNC_STATE_ONLY device links. Also, mark
1984 * all fwnode links in the cycle with FWLINK_FLAG_CYCLE so that when they are
1985 * converted into a device link in the future, they are created as
1986 * SYNC_STATE_ONLY device links. This is the equivalent of doing
1987 * fw_devlink=permissive just between the devices in the cycle. We need to do
1988 * this because, at this point, fw_devlink can't tell which of these
1989 * dependencies is not a real dependency.
1991 * Return true if one or more cycles were found. Otherwise, return false.
1993 static bool __fw_devlink_relax_cycles(struct device *con,
1994 struct fwnode_handle *sup_handle)
1996 struct device *sup_dev = NULL, *par_dev = NULL;
1997 struct fwnode_link *link;
1998 struct device_link *dev_link;
2005 * We aren't trying to find all cycles. Just a cycle between con and
2008 if (sup_handle->flags & FWNODE_FLAG_VISITED)
2011 sup_handle->flags |= FWNODE_FLAG_VISITED;
2013 sup_dev = get_dev_from_fwnode(sup_handle);
2015 /* Termination condition. */
2016 if (sup_dev == con) {
2017 pr_debug("----- cycle: start -----\n");
2023 * If sup_dev is bound to a driver and @con hasn't started binding to a
2024 * driver, sup_dev can't be a consumer of @con. So, no need to check
2027 if (sup_dev && sup_dev->links.status == DL_DEV_DRIVER_BOUND &&
2028 con->links.status == DL_DEV_NO_DRIVER) {
2033 list_for_each_entry(link, &sup_handle->suppliers, c_hook) {
2034 if (link->flags & FWLINK_FLAG_IGNORE)
2037 if (__fw_devlink_relax_cycles(con, link->supplier)) {
2038 __fwnode_link_cycle(link);
2044 * Give priority to device parent over fwnode parent to account for any
2045 * quirks in how fwnodes are converted to devices.
2048 par_dev = get_device(sup_dev->parent);
2050 par_dev = fwnode_get_next_parent_dev(sup_handle);
2052 if (par_dev && __fw_devlink_relax_cycles(con, par_dev->fwnode)) {
2053 pr_debug("%pfwf: cycle: child of %pfwf\n", sup_handle,
2061 list_for_each_entry(dev_link, &sup_dev->links.suppliers, c_node) {
2063 * Ignore a SYNC_STATE_ONLY flag only if it wasn't marked as
2064 * such due to a cycle.
2066 if (device_link_flag_is_sync_state_only(dev_link->flags) &&
2067 !(dev_link->flags & DL_FLAG_CYCLE))
2070 if (__fw_devlink_relax_cycles(con,
2071 dev_link->supplier->fwnode)) {
2072 pr_debug("%pfwf: cycle: depends on %pfwf\n", sup_handle,
2073 dev_link->supplier->fwnode);
2074 fw_devlink_relax_link(dev_link);
2075 dev_link->flags |= DL_FLAG_CYCLE;
2081 sup_handle->flags &= ~FWNODE_FLAG_VISITED;
2082 put_device(sup_dev);
2083 put_device(par_dev);
2088 * fw_devlink_create_devlink - Create a device link from a consumer to fwnode
2089 * @con: consumer device for the device link
2090 * @sup_handle: fwnode handle of supplier
2091 * @link: fwnode link that's being converted to a device link
2093 * This function will try to create a device link between the consumer device
2094 * @con and the supplier device represented by @sup_handle.
2096 * The supplier has to be provided as a fwnode because incorrect cycles in
2097 * fwnode links can sometimes cause the supplier device to never be created.
2098 * This function detects such cases and returns an error if it cannot create a
2099 * device link from the consumer to a missing supplier.
2102 * 0 on successfully creating a device link
2103 * -EINVAL if the device link cannot be created as expected
2104 * -EAGAIN if the device link cannot be created right now, but it may be
2105 * possible to do that in the future
2107 static int fw_devlink_create_devlink(struct device *con,
2108 struct fwnode_handle *sup_handle,
2109 struct fwnode_link *link)
2111 struct device *sup_dev;
2115 if (link->flags & FWLINK_FLAG_IGNORE)
2118 if (con->fwnode == link->consumer)
2119 flags = fw_devlink_get_flags(link->flags);
2121 flags = FW_DEVLINK_FLAGS_PERMISSIVE;
2124 * In some cases, a device P might also be a supplier to its child node
2125 * C. However, this would defer the probe of C until the probe of P
2126 * completes successfully. This is perfectly fine in the device driver
2127 * model. device_add() doesn't guarantee probe completion of the device
2128 * by the time it returns.
2130 * However, there are a few drivers that assume C will finish probing
2131 * as soon as it's added and before P finishes probing. So, we provide
2132 * a flag to let fw_devlink know not to delay the probe of C until the
2133 * probe of P completes successfully.
2135 * When such a flag is set, we can't create device links where P is the
2136 * supplier of C as that would delay the probe of C.
2138 if (sup_handle->flags & FWNODE_FLAG_NEEDS_CHILD_BOUND_ON_ADD &&
2139 fwnode_is_ancestor_of(sup_handle, con->fwnode))
2143 * SYNC_STATE_ONLY device links don't block probing and supports cycles.
2144 * So, one might expect that cycle detection isn't necessary for them.
2145 * However, if the device link was marked as SYNC_STATE_ONLY because
2146 * it's part of a cycle, then we still need to do cycle detection. This
2147 * is because the consumer and supplier might be part of multiple cycles
2148 * and we need to detect all those cycles.
2150 if (!device_link_flag_is_sync_state_only(flags) ||
2151 flags & DL_FLAG_CYCLE) {
2152 device_links_write_lock();
2153 if (__fw_devlink_relax_cycles(con, sup_handle)) {
2154 __fwnode_link_cycle(link);
2155 flags = fw_devlink_get_flags(link->flags);
2156 pr_debug("----- cycle: end -----\n");
2157 dev_info(con, "Fixed dependency cycle(s) with %pfwf\n",
2160 device_links_write_unlock();
2163 if (sup_handle->flags & FWNODE_FLAG_NOT_DEVICE)
2164 sup_dev = fwnode_get_next_parent_dev(sup_handle);
2166 sup_dev = get_dev_from_fwnode(sup_handle);
2170 * If it's one of those drivers that don't actually bind to
2171 * their device using driver core, then don't wait on this
2172 * supplier device indefinitely.
2174 if (sup_dev->links.status == DL_DEV_NO_DRIVER &&
2175 sup_handle->flags & FWNODE_FLAG_INITIALIZED) {
2177 "Not linking %pfwf - dev might never probe\n",
2183 if (con != sup_dev && !device_link_add(con, sup_dev, flags)) {
2184 dev_err(con, "Failed to create device link (0x%x) with %s\n",
2185 flags, dev_name(sup_dev));
2193 * Supplier or supplier's ancestor already initialized without a struct
2194 * device or being probed by a driver.
2196 if (fwnode_init_without_drv(sup_handle) ||
2197 fwnode_ancestor_init_without_drv(sup_handle)) {
2198 dev_dbg(con, "Not linking %pfwf - might never become dev\n",
2205 put_device(sup_dev);
2210 * __fw_devlink_link_to_consumers - Create device links to consumers of a device
2211 * @dev: Device that needs to be linked to its consumers
2213 * This function looks at all the consumer fwnodes of @dev and creates device
2214 * links between the consumer device and @dev (supplier).
2216 * If the consumer device has not been added yet, then this function creates a
2217 * SYNC_STATE_ONLY link between @dev (supplier) and the closest ancestor device
2218 * of the consumer fwnode. This is necessary to make sure @dev doesn't get a
2219 * sync_state() callback before the real consumer device gets to be added and
2222 * Once device links are created from the real consumer to @dev (supplier), the
2223 * fwnode links are deleted.
2225 static void __fw_devlink_link_to_consumers(struct device *dev)
2227 struct fwnode_handle *fwnode = dev->fwnode;
2228 struct fwnode_link *link, *tmp;
2230 list_for_each_entry_safe(link, tmp, &fwnode->consumers, s_hook) {
2231 struct device *con_dev;
2232 bool own_link = true;
2235 con_dev = get_dev_from_fwnode(link->consumer);
2237 * If consumer device is not available yet, make a "proxy"
2238 * SYNC_STATE_ONLY link from the consumer's parent device to
2239 * the supplier device. This is necessary to make sure the
2240 * supplier doesn't get a sync_state() callback before the real
2241 * consumer can create a device link to the supplier.
2243 * This proxy link step is needed to handle the case where the
2244 * consumer's parent device is added before the supplier.
2247 con_dev = fwnode_get_next_parent_dev(link->consumer);
2249 * However, if the consumer's parent device is also the
2250 * parent of the supplier, don't create a
2251 * consumer-supplier link from the parent to its child
2252 * device. Such a dependency is impossible.
2255 fwnode_is_ancestor_of(con_dev->fwnode, fwnode)) {
2256 put_device(con_dev);
2266 ret = fw_devlink_create_devlink(con_dev, fwnode, link);
2267 put_device(con_dev);
2268 if (!own_link || ret == -EAGAIN)
2271 __fwnode_link_del(link);
2276 * __fw_devlink_link_to_suppliers - Create device links to suppliers of a device
2277 * @dev: The consumer device that needs to be linked to its suppliers
2278 * @fwnode: Root of the fwnode tree that is used to create device links
2280 * This function looks at all the supplier fwnodes of fwnode tree rooted at
2281 * @fwnode and creates device links between @dev (consumer) and all the
2282 * supplier devices of the entire fwnode tree at @fwnode.
2284 * The function creates normal (non-SYNC_STATE_ONLY) device links between @dev
2285 * and the real suppliers of @dev. Once these device links are created, the
2286 * fwnode links are deleted.
2288 * In addition, it also looks at all the suppliers of the entire fwnode tree
2289 * because some of the child devices of @dev that have not been added yet
2290 * (because @dev hasn't probed) might already have their suppliers added to
2291 * driver core. So, this function creates SYNC_STATE_ONLY device links between
2292 * @dev (consumer) and these suppliers to make sure they don't execute their
2293 * sync_state() callbacks before these child devices have a chance to create
2294 * their device links. The fwnode links that correspond to the child devices
2295 * aren't delete because they are needed later to create the device links
2296 * between the real consumer and supplier devices.
2298 static void __fw_devlink_link_to_suppliers(struct device *dev,
2299 struct fwnode_handle *fwnode)
2301 bool own_link = (dev->fwnode == fwnode);
2302 struct fwnode_link *link, *tmp;
2303 struct fwnode_handle *child = NULL;
2305 list_for_each_entry_safe(link, tmp, &fwnode->suppliers, c_hook) {
2307 struct fwnode_handle *sup = link->supplier;
2309 ret = fw_devlink_create_devlink(dev, sup, link);
2310 if (!own_link || ret == -EAGAIN)
2313 __fwnode_link_del(link);
2317 * Make "proxy" SYNC_STATE_ONLY device links to represent the needs of
2318 * all the descendants. This proxy link step is needed to handle the
2319 * case where the supplier is added before the consumer's parent device
2322 while ((child = fwnode_get_next_available_child_node(fwnode, child)))
2323 __fw_devlink_link_to_suppliers(dev, child);
2326 static void fw_devlink_link_device(struct device *dev)
2328 struct fwnode_handle *fwnode = dev->fwnode;
2330 if (!fw_devlink_flags)
2333 fw_devlink_parse_fwtree(fwnode);
2335 guard(mutex)(&fwnode_link_lock);
2337 __fw_devlink_link_to_consumers(dev);
2338 __fw_devlink_link_to_suppliers(dev, fwnode);
2341 /* Device links support end. */
2343 static struct kobject *dev_kobj;
2346 static struct kobject *sysfs_dev_char_kobj;
2348 /* /sys/dev/block */
2349 static struct kobject *sysfs_dev_block_kobj;
2351 static DEFINE_MUTEX(device_hotplug_lock);
2353 void lock_device_hotplug(void)
2355 mutex_lock(&device_hotplug_lock);
2358 void unlock_device_hotplug(void)
2360 mutex_unlock(&device_hotplug_lock);
2363 int lock_device_hotplug_sysfs(void)
2365 if (mutex_trylock(&device_hotplug_lock))
2368 /* Avoid busy looping (5 ms of sleep should do). */
2370 return restart_syscall();
2374 static inline int device_is_not_partition(struct device *dev)
2376 return !(dev->type == &part_type);
2379 static inline int device_is_not_partition(struct device *dev)
2385 static void device_platform_notify(struct device *dev)
2387 acpi_device_notify(dev);
2389 software_node_notify(dev);
2392 static void device_platform_notify_remove(struct device *dev)
2394 software_node_notify_remove(dev);
2396 acpi_device_notify_remove(dev);
2400 * dev_driver_string - Return a device's driver name, if at all possible
2401 * @dev: struct device to get the name of
2403 * Will return the device's driver's name if it is bound to a device. If
2404 * the device is not bound to a driver, it will return the name of the bus
2405 * it is attached to. If it is not attached to a bus either, an empty
2406 * string will be returned.
2408 const char *dev_driver_string(const struct device *dev)
2410 struct device_driver *drv;
2412 /* dev->driver can change to NULL underneath us because of unbinding,
2413 * so be careful about accessing it. dev->bus and dev->class should
2414 * never change once they are set, so they don't need special care.
2416 drv = READ_ONCE(dev->driver);
2417 return drv ? drv->name : dev_bus_name(dev);
2419 EXPORT_SYMBOL(dev_driver_string);
2421 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
2423 static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
2426 struct device_attribute *dev_attr = to_dev_attr(attr);
2427 struct device *dev = kobj_to_dev(kobj);
2431 ret = dev_attr->show(dev, dev_attr, buf);
2432 if (ret >= (ssize_t)PAGE_SIZE) {
2433 printk("dev_attr_show: %pS returned bad count\n",
2439 static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
2440 const char *buf, size_t count)
2442 struct device_attribute *dev_attr = to_dev_attr(attr);
2443 struct device *dev = kobj_to_dev(kobj);
2446 if (dev_attr->store)
2447 ret = dev_attr->store(dev, dev_attr, buf, count);
2451 static const struct sysfs_ops dev_sysfs_ops = {
2452 .show = dev_attr_show,
2453 .store = dev_attr_store,
2456 #define to_ext_attr(x) container_of(x, struct dev_ext_attribute, attr)
2458 ssize_t device_store_ulong(struct device *dev,
2459 struct device_attribute *attr,
2460 const char *buf, size_t size)
2462 struct dev_ext_attribute *ea = to_ext_attr(attr);
2466 ret = kstrtoul(buf, 0, &new);
2469 *(unsigned long *)(ea->var) = new;
2470 /* Always return full write size even if we didn't consume all */
2473 EXPORT_SYMBOL_GPL(device_store_ulong);
2475 ssize_t device_show_ulong(struct device *dev,
2476 struct device_attribute *attr,
2479 struct dev_ext_attribute *ea = to_ext_attr(attr);
2480 return sysfs_emit(buf, "%lx\n", *(unsigned long *)(ea->var));
2482 EXPORT_SYMBOL_GPL(device_show_ulong);
2484 ssize_t device_store_int(struct device *dev,
2485 struct device_attribute *attr,
2486 const char *buf, size_t size)
2488 struct dev_ext_attribute *ea = to_ext_attr(attr);
2492 ret = kstrtol(buf, 0, &new);
2496 if (new > INT_MAX || new < INT_MIN)
2498 *(int *)(ea->var) = new;
2499 /* Always return full write size even if we didn't consume all */
2502 EXPORT_SYMBOL_GPL(device_store_int);
2504 ssize_t device_show_int(struct device *dev,
2505 struct device_attribute *attr,
2508 struct dev_ext_attribute *ea = to_ext_attr(attr);
2510 return sysfs_emit(buf, "%d\n", *(int *)(ea->var));
2512 EXPORT_SYMBOL_GPL(device_show_int);
2514 ssize_t device_store_bool(struct device *dev, struct device_attribute *attr,
2515 const char *buf, size_t size)
2517 struct dev_ext_attribute *ea = to_ext_attr(attr);
2519 if (kstrtobool(buf, ea->var) < 0)
2524 EXPORT_SYMBOL_GPL(device_store_bool);
2526 ssize_t device_show_bool(struct device *dev, struct device_attribute *attr,
2529 struct dev_ext_attribute *ea = to_ext_attr(attr);
2531 return sysfs_emit(buf, "%d\n", *(bool *)(ea->var));
2533 EXPORT_SYMBOL_GPL(device_show_bool);
2535 ssize_t device_show_string(struct device *dev,
2536 struct device_attribute *attr, char *buf)
2538 struct dev_ext_attribute *ea = to_ext_attr(attr);
2540 return sysfs_emit(buf, "%s\n", (char *)ea->var);
2542 EXPORT_SYMBOL_GPL(device_show_string);
2545 * device_release - free device structure.
2546 * @kobj: device's kobject.
2548 * This is called once the reference count for the object
2549 * reaches 0. We forward the call to the device's release
2550 * method, which should handle actually freeing the structure.
2552 static void device_release(struct kobject *kobj)
2554 struct device *dev = kobj_to_dev(kobj);
2555 struct device_private *p = dev->p;
2558 * Some platform devices are driven without driver attached
2559 * and managed resources may have been acquired. Make sure
2560 * all resources are released.
2562 * Drivers still can add resources into device after device
2563 * is deleted but alive, so release devres here to avoid
2564 * possible memory leak.
2566 devres_release_all(dev);
2568 kfree(dev->dma_range_map);
2572 else if (dev->type && dev->type->release)
2573 dev->type->release(dev);
2574 else if (dev->class && dev->class->dev_release)
2575 dev->class->dev_release(dev);
2577 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",
2582 static const void *device_namespace(const struct kobject *kobj)
2584 const struct device *dev = kobj_to_dev(kobj);
2585 const void *ns = NULL;
2587 if (dev->class && dev->class->namespace)
2588 ns = dev->class->namespace(dev);
2593 static void device_get_ownership(const struct kobject *kobj, kuid_t *uid, kgid_t *gid)
2595 const struct device *dev = kobj_to_dev(kobj);
2597 if (dev->class && dev->class->get_ownership)
2598 dev->class->get_ownership(dev, uid, gid);
2601 static const struct kobj_type device_ktype = {
2602 .release = device_release,
2603 .sysfs_ops = &dev_sysfs_ops,
2604 .namespace = device_namespace,
2605 .get_ownership = device_get_ownership,
2609 static int dev_uevent_filter(const struct kobject *kobj)
2611 const struct kobj_type *ktype = get_ktype(kobj);
2613 if (ktype == &device_ktype) {
2614 const struct device *dev = kobj_to_dev(kobj);
2623 static const char *dev_uevent_name(const struct kobject *kobj)
2625 const struct device *dev = kobj_to_dev(kobj);
2628 return dev->bus->name;
2630 return dev->class->name;
2634 static int dev_uevent(const struct kobject *kobj, struct kobj_uevent_env *env)
2636 const struct device *dev = kobj_to_dev(kobj);
2637 struct device_driver *driver;
2640 /* add device node properties if present */
2641 if (MAJOR(dev->devt)) {
2645 kuid_t uid = GLOBAL_ROOT_UID;
2646 kgid_t gid = GLOBAL_ROOT_GID;
2648 add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt));
2649 add_uevent_var(env, "MINOR=%u", MINOR(dev->devt));
2650 name = device_get_devnode(dev, &mode, &uid, &gid, &tmp);
2652 add_uevent_var(env, "DEVNAME=%s", name);
2654 add_uevent_var(env, "DEVMODE=%#o", mode & 0777);
2655 if (!uid_eq(uid, GLOBAL_ROOT_UID))
2656 add_uevent_var(env, "DEVUID=%u", from_kuid(&init_user_ns, uid));
2657 if (!gid_eq(gid, GLOBAL_ROOT_GID))
2658 add_uevent_var(env, "DEVGID=%u", from_kgid(&init_user_ns, gid));
2663 if (dev->type && dev->type->name)
2664 add_uevent_var(env, "DEVTYPE=%s", dev->type->name);
2666 /* Synchronize with module_remove_driver() */
2668 driver = READ_ONCE(dev->driver);
2670 add_uevent_var(env, "DRIVER=%s", driver->name);
2673 /* Add common DT information about the device */
2674 of_device_uevent(dev, env);
2676 /* have the bus specific function add its stuff */
2677 if (dev->bus && dev->bus->uevent) {
2678 retval = dev->bus->uevent(dev, env);
2680 pr_debug("device: '%s': %s: bus uevent() returned %d\n",
2681 dev_name(dev), __func__, retval);
2684 /* have the class specific function add its stuff */
2685 if (dev->class && dev->class->dev_uevent) {
2686 retval = dev->class->dev_uevent(dev, env);
2688 pr_debug("device: '%s': %s: class uevent() "
2689 "returned %d\n", dev_name(dev),
2693 /* have the device type specific function add its stuff */
2694 if (dev->type && dev->type->uevent) {
2695 retval = dev->type->uevent(dev, env);
2697 pr_debug("device: '%s': %s: dev_type uevent() "
2698 "returned %d\n", dev_name(dev),
2705 static const struct kset_uevent_ops device_uevent_ops = {
2706 .filter = dev_uevent_filter,
2707 .name = dev_uevent_name,
2708 .uevent = dev_uevent,
2711 static ssize_t uevent_show(struct device *dev, struct device_attribute *attr,
2714 struct kobject *top_kobj;
2716 struct kobj_uevent_env *env = NULL;
2721 /* search the kset, the device belongs to */
2722 top_kobj = &dev->kobj;
2723 while (!top_kobj->kset && top_kobj->parent)
2724 top_kobj = top_kobj->parent;
2725 if (!top_kobj->kset)
2728 kset = top_kobj->kset;
2729 if (!kset->uevent_ops || !kset->uevent_ops->uevent)
2732 /* respect filter */
2733 if (kset->uevent_ops && kset->uevent_ops->filter)
2734 if (!kset->uevent_ops->filter(&dev->kobj))
2737 env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
2741 /* let the kset specific function add its keys */
2742 retval = kset->uevent_ops->uevent(&dev->kobj, env);
2746 /* copy keys to file */
2747 for (i = 0; i < env->envp_idx; i++)
2748 len += sysfs_emit_at(buf, len, "%s\n", env->envp[i]);
2754 static ssize_t uevent_store(struct device *dev, struct device_attribute *attr,
2755 const char *buf, size_t count)
2759 rc = kobject_synth_uevent(&dev->kobj, buf, count);
2762 dev_err(dev, "uevent: failed to send synthetic uevent: %d\n", rc);
2768 static DEVICE_ATTR_RW(uevent);
2770 static ssize_t online_show(struct device *dev, struct device_attribute *attr,
2776 val = !dev->offline;
2778 return sysfs_emit(buf, "%u\n", val);
2781 static ssize_t online_store(struct device *dev, struct device_attribute *attr,
2782 const char *buf, size_t count)
2787 ret = kstrtobool(buf, &val);
2791 ret = lock_device_hotplug_sysfs();
2795 ret = val ? device_online(dev) : device_offline(dev);
2796 unlock_device_hotplug();
2797 return ret < 0 ? ret : count;
2799 static DEVICE_ATTR_RW(online);
2801 static ssize_t removable_show(struct device *dev, struct device_attribute *attr,
2806 switch (dev->removable) {
2807 case DEVICE_REMOVABLE:
2816 return sysfs_emit(buf, "%s\n", loc);
2818 static DEVICE_ATTR_RO(removable);
2820 int device_add_groups(struct device *dev, const struct attribute_group **groups)
2822 return sysfs_create_groups(&dev->kobj, groups);
2824 EXPORT_SYMBOL_GPL(device_add_groups);
2826 void device_remove_groups(struct device *dev,
2827 const struct attribute_group **groups)
2829 sysfs_remove_groups(&dev->kobj, groups);
2831 EXPORT_SYMBOL_GPL(device_remove_groups);
2833 union device_attr_group_devres {
2834 const struct attribute_group *group;
2835 const struct attribute_group **groups;
2838 static void devm_attr_group_remove(struct device *dev, void *res)
2840 union device_attr_group_devres *devres = res;
2841 const struct attribute_group *group = devres->group;
2843 dev_dbg(dev, "%s: removing group %p\n", __func__, group);
2844 sysfs_remove_group(&dev->kobj, group);
2848 * devm_device_add_group - given a device, create a managed attribute group
2849 * @dev: The device to create the group for
2850 * @grp: The attribute group to create
2852 * This function creates a group for the first time. It will explicitly
2853 * warn and error if any of the attribute files being created already exist.
2855 * Returns 0 on success or error code on failure.
2857 int devm_device_add_group(struct device *dev, const struct attribute_group *grp)
2859 union device_attr_group_devres *devres;
2862 devres = devres_alloc(devm_attr_group_remove,
2863 sizeof(*devres), GFP_KERNEL);
2867 error = sysfs_create_group(&dev->kobj, grp);
2869 devres_free(devres);
2873 devres->group = grp;
2874 devres_add(dev, devres);
2877 EXPORT_SYMBOL_GPL(devm_device_add_group);
2879 static int device_add_attrs(struct device *dev)
2881 const struct class *class = dev->class;
2882 const struct device_type *type = dev->type;
2886 error = device_add_groups(dev, class->dev_groups);
2892 error = device_add_groups(dev, type->groups);
2894 goto err_remove_class_groups;
2897 error = device_add_groups(dev, dev->groups);
2899 goto err_remove_type_groups;
2901 if (device_supports_offline(dev) && !dev->offline_disabled) {
2902 error = device_create_file(dev, &dev_attr_online);
2904 goto err_remove_dev_groups;
2907 if (fw_devlink_flags && !fw_devlink_is_permissive() && dev->fwnode) {
2908 error = device_create_file(dev, &dev_attr_waiting_for_supplier);
2910 goto err_remove_dev_online;
2913 if (dev_removable_is_valid(dev)) {
2914 error = device_create_file(dev, &dev_attr_removable);
2916 goto err_remove_dev_waiting_for_supplier;
2919 if (dev_add_physical_location(dev)) {
2920 error = device_add_group(dev,
2921 &dev_attr_physical_location_group);
2923 goto err_remove_dev_removable;
2928 err_remove_dev_removable:
2929 device_remove_file(dev, &dev_attr_removable);
2930 err_remove_dev_waiting_for_supplier:
2931 device_remove_file(dev, &dev_attr_waiting_for_supplier);
2932 err_remove_dev_online:
2933 device_remove_file(dev, &dev_attr_online);
2934 err_remove_dev_groups:
2935 device_remove_groups(dev, dev->groups);
2936 err_remove_type_groups:
2938 device_remove_groups(dev, type->groups);
2939 err_remove_class_groups:
2941 device_remove_groups(dev, class->dev_groups);
2946 static void device_remove_attrs(struct device *dev)
2948 const struct class *class = dev->class;
2949 const struct device_type *type = dev->type;
2951 if (dev->physical_location) {
2952 device_remove_group(dev, &dev_attr_physical_location_group);
2953 kfree(dev->physical_location);
2956 device_remove_file(dev, &dev_attr_removable);
2957 device_remove_file(dev, &dev_attr_waiting_for_supplier);
2958 device_remove_file(dev, &dev_attr_online);
2959 device_remove_groups(dev, dev->groups);
2962 device_remove_groups(dev, type->groups);
2965 device_remove_groups(dev, class->dev_groups);
2968 static ssize_t dev_show(struct device *dev, struct device_attribute *attr,
2971 return print_dev_t(buf, dev->devt);
2973 static DEVICE_ATTR_RO(dev);
2976 struct kset *devices_kset;
2979 * devices_kset_move_before - Move device in the devices_kset's list.
2980 * @deva: Device to move.
2981 * @devb: Device @deva should come before.
2983 static void devices_kset_move_before(struct device *deva, struct device *devb)
2987 pr_debug("devices_kset: Moving %s before %s\n",
2988 dev_name(deva), dev_name(devb));
2989 spin_lock(&devices_kset->list_lock);
2990 list_move_tail(&deva->kobj.entry, &devb->kobj.entry);
2991 spin_unlock(&devices_kset->list_lock);
2995 * devices_kset_move_after - Move device in the devices_kset's list.
2996 * @deva: Device to move
2997 * @devb: Device @deva should come after.
2999 static void devices_kset_move_after(struct device *deva, struct device *devb)
3003 pr_debug("devices_kset: Moving %s after %s\n",
3004 dev_name(deva), dev_name(devb));
3005 spin_lock(&devices_kset->list_lock);
3006 list_move(&deva->kobj.entry, &devb->kobj.entry);
3007 spin_unlock(&devices_kset->list_lock);
3011 * devices_kset_move_last - move the device to the end of devices_kset's list.
3012 * @dev: device to move
3014 void devices_kset_move_last(struct device *dev)
3018 pr_debug("devices_kset: Moving %s to end of list\n", dev_name(dev));
3019 spin_lock(&devices_kset->list_lock);
3020 list_move_tail(&dev->kobj.entry, &devices_kset->list);
3021 spin_unlock(&devices_kset->list_lock);
3025 * device_create_file - create sysfs attribute file for device.
3027 * @attr: device attribute descriptor.
3029 int device_create_file(struct device *dev,
3030 const struct device_attribute *attr)
3035 WARN(((attr->attr.mode & S_IWUGO) && !attr->store),
3036 "Attribute %s: write permission without 'store'\n",
3038 WARN(((attr->attr.mode & S_IRUGO) && !attr->show),
3039 "Attribute %s: read permission without 'show'\n",
3041 error = sysfs_create_file(&dev->kobj, &attr->attr);
3046 EXPORT_SYMBOL_GPL(device_create_file);
3049 * device_remove_file - remove sysfs attribute file.
3051 * @attr: device attribute descriptor.
3053 void device_remove_file(struct device *dev,
3054 const struct device_attribute *attr)
3057 sysfs_remove_file(&dev->kobj, &attr->attr);
3059 EXPORT_SYMBOL_GPL(device_remove_file);
3062 * device_remove_file_self - remove sysfs attribute file from its own method.
3064 * @attr: device attribute descriptor.
3066 * See kernfs_remove_self() for details.
3068 bool device_remove_file_self(struct device *dev,
3069 const struct device_attribute *attr)
3072 return sysfs_remove_file_self(&dev->kobj, &attr->attr);
3076 EXPORT_SYMBOL_GPL(device_remove_file_self);
3079 * device_create_bin_file - create sysfs binary attribute file for device.
3081 * @attr: device binary attribute descriptor.
3083 int device_create_bin_file(struct device *dev,
3084 const struct bin_attribute *attr)
3086 int error = -EINVAL;
3088 error = sysfs_create_bin_file(&dev->kobj, attr);
3091 EXPORT_SYMBOL_GPL(device_create_bin_file);
3094 * device_remove_bin_file - remove sysfs binary attribute file
3096 * @attr: device binary attribute descriptor.
3098 void device_remove_bin_file(struct device *dev,
3099 const struct bin_attribute *attr)
3102 sysfs_remove_bin_file(&dev->kobj, attr);
3104 EXPORT_SYMBOL_GPL(device_remove_bin_file);
3106 static void klist_children_get(struct klist_node *n)
3108 struct device_private *p = to_device_private_parent(n);
3109 struct device *dev = p->device;
3114 static void klist_children_put(struct klist_node *n)
3116 struct device_private *p = to_device_private_parent(n);
3117 struct device *dev = p->device;
3123 * device_initialize - init device structure.
3126 * This prepares the device for use by other layers by initializing
3128 * It is the first half of device_register(), if called by
3129 * that function, though it can also be called separately, so one
3130 * may use @dev's fields. In particular, get_device()/put_device()
3131 * may be used for reference counting of @dev after calling this
3134 * All fields in @dev must be initialized by the caller to 0, except
3135 * for those explicitly set to some other value. The simplest
3136 * approach is to use kzalloc() to allocate the structure containing
3139 * NOTE: Use put_device() to give up your reference instead of freeing
3140 * @dev directly once you have called this function.
3142 void device_initialize(struct device *dev)
3144 dev->kobj.kset = devices_kset;
3145 kobject_init(&dev->kobj, &device_ktype);
3146 INIT_LIST_HEAD(&dev->dma_pools);
3147 mutex_init(&dev->mutex);
3148 lockdep_set_novalidate_class(&dev->mutex);
3149 spin_lock_init(&dev->devres_lock);
3150 INIT_LIST_HEAD(&dev->devres_head);
3151 device_pm_init(dev);
3152 set_dev_node(dev, NUMA_NO_NODE);
3153 INIT_LIST_HEAD(&dev->links.consumers);
3154 INIT_LIST_HEAD(&dev->links.suppliers);
3155 INIT_LIST_HEAD(&dev->links.defer_sync);
3156 dev->links.status = DL_DEV_NO_DRIVER;
3157 #if defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_DEVICE) || \
3158 defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_CPU) || \
3159 defined(CONFIG_ARCH_HAS_SYNC_DMA_FOR_CPU_ALL)
3160 dev->dma_coherent = dma_default_coherent;
3162 swiotlb_dev_init(dev);
3164 EXPORT_SYMBOL_GPL(device_initialize);
3166 struct kobject *virtual_device_parent(void)
3168 static struct kobject *virtual_dir = NULL;
3171 virtual_dir = kobject_create_and_add("virtual",
3172 &devices_kset->kobj);
3178 struct kobject kobj;
3179 const struct class *class;
3182 #define to_class_dir(obj) container_of(obj, struct class_dir, kobj)
3184 static void class_dir_release(struct kobject *kobj)
3186 struct class_dir *dir = to_class_dir(kobj);
3191 struct kobj_ns_type_operations *class_dir_child_ns_type(const struct kobject *kobj)
3193 const struct class_dir *dir = to_class_dir(kobj);
3194 return dir->class->ns_type;
3197 static const struct kobj_type class_dir_ktype = {
3198 .release = class_dir_release,
3199 .sysfs_ops = &kobj_sysfs_ops,
3200 .child_ns_type = class_dir_child_ns_type
3203 static struct kobject *class_dir_create_and_add(struct subsys_private *sp,
3204 struct kobject *parent_kobj)
3206 struct class_dir *dir;
3209 dir = kzalloc(sizeof(*dir), GFP_KERNEL);
3211 return ERR_PTR(-ENOMEM);
3213 dir->class = sp->class;
3214 kobject_init(&dir->kobj, &class_dir_ktype);
3216 dir->kobj.kset = &sp->glue_dirs;
3218 retval = kobject_add(&dir->kobj, parent_kobj, "%s", sp->class->name);
3220 kobject_put(&dir->kobj);
3221 return ERR_PTR(retval);
3226 static DEFINE_MUTEX(gdp_mutex);
3228 static struct kobject *get_device_parent(struct device *dev,
3229 struct device *parent)
3231 struct subsys_private *sp = class_to_subsys(dev->class);
3232 struct kobject *kobj = NULL;
3235 struct kobject *parent_kobj;
3239 * If we have no parent, we live in "virtual".
3240 * Class-devices with a non class-device as parent, live
3241 * in a "glue" directory to prevent namespace collisions.
3244 parent_kobj = virtual_device_parent();
3245 else if (parent->class && !dev->class->ns_type) {
3247 return &parent->kobj;
3249 parent_kobj = &parent->kobj;
3252 mutex_lock(&gdp_mutex);
3254 /* find our class-directory at the parent and reference it */
3255 spin_lock(&sp->glue_dirs.list_lock);
3256 list_for_each_entry(k, &sp->glue_dirs.list, entry)
3257 if (k->parent == parent_kobj) {
3258 kobj = kobject_get(k);
3261 spin_unlock(&sp->glue_dirs.list_lock);
3263 mutex_unlock(&gdp_mutex);
3268 /* or create a new class-directory at the parent device */
3269 k = class_dir_create_and_add(sp, parent_kobj);
3270 /* do not emit an uevent for this simple "glue" directory */
3271 mutex_unlock(&gdp_mutex);
3276 /* subsystems can specify a default root directory for their devices */
3277 if (!parent && dev->bus) {
3278 struct device *dev_root = bus_get_dev_root(dev->bus);
3281 kobj = &dev_root->kobj;
3282 put_device(dev_root);
3288 return &parent->kobj;
3292 static inline bool live_in_glue_dir(struct kobject *kobj,
3295 struct subsys_private *sp;
3298 if (!kobj || !dev->class)
3301 sp = class_to_subsys(dev->class);
3305 if (kobj->kset == &sp->glue_dirs)
3314 static inline struct kobject *get_glue_dir(struct device *dev)
3316 return dev->kobj.parent;
3320 * kobject_has_children - Returns whether a kobject has children.
3321 * @kobj: the object to test
3323 * This will return whether a kobject has other kobjects as children.
3325 * It does NOT account for the presence of attribute files, only sub
3326 * directories. It also assumes there is no concurrent addition or
3327 * removal of such children, and thus relies on external locking.
3329 static inline bool kobject_has_children(struct kobject *kobj)
3331 WARN_ON_ONCE(kref_read(&kobj->kref) == 0);
3333 return kobj->sd && kobj->sd->dir.subdirs;
3337 * make sure cleaning up dir as the last step, we need to make
3338 * sure .release handler of kobject is run with holding the
3341 static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir)
3345 /* see if we live in a "glue" directory */
3346 if (!live_in_glue_dir(glue_dir, dev))
3349 mutex_lock(&gdp_mutex);
3351 * There is a race condition between removing glue directory
3352 * and adding a new device under the glue directory.
3357 * get_device_parent()
3358 * class_dir_create_and_add()
3359 * kobject_add_internal()
3360 * create_dir() // create glue_dir
3363 * get_device_parent()
3364 * kobject_get() // get glue_dir
3367 * cleanup_glue_dir()
3368 * kobject_del(glue_dir)
3371 * kobject_add_internal()
3372 * create_dir() // in glue_dir
3373 * sysfs_create_dir_ns()
3374 * kernfs_create_dir_ns(sd)
3376 * sysfs_remove_dir() // glue_dir->sd=NULL
3377 * sysfs_put() // free glue_dir->sd
3380 * kernfs_new_node(sd)
3381 * kernfs_get(glue_dir)
3385 * Before CPU1 remove last child device under glue dir, if CPU2 add
3386 * a new device under glue dir, the glue_dir kobject reference count
3387 * will be increase to 2 in kobject_get(k). And CPU2 has been called
3388 * kernfs_create_dir_ns(). Meanwhile, CPU1 call sysfs_remove_dir()
3389 * and sysfs_put(). This result in glue_dir->sd is freed.
3391 * Then the CPU2 will see a stale "empty" but still potentially used
3392 * glue dir around in kernfs_new_node().
3394 * In order to avoid this happening, we also should make sure that
3395 * kernfs_node for glue_dir is released in CPU1 only when refcount
3396 * for glue_dir kobj is 1.
3398 ref = kref_read(&glue_dir->kref);
3399 if (!kobject_has_children(glue_dir) && !--ref)
3400 kobject_del(glue_dir);
3401 kobject_put(glue_dir);
3402 mutex_unlock(&gdp_mutex);
3405 static int device_add_class_symlinks(struct device *dev)
3407 struct device_node *of_node = dev_of_node(dev);
3408 struct subsys_private *sp;
3412 error = sysfs_create_link(&dev->kobj, of_node_kobj(of_node), "of_node");
3414 dev_warn(dev, "Error %d creating of_node link\n",error);
3415 /* An error here doesn't warrant bringing down the device */
3418 sp = class_to_subsys(dev->class);
3422 error = sysfs_create_link(&dev->kobj, &sp->subsys.kobj, "subsystem");
3426 if (dev->parent && device_is_not_partition(dev)) {
3427 error = sysfs_create_link(&dev->kobj, &dev->parent->kobj,
3433 /* link in the class directory pointing to the device */
3434 error = sysfs_create_link(&sp->subsys.kobj, &dev->kobj, dev_name(dev));
3440 sysfs_remove_link(&dev->kobj, "device");
3442 sysfs_remove_link(&dev->kobj, "subsystem");
3444 sysfs_remove_link(&dev->kobj, "of_node");
3450 static void device_remove_class_symlinks(struct device *dev)
3452 struct subsys_private *sp = class_to_subsys(dev->class);
3454 if (dev_of_node(dev))
3455 sysfs_remove_link(&dev->kobj, "of_node");
3460 if (dev->parent && device_is_not_partition(dev))
3461 sysfs_remove_link(&dev->kobj, "device");
3462 sysfs_remove_link(&dev->kobj, "subsystem");
3463 sysfs_delete_link(&sp->subsys.kobj, &dev->kobj, dev_name(dev));
3468 * dev_set_name - set a device name
3470 * @fmt: format string for the device's name
3472 int dev_set_name(struct device *dev, const char *fmt, ...)
3477 va_start(vargs, fmt);
3478 err = kobject_set_name_vargs(&dev->kobj, fmt, vargs);
3482 EXPORT_SYMBOL_GPL(dev_set_name);
3484 /* select a /sys/dev/ directory for the device */
3485 static struct kobject *device_to_dev_kobj(struct device *dev)
3487 if (is_blockdev(dev))
3488 return sysfs_dev_block_kobj;
3490 return sysfs_dev_char_kobj;
3493 static int device_create_sys_dev_entry(struct device *dev)
3495 struct kobject *kobj = device_to_dev_kobj(dev);
3500 format_dev_t(devt_str, dev->devt);
3501 error = sysfs_create_link(kobj, &dev->kobj, devt_str);
3507 static void device_remove_sys_dev_entry(struct device *dev)
3509 struct kobject *kobj = device_to_dev_kobj(dev);
3513 format_dev_t(devt_str, dev->devt);
3514 sysfs_remove_link(kobj, devt_str);
3518 static int device_private_init(struct device *dev)
3520 dev->p = kzalloc(sizeof(*dev->p), GFP_KERNEL);
3523 dev->p->device = dev;
3524 klist_init(&dev->p->klist_children, klist_children_get,
3525 klist_children_put);
3526 INIT_LIST_HEAD(&dev->p->deferred_probe);
3531 * device_add - add device to device hierarchy.
3534 * This is part 2 of device_register(), though may be called
3535 * separately _iff_ device_initialize() has been called separately.
3537 * This adds @dev to the kobject hierarchy via kobject_add(), adds it
3538 * to the global and sibling lists for the device, then
3539 * adds it to the other relevant subsystems of the driver model.
3541 * Do not call this routine or device_register() more than once for
3542 * any device structure. The driver model core is not designed to work
3543 * with devices that get unregistered and then spring back to life.
3544 * (Among other things, it's very hard to guarantee that all references
3545 * to the previous incarnation of @dev have been dropped.) Allocate
3546 * and register a fresh new struct device instead.
3548 * NOTE: _Never_ directly free @dev after calling this function, even
3549 * if it returned an error! Always use put_device() to give up your
3550 * reference instead.
3552 * Rule of thumb is: if device_add() succeeds, you should call
3553 * device_del() when you want to get rid of it. If device_add() has
3554 * *not* succeeded, use *only* put_device() to drop the reference
3557 int device_add(struct device *dev)
3559 struct subsys_private *sp;
3560 struct device *parent;
3561 struct kobject *kobj;
3562 struct class_interface *class_intf;
3563 int error = -EINVAL;
3564 struct kobject *glue_dir = NULL;
3566 dev = get_device(dev);
3571 error = device_private_init(dev);
3577 * for statically allocated devices, which should all be converted
3578 * some day, we need to initialize the name. We prevent reading back
3579 * the name, and force the use of dev_name()
3581 if (dev->init_name) {
3582 error = dev_set_name(dev, "%s", dev->init_name);
3583 dev->init_name = NULL;
3588 /* subsystems can specify simple device enumeration */
3589 else if (dev->bus && dev->bus->dev_name)
3590 error = dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
3596 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3598 parent = get_device(dev->parent);
3599 kobj = get_device_parent(dev, parent);
3601 error = PTR_ERR(kobj);
3605 dev->kobj.parent = kobj;
3607 /* use parent numa_node */
3608 if (parent && (dev_to_node(dev) == NUMA_NO_NODE))
3609 set_dev_node(dev, dev_to_node(parent));
3611 /* first, register with generic layer. */
3612 /* we require the name to be set before, and pass NULL */
3613 error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
3619 /* notify platform of device entry */
3620 device_platform_notify(dev);
3622 error = device_create_file(dev, &dev_attr_uevent);
3626 error = device_add_class_symlinks(dev);
3629 error = device_add_attrs(dev);
3632 error = bus_add_device(dev);
3635 error = dpm_sysfs_add(dev);
3640 if (MAJOR(dev->devt)) {
3641 error = device_create_file(dev, &dev_attr_dev);
3645 error = device_create_sys_dev_entry(dev);
3649 devtmpfs_create_node(dev);
3652 /* Notify clients of device addition. This call must come
3653 * after dpm_sysfs_add() and before kobject_uevent().
3655 bus_notify(dev, BUS_NOTIFY_ADD_DEVICE);
3656 kobject_uevent(&dev->kobj, KOBJ_ADD);
3659 * Check if any of the other devices (consumers) have been waiting for
3660 * this device (supplier) to be added so that they can create a device
3663 * This needs to happen after device_pm_add() because device_link_add()
3664 * requires the supplier be registered before it's called.
3666 * But this also needs to happen before bus_probe_device() to make sure
3667 * waiting consumers can link to it before the driver is bound to the
3668 * device and the driver sync_state callback is called for this device.
3670 if (dev->fwnode && !dev->fwnode->dev) {
3671 dev->fwnode->dev = dev;
3672 fw_devlink_link_device(dev);
3675 bus_probe_device(dev);
3678 * If all driver registration is done and a newly added device doesn't
3679 * match with any driver, don't block its consumers from probing in
3680 * case the consumer device is able to operate without this supplier.
3682 if (dev->fwnode && fw_devlink_drv_reg_done && !dev->can_match)
3683 fw_devlink_unblock_consumers(dev);
3686 klist_add_tail(&dev->p->knode_parent,
3687 &parent->p->klist_children);
3689 sp = class_to_subsys(dev->class);
3691 mutex_lock(&sp->mutex);
3692 /* tie the class to the device */
3693 klist_add_tail(&dev->p->knode_class, &sp->klist_devices);
3695 /* notify any interfaces that the device is here */
3696 list_for_each_entry(class_intf, &sp->interfaces, node)
3697 if (class_intf->add_dev)
3698 class_intf->add_dev(dev);
3699 mutex_unlock(&sp->mutex);
3706 if (MAJOR(dev->devt))
3707 device_remove_file(dev, &dev_attr_dev);
3709 device_pm_remove(dev);
3710 dpm_sysfs_remove(dev);
3713 bus_remove_device(dev);
3715 device_remove_attrs(dev);
3717 device_remove_class_symlinks(dev);
3719 device_remove_file(dev, &dev_attr_uevent);
3721 device_platform_notify_remove(dev);
3722 kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3723 glue_dir = get_glue_dir(dev);
3724 kobject_del(&dev->kobj);
3726 cleanup_glue_dir(dev, glue_dir);
3734 EXPORT_SYMBOL_GPL(device_add);
3737 * device_register - register a device with the system.
3738 * @dev: pointer to the device structure
3740 * This happens in two clean steps - initialize the device
3741 * and add it to the system. The two steps can be called
3742 * separately, but this is the easiest and most common.
3743 * I.e. you should only call the two helpers separately if
3744 * have a clearly defined need to use and refcount the device
3745 * before it is added to the hierarchy.
3747 * For more information, see the kerneldoc for device_initialize()
3750 * NOTE: _Never_ directly free @dev after calling this function, even
3751 * if it returned an error! Always use put_device() to give up the
3752 * reference initialized in this function instead.
3754 int device_register(struct device *dev)
3756 device_initialize(dev);
3757 return device_add(dev);
3759 EXPORT_SYMBOL_GPL(device_register);
3762 * get_device - increment reference count for device.
3765 * This simply forwards the call to kobject_get(), though
3766 * we do take care to provide for the case that we get a NULL
3767 * pointer passed in.
3769 struct device *get_device(struct device *dev)
3771 return dev ? kobj_to_dev(kobject_get(&dev->kobj)) : NULL;
3773 EXPORT_SYMBOL_GPL(get_device);
3776 * put_device - decrement reference count.
3777 * @dev: device in question.
3779 void put_device(struct device *dev)
3781 /* might_sleep(); */
3783 kobject_put(&dev->kobj);
3785 EXPORT_SYMBOL_GPL(put_device);
3787 bool kill_device(struct device *dev)
3790 * Require the device lock and set the "dead" flag to guarantee that
3791 * the update behavior is consistent with the other bitfields near
3792 * it and that we cannot have an asynchronous probe routine trying
3793 * to run while we are tearing out the bus/class/sysfs from
3794 * underneath the device.
3796 device_lock_assert(dev);
3800 dev->p->dead = true;
3803 EXPORT_SYMBOL_GPL(kill_device);
3806 * device_del - delete device from system.
3809 * This is the first part of the device unregistration
3810 * sequence. This removes the device from the lists we control
3811 * from here, has it removed from the other driver model
3812 * subsystems it was added to in device_add(), and removes it
3813 * from the kobject hierarchy.
3815 * NOTE: this should be called manually _iff_ device_add() was
3816 * also called manually.
3818 void device_del(struct device *dev)
3820 struct subsys_private *sp;
3821 struct device *parent = dev->parent;
3822 struct kobject *glue_dir = NULL;
3823 struct class_interface *class_intf;
3824 unsigned int noio_flag;
3830 if (dev->fwnode && dev->fwnode->dev == dev)
3831 dev->fwnode->dev = NULL;
3833 /* Notify clients of device removal. This call must come
3834 * before dpm_sysfs_remove().
3836 noio_flag = memalloc_noio_save();
3837 bus_notify(dev, BUS_NOTIFY_DEL_DEVICE);
3839 dpm_sysfs_remove(dev);
3841 klist_del(&dev->p->knode_parent);
3842 if (MAJOR(dev->devt)) {
3843 devtmpfs_delete_node(dev);
3844 device_remove_sys_dev_entry(dev);
3845 device_remove_file(dev, &dev_attr_dev);
3848 sp = class_to_subsys(dev->class);
3850 device_remove_class_symlinks(dev);
3852 mutex_lock(&sp->mutex);
3853 /* notify any interfaces that the device is now gone */
3854 list_for_each_entry(class_intf, &sp->interfaces, node)
3855 if (class_intf->remove_dev)
3856 class_intf->remove_dev(dev);
3857 /* remove the device from the class list */
3858 klist_del(&dev->p->knode_class);
3859 mutex_unlock(&sp->mutex);
3862 device_remove_file(dev, &dev_attr_uevent);
3863 device_remove_attrs(dev);
3864 bus_remove_device(dev);
3865 device_pm_remove(dev);
3866 driver_deferred_probe_del(dev);
3867 device_platform_notify_remove(dev);
3868 device_links_purge(dev);
3871 * If a device does not have a driver attached, we need to clean
3872 * up any managed resources. We do this in device_release(), but
3873 * it's never called (and we leak the device) if a managed
3874 * resource holds a reference to the device. So release all
3875 * managed resources here, like we do in driver_detach(). We
3876 * still need to do so again in device_release() in case someone
3877 * adds a new resource after this point, though.
3879 devres_release_all(dev);
3881 bus_notify(dev, BUS_NOTIFY_REMOVED_DEVICE);
3882 kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3883 glue_dir = get_glue_dir(dev);
3884 kobject_del(&dev->kobj);
3885 cleanup_glue_dir(dev, glue_dir);
3886 memalloc_noio_restore(noio_flag);
3889 EXPORT_SYMBOL_GPL(device_del);
3892 * device_unregister - unregister device from system.
3893 * @dev: device going away.
3895 * We do this in two parts, like we do device_register(). First,
3896 * we remove it from all the subsystems with device_del(), then
3897 * we decrement the reference count via put_device(). If that
3898 * is the final reference count, the device will be cleaned up
3899 * via device_release() above. Otherwise, the structure will
3900 * stick around until the final reference to the device is dropped.
3902 void device_unregister(struct device *dev)
3904 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3908 EXPORT_SYMBOL_GPL(device_unregister);
3910 static struct device *prev_device(struct klist_iter *i)
3912 struct klist_node *n = klist_prev(i);
3913 struct device *dev = NULL;
3914 struct device_private *p;
3917 p = to_device_private_parent(n);
3923 static struct device *next_device(struct klist_iter *i)
3925 struct klist_node *n = klist_next(i);
3926 struct device *dev = NULL;
3927 struct device_private *p;
3930 p = to_device_private_parent(n);
3937 * device_get_devnode - path of device node file
3939 * @mode: returned file access mode
3940 * @uid: returned file owner
3941 * @gid: returned file group
3942 * @tmp: possibly allocated string
3944 * Return the relative path of a possible device node.
3945 * Non-default names may need to allocate a memory to compose
3946 * a name. This memory is returned in tmp and needs to be
3947 * freed by the caller.
3949 const char *device_get_devnode(const struct device *dev,
3950 umode_t *mode, kuid_t *uid, kgid_t *gid,
3957 /* the device type may provide a specific name */
3958 if (dev->type && dev->type->devnode)
3959 *tmp = dev->type->devnode(dev, mode, uid, gid);
3963 /* the class may provide a specific name */
3964 if (dev->class && dev->class->devnode)
3965 *tmp = dev->class->devnode(dev, mode);
3969 /* return name without allocation, tmp == NULL */
3970 if (strchr(dev_name(dev), '!') == NULL)
3971 return dev_name(dev);
3973 /* replace '!' in the name with '/' */
3974 s = kstrdup_and_replace(dev_name(dev), '!', '/', GFP_KERNEL);
3981 * device_for_each_child - device child iterator.
3982 * @parent: parent struct device.
3983 * @fn: function to be called for each device.
3984 * @data: data for the callback.
3986 * Iterate over @parent's child devices, and call @fn for each,
3989 * We check the return of @fn each time. If it returns anything
3990 * other than 0, we break out and return that value.
3992 int device_for_each_child(struct device *parent, void *data,
3993 int (*fn)(struct device *dev, void *data))
3995 struct klist_iter i;
3996 struct device *child;
3999 if (!parent || !parent->p)
4002 klist_iter_init(&parent->p->klist_children, &i);
4003 while (!error && (child = next_device(&i)))
4004 error = fn(child, data);
4005 klist_iter_exit(&i);
4008 EXPORT_SYMBOL_GPL(device_for_each_child);
4011 * device_for_each_child_reverse - device child iterator in reversed order.
4012 * @parent: parent struct device.
4013 * @fn: function to be called for each device.
4014 * @data: data for the callback.
4016 * Iterate over @parent's child devices, and call @fn for each,
4019 * We check the return of @fn each time. If it returns anything
4020 * other than 0, we break out and return that value.
4022 int device_for_each_child_reverse(struct device *parent, void *data,
4023 int (*fn)(struct device *dev, void *data))
4025 struct klist_iter i;
4026 struct device *child;
4029 if (!parent || !parent->p)
4032 klist_iter_init(&parent->p->klist_children, &i);
4033 while ((child = prev_device(&i)) && !error)
4034 error = fn(child, data);
4035 klist_iter_exit(&i);
4038 EXPORT_SYMBOL_GPL(device_for_each_child_reverse);
4041 * device_find_child - device iterator for locating a particular device.
4042 * @parent: parent struct device
4043 * @match: Callback function to check device
4044 * @data: Data to pass to match function
4046 * This is similar to the device_for_each_child() function above, but it
4047 * returns a reference to a device that is 'found' for later use, as
4048 * determined by the @match callback.
4050 * The callback should return 0 if the device doesn't match and non-zero
4051 * if it does. If the callback returns non-zero and a reference to the
4052 * current device can be obtained, this function will return to the caller
4053 * and not iterate over any more devices.
4055 * NOTE: you will need to drop the reference with put_device() after use.
4057 struct device *device_find_child(struct device *parent, void *data,
4058 int (*match)(struct device *dev, void *data))
4060 struct klist_iter i;
4061 struct device *child;
4063 if (!parent || !parent->p)
4066 klist_iter_init(&parent->p->klist_children, &i);
4067 while ((child = next_device(&i)))
4068 if (match(child, data) && get_device(child))
4070 klist_iter_exit(&i);
4073 EXPORT_SYMBOL_GPL(device_find_child);
4076 * device_find_child_by_name - device iterator for locating a child device.
4077 * @parent: parent struct device
4078 * @name: name of the child device
4080 * This is similar to the device_find_child() function above, but it
4081 * returns a reference to a device that has the name @name.
4083 * NOTE: you will need to drop the reference with put_device() after use.
4085 struct device *device_find_child_by_name(struct device *parent,
4088 struct klist_iter i;
4089 struct device *child;
4094 klist_iter_init(&parent->p->klist_children, &i);
4095 while ((child = next_device(&i)))
4096 if (sysfs_streq(dev_name(child), name) && get_device(child))
4098 klist_iter_exit(&i);
4101 EXPORT_SYMBOL_GPL(device_find_child_by_name);
4103 static int match_any(struct device *dev, void *unused)
4109 * device_find_any_child - device iterator for locating a child device, if any.
4110 * @parent: parent struct device
4112 * This is similar to the device_find_child() function above, but it
4113 * returns a reference to a child device, if any.
4115 * NOTE: you will need to drop the reference with put_device() after use.
4117 struct device *device_find_any_child(struct device *parent)
4119 return device_find_child(parent, NULL, match_any);
4121 EXPORT_SYMBOL_GPL(device_find_any_child);
4123 int __init devices_init(void)
4125 devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
4128 dev_kobj = kobject_create_and_add("dev", NULL);
4131 sysfs_dev_block_kobj = kobject_create_and_add("block", dev_kobj);
4132 if (!sysfs_dev_block_kobj)
4133 goto block_kobj_err;
4134 sysfs_dev_char_kobj = kobject_create_and_add("char", dev_kobj);
4135 if (!sysfs_dev_char_kobj)
4137 device_link_wq = alloc_workqueue("device_link_wq", 0, 0);
4138 if (!device_link_wq)
4144 kobject_put(sysfs_dev_char_kobj);
4146 kobject_put(sysfs_dev_block_kobj);
4148 kobject_put(dev_kobj);
4150 kset_unregister(devices_kset);
4154 static int device_check_offline(struct device *dev, void *not_used)
4158 ret = device_for_each_child(dev, NULL, device_check_offline);
4162 return device_supports_offline(dev) && !dev->offline ? -EBUSY : 0;
4166 * device_offline - Prepare the device for hot-removal.
4167 * @dev: Device to be put offline.
4169 * Execute the device bus type's .offline() callback, if present, to prepare
4170 * the device for a subsequent hot-removal. If that succeeds, the device must
4171 * not be used until either it is removed or its bus type's .online() callback
4174 * Call under device_hotplug_lock.
4176 int device_offline(struct device *dev)
4180 if (dev->offline_disabled)
4183 ret = device_for_each_child(dev, NULL, device_check_offline);
4188 if (device_supports_offline(dev)) {
4192 ret = dev->bus->offline(dev);
4194 kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
4195 dev->offline = true;
4205 * device_online - Put the device back online after successful device_offline().
4206 * @dev: Device to be put back online.
4208 * If device_offline() has been successfully executed for @dev, but the device
4209 * has not been removed subsequently, execute its bus type's .online() callback
4210 * to indicate that the device can be used again.
4212 * Call under device_hotplug_lock.
4214 int device_online(struct device *dev)
4219 if (device_supports_offline(dev)) {
4221 ret = dev->bus->online(dev);
4223 kobject_uevent(&dev->kobj, KOBJ_ONLINE);
4224 dev->offline = false;
4235 struct root_device {
4237 struct module *owner;
4240 static inline struct root_device *to_root_device(struct device *d)
4242 return container_of(d, struct root_device, dev);
4245 static void root_device_release(struct device *dev)
4247 kfree(to_root_device(dev));
4251 * __root_device_register - allocate and register a root device
4252 * @name: root device name
4253 * @owner: owner module of the root device, usually THIS_MODULE
4255 * This function allocates a root device and registers it
4256 * using device_register(). In order to free the returned
4257 * device, use root_device_unregister().
4259 * Root devices are dummy devices which allow other devices
4260 * to be grouped under /sys/devices. Use this function to
4261 * allocate a root device and then use it as the parent of
4262 * any device which should appear under /sys/devices/{name}
4264 * The /sys/devices/{name} directory will also contain a
4265 * 'module' symlink which points to the @owner directory
4268 * Returns &struct device pointer on success, or ERR_PTR() on error.
4270 * Note: You probably want to use root_device_register().
4272 struct device *__root_device_register(const char *name, struct module *owner)
4274 struct root_device *root;
4277 root = kzalloc(sizeof(struct root_device), GFP_KERNEL);
4279 return ERR_PTR(err);
4281 err = dev_set_name(&root->dev, "%s", name);
4284 return ERR_PTR(err);
4287 root->dev.release = root_device_release;
4289 err = device_register(&root->dev);
4291 put_device(&root->dev);
4292 return ERR_PTR(err);
4295 #ifdef CONFIG_MODULES /* gotta find a "cleaner" way to do this */
4297 struct module_kobject *mk = &owner->mkobj;
4299 err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module");
4301 device_unregister(&root->dev);
4302 return ERR_PTR(err);
4304 root->owner = owner;
4310 EXPORT_SYMBOL_GPL(__root_device_register);
4313 * root_device_unregister - unregister and free a root device
4314 * @dev: device going away
4316 * This function unregisters and cleans up a device that was created by
4317 * root_device_register().
4319 void root_device_unregister(struct device *dev)
4321 struct root_device *root = to_root_device(dev);
4324 sysfs_remove_link(&root->dev.kobj, "module");
4326 device_unregister(dev);
4328 EXPORT_SYMBOL_GPL(root_device_unregister);
4331 static void device_create_release(struct device *dev)
4333 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
4337 static __printf(6, 0) struct device *
4338 device_create_groups_vargs(const struct class *class, struct device *parent,
4339 dev_t devt, void *drvdata,
4340 const struct attribute_group **groups,
4341 const char *fmt, va_list args)
4343 struct device *dev = NULL;
4344 int retval = -ENODEV;
4346 if (IS_ERR_OR_NULL(class))
4349 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
4355 device_initialize(dev);
4358 dev->parent = parent;
4359 dev->groups = groups;
4360 dev->release = device_create_release;
4361 dev_set_drvdata(dev, drvdata);
4363 retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
4367 retval = device_add(dev);
4375 return ERR_PTR(retval);
4379 * device_create - creates a device and registers it with sysfs
4380 * @class: pointer to the struct class that this device should be registered to
4381 * @parent: pointer to the parent struct device of this new device, if any
4382 * @devt: the dev_t for the char device to be added
4383 * @drvdata: the data to be added to the device for callbacks
4384 * @fmt: string for the device's name
4386 * This function can be used by char device classes. A struct device
4387 * will be created in sysfs, registered to the specified class.
4389 * A "dev" file will be created, showing the dev_t for the device, if
4390 * the dev_t is not 0,0.
4391 * If a pointer to a parent struct device is passed in, the newly created
4392 * struct device will be a child of that device in sysfs.
4393 * The pointer to the struct device will be returned from the call.
4394 * Any further sysfs files that might be required can be created using this
4397 * Returns &struct device pointer on success, or ERR_PTR() on error.
4399 struct device *device_create(const struct class *class, struct device *parent,
4400 dev_t devt, void *drvdata, const char *fmt, ...)
4405 va_start(vargs, fmt);
4406 dev = device_create_groups_vargs(class, parent, devt, drvdata, NULL,
4411 EXPORT_SYMBOL_GPL(device_create);
4414 * device_create_with_groups - creates a device and registers it with sysfs
4415 * @class: pointer to the struct class that this device should be registered to
4416 * @parent: pointer to the parent struct device of this new device, if any
4417 * @devt: the dev_t for the char device to be added
4418 * @drvdata: the data to be added to the device for callbacks
4419 * @groups: NULL-terminated list of attribute groups to be created
4420 * @fmt: string for the device's name
4422 * This function can be used by char device classes. A struct device
4423 * will be created in sysfs, registered to the specified class.
4424 * Additional attributes specified in the groups parameter will also
4425 * be created automatically.
4427 * A "dev" file will be created, showing the dev_t for the device, if
4428 * the dev_t is not 0,0.
4429 * If a pointer to a parent struct device is passed in, the newly created
4430 * struct device will be a child of that device in sysfs.
4431 * The pointer to the struct device will be returned from the call.
4432 * Any further sysfs files that might be required can be created using this
4435 * Returns &struct device pointer on success, or ERR_PTR() on error.
4437 struct device *device_create_with_groups(const struct class *class,
4438 struct device *parent, dev_t devt,
4440 const struct attribute_group **groups,
4441 const char *fmt, ...)
4446 va_start(vargs, fmt);
4447 dev = device_create_groups_vargs(class, parent, devt, drvdata, groups,
4452 EXPORT_SYMBOL_GPL(device_create_with_groups);
4455 * device_destroy - removes a device that was created with device_create()
4456 * @class: pointer to the struct class that this device was registered with
4457 * @devt: the dev_t of the device that was previously registered
4459 * This call unregisters and cleans up a device that was created with a
4460 * call to device_create().
4462 void device_destroy(const struct class *class, dev_t devt)
4466 dev = class_find_device_by_devt(class, devt);
4469 device_unregister(dev);
4472 EXPORT_SYMBOL_GPL(device_destroy);
4475 * device_rename - renames a device
4476 * @dev: the pointer to the struct device to be renamed
4477 * @new_name: the new name of the device
4479 * It is the responsibility of the caller to provide mutual
4480 * exclusion between two different calls of device_rename
4481 * on the same device to ensure that new_name is valid and
4482 * won't conflict with other devices.
4484 * Note: given that some subsystems (networking and infiniband) use this
4485 * function, with no immediate plans for this to change, we cannot assume or
4486 * require that this function not be called at all.
4488 * However, if you're writing new code, do not call this function. The following
4489 * text from Kay Sievers offers some insight:
4491 * Renaming devices is racy at many levels, symlinks and other stuff are not
4492 * replaced atomically, and you get a "move" uevent, but it's not easy to
4493 * connect the event to the old and new device. Device nodes are not renamed at
4494 * all, there isn't even support for that in the kernel now.
4496 * In the meantime, during renaming, your target name might be taken by another
4497 * driver, creating conflicts. Or the old name is taken directly after you
4498 * renamed it -- then you get events for the same DEVPATH, before you even see
4499 * the "move" event. It's just a mess, and nothing new should ever rely on
4500 * kernel device renaming. Besides that, it's not even implemented now for
4501 * other things than (driver-core wise very simple) network devices.
4503 * Make up a "real" name in the driver before you register anything, or add
4504 * some other attributes for userspace to find the device, or use udev to add
4505 * symlinks -- but never rename kernel devices later, it's a complete mess. We
4506 * don't even want to get into that and try to implement the missing pieces in
4507 * the core. We really have other pieces to fix in the driver core mess. :)
4509 int device_rename(struct device *dev, const char *new_name)
4511 struct subsys_private *sp = NULL;
4512 struct kobject *kobj = &dev->kobj;
4513 char *old_device_name = NULL;
4515 bool is_link_renamed = false;
4517 dev = get_device(dev);
4521 dev_dbg(dev, "renaming to %s\n", new_name);
4523 old_device_name = kstrdup(dev_name(dev), GFP_KERNEL);
4524 if (!old_device_name) {
4530 sp = class_to_subsys(dev->class);
4537 error = sysfs_rename_link_ns(&sp->subsys.kobj, kobj, old_device_name,
4538 new_name, kobject_namespace(kobj));
4542 is_link_renamed = true;
4545 error = kobject_rename(kobj, new_name);
4547 if (error && is_link_renamed)
4548 sysfs_rename_link_ns(&sp->subsys.kobj, kobj, new_name,
4549 old_device_name, kobject_namespace(kobj));
4554 kfree(old_device_name);
4558 EXPORT_SYMBOL_GPL(device_rename);
4560 static int device_move_class_links(struct device *dev,
4561 struct device *old_parent,
4562 struct device *new_parent)
4567 sysfs_remove_link(&dev->kobj, "device");
4569 error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
4575 * device_move - moves a device to a new parent
4576 * @dev: the pointer to the struct device to be moved
4577 * @new_parent: the new parent of the device (can be NULL)
4578 * @dpm_order: how to reorder the dpm_list
4580 int device_move(struct device *dev, struct device *new_parent,
4581 enum dpm_order dpm_order)
4584 struct device *old_parent;
4585 struct kobject *new_parent_kobj;
4587 dev = get_device(dev);
4592 new_parent = get_device(new_parent);
4593 new_parent_kobj = get_device_parent(dev, new_parent);
4594 if (IS_ERR(new_parent_kobj)) {
4595 error = PTR_ERR(new_parent_kobj);
4596 put_device(new_parent);
4600 pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev),
4601 __func__, new_parent ? dev_name(new_parent) : "<NULL>");
4602 error = kobject_move(&dev->kobj, new_parent_kobj);
4604 cleanup_glue_dir(dev, new_parent_kobj);
4605 put_device(new_parent);
4608 old_parent = dev->parent;
4609 dev->parent = new_parent;
4611 klist_remove(&dev->p->knode_parent);
4613 klist_add_tail(&dev->p->knode_parent,
4614 &new_parent->p->klist_children);
4615 set_dev_node(dev, dev_to_node(new_parent));
4619 error = device_move_class_links(dev, old_parent, new_parent);
4621 /* We ignore errors on cleanup since we're hosed anyway... */
4622 device_move_class_links(dev, new_parent, old_parent);
4623 if (!kobject_move(&dev->kobj, &old_parent->kobj)) {
4625 klist_remove(&dev->p->knode_parent);
4626 dev->parent = old_parent;
4628 klist_add_tail(&dev->p->knode_parent,
4629 &old_parent->p->klist_children);
4630 set_dev_node(dev, dev_to_node(old_parent));
4633 cleanup_glue_dir(dev, new_parent_kobj);
4634 put_device(new_parent);
4638 switch (dpm_order) {
4639 case DPM_ORDER_NONE:
4641 case DPM_ORDER_DEV_AFTER_PARENT:
4642 device_pm_move_after(dev, new_parent);
4643 devices_kset_move_after(dev, new_parent);
4645 case DPM_ORDER_PARENT_BEFORE_DEV:
4646 device_pm_move_before(new_parent, dev);
4647 devices_kset_move_before(new_parent, dev);
4649 case DPM_ORDER_DEV_LAST:
4650 device_pm_move_last(dev);
4651 devices_kset_move_last(dev);
4655 put_device(old_parent);
4661 EXPORT_SYMBOL_GPL(device_move);
4663 static int device_attrs_change_owner(struct device *dev, kuid_t kuid,
4666 struct kobject *kobj = &dev->kobj;
4667 const struct class *class = dev->class;
4668 const struct device_type *type = dev->type;
4673 * Change the device groups of the device class for @dev to
4676 error = sysfs_groups_change_owner(kobj, class->dev_groups, kuid,
4684 * Change the device groups of the device type for @dev to
4687 error = sysfs_groups_change_owner(kobj, type->groups, kuid,
4693 /* Change the device groups of @dev to @kuid/@kgid. */
4694 error = sysfs_groups_change_owner(kobj, dev->groups, kuid, kgid);
4698 if (device_supports_offline(dev) && !dev->offline_disabled) {
4699 /* Change online device attributes of @dev to @kuid/@kgid. */
4700 error = sysfs_file_change_owner(kobj, dev_attr_online.attr.name,
4710 * device_change_owner - change the owner of an existing device.
4712 * @kuid: new owner's kuid
4713 * @kgid: new owner's kgid
4715 * This changes the owner of @dev and its corresponding sysfs entries to
4716 * @kuid/@kgid. This function closely mirrors how @dev was added via driver
4719 * Returns 0 on success or error code on failure.
4721 int device_change_owner(struct device *dev, kuid_t kuid, kgid_t kgid)
4724 struct kobject *kobj = &dev->kobj;
4725 struct subsys_private *sp;
4727 dev = get_device(dev);
4732 * Change the kobject and the default attributes and groups of the
4733 * ktype associated with it to @kuid/@kgid.
4735 error = sysfs_change_owner(kobj, kuid, kgid);
4740 * Change the uevent file for @dev to the new owner. The uevent file
4741 * was created in a separate step when @dev got added and we mirror
4744 error = sysfs_file_change_owner(kobj, dev_attr_uevent.attr.name, kuid,
4750 * Change the device groups, the device groups associated with the
4751 * device class, and the groups associated with the device type of @dev
4754 error = device_attrs_change_owner(dev, kuid, kgid);
4758 error = dpm_sysfs_change_owner(dev, kuid, kgid);
4763 * Change the owner of the symlink located in the class directory of
4764 * the device class associated with @dev which points to the actual
4765 * directory entry for @dev to @kuid/@kgid. This ensures that the
4766 * symlink shows the same permissions as its target.
4768 sp = class_to_subsys(dev->class);
4773 error = sysfs_link_change_owner(&sp->subsys.kobj, &dev->kobj, dev_name(dev), kuid, kgid);
4780 EXPORT_SYMBOL_GPL(device_change_owner);
4783 * device_shutdown - call ->shutdown() on each device to shutdown.
4785 void device_shutdown(void)
4787 struct device *dev, *parent;
4789 wait_for_device_probe();
4790 device_block_probing();
4794 spin_lock(&devices_kset->list_lock);
4796 * Walk the devices list backward, shutting down each in turn.
4797 * Beware that device unplug events may also start pulling
4798 * devices offline, even as the system is shutting down.
4800 while (!list_empty(&devices_kset->list)) {
4801 dev = list_entry(devices_kset->list.prev, struct device,
4805 * hold reference count of device's parent to
4806 * prevent it from being freed because parent's
4807 * lock is to be held
4809 parent = get_device(dev->parent);
4812 * Make sure the device is off the kset list, in the
4813 * event that dev->*->shutdown() doesn't remove it.
4815 list_del_init(&dev->kobj.entry);
4816 spin_unlock(&devices_kset->list_lock);
4818 /* hold lock to avoid race with probe/release */
4820 device_lock(parent);
4823 /* Don't allow any more runtime suspends */
4824 pm_runtime_get_noresume(dev);
4825 pm_runtime_barrier(dev);
4827 if (dev->class && dev->class->shutdown_pre) {
4829 dev_info(dev, "shutdown_pre\n");
4830 dev->class->shutdown_pre(dev);
4832 if (dev->bus && dev->bus->shutdown) {
4834 dev_info(dev, "shutdown\n");
4835 dev->bus->shutdown(dev);
4836 } else if (dev->driver && dev->driver->shutdown) {
4838 dev_info(dev, "shutdown\n");
4839 dev->driver->shutdown(dev);
4844 device_unlock(parent);
4849 spin_lock(&devices_kset->list_lock);
4851 spin_unlock(&devices_kset->list_lock);
4855 * Device logging functions
4858 #ifdef CONFIG_PRINTK
4860 set_dev_info(const struct device *dev, struct dev_printk_info *dev_info)
4864 memset(dev_info, 0, sizeof(*dev_info));
4867 subsys = dev->class->name;
4869 subsys = dev->bus->name;
4873 strscpy(dev_info->subsystem, subsys);
4876 * Add device identifier DEVICE=:
4880 * +sound:card0 subsystem:devname
4882 if (MAJOR(dev->devt)) {
4885 if (strcmp(subsys, "block") == 0)
4890 snprintf(dev_info->device, sizeof(dev_info->device),
4891 "%c%u:%u", c, MAJOR(dev->devt), MINOR(dev->devt));
4892 } else if (strcmp(subsys, "net") == 0) {
4893 struct net_device *net = to_net_dev(dev);
4895 snprintf(dev_info->device, sizeof(dev_info->device),
4896 "n%u", net->ifindex);
4898 snprintf(dev_info->device, sizeof(dev_info->device),
4899 "+%s:%s", subsys, dev_name(dev));
4903 int dev_vprintk_emit(int level, const struct device *dev,
4904 const char *fmt, va_list args)
4906 struct dev_printk_info dev_info;
4908 set_dev_info(dev, &dev_info);
4910 return vprintk_emit(0, level, &dev_info, fmt, args);
4912 EXPORT_SYMBOL(dev_vprintk_emit);
4914 int dev_printk_emit(int level, const struct device *dev, const char *fmt, ...)
4919 va_start(args, fmt);
4921 r = dev_vprintk_emit(level, dev, fmt, args);
4927 EXPORT_SYMBOL(dev_printk_emit);
4929 static void __dev_printk(const char *level, const struct device *dev,
4930 struct va_format *vaf)
4933 dev_printk_emit(level[1] - '0', dev, "%s %s: %pV",
4934 dev_driver_string(dev), dev_name(dev), vaf);
4936 printk("%s(NULL device *): %pV", level, vaf);
4939 void _dev_printk(const char *level, const struct device *dev,
4940 const char *fmt, ...)
4942 struct va_format vaf;
4945 va_start(args, fmt);
4950 __dev_printk(level, dev, &vaf);
4954 EXPORT_SYMBOL(_dev_printk);
4956 #define define_dev_printk_level(func, kern_level) \
4957 void func(const struct device *dev, const char *fmt, ...) \
4959 struct va_format vaf; \
4962 va_start(args, fmt); \
4967 __dev_printk(kern_level, dev, &vaf); \
4971 EXPORT_SYMBOL(func);
4973 define_dev_printk_level(_dev_emerg, KERN_EMERG);
4974 define_dev_printk_level(_dev_alert, KERN_ALERT);
4975 define_dev_printk_level(_dev_crit, KERN_CRIT);
4976 define_dev_printk_level(_dev_err, KERN_ERR);
4977 define_dev_printk_level(_dev_warn, KERN_WARNING);
4978 define_dev_printk_level(_dev_notice, KERN_NOTICE);
4979 define_dev_printk_level(_dev_info, KERN_INFO);
4984 * dev_err_probe - probe error check and log helper
4985 * @dev: the pointer to the struct device
4986 * @err: error value to test
4987 * @fmt: printf-style format string
4988 * @...: arguments as specified in the format string
4990 * This helper implements common pattern present in probe functions for error
4991 * checking: print debug or error message depending if the error value is
4992 * -EPROBE_DEFER and propagate error upwards.
4993 * In case of -EPROBE_DEFER it sets also defer probe reason, which can be
4994 * checked later by reading devices_deferred debugfs attribute.
4995 * It replaces code sequence::
4997 * if (err != -EPROBE_DEFER)
4998 * dev_err(dev, ...);
5000 * dev_dbg(dev, ...);
5005 * return dev_err_probe(dev, err, ...);
5007 * Using this helper in your probe function is totally fine even if @err is
5008 * known to never be -EPROBE_DEFER.
5009 * The benefit compared to a normal dev_err() is the standardized format
5010 * of the error code, it being emitted symbolically (i.e. you get "EAGAIN"
5011 * instead of "-35") and the fact that the error code is returned which allows
5012 * more compact error paths.
5016 int dev_err_probe(const struct device *dev, int err, const char *fmt, ...)
5018 struct va_format vaf;
5021 va_start(args, fmt);
5027 device_set_deferred_probe_reason(dev, &vaf);
5028 dev_dbg(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
5033 * We don't print anything on -ENOMEM, there is already enough
5039 dev_err(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
5047 EXPORT_SYMBOL_GPL(dev_err_probe);
5049 static inline bool fwnode_is_primary(struct fwnode_handle *fwnode)
5051 return fwnode && !IS_ERR(fwnode->secondary);
5055 * set_primary_fwnode - Change the primary firmware node of a given device.
5056 * @dev: Device to handle.
5057 * @fwnode: New primary firmware node of the device.
5059 * Set the device's firmware node pointer to @fwnode, but if a secondary
5060 * firmware node of the device is present, preserve it.
5062 * Valid fwnode cases are:
5063 * - primary --> secondary --> -ENODEV
5064 * - primary --> NULL
5065 * - secondary --> -ENODEV
5068 void set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
5070 struct device *parent = dev->parent;
5071 struct fwnode_handle *fn = dev->fwnode;
5074 if (fwnode_is_primary(fn))
5078 WARN_ON(fwnode->secondary);
5079 fwnode->secondary = fn;
5081 dev->fwnode = fwnode;
5083 if (fwnode_is_primary(fn)) {
5084 dev->fwnode = fn->secondary;
5086 /* Skip nullifying fn->secondary if the primary is shared */
5087 if (parent && fn == parent->fwnode)
5090 /* Set fn->secondary = NULL, so fn remains the primary fwnode */
5091 fn->secondary = NULL;
5097 EXPORT_SYMBOL_GPL(set_primary_fwnode);
5100 * set_secondary_fwnode - Change the secondary firmware node of a given device.
5101 * @dev: Device to handle.
5102 * @fwnode: New secondary firmware node of the device.
5104 * If a primary firmware node of the device is present, set its secondary
5105 * pointer to @fwnode. Otherwise, set the device's firmware node pointer to
5108 void set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
5111 fwnode->secondary = ERR_PTR(-ENODEV);
5113 if (fwnode_is_primary(dev->fwnode))
5114 dev->fwnode->secondary = fwnode;
5116 dev->fwnode = fwnode;
5118 EXPORT_SYMBOL_GPL(set_secondary_fwnode);
5121 * device_set_of_node_from_dev - reuse device-tree node of another device
5122 * @dev: device whose device-tree node is being set
5123 * @dev2: device whose device-tree node is being reused
5125 * Takes another reference to the new device-tree node after first dropping
5126 * any reference held to the old node.
5128 void device_set_of_node_from_dev(struct device *dev, const struct device *dev2)
5130 of_node_put(dev->of_node);
5131 dev->of_node = of_node_get(dev2->of_node);
5132 dev->of_node_reused = true;
5134 EXPORT_SYMBOL_GPL(device_set_of_node_from_dev);
5136 void device_set_node(struct device *dev, struct fwnode_handle *fwnode)
5138 dev->fwnode = fwnode;
5139 dev->of_node = to_of_node(fwnode);
5141 EXPORT_SYMBOL_GPL(device_set_node);
5143 int device_match_name(struct device *dev, const void *name)
5145 return sysfs_streq(dev_name(dev), name);
5147 EXPORT_SYMBOL_GPL(device_match_name);
5149 int device_match_of_node(struct device *dev, const void *np)
5151 return dev->of_node == np;
5153 EXPORT_SYMBOL_GPL(device_match_of_node);
5155 int device_match_fwnode(struct device *dev, const void *fwnode)
5157 return dev_fwnode(dev) == fwnode;
5159 EXPORT_SYMBOL_GPL(device_match_fwnode);
5161 int device_match_devt(struct device *dev, const void *pdevt)
5163 return dev->devt == *(dev_t *)pdevt;
5165 EXPORT_SYMBOL_GPL(device_match_devt);
5167 int device_match_acpi_dev(struct device *dev, const void *adev)
5169 return ACPI_COMPANION(dev) == adev;
5171 EXPORT_SYMBOL(device_match_acpi_dev);
5173 int device_match_acpi_handle(struct device *dev, const void *handle)
5175 return ACPI_HANDLE(dev) == handle;
5177 EXPORT_SYMBOL(device_match_acpi_handle);
5179 int device_match_any(struct device *dev, const void *unused)
5183 EXPORT_SYMBOL_GPL(device_match_any);