OSDN Git Service

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