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