GNU Linux-libre 5.10.215-gnu1
[releases.git] / drivers / base / power / domain.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * drivers/base/power/domain.c - Common code related to device power domains.
4  *
5  * Copyright (C) 2011 Rafael J. Wysocki <rjw@sisk.pl>, Renesas Electronics Corp.
6  */
7 #define pr_fmt(fmt) "PM: " fmt
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_opp.h>
14 #include <linux/pm_runtime.h>
15 #include <linux/pm_domain.h>
16 #include <linux/pm_qos.h>
17 #include <linux/pm_clock.h>
18 #include <linux/slab.h>
19 #include <linux/err.h>
20 #include <linux/sched.h>
21 #include <linux/suspend.h>
22 #include <linux/export.h>
23 #include <linux/cpu.h>
24
25 #include "power.h"
26
27 #define GENPD_RETRY_MAX_MS      250             /* Approximate */
28
29 #define GENPD_DEV_CALLBACK(genpd, type, callback, dev)          \
30 ({                                                              \
31         type (*__routine)(struct device *__d);                  \
32         type __ret = (type)0;                                   \
33                                                                 \
34         __routine = genpd->dev_ops.callback;                    \
35         if (__routine) {                                        \
36                 __ret = __routine(dev);                         \
37         }                                                       \
38         __ret;                                                  \
39 })
40
41 static LIST_HEAD(gpd_list);
42 static DEFINE_MUTEX(gpd_list_lock);
43
44 struct genpd_lock_ops {
45         void (*lock)(struct generic_pm_domain *genpd);
46         void (*lock_nested)(struct generic_pm_domain *genpd, int depth);
47         int (*lock_interruptible)(struct generic_pm_domain *genpd);
48         void (*unlock)(struct generic_pm_domain *genpd);
49 };
50
51 static void genpd_lock_mtx(struct generic_pm_domain *genpd)
52 {
53         mutex_lock(&genpd->mlock);
54 }
55
56 static void genpd_lock_nested_mtx(struct generic_pm_domain *genpd,
57                                         int depth)
58 {
59         mutex_lock_nested(&genpd->mlock, depth);
60 }
61
62 static int genpd_lock_interruptible_mtx(struct generic_pm_domain *genpd)
63 {
64         return mutex_lock_interruptible(&genpd->mlock);
65 }
66
67 static void genpd_unlock_mtx(struct generic_pm_domain *genpd)
68 {
69         return mutex_unlock(&genpd->mlock);
70 }
71
72 static const struct genpd_lock_ops genpd_mtx_ops = {
73         .lock = genpd_lock_mtx,
74         .lock_nested = genpd_lock_nested_mtx,
75         .lock_interruptible = genpd_lock_interruptible_mtx,
76         .unlock = genpd_unlock_mtx,
77 };
78
79 static void genpd_lock_spin(struct generic_pm_domain *genpd)
80         __acquires(&genpd->slock)
81 {
82         unsigned long flags;
83
84         spin_lock_irqsave(&genpd->slock, flags);
85         genpd->lock_flags = flags;
86 }
87
88 static void genpd_lock_nested_spin(struct generic_pm_domain *genpd,
89                                         int depth)
90         __acquires(&genpd->slock)
91 {
92         unsigned long flags;
93
94         spin_lock_irqsave_nested(&genpd->slock, flags, depth);
95         genpd->lock_flags = flags;
96 }
97
98 static int genpd_lock_interruptible_spin(struct generic_pm_domain *genpd)
99         __acquires(&genpd->slock)
100 {
101         unsigned long flags;
102
103         spin_lock_irqsave(&genpd->slock, flags);
104         genpd->lock_flags = flags;
105         return 0;
106 }
107
108 static void genpd_unlock_spin(struct generic_pm_domain *genpd)
109         __releases(&genpd->slock)
110 {
111         spin_unlock_irqrestore(&genpd->slock, genpd->lock_flags);
112 }
113
114 static const struct genpd_lock_ops genpd_spin_ops = {
115         .lock = genpd_lock_spin,
116         .lock_nested = genpd_lock_nested_spin,
117         .lock_interruptible = genpd_lock_interruptible_spin,
118         .unlock = genpd_unlock_spin,
119 };
120
121 #define genpd_lock(p)                   p->lock_ops->lock(p)
122 #define genpd_lock_nested(p, d)         p->lock_ops->lock_nested(p, d)
123 #define genpd_lock_interruptible(p)     p->lock_ops->lock_interruptible(p)
124 #define genpd_unlock(p)                 p->lock_ops->unlock(p)
125
126 #define genpd_status_on(genpd)          (genpd->status == GENPD_STATE_ON)
127 #define genpd_is_irq_safe(genpd)        (genpd->flags & GENPD_FLAG_IRQ_SAFE)
128 #define genpd_is_always_on(genpd)       (genpd->flags & GENPD_FLAG_ALWAYS_ON)
129 #define genpd_is_active_wakeup(genpd)   (genpd->flags & GENPD_FLAG_ACTIVE_WAKEUP)
130 #define genpd_is_cpu_domain(genpd)      (genpd->flags & GENPD_FLAG_CPU_DOMAIN)
131 #define genpd_is_rpm_always_on(genpd)   (genpd->flags & GENPD_FLAG_RPM_ALWAYS_ON)
132
133 static inline bool irq_safe_dev_in_no_sleep_domain(struct device *dev,
134                 const struct generic_pm_domain *genpd)
135 {
136         bool ret;
137
138         ret = pm_runtime_is_irq_safe(dev) && !genpd_is_irq_safe(genpd);
139
140         /*
141          * Warn once if an IRQ safe device is attached to a no sleep domain, as
142          * to indicate a suboptimal configuration for PM. For an always on
143          * domain this isn't case, thus don't warn.
144          */
145         if (ret && !genpd_is_always_on(genpd))
146                 dev_warn_once(dev, "PM domain %s will not be powered off\n",
147                                 genpd->name);
148
149         return ret;
150 }
151
152 static int genpd_runtime_suspend(struct device *dev);
153
154 /*
155  * Get the generic PM domain for a particular struct device.
156  * This validates the struct device pointer, the PM domain pointer,
157  * and checks that the PM domain pointer is a real generic PM domain.
158  * Any failure results in NULL being returned.
159  */
160 static struct generic_pm_domain *dev_to_genpd_safe(struct device *dev)
161 {
162         if (IS_ERR_OR_NULL(dev) || IS_ERR_OR_NULL(dev->pm_domain))
163                 return NULL;
164
165         /* A genpd's always have its ->runtime_suspend() callback assigned. */
166         if (dev->pm_domain->ops.runtime_suspend == genpd_runtime_suspend)
167                 return pd_to_genpd(dev->pm_domain);
168
169         return NULL;
170 }
171
172 /*
173  * This should only be used where we are certain that the pm_domain
174  * attached to the device is a genpd domain.
175  */
176 static struct generic_pm_domain *dev_to_genpd(struct device *dev)
177 {
178         if (IS_ERR_OR_NULL(dev->pm_domain))
179                 return ERR_PTR(-EINVAL);
180
181         return pd_to_genpd(dev->pm_domain);
182 }
183
184 static int genpd_stop_dev(const struct generic_pm_domain *genpd,
185                           struct device *dev)
186 {
187         return GENPD_DEV_CALLBACK(genpd, int, stop, dev);
188 }
189
190 static int genpd_start_dev(const struct generic_pm_domain *genpd,
191                            struct device *dev)
192 {
193         return GENPD_DEV_CALLBACK(genpd, int, start, dev);
194 }
195
196 static bool genpd_sd_counter_dec(struct generic_pm_domain *genpd)
197 {
198         bool ret = false;
199
200         if (!WARN_ON(atomic_read(&genpd->sd_count) == 0))
201                 ret = !!atomic_dec_and_test(&genpd->sd_count);
202
203         return ret;
204 }
205
206 static void genpd_sd_counter_inc(struct generic_pm_domain *genpd)
207 {
208         atomic_inc(&genpd->sd_count);
209         smp_mb__after_atomic();
210 }
211
212 #ifdef CONFIG_DEBUG_FS
213 static void genpd_update_accounting(struct generic_pm_domain *genpd)
214 {
215         ktime_t delta, now;
216
217         now = ktime_get();
218         delta = ktime_sub(now, genpd->accounting_time);
219
220         /*
221          * If genpd->status is active, it means we are just
222          * out of off and so update the idle time and vice
223          * versa.
224          */
225         if (genpd->status == GENPD_STATE_ON) {
226                 int state_idx = genpd->state_idx;
227
228                 genpd->states[state_idx].idle_time =
229                         ktime_add(genpd->states[state_idx].idle_time, delta);
230         } else {
231                 genpd->on_time = ktime_add(genpd->on_time, delta);
232         }
233
234         genpd->accounting_time = now;
235 }
236 #else
237 static inline void genpd_update_accounting(struct generic_pm_domain *genpd) {}
238 #endif
239
240 static int _genpd_reeval_performance_state(struct generic_pm_domain *genpd,
241                                            unsigned int state)
242 {
243         struct generic_pm_domain_data *pd_data;
244         struct pm_domain_data *pdd;
245         struct gpd_link *link;
246
247         /* New requested state is same as Max requested state */
248         if (state == genpd->performance_state)
249                 return state;
250
251         /* New requested state is higher than Max requested state */
252         if (state > genpd->performance_state)
253                 return state;
254
255         /* Traverse all devices within the domain */
256         list_for_each_entry(pdd, &genpd->dev_list, list_node) {
257                 pd_data = to_gpd_data(pdd);
258
259                 if (pd_data->performance_state > state)
260                         state = pd_data->performance_state;
261         }
262
263         /*
264          * Traverse all sub-domains within the domain. This can be
265          * done without any additional locking as the link->performance_state
266          * field is protected by the parent genpd->lock, which is already taken.
267          *
268          * Also note that link->performance_state (subdomain's performance state
269          * requirement to parent domain) is different from
270          * link->child->performance_state (current performance state requirement
271          * of the devices/sub-domains of the subdomain) and so can have a
272          * different value.
273          *
274          * Note that we also take vote from powered-off sub-domains into account
275          * as the same is done for devices right now.
276          */
277         list_for_each_entry(link, &genpd->parent_links, parent_node) {
278                 if (link->performance_state > state)
279                         state = link->performance_state;
280         }
281
282         return state;
283 }
284
285 static int _genpd_set_performance_state(struct generic_pm_domain *genpd,
286                                         unsigned int state, int depth)
287 {
288         struct generic_pm_domain *parent;
289         struct gpd_link *link;
290         int parent_state, ret;
291
292         if (state == genpd->performance_state)
293                 return 0;
294
295         /* Propagate to parents of genpd */
296         list_for_each_entry(link, &genpd->child_links, child_node) {
297                 parent = link->parent;
298
299                 if (!parent->set_performance_state)
300                         continue;
301
302                 /* Find parent's performance state */
303                 ret = dev_pm_opp_xlate_performance_state(genpd->opp_table,
304                                                          parent->opp_table,
305                                                          state);
306                 if (unlikely(ret < 0))
307                         goto err;
308
309                 parent_state = ret;
310
311                 genpd_lock_nested(parent, depth + 1);
312
313                 link->prev_performance_state = link->performance_state;
314                 link->performance_state = parent_state;
315                 parent_state = _genpd_reeval_performance_state(parent,
316                                                 parent_state);
317                 ret = _genpd_set_performance_state(parent, parent_state, depth + 1);
318                 if (ret)
319                         link->performance_state = link->prev_performance_state;
320
321                 genpd_unlock(parent);
322
323                 if (ret)
324                         goto err;
325         }
326
327         ret = genpd->set_performance_state(genpd, state);
328         if (ret)
329                 goto err;
330
331         genpd->performance_state = state;
332         return 0;
333
334 err:
335         /* Encountered an error, lets rollback */
336         list_for_each_entry_continue_reverse(link, &genpd->child_links,
337                                              child_node) {
338                 parent = link->parent;
339
340                 if (!parent->set_performance_state)
341                         continue;
342
343                 genpd_lock_nested(parent, depth + 1);
344
345                 parent_state = link->prev_performance_state;
346                 link->performance_state = parent_state;
347
348                 parent_state = _genpd_reeval_performance_state(parent,
349                                                 parent_state);
350                 if (_genpd_set_performance_state(parent, parent_state, depth + 1)) {
351                         pr_err("%s: Failed to roll back to %d performance state\n",
352                                parent->name, parent_state);
353                 }
354
355                 genpd_unlock(parent);
356         }
357
358         return ret;
359 }
360
361 /**
362  * dev_pm_genpd_set_performance_state- Set performance state of device's power
363  * domain.
364  *
365  * @dev: Device for which the performance-state needs to be set.
366  * @state: Target performance state of the device. This can be set as 0 when the
367  *         device doesn't have any performance state constraints left (And so
368  *         the device wouldn't participate anymore to find the target
369  *         performance state of the genpd).
370  *
371  * It is assumed that the users guarantee that the genpd wouldn't be detached
372  * while this routine is getting called.
373  *
374  * Returns 0 on success and negative error values on failures.
375  */
376 int dev_pm_genpd_set_performance_state(struct device *dev, unsigned int state)
377 {
378         struct generic_pm_domain *genpd;
379         struct generic_pm_domain_data *gpd_data;
380         unsigned int prev;
381         int ret;
382
383         genpd = dev_to_genpd_safe(dev);
384         if (!genpd)
385                 return -ENODEV;
386
387         if (unlikely(!genpd->set_performance_state))
388                 return -EINVAL;
389
390         if (WARN_ON(!dev->power.subsys_data ||
391                      !dev->power.subsys_data->domain_data))
392                 return -EINVAL;
393
394         genpd_lock(genpd);
395
396         gpd_data = to_gpd_data(dev->power.subsys_data->domain_data);
397         prev = gpd_data->performance_state;
398         gpd_data->performance_state = state;
399
400         state = _genpd_reeval_performance_state(genpd, state);
401         ret = _genpd_set_performance_state(genpd, state, 0);
402         if (ret)
403                 gpd_data->performance_state = prev;
404
405         genpd_unlock(genpd);
406
407         return ret;
408 }
409 EXPORT_SYMBOL_GPL(dev_pm_genpd_set_performance_state);
410
411 static int _genpd_power_on(struct generic_pm_domain *genpd, bool timed)
412 {
413         unsigned int state_idx = genpd->state_idx;
414         ktime_t time_start;
415         s64 elapsed_ns;
416         int ret;
417
418         /* Notify consumers that we are about to power on. */
419         ret = raw_notifier_call_chain_robust(&genpd->power_notifiers,
420                                              GENPD_NOTIFY_PRE_ON,
421                                              GENPD_NOTIFY_OFF, NULL);
422         ret = notifier_to_errno(ret);
423         if (ret)
424                 return ret;
425
426         if (!genpd->power_on)
427                 goto out;
428
429         if (!timed) {
430                 ret = genpd->power_on(genpd);
431                 if (ret)
432                         goto err;
433
434                 goto out;
435         }
436
437         time_start = ktime_get();
438         ret = genpd->power_on(genpd);
439         if (ret)
440                 goto err;
441
442         elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
443         if (elapsed_ns <= genpd->states[state_idx].power_on_latency_ns)
444                 goto out;
445
446         genpd->states[state_idx].power_on_latency_ns = elapsed_ns;
447         genpd->max_off_time_changed = true;
448         pr_debug("%s: Power-%s latency exceeded, new value %lld ns\n",
449                  genpd->name, "on", elapsed_ns);
450
451 out:
452         raw_notifier_call_chain(&genpd->power_notifiers, GENPD_NOTIFY_ON, NULL);
453         return 0;
454 err:
455         raw_notifier_call_chain(&genpd->power_notifiers, GENPD_NOTIFY_OFF,
456                                 NULL);
457         return ret;
458 }
459
460 static int _genpd_power_off(struct generic_pm_domain *genpd, bool timed)
461 {
462         unsigned int state_idx = genpd->state_idx;
463         ktime_t time_start;
464         s64 elapsed_ns;
465         int ret;
466
467         /* Notify consumers that we are about to power off. */
468         ret = raw_notifier_call_chain_robust(&genpd->power_notifiers,
469                                              GENPD_NOTIFY_PRE_OFF,
470                                              GENPD_NOTIFY_ON, NULL);
471         ret = notifier_to_errno(ret);
472         if (ret)
473                 return ret;
474
475         if (!genpd->power_off)
476                 goto out;
477
478         if (!timed) {
479                 ret = genpd->power_off(genpd);
480                 if (ret)
481                         goto busy;
482
483                 goto out;
484         }
485
486         time_start = ktime_get();
487         ret = genpd->power_off(genpd);
488         if (ret)
489                 goto busy;
490
491         elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
492         if (elapsed_ns <= genpd->states[state_idx].power_off_latency_ns)
493                 goto out;
494
495         genpd->states[state_idx].power_off_latency_ns = elapsed_ns;
496         genpd->max_off_time_changed = true;
497         pr_debug("%s: Power-%s latency exceeded, new value %lld ns\n",
498                  genpd->name, "off", elapsed_ns);
499
500 out:
501         raw_notifier_call_chain(&genpd->power_notifiers, GENPD_NOTIFY_OFF,
502                                 NULL);
503         return 0;
504 busy:
505         raw_notifier_call_chain(&genpd->power_notifiers, GENPD_NOTIFY_ON, NULL);
506         return ret;
507 }
508
509 /**
510  * genpd_queue_power_off_work - Queue up the execution of genpd_power_off().
511  * @genpd: PM domain to power off.
512  *
513  * Queue up the execution of genpd_power_off() unless it's already been done
514  * before.
515  */
516 static void genpd_queue_power_off_work(struct generic_pm_domain *genpd)
517 {
518         queue_work(pm_wq, &genpd->power_off_work);
519 }
520
521 /**
522  * genpd_power_off - Remove power from a given PM domain.
523  * @genpd: PM domain to power down.
524  * @one_dev_on: If invoked from genpd's ->runtime_suspend|resume() callback, the
525  * RPM status of the releated device is in an intermediate state, not yet turned
526  * into RPM_SUSPENDED. This means genpd_power_off() must allow one device to not
527  * be RPM_SUSPENDED, while it tries to power off the PM domain.
528  *
529  * If all of the @genpd's devices have been suspended and all of its subdomains
530  * have been powered down, remove power from @genpd.
531  */
532 static int genpd_power_off(struct generic_pm_domain *genpd, bool one_dev_on,
533                            unsigned int depth)
534 {
535         struct pm_domain_data *pdd;
536         struct gpd_link *link;
537         unsigned int not_suspended = 0;
538         int ret;
539
540         /*
541          * Do not try to power off the domain in the following situations:
542          * (1) The domain is already in the "power off" state.
543          * (2) System suspend is in progress.
544          */
545         if (!genpd_status_on(genpd) || genpd->prepared_count > 0)
546                 return 0;
547
548         /*
549          * Abort power off for the PM domain in the following situations:
550          * (1) The domain is configured as always on.
551          * (2) When the domain has a subdomain being powered on.
552          */
553         if (genpd_is_always_on(genpd) ||
554                         genpd_is_rpm_always_on(genpd) ||
555                         atomic_read(&genpd->sd_count) > 0)
556                 return -EBUSY;
557
558         list_for_each_entry(pdd, &genpd->dev_list, list_node) {
559                 enum pm_qos_flags_status stat;
560
561                 stat = dev_pm_qos_flags(pdd->dev, PM_QOS_FLAG_NO_POWER_OFF);
562                 if (stat > PM_QOS_FLAGS_NONE)
563                         return -EBUSY;
564
565                 /*
566                  * Do not allow PM domain to be powered off, when an IRQ safe
567                  * device is part of a non-IRQ safe domain.
568                  */
569                 if (!pm_runtime_suspended(pdd->dev) ||
570                         irq_safe_dev_in_no_sleep_domain(pdd->dev, genpd))
571                         not_suspended++;
572         }
573
574         if (not_suspended > 1 || (not_suspended == 1 && !one_dev_on))
575                 return -EBUSY;
576
577         if (genpd->gov && genpd->gov->power_down_ok) {
578                 if (!genpd->gov->power_down_ok(&genpd->domain))
579                         return -EAGAIN;
580         }
581
582         /* Default to shallowest state. */
583         if (!genpd->gov)
584                 genpd->state_idx = 0;
585
586         /* Don't power off, if a child domain is waiting to power on. */
587         if (atomic_read(&genpd->sd_count) > 0)
588                 return -EBUSY;
589
590         ret = _genpd_power_off(genpd, true);
591         if (ret) {
592                 genpd->states[genpd->state_idx].rejected++;
593                 return ret;
594         }
595
596         genpd->status = GENPD_STATE_OFF;
597         genpd_update_accounting(genpd);
598         genpd->states[genpd->state_idx].usage++;
599
600         list_for_each_entry(link, &genpd->child_links, child_node) {
601                 genpd_sd_counter_dec(link->parent);
602                 genpd_lock_nested(link->parent, depth + 1);
603                 genpd_power_off(link->parent, false, depth + 1);
604                 genpd_unlock(link->parent);
605         }
606
607         return 0;
608 }
609
610 /**
611  * genpd_power_on - Restore power to a given PM domain and its parents.
612  * @genpd: PM domain to power up.
613  * @depth: nesting count for lockdep.
614  *
615  * Restore power to @genpd and all of its parents so that it is possible to
616  * resume a device belonging to it.
617  */
618 static int genpd_power_on(struct generic_pm_domain *genpd, unsigned int depth)
619 {
620         struct gpd_link *link;
621         int ret = 0;
622
623         if (genpd_status_on(genpd))
624                 return 0;
625
626         /*
627          * The list is guaranteed not to change while the loop below is being
628          * executed, unless one of the parents' .power_on() callbacks fiddles
629          * with it.
630          */
631         list_for_each_entry(link, &genpd->child_links, child_node) {
632                 struct generic_pm_domain *parent = link->parent;
633
634                 genpd_sd_counter_inc(parent);
635
636                 genpd_lock_nested(parent, depth + 1);
637                 ret = genpd_power_on(parent, depth + 1);
638                 genpd_unlock(parent);
639
640                 if (ret) {
641                         genpd_sd_counter_dec(parent);
642                         goto err;
643                 }
644         }
645
646         ret = _genpd_power_on(genpd, true);
647         if (ret)
648                 goto err;
649
650         genpd->status = GENPD_STATE_ON;
651         genpd_update_accounting(genpd);
652
653         return 0;
654
655  err:
656         list_for_each_entry_continue_reverse(link,
657                                         &genpd->child_links,
658                                         child_node) {
659                 genpd_sd_counter_dec(link->parent);
660                 genpd_lock_nested(link->parent, depth + 1);
661                 genpd_power_off(link->parent, false, depth + 1);
662                 genpd_unlock(link->parent);
663         }
664
665         return ret;
666 }
667
668 static int genpd_dev_pm_start(struct device *dev)
669 {
670         struct generic_pm_domain *genpd = dev_to_genpd(dev);
671
672         return genpd_start_dev(genpd, dev);
673 }
674
675 static int genpd_dev_pm_qos_notifier(struct notifier_block *nb,
676                                      unsigned long val, void *ptr)
677 {
678         struct generic_pm_domain_data *gpd_data;
679         struct device *dev;
680
681         gpd_data = container_of(nb, struct generic_pm_domain_data, nb);
682         dev = gpd_data->base.dev;
683
684         for (;;) {
685                 struct generic_pm_domain *genpd;
686                 struct pm_domain_data *pdd;
687
688                 spin_lock_irq(&dev->power.lock);
689
690                 pdd = dev->power.subsys_data ?
691                                 dev->power.subsys_data->domain_data : NULL;
692                 if (pdd) {
693                         to_gpd_data(pdd)->td.constraint_changed = true;
694                         genpd = dev_to_genpd(dev);
695                 } else {
696                         genpd = ERR_PTR(-ENODATA);
697                 }
698
699                 spin_unlock_irq(&dev->power.lock);
700
701                 if (!IS_ERR(genpd)) {
702                         genpd_lock(genpd);
703                         genpd->max_off_time_changed = true;
704                         genpd_unlock(genpd);
705                 }
706
707                 dev = dev->parent;
708                 if (!dev || dev->power.ignore_children)
709                         break;
710         }
711
712         return NOTIFY_DONE;
713 }
714
715 /**
716  * genpd_power_off_work_fn - Power off PM domain whose subdomain count is 0.
717  * @work: Work structure used for scheduling the execution of this function.
718  */
719 static void genpd_power_off_work_fn(struct work_struct *work)
720 {
721         struct generic_pm_domain *genpd;
722
723         genpd = container_of(work, struct generic_pm_domain, power_off_work);
724
725         genpd_lock(genpd);
726         genpd_power_off(genpd, false, 0);
727         genpd_unlock(genpd);
728 }
729
730 /**
731  * __genpd_runtime_suspend - walk the hierarchy of ->runtime_suspend() callbacks
732  * @dev: Device to handle.
733  */
734 static int __genpd_runtime_suspend(struct device *dev)
735 {
736         int (*cb)(struct device *__dev);
737
738         if (dev->type && dev->type->pm)
739                 cb = dev->type->pm->runtime_suspend;
740         else if (dev->class && dev->class->pm)
741                 cb = dev->class->pm->runtime_suspend;
742         else if (dev->bus && dev->bus->pm)
743                 cb = dev->bus->pm->runtime_suspend;
744         else
745                 cb = NULL;
746
747         if (!cb && dev->driver && dev->driver->pm)
748                 cb = dev->driver->pm->runtime_suspend;
749
750         return cb ? cb(dev) : 0;
751 }
752
753 /**
754  * __genpd_runtime_resume - walk the hierarchy of ->runtime_resume() callbacks
755  * @dev: Device to handle.
756  */
757 static int __genpd_runtime_resume(struct device *dev)
758 {
759         int (*cb)(struct device *__dev);
760
761         if (dev->type && dev->type->pm)
762                 cb = dev->type->pm->runtime_resume;
763         else if (dev->class && dev->class->pm)
764                 cb = dev->class->pm->runtime_resume;
765         else if (dev->bus && dev->bus->pm)
766                 cb = dev->bus->pm->runtime_resume;
767         else
768                 cb = NULL;
769
770         if (!cb && dev->driver && dev->driver->pm)
771                 cb = dev->driver->pm->runtime_resume;
772
773         return cb ? cb(dev) : 0;
774 }
775
776 /**
777  * genpd_runtime_suspend - Suspend a device belonging to I/O PM domain.
778  * @dev: Device to suspend.
779  *
780  * Carry out a runtime suspend of a device under the assumption that its
781  * pm_domain field points to the domain member of an object of type
782  * struct generic_pm_domain representing a PM domain consisting of I/O devices.
783  */
784 static int genpd_runtime_suspend(struct device *dev)
785 {
786         struct generic_pm_domain *genpd;
787         bool (*suspend_ok)(struct device *__dev);
788         struct gpd_timing_data *td = &dev_gpd_data(dev)->td;
789         bool runtime_pm = pm_runtime_enabled(dev);
790         ktime_t time_start;
791         s64 elapsed_ns;
792         int ret;
793
794         dev_dbg(dev, "%s()\n", __func__);
795
796         genpd = dev_to_genpd(dev);
797         if (IS_ERR(genpd))
798                 return -EINVAL;
799
800         /*
801          * A runtime PM centric subsystem/driver may re-use the runtime PM
802          * callbacks for other purposes than runtime PM. In those scenarios
803          * runtime PM is disabled. Under these circumstances, we shall skip
804          * validating/measuring the PM QoS latency.
805          */
806         suspend_ok = genpd->gov ? genpd->gov->suspend_ok : NULL;
807         if (runtime_pm && suspend_ok && !suspend_ok(dev))
808                 return -EBUSY;
809
810         /* Measure suspend latency. */
811         time_start = 0;
812         if (runtime_pm)
813                 time_start = ktime_get();
814
815         ret = __genpd_runtime_suspend(dev);
816         if (ret)
817                 return ret;
818
819         ret = genpd_stop_dev(genpd, dev);
820         if (ret) {
821                 __genpd_runtime_resume(dev);
822                 return ret;
823         }
824
825         /* Update suspend latency value if the measured time exceeds it. */
826         if (runtime_pm) {
827                 elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
828                 if (elapsed_ns > td->suspend_latency_ns) {
829                         td->suspend_latency_ns = elapsed_ns;
830                         dev_dbg(dev, "suspend latency exceeded, %lld ns\n",
831                                 elapsed_ns);
832                         genpd->max_off_time_changed = true;
833                         td->constraint_changed = true;
834                 }
835         }
836
837         /*
838          * If power.irq_safe is set, this routine may be run with
839          * IRQs disabled, so suspend only if the PM domain also is irq_safe.
840          */
841         if (irq_safe_dev_in_no_sleep_domain(dev, genpd))
842                 return 0;
843
844         genpd_lock(genpd);
845         genpd_power_off(genpd, true, 0);
846         genpd_unlock(genpd);
847
848         return 0;
849 }
850
851 /**
852  * genpd_runtime_resume - Resume a device belonging to I/O PM domain.
853  * @dev: Device to resume.
854  *
855  * Carry out a runtime resume of a device under the assumption that its
856  * pm_domain field points to the domain member of an object of type
857  * struct generic_pm_domain representing a PM domain consisting of I/O devices.
858  */
859 static int genpd_runtime_resume(struct device *dev)
860 {
861         struct generic_pm_domain *genpd;
862         struct gpd_timing_data *td = &dev_gpd_data(dev)->td;
863         bool runtime_pm = pm_runtime_enabled(dev);
864         ktime_t time_start;
865         s64 elapsed_ns;
866         int ret;
867         bool timed = true;
868
869         dev_dbg(dev, "%s()\n", __func__);
870
871         genpd = dev_to_genpd(dev);
872         if (IS_ERR(genpd))
873                 return -EINVAL;
874
875         /*
876          * As we don't power off a non IRQ safe domain, which holds
877          * an IRQ safe device, we don't need to restore power to it.
878          */
879         if (irq_safe_dev_in_no_sleep_domain(dev, genpd)) {
880                 timed = false;
881                 goto out;
882         }
883
884         genpd_lock(genpd);
885         ret = genpd_power_on(genpd, 0);
886         genpd_unlock(genpd);
887
888         if (ret)
889                 return ret;
890
891  out:
892         /* Measure resume latency. */
893         time_start = 0;
894         if (timed && runtime_pm)
895                 time_start = ktime_get();
896
897         ret = genpd_start_dev(genpd, dev);
898         if (ret)
899                 goto err_poweroff;
900
901         ret = __genpd_runtime_resume(dev);
902         if (ret)
903                 goto err_stop;
904
905         /* Update resume latency value if the measured time exceeds it. */
906         if (timed && runtime_pm) {
907                 elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
908                 if (elapsed_ns > td->resume_latency_ns) {
909                         td->resume_latency_ns = elapsed_ns;
910                         dev_dbg(dev, "resume latency exceeded, %lld ns\n",
911                                 elapsed_ns);
912                         genpd->max_off_time_changed = true;
913                         td->constraint_changed = true;
914                 }
915         }
916
917         return 0;
918
919 err_stop:
920         genpd_stop_dev(genpd, dev);
921 err_poweroff:
922         if (!pm_runtime_is_irq_safe(dev) ||
923                 (pm_runtime_is_irq_safe(dev) && genpd_is_irq_safe(genpd))) {
924                 genpd_lock(genpd);
925                 genpd_power_off(genpd, true, 0);
926                 genpd_unlock(genpd);
927         }
928
929         return ret;
930 }
931
932 static bool pd_ignore_unused;
933 static int __init pd_ignore_unused_setup(char *__unused)
934 {
935         pd_ignore_unused = true;
936         return 1;
937 }
938 __setup("pd_ignore_unused", pd_ignore_unused_setup);
939
940 /**
941  * genpd_power_off_unused - Power off all PM domains with no devices in use.
942  */
943 static int __init genpd_power_off_unused(void)
944 {
945         struct generic_pm_domain *genpd;
946
947         if (pd_ignore_unused) {
948                 pr_warn("genpd: Not disabling unused power domains\n");
949                 return 0;
950         }
951
952         mutex_lock(&gpd_list_lock);
953
954         list_for_each_entry(genpd, &gpd_list, gpd_list_node)
955                 genpd_queue_power_off_work(genpd);
956
957         mutex_unlock(&gpd_list_lock);
958
959         return 0;
960 }
961 late_initcall_sync(genpd_power_off_unused);
962
963 #ifdef CONFIG_PM_SLEEP
964
965 /**
966  * genpd_sync_power_off - Synchronously power off a PM domain and its parents.
967  * @genpd: PM domain to power off, if possible.
968  * @use_lock: use the lock.
969  * @depth: nesting count for lockdep.
970  *
971  * Check if the given PM domain can be powered off (during system suspend or
972  * hibernation) and do that if so.  Also, in that case propagate to its parents.
973  *
974  * This function is only called in "noirq" and "syscore" stages of system power
975  * transitions. The "noirq" callbacks may be executed asynchronously, thus in
976  * these cases the lock must be held.
977  */
978 static void genpd_sync_power_off(struct generic_pm_domain *genpd, bool use_lock,
979                                  unsigned int depth)
980 {
981         struct gpd_link *link;
982
983         if (!genpd_status_on(genpd) || genpd_is_always_on(genpd))
984                 return;
985
986         if (genpd->suspended_count != genpd->device_count
987             || atomic_read(&genpd->sd_count) > 0)
988                 return;
989
990         /* Choose the deepest state when suspending */
991         genpd->state_idx = genpd->state_count - 1;
992         if (_genpd_power_off(genpd, false))
993                 return;
994
995         genpd->status = GENPD_STATE_OFF;
996
997         list_for_each_entry(link, &genpd->child_links, child_node) {
998                 genpd_sd_counter_dec(link->parent);
999
1000                 if (use_lock)
1001                         genpd_lock_nested(link->parent, depth + 1);
1002
1003                 genpd_sync_power_off(link->parent, use_lock, depth + 1);
1004
1005                 if (use_lock)
1006                         genpd_unlock(link->parent);
1007         }
1008 }
1009
1010 /**
1011  * genpd_sync_power_on - Synchronously power on a PM domain and its parents.
1012  * @genpd: PM domain to power on.
1013  * @use_lock: use the lock.
1014  * @depth: nesting count for lockdep.
1015  *
1016  * This function is only called in "noirq" and "syscore" stages of system power
1017  * transitions. The "noirq" callbacks may be executed asynchronously, thus in
1018  * these cases the lock must be held.
1019  */
1020 static void genpd_sync_power_on(struct generic_pm_domain *genpd, bool use_lock,
1021                                 unsigned int depth)
1022 {
1023         struct gpd_link *link;
1024
1025         if (genpd_status_on(genpd))
1026                 return;
1027
1028         list_for_each_entry(link, &genpd->child_links, child_node) {
1029                 genpd_sd_counter_inc(link->parent);
1030
1031                 if (use_lock)
1032                         genpd_lock_nested(link->parent, depth + 1);
1033
1034                 genpd_sync_power_on(link->parent, use_lock, depth + 1);
1035
1036                 if (use_lock)
1037                         genpd_unlock(link->parent);
1038         }
1039
1040         _genpd_power_on(genpd, false);
1041         genpd->status = GENPD_STATE_ON;
1042 }
1043
1044 /**
1045  * resume_needed - Check whether to resume a device before system suspend.
1046  * @dev: Device to check.
1047  * @genpd: PM domain the device belongs to.
1048  *
1049  * There are two cases in which a device that can wake up the system from sleep
1050  * states should be resumed by genpd_prepare(): (1) if the device is enabled
1051  * to wake up the system and it has to remain active for this purpose while the
1052  * system is in the sleep state and (2) if the device is not enabled to wake up
1053  * the system from sleep states and it generally doesn't generate wakeup signals
1054  * by itself (those signals are generated on its behalf by other parts of the
1055  * system).  In the latter case it may be necessary to reconfigure the device's
1056  * wakeup settings during system suspend, because it may have been set up to
1057  * signal remote wakeup from the system's working state as needed by runtime PM.
1058  * Return 'true' in either of the above cases.
1059  */
1060 static bool resume_needed(struct device *dev,
1061                           const struct generic_pm_domain *genpd)
1062 {
1063         bool active_wakeup;
1064
1065         if (!device_can_wakeup(dev))
1066                 return false;
1067
1068         active_wakeup = genpd_is_active_wakeup(genpd);
1069         return device_may_wakeup(dev) ? active_wakeup : !active_wakeup;
1070 }
1071
1072 /**
1073  * genpd_prepare - Start power transition of a device in a PM domain.
1074  * @dev: Device to start the transition of.
1075  *
1076  * Start a power transition of a device (during a system-wide power transition)
1077  * under the assumption that its pm_domain field points to the domain member of
1078  * an object of type struct generic_pm_domain representing a PM domain
1079  * consisting of I/O devices.
1080  */
1081 static int genpd_prepare(struct device *dev)
1082 {
1083         struct generic_pm_domain *genpd;
1084         int ret;
1085
1086         dev_dbg(dev, "%s()\n", __func__);
1087
1088         genpd = dev_to_genpd(dev);
1089         if (IS_ERR(genpd))
1090                 return -EINVAL;
1091
1092         /*
1093          * If a wakeup request is pending for the device, it should be woken up
1094          * at this point and a system wakeup event should be reported if it's
1095          * set up to wake up the system from sleep states.
1096          */
1097         if (resume_needed(dev, genpd))
1098                 pm_runtime_resume(dev);
1099
1100         genpd_lock(genpd);
1101
1102         if (genpd->prepared_count++ == 0)
1103                 genpd->suspended_count = 0;
1104
1105         genpd_unlock(genpd);
1106
1107         ret = pm_generic_prepare(dev);
1108         if (ret < 0) {
1109                 genpd_lock(genpd);
1110
1111                 genpd->prepared_count--;
1112
1113                 genpd_unlock(genpd);
1114         }
1115
1116         /* Never return 1, as genpd don't cope with the direct_complete path. */
1117         return ret >= 0 ? 0 : ret;
1118 }
1119
1120 /**
1121  * genpd_finish_suspend - Completion of suspend or hibernation of device in an
1122  *   I/O pm domain.
1123  * @dev: Device to suspend.
1124  * @poweroff: Specifies if this is a poweroff_noirq or suspend_noirq callback.
1125  *
1126  * Stop the device and remove power from the domain if all devices in it have
1127  * been stopped.
1128  */
1129 static int genpd_finish_suspend(struct device *dev, bool poweroff)
1130 {
1131         struct generic_pm_domain *genpd;
1132         int ret = 0;
1133
1134         genpd = dev_to_genpd(dev);
1135         if (IS_ERR(genpd))
1136                 return -EINVAL;
1137
1138         if (poweroff)
1139                 ret = pm_generic_poweroff_noirq(dev);
1140         else
1141                 ret = pm_generic_suspend_noirq(dev);
1142         if (ret)
1143                 return ret;
1144
1145         if (dev->power.wakeup_path && genpd_is_active_wakeup(genpd))
1146                 return 0;
1147
1148         if (genpd->dev_ops.stop && genpd->dev_ops.start &&
1149             !pm_runtime_status_suspended(dev)) {
1150                 ret = genpd_stop_dev(genpd, dev);
1151                 if (ret) {
1152                         if (poweroff)
1153                                 pm_generic_restore_noirq(dev);
1154                         else
1155                                 pm_generic_resume_noirq(dev);
1156                         return ret;
1157                 }
1158         }
1159
1160         genpd_lock(genpd);
1161         genpd->suspended_count++;
1162         genpd_sync_power_off(genpd, true, 0);
1163         genpd_unlock(genpd);
1164
1165         return 0;
1166 }
1167
1168 /**
1169  * genpd_suspend_noirq - Completion of suspend of device in an I/O PM domain.
1170  * @dev: Device to suspend.
1171  *
1172  * Stop the device and remove power from the domain if all devices in it have
1173  * been stopped.
1174  */
1175 static int genpd_suspend_noirq(struct device *dev)
1176 {
1177         dev_dbg(dev, "%s()\n", __func__);
1178
1179         return genpd_finish_suspend(dev, false);
1180 }
1181
1182 /**
1183  * genpd_resume_noirq - Start of resume of device in an I/O PM domain.
1184  * @dev: Device to resume.
1185  *
1186  * Restore power to the device's PM domain, if necessary, and start the device.
1187  */
1188 static int genpd_resume_noirq(struct device *dev)
1189 {
1190         struct generic_pm_domain *genpd;
1191         int ret;
1192
1193         dev_dbg(dev, "%s()\n", __func__);
1194
1195         genpd = dev_to_genpd(dev);
1196         if (IS_ERR(genpd))
1197                 return -EINVAL;
1198
1199         if (dev->power.wakeup_path && genpd_is_active_wakeup(genpd))
1200                 return pm_generic_resume_noirq(dev);
1201
1202         genpd_lock(genpd);
1203         genpd_sync_power_on(genpd, true, 0);
1204         genpd->suspended_count--;
1205         genpd_unlock(genpd);
1206
1207         if (genpd->dev_ops.stop && genpd->dev_ops.start &&
1208             !pm_runtime_status_suspended(dev)) {
1209                 ret = genpd_start_dev(genpd, dev);
1210                 if (ret)
1211                         return ret;
1212         }
1213
1214         return pm_generic_resume_noirq(dev);
1215 }
1216
1217 /**
1218  * genpd_freeze_noirq - Completion of freezing a device in an I/O PM domain.
1219  * @dev: Device to freeze.
1220  *
1221  * Carry out a late freeze of a device under the assumption that its
1222  * pm_domain field points to the domain member of an object of type
1223  * struct generic_pm_domain representing a power domain consisting of I/O
1224  * devices.
1225  */
1226 static int genpd_freeze_noirq(struct device *dev)
1227 {
1228         const struct generic_pm_domain *genpd;
1229         int ret = 0;
1230
1231         dev_dbg(dev, "%s()\n", __func__);
1232
1233         genpd = dev_to_genpd(dev);
1234         if (IS_ERR(genpd))
1235                 return -EINVAL;
1236
1237         ret = pm_generic_freeze_noirq(dev);
1238         if (ret)
1239                 return ret;
1240
1241         if (genpd->dev_ops.stop && genpd->dev_ops.start &&
1242             !pm_runtime_status_suspended(dev))
1243                 ret = genpd_stop_dev(genpd, dev);
1244
1245         return ret;
1246 }
1247
1248 /**
1249  * genpd_thaw_noirq - Early thaw of device in an I/O PM domain.
1250  * @dev: Device to thaw.
1251  *
1252  * Start the device, unless power has been removed from the domain already
1253  * before the system transition.
1254  */
1255 static int genpd_thaw_noirq(struct device *dev)
1256 {
1257         const struct generic_pm_domain *genpd;
1258         int ret = 0;
1259
1260         dev_dbg(dev, "%s()\n", __func__);
1261
1262         genpd = dev_to_genpd(dev);
1263         if (IS_ERR(genpd))
1264                 return -EINVAL;
1265
1266         if (genpd->dev_ops.stop && genpd->dev_ops.start &&
1267             !pm_runtime_status_suspended(dev)) {
1268                 ret = genpd_start_dev(genpd, dev);
1269                 if (ret)
1270                         return ret;
1271         }
1272
1273         return pm_generic_thaw_noirq(dev);
1274 }
1275
1276 /**
1277  * genpd_poweroff_noirq - Completion of hibernation of device in an
1278  *   I/O PM domain.
1279  * @dev: Device to poweroff.
1280  *
1281  * Stop the device and remove power from the domain if all devices in it have
1282  * been stopped.
1283  */
1284 static int genpd_poweroff_noirq(struct device *dev)
1285 {
1286         dev_dbg(dev, "%s()\n", __func__);
1287
1288         return genpd_finish_suspend(dev, true);
1289 }
1290
1291 /**
1292  * genpd_restore_noirq - Start of restore of device in an I/O PM domain.
1293  * @dev: Device to resume.
1294  *
1295  * Make sure the domain will be in the same power state as before the
1296  * hibernation the system is resuming from and start the device if necessary.
1297  */
1298 static int genpd_restore_noirq(struct device *dev)
1299 {
1300         struct generic_pm_domain *genpd;
1301         int ret = 0;
1302
1303         dev_dbg(dev, "%s()\n", __func__);
1304
1305         genpd = dev_to_genpd(dev);
1306         if (IS_ERR(genpd))
1307                 return -EINVAL;
1308
1309         /*
1310          * At this point suspended_count == 0 means we are being run for the
1311          * first time for the given domain in the present cycle.
1312          */
1313         genpd_lock(genpd);
1314         if (genpd->suspended_count++ == 0) {
1315                 /*
1316                  * The boot kernel might put the domain into arbitrary state,
1317                  * so make it appear as powered off to genpd_sync_power_on(),
1318                  * so that it tries to power it on in case it was really off.
1319                  */
1320                 genpd->status = GENPD_STATE_OFF;
1321         }
1322
1323         genpd_sync_power_on(genpd, true, 0);
1324         genpd_unlock(genpd);
1325
1326         if (genpd->dev_ops.stop && genpd->dev_ops.start &&
1327             !pm_runtime_status_suspended(dev)) {
1328                 ret = genpd_start_dev(genpd, dev);
1329                 if (ret)
1330                         return ret;
1331         }
1332
1333         return pm_generic_restore_noirq(dev);
1334 }
1335
1336 /**
1337  * genpd_complete - Complete power transition of a device in a power domain.
1338  * @dev: Device to complete the transition of.
1339  *
1340  * Complete a power transition of a device (during a system-wide power
1341  * transition) under the assumption that its pm_domain field points to the
1342  * domain member of an object of type struct generic_pm_domain representing
1343  * a power domain consisting of I/O devices.
1344  */
1345 static void genpd_complete(struct device *dev)
1346 {
1347         struct generic_pm_domain *genpd;
1348
1349         dev_dbg(dev, "%s()\n", __func__);
1350
1351         genpd = dev_to_genpd(dev);
1352         if (IS_ERR(genpd))
1353                 return;
1354
1355         pm_generic_complete(dev);
1356
1357         genpd_lock(genpd);
1358
1359         genpd->prepared_count--;
1360         if (!genpd->prepared_count)
1361                 genpd_queue_power_off_work(genpd);
1362
1363         genpd_unlock(genpd);
1364 }
1365
1366 /**
1367  * genpd_syscore_switch - Switch power during system core suspend or resume.
1368  * @dev: Device that normally is marked as "always on" to switch power for.
1369  *
1370  * This routine may only be called during the system core (syscore) suspend or
1371  * resume phase for devices whose "always on" flags are set.
1372  */
1373 static void genpd_syscore_switch(struct device *dev, bool suspend)
1374 {
1375         struct generic_pm_domain *genpd;
1376
1377         genpd = dev_to_genpd_safe(dev);
1378         if (!genpd)
1379                 return;
1380
1381         if (suspend) {
1382                 genpd->suspended_count++;
1383                 genpd_sync_power_off(genpd, false, 0);
1384         } else {
1385                 genpd_sync_power_on(genpd, false, 0);
1386                 genpd->suspended_count--;
1387         }
1388 }
1389
1390 void pm_genpd_syscore_poweroff(struct device *dev)
1391 {
1392         genpd_syscore_switch(dev, true);
1393 }
1394 EXPORT_SYMBOL_GPL(pm_genpd_syscore_poweroff);
1395
1396 void pm_genpd_syscore_poweron(struct device *dev)
1397 {
1398         genpd_syscore_switch(dev, false);
1399 }
1400 EXPORT_SYMBOL_GPL(pm_genpd_syscore_poweron);
1401
1402 #else /* !CONFIG_PM_SLEEP */
1403
1404 #define genpd_prepare           NULL
1405 #define genpd_suspend_noirq     NULL
1406 #define genpd_resume_noirq      NULL
1407 #define genpd_freeze_noirq      NULL
1408 #define genpd_thaw_noirq        NULL
1409 #define genpd_poweroff_noirq    NULL
1410 #define genpd_restore_noirq     NULL
1411 #define genpd_complete          NULL
1412
1413 #endif /* CONFIG_PM_SLEEP */
1414
1415 static struct generic_pm_domain_data *genpd_alloc_dev_data(struct device *dev)
1416 {
1417         struct generic_pm_domain_data *gpd_data;
1418         int ret;
1419
1420         ret = dev_pm_get_subsys_data(dev);
1421         if (ret)
1422                 return ERR_PTR(ret);
1423
1424         gpd_data = kzalloc(sizeof(*gpd_data), GFP_KERNEL);
1425         if (!gpd_data) {
1426                 ret = -ENOMEM;
1427                 goto err_put;
1428         }
1429
1430         gpd_data->base.dev = dev;
1431         gpd_data->td.constraint_changed = true;
1432         gpd_data->td.effective_constraint_ns = PM_QOS_RESUME_LATENCY_NO_CONSTRAINT_NS;
1433         gpd_data->nb.notifier_call = genpd_dev_pm_qos_notifier;
1434
1435         spin_lock_irq(&dev->power.lock);
1436
1437         if (dev->power.subsys_data->domain_data) {
1438                 ret = -EINVAL;
1439                 goto err_free;
1440         }
1441
1442         dev->power.subsys_data->domain_data = &gpd_data->base;
1443
1444         spin_unlock_irq(&dev->power.lock);
1445
1446         return gpd_data;
1447
1448  err_free:
1449         spin_unlock_irq(&dev->power.lock);
1450         kfree(gpd_data);
1451  err_put:
1452         dev_pm_put_subsys_data(dev);
1453         return ERR_PTR(ret);
1454 }
1455
1456 static void genpd_free_dev_data(struct device *dev,
1457                                 struct generic_pm_domain_data *gpd_data)
1458 {
1459         spin_lock_irq(&dev->power.lock);
1460
1461         dev->power.subsys_data->domain_data = NULL;
1462
1463         spin_unlock_irq(&dev->power.lock);
1464
1465         kfree(gpd_data);
1466         dev_pm_put_subsys_data(dev);
1467 }
1468
1469 static void genpd_update_cpumask(struct generic_pm_domain *genpd,
1470                                  int cpu, bool set, unsigned int depth)
1471 {
1472         struct gpd_link *link;
1473
1474         if (!genpd_is_cpu_domain(genpd))
1475                 return;
1476
1477         list_for_each_entry(link, &genpd->child_links, child_node) {
1478                 struct generic_pm_domain *parent = link->parent;
1479
1480                 genpd_lock_nested(parent, depth + 1);
1481                 genpd_update_cpumask(parent, cpu, set, depth + 1);
1482                 genpd_unlock(parent);
1483         }
1484
1485         if (set)
1486                 cpumask_set_cpu(cpu, genpd->cpus);
1487         else
1488                 cpumask_clear_cpu(cpu, genpd->cpus);
1489 }
1490
1491 static void genpd_set_cpumask(struct generic_pm_domain *genpd, int cpu)
1492 {
1493         if (cpu >= 0)
1494                 genpd_update_cpumask(genpd, cpu, true, 0);
1495 }
1496
1497 static void genpd_clear_cpumask(struct generic_pm_domain *genpd, int cpu)
1498 {
1499         if (cpu >= 0)
1500                 genpd_update_cpumask(genpd, cpu, false, 0);
1501 }
1502
1503 static int genpd_get_cpu(struct generic_pm_domain *genpd, struct device *dev)
1504 {
1505         int cpu;
1506
1507         if (!genpd_is_cpu_domain(genpd))
1508                 return -1;
1509
1510         for_each_possible_cpu(cpu) {
1511                 if (get_cpu_device(cpu) == dev)
1512                         return cpu;
1513         }
1514
1515         return -1;
1516 }
1517
1518 static int genpd_add_device(struct generic_pm_domain *genpd, struct device *dev,
1519                             struct device *base_dev)
1520 {
1521         struct generic_pm_domain_data *gpd_data;
1522         int ret;
1523
1524         dev_dbg(dev, "%s()\n", __func__);
1525
1526         if (IS_ERR_OR_NULL(genpd) || IS_ERR_OR_NULL(dev))
1527                 return -EINVAL;
1528
1529         gpd_data = genpd_alloc_dev_data(dev);
1530         if (IS_ERR(gpd_data))
1531                 return PTR_ERR(gpd_data);
1532
1533         gpd_data->cpu = genpd_get_cpu(genpd, base_dev);
1534
1535         ret = genpd->attach_dev ? genpd->attach_dev(genpd, dev) : 0;
1536         if (ret)
1537                 goto out;
1538
1539         genpd_lock(genpd);
1540
1541         genpd_set_cpumask(genpd, gpd_data->cpu);
1542         dev_pm_domain_set(dev, &genpd->domain);
1543
1544         genpd->device_count++;
1545         genpd->max_off_time_changed = true;
1546
1547         list_add_tail(&gpd_data->base.list_node, &genpd->dev_list);
1548
1549         genpd_unlock(genpd);
1550  out:
1551         if (ret)
1552                 genpd_free_dev_data(dev, gpd_data);
1553         else
1554                 dev_pm_qos_add_notifier(dev, &gpd_data->nb,
1555                                         DEV_PM_QOS_RESUME_LATENCY);
1556
1557         return ret;
1558 }
1559
1560 /**
1561  * pm_genpd_add_device - Add a device to an I/O PM domain.
1562  * @genpd: PM domain to add the device to.
1563  * @dev: Device to be added.
1564  */
1565 int pm_genpd_add_device(struct generic_pm_domain *genpd, struct device *dev)
1566 {
1567         int ret;
1568
1569         mutex_lock(&gpd_list_lock);
1570         ret = genpd_add_device(genpd, dev, dev);
1571         mutex_unlock(&gpd_list_lock);
1572
1573         return ret;
1574 }
1575 EXPORT_SYMBOL_GPL(pm_genpd_add_device);
1576
1577 static int genpd_remove_device(struct generic_pm_domain *genpd,
1578                                struct device *dev)
1579 {
1580         struct generic_pm_domain_data *gpd_data;
1581         struct pm_domain_data *pdd;
1582         int ret = 0;
1583
1584         dev_dbg(dev, "%s()\n", __func__);
1585
1586         pdd = dev->power.subsys_data->domain_data;
1587         gpd_data = to_gpd_data(pdd);
1588         dev_pm_qos_remove_notifier(dev, &gpd_data->nb,
1589                                    DEV_PM_QOS_RESUME_LATENCY);
1590
1591         genpd_lock(genpd);
1592
1593         if (genpd->prepared_count > 0) {
1594                 ret = -EAGAIN;
1595                 goto out;
1596         }
1597
1598         genpd->device_count--;
1599         genpd->max_off_time_changed = true;
1600
1601         genpd_clear_cpumask(genpd, gpd_data->cpu);
1602         dev_pm_domain_set(dev, NULL);
1603
1604         list_del_init(&pdd->list_node);
1605
1606         genpd_unlock(genpd);
1607
1608         if (genpd->detach_dev)
1609                 genpd->detach_dev(genpd, dev);
1610
1611         genpd_free_dev_data(dev, gpd_data);
1612
1613         return 0;
1614
1615  out:
1616         genpd_unlock(genpd);
1617         dev_pm_qos_add_notifier(dev, &gpd_data->nb, DEV_PM_QOS_RESUME_LATENCY);
1618
1619         return ret;
1620 }
1621
1622 /**
1623  * pm_genpd_remove_device - Remove a device from an I/O PM domain.
1624  * @dev: Device to be removed.
1625  */
1626 int pm_genpd_remove_device(struct device *dev)
1627 {
1628         struct generic_pm_domain *genpd = dev_to_genpd_safe(dev);
1629
1630         if (!genpd)
1631                 return -EINVAL;
1632
1633         return genpd_remove_device(genpd, dev);
1634 }
1635 EXPORT_SYMBOL_GPL(pm_genpd_remove_device);
1636
1637 /**
1638  * dev_pm_genpd_add_notifier - Add a genpd power on/off notifier for @dev
1639  *
1640  * @dev: Device that should be associated with the notifier
1641  * @nb: The notifier block to register
1642  *
1643  * Users may call this function to add a genpd power on/off notifier for an
1644  * attached @dev. Only one notifier per device is allowed. The notifier is
1645  * sent when genpd is powering on/off the PM domain.
1646  *
1647  * It is assumed that the user guarantee that the genpd wouldn't be detached
1648  * while this routine is getting called.
1649  *
1650  * Returns 0 on success and negative error values on failures.
1651  */
1652 int dev_pm_genpd_add_notifier(struct device *dev, struct notifier_block *nb)
1653 {
1654         struct generic_pm_domain *genpd;
1655         struct generic_pm_domain_data *gpd_data;
1656         int ret;
1657
1658         genpd = dev_to_genpd_safe(dev);
1659         if (!genpd)
1660                 return -ENODEV;
1661
1662         if (WARN_ON(!dev->power.subsys_data ||
1663                      !dev->power.subsys_data->domain_data))
1664                 return -EINVAL;
1665
1666         gpd_data = to_gpd_data(dev->power.subsys_data->domain_data);
1667         if (gpd_data->power_nb)
1668                 return -EEXIST;
1669
1670         genpd_lock(genpd);
1671         ret = raw_notifier_chain_register(&genpd->power_notifiers, nb);
1672         genpd_unlock(genpd);
1673
1674         if (ret) {
1675                 dev_warn(dev, "failed to add notifier for PM domain %s\n",
1676                          genpd->name);
1677                 return ret;
1678         }
1679
1680         gpd_data->power_nb = nb;
1681         return 0;
1682 }
1683 EXPORT_SYMBOL_GPL(dev_pm_genpd_add_notifier);
1684
1685 /**
1686  * dev_pm_genpd_remove_notifier - Remove a genpd power on/off notifier for @dev
1687  *
1688  * @dev: Device that is associated with the notifier
1689  *
1690  * Users may call this function to remove a genpd power on/off notifier for an
1691  * attached @dev.
1692  *
1693  * It is assumed that the user guarantee that the genpd wouldn't be detached
1694  * while this routine is getting called.
1695  *
1696  * Returns 0 on success and negative error values on failures.
1697  */
1698 int dev_pm_genpd_remove_notifier(struct device *dev)
1699 {
1700         struct generic_pm_domain *genpd;
1701         struct generic_pm_domain_data *gpd_data;
1702         int ret;
1703
1704         genpd = dev_to_genpd_safe(dev);
1705         if (!genpd)
1706                 return -ENODEV;
1707
1708         if (WARN_ON(!dev->power.subsys_data ||
1709                      !dev->power.subsys_data->domain_data))
1710                 return -EINVAL;
1711
1712         gpd_data = to_gpd_data(dev->power.subsys_data->domain_data);
1713         if (!gpd_data->power_nb)
1714                 return -ENODEV;
1715
1716         genpd_lock(genpd);
1717         ret = raw_notifier_chain_unregister(&genpd->power_notifiers,
1718                                             gpd_data->power_nb);
1719         genpd_unlock(genpd);
1720
1721         if (ret) {
1722                 dev_warn(dev, "failed to remove notifier for PM domain %s\n",
1723                          genpd->name);
1724                 return ret;
1725         }
1726
1727         gpd_data->power_nb = NULL;
1728         return 0;
1729 }
1730 EXPORT_SYMBOL_GPL(dev_pm_genpd_remove_notifier);
1731
1732 static int genpd_add_subdomain(struct generic_pm_domain *genpd,
1733                                struct generic_pm_domain *subdomain)
1734 {
1735         struct gpd_link *link, *itr;
1736         int ret = 0;
1737
1738         if (IS_ERR_OR_NULL(genpd) || IS_ERR_OR_NULL(subdomain)
1739             || genpd == subdomain)
1740                 return -EINVAL;
1741
1742         /*
1743          * If the domain can be powered on/off in an IRQ safe
1744          * context, ensure that the subdomain can also be
1745          * powered on/off in that context.
1746          */
1747         if (!genpd_is_irq_safe(genpd) && genpd_is_irq_safe(subdomain)) {
1748                 WARN(1, "Parent %s of subdomain %s must be IRQ safe\n",
1749                                 genpd->name, subdomain->name);
1750                 return -EINVAL;
1751         }
1752
1753         link = kzalloc(sizeof(*link), GFP_KERNEL);
1754         if (!link)
1755                 return -ENOMEM;
1756
1757         genpd_lock(subdomain);
1758         genpd_lock_nested(genpd, SINGLE_DEPTH_NESTING);
1759
1760         if (!genpd_status_on(genpd) && genpd_status_on(subdomain)) {
1761                 ret = -EINVAL;
1762                 goto out;
1763         }
1764
1765         list_for_each_entry(itr, &genpd->parent_links, parent_node) {
1766                 if (itr->child == subdomain && itr->parent == genpd) {
1767                         ret = -EINVAL;
1768                         goto out;
1769                 }
1770         }
1771
1772         link->parent = genpd;
1773         list_add_tail(&link->parent_node, &genpd->parent_links);
1774         link->child = subdomain;
1775         list_add_tail(&link->child_node, &subdomain->child_links);
1776         if (genpd_status_on(subdomain))
1777                 genpd_sd_counter_inc(genpd);
1778
1779  out:
1780         genpd_unlock(genpd);
1781         genpd_unlock(subdomain);
1782         if (ret)
1783                 kfree(link);
1784         return ret;
1785 }
1786
1787 /**
1788  * pm_genpd_add_subdomain - Add a subdomain to an I/O PM domain.
1789  * @genpd: Leader PM domain to add the subdomain to.
1790  * @subdomain: Subdomain to be added.
1791  */
1792 int pm_genpd_add_subdomain(struct generic_pm_domain *genpd,
1793                            struct generic_pm_domain *subdomain)
1794 {
1795         int ret;
1796
1797         mutex_lock(&gpd_list_lock);
1798         ret = genpd_add_subdomain(genpd, subdomain);
1799         mutex_unlock(&gpd_list_lock);
1800
1801         return ret;
1802 }
1803 EXPORT_SYMBOL_GPL(pm_genpd_add_subdomain);
1804
1805 /**
1806  * pm_genpd_remove_subdomain - Remove a subdomain from an I/O PM domain.
1807  * @genpd: Leader PM domain to remove the subdomain from.
1808  * @subdomain: Subdomain to be removed.
1809  */
1810 int pm_genpd_remove_subdomain(struct generic_pm_domain *genpd,
1811                               struct generic_pm_domain *subdomain)
1812 {
1813         struct gpd_link *l, *link;
1814         int ret = -EINVAL;
1815
1816         if (IS_ERR_OR_NULL(genpd) || IS_ERR_OR_NULL(subdomain))
1817                 return -EINVAL;
1818
1819         genpd_lock(subdomain);
1820         genpd_lock_nested(genpd, SINGLE_DEPTH_NESTING);
1821
1822         if (!list_empty(&subdomain->parent_links) || subdomain->device_count) {
1823                 pr_warn("%s: unable to remove subdomain %s\n",
1824                         genpd->name, subdomain->name);
1825                 ret = -EBUSY;
1826                 goto out;
1827         }
1828
1829         list_for_each_entry_safe(link, l, &genpd->parent_links, parent_node) {
1830                 if (link->child != subdomain)
1831                         continue;
1832
1833                 list_del(&link->parent_node);
1834                 list_del(&link->child_node);
1835                 kfree(link);
1836                 if (genpd_status_on(subdomain))
1837                         genpd_sd_counter_dec(genpd);
1838
1839                 ret = 0;
1840                 break;
1841         }
1842
1843 out:
1844         genpd_unlock(genpd);
1845         genpd_unlock(subdomain);
1846
1847         return ret;
1848 }
1849 EXPORT_SYMBOL_GPL(pm_genpd_remove_subdomain);
1850
1851 static void genpd_free_default_power_state(struct genpd_power_state *states,
1852                                            unsigned int state_count)
1853 {
1854         kfree(states);
1855 }
1856
1857 static int genpd_set_default_power_state(struct generic_pm_domain *genpd)
1858 {
1859         struct genpd_power_state *state;
1860
1861         state = kzalloc(sizeof(*state), GFP_KERNEL);
1862         if (!state)
1863                 return -ENOMEM;
1864
1865         genpd->states = state;
1866         genpd->state_count = 1;
1867         genpd->free_states = genpd_free_default_power_state;
1868
1869         return 0;
1870 }
1871
1872 static void genpd_lock_init(struct generic_pm_domain *genpd)
1873 {
1874         if (genpd->flags & GENPD_FLAG_IRQ_SAFE) {
1875                 spin_lock_init(&genpd->slock);
1876                 genpd->lock_ops = &genpd_spin_ops;
1877         } else {
1878                 mutex_init(&genpd->mlock);
1879                 genpd->lock_ops = &genpd_mtx_ops;
1880         }
1881 }
1882
1883 /**
1884  * pm_genpd_init - Initialize a generic I/O PM domain object.
1885  * @genpd: PM domain object to initialize.
1886  * @gov: PM domain governor to associate with the domain (may be NULL).
1887  * @is_off: Initial value of the domain's power_is_off field.
1888  *
1889  * Returns 0 on successful initialization, else a negative error code.
1890  */
1891 int pm_genpd_init(struct generic_pm_domain *genpd,
1892                   struct dev_power_governor *gov, bool is_off)
1893 {
1894         int ret;
1895
1896         if (IS_ERR_OR_NULL(genpd))
1897                 return -EINVAL;
1898
1899         INIT_LIST_HEAD(&genpd->parent_links);
1900         INIT_LIST_HEAD(&genpd->child_links);
1901         INIT_LIST_HEAD(&genpd->dev_list);
1902         RAW_INIT_NOTIFIER_HEAD(&genpd->power_notifiers);
1903         genpd_lock_init(genpd);
1904         genpd->gov = gov;
1905         INIT_WORK(&genpd->power_off_work, genpd_power_off_work_fn);
1906         atomic_set(&genpd->sd_count, 0);
1907         genpd->status = is_off ? GENPD_STATE_OFF : GENPD_STATE_ON;
1908         genpd->device_count = 0;
1909         genpd->max_off_time_ns = -1;
1910         genpd->max_off_time_changed = true;
1911         genpd->provider = NULL;
1912         genpd->has_provider = false;
1913         genpd->accounting_time = ktime_get();
1914         genpd->domain.ops.runtime_suspend = genpd_runtime_suspend;
1915         genpd->domain.ops.runtime_resume = genpd_runtime_resume;
1916         genpd->domain.ops.prepare = genpd_prepare;
1917         genpd->domain.ops.suspend_noirq = genpd_suspend_noirq;
1918         genpd->domain.ops.resume_noirq = genpd_resume_noirq;
1919         genpd->domain.ops.freeze_noirq = genpd_freeze_noirq;
1920         genpd->domain.ops.thaw_noirq = genpd_thaw_noirq;
1921         genpd->domain.ops.poweroff_noirq = genpd_poweroff_noirq;
1922         genpd->domain.ops.restore_noirq = genpd_restore_noirq;
1923         genpd->domain.ops.complete = genpd_complete;
1924         genpd->domain.start = genpd_dev_pm_start;
1925
1926         if (genpd->flags & GENPD_FLAG_PM_CLK) {
1927                 genpd->dev_ops.stop = pm_clk_suspend;
1928                 genpd->dev_ops.start = pm_clk_resume;
1929         }
1930
1931         /* Always-on domains must be powered on at initialization. */
1932         if ((genpd_is_always_on(genpd) || genpd_is_rpm_always_on(genpd)) &&
1933                         !genpd_status_on(genpd))
1934                 return -EINVAL;
1935
1936         if (genpd_is_cpu_domain(genpd) &&
1937             !zalloc_cpumask_var(&genpd->cpus, GFP_KERNEL))
1938                 return -ENOMEM;
1939
1940         /* Use only one "off" state if there were no states declared */
1941         if (genpd->state_count == 0) {
1942                 ret = genpd_set_default_power_state(genpd);
1943                 if (ret) {
1944                         if (genpd_is_cpu_domain(genpd))
1945                                 free_cpumask_var(genpd->cpus);
1946                         return ret;
1947                 }
1948         } else if (!gov && genpd->state_count > 1) {
1949                 pr_warn("%s: no governor for states\n", genpd->name);
1950         }
1951
1952         device_initialize(&genpd->dev);
1953         dev_set_name(&genpd->dev, "%s", genpd->name);
1954
1955         mutex_lock(&gpd_list_lock);
1956         list_add(&genpd->gpd_list_node, &gpd_list);
1957         mutex_unlock(&gpd_list_lock);
1958
1959         return 0;
1960 }
1961 EXPORT_SYMBOL_GPL(pm_genpd_init);
1962
1963 static int genpd_remove(struct generic_pm_domain *genpd)
1964 {
1965         struct gpd_link *l, *link;
1966
1967         if (IS_ERR_OR_NULL(genpd))
1968                 return -EINVAL;
1969
1970         genpd_lock(genpd);
1971
1972         if (genpd->has_provider) {
1973                 genpd_unlock(genpd);
1974                 pr_err("Provider present, unable to remove %s\n", genpd->name);
1975                 return -EBUSY;
1976         }
1977
1978         if (!list_empty(&genpd->parent_links) || genpd->device_count) {
1979                 genpd_unlock(genpd);
1980                 pr_err("%s: unable to remove %s\n", __func__, genpd->name);
1981                 return -EBUSY;
1982         }
1983
1984         list_for_each_entry_safe(link, l, &genpd->child_links, child_node) {
1985                 list_del(&link->parent_node);
1986                 list_del(&link->child_node);
1987                 kfree(link);
1988         }
1989
1990         list_del(&genpd->gpd_list_node);
1991         genpd_unlock(genpd);
1992         cancel_work_sync(&genpd->power_off_work);
1993         if (genpd_is_cpu_domain(genpd))
1994                 free_cpumask_var(genpd->cpus);
1995         if (genpd->free_states)
1996                 genpd->free_states(genpd->states, genpd->state_count);
1997
1998         pr_debug("%s: removed %s\n", __func__, genpd->name);
1999
2000         return 0;
2001 }
2002
2003 /**
2004  * pm_genpd_remove - Remove a generic I/O PM domain
2005  * @genpd: Pointer to PM domain that is to be removed.
2006  *
2007  * To remove the PM domain, this function:
2008  *  - Removes the PM domain as a subdomain to any parent domains,
2009  *    if it was added.
2010  *  - Removes the PM domain from the list of registered PM domains.
2011  *
2012  * The PM domain will only be removed, if the associated provider has
2013  * been removed, it is not a parent to any other PM domain and has no
2014  * devices associated with it.
2015  */
2016 int pm_genpd_remove(struct generic_pm_domain *genpd)
2017 {
2018         int ret;
2019
2020         mutex_lock(&gpd_list_lock);
2021         ret = genpd_remove(genpd);
2022         mutex_unlock(&gpd_list_lock);
2023
2024         return ret;
2025 }
2026 EXPORT_SYMBOL_GPL(pm_genpd_remove);
2027
2028 #ifdef CONFIG_PM_GENERIC_DOMAINS_OF
2029
2030 /*
2031  * Device Tree based PM domain providers.
2032  *
2033  * The code below implements generic device tree based PM domain providers that
2034  * bind device tree nodes with generic PM domains registered in the system.
2035  *
2036  * Any driver that registers generic PM domains and needs to support binding of
2037  * devices to these domains is supposed to register a PM domain provider, which
2038  * maps a PM domain specifier retrieved from the device tree to a PM domain.
2039  *
2040  * Two simple mapping functions have been provided for convenience:
2041  *  - genpd_xlate_simple() for 1:1 device tree node to PM domain mapping.
2042  *  - genpd_xlate_onecell() for mapping of multiple PM domains per node by
2043  *    index.
2044  */
2045
2046 /**
2047  * struct of_genpd_provider - PM domain provider registration structure
2048  * @link: Entry in global list of PM domain providers
2049  * @node: Pointer to device tree node of PM domain provider
2050  * @xlate: Provider-specific xlate callback mapping a set of specifier cells
2051  *         into a PM domain.
2052  * @data: context pointer to be passed into @xlate callback
2053  */
2054 struct of_genpd_provider {
2055         struct list_head link;
2056         struct device_node *node;
2057         genpd_xlate_t xlate;
2058         void *data;
2059 };
2060
2061 /* List of registered PM domain providers. */
2062 static LIST_HEAD(of_genpd_providers);
2063 /* Mutex to protect the list above. */
2064 static DEFINE_MUTEX(of_genpd_mutex);
2065
2066 /**
2067  * genpd_xlate_simple() - Xlate function for direct node-domain mapping
2068  * @genpdspec: OF phandle args to map into a PM domain
2069  * @data: xlate function private data - pointer to struct generic_pm_domain
2070  *
2071  * This is a generic xlate function that can be used to model PM domains that
2072  * have their own device tree nodes. The private data of xlate function needs
2073  * to be a valid pointer to struct generic_pm_domain.
2074  */
2075 static struct generic_pm_domain *genpd_xlate_simple(
2076                                         struct of_phandle_args *genpdspec,
2077                                         void *data)
2078 {
2079         return data;
2080 }
2081
2082 /**
2083  * genpd_xlate_onecell() - Xlate function using a single index.
2084  * @genpdspec: OF phandle args to map into a PM domain
2085  * @data: xlate function private data - pointer to struct genpd_onecell_data
2086  *
2087  * This is a generic xlate function that can be used to model simple PM domain
2088  * controllers that have one device tree node and provide multiple PM domains.
2089  * A single cell is used as an index into an array of PM domains specified in
2090  * the genpd_onecell_data struct when registering the provider.
2091  */
2092 static struct generic_pm_domain *genpd_xlate_onecell(
2093                                         struct of_phandle_args *genpdspec,
2094                                         void *data)
2095 {
2096         struct genpd_onecell_data *genpd_data = data;
2097         unsigned int idx = genpdspec->args[0];
2098
2099         if (genpdspec->args_count != 1)
2100                 return ERR_PTR(-EINVAL);
2101
2102         if (idx >= genpd_data->num_domains) {
2103                 pr_err("%s: invalid domain index %u\n", __func__, idx);
2104                 return ERR_PTR(-EINVAL);
2105         }
2106
2107         if (!genpd_data->domains[idx])
2108                 return ERR_PTR(-ENOENT);
2109
2110         return genpd_data->domains[idx];
2111 }
2112
2113 /**
2114  * genpd_add_provider() - Register a PM domain provider for a node
2115  * @np: Device node pointer associated with the PM domain provider.
2116  * @xlate: Callback for decoding PM domain from phandle arguments.
2117  * @data: Context pointer for @xlate callback.
2118  */
2119 static int genpd_add_provider(struct device_node *np, genpd_xlate_t xlate,
2120                               void *data)
2121 {
2122         struct of_genpd_provider *cp;
2123
2124         cp = kzalloc(sizeof(*cp), GFP_KERNEL);
2125         if (!cp)
2126                 return -ENOMEM;
2127
2128         cp->node = of_node_get(np);
2129         cp->data = data;
2130         cp->xlate = xlate;
2131
2132         mutex_lock(&of_genpd_mutex);
2133         list_add(&cp->link, &of_genpd_providers);
2134         mutex_unlock(&of_genpd_mutex);
2135         pr_debug("Added domain provider from %pOF\n", np);
2136
2137         return 0;
2138 }
2139
2140 static bool genpd_present(const struct generic_pm_domain *genpd)
2141 {
2142         const struct generic_pm_domain *gpd;
2143
2144         list_for_each_entry(gpd, &gpd_list, gpd_list_node)
2145                 if (gpd == genpd)
2146                         return true;
2147         return false;
2148 }
2149
2150 /**
2151  * of_genpd_add_provider_simple() - Register a simple PM domain provider
2152  * @np: Device node pointer associated with the PM domain provider.
2153  * @genpd: Pointer to PM domain associated with the PM domain provider.
2154  */
2155 int of_genpd_add_provider_simple(struct device_node *np,
2156                                  struct generic_pm_domain *genpd)
2157 {
2158         int ret = -EINVAL;
2159
2160         if (!np || !genpd)
2161                 return -EINVAL;
2162
2163         mutex_lock(&gpd_list_lock);
2164
2165         if (!genpd_present(genpd))
2166                 goto unlock;
2167
2168         genpd->dev.of_node = np;
2169
2170         /* Parse genpd OPP table */
2171         if (genpd->set_performance_state) {
2172                 ret = dev_pm_opp_of_add_table(&genpd->dev);
2173                 if (ret) {
2174                         if (ret != -EPROBE_DEFER)
2175                                 dev_err(&genpd->dev, "Failed to add OPP table: %d\n",
2176                                         ret);
2177                         goto unlock;
2178                 }
2179
2180                 /*
2181                  * Save table for faster processing while setting performance
2182                  * state.
2183                  */
2184                 genpd->opp_table = dev_pm_opp_get_opp_table(&genpd->dev);
2185                 WARN_ON(IS_ERR(genpd->opp_table));
2186         }
2187
2188         ret = genpd_add_provider(np, genpd_xlate_simple, genpd);
2189         if (ret) {
2190                 if (genpd->set_performance_state) {
2191                         dev_pm_opp_put_opp_table(genpd->opp_table);
2192                         dev_pm_opp_of_remove_table(&genpd->dev);
2193                 }
2194
2195                 goto unlock;
2196         }
2197
2198         genpd->provider = &np->fwnode;
2199         genpd->has_provider = true;
2200
2201 unlock:
2202         mutex_unlock(&gpd_list_lock);
2203
2204         return ret;
2205 }
2206 EXPORT_SYMBOL_GPL(of_genpd_add_provider_simple);
2207
2208 /**
2209  * of_genpd_add_provider_onecell() - Register a onecell PM domain provider
2210  * @np: Device node pointer associated with the PM domain provider.
2211  * @data: Pointer to the data associated with the PM domain provider.
2212  */
2213 int of_genpd_add_provider_onecell(struct device_node *np,
2214                                   struct genpd_onecell_data *data)
2215 {
2216         struct generic_pm_domain *genpd;
2217         unsigned int i;
2218         int ret = -EINVAL;
2219
2220         if (!np || !data)
2221                 return -EINVAL;
2222
2223         mutex_lock(&gpd_list_lock);
2224
2225         if (!data->xlate)
2226                 data->xlate = genpd_xlate_onecell;
2227
2228         for (i = 0; i < data->num_domains; i++) {
2229                 genpd = data->domains[i];
2230
2231                 if (!genpd)
2232                         continue;
2233                 if (!genpd_present(genpd))
2234                         goto error;
2235
2236                 genpd->dev.of_node = np;
2237
2238                 /* Parse genpd OPP table */
2239                 if (genpd->set_performance_state) {
2240                         ret = dev_pm_opp_of_add_table_indexed(&genpd->dev, i);
2241                         if (ret) {
2242                                 if (ret != -EPROBE_DEFER)
2243                                         dev_err(&genpd->dev, "Failed to add OPP table for index %d: %d\n",
2244                                                 i, ret);
2245                                 goto error;
2246                         }
2247
2248                         /*
2249                          * Save table for faster processing while setting
2250                          * performance state.
2251                          */
2252                         genpd->opp_table = dev_pm_opp_get_opp_table_indexed(&genpd->dev, i);
2253                         WARN_ON(IS_ERR(genpd->opp_table));
2254                 }
2255
2256                 genpd->provider = &np->fwnode;
2257                 genpd->has_provider = true;
2258         }
2259
2260         ret = genpd_add_provider(np, data->xlate, data);
2261         if (ret < 0)
2262                 goto error;
2263
2264         mutex_unlock(&gpd_list_lock);
2265
2266         return 0;
2267
2268 error:
2269         while (i--) {
2270                 genpd = data->domains[i];
2271
2272                 if (!genpd)
2273                         continue;
2274
2275                 genpd->provider = NULL;
2276                 genpd->has_provider = false;
2277
2278                 if (genpd->set_performance_state) {
2279                         dev_pm_opp_put_opp_table(genpd->opp_table);
2280                         dev_pm_opp_of_remove_table(&genpd->dev);
2281                 }
2282         }
2283
2284         mutex_unlock(&gpd_list_lock);
2285
2286         return ret;
2287 }
2288 EXPORT_SYMBOL_GPL(of_genpd_add_provider_onecell);
2289
2290 /**
2291  * of_genpd_del_provider() - Remove a previously registered PM domain provider
2292  * @np: Device node pointer associated with the PM domain provider
2293  */
2294 void of_genpd_del_provider(struct device_node *np)
2295 {
2296         struct of_genpd_provider *cp, *tmp;
2297         struct generic_pm_domain *gpd;
2298
2299         mutex_lock(&gpd_list_lock);
2300         mutex_lock(&of_genpd_mutex);
2301         list_for_each_entry_safe(cp, tmp, &of_genpd_providers, link) {
2302                 if (cp->node == np) {
2303                         /*
2304                          * For each PM domain associated with the
2305                          * provider, set the 'has_provider' to false
2306                          * so that the PM domain can be safely removed.
2307                          */
2308                         list_for_each_entry(gpd, &gpd_list, gpd_list_node) {
2309                                 if (gpd->provider == &np->fwnode) {
2310                                         gpd->has_provider = false;
2311
2312                                         if (!gpd->set_performance_state)
2313                                                 continue;
2314
2315                                         dev_pm_opp_put_opp_table(gpd->opp_table);
2316                                         dev_pm_opp_of_remove_table(&gpd->dev);
2317                                 }
2318                         }
2319
2320                         list_del(&cp->link);
2321                         of_node_put(cp->node);
2322                         kfree(cp);
2323                         break;
2324                 }
2325         }
2326         mutex_unlock(&of_genpd_mutex);
2327         mutex_unlock(&gpd_list_lock);
2328 }
2329 EXPORT_SYMBOL_GPL(of_genpd_del_provider);
2330
2331 /**
2332  * genpd_get_from_provider() - Look-up PM domain
2333  * @genpdspec: OF phandle args to use for look-up
2334  *
2335  * Looks for a PM domain provider under the node specified by @genpdspec and if
2336  * found, uses xlate function of the provider to map phandle args to a PM
2337  * domain.
2338  *
2339  * Returns a valid pointer to struct generic_pm_domain on success or ERR_PTR()
2340  * on failure.
2341  */
2342 static struct generic_pm_domain *genpd_get_from_provider(
2343                                         struct of_phandle_args *genpdspec)
2344 {
2345         struct generic_pm_domain *genpd = ERR_PTR(-ENOENT);
2346         struct of_genpd_provider *provider;
2347
2348         if (!genpdspec)
2349                 return ERR_PTR(-EINVAL);
2350
2351         mutex_lock(&of_genpd_mutex);
2352
2353         /* Check if we have such a provider in our array */
2354         list_for_each_entry(provider, &of_genpd_providers, link) {
2355                 if (provider->node == genpdspec->np)
2356                         genpd = provider->xlate(genpdspec, provider->data);
2357                 if (!IS_ERR(genpd))
2358                         break;
2359         }
2360
2361         mutex_unlock(&of_genpd_mutex);
2362
2363         return genpd;
2364 }
2365
2366 /**
2367  * of_genpd_add_device() - Add a device to an I/O PM domain
2368  * @genpdspec: OF phandle args to use for look-up PM domain
2369  * @dev: Device to be added.
2370  *
2371  * Looks-up an I/O PM domain based upon phandle args provided and adds
2372  * the device to the PM domain. Returns a negative error code on failure.
2373  */
2374 int of_genpd_add_device(struct of_phandle_args *genpdspec, struct device *dev)
2375 {
2376         struct generic_pm_domain *genpd;
2377         int ret;
2378
2379         mutex_lock(&gpd_list_lock);
2380
2381         genpd = genpd_get_from_provider(genpdspec);
2382         if (IS_ERR(genpd)) {
2383                 ret = PTR_ERR(genpd);
2384                 goto out;
2385         }
2386
2387         ret = genpd_add_device(genpd, dev, dev);
2388
2389 out:
2390         mutex_unlock(&gpd_list_lock);
2391
2392         return ret;
2393 }
2394 EXPORT_SYMBOL_GPL(of_genpd_add_device);
2395
2396 /**
2397  * of_genpd_add_subdomain - Add a subdomain to an I/O PM domain.
2398  * @parent_spec: OF phandle args to use for parent PM domain look-up
2399  * @subdomain_spec: OF phandle args to use for subdomain look-up
2400  *
2401  * Looks-up a parent PM domain and subdomain based upon phandle args
2402  * provided and adds the subdomain to the parent PM domain. Returns a
2403  * negative error code on failure.
2404  */
2405 int of_genpd_add_subdomain(struct of_phandle_args *parent_spec,
2406                            struct of_phandle_args *subdomain_spec)
2407 {
2408         struct generic_pm_domain *parent, *subdomain;
2409         int ret;
2410
2411         mutex_lock(&gpd_list_lock);
2412
2413         parent = genpd_get_from_provider(parent_spec);
2414         if (IS_ERR(parent)) {
2415                 ret = PTR_ERR(parent);
2416                 goto out;
2417         }
2418
2419         subdomain = genpd_get_from_provider(subdomain_spec);
2420         if (IS_ERR(subdomain)) {
2421                 ret = PTR_ERR(subdomain);
2422                 goto out;
2423         }
2424
2425         ret = genpd_add_subdomain(parent, subdomain);
2426
2427 out:
2428         mutex_unlock(&gpd_list_lock);
2429
2430         return ret;
2431 }
2432 EXPORT_SYMBOL_GPL(of_genpd_add_subdomain);
2433
2434 /**
2435  * of_genpd_remove_subdomain - Remove a subdomain from an I/O PM domain.
2436  * @parent_spec: OF phandle args to use for parent PM domain look-up
2437  * @subdomain_spec: OF phandle args to use for subdomain look-up
2438  *
2439  * Looks-up a parent PM domain and subdomain based upon phandle args
2440  * provided and removes the subdomain from the parent PM domain. Returns a
2441  * negative error code on failure.
2442  */
2443 int of_genpd_remove_subdomain(struct of_phandle_args *parent_spec,
2444                               struct of_phandle_args *subdomain_spec)
2445 {
2446         struct generic_pm_domain *parent, *subdomain;
2447         int ret;
2448
2449         mutex_lock(&gpd_list_lock);
2450
2451         parent = genpd_get_from_provider(parent_spec);
2452         if (IS_ERR(parent)) {
2453                 ret = PTR_ERR(parent);
2454                 goto out;
2455         }
2456
2457         subdomain = genpd_get_from_provider(subdomain_spec);
2458         if (IS_ERR(subdomain)) {
2459                 ret = PTR_ERR(subdomain);
2460                 goto out;
2461         }
2462
2463         ret = pm_genpd_remove_subdomain(parent, subdomain);
2464
2465 out:
2466         mutex_unlock(&gpd_list_lock);
2467
2468         return ret;
2469 }
2470 EXPORT_SYMBOL_GPL(of_genpd_remove_subdomain);
2471
2472 /**
2473  * of_genpd_remove_last - Remove the last PM domain registered for a provider
2474  * @provider: Pointer to device structure associated with provider
2475  *
2476  * Find the last PM domain that was added by a particular provider and
2477  * remove this PM domain from the list of PM domains. The provider is
2478  * identified by the 'provider' device structure that is passed. The PM
2479  * domain will only be removed, if the provider associated with domain
2480  * has been removed.
2481  *
2482  * Returns a valid pointer to struct generic_pm_domain on success or
2483  * ERR_PTR() on failure.
2484  */
2485 struct generic_pm_domain *of_genpd_remove_last(struct device_node *np)
2486 {
2487         struct generic_pm_domain *gpd, *tmp, *genpd = ERR_PTR(-ENOENT);
2488         int ret;
2489
2490         if (IS_ERR_OR_NULL(np))
2491                 return ERR_PTR(-EINVAL);
2492
2493         mutex_lock(&gpd_list_lock);
2494         list_for_each_entry_safe(gpd, tmp, &gpd_list, gpd_list_node) {
2495                 if (gpd->provider == &np->fwnode) {
2496                         ret = genpd_remove(gpd);
2497                         genpd = ret ? ERR_PTR(ret) : gpd;
2498                         break;
2499                 }
2500         }
2501         mutex_unlock(&gpd_list_lock);
2502
2503         return genpd;
2504 }
2505 EXPORT_SYMBOL_GPL(of_genpd_remove_last);
2506
2507 static void genpd_release_dev(struct device *dev)
2508 {
2509         of_node_put(dev->of_node);
2510         kfree(dev);
2511 }
2512
2513 static struct bus_type genpd_bus_type = {
2514         .name           = "genpd",
2515 };
2516
2517 /**
2518  * genpd_dev_pm_detach - Detach a device from its PM domain.
2519  * @dev: Device to detach.
2520  * @power_off: Currently not used
2521  *
2522  * Try to locate a corresponding generic PM domain, which the device was
2523  * attached to previously. If such is found, the device is detached from it.
2524  */
2525 static void genpd_dev_pm_detach(struct device *dev, bool power_off)
2526 {
2527         struct generic_pm_domain *pd;
2528         unsigned int i;
2529         int ret = 0;
2530
2531         pd = dev_to_genpd(dev);
2532         if (IS_ERR(pd))
2533                 return;
2534
2535         dev_dbg(dev, "removing from PM domain %s\n", pd->name);
2536
2537         for (i = 1; i < GENPD_RETRY_MAX_MS; i <<= 1) {
2538                 ret = genpd_remove_device(pd, dev);
2539                 if (ret != -EAGAIN)
2540                         break;
2541
2542                 mdelay(i);
2543                 cond_resched();
2544         }
2545
2546         if (ret < 0) {
2547                 dev_err(dev, "failed to remove from PM domain %s: %d",
2548                         pd->name, ret);
2549                 return;
2550         }
2551
2552         /* Check if PM domain can be powered off after removing this device. */
2553         genpd_queue_power_off_work(pd);
2554
2555         /* Unregister the device if it was created by genpd. */
2556         if (dev->bus == &genpd_bus_type)
2557                 device_unregister(dev);
2558 }
2559
2560 static void genpd_dev_pm_sync(struct device *dev)
2561 {
2562         struct generic_pm_domain *pd;
2563
2564         pd = dev_to_genpd(dev);
2565         if (IS_ERR(pd))
2566                 return;
2567
2568         genpd_queue_power_off_work(pd);
2569 }
2570
2571 static int __genpd_dev_pm_attach(struct device *dev, struct device *base_dev,
2572                                  unsigned int index, bool power_on)
2573 {
2574         struct of_phandle_args pd_args;
2575         struct generic_pm_domain *pd;
2576         int ret;
2577
2578         ret = of_parse_phandle_with_args(dev->of_node, "power-domains",
2579                                 "#power-domain-cells", index, &pd_args);
2580         if (ret < 0)
2581                 return ret;
2582
2583         mutex_lock(&gpd_list_lock);
2584         pd = genpd_get_from_provider(&pd_args);
2585         of_node_put(pd_args.np);
2586         if (IS_ERR(pd)) {
2587                 mutex_unlock(&gpd_list_lock);
2588                 dev_dbg(dev, "%s() failed to find PM domain: %ld\n",
2589                         __func__, PTR_ERR(pd));
2590                 return driver_deferred_probe_check_state(base_dev);
2591         }
2592
2593         dev_dbg(dev, "adding to PM domain %s\n", pd->name);
2594
2595         ret = genpd_add_device(pd, dev, base_dev);
2596         mutex_unlock(&gpd_list_lock);
2597
2598         if (ret < 0) {
2599                 if (ret != -EPROBE_DEFER)
2600                         dev_err(dev, "failed to add to PM domain %s: %d",
2601                                 pd->name, ret);
2602                 return ret;
2603         }
2604
2605         dev->pm_domain->detach = genpd_dev_pm_detach;
2606         dev->pm_domain->sync = genpd_dev_pm_sync;
2607
2608         if (power_on) {
2609                 genpd_lock(pd);
2610                 ret = genpd_power_on(pd, 0);
2611                 genpd_unlock(pd);
2612         }
2613
2614         if (ret)
2615                 genpd_remove_device(pd, dev);
2616
2617         return ret ? -EPROBE_DEFER : 1;
2618 }
2619
2620 /**
2621  * genpd_dev_pm_attach - Attach a device to its PM domain using DT.
2622  * @dev: Device to attach.
2623  *
2624  * Parse device's OF node to find a PM domain specifier. If such is found,
2625  * attaches the device to retrieved pm_domain ops.
2626  *
2627  * Returns 1 on successfully attached PM domain, 0 when the device don't need a
2628  * PM domain or when multiple power-domains exists for it, else a negative error
2629  * code. Note that if a power-domain exists for the device, but it cannot be
2630  * found or turned on, then return -EPROBE_DEFER to ensure that the device is
2631  * not probed and to re-try again later.
2632  */
2633 int genpd_dev_pm_attach(struct device *dev)
2634 {
2635         if (!dev->of_node)
2636                 return 0;
2637
2638         /*
2639          * Devices with multiple PM domains must be attached separately, as we
2640          * can only attach one PM domain per device.
2641          */
2642         if (of_count_phandle_with_args(dev->of_node, "power-domains",
2643                                        "#power-domain-cells") != 1)
2644                 return 0;
2645
2646         return __genpd_dev_pm_attach(dev, dev, 0, true);
2647 }
2648 EXPORT_SYMBOL_GPL(genpd_dev_pm_attach);
2649
2650 /**
2651  * genpd_dev_pm_attach_by_id - Associate a device with one of its PM domains.
2652  * @dev: The device used to lookup the PM domain.
2653  * @index: The index of the PM domain.
2654  *
2655  * Parse device's OF node to find a PM domain specifier at the provided @index.
2656  * If such is found, creates a virtual device and attaches it to the retrieved
2657  * pm_domain ops. To deal with detaching of the virtual device, the ->detach()
2658  * callback in the struct dev_pm_domain are assigned to genpd_dev_pm_detach().
2659  *
2660  * Returns the created virtual device if successfully attached PM domain, NULL
2661  * when the device don't need a PM domain, else an ERR_PTR() in case of
2662  * failures. If a power-domain exists for the device, but cannot be found or
2663  * turned on, then ERR_PTR(-EPROBE_DEFER) is returned to ensure that the device
2664  * is not probed and to re-try again later.
2665  */
2666 struct device *genpd_dev_pm_attach_by_id(struct device *dev,
2667                                          unsigned int index)
2668 {
2669         struct device *virt_dev;
2670         int num_domains;
2671         int ret;
2672
2673         if (!dev->of_node)
2674                 return NULL;
2675
2676         /* Verify that the index is within a valid range. */
2677         num_domains = of_count_phandle_with_args(dev->of_node, "power-domains",
2678                                                  "#power-domain-cells");
2679         if (index >= num_domains)
2680                 return NULL;
2681
2682         /* Allocate and register device on the genpd bus. */
2683         virt_dev = kzalloc(sizeof(*virt_dev), GFP_KERNEL);
2684         if (!virt_dev)
2685                 return ERR_PTR(-ENOMEM);
2686
2687         dev_set_name(virt_dev, "genpd:%u:%s", index, dev_name(dev));
2688         virt_dev->bus = &genpd_bus_type;
2689         virt_dev->release = genpd_release_dev;
2690         virt_dev->of_node = of_node_get(dev->of_node);
2691
2692         ret = device_register(virt_dev);
2693         if (ret) {
2694                 put_device(virt_dev);
2695                 return ERR_PTR(ret);
2696         }
2697
2698         /* Try to attach the device to the PM domain at the specified index. */
2699         ret = __genpd_dev_pm_attach(virt_dev, dev, index, false);
2700         if (ret < 1) {
2701                 device_unregister(virt_dev);
2702                 return ret ? ERR_PTR(ret) : NULL;
2703         }
2704
2705         pm_runtime_enable(virt_dev);
2706         genpd_queue_power_off_work(dev_to_genpd(virt_dev));
2707
2708         return virt_dev;
2709 }
2710 EXPORT_SYMBOL_GPL(genpd_dev_pm_attach_by_id);
2711
2712 /**
2713  * genpd_dev_pm_attach_by_name - Associate a device with one of its PM domains.
2714  * @dev: The device used to lookup the PM domain.
2715  * @name: The name of the PM domain.
2716  *
2717  * Parse device's OF node to find a PM domain specifier using the
2718  * power-domain-names DT property. For further description see
2719  * genpd_dev_pm_attach_by_id().
2720  */
2721 struct device *genpd_dev_pm_attach_by_name(struct device *dev, const char *name)
2722 {
2723         int index;
2724
2725         if (!dev->of_node)
2726                 return NULL;
2727
2728         index = of_property_match_string(dev->of_node, "power-domain-names",
2729                                          name);
2730         if (index < 0)
2731                 return NULL;
2732
2733         return genpd_dev_pm_attach_by_id(dev, index);
2734 }
2735
2736 static const struct of_device_id idle_state_match[] = {
2737         { .compatible = "domain-idle-state", },
2738         { }
2739 };
2740
2741 static int genpd_parse_state(struct genpd_power_state *genpd_state,
2742                                     struct device_node *state_node)
2743 {
2744         int err;
2745         u32 residency;
2746         u32 entry_latency, exit_latency;
2747
2748         err = of_property_read_u32(state_node, "entry-latency-us",
2749                                                 &entry_latency);
2750         if (err) {
2751                 pr_debug(" * %pOF missing entry-latency-us property\n",
2752                          state_node);
2753                 return -EINVAL;
2754         }
2755
2756         err = of_property_read_u32(state_node, "exit-latency-us",
2757                                                 &exit_latency);
2758         if (err) {
2759                 pr_debug(" * %pOF missing exit-latency-us property\n",
2760                          state_node);
2761                 return -EINVAL;
2762         }
2763
2764         err = of_property_read_u32(state_node, "min-residency-us", &residency);
2765         if (!err)
2766                 genpd_state->residency_ns = 1000LL * residency;
2767
2768         genpd_state->power_on_latency_ns = 1000LL * exit_latency;
2769         genpd_state->power_off_latency_ns = 1000LL * entry_latency;
2770         genpd_state->fwnode = &state_node->fwnode;
2771
2772         return 0;
2773 }
2774
2775 static int genpd_iterate_idle_states(struct device_node *dn,
2776                                      struct genpd_power_state *states)
2777 {
2778         int ret;
2779         struct of_phandle_iterator it;
2780         struct device_node *np;
2781         int i = 0;
2782
2783         ret = of_count_phandle_with_args(dn, "domain-idle-states", NULL);
2784         if (ret <= 0)
2785                 return ret == -ENOENT ? 0 : ret;
2786
2787         /* Loop over the phandles until all the requested entry is found */
2788         of_for_each_phandle(&it, ret, dn, "domain-idle-states", NULL, 0) {
2789                 np = it.node;
2790                 if (!of_match_node(idle_state_match, np))
2791                         continue;
2792
2793                 if (!of_device_is_available(np))
2794                         continue;
2795
2796                 if (states) {
2797                         ret = genpd_parse_state(&states[i], np);
2798                         if (ret) {
2799                                 pr_err("Parsing idle state node %pOF failed with err %d\n",
2800                                        np, ret);
2801                                 of_node_put(np);
2802                                 return ret;
2803                         }
2804                 }
2805                 i++;
2806         }
2807
2808         return i;
2809 }
2810
2811 /**
2812  * of_genpd_parse_idle_states: Return array of idle states for the genpd.
2813  *
2814  * @dn: The genpd device node
2815  * @states: The pointer to which the state array will be saved.
2816  * @n: The count of elements in the array returned from this function.
2817  *
2818  * Returns the device states parsed from the OF node. The memory for the states
2819  * is allocated by this function and is the responsibility of the caller to
2820  * free the memory after use. If any or zero compatible domain idle states is
2821  * found it returns 0 and in case of errors, a negative error code is returned.
2822  */
2823 int of_genpd_parse_idle_states(struct device_node *dn,
2824                         struct genpd_power_state **states, int *n)
2825 {
2826         struct genpd_power_state *st;
2827         int ret;
2828
2829         ret = genpd_iterate_idle_states(dn, NULL);
2830         if (ret < 0)
2831                 return ret;
2832
2833         if (!ret) {
2834                 *states = NULL;
2835                 *n = 0;
2836                 return 0;
2837         }
2838
2839         st = kcalloc(ret, sizeof(*st), GFP_KERNEL);
2840         if (!st)
2841                 return -ENOMEM;
2842
2843         ret = genpd_iterate_idle_states(dn, st);
2844         if (ret <= 0) {
2845                 kfree(st);
2846                 return ret < 0 ? ret : -EINVAL;
2847         }
2848
2849         *states = st;
2850         *n = ret;
2851
2852         return 0;
2853 }
2854 EXPORT_SYMBOL_GPL(of_genpd_parse_idle_states);
2855
2856 /**
2857  * pm_genpd_opp_to_performance_state - Gets performance state of the genpd from its OPP node.
2858  *
2859  * @genpd_dev: Genpd's device for which the performance-state needs to be found.
2860  * @opp: struct dev_pm_opp of the OPP for which we need to find performance
2861  *      state.
2862  *
2863  * Returns performance state encoded in the OPP of the genpd. This calls
2864  * platform specific genpd->opp_to_performance_state() callback to translate
2865  * power domain OPP to performance state.
2866  *
2867  * Returns performance state on success and 0 on failure.
2868  */
2869 unsigned int pm_genpd_opp_to_performance_state(struct device *genpd_dev,
2870                                                struct dev_pm_opp *opp)
2871 {
2872         struct generic_pm_domain *genpd = NULL;
2873         int state;
2874
2875         genpd = container_of(genpd_dev, struct generic_pm_domain, dev);
2876
2877         if (unlikely(!genpd->opp_to_performance_state))
2878                 return 0;
2879
2880         genpd_lock(genpd);
2881         state = genpd->opp_to_performance_state(genpd, opp);
2882         genpd_unlock(genpd);
2883
2884         return state;
2885 }
2886 EXPORT_SYMBOL_GPL(pm_genpd_opp_to_performance_state);
2887
2888 static int __init genpd_bus_init(void)
2889 {
2890         return bus_register(&genpd_bus_type);
2891 }
2892 core_initcall(genpd_bus_init);
2893
2894 #endif /* CONFIG_PM_GENERIC_DOMAINS_OF */
2895
2896
2897 /***        debugfs support        ***/
2898
2899 #ifdef CONFIG_DEBUG_FS
2900 #include <linux/pm.h>
2901 #include <linux/device.h>
2902 #include <linux/debugfs.h>
2903 #include <linux/seq_file.h>
2904 #include <linux/init.h>
2905 #include <linux/kobject.h>
2906 static struct dentry *genpd_debugfs_dir;
2907
2908 /*
2909  * TODO: This function is a slightly modified version of rtpm_status_show
2910  * from sysfs.c, so generalize it.
2911  */
2912 static void rtpm_status_str(struct seq_file *s, struct device *dev)
2913 {
2914         static const char * const status_lookup[] = {
2915                 [RPM_ACTIVE] = "active",
2916                 [RPM_RESUMING] = "resuming",
2917                 [RPM_SUSPENDED] = "suspended",
2918                 [RPM_SUSPENDING] = "suspending"
2919         };
2920         const char *p = "";
2921
2922         if (dev->power.runtime_error)
2923                 p = "error";
2924         else if (dev->power.disable_depth)
2925                 p = "unsupported";
2926         else if (dev->power.runtime_status < ARRAY_SIZE(status_lookup))
2927                 p = status_lookup[dev->power.runtime_status];
2928         else
2929                 WARN_ON(1);
2930
2931         seq_puts(s, p);
2932 }
2933
2934 static int genpd_summary_one(struct seq_file *s,
2935                         struct generic_pm_domain *genpd)
2936 {
2937         static const char * const status_lookup[] = {
2938                 [GENPD_STATE_ON] = "on",
2939                 [GENPD_STATE_OFF] = "off"
2940         };
2941         struct pm_domain_data *pm_data;
2942         const char *kobj_path;
2943         struct gpd_link *link;
2944         char state[16];
2945         int ret;
2946
2947         ret = genpd_lock_interruptible(genpd);
2948         if (ret)
2949                 return -ERESTARTSYS;
2950
2951         if (WARN_ON(genpd->status >= ARRAY_SIZE(status_lookup)))
2952                 goto exit;
2953         if (!genpd_status_on(genpd))
2954                 snprintf(state, sizeof(state), "%s-%u",
2955                          status_lookup[genpd->status], genpd->state_idx);
2956         else
2957                 snprintf(state, sizeof(state), "%s",
2958                          status_lookup[genpd->status]);
2959         seq_printf(s, "%-30s  %-15s ", genpd->name, state);
2960
2961         /*
2962          * Modifications on the list require holding locks on both
2963          * parent and child, so we are safe.
2964          * Also genpd->name is immutable.
2965          */
2966         list_for_each_entry(link, &genpd->parent_links, parent_node) {
2967                 seq_printf(s, "%s", link->child->name);
2968                 if (!list_is_last(&link->parent_node, &genpd->parent_links))
2969                         seq_puts(s, ", ");
2970         }
2971
2972         list_for_each_entry(pm_data, &genpd->dev_list, list_node) {
2973                 kobj_path = kobject_get_path(&pm_data->dev->kobj,
2974                                 genpd_is_irq_safe(genpd) ?
2975                                 GFP_ATOMIC : GFP_KERNEL);
2976                 if (kobj_path == NULL)
2977                         continue;
2978
2979                 seq_printf(s, "\n    %-50s  ", kobj_path);
2980                 rtpm_status_str(s, pm_data->dev);
2981                 kfree(kobj_path);
2982         }
2983
2984         seq_puts(s, "\n");
2985 exit:
2986         genpd_unlock(genpd);
2987
2988         return 0;
2989 }
2990
2991 static int summary_show(struct seq_file *s, void *data)
2992 {
2993         struct generic_pm_domain *genpd;
2994         int ret = 0;
2995
2996         seq_puts(s, "domain                          status          children\n");
2997         seq_puts(s, "    /device                                             runtime status\n");
2998         seq_puts(s, "----------------------------------------------------------------------\n");
2999
3000         ret = mutex_lock_interruptible(&gpd_list_lock);
3001         if (ret)
3002                 return -ERESTARTSYS;
3003
3004         list_for_each_entry(genpd, &gpd_list, gpd_list_node) {
3005                 ret = genpd_summary_one(s, genpd);
3006                 if (ret)
3007                         break;
3008         }
3009         mutex_unlock(&gpd_list_lock);
3010
3011         return ret;
3012 }
3013
3014 static int status_show(struct seq_file *s, void *data)
3015 {
3016         static const char * const status_lookup[] = {
3017                 [GENPD_STATE_ON] = "on",
3018                 [GENPD_STATE_OFF] = "off"
3019         };
3020
3021         struct generic_pm_domain *genpd = s->private;
3022         int ret = 0;
3023
3024         ret = genpd_lock_interruptible(genpd);
3025         if (ret)
3026                 return -ERESTARTSYS;
3027
3028         if (WARN_ON_ONCE(genpd->status >= ARRAY_SIZE(status_lookup)))
3029                 goto exit;
3030
3031         if (genpd->status == GENPD_STATE_OFF)
3032                 seq_printf(s, "%s-%u\n", status_lookup[genpd->status],
3033                         genpd->state_idx);
3034         else
3035                 seq_printf(s, "%s\n", status_lookup[genpd->status]);
3036 exit:
3037         genpd_unlock(genpd);
3038         return ret;
3039 }
3040
3041 static int sub_domains_show(struct seq_file *s, void *data)
3042 {
3043         struct generic_pm_domain *genpd = s->private;
3044         struct gpd_link *link;
3045         int ret = 0;
3046
3047         ret = genpd_lock_interruptible(genpd);
3048         if (ret)
3049                 return -ERESTARTSYS;
3050
3051         list_for_each_entry(link, &genpd->parent_links, parent_node)
3052                 seq_printf(s, "%s\n", link->child->name);
3053
3054         genpd_unlock(genpd);
3055         return ret;
3056 }
3057
3058 static int idle_states_show(struct seq_file *s, void *data)
3059 {
3060         struct generic_pm_domain *genpd = s->private;
3061         unsigned int i;
3062         int ret = 0;
3063
3064         ret = genpd_lock_interruptible(genpd);
3065         if (ret)
3066                 return -ERESTARTSYS;
3067
3068         seq_puts(s, "State          Time Spent(ms) Usage          Rejected\n");
3069
3070         for (i = 0; i < genpd->state_count; i++) {
3071                 ktime_t delta = 0;
3072                 s64 msecs;
3073
3074                 if ((genpd->status == GENPD_STATE_OFF) &&
3075                                 (genpd->state_idx == i))
3076                         delta = ktime_sub(ktime_get(), genpd->accounting_time);
3077
3078                 msecs = ktime_to_ms(
3079                         ktime_add(genpd->states[i].idle_time, delta));
3080                 seq_printf(s, "S%-13i %-14lld %-14llu %llu\n", i, msecs,
3081                               genpd->states[i].usage, genpd->states[i].rejected);
3082         }
3083
3084         genpd_unlock(genpd);
3085         return ret;
3086 }
3087
3088 static int active_time_show(struct seq_file *s, void *data)
3089 {
3090         struct generic_pm_domain *genpd = s->private;
3091         ktime_t delta = 0;
3092         int ret = 0;
3093
3094         ret = genpd_lock_interruptible(genpd);
3095         if (ret)
3096                 return -ERESTARTSYS;
3097
3098         if (genpd->status == GENPD_STATE_ON)
3099                 delta = ktime_sub(ktime_get(), genpd->accounting_time);
3100
3101         seq_printf(s, "%lld ms\n", ktime_to_ms(
3102                                 ktime_add(genpd->on_time, delta)));
3103
3104         genpd_unlock(genpd);
3105         return ret;
3106 }
3107
3108 static int total_idle_time_show(struct seq_file *s, void *data)
3109 {
3110         struct generic_pm_domain *genpd = s->private;
3111         ktime_t delta = 0, total = 0;
3112         unsigned int i;
3113         int ret = 0;
3114
3115         ret = genpd_lock_interruptible(genpd);
3116         if (ret)
3117                 return -ERESTARTSYS;
3118
3119         for (i = 0; i < genpd->state_count; i++) {
3120
3121                 if ((genpd->status == GENPD_STATE_OFF) &&
3122                                 (genpd->state_idx == i))
3123                         delta = ktime_sub(ktime_get(), genpd->accounting_time);
3124
3125                 total = ktime_add(total, genpd->states[i].idle_time);
3126         }
3127         total = ktime_add(total, delta);
3128
3129         seq_printf(s, "%lld ms\n", ktime_to_ms(total));
3130
3131         genpd_unlock(genpd);
3132         return ret;
3133 }
3134
3135
3136 static int devices_show(struct seq_file *s, void *data)
3137 {
3138         struct generic_pm_domain *genpd = s->private;
3139         struct pm_domain_data *pm_data;
3140         const char *kobj_path;
3141         int ret = 0;
3142
3143         ret = genpd_lock_interruptible(genpd);
3144         if (ret)
3145                 return -ERESTARTSYS;
3146
3147         list_for_each_entry(pm_data, &genpd->dev_list, list_node) {
3148                 kobj_path = kobject_get_path(&pm_data->dev->kobj,
3149                                 genpd_is_irq_safe(genpd) ?
3150                                 GFP_ATOMIC : GFP_KERNEL);
3151                 if (kobj_path == NULL)
3152                         continue;
3153
3154                 seq_printf(s, "%s\n", kobj_path);
3155                 kfree(kobj_path);
3156         }
3157
3158         genpd_unlock(genpd);
3159         return ret;
3160 }
3161
3162 static int perf_state_show(struct seq_file *s, void *data)
3163 {
3164         struct generic_pm_domain *genpd = s->private;
3165
3166         if (genpd_lock_interruptible(genpd))
3167                 return -ERESTARTSYS;
3168
3169         seq_printf(s, "%u\n", genpd->performance_state);
3170
3171         genpd_unlock(genpd);
3172         return 0;
3173 }
3174
3175 DEFINE_SHOW_ATTRIBUTE(summary);
3176 DEFINE_SHOW_ATTRIBUTE(status);
3177 DEFINE_SHOW_ATTRIBUTE(sub_domains);
3178 DEFINE_SHOW_ATTRIBUTE(idle_states);
3179 DEFINE_SHOW_ATTRIBUTE(active_time);
3180 DEFINE_SHOW_ATTRIBUTE(total_idle_time);
3181 DEFINE_SHOW_ATTRIBUTE(devices);
3182 DEFINE_SHOW_ATTRIBUTE(perf_state);
3183
3184 static int __init genpd_debug_init(void)
3185 {
3186         struct dentry *d;
3187         struct generic_pm_domain *genpd;
3188
3189         genpd_debugfs_dir = debugfs_create_dir("pm_genpd", NULL);
3190
3191         debugfs_create_file("pm_genpd_summary", S_IRUGO, genpd_debugfs_dir,
3192                             NULL, &summary_fops);
3193
3194         list_for_each_entry(genpd, &gpd_list, gpd_list_node) {
3195                 d = debugfs_create_dir(genpd->name, genpd_debugfs_dir);
3196
3197                 debugfs_create_file("current_state", 0444,
3198                                 d, genpd, &status_fops);
3199                 debugfs_create_file("sub_domains", 0444,
3200                                 d, genpd, &sub_domains_fops);
3201                 debugfs_create_file("idle_states", 0444,
3202                                 d, genpd, &idle_states_fops);
3203                 debugfs_create_file("active_time", 0444,
3204                                 d, genpd, &active_time_fops);
3205                 debugfs_create_file("total_idle_time", 0444,
3206                                 d, genpd, &total_idle_time_fops);
3207                 debugfs_create_file("devices", 0444,
3208                                 d, genpd, &devices_fops);
3209                 if (genpd->set_performance_state)
3210                         debugfs_create_file("perf_state", 0444,
3211                                             d, genpd, &perf_state_fops);
3212         }
3213
3214         return 0;
3215 }
3216 late_initcall(genpd_debug_init);
3217
3218 static void __exit genpd_debug_exit(void)
3219 {
3220         debugfs_remove_recursive(genpd_debugfs_dir);
3221 }
3222 __exitcall(genpd_debug_exit);
3223 #endif /* CONFIG_DEBUG_FS */