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