base: core: Remove WARN_ON from link dependencies check
[linux-2.6/btrfs-unstable.git] / drivers / base / core.c
blob2300d834d11ff841e4eecd11c795bdb0196eec1c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
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.
9 */
11 #include <linux/device.h>
12 #include <linux/err.h>
13 #include <linux/fwnode.h>
14 #include <linux/init.h>
15 #include <linux/module.h>
16 #include <linux/slab.h>
17 #include <linux/string.h>
18 #include <linux/kdev_t.h>
19 #include <linux/notifier.h>
20 #include <linux/of.h>
21 #include <linux/of_device.h>
22 #include <linux/genhd.h>
23 #include <linux/mutex.h>
24 #include <linux/pm_runtime.h>
25 #include <linux/netdevice.h>
26 #include <linux/sched/signal.h>
27 #include <linux/sysfs.h>
29 #include "base.h"
30 #include "power/power.h"
32 #ifdef CONFIG_SYSFS_DEPRECATED
33 #ifdef CONFIG_SYSFS_DEPRECATED_V2
34 long sysfs_deprecated = 1;
35 #else
36 long sysfs_deprecated = 0;
37 #endif
38 static int __init sysfs_deprecated_setup(char *arg)
40 return kstrtol(arg, 10, &sysfs_deprecated);
42 early_param("sysfs.deprecated", sysfs_deprecated_setup);
43 #endif
45 /* Device links support. */
47 #ifdef CONFIG_SRCU
48 static DEFINE_MUTEX(device_links_lock);
49 DEFINE_STATIC_SRCU(device_links_srcu);
51 static inline void device_links_write_lock(void)
53 mutex_lock(&device_links_lock);
56 static inline void device_links_write_unlock(void)
58 mutex_unlock(&device_links_lock);
61 int device_links_read_lock(void)
63 return srcu_read_lock(&device_links_srcu);
66 void device_links_read_unlock(int idx)
68 srcu_read_unlock(&device_links_srcu, idx);
70 #else /* !CONFIG_SRCU */
71 static DECLARE_RWSEM(device_links_lock);
73 static inline void device_links_write_lock(void)
75 down_write(&device_links_lock);
78 static inline void device_links_write_unlock(void)
80 up_write(&device_links_lock);
83 int device_links_read_lock(void)
85 down_read(&device_links_lock);
86 return 0;
89 void device_links_read_unlock(int not_used)
91 up_read(&device_links_lock);
93 #endif /* !CONFIG_SRCU */
95 /**
96 * device_is_dependent - Check if one device depends on another one
97 * @dev: Device to check dependencies for.
98 * @target: Device to check against.
100 * Check if @target depends on @dev or any device dependent on it (its child or
101 * its consumer etc). Return 1 if that is the case or 0 otherwise.
103 static int device_is_dependent(struct device *dev, void *target)
105 struct device_link *link;
106 int ret;
108 if (dev == target)
109 return 1;
111 ret = device_for_each_child(dev, target, device_is_dependent);
112 if (ret)
113 return ret;
115 list_for_each_entry(link, &dev->links.consumers, s_node) {
116 if (link->consumer == target)
117 return 1;
119 ret = device_is_dependent(link->consumer, target);
120 if (ret)
121 break;
123 return ret;
126 static int device_reorder_to_tail(struct device *dev, void *not_used)
128 struct device_link *link;
131 * Devices that have not been registered yet will be put to the ends
132 * of the lists during the registration, so skip them here.
134 if (device_is_registered(dev))
135 devices_kset_move_last(dev);
137 if (device_pm_initialized(dev))
138 device_pm_move_last(dev);
140 device_for_each_child(dev, NULL, device_reorder_to_tail);
141 list_for_each_entry(link, &dev->links.consumers, s_node)
142 device_reorder_to_tail(link->consumer, NULL);
144 return 0;
148 * device_pm_move_to_tail - Move set of devices to the end of device lists
149 * @dev: Device to move
151 * This is a device_reorder_to_tail() wrapper taking the requisite locks.
153 * It moves the @dev along with all of its children and all of its consumers
154 * to the ends of the device_kset and dpm_list, recursively.
156 void device_pm_move_to_tail(struct device *dev)
158 int idx;
160 idx = device_links_read_lock();
161 device_pm_lock();
162 device_reorder_to_tail(dev, NULL);
163 device_pm_unlock();
164 device_links_read_unlock(idx);
168 * device_link_add - Create a link between two devices.
169 * @consumer: Consumer end of the link.
170 * @supplier: Supplier end of the link.
171 * @flags: Link flags.
173 * The caller is responsible for the proper synchronization of the link creation
174 * with runtime PM. First, setting the DL_FLAG_PM_RUNTIME flag will cause the
175 * runtime PM framework to take the link into account. Second, if the
176 * DL_FLAG_RPM_ACTIVE flag is set in addition to it, the supplier devices will
177 * be forced into the active metastate and reference-counted upon the creation
178 * of the link. If DL_FLAG_PM_RUNTIME is not set, DL_FLAG_RPM_ACTIVE will be
179 * ignored.
181 * If the DL_FLAG_AUTOREMOVE is set, the link will be removed automatically
182 * when the consumer device driver unbinds from it. The combination of both
183 * DL_FLAG_AUTOREMOVE and DL_FLAG_STATELESS set is invalid and will cause NULL
184 * to be returned.
186 * A side effect of the link creation is re-ordering of dpm_list and the
187 * devices_kset list by moving the consumer device and all devices depending
188 * on it to the ends of these lists (that does not happen to devices that have
189 * not been registered when this function is called).
191 * The supplier device is required to be registered when this function is called
192 * and NULL will be returned if that is not the case. The consumer device need
193 * not be registered, however.
195 struct device_link *device_link_add(struct device *consumer,
196 struct device *supplier, u32 flags)
198 struct device_link *link;
200 if (!consumer || !supplier ||
201 ((flags & DL_FLAG_STATELESS) && (flags & DL_FLAG_AUTOREMOVE)))
202 return NULL;
204 device_links_write_lock();
205 device_pm_lock();
208 * If the supplier has not been fully registered yet or there is a
209 * reverse dependency between the consumer and the supplier already in
210 * the graph, return NULL.
212 if (!device_pm_initialized(supplier)
213 || device_is_dependent(consumer, supplier)) {
214 link = NULL;
215 goto out;
218 list_for_each_entry(link, &supplier->links.consumers, s_node)
219 if (link->consumer == consumer) {
220 kref_get(&link->kref);
221 goto out;
224 link = kzalloc(sizeof(*link), GFP_KERNEL);
225 if (!link)
226 goto out;
228 if (flags & DL_FLAG_PM_RUNTIME) {
229 if (flags & DL_FLAG_RPM_ACTIVE) {
230 if (pm_runtime_get_sync(supplier) < 0) {
231 pm_runtime_put_noidle(supplier);
232 kfree(link);
233 link = NULL;
234 goto out;
236 link->rpm_active = true;
238 pm_runtime_new_link(consumer);
240 * If the link is being added by the consumer driver at probe
241 * time, balance the decrementation of the supplier's runtime PM
242 * usage counter after consumer probe in driver_probe_device().
244 if (consumer->links.status == DL_DEV_PROBING)
245 pm_runtime_get_noresume(supplier);
247 get_device(supplier);
248 link->supplier = supplier;
249 INIT_LIST_HEAD(&link->s_node);
250 get_device(consumer);
251 link->consumer = consumer;
252 INIT_LIST_HEAD(&link->c_node);
253 link->flags = flags;
254 kref_init(&link->kref);
256 /* Determine the initial link state. */
257 if (flags & DL_FLAG_STATELESS) {
258 link->status = DL_STATE_NONE;
259 } else {
260 switch (supplier->links.status) {
261 case DL_DEV_DRIVER_BOUND:
262 switch (consumer->links.status) {
263 case DL_DEV_PROBING:
265 * Some callers expect the link creation during
266 * consumer driver probe to resume the supplier
267 * even without DL_FLAG_RPM_ACTIVE.
269 if (flags & DL_FLAG_PM_RUNTIME)
270 pm_runtime_resume(supplier);
272 link->status = DL_STATE_CONSUMER_PROBE;
273 break;
274 case DL_DEV_DRIVER_BOUND:
275 link->status = DL_STATE_ACTIVE;
276 break;
277 default:
278 link->status = DL_STATE_AVAILABLE;
279 break;
281 break;
282 case DL_DEV_UNBINDING:
283 link->status = DL_STATE_SUPPLIER_UNBIND;
284 break;
285 default:
286 link->status = DL_STATE_DORMANT;
287 break;
292 * Move the consumer and all of the devices depending on it to the end
293 * of dpm_list and the devices_kset list.
295 * It is necessary to hold dpm_list locked throughout all that or else
296 * we may end up suspending with a wrong ordering of it.
298 device_reorder_to_tail(consumer, NULL);
300 list_add_tail_rcu(&link->s_node, &supplier->links.consumers);
301 list_add_tail_rcu(&link->c_node, &consumer->links.suppliers);
303 dev_info(consumer, "Linked as a consumer to %s\n", dev_name(supplier));
305 out:
306 device_pm_unlock();
307 device_links_write_unlock();
308 return link;
310 EXPORT_SYMBOL_GPL(device_link_add);
312 static void device_link_free(struct device_link *link)
314 put_device(link->consumer);
315 put_device(link->supplier);
316 kfree(link);
319 #ifdef CONFIG_SRCU
320 static void __device_link_free_srcu(struct rcu_head *rhead)
322 device_link_free(container_of(rhead, struct device_link, rcu_head));
325 static void __device_link_del(struct kref *kref)
327 struct device_link *link = container_of(kref, struct device_link, kref);
329 dev_info(link->consumer, "Dropping the link to %s\n",
330 dev_name(link->supplier));
332 if (link->flags & DL_FLAG_PM_RUNTIME)
333 pm_runtime_drop_link(link->consumer);
335 list_del_rcu(&link->s_node);
336 list_del_rcu(&link->c_node);
337 call_srcu(&device_links_srcu, &link->rcu_head, __device_link_free_srcu);
339 #else /* !CONFIG_SRCU */
340 static void __device_link_del(struct kref *kref)
342 struct device_link *link = container_of(kref, struct device_link, kref);
344 dev_info(link->consumer, "Dropping the link to %s\n",
345 dev_name(link->supplier));
347 if (link->flags & DL_FLAG_PM_RUNTIME)
348 pm_runtime_drop_link(link->consumer);
350 list_del(&link->s_node);
351 list_del(&link->c_node);
352 device_link_free(link);
354 #endif /* !CONFIG_SRCU */
357 * device_link_del - Delete a link between two devices.
358 * @link: Device link to delete.
360 * The caller must ensure proper synchronization of this function with runtime
361 * PM. If the link was added multiple times, it needs to be deleted as often.
362 * Care is required for hotplugged devices: Their links are purged on removal
363 * and calling device_link_del() is then no longer allowed.
365 void device_link_del(struct device_link *link)
367 device_links_write_lock();
368 device_pm_lock();
369 kref_put(&link->kref, __device_link_del);
370 device_pm_unlock();
371 device_links_write_unlock();
373 EXPORT_SYMBOL_GPL(device_link_del);
375 static void device_links_missing_supplier(struct device *dev)
377 struct device_link *link;
379 list_for_each_entry(link, &dev->links.suppliers, c_node)
380 if (link->status == DL_STATE_CONSUMER_PROBE)
381 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
385 * device_links_check_suppliers - Check presence of supplier drivers.
386 * @dev: Consumer device.
388 * Check links from this device to any suppliers. Walk the list of the device's
389 * links to suppliers and see if all of them are available. If not, simply
390 * return -EPROBE_DEFER.
392 * We need to guarantee that the supplier will not go away after the check has
393 * been positive here. It only can go away in __device_release_driver() and
394 * that function checks the device's links to consumers. This means we need to
395 * mark the link as "consumer probe in progress" to make the supplier removal
396 * wait for us to complete (or bad things may happen).
398 * Links with the DL_FLAG_STATELESS flag set are ignored.
400 int device_links_check_suppliers(struct device *dev)
402 struct device_link *link;
403 int ret = 0;
405 device_links_write_lock();
407 list_for_each_entry(link, &dev->links.suppliers, c_node) {
408 if (link->flags & DL_FLAG_STATELESS)
409 continue;
411 if (link->status != DL_STATE_AVAILABLE) {
412 device_links_missing_supplier(dev);
413 ret = -EPROBE_DEFER;
414 break;
416 WRITE_ONCE(link->status, DL_STATE_CONSUMER_PROBE);
418 dev->links.status = DL_DEV_PROBING;
420 device_links_write_unlock();
421 return ret;
425 * device_links_driver_bound - Update device links after probing its driver.
426 * @dev: Device to update the links for.
428 * The probe has been successful, so update links from this device to any
429 * consumers by changing their status to "available".
431 * Also change the status of @dev's links to suppliers to "active".
433 * Links with the DL_FLAG_STATELESS flag set are ignored.
435 void device_links_driver_bound(struct device *dev)
437 struct device_link *link;
439 device_links_write_lock();
441 list_for_each_entry(link, &dev->links.consumers, s_node) {
442 if (link->flags & DL_FLAG_STATELESS)
443 continue;
445 WARN_ON(link->status != DL_STATE_DORMANT);
446 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
449 list_for_each_entry(link, &dev->links.suppliers, c_node) {
450 if (link->flags & DL_FLAG_STATELESS)
451 continue;
453 WARN_ON(link->status != DL_STATE_CONSUMER_PROBE);
454 WRITE_ONCE(link->status, DL_STATE_ACTIVE);
457 dev->links.status = DL_DEV_DRIVER_BOUND;
459 device_links_write_unlock();
463 * __device_links_no_driver - Update links of a device without a driver.
464 * @dev: Device without a drvier.
466 * Delete all non-persistent links from this device to any suppliers.
468 * Persistent links stay around, but their status is changed to "available",
469 * unless they already are in the "supplier unbind in progress" state in which
470 * case they need not be updated.
472 * Links with the DL_FLAG_STATELESS flag set are ignored.
474 static void __device_links_no_driver(struct device *dev)
476 struct device_link *link, *ln;
478 list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
479 if (link->flags & DL_FLAG_STATELESS)
480 continue;
482 if (link->flags & DL_FLAG_AUTOREMOVE)
483 kref_put(&link->kref, __device_link_del);
484 else if (link->status != DL_STATE_SUPPLIER_UNBIND)
485 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
488 dev->links.status = DL_DEV_NO_DRIVER;
491 void device_links_no_driver(struct device *dev)
493 device_links_write_lock();
494 __device_links_no_driver(dev);
495 device_links_write_unlock();
499 * device_links_driver_cleanup - Update links after driver removal.
500 * @dev: Device whose driver has just gone away.
502 * Update links to consumers for @dev by changing their status to "dormant" and
503 * invoke %__device_links_no_driver() to update links to suppliers for it as
504 * appropriate.
506 * Links with the DL_FLAG_STATELESS flag set are ignored.
508 void device_links_driver_cleanup(struct device *dev)
510 struct device_link *link;
512 device_links_write_lock();
514 list_for_each_entry(link, &dev->links.consumers, s_node) {
515 if (link->flags & DL_FLAG_STATELESS)
516 continue;
518 WARN_ON(link->flags & DL_FLAG_AUTOREMOVE);
519 WARN_ON(link->status != DL_STATE_SUPPLIER_UNBIND);
520 WRITE_ONCE(link->status, DL_STATE_DORMANT);
523 __device_links_no_driver(dev);
525 device_links_write_unlock();
529 * device_links_busy - Check if there are any busy links to consumers.
530 * @dev: Device to check.
532 * Check each consumer of the device and return 'true' if its link's status
533 * is one of "consumer probe" or "active" (meaning that the given consumer is
534 * probing right now or its driver is present). Otherwise, change the link
535 * state to "supplier unbind" to prevent the consumer from being probed
536 * successfully going forward.
538 * Return 'false' if there are no probing or active consumers.
540 * Links with the DL_FLAG_STATELESS flag set are ignored.
542 bool device_links_busy(struct device *dev)
544 struct device_link *link;
545 bool ret = false;
547 device_links_write_lock();
549 list_for_each_entry(link, &dev->links.consumers, s_node) {
550 if (link->flags & DL_FLAG_STATELESS)
551 continue;
553 if (link->status == DL_STATE_CONSUMER_PROBE
554 || link->status == DL_STATE_ACTIVE) {
555 ret = true;
556 break;
558 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
561 dev->links.status = DL_DEV_UNBINDING;
563 device_links_write_unlock();
564 return ret;
568 * device_links_unbind_consumers - Force unbind consumers of the given device.
569 * @dev: Device to unbind the consumers of.
571 * Walk the list of links to consumers for @dev and if any of them is in the
572 * "consumer probe" state, wait for all device probes in progress to complete
573 * and start over.
575 * If that's not the case, change the status of the link to "supplier unbind"
576 * and check if the link was in the "active" state. If so, force the consumer
577 * driver to unbind and start over (the consumer will not re-probe as we have
578 * changed the state of the link already).
580 * Links with the DL_FLAG_STATELESS flag set are ignored.
582 void device_links_unbind_consumers(struct device *dev)
584 struct device_link *link;
586 start:
587 device_links_write_lock();
589 list_for_each_entry(link, &dev->links.consumers, s_node) {
590 enum device_link_state status;
592 if (link->flags & DL_FLAG_STATELESS)
593 continue;
595 status = link->status;
596 if (status == DL_STATE_CONSUMER_PROBE) {
597 device_links_write_unlock();
599 wait_for_device_probe();
600 goto start;
602 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
603 if (status == DL_STATE_ACTIVE) {
604 struct device *consumer = link->consumer;
606 get_device(consumer);
608 device_links_write_unlock();
610 device_release_driver_internal(consumer, NULL,
611 consumer->parent);
612 put_device(consumer);
613 goto start;
617 device_links_write_unlock();
621 * device_links_purge - Delete existing links to other devices.
622 * @dev: Target device.
624 static void device_links_purge(struct device *dev)
626 struct device_link *link, *ln;
629 * Delete all of the remaining links from this device to any other
630 * devices (either consumers or suppliers).
632 device_links_write_lock();
634 list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
635 WARN_ON(link->status == DL_STATE_ACTIVE);
636 __device_link_del(&link->kref);
639 list_for_each_entry_safe_reverse(link, ln, &dev->links.consumers, s_node) {
640 WARN_ON(link->status != DL_STATE_DORMANT &&
641 link->status != DL_STATE_NONE);
642 __device_link_del(&link->kref);
645 device_links_write_unlock();
648 /* Device links support end. */
650 int (*platform_notify)(struct device *dev) = NULL;
651 int (*platform_notify_remove)(struct device *dev) = NULL;
652 static struct kobject *dev_kobj;
653 struct kobject *sysfs_dev_char_kobj;
654 struct kobject *sysfs_dev_block_kobj;
656 static DEFINE_MUTEX(device_hotplug_lock);
658 void lock_device_hotplug(void)
660 mutex_lock(&device_hotplug_lock);
663 void unlock_device_hotplug(void)
665 mutex_unlock(&device_hotplug_lock);
668 int lock_device_hotplug_sysfs(void)
670 if (mutex_trylock(&device_hotplug_lock))
671 return 0;
673 /* Avoid busy looping (5 ms of sleep should do). */
674 msleep(5);
675 return restart_syscall();
678 #ifdef CONFIG_BLOCK
679 static inline int device_is_not_partition(struct device *dev)
681 return !(dev->type == &part_type);
683 #else
684 static inline int device_is_not_partition(struct device *dev)
686 return 1;
688 #endif
691 * dev_driver_string - Return a device's driver name, if at all possible
692 * @dev: struct device to get the name of
694 * Will return the device's driver's name if it is bound to a device. If
695 * the device is not bound to a driver, it will return the name of the bus
696 * it is attached to. If it is not attached to a bus either, an empty
697 * string will be returned.
699 const char *dev_driver_string(const struct device *dev)
701 struct device_driver *drv;
703 /* dev->driver can change to NULL underneath us because of unbinding,
704 * so be careful about accessing it. dev->bus and dev->class should
705 * never change once they are set, so they don't need special care.
707 drv = READ_ONCE(dev->driver);
708 return drv ? drv->name :
709 (dev->bus ? dev->bus->name :
710 (dev->class ? dev->class->name : ""));
712 EXPORT_SYMBOL(dev_driver_string);
714 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
716 static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
717 char *buf)
719 struct device_attribute *dev_attr = to_dev_attr(attr);
720 struct device *dev = kobj_to_dev(kobj);
721 ssize_t ret = -EIO;
723 if (dev_attr->show)
724 ret = dev_attr->show(dev, dev_attr, buf);
725 if (ret >= (ssize_t)PAGE_SIZE) {
726 printk("dev_attr_show: %pS returned bad count\n",
727 dev_attr->show);
729 return ret;
732 static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
733 const char *buf, size_t count)
735 struct device_attribute *dev_attr = to_dev_attr(attr);
736 struct device *dev = kobj_to_dev(kobj);
737 ssize_t ret = -EIO;
739 if (dev_attr->store)
740 ret = dev_attr->store(dev, dev_attr, buf, count);
741 return ret;
744 static const struct sysfs_ops dev_sysfs_ops = {
745 .show = dev_attr_show,
746 .store = dev_attr_store,
749 #define to_ext_attr(x) container_of(x, struct dev_ext_attribute, attr)
751 ssize_t device_store_ulong(struct device *dev,
752 struct device_attribute *attr,
753 const char *buf, size_t size)
755 struct dev_ext_attribute *ea = to_ext_attr(attr);
756 char *end;
757 unsigned long new = simple_strtoul(buf, &end, 0);
758 if (end == buf)
759 return -EINVAL;
760 *(unsigned long *)(ea->var) = new;
761 /* Always return full write size even if we didn't consume all */
762 return size;
764 EXPORT_SYMBOL_GPL(device_store_ulong);
766 ssize_t device_show_ulong(struct device *dev,
767 struct device_attribute *attr,
768 char *buf)
770 struct dev_ext_attribute *ea = to_ext_attr(attr);
771 return snprintf(buf, PAGE_SIZE, "%lx\n", *(unsigned long *)(ea->var));
773 EXPORT_SYMBOL_GPL(device_show_ulong);
775 ssize_t device_store_int(struct device *dev,
776 struct device_attribute *attr,
777 const char *buf, size_t size)
779 struct dev_ext_attribute *ea = to_ext_attr(attr);
780 char *end;
781 long new = simple_strtol(buf, &end, 0);
782 if (end == buf || new > INT_MAX || new < INT_MIN)
783 return -EINVAL;
784 *(int *)(ea->var) = new;
785 /* Always return full write size even if we didn't consume all */
786 return size;
788 EXPORT_SYMBOL_GPL(device_store_int);
790 ssize_t device_show_int(struct device *dev,
791 struct device_attribute *attr,
792 char *buf)
794 struct dev_ext_attribute *ea = to_ext_attr(attr);
796 return snprintf(buf, PAGE_SIZE, "%d\n", *(int *)(ea->var));
798 EXPORT_SYMBOL_GPL(device_show_int);
800 ssize_t device_store_bool(struct device *dev, struct device_attribute *attr,
801 const char *buf, size_t size)
803 struct dev_ext_attribute *ea = to_ext_attr(attr);
805 if (strtobool(buf, ea->var) < 0)
806 return -EINVAL;
808 return size;
810 EXPORT_SYMBOL_GPL(device_store_bool);
812 ssize_t device_show_bool(struct device *dev, struct device_attribute *attr,
813 char *buf)
815 struct dev_ext_attribute *ea = to_ext_attr(attr);
817 return snprintf(buf, PAGE_SIZE, "%d\n", *(bool *)(ea->var));
819 EXPORT_SYMBOL_GPL(device_show_bool);
822 * device_release - free device structure.
823 * @kobj: device's kobject.
825 * This is called once the reference count for the object
826 * reaches 0. We forward the call to the device's release
827 * method, which should handle actually freeing the structure.
829 static void device_release(struct kobject *kobj)
831 struct device *dev = kobj_to_dev(kobj);
832 struct device_private *p = dev->p;
835 * Some platform devices are driven without driver attached
836 * and managed resources may have been acquired. Make sure
837 * all resources are released.
839 * Drivers still can add resources into device after device
840 * is deleted but alive, so release devres here to avoid
841 * possible memory leak.
843 devres_release_all(dev);
845 if (dev->release)
846 dev->release(dev);
847 else if (dev->type && dev->type->release)
848 dev->type->release(dev);
849 else if (dev->class && dev->class->dev_release)
850 dev->class->dev_release(dev);
851 else
852 WARN(1, KERN_ERR "Device '%s' does not have a release() "
853 "function, it is broken and must be fixed.\n",
854 dev_name(dev));
855 kfree(p);
858 static const void *device_namespace(struct kobject *kobj)
860 struct device *dev = kobj_to_dev(kobj);
861 const void *ns = NULL;
863 if (dev->class && dev->class->ns_type)
864 ns = dev->class->namespace(dev);
866 return ns;
869 static struct kobj_type device_ktype = {
870 .release = device_release,
871 .sysfs_ops = &dev_sysfs_ops,
872 .namespace = device_namespace,
876 static int dev_uevent_filter(struct kset *kset, struct kobject *kobj)
878 struct kobj_type *ktype = get_ktype(kobj);
880 if (ktype == &device_ktype) {
881 struct device *dev = kobj_to_dev(kobj);
882 if (dev->bus)
883 return 1;
884 if (dev->class)
885 return 1;
887 return 0;
890 static const char *dev_uevent_name(struct kset *kset, struct kobject *kobj)
892 struct device *dev = kobj_to_dev(kobj);
894 if (dev->bus)
895 return dev->bus->name;
896 if (dev->class)
897 return dev->class->name;
898 return NULL;
901 static int dev_uevent(struct kset *kset, struct kobject *kobj,
902 struct kobj_uevent_env *env)
904 struct device *dev = kobj_to_dev(kobj);
905 int retval = 0;
907 /* add device node properties if present */
908 if (MAJOR(dev->devt)) {
909 const char *tmp;
910 const char *name;
911 umode_t mode = 0;
912 kuid_t uid = GLOBAL_ROOT_UID;
913 kgid_t gid = GLOBAL_ROOT_GID;
915 add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt));
916 add_uevent_var(env, "MINOR=%u", MINOR(dev->devt));
917 name = device_get_devnode(dev, &mode, &uid, &gid, &tmp);
918 if (name) {
919 add_uevent_var(env, "DEVNAME=%s", name);
920 if (mode)
921 add_uevent_var(env, "DEVMODE=%#o", mode & 0777);
922 if (!uid_eq(uid, GLOBAL_ROOT_UID))
923 add_uevent_var(env, "DEVUID=%u", from_kuid(&init_user_ns, uid));
924 if (!gid_eq(gid, GLOBAL_ROOT_GID))
925 add_uevent_var(env, "DEVGID=%u", from_kgid(&init_user_ns, gid));
926 kfree(tmp);
930 if (dev->type && dev->type->name)
931 add_uevent_var(env, "DEVTYPE=%s", dev->type->name);
933 if (dev->driver)
934 add_uevent_var(env, "DRIVER=%s", dev->driver->name);
936 /* Add common DT information about the device */
937 of_device_uevent(dev, env);
939 /* have the bus specific function add its stuff */
940 if (dev->bus && dev->bus->uevent) {
941 retval = dev->bus->uevent(dev, env);
942 if (retval)
943 pr_debug("device: '%s': %s: bus uevent() returned %d\n",
944 dev_name(dev), __func__, retval);
947 /* have the class specific function add its stuff */
948 if (dev->class && dev->class->dev_uevent) {
949 retval = dev->class->dev_uevent(dev, env);
950 if (retval)
951 pr_debug("device: '%s': %s: class uevent() "
952 "returned %d\n", dev_name(dev),
953 __func__, retval);
956 /* have the device type specific function add its stuff */
957 if (dev->type && dev->type->uevent) {
958 retval = dev->type->uevent(dev, env);
959 if (retval)
960 pr_debug("device: '%s': %s: dev_type uevent() "
961 "returned %d\n", dev_name(dev),
962 __func__, retval);
965 return retval;
968 static const struct kset_uevent_ops device_uevent_ops = {
969 .filter = dev_uevent_filter,
970 .name = dev_uevent_name,
971 .uevent = dev_uevent,
974 static ssize_t uevent_show(struct device *dev, struct device_attribute *attr,
975 char *buf)
977 struct kobject *top_kobj;
978 struct kset *kset;
979 struct kobj_uevent_env *env = NULL;
980 int i;
981 size_t count = 0;
982 int retval;
984 /* search the kset, the device belongs to */
985 top_kobj = &dev->kobj;
986 while (!top_kobj->kset && top_kobj->parent)
987 top_kobj = top_kobj->parent;
988 if (!top_kobj->kset)
989 goto out;
991 kset = top_kobj->kset;
992 if (!kset->uevent_ops || !kset->uevent_ops->uevent)
993 goto out;
995 /* respect filter */
996 if (kset->uevent_ops && kset->uevent_ops->filter)
997 if (!kset->uevent_ops->filter(kset, &dev->kobj))
998 goto out;
1000 env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
1001 if (!env)
1002 return -ENOMEM;
1004 /* let the kset specific function add its keys */
1005 retval = kset->uevent_ops->uevent(kset, &dev->kobj, env);
1006 if (retval)
1007 goto out;
1009 /* copy keys to file */
1010 for (i = 0; i < env->envp_idx; i++)
1011 count += sprintf(&buf[count], "%s\n", env->envp[i]);
1012 out:
1013 kfree(env);
1014 return count;
1017 static ssize_t uevent_store(struct device *dev, struct device_attribute *attr,
1018 const char *buf, size_t count)
1020 if (kobject_synth_uevent(&dev->kobj, buf, count))
1021 dev_err(dev, "uevent: failed to send synthetic uevent\n");
1023 return count;
1025 static DEVICE_ATTR_RW(uevent);
1027 static ssize_t online_show(struct device *dev, struct device_attribute *attr,
1028 char *buf)
1030 bool val;
1032 device_lock(dev);
1033 val = !dev->offline;
1034 device_unlock(dev);
1035 return sprintf(buf, "%u\n", val);
1038 static ssize_t online_store(struct device *dev, struct device_attribute *attr,
1039 const char *buf, size_t count)
1041 bool val;
1042 int ret;
1044 ret = strtobool(buf, &val);
1045 if (ret < 0)
1046 return ret;
1048 ret = lock_device_hotplug_sysfs();
1049 if (ret)
1050 return ret;
1052 ret = val ? device_online(dev) : device_offline(dev);
1053 unlock_device_hotplug();
1054 return ret < 0 ? ret : count;
1056 static DEVICE_ATTR_RW(online);
1058 int device_add_groups(struct device *dev, const struct attribute_group **groups)
1060 return sysfs_create_groups(&dev->kobj, groups);
1062 EXPORT_SYMBOL_GPL(device_add_groups);
1064 void device_remove_groups(struct device *dev,
1065 const struct attribute_group **groups)
1067 sysfs_remove_groups(&dev->kobj, groups);
1069 EXPORT_SYMBOL_GPL(device_remove_groups);
1071 union device_attr_group_devres {
1072 const struct attribute_group *group;
1073 const struct attribute_group **groups;
1076 static int devm_attr_group_match(struct device *dev, void *res, void *data)
1078 return ((union device_attr_group_devres *)res)->group == data;
1081 static void devm_attr_group_remove(struct device *dev, void *res)
1083 union device_attr_group_devres *devres = res;
1084 const struct attribute_group *group = devres->group;
1086 dev_dbg(dev, "%s: removing group %p\n", __func__, group);
1087 sysfs_remove_group(&dev->kobj, group);
1090 static void devm_attr_groups_remove(struct device *dev, void *res)
1092 union device_attr_group_devres *devres = res;
1093 const struct attribute_group **groups = devres->groups;
1095 dev_dbg(dev, "%s: removing groups %p\n", __func__, groups);
1096 sysfs_remove_groups(&dev->kobj, groups);
1100 * devm_device_add_group - given a device, create a managed attribute group
1101 * @dev: The device to create the group for
1102 * @grp: The attribute group to create
1104 * This function creates a group for the first time. It will explicitly
1105 * warn and error if any of the attribute files being created already exist.
1107 * Returns 0 on success or error code on failure.
1109 int devm_device_add_group(struct device *dev, const struct attribute_group *grp)
1111 union device_attr_group_devres *devres;
1112 int error;
1114 devres = devres_alloc(devm_attr_group_remove,
1115 sizeof(*devres), GFP_KERNEL);
1116 if (!devres)
1117 return -ENOMEM;
1119 error = sysfs_create_group(&dev->kobj, grp);
1120 if (error) {
1121 devres_free(devres);
1122 return error;
1125 devres->group = grp;
1126 devres_add(dev, devres);
1127 return 0;
1129 EXPORT_SYMBOL_GPL(devm_device_add_group);
1132 * devm_device_remove_group: remove a managed group from a device
1133 * @dev: device to remove the group from
1134 * @grp: group to remove
1136 * This function removes a group of attributes from a device. The attributes
1137 * previously have to have been created for this group, otherwise it will fail.
1139 void devm_device_remove_group(struct device *dev,
1140 const struct attribute_group *grp)
1142 WARN_ON(devres_release(dev, devm_attr_group_remove,
1143 devm_attr_group_match,
1144 /* cast away const */ (void *)grp));
1146 EXPORT_SYMBOL_GPL(devm_device_remove_group);
1149 * devm_device_add_groups - create a bunch of managed attribute groups
1150 * @dev: The device to create the group for
1151 * @groups: The attribute groups to create, NULL terminated
1153 * This function creates a bunch of managed attribute groups. If an error
1154 * occurs when creating a group, all previously created groups will be
1155 * removed, unwinding everything back to the original state when this
1156 * function was called. It will explicitly warn and error if any of the
1157 * attribute files being created already exist.
1159 * Returns 0 on success or error code from sysfs_create_group on failure.
1161 int devm_device_add_groups(struct device *dev,
1162 const struct attribute_group **groups)
1164 union device_attr_group_devres *devres;
1165 int error;
1167 devres = devres_alloc(devm_attr_groups_remove,
1168 sizeof(*devres), GFP_KERNEL);
1169 if (!devres)
1170 return -ENOMEM;
1172 error = sysfs_create_groups(&dev->kobj, groups);
1173 if (error) {
1174 devres_free(devres);
1175 return error;
1178 devres->groups = groups;
1179 devres_add(dev, devres);
1180 return 0;
1182 EXPORT_SYMBOL_GPL(devm_device_add_groups);
1185 * devm_device_remove_groups - remove a list of managed groups
1187 * @dev: The device for the groups to be removed from
1188 * @groups: NULL terminated list of groups to be removed
1190 * If groups is not NULL, remove the specified groups from the device.
1192 void devm_device_remove_groups(struct device *dev,
1193 const struct attribute_group **groups)
1195 WARN_ON(devres_release(dev, devm_attr_groups_remove,
1196 devm_attr_group_match,
1197 /* cast away const */ (void *)groups));
1199 EXPORT_SYMBOL_GPL(devm_device_remove_groups);
1201 static int device_add_attrs(struct device *dev)
1203 struct class *class = dev->class;
1204 const struct device_type *type = dev->type;
1205 int error;
1207 if (class) {
1208 error = device_add_groups(dev, class->dev_groups);
1209 if (error)
1210 return error;
1213 if (type) {
1214 error = device_add_groups(dev, type->groups);
1215 if (error)
1216 goto err_remove_class_groups;
1219 error = device_add_groups(dev, dev->groups);
1220 if (error)
1221 goto err_remove_type_groups;
1223 if (device_supports_offline(dev) && !dev->offline_disabled) {
1224 error = device_create_file(dev, &dev_attr_online);
1225 if (error)
1226 goto err_remove_dev_groups;
1229 return 0;
1231 err_remove_dev_groups:
1232 device_remove_groups(dev, dev->groups);
1233 err_remove_type_groups:
1234 if (type)
1235 device_remove_groups(dev, type->groups);
1236 err_remove_class_groups:
1237 if (class)
1238 device_remove_groups(dev, class->dev_groups);
1240 return error;
1243 static void device_remove_attrs(struct device *dev)
1245 struct class *class = dev->class;
1246 const struct device_type *type = dev->type;
1248 device_remove_file(dev, &dev_attr_online);
1249 device_remove_groups(dev, dev->groups);
1251 if (type)
1252 device_remove_groups(dev, type->groups);
1254 if (class)
1255 device_remove_groups(dev, class->dev_groups);
1258 static ssize_t dev_show(struct device *dev, struct device_attribute *attr,
1259 char *buf)
1261 return print_dev_t(buf, dev->devt);
1263 static DEVICE_ATTR_RO(dev);
1265 /* /sys/devices/ */
1266 struct kset *devices_kset;
1269 * devices_kset_move_before - Move device in the devices_kset's list.
1270 * @deva: Device to move.
1271 * @devb: Device @deva should come before.
1273 static void devices_kset_move_before(struct device *deva, struct device *devb)
1275 if (!devices_kset)
1276 return;
1277 pr_debug("devices_kset: Moving %s before %s\n",
1278 dev_name(deva), dev_name(devb));
1279 spin_lock(&devices_kset->list_lock);
1280 list_move_tail(&deva->kobj.entry, &devb->kobj.entry);
1281 spin_unlock(&devices_kset->list_lock);
1285 * devices_kset_move_after - Move device in the devices_kset's list.
1286 * @deva: Device to move
1287 * @devb: Device @deva should come after.
1289 static void devices_kset_move_after(struct device *deva, struct device *devb)
1291 if (!devices_kset)
1292 return;
1293 pr_debug("devices_kset: Moving %s after %s\n",
1294 dev_name(deva), dev_name(devb));
1295 spin_lock(&devices_kset->list_lock);
1296 list_move(&deva->kobj.entry, &devb->kobj.entry);
1297 spin_unlock(&devices_kset->list_lock);
1301 * devices_kset_move_last - move the device to the end of devices_kset's list.
1302 * @dev: device to move
1304 void devices_kset_move_last(struct device *dev)
1306 if (!devices_kset)
1307 return;
1308 pr_debug("devices_kset: Moving %s to end of list\n", dev_name(dev));
1309 spin_lock(&devices_kset->list_lock);
1310 list_move_tail(&dev->kobj.entry, &devices_kset->list);
1311 spin_unlock(&devices_kset->list_lock);
1315 * device_create_file - create sysfs attribute file for device.
1316 * @dev: device.
1317 * @attr: device attribute descriptor.
1319 int device_create_file(struct device *dev,
1320 const struct device_attribute *attr)
1322 int error = 0;
1324 if (dev) {
1325 WARN(((attr->attr.mode & S_IWUGO) && !attr->store),
1326 "Attribute %s: write permission without 'store'\n",
1327 attr->attr.name);
1328 WARN(((attr->attr.mode & S_IRUGO) && !attr->show),
1329 "Attribute %s: read permission without 'show'\n",
1330 attr->attr.name);
1331 error = sysfs_create_file(&dev->kobj, &attr->attr);
1334 return error;
1336 EXPORT_SYMBOL_GPL(device_create_file);
1339 * device_remove_file - remove sysfs attribute file.
1340 * @dev: device.
1341 * @attr: device attribute descriptor.
1343 void device_remove_file(struct device *dev,
1344 const struct device_attribute *attr)
1346 if (dev)
1347 sysfs_remove_file(&dev->kobj, &attr->attr);
1349 EXPORT_SYMBOL_GPL(device_remove_file);
1352 * device_remove_file_self - remove sysfs attribute file from its own method.
1353 * @dev: device.
1354 * @attr: device attribute descriptor.
1356 * See kernfs_remove_self() for details.
1358 bool device_remove_file_self(struct device *dev,
1359 const struct device_attribute *attr)
1361 if (dev)
1362 return sysfs_remove_file_self(&dev->kobj, &attr->attr);
1363 else
1364 return false;
1366 EXPORT_SYMBOL_GPL(device_remove_file_self);
1369 * device_create_bin_file - create sysfs binary attribute file for device.
1370 * @dev: device.
1371 * @attr: device binary attribute descriptor.
1373 int device_create_bin_file(struct device *dev,
1374 const struct bin_attribute *attr)
1376 int error = -EINVAL;
1377 if (dev)
1378 error = sysfs_create_bin_file(&dev->kobj, attr);
1379 return error;
1381 EXPORT_SYMBOL_GPL(device_create_bin_file);
1384 * device_remove_bin_file - remove sysfs binary attribute file
1385 * @dev: device.
1386 * @attr: device binary attribute descriptor.
1388 void device_remove_bin_file(struct device *dev,
1389 const struct bin_attribute *attr)
1391 if (dev)
1392 sysfs_remove_bin_file(&dev->kobj, attr);
1394 EXPORT_SYMBOL_GPL(device_remove_bin_file);
1396 static void klist_children_get(struct klist_node *n)
1398 struct device_private *p = to_device_private_parent(n);
1399 struct device *dev = p->device;
1401 get_device(dev);
1404 static void klist_children_put(struct klist_node *n)
1406 struct device_private *p = to_device_private_parent(n);
1407 struct device *dev = p->device;
1409 put_device(dev);
1413 * device_initialize - init device structure.
1414 * @dev: device.
1416 * This prepares the device for use by other layers by initializing
1417 * its fields.
1418 * It is the first half of device_register(), if called by
1419 * that function, though it can also be called separately, so one
1420 * may use @dev's fields. In particular, get_device()/put_device()
1421 * may be used for reference counting of @dev after calling this
1422 * function.
1424 * All fields in @dev must be initialized by the caller to 0, except
1425 * for those explicitly set to some other value. The simplest
1426 * approach is to use kzalloc() to allocate the structure containing
1427 * @dev.
1429 * NOTE: Use put_device() to give up your reference instead of freeing
1430 * @dev directly once you have called this function.
1432 void device_initialize(struct device *dev)
1434 dev->kobj.kset = devices_kset;
1435 kobject_init(&dev->kobj, &device_ktype);
1436 INIT_LIST_HEAD(&dev->dma_pools);
1437 mutex_init(&dev->mutex);
1438 lockdep_set_novalidate_class(&dev->mutex);
1439 spin_lock_init(&dev->devres_lock);
1440 INIT_LIST_HEAD(&dev->devres_head);
1441 device_pm_init(dev);
1442 set_dev_node(dev, -1);
1443 #ifdef CONFIG_GENERIC_MSI_IRQ
1444 INIT_LIST_HEAD(&dev->msi_list);
1445 #endif
1446 INIT_LIST_HEAD(&dev->links.consumers);
1447 INIT_LIST_HEAD(&dev->links.suppliers);
1448 dev->links.status = DL_DEV_NO_DRIVER;
1450 EXPORT_SYMBOL_GPL(device_initialize);
1452 struct kobject *virtual_device_parent(struct device *dev)
1454 static struct kobject *virtual_dir = NULL;
1456 if (!virtual_dir)
1457 virtual_dir = kobject_create_and_add("virtual",
1458 &devices_kset->kobj);
1460 return virtual_dir;
1463 struct class_dir {
1464 struct kobject kobj;
1465 struct class *class;
1468 #define to_class_dir(obj) container_of(obj, struct class_dir, kobj)
1470 static void class_dir_release(struct kobject *kobj)
1472 struct class_dir *dir = to_class_dir(kobj);
1473 kfree(dir);
1476 static const
1477 struct kobj_ns_type_operations *class_dir_child_ns_type(struct kobject *kobj)
1479 struct class_dir *dir = to_class_dir(kobj);
1480 return dir->class->ns_type;
1483 static struct kobj_type class_dir_ktype = {
1484 .release = class_dir_release,
1485 .sysfs_ops = &kobj_sysfs_ops,
1486 .child_ns_type = class_dir_child_ns_type
1489 static struct kobject *
1490 class_dir_create_and_add(struct class *class, struct kobject *parent_kobj)
1492 struct class_dir *dir;
1493 int retval;
1495 dir = kzalloc(sizeof(*dir), GFP_KERNEL);
1496 if (!dir)
1497 return ERR_PTR(-ENOMEM);
1499 dir->class = class;
1500 kobject_init(&dir->kobj, &class_dir_ktype);
1502 dir->kobj.kset = &class->p->glue_dirs;
1504 retval = kobject_add(&dir->kobj, parent_kobj, "%s", class->name);
1505 if (retval < 0) {
1506 kobject_put(&dir->kobj);
1507 return ERR_PTR(retval);
1509 return &dir->kobj;
1512 static DEFINE_MUTEX(gdp_mutex);
1514 static struct kobject *get_device_parent(struct device *dev,
1515 struct device *parent)
1517 if (dev->class) {
1518 struct kobject *kobj = NULL;
1519 struct kobject *parent_kobj;
1520 struct kobject *k;
1522 #ifdef CONFIG_BLOCK
1523 /* block disks show up in /sys/block */
1524 if (sysfs_deprecated && dev->class == &block_class) {
1525 if (parent && parent->class == &block_class)
1526 return &parent->kobj;
1527 return &block_class.p->subsys.kobj;
1529 #endif
1532 * If we have no parent, we live in "virtual".
1533 * Class-devices with a non class-device as parent, live
1534 * in a "glue" directory to prevent namespace collisions.
1536 if (parent == NULL)
1537 parent_kobj = virtual_device_parent(dev);
1538 else if (parent->class && !dev->class->ns_type)
1539 return &parent->kobj;
1540 else
1541 parent_kobj = &parent->kobj;
1543 mutex_lock(&gdp_mutex);
1545 /* find our class-directory at the parent and reference it */
1546 spin_lock(&dev->class->p->glue_dirs.list_lock);
1547 list_for_each_entry(k, &dev->class->p->glue_dirs.list, entry)
1548 if (k->parent == parent_kobj) {
1549 kobj = kobject_get(k);
1550 break;
1552 spin_unlock(&dev->class->p->glue_dirs.list_lock);
1553 if (kobj) {
1554 mutex_unlock(&gdp_mutex);
1555 return kobj;
1558 /* or create a new class-directory at the parent device */
1559 k = class_dir_create_and_add(dev->class, parent_kobj);
1560 /* do not emit an uevent for this simple "glue" directory */
1561 mutex_unlock(&gdp_mutex);
1562 return k;
1565 /* subsystems can specify a default root directory for their devices */
1566 if (!parent && dev->bus && dev->bus->dev_root)
1567 return &dev->bus->dev_root->kobj;
1569 if (parent)
1570 return &parent->kobj;
1571 return NULL;
1574 static inline bool live_in_glue_dir(struct kobject *kobj,
1575 struct device *dev)
1577 if (!kobj || !dev->class ||
1578 kobj->kset != &dev->class->p->glue_dirs)
1579 return false;
1580 return true;
1583 static inline struct kobject *get_glue_dir(struct device *dev)
1585 return dev->kobj.parent;
1589 * make sure cleaning up dir as the last step, we need to make
1590 * sure .release handler of kobject is run with holding the
1591 * global lock
1593 static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir)
1595 /* see if we live in a "glue" directory */
1596 if (!live_in_glue_dir(glue_dir, dev))
1597 return;
1599 mutex_lock(&gdp_mutex);
1600 if (!kobject_has_children(glue_dir))
1601 kobject_del(glue_dir);
1602 kobject_put(glue_dir);
1603 mutex_unlock(&gdp_mutex);
1606 static int device_add_class_symlinks(struct device *dev)
1608 struct device_node *of_node = dev_of_node(dev);
1609 int error;
1611 if (of_node) {
1612 error = sysfs_create_link(&dev->kobj, of_node_kobj(of_node), "of_node");
1613 if (error)
1614 dev_warn(dev, "Error %d creating of_node link\n",error);
1615 /* An error here doesn't warrant bringing down the device */
1618 if (!dev->class)
1619 return 0;
1621 error = sysfs_create_link(&dev->kobj,
1622 &dev->class->p->subsys.kobj,
1623 "subsystem");
1624 if (error)
1625 goto out_devnode;
1627 if (dev->parent && device_is_not_partition(dev)) {
1628 error = sysfs_create_link(&dev->kobj, &dev->parent->kobj,
1629 "device");
1630 if (error)
1631 goto out_subsys;
1634 #ifdef CONFIG_BLOCK
1635 /* /sys/block has directories and does not need symlinks */
1636 if (sysfs_deprecated && dev->class == &block_class)
1637 return 0;
1638 #endif
1640 /* link in the class directory pointing to the device */
1641 error = sysfs_create_link(&dev->class->p->subsys.kobj,
1642 &dev->kobj, dev_name(dev));
1643 if (error)
1644 goto out_device;
1646 return 0;
1648 out_device:
1649 sysfs_remove_link(&dev->kobj, "device");
1651 out_subsys:
1652 sysfs_remove_link(&dev->kobj, "subsystem");
1653 out_devnode:
1654 sysfs_remove_link(&dev->kobj, "of_node");
1655 return error;
1658 static void device_remove_class_symlinks(struct device *dev)
1660 if (dev_of_node(dev))
1661 sysfs_remove_link(&dev->kobj, "of_node");
1663 if (!dev->class)
1664 return;
1666 if (dev->parent && device_is_not_partition(dev))
1667 sysfs_remove_link(&dev->kobj, "device");
1668 sysfs_remove_link(&dev->kobj, "subsystem");
1669 #ifdef CONFIG_BLOCK
1670 if (sysfs_deprecated && dev->class == &block_class)
1671 return;
1672 #endif
1673 sysfs_delete_link(&dev->class->p->subsys.kobj, &dev->kobj, dev_name(dev));
1677 * dev_set_name - set a device name
1678 * @dev: device
1679 * @fmt: format string for the device's name
1681 int dev_set_name(struct device *dev, const char *fmt, ...)
1683 va_list vargs;
1684 int err;
1686 va_start(vargs, fmt);
1687 err = kobject_set_name_vargs(&dev->kobj, fmt, vargs);
1688 va_end(vargs);
1689 return err;
1691 EXPORT_SYMBOL_GPL(dev_set_name);
1694 * device_to_dev_kobj - select a /sys/dev/ directory for the device
1695 * @dev: device
1697 * By default we select char/ for new entries. Setting class->dev_obj
1698 * to NULL prevents an entry from being created. class->dev_kobj must
1699 * be set (or cleared) before any devices are registered to the class
1700 * otherwise device_create_sys_dev_entry() and
1701 * device_remove_sys_dev_entry() will disagree about the presence of
1702 * the link.
1704 static struct kobject *device_to_dev_kobj(struct device *dev)
1706 struct kobject *kobj;
1708 if (dev->class)
1709 kobj = dev->class->dev_kobj;
1710 else
1711 kobj = sysfs_dev_char_kobj;
1713 return kobj;
1716 static int device_create_sys_dev_entry(struct device *dev)
1718 struct kobject *kobj = device_to_dev_kobj(dev);
1719 int error = 0;
1720 char devt_str[15];
1722 if (kobj) {
1723 format_dev_t(devt_str, dev->devt);
1724 error = sysfs_create_link(kobj, &dev->kobj, devt_str);
1727 return error;
1730 static void device_remove_sys_dev_entry(struct device *dev)
1732 struct kobject *kobj = device_to_dev_kobj(dev);
1733 char devt_str[15];
1735 if (kobj) {
1736 format_dev_t(devt_str, dev->devt);
1737 sysfs_remove_link(kobj, devt_str);
1741 static int device_private_init(struct device *dev)
1743 dev->p = kzalloc(sizeof(*dev->p), GFP_KERNEL);
1744 if (!dev->p)
1745 return -ENOMEM;
1746 dev->p->device = dev;
1747 klist_init(&dev->p->klist_children, klist_children_get,
1748 klist_children_put);
1749 INIT_LIST_HEAD(&dev->p->deferred_probe);
1750 return 0;
1754 * device_add - add device to device hierarchy.
1755 * @dev: device.
1757 * This is part 2 of device_register(), though may be called
1758 * separately _iff_ device_initialize() has been called separately.
1760 * This adds @dev to the kobject hierarchy via kobject_add(), adds it
1761 * to the global and sibling lists for the device, then
1762 * adds it to the other relevant subsystems of the driver model.
1764 * Do not call this routine or device_register() more than once for
1765 * any device structure. The driver model core is not designed to work
1766 * with devices that get unregistered and then spring back to life.
1767 * (Among other things, it's very hard to guarantee that all references
1768 * to the previous incarnation of @dev have been dropped.) Allocate
1769 * and register a fresh new struct device instead.
1771 * NOTE: _Never_ directly free @dev after calling this function, even
1772 * if it returned an error! Always use put_device() to give up your
1773 * reference instead.
1775 int device_add(struct device *dev)
1777 struct device *parent;
1778 struct kobject *kobj;
1779 struct class_interface *class_intf;
1780 int error = -EINVAL;
1781 struct kobject *glue_dir = NULL;
1783 dev = get_device(dev);
1784 if (!dev)
1785 goto done;
1787 if (!dev->p) {
1788 error = device_private_init(dev);
1789 if (error)
1790 goto done;
1794 * for statically allocated devices, which should all be converted
1795 * some day, we need to initialize the name. We prevent reading back
1796 * the name, and force the use of dev_name()
1798 if (dev->init_name) {
1799 dev_set_name(dev, "%s", dev->init_name);
1800 dev->init_name = NULL;
1803 /* subsystems can specify simple device enumeration */
1804 if (!dev_name(dev) && dev->bus && dev->bus->dev_name)
1805 dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
1807 if (!dev_name(dev)) {
1808 error = -EINVAL;
1809 goto name_error;
1812 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
1814 parent = get_device(dev->parent);
1815 kobj = get_device_parent(dev, parent);
1816 if (IS_ERR(kobj)) {
1817 error = PTR_ERR(kobj);
1818 goto parent_error;
1820 if (kobj)
1821 dev->kobj.parent = kobj;
1823 /* use parent numa_node */
1824 if (parent && (dev_to_node(dev) == NUMA_NO_NODE))
1825 set_dev_node(dev, dev_to_node(parent));
1827 /* first, register with generic layer. */
1828 /* we require the name to be set before, and pass NULL */
1829 error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
1830 if (error) {
1831 glue_dir = get_glue_dir(dev);
1832 goto Error;
1835 /* notify platform of device entry */
1836 if (platform_notify)
1837 platform_notify(dev);
1839 error = device_create_file(dev, &dev_attr_uevent);
1840 if (error)
1841 goto attrError;
1843 error = device_add_class_symlinks(dev);
1844 if (error)
1845 goto SymlinkError;
1846 error = device_add_attrs(dev);
1847 if (error)
1848 goto AttrsError;
1849 error = bus_add_device(dev);
1850 if (error)
1851 goto BusError;
1852 error = dpm_sysfs_add(dev);
1853 if (error)
1854 goto DPMError;
1855 device_pm_add(dev);
1857 if (MAJOR(dev->devt)) {
1858 error = device_create_file(dev, &dev_attr_dev);
1859 if (error)
1860 goto DevAttrError;
1862 error = device_create_sys_dev_entry(dev);
1863 if (error)
1864 goto SysEntryError;
1866 devtmpfs_create_node(dev);
1869 /* Notify clients of device addition. This call must come
1870 * after dpm_sysfs_add() and before kobject_uevent().
1872 if (dev->bus)
1873 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
1874 BUS_NOTIFY_ADD_DEVICE, dev);
1876 kobject_uevent(&dev->kobj, KOBJ_ADD);
1877 bus_probe_device(dev);
1878 if (parent)
1879 klist_add_tail(&dev->p->knode_parent,
1880 &parent->p->klist_children);
1882 if (dev->class) {
1883 mutex_lock(&dev->class->p->mutex);
1884 /* tie the class to the device */
1885 klist_add_tail(&dev->knode_class,
1886 &dev->class->p->klist_devices);
1888 /* notify any interfaces that the device is here */
1889 list_for_each_entry(class_intf,
1890 &dev->class->p->interfaces, node)
1891 if (class_intf->add_dev)
1892 class_intf->add_dev(dev, class_intf);
1893 mutex_unlock(&dev->class->p->mutex);
1895 done:
1896 put_device(dev);
1897 return error;
1898 SysEntryError:
1899 if (MAJOR(dev->devt))
1900 device_remove_file(dev, &dev_attr_dev);
1901 DevAttrError:
1902 device_pm_remove(dev);
1903 dpm_sysfs_remove(dev);
1904 DPMError:
1905 bus_remove_device(dev);
1906 BusError:
1907 device_remove_attrs(dev);
1908 AttrsError:
1909 device_remove_class_symlinks(dev);
1910 SymlinkError:
1911 device_remove_file(dev, &dev_attr_uevent);
1912 attrError:
1913 kobject_uevent(&dev->kobj, KOBJ_REMOVE);
1914 glue_dir = get_glue_dir(dev);
1915 kobject_del(&dev->kobj);
1916 Error:
1917 cleanup_glue_dir(dev, glue_dir);
1918 parent_error:
1919 put_device(parent);
1920 name_error:
1921 kfree(dev->p);
1922 dev->p = NULL;
1923 goto done;
1925 EXPORT_SYMBOL_GPL(device_add);
1928 * device_register - register a device with the system.
1929 * @dev: pointer to the device structure
1931 * This happens in two clean steps - initialize the device
1932 * and add it to the system. The two steps can be called
1933 * separately, but this is the easiest and most common.
1934 * I.e. you should only call the two helpers separately if
1935 * have a clearly defined need to use and refcount the device
1936 * before it is added to the hierarchy.
1938 * For more information, see the kerneldoc for device_initialize()
1939 * and device_add().
1941 * NOTE: _Never_ directly free @dev after calling this function, even
1942 * if it returned an error! Always use put_device() to give up the
1943 * reference initialized in this function instead.
1945 int device_register(struct device *dev)
1947 device_initialize(dev);
1948 return device_add(dev);
1950 EXPORT_SYMBOL_GPL(device_register);
1953 * get_device - increment reference count for device.
1954 * @dev: device.
1956 * This simply forwards the call to kobject_get(), though
1957 * we do take care to provide for the case that we get a NULL
1958 * pointer passed in.
1960 struct device *get_device(struct device *dev)
1962 return dev ? kobj_to_dev(kobject_get(&dev->kobj)) : NULL;
1964 EXPORT_SYMBOL_GPL(get_device);
1967 * put_device - decrement reference count.
1968 * @dev: device in question.
1970 void put_device(struct device *dev)
1972 /* might_sleep(); */
1973 if (dev)
1974 kobject_put(&dev->kobj);
1976 EXPORT_SYMBOL_GPL(put_device);
1979 * device_del - delete device from system.
1980 * @dev: device.
1982 * This is the first part of the device unregistration
1983 * sequence. This removes the device from the lists we control
1984 * from here, has it removed from the other driver model
1985 * subsystems it was added to in device_add(), and removes it
1986 * from the kobject hierarchy.
1988 * NOTE: this should be called manually _iff_ device_add() was
1989 * also called manually.
1991 void device_del(struct device *dev)
1993 struct device *parent = dev->parent;
1994 struct kobject *glue_dir = NULL;
1995 struct class_interface *class_intf;
1997 /* Notify clients of device removal. This call must come
1998 * before dpm_sysfs_remove().
2000 if (dev->bus)
2001 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
2002 BUS_NOTIFY_DEL_DEVICE, dev);
2004 dpm_sysfs_remove(dev);
2005 if (parent)
2006 klist_del(&dev->p->knode_parent);
2007 if (MAJOR(dev->devt)) {
2008 devtmpfs_delete_node(dev);
2009 device_remove_sys_dev_entry(dev);
2010 device_remove_file(dev, &dev_attr_dev);
2012 if (dev->class) {
2013 device_remove_class_symlinks(dev);
2015 mutex_lock(&dev->class->p->mutex);
2016 /* notify any interfaces that the device is now gone */
2017 list_for_each_entry(class_intf,
2018 &dev->class->p->interfaces, node)
2019 if (class_intf->remove_dev)
2020 class_intf->remove_dev(dev, class_intf);
2021 /* remove the device from the class list */
2022 klist_del(&dev->knode_class);
2023 mutex_unlock(&dev->class->p->mutex);
2025 device_remove_file(dev, &dev_attr_uevent);
2026 device_remove_attrs(dev);
2027 bus_remove_device(dev);
2028 device_pm_remove(dev);
2029 driver_deferred_probe_del(dev);
2030 device_remove_properties(dev);
2031 device_links_purge(dev);
2033 /* Notify the platform of the removal, in case they
2034 * need to do anything...
2036 if (platform_notify_remove)
2037 platform_notify_remove(dev);
2038 if (dev->bus)
2039 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
2040 BUS_NOTIFY_REMOVED_DEVICE, dev);
2041 kobject_uevent(&dev->kobj, KOBJ_REMOVE);
2042 glue_dir = get_glue_dir(dev);
2043 kobject_del(&dev->kobj);
2044 cleanup_glue_dir(dev, glue_dir);
2045 put_device(parent);
2047 EXPORT_SYMBOL_GPL(device_del);
2050 * device_unregister - unregister device from system.
2051 * @dev: device going away.
2053 * We do this in two parts, like we do device_register(). First,
2054 * we remove it from all the subsystems with device_del(), then
2055 * we decrement the reference count via put_device(). If that
2056 * is the final reference count, the device will be cleaned up
2057 * via device_release() above. Otherwise, the structure will
2058 * stick around until the final reference to the device is dropped.
2060 void device_unregister(struct device *dev)
2062 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
2063 device_del(dev);
2064 put_device(dev);
2066 EXPORT_SYMBOL_GPL(device_unregister);
2068 static struct device *prev_device(struct klist_iter *i)
2070 struct klist_node *n = klist_prev(i);
2071 struct device *dev = NULL;
2072 struct device_private *p;
2074 if (n) {
2075 p = to_device_private_parent(n);
2076 dev = p->device;
2078 return dev;
2081 static struct device *next_device(struct klist_iter *i)
2083 struct klist_node *n = klist_next(i);
2084 struct device *dev = NULL;
2085 struct device_private *p;
2087 if (n) {
2088 p = to_device_private_parent(n);
2089 dev = p->device;
2091 return dev;
2095 * device_get_devnode - path of device node file
2096 * @dev: device
2097 * @mode: returned file access mode
2098 * @uid: returned file owner
2099 * @gid: returned file group
2100 * @tmp: possibly allocated string
2102 * Return the relative path of a possible device node.
2103 * Non-default names may need to allocate a memory to compose
2104 * a name. This memory is returned in tmp and needs to be
2105 * freed by the caller.
2107 const char *device_get_devnode(struct device *dev,
2108 umode_t *mode, kuid_t *uid, kgid_t *gid,
2109 const char **tmp)
2111 char *s;
2113 *tmp = NULL;
2115 /* the device type may provide a specific name */
2116 if (dev->type && dev->type->devnode)
2117 *tmp = dev->type->devnode(dev, mode, uid, gid);
2118 if (*tmp)
2119 return *tmp;
2121 /* the class may provide a specific name */
2122 if (dev->class && dev->class->devnode)
2123 *tmp = dev->class->devnode(dev, mode);
2124 if (*tmp)
2125 return *tmp;
2127 /* return name without allocation, tmp == NULL */
2128 if (strchr(dev_name(dev), '!') == NULL)
2129 return dev_name(dev);
2131 /* replace '!' in the name with '/' */
2132 s = kstrdup(dev_name(dev), GFP_KERNEL);
2133 if (!s)
2134 return NULL;
2135 strreplace(s, '!', '/');
2136 return *tmp = s;
2140 * device_for_each_child - device child iterator.
2141 * @parent: parent struct device.
2142 * @fn: function to be called for each device.
2143 * @data: data for the callback.
2145 * Iterate over @parent's child devices, and call @fn for each,
2146 * passing it @data.
2148 * We check the return of @fn each time. If it returns anything
2149 * other than 0, we break out and return that value.
2151 int device_for_each_child(struct device *parent, void *data,
2152 int (*fn)(struct device *dev, void *data))
2154 struct klist_iter i;
2155 struct device *child;
2156 int error = 0;
2158 if (!parent->p)
2159 return 0;
2161 klist_iter_init(&parent->p->klist_children, &i);
2162 while (!error && (child = next_device(&i)))
2163 error = fn(child, data);
2164 klist_iter_exit(&i);
2165 return error;
2167 EXPORT_SYMBOL_GPL(device_for_each_child);
2170 * device_for_each_child_reverse - device child iterator in reversed order.
2171 * @parent: parent struct device.
2172 * @fn: function to be called for each device.
2173 * @data: data for the callback.
2175 * Iterate over @parent's child devices, and call @fn for each,
2176 * passing it @data.
2178 * We check the return of @fn each time. If it returns anything
2179 * other than 0, we break out and return that value.
2181 int device_for_each_child_reverse(struct device *parent, void *data,
2182 int (*fn)(struct device *dev, void *data))
2184 struct klist_iter i;
2185 struct device *child;
2186 int error = 0;
2188 if (!parent->p)
2189 return 0;
2191 klist_iter_init(&parent->p->klist_children, &i);
2192 while ((child = prev_device(&i)) && !error)
2193 error = fn(child, data);
2194 klist_iter_exit(&i);
2195 return error;
2197 EXPORT_SYMBOL_GPL(device_for_each_child_reverse);
2200 * device_find_child - device iterator for locating a particular device.
2201 * @parent: parent struct device
2202 * @match: Callback function to check device
2203 * @data: Data to pass to match function
2205 * This is similar to the device_for_each_child() function above, but it
2206 * returns a reference to a device that is 'found' for later use, as
2207 * determined by the @match callback.
2209 * The callback should return 0 if the device doesn't match and non-zero
2210 * if it does. If the callback returns non-zero and a reference to the
2211 * current device can be obtained, this function will return to the caller
2212 * and not iterate over any more devices.
2214 * NOTE: you will need to drop the reference with put_device() after use.
2216 struct device *device_find_child(struct device *parent, void *data,
2217 int (*match)(struct device *dev, void *data))
2219 struct klist_iter i;
2220 struct device *child;
2222 if (!parent)
2223 return NULL;
2225 klist_iter_init(&parent->p->klist_children, &i);
2226 while ((child = next_device(&i)))
2227 if (match(child, data) && get_device(child))
2228 break;
2229 klist_iter_exit(&i);
2230 return child;
2232 EXPORT_SYMBOL_GPL(device_find_child);
2234 int __init devices_init(void)
2236 devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
2237 if (!devices_kset)
2238 return -ENOMEM;
2239 dev_kobj = kobject_create_and_add("dev", NULL);
2240 if (!dev_kobj)
2241 goto dev_kobj_err;
2242 sysfs_dev_block_kobj = kobject_create_and_add("block", dev_kobj);
2243 if (!sysfs_dev_block_kobj)
2244 goto block_kobj_err;
2245 sysfs_dev_char_kobj = kobject_create_and_add("char", dev_kobj);
2246 if (!sysfs_dev_char_kobj)
2247 goto char_kobj_err;
2249 return 0;
2251 char_kobj_err:
2252 kobject_put(sysfs_dev_block_kobj);
2253 block_kobj_err:
2254 kobject_put(dev_kobj);
2255 dev_kobj_err:
2256 kset_unregister(devices_kset);
2257 return -ENOMEM;
2260 static int device_check_offline(struct device *dev, void *not_used)
2262 int ret;
2264 ret = device_for_each_child(dev, NULL, device_check_offline);
2265 if (ret)
2266 return ret;
2268 return device_supports_offline(dev) && !dev->offline ? -EBUSY : 0;
2272 * device_offline - Prepare the device for hot-removal.
2273 * @dev: Device to be put offline.
2275 * Execute the device bus type's .offline() callback, if present, to prepare
2276 * the device for a subsequent hot-removal. If that succeeds, the device must
2277 * not be used until either it is removed or its bus type's .online() callback
2278 * is executed.
2280 * Call under device_hotplug_lock.
2282 int device_offline(struct device *dev)
2284 int ret;
2286 if (dev->offline_disabled)
2287 return -EPERM;
2289 ret = device_for_each_child(dev, NULL, device_check_offline);
2290 if (ret)
2291 return ret;
2293 device_lock(dev);
2294 if (device_supports_offline(dev)) {
2295 if (dev->offline) {
2296 ret = 1;
2297 } else {
2298 ret = dev->bus->offline(dev);
2299 if (!ret) {
2300 kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
2301 dev->offline = true;
2305 device_unlock(dev);
2307 return ret;
2311 * device_online - Put the device back online after successful device_offline().
2312 * @dev: Device to be put back online.
2314 * If device_offline() has been successfully executed for @dev, but the device
2315 * has not been removed subsequently, execute its bus type's .online() callback
2316 * to indicate that the device can be used again.
2318 * Call under device_hotplug_lock.
2320 int device_online(struct device *dev)
2322 int ret = 0;
2324 device_lock(dev);
2325 if (device_supports_offline(dev)) {
2326 if (dev->offline) {
2327 ret = dev->bus->online(dev);
2328 if (!ret) {
2329 kobject_uevent(&dev->kobj, KOBJ_ONLINE);
2330 dev->offline = false;
2332 } else {
2333 ret = 1;
2336 device_unlock(dev);
2338 return ret;
2341 struct root_device {
2342 struct device dev;
2343 struct module *owner;
2346 static inline struct root_device *to_root_device(struct device *d)
2348 return container_of(d, struct root_device, dev);
2351 static void root_device_release(struct device *dev)
2353 kfree(to_root_device(dev));
2357 * __root_device_register - allocate and register a root device
2358 * @name: root device name
2359 * @owner: owner module of the root device, usually THIS_MODULE
2361 * This function allocates a root device and registers it
2362 * using device_register(). In order to free the returned
2363 * device, use root_device_unregister().
2365 * Root devices are dummy devices which allow other devices
2366 * to be grouped under /sys/devices. Use this function to
2367 * allocate a root device and then use it as the parent of
2368 * any device which should appear under /sys/devices/{name}
2370 * The /sys/devices/{name} directory will also contain a
2371 * 'module' symlink which points to the @owner directory
2372 * in sysfs.
2374 * Returns &struct device pointer on success, or ERR_PTR() on error.
2376 * Note: You probably want to use root_device_register().
2378 struct device *__root_device_register(const char *name, struct module *owner)
2380 struct root_device *root;
2381 int err = -ENOMEM;
2383 root = kzalloc(sizeof(struct root_device), GFP_KERNEL);
2384 if (!root)
2385 return ERR_PTR(err);
2387 err = dev_set_name(&root->dev, "%s", name);
2388 if (err) {
2389 kfree(root);
2390 return ERR_PTR(err);
2393 root->dev.release = root_device_release;
2395 err = device_register(&root->dev);
2396 if (err) {
2397 put_device(&root->dev);
2398 return ERR_PTR(err);
2401 #ifdef CONFIG_MODULES /* gotta find a "cleaner" way to do this */
2402 if (owner) {
2403 struct module_kobject *mk = &owner->mkobj;
2405 err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module");
2406 if (err) {
2407 device_unregister(&root->dev);
2408 return ERR_PTR(err);
2410 root->owner = owner;
2412 #endif
2414 return &root->dev;
2416 EXPORT_SYMBOL_GPL(__root_device_register);
2419 * root_device_unregister - unregister and free a root device
2420 * @dev: device going away
2422 * This function unregisters and cleans up a device that was created by
2423 * root_device_register().
2425 void root_device_unregister(struct device *dev)
2427 struct root_device *root = to_root_device(dev);
2429 if (root->owner)
2430 sysfs_remove_link(&root->dev.kobj, "module");
2432 device_unregister(dev);
2434 EXPORT_SYMBOL_GPL(root_device_unregister);
2437 static void device_create_release(struct device *dev)
2439 pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
2440 kfree(dev);
2443 static __printf(6, 0) struct device *
2444 device_create_groups_vargs(struct class *class, struct device *parent,
2445 dev_t devt, void *drvdata,
2446 const struct attribute_group **groups,
2447 const char *fmt, va_list args)
2449 struct device *dev = NULL;
2450 int retval = -ENODEV;
2452 if (class == NULL || IS_ERR(class))
2453 goto error;
2455 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2456 if (!dev) {
2457 retval = -ENOMEM;
2458 goto error;
2461 device_initialize(dev);
2462 dev->devt = devt;
2463 dev->class = class;
2464 dev->parent = parent;
2465 dev->groups = groups;
2466 dev->release = device_create_release;
2467 dev_set_drvdata(dev, drvdata);
2469 retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
2470 if (retval)
2471 goto error;
2473 retval = device_add(dev);
2474 if (retval)
2475 goto error;
2477 return dev;
2479 error:
2480 put_device(dev);
2481 return ERR_PTR(retval);
2485 * device_create_vargs - creates a device and registers it with sysfs
2486 * @class: pointer to the struct class that this device should be registered to
2487 * @parent: pointer to the parent struct device of this new device, if any
2488 * @devt: the dev_t for the char device to be added
2489 * @drvdata: the data to be added to the device for callbacks
2490 * @fmt: string for the device's name
2491 * @args: va_list for the device's name
2493 * This function can be used by char device classes. A struct device
2494 * will be created in sysfs, registered to the specified class.
2496 * A "dev" file will be created, showing the dev_t for the device, if
2497 * the dev_t is not 0,0.
2498 * If a pointer to a parent struct device is passed in, the newly created
2499 * struct device will be a child of that device in sysfs.
2500 * The pointer to the struct device will be returned from the call.
2501 * Any further sysfs files that might be required can be created using this
2502 * pointer.
2504 * Returns &struct device pointer on success, or ERR_PTR() on error.
2506 * Note: the struct class passed to this function must have previously
2507 * been created with a call to class_create().
2509 struct device *device_create_vargs(struct class *class, struct device *parent,
2510 dev_t devt, void *drvdata, const char *fmt,
2511 va_list args)
2513 return device_create_groups_vargs(class, parent, devt, drvdata, NULL,
2514 fmt, args);
2516 EXPORT_SYMBOL_GPL(device_create_vargs);
2519 * device_create - creates a device and registers it with sysfs
2520 * @class: pointer to the struct class that this device should be registered to
2521 * @parent: pointer to the parent struct device of this new device, if any
2522 * @devt: the dev_t for the char device to be added
2523 * @drvdata: the data to be added to the device for callbacks
2524 * @fmt: string for the device's name
2526 * This function can be used by char device classes. A struct device
2527 * will be created in sysfs, registered to the specified class.
2529 * A "dev" file will be created, showing the dev_t for the device, if
2530 * the dev_t is not 0,0.
2531 * If a pointer to a parent struct device is passed in, the newly created
2532 * struct device will be a child of that device in sysfs.
2533 * The pointer to the struct device will be returned from the call.
2534 * Any further sysfs files that might be required can be created using this
2535 * pointer.
2537 * Returns &struct device pointer on success, or ERR_PTR() on error.
2539 * Note: the struct class passed to this function must have previously
2540 * been created with a call to class_create().
2542 struct device *device_create(struct class *class, struct device *parent,
2543 dev_t devt, void *drvdata, const char *fmt, ...)
2545 va_list vargs;
2546 struct device *dev;
2548 va_start(vargs, fmt);
2549 dev = device_create_vargs(class, parent, devt, drvdata, fmt, vargs);
2550 va_end(vargs);
2551 return dev;
2553 EXPORT_SYMBOL_GPL(device_create);
2556 * device_create_with_groups - creates a device and registers it with sysfs
2557 * @class: pointer to the struct class that this device should be registered to
2558 * @parent: pointer to the parent struct device of this new device, if any
2559 * @devt: the dev_t for the char device to be added
2560 * @drvdata: the data to be added to the device for callbacks
2561 * @groups: NULL-terminated list of attribute groups to be created
2562 * @fmt: string for the device's name
2564 * This function can be used by char device classes. A struct device
2565 * will be created in sysfs, registered to the specified class.
2566 * Additional attributes specified in the groups parameter will also
2567 * be created automatically.
2569 * A "dev" file will be created, showing the dev_t for the device, if
2570 * the dev_t is not 0,0.
2571 * If a pointer to a parent struct device is passed in, the newly created
2572 * struct device will be a child of that device in sysfs.
2573 * The pointer to the struct device will be returned from the call.
2574 * Any further sysfs files that might be required can be created using this
2575 * pointer.
2577 * Returns &struct device pointer on success, or ERR_PTR() on error.
2579 * Note: the struct class passed to this function must have previously
2580 * been created with a call to class_create().
2582 struct device *device_create_with_groups(struct class *class,
2583 struct device *parent, dev_t devt,
2584 void *drvdata,
2585 const struct attribute_group **groups,
2586 const char *fmt, ...)
2588 va_list vargs;
2589 struct device *dev;
2591 va_start(vargs, fmt);
2592 dev = device_create_groups_vargs(class, parent, devt, drvdata, groups,
2593 fmt, vargs);
2594 va_end(vargs);
2595 return dev;
2597 EXPORT_SYMBOL_GPL(device_create_with_groups);
2599 static int __match_devt(struct device *dev, const void *data)
2601 const dev_t *devt = data;
2603 return dev->devt == *devt;
2607 * device_destroy - removes a device that was created with device_create()
2608 * @class: pointer to the struct class that this device was registered with
2609 * @devt: the dev_t of the device that was previously registered
2611 * This call unregisters and cleans up a device that was created with a
2612 * call to device_create().
2614 void device_destroy(struct class *class, dev_t devt)
2616 struct device *dev;
2618 dev = class_find_device(class, NULL, &devt, __match_devt);
2619 if (dev) {
2620 put_device(dev);
2621 device_unregister(dev);
2624 EXPORT_SYMBOL_GPL(device_destroy);
2627 * device_rename - renames a device
2628 * @dev: the pointer to the struct device to be renamed
2629 * @new_name: the new name of the device
2631 * It is the responsibility of the caller to provide mutual
2632 * exclusion between two different calls of device_rename
2633 * on the same device to ensure that new_name is valid and
2634 * won't conflict with other devices.
2636 * Note: Don't call this function. Currently, the networking layer calls this
2637 * function, but that will change. The following text from Kay Sievers offers
2638 * some insight:
2640 * Renaming devices is racy at many levels, symlinks and other stuff are not
2641 * replaced atomically, and you get a "move" uevent, but it's not easy to
2642 * connect the event to the old and new device. Device nodes are not renamed at
2643 * all, there isn't even support for that in the kernel now.
2645 * In the meantime, during renaming, your target name might be taken by another
2646 * driver, creating conflicts. Or the old name is taken directly after you
2647 * renamed it -- then you get events for the same DEVPATH, before you even see
2648 * the "move" event. It's just a mess, and nothing new should ever rely on
2649 * kernel device renaming. Besides that, it's not even implemented now for
2650 * other things than (driver-core wise very simple) network devices.
2652 * We are currently about to change network renaming in udev to completely
2653 * disallow renaming of devices in the same namespace as the kernel uses,
2654 * because we can't solve the problems properly, that arise with swapping names
2655 * of multiple interfaces without races. Means, renaming of eth[0-9]* will only
2656 * be allowed to some other name than eth[0-9]*, for the aforementioned
2657 * reasons.
2659 * Make up a "real" name in the driver before you register anything, or add
2660 * some other attributes for userspace to find the device, or use udev to add
2661 * symlinks -- but never rename kernel devices later, it's a complete mess. We
2662 * don't even want to get into that and try to implement the missing pieces in
2663 * the core. We really have other pieces to fix in the driver core mess. :)
2665 int device_rename(struct device *dev, const char *new_name)
2667 struct kobject *kobj = &dev->kobj;
2668 char *old_device_name = NULL;
2669 int error;
2671 dev = get_device(dev);
2672 if (!dev)
2673 return -EINVAL;
2675 dev_dbg(dev, "renaming to %s\n", new_name);
2677 old_device_name = kstrdup(dev_name(dev), GFP_KERNEL);
2678 if (!old_device_name) {
2679 error = -ENOMEM;
2680 goto out;
2683 if (dev->class) {
2684 error = sysfs_rename_link_ns(&dev->class->p->subsys.kobj,
2685 kobj, old_device_name,
2686 new_name, kobject_namespace(kobj));
2687 if (error)
2688 goto out;
2691 error = kobject_rename(kobj, new_name);
2692 if (error)
2693 goto out;
2695 out:
2696 put_device(dev);
2698 kfree(old_device_name);
2700 return error;
2702 EXPORT_SYMBOL_GPL(device_rename);
2704 static int device_move_class_links(struct device *dev,
2705 struct device *old_parent,
2706 struct device *new_parent)
2708 int error = 0;
2710 if (old_parent)
2711 sysfs_remove_link(&dev->kobj, "device");
2712 if (new_parent)
2713 error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
2714 "device");
2715 return error;
2719 * device_move - moves a device to a new parent
2720 * @dev: the pointer to the struct device to be moved
2721 * @new_parent: the new parent of the device (can be NULL)
2722 * @dpm_order: how to reorder the dpm_list
2724 int device_move(struct device *dev, struct device *new_parent,
2725 enum dpm_order dpm_order)
2727 int error;
2728 struct device *old_parent;
2729 struct kobject *new_parent_kobj;
2731 dev = get_device(dev);
2732 if (!dev)
2733 return -EINVAL;
2735 device_pm_lock();
2736 new_parent = get_device(new_parent);
2737 new_parent_kobj = get_device_parent(dev, new_parent);
2738 if (IS_ERR(new_parent_kobj)) {
2739 error = PTR_ERR(new_parent_kobj);
2740 put_device(new_parent);
2741 goto out;
2744 pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev),
2745 __func__, new_parent ? dev_name(new_parent) : "<NULL>");
2746 error = kobject_move(&dev->kobj, new_parent_kobj);
2747 if (error) {
2748 cleanup_glue_dir(dev, new_parent_kobj);
2749 put_device(new_parent);
2750 goto out;
2752 old_parent = dev->parent;
2753 dev->parent = new_parent;
2754 if (old_parent)
2755 klist_remove(&dev->p->knode_parent);
2756 if (new_parent) {
2757 klist_add_tail(&dev->p->knode_parent,
2758 &new_parent->p->klist_children);
2759 set_dev_node(dev, dev_to_node(new_parent));
2762 if (dev->class) {
2763 error = device_move_class_links(dev, old_parent, new_parent);
2764 if (error) {
2765 /* We ignore errors on cleanup since we're hosed anyway... */
2766 device_move_class_links(dev, new_parent, old_parent);
2767 if (!kobject_move(&dev->kobj, &old_parent->kobj)) {
2768 if (new_parent)
2769 klist_remove(&dev->p->knode_parent);
2770 dev->parent = old_parent;
2771 if (old_parent) {
2772 klist_add_tail(&dev->p->knode_parent,
2773 &old_parent->p->klist_children);
2774 set_dev_node(dev, dev_to_node(old_parent));
2777 cleanup_glue_dir(dev, new_parent_kobj);
2778 put_device(new_parent);
2779 goto out;
2782 switch (dpm_order) {
2783 case DPM_ORDER_NONE:
2784 break;
2785 case DPM_ORDER_DEV_AFTER_PARENT:
2786 device_pm_move_after(dev, new_parent);
2787 devices_kset_move_after(dev, new_parent);
2788 break;
2789 case DPM_ORDER_PARENT_BEFORE_DEV:
2790 device_pm_move_before(new_parent, dev);
2791 devices_kset_move_before(new_parent, dev);
2792 break;
2793 case DPM_ORDER_DEV_LAST:
2794 device_pm_move_last(dev);
2795 devices_kset_move_last(dev);
2796 break;
2799 put_device(old_parent);
2800 out:
2801 device_pm_unlock();
2802 put_device(dev);
2803 return error;
2805 EXPORT_SYMBOL_GPL(device_move);
2808 * device_shutdown - call ->shutdown() on each device to shutdown.
2810 void device_shutdown(void)
2812 struct device *dev, *parent;
2814 wait_for_device_probe();
2815 device_block_probing();
2817 spin_lock(&devices_kset->list_lock);
2819 * Walk the devices list backward, shutting down each in turn.
2820 * Beware that device unplug events may also start pulling
2821 * devices offline, even as the system is shutting down.
2823 while (!list_empty(&devices_kset->list)) {
2824 dev = list_entry(devices_kset->list.prev, struct device,
2825 kobj.entry);
2828 * hold reference count of device's parent to
2829 * prevent it from being freed because parent's
2830 * lock is to be held
2832 parent = get_device(dev->parent);
2833 get_device(dev);
2835 * Make sure the device is off the kset list, in the
2836 * event that dev->*->shutdown() doesn't remove it.
2838 list_del_init(&dev->kobj.entry);
2839 spin_unlock(&devices_kset->list_lock);
2841 /* hold lock to avoid race with probe/release */
2842 if (parent)
2843 device_lock(parent);
2844 device_lock(dev);
2846 /* Don't allow any more runtime suspends */
2847 pm_runtime_get_noresume(dev);
2848 pm_runtime_barrier(dev);
2850 if (dev->class && dev->class->shutdown_pre) {
2851 if (initcall_debug)
2852 dev_info(dev, "shutdown_pre\n");
2853 dev->class->shutdown_pre(dev);
2855 if (dev->bus && dev->bus->shutdown) {
2856 if (initcall_debug)
2857 dev_info(dev, "shutdown\n");
2858 dev->bus->shutdown(dev);
2859 } else if (dev->driver && dev->driver->shutdown) {
2860 if (initcall_debug)
2861 dev_info(dev, "shutdown\n");
2862 dev->driver->shutdown(dev);
2865 device_unlock(dev);
2866 if (parent)
2867 device_unlock(parent);
2869 put_device(dev);
2870 put_device(parent);
2872 spin_lock(&devices_kset->list_lock);
2874 spin_unlock(&devices_kset->list_lock);
2878 * Device logging functions
2881 #ifdef CONFIG_PRINTK
2882 static int
2883 create_syslog_header(const struct device *dev, char *hdr, size_t hdrlen)
2885 const char *subsys;
2886 size_t pos = 0;
2888 if (dev->class)
2889 subsys = dev->class->name;
2890 else if (dev->bus)
2891 subsys = dev->bus->name;
2892 else
2893 return 0;
2895 pos += snprintf(hdr + pos, hdrlen - pos, "SUBSYSTEM=%s", subsys);
2896 if (pos >= hdrlen)
2897 goto overflow;
2900 * Add device identifier DEVICE=:
2901 * b12:8 block dev_t
2902 * c127:3 char dev_t
2903 * n8 netdev ifindex
2904 * +sound:card0 subsystem:devname
2906 if (MAJOR(dev->devt)) {
2907 char c;
2909 if (strcmp(subsys, "block") == 0)
2910 c = 'b';
2911 else
2912 c = 'c';
2913 pos++;
2914 pos += snprintf(hdr + pos, hdrlen - pos,
2915 "DEVICE=%c%u:%u",
2916 c, MAJOR(dev->devt), MINOR(dev->devt));
2917 } else if (strcmp(subsys, "net") == 0) {
2918 struct net_device *net = to_net_dev(dev);
2920 pos++;
2921 pos += snprintf(hdr + pos, hdrlen - pos,
2922 "DEVICE=n%u", net->ifindex);
2923 } else {
2924 pos++;
2925 pos += snprintf(hdr + pos, hdrlen - pos,
2926 "DEVICE=+%s:%s", subsys, dev_name(dev));
2929 if (pos >= hdrlen)
2930 goto overflow;
2932 return pos;
2934 overflow:
2935 dev_WARN(dev, "device/subsystem name too long");
2936 return 0;
2939 int dev_vprintk_emit(int level, const struct device *dev,
2940 const char *fmt, va_list args)
2942 char hdr[128];
2943 size_t hdrlen;
2945 hdrlen = create_syslog_header(dev, hdr, sizeof(hdr));
2947 return vprintk_emit(0, level, hdrlen ? hdr : NULL, hdrlen, fmt, args);
2949 EXPORT_SYMBOL(dev_vprintk_emit);
2951 int dev_printk_emit(int level, const struct device *dev, const char *fmt, ...)
2953 va_list args;
2954 int r;
2956 va_start(args, fmt);
2958 r = dev_vprintk_emit(level, dev, fmt, args);
2960 va_end(args);
2962 return r;
2964 EXPORT_SYMBOL(dev_printk_emit);
2966 static void __dev_printk(const char *level, const struct device *dev,
2967 struct va_format *vaf)
2969 if (dev)
2970 dev_printk_emit(level[1] - '0', dev, "%s %s: %pV",
2971 dev_driver_string(dev), dev_name(dev), vaf);
2972 else
2973 printk("%s(NULL device *): %pV", level, vaf);
2976 void dev_printk(const char *level, const struct device *dev,
2977 const char *fmt, ...)
2979 struct va_format vaf;
2980 va_list args;
2982 va_start(args, fmt);
2984 vaf.fmt = fmt;
2985 vaf.va = &args;
2987 __dev_printk(level, dev, &vaf);
2989 va_end(args);
2991 EXPORT_SYMBOL(dev_printk);
2993 #define define_dev_printk_level(func, kern_level) \
2994 void func(const struct device *dev, const char *fmt, ...) \
2996 struct va_format vaf; \
2997 va_list args; \
2999 va_start(args, fmt); \
3001 vaf.fmt = fmt; \
3002 vaf.va = &args; \
3004 __dev_printk(kern_level, dev, &vaf); \
3006 va_end(args); \
3008 EXPORT_SYMBOL(func);
3010 define_dev_printk_level(_dev_emerg, KERN_EMERG);
3011 define_dev_printk_level(_dev_alert, KERN_ALERT);
3012 define_dev_printk_level(_dev_crit, KERN_CRIT);
3013 define_dev_printk_level(_dev_err, KERN_ERR);
3014 define_dev_printk_level(_dev_warn, KERN_WARNING);
3015 define_dev_printk_level(_dev_notice, KERN_NOTICE);
3016 define_dev_printk_level(_dev_info, KERN_INFO);
3018 #endif
3020 static inline bool fwnode_is_primary(struct fwnode_handle *fwnode)
3022 return fwnode && !IS_ERR(fwnode->secondary);
3026 * set_primary_fwnode - Change the primary firmware node of a given device.
3027 * @dev: Device to handle.
3028 * @fwnode: New primary firmware node of the device.
3030 * Set the device's firmware node pointer to @fwnode, but if a secondary
3031 * firmware node of the device is present, preserve it.
3033 void set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
3035 if (fwnode) {
3036 struct fwnode_handle *fn = dev->fwnode;
3038 if (fwnode_is_primary(fn))
3039 fn = fn->secondary;
3041 if (fn) {
3042 WARN_ON(fwnode->secondary);
3043 fwnode->secondary = fn;
3045 dev->fwnode = fwnode;
3046 } else {
3047 dev->fwnode = fwnode_is_primary(dev->fwnode) ?
3048 dev->fwnode->secondary : NULL;
3051 EXPORT_SYMBOL_GPL(set_primary_fwnode);
3054 * set_secondary_fwnode - Change the secondary firmware node of a given device.
3055 * @dev: Device to handle.
3056 * @fwnode: New secondary firmware node of the device.
3058 * If a primary firmware node of the device is present, set its secondary
3059 * pointer to @fwnode. Otherwise, set the device's firmware node pointer to
3060 * @fwnode.
3062 void set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
3064 if (fwnode)
3065 fwnode->secondary = ERR_PTR(-ENODEV);
3067 if (fwnode_is_primary(dev->fwnode))
3068 dev->fwnode->secondary = fwnode;
3069 else
3070 dev->fwnode = fwnode;
3074 * device_set_of_node_from_dev - reuse device-tree node of another device
3075 * @dev: device whose device-tree node is being set
3076 * @dev2: device whose device-tree node is being reused
3078 * Takes another reference to the new device-tree node after first dropping
3079 * any reference held to the old node.
3081 void device_set_of_node_from_dev(struct device *dev, const struct device *dev2)
3083 of_node_put(dev->of_node);
3084 dev->of_node = of_node_get(dev2->of_node);
3085 dev->of_node_reused = true;
3087 EXPORT_SYMBOL_GPL(device_set_of_node_from_dev);