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