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