ABI: sysfs-devices-system-cpu: remove a broken reference
[linux.git] / drivers / base / core.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * drivers/base/core.c - core driver model code (device registration, etc)
4  *
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  */
10
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>
28
29 #include "base.h"
30 #include "power/power.h"
31
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)
39 {
40         return kstrtol(arg, 10, &sysfs_deprecated);
41 }
42 early_param("sysfs.deprecated", sysfs_deprecated_setup);
43 #endif
44
45 /* Device links support. */
46
47 #ifdef CONFIG_SRCU
48 static DEFINE_MUTEX(device_links_lock);
49 DEFINE_STATIC_SRCU(device_links_srcu);
50
51 static inline void device_links_write_lock(void)
52 {
53         mutex_lock(&device_links_lock);
54 }
55
56 static inline void device_links_write_unlock(void)
57 {
58         mutex_unlock(&device_links_lock);
59 }
60
61 int device_links_read_lock(void)
62 {
63         return srcu_read_lock(&device_links_srcu);
64 }
65
66 void device_links_read_unlock(int idx)
67 {
68         srcu_read_unlock(&device_links_srcu, idx);
69 }
70 #else /* !CONFIG_SRCU */
71 static DECLARE_RWSEM(device_links_lock);
72
73 static inline void device_links_write_lock(void)
74 {
75         down_write(&device_links_lock);
76 }
77
78 static inline void device_links_write_unlock(void)
79 {
80         up_write(&device_links_lock);
81 }
82
83 int device_links_read_lock(void)
84 {
85         down_read(&device_links_lock);
86         return 0;
87 }
88
89 void device_links_read_unlock(int not_used)
90 {
91         up_read(&device_links_lock);
92 }
93 #endif /* !CONFIG_SRCU */
94
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.
99  *
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.
102  */
103 static int device_is_dependent(struct device *dev, void *target)
104 {
105         struct device_link *link;
106         int ret;
107
108         if (WARN_ON(dev == target))
109                 return 1;
110
111         ret = device_for_each_child(dev, target, device_is_dependent);
112         if (ret)
113                 return ret;
114
115         list_for_each_entry(link, &dev->links.consumers, s_node) {
116                 if (WARN_ON(link->consumer == target))
117                         return 1;
118
119                 ret = device_is_dependent(link->consumer, target);
120                 if (ret)
121                         break;
122         }
123         return ret;
124 }
125
126 static int device_reorder_to_tail(struct device *dev, void *not_used)
127 {
128         struct device_link *link;
129
130         /*
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.
133          */
134         if (device_is_registered(dev))
135                 devices_kset_move_last(dev);
136
137         if (device_pm_initialized(dev))
138                 device_pm_move_last(dev);
139
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);
143
144         return 0;
145 }
146
147 /**
148  * device_pm_move_to_tail - Move set of devices to the end of device lists
149  * @dev: Device to move
150  *
151  * This is a device_reorder_to_tail() wrapper taking the requisite locks.
152  *
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.
155  */
156 void device_pm_move_to_tail(struct device *dev)
157 {
158         int idx;
159
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);
165 }
166
167 /**
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.
172  *
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.
180  *
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.
185  *
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).
190  *
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.
194  */
195 struct device_link *device_link_add(struct device *consumer,
196                                     struct device *supplier, u32 flags)
197 {
198         struct device_link *link;
199
200         if (!consumer || !supplier ||
201             ((flags & DL_FLAG_STATELESS) && (flags & DL_FLAG_AUTOREMOVE)))
202                 return NULL;
203
204         device_links_write_lock();
205         device_pm_lock();
206
207         /*
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.
211          */
212         if (!device_pm_initialized(supplier)
213             || device_is_dependent(consumer, supplier)) {
214                 link = NULL;
215                 goto out;
216         }
217
218         list_for_each_entry(link, &supplier->links.consumers, s_node)
219                 if (link->consumer == consumer) {
220                         kref_get(&link->kref);
221                         goto out;
222                 }
223
224         link = kzalloc(sizeof(*link), GFP_KERNEL);
225         if (!link)
226                 goto out;
227
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;
235                         }
236                         link->rpm_active = true;
237                 }
238                 pm_runtime_new_link(consumer);
239         }
240         get_device(supplier);
241         link->supplier = supplier;
242         INIT_LIST_HEAD(&link->s_node);
243         get_device(consumer);
244         link->consumer = consumer;
245         INIT_LIST_HEAD(&link->c_node);
246         link->flags = flags;
247         kref_init(&link->kref);
248
249         /* Determine the initial link state. */
250         if (flags & DL_FLAG_STATELESS) {
251                 link->status = DL_STATE_NONE;
252         } else {
253                 switch (supplier->links.status) {
254                 case DL_DEV_DRIVER_BOUND:
255                         switch (consumer->links.status) {
256                         case DL_DEV_PROBING:
257                                 /*
258                                  * Balance the decrementation of the supplier's
259                                  * runtime PM usage counter after consumer probe
260                                  * in driver_probe_device().
261                                  */
262                                 if (flags & DL_FLAG_PM_RUNTIME)
263                                         pm_runtime_get_sync(supplier);
264
265                                 link->status = DL_STATE_CONSUMER_PROBE;
266                                 break;
267                         case DL_DEV_DRIVER_BOUND:
268                                 link->status = DL_STATE_ACTIVE;
269                                 break;
270                         default:
271                                 link->status = DL_STATE_AVAILABLE;
272                                 break;
273                         }
274                         break;
275                 case DL_DEV_UNBINDING:
276                         link->status = DL_STATE_SUPPLIER_UNBIND;
277                         break;
278                 default:
279                         link->status = DL_STATE_DORMANT;
280                         break;
281                 }
282         }
283
284         /*
285          * Move the consumer and all of the devices depending on it to the end
286          * of dpm_list and the devices_kset list.
287          *
288          * It is necessary to hold dpm_list locked throughout all that or else
289          * we may end up suspending with a wrong ordering of it.
290          */
291         device_reorder_to_tail(consumer, NULL);
292
293         list_add_tail_rcu(&link->s_node, &supplier->links.consumers);
294         list_add_tail_rcu(&link->c_node, &consumer->links.suppliers);
295
296         dev_info(consumer, "Linked as a consumer to %s\n", dev_name(supplier));
297
298  out:
299         device_pm_unlock();
300         device_links_write_unlock();
301         return link;
302 }
303 EXPORT_SYMBOL_GPL(device_link_add);
304
305 static void device_link_free(struct device_link *link)
306 {
307         put_device(link->consumer);
308         put_device(link->supplier);
309         kfree(link);
310 }
311
312 #ifdef CONFIG_SRCU
313 static void __device_link_free_srcu(struct rcu_head *rhead)
314 {
315         device_link_free(container_of(rhead, struct device_link, rcu_head));
316 }
317
318 static void __device_link_del(struct kref *kref)
319 {
320         struct device_link *link = container_of(kref, struct device_link, kref);
321
322         dev_info(link->consumer, "Dropping the link to %s\n",
323                  dev_name(link->supplier));
324
325         if (link->flags & DL_FLAG_PM_RUNTIME)
326                 pm_runtime_drop_link(link->consumer);
327
328         list_del_rcu(&link->s_node);
329         list_del_rcu(&link->c_node);
330         call_srcu(&device_links_srcu, &link->rcu_head, __device_link_free_srcu);
331 }
332 #else /* !CONFIG_SRCU */
333 static void __device_link_del(struct kref *kref)
334 {
335         struct device_link *link = container_of(kref, struct device_link, kref);
336
337         dev_info(link->consumer, "Dropping the link to %s\n",
338                  dev_name(link->supplier));
339
340         if (link->flags & DL_FLAG_PM_RUNTIME)
341                 pm_runtime_drop_link(link->consumer);
342
343         list_del(&link->s_node);
344         list_del(&link->c_node);
345         device_link_free(link);
346 }
347 #endif /* !CONFIG_SRCU */
348
349 /**
350  * device_link_del - Delete a link between two devices.
351  * @link: Device link to delete.
352  *
353  * The caller must ensure proper synchronization of this function with runtime
354  * PM.  If the link was added multiple times, it needs to be deleted as often.
355  * Care is required for hotplugged devices:  Their links are purged on removal
356  * and calling device_link_del() is then no longer allowed.
357  */
358 void device_link_del(struct device_link *link)
359 {
360         device_links_write_lock();
361         device_pm_lock();
362         kref_put(&link->kref, __device_link_del);
363         device_pm_unlock();
364         device_links_write_unlock();
365 }
366 EXPORT_SYMBOL_GPL(device_link_del);
367
368 static void device_links_missing_supplier(struct device *dev)
369 {
370         struct device_link *link;
371
372         list_for_each_entry(link, &dev->links.suppliers, c_node)
373                 if (link->status == DL_STATE_CONSUMER_PROBE)
374                         WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
375 }
376
377 /**
378  * device_links_check_suppliers - Check presence of supplier drivers.
379  * @dev: Consumer device.
380  *
381  * Check links from this device to any suppliers.  Walk the list of the device's
382  * links to suppliers and see if all of them are available.  If not, simply
383  * return -EPROBE_DEFER.
384  *
385  * We need to guarantee that the supplier will not go away after the check has
386  * been positive here.  It only can go away in __device_release_driver() and
387  * that function  checks the device's links to consumers.  This means we need to
388  * mark the link as "consumer probe in progress" to make the supplier removal
389  * wait for us to complete (or bad things may happen).
390  *
391  * Links with the DL_FLAG_STATELESS flag set are ignored.
392  */
393 int device_links_check_suppliers(struct device *dev)
394 {
395         struct device_link *link;
396         int ret = 0;
397
398         device_links_write_lock();
399
400         list_for_each_entry(link, &dev->links.suppliers, c_node) {
401                 if (link->flags & DL_FLAG_STATELESS)
402                         continue;
403
404                 if (link->status != DL_STATE_AVAILABLE) {
405                         device_links_missing_supplier(dev);
406                         ret = -EPROBE_DEFER;
407                         break;
408                 }
409                 WRITE_ONCE(link->status, DL_STATE_CONSUMER_PROBE);
410         }
411         dev->links.status = DL_DEV_PROBING;
412
413         device_links_write_unlock();
414         return ret;
415 }
416
417 /**
418  * device_links_driver_bound - Update device links after probing its driver.
419  * @dev: Device to update the links for.
420  *
421  * The probe has been successful, so update links from this device to any
422  * consumers by changing their status to "available".
423  *
424  * Also change the status of @dev's links to suppliers to "active".
425  *
426  * Links with the DL_FLAG_STATELESS flag set are ignored.
427  */
428 void device_links_driver_bound(struct device *dev)
429 {
430         struct device_link *link;
431
432         device_links_write_lock();
433
434         list_for_each_entry(link, &dev->links.consumers, s_node) {
435                 if (link->flags & DL_FLAG_STATELESS)
436                         continue;
437
438                 WARN_ON(link->status != DL_STATE_DORMANT);
439                 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
440         }
441
442         list_for_each_entry(link, &dev->links.suppliers, c_node) {
443                 if (link->flags & DL_FLAG_STATELESS)
444                         continue;
445
446                 WARN_ON(link->status != DL_STATE_CONSUMER_PROBE);
447                 WRITE_ONCE(link->status, DL_STATE_ACTIVE);
448         }
449
450         dev->links.status = DL_DEV_DRIVER_BOUND;
451
452         device_links_write_unlock();
453 }
454
455 /**
456  * __device_links_no_driver - Update links of a device without a driver.
457  * @dev: Device without a drvier.
458  *
459  * Delete all non-persistent links from this device to any suppliers.
460  *
461  * Persistent links stay around, but their status is changed to "available",
462  * unless they already are in the "supplier unbind in progress" state in which
463  * case they need not be updated.
464  *
465  * Links with the DL_FLAG_STATELESS flag set are ignored.
466  */
467 static void __device_links_no_driver(struct device *dev)
468 {
469         struct device_link *link, *ln;
470
471         list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
472                 if (link->flags & DL_FLAG_STATELESS)
473                         continue;
474
475                 if (link->flags & DL_FLAG_AUTOREMOVE)
476                         kref_put(&link->kref, __device_link_del);
477                 else if (link->status != DL_STATE_SUPPLIER_UNBIND)
478                         WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
479         }
480
481         dev->links.status = DL_DEV_NO_DRIVER;
482 }
483
484 void device_links_no_driver(struct device *dev)
485 {
486         device_links_write_lock();
487         __device_links_no_driver(dev);
488         device_links_write_unlock();
489 }
490
491 /**
492  * device_links_driver_cleanup - Update links after driver removal.
493  * @dev: Device whose driver has just gone away.
494  *
495  * Update links to consumers for @dev by changing their status to "dormant" and
496  * invoke %__device_links_no_driver() to update links to suppliers for it as
497  * appropriate.
498  *
499  * Links with the DL_FLAG_STATELESS flag set are ignored.
500  */
501 void device_links_driver_cleanup(struct device *dev)
502 {
503         struct device_link *link;
504
505         device_links_write_lock();
506
507         list_for_each_entry(link, &dev->links.consumers, s_node) {
508                 if (link->flags & DL_FLAG_STATELESS)
509                         continue;
510
511                 WARN_ON(link->flags & DL_FLAG_AUTOREMOVE);
512                 WARN_ON(link->status != DL_STATE_SUPPLIER_UNBIND);
513                 WRITE_ONCE(link->status, DL_STATE_DORMANT);
514         }
515
516         __device_links_no_driver(dev);
517
518         device_links_write_unlock();
519 }
520
521 /**
522  * device_links_busy - Check if there are any busy links to consumers.
523  * @dev: Device to check.
524  *
525  * Check each consumer of the device and return 'true' if its link's status
526  * is one of "consumer probe" or "active" (meaning that the given consumer is
527  * probing right now or its driver is present).  Otherwise, change the link
528  * state to "supplier unbind" to prevent the consumer from being probed
529  * successfully going forward.
530  *
531  * Return 'false' if there are no probing or active consumers.
532  *
533  * Links with the DL_FLAG_STATELESS flag set are ignored.
534  */
535 bool device_links_busy(struct device *dev)
536 {
537         struct device_link *link;
538         bool ret = false;
539
540         device_links_write_lock();
541
542         list_for_each_entry(link, &dev->links.consumers, s_node) {
543                 if (link->flags & DL_FLAG_STATELESS)
544                         continue;
545
546                 if (link->status == DL_STATE_CONSUMER_PROBE
547                     || link->status == DL_STATE_ACTIVE) {
548                         ret = true;
549                         break;
550                 }
551                 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
552         }
553
554         dev->links.status = DL_DEV_UNBINDING;
555
556         device_links_write_unlock();
557         return ret;
558 }
559
560 /**
561  * device_links_unbind_consumers - Force unbind consumers of the given device.
562  * @dev: Device to unbind the consumers of.
563  *
564  * Walk the list of links to consumers for @dev and if any of them is in the
565  * "consumer probe" state, wait for all device probes in progress to complete
566  * and start over.
567  *
568  * If that's not the case, change the status of the link to "supplier unbind"
569  * and check if the link was in the "active" state.  If so, force the consumer
570  * driver to unbind and start over (the consumer will not re-probe as we have
571  * changed the state of the link already).
572  *
573  * Links with the DL_FLAG_STATELESS flag set are ignored.
574  */
575 void device_links_unbind_consumers(struct device *dev)
576 {
577         struct device_link *link;
578
579  start:
580         device_links_write_lock();
581
582         list_for_each_entry(link, &dev->links.consumers, s_node) {
583                 enum device_link_state status;
584
585                 if (link->flags & DL_FLAG_STATELESS)
586                         continue;
587
588                 status = link->status;
589                 if (status == DL_STATE_CONSUMER_PROBE) {
590                         device_links_write_unlock();
591
592                         wait_for_device_probe();
593                         goto start;
594                 }
595                 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
596                 if (status == DL_STATE_ACTIVE) {
597                         struct device *consumer = link->consumer;
598
599                         get_device(consumer);
600
601                         device_links_write_unlock();
602
603                         device_release_driver_internal(consumer, NULL,
604                                                        consumer->parent);
605                         put_device(consumer);
606                         goto start;
607                 }
608         }
609
610         device_links_write_unlock();
611 }
612
613 /**
614  * device_links_purge - Delete existing links to other devices.
615  * @dev: Target device.
616  */
617 static void device_links_purge(struct device *dev)
618 {
619         struct device_link *link, *ln;
620
621         /*
622          * Delete all of the remaining links from this device to any other
623          * devices (either consumers or suppliers).
624          */
625         device_links_write_lock();
626
627         list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
628                 WARN_ON(link->status == DL_STATE_ACTIVE);
629                 __device_link_del(&link->kref);
630         }
631
632         list_for_each_entry_safe_reverse(link, ln, &dev->links.consumers, s_node) {
633                 WARN_ON(link->status != DL_STATE_DORMANT &&
634                         link->status != DL_STATE_NONE);
635                 __device_link_del(&link->kref);
636         }
637
638         device_links_write_unlock();
639 }
640
641 /* Device links support end. */
642
643 int (*platform_notify)(struct device *dev) = NULL;
644 int (*platform_notify_remove)(struct device *dev) = NULL;
645 static struct kobject *dev_kobj;
646 struct kobject *sysfs_dev_char_kobj;
647 struct kobject *sysfs_dev_block_kobj;
648
649 static DEFINE_MUTEX(device_hotplug_lock);
650
651 void lock_device_hotplug(void)
652 {
653         mutex_lock(&device_hotplug_lock);
654 }
655
656 void unlock_device_hotplug(void)
657 {
658         mutex_unlock(&device_hotplug_lock);
659 }
660
661 int lock_device_hotplug_sysfs(void)
662 {
663         if (mutex_trylock(&device_hotplug_lock))
664                 return 0;
665
666         /* Avoid busy looping (5 ms of sleep should do). */
667         msleep(5);
668         return restart_syscall();
669 }
670
671 #ifdef CONFIG_BLOCK
672 static inline int device_is_not_partition(struct device *dev)
673 {
674         return !(dev->type == &part_type);
675 }
676 #else
677 static inline int device_is_not_partition(struct device *dev)
678 {
679         return 1;
680 }
681 #endif
682
683 /**
684  * dev_driver_string - Return a device's driver name, if at all possible
685  * @dev: struct device to get the name of
686  *
687  * Will return the device's driver's name if it is bound to a device.  If
688  * the device is not bound to a driver, it will return the name of the bus
689  * it is attached to.  If it is not attached to a bus either, an empty
690  * string will be returned.
691  */
692 const char *dev_driver_string(const struct device *dev)
693 {
694         struct device_driver *drv;
695
696         /* dev->driver can change to NULL underneath us because of unbinding,
697          * so be careful about accessing it.  dev->bus and dev->class should
698          * never change once they are set, so they don't need special care.
699          */
700         drv = READ_ONCE(dev->driver);
701         return drv ? drv->name :
702                         (dev->bus ? dev->bus->name :
703                         (dev->class ? dev->class->name : ""));
704 }
705 EXPORT_SYMBOL(dev_driver_string);
706
707 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
708
709 static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
710                              char *buf)
711 {
712         struct device_attribute *dev_attr = to_dev_attr(attr);
713         struct device *dev = kobj_to_dev(kobj);
714         ssize_t ret = -EIO;
715
716         if (dev_attr->show)
717                 ret = dev_attr->show(dev, dev_attr, buf);
718         if (ret >= (ssize_t)PAGE_SIZE) {
719                 printk("dev_attr_show: %pS returned bad count\n",
720                                 dev_attr->show);
721         }
722         return ret;
723 }
724
725 static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
726                               const char *buf, size_t count)
727 {
728         struct device_attribute *dev_attr = to_dev_attr(attr);
729         struct device *dev = kobj_to_dev(kobj);
730         ssize_t ret = -EIO;
731
732         if (dev_attr->store)
733                 ret = dev_attr->store(dev, dev_attr, buf, count);
734         return ret;
735 }
736
737 static const struct sysfs_ops dev_sysfs_ops = {
738         .show   = dev_attr_show,
739         .store  = dev_attr_store,
740 };
741
742 #define to_ext_attr(x) container_of(x, struct dev_ext_attribute, attr)
743
744 ssize_t device_store_ulong(struct device *dev,
745                            struct device_attribute *attr,
746                            const char *buf, size_t size)
747 {
748         struct dev_ext_attribute *ea = to_ext_attr(attr);
749         char *end;
750         unsigned long new = simple_strtoul(buf, &end, 0);
751         if (end == buf)
752                 return -EINVAL;
753         *(unsigned long *)(ea->var) = new;
754         /* Always return full write size even if we didn't consume all */
755         return size;
756 }
757 EXPORT_SYMBOL_GPL(device_store_ulong);
758
759 ssize_t device_show_ulong(struct device *dev,
760                           struct device_attribute *attr,
761                           char *buf)
762 {
763         struct dev_ext_attribute *ea = to_ext_attr(attr);
764         return snprintf(buf, PAGE_SIZE, "%lx\n", *(unsigned long *)(ea->var));
765 }
766 EXPORT_SYMBOL_GPL(device_show_ulong);
767
768 ssize_t device_store_int(struct device *dev,
769                          struct device_attribute *attr,
770                          const char *buf, size_t size)
771 {
772         struct dev_ext_attribute *ea = to_ext_attr(attr);
773         char *end;
774         long new = simple_strtol(buf, &end, 0);
775         if (end == buf || new > INT_MAX || new < INT_MIN)
776                 return -EINVAL;
777         *(int *)(ea->var) = new;
778         /* Always return full write size even if we didn't consume all */
779         return size;
780 }
781 EXPORT_SYMBOL_GPL(device_store_int);
782
783 ssize_t device_show_int(struct device *dev,
784                         struct device_attribute *attr,
785                         char *buf)
786 {
787         struct dev_ext_attribute *ea = to_ext_attr(attr);
788
789         return snprintf(buf, PAGE_SIZE, "%d\n", *(int *)(ea->var));
790 }
791 EXPORT_SYMBOL_GPL(device_show_int);
792
793 ssize_t device_store_bool(struct device *dev, struct device_attribute *attr,
794                           const char *buf, size_t size)
795 {
796         struct dev_ext_attribute *ea = to_ext_attr(attr);
797
798         if (strtobool(buf, ea->var) < 0)
799                 return -EINVAL;
800
801         return size;
802 }
803 EXPORT_SYMBOL_GPL(device_store_bool);
804
805 ssize_t device_show_bool(struct device *dev, struct device_attribute *attr,
806                          char *buf)
807 {
808         struct dev_ext_attribute *ea = to_ext_attr(attr);
809
810         return snprintf(buf, PAGE_SIZE, "%d\n", *(bool *)(ea->var));
811 }
812 EXPORT_SYMBOL_GPL(device_show_bool);
813
814 /**
815  * device_release - free device structure.
816  * @kobj: device's kobject.
817  *
818  * This is called once the reference count for the object
819  * reaches 0. We forward the call to the device's release
820  * method, which should handle actually freeing the structure.
821  */
822 static void device_release(struct kobject *kobj)
823 {
824         struct device *dev = kobj_to_dev(kobj);
825         struct device_private *p = dev->p;
826
827         /*
828          * Some platform devices are driven without driver attached
829          * and managed resources may have been acquired.  Make sure
830          * all resources are released.
831          *
832          * Drivers still can add resources into device after device
833          * is deleted but alive, so release devres here to avoid
834          * possible memory leak.
835          */
836         devres_release_all(dev);
837
838         if (dev->release)
839                 dev->release(dev);
840         else if (dev->type && dev->type->release)
841                 dev->type->release(dev);
842         else if (dev->class && dev->class->dev_release)
843                 dev->class->dev_release(dev);
844         else
845                 WARN(1, KERN_ERR "Device '%s' does not have a release() "
846                         "function, it is broken and must be fixed.\n",
847                         dev_name(dev));
848         kfree(p);
849 }
850
851 static const void *device_namespace(struct kobject *kobj)
852 {
853         struct device *dev = kobj_to_dev(kobj);
854         const void *ns = NULL;
855
856         if (dev->class && dev->class->ns_type)
857                 ns = dev->class->namespace(dev);
858
859         return ns;
860 }
861
862 static struct kobj_type device_ktype = {
863         .release        = device_release,
864         .sysfs_ops      = &dev_sysfs_ops,
865         .namespace      = device_namespace,
866 };
867
868
869 static int dev_uevent_filter(struct kset *kset, struct kobject *kobj)
870 {
871         struct kobj_type *ktype = get_ktype(kobj);
872
873         if (ktype == &device_ktype) {
874                 struct device *dev = kobj_to_dev(kobj);
875                 if (dev->bus)
876                         return 1;
877                 if (dev->class)
878                         return 1;
879         }
880         return 0;
881 }
882
883 static const char *dev_uevent_name(struct kset *kset, struct kobject *kobj)
884 {
885         struct device *dev = kobj_to_dev(kobj);
886
887         if (dev->bus)
888                 return dev->bus->name;
889         if (dev->class)
890                 return dev->class->name;
891         return NULL;
892 }
893
894 static int dev_uevent(struct kset *kset, struct kobject *kobj,
895                       struct kobj_uevent_env *env)
896 {
897         struct device *dev = kobj_to_dev(kobj);
898         int retval = 0;
899
900         /* add device node properties if present */
901         if (MAJOR(dev->devt)) {
902                 const char *tmp;
903                 const char *name;
904                 umode_t mode = 0;
905                 kuid_t uid = GLOBAL_ROOT_UID;
906                 kgid_t gid = GLOBAL_ROOT_GID;
907
908                 add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt));
909                 add_uevent_var(env, "MINOR=%u", MINOR(dev->devt));
910                 name = device_get_devnode(dev, &mode, &uid, &gid, &tmp);
911                 if (name) {
912                         add_uevent_var(env, "DEVNAME=%s", name);
913                         if (mode)
914                                 add_uevent_var(env, "DEVMODE=%#o", mode & 0777);
915                         if (!uid_eq(uid, GLOBAL_ROOT_UID))
916                                 add_uevent_var(env, "DEVUID=%u", from_kuid(&init_user_ns, uid));
917                         if (!gid_eq(gid, GLOBAL_ROOT_GID))
918                                 add_uevent_var(env, "DEVGID=%u", from_kgid(&init_user_ns, gid));
919                         kfree(tmp);
920                 }
921         }
922
923         if (dev->type && dev->type->name)
924                 add_uevent_var(env, "DEVTYPE=%s", dev->type->name);
925
926         if (dev->driver)
927                 add_uevent_var(env, "DRIVER=%s", dev->driver->name);
928
929         /* Add common DT information about the device */
930         of_device_uevent(dev, env);
931
932         /* have the bus specific function add its stuff */
933         if (dev->bus && dev->bus->uevent) {
934                 retval = dev->bus->uevent(dev, env);
935                 if (retval)
936                         pr_debug("device: '%s': %s: bus uevent() returned %d\n",
937                                  dev_name(dev), __func__, retval);
938         }
939
940         /* have the class specific function add its stuff */
941         if (dev->class && dev->class->dev_uevent) {
942                 retval = dev->class->dev_uevent(dev, env);
943                 if (retval)
944                         pr_debug("device: '%s': %s: class uevent() "
945                                  "returned %d\n", dev_name(dev),
946                                  __func__, retval);
947         }
948
949         /* have the device type specific function add its stuff */
950         if (dev->type && dev->type->uevent) {
951                 retval = dev->type->uevent(dev, env);
952                 if (retval)
953                         pr_debug("device: '%s': %s: dev_type uevent() "
954                                  "returned %d\n", dev_name(dev),
955                                  __func__, retval);
956         }
957
958         return retval;
959 }
960
961 static const struct kset_uevent_ops device_uevent_ops = {
962         .filter =       dev_uevent_filter,
963         .name =         dev_uevent_name,
964         .uevent =       dev_uevent,
965 };
966
967 static ssize_t uevent_show(struct device *dev, struct device_attribute *attr,
968                            char *buf)
969 {
970         struct kobject *top_kobj;
971         struct kset *kset;
972         struct kobj_uevent_env *env = NULL;
973         int i;
974         size_t count = 0;
975         int retval;
976
977         /* search the kset, the device belongs to */
978         top_kobj = &dev->kobj;
979         while (!top_kobj->kset && top_kobj->parent)
980                 top_kobj = top_kobj->parent;
981         if (!top_kobj->kset)
982                 goto out;
983
984         kset = top_kobj->kset;
985         if (!kset->uevent_ops || !kset->uevent_ops->uevent)
986                 goto out;
987
988         /* respect filter */
989         if (kset->uevent_ops && kset->uevent_ops->filter)
990                 if (!kset->uevent_ops->filter(kset, &dev->kobj))
991                         goto out;
992
993         env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
994         if (!env)
995                 return -ENOMEM;
996
997         /* let the kset specific function add its keys */
998         retval = kset->uevent_ops->uevent(kset, &dev->kobj, env);
999         if (retval)
1000                 goto out;
1001
1002         /* copy keys to file */
1003         for (i = 0; i < env->envp_idx; i++)
1004                 count += sprintf(&buf[count], "%s\n", env->envp[i]);
1005 out:
1006         kfree(env);
1007         return count;
1008 }
1009
1010 static ssize_t uevent_store(struct device *dev, struct device_attribute *attr,
1011                             const char *buf, size_t count)
1012 {
1013         if (kobject_synth_uevent(&dev->kobj, buf, count))
1014                 dev_err(dev, "uevent: failed to send synthetic uevent\n");
1015
1016         return count;
1017 }
1018 static DEVICE_ATTR_RW(uevent);
1019
1020 static ssize_t online_show(struct device *dev, struct device_attribute *attr,
1021                            char *buf)
1022 {
1023         bool val;
1024
1025         device_lock(dev);
1026         val = !dev->offline;
1027         device_unlock(dev);
1028         return sprintf(buf, "%u\n", val);
1029 }
1030
1031 static ssize_t online_store(struct device *dev, struct device_attribute *attr,
1032                             const char *buf, size_t count)
1033 {
1034         bool val;
1035         int ret;
1036
1037         ret = strtobool(buf, &val);
1038         if (ret < 0)
1039                 return ret;
1040
1041         ret = lock_device_hotplug_sysfs();
1042         if (ret)
1043                 return ret;
1044
1045         ret = val ? device_online(dev) : device_offline(dev);
1046         unlock_device_hotplug();
1047         return ret < 0 ? ret : count;
1048 }
1049 static DEVICE_ATTR_RW(online);
1050
1051 int device_add_groups(struct device *dev, const struct attribute_group **groups)
1052 {
1053         return sysfs_create_groups(&dev->kobj, groups);
1054 }
1055 EXPORT_SYMBOL_GPL(device_add_groups);
1056
1057 void device_remove_groups(struct device *dev,
1058                           const struct attribute_group **groups)
1059 {
1060         sysfs_remove_groups(&dev->kobj, groups);
1061 }
1062 EXPORT_SYMBOL_GPL(device_remove_groups);
1063
1064 union device_attr_group_devres {
1065         const struct attribute_group *group;
1066         const struct attribute_group **groups;
1067 };
1068
1069 static int devm_attr_group_match(struct device *dev, void *res, void *data)
1070 {
1071         return ((union device_attr_group_devres *)res)->group == data;
1072 }
1073
1074 static void devm_attr_group_remove(struct device *dev, void *res)
1075 {
1076         union device_attr_group_devres *devres = res;
1077         const struct attribute_group *group = devres->group;
1078
1079         dev_dbg(dev, "%s: removing group %p\n", __func__, group);
1080         sysfs_remove_group(&dev->kobj, group);
1081 }
1082
1083 static void devm_attr_groups_remove(struct device *dev, void *res)
1084 {
1085         union device_attr_group_devres *devres = res;
1086         const struct attribute_group **groups = devres->groups;
1087
1088         dev_dbg(dev, "%s: removing groups %p\n", __func__, groups);
1089         sysfs_remove_groups(&dev->kobj, groups);
1090 }
1091
1092 /**
1093  * devm_device_add_group - given a device, create a managed attribute group
1094  * @dev:        The device to create the group for
1095  * @grp:        The attribute group to create
1096  *
1097  * This function creates a group for the first time.  It will explicitly
1098  * warn and error if any of the attribute files being created already exist.
1099  *
1100  * Returns 0 on success or error code on failure.
1101  */
1102 int devm_device_add_group(struct device *dev, const struct attribute_group *grp)
1103 {
1104         union device_attr_group_devres *devres;
1105         int error;
1106
1107         devres = devres_alloc(devm_attr_group_remove,
1108                               sizeof(*devres), GFP_KERNEL);
1109         if (!devres)
1110                 return -ENOMEM;
1111
1112         error = sysfs_create_group(&dev->kobj, grp);
1113         if (error) {
1114                 devres_free(devres);
1115                 return error;
1116         }
1117
1118         devres->group = grp;
1119         devres_add(dev, devres);
1120         return 0;
1121 }
1122 EXPORT_SYMBOL_GPL(devm_device_add_group);
1123
1124 /**
1125  * devm_device_remove_group: remove a managed group from a device
1126  * @dev:        device to remove the group from
1127  * @grp:        group to remove
1128  *
1129  * This function removes a group of attributes from a device. The attributes
1130  * previously have to have been created for this group, otherwise it will fail.
1131  */
1132 void devm_device_remove_group(struct device *dev,
1133                               const struct attribute_group *grp)
1134 {
1135         WARN_ON(devres_release(dev, devm_attr_group_remove,
1136                                devm_attr_group_match,
1137                                /* cast away const */ (void *)grp));
1138 }
1139 EXPORT_SYMBOL_GPL(devm_device_remove_group);
1140
1141 /**
1142  * devm_device_add_groups - create a bunch of managed attribute groups
1143  * @dev:        The device to create the group for
1144  * @groups:     The attribute groups to create, NULL terminated
1145  *
1146  * This function creates a bunch of managed attribute groups.  If an error
1147  * occurs when creating a group, all previously created groups will be
1148  * removed, unwinding everything back to the original state when this
1149  * function was called.  It will explicitly warn and error if any of the
1150  * attribute files being created already exist.
1151  *
1152  * Returns 0 on success or error code from sysfs_create_group on failure.
1153  */
1154 int devm_device_add_groups(struct device *dev,
1155                            const struct attribute_group **groups)
1156 {
1157         union device_attr_group_devres *devres;
1158         int error;
1159
1160         devres = devres_alloc(devm_attr_groups_remove,
1161                               sizeof(*devres), GFP_KERNEL);
1162         if (!devres)
1163                 return -ENOMEM;
1164
1165         error = sysfs_create_groups(&dev->kobj, groups);
1166         if (error) {
1167                 devres_free(devres);
1168                 return error;
1169         }
1170
1171         devres->groups = groups;
1172         devres_add(dev, devres);
1173         return 0;
1174 }
1175 EXPORT_SYMBOL_GPL(devm_device_add_groups);
1176
1177 /**
1178  * devm_device_remove_groups - remove a list of managed groups
1179  *
1180  * @dev:        The device for the groups to be removed from
1181  * @groups:     NULL terminated list of groups to be removed
1182  *
1183  * If groups is not NULL, remove the specified groups from the device.
1184  */
1185 void devm_device_remove_groups(struct device *dev,
1186                                const struct attribute_group **groups)
1187 {
1188         WARN_ON(devres_release(dev, devm_attr_groups_remove,
1189                                devm_attr_group_match,
1190                                /* cast away const */ (void *)groups));
1191 }
1192 EXPORT_SYMBOL_GPL(devm_device_remove_groups);
1193
1194 static int device_add_attrs(struct device *dev)
1195 {
1196         struct class *class = dev->class;
1197         const struct device_type *type = dev->type;
1198         int error;
1199
1200         if (class) {
1201                 error = device_add_groups(dev, class->dev_groups);
1202                 if (error)
1203                         return error;
1204         }
1205
1206         if (type) {
1207                 error = device_add_groups(dev, type->groups);
1208                 if (error)
1209                         goto err_remove_class_groups;
1210         }
1211
1212         error = device_add_groups(dev, dev->groups);
1213         if (error)
1214                 goto err_remove_type_groups;
1215
1216         if (device_supports_offline(dev) && !dev->offline_disabled) {
1217                 error = device_create_file(dev, &dev_attr_online);
1218                 if (error)
1219                         goto err_remove_dev_groups;
1220         }
1221
1222         return 0;
1223
1224  err_remove_dev_groups:
1225         device_remove_groups(dev, dev->groups);
1226  err_remove_type_groups:
1227         if (type)
1228                 device_remove_groups(dev, type->groups);
1229  err_remove_class_groups:
1230         if (class)
1231                 device_remove_groups(dev, class->dev_groups);
1232
1233         return error;
1234 }
1235
1236 static void device_remove_attrs(struct device *dev)
1237 {
1238         struct class *class = dev->class;
1239         const struct device_type *type = dev->type;
1240
1241         device_remove_file(dev, &dev_attr_online);
1242         device_remove_groups(dev, dev->groups);
1243
1244         if (type)
1245                 device_remove_groups(dev, type->groups);
1246
1247         if (class)
1248                 device_remove_groups(dev, class->dev_groups);
1249 }
1250
1251 static ssize_t dev_show(struct device *dev, struct device_attribute *attr,
1252                         char *buf)
1253 {
1254         return print_dev_t(buf, dev->devt);
1255 }
1256 static DEVICE_ATTR_RO(dev);
1257
1258 /* /sys/devices/ */
1259 struct kset *devices_kset;
1260
1261 /**
1262  * devices_kset_move_before - Move device in the devices_kset's list.
1263  * @deva: Device to move.
1264  * @devb: Device @deva should come before.
1265  */
1266 static void devices_kset_move_before(struct device *deva, struct device *devb)
1267 {
1268         if (!devices_kset)
1269                 return;
1270         pr_debug("devices_kset: Moving %s before %s\n",
1271                  dev_name(deva), dev_name(devb));
1272         spin_lock(&devices_kset->list_lock);
1273         list_move_tail(&deva->kobj.entry, &devb->kobj.entry);
1274         spin_unlock(&devices_kset->list_lock);
1275 }
1276
1277 /**
1278  * devices_kset_move_after - Move device in the devices_kset's list.
1279  * @deva: Device to move
1280  * @devb: Device @deva should come after.
1281  */
1282 static void devices_kset_move_after(struct device *deva, struct device *devb)
1283 {
1284         if (!devices_kset)
1285                 return;
1286         pr_debug("devices_kset: Moving %s after %s\n",
1287                  dev_name(deva), dev_name(devb));
1288         spin_lock(&devices_kset->list_lock);
1289         list_move(&deva->kobj.entry, &devb->kobj.entry);
1290         spin_unlock(&devices_kset->list_lock);
1291 }
1292
1293 /**
1294  * devices_kset_move_last - move the device to the end of devices_kset's list.
1295  * @dev: device to move
1296  */
1297 void devices_kset_move_last(struct device *dev)
1298 {
1299         if (!devices_kset)
1300                 return;
1301         pr_debug("devices_kset: Moving %s to end of list\n", dev_name(dev));
1302         spin_lock(&devices_kset->list_lock);
1303         list_move_tail(&dev->kobj.entry, &devices_kset->list);
1304         spin_unlock(&devices_kset->list_lock);
1305 }
1306
1307 /**
1308  * device_create_file - create sysfs attribute file for device.
1309  * @dev: device.
1310  * @attr: device attribute descriptor.
1311  */
1312 int device_create_file(struct device *dev,
1313                        const struct device_attribute *attr)
1314 {
1315         int error = 0;
1316
1317         if (dev) {
1318                 WARN(((attr->attr.mode & S_IWUGO) && !attr->store),
1319                         "Attribute %s: write permission without 'store'\n",
1320                         attr->attr.name);
1321                 WARN(((attr->attr.mode & S_IRUGO) && !attr->show),
1322                         "Attribute %s: read permission without 'show'\n",
1323                         attr->attr.name);
1324                 error = sysfs_create_file(&dev->kobj, &attr->attr);
1325         }
1326
1327         return error;
1328 }
1329 EXPORT_SYMBOL_GPL(device_create_file);
1330
1331 /**
1332  * device_remove_file - remove sysfs attribute file.
1333  * @dev: device.
1334  * @attr: device attribute descriptor.
1335  */
1336 void device_remove_file(struct device *dev,
1337                         const struct device_attribute *attr)
1338 {
1339         if (dev)
1340                 sysfs_remove_file(&dev->kobj, &attr->attr);
1341 }
1342 EXPORT_SYMBOL_GPL(device_remove_file);
1343
1344 /**
1345  * device_remove_file_self - remove sysfs attribute file from its own method.
1346  * @dev: device.
1347  * @attr: device attribute descriptor.
1348  *
1349  * See kernfs_remove_self() for details.
1350  */
1351 bool device_remove_file_self(struct device *dev,
1352                              const struct device_attribute *attr)
1353 {
1354         if (dev)
1355                 return sysfs_remove_file_self(&dev->kobj, &attr->attr);
1356         else
1357                 return false;
1358 }
1359 EXPORT_SYMBOL_GPL(device_remove_file_self);
1360
1361 /**
1362  * device_create_bin_file - create sysfs binary attribute file for device.
1363  * @dev: device.
1364  * @attr: device binary attribute descriptor.
1365  */
1366 int device_create_bin_file(struct device *dev,
1367                            const struct bin_attribute *attr)
1368 {
1369         int error = -EINVAL;
1370         if (dev)
1371                 error = sysfs_create_bin_file(&dev->kobj, attr);
1372         return error;
1373 }
1374 EXPORT_SYMBOL_GPL(device_create_bin_file);
1375
1376 /**
1377  * device_remove_bin_file - remove sysfs binary attribute file
1378  * @dev: device.
1379  * @attr: device binary attribute descriptor.
1380  */
1381 void device_remove_bin_file(struct device *dev,
1382                             const struct bin_attribute *attr)
1383 {
1384         if (dev)
1385                 sysfs_remove_bin_file(&dev->kobj, attr);
1386 }
1387 EXPORT_SYMBOL_GPL(device_remove_bin_file);
1388
1389 static void klist_children_get(struct klist_node *n)
1390 {
1391         struct device_private *p = to_device_private_parent(n);
1392         struct device *dev = p->device;
1393
1394         get_device(dev);
1395 }
1396
1397 static void klist_children_put(struct klist_node *n)
1398 {
1399         struct device_private *p = to_device_private_parent(n);
1400         struct device *dev = p->device;
1401
1402         put_device(dev);
1403 }
1404
1405 /**
1406  * device_initialize - init device structure.
1407  * @dev: device.
1408  *
1409  * This prepares the device for use by other layers by initializing
1410  * its fields.
1411  * It is the first half of device_register(), if called by
1412  * that function, though it can also be called separately, so one
1413  * may use @dev's fields. In particular, get_device()/put_device()
1414  * may be used for reference counting of @dev after calling this
1415  * function.
1416  *
1417  * All fields in @dev must be initialized by the caller to 0, except
1418  * for those explicitly set to some other value.  The simplest
1419  * approach is to use kzalloc() to allocate the structure containing
1420  * @dev.
1421  *
1422  * NOTE: Use put_device() to give up your reference instead of freeing
1423  * @dev directly once you have called this function.
1424  */
1425 void device_initialize(struct device *dev)
1426 {
1427         dev->kobj.kset = devices_kset;
1428         kobject_init(&dev->kobj, &device_ktype);
1429         INIT_LIST_HEAD(&dev->dma_pools);
1430         mutex_init(&dev->mutex);
1431         lockdep_set_novalidate_class(&dev->mutex);
1432         spin_lock_init(&dev->devres_lock);
1433         INIT_LIST_HEAD(&dev->devres_head);
1434         device_pm_init(dev);
1435         set_dev_node(dev, -1);
1436 #ifdef CONFIG_GENERIC_MSI_IRQ
1437         INIT_LIST_HEAD(&dev->msi_list);
1438 #endif
1439         INIT_LIST_HEAD(&dev->links.consumers);
1440         INIT_LIST_HEAD(&dev->links.suppliers);
1441         dev->links.status = DL_DEV_NO_DRIVER;
1442 }
1443 EXPORT_SYMBOL_GPL(device_initialize);
1444
1445 struct kobject *virtual_device_parent(struct device *dev)
1446 {
1447         static struct kobject *virtual_dir = NULL;
1448
1449         if (!virtual_dir)
1450                 virtual_dir = kobject_create_and_add("virtual",
1451                                                      &devices_kset->kobj);
1452
1453         return virtual_dir;
1454 }
1455
1456 struct class_dir {
1457         struct kobject kobj;
1458         struct class *class;
1459 };
1460
1461 #define to_class_dir(obj) container_of(obj, struct class_dir, kobj)
1462
1463 static void class_dir_release(struct kobject *kobj)
1464 {
1465         struct class_dir *dir = to_class_dir(kobj);
1466         kfree(dir);
1467 }
1468
1469 static const
1470 struct kobj_ns_type_operations *class_dir_child_ns_type(struct kobject *kobj)
1471 {
1472         struct class_dir *dir = to_class_dir(kobj);
1473         return dir->class->ns_type;
1474 }
1475
1476 static struct kobj_type class_dir_ktype = {
1477         .release        = class_dir_release,
1478         .sysfs_ops      = &kobj_sysfs_ops,
1479         .child_ns_type  = class_dir_child_ns_type
1480 };
1481
1482 static struct kobject *
1483 class_dir_create_and_add(struct class *class, struct kobject *parent_kobj)
1484 {
1485         struct class_dir *dir;
1486         int retval;
1487
1488         dir = kzalloc(sizeof(*dir), GFP_KERNEL);
1489         if (!dir)
1490                 return ERR_PTR(-ENOMEM);
1491
1492         dir->class = class;
1493         kobject_init(&dir->kobj, &class_dir_ktype);
1494
1495         dir->kobj.kset = &class->p->glue_dirs;
1496
1497         retval = kobject_add(&dir->kobj, parent_kobj, "%s", class->name);
1498         if (retval < 0) {
1499                 kobject_put(&dir->kobj);
1500                 return ERR_PTR(retval);
1501         }
1502         return &dir->kobj;
1503 }
1504
1505 static DEFINE_MUTEX(gdp_mutex);
1506
1507 static struct kobject *get_device_parent(struct device *dev,
1508                                          struct device *parent)
1509 {
1510         if (dev->class) {
1511                 struct kobject *kobj = NULL;
1512                 struct kobject *parent_kobj;
1513                 struct kobject *k;
1514
1515 #ifdef CONFIG_BLOCK
1516                 /* block disks show up in /sys/block */
1517                 if (sysfs_deprecated && dev->class == &block_class) {
1518                         if (parent && parent->class == &block_class)
1519                                 return &parent->kobj;
1520                         return &block_class.p->subsys.kobj;
1521                 }
1522 #endif
1523
1524                 /*
1525                  * If we have no parent, we live in "virtual".
1526                  * Class-devices with a non class-device as parent, live
1527                  * in a "glue" directory to prevent namespace collisions.
1528                  */
1529                 if (parent == NULL)
1530                         parent_kobj = virtual_device_parent(dev);
1531                 else if (parent->class && !dev->class->ns_type)
1532                         return &parent->kobj;
1533                 else
1534                         parent_kobj = &parent->kobj;
1535
1536                 mutex_lock(&gdp_mutex);
1537
1538                 /* find our class-directory at the parent and reference it */
1539                 spin_lock(&dev->class->p->glue_dirs.list_lock);
1540                 list_for_each_entry(k, &dev->class->p->glue_dirs.list, entry)
1541                         if (k->parent == parent_kobj) {
1542                                 kobj = kobject_get(k);
1543                                 break;
1544                         }
1545                 spin_unlock(&dev->class->p->glue_dirs.list_lock);
1546                 if (kobj) {
1547                         mutex_unlock(&gdp_mutex);
1548                         return kobj;
1549                 }
1550
1551                 /* or create a new class-directory at the parent device */
1552                 k = class_dir_create_and_add(dev->class, parent_kobj);
1553                 /* do not emit an uevent for this simple "glue" directory */
1554                 mutex_unlock(&gdp_mutex);
1555                 return k;
1556         }
1557
1558         /* subsystems can specify a default root directory for their devices */
1559         if (!parent && dev->bus && dev->bus->dev_root)
1560                 return &dev->bus->dev_root->kobj;
1561
1562         if (parent)
1563                 return &parent->kobj;
1564         return NULL;
1565 }
1566
1567 static inline bool live_in_glue_dir(struct kobject *kobj,
1568                                     struct device *dev)
1569 {
1570         if (!kobj || !dev->class ||
1571             kobj->kset != &dev->class->p->glue_dirs)
1572                 return false;
1573         return true;
1574 }
1575
1576 static inline struct kobject *get_glue_dir(struct device *dev)
1577 {
1578         return dev->kobj.parent;
1579 }
1580
1581 /*
1582  * make sure cleaning up dir as the last step, we need to make
1583  * sure .release handler of kobject is run with holding the
1584  * global lock
1585  */
1586 static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir)
1587 {
1588         /* see if we live in a "glue" directory */
1589         if (!live_in_glue_dir(glue_dir, dev))
1590                 return;
1591
1592         mutex_lock(&gdp_mutex);
1593         kobject_put(glue_dir);
1594         mutex_unlock(&gdp_mutex);
1595 }
1596
1597 static int device_add_class_symlinks(struct device *dev)
1598 {
1599         struct device_node *of_node = dev_of_node(dev);
1600         int error;
1601
1602         if (of_node) {
1603                 error = sysfs_create_link(&dev->kobj, of_node_kobj(of_node), "of_node");
1604                 if (error)
1605                         dev_warn(dev, "Error %d creating of_node link\n",error);
1606                 /* An error here doesn't warrant bringing down the device */
1607         }
1608
1609         if (!dev->class)
1610                 return 0;
1611
1612         error = sysfs_create_link(&dev->kobj,
1613                                   &dev->class->p->subsys.kobj,
1614                                   "subsystem");
1615         if (error)
1616                 goto out_devnode;
1617
1618         if (dev->parent && device_is_not_partition(dev)) {
1619                 error = sysfs_create_link(&dev->kobj, &dev->parent->kobj,
1620                                           "device");
1621                 if (error)
1622                         goto out_subsys;
1623         }
1624
1625 #ifdef CONFIG_BLOCK
1626         /* /sys/block has directories and does not need symlinks */
1627         if (sysfs_deprecated && dev->class == &block_class)
1628                 return 0;
1629 #endif
1630
1631         /* link in the class directory pointing to the device */
1632         error = sysfs_create_link(&dev->class->p->subsys.kobj,
1633                                   &dev->kobj, dev_name(dev));
1634         if (error)
1635                 goto out_device;
1636
1637         return 0;
1638
1639 out_device:
1640         sysfs_remove_link(&dev->kobj, "device");
1641
1642 out_subsys:
1643         sysfs_remove_link(&dev->kobj, "subsystem");
1644 out_devnode:
1645         sysfs_remove_link(&dev->kobj, "of_node");
1646         return error;
1647 }
1648
1649 static void device_remove_class_symlinks(struct device *dev)
1650 {
1651         if (dev_of_node(dev))
1652                 sysfs_remove_link(&dev->kobj, "of_node");
1653
1654         if (!dev->class)
1655                 return;
1656
1657         if (dev->parent && device_is_not_partition(dev))
1658                 sysfs_remove_link(&dev->kobj, "device");
1659         sysfs_remove_link(&dev->kobj, "subsystem");
1660 #ifdef CONFIG_BLOCK
1661         if (sysfs_deprecated && dev->class == &block_class)
1662                 return;
1663 #endif
1664         sysfs_delete_link(&dev->class->p->subsys.kobj, &dev->kobj, dev_name(dev));
1665 }
1666
1667 /**
1668  * dev_set_name - set a device name
1669  * @dev: device
1670  * @fmt: format string for the device's name
1671  */
1672 int dev_set_name(struct device *dev, const char *fmt, ...)
1673 {
1674         va_list vargs;
1675         int err;
1676
1677         va_start(vargs, fmt);
1678         err = kobject_set_name_vargs(&dev->kobj, fmt, vargs);
1679         va_end(vargs);
1680         return err;
1681 }
1682 EXPORT_SYMBOL_GPL(dev_set_name);
1683
1684 /**
1685  * device_to_dev_kobj - select a /sys/dev/ directory for the device
1686  * @dev: device
1687  *
1688  * By default we select char/ for new entries.  Setting class->dev_obj
1689  * to NULL prevents an entry from being created.  class->dev_kobj must
1690  * be set (or cleared) before any devices are registered to the class
1691  * otherwise device_create_sys_dev_entry() and
1692  * device_remove_sys_dev_entry() will disagree about the presence of
1693  * the link.
1694  */
1695 static struct kobject *device_to_dev_kobj(struct device *dev)
1696 {
1697         struct kobject *kobj;
1698
1699         if (dev->class)
1700                 kobj = dev->class->dev_kobj;
1701         else
1702                 kobj = sysfs_dev_char_kobj;
1703
1704         return kobj;
1705 }
1706
1707 static int device_create_sys_dev_entry(struct device *dev)
1708 {
1709         struct kobject *kobj = device_to_dev_kobj(dev);
1710         int error = 0;
1711         char devt_str[15];
1712
1713         if (kobj) {
1714                 format_dev_t(devt_str, dev->devt);
1715                 error = sysfs_create_link(kobj, &dev->kobj, devt_str);
1716         }
1717
1718         return error;
1719 }
1720
1721 static void device_remove_sys_dev_entry(struct device *dev)
1722 {
1723         struct kobject *kobj = device_to_dev_kobj(dev);
1724         char devt_str[15];
1725
1726         if (kobj) {
1727                 format_dev_t(devt_str, dev->devt);
1728                 sysfs_remove_link(kobj, devt_str);
1729         }
1730 }
1731
1732 int device_private_init(struct device *dev)
1733 {
1734         dev->p = kzalloc(sizeof(*dev->p), GFP_KERNEL);
1735         if (!dev->p)
1736                 return -ENOMEM;
1737         dev->p->device = dev;
1738         klist_init(&dev->p->klist_children, klist_children_get,
1739                    klist_children_put);
1740         INIT_LIST_HEAD(&dev->p->deferred_probe);
1741         return 0;
1742 }
1743
1744 /**
1745  * device_add - add device to device hierarchy.
1746  * @dev: device.
1747  *
1748  * This is part 2 of device_register(), though may be called
1749  * separately _iff_ device_initialize() has been called separately.
1750  *
1751  * This adds @dev to the kobject hierarchy via kobject_add(), adds it
1752  * to the global and sibling lists for the device, then
1753  * adds it to the other relevant subsystems of the driver model.
1754  *
1755  * Do not call this routine or device_register() more than once for
1756  * any device structure.  The driver model core is not designed to work
1757  * with devices that get unregistered and then spring back to life.
1758  * (Among other things, it's very hard to guarantee that all references
1759  * to the previous incarnation of @dev have been dropped.)  Allocate
1760  * and register a fresh new struct device instead.
1761  *
1762  * NOTE: _Never_ directly free @dev after calling this function, even
1763  * if it returned an error! Always use put_device() to give up your
1764  * reference instead.
1765  */
1766 int device_add(struct device *dev)
1767 {
1768         struct device *parent;
1769         struct kobject *kobj;
1770         struct class_interface *class_intf;
1771         int error = -EINVAL;
1772         struct kobject *glue_dir = NULL;
1773
1774         dev = get_device(dev);
1775         if (!dev)
1776                 goto done;
1777
1778         if (!dev->p) {
1779                 error = device_private_init(dev);
1780                 if (error)
1781                         goto done;
1782         }
1783
1784         /*
1785          * for statically allocated devices, which should all be converted
1786          * some day, we need to initialize the name. We prevent reading back
1787          * the name, and force the use of dev_name()
1788          */
1789         if (dev->init_name) {
1790                 dev_set_name(dev, "%s", dev->init_name);
1791                 dev->init_name = NULL;
1792         }
1793
1794         /* subsystems can specify simple device enumeration */
1795         if (!dev_name(dev) && dev->bus && dev->bus->dev_name)
1796                 dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
1797
1798         if (!dev_name(dev)) {
1799                 error = -EINVAL;
1800                 goto name_error;
1801         }
1802
1803         pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
1804
1805         parent = get_device(dev->parent);
1806         kobj = get_device_parent(dev, parent);
1807         if (IS_ERR(kobj)) {
1808                 error = PTR_ERR(kobj);
1809                 goto parent_error;
1810         }
1811         if (kobj)
1812                 dev->kobj.parent = kobj;
1813
1814         /* use parent numa_node */
1815         if (parent && (dev_to_node(dev) == NUMA_NO_NODE))
1816                 set_dev_node(dev, dev_to_node(parent));
1817
1818         /* first, register with generic layer. */
1819         /* we require the name to be set before, and pass NULL */
1820         error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
1821         if (error) {
1822                 glue_dir = get_glue_dir(dev);
1823                 goto Error;
1824         }
1825
1826         /* notify platform of device entry */
1827         if (platform_notify)
1828                 platform_notify(dev);
1829
1830         error = device_create_file(dev, &dev_attr_uevent);
1831         if (error)
1832                 goto attrError;
1833
1834         error = device_add_class_symlinks(dev);
1835         if (error)
1836                 goto SymlinkError;
1837         error = device_add_attrs(dev);
1838         if (error)
1839                 goto AttrsError;
1840         error = bus_add_device(dev);
1841         if (error)
1842                 goto BusError;
1843         error = dpm_sysfs_add(dev);
1844         if (error)
1845                 goto DPMError;
1846         device_pm_add(dev);
1847
1848         if (MAJOR(dev->devt)) {
1849                 error = device_create_file(dev, &dev_attr_dev);
1850                 if (error)
1851                         goto DevAttrError;
1852
1853                 error = device_create_sys_dev_entry(dev);
1854                 if (error)
1855                         goto SysEntryError;
1856
1857                 devtmpfs_create_node(dev);
1858         }
1859
1860         /* Notify clients of device addition.  This call must come
1861          * after dpm_sysfs_add() and before kobject_uevent().
1862          */
1863         if (dev->bus)
1864                 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
1865                                              BUS_NOTIFY_ADD_DEVICE, dev);
1866
1867         kobject_uevent(&dev->kobj, KOBJ_ADD);
1868         bus_probe_device(dev);
1869         if (parent)
1870                 klist_add_tail(&dev->p->knode_parent,
1871                                &parent->p->klist_children);
1872
1873         if (dev->class) {
1874                 mutex_lock(&dev->class->p->mutex);
1875                 /* tie the class to the device */
1876                 klist_add_tail(&dev->knode_class,
1877                                &dev->class->p->klist_devices);
1878
1879                 /* notify any interfaces that the device is here */
1880                 list_for_each_entry(class_intf,
1881                                     &dev->class->p->interfaces, node)
1882                         if (class_intf->add_dev)
1883                                 class_intf->add_dev(dev, class_intf);
1884                 mutex_unlock(&dev->class->p->mutex);
1885         }
1886 done:
1887         put_device(dev);
1888         return error;
1889  SysEntryError:
1890         if (MAJOR(dev->devt))
1891                 device_remove_file(dev, &dev_attr_dev);
1892  DevAttrError:
1893         device_pm_remove(dev);
1894         dpm_sysfs_remove(dev);
1895  DPMError:
1896         bus_remove_device(dev);
1897  BusError:
1898         device_remove_attrs(dev);
1899  AttrsError:
1900         device_remove_class_symlinks(dev);
1901  SymlinkError:
1902         device_remove_file(dev, &dev_attr_uevent);
1903  attrError:
1904         kobject_uevent(&dev->kobj, KOBJ_REMOVE);
1905         glue_dir = get_glue_dir(dev);
1906         kobject_del(&dev->kobj);
1907  Error:
1908         cleanup_glue_dir(dev, glue_dir);
1909 parent_error:
1910         put_device(parent);
1911 name_error:
1912         kfree(dev->p);
1913         dev->p = NULL;
1914         goto done;
1915 }
1916 EXPORT_SYMBOL_GPL(device_add);
1917
1918 /**
1919  * device_register - register a device with the system.
1920  * @dev: pointer to the device structure
1921  *
1922  * This happens in two clean steps - initialize the device
1923  * and add it to the system. The two steps can be called
1924  * separately, but this is the easiest and most common.
1925  * I.e. you should only call the two helpers separately if
1926  * have a clearly defined need to use and refcount the device
1927  * before it is added to the hierarchy.
1928  *
1929  * For more information, see the kerneldoc for device_initialize()
1930  * and device_add().
1931  *
1932  * NOTE: _Never_ directly free @dev after calling this function, even
1933  * if it returned an error! Always use put_device() to give up the
1934  * reference initialized in this function instead.
1935  */
1936 int device_register(struct device *dev)
1937 {
1938         device_initialize(dev);
1939         return device_add(dev);
1940 }
1941 EXPORT_SYMBOL_GPL(device_register);
1942
1943 /**
1944  * get_device - increment reference count for device.
1945  * @dev: device.
1946  *
1947  * This simply forwards the call to kobject_get(), though
1948  * we do take care to provide for the case that we get a NULL
1949  * pointer passed in.
1950  */
1951 struct device *get_device(struct device *dev)
1952 {
1953         return dev ? kobj_to_dev(kobject_get(&dev->kobj)) : NULL;
1954 }
1955 EXPORT_SYMBOL_GPL(get_device);
1956
1957 /**
1958  * put_device - decrement reference count.
1959  * @dev: device in question.
1960  */
1961 void put_device(struct device *dev)
1962 {
1963         /* might_sleep(); */
1964         if (dev)
1965                 kobject_put(&dev->kobj);
1966 }
1967 EXPORT_SYMBOL_GPL(put_device);
1968
1969 /**
1970  * device_del - delete device from system.
1971  * @dev: device.
1972  *
1973  * This is the first part of the device unregistration
1974  * sequence. This removes the device from the lists we control
1975  * from here, has it removed from the other driver model
1976  * subsystems it was added to in device_add(), and removes it
1977  * from the kobject hierarchy.
1978  *
1979  * NOTE: this should be called manually _iff_ device_add() was
1980  * also called manually.
1981  */
1982 void device_del(struct device *dev)
1983 {
1984         struct device *parent = dev->parent;
1985         struct kobject *glue_dir = NULL;
1986         struct class_interface *class_intf;
1987
1988         /* Notify clients of device removal.  This call must come
1989          * before dpm_sysfs_remove().
1990          */
1991         if (dev->bus)
1992                 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
1993                                              BUS_NOTIFY_DEL_DEVICE, dev);
1994
1995         dpm_sysfs_remove(dev);
1996         if (parent)
1997                 klist_del(&dev->p->knode_parent);
1998         if (MAJOR(dev->devt)) {
1999                 devtmpfs_delete_node(dev);
2000                 device_remove_sys_dev_entry(dev);
2001                 device_remove_file(dev, &dev_attr_dev);
2002         }
2003         if (dev->class) {
2004                 device_remove_class_symlinks(dev);
2005
2006                 mutex_lock(&dev->class->p->mutex);
2007                 /* notify any interfaces that the device is now gone */
2008                 list_for_each_entry(class_intf,
2009                                     &dev->class->p->interfaces, node)
2010                         if (class_intf->remove_dev)
2011                                 class_intf->remove_dev(dev, class_intf);
2012                 /* remove the device from the class list */
2013                 klist_del(&dev->knode_class);
2014                 mutex_unlock(&dev->class->p->mutex);
2015         }
2016         device_remove_file(dev, &dev_attr_uevent);
2017         device_remove_attrs(dev);
2018         bus_remove_device(dev);
2019         device_pm_remove(dev);
2020         driver_deferred_probe_del(dev);
2021         device_remove_properties(dev);
2022         device_links_purge(dev);
2023
2024         /* Notify the platform of the removal, in case they
2025          * need to do anything...
2026          */
2027         if (platform_notify_remove)
2028                 platform_notify_remove(dev);
2029         if (dev->bus)
2030                 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
2031                                              BUS_NOTIFY_REMOVED_DEVICE, dev);
2032         kobject_uevent(&dev->kobj, KOBJ_REMOVE);
2033         glue_dir = get_glue_dir(dev);
2034         kobject_del(&dev->kobj);
2035         cleanup_glue_dir(dev, glue_dir);
2036         put_device(parent);
2037 }
2038 EXPORT_SYMBOL_GPL(device_del);
2039
2040 /**
2041  * device_unregister - unregister device from system.
2042  * @dev: device going away.
2043  *
2044  * We do this in two parts, like we do device_register(). First,
2045  * we remove it from all the subsystems with device_del(), then
2046  * we decrement the reference count via put_device(). If that
2047  * is the final reference count, the device will be cleaned up
2048  * via device_release() above. Otherwise, the structure will
2049  * stick around until the final reference to the device is dropped.
2050  */
2051 void device_unregister(struct device *dev)
2052 {
2053         pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
2054         device_del(dev);
2055         put_device(dev);
2056 }
2057 EXPORT_SYMBOL_GPL(device_unregister);
2058
2059 static struct device *prev_device(struct klist_iter *i)
2060 {
2061         struct klist_node *n = klist_prev(i);
2062         struct device *dev = NULL;
2063         struct device_private *p;
2064
2065         if (n) {
2066                 p = to_device_private_parent(n);
2067                 dev = p->device;
2068         }
2069         return dev;
2070 }
2071
2072 static struct device *next_device(struct klist_iter *i)
2073 {
2074         struct klist_node *n = klist_next(i);
2075         struct device *dev = NULL;
2076         struct device_private *p;
2077
2078         if (n) {
2079                 p = to_device_private_parent(n);
2080                 dev = p->device;
2081         }
2082         return dev;
2083 }
2084
2085 /**
2086  * device_get_devnode - path of device node file
2087  * @dev: device
2088  * @mode: returned file access mode
2089  * @uid: returned file owner
2090  * @gid: returned file group
2091  * @tmp: possibly allocated string
2092  *
2093  * Return the relative path of a possible device node.
2094  * Non-default names may need to allocate a memory to compose
2095  * a name. This memory is returned in tmp and needs to be
2096  * freed by the caller.
2097  */
2098 const char *device_get_devnode(struct device *dev,
2099                                umode_t *mode, kuid_t *uid, kgid_t *gid,
2100                                const char **tmp)
2101 {
2102         char *s;
2103
2104         *tmp = NULL;
2105
2106         /* the device type may provide a specific name */
2107         if (dev->type && dev->type->devnode)
2108                 *tmp = dev->type->devnode(dev, mode, uid, gid);
2109         if (*tmp)
2110                 return *tmp;
2111
2112         /* the class may provide a specific name */
2113         if (dev->class && dev->class->devnode)
2114                 *tmp = dev->class->devnode(dev, mode);
2115         if (*tmp)
2116                 return *tmp;
2117
2118         /* return name without allocation, tmp == NULL */
2119         if (strchr(dev_name(dev), '!') == NULL)
2120                 return dev_name(dev);
2121
2122         /* replace '!' in the name with '/' */
2123         s = kstrdup(dev_name(dev), GFP_KERNEL);
2124         if (!s)
2125                 return NULL;
2126         strreplace(s, '!', '/');
2127         return *tmp = s;
2128 }
2129
2130 /**
2131  * device_for_each_child - device child iterator.
2132  * @parent: parent struct device.
2133  * @fn: function to be called for each device.
2134  * @data: data for the callback.
2135  *
2136  * Iterate over @parent's child devices, and call @fn for each,
2137  * passing it @data.
2138  *
2139  * We check the return of @fn each time. If it returns anything
2140  * other than 0, we break out and return that value.
2141  */
2142 int device_for_each_child(struct device *parent, void *data,
2143                           int (*fn)(struct device *dev, void *data))
2144 {
2145         struct klist_iter i;
2146         struct device *child;
2147         int error = 0;
2148
2149         if (!parent->p)
2150                 return 0;
2151
2152         klist_iter_init(&parent->p->klist_children, &i);
2153         while (!error && (child = next_device(&i)))
2154                 error = fn(child, data);
2155         klist_iter_exit(&i);
2156         return error;
2157 }
2158 EXPORT_SYMBOL_GPL(device_for_each_child);
2159
2160 /**
2161  * device_for_each_child_reverse - device child iterator in reversed order.
2162  * @parent: parent struct device.
2163  * @fn: function to be called for each device.
2164  * @data: data for the callback.
2165  *
2166  * Iterate over @parent's child devices, and call @fn for each,
2167  * passing it @data.
2168  *
2169  * We check the return of @fn each time. If it returns anything
2170  * other than 0, we break out and return that value.
2171  */
2172 int device_for_each_child_reverse(struct device *parent, void *data,
2173                                   int (*fn)(struct device *dev, void *data))
2174 {
2175         struct klist_iter i;
2176         struct device *child;
2177         int error = 0;
2178
2179         if (!parent->p)
2180                 return 0;
2181
2182         klist_iter_init(&parent->p->klist_children, &i);
2183         while ((child = prev_device(&i)) && !error)
2184                 error = fn(child, data);
2185         klist_iter_exit(&i);
2186         return error;
2187 }
2188 EXPORT_SYMBOL_GPL(device_for_each_child_reverse);
2189
2190 /**
2191  * device_find_child - device iterator for locating a particular device.
2192  * @parent: parent struct device
2193  * @match: Callback function to check device
2194  * @data: Data to pass to match function
2195  *
2196  * This is similar to the device_for_each_child() function above, but it
2197  * returns a reference to a device that is 'found' for later use, as
2198  * determined by the @match callback.
2199  *
2200  * The callback should return 0 if the device doesn't match and non-zero
2201  * if it does.  If the callback returns non-zero and a reference to the
2202  * current device can be obtained, this function will return to the caller
2203  * and not iterate over any more devices.
2204  *
2205  * NOTE: you will need to drop the reference with put_device() after use.
2206  */
2207 struct device *device_find_child(struct device *parent, void *data,
2208                                  int (*match)(struct device *dev, void *data))
2209 {
2210         struct klist_iter i;
2211         struct device *child;
2212
2213         if (!parent)
2214                 return NULL;
2215
2216         klist_iter_init(&parent->p->klist_children, &i);
2217         while ((child = next_device(&i)))
2218                 if (match(child, data) && get_device(child))
2219                         break;
2220         klist_iter_exit(&i);
2221         return child;
2222 }
2223 EXPORT_SYMBOL_GPL(device_find_child);
2224
2225 int __init devices_init(void)
2226 {
2227         devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
2228         if (!devices_kset)
2229                 return -ENOMEM;
2230         dev_kobj = kobject_create_and_add("dev", NULL);
2231         if (!dev_kobj)
2232                 goto dev_kobj_err;
2233         sysfs_dev_block_kobj = kobject_create_and_add("block", dev_kobj);
2234         if (!sysfs_dev_block_kobj)
2235                 goto block_kobj_err;
2236         sysfs_dev_char_kobj = kobject_create_and_add("char", dev_kobj);
2237         if (!sysfs_dev_char_kobj)
2238                 goto char_kobj_err;
2239
2240         return 0;
2241
2242  char_kobj_err:
2243         kobject_put(sysfs_dev_block_kobj);
2244  block_kobj_err:
2245         kobject_put(dev_kobj);
2246  dev_kobj_err:
2247         kset_unregister(devices_kset);
2248         return -ENOMEM;
2249 }
2250
2251 static int device_check_offline(struct device *dev, void *not_used)
2252 {
2253         int ret;
2254
2255         ret = device_for_each_child(dev, NULL, device_check_offline);
2256         if (ret)
2257                 return ret;
2258
2259         return device_supports_offline(dev) && !dev->offline ? -EBUSY : 0;
2260 }
2261
2262 /**
2263  * device_offline - Prepare the device for hot-removal.
2264  * @dev: Device to be put offline.
2265  *
2266  * Execute the device bus type's .offline() callback, if present, to prepare
2267  * the device for a subsequent hot-removal.  If that succeeds, the device must
2268  * not be used until either it is removed or its bus type's .online() callback
2269  * is executed.
2270  *
2271  * Call under device_hotplug_lock.
2272  */
2273 int device_offline(struct device *dev)
2274 {
2275         int ret;
2276
2277         if (dev->offline_disabled)
2278                 return -EPERM;
2279
2280         ret = device_for_each_child(dev, NULL, device_check_offline);
2281         if (ret)
2282                 return ret;
2283
2284         device_lock(dev);
2285         if (device_supports_offline(dev)) {
2286                 if (dev->offline) {
2287                         ret = 1;
2288                 } else {
2289                         ret = dev->bus->offline(dev);
2290                         if (!ret) {
2291                                 kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
2292                                 dev->offline = true;
2293                         }
2294                 }
2295         }
2296         device_unlock(dev);
2297
2298         return ret;
2299 }
2300
2301 /**
2302  * device_online - Put the device back online after successful device_offline().
2303  * @dev: Device to be put back online.
2304  *
2305  * If device_offline() has been successfully executed for @dev, but the device
2306  * has not been removed subsequently, execute its bus type's .online() callback
2307  * to indicate that the device can be used again.
2308  *
2309  * Call under device_hotplug_lock.
2310  */
2311 int device_online(struct device *dev)
2312 {
2313         int ret = 0;
2314
2315         device_lock(dev);
2316         if (device_supports_offline(dev)) {
2317                 if (dev->offline) {
2318                         ret = dev->bus->online(dev);
2319                         if (!ret) {
2320                                 kobject_uevent(&dev->kobj, KOBJ_ONLINE);
2321                                 dev->offline = false;
2322                         }
2323                 } else {
2324                         ret = 1;
2325                 }
2326         }
2327         device_unlock(dev);
2328
2329         return ret;
2330 }
2331
2332 struct root_device {
2333         struct device dev;
2334         struct module *owner;
2335 };
2336
2337 static inline struct root_device *to_root_device(struct device *d)
2338 {
2339         return container_of(d, struct root_device, dev);
2340 }
2341
2342 static void root_device_release(struct device *dev)
2343 {
2344         kfree(to_root_device(dev));
2345 }
2346
2347 /**
2348  * __root_device_register - allocate and register a root device
2349  * @name: root device name
2350  * @owner: owner module of the root device, usually THIS_MODULE
2351  *
2352  * This function allocates a root device and registers it
2353  * using device_register(). In order to free the returned
2354  * device, use root_device_unregister().
2355  *
2356  * Root devices are dummy devices which allow other devices
2357  * to be grouped under /sys/devices. Use this function to
2358  * allocate a root device and then use it as the parent of
2359  * any device which should appear under /sys/devices/{name}
2360  *
2361  * The /sys/devices/{name} directory will also contain a
2362  * 'module' symlink which points to the @owner directory
2363  * in sysfs.
2364  *
2365  * Returns &struct device pointer on success, or ERR_PTR() on error.
2366  *
2367  * Note: You probably want to use root_device_register().
2368  */
2369 struct device *__root_device_register(const char *name, struct module *owner)
2370 {
2371         struct root_device *root;
2372         int err = -ENOMEM;
2373
2374         root = kzalloc(sizeof(struct root_device), GFP_KERNEL);
2375         if (!root)
2376                 return ERR_PTR(err);
2377
2378         err = dev_set_name(&root->dev, "%s", name);
2379         if (err) {
2380                 kfree(root);
2381                 return ERR_PTR(err);
2382         }
2383
2384         root->dev.release = root_device_release;
2385
2386         err = device_register(&root->dev);
2387         if (err) {
2388                 put_device(&root->dev);
2389                 return ERR_PTR(err);
2390         }
2391
2392 #ifdef CONFIG_MODULES   /* gotta find a "cleaner" way to do this */
2393         if (owner) {
2394                 struct module_kobject *mk = &owner->mkobj;
2395
2396                 err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module");
2397                 if (err) {
2398                         device_unregister(&root->dev);
2399                         return ERR_PTR(err);
2400                 }
2401                 root->owner = owner;
2402         }
2403 #endif
2404
2405         return &root->dev;
2406 }
2407 EXPORT_SYMBOL_GPL(__root_device_register);
2408
2409 /**
2410  * root_device_unregister - unregister and free a root device
2411  * @dev: device going away
2412  *
2413  * This function unregisters and cleans up a device that was created by
2414  * root_device_register().
2415  */
2416 void root_device_unregister(struct device *dev)
2417 {
2418         struct root_device *root = to_root_device(dev);
2419
2420         if (root->owner)
2421                 sysfs_remove_link(&root->dev.kobj, "module");
2422
2423         device_unregister(dev);
2424 }
2425 EXPORT_SYMBOL_GPL(root_device_unregister);
2426
2427
2428 static void device_create_release(struct device *dev)
2429 {
2430         pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
2431         kfree(dev);
2432 }
2433
2434 static __printf(6, 0) struct device *
2435 device_create_groups_vargs(struct class *class, struct device *parent,
2436                            dev_t devt, void *drvdata,
2437                            const struct attribute_group **groups,
2438                            const char *fmt, va_list args)
2439 {
2440         struct device *dev = NULL;
2441         int retval = -ENODEV;
2442
2443         if (class == NULL || IS_ERR(class))
2444                 goto error;
2445
2446         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2447         if (!dev) {
2448                 retval = -ENOMEM;
2449                 goto error;
2450         }
2451
2452         device_initialize(dev);
2453         dev->devt = devt;
2454         dev->class = class;
2455         dev->parent = parent;
2456         dev->groups = groups;
2457         dev->release = device_create_release;
2458         dev_set_drvdata(dev, drvdata);
2459
2460         retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
2461         if (retval)
2462                 goto error;
2463
2464         retval = device_add(dev);
2465         if (retval)
2466                 goto error;
2467
2468         return dev;
2469
2470 error:
2471         put_device(dev);
2472         return ERR_PTR(retval);
2473 }
2474
2475 /**
2476  * device_create_vargs - creates a device and registers it with sysfs
2477  * @class: pointer to the struct class that this device should be registered to
2478  * @parent: pointer to the parent struct device of this new device, if any
2479  * @devt: the dev_t for the char device to be added
2480  * @drvdata: the data to be added to the device for callbacks
2481  * @fmt: string for the device's name
2482  * @args: va_list for the device's name
2483  *
2484  * This function can be used by char device classes.  A struct device
2485  * will be created in sysfs, registered to the specified class.
2486  *
2487  * A "dev" file will be created, showing the dev_t for the device, if
2488  * the dev_t is not 0,0.
2489  * If a pointer to a parent struct device is passed in, the newly created
2490  * struct device will be a child of that device in sysfs.
2491  * The pointer to the struct device will be returned from the call.
2492  * Any further sysfs files that might be required can be created using this
2493  * pointer.
2494  *
2495  * Returns &struct device pointer on success, or ERR_PTR() on error.
2496  *
2497  * Note: the struct class passed to this function must have previously
2498  * been created with a call to class_create().
2499  */
2500 struct device *device_create_vargs(struct class *class, struct device *parent,
2501                                    dev_t devt, void *drvdata, const char *fmt,
2502                                    va_list args)
2503 {
2504         return device_create_groups_vargs(class, parent, devt, drvdata, NULL,
2505                                           fmt, args);
2506 }
2507 EXPORT_SYMBOL_GPL(device_create_vargs);
2508
2509 /**
2510  * device_create - creates a device and registers it with sysfs
2511  * @class: pointer to the struct class that this device should be registered to
2512  * @parent: pointer to the parent struct device of this new device, if any
2513  * @devt: the dev_t for the char device to be added
2514  * @drvdata: the data to be added to the device for callbacks
2515  * @fmt: string for the device's name
2516  *
2517  * This function can be used by char device classes.  A struct device
2518  * will be created in sysfs, registered to the specified class.
2519  *
2520  * A "dev" file will be created, showing the dev_t for the device, if
2521  * the dev_t is not 0,0.
2522  * If a pointer to a parent struct device is passed in, the newly created
2523  * struct device will be a child of that device in sysfs.
2524  * The pointer to the struct device will be returned from the call.
2525  * Any further sysfs files that might be required can be created using this
2526  * pointer.
2527  *
2528  * Returns &struct device pointer on success, or ERR_PTR() on error.
2529  *
2530  * Note: the struct class passed to this function must have previously
2531  * been created with a call to class_create().
2532  */
2533 struct device *device_create(struct class *class, struct device *parent,
2534                              dev_t devt, void *drvdata, const char *fmt, ...)
2535 {
2536         va_list vargs;
2537         struct device *dev;
2538
2539         va_start(vargs, fmt);
2540         dev = device_create_vargs(class, parent, devt, drvdata, fmt, vargs);
2541         va_end(vargs);
2542         return dev;
2543 }
2544 EXPORT_SYMBOL_GPL(device_create);
2545
2546 /**
2547  * device_create_with_groups - creates a device and registers it with sysfs
2548  * @class: pointer to the struct class that this device should be registered to
2549  * @parent: pointer to the parent struct device of this new device, if any
2550  * @devt: the dev_t for the char device to be added
2551  * @drvdata: the data to be added to the device for callbacks
2552  * @groups: NULL-terminated list of attribute groups to be created
2553  * @fmt: string for the device's name
2554  *
2555  * This function can be used by char device classes.  A struct device
2556  * will be created in sysfs, registered to the specified class.
2557  * Additional attributes specified in the groups parameter will also
2558  * be created automatically.
2559  *
2560  * A "dev" file will be created, showing the dev_t for the device, if
2561  * the dev_t is not 0,0.
2562  * If a pointer to a parent struct device is passed in, the newly created
2563  * struct device will be a child of that device in sysfs.
2564  * The pointer to the struct device will be returned from the call.
2565  * Any further sysfs files that might be required can be created using this
2566  * pointer.
2567  *
2568  * Returns &struct device pointer on success, or ERR_PTR() on error.
2569  *
2570  * Note: the struct class passed to this function must have previously
2571  * been created with a call to class_create().
2572  */
2573 struct device *device_create_with_groups(struct class *class,
2574                                          struct device *parent, dev_t devt,
2575                                          void *drvdata,
2576                                          const struct attribute_group **groups,
2577                                          const char *fmt, ...)
2578 {
2579         va_list vargs;
2580         struct device *dev;
2581
2582         va_start(vargs, fmt);
2583         dev = device_create_groups_vargs(class, parent, devt, drvdata, groups,
2584                                          fmt, vargs);
2585         va_end(vargs);
2586         return dev;
2587 }
2588 EXPORT_SYMBOL_GPL(device_create_with_groups);
2589
2590 static int __match_devt(struct device *dev, const void *data)
2591 {
2592         const dev_t *devt = data;
2593
2594         return dev->devt == *devt;
2595 }
2596
2597 /**
2598  * device_destroy - removes a device that was created with device_create()
2599  * @class: pointer to the struct class that this device was registered with
2600  * @devt: the dev_t of the device that was previously registered
2601  *
2602  * This call unregisters and cleans up a device that was created with a
2603  * call to device_create().
2604  */
2605 void device_destroy(struct class *class, dev_t devt)
2606 {
2607         struct device *dev;
2608
2609         dev = class_find_device(class, NULL, &devt, __match_devt);
2610         if (dev) {
2611                 put_device(dev);
2612                 device_unregister(dev);
2613         }
2614 }
2615 EXPORT_SYMBOL_GPL(device_destroy);
2616
2617 /**
2618  * device_rename - renames a device
2619  * @dev: the pointer to the struct device to be renamed
2620  * @new_name: the new name of the device
2621  *
2622  * It is the responsibility of the caller to provide mutual
2623  * exclusion between two different calls of device_rename
2624  * on the same device to ensure that new_name is valid and
2625  * won't conflict with other devices.
2626  *
2627  * Note: Don't call this function.  Currently, the networking layer calls this
2628  * function, but that will change.  The following text from Kay Sievers offers
2629  * some insight:
2630  *
2631  * Renaming devices is racy at many levels, symlinks and other stuff are not
2632  * replaced atomically, and you get a "move" uevent, but it's not easy to
2633  * connect the event to the old and new device. Device nodes are not renamed at
2634  * all, there isn't even support for that in the kernel now.
2635  *
2636  * In the meantime, during renaming, your target name might be taken by another
2637  * driver, creating conflicts. Or the old name is taken directly after you
2638  * renamed it -- then you get events for the same DEVPATH, before you even see
2639  * the "move" event. It's just a mess, and nothing new should ever rely on
2640  * kernel device renaming. Besides that, it's not even implemented now for
2641  * other things than (driver-core wise very simple) network devices.
2642  *
2643  * We are currently about to change network renaming in udev to completely
2644  * disallow renaming of devices in the same namespace as the kernel uses,
2645  * because we can't solve the problems properly, that arise with swapping names
2646  * of multiple interfaces without races. Means, renaming of eth[0-9]* will only
2647  * be allowed to some other name than eth[0-9]*, for the aforementioned
2648  * reasons.
2649  *
2650  * Make up a "real" name in the driver before you register anything, or add
2651  * some other attributes for userspace to find the device, or use udev to add
2652  * symlinks -- but never rename kernel devices later, it's a complete mess. We
2653  * don't even want to get into that and try to implement the missing pieces in
2654  * the core. We really have other pieces to fix in the driver core mess. :)
2655  */
2656 int device_rename(struct device *dev, const char *new_name)
2657 {
2658         struct kobject *kobj = &dev->kobj;
2659         char *old_device_name = NULL;
2660         int error;
2661
2662         dev = get_device(dev);
2663         if (!dev)
2664                 return -EINVAL;
2665
2666         dev_dbg(dev, "renaming to %s\n", new_name);
2667
2668         old_device_name = kstrdup(dev_name(dev), GFP_KERNEL);
2669         if (!old_device_name) {
2670                 error = -ENOMEM;
2671                 goto out;
2672         }
2673
2674         if (dev->class) {
2675                 error = sysfs_rename_link_ns(&dev->class->p->subsys.kobj,
2676                                              kobj, old_device_name,
2677                                              new_name, kobject_namespace(kobj));
2678                 if (error)
2679                         goto out;
2680         }
2681
2682         error = kobject_rename(kobj, new_name);
2683         if (error)
2684                 goto out;
2685
2686 out:
2687         put_device(dev);
2688
2689         kfree(old_device_name);
2690
2691         return error;
2692 }
2693 EXPORT_SYMBOL_GPL(device_rename);
2694
2695 static int device_move_class_links(struct device *dev,
2696                                    struct device *old_parent,
2697                                    struct device *new_parent)
2698 {
2699         int error = 0;
2700
2701         if (old_parent)
2702                 sysfs_remove_link(&dev->kobj, "device");
2703         if (new_parent)
2704                 error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
2705                                           "device");
2706         return error;
2707 }
2708
2709 /**
2710  * device_move - moves a device to a new parent
2711  * @dev: the pointer to the struct device to be moved
2712  * @new_parent: the new parent of the device (can be NULL)
2713  * @dpm_order: how to reorder the dpm_list
2714  */
2715 int device_move(struct device *dev, struct device *new_parent,
2716                 enum dpm_order dpm_order)
2717 {
2718         int error;
2719         struct device *old_parent;
2720         struct kobject *new_parent_kobj;
2721
2722         dev = get_device(dev);
2723         if (!dev)
2724                 return -EINVAL;
2725
2726         device_pm_lock();
2727         new_parent = get_device(new_parent);
2728         new_parent_kobj = get_device_parent(dev, new_parent);
2729         if (IS_ERR(new_parent_kobj)) {
2730                 error = PTR_ERR(new_parent_kobj);
2731                 put_device(new_parent);
2732                 goto out;
2733         }
2734
2735         pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev),
2736                  __func__, new_parent ? dev_name(new_parent) : "<NULL>");
2737         error = kobject_move(&dev->kobj, new_parent_kobj);
2738         if (error) {
2739                 cleanup_glue_dir(dev, new_parent_kobj);
2740                 put_device(new_parent);
2741                 goto out;
2742         }
2743         old_parent = dev->parent;
2744         dev->parent = new_parent;
2745         if (old_parent)
2746                 klist_remove(&dev->p->knode_parent);
2747         if (new_parent) {
2748                 klist_add_tail(&dev->p->knode_parent,
2749                                &new_parent->p->klist_children);
2750                 set_dev_node(dev, dev_to_node(new_parent));
2751         }
2752
2753         if (dev->class) {
2754                 error = device_move_class_links(dev, old_parent, new_parent);
2755                 if (error) {
2756                         /* We ignore errors on cleanup since we're hosed anyway... */
2757                         device_move_class_links(dev, new_parent, old_parent);
2758                         if (!kobject_move(&dev->kobj, &old_parent->kobj)) {
2759                                 if (new_parent)
2760                                         klist_remove(&dev->p->knode_parent);
2761                                 dev->parent = old_parent;
2762                                 if (old_parent) {
2763                                         klist_add_tail(&dev->p->knode_parent,
2764                                                        &old_parent->p->klist_children);
2765                                         set_dev_node(dev, dev_to_node(old_parent));
2766                                 }
2767                         }
2768                         cleanup_glue_dir(dev, new_parent_kobj);
2769                         put_device(new_parent);
2770                         goto out;
2771                 }
2772         }
2773         switch (dpm_order) {
2774         case DPM_ORDER_NONE:
2775                 break;
2776         case DPM_ORDER_DEV_AFTER_PARENT:
2777                 device_pm_move_after(dev, new_parent);
2778                 devices_kset_move_after(dev, new_parent);
2779                 break;
2780         case DPM_ORDER_PARENT_BEFORE_DEV:
2781                 device_pm_move_before(new_parent, dev);
2782                 devices_kset_move_before(new_parent, dev);
2783                 break;
2784         case DPM_ORDER_DEV_LAST:
2785                 device_pm_move_last(dev);
2786                 devices_kset_move_last(dev);
2787                 break;
2788         }
2789
2790         put_device(old_parent);
2791 out:
2792         device_pm_unlock();
2793         put_device(dev);
2794         return error;
2795 }
2796 EXPORT_SYMBOL_GPL(device_move);
2797
2798 /**
2799  * device_shutdown - call ->shutdown() on each device to shutdown.
2800  */
2801 void device_shutdown(void)
2802 {
2803         struct device *dev, *parent;
2804
2805         spin_lock(&devices_kset->list_lock);
2806         /*
2807          * Walk the devices list backward, shutting down each in turn.
2808          * Beware that device unplug events may also start pulling
2809          * devices offline, even as the system is shutting down.
2810          */
2811         while (!list_empty(&devices_kset->list)) {
2812                 dev = list_entry(devices_kset->list.prev, struct device,
2813                                 kobj.entry);
2814
2815                 /*
2816                  * hold reference count of device's parent to
2817                  * prevent it from being freed because parent's
2818                  * lock is to be held
2819                  */
2820                 parent = get_device(dev->parent);
2821                 get_device(dev);
2822                 /*
2823                  * Make sure the device is off the kset list, in the
2824                  * event that dev->*->shutdown() doesn't remove it.
2825                  */
2826                 list_del_init(&dev->kobj.entry);
2827                 spin_unlock(&devices_kset->list_lock);
2828
2829                 /* hold lock to avoid race with probe/release */
2830                 if (parent)
2831                         device_lock(parent);
2832                 device_lock(dev);
2833
2834                 /* Don't allow any more runtime suspends */
2835                 pm_runtime_get_noresume(dev);
2836                 pm_runtime_barrier(dev);
2837
2838                 if (dev->class && dev->class->shutdown_pre) {
2839                         if (initcall_debug)
2840                                 dev_info(dev, "shutdown_pre\n");
2841                         dev->class->shutdown_pre(dev);
2842                 }
2843                 if (dev->bus && dev->bus->shutdown) {
2844                         if (initcall_debug)
2845                                 dev_info(dev, "shutdown\n");
2846                         dev->bus->shutdown(dev);
2847                 } else if (dev->driver && dev->driver->shutdown) {
2848                         if (initcall_debug)
2849                                 dev_info(dev, "shutdown\n");
2850                         dev->driver->shutdown(dev);
2851                 }
2852
2853                 device_unlock(dev);
2854                 if (parent)
2855                         device_unlock(parent);
2856
2857                 put_device(dev);
2858                 put_device(parent);
2859
2860                 spin_lock(&devices_kset->list_lock);
2861         }
2862         spin_unlock(&devices_kset->list_lock);
2863 }
2864
2865 /*
2866  * Device logging functions
2867  */
2868
2869 #ifdef CONFIG_PRINTK
2870 static int
2871 create_syslog_header(const struct device *dev, char *hdr, size_t hdrlen)
2872 {
2873         const char *subsys;
2874         size_t pos = 0;
2875
2876         if (dev->class)
2877                 subsys = dev->class->name;
2878         else if (dev->bus)
2879                 subsys = dev->bus->name;
2880         else
2881                 return 0;
2882
2883         pos += snprintf(hdr + pos, hdrlen - pos, "SUBSYSTEM=%s", subsys);
2884         if (pos >= hdrlen)
2885                 goto overflow;
2886
2887         /*
2888          * Add device identifier DEVICE=:
2889          *   b12:8         block dev_t
2890          *   c127:3        char dev_t
2891          *   n8            netdev ifindex
2892          *   +sound:card0  subsystem:devname
2893          */
2894         if (MAJOR(dev->devt)) {
2895                 char c;
2896
2897                 if (strcmp(subsys, "block") == 0)
2898                         c = 'b';
2899                 else
2900                         c = 'c';
2901                 pos++;
2902                 pos += snprintf(hdr + pos, hdrlen - pos,
2903                                 "DEVICE=%c%u:%u",
2904                                 c, MAJOR(dev->devt), MINOR(dev->devt));
2905         } else if (strcmp(subsys, "net") == 0) {
2906                 struct net_device *net = to_net_dev(dev);
2907
2908                 pos++;
2909                 pos += snprintf(hdr + pos, hdrlen - pos,
2910                                 "DEVICE=n%u", net->ifindex);
2911         } else {
2912                 pos++;
2913                 pos += snprintf(hdr + pos, hdrlen - pos,
2914                                 "DEVICE=+%s:%s", subsys, dev_name(dev));
2915         }
2916
2917         if (pos >= hdrlen)
2918                 goto overflow;
2919
2920         return pos;
2921
2922 overflow:
2923         dev_WARN(dev, "device/subsystem name too long");
2924         return 0;
2925 }
2926
2927 int dev_vprintk_emit(int level, const struct device *dev,
2928                      const char *fmt, va_list args)
2929 {
2930         char hdr[128];
2931         size_t hdrlen;
2932
2933         hdrlen = create_syslog_header(dev, hdr, sizeof(hdr));
2934
2935         return vprintk_emit(0, level, hdrlen ? hdr : NULL, hdrlen, fmt, args);
2936 }
2937 EXPORT_SYMBOL(dev_vprintk_emit);
2938
2939 int dev_printk_emit(int level, const struct device *dev, const char *fmt, ...)
2940 {
2941         va_list args;
2942         int r;
2943
2944         va_start(args, fmt);
2945
2946         r = dev_vprintk_emit(level, dev, fmt, args);
2947
2948         va_end(args);
2949
2950         return r;
2951 }
2952 EXPORT_SYMBOL(dev_printk_emit);
2953
2954 static void __dev_printk(const char *level, const struct device *dev,
2955                         struct va_format *vaf)
2956 {
2957         if (dev)
2958                 dev_printk_emit(level[1] - '0', dev, "%s %s: %pV",
2959                                 dev_driver_string(dev), dev_name(dev), vaf);
2960         else
2961                 printk("%s(NULL device *): %pV", level, vaf);
2962 }
2963
2964 void dev_printk(const char *level, const struct device *dev,
2965                 const char *fmt, ...)
2966 {
2967         struct va_format vaf;
2968         va_list args;
2969
2970         va_start(args, fmt);
2971
2972         vaf.fmt = fmt;
2973         vaf.va = &args;
2974
2975         __dev_printk(level, dev, &vaf);
2976
2977         va_end(args);
2978 }
2979 EXPORT_SYMBOL(dev_printk);
2980
2981 #define define_dev_printk_level(func, kern_level)               \
2982 void func(const struct device *dev, const char *fmt, ...)       \
2983 {                                                               \
2984         struct va_format vaf;                                   \
2985         va_list args;                                           \
2986                                                                 \
2987         va_start(args, fmt);                                    \
2988                                                                 \
2989         vaf.fmt = fmt;                                          \
2990         vaf.va = &args;                                         \
2991                                                                 \
2992         __dev_printk(kern_level, dev, &vaf);                    \
2993                                                                 \
2994         va_end(args);                                           \
2995 }                                                               \
2996 EXPORT_SYMBOL(func);
2997
2998 define_dev_printk_level(dev_emerg, KERN_EMERG);
2999 define_dev_printk_level(dev_alert, KERN_ALERT);
3000 define_dev_printk_level(dev_crit, KERN_CRIT);
3001 define_dev_printk_level(dev_err, KERN_ERR);
3002 define_dev_printk_level(dev_warn, KERN_WARNING);
3003 define_dev_printk_level(dev_notice, KERN_NOTICE);
3004 define_dev_printk_level(_dev_info, KERN_INFO);
3005
3006 #endif
3007
3008 static inline bool fwnode_is_primary(struct fwnode_handle *fwnode)
3009 {
3010         return fwnode && !IS_ERR(fwnode->secondary);
3011 }
3012
3013 /**
3014  * set_primary_fwnode - Change the primary firmware node of a given device.
3015  * @dev: Device to handle.
3016  * @fwnode: New primary firmware node of the device.
3017  *
3018  * Set the device's firmware node pointer to @fwnode, but if a secondary
3019  * firmware node of the device is present, preserve it.
3020  */
3021 void set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
3022 {
3023         if (fwnode) {
3024                 struct fwnode_handle *fn = dev->fwnode;
3025
3026                 if (fwnode_is_primary(fn))
3027                         fn = fn->secondary;
3028
3029                 if (fn) {
3030                         WARN_ON(fwnode->secondary);
3031                         fwnode->secondary = fn;
3032                 }
3033                 dev->fwnode = fwnode;
3034         } else {
3035                 dev->fwnode = fwnode_is_primary(dev->fwnode) ?
3036                         dev->fwnode->secondary : NULL;
3037         }
3038 }
3039 EXPORT_SYMBOL_GPL(set_primary_fwnode);
3040
3041 /**
3042  * set_secondary_fwnode - Change the secondary firmware node of a given device.
3043  * @dev: Device to handle.
3044  * @fwnode: New secondary firmware node of the device.
3045  *
3046  * If a primary firmware node of the device is present, set its secondary
3047  * pointer to @fwnode.  Otherwise, set the device's firmware node pointer to
3048  * @fwnode.
3049  */
3050 void set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
3051 {
3052         if (fwnode)
3053                 fwnode->secondary = ERR_PTR(-ENODEV);
3054
3055         if (fwnode_is_primary(dev->fwnode))
3056                 dev->fwnode->secondary = fwnode;
3057         else
3058                 dev->fwnode = fwnode;
3059 }
3060
3061 /**
3062  * device_set_of_node_from_dev - reuse device-tree node of another device
3063  * @dev: device whose device-tree node is being set
3064  * @dev2: device whose device-tree node is being reused
3065  *
3066  * Takes another reference to the new device-tree node after first dropping
3067  * any reference held to the old node.
3068  */
3069 void device_set_of_node_from_dev(struct device *dev, const struct device *dev2)
3070 {
3071         of_node_put(dev->of_node);
3072         dev->of_node = of_node_get(dev2->of_node);
3073         dev->of_node_reused = true;
3074 }
3075 EXPORT_SYMBOL_GPL(device_set_of_node_from_dev);