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