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