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