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