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