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