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