Connor O'Brien | 5733719 | 2018-11-20 12:49:16 -0800 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2019 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 | #define LOG_TAG "libtimeinstate" |
| 18 | |
| 19 | #include "cputimeinstate.h" |
| 20 | |
| 21 | #include <dirent.h> |
| 22 | #include <errno.h> |
| 23 | #include <inttypes.h> |
| 24 | |
| 25 | #include <mutex> |
| 26 | #include <set> |
| 27 | #include <string> |
| 28 | #include <unordered_map> |
| 29 | #include <vector> |
| 30 | |
| 31 | #include <android-base/file.h> |
| 32 | #include <android-base/parseint.h> |
| 33 | #include <android-base/stringprintf.h> |
| 34 | #include <android-base/strings.h> |
| 35 | #include <android-base/unique_fd.h> |
| 36 | #include <bpf/BpfMap.h> |
| 37 | #include <libbpf.h> |
| 38 | #include <log/log.h> |
| 39 | |
| 40 | #define BPF_FS_PATH "/sys/fs/bpf/" |
| 41 | |
| 42 | using android::base::StringPrintf; |
| 43 | using android::base::unique_fd; |
| 44 | |
| 45 | namespace android { |
| 46 | namespace bpf { |
| 47 | |
| 48 | typedef struct { |
| 49 | uint32_t uid; |
| 50 | uint32_t freq; |
| 51 | } time_key_t; |
| 52 | |
| 53 | typedef struct { |
| 54 | uint64_t ar[100]; |
| 55 | } val_t; |
| 56 | |
| 57 | static std::mutex gInitializedMutex; |
| 58 | static bool gInitialized = false; |
| 59 | static uint32_t gNPolicies = 0; |
| 60 | static std::vector<std::vector<uint32_t>> gPolicyFreqs; |
| 61 | static std::vector<std::vector<uint32_t>> gPolicyCpus; |
| 62 | static std::set<uint32_t> gAllFreqs; |
| 63 | static unique_fd gMapFd; |
| 64 | |
| 65 | static bool readNumbersFromFile(const std::string &path, std::vector<uint32_t> *out) { |
| 66 | std::string data; |
| 67 | |
| 68 | if (!android::base::ReadFileToString(path, &data)) { |
| 69 | ALOGD("Failed to read file %s", path.c_str()); |
| 70 | return false; |
| 71 | } |
| 72 | |
| 73 | auto strings = android::base::Split(data, " \n"); |
| 74 | for (const auto &s : strings) { |
| 75 | if (s.empty()) continue; |
| 76 | uint32_t n; |
| 77 | if (!android::base::ParseUint(s, &n)) { |
| 78 | ALOGD("Failed to parse file %s", path.c_str()); |
| 79 | return false; |
| 80 | } |
| 81 | out->emplace_back(n); |
| 82 | } |
| 83 | return true; |
| 84 | } |
| 85 | |
| 86 | static int isPolicyFile(const struct dirent *d) { |
| 87 | return android::base::StartsWith(d->d_name, "policy"); |
| 88 | } |
| 89 | |
| 90 | static int comparePolicyFiles(const struct dirent **d1, const struct dirent **d2) { |
| 91 | uint32_t policyN1, policyN2; |
| 92 | if (sscanf((*d1)->d_name, "policy%" SCNu32 "", &policyN1) != 1 || |
| 93 | sscanf((*d2)->d_name, "policy%" SCNu32 "", &policyN2) != 1) |
| 94 | return 0; |
| 95 | return policyN1 - policyN2; |
| 96 | } |
| 97 | |
| 98 | static bool initGlobals() { |
| 99 | std::lock_guard<std::mutex> guard(gInitializedMutex); |
| 100 | if (gInitialized) return true; |
| 101 | |
| 102 | struct dirent **dirlist; |
| 103 | const char basepath[] = "/sys/devices/system/cpu/cpufreq"; |
| 104 | int ret = scandir(basepath, &dirlist, isPolicyFile, comparePolicyFiles); |
| 105 | if (ret == -1) return false; |
| 106 | gNPolicies = ret; |
| 107 | |
| 108 | std::vector<std::string> policyFileNames; |
| 109 | for (uint32_t i = 0; i < gNPolicies; ++i) { |
| 110 | policyFileNames.emplace_back(dirlist[i]->d_name); |
| 111 | free(dirlist[i]); |
| 112 | } |
| 113 | free(dirlist); |
| 114 | |
| 115 | for (const auto &policy : policyFileNames) { |
| 116 | std::vector<uint32_t> freqs; |
| 117 | for (const auto &name : {"available", "boost"}) { |
| 118 | std::string path = |
| 119 | StringPrintf("%s/%s/scaling_%s_frequencies", basepath, policy.c_str(), name); |
| 120 | if (!readNumbersFromFile(path, &freqs)) return false; |
| 121 | } |
| 122 | std::sort(freqs.begin(), freqs.end()); |
| 123 | gPolicyFreqs.emplace_back(freqs); |
| 124 | |
| 125 | for (auto freq : freqs) gAllFreqs.insert(freq); |
| 126 | |
| 127 | std::vector<uint32_t> cpus; |
| 128 | std::string path = StringPrintf("%s/%s/%s", basepath, policy.c_str(), "related_cpus"); |
| 129 | if (!readNumbersFromFile(path, &cpus)) return false; |
| 130 | gPolicyCpus.emplace_back(cpus); |
| 131 | } |
| 132 | |
| 133 | gMapFd = unique_fd{bpf_obj_get(BPF_FS_PATH "map_time_in_state_uid_times")}; |
| 134 | if (gMapFd < 0) return false; |
| 135 | |
| 136 | gInitialized = true; |
| 137 | return true; |
| 138 | } |
| 139 | |
| 140 | static bool attachTracepointProgram(const std::string &eventType, const std::string &eventName) { |
| 141 | std::string path = StringPrintf(BPF_FS_PATH "prog_time_in_state_tracepoint_%s_%s", |
| 142 | eventType.c_str(), eventName.c_str()); |
| 143 | int prog_fd = bpf_obj_get(path.c_str()); |
| 144 | if (prog_fd < 0) { |
| 145 | ALOGD("bpf_obj_get() failed for program %s", path.c_str()); |
| 146 | return false; |
| 147 | } |
| 148 | if (bpf_attach_tracepoint(prog_fd, eventType.c_str(), eventName.c_str()) < 0) { |
| 149 | ALOGD("Failed to attach bpf program to tracepoint %s/%s", eventType.c_str(), |
| 150 | eventName.c_str()); |
| 151 | return false; |
| 152 | } |
| 153 | return true; |
| 154 | } |
| 155 | |
| 156 | // Start tracking and aggregating data to be reported by getUidCpuFreqTimes and getUidsCpuFreqTimes. |
| 157 | // Returns true on success, false otherwise. |
| 158 | // Tracking is active only once a live process has successfully called this function; if the calling |
| 159 | // process dies then it must be called again to resume tracking. |
| 160 | // This function should *not* be called while tracking is already active; doing so is unnecessary |
| 161 | // and can lead to accounting errors. |
| 162 | bool startTrackingUidCpuFreqTimes() { |
| 163 | return attachTracepointProgram("sched", "sched_switch") && |
| 164 | attachTracepointProgram("power", "cpu_frequency"); |
| 165 | } |
| 166 | |
| 167 | // Retrieve the times in ns that uid spent running at each CPU frequency and store in freqTimes. |
| 168 | // Returns false on error. Otherwise, returns true and populates freqTimes with a vector of vectors |
| 169 | // using the format: |
| 170 | // [[t0_0, t0_1, ...], |
| 171 | // [t1_0, t1_1, ...], ...] |
| 172 | // where ti_j is the ns that uid spent running on the ith cluster at that cluster's jth lowest freq. |
| 173 | bool getUidCpuFreqTimes(uint32_t uid, std::vector<std::vector<uint64_t>> *freqTimes) { |
| 174 | if (!gInitialized && !initGlobals()) return false; |
| 175 | time_key_t key = {.uid = uid, .freq = 0}; |
| 176 | |
| 177 | freqTimes->clear(); |
| 178 | freqTimes->resize(gNPolicies); |
| 179 | std::vector<uint32_t> idxs(gNPolicies, 0); |
| 180 | |
| 181 | val_t value; |
| 182 | for (uint32_t freq : gAllFreqs) { |
| 183 | key.freq = freq; |
| 184 | int ret = findMapEntry(gMapFd, &key, &value); |
| 185 | if (ret) { |
| 186 | if (errno == ENOENT) |
| 187 | memset(&value.ar, 0, sizeof(value.ar)); |
| 188 | else |
| 189 | return false; |
| 190 | } |
| 191 | for (uint32_t i = 0; i < gNPolicies; ++i) { |
| 192 | if (idxs[i] == gPolicyFreqs[i].size() || freq != gPolicyFreqs[i][idxs[i]]) continue; |
| 193 | uint64_t time = 0; |
| 194 | for (uint32_t cpu : gPolicyCpus[i]) time += value.ar[cpu]; |
| 195 | idxs[i] += 1; |
| 196 | (*freqTimes)[i].emplace_back(time); |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | return true; |
| 201 | } |
| 202 | |
| 203 | // Retrieve the times in ns that each uid spent running at each CPU freq and store in freqTimeMap. |
| 204 | // Returns false on error. Otherwise, returns true and populates freqTimeMap with a map from uids to |
| 205 | // vectors of vectors using the format: |
| 206 | // { uid0 -> [[t0_0_0, t0_0_1, ...], [t0_1_0, t0_1_1, ...], ...], |
| 207 | // uid1 -> [[t1_0_0, t1_0_1, ...], [t1_1_0, t1_1_1, ...], ...], ... } |
| 208 | // where ti_j_k is the ns uid i spent running on the jth cluster at the cluster's kth lowest freq. |
| 209 | bool getUidsCpuFreqTimes( |
| 210 | std::unordered_map<uint32_t, std::vector<std::vector<uint64_t>>> *freqTimeMap) { |
| 211 | if (!gInitialized && !initGlobals()) return false; |
| 212 | |
| 213 | int fd = bpf_obj_get(BPF_FS_PATH "map_time_in_state_uid_times"); |
| 214 | if (fd < 0) return false; |
| 215 | BpfMap<time_key_t, val_t> m(fd); |
| 216 | |
| 217 | std::vector<std::unordered_map<uint32_t, uint32_t>> policyFreqIdxs; |
| 218 | for (uint32_t i = 0; i < gNPolicies; ++i) { |
| 219 | std::unordered_map<uint32_t, uint32_t> freqIdxs; |
| 220 | for (size_t j = 0; j < gPolicyFreqs[i].size(); ++j) freqIdxs[gPolicyFreqs[i][j]] = j; |
| 221 | policyFreqIdxs.emplace_back(freqIdxs); |
| 222 | } |
| 223 | |
| 224 | auto fn = [freqTimeMap, &policyFreqIdxs](const time_key_t &key, const val_t &val, |
| 225 | const BpfMap<time_key_t, val_t> &) { |
| 226 | if (freqTimeMap->find(key.uid) == freqTimeMap->end()) { |
| 227 | std::vector<std::vector<uint64_t>> v; |
| 228 | for (uint32_t i = 0; i < gNPolicies; ++i) { |
| 229 | std::vector<uint64_t> v2(gPolicyFreqs[i].size(), 0); |
| 230 | v.emplace_back(v2); |
| 231 | } |
| 232 | (*freqTimeMap)[key.uid] = v; |
| 233 | } |
| 234 | |
| 235 | for (size_t policy = 0; policy < gNPolicies; ++policy) { |
| 236 | for (const auto &cpu : gPolicyCpus[policy]) { |
| 237 | uint32_t cpuTime = val.ar[cpu]; |
| 238 | if (cpuTime == 0) continue; |
| 239 | auto freqIdx = policyFreqIdxs[policy][key.freq]; |
| 240 | (*freqTimeMap)[key.uid][policy][freqIdx] += cpuTime; |
| 241 | } |
| 242 | } |
| 243 | return android::netdutils::status::ok; |
| 244 | }; |
| 245 | return isOk(m.iterateWithValue(fn)); |
| 246 | } |
| 247 | |
| 248 | // Clear all time in state data for a given uid. Returns false on error, true otherwise. |
| 249 | bool clearUidCpuFreqTimes(uint32_t uid) { |
| 250 | if (!gInitialized && !initGlobals()) return false; |
| 251 | time_key_t key = {.uid = uid, .freq = 0}; |
| 252 | |
| 253 | std::vector<uint32_t> idxs(gNPolicies, 0); |
| 254 | for (auto freq : gAllFreqs) { |
| 255 | key.freq = freq; |
| 256 | if (deleteMapEntry(gMapFd, &key) && errno != ENOENT) return false; |
| 257 | } |
| 258 | return true; |
| 259 | } |
| 260 | |
| 261 | } // namespace bpf |
| 262 | } // namespace android |