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