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