xref: /linux/drivers/pmdomain/core.c (revision 831f98ccaebdb71649519eea75094f16a633fc89)
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/idr.h>
11 #include <linux/kernel.h>
12 #include <linux/io.h>
13 #include <linux/iopoll.h>
14 #include <linux/platform_device.h>
15 #include <linux/pm_opp.h>
16 #include <linux/pm_runtime.h>
17 #include <linux/pm_domain.h>
18 #include <linux/pm_qos.h>
19 #include <linux/pm_clock.h>
20 #include <linux/slab.h>
21 #include <linux/err.h>
22 #include <linux/sched.h>
23 #include <linux/smp.h>
24 #include <linux/suspend.h>
25 #include <linux/export.h>
26 #include <linux/cpu.h>
27 #include <linux/debugfs.h>
28 
29 #include <trace/events/ipi.h>
30 #include "core.h"
31 
32 /* Provides a unique ID for each genpd device */
33 static DEFINE_IDA(genpd_ida);
34 
35 /* The bus for genpd_providers. */
36 static const struct bus_type genpd_provider_bus_type = {
37 	.name		= "genpd_provider",
38 };
39 
40 #define GENPD_RETRY_MAX_MS		250		/* Approximate */
41 #define GENPD_CPU_ON_POLL_PERIOD_US	100		/* 100us */
42 #define GENPD_CPU_ON_TIMEOUT_US		300000		/* 300ms */
43 
44 #define GENPD_DEV_CALLBACK(genpd, type, callback, dev)		\
45 ({								\
46 	type (*__routine)(struct device *__d); 			\
47 	type __ret = (type)0;					\
48 								\
49 	__routine = genpd->dev_ops.callback; 			\
50 	if (__routine) {					\
51 		__ret = __routine(dev); 			\
52 	}							\
53 	__ret;							\
54 })
55 
56 static LIST_HEAD(gpd_list);
57 static DEFINE_MUTEX(gpd_list_lock);
58 
59 struct genpd_lock_ops {
60 	void (*lock)(struct generic_pm_domain *genpd);
61 	void (*lock_nested)(struct generic_pm_domain *genpd, int depth);
62 	int (*lock_interruptible)(struct generic_pm_domain *genpd);
63 	void (*unlock)(struct generic_pm_domain *genpd);
64 };
65 
66 static void genpd_lock_mtx(struct generic_pm_domain *genpd)
67 {
68 	mutex_lock(&genpd->mlock);
69 }
70 
71 static void genpd_lock_nested_mtx(struct generic_pm_domain *genpd,
72 					int depth)
73 {
74 	mutex_lock_nested(&genpd->mlock, depth);
75 }
76 
77 static int genpd_lock_interruptible_mtx(struct generic_pm_domain *genpd)
78 {
79 	return mutex_lock_interruptible(&genpd->mlock);
80 }
81 
82 static void genpd_unlock_mtx(struct generic_pm_domain *genpd)
83 {
84 	return mutex_unlock(&genpd->mlock);
85 }
86 
87 static const struct genpd_lock_ops genpd_mtx_ops = {
88 	.lock = genpd_lock_mtx,
89 	.lock_nested = genpd_lock_nested_mtx,
90 	.lock_interruptible = genpd_lock_interruptible_mtx,
91 	.unlock = genpd_unlock_mtx,
92 };
93 
94 static void genpd_lock_spin(struct generic_pm_domain *genpd)
95 	__acquires(&genpd->slock)
96 {
97 	unsigned long flags;
98 
99 	spin_lock_irqsave(&genpd->slock, flags);
100 	genpd->lock_flags = flags;
101 }
102 
103 static void genpd_lock_nested_spin(struct generic_pm_domain *genpd,
104 					int depth)
105 	__acquires(&genpd->slock)
106 {
107 	unsigned long flags;
108 
109 	spin_lock_irqsave_nested(&genpd->slock, flags, depth);
110 	genpd->lock_flags = flags;
111 }
112 
113 static int genpd_lock_interruptible_spin(struct generic_pm_domain *genpd)
114 	__acquires(&genpd->slock)
115 {
116 	unsigned long flags;
117 
118 	spin_lock_irqsave(&genpd->slock, flags);
119 	genpd->lock_flags = flags;
120 	return 0;
121 }
122 
123 static void genpd_unlock_spin(struct generic_pm_domain *genpd)
124 	__releases(&genpd->slock)
125 {
126 	spin_unlock_irqrestore(&genpd->slock, genpd->lock_flags);
127 }
128 
129 static const struct genpd_lock_ops genpd_spin_ops = {
130 	.lock = genpd_lock_spin,
131 	.lock_nested = genpd_lock_nested_spin,
132 	.lock_interruptible = genpd_lock_interruptible_spin,
133 	.unlock = genpd_unlock_spin,
134 };
135 
136 static void genpd_lock_raw_spin(struct generic_pm_domain *genpd)
137 	__acquires(&genpd->raw_slock)
138 {
139 	unsigned long flags;
140 
141 	raw_spin_lock_irqsave(&genpd->raw_slock, flags);
142 	genpd->raw_lock_flags = flags;
143 }
144 
145 static void genpd_lock_nested_raw_spin(struct generic_pm_domain *genpd,
146 					int depth)
147 	__acquires(&genpd->raw_slock)
148 {
149 	unsigned long flags;
150 
151 	raw_spin_lock_irqsave_nested(&genpd->raw_slock, flags, depth);
152 	genpd->raw_lock_flags = flags;
153 }
154 
155 static int genpd_lock_interruptible_raw_spin(struct generic_pm_domain *genpd)
156 	__acquires(&genpd->raw_slock)
157 {
158 	unsigned long flags;
159 
160 	raw_spin_lock_irqsave(&genpd->raw_slock, flags);
161 	genpd->raw_lock_flags = flags;
162 	return 0;
163 }
164 
165 static void genpd_unlock_raw_spin(struct generic_pm_domain *genpd)
166 	__releases(&genpd->raw_slock)
167 {
168 	raw_spin_unlock_irqrestore(&genpd->raw_slock, genpd->raw_lock_flags);
169 }
170 
171 static const struct genpd_lock_ops genpd_raw_spin_ops = {
172 	.lock = genpd_lock_raw_spin,
173 	.lock_nested = genpd_lock_nested_raw_spin,
174 	.lock_interruptible = genpd_lock_interruptible_raw_spin,
175 	.unlock = genpd_unlock_raw_spin,
176 };
177 
178 #define genpd_lock(p)			p->lock_ops->lock(p)
179 #define genpd_lock_nested(p, d)		p->lock_ops->lock_nested(p, d)
180 #define genpd_lock_interruptible(p)	p->lock_ops->lock_interruptible(p)
181 #define genpd_unlock(p)			p->lock_ops->unlock(p)
182 
183 #define genpd_status_on_unlocked(genpd)	(genpd->status == GENPD_STATE_ON)
184 #define genpd_is_irq_safe(genpd)	(genpd->flags & GENPD_FLAG_IRQ_SAFE)
185 #define genpd_is_always_on(genpd)	(genpd->flags & GENPD_FLAG_ALWAYS_ON)
186 #define genpd_is_active_wakeup(genpd)	(genpd->flags & GENPD_FLAG_ACTIVE_WAKEUP)
187 #define genpd_is_cpu_domain(genpd)	(genpd->flags & GENPD_FLAG_CPU_DOMAIN)
188 #define genpd_is_rpm_always_on(genpd)	(genpd->flags & GENPD_FLAG_RPM_ALWAYS_ON)
189 #define genpd_is_opp_table_fw(genpd)	(genpd->flags & GENPD_FLAG_OPP_TABLE_FW)
190 #define genpd_is_dev_name_fw(genpd)	(genpd->flags & GENPD_FLAG_DEV_NAME_FW)
191 #define genpd_is_no_sync_state(genpd)	(genpd->flags & GENPD_FLAG_NO_SYNC_STATE)
192 #define genpd_is_no_stay_on(genpd)	(genpd->flags & GENPD_FLAG_NO_STAY_ON)
193 #define genpd_is_power_unknown(genpd)	(genpd->flags & GENPD_FLAG_POWER_UNKNOWN)
194 
195 static inline bool irq_safe_dev_in_sleep_domain(struct device *dev,
196 		const struct generic_pm_domain *genpd)
197 {
198 	bool ret;
199 
200 	ret = pm_runtime_is_irq_safe(dev) && !genpd_is_irq_safe(genpd);
201 
202 	/*
203 	 * Warn once if an IRQ safe device is attached to a domain, which
204 	 * callbacks are allowed to sleep. This indicates a suboptimal
205 	 * configuration for PM, but it doesn't matter for an always on domain.
206 	 */
207 	if (genpd_is_always_on(genpd) || genpd_is_rpm_always_on(genpd))
208 		return ret;
209 
210 	if (ret)
211 		dev_warn_once(dev, "PM domain %s will not be powered off\n",
212 			      dev_name(&genpd->dev));
213 
214 	return ret;
215 }
216 
217 static int genpd_runtime_suspend(struct device *dev);
218 
219 /*
220  * Get the generic PM domain for a particular struct device.
221  * This validates the struct device pointer, the PM domain pointer,
222  * and checks that the PM domain pointer is a real generic PM domain.
223  * Any failure results in NULL being returned.
224  */
225 static struct generic_pm_domain *dev_to_genpd_safe(struct device *dev)
226 {
227 	if (IS_ERR_OR_NULL(dev) || IS_ERR_OR_NULL(dev->pm_domain))
228 		return NULL;
229 
230 	/* A genpd's always have its ->runtime_suspend() callback assigned. */
231 	if (dev->pm_domain->ops.runtime_suspend == genpd_runtime_suspend)
232 		return pd_to_genpd(dev->pm_domain);
233 
234 	return NULL;
235 }
236 
237 /*
238  * This should only be used where we are certain that the pm_domain
239  * attached to the device is a genpd domain.
240  */
241 static struct generic_pm_domain *dev_to_genpd(struct device *dev)
242 {
243 	if (IS_ERR_OR_NULL(dev->pm_domain))
244 		return ERR_PTR(-EINVAL);
245 
246 	return pd_to_genpd(dev->pm_domain);
247 }
248 
249 struct device *dev_to_genpd_dev(struct device *dev)
250 {
251 	struct generic_pm_domain *genpd = dev_to_genpd(dev);
252 
253 	if (IS_ERR(genpd))
254 		return ERR_CAST(genpd);
255 
256 	return &genpd->dev;
257 }
258 
259 static int genpd_stop_dev(const struct generic_pm_domain *genpd,
260 			  struct device *dev)
261 {
262 	return GENPD_DEV_CALLBACK(genpd, int, stop, dev);
263 }
264 
265 static int genpd_start_dev(const struct generic_pm_domain *genpd,
266 			   struct device *dev)
267 {
268 	return GENPD_DEV_CALLBACK(genpd, int, start, dev);
269 }
270 
271 static bool genpd_sd_counter_dec(struct generic_pm_domain *genpd)
272 {
273 	bool ret = false;
274 
275 	if (!WARN_ON(atomic_read(&genpd->sd_count) == 0))
276 		ret = !!atomic_dec_and_test(&genpd->sd_count);
277 
278 	return ret;
279 }
280 
281 static void genpd_sd_counter_inc(struct generic_pm_domain *genpd)
282 {
283 	atomic_inc(&genpd->sd_count);
284 	smp_mb__after_atomic();
285 }
286 
287 /**
288  * genpd_for_each_child - Recursively iterate over all devices
289  *                        in a PM domain and its subdomains.
290  * @genpd: PM domain to iterate over.
291  * @fn: Callback function to invoke for each device.
292  * @data: Data to pass to the callback function.
293  *
294  * This function recursively walks through all devices in the given PM domain
295  * and all devices in its child PM domains (subdomains). For each device found,
296  * the callback function @fn is invoked with the device and @data as arguments.
297  *
298  * Note: this function is inteded for use by the core and governors,
299  * not for pmdomain providers.
300  *
301  * Returns: 0 on success, or the first non-zero value returned by @fn.
302  */
303 int genpd_for_each_child(struct generic_pm_domain *genpd,
304 			 int (*fn)(struct device *dev, void *data),
305 			 void *data)
306 {
307 	struct pm_domain_data *pdd;
308 	struct gpd_link *link;
309 	int ret;
310 
311 	/* First, iterate over all devices in this domain */
312 	list_for_each_entry(pdd, &genpd->dev_list, list_node) {
313 		ret = fn(pdd->dev, data);
314 		if (ret)
315 			return ret;
316 	}
317 
318 	/* Then, recursively iterate over all child domains (subdomains) */
319 	list_for_each_entry(link, &genpd->parent_links, parent_node) {
320 		struct generic_pm_domain *child_pd = link->child;
321 
322 		ret = genpd_for_each_child(child_pd, fn, data);
323 		if (ret)
324 			return ret;
325 	}
326 
327 	return 0;
328 }
329 
330 #ifdef CONFIG_DEBUG_FS
331 static struct dentry *genpd_debugfs_dir;
332 
333 static void genpd_debug_add(struct generic_pm_domain *genpd);
334 
335 static void genpd_debug_remove(struct generic_pm_domain *genpd)
336 {
337 	if (!genpd_debugfs_dir)
338 		return;
339 
340 	debugfs_lookup_and_remove(dev_name(&genpd->dev), genpd_debugfs_dir);
341 }
342 
343 static void genpd_update_accounting(struct generic_pm_domain *genpd)
344 {
345 	u64 delta, now;
346 
347 	now = ktime_get_mono_fast_ns();
348 	if (now <= genpd->accounting_time)
349 		return;
350 
351 	delta = now - genpd->accounting_time;
352 
353 	/*
354 	 * If genpd->status is active, it means we are just
355 	 * out of off and so update the idle time and vice
356 	 * versa.
357 	 */
358 	if (genpd->status == GENPD_STATE_ON)
359 		genpd->states[genpd->state_idx].idle_time += delta;
360 	else
361 		genpd->on_time += delta;
362 
363 	genpd->accounting_time = now;
364 }
365 
366 static void genpd_reflect_residency(struct generic_pm_domain *genpd)
367 {
368 	struct genpd_governor_data *gd = genpd->gd;
369 	struct genpd_power_state *state, *next_state;
370 	unsigned int state_idx;
371 	s64 sleep_ns, target_ns;
372 
373 	if (!gd || !gd->reflect_residency)
374 		return;
375 
376 	sleep_ns = ktime_to_ns(ktime_sub(ktime_get(), gd->last_enter));
377 	state_idx = genpd->state_idx;
378 	state = &genpd->states[state_idx];
379 	target_ns = state->power_off_latency_ns + state->residency_ns;
380 
381 	if (sleep_ns < target_ns) {
382 		state->above++;
383 	} else if (state_idx < (genpd->state_count -1)) {
384 		next_state = &genpd->states[state_idx + 1];
385 		target_ns = next_state->power_off_latency_ns +
386 			next_state->residency_ns;
387 
388 		if (sleep_ns >= target_ns)
389 			state->below++;
390 	}
391 
392 	gd->reflect_residency = false;
393 }
394 #else
395 static inline void genpd_debug_add(struct generic_pm_domain *genpd) {}
396 static inline void genpd_debug_remove(struct generic_pm_domain *genpd) {}
397 static inline void genpd_update_accounting(struct generic_pm_domain *genpd) {}
398 static inline void genpd_reflect_residency(struct generic_pm_domain *genpd) {}
399 #endif
400 
401 static int _genpd_reeval_performance_state(struct generic_pm_domain *genpd,
402 					   unsigned int state)
403 {
404 	struct generic_pm_domain_data *pd_data;
405 	struct pm_domain_data *pdd;
406 	struct gpd_link *link;
407 
408 	/* New requested state is same as Max requested state */
409 	if (state == genpd->performance_state)
410 		return state;
411 
412 	/* New requested state is higher than Max requested state */
413 	if (state > genpd->performance_state)
414 		return state;
415 
416 	/* Traverse all devices within the domain */
417 	list_for_each_entry(pdd, &genpd->dev_list, list_node) {
418 		pd_data = to_gpd_data(pdd);
419 
420 		if (pd_data->performance_state > state)
421 			state = pd_data->performance_state;
422 	}
423 
424 	/*
425 	 * Traverse all sub-domains within the domain. This can be
426 	 * done without any additional locking as the link->performance_state
427 	 * field is protected by the parent genpd->lock, which is already taken.
428 	 *
429 	 * Also note that link->performance_state (subdomain's performance state
430 	 * requirement to parent domain) is different from
431 	 * link->child->performance_state (current performance state requirement
432 	 * of the devices/sub-domains of the subdomain) and so can have a
433 	 * different value.
434 	 *
435 	 * Note that we also take vote from powered-off sub-domains into account
436 	 * as the same is done for devices right now.
437 	 */
438 	list_for_each_entry(link, &genpd->parent_links, parent_node) {
439 		if (link->performance_state > state)
440 			state = link->performance_state;
441 	}
442 
443 	return state;
444 }
445 
446 static int genpd_xlate_performance_state(struct generic_pm_domain *genpd,
447 					 struct generic_pm_domain *parent,
448 					 unsigned int pstate)
449 {
450 	if (!parent->set_performance_state)
451 		return pstate;
452 
453 	return dev_pm_opp_xlate_performance_state(genpd->opp_table,
454 						  parent->opp_table,
455 						  pstate);
456 }
457 
458 static int _genpd_set_performance_state(struct generic_pm_domain *genpd,
459 					unsigned int state, int depth);
460 
461 static void _genpd_rollback_parent_state(struct gpd_link *link, int depth)
462 {
463 	struct generic_pm_domain *parent = link->parent;
464 	int parent_state;
465 
466 	genpd_lock_nested(parent, depth + 1);
467 
468 	parent_state = link->prev_performance_state;
469 	link->performance_state = parent_state;
470 
471 	parent_state = _genpd_reeval_performance_state(parent, parent_state);
472 	if (_genpd_set_performance_state(parent, parent_state, depth + 1)) {
473 		pr_err("%s: Failed to roll back to %d performance state\n",
474 		       parent->name, parent_state);
475 	}
476 
477 	genpd_unlock(parent);
478 }
479 
480 static int _genpd_set_parent_state(struct generic_pm_domain *genpd,
481 				   struct gpd_link *link,
482 				   unsigned int state, int depth)
483 {
484 	struct generic_pm_domain *parent = link->parent;
485 	int parent_state, ret;
486 
487 	/* Find parent's performance state */
488 	ret = genpd_xlate_performance_state(genpd, parent, state);
489 	if (unlikely(ret < 0))
490 		return ret;
491 
492 	parent_state = ret;
493 
494 	genpd_lock_nested(parent, depth + 1);
495 
496 	link->prev_performance_state = link->performance_state;
497 	link->performance_state = parent_state;
498 
499 	parent_state = _genpd_reeval_performance_state(parent, parent_state);
500 	ret = _genpd_set_performance_state(parent, parent_state, depth + 1);
501 	if (ret)
502 		link->performance_state = link->prev_performance_state;
503 
504 	genpd_unlock(parent);
505 
506 	return ret;
507 }
508 
509 static int _genpd_set_performance_state(struct generic_pm_domain *genpd,
510 					unsigned int state, int depth)
511 {
512 	struct gpd_link *link = NULL;
513 	int ret;
514 
515 	if (state == genpd->performance_state)
516 		return 0;
517 
518 	/* When scaling up, propagate to parents first in normal order */
519 	if (state > genpd->performance_state) {
520 		list_for_each_entry(link, &genpd->child_links, child_node) {
521 			ret = _genpd_set_parent_state(genpd, link, state, depth);
522 			if (ret)
523 				goto rollback_parents_up;
524 		}
525 	}
526 
527 	if (genpd->set_performance_state) {
528 		ret = genpd->set_performance_state(genpd, state);
529 		if (ret) {
530 			if (link)
531 				goto rollback_parents_up;
532 			return ret;
533 		}
534 	}
535 
536 	/* When scaling down, propagate to parents last in reverse order */
537 	if (state < genpd->performance_state) {
538 		list_for_each_entry_reverse(link, &genpd->child_links, child_node) {
539 			ret = _genpd_set_parent_state(genpd, link, state, depth);
540 			if (ret)
541 				goto rollback_parents_down;
542 		}
543 	}
544 
545 	genpd->performance_state = state;
546 	return 0;
547 
548 rollback_parents_up:
549 	list_for_each_entry_continue_reverse(link, &genpd->child_links, child_node)
550 		_genpd_rollback_parent_state(link, depth);
551 	return ret;
552 rollback_parents_down:
553 	list_for_each_entry_continue(link, &genpd->child_links, child_node)
554 		_genpd_rollback_parent_state(link, depth);
555 	return ret;
556 }
557 
558 static int genpd_set_performance_state(struct device *dev, unsigned int state)
559 {
560 	struct generic_pm_domain *genpd = dev_to_genpd(dev);
561 	struct generic_pm_domain_data *gpd_data = dev_gpd_data(dev);
562 	unsigned int prev_state;
563 	int ret;
564 
565 	prev_state = gpd_data->performance_state;
566 	if (prev_state == state)
567 		return 0;
568 
569 	gpd_data->performance_state = state;
570 	state = _genpd_reeval_performance_state(genpd, state);
571 
572 	ret = _genpd_set_performance_state(genpd, state, 0);
573 	if (ret)
574 		gpd_data->performance_state = prev_state;
575 
576 	return ret;
577 }
578 
579 static int genpd_drop_performance_state(struct device *dev)
580 {
581 	unsigned int prev_state = dev_gpd_data(dev)->performance_state;
582 
583 	if (!genpd_set_performance_state(dev, 0))
584 		return prev_state;
585 
586 	return 0;
587 }
588 
589 static void genpd_restore_performance_state(struct device *dev,
590 					    unsigned int state)
591 {
592 	if (state)
593 		genpd_set_performance_state(dev, state);
594 }
595 
596 static int genpd_dev_pm_set_performance_state(struct device *dev,
597 					      unsigned int state)
598 {
599 	struct generic_pm_domain *genpd = dev_to_genpd(dev);
600 	int ret = 0;
601 
602 	genpd_lock(genpd);
603 	if (pm_runtime_suspended(dev)) {
604 		dev_gpd_data(dev)->rpm_pstate = state;
605 	} else {
606 		ret = genpd_set_performance_state(dev, state);
607 		if (!ret)
608 			dev_gpd_data(dev)->rpm_pstate = 0;
609 	}
610 	genpd_unlock(genpd);
611 
612 	return ret;
613 }
614 
615 /**
616  * dev_pm_genpd_set_performance_state- Set performance state of device's power
617  * domain.
618  *
619  * @dev: Device for which the performance-state needs to be set.
620  * @state: Target performance state of the device. This can be set as 0 when the
621  *	   device doesn't have any performance state constraints left (And so
622  *	   the device wouldn't participate anymore to find the target
623  *	   performance state of the genpd).
624  *
625  * It is assumed that the users guarantee that the genpd wouldn't be detached
626  * while this routine is getting called.
627  *
628  * Returns 0 on success and negative error values on failures.
629  */
630 int dev_pm_genpd_set_performance_state(struct device *dev, unsigned int state)
631 {
632 	struct generic_pm_domain *genpd;
633 
634 	genpd = dev_to_genpd_safe(dev);
635 	if (!genpd)
636 		return -ENODEV;
637 
638 	if (WARN_ON(!dev->power.subsys_data ||
639 		     !dev->power.subsys_data->domain_data))
640 		return -EINVAL;
641 
642 	return genpd_dev_pm_set_performance_state(dev, state);
643 }
644 EXPORT_SYMBOL_GPL(dev_pm_genpd_set_performance_state);
645 
646 /**
647  * dev_pm_genpd_set_next_wakeup - Notify PM framework of an impending wakeup.
648  *
649  * @dev: Device to handle
650  * @next: impending interrupt/wakeup for the device
651  *
652  *
653  * Allow devices to inform of the next wakeup. It's assumed that the users
654  * guarantee that the genpd wouldn't be detached while this routine is getting
655  * called. Additionally, it's also assumed that @dev isn't runtime suspended
656  * (RPM_SUSPENDED)."
657  * Although devices are expected to update the next_wakeup after the end of
658  * their usecase as well, it is possible the devices themselves may not know
659  * about that, so stale @next will be ignored when powering off the domain.
660  */
661 void dev_pm_genpd_set_next_wakeup(struct device *dev, ktime_t next)
662 {
663 	struct generic_pm_domain *genpd;
664 	struct gpd_timing_data *td;
665 
666 	genpd = dev_to_genpd_safe(dev);
667 	if (!genpd)
668 		return;
669 
670 	td = to_gpd_data(dev->power.subsys_data->domain_data)->td;
671 	if (td)
672 		td->next_wakeup = next;
673 }
674 EXPORT_SYMBOL_GPL(dev_pm_genpd_set_next_wakeup);
675 
676 /**
677  * dev_pm_genpd_get_next_hrtimer - Return the next_hrtimer for the genpd
678  * @dev: A device that is attached to the genpd.
679  *
680  * This routine should typically be called for a device, at the point of when a
681  * GENPD_NOTIFY_PRE_OFF notification has been sent for it.
682  *
683  * Returns the aggregated value of the genpd's next hrtimer or KTIME_MAX if no
684  * valid value have been set.
685  */
686 ktime_t dev_pm_genpd_get_next_hrtimer(struct device *dev)
687 {
688 	struct generic_pm_domain *genpd;
689 
690 	genpd = dev_to_genpd_safe(dev);
691 	if (!genpd)
692 		return KTIME_MAX;
693 
694 	if (genpd->gd)
695 		return genpd->gd->next_hrtimer;
696 
697 	return KTIME_MAX;
698 }
699 EXPORT_SYMBOL_GPL(dev_pm_genpd_get_next_hrtimer);
700 
701 /*
702  * dev_pm_genpd_synced_poweroff - Next power off should be synchronous
703  *
704  * @dev: A device that is attached to the genpd.
705  *
706  * Allows a consumer of the genpd to notify the provider that the next power off
707  * should be synchronous.
708  *
709  * It is assumed that the users guarantee that the genpd wouldn't be detached
710  * while this routine is getting called.
711  */
712 void dev_pm_genpd_synced_poweroff(struct device *dev)
713 {
714 	struct generic_pm_domain *genpd;
715 
716 	genpd = dev_to_genpd_safe(dev);
717 	if (!genpd)
718 		return;
719 
720 	genpd_lock(genpd);
721 	genpd->synced_poweroff = true;
722 	genpd_unlock(genpd);
723 }
724 EXPORT_SYMBOL_GPL(dev_pm_genpd_synced_poweroff);
725 
726 /**
727  * dev_pm_genpd_set_hwmode() - Set the HW mode for the device and its PM domain.
728  *
729  * @dev: Device for which the HW-mode should be changed.
730  * @enable: Value to set or unset the HW-mode.
731  *
732  * Some PM domains can rely on HW signals to control the power for a device. To
733  * allow a consumer driver to switch the behaviour for its device in runtime,
734  * which may be beneficial from a latency or energy point of view, this function
735  * may be called.
736  *
737  * It is assumed that the users guarantee that the genpd wouldn't be detached
738  * while this routine is getting called.
739  *
740  * Return: Returns 0 on success and negative error values on failures.
741  */
742 int dev_pm_genpd_set_hwmode(struct device *dev, bool enable)
743 {
744 	struct generic_pm_domain *genpd;
745 	int ret = 0;
746 
747 	genpd = dev_to_genpd_safe(dev);
748 	if (!genpd)
749 		return -ENODEV;
750 
751 	if (!genpd->set_hwmode_dev)
752 		return -EOPNOTSUPP;
753 
754 	genpd_lock(genpd);
755 
756 	if (dev_gpd_data(dev)->hw_mode == enable)
757 		goto out;
758 
759 	ret = genpd->set_hwmode_dev(genpd, dev, enable);
760 	if (!ret)
761 		dev_gpd_data(dev)->hw_mode = enable;
762 
763 out:
764 	genpd_unlock(genpd);
765 	return ret;
766 }
767 EXPORT_SYMBOL_GPL(dev_pm_genpd_set_hwmode);
768 
769 /**
770  * dev_pm_genpd_get_hwmode() - Get the HW mode setting for the device.
771  *
772  * @dev: Device for which the current HW-mode setting should be fetched.
773  *
774  * This helper function allows consumer drivers to fetch the current HW mode
775  * setting of its the device.
776  *
777  * It is assumed that the users guarantee that the genpd wouldn't be detached
778  * while this routine is getting called.
779  *
780  * Return: Returns the HW mode setting of device from SW cached hw_mode.
781  */
782 bool dev_pm_genpd_get_hwmode(struct device *dev)
783 {
784 	return dev_gpd_data(dev)->hw_mode;
785 }
786 EXPORT_SYMBOL_GPL(dev_pm_genpd_get_hwmode);
787 
788 /**
789  * dev_pm_genpd_rpm_always_on() - Control if the PM domain can be powered off.
790  *
791  * @dev: Device for which the PM domain may need to stay on for.
792  * @on: Value to set or unset for the condition.
793  *
794  * For some usecases a consumer driver requires its device to remain power-on
795  * from the PM domain perspective during runtime. This function allows the
796  * behaviour to be dynamically controlled for a device attached to a genpd.
797  *
798  * It is assumed that the users guarantee that the genpd wouldn't be detached
799  * while this routine is getting called.
800  *
801  * Return: Returns 0 on success and negative error values on failures.
802  */
803 int dev_pm_genpd_rpm_always_on(struct device *dev, bool on)
804 {
805 	struct generic_pm_domain *genpd;
806 
807 	genpd = dev_to_genpd_safe(dev);
808 	if (!genpd)
809 		return -ENODEV;
810 
811 	genpd_lock(genpd);
812 	dev_gpd_data(dev)->rpm_always_on = on;
813 	genpd_unlock(genpd);
814 
815 	return 0;
816 }
817 EXPORT_SYMBOL_GPL(dev_pm_genpd_rpm_always_on);
818 
819 /**
820  * dev_pm_genpd_is_on() - Get device's current power domain status
821  *
822  * @dev: Device to get the current power status
823  *
824  * This function checks whether the generic power domain associated with the
825  * given device is on or not by checking if genpd->status equals GENPD_STATE_ON.
826  *
827  * Note: this function returns the power status of the genpd at the time of the
828  * call. The power status may change after due to activity from other devices
829  * sharing the same genpd. Therefore, this information should not be relied for
830  * long-term decisions about the device power state.
831  *
832  * Return: 'true' if the device's power domain is on, 'false' otherwise.
833  */
834 bool dev_pm_genpd_is_on(struct device *dev)
835 {
836 	struct generic_pm_domain *genpd;
837 	bool is_on;
838 
839 	genpd = dev_to_genpd_safe(dev);
840 	if (!genpd)
841 		return false;
842 
843 	genpd_lock(genpd);
844 	is_on = genpd_status_on_unlocked(genpd);
845 	genpd_unlock(genpd);
846 
847 	return is_on;
848 }
849 EXPORT_SYMBOL_GPL(dev_pm_genpd_is_on);
850 
851 /**
852  * pm_genpd_inc_rejected() - Adjust the rejected/usage counts for an idle-state.
853  *
854  * @genpd: The PM domain the idle-state belongs to.
855  * @state_idx: The index of the idle-state that failed.
856  *
857  * In some special cases the ->power_off() callback is asynchronously powering
858  * off the PM domain, leading to that it may return zero to indicate success,
859  * even though the actual power-off could fail. To account for this correctly in
860  * the rejected/usage counts for the idle-state statistics, users can call this
861  * function to adjust the values.
862  *
863  * It is assumed that the users guarantee that the genpd doesn't get removed
864  * while this routine is getting called.
865  */
866 void pm_genpd_inc_rejected(struct generic_pm_domain *genpd,
867 			   unsigned int state_idx)
868 {
869 	genpd_lock(genpd);
870 	genpd->states[genpd->state_idx].rejected++;
871 	genpd->states[genpd->state_idx].usage--;
872 	genpd_unlock(genpd);
873 }
874 EXPORT_SYMBOL_GPL(pm_genpd_inc_rejected);
875 
876 static int _genpd_power_on(struct generic_pm_domain *genpd, bool timed)
877 {
878 	unsigned int state_idx = genpd->state_idx;
879 	ktime_t time_start;
880 	s64 elapsed_ns;
881 	int ret;
882 
883 	/* Notify consumers that we are about to power on. */
884 	ret = raw_notifier_call_chain_robust(&genpd->power_notifiers,
885 					     GENPD_NOTIFY_PRE_ON,
886 					     GENPD_NOTIFY_OFF, NULL);
887 	ret = notifier_to_errno(ret);
888 	if (ret)
889 		return ret;
890 
891 	if (!genpd->power_on)
892 		goto out;
893 
894 	timed = timed && genpd->gd && !genpd->states[state_idx].fwnode;
895 	if (!timed) {
896 		ret = genpd->power_on(genpd);
897 		if (ret)
898 			goto err;
899 
900 		goto out;
901 	}
902 
903 	time_start = ktime_get();
904 	ret = genpd->power_on(genpd);
905 	if (ret)
906 		goto err;
907 
908 	elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
909 	if (elapsed_ns <= genpd->states[state_idx].power_on_latency_ns)
910 		goto out;
911 
912 	genpd->states[state_idx].power_on_latency_ns = elapsed_ns;
913 	genpd->gd->max_off_time_changed = true;
914 	pr_debug("%s: Power-%s latency exceeded, new value %lld ns\n",
915 		 dev_name(&genpd->dev), "on", elapsed_ns);
916 
917 out:
918 	raw_notifier_call_chain(&genpd->power_notifiers, GENPD_NOTIFY_ON, NULL);
919 	genpd->synced_poweroff = false;
920 	return 0;
921 err:
922 	raw_notifier_call_chain(&genpd->power_notifiers, GENPD_NOTIFY_OFF,
923 				NULL);
924 	return ret;
925 }
926 
927 static int _genpd_power_off(struct generic_pm_domain *genpd, bool timed)
928 {
929 	unsigned int state_idx = genpd->state_idx;
930 	ktime_t time_start;
931 	s64 elapsed_ns;
932 	int ret;
933 
934 	/* Notify consumers that we are about to power off. */
935 	ret = raw_notifier_call_chain_robust(&genpd->power_notifiers,
936 					     GENPD_NOTIFY_PRE_OFF,
937 					     GENPD_NOTIFY_ON, NULL);
938 	ret = notifier_to_errno(ret);
939 	if (ret)
940 		return ret;
941 
942 	if (!genpd->power_off)
943 		goto out;
944 
945 	timed = timed && genpd->gd && !genpd->states[state_idx].fwnode;
946 	if (!timed) {
947 		ret = genpd->power_off(genpd);
948 		if (ret)
949 			goto busy;
950 
951 		goto out;
952 	}
953 
954 	time_start = ktime_get();
955 	ret = genpd->power_off(genpd);
956 	if (ret)
957 		goto busy;
958 
959 	elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
960 	if (elapsed_ns <= genpd->states[state_idx].power_off_latency_ns)
961 		goto out;
962 
963 	genpd->states[state_idx].power_off_latency_ns = elapsed_ns;
964 	genpd->gd->max_off_time_changed = true;
965 	pr_debug("%s: Power-%s latency exceeded, new value %lld ns\n",
966 		 dev_name(&genpd->dev), "off", elapsed_ns);
967 
968 out:
969 	raw_notifier_call_chain(&genpd->power_notifiers, GENPD_NOTIFY_OFF,
970 				NULL);
971 	return 0;
972 busy:
973 	raw_notifier_call_chain(&genpd->power_notifiers, GENPD_NOTIFY_ON, NULL);
974 	return ret;
975 }
976 
977 /**
978  * genpd_queue_power_off_work - Queue up the execution of genpd_power_off().
979  * @genpd: PM domain to power off.
980  *
981  * Queue up the execution of genpd_power_off() unless it's already been done
982  * before.
983  */
984 static void genpd_queue_power_off_work(struct generic_pm_domain *genpd)
985 {
986 	queue_work(pm_wq, &genpd->power_off_work);
987 }
988 
989 /**
990  * genpd_power_off - Remove power from a given PM domain.
991  * @genpd: PM domain to power down.
992  * @one_dev_on: If invoked from genpd's ->runtime_suspend|resume() callback, the
993  * RPM status of the related device is in an intermediate state, not yet turned
994  * into RPM_SUSPENDED. This means genpd_power_off() must allow one device to not
995  * be RPM_SUSPENDED, while it tries to power off the PM domain.
996  * @depth: nesting count for lockdep.
997  *
998  * If all of the @genpd's devices have been suspended and all of its subdomains
999  * have been powered down, remove power from @genpd.
1000  */
1001 static void genpd_power_off(struct generic_pm_domain *genpd, bool one_dev_on,
1002 			    unsigned int depth)
1003 {
1004 	struct pm_domain_data *pdd;
1005 	struct gpd_link *link;
1006 	unsigned int not_suspended = 0;
1007 
1008 	/*
1009 	 * Do not try to power off the domain in the following situations:
1010 	 * The domain is already in the "power off" state.
1011 	 * System suspend is in progress.
1012 	 * The domain is configured as always on.
1013 	 * The domain was on at boot and still need to stay on.
1014 	 * The domain has a subdomain being powered on.
1015 	 */
1016 	if (!genpd_status_on_unlocked(genpd) || genpd->prepared_count > 0 ||
1017 	    genpd_is_always_on(genpd) || genpd_is_rpm_always_on(genpd) ||
1018 	    genpd->stay_on || atomic_read(&genpd->sd_count) > 0)
1019 		return;
1020 
1021 	/*
1022 	 * The children must be in their deepest (powered-off) states to allow
1023 	 * the parent to be powered off. Note that, there's no need for
1024 	 * additional locking, as powering on a child, requires the parent's
1025 	 * lock to be acquired first.
1026 	 */
1027 	list_for_each_entry(link, &genpd->parent_links, parent_node) {
1028 		struct generic_pm_domain *child = link->child;
1029 		if (child->state_idx < child->state_count - 1)
1030 			return;
1031 	}
1032 
1033 	list_for_each_entry(pdd, &genpd->dev_list, list_node) {
1034 		/*
1035 		 * Do not allow PM domain to be powered off, when an IRQ safe
1036 		 * device is part of a non-IRQ safe domain.
1037 		 */
1038 		if (!pm_runtime_suspended(pdd->dev) ||
1039 			irq_safe_dev_in_sleep_domain(pdd->dev, genpd))
1040 			not_suspended++;
1041 
1042 		/* The device may need its PM domain to stay powered on. */
1043 		if (to_gpd_data(pdd)->rpm_always_on)
1044 			return;
1045 	}
1046 
1047 	if (not_suspended > 1 || (not_suspended == 1 && !one_dev_on))
1048 		return;
1049 
1050 	if (genpd->gov && genpd->gov->power_down_ok) {
1051 		if (!genpd->gov->power_down_ok(&genpd->domain))
1052 			return;
1053 	}
1054 
1055 	/* Default to shallowest state. */
1056 	if (!genpd->gov)
1057 		genpd->state_idx = 0;
1058 
1059 	/* Don't power off, if a child domain is waiting to power on. */
1060 	if (atomic_read(&genpd->sd_count) > 0)
1061 		return;
1062 
1063 	if (_genpd_power_off(genpd, true)) {
1064 		genpd->states[genpd->state_idx].rejected++;
1065 		return;
1066 	}
1067 
1068 	genpd->status = GENPD_STATE_OFF;
1069 	genpd_update_accounting(genpd);
1070 	genpd->states[genpd->state_idx].usage++;
1071 
1072 	list_for_each_entry(link, &genpd->child_links, child_node) {
1073 		genpd_sd_counter_dec(link->parent);
1074 		genpd_lock_nested(link->parent, depth + 1);
1075 		genpd_power_off(link->parent, false, depth + 1);
1076 		genpd_unlock(link->parent);
1077 	}
1078 }
1079 
1080 static bool genpd_status_on(struct generic_pm_domain *genpd)
1081 {
1082 	bool is_on;
1083 
1084 	genpd_lock(genpd);
1085 	is_on = genpd_status_on_unlocked(genpd);
1086 	genpd_unlock(genpd);
1087 
1088 	return is_on;
1089 }
1090 
1091 static int genpd_wakeup_cpu(struct generic_pm_domain *genpd)
1092 {
1093 	unsigned int cpu;
1094 	bool is_on;
1095 	int ret;
1096 
1097 	/* Find the first online CPU in the genpd's cpumask. */
1098 	cpu = cpumask_first_and(genpd->cpus, cpu_online_mask);
1099 	if (cpu >= nr_cpu_ids)
1100 		return -EAGAIN;
1101 
1102 	genpd_unlock(genpd);
1103 
1104 	/* Send a IPI to wakeup the selected CPU. */
1105 	smp_send_reschedule(cpu);
1106 
1107 	/* Poll to wait for it to complete the power on sequence. */
1108 	ret = readx_poll_timeout_atomic(genpd_status_on, genpd, is_on, is_on,
1109 					GENPD_CPU_ON_POLL_PERIOD_US,
1110 					GENPD_CPU_ON_TIMEOUT_US);
1111 
1112 	genpd_lock(genpd);
1113 
1114 	/* Re-check the status as we have released the lock in between. */
1115 	if (ret || !genpd_status_on_unlocked(genpd))
1116 		return -EAGAIN;
1117 
1118 	return 0;
1119 }
1120 
1121 static bool genpd_need_alive_cpu(struct generic_pm_domain *genpd,
1122 				 struct device *dev)
1123 {
1124 	if (!genpd_is_cpu_domain(genpd))
1125 		return false;
1126 
1127 	/* This is not for CPU devices as those are managed differently. */
1128 	if (to_gpd_data(dev->power.subsys_data->domain_data)->cpu >= 0)
1129 		return false;
1130 
1131 	/*
1132 	 * If the current CPU doesn't belong to the genpd's cpumask, we need to
1133 	 * wake up one of those idle CPUs to power on the CPU domain correctly.
1134 	 */
1135 	return !cpumask_test_cpu(smp_processor_id(), genpd->cpus);
1136 }
1137 
1138 /**
1139  * genpd_power_on - Restore power to a given PM domain and its parents.
1140  * @genpd: PM domain to power up.
1141  * @dev: The device that needs the PM domain to power on.
1142  * @depth: nesting count for lockdep.
1143  *
1144  * Restore power to @genpd and all of its parents so that it is possible to
1145  * resume a device belonging to it.
1146  */
1147 static int genpd_power_on(struct generic_pm_domain *genpd, struct device *dev,
1148 			  unsigned int depth)
1149 {
1150 	struct gpd_link *link;
1151 	int ret = 0;
1152 
1153 	if (genpd_status_on_unlocked(genpd))
1154 		return 0;
1155 
1156 	/* Special case for a device attached to a CPU domain. */
1157 	if (genpd_need_alive_cpu(genpd, dev))
1158 		return genpd_wakeup_cpu(genpd);
1159 
1160 	/* Reflect over the entered idle-states residency for debugfs. */
1161 	genpd_reflect_residency(genpd);
1162 
1163 	/*
1164 	 * The list is guaranteed not to change while the loop below is being
1165 	 * executed, unless one of the parents' .power_on() callbacks fiddles
1166 	 * with it.
1167 	 */
1168 	list_for_each_entry(link, &genpd->child_links, child_node) {
1169 		struct generic_pm_domain *parent = link->parent;
1170 
1171 		genpd_sd_counter_inc(parent);
1172 
1173 		genpd_lock_nested(parent, depth + 1);
1174 		ret = genpd_power_on(parent, dev, depth + 1);
1175 		genpd_unlock(parent);
1176 
1177 		if (ret) {
1178 			genpd_sd_counter_dec(parent);
1179 			goto err;
1180 		}
1181 	}
1182 
1183 	ret = _genpd_power_on(genpd, true);
1184 	if (ret)
1185 		goto err;
1186 
1187 	genpd->status = GENPD_STATE_ON;
1188 	genpd_update_accounting(genpd);
1189 
1190 	return 0;
1191 
1192  err:
1193 	list_for_each_entry_continue_reverse(link,
1194 					&genpd->child_links,
1195 					child_node) {
1196 		genpd_sd_counter_dec(link->parent);
1197 		genpd_lock_nested(link->parent, depth + 1);
1198 		genpd_power_off(link->parent, false, depth + 1);
1199 		genpd_unlock(link->parent);
1200 	}
1201 
1202 	return ret;
1203 }
1204 
1205 static int genpd_dev_pm_start(struct device *dev)
1206 {
1207 	struct generic_pm_domain *genpd = dev_to_genpd(dev);
1208 
1209 	return genpd_start_dev(genpd, dev);
1210 }
1211 
1212 static int genpd_dev_pm_qos_notifier(struct notifier_block *nb,
1213 				     unsigned long val, void *ptr)
1214 {
1215 	struct generic_pm_domain_data *gpd_data;
1216 	struct device *dev;
1217 
1218 	gpd_data = container_of(nb, struct generic_pm_domain_data, nb);
1219 	dev = gpd_data->base.dev;
1220 
1221 	for (;;) {
1222 		struct generic_pm_domain *genpd = ERR_PTR(-ENODATA);
1223 		struct pm_domain_data *pdd;
1224 		struct gpd_timing_data *td;
1225 
1226 		spin_lock_irq(&dev->power.lock);
1227 
1228 		pdd = dev->power.subsys_data ?
1229 				dev->power.subsys_data->domain_data : NULL;
1230 		if (pdd) {
1231 			td = to_gpd_data(pdd)->td;
1232 			if (td) {
1233 				td->constraint_changed = true;
1234 				genpd = dev_to_genpd(dev);
1235 			}
1236 		}
1237 
1238 		spin_unlock_irq(&dev->power.lock);
1239 
1240 		if (!IS_ERR(genpd)) {
1241 			genpd_lock(genpd);
1242 			genpd->gd->max_off_time_changed = true;
1243 			genpd_unlock(genpd);
1244 		}
1245 
1246 		dev = dev->parent;
1247 		if (!dev || dev->power.ignore_children)
1248 			break;
1249 	}
1250 
1251 	return NOTIFY_DONE;
1252 }
1253 
1254 /**
1255  * genpd_power_off_work_fn - Power off PM domain whose subdomain count is 0.
1256  * @work: Work structure used for scheduling the execution of this function.
1257  */
1258 static void genpd_power_off_work_fn(struct work_struct *work)
1259 {
1260 	struct generic_pm_domain *genpd;
1261 
1262 	genpd = container_of(work, struct generic_pm_domain, power_off_work);
1263 
1264 	genpd_lock(genpd);
1265 	genpd_power_off(genpd, false, 0);
1266 	genpd_unlock(genpd);
1267 }
1268 
1269 /**
1270  * __genpd_runtime_suspend - walk the hierarchy of ->runtime_suspend() callbacks
1271  * @dev: Device to handle.
1272  */
1273 static int __genpd_runtime_suspend(struct device *dev)
1274 {
1275 	int (*cb)(struct device *__dev);
1276 
1277 	if (dev->type && dev->type->pm)
1278 		cb = dev->type->pm->runtime_suspend;
1279 	else if (dev->class && dev->class->pm)
1280 		cb = dev->class->pm->runtime_suspend;
1281 	else if (dev->bus && dev->bus->pm)
1282 		cb = dev->bus->pm->runtime_suspend;
1283 	else
1284 		cb = NULL;
1285 
1286 	if (!cb && dev->driver && dev->driver->pm)
1287 		cb = dev->driver->pm->runtime_suspend;
1288 
1289 	return cb ? cb(dev) : 0;
1290 }
1291 
1292 /**
1293  * __genpd_runtime_resume - walk the hierarchy of ->runtime_resume() callbacks
1294  * @dev: Device to handle.
1295  */
1296 static int __genpd_runtime_resume(struct device *dev)
1297 {
1298 	int (*cb)(struct device *__dev);
1299 
1300 	if (dev->type && dev->type->pm)
1301 		cb = dev->type->pm->runtime_resume;
1302 	else if (dev->class && dev->class->pm)
1303 		cb = dev->class->pm->runtime_resume;
1304 	else if (dev->bus && dev->bus->pm)
1305 		cb = dev->bus->pm->runtime_resume;
1306 	else
1307 		cb = NULL;
1308 
1309 	if (!cb && dev->driver && dev->driver->pm)
1310 		cb = dev->driver->pm->runtime_resume;
1311 
1312 	return cb ? cb(dev) : 0;
1313 }
1314 
1315 /**
1316  * genpd_runtime_suspend - Suspend a device belonging to I/O PM domain.
1317  * @dev: Device to suspend.
1318  *
1319  * Carry out a runtime suspend of a device under the assumption that its
1320  * pm_domain field points to the domain member of an object of type
1321  * struct generic_pm_domain representing a PM domain consisting of I/O devices.
1322  */
1323 static int genpd_runtime_suspend(struct device *dev)
1324 {
1325 	struct generic_pm_domain *genpd;
1326 	bool (*suspend_ok)(struct device *__dev);
1327 	struct generic_pm_domain_data *gpd_data = dev_gpd_data(dev);
1328 	struct gpd_timing_data *td = gpd_data->td;
1329 	bool runtime_pm = pm_runtime_enabled(dev);
1330 	ktime_t time_start = 0;
1331 	s64 elapsed_ns;
1332 	int ret;
1333 
1334 	dev_dbg(dev, "%s()\n", __func__);
1335 
1336 	genpd = dev_to_genpd(dev);
1337 	if (IS_ERR(genpd))
1338 		return -EINVAL;
1339 
1340 	/*
1341 	 * A runtime PM centric subsystem/driver may re-use the runtime PM
1342 	 * callbacks for other purposes than runtime PM. In those scenarios
1343 	 * runtime PM is disabled. Under these circumstances, we shall skip
1344 	 * validating/measuring the PM QoS latency.
1345 	 */
1346 	suspend_ok = genpd->gov ? genpd->gov->suspend_ok : NULL;
1347 	if (runtime_pm && suspend_ok && !suspend_ok(dev))
1348 		return -EBUSY;
1349 
1350 	/* Measure suspend latency. */
1351 	if (td && runtime_pm)
1352 		time_start = ktime_get();
1353 
1354 	ret = __genpd_runtime_suspend(dev);
1355 	if (ret)
1356 		return ret;
1357 
1358 	ret = genpd_stop_dev(genpd, dev);
1359 	if (ret) {
1360 		__genpd_runtime_resume(dev);
1361 		return ret;
1362 	}
1363 
1364 	/* Update suspend latency value if the measured time exceeds it. */
1365 	if (td && runtime_pm) {
1366 		elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
1367 		if (elapsed_ns > td->suspend_latency_ns) {
1368 			td->suspend_latency_ns = elapsed_ns;
1369 			dev_dbg(dev, "suspend latency exceeded, %lld ns\n",
1370 				elapsed_ns);
1371 			genpd->gd->max_off_time_changed = true;
1372 			td->constraint_changed = true;
1373 		}
1374 	}
1375 
1376 	/*
1377 	 * If power.irq_safe is set, this routine may be run with
1378 	 * IRQs disabled, so suspend only if the PM domain also is irq_safe.
1379 	 */
1380 	if (irq_safe_dev_in_sleep_domain(dev, genpd))
1381 		return 0;
1382 
1383 	genpd_lock(genpd);
1384 	genpd_power_off(genpd, true, 0);
1385 	gpd_data->rpm_pstate = genpd_drop_performance_state(dev);
1386 	genpd_unlock(genpd);
1387 
1388 	return 0;
1389 }
1390 
1391 /**
1392  * genpd_runtime_resume - Resume a device belonging to I/O PM domain.
1393  * @dev: Device to resume.
1394  *
1395  * Carry out a runtime resume of a device under the assumption that its
1396  * pm_domain field points to the domain member of an object of type
1397  * struct generic_pm_domain representing a PM domain consisting of I/O devices.
1398  */
1399 static int genpd_runtime_resume(struct device *dev)
1400 {
1401 	struct generic_pm_domain *genpd;
1402 	struct generic_pm_domain_data *gpd_data = dev_gpd_data(dev);
1403 	struct gpd_timing_data *td = gpd_data->td;
1404 	bool timed = td && pm_runtime_enabled(dev);
1405 	ktime_t time_start = 0;
1406 	s64 elapsed_ns;
1407 	int ret;
1408 
1409 	dev_dbg(dev, "%s()\n", __func__);
1410 
1411 	genpd = dev_to_genpd(dev);
1412 	if (IS_ERR(genpd))
1413 		return -EINVAL;
1414 
1415 	/*
1416 	 * As we don't power off a non IRQ safe domain, which holds
1417 	 * an IRQ safe device, we don't need to restore power to it.
1418 	 */
1419 	if (irq_safe_dev_in_sleep_domain(dev, genpd))
1420 		goto out;
1421 
1422 	genpd_lock(genpd);
1423 	genpd_restore_performance_state(dev, gpd_data->rpm_pstate);
1424 	ret = genpd_power_on(genpd, dev, 0);
1425 	genpd_unlock(genpd);
1426 
1427 	if (ret)
1428 		return ret;
1429 
1430  out:
1431 	/* Measure resume latency. */
1432 	if (timed)
1433 		time_start = ktime_get();
1434 
1435 	ret = genpd_start_dev(genpd, dev);
1436 	if (ret)
1437 		goto err_poweroff;
1438 
1439 	ret = __genpd_runtime_resume(dev);
1440 	if (ret)
1441 		goto err_stop;
1442 
1443 	/* Update resume latency value if the measured time exceeds it. */
1444 	if (timed) {
1445 		elapsed_ns = ktime_to_ns(ktime_sub(ktime_get(), time_start));
1446 		if (elapsed_ns > td->resume_latency_ns) {
1447 			td->resume_latency_ns = elapsed_ns;
1448 			dev_dbg(dev, "resume latency exceeded, %lld ns\n",
1449 				elapsed_ns);
1450 			genpd->gd->max_off_time_changed = true;
1451 			td->constraint_changed = true;
1452 		}
1453 	}
1454 
1455 	return 0;
1456 
1457 err_stop:
1458 	genpd_stop_dev(genpd, dev);
1459 err_poweroff:
1460 	if (!pm_runtime_is_irq_safe(dev) || genpd_is_irq_safe(genpd)) {
1461 		genpd_lock(genpd);
1462 		genpd_power_off(genpd, true, 0);
1463 		gpd_data->rpm_pstate = genpd_drop_performance_state(dev);
1464 		genpd_unlock(genpd);
1465 	}
1466 
1467 	return ret;
1468 }
1469 
1470 static bool pd_ignore_unused;
1471 static int __init pd_ignore_unused_setup(char *__unused)
1472 {
1473 	pd_ignore_unused = true;
1474 	return 1;
1475 }
1476 __setup("pd_ignore_unused", pd_ignore_unused_setup);
1477 
1478 /**
1479  * genpd_power_off_unused - Power off all PM domains with no devices in use.
1480  */
1481 static int __init genpd_power_off_unused(void)
1482 {
1483 	struct generic_pm_domain *genpd;
1484 
1485 	if (pd_ignore_unused) {
1486 		pr_warn("genpd: Not disabling unused power domains\n");
1487 		return 0;
1488 	}
1489 
1490 	pr_info("genpd: Disabling unused power domains\n");
1491 	mutex_lock(&gpd_list_lock);
1492 
1493 	list_for_each_entry(genpd, &gpd_list, gpd_list_node) {
1494 		genpd_queue_power_off_work(genpd);
1495 	}
1496 
1497 	mutex_unlock(&gpd_list_lock);
1498 
1499 	return 0;
1500 }
1501 late_initcall_sync(genpd_power_off_unused);
1502 
1503 #ifdef CONFIG_PM_SLEEP
1504 
1505 /**
1506  * genpd_sync_power_off - Synchronously power off a PM domain and its parents.
1507  * @genpd: PM domain to power off, if possible.
1508  * @use_lock: use the lock.
1509  * @depth: nesting count for lockdep.
1510  *
1511  * Check if the given PM domain can be powered off (during system suspend or
1512  * hibernation) and do that if so.  Also, in that case propagate to its parents.
1513  *
1514  * This function is only called in "noirq" and "syscore" stages of system power
1515  * transitions. The "noirq" callbacks may be executed asynchronously, thus in
1516  * these cases the lock must be held.
1517  */
1518 static void genpd_sync_power_off(struct generic_pm_domain *genpd, bool use_lock,
1519 				 unsigned int depth)
1520 {
1521 	struct gpd_link *link;
1522 
1523 	if (!genpd_status_on_unlocked(genpd) || genpd_is_always_on(genpd))
1524 		return;
1525 
1526 	if (genpd->suspended_count != genpd->device_count
1527 	    || atomic_read(&genpd->sd_count) > 0)
1528 		return;
1529 
1530 	/* Check that the children are in their deepest (powered-off) state. */
1531 	list_for_each_entry(link, &genpd->parent_links, parent_node) {
1532 		struct generic_pm_domain *child = link->child;
1533 		if (child->state_idx < child->state_count - 1)
1534 			return;
1535 	}
1536 
1537 	if (genpd->gov && genpd->gov->system_power_down_ok) {
1538 		if (!genpd->gov->system_power_down_ok(&genpd->domain))
1539 			return;
1540 	} else {
1541 		/* Default to the deepest state. */
1542 		genpd->state_idx = genpd->state_count - 1;
1543 	}
1544 
1545 	if (_genpd_power_off(genpd, false)) {
1546 		genpd->states[genpd->state_idx].rejected++;
1547 		return;
1548 	} else {
1549 		genpd->states[genpd->state_idx].usage++;
1550 
1551 		/*
1552 		 * The ->system_power_down_ok() callback is currently used only
1553 		 * for s2idle. Use it to know when to update the usage counter.
1554 		 */
1555 		if (genpd->gov && genpd->gov->system_power_down_ok)
1556 			genpd->states[genpd->state_idx].usage_s2idle++;
1557 	}
1558 
1559 	genpd->status = GENPD_STATE_OFF;
1560 
1561 	list_for_each_entry(link, &genpd->child_links, child_node) {
1562 		genpd_sd_counter_dec(link->parent);
1563 
1564 		if (use_lock)
1565 			genpd_lock_nested(link->parent, depth + 1);
1566 
1567 		genpd_sync_power_off(link->parent, use_lock, depth + 1);
1568 
1569 		if (use_lock)
1570 			genpd_unlock(link->parent);
1571 	}
1572 }
1573 
1574 /**
1575  * genpd_sync_power_on - Synchronously power on a PM domain and its parents.
1576  * @genpd: PM domain to power on.
1577  * @use_lock: use the lock.
1578  * @depth: nesting count for lockdep.
1579  *
1580  * This function is only called in "noirq" and "syscore" stages of system power
1581  * transitions. The "noirq" callbacks may be executed asynchronously, thus in
1582  * these cases the lock must be held.
1583  */
1584 static void genpd_sync_power_on(struct generic_pm_domain *genpd, bool use_lock,
1585 				unsigned int depth)
1586 {
1587 	struct gpd_link *link;
1588 
1589 	if (genpd_status_on_unlocked(genpd))
1590 		return;
1591 
1592 	list_for_each_entry(link, &genpd->child_links, child_node) {
1593 		genpd_sd_counter_inc(link->parent);
1594 
1595 		if (use_lock)
1596 			genpd_lock_nested(link->parent, depth + 1);
1597 
1598 		genpd_sync_power_on(link->parent, use_lock, depth + 1);
1599 
1600 		if (use_lock)
1601 			genpd_unlock(link->parent);
1602 	}
1603 
1604 	_genpd_power_on(genpd, false);
1605 	genpd->status = GENPD_STATE_ON;
1606 }
1607 
1608 /**
1609  * genpd_prepare - Start power transition of a device in a PM domain.
1610  * @dev: Device to start the transition of.
1611  *
1612  * Start a power transition of a device (during a system-wide power transition)
1613  * under the assumption that its pm_domain field points to the domain member of
1614  * an object of type struct generic_pm_domain representing a PM domain
1615  * consisting of I/O devices.
1616  */
1617 static int genpd_prepare(struct device *dev)
1618 {
1619 	struct generic_pm_domain *genpd;
1620 	int ret;
1621 
1622 	dev_dbg(dev, "%s()\n", __func__);
1623 
1624 	genpd = dev_to_genpd(dev);
1625 	if (IS_ERR(genpd))
1626 		return -EINVAL;
1627 
1628 	genpd_lock(genpd);
1629 	genpd->prepared_count++;
1630 	genpd_unlock(genpd);
1631 
1632 	ret = pm_generic_prepare(dev);
1633 	if (ret < 0) {
1634 		genpd_lock(genpd);
1635 
1636 		genpd->prepared_count--;
1637 
1638 		genpd_unlock(genpd);
1639 	}
1640 
1641 	/* Never return 1, as genpd don't cope with the direct_complete path. */
1642 	return ret >= 0 ? 0 : ret;
1643 }
1644 
1645 /**
1646  * genpd_finish_suspend - Completion of suspend or hibernation of device in an
1647  *   I/O pm domain.
1648  * @dev: Device to suspend.
1649  * @suspend_noirq: Generic suspend_noirq callback.
1650  * @resume_noirq: Generic resume_noirq callback.
1651  *
1652  * Stop the device and remove power from the domain if all devices in it have
1653  * been stopped.
1654  */
1655 static int genpd_finish_suspend(struct device *dev,
1656 				int (*suspend_noirq)(struct device *dev),
1657 				int (*resume_noirq)(struct device *dev))
1658 {
1659 	struct generic_pm_domain *genpd;
1660 	int ret = 0;
1661 
1662 	genpd = dev_to_genpd(dev);
1663 	if (IS_ERR(genpd))
1664 		return -EINVAL;
1665 
1666 	ret = suspend_noirq(dev);
1667 	if (ret)
1668 		return ret;
1669 
1670 	if (device_awake_path(dev) && genpd_is_active_wakeup(genpd) &&
1671 	    !device_out_band_wakeup(dev))
1672 		return 0;
1673 
1674 	if (genpd->dev_ops.stop && genpd->dev_ops.start &&
1675 	    !pm_runtime_status_suspended(dev)) {
1676 		ret = genpd_stop_dev(genpd, dev);
1677 		if (ret) {
1678 			resume_noirq(dev);
1679 			return ret;
1680 		}
1681 	}
1682 
1683 	genpd_lock(genpd);
1684 	genpd->suspended_count++;
1685 	genpd_sync_power_off(genpd, true, 0);
1686 	genpd_unlock(genpd);
1687 
1688 	return 0;
1689 }
1690 
1691 /**
1692  * genpd_suspend_noirq - Completion of suspend of device in an I/O PM domain.
1693  * @dev: Device to suspend.
1694  *
1695  * Stop the device and remove power from the domain if all devices in it have
1696  * been stopped.
1697  */
1698 static int genpd_suspend_noirq(struct device *dev)
1699 {
1700 	dev_dbg(dev, "%s()\n", __func__);
1701 
1702 	return genpd_finish_suspend(dev,
1703 				    pm_generic_suspend_noirq,
1704 				    pm_generic_resume_noirq);
1705 }
1706 
1707 /**
1708  * genpd_finish_resume - Completion of resume of device in an I/O PM domain.
1709  * @dev: Device to resume.
1710  * @resume_noirq: Generic resume_noirq callback.
1711  *
1712  * Restore power to the device's PM domain, if necessary, and start the device.
1713  */
1714 static int genpd_finish_resume(struct device *dev,
1715 			       int (*resume_noirq)(struct device *dev))
1716 {
1717 	struct generic_pm_domain *genpd;
1718 	int ret;
1719 
1720 	dev_dbg(dev, "%s()\n", __func__);
1721 
1722 	genpd = dev_to_genpd(dev);
1723 	if (IS_ERR(genpd))
1724 		return -EINVAL;
1725 
1726 	if (device_awake_path(dev) && genpd_is_active_wakeup(genpd) &&
1727 	    !device_out_band_wakeup(dev))
1728 		return resume_noirq(dev);
1729 
1730 	genpd_lock(genpd);
1731 	genpd_sync_power_on(genpd, true, 0);
1732 	genpd->suspended_count--;
1733 	genpd_unlock(genpd);
1734 
1735 	if (genpd->dev_ops.stop && genpd->dev_ops.start &&
1736 	    !pm_runtime_status_suspended(dev)) {
1737 		ret = genpd_start_dev(genpd, dev);
1738 		if (ret)
1739 			return ret;
1740 	}
1741 
1742 	return pm_generic_resume_noirq(dev);
1743 }
1744 
1745 /**
1746  * genpd_resume_noirq - Start of resume of device in an I/O PM domain.
1747  * @dev: Device to resume.
1748  *
1749  * Restore power to the device's PM domain, if necessary, and start the device.
1750  */
1751 static int genpd_resume_noirq(struct device *dev)
1752 {
1753 	dev_dbg(dev, "%s()\n", __func__);
1754 
1755 	return genpd_finish_resume(dev, pm_generic_resume_noirq);
1756 }
1757 
1758 /**
1759  * genpd_freeze_noirq - Completion of freezing a device in an I/O PM domain.
1760  * @dev: Device to freeze.
1761  *
1762  * Carry out a late freeze of a device under the assumption that its
1763  * pm_domain field points to the domain member of an object of type
1764  * struct generic_pm_domain representing a power domain consisting of I/O
1765  * devices.
1766  */
1767 static int genpd_freeze_noirq(struct device *dev)
1768 {
1769 	dev_dbg(dev, "%s()\n", __func__);
1770 
1771 	return genpd_finish_suspend(dev,
1772 				    pm_generic_freeze_noirq,
1773 				    pm_generic_thaw_noirq);
1774 }
1775 
1776 /**
1777  * genpd_thaw_noirq - Early thaw of device in an I/O PM domain.
1778  * @dev: Device to thaw.
1779  *
1780  * Start the device, unless power has been removed from the domain already
1781  * before the system transition.
1782  */
1783 static int genpd_thaw_noirq(struct device *dev)
1784 {
1785 	dev_dbg(dev, "%s()\n", __func__);
1786 
1787 	return genpd_finish_resume(dev, pm_generic_thaw_noirq);
1788 }
1789 
1790 /**
1791  * genpd_poweroff_noirq - Completion of hibernation of device in an
1792  *   I/O PM domain.
1793  * @dev: Device to poweroff.
1794  *
1795  * Stop the device and remove power from the domain if all devices in it have
1796  * been stopped.
1797  */
1798 static int genpd_poweroff_noirq(struct device *dev)
1799 {
1800 	dev_dbg(dev, "%s()\n", __func__);
1801 
1802 	return genpd_finish_suspend(dev,
1803 				    pm_generic_poweroff_noirq,
1804 				    pm_generic_restore_noirq);
1805 }
1806 
1807 /**
1808  * genpd_restore_noirq - Start of restore of device in an I/O PM domain.
1809  * @dev: Device to resume.
1810  *
1811  * Make sure the domain will be in the same power state as before the
1812  * hibernation the system is resuming from and start the device if necessary.
1813  */
1814 static int genpd_restore_noirq(struct device *dev)
1815 {
1816 	dev_dbg(dev, "%s()\n", __func__);
1817 
1818 	return genpd_finish_resume(dev, pm_generic_restore_noirq);
1819 }
1820 
1821 /**
1822  * genpd_complete - Complete power transition of a device in a power domain.
1823  * @dev: Device to complete the transition of.
1824  *
1825  * Complete a power transition of a device (during a system-wide power
1826  * transition) under the assumption that its pm_domain field points to the
1827  * domain member of an object of type struct generic_pm_domain representing
1828  * a power domain consisting of I/O devices.
1829  */
1830 static void genpd_complete(struct device *dev)
1831 {
1832 	struct generic_pm_domain *genpd;
1833 
1834 	dev_dbg(dev, "%s()\n", __func__);
1835 
1836 	genpd = dev_to_genpd(dev);
1837 	if (IS_ERR(genpd))
1838 		return;
1839 
1840 	pm_generic_complete(dev);
1841 
1842 	genpd_lock(genpd);
1843 
1844 	genpd->prepared_count--;
1845 	if (!genpd->prepared_count)
1846 		genpd_queue_power_off_work(genpd);
1847 
1848 	genpd_unlock(genpd);
1849 }
1850 
1851 static void genpd_switch_state(struct device *dev, bool suspend)
1852 {
1853 	struct generic_pm_domain *genpd;
1854 	bool use_lock;
1855 
1856 	genpd = dev_to_genpd_safe(dev);
1857 	if (!genpd)
1858 		return;
1859 
1860 	use_lock = genpd_is_irq_safe(genpd);
1861 
1862 	if (use_lock)
1863 		genpd_lock(genpd);
1864 
1865 	if (suspend) {
1866 		genpd->suspended_count++;
1867 		genpd_sync_power_off(genpd, use_lock, 0);
1868 	} else {
1869 		genpd_sync_power_on(genpd, use_lock, 0);
1870 		genpd->suspended_count--;
1871 	}
1872 
1873 	if (use_lock)
1874 		genpd_unlock(genpd);
1875 }
1876 
1877 /**
1878  * dev_pm_genpd_suspend - Synchronously try to suspend the genpd for @dev
1879  * @dev: The device that is attached to the genpd, that can be suspended.
1880  *
1881  * This routine should typically be called for a device that needs to be
1882  * suspended during the syscore suspend phase. It may also be called during
1883  * suspend-to-idle to suspend a corresponding CPU device that is attached to a
1884  * genpd.
1885  */
1886 void dev_pm_genpd_suspend(struct device *dev)
1887 {
1888 	genpd_switch_state(dev, true);
1889 }
1890 EXPORT_SYMBOL_GPL(dev_pm_genpd_suspend);
1891 
1892 /**
1893  * dev_pm_genpd_resume - Synchronously try to resume the genpd for @dev
1894  * @dev: The device that is attached to the genpd, which needs to be resumed.
1895  *
1896  * This routine should typically be called for a device that needs to be resumed
1897  * during the syscore resume phase. It may also be called during suspend-to-idle
1898  * to resume a corresponding CPU device that is attached to a genpd.
1899  */
1900 void dev_pm_genpd_resume(struct device *dev)
1901 {
1902 	genpd_switch_state(dev, false);
1903 }
1904 EXPORT_SYMBOL_GPL(dev_pm_genpd_resume);
1905 
1906 #else /* !CONFIG_PM_SLEEP */
1907 
1908 #define genpd_prepare		NULL
1909 #define genpd_suspend_noirq	NULL
1910 #define genpd_resume_noirq	NULL
1911 #define genpd_freeze_noirq	NULL
1912 #define genpd_thaw_noirq	NULL
1913 #define genpd_poweroff_noirq	NULL
1914 #define genpd_restore_noirq	NULL
1915 #define genpd_complete		NULL
1916 
1917 #endif /* CONFIG_PM_SLEEP */
1918 
1919 static struct generic_pm_domain_data *genpd_alloc_dev_data(struct device *dev,
1920 							   bool has_governor)
1921 {
1922 	struct generic_pm_domain_data *gpd_data;
1923 	struct gpd_timing_data *td;
1924 	int ret;
1925 
1926 	ret = dev_pm_get_subsys_data(dev);
1927 	if (ret)
1928 		return ERR_PTR(ret);
1929 
1930 	gpd_data = kzalloc_obj(*gpd_data);
1931 	if (!gpd_data) {
1932 		ret = -ENOMEM;
1933 		goto err_put;
1934 	}
1935 
1936 	gpd_data->base.dev = dev;
1937 	gpd_data->nb.notifier_call = genpd_dev_pm_qos_notifier;
1938 
1939 	/* Allocate data used by a governor. */
1940 	if (has_governor) {
1941 		td = kzalloc_obj(*td);
1942 		if (!td) {
1943 			ret = -ENOMEM;
1944 			goto err_free;
1945 		}
1946 
1947 		td->constraint_changed = true;
1948 		td->effective_constraint_ns = PM_QOS_RESUME_LATENCY_NO_CONSTRAINT_NS;
1949 		td->next_wakeup = KTIME_MAX;
1950 		gpd_data->td = td;
1951 	}
1952 
1953 	spin_lock_irq(&dev->power.lock);
1954 
1955 	if (dev->power.subsys_data->domain_data)
1956 		ret = -EINVAL;
1957 	else
1958 		dev->power.subsys_data->domain_data = &gpd_data->base;
1959 
1960 	spin_unlock_irq(&dev->power.lock);
1961 
1962 	if (ret)
1963 		goto err_free;
1964 
1965 	return gpd_data;
1966 
1967  err_free:
1968 	kfree(gpd_data->td);
1969 	kfree(gpd_data);
1970  err_put:
1971 	dev_pm_put_subsys_data(dev);
1972 	return ERR_PTR(ret);
1973 }
1974 
1975 static void genpd_free_dev_data(struct device *dev,
1976 				struct generic_pm_domain_data *gpd_data)
1977 {
1978 	spin_lock_irq(&dev->power.lock);
1979 
1980 	dev->power.subsys_data->domain_data = NULL;
1981 
1982 	spin_unlock_irq(&dev->power.lock);
1983 
1984 	dev_pm_opp_clear_config(gpd_data->opp_token);
1985 	kfree(gpd_data->td);
1986 	kfree(gpd_data);
1987 	dev_pm_put_subsys_data(dev);
1988 }
1989 
1990 static void genpd_update_cpumask(struct generic_pm_domain *genpd,
1991 				 int cpu, bool set, unsigned int depth)
1992 {
1993 	struct gpd_link *link;
1994 
1995 	if (!genpd_is_cpu_domain(genpd))
1996 		return;
1997 
1998 	list_for_each_entry(link, &genpd->child_links, child_node) {
1999 		struct generic_pm_domain *parent = link->parent;
2000 
2001 		genpd_lock_nested(parent, depth + 1);
2002 		genpd_update_cpumask(parent, cpu, set, depth + 1);
2003 		genpd_unlock(parent);
2004 	}
2005 
2006 	if (set)
2007 		cpumask_set_cpu(cpu, genpd->cpus);
2008 	else
2009 		cpumask_clear_cpu(cpu, genpd->cpus);
2010 }
2011 
2012 static void genpd_set_cpumask(struct generic_pm_domain *genpd, int cpu)
2013 {
2014 	if (cpu >= 0)
2015 		genpd_update_cpumask(genpd, cpu, true, 0);
2016 }
2017 
2018 static void genpd_clear_cpumask(struct generic_pm_domain *genpd, int cpu)
2019 {
2020 	if (cpu >= 0)
2021 		genpd_update_cpumask(genpd, cpu, false, 0);
2022 }
2023 
2024 static int genpd_get_cpu(struct generic_pm_domain *genpd, struct device *dev)
2025 {
2026 	int cpu;
2027 
2028 	if (!genpd_is_cpu_domain(genpd))
2029 		return -1;
2030 
2031 	for_each_possible_cpu(cpu) {
2032 		if (get_cpu_device(cpu) == dev)
2033 			return cpu;
2034 	}
2035 
2036 	return -1;
2037 }
2038 
2039 static int genpd_add_device(struct generic_pm_domain *genpd, struct device *dev,
2040 			    struct device *base_dev)
2041 {
2042 	struct genpd_governor_data *gd = genpd->gd;
2043 	struct generic_pm_domain_data *gpd_data;
2044 	int ret;
2045 
2046 	dev_dbg(dev, "%s()\n", __func__);
2047 
2048 	gpd_data = genpd_alloc_dev_data(dev, gd);
2049 	if (IS_ERR(gpd_data))
2050 		return PTR_ERR(gpd_data);
2051 
2052 	gpd_data->cpu = genpd_get_cpu(genpd, base_dev);
2053 
2054 	gpd_data->hw_mode = genpd->get_hwmode_dev ? genpd->get_hwmode_dev(genpd, dev) : false;
2055 
2056 	ret = genpd->attach_dev ? genpd->attach_dev(genpd, dev) : 0;
2057 	if (ret)
2058 		goto out;
2059 
2060 	genpd_lock(genpd);
2061 
2062 	genpd_set_cpumask(genpd, gpd_data->cpu);
2063 
2064 	genpd->device_count++;
2065 	if (gd)
2066 		gd->max_off_time_changed = true;
2067 
2068 	list_add_tail(&gpd_data->base.list_node, &genpd->dev_list);
2069 
2070 	genpd_unlock(genpd);
2071 	dev_pm_domain_set(dev, &genpd->domain);
2072  out:
2073 	if (ret)
2074 		genpd_free_dev_data(dev, gpd_data);
2075 	else
2076 		dev_pm_qos_add_notifier(dev, &gpd_data->nb,
2077 					DEV_PM_QOS_RESUME_LATENCY);
2078 
2079 	return ret;
2080 }
2081 
2082 /**
2083  * pm_genpd_add_device - Add a device to an I/O PM domain.
2084  * @genpd: PM domain to add the device to.
2085  * @dev: Device to be added.
2086  */
2087 int pm_genpd_add_device(struct generic_pm_domain *genpd, struct device *dev)
2088 {
2089 	int ret;
2090 
2091 	if (!genpd || !dev)
2092 		return -EINVAL;
2093 
2094 	mutex_lock(&gpd_list_lock);
2095 	ret = genpd_add_device(genpd, dev, dev);
2096 	mutex_unlock(&gpd_list_lock);
2097 
2098 	return ret;
2099 }
2100 EXPORT_SYMBOL_GPL(pm_genpd_add_device);
2101 
2102 static int genpd_remove_device(struct generic_pm_domain *genpd,
2103 			       struct device *dev)
2104 {
2105 	struct generic_pm_domain_data *gpd_data;
2106 	struct pm_domain_data *pdd;
2107 	int ret = 0;
2108 
2109 	dev_dbg(dev, "%s()\n", __func__);
2110 
2111 	pdd = dev->power.subsys_data->domain_data;
2112 	gpd_data = to_gpd_data(pdd);
2113 	dev_pm_qos_remove_notifier(dev, &gpd_data->nb,
2114 				   DEV_PM_QOS_RESUME_LATENCY);
2115 
2116 	genpd_lock(genpd);
2117 
2118 	if (genpd->prepared_count > 0) {
2119 		ret = -EAGAIN;
2120 		goto out;
2121 	}
2122 
2123 	genpd->device_count--;
2124 	if (genpd->gd)
2125 		genpd->gd->max_off_time_changed = true;
2126 
2127 	genpd_clear_cpumask(genpd, gpd_data->cpu);
2128 
2129 	list_del_init(&pdd->list_node);
2130 
2131 	genpd_unlock(genpd);
2132 
2133 	dev_pm_domain_set(dev, NULL);
2134 
2135 	if (genpd->detach_dev)
2136 		genpd->detach_dev(genpd, dev);
2137 
2138 	genpd_free_dev_data(dev, gpd_data);
2139 
2140 	return 0;
2141 
2142  out:
2143 	genpd_unlock(genpd);
2144 	dev_pm_qos_add_notifier(dev, &gpd_data->nb, DEV_PM_QOS_RESUME_LATENCY);
2145 
2146 	return ret;
2147 }
2148 
2149 /**
2150  * pm_genpd_remove_device - Remove a device from an I/O PM domain.
2151  * @dev: Device to be removed.
2152  */
2153 int pm_genpd_remove_device(struct device *dev)
2154 {
2155 	struct generic_pm_domain *genpd = dev_to_genpd_safe(dev);
2156 
2157 	if (!genpd)
2158 		return -EINVAL;
2159 
2160 	return genpd_remove_device(genpd, dev);
2161 }
2162 EXPORT_SYMBOL_GPL(pm_genpd_remove_device);
2163 
2164 /**
2165  * dev_pm_genpd_add_notifier - Add a genpd power on/off notifier for @dev
2166  *
2167  * @dev: Device that should be associated with the notifier
2168  * @nb: The notifier block to register
2169  *
2170  * Users may call this function to add a genpd power on/off notifier for an
2171  * attached @dev. Only one notifier per device is allowed. The notifier is
2172  * sent when genpd is powering on/off the PM domain.
2173  *
2174  * It is assumed that the user guarantee that the genpd wouldn't be detached
2175  * while this routine is getting called.
2176  *
2177  * Returns 0 on success and negative error values on failures.
2178  */
2179 int dev_pm_genpd_add_notifier(struct device *dev, struct notifier_block *nb)
2180 {
2181 	struct generic_pm_domain *genpd;
2182 	struct generic_pm_domain_data *gpd_data;
2183 	int ret;
2184 
2185 	genpd = dev_to_genpd_safe(dev);
2186 	if (!genpd)
2187 		return -ENODEV;
2188 
2189 	if (WARN_ON(!dev->power.subsys_data ||
2190 		     !dev->power.subsys_data->domain_data))
2191 		return -EINVAL;
2192 
2193 	gpd_data = to_gpd_data(dev->power.subsys_data->domain_data);
2194 	if (gpd_data->power_nb)
2195 		return -EEXIST;
2196 
2197 	genpd_lock(genpd);
2198 	ret = raw_notifier_chain_register(&genpd->power_notifiers, nb);
2199 	genpd_unlock(genpd);
2200 
2201 	if (ret) {
2202 		dev_warn(dev, "failed to add notifier for PM domain %s\n",
2203 			 dev_name(&genpd->dev));
2204 		return ret;
2205 	}
2206 
2207 	gpd_data->power_nb = nb;
2208 	return 0;
2209 }
2210 EXPORT_SYMBOL_GPL(dev_pm_genpd_add_notifier);
2211 
2212 /**
2213  * dev_pm_genpd_remove_notifier - Remove a genpd power on/off notifier for @dev
2214  *
2215  * @dev: Device that is associated with the notifier
2216  *
2217  * Users may call this function to remove a genpd power on/off notifier for an
2218  * attached @dev.
2219  *
2220  * It is assumed that the user guarantee that the genpd wouldn't be detached
2221  * while this routine is getting called.
2222  *
2223  * Returns 0 on success and negative error values on failures.
2224  */
2225 int dev_pm_genpd_remove_notifier(struct device *dev)
2226 {
2227 	struct generic_pm_domain *genpd;
2228 	struct generic_pm_domain_data *gpd_data;
2229 	int ret;
2230 
2231 	genpd = dev_to_genpd_safe(dev);
2232 	if (!genpd)
2233 		return -ENODEV;
2234 
2235 	if (WARN_ON(!dev->power.subsys_data ||
2236 		     !dev->power.subsys_data->domain_data))
2237 		return -EINVAL;
2238 
2239 	gpd_data = to_gpd_data(dev->power.subsys_data->domain_data);
2240 	if (!gpd_data->power_nb)
2241 		return -ENODEV;
2242 
2243 	genpd_lock(genpd);
2244 	ret = raw_notifier_chain_unregister(&genpd->power_notifiers,
2245 					    gpd_data->power_nb);
2246 	genpd_unlock(genpd);
2247 
2248 	if (ret) {
2249 		dev_warn(dev, "failed to remove notifier for PM domain %s\n",
2250 			 dev_name(&genpd->dev));
2251 		return ret;
2252 	}
2253 
2254 	gpd_data->power_nb = NULL;
2255 	return 0;
2256 }
2257 EXPORT_SYMBOL_GPL(dev_pm_genpd_remove_notifier);
2258 
2259 static int genpd_add_subdomain(struct generic_pm_domain *genpd,
2260 			       struct generic_pm_domain *subdomain)
2261 {
2262 	struct gpd_link *link, *itr;
2263 	int ret = 0;
2264 
2265 	if (IS_ERR_OR_NULL(genpd) || IS_ERR_OR_NULL(subdomain)
2266 	    || genpd == subdomain)
2267 		return -EINVAL;
2268 
2269 	/*
2270 	 * If the domain can be powered on/off in an IRQ safe
2271 	 * context, ensure that the subdomain can also be
2272 	 * powered on/off in that context.
2273 	 */
2274 	if (!genpd_is_irq_safe(genpd) && genpd_is_irq_safe(subdomain)) {
2275 		WARN(1, "Parent %s of subdomain %s must be IRQ safe\n",
2276 		     dev_name(&genpd->dev), subdomain->name);
2277 		return -EINVAL;
2278 	}
2279 
2280 	link = kzalloc_obj(*link);
2281 	if (!link)
2282 		return -ENOMEM;
2283 
2284 	genpd_lock(subdomain);
2285 	genpd_lock_nested(genpd, SINGLE_DEPTH_NESTING);
2286 
2287 	if (!genpd_status_on_unlocked(genpd) &&
2288 	    genpd_status_on_unlocked(subdomain)) {
2289 		ret = -EINVAL;
2290 		goto out;
2291 	}
2292 
2293 	list_for_each_entry(itr, &genpd->parent_links, parent_node) {
2294 		if (itr->child == subdomain && itr->parent == genpd) {
2295 			ret = -EINVAL;
2296 			goto out;
2297 		}
2298 	}
2299 
2300 	link->parent = genpd;
2301 	list_add_tail(&link->parent_node, &genpd->parent_links);
2302 	link->child = subdomain;
2303 	list_add_tail(&link->child_node, &subdomain->child_links);
2304 	if (genpd_status_on_unlocked(subdomain))
2305 		genpd_sd_counter_inc(genpd);
2306 
2307  out:
2308 	genpd_unlock(genpd);
2309 	genpd_unlock(subdomain);
2310 	if (ret)
2311 		kfree(link);
2312 	return ret;
2313 }
2314 
2315 /**
2316  * pm_genpd_add_subdomain - Add a subdomain to an I/O PM domain.
2317  * @genpd: Leader PM domain to add the subdomain to.
2318  * @subdomain: Subdomain to be added.
2319  */
2320 int pm_genpd_add_subdomain(struct generic_pm_domain *genpd,
2321 			   struct generic_pm_domain *subdomain)
2322 {
2323 	int ret;
2324 
2325 	mutex_lock(&gpd_list_lock);
2326 	ret = genpd_add_subdomain(genpd, subdomain);
2327 	mutex_unlock(&gpd_list_lock);
2328 
2329 	return ret;
2330 }
2331 EXPORT_SYMBOL_GPL(pm_genpd_add_subdomain);
2332 
2333 /**
2334  * pm_genpd_remove_subdomain - Remove a subdomain from an I/O PM domain.
2335  * @genpd: Leader PM domain to remove the subdomain from.
2336  * @subdomain: Subdomain to be removed.
2337  */
2338 int pm_genpd_remove_subdomain(struct generic_pm_domain *genpd,
2339 			      struct generic_pm_domain *subdomain)
2340 {
2341 	struct gpd_link *l, *link;
2342 	int ret = -EINVAL;
2343 
2344 	if (IS_ERR_OR_NULL(genpd) || IS_ERR_OR_NULL(subdomain))
2345 		return -EINVAL;
2346 
2347 	genpd_lock(subdomain);
2348 	genpd_lock_nested(genpd, SINGLE_DEPTH_NESTING);
2349 
2350 	if (!list_empty(&subdomain->parent_links) || subdomain->device_count) {
2351 		pr_warn("%s: unable to remove subdomain %s\n",
2352 			dev_name(&genpd->dev), subdomain->name);
2353 		ret = -EBUSY;
2354 		goto out;
2355 	}
2356 
2357 	list_for_each_entry_safe(link, l, &genpd->parent_links, parent_node) {
2358 		if (link->child != subdomain)
2359 			continue;
2360 
2361 		list_del(&link->parent_node);
2362 		list_del(&link->child_node);
2363 		kfree(link);
2364 		if (genpd_status_on_unlocked(subdomain))
2365 			genpd_sd_counter_dec(genpd);
2366 
2367 		ret = 0;
2368 		break;
2369 	}
2370 
2371 out:
2372 	genpd_unlock(genpd);
2373 	genpd_unlock(subdomain);
2374 
2375 	return ret;
2376 }
2377 EXPORT_SYMBOL_GPL(pm_genpd_remove_subdomain);
2378 
2379 static void genpd_free_default_power_state(struct genpd_power_state *states,
2380 					   unsigned int state_count)
2381 {
2382 	kfree(states);
2383 }
2384 
2385 static int genpd_set_default_power_state(struct generic_pm_domain *genpd)
2386 {
2387 	struct genpd_power_state *state;
2388 
2389 	state = kzalloc_obj(*state);
2390 	if (!state)
2391 		return -ENOMEM;
2392 
2393 	genpd->states = state;
2394 	genpd->state_count = 1;
2395 	genpd->free_states = genpd_free_default_power_state;
2396 
2397 	return 0;
2398 }
2399 
2400 static void genpd_provider_release(struct device *dev)
2401 {
2402 	/* nothing to be done here */
2403 }
2404 
2405 static int genpd_alloc_data(struct generic_pm_domain *genpd)
2406 {
2407 	struct genpd_governor_data *gd = NULL;
2408 	int ret;
2409 
2410 	if (genpd_is_cpu_domain(genpd) &&
2411 	    !zalloc_cpumask_var(&genpd->cpus, GFP_KERNEL))
2412 		return -ENOMEM;
2413 
2414 	if (genpd->gov) {
2415 		gd = kzalloc_obj(*gd);
2416 		if (!gd) {
2417 			ret = -ENOMEM;
2418 			goto free;
2419 		}
2420 
2421 		gd->max_off_time_ns = -1;
2422 		gd->max_off_time_changed = true;
2423 		gd->next_wakeup = KTIME_MAX;
2424 		gd->next_hrtimer = KTIME_MAX;
2425 	}
2426 
2427 	/* Use only one "off" state if there were no states declared */
2428 	if (genpd->state_count == 0) {
2429 		ret = genpd_set_default_power_state(genpd);
2430 		if (ret)
2431 			goto free;
2432 	}
2433 
2434 	genpd->gd = gd;
2435 	device_initialize(&genpd->dev);
2436 	genpd->dev.release = genpd_provider_release;
2437 	genpd->dev.bus = &genpd_provider_bus_type;
2438 
2439 	if (!genpd_is_dev_name_fw(genpd)) {
2440 		dev_set_name(&genpd->dev, "%s", genpd->name);
2441 	} else {
2442 		ret = ida_alloc(&genpd_ida, GFP_KERNEL);
2443 		if (ret < 0)
2444 			goto put;
2445 
2446 		genpd->device_id = ret;
2447 		dev_set_name(&genpd->dev, "%s_%u", genpd->name, genpd->device_id);
2448 	}
2449 
2450 	return 0;
2451 put:
2452 	put_device(&genpd->dev);
2453 	if (genpd->free_states == genpd_free_default_power_state) {
2454 		kfree(genpd->states);
2455 		genpd->states = NULL;
2456 	}
2457 free:
2458 	if (genpd_is_cpu_domain(genpd))
2459 		free_cpumask_var(genpd->cpus);
2460 	kfree(gd);
2461 	return ret;
2462 }
2463 
2464 static void genpd_free_data(struct generic_pm_domain *genpd)
2465 {
2466 	/* Pending device link removals still reference genpd->dev. */
2467 	device_link_wait_removal();
2468 
2469 	put_device(&genpd->dev);
2470 	if (genpd->device_id != -ENXIO)
2471 		ida_free(&genpd_ida, genpd->device_id);
2472 	if (genpd_is_cpu_domain(genpd))
2473 		free_cpumask_var(genpd->cpus);
2474 	if (genpd->free_states) {
2475 		genpd->free_states(genpd->states, genpd->state_count);
2476 		genpd->states = NULL;
2477 		genpd->state_count = 0;
2478 	}
2479 	kfree(genpd->gd);
2480 }
2481 
2482 static void genpd_lock_init(struct generic_pm_domain *genpd)
2483 {
2484 	if (genpd_is_cpu_domain(genpd)) {
2485 		raw_spin_lock_init(&genpd->raw_slock);
2486 		genpd->lock_ops = &genpd_raw_spin_ops;
2487 	} else if (genpd_is_irq_safe(genpd)) {
2488 		spin_lock_init(&genpd->slock);
2489 		genpd->lock_ops = &genpd_spin_ops;
2490 	} else {
2491 		mutex_init(&genpd->mlock);
2492 		genpd->lock_ops = &genpd_mtx_ops;
2493 	}
2494 }
2495 
2496 #ifdef CONFIG_PM_GENERIC_DOMAINS_OF
2497 static void genpd_set_stay_on(struct generic_pm_domain *genpd, bool is_off)
2498 {
2499 	if (genpd_is_power_unknown(genpd))
2500 		genpd->stay_on = is_off;
2501 	else
2502 		genpd->stay_on = !genpd_is_no_stay_on(genpd) && !is_off;
2503 }
2504 #else
2505 static void genpd_set_stay_on(struct generic_pm_domain *genpd, bool is_off)
2506 {
2507 	genpd->stay_on = false;
2508 }
2509 #endif
2510 
2511 /**
2512  * pm_genpd_init - Initialize a generic I/O PM domain object.
2513  * @genpd: PM domain object to initialize.
2514  * @gov: PM domain governor to associate with the domain (may be NULL).
2515  * @is_off: Initial value of the domain's power_is_off field.
2516  *
2517  * Returns 0 on successful initialization, else a negative error code.
2518  */
2519 int pm_genpd_init(struct generic_pm_domain *genpd,
2520 		  struct dev_power_governor *gov, bool is_off)
2521 {
2522 	int ret;
2523 
2524 	if (IS_ERR_OR_NULL(genpd))
2525 		return -EINVAL;
2526 
2527 	INIT_LIST_HEAD(&genpd->parent_links);
2528 	INIT_LIST_HEAD(&genpd->child_links);
2529 	INIT_LIST_HEAD(&genpd->dev_list);
2530 	RAW_INIT_NOTIFIER_HEAD(&genpd->power_notifiers);
2531 	genpd_lock_init(genpd);
2532 	genpd->gov = gov;
2533 	INIT_WORK(&genpd->power_off_work, genpd_power_off_work_fn);
2534 	atomic_set(&genpd->sd_count, 0);
2535 	genpd->status = is_off ? GENPD_STATE_OFF : GENPD_STATE_ON;
2536 	genpd_set_stay_on(genpd, is_off);
2537 	genpd->sync_state = GENPD_SYNC_STATE_OFF;
2538 	genpd->device_count = 0;
2539 	genpd->provider = NULL;
2540 	genpd->device_id = -ENXIO;
2541 	genpd->has_provider = false;
2542 	genpd->opp_table = NULL;
2543 	genpd->accounting_time = ktime_get_mono_fast_ns();
2544 	genpd->domain.ops.runtime_suspend = genpd_runtime_suspend;
2545 	genpd->domain.ops.runtime_resume = genpd_runtime_resume;
2546 	genpd->domain.ops.prepare = genpd_prepare;
2547 	genpd->domain.ops.suspend_noirq = genpd_suspend_noirq;
2548 	genpd->domain.ops.resume_noirq = genpd_resume_noirq;
2549 	genpd->domain.ops.freeze_noirq = genpd_freeze_noirq;
2550 	genpd->domain.ops.thaw_noirq = genpd_thaw_noirq;
2551 	genpd->domain.ops.poweroff_noirq = genpd_poweroff_noirq;
2552 	genpd->domain.ops.restore_noirq = genpd_restore_noirq;
2553 	genpd->domain.ops.complete = genpd_complete;
2554 	genpd->domain.start = genpd_dev_pm_start;
2555 	genpd->domain.set_performance_state = genpd_dev_pm_set_performance_state;
2556 
2557 	if (genpd->flags & GENPD_FLAG_PM_CLK) {
2558 		genpd->dev_ops.stop = pm_clk_suspend;
2559 		genpd->dev_ops.start = pm_clk_resume;
2560 	}
2561 
2562 	/* The always-on governor works better with the corresponding flag. */
2563 	if (gov == &pm_domain_always_on_gov)
2564 		genpd->flags |= GENPD_FLAG_RPM_ALWAYS_ON;
2565 
2566 	/* Always-on domains must be powered on at initialization. */
2567 	if ((genpd_is_always_on(genpd) || genpd_is_rpm_always_on(genpd)) &&
2568 			!genpd_status_on_unlocked(genpd)) {
2569 		pr_err("always-on PM domain %s is not on\n", genpd->name);
2570 		return -EINVAL;
2571 	}
2572 
2573 	/* Multiple states but no governor doesn't make sense. */
2574 	if (!gov && genpd->state_count > 1)
2575 		pr_warn("%s: no governor for states\n", genpd->name);
2576 
2577 	ret = genpd_alloc_data(genpd);
2578 	if (ret)
2579 		return ret;
2580 
2581 	mutex_lock(&gpd_list_lock);
2582 	list_add(&genpd->gpd_list_node, &gpd_list);
2583 	mutex_unlock(&gpd_list_lock);
2584 	genpd_debug_add(genpd);
2585 
2586 	return 0;
2587 }
2588 EXPORT_SYMBOL_GPL(pm_genpd_init);
2589 
2590 static int genpd_remove(struct generic_pm_domain *genpd)
2591 {
2592 	struct gpd_link *l, *link;
2593 
2594 	if (IS_ERR_OR_NULL(genpd))
2595 		return -EINVAL;
2596 
2597 	genpd_lock(genpd);
2598 
2599 	if (genpd->has_provider) {
2600 		genpd_unlock(genpd);
2601 		pr_err("Provider present, unable to remove %s\n", dev_name(&genpd->dev));
2602 		return -EBUSY;
2603 	}
2604 
2605 	if (!list_empty(&genpd->parent_links) || genpd->device_count) {
2606 		genpd_unlock(genpd);
2607 		pr_err("%s: unable to remove %s\n", __func__, dev_name(&genpd->dev));
2608 		return -EBUSY;
2609 	}
2610 
2611 	list_for_each_entry_safe(link, l, &genpd->child_links, child_node) {
2612 		list_del(&link->parent_node);
2613 		list_del(&link->child_node);
2614 		kfree(link);
2615 	}
2616 
2617 	list_del(&genpd->gpd_list_node);
2618 	genpd_unlock(genpd);
2619 	genpd_debug_remove(genpd);
2620 	cancel_work_sync(&genpd->power_off_work);
2621 	genpd_free_data(genpd);
2622 
2623 	pr_debug("%s: removed %s\n", __func__, dev_name(&genpd->dev));
2624 
2625 	return 0;
2626 }
2627 
2628 /**
2629  * pm_genpd_remove - Remove a generic I/O PM domain
2630  * @genpd: Pointer to PM domain that is to be removed.
2631  *
2632  * To remove the PM domain, this function:
2633  *  - Removes the PM domain as a subdomain to any parent domains,
2634  *    if it was added.
2635  *  - Removes the PM domain from the list of registered PM domains.
2636  *
2637  * The PM domain will only be removed, if the associated provider has
2638  * been removed, it is not a parent to any other PM domain and has no
2639  * devices associated with it.
2640  */
2641 int pm_genpd_remove(struct generic_pm_domain *genpd)
2642 {
2643 	int ret;
2644 
2645 	mutex_lock(&gpd_list_lock);
2646 	ret = genpd_remove(genpd);
2647 	mutex_unlock(&gpd_list_lock);
2648 
2649 	return ret;
2650 }
2651 EXPORT_SYMBOL_GPL(pm_genpd_remove);
2652 
2653 #ifdef CONFIG_PM_GENERIC_DOMAINS_OF
2654 
2655 /*
2656  * Device Tree based PM domain providers.
2657  *
2658  * The code below implements generic device tree based PM domain providers that
2659  * bind device tree nodes with generic PM domains registered in the system.
2660  *
2661  * Any driver that registers generic PM domains and needs to support binding of
2662  * devices to these domains is supposed to register a PM domain provider, which
2663  * maps a PM domain specifier retrieved from the device tree to a PM domain.
2664  *
2665  * Two simple mapping functions have been provided for convenience:
2666  *  - genpd_xlate_simple() for 1:1 device tree node to PM domain mapping.
2667  *  - genpd_xlate_onecell() for mapping of multiple PM domains per node by
2668  *    index.
2669  */
2670 
2671 /**
2672  * struct of_genpd_provider - PM domain provider registration structure
2673  * @link: Entry in global list of PM domain providers
2674  * @node: Pointer to device tree node of PM domain provider
2675  * @xlate: Provider-specific xlate callback mapping a set of specifier cells
2676  *         into a PM domain.
2677  * @data: context pointer to be passed into @xlate callback
2678  */
2679 struct of_genpd_provider {
2680 	struct list_head link;
2681 	struct device_node *node;
2682 	genpd_xlate_t xlate;
2683 	void *data;
2684 };
2685 
2686 /* List of registered PM domain providers. */
2687 static LIST_HEAD(of_genpd_providers);
2688 /* Mutex to protect the list above. */
2689 static DEFINE_MUTEX(of_genpd_mutex);
2690 
2691 /* The parent for genpd_provider devices. */
2692 static struct device *genpd_provider_bus;
2693 
2694 /* Used to prevent registering devices before the bus. */
2695 static bool genpd_bus_registered;
2696 
2697 /**
2698  * genpd_xlate_simple() - Xlate function for direct node-domain mapping
2699  * @genpdspec: OF phandle args to map into a PM domain
2700  * @data: xlate function private data - pointer to struct generic_pm_domain
2701  *
2702  * This is a generic xlate function that can be used to model PM domains that
2703  * have their own device tree nodes. The private data of xlate function needs
2704  * to be a valid pointer to struct generic_pm_domain.
2705  */
2706 static struct generic_pm_domain *genpd_xlate_simple(
2707 					const struct of_phandle_args *genpdspec,
2708 					void *data)
2709 {
2710 	return data;
2711 }
2712 
2713 /**
2714  * genpd_xlate_onecell() - Xlate function using a single index.
2715  * @genpdspec: OF phandle args to map into a PM domain
2716  * @data: xlate function private data - pointer to struct genpd_onecell_data
2717  *
2718  * This is a generic xlate function that can be used to model simple PM domain
2719  * controllers that have one device tree node and provide multiple PM domains.
2720  * A single cell is used as an index into an array of PM domains specified in
2721  * the genpd_onecell_data struct when registering the provider.
2722  */
2723 static struct generic_pm_domain *genpd_xlate_onecell(
2724 					const struct of_phandle_args *genpdspec,
2725 					void *data)
2726 {
2727 	struct genpd_onecell_data *genpd_data = data;
2728 	unsigned int idx = genpdspec->args[0];
2729 
2730 	if (genpdspec->args_count != 1)
2731 		return ERR_PTR(-EINVAL);
2732 
2733 	if (idx >= genpd_data->num_domains) {
2734 		pr_err("%s: invalid domain index %u\n", __func__, idx);
2735 		return ERR_PTR(-EINVAL);
2736 	}
2737 
2738 	if (!genpd_data->domains[idx])
2739 		return ERR_PTR(-ENOENT);
2740 
2741 	return genpd_data->domains[idx];
2742 }
2743 
2744 /**
2745  * genpd_add_provider() - Register a PM domain provider for a node
2746  * @np: Device node pointer associated with the PM domain provider.
2747  * @xlate: Callback for decoding PM domain from phandle arguments.
2748  * @data: Context pointer for @xlate callback.
2749  */
2750 static int genpd_add_provider(struct device_node *np, genpd_xlate_t xlate,
2751 			      void *data)
2752 {
2753 	struct of_genpd_provider *cp;
2754 
2755 	cp = kzalloc_obj(*cp);
2756 	if (!cp)
2757 		return -ENOMEM;
2758 
2759 	cp->node = of_node_get(np);
2760 	cp->data = data;
2761 	cp->xlate = xlate;
2762 	fwnode_dev_initialized(of_fwnode_handle(np), true);
2763 
2764 	mutex_lock(&of_genpd_mutex);
2765 	list_add(&cp->link, &of_genpd_providers);
2766 	mutex_unlock(&of_genpd_mutex);
2767 	pr_debug("Added domain provider from %pOF\n", np);
2768 
2769 	return 0;
2770 }
2771 
2772 static bool genpd_present(const struct generic_pm_domain *genpd)
2773 {
2774 	bool ret = false;
2775 	const struct generic_pm_domain *gpd;
2776 
2777 	mutex_lock(&gpd_list_lock);
2778 	list_for_each_entry(gpd, &gpd_list, gpd_list_node) {
2779 		if (gpd == genpd) {
2780 			ret = true;
2781 			break;
2782 		}
2783 	}
2784 	mutex_unlock(&gpd_list_lock);
2785 
2786 	return ret;
2787 }
2788 
2789 static void genpd_sync_state(struct device *dev)
2790 {
2791 	return of_genpd_sync_state(dev->of_node);
2792 }
2793 
2794 /**
2795  * of_genpd_add_provider_simple() - Register a simple PM domain provider
2796  * @np: Device node pointer associated with the PM domain provider.
2797  * @genpd: Pointer to PM domain associated with the PM domain provider.
2798  */
2799 int of_genpd_add_provider_simple(struct device_node *np,
2800 				 struct generic_pm_domain *genpd)
2801 {
2802 	struct fwnode_handle *fwnode;
2803 	struct device *dev;
2804 	int ret;
2805 
2806 	if (!np || !genpd)
2807 		return -EINVAL;
2808 
2809 	if (!genpd_bus_registered)
2810 		return -ENODEV;
2811 
2812 	if (!genpd_present(genpd))
2813 		return -EINVAL;
2814 
2815 	genpd->dev.parent = genpd_provider_bus;
2816 	genpd->dev.of_node = np;
2817 
2818 	fwnode = of_fwnode_handle(np);
2819 	dev = get_dev_from_fwnode(fwnode);
2820 	if (!dev && !genpd_is_no_sync_state(genpd)) {
2821 		genpd->sync_state = GENPD_SYNC_STATE_SIMPLE;
2822 		device_set_node(&genpd->dev, fwnode);
2823 	} else {
2824 		dev_set_drv_sync_state(dev, genpd_sync_state);
2825 	}
2826 
2827 	put_device(dev);
2828 
2829 	ret = device_add(&genpd->dev);
2830 	if (ret)
2831 		return ret;
2832 
2833 	/* Parse genpd OPP table */
2834 	if (!genpd_is_opp_table_fw(genpd) && genpd->set_performance_state) {
2835 		ret = dev_pm_opp_of_add_table(&genpd->dev);
2836 		if (ret) {
2837 			dev_err_probe(&genpd->dev, ret, "Failed to add OPP table\n");
2838 			goto err_del;
2839 		}
2840 
2841 		/*
2842 		 * Save table for faster processing while setting performance
2843 		 * state.
2844 		 */
2845 		genpd->opp_table = dev_pm_opp_get_opp_table(&genpd->dev);
2846 		WARN_ON(IS_ERR(genpd->opp_table));
2847 	}
2848 
2849 	ret = genpd_add_provider(np, genpd_xlate_simple, genpd);
2850 	if (ret)
2851 		goto err_opp;
2852 
2853 	genpd->provider = fwnode;
2854 	genpd->has_provider = true;
2855 
2856 	return 0;
2857 
2858 err_opp:
2859 	if (genpd->opp_table) {
2860 		dev_pm_opp_put_opp_table(genpd->opp_table);
2861 		dev_pm_opp_of_remove_table(&genpd->dev);
2862 	}
2863 err_del:
2864 	device_del(&genpd->dev);
2865 	return ret;
2866 }
2867 EXPORT_SYMBOL_GPL(of_genpd_add_provider_simple);
2868 
2869 /**
2870  * of_genpd_add_provider_onecell() - Register a onecell PM domain provider
2871  * @np: Device node pointer associated with the PM domain provider.
2872  * @data: Pointer to the data associated with the PM domain provider.
2873  */
2874 int of_genpd_add_provider_onecell(struct device_node *np,
2875 				  struct genpd_onecell_data *data)
2876 {
2877 	struct generic_pm_domain *genpd;
2878 	struct fwnode_handle *fwnode;
2879 	struct device *dev;
2880 	unsigned int i;
2881 	int ret = -EINVAL;
2882 	bool sync_state = false;
2883 
2884 	if (!np || !data)
2885 		return -EINVAL;
2886 
2887 	if (!genpd_bus_registered)
2888 		return -ENODEV;
2889 
2890 	if (!data->xlate)
2891 		data->xlate = genpd_xlate_onecell;
2892 
2893 	fwnode = of_fwnode_handle(np);
2894 	dev = get_dev_from_fwnode(fwnode);
2895 	if (!dev)
2896 		sync_state = true;
2897 	else
2898 		dev_set_drv_sync_state(dev, genpd_sync_state);
2899 
2900 	put_device(dev);
2901 
2902 	for (i = 0; i < data->num_domains; i++) {
2903 		genpd = data->domains[i];
2904 
2905 		if (!genpd)
2906 			continue;
2907 		if (!genpd_present(genpd))
2908 			goto error;
2909 
2910 		genpd->dev.parent = genpd_provider_bus;
2911 		genpd->dev.of_node = np;
2912 
2913 		if (sync_state && !genpd_is_no_sync_state(genpd)) {
2914 			genpd->sync_state = GENPD_SYNC_STATE_ONECELL;
2915 			device_set_node(&genpd->dev, fwnode);
2916 			sync_state = false;
2917 		}
2918 
2919 		ret = device_add(&genpd->dev);
2920 		if (ret)
2921 			goto error;
2922 
2923 		/* Parse genpd OPP table */
2924 		if (!genpd_is_opp_table_fw(genpd) && genpd->set_performance_state) {
2925 			ret = dev_pm_opp_of_add_table_indexed(&genpd->dev, i);
2926 			if (ret) {
2927 				dev_err_probe(&genpd->dev, ret,
2928 					      "Failed to add OPP table for index %d\n", i);
2929 				device_del(&genpd->dev);
2930 				goto error;
2931 			}
2932 
2933 			/*
2934 			 * Save table for faster processing while setting
2935 			 * performance state.
2936 			 */
2937 			genpd->opp_table = dev_pm_opp_get_opp_table(&genpd->dev);
2938 			WARN_ON(IS_ERR(genpd->opp_table));
2939 		}
2940 
2941 		genpd->provider = fwnode;
2942 		genpd->has_provider = true;
2943 	}
2944 
2945 	ret = genpd_add_provider(np, data->xlate, data);
2946 	if (ret < 0)
2947 		goto error;
2948 
2949 	return 0;
2950 
2951 error:
2952 	while (i--) {
2953 		genpd = data->domains[i];
2954 
2955 		if (!genpd)
2956 			continue;
2957 
2958 		genpd->provider = NULL;
2959 		genpd->has_provider = false;
2960 
2961 		if (genpd->opp_table) {
2962 			dev_pm_opp_put_opp_table(genpd->opp_table);
2963 			dev_pm_opp_of_remove_table(&genpd->dev);
2964 		}
2965 
2966 		device_del(&genpd->dev);
2967 	}
2968 
2969 	return ret;
2970 }
2971 EXPORT_SYMBOL_GPL(of_genpd_add_provider_onecell);
2972 
2973 /**
2974  * of_genpd_del_provider() - Remove a previously registered PM domain provider
2975  * @np: Device node pointer associated with the PM domain provider
2976  */
2977 void of_genpd_del_provider(struct device_node *np)
2978 {
2979 	struct of_genpd_provider *cp, *tmp;
2980 	struct generic_pm_domain *gpd;
2981 
2982 	mutex_lock(&gpd_list_lock);
2983 	mutex_lock(&of_genpd_mutex);
2984 	list_for_each_entry_safe(cp, tmp, &of_genpd_providers, link) {
2985 		if (cp->node == np) {
2986 			/*
2987 			 * For each PM domain associated with the
2988 			 * provider, set the 'has_provider' to false
2989 			 * so that the PM domain can be safely removed.
2990 			 */
2991 			list_for_each_entry(gpd, &gpd_list, gpd_list_node) {
2992 				if (gpd->provider == of_fwnode_handle(np)) {
2993 					gpd->has_provider = false;
2994 
2995 					if (gpd->opp_table) {
2996 						dev_pm_opp_put_opp_table(gpd->opp_table);
2997 						dev_pm_opp_of_remove_table(&gpd->dev);
2998 					}
2999 
3000 					device_del(&gpd->dev);
3001 				}
3002 			}
3003 
3004 			fwnode_dev_initialized(of_fwnode_handle(cp->node), false);
3005 			list_del(&cp->link);
3006 			of_node_put(cp->node);
3007 			kfree(cp);
3008 			break;
3009 		}
3010 	}
3011 	mutex_unlock(&of_genpd_mutex);
3012 	mutex_unlock(&gpd_list_lock);
3013 }
3014 EXPORT_SYMBOL_GPL(of_genpd_del_provider);
3015 
3016 /**
3017  * genpd_get_from_provider() - Look-up PM domain
3018  * @genpdspec: OF phandle args to use for look-up
3019  *
3020  * Looks for a PM domain provider under the node specified by @genpdspec and if
3021  * found, uses xlate function of the provider to map phandle args to a PM
3022  * domain.
3023  *
3024  * Returns a valid pointer to struct generic_pm_domain on success or ERR_PTR()
3025  * on failure.
3026  */
3027 static struct generic_pm_domain *genpd_get_from_provider(
3028 					const struct of_phandle_args *genpdspec)
3029 {
3030 	struct generic_pm_domain *genpd = ERR_PTR(-ENOENT);
3031 	struct of_genpd_provider *provider;
3032 
3033 	if (!genpdspec)
3034 		return ERR_PTR(-EINVAL);
3035 
3036 	mutex_lock(&of_genpd_mutex);
3037 
3038 	/* Check if we have such a provider in our array */
3039 	list_for_each_entry(provider, &of_genpd_providers, link) {
3040 		if (provider->node == genpdspec->np)
3041 			genpd = provider->xlate(genpdspec, provider->data);
3042 		if (!IS_ERR(genpd))
3043 			break;
3044 	}
3045 
3046 	mutex_unlock(&of_genpd_mutex);
3047 
3048 	return genpd;
3049 }
3050 
3051 /**
3052  * of_genpd_add_child_ids() - Parse power-domains-child-ids property
3053  * @np: Device node pointer associated with the PM domain provider.
3054  * @data: Pointer to the onecell data associated with the PM domain provider.
3055  *
3056  * Parse the power-domains and power-domains-child-ids properties to establish
3057  * parent-child relationships for PM domains. The power-domains property lists
3058  * parent domains, and power-domains-child-ids lists which child domain IDs
3059  * should be associated with each parent.
3060  *
3061  * Uses "all or nothing" semantics: either all relationships are established
3062  * successfully, or none are (any partially-added relationships are unwound
3063  * on error).
3064  *
3065  * Returns the number of parent-child relationships established on success,
3066  * 0 if the properties don't exist, or a negative error code on failure.
3067  */
3068 int of_genpd_add_child_ids(struct device_node *np,
3069 			   struct genpd_onecell_data *data)
3070 {
3071 	struct of_phandle_args parent_args;
3072 	struct generic_pm_domain *parent_genpd, *child_genpd;
3073 	struct generic_pm_domain **pairs; /* pairs[2*i]=parent, pairs[2*i+1]=child */
3074 	u32 child_id;
3075 	int i, ret, count, child_count, added = 0;
3076 
3077 	/* Check if both properties exist */
3078 	count = of_count_phandle_with_args(np, "power-domains", "#power-domain-cells");
3079 	if (count <= 0)
3080 		return 0;
3081 
3082 	child_count = of_property_count_u32_elems(np, "power-domains-child-ids");
3083 	if (child_count < 0)
3084 		return 0;
3085 	if (child_count != count)
3086 		return -EINVAL;
3087 
3088 	/* Allocate tracking array for error unwind (parent/child pairs) */
3089 	pairs = kmalloc_objs(*pairs, count * 2);
3090 	if (!pairs)
3091 		return -ENOMEM;
3092 
3093 	for (i = 0; i < count; i++) {
3094 		ret = of_property_read_u32_index(np, "power-domains-child-ids",
3095 						 i, &child_id);
3096 		if (ret)
3097 			goto err_unwind;
3098 
3099 		/* Validate child ID is within bounds */
3100 		if (child_id >= data->num_domains) {
3101 			pr_err("Child ID %u out of bounds (max %u) for %pOF\n",
3102 			       child_id, data->num_domains - 1, np);
3103 			ret = -EINVAL;
3104 			goto err_unwind;
3105 		}
3106 
3107 		/* Get the child domain */
3108 		child_genpd = data->domains[child_id];
3109 		if (!child_genpd) {
3110 			pr_err("Child domain %u is NULL for %pOF\n", child_id, np);
3111 			ret = -EINVAL;
3112 			goto err_unwind;
3113 		}
3114 
3115 		ret = of_parse_phandle_with_args(np, "power-domains",
3116 						 "#power-domain-cells", i,
3117 						 &parent_args);
3118 		if (ret)
3119 			goto err_unwind;
3120 
3121 		/* Get the parent domain */
3122 		parent_genpd = genpd_get_from_provider(&parent_args);
3123 		of_node_put(parent_args.np);
3124 		if (IS_ERR(parent_genpd)) {
3125 			pr_err("Failed to get parent domain for %pOF: %ld\n",
3126 			       np, PTR_ERR(parent_genpd));
3127 			ret = PTR_ERR(parent_genpd);
3128 			goto err_unwind;
3129 		}
3130 
3131 		/* Establish parent-child relationship */
3132 		ret = pm_genpd_add_subdomain(parent_genpd, child_genpd);
3133 		if (ret) {
3134 			pr_err("Failed to add child domain %u to parent in %pOF: %d\n",
3135 			       child_id, np, ret);
3136 			goto err_unwind;
3137 		}
3138 
3139 		/* Track for potential unwind */
3140 		pairs[2 * added] = parent_genpd;
3141 		pairs[2 * added + 1] = child_genpd;
3142 		added++;
3143 
3144 		pr_debug("Added child domain %u (%s) to parent %s for %pOF\n",
3145 			 child_id, child_genpd->name, parent_genpd->name, np);
3146 	}
3147 
3148 	kfree(pairs);
3149 	return count;
3150 
3151 err_unwind:
3152 	/* Reverse all previously established relationships */
3153 	while (added-- > 0)
3154 		pm_genpd_remove_subdomain(pairs[2 * added], pairs[2 * added + 1]);
3155 	kfree(pairs);
3156 	return ret;
3157 }
3158 EXPORT_SYMBOL_GPL(of_genpd_add_child_ids);
3159 
3160 /**
3161  * of_genpd_remove_child_ids() - Remove parent-child PM domain relationships
3162  * @np: Device node pointer associated with the PM domain provider.
3163  * @data: Pointer to the onecell data associated with the PM domain provider.
3164  *
3165  * Reverses the effect of of_genpd_add_child_ids() by parsing the same
3166  * power-domains and power-domains-child-ids properties and calling
3167  * pm_genpd_remove_subdomain() for each established relationship.
3168  *
3169  * Returns 0 on success, -ENOENT if properties don't exist, or negative error
3170  * code on failure.
3171  */
3172 int of_genpd_remove_child_ids(struct device_node *np,
3173 			   struct genpd_onecell_data *data)
3174 {
3175 	struct of_phandle_args parent_args;
3176 	struct generic_pm_domain *parent_genpd, *child_genpd;
3177 	u32 child_id;
3178 	int i, ret, count, child_count;
3179 
3180 	/* Check if both properties exist */
3181 	count = of_count_phandle_with_args(np, "power-domains", "#power-domain-cells");
3182 	if (count <= 0)
3183 		return -ENOENT;
3184 
3185 	child_count = of_property_count_u32_elems(np, "power-domains-child-ids");
3186 	if (child_count < 0)
3187 		return -ENOENT;
3188 	if (child_count != count)
3189 		return -EINVAL;
3190 
3191 	for (i = 0; i < count; i++) {
3192 		if (of_property_read_u32_index(np, "power-domains-child-ids",
3193 					       i, &child_id))
3194 			continue;
3195 
3196 		if (child_id >= data->num_domains || !data->domains[child_id])
3197 			continue;
3198 
3199 		ret = of_parse_phandle_with_args(np, "power-domains",
3200 						 "#power-domain-cells", i,
3201 						 &parent_args);
3202 		if (ret)
3203 			continue;
3204 
3205 		parent_genpd = genpd_get_from_provider(&parent_args);
3206 		of_node_put(parent_args.np);
3207 		if (IS_ERR(parent_genpd))
3208 			continue;
3209 
3210 		child_genpd = data->domains[child_id];
3211 		pm_genpd_remove_subdomain(parent_genpd, child_genpd);
3212 	}
3213 
3214 	return 0;
3215 }
3216 EXPORT_SYMBOL_GPL(of_genpd_remove_child_ids);
3217 
3218 /**
3219  * of_genpd_add_device() - Add a device to an I/O PM domain
3220  * @genpdspec: OF phandle args to use for look-up PM domain
3221  * @dev: Device to be added.
3222  *
3223  * Looks-up an I/O PM domain based upon phandle args provided and adds
3224  * the device to the PM domain. Returns a negative error code on failure.
3225  */
3226 int of_genpd_add_device(const struct of_phandle_args *genpdspec, struct device *dev)
3227 {
3228 	struct generic_pm_domain *genpd;
3229 	int ret;
3230 
3231 	if (!dev)
3232 		return -EINVAL;
3233 
3234 	mutex_lock(&gpd_list_lock);
3235 
3236 	genpd = genpd_get_from_provider(genpdspec);
3237 	if (IS_ERR(genpd)) {
3238 		ret = PTR_ERR(genpd);
3239 		goto out;
3240 	}
3241 
3242 	ret = genpd_add_device(genpd, dev, dev);
3243 
3244 out:
3245 	mutex_unlock(&gpd_list_lock);
3246 
3247 	return ret;
3248 }
3249 EXPORT_SYMBOL_GPL(of_genpd_add_device);
3250 
3251 /**
3252  * of_genpd_add_subdomain - Add a subdomain to an I/O PM domain.
3253  * @parent_spec: OF phandle args to use for parent PM domain look-up
3254  * @subdomain_spec: OF phandle args to use for subdomain look-up
3255  *
3256  * Looks-up a parent PM domain and subdomain based upon phandle args
3257  * provided and adds the subdomain to the parent PM domain. Returns a
3258  * negative error code on failure.
3259  */
3260 int of_genpd_add_subdomain(const struct of_phandle_args *parent_spec,
3261 			   const struct of_phandle_args *subdomain_spec)
3262 {
3263 	struct generic_pm_domain *parent, *subdomain;
3264 	int ret;
3265 
3266 	mutex_lock(&gpd_list_lock);
3267 
3268 	parent = genpd_get_from_provider(parent_spec);
3269 	if (IS_ERR(parent)) {
3270 		ret = PTR_ERR(parent);
3271 		goto out;
3272 	}
3273 
3274 	subdomain = genpd_get_from_provider(subdomain_spec);
3275 	if (IS_ERR(subdomain)) {
3276 		ret = PTR_ERR(subdomain);
3277 		goto out;
3278 	}
3279 
3280 	ret = genpd_add_subdomain(parent, subdomain);
3281 
3282 out:
3283 	mutex_unlock(&gpd_list_lock);
3284 
3285 	return ret == -ENOENT ? -EPROBE_DEFER : ret;
3286 }
3287 EXPORT_SYMBOL_GPL(of_genpd_add_subdomain);
3288 
3289 /**
3290  * of_genpd_remove_subdomain - Remove a subdomain from an I/O PM domain.
3291  * @parent_spec: OF phandle args to use for parent PM domain look-up
3292  * @subdomain_spec: OF phandle args to use for subdomain look-up
3293  *
3294  * Looks-up a parent PM domain and subdomain based upon phandle args
3295  * provided and removes the subdomain from the parent PM domain. Returns a
3296  * negative error code on failure.
3297  */
3298 int of_genpd_remove_subdomain(const struct of_phandle_args *parent_spec,
3299 			      const struct of_phandle_args *subdomain_spec)
3300 {
3301 	struct generic_pm_domain *parent, *subdomain;
3302 	int ret;
3303 
3304 	mutex_lock(&gpd_list_lock);
3305 
3306 	parent = genpd_get_from_provider(parent_spec);
3307 	if (IS_ERR(parent)) {
3308 		ret = PTR_ERR(parent);
3309 		goto out;
3310 	}
3311 
3312 	subdomain = genpd_get_from_provider(subdomain_spec);
3313 	if (IS_ERR(subdomain)) {
3314 		ret = PTR_ERR(subdomain);
3315 		goto out;
3316 	}
3317 
3318 	ret = pm_genpd_remove_subdomain(parent, subdomain);
3319 
3320 out:
3321 	mutex_unlock(&gpd_list_lock);
3322 
3323 	return ret;
3324 }
3325 EXPORT_SYMBOL_GPL(of_genpd_remove_subdomain);
3326 
3327 /**
3328  * of_genpd_remove_last - Remove the last PM domain registered for a provider
3329  * @np: Pointer to device node associated with provider
3330  *
3331  * Find the last PM domain that was added by a particular provider and
3332  * remove this PM domain from the list of PM domains. The provider is
3333  * identified by the 'provider' device structure that is passed. The PM
3334  * domain will only be removed, if the provider associated with domain
3335  * has been removed.
3336  *
3337  * Returns a valid pointer to struct generic_pm_domain on success or
3338  * ERR_PTR() on failure.
3339  */
3340 struct generic_pm_domain *of_genpd_remove_last(struct device_node *np)
3341 {
3342 	struct generic_pm_domain *gpd, *tmp, *genpd = ERR_PTR(-ENOENT);
3343 	int ret;
3344 
3345 	if (IS_ERR_OR_NULL(np))
3346 		return ERR_PTR(-EINVAL);
3347 
3348 	mutex_lock(&gpd_list_lock);
3349 	list_for_each_entry_safe(gpd, tmp, &gpd_list, gpd_list_node) {
3350 		if (gpd->provider == of_fwnode_handle(np)) {
3351 			ret = genpd_remove(gpd);
3352 			genpd = ret ? ERR_PTR(ret) : gpd;
3353 			break;
3354 		}
3355 	}
3356 	mutex_unlock(&gpd_list_lock);
3357 
3358 	return genpd;
3359 }
3360 EXPORT_SYMBOL_GPL(of_genpd_remove_last);
3361 
3362 static void genpd_release_dev(struct device *dev)
3363 {
3364 	of_node_put(dev->of_node);
3365 	kfree(dev);
3366 }
3367 
3368 static const struct bus_type genpd_bus_type = {
3369 	.name		= "genpd",
3370 };
3371 
3372 /**
3373  * genpd_dev_pm_detach - Detach a device from its PM domain.
3374  * @dev: Device to detach.
3375  * @power_off: Currently not used
3376  *
3377  * Try to locate a corresponding generic PM domain, which the device was
3378  * attached to previously. If such is found, the device is detached from it.
3379  */
3380 static void genpd_dev_pm_detach(struct device *dev, bool power_off)
3381 {
3382 	struct generic_pm_domain *pd;
3383 	bool is_virt_dev;
3384 	unsigned int i;
3385 	int ret = 0;
3386 
3387 	pd = dev_to_genpd(dev);
3388 	if (IS_ERR(pd))
3389 		return;
3390 
3391 	dev_dbg(dev, "removing from PM domain %s\n", pd->name);
3392 
3393 	/* Check if the device was created by genpd at attach. */
3394 	is_virt_dev = dev->bus == &genpd_bus_type;
3395 
3396 	/* Disable runtime PM if we enabled it at attach. */
3397 	if (is_virt_dev)
3398 		pm_runtime_disable(dev);
3399 
3400 	/* Drop the default performance state */
3401 	if (dev_gpd_data(dev)->default_pstate) {
3402 		dev_pm_genpd_set_performance_state(dev, 0);
3403 		dev_gpd_data(dev)->default_pstate = 0;
3404 	}
3405 
3406 	for (i = 1; i < GENPD_RETRY_MAX_MS; i <<= 1) {
3407 		ret = genpd_remove_device(pd, dev);
3408 		if (ret != -EAGAIN)
3409 			break;
3410 
3411 		mdelay(i);
3412 		cond_resched();
3413 	}
3414 
3415 	if (ret < 0) {
3416 		dev_err(dev, "failed to remove from PM domain %s: %d",
3417 			pd->name, ret);
3418 		return;
3419 	}
3420 
3421 	/* Check if PM domain can be powered off after removing this device. */
3422 	genpd_queue_power_off_work(pd);
3423 
3424 	/* Unregister the device if it was created by genpd. */
3425 	if (is_virt_dev)
3426 		device_unregister(dev);
3427 }
3428 
3429 static void genpd_dev_pm_sync(struct device *dev)
3430 {
3431 	struct generic_pm_domain *pd;
3432 
3433 	pd = dev_to_genpd(dev);
3434 	if (IS_ERR(pd))
3435 		return;
3436 
3437 	genpd_queue_power_off_work(pd);
3438 }
3439 
3440 static int genpd_set_required_opp_dev(struct device *dev,
3441 				      struct device *base_dev)
3442 {
3443 	struct dev_pm_opp_config config = {
3444 		.required_dev = dev,
3445 	};
3446 	int ret;
3447 
3448 	/* Limit support to non-providers for now. */
3449 	if (of_property_present(base_dev->of_node, "#power-domain-cells"))
3450 		return 0;
3451 
3452 	if (!dev_pm_opp_of_has_required_opp(base_dev))
3453 		return 0;
3454 
3455 	ret = dev_pm_opp_set_config(base_dev, &config);
3456 	if (ret < 0)
3457 		return ret;
3458 
3459 	dev_gpd_data(dev)->opp_token = ret;
3460 	return 0;
3461 }
3462 
3463 static int genpd_set_required_opp(struct device *dev, unsigned int index)
3464 {
3465 	int ret, pstate;
3466 
3467 	/* Set the default performance state */
3468 	pstate = of_get_required_opp_performance_state(dev->of_node, index);
3469 	if (pstate < 0 && pstate != -ENODEV && pstate != -EOPNOTSUPP) {
3470 		ret = pstate;
3471 		goto err;
3472 	} else if (pstate > 0) {
3473 		ret = dev_pm_genpd_set_performance_state(dev, pstate);
3474 		if (ret)
3475 			goto err;
3476 		dev_gpd_data(dev)->default_pstate = pstate;
3477 	}
3478 
3479 	return 0;
3480 err:
3481 	dev_err(dev, "failed to set required performance state for power-domain %s: %d\n",
3482 		dev_to_genpd(dev)->name, ret);
3483 	return ret;
3484 }
3485 
3486 static int __genpd_dev_pm_attach(struct device *dev, struct device *base_dev,
3487 				 unsigned int index, unsigned int num_domains,
3488 				 bool power_on)
3489 {
3490 	struct of_phandle_args pd_args;
3491 	struct generic_pm_domain *pd;
3492 	int ret;
3493 
3494 	ret = of_parse_phandle_with_args(dev->of_node, "power-domains",
3495 				"#power-domain-cells", index, &pd_args);
3496 	if (ret < 0)
3497 		return ret;
3498 
3499 	mutex_lock(&gpd_list_lock);
3500 	pd = genpd_get_from_provider(&pd_args);
3501 	of_node_put(pd_args.np);
3502 	if (IS_ERR(pd)) {
3503 		mutex_unlock(&gpd_list_lock);
3504 		dev_dbg(dev, "%s() failed to find PM domain: %ld\n",
3505 			__func__, PTR_ERR(pd));
3506 		return driver_deferred_probe_check_state(base_dev);
3507 	}
3508 
3509 	dev_dbg(dev, "adding to PM domain %s\n", pd->name);
3510 
3511 	ret = genpd_add_device(pd, dev, base_dev);
3512 	mutex_unlock(&gpd_list_lock);
3513 
3514 	if (ret < 0)
3515 		return dev_err_probe(dev, ret, "failed to add to PM domain %s\n", pd->name);
3516 
3517 	dev->pm_domain->detach = genpd_dev_pm_detach;
3518 	dev->pm_domain->sync = genpd_dev_pm_sync;
3519 
3520 	/*
3521 	 * For a single PM domain the index of the required OPP must be zero, so
3522 	 * let's try to assign a required dev in that case. In the multiple PM
3523 	 * domains case, we need platform code to specify the index.
3524 	 */
3525 	if (num_domains == 1) {
3526 		ret = genpd_set_required_opp_dev(dev, base_dev);
3527 		if (ret)
3528 			goto err;
3529 	}
3530 
3531 	ret = genpd_set_required_opp(dev, index);
3532 	if (ret)
3533 		goto err;
3534 
3535 	if (power_on) {
3536 		genpd_lock(pd);
3537 		ret = genpd_power_on(pd, dev, 0);
3538 		genpd_unlock(pd);
3539 	}
3540 
3541 	if (ret) {
3542 		/* Drop the default performance state */
3543 		if (dev_gpd_data(dev)->default_pstate) {
3544 			dev_pm_genpd_set_performance_state(dev, 0);
3545 			dev_gpd_data(dev)->default_pstate = 0;
3546 		}
3547 
3548 		genpd_remove_device(pd, dev);
3549 		return -EPROBE_DEFER;
3550 	}
3551 
3552 	return 1;
3553 
3554 err:
3555 	genpd_remove_device(pd, dev);
3556 	return ret;
3557 }
3558 
3559 /**
3560  * genpd_dev_pm_attach - Attach a device to its PM domain using DT.
3561  * @dev: Device to attach.
3562  *
3563  * Parse device's OF node to find a PM domain specifier. If such is found,
3564  * attaches the device to retrieved pm_domain ops.
3565  *
3566  * Returns 1 on successfully attached PM domain, 0 when the device don't need a
3567  * PM domain or when multiple power-domains exists for it, else a negative error
3568  * code. Note that if a power-domain exists for the device, but it cannot be
3569  * found or turned on, then return -EPROBE_DEFER to ensure that the device is
3570  * not probed and to re-try again later.
3571  */
3572 int genpd_dev_pm_attach(struct device *dev)
3573 {
3574 	if (!dev->of_node)
3575 		return 0;
3576 
3577 	/*
3578 	 * Devices with multiple PM domains must be attached separately, as we
3579 	 * can only attach one PM domain per device.
3580 	 */
3581 	if (of_count_phandle_with_args(dev->of_node, "power-domains",
3582 				       "#power-domain-cells") != 1)
3583 		return 0;
3584 
3585 	return __genpd_dev_pm_attach(dev, dev, 0, 1, true);
3586 }
3587 EXPORT_SYMBOL_GPL(genpd_dev_pm_attach);
3588 
3589 /**
3590  * genpd_dev_pm_attach_by_id - Associate a device with one of its PM domains.
3591  * @dev: The device used to lookup the PM domain.
3592  * @index: The index of the PM domain.
3593  *
3594  * Parse device's OF node to find a PM domain specifier at the provided @index.
3595  * If such is found, creates a virtual device and attaches it to the retrieved
3596  * pm_domain ops. To deal with detaching of the virtual device, the ->detach()
3597  * callback in the struct dev_pm_domain are assigned to genpd_dev_pm_detach().
3598  *
3599  * Returns the created virtual device if successfully attached PM domain, NULL
3600  * when the device don't need a PM domain, else an ERR_PTR() in case of
3601  * failures. If a power-domain exists for the device, but cannot be found or
3602  * turned on, then ERR_PTR(-EPROBE_DEFER) is returned to ensure that the device
3603  * is not probed and to re-try again later.
3604  */
3605 struct device *genpd_dev_pm_attach_by_id(struct device *dev,
3606 					 unsigned int index)
3607 {
3608 	struct device *virt_dev;
3609 	int num_domains;
3610 	int ret;
3611 
3612 	if (!dev->of_node)
3613 		return NULL;
3614 
3615 	/* Verify that the index is within a valid range. */
3616 	num_domains = of_count_phandle_with_args(dev->of_node, "power-domains",
3617 						 "#power-domain-cells");
3618 	if (num_domains < 0 || index >= num_domains)
3619 		return NULL;
3620 
3621 	if (!genpd_bus_registered)
3622 		return ERR_PTR(-ENODEV);
3623 
3624 	/* Allocate and register device on the genpd bus. */
3625 	virt_dev = kzalloc_obj(*virt_dev);
3626 	if (!virt_dev)
3627 		return ERR_PTR(-ENOMEM);
3628 
3629 	dev_set_name(virt_dev, "genpd:%u:%s", index, dev_name(dev));
3630 	virt_dev->bus = &genpd_bus_type;
3631 	virt_dev->release = genpd_release_dev;
3632 	virt_dev->of_node = of_node_get(dev->of_node);
3633 
3634 	ret = device_register(virt_dev);
3635 	if (ret) {
3636 		put_device(virt_dev);
3637 		return ERR_PTR(ret);
3638 	}
3639 
3640 	/* Try to attach the device to the PM domain at the specified index. */
3641 	ret = __genpd_dev_pm_attach(virt_dev, dev, index, num_domains, false);
3642 	if (ret < 1) {
3643 		device_unregister(virt_dev);
3644 		return ret ? ERR_PTR(ret) : NULL;
3645 	}
3646 
3647 	pm_runtime_enable(virt_dev);
3648 	genpd_queue_power_off_work(dev_to_genpd(virt_dev));
3649 
3650 	return virt_dev;
3651 }
3652 EXPORT_SYMBOL_GPL(genpd_dev_pm_attach_by_id);
3653 
3654 /**
3655  * genpd_dev_pm_attach_by_name - Associate a device with one of its PM domains.
3656  * @dev: The device used to lookup the PM domain.
3657  * @name: The name of the PM domain.
3658  *
3659  * Parse device's OF node to find a PM domain specifier using the
3660  * power-domain-names DT property. For further description see
3661  * genpd_dev_pm_attach_by_id().
3662  */
3663 struct device *genpd_dev_pm_attach_by_name(struct device *dev, const char *name)
3664 {
3665 	int index;
3666 
3667 	if (!dev->of_node)
3668 		return NULL;
3669 
3670 	index = of_property_match_string(dev->of_node, "power-domain-names",
3671 					 name);
3672 	if (index < 0)
3673 		return NULL;
3674 
3675 	return genpd_dev_pm_attach_by_id(dev, index);
3676 }
3677 
3678 static const struct of_device_id idle_state_match[] = {
3679 	{ .compatible = "domain-idle-state", },
3680 	{ }
3681 };
3682 
3683 static int genpd_parse_state(struct genpd_power_state *genpd_state,
3684 				    struct device_node *state_node)
3685 {
3686 	int err;
3687 	u32 residency;
3688 	u32 entry_latency, exit_latency;
3689 
3690 	err = of_property_read_u32(state_node, "entry-latency-us",
3691 						&entry_latency);
3692 	if (err) {
3693 		pr_debug(" * %pOF missing entry-latency-us property\n",
3694 			 state_node);
3695 		return -EINVAL;
3696 	}
3697 
3698 	err = of_property_read_u32(state_node, "exit-latency-us",
3699 						&exit_latency);
3700 	if (err) {
3701 		pr_debug(" * %pOF missing exit-latency-us property\n",
3702 			 state_node);
3703 		return -EINVAL;
3704 	}
3705 
3706 	err = of_property_read_u32(state_node, "min-residency-us", &residency);
3707 	if (!err)
3708 		genpd_state->residency_ns = 1000LL * residency;
3709 
3710 	err = of_property_read_string(state_node, "idle-state-name",
3711 				      &genpd_state->name);
3712 	if (err)
3713 		genpd_state->name = state_node->name;
3714 
3715 	genpd_state->power_on_latency_ns = 1000LL * exit_latency;
3716 	genpd_state->power_off_latency_ns = 1000LL * entry_latency;
3717 	genpd_state->fwnode = of_fwnode_handle(state_node);
3718 
3719 	return 0;
3720 }
3721 
3722 static int genpd_iterate_idle_states(struct device_node *dn,
3723 				     struct genpd_power_state *states)
3724 {
3725 	int ret;
3726 	struct of_phandle_iterator it;
3727 	struct device_node *np;
3728 	int i = 0;
3729 
3730 	ret = of_count_phandle_with_args(dn, "domain-idle-states", NULL);
3731 	if (ret <= 0)
3732 		return ret == -ENOENT ? 0 : ret;
3733 
3734 	/* Loop over the phandles until all the requested entry is found */
3735 	of_for_each_phandle(&it, ret, dn, "domain-idle-states", NULL, 0) {
3736 		np = it.node;
3737 		if (!of_match_node(idle_state_match, np))
3738 			continue;
3739 
3740 		if (!of_device_is_available(np))
3741 			continue;
3742 
3743 		if (states) {
3744 			ret = genpd_parse_state(&states[i], np);
3745 			if (ret) {
3746 				pr_err("Parsing idle state node %pOF failed with err %d\n",
3747 				       np, ret);
3748 				of_node_put(np);
3749 				return ret;
3750 			}
3751 		}
3752 		i++;
3753 	}
3754 
3755 	return i;
3756 }
3757 
3758 /**
3759  * of_genpd_parse_idle_states: Return array of idle states for the genpd.
3760  *
3761  * @dn: The genpd device node
3762  * @states: The pointer to which the state array will be saved.
3763  * @n: The count of elements in the array returned from this function.
3764  *
3765  * Returns the device states parsed from the OF node. The memory for the states
3766  * is allocated by this function and is the responsibility of the caller to
3767  * free the memory after use. If any or zero compatible domain idle states is
3768  * found it returns 0 and in case of errors, a negative error code is returned.
3769  */
3770 int of_genpd_parse_idle_states(struct device_node *dn,
3771 			struct genpd_power_state **states, int *n)
3772 {
3773 	struct genpd_power_state *st;
3774 	int ret;
3775 
3776 	ret = genpd_iterate_idle_states(dn, NULL);
3777 	if (ret < 0)
3778 		return ret;
3779 
3780 	if (!ret) {
3781 		*states = NULL;
3782 		*n = 0;
3783 		return 0;
3784 	}
3785 
3786 	st = kzalloc_objs(*st, ret);
3787 	if (!st)
3788 		return -ENOMEM;
3789 
3790 	ret = genpd_iterate_idle_states(dn, st);
3791 	if (ret <= 0) {
3792 		kfree(st);
3793 		return ret < 0 ? ret : -EINVAL;
3794 	}
3795 
3796 	*states = st;
3797 	*n = ret;
3798 
3799 	return 0;
3800 }
3801 EXPORT_SYMBOL_GPL(of_genpd_parse_idle_states);
3802 
3803 /**
3804  * of_genpd_sync_state() - A common sync_state function for genpd providers
3805  * @np: The device node the genpd provider is associated with.
3806  *
3807  * The @np that corresponds to a genpd provider may provide one or multiple
3808  * genpds. This function makes use @np to find the genpds that belongs to the
3809  * provider. For each genpd we try a power-off.
3810  */
3811 void of_genpd_sync_state(struct device_node *np)
3812 {
3813 	struct generic_pm_domain *genpd;
3814 
3815 	if (!np)
3816 		return;
3817 
3818 	mutex_lock(&gpd_list_lock);
3819 	list_for_each_entry(genpd, &gpd_list, gpd_list_node) {
3820 		if (genpd->provider == of_fwnode_handle(np)) {
3821 			genpd_lock(genpd);
3822 			genpd->stay_on = false;
3823 			genpd_power_off(genpd, false, 0);
3824 			genpd_unlock(genpd);
3825 		}
3826 	}
3827 	mutex_unlock(&gpd_list_lock);
3828 }
3829 EXPORT_SYMBOL_GPL(of_genpd_sync_state);
3830 
3831 static int genpd_provider_probe(struct device *dev)
3832 {
3833 	return 0;
3834 }
3835 
3836 static void genpd_provider_sync_state(struct device *dev)
3837 {
3838 	struct generic_pm_domain *genpd = container_of(dev, struct generic_pm_domain, dev);
3839 
3840 	switch (genpd->sync_state) {
3841 	case GENPD_SYNC_STATE_OFF:
3842 		break;
3843 
3844 	case GENPD_SYNC_STATE_ONECELL:
3845 		of_genpd_sync_state(dev->of_node);
3846 		break;
3847 
3848 	case GENPD_SYNC_STATE_SIMPLE:
3849 		genpd_lock(genpd);
3850 		genpd->stay_on = false;
3851 		genpd_power_off(genpd, false, 0);
3852 		genpd_unlock(genpd);
3853 		break;
3854 
3855 	default:
3856 		break;
3857 	}
3858 }
3859 
3860 static struct device_driver genpd_provider_drv = {
3861 	.name = "genpd_provider",
3862 	.bus = &genpd_provider_bus_type,
3863 	.probe = genpd_provider_probe,
3864 	.sync_state = genpd_provider_sync_state,
3865 	.suppress_bind_attrs = true,
3866 };
3867 
3868 static int __init genpd_bus_init(void)
3869 {
3870 	int ret;
3871 
3872 	genpd_provider_bus = root_device_register("genpd_provider");
3873 	if (IS_ERR(genpd_provider_bus))
3874 		return PTR_ERR(genpd_provider_bus);
3875 
3876 	ret = bus_register(&genpd_provider_bus_type);
3877 	if (ret)
3878 		goto err_dev;
3879 
3880 	ret = bus_register(&genpd_bus_type);
3881 	if (ret)
3882 		goto err_prov_bus;
3883 
3884 	ret = driver_register(&genpd_provider_drv);
3885 	if (ret)
3886 		goto err_bus;
3887 
3888 	genpd_bus_registered = true;
3889 	return 0;
3890 
3891 err_bus:
3892 	bus_unregister(&genpd_bus_type);
3893 err_prov_bus:
3894 	bus_unregister(&genpd_provider_bus_type);
3895 err_dev:
3896 	root_device_unregister(genpd_provider_bus);
3897 	return ret;
3898 }
3899 core_initcall(genpd_bus_init);
3900 
3901 #endif /* CONFIG_PM_GENERIC_DOMAINS_OF */
3902 
3903 
3904 /***        debugfs support        ***/
3905 
3906 #ifdef CONFIG_DEBUG_FS
3907 /*
3908  * TODO: This function is a slightly modified version of rtpm_status_show
3909  * from sysfs.c, so generalize it.
3910  */
3911 static void rtpm_status_str(struct seq_file *s, struct device *dev)
3912 {
3913 	static const char * const status_lookup[] = {
3914 		[RPM_ACTIVE] = "active",
3915 		[RPM_RESUMING] = "resuming",
3916 		[RPM_SUSPENDED] = "suspended",
3917 		[RPM_SUSPENDING] = "suspending"
3918 	};
3919 	const char *p = "";
3920 
3921 	if (dev->power.runtime_error)
3922 		p = "error";
3923 	else if (dev->power.disable_depth)
3924 		p = "unsupported";
3925 	else if (dev->power.runtime_status < ARRAY_SIZE(status_lookup))
3926 		p = status_lookup[dev->power.runtime_status];
3927 	else
3928 		WARN_ON(1);
3929 
3930 	seq_printf(s, "%-26s  ", p);
3931 }
3932 
3933 static void perf_status_str(struct seq_file *s, struct device *dev)
3934 {
3935 	struct generic_pm_domain_data *gpd_data;
3936 
3937 	gpd_data = to_gpd_data(dev->power.subsys_data->domain_data);
3938 
3939 	seq_printf(s, "%-10u  ", gpd_data->performance_state);
3940 }
3941 
3942 static void mode_status_str(struct seq_file *s, struct device *dev)
3943 {
3944 	struct generic_pm_domain_data *gpd_data;
3945 
3946 	gpd_data = to_gpd_data(dev->power.subsys_data->domain_data);
3947 
3948 	seq_printf(s, "%2s", gpd_data->hw_mode ? "HW" : "SW");
3949 }
3950 
3951 static int genpd_summary_one(struct seq_file *s,
3952 			struct generic_pm_domain *genpd)
3953 {
3954 	static const char * const status_lookup[] = {
3955 		[GENPD_STATE_ON] = "on",
3956 		[GENPD_STATE_OFF] = "off"
3957 	};
3958 	struct pm_domain_data *pm_data;
3959 	struct gpd_link *link;
3960 	char state[16];
3961 	int ret;
3962 
3963 	ret = genpd_lock_interruptible(genpd);
3964 	if (ret)
3965 		return -ERESTARTSYS;
3966 
3967 	if (WARN_ON(genpd->status >= ARRAY_SIZE(status_lookup)))
3968 		goto exit;
3969 	if (!genpd_status_on_unlocked(genpd))
3970 		snprintf(state, sizeof(state), "%s-%u",
3971 			 status_lookup[genpd->status], genpd->state_idx);
3972 	else
3973 		snprintf(state, sizeof(state), "%s",
3974 			 status_lookup[genpd->status]);
3975 	seq_printf(s, "%-30s  %-30s  %u", dev_name(&genpd->dev), state, genpd->performance_state);
3976 
3977 	/*
3978 	 * Modifications on the list require holding locks on both
3979 	 * parent and child, so we are safe.
3980 	 * Also the device name is immutable.
3981 	 */
3982 	list_for_each_entry(link, &genpd->parent_links, parent_node) {
3983 		if (list_is_first(&link->parent_node, &genpd->parent_links))
3984 			seq_printf(s, "\n%48s", " ");
3985 		seq_printf(s, "%s", link->child->name);
3986 		if (!list_is_last(&link->parent_node, &genpd->parent_links))
3987 			seq_puts(s, ", ");
3988 	}
3989 
3990 	list_for_each_entry(pm_data, &genpd->dev_list, list_node) {
3991 		seq_printf(s, "\n    %-30s  ", dev_name(pm_data->dev));
3992 		rtpm_status_str(s, pm_data->dev);
3993 		perf_status_str(s, pm_data->dev);
3994 		mode_status_str(s, pm_data->dev);
3995 	}
3996 
3997 	seq_puts(s, "\n");
3998 exit:
3999 	genpd_unlock(genpd);
4000 
4001 	return 0;
4002 }
4003 
4004 static int summary_show(struct seq_file *s, void *data)
4005 {
4006 	struct generic_pm_domain *genpd;
4007 	int ret = 0;
4008 
4009 	seq_puts(s, "domain                          status          children        performance\n");
4010 	seq_puts(s, "    /device                         runtime status                  managed by\n");
4011 	seq_puts(s, "------------------------------------------------------------------------------\n");
4012 
4013 	ret = mutex_lock_interruptible(&gpd_list_lock);
4014 	if (ret)
4015 		return -ERESTARTSYS;
4016 
4017 	list_for_each_entry(genpd, &gpd_list, gpd_list_node) {
4018 		ret = genpd_summary_one(s, genpd);
4019 		if (ret)
4020 			break;
4021 	}
4022 	mutex_unlock(&gpd_list_lock);
4023 
4024 	return ret;
4025 }
4026 
4027 static int status_show(struct seq_file *s, void *data)
4028 {
4029 	static const char * const status_lookup[] = {
4030 		[GENPD_STATE_ON] = "on",
4031 		[GENPD_STATE_OFF] = "off"
4032 	};
4033 
4034 	struct generic_pm_domain *genpd = s->private;
4035 	int ret = 0;
4036 
4037 	ret = genpd_lock_interruptible(genpd);
4038 	if (ret)
4039 		return -ERESTARTSYS;
4040 
4041 	if (WARN_ON_ONCE(genpd->status >= ARRAY_SIZE(status_lookup)))
4042 		goto exit;
4043 
4044 	if (genpd->status == GENPD_STATE_OFF)
4045 		seq_printf(s, "%s-%u\n", status_lookup[genpd->status],
4046 			genpd->state_idx);
4047 	else
4048 		seq_printf(s, "%s\n", status_lookup[genpd->status]);
4049 exit:
4050 	genpd_unlock(genpd);
4051 	return ret;
4052 }
4053 
4054 static int sub_domains_show(struct seq_file *s, void *data)
4055 {
4056 	struct generic_pm_domain *genpd = s->private;
4057 	struct gpd_link *link;
4058 	int ret = 0;
4059 
4060 	ret = genpd_lock_interruptible(genpd);
4061 	if (ret)
4062 		return -ERESTARTSYS;
4063 
4064 	list_for_each_entry(link, &genpd->parent_links, parent_node)
4065 		seq_printf(s, "%s\n", link->child->name);
4066 
4067 	genpd_unlock(genpd);
4068 	return ret;
4069 }
4070 
4071 static int idle_states_show(struct seq_file *s, void *data)
4072 {
4073 	struct generic_pm_domain *genpd = s->private;
4074 	u64 now, delta, idle_time = 0;
4075 	unsigned int i;
4076 	int ret = 0;
4077 
4078 	ret = genpd_lock_interruptible(genpd);
4079 	if (ret)
4080 		return -ERESTARTSYS;
4081 
4082 	seq_puts(s, "State  Time(ms)       Usage      Rejected   Above      Below      S2idle\n");
4083 
4084 	for (i = 0; i < genpd->state_count; i++) {
4085 		struct genpd_power_state *state = &genpd->states[i];
4086 		char state_name[7];
4087 
4088 		idle_time += state->idle_time;
4089 
4090 		if (genpd->status == GENPD_STATE_OFF && genpd->state_idx == i) {
4091 			now = ktime_get_mono_fast_ns();
4092 			if (now > genpd->accounting_time) {
4093 				delta = now - genpd->accounting_time;
4094 				idle_time += delta;
4095 			}
4096 		}
4097 
4098 		snprintf(state_name, ARRAY_SIZE(state_name), "S%-5d", i);
4099 		do_div(idle_time, NSEC_PER_MSEC);
4100 		seq_printf(s, "%-6s %-14llu %-10llu %-10llu %-10llu %-10llu %llu\n",
4101 			   state_name, idle_time, state->usage, state->rejected,
4102 			   state->above, state->below, state->usage_s2idle);
4103 	}
4104 
4105 	genpd_unlock(genpd);
4106 	return ret;
4107 }
4108 
4109 static int idle_states_desc_show(struct seq_file *s, void *data)
4110 {
4111 	struct generic_pm_domain *genpd = s->private;
4112 	unsigned int i;
4113 	int ret = 0;
4114 
4115 	ret = genpd_lock_interruptible(genpd);
4116 	if (ret)
4117 		return -ERESTARTSYS;
4118 
4119 	seq_puts(s, "State  Latency(us)  Residency(us)  Name\n");
4120 
4121 	for (i = 0; i < genpd->state_count; i++) {
4122 		struct genpd_power_state *state = &genpd->states[i];
4123 		u64 latency, residency;
4124 		char state_name[7];
4125 
4126 		latency = state->power_off_latency_ns +
4127 			state->power_on_latency_ns;
4128 		do_div(latency, NSEC_PER_USEC);
4129 
4130 		residency = state->residency_ns;
4131 		do_div(residency, NSEC_PER_USEC);
4132 
4133 		snprintf(state_name, ARRAY_SIZE(state_name), "S%-5d", i);
4134 		seq_printf(s, "%-6s %-12llu %-14llu %s\n",
4135 			   state_name, latency, residency,
4136 			   state->name ?: "N/A");
4137 	}
4138 
4139 	genpd_unlock(genpd);
4140 	return ret;
4141 }
4142 
4143 static int active_time_show(struct seq_file *s, void *data)
4144 {
4145 	struct generic_pm_domain *genpd = s->private;
4146 	u64 now, on_time, delta = 0;
4147 	int ret = 0;
4148 
4149 	ret = genpd_lock_interruptible(genpd);
4150 	if (ret)
4151 		return -ERESTARTSYS;
4152 
4153 	if (genpd->status == GENPD_STATE_ON) {
4154 		now = ktime_get_mono_fast_ns();
4155 		if (now > genpd->accounting_time)
4156 			delta = now - genpd->accounting_time;
4157 	}
4158 
4159 	on_time = genpd->on_time + delta;
4160 	do_div(on_time, NSEC_PER_MSEC);
4161 	seq_printf(s, "%llu ms\n", on_time);
4162 
4163 	genpd_unlock(genpd);
4164 	return ret;
4165 }
4166 
4167 static int total_idle_time_show(struct seq_file *s, void *data)
4168 {
4169 	struct generic_pm_domain *genpd = s->private;
4170 	u64 now, delta, total = 0;
4171 	unsigned int i;
4172 	int ret = 0;
4173 
4174 	ret = genpd_lock_interruptible(genpd);
4175 	if (ret)
4176 		return -ERESTARTSYS;
4177 
4178 	for (i = 0; i < genpd->state_count; i++) {
4179 		total += genpd->states[i].idle_time;
4180 
4181 		if (genpd->status == GENPD_STATE_OFF && genpd->state_idx == i) {
4182 			now = ktime_get_mono_fast_ns();
4183 			if (now > genpd->accounting_time) {
4184 				delta = now - genpd->accounting_time;
4185 				total += delta;
4186 			}
4187 		}
4188 	}
4189 
4190 	do_div(total, NSEC_PER_MSEC);
4191 	seq_printf(s, "%llu ms\n", total);
4192 
4193 	genpd_unlock(genpd);
4194 	return ret;
4195 }
4196 
4197 
4198 static int devices_show(struct seq_file *s, void *data)
4199 {
4200 	struct generic_pm_domain *genpd = s->private;
4201 	struct pm_domain_data *pm_data;
4202 	int ret = 0;
4203 
4204 	ret = genpd_lock_interruptible(genpd);
4205 	if (ret)
4206 		return -ERESTARTSYS;
4207 
4208 	list_for_each_entry(pm_data, &genpd->dev_list, list_node)
4209 		seq_printf(s, "%s\n", dev_name(pm_data->dev));
4210 
4211 	genpd_unlock(genpd);
4212 	return ret;
4213 }
4214 
4215 static int perf_state_show(struct seq_file *s, void *data)
4216 {
4217 	struct generic_pm_domain *genpd = s->private;
4218 
4219 	if (genpd_lock_interruptible(genpd))
4220 		return -ERESTARTSYS;
4221 
4222 	seq_printf(s, "%u\n", genpd->performance_state);
4223 
4224 	genpd_unlock(genpd);
4225 	return 0;
4226 }
4227 
4228 DEFINE_SHOW_ATTRIBUTE(summary);
4229 DEFINE_SHOW_ATTRIBUTE(status);
4230 DEFINE_SHOW_ATTRIBUTE(sub_domains);
4231 DEFINE_SHOW_ATTRIBUTE(idle_states);
4232 DEFINE_SHOW_ATTRIBUTE(idle_states_desc);
4233 DEFINE_SHOW_ATTRIBUTE(active_time);
4234 DEFINE_SHOW_ATTRIBUTE(total_idle_time);
4235 DEFINE_SHOW_ATTRIBUTE(devices);
4236 DEFINE_SHOW_ATTRIBUTE(perf_state);
4237 
4238 static void genpd_debug_add(struct generic_pm_domain *genpd)
4239 {
4240 	struct dentry *d;
4241 
4242 	if (!genpd_debugfs_dir)
4243 		return;
4244 
4245 	d = debugfs_create_dir(dev_name(&genpd->dev), genpd_debugfs_dir);
4246 
4247 	debugfs_create_file("current_state", 0444,
4248 			    d, genpd, &status_fops);
4249 	debugfs_create_file("sub_domains", 0444,
4250 			    d, genpd, &sub_domains_fops);
4251 	debugfs_create_file("idle_states", 0444,
4252 			    d, genpd, &idle_states_fops);
4253 	debugfs_create_file("idle_states_desc", 0444,
4254 			    d, genpd, &idle_states_desc_fops);
4255 	debugfs_create_file("active_time", 0444,
4256 			    d, genpd, &active_time_fops);
4257 	debugfs_create_file("total_idle_time", 0444,
4258 			    d, genpd, &total_idle_time_fops);
4259 	debugfs_create_file("devices", 0444,
4260 			    d, genpd, &devices_fops);
4261 	if (genpd->set_performance_state)
4262 		debugfs_create_file("perf_state", 0444,
4263 				    d, genpd, &perf_state_fops);
4264 }
4265 
4266 static int __init genpd_debug_init(void)
4267 {
4268 	struct generic_pm_domain *genpd;
4269 
4270 	genpd_debugfs_dir = debugfs_create_dir("pm_genpd", NULL);
4271 
4272 	debugfs_create_file("pm_genpd_summary", S_IRUGO, genpd_debugfs_dir,
4273 			    NULL, &summary_fops);
4274 
4275 	list_for_each_entry(genpd, &gpd_list, gpd_list_node)
4276 		genpd_debug_add(genpd);
4277 
4278 	return 0;
4279 }
4280 late_initcall(genpd_debug_init);
4281 
4282 static void __exit genpd_debug_exit(void)
4283 {
4284 	debugfs_remove_recursive(genpd_debugfs_dir);
4285 }
4286 __exitcall(genpd_debug_exit);
4287 #endif /* CONFIG_DEBUG_FS */
4288