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