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