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