blob: 9c2fb7c7f98fbdeb545841ad814c93ce2ffd64e4 [file] [log] [blame]
Ronghua Wu231c3d12015-03-11 15:10:32 -07001/*
2**
3** Copyright 2015, 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
18//#define LOG_NDEBUG 0
19#define LOG_TAG "ResourceManagerService"
20#include <utils/Log.h>
21
Chong Zhangfdd512a2019-11-22 11:03:14 -080022#include <android/binder_manager.h>
23#include <android/binder_process.h>
Chong Zhangc7303e82020-12-02 16:38:52 -080024#include <binder/IPCThreadState.h>
Ronghua Wu231c3d12015-03-11 15:10:32 -070025#include <binder/IServiceManager.h>
Chong Zhangee33d642019-08-08 14:26:43 -070026#include <cutils/sched_policy.h>
Chong Zhang181e6952019-10-09 13:23:39 -070027#include <media/MediaResourcePolicy.h>
Girish1f002cf2023-02-17 00:36:29 +000028#include <media/stagefright/foundation/ABase.h>
Chong Zhangee33d642019-08-08 14:26:43 -070029#include <mediautils/BatteryNotifier.h>
Girish1f002cf2023-02-17 00:36:29 +000030#include <mediautils/ProcessInfo.h>
Chong Zhangee33d642019-08-08 14:26:43 -070031#include <mediautils/SchedulingPolicyService.h>
Girish1484e5d2023-11-20 06:00:44 +000032#include <com_android_media_codec_flags.h>
Ronghua Wu231c3d12015-03-11 15:10:32 -070033
Girish1f002cf2023-02-17 00:36:29 +000034#include "ResourceManagerMetrics.h"
Girish1484e5d2023-11-20 06:00:44 +000035#include "ResourceManagerServiceNew.h"
Chong Zhanga9d45c72020-09-09 12:41:17 -070036#include "ResourceObserverService.h"
Ronghua Wua8ec8fc2015-05-07 13:58:22 -070037#include "ServiceLog.h"
Chong Zhangee33d642019-08-08 14:26:43 -070038
Girish1484e5d2023-11-20 06:00:44 +000039namespace CodecFeatureFlags = com::android::media::codec::flags;
40
Ronghua Wu231c3d12015-03-11 15:10:32 -070041namespace android {
42
Girish6a6044d2023-11-22 21:23:14 +000043void ResourceManagerService::getResourceDump(std::string& resourceLog) const {
44 PidResourceInfosMap mapCopy;
45 std::map<int, int> overridePidMapCopy;
46 {
47 std::scoped_lock lock{mLock};
48 mapCopy = mMap; // Shadow copy, real copy will happen on write.
49 overridePidMapCopy = mOverridePidMap;
50 }
51
52 const size_t SIZE = 256;
53 char buffer[SIZE];
54 resourceLog.append(" Processes:\n");
55 for (const auto& [pid, infos] : mapCopy) {
56 snprintf(buffer, SIZE, " Pid: %d\n", pid);
57 resourceLog.append(buffer);
58 int priority = 0;
59 if (getPriority_l(pid, &priority)) {
60 snprintf(buffer, SIZE, " Priority: %d\n", priority);
61 } else {
62 snprintf(buffer, SIZE, " Priority: <unknown>\n");
63 }
64 resourceLog.append(buffer);
65
66 for (const auto& [infoKey, info] : infos) {
67 resourceLog.append(" Client:\n");
68 snprintf(buffer, SIZE, " Id: %lld\n", (long long)info.clientId);
69 resourceLog.append(buffer);
70
71 std::string clientName = info.name;
72 snprintf(buffer, SIZE, " Name: %s\n", clientName.c_str());
73 resourceLog.append(buffer);
74
75 const ResourceList& resources = info.resources;
76 resourceLog.append(" Resources:\n");
Girishd11a03a2023-11-30 21:17:51 +000077 resourceLog.append(resources.toString());
Dongwon Kangfe508d32015-12-15 14:22:05 +090078 }
79 }
Girish6a6044d2023-11-22 21:23:14 +000080
81 resourceLog.append(" Process Pid override:\n");
82 for (auto it = overridePidMapCopy.begin(); it != overridePidMapCopy.end(); ++it) {
83 snprintf(buffer, SIZE, " Original Pid: %d, Override Pid: %d\n",
84 it->first, it->second);
85 resourceLog.append(buffer);
86 }
Dongwon Kangfe508d32015-12-15 14:22:05 +090087}
88
Brian Lindahl64ee9452022-01-14 13:31:16 +010089binder_status_t ResourceManagerService::dump(int fd, const char** /*args*/, uint32_t /*numArgs*/) {
Ronghua Wu8f9dd872015-04-23 15:24:25 -070090 String8 result;
Ronghua Wu8f9dd872015-04-23 15:24:25 -070091
dcashman014e91e2015-09-11 09:33:01 -070092 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
93 result.format("Permission Denial: "
94 "can't dump ResourceManagerService from pid=%d, uid=%d\n",
Chong Zhangfdd512a2019-11-22 11:03:14 -080095 AIBinder_getCallingPid(),
96 AIBinder_getCallingUid());
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +000097 write(fd, result.c_str(), result.size());
dcashman014e91e2015-09-11 09:33:01 -070098 return PERMISSION_DENIED;
99 }
100
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700101 bool supportsMultipleSecureCodecs;
102 bool supportsSecureWithNonSecureCodec;
103 String8 serviceLog;
104 {
Girish434b4d82023-07-11 23:24:54 +0000105 std::scoped_lock lock{mLock};
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700106 supportsMultipleSecureCodecs = mSupportsMultipleSecureCodecs;
107 supportsSecureWithNonSecureCodec = mSupportsSecureWithNonSecureCodec;
108 serviceLog = mServiceLog->toString(" " /* linePrefix */);
109 }
110
Girishdc187552024-04-02 21:51:46 +0000111 // Get all the resource (and overload pid) log.
Girish6a6044d2023-11-22 21:23:14 +0000112 std::string resourceLog;
113 getResourceDump(resourceLog);
114
Girishdc187552024-04-02 21:51:46 +0000115 // Get all the metrics log.
116 std::string metricsLog;
117 {
118 std::scoped_lock lock{mLock};
119 metricsLog = mResourceManagerMetrics->dump();
120 }
121
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700122 const size_t SIZE = 256;
123 char buffer[SIZE];
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700124 snprintf(buffer, SIZE, "ResourceManagerService: %p\n", this);
125 result.append(buffer);
126 result.append(" Policies:\n");
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700127 snprintf(buffer, SIZE, " SupportsMultipleSecureCodecs: %d\n", supportsMultipleSecureCodecs);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700128 result.append(buffer);
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700129 snprintf(buffer, SIZE, " SupportsSecureWithNonSecureCodec: %d\n",
130 supportsSecureWithNonSecureCodec);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700131 result.append(buffer);
132
Girishdc187552024-04-02 21:51:46 +0000133 // Add resource log.
Girish6a6044d2023-11-22 21:23:14 +0000134 result.append(resourceLog.c_str());
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700135
Girishdc187552024-04-02 21:51:46 +0000136 // Add service log.
Ronghua Wu022ed722015-05-11 15:15:09 -0700137 result.append(" Events logs (most recent at top):\n");
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700138 result.append(serviceLog);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700139
Girishdc187552024-04-02 21:51:46 +0000140 // Add metrics log.
141 result.append(metricsLog.c_str());
142
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +0000143 write(fd, result.c_str(), result.size());
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700144 return OK;
145}
146
Brian Lindahl64ee9452022-01-14 13:31:16 +0100147struct SystemCallbackImpl : public ResourceManagerService::SystemCallbackInterface {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800148 SystemCallbackImpl() : mClientToken(new BBinder()) {}
Ronghua Wu231c3d12015-03-11 15:10:32 -0700149
Chong Zhangdd726802019-08-21 17:24:13 -0700150 virtual void noteStartVideo(int uid) override {
151 BatteryNotifier::getInstance().noteStartVideo(uid);
152 }
153 virtual void noteStopVideo(int uid) override {
154 BatteryNotifier::getInstance().noteStopVideo(uid);
155 }
156 virtual void noteResetVideo() override {
157 BatteryNotifier::getInstance().noteResetVideo();
158 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800159 virtual bool requestCpusetBoost(bool enable) override {
160 return android::requestCpusetBoost(enable, mClientToken);
Chong Zhangdd726802019-08-21 17:24:13 -0700161 }
162
163protected:
164 virtual ~SystemCallbackImpl() {}
165
166private:
167 DISALLOW_EVIL_CONSTRUCTORS(SystemCallbackImpl);
Chong Zhangfdd512a2019-11-22 11:03:14 -0800168 sp<IBinder> mClientToken;
Chong Zhangdd726802019-08-21 17:24:13 -0700169};
170
171ResourceManagerService::ResourceManagerService()
172 : ResourceManagerService(new ProcessInfo(), new SystemCallbackImpl()) {}
173
Brian Lindahl64ee9452022-01-14 13:31:16 +0100174ResourceManagerService::ResourceManagerService(const sp<ProcessInfoInterface> &processInfo,
Chong Zhangdd726802019-08-21 17:24:13 -0700175 const sp<SystemCallbackInterface> &systemResource)
Ronghua Wu231c3d12015-03-11 15:10:32 -0700176 : mProcessInfo(processInfo),
Chong Zhangdd726802019-08-21 17:24:13 -0700177 mSystemCB(systemResource),
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700178 mServiceLog(new ServiceLog()),
Ronghua Wu231c3d12015-03-11 15:10:32 -0700179 mSupportsMultipleSecureCodecs(true),
Chong Zhang79d2b282018-04-17 14:14:31 -0700180 mSupportsSecureWithNonSecureCodec(true),
Girishab17b0f2023-11-20 06:00:44 +0000181 mCpuBoostCount(0) {
Chong Zhangdd726802019-08-21 17:24:13 -0700182 mSystemCB->noteResetVideo();
Girish1f002cf2023-02-17 00:36:29 +0000183 // Create ResourceManagerMetrics that handles all the metrics.
184 mResourceManagerMetrics = std::make_unique<ResourceManagerMetrics>(mProcessInfo);
Chong Zhangee33d642019-08-08 14:26:43 -0700185}
Ronghua Wu231c3d12015-03-11 15:10:32 -0700186
Chong Zhangfdd512a2019-11-22 11:03:14 -0800187//static
188void ResourceManagerService::instantiate() {
Girishab17b0f2023-11-20 06:00:44 +0000189 std::shared_ptr<ResourceManagerService> service = Create();
Chong Zhangfdd512a2019-11-22 11:03:14 -0800190 binder_status_t status =
Charles Chen5b097ef2023-03-15 01:21:22 +0000191 AServiceManager_addServiceWithFlags(
Charles Chene55549f2023-03-15 01:21:22 +0000192 service->asBinder().get(), getServiceName(),
193 AServiceManager_AddServiceFlag::ADD_SERVICE_ALLOW_ISOLATED);
Chong Zhangfdd512a2019-11-22 11:03:14 -0800194 if (status != STATUS_OK) {
195 return;
196 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700197
198 std::shared_ptr<ResourceObserverService> observerService =
199 ResourceObserverService::instantiate();
200
201 if (observerService != nullptr) {
202 service->setObserverService(observerService);
203 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800204 // TODO: mediaserver main() is already starting the thread pool,
205 // move this to mediaserver main() when other services in mediaserver
206 // are converted to ndk-platform aidl.
207 //ABinderProcess_startThreadPool();
208}
209
Girishab17b0f2023-11-20 06:00:44 +0000210std::shared_ptr<ResourceManagerService> ResourceManagerService::Create() {
211 return Create(new ProcessInfo(), new SystemCallbackImpl());
212}
213
214std::shared_ptr<ResourceManagerService> ResourceManagerService::Create(
215 const sp<ProcessInfoInterface>& processInfo,
216 const sp<SystemCallbackInterface>& systemResource) {
Girish6a6044d2023-11-22 21:23:14 +0000217 std::shared_ptr<ResourceManagerService> service = nullptr;
Girish1484e5d2023-11-20 06:00:44 +0000218 // If codec importance feature is on, create the refactored implementation.
219 if (CodecFeatureFlags::codec_importance()) {
Girish6a6044d2023-11-22 21:23:14 +0000220 service = ::ndk::SharedRefBase::make<ResourceManagerServiceNew>(processInfo,
221 systemResource);
222 } else {
223 service = ::ndk::SharedRefBase::make<ResourceManagerService>(processInfo,
224 systemResource);
Girish1484e5d2023-11-20 06:00:44 +0000225 }
Girish6a6044d2023-11-22 21:23:14 +0000226
227 if (service != nullptr) {
228 service->init();
229 }
230
231 return service;
Girishab17b0f2023-11-20 06:00:44 +0000232}
233
Girish1484e5d2023-11-20 06:00:44 +0000234// TEST only function.
235std::shared_ptr<ResourceManagerService> ResourceManagerService::CreateNew(
236 const sp<ProcessInfoInterface>& processInfo,
237 const sp<SystemCallbackInterface>& systemResource) {
Girish6a6044d2023-11-22 21:23:14 +0000238 std::shared_ptr<ResourceManagerService> service =
239 ::ndk::SharedRefBase::make<ResourceManagerServiceNew>(processInfo, systemResource);
240 service->init();
241 return service;
Girish1484e5d2023-11-20 06:00:44 +0000242}
243
Girish6a6044d2023-11-22 21:23:14 +0000244void ResourceManagerService::init() {}
245
Ronghua Wu231c3d12015-03-11 15:10:32 -0700246ResourceManagerService::~ResourceManagerService() {}
247
Chong Zhanga9d45c72020-09-09 12:41:17 -0700248void ResourceManagerService::setObserverService(
249 const std::shared_ptr<ResourceObserverService>& observerService) {
250 mObserverService = observerService;
251}
252
Chong Zhang181e6952019-10-09 13:23:39 -0700253Status ResourceManagerService::config(const std::vector<MediaResourcePolicyParcel>& policies) {
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +0000254 String8 log = String8::format("config(%s)", getString(policies).c_str());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700255 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700256
Girish434b4d82023-07-11 23:24:54 +0000257 std::scoped_lock lock{mLock};
Ronghua Wu231c3d12015-03-11 15:10:32 -0700258 for (size_t i = 0; i < policies.size(); ++i) {
Chong Zhang181e6952019-10-09 13:23:39 -0700259 const std::string &type = policies[i].type;
260 const std::string &value = policies[i].value;
261 if (type == MediaResourcePolicy::kPolicySupportsMultipleSecureCodecs()) {
Ronghua Wu9ba21b92015-04-21 14:23:06 -0700262 mSupportsMultipleSecureCodecs = (value == "true");
Chong Zhang181e6952019-10-09 13:23:39 -0700263 } else if (type == MediaResourcePolicy::kPolicySupportsSecureWithNonSecureCodec()) {
Ronghua Wu9ba21b92015-04-21 14:23:06 -0700264 mSupportsSecureWithNonSecureCodec = (value == "true");
Ronghua Wu231c3d12015-03-11 15:10:32 -0700265 }
266 }
Chong Zhang181e6952019-10-09 13:23:39 -0700267 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700268}
269
Girishab17b0f2023-11-20 06:00:44 +0000270void ResourceManagerService::onFirstAdded(const MediaResourceParcel& resource, uid_t uid) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700271 // first time added
Chong Zhang181e6952019-10-09 13:23:39 -0700272 if (resource.type == MediaResource::Type::kCpuBoost
273 && resource.subType == MediaResource::SubType::kUnspecifiedSubType) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700274 // Request it on every new instance of kCpuBoost, as the media.codec
275 // could have died, if we only do it the first time subsequent instances
276 // never gets the boost.
Chong Zhangfdd512a2019-11-22 11:03:14 -0800277 if (mSystemCB->requestCpusetBoost(true) != OK) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700278 ALOGW("couldn't request cpuset boost");
279 }
280 mCpuBoostCount++;
Chong Zhang181e6952019-10-09 13:23:39 -0700281 } else if (resource.type == MediaResource::Type::kBattery
Girisha5a2d672023-09-20 18:40:20 +0000282 && (resource.subType == MediaResource::SubType::kHwVideoCodec
283 || resource.subType == MediaResource::SubType::kSwVideoCodec)) {
Girishab17b0f2023-11-20 06:00:44 +0000284 mSystemCB->noteStartVideo(uid);
Chong Zhangfb092d32019-08-12 09:45:44 -0700285 }
286}
287
Girishab17b0f2023-11-20 06:00:44 +0000288void ResourceManagerService::onLastRemoved(const MediaResourceParcel& resource, uid_t uid) {
Chong Zhang181e6952019-10-09 13:23:39 -0700289 if (resource.type == MediaResource::Type::kCpuBoost
290 && resource.subType == MediaResource::SubType::kUnspecifiedSubType
Chong Zhangfb092d32019-08-12 09:45:44 -0700291 && mCpuBoostCount > 0) {
292 if (--mCpuBoostCount == 0) {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800293 mSystemCB->requestCpusetBoost(false);
Chong Zhangfb092d32019-08-12 09:45:44 -0700294 }
Chong Zhang181e6952019-10-09 13:23:39 -0700295 } else if (resource.type == MediaResource::Type::kBattery
Girisha5a2d672023-09-20 18:40:20 +0000296 && (resource.subType == MediaResource::SubType::kHwVideoCodec
297 || resource.subType == MediaResource::SubType::kSwVideoCodec)) {
Girishab17b0f2023-11-20 06:00:44 +0000298 mSystemCB->noteStopVideo(uid);
Robert Shihc3af31b2019-09-20 21:45:01 -0700299 }
300}
301
Girish9128e242022-11-23 20:52:29 +0000302Status ResourceManagerService::addResource(const ClientInfoParcel& clientInfo,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800303 const std::shared_ptr<IResourceManagerClient>& client,
Chong Zhang181e6952019-10-09 13:23:39 -0700304 const std::vector<MediaResourceParcel>& resources) {
Girish9128e242022-11-23 20:52:29 +0000305 int32_t pid = clientInfo.pid;
306 int32_t uid = clientInfo.uid;
307 int64_t clientId = clientInfo.id;
Girish9128e242022-11-23 20:52:29 +0000308 String8 log = String8::format("addResource(pid %d, uid %d clientId %lld, resources %s)",
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +0000309 pid, uid, (long long) clientId, getString(resources).c_str());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700310 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700311
Girish434b4d82023-07-11 23:24:54 +0000312 std::scoped_lock lock{mLock};
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100313 if (!mProcessInfo->isPidUidTrusted(pid, uid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800314 pid_t callingPid = IPCThreadState::self()->getCallingPid();
315 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100316 ALOGW("%s called with untrusted pid %d or uid %d, using calling pid %d, uid %d",
317 __FUNCTION__, pid, uid, callingPid, callingUid);
Chong Zhangc7303e82020-12-02 16:38:52 -0800318 pid = callingPid;
319 uid = callingUid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800320 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700321 ResourceInfos& infos = getResourceInfosForEdit(pid, mMap);
Girish27365ed2023-10-11 20:20:55 +0000322 ResourceInfo& info = getResourceInfoForEdit(clientInfo, client, infos);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700323 ResourceList resourceAdded;
Chong Zhang79d2b282018-04-17 14:14:31 -0700324
325 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700326 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700327
328 if (res.value < 0 && res.type != MediaResource::Type::kDrmSession) {
329 ALOGW("Ignoring request to remove negative value of non-drm resource");
330 continue;
331 }
Girishd11a03a2023-11-30 21:17:51 +0000332 bool isNewEntry = false;
333 if (!info.resources.add(res, &isNewEntry)) {
334 continue;
335 }
336 if (isNewEntry) {
Girishab17b0f2023-11-20 06:00:44 +0000337 onFirstAdded(res, info.uid);
Chong Zhang79d2b282018-04-17 14:14:31 -0700338 }
Girishd11a03a2023-11-30 21:17:51 +0000339
Chong Zhanga9d45c72020-09-09 12:41:17 -0700340 // Add it to the list of added resources for observers.
Girishd11a03a2023-11-30 21:17:51 +0000341 resourceAdded.add(res);
Chong Zhang79d2b282018-04-17 14:14:31 -0700342 }
Girishf1d166c2023-07-20 22:35:29 +0000343 if (info.deathNotifier == nullptr && client != nullptr) {
Girishab17b0f2023-11-20 06:00:44 +0000344 info.deathNotifier = DeathNotifier::Create(
345 client, ref<ResourceManagerService>(), clientInfo);
Wonsik Kim3e378962017-01-05 17:00:02 +0900346 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700347 if (mObserverService != nullptr && !resourceAdded.empty()) {
348 mObserverService->onResourceAdded(uid, pid, resourceAdded);
349 }
Dongwon Kangfe508d32015-12-15 14:22:05 +0900350 notifyResourceGranted(pid, resources);
Girish9128e242022-11-23 20:52:29 +0000351
Chong Zhang181e6952019-10-09 13:23:39 -0700352 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700353}
354
Girish9128e242022-11-23 20:52:29 +0000355Status ResourceManagerService::removeResource(const ClientInfoParcel& clientInfo,
Chong Zhang181e6952019-10-09 13:23:39 -0700356 const std::vector<MediaResourceParcel>& resources) {
Girish9128e242022-11-23 20:52:29 +0000357 int32_t pid = clientInfo.pid;
358 int32_t uid = clientInfo.uid;
359 int64_t clientId = clientInfo.id;
360 String8 log = String8::format("removeResource(pid %d, uid %d clientId %lld, resources %s)",
Tomasz Wasilczyk09977ff2023-08-11 15:52:22 +0000361 pid, uid, (long long) clientId, getString(resources).c_str());
Chong Zhangfb092d32019-08-12 09:45:44 -0700362 mServiceLog->add(log);
363
Girish434b4d82023-07-11 23:24:54 +0000364 std::scoped_lock lock{mLock};
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100365 if (!mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800366 pid_t callingPid = IPCThreadState::self()->getCallingPid();
367 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
368 pid, callingPid);
369 pid = callingPid;
Chong Zhangfb092d32019-08-12 09:45:44 -0700370 }
Girish434b4d82023-07-11 23:24:54 +0000371 PidResourceInfosMap::iterator found = mMap.find(pid);
372 if (found == mMap.end()) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700373 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700374 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700375 }
Girish434b4d82023-07-11 23:24:54 +0000376 ResourceInfos& infos = found->second;
Chong Zhangfb092d32019-08-12 09:45:44 -0700377
Girish434b4d82023-07-11 23:24:54 +0000378 ResourceInfos::iterator foundClient = infos.find(clientId);
379 if (foundClient == infos.end()) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700380 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700381 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700382 }
383
Girish434b4d82023-07-11 23:24:54 +0000384 ResourceInfo& info = foundClient->second;
Chong Zhanga9d45c72020-09-09 12:41:17 -0700385 ResourceList resourceRemoved;
Chong Zhangfb092d32019-08-12 09:45:44 -0700386 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700387 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700388
389 if (res.value < 0) {
390 ALOGW("Ignoring request to remove negative value of resource");
391 continue;
392 }
Girishd11a03a2023-11-30 21:17:51 +0000393
394 long removedEntryValue = -1;
395 if (info.resources.remove(res, &removedEntryValue)) {
Chong Zhanga9d45c72020-09-09 12:41:17 -0700396 MediaResourceParcel actualRemoved = res;
Girishd11a03a2023-11-30 21:17:51 +0000397 if (removedEntryValue != -1) {
Girishab17b0f2023-11-20 06:00:44 +0000398 onLastRemoved(res, info.uid);
Girishd11a03a2023-11-30 21:17:51 +0000399 actualRemoved.value = removedEntryValue;
Chong Zhanga9d45c72020-09-09 12:41:17 -0700400 }
401
402 // Add it to the list of removed resources for observers.
Girishd11a03a2023-11-30 21:17:51 +0000403 resourceRemoved.add(actualRemoved);
Chong Zhangfb092d32019-08-12 09:45:44 -0700404 }
405 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700406 if (mObserverService != nullptr && !resourceRemoved.empty()) {
407 mObserverService->onResourceRemoved(info.uid, pid, resourceRemoved);
408 }
Chong Zhang181e6952019-10-09 13:23:39 -0700409 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700410}
411
Girish9128e242022-11-23 20:52:29 +0000412Status ResourceManagerService::removeClient(const ClientInfoParcel& clientInfo) {
413 removeResource(clientInfo, true /*checkValid*/);
Chong Zhang181e6952019-10-09 13:23:39 -0700414 return Status::ok();
Wonsik Kim3e378962017-01-05 17:00:02 +0900415}
416
Girish9128e242022-11-23 20:52:29 +0000417Status ResourceManagerService::removeResource(const ClientInfoParcel& clientInfo, bool checkValid) {
418 int32_t pid = clientInfo.pid;
419 int32_t uid = clientInfo.uid;
420 int64_t clientId = clientInfo.id;
421 String8 log = String8::format("removeResource(pid %d, uid %d clientId %lld)",
422 pid, uid, (long long) clientId);
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700423 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700424
Girish434b4d82023-07-11 23:24:54 +0000425 std::scoped_lock lock{mLock};
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100426 if (checkValid && !mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800427 pid_t callingPid = IPCThreadState::self()->getCallingPid();
428 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
429 pid, callingPid);
430 pid = callingPid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800431 }
Girish434b4d82023-07-11 23:24:54 +0000432 PidResourceInfosMap::iterator found = mMap.find(pid);
433 if (found == mMap.end()) {
Ronghua Wu37c89242015-07-15 12:23:48 -0700434 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700435 return Status::ok();
Ronghua Wu37c89242015-07-15 12:23:48 -0700436 }
Girish434b4d82023-07-11 23:24:54 +0000437 ResourceInfos& infos = found->second;
Chong Zhangfb092d32019-08-12 09:45:44 -0700438
Girish434b4d82023-07-11 23:24:54 +0000439 ResourceInfos::iterator foundClient = infos.find(clientId);
440 if (foundClient == infos.end()) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700441 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700442 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700443 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700444
Girish434b4d82023-07-11 23:24:54 +0000445 const ResourceInfo& info = foundClient->second;
Girishd11a03a2023-11-30 21:17:51 +0000446 for (const MediaResourceParcel& res : info.resources.getResources()) {
447 onLastRemoved(res, info.uid);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700448 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700449
Girish1f002cf2023-02-17 00:36:29 +0000450 // Since this client has been removed, update the metrics collector.
451 mResourceManagerMetrics->notifyClientReleased(clientInfo);
Girish9128e242022-11-23 20:52:29 +0000452
Chong Zhanga9d45c72020-09-09 12:41:17 -0700453 if (mObserverService != nullptr && !info.resources.empty()) {
454 mObserverService->onResourceRemoved(info.uid, pid, info.resources);
455 }
456
Girish434b4d82023-07-11 23:24:54 +0000457 infos.erase(foundClient);
Chong Zhang181e6952019-10-09 13:23:39 -0700458 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700459}
460
Girish56fda312023-10-12 21:32:35 +0000461void ResourceManagerService::getClientForResource_l(
462 const ResourceRequestInfo& resourceRequestInfo,
463 std::vector<ClientInfo>& clientsInfo) {
Girishaff0ef22023-10-13 00:22:39 +0000464 int callingPid = resourceRequestInfo.mCallingPid;
Girish56fda312023-10-12 21:32:35 +0000465 const MediaResourceParcel* res = resourceRequestInfo.mResource;
Ronghua Wu05d89f12015-07-07 16:47:42 -0700466 if (res == NULL) {
467 return;
468 }
Girishaff0ef22023-10-13 00:22:39 +0000469
470 // Before looking into other processes, check if we have clients marked for
471 // pending removal in the same process.
Girishab17b0f2023-11-20 06:00:44 +0000472 ClientInfo clientInfo;
473 if (getBiggestClientPendingRemoval_l(callingPid, res->type, res->subType, clientInfo)) {
474 clientsInfo.emplace_back(clientInfo);
Girishaff0ef22023-10-13 00:22:39 +0000475 return;
476 }
477
478 // Now find client(s) from a lowest priority process that has needed resources.
Girish56fda312023-10-12 21:32:35 +0000479 if (getLowestPriorityBiggestClient_l(resourceRequestInfo, clientInfo)) {
480 clientsInfo.push_back(clientInfo);
Ronghua Wu05d89f12015-07-07 16:47:42 -0700481 }
482}
483
Girish0ac5c212023-11-23 09:14:03 +0000484bool ResourceManagerService::getTargetClients(
Girish88a83502023-11-23 11:23:07 +0000485 const ClientInfoParcel& clientInfo,
Girish0ac5c212023-11-23 09:14:03 +0000486 const std::vector<MediaResourceParcel>& resources,
487 std::vector<ClientInfo>& targetClients) {
Girish88a83502023-11-23 11:23:07 +0000488 int32_t callingPid = clientInfo.pid;
Girish1c682402024-01-31 21:03:51 +0000489 int64_t clientId = clientInfo.id;
Girish0ac5c212023-11-23 09:14:03 +0000490 std::scoped_lock lock{mLock};
491 if (!mProcessInfo->isPidTrusted(callingPid)) {
492 pid_t actualCallingPid = IPCThreadState::self()->getCallingPid();
493 ALOGW("%s called with untrusted pid %d, using actual calling pid %d", __FUNCTION__,
494 callingPid, actualCallingPid);
495 callingPid = actualCallingPid;
496 }
497 const MediaResourceParcel *secureCodec = NULL;
498 const MediaResourceParcel *nonSecureCodec = NULL;
499 const MediaResourceParcel *graphicMemory = NULL;
500 const MediaResourceParcel *drmSession = NULL;
501 for (size_t i = 0; i < resources.size(); ++i) {
502 switch (resources[i].type) {
503 case MediaResource::Type::kSecureCodec:
504 secureCodec = &resources[i];
505 break;
506 case MediaResource::Type::kNonSecureCodec:
507 nonSecureCodec = &resources[i];
508 break;
509 case MediaResource::Type::kGraphicMemory:
510 graphicMemory = &resources[i];
511 break;
512 case MediaResource::Type::kDrmSession:
513 drmSession = &resources[i];
514 break;
515 default:
516 break;
517 }
518 }
519
520 // first pass to handle secure/non-secure codec conflict
521 if (secureCodec != NULL) {
522 MediaResourceParcel mediaResource{.type = MediaResource::Type::kSecureCodec,
523 .subType = secureCodec->subType};
Girish1c682402024-01-31 21:03:51 +0000524 ResourceRequestInfo resourceRequestInfo{callingPid, clientId, &mediaResource};
Girish0ac5c212023-11-23 09:14:03 +0000525 if (!mSupportsMultipleSecureCodecs) {
526 if (!getAllClients_l(resourceRequestInfo, targetClients)) {
527 return false;
528 }
529 }
530 if (!mSupportsSecureWithNonSecureCodec) {
531 mediaResource.type = MediaResource::Type::kNonSecureCodec;
532 if (!getAllClients_l(resourceRequestInfo, targetClients)) {
533 return false;
534 }
535 }
536 }
537 if (nonSecureCodec != NULL) {
538 if (!mSupportsSecureWithNonSecureCodec) {
539 MediaResourceParcel mediaResource{.type = MediaResource::Type::kSecureCodec,
540 .subType = nonSecureCodec->subType};
Girish1c682402024-01-31 21:03:51 +0000541 ResourceRequestInfo resourceRequestInfo{callingPid, clientId, &mediaResource};
Girish0ac5c212023-11-23 09:14:03 +0000542 if (!getAllClients_l(resourceRequestInfo, targetClients)) {
543 return false;
544 }
545 }
546 }
547
548 if (drmSession != NULL) {
Girish1c682402024-01-31 21:03:51 +0000549 ResourceRequestInfo resourceRequestInfo{callingPid, clientId, drmSession};
Girish0ac5c212023-11-23 09:14:03 +0000550 getClientForResource_l(resourceRequestInfo, targetClients);
551 if (targetClients.size() == 0) {
552 return false;
553 }
554 }
555
556 if (targetClients.size() == 0 && graphicMemory != nullptr) {
557 // if no secure/non-secure codec conflict, run second pass to handle other resources.
Girish1c682402024-01-31 21:03:51 +0000558 ResourceRequestInfo resourceRequestInfo{callingPid, clientId, graphicMemory};
Girish0ac5c212023-11-23 09:14:03 +0000559 getClientForResource_l(resourceRequestInfo, targetClients);
560 }
561
562 if (targetClients.size() == 0) {
563 // if we are here, run the third pass to free one codec with the same type.
564 if (secureCodec != nullptr) {
Girish1c682402024-01-31 21:03:51 +0000565 ResourceRequestInfo resourceRequestInfo{callingPid, clientId, secureCodec};
Girish0ac5c212023-11-23 09:14:03 +0000566 getClientForResource_l(resourceRequestInfo, targetClients);
567 }
568 if (nonSecureCodec != nullptr) {
Girish1c682402024-01-31 21:03:51 +0000569 ResourceRequestInfo resourceRequestInfo{callingPid, clientId, nonSecureCodec};
Girish0ac5c212023-11-23 09:14:03 +0000570 getClientForResource_l(resourceRequestInfo, targetClients);
571 }
572 }
573
574 if (targetClients.size() == 0) {
575 // if we are here, run the fourth pass to free one codec with the different type.
576 if (secureCodec != nullptr) {
577 MediaResource temp(MediaResource::Type::kNonSecureCodec, secureCodec->subType, 1);
Girish1c682402024-01-31 21:03:51 +0000578 ResourceRequestInfo resourceRequestInfo{callingPid, clientId, &temp};
Girish0ac5c212023-11-23 09:14:03 +0000579 getClientForResource_l(resourceRequestInfo, targetClients);
580 }
581 if (nonSecureCodec != nullptr) {
582 MediaResource temp(MediaResource::Type::kSecureCodec, nonSecureCodec->subType, 1);
Girish1c682402024-01-31 21:03:51 +0000583 ResourceRequestInfo resourceRequestInfo{callingPid, clientId, &temp};
Girish0ac5c212023-11-23 09:14:03 +0000584 getClientForResource_l(resourceRequestInfo, targetClients);
585 }
586 }
587
588 return !targetClients.empty();
589}
590
Girish9128e242022-11-23 20:52:29 +0000591Status ResourceManagerService::reclaimResource(const ClientInfoParcel& clientInfo,
Brian Lindahl64ee9452022-01-14 13:31:16 +0100592 const std::vector<MediaResourceParcel>& resources, bool* _aidl_return) {
Girish9128e242022-11-23 20:52:29 +0000593 std::string clientName = clientInfo.name;
594 String8 log = String8::format("reclaimResource(callingPid %d, uid %d resources %s)",
Girish88a83502023-11-23 11:23:07 +0000595 clientInfo.pid, clientInfo.uid, getString(resources).c_str());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700596 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700597 *_aidl_return = false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700598
Girish0ac5c212023-11-23 09:14:03 +0000599 // Check if there are any resources to be reclaimed before processing.
600 if (resources.empty()) {
Girishe7b338f2024-02-08 22:03:51 +0000601 // Invalid reclaim request. So no need to log.
Girish0ac5c212023-11-23 09:14:03 +0000602 return Status::ok();
603 }
604
Girish56fda312023-10-12 21:32:35 +0000605 std::vector<ClientInfo> targetClients;
Girishe7b338f2024-02-08 22:03:51 +0000606 if (getTargetClients(clientInfo, resources, targetClients)) {
607 // Reclaim all the target clients.
608 *_aidl_return = reclaimUnconditionallyFrom(targetClients);
609 } else {
610 // No clients to reclaim from.
Girish0ac5c212023-11-23 09:14:03 +0000611 ALOGI("%s: There aren't any clients to reclaim from", __func__);
Girishe7b338f2024-02-08 22:03:51 +0000612 // We need to log this failed reclaim as "no clients to reclaim from".
613 targetClients.clear();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700614 }
615
Girish9128e242022-11-23 20:52:29 +0000616 // Log Reclaim Pushed Atom to statsd
Girish56fda312023-10-12 21:32:35 +0000617 pushReclaimAtom(clientInfo, targetClients, *_aidl_return);
Girish9128e242022-11-23 20:52:29 +0000618
Wonsik Kim271429d2020-10-01 10:12:56 -0700619 return Status::ok();
620}
621
Girish9128e242022-11-23 20:52:29 +0000622void ResourceManagerService::pushReclaimAtom(const ClientInfoParcel& clientInfo,
Girish56fda312023-10-12 21:32:35 +0000623 const std::vector<ClientInfo>& targetClients,
624 bool reclaimed) {
Girish9128e242022-11-23 20:52:29 +0000625 int32_t callingPid = clientInfo.pid;
Girish9128e242022-11-23 20:52:29 +0000626 int requesterPriority = -1;
627 getPriority_l(callingPid, &requesterPriority);
Girish1f002cf2023-02-17 00:36:29 +0000628 std::vector<int> priorities;
629 priorities.push_back(requesterPriority);
Girish9128e242022-11-23 20:52:29 +0000630
Girish56fda312023-10-12 21:32:35 +0000631 for (const ClientInfo& targetClient : targetClients) {
Girish9128e242022-11-23 20:52:29 +0000632 int targetPriority = -1;
Girish56fda312023-10-12 21:32:35 +0000633 getPriority_l(targetClient.mPid, &targetPriority);
Girish1f002cf2023-02-17 00:36:29 +0000634 priorities.push_back(targetPriority);
Girish9128e242022-11-23 20:52:29 +0000635 }
Girish56fda312023-10-12 21:32:35 +0000636 mResourceManagerMetrics->pushReclaimAtom(clientInfo, priorities, targetClients, reclaimed);
Girish9128e242022-11-23 20:52:29 +0000637}
638
Girishe8305272023-12-18 19:17:58 +0000639std::shared_ptr<IResourceManagerClient> ResourceManagerService::getClient_l(
Girishab17b0f2023-11-20 06:00:44 +0000640 int pid, const int64_t& clientId) const {
641 std::map<int, ResourceInfos>::const_iterator found = mMap.find(pid);
642 if (found == mMap.end()) {
643 ALOGV("%s: didn't find pid %d for clientId %lld", __func__, pid, (long long) clientId);
644 return nullptr;
645 }
646
647 const ResourceInfos& infos = found->second;
648 ResourceInfos::const_iterator foundClient = infos.find(clientId);
649 if (foundClient == infos.end()) {
650 ALOGV("%s: didn't find clientId %lld", __func__, (long long) clientId);
651 return nullptr;
652 }
653
654 return foundClient->second.client;
655}
656
Girishe8305272023-12-18 19:17:58 +0000657bool ResourceManagerService::removeClient_l(int pid, const int64_t& clientId) {
Girishab17b0f2023-11-20 06:00:44 +0000658 std::map<int, ResourceInfos>::iterator found = mMap.find(pid);
659 if (found == mMap.end()) {
660 ALOGV("%s: didn't find pid %d for clientId %lld", __func__, pid, (long long) clientId);
661 return false;
662 }
663
664 ResourceInfos& infos = found->second;
665 ResourceInfos::iterator foundClient = infos.find(clientId);
666 if (foundClient == infos.end()) {
667 ALOGV("%s: didn't find clientId %lld", __func__, (long long) clientId);
668 return false;
669 }
670
671 infos.erase(foundClient);
672 return true;
673}
674
Brian Lindahl64ee9452022-01-14 13:31:16 +0100675bool ResourceManagerService::reclaimUnconditionallyFrom(
Girish56fda312023-10-12 21:32:35 +0000676 const std::vector<ClientInfo>& targetClients) {
677 if (targetClients.size() == 0) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700678 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700679 }
680
Girishab17b0f2023-11-20 06:00:44 +0000681 int64_t failedClientId = -1;
682 int32_t failedClientPid = -1;
Girish56fda312023-10-12 21:32:35 +0000683 for (const ClientInfo& targetClient : targetClients) {
Girishe8305272023-12-18 19:17:58 +0000684 std::shared_ptr<IResourceManagerClient> client = nullptr;
685 {
686 std::scoped_lock lock{mLock};
687 client = getClient_l(targetClient.mPid, targetClient.mClientId);
688 }
Girishab17b0f2023-11-20 06:00:44 +0000689 if (client == nullptr) {
Girish56fda312023-10-12 21:32:35 +0000690 // skip already released clients.
691 continue;
692 }
Girishab17b0f2023-11-20 06:00:44 +0000693 String8 log = String8::format("reclaimResource from client %p", client.get());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700694 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700695 bool success;
Girishab17b0f2023-11-20 06:00:44 +0000696 Status status = client->reclaimResource(&success);
Chong Zhang181e6952019-10-09 13:23:39 -0700697 if (!status.isOk() || !success) {
Girishab17b0f2023-11-20 06:00:44 +0000698 failedClientId = targetClient.mClientId;
699 failedClientPid = targetClient.mPid;
Ronghua Wu67e7f542015-03-13 10:47:08 -0700700 break;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700701 }
702 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700703
Girishab17b0f2023-11-20 06:00:44 +0000704 if (failedClientId == -1) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700705 return true;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700706 }
707
Ronghua Wu67e7f542015-03-13 10:47:08 -0700708 {
Girish434b4d82023-07-11 23:24:54 +0000709 std::scoped_lock lock{mLock};
Girishe8305272023-12-18 19:17:58 +0000710 bool found = removeClient_l(failedClientPid, failedClientId);
Brian Lindahl9f626cf2022-04-25 13:29:59 +0200711 if (found) {
712 ALOGW("Failed to reclaim resources from client with pid %d", failedClientPid);
713 } else {
714 ALOGW("Failed to reclaim resources from unlocateable client");
Ronghua Wu67e7f542015-03-13 10:47:08 -0700715 }
716 }
717
Wonsik Kim271429d2020-10-01 10:12:56 -0700718 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700719}
720
Girish6a6044d2023-11-22 21:23:14 +0000721bool ResourceManagerService::overridePid_l(int32_t originalPid, int32_t newPid) {
722 mOverridePidMap.erase(originalPid);
723 if (newPid != -1) {
724 mOverridePidMap.emplace(originalPid, newPid);
725 return true;
726 }
727
728 return false;
729}
730
Brian Lindahl64ee9452022-01-14 13:31:16 +0100731Status ResourceManagerService::overridePid(int originalPid, int newPid) {
Henry Fang32762922020-01-28 18:40:39 -0800732 String8 log = String8::format("overridePid(originalPid %d, newPid %d)",
733 originalPid, newPid);
734 mServiceLog->add(log);
735
736 // allow if this is called from the same process or the process has
737 // permission.
738 if ((AIBinder_getCallingPid() != getpid()) &&
739 (checkCallingPermission(String16(
740 "android.permission.MEDIA_RESOURCE_OVERRIDE_PID")) == false)) {
741 ALOGE(
742 "Permission Denial: can't access overridePid method from pid=%d, "
743 "self pid=%d\n",
744 AIBinder_getCallingPid(), getpid());
745 return Status::fromServiceSpecificError(PERMISSION_DENIED);
746 }
747
748 {
Girish434b4d82023-07-11 23:24:54 +0000749 std::scoped_lock lock{mLock};
Girish6a6044d2023-11-22 21:23:14 +0000750 if (overridePid_l(originalPid, newPid)) {
Girish1f002cf2023-02-17 00:36:29 +0000751 mResourceManagerMetrics->addPid(newPid);
Henry Fang32762922020-01-28 18:40:39 -0800752 }
753 }
754
755 return Status::ok();
756}
757
Girish6a6044d2023-11-22 21:23:14 +0000758bool ResourceManagerService::overrideProcessInfo_l(
759 const std::shared_ptr<IResourceManagerClient>& client,
760 int pid,
761 int procState,
762 int oomScore) {
763 removeProcessInfoOverride_l(pid);
764
765 if (!mProcessInfo->overrideProcessInfo(pid, procState, oomScore)) {
766 // Override value is rejected by ProcessInfo.
767 return false;
768 }
769
770 ClientInfoParcel clientInfo{.pid = static_cast<int32_t>(pid),
771 .uid = 0,
772 .id = 0,
773 .name = "<unknown client>"};
774 auto deathNotifier = DeathNotifier::Create(
775 client, ref<ResourceManagerService>(), clientInfo, true);
776
777 mProcessInfoOverrideMap.emplace(pid, ProcessInfoOverride{deathNotifier, client});
778 return true;
779}
780
Chong Zhang97d367b2020-09-16 12:53:14 -0700781Status ResourceManagerService::overrideProcessInfo(
Brian Lindahl64ee9452022-01-14 13:31:16 +0100782 const std::shared_ptr<IResourceManagerClient>& client, int pid, int procState,
Chong Zhang97d367b2020-09-16 12:53:14 -0700783 int oomScore) {
784 String8 log = String8::format("overrideProcessInfo(pid %d, procState %d, oomScore %d)",
785 pid, procState, oomScore);
786 mServiceLog->add(log);
787
788 // Only allow the override if the caller already can access process state and oom scores.
789 int callingPid = AIBinder_getCallingPid();
790 if (callingPid != getpid() && (callingPid != pid || !checkCallingPermission(String16(
791 "android.permission.GET_PROCESS_STATE_AND_OOM_SCORE")))) {
792 ALOGE("Permission Denial: overrideProcessInfo method from pid=%d", callingPid);
793 return Status::fromServiceSpecificError(PERMISSION_DENIED);
794 }
795
796 if (client == nullptr) {
797 return Status::fromServiceSpecificError(BAD_VALUE);
798 }
799
Girish434b4d82023-07-11 23:24:54 +0000800 std::scoped_lock lock{mLock};
Girish6a6044d2023-11-22 21:23:14 +0000801 if (!overrideProcessInfo_l(client, pid, procState, oomScore)) {
Chong Zhang97d367b2020-09-16 12:53:14 -0700802 // Override value is rejected by ProcessInfo.
803 return Status::fromServiceSpecificError(BAD_VALUE);
804 }
Chong Zhang97d367b2020-09-16 12:53:14 -0700805 return Status::ok();
Girish6a6044d2023-11-22 21:23:14 +0000806
Chong Zhang97d367b2020-09-16 12:53:14 -0700807}
808
Chong Zhang97d367b2020-09-16 12:53:14 -0700809void ResourceManagerService::removeProcessInfoOverride(int pid) {
Girish434b4d82023-07-11 23:24:54 +0000810 std::scoped_lock lock{mLock};
Chong Zhang97d367b2020-09-16 12:53:14 -0700811
812 removeProcessInfoOverride_l(pid);
813}
814
815void ResourceManagerService::removeProcessInfoOverride_l(int pid) {
816 auto it = mProcessInfoOverrideMap.find(pid);
817 if (it == mProcessInfoOverrideMap.end()) {
818 return;
819 }
820
821 mProcessInfo->removeProcessInfoOverride(pid);
Chong Zhang97d367b2020-09-16 12:53:14 -0700822 mProcessInfoOverrideMap.erase(pid);
823}
824
Girish9128e242022-11-23 20:52:29 +0000825Status ResourceManagerService::markClientForPendingRemoval(const ClientInfoParcel& clientInfo) {
826 int32_t pid = clientInfo.pid;
827 int64_t clientId = clientInfo.id;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700828 String8 log = String8::format(
829 "markClientForPendingRemoval(pid %d, clientId %lld)",
830 pid, (long long) clientId);
831 mServiceLog->add(log);
832
Girish434b4d82023-07-11 23:24:54 +0000833 std::scoped_lock lock{mLock};
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100834 if (!mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800835 pid_t callingPid = IPCThreadState::self()->getCallingPid();
836 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
837 pid, callingPid);
838 pid = callingPid;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700839 }
Girish434b4d82023-07-11 23:24:54 +0000840 PidResourceInfosMap::iterator found = mMap.find(pid);
841 if (found == mMap.end()) {
Wonsik Kimd20e9362020-04-28 10:42:57 -0700842 ALOGV("markClientForPendingRemoval: didn't find pid %d for clientId %lld",
843 pid, (long long)clientId);
844 return Status::ok();
845 }
Girish434b4d82023-07-11 23:24:54 +0000846 ResourceInfos& infos = found->second;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700847
Girish434b4d82023-07-11 23:24:54 +0000848 ResourceInfos::iterator foundClient = infos.find(clientId);
849 if (foundClient == infos.end()) {
Wonsik Kimd20e9362020-04-28 10:42:57 -0700850 ALOGV("markClientForPendingRemoval: didn't find clientId %lld", (long long) clientId);
851 return Status::ok();
852 }
853
Girish434b4d82023-07-11 23:24:54 +0000854 ResourceInfo& info = foundClient->second;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700855 info.pendingRemoval = true;
856 return Status::ok();
857}
858
Wonsik Kim271429d2020-10-01 10:12:56 -0700859Status ResourceManagerService::reclaimResourcesFromClientsPendingRemoval(int32_t pid) {
860 String8 log = String8::format("reclaimResourcesFromClientsPendingRemoval(pid %d)", pid);
861 mServiceLog->add(log);
862
Girish56fda312023-10-12 21:32:35 +0000863 std::vector<ClientInfo> targetClients;
Wonsik Kim271429d2020-10-01 10:12:56 -0700864 {
Girish434b4d82023-07-11 23:24:54 +0000865 std::scoped_lock lock{mLock};
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100866 if (!mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800867 pid_t callingPid = IPCThreadState::self()->getCallingPid();
868 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
869 pid, callingPid);
870 pid = callingPid;
Wonsik Kim271429d2020-10-01 10:12:56 -0700871 }
872
873 for (MediaResource::Type type : {MediaResource::Type::kSecureCodec,
874 MediaResource::Type::kNonSecureCodec,
875 MediaResource::Type::kGraphicMemory,
876 MediaResource::Type::kDrmSession}) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100877 switch (type) {
878 // Codec resources are segregated by audio, video and image domains.
879 case MediaResource::Type::kSecureCodec:
880 case MediaResource::Type::kNonSecureCodec:
Girisha5a2d672023-09-20 18:40:20 +0000881 for (MediaResource::SubType subType : {MediaResource::SubType::kHwAudioCodec,
882 MediaResource::SubType::kSwAudioCodec,
883 MediaResource::SubType::kHwVideoCodec,
884 MediaResource::SubType::kSwVideoCodec,
885 MediaResource::SubType::kHwImageCodec,
886 MediaResource::SubType::kSwImageCodec}) {
Girishab17b0f2023-11-20 06:00:44 +0000887 ClientInfo clientInfo;
888 if (getBiggestClientPendingRemoval_l(pid, type, subType, clientInfo)) {
889 targetClients.emplace_back(clientInfo);
Brian Lindahl64ee9452022-01-14 13:31:16 +0100890 continue;
891 }
892 }
893 break;
894 // Non-codec resources are shared by audio, video and image codecs (no subtype).
895 default:
Girishab17b0f2023-11-20 06:00:44 +0000896 ClientInfo clientInfo;
Brian Lindahl64ee9452022-01-14 13:31:16 +0100897 if (getBiggestClientPendingRemoval_l(pid, type,
Girishab17b0f2023-11-20 06:00:44 +0000898 MediaResource::SubType::kUnspecifiedSubType, clientInfo)) {
899 targetClients.emplace_back(clientInfo);
Brian Lindahl64ee9452022-01-14 13:31:16 +0100900 }
901 break;
Wonsik Kim271429d2020-10-01 10:12:56 -0700902 }
903 }
904 }
905
Girish56fda312023-10-12 21:32:35 +0000906 if (!targetClients.empty()) {
907 reclaimUnconditionallyFrom(targetClients);
Wonsik Kim271429d2020-10-01 10:12:56 -0700908 }
909 return Status::ok();
910}
911
Girish6a6044d2023-11-22 21:23:14 +0000912bool ResourceManagerService::getPriority_l(int pid, int* priority) const {
Henry Fang32762922020-01-28 18:40:39 -0800913 int newPid = pid;
914
Girish6a6044d2023-11-22 21:23:14 +0000915 std::map<int, int>::const_iterator found = mOverridePidMap.find(pid);
916 if (found != mOverridePidMap.end()) {
917 newPid = found->second;
Henry Fang32762922020-01-28 18:40:39 -0800918 ALOGD("getPriority_l: use override pid %d instead original pid %d",
919 newPid, pid);
920 }
921
922 return mProcessInfo->getPriority(newPid, priority);
923}
924
Girish56fda312023-10-12 21:32:35 +0000925bool ResourceManagerService::getAllClients_l(
926 const ResourceRequestInfo& resourceRequestInfo,
927 std::vector<ClientInfo>& clientsInfo) {
928 MediaResource::Type type = resourceRequestInfo.mResource->type;
929 MediaResource::SubType subType = resourceRequestInfo.mResource->subType;
Girish9128e242022-11-23 20:52:29 +0000930
Girish434b4d82023-07-11 23:24:54 +0000931 for (auto& [pid, infos] : mMap) {
932 for (const auto& [id, info] : infos) {
Girish1c682402024-01-31 21:03:51 +0000933 if (pid == resourceRequestInfo.mCallingPid && id == resourceRequestInfo.mClientId) {
934 ALOGI("%s: Skip the client[%jd] for which the resource request is made",
935 __func__, id);
936 continue;
937 }
Girish434b4d82023-07-11 23:24:54 +0000938 if (hasResourceType(type, subType, info.resources)) {
Girish56fda312023-10-12 21:32:35 +0000939 if (!isCallingPriorityHigher_l(resourceRequestInfo.mCallingPid, pid)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700940 // some higher/equal priority process owns the resource,
941 // this request can't be fulfilled.
Girish56fda312023-10-12 21:32:35 +0000942 ALOGE("%s: can't reclaim resource %s from pid %d",
943 __func__, asString(type), pid);
944 clientsInfo.clear();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700945 return false;
946 }
Girishab17b0f2023-11-20 06:00:44 +0000947 clientsInfo.emplace_back(pid, info.uid, info.clientId);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700948 }
949 }
950 }
Girish56fda312023-10-12 21:32:35 +0000951 if (clientsInfo.size() == 0) {
952 ALOGV("%s: didn't find any resource %s", __func__, asString(type));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700953 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700954 return true;
955}
956
Girishaff0ef22023-10-13 00:22:39 +0000957// Process priority (oom score) based reclaim:
958// - Find a process with lowest priority (than that of calling process).
959// - Find the bigegst client (with required resources) from that process.
Girish56fda312023-10-12 21:32:35 +0000960bool ResourceManagerService::getLowestPriorityBiggestClient_l(
961 const ResourceRequestInfo& resourceRequestInfo,
Girishab17b0f2023-11-20 06:00:44 +0000962 ClientInfo& clientInfo) {
Girish56fda312023-10-12 21:32:35 +0000963 int callingPid = resourceRequestInfo.mCallingPid;
964 MediaResource::Type type = resourceRequestInfo.mResource->type;
965 MediaResource::SubType subType = resourceRequestInfo.mResource->subType;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700966 int lowestPriorityPid;
967 int lowestPriority;
968 int callingPriority;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700969
Henry Fang32762922020-01-28 18:40:39 -0800970 if (!getPriority_l(callingPid, &callingPriority)) {
Girishaff0ef22023-10-13 00:22:39 +0000971 ALOGE("%s: can't get process priority for pid %d", __func__, callingPid);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700972 return false;
973 }
Brian Lindahl64ee9452022-01-14 13:31:16 +0100974 if (!getLowestPriorityPid_l(type, subType, &lowestPriorityPid, &lowestPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700975 return false;
976 }
977 if (lowestPriority <= callingPriority) {
Girishaff0ef22023-10-13 00:22:39 +0000978 ALOGE("%s: lowest priority %d vs caller priority %d",
979 __func__, lowestPriority, callingPriority);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700980 return false;
981 }
982
Girishab17b0f2023-11-20 06:00:44 +0000983 if (!getBiggestClient_l(lowestPriorityPid, type, subType, clientInfo)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700984 return false;
985 }
Girish9128e242022-11-23 20:52:29 +0000986
Girishaff0ef22023-10-13 00:22:39 +0000987 ALOGI("%s: CallingProcess(%d:%d) will reclaim from the lowestPriorityProcess(%d:%d)",
988 __func__, callingPid, callingPriority, lowestPriorityPid, lowestPriority);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700989 return true;
990}
991
Brian Lindahl64ee9452022-01-14 13:31:16 +0100992bool ResourceManagerService::getLowestPriorityPid_l(MediaResource::Type type,
993 MediaResource::SubType subType, int *lowestPriorityPid, int *lowestPriority) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700994 int pid = -1;
995 int priority = -1;
Girish434b4d82023-07-11 23:24:54 +0000996 for (auto& [tempPid, infos] : mMap) {
997 if (infos.size() == 0) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700998 // no client on this process.
999 continue;
1000 }
Girish434b4d82023-07-11 23:24:54 +00001001 if (!hasResourceType(type, subType, infos)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001002 // doesn't have the requested resource type
1003 continue;
1004 }
Girish434b4d82023-07-11 23:24:54 +00001005 int tempPriority = -1;
Henry Fang32762922020-01-28 18:40:39 -08001006 if (!getPriority_l(tempPid, &tempPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001007 ALOGV("getLowestPriorityPid_l: can't get priority of pid %d, skipped", tempPid);
1008 // TODO: remove this pid from mMap?
1009 continue;
1010 }
1011 if (pid == -1 || tempPriority > priority) {
1012 // initial the value
1013 pid = tempPid;
1014 priority = tempPriority;
1015 }
1016 }
1017 if (pid != -1) {
1018 *lowestPriorityPid = pid;
1019 *lowestPriority = priority;
1020 }
1021 return (pid != -1);
1022}
1023
1024bool ResourceManagerService::isCallingPriorityHigher_l(int callingPid, int pid) {
1025 int callingPidPriority;
Henry Fang32762922020-01-28 18:40:39 -08001026 if (!getPriority_l(callingPid, &callingPidPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001027 return false;
1028 }
1029
1030 int priority;
Henry Fang32762922020-01-28 18:40:39 -08001031 if (!getPriority_l(pid, &priority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001032 return false;
1033 }
1034
1035 return (callingPidPriority < priority);
1036}
1037
Brian Lindahl64ee9452022-01-14 13:31:16 +01001038bool ResourceManagerService::getBiggestClientPendingRemoval_l(int pid, MediaResource::Type type,
Girishab17b0f2023-11-20 06:00:44 +00001039 MediaResource::SubType subType, ClientInfo& clientInfo) {
1040 return getBiggestClient_l(pid, type, subType, clientInfo, true /* pendingRemovalOnly */);
Brian Lindahl64ee9452022-01-14 13:31:16 +01001041}
1042
1043bool ResourceManagerService::getBiggestClient_l(int pid, MediaResource::Type type,
Girishab17b0f2023-11-20 06:00:44 +00001044 MediaResource::SubType subType, ClientInfo& clientInfo, bool pendingRemovalOnly) {
Girish434b4d82023-07-11 23:24:54 +00001045 PidResourceInfosMap::iterator found = mMap.find(pid);
1046 if (found == mMap.end()) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001047 ALOGE_IF(!pendingRemovalOnly,
1048 "getBiggestClient_l: can't find resource info for pid %d", pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001049 return false;
1050 }
1051
Girishab17b0f2023-11-20 06:00:44 +00001052 uid_t uid = -1;
1053 int64_t clientId = -1;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001054 uint64_t largestValue = 0;
Girish434b4d82023-07-11 23:24:54 +00001055 const ResourceInfos& infos = found->second;
1056 for (const auto& [id, info] : infos) {
1057 const ResourceList& resources = info.resources;
1058 if (pendingRemovalOnly && !info.pendingRemoval) {
Wonsik Kimd20e9362020-04-28 10:42:57 -07001059 continue;
1060 }
Girishd11a03a2023-11-30 21:17:51 +00001061 for (const MediaResourceParcel& resource : resources.getResources()) {
Brian Lindahl64ee9452022-01-14 13:31:16 +01001062 if (hasResourceType(type, subType, resource)) {
Chong Zhang181e6952019-10-09 13:23:39 -07001063 if (resource.value > largestValue) {
1064 largestValue = resource.value;
Girishab17b0f2023-11-20 06:00:44 +00001065 clientId = info.clientId;
Girish434b4d82023-07-11 23:24:54 +00001066 uid = info.uid;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001067 }
1068 }
1069 }
1070 }
1071
Girishab17b0f2023-11-20 06:00:44 +00001072 if (clientId == -1) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001073 ALOGE_IF(!pendingRemovalOnly,
Brian Lindahl64ee9452022-01-14 13:31:16 +01001074 "getBiggestClient_l: can't find resource type %s and subtype %s for pid %d",
1075 asString(type), asString(subType), pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001076 return false;
1077 }
1078
Girishab17b0f2023-11-20 06:00:44 +00001079 clientInfo.mPid = pid;
1080 clientInfo.mUid = uid;
1081 clientInfo.mClientId = clientId;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001082 return true;
1083}
1084
Girish1f002cf2023-02-17 00:36:29 +00001085Status ResourceManagerService::notifyClientCreated(const ClientInfoParcel& clientInfo) {
1086 mResourceManagerMetrics->notifyClientCreated(clientInfo);
1087 return Status::ok();
1088}
1089
1090Status ResourceManagerService::notifyClientStarted(const ClientConfigParcel& clientConfig) {
1091 mResourceManagerMetrics->notifyClientStarted(clientConfig);
1092 return Status::ok();
1093}
1094
1095Status ResourceManagerService::notifyClientStopped(const ClientConfigParcel& clientConfig) {
1096 mResourceManagerMetrics->notifyClientStopped(clientConfig);
1097 return Status::ok();
1098}
1099
Girishde8eb592023-04-13 18:49:17 +00001100Status ResourceManagerService::notifyClientConfigChanged(const ClientConfigParcel& clientConfig) {
1101 mResourceManagerMetrics->notifyClientConfigChanged(clientConfig);
1102 return Status::ok();
1103}
1104
Girish1f002cf2023-02-17 00:36:29 +00001105long ResourceManagerService::getPeakConcurrentPixelCount(int pid) const {
1106 return mResourceManagerMetrics->getPeakConcurrentPixelCount(pid);
1107}
1108
1109long ResourceManagerService::getCurrentConcurrentPixelCount(int pid) const {
1110 return mResourceManagerMetrics->getCurrentConcurrentPixelCount(pid);
1111}
1112
Girish6a6044d2023-11-22 21:23:14 +00001113void ResourceManagerService::notifyClientReleased(const ClientInfoParcel& clientInfo) {
1114 mResourceManagerMetrics->notifyClientReleased(clientInfo);
1115}
1116
Ronghua Wu231c3d12015-03-11 15:10:32 -07001117} // namespace android