driver core: Expose device link details in sysfs
[linux-2.6-microblaze.git] / drivers / base / core.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * drivers/base/core.c - core driver model code (device registration, etc)
4  *
5  * Copyright (c) 2002-3 Patrick Mochel
6  * Copyright (c) 2002-3 Open Source Development Labs
7  * Copyright (c) 2006 Greg Kroah-Hartman <gregkh@suse.de>
8  * Copyright (c) 2006 Novell, Inc.
9  */
10
11 #include <linux/acpi.h>
12 #include <linux/cpufreq.h>
13 #include <linux/device.h>
14 #include <linux/err.h>
15 #include <linux/fwnode.h>
16 #include <linux/init.h>
17 #include <linux/module.h>
18 #include <linux/slab.h>
19 #include <linux/string.h>
20 #include <linux/kdev_t.h>
21 #include <linux/notifier.h>
22 #include <linux/of.h>
23 #include <linux/of_device.h>
24 #include <linux/genhd.h>
25 #include <linux/mutex.h>
26 #include <linux/pm_runtime.h>
27 #include <linux/netdevice.h>
28 #include <linux/sched/signal.h>
29 #include <linux/sysfs.h>
30
31 #include "base.h"
32 #include "power/power.h"
33
34 #ifdef CONFIG_SYSFS_DEPRECATED
35 #ifdef CONFIG_SYSFS_DEPRECATED_V2
36 long sysfs_deprecated = 1;
37 #else
38 long sysfs_deprecated = 0;
39 #endif
40 static int __init sysfs_deprecated_setup(char *arg)
41 {
42         return kstrtol(arg, 10, &sysfs_deprecated);
43 }
44 early_param("sysfs.deprecated", sysfs_deprecated_setup);
45 #endif
46
47 /* Device links support. */
48 static LIST_HEAD(wait_for_suppliers);
49 static DEFINE_MUTEX(wfs_lock);
50 static LIST_HEAD(deferred_sync);
51 static unsigned int defer_sync_state_count = 1;
52 static unsigned int defer_fw_devlink_count;
53 static DEFINE_MUTEX(defer_fw_devlink_lock);
54 static bool fw_devlink_is_permissive(void);
55
56 #ifdef CONFIG_SRCU
57 static DEFINE_MUTEX(device_links_lock);
58 DEFINE_STATIC_SRCU(device_links_srcu);
59
60 static inline void device_links_write_lock(void)
61 {
62         mutex_lock(&device_links_lock);
63 }
64
65 static inline void device_links_write_unlock(void)
66 {
67         mutex_unlock(&device_links_lock);
68 }
69
70 int device_links_read_lock(void) __acquires(&device_links_srcu)
71 {
72         return srcu_read_lock(&device_links_srcu);
73 }
74
75 void device_links_read_unlock(int idx) __releases(&device_links_srcu)
76 {
77         srcu_read_unlock(&device_links_srcu, idx);
78 }
79
80 int device_links_read_lock_held(void)
81 {
82         return srcu_read_lock_held(&device_links_srcu);
83 }
84 #else /* !CONFIG_SRCU */
85 static DECLARE_RWSEM(device_links_lock);
86
87 static inline void device_links_write_lock(void)
88 {
89         down_write(&device_links_lock);
90 }
91
92 static inline void device_links_write_unlock(void)
93 {
94         up_write(&device_links_lock);
95 }
96
97 int device_links_read_lock(void)
98 {
99         down_read(&device_links_lock);
100         return 0;
101 }
102
103 void device_links_read_unlock(int not_used)
104 {
105         up_read(&device_links_lock);
106 }
107
108 #ifdef CONFIG_DEBUG_LOCK_ALLOC
109 int device_links_read_lock_held(void)
110 {
111         return lockdep_is_held(&device_links_lock);
112 }
113 #endif
114 #endif /* !CONFIG_SRCU */
115
116 /**
117  * device_is_dependent - Check if one device depends on another one
118  * @dev: Device to check dependencies for.
119  * @target: Device to check against.
120  *
121  * Check if @target depends on @dev or any device dependent on it (its child or
122  * its consumer etc).  Return 1 if that is the case or 0 otherwise.
123  */
124 static int device_is_dependent(struct device *dev, void *target)
125 {
126         struct device_link *link;
127         int ret;
128
129         if (dev == target)
130                 return 1;
131
132         ret = device_for_each_child(dev, target, device_is_dependent);
133         if (ret)
134                 return ret;
135
136         list_for_each_entry(link, &dev->links.consumers, s_node) {
137                 if (link->flags == (DL_FLAG_SYNC_STATE_ONLY | DL_FLAG_MANAGED))
138                         continue;
139
140                 if (link->consumer == target)
141                         return 1;
142
143                 ret = device_is_dependent(link->consumer, target);
144                 if (ret)
145                         break;
146         }
147         return ret;
148 }
149
150 static void device_link_init_status(struct device_link *link,
151                                     struct device *consumer,
152                                     struct device *supplier)
153 {
154         switch (supplier->links.status) {
155         case DL_DEV_PROBING:
156                 switch (consumer->links.status) {
157                 case DL_DEV_PROBING:
158                         /*
159                          * A consumer driver can create a link to a supplier
160                          * that has not completed its probing yet as long as it
161                          * knows that the supplier is already functional (for
162                          * example, it has just acquired some resources from the
163                          * supplier).
164                          */
165                         link->status = DL_STATE_CONSUMER_PROBE;
166                         break;
167                 default:
168                         link->status = DL_STATE_DORMANT;
169                         break;
170                 }
171                 break;
172         case DL_DEV_DRIVER_BOUND:
173                 switch (consumer->links.status) {
174                 case DL_DEV_PROBING:
175                         link->status = DL_STATE_CONSUMER_PROBE;
176                         break;
177                 case DL_DEV_DRIVER_BOUND:
178                         link->status = DL_STATE_ACTIVE;
179                         break;
180                 default:
181                         link->status = DL_STATE_AVAILABLE;
182                         break;
183                 }
184                 break;
185         case DL_DEV_UNBINDING:
186                 link->status = DL_STATE_SUPPLIER_UNBIND;
187                 break;
188         default:
189                 link->status = DL_STATE_DORMANT;
190                 break;
191         }
192 }
193
194 static int device_reorder_to_tail(struct device *dev, void *not_used)
195 {
196         struct device_link *link;
197
198         /*
199          * Devices that have not been registered yet will be put to the ends
200          * of the lists during the registration, so skip them here.
201          */
202         if (device_is_registered(dev))
203                 devices_kset_move_last(dev);
204
205         if (device_pm_initialized(dev))
206                 device_pm_move_last(dev);
207
208         device_for_each_child(dev, NULL, device_reorder_to_tail);
209         list_for_each_entry(link, &dev->links.consumers, s_node) {
210                 if (link->flags == (DL_FLAG_SYNC_STATE_ONLY | DL_FLAG_MANAGED))
211                         continue;
212                 device_reorder_to_tail(link->consumer, NULL);
213         }
214
215         return 0;
216 }
217
218 /**
219  * device_pm_move_to_tail - Move set of devices to the end of device lists
220  * @dev: Device to move
221  *
222  * This is a device_reorder_to_tail() wrapper taking the requisite locks.
223  *
224  * It moves the @dev along with all of its children and all of its consumers
225  * to the ends of the device_kset and dpm_list, recursively.
226  */
227 void device_pm_move_to_tail(struct device *dev)
228 {
229         int idx;
230
231         idx = device_links_read_lock();
232         device_pm_lock();
233         device_reorder_to_tail(dev, NULL);
234         device_pm_unlock();
235         device_links_read_unlock(idx);
236 }
237
238 #define to_devlink(dev) container_of((dev), struct device_link, link_dev)
239
240 static ssize_t status_show(struct device *dev,
241                           struct device_attribute *attr, char *buf)
242 {
243         char *status;
244
245         switch (to_devlink(dev)->status) {
246         case DL_STATE_NONE:
247                 status = "not tracked"; break;
248         case DL_STATE_DORMANT:
249                 status = "dormant"; break;
250         case DL_STATE_AVAILABLE:
251                 status = "available"; break;
252         case DL_STATE_CONSUMER_PROBE:
253                 status = "consumer probing"; break;
254         case DL_STATE_ACTIVE:
255                 status = "active"; break;
256         case DL_STATE_SUPPLIER_UNBIND:
257                 status = "supplier unbinding"; break;
258         default:
259                 status = "unknown"; break;
260         }
261         return sprintf(buf, "%s\n", status);
262 }
263 static DEVICE_ATTR_RO(status);
264
265 static ssize_t auto_remove_on_show(struct device *dev,
266                                    struct device_attribute *attr, char *buf)
267 {
268         struct device_link *link = to_devlink(dev);
269         char *str;
270
271         if (link->flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
272                 str = "supplier unbind";
273         else if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER)
274                 str = "consumer unbind";
275         else
276                 str = "never";
277
278         return sprintf(buf, "%s\n", str);
279 }
280 static DEVICE_ATTR_RO(auto_remove_on);
281
282 static ssize_t runtime_pm_show(struct device *dev,
283                                struct device_attribute *attr, char *buf)
284 {
285         struct device_link *link = to_devlink(dev);
286
287         return sprintf(buf, "%d\n", !!(link->flags & DL_FLAG_PM_RUNTIME));
288 }
289 static DEVICE_ATTR_RO(runtime_pm);
290
291 static ssize_t sync_state_only_show(struct device *dev,
292                                     struct device_attribute *attr, char *buf)
293 {
294         struct device_link *link = to_devlink(dev);
295
296         return sprintf(buf, "%d\n", !!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
297 }
298 static DEVICE_ATTR_RO(sync_state_only);
299
300 static struct attribute *devlink_attrs[] = {
301         &dev_attr_status.attr,
302         &dev_attr_auto_remove_on.attr,
303         &dev_attr_runtime_pm.attr,
304         &dev_attr_sync_state_only.attr,
305         NULL,
306 };
307 ATTRIBUTE_GROUPS(devlink);
308
309 static void devlink_dev_release(struct device *dev)
310 {
311         kfree(to_devlink(dev));
312 }
313
314 static struct class devlink_class = {
315         .name = "devlink",
316         .owner = THIS_MODULE,
317         .dev_groups = devlink_groups,
318         .dev_release = devlink_dev_release,
319 };
320
321 static int devlink_add_symlinks(struct device *dev,
322                                 struct class_interface *class_intf)
323 {
324         int ret;
325         size_t len;
326         struct device_link *link = to_devlink(dev);
327         struct device *sup = link->supplier;
328         struct device *con = link->consumer;
329         char *buf;
330
331         len = max(strlen(dev_name(sup)), strlen(dev_name(con)));
332         len += strlen("supplier:") + 1;
333         buf = kzalloc(len, GFP_KERNEL);
334         if (!buf)
335                 return -ENOMEM;
336
337         ret = sysfs_create_link(&link->link_dev.kobj, &sup->kobj, "supplier");
338         if (ret)
339                 goto out;
340
341         ret = sysfs_create_link(&link->link_dev.kobj, &con->kobj, "consumer");
342         if (ret)
343                 goto err_con;
344
345         snprintf(buf, len, "consumer:%s", dev_name(con));
346         ret = sysfs_create_link(&sup->kobj, &link->link_dev.kobj, buf);
347         if (ret)
348                 goto err_con_dev;
349
350         snprintf(buf, len, "supplier:%s", dev_name(sup));
351         ret = sysfs_create_link(&con->kobj, &link->link_dev.kobj, buf);
352         if (ret)
353                 goto err_sup_dev;
354
355         goto out;
356
357 err_sup_dev:
358         snprintf(buf, len, "consumer:%s", dev_name(con));
359         sysfs_remove_link(&sup->kobj, buf);
360 err_con_dev:
361         sysfs_remove_link(&link->link_dev.kobj, "consumer");
362 err_con:
363         sysfs_remove_link(&link->link_dev.kobj, "supplier");
364 out:
365         kfree(buf);
366         return ret;
367 }
368
369 static void devlink_remove_symlinks(struct device *dev,
370                                    struct class_interface *class_intf)
371 {
372         struct device_link *link = to_devlink(dev);
373         size_t len;
374         struct device *sup = link->supplier;
375         struct device *con = link->consumer;
376         char *buf;
377
378         sysfs_remove_link(&link->link_dev.kobj, "consumer");
379         sysfs_remove_link(&link->link_dev.kobj, "supplier");
380
381         len = max(strlen(dev_name(sup)), strlen(dev_name(con)));
382         len += strlen("supplier:") + 1;
383         buf = kzalloc(len, GFP_KERNEL);
384         if (!buf) {
385                 WARN(1, "Unable to properly free device link symlinks!\n");
386                 return;
387         }
388
389         snprintf(buf, len, "supplier:%s", dev_name(sup));
390         sysfs_remove_link(&con->kobj, buf);
391         snprintf(buf, len, "consumer:%s", dev_name(con));
392         sysfs_remove_link(&sup->kobj, buf);
393         kfree(buf);
394 }
395
396 static struct class_interface devlink_class_intf = {
397         .class = &devlink_class,
398         .add_dev = devlink_add_symlinks,
399         .remove_dev = devlink_remove_symlinks,
400 };
401
402 static int __init devlink_class_init(void)
403 {
404         int ret;
405
406         ret = class_register(&devlink_class);
407         if (ret)
408                 return ret;
409
410         ret = class_interface_register(&devlink_class_intf);
411         if (ret)
412                 class_unregister(&devlink_class);
413
414         return ret;
415 }
416 postcore_initcall(devlink_class_init);
417
418 #define DL_MANAGED_LINK_FLAGS (DL_FLAG_AUTOREMOVE_CONSUMER | \
419                                DL_FLAG_AUTOREMOVE_SUPPLIER | \
420                                DL_FLAG_AUTOPROBE_CONSUMER  | \
421                                DL_FLAG_SYNC_STATE_ONLY)
422
423 #define DL_ADD_VALID_FLAGS (DL_MANAGED_LINK_FLAGS | DL_FLAG_STATELESS | \
424                             DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE)
425
426 /**
427  * device_link_add - Create a link between two devices.
428  * @consumer: Consumer end of the link.
429  * @supplier: Supplier end of the link.
430  * @flags: Link flags.
431  *
432  * The caller is responsible for the proper synchronization of the link creation
433  * with runtime PM.  First, setting the DL_FLAG_PM_RUNTIME flag will cause the
434  * runtime PM framework to take the link into account.  Second, if the
435  * DL_FLAG_RPM_ACTIVE flag is set in addition to it, the supplier devices will
436  * be forced into the active metastate and reference-counted upon the creation
437  * of the link.  If DL_FLAG_PM_RUNTIME is not set, DL_FLAG_RPM_ACTIVE will be
438  * ignored.
439  *
440  * If DL_FLAG_STATELESS is set in @flags, the caller of this function is
441  * expected to release the link returned by it directly with the help of either
442  * device_link_del() or device_link_remove().
443  *
444  * If that flag is not set, however, the caller of this function is handing the
445  * management of the link over to the driver core entirely and its return value
446  * can only be used to check whether or not the link is present.  In that case,
447  * the DL_FLAG_AUTOREMOVE_CONSUMER and DL_FLAG_AUTOREMOVE_SUPPLIER device link
448  * flags can be used to indicate to the driver core when the link can be safely
449  * deleted.  Namely, setting one of them in @flags indicates to the driver core
450  * that the link is not going to be used (by the given caller of this function)
451  * after unbinding the consumer or supplier driver, respectively, from its
452  * device, so the link can be deleted at that point.  If none of them is set,
453  * the link will be maintained until one of the devices pointed to by it (either
454  * the consumer or the supplier) is unregistered.
455  *
456  * Also, if DL_FLAG_STATELESS, DL_FLAG_AUTOREMOVE_CONSUMER and
457  * DL_FLAG_AUTOREMOVE_SUPPLIER are not set in @flags (that is, a persistent
458  * managed device link is being added), the DL_FLAG_AUTOPROBE_CONSUMER flag can
459  * be used to request the driver core to automaticall probe for a consmer
460  * driver after successfully binding a driver to the supplier device.
461  *
462  * The combination of DL_FLAG_STATELESS and one of DL_FLAG_AUTOREMOVE_CONSUMER,
463  * DL_FLAG_AUTOREMOVE_SUPPLIER, or DL_FLAG_AUTOPROBE_CONSUMER set in @flags at
464  * the same time is invalid and will cause NULL to be returned upfront.
465  * However, if a device link between the given @consumer and @supplier pair
466  * exists already when this function is called for them, the existing link will
467  * be returned regardless of its current type and status (the link's flags may
468  * be modified then).  The caller of this function is then expected to treat
469  * the link as though it has just been created, so (in particular) if
470  * DL_FLAG_STATELESS was passed in @flags, the link needs to be released
471  * explicitly when not needed any more (as stated above).
472  *
473  * A side effect of the link creation is re-ordering of dpm_list and the
474  * devices_kset list by moving the consumer device and all devices depending
475  * on it to the ends of these lists (that does not happen to devices that have
476  * not been registered when this function is called).
477  *
478  * The supplier device is required to be registered when this function is called
479  * and NULL will be returned if that is not the case.  The consumer device need
480  * not be registered, however.
481  */
482 struct device_link *device_link_add(struct device *consumer,
483                                     struct device *supplier, u32 flags)
484 {
485         struct device_link *link;
486
487         if (!consumer || !supplier || flags & ~DL_ADD_VALID_FLAGS ||
488             (flags & DL_FLAG_STATELESS && flags & DL_MANAGED_LINK_FLAGS) ||
489             (flags & DL_FLAG_SYNC_STATE_ONLY &&
490              flags != DL_FLAG_SYNC_STATE_ONLY) ||
491             (flags & DL_FLAG_AUTOPROBE_CONSUMER &&
492              flags & (DL_FLAG_AUTOREMOVE_CONSUMER |
493                       DL_FLAG_AUTOREMOVE_SUPPLIER)))
494                 return NULL;
495
496         if (flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) {
497                 if (pm_runtime_get_sync(supplier) < 0) {
498                         pm_runtime_put_noidle(supplier);
499                         return NULL;
500                 }
501         }
502
503         if (!(flags & DL_FLAG_STATELESS))
504                 flags |= DL_FLAG_MANAGED;
505
506         device_links_write_lock();
507         device_pm_lock();
508
509         /*
510          * If the supplier has not been fully registered yet or there is a
511          * reverse (non-SYNC_STATE_ONLY) dependency between the consumer and
512          * the supplier already in the graph, return NULL. If the link is a
513          * SYNC_STATE_ONLY link, we don't check for reverse dependencies
514          * because it only affects sync_state() callbacks.
515          */
516         if (!device_pm_initialized(supplier)
517             || (!(flags & DL_FLAG_SYNC_STATE_ONLY) &&
518                   device_is_dependent(consumer, supplier))) {
519                 link = NULL;
520                 goto out;
521         }
522
523         /*
524          * DL_FLAG_AUTOREMOVE_SUPPLIER indicates that the link will be needed
525          * longer than for DL_FLAG_AUTOREMOVE_CONSUMER and setting them both
526          * together doesn't make sense, so prefer DL_FLAG_AUTOREMOVE_SUPPLIER.
527          */
528         if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
529                 flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
530
531         list_for_each_entry(link, &supplier->links.consumers, s_node) {
532                 if (link->consumer != consumer)
533                         continue;
534
535                 if (flags & DL_FLAG_PM_RUNTIME) {
536                         if (!(link->flags & DL_FLAG_PM_RUNTIME)) {
537                                 pm_runtime_new_link(consumer);
538                                 link->flags |= DL_FLAG_PM_RUNTIME;
539                         }
540                         if (flags & DL_FLAG_RPM_ACTIVE)
541                                 refcount_inc(&link->rpm_active);
542                 }
543
544                 if (flags & DL_FLAG_STATELESS) {
545                         kref_get(&link->kref);
546                         if (link->flags & DL_FLAG_SYNC_STATE_ONLY &&
547                             !(link->flags & DL_FLAG_STATELESS)) {
548                                 link->flags |= DL_FLAG_STATELESS;
549                                 goto reorder;
550                         } else {
551                                 link->flags |= DL_FLAG_STATELESS;
552                                 goto out;
553                         }
554                 }
555
556                 /*
557                  * If the life time of the link following from the new flags is
558                  * longer than indicated by the flags of the existing link,
559                  * update the existing link to stay around longer.
560                  */
561                 if (flags & DL_FLAG_AUTOREMOVE_SUPPLIER) {
562                         if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER) {
563                                 link->flags &= ~DL_FLAG_AUTOREMOVE_CONSUMER;
564                                 link->flags |= DL_FLAG_AUTOREMOVE_SUPPLIER;
565                         }
566                 } else if (!(flags & DL_FLAG_AUTOREMOVE_CONSUMER)) {
567                         link->flags &= ~(DL_FLAG_AUTOREMOVE_CONSUMER |
568                                          DL_FLAG_AUTOREMOVE_SUPPLIER);
569                 }
570                 if (!(link->flags & DL_FLAG_MANAGED)) {
571                         kref_get(&link->kref);
572                         link->flags |= DL_FLAG_MANAGED;
573                         device_link_init_status(link, consumer, supplier);
574                 }
575                 if (link->flags & DL_FLAG_SYNC_STATE_ONLY &&
576                     !(flags & DL_FLAG_SYNC_STATE_ONLY)) {
577                         link->flags &= ~DL_FLAG_SYNC_STATE_ONLY;
578                         goto reorder;
579                 }
580
581                 goto out;
582         }
583
584         link = kzalloc(sizeof(*link), GFP_KERNEL);
585         if (!link)
586                 goto out;
587
588         refcount_set(&link->rpm_active, 1);
589
590         get_device(supplier);
591         link->supplier = supplier;
592         INIT_LIST_HEAD(&link->s_node);
593         get_device(consumer);
594         link->consumer = consumer;
595         INIT_LIST_HEAD(&link->c_node);
596         link->flags = flags;
597         kref_init(&link->kref);
598
599         link->link_dev.class = &devlink_class;
600         device_set_pm_not_required(&link->link_dev);
601         dev_set_name(&link->link_dev, "%s:%s",
602                      dev_name(supplier), dev_name(consumer));
603         if (device_register(&link->link_dev)) {
604                 put_device(consumer);
605                 put_device(supplier);
606                 kfree(link);
607                 link = NULL;
608                 goto out;
609         }
610
611         if (flags & DL_FLAG_PM_RUNTIME) {
612                 if (flags & DL_FLAG_RPM_ACTIVE)
613                         refcount_inc(&link->rpm_active);
614
615                 pm_runtime_new_link(consumer);
616         }
617
618         /* Determine the initial link state. */
619         if (flags & DL_FLAG_STATELESS)
620                 link->status = DL_STATE_NONE;
621         else
622                 device_link_init_status(link, consumer, supplier);
623
624         /*
625          * Some callers expect the link creation during consumer driver probe to
626          * resume the supplier even without DL_FLAG_RPM_ACTIVE.
627          */
628         if (link->status == DL_STATE_CONSUMER_PROBE &&
629             flags & DL_FLAG_PM_RUNTIME)
630                 pm_runtime_resume(supplier);
631
632         list_add_tail_rcu(&link->s_node, &supplier->links.consumers);
633         list_add_tail_rcu(&link->c_node, &consumer->links.suppliers);
634
635         if (flags & DL_FLAG_SYNC_STATE_ONLY) {
636                 dev_dbg(consumer,
637                         "Linked as a sync state only consumer to %s\n",
638                         dev_name(supplier));
639                 goto out;
640         }
641
642 reorder:
643         /*
644          * Move the consumer and all of the devices depending on it to the end
645          * of dpm_list and the devices_kset list.
646          *
647          * It is necessary to hold dpm_list locked throughout all that or else
648          * we may end up suspending with a wrong ordering of it.
649          */
650         device_reorder_to_tail(consumer, NULL);
651
652         dev_dbg(consumer, "Linked as a consumer to %s\n", dev_name(supplier));
653
654 out:
655         device_pm_unlock();
656         device_links_write_unlock();
657
658         if ((flags & DL_FLAG_PM_RUNTIME && flags & DL_FLAG_RPM_ACTIVE) && !link)
659                 pm_runtime_put(supplier);
660
661         return link;
662 }
663 EXPORT_SYMBOL_GPL(device_link_add);
664
665 /**
666  * device_link_wait_for_supplier - Add device to wait_for_suppliers list
667  * @consumer: Consumer device
668  *
669  * Marks the @consumer device as waiting for suppliers to become available by
670  * adding it to the wait_for_suppliers list. The consumer device will never be
671  * probed until it's removed from the wait_for_suppliers list.
672  *
673  * The caller is responsible for adding the links to the supplier devices once
674  * they are available and removing the @consumer device from the
675  * wait_for_suppliers list once links to all the suppliers have been created.
676  *
677  * This function is NOT meant to be called from the probe function of the
678  * consumer but rather from code that creates/adds the consumer device.
679  */
680 static void device_link_wait_for_supplier(struct device *consumer,
681                                           bool need_for_probe)
682 {
683         mutex_lock(&wfs_lock);
684         list_add_tail(&consumer->links.needs_suppliers, &wait_for_suppliers);
685         consumer->links.need_for_probe = need_for_probe;
686         mutex_unlock(&wfs_lock);
687 }
688
689 static void device_link_wait_for_mandatory_supplier(struct device *consumer)
690 {
691         device_link_wait_for_supplier(consumer, true);
692 }
693
694 static void device_link_wait_for_optional_supplier(struct device *consumer)
695 {
696         device_link_wait_for_supplier(consumer, false);
697 }
698
699 /**
700  * device_link_add_missing_supplier_links - Add links from consumer devices to
701  *                                          supplier devices, leaving any
702  *                                          consumer with inactive suppliers on
703  *                                          the wait_for_suppliers list
704  *
705  * Loops through all consumers waiting on suppliers and tries to add all their
706  * supplier links. If that succeeds, the consumer device is removed from
707  * wait_for_suppliers list. Otherwise, they are left in the wait_for_suppliers
708  * list.  Devices left on the wait_for_suppliers list will not be probed.
709  *
710  * The fwnode add_links callback is expected to return 0 if it has found and
711  * added all the supplier links for the consumer device. It should return an
712  * error if it isn't able to do so.
713  *
714  * The caller of device_link_wait_for_supplier() is expected to call this once
715  * it's aware of potential suppliers becoming available.
716  */
717 static void device_link_add_missing_supplier_links(void)
718 {
719         struct device *dev, *tmp;
720
721         mutex_lock(&wfs_lock);
722         list_for_each_entry_safe(dev, tmp, &wait_for_suppliers,
723                                  links.needs_suppliers) {
724                 int ret = fwnode_call_int_op(dev->fwnode, add_links, dev);
725                 if (!ret)
726                         list_del_init(&dev->links.needs_suppliers);
727                 else if (ret != -ENODEV || fw_devlink_is_permissive())
728                         dev->links.need_for_probe = false;
729         }
730         mutex_unlock(&wfs_lock);
731 }
732
733 static void device_link_free(struct device_link *link)
734 {
735         while (refcount_dec_not_one(&link->rpm_active))
736                 pm_runtime_put(link->supplier);
737
738         put_device(link->consumer);
739         put_device(link->supplier);
740         device_unregister(&link->link_dev);
741 }
742
743 #ifdef CONFIG_SRCU
744 static void __device_link_free_srcu(struct rcu_head *rhead)
745 {
746         device_link_free(container_of(rhead, struct device_link, rcu_head));
747 }
748
749 static void __device_link_del(struct kref *kref)
750 {
751         struct device_link *link = container_of(kref, struct device_link, kref);
752
753         dev_dbg(link->consumer, "Dropping the link to %s\n",
754                 dev_name(link->supplier));
755
756         if (link->flags & DL_FLAG_PM_RUNTIME)
757                 pm_runtime_drop_link(link->consumer);
758
759         list_del_rcu(&link->s_node);
760         list_del_rcu(&link->c_node);
761         call_srcu(&device_links_srcu, &link->rcu_head, __device_link_free_srcu);
762 }
763 #else /* !CONFIG_SRCU */
764 static void __device_link_del(struct kref *kref)
765 {
766         struct device_link *link = container_of(kref, struct device_link, kref);
767
768         dev_info(link->consumer, "Dropping the link to %s\n",
769                  dev_name(link->supplier));
770
771         if (link->flags & DL_FLAG_PM_RUNTIME)
772                 pm_runtime_drop_link(link->consumer);
773
774         list_del(&link->s_node);
775         list_del(&link->c_node);
776         device_link_free(link);
777 }
778 #endif /* !CONFIG_SRCU */
779
780 static void device_link_put_kref(struct device_link *link)
781 {
782         if (link->flags & DL_FLAG_STATELESS)
783                 kref_put(&link->kref, __device_link_del);
784         else
785                 WARN(1, "Unable to drop a managed device link reference\n");
786 }
787
788 /**
789  * device_link_del - Delete a stateless link between two devices.
790  * @link: Device link to delete.
791  *
792  * The caller must ensure proper synchronization of this function with runtime
793  * PM.  If the link was added multiple times, it needs to be deleted as often.
794  * Care is required for hotplugged devices:  Their links are purged on removal
795  * and calling device_link_del() is then no longer allowed.
796  */
797 void device_link_del(struct device_link *link)
798 {
799         device_links_write_lock();
800         device_pm_lock();
801         device_link_put_kref(link);
802         device_pm_unlock();
803         device_links_write_unlock();
804 }
805 EXPORT_SYMBOL_GPL(device_link_del);
806
807 /**
808  * device_link_remove - Delete a stateless link between two devices.
809  * @consumer: Consumer end of the link.
810  * @supplier: Supplier end of the link.
811  *
812  * The caller must ensure proper synchronization of this function with runtime
813  * PM.
814  */
815 void device_link_remove(void *consumer, struct device *supplier)
816 {
817         struct device_link *link;
818
819         if (WARN_ON(consumer == supplier))
820                 return;
821
822         device_links_write_lock();
823         device_pm_lock();
824
825         list_for_each_entry(link, &supplier->links.consumers, s_node) {
826                 if (link->consumer == consumer) {
827                         device_link_put_kref(link);
828                         break;
829                 }
830         }
831
832         device_pm_unlock();
833         device_links_write_unlock();
834 }
835 EXPORT_SYMBOL_GPL(device_link_remove);
836
837 static void device_links_missing_supplier(struct device *dev)
838 {
839         struct device_link *link;
840
841         list_for_each_entry(link, &dev->links.suppliers, c_node) {
842                 if (link->status != DL_STATE_CONSUMER_PROBE)
843                         continue;
844
845                 if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
846                         WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
847                 } else {
848                         WARN_ON(!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
849                         WRITE_ONCE(link->status, DL_STATE_DORMANT);
850                 }
851         }
852 }
853
854 /**
855  * device_links_check_suppliers - Check presence of supplier drivers.
856  * @dev: Consumer device.
857  *
858  * Check links from this device to any suppliers.  Walk the list of the device's
859  * links to suppliers and see if all of them are available.  If not, simply
860  * return -EPROBE_DEFER.
861  *
862  * We need to guarantee that the supplier will not go away after the check has
863  * been positive here.  It only can go away in __device_release_driver() and
864  * that function  checks the device's links to consumers.  This means we need to
865  * mark the link as "consumer probe in progress" to make the supplier removal
866  * wait for us to complete (or bad things may happen).
867  *
868  * Links without the DL_FLAG_MANAGED flag set are ignored.
869  */
870 int device_links_check_suppliers(struct device *dev)
871 {
872         struct device_link *link;
873         int ret = 0;
874
875         /*
876          * Device waiting for supplier to become available is not allowed to
877          * probe.
878          */
879         mutex_lock(&wfs_lock);
880         if (!list_empty(&dev->links.needs_suppliers) &&
881             dev->links.need_for_probe) {
882                 mutex_unlock(&wfs_lock);
883                 return -EPROBE_DEFER;
884         }
885         mutex_unlock(&wfs_lock);
886
887         device_links_write_lock();
888
889         list_for_each_entry(link, &dev->links.suppliers, c_node) {
890                 if (!(link->flags & DL_FLAG_MANAGED))
891                         continue;
892
893                 if (link->status != DL_STATE_AVAILABLE &&
894                     !(link->flags & DL_FLAG_SYNC_STATE_ONLY)) {
895                         device_links_missing_supplier(dev);
896                         ret = -EPROBE_DEFER;
897                         break;
898                 }
899                 WRITE_ONCE(link->status, DL_STATE_CONSUMER_PROBE);
900         }
901         dev->links.status = DL_DEV_PROBING;
902
903         device_links_write_unlock();
904         return ret;
905 }
906
907 /**
908  * __device_links_queue_sync_state - Queue a device for sync_state() callback
909  * @dev: Device to call sync_state() on
910  * @list: List head to queue the @dev on
911  *
912  * Queues a device for a sync_state() callback when the device links write lock
913  * isn't held. This allows the sync_state() execution flow to use device links
914  * APIs.  The caller must ensure this function is called with
915  * device_links_write_lock() held.
916  *
917  * This function does a get_device() to make sure the device is not freed while
918  * on this list.
919  *
920  * So the caller must also ensure that device_links_flush_sync_list() is called
921  * as soon as the caller releases device_links_write_lock().  This is necessary
922  * to make sure the sync_state() is called in a timely fashion and the
923  * put_device() is called on this device.
924  */
925 static void __device_links_queue_sync_state(struct device *dev,
926                                             struct list_head *list)
927 {
928         struct device_link *link;
929
930         if (!dev_has_sync_state(dev))
931                 return;
932         if (dev->state_synced)
933                 return;
934
935         list_for_each_entry(link, &dev->links.consumers, s_node) {
936                 if (!(link->flags & DL_FLAG_MANAGED))
937                         continue;
938                 if (link->status != DL_STATE_ACTIVE)
939                         return;
940         }
941
942         /*
943          * Set the flag here to avoid adding the same device to a list more
944          * than once. This can happen if new consumers get added to the device
945          * and probed before the list is flushed.
946          */
947         dev->state_synced = true;
948
949         if (WARN_ON(!list_empty(&dev->links.defer_sync)))
950                 return;
951
952         get_device(dev);
953         list_add_tail(&dev->links.defer_sync, list);
954 }
955
956 /**
957  * device_links_flush_sync_list - Call sync_state() on a list of devices
958  * @list: List of devices to call sync_state() on
959  * @dont_lock_dev: Device for which lock is already held by the caller
960  *
961  * Calls sync_state() on all the devices that have been queued for it. This
962  * function is used in conjunction with __device_links_queue_sync_state(). The
963  * @dont_lock_dev parameter is useful when this function is called from a
964  * context where a device lock is already held.
965  */
966 static void device_links_flush_sync_list(struct list_head *list,
967                                          struct device *dont_lock_dev)
968 {
969         struct device *dev, *tmp;
970
971         list_for_each_entry_safe(dev, tmp, list, links.defer_sync) {
972                 list_del_init(&dev->links.defer_sync);
973
974                 if (dev != dont_lock_dev)
975                         device_lock(dev);
976
977                 if (dev->bus->sync_state)
978                         dev->bus->sync_state(dev);
979                 else if (dev->driver && dev->driver->sync_state)
980                         dev->driver->sync_state(dev);
981
982                 if (dev != dont_lock_dev)
983                         device_unlock(dev);
984
985                 put_device(dev);
986         }
987 }
988
989 void device_links_supplier_sync_state_pause(void)
990 {
991         device_links_write_lock();
992         defer_sync_state_count++;
993         device_links_write_unlock();
994 }
995
996 void device_links_supplier_sync_state_resume(void)
997 {
998         struct device *dev, *tmp;
999         LIST_HEAD(sync_list);
1000
1001         device_links_write_lock();
1002         if (!defer_sync_state_count) {
1003                 WARN(true, "Unmatched sync_state pause/resume!");
1004                 goto out;
1005         }
1006         defer_sync_state_count--;
1007         if (defer_sync_state_count)
1008                 goto out;
1009
1010         list_for_each_entry_safe(dev, tmp, &deferred_sync, links.defer_sync) {
1011                 /*
1012                  * Delete from deferred_sync list before queuing it to
1013                  * sync_list because defer_sync is used for both lists.
1014                  */
1015                 list_del_init(&dev->links.defer_sync);
1016                 __device_links_queue_sync_state(dev, &sync_list);
1017         }
1018 out:
1019         device_links_write_unlock();
1020
1021         device_links_flush_sync_list(&sync_list, NULL);
1022 }
1023
1024 static int sync_state_resume_initcall(void)
1025 {
1026         device_links_supplier_sync_state_resume();
1027         return 0;
1028 }
1029 late_initcall(sync_state_resume_initcall);
1030
1031 static void __device_links_supplier_defer_sync(struct device *sup)
1032 {
1033         if (list_empty(&sup->links.defer_sync) && dev_has_sync_state(sup))
1034                 list_add_tail(&sup->links.defer_sync, &deferred_sync);
1035 }
1036
1037 static void device_link_drop_managed(struct device_link *link)
1038 {
1039         link->flags &= ~DL_FLAG_MANAGED;
1040         WRITE_ONCE(link->status, DL_STATE_NONE);
1041         kref_put(&link->kref, __device_link_del);
1042 }
1043
1044 /**
1045  * device_links_driver_bound - Update device links after probing its driver.
1046  * @dev: Device to update the links for.
1047  *
1048  * The probe has been successful, so update links from this device to any
1049  * consumers by changing their status to "available".
1050  *
1051  * Also change the status of @dev's links to suppliers to "active".
1052  *
1053  * Links without the DL_FLAG_MANAGED flag set are ignored.
1054  */
1055 void device_links_driver_bound(struct device *dev)
1056 {
1057         struct device_link *link, *ln;
1058         LIST_HEAD(sync_list);
1059
1060         /*
1061          * If a device probes successfully, it's expected to have created all
1062          * the device links it needs to or make new device links as it needs
1063          * them. So, it no longer needs to wait on any suppliers.
1064          */
1065         mutex_lock(&wfs_lock);
1066         list_del_init(&dev->links.needs_suppliers);
1067         mutex_unlock(&wfs_lock);
1068
1069         device_links_write_lock();
1070
1071         list_for_each_entry(link, &dev->links.consumers, s_node) {
1072                 if (!(link->flags & DL_FLAG_MANAGED))
1073                         continue;
1074
1075                 /*
1076                  * Links created during consumer probe may be in the "consumer
1077                  * probe" state to start with if the supplier is still probing
1078                  * when they are created and they may become "active" if the
1079                  * consumer probe returns first.  Skip them here.
1080                  */
1081                 if (link->status == DL_STATE_CONSUMER_PROBE ||
1082                     link->status == DL_STATE_ACTIVE)
1083                         continue;
1084
1085                 WARN_ON(link->status != DL_STATE_DORMANT);
1086                 WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1087
1088                 if (link->flags & DL_FLAG_AUTOPROBE_CONSUMER)
1089                         driver_deferred_probe_add(link->consumer);
1090         }
1091
1092         if (defer_sync_state_count)
1093                 __device_links_supplier_defer_sync(dev);
1094         else
1095                 __device_links_queue_sync_state(dev, &sync_list);
1096
1097         list_for_each_entry_safe(link, ln, &dev->links.suppliers, c_node) {
1098                 struct device *supplier;
1099
1100                 if (!(link->flags & DL_FLAG_MANAGED))
1101                         continue;
1102
1103                 supplier = link->supplier;
1104                 if (link->flags & DL_FLAG_SYNC_STATE_ONLY) {
1105                         /*
1106                          * When DL_FLAG_SYNC_STATE_ONLY is set, it means no
1107                          * other DL_MANAGED_LINK_FLAGS have been set. So, it's
1108                          * save to drop the managed link completely.
1109                          */
1110                         device_link_drop_managed(link);
1111                 } else {
1112                         WARN_ON(link->status != DL_STATE_CONSUMER_PROBE);
1113                         WRITE_ONCE(link->status, DL_STATE_ACTIVE);
1114                 }
1115
1116                 /*
1117                  * This needs to be done even for the deleted
1118                  * DL_FLAG_SYNC_STATE_ONLY device link in case it was the last
1119                  * device link that was preventing the supplier from getting a
1120                  * sync_state() call.
1121                  */
1122                 if (defer_sync_state_count)
1123                         __device_links_supplier_defer_sync(supplier);
1124                 else
1125                         __device_links_queue_sync_state(supplier, &sync_list);
1126         }
1127
1128         dev->links.status = DL_DEV_DRIVER_BOUND;
1129
1130         device_links_write_unlock();
1131
1132         device_links_flush_sync_list(&sync_list, dev);
1133 }
1134
1135 /**
1136  * __device_links_no_driver - Update links of a device without a driver.
1137  * @dev: Device without a drvier.
1138  *
1139  * Delete all non-persistent links from this device to any suppliers.
1140  *
1141  * Persistent links stay around, but their status is changed to "available",
1142  * unless they already are in the "supplier unbind in progress" state in which
1143  * case they need not be updated.
1144  *
1145  * Links without the DL_FLAG_MANAGED flag set are ignored.
1146  */
1147 static void __device_links_no_driver(struct device *dev)
1148 {
1149         struct device_link *link, *ln;
1150
1151         list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1152                 if (!(link->flags & DL_FLAG_MANAGED))
1153                         continue;
1154
1155                 if (link->flags & DL_FLAG_AUTOREMOVE_CONSUMER) {
1156                         device_link_drop_managed(link);
1157                         continue;
1158                 }
1159
1160                 if (link->status != DL_STATE_CONSUMER_PROBE &&
1161                     link->status != DL_STATE_ACTIVE)
1162                         continue;
1163
1164                 if (link->supplier->links.status == DL_DEV_DRIVER_BOUND) {
1165                         WRITE_ONCE(link->status, DL_STATE_AVAILABLE);
1166                 } else {
1167                         WARN_ON(!(link->flags & DL_FLAG_SYNC_STATE_ONLY));
1168                         WRITE_ONCE(link->status, DL_STATE_DORMANT);
1169                 }
1170         }
1171
1172         dev->links.status = DL_DEV_NO_DRIVER;
1173 }
1174
1175 /**
1176  * device_links_no_driver - Update links after failing driver probe.
1177  * @dev: Device whose driver has just failed to probe.
1178  *
1179  * Clean up leftover links to consumers for @dev and invoke
1180  * %__device_links_no_driver() to update links to suppliers for it as
1181  * appropriate.
1182  *
1183  * Links without the DL_FLAG_MANAGED flag set are ignored.
1184  */
1185 void device_links_no_driver(struct device *dev)
1186 {
1187         struct device_link *link;
1188
1189         device_links_write_lock();
1190
1191         list_for_each_entry(link, &dev->links.consumers, s_node) {
1192                 if (!(link->flags & DL_FLAG_MANAGED))
1193                         continue;
1194
1195                 /*
1196                  * The probe has failed, so if the status of the link is
1197                  * "consumer probe" or "active", it must have been added by
1198                  * a probing consumer while this device was still probing.
1199                  * Change its state to "dormant", as it represents a valid
1200                  * relationship, but it is not functionally meaningful.
1201                  */
1202                 if (link->status == DL_STATE_CONSUMER_PROBE ||
1203                     link->status == DL_STATE_ACTIVE)
1204                         WRITE_ONCE(link->status, DL_STATE_DORMANT);
1205         }
1206
1207         __device_links_no_driver(dev);
1208
1209         device_links_write_unlock();
1210 }
1211
1212 /**
1213  * device_links_driver_cleanup - Update links after driver removal.
1214  * @dev: Device whose driver has just gone away.
1215  *
1216  * Update links to consumers for @dev by changing their status to "dormant" and
1217  * invoke %__device_links_no_driver() to update links to suppliers for it as
1218  * appropriate.
1219  *
1220  * Links without the DL_FLAG_MANAGED flag set are ignored.
1221  */
1222 void device_links_driver_cleanup(struct device *dev)
1223 {
1224         struct device_link *link, *ln;
1225
1226         device_links_write_lock();
1227
1228         list_for_each_entry_safe(link, ln, &dev->links.consumers, s_node) {
1229                 if (!(link->flags & DL_FLAG_MANAGED))
1230                         continue;
1231
1232                 WARN_ON(link->flags & DL_FLAG_AUTOREMOVE_CONSUMER);
1233                 WARN_ON(link->status != DL_STATE_SUPPLIER_UNBIND);
1234
1235                 /*
1236                  * autoremove the links between this @dev and its consumer
1237                  * devices that are not active, i.e. where the link state
1238                  * has moved to DL_STATE_SUPPLIER_UNBIND.
1239                  */
1240                 if (link->status == DL_STATE_SUPPLIER_UNBIND &&
1241                     link->flags & DL_FLAG_AUTOREMOVE_SUPPLIER)
1242                         device_link_drop_managed(link);
1243
1244                 WRITE_ONCE(link->status, DL_STATE_DORMANT);
1245         }
1246
1247         list_del_init(&dev->links.defer_sync);
1248         __device_links_no_driver(dev);
1249
1250         device_links_write_unlock();
1251 }
1252
1253 /**
1254  * device_links_busy - Check if there are any busy links to consumers.
1255  * @dev: Device to check.
1256  *
1257  * Check each consumer of the device and return 'true' if its link's status
1258  * is one of "consumer probe" or "active" (meaning that the given consumer is
1259  * probing right now or its driver is present).  Otherwise, change the link
1260  * state to "supplier unbind" to prevent the consumer from being probed
1261  * successfully going forward.
1262  *
1263  * Return 'false' if there are no probing or active consumers.
1264  *
1265  * Links without the DL_FLAG_MANAGED flag set are ignored.
1266  */
1267 bool device_links_busy(struct device *dev)
1268 {
1269         struct device_link *link;
1270         bool ret = false;
1271
1272         device_links_write_lock();
1273
1274         list_for_each_entry(link, &dev->links.consumers, s_node) {
1275                 if (!(link->flags & DL_FLAG_MANAGED))
1276                         continue;
1277
1278                 if (link->status == DL_STATE_CONSUMER_PROBE
1279                     || link->status == DL_STATE_ACTIVE) {
1280                         ret = true;
1281                         break;
1282                 }
1283                 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1284         }
1285
1286         dev->links.status = DL_DEV_UNBINDING;
1287
1288         device_links_write_unlock();
1289         return ret;
1290 }
1291
1292 /**
1293  * device_links_unbind_consumers - Force unbind consumers of the given device.
1294  * @dev: Device to unbind the consumers of.
1295  *
1296  * Walk the list of links to consumers for @dev and if any of them is in the
1297  * "consumer probe" state, wait for all device probes in progress to complete
1298  * and start over.
1299  *
1300  * If that's not the case, change the status of the link to "supplier unbind"
1301  * and check if the link was in the "active" state.  If so, force the consumer
1302  * driver to unbind and start over (the consumer will not re-probe as we have
1303  * changed the state of the link already).
1304  *
1305  * Links without the DL_FLAG_MANAGED flag set are ignored.
1306  */
1307 void device_links_unbind_consumers(struct device *dev)
1308 {
1309         struct device_link *link;
1310
1311  start:
1312         device_links_write_lock();
1313
1314         list_for_each_entry(link, &dev->links.consumers, s_node) {
1315                 enum device_link_state status;
1316
1317                 if (!(link->flags & DL_FLAG_MANAGED) ||
1318                     link->flags & DL_FLAG_SYNC_STATE_ONLY)
1319                         continue;
1320
1321                 status = link->status;
1322                 if (status == DL_STATE_CONSUMER_PROBE) {
1323                         device_links_write_unlock();
1324
1325                         wait_for_device_probe();
1326                         goto start;
1327                 }
1328                 WRITE_ONCE(link->status, DL_STATE_SUPPLIER_UNBIND);
1329                 if (status == DL_STATE_ACTIVE) {
1330                         struct device *consumer = link->consumer;
1331
1332                         get_device(consumer);
1333
1334                         device_links_write_unlock();
1335
1336                         device_release_driver_internal(consumer, NULL,
1337                                                        consumer->parent);
1338                         put_device(consumer);
1339                         goto start;
1340                 }
1341         }
1342
1343         device_links_write_unlock();
1344 }
1345
1346 /**
1347  * device_links_purge - Delete existing links to other devices.
1348  * @dev: Target device.
1349  */
1350 static void device_links_purge(struct device *dev)
1351 {
1352         struct device_link *link, *ln;
1353
1354         if (dev->class == &devlink_class)
1355                 return;
1356
1357         mutex_lock(&wfs_lock);
1358         list_del(&dev->links.needs_suppliers);
1359         mutex_unlock(&wfs_lock);
1360
1361         /*
1362          * Delete all of the remaining links from this device to any other
1363          * devices (either consumers or suppliers).
1364          */
1365         device_links_write_lock();
1366
1367         list_for_each_entry_safe_reverse(link, ln, &dev->links.suppliers, c_node) {
1368                 WARN_ON(link->status == DL_STATE_ACTIVE);
1369                 __device_link_del(&link->kref);
1370         }
1371
1372         list_for_each_entry_safe_reverse(link, ln, &dev->links.consumers, s_node) {
1373                 WARN_ON(link->status != DL_STATE_DORMANT &&
1374                         link->status != DL_STATE_NONE);
1375                 __device_link_del(&link->kref);
1376         }
1377
1378         device_links_write_unlock();
1379 }
1380
1381 static u32 fw_devlink_flags = DL_FLAG_SYNC_STATE_ONLY;
1382 static int __init fw_devlink_setup(char *arg)
1383 {
1384         if (!arg)
1385                 return -EINVAL;
1386
1387         if (strcmp(arg, "off") == 0) {
1388                 fw_devlink_flags = 0;
1389         } else if (strcmp(arg, "permissive") == 0) {
1390                 fw_devlink_flags = DL_FLAG_SYNC_STATE_ONLY;
1391         } else if (strcmp(arg, "on") == 0) {
1392                 fw_devlink_flags = DL_FLAG_AUTOPROBE_CONSUMER;
1393         } else if (strcmp(arg, "rpm") == 0) {
1394                 fw_devlink_flags = DL_FLAG_AUTOPROBE_CONSUMER |
1395                                    DL_FLAG_PM_RUNTIME;
1396         }
1397         return 0;
1398 }
1399 early_param("fw_devlink", fw_devlink_setup);
1400
1401 u32 fw_devlink_get_flags(void)
1402 {
1403         return fw_devlink_flags;
1404 }
1405
1406 static bool fw_devlink_is_permissive(void)
1407 {
1408         return fw_devlink_flags == DL_FLAG_SYNC_STATE_ONLY;
1409 }
1410
1411 static void fw_devlink_link_device(struct device *dev)
1412 {
1413         int fw_ret;
1414
1415         if (!fw_devlink_flags)
1416                 return;
1417
1418         mutex_lock(&defer_fw_devlink_lock);
1419         if (!defer_fw_devlink_count)
1420                 device_link_add_missing_supplier_links();
1421
1422         /*
1423          * The device's fwnode not having add_links() doesn't affect if other
1424          * consumers can find this device as a supplier.  So, this check is
1425          * intentionally placed after device_link_add_missing_supplier_links().
1426          */
1427         if (!fwnode_has_op(dev->fwnode, add_links))
1428                 goto out;
1429
1430         /*
1431          * If fw_devlink is being deferred, assume all devices have mandatory
1432          * suppliers they need to link to later. Then, when the fw_devlink is
1433          * resumed, all these devices will get a chance to try and link to any
1434          * suppliers they have.
1435          */
1436         if (!defer_fw_devlink_count) {
1437                 fw_ret = fwnode_call_int_op(dev->fwnode, add_links, dev);
1438                 if (fw_ret == -ENODEV && fw_devlink_is_permissive())
1439                         fw_ret = -EAGAIN;
1440         } else {
1441                 fw_ret = -ENODEV;
1442         }
1443
1444         if (fw_ret == -ENODEV)
1445                 device_link_wait_for_mandatory_supplier(dev);
1446         else if (fw_ret)
1447                 device_link_wait_for_optional_supplier(dev);
1448
1449 out:
1450         mutex_unlock(&defer_fw_devlink_lock);
1451 }
1452
1453 /**
1454  * fw_devlink_pause - Pause parsing of fwnode to create device links
1455  *
1456  * Calling this function defers any fwnode parsing to create device links until
1457  * fw_devlink_resume() is called. Both these functions are ref counted and the
1458  * caller needs to match the calls.
1459  *
1460  * While fw_devlink is paused:
1461  * - Any device that is added won't have its fwnode parsed to create device
1462  *   links.
1463  * - The probe of the device will also be deferred during this period.
1464  * - Any devices that were already added, but waiting for suppliers won't be
1465  *   able to link to newly added devices.
1466  *
1467  * Once fw_devlink_resume():
1468  * - All the fwnodes that was not parsed will be parsed.
1469  * - All the devices that were deferred probing will be reattempted if they
1470  *   aren't waiting for any more suppliers.
1471  *
1472  * This pair of functions, is mainly meant to optimize the parsing of fwnodes
1473  * when a lot of devices that need to link to each other are added in a short
1474  * interval of time. For example, adding all the top level devices in a system.
1475  *
1476  * For example, if N devices are added and:
1477  * - All the consumers are added before their suppliers
1478  * - All the suppliers of the N devices are part of the N devices
1479  *
1480  * Then:
1481  *
1482  * - With the use of fw_devlink_pause() and fw_devlink_resume(), each device
1483  *   will only need one parsing of its fwnode because it is guaranteed to find
1484  *   all the supplier devices already registered and ready to link to. It won't
1485  *   have to do another pass later to find one or more suppliers it couldn't
1486  *   find in the first parse of the fwnode. So, we'll only need O(N) fwnode
1487  *   parses.
1488  *
1489  * - Without the use of fw_devlink_pause() and fw_devlink_resume(), we would
1490  *   end up doing O(N^2) parses of fwnodes because every device that's added is
1491  *   guaranteed to trigger a parse of the fwnode of every device added before
1492  *   it. This O(N^2) parse is made worse by the fact that when a fwnode of a
1493  *   device is parsed, all it descendant devices might need to have their
1494  *   fwnodes parsed too (even if the devices themselves aren't added).
1495  */
1496 void fw_devlink_pause(void)
1497 {
1498         mutex_lock(&defer_fw_devlink_lock);
1499         defer_fw_devlink_count++;
1500         mutex_unlock(&defer_fw_devlink_lock);
1501 }
1502
1503 /** fw_devlink_resume - Resume parsing of fwnode to create device links
1504  *
1505  * This function is used in conjunction with fw_devlink_pause() and is ref
1506  * counted. See documentation for fw_devlink_pause() for more details.
1507  */
1508 void fw_devlink_resume(void)
1509 {
1510         mutex_lock(&defer_fw_devlink_lock);
1511         if (!defer_fw_devlink_count) {
1512                 WARN(true, "Unmatched fw_devlink pause/resume!");
1513                 goto out;
1514         }
1515
1516         defer_fw_devlink_count--;
1517         if (defer_fw_devlink_count)
1518                 goto out;
1519
1520         device_link_add_missing_supplier_links();
1521         driver_deferred_probe_force_trigger();
1522 out:
1523         mutex_unlock(&defer_fw_devlink_lock);
1524 }
1525 /* Device links support end. */
1526
1527 int (*platform_notify)(struct device *dev) = NULL;
1528 int (*platform_notify_remove)(struct device *dev) = NULL;
1529 static struct kobject *dev_kobj;
1530 struct kobject *sysfs_dev_char_kobj;
1531 struct kobject *sysfs_dev_block_kobj;
1532
1533 static DEFINE_MUTEX(device_hotplug_lock);
1534
1535 void lock_device_hotplug(void)
1536 {
1537         mutex_lock(&device_hotplug_lock);
1538 }
1539
1540 void unlock_device_hotplug(void)
1541 {
1542         mutex_unlock(&device_hotplug_lock);
1543 }
1544
1545 int lock_device_hotplug_sysfs(void)
1546 {
1547         if (mutex_trylock(&device_hotplug_lock))
1548                 return 0;
1549
1550         /* Avoid busy looping (5 ms of sleep should do). */
1551         msleep(5);
1552         return restart_syscall();
1553 }
1554
1555 #ifdef CONFIG_BLOCK
1556 static inline int device_is_not_partition(struct device *dev)
1557 {
1558         return !(dev->type == &part_type);
1559 }
1560 #else
1561 static inline int device_is_not_partition(struct device *dev)
1562 {
1563         return 1;
1564 }
1565 #endif
1566
1567 static int
1568 device_platform_notify(struct device *dev, enum kobject_action action)
1569 {
1570         int ret;
1571
1572         ret = acpi_platform_notify(dev, action);
1573         if (ret)
1574                 return ret;
1575
1576         ret = software_node_notify(dev, action);
1577         if (ret)
1578                 return ret;
1579
1580         if (platform_notify && action == KOBJ_ADD)
1581                 platform_notify(dev);
1582         else if (platform_notify_remove && action == KOBJ_REMOVE)
1583                 platform_notify_remove(dev);
1584         return 0;
1585 }
1586
1587 /**
1588  * dev_driver_string - Return a device's driver name, if at all possible
1589  * @dev: struct device to get the name of
1590  *
1591  * Will return the device's driver's name if it is bound to a device.  If
1592  * the device is not bound to a driver, it will return the name of the bus
1593  * it is attached to.  If it is not attached to a bus either, an empty
1594  * string will be returned.
1595  */
1596 const char *dev_driver_string(const struct device *dev)
1597 {
1598         struct device_driver *drv;
1599
1600         /* dev->driver can change to NULL underneath us because of unbinding,
1601          * so be careful about accessing it.  dev->bus and dev->class should
1602          * never change once they are set, so they don't need special care.
1603          */
1604         drv = READ_ONCE(dev->driver);
1605         return drv ? drv->name :
1606                         (dev->bus ? dev->bus->name :
1607                         (dev->class ? dev->class->name : ""));
1608 }
1609 EXPORT_SYMBOL(dev_driver_string);
1610
1611 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
1612
1613 static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
1614                              char *buf)
1615 {
1616         struct device_attribute *dev_attr = to_dev_attr(attr);
1617         struct device *dev = kobj_to_dev(kobj);
1618         ssize_t ret = -EIO;
1619
1620         if (dev_attr->show)
1621                 ret = dev_attr->show(dev, dev_attr, buf);
1622         if (ret >= (ssize_t)PAGE_SIZE) {
1623                 printk("dev_attr_show: %pS returned bad count\n",
1624                                 dev_attr->show);
1625         }
1626         return ret;
1627 }
1628
1629 static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
1630                               const char *buf, size_t count)
1631 {
1632         struct device_attribute *dev_attr = to_dev_attr(attr);
1633         struct device *dev = kobj_to_dev(kobj);
1634         ssize_t ret = -EIO;
1635
1636         if (dev_attr->store)
1637                 ret = dev_attr->store(dev, dev_attr, buf, count);
1638         return ret;
1639 }
1640
1641 static const struct sysfs_ops dev_sysfs_ops = {
1642         .show   = dev_attr_show,
1643         .store  = dev_attr_store,
1644 };
1645
1646 #define to_ext_attr(x) container_of(x, struct dev_ext_attribute, attr)
1647
1648 ssize_t device_store_ulong(struct device *dev,
1649                            struct device_attribute *attr,
1650                            const char *buf, size_t size)
1651 {
1652         struct dev_ext_attribute *ea = to_ext_attr(attr);
1653         int ret;
1654         unsigned long new;
1655
1656         ret = kstrtoul(buf, 0, &new);
1657         if (ret)
1658                 return ret;
1659         *(unsigned long *)(ea->var) = new;
1660         /* Always return full write size even if we didn't consume all */
1661         return size;
1662 }
1663 EXPORT_SYMBOL_GPL(device_store_ulong);
1664
1665 ssize_t device_show_ulong(struct device *dev,
1666                           struct device_attribute *attr,
1667                           char *buf)
1668 {
1669         struct dev_ext_attribute *ea = to_ext_attr(attr);
1670         return snprintf(buf, PAGE_SIZE, "%lx\n", *(unsigned long *)(ea->var));
1671 }
1672 EXPORT_SYMBOL_GPL(device_show_ulong);
1673
1674 ssize_t device_store_int(struct device *dev,
1675                          struct device_attribute *attr,
1676                          const char *buf, size_t size)
1677 {
1678         struct dev_ext_attribute *ea = to_ext_attr(attr);
1679         int ret;
1680         long new;
1681
1682         ret = kstrtol(buf, 0, &new);
1683         if (ret)
1684                 return ret;
1685
1686         if (new > INT_MAX || new < INT_MIN)
1687                 return -EINVAL;
1688         *(int *)(ea->var) = new;
1689         /* Always return full write size even if we didn't consume all */
1690         return size;
1691 }
1692 EXPORT_SYMBOL_GPL(device_store_int);
1693
1694 ssize_t device_show_int(struct device *dev,
1695                         struct device_attribute *attr,
1696                         char *buf)
1697 {
1698         struct dev_ext_attribute *ea = to_ext_attr(attr);
1699
1700         return snprintf(buf, PAGE_SIZE, "%d\n", *(int *)(ea->var));
1701 }
1702 EXPORT_SYMBOL_GPL(device_show_int);
1703
1704 ssize_t device_store_bool(struct device *dev, struct device_attribute *attr,
1705                           const char *buf, size_t size)
1706 {
1707         struct dev_ext_attribute *ea = to_ext_attr(attr);
1708
1709         if (strtobool(buf, ea->var) < 0)
1710                 return -EINVAL;
1711
1712         return size;
1713 }
1714 EXPORT_SYMBOL_GPL(device_store_bool);
1715
1716 ssize_t device_show_bool(struct device *dev, struct device_attribute *attr,
1717                          char *buf)
1718 {
1719         struct dev_ext_attribute *ea = to_ext_attr(attr);
1720
1721         return snprintf(buf, PAGE_SIZE, "%d\n", *(bool *)(ea->var));
1722 }
1723 EXPORT_SYMBOL_GPL(device_show_bool);
1724
1725 /**
1726  * device_release - free device structure.
1727  * @kobj: device's kobject.
1728  *
1729  * This is called once the reference count for the object
1730  * reaches 0. We forward the call to the device's release
1731  * method, which should handle actually freeing the structure.
1732  */
1733 static void device_release(struct kobject *kobj)
1734 {
1735         struct device *dev = kobj_to_dev(kobj);
1736         struct device_private *p = dev->p;
1737
1738         /*
1739          * Some platform devices are driven without driver attached
1740          * and managed resources may have been acquired.  Make sure
1741          * all resources are released.
1742          *
1743          * Drivers still can add resources into device after device
1744          * is deleted but alive, so release devres here to avoid
1745          * possible memory leak.
1746          */
1747         devres_release_all(dev);
1748
1749         if (dev->release)
1750                 dev->release(dev);
1751         else if (dev->type && dev->type->release)
1752                 dev->type->release(dev);
1753         else if (dev->class && dev->class->dev_release)
1754                 dev->class->dev_release(dev);
1755         else
1756                 WARN(1, KERN_ERR "Device '%s' does not have a release() function, it is broken and must be fixed. See Documentation/core-api/kobject.rst.\n",
1757                         dev_name(dev));
1758         kfree(p);
1759 }
1760
1761 static const void *device_namespace(struct kobject *kobj)
1762 {
1763         struct device *dev = kobj_to_dev(kobj);
1764         const void *ns = NULL;
1765
1766         if (dev->class && dev->class->ns_type)
1767                 ns = dev->class->namespace(dev);
1768
1769         return ns;
1770 }
1771
1772 static void device_get_ownership(struct kobject *kobj, kuid_t *uid, kgid_t *gid)
1773 {
1774         struct device *dev = kobj_to_dev(kobj);
1775
1776         if (dev->class && dev->class->get_ownership)
1777                 dev->class->get_ownership(dev, uid, gid);
1778 }
1779
1780 static struct kobj_type device_ktype = {
1781         .release        = device_release,
1782         .sysfs_ops      = &dev_sysfs_ops,
1783         .namespace      = device_namespace,
1784         .get_ownership  = device_get_ownership,
1785 };
1786
1787
1788 static int dev_uevent_filter(struct kset *kset, struct kobject *kobj)
1789 {
1790         struct kobj_type *ktype = get_ktype(kobj);
1791
1792         if (ktype == &device_ktype) {
1793                 struct device *dev = kobj_to_dev(kobj);
1794                 if (dev->bus)
1795                         return 1;
1796                 if (dev->class)
1797                         return 1;
1798         }
1799         return 0;
1800 }
1801
1802 static const char *dev_uevent_name(struct kset *kset, struct kobject *kobj)
1803 {
1804         struct device *dev = kobj_to_dev(kobj);
1805
1806         if (dev->bus)
1807                 return dev->bus->name;
1808         if (dev->class)
1809                 return dev->class->name;
1810         return NULL;
1811 }
1812
1813 static int dev_uevent(struct kset *kset, struct kobject *kobj,
1814                       struct kobj_uevent_env *env)
1815 {
1816         struct device *dev = kobj_to_dev(kobj);
1817         int retval = 0;
1818
1819         /* add device node properties if present */
1820         if (MAJOR(dev->devt)) {
1821                 const char *tmp;
1822                 const char *name;
1823                 umode_t mode = 0;
1824                 kuid_t uid = GLOBAL_ROOT_UID;
1825                 kgid_t gid = GLOBAL_ROOT_GID;
1826
1827                 add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt));
1828                 add_uevent_var(env, "MINOR=%u", MINOR(dev->devt));
1829                 name = device_get_devnode(dev, &mode, &uid, &gid, &tmp);
1830                 if (name) {
1831                         add_uevent_var(env, "DEVNAME=%s", name);
1832                         if (mode)
1833                                 add_uevent_var(env, "DEVMODE=%#o", mode & 0777);
1834                         if (!uid_eq(uid, GLOBAL_ROOT_UID))
1835                                 add_uevent_var(env, "DEVUID=%u", from_kuid(&init_user_ns, uid));
1836                         if (!gid_eq(gid, GLOBAL_ROOT_GID))
1837                                 add_uevent_var(env, "DEVGID=%u", from_kgid(&init_user_ns, gid));
1838                         kfree(tmp);
1839                 }
1840         }
1841
1842         if (dev->type && dev->type->name)
1843                 add_uevent_var(env, "DEVTYPE=%s", dev->type->name);
1844
1845         if (dev->driver)
1846                 add_uevent_var(env, "DRIVER=%s", dev->driver->name);
1847
1848         /* Add common DT information about the device */
1849         of_device_uevent(dev, env);
1850
1851         /* have the bus specific function add its stuff */
1852         if (dev->bus && dev->bus->uevent) {
1853                 retval = dev->bus->uevent(dev, env);
1854                 if (retval)
1855                         pr_debug("device: '%s': %s: bus uevent() returned %d\n",
1856                                  dev_name(dev), __func__, retval);
1857         }
1858
1859         /* have the class specific function add its stuff */
1860         if (dev->class && dev->class->dev_uevent) {
1861                 retval = dev->class->dev_uevent(dev, env);
1862                 if (retval)
1863                         pr_debug("device: '%s': %s: class uevent() "
1864                                  "returned %d\n", dev_name(dev),
1865                                  __func__, retval);
1866         }
1867
1868         /* have the device type specific function add its stuff */
1869         if (dev->type && dev->type->uevent) {
1870                 retval = dev->type->uevent(dev, env);
1871                 if (retval)
1872                         pr_debug("device: '%s': %s: dev_type uevent() "
1873                                  "returned %d\n", dev_name(dev),
1874                                  __func__, retval);
1875         }
1876
1877         return retval;
1878 }
1879
1880 static const struct kset_uevent_ops device_uevent_ops = {
1881         .filter =       dev_uevent_filter,
1882         .name =         dev_uevent_name,
1883         .uevent =       dev_uevent,
1884 };
1885
1886 static ssize_t uevent_show(struct device *dev, struct device_attribute *attr,
1887                            char *buf)
1888 {
1889         struct kobject *top_kobj;
1890         struct kset *kset;
1891         struct kobj_uevent_env *env = NULL;
1892         int i;
1893         size_t count = 0;
1894         int retval;
1895
1896         /* search the kset, the device belongs to */
1897         top_kobj = &dev->kobj;
1898         while (!top_kobj->kset && top_kobj->parent)
1899                 top_kobj = top_kobj->parent;
1900         if (!top_kobj->kset)
1901                 goto out;
1902
1903         kset = top_kobj->kset;
1904         if (!kset->uevent_ops || !kset->uevent_ops->uevent)
1905                 goto out;
1906
1907         /* respect filter */
1908         if (kset->uevent_ops && kset->uevent_ops->filter)
1909                 if (!kset->uevent_ops->filter(kset, &dev->kobj))
1910                         goto out;
1911
1912         env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
1913         if (!env)
1914                 return -ENOMEM;
1915
1916         /* let the kset specific function add its keys */
1917         retval = kset->uevent_ops->uevent(kset, &dev->kobj, env);
1918         if (retval)
1919                 goto out;
1920
1921         /* copy keys to file */
1922         for (i = 0; i < env->envp_idx; i++)
1923                 count += sprintf(&buf[count], "%s\n", env->envp[i]);
1924 out:
1925         kfree(env);
1926         return count;
1927 }
1928
1929 static ssize_t uevent_store(struct device *dev, struct device_attribute *attr,
1930                             const char *buf, size_t count)
1931 {
1932         int rc;
1933
1934         rc = kobject_synth_uevent(&dev->kobj, buf, count);
1935
1936         if (rc) {
1937                 dev_err(dev, "uevent: failed to send synthetic uevent\n");
1938                 return rc;
1939         }
1940
1941         return count;
1942 }
1943 static DEVICE_ATTR_RW(uevent);
1944
1945 static ssize_t online_show(struct device *dev, struct device_attribute *attr,
1946                            char *buf)
1947 {
1948         bool val;
1949
1950         device_lock(dev);
1951         val = !dev->offline;
1952         device_unlock(dev);
1953         return sprintf(buf, "%u\n", val);
1954 }
1955
1956 static ssize_t online_store(struct device *dev, struct device_attribute *attr,
1957                             const char *buf, size_t count)
1958 {
1959         bool val;
1960         int ret;
1961
1962         ret = strtobool(buf, &val);
1963         if (ret < 0)
1964                 return ret;
1965
1966         ret = lock_device_hotplug_sysfs();
1967         if (ret)
1968                 return ret;
1969
1970         ret = val ? device_online(dev) : device_offline(dev);
1971         unlock_device_hotplug();
1972         return ret < 0 ? ret : count;
1973 }
1974 static DEVICE_ATTR_RW(online);
1975
1976 int device_add_groups(struct device *dev, const struct attribute_group **groups)
1977 {
1978         return sysfs_create_groups(&dev->kobj, groups);
1979 }
1980 EXPORT_SYMBOL_GPL(device_add_groups);
1981
1982 void device_remove_groups(struct device *dev,
1983                           const struct attribute_group **groups)
1984 {
1985         sysfs_remove_groups(&dev->kobj, groups);
1986 }
1987 EXPORT_SYMBOL_GPL(device_remove_groups);
1988
1989 union device_attr_group_devres {
1990         const struct attribute_group *group;
1991         const struct attribute_group **groups;
1992 };
1993
1994 static int devm_attr_group_match(struct device *dev, void *res, void *data)
1995 {
1996         return ((union device_attr_group_devres *)res)->group == data;
1997 }
1998
1999 static void devm_attr_group_remove(struct device *dev, void *res)
2000 {
2001         union device_attr_group_devres *devres = res;
2002         const struct attribute_group *group = devres->group;
2003
2004         dev_dbg(dev, "%s: removing group %p\n", __func__, group);
2005         sysfs_remove_group(&dev->kobj, group);
2006 }
2007
2008 static void devm_attr_groups_remove(struct device *dev, void *res)
2009 {
2010         union device_attr_group_devres *devres = res;
2011         const struct attribute_group **groups = devres->groups;
2012
2013         dev_dbg(dev, "%s: removing groups %p\n", __func__, groups);
2014         sysfs_remove_groups(&dev->kobj, groups);
2015 }
2016
2017 /**
2018  * devm_device_add_group - given a device, create a managed attribute group
2019  * @dev:        The device to create the group for
2020  * @grp:        The attribute group to create
2021  *
2022  * This function creates a group for the first time.  It will explicitly
2023  * warn and error if any of the attribute files being created already exist.
2024  *
2025  * Returns 0 on success or error code on failure.
2026  */
2027 int devm_device_add_group(struct device *dev, const struct attribute_group *grp)
2028 {
2029         union device_attr_group_devres *devres;
2030         int error;
2031
2032         devres = devres_alloc(devm_attr_group_remove,
2033                               sizeof(*devres), GFP_KERNEL);
2034         if (!devres)
2035                 return -ENOMEM;
2036
2037         error = sysfs_create_group(&dev->kobj, grp);
2038         if (error) {
2039                 devres_free(devres);
2040                 return error;
2041         }
2042
2043         devres->group = grp;
2044         devres_add(dev, devres);
2045         return 0;
2046 }
2047 EXPORT_SYMBOL_GPL(devm_device_add_group);
2048
2049 /**
2050  * devm_device_remove_group: remove a managed group from a device
2051  * @dev:        device to remove the group from
2052  * @grp:        group to remove
2053  *
2054  * This function removes a group of attributes from a device. The attributes
2055  * previously have to have been created for this group, otherwise it will fail.
2056  */
2057 void devm_device_remove_group(struct device *dev,
2058                               const struct attribute_group *grp)
2059 {
2060         WARN_ON(devres_release(dev, devm_attr_group_remove,
2061                                devm_attr_group_match,
2062                                /* cast away const */ (void *)grp));
2063 }
2064 EXPORT_SYMBOL_GPL(devm_device_remove_group);
2065
2066 /**
2067  * devm_device_add_groups - create a bunch of managed attribute groups
2068  * @dev:        The device to create the group for
2069  * @groups:     The attribute groups to create, NULL terminated
2070  *
2071  * This function creates a bunch of managed attribute groups.  If an error
2072  * occurs when creating a group, all previously created groups will be
2073  * removed, unwinding everything back to the original state when this
2074  * function was called.  It will explicitly warn and error if any of the
2075  * attribute files being created already exist.
2076  *
2077  * Returns 0 on success or error code from sysfs_create_group on failure.
2078  */
2079 int devm_device_add_groups(struct device *dev,
2080                            const struct attribute_group **groups)
2081 {
2082         union device_attr_group_devres *devres;
2083         int error;
2084
2085         devres = devres_alloc(devm_attr_groups_remove,
2086                               sizeof(*devres), GFP_KERNEL);
2087         if (!devres)
2088                 return -ENOMEM;
2089
2090         error = sysfs_create_groups(&dev->kobj, groups);
2091         if (error) {
2092                 devres_free(devres);
2093                 return error;
2094         }
2095
2096         devres->groups = groups;
2097         devres_add(dev, devres);
2098         return 0;
2099 }
2100 EXPORT_SYMBOL_GPL(devm_device_add_groups);
2101
2102 /**
2103  * devm_device_remove_groups - remove a list of managed groups
2104  *
2105  * @dev:        The device for the groups to be removed from
2106  * @groups:     NULL terminated list of groups to be removed
2107  *
2108  * If groups is not NULL, remove the specified groups from the device.
2109  */
2110 void devm_device_remove_groups(struct device *dev,
2111                                const struct attribute_group **groups)
2112 {
2113         WARN_ON(devres_release(dev, devm_attr_groups_remove,
2114                                devm_attr_group_match,
2115                                /* cast away const */ (void *)groups));
2116 }
2117 EXPORT_SYMBOL_GPL(devm_device_remove_groups);
2118
2119 static int device_add_attrs(struct device *dev)
2120 {
2121         struct class *class = dev->class;
2122         const struct device_type *type = dev->type;
2123         int error;
2124
2125         if (class) {
2126                 error = device_add_groups(dev, class->dev_groups);
2127                 if (error)
2128                         return error;
2129         }
2130
2131         if (type) {
2132                 error = device_add_groups(dev, type->groups);
2133                 if (error)
2134                         goto err_remove_class_groups;
2135         }
2136
2137         error = device_add_groups(dev, dev->groups);
2138         if (error)
2139                 goto err_remove_type_groups;
2140
2141         if (device_supports_offline(dev) && !dev->offline_disabled) {
2142                 error = device_create_file(dev, &dev_attr_online);
2143                 if (error)
2144                         goto err_remove_dev_groups;
2145         }
2146
2147         return 0;
2148
2149  err_remove_dev_groups:
2150         device_remove_groups(dev, dev->groups);
2151  err_remove_type_groups:
2152         if (type)
2153                 device_remove_groups(dev, type->groups);
2154  err_remove_class_groups:
2155         if (class)
2156                 device_remove_groups(dev, class->dev_groups);
2157
2158         return error;
2159 }
2160
2161 static void device_remove_attrs(struct device *dev)
2162 {
2163         struct class *class = dev->class;
2164         const struct device_type *type = dev->type;
2165
2166         device_remove_file(dev, &dev_attr_online);
2167         device_remove_groups(dev, dev->groups);
2168
2169         if (type)
2170                 device_remove_groups(dev, type->groups);
2171
2172         if (class)
2173                 device_remove_groups(dev, class->dev_groups);
2174 }
2175
2176 static ssize_t dev_show(struct device *dev, struct device_attribute *attr,
2177                         char *buf)
2178 {
2179         return print_dev_t(buf, dev->devt);
2180 }
2181 static DEVICE_ATTR_RO(dev);
2182
2183 /* /sys/devices/ */
2184 struct kset *devices_kset;
2185
2186 /**
2187  * devices_kset_move_before - Move device in the devices_kset's list.
2188  * @deva: Device to move.
2189  * @devb: Device @deva should come before.
2190  */
2191 static void devices_kset_move_before(struct device *deva, struct device *devb)
2192 {
2193         if (!devices_kset)
2194                 return;
2195         pr_debug("devices_kset: Moving %s before %s\n",
2196                  dev_name(deva), dev_name(devb));
2197         spin_lock(&devices_kset->list_lock);
2198         list_move_tail(&deva->kobj.entry, &devb->kobj.entry);
2199         spin_unlock(&devices_kset->list_lock);
2200 }
2201
2202 /**
2203  * devices_kset_move_after - Move device in the devices_kset's list.
2204  * @deva: Device to move
2205  * @devb: Device @deva should come after.
2206  */
2207 static void devices_kset_move_after(struct device *deva, struct device *devb)
2208 {
2209         if (!devices_kset)
2210                 return;
2211         pr_debug("devices_kset: Moving %s after %s\n",
2212                  dev_name(deva), dev_name(devb));
2213         spin_lock(&devices_kset->list_lock);
2214         list_move(&deva->kobj.entry, &devb->kobj.entry);
2215         spin_unlock(&devices_kset->list_lock);
2216 }
2217
2218 /**
2219  * devices_kset_move_last - move the device to the end of devices_kset's list.
2220  * @dev: device to move
2221  */
2222 void devices_kset_move_last(struct device *dev)
2223 {
2224         if (!devices_kset)
2225                 return;
2226         pr_debug("devices_kset: Moving %s to end of list\n", dev_name(dev));
2227         spin_lock(&devices_kset->list_lock);
2228         list_move_tail(&dev->kobj.entry, &devices_kset->list);
2229         spin_unlock(&devices_kset->list_lock);
2230 }
2231
2232 /**
2233  * device_create_file - create sysfs attribute file for device.
2234  * @dev: device.
2235  * @attr: device attribute descriptor.
2236  */
2237 int device_create_file(struct device *dev,
2238                        const struct device_attribute *attr)
2239 {
2240         int error = 0;
2241
2242         if (dev) {
2243                 WARN(((attr->attr.mode & S_IWUGO) && !attr->store),
2244                         "Attribute %s: write permission without 'store'\n",
2245                         attr->attr.name);
2246                 WARN(((attr->attr.mode & S_IRUGO) && !attr->show),
2247                         "Attribute %s: read permission without 'show'\n",
2248                         attr->attr.name);
2249                 error = sysfs_create_file(&dev->kobj, &attr->attr);
2250         }
2251
2252         return error;
2253 }
2254 EXPORT_SYMBOL_GPL(device_create_file);
2255
2256 /**
2257  * device_remove_file - remove sysfs attribute file.
2258  * @dev: device.
2259  * @attr: device attribute descriptor.
2260  */
2261 void device_remove_file(struct device *dev,
2262                         const struct device_attribute *attr)
2263 {
2264         if (dev)
2265                 sysfs_remove_file(&dev->kobj, &attr->attr);
2266 }
2267 EXPORT_SYMBOL_GPL(device_remove_file);
2268
2269 /**
2270  * device_remove_file_self - remove sysfs attribute file from its own method.
2271  * @dev: device.
2272  * @attr: device attribute descriptor.
2273  *
2274  * See kernfs_remove_self() for details.
2275  */
2276 bool device_remove_file_self(struct device *dev,
2277                              const struct device_attribute *attr)
2278 {
2279         if (dev)
2280                 return sysfs_remove_file_self(&dev->kobj, &attr->attr);
2281         else
2282                 return false;
2283 }
2284 EXPORT_SYMBOL_GPL(device_remove_file_self);
2285
2286 /**
2287  * device_create_bin_file - create sysfs binary attribute file for device.
2288  * @dev: device.
2289  * @attr: device binary attribute descriptor.
2290  */
2291 int device_create_bin_file(struct device *dev,
2292                            const struct bin_attribute *attr)
2293 {
2294         int error = -EINVAL;
2295         if (dev)
2296                 error = sysfs_create_bin_file(&dev->kobj, attr);
2297         return error;
2298 }
2299 EXPORT_SYMBOL_GPL(device_create_bin_file);
2300
2301 /**
2302  * device_remove_bin_file - remove sysfs binary attribute file
2303  * @dev: device.
2304  * @attr: device binary attribute descriptor.
2305  */
2306 void device_remove_bin_file(struct device *dev,
2307                             const struct bin_attribute *attr)
2308 {
2309         if (dev)
2310                 sysfs_remove_bin_file(&dev->kobj, attr);
2311 }
2312 EXPORT_SYMBOL_GPL(device_remove_bin_file);
2313
2314 static void klist_children_get(struct klist_node *n)
2315 {
2316         struct device_private *p = to_device_private_parent(n);
2317         struct device *dev = p->device;
2318
2319         get_device(dev);
2320 }
2321
2322 static void klist_children_put(struct klist_node *n)
2323 {
2324         struct device_private *p = to_device_private_parent(n);
2325         struct device *dev = p->device;
2326
2327         put_device(dev);
2328 }
2329
2330 /**
2331  * device_initialize - init device structure.
2332  * @dev: device.
2333  *
2334  * This prepares the device for use by other layers by initializing
2335  * its fields.
2336  * It is the first half of device_register(), if called by
2337  * that function, though it can also be called separately, so one
2338  * may use @dev's fields. In particular, get_device()/put_device()
2339  * may be used for reference counting of @dev after calling this
2340  * function.
2341  *
2342  * All fields in @dev must be initialized by the caller to 0, except
2343  * for those explicitly set to some other value.  The simplest
2344  * approach is to use kzalloc() to allocate the structure containing
2345  * @dev.
2346  *
2347  * NOTE: Use put_device() to give up your reference instead of freeing
2348  * @dev directly once you have called this function.
2349  */
2350 void device_initialize(struct device *dev)
2351 {
2352         dev->kobj.kset = devices_kset;
2353         kobject_init(&dev->kobj, &device_ktype);
2354         INIT_LIST_HEAD(&dev->dma_pools);
2355         mutex_init(&dev->mutex);
2356 #ifdef CONFIG_PROVE_LOCKING
2357         mutex_init(&dev->lockdep_mutex);
2358 #endif
2359         lockdep_set_novalidate_class(&dev->mutex);
2360         spin_lock_init(&dev->devres_lock);
2361         INIT_LIST_HEAD(&dev->devres_head);
2362         device_pm_init(dev);
2363         set_dev_node(dev, -1);
2364 #ifdef CONFIG_GENERIC_MSI_IRQ
2365         INIT_LIST_HEAD(&dev->msi_list);
2366 #endif
2367         INIT_LIST_HEAD(&dev->links.consumers);
2368         INIT_LIST_HEAD(&dev->links.suppliers);
2369         INIT_LIST_HEAD(&dev->links.needs_suppliers);
2370         INIT_LIST_HEAD(&dev->links.defer_sync);
2371         dev->links.status = DL_DEV_NO_DRIVER;
2372 }
2373 EXPORT_SYMBOL_GPL(device_initialize);
2374
2375 struct kobject *virtual_device_parent(struct device *dev)
2376 {
2377         static struct kobject *virtual_dir = NULL;
2378
2379         if (!virtual_dir)
2380                 virtual_dir = kobject_create_and_add("virtual",
2381                                                      &devices_kset->kobj);
2382
2383         return virtual_dir;
2384 }
2385
2386 struct class_dir {
2387         struct kobject kobj;
2388         struct class *class;
2389 };
2390
2391 #define to_class_dir(obj) container_of(obj, struct class_dir, kobj)
2392
2393 static void class_dir_release(struct kobject *kobj)
2394 {
2395         struct class_dir *dir = to_class_dir(kobj);
2396         kfree(dir);
2397 }
2398
2399 static const
2400 struct kobj_ns_type_operations *class_dir_child_ns_type(struct kobject *kobj)
2401 {
2402         struct class_dir *dir = to_class_dir(kobj);
2403         return dir->class->ns_type;
2404 }
2405
2406 static struct kobj_type class_dir_ktype = {
2407         .release        = class_dir_release,
2408         .sysfs_ops      = &kobj_sysfs_ops,
2409         .child_ns_type  = class_dir_child_ns_type
2410 };
2411
2412 static struct kobject *
2413 class_dir_create_and_add(struct class *class, struct kobject *parent_kobj)
2414 {
2415         struct class_dir *dir;
2416         int retval;
2417
2418         dir = kzalloc(sizeof(*dir), GFP_KERNEL);
2419         if (!dir)
2420                 return ERR_PTR(-ENOMEM);
2421
2422         dir->class = class;
2423         kobject_init(&dir->kobj, &class_dir_ktype);
2424
2425         dir->kobj.kset = &class->p->glue_dirs;
2426
2427         retval = kobject_add(&dir->kobj, parent_kobj, "%s", class->name);
2428         if (retval < 0) {
2429                 kobject_put(&dir->kobj);
2430                 return ERR_PTR(retval);
2431         }
2432         return &dir->kobj;
2433 }
2434
2435 static DEFINE_MUTEX(gdp_mutex);
2436
2437 static struct kobject *get_device_parent(struct device *dev,
2438                                          struct device *parent)
2439 {
2440         if (dev->class) {
2441                 struct kobject *kobj = NULL;
2442                 struct kobject *parent_kobj;
2443                 struct kobject *k;
2444
2445 #ifdef CONFIG_BLOCK
2446                 /* block disks show up in /sys/block */
2447                 if (sysfs_deprecated && dev->class == &block_class) {
2448                         if (parent && parent->class == &block_class)
2449                                 return &parent->kobj;
2450                         return &block_class.p->subsys.kobj;
2451                 }
2452 #endif
2453
2454                 /*
2455                  * If we have no parent, we live in "virtual".
2456                  * Class-devices with a non class-device as parent, live
2457                  * in a "glue" directory to prevent namespace collisions.
2458                  */
2459                 if (parent == NULL)
2460                         parent_kobj = virtual_device_parent(dev);
2461                 else if (parent->class && !dev->class->ns_type)
2462                         return &parent->kobj;
2463                 else
2464                         parent_kobj = &parent->kobj;
2465
2466                 mutex_lock(&gdp_mutex);
2467
2468                 /* find our class-directory at the parent and reference it */
2469                 spin_lock(&dev->class->p->glue_dirs.list_lock);
2470                 list_for_each_entry(k, &dev->class->p->glue_dirs.list, entry)
2471                         if (k->parent == parent_kobj) {
2472                                 kobj = kobject_get(k);
2473                                 break;
2474                         }
2475                 spin_unlock(&dev->class->p->glue_dirs.list_lock);
2476                 if (kobj) {
2477                         mutex_unlock(&gdp_mutex);
2478                         return kobj;
2479                 }
2480
2481                 /* or create a new class-directory at the parent device */
2482                 k = class_dir_create_and_add(dev->class, parent_kobj);
2483                 /* do not emit an uevent for this simple "glue" directory */
2484                 mutex_unlock(&gdp_mutex);
2485                 return k;
2486         }
2487
2488         /* subsystems can specify a default root directory for their devices */
2489         if (!parent && dev->bus && dev->bus->dev_root)
2490                 return &dev->bus->dev_root->kobj;
2491
2492         if (parent)
2493                 return &parent->kobj;
2494         return NULL;
2495 }
2496
2497 static inline bool live_in_glue_dir(struct kobject *kobj,
2498                                     struct device *dev)
2499 {
2500         if (!kobj || !dev->class ||
2501             kobj->kset != &dev->class->p->glue_dirs)
2502                 return false;
2503         return true;
2504 }
2505
2506 static inline struct kobject *get_glue_dir(struct device *dev)
2507 {
2508         return dev->kobj.parent;
2509 }
2510
2511 /*
2512  * make sure cleaning up dir as the last step, we need to make
2513  * sure .release handler of kobject is run with holding the
2514  * global lock
2515  */
2516 static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir)
2517 {
2518         unsigned int ref;
2519
2520         /* see if we live in a "glue" directory */
2521         if (!live_in_glue_dir(glue_dir, dev))
2522                 return;
2523
2524         mutex_lock(&gdp_mutex);
2525         /**
2526          * There is a race condition between removing glue directory
2527          * and adding a new device under the glue directory.
2528          *
2529          * CPU1:                                         CPU2:
2530          *
2531          * device_add()
2532          *   get_device_parent()
2533          *     class_dir_create_and_add()
2534          *       kobject_add_internal()
2535          *         create_dir()    // create glue_dir
2536          *
2537          *                                               device_add()
2538          *                                                 get_device_parent()
2539          *                                                   kobject_get() // get glue_dir
2540          *
2541          * device_del()
2542          *   cleanup_glue_dir()
2543          *     kobject_del(glue_dir)
2544          *
2545          *                                               kobject_add()
2546          *                                                 kobject_add_internal()
2547          *                                                   create_dir() // in glue_dir
2548          *                                                     sysfs_create_dir_ns()
2549          *                                                       kernfs_create_dir_ns(sd)
2550          *
2551          *       sysfs_remove_dir() // glue_dir->sd=NULL
2552          *       sysfs_put()        // free glue_dir->sd
2553          *
2554          *                                                         // sd is freed
2555          *                                                         kernfs_new_node(sd)
2556          *                                                           kernfs_get(glue_dir)
2557          *                                                           kernfs_add_one()
2558          *                                                           kernfs_put()
2559          *
2560          * Before CPU1 remove last child device under glue dir, if CPU2 add
2561          * a new device under glue dir, the glue_dir kobject reference count
2562          * will be increase to 2 in kobject_get(k). And CPU2 has been called
2563          * kernfs_create_dir_ns(). Meanwhile, CPU1 call sysfs_remove_dir()
2564          * and sysfs_put(). This result in glue_dir->sd is freed.
2565          *
2566          * Then the CPU2 will see a stale "empty" but still potentially used
2567          * glue dir around in kernfs_new_node().
2568          *
2569          * In order to avoid this happening, we also should make sure that
2570          * kernfs_node for glue_dir is released in CPU1 only when refcount
2571          * for glue_dir kobj is 1.
2572          */
2573         ref = kref_read(&glue_dir->kref);
2574         if (!kobject_has_children(glue_dir) && !--ref)
2575                 kobject_del(glue_dir);
2576         kobject_put(glue_dir);
2577         mutex_unlock(&gdp_mutex);
2578 }
2579
2580 static int device_add_class_symlinks(struct device *dev)
2581 {
2582         struct device_node *of_node = dev_of_node(dev);
2583         int error;
2584
2585         if (of_node) {
2586                 error = sysfs_create_link(&dev->kobj, of_node_kobj(of_node), "of_node");
2587                 if (error)
2588                         dev_warn(dev, "Error %d creating of_node link\n",error);
2589                 /* An error here doesn't warrant bringing down the device */
2590         }
2591
2592         if (!dev->class)
2593                 return 0;
2594
2595         error = sysfs_create_link(&dev->kobj,
2596                                   &dev->class->p->subsys.kobj,
2597                                   "subsystem");
2598         if (error)
2599                 goto out_devnode;
2600
2601         if (dev->parent && device_is_not_partition(dev)) {
2602                 error = sysfs_create_link(&dev->kobj, &dev->parent->kobj,
2603                                           "device");
2604                 if (error)
2605                         goto out_subsys;
2606         }
2607
2608 #ifdef CONFIG_BLOCK
2609         /* /sys/block has directories and does not need symlinks */
2610         if (sysfs_deprecated && dev->class == &block_class)
2611                 return 0;
2612 #endif
2613
2614         /* link in the class directory pointing to the device */
2615         error = sysfs_create_link(&dev->class->p->subsys.kobj,
2616                                   &dev->kobj, dev_name(dev));
2617         if (error)
2618                 goto out_device;
2619
2620         return 0;
2621
2622 out_device:
2623         sysfs_remove_link(&dev->kobj, "device");
2624
2625 out_subsys:
2626         sysfs_remove_link(&dev->kobj, "subsystem");
2627 out_devnode:
2628         sysfs_remove_link(&dev->kobj, "of_node");
2629         return error;
2630 }
2631
2632 static void device_remove_class_symlinks(struct device *dev)
2633 {
2634         if (dev_of_node(dev))
2635                 sysfs_remove_link(&dev->kobj, "of_node");
2636
2637         if (!dev->class)
2638                 return;
2639
2640         if (dev->parent && device_is_not_partition(dev))
2641                 sysfs_remove_link(&dev->kobj, "device");
2642         sysfs_remove_link(&dev->kobj, "subsystem");
2643 #ifdef CONFIG_BLOCK
2644         if (sysfs_deprecated && dev->class == &block_class)
2645                 return;
2646 #endif
2647         sysfs_delete_link(&dev->class->p->subsys.kobj, &dev->kobj, dev_name(dev));
2648 }
2649
2650 /**
2651  * dev_set_name - set a device name
2652  * @dev: device
2653  * @fmt: format string for the device's name
2654  */
2655 int dev_set_name(struct device *dev, const char *fmt, ...)
2656 {
2657         va_list vargs;
2658         int err;
2659
2660         va_start(vargs, fmt);
2661         err = kobject_set_name_vargs(&dev->kobj, fmt, vargs);
2662         va_end(vargs);
2663         return err;
2664 }
2665 EXPORT_SYMBOL_GPL(dev_set_name);
2666
2667 /**
2668  * device_to_dev_kobj - select a /sys/dev/ directory for the device
2669  * @dev: device
2670  *
2671  * By default we select char/ for new entries.  Setting class->dev_obj
2672  * to NULL prevents an entry from being created.  class->dev_kobj must
2673  * be set (or cleared) before any devices are registered to the class
2674  * otherwise device_create_sys_dev_entry() and
2675  * device_remove_sys_dev_entry() will disagree about the presence of
2676  * the link.
2677  */
2678 static struct kobject *device_to_dev_kobj(struct device *dev)
2679 {
2680         struct kobject *kobj;
2681
2682         if (dev->class)
2683                 kobj = dev->class->dev_kobj;
2684         else
2685                 kobj = sysfs_dev_char_kobj;
2686
2687         return kobj;
2688 }
2689
2690 static int device_create_sys_dev_entry(struct device *dev)
2691 {
2692         struct kobject *kobj = device_to_dev_kobj(dev);
2693         int error = 0;
2694         char devt_str[15];
2695
2696         if (kobj) {
2697                 format_dev_t(devt_str, dev->devt);
2698                 error = sysfs_create_link(kobj, &dev->kobj, devt_str);
2699         }
2700
2701         return error;
2702 }
2703
2704 static void device_remove_sys_dev_entry(struct device *dev)
2705 {
2706         struct kobject *kobj = device_to_dev_kobj(dev);
2707         char devt_str[15];
2708
2709         if (kobj) {
2710                 format_dev_t(devt_str, dev->devt);
2711                 sysfs_remove_link(kobj, devt_str);
2712         }
2713 }
2714
2715 static int device_private_init(struct device *dev)
2716 {
2717         dev->p = kzalloc(sizeof(*dev->p), GFP_KERNEL);
2718         if (!dev->p)
2719                 return -ENOMEM;
2720         dev->p->device = dev;
2721         klist_init(&dev->p->klist_children, klist_children_get,
2722                    klist_children_put);
2723         INIT_LIST_HEAD(&dev->p->deferred_probe);
2724         return 0;
2725 }
2726
2727 /**
2728  * device_add - add device to device hierarchy.
2729  * @dev: device.
2730  *
2731  * This is part 2 of device_register(), though may be called
2732  * separately _iff_ device_initialize() has been called separately.
2733  *
2734  * This adds @dev to the kobject hierarchy via kobject_add(), adds it
2735  * to the global and sibling lists for the device, then
2736  * adds it to the other relevant subsystems of the driver model.
2737  *
2738  * Do not call this routine or device_register() more than once for
2739  * any device structure.  The driver model core is not designed to work
2740  * with devices that get unregistered and then spring back to life.
2741  * (Among other things, it's very hard to guarantee that all references
2742  * to the previous incarnation of @dev have been dropped.)  Allocate
2743  * and register a fresh new struct device instead.
2744  *
2745  * NOTE: _Never_ directly free @dev after calling this function, even
2746  * if it returned an error! Always use put_device() to give up your
2747  * reference instead.
2748  *
2749  * Rule of thumb is: if device_add() succeeds, you should call
2750  * device_del() when you want to get rid of it. If device_add() has
2751  * *not* succeeded, use *only* put_device() to drop the reference
2752  * count.
2753  */
2754 int device_add(struct device *dev)
2755 {
2756         struct device *parent;
2757         struct kobject *kobj;
2758         struct class_interface *class_intf;
2759         int error = -EINVAL;
2760         struct kobject *glue_dir = NULL;
2761
2762         dev = get_device(dev);
2763         if (!dev)
2764                 goto done;
2765
2766         if (!dev->p) {
2767                 error = device_private_init(dev);
2768                 if (error)
2769                         goto done;
2770         }
2771
2772         /*
2773          * for statically allocated devices, which should all be converted
2774          * some day, we need to initialize the name. We prevent reading back
2775          * the name, and force the use of dev_name()
2776          */
2777         if (dev->init_name) {
2778                 dev_set_name(dev, "%s", dev->init_name);
2779                 dev->init_name = NULL;
2780         }
2781
2782         /* subsystems can specify simple device enumeration */
2783         if (!dev_name(dev) && dev->bus && dev->bus->dev_name)
2784                 dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
2785
2786         if (!dev_name(dev)) {
2787                 error = -EINVAL;
2788                 goto name_error;
2789         }
2790
2791         pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
2792
2793         parent = get_device(dev->parent);
2794         kobj = get_device_parent(dev, parent);
2795         if (IS_ERR(kobj)) {
2796                 error = PTR_ERR(kobj);
2797                 goto parent_error;
2798         }
2799         if (kobj)
2800                 dev->kobj.parent = kobj;
2801
2802         /* use parent numa_node */
2803         if (parent && (dev_to_node(dev) == NUMA_NO_NODE))
2804                 set_dev_node(dev, dev_to_node(parent));
2805
2806         /* first, register with generic layer. */
2807         /* we require the name to be set before, and pass NULL */
2808         error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
2809         if (error) {
2810                 glue_dir = get_glue_dir(dev);
2811                 goto Error;
2812         }
2813
2814         /* notify platform of device entry */
2815         error = device_platform_notify(dev, KOBJ_ADD);
2816         if (error)
2817                 goto platform_error;
2818
2819         error = device_create_file(dev, &dev_attr_uevent);
2820         if (error)
2821                 goto attrError;
2822
2823         error = device_add_class_symlinks(dev);
2824         if (error)
2825                 goto SymlinkError;
2826         error = device_add_attrs(dev);
2827         if (error)
2828                 goto AttrsError;
2829         error = bus_add_device(dev);
2830         if (error)
2831                 goto BusError;
2832         error = dpm_sysfs_add(dev);
2833         if (error)
2834                 goto DPMError;
2835         device_pm_add(dev);
2836
2837         if (MAJOR(dev->devt)) {
2838                 error = device_create_file(dev, &dev_attr_dev);
2839                 if (error)
2840                         goto DevAttrError;
2841
2842                 error = device_create_sys_dev_entry(dev);
2843                 if (error)
2844                         goto SysEntryError;
2845
2846                 devtmpfs_create_node(dev);
2847         }
2848
2849         /* Notify clients of device addition.  This call must come
2850          * after dpm_sysfs_add() and before kobject_uevent().
2851          */
2852         if (dev->bus)
2853                 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
2854                                              BUS_NOTIFY_ADD_DEVICE, dev);
2855
2856         kobject_uevent(&dev->kobj, KOBJ_ADD);
2857
2858         /*
2859          * Check if any of the other devices (consumers) have been waiting for
2860          * this device (supplier) to be added so that they can create a device
2861          * link to it.
2862          *
2863          * This needs to happen after device_pm_add() because device_link_add()
2864          * requires the supplier be registered before it's called.
2865          *
2866          * But this also needs to happen before bus_probe_device() to make sure
2867          * waiting consumers can link to it before the driver is bound to the
2868          * device and the driver sync_state callback is called for this device.
2869          */
2870         if (dev->fwnode && !dev->fwnode->dev) {
2871                 dev->fwnode->dev = dev;
2872                 fw_devlink_link_device(dev);
2873         }
2874
2875         bus_probe_device(dev);
2876         if (parent)
2877                 klist_add_tail(&dev->p->knode_parent,
2878                                &parent->p->klist_children);
2879
2880         if (dev->class) {
2881                 mutex_lock(&dev->class->p->mutex);
2882                 /* tie the class to the device */
2883                 klist_add_tail(&dev->p->knode_class,
2884                                &dev->class->p->klist_devices);
2885
2886                 /* notify any interfaces that the device is here */
2887                 list_for_each_entry(class_intf,
2888                                     &dev->class->p->interfaces, node)
2889                         if (class_intf->add_dev)
2890                                 class_intf->add_dev(dev, class_intf);
2891                 mutex_unlock(&dev->class->p->mutex);
2892         }
2893 done:
2894         put_device(dev);
2895         return error;
2896  SysEntryError:
2897         if (MAJOR(dev->devt))
2898                 device_remove_file(dev, &dev_attr_dev);
2899  DevAttrError:
2900         device_pm_remove(dev);
2901         dpm_sysfs_remove(dev);
2902  DPMError:
2903         bus_remove_device(dev);
2904  BusError:
2905         device_remove_attrs(dev);
2906  AttrsError:
2907         device_remove_class_symlinks(dev);
2908  SymlinkError:
2909         device_remove_file(dev, &dev_attr_uevent);
2910  attrError:
2911         device_platform_notify(dev, KOBJ_REMOVE);
2912 platform_error:
2913         kobject_uevent(&dev->kobj, KOBJ_REMOVE);
2914         glue_dir = get_glue_dir(dev);
2915         kobject_del(&dev->kobj);
2916  Error:
2917         cleanup_glue_dir(dev, glue_dir);
2918 parent_error:
2919         put_device(parent);
2920 name_error:
2921         kfree(dev->p);
2922         dev->p = NULL;
2923         goto done;
2924 }
2925 EXPORT_SYMBOL_GPL(device_add);
2926
2927 /**
2928  * device_register - register a device with the system.
2929  * @dev: pointer to the device structure
2930  *
2931  * This happens in two clean steps - initialize the device
2932  * and add it to the system. The two steps can be called
2933  * separately, but this is the easiest and most common.
2934  * I.e. you should only call the two helpers separately if
2935  * have a clearly defined need to use and refcount the device
2936  * before it is added to the hierarchy.
2937  *
2938  * For more information, see the kerneldoc for device_initialize()
2939  * and device_add().
2940  *
2941  * NOTE: _Never_ directly free @dev after calling this function, even
2942  * if it returned an error! Always use put_device() to give up the
2943  * reference initialized in this function instead.
2944  */
2945 int device_register(struct device *dev)
2946 {
2947         device_initialize(dev);
2948         return device_add(dev);
2949 }
2950 EXPORT_SYMBOL_GPL(device_register);
2951
2952 /**
2953  * get_device - increment reference count for device.
2954  * @dev: device.
2955  *
2956  * This simply forwards the call to kobject_get(), though
2957  * we do take care to provide for the case that we get a NULL
2958  * pointer passed in.
2959  */
2960 struct device *get_device(struct device *dev)
2961 {
2962         return dev ? kobj_to_dev(kobject_get(&dev->kobj)) : NULL;
2963 }
2964 EXPORT_SYMBOL_GPL(get_device);
2965
2966 /**
2967  * put_device - decrement reference count.
2968  * @dev: device in question.
2969  */
2970 void put_device(struct device *dev)
2971 {
2972         /* might_sleep(); */
2973         if (dev)
2974                 kobject_put(&dev->kobj);
2975 }
2976 EXPORT_SYMBOL_GPL(put_device);
2977
2978 bool kill_device(struct device *dev)
2979 {
2980         /*
2981          * Require the device lock and set the "dead" flag to guarantee that
2982          * the update behavior is consistent with the other bitfields near
2983          * it and that we cannot have an asynchronous probe routine trying
2984          * to run while we are tearing out the bus/class/sysfs from
2985          * underneath the device.
2986          */
2987         lockdep_assert_held(&dev->mutex);
2988
2989         if (dev->p->dead)
2990                 return false;
2991         dev->p->dead = true;
2992         return true;
2993 }
2994 EXPORT_SYMBOL_GPL(kill_device);
2995
2996 /**
2997  * device_del - delete device from system.
2998  * @dev: device.
2999  *
3000  * This is the first part of the device unregistration
3001  * sequence. This removes the device from the lists we control
3002  * from here, has it removed from the other driver model
3003  * subsystems it was added to in device_add(), and removes it
3004  * from the kobject hierarchy.
3005  *
3006  * NOTE: this should be called manually _iff_ device_add() was
3007  * also called manually.
3008  */
3009 void device_del(struct device *dev)
3010 {
3011         struct device *parent = dev->parent;
3012         struct kobject *glue_dir = NULL;
3013         struct class_interface *class_intf;
3014
3015         device_lock(dev);
3016         kill_device(dev);
3017         device_unlock(dev);
3018
3019         if (dev->fwnode && dev->fwnode->dev == dev)
3020                 dev->fwnode->dev = NULL;
3021
3022         /* Notify clients of device removal.  This call must come
3023          * before dpm_sysfs_remove().
3024          */
3025         if (dev->bus)
3026                 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
3027                                              BUS_NOTIFY_DEL_DEVICE, dev);
3028
3029         dpm_sysfs_remove(dev);
3030         if (parent)
3031                 klist_del(&dev->p->knode_parent);
3032         if (MAJOR(dev->devt)) {
3033                 devtmpfs_delete_node(dev);
3034                 device_remove_sys_dev_entry(dev);
3035                 device_remove_file(dev, &dev_attr_dev);
3036         }
3037         if (dev->class) {
3038                 device_remove_class_symlinks(dev);
3039
3040                 mutex_lock(&dev->class->p->mutex);
3041                 /* notify any interfaces that the device is now gone */
3042                 list_for_each_entry(class_intf,
3043                                     &dev->class->p->interfaces, node)
3044                         if (class_intf->remove_dev)
3045                                 class_intf->remove_dev(dev, class_intf);
3046                 /* remove the device from the class list */
3047                 klist_del(&dev->p->knode_class);
3048                 mutex_unlock(&dev->class->p->mutex);
3049         }
3050         device_remove_file(dev, &dev_attr_uevent);
3051         device_remove_attrs(dev);
3052         bus_remove_device(dev);
3053         device_pm_remove(dev);
3054         driver_deferred_probe_del(dev);
3055         device_platform_notify(dev, KOBJ_REMOVE);
3056         device_remove_properties(dev);
3057         device_links_purge(dev);
3058
3059         if (dev->bus)
3060                 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
3061                                              BUS_NOTIFY_REMOVED_DEVICE, dev);
3062         kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3063         glue_dir = get_glue_dir(dev);
3064         kobject_del(&dev->kobj);
3065         cleanup_glue_dir(dev, glue_dir);
3066         put_device(parent);
3067 }
3068 EXPORT_SYMBOL_GPL(device_del);
3069
3070 /**
3071  * device_unregister - unregister device from system.
3072  * @dev: device going away.
3073  *
3074  * We do this in two parts, like we do device_register(). First,
3075  * we remove it from all the subsystems with device_del(), then
3076  * we decrement the reference count via put_device(). If that
3077  * is the final reference count, the device will be cleaned up
3078  * via device_release() above. Otherwise, the structure will
3079  * stick around until the final reference to the device is dropped.
3080  */
3081 void device_unregister(struct device *dev)
3082 {
3083         pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3084         device_del(dev);
3085         put_device(dev);
3086 }
3087 EXPORT_SYMBOL_GPL(device_unregister);
3088
3089 static struct device *prev_device(struct klist_iter *i)
3090 {
3091         struct klist_node *n = klist_prev(i);
3092         struct device *dev = NULL;
3093         struct device_private *p;
3094
3095         if (n) {
3096                 p = to_device_private_parent(n);
3097                 dev = p->device;
3098         }
3099         return dev;
3100 }
3101
3102 static struct device *next_device(struct klist_iter *i)
3103 {
3104         struct klist_node *n = klist_next(i);
3105         struct device *dev = NULL;
3106         struct device_private *p;
3107
3108         if (n) {
3109                 p = to_device_private_parent(n);
3110                 dev = p->device;
3111         }
3112         return dev;
3113 }
3114
3115 /**
3116  * device_get_devnode - path of device node file
3117  * @dev: device
3118  * @mode: returned file access mode
3119  * @uid: returned file owner
3120  * @gid: returned file group
3121  * @tmp: possibly allocated string
3122  *
3123  * Return the relative path of a possible device node.
3124  * Non-default names may need to allocate a memory to compose
3125  * a name. This memory is returned in tmp and needs to be
3126  * freed by the caller.
3127  */
3128 const char *device_get_devnode(struct device *dev,
3129                                umode_t *mode, kuid_t *uid, kgid_t *gid,
3130                                const char **tmp)
3131 {
3132         char *s;
3133
3134         *tmp = NULL;
3135
3136         /* the device type may provide a specific name */
3137         if (dev->type && dev->type->devnode)
3138                 *tmp = dev->type->devnode(dev, mode, uid, gid);
3139         if (*tmp)
3140                 return *tmp;
3141
3142         /* the class may provide a specific name */
3143         if (dev->class && dev->class->devnode)
3144                 *tmp = dev->class->devnode(dev, mode);
3145         if (*tmp)
3146                 return *tmp;
3147
3148         /* return name without allocation, tmp == NULL */
3149         if (strchr(dev_name(dev), '!') == NULL)
3150                 return dev_name(dev);
3151
3152         /* replace '!' in the name with '/' */
3153         s = kstrdup(dev_name(dev), GFP_KERNEL);
3154         if (!s)
3155                 return NULL;
3156         strreplace(s, '!', '/');
3157         return *tmp = s;
3158 }
3159
3160 /**
3161  * device_for_each_child - device child iterator.
3162  * @parent: parent struct device.
3163  * @fn: function to be called for each device.
3164  * @data: data for the callback.
3165  *
3166  * Iterate over @parent's child devices, and call @fn for each,
3167  * passing it @data.
3168  *
3169  * We check the return of @fn each time. If it returns anything
3170  * other than 0, we break out and return that value.
3171  */
3172 int device_for_each_child(struct device *parent, void *data,
3173                           int (*fn)(struct device *dev, void *data))
3174 {
3175         struct klist_iter i;
3176         struct device *child;
3177         int error = 0;
3178
3179         if (!parent->p)
3180                 return 0;
3181
3182         klist_iter_init(&parent->p->klist_children, &i);
3183         while (!error && (child = next_device(&i)))
3184                 error = fn(child, data);
3185         klist_iter_exit(&i);
3186         return error;
3187 }
3188 EXPORT_SYMBOL_GPL(device_for_each_child);
3189
3190 /**
3191  * device_for_each_child_reverse - device child iterator in reversed order.
3192  * @parent: parent struct device.
3193  * @fn: function to be called for each device.
3194  * @data: data for the callback.
3195  *
3196  * Iterate over @parent's child devices, and call @fn for each,
3197  * passing it @data.
3198  *
3199  * We check the return of @fn each time. If it returns anything
3200  * other than 0, we break out and return that value.
3201  */
3202 int device_for_each_child_reverse(struct device *parent, void *data,
3203                                   int (*fn)(struct device *dev, void *data))
3204 {
3205         struct klist_iter i;
3206         struct device *child;
3207         int error = 0;
3208
3209         if (!parent->p)
3210                 return 0;
3211
3212         klist_iter_init(&parent->p->klist_children, &i);
3213         while ((child = prev_device(&i)) && !error)
3214                 error = fn(child, data);
3215         klist_iter_exit(&i);
3216         return error;
3217 }
3218 EXPORT_SYMBOL_GPL(device_for_each_child_reverse);
3219
3220 /**
3221  * device_find_child - device iterator for locating a particular device.
3222  * @parent: parent struct device
3223  * @match: Callback function to check device
3224  * @data: Data to pass to match function
3225  *
3226  * This is similar to the device_for_each_child() function above, but it
3227  * returns a reference to a device that is 'found' for later use, as
3228  * determined by the @match callback.
3229  *
3230  * The callback should return 0 if the device doesn't match and non-zero
3231  * if it does.  If the callback returns non-zero and a reference to the
3232  * current device can be obtained, this function will return to the caller
3233  * and not iterate over any more devices.
3234  *
3235  * NOTE: you will need to drop the reference with put_device() after use.
3236  */
3237 struct device *device_find_child(struct device *parent, void *data,
3238                                  int (*match)(struct device *dev, void *data))
3239 {
3240         struct klist_iter i;
3241         struct device *child;
3242
3243         if (!parent)
3244                 return NULL;
3245
3246         klist_iter_init(&parent->p->klist_children, &i);
3247         while ((child = next_device(&i)))
3248                 if (match(child, data) && get_device(child))
3249                         break;
3250         klist_iter_exit(&i);
3251         return child;
3252 }
3253 EXPORT_SYMBOL_GPL(device_find_child);
3254
3255 /**
3256  * device_find_child_by_name - device iterator for locating a child device.
3257  * @parent: parent struct device
3258  * @name: name of the child device
3259  *
3260  * This is similar to the device_find_child() function above, but it
3261  * returns a reference to a device that has the name @name.
3262  *
3263  * NOTE: you will need to drop the reference with put_device() after use.
3264  */
3265 struct device *device_find_child_by_name(struct device *parent,
3266                                          const char *name)
3267 {
3268         struct klist_iter i;
3269         struct device *child;
3270
3271         if (!parent)
3272                 return NULL;
3273
3274         klist_iter_init(&parent->p->klist_children, &i);
3275         while ((child = next_device(&i)))
3276                 if (!strcmp(dev_name(child), name) && get_device(child))
3277                         break;
3278         klist_iter_exit(&i);
3279         return child;
3280 }
3281 EXPORT_SYMBOL_GPL(device_find_child_by_name);
3282
3283 int __init devices_init(void)
3284 {
3285         devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
3286         if (!devices_kset)
3287                 return -ENOMEM;
3288         dev_kobj = kobject_create_and_add("dev", NULL);
3289         if (!dev_kobj)
3290                 goto dev_kobj_err;
3291         sysfs_dev_block_kobj = kobject_create_and_add("block", dev_kobj);
3292         if (!sysfs_dev_block_kobj)
3293                 goto block_kobj_err;
3294         sysfs_dev_char_kobj = kobject_create_and_add("char", dev_kobj);
3295         if (!sysfs_dev_char_kobj)
3296                 goto char_kobj_err;
3297
3298         return 0;
3299
3300  char_kobj_err:
3301         kobject_put(sysfs_dev_block_kobj);
3302  block_kobj_err:
3303         kobject_put(dev_kobj);
3304  dev_kobj_err:
3305         kset_unregister(devices_kset);
3306         return -ENOMEM;
3307 }
3308
3309 static int device_check_offline(struct device *dev, void *not_used)
3310 {
3311         int ret;
3312
3313         ret = device_for_each_child(dev, NULL, device_check_offline);
3314         if (ret)
3315                 return ret;
3316
3317         return device_supports_offline(dev) && !dev->offline ? -EBUSY : 0;
3318 }
3319
3320 /**
3321  * device_offline - Prepare the device for hot-removal.
3322  * @dev: Device to be put offline.
3323  *
3324  * Execute the device bus type's .offline() callback, if present, to prepare
3325  * the device for a subsequent hot-removal.  If that succeeds, the device must
3326  * not be used until either it is removed or its bus type's .online() callback
3327  * is executed.
3328  *
3329  * Call under device_hotplug_lock.
3330  */
3331 int device_offline(struct device *dev)
3332 {
3333         int ret;
3334
3335         if (dev->offline_disabled)
3336                 return -EPERM;
3337
3338         ret = device_for_each_child(dev, NULL, device_check_offline);
3339         if (ret)
3340                 return ret;
3341
3342         device_lock(dev);
3343         if (device_supports_offline(dev)) {
3344                 if (dev->offline) {
3345                         ret = 1;
3346                 } else {
3347                         ret = dev->bus->offline(dev);
3348                         if (!ret) {
3349                                 kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
3350                                 dev->offline = true;
3351                         }
3352                 }
3353         }
3354         device_unlock(dev);
3355
3356         return ret;
3357 }
3358
3359 /**
3360  * device_online - Put the device back online after successful device_offline().
3361  * @dev: Device to be put back online.
3362  *
3363  * If device_offline() has been successfully executed for @dev, but the device
3364  * has not been removed subsequently, execute its bus type's .online() callback
3365  * to indicate that the device can be used again.
3366  *
3367  * Call under device_hotplug_lock.
3368  */
3369 int device_online(struct device *dev)
3370 {
3371         int ret = 0;
3372
3373         device_lock(dev);
3374         if (device_supports_offline(dev)) {
3375                 if (dev->offline) {
3376                         ret = dev->bus->online(dev);
3377                         if (!ret) {
3378                                 kobject_uevent(&dev->kobj, KOBJ_ONLINE);
3379                                 dev->offline = false;
3380                         }
3381                 } else {
3382                         ret = 1;
3383                 }
3384         }
3385         device_unlock(dev);
3386
3387         return ret;
3388 }
3389
3390 struct root_device {
3391         struct device dev;
3392         struct module *owner;
3393 };
3394
3395 static inline struct root_device *to_root_device(struct device *d)
3396 {
3397         return container_of(d, struct root_device, dev);
3398 }
3399
3400 static void root_device_release(struct device *dev)
3401 {
3402         kfree(to_root_device(dev));
3403 }
3404
3405 /**
3406  * __root_device_register - allocate and register a root device
3407  * @name: root device name
3408  * @owner: owner module of the root device, usually THIS_MODULE
3409  *
3410  * This function allocates a root device and registers it
3411  * using device_register(). In order to free the returned
3412  * device, use root_device_unregister().
3413  *
3414  * Root devices are dummy devices which allow other devices
3415  * to be grouped under /sys/devices. Use this function to
3416  * allocate a root device and then use it as the parent of
3417  * any device which should appear under /sys/devices/{name}
3418  *
3419  * The /sys/devices/{name} directory will also contain a
3420  * 'module' symlink which points to the @owner directory
3421  * in sysfs.
3422  *
3423  * Returns &struct device pointer on success, or ERR_PTR() on error.
3424  *
3425  * Note: You probably want to use root_device_register().
3426  */
3427 struct device *__root_device_register(const char *name, struct module *owner)
3428 {
3429         struct root_device *root;
3430         int err = -ENOMEM;
3431
3432         root = kzalloc(sizeof(struct root_device), GFP_KERNEL);
3433         if (!root)
3434                 return ERR_PTR(err);
3435
3436         err = dev_set_name(&root->dev, "%s", name);
3437         if (err) {
3438                 kfree(root);
3439                 return ERR_PTR(err);
3440         }
3441
3442         root->dev.release = root_device_release;
3443
3444         err = device_register(&root->dev);
3445         if (err) {
3446                 put_device(&root->dev);
3447                 return ERR_PTR(err);
3448         }
3449
3450 #ifdef CONFIG_MODULES   /* gotta find a "cleaner" way to do this */
3451         if (owner) {
3452                 struct module_kobject *mk = &owner->mkobj;
3453
3454                 err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module");
3455                 if (err) {
3456                         device_unregister(&root->dev);
3457                         return ERR_PTR(err);
3458                 }
3459                 root->owner = owner;
3460         }
3461 #endif
3462
3463         return &root->dev;
3464 }
3465 EXPORT_SYMBOL_GPL(__root_device_register);
3466
3467 /**
3468  * root_device_unregister - unregister and free a root device
3469  * @dev: device going away
3470  *
3471  * This function unregisters and cleans up a device that was created by
3472  * root_device_register().
3473  */
3474 void root_device_unregister(struct device *dev)
3475 {
3476         struct root_device *root = to_root_device(dev);
3477
3478         if (root->owner)
3479                 sysfs_remove_link(&root->dev.kobj, "module");
3480
3481         device_unregister(dev);
3482 }
3483 EXPORT_SYMBOL_GPL(root_device_unregister);
3484
3485
3486 static void device_create_release(struct device *dev)
3487 {
3488         pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3489         kfree(dev);
3490 }
3491
3492 static __printf(6, 0) struct device *
3493 device_create_groups_vargs(struct class *class, struct device *parent,
3494                            dev_t devt, void *drvdata,
3495                            const struct attribute_group **groups,
3496                            const char *fmt, va_list args)
3497 {
3498         struct device *dev = NULL;
3499         int retval = -ENODEV;
3500
3501         if (class == NULL || IS_ERR(class))
3502                 goto error;
3503
3504         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3505         if (!dev) {
3506                 retval = -ENOMEM;
3507                 goto error;
3508         }
3509
3510         device_initialize(dev);
3511         dev->devt = devt;
3512         dev->class = class;
3513         dev->parent = parent;
3514         dev->groups = groups;
3515         dev->release = device_create_release;
3516         dev_set_drvdata(dev, drvdata);
3517
3518         retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
3519         if (retval)
3520                 goto error;
3521
3522         retval = device_add(dev);
3523         if (retval)
3524                 goto error;
3525
3526         return dev;
3527
3528 error:
3529         put_device(dev);
3530         return ERR_PTR(retval);
3531 }
3532
3533 /**
3534  * device_create - creates a device and registers it with sysfs
3535  * @class: pointer to the struct class that this device should be registered to
3536  * @parent: pointer to the parent struct device of this new device, if any
3537  * @devt: the dev_t for the char device to be added
3538  * @drvdata: the data to be added to the device for callbacks
3539  * @fmt: string for the device's name
3540  *
3541  * This function can be used by char device classes.  A struct device
3542  * will be created in sysfs, registered to the specified class.
3543  *
3544  * A "dev" file will be created, showing the dev_t for the device, if
3545  * the dev_t is not 0,0.
3546  * If a pointer to a parent struct device is passed in, the newly created
3547  * struct device will be a child of that device in sysfs.
3548  * The pointer to the struct device will be returned from the call.
3549  * Any further sysfs files that might be required can be created using this
3550  * pointer.
3551  *
3552  * Returns &struct device pointer on success, or ERR_PTR() on error.
3553  *
3554  * Note: the struct class passed to this function must have previously
3555  * been created with a call to class_create().
3556  */
3557 struct device *device_create(struct class *class, struct device *parent,
3558                              dev_t devt, void *drvdata, const char *fmt, ...)
3559 {
3560         va_list vargs;
3561         struct device *dev;
3562
3563         va_start(vargs, fmt);
3564         dev = device_create_groups_vargs(class, parent, devt, drvdata, NULL,
3565                                           fmt, vargs);
3566         va_end(vargs);
3567         return dev;
3568 }
3569 EXPORT_SYMBOL_GPL(device_create);
3570
3571 /**
3572  * device_create_with_groups - creates a device and registers it with sysfs
3573  * @class: pointer to the struct class that this device should be registered to
3574  * @parent: pointer to the parent struct device of this new device, if any
3575  * @devt: the dev_t for the char device to be added
3576  * @drvdata: the data to be added to the device for callbacks
3577  * @groups: NULL-terminated list of attribute groups to be created
3578  * @fmt: string for the device's name
3579  *
3580  * This function can be used by char device classes.  A struct device
3581  * will be created in sysfs, registered to the specified class.
3582  * Additional attributes specified in the groups parameter will also
3583  * be created automatically.
3584  *
3585  * A "dev" file will be created, showing the dev_t for the device, if
3586  * the dev_t is not 0,0.
3587  * If a pointer to a parent struct device is passed in, the newly created
3588  * struct device will be a child of that device in sysfs.
3589  * The pointer to the struct device will be returned from the call.
3590  * Any further sysfs files that might be required can be created using this
3591  * pointer.
3592  *
3593  * Returns &struct device pointer on success, or ERR_PTR() on error.
3594  *
3595  * Note: the struct class passed to this function must have previously
3596  * been created with a call to class_create().
3597  */
3598 struct device *device_create_with_groups(struct class *class,
3599                                          struct device *parent, dev_t devt,
3600                                          void *drvdata,
3601                                          const struct attribute_group **groups,
3602                                          const char *fmt, ...)
3603 {
3604         va_list vargs;
3605         struct device *dev;
3606
3607         va_start(vargs, fmt);
3608         dev = device_create_groups_vargs(class, parent, devt, drvdata, groups,
3609                                          fmt, vargs);
3610         va_end(vargs);
3611         return dev;
3612 }
3613 EXPORT_SYMBOL_GPL(device_create_with_groups);
3614
3615 /**
3616  * device_destroy - removes a device that was created with device_create()
3617  * @class: pointer to the struct class that this device was registered with
3618  * @devt: the dev_t of the device that was previously registered
3619  *
3620  * This call unregisters and cleans up a device that was created with a
3621  * call to device_create().
3622  */
3623 void device_destroy(struct class *class, dev_t devt)
3624 {
3625         struct device *dev;
3626
3627         dev = class_find_device_by_devt(class, devt);
3628         if (dev) {
3629                 put_device(dev);
3630                 device_unregister(dev);
3631         }
3632 }
3633 EXPORT_SYMBOL_GPL(device_destroy);
3634
3635 /**
3636  * device_rename - renames a device
3637  * @dev: the pointer to the struct device to be renamed
3638  * @new_name: the new name of the device
3639  *
3640  * It is the responsibility of the caller to provide mutual
3641  * exclusion between two different calls of device_rename
3642  * on the same device to ensure that new_name is valid and
3643  * won't conflict with other devices.
3644  *
3645  * Note: Don't call this function.  Currently, the networking layer calls this
3646  * function, but that will change.  The following text from Kay Sievers offers
3647  * some insight:
3648  *
3649  * Renaming devices is racy at many levels, symlinks and other stuff are not
3650  * replaced atomically, and you get a "move" uevent, but it's not easy to
3651  * connect the event to the old and new device. Device nodes are not renamed at
3652  * all, there isn't even support for that in the kernel now.
3653  *
3654  * In the meantime, during renaming, your target name might be taken by another
3655  * driver, creating conflicts. Or the old name is taken directly after you
3656  * renamed it -- then you get events for the same DEVPATH, before you even see
3657  * the "move" event. It's just a mess, and nothing new should ever rely on
3658  * kernel device renaming. Besides that, it's not even implemented now for
3659  * other things than (driver-core wise very simple) network devices.
3660  *
3661  * We are currently about to change network renaming in udev to completely
3662  * disallow renaming of devices in the same namespace as the kernel uses,
3663  * because we can't solve the problems properly, that arise with swapping names
3664  * of multiple interfaces without races. Means, renaming of eth[0-9]* will only
3665  * be allowed to some other name than eth[0-9]*, for the aforementioned
3666  * reasons.
3667  *
3668  * Make up a "real" name in the driver before you register anything, or add
3669  * some other attributes for userspace to find the device, or use udev to add
3670  * symlinks -- but never rename kernel devices later, it's a complete mess. We
3671  * don't even want to get into that and try to implement the missing pieces in
3672  * the core. We really have other pieces to fix in the driver core mess. :)
3673  */
3674 int device_rename(struct device *dev, const char *new_name)
3675 {
3676         struct kobject *kobj = &dev->kobj;
3677         char *old_device_name = NULL;
3678         int error;
3679
3680         dev = get_device(dev);
3681         if (!dev)
3682                 return -EINVAL;
3683
3684         dev_dbg(dev, "renaming to %s\n", new_name);
3685
3686         old_device_name = kstrdup(dev_name(dev), GFP_KERNEL);
3687         if (!old_device_name) {
3688                 error = -ENOMEM;
3689                 goto out;
3690         }
3691
3692         if (dev->class) {
3693                 error = sysfs_rename_link_ns(&dev->class->p->subsys.kobj,
3694                                              kobj, old_device_name,
3695                                              new_name, kobject_namespace(kobj));
3696                 if (error)
3697                         goto out;
3698         }
3699
3700         error = kobject_rename(kobj, new_name);
3701         if (error)
3702                 goto out;
3703
3704 out:
3705         put_device(dev);
3706
3707         kfree(old_device_name);
3708
3709         return error;
3710 }
3711 EXPORT_SYMBOL_GPL(device_rename);
3712
3713 static int device_move_class_links(struct device *dev,
3714                                    struct device *old_parent,
3715                                    struct device *new_parent)
3716 {
3717         int error = 0;
3718
3719         if (old_parent)
3720                 sysfs_remove_link(&dev->kobj, "device");
3721         if (new_parent)
3722                 error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
3723                                           "device");
3724         return error;
3725 }
3726
3727 /**
3728  * device_move - moves a device to a new parent
3729  * @dev: the pointer to the struct device to be moved
3730  * @new_parent: the new parent of the device (can be NULL)
3731  * @dpm_order: how to reorder the dpm_list
3732  */
3733 int device_move(struct device *dev, struct device *new_parent,
3734                 enum dpm_order dpm_order)
3735 {
3736         int error;
3737         struct device *old_parent;
3738         struct kobject *new_parent_kobj;
3739
3740         dev = get_device(dev);
3741         if (!dev)
3742                 return -EINVAL;
3743
3744         device_pm_lock();
3745         new_parent = get_device(new_parent);
3746         new_parent_kobj = get_device_parent(dev, new_parent);
3747         if (IS_ERR(new_parent_kobj)) {
3748                 error = PTR_ERR(new_parent_kobj);
3749                 put_device(new_parent);
3750                 goto out;
3751         }
3752
3753         pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev),
3754                  __func__, new_parent ? dev_name(new_parent) : "<NULL>");
3755         error = kobject_move(&dev->kobj, new_parent_kobj);
3756         if (error) {
3757                 cleanup_glue_dir(dev, new_parent_kobj);
3758                 put_device(new_parent);
3759                 goto out;
3760         }
3761         old_parent = dev->parent;
3762         dev->parent = new_parent;
3763         if (old_parent)
3764                 klist_remove(&dev->p->knode_parent);
3765         if (new_parent) {
3766                 klist_add_tail(&dev->p->knode_parent,
3767                                &new_parent->p->klist_children);
3768                 set_dev_node(dev, dev_to_node(new_parent));
3769         }
3770
3771         if (dev->class) {
3772                 error = device_move_class_links(dev, old_parent, new_parent);
3773                 if (error) {
3774                         /* We ignore errors on cleanup since we're hosed anyway... */
3775                         device_move_class_links(dev, new_parent, old_parent);
3776                         if (!kobject_move(&dev->kobj, &old_parent->kobj)) {
3777                                 if (new_parent)
3778                                         klist_remove(&dev->p->knode_parent);
3779                                 dev->parent = old_parent;
3780                                 if (old_parent) {
3781                                         klist_add_tail(&dev->p->knode_parent,
3782                                                        &old_parent->p->klist_children);
3783                                         set_dev_node(dev, dev_to_node(old_parent));
3784                                 }
3785                         }
3786                         cleanup_glue_dir(dev, new_parent_kobj);
3787                         put_device(new_parent);
3788                         goto out;
3789                 }
3790         }
3791         switch (dpm_order) {
3792         case DPM_ORDER_NONE:
3793                 break;
3794         case DPM_ORDER_DEV_AFTER_PARENT:
3795                 device_pm_move_after(dev, new_parent);
3796                 devices_kset_move_after(dev, new_parent);
3797                 break;
3798         case DPM_ORDER_PARENT_BEFORE_DEV:
3799                 device_pm_move_before(new_parent, dev);
3800                 devices_kset_move_before(new_parent, dev);
3801                 break;
3802         case DPM_ORDER_DEV_LAST:
3803                 device_pm_move_last(dev);
3804                 devices_kset_move_last(dev);
3805                 break;
3806         }
3807
3808         put_device(old_parent);
3809 out:
3810         device_pm_unlock();
3811         put_device(dev);
3812         return error;
3813 }
3814 EXPORT_SYMBOL_GPL(device_move);
3815
3816 static int device_attrs_change_owner(struct device *dev, kuid_t kuid,
3817                                      kgid_t kgid)
3818 {
3819         struct kobject *kobj = &dev->kobj;
3820         struct class *class = dev->class;
3821         const struct device_type *type = dev->type;
3822         int error;
3823
3824         if (class) {
3825                 /*
3826                  * Change the device groups of the device class for @dev to
3827                  * @kuid/@kgid.
3828                  */
3829                 error = sysfs_groups_change_owner(kobj, class->dev_groups, kuid,
3830                                                   kgid);
3831                 if (error)
3832                         return error;
3833         }
3834
3835         if (type) {
3836                 /*
3837                  * Change the device groups of the device type for @dev to
3838                  * @kuid/@kgid.
3839                  */
3840                 error = sysfs_groups_change_owner(kobj, type->groups, kuid,
3841                                                   kgid);
3842                 if (error)
3843                         return error;
3844         }
3845
3846         /* Change the device groups of @dev to @kuid/@kgid. */
3847         error = sysfs_groups_change_owner(kobj, dev->groups, kuid, kgid);
3848         if (error)
3849                 return error;
3850
3851         if (device_supports_offline(dev) && !dev->offline_disabled) {
3852                 /* Change online device attributes of @dev to @kuid/@kgid. */
3853                 error = sysfs_file_change_owner(kobj, dev_attr_online.attr.name,
3854                                                 kuid, kgid);
3855                 if (error)
3856                         return error;
3857         }
3858
3859         return 0;
3860 }
3861
3862 /**
3863  * device_change_owner - change the owner of an existing device.
3864  * @dev: device.
3865  * @kuid: new owner's kuid
3866  * @kgid: new owner's kgid
3867  *
3868  * This changes the owner of @dev and its corresponding sysfs entries to
3869  * @kuid/@kgid. This function closely mirrors how @dev was added via driver
3870  * core.
3871  *
3872  * Returns 0 on success or error code on failure.
3873  */
3874 int device_change_owner(struct device *dev, kuid_t kuid, kgid_t kgid)
3875 {
3876         int error;
3877         struct kobject *kobj = &dev->kobj;
3878
3879         dev = get_device(dev);
3880         if (!dev)
3881                 return -EINVAL;
3882
3883         /*
3884          * Change the kobject and the default attributes and groups of the
3885          * ktype associated with it to @kuid/@kgid.
3886          */
3887         error = sysfs_change_owner(kobj, kuid, kgid);
3888         if (error)
3889                 goto out;
3890
3891         /*
3892          * Change the uevent file for @dev to the new owner. The uevent file
3893          * was created in a separate step when @dev got added and we mirror
3894          * that step here.
3895          */
3896         error = sysfs_file_change_owner(kobj, dev_attr_uevent.attr.name, kuid,
3897                                         kgid);
3898         if (error)
3899                 goto out;
3900
3901         /*
3902          * Change the device groups, the device groups associated with the
3903          * device class, and the groups associated with the device type of @dev
3904          * to @kuid/@kgid.
3905          */
3906         error = device_attrs_change_owner(dev, kuid, kgid);
3907         if (error)
3908                 goto out;
3909
3910         error = dpm_sysfs_change_owner(dev, kuid, kgid);
3911         if (error)
3912                 goto out;
3913
3914 #ifdef CONFIG_BLOCK
3915         if (sysfs_deprecated && dev->class == &block_class)
3916                 goto out;
3917 #endif
3918
3919         /*
3920          * Change the owner of the symlink located in the class directory of
3921          * the device class associated with @dev which points to the actual
3922          * directory entry for @dev to @kuid/@kgid. This ensures that the
3923          * symlink shows the same permissions as its target.
3924          */
3925         error = sysfs_link_change_owner(&dev->class->p->subsys.kobj, &dev->kobj,
3926                                         dev_name(dev), kuid, kgid);
3927         if (error)
3928                 goto out;
3929
3930 out:
3931         put_device(dev);
3932         return error;
3933 }
3934 EXPORT_SYMBOL_GPL(device_change_owner);
3935
3936 /**
3937  * device_shutdown - call ->shutdown() on each device to shutdown.
3938  */
3939 void device_shutdown(void)
3940 {
3941         struct device *dev, *parent;
3942
3943         wait_for_device_probe();
3944         device_block_probing();
3945
3946         cpufreq_suspend();
3947
3948         spin_lock(&devices_kset->list_lock);
3949         /*
3950          * Walk the devices list backward, shutting down each in turn.
3951          * Beware that device unplug events may also start pulling
3952          * devices offline, even as the system is shutting down.
3953          */
3954         while (!list_empty(&devices_kset->list)) {
3955                 dev = list_entry(devices_kset->list.prev, struct device,
3956                                 kobj.entry);
3957
3958                 /*
3959                  * hold reference count of device's parent to
3960                  * prevent it from being freed because parent's
3961                  * lock is to be held
3962                  */
3963                 parent = get_device(dev->parent);
3964                 get_device(dev);
3965                 /*
3966                  * Make sure the device is off the kset list, in the
3967                  * event that dev->*->shutdown() doesn't remove it.
3968                  */
3969                 list_del_init(&dev->kobj.entry);
3970                 spin_unlock(&devices_kset->list_lock);
3971
3972                 /* hold lock to avoid race with probe/release */
3973                 if (parent)
3974                         device_lock(parent);
3975                 device_lock(dev);
3976
3977                 /* Don't allow any more runtime suspends */
3978                 pm_runtime_get_noresume(dev);
3979                 pm_runtime_barrier(dev);
3980
3981                 if (dev->class && dev->class->shutdown_pre) {
3982                         if (initcall_debug)
3983                                 dev_info(dev, "shutdown_pre\n");
3984                         dev->class->shutdown_pre(dev);
3985                 }
3986                 if (dev->bus && dev->bus->shutdown) {
3987                         if (initcall_debug)
3988                                 dev_info(dev, "shutdown\n");
3989                         dev->bus->shutdown(dev);
3990                 } else if (dev->driver && dev->driver->shutdown) {
3991                         if (initcall_debug)
3992                                 dev_info(dev, "shutdown\n");
3993                         dev->driver->shutdown(dev);
3994                 }
3995
3996                 device_unlock(dev);
3997                 if (parent)
3998                         device_unlock(parent);
3999
4000                 put_device(dev);
4001                 put_device(parent);
4002
4003                 spin_lock(&devices_kset->list_lock);
4004         }
4005         spin_unlock(&devices_kset->list_lock);
4006 }
4007
4008 /*
4009  * Device logging functions
4010  */
4011
4012 #ifdef CONFIG_PRINTK
4013 static int
4014 create_syslog_header(const struct device *dev, char *hdr, size_t hdrlen)
4015 {
4016         const char *subsys;
4017         size_t pos = 0;
4018
4019         if (dev->class)
4020                 subsys = dev->class->name;
4021         else if (dev->bus)
4022                 subsys = dev->bus->name;
4023         else
4024                 return 0;
4025
4026         pos += snprintf(hdr + pos, hdrlen - pos, "SUBSYSTEM=%s", subsys);
4027         if (pos >= hdrlen)
4028                 goto overflow;
4029
4030         /*
4031          * Add device identifier DEVICE=:
4032          *   b12:8         block dev_t
4033          *   c127:3        char dev_t
4034          *   n8            netdev ifindex
4035          *   +sound:card0  subsystem:devname
4036          */
4037         if (MAJOR(dev->devt)) {
4038                 char c;
4039
4040                 if (strcmp(subsys, "block") == 0)
4041                         c = 'b';
4042                 else
4043                         c = 'c';
4044                 pos++;
4045                 pos += snprintf(hdr + pos, hdrlen - pos,
4046                                 "DEVICE=%c%u:%u",
4047                                 c, MAJOR(dev->devt), MINOR(dev->devt));
4048         } else if (strcmp(subsys, "net") == 0) {
4049                 struct net_device *net = to_net_dev(dev);
4050
4051                 pos++;
4052                 pos += snprintf(hdr + pos, hdrlen - pos,
4053                                 "DEVICE=n%u", net->ifindex);
4054         } else {
4055                 pos++;
4056                 pos += snprintf(hdr + pos, hdrlen - pos,
4057                                 "DEVICE=+%s:%s", subsys, dev_name(dev));
4058         }
4059
4060         if (pos >= hdrlen)
4061                 goto overflow;
4062
4063         return pos;
4064
4065 overflow:
4066         dev_WARN(dev, "device/subsystem name too long");
4067         return 0;
4068 }
4069
4070 int dev_vprintk_emit(int level, const struct device *dev,
4071                      const char *fmt, va_list args)
4072 {
4073         char hdr[128];
4074         size_t hdrlen;
4075
4076         hdrlen = create_syslog_header(dev, hdr, sizeof(hdr));
4077
4078         return vprintk_emit(0, level, hdrlen ? hdr : NULL, hdrlen, fmt, args);
4079 }
4080 EXPORT_SYMBOL(dev_vprintk_emit);
4081
4082 int dev_printk_emit(int level, const struct device *dev, const char *fmt, ...)
4083 {
4084         va_list args;
4085         int r;
4086
4087         va_start(args, fmt);
4088
4089         r = dev_vprintk_emit(level, dev, fmt, args);
4090
4091         va_end(args);
4092
4093         return r;
4094 }
4095 EXPORT_SYMBOL(dev_printk_emit);
4096
4097 static void __dev_printk(const char *level, const struct device *dev,
4098                         struct va_format *vaf)
4099 {
4100         if (dev)
4101                 dev_printk_emit(level[1] - '0', dev, "%s %s: %pV",
4102                                 dev_driver_string(dev), dev_name(dev), vaf);
4103         else
4104                 printk("%s(NULL device *): %pV", level, vaf);
4105 }
4106
4107 void dev_printk(const char *level, const struct device *dev,
4108                 const char *fmt, ...)
4109 {
4110         struct va_format vaf;
4111         va_list args;
4112
4113         va_start(args, fmt);
4114
4115         vaf.fmt = fmt;
4116         vaf.va = &args;
4117
4118         __dev_printk(level, dev, &vaf);
4119
4120         va_end(args);
4121 }
4122 EXPORT_SYMBOL(dev_printk);
4123
4124 #define define_dev_printk_level(func, kern_level)               \
4125 void func(const struct device *dev, const char *fmt, ...)       \
4126 {                                                               \
4127         struct va_format vaf;                                   \
4128         va_list args;                                           \
4129                                                                 \
4130         va_start(args, fmt);                                    \
4131                                                                 \
4132         vaf.fmt = fmt;                                          \
4133         vaf.va = &args;                                         \
4134                                                                 \
4135         __dev_printk(kern_level, dev, &vaf);                    \
4136                                                                 \
4137         va_end(args);                                           \
4138 }                                                               \
4139 EXPORT_SYMBOL(func);
4140
4141 define_dev_printk_level(_dev_emerg, KERN_EMERG);
4142 define_dev_printk_level(_dev_alert, KERN_ALERT);
4143 define_dev_printk_level(_dev_crit, KERN_CRIT);
4144 define_dev_printk_level(_dev_err, KERN_ERR);
4145 define_dev_printk_level(_dev_warn, KERN_WARNING);
4146 define_dev_printk_level(_dev_notice, KERN_NOTICE);
4147 define_dev_printk_level(_dev_info, KERN_INFO);
4148
4149 #endif
4150
4151 static inline bool fwnode_is_primary(struct fwnode_handle *fwnode)
4152 {
4153         return fwnode && !IS_ERR(fwnode->secondary);
4154 }
4155
4156 /**
4157  * set_primary_fwnode - Change the primary firmware node of a given device.
4158  * @dev: Device to handle.
4159  * @fwnode: New primary firmware node of the device.
4160  *
4161  * Set the device's firmware node pointer to @fwnode, but if a secondary
4162  * firmware node of the device is present, preserve it.
4163  */
4164 void set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
4165 {
4166         if (fwnode) {
4167                 struct fwnode_handle *fn = dev->fwnode;
4168
4169                 if (fwnode_is_primary(fn))
4170                         fn = fn->secondary;
4171
4172                 if (fn) {
4173                         WARN_ON(fwnode->secondary);
4174                         fwnode->secondary = fn;
4175                 }
4176                 dev->fwnode = fwnode;
4177         } else {
4178                 dev->fwnode = fwnode_is_primary(dev->fwnode) ?
4179                         dev->fwnode->secondary : NULL;
4180         }
4181 }
4182 EXPORT_SYMBOL_GPL(set_primary_fwnode);
4183
4184 /**
4185  * set_secondary_fwnode - Change the secondary firmware node of a given device.
4186  * @dev: Device to handle.
4187  * @fwnode: New secondary firmware node of the device.
4188  *
4189  * If a primary firmware node of the device is present, set its secondary
4190  * pointer to @fwnode.  Otherwise, set the device's firmware node pointer to
4191  * @fwnode.
4192  */
4193 void set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
4194 {
4195         if (fwnode)
4196                 fwnode->secondary = ERR_PTR(-ENODEV);
4197
4198         if (fwnode_is_primary(dev->fwnode))
4199                 dev->fwnode->secondary = fwnode;
4200         else
4201                 dev->fwnode = fwnode;
4202 }
4203 EXPORT_SYMBOL_GPL(set_secondary_fwnode);
4204
4205 /**
4206  * device_set_of_node_from_dev - reuse device-tree node of another device
4207  * @dev: device whose device-tree node is being set
4208  * @dev2: device whose device-tree node is being reused
4209  *
4210  * Takes another reference to the new device-tree node after first dropping
4211  * any reference held to the old node.
4212  */
4213 void device_set_of_node_from_dev(struct device *dev, const struct device *dev2)
4214 {
4215         of_node_put(dev->of_node);
4216         dev->of_node = of_node_get(dev2->of_node);
4217         dev->of_node_reused = true;
4218 }
4219 EXPORT_SYMBOL_GPL(device_set_of_node_from_dev);
4220
4221 int device_match_name(struct device *dev, const void *name)
4222 {
4223         return sysfs_streq(dev_name(dev), name);
4224 }
4225 EXPORT_SYMBOL_GPL(device_match_name);
4226
4227 int device_match_of_node(struct device *dev, const void *np)
4228 {
4229         return dev->of_node == np;
4230 }
4231 EXPORT_SYMBOL_GPL(device_match_of_node);
4232
4233 int device_match_fwnode(struct device *dev, const void *fwnode)
4234 {
4235         return dev_fwnode(dev) == fwnode;
4236 }
4237 EXPORT_SYMBOL_GPL(device_match_fwnode);
4238
4239 int device_match_devt(struct device *dev, const void *pdevt)
4240 {
4241         return dev->devt == *(dev_t *)pdevt;
4242 }
4243 EXPORT_SYMBOL_GPL(device_match_devt);
4244
4245 int device_match_acpi_dev(struct device *dev, const void *adev)
4246 {
4247         return ACPI_COMPANION(dev) == adev;
4248 }
4249 EXPORT_SYMBOL(device_match_acpi_dev);
4250
4251 int device_match_any(struct device *dev, const void *unused)
4252 {
4253         return 1;
4254 }
4255 EXPORT_SYMBOL_GPL(device_match_any);