OPP: Call dev_pm_opp_set_opp() for required OPPs
[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.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 /* OPP tables with uninitialized required OPPs, protected by opp_table_lock */
25 static LIST_HEAD(lazy_opp_tables);
26
27 /*
28  * Returns opp descriptor node for a device node, caller must
29  * do of_node_put().
30  */
31 static struct device_node *_opp_of_get_opp_desc_node(struct device_node *np,
32                                                      int index)
33 {
34         /* "operating-points-v2" can be an array for power domain providers */
35         return of_parse_phandle(np, "operating-points-v2", index);
36 }
37
38 /* Returns opp descriptor node for a device, caller must do of_node_put() */
39 struct device_node *dev_pm_opp_of_get_opp_desc_node(struct device *dev)
40 {
41         return _opp_of_get_opp_desc_node(dev->of_node, 0);
42 }
43 EXPORT_SYMBOL_GPL(dev_pm_opp_of_get_opp_desc_node);
44
45 struct opp_table *_managed_opp(struct device *dev, int index)
46 {
47         struct opp_table *opp_table, *managed_table = NULL;
48         struct device_node *np;
49
50         np = _opp_of_get_opp_desc_node(dev->of_node, index);
51         if (!np)
52                 return NULL;
53
54         list_for_each_entry(opp_table, &opp_tables, node) {
55                 if (opp_table->np == np) {
56                         /*
57                          * Multiple devices can point to the same OPP table and
58                          * so will have same node-pointer, np.
59                          *
60                          * But the OPPs will be considered as shared only if the
61                          * OPP table contains a "opp-shared" property.
62                          */
63                         if (opp_table->shared_opp == OPP_TABLE_ACCESS_SHARED) {
64                                 _get_opp_table_kref(opp_table);
65                                 managed_table = opp_table;
66                         }
67
68                         break;
69                 }
70         }
71
72         of_node_put(np);
73
74         return managed_table;
75 }
76
77 /* The caller must call dev_pm_opp_put() after the OPP is used */
78 static struct dev_pm_opp *_find_opp_of_np(struct opp_table *opp_table,
79                                           struct device_node *opp_np)
80 {
81         struct dev_pm_opp *opp;
82
83         mutex_lock(&opp_table->lock);
84
85         list_for_each_entry(opp, &opp_table->opp_list, node) {
86                 if (opp->np == opp_np) {
87                         dev_pm_opp_get(opp);
88                         mutex_unlock(&opp_table->lock);
89                         return opp;
90                 }
91         }
92
93         mutex_unlock(&opp_table->lock);
94
95         return NULL;
96 }
97
98 static struct device_node *of_parse_required_opp(struct device_node *np,
99                                                  int index)
100 {
101         return of_parse_phandle(np, "required-opps", index);
102 }
103
104 /* The caller must call dev_pm_opp_put_opp_table() after the table is used */
105 static struct opp_table *_find_table_of_opp_np(struct device_node *opp_np)
106 {
107         struct opp_table *opp_table;
108         struct device_node *opp_table_np;
109
110         opp_table_np = of_get_parent(opp_np);
111         if (!opp_table_np)
112                 goto err;
113
114         /* It is safe to put the node now as all we need now is its address */
115         of_node_put(opp_table_np);
116
117         mutex_lock(&opp_table_lock);
118         list_for_each_entry(opp_table, &opp_tables, node) {
119                 if (opp_table_np == opp_table->np) {
120                         _get_opp_table_kref(opp_table);
121                         mutex_unlock(&opp_table_lock);
122                         return opp_table;
123                 }
124         }
125         mutex_unlock(&opp_table_lock);
126
127 err:
128         return ERR_PTR(-ENODEV);
129 }
130
131 /* Free resources previously acquired by _opp_table_alloc_required_tables() */
132 static void _opp_table_free_required_tables(struct opp_table *opp_table)
133 {
134         struct opp_table **required_opp_tables = opp_table->required_opp_tables;
135         int i;
136
137         if (!required_opp_tables)
138                 return;
139
140         for (i = 0; i < opp_table->required_opp_count; i++) {
141                 if (IS_ERR_OR_NULL(required_opp_tables[i]))
142                         continue;
143
144                 dev_pm_opp_put_opp_table(required_opp_tables[i]);
145         }
146
147         kfree(required_opp_tables);
148
149         opp_table->required_opp_count = 0;
150         opp_table->required_opp_tables = NULL;
151
152         mutex_lock(&opp_table_lock);
153         list_del(&opp_table->lazy);
154         mutex_unlock(&opp_table_lock);
155 }
156
157 /*
158  * Populate all devices and opp tables which are part of "required-opps" list.
159  * Checking only the first OPP node should be enough.
160  */
161 static void _opp_table_alloc_required_tables(struct opp_table *opp_table,
162                                              struct device *dev,
163                                              struct device_node *opp_np)
164 {
165         struct opp_table **required_opp_tables;
166         struct device_node *required_np, *np;
167         bool lazy = false;
168         int count, i, size;
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_warn(dev, "Empty OPP table\n");
174
175                 return;
176         }
177
178         count = of_count_phandle_with_args(np, "required-opps", NULL);
179         if (count <= 0)
180                 goto put_np;
181
182         size = sizeof(*required_opp_tables) + sizeof(*opp_table->required_devs);
183         required_opp_tables = kcalloc(count, size, GFP_KERNEL);
184         if (!required_opp_tables)
185                 goto put_np;
186
187         opp_table->required_opp_tables = required_opp_tables;
188         opp_table->required_devs = (void *)(required_opp_tables + count);
189         opp_table->required_opp_count = count;
190
191         for (i = 0; i < count; i++) {
192                 required_np = of_parse_required_opp(np, i);
193                 if (!required_np)
194                         goto free_required_tables;
195
196                 required_opp_tables[i] = _find_table_of_opp_np(required_np);
197                 of_node_put(required_np);
198
199                 if (IS_ERR(required_opp_tables[i]))
200                         lazy = true;
201         }
202
203         /* Let's do the linking later on */
204         if (lazy) {
205                 /*
206                  * The OPP table is not held while allocating the table, take it
207                  * now to avoid corruption to the lazy_opp_tables list.
208                  */
209                 mutex_lock(&opp_table_lock);
210                 list_add(&opp_table->lazy, &lazy_opp_tables);
211                 mutex_unlock(&opp_table_lock);
212         }
213
214         goto put_np;
215
216 free_required_tables:
217         _opp_table_free_required_tables(opp_table);
218 put_np:
219         of_node_put(np);
220 }
221
222 void _of_init_opp_table(struct opp_table *opp_table, struct device *dev,
223                         int index)
224 {
225         struct device_node *np, *opp_np;
226         u32 val;
227
228         /*
229          * Only required for backward compatibility with v1 bindings, but isn't
230          * harmful for other cases. And so we do it unconditionally.
231          */
232         np = of_node_get(dev->of_node);
233         if (!np)
234                 return;
235
236         if (!of_property_read_u32(np, "clock-latency", &val))
237                 opp_table->clock_latency_ns_max = val;
238         of_property_read_u32(np, "voltage-tolerance",
239                              &opp_table->voltage_tolerance_v1);
240
241         if (of_property_present(np, "#power-domain-cells"))
242                 opp_table->is_genpd = true;
243
244         /* Get OPP table node */
245         opp_np = _opp_of_get_opp_desc_node(np, index);
246         of_node_put(np);
247
248         if (!opp_np)
249                 return;
250
251         if (of_property_read_bool(opp_np, "opp-shared"))
252                 opp_table->shared_opp = OPP_TABLE_ACCESS_SHARED;
253         else
254                 opp_table->shared_opp = OPP_TABLE_ACCESS_EXCLUSIVE;
255
256         opp_table->np = opp_np;
257
258         _opp_table_alloc_required_tables(opp_table, dev, opp_np);
259 }
260
261 void _of_clear_opp_table(struct opp_table *opp_table)
262 {
263         _opp_table_free_required_tables(opp_table);
264         of_node_put(opp_table->np);
265 }
266
267 /*
268  * Release all resources previously acquired with a call to
269  * _of_opp_alloc_required_opps().
270  */
271 static void _of_opp_free_required_opps(struct opp_table *opp_table,
272                                        struct dev_pm_opp *opp)
273 {
274         struct dev_pm_opp **required_opps = opp->required_opps;
275         int i;
276
277         if (!required_opps)
278                 return;
279
280         for (i = 0; i < opp_table->required_opp_count; i++) {
281                 if (!required_opps[i])
282                         continue;
283
284                 /* Put the reference back */
285                 dev_pm_opp_put(required_opps[i]);
286         }
287
288         opp->required_opps = NULL;
289         kfree(required_opps);
290 }
291
292 void _of_clear_opp(struct opp_table *opp_table, struct dev_pm_opp *opp)
293 {
294         _of_opp_free_required_opps(opp_table, opp);
295         of_node_put(opp->np);
296 }
297
298 static int _link_required_opps(struct dev_pm_opp *opp, struct opp_table *opp_table,
299                                struct opp_table *required_table, int index)
300 {
301         struct device_node *np;
302
303         np = of_parse_required_opp(opp->np, index);
304         if (unlikely(!np))
305                 return -ENODEV;
306
307         opp->required_opps[index] = _find_opp_of_np(required_table, np);
308         of_node_put(np);
309
310         if (!opp->required_opps[index]) {
311                 pr_err("%s: Unable to find required OPP node: %pOF (%d)\n",
312                        __func__, opp->np, index);
313                 return -ENODEV;
314         }
315
316         /*
317          * There are two genpd (as required-opp) cases that we need to handle,
318          * devices with a single genpd and ones with multiple genpds.
319          *
320          * The single genpd case requires special handling as we need to use the
321          * same `dev` structure (instead of a virtual one provided by genpd
322          * core) for setting the performance state.
323          *
324          * It doesn't make sense for a device's DT entry to have both
325          * "opp-level" and single "required-opps" entry pointing to a genpd's
326          * OPP, as that would make the OPP core call
327          * dev_pm_domain_set_performance_state() for two different values for
328          * the same device structure. Lets treat single genpd configuration as a
329          * case where the OPP's level is directly available without required-opp
330          * link in the DT.
331          *
332          * Just update the `level` with the right value, which
333          * dev_pm_opp_set_opp() will take care of in the normal path itself.
334          *
335          * There is another case though, where a genpd's OPP table has
336          * required-opps set to a parent genpd. The OPP core expects the user to
337          * set the respective required `struct device` pointer via
338          * dev_pm_opp_set_config().
339          */
340         if (required_table->is_genpd && opp_table->required_opp_count == 1 &&
341             !opp_table->required_devs[0]) {
342                 if (!WARN_ON(opp->level != OPP_LEVEL_UNSET))
343                         opp->level = opp->required_opps[0]->level;
344         }
345
346         return 0;
347 }
348
349 /* Populate all required OPPs which are part of "required-opps" list */
350 static int _of_opp_alloc_required_opps(struct opp_table *opp_table,
351                                        struct dev_pm_opp *opp)
352 {
353         struct opp_table *required_table;
354         int i, ret, count = opp_table->required_opp_count;
355
356         if (!count)
357                 return 0;
358
359         opp->required_opps = kcalloc(count, sizeof(*opp->required_opps), GFP_KERNEL);
360         if (!opp->required_opps)
361                 return -ENOMEM;
362
363         for (i = 0; i < count; i++) {
364                 required_table = opp_table->required_opp_tables[i];
365
366                 /* Required table not added yet, we will link later */
367                 if (IS_ERR_OR_NULL(required_table))
368                         continue;
369
370                 ret = _link_required_opps(opp, opp_table, required_table, i);
371                 if (ret)
372                         goto free_required_opps;
373         }
374
375         return 0;
376
377 free_required_opps:
378         _of_opp_free_required_opps(opp_table, opp);
379
380         return ret;
381 }
382
383 /* Link required OPPs for an individual OPP */
384 static int lazy_link_required_opps(struct opp_table *opp_table,
385                                    struct opp_table *new_table, int index)
386 {
387         struct dev_pm_opp *opp;
388         int ret;
389
390         list_for_each_entry(opp, &opp_table->opp_list, node) {
391                 ret = _link_required_opps(opp, opp_table, new_table, index);
392                 if (ret)
393                         return ret;
394         }
395
396         return 0;
397 }
398
399 /* Link required OPPs for all OPPs of the newly added OPP table */
400 static void lazy_link_required_opp_table(struct opp_table *new_table)
401 {
402         struct opp_table *opp_table, *temp, **required_opp_tables;
403         struct device_node *required_np, *opp_np, *required_table_np;
404         struct dev_pm_opp *opp;
405         int i, ret;
406
407         mutex_lock(&opp_table_lock);
408
409         list_for_each_entry_safe(opp_table, temp, &lazy_opp_tables, lazy) {
410                 bool lazy = false;
411
412                 /* opp_np can't be invalid here */
413                 opp_np = of_get_next_available_child(opp_table->np, NULL);
414
415                 for (i = 0; i < opp_table->required_opp_count; i++) {
416                         required_opp_tables = opp_table->required_opp_tables;
417
418                         /* Required opp-table is already parsed */
419                         if (!IS_ERR(required_opp_tables[i]))
420                                 continue;
421
422                         /* required_np can't be invalid here */
423                         required_np = of_parse_required_opp(opp_np, i);
424                         required_table_np = of_get_parent(required_np);
425
426                         of_node_put(required_table_np);
427                         of_node_put(required_np);
428
429                         /*
430                          * Newly added table isn't the required opp-table for
431                          * opp_table.
432                          */
433                         if (required_table_np != new_table->np) {
434                                 lazy = true;
435                                 continue;
436                         }
437
438                         required_opp_tables[i] = new_table;
439                         _get_opp_table_kref(new_table);
440
441                         /* Link OPPs now */
442                         ret = lazy_link_required_opps(opp_table, new_table, i);
443                         if (ret) {
444                                 /* The OPPs will be marked unusable */
445                                 lazy = false;
446                                 break;
447                         }
448                 }
449
450                 of_node_put(opp_np);
451
452                 /* All required opp-tables found, remove from lazy list */
453                 if (!lazy) {
454                         list_del_init(&opp_table->lazy);
455
456                         list_for_each_entry(opp, &opp_table->opp_list, node)
457                                 _required_opps_available(opp, opp_table->required_opp_count);
458                 }
459         }
460
461         mutex_unlock(&opp_table_lock);
462 }
463
464 static int _bandwidth_supported(struct device *dev, struct opp_table *opp_table)
465 {
466         struct device_node *np, *opp_np;
467         struct property *prop;
468
469         if (!opp_table) {
470                 np = of_node_get(dev->of_node);
471                 if (!np)
472                         return -ENODEV;
473
474                 opp_np = _opp_of_get_opp_desc_node(np, 0);
475                 of_node_put(np);
476         } else {
477                 opp_np = of_node_get(opp_table->np);
478         }
479
480         /* Lets not fail in case we are parsing opp-v1 bindings */
481         if (!opp_np)
482                 return 0;
483
484         /* Checking only first OPP is sufficient */
485         np = of_get_next_available_child(opp_np, NULL);
486         of_node_put(opp_np);
487         if (!np) {
488                 dev_err(dev, "OPP table empty\n");
489                 return -EINVAL;
490         }
491
492         prop = of_find_property(np, "opp-peak-kBps", NULL);
493         of_node_put(np);
494
495         if (!prop || !prop->length)
496                 return 0;
497
498         return 1;
499 }
500
501 int dev_pm_opp_of_find_icc_paths(struct device *dev,
502                                  struct opp_table *opp_table)
503 {
504         struct device_node *np;
505         int ret, i, count, num_paths;
506         struct icc_path **paths;
507
508         ret = _bandwidth_supported(dev, opp_table);
509         if (ret == -EINVAL)
510                 return 0; /* Empty OPP table is a valid corner-case, let's not fail */
511         else if (ret <= 0)
512                 return ret;
513
514         ret = 0;
515
516         np = of_node_get(dev->of_node);
517         if (!np)
518                 return 0;
519
520         count = of_count_phandle_with_args(np, "interconnects",
521                                            "#interconnect-cells");
522         of_node_put(np);
523         if (count < 0)
524                 return 0;
525
526         /* two phandles when #interconnect-cells = <1> */
527         if (count % 2) {
528                 dev_err(dev, "%s: Invalid interconnects values\n", __func__);
529                 return -EINVAL;
530         }
531
532         num_paths = count / 2;
533         paths = kcalloc(num_paths, sizeof(*paths), GFP_KERNEL);
534         if (!paths)
535                 return -ENOMEM;
536
537         for (i = 0; i < num_paths; i++) {
538                 paths[i] = of_icc_get_by_index(dev, i);
539                 if (IS_ERR(paths[i])) {
540                         ret = dev_err_probe(dev, PTR_ERR(paths[i]), "%s: Unable to get path%d\n", __func__, i);
541                         goto err;
542                 }
543         }
544
545         if (opp_table) {
546                 opp_table->paths = paths;
547                 opp_table->path_count = num_paths;
548                 return 0;
549         }
550
551 err:
552         while (i--)
553                 icc_put(paths[i]);
554
555         kfree(paths);
556
557         return ret;
558 }
559 EXPORT_SYMBOL_GPL(dev_pm_opp_of_find_icc_paths);
560
561 static bool _opp_is_supported(struct device *dev, struct opp_table *opp_table,
562                               struct device_node *np)
563 {
564         unsigned int levels = opp_table->supported_hw_count;
565         int count, versions, ret, i, j;
566         u32 val;
567
568         if (!opp_table->supported_hw) {
569                 /*
570                  * In the case that no supported_hw has been set by the
571                  * platform but there is an opp-supported-hw value set for
572                  * an OPP then the OPP should not be enabled as there is
573                  * no way to see if the hardware supports it.
574                  */
575                 if (of_property_present(np, "opp-supported-hw"))
576                         return false;
577                 else
578                         return true;
579         }
580
581         count = of_property_count_u32_elems(np, "opp-supported-hw");
582         if (count <= 0 || count % levels) {
583                 dev_err(dev, "%s: Invalid opp-supported-hw property (%d)\n",
584                         __func__, count);
585                 return false;
586         }
587
588         versions = count / levels;
589
590         /* All levels in at least one of the versions should match */
591         for (i = 0; i < versions; i++) {
592                 bool supported = true;
593
594                 for (j = 0; j < levels; j++) {
595                         ret = of_property_read_u32_index(np, "opp-supported-hw",
596                                                          i * levels + j, &val);
597                         if (ret) {
598                                 dev_warn(dev, "%s: failed to read opp-supported-hw property at index %d: %d\n",
599                                          __func__, i * levels + j, ret);
600                                 return false;
601                         }
602
603                         /* Check if the level is supported */
604                         if (!(val & opp_table->supported_hw[j])) {
605                                 supported = false;
606                                 break;
607                         }
608                 }
609
610                 if (supported)
611                         return true;
612         }
613
614         return false;
615 }
616
617 static u32 *_parse_named_prop(struct dev_pm_opp *opp, struct device *dev,
618                               struct opp_table *opp_table,
619                               const char *prop_type, bool *triplet)
620 {
621         struct property *prop = NULL;
622         char name[NAME_MAX];
623         int count, ret;
624         u32 *out;
625
626         /* Search for "opp-<prop_type>-<name>" */
627         if (opp_table->prop_name) {
628                 snprintf(name, sizeof(name), "opp-%s-%s", prop_type,
629                          opp_table->prop_name);
630                 prop = of_find_property(opp->np, name, NULL);
631         }
632
633         if (!prop) {
634                 /* Search for "opp-<prop_type>" */
635                 snprintf(name, sizeof(name), "opp-%s", prop_type);
636                 prop = of_find_property(opp->np, name, NULL);
637                 if (!prop)
638                         return NULL;
639         }
640
641         count = of_property_count_u32_elems(opp->np, name);
642         if (count < 0) {
643                 dev_err(dev, "%s: Invalid %s property (%d)\n", __func__, name,
644                         count);
645                 return ERR_PTR(count);
646         }
647
648         /*
649          * Initialize regulator_count, if regulator information isn't provided
650          * by the platform. Now that one of the properties is available, fix the
651          * regulator_count to 1.
652          */
653         if (unlikely(opp_table->regulator_count == -1))
654                 opp_table->regulator_count = 1;
655
656         if (count != opp_table->regulator_count &&
657             (!triplet || count != opp_table->regulator_count * 3)) {
658                 dev_err(dev, "%s: Invalid number of elements in %s property (%u) with supplies (%d)\n",
659                         __func__, prop_type, count, opp_table->regulator_count);
660                 return ERR_PTR(-EINVAL);
661         }
662
663         out = kmalloc_array(count, sizeof(*out), GFP_KERNEL);
664         if (!out)
665                 return ERR_PTR(-EINVAL);
666
667         ret = of_property_read_u32_array(opp->np, name, out, count);
668         if (ret) {
669                 dev_err(dev, "%s: error parsing %s: %d\n", __func__, name, ret);
670                 kfree(out);
671                 return ERR_PTR(-EINVAL);
672         }
673
674         if (triplet)
675                 *triplet = count != opp_table->regulator_count;
676
677         return out;
678 }
679
680 static u32 *opp_parse_microvolt(struct dev_pm_opp *opp, struct device *dev,
681                                 struct opp_table *opp_table, bool *triplet)
682 {
683         u32 *microvolt;
684
685         microvolt = _parse_named_prop(opp, dev, opp_table, "microvolt", triplet);
686         if (IS_ERR(microvolt))
687                 return microvolt;
688
689         if (!microvolt) {
690                 /*
691                  * Missing property isn't a problem, but an invalid
692                  * entry is. This property isn't optional if regulator
693                  * information is provided. Check only for the first OPP, as
694                  * regulator_count may get initialized after that to a valid
695                  * value.
696                  */
697                 if (list_empty(&opp_table->opp_list) &&
698                     opp_table->regulator_count > 0) {
699                         dev_err(dev, "%s: opp-microvolt missing although OPP managing regulators\n",
700                                 __func__);
701                         return ERR_PTR(-EINVAL);
702                 }
703         }
704
705         return microvolt;
706 }
707
708 static int opp_parse_supplies(struct dev_pm_opp *opp, struct device *dev,
709                               struct opp_table *opp_table)
710 {
711         u32 *microvolt, *microamp, *microwatt;
712         int ret = 0, i, j;
713         bool triplet;
714
715         microvolt = opp_parse_microvolt(opp, dev, opp_table, &triplet);
716         if (IS_ERR(microvolt))
717                 return PTR_ERR(microvolt);
718
719         microamp = _parse_named_prop(opp, dev, opp_table, "microamp", NULL);
720         if (IS_ERR(microamp)) {
721                 ret = PTR_ERR(microamp);
722                 goto free_microvolt;
723         }
724
725         microwatt = _parse_named_prop(opp, dev, opp_table, "microwatt", NULL);
726         if (IS_ERR(microwatt)) {
727                 ret = PTR_ERR(microwatt);
728                 goto free_microamp;
729         }
730
731         /*
732          * Initialize regulator_count if it is uninitialized and no properties
733          * are found.
734          */
735         if (unlikely(opp_table->regulator_count == -1)) {
736                 opp_table->regulator_count = 0;
737                 return 0;
738         }
739
740         for (i = 0, j = 0; i < opp_table->regulator_count; i++) {
741                 if (microvolt) {
742                         opp->supplies[i].u_volt = microvolt[j++];
743
744                         if (triplet) {
745                                 opp->supplies[i].u_volt_min = microvolt[j++];
746                                 opp->supplies[i].u_volt_max = microvolt[j++];
747                         } else {
748                                 opp->supplies[i].u_volt_min = opp->supplies[i].u_volt;
749                                 opp->supplies[i].u_volt_max = opp->supplies[i].u_volt;
750                         }
751                 }
752
753                 if (microamp)
754                         opp->supplies[i].u_amp = microamp[i];
755
756                 if (microwatt)
757                         opp->supplies[i].u_watt = microwatt[i];
758         }
759
760         kfree(microwatt);
761 free_microamp:
762         kfree(microamp);
763 free_microvolt:
764         kfree(microvolt);
765
766         return ret;
767 }
768
769 /**
770  * dev_pm_opp_of_remove_table() - Free OPP table entries created from static DT
771  *                                entries
772  * @dev:        device pointer used to lookup OPP table.
773  *
774  * Free OPPs created using static entries present in DT.
775  */
776 void dev_pm_opp_of_remove_table(struct device *dev)
777 {
778         dev_pm_opp_remove_table(dev);
779 }
780 EXPORT_SYMBOL_GPL(dev_pm_opp_of_remove_table);
781
782 static int _read_rate(struct dev_pm_opp *new_opp, struct opp_table *opp_table,
783                       struct device_node *np)
784 {
785         struct property *prop;
786         int i, count, ret;
787         u64 *rates;
788
789         prop = of_find_property(np, "opp-hz", NULL);
790         if (!prop)
791                 return -ENODEV;
792
793         count = prop->length / sizeof(u64);
794         if (opp_table->clk_count != count) {
795                 pr_err("%s: Count mismatch between opp-hz and clk_count (%d %d)\n",
796                        __func__, count, opp_table->clk_count);
797                 return -EINVAL;
798         }
799
800         rates = kmalloc_array(count, sizeof(*rates), GFP_KERNEL);
801         if (!rates)
802                 return -ENOMEM;
803
804         ret = of_property_read_u64_array(np, "opp-hz", rates, count);
805         if (ret) {
806                 pr_err("%s: Error parsing opp-hz: %d\n", __func__, ret);
807         } else {
808                 /*
809                  * Rate is defined as an unsigned long in clk API, and so
810                  * casting explicitly to its type. Must be fixed once rate is 64
811                  * bit guaranteed in clk API.
812                  */
813                 for (i = 0; i < count; i++) {
814                         new_opp->rates[i] = (unsigned long)rates[i];
815
816                         /* This will happen for frequencies > 4.29 GHz */
817                         WARN_ON(new_opp->rates[i] != rates[i]);
818                 }
819         }
820
821         kfree(rates);
822
823         return ret;
824 }
825
826 static int _read_bw(struct dev_pm_opp *new_opp, struct opp_table *opp_table,
827                     struct device_node *np, bool peak)
828 {
829         const char *name = peak ? "opp-peak-kBps" : "opp-avg-kBps";
830         struct property *prop;
831         int i, count, ret;
832         u32 *bw;
833
834         prop = of_find_property(np, name, NULL);
835         if (!prop)
836                 return -ENODEV;
837
838         count = prop->length / sizeof(u32);
839         if (opp_table->path_count != count) {
840                 pr_err("%s: Mismatch between %s and paths (%d %d)\n",
841                                 __func__, name, count, opp_table->path_count);
842                 return -EINVAL;
843         }
844
845         bw = kmalloc_array(count, sizeof(*bw), GFP_KERNEL);
846         if (!bw)
847                 return -ENOMEM;
848
849         ret = of_property_read_u32_array(np, name, bw, count);
850         if (ret) {
851                 pr_err("%s: Error parsing %s: %d\n", __func__, name, ret);
852                 goto out;
853         }
854
855         for (i = 0; i < count; i++) {
856                 if (peak)
857                         new_opp->bandwidth[i].peak = kBps_to_icc(bw[i]);
858                 else
859                         new_opp->bandwidth[i].avg = kBps_to_icc(bw[i]);
860         }
861
862 out:
863         kfree(bw);
864         return ret;
865 }
866
867 static int _read_opp_key(struct dev_pm_opp *new_opp,
868                          struct opp_table *opp_table, struct device_node *np)
869 {
870         bool found = false;
871         int ret;
872
873         ret = _read_rate(new_opp, opp_table, np);
874         if (!ret)
875                 found = true;
876         else if (ret != -ENODEV)
877                 return ret;
878
879         /*
880          * Bandwidth consists of peak and average (optional) values:
881          * opp-peak-kBps = <path1_value path2_value>;
882          * opp-avg-kBps = <path1_value path2_value>;
883          */
884         ret = _read_bw(new_opp, opp_table, np, true);
885         if (!ret) {
886                 found = true;
887                 ret = _read_bw(new_opp, opp_table, np, false);
888         }
889
890         /* The properties were found but we failed to parse them */
891         if (ret && ret != -ENODEV)
892                 return ret;
893
894         if (!of_property_read_u32(np, "opp-level", &new_opp->level))
895                 found = true;
896
897         if (found)
898                 return 0;
899
900         return ret;
901 }
902
903 /**
904  * _opp_add_static_v2() - Allocate static OPPs (As per 'v2' DT bindings)
905  * @opp_table:  OPP table
906  * @dev:        device for which we do this operation
907  * @np:         device node
908  *
909  * This function adds an opp definition to the opp table and returns status. The
910  * opp can be controlled using dev_pm_opp_enable/disable functions and may be
911  * removed by dev_pm_opp_remove.
912  *
913  * Return:
914  * Valid OPP pointer:
915  *              On success
916  * NULL:
917  *              Duplicate OPPs (both freq and volt are same) and opp->available
918  *              OR if the OPP is not supported by hardware.
919  * ERR_PTR(-EEXIST):
920  *              Freq are same and volt are different OR
921  *              Duplicate OPPs (both freq and volt are same) and !opp->available
922  * ERR_PTR(-ENOMEM):
923  *              Memory allocation failure
924  * ERR_PTR(-EINVAL):
925  *              Failed parsing the OPP node
926  */
927 static struct dev_pm_opp *_opp_add_static_v2(struct opp_table *opp_table,
928                 struct device *dev, struct device_node *np)
929 {
930         struct dev_pm_opp *new_opp;
931         u32 val;
932         int ret;
933
934         new_opp = _opp_allocate(opp_table);
935         if (!new_opp)
936                 return ERR_PTR(-ENOMEM);
937
938         ret = _read_opp_key(new_opp, opp_table, np);
939         if (ret < 0) {
940                 dev_err(dev, "%s: opp key field not found\n", __func__);
941                 goto free_opp;
942         }
943
944         /* Check if the OPP supports hardware's hierarchy of versions or not */
945         if (!_opp_is_supported(dev, opp_table, np)) {
946                 dev_dbg(dev, "OPP not supported by hardware: %s\n",
947                         of_node_full_name(np));
948                 goto free_opp;
949         }
950
951         new_opp->turbo = of_property_read_bool(np, "turbo-mode");
952
953         new_opp->np = of_node_get(np);
954         new_opp->dynamic = false;
955         new_opp->available = true;
956
957         ret = _of_opp_alloc_required_opps(opp_table, new_opp);
958         if (ret)
959                 goto free_opp;
960
961         if (!of_property_read_u32(np, "clock-latency-ns", &val))
962                 new_opp->clock_latency_ns = val;
963
964         ret = opp_parse_supplies(new_opp, dev, opp_table);
965         if (ret)
966                 goto free_required_opps;
967
968         ret = _opp_add(dev, new_opp, opp_table);
969         if (ret) {
970                 /* Don't return error for duplicate OPPs */
971                 if (ret == -EBUSY)
972                         ret = 0;
973                 goto free_required_opps;
974         }
975
976         /* OPP to select on device suspend */
977         if (of_property_read_bool(np, "opp-suspend")) {
978                 if (opp_table->suspend_opp) {
979                         /* Pick the OPP with higher rate/bw/level as suspend OPP */
980                         if (_opp_compare_key(opp_table, new_opp, opp_table->suspend_opp) == 1) {
981                                 opp_table->suspend_opp->suspend = false;
982                                 new_opp->suspend = true;
983                                 opp_table->suspend_opp = new_opp;
984                         }
985                 } else {
986                         new_opp->suspend = true;
987                         opp_table->suspend_opp = new_opp;
988                 }
989         }
990
991         if (new_opp->clock_latency_ns > opp_table->clock_latency_ns_max)
992                 opp_table->clock_latency_ns_max = new_opp->clock_latency_ns;
993
994         pr_debug("%s: turbo:%d rate:%lu uv:%lu uvmin:%lu uvmax:%lu latency:%lu level:%u\n",
995                  __func__, new_opp->turbo, new_opp->rates[0],
996                  new_opp->supplies[0].u_volt, new_opp->supplies[0].u_volt_min,
997                  new_opp->supplies[0].u_volt_max, new_opp->clock_latency_ns,
998                  new_opp->level);
999
1000         /*
1001          * Notify the changes in the availability of the operable
1002          * frequency/voltage list.
1003          */
1004         blocking_notifier_call_chain(&opp_table->head, OPP_EVENT_ADD, new_opp);
1005         return new_opp;
1006
1007 free_required_opps:
1008         _of_opp_free_required_opps(opp_table, new_opp);
1009 free_opp:
1010         _opp_free(new_opp);
1011
1012         return ret ? ERR_PTR(ret) : NULL;
1013 }
1014
1015 /* Initializes OPP tables based on new bindings */
1016 static int _of_add_opp_table_v2(struct device *dev, struct opp_table *opp_table)
1017 {
1018         struct device_node *np;
1019         int ret, count = 0;
1020         struct dev_pm_opp *opp;
1021
1022         /* OPP table is already initialized for the device */
1023         mutex_lock(&opp_table->lock);
1024         if (opp_table->parsed_static_opps) {
1025                 opp_table->parsed_static_opps++;
1026                 mutex_unlock(&opp_table->lock);
1027                 return 0;
1028         }
1029
1030         opp_table->parsed_static_opps = 1;
1031         mutex_unlock(&opp_table->lock);
1032
1033         /* We have opp-table node now, iterate over it and add OPPs */
1034         for_each_available_child_of_node(opp_table->np, np) {
1035                 opp = _opp_add_static_v2(opp_table, dev, np);
1036                 if (IS_ERR(opp)) {
1037                         ret = PTR_ERR(opp);
1038                         dev_err(dev, "%s: Failed to add OPP, %d\n", __func__,
1039                                 ret);
1040                         of_node_put(np);
1041                         goto remove_static_opp;
1042                 } else if (opp) {
1043                         count++;
1044                 }
1045         }
1046
1047         /* There should be one or more OPPs defined */
1048         if (!count) {
1049                 dev_err(dev, "%s: no supported OPPs", __func__);
1050                 ret = -ENOENT;
1051                 goto remove_static_opp;
1052         }
1053
1054         lazy_link_required_opp_table(opp_table);
1055
1056         return 0;
1057
1058 remove_static_opp:
1059         _opp_remove_all_static(opp_table);
1060
1061         return ret;
1062 }
1063
1064 /* Initializes OPP tables based on old-deprecated bindings */
1065 static int _of_add_opp_table_v1(struct device *dev, struct opp_table *opp_table)
1066 {
1067         const struct property *prop;
1068         const __be32 *val;
1069         int nr, ret = 0;
1070
1071         mutex_lock(&opp_table->lock);
1072         if (opp_table->parsed_static_opps) {
1073                 opp_table->parsed_static_opps++;
1074                 mutex_unlock(&opp_table->lock);
1075                 return 0;
1076         }
1077
1078         opp_table->parsed_static_opps = 1;
1079         mutex_unlock(&opp_table->lock);
1080
1081         prop = of_find_property(dev->of_node, "operating-points", NULL);
1082         if (!prop) {
1083                 ret = -ENODEV;
1084                 goto remove_static_opp;
1085         }
1086         if (!prop->value) {
1087                 ret = -ENODATA;
1088                 goto remove_static_opp;
1089         }
1090
1091         /*
1092          * Each OPP is a set of tuples consisting of frequency and
1093          * voltage like <freq-kHz vol-uV>.
1094          */
1095         nr = prop->length / sizeof(u32);
1096         if (nr % 2) {
1097                 dev_err(dev, "%s: Invalid OPP table\n", __func__);
1098                 ret = -EINVAL;
1099                 goto remove_static_opp;
1100         }
1101
1102         val = prop->value;
1103         while (nr) {
1104                 unsigned long freq = be32_to_cpup(val++) * 1000;
1105                 unsigned long volt = be32_to_cpup(val++);
1106                 struct dev_pm_opp_data data = {
1107                         .freq = freq,
1108                         .u_volt = volt,
1109                 };
1110
1111                 ret = _opp_add_v1(opp_table, dev, &data, false);
1112                 if (ret) {
1113                         dev_err(dev, "%s: Failed to add OPP %ld (%d)\n",
1114                                 __func__, data.freq, ret);
1115                         goto remove_static_opp;
1116                 }
1117                 nr -= 2;
1118         }
1119
1120         return 0;
1121
1122 remove_static_opp:
1123         _opp_remove_all_static(opp_table);
1124
1125         return ret;
1126 }
1127
1128 static int _of_add_table_indexed(struct device *dev, int index)
1129 {
1130         struct opp_table *opp_table;
1131         int ret, count;
1132
1133         if (index) {
1134                 /*
1135                  * If only one phandle is present, then the same OPP table
1136                  * applies for all index requests.
1137                  */
1138                 count = of_count_phandle_with_args(dev->of_node,
1139                                                    "operating-points-v2", NULL);
1140                 if (count == 1)
1141                         index = 0;
1142         }
1143
1144         opp_table = _add_opp_table_indexed(dev, index, true);
1145         if (IS_ERR(opp_table))
1146                 return PTR_ERR(opp_table);
1147
1148         /*
1149          * OPPs have two version of bindings now. Also try the old (v1)
1150          * bindings for backward compatibility with older dtbs.
1151          */
1152         if (opp_table->np)
1153                 ret = _of_add_opp_table_v2(dev, opp_table);
1154         else
1155                 ret = _of_add_opp_table_v1(dev, opp_table);
1156
1157         if (ret)
1158                 dev_pm_opp_put_opp_table(opp_table);
1159
1160         return ret;
1161 }
1162
1163 static void devm_pm_opp_of_table_release(void *data)
1164 {
1165         dev_pm_opp_of_remove_table(data);
1166 }
1167
1168 static int _devm_of_add_table_indexed(struct device *dev, int index)
1169 {
1170         int ret;
1171
1172         ret = _of_add_table_indexed(dev, index);
1173         if (ret)
1174                 return ret;
1175
1176         return devm_add_action_or_reset(dev, devm_pm_opp_of_table_release, dev);
1177 }
1178
1179 /**
1180  * devm_pm_opp_of_add_table() - Initialize opp table from device tree
1181  * @dev:        device pointer used to lookup OPP table.
1182  *
1183  * Register the initial OPP table with the OPP library for given device.
1184  *
1185  * The opp_table structure will be freed after the device is destroyed.
1186  *
1187  * Return:
1188  * 0            On success OR
1189  *              Duplicate OPPs (both freq and volt are same) and opp->available
1190  * -EEXIST      Freq are same and volt are different OR
1191  *              Duplicate OPPs (both freq and volt are same) and !opp->available
1192  * -ENOMEM      Memory allocation failure
1193  * -ENODEV      when 'operating-points' property is not found or is invalid data
1194  *              in device node.
1195  * -ENODATA     when empty 'operating-points' property is found
1196  * -EINVAL      when invalid entries are found in opp-v2 table
1197  */
1198 int devm_pm_opp_of_add_table(struct device *dev)
1199 {
1200         return _devm_of_add_table_indexed(dev, 0);
1201 }
1202 EXPORT_SYMBOL_GPL(devm_pm_opp_of_add_table);
1203
1204 /**
1205  * dev_pm_opp_of_add_table() - Initialize opp table from device tree
1206  * @dev:        device pointer used to lookup OPP table.
1207  *
1208  * Register the initial OPP table with the OPP library for given device.
1209  *
1210  * Return:
1211  * 0            On success OR
1212  *              Duplicate OPPs (both freq and volt are same) and opp->available
1213  * -EEXIST      Freq are same and volt are different OR
1214  *              Duplicate OPPs (both freq and volt are same) and !opp->available
1215  * -ENOMEM      Memory allocation failure
1216  * -ENODEV      when 'operating-points' property is not found or is invalid data
1217  *              in device node.
1218  * -ENODATA     when empty 'operating-points' property is found
1219  * -EINVAL      when invalid entries are found in opp-v2 table
1220  */
1221 int dev_pm_opp_of_add_table(struct device *dev)
1222 {
1223         return _of_add_table_indexed(dev, 0);
1224 }
1225 EXPORT_SYMBOL_GPL(dev_pm_opp_of_add_table);
1226
1227 /**
1228  * dev_pm_opp_of_add_table_indexed() - Initialize indexed opp table from device tree
1229  * @dev:        device pointer used to lookup OPP table.
1230  * @index:      Index number.
1231  *
1232  * Register the initial OPP table with the OPP library for given device only
1233  * using the "operating-points-v2" property.
1234  *
1235  * Return: Refer to dev_pm_opp_of_add_table() for return values.
1236  */
1237 int dev_pm_opp_of_add_table_indexed(struct device *dev, int index)
1238 {
1239         return _of_add_table_indexed(dev, index);
1240 }
1241 EXPORT_SYMBOL_GPL(dev_pm_opp_of_add_table_indexed);
1242
1243 /**
1244  * devm_pm_opp_of_add_table_indexed() - Initialize indexed opp table from device tree
1245  * @dev:        device pointer used to lookup OPP table.
1246  * @index:      Index number.
1247  *
1248  * This is a resource-managed variant of dev_pm_opp_of_add_table_indexed().
1249  */
1250 int devm_pm_opp_of_add_table_indexed(struct device *dev, int index)
1251 {
1252         return _devm_of_add_table_indexed(dev, index);
1253 }
1254 EXPORT_SYMBOL_GPL(devm_pm_opp_of_add_table_indexed);
1255
1256 /* CPU device specific helpers */
1257
1258 /**
1259  * dev_pm_opp_of_cpumask_remove_table() - Removes OPP table for @cpumask
1260  * @cpumask:    cpumask for which OPP table needs to be removed
1261  *
1262  * This removes the OPP tables for CPUs present in the @cpumask.
1263  * This should be used only to remove static entries created from DT.
1264  */
1265 void dev_pm_opp_of_cpumask_remove_table(const struct cpumask *cpumask)
1266 {
1267         _dev_pm_opp_cpumask_remove_table(cpumask, -1);
1268 }
1269 EXPORT_SYMBOL_GPL(dev_pm_opp_of_cpumask_remove_table);
1270
1271 /**
1272  * dev_pm_opp_of_cpumask_add_table() - Adds OPP table for @cpumask
1273  * @cpumask:    cpumask for which OPP table needs to be added.
1274  *
1275  * This adds the OPP tables for CPUs present in the @cpumask.
1276  */
1277 int dev_pm_opp_of_cpumask_add_table(const struct cpumask *cpumask)
1278 {
1279         struct device *cpu_dev;
1280         int cpu, ret;
1281
1282         if (WARN_ON(cpumask_empty(cpumask)))
1283                 return -ENODEV;
1284
1285         for_each_cpu(cpu, cpumask) {
1286                 cpu_dev = get_cpu_device(cpu);
1287                 if (!cpu_dev) {
1288                         pr_err("%s: failed to get cpu%d device\n", __func__,
1289                                cpu);
1290                         ret = -ENODEV;
1291                         goto remove_table;
1292                 }
1293
1294                 ret = dev_pm_opp_of_add_table(cpu_dev);
1295                 if (ret) {
1296                         /*
1297                          * OPP may get registered dynamically, don't print error
1298                          * message here.
1299                          */
1300                         pr_debug("%s: couldn't find opp table for cpu:%d, %d\n",
1301                                  __func__, cpu, ret);
1302
1303                         goto remove_table;
1304                 }
1305         }
1306
1307         return 0;
1308
1309 remove_table:
1310         /* Free all other OPPs */
1311         _dev_pm_opp_cpumask_remove_table(cpumask, cpu);
1312
1313         return ret;
1314 }
1315 EXPORT_SYMBOL_GPL(dev_pm_opp_of_cpumask_add_table);
1316
1317 /*
1318  * Works only for OPP v2 bindings.
1319  *
1320  * Returns -ENOENT if operating-points-v2 bindings aren't supported.
1321  */
1322 /**
1323  * dev_pm_opp_of_get_sharing_cpus() - Get cpumask of CPUs sharing OPPs with
1324  *                                    @cpu_dev using operating-points-v2
1325  *                                    bindings.
1326  *
1327  * @cpu_dev:    CPU device for which we do this operation
1328  * @cpumask:    cpumask to update with information of sharing CPUs
1329  *
1330  * This updates the @cpumask with CPUs that are sharing OPPs with @cpu_dev.
1331  *
1332  * Returns -ENOENT if operating-points-v2 isn't present for @cpu_dev.
1333  */
1334 int dev_pm_opp_of_get_sharing_cpus(struct device *cpu_dev,
1335                                    struct cpumask *cpumask)
1336 {
1337         struct device_node *np, *tmp_np, *cpu_np;
1338         int cpu, ret = 0;
1339
1340         /* Get OPP descriptor node */
1341         np = dev_pm_opp_of_get_opp_desc_node(cpu_dev);
1342         if (!np) {
1343                 dev_dbg(cpu_dev, "%s: Couldn't find opp node.\n", __func__);
1344                 return -ENOENT;
1345         }
1346
1347         cpumask_set_cpu(cpu_dev->id, cpumask);
1348
1349         /* OPPs are shared ? */
1350         if (!of_property_read_bool(np, "opp-shared"))
1351                 goto put_cpu_node;
1352
1353         for_each_possible_cpu(cpu) {
1354                 if (cpu == cpu_dev->id)
1355                         continue;
1356
1357                 cpu_np = of_cpu_device_node_get(cpu);
1358                 if (!cpu_np) {
1359                         dev_err(cpu_dev, "%s: failed to get cpu%d node\n",
1360                                 __func__, cpu);
1361                         ret = -ENOENT;
1362                         goto put_cpu_node;
1363                 }
1364
1365                 /* Get OPP descriptor node */
1366                 tmp_np = _opp_of_get_opp_desc_node(cpu_np, 0);
1367                 of_node_put(cpu_np);
1368                 if (!tmp_np) {
1369                         pr_err("%pOF: Couldn't find opp node\n", cpu_np);
1370                         ret = -ENOENT;
1371                         goto put_cpu_node;
1372                 }
1373
1374                 /* CPUs are sharing opp node */
1375                 if (np == tmp_np)
1376                         cpumask_set_cpu(cpu, cpumask);
1377
1378                 of_node_put(tmp_np);
1379         }
1380
1381 put_cpu_node:
1382         of_node_put(np);
1383         return ret;
1384 }
1385 EXPORT_SYMBOL_GPL(dev_pm_opp_of_get_sharing_cpus);
1386
1387 /**
1388  * of_get_required_opp_performance_state() - Search for required OPP and return its performance state.
1389  * @np: Node that contains the "required-opps" property.
1390  * @index: Index of the phandle to parse.
1391  *
1392  * Returns the performance state of the OPP pointed out by the "required-opps"
1393  * property at @index in @np.
1394  *
1395  * Return: Zero or positive performance state on success, otherwise negative
1396  * value on errors.
1397  */
1398 int of_get_required_opp_performance_state(struct device_node *np, int index)
1399 {
1400         struct dev_pm_opp *opp;
1401         struct device_node *required_np;
1402         struct opp_table *opp_table;
1403         int pstate = -EINVAL;
1404
1405         required_np = of_parse_required_opp(np, index);
1406         if (!required_np)
1407                 return -ENODEV;
1408
1409         opp_table = _find_table_of_opp_np(required_np);
1410         if (IS_ERR(opp_table)) {
1411                 pr_err("%s: Failed to find required OPP table %pOF: %ld\n",
1412                        __func__, np, PTR_ERR(opp_table));
1413                 goto put_required_np;
1414         }
1415
1416         /* The OPP tables must belong to a genpd */
1417         if (unlikely(!opp_table->is_genpd)) {
1418                 pr_err("%s: Performance state is only valid for genpds.\n", __func__);
1419                 goto put_required_np;
1420         }
1421
1422         opp = _find_opp_of_np(opp_table, required_np);
1423         if (opp) {
1424                 if (opp->level == OPP_LEVEL_UNSET) {
1425                         pr_err("%s: OPP levels aren't available for %pOF\n",
1426                                __func__, np);
1427                 } else {
1428                         pstate = opp->level;
1429                 }
1430                 dev_pm_opp_put(opp);
1431
1432         }
1433
1434         dev_pm_opp_put_opp_table(opp_table);
1435
1436 put_required_np:
1437         of_node_put(required_np);
1438
1439         return pstate;
1440 }
1441 EXPORT_SYMBOL_GPL(of_get_required_opp_performance_state);
1442
1443 /**
1444  * dev_pm_opp_get_of_node() - Gets the DT node corresponding to an opp
1445  * @opp:        opp for which DT node has to be returned for
1446  *
1447  * Return: DT node corresponding to the opp, else 0 on success.
1448  *
1449  * The caller needs to put the node with of_node_put() after using it.
1450  */
1451 struct device_node *dev_pm_opp_get_of_node(struct dev_pm_opp *opp)
1452 {
1453         if (IS_ERR_OR_NULL(opp)) {
1454                 pr_err("%s: Invalid parameters\n", __func__);
1455                 return NULL;
1456         }
1457
1458         return of_node_get(opp->np);
1459 }
1460 EXPORT_SYMBOL_GPL(dev_pm_opp_get_of_node);
1461
1462 /*
1463  * Callback function provided to the Energy Model framework upon registration.
1464  * It provides the power used by @dev at @kHz if it is the frequency of an
1465  * existing OPP, or at the frequency of the first OPP above @kHz otherwise
1466  * (see dev_pm_opp_find_freq_ceil()). This function updates @kHz to the ceiled
1467  * frequency and @uW to the associated power.
1468  *
1469  * Returns 0 on success or a proper -EINVAL value in case of error.
1470  */
1471 static int __maybe_unused
1472 _get_dt_power(struct device *dev, unsigned long *uW, unsigned long *kHz)
1473 {
1474         struct dev_pm_opp *opp;
1475         unsigned long opp_freq, opp_power;
1476
1477         /* Find the right frequency and related OPP */
1478         opp_freq = *kHz * 1000;
1479         opp = dev_pm_opp_find_freq_ceil(dev, &opp_freq);
1480         if (IS_ERR(opp))
1481                 return -EINVAL;
1482
1483         opp_power = dev_pm_opp_get_power(opp);
1484         dev_pm_opp_put(opp);
1485         if (!opp_power)
1486                 return -EINVAL;
1487
1488         *kHz = opp_freq / 1000;
1489         *uW = opp_power;
1490
1491         return 0;
1492 }
1493
1494 /*
1495  * Callback function provided to the Energy Model framework upon registration.
1496  * This computes the power estimated by @dev at @kHz if it is the frequency
1497  * of an existing OPP, or at the frequency of the first OPP above @kHz otherwise
1498  * (see dev_pm_opp_find_freq_ceil()). This function updates @kHz to the ceiled
1499  * frequency and @uW to the associated power. The power is estimated as
1500  * P = C * V^2 * f with C being the device's capacitance and V and f
1501  * respectively the voltage and frequency of the OPP.
1502  *
1503  * Returns -EINVAL if the power calculation failed because of missing
1504  * parameters, 0 otherwise.
1505  */
1506 static int __maybe_unused _get_power(struct device *dev, unsigned long *uW,
1507                                      unsigned long *kHz)
1508 {
1509         struct dev_pm_opp *opp;
1510         struct device_node *np;
1511         unsigned long mV, Hz;
1512         u32 cap;
1513         u64 tmp;
1514         int ret;
1515
1516         np = of_node_get(dev->of_node);
1517         if (!np)
1518                 return -EINVAL;
1519
1520         ret = of_property_read_u32(np, "dynamic-power-coefficient", &cap);
1521         of_node_put(np);
1522         if (ret)
1523                 return -EINVAL;
1524
1525         Hz = *kHz * 1000;
1526         opp = dev_pm_opp_find_freq_ceil(dev, &Hz);
1527         if (IS_ERR(opp))
1528                 return -EINVAL;
1529
1530         mV = dev_pm_opp_get_voltage(opp) / 1000;
1531         dev_pm_opp_put(opp);
1532         if (!mV)
1533                 return -EINVAL;
1534
1535         tmp = (u64)cap * mV * mV * (Hz / 1000000);
1536         /* Provide power in micro-Watts */
1537         do_div(tmp, 1000000);
1538
1539         *uW = (unsigned long)tmp;
1540         *kHz = Hz / 1000;
1541
1542         return 0;
1543 }
1544
1545 static bool _of_has_opp_microwatt_property(struct device *dev)
1546 {
1547         unsigned long power, freq = 0;
1548         struct dev_pm_opp *opp;
1549
1550         /* Check if at least one OPP has needed property */
1551         opp = dev_pm_opp_find_freq_ceil(dev, &freq);
1552         if (IS_ERR(opp))
1553                 return false;
1554
1555         power = dev_pm_opp_get_power(opp);
1556         dev_pm_opp_put(opp);
1557         if (!power)
1558                 return false;
1559
1560         return true;
1561 }
1562
1563 /**
1564  * dev_pm_opp_of_register_em() - Attempt to register an Energy Model
1565  * @dev         : Device for which an Energy Model has to be registered
1566  * @cpus        : CPUs for which an Energy Model has to be registered. For
1567  *              other type of devices it should be set to NULL.
1568  *
1569  * This checks whether the "dynamic-power-coefficient" devicetree property has
1570  * been specified, and tries to register an Energy Model with it if it has.
1571  * Having this property means the voltages are known for OPPs and the EM
1572  * might be calculated.
1573  */
1574 int dev_pm_opp_of_register_em(struct device *dev, struct cpumask *cpus)
1575 {
1576         struct em_data_callback em_cb;
1577         struct device_node *np;
1578         int ret, nr_opp;
1579         u32 cap;
1580
1581         if (IS_ERR_OR_NULL(dev)) {
1582                 ret = -EINVAL;
1583                 goto failed;
1584         }
1585
1586         nr_opp = dev_pm_opp_get_opp_count(dev);
1587         if (nr_opp <= 0) {
1588                 ret = -EINVAL;
1589                 goto failed;
1590         }
1591
1592         /* First, try to find more precised Energy Model in DT */
1593         if (_of_has_opp_microwatt_property(dev)) {
1594                 EM_SET_ACTIVE_POWER_CB(em_cb, _get_dt_power);
1595                 goto register_em;
1596         }
1597
1598         np = of_node_get(dev->of_node);
1599         if (!np) {
1600                 ret = -EINVAL;
1601                 goto failed;
1602         }
1603
1604         /*
1605          * Register an EM only if the 'dynamic-power-coefficient' property is
1606          * set in devicetree. It is assumed the voltage values are known if that
1607          * property is set since it is useless otherwise. If voltages are not
1608          * known, just let the EM registration fail with an error to alert the
1609          * user about the inconsistent configuration.
1610          */
1611         ret = of_property_read_u32(np, "dynamic-power-coefficient", &cap);
1612         of_node_put(np);
1613         if (ret || !cap) {
1614                 dev_dbg(dev, "Couldn't find proper 'dynamic-power-coefficient' in DT\n");
1615                 ret = -EINVAL;
1616                 goto failed;
1617         }
1618
1619         EM_SET_ACTIVE_POWER_CB(em_cb, _get_power);
1620
1621 register_em:
1622         ret = em_dev_register_perf_domain(dev, nr_opp, &em_cb, cpus, true);
1623         if (ret)
1624                 goto failed;
1625
1626         return 0;
1627
1628 failed:
1629         dev_dbg(dev, "Couldn't register Energy Model %d\n", ret);
1630         return ret;
1631 }
1632 EXPORT_SYMBOL_GPL(dev_pm_opp_of_register_em);