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 <dataproviders/IioEnergyMeterDataProvider.h>
18 #include <dataproviders/IioEnergyMeterDataSelector.h>
19 
20 #include <android-base/file.h>
21 #include <android-base/logging.h>
22 #include <android-base/stringprintf.h>
23 #include <android-base/strings.h>
24 #include <inttypes.h>
25 
26 namespace aidl {
27 namespace android {
28 namespace hardware {
29 namespace power {
30 namespace stats {
31 
32 using aidl::android::hardware::power::stats::IioEnergyMeterDataSelector;
33 
34 #define MAX_RAIL_NAME_LEN 50
35 #define STR(s) #s
36 #define XSTR(s) STR(s)
37 
findIioEnergyMeterNodes()38 void IioEnergyMeterDataProvider::findIioEnergyMeterNodes() {
39     struct dirent *ent;
40 
41     DIR *iioDir = opendir(kIioRootDir.c_str());
42     if (!iioDir) {
43         PLOG(ERROR) << "Error opening directory" << kIioRootDir;
44         return;
45     }
46 
47     // Find any iio:devices that match the given kDeviceNames
48     while (ent = readdir(iioDir), ent) {
49         std::string devTypeDir = ent->d_name;
50         if (devTypeDir.find(kDeviceType) != std::string::npos) {
51             std::string devicePath = kIioRootDir + devTypeDir;
52             std::string deviceNameContents;
53 
54             if (!::android::base::ReadFileToString(devicePath + kNameNode, &deviceNameContents)) {
55                 LOG(WARNING) << "Failed to read device name from " << devicePath;
56             } else {
57                 for (const auto &deviceName : kDeviceNames) {
58                     if (deviceNameContents.find(deviceName) != std::string::npos) {
59                         mDevicePaths.emplace(devicePath, deviceName);
60                     }
61                 }
62             }
63         }
64     }
65 
66     closedir(iioDir);
67     return;
68 }
69 
parseEnabledRails()70 void IioEnergyMeterDataProvider::parseEnabledRails() {
71     std::string data;
72     int32_t id = 0;
73     for (const auto &path : mDevicePaths) {
74         // Get list of enabled rails
75         if (!::android::base::ReadFileToString(path.first + kEnabledRailsNode, &data)) {
76             LOG(ERROR) << "Error reading enabled rails from " << path.first;
77             continue;
78         }
79 
80         // Build RailInfos from list of enabled rails
81         std::istringstream railNames(data);
82         std::string line;
83         while (std::getline(railNames, line)) {
84             /* Format example: CH2[VSYS_PWR_RFFE]:Cellular */
85             std::vector<std::string> words = ::android::base::Split(line, ":][");
86             if (words.size() == 4) {
87                 const std::string channelName = words[1];
88                 const std::string subsystemName = words[3];
89                 if (mChannelIds.count(channelName) == 0) {
90                     mChannelInfos.push_back(
91                             {.id = id, .name = channelName, .subsystem = subsystemName});
92                     mChannelIds.emplace(channelName, id);
93                     id++;
94                 } else {
95                     LOG(WARNING) << "There exists rails with the same name (not supported): "
96                                  << channelName << ". Only the last occurrence of rail energy will "
97                                  << "be provided.";
98                 }
99             } else {
100                 LOG(WARNING) << "Unexpected enabled rail format in " << path.first;
101             }
102         }
103     }
104 }
105 
IioEnergyMeterDataProvider(const std::vector<const std::string> & deviceNames,const bool useSelector)106 IioEnergyMeterDataProvider::IioEnergyMeterDataProvider(
107         const std::vector<const std::string> &deviceNames, const bool useSelector)
108     : kDeviceNames(std::move(deviceNames)) {
109     findIioEnergyMeterNodes();
110     if (useSelector) {
111         /* Run meter selection in constructor; object can be discarded afterwards */
112         IioEnergyMeterDataSelector selector(mDevicePaths);
113     }
114     parseEnabledRails();
115     mReading.resize(mChannelInfos.size());
116 }
117 
parseEnergyContents(const std::string & contents)118 int IioEnergyMeterDataProvider::parseEnergyContents(const std::string &contents) {
119     std::istringstream energyData(contents);
120     std::string line;
121 
122     int ret = 0;
123     uint64_t timestamp = 0;
124     bool timestampRead = false;
125 
126     while (std::getline(energyData, line)) {
127         bool parseLineSuccess = false;
128 
129         if (timestampRead == false) {
130             /* Read timestamp from boot (ms) */
131             if (sscanf(line.c_str(), "t=%" PRIu64, &timestamp) == 1) {
132                 if (timestamp == 0 || timestamp == ULLONG_MAX) {
133                     LOG(ERROR) << "Potentially wrong timestamp: " << timestamp;
134                 }
135                 timestampRead = true;
136                 parseLineSuccess = true;
137             }
138 
139         } else {
140             /* Read rail energy */
141             uint64_t energy = 0;
142             uint64_t duration = 0;
143             char railNameRaw[MAX_RAIL_NAME_LEN + 1];
144 
145             /* Format example: CH3(T=358356)[S2M_VDD_CPUCL2], 761330 */
146             if (sscanf(line.c_str(),
147                        "CH%*d(T=%" PRIu64 ")[%" XSTR(MAX_RAIL_NAME_LEN) "[^]]], %" PRIu64,
148                        &duration, railNameRaw, &energy) == 3) {
149                 std::string railName(railNameRaw);
150 
151                 /* If the count == 0, the rail may not be enabled */
152                 /* The count cannot be > 1; mChannelIds is a map */
153                 if (mChannelIds.count(railName) == 1) {
154                     size_t index = mChannelIds[railName];
155                     mReading[index].id = index;
156                     mReading[index].timestampMs = timestamp;
157                     mReading[index].durationMs = duration;
158                     mReading[index].energyUWs = energy;
159                     if (mReading[index].energyUWs == ULLONG_MAX) {
160                         LOG(ERROR) << "Potentially wrong energy value on rail: " << railName;
161                     }
162                 }
163                 parseLineSuccess = true;
164             }
165         }
166 
167         if (parseLineSuccess == false) {
168             ret = -1;
169             break;
170         }
171     }
172 
173     return ret;
174 }
175 
parseEnergyValue(std::string path)176 int IioEnergyMeterDataProvider::parseEnergyValue(std::string path) {
177     int ret = 0;
178     std::string data;
179     if (!::android::base::ReadFileToString(path + kEnergyValueNode, &data)) {
180         LOG(ERROR) << "Error reading energy value in " << path;
181         return -1;
182     }
183 
184     ret = parseEnergyContents(data);
185     if (ret != 0) {
186         LOG(ERROR) << "Unexpected format in " << path;
187     }
188     return ret;
189 }
190 
readEnergyMeter(const std::vector<int32_t> & in_channelIds,std::vector<EnergyMeasurement> * _aidl_return)191 ndk::ScopedAStatus IioEnergyMeterDataProvider::readEnergyMeter(
192         const std::vector<int32_t> &in_channelIds, std::vector<EnergyMeasurement> *_aidl_return) {
193     std::scoped_lock lock(mLock);
194 
195     for (const auto &devicePath : mDevicePaths) {
196         if (parseEnergyValue(devicePath.first) < 0) {
197             LOG(ERROR) << "Error in parsing " << devicePath.first;
198             return ndk::ScopedAStatus::ok();
199         }
200     }
201 
202     if (in_channelIds.empty()) {
203         *_aidl_return = mReading;
204     } else {
205         _aidl_return->reserve(in_channelIds.size());
206         for (const auto &id : in_channelIds) {
207             // check for invalid ids
208             if (id < 0 || id >= mChannelInfos.size()) {
209                 return ndk::ScopedAStatus(AStatus_fromExceptionCode(EX_ILLEGAL_ARGUMENT));
210             }
211 
212             _aidl_return->emplace_back(mReading[id]);
213         }
214     }
215 
216     return ndk::ScopedAStatus::ok();
217 }
218 
getEnergyMeterInfo(std::vector<Channel> * _aidl_return)219 ndk::ScopedAStatus IioEnergyMeterDataProvider::getEnergyMeterInfo(
220         std::vector<Channel> *_aidl_return) {
221     std::scoped_lock lk(mLock);
222     *_aidl_return = mChannelInfos;
223 
224     return ndk::ScopedAStatus::ok();
225 }
226 
227 }  // namespace stats
228 }  // namespace power
229 }  // namespace hardware
230 }  // namespace android
231 }  // namespace aidl
232