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