opp: Don't return opp_dev from _find_opp_dev()
[linux-2.6-microblaze.git] / drivers / opp / core.c
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/slab.h>
17 #include <linux/device.h>
18 #include <linux/export.h>
19 #include <linux/pm_domain.h>
20 #include <linux/regulator/consumer.h>
21
22 #include "opp.h"
23
24 /*
25  * The root of the list of all opp-tables. All opp_table structures branch off
26  * from here, with each opp_table containing the list of opps it supports in
27  * various states of availability.
28  */
29 LIST_HEAD(opp_tables);
30 /* Lock to allow exclusive modification to the device and opp lists */
31 DEFINE_MUTEX(opp_table_lock);
32 /* Flag indicating that opp_tables list is being updated at the moment */
33 static bool opp_tables_busy;
34
35 static bool _find_opp_dev(const struct device *dev, struct opp_table *opp_table)
36 {
37         struct opp_device *opp_dev;
38         bool found = false;
39
40         mutex_lock(&opp_table->lock);
41         list_for_each_entry(opp_dev, &opp_table->dev_list, node)
42                 if (opp_dev->dev == dev) {
43                         found = true;
44                         break;
45                 }
46
47         mutex_unlock(&opp_table->lock);
48         return found;
49 }
50
51 static struct opp_table *_find_opp_table_unlocked(struct device *dev)
52 {
53         struct opp_table *opp_table;
54
55         list_for_each_entry(opp_table, &opp_tables, node) {
56                 if (_find_opp_dev(dev, opp_table)) {
57                         _get_opp_table_kref(opp_table);
58                         return opp_table;
59                 }
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         struct opp_table *opp_table;
79
80         if (IS_ERR_OR_NULL(dev)) {
81                 pr_err("%s: Invalid parameters\n", __func__);
82                 return ERR_PTR(-EINVAL);
83         }
84
85         mutex_lock(&opp_table_lock);
86         opp_table = _find_opp_table_unlocked(dev);
87         mutex_unlock(&opp_table_lock);
88
89         return opp_table;
90 }
91
92 /**
93  * dev_pm_opp_get_voltage() - Gets the voltage corresponding to an opp
94  * @opp:        opp for which voltage has to be returned for
95  *
96  * Return: voltage in micro volt corresponding to the opp, else
97  * return 0
98  *
99  * This is useful only for devices with single power supply.
100  */
101 unsigned long dev_pm_opp_get_voltage(struct dev_pm_opp *opp)
102 {
103         if (IS_ERR_OR_NULL(opp)) {
104                 pr_err("%s: Invalid parameters\n", __func__);
105                 return 0;
106         }
107
108         return opp->supplies[0].u_volt;
109 }
110 EXPORT_SYMBOL_GPL(dev_pm_opp_get_voltage);
111
112 /**
113  * dev_pm_opp_get_freq() - Gets the frequency corresponding to an available opp
114  * @opp:        opp for which frequency has to be returned for
115  *
116  * Return: frequency in hertz corresponding to the opp, else
117  * return 0
118  */
119 unsigned long dev_pm_opp_get_freq(struct dev_pm_opp *opp)
120 {
121         if (IS_ERR_OR_NULL(opp)) {
122                 pr_err("%s: Invalid parameters\n", __func__);
123                 return 0;
124         }
125
126         return opp->rate;
127 }
128 EXPORT_SYMBOL_GPL(dev_pm_opp_get_freq);
129
130 /**
131  * dev_pm_opp_get_level() - Gets the level corresponding to an available opp
132  * @opp:        opp for which level value has to be returned for
133  *
134  * Return: level read from device tree corresponding to the opp, else
135  * return 0.
136  */
137 unsigned int dev_pm_opp_get_level(struct dev_pm_opp *opp)
138 {
139         if (IS_ERR_OR_NULL(opp) || !opp->available) {
140                 pr_err("%s: Invalid parameters\n", __func__);
141                 return 0;
142         }
143
144         return opp->level;
145 }
146 EXPORT_SYMBOL_GPL(dev_pm_opp_get_level);
147
148 /**
149  * dev_pm_opp_is_turbo() - Returns if opp is turbo OPP or not
150  * @opp: opp for which turbo mode is being verified
151  *
152  * Turbo OPPs are not for normal use, and can be enabled (under certain
153  * conditions) for short duration of times to finish high throughput work
154  * quickly. Running on them for longer times may overheat the chip.
155  *
156  * Return: true if opp is turbo opp, else false.
157  */
158 bool dev_pm_opp_is_turbo(struct dev_pm_opp *opp)
159 {
160         if (IS_ERR_OR_NULL(opp) || !opp->available) {
161                 pr_err("%s: Invalid parameters\n", __func__);
162                 return false;
163         }
164
165         return opp->turbo;
166 }
167 EXPORT_SYMBOL_GPL(dev_pm_opp_is_turbo);
168
169 /**
170  * dev_pm_opp_get_max_clock_latency() - Get max clock latency in nanoseconds
171  * @dev:        device for which we do this operation
172  *
173  * Return: This function returns the max clock latency in nanoseconds.
174  */
175 unsigned long dev_pm_opp_get_max_clock_latency(struct device *dev)
176 {
177         struct opp_table *opp_table;
178         unsigned long clock_latency_ns;
179
180         opp_table = _find_opp_table(dev);
181         if (IS_ERR(opp_table))
182                 return 0;
183
184         clock_latency_ns = opp_table->clock_latency_ns_max;
185
186         dev_pm_opp_put_opp_table(opp_table);
187
188         return clock_latency_ns;
189 }
190 EXPORT_SYMBOL_GPL(dev_pm_opp_get_max_clock_latency);
191
192 /**
193  * dev_pm_opp_get_max_volt_latency() - Get max voltage latency in nanoseconds
194  * @dev: device for which we do this operation
195  *
196  * Return: This function returns the max voltage latency in nanoseconds.
197  */
198 unsigned long dev_pm_opp_get_max_volt_latency(struct device *dev)
199 {
200         struct opp_table *opp_table;
201         struct dev_pm_opp *opp;
202         struct regulator *reg;
203         unsigned long latency_ns = 0;
204         int ret, i, count;
205         struct {
206                 unsigned long min;
207                 unsigned long max;
208         } *uV;
209
210         opp_table = _find_opp_table(dev);
211         if (IS_ERR(opp_table))
212                 return 0;
213
214         /* Regulator may not be required for the device */
215         if (!opp_table->regulators)
216                 goto put_opp_table;
217
218         count = opp_table->regulator_count;
219
220         uV = kmalloc_array(count, sizeof(*uV), GFP_KERNEL);
221         if (!uV)
222                 goto put_opp_table;
223
224         mutex_lock(&opp_table->lock);
225
226         for (i = 0; i < count; i++) {
227                 uV[i].min = ~0;
228                 uV[i].max = 0;
229
230                 list_for_each_entry(opp, &opp_table->opp_list, node) {
231                         if (!opp->available)
232                                 continue;
233
234                         if (opp->supplies[i].u_volt_min < uV[i].min)
235                                 uV[i].min = opp->supplies[i].u_volt_min;
236                         if (opp->supplies[i].u_volt_max > uV[i].max)
237                                 uV[i].max = opp->supplies[i].u_volt_max;
238                 }
239         }
240
241         mutex_unlock(&opp_table->lock);
242
243         /*
244          * The caller needs to ensure that opp_table (and hence the regulator)
245          * isn't freed, while we are executing this routine.
246          */
247         for (i = 0; i < count; i++) {
248                 reg = opp_table->regulators[i];
249                 ret = regulator_set_voltage_time(reg, uV[i].min, uV[i].max);
250                 if (ret > 0)
251                         latency_ns += ret * 1000;
252         }
253
254         kfree(uV);
255 put_opp_table:
256         dev_pm_opp_put_opp_table(opp_table);
257
258         return latency_ns;
259 }
260 EXPORT_SYMBOL_GPL(dev_pm_opp_get_max_volt_latency);
261
262 /**
263  * dev_pm_opp_get_max_transition_latency() - Get max transition latency in
264  *                                           nanoseconds
265  * @dev: device for which we do this operation
266  *
267  * Return: This function returns the max transition latency, in nanoseconds, to
268  * switch from one OPP to other.
269  */
270 unsigned long dev_pm_opp_get_max_transition_latency(struct device *dev)
271 {
272         return dev_pm_opp_get_max_volt_latency(dev) +
273                 dev_pm_opp_get_max_clock_latency(dev);
274 }
275 EXPORT_SYMBOL_GPL(dev_pm_opp_get_max_transition_latency);
276
277 /**
278  * dev_pm_opp_get_suspend_opp_freq() - Get frequency of suspend opp in Hz
279  * @dev:        device for which we do this operation
280  *
281  * Return: This function returns the frequency of the OPP marked as suspend_opp
282  * if one is available, else returns 0;
283  */
284 unsigned long dev_pm_opp_get_suspend_opp_freq(struct device *dev)
285 {
286         struct opp_table *opp_table;
287         unsigned long freq = 0;
288
289         opp_table = _find_opp_table(dev);
290         if (IS_ERR(opp_table))
291                 return 0;
292
293         if (opp_table->suspend_opp && opp_table->suspend_opp->available)
294                 freq = dev_pm_opp_get_freq(opp_table->suspend_opp);
295
296         dev_pm_opp_put_opp_table(opp_table);
297
298         return freq;
299 }
300 EXPORT_SYMBOL_GPL(dev_pm_opp_get_suspend_opp_freq);
301
302 int _get_opp_count(struct opp_table *opp_table)
303 {
304         struct dev_pm_opp *opp;
305         int count = 0;
306
307         mutex_lock(&opp_table->lock);
308
309         list_for_each_entry(opp, &opp_table->opp_list, node) {
310                 if (opp->available)
311                         count++;
312         }
313
314         mutex_unlock(&opp_table->lock);
315
316         return count;
317 }
318
319 /**
320  * dev_pm_opp_get_opp_count() - Get number of opps available in the opp table
321  * @dev:        device for which we do this operation
322  *
323  * Return: This function returns the number of available opps if there are any,
324  * else returns 0 if none or the corresponding error value.
325  */
326 int dev_pm_opp_get_opp_count(struct device *dev)
327 {
328         struct opp_table *opp_table;
329         int count;
330
331         opp_table = _find_opp_table(dev);
332         if (IS_ERR(opp_table)) {
333                 count = PTR_ERR(opp_table);
334                 dev_dbg(dev, "%s: OPP table not found (%d)\n",
335                         __func__, count);
336                 return count;
337         }
338
339         count = _get_opp_count(opp_table);
340         dev_pm_opp_put_opp_table(opp_table);
341
342         return count;
343 }
344 EXPORT_SYMBOL_GPL(dev_pm_opp_get_opp_count);
345
346 /**
347  * dev_pm_opp_find_freq_exact() - search for an exact frequency
348  * @dev:                device for which we do this operation
349  * @freq:               frequency to search for
350  * @available:          true/false - match for available opp
351  *
352  * Return: Searches for exact match in the opp table and returns pointer to the
353  * matching opp if found, else returns ERR_PTR in case of error and should
354  * be handled using IS_ERR. Error return values can be:
355  * EINVAL:      for bad pointer
356  * ERANGE:      no match found for search
357  * ENODEV:      if device not found in list of registered devices
358  *
359  * Note: available is a modifier for the search. if available=true, then the
360  * match is for exact matching frequency and is available in the stored OPP
361  * table. if false, the match is for exact frequency which is not available.
362  *
363  * This provides a mechanism to enable an opp which is not available currently
364  * or the opposite as well.
365  *
366  * The callers are required to call dev_pm_opp_put() for the returned OPP after
367  * use.
368  */
369 struct dev_pm_opp *dev_pm_opp_find_freq_exact(struct device *dev,
370                                               unsigned long freq,
371                                               bool available)
372 {
373         struct opp_table *opp_table;
374         struct dev_pm_opp *temp_opp, *opp = ERR_PTR(-ERANGE);
375
376         opp_table = _find_opp_table(dev);
377         if (IS_ERR(opp_table)) {
378                 int r = PTR_ERR(opp_table);
379
380                 dev_err(dev, "%s: OPP table not found (%d)\n", __func__, r);
381                 return ERR_PTR(r);
382         }
383
384         mutex_lock(&opp_table->lock);
385
386         list_for_each_entry(temp_opp, &opp_table->opp_list, node) {
387                 if (temp_opp->available == available &&
388                                 temp_opp->rate == freq) {
389                         opp = temp_opp;
390
391                         /* Increment the reference count of OPP */
392                         dev_pm_opp_get(opp);
393                         break;
394                 }
395         }
396
397         mutex_unlock(&opp_table->lock);
398         dev_pm_opp_put_opp_table(opp_table);
399
400         return opp;
401 }
402 EXPORT_SYMBOL_GPL(dev_pm_opp_find_freq_exact);
403
404 /**
405  * dev_pm_opp_find_level_exact() - search for an exact level
406  * @dev:                device for which we do this operation
407  * @level:              level to search for
408  *
409  * Return: Searches for exact match in the opp table and returns pointer to the
410  * matching opp if found, else returns ERR_PTR in case of error and should
411  * be handled using IS_ERR. Error return values can be:
412  * EINVAL:      for bad pointer
413  * ERANGE:      no match found for search
414  * ENODEV:      if device not found in list of registered devices
415  *
416  * The callers are required to call dev_pm_opp_put() for the returned OPP after
417  * use.
418  */
419 struct dev_pm_opp *dev_pm_opp_find_level_exact(struct device *dev,
420                                                unsigned int level)
421 {
422         struct opp_table *opp_table;
423         struct dev_pm_opp *temp_opp, *opp = ERR_PTR(-ERANGE);
424
425         opp_table = _find_opp_table(dev);
426         if (IS_ERR(opp_table)) {
427                 int r = PTR_ERR(opp_table);
428
429                 dev_err(dev, "%s: OPP table not found (%d)\n", __func__, r);
430                 return ERR_PTR(r);
431         }
432
433         mutex_lock(&opp_table->lock);
434
435         list_for_each_entry(temp_opp, &opp_table->opp_list, node) {
436                 if (temp_opp->level == level) {
437                         opp = temp_opp;
438
439                         /* Increment the reference count of OPP */
440                         dev_pm_opp_get(opp);
441                         break;
442                 }
443         }
444
445         mutex_unlock(&opp_table->lock);
446         dev_pm_opp_put_opp_table(opp_table);
447
448         return opp;
449 }
450 EXPORT_SYMBOL_GPL(dev_pm_opp_find_level_exact);
451
452 static noinline struct dev_pm_opp *_find_freq_ceil(struct opp_table *opp_table,
453                                                    unsigned long *freq)
454 {
455         struct dev_pm_opp *temp_opp, *opp = ERR_PTR(-ERANGE);
456
457         mutex_lock(&opp_table->lock);
458
459         list_for_each_entry(temp_opp, &opp_table->opp_list, node) {
460                 if (temp_opp->available && temp_opp->rate >= *freq) {
461                         opp = temp_opp;
462                         *freq = opp->rate;
463
464                         /* Increment the reference count of OPP */
465                         dev_pm_opp_get(opp);
466                         break;
467                 }
468         }
469
470         mutex_unlock(&opp_table->lock);
471
472         return opp;
473 }
474
475 /**
476  * dev_pm_opp_find_freq_ceil() - Search for an rounded ceil freq
477  * @dev:        device for which we do this operation
478  * @freq:       Start frequency
479  *
480  * Search for the matching ceil *available* OPP from a starting freq
481  * for a device.
482  *
483  * Return: matching *opp and refreshes *freq accordingly, else returns
484  * ERR_PTR in case of error and should be handled using IS_ERR. Error return
485  * values can be:
486  * EINVAL:      for bad pointer
487  * ERANGE:      no match found for search
488  * ENODEV:      if device not found in list of registered devices
489  *
490  * The callers are required to call dev_pm_opp_put() for the returned OPP after
491  * use.
492  */
493 struct dev_pm_opp *dev_pm_opp_find_freq_ceil(struct device *dev,
494                                              unsigned long *freq)
495 {
496         struct opp_table *opp_table;
497         struct dev_pm_opp *opp;
498
499         if (!dev || !freq) {
500                 dev_err(dev, "%s: Invalid argument freq=%p\n", __func__, freq);
501                 return ERR_PTR(-EINVAL);
502         }
503
504         opp_table = _find_opp_table(dev);
505         if (IS_ERR(opp_table))
506                 return ERR_CAST(opp_table);
507
508         opp = _find_freq_ceil(opp_table, freq);
509
510         dev_pm_opp_put_opp_table(opp_table);
511
512         return opp;
513 }
514 EXPORT_SYMBOL_GPL(dev_pm_opp_find_freq_ceil);
515
516 /**
517  * dev_pm_opp_find_freq_floor() - Search for a rounded floor freq
518  * @dev:        device for which we do this operation
519  * @freq:       Start frequency
520  *
521  * Search for the matching floor *available* OPP from a starting freq
522  * for a device.
523  *
524  * Return: matching *opp and refreshes *freq accordingly, else returns
525  * ERR_PTR in case of error and should be handled using IS_ERR. Error return
526  * values can be:
527  * EINVAL:      for bad pointer
528  * ERANGE:      no match found for search
529  * ENODEV:      if device not found in list of registered devices
530  *
531  * The callers are required to call dev_pm_opp_put() for the returned OPP after
532  * use.
533  */
534 struct dev_pm_opp *dev_pm_opp_find_freq_floor(struct device *dev,
535                                               unsigned long *freq)
536 {
537         struct opp_table *opp_table;
538         struct dev_pm_opp *temp_opp, *opp = ERR_PTR(-ERANGE);
539
540         if (!dev || !freq) {
541                 dev_err(dev, "%s: Invalid argument freq=%p\n", __func__, freq);
542                 return ERR_PTR(-EINVAL);
543         }
544
545         opp_table = _find_opp_table(dev);
546         if (IS_ERR(opp_table))
547                 return ERR_CAST(opp_table);
548
549         mutex_lock(&opp_table->lock);
550
551         list_for_each_entry(temp_opp, &opp_table->opp_list, node) {
552                 if (temp_opp->available) {
553                         /* go to the next node, before choosing prev */
554                         if (temp_opp->rate > *freq)
555                                 break;
556                         else
557                                 opp = temp_opp;
558                 }
559         }
560
561         /* Increment the reference count of OPP */
562         if (!IS_ERR(opp))
563                 dev_pm_opp_get(opp);
564         mutex_unlock(&opp_table->lock);
565         dev_pm_opp_put_opp_table(opp_table);
566
567         if (!IS_ERR(opp))
568                 *freq = opp->rate;
569
570         return opp;
571 }
572 EXPORT_SYMBOL_GPL(dev_pm_opp_find_freq_floor);
573
574 /**
575  * dev_pm_opp_find_freq_ceil_by_volt() - Find OPP with highest frequency for
576  *                                       target voltage.
577  * @dev:        Device for which we do this operation.
578  * @u_volt:     Target voltage.
579  *
580  * Search for OPP with highest (ceil) frequency and has voltage <= u_volt.
581  *
582  * Return: matching *opp, else returns ERR_PTR in case of error which should be
583  * handled using IS_ERR.
584  *
585  * Error return values can be:
586  * EINVAL:      bad parameters
587  *
588  * The callers are required to call dev_pm_opp_put() for the returned OPP after
589  * use.
590  */
591 struct dev_pm_opp *dev_pm_opp_find_freq_ceil_by_volt(struct device *dev,
592                                                      unsigned long u_volt)
593 {
594         struct opp_table *opp_table;
595         struct dev_pm_opp *temp_opp, *opp = ERR_PTR(-ERANGE);
596
597         if (!dev || !u_volt) {
598                 dev_err(dev, "%s: Invalid argument volt=%lu\n", __func__,
599                         u_volt);
600                 return ERR_PTR(-EINVAL);
601         }
602
603         opp_table = _find_opp_table(dev);
604         if (IS_ERR(opp_table))
605                 return ERR_CAST(opp_table);
606
607         mutex_lock(&opp_table->lock);
608
609         list_for_each_entry(temp_opp, &opp_table->opp_list, node) {
610                 if (temp_opp->available) {
611                         if (temp_opp->supplies[0].u_volt > u_volt)
612                                 break;
613                         opp = temp_opp;
614                 }
615         }
616
617         /* Increment the reference count of OPP */
618         if (!IS_ERR(opp))
619                 dev_pm_opp_get(opp);
620
621         mutex_unlock(&opp_table->lock);
622         dev_pm_opp_put_opp_table(opp_table);
623
624         return opp;
625 }
626 EXPORT_SYMBOL_GPL(dev_pm_opp_find_freq_ceil_by_volt);
627
628 static int _set_opp_voltage(struct device *dev, struct regulator *reg,
629                             struct dev_pm_opp_supply *supply)
630 {
631         int ret;
632
633         /* Regulator not available for device */
634         if (IS_ERR(reg)) {
635                 dev_dbg(dev, "%s: regulator not available: %ld\n", __func__,
636                         PTR_ERR(reg));
637                 return 0;
638         }
639
640         dev_dbg(dev, "%s: voltages (mV): %lu %lu %lu\n", __func__,
641                 supply->u_volt_min, supply->u_volt, supply->u_volt_max);
642
643         ret = regulator_set_voltage_triplet(reg, supply->u_volt_min,
644                                             supply->u_volt, supply->u_volt_max);
645         if (ret)
646                 dev_err(dev, "%s: failed to set voltage (%lu %lu %lu mV): %d\n",
647                         __func__, supply->u_volt_min, supply->u_volt,
648                         supply->u_volt_max, ret);
649
650         return ret;
651 }
652
653 static inline int _generic_set_opp_clk_only(struct device *dev, struct clk *clk,
654                                             unsigned long freq)
655 {
656         int ret;
657
658         ret = clk_set_rate(clk, freq);
659         if (ret) {
660                 dev_err(dev, "%s: failed to set clock rate: %d\n", __func__,
661                         ret);
662         }
663
664         return ret;
665 }
666
667 static int _generic_set_opp_regulator(struct opp_table *opp_table,
668                                       struct device *dev,
669                                       unsigned long old_freq,
670                                       unsigned long freq,
671                                       struct dev_pm_opp_supply *old_supply,
672                                       struct dev_pm_opp_supply *new_supply)
673 {
674         struct regulator *reg = opp_table->regulators[0];
675         int ret;
676
677         /* This function only supports single regulator per device */
678         if (WARN_ON(opp_table->regulator_count > 1)) {
679                 dev_err(dev, "multiple regulators are not supported\n");
680                 return -EINVAL;
681         }
682
683         /* Scaling up? Scale voltage before frequency */
684         if (freq >= old_freq) {
685                 ret = _set_opp_voltage(dev, reg, new_supply);
686                 if (ret)
687                         goto restore_voltage;
688         }
689
690         /* Change frequency */
691         ret = _generic_set_opp_clk_only(dev, opp_table->clk, freq);
692         if (ret)
693                 goto restore_voltage;
694
695         /* Scaling down? Scale voltage after frequency */
696         if (freq < old_freq) {
697                 ret = _set_opp_voltage(dev, reg, new_supply);
698                 if (ret)
699                         goto restore_freq;
700         }
701
702         /*
703          * Enable the regulator after setting its voltages, otherwise it breaks
704          * some boot-enabled regulators.
705          */
706         if (unlikely(!opp_table->enabled)) {
707                 ret = regulator_enable(reg);
708                 if (ret < 0)
709                         dev_warn(dev, "Failed to enable regulator: %d", ret);
710         }
711
712         return 0;
713
714 restore_freq:
715         if (_generic_set_opp_clk_only(dev, opp_table->clk, old_freq))
716                 dev_err(dev, "%s: failed to restore old-freq (%lu Hz)\n",
717                         __func__, old_freq);
718 restore_voltage:
719         /* This shouldn't harm even if the voltages weren't updated earlier */
720         if (old_supply)
721                 _set_opp_voltage(dev, reg, old_supply);
722
723         return ret;
724 }
725
726 static int _set_opp_bw(const struct opp_table *opp_table,
727                        struct dev_pm_opp *opp, struct device *dev, bool remove)
728 {
729         u32 avg, peak;
730         int i, ret;
731
732         if (!opp_table->paths)
733                 return 0;
734
735         for (i = 0; i < opp_table->path_count; i++) {
736                 if (remove) {
737                         avg = 0;
738                         peak = 0;
739                 } else {
740                         avg = opp->bandwidth[i].avg;
741                         peak = opp->bandwidth[i].peak;
742                 }
743                 ret = icc_set_bw(opp_table->paths[i], avg, peak);
744                 if (ret) {
745                         dev_err(dev, "Failed to %s bandwidth[%d]: %d\n",
746                                 remove ? "remove" : "set", i, ret);
747                         return ret;
748                 }
749         }
750
751         return 0;
752 }
753
754 static int _set_opp_custom(const struct opp_table *opp_table,
755                            struct device *dev, unsigned long old_freq,
756                            unsigned long freq,
757                            struct dev_pm_opp_supply *old_supply,
758                            struct dev_pm_opp_supply *new_supply)
759 {
760         struct dev_pm_set_opp_data *data;
761         int size;
762
763         data = opp_table->set_opp_data;
764         data->regulators = opp_table->regulators;
765         data->regulator_count = opp_table->regulator_count;
766         data->clk = opp_table->clk;
767         data->dev = dev;
768
769         data->old_opp.rate = old_freq;
770         size = sizeof(*old_supply) * opp_table->regulator_count;
771         if (!old_supply)
772                 memset(data->old_opp.supplies, 0, size);
773         else
774                 memcpy(data->old_opp.supplies, old_supply, size);
775
776         data->new_opp.rate = freq;
777         memcpy(data->new_opp.supplies, new_supply, size);
778
779         return opp_table->set_opp(data);
780 }
781
782 static int _set_required_opp(struct device *dev, struct device *pd_dev,
783                              struct dev_pm_opp *opp, int i)
784 {
785         unsigned int pstate = likely(opp) ? opp->required_opps[i]->pstate : 0;
786         int ret;
787
788         if (!pd_dev)
789                 return 0;
790
791         ret = dev_pm_genpd_set_performance_state(pd_dev, pstate);
792         if (ret) {
793                 dev_err(dev, "Failed to set performance rate of %s: %d (%d)\n",
794                         dev_name(pd_dev), pstate, ret);
795         }
796
797         return ret;
798 }
799
800 /* This is only called for PM domain for now */
801 static int _set_required_opps(struct device *dev,
802                               struct opp_table *opp_table,
803                               struct dev_pm_opp *opp, bool up)
804 {
805         struct opp_table **required_opp_tables = opp_table->required_opp_tables;
806         struct device **genpd_virt_devs = opp_table->genpd_virt_devs;
807         int i, ret = 0;
808
809         if (!required_opp_tables)
810                 return 0;
811
812         /* Single genpd case */
813         if (!genpd_virt_devs)
814                 return _set_required_opp(dev, dev, opp, 0);
815
816         /* Multiple genpd case */
817
818         /*
819          * Acquire genpd_virt_dev_lock to make sure we don't use a genpd_dev
820          * after it is freed from another thread.
821          */
822         mutex_lock(&opp_table->genpd_virt_dev_lock);
823
824         /* Scaling up? Set required OPPs in normal order, else reverse */
825         if (up) {
826                 for (i = 0; i < opp_table->required_opp_count; i++) {
827                         ret = _set_required_opp(dev, genpd_virt_devs[i], opp, i);
828                         if (ret)
829                                 break;
830                 }
831         } else {
832                 for (i = opp_table->required_opp_count - 1; i >= 0; i--) {
833                         ret = _set_required_opp(dev, genpd_virt_devs[i], opp, i);
834                         if (ret)
835                                 break;
836                 }
837         }
838
839         mutex_unlock(&opp_table->genpd_virt_dev_lock);
840
841         return ret;
842 }
843
844 /**
845  * dev_pm_opp_set_bw() - sets bandwidth levels corresponding to an opp
846  * @dev:        device for which we do this operation
847  * @opp:        opp based on which the bandwidth levels are to be configured
848  *
849  * This configures the bandwidth to the levels specified by the OPP. However
850  * if the OPP specified is NULL the bandwidth levels are cleared out.
851  *
852  * Return: 0 on success or a negative error value.
853  */
854 int dev_pm_opp_set_bw(struct device *dev, struct dev_pm_opp *opp)
855 {
856         struct opp_table *opp_table;
857         int ret;
858
859         opp_table = _find_opp_table(dev);
860         if (IS_ERR(opp_table)) {
861                 dev_err(dev, "%s: device opp table doesn't exist\n", __func__);
862                 return PTR_ERR(opp_table);
863         }
864
865         if (opp)
866                 ret = _set_opp_bw(opp_table, opp, dev, false);
867         else
868                 ret = _set_opp_bw(opp_table, NULL, dev, true);
869
870         dev_pm_opp_put_opp_table(opp_table);
871         return ret;
872 }
873 EXPORT_SYMBOL_GPL(dev_pm_opp_set_bw);
874
875 static int _opp_set_rate_zero(struct device *dev, struct opp_table *opp_table)
876 {
877         int ret;
878
879         if (!opp_table->enabled)
880                 return 0;
881
882         /*
883          * Some drivers need to support cases where some platforms may
884          * have OPP table for the device, while others don't and
885          * opp_set_rate() just needs to behave like clk_set_rate().
886          */
887         if (!_get_opp_count(opp_table))
888                 return 0;
889
890         ret = _set_opp_bw(opp_table, NULL, dev, true);
891         if (ret)
892                 return ret;
893
894         if (opp_table->regulators)
895                 regulator_disable(opp_table->regulators[0]);
896
897         ret = _set_required_opps(dev, opp_table, NULL, false);
898
899         opp_table->enabled = false;
900         return ret;
901 }
902
903 /**
904  * dev_pm_opp_set_rate() - Configure new OPP based on frequency
905  * @dev:         device for which we do this operation
906  * @target_freq: frequency to achieve
907  *
908  * This configures the power-supplies to the levels specified by the OPP
909  * corresponding to the target_freq, and programs the clock to a value <=
910  * target_freq, as rounded by clk_round_rate(). Device wanting to run at fmax
911  * provided by the opp, should have already rounded to the target OPP's
912  * frequency.
913  */
914 int dev_pm_opp_set_rate(struct device *dev, unsigned long target_freq)
915 {
916         struct opp_table *opp_table;
917         unsigned long freq, old_freq, temp_freq;
918         struct dev_pm_opp *old_opp, *opp;
919         struct clk *clk;
920         int ret;
921
922         opp_table = _find_opp_table(dev);
923         if (IS_ERR(opp_table)) {
924                 dev_err(dev, "%s: device opp doesn't exist\n", __func__);
925                 return PTR_ERR(opp_table);
926         }
927
928         if (unlikely(!target_freq)) {
929                 ret = _opp_set_rate_zero(dev, opp_table);
930                 goto put_opp_table;
931         }
932
933         clk = opp_table->clk;
934         if (IS_ERR(clk)) {
935                 dev_err(dev, "%s: No clock available for the device\n",
936                         __func__);
937                 ret = PTR_ERR(clk);
938                 goto put_opp_table;
939         }
940
941         freq = clk_round_rate(clk, target_freq);
942         if ((long)freq <= 0)
943                 freq = target_freq;
944
945         old_freq = clk_get_rate(clk);
946
947         /* Return early if nothing to do */
948         if (opp_table->enabled && old_freq == freq) {
949                 dev_dbg(dev, "%s: old/new frequencies (%lu Hz) are same, nothing to do\n",
950                         __func__, freq);
951                 ret = 0;
952                 goto put_opp_table;
953         }
954
955         /*
956          * For IO devices which require an OPP on some platforms/SoCs
957          * while just needing to scale the clock on some others
958          * we look for empty OPP tables with just a clock handle and
959          * scale only the clk. This makes dev_pm_opp_set_rate()
960          * equivalent to a clk_set_rate()
961          */
962         if (!_get_opp_count(opp_table)) {
963                 ret = _generic_set_opp_clk_only(dev, clk, freq);
964                 goto put_opp_table;
965         }
966
967         temp_freq = old_freq;
968         old_opp = _find_freq_ceil(opp_table, &temp_freq);
969         if (IS_ERR(old_opp)) {
970                 dev_err(dev, "%s: failed to find current OPP for freq %lu (%ld)\n",
971                         __func__, old_freq, PTR_ERR(old_opp));
972         }
973
974         temp_freq = freq;
975         opp = _find_freq_ceil(opp_table, &temp_freq);
976         if (IS_ERR(opp)) {
977                 ret = PTR_ERR(opp);
978                 dev_err(dev, "%s: failed to find OPP for freq %lu (%d)\n",
979                         __func__, freq, ret);
980                 goto put_old_opp;
981         }
982
983         dev_dbg(dev, "%s: switching OPP: %lu Hz --> %lu Hz\n", __func__,
984                 old_freq, freq);
985
986         /* Scaling up? Configure required OPPs before frequency */
987         if (freq >= old_freq) {
988                 ret = _set_required_opps(dev, opp_table, opp, true);
989                 if (ret)
990                         goto put_opp;
991         }
992
993         if (opp_table->set_opp) {
994                 ret = _set_opp_custom(opp_table, dev, old_freq, freq,
995                                       IS_ERR(old_opp) ? NULL : old_opp->supplies,
996                                       opp->supplies);
997         } else if (opp_table->regulators) {
998                 ret = _generic_set_opp_regulator(opp_table, dev, old_freq, freq,
999                                                  IS_ERR(old_opp) ? NULL : old_opp->supplies,
1000                                                  opp->supplies);
1001         } else {
1002                 /* Only frequency scaling */
1003                 ret = _generic_set_opp_clk_only(dev, clk, freq);
1004         }
1005
1006         /* Scaling down? Configure required OPPs after frequency */
1007         if (!ret && freq < old_freq) {
1008                 ret = _set_required_opps(dev, opp_table, opp, false);
1009                 if (ret)
1010                         dev_err(dev, "Failed to set required opps: %d\n", ret);
1011         }
1012
1013         if (!ret) {
1014                 ret = _set_opp_bw(opp_table, opp, dev, false);
1015                 if (!ret)
1016                         opp_table->enabled = true;
1017         }
1018
1019 put_opp:
1020         dev_pm_opp_put(opp);
1021 put_old_opp:
1022         if (!IS_ERR(old_opp))
1023                 dev_pm_opp_put(old_opp);
1024 put_opp_table:
1025         dev_pm_opp_put_opp_table(opp_table);
1026         return ret;
1027 }
1028 EXPORT_SYMBOL_GPL(dev_pm_opp_set_rate);
1029
1030 /* OPP-dev Helpers */
1031 static void _remove_opp_dev(struct opp_device *opp_dev,
1032                             struct opp_table *opp_table)
1033 {
1034         opp_debug_unregister(opp_dev, opp_table);
1035         list_del(&opp_dev->node);
1036         kfree(opp_dev);
1037 }
1038
1039 struct opp_device *_add_opp_dev(const struct device *dev,
1040                                 struct opp_table *opp_table)
1041 {
1042         struct opp_device *opp_dev;
1043
1044         opp_dev = kzalloc(sizeof(*opp_dev), GFP_KERNEL);
1045         if (!opp_dev)
1046                 return NULL;
1047
1048         /* Initialize opp-dev */
1049         opp_dev->dev = dev;
1050
1051         mutex_lock(&opp_table->lock);
1052         list_add(&opp_dev->node, &opp_table->dev_list);
1053         mutex_unlock(&opp_table->lock);
1054
1055         /* Create debugfs entries for the opp_table */
1056         opp_debug_register(opp_dev, opp_table);
1057
1058         return opp_dev;
1059 }
1060
1061 static struct opp_table *_allocate_opp_table(struct device *dev, int index)
1062 {
1063         struct opp_table *opp_table;
1064         struct opp_device *opp_dev;
1065         int ret;
1066
1067         /*
1068          * Allocate a new OPP table. In the infrequent case where a new
1069          * device is needed to be added, we pay this penalty.
1070          */
1071         opp_table = kzalloc(sizeof(*opp_table), GFP_KERNEL);
1072         if (!opp_table)
1073                 return ERR_PTR(-ENOMEM);
1074
1075         mutex_init(&opp_table->lock);
1076         mutex_init(&opp_table->genpd_virt_dev_lock);
1077         INIT_LIST_HEAD(&opp_table->dev_list);
1078
1079         /* Mark regulator count uninitialized */
1080         opp_table->regulator_count = -1;
1081
1082         opp_dev = _add_opp_dev(dev, opp_table);
1083         if (!opp_dev) {
1084                 ret = -ENOMEM;
1085                 goto err;
1086         }
1087
1088         _of_init_opp_table(opp_table, dev, index);
1089
1090         /* Find clk for the device */
1091         opp_table->clk = clk_get(dev, NULL);
1092         if (IS_ERR(opp_table->clk)) {
1093                 ret = PTR_ERR(opp_table->clk);
1094                 if (ret == -EPROBE_DEFER)
1095                         goto err;
1096
1097                 dev_dbg(dev, "%s: Couldn't find clock: %d\n", __func__, ret);
1098         }
1099
1100         /* Find interconnect path(s) for the device */
1101         ret = dev_pm_opp_of_find_icc_paths(dev, opp_table);
1102         if (ret) {
1103                 if (ret == -EPROBE_DEFER)
1104                         goto err;
1105
1106                 dev_warn(dev, "%s: Error finding interconnect paths: %d\n",
1107                          __func__, ret);
1108         }
1109
1110         BLOCKING_INIT_NOTIFIER_HEAD(&opp_table->head);
1111         INIT_LIST_HEAD(&opp_table->opp_list);
1112         kref_init(&opp_table->kref);
1113
1114         return opp_table;
1115
1116 err:
1117         kfree(opp_table);
1118         return ERR_PTR(ret);
1119 }
1120
1121 void _get_opp_table_kref(struct opp_table *opp_table)
1122 {
1123         kref_get(&opp_table->kref);
1124 }
1125
1126 /*
1127  * We need to make sure that the OPP table for a device doesn't get added twice,
1128  * if this routine gets called in parallel with the same device pointer.
1129  *
1130  * The simplest way to enforce that is to perform everything (find existing
1131  * table and if not found, create a new one) under the opp_table_lock, so only
1132  * one creator gets access to the same. But that expands the critical section
1133  * under the lock and may end up causing circular dependencies with frameworks
1134  * like debugfs, interconnect or clock framework as they may be direct or
1135  * indirect users of OPP core.
1136  *
1137  * And for that reason we have to go for a bit tricky implementation here, which
1138  * uses the opp_tables_busy flag to indicate if another creator is in the middle
1139  * of adding an OPP table and others should wait for it to finish.
1140  */
1141 static struct opp_table *_opp_get_opp_table(struct device *dev, int index)
1142 {
1143         struct opp_table *opp_table;
1144
1145 again:
1146         mutex_lock(&opp_table_lock);
1147
1148         opp_table = _find_opp_table_unlocked(dev);
1149         if (!IS_ERR(opp_table))
1150                 goto unlock;
1151
1152         /*
1153          * The opp_tables list or an OPP table's dev_list is getting updated by
1154          * another user, wait for it to finish.
1155          */
1156         if (unlikely(opp_tables_busy)) {
1157                 mutex_unlock(&opp_table_lock);
1158                 cpu_relax();
1159                 goto again;
1160         }
1161
1162         opp_tables_busy = true;
1163         opp_table = _managed_opp(dev, index);
1164
1165         /* Drop the lock to reduce the size of critical section */
1166         mutex_unlock(&opp_table_lock);
1167
1168         if (opp_table) {
1169                 if (!_add_opp_dev(dev, opp_table)) {
1170                         dev_pm_opp_put_opp_table(opp_table);
1171                         opp_table = ERR_PTR(-ENOMEM);
1172                 }
1173
1174                 mutex_lock(&opp_table_lock);
1175         } else {
1176                 opp_table = _allocate_opp_table(dev, index);
1177
1178                 mutex_lock(&opp_table_lock);
1179                 if (!IS_ERR(opp_table))
1180                         list_add(&opp_table->node, &opp_tables);
1181         }
1182
1183         opp_tables_busy = false;
1184
1185 unlock:
1186         mutex_unlock(&opp_table_lock);
1187
1188         return opp_table;
1189 }
1190
1191 struct opp_table *dev_pm_opp_get_opp_table(struct device *dev)
1192 {
1193         return _opp_get_opp_table(dev, 0);
1194 }
1195 EXPORT_SYMBOL_GPL(dev_pm_opp_get_opp_table);
1196
1197 struct opp_table *dev_pm_opp_get_opp_table_indexed(struct device *dev,
1198                                                    int index)
1199 {
1200         return _opp_get_opp_table(dev, index);
1201 }
1202
1203 static void _opp_table_kref_release(struct kref *kref)
1204 {
1205         struct opp_table *opp_table = container_of(kref, struct opp_table, kref);
1206         struct opp_device *opp_dev, *temp;
1207         int i;
1208
1209         /* Drop the lock as soon as we can */
1210         list_del(&opp_table->node);
1211         mutex_unlock(&opp_table_lock);
1212
1213         _of_clear_opp_table(opp_table);
1214
1215         /* Release clk */
1216         if (!IS_ERR(opp_table->clk))
1217                 clk_put(opp_table->clk);
1218
1219         if (opp_table->paths) {
1220                 for (i = 0; i < opp_table->path_count; i++)
1221                         icc_put(opp_table->paths[i]);
1222                 kfree(opp_table->paths);
1223         }
1224
1225         WARN_ON(!list_empty(&opp_table->opp_list));
1226
1227         list_for_each_entry_safe(opp_dev, temp, &opp_table->dev_list, node) {
1228                 /*
1229                  * The OPP table is getting removed, drop the performance state
1230                  * constraints.
1231                  */
1232                 if (opp_table->genpd_performance_state)
1233                         dev_pm_genpd_set_performance_state((struct device *)(opp_dev->dev), 0);
1234
1235                 _remove_opp_dev(opp_dev, opp_table);
1236         }
1237
1238         mutex_destroy(&opp_table->genpd_virt_dev_lock);
1239         mutex_destroy(&opp_table->lock);
1240         kfree(opp_table);
1241 }
1242
1243 void dev_pm_opp_put_opp_table(struct opp_table *opp_table)
1244 {
1245         kref_put_mutex(&opp_table->kref, _opp_table_kref_release,
1246                        &opp_table_lock);
1247 }
1248 EXPORT_SYMBOL_GPL(dev_pm_opp_put_opp_table);
1249
1250 void _opp_free(struct dev_pm_opp *opp)
1251 {
1252         kfree(opp);
1253 }
1254
1255 static void _opp_kref_release(struct dev_pm_opp *opp,
1256                               struct opp_table *opp_table)
1257 {
1258         /*
1259          * Notify the changes in the availability of the operable
1260          * frequency/voltage list.
1261          */
1262         blocking_notifier_call_chain(&opp_table->head, OPP_EVENT_REMOVE, opp);
1263         _of_opp_free_required_opps(opp_table, opp);
1264         opp_debug_remove_one(opp);
1265         list_del(&opp->node);
1266         kfree(opp);
1267 }
1268
1269 static void _opp_kref_release_unlocked(struct kref *kref)
1270 {
1271         struct dev_pm_opp *opp = container_of(kref, struct dev_pm_opp, kref);
1272         struct opp_table *opp_table = opp->opp_table;
1273
1274         _opp_kref_release(opp, opp_table);
1275 }
1276
1277 static void _opp_kref_release_locked(struct kref *kref)
1278 {
1279         struct dev_pm_opp *opp = container_of(kref, struct dev_pm_opp, kref);
1280         struct opp_table *opp_table = opp->opp_table;
1281
1282         _opp_kref_release(opp, opp_table);
1283         mutex_unlock(&opp_table->lock);
1284 }
1285
1286 void dev_pm_opp_get(struct dev_pm_opp *opp)
1287 {
1288         kref_get(&opp->kref);
1289 }
1290
1291 void dev_pm_opp_put(struct dev_pm_opp *opp)
1292 {
1293         kref_put_mutex(&opp->kref, _opp_kref_release_locked,
1294                        &opp->opp_table->lock);
1295 }
1296 EXPORT_SYMBOL_GPL(dev_pm_opp_put);
1297
1298 static void dev_pm_opp_put_unlocked(struct dev_pm_opp *opp)
1299 {
1300         kref_put(&opp->kref, _opp_kref_release_unlocked);
1301 }
1302
1303 /**
1304  * dev_pm_opp_remove()  - Remove an OPP from OPP table
1305  * @dev:        device for which we do this operation
1306  * @freq:       OPP to remove with matching 'freq'
1307  *
1308  * This function removes an opp from the opp table.
1309  */
1310 void dev_pm_opp_remove(struct device *dev, unsigned long freq)
1311 {
1312         struct dev_pm_opp *opp;
1313         struct opp_table *opp_table;
1314         bool found = false;
1315
1316         opp_table = _find_opp_table(dev);
1317         if (IS_ERR(opp_table))
1318                 return;
1319
1320         mutex_lock(&opp_table->lock);
1321
1322         list_for_each_entry(opp, &opp_table->opp_list, node) {
1323                 if (opp->rate == freq) {
1324                         found = true;
1325                         break;
1326                 }
1327         }
1328
1329         mutex_unlock(&opp_table->lock);
1330
1331         if (found) {
1332                 dev_pm_opp_put(opp);
1333
1334                 /* Drop the reference taken by dev_pm_opp_add() */
1335                 dev_pm_opp_put_opp_table(opp_table);
1336         } else {
1337                 dev_warn(dev, "%s: Couldn't find OPP with freq: %lu\n",
1338                          __func__, freq);
1339         }
1340
1341         /* Drop the reference taken by _find_opp_table() */
1342         dev_pm_opp_put_opp_table(opp_table);
1343 }
1344 EXPORT_SYMBOL_GPL(dev_pm_opp_remove);
1345
1346 bool _opp_remove_all_static(struct opp_table *opp_table)
1347 {
1348         struct dev_pm_opp *opp, *tmp;
1349         bool ret = true;
1350
1351         mutex_lock(&opp_table->lock);
1352
1353         if (!opp_table->parsed_static_opps) {
1354                 ret = false;
1355                 goto unlock;
1356         }
1357
1358         if (--opp_table->parsed_static_opps)
1359                 goto unlock;
1360
1361         list_for_each_entry_safe(opp, tmp, &opp_table->opp_list, node) {
1362                 if (!opp->dynamic)
1363                         dev_pm_opp_put_unlocked(opp);
1364         }
1365
1366 unlock:
1367         mutex_unlock(&opp_table->lock);
1368
1369         return ret;
1370 }
1371
1372 /**
1373  * dev_pm_opp_remove_all_dynamic() - Remove all dynamically created OPPs
1374  * @dev:        device for which we do this operation
1375  *
1376  * This function removes all dynamically created OPPs from the opp table.
1377  */
1378 void dev_pm_opp_remove_all_dynamic(struct device *dev)
1379 {
1380         struct opp_table *opp_table;
1381         struct dev_pm_opp *opp, *temp;
1382         int count = 0;
1383
1384         opp_table = _find_opp_table(dev);
1385         if (IS_ERR(opp_table))
1386                 return;
1387
1388         mutex_lock(&opp_table->lock);
1389         list_for_each_entry_safe(opp, temp, &opp_table->opp_list, node) {
1390                 if (opp->dynamic) {
1391                         dev_pm_opp_put_unlocked(opp);
1392                         count++;
1393                 }
1394         }
1395         mutex_unlock(&opp_table->lock);
1396
1397         /* Drop the references taken by dev_pm_opp_add() */
1398         while (count--)
1399                 dev_pm_opp_put_opp_table(opp_table);
1400
1401         /* Drop the reference taken by _find_opp_table() */
1402         dev_pm_opp_put_opp_table(opp_table);
1403 }
1404 EXPORT_SYMBOL_GPL(dev_pm_opp_remove_all_dynamic);
1405
1406 struct dev_pm_opp *_opp_allocate(struct opp_table *table)
1407 {
1408         struct dev_pm_opp *opp;
1409         int supply_count, supply_size, icc_size;
1410
1411         /* Allocate space for at least one supply */
1412         supply_count = table->regulator_count > 0 ? table->regulator_count : 1;
1413         supply_size = sizeof(*opp->supplies) * supply_count;
1414         icc_size = sizeof(*opp->bandwidth) * table->path_count;
1415
1416         /* allocate new OPP node and supplies structures */
1417         opp = kzalloc(sizeof(*opp) + supply_size + icc_size, GFP_KERNEL);
1418
1419         if (!opp)
1420                 return NULL;
1421
1422         /* Put the supplies at the end of the OPP structure as an empty array */
1423         opp->supplies = (struct dev_pm_opp_supply *)(opp + 1);
1424         if (icc_size)
1425                 opp->bandwidth = (struct dev_pm_opp_icc_bw *)(opp->supplies + supply_count);
1426         INIT_LIST_HEAD(&opp->node);
1427
1428         return opp;
1429 }
1430
1431 static bool _opp_supported_by_regulators(struct dev_pm_opp *opp,
1432                                          struct opp_table *opp_table)
1433 {
1434         struct regulator *reg;
1435         int i;
1436
1437         if (!opp_table->regulators)
1438                 return true;
1439
1440         for (i = 0; i < opp_table->regulator_count; i++) {
1441                 reg = opp_table->regulators[i];
1442
1443                 if (!regulator_is_supported_voltage(reg,
1444                                         opp->supplies[i].u_volt_min,
1445                                         opp->supplies[i].u_volt_max)) {
1446                         pr_warn("%s: OPP minuV: %lu maxuV: %lu, not supported by regulator\n",
1447                                 __func__, opp->supplies[i].u_volt_min,
1448                                 opp->supplies[i].u_volt_max);
1449                         return false;
1450                 }
1451         }
1452
1453         return true;
1454 }
1455
1456 int _opp_compare_key(struct dev_pm_opp *opp1, struct dev_pm_opp *opp2)
1457 {
1458         if (opp1->rate != opp2->rate)
1459                 return opp1->rate < opp2->rate ? -1 : 1;
1460         if (opp1->bandwidth && opp2->bandwidth &&
1461             opp1->bandwidth[0].peak != opp2->bandwidth[0].peak)
1462                 return opp1->bandwidth[0].peak < opp2->bandwidth[0].peak ? -1 : 1;
1463         if (opp1->level != opp2->level)
1464                 return opp1->level < opp2->level ? -1 : 1;
1465         return 0;
1466 }
1467
1468 static int _opp_is_duplicate(struct device *dev, struct dev_pm_opp *new_opp,
1469                              struct opp_table *opp_table,
1470                              struct list_head **head)
1471 {
1472         struct dev_pm_opp *opp;
1473         int opp_cmp;
1474
1475         /*
1476          * Insert new OPP in order of increasing frequency and discard if
1477          * already present.
1478          *
1479          * Need to use &opp_table->opp_list in the condition part of the 'for'
1480          * loop, don't replace it with head otherwise it will become an infinite
1481          * loop.
1482          */
1483         list_for_each_entry(opp, &opp_table->opp_list, node) {
1484                 opp_cmp = _opp_compare_key(new_opp, opp);
1485                 if (opp_cmp > 0) {
1486                         *head = &opp->node;
1487                         continue;
1488                 }
1489
1490                 if (opp_cmp < 0)
1491                         return 0;
1492
1493                 /* Duplicate OPPs */
1494                 dev_warn(dev, "%s: duplicate OPPs detected. Existing: freq: %lu, volt: %lu, enabled: %d. New: freq: %lu, volt: %lu, enabled: %d\n",
1495                          __func__, opp->rate, opp->supplies[0].u_volt,
1496                          opp->available, new_opp->rate,
1497                          new_opp->supplies[0].u_volt, new_opp->available);
1498
1499                 /* Should we compare voltages for all regulators here ? */
1500                 return opp->available &&
1501                        new_opp->supplies[0].u_volt == opp->supplies[0].u_volt ? -EBUSY : -EEXIST;
1502         }
1503
1504         return 0;
1505 }
1506
1507 /*
1508  * Returns:
1509  * 0: On success. And appropriate error message for duplicate OPPs.
1510  * -EBUSY: For OPP with same freq/volt and is available. The callers of
1511  *  _opp_add() must return 0 if they receive -EBUSY from it. This is to make
1512  *  sure we don't print error messages unnecessarily if different parts of
1513  *  kernel try to initialize the OPP table.
1514  * -EEXIST: For OPP with same freq but different volt or is unavailable. This
1515  *  should be considered an error by the callers of _opp_add().
1516  */
1517 int _opp_add(struct device *dev, struct dev_pm_opp *new_opp,
1518              struct opp_table *opp_table, bool rate_not_available)
1519 {
1520         struct list_head *head;
1521         int ret;
1522
1523         mutex_lock(&opp_table->lock);
1524         head = &opp_table->opp_list;
1525
1526         if (likely(!rate_not_available)) {
1527                 ret = _opp_is_duplicate(dev, new_opp, opp_table, &head);
1528                 if (ret) {
1529                         mutex_unlock(&opp_table->lock);
1530                         return ret;
1531                 }
1532         }
1533
1534         list_add(&new_opp->node, head);
1535         mutex_unlock(&opp_table->lock);
1536
1537         new_opp->opp_table = opp_table;
1538         kref_init(&new_opp->kref);
1539
1540         opp_debug_create_one(new_opp, opp_table);
1541
1542         if (!_opp_supported_by_regulators(new_opp, opp_table)) {
1543                 new_opp->available = false;
1544                 dev_warn(dev, "%s: OPP not supported by regulators (%lu)\n",
1545                          __func__, new_opp->rate);
1546         }
1547
1548         return 0;
1549 }
1550
1551 /**
1552  * _opp_add_v1() - Allocate a OPP based on v1 bindings.
1553  * @opp_table:  OPP table
1554  * @dev:        device for which we do this operation
1555  * @freq:       Frequency in Hz for this OPP
1556  * @u_volt:     Voltage in uVolts for this OPP
1557  * @dynamic:    Dynamically added OPPs.
1558  *
1559  * This function adds an opp definition to the opp table and returns status.
1560  * The opp is made available by default and it can be controlled using
1561  * dev_pm_opp_enable/disable functions and may be removed by dev_pm_opp_remove.
1562  *
1563  * NOTE: "dynamic" parameter impacts OPPs added by the dev_pm_opp_of_add_table
1564  * and freed by dev_pm_opp_of_remove_table.
1565  *
1566  * Return:
1567  * 0            On success OR
1568  *              Duplicate OPPs (both freq and volt are same) and opp->available
1569  * -EEXIST      Freq are same and volt are different OR
1570  *              Duplicate OPPs (both freq and volt are same) and !opp->available
1571  * -ENOMEM      Memory allocation failure
1572  */
1573 int _opp_add_v1(struct opp_table *opp_table, struct device *dev,
1574                 unsigned long freq, long u_volt, bool dynamic)
1575 {
1576         struct dev_pm_opp *new_opp;
1577         unsigned long tol;
1578         int ret;
1579
1580         new_opp = _opp_allocate(opp_table);
1581         if (!new_opp)
1582                 return -ENOMEM;
1583
1584         /* populate the opp table */
1585         new_opp->rate = freq;
1586         tol = u_volt * opp_table->voltage_tolerance_v1 / 100;
1587         new_opp->supplies[0].u_volt = u_volt;
1588         new_opp->supplies[0].u_volt_min = u_volt - tol;
1589         new_opp->supplies[0].u_volt_max = u_volt + tol;
1590         new_opp->available = true;
1591         new_opp->dynamic = dynamic;
1592
1593         ret = _opp_add(dev, new_opp, opp_table, false);
1594         if (ret) {
1595                 /* Don't return error for duplicate OPPs */
1596                 if (ret == -EBUSY)
1597                         ret = 0;
1598                 goto free_opp;
1599         }
1600
1601         /*
1602          * Notify the changes in the availability of the operable
1603          * frequency/voltage list.
1604          */
1605         blocking_notifier_call_chain(&opp_table->head, OPP_EVENT_ADD, new_opp);
1606         return 0;
1607
1608 free_opp:
1609         _opp_free(new_opp);
1610
1611         return ret;
1612 }
1613
1614 /**
1615  * dev_pm_opp_set_supported_hw() - Set supported platforms
1616  * @dev: Device for which supported-hw has to be set.
1617  * @versions: Array of hierarchy of versions to match.
1618  * @count: Number of elements in the array.
1619  *
1620  * This is required only for the V2 bindings, and it enables a platform to
1621  * specify the hierarchy of versions it supports. OPP layer will then enable
1622  * OPPs, which are available for those versions, based on its 'opp-supported-hw'
1623  * property.
1624  */
1625 struct opp_table *dev_pm_opp_set_supported_hw(struct device *dev,
1626                         const u32 *versions, unsigned int count)
1627 {
1628         struct opp_table *opp_table;
1629
1630         opp_table = dev_pm_opp_get_opp_table(dev);
1631         if (IS_ERR(opp_table))
1632                 return opp_table;
1633
1634         /* Make sure there are no concurrent readers while updating opp_table */
1635         WARN_ON(!list_empty(&opp_table->opp_list));
1636
1637         /* Another CPU that shares the OPP table has set the property ? */
1638         if (opp_table->supported_hw)
1639                 return opp_table;
1640
1641         opp_table->supported_hw = kmemdup(versions, count * sizeof(*versions),
1642                                         GFP_KERNEL);
1643         if (!opp_table->supported_hw) {
1644                 dev_pm_opp_put_opp_table(opp_table);
1645                 return ERR_PTR(-ENOMEM);
1646         }
1647
1648         opp_table->supported_hw_count = count;
1649
1650         return opp_table;
1651 }
1652 EXPORT_SYMBOL_GPL(dev_pm_opp_set_supported_hw);
1653
1654 /**
1655  * dev_pm_opp_put_supported_hw() - Releases resources blocked for supported hw
1656  * @opp_table: OPP table returned by dev_pm_opp_set_supported_hw().
1657  *
1658  * This is required only for the V2 bindings, and is called for a matching
1659  * dev_pm_opp_set_supported_hw(). Until this is called, the opp_table structure
1660  * will not be freed.
1661  */
1662 void dev_pm_opp_put_supported_hw(struct opp_table *opp_table)
1663 {
1664         /* Make sure there are no concurrent readers while updating opp_table */
1665         WARN_ON(!list_empty(&opp_table->opp_list));
1666
1667         kfree(opp_table->supported_hw);
1668         opp_table->supported_hw = NULL;
1669         opp_table->supported_hw_count = 0;
1670
1671         dev_pm_opp_put_opp_table(opp_table);
1672 }
1673 EXPORT_SYMBOL_GPL(dev_pm_opp_put_supported_hw);
1674
1675 /**
1676  * dev_pm_opp_set_prop_name() - Set prop-extn name
1677  * @dev: Device for which the prop-name has to be set.
1678  * @name: name to postfix to properties.
1679  *
1680  * This is required only for the V2 bindings, and it enables a platform to
1681  * specify the extn to be used for certain property names. The properties to
1682  * which the extension will apply are opp-microvolt and opp-microamp. OPP core
1683  * should postfix the property name with -<name> while looking for them.
1684  */
1685 struct opp_table *dev_pm_opp_set_prop_name(struct device *dev, const char *name)
1686 {
1687         struct opp_table *opp_table;
1688
1689         opp_table = dev_pm_opp_get_opp_table(dev);
1690         if (IS_ERR(opp_table))
1691                 return opp_table;
1692
1693         /* Make sure there are no concurrent readers while updating opp_table */
1694         WARN_ON(!list_empty(&opp_table->opp_list));
1695
1696         /* Another CPU that shares the OPP table has set the property ? */
1697         if (opp_table->prop_name)
1698                 return opp_table;
1699
1700         opp_table->prop_name = kstrdup(name, GFP_KERNEL);
1701         if (!opp_table->prop_name) {
1702                 dev_pm_opp_put_opp_table(opp_table);
1703                 return ERR_PTR(-ENOMEM);
1704         }
1705
1706         return opp_table;
1707 }
1708 EXPORT_SYMBOL_GPL(dev_pm_opp_set_prop_name);
1709
1710 /**
1711  * dev_pm_opp_put_prop_name() - Releases resources blocked for prop-name
1712  * @opp_table: OPP table returned by dev_pm_opp_set_prop_name().
1713  *
1714  * This is required only for the V2 bindings, and is called for a matching
1715  * dev_pm_opp_set_prop_name(). Until this is called, the opp_table structure
1716  * will not be freed.
1717  */
1718 void dev_pm_opp_put_prop_name(struct opp_table *opp_table)
1719 {
1720         /* Make sure there are no concurrent readers while updating opp_table */
1721         WARN_ON(!list_empty(&opp_table->opp_list));
1722
1723         kfree(opp_table->prop_name);
1724         opp_table->prop_name = NULL;
1725
1726         dev_pm_opp_put_opp_table(opp_table);
1727 }
1728 EXPORT_SYMBOL_GPL(dev_pm_opp_put_prop_name);
1729
1730 static int _allocate_set_opp_data(struct opp_table *opp_table)
1731 {
1732         struct dev_pm_set_opp_data *data;
1733         int len, count = opp_table->regulator_count;
1734
1735         if (WARN_ON(!opp_table->regulators))
1736                 return -EINVAL;
1737
1738         /* space for set_opp_data */
1739         len = sizeof(*data);
1740
1741         /* space for old_opp.supplies and new_opp.supplies */
1742         len += 2 * sizeof(struct dev_pm_opp_supply) * count;
1743
1744         data = kzalloc(len, GFP_KERNEL);
1745         if (!data)
1746                 return -ENOMEM;
1747
1748         data->old_opp.supplies = (void *)(data + 1);
1749         data->new_opp.supplies = data->old_opp.supplies + count;
1750
1751         opp_table->set_opp_data = data;
1752
1753         return 0;
1754 }
1755
1756 static void _free_set_opp_data(struct opp_table *opp_table)
1757 {
1758         kfree(opp_table->set_opp_data);
1759         opp_table->set_opp_data = NULL;
1760 }
1761
1762 /**
1763  * dev_pm_opp_set_regulators() - Set regulator names for the device
1764  * @dev: Device for which regulator name is being set.
1765  * @names: Array of pointers to the names of the regulator.
1766  * @count: Number of regulators.
1767  *
1768  * In order to support OPP switching, OPP layer needs to know the name of the
1769  * device's regulators, as the core would be required to switch voltages as
1770  * well.
1771  *
1772  * This must be called before any OPPs are initialized for the device.
1773  */
1774 struct opp_table *dev_pm_opp_set_regulators(struct device *dev,
1775                                             const char * const names[],
1776                                             unsigned int count)
1777 {
1778         struct opp_table *opp_table;
1779         struct regulator *reg;
1780         int ret, i;
1781
1782         opp_table = dev_pm_opp_get_opp_table(dev);
1783         if (IS_ERR(opp_table))
1784                 return opp_table;
1785
1786         /* This should be called before OPPs are initialized */
1787         if (WARN_ON(!list_empty(&opp_table->opp_list))) {
1788                 ret = -EBUSY;
1789                 goto err;
1790         }
1791
1792         /* Another CPU that shares the OPP table has set the regulators ? */
1793         if (opp_table->regulators)
1794                 return opp_table;
1795
1796         opp_table->regulators = kmalloc_array(count,
1797                                               sizeof(*opp_table->regulators),
1798                                               GFP_KERNEL);
1799         if (!opp_table->regulators) {
1800                 ret = -ENOMEM;
1801                 goto err;
1802         }
1803
1804         for (i = 0; i < count; i++) {
1805                 reg = regulator_get_optional(dev, names[i]);
1806                 if (IS_ERR(reg)) {
1807                         ret = PTR_ERR(reg);
1808                         if (ret != -EPROBE_DEFER)
1809                                 dev_err(dev, "%s: no regulator (%s) found: %d\n",
1810                                         __func__, names[i], ret);
1811                         goto free_regulators;
1812                 }
1813
1814                 opp_table->regulators[i] = reg;
1815         }
1816
1817         opp_table->regulator_count = count;
1818
1819         /* Allocate block only once to pass to set_opp() routines */
1820         ret = _allocate_set_opp_data(opp_table);
1821         if (ret)
1822                 goto free_regulators;
1823
1824         return opp_table;
1825
1826 free_regulators:
1827         while (i != 0)
1828                 regulator_put(opp_table->regulators[--i]);
1829
1830         kfree(opp_table->regulators);
1831         opp_table->regulators = NULL;
1832         opp_table->regulator_count = -1;
1833 err:
1834         dev_pm_opp_put_opp_table(opp_table);
1835
1836         return ERR_PTR(ret);
1837 }
1838 EXPORT_SYMBOL_GPL(dev_pm_opp_set_regulators);
1839
1840 /**
1841  * dev_pm_opp_put_regulators() - Releases resources blocked for regulator
1842  * @opp_table: OPP table returned from dev_pm_opp_set_regulators().
1843  */
1844 void dev_pm_opp_put_regulators(struct opp_table *opp_table)
1845 {
1846         int i;
1847
1848         if (!opp_table->regulators)
1849                 goto put_opp_table;
1850
1851         /* Make sure there are no concurrent readers while updating opp_table */
1852         WARN_ON(!list_empty(&opp_table->opp_list));
1853
1854         if (opp_table->enabled) {
1855                 for (i = opp_table->regulator_count - 1; i >= 0; i--)
1856                         regulator_disable(opp_table->regulators[i]);
1857         }
1858
1859         for (i = opp_table->regulator_count - 1; i >= 0; i--)
1860                 regulator_put(opp_table->regulators[i]);
1861
1862         _free_set_opp_data(opp_table);
1863
1864         kfree(opp_table->regulators);
1865         opp_table->regulators = NULL;
1866         opp_table->regulator_count = -1;
1867
1868 put_opp_table:
1869         dev_pm_opp_put_opp_table(opp_table);
1870 }
1871 EXPORT_SYMBOL_GPL(dev_pm_opp_put_regulators);
1872
1873 /**
1874  * dev_pm_opp_set_clkname() - Set clk name for the device
1875  * @dev: Device for which clk name is being set.
1876  * @name: Clk name.
1877  *
1878  * In order to support OPP switching, OPP layer needs to get pointer to the
1879  * clock for the device. Simple cases work fine without using this routine (i.e.
1880  * by passing connection-id as NULL), but for a device with multiple clocks
1881  * available, the OPP core needs to know the exact name of the clk to use.
1882  *
1883  * This must be called before any OPPs are initialized for the device.
1884  */
1885 struct opp_table *dev_pm_opp_set_clkname(struct device *dev, const char *name)
1886 {
1887         struct opp_table *opp_table;
1888         int ret;
1889
1890         opp_table = dev_pm_opp_get_opp_table(dev);
1891         if (IS_ERR(opp_table))
1892                 return opp_table;
1893
1894         /* This should be called before OPPs are initialized */
1895         if (WARN_ON(!list_empty(&opp_table->opp_list))) {
1896                 ret = -EBUSY;
1897                 goto err;
1898         }
1899
1900         /* Already have default clk set, free it */
1901         if (!IS_ERR(opp_table->clk))
1902                 clk_put(opp_table->clk);
1903
1904         /* Find clk for the device */
1905         opp_table->clk = clk_get(dev, name);
1906         if (IS_ERR(opp_table->clk)) {
1907                 ret = PTR_ERR(opp_table->clk);
1908                 if (ret != -EPROBE_DEFER) {
1909                         dev_err(dev, "%s: Couldn't find clock: %d\n", __func__,
1910                                 ret);
1911                 }
1912                 goto err;
1913         }
1914
1915         return opp_table;
1916
1917 err:
1918         dev_pm_opp_put_opp_table(opp_table);
1919
1920         return ERR_PTR(ret);
1921 }
1922 EXPORT_SYMBOL_GPL(dev_pm_opp_set_clkname);
1923
1924 /**
1925  * dev_pm_opp_put_clkname() - Releases resources blocked for clk.
1926  * @opp_table: OPP table returned from dev_pm_opp_set_clkname().
1927  */
1928 void dev_pm_opp_put_clkname(struct opp_table *opp_table)
1929 {
1930         /* Make sure there are no concurrent readers while updating opp_table */
1931         WARN_ON(!list_empty(&opp_table->opp_list));
1932
1933         clk_put(opp_table->clk);
1934         opp_table->clk = ERR_PTR(-EINVAL);
1935
1936         dev_pm_opp_put_opp_table(opp_table);
1937 }
1938 EXPORT_SYMBOL_GPL(dev_pm_opp_put_clkname);
1939
1940 /**
1941  * dev_pm_opp_register_set_opp_helper() - Register custom set OPP helper
1942  * @dev: Device for which the helper is getting registered.
1943  * @set_opp: Custom set OPP helper.
1944  *
1945  * This is useful to support complex platforms (like platforms with multiple
1946  * regulators per device), instead of the generic OPP set rate helper.
1947  *
1948  * This must be called before any OPPs are initialized for the device.
1949  */
1950 struct opp_table *dev_pm_opp_register_set_opp_helper(struct device *dev,
1951                         int (*set_opp)(struct dev_pm_set_opp_data *data))
1952 {
1953         struct opp_table *opp_table;
1954
1955         if (!set_opp)
1956                 return ERR_PTR(-EINVAL);
1957
1958         opp_table = dev_pm_opp_get_opp_table(dev);
1959         if (IS_ERR(opp_table))
1960                 return opp_table;
1961
1962         /* This should be called before OPPs are initialized */
1963         if (WARN_ON(!list_empty(&opp_table->opp_list))) {
1964                 dev_pm_opp_put_opp_table(opp_table);
1965                 return ERR_PTR(-EBUSY);
1966         }
1967
1968         /* Another CPU that shares the OPP table has set the helper ? */
1969         if (!opp_table->set_opp)
1970                 opp_table->set_opp = set_opp;
1971
1972         return opp_table;
1973 }
1974 EXPORT_SYMBOL_GPL(dev_pm_opp_register_set_opp_helper);
1975
1976 /**
1977  * dev_pm_opp_unregister_set_opp_helper() - Releases resources blocked for
1978  *                                         set_opp helper
1979  * @opp_table: OPP table returned from dev_pm_opp_register_set_opp_helper().
1980  *
1981  * Release resources blocked for platform specific set_opp helper.
1982  */
1983 void dev_pm_opp_unregister_set_opp_helper(struct opp_table *opp_table)
1984 {
1985         /* Make sure there are no concurrent readers while updating opp_table */
1986         WARN_ON(!list_empty(&opp_table->opp_list));
1987
1988         opp_table->set_opp = NULL;
1989         dev_pm_opp_put_opp_table(opp_table);
1990 }
1991 EXPORT_SYMBOL_GPL(dev_pm_opp_unregister_set_opp_helper);
1992
1993 static void _opp_detach_genpd(struct opp_table *opp_table)
1994 {
1995         int index;
1996
1997         if (!opp_table->genpd_virt_devs)
1998                 return;
1999
2000         for (index = 0; index < opp_table->required_opp_count; index++) {
2001                 if (!opp_table->genpd_virt_devs[index])
2002                         continue;
2003
2004                 dev_pm_domain_detach(opp_table->genpd_virt_devs[index], false);
2005                 opp_table->genpd_virt_devs[index] = NULL;
2006         }
2007
2008         kfree(opp_table->genpd_virt_devs);
2009         opp_table->genpd_virt_devs = NULL;
2010 }
2011
2012 /**
2013  * dev_pm_opp_attach_genpd - Attach genpd(s) for the device and save virtual device pointer
2014  * @dev: Consumer device for which the genpd is getting attached.
2015  * @names: Null terminated array of pointers containing names of genpd to attach.
2016  * @virt_devs: Pointer to return the array of virtual devices.
2017  *
2018  * Multiple generic power domains for a device are supported with the help of
2019  * virtual genpd devices, which are created for each consumer device - genpd
2020  * pair. These are the device structures which are attached to the power domain
2021  * and are required by the OPP core to set the performance state of the genpd.
2022  * The same API also works for the case where single genpd is available and so
2023  * we don't need to support that separately.
2024  *
2025  * This helper will normally be called by the consumer driver of the device
2026  * "dev", as only that has details of the genpd names.
2027  *
2028  * This helper needs to be called once with a list of all genpd to attach.
2029  * Otherwise the original device structure will be used instead by the OPP core.
2030  *
2031  * The order of entries in the names array must match the order in which
2032  * "required-opps" are added in DT.
2033  */
2034 struct opp_table *dev_pm_opp_attach_genpd(struct device *dev,
2035                 const char **names, struct device ***virt_devs)
2036 {
2037         struct opp_table *opp_table;
2038         struct device *virt_dev;
2039         int index = 0, ret = -EINVAL;
2040         const char **name = names;
2041
2042         opp_table = dev_pm_opp_get_opp_table(dev);
2043         if (IS_ERR(opp_table))
2044                 return opp_table;
2045
2046         if (opp_table->genpd_virt_devs)
2047                 return opp_table;
2048
2049         /*
2050          * If the genpd's OPP table isn't already initialized, parsing of the
2051          * required-opps fail for dev. We should retry this after genpd's OPP
2052          * table is added.
2053          */
2054         if (!opp_table->required_opp_count) {
2055                 ret = -EPROBE_DEFER;
2056                 goto put_table;
2057         }
2058
2059         mutex_lock(&opp_table->genpd_virt_dev_lock);
2060
2061         opp_table->genpd_virt_devs = kcalloc(opp_table->required_opp_count,
2062                                              sizeof(*opp_table->genpd_virt_devs),
2063                                              GFP_KERNEL);
2064         if (!opp_table->genpd_virt_devs)
2065                 goto unlock;
2066
2067         while (*name) {
2068                 if (index >= opp_table->required_opp_count) {
2069                         dev_err(dev, "Index can't be greater than required-opp-count - 1, %s (%d : %d)\n",
2070                                 *name, opp_table->required_opp_count, index);
2071                         goto err;
2072                 }
2073
2074                 virt_dev = dev_pm_domain_attach_by_name(dev, *name);
2075                 if (IS_ERR(virt_dev)) {
2076                         ret = PTR_ERR(virt_dev);
2077                         dev_err(dev, "Couldn't attach to pm_domain: %d\n", ret);
2078                         goto err;
2079                 }
2080
2081                 opp_table->genpd_virt_devs[index] = virt_dev;
2082                 index++;
2083                 name++;
2084         }
2085
2086         if (virt_devs)
2087                 *virt_devs = opp_table->genpd_virt_devs;
2088         mutex_unlock(&opp_table->genpd_virt_dev_lock);
2089
2090         return opp_table;
2091
2092 err:
2093         _opp_detach_genpd(opp_table);
2094 unlock:
2095         mutex_unlock(&opp_table->genpd_virt_dev_lock);
2096
2097 put_table:
2098         dev_pm_opp_put_opp_table(opp_table);
2099
2100         return ERR_PTR(ret);
2101 }
2102 EXPORT_SYMBOL_GPL(dev_pm_opp_attach_genpd);
2103
2104 /**
2105  * dev_pm_opp_detach_genpd() - Detach genpd(s) from the device.
2106  * @opp_table: OPP table returned by dev_pm_opp_attach_genpd().
2107  *
2108  * This detaches the genpd(s), resets the virtual device pointers, and puts the
2109  * OPP table.
2110  */
2111 void dev_pm_opp_detach_genpd(struct opp_table *opp_table)
2112 {
2113         /*
2114          * Acquire genpd_virt_dev_lock to make sure virt_dev isn't getting
2115          * used in parallel.
2116          */
2117         mutex_lock(&opp_table->genpd_virt_dev_lock);
2118         _opp_detach_genpd(opp_table);
2119         mutex_unlock(&opp_table->genpd_virt_dev_lock);
2120
2121         dev_pm_opp_put_opp_table(opp_table);
2122 }
2123 EXPORT_SYMBOL_GPL(dev_pm_opp_detach_genpd);
2124
2125 /**
2126  * dev_pm_opp_xlate_performance_state() - Find required OPP's pstate for src_table.
2127  * @src_table: OPP table which has dst_table as one of its required OPP table.
2128  * @dst_table: Required OPP table of the src_table.
2129  * @pstate: Current performance state of the src_table.
2130  *
2131  * This Returns pstate of the OPP (present in @dst_table) pointed out by the
2132  * "required-opps" property of the OPP (present in @src_table) which has
2133  * performance state set to @pstate.
2134  *
2135  * Return: Zero or positive performance state on success, otherwise negative
2136  * value on errors.
2137  */
2138 int dev_pm_opp_xlate_performance_state(struct opp_table *src_table,
2139                                        struct opp_table *dst_table,
2140                                        unsigned int pstate)
2141 {
2142         struct dev_pm_opp *opp;
2143         int dest_pstate = -EINVAL;
2144         int i;
2145
2146         /*
2147          * Normally the src_table will have the "required_opps" property set to
2148          * point to one of the OPPs in the dst_table, but in some cases the
2149          * genpd and its master have one to one mapping of performance states
2150          * and so none of them have the "required-opps" property set. Return the
2151          * pstate of the src_table as it is in such cases.
2152          */
2153         if (!src_table->required_opp_count)
2154                 return pstate;
2155
2156         for (i = 0; i < src_table->required_opp_count; i++) {
2157                 if (src_table->required_opp_tables[i]->np == dst_table->np)
2158                         break;
2159         }
2160
2161         if (unlikely(i == src_table->required_opp_count)) {
2162                 pr_err("%s: Couldn't find matching OPP table (%p: %p)\n",
2163                        __func__, src_table, dst_table);
2164                 return -EINVAL;
2165         }
2166
2167         mutex_lock(&src_table->lock);
2168
2169         list_for_each_entry(opp, &src_table->opp_list, node) {
2170                 if (opp->pstate == pstate) {
2171                         dest_pstate = opp->required_opps[i]->pstate;
2172                         goto unlock;
2173                 }
2174         }
2175
2176         pr_err("%s: Couldn't find matching OPP (%p: %p)\n", __func__, src_table,
2177                dst_table);
2178
2179 unlock:
2180         mutex_unlock(&src_table->lock);
2181
2182         return dest_pstate;
2183 }
2184
2185 /**
2186  * dev_pm_opp_add()  - Add an OPP table from a table definitions
2187  * @dev:        device for which we do this operation
2188  * @freq:       Frequency in Hz for this OPP
2189  * @u_volt:     Voltage in uVolts for this OPP
2190  *
2191  * This function adds an opp definition to the opp table and returns status.
2192  * The opp is made available by default and it can be controlled using
2193  * dev_pm_opp_enable/disable functions.
2194  *
2195  * Return:
2196  * 0            On success OR
2197  *              Duplicate OPPs (both freq and volt are same) and opp->available
2198  * -EEXIST      Freq are same and volt are different OR
2199  *              Duplicate OPPs (both freq and volt are same) and !opp->available
2200  * -ENOMEM      Memory allocation failure
2201  */
2202 int dev_pm_opp_add(struct device *dev, unsigned long freq, unsigned long u_volt)
2203 {
2204         struct opp_table *opp_table;
2205         int ret;
2206
2207         opp_table = dev_pm_opp_get_opp_table(dev);
2208         if (IS_ERR(opp_table))
2209                 return PTR_ERR(opp_table);
2210
2211         /* Fix regulator count for dynamic OPPs */
2212         opp_table->regulator_count = 1;
2213
2214         ret = _opp_add_v1(opp_table, dev, freq, u_volt, true);
2215         if (ret)
2216                 dev_pm_opp_put_opp_table(opp_table);
2217
2218         return ret;
2219 }
2220 EXPORT_SYMBOL_GPL(dev_pm_opp_add);
2221
2222 /**
2223  * _opp_set_availability() - helper to set the availability of an opp
2224  * @dev:                device for which we do this operation
2225  * @freq:               OPP frequency to modify availability
2226  * @availability_req:   availability status requested for this opp
2227  *
2228  * Set the availability of an OPP, opp_{enable,disable} share a common logic
2229  * which is isolated here.
2230  *
2231  * Return: -EINVAL for bad pointers, -ENOMEM if no memory available for the
2232  * copy operation, returns 0 if no modification was done OR modification was
2233  * successful.
2234  */
2235 static int _opp_set_availability(struct device *dev, unsigned long freq,
2236                                  bool availability_req)
2237 {
2238         struct opp_table *opp_table;
2239         struct dev_pm_opp *tmp_opp, *opp = ERR_PTR(-ENODEV);
2240         int r = 0;
2241
2242         /* Find the opp_table */
2243         opp_table = _find_opp_table(dev);
2244         if (IS_ERR(opp_table)) {
2245                 r = PTR_ERR(opp_table);
2246                 dev_warn(dev, "%s: Device OPP not found (%d)\n", __func__, r);
2247                 return r;
2248         }
2249
2250         mutex_lock(&opp_table->lock);
2251
2252         /* Do we have the frequency? */
2253         list_for_each_entry(tmp_opp, &opp_table->opp_list, node) {
2254                 if (tmp_opp->rate == freq) {
2255                         opp = tmp_opp;
2256                         break;
2257                 }
2258         }
2259
2260         if (IS_ERR(opp)) {
2261                 r = PTR_ERR(opp);
2262                 goto unlock;
2263         }
2264
2265         /* Is update really needed? */
2266         if (opp->available == availability_req)
2267                 goto unlock;
2268
2269         opp->available = availability_req;
2270
2271         dev_pm_opp_get(opp);
2272         mutex_unlock(&opp_table->lock);
2273
2274         /* Notify the change of the OPP availability */
2275         if (availability_req)
2276                 blocking_notifier_call_chain(&opp_table->head, OPP_EVENT_ENABLE,
2277                                              opp);
2278         else
2279                 blocking_notifier_call_chain(&opp_table->head,
2280                                              OPP_EVENT_DISABLE, opp);
2281
2282         dev_pm_opp_put(opp);
2283         goto put_table;
2284
2285 unlock:
2286         mutex_unlock(&opp_table->lock);
2287 put_table:
2288         dev_pm_opp_put_opp_table(opp_table);
2289         return r;
2290 }
2291
2292 /**
2293  * dev_pm_opp_adjust_voltage() - helper to change the voltage of an OPP
2294  * @dev:                device for which we do this operation
2295  * @freq:               OPP frequency to adjust voltage of
2296  * @u_volt:             new OPP target voltage
2297  * @u_volt_min:         new OPP min voltage
2298  * @u_volt_max:         new OPP max voltage
2299  *
2300  * Return: -EINVAL for bad pointers, -ENOMEM if no memory available for the
2301  * copy operation, returns 0 if no modifcation was done OR modification was
2302  * successful.
2303  */
2304 int dev_pm_opp_adjust_voltage(struct device *dev, unsigned long freq,
2305                               unsigned long u_volt, unsigned long u_volt_min,
2306                               unsigned long u_volt_max)
2307
2308 {
2309         struct opp_table *opp_table;
2310         struct dev_pm_opp *tmp_opp, *opp = ERR_PTR(-ENODEV);
2311         int r = 0;
2312
2313         /* Find the opp_table */
2314         opp_table = _find_opp_table(dev);
2315         if (IS_ERR(opp_table)) {
2316                 r = PTR_ERR(opp_table);
2317                 dev_warn(dev, "%s: Device OPP not found (%d)\n", __func__, r);
2318                 return r;
2319         }
2320
2321         mutex_lock(&opp_table->lock);
2322
2323         /* Do we have the frequency? */
2324         list_for_each_entry(tmp_opp, &opp_table->opp_list, node) {
2325                 if (tmp_opp->rate == freq) {
2326                         opp = tmp_opp;
2327                         break;
2328                 }
2329         }
2330
2331         if (IS_ERR(opp)) {
2332                 r = PTR_ERR(opp);
2333                 goto adjust_unlock;
2334         }
2335
2336         /* Is update really needed? */
2337         if (opp->supplies->u_volt == u_volt)
2338                 goto adjust_unlock;
2339
2340         opp->supplies->u_volt = u_volt;
2341         opp->supplies->u_volt_min = u_volt_min;
2342         opp->supplies->u_volt_max = u_volt_max;
2343
2344         dev_pm_opp_get(opp);
2345         mutex_unlock(&opp_table->lock);
2346
2347         /* Notify the voltage change of the OPP */
2348         blocking_notifier_call_chain(&opp_table->head, OPP_EVENT_ADJUST_VOLTAGE,
2349                                      opp);
2350
2351         dev_pm_opp_put(opp);
2352         goto adjust_put_table;
2353
2354 adjust_unlock:
2355         mutex_unlock(&opp_table->lock);
2356 adjust_put_table:
2357         dev_pm_opp_put_opp_table(opp_table);
2358         return r;
2359 }
2360 EXPORT_SYMBOL_GPL(dev_pm_opp_adjust_voltage);
2361
2362 /**
2363  * dev_pm_opp_enable() - Enable a specific OPP
2364  * @dev:        device for which we do this operation
2365  * @freq:       OPP frequency to enable
2366  *
2367  * Enables a provided opp. If the operation is valid, this returns 0, else the
2368  * corresponding error value. It is meant to be used for users an OPP available
2369  * after being temporarily made unavailable with dev_pm_opp_disable.
2370  *
2371  * Return: -EINVAL for bad pointers, -ENOMEM if no memory available for the
2372  * copy operation, returns 0 if no modification was done OR modification was
2373  * successful.
2374  */
2375 int dev_pm_opp_enable(struct device *dev, unsigned long freq)
2376 {
2377         return _opp_set_availability(dev, freq, true);
2378 }
2379 EXPORT_SYMBOL_GPL(dev_pm_opp_enable);
2380
2381 /**
2382  * dev_pm_opp_disable() - Disable a specific OPP
2383  * @dev:        device for which we do this operation
2384  * @freq:       OPP frequency to disable
2385  *
2386  * Disables a provided opp. If the operation is valid, this returns
2387  * 0, else the corresponding error value. It is meant to be a temporary
2388  * control by users to make this OPP not available until the circumstances are
2389  * right to make it available again (with a call to dev_pm_opp_enable).
2390  *
2391  * Return: -EINVAL for bad pointers, -ENOMEM if no memory available for the
2392  * copy operation, returns 0 if no modification was done OR modification was
2393  * successful.
2394  */
2395 int dev_pm_opp_disable(struct device *dev, unsigned long freq)
2396 {
2397         return _opp_set_availability(dev, freq, false);
2398 }
2399 EXPORT_SYMBOL_GPL(dev_pm_opp_disable);
2400
2401 /**
2402  * dev_pm_opp_register_notifier() - Register OPP notifier for the device
2403  * @dev:        Device for which notifier needs to be registered
2404  * @nb:         Notifier block to be registered
2405  *
2406  * Return: 0 on success or a negative error value.
2407  */
2408 int dev_pm_opp_register_notifier(struct device *dev, struct notifier_block *nb)
2409 {
2410         struct opp_table *opp_table;
2411         int ret;
2412
2413         opp_table = _find_opp_table(dev);
2414         if (IS_ERR(opp_table))
2415                 return PTR_ERR(opp_table);
2416
2417         ret = blocking_notifier_chain_register(&opp_table->head, nb);
2418
2419         dev_pm_opp_put_opp_table(opp_table);
2420
2421         return ret;
2422 }
2423 EXPORT_SYMBOL(dev_pm_opp_register_notifier);
2424
2425 /**
2426  * dev_pm_opp_unregister_notifier() - Unregister OPP notifier for the device
2427  * @dev:        Device for which notifier needs to be unregistered
2428  * @nb:         Notifier block to be unregistered
2429  *
2430  * Return: 0 on success or a negative error value.
2431  */
2432 int dev_pm_opp_unregister_notifier(struct device *dev,
2433                                    struct notifier_block *nb)
2434 {
2435         struct opp_table *opp_table;
2436         int ret;
2437
2438         opp_table = _find_opp_table(dev);
2439         if (IS_ERR(opp_table))
2440                 return PTR_ERR(opp_table);
2441
2442         ret = blocking_notifier_chain_unregister(&opp_table->head, nb);
2443
2444         dev_pm_opp_put_opp_table(opp_table);
2445
2446         return ret;
2447 }
2448 EXPORT_SYMBOL(dev_pm_opp_unregister_notifier);
2449
2450 /**
2451  * dev_pm_opp_remove_table() - Free all OPPs associated with the device
2452  * @dev:        device pointer used to lookup OPP table.
2453  *
2454  * Free both OPPs created using static entries present in DT and the
2455  * dynamically added entries.
2456  */
2457 void dev_pm_opp_remove_table(struct device *dev)
2458 {
2459         struct opp_table *opp_table;
2460
2461         /* Check for existing table for 'dev' */
2462         opp_table = _find_opp_table(dev);
2463         if (IS_ERR(opp_table)) {
2464                 int error = PTR_ERR(opp_table);
2465
2466                 if (error != -ENODEV)
2467                         WARN(1, "%s: opp_table: %d\n",
2468                              IS_ERR_OR_NULL(dev) ?
2469                                         "Invalid device" : dev_name(dev),
2470                              error);
2471                 return;
2472         }
2473
2474         /*
2475          * Drop the extra reference only if the OPP table was successfully added
2476          * with dev_pm_opp_of_add_table() earlier.
2477          **/
2478         if (_opp_remove_all_static(opp_table))
2479                 dev_pm_opp_put_opp_table(opp_table);
2480
2481         /* Drop reference taken by _find_opp_table() */
2482         dev_pm_opp_put_opp_table(opp_table);
2483 }
2484 EXPORT_SYMBOL_GPL(dev_pm_opp_remove_table);