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