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