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