thermal: power_allocator: relax the requirement of a sustainable_power in tzp
[cascardo/linux.git] / drivers / thermal / power_allocator.c
1 /*
2  * A power allocator to manage temperature
3  *
4  * Copyright (C) 2014 ARM Ltd.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 as
8  * published by the Free Software Foundation.
9  *
10  * This program is distributed "as is" WITHOUT ANY WARRANTY of any
11  * kind, whether express or implied; without even the implied warranty
12  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  */
15
16 #define pr_fmt(fmt) "Power allocator: " fmt
17
18 #include <linux/rculist.h>
19 #include <linux/slab.h>
20 #include <linux/thermal.h>
21
22 #define CREATE_TRACE_POINTS
23 #include <trace/events/thermal_power_allocator.h>
24
25 #include "thermal_core.h"
26
27 #define FRAC_BITS 10
28 #define int_to_frac(x) ((x) << FRAC_BITS)
29 #define frac_to_int(x) ((x) >> FRAC_BITS)
30
31 /**
32  * mul_frac() - multiply two fixed-point numbers
33  * @x:  first multiplicand
34  * @y:  second multiplicand
35  *
36  * Return: the result of multiplying two fixed-point numbers.  The
37  * result is also a fixed-point number.
38  */
39 static inline s64 mul_frac(s64 x, s64 y)
40 {
41         return (x * y) >> FRAC_BITS;
42 }
43
44 /**
45  * div_frac() - divide two fixed-point numbers
46  * @x:  the dividend
47  * @y:  the divisor
48  *
49  * Return: the result of dividing two fixed-point numbers.  The
50  * result is also a fixed-point number.
51  */
52 static inline s64 div_frac(s64 x, s64 y)
53 {
54         return div_s64(x << FRAC_BITS, y);
55 }
56
57 /**
58  * struct power_allocator_params - parameters for the power allocator governor
59  * @err_integral:       accumulated error in the PID controller.
60  * @prev_err:   error in the previous iteration of the PID controller.
61  *              Used to calculate the derivative term.
62  * @trip_switch_on:     first passive trip point of the thermal zone.  The
63  *                      governor switches on when this trip point is crossed.
64  * @trip_max_desired_temperature:       last passive trip point of the thermal
65  *                                      zone.  The temperature we are
66  *                                      controlling for.
67  */
68 struct power_allocator_params {
69         s64 err_integral;
70         s32 prev_err;
71         int trip_switch_on;
72         int trip_max_desired_temperature;
73 };
74
75 /**
76  * estimate_sustainable_power() - Estimate the sustainable power of a thermal zone
77  * @tz: thermal zone we are operating in
78  *
79  * For thermal zones that don't provide a sustainable_power in their
80  * thermal_zone_params, estimate one.  Calculate it using the minimum
81  * power of all the cooling devices as that gives a valid value that
82  * can give some degree of functionality.  For optimal performance of
83  * this governor, provide a sustainable_power in the thermal zone's
84  * thermal_zone_params.
85  */
86 static u32 estimate_sustainable_power(struct thermal_zone_device *tz)
87 {
88         u32 sustainable_power = 0;
89         struct thermal_instance *instance;
90         struct power_allocator_params *params = tz->governor_data;
91
92         list_for_each_entry(instance, &tz->thermal_instances, tz_node) {
93                 struct thermal_cooling_device *cdev = instance->cdev;
94                 u32 min_power;
95
96                 if (instance->trip != params->trip_max_desired_temperature)
97                         continue;
98
99                 if (power_actor_get_min_power(cdev, tz, &min_power))
100                         continue;
101
102                 sustainable_power += min_power;
103         }
104
105         return sustainable_power;
106 }
107
108 /**
109  * estimate_pid_constants() - Estimate the constants for the PID controller
110  * @tz:         thermal zone for which to estimate the constants
111  * @sustainable_power:  sustainable power for the thermal zone
112  * @trip_switch_on:     trip point number for the switch on temperature
113  * @control_temp:       target temperature for the power allocator governor
114  * @force:      whether to force the update of the constants
115  *
116  * This function is used to update the estimation of the PID
117  * controller constants in struct thermal_zone_parameters.
118  * Sustainable power is provided in case it was estimated.  The
119  * estimated sustainable_power should not be stored in the
120  * thermal_zone_parameters so it has to be passed explicitly to this
121  * function.
122  *
123  * If @force is not set, the values in the thermal zone's parameters
124  * are preserved if they are not zero.  If @force is set, the values
125  * in thermal zone's parameters are overwritten.
126  */
127 static void estimate_pid_constants(struct thermal_zone_device *tz,
128                                    u32 sustainable_power, int trip_switch_on,
129                                    int control_temp, bool force)
130 {
131         int ret;
132         int switch_on_temp;
133         u32 temperature_threshold;
134
135         ret = tz->ops->get_trip_temp(tz, trip_switch_on, &switch_on_temp);
136         if (ret)
137                 switch_on_temp = 0;
138
139         temperature_threshold = control_temp - switch_on_temp;
140
141         if (!tz->tzp->k_po || force)
142                 tz->tzp->k_po = int_to_frac(sustainable_power) /
143                         temperature_threshold;
144
145         if (!tz->tzp->k_pu || force)
146                 tz->tzp->k_pu = int_to_frac(2 * sustainable_power) /
147                         temperature_threshold;
148
149         if (!tz->tzp->k_i || force)
150                 tz->tzp->k_i = int_to_frac(10) / 1000;
151         /*
152          * The default for k_d and integral_cutoff is 0, so we can
153          * leave them as they are.
154          */
155 }
156
157 /**
158  * pid_controller() - PID controller
159  * @tz: thermal zone we are operating in
160  * @current_temp:       the current temperature in millicelsius
161  * @control_temp:       the target temperature in millicelsius
162  * @max_allocatable_power:      maximum allocatable power for this thermal zone
163  *
164  * This PID controller increases the available power budget so that the
165  * temperature of the thermal zone gets as close as possible to
166  * @control_temp and limits the power if it exceeds it.  k_po is the
167  * proportional term when we are overshooting, k_pu is the
168  * proportional term when we are undershooting.  integral_cutoff is a
169  * threshold below which we stop accumulating the error.  The
170  * accumulated error is only valid if the requested power will make
171  * the system warmer.  If the system is mostly idle, there's no point
172  * in accumulating positive error.
173  *
174  * Return: The power budget for the next period.
175  */
176 static u32 pid_controller(struct thermal_zone_device *tz,
177                           int current_temp,
178                           int control_temp,
179                           u32 max_allocatable_power)
180 {
181         s64 p, i, d, power_range;
182         s32 err, max_power_frac;
183         u32 sustainable_power;
184         struct power_allocator_params *params = tz->governor_data;
185
186         max_power_frac = int_to_frac(max_allocatable_power);
187
188         if (tz->tzp->sustainable_power) {
189                 sustainable_power = tz->tzp->sustainable_power;
190         } else {
191                 sustainable_power = estimate_sustainable_power(tz);
192                 estimate_pid_constants(tz, sustainable_power,
193                                        params->trip_switch_on, control_temp,
194                                        true);
195         }
196
197         err = control_temp - current_temp;
198         err = int_to_frac(err);
199
200         /* Calculate the proportional term */
201         p = mul_frac(err < 0 ? tz->tzp->k_po : tz->tzp->k_pu, err);
202
203         /*
204          * Calculate the integral term
205          *
206          * if the error is less than cut off allow integration (but
207          * the integral is limited to max power)
208          */
209         i = mul_frac(tz->tzp->k_i, params->err_integral);
210
211         if (err < int_to_frac(tz->tzp->integral_cutoff)) {
212                 s64 i_next = i + mul_frac(tz->tzp->k_i, err);
213
214                 if (abs64(i_next) < max_power_frac) {
215                         i = i_next;
216                         params->err_integral += err;
217                 }
218         }
219
220         /*
221          * Calculate the derivative term
222          *
223          * We do err - prev_err, so with a positive k_d, a decreasing
224          * error (i.e. driving closer to the line) results in less
225          * power being applied, slowing down the controller)
226          */
227         d = mul_frac(tz->tzp->k_d, err - params->prev_err);
228         d = div_frac(d, tz->passive_delay);
229         params->prev_err = err;
230
231         power_range = p + i + d;
232
233         /* feed-forward the known sustainable dissipatable power */
234         power_range = sustainable_power + frac_to_int(power_range);
235
236         power_range = clamp(power_range, (s64)0, (s64)max_allocatable_power);
237
238         trace_thermal_power_allocator_pid(tz, frac_to_int(err),
239                                           frac_to_int(params->err_integral),
240                                           frac_to_int(p), frac_to_int(i),
241                                           frac_to_int(d), power_range);
242
243         return power_range;
244 }
245
246 /**
247  * divvy_up_power() - divvy the allocated power between the actors
248  * @req_power:  each actor's requested power
249  * @max_power:  each actor's maximum available power
250  * @num_actors: size of the @req_power, @max_power and @granted_power's array
251  * @total_req_power: sum of @req_power
252  * @power_range:        total allocated power
253  * @granted_power:      output array: each actor's granted power
254  * @extra_actor_power:  an appropriately sized array to be used in the
255  *                      function as temporary storage of the extra power given
256  *                      to the actors
257  *
258  * This function divides the total allocated power (@power_range)
259  * fairly between the actors.  It first tries to give each actor a
260  * share of the @power_range according to how much power it requested
261  * compared to the rest of the actors.  For example, if only one actor
262  * requests power, then it receives all the @power_range.  If
263  * three actors each requests 1mW, each receives a third of the
264  * @power_range.
265  *
266  * If any actor received more than their maximum power, then that
267  * surplus is re-divvied among the actors based on how far they are
268  * from their respective maximums.
269  *
270  * Granted power for each actor is written to @granted_power, which
271  * should've been allocated by the calling function.
272  */
273 static void divvy_up_power(u32 *req_power, u32 *max_power, int num_actors,
274                            u32 total_req_power, u32 power_range,
275                            u32 *granted_power, u32 *extra_actor_power)
276 {
277         u32 extra_power, capped_extra_power;
278         int i;
279
280         /*
281          * Prevent division by 0 if none of the actors request power.
282          */
283         if (!total_req_power)
284                 total_req_power = 1;
285
286         capped_extra_power = 0;
287         extra_power = 0;
288         for (i = 0; i < num_actors; i++) {
289                 u64 req_range = req_power[i] * power_range;
290
291                 granted_power[i] = DIV_ROUND_CLOSEST_ULL(req_range,
292                                                          total_req_power);
293
294                 if (granted_power[i] > max_power[i]) {
295                         extra_power += granted_power[i] - max_power[i];
296                         granted_power[i] = max_power[i];
297                 }
298
299                 extra_actor_power[i] = max_power[i] - granted_power[i];
300                 capped_extra_power += extra_actor_power[i];
301         }
302
303         if (!extra_power)
304                 return;
305
306         /*
307          * Re-divvy the reclaimed extra among actors based on
308          * how far they are from the max
309          */
310         extra_power = min(extra_power, capped_extra_power);
311         if (capped_extra_power > 0)
312                 for (i = 0; i < num_actors; i++)
313                         granted_power[i] += (extra_actor_power[i] *
314                                         extra_power) / capped_extra_power;
315 }
316
317 static int allocate_power(struct thermal_zone_device *tz,
318                           int current_temp,
319                           int control_temp)
320 {
321         struct thermal_instance *instance;
322         struct power_allocator_params *params = tz->governor_data;
323         u32 *req_power, *max_power, *granted_power, *extra_actor_power;
324         u32 *weighted_req_power;
325         u32 total_req_power, max_allocatable_power, total_weighted_req_power;
326         u32 total_granted_power, power_range;
327         int i, num_actors, total_weight, ret = 0;
328         int trip_max_desired_temperature = params->trip_max_desired_temperature;
329
330         mutex_lock(&tz->lock);
331
332         num_actors = 0;
333         total_weight = 0;
334         list_for_each_entry(instance, &tz->thermal_instances, tz_node) {
335                 if ((instance->trip == trip_max_desired_temperature) &&
336                     cdev_is_power_actor(instance->cdev)) {
337                         num_actors++;
338                         total_weight += instance->weight;
339                 }
340         }
341
342         /*
343          * We need to allocate five arrays of the same size:
344          * req_power, max_power, granted_power, extra_actor_power and
345          * weighted_req_power.  They are going to be needed until this
346          * function returns.  Allocate them all in one go to simplify
347          * the allocation and deallocation logic.
348          */
349         BUILD_BUG_ON(sizeof(*req_power) != sizeof(*max_power));
350         BUILD_BUG_ON(sizeof(*req_power) != sizeof(*granted_power));
351         BUILD_BUG_ON(sizeof(*req_power) != sizeof(*extra_actor_power));
352         BUILD_BUG_ON(sizeof(*req_power) != sizeof(*weighted_req_power));
353         req_power = kcalloc(num_actors * 5, sizeof(*req_power), GFP_KERNEL);
354         if (!req_power) {
355                 ret = -ENOMEM;
356                 goto unlock;
357         }
358
359         max_power = &req_power[num_actors];
360         granted_power = &req_power[2 * num_actors];
361         extra_actor_power = &req_power[3 * num_actors];
362         weighted_req_power = &req_power[4 * num_actors];
363
364         i = 0;
365         total_weighted_req_power = 0;
366         total_req_power = 0;
367         max_allocatable_power = 0;
368
369         list_for_each_entry(instance, &tz->thermal_instances, tz_node) {
370                 int weight;
371                 struct thermal_cooling_device *cdev = instance->cdev;
372
373                 if (instance->trip != trip_max_desired_temperature)
374                         continue;
375
376                 if (!cdev_is_power_actor(cdev))
377                         continue;
378
379                 if (cdev->ops->get_requested_power(cdev, tz, &req_power[i]))
380                         continue;
381
382                 if (!total_weight)
383                         weight = 1 << FRAC_BITS;
384                 else
385                         weight = instance->weight;
386
387                 weighted_req_power[i] = frac_to_int(weight * req_power[i]);
388
389                 if (power_actor_get_max_power(cdev, tz, &max_power[i]))
390                         continue;
391
392                 total_req_power += req_power[i];
393                 max_allocatable_power += max_power[i];
394                 total_weighted_req_power += weighted_req_power[i];
395
396                 i++;
397         }
398
399         power_range = pid_controller(tz, current_temp, control_temp,
400                                      max_allocatable_power);
401
402         divvy_up_power(weighted_req_power, max_power, num_actors,
403                        total_weighted_req_power, power_range, granted_power,
404                        extra_actor_power);
405
406         total_granted_power = 0;
407         i = 0;
408         list_for_each_entry(instance, &tz->thermal_instances, tz_node) {
409                 if (instance->trip != trip_max_desired_temperature)
410                         continue;
411
412                 if (!cdev_is_power_actor(instance->cdev))
413                         continue;
414
415                 power_actor_set_power(instance->cdev, instance,
416                                       granted_power[i]);
417                 total_granted_power += granted_power[i];
418
419                 i++;
420         }
421
422         trace_thermal_power_allocator(tz, req_power, total_req_power,
423                                       granted_power, total_granted_power,
424                                       num_actors, power_range,
425                                       max_allocatable_power, current_temp,
426                                       control_temp - current_temp);
427
428         kfree(req_power);
429 unlock:
430         mutex_unlock(&tz->lock);
431
432         return ret;
433 }
434
435 static int get_governor_trips(struct thermal_zone_device *tz,
436                               struct power_allocator_params *params)
437 {
438         int i, ret, last_passive;
439         bool found_first_passive;
440
441         found_first_passive = false;
442         last_passive = -1;
443         ret = -EINVAL;
444
445         for (i = 0; i < tz->trips; i++) {
446                 enum thermal_trip_type type;
447
448                 ret = tz->ops->get_trip_type(tz, i, &type);
449                 if (ret)
450                         return ret;
451
452                 if (!found_first_passive) {
453                         if (type == THERMAL_TRIP_PASSIVE) {
454                                 params->trip_switch_on = i;
455                                 found_first_passive = true;
456                         }
457                 } else if (type == THERMAL_TRIP_PASSIVE) {
458                         last_passive = i;
459                 } else {
460                         break;
461                 }
462         }
463
464         if (last_passive != -1) {
465                 params->trip_max_desired_temperature = last_passive;
466                 ret = 0;
467         } else {
468                 ret = -EINVAL;
469         }
470
471         return ret;
472 }
473
474 static void reset_pid_controller(struct power_allocator_params *params)
475 {
476         params->err_integral = 0;
477         params->prev_err = 0;
478 }
479
480 static void allow_maximum_power(struct thermal_zone_device *tz)
481 {
482         struct thermal_instance *instance;
483         struct power_allocator_params *params = tz->governor_data;
484
485         list_for_each_entry(instance, &tz->thermal_instances, tz_node) {
486                 if ((instance->trip != params->trip_max_desired_temperature) ||
487                     (!cdev_is_power_actor(instance->cdev)))
488                         continue;
489
490                 instance->target = 0;
491                 instance->cdev->updated = false;
492                 thermal_cdev_update(instance->cdev);
493         }
494 }
495
496 /**
497  * power_allocator_bind() - bind the power_allocator governor to a thermal zone
498  * @tz: thermal zone to bind it to
499  *
500  * Check that the thermal zone is valid for this governor, that is, it
501  * has two thermal trips.  If so, initialize the PID controller
502  * parameters and bind it to the thermal zone.
503  *
504  * Return: 0 on success, -EINVAL if the trips were invalid or -ENOMEM
505  * if we ran out of memory.
506  */
507 static int power_allocator_bind(struct thermal_zone_device *tz)
508 {
509         int ret;
510         struct power_allocator_params *params;
511         int control_temp;
512
513         if (!tz->tzp)
514                 return -EINVAL;
515
516         params = kzalloc(sizeof(*params), GFP_KERNEL);
517         if (!params)
518                 return -ENOMEM;
519
520         if (!tz->tzp->sustainable_power)
521                 dev_warn(&tz->device, "power_allocator: sustainable_power will be estimated\n");
522
523         ret = get_governor_trips(tz, params);
524         if (ret) {
525                 dev_err(&tz->device,
526                         "thermal zone %s has wrong trip setup for power allocator\n",
527                         tz->type);
528                 goto free;
529         }
530
531         ret = tz->ops->get_trip_temp(tz, params->trip_max_desired_temperature,
532                                      &control_temp);
533         if (ret)
534                 goto free;
535
536         estimate_pid_constants(tz, tz->tzp->sustainable_power,
537                                params->trip_switch_on, control_temp, false);
538         reset_pid_controller(params);
539
540         tz->governor_data = params;
541
542         return 0;
543
544 free:
545         kfree(params);
546         return ret;
547 }
548
549 static void power_allocator_unbind(struct thermal_zone_device *tz)
550 {
551         dev_dbg(&tz->device, "Unbinding from thermal zone %d\n", tz->id);
552         kfree(tz->governor_data);
553         tz->governor_data = NULL;
554 }
555
556 static int power_allocator_throttle(struct thermal_zone_device *tz, int trip)
557 {
558         int ret;
559         int switch_on_temp, control_temp, current_temp;
560         struct power_allocator_params *params = tz->governor_data;
561
562         /*
563          * We get called for every trip point but we only need to do
564          * our calculations once
565          */
566         if (trip != params->trip_max_desired_temperature)
567                 return 0;
568
569         ret = thermal_zone_get_temp(tz, &current_temp);
570         if (ret) {
571                 dev_warn(&tz->device, "Failed to get temperature: %d\n", ret);
572                 return ret;
573         }
574
575         ret = tz->ops->get_trip_temp(tz, params->trip_switch_on,
576                                      &switch_on_temp);
577         if (ret) {
578                 dev_warn(&tz->device,
579                          "Failed to get switch on temperature: %d\n", ret);
580                 return ret;
581         }
582
583         if (current_temp < switch_on_temp) {
584                 tz->passive = 0;
585                 reset_pid_controller(params);
586                 allow_maximum_power(tz);
587                 return 0;
588         }
589
590         tz->passive = 1;
591
592         ret = tz->ops->get_trip_temp(tz, params->trip_max_desired_temperature,
593                                 &control_temp);
594         if (ret) {
595                 dev_warn(&tz->device,
596                          "Failed to get the maximum desired temperature: %d\n",
597                          ret);
598                 return ret;
599         }
600
601         return allocate_power(tz, current_temp, control_temp);
602 }
603
604 static struct thermal_governor thermal_gov_power_allocator = {
605         .name           = "power_allocator",
606         .bind_to_tz     = power_allocator_bind,
607         .unbind_from_tz = power_allocator_unbind,
608         .throttle       = power_allocator_throttle,
609 };
610
611 int thermal_gov_power_allocator_register(void)
612 {
613         return thermal_register_governor(&thermal_gov_power_allocator);
614 }
615
616 void thermal_gov_power_allocator_unregister(void)
617 {
618         thermal_unregister_governor(&thermal_gov_power_allocator);
619 }