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