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