blob: 0e68e628b616f59a7c0523f7ee2a751c9a8e3888 [file] [log] [blame]
Connor O'Brien57337192018-11-20 12:49:16 -08001/*
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"
Connor O'Brienff7bf702019-06-05 18:27:47 -070020#include "timeinstate.h"
Connor O'Brien57337192018-11-20 12:49:16 -080021
22#include <dirent.h>
23#include <errno.h>
24#include <inttypes.h>
25
26#include <mutex>
Connor O'Brien4b9c4982019-06-05 18:03:12 -070027#include <optional>
Connor O'Brien57337192018-11-20 12:49:16 -080028#include <set>
29#include <string>
30#include <unordered_map>
31#include <vector>
32
33#include <android-base/file.h>
34#include <android-base/parseint.h>
35#include <android-base/stringprintf.h>
36#include <android-base/strings.h>
37#include <android-base/unique_fd.h>
38#include <bpf/BpfMap.h>
39#include <libbpf.h>
40#include <log/log.h>
41
Connor O'Brien57337192018-11-20 12:49:16 -080042using android::base::StringPrintf;
43using android::base::unique_fd;
44
45namespace android {
46namespace bpf {
47
Connor O'Brien57337192018-11-20 12:49:16 -080048static std::mutex gInitializedMutex;
49static bool gInitialized = false;
50static uint32_t gNPolicies = 0;
51static std::vector<std::vector<uint32_t>> gPolicyFreqs;
52static std::vector<std::vector<uint32_t>> gPolicyCpus;
53static std::set<uint32_t> gAllFreqs;
54static unique_fd gMapFd;
55
Connor O'Brien4b9c4982019-06-05 18:03:12 -070056static std::optional<std::vector<uint32_t>> readNumbersFromFile(const std::string &path) {
Connor O'Brien57337192018-11-20 12:49:16 -080057 std::string data;
58
Connor O'Brien4b9c4982019-06-05 18:03:12 -070059 if (!android::base::ReadFileToString(path, &data)) return {};
Connor O'Brien57337192018-11-20 12:49:16 -080060
61 auto strings = android::base::Split(data, " \n");
Connor O'Brien4b9c4982019-06-05 18:03:12 -070062 std::vector<uint32_t> ret;
Connor O'Brien57337192018-11-20 12:49:16 -080063 for (const auto &s : strings) {
64 if (s.empty()) continue;
65 uint32_t n;
Connor O'Brien4b9c4982019-06-05 18:03:12 -070066 if (!android::base::ParseUint(s, &n)) return {};
67 ret.emplace_back(n);
Connor O'Brien57337192018-11-20 12:49:16 -080068 }
Connor O'Brien4b9c4982019-06-05 18:03:12 -070069 return ret;
Connor O'Brien57337192018-11-20 12:49:16 -080070}
71
72static int isPolicyFile(const struct dirent *d) {
73 return android::base::StartsWith(d->d_name, "policy");
74}
75
76static int comparePolicyFiles(const struct dirent **d1, const struct dirent **d2) {
77 uint32_t policyN1, policyN2;
78 if (sscanf((*d1)->d_name, "policy%" SCNu32 "", &policyN1) != 1 ||
79 sscanf((*d2)->d_name, "policy%" SCNu32 "", &policyN2) != 1)
80 return 0;
81 return policyN1 - policyN2;
82}
83
84static bool initGlobals() {
85 std::lock_guard<std::mutex> guard(gInitializedMutex);
86 if (gInitialized) return true;
87
88 struct dirent **dirlist;
89 const char basepath[] = "/sys/devices/system/cpu/cpufreq";
90 int ret = scandir(basepath, &dirlist, isPolicyFile, comparePolicyFiles);
91 if (ret == -1) return false;
92 gNPolicies = ret;
93
94 std::vector<std::string> policyFileNames;
95 for (uint32_t i = 0; i < gNPolicies; ++i) {
96 policyFileNames.emplace_back(dirlist[i]->d_name);
97 free(dirlist[i]);
98 }
99 free(dirlist);
100
101 for (const auto &policy : policyFileNames) {
102 std::vector<uint32_t> freqs;
103 for (const auto &name : {"available", "boost"}) {
104 std::string path =
105 StringPrintf("%s/%s/scaling_%s_frequencies", basepath, policy.c_str(), name);
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700106 auto nums = readNumbersFromFile(path);
107 if (!nums) return false;
108 freqs.insert(freqs.end(), nums->begin(), nums->end());
Connor O'Brien57337192018-11-20 12:49:16 -0800109 }
110 std::sort(freqs.begin(), freqs.end());
111 gPolicyFreqs.emplace_back(freqs);
112
113 for (auto freq : freqs) gAllFreqs.insert(freq);
114
Connor O'Brien57337192018-11-20 12:49:16 -0800115 std::string path = StringPrintf("%s/%s/%s", basepath, policy.c_str(), "related_cpus");
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700116 auto cpus = readNumbersFromFile(path);
117 if (!cpus) return false;
118 gPolicyCpus.emplace_back(*cpus);
Connor O'Brien57337192018-11-20 12:49:16 -0800119 }
120
Connor O'Briencf9bc5f2019-06-06 17:29:18 -0700121 gMapFd = unique_fd{bpf_obj_get(BPF_FS_PATH "map_time_in_state_uid_times_map")};
Connor O'Brien57337192018-11-20 12:49:16 -0800122 if (gMapFd < 0) return false;
123
124 gInitialized = true;
125 return true;
126}
127
128static bool attachTracepointProgram(const std::string &eventType, const std::string &eventName) {
129 std::string path = StringPrintf(BPF_FS_PATH "prog_time_in_state_tracepoint_%s_%s",
130 eventType.c_str(), eventName.c_str());
131 int prog_fd = bpf_obj_get(path.c_str());
Connor O'Briend250acc2019-01-23 17:21:41 -0800132 if (prog_fd < 0) return false;
133 return bpf_attach_tracepoint(prog_fd, eventType.c_str(), eventName.c_str()) >= 0;
Connor O'Brien57337192018-11-20 12:49:16 -0800134}
135
136// Start tracking and aggregating data to be reported by getUidCpuFreqTimes and getUidsCpuFreqTimes.
137// Returns true on success, false otherwise.
138// Tracking is active only once a live process has successfully called this function; if the calling
139// process dies then it must be called again to resume tracking.
140// This function should *not* be called while tracking is already active; doing so is unnecessary
141// and can lead to accounting errors.
142bool startTrackingUidCpuFreqTimes() {
143 return attachTracepointProgram("sched", "sched_switch") &&
144 attachTracepointProgram("power", "cpu_frequency");
145}
146
147// Retrieve the times in ns that uid spent running at each CPU frequency and store in freqTimes.
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700148// Return contains no value on error, otherwise it contains a vector of vectors using the format:
Connor O'Brien57337192018-11-20 12:49:16 -0800149// [[t0_0, t0_1, ...],
150// [t1_0, t1_1, ...], ...]
151// where ti_j is the ns that uid spent running on the ith cluster at that cluster's jth lowest freq.
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700152std::optional<std::vector<std::vector<uint64_t>>> getUidCpuFreqTimes(uint32_t uid) {
153 if (!gInitialized && !initGlobals()) return {};
Connor O'Brien57337192018-11-20 12:49:16 -0800154 time_key_t key = {.uid = uid, .freq = 0};
155
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700156 std::vector<std::vector<uint64_t>> out(gNPolicies);
Connor O'Brien57337192018-11-20 12:49:16 -0800157 std::vector<uint32_t> idxs(gNPolicies, 0);
158
159 val_t value;
160 for (uint32_t freq : gAllFreqs) {
161 key.freq = freq;
162 int ret = findMapEntry(gMapFd, &key, &value);
163 if (ret) {
164 if (errno == ENOENT)
165 memset(&value.ar, 0, sizeof(value.ar));
166 else
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700167 return {};
Connor O'Brien57337192018-11-20 12:49:16 -0800168 }
169 for (uint32_t i = 0; i < gNPolicies; ++i) {
170 if (idxs[i] == gPolicyFreqs[i].size() || freq != gPolicyFreqs[i][idxs[i]]) continue;
171 uint64_t time = 0;
172 for (uint32_t cpu : gPolicyCpus[i]) time += value.ar[cpu];
173 idxs[i] += 1;
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700174 out[i].emplace_back(time);
Connor O'Brien57337192018-11-20 12:49:16 -0800175 }
176 }
177
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700178 return out;
Connor O'Brien57337192018-11-20 12:49:16 -0800179}
180
181// Retrieve the times in ns that each uid spent running at each CPU freq and store in freqTimeMap.
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700182// Return contains no value on error, otherwise it contains a map from uids to vectors of vectors
183// using the format:
Connor O'Brien57337192018-11-20 12:49:16 -0800184// { uid0 -> [[t0_0_0, t0_0_1, ...], [t0_1_0, t0_1_1, ...], ...],
185// uid1 -> [[t1_0_0, t1_0_1, ...], [t1_1_0, t1_1_1, ...], ...], ... }
186// where ti_j_k is the ns uid i spent running on the jth cluster at the cluster's kth lowest freq.
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700187std::optional<std::unordered_map<uint32_t, std::vector<std::vector<uint64_t>>>>
188getUidsCpuFreqTimes() {
189 if (!gInitialized && !initGlobals()) return {};
Connor O'Brien57337192018-11-20 12:49:16 -0800190
Connor O'Briencf9bc5f2019-06-06 17:29:18 -0700191 int fd = bpf_obj_get(BPF_FS_PATH "map_time_in_state_uid_times_map");
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700192 if (fd < 0) return {};
Connor O'Brien57337192018-11-20 12:49:16 -0800193 BpfMap<time_key_t, val_t> m(fd);
194
195 std::vector<std::unordered_map<uint32_t, uint32_t>> policyFreqIdxs;
196 for (uint32_t i = 0; i < gNPolicies; ++i) {
197 std::unordered_map<uint32_t, uint32_t> freqIdxs;
198 for (size_t j = 0; j < gPolicyFreqs[i].size(); ++j) freqIdxs[gPolicyFreqs[i][j]] = j;
199 policyFreqIdxs.emplace_back(freqIdxs);
200 }
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700201 std::unordered_map<uint32_t, std::vector<std::vector<uint64_t>>> map;
202 auto fn = [&map, &policyFreqIdxs](const time_key_t &key, const val_t &val,
Connor O'Brien57337192018-11-20 12:49:16 -0800203 const BpfMap<time_key_t, val_t> &) {
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700204 if (map.find(key.uid) == map.end()) {
205 map[key.uid].resize(gNPolicies);
Connor O'Brien57337192018-11-20 12:49:16 -0800206 for (uint32_t i = 0; i < gNPolicies; ++i) {
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700207 map[key.uid][i].resize(gPolicyFreqs[i].size(), 0);
Connor O'Brien57337192018-11-20 12:49:16 -0800208 }
Connor O'Brien57337192018-11-20 12:49:16 -0800209 }
210
211 for (size_t policy = 0; policy < gNPolicies; ++policy) {
212 for (const auto &cpu : gPolicyCpus[policy]) {
Connor O'Brien57337192018-11-20 12:49:16 -0800213 auto freqIdx = policyFreqIdxs[policy][key.freq];
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700214 map[key.uid][policy][freqIdx] += val.ar[cpu];
Connor O'Brien57337192018-11-20 12:49:16 -0800215 }
216 }
217 return android::netdutils::status::ok;
218 };
Connor O'Brien4b9c4982019-06-05 18:03:12 -0700219 if (isOk(m.iterateWithValue(fn))) return map;
220 return {};
Connor O'Brien57337192018-11-20 12:49:16 -0800221}
222
223// Clear all time in state data for a given uid. Returns false on error, true otherwise.
224bool clearUidCpuFreqTimes(uint32_t uid) {
225 if (!gInitialized && !initGlobals()) return false;
226 time_key_t key = {.uid = uid, .freq = 0};
227
228 std::vector<uint32_t> idxs(gNPolicies, 0);
229 for (auto freq : gAllFreqs) {
230 key.freq = freq;
231 if (deleteMapEntry(gMapFd, &key) && errno != ENOENT) return false;
232 }
233 return true;
234}
235
236} // namespace bpf
237} // namespace android