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