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