blob: c080582ac91ec742f8f90d11e309bb4280e58e3d [file] [log] [blame]
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -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_NDEBUG 0
18#define LOG_TAG "libprocessgroup"
19
20#include <fcntl.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080021#include <task_profiles.h>
22#include <string>
23
24#include <android-base/file.h>
25#include <android-base/logging.h>
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080026#include <android-base/properties.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080027#include <android-base/stringprintf.h>
Rick Yiubc1ad962020-10-26 20:32:52 +080028#include <android-base/strings.h>
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080029#include <android-base/threads.h>
30
31#include <cutils/android_filesystem_config.h>
32
33#include <json/reader.h>
34#include <json/value.h>
35
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -080036// To avoid issues in sdk_mac build
37#if defined(__ANDROID__)
38#include <sys/prctl.h>
39#endif
40
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080041using android::base::GetThreadId;
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080042using android::base::GetUintProperty;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080043using android::base::StringPrintf;
Rick Yiubc1ad962020-10-26 20:32:52 +080044using android::base::StringReplace;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080045using android::base::unique_fd;
46using android::base::WriteStringToFile;
47
Suren Baghdasaryan35221b52020-11-20 17:08:51 -080048static constexpr const char* TASK_PROFILE_DB_FILE = "/etc/task_profiles.json";
49static constexpr const char* TASK_PROFILE_DB_VENDOR_FILE = "/vendor/etc/task_profiles.json";
50
51static constexpr const char* TEMPLATE_TASK_PROFILE_API_FILE =
52 "/etc/task_profiles/task_profiles_%u.json";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -080053
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -080054class FdCacheHelper {
55 public:
56 enum FdState {
57 FDS_INACCESSIBLE = -1,
58 FDS_APP_DEPENDENT = -2,
59 FDS_NOT_CACHED = -3,
60 };
61
62 static void Cache(const std::string& path, android::base::unique_fd& fd);
63 static void Drop(android::base::unique_fd& fd);
64 static void Init(const std::string& path, android::base::unique_fd& fd);
65 static bool IsCached(const android::base::unique_fd& fd) { return fd > FDS_INACCESSIBLE; }
66
67 private:
68 static bool IsAppDependentPath(const std::string& path);
69};
70
71void FdCacheHelper::Init(const std::string& path, android::base::unique_fd& fd) {
72 // file descriptors for app-dependent paths can't be cached
73 if (IsAppDependentPath(path)) {
74 // file descriptor is not cached
75 fd.reset(FDS_APP_DEPENDENT);
76 return;
77 }
78 // file descriptor can be cached later on request
79 fd.reset(FDS_NOT_CACHED);
80}
81
82void FdCacheHelper::Cache(const std::string& path, android::base::unique_fd& fd) {
83 if (fd != FDS_NOT_CACHED) {
84 return;
85 }
86
87 if (access(path.c_str(), W_OK) != 0) {
88 // file is not accessible
89 fd.reset(FDS_INACCESSIBLE);
90 return;
91 }
92
93 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
94 if (tmp_fd < 0) {
95 PLOG(ERROR) << "Failed to cache fd '" << path << "'";
96 fd.reset(FDS_INACCESSIBLE);
97 return;
98 }
99
100 fd = std::move(tmp_fd);
101}
102
103void FdCacheHelper::Drop(android::base::unique_fd& fd) {
104 if (fd == FDS_NOT_CACHED) {
105 return;
106 }
107
108 fd.reset(FDS_NOT_CACHED);
109}
110
111bool FdCacheHelper::IsAppDependentPath(const std::string& path) {
112 return path.find("<uid>", 0) != std::string::npos || path.find("<pid>", 0) != std::string::npos;
113}
114
Bart Van Assche4c99e962022-02-03 19:50:16 +0000115IProfileAttribute::~IProfileAttribute() = default;
116
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700117void ProfileAttribute::Reset(const CgroupController& controller, const std::string& file_name) {
118 controller_ = controller;
119 file_name_ = file_name;
120}
121
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800122bool ProfileAttribute::GetPathForTask(int tid, std::string* path) const {
123 std::string subgroup;
Yifan Hong53e0deb2019-03-22 17:01:08 -0700124 if (!controller()->GetTaskGroup(tid, &subgroup)) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800125 return false;
126 }
127
128 if (path == nullptr) {
129 return true;
130 }
131
132 if (subgroup.empty()) {
Yifan Hong53e0deb2019-03-22 17:01:08 -0700133 *path = StringPrintf("%s/%s", controller()->path(), file_name_.c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800134 } else {
Yifan Hong53e0deb2019-03-22 17:01:08 -0700135 *path = StringPrintf("%s/%s/%s", controller()->path(), subgroup.c_str(),
136 file_name_.c_str());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800137 }
138 return true;
139}
140
141bool SetClampsAction::ExecuteForProcess(uid_t, pid_t) const {
142 // TODO: add support when kernel supports util_clamp
143 LOG(WARNING) << "SetClampsAction::ExecuteForProcess is not supported";
144 return false;
145}
146
147bool SetClampsAction::ExecuteForTask(int) const {
148 // TODO: add support when kernel supports util_clamp
149 LOG(WARNING) << "SetClampsAction::ExecuteForTask is not supported";
150 return false;
151}
152
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800153// To avoid issues in sdk_mac build
154#if defined(__ANDROID__)
155
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800156bool SetTimerSlackAction::IsTimerSlackSupported(int tid) {
157 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
158
159 return (access(file.c_str(), W_OK) == 0);
160}
161
162bool SetTimerSlackAction::ExecuteForTask(int tid) const {
163 static bool sys_supports_timerslack = IsTimerSlackSupported(tid);
164
165 // v4.6+ kernels support the /proc/<tid>/timerslack_ns interface.
166 // TODO: once we've backported this, log if the open(2) fails.
167 if (sys_supports_timerslack) {
168 auto file = StringPrintf("/proc/%d/timerslack_ns", tid);
169 if (!WriteStringToFile(std::to_string(slack_), file)) {
Suren Baghdasaryan2bc52282019-02-12 17:30:26 -0800170 if (errno == ENOENT) {
171 // This happens when process is already dead
172 return true;
173 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800174 PLOG(ERROR) << "set_timerslack_ns write failed";
175 }
176 }
177
178 // TODO: Remove when /proc/<tid>/timerslack_ns interface is backported.
179 if (tid == 0 || tid == GetThreadId()) {
180 if (prctl(PR_SET_TIMERSLACK, slack_) == -1) {
181 PLOG(ERROR) << "set_timerslack_ns prctl failed";
182 }
183 }
184
185 return true;
186}
187
Bart Van Assche20d59bd2022-01-24 19:45:59 +0000188#else
189
190bool SetTimerSlackAction::ExecuteForTask(int) const {
191 return true;
192};
193
Suren Baghdasaryaneca87cb2019-02-02 14:19:41 -0800194#endif
195
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800196bool SetAttributeAction::ExecuteForProcess(uid_t, pid_t pid) const {
197 return ExecuteForTask(pid);
198}
199
200bool SetAttributeAction::ExecuteForTask(int tid) const {
201 std::string path;
202
203 if (!attribute_->GetPathForTask(tid, &path)) {
Wei Wangd71d3012019-03-07 11:59:12 -0800204 LOG(ERROR) << "Failed to find cgroup for tid " << tid;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800205 return false;
206 }
207
208 if (!WriteStringToFile(value_, path)) {
209 PLOG(ERROR) << "Failed to write '" << value_ << "' to " << path;
210 return false;
211 }
212
213 return true;
214}
215
Rick Yiud4c53512021-11-21 15:57:36 +0800216SetCgroupAction::SetCgroupAction(const CgroupController& c, const std::string& p)
217 : controller_(c), path_(p) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800218 FdCacheHelper::Init(controller_.GetTasksFilePath(path_), fd_[ProfileAction::RCT_TASK]);
219 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
220 FdCacheHelper::Init(controller_.GetProcsFilePath(path_, 0, 0), fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800221}
222
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700223bool SetCgroupAction::AddTidToCgroup(int tid, int fd, const char* controller_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800224 if (tid <= 0) {
225 return true;
226 }
227
228 std::string value = std::to_string(tid);
229
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700230 if (TEMP_FAILURE_RETRY(write(fd, value.c_str(), value.length())) == value.length()) {
231 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800232 }
233
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700234 // If the thread is in the process of exiting, don't flag an error
235 if (errno == ESRCH) {
236 return true;
237 }
238
239 // ENOSPC is returned when cpuset cgroup that we are joining has no online cpus
240 if (errno == ENOSPC && !strcmp(controller_name, "cpuset")) {
241 // This is an abnormal case happening only in testing, so report it only once
242 static bool empty_cpuset_reported = false;
243
244 if (empty_cpuset_reported) {
245 return true;
246 }
247
248 LOG(ERROR) << "Failed to add task '" << value
249 << "' into cpuset because all cpus in that cpuset are offline";
250 empty_cpuset_reported = true;
251 } else {
252 PLOG(ERROR) << "AddTidToCgroup failed to write '" << value << "'; fd=" << fd;
253 }
254
255 return false;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800256}
257
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800258ProfileAction::CacheUseResult SetCgroupAction::UseCachedFd(ResourceCacheType cache_type,
259 int id) const {
260 std::lock_guard<std::mutex> lock(fd_mutex_);
261 if (FdCacheHelper::IsCached(fd_[cache_type])) {
262 // fd is cached, reuse it
263 if (!AddTidToCgroup(id, fd_[cache_type], controller()->name())) {
264 LOG(ERROR) << "Failed to add task into cgroup";
265 return ProfileAction::FAIL;
266 }
267 return ProfileAction::SUCCESS;
268 }
269
270 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
271 // no permissions to access the file, ignore
272 return ProfileAction::SUCCESS;
273 }
274
275 if (cache_type == ResourceCacheType::RCT_TASK &&
276 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
277 // application-dependent path can't be used with tid
278 PLOG(ERROR) << "Application profile can't be applied to a thread";
279 return ProfileAction::FAIL;
280 }
281
282 return ProfileAction::UNUSED;
283}
284
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800285bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800286 CacheUseResult result = UseCachedFd(ProfileAction::RCT_PROCESS, pid);
287 if (result != ProfileAction::UNUSED) {
288 return result == ProfileAction::SUCCESS;
289 }
290
291 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700292 std::string procs_path = controller()->GetProcsFilePath(path_, uid, pid);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800293 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(procs_path.c_str(), O_WRONLY | O_CLOEXEC)));
294 if (tmp_fd < 0) {
Elliott Hughes08b4d322019-03-14 20:06:36 -0700295 PLOG(WARNING) << "Failed to open " << procs_path;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800296 return false;
297 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700298 if (!AddTidToCgroup(pid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800299 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800300 return false;
301 }
302
303 return true;
304}
305
306bool SetCgroupAction::ExecuteForTask(int tid) const {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800307 CacheUseResult result = UseCachedFd(ProfileAction::RCT_TASK, tid);
308 if (result != ProfileAction::UNUSED) {
309 return result == ProfileAction::SUCCESS;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800310 }
311
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800312 // fd was not cached or cached fd can't be used
Yifan Hong53e0deb2019-03-22 17:01:08 -0700313 std::string tasks_path = controller()->GetTasksFilePath(path_);
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800314 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(tasks_path.c_str(), O_WRONLY | O_CLOEXEC)));
315 if (tmp_fd < 0) {
Rick Yiud4c53512021-11-21 15:57:36 +0800316 PLOG(WARNING) << "Failed to open " << tasks_path;
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800317 return false;
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800318 }
Suren Baghdasaryanec885562021-09-02 19:47:12 -0700319 if (!AddTidToCgroup(tid, tmp_fd, controller()->name())) {
Wei Wangd71d3012019-03-07 11:59:12 -0800320 LOG(ERROR) << "Failed to add task into cgroup";
Suren Baghdasaryanbee9f572019-02-05 16:44:22 -0800321 return false;
322 }
323
324 return true;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800325}
326
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800327void SetCgroupAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800328 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800329 // Return early to prevent unnecessary calls to controller_.Get{Tasks|Procs}FilePath() which
330 // include regex evaluations
331 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
332 return;
333 }
334 switch (cache_type) {
335 case (ProfileAction::RCT_TASK):
336 FdCacheHelper::Cache(controller_.GetTasksFilePath(path_), fd_[cache_type]);
337 break;
338 case (ProfileAction::RCT_PROCESS):
339 // uid and pid don't matter because IsAppDependentPath ensures the path doesn't use them
340 FdCacheHelper::Cache(controller_.GetProcsFilePath(path_, 0, 0), fd_[cache_type]);
341 break;
342 default:
343 LOG(ERROR) << "Invalid cache type is specified!";
344 break;
345 }
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800346}
347
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800348void SetCgroupAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800349 std::lock_guard<std::mutex> lock(fd_mutex_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800350 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800351}
352
Rick Yiu9221b1e2022-02-10 16:44:43 +0800353WriteFileAction::WriteFileAction(const std::string& task_path, const std::string& proc_path,
354 const std::string& value, bool logfailures)
355 : task_path_(task_path), proc_path_(proc_path), value_(value), logfailures_(logfailures) {
356 FdCacheHelper::Init(task_path_, fd_[ProfileAction::RCT_TASK]);
357 if (!proc_path_.empty()) FdCacheHelper::Init(proc_path_, fd_[ProfileAction::RCT_PROCESS]);
Rick Yiud4c53512021-11-21 15:57:36 +0800358}
Rick Yiubc1ad962020-10-26 20:32:52 +0800359
Rick Yiu9221b1e2022-02-10 16:44:43 +0800360bool WriteFileAction::WriteValueToFile(const std::string& value_, ResourceCacheType cache_type,
361 int uid, int pid, bool logfailures) const {
362 std::string value(value_);
363
364 value = StringReplace(value, "<uid>", std::to_string(uid), true);
365 value = StringReplace(value, "<pid>", std::to_string(pid), true);
366
367 CacheUseResult result = UseCachedFd(cache_type, value);
368
369 if (result != ProfileAction::UNUSED) {
370 return result == ProfileAction::SUCCESS;
371 }
372
373 std::string path;
374 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
375 path = task_path_;
376 } else {
377 path = proc_path_;
378 }
379
Rick Yiud4c53512021-11-21 15:57:36 +0800380 // Use WriteStringToFd instead of WriteStringToFile because the latter will open file with
381 // O_TRUNC which causes kernfs_mutex contention
382 unique_fd tmp_fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_WRONLY | O_CLOEXEC)));
Rick Yiubc1ad962020-10-26 20:32:52 +0800383
Rick Yiud4c53512021-11-21 15:57:36 +0800384 if (tmp_fd < 0) {
385 if (logfailures) PLOG(WARNING) << "Failed to open " << path;
386 return false;
387 }
388
389 if (!WriteStringToFd(value, tmp_fd)) {
390 if (logfailures) PLOG(ERROR) << "Failed to write '" << value << "' to " << path;
Rick Yiubc1ad962020-10-26 20:32:52 +0800391 return false;
392 }
393
394 return true;
395}
396
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800397ProfileAction::CacheUseResult WriteFileAction::UseCachedFd(ResourceCacheType cache_type,
398 const std::string& value) const {
Rick Yiud4c53512021-11-21 15:57:36 +0800399 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800400 if (FdCacheHelper::IsCached(fd_[cache_type])) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800401 // fd is cached, reuse it
Rick Yiu9221b1e2022-02-10 16:44:43 +0800402 bool ret = WriteStringToFd(value, fd_[cache_type]);
403
404 if (!ret && logfailures_) {
405 if (cache_type == ProfileAction::RCT_TASK || proc_path_.empty()) {
406 PLOG(ERROR) << "Failed to write '" << value << "' to " << task_path_;
407 } else {
408 PLOG(ERROR) << "Failed to write '" << value << "' to " << proc_path_;
409 }
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800410 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800411 return ret ? ProfileAction::SUCCESS : ProfileAction::FAIL;
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800412 }
413
Rick Yiu9221b1e2022-02-10 16:44:43 +0800414 if (fd_[cache_type] == FdCacheHelper::FDS_INACCESSIBLE) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800415 // no permissions to access the file, ignore
416 return ProfileAction::SUCCESS;
417 }
418
Rick Yiu9221b1e2022-02-10 16:44:43 +0800419 if (cache_type == ResourceCacheType::RCT_TASK &&
420 fd_[cache_type] == FdCacheHelper::FDS_APP_DEPENDENT) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800421 // application-dependent path can't be used with tid
422 PLOG(ERROR) << "Application profile can't be applied to a thread";
423 return ProfileAction::FAIL;
424 }
425 return ProfileAction::UNUSED;
426}
427
428bool WriteFileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800429 if (!proc_path_.empty()) {
430 return WriteValueToFile(value_, ProfileAction::RCT_PROCESS, uid, pid, logfailures_);
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800431 }
432
Rick Yiu9221b1e2022-02-10 16:44:43 +0800433 DIR* d;
434 struct dirent* de;
435 char proc_path[255];
436 int t_pid;
Rick Yiud4c53512021-11-21 15:57:36 +0800437
Rick Yiu9221b1e2022-02-10 16:44:43 +0800438 sprintf(proc_path, "/proc/%d/task", pid);
439 if (!(d = opendir(proc_path))) {
440 return false;
441 }
442
443 while ((de = readdir(d))) {
444 if (de->d_name[0] == '.') {
445 continue;
446 }
447
448 t_pid = atoi(de->d_name);
449
450 if (!t_pid) {
451 continue;
452 }
453
454 WriteValueToFile(value_, ProfileAction::RCT_TASK, uid, t_pid, logfailures_);
455 }
456
457 closedir(d);
458
459 return true;
Rick Yiud4c53512021-11-21 15:57:36 +0800460}
461
Rick Yiubc1ad962020-10-26 20:32:52 +0800462bool WriteFileAction::ExecuteForTask(int tid) const {
Rick Yiu9221b1e2022-02-10 16:44:43 +0800463 return WriteValueToFile(value_, ProfileAction::RCT_TASK, getuid(), tid, logfailures_);
464}
Rick Yiubc1ad962020-10-26 20:32:52 +0800465
Rick Yiu9221b1e2022-02-10 16:44:43 +0800466void WriteFileAction::EnableResourceCaching(ResourceCacheType cache_type) {
467 std::lock_guard<std::mutex> lock(fd_mutex_);
468 if (fd_[cache_type] != FdCacheHelper::FDS_NOT_CACHED) {
469 return;
Rick Yiubc1ad962020-10-26 20:32:52 +0800470 }
Rick Yiu9221b1e2022-02-10 16:44:43 +0800471 switch (cache_type) {
472 case (ProfileAction::RCT_TASK):
473 FdCacheHelper::Cache(task_path_, fd_[cache_type]);
474 break;
475 case (ProfileAction::RCT_PROCESS):
476 if (!proc_path_.empty()) FdCacheHelper::Cache(proc_path_, fd_[cache_type]);
477 break;
478 default:
479 LOG(ERROR) << "Invalid cache type is specified!";
480 break;
481 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800482}
483
Rick Yiu9221b1e2022-02-10 16:44:43 +0800484void WriteFileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800485 std::lock_guard<std::mutex> lock(fd_mutex_);
Rick Yiu9221b1e2022-02-10 16:44:43 +0800486 FdCacheHelper::Drop(fd_[cache_type]);
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800487}
488
Rick Yiu0b211fa2019-09-16 19:07:17 +0800489bool ApplyProfileAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
490 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800491 profile->ExecuteForProcess(uid, pid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800492 }
493 return true;
494}
495
496bool ApplyProfileAction::ExecuteForTask(int tid) const {
497 for (const auto& profile : profiles_) {
Wei Wang8722e4d2021-05-14 12:34:54 -0700498 profile->ExecuteForTask(tid);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800499 }
500 return true;
501}
502
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800503void ApplyProfileAction::EnableResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800504 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800505 profile->EnableResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800506 }
507}
508
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800509void ApplyProfileAction::DropResourceCaching(ResourceCacheType cache_type) {
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800510 for (const auto& profile : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800511 profile->DropResourceCaching(cache_type);
Suren Baghdasaryan911109c2020-02-13 17:28:00 -0800512 }
513}
514
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800515void TaskProfile::MoveTo(TaskProfile* profile) {
516 profile->elements_ = std::move(elements_);
517 profile->res_cached_ = res_cached_;
518}
519
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800520bool TaskProfile::ExecuteForProcess(uid_t uid, pid_t pid) const {
521 for (const auto& element : elements_) {
522 if (!element->ExecuteForProcess(uid, pid)) {
523 return false;
524 }
525 }
526 return true;
527}
528
529bool TaskProfile::ExecuteForTask(int tid) const {
530 if (tid == 0) {
531 tid = GetThreadId();
532 }
533 for (const auto& element : elements_) {
534 if (!element->ExecuteForTask(tid)) {
535 return false;
536 }
537 }
538 return true;
539}
540
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800541void TaskProfile::EnableResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800542 if (res_cached_) {
543 return;
544 }
545
546 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800547 element->EnableResourceCaching(cache_type);
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800548 }
549
550 res_cached_ = true;
551}
552
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800553void TaskProfile::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) {
Riddle Hsua6abd822019-06-18 15:53:53 -0600554 if (!res_cached_) {
555 return;
556 }
557
558 for (auto& element : elements_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800559 element->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600560 }
561
562 res_cached_ = false;
563}
564
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800565void TaskProfiles::DropResourceCaching(ProfileAction::ResourceCacheType cache_type) const {
Riddle Hsua6abd822019-06-18 15:53:53 -0600566 for (auto& iter : profiles_) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800567 iter.second->DropResourceCaching(cache_type);
Riddle Hsua6abd822019-06-18 15:53:53 -0600568 }
569}
570
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800571TaskProfiles& TaskProfiles::GetInstance() {
Peter Collingbournedba6d442019-03-20 21:09:46 -0700572 // Deliberately leak this object to avoid a race between destruction on
573 // process exit and concurrent access from another thread.
574 static auto* instance = new TaskProfiles;
575 return *instance;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800576}
577
578TaskProfiles::TaskProfiles() {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800579 // load system task profiles
580 if (!Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_FILE)) {
581 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_FILE << " for [" << getpid() << "] failed";
582 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800583
584 // load API-level specific system task profiles if available
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800585 unsigned int api_level = GetUintProperty<unsigned int>("ro.product.first_api_level", 0);
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800586 if (api_level > 0) {
587 std::string api_profiles_path =
588 android::base::StringPrintf(TEMPLATE_TASK_PROFILE_API_FILE, api_level);
589 if (!access(api_profiles_path.c_str(), F_OK) || errno != ENOENT) {
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800590 if (!Load(CgroupMap::GetInstance(), api_profiles_path)) {
Suren Baghdasaryanc2ee2e52022-01-20 10:58:43 -0800591 LOG(ERROR) << "Loading " << api_profiles_path << " for [" << getpid() << "] failed";
Suren Baghdasaryan756a6042020-12-03 11:38:42 -0800592 }
Suren Baghdasaryan35221b52020-11-20 17:08:51 -0800593 }
594 }
595
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800596 // load vendor task profiles if the file exists
597 if (!access(TASK_PROFILE_DB_VENDOR_FILE, F_OK) &&
598 !Load(CgroupMap::GetInstance(), TASK_PROFILE_DB_VENDOR_FILE)) {
599 LOG(ERROR) << "Loading " << TASK_PROFILE_DB_VENDOR_FILE << " for [" << getpid()
600 << "] failed";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800601 }
602}
603
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800604bool TaskProfiles::Load(const CgroupMap& cg_map, const std::string& file_name) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800605 std::string json_doc;
606
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800607 if (!android::base::ReadFileToString(file_name, &json_doc)) {
608 LOG(ERROR) << "Failed to read task profiles from " << file_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800609 return false;
610 }
611
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800612 Json::CharReaderBuilder builder;
613 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800614 Json::Value root;
Haibo Huangd9ac92a2021-02-24 17:34:50 -0800615 std::string errorMessage;
616 if (!reader->parse(&*json_doc.begin(), &*json_doc.end(), &root, &errorMessage)) {
617 LOG(ERROR) << "Failed to parse task profiles: " << errorMessage;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800618 return false;
619 }
620
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800621 const Json::Value& attr = root["Attributes"];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800622 for (Json::Value::ArrayIndex i = 0; i < attr.size(); ++i) {
623 std::string name = attr[i]["Name"].asString();
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800624 std::string controller_name = attr[i]["Controller"].asString();
625 std::string file_attr = attr[i]["File"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800626
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700627 auto controller = cg_map.FindController(controller_name);
628 if (controller.HasValue()) {
629 auto iter = attributes_.find(name);
630 if (iter == attributes_.end()) {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800631 attributes_[name] = std::make_unique<ProfileAttribute>(controller, file_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800632 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700633 iter->second->Reset(controller, file_attr);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800634 }
635 } else {
Suren Baghdasaryan81b9f0b2020-07-01 12:34:17 -0700636 LOG(WARNING) << "Controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800637 }
638 }
639
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800640 const Json::Value& profiles_val = root["Profiles"];
641 for (Json::Value::ArrayIndex i = 0; i < profiles_val.size(); ++i) {
642 const Json::Value& profile_val = profiles_val[i];
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800643
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800644 std::string profile_name = profile_val["Name"].asString();
645 const Json::Value& actions = profile_val["Actions"];
Rick Yiu0b211fa2019-09-16 19:07:17 +0800646 auto profile = std::make_shared<TaskProfile>();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800647
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800648 for (Json::Value::ArrayIndex act_idx = 0; act_idx < actions.size(); ++act_idx) {
649 const Json::Value& action_val = actions[act_idx];
650 std::string action_name = action_val["Name"].asString();
651 const Json::Value& params_val = action_val["Params"];
652 if (action_name == "JoinCgroup") {
653 std::string controller_name = params_val["Controller"].asString();
654 std::string path = params_val["Path"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800655
Yifan Hong53e0deb2019-03-22 17:01:08 -0700656 auto controller = cg_map.FindController(controller_name);
657 if (controller.HasValue()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800658 profile->Add(std::make_unique<SetCgroupAction>(controller, path));
659 } else {
Suren Baghdasaryan05da67c2019-02-19 15:01:28 -0800660 LOG(WARNING) << "JoinCgroup: controller " << controller_name << " is not found";
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800661 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800662 } else if (action_name == "SetTimerSlack") {
663 std::string slack_value = params_val["Slack"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800664 char* end;
665 unsigned long slack;
666
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800667 slack = strtoul(slack_value.c_str(), &end, 10);
668 if (end > slack_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800669 profile->Add(std::make_unique<SetTimerSlackAction>(slack));
670 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800671 LOG(WARNING) << "SetTimerSlack: invalid parameter: " << slack_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800672 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800673 } else if (action_name == "SetAttribute") {
674 std::string attr_name = params_val["Name"].asString();
675 std::string attr_value = params_val["Value"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800676
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800677 auto iter = attributes_.find(attr_name);
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800678 if (iter != attributes_.end()) {
679 profile->Add(
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800680 std::make_unique<SetAttributeAction>(iter->second.get(), attr_value));
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800681 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800682 LOG(WARNING) << "SetAttribute: unknown attribute: " << attr_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800683 }
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800684 } else if (action_name == "SetClamps") {
685 std::string boost_value = params_val["Boost"].asString();
686 std::string clamp_value = params_val["Clamp"].asString();
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800687 char* end;
688 unsigned long boost;
689
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800690 boost = strtoul(boost_value.c_str(), &end, 10);
691 if (end > boost_value.c_str()) {
692 unsigned long clamp = strtoul(clamp_value.c_str(), &end, 10);
693 if (end > clamp_value.c_str()) {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800694 profile->Add(std::make_unique<SetClampsAction>(boost, clamp));
695 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800696 LOG(WARNING) << "SetClamps: invalid parameter " << clamp_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800697 }
698 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800699 LOG(WARNING) << "SetClamps: invalid parameter: " << boost_value;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800700 }
Rick Yiubc1ad962020-10-26 20:32:52 +0800701 } else if (action_name == "WriteFile") {
702 std::string attr_filepath = params_val["FilePath"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800703 std::string attr_procfilepath = params_val["ProcFilePath"].asString();
Rick Yiubc1ad962020-10-26 20:32:52 +0800704 std::string attr_value = params_val["Value"].asString();
Rick Yiu9221b1e2022-02-10 16:44:43 +0800705 // FilePath and Value are mandatory
Rick Yiubc1ad962020-10-26 20:32:52 +0800706 if (!attr_filepath.empty() && !attr_value.empty()) {
Rick Yiu49fce952021-04-08 22:10:06 +0800707 std::string attr_logfailures = params_val["LogFailures"].asString();
708 bool logfailures = attr_logfailures.empty() || attr_logfailures == "true";
Rick Yiu9221b1e2022-02-10 16:44:43 +0800709 profile->Add(std::make_unique<WriteFileAction>(attr_filepath, attr_procfilepath,
710 attr_value, logfailures));
Rick Yiubc1ad962020-10-26 20:32:52 +0800711 } else if (attr_filepath.empty()) {
712 LOG(WARNING) << "WriteFile: invalid parameter: "
713 << "empty filepath";
714 } else if (attr_value.empty()) {
715 LOG(WARNING) << "WriteFile: invalid parameter: "
716 << "empty value";
717 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800718 } else {
Suren Baghdasaryane681df42019-02-20 16:17:22 -0800719 LOG(WARNING) << "Unknown profile action: " << action_name;
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800720 }
721 }
Suren Baghdasaryan84385952020-01-24 16:36:10 -0800722 auto iter = profiles_.find(profile_name);
723 if (iter == profiles_.end()) {
724 profiles_[profile_name] = profile;
725 } else {
726 // Move the content rather that replace the profile because old profile might be
727 // referenced from an aggregate profile if vendor overrides task profiles
728 profile->MoveTo(iter->second.get());
729 profile.reset();
730 }
Rick Yiu0b211fa2019-09-16 19:07:17 +0800731 }
732
733 const Json::Value& aggregateprofiles_val = root["AggregateProfiles"];
734 for (Json::Value::ArrayIndex i = 0; i < aggregateprofiles_val.size(); ++i) {
735 const Json::Value& aggregateprofile_val = aggregateprofiles_val[i];
736
737 std::string aggregateprofile_name = aggregateprofile_val["Name"].asString();
738 const Json::Value& aggregateprofiles = aggregateprofile_val["Profiles"];
739 std::vector<std::shared_ptr<TaskProfile>> profiles;
740 bool ret = true;
741
742 for (Json::Value::ArrayIndex pf_idx = 0; pf_idx < aggregateprofiles.size(); ++pf_idx) {
743 std::string profile_name = aggregateprofiles[pf_idx].asString();
744
745 if (profile_name == aggregateprofile_name) {
746 LOG(WARNING) << "AggregateProfiles: recursive profile name: " << profile_name;
747 ret = false;
748 break;
749 } else if (profiles_.find(profile_name) == profiles_.end()) {
750 LOG(WARNING) << "AggregateProfiles: undefined profile name: " << profile_name;
751 ret = false;
752 break;
753 } else {
754 profiles.push_back(profiles_[profile_name]);
755 }
756 }
757 if (ret) {
758 auto profile = std::make_shared<TaskProfile>();
759 profile->Add(std::make_unique<ApplyProfileAction>(profiles));
760 profiles_[aggregateprofile_name] = profile;
761 }
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800762 }
763
764 return true;
765}
766
Suren Baghdasaryan8a315d22019-02-14 14:40:41 -0800767TaskProfile* TaskProfiles::GetProfile(const std::string& name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800768 auto iter = profiles_.find(name);
769
770 if (iter != profiles_.end()) {
771 return iter->second.get();
772 }
773 return nullptr;
774}
775
Bart Van Assche4c99e962022-02-03 19:50:16 +0000776const IProfileAttribute* TaskProfiles::GetAttribute(const std::string& name) const {
Suren Baghdasaryan82b72a52018-12-21 11:41:50 -0800777 auto iter = attributes_.find(name);
778
779 if (iter != attributes_.end()) {
780 return iter->second.get();
781 }
782 return nullptr;
783}
Rick Yiu0b211fa2019-09-16 19:07:17 +0800784
785bool TaskProfiles::SetProcessProfiles(uid_t uid, pid_t pid,
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800786 const std::vector<std::string>& profiles, bool use_fd_cache) {
Rick Yiu0b211fa2019-09-16 19:07:17 +0800787 for (const auto& name : profiles) {
788 TaskProfile* profile = GetProfile(name);
789 if (profile != nullptr) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800790 if (use_fd_cache) {
791 profile->EnableResourceCaching(ProfileAction::RCT_PROCESS);
792 }
Rick Yiu0b211fa2019-09-16 19:07:17 +0800793 if (!profile->ExecuteForProcess(uid, pid)) {
794 PLOG(WARNING) << "Failed to apply " << name << " process profile";
795 }
796 } else {
797 PLOG(WARNING) << "Failed to find " << name << "process profile";
798 }
799 }
800 return true;
801}
802
803bool TaskProfiles::SetTaskProfiles(int tid, const std::vector<std::string>& profiles,
804 bool use_fd_cache) {
805 for (const auto& name : profiles) {
806 TaskProfile* profile = GetProfile(name);
807 if (profile != nullptr) {
808 if (use_fd_cache) {
Suren Baghdasaryanf3bdac72022-01-20 15:41:28 -0800809 profile->EnableResourceCaching(ProfileAction::RCT_TASK);
Rick Yiu0b211fa2019-09-16 19:07:17 +0800810 }
811 if (!profile->ExecuteForTask(tid)) {
812 PLOG(WARNING) << "Failed to apply " << name << " task profile";
813 }
814 } else {
815 PLOG(WARNING) << "Failed to find " << name << "task profile";
816 }
817 }
818 return true;
819}