1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #define ATRACE_TAG (ATRACE_TAG_THERMAL | ATRACE_TAG_HAL)
17 
18 #include "thermal_throttling.h"
19 
20 #include <android-base/file.h>
21 #include <android-base/logging.h>
22 #include <android-base/properties.h>
23 #include <android-base/stringprintf.h>
24 #include <android-base/strings.h>
25 #include <utils/Trace.h>
26 
27 #include <iterator>
28 #include <set>
29 #include <sstream>
30 #include <thread>
31 #include <vector>
32 
33 #include "power_files.h"
34 #include "thermal_info.h"
35 
36 namespace aidl {
37 namespace android {
38 namespace hardware {
39 namespace thermal {
40 namespace implementation {
41 using ::android::base::StringPrintf;
42 
43 // To find the next PID target state according to the current thermal severity
getTargetStateOfPID(const SensorInfo & sensor_info,const ThrottlingSeverity curr_severity)44 size_t getTargetStateOfPID(const SensorInfo &sensor_info, const ThrottlingSeverity curr_severity) {
45     size_t target_state = 0;
46 
47     for (const auto &severity : ::ndk::enum_range<ThrottlingSeverity>()) {
48         size_t state = static_cast<size_t>(severity);
49         if (std::isnan(sensor_info.throttling_info->s_power[state])) {
50             continue;
51         }
52         target_state = state;
53         if (severity > curr_severity) {
54             break;
55         }
56     }
57     LOG(VERBOSE) << "PID target state = " << target_state;
58     return target_state;
59 }
60 
parseProfileProperty(std::string_view sensor_name,const SensorInfo & sensor_info)61 void ThermalThrottling::parseProfileProperty(std::string_view sensor_name,
62                                              const SensorInfo &sensor_info) {
63     if (sensor_info.throttling_info == nullptr) {
64         return;
65     }
66 
67     const std::string profile = ::android::base::GetProperty(
68             StringPrintf("vendor.thermal.%s.profile", sensor_name.data()), "");
69 
70     if (profile.empty() || sensor_info.throttling_info->profile_map.count(profile)) {
71         if (profile != thermal_throttling_status_map_[sensor_name.data()].profile) {
72             LOG(INFO) << sensor_name.data() << ": throttling profile change to "
73                       << ((profile.empty()) ? "default" : profile);
74             thermal_throttling_status_map_[sensor_name.data()].profile = profile;
75         }
76     } else {
77         LOG(ERROR) << sensor_name.data() << ": set profile to default because " << profile
78                    << " is invalid";
79         thermal_throttling_status_map_[sensor_name.data()].profile = "";
80     }
81 }
82 
clearThrottlingData(std::string_view sensor_name)83 void ThermalThrottling::clearThrottlingData(std::string_view sensor_name) {
84     if (!thermal_throttling_status_map_.count(sensor_name.data())) {
85         return;
86     }
87     std::unique_lock<std::shared_mutex> _lock(thermal_throttling_status_map_mutex_);
88 
89     for (auto &pid_power_budget_pair :
90          thermal_throttling_status_map_.at(sensor_name.data()).pid_power_budget_map) {
91         pid_power_budget_pair.second = std::numeric_limits<int>::max();
92     }
93 
94     for (auto &pid_cdev_request_pair :
95          thermal_throttling_status_map_.at(sensor_name.data()).pid_cdev_request_map) {
96         pid_cdev_request_pair.second = 0;
97     }
98 
99     for (auto &hardlimit_cdev_request_pair :
100          thermal_throttling_status_map_.at(sensor_name.data()).hardlimit_cdev_request_map) {
101         hardlimit_cdev_request_pair.second = 0;
102     }
103 
104     for (auto &throttling_release_pair :
105          thermal_throttling_status_map_.at(sensor_name.data()).throttling_release_map) {
106         throttling_release_pair.second = 0;
107     }
108 
109     thermal_throttling_status_map_[sensor_name.data()].prev_err = NAN;
110     thermal_throttling_status_map_[sensor_name.data()].i_budget = NAN;
111     thermal_throttling_status_map_[sensor_name.data()].prev_target =
112             static_cast<size_t>(ThrottlingSeverity::NONE);
113     thermal_throttling_status_map_[sensor_name.data()].prev_power_budget = NAN;
114     thermal_throttling_status_map_[sensor_name.data()].tran_cycle = 0;
115 
116     return;
117 }
118 
registerThermalThrottling(std::string_view sensor_name,const std::shared_ptr<ThrottlingInfo> & throttling_info,const std::unordered_map<std::string,CdevInfo> & cooling_device_info_map)119 bool ThermalThrottling::registerThermalThrottling(
120         std::string_view sensor_name, const std::shared_ptr<ThrottlingInfo> &throttling_info,
121         const std::unordered_map<std::string, CdevInfo> &cooling_device_info_map) {
122     if (thermal_throttling_status_map_.count(sensor_name.data())) {
123         LOG(ERROR) << "Sensor " << sensor_name.data() << " throttling map has been registered";
124         return false;
125     }
126 
127     if (throttling_info == nullptr) {
128         LOG(ERROR) << "Sensor " << sensor_name.data() << " has no throttling info";
129         return false;
130     }
131 
132     thermal_throttling_status_map_[sensor_name.data()].prev_err = NAN;
133     thermal_throttling_status_map_[sensor_name.data()].i_budget = NAN;
134     thermal_throttling_status_map_[sensor_name.data()].prev_target =
135             static_cast<size_t>(ThrottlingSeverity::NONE);
136     thermal_throttling_status_map_[sensor_name.data()].prev_power_budget = NAN;
137     thermal_throttling_status_map_[sensor_name.data()].tran_cycle = 0;
138     thermal_throttling_status_map_[sensor_name.data()].profile = "";
139 
140     for (auto &binded_cdev_pair : throttling_info->binded_cdev_info_map) {
141         if (!cooling_device_info_map.count(binded_cdev_pair.first)) {
142             LOG(ERROR) << "Could not find " << sensor_name.data() << "'s binded CDEV "
143                        << binded_cdev_pair.first;
144             return false;
145         }
146         // Register PID throttling map
147         for (const auto &cdev_weight : binded_cdev_pair.second.cdev_weight_for_pid) {
148             if (!std::isnan(cdev_weight)) {
149                 thermal_throttling_status_map_[sensor_name.data()]
150                         .pid_power_budget_map[binded_cdev_pair.first] =
151                         std::numeric_limits<int>::max();
152                 thermal_throttling_status_map_[sensor_name.data()]
153                         .pid_cdev_request_map[binded_cdev_pair.first] = 0;
154                 thermal_throttling_status_map_[sensor_name.data()]
155                         .cdev_status_map[binded_cdev_pair.first] = 0;
156                 cdev_all_request_map_[binded_cdev_pair.first].insert(0);
157                 break;
158             }
159         }
160         // Register hard limit throttling map
161         for (const auto &limit_info : binded_cdev_pair.second.limit_info) {
162             if (limit_info > 0) {
163                 thermal_throttling_status_map_[sensor_name.data()]
164                         .hardlimit_cdev_request_map[binded_cdev_pair.first] = 0;
165                 thermal_throttling_status_map_[sensor_name.data()]
166                         .cdev_status_map[binded_cdev_pair.first] = 0;
167                 cdev_all_request_map_[binded_cdev_pair.first].insert(0);
168                 break;
169             }
170         }
171         // Register throttling release map if power threshold exists
172         if (!binded_cdev_pair.second.power_rail.empty()) {
173             for (const auto &power_threshold : binded_cdev_pair.second.power_thresholds) {
174                 if (!std::isnan(power_threshold)) {
175                     thermal_throttling_status_map_[sensor_name.data()]
176                             .throttling_release_map[binded_cdev_pair.first] = 0;
177                     break;
178                 }
179             }
180         }
181     }
182     return true;
183 }
184 
185 // return power budget based on PID algo
updatePowerBudget(const Temperature & temp,const SensorInfo & sensor_info,const std::unordered_map<std::string,CdevInfo> & cooling_device_info_map,std::chrono::milliseconds time_elapsed_ms,ThrottlingSeverity curr_severity,const bool max_throttling,const std::vector<float> & sensor_predictions)186 float ThermalThrottling::updatePowerBudget(
187         const Temperature &temp, const SensorInfo &sensor_info,
188         const std::unordered_map<std::string, CdevInfo> &cooling_device_info_map,
189         std::chrono::milliseconds time_elapsed_ms, ThrottlingSeverity curr_severity,
190         const bool max_throttling, const std::vector<float> &sensor_predictions) {
191     float p = 0, d = 0;
192     float power_budget = std::numeric_limits<float>::max();
193     bool target_changed = false;
194     bool is_fully_throttle = true;
195     bool is_fully_release = true;
196     float budget_transient = 0.0;
197     auto &throttling_status = thermal_throttling_status_map_.at(temp.name);
198     const auto &profile = throttling_status.profile;
199     std::string sensor_name = temp.name;
200 
201     if (curr_severity == ThrottlingSeverity::NONE) {
202         return power_budget;
203     }
204 
205     // Go through the binded cdev, check current throttle status
206     for (const auto &binded_cdev_info_pair :
207          ((sensor_info.throttling_info->profile_map.empty() ||
208            !sensor_info.throttling_info->profile_map.contains(profile))
209                   ? sensor_info.throttling_info->binded_cdev_info_map
210                   : sensor_info.throttling_info->profile_map.at(profile))) {
211         if (throttling_status.pid_cdev_request_map.at(binded_cdev_info_pair.first) >
212             binded_cdev_info_pair.second.limit_info[static_cast<size_t>(curr_severity)]) {
213             is_fully_release = false;
214         }
215         if (throttling_status.pid_cdev_request_map.at(binded_cdev_info_pair.first) <
216             binded_cdev_info_pair.second.cdev_ceiling[static_cast<size_t>(curr_severity)]) {
217             is_fully_throttle = false;
218         }
219     }
220 
221     const auto target_state = getTargetStateOfPID(sensor_info, curr_severity);
222     if (throttling_status.prev_target != static_cast<size_t>(ThrottlingSeverity::NONE) &&
223         target_state != throttling_status.prev_target &&
224         sensor_info.throttling_info->tran_cycle > 0) {
225         throttling_status.tran_cycle = sensor_info.throttling_info->tran_cycle - 1;
226         target_changed = true;
227     }
228     throttling_status.prev_target = target_state;
229 
230     // Compute PID
231     float target = sensor_info.hot_thresholds[target_state];
232     float err = target - temp.value;
233 
234     if (max_throttling && err <= 0) {
235         return sensor_info.throttling_info->min_alloc_power[target_state];
236     }
237 
238     // Calculate P budget
239     p = err * (err < 0 ? sensor_info.throttling_info->k_po[target_state]
240                        : sensor_info.throttling_info->k_pu[target_state]);
241 
242     // Calculate I budget
243     if (std::isnan(throttling_status.i_budget)) {
244         if (std::isnan(sensor_info.throttling_info->i_default_pct)) {
245             throttling_status.i_budget = sensor_info.throttling_info->i_default;
246         } else {
247             float default_i_budget = 0.0;
248             for (const auto &binded_cdev_info_pair :
249                  sensor_info.throttling_info->binded_cdev_info_map) {
250                 int max_cdev_vote;
251                 const CdevInfo &cdev_info = cooling_device_info_map.at(binded_cdev_info_pair.first);
252                 max_cdev_vote = getCdevMaxRequest(binded_cdev_info_pair.first, &max_cdev_vote);
253                 default_i_budget += cdev_info.state2power[max_cdev_vote];
254             }
255             throttling_status.i_budget =
256                     default_i_budget * sensor_info.throttling_info->i_default_pct / 100;
257         }
258     }
259 
260     if (err < sensor_info.throttling_info->i_cutoff[target_state]) {
261         if (err < 0 &&
262             throttling_status.prev_power_budget >
263                     sensor_info.throttling_info->min_alloc_power[target_state] &&
264             !is_fully_throttle) {
265             throttling_status.i_budget += err * sensor_info.throttling_info->k_io[target_state];
266         } else if (err > 0 &&
267                    throttling_status.prev_power_budget <
268                            sensor_info.throttling_info->max_alloc_power[target_state] &&
269                    !is_fully_release) {
270             throttling_status.i_budget += err * sensor_info.throttling_info->k_iu[target_state];
271         }
272     }
273 
274     if (fabsf(throttling_status.i_budget) > sensor_info.throttling_info->i_max[target_state]) {
275         throttling_status.i_budget = sensor_info.throttling_info->i_max[target_state] *
276                                      (throttling_status.i_budget > 0 ? 1 : -1);
277     }
278 
279     // Calculate D budget
280     if (!std::isnan(throttling_status.prev_err) &&
281         time_elapsed_ms != std::chrono::milliseconds::zero()) {
282         d = sensor_info.throttling_info->k_d[target_state] * (err - throttling_status.prev_err) /
283             time_elapsed_ms.count();
284     }
285 
286     // Compute Compensation
287     float compensation = 0;
288     if (sensor_info.predictor_info != nullptr &&
289         sensor_info.predictor_info->support_pid_compensation) {
290         const std::vector<float> &prediction_weights =
291                 sensor_info.predictor_info->prediction_weights;
292         for (size_t i = 0; i < sensor_predictions.size(); ++i) {
293             float prediction_err = target - (sensor_predictions[i] * sensor_info.multiplier);
294             compensation += prediction_weights[i] * prediction_err;
295         }
296         // apply weight based on current severity level
297         compensation *= sensor_info.predictor_info->k_p_compensate[target_state];
298     }
299 
300     throttling_status.prev_err = err;
301     // Calculate power budget
302     power_budget = sensor_info.throttling_info->s_power[target_state] + p +
303                    throttling_status.i_budget + d + compensation;
304 
305     power_budget =
306             std::clamp(power_budget, sensor_info.throttling_info->min_alloc_power[target_state],
307                        sensor_info.throttling_info->max_alloc_power[target_state]);
308 
309     if (target_changed) {
310         throttling_status.budget_transient = throttling_status.prev_power_budget - power_budget;
311     }
312 
313     if (throttling_status.tran_cycle) {
314         budget_transient = throttling_status.budget_transient *
315                            ((static_cast<float>(throttling_status.tran_cycle) /
316                              static_cast<float>(sensor_info.throttling_info->tran_cycle)));
317         power_budget += budget_transient;
318         throttling_status.tran_cycle--;
319     }
320 
321     LOG(INFO) << temp.name << " power_budget=" << power_budget << " err=" << err
322               << " s_power=" << sensor_info.throttling_info->s_power[target_state]
323               << " time_elapsed_ms=" << time_elapsed_ms.count() << " p=" << p
324               << " i=" << throttling_status.i_budget << " d=" << d
325               << " compensation=" << compensation << " budget transient=" << budget_transient
326               << " control target=" << target_state;
327 
328     ATRACE_INT((sensor_name + std::string("-power_budget")).c_str(),
329                static_cast<int>(power_budget));
330     ATRACE_INT((sensor_name + std::string("-s_power")).c_str(),
331                static_cast<int>(sensor_info.throttling_info->s_power[target_state]));
332     ATRACE_INT((sensor_name + std::string("-time_elapsed_ms")).c_str(),
333                static_cast<int>(time_elapsed_ms.count()));
334     ATRACE_INT((sensor_name + std::string("-budget_transient")).c_str(),
335                static_cast<int>(budget_transient));
336     ATRACE_INT((sensor_name + std::string("-i")).c_str(),
337                static_cast<int>(throttling_status.i_budget));
338     ATRACE_INT((sensor_name + std::string("-target_state")).c_str(),
339                static_cast<int>(target_state));
340 
341     ATRACE_INT((sensor_name + std::string("-err")).c_str(),
342                static_cast<int>(err / sensor_info.multiplier));
343     ATRACE_INT((sensor_name + std::string("-p")).c_str(), static_cast<int>(p));
344     ATRACE_INT((sensor_name + std::string("-d")).c_str(), static_cast<int>(d));
345     ATRACE_INT((sensor_name + std::string("-predict_compensation")).c_str(),
346                static_cast<int>(compensation));
347     ATRACE_INT((sensor_name + std::string("-temp")).c_str(),
348                static_cast<int>(temp.value / sensor_info.multiplier));
349 
350     throttling_status.prev_power_budget = power_budget;
351 
352     return power_budget;
353 }
354 
computeExcludedPower(const SensorInfo & sensor_info,const ThrottlingSeverity curr_severity,const std::unordered_map<std::string,PowerStatus> & power_status_map,std::string * log_buf,std::string_view sensor_name)355 float ThermalThrottling::computeExcludedPower(
356         const SensorInfo &sensor_info, const ThrottlingSeverity curr_severity,
357         const std::unordered_map<std::string, PowerStatus> &power_status_map, std::string *log_buf,
358         std::string_view sensor_name) {
359     float excluded_power = 0.0;
360 
361     for (const auto &excluded_power_info_pair :
362          sensor_info.throttling_info->excluded_power_info_map) {
363         const auto last_updated_avg_power =
364                 power_status_map.at(excluded_power_info_pair.first).last_updated_avg_power;
365         if (!std::isnan(last_updated_avg_power)) {
366             excluded_power += last_updated_avg_power *
367                               excluded_power_info_pair.second[static_cast<size_t>(curr_severity)];
368             log_buf->append(StringPrintf(
369                     "(%s: %0.2f mW, cdev_weight: %f)", excluded_power_info_pair.first.c_str(),
370                     last_updated_avg_power,
371                     excluded_power_info_pair.second[static_cast<size_t>(curr_severity)]));
372 
373             ATRACE_INT((std::string(sensor_name) + std::string("-") +
374                         excluded_power_info_pair.first + std::string("-avg_power"))
375                                .c_str(),
376                        static_cast<int>(last_updated_avg_power));
377         }
378     }
379 
380     ATRACE_INT((std::string(sensor_name) + std::string("-excluded_power")).c_str(),
381                static_cast<int>(excluded_power));
382     return excluded_power;
383 }
384 
385 // Allocate power budget to binded cooling devices base on the real ODPM power data
allocatePowerToCdev(const Temperature & temp,const SensorInfo & sensor_info,const ThrottlingSeverity curr_severity,const std::chrono::milliseconds time_elapsed_ms,const std::unordered_map<std::string,PowerStatus> & power_status_map,const std::unordered_map<std::string,CdevInfo> & cooling_device_info_map,const bool max_throttling,const std::vector<float> & sensor_predictions)386 bool ThermalThrottling::allocatePowerToCdev(
387         const Temperature &temp, const SensorInfo &sensor_info,
388         const ThrottlingSeverity curr_severity, const std::chrono::milliseconds time_elapsed_ms,
389         const std::unordered_map<std::string, PowerStatus> &power_status_map,
390         const std::unordered_map<std::string, CdevInfo> &cooling_device_info_map,
391         const bool max_throttling, const std::vector<float> &sensor_predictions) {
392     float total_weight = 0;
393     float last_updated_avg_power = NAN;
394     float allocated_power = 0;
395     float allocated_weight = 0;
396     bool low_power_device_check = true;
397     bool is_budget_allocated = false;
398     bool power_data_invalid = false;
399     std::set<std::string> allocated_cdev;
400     std::string log_buf;
401 
402     std::unique_lock<std::shared_mutex> _lock(thermal_throttling_status_map_mutex_);
403     auto total_power_budget =
404             updatePowerBudget(temp, sensor_info, cooling_device_info_map, time_elapsed_ms,
405                               curr_severity, max_throttling, sensor_predictions);
406     const auto &profile = thermal_throttling_status_map_[temp.name].profile;
407 
408     if (sensor_info.throttling_info->excluded_power_info_map.size()) {
409         total_power_budget -= computeExcludedPower(sensor_info, curr_severity, power_status_map,
410                                                    &log_buf, temp.name);
411         total_power_budget = std::max(total_power_budget, 0.0f);
412         if (!log_buf.empty()) {
413             LOG(INFO) << temp.name << " power budget=" << total_power_budget << " after " << log_buf
414                       << " is excluded";
415         }
416     }
417 
418     // Go through binded cdev, compute total cdev weight
419     for (const auto &binded_cdev_info_pair :
420          (sensor_info.throttling_info->profile_map.count(profile)
421                   ? sensor_info.throttling_info->profile_map.at(profile)
422                   : sensor_info.throttling_info->binded_cdev_info_map)) {
423         const auto cdev_weight = binded_cdev_info_pair.second
424                                          .cdev_weight_for_pid[static_cast<size_t>(curr_severity)];
425         if (!binded_cdev_info_pair.second.enabled) {
426             continue;
427         } else if (std::isnan(cdev_weight) || cdev_weight == 0) {
428             allocated_cdev.insert(binded_cdev_info_pair.first);
429             continue;
430         }
431         total_weight += cdev_weight;
432     }
433 
434     while (!is_budget_allocated) {
435         for (const auto &binded_cdev_info_pair :
436              (sensor_info.throttling_info->profile_map.count(profile)
437                       ? sensor_info.throttling_info->profile_map.at(profile)
438                       : sensor_info.throttling_info->binded_cdev_info_map)) {
439             float cdev_power_adjustment = 0;
440             const auto cdev_weight =
441                     binded_cdev_info_pair.second
442                             .cdev_weight_for_pid[static_cast<size_t>(curr_severity)];
443 
444             if (allocated_cdev.count(binded_cdev_info_pair.first)) {
445                 continue;
446             }
447 
448             // Get the power data
449             if (!power_data_invalid) {
450                 if (!binded_cdev_info_pair.second.power_rail.empty()) {
451                     last_updated_avg_power =
452                             power_status_map.at(binded_cdev_info_pair.second.power_rail)
453                                     .last_updated_avg_power;
454                     if (std::isnan(last_updated_avg_power)) {
455                         LOG(VERBOSE) << "power data is under collecting";
456                         power_data_invalid = true;
457                         break;
458                     }
459 
460                     ATRACE_INT((temp.name + std::string("-") +
461                                 binded_cdev_info_pair.second.power_rail + std::string("-avg_power"))
462                                        .c_str(),
463                                static_cast<int>(last_updated_avg_power));
464                 } else {
465                     power_data_invalid = true;
466                     break;
467                 }
468                 if (binded_cdev_info_pair.second.throttling_with_power_link) {
469                     return false;
470                 }
471             }
472 
473             auto cdev_power_budget = total_power_budget * (cdev_weight / total_weight);
474             cdev_power_adjustment = cdev_power_budget - last_updated_avg_power;
475 
476             if (low_power_device_check) {
477                 // Share the budget for the CDEV which power is lower than target
478                 if (cdev_power_adjustment > 0 &&
479                     thermal_throttling_status_map_[temp.name].pid_cdev_request_map.at(
480                             binded_cdev_info_pair.first) == 0) {
481                     allocated_power += last_updated_avg_power;
482                     allocated_weight += cdev_weight;
483                     allocated_cdev.insert(binded_cdev_info_pair.first);
484                     if (!binded_cdev_info_pair.second.power_rail.empty()) {
485                         log_buf.append(StringPrintf("(%s: %0.2f mW)",
486                                                     binded_cdev_info_pair.second.power_rail.c_str(),
487                                                     last_updated_avg_power));
488                     }
489                     LOG(VERBOSE) << temp.name << " binded " << binded_cdev_info_pair.first
490                                  << " has been already at min state 0";
491                 }
492             } else {
493                 const CdevInfo &cdev_info = cooling_device_info_map.at(binded_cdev_info_pair.first);
494                 if (!binded_cdev_info_pair.second.power_rail.empty()) {
495                     log_buf.append(StringPrintf("(%s: %0.2f mW)",
496                                                 binded_cdev_info_pair.second.power_rail.c_str(),
497                                                 last_updated_avg_power));
498                 }
499                 // Ignore the power distribution if the CDEV has no space to reduce power
500                 if ((cdev_power_adjustment < 0 &&
501                      thermal_throttling_status_map_[temp.name].pid_cdev_request_map.at(
502                              binded_cdev_info_pair.first) == cdev_info.max_state)) {
503                     LOG(VERBOSE) << temp.name << " binded " << binded_cdev_info_pair.first
504                                  << " has been already at max state " << cdev_info.max_state;
505                     continue;
506                 }
507 
508                 if (!binded_cdev_info_pair.second.enabled) {
509                     cdev_power_budget = cdev_info.state2power[0];
510                 } else if (!power_data_invalid && binded_cdev_info_pair.second.power_rail != "") {
511                     auto cdev_curr_power_budget =
512                             thermal_throttling_status_map_[temp.name].pid_power_budget_map.at(
513                                     binded_cdev_info_pair.first);
514 
515                     if (last_updated_avg_power > cdev_curr_power_budget) {
516                         cdev_power_budget = cdev_curr_power_budget +=
517                                 (cdev_power_adjustment *
518                                  (cdev_curr_power_budget / last_updated_avg_power));
519                     } else {
520                         cdev_power_budget = cdev_curr_power_budget += cdev_power_adjustment;
521                     }
522                 } else {
523                     cdev_power_budget = total_power_budget * (cdev_weight / total_weight);
524                 }
525 
526                 if (!std::isnan(cdev_info.state2power[0]) &&
527                     cdev_power_budget > cdev_info.state2power[0]) {
528                     cdev_power_budget = cdev_info.state2power[0];
529                 } else if (cdev_power_budget < 0) {
530                     cdev_power_budget = 0;
531                 }
532 
533                 int max_cdev_vote;
534                 if (!getCdevMaxRequest(binded_cdev_info_pair.first, &max_cdev_vote)) {
535                     return false;
536                 }
537 
538                 const auto curr_cdev_vote =
539                         thermal_throttling_status_map_[temp.name].pid_cdev_request_map.at(
540                                 binded_cdev_info_pair.first);
541 
542                 if (!max_throttling) {
543                     if (binded_cdev_info_pair.second.max_release_step !=
544                                 std::numeric_limits<int>::max() &&
545                         (power_data_invalid || cdev_power_adjustment > 0)) {
546                         if (!power_data_invalid && curr_cdev_vote < max_cdev_vote) {
547                             cdev_power_budget = cdev_info.state2power[curr_cdev_vote];
548                             LOG(VERBOSE) << temp.name << "'s " << binded_cdev_info_pair.first
549                                          << " vote: " << curr_cdev_vote
550                                          << " is lower than max cdev vote: " << max_cdev_vote;
551                         } else {
552                             int target_release_step = binded_cdev_info_pair.second.max_release_step;
553                             while ((curr_cdev_vote - target_release_step) >
554                                            binded_cdev_info_pair.second
555                                                    .limit_info[static_cast<size_t>(
556                                                            curr_severity)] &&
557                                    cdev_info.state2power[curr_cdev_vote - target_release_step] ==
558                                            cdev_info.state2power[curr_cdev_vote]) {
559                                 target_release_step += 1;
560                             }
561                             const auto target_state =
562                                     std::max(curr_cdev_vote - target_release_step, 0);
563 
564                             cdev_power_budget = std::min(cdev_power_budget,
565                                                          cdev_info.state2power[target_state]);
566                         }
567                     }
568 
569                     if (binded_cdev_info_pair.second.max_throttle_step !=
570                                 std::numeric_limits<int>::max() &&
571                         (power_data_invalid || cdev_power_adjustment < 0)) {
572                         int target_throttle_step = binded_cdev_info_pair.second.max_throttle_step;
573                         while ((curr_cdev_vote + target_throttle_step) <
574                                        binded_cdev_info_pair.second
575                                                .cdev_ceiling[static_cast<size_t>(curr_severity)] &&
576                                cdev_info.state2power[curr_cdev_vote + target_throttle_step] ==
577                                        cdev_info.state2power[curr_cdev_vote]) {
578                             target_throttle_step += 1;
579                         }
580                         const auto target_state =
581                                 std::min(curr_cdev_vote + target_throttle_step,
582                                          binded_cdev_info_pair.second
583                                                  .cdev_ceiling[static_cast<size_t>(curr_severity)]);
584                         cdev_power_budget =
585                                 std::max(cdev_power_budget, cdev_info.state2power[target_state]);
586                     }
587                 }
588 
589                 thermal_throttling_status_map_[temp.name].pid_power_budget_map.at(
590                         binded_cdev_info_pair.first) = cdev_power_budget;
591                 LOG(VERBOSE) << temp.name << " allocate "
592                              << thermal_throttling_status_map_[temp.name].pid_power_budget_map.at(
593                                         binded_cdev_info_pair.first)
594                              << "mW to " << binded_cdev_info_pair.first
595                              << "(cdev_weight=" << cdev_weight << ")";
596             }
597         }
598 
599         if (!power_data_invalid) {
600             total_power_budget -= allocated_power;
601             total_weight -= allocated_weight;
602         }
603         allocated_power = 0;
604         allocated_weight = 0;
605 
606         if (low_power_device_check) {
607             low_power_device_check = false;
608         } else {
609             is_budget_allocated = true;
610         }
611     }
612     if (log_buf.size()) {
613         LOG(INFO) << temp.name << " binded power rails: " << log_buf;
614     }
615     return true;
616 }
617 
updateCdevRequestByPower(std::string sensor_name,const std::unordered_map<std::string,CdevInfo> & cooling_device_info_map)618 void ThermalThrottling::updateCdevRequestByPower(
619         std::string sensor_name,
620         const std::unordered_map<std::string, CdevInfo> &cooling_device_info_map) {
621     size_t i;
622 
623     std::unique_lock<std::shared_mutex> _lock(thermal_throttling_status_map_mutex_);
624     for (auto &pid_power_budget_pair :
625          thermal_throttling_status_map_[sensor_name.data()].pid_power_budget_map) {
626         const CdevInfo &cdev_info = cooling_device_info_map.at(pid_power_budget_pair.first);
627 
628         for (i = 0; i < cdev_info.state2power.size() - 1; ++i) {
629             if (pid_power_budget_pair.second >= cdev_info.state2power[i]) {
630                 break;
631             }
632         }
633         thermal_throttling_status_map_[sensor_name.data()].pid_cdev_request_map.at(
634                 pid_power_budget_pair.first) = static_cast<int>(i);
635     }
636 
637     return;
638 }
639 
updateCdevRequestBySeverity(std::string_view sensor_name,const SensorInfo & sensor_info,ThrottlingSeverity curr_severity)640 void ThermalThrottling::updateCdevRequestBySeverity(std::string_view sensor_name,
641                                                     const SensorInfo &sensor_info,
642                                                     ThrottlingSeverity curr_severity) {
643     std::unique_lock<std::shared_mutex> _lock(thermal_throttling_status_map_mutex_);
644     const auto &profile = thermal_throttling_status_map_[sensor_name.data()].profile;
645 
646     for (const auto &binded_cdev_info_pair :
647          (sensor_info.throttling_info->profile_map.count(profile)
648                   ? sensor_info.throttling_info->profile_map.at(profile)
649                   : sensor_info.throttling_info->binded_cdev_info_map)) {
650         if (!thermal_throttling_status_map_[sensor_name.data()].hardlimit_cdev_request_map.count(
651                     binded_cdev_info_pair.first)) {
652             continue;
653         }
654         thermal_throttling_status_map_[sensor_name.data()].hardlimit_cdev_request_map.at(
655                 binded_cdev_info_pair.first) =
656                 (binded_cdev_info_pair.second.enabled)
657                         ? binded_cdev_info_pair.second
658                                   .limit_info[static_cast<size_t>(curr_severity)]
659                         : 0;
660         LOG(VERBOSE) << "Hard Limit: Sensor " << sensor_name.data() << " update cdev "
661                      << binded_cdev_info_pair.first << " to "
662                      << thermal_throttling_status_map_[sensor_name.data()]
663                                 .hardlimit_cdev_request_map.at(binded_cdev_info_pair.first);
664     }
665 }
666 
throttlingReleaseUpdate(std::string_view sensor_name,const std::unordered_map<std::string,CdevInfo> & cooling_device_info_map,const std::unordered_map<std::string,PowerStatus> & power_status_map,const ThrottlingSeverity severity,const SensorInfo & sensor_info)667 bool ThermalThrottling::throttlingReleaseUpdate(
668         std::string_view sensor_name,
669         const std::unordered_map<std::string, CdevInfo> &cooling_device_info_map,
670         const std::unordered_map<std::string, PowerStatus> &power_status_map,
671         const ThrottlingSeverity severity, const SensorInfo &sensor_info) {
672     ATRACE_CALL();
673     std::unique_lock<std::shared_mutex> _lock(thermal_throttling_status_map_mutex_);
674     if (!thermal_throttling_status_map_.count(sensor_name.data())) {
675         return false;
676     }
677     auto &thermal_throttling_status = thermal_throttling_status_map_.at(sensor_name.data());
678     for (const auto &binded_cdev_info_pair : sensor_info.throttling_info->binded_cdev_info_map) {
679         float avg_power = -1;
680 
681         if (!thermal_throttling_status.throttling_release_map.count(binded_cdev_info_pair.first) ||
682             !power_status_map.count(binded_cdev_info_pair.second.power_rail)) {
683             return false;
684         }
685 
686         const auto max_state = cooling_device_info_map.at(binded_cdev_info_pair.first).max_state;
687 
688         auto &release_step =
689                 thermal_throttling_status.throttling_release_map.at(binded_cdev_info_pair.first);
690         avg_power =
691                 power_status_map.at(binded_cdev_info_pair.second.power_rail).last_updated_avg_power;
692 
693         if (std::isnan(avg_power) || avg_power < 0) {
694             release_step = binded_cdev_info_pair.second.throttling_with_power_link ? max_state : 0;
695             continue;
696         }
697 
698         bool is_over_budget = true;
699         if (!binded_cdev_info_pair.second.high_power_check) {
700             if (avg_power <
701                 binded_cdev_info_pair.second.power_thresholds[static_cast<int>(severity)]) {
702                 is_over_budget = false;
703             }
704         } else {
705             if (avg_power >
706                 binded_cdev_info_pair.second.power_thresholds[static_cast<int>(severity)]) {
707                 is_over_budget = false;
708             }
709         }
710         LOG(INFO) << sensor_name.data() << "'s " << binded_cdev_info_pair.first
711                   << " binded power rail " << binded_cdev_info_pair.second.power_rail
712                   << ": power threshold = "
713                   << binded_cdev_info_pair.second.power_thresholds[static_cast<int>(severity)]
714                   << ", avg power = " << avg_power;
715         std::string atrace_prefix = ::android::base::StringPrintf(
716                 "%s-%s", sensor_name.data(), binded_cdev_info_pair.second.power_rail.data());
717         ATRACE_INT(
718                 (atrace_prefix + std::string("-power_threshold")).c_str(),
719                 static_cast<int>(
720                         binded_cdev_info_pair.second.power_thresholds[static_cast<int>(severity)]));
721         ATRACE_INT((atrace_prefix + std::string("-avg_power")).c_str(), avg_power);
722 
723         switch (binded_cdev_info_pair.second.release_logic) {
724             case ReleaseLogic::INCREASE:
725                 if (!is_over_budget) {
726                     if (std::abs(release_step) < static_cast<int>(max_state)) {
727                         release_step--;
728                     }
729                 } else {
730                     release_step = 0;
731                 }
732                 break;
733             case ReleaseLogic::DECREASE:
734                 if (!is_over_budget) {
735                     if (release_step < static_cast<int>(max_state)) {
736                         release_step++;
737                     }
738                 } else {
739                     release_step = 0;
740                 }
741                 break;
742             case ReleaseLogic::STEPWISE:
743                 if (!is_over_budget) {
744                     if (release_step < static_cast<int>(max_state)) {
745                         release_step++;
746                     }
747                 } else {
748                     if (std::abs(release_step) < static_cast<int>(max_state)) {
749                         release_step--;
750                     }
751                 }
752                 break;
753             case ReleaseLogic::RELEASE_TO_FLOOR:
754                 release_step = is_over_budget ? 0 : max_state;
755                 break;
756             case ReleaseLogic::NONE:
757             default:
758                 break;
759         }
760     }
761     return true;
762 }
763 
thermalThrottlingUpdate(const Temperature & temp,const SensorInfo & sensor_info,const ThrottlingSeverity curr_severity,const std::chrono::milliseconds time_elapsed_ms,const std::unordered_map<std::string,PowerStatus> & power_status_map,const std::unordered_map<std::string,CdevInfo> & cooling_device_info_map,const bool max_throttling,const std::vector<float> & sensor_predictions)764 void ThermalThrottling::thermalThrottlingUpdate(
765         const Temperature &temp, const SensorInfo &sensor_info,
766         const ThrottlingSeverity curr_severity, const std::chrono::milliseconds time_elapsed_ms,
767         const std::unordered_map<std::string, PowerStatus> &power_status_map,
768         const std::unordered_map<std::string, CdevInfo> &cooling_device_info_map,
769         const bool max_throttling, const std::vector<float> &sensor_predictions) {
770     if (!thermal_throttling_status_map_.count(temp.name)) {
771         return;
772     }
773 
774     if (sensor_info.throttling_info->profile_map.size()) {
775         parseProfileProperty(temp.name.c_str(), sensor_info);
776     }
777 
778     if (thermal_throttling_status_map_[temp.name].pid_power_budget_map.size()) {
779         if (!allocatePowerToCdev(temp, sensor_info, curr_severity, time_elapsed_ms,
780                                  power_status_map, cooling_device_info_map, max_throttling,
781                                  sensor_predictions)) {
782             LOG(ERROR) << "Sensor " << temp.name << " PID request cdev failed";
783             // Clear the CDEV request if the power budget is failed to be allocated
784             for (auto &pid_cdev_request_pair :
785                  thermal_throttling_status_map_[temp.name].pid_cdev_request_map) {
786                 pid_cdev_request_pair.second = 0;
787             }
788         }
789         updateCdevRequestByPower(temp.name, cooling_device_info_map);
790     }
791 
792     if (thermal_throttling_status_map_[temp.name].hardlimit_cdev_request_map.size()) {
793         updateCdevRequestBySeverity(temp.name.c_str(), sensor_info, curr_severity);
794     }
795 
796     if (thermal_throttling_status_map_[temp.name].throttling_release_map.size()) {
797         throttlingReleaseUpdate(temp.name.c_str(), cooling_device_info_map, power_status_map,
798                                 curr_severity, sensor_info);
799     }
800 }
801 
computeCoolingDevicesRequest(std::string_view sensor_name,const SensorInfo & sensor_info,const ThrottlingSeverity curr_severity,std::vector<std::string> * cooling_devices_to_update,ThermalStatsHelper * thermal_stats_helper)802 void ThermalThrottling::computeCoolingDevicesRequest(
803         std::string_view sensor_name, const SensorInfo &sensor_info,
804         const ThrottlingSeverity curr_severity, std::vector<std::string> *cooling_devices_to_update,
805         ThermalStatsHelper *thermal_stats_helper) {
806     int release_step = 0;
807     std::unique_lock<std::shared_mutex> _lock(thermal_throttling_status_map_mutex_);
808 
809     if (!thermal_throttling_status_map_.count(sensor_name.data())) {
810         return;
811     }
812 
813     auto &thermal_throttling_status = thermal_throttling_status_map_.at(sensor_name.data());
814     const auto &cdev_release_map = thermal_throttling_status.throttling_release_map;
815 
816     const auto &profile = thermal_throttling_status_map_[sensor_name.data()].profile;
817     const auto &binded_cdev_info_map =
818             sensor_info.throttling_info->profile_map.count(profile)
819                     ? sensor_info.throttling_info->profile_map.at(profile)
820                     : sensor_info.throttling_info->binded_cdev_info_map;
821 
822     for (auto &cdev_request_pair : thermal_throttling_status.cdev_status_map) {
823         int pid_cdev_request = 0;
824         int hardlimit_cdev_request = 0;
825         const auto &cdev_name = cdev_request_pair.first;
826         const auto &binded_cdev_info = binded_cdev_info_map.at(cdev_name);
827         const auto cdev_ceiling = binded_cdev_info.cdev_ceiling[static_cast<size_t>(curr_severity)];
828         const auto cdev_floor =
829                 binded_cdev_info.cdev_floor_with_power_link[static_cast<size_t>(curr_severity)];
830         release_step = 0;
831 
832         if (thermal_throttling_status.pid_cdev_request_map.count(cdev_name)) {
833             pid_cdev_request = thermal_throttling_status.pid_cdev_request_map.at(cdev_name);
834         }
835 
836         if (thermal_throttling_status.hardlimit_cdev_request_map.count(cdev_name)) {
837             hardlimit_cdev_request =
838                     thermal_throttling_status.hardlimit_cdev_request_map.at(cdev_name);
839         }
840 
841         if (cdev_release_map.count(cdev_name)) {
842             release_step = cdev_release_map.at(cdev_name);
843         }
844 
845         LOG(VERBOSE) << sensor_name.data() << " binded cooling device " << cdev_name
846                      << "'s pid_request=" << pid_cdev_request
847                      << " hardlimit_cdev_request=" << hardlimit_cdev_request
848                      << " release_step=" << release_step
849                      << " cdev_floor_with_power_link=" << cdev_floor
850                      << " cdev_ceiling=" << cdev_ceiling;
851         std::string atrace_prefix =
852                 ::android::base::StringPrintf("%s-%s", sensor_name.data(), cdev_name.data());
853         ATRACE_INT((atrace_prefix + std::string("-pid_request")).c_str(), pid_cdev_request);
854         ATRACE_INT((atrace_prefix + std::string("-hardlimit_request")).c_str(),
855                    hardlimit_cdev_request);
856         ATRACE_INT((atrace_prefix + std::string("-release_step")).c_str(), release_step);
857         ATRACE_INT((atrace_prefix + std::string("-cdev_floor")).c_str(), cdev_floor);
858         ATRACE_INT((atrace_prefix + std::string("-cdev_ceiling")).c_str(), cdev_ceiling);
859 
860         auto request_state = std::max(pid_cdev_request, hardlimit_cdev_request);
861         if (release_step) {
862             if (release_step >= request_state) {
863                 request_state = 0;
864             } else {
865                 request_state = request_state - release_step;
866             }
867             // Only check the cdev_floor when release step is non zero
868             request_state = std::max(request_state, cdev_floor);
869         }
870         request_state = std::min(request_state, cdev_ceiling);
871         if (cdev_request_pair.second != request_state) {
872             ATRACE_INT((atrace_prefix + std::string("-final_request")).c_str(), request_state);
873             if (updateCdevMaxRequestAndNotifyIfChange(cdev_name, cdev_request_pair.second,
874                                                       request_state)) {
875                 cooling_devices_to_update->emplace_back(cdev_name);
876             }
877             cdev_request_pair.second = request_state;
878             // Update sensor cdev request time in state
879             thermal_stats_helper->updateSensorCdevRequestStats(sensor_name, cdev_name,
880                                                                cdev_request_pair.second);
881         }
882     }
883 }
884 
updateCdevMaxRequestAndNotifyIfChange(std::string_view cdev_name,int cur_request,int new_request)885 bool ThermalThrottling::updateCdevMaxRequestAndNotifyIfChange(std::string_view cdev_name,
886                                                               int cur_request, int new_request) {
887     std::unique_lock<std::shared_mutex> _lock(cdev_all_request_map_mutex_);
888     auto &request_set = cdev_all_request_map_.at(cdev_name.data());
889     int cur_max_request = (*request_set.begin());
890     // Remove old cdev request and add the new one.
891     request_set.erase(request_set.find(cur_request));
892     request_set.insert(new_request);
893     // Check if there is any change in aggregated max cdev request.
894     int new_max_request = (*request_set.begin());
895     LOG(VERBOSE) << "For cooling device [" << cdev_name.data()
896                  << "] cur_max_request is: " << cur_max_request
897                  << " new_max_request is: " << new_max_request;
898     return new_max_request != cur_max_request;
899 }
900 
getCdevMaxRequest(std::string_view cdev_name,int * max_state)901 bool ThermalThrottling::getCdevMaxRequest(std::string_view cdev_name, int *max_state) {
902     std::shared_lock<std::shared_mutex> _lock(cdev_all_request_map_mutex_);
903     if (!cdev_all_request_map_.count(cdev_name.data())) {
904         LOG(ERROR) << "Cooling device [" << cdev_name.data()
905                    << "] not present in cooling device request map";
906         return false;
907     }
908     *max_state = *cdev_all_request_map_.at(cdev_name.data()).begin();
909     return true;
910 }
911 
912 }  // namespace implementation
913 }  // namespace thermal
914 }  // namespace hardware
915 }  // namespace android
916 }  // namespace aidl
917