xref: /linux/drivers/pmdomain/core.c (revision 44ff5057d75c5680090743233de5a721eb9dabe4)
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 	put_device(&genpd->dev);
2467 	if (genpd->device_id != -ENXIO)
2468 		ida_free(&genpd_ida, genpd->device_id);
2469 	if (genpd_is_cpu_domain(genpd))
2470 		free_cpumask_var(genpd->cpus);
2471 	if (genpd->free_states)
2472 		genpd->free_states(genpd->states, genpd->state_count);
2473 	kfree(genpd->gd);
2474 }
2475 
2476 static void genpd_lock_init(struct generic_pm_domain *genpd)
2477 {
2478 	if (genpd_is_cpu_domain(genpd)) {
2479 		raw_spin_lock_init(&genpd->raw_slock);
2480 		genpd->lock_ops = &genpd_raw_spin_ops;
2481 	} else if (genpd_is_irq_safe(genpd)) {
2482 		spin_lock_init(&genpd->slock);
2483 		genpd->lock_ops = &genpd_spin_ops;
2484 	} else {
2485 		mutex_init(&genpd->mlock);
2486 		genpd->lock_ops = &genpd_mtx_ops;
2487 	}
2488 }
2489 
2490 #ifdef CONFIG_PM_GENERIC_DOMAINS_OF
2491 static void genpd_set_stay_on(struct generic_pm_domain *genpd, bool is_off)
2492 {
2493 	if (genpd_is_power_unknown(genpd))
2494 		genpd->stay_on = is_off;
2495 	else
2496 		genpd->stay_on = !genpd_is_no_stay_on(genpd) && !is_off;
2497 }
2498 #else
2499 static void genpd_set_stay_on(struct generic_pm_domain *genpd, bool is_off)
2500 {
2501 	genpd->stay_on = false;
2502 }
2503 #endif
2504 
2505 /**
2506  * pm_genpd_init - Initialize a generic I/O PM domain object.
2507  * @genpd: PM domain object to initialize.
2508  * @gov: PM domain governor to associate with the domain (may be NULL).
2509  * @is_off: Initial value of the domain's power_is_off field.
2510  *
2511  * Returns 0 on successful initialization, else a negative error code.
2512  */
2513 int pm_genpd_init(struct generic_pm_domain *genpd,
2514 		  struct dev_power_governor *gov, bool is_off)
2515 {
2516 	int ret;
2517 
2518 	if (IS_ERR_OR_NULL(genpd))
2519 		return -EINVAL;
2520 
2521 	INIT_LIST_HEAD(&genpd->parent_links);
2522 	INIT_LIST_HEAD(&genpd->child_links);
2523 	INIT_LIST_HEAD(&genpd->dev_list);
2524 	RAW_INIT_NOTIFIER_HEAD(&genpd->power_notifiers);
2525 	genpd_lock_init(genpd);
2526 	genpd->gov = gov;
2527 	INIT_WORK(&genpd->power_off_work, genpd_power_off_work_fn);
2528 	atomic_set(&genpd->sd_count, 0);
2529 	genpd->status = is_off ? GENPD_STATE_OFF : GENPD_STATE_ON;
2530 	genpd_set_stay_on(genpd, is_off);
2531 	genpd->sync_state = GENPD_SYNC_STATE_OFF;
2532 	genpd->device_count = 0;
2533 	genpd->provider = NULL;
2534 	genpd->device_id = -ENXIO;
2535 	genpd->has_provider = false;
2536 	genpd->opp_table = NULL;
2537 	genpd->accounting_time = ktime_get_mono_fast_ns();
2538 	genpd->domain.ops.runtime_suspend = genpd_runtime_suspend;
2539 	genpd->domain.ops.runtime_resume = genpd_runtime_resume;
2540 	genpd->domain.ops.prepare = genpd_prepare;
2541 	genpd->domain.ops.suspend_noirq = genpd_suspend_noirq;
2542 	genpd->domain.ops.resume_noirq = genpd_resume_noirq;
2543 	genpd->domain.ops.freeze_noirq = genpd_freeze_noirq;
2544 	genpd->domain.ops.thaw_noirq = genpd_thaw_noirq;
2545 	genpd->domain.ops.poweroff_noirq = genpd_poweroff_noirq;
2546 	genpd->domain.ops.restore_noirq = genpd_restore_noirq;
2547 	genpd->domain.ops.complete = genpd_complete;
2548 	genpd->domain.start = genpd_dev_pm_start;
2549 	genpd->domain.set_performance_state = genpd_dev_pm_set_performance_state;
2550 
2551 	if (genpd->flags & GENPD_FLAG_PM_CLK) {
2552 		genpd->dev_ops.stop = pm_clk_suspend;
2553 		genpd->dev_ops.start = pm_clk_resume;
2554 	}
2555 
2556 	/* The always-on governor works better with the corresponding flag. */
2557 	if (gov == &pm_domain_always_on_gov)
2558 		genpd->flags |= GENPD_FLAG_RPM_ALWAYS_ON;
2559 
2560 	/* Always-on domains must be powered on at initialization. */
2561 	if ((genpd_is_always_on(genpd) || genpd_is_rpm_always_on(genpd)) &&
2562 			!genpd_status_on_unlocked(genpd)) {
2563 		pr_err("always-on PM domain %s is not on\n", genpd->name);
2564 		return -EINVAL;
2565 	}
2566 
2567 	/* Multiple states but no governor doesn't make sense. */
2568 	if (!gov && genpd->state_count > 1)
2569 		pr_warn("%s: no governor for states\n", genpd->name);
2570 
2571 	ret = genpd_alloc_data(genpd);
2572 	if (ret)
2573 		return ret;
2574 
2575 	mutex_lock(&gpd_list_lock);
2576 	list_add(&genpd->gpd_list_node, &gpd_list);
2577 	mutex_unlock(&gpd_list_lock);
2578 	genpd_debug_add(genpd);
2579 
2580 	return 0;
2581 }
2582 EXPORT_SYMBOL_GPL(pm_genpd_init);
2583 
2584 static int genpd_remove(struct generic_pm_domain *genpd)
2585 {
2586 	struct gpd_link *l, *link;
2587 
2588 	if (IS_ERR_OR_NULL(genpd))
2589 		return -EINVAL;
2590 
2591 	genpd_lock(genpd);
2592 
2593 	if (genpd->has_provider) {
2594 		genpd_unlock(genpd);
2595 		pr_err("Provider present, unable to remove %s\n", dev_name(&genpd->dev));
2596 		return -EBUSY;
2597 	}
2598 
2599 	if (!list_empty(&genpd->parent_links) || genpd->device_count) {
2600 		genpd_unlock(genpd);
2601 		pr_err("%s: unable to remove %s\n", __func__, dev_name(&genpd->dev));
2602 		return -EBUSY;
2603 	}
2604 
2605 	list_for_each_entry_safe(link, l, &genpd->child_links, child_node) {
2606 		list_del(&link->parent_node);
2607 		list_del(&link->child_node);
2608 		kfree(link);
2609 	}
2610 
2611 	list_del(&genpd->gpd_list_node);
2612 	genpd_unlock(genpd);
2613 	genpd_debug_remove(genpd);
2614 	cancel_work_sync(&genpd->power_off_work);
2615 	genpd_free_data(genpd);
2616 
2617 	pr_debug("%s: removed %s\n", __func__, dev_name(&genpd->dev));
2618 
2619 	return 0;
2620 }
2621 
2622 /**
2623  * pm_genpd_remove - Remove a generic I/O PM domain
2624  * @genpd: Pointer to PM domain that is to be removed.
2625  *
2626  * To remove the PM domain, this function:
2627  *  - Removes the PM domain as a subdomain to any parent domains,
2628  *    if it was added.
2629  *  - Removes the PM domain from the list of registered PM domains.
2630  *
2631  * The PM domain will only be removed, if the associated provider has
2632  * been removed, it is not a parent to any other PM domain and has no
2633  * devices associated with it.
2634  */
2635 int pm_genpd_remove(struct generic_pm_domain *genpd)
2636 {
2637 	int ret;
2638 
2639 	mutex_lock(&gpd_list_lock);
2640 	ret = genpd_remove(genpd);
2641 	mutex_unlock(&gpd_list_lock);
2642 
2643 	return ret;
2644 }
2645 EXPORT_SYMBOL_GPL(pm_genpd_remove);
2646 
2647 #ifdef CONFIG_PM_GENERIC_DOMAINS_OF
2648 
2649 /*
2650  * Device Tree based PM domain providers.
2651  *
2652  * The code below implements generic device tree based PM domain providers that
2653  * bind device tree nodes with generic PM domains registered in the system.
2654  *
2655  * Any driver that registers generic PM domains and needs to support binding of
2656  * devices to these domains is supposed to register a PM domain provider, which
2657  * maps a PM domain specifier retrieved from the device tree to a PM domain.
2658  *
2659  * Two simple mapping functions have been provided for convenience:
2660  *  - genpd_xlate_simple() for 1:1 device tree node to PM domain mapping.
2661  *  - genpd_xlate_onecell() for mapping of multiple PM domains per node by
2662  *    index.
2663  */
2664 
2665 /**
2666  * struct of_genpd_provider - PM domain provider registration structure
2667  * @link: Entry in global list of PM domain providers
2668  * @node: Pointer to device tree node of PM domain provider
2669  * @xlate: Provider-specific xlate callback mapping a set of specifier cells
2670  *         into a PM domain.
2671  * @data: context pointer to be passed into @xlate callback
2672  */
2673 struct of_genpd_provider {
2674 	struct list_head link;
2675 	struct device_node *node;
2676 	genpd_xlate_t xlate;
2677 	void *data;
2678 };
2679 
2680 /* List of registered PM domain providers. */
2681 static LIST_HEAD(of_genpd_providers);
2682 /* Mutex to protect the list above. */
2683 static DEFINE_MUTEX(of_genpd_mutex);
2684 
2685 /* The parent for genpd_provider devices. */
2686 static struct device *genpd_provider_bus;
2687 
2688 /* Used to prevent registering devices before the bus. */
2689 static bool genpd_bus_registered;
2690 
2691 /**
2692  * genpd_xlate_simple() - Xlate function for direct node-domain mapping
2693  * @genpdspec: OF phandle args to map into a PM domain
2694  * @data: xlate function private data - pointer to struct generic_pm_domain
2695  *
2696  * This is a generic xlate function that can be used to model PM domains that
2697  * have their own device tree nodes. The private data of xlate function needs
2698  * to be a valid pointer to struct generic_pm_domain.
2699  */
2700 static struct generic_pm_domain *genpd_xlate_simple(
2701 					const struct of_phandle_args *genpdspec,
2702 					void *data)
2703 {
2704 	return data;
2705 }
2706 
2707 /**
2708  * genpd_xlate_onecell() - Xlate function using a single index.
2709  * @genpdspec: OF phandle args to map into a PM domain
2710  * @data: xlate function private data - pointer to struct genpd_onecell_data
2711  *
2712  * This is a generic xlate function that can be used to model simple PM domain
2713  * controllers that have one device tree node and provide multiple PM domains.
2714  * A single cell is used as an index into an array of PM domains specified in
2715  * the genpd_onecell_data struct when registering the provider.
2716  */
2717 static struct generic_pm_domain *genpd_xlate_onecell(
2718 					const struct of_phandle_args *genpdspec,
2719 					void *data)
2720 {
2721 	struct genpd_onecell_data *genpd_data = data;
2722 	unsigned int idx = genpdspec->args[0];
2723 
2724 	if (genpdspec->args_count != 1)
2725 		return ERR_PTR(-EINVAL);
2726 
2727 	if (idx >= genpd_data->num_domains) {
2728 		pr_err("%s: invalid domain index %u\n", __func__, idx);
2729 		return ERR_PTR(-EINVAL);
2730 	}
2731 
2732 	if (!genpd_data->domains[idx])
2733 		return ERR_PTR(-ENOENT);
2734 
2735 	return genpd_data->domains[idx];
2736 }
2737 
2738 /**
2739  * genpd_add_provider() - Register a PM domain provider for a node
2740  * @np: Device node pointer associated with the PM domain provider.
2741  * @xlate: Callback for decoding PM domain from phandle arguments.
2742  * @data: Context pointer for @xlate callback.
2743  */
2744 static int genpd_add_provider(struct device_node *np, genpd_xlate_t xlate,
2745 			      void *data)
2746 {
2747 	struct of_genpd_provider *cp;
2748 
2749 	cp = kzalloc_obj(*cp);
2750 	if (!cp)
2751 		return -ENOMEM;
2752 
2753 	cp->node = of_node_get(np);
2754 	cp->data = data;
2755 	cp->xlate = xlate;
2756 	fwnode_dev_initialized(of_fwnode_handle(np), true);
2757 
2758 	mutex_lock(&of_genpd_mutex);
2759 	list_add(&cp->link, &of_genpd_providers);
2760 	mutex_unlock(&of_genpd_mutex);
2761 	pr_debug("Added domain provider from %pOF\n", np);
2762 
2763 	return 0;
2764 }
2765 
2766 static bool genpd_present(const struct generic_pm_domain *genpd)
2767 {
2768 	bool ret = false;
2769 	const struct generic_pm_domain *gpd;
2770 
2771 	mutex_lock(&gpd_list_lock);
2772 	list_for_each_entry(gpd, &gpd_list, gpd_list_node) {
2773 		if (gpd == genpd) {
2774 			ret = true;
2775 			break;
2776 		}
2777 	}
2778 	mutex_unlock(&gpd_list_lock);
2779 
2780 	return ret;
2781 }
2782 
2783 static void genpd_sync_state(struct device *dev)
2784 {
2785 	return of_genpd_sync_state(dev->of_node);
2786 }
2787 
2788 /**
2789  * of_genpd_add_provider_simple() - Register a simple PM domain provider
2790  * @np: Device node pointer associated with the PM domain provider.
2791  * @genpd: Pointer to PM domain associated with the PM domain provider.
2792  */
2793 int of_genpd_add_provider_simple(struct device_node *np,
2794 				 struct generic_pm_domain *genpd)
2795 {
2796 	struct fwnode_handle *fwnode;
2797 	struct device *dev;
2798 	int ret;
2799 
2800 	if (!np || !genpd)
2801 		return -EINVAL;
2802 
2803 	if (!genpd_bus_registered)
2804 		return -ENODEV;
2805 
2806 	if (!genpd_present(genpd))
2807 		return -EINVAL;
2808 
2809 	genpd->dev.parent = genpd_provider_bus;
2810 	genpd->dev.of_node = np;
2811 
2812 	fwnode = of_fwnode_handle(np);
2813 	dev = get_dev_from_fwnode(fwnode);
2814 	if (!dev && !genpd_is_no_sync_state(genpd)) {
2815 		genpd->sync_state = GENPD_SYNC_STATE_SIMPLE;
2816 		device_set_node(&genpd->dev, fwnode);
2817 	} else {
2818 		dev_set_drv_sync_state(dev, genpd_sync_state);
2819 	}
2820 
2821 	put_device(dev);
2822 
2823 	ret = device_add(&genpd->dev);
2824 	if (ret)
2825 		return ret;
2826 
2827 	/* Parse genpd OPP table */
2828 	if (!genpd_is_opp_table_fw(genpd) && genpd->set_performance_state) {
2829 		ret = dev_pm_opp_of_add_table(&genpd->dev);
2830 		if (ret) {
2831 			dev_err_probe(&genpd->dev, ret, "Failed to add OPP table\n");
2832 			goto err_del;
2833 		}
2834 
2835 		/*
2836 		 * Save table for faster processing while setting performance
2837 		 * state.
2838 		 */
2839 		genpd->opp_table = dev_pm_opp_get_opp_table(&genpd->dev);
2840 		WARN_ON(IS_ERR(genpd->opp_table));
2841 	}
2842 
2843 	ret = genpd_add_provider(np, genpd_xlate_simple, genpd);
2844 	if (ret)
2845 		goto err_opp;
2846 
2847 	genpd->provider = fwnode;
2848 	genpd->has_provider = true;
2849 
2850 	return 0;
2851 
2852 err_opp:
2853 	if (genpd->opp_table) {
2854 		dev_pm_opp_put_opp_table(genpd->opp_table);
2855 		dev_pm_opp_of_remove_table(&genpd->dev);
2856 	}
2857 err_del:
2858 	device_del(&genpd->dev);
2859 	return ret;
2860 }
2861 EXPORT_SYMBOL_GPL(of_genpd_add_provider_simple);
2862 
2863 /**
2864  * of_genpd_add_provider_onecell() - Register a onecell PM domain provider
2865  * @np: Device node pointer associated with the PM domain provider.
2866  * @data: Pointer to the data associated with the PM domain provider.
2867  */
2868 int of_genpd_add_provider_onecell(struct device_node *np,
2869 				  struct genpd_onecell_data *data)
2870 {
2871 	struct generic_pm_domain *genpd;
2872 	struct fwnode_handle *fwnode;
2873 	struct device *dev;
2874 	unsigned int i;
2875 	int ret = -EINVAL;
2876 	bool sync_state = false;
2877 
2878 	if (!np || !data)
2879 		return -EINVAL;
2880 
2881 	if (!genpd_bus_registered)
2882 		return -ENODEV;
2883 
2884 	if (!data->xlate)
2885 		data->xlate = genpd_xlate_onecell;
2886 
2887 	fwnode = of_fwnode_handle(np);
2888 	dev = get_dev_from_fwnode(fwnode);
2889 	if (!dev)
2890 		sync_state = true;
2891 	else
2892 		dev_set_drv_sync_state(dev, genpd_sync_state);
2893 
2894 	put_device(dev);
2895 
2896 	for (i = 0; i < data->num_domains; i++) {
2897 		genpd = data->domains[i];
2898 
2899 		if (!genpd)
2900 			continue;
2901 		if (!genpd_present(genpd))
2902 			goto error;
2903 
2904 		genpd->dev.parent = genpd_provider_bus;
2905 		genpd->dev.of_node = np;
2906 
2907 		if (sync_state && !genpd_is_no_sync_state(genpd)) {
2908 			genpd->sync_state = GENPD_SYNC_STATE_ONECELL;
2909 			device_set_node(&genpd->dev, fwnode);
2910 			sync_state = false;
2911 		}
2912 
2913 		ret = device_add(&genpd->dev);
2914 		if (ret)
2915 			goto error;
2916 
2917 		/* Parse genpd OPP table */
2918 		if (!genpd_is_opp_table_fw(genpd) && genpd->set_performance_state) {
2919 			ret = dev_pm_opp_of_add_table_indexed(&genpd->dev, i);
2920 			if (ret) {
2921 				dev_err_probe(&genpd->dev, ret,
2922 					      "Failed to add OPP table for index %d\n", i);
2923 				device_del(&genpd->dev);
2924 				goto error;
2925 			}
2926 
2927 			/*
2928 			 * Save table for faster processing while setting
2929 			 * performance state.
2930 			 */
2931 			genpd->opp_table = dev_pm_opp_get_opp_table(&genpd->dev);
2932 			WARN_ON(IS_ERR(genpd->opp_table));
2933 		}
2934 
2935 		genpd->provider = fwnode;
2936 		genpd->has_provider = true;
2937 	}
2938 
2939 	ret = genpd_add_provider(np, data->xlate, data);
2940 	if (ret < 0)
2941 		goto error;
2942 
2943 	return 0;
2944 
2945 error:
2946 	while (i--) {
2947 		genpd = data->domains[i];
2948 
2949 		if (!genpd)
2950 			continue;
2951 
2952 		genpd->provider = NULL;
2953 		genpd->has_provider = false;
2954 
2955 		if (genpd->opp_table) {
2956 			dev_pm_opp_put_opp_table(genpd->opp_table);
2957 			dev_pm_opp_of_remove_table(&genpd->dev);
2958 		}
2959 
2960 		device_del(&genpd->dev);
2961 	}
2962 
2963 	return ret;
2964 }
2965 EXPORT_SYMBOL_GPL(of_genpd_add_provider_onecell);
2966 
2967 /**
2968  * of_genpd_del_provider() - Remove a previously registered PM domain provider
2969  * @np: Device node pointer associated with the PM domain provider
2970  */
2971 void of_genpd_del_provider(struct device_node *np)
2972 {
2973 	struct of_genpd_provider *cp, *tmp;
2974 	struct generic_pm_domain *gpd;
2975 
2976 	mutex_lock(&gpd_list_lock);
2977 	mutex_lock(&of_genpd_mutex);
2978 	list_for_each_entry_safe(cp, tmp, &of_genpd_providers, link) {
2979 		if (cp->node == np) {
2980 			/*
2981 			 * For each PM domain associated with the
2982 			 * provider, set the 'has_provider' to false
2983 			 * so that the PM domain can be safely removed.
2984 			 */
2985 			list_for_each_entry(gpd, &gpd_list, gpd_list_node) {
2986 				if (gpd->provider == of_fwnode_handle(np)) {
2987 					gpd->has_provider = false;
2988 
2989 					if (gpd->opp_table) {
2990 						dev_pm_opp_put_opp_table(gpd->opp_table);
2991 						dev_pm_opp_of_remove_table(&gpd->dev);
2992 					}
2993 
2994 					device_del(&gpd->dev);
2995 				}
2996 			}
2997 
2998 			fwnode_dev_initialized(of_fwnode_handle(cp->node), false);
2999 			list_del(&cp->link);
3000 			of_node_put(cp->node);
3001 			kfree(cp);
3002 			break;
3003 		}
3004 	}
3005 	mutex_unlock(&of_genpd_mutex);
3006 	mutex_unlock(&gpd_list_lock);
3007 }
3008 EXPORT_SYMBOL_GPL(of_genpd_del_provider);
3009 
3010 /**
3011  * genpd_get_from_provider() - Look-up PM domain
3012  * @genpdspec: OF phandle args to use for look-up
3013  *
3014  * Looks for a PM domain provider under the node specified by @genpdspec and if
3015  * found, uses xlate function of the provider to map phandle args to a PM
3016  * domain.
3017  *
3018  * Returns a valid pointer to struct generic_pm_domain on success or ERR_PTR()
3019  * on failure.
3020  */
3021 static struct generic_pm_domain *genpd_get_from_provider(
3022 					const struct of_phandle_args *genpdspec)
3023 {
3024 	struct generic_pm_domain *genpd = ERR_PTR(-ENOENT);
3025 	struct of_genpd_provider *provider;
3026 
3027 	if (!genpdspec)
3028 		return ERR_PTR(-EINVAL);
3029 
3030 	mutex_lock(&of_genpd_mutex);
3031 
3032 	/* Check if we have such a provider in our array */
3033 	list_for_each_entry(provider, &of_genpd_providers, link) {
3034 		if (provider->node == genpdspec->np)
3035 			genpd = provider->xlate(genpdspec, provider->data);
3036 		if (!IS_ERR(genpd))
3037 			break;
3038 	}
3039 
3040 	mutex_unlock(&of_genpd_mutex);
3041 
3042 	return genpd;
3043 }
3044 
3045 /**
3046  * of_genpd_add_child_ids() - Parse power-domains-child-ids property
3047  * @np: Device node pointer associated with the PM domain provider.
3048  * @data: Pointer to the onecell data associated with the PM domain provider.
3049  *
3050  * Parse the power-domains and power-domains-child-ids properties to establish
3051  * parent-child relationships for PM domains. The power-domains property lists
3052  * parent domains, and power-domains-child-ids lists which child domain IDs
3053  * should be associated with each parent.
3054  *
3055  * Uses "all or nothing" semantics: either all relationships are established
3056  * successfully, or none are (any partially-added relationships are unwound
3057  * on error).
3058  *
3059  * Returns the number of parent-child relationships established on success,
3060  * 0 if the properties don't exist, or a negative error code on failure.
3061  */
3062 int of_genpd_add_child_ids(struct device_node *np,
3063 			   struct genpd_onecell_data *data)
3064 {
3065 	struct of_phandle_args parent_args;
3066 	struct generic_pm_domain *parent_genpd, *child_genpd;
3067 	struct generic_pm_domain **pairs; /* pairs[2*i]=parent, pairs[2*i+1]=child */
3068 	u32 child_id;
3069 	int i, ret, count, child_count, added = 0;
3070 
3071 	/* Check if both properties exist */
3072 	count = of_count_phandle_with_args(np, "power-domains", "#power-domain-cells");
3073 	if (count <= 0)
3074 		return 0;
3075 
3076 	child_count = of_property_count_u32_elems(np, "power-domains-child-ids");
3077 	if (child_count < 0)
3078 		return 0;
3079 	if (child_count != count)
3080 		return -EINVAL;
3081 
3082 	/* Allocate tracking array for error unwind (parent/child pairs) */
3083 	pairs = kmalloc_objs(*pairs, count * 2);
3084 	if (!pairs)
3085 		return -ENOMEM;
3086 
3087 	for (i = 0; i < count; i++) {
3088 		ret = of_property_read_u32_index(np, "power-domains-child-ids",
3089 						 i, &child_id);
3090 		if (ret)
3091 			goto err_unwind;
3092 
3093 		/* Validate child ID is within bounds */
3094 		if (child_id >= data->num_domains) {
3095 			pr_err("Child ID %u out of bounds (max %u) for %pOF\n",
3096 			       child_id, data->num_domains - 1, np);
3097 			ret = -EINVAL;
3098 			goto err_unwind;
3099 		}
3100 
3101 		/* Get the child domain */
3102 		child_genpd = data->domains[child_id];
3103 		if (!child_genpd) {
3104 			pr_err("Child domain %u is NULL for %pOF\n", child_id, np);
3105 			ret = -EINVAL;
3106 			goto err_unwind;
3107 		}
3108 
3109 		ret = of_parse_phandle_with_args(np, "power-domains",
3110 						 "#power-domain-cells", i,
3111 						 &parent_args);
3112 		if (ret)
3113 			goto err_unwind;
3114 
3115 		/* Get the parent domain */
3116 		parent_genpd = genpd_get_from_provider(&parent_args);
3117 		of_node_put(parent_args.np);
3118 		if (IS_ERR(parent_genpd)) {
3119 			pr_err("Failed to get parent domain for %pOF: %ld\n",
3120 			       np, PTR_ERR(parent_genpd));
3121 			ret = PTR_ERR(parent_genpd);
3122 			goto err_unwind;
3123 		}
3124 
3125 		/* Establish parent-child relationship */
3126 		ret = pm_genpd_add_subdomain(parent_genpd, child_genpd);
3127 		if (ret) {
3128 			pr_err("Failed to add child domain %u to parent in %pOF: %d\n",
3129 			       child_id, np, ret);
3130 			goto err_unwind;
3131 		}
3132 
3133 		/* Track for potential unwind */
3134 		pairs[2 * added] = parent_genpd;
3135 		pairs[2 * added + 1] = child_genpd;
3136 		added++;
3137 
3138 		pr_debug("Added child domain %u (%s) to parent %s for %pOF\n",
3139 			 child_id, child_genpd->name, parent_genpd->name, np);
3140 	}
3141 
3142 	kfree(pairs);
3143 	return count;
3144 
3145 err_unwind:
3146 	/* Reverse all previously established relationships */
3147 	while (added-- > 0)
3148 		pm_genpd_remove_subdomain(pairs[2 * added], pairs[2 * added + 1]);
3149 	kfree(pairs);
3150 	return ret;
3151 }
3152 EXPORT_SYMBOL_GPL(of_genpd_add_child_ids);
3153 
3154 /**
3155  * of_genpd_remove_child_ids() - Remove parent-child PM domain relationships
3156  * @np: Device node pointer associated with the PM domain provider.
3157  * @data: Pointer to the onecell data associated with the PM domain provider.
3158  *
3159  * Reverses the effect of of_genpd_add_child_ids() by parsing the same
3160  * power-domains and power-domains-child-ids properties and calling
3161  * pm_genpd_remove_subdomain() for each established relationship.
3162  *
3163  * Returns 0 on success, -ENOENT if properties don't exist, or negative error
3164  * code on failure.
3165  */
3166 int of_genpd_remove_child_ids(struct device_node *np,
3167 			   struct genpd_onecell_data *data)
3168 {
3169 	struct of_phandle_args parent_args;
3170 	struct generic_pm_domain *parent_genpd, *child_genpd;
3171 	u32 child_id;
3172 	int i, ret, count, child_count;
3173 
3174 	/* Check if both properties exist */
3175 	count = of_count_phandle_with_args(np, "power-domains", "#power-domain-cells");
3176 	if (count <= 0)
3177 		return -ENOENT;
3178 
3179 	child_count = of_property_count_u32_elems(np, "power-domains-child-ids");
3180 	if (child_count < 0)
3181 		return -ENOENT;
3182 	if (child_count != count)
3183 		return -EINVAL;
3184 
3185 	for (i = 0; i < count; i++) {
3186 		if (of_property_read_u32_index(np, "power-domains-child-ids",
3187 					       i, &child_id))
3188 			continue;
3189 
3190 		if (child_id >= data->num_domains || !data->domains[child_id])
3191 			continue;
3192 
3193 		ret = of_parse_phandle_with_args(np, "power-domains",
3194 						 "#power-domain-cells", i,
3195 						 &parent_args);
3196 		if (ret)
3197 			continue;
3198 
3199 		parent_genpd = genpd_get_from_provider(&parent_args);
3200 		of_node_put(parent_args.np);
3201 		if (IS_ERR(parent_genpd))
3202 			continue;
3203 
3204 		child_genpd = data->domains[child_id];
3205 		pm_genpd_remove_subdomain(parent_genpd, child_genpd);
3206 	}
3207 
3208 	return 0;
3209 }
3210 EXPORT_SYMBOL_GPL(of_genpd_remove_child_ids);
3211 
3212 /**
3213  * of_genpd_add_device() - Add a device to an I/O PM domain
3214  * @genpdspec: OF phandle args to use for look-up PM domain
3215  * @dev: Device to be added.
3216  *
3217  * Looks-up an I/O PM domain based upon phandle args provided and adds
3218  * the device to the PM domain. Returns a negative error code on failure.
3219  */
3220 int of_genpd_add_device(const struct of_phandle_args *genpdspec, struct device *dev)
3221 {
3222 	struct generic_pm_domain *genpd;
3223 	int ret;
3224 
3225 	if (!dev)
3226 		return -EINVAL;
3227 
3228 	mutex_lock(&gpd_list_lock);
3229 
3230 	genpd = genpd_get_from_provider(genpdspec);
3231 	if (IS_ERR(genpd)) {
3232 		ret = PTR_ERR(genpd);
3233 		goto out;
3234 	}
3235 
3236 	ret = genpd_add_device(genpd, dev, dev);
3237 
3238 out:
3239 	mutex_unlock(&gpd_list_lock);
3240 
3241 	return ret;
3242 }
3243 EXPORT_SYMBOL_GPL(of_genpd_add_device);
3244 
3245 /**
3246  * of_genpd_add_subdomain - Add a subdomain to an I/O PM domain.
3247  * @parent_spec: OF phandle args to use for parent PM domain look-up
3248  * @subdomain_spec: OF phandle args to use for subdomain look-up
3249  *
3250  * Looks-up a parent PM domain and subdomain based upon phandle args
3251  * provided and adds the subdomain to the parent PM domain. Returns a
3252  * negative error code on failure.
3253  */
3254 int of_genpd_add_subdomain(const struct of_phandle_args *parent_spec,
3255 			   const struct of_phandle_args *subdomain_spec)
3256 {
3257 	struct generic_pm_domain *parent, *subdomain;
3258 	int ret;
3259 
3260 	mutex_lock(&gpd_list_lock);
3261 
3262 	parent = genpd_get_from_provider(parent_spec);
3263 	if (IS_ERR(parent)) {
3264 		ret = PTR_ERR(parent);
3265 		goto out;
3266 	}
3267 
3268 	subdomain = genpd_get_from_provider(subdomain_spec);
3269 	if (IS_ERR(subdomain)) {
3270 		ret = PTR_ERR(subdomain);
3271 		goto out;
3272 	}
3273 
3274 	ret = genpd_add_subdomain(parent, subdomain);
3275 
3276 out:
3277 	mutex_unlock(&gpd_list_lock);
3278 
3279 	return ret == -ENOENT ? -EPROBE_DEFER : ret;
3280 }
3281 EXPORT_SYMBOL_GPL(of_genpd_add_subdomain);
3282 
3283 /**
3284  * of_genpd_remove_subdomain - Remove a subdomain from an I/O PM domain.
3285  * @parent_spec: OF phandle args to use for parent PM domain look-up
3286  * @subdomain_spec: OF phandle args to use for subdomain look-up
3287  *
3288  * Looks-up a parent PM domain and subdomain based upon phandle args
3289  * provided and removes the subdomain from the parent PM domain. Returns a
3290  * negative error code on failure.
3291  */
3292 int of_genpd_remove_subdomain(const struct of_phandle_args *parent_spec,
3293 			      const struct of_phandle_args *subdomain_spec)
3294 {
3295 	struct generic_pm_domain *parent, *subdomain;
3296 	int ret;
3297 
3298 	mutex_lock(&gpd_list_lock);
3299 
3300 	parent = genpd_get_from_provider(parent_spec);
3301 	if (IS_ERR(parent)) {
3302 		ret = PTR_ERR(parent);
3303 		goto out;
3304 	}
3305 
3306 	subdomain = genpd_get_from_provider(subdomain_spec);
3307 	if (IS_ERR(subdomain)) {
3308 		ret = PTR_ERR(subdomain);
3309 		goto out;
3310 	}
3311 
3312 	ret = pm_genpd_remove_subdomain(parent, subdomain);
3313 
3314 out:
3315 	mutex_unlock(&gpd_list_lock);
3316 
3317 	return ret;
3318 }
3319 EXPORT_SYMBOL_GPL(of_genpd_remove_subdomain);
3320 
3321 /**
3322  * of_genpd_remove_last - Remove the last PM domain registered for a provider
3323  * @np: Pointer to device node associated with provider
3324  *
3325  * Find the last PM domain that was added by a particular provider and
3326  * remove this PM domain from the list of PM domains. The provider is
3327  * identified by the 'provider' device structure that is passed. The PM
3328  * domain will only be removed, if the provider associated with domain
3329  * has been removed.
3330  *
3331  * Returns a valid pointer to struct generic_pm_domain on success or
3332  * ERR_PTR() on failure.
3333  */
3334 struct generic_pm_domain *of_genpd_remove_last(struct device_node *np)
3335 {
3336 	struct generic_pm_domain *gpd, *tmp, *genpd = ERR_PTR(-ENOENT);
3337 	int ret;
3338 
3339 	if (IS_ERR_OR_NULL(np))
3340 		return ERR_PTR(-EINVAL);
3341 
3342 	mutex_lock(&gpd_list_lock);
3343 	list_for_each_entry_safe(gpd, tmp, &gpd_list, gpd_list_node) {
3344 		if (gpd->provider == of_fwnode_handle(np)) {
3345 			ret = genpd_remove(gpd);
3346 			genpd = ret ? ERR_PTR(ret) : gpd;
3347 			break;
3348 		}
3349 	}
3350 	mutex_unlock(&gpd_list_lock);
3351 
3352 	return genpd;
3353 }
3354 EXPORT_SYMBOL_GPL(of_genpd_remove_last);
3355 
3356 static void genpd_release_dev(struct device *dev)
3357 {
3358 	of_node_put(dev->of_node);
3359 	kfree(dev);
3360 }
3361 
3362 static const struct bus_type genpd_bus_type = {
3363 	.name		= "genpd",
3364 };
3365 
3366 /**
3367  * genpd_dev_pm_detach - Detach a device from its PM domain.
3368  * @dev: Device to detach.
3369  * @power_off: Currently not used
3370  *
3371  * Try to locate a corresponding generic PM domain, which the device was
3372  * attached to previously. If such is found, the device is detached from it.
3373  */
3374 static void genpd_dev_pm_detach(struct device *dev, bool power_off)
3375 {
3376 	struct generic_pm_domain *pd;
3377 	bool is_virt_dev;
3378 	unsigned int i;
3379 	int ret = 0;
3380 
3381 	pd = dev_to_genpd(dev);
3382 	if (IS_ERR(pd))
3383 		return;
3384 
3385 	dev_dbg(dev, "removing from PM domain %s\n", pd->name);
3386 
3387 	/* Check if the device was created by genpd at attach. */
3388 	is_virt_dev = dev->bus == &genpd_bus_type;
3389 
3390 	/* Disable runtime PM if we enabled it at attach. */
3391 	if (is_virt_dev)
3392 		pm_runtime_disable(dev);
3393 
3394 	/* Drop the default performance state */
3395 	if (dev_gpd_data(dev)->default_pstate) {
3396 		dev_pm_genpd_set_performance_state(dev, 0);
3397 		dev_gpd_data(dev)->default_pstate = 0;
3398 	}
3399 
3400 	for (i = 1; i < GENPD_RETRY_MAX_MS; i <<= 1) {
3401 		ret = genpd_remove_device(pd, dev);
3402 		if (ret != -EAGAIN)
3403 			break;
3404 
3405 		mdelay(i);
3406 		cond_resched();
3407 	}
3408 
3409 	if (ret < 0) {
3410 		dev_err(dev, "failed to remove from PM domain %s: %d",
3411 			pd->name, ret);
3412 		return;
3413 	}
3414 
3415 	/* Check if PM domain can be powered off after removing this device. */
3416 	genpd_queue_power_off_work(pd);
3417 
3418 	/* Unregister the device if it was created by genpd. */
3419 	if (is_virt_dev)
3420 		device_unregister(dev);
3421 }
3422 
3423 static void genpd_dev_pm_sync(struct device *dev)
3424 {
3425 	struct generic_pm_domain *pd;
3426 
3427 	pd = dev_to_genpd(dev);
3428 	if (IS_ERR(pd))
3429 		return;
3430 
3431 	genpd_queue_power_off_work(pd);
3432 }
3433 
3434 static int genpd_set_required_opp_dev(struct device *dev,
3435 				      struct device *base_dev)
3436 {
3437 	struct dev_pm_opp_config config = {
3438 		.required_dev = dev,
3439 	};
3440 	int ret;
3441 
3442 	/* Limit support to non-providers for now. */
3443 	if (of_property_present(base_dev->of_node, "#power-domain-cells"))
3444 		return 0;
3445 
3446 	if (!dev_pm_opp_of_has_required_opp(base_dev))
3447 		return 0;
3448 
3449 	ret = dev_pm_opp_set_config(base_dev, &config);
3450 	if (ret < 0)
3451 		return ret;
3452 
3453 	dev_gpd_data(dev)->opp_token = ret;
3454 	return 0;
3455 }
3456 
3457 static int genpd_set_required_opp(struct device *dev, unsigned int index)
3458 {
3459 	int ret, pstate;
3460 
3461 	/* Set the default performance state */
3462 	pstate = of_get_required_opp_performance_state(dev->of_node, index);
3463 	if (pstate < 0 && pstate != -ENODEV && pstate != -EOPNOTSUPP) {
3464 		ret = pstate;
3465 		goto err;
3466 	} else if (pstate > 0) {
3467 		ret = dev_pm_genpd_set_performance_state(dev, pstate);
3468 		if (ret)
3469 			goto err;
3470 		dev_gpd_data(dev)->default_pstate = pstate;
3471 	}
3472 
3473 	return 0;
3474 err:
3475 	dev_err(dev, "failed to set required performance state for power-domain %s: %d\n",
3476 		dev_to_genpd(dev)->name, ret);
3477 	return ret;
3478 }
3479 
3480 static int __genpd_dev_pm_attach(struct device *dev, struct device *base_dev,
3481 				 unsigned int index, unsigned int num_domains,
3482 				 bool power_on)
3483 {
3484 	struct of_phandle_args pd_args;
3485 	struct generic_pm_domain *pd;
3486 	int ret;
3487 
3488 	ret = of_parse_phandle_with_args(dev->of_node, "power-domains",
3489 				"#power-domain-cells", index, &pd_args);
3490 	if (ret < 0)
3491 		return ret;
3492 
3493 	mutex_lock(&gpd_list_lock);
3494 	pd = genpd_get_from_provider(&pd_args);
3495 	of_node_put(pd_args.np);
3496 	if (IS_ERR(pd)) {
3497 		mutex_unlock(&gpd_list_lock);
3498 		dev_dbg(dev, "%s() failed to find PM domain: %ld\n",
3499 			__func__, PTR_ERR(pd));
3500 		return driver_deferred_probe_check_state(base_dev);
3501 	}
3502 
3503 	dev_dbg(dev, "adding to PM domain %s\n", pd->name);
3504 
3505 	ret = genpd_add_device(pd, dev, base_dev);
3506 	mutex_unlock(&gpd_list_lock);
3507 
3508 	if (ret < 0)
3509 		return dev_err_probe(dev, ret, "failed to add to PM domain %s\n", pd->name);
3510 
3511 	dev->pm_domain->detach = genpd_dev_pm_detach;
3512 	dev->pm_domain->sync = genpd_dev_pm_sync;
3513 
3514 	/*
3515 	 * For a single PM domain the index of the required OPP must be zero, so
3516 	 * let's try to assign a required dev in that case. In the multiple PM
3517 	 * domains case, we need platform code to specify the index.
3518 	 */
3519 	if (num_domains == 1) {
3520 		ret = genpd_set_required_opp_dev(dev, base_dev);
3521 		if (ret)
3522 			goto err;
3523 	}
3524 
3525 	ret = genpd_set_required_opp(dev, index);
3526 	if (ret)
3527 		goto err;
3528 
3529 	if (power_on) {
3530 		genpd_lock(pd);
3531 		ret = genpd_power_on(pd, dev, 0);
3532 		genpd_unlock(pd);
3533 	}
3534 
3535 	if (ret) {
3536 		/* Drop the default performance state */
3537 		if (dev_gpd_data(dev)->default_pstate) {
3538 			dev_pm_genpd_set_performance_state(dev, 0);
3539 			dev_gpd_data(dev)->default_pstate = 0;
3540 		}
3541 
3542 		genpd_remove_device(pd, dev);
3543 		return -EPROBE_DEFER;
3544 	}
3545 
3546 	return 1;
3547 
3548 err:
3549 	genpd_remove_device(pd, dev);
3550 	return ret;
3551 }
3552 
3553 /**
3554  * genpd_dev_pm_attach - Attach a device to its PM domain using DT.
3555  * @dev: Device to attach.
3556  *
3557  * Parse device's OF node to find a PM domain specifier. If such is found,
3558  * attaches the device to retrieved pm_domain ops.
3559  *
3560  * Returns 1 on successfully attached PM domain, 0 when the device don't need a
3561  * PM domain or when multiple power-domains exists for it, else a negative error
3562  * code. Note that if a power-domain exists for the device, but it cannot be
3563  * found or turned on, then return -EPROBE_DEFER to ensure that the device is
3564  * not probed and to re-try again later.
3565  */
3566 int genpd_dev_pm_attach(struct device *dev)
3567 {
3568 	if (!dev->of_node)
3569 		return 0;
3570 
3571 	/*
3572 	 * Devices with multiple PM domains must be attached separately, as we
3573 	 * can only attach one PM domain per device.
3574 	 */
3575 	if (of_count_phandle_with_args(dev->of_node, "power-domains",
3576 				       "#power-domain-cells") != 1)
3577 		return 0;
3578 
3579 	return __genpd_dev_pm_attach(dev, dev, 0, 1, true);
3580 }
3581 EXPORT_SYMBOL_GPL(genpd_dev_pm_attach);
3582 
3583 /**
3584  * genpd_dev_pm_attach_by_id - Associate a device with one of its PM domains.
3585  * @dev: The device used to lookup the PM domain.
3586  * @index: The index of the PM domain.
3587  *
3588  * Parse device's OF node to find a PM domain specifier at the provided @index.
3589  * If such is found, creates a virtual device and attaches it to the retrieved
3590  * pm_domain ops. To deal with detaching of the virtual device, the ->detach()
3591  * callback in the struct dev_pm_domain are assigned to genpd_dev_pm_detach().
3592  *
3593  * Returns the created virtual device if successfully attached PM domain, NULL
3594  * when the device don't need a PM domain, else an ERR_PTR() in case of
3595  * failures. If a power-domain exists for the device, but cannot be found or
3596  * turned on, then ERR_PTR(-EPROBE_DEFER) is returned to ensure that the device
3597  * is not probed and to re-try again later.
3598  */
3599 struct device *genpd_dev_pm_attach_by_id(struct device *dev,
3600 					 unsigned int index)
3601 {
3602 	struct device *virt_dev;
3603 	int num_domains;
3604 	int ret;
3605 
3606 	if (!dev->of_node)
3607 		return NULL;
3608 
3609 	/* Verify that the index is within a valid range. */
3610 	num_domains = of_count_phandle_with_args(dev->of_node, "power-domains",
3611 						 "#power-domain-cells");
3612 	if (num_domains < 0 || index >= num_domains)
3613 		return NULL;
3614 
3615 	if (!genpd_bus_registered)
3616 		return ERR_PTR(-ENODEV);
3617 
3618 	/* Allocate and register device on the genpd bus. */
3619 	virt_dev = kzalloc_obj(*virt_dev);
3620 	if (!virt_dev)
3621 		return ERR_PTR(-ENOMEM);
3622 
3623 	dev_set_name(virt_dev, "genpd:%u:%s", index, dev_name(dev));
3624 	virt_dev->bus = &genpd_bus_type;
3625 	virt_dev->release = genpd_release_dev;
3626 	virt_dev->of_node = of_node_get(dev->of_node);
3627 
3628 	ret = device_register(virt_dev);
3629 	if (ret) {
3630 		put_device(virt_dev);
3631 		return ERR_PTR(ret);
3632 	}
3633 
3634 	/* Try to attach the device to the PM domain at the specified index. */
3635 	ret = __genpd_dev_pm_attach(virt_dev, dev, index, num_domains, false);
3636 	if (ret < 1) {
3637 		device_unregister(virt_dev);
3638 		return ret ? ERR_PTR(ret) : NULL;
3639 	}
3640 
3641 	pm_runtime_enable(virt_dev);
3642 	genpd_queue_power_off_work(dev_to_genpd(virt_dev));
3643 
3644 	return virt_dev;
3645 }
3646 EXPORT_SYMBOL_GPL(genpd_dev_pm_attach_by_id);
3647 
3648 /**
3649  * genpd_dev_pm_attach_by_name - Associate a device with one of its PM domains.
3650  * @dev: The device used to lookup the PM domain.
3651  * @name: The name of the PM domain.
3652  *
3653  * Parse device's OF node to find a PM domain specifier using the
3654  * power-domain-names DT property. For further description see
3655  * genpd_dev_pm_attach_by_id().
3656  */
3657 struct device *genpd_dev_pm_attach_by_name(struct device *dev, const char *name)
3658 {
3659 	int index;
3660 
3661 	if (!dev->of_node)
3662 		return NULL;
3663 
3664 	index = of_property_match_string(dev->of_node, "power-domain-names",
3665 					 name);
3666 	if (index < 0)
3667 		return NULL;
3668 
3669 	return genpd_dev_pm_attach_by_id(dev, index);
3670 }
3671 
3672 static const struct of_device_id idle_state_match[] = {
3673 	{ .compatible = "domain-idle-state", },
3674 	{ }
3675 };
3676 
3677 static int genpd_parse_state(struct genpd_power_state *genpd_state,
3678 				    struct device_node *state_node)
3679 {
3680 	int err;
3681 	u32 residency;
3682 	u32 entry_latency, exit_latency;
3683 
3684 	err = of_property_read_u32(state_node, "entry-latency-us",
3685 						&entry_latency);
3686 	if (err) {
3687 		pr_debug(" * %pOF missing entry-latency-us property\n",
3688 			 state_node);
3689 		return -EINVAL;
3690 	}
3691 
3692 	err = of_property_read_u32(state_node, "exit-latency-us",
3693 						&exit_latency);
3694 	if (err) {
3695 		pr_debug(" * %pOF missing exit-latency-us property\n",
3696 			 state_node);
3697 		return -EINVAL;
3698 	}
3699 
3700 	err = of_property_read_u32(state_node, "min-residency-us", &residency);
3701 	if (!err)
3702 		genpd_state->residency_ns = 1000LL * residency;
3703 
3704 	err = of_property_read_string(state_node, "idle-state-name",
3705 				      &genpd_state->name);
3706 	if (err)
3707 		genpd_state->name = state_node->name;
3708 
3709 	genpd_state->power_on_latency_ns = 1000LL * exit_latency;
3710 	genpd_state->power_off_latency_ns = 1000LL * entry_latency;
3711 	genpd_state->fwnode = of_fwnode_handle(state_node);
3712 
3713 	return 0;
3714 }
3715 
3716 static int genpd_iterate_idle_states(struct device_node *dn,
3717 				     struct genpd_power_state *states)
3718 {
3719 	int ret;
3720 	struct of_phandle_iterator it;
3721 	struct device_node *np;
3722 	int i = 0;
3723 
3724 	ret = of_count_phandle_with_args(dn, "domain-idle-states", NULL);
3725 	if (ret <= 0)
3726 		return ret == -ENOENT ? 0 : ret;
3727 
3728 	/* Loop over the phandles until all the requested entry is found */
3729 	of_for_each_phandle(&it, ret, dn, "domain-idle-states", NULL, 0) {
3730 		np = it.node;
3731 		if (!of_match_node(idle_state_match, np))
3732 			continue;
3733 
3734 		if (!of_device_is_available(np))
3735 			continue;
3736 
3737 		if (states) {
3738 			ret = genpd_parse_state(&states[i], np);
3739 			if (ret) {
3740 				pr_err("Parsing idle state node %pOF failed with err %d\n",
3741 				       np, ret);
3742 				of_node_put(np);
3743 				return ret;
3744 			}
3745 		}
3746 		i++;
3747 	}
3748 
3749 	return i;
3750 }
3751 
3752 /**
3753  * of_genpd_parse_idle_states: Return array of idle states for the genpd.
3754  *
3755  * @dn: The genpd device node
3756  * @states: The pointer to which the state array will be saved.
3757  * @n: The count of elements in the array returned from this function.
3758  *
3759  * Returns the device states parsed from the OF node. The memory for the states
3760  * is allocated by this function and is the responsibility of the caller to
3761  * free the memory after use. If any or zero compatible domain idle states is
3762  * found it returns 0 and in case of errors, a negative error code is returned.
3763  */
3764 int of_genpd_parse_idle_states(struct device_node *dn,
3765 			struct genpd_power_state **states, int *n)
3766 {
3767 	struct genpd_power_state *st;
3768 	int ret;
3769 
3770 	ret = genpd_iterate_idle_states(dn, NULL);
3771 	if (ret < 0)
3772 		return ret;
3773 
3774 	if (!ret) {
3775 		*states = NULL;
3776 		*n = 0;
3777 		return 0;
3778 	}
3779 
3780 	st = kzalloc_objs(*st, ret);
3781 	if (!st)
3782 		return -ENOMEM;
3783 
3784 	ret = genpd_iterate_idle_states(dn, st);
3785 	if (ret <= 0) {
3786 		kfree(st);
3787 		return ret < 0 ? ret : -EINVAL;
3788 	}
3789 
3790 	*states = st;
3791 	*n = ret;
3792 
3793 	return 0;
3794 }
3795 EXPORT_SYMBOL_GPL(of_genpd_parse_idle_states);
3796 
3797 /**
3798  * of_genpd_sync_state() - A common sync_state function for genpd providers
3799  * @np: The device node the genpd provider is associated with.
3800  *
3801  * The @np that corresponds to a genpd provider may provide one or multiple
3802  * genpds. This function makes use @np to find the genpds that belongs to the
3803  * provider. For each genpd we try a power-off.
3804  */
3805 void of_genpd_sync_state(struct device_node *np)
3806 {
3807 	struct generic_pm_domain *genpd;
3808 
3809 	if (!np)
3810 		return;
3811 
3812 	mutex_lock(&gpd_list_lock);
3813 	list_for_each_entry(genpd, &gpd_list, gpd_list_node) {
3814 		if (genpd->provider == of_fwnode_handle(np)) {
3815 			genpd_lock(genpd);
3816 			genpd->stay_on = false;
3817 			genpd_power_off(genpd, false, 0);
3818 			genpd_unlock(genpd);
3819 		}
3820 	}
3821 	mutex_unlock(&gpd_list_lock);
3822 }
3823 EXPORT_SYMBOL_GPL(of_genpd_sync_state);
3824 
3825 static int genpd_provider_probe(struct device *dev)
3826 {
3827 	return 0;
3828 }
3829 
3830 static void genpd_provider_sync_state(struct device *dev)
3831 {
3832 	struct generic_pm_domain *genpd = container_of(dev, struct generic_pm_domain, dev);
3833 
3834 	switch (genpd->sync_state) {
3835 	case GENPD_SYNC_STATE_OFF:
3836 		break;
3837 
3838 	case GENPD_SYNC_STATE_ONECELL:
3839 		of_genpd_sync_state(dev->of_node);
3840 		break;
3841 
3842 	case GENPD_SYNC_STATE_SIMPLE:
3843 		genpd_lock(genpd);
3844 		genpd->stay_on = false;
3845 		genpd_power_off(genpd, false, 0);
3846 		genpd_unlock(genpd);
3847 		break;
3848 
3849 	default:
3850 		break;
3851 	}
3852 }
3853 
3854 static struct device_driver genpd_provider_drv = {
3855 	.name = "genpd_provider",
3856 	.bus = &genpd_provider_bus_type,
3857 	.probe = genpd_provider_probe,
3858 	.sync_state = genpd_provider_sync_state,
3859 	.suppress_bind_attrs = true,
3860 };
3861 
3862 static int __init genpd_bus_init(void)
3863 {
3864 	int ret;
3865 
3866 	genpd_provider_bus = root_device_register("genpd_provider");
3867 	if (IS_ERR(genpd_provider_bus))
3868 		return PTR_ERR(genpd_provider_bus);
3869 
3870 	ret = bus_register(&genpd_provider_bus_type);
3871 	if (ret)
3872 		goto err_dev;
3873 
3874 	ret = bus_register(&genpd_bus_type);
3875 	if (ret)
3876 		goto err_prov_bus;
3877 
3878 	ret = driver_register(&genpd_provider_drv);
3879 	if (ret)
3880 		goto err_bus;
3881 
3882 	genpd_bus_registered = true;
3883 	return 0;
3884 
3885 err_bus:
3886 	bus_unregister(&genpd_bus_type);
3887 err_prov_bus:
3888 	bus_unregister(&genpd_provider_bus_type);
3889 err_dev:
3890 	root_device_unregister(genpd_provider_bus);
3891 	return ret;
3892 }
3893 core_initcall(genpd_bus_init);
3894 
3895 #endif /* CONFIG_PM_GENERIC_DOMAINS_OF */
3896 
3897 
3898 /***        debugfs support        ***/
3899 
3900 #ifdef CONFIG_DEBUG_FS
3901 /*
3902  * TODO: This function is a slightly modified version of rtpm_status_show
3903  * from sysfs.c, so generalize it.
3904  */
3905 static void rtpm_status_str(struct seq_file *s, struct device *dev)
3906 {
3907 	static const char * const status_lookup[] = {
3908 		[RPM_ACTIVE] = "active",
3909 		[RPM_RESUMING] = "resuming",
3910 		[RPM_SUSPENDED] = "suspended",
3911 		[RPM_SUSPENDING] = "suspending"
3912 	};
3913 	const char *p = "";
3914 
3915 	if (dev->power.runtime_error)
3916 		p = "error";
3917 	else if (dev->power.disable_depth)
3918 		p = "unsupported";
3919 	else if (dev->power.runtime_status < ARRAY_SIZE(status_lookup))
3920 		p = status_lookup[dev->power.runtime_status];
3921 	else
3922 		WARN_ON(1);
3923 
3924 	seq_printf(s, "%-26s  ", p);
3925 }
3926 
3927 static void perf_status_str(struct seq_file *s, struct device *dev)
3928 {
3929 	struct generic_pm_domain_data *gpd_data;
3930 
3931 	gpd_data = to_gpd_data(dev->power.subsys_data->domain_data);
3932 
3933 	seq_printf(s, "%-10u  ", gpd_data->performance_state);
3934 }
3935 
3936 static void mode_status_str(struct seq_file *s, struct device *dev)
3937 {
3938 	struct generic_pm_domain_data *gpd_data;
3939 
3940 	gpd_data = to_gpd_data(dev->power.subsys_data->domain_data);
3941 
3942 	seq_printf(s, "%2s", gpd_data->hw_mode ? "HW" : "SW");
3943 }
3944 
3945 static int genpd_summary_one(struct seq_file *s,
3946 			struct generic_pm_domain *genpd)
3947 {
3948 	static const char * const status_lookup[] = {
3949 		[GENPD_STATE_ON] = "on",
3950 		[GENPD_STATE_OFF] = "off"
3951 	};
3952 	struct pm_domain_data *pm_data;
3953 	struct gpd_link *link;
3954 	char state[16];
3955 	int ret;
3956 
3957 	ret = genpd_lock_interruptible(genpd);
3958 	if (ret)
3959 		return -ERESTARTSYS;
3960 
3961 	if (WARN_ON(genpd->status >= ARRAY_SIZE(status_lookup)))
3962 		goto exit;
3963 	if (!genpd_status_on_unlocked(genpd))
3964 		snprintf(state, sizeof(state), "%s-%u",
3965 			 status_lookup[genpd->status], genpd->state_idx);
3966 	else
3967 		snprintf(state, sizeof(state), "%s",
3968 			 status_lookup[genpd->status]);
3969 	seq_printf(s, "%-30s  %-30s  %u", dev_name(&genpd->dev), state, genpd->performance_state);
3970 
3971 	/*
3972 	 * Modifications on the list require holding locks on both
3973 	 * parent and child, so we are safe.
3974 	 * Also the device name is immutable.
3975 	 */
3976 	list_for_each_entry(link, &genpd->parent_links, parent_node) {
3977 		if (list_is_first(&link->parent_node, &genpd->parent_links))
3978 			seq_printf(s, "\n%48s", " ");
3979 		seq_printf(s, "%s", link->child->name);
3980 		if (!list_is_last(&link->parent_node, &genpd->parent_links))
3981 			seq_puts(s, ", ");
3982 	}
3983 
3984 	list_for_each_entry(pm_data, &genpd->dev_list, list_node) {
3985 		seq_printf(s, "\n    %-30s  ", dev_name(pm_data->dev));
3986 		rtpm_status_str(s, pm_data->dev);
3987 		perf_status_str(s, pm_data->dev);
3988 		mode_status_str(s, pm_data->dev);
3989 	}
3990 
3991 	seq_puts(s, "\n");
3992 exit:
3993 	genpd_unlock(genpd);
3994 
3995 	return 0;
3996 }
3997 
3998 static int summary_show(struct seq_file *s, void *data)
3999 {
4000 	struct generic_pm_domain *genpd;
4001 	int ret = 0;
4002 
4003 	seq_puts(s, "domain                          status          children        performance\n");
4004 	seq_puts(s, "    /device                         runtime status                  managed by\n");
4005 	seq_puts(s, "------------------------------------------------------------------------------\n");
4006 
4007 	ret = mutex_lock_interruptible(&gpd_list_lock);
4008 	if (ret)
4009 		return -ERESTARTSYS;
4010 
4011 	list_for_each_entry(genpd, &gpd_list, gpd_list_node) {
4012 		ret = genpd_summary_one(s, genpd);
4013 		if (ret)
4014 			break;
4015 	}
4016 	mutex_unlock(&gpd_list_lock);
4017 
4018 	return ret;
4019 }
4020 
4021 static int status_show(struct seq_file *s, void *data)
4022 {
4023 	static const char * const status_lookup[] = {
4024 		[GENPD_STATE_ON] = "on",
4025 		[GENPD_STATE_OFF] = "off"
4026 	};
4027 
4028 	struct generic_pm_domain *genpd = s->private;
4029 	int ret = 0;
4030 
4031 	ret = genpd_lock_interruptible(genpd);
4032 	if (ret)
4033 		return -ERESTARTSYS;
4034 
4035 	if (WARN_ON_ONCE(genpd->status >= ARRAY_SIZE(status_lookup)))
4036 		goto exit;
4037 
4038 	if (genpd->status == GENPD_STATE_OFF)
4039 		seq_printf(s, "%s-%u\n", status_lookup[genpd->status],
4040 			genpd->state_idx);
4041 	else
4042 		seq_printf(s, "%s\n", status_lookup[genpd->status]);
4043 exit:
4044 	genpd_unlock(genpd);
4045 	return ret;
4046 }
4047 
4048 static int sub_domains_show(struct seq_file *s, void *data)
4049 {
4050 	struct generic_pm_domain *genpd = s->private;
4051 	struct gpd_link *link;
4052 	int ret = 0;
4053 
4054 	ret = genpd_lock_interruptible(genpd);
4055 	if (ret)
4056 		return -ERESTARTSYS;
4057 
4058 	list_for_each_entry(link, &genpd->parent_links, parent_node)
4059 		seq_printf(s, "%s\n", link->child->name);
4060 
4061 	genpd_unlock(genpd);
4062 	return ret;
4063 }
4064 
4065 static int idle_states_show(struct seq_file *s, void *data)
4066 {
4067 	struct generic_pm_domain *genpd = s->private;
4068 	u64 now, delta, idle_time = 0;
4069 	unsigned int i;
4070 	int ret = 0;
4071 
4072 	ret = genpd_lock_interruptible(genpd);
4073 	if (ret)
4074 		return -ERESTARTSYS;
4075 
4076 	seq_puts(s, "State  Time(ms)       Usage      Rejected   Above      Below      S2idle\n");
4077 
4078 	for (i = 0; i < genpd->state_count; i++) {
4079 		struct genpd_power_state *state = &genpd->states[i];
4080 		char state_name[7];
4081 
4082 		idle_time += state->idle_time;
4083 
4084 		if (genpd->status == GENPD_STATE_OFF && genpd->state_idx == i) {
4085 			now = ktime_get_mono_fast_ns();
4086 			if (now > genpd->accounting_time) {
4087 				delta = now - genpd->accounting_time;
4088 				idle_time += delta;
4089 			}
4090 		}
4091 
4092 		snprintf(state_name, ARRAY_SIZE(state_name), "S%-5d", i);
4093 		do_div(idle_time, NSEC_PER_MSEC);
4094 		seq_printf(s, "%-6s %-14llu %-10llu %-10llu %-10llu %-10llu %llu\n",
4095 			   state_name, idle_time, state->usage, state->rejected,
4096 			   state->above, state->below, state->usage_s2idle);
4097 	}
4098 
4099 	genpd_unlock(genpd);
4100 	return ret;
4101 }
4102 
4103 static int idle_states_desc_show(struct seq_file *s, void *data)
4104 {
4105 	struct generic_pm_domain *genpd = s->private;
4106 	unsigned int i;
4107 	int ret = 0;
4108 
4109 	ret = genpd_lock_interruptible(genpd);
4110 	if (ret)
4111 		return -ERESTARTSYS;
4112 
4113 	seq_puts(s, "State  Latency(us)  Residency(us)  Name\n");
4114 
4115 	for (i = 0; i < genpd->state_count; i++) {
4116 		struct genpd_power_state *state = &genpd->states[i];
4117 		u64 latency, residency;
4118 		char state_name[7];
4119 
4120 		latency = state->power_off_latency_ns +
4121 			state->power_on_latency_ns;
4122 		do_div(latency, NSEC_PER_USEC);
4123 
4124 		residency = state->residency_ns;
4125 		do_div(residency, NSEC_PER_USEC);
4126 
4127 		snprintf(state_name, ARRAY_SIZE(state_name), "S%-5d", i);
4128 		seq_printf(s, "%-6s %-12llu %-14llu %s\n",
4129 			   state_name, latency, residency,
4130 			   state->name ?: "N/A");
4131 	}
4132 
4133 	genpd_unlock(genpd);
4134 	return ret;
4135 }
4136 
4137 static int active_time_show(struct seq_file *s, void *data)
4138 {
4139 	struct generic_pm_domain *genpd = s->private;
4140 	u64 now, on_time, delta = 0;
4141 	int ret = 0;
4142 
4143 	ret = genpd_lock_interruptible(genpd);
4144 	if (ret)
4145 		return -ERESTARTSYS;
4146 
4147 	if (genpd->status == GENPD_STATE_ON) {
4148 		now = ktime_get_mono_fast_ns();
4149 		if (now > genpd->accounting_time)
4150 			delta = now - genpd->accounting_time;
4151 	}
4152 
4153 	on_time = genpd->on_time + delta;
4154 	do_div(on_time, NSEC_PER_MSEC);
4155 	seq_printf(s, "%llu ms\n", on_time);
4156 
4157 	genpd_unlock(genpd);
4158 	return ret;
4159 }
4160 
4161 static int total_idle_time_show(struct seq_file *s, void *data)
4162 {
4163 	struct generic_pm_domain *genpd = s->private;
4164 	u64 now, delta, total = 0;
4165 	unsigned int i;
4166 	int ret = 0;
4167 
4168 	ret = genpd_lock_interruptible(genpd);
4169 	if (ret)
4170 		return -ERESTARTSYS;
4171 
4172 	for (i = 0; i < genpd->state_count; i++) {
4173 		total += genpd->states[i].idle_time;
4174 
4175 		if (genpd->status == GENPD_STATE_OFF && genpd->state_idx == i) {
4176 			now = ktime_get_mono_fast_ns();
4177 			if (now > genpd->accounting_time) {
4178 				delta = now - genpd->accounting_time;
4179 				total += delta;
4180 			}
4181 		}
4182 	}
4183 
4184 	do_div(total, NSEC_PER_MSEC);
4185 	seq_printf(s, "%llu ms\n", total);
4186 
4187 	genpd_unlock(genpd);
4188 	return ret;
4189 }
4190 
4191 
4192 static int devices_show(struct seq_file *s, void *data)
4193 {
4194 	struct generic_pm_domain *genpd = s->private;
4195 	struct pm_domain_data *pm_data;
4196 	int ret = 0;
4197 
4198 	ret = genpd_lock_interruptible(genpd);
4199 	if (ret)
4200 		return -ERESTARTSYS;
4201 
4202 	list_for_each_entry(pm_data, &genpd->dev_list, list_node)
4203 		seq_printf(s, "%s\n", dev_name(pm_data->dev));
4204 
4205 	genpd_unlock(genpd);
4206 	return ret;
4207 }
4208 
4209 static int perf_state_show(struct seq_file *s, void *data)
4210 {
4211 	struct generic_pm_domain *genpd = s->private;
4212 
4213 	if (genpd_lock_interruptible(genpd))
4214 		return -ERESTARTSYS;
4215 
4216 	seq_printf(s, "%u\n", genpd->performance_state);
4217 
4218 	genpd_unlock(genpd);
4219 	return 0;
4220 }
4221 
4222 DEFINE_SHOW_ATTRIBUTE(summary);
4223 DEFINE_SHOW_ATTRIBUTE(status);
4224 DEFINE_SHOW_ATTRIBUTE(sub_domains);
4225 DEFINE_SHOW_ATTRIBUTE(idle_states);
4226 DEFINE_SHOW_ATTRIBUTE(idle_states_desc);
4227 DEFINE_SHOW_ATTRIBUTE(active_time);
4228 DEFINE_SHOW_ATTRIBUTE(total_idle_time);
4229 DEFINE_SHOW_ATTRIBUTE(devices);
4230 DEFINE_SHOW_ATTRIBUTE(perf_state);
4231 
4232 static void genpd_debug_add(struct generic_pm_domain *genpd)
4233 {
4234 	struct dentry *d;
4235 
4236 	if (!genpd_debugfs_dir)
4237 		return;
4238 
4239 	d = debugfs_create_dir(dev_name(&genpd->dev), genpd_debugfs_dir);
4240 
4241 	debugfs_create_file("current_state", 0444,
4242 			    d, genpd, &status_fops);
4243 	debugfs_create_file("sub_domains", 0444,
4244 			    d, genpd, &sub_domains_fops);
4245 	debugfs_create_file("idle_states", 0444,
4246 			    d, genpd, &idle_states_fops);
4247 	debugfs_create_file("idle_states_desc", 0444,
4248 			    d, genpd, &idle_states_desc_fops);
4249 	debugfs_create_file("active_time", 0444,
4250 			    d, genpd, &active_time_fops);
4251 	debugfs_create_file("total_idle_time", 0444,
4252 			    d, genpd, &total_idle_time_fops);
4253 	debugfs_create_file("devices", 0444,
4254 			    d, genpd, &devices_fops);
4255 	if (genpd->set_performance_state)
4256 		debugfs_create_file("perf_state", 0444,
4257 				    d, genpd, &perf_state_fops);
4258 }
4259 
4260 static int __init genpd_debug_init(void)
4261 {
4262 	struct generic_pm_domain *genpd;
4263 
4264 	genpd_debugfs_dir = debugfs_create_dir("pm_genpd", NULL);
4265 
4266 	debugfs_create_file("pm_genpd_summary", S_IRUGO, genpd_debugfs_dir,
4267 			    NULL, &summary_fops);
4268 
4269 	list_for_each_entry(genpd, &gpd_list, gpd_list_node)
4270 		genpd_debug_add(genpd);
4271 
4272 	return 0;
4273 }
4274 late_initcall(genpd_debug_init);
4275 
4276 static void __exit genpd_debug_exit(void)
4277 {
4278 	debugfs_remove_recursive(genpd_debugfs_dir);
4279 }
4280 __exitcall(genpd_debug_exit);
4281 #endif /* CONFIG_DEBUG_FS */
4282