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