blob: c6ded5f5a0c9af4e0638e7e4c0c4ff10c44199f4 [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>
Ronghua Wu231c3d12015-03-11 15:10:32 -070027#include <dirent.h>
Chong Zhang181e6952019-10-09 13:23:39 -070028#include <media/MediaResourcePolicy.h>
Atneya Nairf5b68512022-05-23 20:02:49 -040029#include <media/stagefright/foundation/ABase.h>
Chong Zhangee33d642019-08-08 14:26:43 -070030#include <mediautils/BatteryNotifier.h>
Atneya Nairf5b68512022-05-23 20:02:49 -040031#include <mediautils/ProcessInfo.h>
Chong Zhangee33d642019-08-08 14:26:43 -070032#include <mediautils/SchedulingPolicyService.h>
Ronghua Wu231c3d12015-03-11 15:10:32 -070033#include <string.h>
34#include <sys/types.h>
35#include <sys/stat.h>
36#include <sys/time.h>
37#include <unistd.h>
38
Steven Moreland0a0ff0b2021-04-02 00:06:01 +000039#include "IMediaResourceMonitor.h"
Ronghua Wu231c3d12015-03-11 15:10:32 -070040#include "ResourceManagerService.h"
Chong Zhanga9d45c72020-09-09 12:41:17 -070041#include "ResourceObserverService.h"
Ronghua Wua8ec8fc2015-05-07 13:58:22 -070042#include "ServiceLog.h"
Chong Zhangee33d642019-08-08 14:26:43 -070043
Ronghua Wu231c3d12015-03-11 15:10:32 -070044namespace android {
45
Chong Zhang97d367b2020-09-16 12:53:14 -070046//static
47std::mutex ResourceManagerService::sCookieLock;
48//static
49uintptr_t ResourceManagerService::sCookieCounter = 0;
50//static
51std::map<uintptr_t, sp<DeathNotifier> > ResourceManagerService::sCookieToDeathNotifierMap;
52
53class DeathNotifier : public RefBase {
54public:
Brian Lindahl64ee9452022-01-14 13:31:16 +010055 DeathNotifier(const std::shared_ptr<ResourceManagerService> &service, int pid,
56 int64_t clientId);
Chong Zhang97d367b2020-09-16 12:53:14 -070057
58 virtual ~DeathNotifier() {}
59
60 // Implement death recipient
61 static void BinderDiedCallback(void* cookie);
62 virtual void binderDied();
63
64protected:
65 std::weak_ptr<ResourceManagerService> mService;
66 int mPid;
67 int64_t mClientId;
68};
69
Chong Zhangfdd512a2019-11-22 11:03:14 -080070DeathNotifier::DeathNotifier(const std::shared_ptr<ResourceManagerService> &service,
71 int pid, int64_t clientId)
72 : mService(service), mPid(pid), mClientId(clientId) {}
Wonsik Kim3e378962017-01-05 17:00:02 +090073
Chong Zhangfdd512a2019-11-22 11:03:14 -080074//static
75void DeathNotifier::BinderDiedCallback(void* cookie) {
Chong Zhang97d367b2020-09-16 12:53:14 -070076 sp<DeathNotifier> notifier;
77 {
78 std::scoped_lock lock{ResourceManagerService::sCookieLock};
79 auto it = ResourceManagerService::sCookieToDeathNotifierMap.find(
80 reinterpret_cast<uintptr_t>(cookie));
81 if (it == ResourceManagerService::sCookieToDeathNotifierMap.end()) {
82 return;
83 }
84 notifier = it->second;
85 }
86 if (notifier.get() != nullptr) {
87 notifier->binderDied();
88 }
Chong Zhangfdd512a2019-11-22 11:03:14 -080089}
Wonsik Kim3e378962017-01-05 17:00:02 +090090
Chong Zhangfdd512a2019-11-22 11:03:14 -080091void DeathNotifier::binderDied() {
92 // Don't check for pid validity since we know it's already dead.
93 std::shared_ptr<ResourceManagerService> service = mService.lock();
94 if (service == nullptr) {
95 ALOGW("ResourceManagerService is dead as well.");
96 return;
Wonsik Kim3e378962017-01-05 17:00:02 +090097 }
Henry Fang32762922020-01-28 18:40:39 -080098
99 service->overridePid(mPid, -1);
Henry Fangb35141c2020-06-29 13:11:39 -0700100 // thiz is freed in the call below, so it must be last call referring thiz
Chong Zhangc7303e82020-12-02 16:38:52 -0800101 service->removeResource(mPid, mClientId, false /*checkValid*/);
Chong Zhang97d367b2020-09-16 12:53:14 -0700102}
Henry Fangb35141c2020-06-29 13:11:39 -0700103
Chong Zhang97d367b2020-09-16 12:53:14 -0700104class OverrideProcessInfoDeathNotifier : public DeathNotifier {
105public:
106 OverrideProcessInfoDeathNotifier(const std::shared_ptr<ResourceManagerService> &service,
107 int pid) : DeathNotifier(service, pid, 0) {}
108
109 virtual ~OverrideProcessInfoDeathNotifier() {}
110
111 virtual void binderDied();
112};
113
114void OverrideProcessInfoDeathNotifier::binderDied() {
115 // Don't check for pid validity since we know it's already dead.
116 std::shared_ptr<ResourceManagerService> service = mService.lock();
117 if (service == nullptr) {
118 ALOGW("ResourceManagerService is dead as well.");
119 return;
120 }
121
122 service->removeProcessInfoOverride(mPid);
Chong Zhangfdd512a2019-11-22 11:03:14 -0800123}
Wonsik Kim3e378962017-01-05 17:00:02 +0900124
Ronghua Wu231c3d12015-03-11 15:10:32 -0700125template <typename T>
Chong Zhang181e6952019-10-09 13:23:39 -0700126static String8 getString(const std::vector<T> &items) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700127 String8 itemsStr;
128 for (size_t i = 0; i < items.size(); ++i) {
Chong Zhang181e6952019-10-09 13:23:39 -0700129 itemsStr.appendFormat("%s ", toString(items[i]).string());
Ronghua Wu231c3d12015-03-11 15:10:32 -0700130 }
131 return itemsStr;
132}
133
Brian Lindahl64ee9452022-01-14 13:31:16 +0100134static bool hasResourceType(MediaResource::Type type, MediaResource::SubType subType,
135 MediaResourceParcel resource) {
136 if (type != resource.type) {
137 return false;
138 }
139 switch (type) {
140 // Codec subtypes (e.g. video vs. audio) are each considered separate resources, so
141 // compare the subtypes as well.
142 case MediaResource::Type::kSecureCodec:
143 case MediaResource::Type::kNonSecureCodec:
144 if (resource.subType == subType) {
145 return true;
146 }
147 break;
148 // Non-codec resources are not segregated by the subtype (e.g. video vs. audio).
149 default:
150 return true;
151 }
152 return false;
153}
154
155static bool hasResourceType(MediaResource::Type type, MediaResource::SubType subType,
156 const ResourceList& resources) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700157 for (auto it = resources.begin(); it != resources.end(); it++) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100158 if (hasResourceType(type, subType, it->second)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700159 return true;
160 }
161 }
162 return false;
163}
164
Brian Lindahl64ee9452022-01-14 13:31:16 +0100165static bool hasResourceType(MediaResource::Type type, MediaResource::SubType subType,
166 const ResourceInfos& infos) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700167 for (size_t i = 0; i < infos.size(); ++i) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100168 if (hasResourceType(type, subType, infos[i].resources)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700169 return true;
170 }
171 }
172 return false;
173}
174
Brian Lindahl64ee9452022-01-14 13:31:16 +0100175static ResourceInfos& getResourceInfosForEdit(int pid, PidResourceInfosMap& map) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700176 ssize_t index = map.indexOfKey(pid);
177 if (index < 0) {
178 // new pid
179 ResourceInfos infosForPid;
180 map.add(pid, infosForPid);
181 }
182
183 return map.editValueFor(pid);
184}
185
Brian Lindahl64ee9452022-01-14 13:31:16 +0100186static ResourceInfo& getResourceInfoForEdit(uid_t uid, int64_t clientId,
187 const std::shared_ptr<IResourceManagerClient>& client, ResourceInfos& infos) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700188 ssize_t index = infos.indexOfKey(clientId);
189
190 if (index < 0) {
191 ResourceInfo info;
192 info.uid = uid;
193 info.clientId = clientId;
194 info.client = client;
Chong Zhang97d367b2020-09-16 12:53:14 -0700195 info.cookie = 0;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700196 info.pendingRemoval = false;
Chong Zhangfb092d32019-08-12 09:45:44 -0700197
198 index = infos.add(clientId, info);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700199 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700200
201 return infos.editValueAt(index);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700202}
203
Chong Zhang181e6952019-10-09 13:23:39 -0700204static void notifyResourceGranted(int pid, const std::vector<MediaResourceParcel> &resources) {
Dongwon Kangfe508d32015-12-15 14:22:05 +0900205 static const char* const kServiceName = "media_resource_monitor";
Dongwon Kang2642c842016-03-23 18:07:29 -0700206 sp<IBinder> binder = defaultServiceManager()->checkService(String16(kServiceName));
Dongwon Kangfe508d32015-12-15 14:22:05 +0900207 if (binder != NULL) {
208 sp<IMediaResourceMonitor> service = interface_cast<IMediaResourceMonitor>(binder);
209 for (size_t i = 0; i < resources.size(); ++i) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100210 switch (resources[i].subType) {
211 case MediaResource::SubType::kAudioCodec:
212 service->notifyResourceGranted(pid, IMediaResourceMonitor::TYPE_AUDIO_CODEC);
213 break;
214 case MediaResource::SubType::kVideoCodec:
215 service->notifyResourceGranted(pid, IMediaResourceMonitor::TYPE_VIDEO_CODEC);
216 break;
217 case MediaResource::SubType::kImageCodec:
218 service->notifyResourceGranted(pid, IMediaResourceMonitor::TYPE_IMAGE_CODEC);
219 break;
220 case MediaResource::SubType::kUnspecifiedSubType:
221 break;
Dongwon Kang69c23dd2016-03-22 15:22:45 -0700222 }
Dongwon Kangfe508d32015-12-15 14:22:05 +0900223 }
224 }
225}
226
Brian Lindahl64ee9452022-01-14 13:31:16 +0100227binder_status_t ResourceManagerService::dump(int fd, const char** /*args*/, uint32_t /*numArgs*/) {
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700228 String8 result;
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700229
dcashman014e91e2015-09-11 09:33:01 -0700230 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
231 result.format("Permission Denial: "
232 "can't dump ResourceManagerService from pid=%d, uid=%d\n",
Chong Zhangfdd512a2019-11-22 11:03:14 -0800233 AIBinder_getCallingPid(),
234 AIBinder_getCallingUid());
dcashman014e91e2015-09-11 09:33:01 -0700235 write(fd, result.string(), result.size());
236 return PERMISSION_DENIED;
237 }
238
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700239 PidResourceInfosMap mapCopy;
240 bool supportsMultipleSecureCodecs;
241 bool supportsSecureWithNonSecureCodec;
Henry Fang32762922020-01-28 18:40:39 -0800242 std::map<int, int> overridePidMapCopy;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700243 String8 serviceLog;
244 {
245 Mutex::Autolock lock(mLock);
246 mapCopy = mMap; // Shadow copy, real copy will happen on write.
247 supportsMultipleSecureCodecs = mSupportsMultipleSecureCodecs;
248 supportsSecureWithNonSecureCodec = mSupportsSecureWithNonSecureCodec;
249 serviceLog = mServiceLog->toString(" " /* linePrefix */);
Henry Fang32762922020-01-28 18:40:39 -0800250 overridePidMapCopy = mOverridePidMap;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700251 }
252
253 const size_t SIZE = 256;
254 char buffer[SIZE];
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700255 snprintf(buffer, SIZE, "ResourceManagerService: %p\n", this);
256 result.append(buffer);
257 result.append(" Policies:\n");
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700258 snprintf(buffer, SIZE, " SupportsMultipleSecureCodecs: %d\n", supportsMultipleSecureCodecs);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700259 result.append(buffer);
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700260 snprintf(buffer, SIZE, " SupportsSecureWithNonSecureCodec: %d\n",
261 supportsSecureWithNonSecureCodec);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700262 result.append(buffer);
263
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700264 result.append(" Processes:\n");
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700265 for (size_t i = 0; i < mapCopy.size(); ++i) {
266 snprintf(buffer, SIZE, " Pid: %d\n", mapCopy.keyAt(i));
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700267 result.append(buffer);
268
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700269 const ResourceInfos &infos = mapCopy.valueAt(i);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700270 for (size_t j = 0; j < infos.size(); ++j) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700271 result.append(" Client:\n");
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700272 snprintf(buffer, SIZE, " Id: %lld\n", (long long)infos[j].clientId);
273 result.append(buffer);
274
Arun Johnsonaabe0142022-07-18 19:16:04 +0000275 std::string clientName = "<unknown client>";
276 if (infos[j].client != nullptr) {
277 Status status = infos[j].client->getName(&clientName);
Chong Zhang181e6952019-10-09 13:23:39 -0700278 }
279 snprintf(buffer, SIZE, " Name: %s\n", clientName.c_str());
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700280 result.append(buffer);
281
Chong Zhangfb092d32019-08-12 09:45:44 -0700282 const ResourceList &resources = infos[j].resources;
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700283 result.append(" Resources:\n");
Chong Zhangfb092d32019-08-12 09:45:44 -0700284 for (auto it = resources.begin(); it != resources.end(); it++) {
Chong Zhang181e6952019-10-09 13:23:39 -0700285 snprintf(buffer, SIZE, " %s\n", toString(it->second).string());
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700286 result.append(buffer);
287 }
288 }
289 }
Henry Fang32762922020-01-28 18:40:39 -0800290 result.append(" Process Pid override:\n");
291 for (auto it = overridePidMapCopy.begin(); it != overridePidMapCopy.end(); ++it) {
292 snprintf(buffer, SIZE, " Original Pid: %d, Override Pid: %d\n",
293 it->first, it->second);
294 result.append(buffer);
295 }
Ronghua Wu022ed722015-05-11 15:15:09 -0700296 result.append(" Events logs (most recent at top):\n");
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700297 result.append(serviceLog);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700298
299 write(fd, result.string(), result.size());
300 return OK;
301}
302
Brian Lindahl64ee9452022-01-14 13:31:16 +0100303struct SystemCallbackImpl : public ResourceManagerService::SystemCallbackInterface {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800304 SystemCallbackImpl() : mClientToken(new BBinder()) {}
Ronghua Wu231c3d12015-03-11 15:10:32 -0700305
Chong Zhangdd726802019-08-21 17:24:13 -0700306 virtual void noteStartVideo(int uid) override {
307 BatteryNotifier::getInstance().noteStartVideo(uid);
308 }
309 virtual void noteStopVideo(int uid) override {
310 BatteryNotifier::getInstance().noteStopVideo(uid);
311 }
312 virtual void noteResetVideo() override {
313 BatteryNotifier::getInstance().noteResetVideo();
314 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800315 virtual bool requestCpusetBoost(bool enable) override {
316 return android::requestCpusetBoost(enable, mClientToken);
Chong Zhangdd726802019-08-21 17:24:13 -0700317 }
318
319protected:
320 virtual ~SystemCallbackImpl() {}
321
322private:
323 DISALLOW_EVIL_CONSTRUCTORS(SystemCallbackImpl);
Chong Zhangfdd512a2019-11-22 11:03:14 -0800324 sp<IBinder> mClientToken;
Chong Zhangdd726802019-08-21 17:24:13 -0700325};
326
327ResourceManagerService::ResourceManagerService()
328 : ResourceManagerService(new ProcessInfo(), new SystemCallbackImpl()) {}
329
Brian Lindahl64ee9452022-01-14 13:31:16 +0100330ResourceManagerService::ResourceManagerService(const sp<ProcessInfoInterface> &processInfo,
Chong Zhangdd726802019-08-21 17:24:13 -0700331 const sp<SystemCallbackInterface> &systemResource)
Ronghua Wu231c3d12015-03-11 15:10:32 -0700332 : mProcessInfo(processInfo),
Chong Zhangdd726802019-08-21 17:24:13 -0700333 mSystemCB(systemResource),
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700334 mServiceLog(new ServiceLog()),
Ronghua Wu231c3d12015-03-11 15:10:32 -0700335 mSupportsMultipleSecureCodecs(true),
Chong Zhang79d2b282018-04-17 14:14:31 -0700336 mSupportsSecureWithNonSecureCodec(true),
Chong Zhangfdd512a2019-11-22 11:03:14 -0800337 mCpuBoostCount(0),
338 mDeathRecipient(AIBinder_DeathRecipient_new(DeathNotifier::BinderDiedCallback)) {
Chong Zhangdd726802019-08-21 17:24:13 -0700339 mSystemCB->noteResetVideo();
Chong Zhangee33d642019-08-08 14:26:43 -0700340}
Ronghua Wu231c3d12015-03-11 15:10:32 -0700341
Chong Zhangfdd512a2019-11-22 11:03:14 -0800342//static
343void ResourceManagerService::instantiate() {
344 std::shared_ptr<ResourceManagerService> service =
345 ::ndk::SharedRefBase::make<ResourceManagerService>();
346 binder_status_t status =
Charles Chend2fb31f2023-02-16 00:11:56 +0000347 AServiceManager_addServiceWithFlag(
348 service->asBinder().get(), getServiceName(),
349 AServiceManager_AddServiceFlag::ADD_SERVICE_ALLOW_ISOLATED);
Chong Zhangfdd512a2019-11-22 11:03:14 -0800350 if (status != STATUS_OK) {
351 return;
352 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700353
354 std::shared_ptr<ResourceObserverService> observerService =
355 ResourceObserverService::instantiate();
356
357 if (observerService != nullptr) {
358 service->setObserverService(observerService);
359 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800360 // TODO: mediaserver main() is already starting the thread pool,
361 // move this to mediaserver main() when other services in mediaserver
362 // are converted to ndk-platform aidl.
363 //ABinderProcess_startThreadPool();
364}
365
Ronghua Wu231c3d12015-03-11 15:10:32 -0700366ResourceManagerService::~ResourceManagerService() {}
367
Chong Zhanga9d45c72020-09-09 12:41:17 -0700368void ResourceManagerService::setObserverService(
369 const std::shared_ptr<ResourceObserverService>& observerService) {
370 mObserverService = observerService;
371}
372
Chong Zhang181e6952019-10-09 13:23:39 -0700373Status ResourceManagerService::config(const std::vector<MediaResourcePolicyParcel>& policies) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700374 String8 log = String8::format("config(%s)", getString(policies).string());
375 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700376
377 Mutex::Autolock lock(mLock);
378 for (size_t i = 0; i < policies.size(); ++i) {
Chong Zhang181e6952019-10-09 13:23:39 -0700379 const std::string &type = policies[i].type;
380 const std::string &value = policies[i].value;
381 if (type == MediaResourcePolicy::kPolicySupportsMultipleSecureCodecs()) {
Ronghua Wu9ba21b92015-04-21 14:23:06 -0700382 mSupportsMultipleSecureCodecs = (value == "true");
Chong Zhang181e6952019-10-09 13:23:39 -0700383 } else if (type == MediaResourcePolicy::kPolicySupportsSecureWithNonSecureCodec()) {
Ronghua Wu9ba21b92015-04-21 14:23:06 -0700384 mSupportsSecureWithNonSecureCodec = (value == "true");
Ronghua Wu231c3d12015-03-11 15:10:32 -0700385 }
386 }
Chong Zhang181e6952019-10-09 13:23:39 -0700387 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700388}
389
Brian Lindahl64ee9452022-01-14 13:31:16 +0100390void ResourceManagerService::onFirstAdded(const MediaResourceParcel& resource,
391 const ResourceInfo& clientInfo) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700392 // first time added
Chong Zhang181e6952019-10-09 13:23:39 -0700393 if (resource.type == MediaResource::Type::kCpuBoost
394 && resource.subType == MediaResource::SubType::kUnspecifiedSubType) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700395 // Request it on every new instance of kCpuBoost, as the media.codec
396 // could have died, if we only do it the first time subsequent instances
397 // never gets the boost.
Chong Zhangfdd512a2019-11-22 11:03:14 -0800398 if (mSystemCB->requestCpusetBoost(true) != OK) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700399 ALOGW("couldn't request cpuset boost");
400 }
401 mCpuBoostCount++;
Chong Zhang181e6952019-10-09 13:23:39 -0700402 } else if (resource.type == MediaResource::Type::kBattery
403 && resource.subType == MediaResource::SubType::kVideoCodec) {
Chong Zhangdd726802019-08-21 17:24:13 -0700404 mSystemCB->noteStartVideo(clientInfo.uid);
Chong Zhangfb092d32019-08-12 09:45:44 -0700405 }
406}
407
Brian Lindahl64ee9452022-01-14 13:31:16 +0100408void ResourceManagerService::onLastRemoved(const MediaResourceParcel& resource,
409 const ResourceInfo& clientInfo) {
Chong Zhang181e6952019-10-09 13:23:39 -0700410 if (resource.type == MediaResource::Type::kCpuBoost
411 && resource.subType == MediaResource::SubType::kUnspecifiedSubType
Chong Zhangfb092d32019-08-12 09:45:44 -0700412 && mCpuBoostCount > 0) {
413 if (--mCpuBoostCount == 0) {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800414 mSystemCB->requestCpusetBoost(false);
Chong Zhangfb092d32019-08-12 09:45:44 -0700415 }
Chong Zhang181e6952019-10-09 13:23:39 -0700416 } else if (resource.type == MediaResource::Type::kBattery
417 && resource.subType == MediaResource::SubType::kVideoCodec) {
Chong Zhangdd726802019-08-21 17:24:13 -0700418 mSystemCB->noteStopVideo(clientInfo.uid);
Chong Zhangfb092d32019-08-12 09:45:44 -0700419 }
420}
421
Brian Lindahl64ee9452022-01-14 13:31:16 +0100422void ResourceManagerService::mergeResources(MediaResourceParcel& r1,
423 const MediaResourceParcel& r2) {
Chong Zhang181e6952019-10-09 13:23:39 -0700424 // The resource entry on record is maintained to be in [0,INT64_MAX].
425 // Clamp if merging in the new resource value causes it to go out of bound.
426 // Note that the new resource value could be negative, eg.DrmSession, the
427 // value goes lower when the session is used more often. During reclaim
428 // the session with the highest value (lowest usage) would be closed.
429 if (r2.value < INT64_MAX - r1.value) {
430 r1.value += r2.value;
431 if (r1.value < 0) {
432 r1.value = 0;
433 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700434 } else {
Chong Zhang181e6952019-10-09 13:23:39 -0700435 r1.value = INT64_MAX;
Robert Shihc3af31b2019-09-20 21:45:01 -0700436 }
437}
438
Brian Lindahl64ee9452022-01-14 13:31:16 +0100439Status ResourceManagerService::addResource(int32_t pid, int32_t uid, int64_t clientId,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800440 const std::shared_ptr<IResourceManagerClient>& client,
Chong Zhang181e6952019-10-09 13:23:39 -0700441 const std::vector<MediaResourceParcel>& resources) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700442 String8 log = String8::format("addResource(pid %d, clientId %lld, resources %s)",
Ronghua Wu231c3d12015-03-11 15:10:32 -0700443 pid, (long long) clientId, getString(resources).string());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700444 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700445
446 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100447 if (!mProcessInfo->isPidUidTrusted(pid, uid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800448 pid_t callingPid = IPCThreadState::self()->getCallingPid();
449 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100450 ALOGW("%s called with untrusted pid %d or uid %d, using calling pid %d, uid %d",
451 __FUNCTION__, pid, uid, callingPid, callingUid);
Chong Zhangc7303e82020-12-02 16:38:52 -0800452 pid = callingPid;
453 uid = callingUid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800454 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700455 ResourceInfos& infos = getResourceInfosForEdit(pid, mMap);
Chong Zhangee33d642019-08-08 14:26:43 -0700456 ResourceInfo& info = getResourceInfoForEdit(uid, clientId, client, infos);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700457 ResourceList resourceAdded;
Chong Zhang79d2b282018-04-17 14:14:31 -0700458
459 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700460 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700461 const auto resType = std::tuple(res.type, res.subType, res.id);
462
463 if (res.value < 0 && res.type != MediaResource::Type::kDrmSession) {
464 ALOGW("Ignoring request to remove negative value of non-drm resource");
465 continue;
466 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700467 if (info.resources.find(resType) == info.resources.end()) {
Chong Zhang181e6952019-10-09 13:23:39 -0700468 if (res.value <= 0) {
469 // We can't init a new entry with negative value, although it's allowed
470 // to merge in negative values after the initial add.
471 ALOGW("Ignoring request to add new resource entry with value <= 0");
472 continue;
473 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700474 onFirstAdded(res, info);
475 info.resources[resType] = res;
Chong Zhangfb092d32019-08-12 09:45:44 -0700476 } else {
Robert Shihc3af31b2019-09-20 21:45:01 -0700477 mergeResources(info.resources[resType], res);
Chong Zhang79d2b282018-04-17 14:14:31 -0700478 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700479 // Add it to the list of added resources for observers.
480 auto it = resourceAdded.find(resType);
481 if (it == resourceAdded.end()) {
482 resourceAdded[resType] = res;
483 } else {
484 mergeResources(it->second, res);
485 }
Chong Zhang79d2b282018-04-17 14:14:31 -0700486 }
Chong Zhang97d367b2020-09-16 12:53:14 -0700487 if (info.cookie == 0 && client != nullptr) {
Arun Johnsond1f59732022-03-25 17:10:29 +0000488 info.cookie = addCookieAndLink_l(client,
Chong Zhang97d367b2020-09-16 12:53:14 -0700489 new DeathNotifier(ref<ResourceManagerService>(), pid, clientId));
Wonsik Kim3e378962017-01-05 17:00:02 +0900490 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700491 if (mObserverService != nullptr && !resourceAdded.empty()) {
492 mObserverService->onResourceAdded(uid, pid, resourceAdded);
493 }
Dongwon Kangfe508d32015-12-15 14:22:05 +0900494 notifyResourceGranted(pid, resources);
Chong Zhang181e6952019-10-09 13:23:39 -0700495 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700496}
497
Brian Lindahl64ee9452022-01-14 13:31:16 +0100498Status ResourceManagerService::removeResource(int32_t pid, int64_t clientId,
Chong Zhang181e6952019-10-09 13:23:39 -0700499 const std::vector<MediaResourceParcel>& resources) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700500 String8 log = String8::format("removeResource(pid %d, clientId %lld, resources %s)",
501 pid, (long long) clientId, getString(resources).string());
502 mServiceLog->add(log);
503
504 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100505 if (!mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800506 pid_t callingPid = IPCThreadState::self()->getCallingPid();
507 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
508 pid, callingPid);
509 pid = callingPid;
Chong Zhangfb092d32019-08-12 09:45:44 -0700510 }
511 ssize_t index = mMap.indexOfKey(pid);
512 if (index < 0) {
513 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700514 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700515 }
516 ResourceInfos &infos = mMap.editValueAt(index);
517
518 index = infos.indexOfKey(clientId);
519 if (index < 0) {
520 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700521 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700522 }
523
524 ResourceInfo &info = infos.editValueAt(index);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700525 ResourceList resourceRemoved;
Chong Zhangfb092d32019-08-12 09:45:44 -0700526 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700527 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700528 const auto resType = std::tuple(res.type, res.subType, res.id);
529
530 if (res.value < 0) {
531 ALOGW("Ignoring request to remove negative value of resource");
532 continue;
533 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700534 // ignore if we don't have it
535 if (info.resources.find(resType) != info.resources.end()) {
Chong Zhang181e6952019-10-09 13:23:39 -0700536 MediaResourceParcel &resource = info.resources[resType];
Chong Zhanga9d45c72020-09-09 12:41:17 -0700537 MediaResourceParcel actualRemoved = res;
Chong Zhang181e6952019-10-09 13:23:39 -0700538 if (resource.value > res.value) {
539 resource.value -= res.value;
Chong Zhangfb092d32019-08-12 09:45:44 -0700540 } else {
Robert Shihc3af31b2019-09-20 21:45:01 -0700541 onLastRemoved(res, info);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700542 actualRemoved.value = resource.value;
Chong Zhang102b3e32020-11-02 12:21:50 -0800543 info.resources.erase(resType);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700544 }
545
546 // Add it to the list of removed resources for observers.
547 auto it = resourceRemoved.find(resType);
548 if (it == resourceRemoved.end()) {
549 resourceRemoved[resType] = actualRemoved;
550 } else {
551 mergeResources(it->second, actualRemoved);
Chong Zhangfb092d32019-08-12 09:45:44 -0700552 }
553 }
554 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700555 if (mObserverService != nullptr && !resourceRemoved.empty()) {
556 mObserverService->onResourceRemoved(info.uid, pid, resourceRemoved);
557 }
Chong Zhang181e6952019-10-09 13:23:39 -0700558 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700559}
560
Chong Zhang181e6952019-10-09 13:23:39 -0700561Status ResourceManagerService::removeClient(int32_t pid, int64_t clientId) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800562 removeResource(pid, clientId, true /*checkValid*/);
Chong Zhang181e6952019-10-09 13:23:39 -0700563 return Status::ok();
Wonsik Kim3e378962017-01-05 17:00:02 +0900564}
565
Chong Zhang181e6952019-10-09 13:23:39 -0700566Status ResourceManagerService::removeResource(int pid, int64_t clientId, bool checkValid) {
Ronghua Wu37c89242015-07-15 12:23:48 -0700567 String8 log = String8::format(
568 "removeResource(pid %d, clientId %lld)",
569 pid, (long long) clientId);
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700570 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700571
572 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100573 if (checkValid && !mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800574 pid_t callingPid = IPCThreadState::self()->getCallingPid();
575 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
576 pid, callingPid);
577 pid = callingPid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800578 }
Ronghua Wu37c89242015-07-15 12:23:48 -0700579 ssize_t index = mMap.indexOfKey(pid);
580 if (index < 0) {
581 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700582 return Status::ok();
Ronghua Wu37c89242015-07-15 12:23:48 -0700583 }
Ronghua Wu37c89242015-07-15 12:23:48 -0700584 ResourceInfos &infos = mMap.editValueAt(index);
Chong Zhangfb092d32019-08-12 09:45:44 -0700585
586 index = infos.indexOfKey(clientId);
587 if (index < 0) {
588 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700589 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700590 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700591
592 const ResourceInfo &info = infos[index];
593 for (auto it = info.resources.begin(); it != info.resources.end(); it++) {
594 onLastRemoved(it->second, info);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700595 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700596
Arun Johnsond1f59732022-03-25 17:10:29 +0000597 removeCookieAndUnlink_l(info.client, info.cookie);
Chong Zhangfb092d32019-08-12 09:45:44 -0700598
Chong Zhanga9d45c72020-09-09 12:41:17 -0700599 if (mObserverService != nullptr && !info.resources.empty()) {
600 mObserverService->onResourceRemoved(info.uid, pid, info.resources);
601 }
602
Chong Zhangfb092d32019-08-12 09:45:44 -0700603 infos.removeItemsAt(index);
Chong Zhang181e6952019-10-09 13:23:39 -0700604 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700605}
606
Brian Lindahl64ee9452022-01-14 13:31:16 +0100607void ResourceManagerService::getClientForResource_l(int callingPid, const MediaResourceParcel *res,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800608 Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700609 if (res == NULL) {
610 return;
611 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800612 std::shared_ptr<IResourceManagerClient> client;
Brian Lindahl64ee9452022-01-14 13:31:16 +0100613 if (getLowestPriorityBiggestClient_l(callingPid, res->type, res->subType, &client)) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700614 clients->push_back(client);
615 }
616}
617
Brian Lindahl64ee9452022-01-14 13:31:16 +0100618Status ResourceManagerService::reclaimResource(int32_t callingPid,
619 const std::vector<MediaResourceParcel>& resources, bool* _aidl_return) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700620 String8 log = String8::format("reclaimResource(callingPid %d, resources %s)",
Ronghua Wu231c3d12015-03-11 15:10:32 -0700621 callingPid, getString(resources).string());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700622 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700623 *_aidl_return = false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700624
Chong Zhangfdd512a2019-11-22 11:03:14 -0800625 Vector<std::shared_ptr<IResourceManagerClient>> clients;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700626 {
627 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100628 if (!mProcessInfo->isPidTrusted(callingPid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800629 pid_t actualCallingPid = IPCThreadState::self()->getCallingPid();
630 ALOGW("%s called with untrusted pid %d, using actual calling pid %d", __FUNCTION__,
631 callingPid, actualCallingPid);
632 callingPid = actualCallingPid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800633 }
Chong Zhang181e6952019-10-09 13:23:39 -0700634 const MediaResourceParcel *secureCodec = NULL;
635 const MediaResourceParcel *nonSecureCodec = NULL;
636 const MediaResourceParcel *graphicMemory = NULL;
637 const MediaResourceParcel *drmSession = NULL;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700638 for (size_t i = 0; i < resources.size(); ++i) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100639 switch (resources[i].type) {
640 case MediaResource::Type::kSecureCodec:
641 secureCodec = &resources[i];
642 break;
643 case MediaResource::Type::kNonSecureCodec:
644 nonSecureCodec = &resources[i];
645 break;
646 case MediaResource::Type::kGraphicMemory:
647 graphicMemory = &resources[i];
648 break;
649 case MediaResource::Type::kDrmSession:
650 drmSession = &resources[i];
651 break;
652 default:
653 break;
Ronghua Wu05d89f12015-07-07 16:47:42 -0700654 }
655 }
656
657 // first pass to handle secure/non-secure codec conflict
658 if (secureCodec != NULL) {
659 if (!mSupportsMultipleSecureCodecs) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100660 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec,
661 secureCodec->subType, &clients)) {
Chong Zhang181e6952019-10-09 13:23:39 -0700662 return Status::ok();
Ronghua Wu05d89f12015-07-07 16:47:42 -0700663 }
664 }
665 if (!mSupportsSecureWithNonSecureCodec) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100666 if (!getAllClients_l(callingPid, MediaResource::Type::kNonSecureCodec,
667 secureCodec->subType, &clients)) {
Chong Zhang181e6952019-10-09 13:23:39 -0700668 return Status::ok();
Ronghua Wu05d89f12015-07-07 16:47:42 -0700669 }
670 }
671 }
672 if (nonSecureCodec != NULL) {
673 if (!mSupportsSecureWithNonSecureCodec) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100674 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec,
675 nonSecureCodec->subType, &clients)) {
Chong Zhang181e6952019-10-09 13:23:39 -0700676 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700677 }
678 }
679 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700680 if (drmSession != NULL) {
681 getClientForResource_l(callingPid, drmSession, &clients);
682 if (clients.size() == 0) {
Chong Zhang181e6952019-10-09 13:23:39 -0700683 return Status::ok();
Robert Shihc3af31b2019-09-20 21:45:01 -0700684 }
685 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700686
687 if (clients.size() == 0) {
688 // if no secure/non-secure codec conflict, run second pass to handle other resources.
Ronghua Wu05d89f12015-07-07 16:47:42 -0700689 getClientForResource_l(callingPid, graphicMemory, &clients);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700690 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700691
692 if (clients.size() == 0) {
693 // if we are here, run the third pass to free one codec with the same type.
Ronghua Wu05d89f12015-07-07 16:47:42 -0700694 getClientForResource_l(callingPid, secureCodec, &clients);
695 getClientForResource_l(callingPid, nonSecureCodec, &clients);
696 }
697
698 if (clients.size() == 0) {
699 // if we are here, run the fourth pass to free one codec with the different type.
700 if (secureCodec != NULL) {
Wonsik Kimb3639012022-03-16 13:57:41 -0700701 MediaResource temp(MediaResource::Type::kNonSecureCodec, secureCodec->subType, 1);
Ronghua Wu05d89f12015-07-07 16:47:42 -0700702 getClientForResource_l(callingPid, &temp, &clients);
703 }
704 if (nonSecureCodec != NULL) {
Wonsik Kimb3639012022-03-16 13:57:41 -0700705 MediaResource temp(MediaResource::Type::kSecureCodec, nonSecureCodec->subType, 1);
Ronghua Wu05d89f12015-07-07 16:47:42 -0700706 getClientForResource_l(callingPid, &temp, &clients);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700707 }
708 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700709 }
710
Brian Lindahl64ee9452022-01-14 13:31:16 +0100711 *_aidl_return = reclaimUnconditionallyFrom(clients);
Wonsik Kim271429d2020-10-01 10:12:56 -0700712 return Status::ok();
713}
714
Brian Lindahl64ee9452022-01-14 13:31:16 +0100715bool ResourceManagerService::reclaimUnconditionallyFrom(
Wonsik Kim271429d2020-10-01 10:12:56 -0700716 const Vector<std::shared_ptr<IResourceManagerClient>> &clients) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700717 if (clients.size() == 0) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700718 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700719 }
720
Chong Zhangfdd512a2019-11-22 11:03:14 -0800721 std::shared_ptr<IResourceManagerClient> failedClient;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700722 for (size_t i = 0; i < clients.size(); ++i) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700723 String8 log = String8::format("reclaimResource from client %p", clients[i].get());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700724 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700725 bool success;
726 Status status = clients[i]->reclaimResource(&success);
727 if (!status.isOk() || !success) {
Ronghua Wu67e7f542015-03-13 10:47:08 -0700728 failedClient = clients[i];
729 break;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700730 }
731 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700732
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700733 if (failedClient == NULL) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700734 return true;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700735 }
736
Brian Lindahl9f626cf2022-04-25 13:29:59 +0200737 int failedClientPid = -1;
Ronghua Wu67e7f542015-03-13 10:47:08 -0700738 {
739 Mutex::Autolock lock(mLock);
740 bool found = false;
741 for (size_t i = 0; i < mMap.size(); ++i) {
742 ResourceInfos &infos = mMap.editValueAt(i);
743 for (size_t j = 0; j < infos.size();) {
744 if (infos[j].client == failedClient) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700745 j = infos.removeItemsAt(j);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700746 found = true;
747 } else {
748 ++j;
749 }
750 }
751 if (found) {
Brian Lindahl9f626cf2022-04-25 13:29:59 +0200752 failedClientPid = mMap.keyAt(i);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700753 break;
754 }
755 }
Brian Lindahl9f626cf2022-04-25 13:29:59 +0200756 if (found) {
757 ALOGW("Failed to reclaim resources from client with pid %d", failedClientPid);
758 } else {
759 ALOGW("Failed to reclaim resources from unlocateable client");
Ronghua Wu67e7f542015-03-13 10:47:08 -0700760 }
761 }
762
Wonsik Kim271429d2020-10-01 10:12:56 -0700763 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700764}
765
Brian Lindahl64ee9452022-01-14 13:31:16 +0100766Status ResourceManagerService::overridePid(int originalPid, int newPid) {
Henry Fang32762922020-01-28 18:40:39 -0800767 String8 log = String8::format("overridePid(originalPid %d, newPid %d)",
768 originalPid, newPid);
769 mServiceLog->add(log);
770
771 // allow if this is called from the same process or the process has
772 // permission.
773 if ((AIBinder_getCallingPid() != getpid()) &&
774 (checkCallingPermission(String16(
775 "android.permission.MEDIA_RESOURCE_OVERRIDE_PID")) == false)) {
776 ALOGE(
777 "Permission Denial: can't access overridePid method from pid=%d, "
778 "self pid=%d\n",
779 AIBinder_getCallingPid(), getpid());
780 return Status::fromServiceSpecificError(PERMISSION_DENIED);
781 }
782
783 {
784 Mutex::Autolock lock(mLock);
785 mOverridePidMap.erase(originalPid);
786 if (newPid != -1) {
787 mOverridePidMap.emplace(originalPid, newPid);
788 }
789 }
790
791 return Status::ok();
792}
793
Chong Zhang97d367b2020-09-16 12:53:14 -0700794Status ResourceManagerService::overrideProcessInfo(
Brian Lindahl64ee9452022-01-14 13:31:16 +0100795 const std::shared_ptr<IResourceManagerClient>& client, int pid, int procState,
Chong Zhang97d367b2020-09-16 12:53:14 -0700796 int oomScore) {
797 String8 log = String8::format("overrideProcessInfo(pid %d, procState %d, oomScore %d)",
798 pid, procState, oomScore);
799 mServiceLog->add(log);
800
801 // Only allow the override if the caller already can access process state and oom scores.
802 int callingPid = AIBinder_getCallingPid();
803 if (callingPid != getpid() && (callingPid != pid || !checkCallingPermission(String16(
804 "android.permission.GET_PROCESS_STATE_AND_OOM_SCORE")))) {
805 ALOGE("Permission Denial: overrideProcessInfo method from pid=%d", callingPid);
806 return Status::fromServiceSpecificError(PERMISSION_DENIED);
807 }
808
809 if (client == nullptr) {
810 return Status::fromServiceSpecificError(BAD_VALUE);
811 }
812
813 Mutex::Autolock lock(mLock);
814 removeProcessInfoOverride_l(pid);
815
816 if (!mProcessInfo->overrideProcessInfo(pid, procState, oomScore)) {
817 // Override value is rejected by ProcessInfo.
818 return Status::fromServiceSpecificError(BAD_VALUE);
819 }
820
Arun Johnsond1f59732022-03-25 17:10:29 +0000821 uintptr_t cookie = addCookieAndLink_l(client,
Chong Zhang97d367b2020-09-16 12:53:14 -0700822 new OverrideProcessInfoDeathNotifier(ref<ResourceManagerService>(), pid));
823
824 mProcessInfoOverrideMap.emplace(pid, ProcessInfoOverride{cookie, client});
825
826 return Status::ok();
827}
828
Arun Johnsond1f59732022-03-25 17:10:29 +0000829uintptr_t ResourceManagerService::addCookieAndLink_l(
830 const std::shared_ptr<IResourceManagerClient>& client, const sp<DeathNotifier>& notifier) {
831 if (client == nullptr) {
832 return 0;
833 }
Chong Zhang97d367b2020-09-16 12:53:14 -0700834 std::scoped_lock lock{sCookieLock};
835
836 uintptr_t cookie;
837 // Need to skip cookie 0 (if it wraps around). ResourceInfo has cookie initialized to 0
838 // indicating the death notifier is not created yet.
839 while ((cookie = ++sCookieCounter) == 0);
Arun Johnsond1f59732022-03-25 17:10:29 +0000840 AIBinder_linkToDeath(client->asBinder().get(), mDeathRecipient.get(), (void*)cookie);
Chong Zhang97d367b2020-09-16 12:53:14 -0700841 sCookieToDeathNotifierMap.emplace(cookie, notifier);
842
843 return cookie;
844}
845
Arun Johnsond1f59732022-03-25 17:10:29 +0000846void ResourceManagerService::removeCookieAndUnlink_l(
847 const std::shared_ptr<IResourceManagerClient>& client, uintptr_t cookie) {
Chong Zhang97d367b2020-09-16 12:53:14 -0700848 std::scoped_lock lock{sCookieLock};
Arun Johnsond1f59732022-03-25 17:10:29 +0000849 if (client != nullptr) {
850 AIBinder_unlinkToDeath(client->asBinder().get(), mDeathRecipient.get(), (void*)cookie);
851 }
Chong Zhang97d367b2020-09-16 12:53:14 -0700852 sCookieToDeathNotifierMap.erase(cookie);
853}
854
855void ResourceManagerService::removeProcessInfoOverride(int pid) {
856 Mutex::Autolock lock(mLock);
857
858 removeProcessInfoOverride_l(pid);
859}
860
861void ResourceManagerService::removeProcessInfoOverride_l(int pid) {
862 auto it = mProcessInfoOverrideMap.find(pid);
863 if (it == mProcessInfoOverrideMap.end()) {
864 return;
865 }
866
867 mProcessInfo->removeProcessInfoOverride(pid);
868
Arun Johnsond1f59732022-03-25 17:10:29 +0000869 removeCookieAndUnlink_l(it->second.client, it->second.cookie);
Chong Zhang97d367b2020-09-16 12:53:14 -0700870
871 mProcessInfoOverrideMap.erase(pid);
872}
873
Wonsik Kimd20e9362020-04-28 10:42:57 -0700874Status ResourceManagerService::markClientForPendingRemoval(int32_t pid, int64_t clientId) {
875 String8 log = String8::format(
876 "markClientForPendingRemoval(pid %d, clientId %lld)",
877 pid, (long long) clientId);
878 mServiceLog->add(log);
879
880 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100881 if (!mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800882 pid_t callingPid = IPCThreadState::self()->getCallingPid();
883 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
884 pid, callingPid);
885 pid = callingPid;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700886 }
887 ssize_t index = mMap.indexOfKey(pid);
888 if (index < 0) {
889 ALOGV("markClientForPendingRemoval: didn't find pid %d for clientId %lld",
890 pid, (long long)clientId);
891 return Status::ok();
892 }
893 ResourceInfos &infos = mMap.editValueAt(index);
894
895 index = infos.indexOfKey(clientId);
896 if (index < 0) {
897 ALOGV("markClientForPendingRemoval: didn't find clientId %lld", (long long) clientId);
898 return Status::ok();
899 }
900
901 ResourceInfo &info = infos.editValueAt(index);
902 info.pendingRemoval = true;
903 return Status::ok();
904}
905
Wonsik Kim271429d2020-10-01 10:12:56 -0700906Status ResourceManagerService::reclaimResourcesFromClientsPendingRemoval(int32_t pid) {
907 String8 log = String8::format("reclaimResourcesFromClientsPendingRemoval(pid %d)", pid);
908 mServiceLog->add(log);
909
910 Vector<std::shared_ptr<IResourceManagerClient>> clients;
911 {
912 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100913 if (!mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800914 pid_t callingPid = IPCThreadState::self()->getCallingPid();
915 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
916 pid, callingPid);
917 pid = callingPid;
Wonsik Kim271429d2020-10-01 10:12:56 -0700918 }
919
920 for (MediaResource::Type type : {MediaResource::Type::kSecureCodec,
921 MediaResource::Type::kNonSecureCodec,
922 MediaResource::Type::kGraphicMemory,
923 MediaResource::Type::kDrmSession}) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100924 switch (type) {
925 // Codec resources are segregated by audio, video and image domains.
926 case MediaResource::Type::kSecureCodec:
927 case MediaResource::Type::kNonSecureCodec:
928 for (MediaResource::SubType subType : {MediaResource::SubType::kAudioCodec,
929 MediaResource::SubType::kVideoCodec,
930 MediaResource::SubType::kImageCodec}) {
931 std::shared_ptr<IResourceManagerClient> client;
932 if (getBiggestClientPendingRemoval_l(pid, type, subType, &client)) {
933 clients.add(client);
934 continue;
935 }
936 }
937 break;
938 // Non-codec resources are shared by audio, video and image codecs (no subtype).
939 default:
940 std::shared_ptr<IResourceManagerClient> client;
941 if (getBiggestClientPendingRemoval_l(pid, type,
942 MediaResource::SubType::kUnspecifiedSubType, &client)) {
943 clients.add(client);
944 }
945 break;
Wonsik Kim271429d2020-10-01 10:12:56 -0700946 }
947 }
948 }
949
950 if (!clients.empty()) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100951 reclaimUnconditionallyFrom(clients);
Wonsik Kim271429d2020-10-01 10:12:56 -0700952 }
953 return Status::ok();
954}
955
Henry Fang32762922020-01-28 18:40:39 -0800956bool ResourceManagerService::getPriority_l(int pid, int* priority) {
957 int newPid = pid;
958
959 if (mOverridePidMap.find(pid) != mOverridePidMap.end()) {
960 newPid = mOverridePidMap[pid];
961 ALOGD("getPriority_l: use override pid %d instead original pid %d",
962 newPid, pid);
963 }
964
965 return mProcessInfo->getPriority(newPid, priority);
966}
967
Brian Lindahl64ee9452022-01-14 13:31:16 +0100968bool ResourceManagerService::getAllClients_l(int callingPid, MediaResource::Type type,
969 MediaResource::SubType subType, Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800970 Vector<std::shared_ptr<IResourceManagerClient>> temp;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700971 for (size_t i = 0; i < mMap.size(); ++i) {
972 ResourceInfos &infos = mMap.editValueAt(i);
973 for (size_t j = 0; j < infos.size(); ++j) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100974 if (hasResourceType(type, subType, infos[j].resources)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700975 if (!isCallingPriorityHigher_l(callingPid, mMap.keyAt(i))) {
976 // some higher/equal priority process owns the resource,
977 // this request can't be fulfilled.
978 ALOGE("getAllClients_l: can't reclaim resource %s from pid %d",
Ronghua Wuea15fd22016-03-03 13:35:05 -0800979 asString(type), mMap.keyAt(i));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700980 return false;
981 }
982 temp.push_back(infos[j].client);
983 }
984 }
985 }
986 if (temp.size() == 0) {
Ronghua Wuea15fd22016-03-03 13:35:05 -0800987 ALOGV("getAllClients_l: didn't find any resource %s", asString(type));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700988 return true;
989 }
990 clients->appendVector(temp);
991 return true;
992}
993
Brian Lindahl64ee9452022-01-14 13:31:16 +0100994bool ResourceManagerService::getLowestPriorityBiggestClient_l(int callingPid,
995 MediaResource::Type type, MediaResource::SubType subType,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800996 std::shared_ptr<IResourceManagerClient> *client) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700997 int lowestPriorityPid;
998 int lowestPriority;
999 int callingPriority;
Wonsik Kimd20e9362020-04-28 10:42:57 -07001000
1001 // Before looking into other processes, check if we have clients marked for
1002 // pending removal in the same process.
Brian Lindahl64ee9452022-01-14 13:31:16 +01001003 if (getBiggestClientPendingRemoval_l(callingPid, type, subType, client)) {
Wonsik Kimd20e9362020-04-28 10:42:57 -07001004 return true;
1005 }
Henry Fang32762922020-01-28 18:40:39 -08001006 if (!getPriority_l(callingPid, &callingPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001007 ALOGE("getLowestPriorityBiggestClient_l: can't get process priority for pid %d",
1008 callingPid);
1009 return false;
1010 }
Brian Lindahl64ee9452022-01-14 13:31:16 +01001011 if (!getLowestPriorityPid_l(type, subType, &lowestPriorityPid, &lowestPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001012 return false;
1013 }
1014 if (lowestPriority <= callingPriority) {
1015 ALOGE("getLowestPriorityBiggestClient_l: lowest priority %d vs caller priority %d",
1016 lowestPriority, callingPriority);
1017 return false;
1018 }
1019
Brian Lindahl64ee9452022-01-14 13:31:16 +01001020 if (!getBiggestClient_l(lowestPriorityPid, type, subType, client)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001021 return false;
1022 }
1023 return true;
1024}
1025
Brian Lindahl64ee9452022-01-14 13:31:16 +01001026bool ResourceManagerService::getLowestPriorityPid_l(MediaResource::Type type,
1027 MediaResource::SubType subType, int *lowestPriorityPid, int *lowestPriority) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001028 int pid = -1;
1029 int priority = -1;
1030 for (size_t i = 0; i < mMap.size(); ++i) {
1031 if (mMap.valueAt(i).size() == 0) {
1032 // no client on this process.
1033 continue;
1034 }
Brian Lindahl64ee9452022-01-14 13:31:16 +01001035 if (!hasResourceType(type, subType, mMap.valueAt(i))) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001036 // doesn't have the requested resource type
1037 continue;
1038 }
1039 int tempPid = mMap.keyAt(i);
1040 int tempPriority;
Henry Fang32762922020-01-28 18:40:39 -08001041 if (!getPriority_l(tempPid, &tempPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001042 ALOGV("getLowestPriorityPid_l: can't get priority of pid %d, skipped", tempPid);
1043 // TODO: remove this pid from mMap?
1044 continue;
1045 }
1046 if (pid == -1 || tempPriority > priority) {
1047 // initial the value
1048 pid = tempPid;
1049 priority = tempPriority;
1050 }
1051 }
1052 if (pid != -1) {
1053 *lowestPriorityPid = pid;
1054 *lowestPriority = priority;
1055 }
1056 return (pid != -1);
1057}
1058
1059bool ResourceManagerService::isCallingPriorityHigher_l(int callingPid, int pid) {
1060 int callingPidPriority;
Henry Fang32762922020-01-28 18:40:39 -08001061 if (!getPriority_l(callingPid, &callingPidPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001062 return false;
1063 }
1064
1065 int priority;
Henry Fang32762922020-01-28 18:40:39 -08001066 if (!getPriority_l(pid, &priority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001067 return false;
1068 }
1069
1070 return (callingPidPriority < priority);
1071}
1072
Brian Lindahl64ee9452022-01-14 13:31:16 +01001073bool ResourceManagerService::getBiggestClientPendingRemoval_l(int pid, MediaResource::Type type,
1074 MediaResource::SubType subType, std::shared_ptr<IResourceManagerClient> *client) {
1075 return getBiggestClient_l(pid, type, subType, client, true /* pendingRemovalOnly */);
1076}
1077
1078bool ResourceManagerService::getBiggestClient_l(int pid, MediaResource::Type type,
1079 MediaResource::SubType subType, std::shared_ptr<IResourceManagerClient> *client,
Wonsik Kimd20e9362020-04-28 10:42:57 -07001080 bool pendingRemovalOnly) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001081 ssize_t index = mMap.indexOfKey(pid);
1082 if (index < 0) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001083 ALOGE_IF(!pendingRemovalOnly,
1084 "getBiggestClient_l: can't find resource info for pid %d", pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001085 return false;
1086 }
1087
Chong Zhangfdd512a2019-11-22 11:03:14 -08001088 std::shared_ptr<IResourceManagerClient> clientTemp;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001089 uint64_t largestValue = 0;
1090 const ResourceInfos &infos = mMap.valueAt(index);
1091 for (size_t i = 0; i < infos.size(); ++i) {
Chong Zhangfb092d32019-08-12 09:45:44 -07001092 const ResourceList &resources = infos[i].resources;
Wonsik Kimd20e9362020-04-28 10:42:57 -07001093 if (pendingRemovalOnly && !infos[i].pendingRemoval) {
1094 continue;
1095 }
Chong Zhangfb092d32019-08-12 09:45:44 -07001096 for (auto it = resources.begin(); it != resources.end(); it++) {
Chong Zhang181e6952019-10-09 13:23:39 -07001097 const MediaResourceParcel &resource = it->second;
Brian Lindahl64ee9452022-01-14 13:31:16 +01001098 if (hasResourceType(type, subType, resource)) {
Chong Zhang181e6952019-10-09 13:23:39 -07001099 if (resource.value > largestValue) {
1100 largestValue = resource.value;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001101 clientTemp = infos[i].client;
1102 }
1103 }
1104 }
1105 }
1106
1107 if (clientTemp == NULL) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001108 ALOGE_IF(!pendingRemovalOnly,
Brian Lindahl64ee9452022-01-14 13:31:16 +01001109 "getBiggestClient_l: can't find resource type %s and subtype %s for pid %d",
1110 asString(type), asString(subType), pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001111 return false;
1112 }
1113
1114 *client = clientTemp;
1115 return true;
1116}
1117
Ronghua Wu231c3d12015-03-11 15:10:32 -07001118} // namespace android