PM / OPP: fix the errors occurred during getting or setting voltage
[firefly-linux-kernel-4.4.55.git] / drivers / base / power / opp / core.c
1 /*
2  * Generic OPP Interface
3  *
4  * Copyright (C) 2009-2010 Texas Instruments Incorporated.
5  *      Nishanth Menon
6  *      Romit Dasgupta
7  *      Kevin Hilman
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  */
13
14 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
15
16 #include <linux/clk.h>
17 #include <linux/errno.h>
18 #include <linux/err.h>
19 #include <linux/slab.h>
20 #include <linux/device.h>
21 #include <linux/of.h>
22 #include <linux/export.h>
23 #include <linux/regulator/consumer.h>
24
25 #include "opp.h"
26
27 /*
28  * The root of the list of all opp-tables. All opp_table structures branch off
29  * from here, with each opp_table containing the list of opps it supports in
30  * various states of availability.
31  */
32 static LIST_HEAD(opp_tables);
33 /* Lock to allow exclusive modification to the device and opp lists */
34 DEFINE_MUTEX(opp_table_lock);
35
36 #define opp_rcu_lockdep_assert()                                        \
37 do {                                                                    \
38         RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&                       \
39                          !lockdep_is_held(&opp_table_lock),             \
40                          "Missing rcu_read_lock() or "                  \
41                          "opp_table_lock protection");                  \
42 } while (0)
43
44 static struct opp_device *_find_opp_dev(const struct device *dev,
45                                         struct opp_table *opp_table)
46 {
47         struct opp_device *opp_dev;
48
49         list_for_each_entry(opp_dev, &opp_table->dev_list, node)
50                 if (opp_dev->dev == dev)
51                         return opp_dev;
52
53         return NULL;
54 }
55
56 static struct opp_table *_managed_opp(const struct device_node *np)
57 {
58         struct opp_table *opp_table;
59
60         list_for_each_entry_rcu(opp_table, &opp_tables, node) {
61                 if (opp_table->np == np) {
62                         /*
63                          * Multiple devices can point to the same OPP table and
64                          * so will have same node-pointer, np.
65                          *
66                          * But the OPPs will be considered as shared only if the
67                          * OPP table contains a "opp-shared" property.
68                          */
69                         return opp_table->shared_opp ? opp_table : NULL;
70                 }
71         }
72
73         return NULL;
74 }
75
76 /**
77  * _find_opp_table() - find opp_table struct using device pointer
78  * @dev:        device pointer used to lookup OPP table
79  *
80  * Search OPP table for one containing matching device. Does a RCU reader
81  * operation to grab the pointer needed.
82  *
83  * Return: pointer to 'struct opp_table' if found, otherwise -ENODEV or
84  * -EINVAL based on type of error.
85  *
86  * Locking: For readers, this function must be called under rcu_read_lock().
87  * opp_table is a RCU protected pointer, which means that opp_table is valid
88  * as long as we are under RCU lock.
89  *
90  * For Writers, this function must be called with opp_table_lock held.
91  */
92 struct opp_table *_find_opp_table(struct device *dev)
93 {
94         struct opp_table *opp_table;
95
96         opp_rcu_lockdep_assert();
97
98         if (IS_ERR_OR_NULL(dev)) {
99                 pr_err("%s: Invalid parameters\n", __func__);
100                 return ERR_PTR(-EINVAL);
101         }
102
103         list_for_each_entry_rcu(opp_table, &opp_tables, node)
104                 if (_find_opp_dev(dev, opp_table))
105                         return opp_table;
106
107         return ERR_PTR(-ENODEV);
108 }
109
110 /**
111  * dev_pm_opp_get_voltage() - Gets the voltage corresponding to an opp
112  * @opp:        opp for which voltage has to be returned for
113  *
114  * Return: voltage in micro volt corresponding to the opp, else
115  * return 0
116  *
117  * Locking: This function must be called under rcu_read_lock(). opp is a rcu
118  * protected pointer. This means that opp which could have been fetched by
119  * opp_find_freq_{exact,ceil,floor} functions is valid as long as we are
120  * under RCU lock. The pointer returned by the opp_find_freq family must be
121  * used in the same section as the usage of this function with the pointer
122  * prior to unlocking with rcu_read_unlock() to maintain the integrity of the
123  * pointer.
124  */
125 unsigned long dev_pm_opp_get_voltage(struct dev_pm_opp *opp)
126 {
127         struct dev_pm_opp *tmp_opp;
128         unsigned long v = 0;
129
130         opp_rcu_lockdep_assert();
131
132         tmp_opp = rcu_dereference(opp);
133         if (IS_ERR_OR_NULL(tmp_opp))
134                 pr_err("%s: Invalid parameters\n", __func__);
135         else
136                 v = tmp_opp->u_volt;
137
138         return v;
139 }
140 EXPORT_SYMBOL_GPL(dev_pm_opp_get_voltage);
141
142 /**
143  * dev_pm_opp_get_freq() - Gets the frequency corresponding to an available opp
144  * @opp:        opp for which frequency has to be returned for
145  *
146  * Return: frequency in hertz corresponding to the opp, else
147  * return 0
148  *
149  * Locking: This function must be called under rcu_read_lock(). opp is a rcu
150  * protected pointer. This means that opp which could have been fetched by
151  * opp_find_freq_{exact,ceil,floor} functions is valid as long as we are
152  * under RCU lock. The pointer returned by the opp_find_freq family must be
153  * used in the same section as the usage of this function with the pointer
154  * prior to unlocking with rcu_read_unlock() to maintain the integrity of the
155  * pointer.
156  */
157 unsigned long dev_pm_opp_get_freq(struct dev_pm_opp *opp)
158 {
159         struct dev_pm_opp *tmp_opp;
160         unsigned long f = 0;
161
162         opp_rcu_lockdep_assert();
163
164         tmp_opp = rcu_dereference(opp);
165         if (IS_ERR_OR_NULL(tmp_opp) || !tmp_opp->available)
166                 pr_err("%s: Invalid parameters\n", __func__);
167         else
168                 f = tmp_opp->rate;
169
170         return f;
171 }
172 EXPORT_SYMBOL_GPL(dev_pm_opp_get_freq);
173
174 /**
175  * dev_pm_opp_is_turbo() - Returns if opp is turbo OPP or not
176  * @opp: opp for which turbo mode is being verified
177  *
178  * Turbo OPPs are not for normal use, and can be enabled (under certain
179  * conditions) for short duration of times to finish high throughput work
180  * quickly. Running on them for longer times may overheat the chip.
181  *
182  * Return: true if opp is turbo opp, else false.
183  *
184  * Locking: This function must be called under rcu_read_lock(). opp is a rcu
185  * protected pointer. This means that opp which could have been fetched by
186  * opp_find_freq_{exact,ceil,floor} functions is valid as long as we are
187  * under RCU lock. The pointer returned by the opp_find_freq family must be
188  * used in the same section as the usage of this function with the pointer
189  * prior to unlocking with rcu_read_unlock() to maintain the integrity of the
190  * pointer.
191  */
192 bool dev_pm_opp_is_turbo(struct dev_pm_opp *opp)
193 {
194         struct dev_pm_opp *tmp_opp;
195
196         opp_rcu_lockdep_assert();
197
198         tmp_opp = rcu_dereference(opp);
199         if (IS_ERR_OR_NULL(tmp_opp) || !tmp_opp->available) {
200                 pr_err("%s: Invalid parameters\n", __func__);
201                 return false;
202         }
203
204         return tmp_opp->turbo;
205 }
206 EXPORT_SYMBOL_GPL(dev_pm_opp_is_turbo);
207
208 /**
209  * dev_pm_opp_get_max_clock_latency() - Get max clock latency in nanoseconds
210  * @dev:        device for which we do this operation
211  *
212  * Return: This function returns the max clock latency in nanoseconds.
213  *
214  * Locking: This function takes rcu_read_lock().
215  */
216 unsigned long dev_pm_opp_get_max_clock_latency(struct device *dev)
217 {
218         struct opp_table *opp_table;
219         unsigned long clock_latency_ns;
220
221         rcu_read_lock();
222
223         opp_table = _find_opp_table(dev);
224         if (IS_ERR(opp_table))
225                 clock_latency_ns = 0;
226         else
227                 clock_latency_ns = opp_table->clock_latency_ns_max;
228
229         rcu_read_unlock();
230         return clock_latency_ns;
231 }
232 EXPORT_SYMBOL_GPL(dev_pm_opp_get_max_clock_latency);
233
234 /**
235  * dev_pm_opp_get_max_volt_latency() - Get max voltage latency in nanoseconds
236  * @dev: device for which we do this operation
237  *
238  * Return: This function returns the max voltage latency in nanoseconds.
239  *
240  * Locking: This function takes rcu_read_lock().
241  */
242 unsigned long dev_pm_opp_get_max_volt_latency(struct device *dev)
243 {
244         struct opp_table *opp_table;
245         struct dev_pm_opp *opp;
246         struct regulator *reg;
247         unsigned long latency_ns = 0;
248         unsigned long min_uV = ~0, max_uV = 0;
249         int ret;
250
251         rcu_read_lock();
252
253         opp_table = _find_opp_table(dev);
254         if (IS_ERR(opp_table)) {
255                 rcu_read_unlock();
256                 return 0;
257         }
258
259         reg = opp_table->regulator;
260         if (IS_ERR(reg)) {
261                 /* Regulator may not be required for device */
262                 if (reg)
263                         dev_err(dev, "%s: Invalid regulator (%ld)\n", __func__,
264                                 PTR_ERR(reg));
265                 rcu_read_unlock();
266                 return 0;
267         }
268
269         list_for_each_entry_rcu(opp, &opp_table->opp_list, node) {
270                 if (!opp->available)
271                         continue;
272
273                 if (opp->u_volt_min < min_uV)
274                         min_uV = opp->u_volt_min;
275                 if (opp->u_volt_max > max_uV)
276                         max_uV = opp->u_volt_max;
277         }
278
279         rcu_read_unlock();
280
281         /*
282          * The caller needs to ensure that opp_table (and hence the regulator)
283          * isn't freed, while we are executing this routine.
284          */
285         ret = regulator_set_voltage_time(reg, min_uV, max_uV);
286         if (ret > 0)
287                 latency_ns = ret * 1000;
288
289         return latency_ns;
290 }
291 EXPORT_SYMBOL_GPL(dev_pm_opp_get_max_volt_latency);
292
293 /**
294  * dev_pm_opp_get_max_transition_latency() - Get max transition latency in
295  *                                           nanoseconds
296  * @dev: device for which we do this operation
297  *
298  * Return: This function returns the max transition latency, in nanoseconds, to
299  * switch from one OPP to other.
300  *
301  * Locking: This function takes rcu_read_lock().
302  */
303 unsigned long dev_pm_opp_get_max_transition_latency(struct device *dev)
304 {
305         return dev_pm_opp_get_max_volt_latency(dev) +
306                 dev_pm_opp_get_max_clock_latency(dev);
307 }
308 EXPORT_SYMBOL_GPL(dev_pm_opp_get_max_transition_latency);
309
310 /**
311  * dev_pm_opp_get_suspend_opp() - Get suspend opp
312  * @dev:        device for which we do this operation
313  *
314  * Return: This function returns pointer to the suspend opp if it is
315  * defined and available, otherwise it returns NULL.
316  *
317  * Locking: This function must be called under rcu_read_lock(). opp is a rcu
318  * protected pointer. The reason for the same is that the opp pointer which is
319  * returned will remain valid for use with opp_get_{voltage, freq} only while
320  * under the locked area. The pointer returned must be used prior to unlocking
321  * with rcu_read_unlock() to maintain the integrity of the pointer.
322  */
323 struct dev_pm_opp *dev_pm_opp_get_suspend_opp(struct device *dev)
324 {
325         struct opp_table *opp_table;
326
327         opp_rcu_lockdep_assert();
328
329         opp_table = _find_opp_table(dev);
330         if (IS_ERR(opp_table) || !opp_table->suspend_opp ||
331             !opp_table->suspend_opp->available)
332                 return NULL;
333
334         return opp_table->suspend_opp;
335 }
336 EXPORT_SYMBOL_GPL(dev_pm_opp_get_suspend_opp);
337
338 /**
339  * dev_pm_opp_get_opp_count() - Get number of opps available in the opp table
340  * @dev:        device for which we do this operation
341  *
342  * Return: This function returns the number of available opps if there are any,
343  * else returns 0 if none or the corresponding error value.
344  *
345  * Locking: This function takes rcu_read_lock().
346  */
347 int dev_pm_opp_get_opp_count(struct device *dev)
348 {
349         struct opp_table *opp_table;
350         struct dev_pm_opp *temp_opp;
351         int count = 0;
352
353         rcu_read_lock();
354
355         opp_table = _find_opp_table(dev);
356         if (IS_ERR(opp_table)) {
357                 count = PTR_ERR(opp_table);
358                 dev_err(dev, "%s: OPP table not found (%d)\n",
359                         __func__, count);
360                 goto out_unlock;
361         }
362
363         list_for_each_entry_rcu(temp_opp, &opp_table->opp_list, node) {
364                 if (temp_opp->available)
365                         count++;
366         }
367
368 out_unlock:
369         rcu_read_unlock();
370         return count;
371 }
372 EXPORT_SYMBOL_GPL(dev_pm_opp_get_opp_count);
373
374 /**
375  * dev_pm_opp_find_freq_exact() - search for an exact frequency
376  * @dev:                device for which we do this operation
377  * @freq:               frequency to search for
378  * @available:          true/false - match for available opp
379  *
380  * Return: Searches for exact match in the opp table and returns pointer to the
381  * matching opp if found, else returns ERR_PTR in case of error and should
382  * be handled using IS_ERR. Error return values can be:
383  * EINVAL:      for bad pointer
384  * ERANGE:      no match found for search
385  * ENODEV:      if device not found in list of registered devices
386  *
387  * Note: available is a modifier for the search. if available=true, then the
388  * match is for exact matching frequency and is available in the stored OPP
389  * table. if false, the match is for exact frequency which is not available.
390  *
391  * This provides a mechanism to enable an opp which is not available currently
392  * or the opposite as well.
393  *
394  * Locking: This function must be called under rcu_read_lock(). opp is a rcu
395  * protected pointer. The reason for the same is that the opp pointer which is
396  * returned will remain valid for use with opp_get_{voltage, freq} only while
397  * under the locked area. The pointer returned must be used prior to unlocking
398  * with rcu_read_unlock() to maintain the integrity of the pointer.
399  */
400 struct dev_pm_opp *dev_pm_opp_find_freq_exact(struct device *dev,
401                                               unsigned long freq,
402                                               bool available)
403 {
404         struct opp_table *opp_table;
405         struct dev_pm_opp *temp_opp, *opp = ERR_PTR(-ERANGE);
406
407         opp_rcu_lockdep_assert();
408
409         opp_table = _find_opp_table(dev);
410         if (IS_ERR(opp_table)) {
411                 int r = PTR_ERR(opp_table);
412
413                 dev_err(dev, "%s: OPP table not found (%d)\n", __func__, r);
414                 return ERR_PTR(r);
415         }
416
417         list_for_each_entry_rcu(temp_opp, &opp_table->opp_list, node) {
418                 if (temp_opp->available == available &&
419                                 temp_opp->rate == freq) {
420                         opp = temp_opp;
421                         break;
422                 }
423         }
424
425         return opp;
426 }
427 EXPORT_SYMBOL_GPL(dev_pm_opp_find_freq_exact);
428
429 /**
430  * dev_pm_opp_find_freq_ceil() - Search for an rounded ceil freq
431  * @dev:        device for which we do this operation
432  * @freq:       Start frequency
433  *
434  * Search for the matching ceil *available* OPP from a starting freq
435  * for a device.
436  *
437  * Return: matching *opp and refreshes *freq accordingly, else returns
438  * ERR_PTR in case of error and should be handled using IS_ERR. Error return
439  * values can be:
440  * EINVAL:      for bad pointer
441  * ERANGE:      no match found for search
442  * ENODEV:      if device not found in list of registered devices
443  *
444  * Locking: This function must be called under rcu_read_lock(). opp is a rcu
445  * protected pointer. The reason for the same is that the opp pointer which is
446  * returned will remain valid for use with opp_get_{voltage, freq} only while
447  * under the locked area. The pointer returned must be used prior to unlocking
448  * with rcu_read_unlock() to maintain the integrity of the pointer.
449  */
450 struct dev_pm_opp *dev_pm_opp_find_freq_ceil(struct device *dev,
451                                              unsigned long *freq)
452 {
453         struct opp_table *opp_table;
454         struct dev_pm_opp *temp_opp, *opp = ERR_PTR(-ERANGE);
455
456         opp_rcu_lockdep_assert();
457
458         if (!dev || !freq) {
459                 dev_err(dev, "%s: Invalid argument freq=%p\n", __func__, freq);
460                 return ERR_PTR(-EINVAL);
461         }
462
463         opp_table = _find_opp_table(dev);
464         if (IS_ERR(opp_table))
465                 return ERR_CAST(opp_table);
466
467         list_for_each_entry_rcu(temp_opp, &opp_table->opp_list, node) {
468                 if (temp_opp->available && temp_opp->rate >= *freq) {
469                         opp = temp_opp;
470                         *freq = opp->rate;
471                         break;
472                 }
473         }
474
475         return opp;
476 }
477 EXPORT_SYMBOL_GPL(dev_pm_opp_find_freq_ceil);
478
479 /**
480  * dev_pm_opp_find_freq_floor() - Search for a rounded floor freq
481  * @dev:        device for which we do this operation
482  * @freq:       Start frequency
483  *
484  * Search for the matching floor *available* OPP from a starting freq
485  * for a device.
486  *
487  * Return: matching *opp and refreshes *freq accordingly, else returns
488  * ERR_PTR in case of error and should be handled using IS_ERR. Error return
489  * values can be:
490  * EINVAL:      for bad pointer
491  * ERANGE:      no match found for search
492  * ENODEV:      if device not found in list of registered devices
493  *
494  * Locking: This function must be called under rcu_read_lock(). opp is a rcu
495  * protected pointer. The reason for the same is that the opp pointer which is
496  * returned will remain valid for use with opp_get_{voltage, freq} only while
497  * under the locked area. The pointer returned must be used prior to unlocking
498  * with rcu_read_unlock() to maintain the integrity of the pointer.
499  */
500 struct dev_pm_opp *dev_pm_opp_find_freq_floor(struct device *dev,
501                                               unsigned long *freq)
502 {
503         struct opp_table *opp_table;
504         struct dev_pm_opp *temp_opp, *opp = ERR_PTR(-ERANGE);
505
506         opp_rcu_lockdep_assert();
507
508         if (!dev || !freq) {
509                 dev_err(dev, "%s: Invalid argument freq=%p\n", __func__, freq);
510                 return ERR_PTR(-EINVAL);
511         }
512
513         opp_table = _find_opp_table(dev);
514         if (IS_ERR(opp_table))
515                 return ERR_CAST(opp_table);
516
517         list_for_each_entry_rcu(temp_opp, &opp_table->opp_list, node) {
518                 if (temp_opp->available) {
519                         /* go to the next node, before choosing prev */
520                         if (temp_opp->rate > *freq)
521                                 break;
522                         else
523                                 opp = temp_opp;
524                 }
525         }
526         if (!IS_ERR(opp))
527                 *freq = opp->rate;
528
529         return opp;
530 }
531 EXPORT_SYMBOL_GPL(dev_pm_opp_find_freq_floor);
532
533 /*
534  * The caller needs to ensure that opp_table (and hence the clk) isn't freed,
535  * while clk returned here is used.
536  */
537 static struct clk *_get_opp_clk(struct device *dev)
538 {
539         struct opp_table *opp_table;
540         struct clk *clk;
541
542         rcu_read_lock();
543
544         opp_table = _find_opp_table(dev);
545         if (IS_ERR(opp_table)) {
546                 dev_err(dev, "%s: device opp doesn't exist\n", __func__);
547                 clk = ERR_CAST(opp_table);
548                 goto unlock;
549         }
550
551         clk = opp_table->clk;
552         if (IS_ERR(clk))
553                 dev_err(dev, "%s: No clock available for the device\n",
554                         __func__);
555
556 unlock:
557         rcu_read_unlock();
558         return clk;
559 }
560
561 static int _set_opp_voltage(struct device *dev, struct regulator *reg,
562                             unsigned long u_volt, unsigned long u_volt_min,
563                             unsigned long u_volt_max)
564 {
565         int ret;
566
567         /* Regulator not available for device */
568         if (IS_ERR(reg)) {
569                 dev_dbg(dev, "%s: regulator not available: %ld\n", __func__,
570                         PTR_ERR(reg));
571                 return 0;
572         }
573
574         dev_dbg(dev, "%s: voltages (mV): %lu %lu %lu\n", __func__, u_volt_min,
575                 u_volt, u_volt_max);
576
577         ret = regulator_set_voltage_triplet(reg, u_volt_min, u_volt,
578                                             u_volt_max);
579         if (ret)
580                 dev_err(dev, "%s: failed to set voltage (%lu %lu %lu mV): %d\n",
581                         __func__, u_volt_min, u_volt, u_volt_max, ret);
582
583         return ret;
584 }
585
586 /**
587  * dev_pm_opp_set_rate() - Configure new OPP based on frequency
588  * @dev:         device for which we do this operation
589  * @target_freq: frequency to achieve
590  *
591  * This configures the power-supplies and clock source to the levels specified
592  * by the OPP corresponding to the target_freq.
593  *
594  * Locking: This function takes rcu_read_lock().
595  */
596 int dev_pm_opp_set_rate(struct device *dev, unsigned long target_freq)
597 {
598         struct opp_table *opp_table;
599         struct dev_pm_opp *old_opp, *opp;
600         struct regulator *reg;
601         struct clk *clk;
602         unsigned long freq, old_freq;
603         unsigned long u_volt, u_volt_min, u_volt_max;
604         unsigned long ou_volt, ou_volt_min, ou_volt_max;
605         int ret;
606
607         if (unlikely(!target_freq)) {
608                 dev_err(dev, "%s: Invalid target frequency %lu\n", __func__,
609                         target_freq);
610                 return -EINVAL;
611         }
612
613         clk = _get_opp_clk(dev);
614         if (IS_ERR(clk))
615                 return PTR_ERR(clk);
616
617         freq = clk_round_rate(clk, target_freq);
618         if ((long)freq <= 0)
619                 freq = target_freq;
620
621         old_freq = clk_get_rate(clk);
622
623         /* Return early if nothing to do */
624         if (old_freq == freq) {
625                 dev_dbg(dev, "%s: old/new frequencies (%lu Hz) are same, nothing to do\n",
626                         __func__, freq);
627                 return 0;
628         }
629
630         rcu_read_lock();
631
632         opp_table = _find_opp_table(dev);
633         if (IS_ERR(opp_table)) {
634                 dev_err(dev, "%s: device opp doesn't exist\n", __func__);
635                 rcu_read_unlock();
636                 return PTR_ERR(opp_table);
637         }
638
639         old_opp = dev_pm_opp_find_freq_ceil(dev, &old_freq);
640         if (!IS_ERR(old_opp)) {
641                 ou_volt = old_opp->u_volt;
642                 ou_volt_min = old_opp->u_volt_min;
643                 ou_volt_max = old_opp->u_volt_max;
644         } else {
645                 dev_err(dev, "%s: failed to find current OPP for freq %lu (%ld)\n",
646                         __func__, old_freq, PTR_ERR(old_opp));
647         }
648
649         opp = dev_pm_opp_find_freq_ceil(dev, &freq);
650         if (IS_ERR(opp)) {
651                 ret = PTR_ERR(opp);
652                 dev_err(dev, "%s: failed to find OPP for freq %lu (%d)\n",
653                         __func__, freq, ret);
654                 rcu_read_unlock();
655                 return ret;
656         }
657
658         u_volt = opp->u_volt;
659         u_volt_min = opp->u_volt_min;
660         u_volt_max = opp->u_volt_max;
661
662         reg = opp_table->regulator;
663
664         rcu_read_unlock();
665
666         /* Scaling up? Scale voltage before frequency */
667         if (freq > old_freq) {
668                 ret = _set_opp_voltage(dev, reg, u_volt, u_volt_min,
669                                        u_volt_max);
670                 if (ret)
671                         goto restore_voltage;
672         }
673
674         /* Change frequency */
675
676         dev_dbg(dev, "%s: switching OPP: %lu Hz --> %lu Hz\n",
677                 __func__, old_freq, freq);
678
679         ret = clk_set_rate(clk, freq);
680         if (ret) {
681                 dev_err(dev, "%s: failed to set clock rate: %d\n", __func__,
682                         ret);
683                 goto restore_voltage;
684         }
685
686         /* Scaling down? Scale voltage after frequency */
687         if (freq < old_freq) {
688                 ret = _set_opp_voltage(dev, reg, u_volt, u_volt_min,
689                                        u_volt_max);
690                 if (ret)
691                         goto restore_freq;
692         }
693
694         return 0;
695
696 restore_freq:
697         if (clk_set_rate(clk, old_freq))
698                 dev_err(dev, "%s: failed to restore old-freq (%lu Hz)\n",
699                         __func__, old_freq);
700 restore_voltage:
701         /* This shouldn't harm even if the voltages weren't updated earlier */
702         if (!IS_ERR(old_opp))
703                 _set_opp_voltage(dev, reg, ou_volt, ou_volt_min, ou_volt_max);
704
705         return ret;
706 }
707 EXPORT_SYMBOL_GPL(dev_pm_opp_set_rate);
708
709 /**
710  * dev_pm_opp_check_initial_rate() - Configure new OPP based on initial rate
711  * @dev:         device for which we do this operation
712  *
713  * This configures the power-supplies and clock source to the levels specified
714  * by the OPP corresponding to the system initial rate.
715  *
716  * Locking: This function takes rcu_read_lock().
717  */
718 int dev_pm_opp_check_initial_rate(struct device *dev, unsigned long *cur_freq)
719 {
720         struct opp_table *opp_table;
721         struct dev_pm_opp *opp;
722         struct regulator *reg;
723         struct clk *clk;
724         unsigned long target_freq, old_freq;
725         unsigned long u_volt, u_volt_min, u_volt_max;
726         int old_volt;
727         int ret;
728
729         rcu_read_lock();
730
731         opp_table = _find_opp_table(dev);
732         if (IS_ERR(opp_table)) {
733                 dev_err(dev, "%s: device opp doesn't exist\n", __func__);
734                 rcu_read_unlock();
735                 return PTR_ERR(opp_table);
736         }
737
738         clk = opp_table->clk;
739         reg = opp_table->regulator;
740         if (IS_ERR_OR_NULL(clk) || IS_ERR_OR_NULL(reg)) {
741                 dev_err(dev, "clk or regulater is unavailable\n");
742                 rcu_read_unlock();
743                 return -EINVAL;
744         }
745
746         old_freq = clk_get_rate(clk);
747         *cur_freq = old_freq;
748         target_freq = old_freq;
749
750         opp = dev_pm_opp_find_freq_ceil(dev, &target_freq);
751         if (IS_ERR(opp)) {
752                 opp = dev_pm_opp_find_freq_floor(dev, &target_freq);
753                 if (IS_ERR(opp)) {
754                         dev_err(dev, "failed to find OPP for freq %lu\n",
755                                 target_freq);
756                         rcu_read_unlock();
757                         return PTR_ERR(opp);
758                 }
759         }
760
761         u_volt = opp->u_volt;
762         u_volt_min = opp->u_volt_min;
763         u_volt_max = opp->u_volt_max;
764
765         rcu_read_unlock();
766
767         target_freq = clk_round_rate(clk, target_freq);
768         old_volt = regulator_get_voltage(reg);
769         if (old_volt <= 0) {
770                 dev_err(dev, "failed to get volt %d\n", old_volt);
771                 return -EINVAL;
772         }
773
774         dev_dbg(dev, "%lu Hz %d uV --> %lu Hz %lu uV\n", old_freq, old_volt,
775                 target_freq, u_volt);
776
777         if (old_freq == target_freq && old_volt == u_volt)
778                 return 0;
779
780         if (old_freq == target_freq && old_volt != u_volt) {
781                 ret = _set_opp_voltage(dev, reg, u_volt, u_volt_min,
782                                        u_volt_max);
783                 if (ret) {
784                         dev_err(dev, "failed to set volt %lu\n", u_volt);
785                         return ret;
786                 }
787                 return 0;
788         }
789
790         /* Scaling up? Scale voltage before frequency */
791         if (target_freq > old_freq) {
792                 ret = _set_opp_voltage(dev, reg, u_volt, u_volt_min,
793                                        u_volt_max);
794                 if (ret) {
795                         dev_err(dev, "failed to set volt %lu\n", u_volt);
796                         return ret;
797                 }
798         }
799
800         /* Change frequency */
801         ret = clk_set_rate(clk, target_freq);
802         if (ret) {
803                 dev_err(dev, "failed to set clock rate %lu\n", target_freq);
804                 return ret;
805         }
806
807         *cur_freq = clk_get_rate(clk);
808
809         /* Scaling down? Scale voltage after frequency */
810         if (target_freq < old_freq) {
811                 ret = _set_opp_voltage(dev, reg, u_volt, u_volt_min,
812                                        u_volt_max);
813                 if (ret) {
814                         dev_err(dev, "failed to set volt %lu\n", u_volt);
815                         return ret;
816                 }
817         }
818
819         return 0;
820 }
821 EXPORT_SYMBOL_GPL(dev_pm_opp_check_initial_rate);
822
823 /* OPP-dev Helpers */
824 static void _kfree_opp_dev_rcu(struct rcu_head *head)
825 {
826         struct opp_device *opp_dev;
827
828         opp_dev = container_of(head, struct opp_device, rcu_head);
829         kfree_rcu(opp_dev, rcu_head);
830 }
831
832 static void _remove_opp_dev(struct opp_device *opp_dev,
833                             struct opp_table *opp_table)
834 {
835         opp_debug_unregister(opp_dev, opp_table);
836         list_del(&opp_dev->node);
837         call_srcu(&opp_table->srcu_head.srcu, &opp_dev->rcu_head,
838                   _kfree_opp_dev_rcu);
839 }
840
841 struct opp_device *_add_opp_dev(const struct device *dev,
842                                 struct opp_table *opp_table)
843 {
844         struct opp_device *opp_dev;
845         int ret;
846
847         opp_dev = kzalloc(sizeof(*opp_dev), GFP_KERNEL);
848         if (!opp_dev)
849                 return NULL;
850
851         /* Initialize opp-dev */
852         opp_dev->dev = dev;
853         list_add_rcu(&opp_dev->node, &opp_table->dev_list);
854
855         /* Create debugfs entries for the opp_table */
856         ret = opp_debug_register(opp_dev, opp_table);
857         if (ret)
858                 dev_err(dev, "%s: Failed to register opp debugfs (%d)\n",
859                         __func__, ret);
860
861         return opp_dev;
862 }
863
864 /**
865  * _add_opp_table() - Find OPP table or allocate a new one
866  * @dev:        device for which we do this operation
867  *
868  * It tries to find an existing table first, if it couldn't find one, it
869  * allocates a new OPP table and returns that.
870  *
871  * Return: valid opp_table pointer if success, else NULL.
872  */
873 static struct opp_table *_add_opp_table(struct device *dev)
874 {
875         struct opp_table *opp_table;
876         struct opp_device *opp_dev;
877         struct device_node *np;
878         int ret;
879
880         /* Check for existing table for 'dev' first */
881         opp_table = _find_opp_table(dev);
882         if (!IS_ERR(opp_table))
883                 return opp_table;
884
885         /*
886          * Allocate a new OPP table. In the infrequent case where a new
887          * device is needed to be added, we pay this penalty.
888          */
889         opp_table = kzalloc(sizeof(*opp_table), GFP_KERNEL);
890         if (!opp_table)
891                 return NULL;
892
893         INIT_LIST_HEAD(&opp_table->dev_list);
894
895         opp_dev = _add_opp_dev(dev, opp_table);
896         if (!opp_dev) {
897                 kfree(opp_table);
898                 return NULL;
899         }
900
901         /*
902          * Only required for backward compatibility with v1 bindings, but isn't
903          * harmful for other cases. And so we do it unconditionally.
904          */
905         np = of_node_get(dev->of_node);
906         if (np) {
907                 u32 val;
908
909                 if (!of_property_read_u32(np, "clock-latency", &val))
910                         opp_table->clock_latency_ns_max = val;
911                 of_property_read_u32(np, "voltage-tolerance",
912                                      &opp_table->voltage_tolerance_v1);
913                 of_node_put(np);
914         }
915
916         /* Set regulator to a non-NULL error value */
917         opp_table->regulator = ERR_PTR(-ENXIO);
918
919         /* Find clk for the device */
920         opp_table->clk = clk_get(dev, NULL);
921         if (IS_ERR(opp_table->clk)) {
922                 ret = PTR_ERR(opp_table->clk);
923                 if (ret != -EPROBE_DEFER)
924                         dev_dbg(dev, "%s: Couldn't find clock: %d\n", __func__,
925                                 ret);
926         }
927
928         srcu_init_notifier_head(&opp_table->srcu_head);
929         INIT_LIST_HEAD(&opp_table->opp_list);
930
931         /* Secure the device table modification */
932         list_add_rcu(&opp_table->node, &opp_tables);
933         return opp_table;
934 }
935
936 /**
937  * _kfree_device_rcu() - Free opp_table RCU handler
938  * @head:       RCU head
939  */
940 static void _kfree_device_rcu(struct rcu_head *head)
941 {
942         struct opp_table *opp_table = container_of(head, struct opp_table,
943                                                    rcu_head);
944
945         kfree_rcu(opp_table, rcu_head);
946 }
947
948 /**
949  * _remove_opp_table() - Removes a OPP table
950  * @opp_table: OPP table to be removed.
951  *
952  * Removes/frees OPP table if it doesn't contain any OPPs.
953  */
954 static void _remove_opp_table(struct opp_table *opp_table)
955 {
956         struct opp_device *opp_dev;
957
958         if (!list_empty(&opp_table->opp_list))
959                 return;
960
961         if (opp_table->supported_hw)
962                 return;
963
964         if (opp_table->prop_name)
965                 return;
966
967         if (!IS_ERR(opp_table->regulator))
968                 return;
969
970         /* Release clk */
971         if (!IS_ERR(opp_table->clk))
972                 clk_put(opp_table->clk);
973
974         opp_dev = list_first_entry(&opp_table->dev_list, struct opp_device,
975                                    node);
976
977         _remove_opp_dev(opp_dev, opp_table);
978
979         /* dev_list must be empty now */
980         WARN_ON(!list_empty(&opp_table->dev_list));
981
982         list_del_rcu(&opp_table->node);
983         call_srcu(&opp_table->srcu_head.srcu, &opp_table->rcu_head,
984                   _kfree_device_rcu);
985 }
986
987 /**
988  * _kfree_opp_rcu() - Free OPP RCU handler
989  * @head:       RCU head
990  */
991 static void _kfree_opp_rcu(struct rcu_head *head)
992 {
993         struct dev_pm_opp *opp = container_of(head, struct dev_pm_opp, rcu_head);
994
995         kfree_rcu(opp, rcu_head);
996 }
997
998 /**
999  * _opp_remove()  - Remove an OPP from a table definition
1000  * @opp_table:  points back to the opp_table struct this opp belongs to
1001  * @opp:        pointer to the OPP to remove
1002  * @notify:     OPP_EVENT_REMOVE notification should be sent or not
1003  *
1004  * This function removes an opp definition from the opp table.
1005  *
1006  * Locking: The internal opp_table and opp structures are RCU protected.
1007  * It is assumed that the caller holds required mutex for an RCU updater
1008  * strategy.
1009  */
1010 static void _opp_remove(struct opp_table *opp_table,
1011                         struct dev_pm_opp *opp, bool notify)
1012 {
1013         /*
1014          * Notify the changes in the availability of the operable
1015          * frequency/voltage list.
1016          */
1017         if (notify)
1018                 srcu_notifier_call_chain(&opp_table->srcu_head,
1019                                          OPP_EVENT_REMOVE, opp);
1020         opp_debug_remove_one(opp);
1021         list_del_rcu(&opp->node);
1022         call_srcu(&opp_table->srcu_head.srcu, &opp->rcu_head, _kfree_opp_rcu);
1023
1024         _remove_opp_table(opp_table);
1025 }
1026
1027 /**
1028  * dev_pm_opp_remove()  - Remove an OPP from OPP table
1029  * @dev:        device for which we do this operation
1030  * @freq:       OPP to remove with matching 'freq'
1031  *
1032  * This function removes an opp from the opp table.
1033  *
1034  * Locking: The internal opp_table and opp structures are RCU protected.
1035  * Hence this function internally uses RCU updater strategy with mutex locks
1036  * to keep the integrity of the internal data structures. Callers should ensure
1037  * that this function is *NOT* called under RCU protection or in contexts where
1038  * mutex cannot be locked.
1039  */
1040 void dev_pm_opp_remove(struct device *dev, unsigned long freq)
1041 {
1042         struct dev_pm_opp *opp;
1043         struct opp_table *opp_table;
1044         bool found = false;
1045
1046         /* Hold our table modification lock here */
1047         mutex_lock(&opp_table_lock);
1048
1049         opp_table = _find_opp_table(dev);
1050         if (IS_ERR(opp_table))
1051                 goto unlock;
1052
1053         list_for_each_entry(opp, &opp_table->opp_list, node) {
1054                 if (opp->rate == freq) {
1055                         found = true;
1056                         break;
1057                 }
1058         }
1059
1060         if (!found) {
1061                 dev_warn(dev, "%s: Couldn't find OPP with freq: %lu\n",
1062                          __func__, freq);
1063                 goto unlock;
1064         }
1065
1066         _opp_remove(opp_table, opp, true);
1067 unlock:
1068         mutex_unlock(&opp_table_lock);
1069 }
1070 EXPORT_SYMBOL_GPL(dev_pm_opp_remove);
1071
1072 static struct dev_pm_opp *_allocate_opp(struct device *dev,
1073                                         struct opp_table **opp_table)
1074 {
1075         struct dev_pm_opp *opp;
1076
1077         /* allocate new OPP node */
1078         opp = kzalloc(sizeof(*opp), GFP_KERNEL);
1079         if (!opp)
1080                 return NULL;
1081
1082         INIT_LIST_HEAD(&opp->node);
1083
1084         *opp_table = _add_opp_table(dev);
1085         if (!*opp_table) {
1086                 kfree(opp);
1087                 return NULL;
1088         }
1089
1090         return opp;
1091 }
1092
1093 static bool _opp_supported_by_regulators(struct dev_pm_opp *opp,
1094                                          struct opp_table *opp_table)
1095 {
1096         struct regulator *reg = opp_table->regulator;
1097
1098         if (!IS_ERR(reg) &&
1099             !regulator_is_supported_voltage(reg, opp->u_volt_min,
1100                                             opp->u_volt_max)) {
1101                 pr_warn("%s: OPP minuV: %lu maxuV: %lu, not supported by regulator\n",
1102                         __func__, opp->u_volt_min, opp->u_volt_max);
1103                 return false;
1104         }
1105
1106         return true;
1107 }
1108
1109 static int _opp_add(struct device *dev, struct dev_pm_opp *new_opp,
1110                     struct opp_table *opp_table)
1111 {
1112         struct dev_pm_opp *opp;
1113         struct list_head *head = &opp_table->opp_list;
1114         int ret;
1115
1116         /*
1117          * Insert new OPP in order of increasing frequency and discard if
1118          * already present.
1119          *
1120          * Need to use &opp_table->opp_list in the condition part of the 'for'
1121          * loop, don't replace it with head otherwise it will become an infinite
1122          * loop.
1123          */
1124         list_for_each_entry_rcu(opp, &opp_table->opp_list, node) {
1125                 if (new_opp->rate > opp->rate) {
1126                         head = &opp->node;
1127                         continue;
1128                 }
1129
1130                 if (new_opp->rate < opp->rate)
1131                         break;
1132
1133                 /* Duplicate OPPs */
1134                 dev_warn(dev, "%s: duplicate OPPs detected. Existing: freq: %lu, volt: %lu, enabled: %d. New: freq: %lu, volt: %lu, enabled: %d\n",
1135                          __func__, opp->rate, opp->u_volt, opp->available,
1136                          new_opp->rate, new_opp->u_volt, new_opp->available);
1137
1138                 return opp->available && new_opp->u_volt == opp->u_volt ?
1139                         0 : -EEXIST;
1140         }
1141
1142         new_opp->opp_table = opp_table;
1143         list_add_rcu(&new_opp->node, head);
1144
1145         ret = opp_debug_create_one(new_opp, opp_table);
1146         if (ret)
1147                 dev_err(dev, "%s: Failed to register opp to debugfs (%d)\n",
1148                         __func__, ret);
1149
1150         if (!_opp_supported_by_regulators(new_opp, opp_table)) {
1151                 new_opp->available = false;
1152                 dev_warn(dev, "%s: OPP not supported by regulators (%lu)\n",
1153                          __func__, new_opp->rate);
1154         }
1155
1156         return 0;
1157 }
1158
1159 /**
1160  * _opp_add_v1() - Allocate a OPP based on v1 bindings.
1161  * @dev:        device for which we do this operation
1162  * @freq:       Frequency in Hz for this OPP
1163  * @u_volt:     Voltage in uVolts for this OPP
1164  * @dynamic:    Dynamically added OPPs.
1165  *
1166  * This function adds an opp definition to the opp table and returns status.
1167  * The opp is made available by default and it can be controlled using
1168  * dev_pm_opp_enable/disable functions and may be removed by dev_pm_opp_remove.
1169  *
1170  * NOTE: "dynamic" parameter impacts OPPs added by the dev_pm_opp_of_add_table
1171  * and freed by dev_pm_opp_of_remove_table.
1172  *
1173  * Locking: The internal opp_table and opp structures are RCU protected.
1174  * Hence this function internally uses RCU updater strategy with mutex locks
1175  * to keep the integrity of the internal data structures. Callers should ensure
1176  * that this function is *NOT* called under RCU protection or in contexts where
1177  * mutex cannot be locked.
1178  *
1179  * Return:
1180  * 0            On success OR
1181  *              Duplicate OPPs (both freq and volt are same) and opp->available
1182  * -EEXIST      Freq are same and volt are different OR
1183  *              Duplicate OPPs (both freq and volt are same) and !opp->available
1184  * -ENOMEM      Memory allocation failure
1185  */
1186 static int _opp_add_v1(struct device *dev, unsigned long freq, long u_volt,
1187                        bool dynamic)
1188 {
1189         struct opp_table *opp_table;
1190         struct dev_pm_opp *new_opp;
1191         unsigned long tol;
1192         int ret;
1193
1194         /* Hold our table modification lock here */
1195         mutex_lock(&opp_table_lock);
1196
1197         new_opp = _allocate_opp(dev, &opp_table);
1198         if (!new_opp) {
1199                 ret = -ENOMEM;
1200                 goto unlock;
1201         }
1202
1203         /* populate the opp table */
1204         new_opp->rate = freq;
1205         tol = u_volt * opp_table->voltage_tolerance_v1 / 100;
1206         new_opp->u_volt = u_volt;
1207         new_opp->u_volt_min = u_volt - tol;
1208         new_opp->u_volt_max = u_volt + tol;
1209         new_opp->available = true;
1210         new_opp->dynamic = dynamic;
1211
1212         ret = _opp_add(dev, new_opp, opp_table);
1213         if (ret)
1214                 goto free_opp;
1215
1216         mutex_unlock(&opp_table_lock);
1217
1218         /*
1219          * Notify the changes in the availability of the operable
1220          * frequency/voltage list.
1221          */
1222         srcu_notifier_call_chain(&opp_table->srcu_head, OPP_EVENT_ADD, new_opp);
1223         return 0;
1224
1225 free_opp:
1226         _opp_remove(opp_table, new_opp, false);
1227 unlock:
1228         mutex_unlock(&opp_table_lock);
1229         return ret;
1230 }
1231
1232 /* TODO: Support multiple regulators */
1233 static int opp_parse_supplies(struct dev_pm_opp *opp, struct device *dev,
1234                               struct opp_table *opp_table)
1235 {
1236         u32 microvolt[3] = {0};
1237         u32 val;
1238         int count, ret;
1239         struct property *prop = NULL;
1240         char name[NAME_MAX];
1241
1242         /* Search for "opp-microvolt-<name>" */
1243         if (opp_table->prop_name) {
1244                 snprintf(name, sizeof(name), "opp-microvolt-%s",
1245                          opp_table->prop_name);
1246                 prop = of_find_property(opp->np, name, NULL);
1247         }
1248
1249         if (!prop) {
1250                 /* Search for "opp-microvolt" */
1251                 sprintf(name, "opp-microvolt");
1252                 prop = of_find_property(opp->np, name, NULL);
1253
1254                 /* Missing property isn't a problem, but an invalid entry is */
1255                 if (!prop)
1256                         return 0;
1257         }
1258
1259         count = of_property_count_u32_elems(opp->np, name);
1260         if (count < 0) {
1261                 dev_err(dev, "%s: Invalid %s property (%d)\n",
1262                         __func__, name, count);
1263                 return count;
1264         }
1265
1266         /* There can be one or three elements here */
1267         if (count != 1 && count != 3) {
1268                 dev_err(dev, "%s: Invalid number of elements in %s property (%d)\n",
1269                         __func__, name, count);
1270                 return -EINVAL;
1271         }
1272
1273         ret = of_property_read_u32_array(opp->np, name, microvolt, count);
1274         if (ret) {
1275                 dev_err(dev, "%s: error parsing %s: %d\n", __func__, name, ret);
1276                 return -EINVAL;
1277         }
1278
1279         opp->u_volt = microvolt[0];
1280
1281         if (count == 1) {
1282                 opp->u_volt_min = opp->u_volt;
1283                 opp->u_volt_max = opp->u_volt;
1284         } else {
1285                 opp->u_volt_min = microvolt[1];
1286                 opp->u_volt_max = microvolt[2];
1287         }
1288
1289         /* Search for "opp-microamp-<name>" */
1290         prop = NULL;
1291         if (opp_table->prop_name) {
1292                 snprintf(name, sizeof(name), "opp-microamp-%s",
1293                          opp_table->prop_name);
1294                 prop = of_find_property(opp->np, name, NULL);
1295         }
1296
1297         if (!prop) {
1298                 /* Search for "opp-microamp" */
1299                 sprintf(name, "opp-microamp");
1300                 prop = of_find_property(opp->np, name, NULL);
1301         }
1302
1303         if (prop && !of_property_read_u32(opp->np, name, &val))
1304                 opp->u_amp = val;
1305
1306         return 0;
1307 }
1308
1309 /**
1310  * dev_pm_opp_set_supported_hw() - Set supported platforms
1311  * @dev: Device for which supported-hw has to be set.
1312  * @versions: Array of hierarchy of versions to match.
1313  * @count: Number of elements in the array.
1314  *
1315  * This is required only for the V2 bindings, and it enables a platform to
1316  * specify the hierarchy of versions it supports. OPP layer will then enable
1317  * OPPs, which are available for those versions, based on its 'opp-supported-hw'
1318  * property.
1319  *
1320  * Locking: The internal opp_table and opp structures are RCU protected.
1321  * Hence this function internally uses RCU updater strategy with mutex locks
1322  * to keep the integrity of the internal data structures. Callers should ensure
1323  * that this function is *NOT* called under RCU protection or in contexts where
1324  * mutex cannot be locked.
1325  */
1326 int dev_pm_opp_set_supported_hw(struct device *dev, const u32 *versions,
1327                                 unsigned int count)
1328 {
1329         struct opp_table *opp_table;
1330         int ret = 0;
1331
1332         /* Hold our table modification lock here */
1333         mutex_lock(&opp_table_lock);
1334
1335         opp_table = _add_opp_table(dev);
1336         if (!opp_table) {
1337                 ret = -ENOMEM;
1338                 goto unlock;
1339         }
1340
1341         /* Make sure there are no concurrent readers while updating opp_table */
1342         WARN_ON(!list_empty(&opp_table->opp_list));
1343
1344         /* Do we already have a version hierarchy associated with opp_table? */
1345         if (opp_table->supported_hw) {
1346                 dev_err(dev, "%s: Already have supported hardware list\n",
1347                         __func__);
1348                 ret = -EBUSY;
1349                 goto err;
1350         }
1351
1352         opp_table->supported_hw = kmemdup(versions, count * sizeof(*versions),
1353                                         GFP_KERNEL);
1354         if (!opp_table->supported_hw) {
1355                 ret = -ENOMEM;
1356                 goto err;
1357         }
1358
1359         opp_table->supported_hw_count = count;
1360         mutex_unlock(&opp_table_lock);
1361         return 0;
1362
1363 err:
1364         _remove_opp_table(opp_table);
1365 unlock:
1366         mutex_unlock(&opp_table_lock);
1367
1368         return ret;
1369 }
1370 EXPORT_SYMBOL_GPL(dev_pm_opp_set_supported_hw);
1371
1372 /**
1373  * dev_pm_opp_put_supported_hw() - Releases resources blocked for supported hw
1374  * @dev: Device for which supported-hw has to be put.
1375  *
1376  * This is required only for the V2 bindings, and is called for a matching
1377  * dev_pm_opp_set_supported_hw(). Until this is called, the opp_table structure
1378  * will not be freed.
1379  *
1380  * Locking: The internal opp_table and opp structures are RCU protected.
1381  * Hence this function internally uses RCU updater strategy with mutex locks
1382  * to keep the integrity of the internal data structures. Callers should ensure
1383  * that this function is *NOT* called under RCU protection or in contexts where
1384  * mutex cannot be locked.
1385  */
1386 void dev_pm_opp_put_supported_hw(struct device *dev)
1387 {
1388         struct opp_table *opp_table;
1389
1390         /* Hold our table modification lock here */
1391         mutex_lock(&opp_table_lock);
1392
1393         /* Check for existing table for 'dev' first */
1394         opp_table = _find_opp_table(dev);
1395         if (IS_ERR(opp_table)) {
1396                 dev_err(dev, "Failed to find opp_table: %ld\n",
1397                         PTR_ERR(opp_table));
1398                 goto unlock;
1399         }
1400
1401         /* Make sure there are no concurrent readers while updating opp_table */
1402         WARN_ON(!list_empty(&opp_table->opp_list));
1403
1404         if (!opp_table->supported_hw) {
1405                 dev_err(dev, "%s: Doesn't have supported hardware list\n",
1406                         __func__);
1407                 goto unlock;
1408         }
1409
1410         kfree(opp_table->supported_hw);
1411         opp_table->supported_hw = NULL;
1412         opp_table->supported_hw_count = 0;
1413
1414         /* Try freeing opp_table if this was the last blocking resource */
1415         _remove_opp_table(opp_table);
1416
1417 unlock:
1418         mutex_unlock(&opp_table_lock);
1419 }
1420 EXPORT_SYMBOL_GPL(dev_pm_opp_put_supported_hw);
1421
1422 /**
1423  * dev_pm_opp_set_prop_name() - Set prop-extn name
1424  * @dev: Device for which the prop-name has to be set.
1425  * @name: name to postfix to properties.
1426  *
1427  * This is required only for the V2 bindings, and it enables a platform to
1428  * specify the extn to be used for certain property names. The properties to
1429  * which the extension will apply are opp-microvolt and opp-microamp. OPP core
1430  * should postfix the property name with -<name> while looking for them.
1431  *
1432  * Locking: The internal opp_table and opp structures are RCU protected.
1433  * Hence this function internally uses RCU updater strategy with mutex locks
1434  * to keep the integrity of the internal data structures. Callers should ensure
1435  * that this function is *NOT* called under RCU protection or in contexts where
1436  * mutex cannot be locked.
1437  */
1438 int dev_pm_opp_set_prop_name(struct device *dev, const char *name)
1439 {
1440         struct opp_table *opp_table;
1441         int ret = 0;
1442
1443         /* Hold our table modification lock here */
1444         mutex_lock(&opp_table_lock);
1445
1446         opp_table = _add_opp_table(dev);
1447         if (!opp_table) {
1448                 ret = -ENOMEM;
1449                 goto unlock;
1450         }
1451
1452         /* Make sure there are no concurrent readers while updating opp_table */
1453         WARN_ON(!list_empty(&opp_table->opp_list));
1454
1455         /* Do we already have a prop-name associated with opp_table? */
1456         if (opp_table->prop_name) {
1457                 dev_err(dev, "%s: Already have prop-name %s\n", __func__,
1458                         opp_table->prop_name);
1459                 ret = -EBUSY;
1460                 goto err;
1461         }
1462
1463         opp_table->prop_name = kstrdup(name, GFP_KERNEL);
1464         if (!opp_table->prop_name) {
1465                 ret = -ENOMEM;
1466                 goto err;
1467         }
1468
1469         mutex_unlock(&opp_table_lock);
1470         return 0;
1471
1472 err:
1473         _remove_opp_table(opp_table);
1474 unlock:
1475         mutex_unlock(&opp_table_lock);
1476
1477         return ret;
1478 }
1479 EXPORT_SYMBOL_GPL(dev_pm_opp_set_prop_name);
1480
1481 /**
1482  * dev_pm_opp_put_prop_name() - Releases resources blocked for prop-name
1483  * @dev: Device for which the prop-name has to be put.
1484  *
1485  * This is required only for the V2 bindings, and is called for a matching
1486  * dev_pm_opp_set_prop_name(). Until this is called, the opp_table structure
1487  * will not be freed.
1488  *
1489  * Locking: The internal opp_table and opp structures are RCU protected.
1490  * Hence this function internally uses RCU updater strategy with mutex locks
1491  * to keep the integrity of the internal data structures. Callers should ensure
1492  * that this function is *NOT* called under RCU protection or in contexts where
1493  * mutex cannot be locked.
1494  */
1495 void dev_pm_opp_put_prop_name(struct device *dev)
1496 {
1497         struct opp_table *opp_table;
1498
1499         /* Hold our table modification lock here */
1500         mutex_lock(&opp_table_lock);
1501
1502         /* Check for existing table for 'dev' first */
1503         opp_table = _find_opp_table(dev);
1504         if (IS_ERR(opp_table)) {
1505                 dev_err(dev, "Failed to find opp_table: %ld\n",
1506                         PTR_ERR(opp_table));
1507                 goto unlock;
1508         }
1509
1510         /* Make sure there are no concurrent readers while updating opp_table */
1511         WARN_ON(!list_empty(&opp_table->opp_list));
1512
1513         if (!opp_table->prop_name) {
1514                 dev_err(dev, "%s: Doesn't have a prop-name\n", __func__);
1515                 goto unlock;
1516         }
1517
1518         kfree(opp_table->prop_name);
1519         opp_table->prop_name = NULL;
1520
1521         /* Try freeing opp_table if this was the last blocking resource */
1522         _remove_opp_table(opp_table);
1523
1524 unlock:
1525         mutex_unlock(&opp_table_lock);
1526 }
1527 EXPORT_SYMBOL_GPL(dev_pm_opp_put_prop_name);
1528
1529 /**
1530  * dev_pm_opp_set_regulator() - Set regulator name for the device
1531  * @dev: Device for which regulator name is being set.
1532  * @name: Name of the regulator.
1533  *
1534  * In order to support OPP switching, OPP layer needs to know the name of the
1535  * device's regulator, as the core would be required to switch voltages as well.
1536  *
1537  * This must be called before any OPPs are initialized for the device.
1538  *
1539  * Locking: The internal opp_table and opp structures are RCU protected.
1540  * Hence this function internally uses RCU updater strategy with mutex locks
1541  * to keep the integrity of the internal data structures. Callers should ensure
1542  * that this function is *NOT* called under RCU protection or in contexts where
1543  * mutex cannot be locked.
1544  */
1545 int dev_pm_opp_set_regulator(struct device *dev, const char *name)
1546 {
1547         struct opp_table *opp_table;
1548         struct regulator *reg;
1549         int ret;
1550
1551         mutex_lock(&opp_table_lock);
1552
1553         opp_table = _add_opp_table(dev);
1554         if (!opp_table) {
1555                 ret = -ENOMEM;
1556                 goto unlock;
1557         }
1558
1559         /* This should be called before OPPs are initialized */
1560         if (WARN_ON(!list_empty(&opp_table->opp_list))) {
1561                 ret = -EBUSY;
1562                 goto err;
1563         }
1564
1565         /* Already have a regulator set */
1566         if (WARN_ON(!IS_ERR(opp_table->regulator))) {
1567                 ret = -EBUSY;
1568                 goto err;
1569         }
1570         /* Allocate the regulator */
1571         reg = regulator_get_optional(dev, name);
1572         if (IS_ERR(reg)) {
1573                 ret = PTR_ERR(reg);
1574                 if (ret != -EPROBE_DEFER)
1575                         dev_err(dev, "%s: no regulator (%s) found: %d\n",
1576                                 __func__, name, ret);
1577                 goto err;
1578         }
1579
1580         opp_table->regulator = reg;
1581
1582         mutex_unlock(&opp_table_lock);
1583         return 0;
1584
1585 err:
1586         _remove_opp_table(opp_table);
1587 unlock:
1588         mutex_unlock(&opp_table_lock);
1589
1590         return ret;
1591 }
1592 EXPORT_SYMBOL_GPL(dev_pm_opp_set_regulator);
1593
1594 /**
1595  * dev_pm_opp_put_regulator() - Releases resources blocked for regulator
1596  * @dev: Device for which regulator was set.
1597  *
1598  * Locking: The internal opp_table and opp structures are RCU protected.
1599  * Hence this function internally uses RCU updater strategy with mutex locks
1600  * to keep the integrity of the internal data structures. Callers should ensure
1601  * that this function is *NOT* called under RCU protection or in contexts where
1602  * mutex cannot be locked.
1603  */
1604 void dev_pm_opp_put_regulator(struct device *dev)
1605 {
1606         struct opp_table *opp_table;
1607
1608         mutex_lock(&opp_table_lock);
1609
1610         /* Check for existing table for 'dev' first */
1611         opp_table = _find_opp_table(dev);
1612         if (IS_ERR(opp_table)) {
1613                 dev_err(dev, "Failed to find opp_table: %ld\n",
1614                         PTR_ERR(opp_table));
1615                 goto unlock;
1616         }
1617
1618         if (IS_ERR(opp_table->regulator)) {
1619                 dev_err(dev, "%s: Doesn't have regulator set\n", __func__);
1620                 goto unlock;
1621         }
1622
1623         /* Make sure there are no concurrent readers while updating opp_table */
1624         WARN_ON(!list_empty(&opp_table->opp_list));
1625
1626         regulator_put(opp_table->regulator);
1627         opp_table->regulator = ERR_PTR(-ENXIO);
1628
1629         /* Try freeing opp_table if this was the last blocking resource */
1630         _remove_opp_table(opp_table);
1631
1632 unlock:
1633         mutex_unlock(&opp_table_lock);
1634 }
1635 EXPORT_SYMBOL_GPL(dev_pm_opp_put_regulator);
1636
1637 static bool _opp_is_supported(struct device *dev, struct opp_table *opp_table,
1638                               struct device_node *np)
1639 {
1640         unsigned int count = opp_table->supported_hw_count;
1641         u32 version;
1642         int ret;
1643
1644         if (!opp_table->supported_hw)
1645                 return true;
1646
1647         while (count--) {
1648                 ret = of_property_read_u32_index(np, "opp-supported-hw", count,
1649                                                  &version);
1650                 if (ret) {
1651                         dev_warn(dev, "%s: failed to read opp-supported-hw property at index %d: %d\n",
1652                                  __func__, count, ret);
1653                         return false;
1654                 }
1655
1656                 /* Both of these are bitwise masks of the versions */
1657                 if (!(version & opp_table->supported_hw[count]))
1658                         return false;
1659         }
1660
1661         return true;
1662 }
1663
1664 /**
1665  * _opp_add_static_v2() - Allocate static OPPs (As per 'v2' DT bindings)
1666  * @dev:        device for which we do this operation
1667  * @np:         device node
1668  *
1669  * This function adds an opp definition to the opp table and returns status. The
1670  * opp can be controlled using dev_pm_opp_enable/disable functions and may be
1671  * removed by dev_pm_opp_remove.
1672  *
1673  * Locking: The internal opp_table and opp structures are RCU protected.
1674  * Hence this function internally uses RCU updater strategy with mutex locks
1675  * to keep the integrity of the internal data structures. Callers should ensure
1676  * that this function is *NOT* called under RCU protection or in contexts where
1677  * mutex cannot be locked.
1678  *
1679  * Return:
1680  * 0            On success OR
1681  *              Duplicate OPPs (both freq and volt are same) and opp->available
1682  * -EEXIST      Freq are same and volt are different OR
1683  *              Duplicate OPPs (both freq and volt are same) and !opp->available
1684  * -ENOMEM      Memory allocation failure
1685  * -EINVAL      Failed parsing the OPP node
1686  */
1687 static int _opp_add_static_v2(struct device *dev, struct device_node *np)
1688 {
1689         struct opp_table *opp_table;
1690         struct dev_pm_opp *new_opp;
1691         u64 rate;
1692         u32 val;
1693         int ret;
1694
1695         /* Hold our table modification lock here */
1696         mutex_lock(&opp_table_lock);
1697
1698         new_opp = _allocate_opp(dev, &opp_table);
1699         if (!new_opp) {
1700                 ret = -ENOMEM;
1701                 goto unlock;
1702         }
1703
1704         ret = of_property_read_u64(np, "opp-hz", &rate);
1705         if (ret < 0) {
1706                 dev_err(dev, "%s: opp-hz not found\n", __func__);
1707                 goto free_opp;
1708         }
1709
1710         /* Check if the OPP supports hardware's hierarchy of versions or not */
1711         if (!_opp_is_supported(dev, opp_table, np)) {
1712                 dev_dbg(dev, "OPP not supported by hardware: %llu\n", rate);
1713                 goto free_opp;
1714         }
1715
1716         /*
1717          * Rate is defined as an unsigned long in clk API, and so casting
1718          * explicitly to its type. Must be fixed once rate is 64 bit
1719          * guaranteed in clk API.
1720          */
1721         new_opp->rate = (unsigned long)rate;
1722         new_opp->turbo = of_property_read_bool(np, "turbo-mode");
1723
1724         new_opp->np = np;
1725         new_opp->dynamic = false;
1726         new_opp->available = true;
1727
1728         if (!of_property_read_u32(np, "clock-latency-ns", &val))
1729                 new_opp->clock_latency_ns = val;
1730
1731         ret = opp_parse_supplies(new_opp, dev, opp_table);
1732         if (ret)
1733                 goto free_opp;
1734
1735         ret = _opp_add(dev, new_opp, opp_table);
1736         if (ret)
1737                 goto free_opp;
1738
1739         /* OPP to select on device suspend */
1740         if (of_property_read_bool(np, "opp-suspend")) {
1741                 if (opp_table->suspend_opp) {
1742                         dev_warn(dev, "%s: Multiple suspend OPPs found (%lu %lu)\n",
1743                                  __func__, opp_table->suspend_opp->rate,
1744                                  new_opp->rate);
1745                 } else {
1746                         new_opp->suspend = true;
1747                         opp_table->suspend_opp = new_opp;
1748                 }
1749         }
1750
1751         if (new_opp->clock_latency_ns > opp_table->clock_latency_ns_max)
1752                 opp_table->clock_latency_ns_max = new_opp->clock_latency_ns;
1753
1754         mutex_unlock(&opp_table_lock);
1755
1756         pr_debug("%s: turbo:%d rate:%lu uv:%lu uvmin:%lu uvmax:%lu latency:%lu\n",
1757                  __func__, new_opp->turbo, new_opp->rate, new_opp->u_volt,
1758                  new_opp->u_volt_min, new_opp->u_volt_max,
1759                  new_opp->clock_latency_ns);
1760
1761         /*
1762          * Notify the changes in the availability of the operable
1763          * frequency/voltage list.
1764          */
1765         srcu_notifier_call_chain(&opp_table->srcu_head, OPP_EVENT_ADD, new_opp);
1766         return 0;
1767
1768 free_opp:
1769         _opp_remove(opp_table, new_opp, false);
1770 unlock:
1771         mutex_unlock(&opp_table_lock);
1772         return ret;
1773 }
1774
1775 /**
1776  * dev_pm_opp_add()  - Add an OPP table from a table definitions
1777  * @dev:        device for which we do this operation
1778  * @freq:       Frequency in Hz for this OPP
1779  * @u_volt:     Voltage in uVolts for this OPP
1780  *
1781  * This function adds an opp definition to the opp table and returns status.
1782  * The opp is made available by default and it can be controlled using
1783  * dev_pm_opp_enable/disable functions.
1784  *
1785  * Locking: The internal opp_table and opp structures are RCU protected.
1786  * Hence this function internally uses RCU updater strategy with mutex locks
1787  * to keep the integrity of the internal data structures. Callers should ensure
1788  * that this function is *NOT* called under RCU protection or in contexts where
1789  * mutex cannot be locked.
1790  *
1791  * Return:
1792  * 0            On success OR
1793  *              Duplicate OPPs (both freq and volt are same) and opp->available
1794  * -EEXIST      Freq are same and volt are different OR
1795  *              Duplicate OPPs (both freq and volt are same) and !opp->available
1796  * -ENOMEM      Memory allocation failure
1797  */
1798 int dev_pm_opp_add(struct device *dev, unsigned long freq, unsigned long u_volt)
1799 {
1800         return _opp_add_v1(dev, freq, u_volt, true);
1801 }
1802 EXPORT_SYMBOL_GPL(dev_pm_opp_add);
1803
1804 /**
1805  * _opp_set_availability() - helper to set the availability of an opp
1806  * @dev:                device for which we do this operation
1807  * @freq:               OPP frequency to modify availability
1808  * @availability_req:   availability status requested for this opp
1809  *
1810  * Set the availability of an OPP with an RCU operation, opp_{enable,disable}
1811  * share a common logic which is isolated here.
1812  *
1813  * Return: -EINVAL for bad pointers, -ENOMEM if no memory available for the
1814  * copy operation, returns 0 if no modification was done OR modification was
1815  * successful.
1816  *
1817  * Locking: The internal opp_table and opp structures are RCU protected.
1818  * Hence this function internally uses RCU updater strategy with mutex locks to
1819  * keep the integrity of the internal data structures. Callers should ensure
1820  * that this function is *NOT* called under RCU protection or in contexts where
1821  * mutex locking or synchronize_rcu() blocking calls cannot be used.
1822  */
1823 static int _opp_set_availability(struct device *dev, unsigned long freq,
1824                                  bool availability_req)
1825 {
1826         struct opp_table *opp_table;
1827         struct dev_pm_opp *new_opp, *tmp_opp, *opp = ERR_PTR(-ENODEV);
1828         int r = 0;
1829
1830         /* keep the node allocated */
1831         new_opp = kmalloc(sizeof(*new_opp), GFP_KERNEL);
1832         if (!new_opp)
1833                 return -ENOMEM;
1834
1835         mutex_lock(&opp_table_lock);
1836
1837         /* Find the opp_table */
1838         opp_table = _find_opp_table(dev);
1839         if (IS_ERR(opp_table)) {
1840                 r = PTR_ERR(opp_table);
1841                 dev_warn(dev, "%s: Device OPP not found (%d)\n", __func__, r);
1842                 goto unlock;
1843         }
1844
1845         /* Do we have the frequency? */
1846         list_for_each_entry(tmp_opp, &opp_table->opp_list, node) {
1847                 if (tmp_opp->rate == freq) {
1848                         opp = tmp_opp;
1849                         break;
1850                 }
1851         }
1852         if (IS_ERR(opp)) {
1853                 r = PTR_ERR(opp);
1854                 goto unlock;
1855         }
1856
1857         /* Is update really needed? */
1858         if (opp->available == availability_req)
1859                 goto unlock;
1860         /* copy the old data over */
1861         *new_opp = *opp;
1862
1863         /* plug in new node */
1864         new_opp->available = availability_req;
1865
1866         list_replace_rcu(&opp->node, &new_opp->node);
1867         mutex_unlock(&opp_table_lock);
1868         call_srcu(&opp_table->srcu_head.srcu, &opp->rcu_head, _kfree_opp_rcu);
1869
1870         /* Notify the change of the OPP availability */
1871         if (availability_req)
1872                 srcu_notifier_call_chain(&opp_table->srcu_head,
1873                                          OPP_EVENT_ENABLE, new_opp);
1874         else
1875                 srcu_notifier_call_chain(&opp_table->srcu_head,
1876                                          OPP_EVENT_DISABLE, new_opp);
1877
1878         return 0;
1879
1880 unlock:
1881         mutex_unlock(&opp_table_lock);
1882         kfree(new_opp);
1883         return r;
1884 }
1885
1886 /*
1887  * dev_pm_opp_adjust_voltage() - helper to change the voltage of an OPP
1888  * @dev:                device for which we do this operation
1889  * @freq:               OPP frequency to adjust voltage of
1890  * @u_volt:             new OPP voltage
1891  *
1892  * Change the voltage of an OPP with an RCU operation.
1893  *
1894  * Return: -EINVAL for bad pointers, -ENOMEM if no memory available for the
1895  * copy operation, returns 0 if no modifcation was done OR modification was
1896  * successful.
1897  *
1898  * Locking: The internal device_opp and opp structures are RCU protected.
1899  * Hence this function internally uses RCU updater strategy with mutex locks to
1900  * keep the integrity of the internal data structures. Callers should ensure
1901  * that this function is *NOT* called under RCU protection or in contexts where
1902  * mutex locking or synchronize_rcu() blocking calls cannot be used.
1903  */
1904 int dev_pm_opp_adjust_voltage(struct device *dev, unsigned long freq,
1905                               unsigned long u_volt)
1906 {
1907         struct opp_table *opp_table;
1908         struct dev_pm_opp *new_opp, *tmp_opp, *opp = ERR_PTR(-ENODEV);
1909         int r = 0;
1910
1911         /* keep the node allocated */
1912         new_opp = kmalloc(sizeof(*new_opp), GFP_KERNEL);
1913         if (!new_opp)
1914                 return -ENOMEM;
1915
1916         mutex_lock(&opp_table_lock);
1917
1918         /* Find the opp_table */
1919         opp_table = _find_opp_table(dev);
1920         if (IS_ERR(opp_table)) {
1921                 r = PTR_ERR(opp_table);
1922                 dev_warn(dev, "%s: Device OPP not found (%d)\n", __func__, r);
1923                 goto unlock;
1924         }
1925
1926         /* Do we have the frequency? */
1927         list_for_each_entry(tmp_opp, &opp_table->opp_list, node) {
1928                 if (tmp_opp->rate == freq) {
1929                         opp = tmp_opp;
1930                         break;
1931                 }
1932         }
1933         if (IS_ERR(opp)) {
1934                 r = PTR_ERR(opp);
1935                 goto unlock;
1936         }
1937
1938         /* Is update really needed? */
1939         if (opp->u_volt == u_volt)
1940                 goto unlock;
1941         /* copy the old data over */
1942         *new_opp = *opp;
1943
1944         /* plug in new node */
1945         new_opp->u_volt = u_volt;
1946
1947         if (new_opp->u_volt_min > u_volt)
1948                 new_opp->u_volt_min = u_volt;
1949         if (new_opp->u_volt_max < u_volt)
1950                 new_opp->u_volt_max = u_volt;
1951
1952         _opp_remove(opp_table, opp, false);
1953         r = _opp_add(dev, new_opp, opp_table);
1954         if (r) {
1955                 dev_err(dev, "Failed to add new_opp (u_volt=%lu)\n", u_volt);
1956                 _opp_add(dev, opp, opp_table);
1957                 goto unlock;
1958         }
1959
1960         mutex_unlock(&opp_table_lock);
1961
1962         /* Notify the change of the OPP */
1963         srcu_notifier_call_chain(&opp_table->srcu_head,
1964                                  OPP_EVENT_ADJUST_VOLTAGE, new_opp);
1965
1966         return 0;
1967
1968 unlock:
1969         mutex_unlock(&opp_table_lock);
1970         kfree(new_opp);
1971         return r;
1972 }
1973
1974 /**
1975  * dev_pm_opp_enable() - Enable a specific OPP
1976  * @dev:        device for which we do this operation
1977  * @freq:       OPP frequency to enable
1978  *
1979  * Enables a provided opp. If the operation is valid, this returns 0, else the
1980  * corresponding error value. It is meant to be used for users an OPP available
1981  * after being temporarily made unavailable with dev_pm_opp_disable.
1982  *
1983  * Locking: The internal opp_table and opp structures are RCU protected.
1984  * Hence this function indirectly uses RCU and mutex locks to keep the
1985  * integrity of the internal data structures. Callers should ensure that
1986  * this function is *NOT* called under RCU protection or in contexts where
1987  * mutex locking or synchronize_rcu() blocking calls cannot be used.
1988  *
1989  * Return: -EINVAL for bad pointers, -ENOMEM if no memory available for the
1990  * copy operation, returns 0 if no modification was done OR modification was
1991  * successful.
1992  */
1993 int dev_pm_opp_enable(struct device *dev, unsigned long freq)
1994 {
1995         return _opp_set_availability(dev, freq, true);
1996 }
1997 EXPORT_SYMBOL_GPL(dev_pm_opp_enable);
1998
1999 /**
2000  * dev_pm_opp_disable() - Disable a specific OPP
2001  * @dev:        device for which we do this operation
2002  * @freq:       OPP frequency to disable
2003  *
2004  * Disables a provided opp. If the operation is valid, this returns
2005  * 0, else the corresponding error value. It is meant to be a temporary
2006  * control by users to make this OPP not available until the circumstances are
2007  * right to make it available again (with a call to dev_pm_opp_enable).
2008  *
2009  * Locking: The internal opp_table and opp structures are RCU protected.
2010  * Hence this function indirectly uses RCU and mutex locks to keep the
2011  * integrity of the internal data structures. Callers should ensure that
2012  * this function is *NOT* called under RCU protection or in contexts where
2013  * mutex locking or synchronize_rcu() blocking calls cannot be used.
2014  *
2015  * Return: -EINVAL for bad pointers, -ENOMEM if no memory available for the
2016  * copy operation, returns 0 if no modification was done OR modification was
2017  * successful.
2018  */
2019 int dev_pm_opp_disable(struct device *dev, unsigned long freq)
2020 {
2021         return _opp_set_availability(dev, freq, false);
2022 }
2023 EXPORT_SYMBOL_GPL(dev_pm_opp_disable);
2024
2025 /**
2026  * dev_pm_opp_get_notifier() - find notifier_head of the device with opp
2027  * @dev:        device pointer used to lookup OPP table.
2028  *
2029  * Return: pointer to  notifier head if found, otherwise -ENODEV or
2030  * -EINVAL based on type of error casted as pointer. value must be checked
2031  *  with IS_ERR to determine valid pointer or error result.
2032  *
2033  * Locking: This function must be called under rcu_read_lock(). opp_table is a
2034  * RCU protected pointer. The reason for the same is that the opp pointer which
2035  * is returned will remain valid for use with opp_get_{voltage, freq} only while
2036  * under the locked area. The pointer returned must be used prior to unlocking
2037  * with rcu_read_unlock() to maintain the integrity of the pointer.
2038  */
2039 struct srcu_notifier_head *dev_pm_opp_get_notifier(struct device *dev)
2040 {
2041         struct opp_table *opp_table = _find_opp_table(dev);
2042
2043         if (IS_ERR(opp_table))
2044                 return ERR_CAST(opp_table); /* matching type */
2045
2046         return &opp_table->srcu_head;
2047 }
2048 EXPORT_SYMBOL_GPL(dev_pm_opp_get_notifier);
2049
2050 #ifdef CONFIG_OF
2051 /**
2052  * dev_pm_opp_of_remove_table() - Free OPP table entries created from static DT
2053  *                                entries
2054  * @dev:        device pointer used to lookup OPP table.
2055  *
2056  * Free OPPs created using static entries present in DT.
2057  *
2058  * Locking: The internal opp_table and opp structures are RCU protected.
2059  * Hence this function indirectly uses RCU updater strategy with mutex locks
2060  * to keep the integrity of the internal data structures. Callers should ensure
2061  * that this function is *NOT* called under RCU protection or in contexts where
2062  * mutex cannot be locked.
2063  */
2064 void dev_pm_opp_of_remove_table(struct device *dev)
2065 {
2066         struct opp_table *opp_table;
2067         struct dev_pm_opp *opp, *tmp;
2068
2069         /* Hold our table modification lock here */
2070         mutex_lock(&opp_table_lock);
2071
2072         /* Check for existing table for 'dev' */
2073         opp_table = _find_opp_table(dev);
2074         if (IS_ERR(opp_table)) {
2075                 int error = PTR_ERR(opp_table);
2076
2077                 if (error != -ENODEV)
2078                         WARN(1, "%s: opp_table: %d\n",
2079                              IS_ERR_OR_NULL(dev) ?
2080                                         "Invalid device" : dev_name(dev),
2081                              error);
2082                 goto unlock;
2083         }
2084
2085         /* Find if opp_table manages a single device */
2086         if (list_is_singular(&opp_table->dev_list)) {
2087                 /* Free static OPPs */
2088                 list_for_each_entry_safe(opp, tmp, &opp_table->opp_list, node) {
2089                         if (!opp->dynamic)
2090                                 _opp_remove(opp_table, opp, true);
2091                 }
2092         } else {
2093                 _remove_opp_dev(_find_opp_dev(dev, opp_table), opp_table);
2094         }
2095
2096 unlock:
2097         mutex_unlock(&opp_table_lock);
2098 }
2099 EXPORT_SYMBOL_GPL(dev_pm_opp_of_remove_table);
2100
2101 /* Returns opp descriptor node for a device, caller must do of_node_put() */
2102 struct device_node *_of_get_opp_desc_node(struct device *dev)
2103 {
2104         /*
2105          * TODO: Support for multiple OPP tables.
2106          *
2107          * There should be only ONE phandle present in "operating-points-v2"
2108          * property.
2109          */
2110
2111         return of_parse_phandle(dev->of_node, "operating-points-v2", 0);
2112 }
2113
2114 /* Initializes OPP tables based on new bindings */
2115 static int _of_add_opp_table_v2(struct device *dev, struct device_node *opp_np)
2116 {
2117         struct device_node *np;
2118         struct opp_table *opp_table;
2119         int ret = 0, count = 0;
2120
2121         mutex_lock(&opp_table_lock);
2122
2123         opp_table = _managed_opp(opp_np);
2124         if (opp_table) {
2125                 /* OPPs are already managed */
2126                 if (!_add_opp_dev(dev, opp_table))
2127                         ret = -ENOMEM;
2128                 mutex_unlock(&opp_table_lock);
2129                 return ret;
2130         }
2131         mutex_unlock(&opp_table_lock);
2132
2133         /* We have opp-table node now, iterate over it and add OPPs */
2134         for_each_available_child_of_node(opp_np, np) {
2135                 count++;
2136
2137                 ret = _opp_add_static_v2(dev, np);
2138                 if (ret) {
2139                         dev_err(dev, "%s: Failed to add OPP, %d\n", __func__,
2140                                 ret);
2141                         goto free_table;
2142                 }
2143         }
2144
2145         /* There should be one of more OPP defined */
2146         if (WARN_ON(!count))
2147                 return -ENOENT;
2148
2149         mutex_lock(&opp_table_lock);
2150
2151         opp_table = _find_opp_table(dev);
2152         if (WARN_ON(IS_ERR(opp_table))) {
2153                 ret = PTR_ERR(opp_table);
2154                 mutex_unlock(&opp_table_lock);
2155                 goto free_table;
2156         }
2157
2158         opp_table->np = opp_np;
2159         opp_table->shared_opp = of_property_read_bool(opp_np, "opp-shared");
2160
2161         mutex_unlock(&opp_table_lock);
2162
2163         return 0;
2164
2165 free_table:
2166         dev_pm_opp_of_remove_table(dev);
2167
2168         return ret;
2169 }
2170
2171 /* Initializes OPP tables based on old-deprecated bindings */
2172 static int _of_add_opp_table_v1(struct device *dev)
2173 {
2174         const struct property *prop;
2175         const __be32 *val;
2176         int nr;
2177
2178         prop = of_find_property(dev->of_node, "operating-points", NULL);
2179         if (!prop)
2180                 return -ENODEV;
2181         if (!prop->value)
2182                 return -ENODATA;
2183
2184         /*
2185          * Each OPP is a set of tuples consisting of frequency and
2186          * voltage like <freq-kHz vol-uV>.
2187          */
2188         nr = prop->length / sizeof(u32);
2189         if (nr % 2) {
2190                 dev_err(dev, "%s: Invalid OPP table\n", __func__);
2191                 return -EINVAL;
2192         }
2193
2194         val = prop->value;
2195         while (nr) {
2196                 unsigned long freq = be32_to_cpup(val++) * 1000;
2197                 unsigned long volt = be32_to_cpup(val++);
2198
2199                 if (_opp_add_v1(dev, freq, volt, false))
2200                         dev_warn(dev, "%s: Failed to add OPP %ld\n",
2201                                  __func__, freq);
2202                 nr -= 2;
2203         }
2204
2205         return 0;
2206 }
2207
2208 /**
2209  * dev_pm_opp_of_add_table() - Initialize opp table from device tree
2210  * @dev:        device pointer used to lookup OPP table.
2211  *
2212  * Register the initial OPP table with the OPP library for given device.
2213  *
2214  * Locking: The internal opp_table and opp structures are RCU protected.
2215  * Hence this function indirectly uses RCU updater strategy with mutex locks
2216  * to keep the integrity of the internal data structures. Callers should ensure
2217  * that this function is *NOT* called under RCU protection or in contexts where
2218  * mutex cannot be locked.
2219  *
2220  * Return:
2221  * 0            On success OR
2222  *              Duplicate OPPs (both freq and volt are same) and opp->available
2223  * -EEXIST      Freq are same and volt are different OR
2224  *              Duplicate OPPs (both freq and volt are same) and !opp->available
2225  * -ENOMEM      Memory allocation failure
2226  * -ENODEV      when 'operating-points' property is not found or is invalid data
2227  *              in device node.
2228  * -ENODATA     when empty 'operating-points' property is found
2229  * -EINVAL      when invalid entries are found in opp-v2 table
2230  */
2231 int dev_pm_opp_of_add_table(struct device *dev)
2232 {
2233         struct device_node *opp_np;
2234         int ret;
2235
2236         /*
2237          * OPPs have two version of bindings now. The older one is deprecated,
2238          * try for the new binding first.
2239          */
2240         opp_np = _of_get_opp_desc_node(dev);
2241         if (!opp_np) {
2242                 /*
2243                  * Try old-deprecated bindings for backward compatibility with
2244                  * older dtbs.
2245                  */
2246                 return _of_add_opp_table_v1(dev);
2247         }
2248
2249         ret = _of_add_opp_table_v2(dev, opp_np);
2250         of_node_put(opp_np);
2251
2252         return ret;
2253 }
2254 EXPORT_SYMBOL_GPL(dev_pm_opp_of_add_table);
2255 #endif