Merge branch 'pm-core'
[linux-drm-fsl-dcu.git] / drivers / base / power / domain.c
1 /*
2  * drivers/base/power/domain.c - Common code related to device power domains.
3  *
4  * Copyright (C) 2011 Rafael J. Wysocki <rjw@sisk.pl>, Renesas Electronics Corp.
5  *
6  * This file is released under the GPLv2.
7  */
8
9 #include <linux/delay.h>
10 #include <linux/kernel.h>
11 #include <linux/io.h>
12 #include <linux/platform_device.h>
13 #include <linux/pm_runtime.h>
14 #include <linux/pm_domain.h>
15 #include <linux/pm_qos.h>
16 #include <linux/pm_clock.h>
17 #include <linux/slab.h>
18 #include <linux/err.h>
19 #include <linux/sched.h>
20 #include <linux/suspend.h>
21 #include <linux/export.h>
22
23 #include "power.h"
24
25 #define GENPD_RETRY_MAX_MS      250             /* Approximate */
26
27 #define GENPD_DEV_CALLBACK(genpd, type, callback, dev)          \
28 ({                                                              \
29         type (*__routine)(struct device *__d);                  \
30         type __ret = (type)0;                                   \
31                                                                 \
32         __routine = genpd->dev_ops.callback;                    \
33         if (__routine) {                                        \
34                 __ret = __routine(dev);                         \
35         }                                                       \
36         __ret;                                                  \
37 })
38
39 static LIST_HEAD(gpd_list);
40 static DEFINE_MUTEX(gpd_list_lock);
41
42 /*
43  * Get the generic PM domain for a particular struct device.
44  * This validates the struct device pointer, the PM domain pointer,
45  * and checks that the PM domain pointer is a real generic PM domain.
46  * Any failure results in NULL being returned.
47  */
48 struct generic_pm_domain *pm_genpd_lookup_dev(struct device *dev)
49 {
50         struct generic_pm_domain *genpd = NULL, *gpd;
51
52         if (IS_ERR_OR_NULL(dev) || IS_ERR_OR_NULL(dev->pm_domain))
53                 return NULL;
54
55         mutex_lock(&gpd_list_lock);
56         list_for_each_entry(gpd, &gpd_list, gpd_list_node) {
57                 if (&gpd->domain == dev->pm_domain) {
58                         genpd = gpd;
59                         break;
60                 }
61         }
62         mutex_unlock(&gpd_list_lock);
63
64         return genpd;
65 }
66
67 /*
68  * This should only be used where we are certain that the pm_domain
69  * attached to the device is a genpd domain.
70  */
71 static struct generic_pm_domain *dev_to_genpd(struct device *dev)
72 {
73         if (IS_ERR_OR_NULL(dev->pm_domain))
74                 return ERR_PTR(-EINVAL);
75
76         return pd_to_genpd(dev->pm_domain);
77 }
78
79 static int genpd_stop_dev(struct generic_pm_domain *genpd, struct device *dev)
80 {
81         return GENPD_DEV_CALLBACK(genpd, int, stop, dev);
82 }
83
84 static int genpd_start_dev(struct generic_pm_domain *genpd, struct device *dev)
85 {
86         return GENPD_DEV_CALLBACK(genpd, int, start, dev);
87 }
88
89 static bool genpd_sd_counter_dec(struct generic_pm_domain *genpd)
90 {
91         bool ret = false;
92
93         if (!WARN_ON(atomic_read(&genpd->sd_count) == 0))
94                 ret = !!atomic_dec_and_test(&genpd->sd_count);
95
96         return ret;
97 }
98
99 static void genpd_sd_counter_inc(struct generic_pm_domain *genpd)
100 {
101         atomic_inc(&genpd->sd_count);
102         smp_mb__after_atomic();
103 }
104
105 static int genpd_power_on(struct generic_pm_domain *genpd, bool timed)
106 {
107         ktime_t time_start;
108         s64 elapsed_ns;
109         int ret;
110
111         if (!genpd->power_on)
112                 return 0;
113
114         if (!timed)
115                 return genpd->power_on(genpd);
116
117         time_start = ktime_get();
118         ret = genpd->power_on(genpd);
119         if (ret)
120                 return ret;
121
122         elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
123         if (elapsed_ns <= genpd->power_on_latency_ns)
124                 return ret;
125
126         genpd->power_on_latency_ns = elapsed_ns;
127         genpd->max_off_time_changed = true;
128         pr_debug("%s: Power-%s latency exceeded, new value %lld ns\n",
129                  genpd->name, "on", elapsed_ns);
130
131         return ret;
132 }
133
134 static int genpd_power_off(struct generic_pm_domain *genpd, bool timed)
135 {
136         ktime_t time_start;
137         s64 elapsed_ns;
138         int ret;
139
140         if (!genpd->power_off)
141                 return 0;
142
143         if (!timed)
144                 return genpd->power_off(genpd);
145
146         time_start = ktime_get();
147         ret = genpd->power_off(genpd);
148         if (ret == -EBUSY)
149                 return ret;
150
151         elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
152         if (elapsed_ns <= genpd->power_off_latency_ns)
153                 return ret;
154
155         genpd->power_off_latency_ns = elapsed_ns;
156         genpd->max_off_time_changed = true;
157         pr_debug("%s: Power-%s latency exceeded, new value %lld ns\n",
158                  genpd->name, "off", elapsed_ns);
159
160         return ret;
161 }
162
163 /**
164  * genpd_queue_power_off_work - Queue up the execution of genpd_poweroff().
165  * @genpd: PM domait to power off.
166  *
167  * Queue up the execution of genpd_poweroff() unless it's already been done
168  * before.
169  */
170 static void genpd_queue_power_off_work(struct generic_pm_domain *genpd)
171 {
172         queue_work(pm_wq, &genpd->power_off_work);
173 }
174
175 static int genpd_poweron(struct generic_pm_domain *genpd);
176
177 /**
178  * __genpd_poweron - Restore power to a given PM domain and its masters.
179  * @genpd: PM domain to power up.
180  *
181  * Restore power to @genpd and all of its masters so that it is possible to
182  * resume a device belonging to it.
183  */
184 static int __genpd_poweron(struct generic_pm_domain *genpd)
185 {
186         struct gpd_link *link;
187         int ret = 0;
188
189         if (genpd->status == GPD_STATE_ACTIVE
190             || (genpd->prepared_count > 0 && genpd->suspend_power_off))
191                 return 0;
192
193         /*
194          * The list is guaranteed not to change while the loop below is being
195          * executed, unless one of the masters' .power_on() callbacks fiddles
196          * with it.
197          */
198         list_for_each_entry(link, &genpd->slave_links, slave_node) {
199                 genpd_sd_counter_inc(link->master);
200
201                 ret = genpd_poweron(link->master);
202                 if (ret) {
203                         genpd_sd_counter_dec(link->master);
204                         goto err;
205                 }
206         }
207
208         ret = genpd_power_on(genpd, true);
209         if (ret)
210                 goto err;
211
212         genpd->status = GPD_STATE_ACTIVE;
213         return 0;
214
215  err:
216         list_for_each_entry_continue_reverse(link,
217                                         &genpd->slave_links,
218                                         slave_node) {
219                 genpd_sd_counter_dec(link->master);
220                 genpd_queue_power_off_work(link->master);
221         }
222
223         return ret;
224 }
225
226 /**
227  * genpd_poweron - Restore power to a given PM domain and its masters.
228  * @genpd: PM domain to power up.
229  */
230 static int genpd_poweron(struct generic_pm_domain *genpd)
231 {
232         int ret;
233
234         mutex_lock(&genpd->lock);
235         ret = __genpd_poweron(genpd);
236         mutex_unlock(&genpd->lock);
237         return ret;
238 }
239
240 static int genpd_save_dev(struct generic_pm_domain *genpd, struct device *dev)
241 {
242         return GENPD_DEV_CALLBACK(genpd, int, save_state, dev);
243 }
244
245 static int genpd_restore_dev(struct generic_pm_domain *genpd,
246                         struct device *dev)
247 {
248         return GENPD_DEV_CALLBACK(genpd, int, restore_state, dev);
249 }
250
251 static int genpd_dev_pm_qos_notifier(struct notifier_block *nb,
252                                      unsigned long val, void *ptr)
253 {
254         struct generic_pm_domain_data *gpd_data;
255         struct device *dev;
256
257         gpd_data = container_of(nb, struct generic_pm_domain_data, nb);
258         dev = gpd_data->base.dev;
259
260         for (;;) {
261                 struct generic_pm_domain *genpd;
262                 struct pm_domain_data *pdd;
263
264                 spin_lock_irq(&dev->power.lock);
265
266                 pdd = dev->power.subsys_data ?
267                                 dev->power.subsys_data->domain_data : NULL;
268                 if (pdd && pdd->dev) {
269                         to_gpd_data(pdd)->td.constraint_changed = true;
270                         genpd = dev_to_genpd(dev);
271                 } else {
272                         genpd = ERR_PTR(-ENODATA);
273                 }
274
275                 spin_unlock_irq(&dev->power.lock);
276
277                 if (!IS_ERR(genpd)) {
278                         mutex_lock(&genpd->lock);
279                         genpd->max_off_time_changed = true;
280                         mutex_unlock(&genpd->lock);
281                 }
282
283                 dev = dev->parent;
284                 if (!dev || dev->power.ignore_children)
285                         break;
286         }
287
288         return NOTIFY_DONE;
289 }
290
291 /**
292  * genpd_poweroff - Remove power from a given PM domain.
293  * @genpd: PM domain to power down.
294  * @is_async: PM domain is powered down from a scheduled work
295  *
296  * If all of the @genpd's devices have been suspended and all of its subdomains
297  * have been powered down, remove power from @genpd.
298  */
299 static int genpd_poweroff(struct generic_pm_domain *genpd, bool is_async)
300 {
301         struct pm_domain_data *pdd;
302         struct gpd_link *link;
303         unsigned int not_suspended = 0;
304
305         /*
306          * Do not try to power off the domain in the following situations:
307          * (1) The domain is already in the "power off" state.
308          * (2) System suspend is in progress.
309          */
310         if (genpd->status == GPD_STATE_POWER_OFF
311             || genpd->prepared_count > 0)
312                 return 0;
313
314         if (atomic_read(&genpd->sd_count) > 0)
315                 return -EBUSY;
316
317         list_for_each_entry(pdd, &genpd->dev_list, list_node) {
318                 enum pm_qos_flags_status stat;
319
320                 stat = dev_pm_qos_flags(pdd->dev,
321                                         PM_QOS_FLAG_NO_POWER_OFF
322                                                 | PM_QOS_FLAG_REMOTE_WAKEUP);
323                 if (stat > PM_QOS_FLAGS_NONE)
324                         return -EBUSY;
325
326                 if (!pm_runtime_suspended(pdd->dev) || pdd->dev->power.irq_safe)
327                         not_suspended++;
328         }
329
330         if (not_suspended > 1 || (not_suspended == 1 && is_async))
331                 return -EBUSY;
332
333         if (genpd->gov && genpd->gov->power_down_ok) {
334                 if (!genpd->gov->power_down_ok(&genpd->domain))
335                         return -EAGAIN;
336         }
337
338         if (genpd->power_off) {
339                 int ret;
340
341                 if (atomic_read(&genpd->sd_count) > 0)
342                         return -EBUSY;
343
344                 /*
345                  * If sd_count > 0 at this point, one of the subdomains hasn't
346                  * managed to call genpd_poweron() for the master yet after
347                  * incrementing it.  In that case genpd_poweron() will wait
348                  * for us to drop the lock, so we can call .power_off() and let
349                  * the genpd_poweron() restore power for us (this shouldn't
350                  * happen very often).
351                  */
352                 ret = genpd_power_off(genpd, true);
353                 if (ret)
354                         return ret;
355         }
356
357         genpd->status = GPD_STATE_POWER_OFF;
358
359         list_for_each_entry(link, &genpd->slave_links, slave_node) {
360                 genpd_sd_counter_dec(link->master);
361                 genpd_queue_power_off_work(link->master);
362         }
363
364         return 0;
365 }
366
367 /**
368  * genpd_power_off_work_fn - Power off PM domain whose subdomain count is 0.
369  * @work: Work structure used for scheduling the execution of this function.
370  */
371 static void genpd_power_off_work_fn(struct work_struct *work)
372 {
373         struct generic_pm_domain *genpd;
374
375         genpd = container_of(work, struct generic_pm_domain, power_off_work);
376
377         mutex_lock(&genpd->lock);
378         genpd_poweroff(genpd, true);
379         mutex_unlock(&genpd->lock);
380 }
381
382 /**
383  * pm_genpd_runtime_suspend - Suspend a device belonging to I/O PM domain.
384  * @dev: Device to suspend.
385  *
386  * Carry out a runtime suspend of a device under the assumption that its
387  * pm_domain field points to the domain member of an object of type
388  * struct generic_pm_domain representing a PM domain consisting of I/O devices.
389  */
390 static int pm_genpd_runtime_suspend(struct device *dev)
391 {
392         struct generic_pm_domain *genpd;
393         bool (*stop_ok)(struct device *__dev);
394         struct gpd_timing_data *td = &dev_gpd_data(dev)->td;
395         bool runtime_pm = pm_runtime_enabled(dev);
396         ktime_t time_start;
397         s64 elapsed_ns;
398         int ret;
399
400         dev_dbg(dev, "%s()\n", __func__);
401
402         genpd = dev_to_genpd(dev);
403         if (IS_ERR(genpd))
404                 return -EINVAL;
405
406         /*
407          * A runtime PM centric subsystem/driver may re-use the runtime PM
408          * callbacks for other purposes than runtime PM. In those scenarios
409          * runtime PM is disabled. Under these circumstances, we shall skip
410          * validating/measuring the PM QoS latency.
411          */
412         stop_ok = genpd->gov ? genpd->gov->stop_ok : NULL;
413         if (runtime_pm && stop_ok && !stop_ok(dev))
414                 return -EBUSY;
415
416         /* Measure suspend latency. */
417         if (runtime_pm)
418                 time_start = ktime_get();
419
420         ret = genpd_save_dev(genpd, dev);
421         if (ret)
422                 return ret;
423
424         ret = genpd_stop_dev(genpd, dev);
425         if (ret) {
426                 genpd_restore_dev(genpd, dev);
427                 return ret;
428         }
429
430         /* Update suspend latency value if the measured time exceeds it. */
431         if (runtime_pm) {
432                 elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
433                 if (elapsed_ns > td->suspend_latency_ns) {
434                         td->suspend_latency_ns = elapsed_ns;
435                         dev_dbg(dev, "suspend latency exceeded, %lld ns\n",
436                                 elapsed_ns);
437                         genpd->max_off_time_changed = true;
438                         td->constraint_changed = true;
439                 }
440         }
441
442         /*
443          * If power.irq_safe is set, this routine will be run with interrupts
444          * off, so it can't use mutexes.
445          */
446         if (dev->power.irq_safe)
447                 return 0;
448
449         mutex_lock(&genpd->lock);
450         genpd_poweroff(genpd, false);
451         mutex_unlock(&genpd->lock);
452
453         return 0;
454 }
455
456 /**
457  * pm_genpd_runtime_resume - Resume a device belonging to I/O PM domain.
458  * @dev: Device to resume.
459  *
460  * Carry out a runtime resume of a device under the assumption that its
461  * pm_domain field points to the domain member of an object of type
462  * struct generic_pm_domain representing a PM domain consisting of I/O devices.
463  */
464 static int pm_genpd_runtime_resume(struct device *dev)
465 {
466         struct generic_pm_domain *genpd;
467         struct gpd_timing_data *td = &dev_gpd_data(dev)->td;
468         bool runtime_pm = pm_runtime_enabled(dev);
469         ktime_t time_start;
470         s64 elapsed_ns;
471         int ret;
472         bool timed = true;
473
474         dev_dbg(dev, "%s()\n", __func__);
475
476         genpd = dev_to_genpd(dev);
477         if (IS_ERR(genpd))
478                 return -EINVAL;
479
480         /* If power.irq_safe, the PM domain is never powered off. */
481         if (dev->power.irq_safe) {
482                 timed = false;
483                 goto out;
484         }
485
486         mutex_lock(&genpd->lock);
487         ret = __genpd_poweron(genpd);
488         mutex_unlock(&genpd->lock);
489
490         if (ret)
491                 return ret;
492
493  out:
494         /* Measure resume latency. */
495         if (timed && runtime_pm)
496                 time_start = ktime_get();
497
498         genpd_start_dev(genpd, dev);
499         genpd_restore_dev(genpd, dev);
500
501         /* Update resume latency value if the measured time exceeds it. */
502         if (timed && runtime_pm) {
503                 elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
504                 if (elapsed_ns > td->resume_latency_ns) {
505                         td->resume_latency_ns = elapsed_ns;
506                         dev_dbg(dev, "resume latency exceeded, %lld ns\n",
507                                 elapsed_ns);
508                         genpd->max_off_time_changed = true;
509                         td->constraint_changed = true;
510                 }
511         }
512
513         return 0;
514 }
515
516 static bool pd_ignore_unused;
517 static int __init pd_ignore_unused_setup(char *__unused)
518 {
519         pd_ignore_unused = true;
520         return 1;
521 }
522 __setup("pd_ignore_unused", pd_ignore_unused_setup);
523
524 /**
525  * genpd_poweroff_unused - Power off all PM domains with no devices in use.
526  */
527 static int __init genpd_poweroff_unused(void)
528 {
529         struct generic_pm_domain *genpd;
530
531         if (pd_ignore_unused) {
532                 pr_warn("genpd: Not disabling unused power domains\n");
533                 return 0;
534         }
535
536         mutex_lock(&gpd_list_lock);
537
538         list_for_each_entry(genpd, &gpd_list, gpd_list_node)
539                 genpd_queue_power_off_work(genpd);
540
541         mutex_unlock(&gpd_list_lock);
542
543         return 0;
544 }
545 late_initcall(genpd_poweroff_unused);
546
547 #ifdef CONFIG_PM_SLEEP
548
549 /**
550  * pm_genpd_present - Check if the given PM domain has been initialized.
551  * @genpd: PM domain to check.
552  */
553 static bool pm_genpd_present(const struct generic_pm_domain *genpd)
554 {
555         const struct generic_pm_domain *gpd;
556
557         if (IS_ERR_OR_NULL(genpd))
558                 return false;
559
560         list_for_each_entry(gpd, &gpd_list, gpd_list_node)
561                 if (gpd == genpd)
562                         return true;
563
564         return false;
565 }
566
567 static bool genpd_dev_active_wakeup(struct generic_pm_domain *genpd,
568                                     struct device *dev)
569 {
570         return GENPD_DEV_CALLBACK(genpd, bool, active_wakeup, dev);
571 }
572
573 /**
574  * pm_genpd_sync_poweroff - Synchronously power off a PM domain and its masters.
575  * @genpd: PM domain to power off, if possible.
576  * @timed: True if latency measurements are allowed.
577  *
578  * Check if the given PM domain can be powered off (during system suspend or
579  * hibernation) and do that if so.  Also, in that case propagate to its masters.
580  *
581  * This function is only called in "noirq" and "syscore" stages of system power
582  * transitions, so it need not acquire locks (all of the "noirq" callbacks are
583  * executed sequentially, so it is guaranteed that it will never run twice in
584  * parallel).
585  */
586 static void pm_genpd_sync_poweroff(struct generic_pm_domain *genpd,
587                                    bool timed)
588 {
589         struct gpd_link *link;
590
591         if (genpd->status == GPD_STATE_POWER_OFF)
592                 return;
593
594         if (genpd->suspended_count != genpd->device_count
595             || atomic_read(&genpd->sd_count) > 0)
596                 return;
597
598         genpd_power_off(genpd, timed);
599
600         genpd->status = GPD_STATE_POWER_OFF;
601
602         list_for_each_entry(link, &genpd->slave_links, slave_node) {
603                 genpd_sd_counter_dec(link->master);
604                 pm_genpd_sync_poweroff(link->master, timed);
605         }
606 }
607
608 /**
609  * pm_genpd_sync_poweron - Synchronously power on a PM domain and its masters.
610  * @genpd: PM domain to power on.
611  * @timed: True if latency measurements are allowed.
612  *
613  * This function is only called in "noirq" and "syscore" stages of system power
614  * transitions, so it need not acquire locks (all of the "noirq" callbacks are
615  * executed sequentially, so it is guaranteed that it will never run twice in
616  * parallel).
617  */
618 static void pm_genpd_sync_poweron(struct generic_pm_domain *genpd,
619                                   bool timed)
620 {
621         struct gpd_link *link;
622
623         if (genpd->status == GPD_STATE_ACTIVE)
624                 return;
625
626         list_for_each_entry(link, &genpd->slave_links, slave_node) {
627                 pm_genpd_sync_poweron(link->master, timed);
628                 genpd_sd_counter_inc(link->master);
629         }
630
631         genpd_power_on(genpd, timed);
632
633         genpd->status = GPD_STATE_ACTIVE;
634 }
635
636 /**
637  * resume_needed - Check whether to resume a device before system suspend.
638  * @dev: Device to check.
639  * @genpd: PM domain the device belongs to.
640  *
641  * There are two cases in which a device that can wake up the system from sleep
642  * states should be resumed by pm_genpd_prepare(): (1) if the device is enabled
643  * to wake up the system and it has to remain active for this purpose while the
644  * system is in the sleep state and (2) if the device is not enabled to wake up
645  * the system from sleep states and it generally doesn't generate wakeup signals
646  * by itself (those signals are generated on its behalf by other parts of the
647  * system).  In the latter case it may be necessary to reconfigure the device's
648  * wakeup settings during system suspend, because it may have been set up to
649  * signal remote wakeup from the system's working state as needed by runtime PM.
650  * Return 'true' in either of the above cases.
651  */
652 static bool resume_needed(struct device *dev, struct generic_pm_domain *genpd)
653 {
654         bool active_wakeup;
655
656         if (!device_can_wakeup(dev))
657                 return false;
658
659         active_wakeup = genpd_dev_active_wakeup(genpd, dev);
660         return device_may_wakeup(dev) ? active_wakeup : !active_wakeup;
661 }
662
663 /**
664  * pm_genpd_prepare - Start power transition of a device in a PM domain.
665  * @dev: Device to start the transition of.
666  *
667  * Start a power transition of a device (during a system-wide power transition)
668  * under the assumption that its pm_domain field points to the domain member of
669  * an object of type struct generic_pm_domain representing a PM domain
670  * consisting of I/O devices.
671  */
672 static int pm_genpd_prepare(struct device *dev)
673 {
674         struct generic_pm_domain *genpd;
675         int ret;
676
677         dev_dbg(dev, "%s()\n", __func__);
678
679         genpd = dev_to_genpd(dev);
680         if (IS_ERR(genpd))
681                 return -EINVAL;
682
683         /*
684          * If a wakeup request is pending for the device, it should be woken up
685          * at this point and a system wakeup event should be reported if it's
686          * set up to wake up the system from sleep states.
687          */
688         pm_runtime_get_noresume(dev);
689         if (pm_runtime_barrier(dev) && device_may_wakeup(dev))
690                 pm_wakeup_event(dev, 0);
691
692         if (pm_wakeup_pending()) {
693                 pm_runtime_put(dev);
694                 return -EBUSY;
695         }
696
697         if (resume_needed(dev, genpd))
698                 pm_runtime_resume(dev);
699
700         mutex_lock(&genpd->lock);
701
702         if (genpd->prepared_count++ == 0) {
703                 genpd->suspended_count = 0;
704                 genpd->suspend_power_off = genpd->status == GPD_STATE_POWER_OFF;
705         }
706
707         mutex_unlock(&genpd->lock);
708
709         if (genpd->suspend_power_off) {
710                 pm_runtime_put_noidle(dev);
711                 return 0;
712         }
713
714         /*
715          * The PM domain must be in the GPD_STATE_ACTIVE state at this point,
716          * so genpd_poweron() will return immediately, but if the device
717          * is suspended (e.g. it's been stopped by genpd_stop_dev()), we need
718          * to make it operational.
719          */
720         pm_runtime_resume(dev);
721         __pm_runtime_disable(dev, false);
722
723         ret = pm_generic_prepare(dev);
724         if (ret) {
725                 mutex_lock(&genpd->lock);
726
727                 if (--genpd->prepared_count == 0)
728                         genpd->suspend_power_off = false;
729
730                 mutex_unlock(&genpd->lock);
731                 pm_runtime_enable(dev);
732         }
733
734         pm_runtime_put(dev);
735         return ret;
736 }
737
738 /**
739  * pm_genpd_suspend - Suspend a device belonging to an I/O PM domain.
740  * @dev: Device to suspend.
741  *
742  * Suspend a device under the assumption that its pm_domain field points to the
743  * domain member of an object of type struct generic_pm_domain representing
744  * a PM domain consisting of I/O devices.
745  */
746 static int pm_genpd_suspend(struct device *dev)
747 {
748         struct generic_pm_domain *genpd;
749
750         dev_dbg(dev, "%s()\n", __func__);
751
752         genpd = dev_to_genpd(dev);
753         if (IS_ERR(genpd))
754                 return -EINVAL;
755
756         return genpd->suspend_power_off ? 0 : pm_generic_suspend(dev);
757 }
758
759 /**
760  * pm_genpd_suspend_late - Late suspend of a device from an I/O PM domain.
761  * @dev: Device to suspend.
762  *
763  * Carry out a late suspend of a device under the assumption that its
764  * pm_domain field points to the domain member of an object of type
765  * struct generic_pm_domain representing a PM domain consisting of I/O devices.
766  */
767 static int pm_genpd_suspend_late(struct device *dev)
768 {
769         struct generic_pm_domain *genpd;
770
771         dev_dbg(dev, "%s()\n", __func__);
772
773         genpd = dev_to_genpd(dev);
774         if (IS_ERR(genpd))
775                 return -EINVAL;
776
777         return genpd->suspend_power_off ? 0 : pm_generic_suspend_late(dev);
778 }
779
780 /**
781  * pm_genpd_suspend_noirq - Completion of suspend of device in an I/O PM domain.
782  * @dev: Device to suspend.
783  *
784  * Stop the device and remove power from the domain if all devices in it have
785  * been stopped.
786  */
787 static int pm_genpd_suspend_noirq(struct device *dev)
788 {
789         struct generic_pm_domain *genpd;
790
791         dev_dbg(dev, "%s()\n", __func__);
792
793         genpd = dev_to_genpd(dev);
794         if (IS_ERR(genpd))
795                 return -EINVAL;
796
797         if (genpd->suspend_power_off
798             || (dev->power.wakeup_path && genpd_dev_active_wakeup(genpd, dev)))
799                 return 0;
800
801         genpd_stop_dev(genpd, dev);
802
803         /*
804          * Since all of the "noirq" callbacks are executed sequentially, it is
805          * guaranteed that this function will never run twice in parallel for
806          * the same PM domain, so it is not necessary to use locking here.
807          */
808         genpd->suspended_count++;
809         pm_genpd_sync_poweroff(genpd, true);
810
811         return 0;
812 }
813
814 /**
815  * pm_genpd_resume_noirq - Start of resume of device in an I/O PM domain.
816  * @dev: Device to resume.
817  *
818  * Restore power to the device's PM domain, if necessary, and start the device.
819  */
820 static int pm_genpd_resume_noirq(struct device *dev)
821 {
822         struct generic_pm_domain *genpd;
823
824         dev_dbg(dev, "%s()\n", __func__);
825
826         genpd = dev_to_genpd(dev);
827         if (IS_ERR(genpd))
828                 return -EINVAL;
829
830         if (genpd->suspend_power_off
831             || (dev->power.wakeup_path && genpd_dev_active_wakeup(genpd, dev)))
832                 return 0;
833
834         /*
835          * Since all of the "noirq" callbacks are executed sequentially, it is
836          * guaranteed that this function will never run twice in parallel for
837          * the same PM domain, so it is not necessary to use locking here.
838          */
839         pm_genpd_sync_poweron(genpd, true);
840         genpd->suspended_count--;
841
842         return genpd_start_dev(genpd, dev);
843 }
844
845 /**
846  * pm_genpd_resume_early - Early resume of a device in an I/O PM domain.
847  * @dev: Device to resume.
848  *
849  * Carry out an early resume of a device under the assumption that its
850  * pm_domain field points to the domain member of an object of type
851  * struct generic_pm_domain representing a power domain consisting of I/O
852  * devices.
853  */
854 static int pm_genpd_resume_early(struct device *dev)
855 {
856         struct generic_pm_domain *genpd;
857
858         dev_dbg(dev, "%s()\n", __func__);
859
860         genpd = dev_to_genpd(dev);
861         if (IS_ERR(genpd))
862                 return -EINVAL;
863
864         return genpd->suspend_power_off ? 0 : pm_generic_resume_early(dev);
865 }
866
867 /**
868  * pm_genpd_resume - Resume of device in an I/O PM domain.
869  * @dev: Device to resume.
870  *
871  * Resume a device under the assumption that its pm_domain field points to the
872  * domain member of an object of type struct generic_pm_domain representing
873  * a power domain consisting of I/O devices.
874  */
875 static int pm_genpd_resume(struct device *dev)
876 {
877         struct generic_pm_domain *genpd;
878
879         dev_dbg(dev, "%s()\n", __func__);
880
881         genpd = dev_to_genpd(dev);
882         if (IS_ERR(genpd))
883                 return -EINVAL;
884
885         return genpd->suspend_power_off ? 0 : pm_generic_resume(dev);
886 }
887
888 /**
889  * pm_genpd_freeze - Freezing a device in an I/O PM domain.
890  * @dev: Device to freeze.
891  *
892  * Freeze a device under the assumption that its pm_domain field points to the
893  * domain member of an object of type struct generic_pm_domain representing
894  * a power domain consisting of I/O devices.
895  */
896 static int pm_genpd_freeze(struct device *dev)
897 {
898         struct generic_pm_domain *genpd;
899
900         dev_dbg(dev, "%s()\n", __func__);
901
902         genpd = dev_to_genpd(dev);
903         if (IS_ERR(genpd))
904                 return -EINVAL;
905
906         return genpd->suspend_power_off ? 0 : pm_generic_freeze(dev);
907 }
908
909 /**
910  * pm_genpd_freeze_late - Late freeze of a device in an I/O PM domain.
911  * @dev: Device to freeze.
912  *
913  * Carry out a late freeze of a device under the assumption that its
914  * pm_domain field points to the domain member of an object of type
915  * struct generic_pm_domain representing a power domain consisting of I/O
916  * devices.
917  */
918 static int pm_genpd_freeze_late(struct device *dev)
919 {
920         struct generic_pm_domain *genpd;
921
922         dev_dbg(dev, "%s()\n", __func__);
923
924         genpd = dev_to_genpd(dev);
925         if (IS_ERR(genpd))
926                 return -EINVAL;
927
928         return genpd->suspend_power_off ? 0 : pm_generic_freeze_late(dev);
929 }
930
931 /**
932  * pm_genpd_freeze_noirq - Completion of freezing a device in an I/O PM domain.
933  * @dev: Device to freeze.
934  *
935  * Carry out a late freeze of a device under the assumption that its
936  * pm_domain field points to the domain member of an object of type
937  * struct generic_pm_domain representing a power domain consisting of I/O
938  * devices.
939  */
940 static int pm_genpd_freeze_noirq(struct device *dev)
941 {
942         struct generic_pm_domain *genpd;
943
944         dev_dbg(dev, "%s()\n", __func__);
945
946         genpd = dev_to_genpd(dev);
947         if (IS_ERR(genpd))
948                 return -EINVAL;
949
950         return genpd->suspend_power_off ? 0 : genpd_stop_dev(genpd, dev);
951 }
952
953 /**
954  * pm_genpd_thaw_noirq - Early thaw of device in an I/O PM domain.
955  * @dev: Device to thaw.
956  *
957  * Start the device, unless power has been removed from the domain already
958  * before the system transition.
959  */
960 static int pm_genpd_thaw_noirq(struct device *dev)
961 {
962         struct generic_pm_domain *genpd;
963
964         dev_dbg(dev, "%s()\n", __func__);
965
966         genpd = dev_to_genpd(dev);
967         if (IS_ERR(genpd))
968                 return -EINVAL;
969
970         return genpd->suspend_power_off ?
971                 0 : genpd_start_dev(genpd, dev);
972 }
973
974 /**
975  * pm_genpd_thaw_early - Early thaw of device in an I/O PM domain.
976  * @dev: Device to thaw.
977  *
978  * Carry out an early thaw of a device under the assumption that its
979  * pm_domain field points to the domain member of an object of type
980  * struct generic_pm_domain representing a power domain consisting of I/O
981  * devices.
982  */
983 static int pm_genpd_thaw_early(struct device *dev)
984 {
985         struct generic_pm_domain *genpd;
986
987         dev_dbg(dev, "%s()\n", __func__);
988
989         genpd = dev_to_genpd(dev);
990         if (IS_ERR(genpd))
991                 return -EINVAL;
992
993         return genpd->suspend_power_off ? 0 : pm_generic_thaw_early(dev);
994 }
995
996 /**
997  * pm_genpd_thaw - Thaw a device belonging to an I/O power domain.
998  * @dev: Device to thaw.
999  *
1000  * Thaw a device under the assumption that its pm_domain field points to the
1001  * domain member of an object of type struct generic_pm_domain representing
1002  * a power domain consisting of I/O devices.
1003  */
1004 static int pm_genpd_thaw(struct device *dev)
1005 {
1006         struct generic_pm_domain *genpd;
1007
1008         dev_dbg(dev, "%s()\n", __func__);
1009
1010         genpd = dev_to_genpd(dev);
1011         if (IS_ERR(genpd))
1012                 return -EINVAL;
1013
1014         return genpd->suspend_power_off ? 0 : pm_generic_thaw(dev);
1015 }
1016
1017 /**
1018  * pm_genpd_restore_noirq - Start of restore of device in an I/O PM domain.
1019  * @dev: Device to resume.
1020  *
1021  * Make sure the domain will be in the same power state as before the
1022  * hibernation the system is resuming from and start the device if necessary.
1023  */
1024 static int pm_genpd_restore_noirq(struct device *dev)
1025 {
1026         struct generic_pm_domain *genpd;
1027
1028         dev_dbg(dev, "%s()\n", __func__);
1029
1030         genpd = dev_to_genpd(dev);
1031         if (IS_ERR(genpd))
1032                 return -EINVAL;
1033
1034         /*
1035          * Since all of the "noirq" callbacks are executed sequentially, it is
1036          * guaranteed that this function will never run twice in parallel for
1037          * the same PM domain, so it is not necessary to use locking here.
1038          *
1039          * At this point suspended_count == 0 means we are being run for the
1040          * first time for the given domain in the present cycle.
1041          */
1042         if (genpd->suspended_count++ == 0) {
1043                 /*
1044                  * The boot kernel might put the domain into arbitrary state,
1045                  * so make it appear as powered off to pm_genpd_sync_poweron(),
1046                  * so that it tries to power it on in case it was really off.
1047                  */
1048                 genpd->status = GPD_STATE_POWER_OFF;
1049                 if (genpd->suspend_power_off) {
1050                         /*
1051                          * If the domain was off before the hibernation, make
1052                          * sure it will be off going forward.
1053                          */
1054                         genpd_power_off(genpd, true);
1055
1056                         return 0;
1057                 }
1058         }
1059
1060         if (genpd->suspend_power_off)
1061                 return 0;
1062
1063         pm_genpd_sync_poweron(genpd, true);
1064
1065         return genpd_start_dev(genpd, dev);
1066 }
1067
1068 /**
1069  * pm_genpd_complete - Complete power transition of a device in a power domain.
1070  * @dev: Device to complete the transition of.
1071  *
1072  * Complete a power transition of a device (during a system-wide power
1073  * transition) under the assumption that its pm_domain field points to the
1074  * domain member of an object of type struct generic_pm_domain representing
1075  * a power domain consisting of I/O devices.
1076  */
1077 static void pm_genpd_complete(struct device *dev)
1078 {
1079         struct generic_pm_domain *genpd;
1080         bool run_complete;
1081
1082         dev_dbg(dev, "%s()\n", __func__);
1083
1084         genpd = dev_to_genpd(dev);
1085         if (IS_ERR(genpd))
1086                 return;
1087
1088         mutex_lock(&genpd->lock);
1089
1090         run_complete = !genpd->suspend_power_off;
1091         if (--genpd->prepared_count == 0)
1092                 genpd->suspend_power_off = false;
1093
1094         mutex_unlock(&genpd->lock);
1095
1096         if (run_complete) {
1097                 pm_generic_complete(dev);
1098                 pm_runtime_set_active(dev);
1099                 pm_runtime_enable(dev);
1100                 pm_request_idle(dev);
1101         }
1102 }
1103
1104 /**
1105  * genpd_syscore_switch - Switch power during system core suspend or resume.
1106  * @dev: Device that normally is marked as "always on" to switch power for.
1107  *
1108  * This routine may only be called during the system core (syscore) suspend or
1109  * resume phase for devices whose "always on" flags are set.
1110  */
1111 static void genpd_syscore_switch(struct device *dev, bool suspend)
1112 {
1113         struct generic_pm_domain *genpd;
1114
1115         genpd = dev_to_genpd(dev);
1116         if (!pm_genpd_present(genpd))
1117                 return;
1118
1119         if (suspend) {
1120                 genpd->suspended_count++;
1121                 pm_genpd_sync_poweroff(genpd, false);
1122         } else {
1123                 pm_genpd_sync_poweron(genpd, false);
1124                 genpd->suspended_count--;
1125         }
1126 }
1127
1128 void pm_genpd_syscore_poweroff(struct device *dev)
1129 {
1130         genpd_syscore_switch(dev, true);
1131 }
1132 EXPORT_SYMBOL_GPL(pm_genpd_syscore_poweroff);
1133
1134 void pm_genpd_syscore_poweron(struct device *dev)
1135 {
1136         genpd_syscore_switch(dev, false);
1137 }
1138 EXPORT_SYMBOL_GPL(pm_genpd_syscore_poweron);
1139
1140 #else /* !CONFIG_PM_SLEEP */
1141
1142 #define pm_genpd_prepare                NULL
1143 #define pm_genpd_suspend                NULL
1144 #define pm_genpd_suspend_late           NULL
1145 #define pm_genpd_suspend_noirq          NULL
1146 #define pm_genpd_resume_early           NULL
1147 #define pm_genpd_resume_noirq           NULL
1148 #define pm_genpd_resume                 NULL
1149 #define pm_genpd_freeze                 NULL
1150 #define pm_genpd_freeze_late            NULL
1151 #define pm_genpd_freeze_noirq           NULL
1152 #define pm_genpd_thaw_early             NULL
1153 #define pm_genpd_thaw_noirq             NULL
1154 #define pm_genpd_thaw                   NULL
1155 #define pm_genpd_restore_noirq          NULL
1156 #define pm_genpd_complete               NULL
1157
1158 #endif /* CONFIG_PM_SLEEP */
1159
1160 static struct generic_pm_domain_data *genpd_alloc_dev_data(struct device *dev,
1161                                         struct generic_pm_domain *genpd,
1162                                         struct gpd_timing_data *td)
1163 {
1164         struct generic_pm_domain_data *gpd_data;
1165         int ret;
1166
1167         ret = dev_pm_get_subsys_data(dev);
1168         if (ret)
1169                 return ERR_PTR(ret);
1170
1171         gpd_data = kzalloc(sizeof(*gpd_data), GFP_KERNEL);
1172         if (!gpd_data) {
1173                 ret = -ENOMEM;
1174                 goto err_put;
1175         }
1176
1177         if (td)
1178                 gpd_data->td = *td;
1179
1180         gpd_data->base.dev = dev;
1181         gpd_data->td.constraint_changed = true;
1182         gpd_data->td.effective_constraint_ns = -1;
1183         gpd_data->nb.notifier_call = genpd_dev_pm_qos_notifier;
1184
1185         spin_lock_irq(&dev->power.lock);
1186
1187         if (dev->power.subsys_data->domain_data) {
1188                 ret = -EINVAL;
1189                 goto err_free;
1190         }
1191
1192         dev->power.subsys_data->domain_data = &gpd_data->base;
1193
1194         spin_unlock_irq(&dev->power.lock);
1195
1196         dev_pm_domain_set(dev, &genpd->domain);
1197
1198         return gpd_data;
1199
1200  err_free:
1201         spin_unlock_irq(&dev->power.lock);
1202         kfree(gpd_data);
1203  err_put:
1204         dev_pm_put_subsys_data(dev);
1205         return ERR_PTR(ret);
1206 }
1207
1208 static void genpd_free_dev_data(struct device *dev,
1209                                 struct generic_pm_domain_data *gpd_data)
1210 {
1211         dev_pm_domain_set(dev, NULL);
1212
1213         spin_lock_irq(&dev->power.lock);
1214
1215         dev->power.subsys_data->domain_data = NULL;
1216
1217         spin_unlock_irq(&dev->power.lock);
1218
1219         kfree(gpd_data);
1220         dev_pm_put_subsys_data(dev);
1221 }
1222
1223 /**
1224  * __pm_genpd_add_device - Add a device to an I/O PM domain.
1225  * @genpd: PM domain to add the device to.
1226  * @dev: Device to be added.
1227  * @td: Set of PM QoS timing parameters to attach to the device.
1228  */
1229 int __pm_genpd_add_device(struct generic_pm_domain *genpd, struct device *dev,
1230                           struct gpd_timing_data *td)
1231 {
1232         struct generic_pm_domain_data *gpd_data;
1233         int ret = 0;
1234
1235         dev_dbg(dev, "%s()\n", __func__);
1236
1237         if (IS_ERR_OR_NULL(genpd) || IS_ERR_OR_NULL(dev))
1238                 return -EINVAL;
1239
1240         gpd_data = genpd_alloc_dev_data(dev, genpd, td);
1241         if (IS_ERR(gpd_data))
1242                 return PTR_ERR(gpd_data);
1243
1244         mutex_lock(&genpd->lock);
1245
1246         if (genpd->prepared_count > 0) {
1247                 ret = -EAGAIN;
1248                 goto out;
1249         }
1250
1251         ret = genpd->attach_dev ? genpd->attach_dev(genpd, dev) : 0;
1252         if (ret)
1253                 goto out;
1254
1255         genpd->device_count++;
1256         genpd->max_off_time_changed = true;
1257
1258         list_add_tail(&gpd_data->base.list_node, &genpd->dev_list);
1259
1260  out:
1261         mutex_unlock(&genpd->lock);
1262
1263         if (ret)
1264                 genpd_free_dev_data(dev, gpd_data);
1265         else
1266                 dev_pm_qos_add_notifier(dev, &gpd_data->nb);
1267
1268         return ret;
1269 }
1270 EXPORT_SYMBOL_GPL(__pm_genpd_add_device);
1271
1272 /**
1273  * pm_genpd_remove_device - Remove a device from an I/O PM domain.
1274  * @genpd: PM domain to remove the device from.
1275  * @dev: Device to be removed.
1276  */
1277 int pm_genpd_remove_device(struct generic_pm_domain *genpd,
1278                            struct device *dev)
1279 {
1280         struct generic_pm_domain_data *gpd_data;
1281         struct pm_domain_data *pdd;
1282         int ret = 0;
1283
1284         dev_dbg(dev, "%s()\n", __func__);
1285
1286         if (!genpd || genpd != pm_genpd_lookup_dev(dev))
1287                 return -EINVAL;
1288
1289         /* The above validation also means we have existing domain_data. */
1290         pdd = dev->power.subsys_data->domain_data;
1291         gpd_data = to_gpd_data(pdd);
1292         dev_pm_qos_remove_notifier(dev, &gpd_data->nb);
1293
1294         mutex_lock(&genpd->lock);
1295
1296         if (genpd->prepared_count > 0) {
1297                 ret = -EAGAIN;
1298                 goto out;
1299         }
1300
1301         genpd->device_count--;
1302         genpd->max_off_time_changed = true;
1303
1304         if (genpd->detach_dev)
1305                 genpd->detach_dev(genpd, dev);
1306
1307         list_del_init(&pdd->list_node);
1308
1309         mutex_unlock(&genpd->lock);
1310
1311         genpd_free_dev_data(dev, gpd_data);
1312
1313         return 0;
1314
1315  out:
1316         mutex_unlock(&genpd->lock);
1317         dev_pm_qos_add_notifier(dev, &gpd_data->nb);
1318
1319         return ret;
1320 }
1321 EXPORT_SYMBOL_GPL(pm_genpd_remove_device);
1322
1323 /**
1324  * pm_genpd_add_subdomain - Add a subdomain to an I/O PM domain.
1325  * @genpd: Master PM domain to add the subdomain to.
1326  * @subdomain: Subdomain to be added.
1327  */
1328 int pm_genpd_add_subdomain(struct generic_pm_domain *genpd,
1329                            struct generic_pm_domain *subdomain)
1330 {
1331         struct gpd_link *link, *itr;
1332         int ret = 0;
1333
1334         if (IS_ERR_OR_NULL(genpd) || IS_ERR_OR_NULL(subdomain)
1335             || genpd == subdomain)
1336                 return -EINVAL;
1337
1338         link = kzalloc(sizeof(*link), GFP_KERNEL);
1339         if (!link)
1340                 return -ENOMEM;
1341
1342         mutex_lock(&genpd->lock);
1343         mutex_lock_nested(&subdomain->lock, SINGLE_DEPTH_NESTING);
1344
1345         if (genpd->status == GPD_STATE_POWER_OFF
1346             &&  subdomain->status != GPD_STATE_POWER_OFF) {
1347                 ret = -EINVAL;
1348                 goto out;
1349         }
1350
1351         list_for_each_entry(itr, &genpd->master_links, master_node) {
1352                 if (itr->slave == subdomain && itr->master == genpd) {
1353                         ret = -EINVAL;
1354                         goto out;
1355                 }
1356         }
1357
1358         link->master = genpd;
1359         list_add_tail(&link->master_node, &genpd->master_links);
1360         link->slave = subdomain;
1361         list_add_tail(&link->slave_node, &subdomain->slave_links);
1362         if (subdomain->status != GPD_STATE_POWER_OFF)
1363                 genpd_sd_counter_inc(genpd);
1364
1365  out:
1366         mutex_unlock(&subdomain->lock);
1367         mutex_unlock(&genpd->lock);
1368         if (ret)
1369                 kfree(link);
1370         return ret;
1371 }
1372 EXPORT_SYMBOL_GPL(pm_genpd_add_subdomain);
1373
1374 /**
1375  * pm_genpd_remove_subdomain - Remove a subdomain from an I/O PM domain.
1376  * @genpd: Master PM domain to remove the subdomain from.
1377  * @subdomain: Subdomain to be removed.
1378  */
1379 int pm_genpd_remove_subdomain(struct generic_pm_domain *genpd,
1380                               struct generic_pm_domain *subdomain)
1381 {
1382         struct gpd_link *link;
1383         int ret = -EINVAL;
1384
1385         if (IS_ERR_OR_NULL(genpd) || IS_ERR_OR_NULL(subdomain))
1386                 return -EINVAL;
1387
1388         mutex_lock(&genpd->lock);
1389
1390         if (!list_empty(&subdomain->slave_links) || subdomain->device_count) {
1391                 pr_warn("%s: unable to remove subdomain %s\n", genpd->name,
1392                         subdomain->name);
1393                 ret = -EBUSY;
1394                 goto out;
1395         }
1396
1397         list_for_each_entry(link, &genpd->master_links, master_node) {
1398                 if (link->slave != subdomain)
1399                         continue;
1400
1401                 mutex_lock_nested(&subdomain->lock, SINGLE_DEPTH_NESTING);
1402
1403                 list_del(&link->master_node);
1404                 list_del(&link->slave_node);
1405                 kfree(link);
1406                 if (subdomain->status != GPD_STATE_POWER_OFF)
1407                         genpd_sd_counter_dec(genpd);
1408
1409                 mutex_unlock(&subdomain->lock);
1410
1411                 ret = 0;
1412                 break;
1413         }
1414
1415 out:
1416         mutex_unlock(&genpd->lock);
1417
1418         return ret;
1419 }
1420 EXPORT_SYMBOL_GPL(pm_genpd_remove_subdomain);
1421
1422 /* Default device callbacks for generic PM domains. */
1423
1424 /**
1425  * pm_genpd_default_save_state - Default "save device state" for PM domains.
1426  * @dev: Device to handle.
1427  */
1428 static int pm_genpd_default_save_state(struct device *dev)
1429 {
1430         int (*cb)(struct device *__dev);
1431
1432         if (dev->type && dev->type->pm)
1433                 cb = dev->type->pm->runtime_suspend;
1434         else if (dev->class && dev->class->pm)
1435                 cb = dev->class->pm->runtime_suspend;
1436         else if (dev->bus && dev->bus->pm)
1437                 cb = dev->bus->pm->runtime_suspend;
1438         else
1439                 cb = NULL;
1440
1441         if (!cb && dev->driver && dev->driver->pm)
1442                 cb = dev->driver->pm->runtime_suspend;
1443
1444         return cb ? cb(dev) : 0;
1445 }
1446
1447 /**
1448  * pm_genpd_default_restore_state - Default PM domains "restore device state".
1449  * @dev: Device to handle.
1450  */
1451 static int pm_genpd_default_restore_state(struct device *dev)
1452 {
1453         int (*cb)(struct device *__dev);
1454
1455         if (dev->type && dev->type->pm)
1456                 cb = dev->type->pm->runtime_resume;
1457         else if (dev->class && dev->class->pm)
1458                 cb = dev->class->pm->runtime_resume;
1459         else if (dev->bus && dev->bus->pm)
1460                 cb = dev->bus->pm->runtime_resume;
1461         else
1462                 cb = NULL;
1463
1464         if (!cb && dev->driver && dev->driver->pm)
1465                 cb = dev->driver->pm->runtime_resume;
1466
1467         return cb ? cb(dev) : 0;
1468 }
1469
1470 /**
1471  * pm_genpd_init - Initialize a generic I/O PM domain object.
1472  * @genpd: PM domain object to initialize.
1473  * @gov: PM domain governor to associate with the domain (may be NULL).
1474  * @is_off: Initial value of the domain's power_is_off field.
1475  */
1476 void pm_genpd_init(struct generic_pm_domain *genpd,
1477                    struct dev_power_governor *gov, bool is_off)
1478 {
1479         if (IS_ERR_OR_NULL(genpd))
1480                 return;
1481
1482         INIT_LIST_HEAD(&genpd->master_links);
1483         INIT_LIST_HEAD(&genpd->slave_links);
1484         INIT_LIST_HEAD(&genpd->dev_list);
1485         mutex_init(&genpd->lock);
1486         genpd->gov = gov;
1487         INIT_WORK(&genpd->power_off_work, genpd_power_off_work_fn);
1488         atomic_set(&genpd->sd_count, 0);
1489         genpd->status = is_off ? GPD_STATE_POWER_OFF : GPD_STATE_ACTIVE;
1490         genpd->device_count = 0;
1491         genpd->max_off_time_ns = -1;
1492         genpd->max_off_time_changed = true;
1493         genpd->domain.ops.runtime_suspend = pm_genpd_runtime_suspend;
1494         genpd->domain.ops.runtime_resume = pm_genpd_runtime_resume;
1495         genpd->domain.ops.prepare = pm_genpd_prepare;
1496         genpd->domain.ops.suspend = pm_genpd_suspend;
1497         genpd->domain.ops.suspend_late = pm_genpd_suspend_late;
1498         genpd->domain.ops.suspend_noirq = pm_genpd_suspend_noirq;
1499         genpd->domain.ops.resume_noirq = pm_genpd_resume_noirq;
1500         genpd->domain.ops.resume_early = pm_genpd_resume_early;
1501         genpd->domain.ops.resume = pm_genpd_resume;
1502         genpd->domain.ops.freeze = pm_genpd_freeze;
1503         genpd->domain.ops.freeze_late = pm_genpd_freeze_late;
1504         genpd->domain.ops.freeze_noirq = pm_genpd_freeze_noirq;
1505         genpd->domain.ops.thaw_noirq = pm_genpd_thaw_noirq;
1506         genpd->domain.ops.thaw_early = pm_genpd_thaw_early;
1507         genpd->domain.ops.thaw = pm_genpd_thaw;
1508         genpd->domain.ops.poweroff = pm_genpd_suspend;
1509         genpd->domain.ops.poweroff_late = pm_genpd_suspend_late;
1510         genpd->domain.ops.poweroff_noirq = pm_genpd_suspend_noirq;
1511         genpd->domain.ops.restore_noirq = pm_genpd_restore_noirq;
1512         genpd->domain.ops.restore_early = pm_genpd_resume_early;
1513         genpd->domain.ops.restore = pm_genpd_resume;
1514         genpd->domain.ops.complete = pm_genpd_complete;
1515         genpd->dev_ops.save_state = pm_genpd_default_save_state;
1516         genpd->dev_ops.restore_state = pm_genpd_default_restore_state;
1517
1518         if (genpd->flags & GENPD_FLAG_PM_CLK) {
1519                 genpd->dev_ops.stop = pm_clk_suspend;
1520                 genpd->dev_ops.start = pm_clk_resume;
1521         }
1522
1523         mutex_lock(&gpd_list_lock);
1524         list_add(&genpd->gpd_list_node, &gpd_list);
1525         mutex_unlock(&gpd_list_lock);
1526 }
1527 EXPORT_SYMBOL_GPL(pm_genpd_init);
1528
1529 #ifdef CONFIG_PM_GENERIC_DOMAINS_OF
1530 /*
1531  * Device Tree based PM domain providers.
1532  *
1533  * The code below implements generic device tree based PM domain providers that
1534  * bind device tree nodes with generic PM domains registered in the system.
1535  *
1536  * Any driver that registers generic PM domains and needs to support binding of
1537  * devices to these domains is supposed to register a PM domain provider, which
1538  * maps a PM domain specifier retrieved from the device tree to a PM domain.
1539  *
1540  * Two simple mapping functions have been provided for convenience:
1541  *  - __of_genpd_xlate_simple() for 1:1 device tree node to PM domain mapping.
1542  *  - __of_genpd_xlate_onecell() for mapping of multiple PM domains per node by
1543  *    index.
1544  */
1545
1546 /**
1547  * struct of_genpd_provider - PM domain provider registration structure
1548  * @link: Entry in global list of PM domain providers
1549  * @node: Pointer to device tree node of PM domain provider
1550  * @xlate: Provider-specific xlate callback mapping a set of specifier cells
1551  *         into a PM domain.
1552  * @data: context pointer to be passed into @xlate callback
1553  */
1554 struct of_genpd_provider {
1555         struct list_head link;
1556         struct device_node *node;
1557         genpd_xlate_t xlate;
1558         void *data;
1559 };
1560
1561 /* List of registered PM domain providers. */
1562 static LIST_HEAD(of_genpd_providers);
1563 /* Mutex to protect the list above. */
1564 static DEFINE_MUTEX(of_genpd_mutex);
1565
1566 /**
1567  * __of_genpd_xlate_simple() - Xlate function for direct node-domain mapping
1568  * @genpdspec: OF phandle args to map into a PM domain
1569  * @data: xlate function private data - pointer to struct generic_pm_domain
1570  *
1571  * This is a generic xlate function that can be used to model PM domains that
1572  * have their own device tree nodes. The private data of xlate function needs
1573  * to be a valid pointer to struct generic_pm_domain.
1574  */
1575 struct generic_pm_domain *__of_genpd_xlate_simple(
1576                                         struct of_phandle_args *genpdspec,
1577                                         void *data)
1578 {
1579         if (genpdspec->args_count != 0)
1580                 return ERR_PTR(-EINVAL);
1581         return data;
1582 }
1583 EXPORT_SYMBOL_GPL(__of_genpd_xlate_simple);
1584
1585 /**
1586  * __of_genpd_xlate_onecell() - Xlate function using a single index.
1587  * @genpdspec: OF phandle args to map into a PM domain
1588  * @data: xlate function private data - pointer to struct genpd_onecell_data
1589  *
1590  * This is a generic xlate function that can be used to model simple PM domain
1591  * controllers that have one device tree node and provide multiple PM domains.
1592  * A single cell is used as an index into an array of PM domains specified in
1593  * the genpd_onecell_data struct when registering the provider.
1594  */
1595 struct generic_pm_domain *__of_genpd_xlate_onecell(
1596                                         struct of_phandle_args *genpdspec,
1597                                         void *data)
1598 {
1599         struct genpd_onecell_data *genpd_data = data;
1600         unsigned int idx = genpdspec->args[0];
1601
1602         if (genpdspec->args_count != 1)
1603                 return ERR_PTR(-EINVAL);
1604
1605         if (idx >= genpd_data->num_domains) {
1606                 pr_err("%s: invalid domain index %u\n", __func__, idx);
1607                 return ERR_PTR(-EINVAL);
1608         }
1609
1610         if (!genpd_data->domains[idx])
1611                 return ERR_PTR(-ENOENT);
1612
1613         return genpd_data->domains[idx];
1614 }
1615 EXPORT_SYMBOL_GPL(__of_genpd_xlate_onecell);
1616
1617 /**
1618  * __of_genpd_add_provider() - Register a PM domain provider for a node
1619  * @np: Device node pointer associated with the PM domain provider.
1620  * @xlate: Callback for decoding PM domain from phandle arguments.
1621  * @data: Context pointer for @xlate callback.
1622  */
1623 int __of_genpd_add_provider(struct device_node *np, genpd_xlate_t xlate,
1624                         void *data)
1625 {
1626         struct of_genpd_provider *cp;
1627
1628         cp = kzalloc(sizeof(*cp), GFP_KERNEL);
1629         if (!cp)
1630                 return -ENOMEM;
1631
1632         cp->node = of_node_get(np);
1633         cp->data = data;
1634         cp->xlate = xlate;
1635
1636         mutex_lock(&of_genpd_mutex);
1637         list_add(&cp->link, &of_genpd_providers);
1638         mutex_unlock(&of_genpd_mutex);
1639         pr_debug("Added domain provider from %s\n", np->full_name);
1640
1641         return 0;
1642 }
1643 EXPORT_SYMBOL_GPL(__of_genpd_add_provider);
1644
1645 /**
1646  * of_genpd_del_provider() - Remove a previously registered PM domain provider
1647  * @np: Device node pointer associated with the PM domain provider
1648  */
1649 void of_genpd_del_provider(struct device_node *np)
1650 {
1651         struct of_genpd_provider *cp;
1652
1653         mutex_lock(&of_genpd_mutex);
1654         list_for_each_entry(cp, &of_genpd_providers, link) {
1655                 if (cp->node == np) {
1656                         list_del(&cp->link);
1657                         of_node_put(cp->node);
1658                         kfree(cp);
1659                         break;
1660                 }
1661         }
1662         mutex_unlock(&of_genpd_mutex);
1663 }
1664 EXPORT_SYMBOL_GPL(of_genpd_del_provider);
1665
1666 /**
1667  * of_genpd_get_from_provider() - Look-up PM domain
1668  * @genpdspec: OF phandle args to use for look-up
1669  *
1670  * Looks for a PM domain provider under the node specified by @genpdspec and if
1671  * found, uses xlate function of the provider to map phandle args to a PM
1672  * domain.
1673  *
1674  * Returns a valid pointer to struct generic_pm_domain on success or ERR_PTR()
1675  * on failure.
1676  */
1677 struct generic_pm_domain *of_genpd_get_from_provider(
1678                                         struct of_phandle_args *genpdspec)
1679 {
1680         struct generic_pm_domain *genpd = ERR_PTR(-ENOENT);
1681         struct of_genpd_provider *provider;
1682
1683         mutex_lock(&of_genpd_mutex);
1684
1685         /* Check if we have such a provider in our array */
1686         list_for_each_entry(provider, &of_genpd_providers, link) {
1687                 if (provider->node == genpdspec->np)
1688                         genpd = provider->xlate(genpdspec, provider->data);
1689                 if (!IS_ERR(genpd))
1690                         break;
1691         }
1692
1693         mutex_unlock(&of_genpd_mutex);
1694
1695         return genpd;
1696 }
1697 EXPORT_SYMBOL_GPL(of_genpd_get_from_provider);
1698
1699 /**
1700  * genpd_dev_pm_detach - Detach a device from its PM domain.
1701  * @dev: Device to detach.
1702  * @power_off: Currently not used
1703  *
1704  * Try to locate a corresponding generic PM domain, which the device was
1705  * attached to previously. If such is found, the device is detached from it.
1706  */
1707 static void genpd_dev_pm_detach(struct device *dev, bool power_off)
1708 {
1709         struct generic_pm_domain *pd;
1710         unsigned int i;
1711         int ret = 0;
1712
1713         pd = pm_genpd_lookup_dev(dev);
1714         if (!pd)
1715                 return;
1716
1717         dev_dbg(dev, "removing from PM domain %s\n", pd->name);
1718
1719         for (i = 1; i < GENPD_RETRY_MAX_MS; i <<= 1) {
1720                 ret = pm_genpd_remove_device(pd, dev);
1721                 if (ret != -EAGAIN)
1722                         break;
1723
1724                 mdelay(i);
1725                 cond_resched();
1726         }
1727
1728         if (ret < 0) {
1729                 dev_err(dev, "failed to remove from PM domain %s: %d",
1730                         pd->name, ret);
1731                 return;
1732         }
1733
1734         /* Check if PM domain can be powered off after removing this device. */
1735         genpd_queue_power_off_work(pd);
1736 }
1737
1738 static void genpd_dev_pm_sync(struct device *dev)
1739 {
1740         struct generic_pm_domain *pd;
1741
1742         pd = dev_to_genpd(dev);
1743         if (IS_ERR(pd))
1744                 return;
1745
1746         genpd_queue_power_off_work(pd);
1747 }
1748
1749 /**
1750  * genpd_dev_pm_attach - Attach a device to its PM domain using DT.
1751  * @dev: Device to attach.
1752  *
1753  * Parse device's OF node to find a PM domain specifier. If such is found,
1754  * attaches the device to retrieved pm_domain ops.
1755  *
1756  * Both generic and legacy Samsung-specific DT bindings are supported to keep
1757  * backwards compatibility with existing DTBs.
1758  *
1759  * Returns 0 on successfully attached PM domain or negative error code. Note
1760  * that if a power-domain exists for the device, but it cannot be found or
1761  * turned on, then return -EPROBE_DEFER to ensure that the device is not
1762  * probed and to re-try again later.
1763  */
1764 int genpd_dev_pm_attach(struct device *dev)
1765 {
1766         struct of_phandle_args pd_args;
1767         struct generic_pm_domain *pd;
1768         unsigned int i;
1769         int ret;
1770
1771         if (!dev->of_node)
1772                 return -ENODEV;
1773
1774         if (dev->pm_domain)
1775                 return -EEXIST;
1776
1777         ret = of_parse_phandle_with_args(dev->of_node, "power-domains",
1778                                         "#power-domain-cells", 0, &pd_args);
1779         if (ret < 0) {
1780                 if (ret != -ENOENT)
1781                         return ret;
1782
1783                 /*
1784                  * Try legacy Samsung-specific bindings
1785                  * (for backwards compatibility of DT ABI)
1786                  */
1787                 pd_args.args_count = 0;
1788                 pd_args.np = of_parse_phandle(dev->of_node,
1789                                                 "samsung,power-domain", 0);
1790                 if (!pd_args.np)
1791                         return -ENOENT;
1792         }
1793
1794         pd = of_genpd_get_from_provider(&pd_args);
1795         of_node_put(pd_args.np);
1796         if (IS_ERR(pd)) {
1797                 dev_dbg(dev, "%s() failed to find PM domain: %ld\n",
1798                         __func__, PTR_ERR(pd));
1799                 return -EPROBE_DEFER;
1800         }
1801
1802         dev_dbg(dev, "adding to PM domain %s\n", pd->name);
1803
1804         for (i = 1; i < GENPD_RETRY_MAX_MS; i <<= 1) {
1805                 ret = pm_genpd_add_device(pd, dev);
1806                 if (ret != -EAGAIN)
1807                         break;
1808
1809                 mdelay(i);
1810                 cond_resched();
1811         }
1812
1813         if (ret < 0) {
1814                 dev_err(dev, "failed to add to PM domain %s: %d",
1815                         pd->name, ret);
1816                 goto out;
1817         }
1818
1819         dev->pm_domain->detach = genpd_dev_pm_detach;
1820         dev->pm_domain->sync = genpd_dev_pm_sync;
1821         ret = genpd_poweron(pd);
1822
1823 out:
1824         return ret ? -EPROBE_DEFER : 0;
1825 }
1826 EXPORT_SYMBOL_GPL(genpd_dev_pm_attach);
1827 #endif /* CONFIG_PM_GENERIC_DOMAINS_OF */
1828
1829
1830 /***        debugfs support        ***/
1831
1832 #ifdef CONFIG_PM_ADVANCED_DEBUG
1833 #include <linux/pm.h>
1834 #include <linux/device.h>
1835 #include <linux/debugfs.h>
1836 #include <linux/seq_file.h>
1837 #include <linux/init.h>
1838 #include <linux/kobject.h>
1839 static struct dentry *pm_genpd_debugfs_dir;
1840
1841 /*
1842  * TODO: This function is a slightly modified version of rtpm_status_show
1843  * from sysfs.c, so generalize it.
1844  */
1845 static void rtpm_status_str(struct seq_file *s, struct device *dev)
1846 {
1847         static const char * const status_lookup[] = {
1848                 [RPM_ACTIVE] = "active",
1849                 [RPM_RESUMING] = "resuming",
1850                 [RPM_SUSPENDED] = "suspended",
1851                 [RPM_SUSPENDING] = "suspending"
1852         };
1853         const char *p = "";
1854
1855         if (dev->power.runtime_error)
1856                 p = "error";
1857         else if (dev->power.disable_depth)
1858                 p = "unsupported";
1859         else if (dev->power.runtime_status < ARRAY_SIZE(status_lookup))
1860                 p = status_lookup[dev->power.runtime_status];
1861         else
1862                 WARN_ON(1);
1863
1864         seq_puts(s, p);
1865 }
1866
1867 static int pm_genpd_summary_one(struct seq_file *s,
1868                                 struct generic_pm_domain *genpd)
1869 {
1870         static const char * const status_lookup[] = {
1871                 [GPD_STATE_ACTIVE] = "on",
1872                 [GPD_STATE_POWER_OFF] = "off"
1873         };
1874         struct pm_domain_data *pm_data;
1875         const char *kobj_path;
1876         struct gpd_link *link;
1877         int ret;
1878
1879         ret = mutex_lock_interruptible(&genpd->lock);
1880         if (ret)
1881                 return -ERESTARTSYS;
1882
1883         if (WARN_ON(genpd->status >= ARRAY_SIZE(status_lookup)))
1884                 goto exit;
1885         seq_printf(s, "%-30s  %-15s ", genpd->name, status_lookup[genpd->status]);
1886
1887         /*
1888          * Modifications on the list require holding locks on both
1889          * master and slave, so we are safe.
1890          * Also genpd->name is immutable.
1891          */
1892         list_for_each_entry(link, &genpd->master_links, master_node) {
1893                 seq_printf(s, "%s", link->slave->name);
1894                 if (!list_is_last(&link->master_node, &genpd->master_links))
1895                         seq_puts(s, ", ");
1896         }
1897
1898         list_for_each_entry(pm_data, &genpd->dev_list, list_node) {
1899                 kobj_path = kobject_get_path(&pm_data->dev->kobj, GFP_KERNEL);
1900                 if (kobj_path == NULL)
1901                         continue;
1902
1903                 seq_printf(s, "\n    %-50s  ", kobj_path);
1904                 rtpm_status_str(s, pm_data->dev);
1905                 kfree(kobj_path);
1906         }
1907
1908         seq_puts(s, "\n");
1909 exit:
1910         mutex_unlock(&genpd->lock);
1911
1912         return 0;
1913 }
1914
1915 static int pm_genpd_summary_show(struct seq_file *s, void *data)
1916 {
1917         struct generic_pm_domain *genpd;
1918         int ret = 0;
1919
1920         seq_puts(s, "domain                          status          slaves\n");
1921         seq_puts(s, "    /device                                             runtime status\n");
1922         seq_puts(s, "----------------------------------------------------------------------\n");
1923
1924         ret = mutex_lock_interruptible(&gpd_list_lock);
1925         if (ret)
1926                 return -ERESTARTSYS;
1927
1928         list_for_each_entry(genpd, &gpd_list, gpd_list_node) {
1929                 ret = pm_genpd_summary_one(s, genpd);
1930                 if (ret)
1931                         break;
1932         }
1933         mutex_unlock(&gpd_list_lock);
1934
1935         return ret;
1936 }
1937
1938 static int pm_genpd_summary_open(struct inode *inode, struct file *file)
1939 {
1940         return single_open(file, pm_genpd_summary_show, NULL);
1941 }
1942
1943 static const struct file_operations pm_genpd_summary_fops = {
1944         .open = pm_genpd_summary_open,
1945         .read = seq_read,
1946         .llseek = seq_lseek,
1947         .release = single_release,
1948 };
1949
1950 static int __init pm_genpd_debug_init(void)
1951 {
1952         struct dentry *d;
1953
1954         pm_genpd_debugfs_dir = debugfs_create_dir("pm_genpd", NULL);
1955
1956         if (!pm_genpd_debugfs_dir)
1957                 return -ENOMEM;
1958
1959         d = debugfs_create_file("pm_genpd_summary", S_IRUGO,
1960                         pm_genpd_debugfs_dir, NULL, &pm_genpd_summary_fops);
1961         if (!d)
1962                 return -ENOMEM;
1963
1964         return 0;
1965 }
1966 late_initcall(pm_genpd_debug_init);
1967
1968 static void __exit pm_genpd_debug_exit(void)
1969 {
1970         debugfs_remove_recursive(pm_genpd_debugfs_dir);
1971 }
1972 __exitcall(pm_genpd_debug_exit);
1973 #endif /* CONFIG_PM_ADVANCED_DEBUG */