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