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