ARM: tegra: dvfs: Add dvfs thermal dependency
[linux-3.10.git] / arch / arm / mach-tegra / dvfs.c
1 /*
2  *
3  * Copyright (C) 2010 Google, Inc.
4  *
5  * Author:
6  *      Colin Cross <ccross@google.com>
7  *
8  * Copyright (C) 2010-2013 NVIDIA CORPORATION. All rights reserved.
9  *
10  * This software is licensed under the terms of the GNU General Public
11  * License version 2, as published by the Free Software Foundation, and
12  * may be copied, distributed, and modified under those terms.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  */
20
21 #include <linux/kernel.h>
22 #include <linux/clk.h>
23 #include <linux/clkdev.h>
24 #include <linux/debugfs.h>
25 #include <linux/init.h>
26 #include <linux/list.h>
27 #include <linux/list_sort.h>
28 #include <linux/module.h>
29 #include <linux/regulator/consumer.h>
30 #include <linux/seq_file.h>
31 #include <linux/slab.h>
32 #include <linux/suspend.h>
33 #include <linux/delay.h>
34 #include <linux/clk/tegra.h>
35 #include <linux/reboot.h>
36 #include <linux/clk/tegra.h>
37 #include <linux/tegra-soc.h>
38
39 #include "board.h"
40 #include "clock.h"
41 #include "dvfs.h"
42
43 #define DVFS_RAIL_STATS_BIN     12500
44
45 struct dvfs_rail *tegra_cpu_rail;
46 struct dvfs_rail *tegra_core_rail;
47 struct dvfs_rail *tegra_gpu_rail;
48
49 static LIST_HEAD(dvfs_rail_list);
50 static DEFINE_MUTEX(dvfs_lock);
51 static DEFINE_MUTEX(rail_disable_lock);
52
53 static int dvfs_rail_update(struct dvfs_rail *rail);
54
55 static inline int tegra_dvfs_rail_get_disable_level(struct dvfs_rail *rail)
56 {
57         return rail->disable_millivolts ? : rail->nominal_millivolts;
58 }
59
60 static inline int tegra_dvfs_rail_get_suspend_level(struct dvfs_rail *rail)
61 {
62         return rail->suspend_millivolts ? : rail->nominal_millivolts;
63 }
64
65 void tegra_dvfs_add_relationships(struct dvfs_relationship *rels, int n)
66 {
67         int i;
68         struct dvfs_relationship *rel;
69
70         mutex_lock(&dvfs_lock);
71
72         for (i = 0; i < n; i++) {
73                 rel = &rels[i];
74                 list_add_tail(&rel->from_node, &rel->to->relationships_from);
75                 list_add_tail(&rel->to_node, &rel->from->relationships_to);
76         }
77
78         mutex_unlock(&dvfs_lock);
79 }
80
81 /* Make sure there is a matching cooling device for thermal limit profile. */
82 static void dvfs_validate_cdevs(struct dvfs_rail *rail)
83 {
84         if (!rail->therm_mv_caps != !rail->therm_mv_caps_num) {
85                 rail->therm_mv_caps_num = 0;
86                 rail->therm_mv_caps = NULL;
87                 WARN(1, "%s: not matching thermal caps/num\n", rail->reg_id);
88         }
89
90         if (rail->therm_mv_caps && !rail->vmax_cdev)
91                 WARN(1, "%s: missing vmax cooling device\n", rail->reg_id);
92
93         if (!rail->therm_mv_floors != !rail->therm_mv_floors_num) {
94                 rail->therm_mv_floors_num = 0;
95                 rail->therm_mv_floors = NULL;
96                 WARN(1, "%s: not matching thermal floors/num\n", rail->reg_id);
97         }
98
99         if (rail->therm_mv_floors && !rail->vmin_cdev)
100                 WARN(1, "%s: missing vmin cooling device\n", rail->reg_id);
101
102         /* Limit override range to maximum floor */
103         if (rail->therm_mv_floors)
104                 rail->min_override_millivolts = rail->therm_mv_floors[0];
105
106         /* Only GPU thermal dvfs is supported */
107         if (rail->vts_cdev && (rail != tegra_gpu_rail)) {
108                 rail->vts_cdev = NULL;
109                 WARN(1, "%s: thermal dvfs is not supported\n", rail->reg_id);
110         }
111 }
112
113 int tegra_dvfs_init_rails(struct dvfs_rail *rails[], int n)
114 {
115         int i, mv;
116
117         mutex_lock(&dvfs_lock);
118
119         for (i = 0; i < n; i++) {
120                 INIT_LIST_HEAD(&rails[i]->dvfs);
121                 INIT_LIST_HEAD(&rails[i]->relationships_from);
122                 INIT_LIST_HEAD(&rails[i]->relationships_to);
123
124                 mv = rails[i]->nominal_millivolts;
125                 if (rails[i]->boot_millivolts > mv)
126                         WARN(1, "%s: boot voltage %d above nominal %d\n",
127                              rails[i]->reg_id, rails[i]->boot_millivolts, mv);
128                 if (rails[i]->disable_millivolts > mv)
129                         rails[i]->disable_millivolts = mv;
130                 if (rails[i]->suspend_millivolts > mv)
131                         rails[i]->suspend_millivolts = mv;
132
133                 mv = tegra_dvfs_rail_get_boot_level(rails[i]);
134                 rails[i]->millivolts = mv;
135                 rails[i]->new_millivolts = mv;
136                 if (!rails[i]->step)
137                         rails[i]->step = rails[i]->max_millivolts;
138                 if (!rails[i]->step_up)
139                         rails[i]->step_up = rails[i]->step;
140
141                 list_add_tail(&rails[i]->node, &dvfs_rail_list);
142
143                 if (!strcmp("vdd_cpu", rails[i]->reg_id))
144                         tegra_cpu_rail = rails[i];
145                 else if (!strcmp("vdd_gpu", rails[i]->reg_id))
146                         tegra_gpu_rail = rails[i];
147                 else if (!strcmp("vdd_core", rails[i]->reg_id))
148                         tegra_core_rail = rails[i];
149
150                 dvfs_validate_cdevs(rails[i]);
151         }
152
153         mutex_unlock(&dvfs_lock);
154
155         return 0;
156 };
157
158 static int dvfs_solve_relationship(struct dvfs_relationship *rel)
159 {
160         return rel->solve(rel->from, rel->to);
161 }
162
163 /* rail statistic - called during rail init, or under dfs_lock, or with
164    CPU0 only on-line, and interrupts disabled */
165 static void dvfs_rail_stats_init(struct dvfs_rail *rail, int millivolts)
166 {
167         int dvfs_rail_stats_range;
168
169         if (!rail->stats.bin_uV)
170                 rail->stats.bin_uV = DVFS_RAIL_STATS_BIN;
171
172         dvfs_rail_stats_range =
173                 (DVFS_RAIL_STATS_TOP_BIN - 1) * rail->stats.bin_uV / 1000;
174
175         rail->stats.last_update = ktime_get();
176         if (millivolts >= rail->min_millivolts) {
177                 int i = 1 + (2 * (millivolts - rail->min_millivolts) * 1000 +
178                              rail->stats.bin_uV) / (2 * rail->stats.bin_uV);
179                 rail->stats.last_index = min(i, DVFS_RAIL_STATS_TOP_BIN);
180         }
181
182         if (rail->max_millivolts >
183             rail->min_millivolts + dvfs_rail_stats_range)
184                 pr_warn("tegra_dvfs: %s: stats above %d mV will be squashed\n",
185                         rail->reg_id,
186                         rail->min_millivolts + dvfs_rail_stats_range);
187 }
188
189 static void dvfs_rail_stats_update(
190         struct dvfs_rail *rail, int millivolts, ktime_t now)
191 {
192         rail->stats.time_at_mv[rail->stats.last_index] = ktime_add(
193                 rail->stats.time_at_mv[rail->stats.last_index], ktime_sub(
194                         now, rail->stats.last_update));
195         rail->stats.last_update = now;
196
197         if (rail->stats.off)
198                 return;
199
200         if (millivolts >= rail->min_millivolts) {
201                 int i = 1 + (2 * (millivolts - rail->min_millivolts) * 1000 +
202                              rail->stats.bin_uV) / (2 * rail->stats.bin_uV);
203                 rail->stats.last_index = min(i, DVFS_RAIL_STATS_TOP_BIN);
204         } else if (millivolts == 0)
205                         rail->stats.last_index = 0;
206 }
207
208 static void dvfs_rail_stats_pause(struct dvfs_rail *rail,
209                                   ktime_t delta, bool on)
210 {
211         int i = on ? rail->stats.last_index : 0;
212         rail->stats.time_at_mv[i] = ktime_add(rail->stats.time_at_mv[i], delta);
213 }
214
215 void tegra_dvfs_rail_off(struct dvfs_rail *rail, ktime_t now)
216 {
217         if (rail) {
218                 dvfs_rail_stats_update(rail, 0, now);
219                 rail->stats.off = true;
220         }
221 }
222
223 void tegra_dvfs_rail_on(struct dvfs_rail *rail, ktime_t now)
224 {
225         if (rail) {
226                 rail->stats.off = false;
227                 dvfs_rail_stats_update(rail, rail->millivolts, now);
228         }
229 }
230
231 void tegra_dvfs_rail_pause(struct dvfs_rail *rail, ktime_t delta, bool on)
232 {
233         if (rail)
234                 dvfs_rail_stats_pause(rail, delta, on);
235 }
236
237 static int dvfs_rail_set_voltage_reg(struct dvfs_rail *rail, int millivolts)
238 {
239         int ret;
240
241         /*
242          * safely return success for low voltage requests on fixed regulator
243          * (higher requests will go through and fail, as they should)
244          */
245         if (rail->fixed_millivolts && (millivolts <= rail->fixed_millivolts))
246                 return 0;
247
248         rail->updating = true;
249         rail->reg_max_millivolts = rail->reg_max_millivolts ==
250                 rail->max_millivolts ?
251                 rail->max_millivolts + 1 : rail->max_millivolts;
252         ret = regulator_set_voltage(rail->reg,
253                 millivolts * 1000,
254                 rail->reg_max_millivolts * 1000);
255         rail->updating = false;
256
257         return ret;
258 }
259
260 /* Sets the voltage on a dvfs rail to a specific value, and updates any
261  * rails that depend on this rail. */
262 static int dvfs_rail_set_voltage(struct dvfs_rail *rail, int millivolts)
263 {
264         int ret = 0;
265         struct dvfs_relationship *rel;
266         int step, offset;
267         int i;
268         int steps;
269         bool jmp_to_zero;
270
271         if (!rail->reg) {
272                 if (millivolts == rail->millivolts)
273                         return 0;
274                 else
275                         return -EINVAL;
276         }
277
278         if (millivolts > rail->millivolts) {
279                 step = rail->step_up;
280                 offset = step;
281         } else {
282                 step = rail->step;
283                 offset = -step;
284         }
285
286         /*
287          * DFLL adjusts rail voltage automatically, but not exactly to the
288          * expected level - update stats, anyway.
289          */
290         if (rail->dfll_mode) {
291                 rail->millivolts = rail->new_millivolts = millivolts;
292                 dvfs_rail_stats_update(rail, millivolts, ktime_get());
293                 return 0;
294         }
295
296         if (rail->disabled)
297                 return 0;
298
299         rail->resolving_to = true;
300         jmp_to_zero = rail->jmp_to_zero &&
301                         ((millivolts == 0) || (rail->millivolts == 0));
302         steps = jmp_to_zero ? 1 :
303                 DIV_ROUND_UP(abs(millivolts - rail->millivolts), step);
304
305         for (i = 0; i < steps; i++) {
306                 if (!jmp_to_zero &&
307                     (abs(millivolts - rail->millivolts) > step))
308                         rail->new_millivolts = rail->millivolts + offset;
309                 else
310                         rail->new_millivolts = millivolts;
311
312                 /* Before changing the voltage, tell each rail that depends
313                  * on this rail that the voltage will change.
314                  * This rail will be the "from" rail in the relationship,
315                  * the rail that depends on this rail will be the "to" rail.
316                  * from->millivolts will be the old voltage
317                  * from->new_millivolts will be the new voltage */
318                 list_for_each_entry(rel, &rail->relationships_to, to_node) {
319                         ret = dvfs_rail_update(rel->to);
320                         if (ret)
321                                 goto out;
322                 }
323
324                 ret = dvfs_rail_set_voltage_reg(rail, rail->new_millivolts);
325                 if (ret) {
326                         pr_err("Failed to set dvfs regulator %s\n", rail->reg_id);
327                         goto out;
328                 }
329
330                 rail->millivolts = rail->new_millivolts;
331                 dvfs_rail_stats_update(rail, rail->millivolts, ktime_get());
332
333                 /* After changing the voltage, tell each rail that depends
334                  * on this rail that the voltage has changed.
335                  * from->millivolts and from->new_millivolts will be the
336                  * new voltage */
337                 list_for_each_entry(rel, &rail->relationships_to, to_node) {
338                         ret = dvfs_rail_update(rel->to);
339                         if (ret)
340                                 goto out;
341                 }
342         }
343
344         if (unlikely(rail->millivolts != millivolts)) {
345                 pr_err("%s: rail didn't reach target %d in %d steps (%d)\n",
346                         __func__, millivolts, steps, rail->millivolts);
347                 ret = -EINVAL;
348         }
349
350 out:
351         rail->resolving_to = false;
352         return ret;
353 }
354
355 /* Determine the minimum valid voltage for a rail, taking into account
356  * the dvfs clocks and any rails that this rail depends on.  Calls
357  * dvfs_rail_set_voltage with the new voltage, which will call
358  * dvfs_rail_update on any rails that depend on this rail. */
359 static inline int dvfs_rail_apply_limits(struct dvfs_rail *rail, int millivolts)
360 {
361         int min_mv = rail->min_millivolts;
362
363         if (rail->therm_mv_floors) {
364                 int i = rail->therm_floor_idx;
365                 if (i < rail->therm_mv_floors_num)
366                         min_mv = rail->therm_mv_floors[i];
367         }
368
369         if (rail->override_millivolts) {
370                 millivolts = rail->override_millivolts;
371         } else {
372                 /* apply offset and clip up to pll mode fixed mv */
373                 millivolts += rail->dbg_mv_offs;
374                 if (!rail->dfll_mode && rail->fixed_millivolts &&
375                     (millivolts < rail->fixed_millivolts))
376                         millivolts = rail->fixed_millivolts;
377         }
378
379         if (millivolts < min_mv)
380                 millivolts = min_mv;
381
382         return millivolts;
383 }
384
385 static int dvfs_rail_update(struct dvfs_rail *rail)
386 {
387         int millivolts = 0;
388         struct dvfs *d;
389         struct dvfs_relationship *rel;
390         int ret = 0;
391         int steps;
392
393         /* if dvfs is suspended, return and handle it during resume */
394         if (rail->suspended)
395                 return 0;
396
397         /* if regulators are not connected yet, return and handle it later */
398         if (!rail->reg)
399                 return 0;
400
401         /* if no clock has requested voltage since boot, defer update */
402         if (!rail->rate_set)
403                 return 0;
404
405         /* if rail update is entered while resolving circular dependencies,
406            abort recursion */
407         if (rail->resolving_to)
408                 return 0;
409
410         /* Find the maximum voltage requested by any clock */
411         list_for_each_entry(d, &rail->dvfs, reg_node)
412                 millivolts = max(d->cur_millivolts, millivolts);
413
414         /* Apply offset and min/max limits if any clock is requesting voltage */
415         if (millivolts)
416                 millivolts = dvfs_rail_apply_limits(rail, millivolts);
417         /* Keep current voltage if regulator is to be disabled via explicitly */
418         else if (rail->in_band_pm)
419                 return 0;
420         /* Keep current voltage if regulator must not be disabled at run time */
421         else if (!rail->jmp_to_zero) {
422                 WARN(1, "%s cannot be turned off by dvfs\n");
423                 return 0;
424         }
425         /* else: fall thru if regulator is turned off by side band signaling */
426
427         /* retry update if limited by from-relationship to account for
428            circular dependencies */
429         steps = DIV_ROUND_UP(abs(millivolts - rail->millivolts), rail->step);
430         for (; steps >= 0; steps--) {
431                 rail->new_millivolts = millivolts;
432
433                 /* Check any rails that this rail depends on */
434                 list_for_each_entry(rel, &rail->relationships_from, from_node)
435                         rail->new_millivolts = dvfs_solve_relationship(rel);
436
437                 if (rail->new_millivolts == rail->millivolts)
438                         break;
439
440                 ret = dvfs_rail_set_voltage(rail, rail->new_millivolts);
441         }
442
443         return ret;
444 }
445
446 static struct regulator *get_fixed_regulator(struct dvfs_rail *rail)
447 {
448         struct regulator *reg;
449         char reg_id[80];
450         struct dvfs *d;
451         int v, i;
452         unsigned long dfll_boost;
453
454         strcpy(reg_id, rail->reg_id);
455         strcat(reg_id, "_fixed");
456         reg = regulator_get(NULL, reg_id);
457         if (IS_ERR(reg))
458                 return reg;
459
460         v = regulator_get_voltage(reg) / 1000;
461         if ((v < rail->min_millivolts) || (v > rail->nominal_millivolts) ||
462             (rail->therm_mv_floors && v < rail->therm_mv_floors[0])) {
463                 pr_err("tegra_dvfs: ivalid fixed %s voltage %d\n",
464                        rail->reg_id, v);
465                 return ERR_PTR(-EINVAL);
466         }
467
468         /*
469          * Only fixed at nominal voltage vdd_core regulator is allowed, same
470          * is true for cpu rail if dfll mode is not supported at all. No thermal
471          * capping can be implemented in this case.
472          */
473         if (!IS_ENABLED(CONFIG_ARCH_TEGRA_HAS_CL_DVFS) ||
474             (rail != tegra_cpu_rail)) {
475                 if (v != rail->nominal_millivolts) {
476                         pr_err("tegra_dvfs: %s fixed below nominal at %d\n",
477                                rail->reg_id, v);
478                         return ERR_PTR(-EINVAL);
479                 }
480                 if (rail->therm_mv_caps) {
481                         pr_err("tegra_dvfs: cannot fix %s with thermal caps\n",
482                                rail->reg_id);
483                         return ERR_PTR(-ENOSYS);
484                 }
485                 return reg;
486         }
487
488         /*
489          * If dfll mode is supported, fixed vdd_cpu regulator may be below
490          * nominal in pll mode - maximum cpu rate in pll mode is limited
491          * respectively. Regulator is required to allow automatic scaling
492          * in dfll mode.
493          *
494          * FIXME: platform data to explicitly identify such "hybrid" regulator?
495          */
496         d = list_first_entry(&rail->dvfs, struct dvfs, reg_node);
497         for (i = 0; i < d->num_freqs; i++) {
498                 if (d->millivolts[i] > v)
499                         break;
500         }
501
502         if (!i) {
503                 pr_err("tegra_dvfs: %s fixed at %d: too low for min rate\n",
504                        rail->reg_id, v);
505                 return ERR_PTR(-EINVAL);
506         }
507
508         dfll_boost = (d->freqs[d->num_freqs - 1] - d->freqs[i - 1]);
509         if (d->dfll_data.max_rate_boost < dfll_boost)
510                 d->dfll_data.max_rate_boost = dfll_boost;
511
512         rail->fixed_millivolts = v;
513         return reg;
514 }
515
516 static int dvfs_rail_connect_to_regulator(struct dvfs_rail *rail)
517 {
518         struct regulator *reg;
519         int v;
520
521         if (!rail->reg) {
522                 reg = regulator_get(NULL, rail->reg_id);
523                 if (IS_ERR(reg)) {
524                         reg = get_fixed_regulator(rail);
525                         if (IS_ERR(reg)) {
526                                 pr_err("tegra_dvfs: failed to connect %s rail\n",
527                                        rail->reg_id);
528                                 return PTR_ERR(reg);
529                         }
530                 }
531                 rail->reg = reg;
532         }
533
534         v = regulator_enable(rail->reg);
535         if (v < 0) {
536                 pr_err("tegra_dvfs: failed on enabling regulator %s\n, err %d",
537                         rail->reg_id, v);
538                 return v;
539         }
540
541         v = regulator_get_voltage(rail->reg);
542         if (v < 0) {
543                 pr_err("tegra_dvfs: failed initial get %s voltage\n",
544                        rail->reg_id);
545                 return v;
546         }
547         rail->millivolts = v / 1000;
548         rail->new_millivolts = rail->millivolts;
549         dvfs_rail_stats_init(rail, rail->millivolts);
550
551         if (rail->boot_millivolts &&
552             (rail->boot_millivolts != rail->millivolts)) {
553                 WARN(1, "%s boot voltage %d does not match expected %d\n",
554                      rail->reg_id, rail->millivolts, rail->boot_millivolts);
555                 rail->boot_millivolts = rail->millivolts;
556         }
557         return 0;
558 }
559
560 static inline unsigned long *dvfs_get_freqs(struct dvfs *d)
561 {
562         return d->alt_freqs ? : &d->freqs[0];
563 }
564
565 static inline const int *dvfs_get_millivolts(struct dvfs *d, unsigned long rate)
566 {
567         if (tegra_dvfs_is_dfll_scale(d, rate))
568                 return d->dfll_millivolts;
569
570         return tegra_dvfs_get_millivolts_pll(d);
571 }
572
573 static int
574 __tegra_dvfs_set_rate(struct dvfs *d, unsigned long rate)
575 {
576         int i = 0;
577         int ret, mv, detach_mv;
578         unsigned long *freqs = dvfs_get_freqs(d);
579         const int *millivolts = dvfs_get_millivolts(d, rate);
580
581         if (freqs == NULL || millivolts == NULL)
582                 return -ENODEV;
583
584         /* On entry to dfll range limit 1st step to range bottom (full ramp of
585            voltage/rate is completed automatically in dfll mode) */
586         if (tegra_dvfs_is_dfll_range_entry(d, rate))
587                 rate = d->dfll_data.use_dfll_rate_min;
588
589         if (rate > freqs[d->num_freqs - 1]) {
590                 pr_warn("tegra_dvfs: rate %lu too high for dvfs on %s\n", rate,
591                         d->clk_name);
592                 return -EINVAL;
593         }
594
595         if (rate == 0) {
596                 d->cur_millivolts = 0;
597         } else {
598                 while (i < d->num_freqs && rate > freqs[i])
599                         i++;
600
601                 if ((d->max_millivolts) &&
602                     (millivolts[i] > d->max_millivolts)) {
603                         pr_warn("tegra_dvfs: voltage %d too high for dvfs on"
604                                 " %s\n", millivolts[i], d->clk_name);
605                         return -EINVAL;
606                 }
607
608                 mv = millivolts[i];
609                 detach_mv = tegra_dvfs_rail_get_boot_level(d->dvfs_rail);
610                 if (!d->dvfs_rail->reg && (mv > detach_mv)) {
611                         pr_warn("%s: %s: voltage %d above boot limit %d\n",
612                                 __func__, d->clk_name, mv, detach_mv);
613                         return -EINVAL;
614                 }
615
616                 detach_mv = tegra_dvfs_rail_get_disable_level(d->dvfs_rail);
617                 if (d->dvfs_rail->disabled && (mv > detach_mv)) {
618                         pr_warn("%s: %s: voltage %d above disable limit %d\n",
619                                 __func__, d->clk_name, mv, detach_mv);
620                         return -EINVAL;
621                 }
622
623                 detach_mv = tegra_dvfs_rail_get_suspend_level(d->dvfs_rail);
624                 if (d->dvfs_rail->suspended && (mv > detach_mv)) {
625                         pr_warn("%s: %s: voltage %d above disable limit %d\n",
626                                 __func__, d->clk_name, mv, detach_mv);
627                         return -EINVAL;
628                 }
629                 d->cur_millivolts = millivolts[i];
630         }
631
632         d->cur_rate = rate;
633
634         d->dvfs_rail->rate_set = true;
635         ret = dvfs_rail_update(d->dvfs_rail);
636         if (ret)
637                 pr_err("Failed to set regulator %s for clock %s to %d mV\n",
638                         d->dvfs_rail->reg_id, d->clk_name, d->cur_millivolts);
639
640         return ret;
641 }
642
643 int tegra_dvfs_alt_freqs_set(struct dvfs *d, unsigned long *alt_freqs)
644 {
645         int ret = 0;
646
647         mutex_lock(&dvfs_lock);
648
649         if (d->alt_freqs != alt_freqs) {
650                 d->alt_freqs = alt_freqs;
651                 ret = __tegra_dvfs_set_rate(d, d->cur_rate);
652         }
653
654         mutex_unlock(&dvfs_lock);
655         return ret;
656 }
657
658 static int predict_millivolts(struct clk *c, const int *millivolts,
659                               unsigned long rate)
660 {
661         int i;
662
663         if (!millivolts)
664                 return -ENODEV;
665         /*
666          * Predicted voltage can not be used across the switch to alternative
667          * frequency limits. For now, just fail the call for clock that has
668          * alternative limits initialized.
669          */
670         if (c->dvfs->alt_freqs)
671                 return -ENOSYS;
672
673         for (i = 0; i < c->dvfs->num_freqs; i++) {
674                 if (rate <= c->dvfs->freqs[i])
675                         break;
676         }
677
678         if (i == c->dvfs->num_freqs)
679                 return -EINVAL;
680
681         return millivolts[i];
682 }
683
684 int tegra_dvfs_predict_millivolts(struct clk *c, unsigned long rate)
685 {
686         const int *millivolts;
687
688         if (!rate || !c->dvfs)
689                 return 0;
690
691         millivolts = dvfs_get_millivolts(c->dvfs, rate);
692         return predict_millivolts(c, millivolts, rate);
693 }
694
695 int tegra_dvfs_predict_millivolts_pll(struct clk *c, unsigned long rate)
696 {
697         const int *millivolts;
698
699         if (!rate || !c->dvfs)
700                 return 0;
701
702         millivolts = tegra_dvfs_get_millivolts_pll(c->dvfs);
703         return predict_millivolts(c, millivolts, rate);
704 }
705
706 int tegra_dvfs_predict_millivolts_dfll(struct clk *c, unsigned long rate)
707 {
708         const int *millivolts;
709
710         if (!rate || !c->dvfs)
711                 return 0;
712
713         millivolts = c->dvfs->dfll_millivolts;
714         return predict_millivolts(c, millivolts, rate);
715 }
716
717 const int *tegra_dvfs_get_millivolts_pll(struct dvfs *d)
718 {
719         if (d->therm_dvfs) {
720                 int therm_idx = d->dvfs_rail->therm_scale_idx;
721                 return d->millivolts + therm_idx * MAX_DVFS_FREQS;
722         }
723         return d->millivolts;
724 }
725
726 int tegra_dvfs_set_rate(struct clk *c, unsigned long rate)
727 {
728         int ret;
729
730         if (!c->dvfs)
731                 return -EINVAL;
732
733         mutex_lock(&dvfs_lock);
734         ret = __tegra_dvfs_set_rate(c->dvfs, rate);
735         mutex_unlock(&dvfs_lock);
736
737         return ret;
738 }
739 EXPORT_SYMBOL(tegra_dvfs_set_rate);
740
741 int tegra_dvfs_get_freqs(struct clk *c, unsigned long **freqs, int *num_freqs)
742 {
743         if (!c->dvfs)
744                 return -ENOSYS;
745
746         if (c->dvfs->alt_freqs)
747                 return -ENOSYS;
748
749         *num_freqs = c->dvfs->num_freqs;
750         *freqs = c->dvfs->freqs;
751
752         return 0;
753 }
754 EXPORT_SYMBOL(tegra_dvfs_get_freqs);
755
756 #ifdef CONFIG_TEGRA_VDD_CORE_OVERRIDE
757 static DEFINE_MUTEX(rail_override_lock);
758
759 static int dvfs_override_core_voltage(int override_mv)
760 {
761         int ret, floor, ceiling;
762         struct dvfs_rail *rail = tegra_core_rail;
763
764         if (!rail)
765                 return -ENOENT;
766
767         if (rail->fixed_millivolts)
768                 return -ENOSYS;
769
770         floor = rail->min_override_millivolts;
771         ceiling = rail->nominal_millivolts;
772         if (override_mv && ((override_mv < floor) || (override_mv > ceiling))) {
773                 pr_err("%s: override level %d outside the range [%d...%d]\n",
774                        __func__, override_mv, floor, ceiling);
775                 return -EINVAL;
776         }
777
778         mutex_lock(&rail_override_lock);
779
780         if (override_mv == rail->override_millivolts) {
781                 ret = 0;
782                 goto out;
783         }
784
785         if (override_mv) {
786                 ret = tegra_dvfs_core_cap_level_apply(override_mv);
787                 if (ret) {
788                         pr_err("%s: failed to set cap for override level %d\n",
789                                __func__, override_mv);
790                         goto out;
791                 }
792         }
793
794         mutex_lock(&dvfs_lock);
795         if (rail->disabled || rail->suspended) {
796                 pr_err("%s: cannot scale %s rail\n", __func__,
797                        rail->disabled ? "disabled" : "suspended");
798                 ret = -EPERM;
799                 if (!override_mv) {
800                         mutex_unlock(&dvfs_lock);
801                         goto out;
802                 }
803         } else {
804                 rail->override_millivolts = override_mv;
805                 ret = dvfs_rail_update(rail);
806                 if (ret) {
807                         pr_err("%s: failed to set override level %d\n",
808                                __func__, override_mv);
809                         rail->override_millivolts = 0;
810                         dvfs_rail_update(rail);
811                 }
812         }
813         mutex_unlock(&dvfs_lock);
814
815         if (!override_mv || ret)
816                 tegra_dvfs_core_cap_level_apply(0);
817 out:
818         mutex_unlock(&rail_override_lock);
819         return ret;
820 }
821 #else
822 static int dvfs_override_core_voltage(int override_mv)
823 {
824         pr_err("%s: vdd core override is not supported\n", __func__);
825         return -ENOSYS;
826 }
827 #endif
828
829 int tegra_dvfs_override_core_voltage(struct clk *c, int override_mv)
830 {
831         if (!c->dvfs || !c->dvfs->can_override) {
832                 pr_err("%s: %s cannot override vdd core\n", __func__, c->name);
833                 return -EPERM;
834         }
835         return dvfs_override_core_voltage(override_mv);
836 }
837 EXPORT_SYMBOL(tegra_dvfs_override_core_voltage);
838
839 /* May only be called during clock init, does not take any locks on clock c. */
840 int __init tegra_enable_dvfs_on_clk(struct clk *c, struct dvfs *d)
841 {
842         int i;
843
844         if (c->dvfs) {
845                 pr_err("Error when enabling dvfs on %s for clock %s:\n",
846                         d->dvfs_rail->reg_id, c->name);
847                 pr_err("DVFS already enabled for %s\n",
848                         c->dvfs->dvfs_rail->reg_id);
849                 return -EINVAL;
850         }
851
852         for (i = 0; i < MAX_DVFS_FREQS; i++) {
853                 if (d->millivolts[i] == 0)
854                         break;
855
856                 d->freqs[i] *= d->freqs_mult;
857
858                 /* If final frequencies are 0, pad with previous frequency */
859                 if (d->freqs[i] == 0 && i > 1)
860                         d->freqs[i] = d->freqs[i - 1];
861         }
862         d->num_freqs = i;
863
864         if (d->auto_dvfs) {
865                 c->auto_dvfs = true;
866                 clk_set_cansleep(c);
867         }
868
869         c->dvfs = d;
870
871         /*
872          * Minimum core override level is determined as maximum voltage required
873          * for clocks outside shared buses (shared bus rates can be capped to
874          * safe levels when override limit is set)
875          */
876         if (i && c->ops && !c->ops->shared_bus_update &&
877             !(c->flags & PERIPH_ON_CBUS) && !d->can_override) {
878                 int mv = tegra_dvfs_predict_millivolts(c, d->freqs[i-1]);
879                 if (d->dvfs_rail->min_override_millivolts < mv)
880                         d->dvfs_rail->min_override_millivolts = mv;
881         }
882
883         mutex_lock(&dvfs_lock);
884         list_add_tail(&d->reg_node, &d->dvfs_rail->dvfs);
885         mutex_unlock(&dvfs_lock);
886
887         return 0;
888 }
889
890 static bool tegra_dvfs_all_rails_suspended(void)
891 {
892         struct dvfs_rail *rail;
893         bool all_suspended = true;
894
895         list_for_each_entry(rail, &dvfs_rail_list, node)
896                 if (!rail->suspended && !rail->disabled)
897                         all_suspended = false;
898
899         return all_suspended;
900 }
901
902 static bool tegra_dvfs_from_rails_suspended_or_solved(struct dvfs_rail *to)
903 {
904         struct dvfs_relationship *rel;
905         bool all_suspended = true;
906
907         list_for_each_entry(rel, &to->relationships_from, from_node)
908                 if (!rel->from->suspended && !rel->from->disabled &&
909                         !rel->solved_at_nominal)
910                         all_suspended = false;
911
912         return all_suspended;
913 }
914
915 static int tegra_dvfs_suspend_one(void)
916 {
917         struct dvfs_rail *rail;
918         int ret, mv;
919
920         list_for_each_entry(rail, &dvfs_rail_list, node) {
921                 if (!rail->suspended && !rail->disabled &&
922                     tegra_dvfs_from_rails_suspended_or_solved(rail)) {
923                         /* Safe, as pll mode rate is capped to fixed level */
924                         if (!rail->dfll_mode && rail->fixed_millivolts) {
925                                 mv = rail->fixed_millivolts;
926                         } else {
927                                 mv = tegra_dvfs_rail_get_suspend_level(rail);
928                                 mv = dvfs_rail_apply_limits(rail, mv);
929                         }
930
931                         /* apply suspend limit only if it is above current mv */
932                         ret = -EPERM;
933                         if (mv >= rail->millivolts)
934                                 ret = dvfs_rail_set_voltage(rail, mv);
935                         if (ret) {
936                                 pr_err("tegra_dvfs: failed %s suspend at %d\n",
937                                        rail->reg_id, rail->millivolts);
938                                 return ret;
939                         }
940
941                         rail->suspended = true;
942                         return 0;
943                 }
944         }
945
946         return -EINVAL;
947 }
948
949 static void tegra_dvfs_resume(void)
950 {
951         struct dvfs_rail *rail;
952
953         mutex_lock(&dvfs_lock);
954
955         list_for_each_entry(rail, &dvfs_rail_list, node)
956                 rail->suspended = false;
957
958         list_for_each_entry(rail, &dvfs_rail_list, node)
959                 dvfs_rail_update(rail);
960
961         mutex_unlock(&dvfs_lock);
962 }
963
964 static int tegra_dvfs_suspend(void)
965 {
966         int ret = 0;
967
968         mutex_lock(&dvfs_lock);
969
970         while (!tegra_dvfs_all_rails_suspended()) {
971                 ret = tegra_dvfs_suspend_one();
972                 if (ret)
973                         break;
974         }
975
976         mutex_unlock(&dvfs_lock);
977
978         if (ret)
979                 tegra_dvfs_resume();
980
981         return ret;
982 }
983
984 static int tegra_dvfs_pm_suspend(struct notifier_block *nb,
985                                  unsigned long event, void *data)
986 {
987         if (event == PM_SUSPEND_PREPARE) {
988                 if (tegra_dvfs_suspend())
989                         return NOTIFY_STOP;
990                 pr_info("tegra_dvfs: suspended\n");
991         }
992         return NOTIFY_OK;
993 };
994
995 static int tegra_dvfs_pm_resume(struct notifier_block *nb,
996                                 unsigned long event, void *data)
997 {
998         if (event == PM_POST_SUSPEND) {
999                 tegra_dvfs_resume();
1000                 pr_info("tegra_dvfs: resumed\n");
1001         }
1002         return NOTIFY_OK;
1003 };
1004
1005 static struct notifier_block tegra_dvfs_suspend_nb = {
1006         .notifier_call = tegra_dvfs_pm_suspend,
1007         .priority = -1,
1008 };
1009
1010 static struct notifier_block tegra_dvfs_resume_nb = {
1011         .notifier_call = tegra_dvfs_pm_resume,
1012         .priority = 1,
1013 };
1014
1015 static int tegra_dvfs_reboot_notify(struct notifier_block *nb,
1016                                 unsigned long event, void *data)
1017 {
1018         switch (event) {
1019         case SYS_RESTART:
1020         case SYS_HALT:
1021         case SYS_POWER_OFF:
1022                 tegra_dvfs_suspend();
1023                 return NOTIFY_OK;
1024         }
1025         return NOTIFY_DONE;
1026 }
1027
1028 static struct notifier_block tegra_dvfs_reboot_nb = {
1029         .notifier_call = tegra_dvfs_reboot_notify,
1030 };
1031
1032 /* must be called with dvfs lock held */
1033 static void __tegra_dvfs_rail_disable(struct dvfs_rail *rail)
1034 {
1035         int ret = -EPERM;
1036         int mv;
1037
1038         /* don't set voltage in DFLL mode - won't work, but break stats */
1039         if (rail->dfll_mode) {
1040                 rail->disabled = true;
1041                 return;
1042         }
1043
1044         /* Safe, as pll mode rate is capped to fixed level */
1045         if (!rail->dfll_mode && rail->fixed_millivolts) {
1046                 mv = rail->fixed_millivolts;
1047         } else {
1048                 mv = tegra_dvfs_rail_get_disable_level(rail);
1049                 mv = dvfs_rail_apply_limits(rail, mv);
1050         }
1051
1052         /* apply detach mode limit provided it is above current volatge */
1053         if (mv >= rail->millivolts)
1054                 ret = dvfs_rail_set_voltage(rail, mv);
1055         if (ret) {
1056                 pr_err("tegra_dvfs: failed to disable %s at %d\n",
1057                        rail->reg_id, rail->millivolts);
1058                 return;
1059         }
1060         rail->disabled = true;
1061 }
1062
1063 /* must be called with dvfs lock held */
1064 static void __tegra_dvfs_rail_enable(struct dvfs_rail *rail)
1065 {
1066         rail->disabled = false;
1067         dvfs_rail_update(rail);
1068 }
1069
1070 void tegra_dvfs_rail_enable(struct dvfs_rail *rail)
1071 {
1072         if (!rail)
1073                 return;
1074
1075         mutex_lock(&rail_disable_lock);
1076
1077         if (rail->disabled) {
1078                 mutex_lock(&dvfs_lock);
1079                 __tegra_dvfs_rail_enable(rail);
1080                 mutex_unlock(&dvfs_lock);
1081
1082                 tegra_dvfs_rail_post_enable(rail);
1083         }
1084         mutex_unlock(&rail_disable_lock);
1085 }
1086
1087 void tegra_dvfs_rail_disable(struct dvfs_rail *rail)
1088 {
1089         if (!rail)
1090                 return;
1091
1092         mutex_lock(&rail_disable_lock);
1093         if (rail->disabled)
1094                 goto out;
1095
1096         /* rail disable will set it to nominal voltage underneath clock
1097            framework - need to re-configure clock rates that are not safe
1098            at nominal (yes, unsafe at nominal is ugly, but possible). Rate
1099            change must be done outside of dvfs lock. */
1100         if (tegra_dvfs_rail_disable_prepare(rail)) {
1101                 pr_info("dvfs: failed to prepare regulator %s to disable\n",
1102                         rail->reg_id);
1103                 goto out;
1104         }
1105
1106         mutex_lock(&dvfs_lock);
1107         __tegra_dvfs_rail_disable(rail);
1108         mutex_unlock(&dvfs_lock);
1109 out:
1110         mutex_unlock(&rail_disable_lock);
1111 }
1112
1113 int tegra_dvfs_rail_disable_by_name(const char *reg_id)
1114 {
1115         struct dvfs_rail *rail = tegra_dvfs_get_rail_by_name(reg_id);
1116         if (!rail)
1117                 return -EINVAL;
1118
1119         tegra_dvfs_rail_disable(rail);
1120         return 0;
1121 }
1122
1123 struct dvfs_rail *tegra_dvfs_get_rail_by_name(const char *reg_id)
1124 {
1125         struct dvfs_rail *rail;
1126
1127         mutex_lock(&dvfs_lock);
1128         list_for_each_entry(rail, &dvfs_rail_list, node) {
1129                 if (!strcmp(reg_id, rail->reg_id)) {
1130                         mutex_unlock(&dvfs_lock);
1131                         return rail;
1132                 }
1133         }
1134         mutex_unlock(&dvfs_lock);
1135         return NULL;
1136 }
1137
1138 int tegra_dvfs_rail_power_up(struct dvfs_rail *rail)
1139 {
1140         int ret = -ENOENT;
1141
1142         if (!rail || !rail->in_band_pm)
1143                 return -ENOSYS;
1144
1145         mutex_lock(&dvfs_lock);
1146         if (rail->reg) {
1147                 ret = regulator_enable(rail->reg);
1148                 if (!ret && !timekeeping_suspended)
1149                         tegra_dvfs_rail_on(rail, ktime_get());
1150         }
1151         mutex_unlock(&dvfs_lock);
1152         return ret;
1153 }
1154
1155 int tegra_dvfs_rail_power_down(struct dvfs_rail *rail)
1156 {
1157         int ret = -ENOENT;
1158
1159         if (!rail || !rail->in_band_pm)
1160                 return -ENOSYS;
1161
1162         mutex_lock(&dvfs_lock);
1163         if (rail->reg) {
1164                 ret = regulator_disable(rail->reg);
1165                 if (!ret && !timekeeping_suspended)
1166                         tegra_dvfs_rail_off(rail, ktime_get());
1167         }
1168         mutex_unlock(&dvfs_lock);
1169         return ret;
1170 }
1171
1172 bool tegra_dvfs_is_rail_up(struct dvfs_rail *rail)
1173 {
1174         bool ret = false;
1175
1176         if (!rail)
1177                 return false;
1178
1179         if (!rail->in_band_pm)
1180                 return true;
1181
1182         mutex_lock(&dvfs_lock);
1183         if (rail->reg)
1184                 ret = regulator_is_enabled(rail->reg) > 0;
1185         mutex_unlock(&dvfs_lock);
1186         return ret;
1187 }
1188
1189 bool tegra_dvfs_rail_updating(struct clk *clk)
1190 {
1191         return (!clk ? false :
1192                 (!clk->dvfs ? false :
1193                  (!clk->dvfs->dvfs_rail ? false :
1194                   (clk->dvfs->dvfs_rail->updating ||
1195                    clk->dvfs->dvfs_rail->dfll_mode_updating))));
1196 }
1197
1198 #ifdef CONFIG_OF
1199 int __init of_tegra_dvfs_init(const struct of_device_id *matches)
1200 {
1201         int ret;
1202         struct device_node *np;
1203
1204         for_each_matching_node(np, matches) {
1205                 const struct of_device_id *match = of_match_node(matches, np);
1206                 of_tegra_dvfs_init_cb_t dvfs_init_cb = match->data;
1207                 ret = dvfs_init_cb(np);
1208                 if (ret) {
1209                         pr_err("dt: Failed to read %s tables from DT\n",
1210                                                         match->compatible);
1211                         return ret;
1212                 }
1213         }
1214         return 0;
1215 }
1216 #endif
1217 int tegra_dvfs_dfll_mode_set(struct dvfs *d, unsigned long rate)
1218 {
1219         mutex_lock(&dvfs_lock);
1220         if (!d->dvfs_rail->dfll_mode) {
1221                 d->dvfs_rail->dfll_mode = true;
1222                 __tegra_dvfs_set_rate(d, rate);
1223         }
1224         mutex_unlock(&dvfs_lock);
1225         return 0;
1226 }
1227
1228 int tegra_dvfs_dfll_mode_clear(struct dvfs *d, unsigned long rate)
1229 {
1230         int ret = 0;
1231
1232         mutex_lock(&dvfs_lock);
1233         if (d->dvfs_rail->dfll_mode) {
1234                 d->dvfs_rail->dfll_mode = false;
1235                 /* avoid false detection of matching target (voltage in dfll
1236                    mode is fluctuating, and recorded level is just estimate) */
1237                 d->dvfs_rail->millivolts--;
1238                 if (d->dvfs_rail->disabled) {
1239                         d->dvfs_rail->disabled = false;
1240                         __tegra_dvfs_rail_disable(d->dvfs_rail);
1241                 }
1242                 ret = __tegra_dvfs_set_rate(d, rate);
1243         }
1244         mutex_unlock(&dvfs_lock);
1245         return ret;
1246 }
1247
1248 struct tegra_cooling_device *tegra_dvfs_get_cpu_vmax_cdev(void)
1249 {
1250         if (tegra_cpu_rail)
1251                 return tegra_cpu_rail->vmax_cdev;
1252         return NULL;
1253 }
1254
1255 struct tegra_cooling_device *tegra_dvfs_get_cpu_vmin_cdev(void)
1256 {
1257         if (tegra_cpu_rail)
1258                 return tegra_cpu_rail->vmin_cdev;
1259         return NULL;
1260 }
1261
1262 struct tegra_cooling_device *tegra_dvfs_get_core_vmin_cdev(void)
1263 {
1264         if (tegra_core_rail)
1265                 return tegra_core_rail->vmin_cdev;
1266         return NULL;
1267 }
1268
1269 struct tegra_cooling_device *tegra_dvfs_get_gpu_vmin_cdev(void)
1270 {
1271         if (tegra_gpu_rail)
1272                 return tegra_gpu_rail->vmin_cdev;
1273         return NULL;
1274 }
1275
1276 #ifdef CONFIG_THERMAL
1277 /* Cooling device limits minimum rail voltage at cold temperature in pll mode */
1278 static int tegra_dvfs_rail_get_vmin_cdev_max_state(
1279         struct thermal_cooling_device *cdev, unsigned long *max_state)
1280 {
1281         struct dvfs_rail *rail = (struct dvfs_rail *)cdev->devdata;
1282         *max_state = rail->vmin_cdev->trip_temperatures_num;
1283         return 0;
1284 }
1285
1286 static int tegra_dvfs_rail_get_vmin_cdev_cur_state(
1287         struct thermal_cooling_device *cdev, unsigned long *cur_state)
1288 {
1289         struct dvfs_rail *rail = (struct dvfs_rail *)cdev->devdata;
1290         *cur_state = rail->therm_floor_idx;
1291         return 0;
1292 }
1293
1294 static int tegra_dvfs_rail_set_vmin_cdev_state(
1295         struct thermal_cooling_device *cdev, unsigned long cur_state)
1296 {
1297         struct dvfs_rail *rail = (struct dvfs_rail *)cdev->devdata;
1298
1299         mutex_lock(&dvfs_lock);
1300         if (rail->therm_floor_idx != cur_state) {
1301                 rail->therm_floor_idx = cur_state;
1302                 dvfs_rail_update(rail);
1303         }
1304         mutex_unlock(&dvfs_lock);
1305         return 0;
1306 }
1307
1308 static struct thermal_cooling_device_ops tegra_dvfs_vmin_cooling_ops = {
1309         .get_max_state = tegra_dvfs_rail_get_vmin_cdev_max_state,
1310         .get_cur_state = tegra_dvfs_rail_get_vmin_cdev_cur_state,
1311         .set_cur_state = tegra_dvfs_rail_set_vmin_cdev_state,
1312 };
1313
1314 static void tegra_dvfs_rail_register_vmin_cdev(struct dvfs_rail *rail)
1315 {
1316         if (!rail->vmin_cdev)
1317                 return;
1318
1319         /* just report error - initialized for cold temperature, anyway */
1320         if (IS_ERR_OR_NULL(thermal_cooling_device_register(
1321                 rail->vmin_cdev->cdev_type, (void *)rail,
1322                 &tegra_dvfs_vmin_cooling_ops)))
1323                 pr_err("tegra cooling device %s failed to register\n",
1324                        rail->vmin_cdev->cdev_type);
1325 }
1326
1327 /* Cooling device to scale voltage with temperature in pll mode */
1328 static int tegra_dvfs_rail_get_vts_cdev_max_state(
1329         struct thermal_cooling_device *cdev, unsigned long *max_state)
1330 {
1331         struct dvfs_rail *rail = (struct dvfs_rail *)cdev->devdata;
1332         *max_state = rail->vts_cdev->trip_temperatures_num;
1333         return 0;
1334 }
1335
1336 static int tegra_dvfs_rail_get_vts_cdev_cur_state(
1337         struct thermal_cooling_device *cdev, unsigned long *cur_state)
1338 {
1339         struct dvfs_rail *rail = (struct dvfs_rail *)cdev->devdata;
1340         *cur_state = rail->therm_scale_idx;
1341         return 0;
1342 }
1343
1344 static int tegra_dvfs_rail_set_vts_cdev_state(
1345         struct thermal_cooling_device *cdev, unsigned long cur_state)
1346 {
1347         struct dvfs_rail *rail = (struct dvfs_rail *)cdev->devdata;
1348         struct dvfs *d;
1349
1350         mutex_lock(&dvfs_lock);
1351         if (rail->therm_scale_idx != cur_state) {
1352                 rail->therm_scale_idx = cur_state;
1353                 list_for_each_entry(d, &rail->dvfs, reg_node) {
1354                         if (d->therm_dvfs)
1355                                 __tegra_dvfs_set_rate(d, d->cur_rate);
1356                 }
1357         }
1358         mutex_unlock(&dvfs_lock);
1359         return 0;
1360 }
1361
1362 static struct thermal_cooling_device_ops tegra_dvfs_vts_cooling_ops = {
1363         .get_max_state = tegra_dvfs_rail_get_vts_cdev_max_state,
1364         .get_cur_state = tegra_dvfs_rail_get_vts_cdev_cur_state,
1365         .set_cur_state = tegra_dvfs_rail_set_vts_cdev_state,
1366 };
1367
1368 static void tegra_dvfs_rail_register_vts_cdev(struct dvfs_rail *rail)
1369 {
1370         if (!rail->vts_cdev)
1371                 return;
1372
1373         /* just report error - initialized for cold temperature, anyway */
1374         if (IS_ERR_OR_NULL(thermal_cooling_device_register(
1375                 rail->vts_cdev->cdev_type, (void *)rail,
1376                 &tegra_dvfs_vts_cooling_ops)))
1377                 pr_err("tegra cooling device %s failed to register\n",
1378                        rail->vts_cdev->cdev_type);
1379 }
1380
1381 #else
1382 #define tegra_dvfs_rail_register_vmin_cdev(rail)
1383 #define tegra_dvfs_rail_register_vts_cdev(rail)
1384 #endif
1385
1386 /*
1387  * Validate rail thermal profile, and get its size. Valid profile:
1388  * - voltage limits are descending with temperature increasing
1389  * - the lowest limit is above rail minimum voltage in pll and
1390  *   in dfll mode (if applicable)
1391  * - the highest limit is below rail nominal voltage
1392  */
1393 static int __init get_thermal_profile_size(
1394         int *trips_table, int *limits_table,
1395         struct dvfs_rail *rail, struct dvfs_dfll_data *d)
1396 {
1397         int i, min_mv;
1398
1399         for (i = 0; i < MAX_THERMAL_LIMITS - 1; i++) {
1400                 if (!limits_table[i+1])
1401                         break;
1402
1403                 if ((trips_table[i] >= trips_table[i+1]) ||
1404                     (limits_table[i] < limits_table[i+1])) {
1405                         pr_warn("%s: not ordered profile\n", rail->reg_id);
1406                         return -EINVAL;
1407                 }
1408         }
1409
1410         min_mv = max(rail->min_millivolts, d ? d->min_millivolts : 0);
1411         if (limits_table[i] < min_mv) {
1412                 pr_warn("%s: thermal profile below Vmin\n", rail->reg_id);
1413                 return -EINVAL;
1414         }
1415
1416         if (limits_table[0] > rail->nominal_millivolts) {
1417                 pr_warn("%s: thermal profile above Vmax\n", rail->reg_id);
1418                 return -EINVAL;
1419         }
1420         return i + 1;
1421 }
1422
1423 void __init tegra_dvfs_rail_init_vmax_thermal_profile(
1424         int *therm_trips_table, int *therm_caps_table,
1425         struct dvfs_rail *rail, struct dvfs_dfll_data *d)
1426 {
1427         int i = get_thermal_profile_size(therm_trips_table,
1428                                          therm_caps_table, rail, d);
1429         if (i <= 0) {
1430                 rail->vmax_cdev = NULL;
1431                 WARN(1, "%s: invalid Vmax thermal profile\n", rail->reg_id);
1432                 return;
1433         }
1434
1435         /* Install validated thermal caps */
1436         rail->therm_mv_caps = therm_caps_table;
1437         rail->therm_mv_caps_num = i;
1438
1439         /* Setup trip-points if applicable */
1440         if (rail->vmax_cdev) {
1441                 rail->vmax_cdev->trip_temperatures_num = i;
1442                 rail->vmax_cdev->trip_temperatures = therm_trips_table;
1443         }
1444 }
1445
1446 void __init tegra_dvfs_rail_init_vmin_thermal_profile(
1447         int *therm_trips_table, int *therm_floors_table,
1448         struct dvfs_rail *rail, struct dvfs_dfll_data *d)
1449 {
1450         int i = get_thermal_profile_size(therm_trips_table,
1451                                          therm_floors_table, rail, d);
1452         if (i <= 0) {
1453                 rail->vmin_cdev = NULL;
1454                 WARN(1, "%s: invalid Vmin thermal profile\n", rail->reg_id);
1455                 return;
1456         }
1457
1458         /* Install validated thermal floors */
1459         rail->therm_mv_floors = therm_floors_table;
1460         rail->therm_mv_floors_num = i;
1461
1462         /* Setup trip-points if applicable */
1463         if (rail->vmin_cdev) {
1464                 rail->vmin_cdev->trip_temperatures_num = i;
1465                 rail->vmin_cdev->trip_temperatures = therm_trips_table;
1466         }
1467 }
1468
1469 /*
1470  * Validate thermal dvfs settings:
1471  * - trip-points are montonically increasing
1472  * - voltages in any temperature range are montonically increasing with
1473  *   frequency (can go up/down across ranges at iso frequency)
1474  * - voltage for any frequency/thermal range combination must be within
1475  *   rail minimum/maximum limits
1476  */
1477 int __init tegra_dvfs_rail_init_thermal_dvfs_trips(
1478         int *therm_trips_table, struct dvfs_rail *rail)
1479 {
1480         int i;
1481
1482         if (!rail->vts_cdev) {
1483                 WARN(1, "%s: missing thermal dvfs cooling device\n",
1484                      rail->reg_id);
1485                 return -ENOENT;
1486         }
1487
1488         for (i = 0; i < MAX_THERMAL_LIMITS - 1; i++) {
1489                 if (therm_trips_table[i] >= therm_trips_table[i+1])
1490                         break;
1491         }
1492
1493         rail->vts_cdev->trip_temperatures_num = i + 1;
1494         rail->vts_cdev->trip_temperatures = therm_trips_table;
1495         return 0;
1496 }
1497
1498 int __init tegra_dvfs_init_thermal_dvfs_voltages(
1499         int *therm_voltages, int freqs_num, int ranges_num, struct dvfs *d)
1500 {
1501         int *millivolts;
1502         int freq_idx, therm_idx;
1503
1504         for (therm_idx = 0; therm_idx < ranges_num; therm_idx++) {
1505                 millivolts = therm_voltages + therm_idx * MAX_DVFS_FREQS;
1506                 for (freq_idx = 0; freq_idx < freqs_num; freq_idx++) {
1507                         int mv = millivolts[freq_idx];
1508                         if ((mv > d->dvfs_rail->max_millivolts) ||
1509                             (mv < d->dvfs_rail->min_millivolts) ||
1510                             (freq_idx && (mv < millivolts[freq_idx - 1]))) {
1511                                 WARN(1, "%s: invalid thermal dvfs entry %d(%d, %d)\n",
1512                                      d->clk_name, mv, freq_idx, therm_idx);
1513                                 return -EINVAL;
1514                         }
1515                 }
1516         }
1517
1518         d->millivolts = therm_voltages;
1519         d->therm_dvfs = true;
1520         return 0;
1521 }
1522
1523 /* Directly set cold temperature limit in dfll mode */
1524 int tegra_dvfs_rail_dfll_mode_set_cold(struct dvfs_rail *rail)
1525 {
1526         int ret = 0;
1527
1528         /* No thermal floors - nothing to do */
1529         if (!rail || !rail->therm_mv_floors)
1530                 return ret;
1531
1532         /*
1533          * Since cooling thresholds are the same in pll and dfll modes, pll mode
1534          * thermal index can be used to decide if cold limit should be set in
1535          * dfll mode.
1536          */
1537         mutex_lock(&dvfs_lock);
1538         if (rail->dfll_mode &&
1539             (rail->therm_floor_idx < rail->therm_mv_floors_num)) {
1540                         int mv = rail->therm_mv_floors[rail->therm_floor_idx];
1541                         ret = dvfs_rail_set_voltage_reg(rail, mv);
1542         }
1543         mutex_unlock(&dvfs_lock);
1544
1545         return ret;
1546 }
1547
1548 /*
1549  * Iterate through all the dvfs regulators, finding the regulator exported
1550  * by the regulator api for each one.  Must be called in late init, after
1551  * all the regulator api's regulators are initialized.
1552  */
1553 int __init tegra_dvfs_late_init(void)
1554 {
1555         bool connected = true;
1556         struct dvfs_rail *rail;
1557
1558         mutex_lock(&dvfs_lock);
1559
1560         list_for_each_entry(rail, &dvfs_rail_list, node)
1561                 if (dvfs_rail_connect_to_regulator(rail))
1562                         connected = false;
1563
1564         list_for_each_entry(rail, &dvfs_rail_list, node)
1565                 if (connected)
1566                         dvfs_rail_update(rail);
1567                 else
1568                         __tegra_dvfs_rail_disable(rail);
1569
1570         mutex_unlock(&dvfs_lock);
1571
1572         if (!connected && tegra_platform_is_silicon()) {
1573                 pr_warn("tegra_dvfs: DVFS regulators connection failed\n"
1574                         "            !!!! voltage scaling is disabled !!!!\n");
1575                 return -ENODEV;
1576         }
1577
1578         register_pm_notifier(&tegra_dvfs_suspend_nb);
1579         register_pm_notifier(&tegra_dvfs_resume_nb);
1580         register_reboot_notifier(&tegra_dvfs_reboot_nb);
1581
1582         list_for_each_entry(rail, &dvfs_rail_list, node) {
1583                         tegra_dvfs_rail_register_vmin_cdev(rail);
1584                         tegra_dvfs_rail_register_vts_cdev(rail);
1585         }
1586
1587         return 0;
1588 }
1589
1590 static int rail_stats_save_to_buf(char *buf, int len)
1591 {
1592         int i;
1593         struct dvfs_rail *rail;
1594         char *str = buf;
1595         char *end = buf + len;
1596
1597         str += scnprintf(str, end - str, "%-12s %-10s\n", "millivolts", "time");
1598
1599         mutex_lock(&dvfs_lock);
1600
1601         list_for_each_entry(rail, &dvfs_rail_list, node) {
1602                 str += scnprintf(str, end - str, "%s (bin: %d.%dmV)\n",
1603                            rail->reg_id,
1604                            rail->stats.bin_uV / 1000,
1605                            (rail->stats.bin_uV / 10) % 100);
1606
1607                 dvfs_rail_stats_update(rail, -1, ktime_get());
1608
1609                 str += scnprintf(str, end - str, "%-12d %-10llu\n", 0,
1610                         cputime64_to_clock_t(msecs_to_jiffies(
1611                                 ktime_to_ms(rail->stats.time_at_mv[0]))));
1612
1613                 for (i = 1; i <= DVFS_RAIL_STATS_TOP_BIN; i++) {
1614                         ktime_t ktime_zero = ktime_set(0, 0);
1615                         if (ktime_equal(rail->stats.time_at_mv[i], ktime_zero))
1616                                 continue;
1617                         str += scnprintf(str, end - str, "%-12d %-10llu\n",
1618                                 rail->min_millivolts +
1619                                 (i - 1) * rail->stats.bin_uV / 1000,
1620                                 cputime64_to_clock_t(msecs_to_jiffies(
1621                                         ktime_to_ms(rail->stats.time_at_mv[i])))
1622                         );
1623                 }
1624         }
1625         mutex_unlock(&dvfs_lock);
1626         return str - buf;
1627 }
1628
1629 #ifdef CONFIG_DEBUG_FS
1630 static int dvfs_tree_sort_cmp(void *p, struct list_head *a, struct list_head *b)
1631 {
1632         struct dvfs *da = list_entry(a, struct dvfs, reg_node);
1633         struct dvfs *db = list_entry(b, struct dvfs, reg_node);
1634         int ret;
1635
1636         ret = strcmp(da->dvfs_rail->reg_id, db->dvfs_rail->reg_id);
1637         if (ret != 0)
1638                 return ret;
1639
1640         if (da->cur_millivolts < db->cur_millivolts)
1641                 return 1;
1642         if (da->cur_millivolts > db->cur_millivolts)
1643                 return -1;
1644
1645         return strcmp(da->clk_name, db->clk_name);
1646 }
1647
1648 static int dvfs_tree_show(struct seq_file *s, void *data)
1649 {
1650         struct dvfs *d;
1651         struct dvfs_rail *rail;
1652         struct dvfs_relationship *rel;
1653
1654         seq_printf(s, "   clock      rate       mV\n");
1655         seq_printf(s, "--------------------------------\n");
1656
1657         mutex_lock(&dvfs_lock);
1658
1659         list_for_each_entry(rail, &dvfs_rail_list, node) {
1660                 int thermal_mv_floor = 0;
1661
1662                 seq_printf(s, "%s %d mV%s:\n", rail->reg_id,
1663                            rail->stats.off ? 0 : rail->millivolts,
1664                            rail->dfll_mode ? " dfll mode" :
1665                                 rail->disabled ? " disabled" : "");
1666                 list_for_each_entry(rel, &rail->relationships_from, from_node) {
1667                         seq_printf(s, "   %-10s %-7d mV %-4d mV\n",
1668                                 rel->from->reg_id, rel->from->millivolts,
1669                                 dvfs_solve_relationship(rel));
1670                 }
1671                 seq_printf(s, "   offset     %-7d mV\n", rail->dbg_mv_offs);
1672
1673                 if (rail->therm_mv_floors) {
1674                         int i = rail->therm_floor_idx;
1675                         if (i < rail->therm_mv_floors_num)
1676                                 thermal_mv_floor = rail->therm_mv_floors[i];
1677                 }
1678                 seq_printf(s, "   thermal    %-7d mV\n", thermal_mv_floor);
1679
1680                 if (rail == tegra_core_rail) {
1681                         seq_printf(s, "   override   %-7d mV [%-4d...%-4d]\n",
1682                                    rail->override_millivolts,
1683                                    rail->min_override_millivolts,
1684                                    rail->nominal_millivolts);
1685                 }
1686
1687                 list_sort(NULL, &rail->dvfs, dvfs_tree_sort_cmp);
1688
1689                 list_for_each_entry(d, &rail->dvfs, reg_node) {
1690                         seq_printf(s, "   %-10s %-10lu %-4d mV\n", d->clk_name,
1691                                 d->cur_rate, d->cur_millivolts);
1692                 }
1693         }
1694
1695         mutex_unlock(&dvfs_lock);
1696
1697         return 0;
1698 }
1699
1700 static int dvfs_tree_open(struct inode *inode, struct file *file)
1701 {
1702         return single_open(file, dvfs_tree_show, inode->i_private);
1703 }
1704
1705 static const struct file_operations dvfs_tree_fops = {
1706         .open           = dvfs_tree_open,
1707         .read           = seq_read,
1708         .llseek         = seq_lseek,
1709         .release        = single_release,
1710 };
1711
1712 static int rail_stats_show(struct seq_file *s, void *data)
1713 {
1714         char *buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
1715         int size = 0;
1716
1717         if (!buf)
1718                 return -ENOMEM;
1719
1720         size = rail_stats_save_to_buf(buf, PAGE_SIZE);
1721         seq_write(s, buf, size);
1722         kfree(buf);
1723         return 0;
1724 }
1725
1726 static int rail_stats_open(struct inode *inode, struct file *file)
1727 {
1728         return single_open(file, rail_stats_show, inode->i_private);
1729 }
1730
1731 static const struct file_operations rail_stats_fops = {
1732         .open           = rail_stats_open,
1733         .read           = seq_read,
1734         .llseek         = seq_lseek,
1735         .release        = single_release,
1736 };
1737
1738 static int gpu_dvfs_show(struct seq_file *s, void *data)
1739 {
1740         int idx;
1741         int *millivolts;
1742         unsigned long *freqs;
1743
1744         if (read_gpu_dvfs_table(&millivolts, &freqs)) {
1745                 seq_printf(s, "Only supported for T124 or higher\n");
1746                 return 0;
1747         }
1748
1749         seq_printf(s, "millivolts \t \t frequency\n");
1750         seq_printf(s, "=====================================\n");
1751
1752         for (idx = 0; millivolts[idx]; idx++)
1753                 seq_printf(s, "%d mV \t \t %lu Hz\n", millivolts[idx],
1754                                 freqs[idx]);
1755
1756         return 0;
1757 }
1758
1759 static int gpu_dvfs_open(struct inode *inode, struct file *file)
1760 {
1761         return single_open(file, gpu_dvfs_show, NULL);
1762 }
1763
1764 static const struct file_operations gpu_dvfs_fops = {
1765         .open           = gpu_dvfs_open,
1766         .read           = seq_read,
1767         .llseek         = seq_lseek,
1768         .release        = single_release,
1769 };
1770
1771 static int rail_offs_set(struct dvfs_rail *rail, int offs)
1772 {
1773         if (rail) {
1774                 mutex_lock(&dvfs_lock);
1775                 rail->dbg_mv_offs = offs;
1776                 dvfs_rail_update(rail);
1777                 mutex_unlock(&dvfs_lock);
1778                 return 0;
1779         }
1780         return -ENOENT;
1781 }
1782
1783 static int cpu_offs_get(void *data, u64 *val)
1784 {
1785         if (tegra_cpu_rail) {
1786                 *val = (u64)tegra_cpu_rail->dbg_mv_offs;
1787                 return 0;
1788         }
1789         *val = 0;
1790         return -ENOENT;
1791 }
1792 static int cpu_offs_set(void *data, u64 val)
1793 {
1794         return rail_offs_set(tegra_cpu_rail, (int)val);
1795 }
1796 DEFINE_SIMPLE_ATTRIBUTE(cpu_offs_fops, cpu_offs_get, cpu_offs_set, "%lld\n");
1797
1798 static int gpu_offs_get(void *data, u64 *val)
1799 {
1800         if (tegra_gpu_rail) {
1801                 *val = (u64)tegra_gpu_rail->dbg_mv_offs;
1802                 return 0;
1803         }
1804         *val = 0;
1805         return -ENOENT;
1806 }
1807 static int gpu_offs_set(void *data, u64 val)
1808 {
1809         return rail_offs_set(tegra_gpu_rail, (int)val);
1810 }
1811 DEFINE_SIMPLE_ATTRIBUTE(gpu_offs_fops, gpu_offs_get, gpu_offs_set, "%lld\n");
1812
1813 static int core_offs_get(void *data, u64 *val)
1814 {
1815         if (tegra_core_rail) {
1816                 *val = (u64)tegra_core_rail->dbg_mv_offs;
1817                 return 0;
1818         }
1819         *val = 0;
1820         return -ENOENT;
1821 }
1822 static int core_offs_set(void *data, u64 val)
1823 {
1824         return rail_offs_set(tegra_core_rail, (int)val);
1825 }
1826 DEFINE_SIMPLE_ATTRIBUTE(core_offs_fops, core_offs_get, core_offs_set, "%lld\n");
1827
1828 static int core_override_get(void *data, u64 *val)
1829 {
1830         if (tegra_core_rail) {
1831                 *val = (u64)tegra_core_rail->override_millivolts;
1832                 return 0;
1833         }
1834         *val = 0;
1835         return -ENOENT;
1836 }
1837 static int core_override_set(void *data, u64 val)
1838 {
1839         return dvfs_override_core_voltage((int)val);
1840 }
1841 DEFINE_SIMPLE_ATTRIBUTE(core_override_fops,
1842                         core_override_get, core_override_set, "%llu\n");
1843
1844 static int dvfs_table_show(struct seq_file *s, void *data)
1845 {
1846         int i;
1847         struct dvfs *d;
1848         struct dvfs_rail *rail;
1849
1850         seq_printf(s, "DVFS tables: units mV/MHz\n\n");
1851
1852         mutex_lock(&dvfs_lock);
1853
1854         list_for_each_entry(rail, &dvfs_rail_list, node) {
1855                 bool mv_done = false;
1856                 list_for_each_entry(d, &rail->dvfs, reg_node) {
1857                         if (!mv_done) {
1858                                 const int *m = tegra_dvfs_get_millivolts_pll(d);
1859                                 mv_done = true;
1860                                 seq_printf(s, "%-16s", rail->reg_id);
1861                                 for (i = 0; i < d->num_freqs; i++) {
1862                                         int mv = m[i];
1863                                         seq_printf(s, "%7d", mv);
1864                                 }
1865                                 seq_printf(s, "\n");
1866                                 if (d->dfll_millivolts) {
1867                                         seq_printf(s, "%-8s (dfll) ",
1868                                                    rail->reg_id);
1869                                         for (i = 0; i < d->num_freqs; i++) {
1870                                                 int mv = d->dfll_millivolts[i];
1871                                                 seq_printf(s, "%7d", mv);
1872                                         }
1873                                         seq_printf(s, "\n");
1874                                 }
1875                         }
1876
1877                         seq_printf(s, "%-16s", d->clk_name);
1878                         for (i = 0; i < d->num_freqs; i++) {
1879                                 unsigned int f = d->freqs[i]/100000;
1880                                 seq_printf(s, " %4u.%u", f/10, f%10);
1881                         }
1882                         seq_printf(s, "\n");
1883                 }
1884                 seq_printf(s, "\n");
1885         }
1886
1887         mutex_unlock(&dvfs_lock);
1888
1889         return 0;
1890 }
1891
1892 static int dvfs_table_open(struct inode *inode, struct file *file)
1893 {
1894         return single_open(file, dvfs_table_show, inode->i_private);
1895 }
1896
1897 static const struct file_operations dvfs_table_fops = {
1898         .open           = dvfs_table_open,
1899         .read           = seq_read,
1900         .llseek         = seq_lseek,
1901         .release        = single_release,
1902 };
1903
1904 int __init dvfs_debugfs_init(struct dentry *clk_debugfs_root)
1905 {
1906         struct dentry *d;
1907
1908         d = debugfs_create_file("dvfs", S_IRUGO, clk_debugfs_root, NULL,
1909                 &dvfs_tree_fops);
1910         if (!d)
1911                 return -ENOMEM;
1912
1913         d = debugfs_create_file("rails", S_IRUGO, clk_debugfs_root, NULL,
1914                 &rail_stats_fops);
1915         if (!d)
1916                 return -ENOMEM;
1917
1918         d = debugfs_create_file("vdd_cpu_offs", S_IRUGO | S_IWUSR,
1919                 clk_debugfs_root, NULL, &cpu_offs_fops);
1920         if (!d)
1921                 return -ENOMEM;
1922
1923         d = debugfs_create_file("vdd_gpu_offs", S_IRUGO | S_IWUSR,
1924                 clk_debugfs_root, NULL, &gpu_offs_fops);
1925         if (!d)
1926                 return -ENOMEM;
1927
1928         d = debugfs_create_file("vdd_core_offs", S_IRUGO | S_IWUSR,
1929                 clk_debugfs_root, NULL, &core_offs_fops);
1930         if (!d)
1931                 return -ENOMEM;
1932
1933         d = debugfs_create_file("vdd_core_override", S_IRUGO | S_IWUSR,
1934                 clk_debugfs_root, NULL, &core_override_fops);
1935         if (!d)
1936                 return -ENOMEM;
1937
1938         d = debugfs_create_file("gpu_dvfs", S_IRUGO | S_IWUSR,
1939                 clk_debugfs_root, NULL, &gpu_dvfs_fops);
1940         if (!d)
1941                 return -ENOMEM;
1942
1943         d = debugfs_create_file("dvfs_table", S_IRUGO, clk_debugfs_root, NULL,
1944                 &dvfs_table_fops);
1945         if (!d)
1946                 return -ENOMEM;
1947
1948         return 0;
1949 }
1950
1951 #endif
1952
1953 #ifdef CONFIG_PM
1954 static ssize_t tegra_rail_stats_show(struct kobject *kobj,
1955                                         struct kobj_attribute *attr,
1956                                         char *buf)
1957 {
1958         return rail_stats_save_to_buf(buf, PAGE_SIZE);
1959 }
1960
1961 static struct kobj_attribute rail_stats_attr =
1962                 __ATTR_RO(tegra_rail_stats);
1963
1964 static int __init tegra_dvfs_sysfs_stats_init(void)
1965 {
1966         int error;
1967         error = sysfs_create_file(power_kobj, &rail_stats_attr.attr);
1968         return 0;
1969 }
1970 late_initcall(tegra_dvfs_sysfs_stats_init);
1971 #endif