driver core: Add device link support for INFERRED flag
[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 static u32 fw_devlink_flags = DL_FLAG_SYNC_STATE_ONLY;
1454 static int __init fw_devlink_setup(char *arg)
1455 {
1456         if (!arg)
1457                 return -EINVAL;
1458
1459         if (strcmp(arg, "off") == 0) {
1460                 fw_devlink_flags = 0;
1461         } else if (strcmp(arg, "permissive") == 0) {
1462                 fw_devlink_flags = DL_FLAG_SYNC_STATE_ONLY;
1463         } else if (strcmp(arg, "on") == 0) {
1464                 fw_devlink_flags = DL_FLAG_AUTOPROBE_CONSUMER;
1465         } else if (strcmp(arg, "rpm") == 0) {
1466                 fw_devlink_flags = DL_FLAG_AUTOPROBE_CONSUMER |
1467                                    DL_FLAG_PM_RUNTIME;
1468         }
1469         return 0;
1470 }
1471 early_param("fw_devlink", fw_devlink_setup);
1472
1473 u32 fw_devlink_get_flags(void)
1474 {
1475         return fw_devlink_flags;
1476 }
1477
1478 static bool fw_devlink_is_permissive(void)
1479 {
1480         return fw_devlink_flags == DL_FLAG_SYNC_STATE_ONLY;
1481 }
1482
1483 static void fw_devlink_parse_fwnode(struct fwnode_handle *fwnode)
1484 {
1485         if (fwnode->flags & FWNODE_FLAG_LINKS_ADDED)
1486                 return;
1487
1488         fwnode_call_int_op(fwnode, add_links);
1489         fwnode->flags |= FWNODE_FLAG_LINKS_ADDED;
1490 }
1491
1492 static void fw_devlink_parse_fwtree(struct fwnode_handle *fwnode)
1493 {
1494         struct fwnode_handle *child = NULL;
1495
1496         fw_devlink_parse_fwnode(fwnode);
1497
1498         while ((child = fwnode_get_next_available_child_node(fwnode, child)))
1499                 fw_devlink_parse_fwtree(child);
1500 }
1501
1502 /**
1503  * fw_devlink_create_devlink - Create a device link from a consumer to fwnode
1504  * @con - Consumer device for the device link
1505  * @sup_handle - fwnode handle of supplier
1506  *
1507  * This function will try to create a device link between the consumer device
1508  * @con and the supplier device represented by @sup_handle.
1509  *
1510  * The supplier has to be provided as a fwnode because incorrect cycles in
1511  * fwnode links can sometimes cause the supplier device to never be created.
1512  * This function detects such cases and returns an error if it cannot create a
1513  * device link from the consumer to a missing supplier.
1514  *
1515  * Returns,
1516  * 0 on successfully creating a device link
1517  * -EINVAL if the device link cannot be created as expected
1518  * -EAGAIN if the device link cannot be created right now, but it may be
1519  *  possible to do that in the future
1520  */
1521 static int fw_devlink_create_devlink(struct device *con,
1522                                      struct fwnode_handle *sup_handle, u32 flags)
1523 {
1524         struct device *sup_dev;
1525         int ret = 0;
1526
1527         sup_dev = get_dev_from_fwnode(sup_handle);
1528         if (sup_dev) {
1529                 /*
1530                  * If this fails, it is due to cycles in device links.  Just
1531                  * give up on this link and treat it as invalid.
1532                  */
1533                 if (!device_link_add(con, sup_dev, flags))
1534                         ret = -EINVAL;
1535
1536                 goto out;
1537         }
1538
1539         /*
1540          * DL_FLAG_SYNC_STATE_ONLY doesn't block probing and supports
1541          * cycles. So cycle detection isn't necessary and shouldn't be
1542          * done.
1543          */
1544         if (flags & DL_FLAG_SYNC_STATE_ONLY)
1545                 return -EAGAIN;
1546
1547         /*
1548          * If we can't find the supplier device from its fwnode, it might be
1549          * due to a cyclic dependency between fwnodes. Some of these cycles can
1550          * be broken by applying logic. Check for these types of cycles and
1551          * break them so that devices in the cycle probe properly.
1552          *
1553          * If the supplier's parent is dependent on the consumer, then
1554          * the consumer-supplier dependency is a false dependency. So,
1555          * treat it as an invalid link.
1556          */
1557         sup_dev = fwnode_get_next_parent_dev(sup_handle);
1558         if (sup_dev && device_is_dependent(con, sup_dev)) {
1559                 dev_dbg(con, "Not linking to %pfwP - False link\n",
1560                         sup_handle);
1561                 ret = -EINVAL;
1562         } else {
1563                 /*
1564                  * Can't check for cycles or no cycles. So let's try
1565                  * again later.
1566                  */
1567                 ret = -EAGAIN;
1568         }
1569
1570 out:
1571         put_device(sup_dev);
1572         return ret;
1573 }
1574
1575 /**
1576  * __fw_devlink_link_to_consumers - Create device links to consumers of a device
1577  * @dev - Device that needs to be linked to its consumers
1578  *
1579  * This function looks at all the consumer fwnodes of @dev and creates device
1580  * links between the consumer device and @dev (supplier).
1581  *
1582  * If the consumer device has not been added yet, then this function creates a
1583  * SYNC_STATE_ONLY link between @dev (supplier) and the closest ancestor device
1584  * of the consumer fwnode. This is necessary to make sure @dev doesn't get a
1585  * sync_state() callback before the real consumer device gets to be added and
1586  * then probed.
1587  *
1588  * Once device links are created from the real consumer to @dev (supplier), the
1589  * fwnode links are deleted.
1590  */
1591 static void __fw_devlink_link_to_consumers(struct device *dev)
1592 {
1593         struct fwnode_handle *fwnode = dev->fwnode;
1594         struct fwnode_link *link, *tmp;
1595
1596         list_for_each_entry_safe(link, tmp, &fwnode->consumers, s_hook) {
1597                 u32 dl_flags = fw_devlink_get_flags();
1598                 struct device *con_dev;
1599                 bool own_link = true;
1600                 int ret;
1601
1602                 con_dev = get_dev_from_fwnode(link->consumer);
1603                 /*
1604                  * If consumer device is not available yet, make a "proxy"
1605                  * SYNC_STATE_ONLY link from the consumer's parent device to
1606                  * the supplier device. This is necessary to make sure the
1607                  * supplier doesn't get a sync_state() callback before the real
1608                  * consumer can create a device link to the supplier.
1609                  *
1610                  * This proxy link step is needed to handle the case where the
1611                  * consumer's parent device is added before the supplier.
1612                  */
1613                 if (!con_dev) {
1614                         con_dev = fwnode_get_next_parent_dev(link->consumer);
1615                         /*
1616                          * However, if the consumer's parent device is also the
1617                          * parent of the supplier, don't create a
1618                          * consumer-supplier link from the parent to its child
1619                          * device. Such a dependency is impossible.
1620                          */
1621                         if (con_dev &&
1622                             fwnode_is_ancestor_of(con_dev->fwnode, fwnode)) {
1623                                 put_device(con_dev);
1624                                 con_dev = NULL;
1625                         } else {
1626                                 own_link = false;
1627                                 dl_flags = DL_FLAG_SYNC_STATE_ONLY;
1628                         }
1629                 }
1630
1631                 if (!con_dev)
1632                         continue;
1633
1634                 ret = fw_devlink_create_devlink(con_dev, fwnode, dl_flags);
1635                 put_device(con_dev);
1636                 if (!own_link || ret == -EAGAIN)
1637                         continue;
1638
1639                 list_del(&link->s_hook);
1640                 list_del(&link->c_hook);
1641                 kfree(link);
1642         }
1643 }
1644
1645 /**
1646  * __fw_devlink_link_to_suppliers - Create device links to suppliers of a device
1647  * @dev - The consumer device that needs to be linked to its suppliers
1648  * @fwnode - Root of the fwnode tree that is used to create device links
1649  *
1650  * This function looks at all the supplier fwnodes of fwnode tree rooted at
1651  * @fwnode and creates device links between @dev (consumer) and all the
1652  * supplier devices of the entire fwnode tree at @fwnode.
1653  *
1654  * The function creates normal (non-SYNC_STATE_ONLY) device links between @dev
1655  * and the real suppliers of @dev. Once these device links are created, the
1656  * fwnode links are deleted. When such device links are successfully created,
1657  * this function is called recursively on those supplier devices. This is
1658  * needed to detect and break some invalid cycles in fwnode links.  See
1659  * fw_devlink_create_devlink() for more details.
1660  *
1661  * In addition, it also looks at all the suppliers of the entire fwnode tree
1662  * because some of the child devices of @dev that have not been added yet
1663  * (because @dev hasn't probed) might already have their suppliers added to
1664  * driver core. So, this function creates SYNC_STATE_ONLY device links between
1665  * @dev (consumer) and these suppliers to make sure they don't execute their
1666  * sync_state() callbacks before these child devices have a chance to create
1667  * their device links. The fwnode links that correspond to the child devices
1668  * aren't delete because they are needed later to create the device links
1669  * between the real consumer and supplier devices.
1670  */
1671 static void __fw_devlink_link_to_suppliers(struct device *dev,
1672                                            struct fwnode_handle *fwnode)
1673 {
1674         bool own_link = (dev->fwnode == fwnode);
1675         struct fwnode_link *link, *tmp;
1676         struct fwnode_handle *child = NULL;
1677         u32 dl_flags;
1678
1679         if (own_link)
1680                 dl_flags = fw_devlink_get_flags();
1681         else
1682                 dl_flags = DL_FLAG_SYNC_STATE_ONLY;
1683
1684         list_for_each_entry_safe(link, tmp, &fwnode->suppliers, c_hook) {
1685                 int ret;
1686                 struct device *sup_dev;
1687                 struct fwnode_handle *sup = link->supplier;
1688
1689                 ret = fw_devlink_create_devlink(dev, sup, dl_flags);
1690                 if (!own_link || ret == -EAGAIN)
1691                         continue;
1692
1693                 list_del(&link->s_hook);
1694                 list_del(&link->c_hook);
1695                 kfree(link);
1696
1697                 /* If no device link was created, nothing more to do. */
1698                 if (ret)
1699                         continue;
1700
1701                 /*
1702                  * If a device link was successfully created to a supplier, we
1703                  * now need to try and link the supplier to all its suppliers.
1704                  *
1705                  * This is needed to detect and delete false dependencies in
1706                  * fwnode links that haven't been converted to a device link
1707                  * yet. See comments in fw_devlink_create_devlink() for more
1708                  * details on the false dependency.
1709                  *
1710                  * Without deleting these false dependencies, some devices will
1711                  * never probe because they'll keep waiting for their false
1712                  * dependency fwnode links to be converted to device links.
1713                  */
1714                 sup_dev = get_dev_from_fwnode(sup);
1715                 __fw_devlink_link_to_suppliers(sup_dev, sup_dev->fwnode);
1716                 put_device(sup_dev);
1717         }
1718
1719         /*
1720          * Make "proxy" SYNC_STATE_ONLY device links to represent the needs of
1721          * all the descendants. This proxy link step is needed to handle the
1722          * case where the supplier is added before the consumer's parent device
1723          * (@dev).
1724          */
1725         while ((child = fwnode_get_next_available_child_node(fwnode, child)))
1726                 __fw_devlink_link_to_suppliers(dev, child);
1727 }
1728
1729 static void fw_devlink_link_device(struct device *dev)
1730 {
1731         struct fwnode_handle *fwnode = dev->fwnode;
1732
1733         if (!fw_devlink_flags)
1734                 return;
1735
1736         fw_devlink_parse_fwtree(fwnode);
1737
1738         mutex_lock(&fwnode_link_lock);
1739         __fw_devlink_link_to_consumers(dev);
1740         __fw_devlink_link_to_suppliers(dev, fwnode);
1741         mutex_unlock(&fwnode_link_lock);
1742 }
1743
1744 /* Device links support end. */
1745
1746 int (*platform_notify)(struct device *dev) = NULL;
1747 int (*platform_notify_remove)(struct device *dev) = NULL;
1748 static struct kobject *dev_kobj;
1749 struct kobject *sysfs_dev_char_kobj;
1750 struct kobject *sysfs_dev_block_kobj;
1751
1752 static DEFINE_MUTEX(device_hotplug_lock);
1753
1754 void lock_device_hotplug(void)
1755 {
1756         mutex_lock(&device_hotplug_lock);
1757 }
1758
1759 void unlock_device_hotplug(void)
1760 {
1761         mutex_unlock(&device_hotplug_lock);
1762 }
1763
1764 int lock_device_hotplug_sysfs(void)
1765 {
1766         if (mutex_trylock(&device_hotplug_lock))
1767                 return 0;
1768
1769         /* Avoid busy looping (5 ms of sleep should do). */
1770         msleep(5);
1771         return restart_syscall();
1772 }
1773
1774 #ifdef CONFIG_BLOCK
1775 static inline int device_is_not_partition(struct device *dev)
1776 {
1777         return !(dev->type == &part_type);
1778 }
1779 #else
1780 static inline int device_is_not_partition(struct device *dev)
1781 {
1782         return 1;
1783 }
1784 #endif
1785
1786 static int
1787 device_platform_notify(struct device *dev, enum kobject_action action)
1788 {
1789         int ret;
1790
1791         ret = acpi_platform_notify(dev, action);
1792         if (ret)
1793                 return ret;
1794
1795         ret = software_node_notify(dev, action);
1796         if (ret)
1797                 return ret;
1798
1799         if (platform_notify && action == KOBJ_ADD)
1800                 platform_notify(dev);
1801         else if (platform_notify_remove && action == KOBJ_REMOVE)
1802                 platform_notify_remove(dev);
1803         return 0;
1804 }
1805
1806 /**
1807  * dev_driver_string - Return a device's driver name, if at all possible
1808  * @dev: struct device to get the name of
1809  *
1810  * Will return the device's driver's name if it is bound to a device.  If
1811  * the device is not bound to a driver, it will return the name of the bus
1812  * it is attached to.  If it is not attached to a bus either, an empty
1813  * string will be returned.
1814  */
1815 const char *dev_driver_string(const struct device *dev)
1816 {
1817         struct device_driver *drv;
1818
1819         /* dev->driver can change to NULL underneath us because of unbinding,
1820          * so be careful about accessing it.  dev->bus and dev->class should
1821          * never change once they are set, so they don't need special care.
1822          */
1823         drv = READ_ONCE(dev->driver);
1824         return drv ? drv->name :
1825                         (dev->bus ? dev->bus->name :
1826                         (dev->class ? dev->class->name : ""));
1827 }
1828 EXPORT_SYMBOL(dev_driver_string);
1829
1830 #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr)
1831
1832 static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr,
1833                              char *buf)
1834 {
1835         struct device_attribute *dev_attr = to_dev_attr(attr);
1836         struct device *dev = kobj_to_dev(kobj);
1837         ssize_t ret = -EIO;
1838
1839         if (dev_attr->show)
1840                 ret = dev_attr->show(dev, dev_attr, buf);
1841         if (ret >= (ssize_t)PAGE_SIZE) {
1842                 printk("dev_attr_show: %pS returned bad count\n",
1843                                 dev_attr->show);
1844         }
1845         return ret;
1846 }
1847
1848 static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr,
1849                               const char *buf, size_t count)
1850 {
1851         struct device_attribute *dev_attr = to_dev_attr(attr);
1852         struct device *dev = kobj_to_dev(kobj);
1853         ssize_t ret = -EIO;
1854
1855         if (dev_attr->store)
1856                 ret = dev_attr->store(dev, dev_attr, buf, count);
1857         return ret;
1858 }
1859
1860 static const struct sysfs_ops dev_sysfs_ops = {
1861         .show   = dev_attr_show,
1862         .store  = dev_attr_store,
1863 };
1864
1865 #define to_ext_attr(x) container_of(x, struct dev_ext_attribute, attr)
1866
1867 ssize_t device_store_ulong(struct device *dev,
1868                            struct device_attribute *attr,
1869                            const char *buf, size_t size)
1870 {
1871         struct dev_ext_attribute *ea = to_ext_attr(attr);
1872         int ret;
1873         unsigned long new;
1874
1875         ret = kstrtoul(buf, 0, &new);
1876         if (ret)
1877                 return ret;
1878         *(unsigned long *)(ea->var) = new;
1879         /* Always return full write size even if we didn't consume all */
1880         return size;
1881 }
1882 EXPORT_SYMBOL_GPL(device_store_ulong);
1883
1884 ssize_t device_show_ulong(struct device *dev,
1885                           struct device_attribute *attr,
1886                           char *buf)
1887 {
1888         struct dev_ext_attribute *ea = to_ext_attr(attr);
1889         return sysfs_emit(buf, "%lx\n", *(unsigned long *)(ea->var));
1890 }
1891 EXPORT_SYMBOL_GPL(device_show_ulong);
1892
1893 ssize_t device_store_int(struct device *dev,
1894                          struct device_attribute *attr,
1895                          const char *buf, size_t size)
1896 {
1897         struct dev_ext_attribute *ea = to_ext_attr(attr);
1898         int ret;
1899         long new;
1900
1901         ret = kstrtol(buf, 0, &new);
1902         if (ret)
1903                 return ret;
1904
1905         if (new > INT_MAX || new < INT_MIN)
1906                 return -EINVAL;
1907         *(int *)(ea->var) = new;
1908         /* Always return full write size even if we didn't consume all */
1909         return size;
1910 }
1911 EXPORT_SYMBOL_GPL(device_store_int);
1912
1913 ssize_t device_show_int(struct device *dev,
1914                         struct device_attribute *attr,
1915                         char *buf)
1916 {
1917         struct dev_ext_attribute *ea = to_ext_attr(attr);
1918
1919         return sysfs_emit(buf, "%d\n", *(int *)(ea->var));
1920 }
1921 EXPORT_SYMBOL_GPL(device_show_int);
1922
1923 ssize_t device_store_bool(struct device *dev, struct device_attribute *attr,
1924                           const char *buf, size_t size)
1925 {
1926         struct dev_ext_attribute *ea = to_ext_attr(attr);
1927
1928         if (strtobool(buf, ea->var) < 0)
1929                 return -EINVAL;
1930
1931         return size;
1932 }
1933 EXPORT_SYMBOL_GPL(device_store_bool);
1934
1935 ssize_t device_show_bool(struct device *dev, struct device_attribute *attr,
1936                          char *buf)
1937 {
1938         struct dev_ext_attribute *ea = to_ext_attr(attr);
1939
1940         return sysfs_emit(buf, "%d\n", *(bool *)(ea->var));
1941 }
1942 EXPORT_SYMBOL_GPL(device_show_bool);
1943
1944 /**
1945  * device_release - free device structure.
1946  * @kobj: device's kobject.
1947  *
1948  * This is called once the reference count for the object
1949  * reaches 0. We forward the call to the device's release
1950  * method, which should handle actually freeing the structure.
1951  */
1952 static void device_release(struct kobject *kobj)
1953 {
1954         struct device *dev = kobj_to_dev(kobj);
1955         struct device_private *p = dev->p;
1956
1957         /*
1958          * Some platform devices are driven without driver attached
1959          * and managed resources may have been acquired.  Make sure
1960          * all resources are released.
1961          *
1962          * Drivers still can add resources into device after device
1963          * is deleted but alive, so release devres here to avoid
1964          * possible memory leak.
1965          */
1966         devres_release_all(dev);
1967
1968         kfree(dev->dma_range_map);
1969
1970         if (dev->release)
1971                 dev->release(dev);
1972         else if (dev->type && dev->type->release)
1973                 dev->type->release(dev);
1974         else if (dev->class && dev->class->dev_release)
1975                 dev->class->dev_release(dev);
1976         else
1977                 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",
1978                         dev_name(dev));
1979         kfree(p);
1980 }
1981
1982 static const void *device_namespace(struct kobject *kobj)
1983 {
1984         struct device *dev = kobj_to_dev(kobj);
1985         const void *ns = NULL;
1986
1987         if (dev->class && dev->class->ns_type)
1988                 ns = dev->class->namespace(dev);
1989
1990         return ns;
1991 }
1992
1993 static void device_get_ownership(struct kobject *kobj, kuid_t *uid, kgid_t *gid)
1994 {
1995         struct device *dev = kobj_to_dev(kobj);
1996
1997         if (dev->class && dev->class->get_ownership)
1998                 dev->class->get_ownership(dev, uid, gid);
1999 }
2000
2001 static struct kobj_type device_ktype = {
2002         .release        = device_release,
2003         .sysfs_ops      = &dev_sysfs_ops,
2004         .namespace      = device_namespace,
2005         .get_ownership  = device_get_ownership,
2006 };
2007
2008
2009 static int dev_uevent_filter(struct kset *kset, struct kobject *kobj)
2010 {
2011         struct kobj_type *ktype = get_ktype(kobj);
2012
2013         if (ktype == &device_ktype) {
2014                 struct device *dev = kobj_to_dev(kobj);
2015                 if (dev->bus)
2016                         return 1;
2017                 if (dev->class)
2018                         return 1;
2019         }
2020         return 0;
2021 }
2022
2023 static const char *dev_uevent_name(struct kset *kset, struct kobject *kobj)
2024 {
2025         struct device *dev = kobj_to_dev(kobj);
2026
2027         if (dev->bus)
2028                 return dev->bus->name;
2029         if (dev->class)
2030                 return dev->class->name;
2031         return NULL;
2032 }
2033
2034 static int dev_uevent(struct kset *kset, struct kobject *kobj,
2035                       struct kobj_uevent_env *env)
2036 {
2037         struct device *dev = kobj_to_dev(kobj);
2038         int retval = 0;
2039
2040         /* add device node properties if present */
2041         if (MAJOR(dev->devt)) {
2042                 const char *tmp;
2043                 const char *name;
2044                 umode_t mode = 0;
2045                 kuid_t uid = GLOBAL_ROOT_UID;
2046                 kgid_t gid = GLOBAL_ROOT_GID;
2047
2048                 add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt));
2049                 add_uevent_var(env, "MINOR=%u", MINOR(dev->devt));
2050                 name = device_get_devnode(dev, &mode, &uid, &gid, &tmp);
2051                 if (name) {
2052                         add_uevent_var(env, "DEVNAME=%s", name);
2053                         if (mode)
2054                                 add_uevent_var(env, "DEVMODE=%#o", mode & 0777);
2055                         if (!uid_eq(uid, GLOBAL_ROOT_UID))
2056                                 add_uevent_var(env, "DEVUID=%u", from_kuid(&init_user_ns, uid));
2057                         if (!gid_eq(gid, GLOBAL_ROOT_GID))
2058                                 add_uevent_var(env, "DEVGID=%u", from_kgid(&init_user_ns, gid));
2059                         kfree(tmp);
2060                 }
2061         }
2062
2063         if (dev->type && dev->type->name)
2064                 add_uevent_var(env, "DEVTYPE=%s", dev->type->name);
2065
2066         if (dev->driver)
2067                 add_uevent_var(env, "DRIVER=%s", dev->driver->name);
2068
2069         /* Add common DT information about the device */
2070         of_device_uevent(dev, env);
2071
2072         /* have the bus specific function add its stuff */
2073         if (dev->bus && dev->bus->uevent) {
2074                 retval = dev->bus->uevent(dev, env);
2075                 if (retval)
2076                         pr_debug("device: '%s': %s: bus uevent() returned %d\n",
2077                                  dev_name(dev), __func__, retval);
2078         }
2079
2080         /* have the class specific function add its stuff */
2081         if (dev->class && dev->class->dev_uevent) {
2082                 retval = dev->class->dev_uevent(dev, env);
2083                 if (retval)
2084                         pr_debug("device: '%s': %s: class uevent() "
2085                                  "returned %d\n", dev_name(dev),
2086                                  __func__, retval);
2087         }
2088
2089         /* have the device type specific function add its stuff */
2090         if (dev->type && dev->type->uevent) {
2091                 retval = dev->type->uevent(dev, env);
2092                 if (retval)
2093                         pr_debug("device: '%s': %s: dev_type uevent() "
2094                                  "returned %d\n", dev_name(dev),
2095                                  __func__, retval);
2096         }
2097
2098         return retval;
2099 }
2100
2101 static const struct kset_uevent_ops device_uevent_ops = {
2102         .filter =       dev_uevent_filter,
2103         .name =         dev_uevent_name,
2104         .uevent =       dev_uevent,
2105 };
2106
2107 static ssize_t uevent_show(struct device *dev, struct device_attribute *attr,
2108                            char *buf)
2109 {
2110         struct kobject *top_kobj;
2111         struct kset *kset;
2112         struct kobj_uevent_env *env = NULL;
2113         int i;
2114         int len = 0;
2115         int retval;
2116
2117         /* search the kset, the device belongs to */
2118         top_kobj = &dev->kobj;
2119         while (!top_kobj->kset && top_kobj->parent)
2120                 top_kobj = top_kobj->parent;
2121         if (!top_kobj->kset)
2122                 goto out;
2123
2124         kset = top_kobj->kset;
2125         if (!kset->uevent_ops || !kset->uevent_ops->uevent)
2126                 goto out;
2127
2128         /* respect filter */
2129         if (kset->uevent_ops && kset->uevent_ops->filter)
2130                 if (!kset->uevent_ops->filter(kset, &dev->kobj))
2131                         goto out;
2132
2133         env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL);
2134         if (!env)
2135                 return -ENOMEM;
2136
2137         /* let the kset specific function add its keys */
2138         retval = kset->uevent_ops->uevent(kset, &dev->kobj, env);
2139         if (retval)
2140                 goto out;
2141
2142         /* copy keys to file */
2143         for (i = 0; i < env->envp_idx; i++)
2144                 len += sysfs_emit_at(buf, len, "%s\n", env->envp[i]);
2145 out:
2146         kfree(env);
2147         return len;
2148 }
2149
2150 static ssize_t uevent_store(struct device *dev, struct device_attribute *attr,
2151                             const char *buf, size_t count)
2152 {
2153         int rc;
2154
2155         rc = kobject_synth_uevent(&dev->kobj, buf, count);
2156
2157         if (rc) {
2158                 dev_err(dev, "uevent: failed to send synthetic uevent\n");
2159                 return rc;
2160         }
2161
2162         return count;
2163 }
2164 static DEVICE_ATTR_RW(uevent);
2165
2166 static ssize_t online_show(struct device *dev, struct device_attribute *attr,
2167                            char *buf)
2168 {
2169         bool val;
2170
2171         device_lock(dev);
2172         val = !dev->offline;
2173         device_unlock(dev);
2174         return sysfs_emit(buf, "%u\n", val);
2175 }
2176
2177 static ssize_t online_store(struct device *dev, struct device_attribute *attr,
2178                             const char *buf, size_t count)
2179 {
2180         bool val;
2181         int ret;
2182
2183         ret = strtobool(buf, &val);
2184         if (ret < 0)
2185                 return ret;
2186
2187         ret = lock_device_hotplug_sysfs();
2188         if (ret)
2189                 return ret;
2190
2191         ret = val ? device_online(dev) : device_offline(dev);
2192         unlock_device_hotplug();
2193         return ret < 0 ? ret : count;
2194 }
2195 static DEVICE_ATTR_RW(online);
2196
2197 int device_add_groups(struct device *dev, const struct attribute_group **groups)
2198 {
2199         return sysfs_create_groups(&dev->kobj, groups);
2200 }
2201 EXPORT_SYMBOL_GPL(device_add_groups);
2202
2203 void device_remove_groups(struct device *dev,
2204                           const struct attribute_group **groups)
2205 {
2206         sysfs_remove_groups(&dev->kobj, groups);
2207 }
2208 EXPORT_SYMBOL_GPL(device_remove_groups);
2209
2210 union device_attr_group_devres {
2211         const struct attribute_group *group;
2212         const struct attribute_group **groups;
2213 };
2214
2215 static int devm_attr_group_match(struct device *dev, void *res, void *data)
2216 {
2217         return ((union device_attr_group_devres *)res)->group == data;
2218 }
2219
2220 static void devm_attr_group_remove(struct device *dev, void *res)
2221 {
2222         union device_attr_group_devres *devres = res;
2223         const struct attribute_group *group = devres->group;
2224
2225         dev_dbg(dev, "%s: removing group %p\n", __func__, group);
2226         sysfs_remove_group(&dev->kobj, group);
2227 }
2228
2229 static void devm_attr_groups_remove(struct device *dev, void *res)
2230 {
2231         union device_attr_group_devres *devres = res;
2232         const struct attribute_group **groups = devres->groups;
2233
2234         dev_dbg(dev, "%s: removing groups %p\n", __func__, groups);
2235         sysfs_remove_groups(&dev->kobj, groups);
2236 }
2237
2238 /**
2239  * devm_device_add_group - given a device, create a managed attribute group
2240  * @dev:        The device to create the group for
2241  * @grp:        The attribute group to create
2242  *
2243  * This function creates a group for the first time.  It will explicitly
2244  * warn and error if any of the attribute files being created already exist.
2245  *
2246  * Returns 0 on success or error code on failure.
2247  */
2248 int devm_device_add_group(struct device *dev, const struct attribute_group *grp)
2249 {
2250         union device_attr_group_devres *devres;
2251         int error;
2252
2253         devres = devres_alloc(devm_attr_group_remove,
2254                               sizeof(*devres), GFP_KERNEL);
2255         if (!devres)
2256                 return -ENOMEM;
2257
2258         error = sysfs_create_group(&dev->kobj, grp);
2259         if (error) {
2260                 devres_free(devres);
2261                 return error;
2262         }
2263
2264         devres->group = grp;
2265         devres_add(dev, devres);
2266         return 0;
2267 }
2268 EXPORT_SYMBOL_GPL(devm_device_add_group);
2269
2270 /**
2271  * devm_device_remove_group: remove a managed group from a device
2272  * @dev:        device to remove the group from
2273  * @grp:        group to remove
2274  *
2275  * This function removes a group of attributes from a device. The attributes
2276  * previously have to have been created for this group, otherwise it will fail.
2277  */
2278 void devm_device_remove_group(struct device *dev,
2279                               const struct attribute_group *grp)
2280 {
2281         WARN_ON(devres_release(dev, devm_attr_group_remove,
2282                                devm_attr_group_match,
2283                                /* cast away const */ (void *)grp));
2284 }
2285 EXPORT_SYMBOL_GPL(devm_device_remove_group);
2286
2287 /**
2288  * devm_device_add_groups - create a bunch of managed attribute groups
2289  * @dev:        The device to create the group for
2290  * @groups:     The attribute groups to create, NULL terminated
2291  *
2292  * This function creates a bunch of managed attribute groups.  If an error
2293  * occurs when creating a group, all previously created groups will be
2294  * removed, unwinding everything back to the original state when this
2295  * function was called.  It will explicitly warn and error if any of the
2296  * attribute files being created already exist.
2297  *
2298  * Returns 0 on success or error code from sysfs_create_group on failure.
2299  */
2300 int devm_device_add_groups(struct device *dev,
2301                            const struct attribute_group **groups)
2302 {
2303         union device_attr_group_devres *devres;
2304         int error;
2305
2306         devres = devres_alloc(devm_attr_groups_remove,
2307                               sizeof(*devres), GFP_KERNEL);
2308         if (!devres)
2309                 return -ENOMEM;
2310
2311         error = sysfs_create_groups(&dev->kobj, groups);
2312         if (error) {
2313                 devres_free(devres);
2314                 return error;
2315         }
2316
2317         devres->groups = groups;
2318         devres_add(dev, devres);
2319         return 0;
2320 }
2321 EXPORT_SYMBOL_GPL(devm_device_add_groups);
2322
2323 /**
2324  * devm_device_remove_groups - remove a list of managed groups
2325  *
2326  * @dev:        The device for the groups to be removed from
2327  * @groups:     NULL terminated list of groups to be removed
2328  *
2329  * If groups is not NULL, remove the specified groups from the device.
2330  */
2331 void devm_device_remove_groups(struct device *dev,
2332                                const struct attribute_group **groups)
2333 {
2334         WARN_ON(devres_release(dev, devm_attr_groups_remove,
2335                                devm_attr_group_match,
2336                                /* cast away const */ (void *)groups));
2337 }
2338 EXPORT_SYMBOL_GPL(devm_device_remove_groups);
2339
2340 static int device_add_attrs(struct device *dev)
2341 {
2342         struct class *class = dev->class;
2343         const struct device_type *type = dev->type;
2344         int error;
2345
2346         if (class) {
2347                 error = device_add_groups(dev, class->dev_groups);
2348                 if (error)
2349                         return error;
2350         }
2351
2352         if (type) {
2353                 error = device_add_groups(dev, type->groups);
2354                 if (error)
2355                         goto err_remove_class_groups;
2356         }
2357
2358         error = device_add_groups(dev, dev->groups);
2359         if (error)
2360                 goto err_remove_type_groups;
2361
2362         if (device_supports_offline(dev) && !dev->offline_disabled) {
2363                 error = device_create_file(dev, &dev_attr_online);
2364                 if (error)
2365                         goto err_remove_dev_groups;
2366         }
2367
2368         if (fw_devlink_flags && !fw_devlink_is_permissive() && dev->fwnode) {
2369                 error = device_create_file(dev, &dev_attr_waiting_for_supplier);
2370                 if (error)
2371                         goto err_remove_dev_online;
2372         }
2373
2374         return 0;
2375
2376  err_remove_dev_online:
2377         device_remove_file(dev, &dev_attr_online);
2378  err_remove_dev_groups:
2379         device_remove_groups(dev, dev->groups);
2380  err_remove_type_groups:
2381         if (type)
2382                 device_remove_groups(dev, type->groups);
2383  err_remove_class_groups:
2384         if (class)
2385                 device_remove_groups(dev, class->dev_groups);
2386
2387         return error;
2388 }
2389
2390 static void device_remove_attrs(struct device *dev)
2391 {
2392         struct class *class = dev->class;
2393         const struct device_type *type = dev->type;
2394
2395         device_remove_file(dev, &dev_attr_waiting_for_supplier);
2396         device_remove_file(dev, &dev_attr_online);
2397         device_remove_groups(dev, dev->groups);
2398
2399         if (type)
2400                 device_remove_groups(dev, type->groups);
2401
2402         if (class)
2403                 device_remove_groups(dev, class->dev_groups);
2404 }
2405
2406 static ssize_t dev_show(struct device *dev, struct device_attribute *attr,
2407                         char *buf)
2408 {
2409         return print_dev_t(buf, dev->devt);
2410 }
2411 static DEVICE_ATTR_RO(dev);
2412
2413 /* /sys/devices/ */
2414 struct kset *devices_kset;
2415
2416 /**
2417  * devices_kset_move_before - Move device in the devices_kset's list.
2418  * @deva: Device to move.
2419  * @devb: Device @deva should come before.
2420  */
2421 static void devices_kset_move_before(struct device *deva, struct device *devb)
2422 {
2423         if (!devices_kset)
2424                 return;
2425         pr_debug("devices_kset: Moving %s before %s\n",
2426                  dev_name(deva), dev_name(devb));
2427         spin_lock(&devices_kset->list_lock);
2428         list_move_tail(&deva->kobj.entry, &devb->kobj.entry);
2429         spin_unlock(&devices_kset->list_lock);
2430 }
2431
2432 /**
2433  * devices_kset_move_after - Move device in the devices_kset's list.
2434  * @deva: Device to move
2435  * @devb: Device @deva should come after.
2436  */
2437 static void devices_kset_move_after(struct device *deva, struct device *devb)
2438 {
2439         if (!devices_kset)
2440                 return;
2441         pr_debug("devices_kset: Moving %s after %s\n",
2442                  dev_name(deva), dev_name(devb));
2443         spin_lock(&devices_kset->list_lock);
2444         list_move(&deva->kobj.entry, &devb->kobj.entry);
2445         spin_unlock(&devices_kset->list_lock);
2446 }
2447
2448 /**
2449  * devices_kset_move_last - move the device to the end of devices_kset's list.
2450  * @dev: device to move
2451  */
2452 void devices_kset_move_last(struct device *dev)
2453 {
2454         if (!devices_kset)
2455                 return;
2456         pr_debug("devices_kset: Moving %s to end of list\n", dev_name(dev));
2457         spin_lock(&devices_kset->list_lock);
2458         list_move_tail(&dev->kobj.entry, &devices_kset->list);
2459         spin_unlock(&devices_kset->list_lock);
2460 }
2461
2462 /**
2463  * device_create_file - create sysfs attribute file for device.
2464  * @dev: device.
2465  * @attr: device attribute descriptor.
2466  */
2467 int device_create_file(struct device *dev,
2468                        const struct device_attribute *attr)
2469 {
2470         int error = 0;
2471
2472         if (dev) {
2473                 WARN(((attr->attr.mode & S_IWUGO) && !attr->store),
2474                         "Attribute %s: write permission without 'store'\n",
2475                         attr->attr.name);
2476                 WARN(((attr->attr.mode & S_IRUGO) && !attr->show),
2477                         "Attribute %s: read permission without 'show'\n",
2478                         attr->attr.name);
2479                 error = sysfs_create_file(&dev->kobj, &attr->attr);
2480         }
2481
2482         return error;
2483 }
2484 EXPORT_SYMBOL_GPL(device_create_file);
2485
2486 /**
2487  * device_remove_file - remove sysfs attribute file.
2488  * @dev: device.
2489  * @attr: device attribute descriptor.
2490  */
2491 void device_remove_file(struct device *dev,
2492                         const struct device_attribute *attr)
2493 {
2494         if (dev)
2495                 sysfs_remove_file(&dev->kobj, &attr->attr);
2496 }
2497 EXPORT_SYMBOL_GPL(device_remove_file);
2498
2499 /**
2500  * device_remove_file_self - remove sysfs attribute file from its own method.
2501  * @dev: device.
2502  * @attr: device attribute descriptor.
2503  *
2504  * See kernfs_remove_self() for details.
2505  */
2506 bool device_remove_file_self(struct device *dev,
2507                              const struct device_attribute *attr)
2508 {
2509         if (dev)
2510                 return sysfs_remove_file_self(&dev->kobj, &attr->attr);
2511         else
2512                 return false;
2513 }
2514 EXPORT_SYMBOL_GPL(device_remove_file_self);
2515
2516 /**
2517  * device_create_bin_file - create sysfs binary attribute file for device.
2518  * @dev: device.
2519  * @attr: device binary attribute descriptor.
2520  */
2521 int device_create_bin_file(struct device *dev,
2522                            const struct bin_attribute *attr)
2523 {
2524         int error = -EINVAL;
2525         if (dev)
2526                 error = sysfs_create_bin_file(&dev->kobj, attr);
2527         return error;
2528 }
2529 EXPORT_SYMBOL_GPL(device_create_bin_file);
2530
2531 /**
2532  * device_remove_bin_file - remove sysfs binary attribute file
2533  * @dev: device.
2534  * @attr: device binary attribute descriptor.
2535  */
2536 void device_remove_bin_file(struct device *dev,
2537                             const struct bin_attribute *attr)
2538 {
2539         if (dev)
2540                 sysfs_remove_bin_file(&dev->kobj, attr);
2541 }
2542 EXPORT_SYMBOL_GPL(device_remove_bin_file);
2543
2544 static void klist_children_get(struct klist_node *n)
2545 {
2546         struct device_private *p = to_device_private_parent(n);
2547         struct device *dev = p->device;
2548
2549         get_device(dev);
2550 }
2551
2552 static void klist_children_put(struct klist_node *n)
2553 {
2554         struct device_private *p = to_device_private_parent(n);
2555         struct device *dev = p->device;
2556
2557         put_device(dev);
2558 }
2559
2560 /**
2561  * device_initialize - init device structure.
2562  * @dev: device.
2563  *
2564  * This prepares the device for use by other layers by initializing
2565  * its fields.
2566  * It is the first half of device_register(), if called by
2567  * that function, though it can also be called separately, so one
2568  * may use @dev's fields. In particular, get_device()/put_device()
2569  * may be used for reference counting of @dev after calling this
2570  * function.
2571  *
2572  * All fields in @dev must be initialized by the caller to 0, except
2573  * for those explicitly set to some other value.  The simplest
2574  * approach is to use kzalloc() to allocate the structure containing
2575  * @dev.
2576  *
2577  * NOTE: Use put_device() to give up your reference instead of freeing
2578  * @dev directly once you have called this function.
2579  */
2580 void device_initialize(struct device *dev)
2581 {
2582         dev->kobj.kset = devices_kset;
2583         kobject_init(&dev->kobj, &device_ktype);
2584         INIT_LIST_HEAD(&dev->dma_pools);
2585         mutex_init(&dev->mutex);
2586 #ifdef CONFIG_PROVE_LOCKING
2587         mutex_init(&dev->lockdep_mutex);
2588 #endif
2589         lockdep_set_novalidate_class(&dev->mutex);
2590         spin_lock_init(&dev->devres_lock);
2591         INIT_LIST_HEAD(&dev->devres_head);
2592         device_pm_init(dev);
2593         set_dev_node(dev, -1);
2594 #ifdef CONFIG_GENERIC_MSI_IRQ
2595         INIT_LIST_HEAD(&dev->msi_list);
2596 #endif
2597         INIT_LIST_HEAD(&dev->links.consumers);
2598         INIT_LIST_HEAD(&dev->links.suppliers);
2599         INIT_LIST_HEAD(&dev->links.defer_sync);
2600         dev->links.status = DL_DEV_NO_DRIVER;
2601 }
2602 EXPORT_SYMBOL_GPL(device_initialize);
2603
2604 struct kobject *virtual_device_parent(struct device *dev)
2605 {
2606         static struct kobject *virtual_dir = NULL;
2607
2608         if (!virtual_dir)
2609                 virtual_dir = kobject_create_and_add("virtual",
2610                                                      &devices_kset->kobj);
2611
2612         return virtual_dir;
2613 }
2614
2615 struct class_dir {
2616         struct kobject kobj;
2617         struct class *class;
2618 };
2619
2620 #define to_class_dir(obj) container_of(obj, struct class_dir, kobj)
2621
2622 static void class_dir_release(struct kobject *kobj)
2623 {
2624         struct class_dir *dir = to_class_dir(kobj);
2625         kfree(dir);
2626 }
2627
2628 static const
2629 struct kobj_ns_type_operations *class_dir_child_ns_type(struct kobject *kobj)
2630 {
2631         struct class_dir *dir = to_class_dir(kobj);
2632         return dir->class->ns_type;
2633 }
2634
2635 static struct kobj_type class_dir_ktype = {
2636         .release        = class_dir_release,
2637         .sysfs_ops      = &kobj_sysfs_ops,
2638         .child_ns_type  = class_dir_child_ns_type
2639 };
2640
2641 static struct kobject *
2642 class_dir_create_and_add(struct class *class, struct kobject *parent_kobj)
2643 {
2644         struct class_dir *dir;
2645         int retval;
2646
2647         dir = kzalloc(sizeof(*dir), GFP_KERNEL);
2648         if (!dir)
2649                 return ERR_PTR(-ENOMEM);
2650
2651         dir->class = class;
2652         kobject_init(&dir->kobj, &class_dir_ktype);
2653
2654         dir->kobj.kset = &class->p->glue_dirs;
2655
2656         retval = kobject_add(&dir->kobj, parent_kobj, "%s", class->name);
2657         if (retval < 0) {
2658                 kobject_put(&dir->kobj);
2659                 return ERR_PTR(retval);
2660         }
2661         return &dir->kobj;
2662 }
2663
2664 static DEFINE_MUTEX(gdp_mutex);
2665
2666 static struct kobject *get_device_parent(struct device *dev,
2667                                          struct device *parent)
2668 {
2669         if (dev->class) {
2670                 struct kobject *kobj = NULL;
2671                 struct kobject *parent_kobj;
2672                 struct kobject *k;
2673
2674 #ifdef CONFIG_BLOCK
2675                 /* block disks show up in /sys/block */
2676                 if (sysfs_deprecated && dev->class == &block_class) {
2677                         if (parent && parent->class == &block_class)
2678                                 return &parent->kobj;
2679                         return &block_class.p->subsys.kobj;
2680                 }
2681 #endif
2682
2683                 /*
2684                  * If we have no parent, we live in "virtual".
2685                  * Class-devices with a non class-device as parent, live
2686                  * in a "glue" directory to prevent namespace collisions.
2687                  */
2688                 if (parent == NULL)
2689                         parent_kobj = virtual_device_parent(dev);
2690                 else if (parent->class && !dev->class->ns_type)
2691                         return &parent->kobj;
2692                 else
2693                         parent_kobj = &parent->kobj;
2694
2695                 mutex_lock(&gdp_mutex);
2696
2697                 /* find our class-directory at the parent and reference it */
2698                 spin_lock(&dev->class->p->glue_dirs.list_lock);
2699                 list_for_each_entry(k, &dev->class->p->glue_dirs.list, entry)
2700                         if (k->parent == parent_kobj) {
2701                                 kobj = kobject_get(k);
2702                                 break;
2703                         }
2704                 spin_unlock(&dev->class->p->glue_dirs.list_lock);
2705                 if (kobj) {
2706                         mutex_unlock(&gdp_mutex);
2707                         return kobj;
2708                 }
2709
2710                 /* or create a new class-directory at the parent device */
2711                 k = class_dir_create_and_add(dev->class, parent_kobj);
2712                 /* do not emit an uevent for this simple "glue" directory */
2713                 mutex_unlock(&gdp_mutex);
2714                 return k;
2715         }
2716
2717         /* subsystems can specify a default root directory for their devices */
2718         if (!parent && dev->bus && dev->bus->dev_root)
2719                 return &dev->bus->dev_root->kobj;
2720
2721         if (parent)
2722                 return &parent->kobj;
2723         return NULL;
2724 }
2725
2726 static inline bool live_in_glue_dir(struct kobject *kobj,
2727                                     struct device *dev)
2728 {
2729         if (!kobj || !dev->class ||
2730             kobj->kset != &dev->class->p->glue_dirs)
2731                 return false;
2732         return true;
2733 }
2734
2735 static inline struct kobject *get_glue_dir(struct device *dev)
2736 {
2737         return dev->kobj.parent;
2738 }
2739
2740 /*
2741  * make sure cleaning up dir as the last step, we need to make
2742  * sure .release handler of kobject is run with holding the
2743  * global lock
2744  */
2745 static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir)
2746 {
2747         unsigned int ref;
2748
2749         /* see if we live in a "glue" directory */
2750         if (!live_in_glue_dir(glue_dir, dev))
2751                 return;
2752
2753         mutex_lock(&gdp_mutex);
2754         /**
2755          * There is a race condition between removing glue directory
2756          * and adding a new device under the glue directory.
2757          *
2758          * CPU1:                                         CPU2:
2759          *
2760          * device_add()
2761          *   get_device_parent()
2762          *     class_dir_create_and_add()
2763          *       kobject_add_internal()
2764          *         create_dir()    // create glue_dir
2765          *
2766          *                                               device_add()
2767          *                                                 get_device_parent()
2768          *                                                   kobject_get() // get glue_dir
2769          *
2770          * device_del()
2771          *   cleanup_glue_dir()
2772          *     kobject_del(glue_dir)
2773          *
2774          *                                               kobject_add()
2775          *                                                 kobject_add_internal()
2776          *                                                   create_dir() // in glue_dir
2777          *                                                     sysfs_create_dir_ns()
2778          *                                                       kernfs_create_dir_ns(sd)
2779          *
2780          *       sysfs_remove_dir() // glue_dir->sd=NULL
2781          *       sysfs_put()        // free glue_dir->sd
2782          *
2783          *                                                         // sd is freed
2784          *                                                         kernfs_new_node(sd)
2785          *                                                           kernfs_get(glue_dir)
2786          *                                                           kernfs_add_one()
2787          *                                                           kernfs_put()
2788          *
2789          * Before CPU1 remove last child device under glue dir, if CPU2 add
2790          * a new device under glue dir, the glue_dir kobject reference count
2791          * will be increase to 2 in kobject_get(k). And CPU2 has been called
2792          * kernfs_create_dir_ns(). Meanwhile, CPU1 call sysfs_remove_dir()
2793          * and sysfs_put(). This result in glue_dir->sd is freed.
2794          *
2795          * Then the CPU2 will see a stale "empty" but still potentially used
2796          * glue dir around in kernfs_new_node().
2797          *
2798          * In order to avoid this happening, we also should make sure that
2799          * kernfs_node for glue_dir is released in CPU1 only when refcount
2800          * for glue_dir kobj is 1.
2801          */
2802         ref = kref_read(&glue_dir->kref);
2803         if (!kobject_has_children(glue_dir) && !--ref)
2804                 kobject_del(glue_dir);
2805         kobject_put(glue_dir);
2806         mutex_unlock(&gdp_mutex);
2807 }
2808
2809 static int device_add_class_symlinks(struct device *dev)
2810 {
2811         struct device_node *of_node = dev_of_node(dev);
2812         int error;
2813
2814         if (of_node) {
2815                 error = sysfs_create_link(&dev->kobj, of_node_kobj(of_node), "of_node");
2816                 if (error)
2817                         dev_warn(dev, "Error %d creating of_node link\n",error);
2818                 /* An error here doesn't warrant bringing down the device */
2819         }
2820
2821         if (!dev->class)
2822                 return 0;
2823
2824         error = sysfs_create_link(&dev->kobj,
2825                                   &dev->class->p->subsys.kobj,
2826                                   "subsystem");
2827         if (error)
2828                 goto out_devnode;
2829
2830         if (dev->parent && device_is_not_partition(dev)) {
2831                 error = sysfs_create_link(&dev->kobj, &dev->parent->kobj,
2832                                           "device");
2833                 if (error)
2834                         goto out_subsys;
2835         }
2836
2837 #ifdef CONFIG_BLOCK
2838         /* /sys/block has directories and does not need symlinks */
2839         if (sysfs_deprecated && dev->class == &block_class)
2840                 return 0;
2841 #endif
2842
2843         /* link in the class directory pointing to the device */
2844         error = sysfs_create_link(&dev->class->p->subsys.kobj,
2845                                   &dev->kobj, dev_name(dev));
2846         if (error)
2847                 goto out_device;
2848
2849         return 0;
2850
2851 out_device:
2852         sysfs_remove_link(&dev->kobj, "device");
2853
2854 out_subsys:
2855         sysfs_remove_link(&dev->kobj, "subsystem");
2856 out_devnode:
2857         sysfs_remove_link(&dev->kobj, "of_node");
2858         return error;
2859 }
2860
2861 static void device_remove_class_symlinks(struct device *dev)
2862 {
2863         if (dev_of_node(dev))
2864                 sysfs_remove_link(&dev->kobj, "of_node");
2865
2866         if (!dev->class)
2867                 return;
2868
2869         if (dev->parent && device_is_not_partition(dev))
2870                 sysfs_remove_link(&dev->kobj, "device");
2871         sysfs_remove_link(&dev->kobj, "subsystem");
2872 #ifdef CONFIG_BLOCK
2873         if (sysfs_deprecated && dev->class == &block_class)
2874                 return;
2875 #endif
2876         sysfs_delete_link(&dev->class->p->subsys.kobj, &dev->kobj, dev_name(dev));
2877 }
2878
2879 /**
2880  * dev_set_name - set a device name
2881  * @dev: device
2882  * @fmt: format string for the device's name
2883  */
2884 int dev_set_name(struct device *dev, const char *fmt, ...)
2885 {
2886         va_list vargs;
2887         int err;
2888
2889         va_start(vargs, fmt);
2890         err = kobject_set_name_vargs(&dev->kobj, fmt, vargs);
2891         va_end(vargs);
2892         return err;
2893 }
2894 EXPORT_SYMBOL_GPL(dev_set_name);
2895
2896 /**
2897  * device_to_dev_kobj - select a /sys/dev/ directory for the device
2898  * @dev: device
2899  *
2900  * By default we select char/ for new entries.  Setting class->dev_obj
2901  * to NULL prevents an entry from being created.  class->dev_kobj must
2902  * be set (or cleared) before any devices are registered to the class
2903  * otherwise device_create_sys_dev_entry() and
2904  * device_remove_sys_dev_entry() will disagree about the presence of
2905  * the link.
2906  */
2907 static struct kobject *device_to_dev_kobj(struct device *dev)
2908 {
2909         struct kobject *kobj;
2910
2911         if (dev->class)
2912                 kobj = dev->class->dev_kobj;
2913         else
2914                 kobj = sysfs_dev_char_kobj;
2915
2916         return kobj;
2917 }
2918
2919 static int device_create_sys_dev_entry(struct device *dev)
2920 {
2921         struct kobject *kobj = device_to_dev_kobj(dev);
2922         int error = 0;
2923         char devt_str[15];
2924
2925         if (kobj) {
2926                 format_dev_t(devt_str, dev->devt);
2927                 error = sysfs_create_link(kobj, &dev->kobj, devt_str);
2928         }
2929
2930         return error;
2931 }
2932
2933 static void device_remove_sys_dev_entry(struct device *dev)
2934 {
2935         struct kobject *kobj = device_to_dev_kobj(dev);
2936         char devt_str[15];
2937
2938         if (kobj) {
2939                 format_dev_t(devt_str, dev->devt);
2940                 sysfs_remove_link(kobj, devt_str);
2941         }
2942 }
2943
2944 static int device_private_init(struct device *dev)
2945 {
2946         dev->p = kzalloc(sizeof(*dev->p), GFP_KERNEL);
2947         if (!dev->p)
2948                 return -ENOMEM;
2949         dev->p->device = dev;
2950         klist_init(&dev->p->klist_children, klist_children_get,
2951                    klist_children_put);
2952         INIT_LIST_HEAD(&dev->p->deferred_probe);
2953         return 0;
2954 }
2955
2956 /**
2957  * device_add - add device to device hierarchy.
2958  * @dev: device.
2959  *
2960  * This is part 2 of device_register(), though may be called
2961  * separately _iff_ device_initialize() has been called separately.
2962  *
2963  * This adds @dev to the kobject hierarchy via kobject_add(), adds it
2964  * to the global and sibling lists for the device, then
2965  * adds it to the other relevant subsystems of the driver model.
2966  *
2967  * Do not call this routine or device_register() more than once for
2968  * any device structure.  The driver model core is not designed to work
2969  * with devices that get unregistered and then spring back to life.
2970  * (Among other things, it's very hard to guarantee that all references
2971  * to the previous incarnation of @dev have been dropped.)  Allocate
2972  * and register a fresh new struct device instead.
2973  *
2974  * NOTE: _Never_ directly free @dev after calling this function, even
2975  * if it returned an error! Always use put_device() to give up your
2976  * reference instead.
2977  *
2978  * Rule of thumb is: if device_add() succeeds, you should call
2979  * device_del() when you want to get rid of it. If device_add() has
2980  * *not* succeeded, use *only* put_device() to drop the reference
2981  * count.
2982  */
2983 int device_add(struct device *dev)
2984 {
2985         struct device *parent;
2986         struct kobject *kobj;
2987         struct class_interface *class_intf;
2988         int error = -EINVAL;
2989         struct kobject *glue_dir = NULL;
2990
2991         dev = get_device(dev);
2992         if (!dev)
2993                 goto done;
2994
2995         if (!dev->p) {
2996                 error = device_private_init(dev);
2997                 if (error)
2998                         goto done;
2999         }
3000
3001         /*
3002          * for statically allocated devices, which should all be converted
3003          * some day, we need to initialize the name. We prevent reading back
3004          * the name, and force the use of dev_name()
3005          */
3006         if (dev->init_name) {
3007                 dev_set_name(dev, "%s", dev->init_name);
3008                 dev->init_name = NULL;
3009         }
3010
3011         /* subsystems can specify simple device enumeration */
3012         if (!dev_name(dev) && dev->bus && dev->bus->dev_name)
3013                 dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id);
3014
3015         if (!dev_name(dev)) {
3016                 error = -EINVAL;
3017                 goto name_error;
3018         }
3019
3020         pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3021
3022         parent = get_device(dev->parent);
3023         kobj = get_device_parent(dev, parent);
3024         if (IS_ERR(kobj)) {
3025                 error = PTR_ERR(kobj);
3026                 goto parent_error;
3027         }
3028         if (kobj)
3029                 dev->kobj.parent = kobj;
3030
3031         /* use parent numa_node */
3032         if (parent && (dev_to_node(dev) == NUMA_NO_NODE))
3033                 set_dev_node(dev, dev_to_node(parent));
3034
3035         /* first, register with generic layer. */
3036         /* we require the name to be set before, and pass NULL */
3037         error = kobject_add(&dev->kobj, dev->kobj.parent, NULL);
3038         if (error) {
3039                 glue_dir = get_glue_dir(dev);
3040                 goto Error;
3041         }
3042
3043         /* notify platform of device entry */
3044         error = device_platform_notify(dev, KOBJ_ADD);
3045         if (error)
3046                 goto platform_error;
3047
3048         error = device_create_file(dev, &dev_attr_uevent);
3049         if (error)
3050                 goto attrError;
3051
3052         error = device_add_class_symlinks(dev);
3053         if (error)
3054                 goto SymlinkError;
3055         error = device_add_attrs(dev);
3056         if (error)
3057                 goto AttrsError;
3058         error = bus_add_device(dev);
3059         if (error)
3060                 goto BusError;
3061         error = dpm_sysfs_add(dev);
3062         if (error)
3063                 goto DPMError;
3064         device_pm_add(dev);
3065
3066         if (MAJOR(dev->devt)) {
3067                 error = device_create_file(dev, &dev_attr_dev);
3068                 if (error)
3069                         goto DevAttrError;
3070
3071                 error = device_create_sys_dev_entry(dev);
3072                 if (error)
3073                         goto SysEntryError;
3074
3075                 devtmpfs_create_node(dev);
3076         }
3077
3078         /* Notify clients of device addition.  This call must come
3079          * after dpm_sysfs_add() and before kobject_uevent().
3080          */
3081         if (dev->bus)
3082                 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
3083                                              BUS_NOTIFY_ADD_DEVICE, dev);
3084
3085         kobject_uevent(&dev->kobj, KOBJ_ADD);
3086
3087         /*
3088          * Check if any of the other devices (consumers) have been waiting for
3089          * this device (supplier) to be added so that they can create a device
3090          * link to it.
3091          *
3092          * This needs to happen after device_pm_add() because device_link_add()
3093          * requires the supplier be registered before it's called.
3094          *
3095          * But this also needs to happen before bus_probe_device() to make sure
3096          * waiting consumers can link to it before the driver is bound to the
3097          * device and the driver sync_state callback is called for this device.
3098          */
3099         if (dev->fwnode && !dev->fwnode->dev) {
3100                 dev->fwnode->dev = dev;
3101                 fw_devlink_link_device(dev);
3102         }
3103
3104         bus_probe_device(dev);
3105         if (parent)
3106                 klist_add_tail(&dev->p->knode_parent,
3107                                &parent->p->klist_children);
3108
3109         if (dev->class) {
3110                 mutex_lock(&dev->class->p->mutex);
3111                 /* tie the class to the device */
3112                 klist_add_tail(&dev->p->knode_class,
3113                                &dev->class->p->klist_devices);
3114
3115                 /* notify any interfaces that the device is here */
3116                 list_for_each_entry(class_intf,
3117                                     &dev->class->p->interfaces, node)
3118                         if (class_intf->add_dev)
3119                                 class_intf->add_dev(dev, class_intf);
3120                 mutex_unlock(&dev->class->p->mutex);
3121         }
3122 done:
3123         put_device(dev);
3124         return error;
3125  SysEntryError:
3126         if (MAJOR(dev->devt))
3127                 device_remove_file(dev, &dev_attr_dev);
3128  DevAttrError:
3129         device_pm_remove(dev);
3130         dpm_sysfs_remove(dev);
3131  DPMError:
3132         bus_remove_device(dev);
3133  BusError:
3134         device_remove_attrs(dev);
3135  AttrsError:
3136         device_remove_class_symlinks(dev);
3137  SymlinkError:
3138         device_remove_file(dev, &dev_attr_uevent);
3139  attrError:
3140         device_platform_notify(dev, KOBJ_REMOVE);
3141 platform_error:
3142         kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3143         glue_dir = get_glue_dir(dev);
3144         kobject_del(&dev->kobj);
3145  Error:
3146         cleanup_glue_dir(dev, glue_dir);
3147 parent_error:
3148         put_device(parent);
3149 name_error:
3150         kfree(dev->p);
3151         dev->p = NULL;
3152         goto done;
3153 }
3154 EXPORT_SYMBOL_GPL(device_add);
3155
3156 /**
3157  * device_register - register a device with the system.
3158  * @dev: pointer to the device structure
3159  *
3160  * This happens in two clean steps - initialize the device
3161  * and add it to the system. The two steps can be called
3162  * separately, but this is the easiest and most common.
3163  * I.e. you should only call the two helpers separately if
3164  * have a clearly defined need to use and refcount the device
3165  * before it is added to the hierarchy.
3166  *
3167  * For more information, see the kerneldoc for device_initialize()
3168  * and device_add().
3169  *
3170  * NOTE: _Never_ directly free @dev after calling this function, even
3171  * if it returned an error! Always use put_device() to give up the
3172  * reference initialized in this function instead.
3173  */
3174 int device_register(struct device *dev)
3175 {
3176         device_initialize(dev);
3177         return device_add(dev);
3178 }
3179 EXPORT_SYMBOL_GPL(device_register);
3180
3181 /**
3182  * get_device - increment reference count for device.
3183  * @dev: device.
3184  *
3185  * This simply forwards the call to kobject_get(), though
3186  * we do take care to provide for the case that we get a NULL
3187  * pointer passed in.
3188  */
3189 struct device *get_device(struct device *dev)
3190 {
3191         return dev ? kobj_to_dev(kobject_get(&dev->kobj)) : NULL;
3192 }
3193 EXPORT_SYMBOL_GPL(get_device);
3194
3195 /**
3196  * put_device - decrement reference count.
3197  * @dev: device in question.
3198  */
3199 void put_device(struct device *dev)
3200 {
3201         /* might_sleep(); */
3202         if (dev)
3203                 kobject_put(&dev->kobj);
3204 }
3205 EXPORT_SYMBOL_GPL(put_device);
3206
3207 bool kill_device(struct device *dev)
3208 {
3209         /*
3210          * Require the device lock and set the "dead" flag to guarantee that
3211          * the update behavior is consistent with the other bitfields near
3212          * it and that we cannot have an asynchronous probe routine trying
3213          * to run while we are tearing out the bus/class/sysfs from
3214          * underneath the device.
3215          */
3216         lockdep_assert_held(&dev->mutex);
3217
3218         if (dev->p->dead)
3219                 return false;
3220         dev->p->dead = true;
3221         return true;
3222 }
3223 EXPORT_SYMBOL_GPL(kill_device);
3224
3225 /**
3226  * device_del - delete device from system.
3227  * @dev: device.
3228  *
3229  * This is the first part of the device unregistration
3230  * sequence. This removes the device from the lists we control
3231  * from here, has it removed from the other driver model
3232  * subsystems it was added to in device_add(), and removes it
3233  * from the kobject hierarchy.
3234  *
3235  * NOTE: this should be called manually _iff_ device_add() was
3236  * also called manually.
3237  */
3238 void device_del(struct device *dev)
3239 {
3240         struct device *parent = dev->parent;
3241         struct kobject *glue_dir = NULL;
3242         struct class_interface *class_intf;
3243         unsigned int noio_flag;
3244
3245         device_lock(dev);
3246         kill_device(dev);
3247         device_unlock(dev);
3248
3249         if (dev->fwnode && dev->fwnode->dev == dev)
3250                 dev->fwnode->dev = NULL;
3251
3252         /* Notify clients of device removal.  This call must come
3253          * before dpm_sysfs_remove().
3254          */
3255         noio_flag = memalloc_noio_save();
3256         if (dev->bus)
3257                 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
3258                                              BUS_NOTIFY_DEL_DEVICE, dev);
3259
3260         dpm_sysfs_remove(dev);
3261         if (parent)
3262                 klist_del(&dev->p->knode_parent);
3263         if (MAJOR(dev->devt)) {
3264                 devtmpfs_delete_node(dev);
3265                 device_remove_sys_dev_entry(dev);
3266                 device_remove_file(dev, &dev_attr_dev);
3267         }
3268         if (dev->class) {
3269                 device_remove_class_symlinks(dev);
3270
3271                 mutex_lock(&dev->class->p->mutex);
3272                 /* notify any interfaces that the device is now gone */
3273                 list_for_each_entry(class_intf,
3274                                     &dev->class->p->interfaces, node)
3275                         if (class_intf->remove_dev)
3276                                 class_intf->remove_dev(dev, class_intf);
3277                 /* remove the device from the class list */
3278                 klist_del(&dev->p->knode_class);
3279                 mutex_unlock(&dev->class->p->mutex);
3280         }
3281         device_remove_file(dev, &dev_attr_uevent);
3282         device_remove_attrs(dev);
3283         bus_remove_device(dev);
3284         device_pm_remove(dev);
3285         driver_deferred_probe_del(dev);
3286         device_platform_notify(dev, KOBJ_REMOVE);
3287         device_remove_properties(dev);
3288         device_links_purge(dev);
3289
3290         if (dev->bus)
3291                 blocking_notifier_call_chain(&dev->bus->p->bus_notifier,
3292                                              BUS_NOTIFY_REMOVED_DEVICE, dev);
3293         kobject_uevent(&dev->kobj, KOBJ_REMOVE);
3294         glue_dir = get_glue_dir(dev);
3295         kobject_del(&dev->kobj);
3296         cleanup_glue_dir(dev, glue_dir);
3297         memalloc_noio_restore(noio_flag);
3298         put_device(parent);
3299 }
3300 EXPORT_SYMBOL_GPL(device_del);
3301
3302 /**
3303  * device_unregister - unregister device from system.
3304  * @dev: device going away.
3305  *
3306  * We do this in two parts, like we do device_register(). First,
3307  * we remove it from all the subsystems with device_del(), then
3308  * we decrement the reference count via put_device(). If that
3309  * is the final reference count, the device will be cleaned up
3310  * via device_release() above. Otherwise, the structure will
3311  * stick around until the final reference to the device is dropped.
3312  */
3313 void device_unregister(struct device *dev)
3314 {
3315         pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3316         device_del(dev);
3317         put_device(dev);
3318 }
3319 EXPORT_SYMBOL_GPL(device_unregister);
3320
3321 static struct device *prev_device(struct klist_iter *i)
3322 {
3323         struct klist_node *n = klist_prev(i);
3324         struct device *dev = NULL;
3325         struct device_private *p;
3326
3327         if (n) {
3328                 p = to_device_private_parent(n);
3329                 dev = p->device;
3330         }
3331         return dev;
3332 }
3333
3334 static struct device *next_device(struct klist_iter *i)
3335 {
3336         struct klist_node *n = klist_next(i);
3337         struct device *dev = NULL;
3338         struct device_private *p;
3339
3340         if (n) {
3341                 p = to_device_private_parent(n);
3342                 dev = p->device;
3343         }
3344         return dev;
3345 }
3346
3347 /**
3348  * device_get_devnode - path of device node file
3349  * @dev: device
3350  * @mode: returned file access mode
3351  * @uid: returned file owner
3352  * @gid: returned file group
3353  * @tmp: possibly allocated string
3354  *
3355  * Return the relative path of a possible device node.
3356  * Non-default names may need to allocate a memory to compose
3357  * a name. This memory is returned in tmp and needs to be
3358  * freed by the caller.
3359  */
3360 const char *device_get_devnode(struct device *dev,
3361                                umode_t *mode, kuid_t *uid, kgid_t *gid,
3362                                const char **tmp)
3363 {
3364         char *s;
3365
3366         *tmp = NULL;
3367
3368         /* the device type may provide a specific name */
3369         if (dev->type && dev->type->devnode)
3370                 *tmp = dev->type->devnode(dev, mode, uid, gid);
3371         if (*tmp)
3372                 return *tmp;
3373
3374         /* the class may provide a specific name */
3375         if (dev->class && dev->class->devnode)
3376                 *tmp = dev->class->devnode(dev, mode);
3377         if (*tmp)
3378                 return *tmp;
3379
3380         /* return name without allocation, tmp == NULL */
3381         if (strchr(dev_name(dev), '!') == NULL)
3382                 return dev_name(dev);
3383
3384         /* replace '!' in the name with '/' */
3385         s = kstrdup(dev_name(dev), GFP_KERNEL);
3386         if (!s)
3387                 return NULL;
3388         strreplace(s, '!', '/');
3389         return *tmp = s;
3390 }
3391
3392 /**
3393  * device_for_each_child - device child iterator.
3394  * @parent: parent struct device.
3395  * @fn: function to be called for each device.
3396  * @data: data for the callback.
3397  *
3398  * Iterate over @parent's child devices, and call @fn for each,
3399  * passing it @data.
3400  *
3401  * We check the return of @fn each time. If it returns anything
3402  * other than 0, we break out and return that value.
3403  */
3404 int device_for_each_child(struct device *parent, void *data,
3405                           int (*fn)(struct device *dev, void *data))
3406 {
3407         struct klist_iter i;
3408         struct device *child;
3409         int error = 0;
3410
3411         if (!parent->p)
3412                 return 0;
3413
3414         klist_iter_init(&parent->p->klist_children, &i);
3415         while (!error && (child = next_device(&i)))
3416                 error = fn(child, data);
3417         klist_iter_exit(&i);
3418         return error;
3419 }
3420 EXPORT_SYMBOL_GPL(device_for_each_child);
3421
3422 /**
3423  * device_for_each_child_reverse - device child iterator in reversed order.
3424  * @parent: parent struct device.
3425  * @fn: function to be called for each device.
3426  * @data: data for the callback.
3427  *
3428  * Iterate over @parent's child devices, and call @fn for each,
3429  * passing it @data.
3430  *
3431  * We check the return of @fn each time. If it returns anything
3432  * other than 0, we break out and return that value.
3433  */
3434 int device_for_each_child_reverse(struct device *parent, void *data,
3435                                   int (*fn)(struct device *dev, void *data))
3436 {
3437         struct klist_iter i;
3438         struct device *child;
3439         int error = 0;
3440
3441         if (!parent->p)
3442                 return 0;
3443
3444         klist_iter_init(&parent->p->klist_children, &i);
3445         while ((child = prev_device(&i)) && !error)
3446                 error = fn(child, data);
3447         klist_iter_exit(&i);
3448         return error;
3449 }
3450 EXPORT_SYMBOL_GPL(device_for_each_child_reverse);
3451
3452 /**
3453  * device_find_child - device iterator for locating a particular device.
3454  * @parent: parent struct device
3455  * @match: Callback function to check device
3456  * @data: Data to pass to match function
3457  *
3458  * This is similar to the device_for_each_child() function above, but it
3459  * returns a reference to a device that is 'found' for later use, as
3460  * determined by the @match callback.
3461  *
3462  * The callback should return 0 if the device doesn't match and non-zero
3463  * if it does.  If the callback returns non-zero and a reference to the
3464  * current device can be obtained, this function will return to the caller
3465  * and not iterate over any more devices.
3466  *
3467  * NOTE: you will need to drop the reference with put_device() after use.
3468  */
3469 struct device *device_find_child(struct device *parent, void *data,
3470                                  int (*match)(struct device *dev, void *data))
3471 {
3472         struct klist_iter i;
3473         struct device *child;
3474
3475         if (!parent)
3476                 return NULL;
3477
3478         klist_iter_init(&parent->p->klist_children, &i);
3479         while ((child = next_device(&i)))
3480                 if (match(child, data) && get_device(child))
3481                         break;
3482         klist_iter_exit(&i);
3483         return child;
3484 }
3485 EXPORT_SYMBOL_GPL(device_find_child);
3486
3487 /**
3488  * device_find_child_by_name - device iterator for locating a child device.
3489  * @parent: parent struct device
3490  * @name: name of the child device
3491  *
3492  * This is similar to the device_find_child() function above, but it
3493  * returns a reference to a device that has the name @name.
3494  *
3495  * NOTE: you will need to drop the reference with put_device() after use.
3496  */
3497 struct device *device_find_child_by_name(struct device *parent,
3498                                          const char *name)
3499 {
3500         struct klist_iter i;
3501         struct device *child;
3502
3503         if (!parent)
3504                 return NULL;
3505
3506         klist_iter_init(&parent->p->klist_children, &i);
3507         while ((child = next_device(&i)))
3508                 if (sysfs_streq(dev_name(child), name) && get_device(child))
3509                         break;
3510         klist_iter_exit(&i);
3511         return child;
3512 }
3513 EXPORT_SYMBOL_GPL(device_find_child_by_name);
3514
3515 int __init devices_init(void)
3516 {
3517         devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL);
3518         if (!devices_kset)
3519                 return -ENOMEM;
3520         dev_kobj = kobject_create_and_add("dev", NULL);
3521         if (!dev_kobj)
3522                 goto dev_kobj_err;
3523         sysfs_dev_block_kobj = kobject_create_and_add("block", dev_kobj);
3524         if (!sysfs_dev_block_kobj)
3525                 goto block_kobj_err;
3526         sysfs_dev_char_kobj = kobject_create_and_add("char", dev_kobj);
3527         if (!sysfs_dev_char_kobj)
3528                 goto char_kobj_err;
3529
3530         return 0;
3531
3532  char_kobj_err:
3533         kobject_put(sysfs_dev_block_kobj);
3534  block_kobj_err:
3535         kobject_put(dev_kobj);
3536  dev_kobj_err:
3537         kset_unregister(devices_kset);
3538         return -ENOMEM;
3539 }
3540
3541 static int device_check_offline(struct device *dev, void *not_used)
3542 {
3543         int ret;
3544
3545         ret = device_for_each_child(dev, NULL, device_check_offline);
3546         if (ret)
3547                 return ret;
3548
3549         return device_supports_offline(dev) && !dev->offline ? -EBUSY : 0;
3550 }
3551
3552 /**
3553  * device_offline - Prepare the device for hot-removal.
3554  * @dev: Device to be put offline.
3555  *
3556  * Execute the device bus type's .offline() callback, if present, to prepare
3557  * the device for a subsequent hot-removal.  If that succeeds, the device must
3558  * not be used until either it is removed or its bus type's .online() callback
3559  * is executed.
3560  *
3561  * Call under device_hotplug_lock.
3562  */
3563 int device_offline(struct device *dev)
3564 {
3565         int ret;
3566
3567         if (dev->offline_disabled)
3568                 return -EPERM;
3569
3570         ret = device_for_each_child(dev, NULL, device_check_offline);
3571         if (ret)
3572                 return ret;
3573
3574         device_lock(dev);
3575         if (device_supports_offline(dev)) {
3576                 if (dev->offline) {
3577                         ret = 1;
3578                 } else {
3579                         ret = dev->bus->offline(dev);
3580                         if (!ret) {
3581                                 kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
3582                                 dev->offline = true;
3583                         }
3584                 }
3585         }
3586         device_unlock(dev);
3587
3588         return ret;
3589 }
3590
3591 /**
3592  * device_online - Put the device back online after successful device_offline().
3593  * @dev: Device to be put back online.
3594  *
3595  * If device_offline() has been successfully executed for @dev, but the device
3596  * has not been removed subsequently, execute its bus type's .online() callback
3597  * to indicate that the device can be used again.
3598  *
3599  * Call under device_hotplug_lock.
3600  */
3601 int device_online(struct device *dev)
3602 {
3603         int ret = 0;
3604
3605         device_lock(dev);
3606         if (device_supports_offline(dev)) {
3607                 if (dev->offline) {
3608                         ret = dev->bus->online(dev);
3609                         if (!ret) {
3610                                 kobject_uevent(&dev->kobj, KOBJ_ONLINE);
3611                                 dev->offline = false;
3612                         }
3613                 } else {
3614                         ret = 1;
3615                 }
3616         }
3617         device_unlock(dev);
3618
3619         return ret;
3620 }
3621
3622 struct root_device {
3623         struct device dev;
3624         struct module *owner;
3625 };
3626
3627 static inline struct root_device *to_root_device(struct device *d)
3628 {
3629         return container_of(d, struct root_device, dev);
3630 }
3631
3632 static void root_device_release(struct device *dev)
3633 {
3634         kfree(to_root_device(dev));
3635 }
3636
3637 /**
3638  * __root_device_register - allocate and register a root device
3639  * @name: root device name
3640  * @owner: owner module of the root device, usually THIS_MODULE
3641  *
3642  * This function allocates a root device and registers it
3643  * using device_register(). In order to free the returned
3644  * device, use root_device_unregister().
3645  *
3646  * Root devices are dummy devices which allow other devices
3647  * to be grouped under /sys/devices. Use this function to
3648  * allocate a root device and then use it as the parent of
3649  * any device which should appear under /sys/devices/{name}
3650  *
3651  * The /sys/devices/{name} directory will also contain a
3652  * 'module' symlink which points to the @owner directory
3653  * in sysfs.
3654  *
3655  * Returns &struct device pointer on success, or ERR_PTR() on error.
3656  *
3657  * Note: You probably want to use root_device_register().
3658  */
3659 struct device *__root_device_register(const char *name, struct module *owner)
3660 {
3661         struct root_device *root;
3662         int err = -ENOMEM;
3663
3664         root = kzalloc(sizeof(struct root_device), GFP_KERNEL);
3665         if (!root)
3666                 return ERR_PTR(err);
3667
3668         err = dev_set_name(&root->dev, "%s", name);
3669         if (err) {
3670                 kfree(root);
3671                 return ERR_PTR(err);
3672         }
3673
3674         root->dev.release = root_device_release;
3675
3676         err = device_register(&root->dev);
3677         if (err) {
3678                 put_device(&root->dev);
3679                 return ERR_PTR(err);
3680         }
3681
3682 #ifdef CONFIG_MODULES   /* gotta find a "cleaner" way to do this */
3683         if (owner) {
3684                 struct module_kobject *mk = &owner->mkobj;
3685
3686                 err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module");
3687                 if (err) {
3688                         device_unregister(&root->dev);
3689                         return ERR_PTR(err);
3690                 }
3691                 root->owner = owner;
3692         }
3693 #endif
3694
3695         return &root->dev;
3696 }
3697 EXPORT_SYMBOL_GPL(__root_device_register);
3698
3699 /**
3700  * root_device_unregister - unregister and free a root device
3701  * @dev: device going away
3702  *
3703  * This function unregisters and cleans up a device that was created by
3704  * root_device_register().
3705  */
3706 void root_device_unregister(struct device *dev)
3707 {
3708         struct root_device *root = to_root_device(dev);
3709
3710         if (root->owner)
3711                 sysfs_remove_link(&root->dev.kobj, "module");
3712
3713         device_unregister(dev);
3714 }
3715 EXPORT_SYMBOL_GPL(root_device_unregister);
3716
3717
3718 static void device_create_release(struct device *dev)
3719 {
3720         pr_debug("device: '%s': %s\n", dev_name(dev), __func__);
3721         kfree(dev);
3722 }
3723
3724 static __printf(6, 0) struct device *
3725 device_create_groups_vargs(struct class *class, struct device *parent,
3726                            dev_t devt, void *drvdata,
3727                            const struct attribute_group **groups,
3728                            const char *fmt, va_list args)
3729 {
3730         struct device *dev = NULL;
3731         int retval = -ENODEV;
3732
3733         if (class == NULL || IS_ERR(class))
3734                 goto error;
3735
3736         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3737         if (!dev) {
3738                 retval = -ENOMEM;
3739                 goto error;
3740         }
3741
3742         device_initialize(dev);
3743         dev->devt = devt;
3744         dev->class = class;
3745         dev->parent = parent;
3746         dev->groups = groups;
3747         dev->release = device_create_release;
3748         dev_set_drvdata(dev, drvdata);
3749
3750         retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
3751         if (retval)
3752                 goto error;
3753
3754         retval = device_add(dev);
3755         if (retval)
3756                 goto error;
3757
3758         return dev;
3759
3760 error:
3761         put_device(dev);
3762         return ERR_PTR(retval);
3763 }
3764
3765 /**
3766  * device_create - creates a device and registers it with sysfs
3767  * @class: pointer to the struct class that this device should be registered to
3768  * @parent: pointer to the parent struct device of this new device, if any
3769  * @devt: the dev_t for the char device to be added
3770  * @drvdata: the data to be added to the device for callbacks
3771  * @fmt: string for the device's name
3772  *
3773  * This function can be used by char device classes.  A struct device
3774  * will be created in sysfs, registered to the specified class.
3775  *
3776  * A "dev" file will be created, showing the dev_t for the device, if
3777  * the dev_t is not 0,0.
3778  * If a pointer to a parent struct device is passed in, the newly created
3779  * struct device will be a child of that device in sysfs.
3780  * The pointer to the struct device will be returned from the call.
3781  * Any further sysfs files that might be required can be created using this
3782  * pointer.
3783  *
3784  * Returns &struct device pointer on success, or ERR_PTR() on error.
3785  *
3786  * Note: the struct class passed to this function must have previously
3787  * been created with a call to class_create().
3788  */
3789 struct device *device_create(struct class *class, struct device *parent,
3790                              dev_t devt, void *drvdata, const char *fmt, ...)
3791 {
3792         va_list vargs;
3793         struct device *dev;
3794
3795         va_start(vargs, fmt);
3796         dev = device_create_groups_vargs(class, parent, devt, drvdata, NULL,
3797                                           fmt, vargs);
3798         va_end(vargs);
3799         return dev;
3800 }
3801 EXPORT_SYMBOL_GPL(device_create);
3802
3803 /**
3804  * device_create_with_groups - creates a device and registers it with sysfs
3805  * @class: pointer to the struct class that this device should be registered to
3806  * @parent: pointer to the parent struct device of this new device, if any
3807  * @devt: the dev_t for the char device to be added
3808  * @drvdata: the data to be added to the device for callbacks
3809  * @groups: NULL-terminated list of attribute groups to be created
3810  * @fmt: string for the device's name
3811  *
3812  * This function can be used by char device classes.  A struct device
3813  * will be created in sysfs, registered to the specified class.
3814  * Additional attributes specified in the groups parameter will also
3815  * be created automatically.
3816  *
3817  * A "dev" file will be created, showing the dev_t for the device, if
3818  * the dev_t is not 0,0.
3819  * If a pointer to a parent struct device is passed in, the newly created
3820  * struct device will be a child of that device in sysfs.
3821  * The pointer to the struct device will be returned from the call.
3822  * Any further sysfs files that might be required can be created using this
3823  * pointer.
3824  *
3825  * Returns &struct device pointer on success, or ERR_PTR() on error.
3826  *
3827  * Note: the struct class passed to this function must have previously
3828  * been created with a call to class_create().
3829  */
3830 struct device *device_create_with_groups(struct class *class,
3831                                          struct device *parent, dev_t devt,
3832                                          void *drvdata,
3833                                          const struct attribute_group **groups,
3834                                          const char *fmt, ...)
3835 {
3836         va_list vargs;
3837         struct device *dev;
3838
3839         va_start(vargs, fmt);
3840         dev = device_create_groups_vargs(class, parent, devt, drvdata, groups,
3841                                          fmt, vargs);
3842         va_end(vargs);
3843         return dev;
3844 }
3845 EXPORT_SYMBOL_GPL(device_create_with_groups);
3846
3847 /**
3848  * device_destroy - removes a device that was created with device_create()
3849  * @class: pointer to the struct class that this device was registered with
3850  * @devt: the dev_t of the device that was previously registered
3851  *
3852  * This call unregisters and cleans up a device that was created with a
3853  * call to device_create().
3854  */
3855 void device_destroy(struct class *class, dev_t devt)
3856 {
3857         struct device *dev;
3858
3859         dev = class_find_device_by_devt(class, devt);
3860         if (dev) {
3861                 put_device(dev);
3862                 device_unregister(dev);
3863         }
3864 }
3865 EXPORT_SYMBOL_GPL(device_destroy);
3866
3867 /**
3868  * device_rename - renames a device
3869  * @dev: the pointer to the struct device to be renamed
3870  * @new_name: the new name of the device
3871  *
3872  * It is the responsibility of the caller to provide mutual
3873  * exclusion between two different calls of device_rename
3874  * on the same device to ensure that new_name is valid and
3875  * won't conflict with other devices.
3876  *
3877  * Note: Don't call this function.  Currently, the networking layer calls this
3878  * function, but that will change.  The following text from Kay Sievers offers
3879  * some insight:
3880  *
3881  * Renaming devices is racy at many levels, symlinks and other stuff are not
3882  * replaced atomically, and you get a "move" uevent, but it's not easy to
3883  * connect the event to the old and new device. Device nodes are not renamed at
3884  * all, there isn't even support for that in the kernel now.
3885  *
3886  * In the meantime, during renaming, your target name might be taken by another
3887  * driver, creating conflicts. Or the old name is taken directly after you
3888  * renamed it -- then you get events for the same DEVPATH, before you even see
3889  * the "move" event. It's just a mess, and nothing new should ever rely on
3890  * kernel device renaming. Besides that, it's not even implemented now for
3891  * other things than (driver-core wise very simple) network devices.
3892  *
3893  * We are currently about to change network renaming in udev to completely
3894  * disallow renaming of devices in the same namespace as the kernel uses,
3895  * because we can't solve the problems properly, that arise with swapping names
3896  * of multiple interfaces without races. Means, renaming of eth[0-9]* will only
3897  * be allowed to some other name than eth[0-9]*, for the aforementioned
3898  * reasons.
3899  *
3900  * Make up a "real" name in the driver before you register anything, or add
3901  * some other attributes for userspace to find the device, or use udev to add
3902  * symlinks -- but never rename kernel devices later, it's a complete mess. We
3903  * don't even want to get into that and try to implement the missing pieces in
3904  * the core. We really have other pieces to fix in the driver core mess. :)
3905  */
3906 int device_rename(struct device *dev, const char *new_name)
3907 {
3908         struct kobject *kobj = &dev->kobj;
3909         char *old_device_name = NULL;
3910         int error;
3911
3912         dev = get_device(dev);
3913         if (!dev)
3914                 return -EINVAL;
3915
3916         dev_dbg(dev, "renaming to %s\n", new_name);
3917
3918         old_device_name = kstrdup(dev_name(dev), GFP_KERNEL);
3919         if (!old_device_name) {
3920                 error = -ENOMEM;
3921                 goto out;
3922         }
3923
3924         if (dev->class) {
3925                 error = sysfs_rename_link_ns(&dev->class->p->subsys.kobj,
3926                                              kobj, old_device_name,
3927                                              new_name, kobject_namespace(kobj));
3928                 if (error)
3929                         goto out;
3930         }
3931
3932         error = kobject_rename(kobj, new_name);
3933         if (error)
3934                 goto out;
3935
3936 out:
3937         put_device(dev);
3938
3939         kfree(old_device_name);
3940
3941         return error;
3942 }
3943 EXPORT_SYMBOL_GPL(device_rename);
3944
3945 static int device_move_class_links(struct device *dev,
3946                                    struct device *old_parent,
3947                                    struct device *new_parent)
3948 {
3949         int error = 0;
3950
3951         if (old_parent)
3952                 sysfs_remove_link(&dev->kobj, "device");
3953         if (new_parent)
3954                 error = sysfs_create_link(&dev->kobj, &new_parent->kobj,
3955                                           "device");
3956         return error;
3957 }
3958
3959 /**
3960  * device_move - moves a device to a new parent
3961  * @dev: the pointer to the struct device to be moved
3962  * @new_parent: the new parent of the device (can be NULL)
3963  * @dpm_order: how to reorder the dpm_list
3964  */
3965 int device_move(struct device *dev, struct device *new_parent,
3966                 enum dpm_order dpm_order)
3967 {
3968         int error;
3969         struct device *old_parent;
3970         struct kobject *new_parent_kobj;
3971
3972         dev = get_device(dev);
3973         if (!dev)
3974                 return -EINVAL;
3975
3976         device_pm_lock();
3977         new_parent = get_device(new_parent);
3978         new_parent_kobj = get_device_parent(dev, new_parent);
3979         if (IS_ERR(new_parent_kobj)) {
3980                 error = PTR_ERR(new_parent_kobj);
3981                 put_device(new_parent);
3982                 goto out;
3983         }
3984
3985         pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev),
3986                  __func__, new_parent ? dev_name(new_parent) : "<NULL>");
3987         error = kobject_move(&dev->kobj, new_parent_kobj);
3988         if (error) {
3989                 cleanup_glue_dir(dev, new_parent_kobj);
3990                 put_device(new_parent);
3991                 goto out;
3992         }
3993         old_parent = dev->parent;
3994         dev->parent = new_parent;
3995         if (old_parent)
3996                 klist_remove(&dev->p->knode_parent);
3997         if (new_parent) {
3998                 klist_add_tail(&dev->p->knode_parent,
3999                                &new_parent->p->klist_children);
4000                 set_dev_node(dev, dev_to_node(new_parent));
4001         }
4002
4003         if (dev->class) {
4004                 error = device_move_class_links(dev, old_parent, new_parent);
4005                 if (error) {
4006                         /* We ignore errors on cleanup since we're hosed anyway... */
4007                         device_move_class_links(dev, new_parent, old_parent);
4008                         if (!kobject_move(&dev->kobj, &old_parent->kobj)) {
4009                                 if (new_parent)
4010                                         klist_remove(&dev->p->knode_parent);
4011                                 dev->parent = old_parent;
4012                                 if (old_parent) {
4013                                         klist_add_tail(&dev->p->knode_parent,
4014                                                        &old_parent->p->klist_children);
4015                                         set_dev_node(dev, dev_to_node(old_parent));
4016                                 }
4017                         }
4018                         cleanup_glue_dir(dev, new_parent_kobj);
4019                         put_device(new_parent);
4020                         goto out;
4021                 }
4022         }
4023         switch (dpm_order) {
4024         case DPM_ORDER_NONE:
4025                 break;
4026         case DPM_ORDER_DEV_AFTER_PARENT:
4027                 device_pm_move_after(dev, new_parent);
4028                 devices_kset_move_after(dev, new_parent);
4029                 break;
4030         case DPM_ORDER_PARENT_BEFORE_DEV:
4031                 device_pm_move_before(new_parent, dev);
4032                 devices_kset_move_before(new_parent, dev);
4033                 break;
4034         case DPM_ORDER_DEV_LAST:
4035                 device_pm_move_last(dev);
4036                 devices_kset_move_last(dev);
4037                 break;
4038         }
4039
4040         put_device(old_parent);
4041 out:
4042         device_pm_unlock();
4043         put_device(dev);
4044         return error;
4045 }
4046 EXPORT_SYMBOL_GPL(device_move);
4047
4048 static int device_attrs_change_owner(struct device *dev, kuid_t kuid,
4049                                      kgid_t kgid)
4050 {
4051         struct kobject *kobj = &dev->kobj;
4052         struct class *class = dev->class;
4053         const struct device_type *type = dev->type;
4054         int error;
4055
4056         if (class) {
4057                 /*
4058                  * Change the device groups of the device class for @dev to
4059                  * @kuid/@kgid.
4060                  */
4061                 error = sysfs_groups_change_owner(kobj, class->dev_groups, kuid,
4062                                                   kgid);
4063                 if (error)
4064                         return error;
4065         }
4066
4067         if (type) {
4068                 /*
4069                  * Change the device groups of the device type for @dev to
4070                  * @kuid/@kgid.
4071                  */
4072                 error = sysfs_groups_change_owner(kobj, type->groups, kuid,
4073                                                   kgid);
4074                 if (error)
4075                         return error;
4076         }
4077
4078         /* Change the device groups of @dev to @kuid/@kgid. */
4079         error = sysfs_groups_change_owner(kobj, dev->groups, kuid, kgid);
4080         if (error)
4081                 return error;
4082
4083         if (device_supports_offline(dev) && !dev->offline_disabled) {
4084                 /* Change online device attributes of @dev to @kuid/@kgid. */
4085                 error = sysfs_file_change_owner(kobj, dev_attr_online.attr.name,
4086                                                 kuid, kgid);
4087                 if (error)
4088                         return error;
4089         }
4090
4091         return 0;
4092 }
4093
4094 /**
4095  * device_change_owner - change the owner of an existing device.
4096  * @dev: device.
4097  * @kuid: new owner's kuid
4098  * @kgid: new owner's kgid
4099  *
4100  * This changes the owner of @dev and its corresponding sysfs entries to
4101  * @kuid/@kgid. This function closely mirrors how @dev was added via driver
4102  * core.
4103  *
4104  * Returns 0 on success or error code on failure.
4105  */
4106 int device_change_owner(struct device *dev, kuid_t kuid, kgid_t kgid)
4107 {
4108         int error;
4109         struct kobject *kobj = &dev->kobj;
4110
4111         dev = get_device(dev);
4112         if (!dev)
4113                 return -EINVAL;
4114
4115         /*
4116          * Change the kobject and the default attributes and groups of the
4117          * ktype associated with it to @kuid/@kgid.
4118          */
4119         error = sysfs_change_owner(kobj, kuid, kgid);
4120         if (error)
4121                 goto out;
4122
4123         /*
4124          * Change the uevent file for @dev to the new owner. The uevent file
4125          * was created in a separate step when @dev got added and we mirror
4126          * that step here.
4127          */
4128         error = sysfs_file_change_owner(kobj, dev_attr_uevent.attr.name, kuid,
4129                                         kgid);
4130         if (error)
4131                 goto out;
4132
4133         /*
4134          * Change the device groups, the device groups associated with the
4135          * device class, and the groups associated with the device type of @dev
4136          * to @kuid/@kgid.
4137          */
4138         error = device_attrs_change_owner(dev, kuid, kgid);
4139         if (error)
4140                 goto out;
4141
4142         error = dpm_sysfs_change_owner(dev, kuid, kgid);
4143         if (error)
4144                 goto out;
4145
4146 #ifdef CONFIG_BLOCK
4147         if (sysfs_deprecated && dev->class == &block_class)
4148                 goto out;
4149 #endif
4150
4151         /*
4152          * Change the owner of the symlink located in the class directory of
4153          * the device class associated with @dev which points to the actual
4154          * directory entry for @dev to @kuid/@kgid. This ensures that the
4155          * symlink shows the same permissions as its target.
4156          */
4157         error = sysfs_link_change_owner(&dev->class->p->subsys.kobj, &dev->kobj,
4158                                         dev_name(dev), kuid, kgid);
4159         if (error)
4160                 goto out;
4161
4162 out:
4163         put_device(dev);
4164         return error;
4165 }
4166 EXPORT_SYMBOL_GPL(device_change_owner);
4167
4168 /**
4169  * device_shutdown - call ->shutdown() on each device to shutdown.
4170  */
4171 void device_shutdown(void)
4172 {
4173         struct device *dev, *parent;
4174
4175         wait_for_device_probe();
4176         device_block_probing();
4177
4178         cpufreq_suspend();
4179
4180         spin_lock(&devices_kset->list_lock);
4181         /*
4182          * Walk the devices list backward, shutting down each in turn.
4183          * Beware that device unplug events may also start pulling
4184          * devices offline, even as the system is shutting down.
4185          */
4186         while (!list_empty(&devices_kset->list)) {
4187                 dev = list_entry(devices_kset->list.prev, struct device,
4188                                 kobj.entry);
4189
4190                 /*
4191                  * hold reference count of device's parent to
4192                  * prevent it from being freed because parent's
4193                  * lock is to be held
4194                  */
4195                 parent = get_device(dev->parent);
4196                 get_device(dev);
4197                 /*
4198                  * Make sure the device is off the kset list, in the
4199                  * event that dev->*->shutdown() doesn't remove it.
4200                  */
4201                 list_del_init(&dev->kobj.entry);
4202                 spin_unlock(&devices_kset->list_lock);
4203
4204                 /* hold lock to avoid race with probe/release */
4205                 if (parent)
4206                         device_lock(parent);
4207                 device_lock(dev);
4208
4209                 /* Don't allow any more runtime suspends */
4210                 pm_runtime_get_noresume(dev);
4211                 pm_runtime_barrier(dev);
4212
4213                 if (dev->class && dev->class->shutdown_pre) {
4214                         if (initcall_debug)
4215                                 dev_info(dev, "shutdown_pre\n");
4216                         dev->class->shutdown_pre(dev);
4217                 }
4218                 if (dev->bus && dev->bus->shutdown) {
4219                         if (initcall_debug)
4220                                 dev_info(dev, "shutdown\n");
4221                         dev->bus->shutdown(dev);
4222                 } else if (dev->driver && dev->driver->shutdown) {
4223                         if (initcall_debug)
4224                                 dev_info(dev, "shutdown\n");
4225                         dev->driver->shutdown(dev);
4226                 }
4227
4228                 device_unlock(dev);
4229                 if (parent)
4230                         device_unlock(parent);
4231
4232                 put_device(dev);
4233                 put_device(parent);
4234
4235                 spin_lock(&devices_kset->list_lock);
4236         }
4237         spin_unlock(&devices_kset->list_lock);
4238 }
4239
4240 /*
4241  * Device logging functions
4242  */
4243
4244 #ifdef CONFIG_PRINTK
4245 static void
4246 set_dev_info(const struct device *dev, struct dev_printk_info *dev_info)
4247 {
4248         const char *subsys;
4249
4250         memset(dev_info, 0, sizeof(*dev_info));
4251
4252         if (dev->class)
4253                 subsys = dev->class->name;
4254         else if (dev->bus)
4255                 subsys = dev->bus->name;
4256         else
4257                 return;
4258
4259         strscpy(dev_info->subsystem, subsys, sizeof(dev_info->subsystem));
4260
4261         /*
4262          * Add device identifier DEVICE=:
4263          *   b12:8         block dev_t
4264          *   c127:3        char dev_t
4265          *   n8            netdev ifindex
4266          *   +sound:card0  subsystem:devname
4267          */
4268         if (MAJOR(dev->devt)) {
4269                 char c;
4270
4271                 if (strcmp(subsys, "block") == 0)
4272                         c = 'b';
4273                 else
4274                         c = 'c';
4275
4276                 snprintf(dev_info->device, sizeof(dev_info->device),
4277                          "%c%u:%u", c, MAJOR(dev->devt), MINOR(dev->devt));
4278         } else if (strcmp(subsys, "net") == 0) {
4279                 struct net_device *net = to_net_dev(dev);
4280
4281                 snprintf(dev_info->device, sizeof(dev_info->device),
4282                          "n%u", net->ifindex);
4283         } else {
4284                 snprintf(dev_info->device, sizeof(dev_info->device),
4285                          "+%s:%s", subsys, dev_name(dev));
4286         }
4287 }
4288
4289 int dev_vprintk_emit(int level, const struct device *dev,
4290                      const char *fmt, va_list args)
4291 {
4292         struct dev_printk_info dev_info;
4293
4294         set_dev_info(dev, &dev_info);
4295
4296         return vprintk_emit(0, level, &dev_info, fmt, args);
4297 }
4298 EXPORT_SYMBOL(dev_vprintk_emit);
4299
4300 int dev_printk_emit(int level, const struct device *dev, const char *fmt, ...)
4301 {
4302         va_list args;
4303         int r;
4304
4305         va_start(args, fmt);
4306
4307         r = dev_vprintk_emit(level, dev, fmt, args);
4308
4309         va_end(args);
4310
4311         return r;
4312 }
4313 EXPORT_SYMBOL(dev_printk_emit);
4314
4315 static void __dev_printk(const char *level, const struct device *dev,
4316                         struct va_format *vaf)
4317 {
4318         if (dev)
4319                 dev_printk_emit(level[1] - '0', dev, "%s %s: %pV",
4320                                 dev_driver_string(dev), dev_name(dev), vaf);
4321         else
4322                 printk("%s(NULL device *): %pV", level, vaf);
4323 }
4324
4325 void dev_printk(const char *level, const struct device *dev,
4326                 const char *fmt, ...)
4327 {
4328         struct va_format vaf;
4329         va_list args;
4330
4331         va_start(args, fmt);
4332
4333         vaf.fmt = fmt;
4334         vaf.va = &args;
4335
4336         __dev_printk(level, dev, &vaf);
4337
4338         va_end(args);
4339 }
4340 EXPORT_SYMBOL(dev_printk);
4341
4342 #define define_dev_printk_level(func, kern_level)               \
4343 void func(const struct device *dev, const char *fmt, ...)       \
4344 {                                                               \
4345         struct va_format vaf;                                   \
4346         va_list args;                                           \
4347                                                                 \
4348         va_start(args, fmt);                                    \
4349                                                                 \
4350         vaf.fmt = fmt;                                          \
4351         vaf.va = &args;                                         \
4352                                                                 \
4353         __dev_printk(kern_level, dev, &vaf);                    \
4354                                                                 \
4355         va_end(args);                                           \
4356 }                                                               \
4357 EXPORT_SYMBOL(func);
4358
4359 define_dev_printk_level(_dev_emerg, KERN_EMERG);
4360 define_dev_printk_level(_dev_alert, KERN_ALERT);
4361 define_dev_printk_level(_dev_crit, KERN_CRIT);
4362 define_dev_printk_level(_dev_err, KERN_ERR);
4363 define_dev_printk_level(_dev_warn, KERN_WARNING);
4364 define_dev_printk_level(_dev_notice, KERN_NOTICE);
4365 define_dev_printk_level(_dev_info, KERN_INFO);
4366
4367 #endif
4368
4369 /**
4370  * dev_err_probe - probe error check and log helper
4371  * @dev: the pointer to the struct device
4372  * @err: error value to test
4373  * @fmt: printf-style format string
4374  * @...: arguments as specified in the format string
4375  *
4376  * This helper implements common pattern present in probe functions for error
4377  * checking: print debug or error message depending if the error value is
4378  * -EPROBE_DEFER and propagate error upwards.
4379  * In case of -EPROBE_DEFER it sets also defer probe reason, which can be
4380  * checked later by reading devices_deferred debugfs attribute.
4381  * It replaces code sequence::
4382  *
4383  *      if (err != -EPROBE_DEFER)
4384  *              dev_err(dev, ...);
4385  *      else
4386  *              dev_dbg(dev, ...);
4387  *      return err;
4388  *
4389  * with::
4390  *
4391  *      return dev_err_probe(dev, err, ...);
4392  *
4393  * Returns @err.
4394  *
4395  */
4396 int dev_err_probe(const struct device *dev, int err, const char *fmt, ...)
4397 {
4398         struct va_format vaf;
4399         va_list args;
4400
4401         va_start(args, fmt);
4402         vaf.fmt = fmt;
4403         vaf.va = &args;
4404
4405         if (err != -EPROBE_DEFER) {
4406                 dev_err(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
4407         } else {
4408                 device_set_deferred_probe_reason(dev, &vaf);
4409                 dev_dbg(dev, "error %pe: %pV", ERR_PTR(err), &vaf);
4410         }
4411
4412         va_end(args);
4413
4414         return err;
4415 }
4416 EXPORT_SYMBOL_GPL(dev_err_probe);
4417
4418 static inline bool fwnode_is_primary(struct fwnode_handle *fwnode)
4419 {
4420         return fwnode && !IS_ERR(fwnode->secondary);
4421 }
4422
4423 /**
4424  * set_primary_fwnode - Change the primary firmware node of a given device.
4425  * @dev: Device to handle.
4426  * @fwnode: New primary firmware node of the device.
4427  *
4428  * Set the device's firmware node pointer to @fwnode, but if a secondary
4429  * firmware node of the device is present, preserve it.
4430  */
4431 void set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
4432 {
4433         struct device *parent = dev->parent;
4434         struct fwnode_handle *fn = dev->fwnode;
4435
4436         if (fwnode) {
4437                 if (fwnode_is_primary(fn))
4438                         fn = fn->secondary;
4439
4440                 if (fn) {
4441                         WARN_ON(fwnode->secondary);
4442                         fwnode->secondary = fn;
4443                 }
4444                 dev->fwnode = fwnode;
4445         } else {
4446                 if (fwnode_is_primary(fn)) {
4447                         dev->fwnode = fn->secondary;
4448                         if (!(parent && fn == parent->fwnode))
4449                                 fn->secondary = ERR_PTR(-ENODEV);
4450                 } else {
4451                         dev->fwnode = NULL;
4452                 }
4453         }
4454 }
4455 EXPORT_SYMBOL_GPL(set_primary_fwnode);
4456
4457 /**
4458  * set_secondary_fwnode - Change the secondary firmware node of a given device.
4459  * @dev: Device to handle.
4460  * @fwnode: New secondary firmware node of the device.
4461  *
4462  * If a primary firmware node of the device is present, set its secondary
4463  * pointer to @fwnode.  Otherwise, set the device's firmware node pointer to
4464  * @fwnode.
4465  */
4466 void set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode)
4467 {
4468         if (fwnode)
4469                 fwnode->secondary = ERR_PTR(-ENODEV);
4470
4471         if (fwnode_is_primary(dev->fwnode))
4472                 dev->fwnode->secondary = fwnode;
4473         else
4474                 dev->fwnode = fwnode;
4475 }
4476 EXPORT_SYMBOL_GPL(set_secondary_fwnode);
4477
4478 /**
4479  * device_set_of_node_from_dev - reuse device-tree node of another device
4480  * @dev: device whose device-tree node is being set
4481  * @dev2: device whose device-tree node is being reused
4482  *
4483  * Takes another reference to the new device-tree node after first dropping
4484  * any reference held to the old node.
4485  */
4486 void device_set_of_node_from_dev(struct device *dev, const struct device *dev2)
4487 {
4488         of_node_put(dev->of_node);
4489         dev->of_node = of_node_get(dev2->of_node);
4490         dev->of_node_reused = true;
4491 }
4492 EXPORT_SYMBOL_GPL(device_set_of_node_from_dev);
4493
4494 int device_match_name(struct device *dev, const void *name)
4495 {
4496         return sysfs_streq(dev_name(dev), name);
4497 }
4498 EXPORT_SYMBOL_GPL(device_match_name);
4499
4500 int device_match_of_node(struct device *dev, const void *np)
4501 {
4502         return dev->of_node == np;
4503 }
4504 EXPORT_SYMBOL_GPL(device_match_of_node);
4505
4506 int device_match_fwnode(struct device *dev, const void *fwnode)
4507 {
4508         return dev_fwnode(dev) == fwnode;
4509 }
4510 EXPORT_SYMBOL_GPL(device_match_fwnode);
4511
4512 int device_match_devt(struct device *dev, const void *pdevt)
4513 {
4514         return dev->devt == *(dev_t *)pdevt;
4515 }
4516 EXPORT_SYMBOL_GPL(device_match_devt);
4517
4518 int device_match_acpi_dev(struct device *dev, const void *adev)
4519 {
4520         return ACPI_COMPANION(dev) == adev;
4521 }
4522 EXPORT_SYMBOL(device_match_acpi_dev);
4523
4524 int device_match_any(struct device *dev, const void *unused)
4525 {
4526         return 1;
4527 }
4528 EXPORT_SYMBOL_GPL(device_match_any);