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