1 // SPDX-License-Identifier: GPL-2.0
3 * drivers/base/core.c - core driver model code (device registration, etc)
5 * Copyright (c) 2002-3 Patrick Mochel
6 * Copyright (c) 2002-3 Open Source Development Labs
7 * Copyright (c) 2006 Greg Kroah-Hartman <gregkh@suse.de>
8 * Copyright (c) 2006 Novell, Inc.
11 #include <linux/acpi.h>
12 #include <linux/cpufreq.h>
13 #include <linux/device.h>
14 #include <linux/err.h>
15 #include <linux/fwnode.h>
16 #include <linux/init.h>
17 #include <linux/module.h>
18 #include <linux/slab.h>
19 #include <linux/string.h>
20 #include <linux/kdev_t.h>
21 #include <linux/notifier.h>
23 #include <linux/of_device.h>
24 #include <linux/genhd.h>
25 #include <linux/mutex.h>
26 #include <linux/pm_runtime.h>
27 #include <linux/netdevice.h>
28 #include <linux/sched/signal.h>
29 #include <linux/sched/mm.h>
30 #include <linux/sysfs.h>
33 #include "power/power.h"
35 #ifdef CONFIG_SYSFS_DEPRECATED
36 #ifdef CONFIG_SYSFS_DEPRECATED_V2
37 long sysfs_deprecated = 1;
39 long sysfs_deprecated = 0;
41 static int __init sysfs_deprecated_setup(char *arg)
43 return kstrtol(arg, 10, &sysfs_deprecated);
45 early_param("sysfs.deprecated", sysfs_deprecated_setup);
48 /* Device links support. */
49 static LIST_HEAD(wait_for_suppliers);
50 static DEFINE_MUTEX(wfs_lock);
51 static LIST_HEAD(deferred_sync);
52 static unsigned int defer_sync_state_count = 1;
53 static unsigned int defer_fw_devlink_count;
54 static DEFINE_MUTEX(defer_fw_devlink_lock);
55 static bool fw_devlink_is_permissive(void);
58 static DEFINE_MUTEX(device_links_lock);
59 DEFINE_STATIC_SRCU(device_links_srcu);
61 static inline void device_links_write_lock(void)
63 mutex_lock(&device_links_lock);
66 static inline void device_links_write_unlock(void)
68 mutex_unlock(&device_links_lock);
71 int device_links_read_lock(void) __acquires(&device_links_srcu)
73 return srcu_read_lock(&device_links_srcu);
76 void device_links_read_unlock(int idx) __releases(&device_links_srcu)
78 srcu_read_unlock(&device_links_srcu, idx);
81 int device_links_read_lock_held(void)
83 return srcu_read_lock_held(&device_links_srcu);
85 #else /* !CONFIG_SRCU */
86 static DECLARE_RWSEM(device_links_lock);
88 static inline void device_links_write_lock(void)
90 down_write(&device_links_lock);
93 static inline void device_links_write_unlock(void)
95 up_write(&device_links_lock);
98 int device_links_read_lock(void)
100 down_read(&device_links_lock);
104 void device_links_read_unlock(int not_used)
106 up_read(&device_links_lock);
109 #ifdef CONFIG_DEBUG_LOCK_ALLOC
110 int device_links_read_lock_held(void)
112 return lockdep_is_held(&device_links_lock);
115 #endif /* !CONFIG_SRCU */
118 * device_is_dependent - Check if one device depends on another one
119 * @dev: Device to check dependencies for.
120 * @target: Device to check against.
122 * Check if @target depends on @dev or any device dependent on it (its child or
123 * its consumer etc). Return 1 if that is the case or 0 otherwise.
125 int device_is_dependent(struct device *dev, void *target)
127 struct device_link *link;
133 ret = device_for_each_child(dev, target, device_is_dependent);
137 list_for_each_entry(link, &dev->links.consumers, s_node) {
138 if (link->flags == (DL_FLAG_SYNC_STATE_ONLY | DL_FLAG_MANAGED))
141 if (link->consumer == target)
144 ret = device_is_dependent(link->consumer, target);
151 static void device_link_init_status(struct device_link *link,
152 struct device *consumer,
153 struct device *supplier)
155 switch (supplier->links.status) {
157 switch (consumer->links.status) {
160 * A consumer driver can create a link to a supplier
161 * that has not completed its probing yet as long as it
162 * knows that the supplier is already functional (for
163 * example, it has just acquired some resources from the
166 link->status = DL_STATE_CONSUMER_PROBE;
169 link->status = DL_STATE_DORMANT;
173 case DL_DEV_DRIVER_BOUND:
174 switch (consumer->links.status) {
176 link->status = DL_STATE_CONSUMER_PROBE;
178 case DL_DEV_DRIVER_BOUND:
179 link->status = DL_STATE_ACTIVE;
182 link->status = DL_STATE_AVAILABLE;
186 case DL_DEV_UNBINDING:
187 link->status = DL_STATE_SUPPLIER_UNBIND;
190 link->status = DL_STATE_DORMANT;
195 static int device_reorder_to_tail(struct device *dev, void *not_used)
197 struct device_link *link;
200 * Devices that have not been registered yet will be put to the ends
201 * of the lists during the registration, so skip them here.
203 if (device_is_registered(dev))
204 devices_kset_move_last(dev);
206 if (device_pm_initialized(dev))
207 device_pm_move_last(dev);
209 device_for_each_child(dev, NULL, device_reorder_to_tail);
210 list_for_each_entry(link, &dev->links.consumers, s_node) {
211 if (link->flags == (DL_FLAG_SYNC_STATE_ONLY | DL_FLAG_MANAGED))
213 device_reorder_to_tail(link->consumer, NULL);
220 * device_pm_move_to_tail - Move set of devices to the end of device lists
221 * @dev: Device to move
223 * This is a device_reorder_to_tail() wrapper taking the requisite locks.
225 * It moves the @dev along with all of its children and all of its consumers
226 * to the ends of the device_kset and dpm_list, recursively.
228 void device_pm_move_to_tail(struct device *dev)
232 idx = device_links_read_lock();
234 device_reorder_to_tail(dev, NULL);
236 device_links_read_unlock(idx);
239 #define to_devlink(dev) container_of((dev), struct device_link, link_dev)
241 static ssize_t status_show(struct device *dev,
242 struct device_attribute *attr, char *buf)
246 switch (to_devlink(dev)->status) {
248 output = "not tracked";
250 case DL_STATE_DORMANT:
253 case DL_STATE_AVAILABLE:
254 output = "available";
256 case DL_STATE_CONSUMER_PROBE:
257 output = "consumer probing";
259 case DL_STATE_ACTIVE:
262 case DL_STATE_SUPPLIER_UNBIND:
263 output = "supplier unbinding";
270 return sysfs_emit(buf, "%s\n", output);
272 static DEVICE_ATTR_RO(status);
274 static ssize_t auto_remove_on_show(struct device *dev,
275 struct device_attribute *attr, char *buf)
277 struct device_link *link = to_devlink(dev);
280 if (link->flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
281 output = "supplier unbind";
282 else if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER)
283 output = "consumer unbind";
287 return sysfs_emit(buf, "%s\n", output);
289 static DEVICE_ATTR_RO(auto_remove_on);
291 static ssize_t runtime_pm_show(struct device *dev,
292 struct device_attribute *attr, char *buf)
294 struct device_link *link = to_devlink(dev);
296 return sysfs_emit(buf, "%d\n", !!(link->flags & DL_FLAG_PM_RUNTIME));
298 static DEVICE_ATTR_RO(runtime_pm);
300 static ssize_t sync_state_only_show(struct device *dev,
301 struct device_attribute *attr, char *buf)
303 struct device_link *link = to_devlink(dev);
305 return sysfs_emit(buf, "%d\n",
306 !!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
308 static DEVICE_ATTR_RO(sync_state_only);
310 static struct attribute *devlink_attrs[] = {
311 &dev_attr_status.attr,
312 &dev_attr_auto_remove_on.attr,
313 &dev_attr_runtime_pm.attr,
314 &dev_attr_sync_state_only.attr,
317 ATTRIBUTE_GROUPS(devlink);
319 static void device_link_free(struct device_link *link)
321 while (refcount_dec_not_one(&link->rpm_active))
322 pm_runtime_put(link->supplier);
324 put_device(link->consumer);
325 put_device(link->supplier);
330 static void __device_link_free_srcu(struct rcu_head *rhead)
332 device_link_free(container_of(rhead, struct device_link, rcu_head));
335 static void devlink_dev_release(struct device *dev)
337 struct device_link *link = to_devlink(dev);
339 call_srcu(&device_links_srcu, &link->rcu_head, __device_link_free_srcu);
342 static void devlink_dev_release(struct device *dev)
344 device_link_free(to_devlink(dev));
348 static struct class devlink_class = {
350 .owner = THIS_MODULE,
351 .dev_groups = devlink_groups,
352 .dev_release = devlink_dev_release,
355 static int devlink_add_symlinks(struct device *dev,
356 struct class_interface *class_intf)
360 struct device_link *link = to_devlink(dev);
361 struct device *sup = link->supplier;
362 struct device *con = link->consumer;
365 len = max(strlen(dev_name(sup)), strlen(dev_name(con)));
366 len += strlen("supplier:") + 1;
367 buf = kzalloc(len, GFP_KERNEL);
371 ret = sysfs_create_link(&link->link_dev.kobj, &sup->kobj, "supplier");
375 ret = sysfs_create_link(&link->link_dev.kobj, &con->kobj, "consumer");
379 snprintf(buf, len, "consumer:%s", dev_name(con));
380 ret = sysfs_create_link(&sup->kobj, &link->link_dev.kobj, buf);
384 snprintf(buf, len, "supplier:%s", dev_name(sup));
385 ret = sysfs_create_link(&con->kobj, &link->link_dev.kobj, buf);
392 snprintf(buf, len, "consumer:%s", dev_name(con));
393 sysfs_remove_link(&sup->kobj, buf);
395 sysfs_remove_link(&link->link_dev.kobj, "consumer");
397 sysfs_remove_link(&link->link_dev.kobj, "supplier");
403 static void devlink_remove_symlinks(struct device *dev,
404 struct class_interface *class_intf)
406 struct device_link *link = to_devlink(dev);
408 struct device *sup = link->supplier;
409 struct device *con = link->consumer;
412 sysfs_remove_link(&link->link_dev.kobj, "consumer");
413 sysfs_remove_link(&link->link_dev.kobj, "supplier");
415 len = max(strlen(dev_name(sup)), strlen(dev_name(con)));
416 len += strlen("supplier:") + 1;
417 buf = kzalloc(len, GFP_KERNEL);
419 WARN(1, "Unable to properly free device link symlinks!\n");
423 snprintf(buf, len, "supplier:%s", dev_name(sup));
424 sysfs_remove_link(&con->kobj, buf);
425 snprintf(buf, len, "consumer:%s", dev_name(con));
426 sysfs_remove_link(&sup->kobj, buf);
430 static struct class_interface devlink_class_intf = {
431 .class = &devlink_class,
432 .add_dev = devlink_add_symlinks,
433 .remove_dev = devlink_remove_symlinks,
436 static int __init devlink_class_init(void)
440 ret = class_register(&devlink_class);
444 ret = class_interface_register(&devlink_class_intf);
446 class_unregister(&devlink_class);
450 postcore_initcall(devlink_class_init);
452 #define DL_MANAGED_LINK_FLAGS (DL_FLAG_AUTOREMOVE_CONSUMER | \
453 DL_FLAG_AUTOREMOVE_SUPPLIER | \
454 DL_FLAG_AUTOPROBE_CONSUMER | \
455 DL_FLAG_SYNC_STATE_ONLY)
457 #define DL_ADD_VALID_FLAGS (DL_MANAGED_LINK_FLAGS | DL_FLAG_STATELESS | \
458 DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE)
461 * device_link_add - Create a link between two devices.
462 * @consumer: Consumer end of the link.
463 * @supplier: Supplier end of the link.
464 * @flags: Link flags.
466 * The caller is responsible for the proper synchronization of the link creation
467 * with runtime PM. First, setting the DL_FLAG_PM_RUNTIME flag will cause the
468 * runtime PM framework to take the link into account. Second, if the
469 * DL_FLAG_RPM_ACTIVE flag is set in addition to it, the supplier devices will
470 * be forced into the active metastate and reference-counted upon the creation
471 * of the link. If DL_FLAG_PM_RUNTIME is not set, DL_FLAG_RPM_ACTIVE will be
474 * If DL_FLAG_STATELESS is set in @flags, the caller of this function is
475 * expected to release the link returned by it directly with the help of either
476 * device_link_del() or device_link_remove().
478 * If that flag is not set, however, the caller of this function is handing the
479 * management of the link over to the driver core entirely and its return value
480 * can only be used to check whether or not the link is present. In that case,
481 * the DL_FLAG_AUTOREMOVE_CONSUMER and DL_FLAG_AUTOREMOVE_SUPPLIER device link
482 * flags can be used to indicate to the driver core when the link can be safely
483 * deleted. Namely, setting one of them in @flags indicates to the driver core
484 * that the link is not going to be used (by the given caller of this function)
485 * after unbinding the consumer or supplier driver, respectively, from its
486 * device, so the link can be deleted at that point. If none of them is set,
487 * the link will be maintained until one of the devices pointed to by it (either
488 * the consumer or the supplier) is unregistered.
490 * Also, if DL_FLAG_STATELESS, DL_FLAG_AUTOREMOVE_CONSUMER and
491 * DL_FLAG_AUTOREMOVE_SUPPLIER are not set in @flags (that is, a persistent
492 * managed device link is being added), the DL_FLAG_AUTOPROBE_CONSUMER flag can
493 * be used to request the driver core to automaticall probe for a consmer
494 * driver after successfully binding a driver to the supplier device.
496 * The combination of DL_FLAG_STATELESS and one of DL_FLAG_AUTOREMOVE_CONSUMER,
497 * DL_FLAG_AUTOREMOVE_SUPPLIER, or DL_FLAG_AUTOPROBE_CONSUMER set in @flags at
498 * the same time is invalid and will cause NULL to be returned upfront.
499 * However, if a device link between the given @consumer and @supplier pair
500 * exists already when this function is called for them, the existing link will
501 * be returned regardless of its current type and status (the link's flags may
502 * be modified then). The caller of this function is then expected to treat
503 * the link as though it has just been created, so (in particular) if
504 * DL_FLAG_STATELESS was passed in @flags, the link needs to be released
505 * explicitly when not needed any more (as stated above).
507 * A side effect of the link creation is re-ordering of dpm_list and the
508 * devices_kset list by moving the consumer device and all devices depending
509 * on it to the ends of these lists (that does not happen to devices that have
510 * not been registered when this function is called).
512 * The supplier device is required to be registered when this function is called
513 * and NULL will be returned if that is not the case. The consumer device need
514 * not be registered, however.
516 struct device_link *device_link_add(struct device *consumer,
517 struct device *supplier, u32 flags)
519 struct device_link *link;
521 if (!consumer || !supplier || flags & ~DL_ADD_VALID_FLAGS ||
522 (flags & DL_FLAG_STATELESS && flags & DL_MANAGED_LINK_FLAGS) ||
523 (flags & DL_FLAG_SYNC_STATE_ONLY &&
524 flags != DL_FLAG_SYNC_STATE_ONLY) ||
525 (flags & DL_FLAG_AUTOPROBE_CONSUMER &&
526 flags & (DL_FLAG_AUTOREMOVE_CONSUMER |
527 DL_FLAG_AUTOREMOVE_SUPPLIER)))
530 if (flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) {
531 if (pm_runtime_get_sync(supplier) < 0) {
532 pm_runtime_put_noidle(supplier);
537 if (!(flags & DL_FLAG_STATELESS))
538 flags |= DL_FLAG_MANAGED;
540 device_links_write_lock();
544 * If the supplier has not been fully registered yet or there is a
545 * reverse (non-SYNC_STATE_ONLY) dependency between the consumer and
546 * the supplier already in the graph, return NULL. If the link is a
547 * SYNC_STATE_ONLY link, we don't check for reverse dependencies
548 * because it only affects sync_state() callbacks.
550 if (!device_pm_initialized(supplier)
551 || (!(flags & DL_FLAG_SYNC_STATE_ONLY) &&
552 device_is_dependent(consumer, supplier))) {
558 * DL_FLAG_AUTOREMOVE_SUPPLIER indicates that the link will be needed
559 * longer than for DL_FLAG_AUTOREMOVE_CONSUMER and setting them both
560 * together doesn't make sense, so prefer DL_FLAG_AUTOREMOVE_SUPPLIER.
562 if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
563 flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
565 list_for_each_entry(link, &supplier->links.consumers, s_node) {
566 if (link->consumer != consumer)
569 if (flags & DL_FLAG_PM_RUNTIME) {
570 if (!(link->flags & DL_FLAG_PM_RUNTIME)) {
571 pm_runtime_new_link(consumer);
572 link->flags |= DL_FLAG_PM_RUNTIME;
574 if (flags & DL_FLAG_RPM_ACTIVE)
575 refcount_inc(&link->rpm_active);
578 if (flags & DL_FLAG_STATELESS) {
579 kref_get(&link->kref);
580 if (link->flags & DL_FLAG_SYNC_STATE_ONLY &&
581 !(link->flags & DL_FLAG_STATELESS)) {
582 link->flags |= DL_FLAG_STATELESS;
585 link->flags |= DL_FLAG_STATELESS;
591 * If the life time of the link following from the new flags is
592 * longer than indicated by the flags of the existing link,
593 * update the existing link to stay around longer.
595 if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER) {
596 if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER) {
597 link->flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
598 link->flags |= DL_FLAG_AUTOREMOVE_SUPPLIER;
600 } else if (!(flags & DL_FLAG_AUTOREMOVE_CONSUMER)) {
601 link->flags &= ~(DL_FLAG_AUTOREMOVE_CONSUMER |
602 DL_FLAG_AUTOREMOVE_SUPPLIER);
604 if (!(link->flags & DL_FLAG_MANAGED)) {
605 kref_get(&link->kref);
606 link->flags |= DL_FLAG_MANAGED;
607 device_link_init_status(link, consumer, supplier);
609 if (link->flags & DL_FLAG_SYNC_STATE_ONLY &&
610 !(flags & DL_FLAG_SYNC_STATE_ONLY)) {
611 link->flags &= ~DL_FLAG_SYNC_STATE_ONLY;
618 link = kzalloc(sizeof(*link), GFP_KERNEL);
622 refcount_set(&link->rpm_active, 1);
624 get_device(supplier);
625 link->supplier = supplier;
626 INIT_LIST_HEAD(&link->s_node);
627 get_device(consumer);
628 link->consumer = consumer;
629 INIT_LIST_HEAD(&link->c_node);
631 kref_init(&link->kref);
633 link->link_dev.class = &devlink_class;
634 device_set_pm_not_required(&link->link_dev);
635 dev_set_name(&link->link_dev, "%s--%s",
636 dev_name(supplier), dev_name(consumer));
637 if (device_register(&link->link_dev)) {
638 put_device(consumer);
639 put_device(supplier);
645 if (flags & DL_FLAG_PM_RUNTIME) {
646 if (flags & DL_FLAG_RPM_ACTIVE)
647 refcount_inc(&link->rpm_active);
649 pm_runtime_new_link(consumer);
652 /* Determine the initial link state. */
653 if (flags & DL_FLAG_STATELESS)
654 link->status = DL_STATE_NONE;
656 device_link_init_status(link, consumer, supplier);
659 * Some callers expect the link creation during consumer driver probe to
660 * resume the supplier even without DL_FLAG_RPM_ACTIVE.
662 if (link->status == DL_STATE_CONSUMER_PROBE &&
663 flags & DL_FLAG_PM_RUNTIME)
664 pm_runtime_resume(supplier);
666 list_add_tail_rcu(&link->s_node, &supplier->links.consumers);
667 list_add_tail_rcu(&link->c_node, &consumer->links.suppliers);
669 if (flags & DL_FLAG_SYNC_STATE_ONLY) {
671 "Linked as a sync state only consumer to %s\n",
678 * Move the consumer and all of the devices depending on it to the end
679 * of dpm_list and the devices_kset list.
681 * It is necessary to hold dpm_list locked throughout all that or else
682 * we may end up suspending with a wrong ordering of it.
684 device_reorder_to_tail(consumer, NULL);
686 dev_dbg(consumer, "Linked as a consumer to %s\n", dev_name(supplier));
690 device_links_write_unlock();
692 if ((flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) && !link)
693 pm_runtime_put(supplier);
697 EXPORT_SYMBOL_GPL(device_link_add);
700 * device_link_wait_for_supplier - Add device to wait_for_suppliers list
701 * @consumer: Consumer device
703 * Marks the @consumer device as waiting for suppliers to become available by
704 * adding it to the wait_for_suppliers list. The consumer device will never be
705 * probed until it's removed from the wait_for_suppliers list.
707 * The caller is responsible for adding the links to the supplier devices once
708 * they are available and removing the @consumer device from the
709 * wait_for_suppliers list once links to all the suppliers have been created.
711 * This function is NOT meant to be called from the probe function of the
712 * consumer but rather from code that creates/adds the consumer device.
714 static void device_link_wait_for_supplier(struct device *consumer,
717 mutex_lock(&wfs_lock);
718 list_add_tail(&consumer->links.needs_suppliers, &wait_for_suppliers);
719 consumer->links.need_for_probe = need_for_probe;
720 mutex_unlock(&wfs_lock);
723 static void device_link_wait_for_mandatory_supplier(struct device *consumer)
725 device_link_wait_for_supplier(consumer, true);
728 static void device_link_wait_for_optional_supplier(struct device *consumer)
730 device_link_wait_for_supplier(consumer, false);
734 * device_link_add_missing_supplier_links - Add links from consumer devices to
735 * supplier devices, leaving any
736 * consumer with inactive suppliers on
737 * the wait_for_suppliers list
739 * Loops through all consumers waiting on suppliers and tries to add all their
740 * supplier links. If that succeeds, the consumer device is removed from
741 * wait_for_suppliers list. Otherwise, they are left in the wait_for_suppliers
742 * list. Devices left on the wait_for_suppliers list will not be probed.
744 * The fwnode add_links callback is expected to return 0 if it has found and
745 * added all the supplier links for the consumer device. It should return an
746 * error if it isn't able to do so.
748 * The caller of device_link_wait_for_supplier() is expected to call this once
749 * it's aware of potential suppliers becoming available.
751 static void device_link_add_missing_supplier_links(void)
753 struct device *dev, *tmp;
755 mutex_lock(&wfs_lock);
756 list_for_each_entry_safe(dev, tmp, &wait_for_suppliers,
757 links.needs_suppliers) {
758 int ret = fwnode_call_int_op(dev->fwnode, add_links, dev);
760 list_del_init(&dev->links.needs_suppliers);
761 else if (ret != -ENODEV || fw_devlink_is_permissive())
762 dev->links.need_for_probe = false;
764 mutex_unlock(&wfs_lock);
768 static void __device_link_del(struct kref *kref)
770 struct device_link *link = container_of(kref, struct device_link, kref);
772 dev_dbg(link->consumer, "Dropping the link to %s\n",
773 dev_name(link->supplier));
775 pm_runtime_drop_link(link);
777 list_del_rcu(&link->s_node);
778 list_del_rcu(&link->c_node);
779 device_unregister(&link->link_dev);
781 #else /* !CONFIG_SRCU */
782 static void __device_link_del(struct kref *kref)
784 struct device_link *link = container_of(kref, struct device_link, kref);
786 dev_info(link->consumer, "Dropping the link to %s\n",
787 dev_name(link->supplier));
789 pm_runtime_drop_link(link);
791 list_del(&link->s_node);
792 list_del(&link->c_node);
793 device_unregister(&link->link_dev);
795 #endif /* !CONFIG_SRCU */
797 static void device_link_put_kref(struct device_link *link)
799 if (link->flags & DL_FLAG_STATELESS)
800 kref_put(&link->kref, __device_link_del);
802 WARN(1, "Unable to drop a managed device link reference\n");
806 * device_link_del - Delete a stateless link between two devices.
807 * @link: Device link to delete.
809 * The caller must ensure proper synchronization of this function with runtime
810 * PM. If the link was added multiple times, it needs to be deleted as often.
811 * Care is required for hotplugged devices: Their links are purged on removal
812 * and calling device_link_del() is then no longer allowed.
814 void device_link_del(struct device_link *link)
816 device_links_write_lock();
817 device_link_put_kref(link);
818 device_links_write_unlock();
820 EXPORT_SYMBOL_GPL(device_link_del);
823 * device_link_remove - Delete a stateless link between two devices.
824 * @consumer: Consumer end of the link.
825 * @supplier: Supplier end of the link.
827 * The caller must ensure proper synchronization of this function with runtime
830 void device_link_remove(void *consumer, struct device *supplier)
832 struct device_link *link;
834 if (WARN_ON(consumer == supplier))
837 device_links_write_lock();
839 list_for_each_entry(link, &supplier->links.consumers, s_node) {
840 if (link->consumer == consumer) {
841 device_link_put_kref(link);
846 device_links_write_unlock();
848 EXPORT_SYMBOL_GPL(device_link_remove);
850 static void device_links_missing_supplier(struct device *dev)
852 struct device_link *link;
854 list_for_each_entry(link, &dev->links.suppliers, c_node) {
855 if (link->status != DL_STATE_CONSUMER_PROBE)
858 if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
859 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
861 WARN_ON(!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
862 WRITE_ONCE(link->status, DL_STATE_DORMANT);
868 * device_links_check_suppliers - Check presence of supplier drivers.
869 * @dev: Consumer device.
871 * Check links from this device to any suppliers. Walk the list of the device's
872 * links to suppliers and see if all of them are available. If not, simply
873 * return -EPROBE_DEFER.
875 * We need to guarantee that the supplier will not go away after the check has
876 * been positive here. It only can go away in __device_release_driver() and
877 * that function checks the device's links to consumers. This means we need to
878 * mark the link as "consumer probe in progress" to make the supplier removal
879 * wait for us to complete (or bad things may happen).
881 * Links without the DL_FLAG_MANAGED flag set are ignored.
883 int device_links_check_suppliers(struct device *dev)
885 struct device_link *link;
889 * Device waiting for supplier to become available is not allowed to
892 mutex_lock(&wfs_lock);
893 if (!list_empty(&dev->links.needs_suppliers) &&
894 dev->links.need_for_probe) {
895 mutex_unlock(&wfs_lock);
896 return -EPROBE_DEFER;
898 mutex_unlock(&wfs_lock);
900 device_links_write_lock();
902 list_for_each_entry(link, &dev->links.suppliers, c_node) {
903 if (!(link->flags & DL_FLAG_MANAGED))
906 if (link->status != DL_STATE_AVAILABLE &&
907 !(link->flags & DL_FLAG_SYNC_STATE_ONLY)) {
908 device_links_missing_supplier(dev);
912 WRITE_ONCE(link->status, DL_STATE_CONSUMER_PROBE);
914 dev->links.status = DL_DEV_PROBING;
916 device_links_write_unlock();
921 * __device_links_queue_sync_state - Queue a device for sync_state() callback
922 * @dev: Device to call sync_state() on
923 * @list: List head to queue the @dev on
925 * Queues a device for a sync_state() callback when the device links write lock
926 * isn't held. This allows the sync_state() execution flow to use device links
927 * APIs. The caller must ensure this function is called with
928 * device_links_write_lock() held.
930 * This function does a get_device() to make sure the device is not freed while
933 * So the caller must also ensure that device_links_flush_sync_list() is called
934 * as soon as the caller releases device_links_write_lock(). This is necessary
935 * to make sure the sync_state() is called in a timely fashion and the
936 * put_device() is called on this device.
938 static void __device_links_queue_sync_state(struct device *dev,
939 struct list_head *list)
941 struct device_link *link;
943 if (!dev_has_sync_state(dev))
945 if (dev->state_synced)
948 list_for_each_entry(link, &dev->links.consumers, s_node) {
949 if (!(link->flags & DL_FLAG_MANAGED))
951 if (link->status != DL_STATE_ACTIVE)
956 * Set the flag here to avoid adding the same device to a list more
957 * than once. This can happen if new consumers get added to the device
958 * and probed before the list is flushed.
960 dev->state_synced = true;
962 if (WARN_ON(!list_empty(&dev->links.defer_hook)))
966 list_add_tail(&dev->links.defer_hook, list);
970 * device_links_flush_sync_list - Call sync_state() on a list of devices
971 * @list: List of devices to call sync_state() on
972 * @dont_lock_dev: Device for which lock is already held by the caller
974 * Calls sync_state() on all the devices that have been queued for it. This
975 * function is used in conjunction with __device_links_queue_sync_state(). The
976 * @dont_lock_dev parameter is useful when this function is called from a
977 * context where a device lock is already held.
979 static void device_links_flush_sync_list(struct list_head *list,
980 struct device *dont_lock_dev)
982 struct device *dev, *tmp;
984 list_for_each_entry_safe(dev, tmp, list, links.defer_hook) {
985 list_del_init(&dev->links.defer_hook);
987 if (dev != dont_lock_dev)
990 if (dev->bus->sync_state)
991 dev->bus->sync_state(dev);
992 else if (dev->driver && dev->driver->sync_state)
993 dev->driver->sync_state(dev);
995 if (dev != dont_lock_dev)
1002 void device_links_supplier_sync_state_pause(void)
1004 device_links_write_lock();
1005 defer_sync_state_count++;
1006 device_links_write_unlock();
1009 void device_links_supplier_sync_state_resume(void)
1011 struct device *dev, *tmp;
1012 LIST_HEAD(sync_list);
1014 device_links_write_lock();
1015 if (!defer_sync_state_count) {
1016 WARN(true, "Unmatched sync_state pause/resume!");
1019 defer_sync_state_count--;
1020 if (defer_sync_state_count)
1023 list_for_each_entry_safe(dev, tmp, &deferred_sync, links.defer_hook) {
1025 * Delete from deferred_sync list before queuing it to
1026 * sync_list because defer_hook is used for both lists.
1028 list_del_init(&dev->links.defer_hook);
1029 __device_links_queue_sync_state(dev, &sync_list);
1032 device_links_write_unlock();
1034 device_links_flush_sync_list(&sync_list, NULL);
1037 static int sync_state_resume_initcall(void)
1039 device_links_supplier_sync_state_resume();
1042 late_initcall(sync_state_resume_initcall);
1044 static void __device_links_supplier_defer_sync(struct device *sup)
1046 if (list_empty(&sup->links.defer_hook) && dev_has_sync_state(sup))
1047 list_add_tail(&sup->links.defer_hook, &deferred_sync);
1050 static void device_link_drop_managed(struct device_link *link)
1052 link->flags &= ~DL_FLAG_MANAGED;
1053 WRITE_ONCE(link->status, DL_STATE_NONE);
1054 kref_put(&link->kref, __device_link_del);
1057 static ssize_t waiting_for_supplier_show(struct device *dev,
1058 struct device_attribute *attr,
1064 val = !list_empty(&dev->links.needs_suppliers)
1065 && dev->links.need_for_probe;
1067 return sysfs_emit(buf, "%u\n", val);
1069 static DEVICE_ATTR_RO(waiting_for_supplier);
1072 * device_links_driver_bound - Update device links after probing its driver.
1073 * @dev: Device to update the links for.
1075 * The probe has been successful, so update links from this device to any
1076 * consumers by changing their status to "available".
1078 * Also change the status of @dev's links to suppliers to "active".
1080 * Links without the DL_FLAG_MANAGED flag set are ignored.
1082 void device_links_driver_bound(struct device *dev)
1084 struct device_link *link, *ln;
1085 LIST_HEAD(sync_list);
1088 * If a device probes successfully, it's expected to have created all
1089 * the device links it needs to or make new device links as it needs
1090 * them. So, it no longer needs to wait on any suppliers.
1092 mutex_lock(&wfs_lock);
1093 list_del_init(&dev->links.needs_suppliers);
1094 mutex_unlock(&wfs_lock);
1095 device_remove_file(dev, &dev_attr_waiting_for_supplier);
1097 device_links_write_lock();
1099 list_for_each_entry(link, &dev->links.consumers, s_node) {
1100 if (!(link->flags & DL_FLAG_MANAGED))
1104 * Links created during consumer probe may be in the "consumer
1105 * probe" state to start with if the supplier is still probing
1106 * when they are created and they may become "active" if the
1107 * consumer probe returns first. Skip them here.
1109 if (link->status == DL_STATE_CONSUMER_PROBE ||
1110 link->status == DL_STATE_ACTIVE)
1113 WARN_ON(link->status != DL_STATE_DORMANT);
1114 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1116 if (link->flags & DL_FLAG_AUTOPROBE_CONSUMER)
1117 driver_deferred_probe_add(link->consumer);
1120 if (defer_sync_state_count)
1121 __device_links_supplier_defer_sync(dev);
1123 __device_links_queue_sync_state(dev, &sync_list);
1125 list_for_each_entry_safe(link, ln, &dev->links.suppliers, c_node) {
1126 struct device *supplier;
1128 if (!(link->flags & DL_FLAG_MANAGED))
1131 supplier = link->supplier;
1132 if (link->flags & DL_FLAG_SYNC_STATE_ONLY) {
1134 * When DL_FLAG_SYNC_STATE_ONLY is set, it means no
1135 * other DL_MANAGED_LINK_FLAGS have been set. So, it's
1136 * save to drop the managed link completely.
1138 device_link_drop_managed(link);
1140 WARN_ON(link->status != DL_STATE_CONSUMER_PROBE);
1141 WRITE_ONCE(link->status, DL_STATE_ACTIVE);
1145 * This needs to be done even for the deleted
1146 * DL_FLAG_SYNC_STATE_ONLY device link in case it was the last
1147 * device link that was preventing the supplier from getting a
1148 * sync_state() call.
1150 if (defer_sync_state_count)
1151 __device_links_supplier_defer_sync(supplier);
1153 __device_links_queue_sync_state(supplier, &sync_list);
1156 dev->links.status = DL_DEV_DRIVER_BOUND;
1158 device_links_write_unlock();
1160 device_links_flush_sync_list(&sync_list, dev);
1164 * __device_links_no_driver - Update links of a device without a driver.
1165 * @dev: Device without a drvier.
1167 * Delete all non-persistent links from this device to any suppliers.
1169 * Persistent links stay around, but their status is changed to "available",
1170 * unless they already are in the "supplier unbind in progress" state in which
1171 * case they need not be updated.
1173 * Links without the DL_FLAG_MANAGED flag set are ignored.
1175 static void __device_links_no_driver(struct device *dev)
1177 struct device_link *link, *ln;
1179 list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1180 if (!(link->flags & DL_FLAG_MANAGED))
1183 if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER) {
1184 device_link_drop_managed(link);
1188 if (link->status != DL_STATE_CONSUMER_PROBE &&
1189 link->status != DL_STATE_ACTIVE)
1192 if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
1193 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1195 WARN_ON(!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
1196 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1200 dev->links.status = DL_DEV_NO_DRIVER;
1204 * device_links_no_driver - Update links after failing driver probe.
1205 * @dev: Device whose driver has just failed to probe.
1207 * Clean up leftover links to consumers for @dev and invoke
1208 * %__device_links_no_driver() to update links to suppliers for it as
1211 * Links without the DL_FLAG_MANAGED flag set are ignored.
1213 void device_links_no_driver(struct device *dev)
1215 struct device_link *link;
1217 device_links_write_lock();
1219 list_for_each_entry(link, &dev->links.consumers, s_node) {
1220 if (!(link->flags & DL_FLAG_MANAGED))
1224 * The probe has failed, so if the status of the link is
1225 * "consumer probe" or "active", it must have been added by
1226 * a probing consumer while this device was still probing.
1227 * Change its state to "dormant", as it represents a valid
1228 * relationship, but it is not functionally meaningful.
1230 if (link->status == DL_STATE_CONSUMER_PROBE ||
1231 link->status == DL_STATE_ACTIVE)
1232 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1235 __device_links_no_driver(dev);
1237 device_links_write_unlock();
1241 * device_links_driver_cleanup - Update links after driver removal.
1242 * @dev: Device whose driver has just gone away.
1244 * Update links to consumers for @dev by changing their status to "dormant" and
1245 * invoke %__device_links_no_driver() to update links to suppliers for it as
1248 * Links without the DL_FLAG_MANAGED flag set are ignored.
1250 void device_links_driver_cleanup(struct device *dev)
1252 struct device_link *link, *ln;
1254 device_links_write_lock();
1256 list_for_each_entry_safe(link, ln, &dev->links.consumers, s_node) {
1257 if (!(link->flags & DL_FLAG_MANAGED))
1260 WARN_ON(link->flags & DL_FLAG_AUTOREMOVE_CONSUMER);
1261 WARN_ON(link->status != DL_STATE_SUPPLIER_UNBIND);
1264 * autoremove the links between this @dev and its consumer
1265 * devices that are not active, i.e. where the link state
1266 * has moved to DL_STATE_SUPPLIER_UNBIND.
1268 if (link->status == DL_STATE_SUPPLIER_UNBIND &&
1269 link->flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
1270 device_link_drop_managed(link);
1272 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1275 list_del_init(&dev->links.defer_hook);
1276 __device_links_no_driver(dev);
1278 device_links_write_unlock();
1282 * device_links_busy - Check if there are any busy links to consumers.
1283 * @dev: Device to check.
1285 * Check each consumer of the device and return 'true' if its link's status
1286 * is one of "consumer probe" or "active" (meaning that the given consumer is
1287 * probing right now or its driver is present). Otherwise, change the link
1288 * state to "supplier unbind" to prevent the consumer from being probed
1289 * successfully going forward.
1291 * Return 'false' if there are no probing or active consumers.
1293 * Links without the DL_FLAG_MANAGED flag set are ignored.
1295 bool device_links_busy(struct device *dev)
1297 struct device_link *link;
1300 device_links_write_lock();
1302 list_for_each_entry(link, &dev->links.consumers, s_node) {
1303 if (!(link->flags & DL_FLAG_MANAGED))
1306 if (link->status == DL_STATE_CONSUMER_PROBE
1307 || link->status == DL_STATE_ACTIVE) {
1311 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1314 dev->links.status = DL_DEV_UNBINDING;
1316 device_links_write_unlock();
1321 * device_links_unbind_consumers - Force unbind consumers of the given device.
1322 * @dev: Device to unbind the consumers of.
1324 * Walk the list of links to consumers for @dev and if any of them is in the
1325 * "consumer probe" state, wait for all device probes in progress to complete
1328 * If that's not the case, change the status of the link to "supplier unbind"
1329 * and check if the link was in the "active" state. If so, force the consumer
1330 * driver to unbind and start over (the consumer will not re-probe as we have
1331 * changed the state of the link already).
1333 * Links without the DL_FLAG_MANAGED flag set are ignored.
1335 void device_links_unbind_consumers(struct device *dev)
1337 struct device_link *link;
1340 device_links_write_lock();
1342 list_for_each_entry(link, &dev->links.consumers, s_node) {
1343 enum device_link_state status;
1345 if (!(link->flags & DL_FLAG_MANAGED) ||
1346 link->flags & DL_FLAG_SYNC_STATE_ONLY)
1349 status = link->status;
1350 if (status == DL_STATE_CONSUMER_PROBE) {
1351 device_links_write_unlock();
1353 wait_for_device_probe();
1356 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1357 if (status == DL_STATE_ACTIVE) {
1358 struct device *consumer = link->consumer;
1360 get_device(consumer);
1362 device_links_write_unlock();
1364 device_release_driver_internal(consumer, NULL,
1366 put_device(consumer);
1371 device_links_write_unlock();
1375 * device_links_purge - Delete existing links to other devices.
1376 * @dev: Target device.
1378 static void device_links_purge(struct device *dev)
1380 struct device_link *link, *ln;
1382 if (dev->class == &devlink_class)
1385 mutex_lock(&wfs_lock);
1386 list_del_init(&dev->links.needs_suppliers);
1387 mutex_unlock(&wfs_lock);
1390 * Delete all of the remaining links from this device to any other
1391 * devices (either consumers or suppliers).
1393 device_links_write_lock();
1395 list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1396 WARN_ON(link->status == DL_STATE_ACTIVE);
1397 __device_link_del(&link->kref);
1400 list_for_each_entry_safe_reverse(link, ln, &dev->links.consumers, s_node) {
1401 WARN_ON(link->status != DL_STATE_DORMANT &&
1402 link->status != DL_STATE_NONE);
1403 __device_link_del(&link->kref);
1406 device_links_write_unlock();
1409 static u32 fw_devlink_flags = DL_FLAG_SYNC_STATE_ONLY;
1410 static int __init fw_devlink_setup(char *arg)
1415 if (strcmp(arg, "off") == 0) {
1416 fw_devlink_flags = 0;
1417 } else if (strcmp(arg, "permissive") == 0) {
1418 fw_devlink_flags = DL_FLAG_SYNC_STATE_ONLY;
1419 } else if (strcmp(arg, "on") == 0) {
1420 fw_devlink_flags = DL_FLAG_AUTOPROBE_CONSUMER;
1421 } else if (strcmp(arg, "rpm") == 0) {
1422 fw_devlink_flags = DL_FLAG_AUTOPROBE_CONSUMER |
1427 early_param("fw_devlink", fw_devlink_setup);
1429 u32 fw_devlink_get_flags(void)
1431 return fw_devlink_flags;
1434 static bool fw_devlink_is_permissive(void)
1436 return fw_devlink_flags == DL_FLAG_SYNC_STATE_ONLY;
1439 static void fw_devlink_link_device(struct device *dev)
1443 if (!fw_devlink_flags)
1446 mutex_lock(&defer_fw_devlink_lock);
1447 if (!defer_fw_devlink_count)
1448 device_link_add_missing_supplier_links();
1451 * The device's fwnode not having add_links() doesn't affect if other
1452 * consumers can find this device as a supplier. So, this check is
1453 * intentionally placed after device_link_add_missing_supplier_links().
1455 if (!fwnode_has_op(dev->fwnode, add_links))
1459 * If fw_devlink is being deferred, assume all devices have mandatory
1460 * suppliers they need to link to later. Then, when the fw_devlink is
1461 * resumed, all these devices will get a chance to try and link to any
1462 * suppliers they have.
1464 if (!defer_fw_devlink_count) {
1465 fw_ret = fwnode_call_int_op(dev->fwnode, add_links, dev);
1466 if (fw_ret == -ENODEV && fw_devlink_is_permissive())
1472 if (fw_ret == -ENODEV)
1473 device_link_wait_for_mandatory_supplier(dev);
1475 device_link_wait_for_optional_supplier(dev);
1478 mutex_unlock(&defer_fw_devlink_lock);
1482 * fw_devlink_pause - Pause parsing of fwnode to create device links
1484 * Calling this function defers any fwnode parsing to create device links until
1485 * fw_devlink_resume() is called. Both these functions are ref counted and the
1486 * caller needs to match the calls.
1488 * While fw_devlink is paused:
1489 * - Any device that is added won't have its fwnode parsed to create device
1491 * - The probe of the device will also be deferred during this period.
1492 * - Any devices that were already added, but waiting for suppliers won't be
1493 * able to link to newly added devices.
1495 * Once fw_devlink_resume():
1496 * - All the fwnodes that was not parsed will be parsed.
1497 * - All the devices that were deferred probing will be reattempted if they
1498 * aren't waiting for any more suppliers.
1500 * This pair of functions, is mainly meant to optimize the parsing of fwnodes
1501 * when a lot of devices that need to link to each other are added in a short
1502 * interval of time. For example, adding all the top level devices in a system.
1504 * For example, if N devices are added and:
1505 * - All the consumers are added before their suppliers
1506 * - All the suppliers of the N devices are part of the N devices
1510 * - With the use of fw_devlink_pause() and fw_devlink_resume(), each device
1511 * will only need one parsing of its fwnode because it is guaranteed to find
1512 * all the supplier devices already registered and ready to link to. It won't
1513 * have to do another pass later to find one or more suppliers it couldn't
1514 * find in the first parse of the fwnode. So, we'll only need O(N) fwnode
1517 * - Without the use of fw_devlink_pause() and fw_devlink_resume(), we would
1518 * end up doing O(N^2) parses of fwnodes because every device that's added is
1519 * guaranteed to trigger a parse of the fwnode of every device added before
1520 * it. This O(N^2) parse is made worse by the fact that when a fwnode of a
1521 * device is parsed, all it descendant devices might need to have their
1522 * fwnodes parsed too (even if the devices themselves aren't added).
1524 void fw_devlink_pause(void)
1526 mutex_lock(&defer_fw_devlink_lock);
1527 defer_fw_devlink_count++;
1528 mutex_unlock(&defer_fw_devlink_lock);
1531 /** fw_devlink_resume - Resume parsing of fwnode to create device links
1533 * This function is used in conjunction with fw_devlink_pause() and is ref
1534 * counted. See documentation for fw_devlink_pause() for more details.
1536 void fw_devlink_resume(void)
1538 mutex_lock(&defer_fw_devlink_lock);
1539 if (!defer_fw_devlink_count) {
1540 WARN(true, "Unmatched fw_devlink pause/resume!");
1544 defer_fw_devlink_count--;
1545 if (defer_fw_devlink_count)
1548 device_link_add_missing_supplier_links();
1550 mutex_unlock(&defer_fw_devlink_lock);
1552 /* Device links support end. */
1554 int (*platform_notify)(struct device *dev) = NULL;
1555 int (*platform_notify_remove)(struct device *dev) = NULL;
1556 static struct kobject *dev_kobj;
1557 struct kobject *sysfs_dev_char_kobj;
1558 struct kobject *sysfs_dev_block_kobj;
1560 static DEFINE_MUTEX(device_hotplug_lock);
1562 void lock_device_hotplug(void)
1564 mutex_lock(&device_hotplug_lock);
1567 void unlock_device_hotplug(void)
1569 mutex_unlock(&device_hotplug_lock);
1572 int lock_device_hotplug_sysfs(void)
1574 if (mutex_trylock(&device_hotplug_lock))
1577 /* Avoid busy looping (5 ms of sleep should do). */
1579 return restart_syscall();
1583 static inline int device_is_not_partition(struct device *dev)
1585 return !(dev->type == &part_type);
1588 static inline int device_is_not_partition(struct device *dev)
1595 device_platform_notify(struct device *dev, enum kobject_action action)
1599 ret = acpi_platform_notify(dev, action);
1603 ret = software_node_notify(dev, action);
1607 if (platform_notify && action == KOBJ_ADD)
1608 platform_notify(dev);
1609 else if (platform_notify_remove && action == KOBJ_REMOVE)
1610 platform_notify_remove(dev);
1615 * dev_driver_string - Return a device's driver name, if at all possible
1616 * @dev: struct device to get the name of
1618 * Will return the device's driver's name if it is bound to a device. If
1619 * the device is not bound to a driver, it will return the name of the bus
1620 * it is attached to. If it is not attached to a bus either, an empty
1621 * string will be returned.
1623 const char *dev_driver_string(const struct device *dev)
1625 struct device_driver *drv;
1627 /* dev->driver can change to NULL underneath us because of unbinding,
1628 * so be careful about accessing it. dev->bus and dev->class should
1629 * never change once they are set, so they don't need special care.
1631 drv = READ_ONCE(dev->driver);
1632 return drv ? drv->name :
1633 (dev->bus ? dev->bus->name :
1634 (dev->class ? dev->class->name : ""));
1636 EXPORT_SYMBOL(dev_driver_string);
1638 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
1640 static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
1643 struct device_attribute *dev_attr = to_dev_attr(attr);
1644 struct device *dev = kobj_to_dev(kobj);
1648 ret = dev_attr->show(dev, dev_attr, buf);
1649 if (ret >= (ssize_t)PAGE_SIZE) {
1650 printk("dev_attr_show: %pS returned bad count\n",
1656 static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
1657 const char *buf, size_t count)
1659 struct device_attribute *dev_attr = to_dev_attr(attr);
1660 struct device *dev = kobj_to_dev(kobj);
1663 if (dev_attr->store)
1664 ret = dev_attr->store(dev, dev_attr, buf, count);
1668 static const struct sysfs_ops dev_sysfs_ops = {
1669 .show = dev_attr_show,
1670 .store = dev_attr_store,
1673 #define to_ext_attr(x) container_of(x, struct dev_ext_attribute, attr)
1675 ssize_t device_store_ulong(struct device *dev,
1676 struct device_attribute *attr,
1677 const char *buf, size_t size)
1679 struct dev_ext_attribute *ea = to_ext_attr(attr);
1683 ret = kstrtoul(buf, 0, &new);
1686 *(unsigned long *)(ea->var) = new;
1687 /* Always return full write size even if we didn't consume all */
1690 EXPORT_SYMBOL_GPL(device_store_ulong);
1692 ssize_t device_show_ulong(struct device *dev,
1693 struct device_attribute *attr,
1696 struct dev_ext_attribute *ea = to_ext_attr(attr);
1697 return sysfs_emit(buf, "%lx\n", *(unsigned long *)(ea->var));
1699 EXPORT_SYMBOL_GPL(device_show_ulong);
1701 ssize_t device_store_int(struct device *dev,
1702 struct device_attribute *attr,
1703 const char *buf, size_t size)
1705 struct dev_ext_attribute *ea = to_ext_attr(attr);
1709 ret = kstrtol(buf, 0, &new);
1713 if (new > INT_MAX || new < INT_MIN)
1715 *(int *)(ea->var) = new;
1716 /* Always return full write size even if we didn't consume all */
1719 EXPORT_SYMBOL_GPL(device_store_int);
1721 ssize_t device_show_int(struct device *dev,
1722 struct device_attribute *attr,
1725 struct dev_ext_attribute *ea = to_ext_attr(attr);
1727 return sysfs_emit(buf, "%d\n", *(int *)(ea->var));
1729 EXPORT_SYMBOL_GPL(device_show_int);
1731 ssize_t device_store_bool(struct device *dev, struct device_attribute *attr,
1732 const char *buf, size_t size)
1734 struct dev_ext_attribute *ea = to_ext_attr(attr);
1736 if (strtobool(buf, ea->var) < 0)
1741 EXPORT_SYMBOL_GPL(device_store_bool);
1743 ssize_t device_show_bool(struct device *dev, struct device_attribute *attr,
1746 struct dev_ext_attribute *ea = to_ext_attr(attr);
1748 return sysfs_emit(buf, "%d\n", *(bool *)(ea->var));
1750 EXPORT_SYMBOL_GPL(device_show_bool);
1753 * device_release - free device structure.
1754 * @kobj: device's kobject.
1756 * This is called once the reference count for the object
1757 * reaches 0. We forward the call to the device's release
1758 * method, which should handle actually freeing the structure.
1760 static void device_release(struct kobject *kobj)
1762 struct device *dev = kobj_to_dev(kobj);
1763 struct device_private *p = dev->p;
1766 * Some platform devices are driven without driver attached
1767 * and managed resources may have been acquired. Make sure
1768 * all resources are released.
1770 * Drivers still can add resources into device after device
1771 * is deleted but alive, so release devres here to avoid
1772 * possible memory leak.
1774 devres_release_all(dev);
1776 kfree(dev->dma_range_map);
1780 else if (dev->type && dev->type->release)
1781 dev->type->release(dev);
1782 else if (dev->class && dev->class->dev_release)
1783 dev->class->dev_release(dev);
1785 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",
1790 static const void *device_namespace(struct kobject *kobj)
1792 struct device *dev = kobj_to_dev(kobj);
1793 const void *ns = NULL;
1795 if (dev->class && dev->class->ns_type)
1796 ns = dev->class->namespace(dev);
1801 static void device_get_ownership(struct kobject *kobj, kuid_t *uid, kgid_t *gid)
1803 struct device *dev = kobj_to_dev(kobj);
1805 if (dev->class && dev->class->get_ownership)
1806 dev->class->get_ownership(dev, uid, gid);
1809 static struct kobj_type device_ktype = {
1810 .release = device_release,
1811 .sysfs_ops = &dev_sysfs_ops,
1812 .namespace = device_namespace,
1813 .get_ownership = device_get_ownership,
1817 static int dev_uevent_filter(struct kset *kset, struct kobject *kobj)
1819 struct kobj_type *ktype = get_ktype(kobj);
1821 if (ktype == &device_ktype) {
1822 struct device *dev = kobj_to_dev(kobj);
1831 static const char *dev_uevent_name(struct kset *kset, struct kobject *kobj)
1833 struct device *dev = kobj_to_dev(kobj);
1836 return dev->bus->name;
1838 return dev->class->name;
1842 static int dev_uevent(struct kset *kset, struct kobject *kobj,
1843 struct kobj_uevent_env *env)
1845 struct device *dev = kobj_to_dev(kobj);
1848 /* add device node properties if present */
1849 if (MAJOR(dev->devt)) {
1853 kuid_t uid = GLOBAL_ROOT_UID;
1854 kgid_t gid = GLOBAL_ROOT_GID;
1856 add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt));
1857 add_uevent_var(env, "MINOR=%u", MINOR(dev->devt));
1858 name = device_get_devnode(dev, &mode, &uid, &gid, &tmp);
1860 add_uevent_var(env, "DEVNAME=%s", name);
1862 add_uevent_var(env, "DEVMODE=%#o", mode & 0777);
1863 if (!uid_eq(uid, GLOBAL_ROOT_UID))
1864 add_uevent_var(env, "DEVUID=%u", from_kuid(&init_user_ns, uid));
1865 if (!gid_eq(gid, GLOBAL_ROOT_GID))
1866 add_uevent_var(env, "DEVGID=%u", from_kgid(&init_user_ns, gid));
1871 if (dev->type && dev->type->name)
1872 add_uevent_var(env, "DEVTYPE=%s", dev->type->name);
1875 add_uevent_var(env, "DRIVER=%s", dev->driver->name);
1877 /* Add common DT information about the device */
1878 of_device_uevent(dev, env);
1880 /* have the bus specific function add its stuff */
1881 if (dev->bus && dev->bus->uevent) {
1882 retval = dev->bus->uevent(dev, env);
1884 pr_debug("device: '%s': %s: bus uevent() returned %d\n",
1885 dev_name(dev), __func__, retval);
1888 /* have the class specific function add its stuff */
1889 if (dev->class && dev->class->dev_uevent) {
1890 retval = dev->class->dev_uevent(dev, env);
1892 pr_debug("device: '%s': %s: class uevent() "
1893 "returned %d\n", dev_name(dev),
1897 /* have the device type specific function add its stuff */
1898 if (dev->type && dev->type->uevent) {
1899 retval = dev->type->uevent(dev, env);
1901 pr_debug("device: '%s': %s: dev_type uevent() "
1902 "returned %d\n", dev_name(dev),
1909 static const struct kset_uevent_ops device_uevent_ops = {
1910 .filter = dev_uevent_filter,
1911 .name = dev_uevent_name,
1912 .uevent = dev_uevent,
1915 static ssize_t uevent_show(struct device *dev, struct device_attribute *attr,
1918 struct kobject *top_kobj;
1920 struct kobj_uevent_env *env = NULL;
1925 /* search the kset, the device belongs to */
1926 top_kobj = &dev->kobj;
1927 while (!top_kobj->kset && top_kobj->parent)
1928 top_kobj = top_kobj->parent;
1929 if (!top_kobj->kset)
1932 kset = top_kobj->kset;
1933 if (!kset->uevent_ops || !kset->uevent_ops->uevent)
1936 /* respect filter */
1937 if (kset->uevent_ops && kset->uevent_ops->filter)
1938 if (!kset->uevent_ops->filter(kset, &dev->kobj))
1941 env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
1945 /* let the kset specific function add its keys */
1946 retval = kset->uevent_ops->uevent(kset, &dev->kobj, env);
1950 /* copy keys to file */
1951 for (i = 0; i < env->envp_idx; i++)
1952 len += sysfs_emit_at(buf, len, "%s\n", env->envp[i]);
1958 static ssize_t uevent_store(struct device *dev, struct device_attribute *attr,
1959 const char *buf, size_t count)
1963 rc = kobject_synth_uevent(&dev->kobj, buf, count);
1966 dev_err(dev, "uevent: failed to send synthetic uevent\n");
1972 static DEVICE_ATTR_RW(uevent);
1974 static ssize_t online_show(struct device *dev, struct device_attribute *attr,
1980 val = !dev->offline;
1982 return sysfs_emit(buf, "%u\n", val);
1985 static ssize_t online_store(struct device *dev, struct device_attribute *attr,
1986 const char *buf, size_t count)
1991 ret = strtobool(buf, &val);
1995 ret = lock_device_hotplug_sysfs();
1999 ret = val ? device_online(dev) : device_offline(dev);
2000 unlock_device_hotplug();
2001 return ret < 0 ? ret : count;
2003 static DEVICE_ATTR_RW(online);
2005 int device_add_groups(struct device *dev, const struct attribute_group **groups)
2007 return sysfs_create_groups(&dev->kobj, groups);
2009 EXPORT_SYMBOL_GPL(device_add_groups);
2011 void device_remove_groups(struct device *dev,
2012 const struct attribute_group **groups)
2014 sysfs_remove_groups(&dev->kobj, groups);
2016 EXPORT_SYMBOL_GPL(device_remove_groups);
2018 union device_attr_group_devres {
2019 const struct attribute_group *group;
2020 const struct attribute_group **groups;
2023 static int devm_attr_group_match(struct device *dev, void *res, void *data)
2025 return ((union device_attr_group_devres *)res)->group == data;
2028 static void devm_attr_group_remove(struct device *dev, void *res)
2030 union device_attr_group_devres *devres = res;
2031 const struct attribute_group *group = devres->group;
2033 dev_dbg(dev, "%s: removing group %p\n", __func__, group);
2034 sysfs_remove_group(&dev->kobj, group);
2037 static void devm_attr_groups_remove(struct device *dev, void *res)
2039 union device_attr_group_devres *devres = res;
2040 const struct attribute_group **groups = devres->groups;
2042 dev_dbg(dev, "%s: removing groups %p\n", __func__, groups);
2043 sysfs_remove_groups(&dev->kobj, groups);
2047 * devm_device_add_group - given a device, create a managed attribute group
2048 * @dev: The device to create the group for
2049 * @grp: The attribute group to create
2051 * This function creates a group for the first time. It will explicitly
2052 * warn and error if any of the attribute files being created already exist.
2054 * Returns 0 on success or error code on failure.
2056 int devm_device_add_group(struct device *dev, const struct attribute_group *grp)
2058 union device_attr_group_devres *devres;
2061 devres = devres_alloc(devm_attr_group_remove,
2062 sizeof(*devres), GFP_KERNEL);
2066 error = sysfs_create_group(&dev->kobj, grp);
2068 devres_free(devres);
2072 devres->group = grp;
2073 devres_add(dev, devres);
2076 EXPORT_SYMBOL_GPL(devm_device_add_group);
2079 * devm_device_remove_group: remove a managed group from a device
2080 * @dev: device to remove the group from
2081 * @grp: group to remove
2083 * This function removes a group of attributes from a device. The attributes
2084 * previously have to have been created for this group, otherwise it will fail.
2086 void devm_device_remove_group(struct device *dev,
2087 const struct attribute_group *grp)
2089 WARN_ON(devres_release(dev, devm_attr_group_remove,
2090 devm_attr_group_match,
2091 /* cast away const */ (void *)grp));
2093 EXPORT_SYMBOL_GPL(devm_device_remove_group);
2096 * devm_device_add_groups - create a bunch of managed attribute groups
2097 * @dev: The device to create the group for
2098 * @groups: The attribute groups to create, NULL terminated
2100 * This function creates a bunch of managed attribute groups. If an error
2101 * occurs when creating a group, all previously created groups will be
2102 * removed, unwinding everything back to the original state when this
2103 * function was called. It will explicitly warn and error if any of the
2104 * attribute files being created already exist.
2106 * Returns 0 on success or error code from sysfs_create_group on failure.
2108 int devm_device_add_groups(struct device *dev,
2109 const struct attribute_group **groups)
2111 union device_attr_group_devres *devres;
2114 devres = devres_alloc(devm_attr_groups_remove,
2115 sizeof(*devres), GFP_KERNEL);
2119 error = sysfs_create_groups(&dev->kobj, groups);
2121 devres_free(devres);
2125 devres->groups = groups;
2126 devres_add(dev, devres);
2129 EXPORT_SYMBOL_GPL(devm_device_add_groups);
2132 * devm_device_remove_groups - remove a list of managed groups
2134 * @dev: The device for the groups to be removed from
2135 * @groups: NULL terminated list of groups to be removed
2137 * If groups is not NULL, remove the specified groups from the device.
2139 void devm_device_remove_groups(struct device *dev,
2140 const struct attribute_group **groups)
2142 WARN_ON(devres_release(dev, devm_attr_groups_remove,
2143 devm_attr_group_match,
2144 /* cast away const */ (void *)groups));
2146 EXPORT_SYMBOL_GPL(devm_device_remove_groups);
2148 static int device_add_attrs(struct device *dev)
2150 struct class *class = dev->class;
2151 const struct device_type *type = dev->type;
2155 error = device_add_groups(dev, class->dev_groups);
2161 error = device_add_groups(dev, type->groups);
2163 goto err_remove_class_groups;
2166 error = device_add_groups(dev, dev->groups);
2168 goto err_remove_type_groups;
2170 if (device_supports_offline(dev) && !dev->offline_disabled) {
2171 error = device_create_file(dev, &dev_attr_online);
2173 goto err_remove_dev_groups;
2176 if (fw_devlink_flags && !fw_devlink_is_permissive()) {
2177 error = device_create_file(dev, &dev_attr_waiting_for_supplier);
2179 goto err_remove_dev_online;
2184 err_remove_dev_online:
2185 device_remove_file(dev, &dev_attr_online);
2186 err_remove_dev_groups:
2187 device_remove_groups(dev, dev->groups);
2188 err_remove_type_groups:
2190 device_remove_groups(dev, type->groups);
2191 err_remove_class_groups:
2193 device_remove_groups(dev, class->dev_groups);
2198 static void device_remove_attrs(struct device *dev)
2200 struct class *class = dev->class;
2201 const struct device_type *type = dev->type;
2203 device_remove_file(dev, &dev_attr_waiting_for_supplier);
2204 device_remove_file(dev, &dev_attr_online);
2205 device_remove_groups(dev, dev->groups);
2208 device_remove_groups(dev, type->groups);
2211 device_remove_groups(dev, class->dev_groups);
2214 static ssize_t dev_show(struct device *dev, struct device_attribute *attr,
2217 return print_dev_t(buf, dev->devt);
2219 static DEVICE_ATTR_RO(dev);
2222 struct kset *devices_kset;
2225 * devices_kset_move_before - Move device in the devices_kset's list.
2226 * @deva: Device to move.
2227 * @devb: Device @deva should come before.
2229 static void devices_kset_move_before(struct device *deva, struct device *devb)
2233 pr_debug("devices_kset: Moving %s before %s\n",
2234 dev_name(deva), dev_name(devb));
2235 spin_lock(&devices_kset->list_lock);
2236 list_move_tail(&deva->kobj.entry, &devb->kobj.entry);
2237 spin_unlock(&devices_kset->list_lock);
2241 * devices_kset_move_after - Move device in the devices_kset's list.
2242 * @deva: Device to move
2243 * @devb: Device @deva should come after.
2245 static void devices_kset_move_after(struct device *deva, struct device *devb)
2249 pr_debug("devices_kset: Moving %s after %s\n",
2250 dev_name(deva), dev_name(devb));
2251 spin_lock(&devices_kset->list_lock);
2252 list_move(&deva->kobj.entry, &devb->kobj.entry);
2253 spin_unlock(&devices_kset->list_lock);
2257 * devices_kset_move_last - move the device to the end of devices_kset's list.
2258 * @dev: device to move
2260 void devices_kset_move_last(struct device *dev)
2264 pr_debug("devices_kset: Moving %s to end of list\n", dev_name(dev));
2265 spin_lock(&devices_kset->list_lock);
2266 list_move_tail(&dev->kobj.entry, &devices_kset->list);
2267 spin_unlock(&devices_kset->list_lock);
2271 * device_create_file - create sysfs attribute file for device.
2273 * @attr: device attribute descriptor.
2275 int device_create_file(struct device *dev,
2276 const struct device_attribute *attr)
2281 WARN(((attr->attr.mode & S_IWUGO) && !attr->store),
2282 "Attribute %s: write permission without 'store'\n",
2284 WARN(((attr->attr.mode & S_IRUGO) && !attr->show),
2285 "Attribute %s: read permission without 'show'\n",
2287 error = sysfs_create_file(&dev->kobj, &attr->attr);
2292 EXPORT_SYMBOL_GPL(device_create_file);
2295 * device_remove_file - remove sysfs attribute file.
2297 * @attr: device attribute descriptor.
2299 void device_remove_file(struct device *dev,
2300 const struct device_attribute *attr)
2303 sysfs_remove_file(&dev->kobj, &attr->attr);
2305 EXPORT_SYMBOL_GPL(device_remove_file);
2308 * device_remove_file_self - remove sysfs attribute file from its own method.
2310 * @attr: device attribute descriptor.
2312 * See kernfs_remove_self() for details.
2314 bool device_remove_file_self(struct device *dev,
2315 const struct device_attribute *attr)
2318 return sysfs_remove_file_self(&dev->kobj, &attr->attr);
2322 EXPORT_SYMBOL_GPL(device_remove_file_self);
2325 * device_create_bin_file - create sysfs binary attribute file for device.
2327 * @attr: device binary attribute descriptor.
2329 int device_create_bin_file(struct device *dev,
2330 const struct bin_attribute *attr)
2332 int error = -EINVAL;
2334 error = sysfs_create_bin_file(&dev->kobj, attr);
2337 EXPORT_SYMBOL_GPL(device_create_bin_file);
2340 * device_remove_bin_file - remove sysfs binary attribute file
2342 * @attr: device binary attribute descriptor.
2344 void device_remove_bin_file(struct device *dev,
2345 const struct bin_attribute *attr)
2348 sysfs_remove_bin_file(&dev->kobj, attr);
2350 EXPORT_SYMBOL_GPL(device_remove_bin_file);
2352 static void klist_children_get(struct klist_node *n)
2354 struct device_private *p = to_device_private_parent(n);
2355 struct device *dev = p->device;
2360 static void klist_children_put(struct klist_node *n)
2362 struct device_private *p = to_device_private_parent(n);
2363 struct device *dev = p->device;
2369 * device_initialize - init device structure.
2372 * This prepares the device for use by other layers by initializing
2374 * It is the first half of device_register(), if called by
2375 * that function, though it can also be called separately, so one
2376 * may use @dev's fields. In particular, get_device()/put_device()
2377 * may be used for reference counting of @dev after calling this
2380 * All fields in @dev must be initialized by the caller to 0, except
2381 * for those explicitly set to some other value. The simplest
2382 * approach is to use kzalloc() to allocate the structure containing
2385 * NOTE: Use put_device() to give up your reference instead of freeing
2386 * @dev directly once you have called this function.
2388 void device_initialize(struct device *dev)
2390 dev->kobj.kset = devices_kset;
2391 kobject_init(&dev->kobj, &device_ktype);
2392 INIT_LIST_HEAD(&dev->dma_pools);
2393 mutex_init(&dev->mutex);
2394 #ifdef CONFIG_PROVE_LOCKING
2395 mutex_init(&dev->lockdep_mutex);
2397 lockdep_set_novalidate_class(&dev->mutex);
2398 spin_lock_init(&dev->devres_lock);
2399 INIT_LIST_HEAD(&dev->devres_head);
2400 device_pm_init(dev);
2401 set_dev_node(dev, -1);
2402 #ifdef CONFIG_GENERIC_MSI_IRQ
2403 INIT_LIST_HEAD(&dev->msi_list);
2405 INIT_LIST_HEAD(&dev->links.consumers);
2406 INIT_LIST_HEAD(&dev->links.suppliers);
2407 INIT_LIST_HEAD(&dev->links.needs_suppliers);
2408 INIT_LIST_HEAD(&dev->links.defer_hook);
2409 dev->links.status = DL_DEV_NO_DRIVER;
2411 EXPORT_SYMBOL_GPL(device_initialize);
2413 struct kobject *virtual_device_parent(struct device *dev)
2415 static struct kobject *virtual_dir = NULL;
2418 virtual_dir = kobject_create_and_add("virtual",
2419 &devices_kset->kobj);
2425 struct kobject kobj;
2426 struct class *class;
2429 #define to_class_dir(obj) container_of(obj, struct class_dir, kobj)
2431 static void class_dir_release(struct kobject *kobj)
2433 struct class_dir *dir = to_class_dir(kobj);
2438 struct kobj_ns_type_operations *class_dir_child_ns_type(struct kobject *kobj)
2440 struct class_dir *dir = to_class_dir(kobj);
2441 return dir->class->ns_type;
2444 static struct kobj_type class_dir_ktype = {
2445 .release = class_dir_release,
2446 .sysfs_ops = &kobj_sysfs_ops,
2447 .child_ns_type = class_dir_child_ns_type
2450 static struct kobject *
2451 class_dir_create_and_add(struct class *class, struct kobject *parent_kobj)
2453 struct class_dir *dir;
2456 dir = kzalloc(sizeof(*dir), GFP_KERNEL);
2458 return ERR_PTR(-ENOMEM);
2461 kobject_init(&dir->kobj, &class_dir_ktype);
2463 dir->kobj.kset = &class->p->glue_dirs;
2465 retval = kobject_add(&dir->kobj, parent_kobj, "%s", class->name);
2467 kobject_put(&dir->kobj);
2468 return ERR_PTR(retval);
2473 static DEFINE_MUTEX(gdp_mutex);
2475 static struct kobject *get_device_parent(struct device *dev,
2476 struct device *parent)
2479 struct kobject *kobj = NULL;
2480 struct kobject *parent_kobj;
2484 /* block disks show up in /sys/block */
2485 if (sysfs_deprecated && dev->class == &block_class) {
2486 if (parent && parent->class == &block_class)
2487 return &parent->kobj;
2488 return &block_class.p->subsys.kobj;
2493 * If we have no parent, we live in "virtual".
2494 * Class-devices with a non class-device as parent, live
2495 * in a "glue" directory to prevent namespace collisions.
2498 parent_kobj = virtual_device_parent(dev);
2499 else if (parent->class && !dev->class->ns_type)
2500 return &parent->kobj;
2502 parent_kobj = &parent->kobj;
2504 mutex_lock(&gdp_mutex);
2506 /* find our class-directory at the parent and reference it */
2507 spin_lock(&dev->class->p->glue_dirs.list_lock);
2508 list_for_each_entry(k, &dev->class->p->glue_dirs.list, entry)
2509 if (k->parent == parent_kobj) {
2510 kobj = kobject_get(k);
2513 spin_unlock(&dev->class->p->glue_dirs.list_lock);
2515 mutex_unlock(&gdp_mutex);
2519 /* or create a new class-directory at the parent device */
2520 k = class_dir_create_and_add(dev->class, parent_kobj);
2521 /* do not emit an uevent for this simple "glue" directory */
2522 mutex_unlock(&gdp_mutex);
2526 /* subsystems can specify a default root directory for their devices */
2527 if (!parent && dev->bus && dev->bus->dev_root)
2528 return &dev->bus->dev_root->kobj;
2531 return &parent->kobj;
2535 static inline bool live_in_glue_dir(struct kobject *kobj,
2538 if (!kobj || !dev->class ||
2539 kobj->kset != &dev->class->p->glue_dirs)
2544 static inline struct kobject *get_glue_dir(struct device *dev)
2546 return dev->kobj.parent;
2550 * make sure cleaning up dir as the last step, we need to make
2551 * sure .release handler of kobject is run with holding the
2554 static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir)
2558 /* see if we live in a "glue" directory */
2559 if (!live_in_glue_dir(glue_dir, dev))
2562 mutex_lock(&gdp_mutex);
2564 * There is a race condition between removing glue directory
2565 * and adding a new device under the glue directory.
2570 * get_device_parent()
2571 * class_dir_create_and_add()
2572 * kobject_add_internal()
2573 * create_dir() // create glue_dir
2576 * get_device_parent()
2577 * kobject_get() // get glue_dir
2580 * cleanup_glue_dir()
2581 * kobject_del(glue_dir)
2584 * kobject_add_internal()
2585 * create_dir() // in glue_dir
2586 * sysfs_create_dir_ns()
2587 * kernfs_create_dir_ns(sd)
2589 * sysfs_remove_dir() // glue_dir->sd=NULL
2590 * sysfs_put() // free glue_dir->sd
2593 * kernfs_new_node(sd)
2594 * kernfs_get(glue_dir)
2598 * Before CPU1 remove last child device under glue dir, if CPU2 add
2599 * a new device under glue dir, the glue_dir kobject reference count
2600 * will be increase to 2 in kobject_get(k). And CPU2 has been called
2601 * kernfs_create_dir_ns(). Meanwhile, CPU1 call sysfs_remove_dir()
2602 * and sysfs_put(). This result in glue_dir->sd is freed.
2604 * Then the CPU2 will see a stale "empty" but still potentially used
2605 * glue dir around in kernfs_new_node().
2607 * In order to avoid this happening, we also should make sure that
2608 * kernfs_node for glue_dir is released in CPU1 only when refcount
2609 * for glue_dir kobj is 1.
2611 ref = kref_read(&glue_dir->kref);
2612 if (!kobject_has_children(glue_dir) && !--ref)
2613 kobject_del(glue_dir);
2614 kobject_put(glue_dir);
2615 mutex_unlock(&gdp_mutex);
2618 static int device_add_class_symlinks(struct device *dev)
2620 struct device_node *of_node = dev_of_node(dev);
2624 error = sysfs_create_link(&dev->kobj, of_node_kobj(of_node), "of_node");
2626 dev_warn(dev, "Error %d creating of_node link\n",error);
2627 /* An error here doesn't warrant bringing down the device */
2633 error = sysfs_create_link(&dev->kobj,
2634 &dev->class->p->subsys.kobj,
2639 if (dev->parent && device_is_not_partition(dev)) {
2640 error = sysfs_create_link(&dev->kobj, &dev->parent->kobj,
2647 /* /sys/block has directories and does not need symlinks */
2648 if (sysfs_deprecated && dev->class == &block_class)
2652 /* link in the class directory pointing to the device */
2653 error = sysfs_create_link(&dev->class->p->subsys.kobj,
2654 &dev->kobj, dev_name(dev));
2661 sysfs_remove_link(&dev->kobj, "device");
2664 sysfs_remove_link(&dev->kobj, "subsystem");
2666 sysfs_remove_link(&dev->kobj, "of_node");
2670 static void device_remove_class_symlinks(struct device *dev)
2672 if (dev_of_node(dev))
2673 sysfs_remove_link(&dev->kobj, "of_node");
2678 if (dev->parent && device_is_not_partition(dev))
2679 sysfs_remove_link(&dev->kobj, "device");
2680 sysfs_remove_link(&dev->kobj, "subsystem");
2682 if (sysfs_deprecated && dev->class == &block_class)
2685 sysfs_delete_link(&dev->class->p->subsys.kobj, &dev->kobj, dev_name(dev));
2689 * dev_set_name - set a device name
2691 * @fmt: format string for the device's name
2693 int dev_set_name(struct device *dev, const char *fmt, ...)
2698 va_start(vargs, fmt);
2699 err = kobject_set_name_vargs(&dev->kobj, fmt, vargs);
2703 EXPORT_SYMBOL_GPL(dev_set_name);
2706 * device_to_dev_kobj - select a /sys/dev/ directory for the device
2709 * By default we select char/ for new entries. Setting class->dev_obj
2710 * to NULL prevents an entry from being created. class->dev_kobj must
2711 * be set (or cleared) before any devices are registered to the class
2712 * otherwise device_create_sys_dev_entry() and
2713 * device_remove_sys_dev_entry() will disagree about the presence of
2716 static struct kobject *device_to_dev_kobj(struct device *dev)
2718 struct kobject *kobj;
2721 kobj = dev->class->dev_kobj;
2723 kobj = sysfs_dev_char_kobj;
2728 static int device_create_sys_dev_entry(struct device *dev)
2730 struct kobject *kobj = device_to_dev_kobj(dev);
2735 format_dev_t(devt_str, dev->devt);
2736 error = sysfs_create_link(kobj, &dev->kobj, devt_str);
2742 static void device_remove_sys_dev_entry(struct device *dev)
2744 struct kobject *kobj = device_to_dev_kobj(dev);
2748 format_dev_t(devt_str, dev->devt);
2749 sysfs_remove_link(kobj, devt_str);
2753 static int device_private_init(struct device *dev)
2755 dev->p = kzalloc(sizeof(*dev->p), GFP_KERNEL);
2758 dev->p->device = dev;
2759 klist_init(&dev->p->klist_children, klist_children_get,
2760 klist_children_put);
2761 INIT_LIST_HEAD(&dev->p->deferred_probe);
2766 * device_add - add device to device hierarchy.
2769 * This is part 2 of device_register(), though may be called
2770 * separately _iff_ device_initialize() has been called separately.
2772 * This adds @dev to the kobject hierarchy via kobject_add(), adds it
2773 * to the global and sibling lists for the device, then
2774 * adds it to the other relevant subsystems of the driver model.
2776 * Do not call this routine or device_register() more than once for
2777 * any device structure. The driver model core is not designed to work
2778 * with devices that get unregistered and then spring back to life.
2779 * (Among other things, it's very hard to guarantee that all references
2780 * to the previous incarnation of @dev have been dropped.) Allocate
2781 * and register a fresh new struct device instead.
2783 * NOTE: _Never_ directly free @dev after calling this function, even
2784 * if it returned an error! Always use put_device() to give up your
2785 * reference instead.
2787 * Rule of thumb is: if device_add() succeeds, you should call
2788 * device_del() when you want to get rid of it. If device_add() has
2789 * *not* succeeded, use *only* put_device() to drop the reference
2792 int device_add(struct device *dev)
2794 struct device *parent;
2795 struct kobject *kobj;
2796 struct class_interface *class_intf;
2797 int error = -EINVAL;
2798 struct kobject *glue_dir = NULL;
2800 dev = get_device(dev);
2805 error = device_private_init(dev);
2811 * for statically allocated devices, which should all be converted
2812 * some day, we need to initialize the name. We prevent reading back
2813 * the name, and force the use of dev_name()
2815 if (dev->init_name) {
2816 dev_set_name(dev, "%s", dev->init_name);
2817 dev->init_name = NULL;
2820 /* subsystems can specify simple device enumeration */
2821 if (!dev_name(dev) && dev->bus && dev->bus->dev_name)
2822 dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
2824 if (!dev_name(dev)) {
2829 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
2831 parent = get_device(dev->parent);
2832 kobj = get_device_parent(dev, parent);
2834 error = PTR_ERR(kobj);
2838 dev->kobj.parent = kobj;
2840 /* use parent numa_node */
2841 if (parent && (dev_to_node(dev) == NUMA_NO_NODE))
2842 set_dev_node(dev, dev_to_node(parent));
2844 /* first, register with generic layer. */
2845 /* we require the name to be set before, and pass NULL */
2846 error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
2848 glue_dir = get_glue_dir(dev);
2852 /* notify platform of device entry */
2853 error = device_platform_notify(dev, KOBJ_ADD);
2855 goto platform_error;
2857 error = device_create_file(dev, &dev_attr_uevent);
2861 error = device_add_class_symlinks(dev);
2864 error = device_add_attrs(dev);
2867 error = bus_add_device(dev);
2870 error = dpm_sysfs_add(dev);
2875 if (MAJOR(dev->devt)) {
2876 error = device_create_file(dev, &dev_attr_dev);
2880 error = device_create_sys_dev_entry(dev);
2884 devtmpfs_create_node(dev);
2887 /* Notify clients of device addition. This call must come
2888 * after dpm_sysfs_add() and before kobject_uevent().
2891 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
2892 BUS_NOTIFY_ADD_DEVICE, dev);
2894 kobject_uevent(&dev->kobj, KOBJ_ADD);
2897 * Check if any of the other devices (consumers) have been waiting for
2898 * this device (supplier) to be added so that they can create a device
2901 * This needs to happen after device_pm_add() because device_link_add()
2902 * requires the supplier be registered before it's called.
2904 * But this also needs to happen before bus_probe_device() to make sure
2905 * waiting consumers can link to it before the driver is bound to the
2906 * device and the driver sync_state callback is called for this device.
2908 if (dev->fwnode && !dev->fwnode->dev) {
2909 dev->fwnode->dev = dev;
2910 fw_devlink_link_device(dev);
2913 bus_probe_device(dev);
2915 klist_add_tail(&dev->p->knode_parent,
2916 &parent->p->klist_children);
2919 mutex_lock(&dev->class->p->mutex);
2920 /* tie the class to the device */
2921 klist_add_tail(&dev->p->knode_class,
2922 &dev->class->p->klist_devices);
2924 /* notify any interfaces that the device is here */
2925 list_for_each_entry(class_intf,
2926 &dev->class->p->interfaces, node)
2927 if (class_intf->add_dev)
2928 class_intf->add_dev(dev, class_intf);
2929 mutex_unlock(&dev->class->p->mutex);
2935 if (MAJOR(dev->devt))
2936 device_remove_file(dev, &dev_attr_dev);
2938 device_pm_remove(dev);
2939 dpm_sysfs_remove(dev);
2941 bus_remove_device(dev);
2943 device_remove_attrs(dev);
2945 device_remove_class_symlinks(dev);
2947 device_remove_file(dev, &dev_attr_uevent);
2949 device_platform_notify(dev, KOBJ_REMOVE);
2951 kobject_uevent(&dev->kobj, KOBJ_REMOVE);
2952 glue_dir = get_glue_dir(dev);
2953 kobject_del(&dev->kobj);
2955 cleanup_glue_dir(dev, glue_dir);
2963 EXPORT_SYMBOL_GPL(device_add);
2966 * device_register - register a device with the system.
2967 * @dev: pointer to the device structure
2969 * This happens in two clean steps - initialize the device
2970 * and add it to the system. The two steps can be called
2971 * separately, but this is the easiest and most common.
2972 * I.e. you should only call the two helpers separately if
2973 * have a clearly defined need to use and refcount the device
2974 * before it is added to the hierarchy.
2976 * For more information, see the kerneldoc for device_initialize()
2979 * NOTE: _Never_ directly free @dev after calling this function, even
2980 * if it returned an error! Always use put_device() to give up the
2981 * reference initialized in this function instead.
2983 int device_register(struct device *dev)
2985 device_initialize(dev);
2986 return device_add(dev);
2988 EXPORT_SYMBOL_GPL(device_register);
2991 * get_device - increment reference count for device.
2994 * This simply forwards the call to kobject_get(), though
2995 * we do take care to provide for the case that we get a NULL
2996 * pointer passed in.
2998 struct device *get_device(struct device *dev)
3000 return dev ? kobj_to_dev(kobject_get(&dev->kobj)) : NULL;
3002 EXPORT_SYMBOL_GPL(get_device);
3005 * put_device - decrement reference count.
3006 * @dev: device in question.
3008 void put_device(struct device *dev)
3010 /* might_sleep(); */
3012 kobject_put(&dev->kobj);
3014 EXPORT_SYMBOL_GPL(put_device);
3016 bool kill_device(struct device *dev)
3019 * Require the device lock and set the "dead" flag to guarantee that
3020 * the update behavior is consistent with the other bitfields near
3021 * it and that we cannot have an asynchronous probe routine trying
3022 * to run while we are tearing out the bus/class/sysfs from
3023 * underneath the device.
3025 lockdep_assert_held(&dev->mutex);
3029 dev->p->dead = true;
3032 EXPORT_SYMBOL_GPL(kill_device);
3035 * device_del - delete device from system.
3038 * This is the first part of the device unregistration
3039 * sequence. This removes the device from the lists we control
3040 * from here, has it removed from the other driver model
3041 * subsystems it was added to in device_add(), and removes it
3042 * from the kobject hierarchy.
3044 * NOTE: this should be called manually _iff_ device_add() was
3045 * also called manually.
3047 void device_del(struct device *dev)
3049 struct device *parent = dev->parent;
3050 struct kobject *glue_dir = NULL;
3051 struct class_interface *class_intf;
3052 unsigned int noio_flag;
3058 if (dev->fwnode && dev->fwnode->dev == dev)
3059 dev->fwnode->dev = NULL;
3061 /* Notify clients of device removal. This call must come
3062 * before dpm_sysfs_remove().
3064 noio_flag = memalloc_noio_save();
3066 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
3067 BUS_NOTIFY_DEL_DEVICE, dev);
3069 dpm_sysfs_remove(dev);
3071 klist_del(&dev->p->knode_parent);
3072 if (MAJOR(dev->devt)) {
3073 devtmpfs_delete_node(dev);
3074 device_remove_sys_dev_entry(dev);
3075 device_remove_file(dev, &dev_attr_dev);
3078 device_remove_class_symlinks(dev);
3080 mutex_lock(&dev->class->p->mutex);
3081 /* notify any interfaces that the device is now gone */
3082 list_for_each_entry(class_intf,
3083 &dev->class->p->interfaces, node)
3084 if (class_intf->remove_dev)
3085 class_intf->remove_dev(dev, class_intf);
3086 /* remove the device from the class list */
3087 klist_del(&dev->p->knode_class);
3088 mutex_unlock(&dev->class->p->mutex);
3090 device_remove_file(dev, &dev_attr_uevent);
3091 device_remove_attrs(dev);
3092 bus_remove_device(dev);
3093 device_pm_remove(dev);
3094 driver_deferred_probe_del(dev);
3095 device_platform_notify(dev, KOBJ_REMOVE);
3096 device_remove_properties(dev);
3097 device_links_purge(dev);
3100 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
3101 BUS_NOTIFY_REMOVED_DEVICE, dev);
3102 kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3103 glue_dir = get_glue_dir(dev);
3104 kobject_del(&dev->kobj);
3105 cleanup_glue_dir(dev, glue_dir);
3106 memalloc_noio_restore(noio_flag);
3109 EXPORT_SYMBOL_GPL(device_del);
3112 * device_unregister - unregister device from system.
3113 * @dev: device going away.
3115 * We do this in two parts, like we do device_register(). First,
3116 * we remove it from all the subsystems with device_del(), then
3117 * we decrement the reference count via put_device(). If that
3118 * is the final reference count, the device will be cleaned up
3119 * via device_release() above. Otherwise, the structure will
3120 * stick around until the final reference to the device is dropped.
3122 void device_unregister(struct device *dev)
3124 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3128 EXPORT_SYMBOL_GPL(device_unregister);
3130 static struct device *prev_device(struct klist_iter *i)
3132 struct klist_node *n = klist_prev(i);
3133 struct device *dev = NULL;
3134 struct device_private *p;
3137 p = to_device_private_parent(n);
3143 static struct device *next_device(struct klist_iter *i)
3145 struct klist_node *n = klist_next(i);
3146 struct device *dev = NULL;
3147 struct device_private *p;
3150 p = to_device_private_parent(n);
3157 * device_get_devnode - path of device node file
3159 * @mode: returned file access mode
3160 * @uid: returned file owner
3161 * @gid: returned file group
3162 * @tmp: possibly allocated string
3164 * Return the relative path of a possible device node.
3165 * Non-default names may need to allocate a memory to compose
3166 * a name. This memory is returned in tmp and needs to be
3167 * freed by the caller.
3169 const char *device_get_devnode(struct device *dev,
3170 umode_t *mode, kuid_t *uid, kgid_t *gid,
3177 /* the device type may provide a specific name */
3178 if (dev->type && dev->type->devnode)
3179 *tmp = dev->type->devnode(dev, mode, uid, gid);
3183 /* the class may provide a specific name */
3184 if (dev->class && dev->class->devnode)
3185 *tmp = dev->class->devnode(dev, mode);
3189 /* return name without allocation, tmp == NULL */
3190 if (strchr(dev_name(dev), '!') == NULL)
3191 return dev_name(dev);
3193 /* replace '!' in the name with '/' */
3194 s = kstrdup(dev_name(dev), GFP_KERNEL);
3197 strreplace(s, '!', '/');
3202 * device_for_each_child - device child iterator.
3203 * @parent: parent struct device.
3204 * @fn: function to be called for each device.
3205 * @data: data for the callback.
3207 * Iterate over @parent's child devices, and call @fn for each,
3210 * We check the return of @fn each time. If it returns anything
3211 * other than 0, we break out and return that value.
3213 int device_for_each_child(struct device *parent, void *data,
3214 int (*fn)(struct device *dev, void *data))
3216 struct klist_iter i;
3217 struct device *child;
3223 klist_iter_init(&parent->p->klist_children, &i);
3224 while (!error && (child = next_device(&i)))
3225 error = fn(child, data);
3226 klist_iter_exit(&i);
3229 EXPORT_SYMBOL_GPL(device_for_each_child);
3232 * device_for_each_child_reverse - device child iterator in reversed order.
3233 * @parent: parent struct device.
3234 * @fn: function to be called for each device.
3235 * @data: data for the callback.
3237 * Iterate over @parent's child devices, and call @fn for each,
3240 * We check the return of @fn each time. If it returns anything
3241 * other than 0, we break out and return that value.
3243 int device_for_each_child_reverse(struct device *parent, void *data,
3244 int (*fn)(struct device *dev, void *data))
3246 struct klist_iter i;
3247 struct device *child;
3253 klist_iter_init(&parent->p->klist_children, &i);
3254 while ((child = prev_device(&i)) && !error)
3255 error = fn(child, data);
3256 klist_iter_exit(&i);
3259 EXPORT_SYMBOL_GPL(device_for_each_child_reverse);
3262 * device_find_child - device iterator for locating a particular device.
3263 * @parent: parent struct device
3264 * @match: Callback function to check device
3265 * @data: Data to pass to match function
3267 * This is similar to the device_for_each_child() function above, but it
3268 * returns a reference to a device that is 'found' for later use, as
3269 * determined by the @match callback.
3271 * The callback should return 0 if the device doesn't match and non-zero
3272 * if it does. If the callback returns non-zero and a reference to the
3273 * current device can be obtained, this function will return to the caller
3274 * and not iterate over any more devices.
3276 * NOTE: you will need to drop the reference with put_device() after use.
3278 struct device *device_find_child(struct device *parent, void *data,
3279 int (*match)(struct device *dev, void *data))
3281 struct klist_iter i;
3282 struct device *child;
3287 klist_iter_init(&parent->p->klist_children, &i);
3288 while ((child = next_device(&i)))
3289 if (match(child, data) && get_device(child))
3291 klist_iter_exit(&i);
3294 EXPORT_SYMBOL_GPL(device_find_child);
3297 * device_find_child_by_name - device iterator for locating a child device.
3298 * @parent: parent struct device
3299 * @name: name of the child device
3301 * This is similar to the device_find_child() function above, but it
3302 * returns a reference to a device that has the name @name.
3304 * NOTE: you will need to drop the reference with put_device() after use.
3306 struct device *device_find_child_by_name(struct device *parent,
3309 struct klist_iter i;
3310 struct device *child;
3315 klist_iter_init(&parent->p->klist_children, &i);
3316 while ((child = next_device(&i)))
3317 if (sysfs_streq(dev_name(child), name) && get_device(child))
3319 klist_iter_exit(&i);
3322 EXPORT_SYMBOL_GPL(device_find_child_by_name);
3324 int __init devices_init(void)
3326 devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
3329 dev_kobj = kobject_create_and_add("dev", NULL);
3332 sysfs_dev_block_kobj = kobject_create_and_add("block", dev_kobj);
3333 if (!sysfs_dev_block_kobj)
3334 goto block_kobj_err;
3335 sysfs_dev_char_kobj = kobject_create_and_add("char", dev_kobj);
3336 if (!sysfs_dev_char_kobj)
3342 kobject_put(sysfs_dev_block_kobj);
3344 kobject_put(dev_kobj);
3346 kset_unregister(devices_kset);
3350 static int device_check_offline(struct device *dev, void *not_used)
3354 ret = device_for_each_child(dev, NULL, device_check_offline);
3358 return device_supports_offline(dev) && !dev->offline ? -EBUSY : 0;
3362 * device_offline - Prepare the device for hot-removal.
3363 * @dev: Device to be put offline.
3365 * Execute the device bus type's .offline() callback, if present, to prepare
3366 * the device for a subsequent hot-removal. If that succeeds, the device must
3367 * not be used until either it is removed or its bus type's .online() callback
3370 * Call under device_hotplug_lock.
3372 int device_offline(struct device *dev)
3376 if (dev->offline_disabled)
3379 ret = device_for_each_child(dev, NULL, device_check_offline);
3384 if (device_supports_offline(dev)) {
3388 ret = dev->bus->offline(dev);
3390 kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
3391 dev->offline = true;
3401 * device_online - Put the device back online after successful device_offline().
3402 * @dev: Device to be put back online.
3404 * If device_offline() has been successfully executed for @dev, but the device
3405 * has not been removed subsequently, execute its bus type's .online() callback
3406 * to indicate that the device can be used again.
3408 * Call under device_hotplug_lock.
3410 int device_online(struct device *dev)
3415 if (device_supports_offline(dev)) {
3417 ret = dev->bus->online(dev);
3419 kobject_uevent(&dev->kobj, KOBJ_ONLINE);
3420 dev->offline = false;
3431 struct root_device {
3433 struct module *owner;
3436 static inline struct root_device *to_root_device(struct device *d)
3438 return container_of(d, struct root_device, dev);
3441 static void root_device_release(struct device *dev)
3443 kfree(to_root_device(dev));
3447 * __root_device_register - allocate and register a root device
3448 * @name: root device name
3449 * @owner: owner module of the root device, usually THIS_MODULE
3451 * This function allocates a root device and registers it
3452 * using device_register(). In order to free the returned
3453 * device, use root_device_unregister().
3455 * Root devices are dummy devices which allow other devices
3456 * to be grouped under /sys/devices. Use this function to
3457 * allocate a root device and then use it as the parent of
3458 * any device which should appear under /sys/devices/{name}
3460 * The /sys/devices/{name} directory will also contain a
3461 * 'module' symlink which points to the @owner directory
3464 * Returns &struct device pointer on success, or ERR_PTR() on error.
3466 * Note: You probably want to use root_device_register().
3468 struct device *__root_device_register(const char *name, struct module *owner)
3470 struct root_device *root;
3473 root = kzalloc(sizeof(struct root_device), GFP_KERNEL);
3475 return ERR_PTR(err);
3477 err = dev_set_name(&root->dev, "%s", name);
3480 return ERR_PTR(err);
3483 root->dev.release = root_device_release;
3485 err = device_register(&root->dev);
3487 put_device(&root->dev);
3488 return ERR_PTR(err);
3491 #ifdef CONFIG_MODULES /* gotta find a "cleaner" way to do this */
3493 struct module_kobject *mk = &owner->mkobj;
3495 err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module");
3497 device_unregister(&root->dev);
3498 return ERR_PTR(err);
3500 root->owner = owner;
3506 EXPORT_SYMBOL_GPL(__root_device_register);
3509 * root_device_unregister - unregister and free a root device
3510 * @dev: device going away
3512 * This function unregisters and cleans up a device that was created by
3513 * root_device_register().
3515 void root_device_unregister(struct device *dev)
3517 struct root_device *root = to_root_device(dev);
3520 sysfs_remove_link(&root->dev.kobj, "module");
3522 device_unregister(dev);
3524 EXPORT_SYMBOL_GPL(root_device_unregister);
3527 static void device_create_release(struct device *dev)
3529 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3533 static __printf(6, 0) struct device *
3534 device_create_groups_vargs(struct class *class, struct device *parent,
3535 dev_t devt, void *drvdata,
3536 const struct attribute_group **groups,
3537 const char *fmt, va_list args)
3539 struct device *dev = NULL;
3540 int retval = -ENODEV;
3542 if (class == NULL || IS_ERR(class))
3545 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3551 device_initialize(dev);
3554 dev->parent = parent;
3555 dev->groups = groups;
3556 dev->release = device_create_release;
3557 dev_set_drvdata(dev, drvdata);
3559 retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
3563 retval = device_add(dev);
3571 return ERR_PTR(retval);
3575 * device_create - creates a device and registers it with sysfs
3576 * @class: pointer to the struct class that this device should be registered to
3577 * @parent: pointer to the parent struct device of this new device, if any
3578 * @devt: the dev_t for the char device to be added
3579 * @drvdata: the data to be added to the device for callbacks
3580 * @fmt: string for the device's name
3582 * This function can be used by char device classes. A struct device
3583 * will be created in sysfs, registered to the specified class.
3585 * A "dev" file will be created, showing the dev_t for the device, if
3586 * the dev_t is not 0,0.
3587 * If a pointer to a parent struct device is passed in, the newly created
3588 * struct device will be a child of that device in sysfs.
3589 * The pointer to the struct device will be returned from the call.
3590 * Any further sysfs files that might be required can be created using this
3593 * Returns &struct device pointer on success, or ERR_PTR() on error.
3595 * Note: the struct class passed to this function must have previously
3596 * been created with a call to class_create().
3598 struct device *device_create(struct class *class, struct device *parent,
3599 dev_t devt, void *drvdata, const char *fmt, ...)
3604 va_start(vargs, fmt);
3605 dev = device_create_groups_vargs(class, parent, devt, drvdata, NULL,
3610 EXPORT_SYMBOL_GPL(device_create);
3613 * device_create_with_groups - creates a device and registers it with sysfs
3614 * @class: pointer to the struct class that this device should be registered to
3615 * @parent: pointer to the parent struct device of this new device, if any
3616 * @devt: the dev_t for the char device to be added
3617 * @drvdata: the data to be added to the device for callbacks
3618 * @groups: NULL-terminated list of attribute groups to be created
3619 * @fmt: string for the device's name
3621 * This function can be used by char device classes. A struct device
3622 * will be created in sysfs, registered to the specified class.
3623 * Additional attributes specified in the groups parameter will also
3624 * be created automatically.
3626 * A "dev" file will be created, showing the dev_t for the device, if
3627 * the dev_t is not 0,0.
3628 * If a pointer to a parent struct device is passed in, the newly created
3629 * struct device will be a child of that device in sysfs.
3630 * The pointer to the struct device will be returned from the call.
3631 * Any further sysfs files that might be required can be created using this
3634 * Returns &struct device pointer on success, or ERR_PTR() on error.
3636 * Note: the struct class passed to this function must have previously
3637 * been created with a call to class_create().
3639 struct device *device_create_with_groups(struct class *class,
3640 struct device *parent, dev_t devt,
3642 const struct attribute_group **groups,
3643 const char *fmt, ...)
3648 va_start(vargs, fmt);
3649 dev = device_create_groups_vargs(class, parent, devt, drvdata, groups,
3654 EXPORT_SYMBOL_GPL(device_create_with_groups);
3657 * device_destroy - removes a device that was created with device_create()
3658 * @class: pointer to the struct class that this device was registered with
3659 * @devt: the dev_t of the device that was previously registered
3661 * This call unregisters and cleans up a device that was created with a
3662 * call to device_create().
3664 void device_destroy(struct class *class, dev_t devt)
3668 dev = class_find_device_by_devt(class, devt);
3671 device_unregister(dev);
3674 EXPORT_SYMBOL_GPL(device_destroy);
3677 * device_rename - renames a device
3678 * @dev: the pointer to the struct device to be renamed
3679 * @new_name: the new name of the device
3681 * It is the responsibility of the caller to provide mutual
3682 * exclusion between two different calls of device_rename
3683 * on the same device to ensure that new_name is valid and
3684 * won't conflict with other devices.
3686 * Note: Don't call this function. Currently, the networking layer calls this
3687 * function, but that will change. The following text from Kay Sievers offers
3690 * Renaming devices is racy at many levels, symlinks and other stuff are not
3691 * replaced atomically, and you get a "move" uevent, but it's not easy to
3692 * connect the event to the old and new device. Device nodes are not renamed at
3693 * all, there isn't even support for that in the kernel now.
3695 * In the meantime, during renaming, your target name might be taken by another
3696 * driver, creating conflicts. Or the old name is taken directly after you
3697 * renamed it -- then you get events for the same DEVPATH, before you even see
3698 * the "move" event. It's just a mess, and nothing new should ever rely on
3699 * kernel device renaming. Besides that, it's not even implemented now for
3700 * other things than (driver-core wise very simple) network devices.
3702 * We are currently about to change network renaming in udev to completely
3703 * disallow renaming of devices in the same namespace as the kernel uses,
3704 * because we can't solve the problems properly, that arise with swapping names
3705 * of multiple interfaces without races. Means, renaming of eth[0-9]* will only
3706 * be allowed to some other name than eth[0-9]*, for the aforementioned
3709 * Make up a "real" name in the driver before you register anything, or add
3710 * some other attributes for userspace to find the device, or use udev to add
3711 * symlinks -- but never rename kernel devices later, it's a complete mess. We
3712 * don't even want to get into that and try to implement the missing pieces in
3713 * the core. We really have other pieces to fix in the driver core mess. :)
3715 int device_rename(struct device *dev, const char *new_name)
3717 struct kobject *kobj = &dev->kobj;
3718 char *old_device_name = NULL;
3721 dev = get_device(dev);
3725 dev_dbg(dev, "renaming to %s\n", new_name);
3727 old_device_name = kstrdup(dev_name(dev), GFP_KERNEL);
3728 if (!old_device_name) {
3734 error = sysfs_rename_link_ns(&dev->class->p->subsys.kobj,
3735 kobj, old_device_name,
3736 new_name, kobject_namespace(kobj));
3741 error = kobject_rename(kobj, new_name);
3748 kfree(old_device_name);
3752 EXPORT_SYMBOL_GPL(device_rename);
3754 static int device_move_class_links(struct device *dev,
3755 struct device *old_parent,
3756 struct device *new_parent)
3761 sysfs_remove_link(&dev->kobj, "device");
3763 error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
3769 * device_move - moves a device to a new parent
3770 * @dev: the pointer to the struct device to be moved
3771 * @new_parent: the new parent of the device (can be NULL)
3772 * @dpm_order: how to reorder the dpm_list
3774 int device_move(struct device *dev, struct device *new_parent,
3775 enum dpm_order dpm_order)
3778 struct device *old_parent;
3779 struct kobject *new_parent_kobj;
3781 dev = get_device(dev);
3786 new_parent = get_device(new_parent);
3787 new_parent_kobj = get_device_parent(dev, new_parent);
3788 if (IS_ERR(new_parent_kobj)) {
3789 error = PTR_ERR(new_parent_kobj);
3790 put_device(new_parent);
3794 pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev),
3795 __func__, new_parent ? dev_name(new_parent) : "<NULL>");
3796 error = kobject_move(&dev->kobj, new_parent_kobj);
3798 cleanup_glue_dir(dev, new_parent_kobj);
3799 put_device(new_parent);
3802 old_parent = dev->parent;
3803 dev->parent = new_parent;
3805 klist_remove(&dev->p->knode_parent);
3807 klist_add_tail(&dev->p->knode_parent,
3808 &new_parent->p->klist_children);
3809 set_dev_node(dev, dev_to_node(new_parent));
3813 error = device_move_class_links(dev, old_parent, new_parent);
3815 /* We ignore errors on cleanup since we're hosed anyway... */
3816 device_move_class_links(dev, new_parent, old_parent);
3817 if (!kobject_move(&dev->kobj, &old_parent->kobj)) {
3819 klist_remove(&dev->p->knode_parent);
3820 dev->parent = old_parent;
3822 klist_add_tail(&dev->p->knode_parent,
3823 &old_parent->p->klist_children);
3824 set_dev_node(dev, dev_to_node(old_parent));
3827 cleanup_glue_dir(dev, new_parent_kobj);
3828 put_device(new_parent);
3832 switch (dpm_order) {
3833 case DPM_ORDER_NONE:
3835 case DPM_ORDER_DEV_AFTER_PARENT:
3836 device_pm_move_after(dev, new_parent);
3837 devices_kset_move_after(dev, new_parent);
3839 case DPM_ORDER_PARENT_BEFORE_DEV:
3840 device_pm_move_before(new_parent, dev);
3841 devices_kset_move_before(new_parent, dev);
3843 case DPM_ORDER_DEV_LAST:
3844 device_pm_move_last(dev);
3845 devices_kset_move_last(dev);
3849 put_device(old_parent);
3855 EXPORT_SYMBOL_GPL(device_move);
3857 static int device_attrs_change_owner(struct device *dev, kuid_t kuid,
3860 struct kobject *kobj = &dev->kobj;
3861 struct class *class = dev->class;
3862 const struct device_type *type = dev->type;
3867 * Change the device groups of the device class for @dev to
3870 error = sysfs_groups_change_owner(kobj, class->dev_groups, kuid,
3878 * Change the device groups of the device type for @dev to
3881 error = sysfs_groups_change_owner(kobj, type->groups, kuid,
3887 /* Change the device groups of @dev to @kuid/@kgid. */
3888 error = sysfs_groups_change_owner(kobj, dev->groups, kuid, kgid);
3892 if (device_supports_offline(dev) && !dev->offline_disabled) {
3893 /* Change online device attributes of @dev to @kuid/@kgid. */
3894 error = sysfs_file_change_owner(kobj, dev_attr_online.attr.name,
3904 * device_change_owner - change the owner of an existing device.
3906 * @kuid: new owner's kuid
3907 * @kgid: new owner's kgid
3909 * This changes the owner of @dev and its corresponding sysfs entries to
3910 * @kuid/@kgid. This function closely mirrors how @dev was added via driver
3913 * Returns 0 on success or error code on failure.
3915 int device_change_owner(struct device *dev, kuid_t kuid, kgid_t kgid)
3918 struct kobject *kobj = &dev->kobj;
3920 dev = get_device(dev);
3925 * Change the kobject and the default attributes and groups of the
3926 * ktype associated with it to @kuid/@kgid.
3928 error = sysfs_change_owner(kobj, kuid, kgid);
3933 * Change the uevent file for @dev to the new owner. The uevent file
3934 * was created in a separate step when @dev got added and we mirror
3937 error = sysfs_file_change_owner(kobj, dev_attr_uevent.attr.name, kuid,
3943 * Change the device groups, the device groups associated with the
3944 * device class, and the groups associated with the device type of @dev
3947 error = device_attrs_change_owner(dev, kuid, kgid);
3951 error = dpm_sysfs_change_owner(dev, kuid, kgid);
3956 if (sysfs_deprecated && dev->class == &block_class)
3961 * Change the owner of the symlink located in the class directory of
3962 * the device class associated with @dev which points to the actual
3963 * directory entry for @dev to @kuid/@kgid. This ensures that the
3964 * symlink shows the same permissions as its target.
3966 error = sysfs_link_change_owner(&dev->class->p->subsys.kobj, &dev->kobj,
3967 dev_name(dev), kuid, kgid);
3975 EXPORT_SYMBOL_GPL(device_change_owner);
3978 * device_shutdown - call ->shutdown() on each device to shutdown.
3980 void device_shutdown(void)
3982 struct device *dev, *parent;
3984 wait_for_device_probe();
3985 device_block_probing();
3989 spin_lock(&devices_kset->list_lock);
3991 * Walk the devices list backward, shutting down each in turn.
3992 * Beware that device unplug events may also start pulling
3993 * devices offline, even as the system is shutting down.
3995 while (!list_empty(&devices_kset->list)) {
3996 dev = list_entry(devices_kset->list.prev, struct device,
4000 * hold reference count of device's parent to
4001 * prevent it from being freed because parent's
4002 * lock is to be held
4004 parent = get_device(dev->parent);
4007 * Make sure the device is off the kset list, in the
4008 * event that dev->*->shutdown() doesn't remove it.
4010 list_del_init(&dev->kobj.entry);
4011 spin_unlock(&devices_kset->list_lock);
4013 /* hold lock to avoid race with probe/release */
4015 device_lock(parent);
4018 /* Don't allow any more runtime suspends */
4019 pm_runtime_get_noresume(dev);
4020 pm_runtime_barrier(dev);
4022 if (dev->class && dev->class->shutdown_pre) {
4024 dev_info(dev, "shutdown_pre\n");
4025 dev->class->shutdown_pre(dev);
4027 if (dev->bus && dev->bus->shutdown) {
4029 dev_info(dev, "shutdown\n");
4030 dev->bus->shutdown(dev);
4031 } else if (dev->driver && dev->driver->shutdown) {
4033 dev_info(dev, "shutdown\n");
4034 dev->driver->shutdown(dev);
4039 device_unlock(parent);
4044 spin_lock(&devices_kset->list_lock);
4046 spin_unlock(&devices_kset->list_lock);
4050 * Device logging functions
4053 #ifdef CONFIG_PRINTK
4055 set_dev_info(const struct device *dev, struct dev_printk_info *dev_info)
4059 memset(dev_info, 0, sizeof(*dev_info));
4062 subsys = dev->class->name;
4064 subsys = dev->bus->name;
4068 strscpy(dev_info->subsystem, subsys, sizeof(dev_info->subsystem));
4071 * Add device identifier DEVICE=:
4075 * +sound:card0 subsystem:devname
4077 if (MAJOR(dev->devt)) {
4080 if (strcmp(subsys, "block") == 0)
4085 snprintf(dev_info->device, sizeof(dev_info->device),
4086 "%c%u:%u", c, MAJOR(dev->devt), MINOR(dev->devt));
4087 } else if (strcmp(subsys, "net") == 0) {
4088 struct net_device *net = to_net_dev(dev);
4090 snprintf(dev_info->device, sizeof(dev_info->device),
4091 "n%u", net->ifindex);
4093 snprintf(dev_info->device, sizeof(dev_info->device),
4094 "+%s:%s", subsys, dev_name(dev));
4098 int dev_vprintk_emit(int level, const struct device *dev,
4099 const char *fmt, va_list args)
4101 struct dev_printk_info dev_info;
4103 set_dev_info(dev, &dev_info);
4105 return vprintk_emit(0, level, &dev_info, fmt, args);
4107 EXPORT_SYMBOL(dev_vprintk_emit);
4109 int dev_printk_emit(int level, const struct device *dev, const char *fmt, ...)
4114 va_start(args, fmt);
4116 r = dev_vprintk_emit(level, dev, fmt, args);
4122 EXPORT_SYMBOL(dev_printk_emit);
4124 static void __dev_printk(const char *level, const struct device *dev,
4125 struct va_format *vaf)
4128 dev_printk_emit(level[1] - '0', dev, "%s %s: %pV",
4129 dev_driver_string(dev), dev_name(dev), vaf);
4131 printk("%s(NULL device *): %pV", level, vaf);
4134 void dev_printk(const char *level, const struct device *dev,
4135 const char *fmt, ...)
4137 struct va_format vaf;
4140 va_start(args, fmt);
4145 __dev_printk(level, dev, &vaf);
4149 EXPORT_SYMBOL(dev_printk);
4151 #define define_dev_printk_level(func, kern_level) \
4152 void func(const struct device *dev, const char *fmt, ...) \
4154 struct va_format vaf; \
4157 va_start(args, fmt); \
4162 __dev_printk(kern_level, dev, &vaf); \
4166 EXPORT_SYMBOL(func);
4168 define_dev_printk_level(_dev_emerg, KERN_EMERG);
4169 define_dev_printk_level(_dev_alert, KERN_ALERT);
4170 define_dev_printk_level(_dev_crit, KERN_CRIT);
4171 define_dev_printk_level(_dev_err, KERN_ERR);
4172 define_dev_printk_level(_dev_warn, KERN_WARNING);
4173 define_dev_printk_level(_dev_notice, KERN_NOTICE);
4174 define_dev_printk_level(_dev_info, KERN_INFO);
4179 * dev_err_probe - probe error check and log helper
4180 * @dev: the pointer to the struct device
4181 * @err: error value to test
4182 * @fmt: printf-style format string
4183 * @...: arguments as specified in the format string
4185 * This helper implements common pattern present in probe functions for error
4186 * checking: print debug or error message depending if the error value is
4187 * -EPROBE_DEFER and propagate error upwards.
4188 * In case of -EPROBE_DEFER it sets also defer probe reason, which can be
4189 * checked later by reading devices_deferred debugfs attribute.
4190 * It replaces code sequence::
4192 * if (err != -EPROBE_DEFER)
4193 * dev_err(dev, ...);
4195 * dev_dbg(dev, ...);
4200 * return dev_err_probe(dev, err, ...);
4205 int dev_err_probe(const struct device *dev, int err, const char *fmt, ...)
4207 struct va_format vaf;
4210 va_start(args, fmt);
4214 if (err != -EPROBE_DEFER) {
4215 dev_err(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
4217 device_set_deferred_probe_reason(dev, &vaf);
4218 dev_dbg(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
4225 EXPORT_SYMBOL_GPL(dev_err_probe);
4227 static inline bool fwnode_is_primary(struct fwnode_handle *fwnode)
4229 return fwnode && !IS_ERR(fwnode->secondary);
4233 * set_primary_fwnode - Change the primary firmware node of a given device.
4234 * @dev: Device to handle.
4235 * @fwnode: New primary firmware node of the device.
4237 * Set the device's firmware node pointer to @fwnode, but if a secondary
4238 * firmware node of the device is present, preserve it.
4240 void set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
4242 struct device *parent = dev->parent;
4243 struct fwnode_handle *fn = dev->fwnode;
4246 if (fwnode_is_primary(fn))
4250 WARN_ON(fwnode->secondary);
4251 fwnode->secondary = fn;
4253 dev->fwnode = fwnode;
4255 if (fwnode_is_primary(fn)) {
4256 dev->fwnode = fn->secondary;
4257 if (!(parent && fn == parent->fwnode))
4258 fn->secondary = ERR_PTR(-ENODEV);
4264 EXPORT_SYMBOL_GPL(set_primary_fwnode);
4267 * set_secondary_fwnode - Change the secondary firmware node of a given device.
4268 * @dev: Device to handle.
4269 * @fwnode: New secondary firmware node of the device.
4271 * If a primary firmware node of the device is present, set its secondary
4272 * pointer to @fwnode. Otherwise, set the device's firmware node pointer to
4275 void set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
4278 fwnode->secondary = ERR_PTR(-ENODEV);
4280 if (fwnode_is_primary(dev->fwnode))
4281 dev->fwnode->secondary = fwnode;
4283 dev->fwnode = fwnode;
4285 EXPORT_SYMBOL_GPL(set_secondary_fwnode);
4288 * device_set_of_node_from_dev - reuse device-tree node of another device
4289 * @dev: device whose device-tree node is being set
4290 * @dev2: device whose device-tree node is being reused
4292 * Takes another reference to the new device-tree node after first dropping
4293 * any reference held to the old node.
4295 void device_set_of_node_from_dev(struct device *dev, const struct device *dev2)
4297 of_node_put(dev->of_node);
4298 dev->of_node = of_node_get(dev2->of_node);
4299 dev->of_node_reused = true;
4301 EXPORT_SYMBOL_GPL(device_set_of_node_from_dev);
4303 int device_match_name(struct device *dev, const void *name)
4305 return sysfs_streq(dev_name(dev), name);
4307 EXPORT_SYMBOL_GPL(device_match_name);
4309 int device_match_of_node(struct device *dev, const void *np)
4311 return dev->of_node == np;
4313 EXPORT_SYMBOL_GPL(device_match_of_node);
4315 int device_match_fwnode(struct device *dev, const void *fwnode)
4317 return dev_fwnode(dev) == fwnode;
4319 EXPORT_SYMBOL_GPL(device_match_fwnode);
4321 int device_match_devt(struct device *dev, const void *pdevt)
4323 return dev->devt == *(dev_t *)pdevt;
4325 EXPORT_SYMBOL_GPL(device_match_devt);
4327 int device_match_acpi_dev(struct device *dev, const void *adev)
4329 return ACPI_COMPANION(dev) == adev;
4331 EXPORT_SYMBOL(device_match_acpi_dev);
4333 int device_match_any(struct device *dev, const void *unused)
4337 EXPORT_SYMBOL_GPL(device_match_any);