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