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