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