thermal: core: Move power_actor_set_power into IPA
[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  */
67 struct power_allocator_params {
68         bool allocated_tzp;
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 (!cdev_is_power_actor(cdev))
100                         continue;
101
102                 if (cdev->ops->state2power(cdev, instance->upper, &min_power))
103                         continue;
104
105                 sustainable_power += min_power;
106         }
107
108         return sustainable_power;
109 }
110
111 /**
112  * estimate_pid_constants() - Estimate the constants for the PID controller
113  * @tz:         thermal zone for which to estimate the constants
114  * @sustainable_power:  sustainable power for the thermal zone
115  * @trip_switch_on:     trip point number for the switch on temperature
116  * @control_temp:       target temperature for the power allocator governor
117  * @force:      whether to force the update of the constants
118  *
119  * This function is used to update the estimation of the PID
120  * controller constants in struct thermal_zone_parameters.
121  * Sustainable power is provided in case it was estimated.  The
122  * estimated sustainable_power should not be stored in the
123  * thermal_zone_parameters so it has to be passed explicitly to this
124  * function.
125  *
126  * If @force is not set, the values in the thermal zone's parameters
127  * are preserved if they are not zero.  If @force is set, the values
128  * in thermal zone's parameters are overwritten.
129  */
130 static void estimate_pid_constants(struct thermal_zone_device *tz,
131                                    u32 sustainable_power, int trip_switch_on,
132                                    int control_temp, bool force)
133 {
134         int ret;
135         int switch_on_temp;
136         u32 temperature_threshold;
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                 tz->tzp->k_i = int_to_frac(10) / 1000;
164         /*
165          * The default for k_d and integral_cutoff is 0, so we can
166          * leave them as they are.
167          */
168 }
169
170 /**
171  * pid_controller() - PID controller
172  * @tz: thermal zone we are operating in
173  * @control_temp:       the target temperature in millicelsius
174  * @max_allocatable_power:      maximum allocatable power for this thermal zone
175  *
176  * This PID controller increases the available power budget so that the
177  * temperature of the thermal zone gets as close as possible to
178  * @control_temp and limits the power if it exceeds it.  k_po is the
179  * proportional term when we are overshooting, k_pu is the
180  * proportional term when we are undershooting.  integral_cutoff is a
181  * threshold below which we stop accumulating the error.  The
182  * accumulated error is only valid if the requested power will make
183  * the system warmer.  If the system is mostly idle, there's no point
184  * in accumulating positive error.
185  *
186  * Return: The power budget for the next period.
187  */
188 static u32 pid_controller(struct thermal_zone_device *tz,
189                           int control_temp,
190                           u32 max_allocatable_power)
191 {
192         s64 p, i, d, power_range;
193         s32 err, max_power_frac;
194         u32 sustainable_power;
195         struct power_allocator_params *params = tz->governor_data;
196
197         max_power_frac = int_to_frac(max_allocatable_power);
198
199         if (tz->tzp->sustainable_power) {
200                 sustainable_power = tz->tzp->sustainable_power;
201         } else {
202                 sustainable_power = estimate_sustainable_power(tz);
203                 estimate_pid_constants(tz, sustainable_power,
204                                        params->trip_switch_on, control_temp,
205                                        true);
206         }
207
208         err = control_temp - tz->temperature;
209         err = int_to_frac(err);
210
211         /* Calculate the proportional term */
212         p = mul_frac(err < 0 ? tz->tzp->k_po : tz->tzp->k_pu, err);
213
214         /*
215          * Calculate the integral term
216          *
217          * if the error is less than cut off allow integration (but
218          * the integral is limited to max power)
219          */
220         i = mul_frac(tz->tzp->k_i, params->err_integral);
221
222         if (err < int_to_frac(tz->tzp->integral_cutoff)) {
223                 s64 i_next = i + mul_frac(tz->tzp->k_i, err);
224
225                 if (abs(i_next) < max_power_frac) {
226                         i = i_next;
227                         params->err_integral += err;
228                 }
229         }
230
231         /*
232          * Calculate the derivative term
233          *
234          * We do err - prev_err, so with a positive k_d, a decreasing
235          * error (i.e. driving closer to the line) results in less
236          * power being applied, slowing down the controller)
237          */
238         d = mul_frac(tz->tzp->k_d, err - params->prev_err);
239         d = div_frac(d, tz->passive_delay);
240         params->prev_err = err;
241
242         power_range = p + i + d;
243
244         /* feed-forward the known sustainable dissipatable power */
245         power_range = sustainable_power + frac_to_int(power_range);
246
247         power_range = clamp(power_range, (s64)0, (s64)max_allocatable_power);
248
249         trace_thermal_power_allocator_pid(tz, frac_to_int(err),
250                                           frac_to_int(params->err_integral),
251                                           frac_to_int(p), frac_to_int(i),
252                                           frac_to_int(d), power_range);
253
254         return power_range;
255 }
256
257 /**
258  * power_actor_set_power() - limit the maximum power a cooling device consumes
259  * @cdev:       pointer to &thermal_cooling_device
260  * @instance:   thermal instance to update
261  * @power:      the power in milliwatts
262  *
263  * Set the cooling device to consume at most @power milliwatts. The limit is
264  * expected to be a cap at the maximum power consumption.
265  *
266  * Return: 0 on success, -EINVAL if the cooling device does not
267  * implement the power actor API or -E* for other failures.
268  */
269 static int
270 power_actor_set_power(struct thermal_cooling_device *cdev,
271                       struct thermal_instance *instance, u32 power)
272 {
273         unsigned long state;
274         int ret;
275
276         ret = cdev->ops->power2state(cdev, power, &state);
277         if (ret)
278                 return ret;
279
280         instance->target = clamp_val(state, instance->lower, instance->upper);
281         mutex_lock(&cdev->lock);
282         cdev->updated = false;
283         mutex_unlock(&cdev->lock);
284         thermal_cdev_update(cdev);
285
286         return 0;
287 }
288
289 /**
290  * divvy_up_power() - divvy the allocated power between the actors
291  * @req_power:  each actor's requested power
292  * @max_power:  each actor's maximum available power
293  * @num_actors: size of the @req_power, @max_power and @granted_power's array
294  * @total_req_power: sum of @req_power
295  * @power_range:        total allocated power
296  * @granted_power:      output array: each actor's granted power
297  * @extra_actor_power:  an appropriately sized array to be used in the
298  *                      function as temporary storage of the extra power given
299  *                      to the actors
300  *
301  * This function divides the total allocated power (@power_range)
302  * fairly between the actors.  It first tries to give each actor a
303  * share of the @power_range according to how much power it requested
304  * compared to the rest of the actors.  For example, if only one actor
305  * requests power, then it receives all the @power_range.  If
306  * three actors each requests 1mW, each receives a third of the
307  * @power_range.
308  *
309  * If any actor received more than their maximum power, then that
310  * surplus is re-divvied among the actors based on how far they are
311  * from their respective maximums.
312  *
313  * Granted power for each actor is written to @granted_power, which
314  * should've been allocated by the calling function.
315  */
316 static void divvy_up_power(u32 *req_power, u32 *max_power, int num_actors,
317                            u32 total_req_power, u32 power_range,
318                            u32 *granted_power, u32 *extra_actor_power)
319 {
320         u32 extra_power, capped_extra_power;
321         int i;
322
323         /*
324          * Prevent division by 0 if none of the actors request power.
325          */
326         if (!total_req_power)
327                 total_req_power = 1;
328
329         capped_extra_power = 0;
330         extra_power = 0;
331         for (i = 0; i < num_actors; i++) {
332                 u64 req_range = (u64)req_power[i] * power_range;
333
334                 granted_power[i] = DIV_ROUND_CLOSEST_ULL(req_range,
335                                                          total_req_power);
336
337                 if (granted_power[i] > max_power[i]) {
338                         extra_power += granted_power[i] - max_power[i];
339                         granted_power[i] = max_power[i];
340                 }
341
342                 extra_actor_power[i] = max_power[i] - granted_power[i];
343                 capped_extra_power += extra_actor_power[i];
344         }
345
346         if (!extra_power)
347                 return;
348
349         /*
350          * Re-divvy the reclaimed extra among actors based on
351          * how far they are from the max
352          */
353         extra_power = min(extra_power, capped_extra_power);
354         if (capped_extra_power > 0)
355                 for (i = 0; i < num_actors; i++)
356                         granted_power[i] += (extra_actor_power[i] *
357                                         extra_power) / capped_extra_power;
358 }
359
360 static int allocate_power(struct thermal_zone_device *tz,
361                           int control_temp)
362 {
363         struct thermal_instance *instance;
364         struct power_allocator_params *params = tz->governor_data;
365         u32 *req_power, *max_power, *granted_power, *extra_actor_power;
366         u32 *weighted_req_power;
367         u32 total_req_power, max_allocatable_power, total_weighted_req_power;
368         u32 total_granted_power, power_range;
369         int i, num_actors, total_weight, ret = 0;
370         int trip_max_desired_temperature = params->trip_max_desired_temperature;
371
372         mutex_lock(&tz->lock);
373
374         num_actors = 0;
375         total_weight = 0;
376         list_for_each_entry(instance, &tz->thermal_instances, tz_node) {
377                 if ((instance->trip == trip_max_desired_temperature) &&
378                     cdev_is_power_actor(instance->cdev)) {
379                         num_actors++;
380                         total_weight += instance->weight;
381                 }
382         }
383
384         if (!num_actors) {
385                 ret = -ENODEV;
386                 goto unlock;
387         }
388
389         /*
390          * We need to allocate five arrays of the same size:
391          * req_power, max_power, granted_power, extra_actor_power and
392          * weighted_req_power.  They are going to be needed until this
393          * function returns.  Allocate them all in one go to simplify
394          * the allocation and deallocation logic.
395          */
396         BUILD_BUG_ON(sizeof(*req_power) != sizeof(*max_power));
397         BUILD_BUG_ON(sizeof(*req_power) != sizeof(*granted_power));
398         BUILD_BUG_ON(sizeof(*req_power) != sizeof(*extra_actor_power));
399         BUILD_BUG_ON(sizeof(*req_power) != sizeof(*weighted_req_power));
400         req_power = kcalloc(num_actors * 5, sizeof(*req_power), GFP_KERNEL);
401         if (!req_power) {
402                 ret = -ENOMEM;
403                 goto unlock;
404         }
405
406         max_power = &req_power[num_actors];
407         granted_power = &req_power[2 * num_actors];
408         extra_actor_power = &req_power[3 * num_actors];
409         weighted_req_power = &req_power[4 * num_actors];
410
411         i = 0;
412         total_weighted_req_power = 0;
413         total_req_power = 0;
414         max_allocatable_power = 0;
415
416         list_for_each_entry(instance, &tz->thermal_instances, tz_node) {
417                 int weight;
418                 struct thermal_cooling_device *cdev = instance->cdev;
419
420                 if (instance->trip != trip_max_desired_temperature)
421                         continue;
422
423                 if (!cdev_is_power_actor(cdev))
424                         continue;
425
426                 if (cdev->ops->get_requested_power(cdev, &req_power[i]))
427                         continue;
428
429                 if (!total_weight)
430                         weight = 1 << FRAC_BITS;
431                 else
432                         weight = instance->weight;
433
434                 weighted_req_power[i] = frac_to_int(weight * req_power[i]);
435
436                 if (cdev->ops->state2power(cdev, instance->lower,
437                                            &max_power[i]))
438                         continue;
439
440                 total_req_power += req_power[i];
441                 max_allocatable_power += max_power[i];
442                 total_weighted_req_power += weighted_req_power[i];
443
444                 i++;
445         }
446
447         power_range = pid_controller(tz, control_temp, max_allocatable_power);
448
449         divvy_up_power(weighted_req_power, max_power, num_actors,
450                        total_weighted_req_power, power_range, granted_power,
451                        extra_actor_power);
452
453         total_granted_power = 0;
454         i = 0;
455         list_for_each_entry(instance, &tz->thermal_instances, tz_node) {
456                 if (instance->trip != trip_max_desired_temperature)
457                         continue;
458
459                 if (!cdev_is_power_actor(instance->cdev))
460                         continue;
461
462                 power_actor_set_power(instance->cdev, instance,
463                                       granted_power[i]);
464                 total_granted_power += granted_power[i];
465
466                 i++;
467         }
468
469         trace_thermal_power_allocator(tz, req_power, total_req_power,
470                                       granted_power, total_granted_power,
471                                       num_actors, power_range,
472                                       max_allocatable_power, tz->temperature,
473                                       control_temp - tz->temperature);
474
475         kfree(req_power);
476 unlock:
477         mutex_unlock(&tz->lock);
478
479         return ret;
480 }
481
482 /**
483  * get_governor_trips() - get the number of the two trip points that are key for this governor
484  * @tz: thermal zone to operate on
485  * @params:     pointer to private data for this governor
486  *
487  * The power allocator governor works optimally with two trips points:
488  * a "switch on" trip point and a "maximum desired temperature".  These
489  * are defined as the first and last passive trip points.
490  *
491  * If there is only one trip point, then that's considered to be the
492  * "maximum desired temperature" trip point and the governor is always
493  * on.  If there are no passive or active trip points, then the
494  * governor won't do anything.  In fact, its throttle function
495  * won't be called at all.
496  */
497 static void get_governor_trips(struct thermal_zone_device *tz,
498                                struct power_allocator_params *params)
499 {
500         int i, last_active, last_passive;
501         bool found_first_passive;
502
503         found_first_passive = false;
504         last_active = INVALID_TRIP;
505         last_passive = INVALID_TRIP;
506
507         for (i = 0; i < tz->trips; i++) {
508                 enum thermal_trip_type type;
509                 int ret;
510
511                 ret = tz->ops->get_trip_type(tz, i, &type);
512                 if (ret) {
513                         dev_warn(&tz->device,
514                                  "Failed to get trip point %d type: %d\n", i,
515                                  ret);
516                         continue;
517                 }
518
519                 if (type == THERMAL_TRIP_PASSIVE) {
520                         if (!found_first_passive) {
521                                 params->trip_switch_on = i;
522                                 found_first_passive = true;
523                         } else  {
524                                 last_passive = i;
525                         }
526                 } else if (type == THERMAL_TRIP_ACTIVE) {
527                         last_active = i;
528                 } else {
529                         break;
530                 }
531         }
532
533         if (last_passive != INVALID_TRIP) {
534                 params->trip_max_desired_temperature = last_passive;
535         } else if (found_first_passive) {
536                 params->trip_max_desired_temperature = params->trip_switch_on;
537                 params->trip_switch_on = INVALID_TRIP;
538         } else {
539                 params->trip_switch_on = INVALID_TRIP;
540                 params->trip_max_desired_temperature = last_active;
541         }
542 }
543
544 static void reset_pid_controller(struct power_allocator_params *params)
545 {
546         params->err_integral = 0;
547         params->prev_err = 0;
548 }
549
550 static void allow_maximum_power(struct thermal_zone_device *tz)
551 {
552         struct thermal_instance *instance;
553         struct power_allocator_params *params = tz->governor_data;
554
555         mutex_lock(&tz->lock);
556         list_for_each_entry(instance, &tz->thermal_instances, tz_node) {
557                 if ((instance->trip != params->trip_max_desired_temperature) ||
558                     (!cdev_is_power_actor(instance->cdev)))
559                         continue;
560
561                 instance->target = 0;
562                 mutex_lock(&instance->cdev->lock);
563                 instance->cdev->updated = false;
564                 mutex_unlock(&instance->cdev->lock);
565                 thermal_cdev_update(instance->cdev);
566         }
567         mutex_unlock(&tz->lock);
568 }
569
570 /**
571  * power_allocator_bind() - bind the power_allocator governor to a thermal zone
572  * @tz: thermal zone to bind it to
573  *
574  * Initialize the PID controller parameters and bind it to the thermal
575  * zone.
576  *
577  * Return: 0 on success, or -ENOMEM if we ran out of memory.
578  */
579 static int power_allocator_bind(struct thermal_zone_device *tz)
580 {
581         int ret;
582         struct power_allocator_params *params;
583         int control_temp;
584
585         params = kzalloc(sizeof(*params), GFP_KERNEL);
586         if (!params)
587                 return -ENOMEM;
588
589         if (!tz->tzp) {
590                 tz->tzp = kzalloc(sizeof(*tz->tzp), GFP_KERNEL);
591                 if (!tz->tzp) {
592                         ret = -ENOMEM;
593                         goto free_params;
594                 }
595
596                 params->allocated_tzp = true;
597         }
598
599         if (!tz->tzp->sustainable_power)
600                 dev_warn(&tz->device, "power_allocator: sustainable_power will be estimated\n");
601
602         get_governor_trips(tz, params);
603
604         if (tz->trips > 0) {
605                 ret = tz->ops->get_trip_temp(tz,
606                                         params->trip_max_desired_temperature,
607                                         &control_temp);
608                 if (!ret)
609                         estimate_pid_constants(tz, tz->tzp->sustainable_power,
610                                                params->trip_switch_on,
611                                                control_temp, false);
612         }
613
614         reset_pid_controller(params);
615
616         tz->governor_data = params;
617
618         return 0;
619
620 free_params:
621         kfree(params);
622
623         return ret;
624 }
625
626 static void power_allocator_unbind(struct thermal_zone_device *tz)
627 {
628         struct power_allocator_params *params = tz->governor_data;
629
630         dev_dbg(&tz->device, "Unbinding from thermal zone %d\n", tz->id);
631
632         if (params->allocated_tzp) {
633                 kfree(tz->tzp);
634                 tz->tzp = NULL;
635         }
636
637         kfree(tz->governor_data);
638         tz->governor_data = NULL;
639 }
640
641 static int power_allocator_throttle(struct thermal_zone_device *tz, int trip)
642 {
643         int ret;
644         int switch_on_temp, control_temp;
645         struct power_allocator_params *params = tz->governor_data;
646
647         /*
648          * We get called for every trip point but we only need to do
649          * our calculations once
650          */
651         if (trip != params->trip_max_desired_temperature)
652                 return 0;
653
654         ret = tz->ops->get_trip_temp(tz, params->trip_switch_on,
655                                      &switch_on_temp);
656         if (!ret && (tz->temperature < switch_on_temp)) {
657                 tz->passive = 0;
658                 reset_pid_controller(params);
659                 allow_maximum_power(tz);
660                 return 0;
661         }
662
663         tz->passive = 1;
664
665         ret = tz->ops->get_trip_temp(tz, params->trip_max_desired_temperature,
666                                 &control_temp);
667         if (ret) {
668                 dev_warn(&tz->device,
669                          "Failed to get the maximum desired temperature: %d\n",
670                          ret);
671                 return ret;
672         }
673
674         return allocate_power(tz, control_temp);
675 }
676
677 static struct thermal_governor thermal_gov_power_allocator = {
678         .name           = "power_allocator",
679         .bind_to_tz     = power_allocator_bind,
680         .unbind_from_tz = power_allocator_unbind,
681         .throttle       = power_allocator_throttle,
682 };
683 THERMAL_GOVERNOR_DECLARE(thermal_gov_power_allocator);