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