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