OSDN Git Service

146d8c081695cfecf51ea02d77bc5bf932fea307
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / drivers / base / core.c
1 /*
2  * drivers/base/core.c - core driver model code (device registration, etc)
3  *
4  * Copyright (c) 2002-3 Patrick Mochel
5  * Copyright (c) 2002-3 Open Source Development Labs
6  * Copyright (c) 2006 Greg Kroah-Hartman <gregkh@suse.de>
7  * Copyright (c) 2006 Novell, Inc.
8  *
9  * This file is released under the GPLv2
10  *
11  */
12
13 #include <linux/cpufreq.h>
14 #include <linux/device.h>
15 #include <linux/err.h>
16 #include <linux/fwnode.h>
17 #include <linux/init.h>
18 #include <linux/module.h>
19 #include <linux/slab.h>
20 #include <linux/string.h>
21 #include <linux/kdev_t.h>
22 #include <linux/notifier.h>
23 #include <linux/of.h>
24 #include <linux/of_device.h>
25 #include <linux/genhd.h>
26 #include <linux/kallsyms.h>
27 #include <linux/mutex.h>
28 #include <linux/pm_runtime.h>
29 #include <linux/netdevice.h>
30 #include <linux/sysfs.h>
31
32 #include "base.h"
33 #include "power/power.h"
34
35 #ifdef CONFIG_SYSFS_DEPRECATED
36 #ifdef CONFIG_SYSFS_DEPRECATED_V2
37 long sysfs_deprecated = 1;
38 #else
39 long sysfs_deprecated = 0;
40 #endif
41 static int __init sysfs_deprecated_setup(char *arg)
42 {
43         return kstrtol(arg, 10, &sysfs_deprecated);
44 }
45 early_param("sysfs.deprecated", sysfs_deprecated_setup);
46 #endif
47
48 int (*platform_notify)(struct device *dev) = NULL;
49 int (*platform_notify_remove)(struct device *dev) = NULL;
50 static struct kobject *dev_kobj;
51 struct kobject *sysfs_dev_char_kobj;
52 struct kobject *sysfs_dev_block_kobj;
53
54 static DEFINE_MUTEX(device_hotplug_lock);
55
56 void lock_device_hotplug(void)
57 {
58         mutex_lock(&device_hotplug_lock);
59 }
60
61 void unlock_device_hotplug(void)
62 {
63         mutex_unlock(&device_hotplug_lock);
64 }
65
66 int lock_device_hotplug_sysfs(void)
67 {
68         if (mutex_trylock(&device_hotplug_lock))
69                 return 0;
70
71         /* Avoid busy looping (5 ms of sleep should do). */
72         msleep(5);
73         return restart_syscall();
74 }
75
76 void lock_device_hotplug_assert(void)
77 {
78         lockdep_assert_held(&device_hotplug_lock);
79 }
80
81 #ifdef CONFIG_BLOCK
82 static inline int device_is_not_partition(struct device *dev)
83 {
84         return !(dev->type == &part_type);
85 }
86 #else
87 static inline int device_is_not_partition(struct device *dev)
88 {
89         return 1;
90 }
91 #endif
92
93 /**
94  * dev_driver_string - Return a device's driver name, if at all possible
95  * @dev: struct device to get the name of
96  *
97  * Will return the device's driver's name if it is bound to a device.  If
98  * the device is not bound to a driver, it will return the name of the bus
99  * it is attached to.  If it is not attached to a bus either, an empty
100  * string will be returned.
101  */
102 const char *dev_driver_string(const struct device *dev)
103 {
104         struct device_driver *drv;
105
106         /* dev->driver can change to NULL underneath us because of unbinding,
107          * so be careful about accessing it.  dev->bus and dev->class should
108          * never change once they are set, so they don't need special care.
109          */
110         drv = ACCESS_ONCE(dev->driver);
111         return drv ? drv->name :
112                         (dev->bus ? dev->bus->name :
113                         (dev->class ? dev->class->name : ""));
114 }
115 EXPORT_SYMBOL(dev_driver_string);
116
117 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
118
119 static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
120                              char *buf)
121 {
122         struct device_attribute *dev_attr = to_dev_attr(attr);
123         struct device *dev = kobj_to_dev(kobj);
124         ssize_t ret = -EIO;
125
126         if (dev_attr->show)
127                 ret = dev_attr->show(dev, dev_attr, buf);
128         if (ret >= (ssize_t)PAGE_SIZE) {
129                 print_symbol("dev_attr_show: %s returned bad count\n",
130                                 (unsigned long)dev_attr->show);
131         }
132         return ret;
133 }
134
135 static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
136                               const char *buf, size_t count)
137 {
138         struct device_attribute *dev_attr = to_dev_attr(attr);
139         struct device *dev = kobj_to_dev(kobj);
140         ssize_t ret = -EIO;
141
142         if (dev_attr->store)
143                 ret = dev_attr->store(dev, dev_attr, buf, count);
144         return ret;
145 }
146
147 static const struct sysfs_ops dev_sysfs_ops = {
148         .show   = dev_attr_show,
149         .store  = dev_attr_store,
150 };
151
152 #define to_ext_attr(x) container_of(x, struct dev_ext_attribute, attr)
153
154 ssize_t device_store_ulong(struct device *dev,
155                            struct device_attribute *attr,
156                            const char *buf, size_t size)
157 {
158         struct dev_ext_attribute *ea = to_ext_attr(attr);
159         char *end;
160         unsigned long new = simple_strtoul(buf, &end, 0);
161         if (end == buf)
162                 return -EINVAL;
163         *(unsigned long *)(ea->var) = new;
164         /* Always return full write size even if we didn't consume all */
165         return size;
166 }
167 EXPORT_SYMBOL_GPL(device_store_ulong);
168
169 ssize_t device_show_ulong(struct device *dev,
170                           struct device_attribute *attr,
171                           char *buf)
172 {
173         struct dev_ext_attribute *ea = to_ext_attr(attr);
174         return snprintf(buf, PAGE_SIZE, "%lx\n", *(unsigned long *)(ea->var));
175 }
176 EXPORT_SYMBOL_GPL(device_show_ulong);
177
178 ssize_t device_store_int(struct device *dev,
179                          struct device_attribute *attr,
180                          const char *buf, size_t size)
181 {
182         struct dev_ext_attribute *ea = to_ext_attr(attr);
183         char *end;
184         long new = simple_strtol(buf, &end, 0);
185         if (end == buf || new > INT_MAX || new < INT_MIN)
186                 return -EINVAL;
187         *(int *)(ea->var) = new;
188         /* Always return full write size even if we didn't consume all */
189         return size;
190 }
191 EXPORT_SYMBOL_GPL(device_store_int);
192
193 ssize_t device_show_int(struct device *dev,
194                         struct device_attribute *attr,
195                         char *buf)
196 {
197         struct dev_ext_attribute *ea = to_ext_attr(attr);
198
199         return snprintf(buf, PAGE_SIZE, "%d\n", *(int *)(ea->var));
200 }
201 EXPORT_SYMBOL_GPL(device_show_int);
202
203 ssize_t device_store_bool(struct device *dev, struct device_attribute *attr,
204                           const char *buf, size_t size)
205 {
206         struct dev_ext_attribute *ea = to_ext_attr(attr);
207
208         if (strtobool(buf, ea->var) < 0)
209                 return -EINVAL;
210
211         return size;
212 }
213 EXPORT_SYMBOL_GPL(device_store_bool);
214
215 ssize_t device_show_bool(struct device *dev, struct device_attribute *attr,
216                          char *buf)
217 {
218         struct dev_ext_attribute *ea = to_ext_attr(attr);
219
220         return snprintf(buf, PAGE_SIZE, "%d\n", *(bool *)(ea->var));
221 }
222 EXPORT_SYMBOL_GPL(device_show_bool);
223
224 /**
225  * device_release - free device structure.
226  * @kobj: device's kobject.
227  *
228  * This is called once the reference count for the object
229  * reaches 0. We forward the call to the device's release
230  * method, which should handle actually freeing the structure.
231  */
232 static void device_release(struct kobject *kobj)
233 {
234         struct device *dev = kobj_to_dev(kobj);
235         struct device_private *p = dev->p;
236
237         /*
238          * Some platform devices are driven without driver attached
239          * and managed resources may have been acquired.  Make sure
240          * all resources are released.
241          *
242          * Drivers still can add resources into device after device
243          * is deleted but alive, so release devres here to avoid
244          * possible memory leak.
245          */
246         devres_release_all(dev);
247
248         if (dev->release)
249                 dev->release(dev);
250         else if (dev->type && dev->type->release)
251                 dev->type->release(dev);
252         else if (dev->class && dev->class->dev_release)
253                 dev->class->dev_release(dev);
254         else
255                 WARN(1, KERN_ERR "Device '%s' does not have a release() "
256                         "function, it is broken and must be fixed.\n",
257                         dev_name(dev));
258         kfree(p);
259 }
260
261 static const void *device_namespace(struct kobject *kobj)
262 {
263         struct device *dev = kobj_to_dev(kobj);
264         const void *ns = NULL;
265
266         if (dev->class && dev->class->ns_type)
267                 ns = dev->class->namespace(dev);
268
269         return ns;
270 }
271
272 static struct kobj_type device_ktype = {
273         .release        = device_release,
274         .sysfs_ops      = &dev_sysfs_ops,
275         .namespace      = device_namespace,
276 };
277
278
279 static int dev_uevent_filter(struct kset *kset, struct kobject *kobj)
280 {
281         struct kobj_type *ktype = get_ktype(kobj);
282
283         if (ktype == &device_ktype) {
284                 struct device *dev = kobj_to_dev(kobj);
285                 if (dev->bus)
286                         return 1;
287                 if (dev->class)
288                         return 1;
289         }
290         return 0;
291 }
292
293 static const char *dev_uevent_name(struct kset *kset, struct kobject *kobj)
294 {
295         struct device *dev = kobj_to_dev(kobj);
296
297         if (dev->bus)
298                 return dev->bus->name;
299         if (dev->class)
300                 return dev->class->name;
301         return NULL;
302 }
303
304 static int dev_uevent(struct kset *kset, struct kobject *kobj,
305                       struct kobj_uevent_env *env)
306 {
307         struct device *dev = kobj_to_dev(kobj);
308         int retval = 0;
309
310         /* add device node properties if present */
311         if (MAJOR(dev->devt)) {
312                 const char *tmp;
313                 const char *name;
314                 umode_t mode = 0;
315                 kuid_t uid = GLOBAL_ROOT_UID;
316                 kgid_t gid = GLOBAL_ROOT_GID;
317
318                 add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt));
319                 add_uevent_var(env, "MINOR=%u", MINOR(dev->devt));
320                 name = device_get_devnode(dev, &mode, &uid, &gid, &tmp);
321                 if (name) {
322                         add_uevent_var(env, "DEVNAME=%s", name);
323                         if (mode)
324                                 add_uevent_var(env, "DEVMODE=%#o", mode & 0777);
325                         if (!uid_eq(uid, GLOBAL_ROOT_UID))
326                                 add_uevent_var(env, "DEVUID=%u", from_kuid(&init_user_ns, uid));
327                         if (!gid_eq(gid, GLOBAL_ROOT_GID))
328                                 add_uevent_var(env, "DEVGID=%u", from_kgid(&init_user_ns, gid));
329                         kfree(tmp);
330                 }
331         }
332
333         if (dev->type && dev->type->name)
334                 add_uevent_var(env, "DEVTYPE=%s", dev->type->name);
335
336         if (dev->driver)
337                 add_uevent_var(env, "DRIVER=%s", dev->driver->name);
338
339         /* Add common DT information about the device */
340         of_device_uevent(dev, env);
341
342         /* have the bus specific function add its stuff */
343         if (dev->bus && dev->bus->uevent) {
344                 retval = dev->bus->uevent(dev, env);
345                 if (retval)
346                         pr_debug("device: '%s': %s: bus uevent() returned %d\n",
347                                  dev_name(dev), __func__, retval);
348         }
349
350         /* have the class specific function add its stuff */
351         if (dev->class && dev->class->dev_uevent) {
352                 retval = dev->class->dev_uevent(dev, env);
353                 if (retval)
354                         pr_debug("device: '%s': %s: class uevent() "
355                                  "returned %d\n", dev_name(dev),
356                                  __func__, retval);
357         }
358
359         /* have the device type specific function add its stuff */
360         if (dev->type && dev->type->uevent) {
361                 retval = dev->type->uevent(dev, env);
362                 if (retval)
363                         pr_debug("device: '%s': %s: dev_type uevent() "
364                                  "returned %d\n", dev_name(dev),
365                                  __func__, retval);
366         }
367
368         return retval;
369 }
370
371 static const struct kset_uevent_ops device_uevent_ops = {
372         .filter =       dev_uevent_filter,
373         .name =         dev_uevent_name,
374         .uevent =       dev_uevent,
375 };
376
377 static ssize_t uevent_show(struct device *dev, struct device_attribute *attr,
378                            char *buf)
379 {
380         struct kobject *top_kobj;
381         struct kset *kset;
382         struct kobj_uevent_env *env = NULL;
383         int i;
384         size_t count = 0;
385         int retval;
386
387         /* search the kset, the device belongs to */
388         top_kobj = &dev->kobj;
389         while (!top_kobj->kset && top_kobj->parent)
390                 top_kobj = top_kobj->parent;
391         if (!top_kobj->kset)
392                 goto out;
393
394         kset = top_kobj->kset;
395         if (!kset->uevent_ops || !kset->uevent_ops->uevent)
396                 goto out;
397
398         /* respect filter */
399         if (kset->uevent_ops && kset->uevent_ops->filter)
400                 if (!kset->uevent_ops->filter(kset, &dev->kobj))
401                         goto out;
402
403         env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
404         if (!env)
405                 return -ENOMEM;
406
407         /* let the kset specific function add its keys */
408         retval = kset->uevent_ops->uevent(kset, &dev->kobj, env);
409         if (retval)
410                 goto out;
411
412         /* copy keys to file */
413         for (i = 0; i < env->envp_idx; i++)
414                 count += sprintf(&buf[count], "%s\n", env->envp[i]);
415 out:
416         kfree(env);
417         return count;
418 }
419
420 static ssize_t uevent_store(struct device *dev, struct device_attribute *attr,
421                             const char *buf, size_t count)
422 {
423         enum kobject_action action;
424
425         if (kobject_action_type(buf, count, &action) == 0)
426                 kobject_uevent(&dev->kobj, action);
427         else
428                 dev_err(dev, "uevent: unknown action-string\n");
429         return count;
430 }
431 static DEVICE_ATTR_RW(uevent);
432
433 static ssize_t online_show(struct device *dev, struct device_attribute *attr,
434                            char *buf)
435 {
436         bool val;
437
438         device_lock(dev);
439         val = !dev->offline;
440         device_unlock(dev);
441         return sprintf(buf, "%u\n", val);
442 }
443
444 static ssize_t online_store(struct device *dev, struct device_attribute *attr,
445                             const char *buf, size_t count)
446 {
447         bool val;
448         int ret;
449
450         ret = strtobool(buf, &val);
451         if (ret < 0)
452                 return ret;
453
454         ret = lock_device_hotplug_sysfs();
455         if (ret)
456                 return ret;
457
458         ret = val ? device_online(dev) : device_offline(dev);
459         unlock_device_hotplug();
460         return ret < 0 ? ret : count;
461 }
462 static DEVICE_ATTR_RW(online);
463
464 int device_add_groups(struct device *dev, const struct attribute_group **groups)
465 {
466         return sysfs_create_groups(&dev->kobj, groups);
467 }
468
469 void device_remove_groups(struct device *dev,
470                           const struct attribute_group **groups)
471 {
472         sysfs_remove_groups(&dev->kobj, groups);
473 }
474
475 static int device_add_attrs(struct device *dev)
476 {
477         struct class *class = dev->class;
478         const struct device_type *type = dev->type;
479         int error;
480
481         if (class) {
482                 error = device_add_groups(dev, class->dev_groups);
483                 if (error)
484                         return error;
485         }
486
487         if (type) {
488                 error = device_add_groups(dev, type->groups);
489                 if (error)
490                         goto err_remove_class_groups;
491         }
492
493         error = device_add_groups(dev, dev->groups);
494         if (error)
495                 goto err_remove_type_groups;
496
497         if (device_supports_offline(dev) && !dev->offline_disabled) {
498                 error = device_create_file(dev, &dev_attr_online);
499                 if (error)
500                         goto err_remove_dev_groups;
501         }
502
503         return 0;
504
505  err_remove_dev_groups:
506         device_remove_groups(dev, dev->groups);
507  err_remove_type_groups:
508         if (type)
509                 device_remove_groups(dev, type->groups);
510  err_remove_class_groups:
511         if (class)
512                 device_remove_groups(dev, class->dev_groups);
513
514         return error;
515 }
516
517 static void device_remove_attrs(struct device *dev)
518 {
519         struct class *class = dev->class;
520         const struct device_type *type = dev->type;
521
522         device_remove_file(dev, &dev_attr_online);
523         device_remove_groups(dev, dev->groups);
524
525         if (type)
526                 device_remove_groups(dev, type->groups);
527
528         if (class)
529                 device_remove_groups(dev, class->dev_groups);
530 }
531
532 static ssize_t dev_show(struct device *dev, struct device_attribute *attr,
533                         char *buf)
534 {
535         return print_dev_t(buf, dev->devt);
536 }
537 static DEVICE_ATTR_RO(dev);
538
539 /* /sys/devices/ */
540 struct kset *devices_kset;
541
542 /**
543  * devices_kset_move_before - Move device in the devices_kset's list.
544  * @deva: Device to move.
545  * @devb: Device @deva should come before.
546  */
547 static void devices_kset_move_before(struct device *deva, struct device *devb)
548 {
549         if (!devices_kset)
550                 return;
551         pr_debug("devices_kset: Moving %s before %s\n",
552                  dev_name(deva), dev_name(devb));
553         spin_lock(&devices_kset->list_lock);
554         list_move_tail(&deva->kobj.entry, &devb->kobj.entry);
555         spin_unlock(&devices_kset->list_lock);
556 }
557
558 /**
559  * devices_kset_move_after - Move device in the devices_kset's list.
560  * @deva: Device to move
561  * @devb: Device @deva should come after.
562  */
563 static void devices_kset_move_after(struct device *deva, struct device *devb)
564 {
565         if (!devices_kset)
566                 return;
567         pr_debug("devices_kset: Moving %s after %s\n",
568                  dev_name(deva), dev_name(devb));
569         spin_lock(&devices_kset->list_lock);
570         list_move(&deva->kobj.entry, &devb->kobj.entry);
571         spin_unlock(&devices_kset->list_lock);
572 }
573
574 /**
575  * devices_kset_move_last - move the device to the end of devices_kset's list.
576  * @dev: device to move
577  */
578 void devices_kset_move_last(struct device *dev)
579 {
580         if (!devices_kset)
581                 return;
582         pr_debug("devices_kset: Moving %s to end of list\n", dev_name(dev));
583         spin_lock(&devices_kset->list_lock);
584         list_move_tail(&dev->kobj.entry, &devices_kset->list);
585         spin_unlock(&devices_kset->list_lock);
586 }
587
588 /**
589  * device_create_file - create sysfs attribute file for device.
590  * @dev: device.
591  * @attr: device attribute descriptor.
592  */
593 int device_create_file(struct device *dev,
594                        const struct device_attribute *attr)
595 {
596         int error = 0;
597
598         if (dev) {
599                 WARN(((attr->attr.mode & S_IWUGO) && !attr->store),
600                         "Attribute %s: write permission without 'store'\n",
601                         attr->attr.name);
602                 WARN(((attr->attr.mode & S_IRUGO) && !attr->show),
603                         "Attribute %s: read permission without 'show'\n",
604                         attr->attr.name);
605                 error = sysfs_create_file(&dev->kobj, &attr->attr);
606         }
607
608         return error;
609 }
610 EXPORT_SYMBOL_GPL(device_create_file);
611
612 /**
613  * device_remove_file - remove sysfs attribute file.
614  * @dev: device.
615  * @attr: device attribute descriptor.
616  */
617 void device_remove_file(struct device *dev,
618                         const struct device_attribute *attr)
619 {
620         if (dev)
621                 sysfs_remove_file(&dev->kobj, &attr->attr);
622 }
623 EXPORT_SYMBOL_GPL(device_remove_file);
624
625 /**
626  * device_remove_file_self - remove sysfs attribute file from its own method.
627  * @dev: device.
628  * @attr: device attribute descriptor.
629  *
630  * See kernfs_remove_self() for details.
631  */
632 bool device_remove_file_self(struct device *dev,
633                              const struct device_attribute *attr)
634 {
635         if (dev)
636                 return sysfs_remove_file_self(&dev->kobj, &attr->attr);
637         else
638                 return false;
639 }
640 EXPORT_SYMBOL_GPL(device_remove_file_self);
641
642 /**
643  * device_create_bin_file - create sysfs binary attribute file for device.
644  * @dev: device.
645  * @attr: device binary attribute descriptor.
646  */
647 int device_create_bin_file(struct device *dev,
648                            const struct bin_attribute *attr)
649 {
650         int error = -EINVAL;
651         if (dev)
652                 error = sysfs_create_bin_file(&dev->kobj, attr);
653         return error;
654 }
655 EXPORT_SYMBOL_GPL(device_create_bin_file);
656
657 /**
658  * device_remove_bin_file - remove sysfs binary attribute file
659  * @dev: device.
660  * @attr: device binary attribute descriptor.
661  */
662 void device_remove_bin_file(struct device *dev,
663                             const struct bin_attribute *attr)
664 {
665         if (dev)
666                 sysfs_remove_bin_file(&dev->kobj, attr);
667 }
668 EXPORT_SYMBOL_GPL(device_remove_bin_file);
669
670 static void klist_children_get(struct klist_node *n)
671 {
672         struct device_private *p = to_device_private_parent(n);
673         struct device *dev = p->device;
674
675         get_device(dev);
676 }
677
678 static void klist_children_put(struct klist_node *n)
679 {
680         struct device_private *p = to_device_private_parent(n);
681         struct device *dev = p->device;
682
683         put_device(dev);
684 }
685
686 /**
687  * device_initialize - init device structure.
688  * @dev: device.
689  *
690  * This prepares the device for use by other layers by initializing
691  * its fields.
692  * It is the first half of device_register(), if called by
693  * that function, though it can also be called separately, so one
694  * may use @dev's fields. In particular, get_device()/put_device()
695  * may be used for reference counting of @dev after calling this
696  * function.
697  *
698  * All fields in @dev must be initialized by the caller to 0, except
699  * for those explicitly set to some other value.  The simplest
700  * approach is to use kzalloc() to allocate the structure containing
701  * @dev.
702  *
703  * NOTE: Use put_device() to give up your reference instead of freeing
704  * @dev directly once you have called this function.
705  */
706 void device_initialize(struct device *dev)
707 {
708         dev->kobj.kset = devices_kset;
709         kobject_init(&dev->kobj, &device_ktype);
710         INIT_LIST_HEAD(&dev->dma_pools);
711         mutex_init(&dev->mutex);
712         lockdep_set_novalidate_class(&dev->mutex);
713         spin_lock_init(&dev->devres_lock);
714         INIT_LIST_HEAD(&dev->devres_head);
715         device_pm_init(dev);
716         set_dev_node(dev, -1);
717 #ifdef CONFIG_GENERIC_MSI_IRQ
718         INIT_LIST_HEAD(&dev->msi_list);
719 #endif
720 }
721 EXPORT_SYMBOL_GPL(device_initialize);
722
723 struct kobject *virtual_device_parent(struct device *dev)
724 {
725         static struct kobject *virtual_dir = NULL;
726
727         if (!virtual_dir)
728                 virtual_dir = kobject_create_and_add("virtual",
729                                                      &devices_kset->kobj);
730
731         return virtual_dir;
732 }
733
734 struct class_dir {
735         struct kobject kobj;
736         struct class *class;
737 };
738
739 #define to_class_dir(obj) container_of(obj, struct class_dir, kobj)
740
741 static void class_dir_release(struct kobject *kobj)
742 {
743         struct class_dir *dir = to_class_dir(kobj);
744         kfree(dir);
745 }
746
747 static const
748 struct kobj_ns_type_operations *class_dir_child_ns_type(struct kobject *kobj)
749 {
750         struct class_dir *dir = to_class_dir(kobj);
751         return dir->class->ns_type;
752 }
753
754 static struct kobj_type class_dir_ktype = {
755         .release        = class_dir_release,
756         .sysfs_ops      = &kobj_sysfs_ops,
757         .child_ns_type  = class_dir_child_ns_type
758 };
759
760 static struct kobject *
761 class_dir_create_and_add(struct class *class, struct kobject *parent_kobj)
762 {
763         struct class_dir *dir;
764         int retval;
765
766         dir = kzalloc(sizeof(*dir), GFP_KERNEL);
767         if (!dir)
768                 return ERR_PTR(-ENOMEM);
769
770         dir->class = class;
771         kobject_init(&dir->kobj, &class_dir_ktype);
772
773         dir->kobj.kset = &class->p->glue_dirs;
774
775         retval = kobject_add(&dir->kobj, parent_kobj, "%s", class->name);
776         if (retval < 0) {
777                 kobject_put(&dir->kobj);
778                 return ERR_PTR(retval);
779         }
780         return &dir->kobj;
781 }
782
783 static DEFINE_MUTEX(gdp_mutex);
784
785 static struct kobject *get_device_parent(struct device *dev,
786                                          struct device *parent)
787 {
788         if (dev->class) {
789                 struct kobject *kobj = NULL;
790                 struct kobject *parent_kobj;
791                 struct kobject *k;
792
793 #ifdef CONFIG_BLOCK
794                 /* block disks show up in /sys/block */
795                 if (sysfs_deprecated && dev->class == &block_class) {
796                         if (parent && parent->class == &block_class)
797                                 return &parent->kobj;
798                         return &block_class.p->subsys.kobj;
799                 }
800 #endif
801
802                 /*
803                  * If we have no parent, we live in "virtual".
804                  * Class-devices with a non class-device as parent, live
805                  * in a "glue" directory to prevent namespace collisions.
806                  */
807                 if (parent == NULL)
808                         parent_kobj = virtual_device_parent(dev);
809                 else if (parent->class && !dev->class->ns_type)
810                         return &parent->kobj;
811                 else
812                         parent_kobj = &parent->kobj;
813
814                 mutex_lock(&gdp_mutex);
815
816                 /* find our class-directory at the parent and reference it */
817                 spin_lock(&dev->class->p->glue_dirs.list_lock);
818                 list_for_each_entry(k, &dev->class->p->glue_dirs.list, entry)
819                         if (k->parent == parent_kobj) {
820                                 kobj = kobject_get(k);
821                                 break;
822                         }
823                 spin_unlock(&dev->class->p->glue_dirs.list_lock);
824                 if (kobj) {
825                         mutex_unlock(&gdp_mutex);
826                         return kobj;
827                 }
828
829                 /* or create a new class-directory at the parent device */
830                 k = class_dir_create_and_add(dev->class, parent_kobj);
831                 /* do not emit an uevent for this simple "glue" directory */
832                 mutex_unlock(&gdp_mutex);
833                 return k;
834         }
835
836         /* subsystems can specify a default root directory for their devices */
837         if (!parent && dev->bus && dev->bus->dev_root)
838                 return &dev->bus->dev_root->kobj;
839
840         if (parent)
841                 return &parent->kobj;
842         return NULL;
843 }
844
845 static inline bool live_in_glue_dir(struct kobject *kobj,
846                                     struct device *dev)
847 {
848         if (!kobj || !dev->class ||
849             kobj->kset != &dev->class->p->glue_dirs)
850                 return false;
851         return true;
852 }
853
854 static inline struct kobject *get_glue_dir(struct device *dev)
855 {
856         return dev->kobj.parent;
857 }
858
859 /*
860  * make sure cleaning up dir as the last step, we need to make
861  * sure .release handler of kobject is run with holding the
862  * global lock
863  */
864 static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir)
865 {
866         unsigned int ref;
867
868         /* see if we live in a "glue" directory */
869         if (!live_in_glue_dir(glue_dir, dev))
870                 return;
871
872         mutex_lock(&gdp_mutex);
873         /**
874          * There is a race condition between removing glue directory
875          * and adding a new device under the glue directory.
876          *
877          * CPU1:                                         CPU2:
878          *
879          * device_add()
880          *   get_device_parent()
881          *     class_dir_create_and_add()
882          *       kobject_add_internal()
883          *         create_dir()    // create glue_dir
884          *
885          *                                               device_add()
886          *                                                 get_device_parent()
887          *                                                   kobject_get() // get glue_dir
888          *
889          * device_del()
890          *   cleanup_glue_dir()
891          *     kobject_del(glue_dir)
892          *
893          *                                               kobject_add()
894          *                                                 kobject_add_internal()
895          *                                                   create_dir() // in glue_dir
896          *                                                     sysfs_create_dir_ns()
897          *                                                       kernfs_create_dir_ns(sd)
898          *
899          *       sysfs_remove_dir() // glue_dir->sd=NULL
900          *       sysfs_put()        // free glue_dir->sd
901          *
902          *                                                         // sd is freed
903          *                                                         kernfs_new_node(sd)
904          *                                                           kernfs_get(glue_dir)
905          *                                                           kernfs_add_one()
906          *                                                           kernfs_put()
907          *
908          * Before CPU1 remove last child device under glue dir, if CPU2 add
909          * a new device under glue dir, the glue_dir kobject reference count
910          * will be increase to 2 in kobject_get(k). And CPU2 has been called
911          * kernfs_create_dir_ns(). Meanwhile, CPU1 call sysfs_remove_dir()
912          * and sysfs_put(). This result in glue_dir->sd is freed.
913          *
914          * Then the CPU2 will see a stale "empty" but still potentially used
915          * glue dir around in kernfs_new_node().
916          *
917          * In order to avoid this happening, we also should make sure that
918          * kernfs_node for glue_dir is released in CPU1 only when refcount
919          * for glue_dir kobj is 1.
920          */
921         ref = atomic_read(&glue_dir->kref.refcount);
922         if (!kobject_has_children(glue_dir) && !--ref)
923                 kobject_del(glue_dir);
924         kobject_put(glue_dir);
925         mutex_unlock(&gdp_mutex);
926 }
927
928 static int device_add_class_symlinks(struct device *dev)
929 {
930         struct device_node *of_node = dev_of_node(dev);
931         int error;
932
933         if (of_node) {
934                 error = sysfs_create_link(&dev->kobj, &of_node->kobj,"of_node");
935                 if (error)
936                         dev_warn(dev, "Error %d creating of_node link\n",error);
937                 /* An error here doesn't warrant bringing down the device */
938         }
939
940         if (!dev->class)
941                 return 0;
942
943         error = sysfs_create_link(&dev->kobj,
944                                   &dev->class->p->subsys.kobj,
945                                   "subsystem");
946         if (error)
947                 goto out_devnode;
948
949         if (dev->parent && device_is_not_partition(dev)) {
950                 error = sysfs_create_link(&dev->kobj, &dev->parent->kobj,
951                                           "device");
952                 if (error)
953                         goto out_subsys;
954         }
955
956 #ifdef CONFIG_BLOCK
957         /* /sys/block has directories and does not need symlinks */
958         if (sysfs_deprecated && dev->class == &block_class)
959                 return 0;
960 #endif
961
962         /* link in the class directory pointing to the device */
963         error = sysfs_create_link(&dev->class->p->subsys.kobj,
964                                   &dev->kobj, dev_name(dev));
965         if (error)
966                 goto out_device;
967
968         return 0;
969
970 out_device:
971         sysfs_remove_link(&dev->kobj, "device");
972
973 out_subsys:
974         sysfs_remove_link(&dev->kobj, "subsystem");
975 out_devnode:
976         sysfs_remove_link(&dev->kobj, "of_node");
977         return error;
978 }
979
980 static void device_remove_class_symlinks(struct device *dev)
981 {
982         if (dev_of_node(dev))
983                 sysfs_remove_link(&dev->kobj, "of_node");
984
985         if (!dev->class)
986                 return;
987
988         if (dev->parent && device_is_not_partition(dev))
989                 sysfs_remove_link(&dev->kobj, "device");
990         sysfs_remove_link(&dev->kobj, "subsystem");
991 #ifdef CONFIG_BLOCK
992         if (sysfs_deprecated && dev->class == &block_class)
993                 return;
994 #endif
995         sysfs_delete_link(&dev->class->p->subsys.kobj, &dev->kobj, dev_name(dev));
996 }
997
998 /**
999  * dev_set_name - set a device name
1000  * @dev: device
1001  * @fmt: format string for the device's name
1002  */
1003 int dev_set_name(struct device *dev, const char *fmt, ...)
1004 {
1005         va_list vargs;
1006         int err;
1007
1008         va_start(vargs, fmt);
1009         err = kobject_set_name_vargs(&dev->kobj, fmt, vargs);
1010         va_end(vargs);
1011         return err;
1012 }
1013 EXPORT_SYMBOL_GPL(dev_set_name);
1014
1015 /**
1016  * device_to_dev_kobj - select a /sys/dev/ directory for the device
1017  * @dev: device
1018  *
1019  * By default we select char/ for new entries.  Setting class->dev_obj
1020  * to NULL prevents an entry from being created.  class->dev_kobj must
1021  * be set (or cleared) before any devices are registered to the class
1022  * otherwise device_create_sys_dev_entry() and
1023  * device_remove_sys_dev_entry() will disagree about the presence of
1024  * the link.
1025  */
1026 static struct kobject *device_to_dev_kobj(struct device *dev)
1027 {
1028         struct kobject *kobj;
1029
1030         if (dev->class)
1031                 kobj = dev->class->dev_kobj;
1032         else
1033                 kobj = sysfs_dev_char_kobj;
1034
1035         return kobj;
1036 }
1037
1038 static int device_create_sys_dev_entry(struct device *dev)
1039 {
1040         struct kobject *kobj = device_to_dev_kobj(dev);
1041         int error = 0;
1042         char devt_str[15];
1043
1044         if (kobj) {
1045                 format_dev_t(devt_str, dev->devt);
1046                 error = sysfs_create_link(kobj, &dev->kobj, devt_str);
1047         }
1048
1049         return error;
1050 }
1051
1052 static void device_remove_sys_dev_entry(struct device *dev)
1053 {
1054         struct kobject *kobj = device_to_dev_kobj(dev);
1055         char devt_str[15];
1056
1057         if (kobj) {
1058                 format_dev_t(devt_str, dev->devt);
1059                 sysfs_remove_link(kobj, devt_str);
1060         }
1061 }
1062
1063 int device_private_init(struct device *dev)
1064 {
1065         dev->p = kzalloc(sizeof(*dev->p), GFP_KERNEL);
1066         if (!dev->p)
1067                 return -ENOMEM;
1068         dev->p->device = dev;
1069         klist_init(&dev->p->klist_children, klist_children_get,
1070                    klist_children_put);
1071         INIT_LIST_HEAD(&dev->p->deferred_probe);
1072         return 0;
1073 }
1074
1075 /**
1076  * device_add - add device to device hierarchy.
1077  * @dev: device.
1078  *
1079  * This is part 2 of device_register(), though may be called
1080  * separately _iff_ device_initialize() has been called separately.
1081  *
1082  * This adds @dev to the kobject hierarchy via kobject_add(), adds it
1083  * to the global and sibling lists for the device, then
1084  * adds it to the other relevant subsystems of the driver model.
1085  *
1086  * Do not call this routine or device_register() more than once for
1087  * any device structure.  The driver model core is not designed to work
1088  * with devices that get unregistered and then spring back to life.
1089  * (Among other things, it's very hard to guarantee that all references
1090  * to the previous incarnation of @dev have been dropped.)  Allocate
1091  * and register a fresh new struct device instead.
1092  *
1093  * NOTE: _Never_ directly free @dev after calling this function, even
1094  * if it returned an error! Always use put_device() to give up your
1095  * reference instead.
1096  */
1097 int device_add(struct device *dev)
1098 {
1099         struct device *parent = NULL;
1100         struct kobject *kobj;
1101         struct class_interface *class_intf;
1102         int error = -EINVAL;
1103         struct kobject *glue_dir = NULL;
1104
1105         dev = get_device(dev);
1106         if (!dev)
1107                 goto done;
1108
1109         if (!dev->p) {
1110                 error = device_private_init(dev);
1111                 if (error)
1112                         goto done;
1113         }
1114
1115         /*
1116          * for statically allocated devices, which should all be converted
1117          * some day, we need to initialize the name. We prevent reading back
1118          * the name, and force the use of dev_name()
1119          */
1120         if (dev->init_name) {
1121                 dev_set_name(dev, "%s", dev->init_name);
1122                 dev->init_name = NULL;
1123         }
1124
1125         /* subsystems can specify simple device enumeration */
1126         if (!dev_name(dev) && dev->bus && dev->bus->dev_name)
1127                 dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
1128
1129         if (!dev_name(dev)) {
1130                 error = -EINVAL;
1131                 goto name_error;
1132         }
1133
1134         pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
1135
1136         parent = get_device(dev->parent);
1137         kobj = get_device_parent(dev, parent);
1138         if (IS_ERR(kobj)) {
1139                 error = PTR_ERR(kobj);
1140                 goto parent_error;
1141         }
1142         if (kobj)
1143                 dev->kobj.parent = kobj;
1144
1145         /* use parent numa_node */
1146         if (parent && (dev_to_node(dev) == NUMA_NO_NODE))
1147                 set_dev_node(dev, dev_to_node(parent));
1148
1149         /* first, register with generic layer. */
1150         /* we require the name to be set before, and pass NULL */
1151         error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
1152         if (error) {
1153                 glue_dir = get_glue_dir(dev);
1154                 goto Error;
1155         }
1156
1157         /* notify platform of device entry */
1158         if (platform_notify)
1159                 platform_notify(dev);
1160
1161         error = device_create_file(dev, &dev_attr_uevent);
1162         if (error)
1163                 goto attrError;
1164
1165         error = device_add_class_symlinks(dev);
1166         if (error)
1167                 goto SymlinkError;
1168         error = device_add_attrs(dev);
1169         if (error)
1170                 goto AttrsError;
1171         error = bus_add_device(dev);
1172         if (error)
1173                 goto BusError;
1174         error = dpm_sysfs_add(dev);
1175         if (error)
1176                 goto DPMError;
1177         device_pm_add(dev);
1178
1179         if (MAJOR(dev->devt)) {
1180                 error = device_create_file(dev, &dev_attr_dev);
1181                 if (error)
1182                         goto DevAttrError;
1183
1184                 error = device_create_sys_dev_entry(dev);
1185                 if (error)
1186                         goto SysEntryError;
1187
1188                 devtmpfs_create_node(dev);
1189         }
1190
1191         /* Notify clients of device addition.  This call must come
1192          * after dpm_sysfs_add() and before kobject_uevent().
1193          */
1194         if (dev->bus)
1195                 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
1196                                              BUS_NOTIFY_ADD_DEVICE, dev);
1197
1198         kobject_uevent(&dev->kobj, KOBJ_ADD);
1199         bus_probe_device(dev);
1200         if (parent)
1201                 klist_add_tail(&dev->p->knode_parent,
1202                                &parent->p->klist_children);
1203
1204         if (dev->class) {
1205                 mutex_lock(&dev->class->p->mutex);
1206                 /* tie the class to the device */
1207                 klist_add_tail(&dev->knode_class,
1208                                &dev->class->p->klist_devices);
1209
1210                 /* notify any interfaces that the device is here */
1211                 list_for_each_entry(class_intf,
1212                                     &dev->class->p->interfaces, node)
1213                         if (class_intf->add_dev)
1214                                 class_intf->add_dev(dev, class_intf);
1215                 mutex_unlock(&dev->class->p->mutex);
1216         }
1217 done:
1218         put_device(dev);
1219         return error;
1220  SysEntryError:
1221         if (MAJOR(dev->devt))
1222                 device_remove_file(dev, &dev_attr_dev);
1223  DevAttrError:
1224         device_pm_remove(dev);
1225         dpm_sysfs_remove(dev);
1226  DPMError:
1227         bus_remove_device(dev);
1228  BusError:
1229         device_remove_attrs(dev);
1230  AttrsError:
1231         device_remove_class_symlinks(dev);
1232  SymlinkError:
1233         device_remove_file(dev, &dev_attr_uevent);
1234  attrError:
1235         kobject_uevent(&dev->kobj, KOBJ_REMOVE);
1236         glue_dir = get_glue_dir(dev);
1237         kobject_del(&dev->kobj);
1238  Error:
1239         cleanup_glue_dir(dev, glue_dir);
1240 parent_error:
1241         put_device(parent);
1242 name_error:
1243         kfree(dev->p);
1244         dev->p = NULL;
1245         goto done;
1246 }
1247 EXPORT_SYMBOL_GPL(device_add);
1248
1249 /**
1250  * device_register - register a device with the system.
1251  * @dev: pointer to the device structure
1252  *
1253  * This happens in two clean steps - initialize the device
1254  * and add it to the system. The two steps can be called
1255  * separately, but this is the easiest and most common.
1256  * I.e. you should only call the two helpers separately if
1257  * have a clearly defined need to use and refcount the device
1258  * before it is added to the hierarchy.
1259  *
1260  * For more information, see the kerneldoc for device_initialize()
1261  * and device_add().
1262  *
1263  * NOTE: _Never_ directly free @dev after calling this function, even
1264  * if it returned an error! Always use put_device() to give up the
1265  * reference initialized in this function instead.
1266  */
1267 int device_register(struct device *dev)
1268 {
1269         device_initialize(dev);
1270         return device_add(dev);
1271 }
1272 EXPORT_SYMBOL_GPL(device_register);
1273
1274 /**
1275  * get_device - increment reference count for device.
1276  * @dev: device.
1277  *
1278  * This simply forwards the call to kobject_get(), though
1279  * we do take care to provide for the case that we get a NULL
1280  * pointer passed in.
1281  */
1282 struct device *get_device(struct device *dev)
1283 {
1284         return dev ? kobj_to_dev(kobject_get(&dev->kobj)) : NULL;
1285 }
1286 EXPORT_SYMBOL_GPL(get_device);
1287
1288 /**
1289  * put_device - decrement reference count.
1290  * @dev: device in question.
1291  */
1292 void put_device(struct device *dev)
1293 {
1294         /* might_sleep(); */
1295         if (dev)
1296                 kobject_put(&dev->kobj);
1297 }
1298 EXPORT_SYMBOL_GPL(put_device);
1299
1300 /**
1301  * device_del - delete device from system.
1302  * @dev: device.
1303  *
1304  * This is the first part of the device unregistration
1305  * sequence. This removes the device from the lists we control
1306  * from here, has it removed from the other driver model
1307  * subsystems it was added to in device_add(), and removes it
1308  * from the kobject hierarchy.
1309  *
1310  * NOTE: this should be called manually _iff_ device_add() was
1311  * also called manually.
1312  */
1313 void device_del(struct device *dev)
1314 {
1315         struct device *parent = dev->parent;
1316         struct kobject *glue_dir = NULL;
1317         struct class_interface *class_intf;
1318
1319         /* Notify clients of device removal.  This call must come
1320          * before dpm_sysfs_remove().
1321          */
1322         if (dev->bus)
1323                 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
1324                                              BUS_NOTIFY_DEL_DEVICE, dev);
1325         dpm_sysfs_remove(dev);
1326         if (parent)
1327                 klist_del(&dev->p->knode_parent);
1328         if (MAJOR(dev->devt)) {
1329                 devtmpfs_delete_node(dev);
1330                 device_remove_sys_dev_entry(dev);
1331                 device_remove_file(dev, &dev_attr_dev);
1332         }
1333         if (dev->class) {
1334                 device_remove_class_symlinks(dev);
1335
1336                 mutex_lock(&dev->class->p->mutex);
1337                 /* notify any interfaces that the device is now gone */
1338                 list_for_each_entry(class_intf,
1339                                     &dev->class->p->interfaces, node)
1340                         if (class_intf->remove_dev)
1341                                 class_intf->remove_dev(dev, class_intf);
1342                 /* remove the device from the class list */
1343                 klist_del(&dev->knode_class);
1344                 mutex_unlock(&dev->class->p->mutex);
1345         }
1346         device_remove_file(dev, &dev_attr_uevent);
1347         device_remove_attrs(dev);
1348         bus_remove_device(dev);
1349         device_pm_remove(dev);
1350         driver_deferred_probe_del(dev);
1351
1352         /* Notify the platform of the removal, in case they
1353          * need to do anything...
1354          */
1355         if (platform_notify_remove)
1356                 platform_notify_remove(dev);
1357         if (dev->bus)
1358                 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
1359                                              BUS_NOTIFY_REMOVED_DEVICE, dev);
1360         kobject_uevent(&dev->kobj, KOBJ_REMOVE);
1361         glue_dir = get_glue_dir(dev);
1362         kobject_del(&dev->kobj);
1363         cleanup_glue_dir(dev, glue_dir);
1364         put_device(parent);
1365 }
1366 EXPORT_SYMBOL_GPL(device_del);
1367
1368 /**
1369  * device_unregister - unregister device from system.
1370  * @dev: device going away.
1371  *
1372  * We do this in two parts, like we do device_register(). First,
1373  * we remove it from all the subsystems with device_del(), then
1374  * we decrement the reference count via put_device(). If that
1375  * is the final reference count, the device will be cleaned up
1376  * via device_release() above. Otherwise, the structure will
1377  * stick around until the final reference to the device is dropped.
1378  */
1379 void device_unregister(struct device *dev)
1380 {
1381         pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
1382         device_del(dev);
1383         put_device(dev);
1384 }
1385 EXPORT_SYMBOL_GPL(device_unregister);
1386
1387 static struct device *prev_device(struct klist_iter *i)
1388 {
1389         struct klist_node *n = klist_prev(i);
1390         struct device *dev = NULL;
1391         struct device_private *p;
1392
1393         if (n) {
1394                 p = to_device_private_parent(n);
1395                 dev = p->device;
1396         }
1397         return dev;
1398 }
1399
1400 static struct device *next_device(struct klist_iter *i)
1401 {
1402         struct klist_node *n = klist_next(i);
1403         struct device *dev = NULL;
1404         struct device_private *p;
1405
1406         if (n) {
1407                 p = to_device_private_parent(n);
1408                 dev = p->device;
1409         }
1410         return dev;
1411 }
1412
1413 /**
1414  * device_get_devnode - path of device node file
1415  * @dev: device
1416  * @mode: returned file access mode
1417  * @uid: returned file owner
1418  * @gid: returned file group
1419  * @tmp: possibly allocated string
1420  *
1421  * Return the relative path of a possible device node.
1422  * Non-default names may need to allocate a memory to compose
1423  * a name. This memory is returned in tmp and needs to be
1424  * freed by the caller.
1425  */
1426 const char *device_get_devnode(struct device *dev,
1427                                umode_t *mode, kuid_t *uid, kgid_t *gid,
1428                                const char **tmp)
1429 {
1430         char *s;
1431
1432         *tmp = NULL;
1433
1434         /* the device type may provide a specific name */
1435         if (dev->type && dev->type->devnode)
1436                 *tmp = dev->type->devnode(dev, mode, uid, gid);
1437         if (*tmp)
1438                 return *tmp;
1439
1440         /* the class may provide a specific name */
1441         if (dev->class && dev->class->devnode)
1442                 *tmp = dev->class->devnode(dev, mode);
1443         if (*tmp)
1444                 return *tmp;
1445
1446         /* return name without allocation, tmp == NULL */
1447         if (strchr(dev_name(dev), '!') == NULL)
1448                 return dev_name(dev);
1449
1450         /* replace '!' in the name with '/' */
1451         s = kstrdup(dev_name(dev), GFP_KERNEL);
1452         if (!s)
1453                 return NULL;
1454         strreplace(s, '!', '/');
1455         return *tmp = s;
1456 }
1457
1458 /**
1459  * device_for_each_child - device child iterator.
1460  * @parent: parent struct device.
1461  * @fn: function to be called for each device.
1462  * @data: data for the callback.
1463  *
1464  * Iterate over @parent's child devices, and call @fn for each,
1465  * passing it @data.
1466  *
1467  * We check the return of @fn each time. If it returns anything
1468  * other than 0, we break out and return that value.
1469  */
1470 int device_for_each_child(struct device *parent, void *data,
1471                           int (*fn)(struct device *dev, void *data))
1472 {
1473         struct klist_iter i;
1474         struct device *child;
1475         int error = 0;
1476
1477         if (!parent->p)
1478                 return 0;
1479
1480         klist_iter_init(&parent->p->klist_children, &i);
1481         while ((child = next_device(&i)) && !error)
1482                 error = fn(child, data);
1483         klist_iter_exit(&i);
1484         return error;
1485 }
1486 EXPORT_SYMBOL_GPL(device_for_each_child);
1487
1488 /**
1489  * device_for_each_child_reverse - device child iterator in reversed order.
1490  * @parent: parent struct device.
1491  * @fn: function to be called for each device.
1492  * @data: data for the callback.
1493  *
1494  * Iterate over @parent's child devices, and call @fn for each,
1495  * passing it @data.
1496  *
1497  * We check the return of @fn each time. If it returns anything
1498  * other than 0, we break out and return that value.
1499  */
1500 int device_for_each_child_reverse(struct device *parent, void *data,
1501                                   int (*fn)(struct device *dev, void *data))
1502 {
1503         struct klist_iter i;
1504         struct device *child;
1505         int error = 0;
1506
1507         if (!parent->p)
1508                 return 0;
1509
1510         klist_iter_init(&parent->p->klist_children, &i);
1511         while ((child = prev_device(&i)) && !error)
1512                 error = fn(child, data);
1513         klist_iter_exit(&i);
1514         return error;
1515 }
1516 EXPORT_SYMBOL_GPL(device_for_each_child_reverse);
1517
1518 /**
1519  * device_find_child - device iterator for locating a particular device.
1520  * @parent: parent struct device
1521  * @match: Callback function to check device
1522  * @data: Data to pass to match function
1523  *
1524  * This is similar to the device_for_each_child() function above, but it
1525  * returns a reference to a device that is 'found' for later use, as
1526  * determined by the @match callback.
1527  *
1528  * The callback should return 0 if the device doesn't match and non-zero
1529  * if it does.  If the callback returns non-zero and a reference to the
1530  * current device can be obtained, this function will return to the caller
1531  * and not iterate over any more devices.
1532  *
1533  * NOTE: you will need to drop the reference with put_device() after use.
1534  */
1535 struct device *device_find_child(struct device *parent, void *data,
1536                                  int (*match)(struct device *dev, void *data))
1537 {
1538         struct klist_iter i;
1539         struct device *child;
1540
1541         if (!parent)
1542                 return NULL;
1543
1544         klist_iter_init(&parent->p->klist_children, &i);
1545         while ((child = next_device(&i)))
1546                 if (match(child, data) && get_device(child))
1547                         break;
1548         klist_iter_exit(&i);
1549         return child;
1550 }
1551 EXPORT_SYMBOL_GPL(device_find_child);
1552
1553 int __init devices_init(void)
1554 {
1555         devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
1556         if (!devices_kset)
1557                 return -ENOMEM;
1558         dev_kobj = kobject_create_and_add("dev", NULL);
1559         if (!dev_kobj)
1560                 goto dev_kobj_err;
1561         sysfs_dev_block_kobj = kobject_create_and_add("block", dev_kobj);
1562         if (!sysfs_dev_block_kobj)
1563                 goto block_kobj_err;
1564         sysfs_dev_char_kobj = kobject_create_and_add("char", dev_kobj);
1565         if (!sysfs_dev_char_kobj)
1566                 goto char_kobj_err;
1567
1568         return 0;
1569
1570  char_kobj_err:
1571         kobject_put(sysfs_dev_block_kobj);
1572  block_kobj_err:
1573         kobject_put(dev_kobj);
1574  dev_kobj_err:
1575         kset_unregister(devices_kset);
1576         return -ENOMEM;
1577 }
1578
1579 static int device_check_offline(struct device *dev, void *not_used)
1580 {
1581         int ret;
1582
1583         ret = device_for_each_child(dev, NULL, device_check_offline);
1584         if (ret)
1585                 return ret;
1586
1587         return device_supports_offline(dev) && !dev->offline ? -EBUSY : 0;
1588 }
1589
1590 /**
1591  * device_offline - Prepare the device for hot-removal.
1592  * @dev: Device to be put offline.
1593  *
1594  * Execute the device bus type's .offline() callback, if present, to prepare
1595  * the device for a subsequent hot-removal.  If that succeeds, the device must
1596  * not be used until either it is removed or its bus type's .online() callback
1597  * is executed.
1598  *
1599  * Call under device_hotplug_lock.
1600  */
1601 int device_offline(struct device *dev)
1602 {
1603         int ret;
1604
1605         if (dev->offline_disabled)
1606                 return -EPERM;
1607
1608         ret = device_for_each_child(dev, NULL, device_check_offline);
1609         if (ret)
1610                 return ret;
1611
1612         device_lock(dev);
1613         if (device_supports_offline(dev)) {
1614                 if (dev->offline) {
1615                         ret = 1;
1616                 } else {
1617                         ret = dev->bus->offline(dev);
1618                         if (!ret) {
1619                                 kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
1620                                 dev->offline = true;
1621                         }
1622                 }
1623         }
1624         device_unlock(dev);
1625
1626         return ret;
1627 }
1628
1629 /**
1630  * device_online - Put the device back online after successful device_offline().
1631  * @dev: Device to be put back online.
1632  *
1633  * If device_offline() has been successfully executed for @dev, but the device
1634  * has not been removed subsequently, execute its bus type's .online() callback
1635  * to indicate that the device can be used again.
1636  *
1637  * Call under device_hotplug_lock.
1638  */
1639 int device_online(struct device *dev)
1640 {
1641         int ret = 0;
1642
1643         device_lock(dev);
1644         if (device_supports_offline(dev)) {
1645                 if (dev->offline) {
1646                         ret = dev->bus->online(dev);
1647                         if (!ret) {
1648                                 kobject_uevent(&dev->kobj, KOBJ_ONLINE);
1649                                 dev->offline = false;
1650                         }
1651                 } else {
1652                         ret = 1;
1653                 }
1654         }
1655         device_unlock(dev);
1656
1657         return ret;
1658 }
1659
1660 struct root_device {
1661         struct device dev;
1662         struct module *owner;
1663 };
1664
1665 static inline struct root_device *to_root_device(struct device *d)
1666 {
1667         return container_of(d, struct root_device, dev);
1668 }
1669
1670 static void root_device_release(struct device *dev)
1671 {
1672         kfree(to_root_device(dev));
1673 }
1674
1675 /**
1676  * __root_device_register - allocate and register a root device
1677  * @name: root device name
1678  * @owner: owner module of the root device, usually THIS_MODULE
1679  *
1680  * This function allocates a root device and registers it
1681  * using device_register(). In order to free the returned
1682  * device, use root_device_unregister().
1683  *
1684  * Root devices are dummy devices which allow other devices
1685  * to be grouped under /sys/devices. Use this function to
1686  * allocate a root device and then use it as the parent of
1687  * any device which should appear under /sys/devices/{name}
1688  *
1689  * The /sys/devices/{name} directory will also contain a
1690  * 'module' symlink which points to the @owner directory
1691  * in sysfs.
1692  *
1693  * Returns &struct device pointer on success, or ERR_PTR() on error.
1694  *
1695  * Note: You probably want to use root_device_register().
1696  */
1697 struct device *__root_device_register(const char *name, struct module *owner)
1698 {
1699         struct root_device *root;
1700         int err = -ENOMEM;
1701
1702         root = kzalloc(sizeof(struct root_device), GFP_KERNEL);
1703         if (!root)
1704                 return ERR_PTR(err);
1705
1706         err = dev_set_name(&root->dev, "%s", name);
1707         if (err) {
1708                 kfree(root);
1709                 return ERR_PTR(err);
1710         }
1711
1712         root->dev.release = root_device_release;
1713
1714         err = device_register(&root->dev);
1715         if (err) {
1716                 put_device(&root->dev);
1717                 return ERR_PTR(err);
1718         }
1719
1720 #ifdef CONFIG_MODULES   /* gotta find a "cleaner" way to do this */
1721         if (owner) {
1722                 struct module_kobject *mk = &owner->mkobj;
1723
1724                 err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module");
1725                 if (err) {
1726                         device_unregister(&root->dev);
1727                         return ERR_PTR(err);
1728                 }
1729                 root->owner = owner;
1730         }
1731 #endif
1732
1733         return &root->dev;
1734 }
1735 EXPORT_SYMBOL_GPL(__root_device_register);
1736
1737 /**
1738  * root_device_unregister - unregister and free a root device
1739  * @dev: device going away
1740  *
1741  * This function unregisters and cleans up a device that was created by
1742  * root_device_register().
1743  */
1744 void root_device_unregister(struct device *dev)
1745 {
1746         struct root_device *root = to_root_device(dev);
1747
1748         if (root->owner)
1749                 sysfs_remove_link(&root->dev.kobj, "module");
1750
1751         device_unregister(dev);
1752 }
1753 EXPORT_SYMBOL_GPL(root_device_unregister);
1754
1755
1756 static void device_create_release(struct device *dev)
1757 {
1758         pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
1759         kfree(dev);
1760 }
1761
1762 static struct device *
1763 device_create_groups_vargs(struct class *class, struct device *parent,
1764                            dev_t devt, void *drvdata,
1765                            const struct attribute_group **groups,
1766                            const char *fmt, va_list args)
1767 {
1768         struct device *dev = NULL;
1769         int retval = -ENODEV;
1770
1771         if (class == NULL || IS_ERR(class))
1772                 goto error;
1773
1774         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1775         if (!dev) {
1776                 retval = -ENOMEM;
1777                 goto error;
1778         }
1779
1780         device_initialize(dev);
1781         dev->devt = devt;
1782         dev->class = class;
1783         dev->parent = parent;
1784         dev->groups = groups;
1785         dev->release = device_create_release;
1786         dev_set_drvdata(dev, drvdata);
1787
1788         retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
1789         if (retval)
1790                 goto error;
1791
1792         retval = device_add(dev);
1793         if (retval)
1794                 goto error;
1795
1796         return dev;
1797
1798 error:
1799         put_device(dev);
1800         return ERR_PTR(retval);
1801 }
1802
1803 /**
1804  * device_create_vargs - creates a device and registers it with sysfs
1805  * @class: pointer to the struct class that this device should be registered to
1806  * @parent: pointer to the parent struct device of this new device, if any
1807  * @devt: the dev_t for the char device to be added
1808  * @drvdata: the data to be added to the device for callbacks
1809  * @fmt: string for the device's name
1810  * @args: va_list for the device's name
1811  *
1812  * This function can be used by char device classes.  A struct device
1813  * will be created in sysfs, registered to the specified class.
1814  *
1815  * A "dev" file will be created, showing the dev_t for the device, if
1816  * the dev_t is not 0,0.
1817  * If a pointer to a parent struct device is passed in, the newly created
1818  * struct device will be a child of that device in sysfs.
1819  * The pointer to the struct device will be returned from the call.
1820  * Any further sysfs files that might be required can be created using this
1821  * pointer.
1822  *
1823  * Returns &struct device pointer on success, or ERR_PTR() on error.
1824  *
1825  * Note: the struct class passed to this function must have previously
1826  * been created with a call to class_create().
1827  */
1828 struct device *device_create_vargs(struct class *class, struct device *parent,
1829                                    dev_t devt, void *drvdata, const char *fmt,
1830                                    va_list args)
1831 {
1832         return device_create_groups_vargs(class, parent, devt, drvdata, NULL,
1833                                           fmt, args);
1834 }
1835 EXPORT_SYMBOL_GPL(device_create_vargs);
1836
1837 /**
1838  * device_create - creates a device and registers it with sysfs
1839  * @class: pointer to the struct class that this device should be registered to
1840  * @parent: pointer to the parent struct device of this new device, if any
1841  * @devt: the dev_t for the char device to be added
1842  * @drvdata: the data to be added to the device for callbacks
1843  * @fmt: string for the device's name
1844  *
1845  * This function can be used by char device classes.  A struct device
1846  * will be created in sysfs, registered to the specified class.
1847  *
1848  * A "dev" file will be created, showing the dev_t for the device, if
1849  * the dev_t is not 0,0.
1850  * If a pointer to a parent struct device is passed in, the newly created
1851  * struct device will be a child of that device in sysfs.
1852  * The pointer to the struct device will be returned from the call.
1853  * Any further sysfs files that might be required can be created using this
1854  * pointer.
1855  *
1856  * Returns &struct device pointer on success, or ERR_PTR() on error.
1857  *
1858  * Note: the struct class passed to this function must have previously
1859  * been created with a call to class_create().
1860  */
1861 struct device *device_create(struct class *class, struct device *parent,
1862                              dev_t devt, void *drvdata, const char *fmt, ...)
1863 {
1864         va_list vargs;
1865         struct device *dev;
1866
1867         va_start(vargs, fmt);
1868         dev = device_create_vargs(class, parent, devt, drvdata, fmt, vargs);
1869         va_end(vargs);
1870         return dev;
1871 }
1872 EXPORT_SYMBOL_GPL(device_create);
1873
1874 /**
1875  * device_create_with_groups - creates a device and registers it with sysfs
1876  * @class: pointer to the struct class that this device should be registered to
1877  * @parent: pointer to the parent struct device of this new device, if any
1878  * @devt: the dev_t for the char device to be added
1879  * @drvdata: the data to be added to the device for callbacks
1880  * @groups: NULL-terminated list of attribute groups to be created
1881  * @fmt: string for the device's name
1882  *
1883  * This function can be used by char device classes.  A struct device
1884  * will be created in sysfs, registered to the specified class.
1885  * Additional attributes specified in the groups parameter will also
1886  * be created automatically.
1887  *
1888  * A "dev" file will be created, showing the dev_t for the device, if
1889  * the dev_t is not 0,0.
1890  * If a pointer to a parent struct device is passed in, the newly created
1891  * struct device will be a child of that device in sysfs.
1892  * The pointer to the struct device will be returned from the call.
1893  * Any further sysfs files that might be required can be created using this
1894  * pointer.
1895  *
1896  * Returns &struct device pointer on success, or ERR_PTR() on error.
1897  *
1898  * Note: the struct class passed to this function must have previously
1899  * been created with a call to class_create().
1900  */
1901 struct device *device_create_with_groups(struct class *class,
1902                                          struct device *parent, dev_t devt,
1903                                          void *drvdata,
1904                                          const struct attribute_group **groups,
1905                                          const char *fmt, ...)
1906 {
1907         va_list vargs;
1908         struct device *dev;
1909
1910         va_start(vargs, fmt);
1911         dev = device_create_groups_vargs(class, parent, devt, drvdata, groups,
1912                                          fmt, vargs);
1913         va_end(vargs);
1914         return dev;
1915 }
1916 EXPORT_SYMBOL_GPL(device_create_with_groups);
1917
1918 static int __match_devt(struct device *dev, const void *data)
1919 {
1920         const dev_t *devt = data;
1921
1922         return dev->devt == *devt;
1923 }
1924
1925 /**
1926  * device_destroy - removes a device that was created with device_create()
1927  * @class: pointer to the struct class that this device was registered with
1928  * @devt: the dev_t of the device that was previously registered
1929  *
1930  * This call unregisters and cleans up a device that was created with a
1931  * call to device_create().
1932  */
1933 void device_destroy(struct class *class, dev_t devt)
1934 {
1935         struct device *dev;
1936
1937         dev = class_find_device(class, NULL, &devt, __match_devt);
1938         if (dev) {
1939                 put_device(dev);
1940                 device_unregister(dev);
1941         }
1942 }
1943 EXPORT_SYMBOL_GPL(device_destroy);
1944
1945 /**
1946  * device_rename - renames a device
1947  * @dev: the pointer to the struct device to be renamed
1948  * @new_name: the new name of the device
1949  *
1950  * It is the responsibility of the caller to provide mutual
1951  * exclusion between two different calls of device_rename
1952  * on the same device to ensure that new_name is valid and
1953  * won't conflict with other devices.
1954  *
1955  * Note: Don't call this function.  Currently, the networking layer calls this
1956  * function, but that will change.  The following text from Kay Sievers offers
1957  * some insight:
1958  *
1959  * Renaming devices is racy at many levels, symlinks and other stuff are not
1960  * replaced atomically, and you get a "move" uevent, but it's not easy to
1961  * connect the event to the old and new device. Device nodes are not renamed at
1962  * all, there isn't even support for that in the kernel now.
1963  *
1964  * In the meantime, during renaming, your target name might be taken by another
1965  * driver, creating conflicts. Or the old name is taken directly after you
1966  * renamed it -- then you get events for the same DEVPATH, before you even see
1967  * the "move" event. It's just a mess, and nothing new should ever rely on
1968  * kernel device renaming. Besides that, it's not even implemented now for
1969  * other things than (driver-core wise very simple) network devices.
1970  *
1971  * We are currently about to change network renaming in udev to completely
1972  * disallow renaming of devices in the same namespace as the kernel uses,
1973  * because we can't solve the problems properly, that arise with swapping names
1974  * of multiple interfaces without races. Means, renaming of eth[0-9]* will only
1975  * be allowed to some other name than eth[0-9]*, for the aforementioned
1976  * reasons.
1977  *
1978  * Make up a "real" name in the driver before you register anything, or add
1979  * some other attributes for userspace to find the device, or use udev to add
1980  * symlinks -- but never rename kernel devices later, it's a complete mess. We
1981  * don't even want to get into that and try to implement the missing pieces in
1982  * the core. We really have other pieces to fix in the driver core mess. :)
1983  */
1984 int device_rename(struct device *dev, const char *new_name)
1985 {
1986         struct kobject *kobj = &dev->kobj;
1987         char *old_device_name = NULL;
1988         int error;
1989
1990         dev = get_device(dev);
1991         if (!dev)
1992                 return -EINVAL;
1993
1994         dev_dbg(dev, "renaming to %s\n", new_name);
1995
1996         old_device_name = kstrdup(dev_name(dev), GFP_KERNEL);
1997         if (!old_device_name) {
1998                 error = -ENOMEM;
1999                 goto out;
2000         }
2001
2002         if (dev->class) {
2003                 error = sysfs_rename_link_ns(&dev->class->p->subsys.kobj,
2004                                              kobj, old_device_name,
2005                                              new_name, kobject_namespace(kobj));
2006                 if (error)
2007                         goto out;
2008         }
2009
2010         error = kobject_rename(kobj, new_name);
2011         if (error)
2012                 goto out;
2013
2014 out:
2015         put_device(dev);
2016
2017         kfree(old_device_name);
2018
2019         return error;
2020 }
2021 EXPORT_SYMBOL_GPL(device_rename);
2022
2023 static int device_move_class_links(struct device *dev,
2024                                    struct device *old_parent,
2025                                    struct device *new_parent)
2026 {
2027         int error = 0;
2028
2029         if (old_parent)
2030                 sysfs_remove_link(&dev->kobj, "device");
2031         if (new_parent)
2032                 error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
2033                                           "device");
2034         return error;
2035 }
2036
2037 /**
2038  * device_move - moves a device to a new parent
2039  * @dev: the pointer to the struct device to be moved
2040  * @new_parent: the new parent of the device (can by NULL)
2041  * @dpm_order: how to reorder the dpm_list
2042  */
2043 int device_move(struct device *dev, struct device *new_parent,
2044                 enum dpm_order dpm_order)
2045 {
2046         int error;
2047         struct device *old_parent;
2048         struct kobject *new_parent_kobj;
2049
2050         dev = get_device(dev);
2051         if (!dev)
2052                 return -EINVAL;
2053
2054         device_pm_lock();
2055         new_parent = get_device(new_parent);
2056         new_parent_kobj = get_device_parent(dev, new_parent);
2057         if (IS_ERR(new_parent_kobj)) {
2058                 error = PTR_ERR(new_parent_kobj);
2059                 put_device(new_parent);
2060                 goto out;
2061         }
2062
2063         pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev),
2064                  __func__, new_parent ? dev_name(new_parent) : "<NULL>");
2065         error = kobject_move(&dev->kobj, new_parent_kobj);
2066         if (error) {
2067                 cleanup_glue_dir(dev, new_parent_kobj);
2068                 put_device(new_parent);
2069                 goto out;
2070         }
2071         old_parent = dev->parent;
2072         dev->parent = new_parent;
2073         if (old_parent)
2074                 klist_remove(&dev->p->knode_parent);
2075         if (new_parent) {
2076                 klist_add_tail(&dev->p->knode_parent,
2077                                &new_parent->p->klist_children);
2078                 set_dev_node(dev, dev_to_node(new_parent));
2079         }
2080
2081         if (dev->class) {
2082                 error = device_move_class_links(dev, old_parent, new_parent);
2083                 if (error) {
2084                         /* We ignore errors on cleanup since we're hosed anyway... */
2085                         device_move_class_links(dev, new_parent, old_parent);
2086                         if (!kobject_move(&dev->kobj, &old_parent->kobj)) {
2087                                 if (new_parent)
2088                                         klist_remove(&dev->p->knode_parent);
2089                                 dev->parent = old_parent;
2090                                 if (old_parent) {
2091                                         klist_add_tail(&dev->p->knode_parent,
2092                                                        &old_parent->p->klist_children);
2093                                         set_dev_node(dev, dev_to_node(old_parent));
2094                                 }
2095                         }
2096                         cleanup_glue_dir(dev, new_parent_kobj);
2097                         put_device(new_parent);
2098                         goto out;
2099                 }
2100         }
2101         switch (dpm_order) {
2102         case DPM_ORDER_NONE:
2103                 break;
2104         case DPM_ORDER_DEV_AFTER_PARENT:
2105                 device_pm_move_after(dev, new_parent);
2106                 devices_kset_move_after(dev, new_parent);
2107                 break;
2108         case DPM_ORDER_PARENT_BEFORE_DEV:
2109                 device_pm_move_before(new_parent, dev);
2110                 devices_kset_move_before(new_parent, dev);
2111                 break;
2112         case DPM_ORDER_DEV_LAST:
2113                 device_pm_move_last(dev);
2114                 devices_kset_move_last(dev);
2115                 break;
2116         }
2117
2118         put_device(old_parent);
2119 out:
2120         device_pm_unlock();
2121         put_device(dev);
2122         return error;
2123 }
2124 EXPORT_SYMBOL_GPL(device_move);
2125
2126 /**
2127  * device_shutdown - call ->shutdown() on each device to shutdown.
2128  */
2129 void device_shutdown(void)
2130 {
2131         struct device *dev, *parent;
2132
2133         cpufreq_suspend();
2134
2135         spin_lock(&devices_kset->list_lock);
2136         /*
2137          * Walk the devices list backward, shutting down each in turn.
2138          * Beware that device unplug events may also start pulling
2139          * devices offline, even as the system is shutting down.
2140          */
2141         while (!list_empty(&devices_kset->list)) {
2142                 dev = list_entry(devices_kset->list.prev, struct device,
2143                                 kobj.entry);
2144
2145                 /*
2146                  * hold reference count of device's parent to
2147                  * prevent it from being freed because parent's
2148                  * lock is to be held
2149                  */
2150                 parent = get_device(dev->parent);
2151                 get_device(dev);
2152                 /*
2153                  * Make sure the device is off the kset list, in the
2154                  * event that dev->*->shutdown() doesn't remove it.
2155                  */
2156                 list_del_init(&dev->kobj.entry);
2157                 spin_unlock(&devices_kset->list_lock);
2158
2159                 /* hold lock to avoid race with probe/release */
2160                 if (parent)
2161                         device_lock(parent);
2162                 device_lock(dev);
2163
2164                 /* Don't allow any more runtime suspends */
2165                 pm_runtime_get_noresume(dev);
2166                 pm_runtime_barrier(dev);
2167
2168                 if (dev->class && dev->class->shutdown) {
2169                         if (initcall_debug)
2170                                 dev_info(dev, "shutdown\n");
2171                         dev->class->shutdown(dev);
2172                 } else if (dev->bus && dev->bus->shutdown) {
2173                         if (initcall_debug)
2174                                 dev_info(dev, "shutdown\n");
2175                         dev->bus->shutdown(dev);
2176                 } else if (dev->driver && dev->driver->shutdown) {
2177                         if (initcall_debug)
2178                                 dev_info(dev, "shutdown\n");
2179                         dev->driver->shutdown(dev);
2180                 }
2181
2182                 device_unlock(dev);
2183                 if (parent)
2184                         device_unlock(parent);
2185
2186                 put_device(dev);
2187                 put_device(parent);
2188
2189                 spin_lock(&devices_kset->list_lock);
2190         }
2191         spin_unlock(&devices_kset->list_lock);
2192 }
2193
2194 /*
2195  * Device logging functions
2196  */
2197
2198 #ifdef CONFIG_PRINTK
2199 static int
2200 create_syslog_header(const struct device *dev, char *hdr, size_t hdrlen)
2201 {
2202         const char *subsys;
2203         size_t pos = 0;
2204
2205         if (dev->class)
2206                 subsys = dev->class->name;
2207         else if (dev->bus)
2208                 subsys = dev->bus->name;
2209         else
2210                 return 0;
2211
2212         pos += snprintf(hdr + pos, hdrlen - pos, "SUBSYSTEM=%s", subsys);
2213         if (pos >= hdrlen)
2214                 goto overflow;
2215
2216         /*
2217          * Add device identifier DEVICE=:
2218          *   b12:8         block dev_t
2219          *   c127:3        char dev_t
2220          *   n8            netdev ifindex
2221          *   +sound:card0  subsystem:devname
2222          */
2223         if (MAJOR(dev->devt)) {
2224                 char c;
2225
2226                 if (strcmp(subsys, "block") == 0)
2227                         c = 'b';
2228                 else
2229                         c = 'c';
2230                 pos++;
2231                 pos += snprintf(hdr + pos, hdrlen - pos,
2232                                 "DEVICE=%c%u:%u",
2233                                 c, MAJOR(dev->devt), MINOR(dev->devt));
2234         } else if (strcmp(subsys, "net") == 0) {
2235                 struct net_device *net = to_net_dev(dev);
2236
2237                 pos++;
2238                 pos += snprintf(hdr + pos, hdrlen - pos,
2239                                 "DEVICE=n%u", net->ifindex);
2240         } else {
2241                 pos++;
2242                 pos += snprintf(hdr + pos, hdrlen - pos,
2243                                 "DEVICE=+%s:%s", subsys, dev_name(dev));
2244         }
2245
2246         if (pos >= hdrlen)
2247                 goto overflow;
2248
2249         return pos;
2250
2251 overflow:
2252         dev_WARN(dev, "device/subsystem name too long");
2253         return 0;
2254 }
2255
2256 int dev_vprintk_emit(int level, const struct device *dev,
2257                      const char *fmt, va_list args)
2258 {
2259         char hdr[128];
2260         size_t hdrlen;
2261
2262         hdrlen = create_syslog_header(dev, hdr, sizeof(hdr));
2263
2264         return vprintk_emit(0, level, hdrlen ? hdr : NULL, hdrlen, fmt, args);
2265 }
2266 EXPORT_SYMBOL(dev_vprintk_emit);
2267
2268 int dev_printk_emit(int level, const struct device *dev, const char *fmt, ...)
2269 {
2270         va_list args;
2271         int r;
2272
2273         va_start(args, fmt);
2274
2275         r = dev_vprintk_emit(level, dev, fmt, args);
2276
2277         va_end(args);
2278
2279         return r;
2280 }
2281 EXPORT_SYMBOL(dev_printk_emit);
2282
2283 static void __dev_printk(const char *level, const struct device *dev,
2284                         struct va_format *vaf)
2285 {
2286         if (dev)
2287                 dev_printk_emit(level[1] - '0', dev, "%s %s: %pV",
2288                                 dev_driver_string(dev), dev_name(dev), vaf);
2289         else
2290                 printk("%s(NULL device *): %pV", level, vaf);
2291 }
2292
2293 void dev_printk(const char *level, const struct device *dev,
2294                 const char *fmt, ...)
2295 {
2296         struct va_format vaf;
2297         va_list args;
2298
2299         va_start(args, fmt);
2300
2301         vaf.fmt = fmt;
2302         vaf.va = &args;
2303
2304         __dev_printk(level, dev, &vaf);
2305
2306         va_end(args);
2307 }
2308 EXPORT_SYMBOL(dev_printk);
2309
2310 #define define_dev_printk_level(func, kern_level)               \
2311 void func(const struct device *dev, const char *fmt, ...)       \
2312 {                                                               \
2313         struct va_format vaf;                                   \
2314         va_list args;                                           \
2315                                                                 \
2316         va_start(args, fmt);                                    \
2317                                                                 \
2318         vaf.fmt = fmt;                                          \
2319         vaf.va = &args;                                         \
2320                                                                 \
2321         __dev_printk(kern_level, dev, &vaf);                    \
2322                                                                 \
2323         va_end(args);                                           \
2324 }                                                               \
2325 EXPORT_SYMBOL(func);
2326
2327 define_dev_printk_level(dev_emerg, KERN_EMERG);
2328 define_dev_printk_level(dev_alert, KERN_ALERT);
2329 define_dev_printk_level(dev_crit, KERN_CRIT);
2330 define_dev_printk_level(dev_err, KERN_ERR);
2331 define_dev_printk_level(dev_warn, KERN_WARNING);
2332 define_dev_printk_level(dev_notice, KERN_NOTICE);
2333 define_dev_printk_level(_dev_info, KERN_INFO);
2334
2335 #endif
2336
2337 static inline bool fwnode_is_primary(struct fwnode_handle *fwnode)
2338 {
2339         return fwnode && !IS_ERR(fwnode->secondary);
2340 }
2341
2342 /**
2343  * set_primary_fwnode - Change the primary firmware node of a given device.
2344  * @dev: Device to handle.
2345  * @fwnode: New primary firmware node of the device.
2346  *
2347  * Set the device's firmware node pointer to @fwnode, but if a secondary
2348  * firmware node of the device is present, preserve it.
2349  */
2350 void set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
2351 {
2352         if (fwnode) {
2353                 struct fwnode_handle *fn = dev->fwnode;
2354
2355                 if (fwnode_is_primary(fn))
2356                         fn = fn->secondary;
2357
2358                 fwnode->secondary = fn;
2359                 dev->fwnode = fwnode;
2360         } else {
2361                 dev->fwnode = fwnode_is_primary(dev->fwnode) ?
2362                         dev->fwnode->secondary : NULL;
2363         }
2364 }
2365 EXPORT_SYMBOL_GPL(set_primary_fwnode);
2366
2367 /**
2368  * set_secondary_fwnode - Change the secondary firmware node of a given device.
2369  * @dev: Device to handle.
2370  * @fwnode: New secondary firmware node of the device.
2371  *
2372  * If a primary firmware node of the device is present, set its secondary
2373  * pointer to @fwnode.  Otherwise, set the device's firmware node pointer to
2374  * @fwnode.
2375  */
2376 void set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
2377 {
2378         if (fwnode)
2379                 fwnode->secondary = ERR_PTR(-ENODEV);
2380
2381         if (fwnode_is_primary(dev->fwnode))
2382                 dev->fwnode->secondary = fwnode;
2383         else
2384                 dev->fwnode = fwnode;
2385 }