1 
2 /*
3  * Copyright (C) 2018 The Android Open Source Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 #define LOG_TAG "libpixelpowerstats"
18 #include <algorithm>
19 #include <thread>
20 #include <exception>
21 #include <inttypes.h>
22 #include <stdlib.h>
23 #include <android-base/file.h>
24 #include <android-base/logging.h>
25 #include <android-base/properties.h>
26 #include <android-base/strings.h>
27 #include <android-base/stringprintf.h>
28 #include "RailDataProvider.h"
29 namespace android {
30 namespace hardware {
31 namespace google {
32 namespace pixel {
33 namespace powerstats {
34 #define MAX_FILE_PATH_LEN 128
35 #define MAX_DEVICE_NAME_LEN 64
36 #define MAX_QUEUE_SIZE 8192
37 constexpr char kIioDirRoot[] = "/sys/bus/iio/devices/";
38 constexpr char kDeviceName[] = "microchip,pac1934";
39 constexpr char kDeviceType[] = "iio:device";
40 constexpr uint32_t MAX_SAMPLING_RATE = 10;
41 constexpr uint64_t WRITE_TIMEOUT_NS = 1000000000;
findIioPowerMonitorNodes()42 void RailDataProvider::findIioPowerMonitorNodes() {
43   struct dirent *ent;
44   int fd;
45   char devName[MAX_DEVICE_NAME_LEN];
46   char filePath[MAX_FILE_PATH_LEN];
47   DIR *iioDir = opendir(kIioDirRoot);
48   if (!iioDir) {
49     ALOGE("Error opening directory: %s, error: %d", kIioDirRoot, errno);
50     return;
51   }
52   while (ent = readdir(iioDir), ent) {
53     if (strcmp(ent->d_name, ".") != 0 &&
54         strcmp(ent->d_name, "..") != 0 &&
55         strlen(ent->d_name) > strlen(kDeviceType) &&
56         strncmp(ent->d_name, kDeviceType, strlen(kDeviceType)) == 0) {
57       snprintf(filePath, MAX_FILE_PATH_LEN, "%s/%s", ent->d_name, "name");
58       fd = openat(dirfd(iioDir), filePath, O_RDONLY);
59       if (fd < 0) {
60         ALOGW("Failed to open directory: %s, error: %d", filePath, errno);
61         continue;
62       }
63       if (read(fd, devName, MAX_DEVICE_NAME_LEN) < 0) {
64         ALOGW("Failed to read device name from file: %s(%d)",
65               filePath, fd);
66         close(fd);
67         continue;
68       }
69       if (strncmp(devName, kDeviceName, strlen(kDeviceName)) == 0) {
70         snprintf(filePath, MAX_FILE_PATH_LEN, "%s/%s", kIioDirRoot, ent->d_name);
71         mOdpm.devicePaths.push_back(filePath);
72       }
73       close(fd);
74     }
75   }
76   closedir(iioDir);
77   return;
78 }
parsePowerRails()79 size_t RailDataProvider::parsePowerRails() {
80   std::string data;
81   std::string railFileName;
82   std::string spsFileName;
83   uint32_t index = 0;
84   uint32_t samplingRate;
85   for (const auto &path : mOdpm.devicePaths) {
86     railFileName = path + "/enabled_rails";
87     spsFileName = path + "/sampling_rate";
88     if (!android::base::ReadFileToString(spsFileName, &data)) {
89       ALOGW("Error reading file: %s", spsFileName.c_str());
90       continue;
91     }
92     samplingRate = strtoul(data.c_str(), NULL, 10);
93     if (!samplingRate || samplingRate == ULONG_MAX) {
94       ALOGE("Error parsing: %s", spsFileName.c_str());
95       break;
96     }
97     if (!android::base::ReadFileToString(railFileName, &data)) {
98       ALOGW("Error reading file: %s", railFileName.c_str());
99       continue;
100     }
101     std::istringstream railNames(data);
102     std::string line;
103     while (std::getline(railNames, line)) {
104       std::vector<std::string> words = android::base::Split(line, ":");
105       if (words.size() == 2) {
106         mOdpm.railsInfo.emplace(words[0],
107                            RailData {
108                              .devicePath = path,
109                              .index = index,
110                              .subsysName = words[1],
111                              .samplingRate = samplingRate
112                            });
113         index++;
114       } else {
115         ALOGW("Unexpected format in file: %s", railFileName.c_str());
116       }
117     }
118   }
119   return index;
120 }
parseIioEnergyNode(std::string devName)121 int RailDataProvider::parseIioEnergyNode(std::string devName) {
122    int ret = 0;
123    std::string data;
124    std::string fileName = devName + "/energy_value";
125    if (!android::base::ReadFileToString(fileName, &data)) {
126      ALOGE("Error reading file: %s", fileName.c_str());
127      return -1;
128    }
129    std::istringstream energyData(data);
130    std::string line;
131    uint64_t timestamp = 0;
132    bool timestampRead = false;
133    while (std::getline(energyData, line)) {
134      std::vector<std::string> words = android::base::Split(line, ",");
135      if (timestampRead == false) {
136        if (words.size() == 1) {
137          timestamp = strtoull(words[0].c_str(), NULL, 10);
138          if (timestamp == 0 || timestamp == ULLONG_MAX) {
139            ALOGW("Potentially wrong timestamp: %" PRIu64, timestamp);
140          }
141          timestampRead = true;
142        }
143      } else if (words.size() == 2) {
144          std::string railName = words[0];
145          if (mOdpm.railsInfo.count(railName) != 0) {
146            size_t index = mOdpm.railsInfo[railName].index;
147            mOdpm.reading[index].index = index;
148            mOdpm.reading[index].timestamp = timestamp;
149            mOdpm.reading[index].energy = strtoull(words[1].c_str(), NULL, 10);
150            if (mOdpm.reading[index].energy == ULLONG_MAX) {
151              ALOGW("Potentially wrong energy value: %" PRIu64,
152                    mOdpm.reading[index].energy);
153            }
154          }
155      } else {
156        ALOGW("Unexpected format in file: %s", fileName.c_str());
157        ret = -1;
158        break;
159      }
160    }
161    return ret;
162 }
parseIioEnergyNodes()163 Status RailDataProvider::parseIioEnergyNodes() {
164   Status ret = Status::SUCCESS;
165   if (mOdpm.hwEnabled == false) {
166     return Status::NOT_SUPPORTED;
167   }
168   for (const auto &devicePath : mOdpm.devicePaths) {
169     if(parseIioEnergyNode(devicePath) < 0) {
170       ALOGE("Error in parsing power stats");
171       ret = Status::FILESYSTEM_ERROR;
172       break;
173     }
174   }
175   return ret;
176 }
RailDataProvider()177 RailDataProvider::RailDataProvider() {
178     findIioPowerMonitorNodes();
179     size_t numRails = parsePowerRails();
180     if (mOdpm.devicePaths.empty() || numRails == 0) {
181       mOdpm.hwEnabled = false;
182     } else {
183       mOdpm.hwEnabled = true;
184       mOdpm.reading.resize(numRails);
185     }
186 }
getRailInfo(IPowerStats::getRailInfo_cb _hidl_cb)187 Return<void> RailDataProvider::getRailInfo(IPowerStats::getRailInfo_cb _hidl_cb) {
188   hidl_vec<RailInfo> rInfo;
189   Status ret = Status::SUCCESS;
190   size_t index;
191   std::lock_guard<std::mutex> _lock(mOdpm.mLock);
192   if (mOdpm.hwEnabled == false) {
193     ALOGI("getRailInfo not supported");
194     _hidl_cb(rInfo, Status::NOT_SUPPORTED);
195     return Void();
196   }
197   rInfo.resize(mOdpm.railsInfo.size());
198   for (const auto& railData : mOdpm.railsInfo) {
199     index = railData.second.index;
200     rInfo[index].railName = railData.first;
201     rInfo[index].subsysName = railData.second.subsysName;
202     rInfo[index].index = index;
203     rInfo[index].samplingRate = railData.second.samplingRate;
204   }
205   _hidl_cb(rInfo, ret);
206   return Void();
207 }
getEnergyData(const hidl_vec<uint32_t> & railIndices,IPowerStats::getEnergyData_cb _hidl_cb)208 Return<void> RailDataProvider::getEnergyData(const hidl_vec<uint32_t>& railIndices, IPowerStats::getEnergyData_cb _hidl_cb) {
209   hidl_vec<EnergyData> eVal;
210   std::lock_guard<std::mutex> _lock(mOdpm.mLock);
211   Status ret = parseIioEnergyNodes();
212   if (ret != Status::SUCCESS) {
213     _hidl_cb(eVal, ret);
214     return Void();
215   }
216   if (railIndices.size() == 0) {
217     eVal.resize(mOdpm.railsInfo.size());
218     memcpy(&eVal[0], &mOdpm.reading[0], mOdpm.reading.size() * sizeof(EnergyData));
219   } else {
220     eVal.resize(railIndices.size());
221     int i = 0;
222     for (const auto &railIndex : railIndices) {
223       if (railIndex >= mOdpm.reading.size()) {
224         ret = Status::INVALID_INPUT;
225         eVal.resize(0);
226         break;
227       }
228       memcpy(&eVal[i], &mOdpm.reading[railIndex], sizeof(EnergyData));
229       i++;
230     }
231   }
232   _hidl_cb(eVal, ret);
233   return Void();
234 }
streamEnergyData(uint32_t timeMs,uint32_t samplingRate,IPowerStats::streamEnergyData_cb _hidl_cb)235 Return<void> RailDataProvider::streamEnergyData(uint32_t timeMs, uint32_t samplingRate,
236                                 IPowerStats::streamEnergyData_cb _hidl_cb) {
237   std::lock_guard<std::mutex> _lock(mOdpm.mLock);
238   if (mOdpm.fmqSynchronized != nullptr) {
239     _hidl_cb(MessageQueueSync::Descriptor(),
240              0, 0, Status::INSUFFICIENT_RESOURCES);
241     return Void();
242   }
243   uint32_t sps = std::min(samplingRate, MAX_SAMPLING_RATE);
244   uint32_t numSamples = timeMs * sps / 1000;
245   mOdpm.fmqSynchronized.reset(new (std::nothrow) MessageQueueSync(MAX_QUEUE_SIZE, true));
246   if (mOdpm.fmqSynchronized == nullptr || mOdpm.fmqSynchronized->isValid() == false) {
247     mOdpm.fmqSynchronized = nullptr;
248     _hidl_cb(MessageQueueSync::Descriptor(),
249              0, 0, Status::INSUFFICIENT_RESOURCES);
250     return Void();
251   }
252   std::thread pollThread = std::thread([this, sps, numSamples]() {
253     uint64_t sleepTimeUs = 1000000/sps;
254     uint32_t currSamples = 0;
255     while (currSamples < numSamples) {
256       mOdpm.mLock.lock();
257       if (parseIioEnergyNodes() == Status::SUCCESS) {
258         mOdpm.fmqSynchronized->writeBlocking(&mOdpm.reading[0],
259                                              mOdpm.reading.size(), WRITE_TIMEOUT_NS);
260         mOdpm.mLock.unlock();
261         currSamples++;
262         if (usleep(sleepTimeUs) < 0) {
263           ALOGW("Sleep interrupted");
264           break;
265         }
266       } else {
267         mOdpm.mLock.unlock();
268         break;
269       }
270     }
271     mOdpm.mLock.lock();
272     mOdpm.fmqSynchronized = nullptr;
273     mOdpm.mLock.unlock();
274     return;
275   });
276   pollThread.detach();
277   _hidl_cb(*(mOdpm.fmqSynchronized)->getDesc(), numSamples,
278            mOdpm.reading.size(), Status::SUCCESS);
279   return Void();
280 }
281 }  // namespace powerstats
282 }  // namespace pixel
283 }  // namespace google
284 }  // namespace hardware
285 }  // namespace android
286