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