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