blob: d50f8d5dbccad2da31cd0fd00e0ba2b652d38aaf [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>
Ronghua Wu231c3d12015-03-11 15:10:32 -070029#include <media/stagefright/ProcessInfo.h>
Chong Zhangee33d642019-08-08 14:26:43 -070030#include <mediautils/BatteryNotifier.h>
31#include <mediautils/SchedulingPolicyService.h>
Ronghua Wu231c3d12015-03-11 15:10:32 -070032#include <string.h>
33#include <sys/types.h>
34#include <sys/stat.h>
35#include <sys/time.h>
36#include <unistd.h>
37
Steven Moreland0a0ff0b2021-04-02 00:06:01 +000038#include "IMediaResourceMonitor.h"
Ronghua Wu231c3d12015-03-11 15:10:32 -070039#include "ResourceManagerService.h"
Chong Zhanga9d45c72020-09-09 12:41:17 -070040#include "ResourceObserverService.h"
Ronghua Wua8ec8fc2015-05-07 13:58:22 -070041#include "ServiceLog.h"
Chong Zhangee33d642019-08-08 14:26:43 -070042
Ronghua Wu231c3d12015-03-11 15:10:32 -070043namespace android {
44
Chong Zhang97d367b2020-09-16 12:53:14 -070045//static
46std::mutex ResourceManagerService::sCookieLock;
47//static
48uintptr_t ResourceManagerService::sCookieCounter = 0;
49//static
50std::map<uintptr_t, sp<DeathNotifier> > ResourceManagerService::sCookieToDeathNotifierMap;
51
52class DeathNotifier : public RefBase {
53public:
Brian Lindahl64ee9452022-01-14 13:31:16 +010054 DeathNotifier(const std::shared_ptr<ResourceManagerService> &service, int pid,
55 int64_t clientId);
Chong Zhang97d367b2020-09-16 12:53:14 -070056
57 virtual ~DeathNotifier() {}
58
59 // Implement death recipient
60 static void BinderDiedCallback(void* cookie);
61 virtual void binderDied();
62
63protected:
64 std::weak_ptr<ResourceManagerService> mService;
65 int mPid;
66 int64_t mClientId;
67};
68
Chong Zhangfdd512a2019-11-22 11:03:14 -080069DeathNotifier::DeathNotifier(const std::shared_ptr<ResourceManagerService> &service,
70 int pid, int64_t clientId)
71 : mService(service), mPid(pid), mClientId(clientId) {}
Wonsik Kim3e378962017-01-05 17:00:02 +090072
Chong Zhangfdd512a2019-11-22 11:03:14 -080073//static
74void DeathNotifier::BinderDiedCallback(void* cookie) {
Chong Zhang97d367b2020-09-16 12:53:14 -070075 sp<DeathNotifier> notifier;
76 {
77 std::scoped_lock lock{ResourceManagerService::sCookieLock};
78 auto it = ResourceManagerService::sCookieToDeathNotifierMap.find(
79 reinterpret_cast<uintptr_t>(cookie));
80 if (it == ResourceManagerService::sCookieToDeathNotifierMap.end()) {
81 return;
82 }
83 notifier = it->second;
84 }
85 if (notifier.get() != nullptr) {
86 notifier->binderDied();
87 }
Chong Zhangfdd512a2019-11-22 11:03:14 -080088}
Wonsik Kim3e378962017-01-05 17:00:02 +090089
Chong Zhangfdd512a2019-11-22 11:03:14 -080090void DeathNotifier::binderDied() {
91 // Don't check for pid validity since we know it's already dead.
92 std::shared_ptr<ResourceManagerService> service = mService.lock();
93 if (service == nullptr) {
94 ALOGW("ResourceManagerService is dead as well.");
95 return;
Wonsik Kim3e378962017-01-05 17:00:02 +090096 }
Henry Fang32762922020-01-28 18:40:39 -080097
98 service->overridePid(mPid, -1);
Henry Fangb35141c2020-06-29 13:11:39 -070099 // thiz is freed in the call below, so it must be last call referring thiz
Chong Zhangc7303e82020-12-02 16:38:52 -0800100 service->removeResource(mPid, mClientId, false /*checkValid*/);
Chong Zhang97d367b2020-09-16 12:53:14 -0700101}
Henry Fangb35141c2020-06-29 13:11:39 -0700102
Chong Zhang97d367b2020-09-16 12:53:14 -0700103class OverrideProcessInfoDeathNotifier : public DeathNotifier {
104public:
105 OverrideProcessInfoDeathNotifier(const std::shared_ptr<ResourceManagerService> &service,
106 int pid) : DeathNotifier(service, pid, 0) {}
107
108 virtual ~OverrideProcessInfoDeathNotifier() {}
109
110 virtual void binderDied();
111};
112
113void OverrideProcessInfoDeathNotifier::binderDied() {
114 // Don't check for pid validity since we know it's already dead.
115 std::shared_ptr<ResourceManagerService> service = mService.lock();
116 if (service == nullptr) {
117 ALOGW("ResourceManagerService is dead as well.");
118 return;
119 }
120
121 service->removeProcessInfoOverride(mPid);
Chong Zhangfdd512a2019-11-22 11:03:14 -0800122}
Wonsik Kim3e378962017-01-05 17:00:02 +0900123
Ronghua Wu231c3d12015-03-11 15:10:32 -0700124template <typename T>
Chong Zhang181e6952019-10-09 13:23:39 -0700125static String8 getString(const std::vector<T> &items) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700126 String8 itemsStr;
127 for (size_t i = 0; i < items.size(); ++i) {
Chong Zhang181e6952019-10-09 13:23:39 -0700128 itemsStr.appendFormat("%s ", toString(items[i]).string());
Ronghua Wu231c3d12015-03-11 15:10:32 -0700129 }
130 return itemsStr;
131}
132
Brian Lindahl64ee9452022-01-14 13:31:16 +0100133static bool hasResourceType(MediaResource::Type type, MediaResource::SubType subType,
134 MediaResourceParcel resource) {
135 if (type != resource.type) {
136 return false;
137 }
138 switch (type) {
139 // Codec subtypes (e.g. video vs. audio) are each considered separate resources, so
140 // compare the subtypes as well.
141 case MediaResource::Type::kSecureCodec:
142 case MediaResource::Type::kNonSecureCodec:
143 if (resource.subType == subType) {
144 return true;
145 }
146 break;
147 // Non-codec resources are not segregated by the subtype (e.g. video vs. audio).
148 default:
149 return true;
150 }
151 return false;
152}
153
154static bool hasResourceType(MediaResource::Type type, MediaResource::SubType subType,
155 const ResourceList& resources) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700156 for (auto it = resources.begin(); it != resources.end(); it++) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100157 if (hasResourceType(type, subType, it->second)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700158 return true;
159 }
160 }
161 return false;
162}
163
Brian Lindahl64ee9452022-01-14 13:31:16 +0100164static bool hasResourceType(MediaResource::Type type, MediaResource::SubType subType,
165 const ResourceInfos& infos) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700166 for (size_t i = 0; i < infos.size(); ++i) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100167 if (hasResourceType(type, subType, infos[i].resources)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700168 return true;
169 }
170 }
171 return false;
172}
173
Brian Lindahl64ee9452022-01-14 13:31:16 +0100174static ResourceInfos& getResourceInfosForEdit(int pid, PidResourceInfosMap& map) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700175 ssize_t index = map.indexOfKey(pid);
176 if (index < 0) {
177 // new pid
178 ResourceInfos infosForPid;
179 map.add(pid, infosForPid);
180 }
181
182 return map.editValueFor(pid);
183}
184
Brian Lindahl64ee9452022-01-14 13:31:16 +0100185static ResourceInfo& getResourceInfoForEdit(uid_t uid, int64_t clientId,
186 const std::shared_ptr<IResourceManagerClient>& client, ResourceInfos& infos) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700187 ssize_t index = infos.indexOfKey(clientId);
188
189 if (index < 0) {
190 ResourceInfo info;
191 info.uid = uid;
192 info.clientId = clientId;
193 info.client = client;
Chong Zhang97d367b2020-09-16 12:53:14 -0700194 info.cookie = 0;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700195 info.pendingRemoval = false;
Chong Zhangfb092d32019-08-12 09:45:44 -0700196
197 index = infos.add(clientId, info);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700198 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700199
200 return infos.editValueAt(index);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700201}
202
Chong Zhang181e6952019-10-09 13:23:39 -0700203static void notifyResourceGranted(int pid, const std::vector<MediaResourceParcel> &resources) {
Dongwon Kangfe508d32015-12-15 14:22:05 +0900204 static const char* const kServiceName = "media_resource_monitor";
Dongwon Kang2642c842016-03-23 18:07:29 -0700205 sp<IBinder> binder = defaultServiceManager()->checkService(String16(kServiceName));
Dongwon Kangfe508d32015-12-15 14:22:05 +0900206 if (binder != NULL) {
207 sp<IMediaResourceMonitor> service = interface_cast<IMediaResourceMonitor>(binder);
208 for (size_t i = 0; i < resources.size(); ++i) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100209 switch (resources[i].subType) {
210 case MediaResource::SubType::kAudioCodec:
211 service->notifyResourceGranted(pid, IMediaResourceMonitor::TYPE_AUDIO_CODEC);
212 break;
213 case MediaResource::SubType::kVideoCodec:
214 service->notifyResourceGranted(pid, IMediaResourceMonitor::TYPE_VIDEO_CODEC);
215 break;
216 case MediaResource::SubType::kImageCodec:
217 service->notifyResourceGranted(pid, IMediaResourceMonitor::TYPE_IMAGE_CODEC);
218 break;
219 case MediaResource::SubType::kUnspecifiedSubType:
220 break;
Dongwon Kang69c23dd2016-03-22 15:22:45 -0700221 }
Dongwon Kangfe508d32015-12-15 14:22:05 +0900222 }
223 }
224}
225
Brian Lindahl64ee9452022-01-14 13:31:16 +0100226binder_status_t ResourceManagerService::dump(int fd, const char** /*args*/, uint32_t /*numArgs*/) {
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700227 String8 result;
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700228
dcashman014e91e2015-09-11 09:33:01 -0700229 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
230 result.format("Permission Denial: "
231 "can't dump ResourceManagerService from pid=%d, uid=%d\n",
Chong Zhangfdd512a2019-11-22 11:03:14 -0800232 AIBinder_getCallingPid(),
233 AIBinder_getCallingUid());
dcashman014e91e2015-09-11 09:33:01 -0700234 write(fd, result.string(), result.size());
235 return PERMISSION_DENIED;
236 }
237
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700238 PidResourceInfosMap mapCopy;
239 bool supportsMultipleSecureCodecs;
240 bool supportsSecureWithNonSecureCodec;
Henry Fang32762922020-01-28 18:40:39 -0800241 std::map<int, int> overridePidMapCopy;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700242 String8 serviceLog;
243 {
244 Mutex::Autolock lock(mLock);
245 mapCopy = mMap; // Shadow copy, real copy will happen on write.
246 supportsMultipleSecureCodecs = mSupportsMultipleSecureCodecs;
247 supportsSecureWithNonSecureCodec = mSupportsSecureWithNonSecureCodec;
248 serviceLog = mServiceLog->toString(" " /* linePrefix */);
Henry Fang32762922020-01-28 18:40:39 -0800249 overridePidMapCopy = mOverridePidMap;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700250 }
251
252 const size_t SIZE = 256;
253 char buffer[SIZE];
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700254 snprintf(buffer, SIZE, "ResourceManagerService: %p\n", this);
255 result.append(buffer);
256 result.append(" Policies:\n");
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700257 snprintf(buffer, SIZE, " SupportsMultipleSecureCodecs: %d\n", supportsMultipleSecureCodecs);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700258 result.append(buffer);
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700259 snprintf(buffer, SIZE, " SupportsSecureWithNonSecureCodec: %d\n",
260 supportsSecureWithNonSecureCodec);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700261 result.append(buffer);
262
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700263 result.append(" Processes:\n");
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700264 for (size_t i = 0; i < mapCopy.size(); ++i) {
265 snprintf(buffer, SIZE, " Pid: %d\n", mapCopy.keyAt(i));
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700266 result.append(buffer);
267
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700268 const ResourceInfos &infos = mapCopy.valueAt(i);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700269 for (size_t j = 0; j < infos.size(); ++j) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700270 result.append(" Client:\n");
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700271 snprintf(buffer, SIZE, " Id: %lld\n", (long long)infos[j].clientId);
272 result.append(buffer);
273
Chong Zhang181e6952019-10-09 13:23:39 -0700274 std::string clientName;
275 Status status = infos[j].client->getName(&clientName);
276 if (!status.isOk()) {
277 clientName = "<unknown client>";
278 }
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 =
347 AServiceManager_addService(service->asBinder().get(), getServiceName());
348 if (status != STATUS_OK) {
349 return;
350 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700351
352 std::shared_ptr<ResourceObserverService> observerService =
353 ResourceObserverService::instantiate();
354
355 if (observerService != nullptr) {
356 service->setObserverService(observerService);
357 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800358 // TODO: mediaserver main() is already starting the thread pool,
359 // move this to mediaserver main() when other services in mediaserver
360 // are converted to ndk-platform aidl.
361 //ABinderProcess_startThreadPool();
362}
363
Ronghua Wu231c3d12015-03-11 15:10:32 -0700364ResourceManagerService::~ResourceManagerService() {}
365
Chong Zhanga9d45c72020-09-09 12:41:17 -0700366void ResourceManagerService::setObserverService(
367 const std::shared_ptr<ResourceObserverService>& observerService) {
368 mObserverService = observerService;
369}
370
Chong Zhang181e6952019-10-09 13:23:39 -0700371Status ResourceManagerService::config(const std::vector<MediaResourcePolicyParcel>& policies) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700372 String8 log = String8::format("config(%s)", getString(policies).string());
373 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700374
375 Mutex::Autolock lock(mLock);
376 for (size_t i = 0; i < policies.size(); ++i) {
Chong Zhang181e6952019-10-09 13:23:39 -0700377 const std::string &type = policies[i].type;
378 const std::string &value = policies[i].value;
379 if (type == MediaResourcePolicy::kPolicySupportsMultipleSecureCodecs()) {
Ronghua Wu9ba21b92015-04-21 14:23:06 -0700380 mSupportsMultipleSecureCodecs = (value == "true");
Chong Zhang181e6952019-10-09 13:23:39 -0700381 } else if (type == MediaResourcePolicy::kPolicySupportsSecureWithNonSecureCodec()) {
Ronghua Wu9ba21b92015-04-21 14:23:06 -0700382 mSupportsSecureWithNonSecureCodec = (value == "true");
Ronghua Wu231c3d12015-03-11 15:10:32 -0700383 }
384 }
Chong Zhang181e6952019-10-09 13:23:39 -0700385 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700386}
387
Brian Lindahl64ee9452022-01-14 13:31:16 +0100388void ResourceManagerService::onFirstAdded(const MediaResourceParcel& resource,
389 const ResourceInfo& clientInfo) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700390 // first time added
Chong Zhang181e6952019-10-09 13:23:39 -0700391 if (resource.type == MediaResource::Type::kCpuBoost
392 && resource.subType == MediaResource::SubType::kUnspecifiedSubType) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700393 // Request it on every new instance of kCpuBoost, as the media.codec
394 // could have died, if we only do it the first time subsequent instances
395 // never gets the boost.
Chong Zhangfdd512a2019-11-22 11:03:14 -0800396 if (mSystemCB->requestCpusetBoost(true) != OK) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700397 ALOGW("couldn't request cpuset boost");
398 }
399 mCpuBoostCount++;
Chong Zhang181e6952019-10-09 13:23:39 -0700400 } else if (resource.type == MediaResource::Type::kBattery
401 && resource.subType == MediaResource::SubType::kVideoCodec) {
Chong Zhangdd726802019-08-21 17:24:13 -0700402 mSystemCB->noteStartVideo(clientInfo.uid);
Chong Zhangfb092d32019-08-12 09:45:44 -0700403 }
404}
405
Brian Lindahl64ee9452022-01-14 13:31:16 +0100406void ResourceManagerService::onLastRemoved(const MediaResourceParcel& resource,
407 const ResourceInfo& clientInfo) {
Chong Zhang181e6952019-10-09 13:23:39 -0700408 if (resource.type == MediaResource::Type::kCpuBoost
409 && resource.subType == MediaResource::SubType::kUnspecifiedSubType
Chong Zhangfb092d32019-08-12 09:45:44 -0700410 && mCpuBoostCount > 0) {
411 if (--mCpuBoostCount == 0) {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800412 mSystemCB->requestCpusetBoost(false);
Chong Zhangfb092d32019-08-12 09:45:44 -0700413 }
Chong Zhang181e6952019-10-09 13:23:39 -0700414 } else if (resource.type == MediaResource::Type::kBattery
415 && resource.subType == MediaResource::SubType::kVideoCodec) {
Chong Zhangdd726802019-08-21 17:24:13 -0700416 mSystemCB->noteStopVideo(clientInfo.uid);
Chong Zhangfb092d32019-08-12 09:45:44 -0700417 }
418}
419
Brian Lindahl64ee9452022-01-14 13:31:16 +0100420void ResourceManagerService::mergeResources(MediaResourceParcel& r1,
421 const MediaResourceParcel& r2) {
Chong Zhang181e6952019-10-09 13:23:39 -0700422 // The resource entry on record is maintained to be in [0,INT64_MAX].
423 // Clamp if merging in the new resource value causes it to go out of bound.
424 // Note that the new resource value could be negative, eg.DrmSession, the
425 // value goes lower when the session is used more often. During reclaim
426 // the session with the highest value (lowest usage) would be closed.
427 if (r2.value < INT64_MAX - r1.value) {
428 r1.value += r2.value;
429 if (r1.value < 0) {
430 r1.value = 0;
431 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700432 } else {
Chong Zhang181e6952019-10-09 13:23:39 -0700433 r1.value = INT64_MAX;
Robert Shihc3af31b2019-09-20 21:45:01 -0700434 }
435}
436
Brian Lindahl64ee9452022-01-14 13:31:16 +0100437Status ResourceManagerService::addResource(int32_t pid, int32_t uid, int64_t clientId,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800438 const std::shared_ptr<IResourceManagerClient>& client,
Chong Zhang181e6952019-10-09 13:23:39 -0700439 const std::vector<MediaResourceParcel>& resources) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700440 String8 log = String8::format("addResource(pid %d, clientId %lld, resources %s)",
Ronghua Wu231c3d12015-03-11 15:10:32 -0700441 pid, (long long) clientId, getString(resources).string());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700442 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700443
444 Mutex::Autolock lock(mLock);
Ronghua Wud11c43a2016-01-27 16:26:12 -0800445 if (!mProcessInfo->isValidPid(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800446 pid_t callingPid = IPCThreadState::self()->getCallingPid();
447 uid_t callingUid = IPCThreadState::self()->getCallingUid();
448 ALOGW("%s called with untrusted pid %d, using calling pid %d, uid %d", __FUNCTION__,
449 pid, callingPid, callingUid);
450 pid = callingPid;
451 uid = callingUid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800452 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700453 ResourceInfos& infos = getResourceInfosForEdit(pid, mMap);
Chong Zhangee33d642019-08-08 14:26:43 -0700454 ResourceInfo& info = getResourceInfoForEdit(uid, clientId, client, infos);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700455 ResourceList resourceAdded;
Chong Zhang79d2b282018-04-17 14:14:31 -0700456
457 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700458 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700459 const auto resType = std::tuple(res.type, res.subType, res.id);
460
461 if (res.value < 0 && res.type != MediaResource::Type::kDrmSession) {
462 ALOGW("Ignoring request to remove negative value of non-drm resource");
463 continue;
464 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700465 if (info.resources.find(resType) == info.resources.end()) {
Chong Zhang181e6952019-10-09 13:23:39 -0700466 if (res.value <= 0) {
467 // We can't init a new entry with negative value, although it's allowed
468 // to merge in negative values after the initial add.
469 ALOGW("Ignoring request to add new resource entry with value <= 0");
470 continue;
471 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700472 onFirstAdded(res, info);
473 info.resources[resType] = res;
Chong Zhangfb092d32019-08-12 09:45:44 -0700474 } else {
Robert Shihc3af31b2019-09-20 21:45:01 -0700475 mergeResources(info.resources[resType], res);
Chong Zhang79d2b282018-04-17 14:14:31 -0700476 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700477 // Add it to the list of added resources for observers.
478 auto it = resourceAdded.find(resType);
479 if (it == resourceAdded.end()) {
480 resourceAdded[resType] = res;
481 } else {
482 mergeResources(it->second, res);
483 }
Chong Zhang79d2b282018-04-17 14:14:31 -0700484 }
Chong Zhang97d367b2020-09-16 12:53:14 -0700485 if (info.cookie == 0 && client != nullptr) {
486 info.cookie = addCookieAndLink_l(client->asBinder(),
487 new DeathNotifier(ref<ResourceManagerService>(), pid, clientId));
Wonsik Kim3e378962017-01-05 17:00:02 +0900488 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700489 if (mObserverService != nullptr && !resourceAdded.empty()) {
490 mObserverService->onResourceAdded(uid, pid, resourceAdded);
491 }
Dongwon Kangfe508d32015-12-15 14:22:05 +0900492 notifyResourceGranted(pid, resources);
Chong Zhang181e6952019-10-09 13:23:39 -0700493 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700494}
495
Brian Lindahl64ee9452022-01-14 13:31:16 +0100496Status ResourceManagerService::removeResource(int32_t pid, int64_t clientId,
Chong Zhang181e6952019-10-09 13:23:39 -0700497 const std::vector<MediaResourceParcel>& resources) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700498 String8 log = String8::format("removeResource(pid %d, clientId %lld, resources %s)",
499 pid, (long long) clientId, getString(resources).string());
500 mServiceLog->add(log);
501
502 Mutex::Autolock lock(mLock);
503 if (!mProcessInfo->isValidPid(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800504 pid_t callingPid = IPCThreadState::self()->getCallingPid();
505 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
506 pid, callingPid);
507 pid = callingPid;
Chong Zhangfb092d32019-08-12 09:45:44 -0700508 }
509 ssize_t index = mMap.indexOfKey(pid);
510 if (index < 0) {
511 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700512 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700513 }
514 ResourceInfos &infos = mMap.editValueAt(index);
515
516 index = infos.indexOfKey(clientId);
517 if (index < 0) {
518 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700519 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700520 }
521
522 ResourceInfo &info = infos.editValueAt(index);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700523 ResourceList resourceRemoved;
Chong Zhangfb092d32019-08-12 09:45:44 -0700524 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700525 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700526 const auto resType = std::tuple(res.type, res.subType, res.id);
527
528 if (res.value < 0) {
529 ALOGW("Ignoring request to remove negative value of resource");
530 continue;
531 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700532 // ignore if we don't have it
533 if (info.resources.find(resType) != info.resources.end()) {
Chong Zhang181e6952019-10-09 13:23:39 -0700534 MediaResourceParcel &resource = info.resources[resType];
Chong Zhanga9d45c72020-09-09 12:41:17 -0700535 MediaResourceParcel actualRemoved = res;
Chong Zhang181e6952019-10-09 13:23:39 -0700536 if (resource.value > res.value) {
537 resource.value -= res.value;
Chong Zhangfb092d32019-08-12 09:45:44 -0700538 } else {
Robert Shihc3af31b2019-09-20 21:45:01 -0700539 onLastRemoved(res, info);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700540 actualRemoved.value = resource.value;
Chong Zhang102b3e32020-11-02 12:21:50 -0800541 info.resources.erase(resType);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700542 }
543
544 // Add it to the list of removed resources for observers.
545 auto it = resourceRemoved.find(resType);
546 if (it == resourceRemoved.end()) {
547 resourceRemoved[resType] = actualRemoved;
548 } else {
549 mergeResources(it->second, actualRemoved);
Chong Zhangfb092d32019-08-12 09:45:44 -0700550 }
551 }
552 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700553 if (mObserverService != nullptr && !resourceRemoved.empty()) {
554 mObserverService->onResourceRemoved(info.uid, pid, resourceRemoved);
555 }
Chong Zhang181e6952019-10-09 13:23:39 -0700556 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700557}
558
Chong Zhang181e6952019-10-09 13:23:39 -0700559Status ResourceManagerService::removeClient(int32_t pid, int64_t clientId) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800560 removeResource(pid, clientId, true /*checkValid*/);
Chong Zhang181e6952019-10-09 13:23:39 -0700561 return Status::ok();
Wonsik Kim3e378962017-01-05 17:00:02 +0900562}
563
Chong Zhang181e6952019-10-09 13:23:39 -0700564Status ResourceManagerService::removeResource(int pid, int64_t clientId, bool checkValid) {
Ronghua Wu37c89242015-07-15 12:23:48 -0700565 String8 log = String8::format(
566 "removeResource(pid %d, clientId %lld)",
567 pid, (long long) clientId);
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700568 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700569
570 Mutex::Autolock lock(mLock);
Wonsik Kim3e378962017-01-05 17:00:02 +0900571 if (checkValid && !mProcessInfo->isValidPid(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800572 pid_t callingPid = IPCThreadState::self()->getCallingPid();
573 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
574 pid, callingPid);
575 pid = callingPid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800576 }
Ronghua Wu37c89242015-07-15 12:23:48 -0700577 ssize_t index = mMap.indexOfKey(pid);
578 if (index < 0) {
579 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700580 return Status::ok();
Ronghua Wu37c89242015-07-15 12:23:48 -0700581 }
Ronghua Wu37c89242015-07-15 12:23:48 -0700582 ResourceInfos &infos = mMap.editValueAt(index);
Chong Zhangfb092d32019-08-12 09:45:44 -0700583
584 index = infos.indexOfKey(clientId);
585 if (index < 0) {
586 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700587 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700588 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700589
590 const ResourceInfo &info = infos[index];
591 for (auto it = info.resources.begin(); it != info.resources.end(); it++) {
592 onLastRemoved(it->second, info);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700593 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700594
Chong Zhang97d367b2020-09-16 12:53:14 -0700595 removeCookieAndUnlink_l(info.client->asBinder(), info.cookie);
Chong Zhangfb092d32019-08-12 09:45:44 -0700596
Chong Zhanga9d45c72020-09-09 12:41:17 -0700597 if (mObserverService != nullptr && !info.resources.empty()) {
598 mObserverService->onResourceRemoved(info.uid, pid, info.resources);
599 }
600
Chong Zhangfb092d32019-08-12 09:45:44 -0700601 infos.removeItemsAt(index);
Chong Zhang181e6952019-10-09 13:23:39 -0700602 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700603}
604
Brian Lindahl64ee9452022-01-14 13:31:16 +0100605void ResourceManagerService::getClientForResource_l(int callingPid, const MediaResourceParcel *res,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800606 Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700607 if (res == NULL) {
608 return;
609 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800610 std::shared_ptr<IResourceManagerClient> client;
Brian Lindahl64ee9452022-01-14 13:31:16 +0100611 if (getLowestPriorityBiggestClient_l(callingPid, res->type, res->subType, &client)) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700612 clients->push_back(client);
613 }
614}
615
Brian Lindahl64ee9452022-01-14 13:31:16 +0100616Status ResourceManagerService::reclaimResource(int32_t callingPid,
617 const std::vector<MediaResourceParcel>& resources, bool* _aidl_return) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700618 String8 log = String8::format("reclaimResource(callingPid %d, resources %s)",
Ronghua Wu231c3d12015-03-11 15:10:32 -0700619 callingPid, getString(resources).string());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700620 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700621 *_aidl_return = false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700622
Chong Zhangfdd512a2019-11-22 11:03:14 -0800623 Vector<std::shared_ptr<IResourceManagerClient>> clients;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700624 {
625 Mutex::Autolock lock(mLock);
Ronghua Wud11c43a2016-01-27 16:26:12 -0800626 if (!mProcessInfo->isValidPid(callingPid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800627 pid_t actualCallingPid = IPCThreadState::self()->getCallingPid();
628 ALOGW("%s called with untrusted pid %d, using actual calling pid %d", __FUNCTION__,
629 callingPid, actualCallingPid);
630 callingPid = actualCallingPid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800631 }
Chong Zhang181e6952019-10-09 13:23:39 -0700632 const MediaResourceParcel *secureCodec = NULL;
633 const MediaResourceParcel *nonSecureCodec = NULL;
634 const MediaResourceParcel *graphicMemory = NULL;
635 const MediaResourceParcel *drmSession = NULL;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700636 for (size_t i = 0; i < resources.size(); ++i) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100637 switch (resources[i].type) {
638 case MediaResource::Type::kSecureCodec:
639 secureCodec = &resources[i];
640 break;
641 case MediaResource::Type::kNonSecureCodec:
642 nonSecureCodec = &resources[i];
643 break;
644 case MediaResource::Type::kGraphicMemory:
645 graphicMemory = &resources[i];
646 break;
647 case MediaResource::Type::kDrmSession:
648 drmSession = &resources[i];
649 break;
650 default:
651 break;
Ronghua Wu05d89f12015-07-07 16:47:42 -0700652 }
653 }
654
655 // first pass to handle secure/non-secure codec conflict
656 if (secureCodec != NULL) {
657 if (!mSupportsMultipleSecureCodecs) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100658 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec,
659 secureCodec->subType, &clients)) {
Chong Zhang181e6952019-10-09 13:23:39 -0700660 return Status::ok();
Ronghua Wu05d89f12015-07-07 16:47:42 -0700661 }
662 }
663 if (!mSupportsSecureWithNonSecureCodec) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100664 if (!getAllClients_l(callingPid, MediaResource::Type::kNonSecureCodec,
665 secureCodec->subType, &clients)) {
Chong Zhang181e6952019-10-09 13:23:39 -0700666 return Status::ok();
Ronghua Wu05d89f12015-07-07 16:47:42 -0700667 }
668 }
669 }
670 if (nonSecureCodec != NULL) {
671 if (!mSupportsSecureWithNonSecureCodec) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100672 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec,
673 nonSecureCodec->subType, &clients)) {
Chong Zhang181e6952019-10-09 13:23:39 -0700674 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700675 }
676 }
677 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700678 if (drmSession != NULL) {
679 getClientForResource_l(callingPid, drmSession, &clients);
680 if (clients.size() == 0) {
Chong Zhang181e6952019-10-09 13:23:39 -0700681 return Status::ok();
Robert Shihc3af31b2019-09-20 21:45:01 -0700682 }
683 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700684
685 if (clients.size() == 0) {
686 // if no secure/non-secure codec conflict, run second pass to handle other resources.
Ronghua Wu05d89f12015-07-07 16:47:42 -0700687 getClientForResource_l(callingPid, graphicMemory, &clients);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700688 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700689
690 if (clients.size() == 0) {
691 // if we are here, run the third pass to free one codec with the same type.
Ronghua Wu05d89f12015-07-07 16:47:42 -0700692 getClientForResource_l(callingPid, secureCodec, &clients);
693 getClientForResource_l(callingPid, nonSecureCodec, &clients);
694 }
695
696 if (clients.size() == 0) {
697 // if we are here, run the fourth pass to free one codec with the different type.
698 if (secureCodec != NULL) {
Chong Zhang181e6952019-10-09 13:23:39 -0700699 MediaResource temp(MediaResource::Type::kNonSecureCodec, 1);
Ronghua Wu05d89f12015-07-07 16:47:42 -0700700 getClientForResource_l(callingPid, &temp, &clients);
701 }
702 if (nonSecureCodec != NULL) {
Chong Zhang181e6952019-10-09 13:23:39 -0700703 MediaResource temp(MediaResource::Type::kSecureCodec, 1);
Ronghua Wu05d89f12015-07-07 16:47:42 -0700704 getClientForResource_l(callingPid, &temp, &clients);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700705 }
706 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700707 }
708
Brian Lindahl64ee9452022-01-14 13:31:16 +0100709 *_aidl_return = reclaimUnconditionallyFrom(clients);
Wonsik Kim271429d2020-10-01 10:12:56 -0700710 return Status::ok();
711}
712
Brian Lindahl64ee9452022-01-14 13:31:16 +0100713bool ResourceManagerService::reclaimUnconditionallyFrom(
Wonsik Kim271429d2020-10-01 10:12:56 -0700714 const Vector<std::shared_ptr<IResourceManagerClient>> &clients) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700715 if (clients.size() == 0) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700716 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700717 }
718
Chong Zhangfdd512a2019-11-22 11:03:14 -0800719 std::shared_ptr<IResourceManagerClient> failedClient;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700720 for (size_t i = 0; i < clients.size(); ++i) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700721 String8 log = String8::format("reclaimResource from client %p", clients[i].get());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700722 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700723 bool success;
724 Status status = clients[i]->reclaimResource(&success);
725 if (!status.isOk() || !success) {
Ronghua Wu67e7f542015-03-13 10:47:08 -0700726 failedClient = clients[i];
727 break;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700728 }
729 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700730
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700731 if (failedClient == NULL) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700732 return true;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700733 }
734
Ronghua Wu67e7f542015-03-13 10:47:08 -0700735 {
736 Mutex::Autolock lock(mLock);
737 bool found = false;
738 for (size_t i = 0; i < mMap.size(); ++i) {
739 ResourceInfos &infos = mMap.editValueAt(i);
740 for (size_t j = 0; j < infos.size();) {
741 if (infos[j].client == failedClient) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700742 j = infos.removeItemsAt(j);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700743 found = true;
744 } else {
745 ++j;
746 }
747 }
748 if (found) {
749 break;
750 }
751 }
752 if (!found) {
753 ALOGV("didn't find failed client");
754 }
755 }
756
Wonsik Kim271429d2020-10-01 10:12:56 -0700757 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700758}
759
Brian Lindahl64ee9452022-01-14 13:31:16 +0100760Status ResourceManagerService::overridePid(int originalPid, int newPid) {
Henry Fang32762922020-01-28 18:40:39 -0800761 String8 log = String8::format("overridePid(originalPid %d, newPid %d)",
762 originalPid, newPid);
763 mServiceLog->add(log);
764
765 // allow if this is called from the same process or the process has
766 // permission.
767 if ((AIBinder_getCallingPid() != getpid()) &&
768 (checkCallingPermission(String16(
769 "android.permission.MEDIA_RESOURCE_OVERRIDE_PID")) == false)) {
770 ALOGE(
771 "Permission Denial: can't access overridePid method from pid=%d, "
772 "self pid=%d\n",
773 AIBinder_getCallingPid(), getpid());
774 return Status::fromServiceSpecificError(PERMISSION_DENIED);
775 }
776
777 {
778 Mutex::Autolock lock(mLock);
779 mOverridePidMap.erase(originalPid);
780 if (newPid != -1) {
781 mOverridePidMap.emplace(originalPid, newPid);
782 }
783 }
784
785 return Status::ok();
786}
787
Chong Zhang97d367b2020-09-16 12:53:14 -0700788Status ResourceManagerService::overrideProcessInfo(
Brian Lindahl64ee9452022-01-14 13:31:16 +0100789 const std::shared_ptr<IResourceManagerClient>& client, int pid, int procState,
Chong Zhang97d367b2020-09-16 12:53:14 -0700790 int oomScore) {
791 String8 log = String8::format("overrideProcessInfo(pid %d, procState %d, oomScore %d)",
792 pid, procState, oomScore);
793 mServiceLog->add(log);
794
795 // Only allow the override if the caller already can access process state and oom scores.
796 int callingPid = AIBinder_getCallingPid();
797 if (callingPid != getpid() && (callingPid != pid || !checkCallingPermission(String16(
798 "android.permission.GET_PROCESS_STATE_AND_OOM_SCORE")))) {
799 ALOGE("Permission Denial: overrideProcessInfo method from pid=%d", callingPid);
800 return Status::fromServiceSpecificError(PERMISSION_DENIED);
801 }
802
803 if (client == nullptr) {
804 return Status::fromServiceSpecificError(BAD_VALUE);
805 }
806
807 Mutex::Autolock lock(mLock);
808 removeProcessInfoOverride_l(pid);
809
810 if (!mProcessInfo->overrideProcessInfo(pid, procState, oomScore)) {
811 // Override value is rejected by ProcessInfo.
812 return Status::fromServiceSpecificError(BAD_VALUE);
813 }
814
815 uintptr_t cookie = addCookieAndLink_l(client->asBinder(),
816 new OverrideProcessInfoDeathNotifier(ref<ResourceManagerService>(), pid));
817
818 mProcessInfoOverrideMap.emplace(pid, ProcessInfoOverride{cookie, client});
819
820 return Status::ok();
821}
822
Brian Lindahl64ee9452022-01-14 13:31:16 +0100823uintptr_t ResourceManagerService::addCookieAndLink_l(::ndk::SpAIBinder binder,
824 const sp<DeathNotifier>& notifier) {
Chong Zhang97d367b2020-09-16 12:53:14 -0700825 std::scoped_lock lock{sCookieLock};
826
827 uintptr_t cookie;
828 // Need to skip cookie 0 (if it wraps around). ResourceInfo has cookie initialized to 0
829 // indicating the death notifier is not created yet.
830 while ((cookie = ++sCookieCounter) == 0);
831 AIBinder_linkToDeath(binder.get(), mDeathRecipient.get(), (void*)cookie);
832 sCookieToDeathNotifierMap.emplace(cookie, notifier);
833
834 return cookie;
835}
836
Brian Lindahl64ee9452022-01-14 13:31:16 +0100837void ResourceManagerService::removeCookieAndUnlink_l(::ndk::SpAIBinder binder, uintptr_t cookie) {
Chong Zhang97d367b2020-09-16 12:53:14 -0700838 std::scoped_lock lock{sCookieLock};
839 AIBinder_unlinkToDeath(binder.get(), mDeathRecipient.get(), (void*)cookie);
840 sCookieToDeathNotifierMap.erase(cookie);
841}
842
843void ResourceManagerService::removeProcessInfoOverride(int pid) {
844 Mutex::Autolock lock(mLock);
845
846 removeProcessInfoOverride_l(pid);
847}
848
849void ResourceManagerService::removeProcessInfoOverride_l(int pid) {
850 auto it = mProcessInfoOverrideMap.find(pid);
851 if (it == mProcessInfoOverrideMap.end()) {
852 return;
853 }
854
855 mProcessInfo->removeProcessInfoOverride(pid);
856
857 removeCookieAndUnlink_l(it->second.client->asBinder(), it->second.cookie);
858
859 mProcessInfoOverrideMap.erase(pid);
860}
861
Wonsik Kimd20e9362020-04-28 10:42:57 -0700862Status ResourceManagerService::markClientForPendingRemoval(int32_t pid, int64_t clientId) {
863 String8 log = String8::format(
864 "markClientForPendingRemoval(pid %d, clientId %lld)",
865 pid, (long long) clientId);
866 mServiceLog->add(log);
867
868 Mutex::Autolock lock(mLock);
869 if (!mProcessInfo->isValidPid(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800870 pid_t callingPid = IPCThreadState::self()->getCallingPid();
871 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
872 pid, callingPid);
873 pid = callingPid;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700874 }
875 ssize_t index = mMap.indexOfKey(pid);
876 if (index < 0) {
877 ALOGV("markClientForPendingRemoval: didn't find pid %d for clientId %lld",
878 pid, (long long)clientId);
879 return Status::ok();
880 }
881 ResourceInfos &infos = mMap.editValueAt(index);
882
883 index = infos.indexOfKey(clientId);
884 if (index < 0) {
885 ALOGV("markClientForPendingRemoval: didn't find clientId %lld", (long long) clientId);
886 return Status::ok();
887 }
888
889 ResourceInfo &info = infos.editValueAt(index);
890 info.pendingRemoval = true;
891 return Status::ok();
892}
893
Wonsik Kim271429d2020-10-01 10:12:56 -0700894Status ResourceManagerService::reclaimResourcesFromClientsPendingRemoval(int32_t pid) {
895 String8 log = String8::format("reclaimResourcesFromClientsPendingRemoval(pid %d)", pid);
896 mServiceLog->add(log);
897
898 Vector<std::shared_ptr<IResourceManagerClient>> clients;
899 {
900 Mutex::Autolock lock(mLock);
901 if (!mProcessInfo->isValidPid(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800902 pid_t callingPid = IPCThreadState::self()->getCallingPid();
903 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
904 pid, callingPid);
905 pid = callingPid;
Wonsik Kim271429d2020-10-01 10:12:56 -0700906 }
907
908 for (MediaResource::Type type : {MediaResource::Type::kSecureCodec,
909 MediaResource::Type::kNonSecureCodec,
910 MediaResource::Type::kGraphicMemory,
911 MediaResource::Type::kDrmSession}) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100912 switch (type) {
913 // Codec resources are segregated by audio, video and image domains.
914 case MediaResource::Type::kSecureCodec:
915 case MediaResource::Type::kNonSecureCodec:
916 for (MediaResource::SubType subType : {MediaResource::SubType::kAudioCodec,
917 MediaResource::SubType::kVideoCodec,
918 MediaResource::SubType::kImageCodec}) {
919 std::shared_ptr<IResourceManagerClient> client;
920 if (getBiggestClientPendingRemoval_l(pid, type, subType, &client)) {
921 clients.add(client);
922 continue;
923 }
924 }
925 break;
926 // Non-codec resources are shared by audio, video and image codecs (no subtype).
927 default:
928 std::shared_ptr<IResourceManagerClient> client;
929 if (getBiggestClientPendingRemoval_l(pid, type,
930 MediaResource::SubType::kUnspecifiedSubType, &client)) {
931 clients.add(client);
932 }
933 break;
Wonsik Kim271429d2020-10-01 10:12:56 -0700934 }
935 }
936 }
937
938 if (!clients.empty()) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100939 reclaimUnconditionallyFrom(clients);
Wonsik Kim271429d2020-10-01 10:12:56 -0700940 }
941 return Status::ok();
942}
943
Henry Fang32762922020-01-28 18:40:39 -0800944bool ResourceManagerService::getPriority_l(int pid, int* priority) {
945 int newPid = pid;
946
947 if (mOverridePidMap.find(pid) != mOverridePidMap.end()) {
948 newPid = mOverridePidMap[pid];
949 ALOGD("getPriority_l: use override pid %d instead original pid %d",
950 newPid, pid);
951 }
952
953 return mProcessInfo->getPriority(newPid, priority);
954}
955
Brian Lindahl64ee9452022-01-14 13:31:16 +0100956bool ResourceManagerService::getAllClients_l(int callingPid, MediaResource::Type type,
957 MediaResource::SubType subType, Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800958 Vector<std::shared_ptr<IResourceManagerClient>> temp;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700959 for (size_t i = 0; i < mMap.size(); ++i) {
960 ResourceInfos &infos = mMap.editValueAt(i);
961 for (size_t j = 0; j < infos.size(); ++j) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100962 if (hasResourceType(type, subType, infos[j].resources)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700963 if (!isCallingPriorityHigher_l(callingPid, mMap.keyAt(i))) {
964 // some higher/equal priority process owns the resource,
965 // this request can't be fulfilled.
966 ALOGE("getAllClients_l: can't reclaim resource %s from pid %d",
Ronghua Wuea15fd22016-03-03 13:35:05 -0800967 asString(type), mMap.keyAt(i));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700968 return false;
969 }
970 temp.push_back(infos[j].client);
971 }
972 }
973 }
974 if (temp.size() == 0) {
Ronghua Wuea15fd22016-03-03 13:35:05 -0800975 ALOGV("getAllClients_l: didn't find any resource %s", asString(type));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700976 return true;
977 }
978 clients->appendVector(temp);
979 return true;
980}
981
Brian Lindahl64ee9452022-01-14 13:31:16 +0100982bool ResourceManagerService::getLowestPriorityBiggestClient_l(int callingPid,
983 MediaResource::Type type, MediaResource::SubType subType,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800984 std::shared_ptr<IResourceManagerClient> *client) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700985 int lowestPriorityPid;
986 int lowestPriority;
987 int callingPriority;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700988
989 // Before looking into other processes, check if we have clients marked for
990 // pending removal in the same process.
Brian Lindahl64ee9452022-01-14 13:31:16 +0100991 if (getBiggestClientPendingRemoval_l(callingPid, type, subType, client)) {
Wonsik Kimd20e9362020-04-28 10:42:57 -0700992 return true;
993 }
Henry Fang32762922020-01-28 18:40:39 -0800994 if (!getPriority_l(callingPid, &callingPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700995 ALOGE("getLowestPriorityBiggestClient_l: can't get process priority for pid %d",
996 callingPid);
997 return false;
998 }
Brian Lindahl64ee9452022-01-14 13:31:16 +0100999 if (!getLowestPriorityPid_l(type, subType, &lowestPriorityPid, &lowestPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001000 return false;
1001 }
1002 if (lowestPriority <= callingPriority) {
1003 ALOGE("getLowestPriorityBiggestClient_l: lowest priority %d vs caller priority %d",
1004 lowestPriority, callingPriority);
1005 return false;
1006 }
1007
Brian Lindahl64ee9452022-01-14 13:31:16 +01001008 if (!getBiggestClient_l(lowestPriorityPid, type, subType, client)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001009 return false;
1010 }
1011 return true;
1012}
1013
Brian Lindahl64ee9452022-01-14 13:31:16 +01001014bool ResourceManagerService::getLowestPriorityPid_l(MediaResource::Type type,
1015 MediaResource::SubType subType, int *lowestPriorityPid, int *lowestPriority) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001016 int pid = -1;
1017 int priority = -1;
1018 for (size_t i = 0; i < mMap.size(); ++i) {
1019 if (mMap.valueAt(i).size() == 0) {
1020 // no client on this process.
1021 continue;
1022 }
Brian Lindahl64ee9452022-01-14 13:31:16 +01001023 if (!hasResourceType(type, subType, mMap.valueAt(i))) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001024 // doesn't have the requested resource type
1025 continue;
1026 }
1027 int tempPid = mMap.keyAt(i);
1028 int tempPriority;
Henry Fang32762922020-01-28 18:40:39 -08001029 if (!getPriority_l(tempPid, &tempPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001030 ALOGV("getLowestPriorityPid_l: can't get priority of pid %d, skipped", tempPid);
1031 // TODO: remove this pid from mMap?
1032 continue;
1033 }
1034 if (pid == -1 || tempPriority > priority) {
1035 // initial the value
1036 pid = tempPid;
1037 priority = tempPriority;
1038 }
1039 }
1040 if (pid != -1) {
1041 *lowestPriorityPid = pid;
1042 *lowestPriority = priority;
1043 }
1044 return (pid != -1);
1045}
1046
1047bool ResourceManagerService::isCallingPriorityHigher_l(int callingPid, int pid) {
1048 int callingPidPriority;
Henry Fang32762922020-01-28 18:40:39 -08001049 if (!getPriority_l(callingPid, &callingPidPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001050 return false;
1051 }
1052
1053 int priority;
Henry Fang32762922020-01-28 18:40:39 -08001054 if (!getPriority_l(pid, &priority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001055 return false;
1056 }
1057
1058 return (callingPidPriority < priority);
1059}
1060
Brian Lindahl64ee9452022-01-14 13:31:16 +01001061bool ResourceManagerService::getBiggestClientPendingRemoval_l(int pid, MediaResource::Type type,
1062 MediaResource::SubType subType, std::shared_ptr<IResourceManagerClient> *client) {
1063 return getBiggestClient_l(pid, type, subType, client, true /* pendingRemovalOnly */);
1064}
1065
1066bool ResourceManagerService::getBiggestClient_l(int pid, MediaResource::Type type,
1067 MediaResource::SubType subType, std::shared_ptr<IResourceManagerClient> *client,
Wonsik Kimd20e9362020-04-28 10:42:57 -07001068 bool pendingRemovalOnly) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001069 ssize_t index = mMap.indexOfKey(pid);
1070 if (index < 0) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001071 ALOGE_IF(!pendingRemovalOnly,
1072 "getBiggestClient_l: can't find resource info for pid %d", pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001073 return false;
1074 }
1075
Chong Zhangfdd512a2019-11-22 11:03:14 -08001076 std::shared_ptr<IResourceManagerClient> clientTemp;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001077 uint64_t largestValue = 0;
1078 const ResourceInfos &infos = mMap.valueAt(index);
1079 for (size_t i = 0; i < infos.size(); ++i) {
Chong Zhangfb092d32019-08-12 09:45:44 -07001080 const ResourceList &resources = infos[i].resources;
Wonsik Kimd20e9362020-04-28 10:42:57 -07001081 if (pendingRemovalOnly && !infos[i].pendingRemoval) {
1082 continue;
1083 }
Chong Zhangfb092d32019-08-12 09:45:44 -07001084 for (auto it = resources.begin(); it != resources.end(); it++) {
Chong Zhang181e6952019-10-09 13:23:39 -07001085 const MediaResourceParcel &resource = it->second;
Brian Lindahl64ee9452022-01-14 13:31:16 +01001086 if (hasResourceType(type, subType, resource)) {
Chong Zhang181e6952019-10-09 13:23:39 -07001087 if (resource.value > largestValue) {
1088 largestValue = resource.value;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001089 clientTemp = infos[i].client;
1090 }
1091 }
1092 }
1093 }
1094
1095 if (clientTemp == NULL) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001096 ALOGE_IF(!pendingRemovalOnly,
Brian Lindahl64ee9452022-01-14 13:31:16 +01001097 "getBiggestClient_l: can't find resource type %s and subtype %s for pid %d",
1098 asString(type), asString(subType), pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001099 return false;
1100 }
1101
1102 *client = clientTemp;
1103 return true;
1104}
1105
Ronghua Wu231c3d12015-03-11 15:10:32 -07001106} // namespace android