1 /*
2  * Copyright (C) 2020 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 
17 #include "include/PowerStatsAidl.h"
18 #include <aidl/android/hardware/power/stats/BnPowerStats.h>
19 
20 #include <android-base/chrono_utils.h>
21 #include <android-base/file.h>
22 #include <android-base/logging.h>
23 #include <android-base/stringprintf.h>
24 #include <android-base/strings.h>
25 
26 #include <inttypes.h>
27 #include <chrono>
28 #include <numeric>
29 #include <string>
30 
31 namespace aidl {
32 namespace android {
33 namespace hardware {
34 namespace power {
35 namespace stats {
36 
addStateResidencyDataProvider(std::unique_ptr<IStateResidencyDataProvider> p)37 void PowerStats::addStateResidencyDataProvider(std::unique_ptr<IStateResidencyDataProvider> p) {
38     if (!p) {
39         return;
40     }
41 
42     int32_t id = mPowerEntityInfos.size();
43     auto info = p->getInfo();
44 
45     size_t index = mStateResidencyDataProviders.size();
46     mStateResidencyDataProviders.emplace_back(std::move(p));
47 
48     for (const auto &[entityName, states] : info) {
49         PowerEntity i = {
50                 .id = id++,
51                 .name = entityName,
52                 .states = states,
53         };
54         if (states.empty()) {
55             mStateResidencyDataProviders.back()->registerStatesUpdateCallback(std::bind(
56                     &PowerStats::statesUpdate, this, std::placeholders::_1, std::placeholders::_2));
57         }
58         mPowerEntityInfos.emplace_back(i);
59         mStateResidencyDataProviderIndex.emplace_back(index);
60     }
61 }
62 
getPowerEntityInfo(std::vector<PowerEntity> * _aidl_return)63 ndk::ScopedAStatus PowerStats::getPowerEntityInfo(std::vector<PowerEntity> *_aidl_return) {
64     *_aidl_return = mPowerEntityInfos;
65     return ndk::ScopedAStatus::ok();
66 }
67 
getStateResidency(const std::vector<int32_t> & in_powerEntityIds,std::vector<StateResidencyResult> * _aidl_return)68 ndk::ScopedAStatus PowerStats::getStateResidency(const std::vector<int32_t> &in_powerEntityIds,
69                                                  std::vector<StateResidencyResult> *_aidl_return) {
70     if (mPowerEntityInfos.empty()) {
71         return ndk::ScopedAStatus::ok();
72     }
73 
74     // If in_powerEntityIds is empty then return data for all supported entities
75     if (in_powerEntityIds.empty()) {
76         std::vector<int32_t> v(mPowerEntityInfos.size());
77         std::iota(std::begin(v), std::end(v), 0);
78         return getStateResidency(v, _aidl_return);
79     }
80 
81     std::unordered_map<std::string, std::vector<StateResidency>> stateResidencies;
82 
83     for (const int32_t id : in_powerEntityIds) {
84         // check for invalid ids
85         if (id < 0 || id >= mPowerEntityInfos.size()) {
86             return ndk::ScopedAStatus(AStatus_fromExceptionCode(EX_ILLEGAL_ARGUMENT));
87         }
88 
89         // Check to see if we already have data for the given id
90         std::string powerEntityName = mPowerEntityInfos[id].name;
91         if (stateResidencies.find(powerEntityName) == stateResidencies.end()) {
92             mStateResidencyDataProviders.at(mStateResidencyDataProviderIndex.at(id))
93                     ->getStateResidencies(&stateResidencies);
94         }
95 
96         // Append results if we have them
97         auto stateResidency = stateResidencies.find(powerEntityName);
98         if (stateResidency != stateResidencies.end()) {
99             StateResidencyResult res = {
100                     .id = id,
101                     .stateResidencyData = stateResidency->second,
102             };
103             _aidl_return->emplace_back(res);
104         } else {
105             // Failed to get results for the given id.
106             LOG(ERROR) << "Failed to get results for " << powerEntityName;
107         }
108     }
109 
110     return ndk::ScopedAStatus::ok();
111 }
112 
addEnergyConsumer(std::unique_ptr<IEnergyConsumer> p)113 void PowerStats::addEnergyConsumer(std::unique_ptr<IEnergyConsumer> p) {
114     if (!p) {
115         return;
116     }
117 
118     std::pair<EnergyConsumerType, std::string> info = p->getInfo();
119 
120     int32_t count = count_if(mEnergyConsumerInfos.begin(), mEnergyConsumerInfos.end(),
121                              [&info](const EnergyConsumer &c) { return info.first == c.type; });
122     int32_t id = mEnergyConsumers.size();
123     mEnergyConsumerInfos.emplace_back(
124             EnergyConsumer{.id = id, .ordinal = count, .type = info.first, .name = info.second});
125     mEnergyConsumers.emplace_back(std::move(p));
126 }
127 
getEnergyConsumerInfo(std::vector<EnergyConsumer> * _aidl_return)128 ndk::ScopedAStatus PowerStats::getEnergyConsumerInfo(std::vector<EnergyConsumer> *_aidl_return) {
129     *_aidl_return = mEnergyConsumerInfos;
130     return ndk::ScopedAStatus::ok();
131 }
132 
getEnergyConsumed(const std::vector<int32_t> & in_energyConsumerIds,std::vector<EnergyConsumerResult> * _aidl_return)133 ndk::ScopedAStatus PowerStats::getEnergyConsumed(const std::vector<int32_t> &in_energyConsumerIds,
134                                                  std::vector<EnergyConsumerResult> *_aidl_return) {
135     if (mEnergyConsumers.empty()) {
136         return ndk::ScopedAStatus::ok();
137     }
138 
139     // If in_powerEntityIds is empty then return data for all supported energy consumers
140     if (in_energyConsumerIds.empty()) {
141         std::vector<int32_t> v(mEnergyConsumerInfos.size());
142         std::iota(std::begin(v), std::end(v), 0);
143         return getEnergyConsumed(v, _aidl_return);
144     }
145 
146     for (const auto id : in_energyConsumerIds) {
147         // check for invalid ids
148         if (id < 0 || id >= mEnergyConsumers.size()) {
149             return ndk::ScopedAStatus(AStatus_fromExceptionCode(EX_ILLEGAL_ARGUMENT));
150         }
151 
152         auto resopt = mEnergyConsumers[id]->getEnergyConsumed();
153         if (resopt) {
154             EnergyConsumerResult res = resopt.value();
155             res.id = id;
156             _aidl_return->emplace_back(res);
157         } else {
158             // Failed to get results for the given id.
159             LOG(ERROR) << "Failed to get results for " << mEnergyConsumerInfos[id].name;
160         }
161     }
162 
163     return ndk::ScopedAStatus::ok();
164 }
165 
setEnergyMeterDataProvider(std::unique_ptr<IEnergyMeterDataProvider> p)166 void PowerStats::setEnergyMeterDataProvider(std::unique_ptr<IEnergyMeterDataProvider> p) {
167     mEnergyMeterDataProvider = std::move(p);
168 }
169 
getEnergyMeterInfo(std::vector<Channel> * _aidl_return)170 ndk::ScopedAStatus PowerStats::getEnergyMeterInfo(std::vector<Channel> *_aidl_return) {
171     if (!mEnergyMeterDataProvider) {
172         return ndk::ScopedAStatus::ok();
173     }
174     return mEnergyMeterDataProvider->getEnergyMeterInfo(_aidl_return);
175 }
176 
readEnergyMeter(const std::vector<int32_t> & in_channelIds,std::vector<EnergyMeasurement> * _aidl_return)177 ndk::ScopedAStatus PowerStats::readEnergyMeter(const std::vector<int32_t> &in_channelIds,
178                                                std::vector<EnergyMeasurement> *_aidl_return) {
179     if (!mEnergyMeterDataProvider) {
180         return ndk::ScopedAStatus::ok();
181     }
182     return mEnergyMeterDataProvider->readEnergyMeter(in_channelIds, _aidl_return);
183 }
184 
statesUpdate(const std::string & entityName,const std::vector<State> & states)185 void PowerStats::statesUpdate(const std::string &entityName, const std::vector<State> &states) {
186     for (auto &powerEntityInfo : mPowerEntityInfos) {
187         if (powerEntityInfo.name == entityName) {
188             // Update only if states have not yet been set.
189             if (powerEntityInfo.states.empty()) {
190                 powerEntityInfo.states = states;
191             }
192             return;
193         }
194     }
195     LOG(WARNING) << "Attempt to update a non-existent entry: " << entityName;
196 }
197 
getEntityStateNames(std::unordered_map<int32_t,std::string> * entityNames,std::unordered_map<int32_t,std::unordered_map<int32_t,std::string>> * stateNames)198 void PowerStats::getEntityStateNames(
199         std::unordered_map<int32_t, std::string> *entityNames,
200         std::unordered_map<int32_t, std::unordered_map<int32_t, std::string>> *stateNames) {
201     std::vector<PowerEntity> infos;
202     getPowerEntityInfo(&infos);
203 
204     for (const auto &info : infos) {
205         entityNames->emplace(info.id, info.name);
206         stateNames->emplace(info.id, std::unordered_map<int32_t, std::string>());
207         auto &entityStateNames = stateNames->at(info.id);
208         for (const auto &state : info.states) {
209             entityStateNames.emplace(state.id, state.name);
210         }
211     }
212 }
213 
getChannelNames(std::unordered_map<int32_t,std::string> * channelNames)214 void PowerStats::getChannelNames(std::unordered_map<int32_t, std::string> *channelNames) {
215     std::vector<Channel> infos;
216     getEnergyMeterInfo(&infos);
217 
218     for (const auto &info : infos) {
219         channelNames->emplace(info.id, "[" + info.name + "]:" + info.subsystem);
220     }
221 }
222 
dumpEnergyMeter(std::ostringstream & oss,bool delta)223 void PowerStats::dumpEnergyMeter(std::ostringstream &oss, bool delta) {
224     const char *headerFormat = "  %32s   %18s\n";
225     const char *dataFormat = "  %32s   %14.2f mWs\n";
226     const char *headerFormatDelta = "  %32s   %18s (%14s)\n";
227     const char *dataFormatDelta = "  %32s   %14.2f mWs (%14.2f)\n";
228 
229     std::unordered_map<int32_t, std::string> channelNames;
230     getChannelNames(&channelNames);
231 
232     oss << "\n============= PowerStats HAL 2.0 energy meter ==============\n";
233 
234     std::vector<EnergyMeasurement> energyData;
235     readEnergyMeter({}, &energyData);
236 
237     if (delta) {
238         static std::vector<EnergyMeasurement> prevEnergyData;
239         ::android::base::boot_clock::time_point curTime = ::android::base::boot_clock::now();
240         static ::android::base::boot_clock::time_point prevTime = curTime;
241 
242         oss << "Elapsed time: "
243             << std::chrono::duration_cast<std::chrono::milliseconds>(curTime - prevTime).count()
244             << " ms\n";
245 
246         oss << ::android::base::StringPrintf(headerFormatDelta, "Channel", "Cumulative Energy",
247                                              "Delta   ");
248 
249         std::unordered_map<int32_t, int64_t> prevEnergyDataMap;
250         for (const auto &data : prevEnergyData) {
251             prevEnergyDataMap.emplace(data.id, data.energyUWs);
252         }
253 
254         for (const auto &data : energyData) {
255             auto prevEnergyDataIt = prevEnergyDataMap.find(data.id);
256             int64_t deltaEnergy = 0;
257             if (prevEnergyDataIt != prevEnergyDataMap.end()) {
258                 deltaEnergy = data.energyUWs - prevEnergyDataIt->second;
259             }
260 
261             oss << ::android::base::StringPrintf(dataFormatDelta, channelNames.at(data.id).c_str(),
262                                                  static_cast<float>(data.energyUWs) / 1000.0,
263                                                  static_cast<float>(deltaEnergy) / 1000.0);
264         }
265 
266         prevEnergyData = energyData;
267         prevTime = curTime;
268     } else {
269         oss << ::android::base::StringPrintf(headerFormat, "Channel", "Cumulative Energy");
270 
271         for (const auto &data : energyData) {
272             oss << ::android::base::StringPrintf(dataFormat, channelNames.at(data.id).c_str(),
273                                                  static_cast<float>(data.energyUWs) / 1000.0);
274         }
275     }
276 
277     oss << "========== End of PowerStats HAL 2.0 energy meter ==========\n";
278 }
279 
dumpStateResidency(std::ostringstream & oss,bool delta)280 void PowerStats::dumpStateResidency(std::ostringstream &oss, bool delta) {
281     const char *headerFormat = "  %16s   %18s   %16s   %15s   %17s\n";
282     const char *dataFormat =
283             "  %16s   %18s   %13" PRIu64 " ms   %15" PRIu64 "   %14" PRIu64 " ms\n";
284     const char *headerFormatDelta = "  %16s   %18s   %16s (%14s)   %15s (%16s)   %17s (%14s)\n";
285     const char *dataFormatDelta = "  %16s   %18s   %13" PRIu64 " ms (%14" PRId64 ")   %15" PRIu64
286                                   " (%16" PRId64 ")   %14" PRIu64 " ms (%14" PRId64 ")\n";
287 
288     // Construct maps to entity and state names
289     std::unordered_map<int32_t, std::string> entityNames;
290     std::unordered_map<int32_t, std::unordered_map<int32_t, std::string>> stateNames;
291     getEntityStateNames(&entityNames, &stateNames);
292 
293     oss << "\n============= PowerStats HAL 2.0 state residencies ==============\n";
294 
295     std::vector<StateResidencyResult> results;
296     getStateResidency({}, &results);
297 
298     if (delta) {
299         static std::vector<StateResidencyResult> prevResults;
300         ::android::base::boot_clock::time_point curTime = ::android::base::boot_clock::now();
301         static ::android::base::boot_clock::time_point prevTime = curTime;
302 
303         oss << "Elapsed time: "
304             << std::chrono::duration_cast<std::chrono::milliseconds>(curTime - prevTime).count()
305             << " ms\n";
306 
307         oss << ::android::base::StringPrintf(headerFormatDelta, "Entity", "State", "Total time",
308                                              "Delta   ", "Total entries", "Delta   ",
309                                              "Last entry tstamp", "Delta ");
310 
311         // Process prevResults into a 2-tier lookup table for easy reference
312         std::unordered_map<int32_t, std::unordered_map<int32_t, StateResidency>> prevResultsMap;
313         for (const auto &prevResult : prevResults) {
314             prevResultsMap.emplace(prevResult.id, std::unordered_map<int32_t, StateResidency>());
315             for (auto stateResidency : prevResult.stateResidencyData) {
316                 prevResultsMap.at(prevResult.id).emplace(stateResidency.id, stateResidency);
317             }
318         }
319 
320         // Iterate over the new result data (one "result" per entity)
321         for (const auto &result : results) {
322             const char *entityName = entityNames.at(result.id).c_str();
323 
324             // Look up previous result data for the same entity
325             auto prevEntityResultIt = prevResultsMap.find(result.id);
326 
327             // Iterate over individual states within the current entity's new result
328             for (const auto &stateResidency : result.stateResidencyData) {
329                 const char *stateName = stateNames.at(result.id).at(stateResidency.id).c_str();
330 
331                 // If a previous result was found for the same entity, see if that
332                 // result also contains data for the current state
333                 int64_t deltaTotalTime = 0;
334                 int64_t deltaTotalCount = 0;
335                 int64_t deltaTimestamp = 0;
336                 if (prevEntityResultIt != prevResultsMap.end()) {
337                     auto prevStateResidencyIt = prevEntityResultIt->second.find(stateResidency.id);
338                     // If a previous result was found for the current entity and state, calculate
339                     // the deltas and display them along with new result
340                     if (prevStateResidencyIt != prevEntityResultIt->second.end()) {
341                         deltaTotalTime = stateResidency.totalTimeInStateMs -
342                                          prevStateResidencyIt->second.totalTimeInStateMs;
343                         deltaTotalCount = stateResidency.totalStateEntryCount -
344                                           prevStateResidencyIt->second.totalStateEntryCount;
345                         deltaTimestamp = stateResidency.lastEntryTimestampMs -
346                                          prevStateResidencyIt->second.lastEntryTimestampMs;
347                     }
348                 }
349 
350                 oss << ::android::base::StringPrintf(
351                         dataFormatDelta, entityName, stateName, stateResidency.totalTimeInStateMs,
352                         deltaTotalTime, stateResidency.totalStateEntryCount, deltaTotalCount,
353                         stateResidency.lastEntryTimestampMs, deltaTimestamp);
354             }
355         }
356 
357         prevResults = results;
358         prevTime = curTime;
359     } else {
360         oss << ::android::base::StringPrintf(headerFormat, "Entity", "State", "Total time",
361                                              "Total entries", "Last entry tstamp");
362         for (const auto &result : results) {
363             for (const auto &stateResidency : result.stateResidencyData) {
364                 oss << ::android::base::StringPrintf(
365                         dataFormat, entityNames.at(result.id).c_str(),
366                         stateNames.at(result.id).at(stateResidency.id).c_str(),
367                         stateResidency.totalTimeInStateMs, stateResidency.totalStateEntryCount,
368                         stateResidency.lastEntryTimestampMs);
369             }
370         }
371     }
372 
373     oss << "========== End of PowerStats HAL 2.0 state residencies ==========\n";
374 }
375 
dumpEnergyConsumer(std::ostringstream & oss,bool delta)376 void PowerStats::dumpEnergyConsumer(std::ostringstream &oss, bool delta) {
377     (void)delta;
378 
379     std::vector<EnergyConsumerResult> results;
380     getEnergyConsumed({}, &results);
381 
382     oss << "\n============= PowerStats HAL 2.0 energy consumers ==============\n";
383 
384     for (const auto &result : results) {
385         oss << ::android::base::StringPrintf("%-12s : %14.2f mWs\n",
386                                              mEnergyConsumers[result.id]->getConsumerName().c_str(),
387                                              static_cast<float>(result.energyUWs) / 1000.0);
388         for (auto &attr : result.attribution) {
389             oss << ::android::base::StringPrintf("  %10d - %14.2f mWs\n", attr.uid,
390                                                  static_cast<float>(attr.energyUWs) / 1000.0);
391         }
392     }
393 
394     oss << "========== End of PowerStats HAL 2.0 energy consumers ==========\n";
395 }
396 
dump(int fd,const char ** args,uint32_t numArgs)397 binder_status_t PowerStats::dump(int fd, const char **args, uint32_t numArgs) {
398     std::ostringstream oss;
399     bool delta = (numArgs == 1) && (std::string(args[0]) == "delta");
400 
401     // Generate debug output for state residency
402     dumpStateResidency(oss, delta);
403 
404     // Generate debug output for energy consumer
405     dumpEnergyConsumer(oss, delta);
406 
407     // Generate debug output energy meter
408     dumpEnergyMeter(oss, delta);
409 
410     ::android::base::WriteStringToFd(oss.str(), fd);
411     fsync(fd);
412     return STATUS_OK;
413 }
414 
415 }  // namespace stats
416 }  // namespace power
417 }  // namespace hardware
418 }  // namespace android
419 }  // namespace aidl
420