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