xref: /openbmc/linux/drivers/opp/core.c (revision 68f436a8)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Generic OPP Interface
4  *
5  * Copyright (C) 2009-2010 Texas Instruments Incorporated.
6  *	Nishanth Menon
7  *	Romit Dasgupta
8  *	Kevin Hilman
9  */
10 
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12 
13 #include <linux/clk.h>
14 #include <linux/errno.h>
15 #include <linux/err.h>
16 #include <linux/device.h>
17 #include <linux/export.h>
18 #include <linux/pm_domain.h>
19 #include <linux/regulator/consumer.h>
20 #include <linux/slab.h>
21 #include <linux/xarray.h>
22 
23 #include "opp.h"
24 
25 /*
26  * The root of the list of all opp-tables. All opp_table structures branch off
27  * from here, with each opp_table containing the list of opps it supports in
28  * various states of availability.
29  */
30 LIST_HEAD(opp_tables);
31 
32 /* Lock to allow exclusive modification to the device and opp lists */
33 DEFINE_MUTEX(opp_table_lock);
34 /* Flag indicating that opp_tables list is being updated at the moment */
35 static bool opp_tables_busy;
36 
37 /* OPP ID allocator */
38 static DEFINE_XARRAY_ALLOC1(opp_configs);
39 
40 static bool _find_opp_dev(const struct device *dev, struct opp_table *opp_table)
41 {
42 	struct opp_device *opp_dev;
43 	bool found = false;
44 
45 	mutex_lock(&opp_table->lock);
46 	list_for_each_entry(opp_dev, &opp_table->dev_list, node)
47 		if (opp_dev->dev == dev) {
48 			found = true;
49 			break;
50 		}
51 
52 	mutex_unlock(&opp_table->lock);
53 	return found;
54 }
55 
56 static struct opp_table *_find_opp_table_unlocked(struct device *dev)
57 {
58 	struct opp_table *opp_table;
59 
60 	list_for_each_entry(opp_table, &opp_tables, node) {
61 		if (_find_opp_dev(dev, opp_table)) {
62 			_get_opp_table_kref(opp_table);
63 			return opp_table;
64 		}
65 	}
66 
67 	return ERR_PTR(-ENODEV);
68 }
69 
70 /**
71  * _find_opp_table() - find opp_table struct using device pointer
72  * @dev:	device pointer used to lookup OPP table
73  *
74  * Search OPP table for one containing matching device.
75  *
76  * Return: pointer to 'struct opp_table' if found, otherwise -ENODEV or
77  * -EINVAL based on type of error.
78  *
79  * The callers must call dev_pm_opp_put_opp_table() after the table is used.
80  */
81 struct opp_table *_find_opp_table(struct device *dev)
82 {
83 	struct opp_table *opp_table;
84 
85 	if (IS_ERR_OR_NULL(dev)) {
86 		pr_err("%s: Invalid parameters\n", __func__);
87 		return ERR_PTR(-EINVAL);
88 	}
89 
90 	mutex_lock(&opp_table_lock);
91 	opp_table = _find_opp_table_unlocked(dev);
92 	mutex_unlock(&opp_table_lock);
93 
94 	return opp_table;
95 }
96 
97 /*
98  * Returns true if multiple clocks aren't there, else returns false with WARN.
99  *
100  * We don't force clk_count == 1 here as there are users who don't have a clock
101  * representation in the OPP table and manage the clock configuration themselves
102  * in an platform specific way.
103  */
104 static bool assert_single_clk(struct opp_table *opp_table)
105 {
106 	return !WARN_ON(opp_table->clk_count > 1);
107 }
108 
109 /**
110  * dev_pm_opp_get_voltage() - Gets the voltage corresponding to an opp
111  * @opp:	opp for which voltage has to be returned for
112  *
113  * Return: voltage in micro volt corresponding to the opp, else
114  * return 0
115  *
116  * This is useful only for devices with single power supply.
117  */
118 unsigned long dev_pm_opp_get_voltage(struct dev_pm_opp *opp)
119 {
120 	if (IS_ERR_OR_NULL(opp)) {
121 		pr_err("%s: Invalid parameters\n", __func__);
122 		return 0;
123 	}
124 
125 	return opp->supplies[0].u_volt;
126 }
127 EXPORT_SYMBOL_GPL(dev_pm_opp_get_voltage);
128 
129 /**
130  * dev_pm_opp_get_supplies() - Gets the supply information corresponding to an opp
131  * @opp:	opp for which voltage has to be returned for
132  * @supplies:	Placeholder for copying the supply information.
133  *
134  * Return: negative error number on failure, 0 otherwise on success after
135  * setting @supplies.
136  *
137  * This can be used for devices with any number of power supplies. The caller
138  * must ensure the @supplies array must contain space for each regulator.
139  */
140 int dev_pm_opp_get_supplies(struct dev_pm_opp *opp,
141 			    struct dev_pm_opp_supply *supplies)
142 {
143 	if (IS_ERR_OR_NULL(opp) || !supplies) {
144 		pr_err("%s: Invalid parameters\n", __func__);
145 		return -EINVAL;
146 	}
147 
148 	memcpy(supplies, opp->supplies,
149 	       sizeof(*supplies) * opp->opp_table->regulator_count);
150 	return 0;
151 }
152 EXPORT_SYMBOL_GPL(dev_pm_opp_get_supplies);
153 
154 /**
155  * dev_pm_opp_get_power() - Gets the power corresponding to an opp
156  * @opp:	opp for which power has to be returned for
157  *
158  * Return: power in micro watt corresponding to the opp, else
159  * return 0
160  *
161  * This is useful only for devices with single power supply.
162  */
163 unsigned long dev_pm_opp_get_power(struct dev_pm_opp *opp)
164 {
165 	unsigned long opp_power = 0;
166 	int i;
167 
168 	if (IS_ERR_OR_NULL(opp)) {
169 		pr_err("%s: Invalid parameters\n", __func__);
170 		return 0;
171 	}
172 	for (i = 0; i < opp->opp_table->regulator_count; i++)
173 		opp_power += opp->supplies[i].u_watt;
174 
175 	return opp_power;
176 }
177 EXPORT_SYMBOL_GPL(dev_pm_opp_get_power);
178 
179 /**
180  * dev_pm_opp_get_freq() - Gets the frequency corresponding to an available opp
181  * @opp:	opp for which frequency has to be returned for
182  *
183  * Return: frequency in hertz corresponding to the opp, else
184  * return 0
185  */
186 unsigned long dev_pm_opp_get_freq(struct dev_pm_opp *opp)
187 {
188 	if (IS_ERR_OR_NULL(opp)) {
189 		pr_err("%s: Invalid parameters\n", __func__);
190 		return 0;
191 	}
192 
193 	if (!assert_single_clk(opp->opp_table))
194 		return 0;
195 
196 	return opp->rates[0];
197 }
198 EXPORT_SYMBOL_GPL(dev_pm_opp_get_freq);
199 
200 /**
201  * dev_pm_opp_get_level() - Gets the level corresponding to an available opp
202  * @opp:	opp for which level value has to be returned for
203  *
204  * Return: level read from device tree corresponding to the opp, else
205  * return 0.
206  */
207 unsigned int dev_pm_opp_get_level(struct dev_pm_opp *opp)
208 {
209 	if (IS_ERR_OR_NULL(opp) || !opp->available) {
210 		pr_err("%s: Invalid parameters\n", __func__);
211 		return 0;
212 	}
213 
214 	return opp->level;
215 }
216 EXPORT_SYMBOL_GPL(dev_pm_opp_get_level);
217 
218 /**
219  * dev_pm_opp_get_required_pstate() - Gets the required performance state
220  *                                    corresponding to an available opp
221  * @opp:	opp for which performance state has to be returned for
222  * @index:	index of the required opp
223  *
224  * Return: performance state read from device tree corresponding to the
225  * required opp, else return 0.
226  */
227 unsigned int dev_pm_opp_get_required_pstate(struct dev_pm_opp *opp,
228 					    unsigned int index)
229 {
230 	struct opp_table *opp_table = opp->opp_table;
231 
232 	if (IS_ERR_OR_NULL(opp) || !opp->available ||
233 	    index >= opp_table->required_opp_count) {
234 		pr_err("%s: Invalid parameters\n", __func__);
235 		return 0;
236 	}
237 
238 	/* required-opps not fully initialized yet */
239 	if (lazy_linking_pending(opp_table))
240 		return 0;
241 
242 	/* The required OPP table must belong to a genpd */
243 	if (unlikely(!opp_table->required_opp_tables[index]->is_genpd)) {
244 		pr_err("%s: Performance state is only valid for genpds.\n", __func__);
245 		return 0;
246 	}
247 
248 	return opp->required_opps[index]->level;
249 }
250 EXPORT_SYMBOL_GPL(dev_pm_opp_get_required_pstate);
251 
252 /**
253  * dev_pm_opp_is_turbo() - Returns if opp is turbo OPP or not
254  * @opp: opp for which turbo mode is being verified
255  *
256  * Turbo OPPs are not for normal use, and can be enabled (under certain
257  * conditions) for short duration of times to finish high throughput work
258  * quickly. Running on them for longer times may overheat the chip.
259  *
260  * Return: true if opp is turbo opp, else false.
261  */
262 bool dev_pm_opp_is_turbo(struct dev_pm_opp *opp)
263 {
264 	if (IS_ERR_OR_NULL(opp) || !opp->available) {
265 		pr_err("%s: Invalid parameters\n", __func__);
266 		return false;
267 	}
268 
269 	return opp->turbo;
270 }
271 EXPORT_SYMBOL_GPL(dev_pm_opp_is_turbo);
272 
273 /**
274  * dev_pm_opp_get_max_clock_latency() - Get max clock latency in nanoseconds
275  * @dev:	device for which we do this operation
276  *
277  * Return: This function returns the max clock latency in nanoseconds.
278  */
279 unsigned long dev_pm_opp_get_max_clock_latency(struct device *dev)
280 {
281 	struct opp_table *opp_table;
282 	unsigned long clock_latency_ns;
283 
284 	opp_table = _find_opp_table(dev);
285 	if (IS_ERR(opp_table))
286 		return 0;
287 
288 	clock_latency_ns = opp_table->clock_latency_ns_max;
289 
290 	dev_pm_opp_put_opp_table(opp_table);
291 
292 	return clock_latency_ns;
293 }
294 EXPORT_SYMBOL_GPL(dev_pm_opp_get_max_clock_latency);
295 
296 /**
297  * dev_pm_opp_get_max_volt_latency() - Get max voltage latency in nanoseconds
298  * @dev: device for which we do this operation
299  *
300  * Return: This function returns the max voltage latency in nanoseconds.
301  */
302 unsigned long dev_pm_opp_get_max_volt_latency(struct device *dev)
303 {
304 	struct opp_table *opp_table;
305 	struct dev_pm_opp *opp;
306 	struct regulator *reg;
307 	unsigned long latency_ns = 0;
308 	int ret, i, count;
309 	struct {
310 		unsigned long min;
311 		unsigned long max;
312 	} *uV;
313 
314 	opp_table = _find_opp_table(dev);
315 	if (IS_ERR(opp_table))
316 		return 0;
317 
318 	/* Regulator may not be required for the device */
319 	if (!opp_table->regulators)
320 		goto put_opp_table;
321 
322 	count = opp_table->regulator_count;
323 
324 	uV = kmalloc_array(count, sizeof(*uV), GFP_KERNEL);
325 	if (!uV)
326 		goto put_opp_table;
327 
328 	mutex_lock(&opp_table->lock);
329 
330 	for (i = 0; i < count; i++) {
331 		uV[i].min = ~0;
332 		uV[i].max = 0;
333 
334 		list_for_each_entry(opp, &opp_table->opp_list, node) {
335 			if (!opp->available)
336 				continue;
337 
338 			if (opp->supplies[i].u_volt_min < uV[i].min)
339 				uV[i].min = opp->supplies[i].u_volt_min;
340 			if (opp->supplies[i].u_volt_max > uV[i].max)
341 				uV[i].max = opp->supplies[i].u_volt_max;
342 		}
343 	}
344 
345 	mutex_unlock(&opp_table->lock);
346 
347 	/*
348 	 * The caller needs to ensure that opp_table (and hence the regulator)
349 	 * isn't freed, while we are executing this routine.
350 	 */
351 	for (i = 0; i < count; i++) {
352 		reg = opp_table->regulators[i];
353 		ret = regulator_set_voltage_time(reg, uV[i].min, uV[i].max);
354 		if (ret > 0)
355 			latency_ns += ret * 1000;
356 	}
357 
358 	kfree(uV);
359 put_opp_table:
360 	dev_pm_opp_put_opp_table(opp_table);
361 
362 	return latency_ns;
363 }
364 EXPORT_SYMBOL_GPL(dev_pm_opp_get_max_volt_latency);
365 
366 /**
367  * dev_pm_opp_get_max_transition_latency() - Get max transition latency in
368  *					     nanoseconds
369  * @dev: device for which we do this operation
370  *
371  * Return: This function returns the max transition latency, in nanoseconds, to
372  * switch from one OPP to other.
373  */
374 unsigned long dev_pm_opp_get_max_transition_latency(struct device *dev)
375 {
376 	return dev_pm_opp_get_max_volt_latency(dev) +
377 		dev_pm_opp_get_max_clock_latency(dev);
378 }
379 EXPORT_SYMBOL_GPL(dev_pm_opp_get_max_transition_latency);
380 
381 /**
382  * dev_pm_opp_get_suspend_opp_freq() - Get frequency of suspend opp in Hz
383  * @dev:	device for which we do this operation
384  *
385  * Return: This function returns the frequency of the OPP marked as suspend_opp
386  * if one is available, else returns 0;
387  */
388 unsigned long dev_pm_opp_get_suspend_opp_freq(struct device *dev)
389 {
390 	struct opp_table *opp_table;
391 	unsigned long freq = 0;
392 
393 	opp_table = _find_opp_table(dev);
394 	if (IS_ERR(opp_table))
395 		return 0;
396 
397 	if (opp_table->suspend_opp && opp_table->suspend_opp->available)
398 		freq = dev_pm_opp_get_freq(opp_table->suspend_opp);
399 
400 	dev_pm_opp_put_opp_table(opp_table);
401 
402 	return freq;
403 }
404 EXPORT_SYMBOL_GPL(dev_pm_opp_get_suspend_opp_freq);
405 
406 int _get_opp_count(struct opp_table *opp_table)
407 {
408 	struct dev_pm_opp *opp;
409 	int count = 0;
410 
411 	mutex_lock(&opp_table->lock);
412 
413 	list_for_each_entry(opp, &opp_table->opp_list, node) {
414 		if (opp->available)
415 			count++;
416 	}
417 
418 	mutex_unlock(&opp_table->lock);
419 
420 	return count;
421 }
422 
423 /**
424  * dev_pm_opp_get_opp_count() - Get number of opps available in the opp table
425  * @dev:	device for which we do this operation
426  *
427  * Return: This function returns the number of available opps if there are any,
428  * else returns 0 if none or the corresponding error value.
429  */
430 int dev_pm_opp_get_opp_count(struct device *dev)
431 {
432 	struct opp_table *opp_table;
433 	int count;
434 
435 	opp_table = _find_opp_table(dev);
436 	if (IS_ERR(opp_table)) {
437 		count = PTR_ERR(opp_table);
438 		dev_dbg(dev, "%s: OPP table not found (%d)\n",
439 			__func__, count);
440 		return count;
441 	}
442 
443 	count = _get_opp_count(opp_table);
444 	dev_pm_opp_put_opp_table(opp_table);
445 
446 	return count;
447 }
448 EXPORT_SYMBOL_GPL(dev_pm_opp_get_opp_count);
449 
450 /* Helpers to read keys */
451 static unsigned long _read_freq(struct dev_pm_opp *opp, int index)
452 {
453 	return opp->rates[0];
454 }
455 
456 static unsigned long _read_level(struct dev_pm_opp *opp, int index)
457 {
458 	return opp->level;
459 }
460 
461 static unsigned long _read_bw(struct dev_pm_opp *opp, int index)
462 {
463 	return opp->bandwidth[index].peak;
464 }
465 
466 /* Generic comparison helpers */
467 static bool _compare_exact(struct dev_pm_opp **opp, struct dev_pm_opp *temp_opp,
468 			   unsigned long opp_key, unsigned long key)
469 {
470 	if (opp_key == key) {
471 		*opp = temp_opp;
472 		return true;
473 	}
474 
475 	return false;
476 }
477 
478 static bool _compare_ceil(struct dev_pm_opp **opp, struct dev_pm_opp *temp_opp,
479 			  unsigned long opp_key, unsigned long key)
480 {
481 	if (opp_key >= key) {
482 		*opp = temp_opp;
483 		return true;
484 	}
485 
486 	return false;
487 }
488 
489 static bool _compare_floor(struct dev_pm_opp **opp, struct dev_pm_opp *temp_opp,
490 			   unsigned long opp_key, unsigned long key)
491 {
492 	if (opp_key > key)
493 		return true;
494 
495 	*opp = temp_opp;
496 	return false;
497 }
498 
499 /* Generic key finding helpers */
500 static struct dev_pm_opp *_opp_table_find_key(struct opp_table *opp_table,
501 		unsigned long *key, int index, bool available,
502 		unsigned long (*read)(struct dev_pm_opp *opp, int index),
503 		bool (*compare)(struct dev_pm_opp **opp, struct dev_pm_opp *temp_opp,
504 				unsigned long opp_key, unsigned long key),
505 		bool (*assert)(struct opp_table *opp_table))
506 {
507 	struct dev_pm_opp *temp_opp, *opp = ERR_PTR(-ERANGE);
508 
509 	/* Assert that the requirement is met */
510 	if (assert && !assert(opp_table))
511 		return ERR_PTR(-EINVAL);
512 
513 	mutex_lock(&opp_table->lock);
514 
515 	list_for_each_entry(temp_opp, &opp_table->opp_list, node) {
516 		if (temp_opp->available == available) {
517 			if (compare(&opp, temp_opp, read(temp_opp, index), *key))
518 				break;
519 		}
520 	}
521 
522 	/* Increment the reference count of OPP */
523 	if (!IS_ERR(opp)) {
524 		*key = read(opp, index);
525 		dev_pm_opp_get(opp);
526 	}
527 
528 	mutex_unlock(&opp_table->lock);
529 
530 	return opp;
531 }
532 
533 static struct dev_pm_opp *
534 _find_key(struct device *dev, unsigned long *key, int index, bool available,
535 	  unsigned long (*read)(struct dev_pm_opp *opp, int index),
536 	  bool (*compare)(struct dev_pm_opp **opp, struct dev_pm_opp *temp_opp,
537 			  unsigned long opp_key, unsigned long key),
538 	  bool (*assert)(struct opp_table *opp_table))
539 {
540 	struct opp_table *opp_table;
541 	struct dev_pm_opp *opp;
542 
543 	opp_table = _find_opp_table(dev);
544 	if (IS_ERR(opp_table)) {
545 		dev_err(dev, "%s: OPP table not found (%ld)\n", __func__,
546 			PTR_ERR(opp_table));
547 		return ERR_CAST(opp_table);
548 	}
549 
550 	opp = _opp_table_find_key(opp_table, key, index, available, read,
551 				  compare, assert);
552 
553 	dev_pm_opp_put_opp_table(opp_table);
554 
555 	return opp;
556 }
557 
558 static struct dev_pm_opp *_find_key_exact(struct device *dev,
559 		unsigned long key, int index, bool available,
560 		unsigned long (*read)(struct dev_pm_opp *opp, int index),
561 		bool (*assert)(struct opp_table *opp_table))
562 {
563 	/*
564 	 * The value of key will be updated here, but will be ignored as the
565 	 * caller doesn't need it.
566 	 */
567 	return _find_key(dev, &key, index, available, read, _compare_exact,
568 			 assert);
569 }
570 
571 static struct dev_pm_opp *_opp_table_find_key_ceil(struct opp_table *opp_table,
572 		unsigned long *key, int index, bool available,
573 		unsigned long (*read)(struct dev_pm_opp *opp, int index),
574 		bool (*assert)(struct opp_table *opp_table))
575 {
576 	return _opp_table_find_key(opp_table, key, index, available, read,
577 				   _compare_ceil, assert);
578 }
579 
580 static struct dev_pm_opp *_find_key_ceil(struct device *dev, unsigned long *key,
581 		int index, bool available,
582 		unsigned long (*read)(struct dev_pm_opp *opp, int index),
583 		bool (*assert)(struct opp_table *opp_table))
584 {
585 	return _find_key(dev, key, index, available, read, _compare_ceil,
586 			 assert);
587 }
588 
589 static struct dev_pm_opp *_find_key_floor(struct device *dev,
590 		unsigned long *key, int index, bool available,
591 		unsigned long (*read)(struct dev_pm_opp *opp, int index),
592 		bool (*assert)(struct opp_table *opp_table))
593 {
594 	return _find_key(dev, key, index, available, read, _compare_floor,
595 			 assert);
596 }
597 
598 /**
599  * dev_pm_opp_find_freq_exact() - search for an exact frequency
600  * @dev:		device for which we do this operation
601  * @freq:		frequency to search for
602  * @available:		true/false - match for available opp
603  *
604  * Return: Searches for exact match in the opp table and returns pointer to the
605  * matching opp if found, else returns ERR_PTR in case of error and should
606  * be handled using IS_ERR. Error return values can be:
607  * EINVAL:	for bad pointer
608  * ERANGE:	no match found for search
609  * ENODEV:	if device not found in list of registered devices
610  *
611  * Note: available is a modifier for the search. if available=true, then the
612  * match is for exact matching frequency and is available in the stored OPP
613  * table. if false, the match is for exact frequency which is not available.
614  *
615  * This provides a mechanism to enable an opp which is not available currently
616  * or the opposite as well.
617  *
618  * The callers are required to call dev_pm_opp_put() for the returned OPP after
619  * use.
620  */
621 struct dev_pm_opp *dev_pm_opp_find_freq_exact(struct device *dev,
622 		unsigned long freq, bool available)
623 {
624 	return _find_key_exact(dev, freq, 0, available, _read_freq,
625 			       assert_single_clk);
626 }
627 EXPORT_SYMBOL_GPL(dev_pm_opp_find_freq_exact);
628 
629 static noinline struct dev_pm_opp *_find_freq_ceil(struct opp_table *opp_table,
630 						   unsigned long *freq)
631 {
632 	return _opp_table_find_key_ceil(opp_table, freq, 0, true, _read_freq,
633 					assert_single_clk);
634 }
635 
636 /**
637  * dev_pm_opp_find_freq_ceil() - Search for an rounded ceil freq
638  * @dev:	device for which we do this operation
639  * @freq:	Start frequency
640  *
641  * Search for the matching ceil *available* OPP from a starting freq
642  * for a device.
643  *
644  * Return: matching *opp and refreshes *freq accordingly, else returns
645  * ERR_PTR in case of error and should be handled using IS_ERR. Error return
646  * values can be:
647  * EINVAL:	for bad pointer
648  * ERANGE:	no match found for search
649  * ENODEV:	if device not found in list of registered devices
650  *
651  * The callers are required to call dev_pm_opp_put() for the returned OPP after
652  * use.
653  */
654 struct dev_pm_opp *dev_pm_opp_find_freq_ceil(struct device *dev,
655 					     unsigned long *freq)
656 {
657 	return _find_key_ceil(dev, freq, 0, true, _read_freq, assert_single_clk);
658 }
659 EXPORT_SYMBOL_GPL(dev_pm_opp_find_freq_ceil);
660 
661 /**
662  * dev_pm_opp_find_freq_floor() - Search for a rounded floor freq
663  * @dev:	device for which we do this operation
664  * @freq:	Start frequency
665  *
666  * Search for the matching floor *available* OPP from a starting freq
667  * for a device.
668  *
669  * Return: matching *opp and refreshes *freq accordingly, else returns
670  * ERR_PTR in case of error and should be handled using IS_ERR. Error return
671  * values can be:
672  * EINVAL:	for bad pointer
673  * ERANGE:	no match found for search
674  * ENODEV:	if device not found in list of registered devices
675  *
676  * The callers are required to call dev_pm_opp_put() for the returned OPP after
677  * use.
678  */
679 struct dev_pm_opp *dev_pm_opp_find_freq_floor(struct device *dev,
680 					      unsigned long *freq)
681 {
682 	return _find_key_floor(dev, freq, 0, true, _read_freq, assert_single_clk);
683 }
684 EXPORT_SYMBOL_GPL(dev_pm_opp_find_freq_floor);
685 
686 /**
687  * dev_pm_opp_find_level_exact() - search for an exact level
688  * @dev:		device for which we do this operation
689  * @level:		level to search for
690  *
691  * Return: Searches for exact match in the opp table and returns pointer to the
692  * matching opp if found, else returns ERR_PTR in case of error and should
693  * be handled using IS_ERR. Error return values can be:
694  * EINVAL:	for bad pointer
695  * ERANGE:	no match found for search
696  * ENODEV:	if device not found in list of registered devices
697  *
698  * The callers are required to call dev_pm_opp_put() for the returned OPP after
699  * use.
700  */
701 struct dev_pm_opp *dev_pm_opp_find_level_exact(struct device *dev,
702 					       unsigned int level)
703 {
704 	return _find_key_exact(dev, level, 0, true, _read_level, NULL);
705 }
706 EXPORT_SYMBOL_GPL(dev_pm_opp_find_level_exact);
707 
708 /**
709  * dev_pm_opp_find_level_ceil() - search for an rounded up level
710  * @dev:		device for which we do this operation
711  * @level:		level to search for
712  *
713  * Return: Searches for rounded up match in the opp table and returns pointer
714  * to the  matching opp if found, else returns ERR_PTR in case of error and
715  * should be handled using IS_ERR. Error return values can be:
716  * EINVAL:	for bad pointer
717  * ERANGE:	no match found for search
718  * ENODEV:	if device not found in list of registered devices
719  *
720  * The callers are required to call dev_pm_opp_put() for the returned OPP after
721  * use.
722  */
723 struct dev_pm_opp *dev_pm_opp_find_level_ceil(struct device *dev,
724 					      unsigned int *level)
725 {
726 	unsigned long temp = *level;
727 	struct dev_pm_opp *opp;
728 
729 	opp = _find_key_ceil(dev, &temp, 0, true, _read_level, NULL);
730 	*level = temp;
731 	return opp;
732 }
733 EXPORT_SYMBOL_GPL(dev_pm_opp_find_level_ceil);
734 
735 /**
736  * dev_pm_opp_find_bw_ceil() - Search for a rounded ceil bandwidth
737  * @dev:	device for which we do this operation
738  * @bw:	start bandwidth
739  * @index:	which bandwidth to compare, in case of OPPs with several values
740  *
741  * Search for the matching floor *available* OPP from a starting bandwidth
742  * for a device.
743  *
744  * Return: matching *opp and refreshes *bw accordingly, else returns
745  * ERR_PTR in case of error and should be handled using IS_ERR. Error return
746  * values can be:
747  * EINVAL:	for bad pointer
748  * ERANGE:	no match found for search
749  * ENODEV:	if device not found in list of registered devices
750  *
751  * The callers are required to call dev_pm_opp_put() for the returned OPP after
752  * use.
753  */
754 struct dev_pm_opp *dev_pm_opp_find_bw_ceil(struct device *dev, unsigned int *bw,
755 					   int index)
756 {
757 	unsigned long temp = *bw;
758 	struct dev_pm_opp *opp;
759 
760 	opp = _find_key_ceil(dev, &temp, index, true, _read_bw, NULL);
761 	*bw = temp;
762 	return opp;
763 }
764 EXPORT_SYMBOL_GPL(dev_pm_opp_find_bw_ceil);
765 
766 /**
767  * dev_pm_opp_find_bw_floor() - Search for a rounded floor bandwidth
768  * @dev:	device for which we do this operation
769  * @bw:	start bandwidth
770  * @index:	which bandwidth to compare, in case of OPPs with several values
771  *
772  * Search for the matching floor *available* OPP from a starting bandwidth
773  * for a device.
774  *
775  * Return: matching *opp and refreshes *bw accordingly, else returns
776  * ERR_PTR in case of error and should be handled using IS_ERR. Error return
777  * values can be:
778  * EINVAL:	for bad pointer
779  * ERANGE:	no match found for search
780  * ENODEV:	if device not found in list of registered devices
781  *
782  * The callers are required to call dev_pm_opp_put() for the returned OPP after
783  * use.
784  */
785 struct dev_pm_opp *dev_pm_opp_find_bw_floor(struct device *dev,
786 					    unsigned int *bw, int index)
787 {
788 	unsigned long temp = *bw;
789 	struct dev_pm_opp *opp;
790 
791 	opp = _find_key_floor(dev, &temp, index, true, _read_bw, NULL);
792 	*bw = temp;
793 	return opp;
794 }
795 EXPORT_SYMBOL_GPL(dev_pm_opp_find_bw_floor);
796 
797 static int _set_opp_voltage(struct device *dev, struct regulator *reg,
798 			    struct dev_pm_opp_supply *supply)
799 {
800 	int ret;
801 
802 	/* Regulator not available for device */
803 	if (IS_ERR(reg)) {
804 		dev_dbg(dev, "%s: regulator not available: %ld\n", __func__,
805 			PTR_ERR(reg));
806 		return 0;
807 	}
808 
809 	dev_dbg(dev, "%s: voltages (mV): %lu %lu %lu\n", __func__,
810 		supply->u_volt_min, supply->u_volt, supply->u_volt_max);
811 
812 	ret = regulator_set_voltage_triplet(reg, supply->u_volt_min,
813 					    supply->u_volt, supply->u_volt_max);
814 	if (ret)
815 		dev_err(dev, "%s: failed to set voltage (%lu %lu %lu mV): %d\n",
816 			__func__, supply->u_volt_min, supply->u_volt,
817 			supply->u_volt_max, ret);
818 
819 	return ret;
820 }
821 
822 static int
823 _opp_config_clk_single(struct device *dev, struct opp_table *opp_table,
824 		       struct dev_pm_opp *opp, void *data, bool scaling_down)
825 {
826 	unsigned long *target = data;
827 	unsigned long freq;
828 	int ret;
829 
830 	/* One of target and opp must be available */
831 	if (target) {
832 		freq = *target;
833 	} else if (opp) {
834 		freq = opp->rates[0];
835 	} else {
836 		WARN_ON(1);
837 		return -EINVAL;
838 	}
839 
840 	ret = clk_set_rate(opp_table->clk, freq);
841 	if (ret) {
842 		dev_err(dev, "%s: failed to set clock rate: %d\n", __func__,
843 			ret);
844 	} else {
845 		opp_table->rate_clk_single = freq;
846 	}
847 
848 	return ret;
849 }
850 
851 /*
852  * Simple implementation for configuring multiple clocks. Configure clocks in
853  * the order in which they are present in the array while scaling up.
854  */
855 int dev_pm_opp_config_clks_simple(struct device *dev,
856 		struct opp_table *opp_table, struct dev_pm_opp *opp, void *data,
857 		bool scaling_down)
858 {
859 	int ret, i;
860 
861 	if (scaling_down) {
862 		for (i = opp_table->clk_count - 1; i >= 0; i--) {
863 			ret = clk_set_rate(opp_table->clks[i], opp->rates[i]);
864 			if (ret) {
865 				dev_err(dev, "%s: failed to set clock rate: %d\n", __func__,
866 					ret);
867 				return ret;
868 			}
869 		}
870 	} else {
871 		for (i = 0; i < opp_table->clk_count; i++) {
872 			ret = clk_set_rate(opp_table->clks[i], opp->rates[i]);
873 			if (ret) {
874 				dev_err(dev, "%s: failed to set clock rate: %d\n", __func__,
875 					ret);
876 				return ret;
877 			}
878 		}
879 	}
880 
881 	return 0;
882 }
883 EXPORT_SYMBOL_GPL(dev_pm_opp_config_clks_simple);
884 
885 static int _opp_config_regulator_single(struct device *dev,
886 			struct dev_pm_opp *old_opp, struct dev_pm_opp *new_opp,
887 			struct regulator **regulators, unsigned int count)
888 {
889 	struct regulator *reg = regulators[0];
890 	int ret;
891 
892 	/* This function only supports single regulator per device */
893 	if (WARN_ON(count > 1)) {
894 		dev_err(dev, "multiple regulators are not supported\n");
895 		return -EINVAL;
896 	}
897 
898 	ret = _set_opp_voltage(dev, reg, new_opp->supplies);
899 	if (ret)
900 		return ret;
901 
902 	/*
903 	 * Enable the regulator after setting its voltages, otherwise it breaks
904 	 * some boot-enabled regulators.
905 	 */
906 	if (unlikely(!new_opp->opp_table->enabled)) {
907 		ret = regulator_enable(reg);
908 		if (ret < 0)
909 			dev_warn(dev, "Failed to enable regulator: %d", ret);
910 	}
911 
912 	return 0;
913 }
914 
915 static int _set_opp_bw(const struct opp_table *opp_table,
916 		       struct dev_pm_opp *opp, struct device *dev)
917 {
918 	u32 avg, peak;
919 	int i, ret;
920 
921 	if (!opp_table->paths)
922 		return 0;
923 
924 	for (i = 0; i < opp_table->path_count; i++) {
925 		if (!opp) {
926 			avg = 0;
927 			peak = 0;
928 		} else {
929 			avg = opp->bandwidth[i].avg;
930 			peak = opp->bandwidth[i].peak;
931 		}
932 		ret = icc_set_bw(opp_table->paths[i], avg, peak);
933 		if (ret) {
934 			dev_err(dev, "Failed to %s bandwidth[%d]: %d\n",
935 				opp ? "set" : "remove", i, ret);
936 			return ret;
937 		}
938 	}
939 
940 	return 0;
941 }
942 
943 static int _set_performance_state(struct device *dev, struct device *pd_dev,
944 				  struct dev_pm_opp *opp, int i)
945 {
946 	unsigned int pstate = likely(opp) ? opp->required_opps[i]->level: 0;
947 	int ret;
948 
949 	if (!pd_dev)
950 		return 0;
951 
952 	ret = dev_pm_genpd_set_performance_state(pd_dev, pstate);
953 	if (ret) {
954 		dev_err(dev, "Failed to set performance state of %s: %d (%d)\n",
955 			dev_name(pd_dev), pstate, ret);
956 	}
957 
958 	return ret;
959 }
960 
961 static int _opp_set_required_opps_generic(struct device *dev,
962 	struct opp_table *opp_table, struct dev_pm_opp *opp, bool scaling_down)
963 {
964 	dev_err(dev, "setting required-opps isn't supported for non-genpd devices\n");
965 	return -ENOENT;
966 }
967 
968 static int _opp_set_required_opps_genpd(struct device *dev,
969 	struct opp_table *opp_table, struct dev_pm_opp *opp, bool scaling_down)
970 {
971 	struct device **genpd_virt_devs =
972 		opp_table->genpd_virt_devs ? opp_table->genpd_virt_devs : &dev;
973 	int i, ret = 0;
974 
975 	/*
976 	 * Acquire genpd_virt_dev_lock to make sure we don't use a genpd_dev
977 	 * after it is freed from another thread.
978 	 */
979 	mutex_lock(&opp_table->genpd_virt_dev_lock);
980 
981 	/* Scaling up? Set required OPPs in normal order, else reverse */
982 	if (!scaling_down) {
983 		for (i = 0; i < opp_table->required_opp_count; i++) {
984 			ret = _set_performance_state(dev, genpd_virt_devs[i], opp, i);
985 			if (ret)
986 				break;
987 		}
988 	} else {
989 		for (i = opp_table->required_opp_count - 1; i >= 0; i--) {
990 			ret = _set_performance_state(dev, genpd_virt_devs[i], opp, i);
991 			if (ret)
992 				break;
993 		}
994 	}
995 
996 	mutex_unlock(&opp_table->genpd_virt_dev_lock);
997 
998 	return ret;
999 }
1000 
1001 /* This is only called for PM domain for now */
1002 static int _set_required_opps(struct device *dev, struct opp_table *opp_table,
1003 			      struct dev_pm_opp *opp, bool up)
1004 {
1005 	/* required-opps not fully initialized yet */
1006 	if (lazy_linking_pending(opp_table))
1007 		return -EBUSY;
1008 
1009 	if (opp_table->set_required_opps)
1010 		return opp_table->set_required_opps(dev, opp_table, opp, up);
1011 
1012 	return 0;
1013 }
1014 
1015 /* Update set_required_opps handler */
1016 void _update_set_required_opps(struct opp_table *opp_table)
1017 {
1018 	/* Already set */
1019 	if (opp_table->set_required_opps)
1020 		return;
1021 
1022 	/* All required OPPs will belong to genpd or none */
1023 	if (opp_table->required_opp_tables[0]->is_genpd)
1024 		opp_table->set_required_opps = _opp_set_required_opps_genpd;
1025 	else
1026 		opp_table->set_required_opps = _opp_set_required_opps_generic;
1027 }
1028 
1029 static void _find_current_opp(struct device *dev, struct opp_table *opp_table)
1030 {
1031 	struct dev_pm_opp *opp = ERR_PTR(-ENODEV);
1032 	unsigned long freq;
1033 
1034 	if (!IS_ERR(opp_table->clk)) {
1035 		freq = clk_get_rate(opp_table->clk);
1036 		opp = _find_freq_ceil(opp_table, &freq);
1037 	}
1038 
1039 	/*
1040 	 * Unable to find the current OPP ? Pick the first from the list since
1041 	 * it is in ascending order, otherwise rest of the code will need to
1042 	 * make special checks to validate current_opp.
1043 	 */
1044 	if (IS_ERR(opp)) {
1045 		mutex_lock(&opp_table->lock);
1046 		opp = list_first_entry(&opp_table->opp_list, struct dev_pm_opp, node);
1047 		dev_pm_opp_get(opp);
1048 		mutex_unlock(&opp_table->lock);
1049 	}
1050 
1051 	opp_table->current_opp = opp;
1052 }
1053 
1054 static int _disable_opp_table(struct device *dev, struct opp_table *opp_table)
1055 {
1056 	int ret;
1057 
1058 	if (!opp_table->enabled)
1059 		return 0;
1060 
1061 	/*
1062 	 * Some drivers need to support cases where some platforms may
1063 	 * have OPP table for the device, while others don't and
1064 	 * opp_set_rate() just needs to behave like clk_set_rate().
1065 	 */
1066 	if (!_get_opp_count(opp_table))
1067 		return 0;
1068 
1069 	ret = _set_opp_bw(opp_table, NULL, dev);
1070 	if (ret)
1071 		return ret;
1072 
1073 	if (opp_table->regulators)
1074 		regulator_disable(opp_table->regulators[0]);
1075 
1076 	ret = _set_required_opps(dev, opp_table, NULL, false);
1077 
1078 	opp_table->enabled = false;
1079 	return ret;
1080 }
1081 
1082 static int _set_opp(struct device *dev, struct opp_table *opp_table,
1083 		    struct dev_pm_opp *opp, void *clk_data, bool forced)
1084 {
1085 	struct dev_pm_opp *old_opp;
1086 	int scaling_down, ret;
1087 
1088 	if (unlikely(!opp))
1089 		return _disable_opp_table(dev, opp_table);
1090 
1091 	/* Find the currently set OPP if we don't know already */
1092 	if (unlikely(!opp_table->current_opp))
1093 		_find_current_opp(dev, opp_table);
1094 
1095 	old_opp = opp_table->current_opp;
1096 
1097 	/* Return early if nothing to do */
1098 	if (!forced && old_opp == opp && opp_table->enabled) {
1099 		dev_dbg_ratelimited(dev, "%s: OPPs are same, nothing to do\n", __func__);
1100 		return 0;
1101 	}
1102 
1103 	dev_dbg(dev, "%s: switching OPP: Freq %lu -> %lu Hz, Level %u -> %u, Bw %u -> %u\n",
1104 		__func__, old_opp->rates[0], opp->rates[0], old_opp->level,
1105 		opp->level, old_opp->bandwidth ? old_opp->bandwidth[0].peak : 0,
1106 		opp->bandwidth ? opp->bandwidth[0].peak : 0);
1107 
1108 	scaling_down = _opp_compare_key(opp_table, old_opp, opp);
1109 	if (scaling_down == -1)
1110 		scaling_down = 0;
1111 
1112 	/* Scaling up? Configure required OPPs before frequency */
1113 	if (!scaling_down) {
1114 		ret = _set_required_opps(dev, opp_table, opp, true);
1115 		if (ret) {
1116 			dev_err(dev, "Failed to set required opps: %d\n", ret);
1117 			return ret;
1118 		}
1119 
1120 		ret = _set_opp_bw(opp_table, opp, dev);
1121 		if (ret) {
1122 			dev_err(dev, "Failed to set bw: %d\n", ret);
1123 			return ret;
1124 		}
1125 
1126 		if (opp_table->config_regulators) {
1127 			ret = opp_table->config_regulators(dev, old_opp, opp,
1128 							   opp_table->regulators,
1129 							   opp_table->regulator_count);
1130 			if (ret) {
1131 				dev_err(dev, "Failed to set regulator voltages: %d\n",
1132 					ret);
1133 				return ret;
1134 			}
1135 		}
1136 	}
1137 
1138 	if (opp_table->config_clks) {
1139 		ret = opp_table->config_clks(dev, opp_table, opp, clk_data, scaling_down);
1140 		if (ret)
1141 			return ret;
1142 	}
1143 
1144 	/* Scaling down? Configure required OPPs after frequency */
1145 	if (scaling_down) {
1146 		if (opp_table->config_regulators) {
1147 			ret = opp_table->config_regulators(dev, old_opp, opp,
1148 							   opp_table->regulators,
1149 							   opp_table->regulator_count);
1150 			if (ret) {
1151 				dev_err(dev, "Failed to set regulator voltages: %d\n",
1152 					ret);
1153 				return ret;
1154 			}
1155 		}
1156 
1157 		ret = _set_opp_bw(opp_table, opp, dev);
1158 		if (ret) {
1159 			dev_err(dev, "Failed to set bw: %d\n", ret);
1160 			return ret;
1161 		}
1162 
1163 		ret = _set_required_opps(dev, opp_table, opp, false);
1164 		if (ret) {
1165 			dev_err(dev, "Failed to set required opps: %d\n", ret);
1166 			return ret;
1167 		}
1168 	}
1169 
1170 	opp_table->enabled = true;
1171 	dev_pm_opp_put(old_opp);
1172 
1173 	/* Make sure current_opp doesn't get freed */
1174 	dev_pm_opp_get(opp);
1175 	opp_table->current_opp = opp;
1176 
1177 	return ret;
1178 }
1179 
1180 /**
1181  * dev_pm_opp_set_rate() - Configure new OPP based on frequency
1182  * @dev:	 device for which we do this operation
1183  * @target_freq: frequency to achieve
1184  *
1185  * This configures the power-supplies to the levels specified by the OPP
1186  * corresponding to the target_freq, and programs the clock to a value <=
1187  * target_freq, as rounded by clk_round_rate(). Device wanting to run at fmax
1188  * provided by the opp, should have already rounded to the target OPP's
1189  * frequency.
1190  */
1191 int dev_pm_opp_set_rate(struct device *dev, unsigned long target_freq)
1192 {
1193 	struct opp_table *opp_table;
1194 	unsigned long freq = 0, temp_freq;
1195 	struct dev_pm_opp *opp = NULL;
1196 	bool forced = false;
1197 	int ret;
1198 
1199 	opp_table = _find_opp_table(dev);
1200 	if (IS_ERR(opp_table)) {
1201 		dev_err(dev, "%s: device's opp table doesn't exist\n", __func__);
1202 		return PTR_ERR(opp_table);
1203 	}
1204 
1205 	if (target_freq) {
1206 		/*
1207 		 * For IO devices which require an OPP on some platforms/SoCs
1208 		 * while just needing to scale the clock on some others
1209 		 * we look for empty OPP tables with just a clock handle and
1210 		 * scale only the clk. This makes dev_pm_opp_set_rate()
1211 		 * equivalent to a clk_set_rate()
1212 		 */
1213 		if (!_get_opp_count(opp_table)) {
1214 			ret = opp_table->config_clks(dev, opp_table, NULL,
1215 						     &target_freq, false);
1216 			goto put_opp_table;
1217 		}
1218 
1219 		freq = clk_round_rate(opp_table->clk, target_freq);
1220 		if ((long)freq <= 0)
1221 			freq = target_freq;
1222 
1223 		/*
1224 		 * The clock driver may support finer resolution of the
1225 		 * frequencies than the OPP table, don't update the frequency we
1226 		 * pass to clk_set_rate() here.
1227 		 */
1228 		temp_freq = freq;
1229 		opp = _find_freq_ceil(opp_table, &temp_freq);
1230 		if (IS_ERR(opp)) {
1231 			ret = PTR_ERR(opp);
1232 			dev_err(dev, "%s: failed to find OPP for freq %lu (%d)\n",
1233 				__func__, freq, ret);
1234 			goto put_opp_table;
1235 		}
1236 
1237 		/*
1238 		 * An OPP entry specifies the highest frequency at which other
1239 		 * properties of the OPP entry apply. Even if the new OPP is
1240 		 * same as the old one, we may still reach here for a different
1241 		 * value of the frequency. In such a case, do not abort but
1242 		 * configure the hardware to the desired frequency forcefully.
1243 		 */
1244 		forced = opp_table->rate_clk_single != target_freq;
1245 	}
1246 
1247 	ret = _set_opp(dev, opp_table, opp, &target_freq, forced);
1248 
1249 	if (target_freq)
1250 		dev_pm_opp_put(opp);
1251 
1252 put_opp_table:
1253 	dev_pm_opp_put_opp_table(opp_table);
1254 	return ret;
1255 }
1256 EXPORT_SYMBOL_GPL(dev_pm_opp_set_rate);
1257 
1258 /**
1259  * dev_pm_opp_set_opp() - Configure device for OPP
1260  * @dev: device for which we do this operation
1261  * @opp: OPP to set to
1262  *
1263  * This configures the device based on the properties of the OPP passed to this
1264  * routine.
1265  *
1266  * Return: 0 on success, a negative error number otherwise.
1267  */
1268 int dev_pm_opp_set_opp(struct device *dev, struct dev_pm_opp *opp)
1269 {
1270 	struct opp_table *opp_table;
1271 	int ret;
1272 
1273 	opp_table = _find_opp_table(dev);
1274 	if (IS_ERR(opp_table)) {
1275 		dev_err(dev, "%s: device opp doesn't exist\n", __func__);
1276 		return PTR_ERR(opp_table);
1277 	}
1278 
1279 	ret = _set_opp(dev, opp_table, opp, NULL, false);
1280 	dev_pm_opp_put_opp_table(opp_table);
1281 
1282 	return ret;
1283 }
1284 EXPORT_SYMBOL_GPL(dev_pm_opp_set_opp);
1285 
1286 /* OPP-dev Helpers */
1287 static void _remove_opp_dev(struct opp_device *opp_dev,
1288 			    struct opp_table *opp_table)
1289 {
1290 	opp_debug_unregister(opp_dev, opp_table);
1291 	list_del(&opp_dev->node);
1292 	kfree(opp_dev);
1293 }
1294 
1295 struct opp_device *_add_opp_dev(const struct device *dev,
1296 				struct opp_table *opp_table)
1297 {
1298 	struct opp_device *opp_dev;
1299 
1300 	opp_dev = kzalloc(sizeof(*opp_dev), GFP_KERNEL);
1301 	if (!opp_dev)
1302 		return NULL;
1303 
1304 	/* Initialize opp-dev */
1305 	opp_dev->dev = dev;
1306 
1307 	mutex_lock(&opp_table->lock);
1308 	list_add(&opp_dev->node, &opp_table->dev_list);
1309 	mutex_unlock(&opp_table->lock);
1310 
1311 	/* Create debugfs entries for the opp_table */
1312 	opp_debug_register(opp_dev, opp_table);
1313 
1314 	return opp_dev;
1315 }
1316 
1317 static struct opp_table *_allocate_opp_table(struct device *dev, int index)
1318 {
1319 	struct opp_table *opp_table;
1320 	struct opp_device *opp_dev;
1321 	int ret;
1322 
1323 	/*
1324 	 * Allocate a new OPP table. In the infrequent case where a new
1325 	 * device is needed to be added, we pay this penalty.
1326 	 */
1327 	opp_table = kzalloc(sizeof(*opp_table), GFP_KERNEL);
1328 	if (!opp_table)
1329 		return ERR_PTR(-ENOMEM);
1330 
1331 	mutex_init(&opp_table->lock);
1332 	mutex_init(&opp_table->genpd_virt_dev_lock);
1333 	INIT_LIST_HEAD(&opp_table->dev_list);
1334 	INIT_LIST_HEAD(&opp_table->lazy);
1335 
1336 	opp_table->clk = ERR_PTR(-ENODEV);
1337 
1338 	/* Mark regulator count uninitialized */
1339 	opp_table->regulator_count = -1;
1340 
1341 	opp_dev = _add_opp_dev(dev, opp_table);
1342 	if (!opp_dev) {
1343 		ret = -ENOMEM;
1344 		goto err;
1345 	}
1346 
1347 	_of_init_opp_table(opp_table, dev, index);
1348 
1349 	/* Find interconnect path(s) for the device */
1350 	ret = dev_pm_opp_of_find_icc_paths(dev, opp_table);
1351 	if (ret) {
1352 		if (ret == -EPROBE_DEFER)
1353 			goto remove_opp_dev;
1354 
1355 		dev_warn(dev, "%s: Error finding interconnect paths: %d\n",
1356 			 __func__, ret);
1357 	}
1358 
1359 	BLOCKING_INIT_NOTIFIER_HEAD(&opp_table->head);
1360 	INIT_LIST_HEAD(&opp_table->opp_list);
1361 	kref_init(&opp_table->kref);
1362 
1363 	return opp_table;
1364 
1365 remove_opp_dev:
1366 	_of_clear_opp_table(opp_table);
1367 	_remove_opp_dev(opp_dev, opp_table);
1368 	mutex_destroy(&opp_table->genpd_virt_dev_lock);
1369 	mutex_destroy(&opp_table->lock);
1370 err:
1371 	kfree(opp_table);
1372 	return ERR_PTR(ret);
1373 }
1374 
1375 void _get_opp_table_kref(struct opp_table *opp_table)
1376 {
1377 	kref_get(&opp_table->kref);
1378 }
1379 
1380 static struct opp_table *_update_opp_table_clk(struct device *dev,
1381 					       struct opp_table *opp_table,
1382 					       bool getclk)
1383 {
1384 	int ret;
1385 
1386 	/*
1387 	 * Return early if we don't need to get clk or we have already done it
1388 	 * earlier.
1389 	 */
1390 	if (!getclk || IS_ERR(opp_table) || !IS_ERR(opp_table->clk) ||
1391 	    opp_table->clks)
1392 		return opp_table;
1393 
1394 	/* Find clk for the device */
1395 	opp_table->clk = clk_get(dev, NULL);
1396 
1397 	ret = PTR_ERR_OR_ZERO(opp_table->clk);
1398 	if (!ret) {
1399 		opp_table->config_clks = _opp_config_clk_single;
1400 		opp_table->clk_count = 1;
1401 		return opp_table;
1402 	}
1403 
1404 	if (ret == -ENOENT) {
1405 		/*
1406 		 * There are few platforms which don't want the OPP core to
1407 		 * manage device's clock settings. In such cases neither the
1408 		 * platform provides the clks explicitly to us, nor the DT
1409 		 * contains a valid clk entry. The OPP nodes in DT may still
1410 		 * contain "opp-hz" property though, which we need to parse and
1411 		 * allow the platform to find an OPP based on freq later on.
1412 		 *
1413 		 * This is a simple solution to take care of such corner cases,
1414 		 * i.e. make the clk_count 1, which lets us allocate space for
1415 		 * frequency in opp->rates and also parse the entries in DT.
1416 		 */
1417 		opp_table->clk_count = 1;
1418 
1419 		dev_dbg(dev, "%s: Couldn't find clock: %d\n", __func__, ret);
1420 		return opp_table;
1421 	}
1422 
1423 	dev_pm_opp_put_opp_table(opp_table);
1424 	dev_err_probe(dev, ret, "Couldn't find clock\n");
1425 
1426 	return ERR_PTR(ret);
1427 }
1428 
1429 /*
1430  * We need to make sure that the OPP table for a device doesn't get added twice,
1431  * if this routine gets called in parallel with the same device pointer.
1432  *
1433  * The simplest way to enforce that is to perform everything (find existing
1434  * table and if not found, create a new one) under the opp_table_lock, so only
1435  * one creator gets access to the same. But that expands the critical section
1436  * under the lock and may end up causing circular dependencies with frameworks
1437  * like debugfs, interconnect or clock framework as they may be direct or
1438  * indirect users of OPP core.
1439  *
1440  * And for that reason we have to go for a bit tricky implementation here, which
1441  * uses the opp_tables_busy flag to indicate if another creator is in the middle
1442  * of adding an OPP table and others should wait for it to finish.
1443  */
1444 struct opp_table *_add_opp_table_indexed(struct device *dev, int index,
1445 					 bool getclk)
1446 {
1447 	struct opp_table *opp_table;
1448 
1449 again:
1450 	mutex_lock(&opp_table_lock);
1451 
1452 	opp_table = _find_opp_table_unlocked(dev);
1453 	if (!IS_ERR(opp_table))
1454 		goto unlock;
1455 
1456 	/*
1457 	 * The opp_tables list or an OPP table's dev_list is getting updated by
1458 	 * another user, wait for it to finish.
1459 	 */
1460 	if (unlikely(opp_tables_busy)) {
1461 		mutex_unlock(&opp_table_lock);
1462 		cpu_relax();
1463 		goto again;
1464 	}
1465 
1466 	opp_tables_busy = true;
1467 	opp_table = _managed_opp(dev, index);
1468 
1469 	/* Drop the lock to reduce the size of critical section */
1470 	mutex_unlock(&opp_table_lock);
1471 
1472 	if (opp_table) {
1473 		if (!_add_opp_dev(dev, opp_table)) {
1474 			dev_pm_opp_put_opp_table(opp_table);
1475 			opp_table = ERR_PTR(-ENOMEM);
1476 		}
1477 
1478 		mutex_lock(&opp_table_lock);
1479 	} else {
1480 		opp_table = _allocate_opp_table(dev, index);
1481 
1482 		mutex_lock(&opp_table_lock);
1483 		if (!IS_ERR(opp_table))
1484 			list_add(&opp_table->node, &opp_tables);
1485 	}
1486 
1487 	opp_tables_busy = false;
1488 
1489 unlock:
1490 	mutex_unlock(&opp_table_lock);
1491 
1492 	return _update_opp_table_clk(dev, opp_table, getclk);
1493 }
1494 
1495 static struct opp_table *_add_opp_table(struct device *dev, bool getclk)
1496 {
1497 	return _add_opp_table_indexed(dev, 0, getclk);
1498 }
1499 
1500 struct opp_table *dev_pm_opp_get_opp_table(struct device *dev)
1501 {
1502 	return _find_opp_table(dev);
1503 }
1504 EXPORT_SYMBOL_GPL(dev_pm_opp_get_opp_table);
1505 
1506 static void _opp_table_kref_release(struct kref *kref)
1507 {
1508 	struct opp_table *opp_table = container_of(kref, struct opp_table, kref);
1509 	struct opp_device *opp_dev, *temp;
1510 	int i;
1511 
1512 	/* Drop the lock as soon as we can */
1513 	list_del(&opp_table->node);
1514 	mutex_unlock(&opp_table_lock);
1515 
1516 	if (opp_table->current_opp)
1517 		dev_pm_opp_put(opp_table->current_opp);
1518 
1519 	_of_clear_opp_table(opp_table);
1520 
1521 	/* Release automatically acquired single clk */
1522 	if (!IS_ERR(opp_table->clk))
1523 		clk_put(opp_table->clk);
1524 
1525 	if (opp_table->paths) {
1526 		for (i = 0; i < opp_table->path_count; i++)
1527 			icc_put(opp_table->paths[i]);
1528 		kfree(opp_table->paths);
1529 	}
1530 
1531 	WARN_ON(!list_empty(&opp_table->opp_list));
1532 
1533 	list_for_each_entry_safe(opp_dev, temp, &opp_table->dev_list, node)
1534 		_remove_opp_dev(opp_dev, opp_table);
1535 
1536 	mutex_destroy(&opp_table->genpd_virt_dev_lock);
1537 	mutex_destroy(&opp_table->lock);
1538 	kfree(opp_table);
1539 }
1540 
1541 void dev_pm_opp_put_opp_table(struct opp_table *opp_table)
1542 {
1543 	kref_put_mutex(&opp_table->kref, _opp_table_kref_release,
1544 		       &opp_table_lock);
1545 }
1546 EXPORT_SYMBOL_GPL(dev_pm_opp_put_opp_table);
1547 
1548 void _opp_free(struct dev_pm_opp *opp)
1549 {
1550 	kfree(opp);
1551 }
1552 
1553 static void _opp_kref_release(struct kref *kref)
1554 {
1555 	struct dev_pm_opp *opp = container_of(kref, struct dev_pm_opp, kref);
1556 	struct opp_table *opp_table = opp->opp_table;
1557 
1558 	list_del(&opp->node);
1559 	mutex_unlock(&opp_table->lock);
1560 
1561 	/*
1562 	 * Notify the changes in the availability of the operable
1563 	 * frequency/voltage list.
1564 	 */
1565 	blocking_notifier_call_chain(&opp_table->head, OPP_EVENT_REMOVE, opp);
1566 	_of_clear_opp(opp_table, opp);
1567 	opp_debug_remove_one(opp);
1568 	kfree(opp);
1569 }
1570 
1571 void dev_pm_opp_get(struct dev_pm_opp *opp)
1572 {
1573 	kref_get(&opp->kref);
1574 }
1575 
1576 void dev_pm_opp_put(struct dev_pm_opp *opp)
1577 {
1578 	kref_put_mutex(&opp->kref, _opp_kref_release, &opp->opp_table->lock);
1579 }
1580 EXPORT_SYMBOL_GPL(dev_pm_opp_put);
1581 
1582 /**
1583  * dev_pm_opp_remove()  - Remove an OPP from OPP table
1584  * @dev:	device for which we do this operation
1585  * @freq:	OPP to remove with matching 'freq'
1586  *
1587  * This function removes an opp from the opp table.
1588  */
1589 void dev_pm_opp_remove(struct device *dev, unsigned long freq)
1590 {
1591 	struct dev_pm_opp *opp = NULL, *iter;
1592 	struct opp_table *opp_table;
1593 
1594 	opp_table = _find_opp_table(dev);
1595 	if (IS_ERR(opp_table))
1596 		return;
1597 
1598 	if (!assert_single_clk(opp_table))
1599 		goto put_table;
1600 
1601 	mutex_lock(&opp_table->lock);
1602 
1603 	list_for_each_entry(iter, &opp_table->opp_list, node) {
1604 		if (iter->rates[0] == freq) {
1605 			opp = iter;
1606 			break;
1607 		}
1608 	}
1609 
1610 	mutex_unlock(&opp_table->lock);
1611 
1612 	if (opp) {
1613 		dev_pm_opp_put(opp);
1614 
1615 		/* Drop the reference taken by dev_pm_opp_add() */
1616 		dev_pm_opp_put_opp_table(opp_table);
1617 	} else {
1618 		dev_warn(dev, "%s: Couldn't find OPP with freq: %lu\n",
1619 			 __func__, freq);
1620 	}
1621 
1622 put_table:
1623 	/* Drop the reference taken by _find_opp_table() */
1624 	dev_pm_opp_put_opp_table(opp_table);
1625 }
1626 EXPORT_SYMBOL_GPL(dev_pm_opp_remove);
1627 
1628 static struct dev_pm_opp *_opp_get_next(struct opp_table *opp_table,
1629 					bool dynamic)
1630 {
1631 	struct dev_pm_opp *opp = NULL, *temp;
1632 
1633 	mutex_lock(&opp_table->lock);
1634 	list_for_each_entry(temp, &opp_table->opp_list, node) {
1635 		/*
1636 		 * Refcount must be dropped only once for each OPP by OPP core,
1637 		 * do that with help of "removed" flag.
1638 		 */
1639 		if (!temp->removed && dynamic == temp->dynamic) {
1640 			opp = temp;
1641 			break;
1642 		}
1643 	}
1644 
1645 	mutex_unlock(&opp_table->lock);
1646 	return opp;
1647 }
1648 
1649 /*
1650  * Can't call dev_pm_opp_put() from under the lock as debugfs removal needs to
1651  * happen lock less to avoid circular dependency issues. This routine must be
1652  * called without the opp_table->lock held.
1653  */
1654 static void _opp_remove_all(struct opp_table *opp_table, bool dynamic)
1655 {
1656 	struct dev_pm_opp *opp;
1657 
1658 	while ((opp = _opp_get_next(opp_table, dynamic))) {
1659 		opp->removed = true;
1660 		dev_pm_opp_put(opp);
1661 
1662 		/* Drop the references taken by dev_pm_opp_add() */
1663 		if (dynamic)
1664 			dev_pm_opp_put_opp_table(opp_table);
1665 	}
1666 }
1667 
1668 bool _opp_remove_all_static(struct opp_table *opp_table)
1669 {
1670 	mutex_lock(&opp_table->lock);
1671 
1672 	if (!opp_table->parsed_static_opps) {
1673 		mutex_unlock(&opp_table->lock);
1674 		return false;
1675 	}
1676 
1677 	if (--opp_table->parsed_static_opps) {
1678 		mutex_unlock(&opp_table->lock);
1679 		return true;
1680 	}
1681 
1682 	mutex_unlock(&opp_table->lock);
1683 
1684 	_opp_remove_all(opp_table, false);
1685 	return true;
1686 }
1687 
1688 /**
1689  * dev_pm_opp_remove_all_dynamic() - Remove all dynamically created OPPs
1690  * @dev:	device for which we do this operation
1691  *
1692  * This function removes all dynamically created OPPs from the opp table.
1693  */
1694 void dev_pm_opp_remove_all_dynamic(struct device *dev)
1695 {
1696 	struct opp_table *opp_table;
1697 
1698 	opp_table = _find_opp_table(dev);
1699 	if (IS_ERR(opp_table))
1700 		return;
1701 
1702 	_opp_remove_all(opp_table, true);
1703 
1704 	/* Drop the reference taken by _find_opp_table() */
1705 	dev_pm_opp_put_opp_table(opp_table);
1706 }
1707 EXPORT_SYMBOL_GPL(dev_pm_opp_remove_all_dynamic);
1708 
1709 struct dev_pm_opp *_opp_allocate(struct opp_table *opp_table)
1710 {
1711 	struct dev_pm_opp *opp;
1712 	int supply_count, supply_size, icc_size, clk_size;
1713 
1714 	/* Allocate space for at least one supply */
1715 	supply_count = opp_table->regulator_count > 0 ?
1716 			opp_table->regulator_count : 1;
1717 	supply_size = sizeof(*opp->supplies) * supply_count;
1718 	clk_size = sizeof(*opp->rates) * opp_table->clk_count;
1719 	icc_size = sizeof(*opp->bandwidth) * opp_table->path_count;
1720 
1721 	/* allocate new OPP node and supplies structures */
1722 	opp = kzalloc(sizeof(*opp) + supply_size + clk_size + icc_size, GFP_KERNEL);
1723 	if (!opp)
1724 		return NULL;
1725 
1726 	/* Put the supplies, bw and clock at the end of the OPP structure */
1727 	opp->supplies = (struct dev_pm_opp_supply *)(opp + 1);
1728 
1729 	opp->rates = (unsigned long *)(opp->supplies + supply_count);
1730 
1731 	if (icc_size)
1732 		opp->bandwidth = (struct dev_pm_opp_icc_bw *)(opp->rates + opp_table->clk_count);
1733 
1734 	INIT_LIST_HEAD(&opp->node);
1735 
1736 	return opp;
1737 }
1738 
1739 static bool _opp_supported_by_regulators(struct dev_pm_opp *opp,
1740 					 struct opp_table *opp_table)
1741 {
1742 	struct regulator *reg;
1743 	int i;
1744 
1745 	if (!opp_table->regulators)
1746 		return true;
1747 
1748 	for (i = 0; i < opp_table->regulator_count; i++) {
1749 		reg = opp_table->regulators[i];
1750 
1751 		if (!regulator_is_supported_voltage(reg,
1752 					opp->supplies[i].u_volt_min,
1753 					opp->supplies[i].u_volt_max)) {
1754 			pr_warn("%s: OPP minuV: %lu maxuV: %lu, not supported by regulator\n",
1755 				__func__, opp->supplies[i].u_volt_min,
1756 				opp->supplies[i].u_volt_max);
1757 			return false;
1758 		}
1759 	}
1760 
1761 	return true;
1762 }
1763 
1764 static int _opp_compare_rate(struct opp_table *opp_table,
1765 			     struct dev_pm_opp *opp1, struct dev_pm_opp *opp2)
1766 {
1767 	int i;
1768 
1769 	for (i = 0; i < opp_table->clk_count; i++) {
1770 		if (opp1->rates[i] != opp2->rates[i])
1771 			return opp1->rates[i] < opp2->rates[i] ? -1 : 1;
1772 	}
1773 
1774 	/* Same rates for both OPPs */
1775 	return 0;
1776 }
1777 
1778 static int _opp_compare_bw(struct opp_table *opp_table, struct dev_pm_opp *opp1,
1779 			   struct dev_pm_opp *opp2)
1780 {
1781 	int i;
1782 
1783 	for (i = 0; i < opp_table->path_count; i++) {
1784 		if (opp1->bandwidth[i].peak != opp2->bandwidth[i].peak)
1785 			return opp1->bandwidth[i].peak < opp2->bandwidth[i].peak ? -1 : 1;
1786 	}
1787 
1788 	/* Same bw for both OPPs */
1789 	return 0;
1790 }
1791 
1792 /*
1793  * Returns
1794  * 0: opp1 == opp2
1795  * 1: opp1 > opp2
1796  * -1: opp1 < opp2
1797  */
1798 int _opp_compare_key(struct opp_table *opp_table, struct dev_pm_opp *opp1,
1799 		     struct dev_pm_opp *opp2)
1800 {
1801 	int ret;
1802 
1803 	ret = _opp_compare_rate(opp_table, opp1, opp2);
1804 	if (ret)
1805 		return ret;
1806 
1807 	ret = _opp_compare_bw(opp_table, opp1, opp2);
1808 	if (ret)
1809 		return ret;
1810 
1811 	if (opp1->level != opp2->level)
1812 		return opp1->level < opp2->level ? -1 : 1;
1813 
1814 	/* Duplicate OPPs */
1815 	return 0;
1816 }
1817 
1818 static int _opp_is_duplicate(struct device *dev, struct dev_pm_opp *new_opp,
1819 			     struct opp_table *opp_table,
1820 			     struct list_head **head)
1821 {
1822 	struct dev_pm_opp *opp;
1823 	int opp_cmp;
1824 
1825 	/*
1826 	 * Insert new OPP in order of increasing frequency and discard if
1827 	 * already present.
1828 	 *
1829 	 * Need to use &opp_table->opp_list in the condition part of the 'for'
1830 	 * loop, don't replace it with head otherwise it will become an infinite
1831 	 * loop.
1832 	 */
1833 	list_for_each_entry(opp, &opp_table->opp_list, node) {
1834 		opp_cmp = _opp_compare_key(opp_table, new_opp, opp);
1835 		if (opp_cmp > 0) {
1836 			*head = &opp->node;
1837 			continue;
1838 		}
1839 
1840 		if (opp_cmp < 0)
1841 			return 0;
1842 
1843 		/* Duplicate OPPs */
1844 		dev_warn(dev, "%s: duplicate OPPs detected. Existing: freq: %lu, volt: %lu, enabled: %d. New: freq: %lu, volt: %lu, enabled: %d\n",
1845 			 __func__, opp->rates[0], opp->supplies[0].u_volt,
1846 			 opp->available, new_opp->rates[0],
1847 			 new_opp->supplies[0].u_volt, new_opp->available);
1848 
1849 		/* Should we compare voltages for all regulators here ? */
1850 		return opp->available &&
1851 		       new_opp->supplies[0].u_volt == opp->supplies[0].u_volt ? -EBUSY : -EEXIST;
1852 	}
1853 
1854 	return 0;
1855 }
1856 
1857 void _required_opps_available(struct dev_pm_opp *opp, int count)
1858 {
1859 	int i;
1860 
1861 	for (i = 0; i < count; i++) {
1862 		if (opp->required_opps[i]->available)
1863 			continue;
1864 
1865 		opp->available = false;
1866 		pr_warn("%s: OPP not supported by required OPP %pOF (%lu)\n",
1867 			 __func__, opp->required_opps[i]->np, opp->rates[0]);
1868 		return;
1869 	}
1870 }
1871 
1872 /*
1873  * Returns:
1874  * 0: On success. And appropriate error message for duplicate OPPs.
1875  * -EBUSY: For OPP with same freq/volt and is available. The callers of
1876  *  _opp_add() must return 0 if they receive -EBUSY from it. This is to make
1877  *  sure we don't print error messages unnecessarily if different parts of
1878  *  kernel try to initialize the OPP table.
1879  * -EEXIST: For OPP with same freq but different volt or is unavailable. This
1880  *  should be considered an error by the callers of _opp_add().
1881  */
1882 int _opp_add(struct device *dev, struct dev_pm_opp *new_opp,
1883 	     struct opp_table *opp_table)
1884 {
1885 	struct list_head *head;
1886 	int ret;
1887 
1888 	mutex_lock(&opp_table->lock);
1889 	head = &opp_table->opp_list;
1890 
1891 	ret = _opp_is_duplicate(dev, new_opp, opp_table, &head);
1892 	if (ret) {
1893 		mutex_unlock(&opp_table->lock);
1894 		return ret;
1895 	}
1896 
1897 	list_add(&new_opp->node, head);
1898 	mutex_unlock(&opp_table->lock);
1899 
1900 	new_opp->opp_table = opp_table;
1901 	kref_init(&new_opp->kref);
1902 
1903 	opp_debug_create_one(new_opp, opp_table);
1904 
1905 	if (!_opp_supported_by_regulators(new_opp, opp_table)) {
1906 		new_opp->available = false;
1907 		dev_warn(dev, "%s: OPP not supported by regulators (%lu)\n",
1908 			 __func__, new_opp->rates[0]);
1909 	}
1910 
1911 	/* required-opps not fully initialized yet */
1912 	if (lazy_linking_pending(opp_table))
1913 		return 0;
1914 
1915 	_required_opps_available(new_opp, opp_table->required_opp_count);
1916 
1917 	return 0;
1918 }
1919 
1920 /**
1921  * _opp_add_v1() - Allocate a OPP based on v1 bindings.
1922  * @opp_table:	OPP table
1923  * @dev:	device for which we do this operation
1924  * @freq:	Frequency in Hz for this OPP
1925  * @u_volt:	Voltage in uVolts for this OPP
1926  * @dynamic:	Dynamically added OPPs.
1927  *
1928  * This function adds an opp definition to the opp table and returns status.
1929  * The opp is made available by default and it can be controlled using
1930  * dev_pm_opp_enable/disable functions and may be removed by dev_pm_opp_remove.
1931  *
1932  * NOTE: "dynamic" parameter impacts OPPs added by the dev_pm_opp_of_add_table
1933  * and freed by dev_pm_opp_of_remove_table.
1934  *
1935  * Return:
1936  * 0		On success OR
1937  *		Duplicate OPPs (both freq and volt are same) and opp->available
1938  * -EEXIST	Freq are same and volt are different OR
1939  *		Duplicate OPPs (both freq and volt are same) and !opp->available
1940  * -ENOMEM	Memory allocation failure
1941  */
1942 int _opp_add_v1(struct opp_table *opp_table, struct device *dev,
1943 		unsigned long freq, long u_volt, bool dynamic)
1944 {
1945 	struct dev_pm_opp *new_opp;
1946 	unsigned long tol;
1947 	int ret;
1948 
1949 	if (!assert_single_clk(opp_table))
1950 		return -EINVAL;
1951 
1952 	new_opp = _opp_allocate(opp_table);
1953 	if (!new_opp)
1954 		return -ENOMEM;
1955 
1956 	/* populate the opp table */
1957 	new_opp->rates[0] = freq;
1958 	tol = u_volt * opp_table->voltage_tolerance_v1 / 100;
1959 	new_opp->supplies[0].u_volt = u_volt;
1960 	new_opp->supplies[0].u_volt_min = u_volt - tol;
1961 	new_opp->supplies[0].u_volt_max = u_volt + tol;
1962 	new_opp->available = true;
1963 	new_opp->dynamic = dynamic;
1964 
1965 	ret = _opp_add(dev, new_opp, opp_table);
1966 	if (ret) {
1967 		/* Don't return error for duplicate OPPs */
1968 		if (ret == -EBUSY)
1969 			ret = 0;
1970 		goto free_opp;
1971 	}
1972 
1973 	/*
1974 	 * Notify the changes in the availability of the operable
1975 	 * frequency/voltage list.
1976 	 */
1977 	blocking_notifier_call_chain(&opp_table->head, OPP_EVENT_ADD, new_opp);
1978 	return 0;
1979 
1980 free_opp:
1981 	_opp_free(new_opp);
1982 
1983 	return ret;
1984 }
1985 
1986 /**
1987  * _opp_set_supported_hw() - Set supported platforms
1988  * @dev: Device for which supported-hw has to be set.
1989  * @versions: Array of hierarchy of versions to match.
1990  * @count: Number of elements in the array.
1991  *
1992  * This is required only for the V2 bindings, and it enables a platform to
1993  * specify the hierarchy of versions it supports. OPP layer will then enable
1994  * OPPs, which are available for those versions, based on its 'opp-supported-hw'
1995  * property.
1996  */
1997 static int _opp_set_supported_hw(struct opp_table *opp_table,
1998 				 const u32 *versions, unsigned int count)
1999 {
2000 	/* Another CPU that shares the OPP table has set the property ? */
2001 	if (opp_table->supported_hw)
2002 		return 0;
2003 
2004 	opp_table->supported_hw = kmemdup(versions, count * sizeof(*versions),
2005 					GFP_KERNEL);
2006 	if (!opp_table->supported_hw)
2007 		return -ENOMEM;
2008 
2009 	opp_table->supported_hw_count = count;
2010 
2011 	return 0;
2012 }
2013 
2014 /**
2015  * _opp_put_supported_hw() - Releases resources blocked for supported hw
2016  * @opp_table: OPP table returned by _opp_set_supported_hw().
2017  *
2018  * This is required only for the V2 bindings, and is called for a matching
2019  * _opp_set_supported_hw(). Until this is called, the opp_table structure
2020  * will not be freed.
2021  */
2022 static void _opp_put_supported_hw(struct opp_table *opp_table)
2023 {
2024 	if (opp_table->supported_hw) {
2025 		kfree(opp_table->supported_hw);
2026 		opp_table->supported_hw = NULL;
2027 		opp_table->supported_hw_count = 0;
2028 	}
2029 }
2030 
2031 /**
2032  * _opp_set_prop_name() - Set prop-extn name
2033  * @dev: Device for which the prop-name has to be set.
2034  * @name: name to postfix to properties.
2035  *
2036  * This is required only for the V2 bindings, and it enables a platform to
2037  * specify the extn to be used for certain property names. The properties to
2038  * which the extension will apply are opp-microvolt and opp-microamp. OPP core
2039  * should postfix the property name with -<name> while looking for them.
2040  */
2041 static int _opp_set_prop_name(struct opp_table *opp_table, const char *name)
2042 {
2043 	/* Another CPU that shares the OPP table has set the property ? */
2044 	if (!opp_table->prop_name) {
2045 		opp_table->prop_name = kstrdup(name, GFP_KERNEL);
2046 		if (!opp_table->prop_name)
2047 			return -ENOMEM;
2048 	}
2049 
2050 	return 0;
2051 }
2052 
2053 /**
2054  * _opp_put_prop_name() - Releases resources blocked for prop-name
2055  * @opp_table: OPP table returned by _opp_set_prop_name().
2056  *
2057  * This is required only for the V2 bindings, and is called for a matching
2058  * _opp_set_prop_name(). Until this is called, the opp_table structure
2059  * will not be freed.
2060  */
2061 static void _opp_put_prop_name(struct opp_table *opp_table)
2062 {
2063 	if (opp_table->prop_name) {
2064 		kfree(opp_table->prop_name);
2065 		opp_table->prop_name = NULL;
2066 	}
2067 }
2068 
2069 /**
2070  * _opp_set_regulators() - Set regulator names for the device
2071  * @dev: Device for which regulator name is being set.
2072  * @names: Array of pointers to the names of the regulator.
2073  * @count: Number of regulators.
2074  *
2075  * In order to support OPP switching, OPP layer needs to know the name of the
2076  * device's regulators, as the core would be required to switch voltages as
2077  * well.
2078  *
2079  * This must be called before any OPPs are initialized for the device.
2080  */
2081 static int _opp_set_regulators(struct opp_table *opp_table, struct device *dev,
2082 			       const char * const names[])
2083 {
2084 	const char * const *temp = names;
2085 	struct regulator *reg;
2086 	int count = 0, ret, i;
2087 
2088 	/* Count number of regulators */
2089 	while (*temp++)
2090 		count++;
2091 
2092 	if (!count)
2093 		return -EINVAL;
2094 
2095 	/* Another CPU that shares the OPP table has set the regulators ? */
2096 	if (opp_table->regulators)
2097 		return 0;
2098 
2099 	opp_table->regulators = kmalloc_array(count,
2100 					      sizeof(*opp_table->regulators),
2101 					      GFP_KERNEL);
2102 	if (!opp_table->regulators)
2103 		return -ENOMEM;
2104 
2105 	for (i = 0; i < count; i++) {
2106 		reg = regulator_get_optional(dev, names[i]);
2107 		if (IS_ERR(reg)) {
2108 			ret = dev_err_probe(dev, PTR_ERR(reg),
2109 					    "%s: no regulator (%s) found\n",
2110 					    __func__, names[i]);
2111 			goto free_regulators;
2112 		}
2113 
2114 		opp_table->regulators[i] = reg;
2115 	}
2116 
2117 	opp_table->regulator_count = count;
2118 
2119 	/* Set generic config_regulators() for single regulators here */
2120 	if (count == 1)
2121 		opp_table->config_regulators = _opp_config_regulator_single;
2122 
2123 	return 0;
2124 
2125 free_regulators:
2126 	while (i != 0)
2127 		regulator_put(opp_table->regulators[--i]);
2128 
2129 	kfree(opp_table->regulators);
2130 	opp_table->regulators = NULL;
2131 	opp_table->regulator_count = -1;
2132 
2133 	return ret;
2134 }
2135 
2136 /**
2137  * _opp_put_regulators() - Releases resources blocked for regulator
2138  * @opp_table: OPP table returned from _opp_set_regulators().
2139  */
2140 static void _opp_put_regulators(struct opp_table *opp_table)
2141 {
2142 	int i;
2143 
2144 	if (!opp_table->regulators)
2145 		return;
2146 
2147 	if (opp_table->enabled) {
2148 		for (i = opp_table->regulator_count - 1; i >= 0; i--)
2149 			regulator_disable(opp_table->regulators[i]);
2150 	}
2151 
2152 	for (i = opp_table->regulator_count - 1; i >= 0; i--)
2153 		regulator_put(opp_table->regulators[i]);
2154 
2155 	kfree(opp_table->regulators);
2156 	opp_table->regulators = NULL;
2157 	opp_table->regulator_count = -1;
2158 }
2159 
2160 static void _put_clks(struct opp_table *opp_table, int count)
2161 {
2162 	int i;
2163 
2164 	for (i = count - 1; i >= 0; i--)
2165 		clk_put(opp_table->clks[i]);
2166 
2167 	kfree(opp_table->clks);
2168 	opp_table->clks = NULL;
2169 }
2170 
2171 /**
2172  * _opp_set_clknames() - Set clk names for the device
2173  * @dev: Device for which clk names is being set.
2174  * @names: Clk names.
2175  *
2176  * In order to support OPP switching, OPP layer needs to get pointers to the
2177  * clocks for the device. Simple cases work fine without using this routine
2178  * (i.e. by passing connection-id as NULL), but for a device with multiple
2179  * clocks available, the OPP core needs to know the exact names of the clks to
2180  * use.
2181  *
2182  * This must be called before any OPPs are initialized for the device.
2183  */
2184 static int _opp_set_clknames(struct opp_table *opp_table, struct device *dev,
2185 			     const char * const names[],
2186 			     config_clks_t config_clks)
2187 {
2188 	const char * const *temp = names;
2189 	int count = 0, ret, i;
2190 	struct clk *clk;
2191 
2192 	/* Count number of clks */
2193 	while (*temp++)
2194 		count++;
2195 
2196 	/*
2197 	 * This is a special case where we have a single clock, whose connection
2198 	 * id name is NULL, i.e. first two entries are NULL in the array.
2199 	 */
2200 	if (!count && !names[1])
2201 		count = 1;
2202 
2203 	/* Fail early for invalid configurations */
2204 	if (!count || (!config_clks && count > 1))
2205 		return -EINVAL;
2206 
2207 	/* Another CPU that shares the OPP table has set the clkname ? */
2208 	if (opp_table->clks)
2209 		return 0;
2210 
2211 	opp_table->clks = kmalloc_array(count, sizeof(*opp_table->clks),
2212 					GFP_KERNEL);
2213 	if (!opp_table->clks)
2214 		return -ENOMEM;
2215 
2216 	/* Find clks for the device */
2217 	for (i = 0; i < count; i++) {
2218 		clk = clk_get(dev, names[i]);
2219 		if (IS_ERR(clk)) {
2220 			ret = dev_err_probe(dev, PTR_ERR(clk),
2221 					    "%s: Couldn't find clock with name: %s\n",
2222 					    __func__, names[i]);
2223 			goto free_clks;
2224 		}
2225 
2226 		opp_table->clks[i] = clk;
2227 	}
2228 
2229 	opp_table->clk_count = count;
2230 	opp_table->config_clks = config_clks;
2231 
2232 	/* Set generic single clk set here */
2233 	if (count == 1) {
2234 		if (!opp_table->config_clks)
2235 			opp_table->config_clks = _opp_config_clk_single;
2236 
2237 		/*
2238 		 * We could have just dropped the "clk" field and used "clks"
2239 		 * everywhere. Instead we kept the "clk" field around for
2240 		 * following reasons:
2241 		 *
2242 		 * - avoiding clks[0] everywhere else.
2243 		 * - not running single clk helpers for multiple clk usecase by
2244 		 *   mistake.
2245 		 *
2246 		 * Since this is single-clk case, just update the clk pointer
2247 		 * too.
2248 		 */
2249 		opp_table->clk = opp_table->clks[0];
2250 	}
2251 
2252 	return 0;
2253 
2254 free_clks:
2255 	_put_clks(opp_table, i);
2256 	return ret;
2257 }
2258 
2259 /**
2260  * _opp_put_clknames() - Releases resources blocked for clks.
2261  * @opp_table: OPP table returned from _opp_set_clknames().
2262  */
2263 static void _opp_put_clknames(struct opp_table *opp_table)
2264 {
2265 	if (!opp_table->clks)
2266 		return;
2267 
2268 	opp_table->config_clks = NULL;
2269 	opp_table->clk = ERR_PTR(-ENODEV);
2270 
2271 	_put_clks(opp_table, opp_table->clk_count);
2272 }
2273 
2274 /**
2275  * _opp_set_config_regulators_helper() - Register custom set regulator helper.
2276  * @dev: Device for which the helper is getting registered.
2277  * @config_regulators: Custom set regulator helper.
2278  *
2279  * This is useful to support platforms with multiple regulators per device.
2280  *
2281  * This must be called before any OPPs are initialized for the device.
2282  */
2283 static int _opp_set_config_regulators_helper(struct opp_table *opp_table,
2284 		struct device *dev, config_regulators_t config_regulators)
2285 {
2286 	/* Another CPU that shares the OPP table has set the helper ? */
2287 	if (!opp_table->config_regulators)
2288 		opp_table->config_regulators = config_regulators;
2289 
2290 	return 0;
2291 }
2292 
2293 /**
2294  * _opp_put_config_regulators_helper() - Releases resources blocked for
2295  *					 config_regulators helper.
2296  * @opp_table: OPP table returned from _opp_set_config_regulators_helper().
2297  *
2298  * Release resources blocked for platform specific config_regulators helper.
2299  */
2300 static void _opp_put_config_regulators_helper(struct opp_table *opp_table)
2301 {
2302 	if (opp_table->config_regulators)
2303 		opp_table->config_regulators = NULL;
2304 }
2305 
2306 static void _detach_genpd(struct opp_table *opp_table)
2307 {
2308 	int index;
2309 
2310 	if (!opp_table->genpd_virt_devs)
2311 		return;
2312 
2313 	for (index = 0; index < opp_table->required_opp_count; index++) {
2314 		if (!opp_table->genpd_virt_devs[index])
2315 			continue;
2316 
2317 		dev_pm_domain_detach(opp_table->genpd_virt_devs[index], false);
2318 		opp_table->genpd_virt_devs[index] = NULL;
2319 	}
2320 
2321 	kfree(opp_table->genpd_virt_devs);
2322 	opp_table->genpd_virt_devs = NULL;
2323 }
2324 
2325 /**
2326  * _opp_attach_genpd - Attach genpd(s) for the device and save virtual device pointer
2327  * @dev: Consumer device for which the genpd is getting attached.
2328  * @names: Null terminated array of pointers containing names of genpd to attach.
2329  * @virt_devs: Pointer to return the array of virtual devices.
2330  *
2331  * Multiple generic power domains for a device are supported with the help of
2332  * virtual genpd devices, which are created for each consumer device - genpd
2333  * pair. These are the device structures which are attached to the power domain
2334  * and are required by the OPP core to set the performance state of the genpd.
2335  * The same API also works for the case where single genpd is available and so
2336  * we don't need to support that separately.
2337  *
2338  * This helper will normally be called by the consumer driver of the device
2339  * "dev", as only that has details of the genpd names.
2340  *
2341  * This helper needs to be called once with a list of all genpd to attach.
2342  * Otherwise the original device structure will be used instead by the OPP core.
2343  *
2344  * The order of entries in the names array must match the order in which
2345  * "required-opps" are added in DT.
2346  */
2347 static int _opp_attach_genpd(struct opp_table *opp_table, struct device *dev,
2348 			const char * const *names, struct device ***virt_devs)
2349 {
2350 	struct device *virt_dev;
2351 	int index = 0, ret = -EINVAL;
2352 	const char * const *name = names;
2353 
2354 	if (opp_table->genpd_virt_devs)
2355 		return 0;
2356 
2357 	/*
2358 	 * If the genpd's OPP table isn't already initialized, parsing of the
2359 	 * required-opps fail for dev. We should retry this after genpd's OPP
2360 	 * table is added.
2361 	 */
2362 	if (!opp_table->required_opp_count)
2363 		return -EPROBE_DEFER;
2364 
2365 	mutex_lock(&opp_table->genpd_virt_dev_lock);
2366 
2367 	opp_table->genpd_virt_devs = kcalloc(opp_table->required_opp_count,
2368 					     sizeof(*opp_table->genpd_virt_devs),
2369 					     GFP_KERNEL);
2370 	if (!opp_table->genpd_virt_devs)
2371 		goto unlock;
2372 
2373 	while (*name) {
2374 		if (index >= opp_table->required_opp_count) {
2375 			dev_err(dev, "Index can't be greater than required-opp-count - 1, %s (%d : %d)\n",
2376 				*name, opp_table->required_opp_count, index);
2377 			goto err;
2378 		}
2379 
2380 		virt_dev = dev_pm_domain_attach_by_name(dev, *name);
2381 		if (IS_ERR_OR_NULL(virt_dev)) {
2382 			ret = PTR_ERR(virt_dev) ? : -ENODEV;
2383 			dev_err(dev, "Couldn't attach to pm_domain: %d\n", ret);
2384 			goto err;
2385 		}
2386 
2387 		opp_table->genpd_virt_devs[index] = virt_dev;
2388 		index++;
2389 		name++;
2390 	}
2391 
2392 	if (virt_devs)
2393 		*virt_devs = opp_table->genpd_virt_devs;
2394 	mutex_unlock(&opp_table->genpd_virt_dev_lock);
2395 
2396 	return 0;
2397 
2398 err:
2399 	_detach_genpd(opp_table);
2400 unlock:
2401 	mutex_unlock(&opp_table->genpd_virt_dev_lock);
2402 	return ret;
2403 
2404 }
2405 
2406 /**
2407  * _opp_detach_genpd() - Detach genpd(s) from the device.
2408  * @opp_table: OPP table returned by _opp_attach_genpd().
2409  *
2410  * This detaches the genpd(s), resets the virtual device pointers, and puts the
2411  * OPP table.
2412  */
2413 static void _opp_detach_genpd(struct opp_table *opp_table)
2414 {
2415 	/*
2416 	 * Acquire genpd_virt_dev_lock to make sure virt_dev isn't getting
2417 	 * used in parallel.
2418 	 */
2419 	mutex_lock(&opp_table->genpd_virt_dev_lock);
2420 	_detach_genpd(opp_table);
2421 	mutex_unlock(&opp_table->genpd_virt_dev_lock);
2422 }
2423 
2424 static void _opp_clear_config(struct opp_config_data *data)
2425 {
2426 	if (data->flags & OPP_CONFIG_GENPD)
2427 		_opp_detach_genpd(data->opp_table);
2428 	if (data->flags & OPP_CONFIG_REGULATOR)
2429 		_opp_put_regulators(data->opp_table);
2430 	if (data->flags & OPP_CONFIG_SUPPORTED_HW)
2431 		_opp_put_supported_hw(data->opp_table);
2432 	if (data->flags & OPP_CONFIG_REGULATOR_HELPER)
2433 		_opp_put_config_regulators_helper(data->opp_table);
2434 	if (data->flags & OPP_CONFIG_PROP_NAME)
2435 		_opp_put_prop_name(data->opp_table);
2436 	if (data->flags & OPP_CONFIG_CLK)
2437 		_opp_put_clknames(data->opp_table);
2438 
2439 	dev_pm_opp_put_opp_table(data->opp_table);
2440 	kfree(data);
2441 }
2442 
2443 /**
2444  * dev_pm_opp_set_config() - Set OPP configuration for the device.
2445  * @dev: Device for which configuration is being set.
2446  * @config: OPP configuration.
2447  *
2448  * This allows all device OPP configurations to be performed at once.
2449  *
2450  * This must be called before any OPPs are initialized for the device. This may
2451  * be called multiple times for the same OPP table, for example once for each
2452  * CPU that share the same table. This must be balanced by the same number of
2453  * calls to dev_pm_opp_clear_config() in order to free the OPP table properly.
2454  *
2455  * This returns a token to the caller, which must be passed to
2456  * dev_pm_opp_clear_config() to free the resources later. The value of the
2457  * returned token will be >= 1 for success and negative for errors. The minimum
2458  * value of 1 is chosen here to make it easy for callers to manage the resource.
2459  */
2460 int dev_pm_opp_set_config(struct device *dev, struct dev_pm_opp_config *config)
2461 {
2462 	struct opp_table *opp_table;
2463 	struct opp_config_data *data;
2464 	unsigned int id;
2465 	int ret;
2466 
2467 	data = kmalloc(sizeof(*data), GFP_KERNEL);
2468 	if (!data)
2469 		return -ENOMEM;
2470 
2471 	opp_table = _add_opp_table(dev, false);
2472 	if (IS_ERR(opp_table)) {
2473 		kfree(data);
2474 		return PTR_ERR(opp_table);
2475 	}
2476 
2477 	data->opp_table = opp_table;
2478 	data->flags = 0;
2479 
2480 	/* This should be called before OPPs are initialized */
2481 	if (WARN_ON(!list_empty(&opp_table->opp_list))) {
2482 		ret = -EBUSY;
2483 		goto err;
2484 	}
2485 
2486 	/* Configure clocks */
2487 	if (config->clk_names) {
2488 		ret = _opp_set_clknames(opp_table, dev, config->clk_names,
2489 					config->config_clks);
2490 		if (ret)
2491 			goto err;
2492 
2493 		data->flags |= OPP_CONFIG_CLK;
2494 	} else if (config->config_clks) {
2495 		/* Don't allow config callback without clocks */
2496 		ret = -EINVAL;
2497 		goto err;
2498 	}
2499 
2500 	/* Configure property names */
2501 	if (config->prop_name) {
2502 		ret = _opp_set_prop_name(opp_table, config->prop_name);
2503 		if (ret)
2504 			goto err;
2505 
2506 		data->flags |= OPP_CONFIG_PROP_NAME;
2507 	}
2508 
2509 	/* Configure config_regulators helper */
2510 	if (config->config_regulators) {
2511 		ret = _opp_set_config_regulators_helper(opp_table, dev,
2512 						config->config_regulators);
2513 		if (ret)
2514 			goto err;
2515 
2516 		data->flags |= OPP_CONFIG_REGULATOR_HELPER;
2517 	}
2518 
2519 	/* Configure supported hardware */
2520 	if (config->supported_hw) {
2521 		ret = _opp_set_supported_hw(opp_table, config->supported_hw,
2522 					    config->supported_hw_count);
2523 		if (ret)
2524 			goto err;
2525 
2526 		data->flags |= OPP_CONFIG_SUPPORTED_HW;
2527 	}
2528 
2529 	/* Configure supplies */
2530 	if (config->regulator_names) {
2531 		ret = _opp_set_regulators(opp_table, dev,
2532 					  config->regulator_names);
2533 		if (ret)
2534 			goto err;
2535 
2536 		data->flags |= OPP_CONFIG_REGULATOR;
2537 	}
2538 
2539 	/* Attach genpds */
2540 	if (config->genpd_names) {
2541 		ret = _opp_attach_genpd(opp_table, dev, config->genpd_names,
2542 					config->virt_devs);
2543 		if (ret)
2544 			goto err;
2545 
2546 		data->flags |= OPP_CONFIG_GENPD;
2547 	}
2548 
2549 	ret = xa_alloc(&opp_configs, &id, data, XA_LIMIT(1, INT_MAX),
2550 		       GFP_KERNEL);
2551 	if (ret)
2552 		goto err;
2553 
2554 	return id;
2555 
2556 err:
2557 	_opp_clear_config(data);
2558 	return ret;
2559 }
2560 EXPORT_SYMBOL_GPL(dev_pm_opp_set_config);
2561 
2562 /**
2563  * dev_pm_opp_clear_config() - Releases resources blocked for OPP configuration.
2564  * @opp_table: OPP table returned from dev_pm_opp_set_config().
2565  *
2566  * This allows all device OPP configurations to be cleared at once. This must be
2567  * called once for each call made to dev_pm_opp_set_config(), in order to free
2568  * the OPPs properly.
2569  *
2570  * Currently the first call itself ends up freeing all the OPP configurations,
2571  * while the later ones only drop the OPP table reference. This works well for
2572  * now as we would never want to use an half initialized OPP table and want to
2573  * remove the configurations together.
2574  */
2575 void dev_pm_opp_clear_config(int token)
2576 {
2577 	struct opp_config_data *data;
2578 
2579 	/*
2580 	 * This lets the callers call this unconditionally and keep their code
2581 	 * simple.
2582 	 */
2583 	if (unlikely(token <= 0))
2584 		return;
2585 
2586 	data = xa_erase(&opp_configs, token);
2587 	if (WARN_ON(!data))
2588 		return;
2589 
2590 	_opp_clear_config(data);
2591 }
2592 EXPORT_SYMBOL_GPL(dev_pm_opp_clear_config);
2593 
2594 static void devm_pm_opp_config_release(void *token)
2595 {
2596 	dev_pm_opp_clear_config((unsigned long)token);
2597 }
2598 
2599 /**
2600  * devm_pm_opp_set_config() - Set OPP configuration for the device.
2601  * @dev: Device for which configuration is being set.
2602  * @config: OPP configuration.
2603  *
2604  * This allows all device OPP configurations to be performed at once.
2605  * This is a resource-managed variant of dev_pm_opp_set_config().
2606  *
2607  * Return: 0 on success and errorno otherwise.
2608  */
2609 int devm_pm_opp_set_config(struct device *dev, struct dev_pm_opp_config *config)
2610 {
2611 	int token = dev_pm_opp_set_config(dev, config);
2612 
2613 	if (token < 0)
2614 		return token;
2615 
2616 	return devm_add_action_or_reset(dev, devm_pm_opp_config_release,
2617 					(void *) ((unsigned long) token));
2618 }
2619 EXPORT_SYMBOL_GPL(devm_pm_opp_set_config);
2620 
2621 /**
2622  * dev_pm_opp_xlate_required_opp() - Find required OPP for @src_table OPP.
2623  * @src_table: OPP table which has @dst_table as one of its required OPP table.
2624  * @dst_table: Required OPP table of the @src_table.
2625  * @src_opp: OPP from the @src_table.
2626  *
2627  * This function returns the OPP (present in @dst_table) pointed out by the
2628  * "required-opps" property of the @src_opp (present in @src_table).
2629  *
2630  * The callers are required to call dev_pm_opp_put() for the returned OPP after
2631  * use.
2632  *
2633  * Return: pointer to 'struct dev_pm_opp' on success and errorno otherwise.
2634  */
2635 struct dev_pm_opp *dev_pm_opp_xlate_required_opp(struct opp_table *src_table,
2636 						 struct opp_table *dst_table,
2637 						 struct dev_pm_opp *src_opp)
2638 {
2639 	struct dev_pm_opp *opp, *dest_opp = ERR_PTR(-ENODEV);
2640 	int i;
2641 
2642 	if (!src_table || !dst_table || !src_opp ||
2643 	    !src_table->required_opp_tables)
2644 		return ERR_PTR(-EINVAL);
2645 
2646 	/* required-opps not fully initialized yet */
2647 	if (lazy_linking_pending(src_table))
2648 		return ERR_PTR(-EBUSY);
2649 
2650 	for (i = 0; i < src_table->required_opp_count; i++) {
2651 		if (src_table->required_opp_tables[i] == dst_table) {
2652 			mutex_lock(&src_table->lock);
2653 
2654 			list_for_each_entry(opp, &src_table->opp_list, node) {
2655 				if (opp == src_opp) {
2656 					dest_opp = opp->required_opps[i];
2657 					dev_pm_opp_get(dest_opp);
2658 					break;
2659 				}
2660 			}
2661 
2662 			mutex_unlock(&src_table->lock);
2663 			break;
2664 		}
2665 	}
2666 
2667 	if (IS_ERR(dest_opp)) {
2668 		pr_err("%s: Couldn't find matching OPP (%p: %p)\n", __func__,
2669 		       src_table, dst_table);
2670 	}
2671 
2672 	return dest_opp;
2673 }
2674 EXPORT_SYMBOL_GPL(dev_pm_opp_xlate_required_opp);
2675 
2676 /**
2677  * dev_pm_opp_xlate_performance_state() - Find required OPP's pstate for src_table.
2678  * @src_table: OPP table which has dst_table as one of its required OPP table.
2679  * @dst_table: Required OPP table of the src_table.
2680  * @pstate: Current performance state of the src_table.
2681  *
2682  * This Returns pstate of the OPP (present in @dst_table) pointed out by the
2683  * "required-opps" property of the OPP (present in @src_table) which has
2684  * performance state set to @pstate.
2685  *
2686  * Return: Zero or positive performance state on success, otherwise negative
2687  * value on errors.
2688  */
2689 int dev_pm_opp_xlate_performance_state(struct opp_table *src_table,
2690 				       struct opp_table *dst_table,
2691 				       unsigned int pstate)
2692 {
2693 	struct dev_pm_opp *opp;
2694 	int dest_pstate = -EINVAL;
2695 	int i;
2696 
2697 	/*
2698 	 * Normally the src_table will have the "required_opps" property set to
2699 	 * point to one of the OPPs in the dst_table, but in some cases the
2700 	 * genpd and its master have one to one mapping of performance states
2701 	 * and so none of them have the "required-opps" property set. Return the
2702 	 * pstate of the src_table as it is in such cases.
2703 	 */
2704 	if (!src_table || !src_table->required_opp_count)
2705 		return pstate;
2706 
2707 	/* Both OPP tables must belong to genpds */
2708 	if (unlikely(!src_table->is_genpd || !dst_table->is_genpd)) {
2709 		pr_err("%s: Performance state is only valid for genpds.\n", __func__);
2710 		return -EINVAL;
2711 	}
2712 
2713 	/* required-opps not fully initialized yet */
2714 	if (lazy_linking_pending(src_table))
2715 		return -EBUSY;
2716 
2717 	for (i = 0; i < src_table->required_opp_count; i++) {
2718 		if (src_table->required_opp_tables[i]->np == dst_table->np)
2719 			break;
2720 	}
2721 
2722 	if (unlikely(i == src_table->required_opp_count)) {
2723 		pr_err("%s: Couldn't find matching OPP table (%p: %p)\n",
2724 		       __func__, src_table, dst_table);
2725 		return -EINVAL;
2726 	}
2727 
2728 	mutex_lock(&src_table->lock);
2729 
2730 	list_for_each_entry(opp, &src_table->opp_list, node) {
2731 		if (opp->level == pstate) {
2732 			dest_pstate = opp->required_opps[i]->level;
2733 			goto unlock;
2734 		}
2735 	}
2736 
2737 	pr_err("%s: Couldn't find matching OPP (%p: %p)\n", __func__, src_table,
2738 	       dst_table);
2739 
2740 unlock:
2741 	mutex_unlock(&src_table->lock);
2742 
2743 	return dest_pstate;
2744 }
2745 
2746 /**
2747  * dev_pm_opp_add()  - Add an OPP table from a table definitions
2748  * @dev:	device for which we do this operation
2749  * @freq:	Frequency in Hz for this OPP
2750  * @u_volt:	Voltage in uVolts for this OPP
2751  *
2752  * This function adds an opp definition to the opp table and returns status.
2753  * The opp is made available by default and it can be controlled using
2754  * dev_pm_opp_enable/disable functions.
2755  *
2756  * Return:
2757  * 0		On success OR
2758  *		Duplicate OPPs (both freq and volt are same) and opp->available
2759  * -EEXIST	Freq are same and volt are different OR
2760  *		Duplicate OPPs (both freq and volt are same) and !opp->available
2761  * -ENOMEM	Memory allocation failure
2762  */
2763 int dev_pm_opp_add(struct device *dev, unsigned long freq, unsigned long u_volt)
2764 {
2765 	struct opp_table *opp_table;
2766 	int ret;
2767 
2768 	opp_table = _add_opp_table(dev, true);
2769 	if (IS_ERR(opp_table))
2770 		return PTR_ERR(opp_table);
2771 
2772 	/* Fix regulator count for dynamic OPPs */
2773 	opp_table->regulator_count = 1;
2774 
2775 	ret = _opp_add_v1(opp_table, dev, freq, u_volt, true);
2776 	if (ret)
2777 		dev_pm_opp_put_opp_table(opp_table);
2778 
2779 	return ret;
2780 }
2781 EXPORT_SYMBOL_GPL(dev_pm_opp_add);
2782 
2783 /**
2784  * _opp_set_availability() - helper to set the availability of an opp
2785  * @dev:		device for which we do this operation
2786  * @freq:		OPP frequency to modify availability
2787  * @availability_req:	availability status requested for this opp
2788  *
2789  * Set the availability of an OPP, opp_{enable,disable} share a common logic
2790  * which is isolated here.
2791  *
2792  * Return: -EINVAL for bad pointers, -ENOMEM if no memory available for the
2793  * copy operation, returns 0 if no modification was done OR modification was
2794  * successful.
2795  */
2796 static int _opp_set_availability(struct device *dev, unsigned long freq,
2797 				 bool availability_req)
2798 {
2799 	struct opp_table *opp_table;
2800 	struct dev_pm_opp *tmp_opp, *opp = ERR_PTR(-ENODEV);
2801 	int r = 0;
2802 
2803 	/* Find the opp_table */
2804 	opp_table = _find_opp_table(dev);
2805 	if (IS_ERR(opp_table)) {
2806 		r = PTR_ERR(opp_table);
2807 		dev_warn(dev, "%s: Device OPP not found (%d)\n", __func__, r);
2808 		return r;
2809 	}
2810 
2811 	if (!assert_single_clk(opp_table)) {
2812 		r = -EINVAL;
2813 		goto put_table;
2814 	}
2815 
2816 	mutex_lock(&opp_table->lock);
2817 
2818 	/* Do we have the frequency? */
2819 	list_for_each_entry(tmp_opp, &opp_table->opp_list, node) {
2820 		if (tmp_opp->rates[0] == freq) {
2821 			opp = tmp_opp;
2822 			break;
2823 		}
2824 	}
2825 
2826 	if (IS_ERR(opp)) {
2827 		r = PTR_ERR(opp);
2828 		goto unlock;
2829 	}
2830 
2831 	/* Is update really needed? */
2832 	if (opp->available == availability_req)
2833 		goto unlock;
2834 
2835 	opp->available = availability_req;
2836 
2837 	dev_pm_opp_get(opp);
2838 	mutex_unlock(&opp_table->lock);
2839 
2840 	/* Notify the change of the OPP availability */
2841 	if (availability_req)
2842 		blocking_notifier_call_chain(&opp_table->head, OPP_EVENT_ENABLE,
2843 					     opp);
2844 	else
2845 		blocking_notifier_call_chain(&opp_table->head,
2846 					     OPP_EVENT_DISABLE, opp);
2847 
2848 	dev_pm_opp_put(opp);
2849 	goto put_table;
2850 
2851 unlock:
2852 	mutex_unlock(&opp_table->lock);
2853 put_table:
2854 	dev_pm_opp_put_opp_table(opp_table);
2855 	return r;
2856 }
2857 
2858 /**
2859  * dev_pm_opp_adjust_voltage() - helper to change the voltage of an OPP
2860  * @dev:		device for which we do this operation
2861  * @freq:		OPP frequency to adjust voltage of
2862  * @u_volt:		new OPP target voltage
2863  * @u_volt_min:		new OPP min voltage
2864  * @u_volt_max:		new OPP max voltage
2865  *
2866  * Return: -EINVAL for bad pointers, -ENOMEM if no memory available for the
2867  * copy operation, returns 0 if no modifcation was done OR modification was
2868  * successful.
2869  */
2870 int dev_pm_opp_adjust_voltage(struct device *dev, unsigned long freq,
2871 			      unsigned long u_volt, unsigned long u_volt_min,
2872 			      unsigned long u_volt_max)
2873 
2874 {
2875 	struct opp_table *opp_table;
2876 	struct dev_pm_opp *tmp_opp, *opp = ERR_PTR(-ENODEV);
2877 	int r = 0;
2878 
2879 	/* Find the opp_table */
2880 	opp_table = _find_opp_table(dev);
2881 	if (IS_ERR(opp_table)) {
2882 		r = PTR_ERR(opp_table);
2883 		dev_warn(dev, "%s: Device OPP not found (%d)\n", __func__, r);
2884 		return r;
2885 	}
2886 
2887 	if (!assert_single_clk(opp_table)) {
2888 		r = -EINVAL;
2889 		goto put_table;
2890 	}
2891 
2892 	mutex_lock(&opp_table->lock);
2893 
2894 	/* Do we have the frequency? */
2895 	list_for_each_entry(tmp_opp, &opp_table->opp_list, node) {
2896 		if (tmp_opp->rates[0] == freq) {
2897 			opp = tmp_opp;
2898 			break;
2899 		}
2900 	}
2901 
2902 	if (IS_ERR(opp)) {
2903 		r = PTR_ERR(opp);
2904 		goto adjust_unlock;
2905 	}
2906 
2907 	/* Is update really needed? */
2908 	if (opp->supplies->u_volt == u_volt)
2909 		goto adjust_unlock;
2910 
2911 	opp->supplies->u_volt = u_volt;
2912 	opp->supplies->u_volt_min = u_volt_min;
2913 	opp->supplies->u_volt_max = u_volt_max;
2914 
2915 	dev_pm_opp_get(opp);
2916 	mutex_unlock(&opp_table->lock);
2917 
2918 	/* Notify the voltage change of the OPP */
2919 	blocking_notifier_call_chain(&opp_table->head, OPP_EVENT_ADJUST_VOLTAGE,
2920 				     opp);
2921 
2922 	dev_pm_opp_put(opp);
2923 	goto put_table;
2924 
2925 adjust_unlock:
2926 	mutex_unlock(&opp_table->lock);
2927 put_table:
2928 	dev_pm_opp_put_opp_table(opp_table);
2929 	return r;
2930 }
2931 EXPORT_SYMBOL_GPL(dev_pm_opp_adjust_voltage);
2932 
2933 /**
2934  * dev_pm_opp_enable() - Enable a specific OPP
2935  * @dev:	device for which we do this operation
2936  * @freq:	OPP frequency to enable
2937  *
2938  * Enables a provided opp. If the operation is valid, this returns 0, else the
2939  * corresponding error value. It is meant to be used for users an OPP available
2940  * after being temporarily made unavailable with dev_pm_opp_disable.
2941  *
2942  * Return: -EINVAL for bad pointers, -ENOMEM if no memory available for the
2943  * copy operation, returns 0 if no modification was done OR modification was
2944  * successful.
2945  */
2946 int dev_pm_opp_enable(struct device *dev, unsigned long freq)
2947 {
2948 	return _opp_set_availability(dev, freq, true);
2949 }
2950 EXPORT_SYMBOL_GPL(dev_pm_opp_enable);
2951 
2952 /**
2953  * dev_pm_opp_disable() - Disable a specific OPP
2954  * @dev:	device for which we do this operation
2955  * @freq:	OPP frequency to disable
2956  *
2957  * Disables a provided opp. If the operation is valid, this returns
2958  * 0, else the corresponding error value. It is meant to be a temporary
2959  * control by users to make this OPP not available until the circumstances are
2960  * right to make it available again (with a call to dev_pm_opp_enable).
2961  *
2962  * Return: -EINVAL for bad pointers, -ENOMEM if no memory available for the
2963  * copy operation, returns 0 if no modification was done OR modification was
2964  * successful.
2965  */
2966 int dev_pm_opp_disable(struct device *dev, unsigned long freq)
2967 {
2968 	return _opp_set_availability(dev, freq, false);
2969 }
2970 EXPORT_SYMBOL_GPL(dev_pm_opp_disable);
2971 
2972 /**
2973  * dev_pm_opp_register_notifier() - Register OPP notifier for the device
2974  * @dev:	Device for which notifier needs to be registered
2975  * @nb:		Notifier block to be registered
2976  *
2977  * Return: 0 on success or a negative error value.
2978  */
2979 int dev_pm_opp_register_notifier(struct device *dev, struct notifier_block *nb)
2980 {
2981 	struct opp_table *opp_table;
2982 	int ret;
2983 
2984 	opp_table = _find_opp_table(dev);
2985 	if (IS_ERR(opp_table))
2986 		return PTR_ERR(opp_table);
2987 
2988 	ret = blocking_notifier_chain_register(&opp_table->head, nb);
2989 
2990 	dev_pm_opp_put_opp_table(opp_table);
2991 
2992 	return ret;
2993 }
2994 EXPORT_SYMBOL(dev_pm_opp_register_notifier);
2995 
2996 /**
2997  * dev_pm_opp_unregister_notifier() - Unregister OPP notifier for the device
2998  * @dev:	Device for which notifier needs to be unregistered
2999  * @nb:		Notifier block to be unregistered
3000  *
3001  * Return: 0 on success or a negative error value.
3002  */
3003 int dev_pm_opp_unregister_notifier(struct device *dev,
3004 				   struct notifier_block *nb)
3005 {
3006 	struct opp_table *opp_table;
3007 	int ret;
3008 
3009 	opp_table = _find_opp_table(dev);
3010 	if (IS_ERR(opp_table))
3011 		return PTR_ERR(opp_table);
3012 
3013 	ret = blocking_notifier_chain_unregister(&opp_table->head, nb);
3014 
3015 	dev_pm_opp_put_opp_table(opp_table);
3016 
3017 	return ret;
3018 }
3019 EXPORT_SYMBOL(dev_pm_opp_unregister_notifier);
3020 
3021 /**
3022  * dev_pm_opp_remove_table() - Free all OPPs associated with the device
3023  * @dev:	device pointer used to lookup OPP table.
3024  *
3025  * Free both OPPs created using static entries present in DT and the
3026  * dynamically added entries.
3027  */
3028 void dev_pm_opp_remove_table(struct device *dev)
3029 {
3030 	struct opp_table *opp_table;
3031 
3032 	/* Check for existing table for 'dev' */
3033 	opp_table = _find_opp_table(dev);
3034 	if (IS_ERR(opp_table)) {
3035 		int error = PTR_ERR(opp_table);
3036 
3037 		if (error != -ENODEV)
3038 			WARN(1, "%s: opp_table: %d\n",
3039 			     IS_ERR_OR_NULL(dev) ?
3040 					"Invalid device" : dev_name(dev),
3041 			     error);
3042 		return;
3043 	}
3044 
3045 	/*
3046 	 * Drop the extra reference only if the OPP table was successfully added
3047 	 * with dev_pm_opp_of_add_table() earlier.
3048 	 **/
3049 	if (_opp_remove_all_static(opp_table))
3050 		dev_pm_opp_put_opp_table(opp_table);
3051 
3052 	/* Drop reference taken by _find_opp_table() */
3053 	dev_pm_opp_put_opp_table(opp_table);
3054 }
3055 EXPORT_SYMBOL_GPL(dev_pm_opp_remove_table);
3056 
3057 /**
3058  * dev_pm_opp_sync_regulators() - Sync state of voltage regulators
3059  * @dev:	device for which we do this operation
3060  *
3061  * Sync voltage state of the OPP table regulators.
3062  *
3063  * Return: 0 on success or a negative error value.
3064  */
3065 int dev_pm_opp_sync_regulators(struct device *dev)
3066 {
3067 	struct opp_table *opp_table;
3068 	struct regulator *reg;
3069 	int i, ret = 0;
3070 
3071 	/* Device may not have OPP table */
3072 	opp_table = _find_opp_table(dev);
3073 	if (IS_ERR(opp_table))
3074 		return 0;
3075 
3076 	/* Regulator may not be required for the device */
3077 	if (unlikely(!opp_table->regulators))
3078 		goto put_table;
3079 
3080 	/* Nothing to sync if voltage wasn't changed */
3081 	if (!opp_table->enabled)
3082 		goto put_table;
3083 
3084 	for (i = 0; i < opp_table->regulator_count; i++) {
3085 		reg = opp_table->regulators[i];
3086 		ret = regulator_sync_voltage(reg);
3087 		if (ret)
3088 			break;
3089 	}
3090 put_table:
3091 	/* Drop reference taken by _find_opp_table() */
3092 	dev_pm_opp_put_opp_table(opp_table);
3093 
3094 	return ret;
3095 }
3096 EXPORT_SYMBOL_GPL(dev_pm_opp_sync_regulators);
3097