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