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