Linux-libre 4.14.68-gnu
[librecmc/linux-libre.git] / drivers / base / power / domain.c
1 /*
2  * drivers/base/power/domain.c - Common code related to device power domains.
3  *
4  * Copyright (C) 2011 Rafael J. Wysocki <rjw@sisk.pl>, Renesas Electronics Corp.
5  *
6  * This file is released under the GPLv2.
7  */
8
9 #include <linux/delay.h>
10 #include <linux/kernel.h>
11 #include <linux/io.h>
12 #include <linux/platform_device.h>
13 #include <linux/pm_runtime.h>
14 #include <linux/pm_domain.h>
15 #include <linux/pm_qos.h>
16 #include <linux/pm_clock.h>
17 #include <linux/slab.h>
18 #include <linux/err.h>
19 #include <linux/sched.h>
20 #include <linux/suspend.h>
21 #include <linux/export.h>
22
23 #include "power.h"
24
25 #define GENPD_RETRY_MAX_MS      250             /* Approximate */
26
27 #define GENPD_DEV_CALLBACK(genpd, type, callback, dev)          \
28 ({                                                              \
29         type (*__routine)(struct device *__d);                  \
30         type __ret = (type)0;                                   \
31                                                                 \
32         __routine = genpd->dev_ops.callback;                    \
33         if (__routine) {                                        \
34                 __ret = __routine(dev);                         \
35         }                                                       \
36         __ret;                                                  \
37 })
38
39 static LIST_HEAD(gpd_list);
40 static DEFINE_MUTEX(gpd_list_lock);
41
42 struct genpd_lock_ops {
43         void (*lock)(struct generic_pm_domain *genpd);
44         void (*lock_nested)(struct generic_pm_domain *genpd, int depth);
45         int (*lock_interruptible)(struct generic_pm_domain *genpd);
46         void (*unlock)(struct generic_pm_domain *genpd);
47 };
48
49 static void genpd_lock_mtx(struct generic_pm_domain *genpd)
50 {
51         mutex_lock(&genpd->mlock);
52 }
53
54 static void genpd_lock_nested_mtx(struct generic_pm_domain *genpd,
55                                         int depth)
56 {
57         mutex_lock_nested(&genpd->mlock, depth);
58 }
59
60 static int genpd_lock_interruptible_mtx(struct generic_pm_domain *genpd)
61 {
62         return mutex_lock_interruptible(&genpd->mlock);
63 }
64
65 static void genpd_unlock_mtx(struct generic_pm_domain *genpd)
66 {
67         return mutex_unlock(&genpd->mlock);
68 }
69
70 static const struct genpd_lock_ops genpd_mtx_ops = {
71         .lock = genpd_lock_mtx,
72         .lock_nested = genpd_lock_nested_mtx,
73         .lock_interruptible = genpd_lock_interruptible_mtx,
74         .unlock = genpd_unlock_mtx,
75 };
76
77 static void genpd_lock_spin(struct generic_pm_domain *genpd)
78         __acquires(&genpd->slock)
79 {
80         unsigned long flags;
81
82         spin_lock_irqsave(&genpd->slock, flags);
83         genpd->lock_flags = flags;
84 }
85
86 static void genpd_lock_nested_spin(struct generic_pm_domain *genpd,
87                                         int depth)
88         __acquires(&genpd->slock)
89 {
90         unsigned long flags;
91
92         spin_lock_irqsave_nested(&genpd->slock, flags, depth);
93         genpd->lock_flags = flags;
94 }
95
96 static int genpd_lock_interruptible_spin(struct generic_pm_domain *genpd)
97         __acquires(&genpd->slock)
98 {
99         unsigned long flags;
100
101         spin_lock_irqsave(&genpd->slock, flags);
102         genpd->lock_flags = flags;
103         return 0;
104 }
105
106 static void genpd_unlock_spin(struct generic_pm_domain *genpd)
107         __releases(&genpd->slock)
108 {
109         spin_unlock_irqrestore(&genpd->slock, genpd->lock_flags);
110 }
111
112 static const struct genpd_lock_ops genpd_spin_ops = {
113         .lock = genpd_lock_spin,
114         .lock_nested = genpd_lock_nested_spin,
115         .lock_interruptible = genpd_lock_interruptible_spin,
116         .unlock = genpd_unlock_spin,
117 };
118
119 #define genpd_lock(p)                   p->lock_ops->lock(p)
120 #define genpd_lock_nested(p, d)         p->lock_ops->lock_nested(p, d)
121 #define genpd_lock_interruptible(p)     p->lock_ops->lock_interruptible(p)
122 #define genpd_unlock(p)                 p->lock_ops->unlock(p)
123
124 #define genpd_status_on(genpd)          (genpd->status == GPD_STATE_ACTIVE)
125 #define genpd_is_irq_safe(genpd)        (genpd->flags & GENPD_FLAG_IRQ_SAFE)
126 #define genpd_is_always_on(genpd)       (genpd->flags & GENPD_FLAG_ALWAYS_ON)
127
128 static inline bool irq_safe_dev_in_no_sleep_domain(struct device *dev,
129                 const struct generic_pm_domain *genpd)
130 {
131         bool ret;
132
133         ret = pm_runtime_is_irq_safe(dev) && !genpd_is_irq_safe(genpd);
134
135         /*
136          * Warn once if an IRQ safe device is attached to a no sleep domain, as
137          * to indicate a suboptimal configuration for PM. For an always on
138          * domain this isn't case, thus don't warn.
139          */
140         if (ret && !genpd_is_always_on(genpd))
141                 dev_warn_once(dev, "PM domain %s will not be powered off\n",
142                                 genpd->name);
143
144         return ret;
145 }
146
147 /*
148  * Get the generic PM domain for a particular struct device.
149  * This validates the struct device pointer, the PM domain pointer,
150  * and checks that the PM domain pointer is a real generic PM domain.
151  * Any failure results in NULL being returned.
152  */
153 static struct generic_pm_domain *genpd_lookup_dev(struct device *dev)
154 {
155         struct generic_pm_domain *genpd = NULL, *gpd;
156
157         if (IS_ERR_OR_NULL(dev) || IS_ERR_OR_NULL(dev->pm_domain))
158                 return NULL;
159
160         mutex_lock(&gpd_list_lock);
161         list_for_each_entry(gpd, &gpd_list, gpd_list_node) {
162                 if (&gpd->domain == dev->pm_domain) {
163                         genpd = gpd;
164                         break;
165                 }
166         }
167         mutex_unlock(&gpd_list_lock);
168
169         return genpd;
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 == GPD_STATE_ACTIVE) {
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_power_on(struct generic_pm_domain *genpd, bool timed)
241 {
242         unsigned int state_idx = genpd->state_idx;
243         ktime_t time_start;
244         s64 elapsed_ns;
245         int ret;
246
247         if (!genpd->power_on)
248                 return 0;
249
250         if (!timed)
251                 return genpd->power_on(genpd);
252
253         time_start = ktime_get();
254         ret = genpd->power_on(genpd);
255         if (ret)
256                 return ret;
257
258         elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
259         if (elapsed_ns <= genpd->states[state_idx].power_on_latency_ns)
260                 return ret;
261
262         genpd->states[state_idx].power_on_latency_ns = elapsed_ns;
263         genpd->max_off_time_changed = true;
264         pr_debug("%s: Power-%s latency exceeded, new value %lld ns\n",
265                  genpd->name, "on", elapsed_ns);
266
267         return ret;
268 }
269
270 static int _genpd_power_off(struct generic_pm_domain *genpd, bool timed)
271 {
272         unsigned int state_idx = genpd->state_idx;
273         ktime_t time_start;
274         s64 elapsed_ns;
275         int ret;
276
277         if (!genpd->power_off)
278                 return 0;
279
280         if (!timed)
281                 return genpd->power_off(genpd);
282
283         time_start = ktime_get();
284         ret = genpd->power_off(genpd);
285         if (ret == -EBUSY)
286                 return ret;
287
288         elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
289         if (elapsed_ns <= genpd->states[state_idx].power_off_latency_ns)
290                 return ret;
291
292         genpd->states[state_idx].power_off_latency_ns = elapsed_ns;
293         genpd->max_off_time_changed = true;
294         pr_debug("%s: Power-%s latency exceeded, new value %lld ns\n",
295                  genpd->name, "off", elapsed_ns);
296
297         return ret;
298 }
299
300 /**
301  * genpd_queue_power_off_work - Queue up the execution of genpd_power_off().
302  * @genpd: PM domain to power off.
303  *
304  * Queue up the execution of genpd_power_off() unless it's already been done
305  * before.
306  */
307 static void genpd_queue_power_off_work(struct generic_pm_domain *genpd)
308 {
309         queue_work(pm_wq, &genpd->power_off_work);
310 }
311
312 /**
313  * genpd_power_off - Remove power from a given PM domain.
314  * @genpd: PM domain to power down.
315  * @one_dev_on: If invoked from genpd's ->runtime_suspend|resume() callback, the
316  * RPM status of the releated device is in an intermediate state, not yet turned
317  * into RPM_SUSPENDED. This means genpd_power_off() must allow one device to not
318  * be RPM_SUSPENDED, while it tries to power off the PM domain.
319  *
320  * If all of the @genpd's devices have been suspended and all of its subdomains
321  * have been powered down, remove power from @genpd.
322  */
323 static int genpd_power_off(struct generic_pm_domain *genpd, bool one_dev_on,
324                            unsigned int depth)
325 {
326         struct pm_domain_data *pdd;
327         struct gpd_link *link;
328         unsigned int not_suspended = 0;
329
330         /*
331          * Do not try to power off the domain in the following situations:
332          * (1) The domain is already in the "power off" state.
333          * (2) System suspend is in progress.
334          */
335         if (!genpd_status_on(genpd) || genpd->prepared_count > 0)
336                 return 0;
337
338         /*
339          * Abort power off for the PM domain in the following situations:
340          * (1) The domain is configured as always on.
341          * (2) When the domain has a subdomain being powered on.
342          */
343         if (genpd_is_always_on(genpd) || atomic_read(&genpd->sd_count) > 0)
344                 return -EBUSY;
345
346         list_for_each_entry(pdd, &genpd->dev_list, list_node) {
347                 enum pm_qos_flags_status stat;
348
349                 stat = dev_pm_qos_flags(pdd->dev,
350                                         PM_QOS_FLAG_NO_POWER_OFF
351                                                 | PM_QOS_FLAG_REMOTE_WAKEUP);
352                 if (stat > PM_QOS_FLAGS_NONE)
353                         return -EBUSY;
354
355                 /*
356                  * Do not allow PM domain to be powered off, when an IRQ safe
357                  * device is part of a non-IRQ safe domain.
358                  */
359                 if (!pm_runtime_suspended(pdd->dev) ||
360                         irq_safe_dev_in_no_sleep_domain(pdd->dev, genpd))
361                         not_suspended++;
362         }
363
364         if (not_suspended > 1 || (not_suspended == 1 && !one_dev_on))
365                 return -EBUSY;
366
367         if (genpd->gov && genpd->gov->power_down_ok) {
368                 if (!genpd->gov->power_down_ok(&genpd->domain))
369                         return -EAGAIN;
370         }
371
372         if (genpd->power_off) {
373                 int ret;
374
375                 if (atomic_read(&genpd->sd_count) > 0)
376                         return -EBUSY;
377
378                 /*
379                  * If sd_count > 0 at this point, one of the subdomains hasn't
380                  * managed to call genpd_power_on() for the master yet after
381                  * incrementing it.  In that case genpd_power_on() will wait
382                  * for us to drop the lock, so we can call .power_off() and let
383                  * the genpd_power_on() restore power for us (this shouldn't
384                  * happen very often).
385                  */
386                 ret = _genpd_power_off(genpd, true);
387                 if (ret)
388                         return ret;
389         }
390
391         genpd->status = GPD_STATE_POWER_OFF;
392         genpd_update_accounting(genpd);
393
394         list_for_each_entry(link, &genpd->slave_links, slave_node) {
395                 genpd_sd_counter_dec(link->master);
396                 genpd_lock_nested(link->master, depth + 1);
397                 genpd_power_off(link->master, false, depth + 1);
398                 genpd_unlock(link->master);
399         }
400
401         return 0;
402 }
403
404 /**
405  * genpd_power_on - Restore power to a given PM domain and its masters.
406  * @genpd: PM domain to power up.
407  * @depth: nesting count for lockdep.
408  *
409  * Restore power to @genpd and all of its masters so that it is possible to
410  * resume a device belonging to it.
411  */
412 static int genpd_power_on(struct generic_pm_domain *genpd, unsigned int depth)
413 {
414         struct gpd_link *link;
415         int ret = 0;
416
417         if (genpd_status_on(genpd))
418                 return 0;
419
420         /*
421          * The list is guaranteed not to change while the loop below is being
422          * executed, unless one of the masters' .power_on() callbacks fiddles
423          * with it.
424          */
425         list_for_each_entry(link, &genpd->slave_links, slave_node) {
426                 struct generic_pm_domain *master = link->master;
427
428                 genpd_sd_counter_inc(master);
429
430                 genpd_lock_nested(master, depth + 1);
431                 ret = genpd_power_on(master, depth + 1);
432                 genpd_unlock(master);
433
434                 if (ret) {
435                         genpd_sd_counter_dec(master);
436                         goto err;
437                 }
438         }
439
440         ret = _genpd_power_on(genpd, true);
441         if (ret)
442                 goto err;
443
444         genpd->status = GPD_STATE_ACTIVE;
445         genpd_update_accounting(genpd);
446
447         return 0;
448
449  err:
450         list_for_each_entry_continue_reverse(link,
451                                         &genpd->slave_links,
452                                         slave_node) {
453                 genpd_sd_counter_dec(link->master);
454                 genpd_lock_nested(link->master, depth + 1);
455                 genpd_power_off(link->master, false, depth + 1);
456                 genpd_unlock(link->master);
457         }
458
459         return ret;
460 }
461
462 static int genpd_dev_pm_qos_notifier(struct notifier_block *nb,
463                                      unsigned long val, void *ptr)
464 {
465         struct generic_pm_domain_data *gpd_data;
466         struct device *dev;
467
468         gpd_data = container_of(nb, struct generic_pm_domain_data, nb);
469         dev = gpd_data->base.dev;
470
471         for (;;) {
472                 struct generic_pm_domain *genpd;
473                 struct pm_domain_data *pdd;
474
475                 spin_lock_irq(&dev->power.lock);
476
477                 pdd = dev->power.subsys_data ?
478                                 dev->power.subsys_data->domain_data : NULL;
479                 if (pdd) {
480                         to_gpd_data(pdd)->td.constraint_changed = true;
481                         genpd = dev_to_genpd(dev);
482                 } else {
483                         genpd = ERR_PTR(-ENODATA);
484                 }
485
486                 spin_unlock_irq(&dev->power.lock);
487
488                 if (!IS_ERR(genpd)) {
489                         genpd_lock(genpd);
490                         genpd->max_off_time_changed = true;
491                         genpd_unlock(genpd);
492                 }
493
494                 dev = dev->parent;
495                 if (!dev || dev->power.ignore_children)
496                         break;
497         }
498
499         return NOTIFY_DONE;
500 }
501
502 /**
503  * genpd_power_off_work_fn - Power off PM domain whose subdomain count is 0.
504  * @work: Work structure used for scheduling the execution of this function.
505  */
506 static void genpd_power_off_work_fn(struct work_struct *work)
507 {
508         struct generic_pm_domain *genpd;
509
510         genpd = container_of(work, struct generic_pm_domain, power_off_work);
511
512         genpd_lock(genpd);
513         genpd_power_off(genpd, false, 0);
514         genpd_unlock(genpd);
515 }
516
517 /**
518  * __genpd_runtime_suspend - walk the hierarchy of ->runtime_suspend() callbacks
519  * @dev: Device to handle.
520  */
521 static int __genpd_runtime_suspend(struct device *dev)
522 {
523         int (*cb)(struct device *__dev);
524
525         if (dev->type && dev->type->pm)
526                 cb = dev->type->pm->runtime_suspend;
527         else if (dev->class && dev->class->pm)
528                 cb = dev->class->pm->runtime_suspend;
529         else if (dev->bus && dev->bus->pm)
530                 cb = dev->bus->pm->runtime_suspend;
531         else
532                 cb = NULL;
533
534         if (!cb && dev->driver && dev->driver->pm)
535                 cb = dev->driver->pm->runtime_suspend;
536
537         return cb ? cb(dev) : 0;
538 }
539
540 /**
541  * __genpd_runtime_resume - walk the hierarchy of ->runtime_resume() callbacks
542  * @dev: Device to handle.
543  */
544 static int __genpd_runtime_resume(struct device *dev)
545 {
546         int (*cb)(struct device *__dev);
547
548         if (dev->type && dev->type->pm)
549                 cb = dev->type->pm->runtime_resume;
550         else if (dev->class && dev->class->pm)
551                 cb = dev->class->pm->runtime_resume;
552         else if (dev->bus && dev->bus->pm)
553                 cb = dev->bus->pm->runtime_resume;
554         else
555                 cb = NULL;
556
557         if (!cb && dev->driver && dev->driver->pm)
558                 cb = dev->driver->pm->runtime_resume;
559
560         return cb ? cb(dev) : 0;
561 }
562
563 /**
564  * genpd_runtime_suspend - Suspend a device belonging to I/O PM domain.
565  * @dev: Device to suspend.
566  *
567  * Carry out a runtime suspend of a device under the assumption that its
568  * pm_domain field points to the domain member of an object of type
569  * struct generic_pm_domain representing a PM domain consisting of I/O devices.
570  */
571 static int genpd_runtime_suspend(struct device *dev)
572 {
573         struct generic_pm_domain *genpd;
574         bool (*suspend_ok)(struct device *__dev);
575         struct gpd_timing_data *td = &dev_gpd_data(dev)->td;
576         bool runtime_pm = pm_runtime_enabled(dev);
577         ktime_t time_start;
578         s64 elapsed_ns;
579         int ret;
580
581         dev_dbg(dev, "%s()\n", __func__);
582
583         genpd = dev_to_genpd(dev);
584         if (IS_ERR(genpd))
585                 return -EINVAL;
586
587         /*
588          * A runtime PM centric subsystem/driver may re-use the runtime PM
589          * callbacks for other purposes than runtime PM. In those scenarios
590          * runtime PM is disabled. Under these circumstances, we shall skip
591          * validating/measuring the PM QoS latency.
592          */
593         suspend_ok = genpd->gov ? genpd->gov->suspend_ok : NULL;
594         if (runtime_pm && suspend_ok && !suspend_ok(dev))
595                 return -EBUSY;
596
597         /* Measure suspend latency. */
598         time_start = 0;
599         if (runtime_pm)
600                 time_start = ktime_get();
601
602         ret = __genpd_runtime_suspend(dev);
603         if (ret)
604                 return ret;
605
606         ret = genpd_stop_dev(genpd, dev);
607         if (ret) {
608                 __genpd_runtime_resume(dev);
609                 return ret;
610         }
611
612         /* Update suspend latency value if the measured time exceeds it. */
613         if (runtime_pm) {
614                 elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
615                 if (elapsed_ns > td->suspend_latency_ns) {
616                         td->suspend_latency_ns = elapsed_ns;
617                         dev_dbg(dev, "suspend latency exceeded, %lld ns\n",
618                                 elapsed_ns);
619                         genpd->max_off_time_changed = true;
620                         td->constraint_changed = true;
621                 }
622         }
623
624         /*
625          * If power.irq_safe is set, this routine may be run with
626          * IRQs disabled, so suspend only if the PM domain also is irq_safe.
627          */
628         if (irq_safe_dev_in_no_sleep_domain(dev, genpd))
629                 return 0;
630
631         genpd_lock(genpd);
632         genpd_power_off(genpd, true, 0);
633         genpd_unlock(genpd);
634
635         return 0;
636 }
637
638 /**
639  * genpd_runtime_resume - Resume a device belonging to I/O PM domain.
640  * @dev: Device to resume.
641  *
642  * Carry out a runtime resume of a device under the assumption that its
643  * pm_domain field points to the domain member of an object of type
644  * struct generic_pm_domain representing a PM domain consisting of I/O devices.
645  */
646 static int genpd_runtime_resume(struct device *dev)
647 {
648         struct generic_pm_domain *genpd;
649         struct gpd_timing_data *td = &dev_gpd_data(dev)->td;
650         bool runtime_pm = pm_runtime_enabled(dev);
651         ktime_t time_start;
652         s64 elapsed_ns;
653         int ret;
654         bool timed = true;
655
656         dev_dbg(dev, "%s()\n", __func__);
657
658         genpd = dev_to_genpd(dev);
659         if (IS_ERR(genpd))
660                 return -EINVAL;
661
662         /*
663          * As we don't power off a non IRQ safe domain, which holds
664          * an IRQ safe device, we don't need to restore power to it.
665          */
666         if (irq_safe_dev_in_no_sleep_domain(dev, genpd)) {
667                 timed = false;
668                 goto out;
669         }
670
671         genpd_lock(genpd);
672         ret = genpd_power_on(genpd, 0);
673         genpd_unlock(genpd);
674
675         if (ret)
676                 return ret;
677
678  out:
679         /* Measure resume latency. */
680         time_start = 0;
681         if (timed && runtime_pm)
682                 time_start = ktime_get();
683
684         ret = genpd_start_dev(genpd, dev);
685         if (ret)
686                 goto err_poweroff;
687
688         ret = __genpd_runtime_resume(dev);
689         if (ret)
690                 goto err_stop;
691
692         /* Update resume latency value if the measured time exceeds it. */
693         if (timed && runtime_pm) {
694                 elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
695                 if (elapsed_ns > td->resume_latency_ns) {
696                         td->resume_latency_ns = elapsed_ns;
697                         dev_dbg(dev, "resume latency exceeded, %lld ns\n",
698                                 elapsed_ns);
699                         genpd->max_off_time_changed = true;
700                         td->constraint_changed = true;
701                 }
702         }
703
704         return 0;
705
706 err_stop:
707         genpd_stop_dev(genpd, dev);
708 err_poweroff:
709         if (!pm_runtime_is_irq_safe(dev) ||
710                 (pm_runtime_is_irq_safe(dev) && genpd_is_irq_safe(genpd))) {
711                 genpd_lock(genpd);
712                 genpd_power_off(genpd, true, 0);
713                 genpd_unlock(genpd);
714         }
715
716         return ret;
717 }
718
719 static bool pd_ignore_unused;
720 static int __init pd_ignore_unused_setup(char *__unused)
721 {
722         pd_ignore_unused = true;
723         return 1;
724 }
725 __setup("pd_ignore_unused", pd_ignore_unused_setup);
726
727 /**
728  * genpd_power_off_unused - Power off all PM domains with no devices in use.
729  */
730 static int __init genpd_power_off_unused(void)
731 {
732         struct generic_pm_domain *genpd;
733
734         if (pd_ignore_unused) {
735                 pr_warn("genpd: Not disabling unused power domains\n");
736                 return 0;
737         }
738
739         mutex_lock(&gpd_list_lock);
740
741         list_for_each_entry(genpd, &gpd_list, gpd_list_node)
742                 genpd_queue_power_off_work(genpd);
743
744         mutex_unlock(&gpd_list_lock);
745
746         return 0;
747 }
748 late_initcall(genpd_power_off_unused);
749
750 #if defined(CONFIG_PM_SLEEP) || defined(CONFIG_PM_GENERIC_DOMAINS_OF)
751
752 /**
753  * pm_genpd_present - Check if the given PM domain has been initialized.
754  * @genpd: PM domain to check.
755  */
756 static bool pm_genpd_present(const struct generic_pm_domain *genpd)
757 {
758         const struct generic_pm_domain *gpd;
759
760         if (IS_ERR_OR_NULL(genpd))
761                 return false;
762
763         list_for_each_entry(gpd, &gpd_list, gpd_list_node)
764                 if (gpd == genpd)
765                         return true;
766
767         return false;
768 }
769
770 #endif
771
772 #ifdef CONFIG_PM_SLEEP
773
774 static bool genpd_dev_active_wakeup(const struct generic_pm_domain *genpd,
775                                     struct device *dev)
776 {
777         return GENPD_DEV_CALLBACK(genpd, bool, active_wakeup, dev);
778 }
779
780 /**
781  * genpd_sync_power_off - Synchronously power off a PM domain and its masters.
782  * @genpd: PM domain to power off, if possible.
783  * @use_lock: use the lock.
784  * @depth: nesting count for lockdep.
785  *
786  * Check if the given PM domain can be powered off (during system suspend or
787  * hibernation) and do that if so.  Also, in that case propagate to its masters.
788  *
789  * This function is only called in "noirq" and "syscore" stages of system power
790  * transitions. The "noirq" callbacks may be executed asynchronously, thus in
791  * these cases the lock must be held.
792  */
793 static void genpd_sync_power_off(struct generic_pm_domain *genpd, bool use_lock,
794                                  unsigned int depth)
795 {
796         struct gpd_link *link;
797
798         if (!genpd_status_on(genpd) || genpd_is_always_on(genpd))
799                 return;
800
801         if (genpd->suspended_count != genpd->device_count
802             || atomic_read(&genpd->sd_count) > 0)
803                 return;
804
805         /* Choose the deepest state when suspending */
806         genpd->state_idx = genpd->state_count - 1;
807         if (_genpd_power_off(genpd, false))
808                 return;
809
810         genpd->status = GPD_STATE_POWER_OFF;
811
812         list_for_each_entry(link, &genpd->slave_links, slave_node) {
813                 genpd_sd_counter_dec(link->master);
814
815                 if (use_lock)
816                         genpd_lock_nested(link->master, depth + 1);
817
818                 genpd_sync_power_off(link->master, use_lock, depth + 1);
819
820                 if (use_lock)
821                         genpd_unlock(link->master);
822         }
823 }
824
825 /**
826  * genpd_sync_power_on - Synchronously power on a PM domain and its masters.
827  * @genpd: PM domain to power on.
828  * @use_lock: use the lock.
829  * @depth: nesting count for lockdep.
830  *
831  * This function is only called in "noirq" and "syscore" stages of system power
832  * transitions. The "noirq" callbacks may be executed asynchronously, thus in
833  * these cases the lock must be held.
834  */
835 static void genpd_sync_power_on(struct generic_pm_domain *genpd, bool use_lock,
836                                 unsigned int depth)
837 {
838         struct gpd_link *link;
839
840         if (genpd_status_on(genpd))
841                 return;
842
843         list_for_each_entry(link, &genpd->slave_links, slave_node) {
844                 genpd_sd_counter_inc(link->master);
845
846                 if (use_lock)
847                         genpd_lock_nested(link->master, depth + 1);
848
849                 genpd_sync_power_on(link->master, use_lock, depth + 1);
850
851                 if (use_lock)
852                         genpd_unlock(link->master);
853         }
854
855         _genpd_power_on(genpd, false);
856
857         genpd->status = GPD_STATE_ACTIVE;
858 }
859
860 /**
861  * resume_needed - Check whether to resume a device before system suspend.
862  * @dev: Device to check.
863  * @genpd: PM domain the device belongs to.
864  *
865  * There are two cases in which a device that can wake up the system from sleep
866  * states should be resumed by pm_genpd_prepare(): (1) if the device is enabled
867  * to wake up the system and it has to remain active for this purpose while the
868  * system is in the sleep state and (2) if the device is not enabled to wake up
869  * the system from sleep states and it generally doesn't generate wakeup signals
870  * by itself (those signals are generated on its behalf by other parts of the
871  * system).  In the latter case it may be necessary to reconfigure the device's
872  * wakeup settings during system suspend, because it may have been set up to
873  * signal remote wakeup from the system's working state as needed by runtime PM.
874  * Return 'true' in either of the above cases.
875  */
876 static bool resume_needed(struct device *dev,
877                           const struct generic_pm_domain *genpd)
878 {
879         bool active_wakeup;
880
881         if (!device_can_wakeup(dev))
882                 return false;
883
884         active_wakeup = genpd_dev_active_wakeup(genpd, dev);
885         return device_may_wakeup(dev) ? active_wakeup : !active_wakeup;
886 }
887
888 /**
889  * pm_genpd_prepare - Start power transition of a device in a PM domain.
890  * @dev: Device to start the transition of.
891  *
892  * Start a power transition of a device (during a system-wide power transition)
893  * under the assumption that its pm_domain field points to the domain member of
894  * an object of type struct generic_pm_domain representing a PM domain
895  * consisting of I/O devices.
896  */
897 static int pm_genpd_prepare(struct device *dev)
898 {
899         struct generic_pm_domain *genpd;
900         int ret;
901
902         dev_dbg(dev, "%s()\n", __func__);
903
904         genpd = dev_to_genpd(dev);
905         if (IS_ERR(genpd))
906                 return -EINVAL;
907
908         /*
909          * If a wakeup request is pending for the device, it should be woken up
910          * at this point and a system wakeup event should be reported if it's
911          * set up to wake up the system from sleep states.
912          */
913         if (resume_needed(dev, genpd))
914                 pm_runtime_resume(dev);
915
916         genpd_lock(genpd);
917
918         if (genpd->prepared_count++ == 0)
919                 genpd->suspended_count = 0;
920
921         genpd_unlock(genpd);
922
923         ret = pm_generic_prepare(dev);
924         if (ret < 0) {
925                 genpd_lock(genpd);
926
927                 genpd->prepared_count--;
928
929                 genpd_unlock(genpd);
930         }
931
932         /* Never return 1, as genpd don't cope with the direct_complete path. */
933         return ret >= 0 ? 0 : ret;
934 }
935
936 /**
937  * genpd_finish_suspend - Completion of suspend or hibernation of device in an
938  *   I/O pm domain.
939  * @dev: Device to suspend.
940  * @poweroff: Specifies if this is a poweroff_noirq or suspend_noirq callback.
941  *
942  * Stop the device and remove power from the domain if all devices in it have
943  * been stopped.
944  */
945 static int genpd_finish_suspend(struct device *dev, bool poweroff)
946 {
947         struct generic_pm_domain *genpd;
948         int ret;
949
950         genpd = dev_to_genpd(dev);
951         if (IS_ERR(genpd))
952                 return -EINVAL;
953
954         if (dev->power.wakeup_path && genpd_dev_active_wakeup(genpd, dev))
955                 return 0;
956
957         if (poweroff)
958                 ret = pm_generic_poweroff_noirq(dev);
959         else
960                 ret = pm_generic_suspend_noirq(dev);
961         if (ret)
962                 return ret;
963
964         if (genpd->dev_ops.stop && genpd->dev_ops.start) {
965                 ret = pm_runtime_force_suspend(dev);
966                 if (ret)
967                         return ret;
968         }
969
970         genpd_lock(genpd);
971         genpd->suspended_count++;
972         genpd_sync_power_off(genpd, true, 0);
973         genpd_unlock(genpd);
974
975         return 0;
976 }
977
978 /**
979  * pm_genpd_suspend_noirq - Completion of suspend of device in an I/O PM domain.
980  * @dev: Device to suspend.
981  *
982  * Stop the device and remove power from the domain if all devices in it have
983  * been stopped.
984  */
985 static int pm_genpd_suspend_noirq(struct device *dev)
986 {
987         dev_dbg(dev, "%s()\n", __func__);
988
989         return genpd_finish_suspend(dev, false);
990 }
991
992 /**
993  * pm_genpd_resume_noirq - Start of resume of device in an I/O PM domain.
994  * @dev: Device to resume.
995  *
996  * Restore power to the device's PM domain, if necessary, and start the device.
997  */
998 static int pm_genpd_resume_noirq(struct device *dev)
999 {
1000         struct generic_pm_domain *genpd;
1001         int ret = 0;
1002
1003         dev_dbg(dev, "%s()\n", __func__);
1004
1005         genpd = dev_to_genpd(dev);
1006         if (IS_ERR(genpd))
1007                 return -EINVAL;
1008
1009         if (dev->power.wakeup_path && genpd_dev_active_wakeup(genpd, dev))
1010                 return 0;
1011
1012         genpd_lock(genpd);
1013         genpd_sync_power_on(genpd, true, 0);
1014         genpd->suspended_count--;
1015         genpd_unlock(genpd);
1016
1017         if (genpd->dev_ops.stop && genpd->dev_ops.start)
1018                 ret = pm_runtime_force_resume(dev);
1019
1020         ret = pm_generic_resume_noirq(dev);
1021         if (ret)
1022                 return ret;
1023
1024         return ret;
1025 }
1026
1027 /**
1028  * pm_genpd_freeze_noirq - Completion of freezing a device in an I/O PM domain.
1029  * @dev: Device to freeze.
1030  *
1031  * Carry out a late freeze of a device under the assumption that its
1032  * pm_domain field points to the domain member of an object of type
1033  * struct generic_pm_domain representing a power domain consisting of I/O
1034  * devices.
1035  */
1036 static int pm_genpd_freeze_noirq(struct device *dev)
1037 {
1038         const struct generic_pm_domain *genpd;
1039         int ret = 0;
1040
1041         dev_dbg(dev, "%s()\n", __func__);
1042
1043         genpd = dev_to_genpd(dev);
1044         if (IS_ERR(genpd))
1045                 return -EINVAL;
1046
1047         ret = pm_generic_freeze_noirq(dev);
1048         if (ret)
1049                 return ret;
1050
1051         if (genpd->dev_ops.stop && genpd->dev_ops.start)
1052                 ret = pm_runtime_force_suspend(dev);
1053
1054         return ret;
1055 }
1056
1057 /**
1058  * pm_genpd_thaw_noirq - Early thaw of device in an I/O PM domain.
1059  * @dev: Device to thaw.
1060  *
1061  * Start the device, unless power has been removed from the domain already
1062  * before the system transition.
1063  */
1064 static int pm_genpd_thaw_noirq(struct device *dev)
1065 {
1066         const struct generic_pm_domain *genpd;
1067         int ret = 0;
1068
1069         dev_dbg(dev, "%s()\n", __func__);
1070
1071         genpd = dev_to_genpd(dev);
1072         if (IS_ERR(genpd))
1073                 return -EINVAL;
1074
1075         if (genpd->dev_ops.stop && genpd->dev_ops.start) {
1076                 ret = pm_runtime_force_resume(dev);
1077                 if (ret)
1078                         return ret;
1079         }
1080
1081         return pm_generic_thaw_noirq(dev);
1082 }
1083
1084 /**
1085  * pm_genpd_poweroff_noirq - Completion of hibernation of device in an
1086  *   I/O PM domain.
1087  * @dev: Device to poweroff.
1088  *
1089  * Stop the device and remove power from the domain if all devices in it have
1090  * been stopped.
1091  */
1092 static int pm_genpd_poweroff_noirq(struct device *dev)
1093 {
1094         dev_dbg(dev, "%s()\n", __func__);
1095
1096         return genpd_finish_suspend(dev, true);
1097 }
1098
1099 /**
1100  * pm_genpd_restore_noirq - Start of restore of device in an I/O PM domain.
1101  * @dev: Device to resume.
1102  *
1103  * Make sure the domain will be in the same power state as before the
1104  * hibernation the system is resuming from and start the device if necessary.
1105  */
1106 static int pm_genpd_restore_noirq(struct device *dev)
1107 {
1108         struct generic_pm_domain *genpd;
1109         int ret = 0;
1110
1111         dev_dbg(dev, "%s()\n", __func__);
1112
1113         genpd = dev_to_genpd(dev);
1114         if (IS_ERR(genpd))
1115                 return -EINVAL;
1116
1117         /*
1118          * At this point suspended_count == 0 means we are being run for the
1119          * first time for the given domain in the present cycle.
1120          */
1121         genpd_lock(genpd);
1122         if (genpd->suspended_count++ == 0)
1123                 /*
1124                  * The boot kernel might put the domain into arbitrary state,
1125                  * so make it appear as powered off to genpd_sync_power_on(),
1126                  * so that it tries to power it on in case it was really off.
1127                  */
1128                 genpd->status = GPD_STATE_POWER_OFF;
1129
1130         genpd_sync_power_on(genpd, true, 0);
1131         genpd_unlock(genpd);
1132
1133         if (genpd->dev_ops.stop && genpd->dev_ops.start) {
1134                 ret = pm_runtime_force_resume(dev);
1135                 if (ret)
1136                         return ret;
1137         }
1138
1139         return pm_generic_restore_noirq(dev);
1140 }
1141
1142 /**
1143  * pm_genpd_complete - Complete power transition of a device in a power domain.
1144  * @dev: Device to complete the transition of.
1145  *
1146  * Complete a power transition of a device (during a system-wide power
1147  * transition) under the assumption that its pm_domain field points to the
1148  * domain member of an object of type struct generic_pm_domain representing
1149  * a power domain consisting of I/O devices.
1150  */
1151 static void pm_genpd_complete(struct device *dev)
1152 {
1153         struct generic_pm_domain *genpd;
1154
1155         dev_dbg(dev, "%s()\n", __func__);
1156
1157         genpd = dev_to_genpd(dev);
1158         if (IS_ERR(genpd))
1159                 return;
1160
1161         pm_generic_complete(dev);
1162
1163         genpd_lock(genpd);
1164
1165         genpd->prepared_count--;
1166         if (!genpd->prepared_count)
1167                 genpd_queue_power_off_work(genpd);
1168
1169         genpd_unlock(genpd);
1170 }
1171
1172 /**
1173  * genpd_syscore_switch - Switch power during system core suspend or resume.
1174  * @dev: Device that normally is marked as "always on" to switch power for.
1175  *
1176  * This routine may only be called during the system core (syscore) suspend or
1177  * resume phase for devices whose "always on" flags are set.
1178  */
1179 static void genpd_syscore_switch(struct device *dev, bool suspend)
1180 {
1181         struct generic_pm_domain *genpd;
1182
1183         genpd = dev_to_genpd(dev);
1184         if (!pm_genpd_present(genpd))
1185                 return;
1186
1187         if (suspend) {
1188                 genpd->suspended_count++;
1189                 genpd_sync_power_off(genpd, false, 0);
1190         } else {
1191                 genpd_sync_power_on(genpd, false, 0);
1192                 genpd->suspended_count--;
1193         }
1194 }
1195
1196 void pm_genpd_syscore_poweroff(struct device *dev)
1197 {
1198         genpd_syscore_switch(dev, true);
1199 }
1200 EXPORT_SYMBOL_GPL(pm_genpd_syscore_poweroff);
1201
1202 void pm_genpd_syscore_poweron(struct device *dev)
1203 {
1204         genpd_syscore_switch(dev, false);
1205 }
1206 EXPORT_SYMBOL_GPL(pm_genpd_syscore_poweron);
1207
1208 #else /* !CONFIG_PM_SLEEP */
1209
1210 #define pm_genpd_prepare                NULL
1211 #define pm_genpd_suspend_noirq          NULL
1212 #define pm_genpd_resume_noirq           NULL
1213 #define pm_genpd_freeze_noirq           NULL
1214 #define pm_genpd_thaw_noirq             NULL
1215 #define pm_genpd_poweroff_noirq         NULL
1216 #define pm_genpd_restore_noirq          NULL
1217 #define pm_genpd_complete               NULL
1218
1219 #endif /* CONFIG_PM_SLEEP */
1220
1221 static struct generic_pm_domain_data *genpd_alloc_dev_data(struct device *dev,
1222                                         struct generic_pm_domain *genpd,
1223                                         struct gpd_timing_data *td)
1224 {
1225         struct generic_pm_domain_data *gpd_data;
1226         int ret;
1227
1228         ret = dev_pm_get_subsys_data(dev);
1229         if (ret)
1230                 return ERR_PTR(ret);
1231
1232         gpd_data = kzalloc(sizeof(*gpd_data), GFP_KERNEL);
1233         if (!gpd_data) {
1234                 ret = -ENOMEM;
1235                 goto err_put;
1236         }
1237
1238         if (td)
1239                 gpd_data->td = *td;
1240
1241         gpd_data->base.dev = dev;
1242         gpd_data->td.constraint_changed = true;
1243         gpd_data->td.effective_constraint_ns = -1;
1244         gpd_data->nb.notifier_call = genpd_dev_pm_qos_notifier;
1245
1246         spin_lock_irq(&dev->power.lock);
1247
1248         if (dev->power.subsys_data->domain_data) {
1249                 ret = -EINVAL;
1250                 goto err_free;
1251         }
1252
1253         dev->power.subsys_data->domain_data = &gpd_data->base;
1254
1255         spin_unlock_irq(&dev->power.lock);
1256
1257         return gpd_data;
1258
1259  err_free:
1260         spin_unlock_irq(&dev->power.lock);
1261         kfree(gpd_data);
1262  err_put:
1263         dev_pm_put_subsys_data(dev);
1264         return ERR_PTR(ret);
1265 }
1266
1267 static void genpd_free_dev_data(struct device *dev,
1268                                 struct generic_pm_domain_data *gpd_data)
1269 {
1270         spin_lock_irq(&dev->power.lock);
1271
1272         dev->power.subsys_data->domain_data = NULL;
1273
1274         spin_unlock_irq(&dev->power.lock);
1275
1276         kfree(gpd_data);
1277         dev_pm_put_subsys_data(dev);
1278 }
1279
1280 static int genpd_add_device(struct generic_pm_domain *genpd, struct device *dev,
1281                             struct gpd_timing_data *td)
1282 {
1283         struct generic_pm_domain_data *gpd_data;
1284         int ret = 0;
1285
1286         dev_dbg(dev, "%s()\n", __func__);
1287
1288         if (IS_ERR_OR_NULL(genpd) || IS_ERR_OR_NULL(dev))
1289                 return -EINVAL;
1290
1291         gpd_data = genpd_alloc_dev_data(dev, genpd, td);
1292         if (IS_ERR(gpd_data))
1293                 return PTR_ERR(gpd_data);
1294
1295         genpd_lock(genpd);
1296
1297         if (genpd->prepared_count > 0) {
1298                 ret = -EAGAIN;
1299                 goto out;
1300         }
1301
1302         ret = genpd->attach_dev ? genpd->attach_dev(genpd, dev) : 0;
1303         if (ret)
1304                 goto out;
1305
1306         dev_pm_domain_set(dev, &genpd->domain);
1307
1308         genpd->device_count++;
1309         genpd->max_off_time_changed = true;
1310
1311         list_add_tail(&gpd_data->base.list_node, &genpd->dev_list);
1312
1313  out:
1314         genpd_unlock(genpd);
1315
1316         if (ret)
1317                 genpd_free_dev_data(dev, gpd_data);
1318         else
1319                 dev_pm_qos_add_notifier(dev, &gpd_data->nb);
1320
1321         return ret;
1322 }
1323
1324 /**
1325  * __pm_genpd_add_device - Add a device to an I/O PM domain.
1326  * @genpd: PM domain to add the device to.
1327  * @dev: Device to be added.
1328  * @td: Set of PM QoS timing parameters to attach to the device.
1329  */
1330 int __pm_genpd_add_device(struct generic_pm_domain *genpd, struct device *dev,
1331                           struct gpd_timing_data *td)
1332 {
1333         int ret;
1334
1335         mutex_lock(&gpd_list_lock);
1336         ret = genpd_add_device(genpd, dev, td);
1337         mutex_unlock(&gpd_list_lock);
1338
1339         return ret;
1340 }
1341 EXPORT_SYMBOL_GPL(__pm_genpd_add_device);
1342
1343 static int genpd_remove_device(struct generic_pm_domain *genpd,
1344                                struct device *dev)
1345 {
1346         struct generic_pm_domain_data *gpd_data;
1347         struct pm_domain_data *pdd;
1348         int ret = 0;
1349
1350         dev_dbg(dev, "%s()\n", __func__);
1351
1352         pdd = dev->power.subsys_data->domain_data;
1353         gpd_data = to_gpd_data(pdd);
1354         dev_pm_qos_remove_notifier(dev, &gpd_data->nb);
1355
1356         genpd_lock(genpd);
1357
1358         if (genpd->prepared_count > 0) {
1359                 ret = -EAGAIN;
1360                 goto out;
1361         }
1362
1363         genpd->device_count--;
1364         genpd->max_off_time_changed = true;
1365
1366         if (genpd->detach_dev)
1367                 genpd->detach_dev(genpd, dev);
1368
1369         dev_pm_domain_set(dev, NULL);
1370
1371         list_del_init(&pdd->list_node);
1372
1373         genpd_unlock(genpd);
1374
1375         genpd_free_dev_data(dev, gpd_data);
1376
1377         return 0;
1378
1379  out:
1380         genpd_unlock(genpd);
1381         dev_pm_qos_add_notifier(dev, &gpd_data->nb);
1382
1383         return ret;
1384 }
1385
1386 /**
1387  * pm_genpd_remove_device - Remove a device from an I/O PM domain.
1388  * @genpd: PM domain to remove the device from.
1389  * @dev: Device to be removed.
1390  */
1391 int pm_genpd_remove_device(struct generic_pm_domain *genpd,
1392                            struct device *dev)
1393 {
1394         if (!genpd || genpd != genpd_lookup_dev(dev))
1395                 return -EINVAL;
1396
1397         return genpd_remove_device(genpd, dev);
1398 }
1399 EXPORT_SYMBOL_GPL(pm_genpd_remove_device);
1400
1401 static int genpd_add_subdomain(struct generic_pm_domain *genpd,
1402                                struct generic_pm_domain *subdomain)
1403 {
1404         struct gpd_link *link, *itr;
1405         int ret = 0;
1406
1407         if (IS_ERR_OR_NULL(genpd) || IS_ERR_OR_NULL(subdomain)
1408             || genpd == subdomain)
1409                 return -EINVAL;
1410
1411         /*
1412          * If the domain can be powered on/off in an IRQ safe
1413          * context, ensure that the subdomain can also be
1414          * powered on/off in that context.
1415          */
1416         if (!genpd_is_irq_safe(genpd) && genpd_is_irq_safe(subdomain)) {
1417                 WARN(1, "Parent %s of subdomain %s must be IRQ safe\n",
1418                                 genpd->name, subdomain->name);
1419                 return -EINVAL;
1420         }
1421
1422         link = kzalloc(sizeof(*link), GFP_KERNEL);
1423         if (!link)
1424                 return -ENOMEM;
1425
1426         genpd_lock(subdomain);
1427         genpd_lock_nested(genpd, SINGLE_DEPTH_NESTING);
1428
1429         if (!genpd_status_on(genpd) && genpd_status_on(subdomain)) {
1430                 ret = -EINVAL;
1431                 goto out;
1432         }
1433
1434         list_for_each_entry(itr, &genpd->master_links, master_node) {
1435                 if (itr->slave == subdomain && itr->master == genpd) {
1436                         ret = -EINVAL;
1437                         goto out;
1438                 }
1439         }
1440
1441         link->master = genpd;
1442         list_add_tail(&link->master_node, &genpd->master_links);
1443         link->slave = subdomain;
1444         list_add_tail(&link->slave_node, &subdomain->slave_links);
1445         if (genpd_status_on(subdomain))
1446                 genpd_sd_counter_inc(genpd);
1447
1448  out:
1449         genpd_unlock(genpd);
1450         genpd_unlock(subdomain);
1451         if (ret)
1452                 kfree(link);
1453         return ret;
1454 }
1455
1456 /**
1457  * pm_genpd_add_subdomain - Add a subdomain to an I/O PM domain.
1458  * @genpd: Master PM domain to add the subdomain to.
1459  * @subdomain: Subdomain to be added.
1460  */
1461 int pm_genpd_add_subdomain(struct generic_pm_domain *genpd,
1462                            struct generic_pm_domain *subdomain)
1463 {
1464         int ret;
1465
1466         mutex_lock(&gpd_list_lock);
1467         ret = genpd_add_subdomain(genpd, subdomain);
1468         mutex_unlock(&gpd_list_lock);
1469
1470         return ret;
1471 }
1472 EXPORT_SYMBOL_GPL(pm_genpd_add_subdomain);
1473
1474 /**
1475  * pm_genpd_remove_subdomain - Remove a subdomain from an I/O PM domain.
1476  * @genpd: Master PM domain to remove the subdomain from.
1477  * @subdomain: Subdomain to be removed.
1478  */
1479 int pm_genpd_remove_subdomain(struct generic_pm_domain *genpd,
1480                               struct generic_pm_domain *subdomain)
1481 {
1482         struct gpd_link *l, *link;
1483         int ret = -EINVAL;
1484
1485         if (IS_ERR_OR_NULL(genpd) || IS_ERR_OR_NULL(subdomain))
1486                 return -EINVAL;
1487
1488         genpd_lock(subdomain);
1489         genpd_lock_nested(genpd, SINGLE_DEPTH_NESTING);
1490
1491         if (!list_empty(&subdomain->master_links) || subdomain->device_count) {
1492                 pr_warn("%s: unable to remove subdomain %s\n", genpd->name,
1493                         subdomain->name);
1494                 ret = -EBUSY;
1495                 goto out;
1496         }
1497
1498         list_for_each_entry_safe(link, l, &genpd->master_links, master_node) {
1499                 if (link->slave != subdomain)
1500                         continue;
1501
1502                 list_del(&link->master_node);
1503                 list_del(&link->slave_node);
1504                 kfree(link);
1505                 if (genpd_status_on(subdomain))
1506                         genpd_sd_counter_dec(genpd);
1507
1508                 ret = 0;
1509                 break;
1510         }
1511
1512 out:
1513         genpd_unlock(genpd);
1514         genpd_unlock(subdomain);
1515
1516         return ret;
1517 }
1518 EXPORT_SYMBOL_GPL(pm_genpd_remove_subdomain);
1519
1520 static int genpd_set_default_power_state(struct generic_pm_domain *genpd)
1521 {
1522         struct genpd_power_state *state;
1523
1524         state = kzalloc(sizeof(*state), GFP_KERNEL);
1525         if (!state)
1526                 return -ENOMEM;
1527
1528         genpd->states = state;
1529         genpd->state_count = 1;
1530         genpd->free = state;
1531
1532         return 0;
1533 }
1534
1535 static void genpd_lock_init(struct generic_pm_domain *genpd)
1536 {
1537         if (genpd->flags & GENPD_FLAG_IRQ_SAFE) {
1538                 spin_lock_init(&genpd->slock);
1539                 genpd->lock_ops = &genpd_spin_ops;
1540         } else {
1541                 mutex_init(&genpd->mlock);
1542                 genpd->lock_ops = &genpd_mtx_ops;
1543         }
1544 }
1545
1546 /**
1547  * pm_genpd_init - Initialize a generic I/O PM domain object.
1548  * @genpd: PM domain object to initialize.
1549  * @gov: PM domain governor to associate with the domain (may be NULL).
1550  * @is_off: Initial value of the domain's power_is_off field.
1551  *
1552  * Returns 0 on successful initialization, else a negative error code.
1553  */
1554 int pm_genpd_init(struct generic_pm_domain *genpd,
1555                   struct dev_power_governor *gov, bool is_off)
1556 {
1557         int ret;
1558
1559         if (IS_ERR_OR_NULL(genpd))
1560                 return -EINVAL;
1561
1562         INIT_LIST_HEAD(&genpd->master_links);
1563         INIT_LIST_HEAD(&genpd->slave_links);
1564         INIT_LIST_HEAD(&genpd->dev_list);
1565         genpd_lock_init(genpd);
1566         genpd->gov = gov;
1567         INIT_WORK(&genpd->power_off_work, genpd_power_off_work_fn);
1568         atomic_set(&genpd->sd_count, 0);
1569         genpd->status = is_off ? GPD_STATE_POWER_OFF : GPD_STATE_ACTIVE;
1570         genpd->device_count = 0;
1571         genpd->max_off_time_ns = -1;
1572         genpd->max_off_time_changed = true;
1573         genpd->provider = NULL;
1574         genpd->has_provider = false;
1575         genpd->accounting_time = ktime_get();
1576         genpd->domain.ops.runtime_suspend = genpd_runtime_suspend;
1577         genpd->domain.ops.runtime_resume = genpd_runtime_resume;
1578         genpd->domain.ops.prepare = pm_genpd_prepare;
1579         genpd->domain.ops.suspend_noirq = pm_genpd_suspend_noirq;
1580         genpd->domain.ops.resume_noirq = pm_genpd_resume_noirq;
1581         genpd->domain.ops.freeze_noirq = pm_genpd_freeze_noirq;
1582         genpd->domain.ops.thaw_noirq = pm_genpd_thaw_noirq;
1583         genpd->domain.ops.poweroff_noirq = pm_genpd_poweroff_noirq;
1584         genpd->domain.ops.restore_noirq = pm_genpd_restore_noirq;
1585         genpd->domain.ops.complete = pm_genpd_complete;
1586
1587         if (genpd->flags & GENPD_FLAG_PM_CLK) {
1588                 genpd->dev_ops.stop = pm_clk_suspend;
1589                 genpd->dev_ops.start = pm_clk_resume;
1590         }
1591
1592         /* Always-on domains must be powered on at initialization. */
1593         if (genpd_is_always_on(genpd) && !genpd_status_on(genpd))
1594                 return -EINVAL;
1595
1596         /* Use only one "off" state if there were no states declared */
1597         if (genpd->state_count == 0) {
1598                 ret = genpd_set_default_power_state(genpd);
1599                 if (ret)
1600                         return ret;
1601         }
1602
1603         mutex_lock(&gpd_list_lock);
1604         list_add(&genpd->gpd_list_node, &gpd_list);
1605         mutex_unlock(&gpd_list_lock);
1606
1607         return 0;
1608 }
1609 EXPORT_SYMBOL_GPL(pm_genpd_init);
1610
1611 static int genpd_remove(struct generic_pm_domain *genpd)
1612 {
1613         struct gpd_link *l, *link;
1614
1615         if (IS_ERR_OR_NULL(genpd))
1616                 return -EINVAL;
1617
1618         genpd_lock(genpd);
1619
1620         if (genpd->has_provider) {
1621                 genpd_unlock(genpd);
1622                 pr_err("Provider present, unable to remove %s\n", genpd->name);
1623                 return -EBUSY;
1624         }
1625
1626         if (!list_empty(&genpd->master_links) || genpd->device_count) {
1627                 genpd_unlock(genpd);
1628                 pr_err("%s: unable to remove %s\n", __func__, genpd->name);
1629                 return -EBUSY;
1630         }
1631
1632         list_for_each_entry_safe(link, l, &genpd->slave_links, slave_node) {
1633                 list_del(&link->master_node);
1634                 list_del(&link->slave_node);
1635                 kfree(link);
1636         }
1637
1638         list_del(&genpd->gpd_list_node);
1639         genpd_unlock(genpd);
1640         cancel_work_sync(&genpd->power_off_work);
1641         kfree(genpd->free);
1642         pr_debug("%s: removed %s\n", __func__, genpd->name);
1643
1644         return 0;
1645 }
1646
1647 /**
1648  * pm_genpd_remove - Remove a generic I/O PM domain
1649  * @genpd: Pointer to PM domain that is to be removed.
1650  *
1651  * To remove the PM domain, this function:
1652  *  - Removes the PM domain as a subdomain to any parent domains,
1653  *    if it was added.
1654  *  - Removes the PM domain from the list of registered PM domains.
1655  *
1656  * The PM domain will only be removed, if the associated provider has
1657  * been removed, it is not a parent to any other PM domain and has no
1658  * devices associated with it.
1659  */
1660 int pm_genpd_remove(struct generic_pm_domain *genpd)
1661 {
1662         int ret;
1663
1664         mutex_lock(&gpd_list_lock);
1665         ret = genpd_remove(genpd);
1666         mutex_unlock(&gpd_list_lock);
1667
1668         return ret;
1669 }
1670 EXPORT_SYMBOL_GPL(pm_genpd_remove);
1671
1672 #ifdef CONFIG_PM_GENERIC_DOMAINS_OF
1673
1674 /*
1675  * Device Tree based PM domain providers.
1676  *
1677  * The code below implements generic device tree based PM domain providers that
1678  * bind device tree nodes with generic PM domains registered in the system.
1679  *
1680  * Any driver that registers generic PM domains and needs to support binding of
1681  * devices to these domains is supposed to register a PM domain provider, which
1682  * maps a PM domain specifier retrieved from the device tree to a PM domain.
1683  *
1684  * Two simple mapping functions have been provided for convenience:
1685  *  - genpd_xlate_simple() for 1:1 device tree node to PM domain mapping.
1686  *  - genpd_xlate_onecell() for mapping of multiple PM domains per node by
1687  *    index.
1688  */
1689
1690 /**
1691  * struct of_genpd_provider - PM domain provider registration structure
1692  * @link: Entry in global list of PM domain providers
1693  * @node: Pointer to device tree node of PM domain provider
1694  * @xlate: Provider-specific xlate callback mapping a set of specifier cells
1695  *         into a PM domain.
1696  * @data: context pointer to be passed into @xlate callback
1697  */
1698 struct of_genpd_provider {
1699         struct list_head link;
1700         struct device_node *node;
1701         genpd_xlate_t xlate;
1702         void *data;
1703 };
1704
1705 /* List of registered PM domain providers. */
1706 static LIST_HEAD(of_genpd_providers);
1707 /* Mutex to protect the list above. */
1708 static DEFINE_MUTEX(of_genpd_mutex);
1709
1710 /**
1711  * genpd_xlate_simple() - Xlate function for direct node-domain mapping
1712  * @genpdspec: OF phandle args to map into a PM domain
1713  * @data: xlate function private data - pointer to struct generic_pm_domain
1714  *
1715  * This is a generic xlate function that can be used to model PM domains that
1716  * have their own device tree nodes. The private data of xlate function needs
1717  * to be a valid pointer to struct generic_pm_domain.
1718  */
1719 static struct generic_pm_domain *genpd_xlate_simple(
1720                                         struct of_phandle_args *genpdspec,
1721                                         void *data)
1722 {
1723         return data;
1724 }
1725
1726 /**
1727  * genpd_xlate_onecell() - Xlate function using a single index.
1728  * @genpdspec: OF phandle args to map into a PM domain
1729  * @data: xlate function private data - pointer to struct genpd_onecell_data
1730  *
1731  * This is a generic xlate function that can be used to model simple PM domain
1732  * controllers that have one device tree node and provide multiple PM domains.
1733  * A single cell is used as an index into an array of PM domains specified in
1734  * the genpd_onecell_data struct when registering the provider.
1735  */
1736 static struct generic_pm_domain *genpd_xlate_onecell(
1737                                         struct of_phandle_args *genpdspec,
1738                                         void *data)
1739 {
1740         struct genpd_onecell_data *genpd_data = data;
1741         unsigned int idx = genpdspec->args[0];
1742
1743         if (genpdspec->args_count != 1)
1744                 return ERR_PTR(-EINVAL);
1745
1746         if (idx >= genpd_data->num_domains) {
1747                 pr_err("%s: invalid domain index %u\n", __func__, idx);
1748                 return ERR_PTR(-EINVAL);
1749         }
1750
1751         if (!genpd_data->domains[idx])
1752                 return ERR_PTR(-ENOENT);
1753
1754         return genpd_data->domains[idx];
1755 }
1756
1757 /**
1758  * genpd_add_provider() - Register a PM domain provider for a node
1759  * @np: Device node pointer associated with the PM domain provider.
1760  * @xlate: Callback for decoding PM domain from phandle arguments.
1761  * @data: Context pointer for @xlate callback.
1762  */
1763 static int genpd_add_provider(struct device_node *np, genpd_xlate_t xlate,
1764                               void *data)
1765 {
1766         struct of_genpd_provider *cp;
1767
1768         cp = kzalloc(sizeof(*cp), GFP_KERNEL);
1769         if (!cp)
1770                 return -ENOMEM;
1771
1772         cp->node = of_node_get(np);
1773         cp->data = data;
1774         cp->xlate = xlate;
1775
1776         mutex_lock(&of_genpd_mutex);
1777         list_add(&cp->link, &of_genpd_providers);
1778         mutex_unlock(&of_genpd_mutex);
1779         pr_debug("Added domain provider from %pOF\n", np);
1780
1781         return 0;
1782 }
1783
1784 /**
1785  * of_genpd_add_provider_simple() - Register a simple PM domain provider
1786  * @np: Device node pointer associated with the PM domain provider.
1787  * @genpd: Pointer to PM domain associated with the PM domain provider.
1788  */
1789 int of_genpd_add_provider_simple(struct device_node *np,
1790                                  struct generic_pm_domain *genpd)
1791 {
1792         int ret = -EINVAL;
1793
1794         if (!np || !genpd)
1795                 return -EINVAL;
1796
1797         mutex_lock(&gpd_list_lock);
1798
1799         if (pm_genpd_present(genpd)) {
1800                 ret = genpd_add_provider(np, genpd_xlate_simple, genpd);
1801                 if (!ret) {
1802                         genpd->provider = &np->fwnode;
1803                         genpd->has_provider = true;
1804                 }
1805         }
1806
1807         mutex_unlock(&gpd_list_lock);
1808
1809         return ret;
1810 }
1811 EXPORT_SYMBOL_GPL(of_genpd_add_provider_simple);
1812
1813 /**
1814  * of_genpd_add_provider_onecell() - Register a onecell PM domain provider
1815  * @np: Device node pointer associated with the PM domain provider.
1816  * @data: Pointer to the data associated with the PM domain provider.
1817  */
1818 int of_genpd_add_provider_onecell(struct device_node *np,
1819                                   struct genpd_onecell_data *data)
1820 {
1821         unsigned int i;
1822         int ret = -EINVAL;
1823
1824         if (!np || !data)
1825                 return -EINVAL;
1826
1827         mutex_lock(&gpd_list_lock);
1828
1829         if (!data->xlate)
1830                 data->xlate = genpd_xlate_onecell;
1831
1832         for (i = 0; i < data->num_domains; i++) {
1833                 if (!data->domains[i])
1834                         continue;
1835                 if (!pm_genpd_present(data->domains[i]))
1836                         goto error;
1837
1838                 data->domains[i]->provider = &np->fwnode;
1839                 data->domains[i]->has_provider = true;
1840         }
1841
1842         ret = genpd_add_provider(np, data->xlate, data);
1843         if (ret < 0)
1844                 goto error;
1845
1846         mutex_unlock(&gpd_list_lock);
1847
1848         return 0;
1849
1850 error:
1851         while (i--) {
1852                 if (!data->domains[i])
1853                         continue;
1854                 data->domains[i]->provider = NULL;
1855                 data->domains[i]->has_provider = false;
1856         }
1857
1858         mutex_unlock(&gpd_list_lock);
1859
1860         return ret;
1861 }
1862 EXPORT_SYMBOL_GPL(of_genpd_add_provider_onecell);
1863
1864 /**
1865  * of_genpd_del_provider() - Remove a previously registered PM domain provider
1866  * @np: Device node pointer associated with the PM domain provider
1867  */
1868 void of_genpd_del_provider(struct device_node *np)
1869 {
1870         struct of_genpd_provider *cp, *tmp;
1871         struct generic_pm_domain *gpd;
1872
1873         mutex_lock(&gpd_list_lock);
1874         mutex_lock(&of_genpd_mutex);
1875         list_for_each_entry_safe(cp, tmp, &of_genpd_providers, link) {
1876                 if (cp->node == np) {
1877                         /*
1878                          * For each PM domain associated with the
1879                          * provider, set the 'has_provider' to false
1880                          * so that the PM domain can be safely removed.
1881                          */
1882                         list_for_each_entry(gpd, &gpd_list, gpd_list_node)
1883                                 if (gpd->provider == &np->fwnode)
1884                                         gpd->has_provider = false;
1885
1886                         list_del(&cp->link);
1887                         of_node_put(cp->node);
1888                         kfree(cp);
1889                         break;
1890                 }
1891         }
1892         mutex_unlock(&of_genpd_mutex);
1893         mutex_unlock(&gpd_list_lock);
1894 }
1895 EXPORT_SYMBOL_GPL(of_genpd_del_provider);
1896
1897 /**
1898  * genpd_get_from_provider() - Look-up PM domain
1899  * @genpdspec: OF phandle args to use for look-up
1900  *
1901  * Looks for a PM domain provider under the node specified by @genpdspec and if
1902  * found, uses xlate function of the provider to map phandle args to a PM
1903  * domain.
1904  *
1905  * Returns a valid pointer to struct generic_pm_domain on success or ERR_PTR()
1906  * on failure.
1907  */
1908 static struct generic_pm_domain *genpd_get_from_provider(
1909                                         struct of_phandle_args *genpdspec)
1910 {
1911         struct generic_pm_domain *genpd = ERR_PTR(-ENOENT);
1912         struct of_genpd_provider *provider;
1913
1914         if (!genpdspec)
1915                 return ERR_PTR(-EINVAL);
1916
1917         mutex_lock(&of_genpd_mutex);
1918
1919         /* Check if we have such a provider in our array */
1920         list_for_each_entry(provider, &of_genpd_providers, link) {
1921                 if (provider->node == genpdspec->np)
1922                         genpd = provider->xlate(genpdspec, provider->data);
1923                 if (!IS_ERR(genpd))
1924                         break;
1925         }
1926
1927         mutex_unlock(&of_genpd_mutex);
1928
1929         return genpd;
1930 }
1931
1932 /**
1933  * of_genpd_add_device() - Add a device to an I/O PM domain
1934  * @genpdspec: OF phandle args to use for look-up PM domain
1935  * @dev: Device to be added.
1936  *
1937  * Looks-up an I/O PM domain based upon phandle args provided and adds
1938  * the device to the PM domain. Returns a negative error code on failure.
1939  */
1940 int of_genpd_add_device(struct of_phandle_args *genpdspec, struct device *dev)
1941 {
1942         struct generic_pm_domain *genpd;
1943         int ret;
1944
1945         mutex_lock(&gpd_list_lock);
1946
1947         genpd = genpd_get_from_provider(genpdspec);
1948         if (IS_ERR(genpd)) {
1949                 ret = PTR_ERR(genpd);
1950                 goto out;
1951         }
1952
1953         ret = genpd_add_device(genpd, dev, NULL);
1954
1955 out:
1956         mutex_unlock(&gpd_list_lock);
1957
1958         return ret;
1959 }
1960 EXPORT_SYMBOL_GPL(of_genpd_add_device);
1961
1962 /**
1963  * of_genpd_add_subdomain - Add a subdomain to an I/O PM domain.
1964  * @parent_spec: OF phandle args to use for parent PM domain look-up
1965  * @subdomain_spec: OF phandle args to use for subdomain look-up
1966  *
1967  * Looks-up a parent PM domain and subdomain based upon phandle args
1968  * provided and adds the subdomain to the parent PM domain. Returns a
1969  * negative error code on failure.
1970  */
1971 int of_genpd_add_subdomain(struct of_phandle_args *parent_spec,
1972                            struct of_phandle_args *subdomain_spec)
1973 {
1974         struct generic_pm_domain *parent, *subdomain;
1975         int ret;
1976
1977         mutex_lock(&gpd_list_lock);
1978
1979         parent = genpd_get_from_provider(parent_spec);
1980         if (IS_ERR(parent)) {
1981                 ret = PTR_ERR(parent);
1982                 goto out;
1983         }
1984
1985         subdomain = genpd_get_from_provider(subdomain_spec);
1986         if (IS_ERR(subdomain)) {
1987                 ret = PTR_ERR(subdomain);
1988                 goto out;
1989         }
1990
1991         ret = genpd_add_subdomain(parent, subdomain);
1992
1993 out:
1994         mutex_unlock(&gpd_list_lock);
1995
1996         return ret;
1997 }
1998 EXPORT_SYMBOL_GPL(of_genpd_add_subdomain);
1999
2000 /**
2001  * of_genpd_remove_last - Remove the last PM domain registered for a provider
2002  * @provider: Pointer to device structure associated with provider
2003  *
2004  * Find the last PM domain that was added by a particular provider and
2005  * remove this PM domain from the list of PM domains. The provider is
2006  * identified by the 'provider' device structure that is passed. The PM
2007  * domain will only be removed, if the provider associated with domain
2008  * has been removed.
2009  *
2010  * Returns a valid pointer to struct generic_pm_domain on success or
2011  * ERR_PTR() on failure.
2012  */
2013 struct generic_pm_domain *of_genpd_remove_last(struct device_node *np)
2014 {
2015         struct generic_pm_domain *gpd, *tmp, *genpd = ERR_PTR(-ENOENT);
2016         int ret;
2017
2018         if (IS_ERR_OR_NULL(np))
2019                 return ERR_PTR(-EINVAL);
2020
2021         mutex_lock(&gpd_list_lock);
2022         list_for_each_entry_safe(gpd, tmp, &gpd_list, gpd_list_node) {
2023                 if (gpd->provider == &np->fwnode) {
2024                         ret = genpd_remove(gpd);
2025                         genpd = ret ? ERR_PTR(ret) : gpd;
2026                         break;
2027                 }
2028         }
2029         mutex_unlock(&gpd_list_lock);
2030
2031         return genpd;
2032 }
2033 EXPORT_SYMBOL_GPL(of_genpd_remove_last);
2034
2035 /**
2036  * genpd_dev_pm_detach - Detach a device from its PM domain.
2037  * @dev: Device to detach.
2038  * @power_off: Currently not used
2039  *
2040  * Try to locate a corresponding generic PM domain, which the device was
2041  * attached to previously. If such is found, the device is detached from it.
2042  */
2043 static void genpd_dev_pm_detach(struct device *dev, bool power_off)
2044 {
2045         struct generic_pm_domain *pd;
2046         unsigned int i;
2047         int ret = 0;
2048
2049         pd = dev_to_genpd(dev);
2050         if (IS_ERR(pd))
2051                 return;
2052
2053         dev_dbg(dev, "removing from PM domain %s\n", pd->name);
2054
2055         for (i = 1; i < GENPD_RETRY_MAX_MS; i <<= 1) {
2056                 ret = genpd_remove_device(pd, dev);
2057                 if (ret != -EAGAIN)
2058                         break;
2059
2060                 mdelay(i);
2061                 cond_resched();
2062         }
2063
2064         if (ret < 0) {
2065                 dev_err(dev, "failed to remove from PM domain %s: %d",
2066                         pd->name, ret);
2067                 return;
2068         }
2069
2070         /* Check if PM domain can be powered off after removing this device. */
2071         genpd_queue_power_off_work(pd);
2072 }
2073
2074 static void genpd_dev_pm_sync(struct device *dev)
2075 {
2076         struct generic_pm_domain *pd;
2077
2078         pd = dev_to_genpd(dev);
2079         if (IS_ERR(pd))
2080                 return;
2081
2082         genpd_queue_power_off_work(pd);
2083 }
2084
2085 /**
2086  * genpd_dev_pm_attach - Attach a device to its PM domain using DT.
2087  * @dev: Device to attach.
2088  *
2089  * Parse device's OF node to find a PM domain specifier. If such is found,
2090  * attaches the device to retrieved pm_domain ops.
2091  *
2092  * Both generic and legacy Samsung-specific DT bindings are supported to keep
2093  * backwards compatibility with existing DTBs.
2094  *
2095  * Returns 0 on successfully attached PM domain or negative error code. Note
2096  * that if a power-domain exists for the device, but it cannot be found or
2097  * turned on, then return -EPROBE_DEFER to ensure that the device is not
2098  * probed and to re-try again later.
2099  */
2100 int genpd_dev_pm_attach(struct device *dev)
2101 {
2102         struct of_phandle_args pd_args;
2103         struct generic_pm_domain *pd;
2104         unsigned int i;
2105         int ret;
2106
2107         if (!dev->of_node)
2108                 return -ENODEV;
2109
2110         if (dev->pm_domain)
2111                 return -EEXIST;
2112
2113         ret = of_parse_phandle_with_args(dev->of_node, "power-domains",
2114                                         "#power-domain-cells", 0, &pd_args);
2115         if (ret < 0) {
2116                 if (ret != -ENOENT)
2117                         return ret;
2118
2119                 /*
2120                  * Try legacy Samsung-specific bindings
2121                  * (for backwards compatibility of DT ABI)
2122                  */
2123                 pd_args.args_count = 0;
2124                 pd_args.np = of_parse_phandle(dev->of_node,
2125                                                 "samsung,power-domain", 0);
2126                 if (!pd_args.np)
2127                         return -ENOENT;
2128         }
2129
2130         mutex_lock(&gpd_list_lock);
2131         pd = genpd_get_from_provider(&pd_args);
2132         of_node_put(pd_args.np);
2133         if (IS_ERR(pd)) {
2134                 mutex_unlock(&gpd_list_lock);
2135                 dev_dbg(dev, "%s() failed to find PM domain: %ld\n",
2136                         __func__, PTR_ERR(pd));
2137                 return -EPROBE_DEFER;
2138         }
2139
2140         dev_dbg(dev, "adding to PM domain %s\n", pd->name);
2141
2142         for (i = 1; i < GENPD_RETRY_MAX_MS; i <<= 1) {
2143                 ret = genpd_add_device(pd, dev, NULL);
2144                 if (ret != -EAGAIN)
2145                         break;
2146
2147                 mdelay(i);
2148                 cond_resched();
2149         }
2150         mutex_unlock(&gpd_list_lock);
2151
2152         if (ret < 0) {
2153                 if (ret != -EPROBE_DEFER)
2154                         dev_err(dev, "failed to add to PM domain %s: %d",
2155                                 pd->name, ret);
2156                 goto out;
2157         }
2158
2159         dev->pm_domain->detach = genpd_dev_pm_detach;
2160         dev->pm_domain->sync = genpd_dev_pm_sync;
2161
2162         genpd_lock(pd);
2163         ret = genpd_power_on(pd, 0);
2164         genpd_unlock(pd);
2165
2166         if (ret)
2167                 genpd_remove_device(pd, dev);
2168 out:
2169         return ret ? -EPROBE_DEFER : 0;
2170 }
2171 EXPORT_SYMBOL_GPL(genpd_dev_pm_attach);
2172
2173 static const struct of_device_id idle_state_match[] = {
2174         { .compatible = "domain-idle-state", },
2175         { }
2176 };
2177
2178 static int genpd_parse_state(struct genpd_power_state *genpd_state,
2179                                     struct device_node *state_node)
2180 {
2181         int err;
2182         u32 residency;
2183         u32 entry_latency, exit_latency;
2184
2185         err = of_property_read_u32(state_node, "entry-latency-us",
2186                                                 &entry_latency);
2187         if (err) {
2188                 pr_debug(" * %pOF missing entry-latency-us property\n",
2189                                                 state_node);
2190                 return -EINVAL;
2191         }
2192
2193         err = of_property_read_u32(state_node, "exit-latency-us",
2194                                                 &exit_latency);
2195         if (err) {
2196                 pr_debug(" * %pOF missing exit-latency-us property\n",
2197                                                 state_node);
2198                 return -EINVAL;
2199         }
2200
2201         err = of_property_read_u32(state_node, "min-residency-us", &residency);
2202         if (!err)
2203                 genpd_state->residency_ns = 1000 * residency;
2204
2205         genpd_state->power_on_latency_ns = 1000 * exit_latency;
2206         genpd_state->power_off_latency_ns = 1000 * entry_latency;
2207         genpd_state->fwnode = &state_node->fwnode;
2208
2209         return 0;
2210 }
2211
2212 static int genpd_iterate_idle_states(struct device_node *dn,
2213                                      struct genpd_power_state *states)
2214 {
2215         int ret;
2216         struct of_phandle_iterator it;
2217         struct device_node *np;
2218         int i = 0;
2219
2220         ret = of_count_phandle_with_args(dn, "domain-idle-states", NULL);
2221         if (ret <= 0)
2222                 return ret;
2223
2224         /* Loop over the phandles until all the requested entry is found */
2225         of_for_each_phandle(&it, ret, dn, "domain-idle-states", NULL, 0) {
2226                 np = it.node;
2227                 if (!of_match_node(idle_state_match, np))
2228                         continue;
2229                 if (states) {
2230                         ret = genpd_parse_state(&states[i], np);
2231                         if (ret) {
2232                                 pr_err("Parsing idle state node %pOF failed with err %d\n",
2233                                        np, ret);
2234                                 of_node_put(np);
2235                                 return ret;
2236                         }
2237                 }
2238                 i++;
2239         }
2240
2241         return i;
2242 }
2243
2244 /**
2245  * of_genpd_parse_idle_states: Return array of idle states for the genpd.
2246  *
2247  * @dn: The genpd device node
2248  * @states: The pointer to which the state array will be saved.
2249  * @n: The count of elements in the array returned from this function.
2250  *
2251  * Returns the device states parsed from the OF node. The memory for the states
2252  * is allocated by this function and is the responsibility of the caller to
2253  * free the memory after use. If no domain idle states is found it returns
2254  * -EINVAL and in case of errors, a negative error code.
2255  */
2256 int of_genpd_parse_idle_states(struct device_node *dn,
2257                         struct genpd_power_state **states, int *n)
2258 {
2259         struct genpd_power_state *st;
2260         int ret;
2261
2262         ret = genpd_iterate_idle_states(dn, NULL);
2263         if (ret <= 0)
2264                 return ret < 0 ? ret : -EINVAL;
2265
2266         st = kcalloc(ret, sizeof(*st), GFP_KERNEL);
2267         if (!st)
2268                 return -ENOMEM;
2269
2270         ret = genpd_iterate_idle_states(dn, st);
2271         if (ret <= 0) {
2272                 kfree(st);
2273                 return ret < 0 ? ret : -EINVAL;
2274         }
2275
2276         *states = st;
2277         *n = ret;
2278
2279         return 0;
2280 }
2281 EXPORT_SYMBOL_GPL(of_genpd_parse_idle_states);
2282
2283 #endif /* CONFIG_PM_GENERIC_DOMAINS_OF */
2284
2285
2286 /***        debugfs support        ***/
2287
2288 #ifdef CONFIG_DEBUG_FS
2289 #include <linux/pm.h>
2290 #include <linux/device.h>
2291 #include <linux/debugfs.h>
2292 #include <linux/seq_file.h>
2293 #include <linux/init.h>
2294 #include <linux/kobject.h>
2295 static struct dentry *pm_genpd_debugfs_dir;
2296
2297 /*
2298  * TODO: This function is a slightly modified version of rtpm_status_show
2299  * from sysfs.c, so generalize it.
2300  */
2301 static void rtpm_status_str(struct seq_file *s, struct device *dev)
2302 {
2303         static const char * const status_lookup[] = {
2304                 [RPM_ACTIVE] = "active",
2305                 [RPM_RESUMING] = "resuming",
2306                 [RPM_SUSPENDED] = "suspended",
2307                 [RPM_SUSPENDING] = "suspending"
2308         };
2309         const char *p = "";
2310
2311         if (dev->power.runtime_error)
2312                 p = "error";
2313         else if (dev->power.disable_depth)
2314                 p = "unsupported";
2315         else if (dev->power.runtime_status < ARRAY_SIZE(status_lookup))
2316                 p = status_lookup[dev->power.runtime_status];
2317         else
2318                 WARN_ON(1);
2319
2320         seq_puts(s, p);
2321 }
2322
2323 static int pm_genpd_summary_one(struct seq_file *s,
2324                                 struct generic_pm_domain *genpd)
2325 {
2326         static const char * const status_lookup[] = {
2327                 [GPD_STATE_ACTIVE] = "on",
2328                 [GPD_STATE_POWER_OFF] = "off"
2329         };
2330         struct pm_domain_data *pm_data;
2331         const char *kobj_path;
2332         struct gpd_link *link;
2333         char state[16];
2334         int ret;
2335
2336         ret = genpd_lock_interruptible(genpd);
2337         if (ret)
2338                 return -ERESTARTSYS;
2339
2340         if (WARN_ON(genpd->status >= ARRAY_SIZE(status_lookup)))
2341                 goto exit;
2342         if (!genpd_status_on(genpd))
2343                 snprintf(state, sizeof(state), "%s-%u",
2344                          status_lookup[genpd->status], genpd->state_idx);
2345         else
2346                 snprintf(state, sizeof(state), "%s",
2347                          status_lookup[genpd->status]);
2348         seq_printf(s, "%-30s  %-15s ", genpd->name, state);
2349
2350         /*
2351          * Modifications on the list require holding locks on both
2352          * master and slave, so we are safe.
2353          * Also genpd->name is immutable.
2354          */
2355         list_for_each_entry(link, &genpd->master_links, master_node) {
2356                 seq_printf(s, "%s", link->slave->name);
2357                 if (!list_is_last(&link->master_node, &genpd->master_links))
2358                         seq_puts(s, ", ");
2359         }
2360
2361         list_for_each_entry(pm_data, &genpd->dev_list, list_node) {
2362                 kobj_path = kobject_get_path(&pm_data->dev->kobj,
2363                                 genpd_is_irq_safe(genpd) ?
2364                                 GFP_ATOMIC : GFP_KERNEL);
2365                 if (kobj_path == NULL)
2366                         continue;
2367
2368                 seq_printf(s, "\n    %-50s  ", kobj_path);
2369                 rtpm_status_str(s, pm_data->dev);
2370                 kfree(kobj_path);
2371         }
2372
2373         seq_puts(s, "\n");
2374 exit:
2375         genpd_unlock(genpd);
2376
2377         return 0;
2378 }
2379
2380 static int genpd_summary_show(struct seq_file *s, void *data)
2381 {
2382         struct generic_pm_domain *genpd;
2383         int ret = 0;
2384
2385         seq_puts(s, "domain                          status          slaves\n");
2386         seq_puts(s, "    /device                                             runtime status\n");
2387         seq_puts(s, "----------------------------------------------------------------------\n");
2388
2389         ret = mutex_lock_interruptible(&gpd_list_lock);
2390         if (ret)
2391                 return -ERESTARTSYS;
2392
2393         list_for_each_entry(genpd, &gpd_list, gpd_list_node) {
2394                 ret = pm_genpd_summary_one(s, genpd);
2395                 if (ret)
2396                         break;
2397         }
2398         mutex_unlock(&gpd_list_lock);
2399
2400         return ret;
2401 }
2402
2403 static int genpd_status_show(struct seq_file *s, void *data)
2404 {
2405         static const char * const status_lookup[] = {
2406                 [GPD_STATE_ACTIVE] = "on",
2407                 [GPD_STATE_POWER_OFF] = "off"
2408         };
2409
2410         struct generic_pm_domain *genpd = s->private;
2411         int ret = 0;
2412
2413         ret = genpd_lock_interruptible(genpd);
2414         if (ret)
2415                 return -ERESTARTSYS;
2416
2417         if (WARN_ON_ONCE(genpd->status >= ARRAY_SIZE(status_lookup)))
2418                 goto exit;
2419
2420         if (genpd->status == GPD_STATE_POWER_OFF)
2421                 seq_printf(s, "%s-%u\n", status_lookup[genpd->status],
2422                         genpd->state_idx);
2423         else
2424                 seq_printf(s, "%s\n", status_lookup[genpd->status]);
2425 exit:
2426         genpd_unlock(genpd);
2427         return ret;
2428 }
2429
2430 static int genpd_sub_domains_show(struct seq_file *s, void *data)
2431 {
2432         struct generic_pm_domain *genpd = s->private;
2433         struct gpd_link *link;
2434         int ret = 0;
2435
2436         ret = genpd_lock_interruptible(genpd);
2437         if (ret)
2438                 return -ERESTARTSYS;
2439
2440         list_for_each_entry(link, &genpd->master_links, master_node)
2441                 seq_printf(s, "%s\n", link->slave->name);
2442
2443         genpd_unlock(genpd);
2444         return ret;
2445 }
2446
2447 static int genpd_idle_states_show(struct seq_file *s, void *data)
2448 {
2449         struct generic_pm_domain *genpd = s->private;
2450         unsigned int i;
2451         int ret = 0;
2452
2453         ret = genpd_lock_interruptible(genpd);
2454         if (ret)
2455                 return -ERESTARTSYS;
2456
2457         seq_puts(s, "State          Time Spent(ms)\n");
2458
2459         for (i = 0; i < genpd->state_count; i++) {
2460                 ktime_t delta = 0;
2461                 s64 msecs;
2462
2463                 if ((genpd->status == GPD_STATE_POWER_OFF) &&
2464                                 (genpd->state_idx == i))
2465                         delta = ktime_sub(ktime_get(), genpd->accounting_time);
2466
2467                 msecs = ktime_to_ms(
2468                         ktime_add(genpd->states[i].idle_time, delta));
2469                 seq_printf(s, "S%-13i %lld\n", i, msecs);
2470         }
2471
2472         genpd_unlock(genpd);
2473         return ret;
2474 }
2475
2476 static int genpd_active_time_show(struct seq_file *s, void *data)
2477 {
2478         struct generic_pm_domain *genpd = s->private;
2479         ktime_t delta = 0;
2480         int ret = 0;
2481
2482         ret = genpd_lock_interruptible(genpd);
2483         if (ret)
2484                 return -ERESTARTSYS;
2485
2486         if (genpd->status == GPD_STATE_ACTIVE)
2487                 delta = ktime_sub(ktime_get(), genpd->accounting_time);
2488
2489         seq_printf(s, "%lld ms\n", ktime_to_ms(
2490                                 ktime_add(genpd->on_time, delta)));
2491
2492         genpd_unlock(genpd);
2493         return ret;
2494 }
2495
2496 static int genpd_total_idle_time_show(struct seq_file *s, void *data)
2497 {
2498         struct generic_pm_domain *genpd = s->private;
2499         ktime_t delta = 0, total = 0;
2500         unsigned int i;
2501         int ret = 0;
2502
2503         ret = genpd_lock_interruptible(genpd);
2504         if (ret)
2505                 return -ERESTARTSYS;
2506
2507         for (i = 0; i < genpd->state_count; i++) {
2508
2509                 if ((genpd->status == GPD_STATE_POWER_OFF) &&
2510                                 (genpd->state_idx == i))
2511                         delta = ktime_sub(ktime_get(), genpd->accounting_time);
2512
2513                 total = ktime_add(total, genpd->states[i].idle_time);
2514         }
2515         total = ktime_add(total, delta);
2516
2517         seq_printf(s, "%lld ms\n", ktime_to_ms(total));
2518
2519         genpd_unlock(genpd);
2520         return ret;
2521 }
2522
2523
2524 static int genpd_devices_show(struct seq_file *s, void *data)
2525 {
2526         struct generic_pm_domain *genpd = s->private;
2527         struct pm_domain_data *pm_data;
2528         const char *kobj_path;
2529         int ret = 0;
2530
2531         ret = genpd_lock_interruptible(genpd);
2532         if (ret)
2533                 return -ERESTARTSYS;
2534
2535         list_for_each_entry(pm_data, &genpd->dev_list, list_node) {
2536                 kobj_path = kobject_get_path(&pm_data->dev->kobj,
2537                                 genpd_is_irq_safe(genpd) ?
2538                                 GFP_ATOMIC : GFP_KERNEL);
2539                 if (kobj_path == NULL)
2540                         continue;
2541
2542                 seq_printf(s, "%s\n", kobj_path);
2543                 kfree(kobj_path);
2544         }
2545
2546         genpd_unlock(genpd);
2547         return ret;
2548 }
2549
2550 #define define_genpd_open_function(name) \
2551 static int genpd_##name##_open(struct inode *inode, struct file *file) \
2552 { \
2553         return single_open(file, genpd_##name##_show, inode->i_private); \
2554 }
2555
2556 define_genpd_open_function(summary);
2557 define_genpd_open_function(status);
2558 define_genpd_open_function(sub_domains);
2559 define_genpd_open_function(idle_states);
2560 define_genpd_open_function(active_time);
2561 define_genpd_open_function(total_idle_time);
2562 define_genpd_open_function(devices);
2563
2564 #define define_genpd_debugfs_fops(name) \
2565 static const struct file_operations genpd_##name##_fops = { \
2566         .open = genpd_##name##_open, \
2567         .read = seq_read, \
2568         .llseek = seq_lseek, \
2569         .release = single_release, \
2570 }
2571
2572 define_genpd_debugfs_fops(summary);
2573 define_genpd_debugfs_fops(status);
2574 define_genpd_debugfs_fops(sub_domains);
2575 define_genpd_debugfs_fops(idle_states);
2576 define_genpd_debugfs_fops(active_time);
2577 define_genpd_debugfs_fops(total_idle_time);
2578 define_genpd_debugfs_fops(devices);
2579
2580 static int __init pm_genpd_debug_init(void)
2581 {
2582         struct dentry *d;
2583         struct generic_pm_domain *genpd;
2584
2585         pm_genpd_debugfs_dir = debugfs_create_dir("pm_genpd", NULL);
2586
2587         if (!pm_genpd_debugfs_dir)
2588                 return -ENOMEM;
2589
2590         d = debugfs_create_file("pm_genpd_summary", S_IRUGO,
2591                         pm_genpd_debugfs_dir, NULL, &genpd_summary_fops);
2592         if (!d)
2593                 return -ENOMEM;
2594
2595         list_for_each_entry(genpd, &gpd_list, gpd_list_node) {
2596                 d = debugfs_create_dir(genpd->name, pm_genpd_debugfs_dir);
2597                 if (!d)
2598                         return -ENOMEM;
2599
2600                 debugfs_create_file("current_state", 0444,
2601                                 d, genpd, &genpd_status_fops);
2602                 debugfs_create_file("sub_domains", 0444,
2603                                 d, genpd, &genpd_sub_domains_fops);
2604                 debugfs_create_file("idle_states", 0444,
2605                                 d, genpd, &genpd_idle_states_fops);
2606                 debugfs_create_file("active_time", 0444,
2607                                 d, genpd, &genpd_active_time_fops);
2608                 debugfs_create_file("total_idle_time", 0444,
2609                                 d, genpd, &genpd_total_idle_time_fops);
2610                 debugfs_create_file("devices", 0444,
2611                                 d, genpd, &genpd_devices_fops);
2612         }
2613
2614         return 0;
2615 }
2616 late_initcall(pm_genpd_debug_init);
2617
2618 static void __exit pm_genpd_debug_exit(void)
2619 {
2620         debugfs_remove_recursive(pm_genpd_debugfs_dir);
2621 }
2622 __exitcall(pm_genpd_debug_exit);
2623 #endif /* CONFIG_DEBUG_FS */