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