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