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