6b7f0066942dbe6b7c760241d9c04503e68818e7
[linux-2.6-microblaze.git] / drivers / opp / of.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Generic OPP OF helpers
4  *
5  * Copyright (C) 2009-2010 Texas Instruments Incorporated.
6  *      Nishanth Menon
7  *      Romit Dasgupta
8  *      Kevin Hilman
9  */
10
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12
13 #include <linux/cpu.h>
14 #include <linux/errno.h>
15 #include <linux/device.h>
16 #include <linux/of_device.h>
17 #include <linux/pm_domain.h>
18 #include <linux/slab.h>
19 #include <linux/export.h>
20 #include <linux/energy_model.h>
21
22 #include "opp.h"
23
24 /*
25  * Returns opp descriptor node for a device node, caller must
26  * do of_node_put().
27  */
28 static struct device_node *_opp_of_get_opp_desc_node(struct device_node *np,
29                                                      int index)
30 {
31         /* "operating-points-v2" can be an array for power domain providers */
32         return of_parse_phandle(np, "operating-points-v2", index);
33 }
34
35 /* Returns opp descriptor node for a device, caller must do of_node_put() */
36 struct device_node *dev_pm_opp_of_get_opp_desc_node(struct device *dev)
37 {
38         return _opp_of_get_opp_desc_node(dev->of_node, 0);
39 }
40 EXPORT_SYMBOL_GPL(dev_pm_opp_of_get_opp_desc_node);
41
42 struct opp_table *_managed_opp(struct device *dev, int index)
43 {
44         struct opp_table *opp_table, *managed_table = NULL;
45         struct device_node *np;
46
47         np = _opp_of_get_opp_desc_node(dev->of_node, index);
48         if (!np)
49                 return NULL;
50
51         list_for_each_entry(opp_table, &opp_tables, node) {
52                 if (opp_table->np == np) {
53                         /*
54                          * Multiple devices can point to the same OPP table and
55                          * so will have same node-pointer, np.
56                          *
57                          * But the OPPs will be considered as shared only if the
58                          * OPP table contains a "opp-shared" property.
59                          */
60                         if (opp_table->shared_opp == OPP_TABLE_ACCESS_SHARED) {
61                                 _get_opp_table_kref(opp_table);
62                                 managed_table = opp_table;
63                         }
64
65                         break;
66                 }
67         }
68
69         of_node_put(np);
70
71         return managed_table;
72 }
73
74 /* The caller must call dev_pm_opp_put() after the OPP is used */
75 static struct dev_pm_opp *_find_opp_of_np(struct opp_table *opp_table,
76                                           struct device_node *opp_np)
77 {
78         struct dev_pm_opp *opp;
79
80         mutex_lock(&opp_table->lock);
81
82         list_for_each_entry(opp, &opp_table->opp_list, node) {
83                 if (opp->np == opp_np) {
84                         dev_pm_opp_get(opp);
85                         mutex_unlock(&opp_table->lock);
86                         return opp;
87                 }
88         }
89
90         mutex_unlock(&opp_table->lock);
91
92         return NULL;
93 }
94
95 static struct device_node *of_parse_required_opp(struct device_node *np,
96                                                  int index)
97 {
98         struct device_node *required_np;
99
100         required_np = of_parse_phandle(np, "required-opps", index);
101         if (unlikely(!required_np)) {
102                 pr_err("%s: Unable to parse required-opps: %pOF, index: %d\n",
103                        __func__, np, index);
104         }
105
106         return required_np;
107 }
108
109 /* The caller must call dev_pm_opp_put_opp_table() after the table is used */
110 static struct opp_table *_find_table_of_opp_np(struct device_node *opp_np)
111 {
112         struct opp_table *opp_table;
113         struct device_node *opp_table_np;
114
115         opp_table_np = of_get_parent(opp_np);
116         if (!opp_table_np)
117                 goto err;
118
119         /* It is safe to put the node now as all we need now is its address */
120         of_node_put(opp_table_np);
121
122         mutex_lock(&opp_table_lock);
123         list_for_each_entry(opp_table, &opp_tables, node) {
124                 if (opp_table_np == opp_table->np) {
125                         _get_opp_table_kref(opp_table);
126                         mutex_unlock(&opp_table_lock);
127                         return opp_table;
128                 }
129         }
130         mutex_unlock(&opp_table_lock);
131
132 err:
133         return ERR_PTR(-ENODEV);
134 }
135
136 /* Free resources previously acquired by _opp_table_alloc_required_tables() */
137 static void _opp_table_free_required_tables(struct opp_table *opp_table)
138 {
139         struct opp_table **required_opp_tables = opp_table->required_opp_tables;
140         int i;
141
142         if (!required_opp_tables)
143                 return;
144
145         for (i = 0; i < opp_table->required_opp_count; i++) {
146                 if (IS_ERR_OR_NULL(required_opp_tables[i]))
147                         break;
148
149                 dev_pm_opp_put_opp_table(required_opp_tables[i]);
150         }
151
152         kfree(required_opp_tables);
153
154         opp_table->required_opp_count = 0;
155         opp_table->required_opp_tables = NULL;
156 }
157
158 /*
159  * Populate all devices and opp tables which are part of "required-opps" list.
160  * Checking only the first OPP node should be enough.
161  */
162 static void _opp_table_alloc_required_tables(struct opp_table *opp_table,
163                                              struct device *dev,
164                                              struct device_node *opp_np)
165 {
166         struct opp_table **required_opp_tables;
167         struct device_node *required_np, *np;
168         int count, i;
169
170         /* Traversing the first OPP node is all we need */
171         np = of_get_next_available_child(opp_np, NULL);
172         if (!np) {
173                 dev_err(dev, "Empty OPP table\n");
174                 return;
175         }
176
177         count = of_count_phandle_with_args(np, "required-opps", NULL);
178         if (!count)
179                 goto put_np;
180
181         required_opp_tables = kcalloc(count, sizeof(*required_opp_tables),
182                                       GFP_KERNEL);
183         if (!required_opp_tables)
184                 goto put_np;
185
186         opp_table->required_opp_tables = required_opp_tables;
187         opp_table->required_opp_count = count;
188
189         for (i = 0; i < count; i++) {
190                 required_np = of_parse_required_opp(np, i);
191                 if (!required_np)
192                         goto free_required_tables;
193
194                 required_opp_tables[i] = _find_table_of_opp_np(required_np);
195                 of_node_put(required_np);
196
197                 if (IS_ERR(required_opp_tables[i]))
198                         goto free_required_tables;
199
200                 /*
201                  * We only support genpd's OPPs in the "required-opps" for now,
202                  * as we don't know how much about other cases. Error out if the
203                  * required OPP doesn't belong to a genpd.
204                  */
205                 if (!required_opp_tables[i]->is_genpd) {
206                         dev_err(dev, "required-opp doesn't belong to genpd: %pOF\n",
207                                 required_np);
208                         goto free_required_tables;
209                 }
210         }
211
212         goto put_np;
213
214 free_required_tables:
215         _opp_table_free_required_tables(opp_table);
216 put_np:
217         of_node_put(np);
218 }
219
220 void _of_init_opp_table(struct opp_table *opp_table, struct device *dev,
221                         int index)
222 {
223         struct device_node *np, *opp_np;
224         u32 val;
225
226         /*
227          * Only required for backward compatibility with v1 bindings, but isn't
228          * harmful for other cases. And so we do it unconditionally.
229          */
230         np = of_node_get(dev->of_node);
231         if (!np)
232                 return;
233
234         if (!of_property_read_u32(np, "clock-latency", &val))
235                 opp_table->clock_latency_ns_max = val;
236         of_property_read_u32(np, "voltage-tolerance",
237                              &opp_table->voltage_tolerance_v1);
238
239         if (of_find_property(np, "#power-domain-cells", NULL))
240                 opp_table->is_genpd = true;
241
242         /* Get OPP table node */
243         opp_np = _opp_of_get_opp_desc_node(np, index);
244         of_node_put(np);
245
246         if (!opp_np)
247                 return;
248
249         if (of_property_read_bool(opp_np, "opp-shared"))
250                 opp_table->shared_opp = OPP_TABLE_ACCESS_SHARED;
251         else
252                 opp_table->shared_opp = OPP_TABLE_ACCESS_EXCLUSIVE;
253
254         opp_table->np = opp_np;
255
256         _opp_table_alloc_required_tables(opp_table, dev, opp_np);
257         of_node_put(opp_np);
258 }
259
260 void _of_clear_opp_table(struct opp_table *opp_table)
261 {
262         _opp_table_free_required_tables(opp_table);
263 }
264
265 /*
266  * Release all resources previously acquired with a call to
267  * _of_opp_alloc_required_opps().
268  */
269 void _of_opp_free_required_opps(struct opp_table *opp_table,
270                                 struct dev_pm_opp *opp)
271 {
272         struct dev_pm_opp **required_opps = opp->required_opps;
273         int i;
274
275         if (!required_opps)
276                 return;
277
278         for (i = 0; i < opp_table->required_opp_count; i++) {
279                 if (!required_opps[i])
280                         break;
281
282                 /* Put the reference back */
283                 dev_pm_opp_put(required_opps[i]);
284         }
285
286         kfree(required_opps);
287         opp->required_opps = NULL;
288 }
289
290 /* Populate all required OPPs which are part of "required-opps" list */
291 static int _of_opp_alloc_required_opps(struct opp_table *opp_table,
292                                        struct dev_pm_opp *opp)
293 {
294         struct dev_pm_opp **required_opps;
295         struct opp_table *required_table;
296         struct device_node *np;
297         int i, ret, count = opp_table->required_opp_count;
298
299         if (!count)
300                 return 0;
301
302         required_opps = kcalloc(count, sizeof(*required_opps), GFP_KERNEL);
303         if (!required_opps)
304                 return -ENOMEM;
305
306         opp->required_opps = required_opps;
307
308         for (i = 0; i < count; i++) {
309                 required_table = opp_table->required_opp_tables[i];
310
311                 np = of_parse_required_opp(opp->np, i);
312                 if (unlikely(!np)) {
313                         ret = -ENODEV;
314                         goto free_required_opps;
315                 }
316
317                 required_opps[i] = _find_opp_of_np(required_table, np);
318                 of_node_put(np);
319
320                 if (!required_opps[i]) {
321                         pr_err("%s: Unable to find required OPP node: %pOF (%d)\n",
322                                __func__, opp->np, i);
323                         ret = -ENODEV;
324                         goto free_required_opps;
325                 }
326         }
327
328         return 0;
329
330 free_required_opps:
331         _of_opp_free_required_opps(opp_table, opp);
332
333         return ret;
334 }
335
336 static int _bandwidth_supported(struct device *dev, struct opp_table *opp_table)
337 {
338         struct device_node *np, *opp_np;
339         struct property *prop;
340
341         if (!opp_table) {
342                 np = of_node_get(dev->of_node);
343                 if (!np)
344                         return -ENODEV;
345
346                 opp_np = _opp_of_get_opp_desc_node(np, 0);
347                 of_node_put(np);
348         } else {
349                 opp_np = of_node_get(opp_table->np);
350         }
351
352         /* Lets not fail in case we are parsing opp-v1 bindings */
353         if (!opp_np)
354                 return 0;
355
356         /* Checking only first OPP is sufficient */
357         np = of_get_next_available_child(opp_np, NULL);
358         if (!np) {
359                 dev_err(dev, "OPP table empty\n");
360                 return -EINVAL;
361         }
362         of_node_put(opp_np);
363
364         prop = of_find_property(np, "opp-peak-kBps", NULL);
365         of_node_put(np);
366
367         if (!prop || !prop->length)
368                 return 0;
369
370         return 1;
371 }
372
373 int dev_pm_opp_of_find_icc_paths(struct device *dev,
374                                  struct opp_table *opp_table)
375 {
376         struct device_node *np;
377         int ret, i, count, num_paths;
378         struct icc_path **paths;
379
380         ret = _bandwidth_supported(dev, opp_table);
381         if (ret <= 0)
382                 return ret;
383
384         ret = 0;
385
386         np = of_node_get(dev->of_node);
387         if (!np)
388                 return 0;
389
390         count = of_count_phandle_with_args(np, "interconnects",
391                                            "#interconnect-cells");
392         of_node_put(np);
393         if (count < 0)
394                 return 0;
395
396         /* two phandles when #interconnect-cells = <1> */
397         if (count % 2) {
398                 dev_err(dev, "%s: Invalid interconnects values\n", __func__);
399                 return -EINVAL;
400         }
401
402         num_paths = count / 2;
403         paths = kcalloc(num_paths, sizeof(*paths), GFP_KERNEL);
404         if (!paths)
405                 return -ENOMEM;
406
407         for (i = 0; i < num_paths; i++) {
408                 paths[i] = of_icc_get_by_index(dev, i);
409                 if (IS_ERR(paths[i])) {
410                         ret = PTR_ERR(paths[i]);
411                         if (ret != -EPROBE_DEFER) {
412                                 dev_err(dev, "%s: Unable to get path%d: %d\n",
413                                         __func__, i, ret);
414                         }
415                         goto err;
416                 }
417         }
418
419         if (opp_table) {
420                 opp_table->paths = paths;
421                 opp_table->path_count = num_paths;
422                 return 0;
423         }
424
425 err:
426         while (i--)
427                 icc_put(paths[i]);
428
429         kfree(paths);
430
431         return ret;
432 }
433 EXPORT_SYMBOL_GPL(dev_pm_opp_of_find_icc_paths);
434
435 static bool _opp_is_supported(struct device *dev, struct opp_table *opp_table,
436                               struct device_node *np)
437 {
438         unsigned int levels = opp_table->supported_hw_count;
439         int count, versions, ret, i, j;
440         u32 val;
441
442         if (!opp_table->supported_hw) {
443                 /*
444                  * In the case that no supported_hw has been set by the
445                  * platform but there is an opp-supported-hw value set for
446                  * an OPP then the OPP should not be enabled as there is
447                  * no way to see if the hardware supports it.
448                  */
449                 if (of_find_property(np, "opp-supported-hw", NULL))
450                         return false;
451                 else
452                         return true;
453         }
454
455         count = of_property_count_u32_elems(np, "opp-supported-hw");
456         if (count <= 0 || count % levels) {
457                 dev_err(dev, "%s: Invalid opp-supported-hw property (%d)\n",
458                         __func__, count);
459                 return false;
460         }
461
462         versions = count / levels;
463
464         /* All levels in at least one of the versions should match */
465         for (i = 0; i < versions; i++) {
466                 bool supported = true;
467
468                 for (j = 0; j < levels; j++) {
469                         ret = of_property_read_u32_index(np, "opp-supported-hw",
470                                                          i * levels + j, &val);
471                         if (ret) {
472                                 dev_warn(dev, "%s: failed to read opp-supported-hw property at index %d: %d\n",
473                                          __func__, i * levels + j, ret);
474                                 return false;
475                         }
476
477                         /* Check if the level is supported */
478                         if (!(val & opp_table->supported_hw[j])) {
479                                 supported = false;
480                                 break;
481                         }
482                 }
483
484                 if (supported)
485                         return true;
486         }
487
488         return false;
489 }
490
491 static int opp_parse_supplies(struct dev_pm_opp *opp, struct device *dev,
492                               struct opp_table *opp_table)
493 {
494         u32 *microvolt, *microamp = NULL;
495         int supplies = opp_table->regulator_count, vcount, icount, ret, i, j;
496         struct property *prop = NULL;
497         char name[NAME_MAX];
498
499         /* Search for "opp-microvolt-<name>" */
500         if (opp_table->prop_name) {
501                 snprintf(name, sizeof(name), "opp-microvolt-%s",
502                          opp_table->prop_name);
503                 prop = of_find_property(opp->np, name, NULL);
504         }
505
506         if (!prop) {
507                 /* Search for "opp-microvolt" */
508                 sprintf(name, "opp-microvolt");
509                 prop = of_find_property(opp->np, name, NULL);
510
511                 /* Missing property isn't a problem, but an invalid entry is */
512                 if (!prop) {
513                         if (unlikely(supplies == -1)) {
514                                 /* Initialize regulator_count */
515                                 opp_table->regulator_count = 0;
516                                 return 0;
517                         }
518
519                         if (!supplies)
520                                 return 0;
521
522                         dev_err(dev, "%s: opp-microvolt missing although OPP managing regulators\n",
523                                 __func__);
524                         return -EINVAL;
525                 }
526         }
527
528         if (unlikely(supplies == -1)) {
529                 /* Initialize regulator_count */
530                 supplies = opp_table->regulator_count = 1;
531         } else if (unlikely(!supplies)) {
532                 dev_err(dev, "%s: opp-microvolt wasn't expected\n", __func__);
533                 return -EINVAL;
534         }
535
536         vcount = of_property_count_u32_elems(opp->np, name);
537         if (vcount < 0) {
538                 dev_err(dev, "%s: Invalid %s property (%d)\n",
539                         __func__, name, vcount);
540                 return vcount;
541         }
542
543         /* There can be one or three elements per supply */
544         if (vcount != supplies && vcount != supplies * 3) {
545                 dev_err(dev, "%s: Invalid number of elements in %s property (%d) with supplies (%d)\n",
546                         __func__, name, vcount, supplies);
547                 return -EINVAL;
548         }
549
550         microvolt = kmalloc_array(vcount, sizeof(*microvolt), GFP_KERNEL);
551         if (!microvolt)
552                 return -ENOMEM;
553
554         ret = of_property_read_u32_array(opp->np, name, microvolt, vcount);
555         if (ret) {
556                 dev_err(dev, "%s: error parsing %s: %d\n", __func__, name, ret);
557                 ret = -EINVAL;
558                 goto free_microvolt;
559         }
560
561         /* Search for "opp-microamp-<name>" */
562         prop = NULL;
563         if (opp_table->prop_name) {
564                 snprintf(name, sizeof(name), "opp-microamp-%s",
565                          opp_table->prop_name);
566                 prop = of_find_property(opp->np, name, NULL);
567         }
568
569         if (!prop) {
570                 /* Search for "opp-microamp" */
571                 sprintf(name, "opp-microamp");
572                 prop = of_find_property(opp->np, name, NULL);
573         }
574
575         if (prop) {
576                 icount = of_property_count_u32_elems(opp->np, name);
577                 if (icount < 0) {
578                         dev_err(dev, "%s: Invalid %s property (%d)\n", __func__,
579                                 name, icount);
580                         ret = icount;
581                         goto free_microvolt;
582                 }
583
584                 if (icount != supplies) {
585                         dev_err(dev, "%s: Invalid number of elements in %s property (%d) with supplies (%d)\n",
586                                 __func__, name, icount, supplies);
587                         ret = -EINVAL;
588                         goto free_microvolt;
589                 }
590
591                 microamp = kmalloc_array(icount, sizeof(*microamp), GFP_KERNEL);
592                 if (!microamp) {
593                         ret = -EINVAL;
594                         goto free_microvolt;
595                 }
596
597                 ret = of_property_read_u32_array(opp->np, name, microamp,
598                                                  icount);
599                 if (ret) {
600                         dev_err(dev, "%s: error parsing %s: %d\n", __func__,
601                                 name, ret);
602                         ret = -EINVAL;
603                         goto free_microamp;
604                 }
605         }
606
607         for (i = 0, j = 0; i < supplies; i++) {
608                 opp->supplies[i].u_volt = microvolt[j++];
609
610                 if (vcount == supplies) {
611                         opp->supplies[i].u_volt_min = opp->supplies[i].u_volt;
612                         opp->supplies[i].u_volt_max = opp->supplies[i].u_volt;
613                 } else {
614                         opp->supplies[i].u_volt_min = microvolt[j++];
615                         opp->supplies[i].u_volt_max = microvolt[j++];
616                 }
617
618                 if (microamp)
619                         opp->supplies[i].u_amp = microamp[i];
620         }
621
622 free_microamp:
623         kfree(microamp);
624 free_microvolt:
625         kfree(microvolt);
626
627         return ret;
628 }
629
630 /**
631  * dev_pm_opp_of_remove_table() - Free OPP table entries created from static DT
632  *                                entries
633  * @dev:        device pointer used to lookup OPP table.
634  *
635  * Free OPPs created using static entries present in DT.
636  */
637 void dev_pm_opp_of_remove_table(struct device *dev)
638 {
639         dev_pm_opp_remove_table(dev);
640 }
641 EXPORT_SYMBOL_GPL(dev_pm_opp_of_remove_table);
642
643 static int _read_bw(struct dev_pm_opp *new_opp, struct opp_table *table,
644                     struct device_node *np, bool peak)
645 {
646         const char *name = peak ? "opp-peak-kBps" : "opp-avg-kBps";
647         struct property *prop;
648         int i, count, ret;
649         u32 *bw;
650
651         prop = of_find_property(np, name, NULL);
652         if (!prop)
653                 return -ENODEV;
654
655         count = prop->length / sizeof(u32);
656         if (table->path_count != count) {
657                 pr_err("%s: Mismatch between %s and paths (%d %d)\n",
658                                 __func__, name, count, table->path_count);
659                 return -EINVAL;
660         }
661
662         bw = kmalloc_array(count, sizeof(*bw), GFP_KERNEL);
663         if (!bw)
664                 return -ENOMEM;
665
666         ret = of_property_read_u32_array(np, name, bw, count);
667         if (ret) {
668                 pr_err("%s: Error parsing %s: %d\n", __func__, name, ret);
669                 goto out;
670         }
671
672         for (i = 0; i < count; i++) {
673                 if (peak)
674                         new_opp->bandwidth[i].peak = kBps_to_icc(bw[i]);
675                 else
676                         new_opp->bandwidth[i].avg = kBps_to_icc(bw[i]);
677         }
678
679 out:
680         kfree(bw);
681         return ret;
682 }
683
684 static int _read_opp_key(struct dev_pm_opp *new_opp, struct opp_table *table,
685                          struct device_node *np, bool *rate_not_available)
686 {
687         bool found = false;
688         u64 rate;
689         int ret;
690
691         ret = of_property_read_u64(np, "opp-hz", &rate);
692         if (!ret) {
693                 /*
694                  * Rate is defined as an unsigned long in clk API, and so
695                  * casting explicitly to its type. Must be fixed once rate is 64
696                  * bit guaranteed in clk API.
697                  */
698                 new_opp->rate = (unsigned long)rate;
699                 found = true;
700         }
701         *rate_not_available = !!ret;
702
703         /*
704          * Bandwidth consists of peak and average (optional) values:
705          * opp-peak-kBps = <path1_value path2_value>;
706          * opp-avg-kBps = <path1_value path2_value>;
707          */
708         ret = _read_bw(new_opp, table, np, true);
709         if (!ret) {
710                 found = true;
711                 ret = _read_bw(new_opp, table, np, false);
712         }
713
714         /* The properties were found but we failed to parse them */
715         if (ret && ret != -ENODEV)
716                 return ret;
717
718         if (!of_property_read_u32(np, "opp-level", &new_opp->level))
719                 found = true;
720
721         if (found)
722                 return 0;
723
724         return ret;
725 }
726
727 /**
728  * _opp_add_static_v2() - Allocate static OPPs (As per 'v2' DT bindings)
729  * @opp_table:  OPP table
730  * @dev:        device for which we do this operation
731  * @np:         device node
732  *
733  * This function adds an opp definition to the opp table and returns status. The
734  * opp can be controlled using dev_pm_opp_enable/disable functions and may be
735  * removed by dev_pm_opp_remove.
736  *
737  * Return:
738  * Valid OPP pointer:
739  *              On success
740  * NULL:
741  *              Duplicate OPPs (both freq and volt are same) and opp->available
742  *              OR if the OPP is not supported by hardware.
743  * ERR_PTR(-EEXIST):
744  *              Freq are same and volt are different OR
745  *              Duplicate OPPs (both freq and volt are same) and !opp->available
746  * ERR_PTR(-ENOMEM):
747  *              Memory allocation failure
748  * ERR_PTR(-EINVAL):
749  *              Failed parsing the OPP node
750  */
751 static struct dev_pm_opp *_opp_add_static_v2(struct opp_table *opp_table,
752                 struct device *dev, struct device_node *np)
753 {
754         struct dev_pm_opp *new_opp;
755         u64 rate = 0;
756         u32 val;
757         int ret;
758         bool rate_not_available = false;
759
760         new_opp = _opp_allocate(opp_table);
761         if (!new_opp)
762                 return ERR_PTR(-ENOMEM);
763
764         ret = _read_opp_key(new_opp, opp_table, np, &rate_not_available);
765         if (ret < 0 && !opp_table->is_genpd) {
766                 dev_err(dev, "%s: opp key field not found\n", __func__);
767                 goto free_opp;
768         }
769
770         /* Check if the OPP supports hardware's hierarchy of versions or not */
771         if (!_opp_is_supported(dev, opp_table, np)) {
772                 dev_dbg(dev, "OPP not supported by hardware: %llu\n", rate);
773                 goto free_opp;
774         }
775
776         new_opp->turbo = of_property_read_bool(np, "turbo-mode");
777
778         new_opp->np = np;
779         new_opp->dynamic = false;
780         new_opp->available = true;
781
782         ret = _of_opp_alloc_required_opps(opp_table, new_opp);
783         if (ret)
784                 goto free_opp;
785
786         if (!of_property_read_u32(np, "clock-latency-ns", &val))
787                 new_opp->clock_latency_ns = val;
788
789         ret = opp_parse_supplies(new_opp, dev, opp_table);
790         if (ret)
791                 goto free_required_opps;
792
793         if (opp_table->is_genpd)
794                 new_opp->pstate = pm_genpd_opp_to_performance_state(dev, new_opp);
795
796         ret = _opp_add(dev, new_opp, opp_table, rate_not_available);
797         if (ret) {
798                 /* Don't return error for duplicate OPPs */
799                 if (ret == -EBUSY)
800                         ret = 0;
801                 goto free_required_opps;
802         }
803
804         /* OPP to select on device suspend */
805         if (of_property_read_bool(np, "opp-suspend")) {
806                 if (opp_table->suspend_opp) {
807                         /* Pick the OPP with higher rate as suspend OPP */
808                         if (new_opp->rate > opp_table->suspend_opp->rate) {
809                                 opp_table->suspend_opp->suspend = false;
810                                 new_opp->suspend = true;
811                                 opp_table->suspend_opp = new_opp;
812                         }
813                 } else {
814                         new_opp->suspend = true;
815                         opp_table->suspend_opp = new_opp;
816                 }
817         }
818
819         if (new_opp->clock_latency_ns > opp_table->clock_latency_ns_max)
820                 opp_table->clock_latency_ns_max = new_opp->clock_latency_ns;
821
822         pr_debug("%s: turbo:%d rate:%lu uv:%lu uvmin:%lu uvmax:%lu latency:%lu\n",
823                  __func__, new_opp->turbo, new_opp->rate,
824                  new_opp->supplies[0].u_volt, new_opp->supplies[0].u_volt_min,
825                  new_opp->supplies[0].u_volt_max, new_opp->clock_latency_ns);
826
827         /*
828          * Notify the changes in the availability of the operable
829          * frequency/voltage list.
830          */
831         blocking_notifier_call_chain(&opp_table->head, OPP_EVENT_ADD, new_opp);
832         return new_opp;
833
834 free_required_opps:
835         _of_opp_free_required_opps(opp_table, new_opp);
836 free_opp:
837         _opp_free(new_opp);
838
839         return ERR_PTR(ret);
840 }
841
842 /* Initializes OPP tables based on new bindings */
843 static int _of_add_opp_table_v2(struct device *dev, struct opp_table *opp_table)
844 {
845         struct device_node *np;
846         int ret, count = 0;
847         struct dev_pm_opp *opp;
848
849         /* OPP table is already initialized for the device */
850         mutex_lock(&opp_table->lock);
851         if (opp_table->parsed_static_opps) {
852                 opp_table->parsed_static_opps++;
853                 mutex_unlock(&opp_table->lock);
854                 return 0;
855         }
856
857         opp_table->parsed_static_opps = 1;
858         mutex_unlock(&opp_table->lock);
859
860         /* We have opp-table node now, iterate over it and add OPPs */
861         for_each_available_child_of_node(opp_table->np, np) {
862                 opp = _opp_add_static_v2(opp_table, dev, np);
863                 if (IS_ERR(opp)) {
864                         ret = PTR_ERR(opp);
865                         dev_err(dev, "%s: Failed to add OPP, %d\n", __func__,
866                                 ret);
867                         of_node_put(np);
868                         goto remove_static_opp;
869                 } else if (opp) {
870                         count++;
871                 }
872         }
873
874         /* There should be one of more OPP defined */
875         if (WARN_ON(!count)) {
876                 ret = -ENOENT;
877                 goto remove_static_opp;
878         }
879
880         list_for_each_entry(opp, &opp_table->opp_list, node) {
881                 /* Any non-zero performance state would enable the feature */
882                 if (opp->pstate) {
883                         opp_table->genpd_performance_state = true;
884                         break;
885                 }
886         }
887
888         return 0;
889
890 remove_static_opp:
891         _opp_remove_all_static(opp_table);
892
893         return ret;
894 }
895
896 /* Initializes OPP tables based on old-deprecated bindings */
897 static int _of_add_opp_table_v1(struct device *dev, struct opp_table *opp_table)
898 {
899         const struct property *prop;
900         const __be32 *val;
901         int nr, ret = 0;
902
903         mutex_lock(&opp_table->lock);
904         if (opp_table->parsed_static_opps) {
905                 opp_table->parsed_static_opps++;
906                 mutex_unlock(&opp_table->lock);
907                 return 0;
908         }
909
910         opp_table->parsed_static_opps = 1;
911         mutex_unlock(&opp_table->lock);
912
913         prop = of_find_property(dev->of_node, "operating-points", NULL);
914         if (!prop) {
915                 ret = -ENODEV;
916                 goto remove_static_opp;
917         }
918         if (!prop->value) {
919                 ret = -ENODATA;
920                 goto remove_static_opp;
921         }
922
923         /*
924          * Each OPP is a set of tuples consisting of frequency and
925          * voltage like <freq-kHz vol-uV>.
926          */
927         nr = prop->length / sizeof(u32);
928         if (nr % 2) {
929                 dev_err(dev, "%s: Invalid OPP table\n", __func__);
930                 ret = -EINVAL;
931                 goto remove_static_opp;
932         }
933
934         val = prop->value;
935         while (nr) {
936                 unsigned long freq = be32_to_cpup(val++) * 1000;
937                 unsigned long volt = be32_to_cpup(val++);
938
939                 ret = _opp_add_v1(opp_table, dev, freq, volt, false);
940                 if (ret) {
941                         dev_err(dev, "%s: Failed to add OPP %ld (%d)\n",
942                                 __func__, freq, ret);
943                         goto remove_static_opp;
944                 }
945                 nr -= 2;
946         }
947
948         return 0;
949
950 remove_static_opp:
951         _opp_remove_all_static(opp_table);
952
953         return ret;
954 }
955
956 /**
957  * dev_pm_opp_of_add_table() - Initialize opp table from device tree
958  * @dev:        device pointer used to lookup OPP table.
959  *
960  * Register the initial OPP table with the OPP library for given device.
961  *
962  * Return:
963  * 0            On success OR
964  *              Duplicate OPPs (both freq and volt are same) and opp->available
965  * -EEXIST      Freq are same and volt are different OR
966  *              Duplicate OPPs (both freq and volt are same) and !opp->available
967  * -ENOMEM      Memory allocation failure
968  * -ENODEV      when 'operating-points' property is not found or is invalid data
969  *              in device node.
970  * -ENODATA     when empty 'operating-points' property is found
971  * -EINVAL      when invalid entries are found in opp-v2 table
972  */
973 int dev_pm_opp_of_add_table(struct device *dev)
974 {
975         struct opp_table *opp_table;
976         int ret;
977
978         opp_table = _add_opp_table_indexed(dev, 0);
979         if (IS_ERR(opp_table))
980                 return PTR_ERR(opp_table);
981
982         /*
983          * OPPs have two version of bindings now. Also try the old (v1)
984          * bindings for backward compatibility with older dtbs.
985          */
986         if (opp_table->np)
987                 ret = _of_add_opp_table_v2(dev, opp_table);
988         else
989                 ret = _of_add_opp_table_v1(dev, opp_table);
990
991         if (ret)
992                 dev_pm_opp_put_opp_table(opp_table);
993
994         return ret;
995 }
996 EXPORT_SYMBOL_GPL(dev_pm_opp_of_add_table);
997
998 /**
999  * dev_pm_opp_of_add_table_indexed() - Initialize indexed opp table from device tree
1000  * @dev:        device pointer used to lookup OPP table.
1001  * @index:      Index number.
1002  *
1003  * Register the initial OPP table with the OPP library for given device only
1004  * using the "operating-points-v2" property.
1005  *
1006  * Return:
1007  * 0            On success OR
1008  *              Duplicate OPPs (both freq and volt are same) and opp->available
1009  * -EEXIST      Freq are same and volt are different OR
1010  *              Duplicate OPPs (both freq and volt are same) and !opp->available
1011  * -ENOMEM      Memory allocation failure
1012  * -ENODEV      when 'operating-points' property is not found or is invalid data
1013  *              in device node.
1014  * -ENODATA     when empty 'operating-points' property is found
1015  * -EINVAL      when invalid entries are found in opp-v2 table
1016  */
1017 int dev_pm_opp_of_add_table_indexed(struct device *dev, int index)
1018 {
1019         struct opp_table *opp_table;
1020         int ret, count;
1021
1022         if (index) {
1023                 /*
1024                  * If only one phandle is present, then the same OPP table
1025                  * applies for all index requests.
1026                  */
1027                 count = of_count_phandle_with_args(dev->of_node,
1028                                                    "operating-points-v2", NULL);
1029                 if (count == 1)
1030                         index = 0;
1031         }
1032
1033         opp_table = _add_opp_table_indexed(dev, index);
1034         if (IS_ERR(opp_table))
1035                 return PTR_ERR(opp_table);
1036
1037         ret = _of_add_opp_table_v2(dev, opp_table);
1038         if (ret)
1039                 dev_pm_opp_put_opp_table(opp_table);
1040
1041         return ret;
1042 }
1043 EXPORT_SYMBOL_GPL(dev_pm_opp_of_add_table_indexed);
1044
1045 /* CPU device specific helpers */
1046
1047 /**
1048  * dev_pm_opp_of_cpumask_remove_table() - Removes OPP table for @cpumask
1049  * @cpumask:    cpumask for which OPP table needs to be removed
1050  *
1051  * This removes the OPP tables for CPUs present in the @cpumask.
1052  * This should be used only to remove static entries created from DT.
1053  */
1054 void dev_pm_opp_of_cpumask_remove_table(const struct cpumask *cpumask)
1055 {
1056         _dev_pm_opp_cpumask_remove_table(cpumask, -1);
1057 }
1058 EXPORT_SYMBOL_GPL(dev_pm_opp_of_cpumask_remove_table);
1059
1060 /**
1061  * dev_pm_opp_of_cpumask_add_table() - Adds OPP table for @cpumask
1062  * @cpumask:    cpumask for which OPP table needs to be added.
1063  *
1064  * This adds the OPP tables for CPUs present in the @cpumask.
1065  */
1066 int dev_pm_opp_of_cpumask_add_table(const struct cpumask *cpumask)
1067 {
1068         struct device *cpu_dev;
1069         int cpu, ret;
1070
1071         if (WARN_ON(cpumask_empty(cpumask)))
1072                 return -ENODEV;
1073
1074         for_each_cpu(cpu, cpumask) {
1075                 cpu_dev = get_cpu_device(cpu);
1076                 if (!cpu_dev) {
1077                         pr_err("%s: failed to get cpu%d device\n", __func__,
1078                                cpu);
1079                         ret = -ENODEV;
1080                         goto remove_table;
1081                 }
1082
1083                 ret = dev_pm_opp_of_add_table(cpu_dev);
1084                 if (ret) {
1085                         /*
1086                          * OPP may get registered dynamically, don't print error
1087                          * message here.
1088                          */
1089                         pr_debug("%s: couldn't find opp table for cpu:%d, %d\n",
1090                                  __func__, cpu, ret);
1091
1092                         goto remove_table;
1093                 }
1094         }
1095
1096         return 0;
1097
1098 remove_table:
1099         /* Free all other OPPs */
1100         _dev_pm_opp_cpumask_remove_table(cpumask, cpu);
1101
1102         return ret;
1103 }
1104 EXPORT_SYMBOL_GPL(dev_pm_opp_of_cpumask_add_table);
1105
1106 /*
1107  * Works only for OPP v2 bindings.
1108  *
1109  * Returns -ENOENT if operating-points-v2 bindings aren't supported.
1110  */
1111 /**
1112  * dev_pm_opp_of_get_sharing_cpus() - Get cpumask of CPUs sharing OPPs with
1113  *                                    @cpu_dev using operating-points-v2
1114  *                                    bindings.
1115  *
1116  * @cpu_dev:    CPU device for which we do this operation
1117  * @cpumask:    cpumask to update with information of sharing CPUs
1118  *
1119  * This updates the @cpumask with CPUs that are sharing OPPs with @cpu_dev.
1120  *
1121  * Returns -ENOENT if operating-points-v2 isn't present for @cpu_dev.
1122  */
1123 int dev_pm_opp_of_get_sharing_cpus(struct device *cpu_dev,
1124                                    struct cpumask *cpumask)
1125 {
1126         struct device_node *np, *tmp_np, *cpu_np;
1127         int cpu, ret = 0;
1128
1129         /* Get OPP descriptor node */
1130         np = dev_pm_opp_of_get_opp_desc_node(cpu_dev);
1131         if (!np) {
1132                 dev_dbg(cpu_dev, "%s: Couldn't find opp node.\n", __func__);
1133                 return -ENOENT;
1134         }
1135
1136         cpumask_set_cpu(cpu_dev->id, cpumask);
1137
1138         /* OPPs are shared ? */
1139         if (!of_property_read_bool(np, "opp-shared"))
1140                 goto put_cpu_node;
1141
1142         for_each_possible_cpu(cpu) {
1143                 if (cpu == cpu_dev->id)
1144                         continue;
1145
1146                 cpu_np = of_cpu_device_node_get(cpu);
1147                 if (!cpu_np) {
1148                         dev_err(cpu_dev, "%s: failed to get cpu%d node\n",
1149                                 __func__, cpu);
1150                         ret = -ENOENT;
1151                         goto put_cpu_node;
1152                 }
1153
1154                 /* Get OPP descriptor node */
1155                 tmp_np = _opp_of_get_opp_desc_node(cpu_np, 0);
1156                 of_node_put(cpu_np);
1157                 if (!tmp_np) {
1158                         pr_err("%pOF: Couldn't find opp node\n", cpu_np);
1159                         ret = -ENOENT;
1160                         goto put_cpu_node;
1161                 }
1162
1163                 /* CPUs are sharing opp node */
1164                 if (np == tmp_np)
1165                         cpumask_set_cpu(cpu, cpumask);
1166
1167                 of_node_put(tmp_np);
1168         }
1169
1170 put_cpu_node:
1171         of_node_put(np);
1172         return ret;
1173 }
1174 EXPORT_SYMBOL_GPL(dev_pm_opp_of_get_sharing_cpus);
1175
1176 /**
1177  * of_get_required_opp_performance_state() - Search for required OPP and return its performance state.
1178  * @np: Node that contains the "required-opps" property.
1179  * @index: Index of the phandle to parse.
1180  *
1181  * Returns the performance state of the OPP pointed out by the "required-opps"
1182  * property at @index in @np.
1183  *
1184  * Return: Zero or positive performance state on success, otherwise negative
1185  * value on errors.
1186  */
1187 int of_get_required_opp_performance_state(struct device_node *np, int index)
1188 {
1189         struct dev_pm_opp *opp;
1190         struct device_node *required_np;
1191         struct opp_table *opp_table;
1192         int pstate = -EINVAL;
1193
1194         required_np = of_parse_required_opp(np, index);
1195         if (!required_np)
1196                 return -EINVAL;
1197
1198         opp_table = _find_table_of_opp_np(required_np);
1199         if (IS_ERR(opp_table)) {
1200                 pr_err("%s: Failed to find required OPP table %pOF: %ld\n",
1201                        __func__, np, PTR_ERR(opp_table));
1202                 goto put_required_np;
1203         }
1204
1205         opp = _find_opp_of_np(opp_table, required_np);
1206         if (opp) {
1207                 pstate = opp->pstate;
1208                 dev_pm_opp_put(opp);
1209         }
1210
1211         dev_pm_opp_put_opp_table(opp_table);
1212
1213 put_required_np:
1214         of_node_put(required_np);
1215
1216         return pstate;
1217 }
1218 EXPORT_SYMBOL_GPL(of_get_required_opp_performance_state);
1219
1220 /**
1221  * dev_pm_opp_get_of_node() - Gets the DT node corresponding to an opp
1222  * @opp:        opp for which DT node has to be returned for
1223  *
1224  * Return: DT node corresponding to the opp, else 0 on success.
1225  *
1226  * The caller needs to put the node with of_node_put() after using it.
1227  */
1228 struct device_node *dev_pm_opp_get_of_node(struct dev_pm_opp *opp)
1229 {
1230         if (IS_ERR_OR_NULL(opp)) {
1231                 pr_err("%s: Invalid parameters\n", __func__);
1232                 return NULL;
1233         }
1234
1235         return of_node_get(opp->np);
1236 }
1237 EXPORT_SYMBOL_GPL(dev_pm_opp_get_of_node);
1238
1239 /*
1240  * Callback function provided to the Energy Model framework upon registration.
1241  * This computes the power estimated by @dev at @kHz if it is the frequency
1242  * of an existing OPP, or at the frequency of the first OPP above @kHz otherwise
1243  * (see dev_pm_opp_find_freq_ceil()). This function updates @kHz to the ceiled
1244  * frequency and @mW to the associated power. The power is estimated as
1245  * P = C * V^2 * f with C being the device's capacitance and V and f
1246  * respectively the voltage and frequency of the OPP.
1247  *
1248  * Returns -EINVAL if the power calculation failed because of missing
1249  * parameters, 0 otherwise.
1250  */
1251 static int __maybe_unused _get_power(unsigned long *mW, unsigned long *kHz,
1252                                      struct device *dev)
1253 {
1254         struct dev_pm_opp *opp;
1255         struct device_node *np;
1256         unsigned long mV, Hz;
1257         u32 cap;
1258         u64 tmp;
1259         int ret;
1260
1261         np = of_node_get(dev->of_node);
1262         if (!np)
1263                 return -EINVAL;
1264
1265         ret = of_property_read_u32(np, "dynamic-power-coefficient", &cap);
1266         of_node_put(np);
1267         if (ret)
1268                 return -EINVAL;
1269
1270         Hz = *kHz * 1000;
1271         opp = dev_pm_opp_find_freq_ceil(dev, &Hz);
1272         if (IS_ERR(opp))
1273                 return -EINVAL;
1274
1275         mV = dev_pm_opp_get_voltage(opp) / 1000;
1276         dev_pm_opp_put(opp);
1277         if (!mV)
1278                 return -EINVAL;
1279
1280         tmp = (u64)cap * mV * mV * (Hz / 1000000);
1281         do_div(tmp, 1000000000);
1282
1283         *mW = (unsigned long)tmp;
1284         *kHz = Hz / 1000;
1285
1286         return 0;
1287 }
1288
1289 /**
1290  * dev_pm_opp_of_register_em() - Attempt to register an Energy Model
1291  * @dev         : Device for which an Energy Model has to be registered
1292  * @cpus        : CPUs for which an Energy Model has to be registered. For
1293  *              other type of devices it should be set to NULL.
1294  *
1295  * This checks whether the "dynamic-power-coefficient" devicetree property has
1296  * been specified, and tries to register an Energy Model with it if it has.
1297  * Having this property means the voltages are known for OPPs and the EM
1298  * might be calculated.
1299  */
1300 int dev_pm_opp_of_register_em(struct device *dev, struct cpumask *cpus)
1301 {
1302         struct em_data_callback em_cb = EM_DATA_CB(_get_power);
1303         struct device_node *np;
1304         int ret, nr_opp;
1305         u32 cap;
1306
1307         if (IS_ERR_OR_NULL(dev)) {
1308                 ret = -EINVAL;
1309                 goto failed;
1310         }
1311
1312         nr_opp = dev_pm_opp_get_opp_count(dev);
1313         if (nr_opp <= 0) {
1314                 ret = -EINVAL;
1315                 goto failed;
1316         }
1317
1318         np = of_node_get(dev->of_node);
1319         if (!np) {
1320                 ret = -EINVAL;
1321                 goto failed;
1322         }
1323
1324         /*
1325          * Register an EM only if the 'dynamic-power-coefficient' property is
1326          * set in devicetree. It is assumed the voltage values are known if that
1327          * property is set since it is useless otherwise. If voltages are not
1328          * known, just let the EM registration fail with an error to alert the
1329          * user about the inconsistent configuration.
1330          */
1331         ret = of_property_read_u32(np, "dynamic-power-coefficient", &cap);
1332         of_node_put(np);
1333         if (ret || !cap) {
1334                 dev_dbg(dev, "Couldn't find proper 'dynamic-power-coefficient' in DT\n");
1335                 ret = -EINVAL;
1336                 goto failed;
1337         }
1338
1339         ret = em_dev_register_perf_domain(dev, nr_opp, &em_cb, cpus);
1340         if (ret)
1341                 goto failed;
1342
1343         return 0;
1344
1345 failed:
1346         dev_dbg(dev, "Couldn't register Energy Model %d\n", ret);
1347         return ret;
1348 }
1349 EXPORT_SYMBOL_GPL(dev_pm_opp_of_register_em);