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