blob: 5697acdf3943282d898fa55418cc7c467a8944be [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 =
Charlie Wang429ef822023-02-03 16:15:41 -0800347 AServiceManager_addServiceWithAllowIsolated(
348 service->asBinder().get(), getServiceName(), /*allowIsolated=*/ true);
Chong Zhangfdd512a2019-11-22 11:03:14 -0800349 if (status != STATUS_OK) {
350 return;
351 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700352
353 std::shared_ptr<ResourceObserverService> observerService =
354 ResourceObserverService::instantiate();
355
356 if (observerService != nullptr) {
357 service->setObserverService(observerService);
358 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800359 // TODO: mediaserver main() is already starting the thread pool,
360 // move this to mediaserver main() when other services in mediaserver
361 // are converted to ndk-platform aidl.
362 //ABinderProcess_startThreadPool();
363}
364
Ronghua Wu231c3d12015-03-11 15:10:32 -0700365ResourceManagerService::~ResourceManagerService() {}
366
Chong Zhanga9d45c72020-09-09 12:41:17 -0700367void ResourceManagerService::setObserverService(
368 const std::shared_ptr<ResourceObserverService>& observerService) {
369 mObserverService = observerService;
370}
371
Chong Zhang181e6952019-10-09 13:23:39 -0700372Status ResourceManagerService::config(const std::vector<MediaResourcePolicyParcel>& policies) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700373 String8 log = String8::format("config(%s)", getString(policies).string());
374 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700375
376 Mutex::Autolock lock(mLock);
377 for (size_t i = 0; i < policies.size(); ++i) {
Chong Zhang181e6952019-10-09 13:23:39 -0700378 const std::string &type = policies[i].type;
379 const std::string &value = policies[i].value;
380 if (type == MediaResourcePolicy::kPolicySupportsMultipleSecureCodecs()) {
Ronghua Wu9ba21b92015-04-21 14:23:06 -0700381 mSupportsMultipleSecureCodecs = (value == "true");
Chong Zhang181e6952019-10-09 13:23:39 -0700382 } else if (type == MediaResourcePolicy::kPolicySupportsSecureWithNonSecureCodec()) {
Ronghua Wu9ba21b92015-04-21 14:23:06 -0700383 mSupportsSecureWithNonSecureCodec = (value == "true");
Ronghua Wu231c3d12015-03-11 15:10:32 -0700384 }
385 }
Chong Zhang181e6952019-10-09 13:23:39 -0700386 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700387}
388
Brian Lindahl64ee9452022-01-14 13:31:16 +0100389void ResourceManagerService::onFirstAdded(const MediaResourceParcel& resource,
390 const ResourceInfo& clientInfo) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700391 // first time added
Chong Zhang181e6952019-10-09 13:23:39 -0700392 if (resource.type == MediaResource::Type::kCpuBoost
393 && resource.subType == MediaResource::SubType::kUnspecifiedSubType) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700394 // Request it on every new instance of kCpuBoost, as the media.codec
395 // could have died, if we only do it the first time subsequent instances
396 // never gets the boost.
Chong Zhangfdd512a2019-11-22 11:03:14 -0800397 if (mSystemCB->requestCpusetBoost(true) != OK) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700398 ALOGW("couldn't request cpuset boost");
399 }
400 mCpuBoostCount++;
Chong Zhang181e6952019-10-09 13:23:39 -0700401 } else if (resource.type == MediaResource::Type::kBattery
402 && resource.subType == MediaResource::SubType::kVideoCodec) {
Chong Zhangdd726802019-08-21 17:24:13 -0700403 mSystemCB->noteStartVideo(clientInfo.uid);
Chong Zhangfb092d32019-08-12 09:45:44 -0700404 }
405}
406
Brian Lindahl64ee9452022-01-14 13:31:16 +0100407void ResourceManagerService::onLastRemoved(const MediaResourceParcel& resource,
408 const ResourceInfo& clientInfo) {
Chong Zhang181e6952019-10-09 13:23:39 -0700409 if (resource.type == MediaResource::Type::kCpuBoost
410 && resource.subType == MediaResource::SubType::kUnspecifiedSubType
Chong Zhangfb092d32019-08-12 09:45:44 -0700411 && mCpuBoostCount > 0) {
412 if (--mCpuBoostCount == 0) {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800413 mSystemCB->requestCpusetBoost(false);
Chong Zhangfb092d32019-08-12 09:45:44 -0700414 }
Chong Zhang181e6952019-10-09 13:23:39 -0700415 } else if (resource.type == MediaResource::Type::kBattery
416 && resource.subType == MediaResource::SubType::kVideoCodec) {
Chong Zhangdd726802019-08-21 17:24:13 -0700417 mSystemCB->noteStopVideo(clientInfo.uid);
Chong Zhangfb092d32019-08-12 09:45:44 -0700418 }
419}
420
Brian Lindahl64ee9452022-01-14 13:31:16 +0100421void ResourceManagerService::mergeResources(MediaResourceParcel& r1,
422 const MediaResourceParcel& r2) {
Chong Zhang181e6952019-10-09 13:23:39 -0700423 // The resource entry on record is maintained to be in [0,INT64_MAX].
424 // Clamp if merging in the new resource value causes it to go out of bound.
425 // Note that the new resource value could be negative, eg.DrmSession, the
426 // value goes lower when the session is used more often. During reclaim
427 // the session with the highest value (lowest usage) would be closed.
428 if (r2.value < INT64_MAX - r1.value) {
429 r1.value += r2.value;
430 if (r1.value < 0) {
431 r1.value = 0;
432 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700433 } else {
Chong Zhang181e6952019-10-09 13:23:39 -0700434 r1.value = INT64_MAX;
Robert Shihc3af31b2019-09-20 21:45:01 -0700435 }
436}
437
Brian Lindahl64ee9452022-01-14 13:31:16 +0100438Status ResourceManagerService::addResource(int32_t pid, int32_t uid, int64_t clientId,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800439 const std::shared_ptr<IResourceManagerClient>& client,
Chong Zhang181e6952019-10-09 13:23:39 -0700440 const std::vector<MediaResourceParcel>& resources) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700441 String8 log = String8::format("addResource(pid %d, clientId %lld, resources %s)",
Ronghua Wu231c3d12015-03-11 15:10:32 -0700442 pid, (long long) clientId, getString(resources).string());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700443 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700444
445 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100446 if (!mProcessInfo->isPidUidTrusted(pid, uid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800447 pid_t callingPid = IPCThreadState::self()->getCallingPid();
448 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100449 ALOGW("%s called with untrusted pid %d or uid %d, using calling pid %d, uid %d",
450 __FUNCTION__, pid, uid, callingPid, callingUid);
Chong Zhangc7303e82020-12-02 16:38:52 -0800451 pid = callingPid;
452 uid = callingUid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800453 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700454 ResourceInfos& infos = getResourceInfosForEdit(pid, mMap);
Chong Zhangee33d642019-08-08 14:26:43 -0700455 ResourceInfo& info = getResourceInfoForEdit(uid, clientId, client, infos);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700456 ResourceList resourceAdded;
Chong Zhang79d2b282018-04-17 14:14:31 -0700457
458 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700459 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700460 const auto resType = std::tuple(res.type, res.subType, res.id);
461
462 if (res.value < 0 && res.type != MediaResource::Type::kDrmSession) {
463 ALOGW("Ignoring request to remove negative value of non-drm resource");
464 continue;
465 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700466 if (info.resources.find(resType) == info.resources.end()) {
Chong Zhang181e6952019-10-09 13:23:39 -0700467 if (res.value <= 0) {
468 // We can't init a new entry with negative value, although it's allowed
469 // to merge in negative values after the initial add.
470 ALOGW("Ignoring request to add new resource entry with value <= 0");
471 continue;
472 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700473 onFirstAdded(res, info);
474 info.resources[resType] = res;
Chong Zhangfb092d32019-08-12 09:45:44 -0700475 } else {
Robert Shihc3af31b2019-09-20 21:45:01 -0700476 mergeResources(info.resources[resType], res);
Chong Zhang79d2b282018-04-17 14:14:31 -0700477 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700478 // Add it to the list of added resources for observers.
479 auto it = resourceAdded.find(resType);
480 if (it == resourceAdded.end()) {
481 resourceAdded[resType] = res;
482 } else {
483 mergeResources(it->second, res);
484 }
Chong Zhang79d2b282018-04-17 14:14:31 -0700485 }
Chong Zhang97d367b2020-09-16 12:53:14 -0700486 if (info.cookie == 0 && client != nullptr) {
Arun Johnsond1f59732022-03-25 17:10:29 +0000487 info.cookie = addCookieAndLink_l(client,
Chong Zhang97d367b2020-09-16 12:53:14 -0700488 new DeathNotifier(ref<ResourceManagerService>(), pid, clientId));
Wonsik Kim3e378962017-01-05 17:00:02 +0900489 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700490 if (mObserverService != nullptr && !resourceAdded.empty()) {
491 mObserverService->onResourceAdded(uid, pid, resourceAdded);
492 }
Dongwon Kangfe508d32015-12-15 14:22:05 +0900493 notifyResourceGranted(pid, resources);
Chong Zhang181e6952019-10-09 13:23:39 -0700494 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700495}
496
Brian Lindahl64ee9452022-01-14 13:31:16 +0100497Status ResourceManagerService::removeResource(int32_t pid, int64_t clientId,
Chong Zhang181e6952019-10-09 13:23:39 -0700498 const std::vector<MediaResourceParcel>& resources) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700499 String8 log = String8::format("removeResource(pid %d, clientId %lld, resources %s)",
500 pid, (long long) clientId, getString(resources).string());
501 mServiceLog->add(log);
502
503 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100504 if (!mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800505 pid_t callingPid = IPCThreadState::self()->getCallingPid();
506 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
507 pid, callingPid);
508 pid = callingPid;
Chong Zhangfb092d32019-08-12 09:45:44 -0700509 }
510 ssize_t index = mMap.indexOfKey(pid);
511 if (index < 0) {
512 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700513 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700514 }
515 ResourceInfos &infos = mMap.editValueAt(index);
516
517 index = infos.indexOfKey(clientId);
518 if (index < 0) {
519 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700520 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700521 }
522
523 ResourceInfo &info = infos.editValueAt(index);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700524 ResourceList resourceRemoved;
Chong Zhangfb092d32019-08-12 09:45:44 -0700525 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700526 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700527 const auto resType = std::tuple(res.type, res.subType, res.id);
528
529 if (res.value < 0) {
530 ALOGW("Ignoring request to remove negative value of resource");
531 continue;
532 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700533 // ignore if we don't have it
534 if (info.resources.find(resType) != info.resources.end()) {
Chong Zhang181e6952019-10-09 13:23:39 -0700535 MediaResourceParcel &resource = info.resources[resType];
Chong Zhanga9d45c72020-09-09 12:41:17 -0700536 MediaResourceParcel actualRemoved = res;
Chong Zhang181e6952019-10-09 13:23:39 -0700537 if (resource.value > res.value) {
538 resource.value -= res.value;
Chong Zhangfb092d32019-08-12 09:45:44 -0700539 } else {
Robert Shihc3af31b2019-09-20 21:45:01 -0700540 onLastRemoved(res, info);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700541 actualRemoved.value = resource.value;
Chong Zhang102b3e32020-11-02 12:21:50 -0800542 info.resources.erase(resType);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700543 }
544
545 // Add it to the list of removed resources for observers.
546 auto it = resourceRemoved.find(resType);
547 if (it == resourceRemoved.end()) {
548 resourceRemoved[resType] = actualRemoved;
549 } else {
550 mergeResources(it->second, actualRemoved);
Chong Zhangfb092d32019-08-12 09:45:44 -0700551 }
552 }
553 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700554 if (mObserverService != nullptr && !resourceRemoved.empty()) {
555 mObserverService->onResourceRemoved(info.uid, pid, resourceRemoved);
556 }
Chong Zhang181e6952019-10-09 13:23:39 -0700557 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700558}
559
Chong Zhang181e6952019-10-09 13:23:39 -0700560Status ResourceManagerService::removeClient(int32_t pid, int64_t clientId) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800561 removeResource(pid, clientId, true /*checkValid*/);
Chong Zhang181e6952019-10-09 13:23:39 -0700562 return Status::ok();
Wonsik Kim3e378962017-01-05 17:00:02 +0900563}
564
Chong Zhang181e6952019-10-09 13:23:39 -0700565Status ResourceManagerService::removeResource(int pid, int64_t clientId, bool checkValid) {
Ronghua Wu37c89242015-07-15 12:23:48 -0700566 String8 log = String8::format(
567 "removeResource(pid %d, clientId %lld)",
568 pid, (long long) clientId);
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700569 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700570
571 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100572 if (checkValid && !mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800573 pid_t callingPid = IPCThreadState::self()->getCallingPid();
574 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
575 pid, callingPid);
576 pid = callingPid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800577 }
Ronghua Wu37c89242015-07-15 12:23:48 -0700578 ssize_t index = mMap.indexOfKey(pid);
579 if (index < 0) {
580 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700581 return Status::ok();
Ronghua Wu37c89242015-07-15 12:23:48 -0700582 }
Ronghua Wu37c89242015-07-15 12:23:48 -0700583 ResourceInfos &infos = mMap.editValueAt(index);
Chong Zhangfb092d32019-08-12 09:45:44 -0700584
585 index = infos.indexOfKey(clientId);
586 if (index < 0) {
587 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700588 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700589 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700590
591 const ResourceInfo &info = infos[index];
592 for (auto it = info.resources.begin(); it != info.resources.end(); it++) {
593 onLastRemoved(it->second, info);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700594 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700595
Arun Johnsond1f59732022-03-25 17:10:29 +0000596 removeCookieAndUnlink_l(info.client, info.cookie);
Chong Zhangfb092d32019-08-12 09:45:44 -0700597
Chong Zhanga9d45c72020-09-09 12:41:17 -0700598 if (mObserverService != nullptr && !info.resources.empty()) {
599 mObserverService->onResourceRemoved(info.uid, pid, info.resources);
600 }
601
Chong Zhangfb092d32019-08-12 09:45:44 -0700602 infos.removeItemsAt(index);
Chong Zhang181e6952019-10-09 13:23:39 -0700603 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700604}
605
Brian Lindahl64ee9452022-01-14 13:31:16 +0100606void ResourceManagerService::getClientForResource_l(int callingPid, const MediaResourceParcel *res,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800607 Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700608 if (res == NULL) {
609 return;
610 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800611 std::shared_ptr<IResourceManagerClient> client;
Brian Lindahl64ee9452022-01-14 13:31:16 +0100612 if (getLowestPriorityBiggestClient_l(callingPid, res->type, res->subType, &client)) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700613 clients->push_back(client);
614 }
615}
616
Brian Lindahl64ee9452022-01-14 13:31:16 +0100617Status ResourceManagerService::reclaimResource(int32_t callingPid,
618 const std::vector<MediaResourceParcel>& resources, bool* _aidl_return) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700619 String8 log = String8::format("reclaimResource(callingPid %d, resources %s)",
Ronghua Wu231c3d12015-03-11 15:10:32 -0700620 callingPid, getString(resources).string());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700621 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700622 *_aidl_return = false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700623
Chong Zhangfdd512a2019-11-22 11:03:14 -0800624 Vector<std::shared_ptr<IResourceManagerClient>> clients;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700625 {
626 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100627 if (!mProcessInfo->isPidTrusted(callingPid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800628 pid_t actualCallingPid = IPCThreadState::self()->getCallingPid();
629 ALOGW("%s called with untrusted pid %d, using actual calling pid %d", __FUNCTION__,
630 callingPid, actualCallingPid);
631 callingPid = actualCallingPid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800632 }
Chong Zhang181e6952019-10-09 13:23:39 -0700633 const MediaResourceParcel *secureCodec = NULL;
634 const MediaResourceParcel *nonSecureCodec = NULL;
635 const MediaResourceParcel *graphicMemory = NULL;
636 const MediaResourceParcel *drmSession = NULL;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700637 for (size_t i = 0; i < resources.size(); ++i) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100638 switch (resources[i].type) {
639 case MediaResource::Type::kSecureCodec:
640 secureCodec = &resources[i];
641 break;
642 case MediaResource::Type::kNonSecureCodec:
643 nonSecureCodec = &resources[i];
644 break;
645 case MediaResource::Type::kGraphicMemory:
646 graphicMemory = &resources[i];
647 break;
648 case MediaResource::Type::kDrmSession:
649 drmSession = &resources[i];
650 break;
651 default:
652 break;
Ronghua Wu05d89f12015-07-07 16:47:42 -0700653 }
654 }
655
656 // first pass to handle secure/non-secure codec conflict
657 if (secureCodec != NULL) {
658 if (!mSupportsMultipleSecureCodecs) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100659 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec,
660 secureCodec->subType, &clients)) {
Chong Zhang181e6952019-10-09 13:23:39 -0700661 return Status::ok();
Ronghua Wu05d89f12015-07-07 16:47:42 -0700662 }
663 }
664 if (!mSupportsSecureWithNonSecureCodec) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100665 if (!getAllClients_l(callingPid, MediaResource::Type::kNonSecureCodec,
666 secureCodec->subType, &clients)) {
Chong Zhang181e6952019-10-09 13:23:39 -0700667 return Status::ok();
Ronghua Wu05d89f12015-07-07 16:47:42 -0700668 }
669 }
670 }
671 if (nonSecureCodec != NULL) {
672 if (!mSupportsSecureWithNonSecureCodec) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100673 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec,
674 nonSecureCodec->subType, &clients)) {
Chong Zhang181e6952019-10-09 13:23:39 -0700675 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700676 }
677 }
678 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700679 if (drmSession != NULL) {
680 getClientForResource_l(callingPid, drmSession, &clients);
681 if (clients.size() == 0) {
Chong Zhang181e6952019-10-09 13:23:39 -0700682 return Status::ok();
Robert Shihc3af31b2019-09-20 21:45:01 -0700683 }
684 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700685
686 if (clients.size() == 0) {
687 // if no secure/non-secure codec conflict, run second pass to handle other resources.
Ronghua Wu05d89f12015-07-07 16:47:42 -0700688 getClientForResource_l(callingPid, graphicMemory, &clients);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700689 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700690
691 if (clients.size() == 0) {
692 // if we are here, run the third pass to free one codec with the same type.
Ronghua Wu05d89f12015-07-07 16:47:42 -0700693 getClientForResource_l(callingPid, secureCodec, &clients);
694 getClientForResource_l(callingPid, nonSecureCodec, &clients);
695 }
696
697 if (clients.size() == 0) {
698 // if we are here, run the fourth pass to free one codec with the different type.
699 if (secureCodec != NULL) {
Wonsik Kimb3639012022-03-16 13:57:41 -0700700 MediaResource temp(MediaResource::Type::kNonSecureCodec, secureCodec->subType, 1);
Ronghua Wu05d89f12015-07-07 16:47:42 -0700701 getClientForResource_l(callingPid, &temp, &clients);
702 }
703 if (nonSecureCodec != NULL) {
Wonsik Kimb3639012022-03-16 13:57:41 -0700704 MediaResource temp(MediaResource::Type::kSecureCodec, nonSecureCodec->subType, 1);
Ronghua Wu05d89f12015-07-07 16:47:42 -0700705 getClientForResource_l(callingPid, &temp, &clients);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700706 }
707 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700708 }
709
Brian Lindahl64ee9452022-01-14 13:31:16 +0100710 *_aidl_return = reclaimUnconditionallyFrom(clients);
Wonsik Kim271429d2020-10-01 10:12:56 -0700711 return Status::ok();
712}
713
Brian Lindahl64ee9452022-01-14 13:31:16 +0100714bool ResourceManagerService::reclaimUnconditionallyFrom(
Wonsik Kim271429d2020-10-01 10:12:56 -0700715 const Vector<std::shared_ptr<IResourceManagerClient>> &clients) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700716 if (clients.size() == 0) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700717 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700718 }
719
Chong Zhangfdd512a2019-11-22 11:03:14 -0800720 std::shared_ptr<IResourceManagerClient> failedClient;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700721 for (size_t i = 0; i < clients.size(); ++i) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700722 String8 log = String8::format("reclaimResource from client %p", clients[i].get());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700723 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700724 bool success;
725 Status status = clients[i]->reclaimResource(&success);
726 if (!status.isOk() || !success) {
Ronghua Wu67e7f542015-03-13 10:47:08 -0700727 failedClient = clients[i];
728 break;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700729 }
730 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700731
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700732 if (failedClient == NULL) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700733 return true;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700734 }
735
Brian Lindahl9f626cf2022-04-25 13:29:59 +0200736 int failedClientPid = -1;
Ronghua Wu67e7f542015-03-13 10:47:08 -0700737 {
738 Mutex::Autolock lock(mLock);
739 bool found = false;
740 for (size_t i = 0; i < mMap.size(); ++i) {
741 ResourceInfos &infos = mMap.editValueAt(i);
742 for (size_t j = 0; j < infos.size();) {
743 if (infos[j].client == failedClient) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700744 j = infos.removeItemsAt(j);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700745 found = true;
746 } else {
747 ++j;
748 }
749 }
750 if (found) {
Brian Lindahl9f626cf2022-04-25 13:29:59 +0200751 failedClientPid = mMap.keyAt(i);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700752 break;
753 }
754 }
Brian Lindahl9f626cf2022-04-25 13:29:59 +0200755 if (found) {
756 ALOGW("Failed to reclaim resources from client with pid %d", failedClientPid);
757 } else {
758 ALOGW("Failed to reclaim resources from unlocateable client");
Ronghua Wu67e7f542015-03-13 10:47:08 -0700759 }
760 }
761
Wonsik Kim271429d2020-10-01 10:12:56 -0700762 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700763}
764
Brian Lindahl64ee9452022-01-14 13:31:16 +0100765Status ResourceManagerService::overridePid(int originalPid, int newPid) {
Henry Fang32762922020-01-28 18:40:39 -0800766 String8 log = String8::format("overridePid(originalPid %d, newPid %d)",
767 originalPid, newPid);
768 mServiceLog->add(log);
769
770 // allow if this is called from the same process or the process has
771 // permission.
772 if ((AIBinder_getCallingPid() != getpid()) &&
773 (checkCallingPermission(String16(
774 "android.permission.MEDIA_RESOURCE_OVERRIDE_PID")) == false)) {
775 ALOGE(
776 "Permission Denial: can't access overridePid method from pid=%d, "
777 "self pid=%d\n",
778 AIBinder_getCallingPid(), getpid());
779 return Status::fromServiceSpecificError(PERMISSION_DENIED);
780 }
781
782 {
783 Mutex::Autolock lock(mLock);
784 mOverridePidMap.erase(originalPid);
785 if (newPid != -1) {
786 mOverridePidMap.emplace(originalPid, newPid);
787 }
788 }
789
790 return Status::ok();
791}
792
Chong Zhang97d367b2020-09-16 12:53:14 -0700793Status ResourceManagerService::overrideProcessInfo(
Brian Lindahl64ee9452022-01-14 13:31:16 +0100794 const std::shared_ptr<IResourceManagerClient>& client, int pid, int procState,
Chong Zhang97d367b2020-09-16 12:53:14 -0700795 int oomScore) {
796 String8 log = String8::format("overrideProcessInfo(pid %d, procState %d, oomScore %d)",
797 pid, procState, oomScore);
798 mServiceLog->add(log);
799
800 // Only allow the override if the caller already can access process state and oom scores.
801 int callingPid = AIBinder_getCallingPid();
802 if (callingPid != getpid() && (callingPid != pid || !checkCallingPermission(String16(
803 "android.permission.GET_PROCESS_STATE_AND_OOM_SCORE")))) {
804 ALOGE("Permission Denial: overrideProcessInfo method from pid=%d", callingPid);
805 return Status::fromServiceSpecificError(PERMISSION_DENIED);
806 }
807
808 if (client == nullptr) {
809 return Status::fromServiceSpecificError(BAD_VALUE);
810 }
811
812 Mutex::Autolock lock(mLock);
813 removeProcessInfoOverride_l(pid);
814
815 if (!mProcessInfo->overrideProcessInfo(pid, procState, oomScore)) {
816 // Override value is rejected by ProcessInfo.
817 return Status::fromServiceSpecificError(BAD_VALUE);
818 }
819
Arun Johnsond1f59732022-03-25 17:10:29 +0000820 uintptr_t cookie = addCookieAndLink_l(client,
Chong Zhang97d367b2020-09-16 12:53:14 -0700821 new OverrideProcessInfoDeathNotifier(ref<ResourceManagerService>(), pid));
822
823 mProcessInfoOverrideMap.emplace(pid, ProcessInfoOverride{cookie, client});
824
825 return Status::ok();
826}
827
Arun Johnsond1f59732022-03-25 17:10:29 +0000828uintptr_t ResourceManagerService::addCookieAndLink_l(
829 const std::shared_ptr<IResourceManagerClient>& client, const sp<DeathNotifier>& notifier) {
830 if (client == nullptr) {
831 return 0;
832 }
Chong Zhang97d367b2020-09-16 12:53:14 -0700833 std::scoped_lock lock{sCookieLock};
834
835 uintptr_t cookie;
836 // Need to skip cookie 0 (if it wraps around). ResourceInfo has cookie initialized to 0
837 // indicating the death notifier is not created yet.
838 while ((cookie = ++sCookieCounter) == 0);
Arun Johnsond1f59732022-03-25 17:10:29 +0000839 AIBinder_linkToDeath(client->asBinder().get(), mDeathRecipient.get(), (void*)cookie);
Chong Zhang97d367b2020-09-16 12:53:14 -0700840 sCookieToDeathNotifierMap.emplace(cookie, notifier);
841
842 return cookie;
843}
844
Arun Johnsond1f59732022-03-25 17:10:29 +0000845void ResourceManagerService::removeCookieAndUnlink_l(
846 const std::shared_ptr<IResourceManagerClient>& client, uintptr_t cookie) {
Chong Zhang97d367b2020-09-16 12:53:14 -0700847 std::scoped_lock lock{sCookieLock};
Arun Johnsond1f59732022-03-25 17:10:29 +0000848 if (client != nullptr) {
849 AIBinder_unlinkToDeath(client->asBinder().get(), mDeathRecipient.get(), (void*)cookie);
850 }
Chong Zhang97d367b2020-09-16 12:53:14 -0700851 sCookieToDeathNotifierMap.erase(cookie);
852}
853
854void ResourceManagerService::removeProcessInfoOverride(int pid) {
855 Mutex::Autolock lock(mLock);
856
857 removeProcessInfoOverride_l(pid);
858}
859
860void ResourceManagerService::removeProcessInfoOverride_l(int pid) {
861 auto it = mProcessInfoOverrideMap.find(pid);
862 if (it == mProcessInfoOverrideMap.end()) {
863 return;
864 }
865
866 mProcessInfo->removeProcessInfoOverride(pid);
867
Arun Johnsond1f59732022-03-25 17:10:29 +0000868 removeCookieAndUnlink_l(it->second.client, it->second.cookie);
Chong Zhang97d367b2020-09-16 12:53:14 -0700869
870 mProcessInfoOverrideMap.erase(pid);
871}
872
Wonsik Kimd20e9362020-04-28 10:42:57 -0700873Status ResourceManagerService::markClientForPendingRemoval(int32_t pid, int64_t clientId) {
874 String8 log = String8::format(
875 "markClientForPendingRemoval(pid %d, clientId %lld)",
876 pid, (long long) clientId);
877 mServiceLog->add(log);
878
879 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100880 if (!mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800881 pid_t callingPid = IPCThreadState::self()->getCallingPid();
882 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
883 pid, callingPid);
884 pid = callingPid;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700885 }
886 ssize_t index = mMap.indexOfKey(pid);
887 if (index < 0) {
888 ALOGV("markClientForPendingRemoval: didn't find pid %d for clientId %lld",
889 pid, (long long)clientId);
890 return Status::ok();
891 }
892 ResourceInfos &infos = mMap.editValueAt(index);
893
894 index = infos.indexOfKey(clientId);
895 if (index < 0) {
896 ALOGV("markClientForPendingRemoval: didn't find clientId %lld", (long long) clientId);
897 return Status::ok();
898 }
899
900 ResourceInfo &info = infos.editValueAt(index);
901 info.pendingRemoval = true;
902 return Status::ok();
903}
904
Wonsik Kim271429d2020-10-01 10:12:56 -0700905Status ResourceManagerService::reclaimResourcesFromClientsPendingRemoval(int32_t pid) {
906 String8 log = String8::format("reclaimResourcesFromClientsPendingRemoval(pid %d)", pid);
907 mServiceLog->add(log);
908
909 Vector<std::shared_ptr<IResourceManagerClient>> clients;
910 {
911 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100912 if (!mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800913 pid_t callingPid = IPCThreadState::self()->getCallingPid();
914 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
915 pid, callingPid);
916 pid = callingPid;
Wonsik Kim271429d2020-10-01 10:12:56 -0700917 }
918
919 for (MediaResource::Type type : {MediaResource::Type::kSecureCodec,
920 MediaResource::Type::kNonSecureCodec,
921 MediaResource::Type::kGraphicMemory,
922 MediaResource::Type::kDrmSession}) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100923 switch (type) {
924 // Codec resources are segregated by audio, video and image domains.
925 case MediaResource::Type::kSecureCodec:
926 case MediaResource::Type::kNonSecureCodec:
927 for (MediaResource::SubType subType : {MediaResource::SubType::kAudioCodec,
928 MediaResource::SubType::kVideoCodec,
929 MediaResource::SubType::kImageCodec}) {
930 std::shared_ptr<IResourceManagerClient> client;
931 if (getBiggestClientPendingRemoval_l(pid, type, subType, &client)) {
932 clients.add(client);
933 continue;
934 }
935 }
936 break;
937 // Non-codec resources are shared by audio, video and image codecs (no subtype).
938 default:
939 std::shared_ptr<IResourceManagerClient> client;
940 if (getBiggestClientPendingRemoval_l(pid, type,
941 MediaResource::SubType::kUnspecifiedSubType, &client)) {
942 clients.add(client);
943 }
944 break;
Wonsik Kim271429d2020-10-01 10:12:56 -0700945 }
946 }
947 }
948
949 if (!clients.empty()) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100950 reclaimUnconditionallyFrom(clients);
Wonsik Kim271429d2020-10-01 10:12:56 -0700951 }
952 return Status::ok();
953}
954
Henry Fang32762922020-01-28 18:40:39 -0800955bool ResourceManagerService::getPriority_l(int pid, int* priority) {
956 int newPid = pid;
957
958 if (mOverridePidMap.find(pid) != mOverridePidMap.end()) {
959 newPid = mOverridePidMap[pid];
960 ALOGD("getPriority_l: use override pid %d instead original pid %d",
961 newPid, pid);
962 }
963
964 return mProcessInfo->getPriority(newPid, priority);
965}
966
Brian Lindahl64ee9452022-01-14 13:31:16 +0100967bool ResourceManagerService::getAllClients_l(int callingPid, MediaResource::Type type,
968 MediaResource::SubType subType, Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800969 Vector<std::shared_ptr<IResourceManagerClient>> temp;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700970 for (size_t i = 0; i < mMap.size(); ++i) {
971 ResourceInfos &infos = mMap.editValueAt(i);
972 for (size_t j = 0; j < infos.size(); ++j) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100973 if (hasResourceType(type, subType, infos[j].resources)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700974 if (!isCallingPriorityHigher_l(callingPid, mMap.keyAt(i))) {
975 // some higher/equal priority process owns the resource,
976 // this request can't be fulfilled.
977 ALOGE("getAllClients_l: can't reclaim resource %s from pid %d",
Ronghua Wuea15fd22016-03-03 13:35:05 -0800978 asString(type), mMap.keyAt(i));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700979 return false;
980 }
981 temp.push_back(infos[j].client);
982 }
983 }
984 }
985 if (temp.size() == 0) {
Ronghua Wuea15fd22016-03-03 13:35:05 -0800986 ALOGV("getAllClients_l: didn't find any resource %s", asString(type));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700987 return true;
988 }
989 clients->appendVector(temp);
990 return true;
991}
992
Brian Lindahl64ee9452022-01-14 13:31:16 +0100993bool ResourceManagerService::getLowestPriorityBiggestClient_l(int callingPid,
994 MediaResource::Type type, MediaResource::SubType subType,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800995 std::shared_ptr<IResourceManagerClient> *client) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700996 int lowestPriorityPid;
997 int lowestPriority;
998 int callingPriority;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700999
1000 // Before looking into other processes, check if we have clients marked for
1001 // pending removal in the same process.
Brian Lindahl64ee9452022-01-14 13:31:16 +01001002 if (getBiggestClientPendingRemoval_l(callingPid, type, subType, client)) {
Wonsik Kimd20e9362020-04-28 10:42:57 -07001003 return true;
1004 }
Henry Fang32762922020-01-28 18:40:39 -08001005 if (!getPriority_l(callingPid, &callingPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001006 ALOGE("getLowestPriorityBiggestClient_l: can't get process priority for pid %d",
1007 callingPid);
1008 return false;
1009 }
Brian Lindahl64ee9452022-01-14 13:31:16 +01001010 if (!getLowestPriorityPid_l(type, subType, &lowestPriorityPid, &lowestPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001011 return false;
1012 }
1013 if (lowestPriority <= callingPriority) {
1014 ALOGE("getLowestPriorityBiggestClient_l: lowest priority %d vs caller priority %d",
1015 lowestPriority, callingPriority);
1016 return false;
1017 }
1018
Brian Lindahl64ee9452022-01-14 13:31:16 +01001019 if (!getBiggestClient_l(lowestPriorityPid, type, subType, client)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001020 return false;
1021 }
1022 return true;
1023}
1024
Brian Lindahl64ee9452022-01-14 13:31:16 +01001025bool ResourceManagerService::getLowestPriorityPid_l(MediaResource::Type type,
1026 MediaResource::SubType subType, int *lowestPriorityPid, int *lowestPriority) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001027 int pid = -1;
1028 int priority = -1;
1029 for (size_t i = 0; i < mMap.size(); ++i) {
1030 if (mMap.valueAt(i).size() == 0) {
1031 // no client on this process.
1032 continue;
1033 }
Brian Lindahl64ee9452022-01-14 13:31:16 +01001034 if (!hasResourceType(type, subType, mMap.valueAt(i))) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001035 // doesn't have the requested resource type
1036 continue;
1037 }
1038 int tempPid = mMap.keyAt(i);
1039 int tempPriority;
Henry Fang32762922020-01-28 18:40:39 -08001040 if (!getPriority_l(tempPid, &tempPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001041 ALOGV("getLowestPriorityPid_l: can't get priority of pid %d, skipped", tempPid);
1042 // TODO: remove this pid from mMap?
1043 continue;
1044 }
1045 if (pid == -1 || tempPriority > priority) {
1046 // initial the value
1047 pid = tempPid;
1048 priority = tempPriority;
1049 }
1050 }
1051 if (pid != -1) {
1052 *lowestPriorityPid = pid;
1053 *lowestPriority = priority;
1054 }
1055 return (pid != -1);
1056}
1057
1058bool ResourceManagerService::isCallingPriorityHigher_l(int callingPid, int pid) {
1059 int callingPidPriority;
Henry Fang32762922020-01-28 18:40:39 -08001060 if (!getPriority_l(callingPid, &callingPidPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001061 return false;
1062 }
1063
1064 int priority;
Henry Fang32762922020-01-28 18:40:39 -08001065 if (!getPriority_l(pid, &priority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001066 return false;
1067 }
1068
1069 return (callingPidPriority < priority);
1070}
1071
Brian Lindahl64ee9452022-01-14 13:31:16 +01001072bool ResourceManagerService::getBiggestClientPendingRemoval_l(int pid, MediaResource::Type type,
1073 MediaResource::SubType subType, std::shared_ptr<IResourceManagerClient> *client) {
1074 return getBiggestClient_l(pid, type, subType, client, true /* pendingRemovalOnly */);
1075}
1076
1077bool ResourceManagerService::getBiggestClient_l(int pid, MediaResource::Type type,
1078 MediaResource::SubType subType, std::shared_ptr<IResourceManagerClient> *client,
Wonsik Kimd20e9362020-04-28 10:42:57 -07001079 bool pendingRemovalOnly) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001080 ssize_t index = mMap.indexOfKey(pid);
1081 if (index < 0) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001082 ALOGE_IF(!pendingRemovalOnly,
1083 "getBiggestClient_l: can't find resource info for pid %d", pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001084 return false;
1085 }
1086
Chong Zhangfdd512a2019-11-22 11:03:14 -08001087 std::shared_ptr<IResourceManagerClient> clientTemp;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001088 uint64_t largestValue = 0;
1089 const ResourceInfos &infos = mMap.valueAt(index);
1090 for (size_t i = 0; i < infos.size(); ++i) {
Chong Zhangfb092d32019-08-12 09:45:44 -07001091 const ResourceList &resources = infos[i].resources;
Wonsik Kimd20e9362020-04-28 10:42:57 -07001092 if (pendingRemovalOnly && !infos[i].pendingRemoval) {
1093 continue;
1094 }
Chong Zhangfb092d32019-08-12 09:45:44 -07001095 for (auto it = resources.begin(); it != resources.end(); it++) {
Chong Zhang181e6952019-10-09 13:23:39 -07001096 const MediaResourceParcel &resource = it->second;
Brian Lindahl64ee9452022-01-14 13:31:16 +01001097 if (hasResourceType(type, subType, resource)) {
Chong Zhang181e6952019-10-09 13:23:39 -07001098 if (resource.value > largestValue) {
1099 largestValue = resource.value;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001100 clientTemp = infos[i].client;
1101 }
1102 }
1103 }
1104 }
1105
1106 if (clientTemp == NULL) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001107 ALOGE_IF(!pendingRemovalOnly,
Brian Lindahl64ee9452022-01-14 13:31:16 +01001108 "getBiggestClient_l: can't find resource type %s and subtype %s for pid %d",
1109 asString(type), asString(subType), pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001110 return false;
1111 }
1112
1113 *client = clientTemp;
1114 return true;
1115}
1116
Ronghua Wu231c3d12015-03-11 15:10:32 -07001117} // namespace android