blob: 4d18876bfca6eb82dff8a4de53f20e951da8942d [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
Arun Johnsonaabe0142022-07-18 19:16:04 +0000274 std::string clientName = "<unknown client>";
275 if (infos[j].client != nullptr) {
276 Status status = infos[j].client->getName(&clientName);
Chong Zhang181e6952019-10-09 13:23:39 -0700277 }
278 snprintf(buffer, SIZE, " Name: %s\n", clientName.c_str());
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700279 result.append(buffer);
280
Chong Zhangfb092d32019-08-12 09:45:44 -0700281 const ResourceList &resources = infos[j].resources;
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700282 result.append(" Resources:\n");
Chong Zhangfb092d32019-08-12 09:45:44 -0700283 for (auto it = resources.begin(); it != resources.end(); it++) {
Chong Zhang181e6952019-10-09 13:23:39 -0700284 snprintf(buffer, SIZE, " %s\n", toString(it->second).string());
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700285 result.append(buffer);
286 }
287 }
288 }
Henry Fang32762922020-01-28 18:40:39 -0800289 result.append(" Process Pid override:\n");
290 for (auto it = overridePidMapCopy.begin(); it != overridePidMapCopy.end(); ++it) {
291 snprintf(buffer, SIZE, " Original Pid: %d, Override Pid: %d\n",
292 it->first, it->second);
293 result.append(buffer);
294 }
Ronghua Wu022ed722015-05-11 15:15:09 -0700295 result.append(" Events logs (most recent at top):\n");
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700296 result.append(serviceLog);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700297
298 write(fd, result.string(), result.size());
299 return OK;
300}
301
Brian Lindahl64ee9452022-01-14 13:31:16 +0100302struct SystemCallbackImpl : public ResourceManagerService::SystemCallbackInterface {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800303 SystemCallbackImpl() : mClientToken(new BBinder()) {}
Ronghua Wu231c3d12015-03-11 15:10:32 -0700304
Chong Zhangdd726802019-08-21 17:24:13 -0700305 virtual void noteStartVideo(int uid) override {
306 BatteryNotifier::getInstance().noteStartVideo(uid);
307 }
308 virtual void noteStopVideo(int uid) override {
309 BatteryNotifier::getInstance().noteStopVideo(uid);
310 }
311 virtual void noteResetVideo() override {
312 BatteryNotifier::getInstance().noteResetVideo();
313 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800314 virtual bool requestCpusetBoost(bool enable) override {
315 return android::requestCpusetBoost(enable, mClientToken);
Chong Zhangdd726802019-08-21 17:24:13 -0700316 }
317
318protected:
319 virtual ~SystemCallbackImpl() {}
320
321private:
322 DISALLOW_EVIL_CONSTRUCTORS(SystemCallbackImpl);
Chong Zhangfdd512a2019-11-22 11:03:14 -0800323 sp<IBinder> mClientToken;
Chong Zhangdd726802019-08-21 17:24:13 -0700324};
325
326ResourceManagerService::ResourceManagerService()
327 : ResourceManagerService(new ProcessInfo(), new SystemCallbackImpl()) {}
328
Brian Lindahl64ee9452022-01-14 13:31:16 +0100329ResourceManagerService::ResourceManagerService(const sp<ProcessInfoInterface> &processInfo,
Chong Zhangdd726802019-08-21 17:24:13 -0700330 const sp<SystemCallbackInterface> &systemResource)
Ronghua Wu231c3d12015-03-11 15:10:32 -0700331 : mProcessInfo(processInfo),
Chong Zhangdd726802019-08-21 17:24:13 -0700332 mSystemCB(systemResource),
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700333 mServiceLog(new ServiceLog()),
Ronghua Wu231c3d12015-03-11 15:10:32 -0700334 mSupportsMultipleSecureCodecs(true),
Chong Zhang79d2b282018-04-17 14:14:31 -0700335 mSupportsSecureWithNonSecureCodec(true),
Chong Zhangfdd512a2019-11-22 11:03:14 -0800336 mCpuBoostCount(0),
337 mDeathRecipient(AIBinder_DeathRecipient_new(DeathNotifier::BinderDiedCallback)) {
Chong Zhangdd726802019-08-21 17:24:13 -0700338 mSystemCB->noteResetVideo();
Chong Zhangee33d642019-08-08 14:26:43 -0700339}
Ronghua Wu231c3d12015-03-11 15:10:32 -0700340
Chong Zhangfdd512a2019-11-22 11:03:14 -0800341//static
342void ResourceManagerService::instantiate() {
343 std::shared_ptr<ResourceManagerService> service =
344 ::ndk::SharedRefBase::make<ResourceManagerService>();
345 binder_status_t status =
346 AServiceManager_addService(service->asBinder().get(), getServiceName());
347 if (status != STATUS_OK) {
348 return;
349 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700350
351 std::shared_ptr<ResourceObserverService> observerService =
352 ResourceObserverService::instantiate();
353
354 if (observerService != nullptr) {
355 service->setObserverService(observerService);
356 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800357 // TODO: mediaserver main() is already starting the thread pool,
358 // move this to mediaserver main() when other services in mediaserver
359 // are converted to ndk-platform aidl.
360 //ABinderProcess_startThreadPool();
361}
362
Ronghua Wu231c3d12015-03-11 15:10:32 -0700363ResourceManagerService::~ResourceManagerService() {}
364
Chong Zhanga9d45c72020-09-09 12:41:17 -0700365void ResourceManagerService::setObserverService(
366 const std::shared_ptr<ResourceObserverService>& observerService) {
367 mObserverService = observerService;
368}
369
Chong Zhang181e6952019-10-09 13:23:39 -0700370Status ResourceManagerService::config(const std::vector<MediaResourcePolicyParcel>& policies) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700371 String8 log = String8::format("config(%s)", getString(policies).string());
372 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700373
374 Mutex::Autolock lock(mLock);
375 for (size_t i = 0; i < policies.size(); ++i) {
Chong Zhang181e6952019-10-09 13:23:39 -0700376 const std::string &type = policies[i].type;
377 const std::string &value = policies[i].value;
378 if (type == MediaResourcePolicy::kPolicySupportsMultipleSecureCodecs()) {
Ronghua Wu9ba21b92015-04-21 14:23:06 -0700379 mSupportsMultipleSecureCodecs = (value == "true");
Chong Zhang181e6952019-10-09 13:23:39 -0700380 } else if (type == MediaResourcePolicy::kPolicySupportsSecureWithNonSecureCodec()) {
Ronghua Wu9ba21b92015-04-21 14:23:06 -0700381 mSupportsSecureWithNonSecureCodec = (value == "true");
Ronghua Wu231c3d12015-03-11 15:10:32 -0700382 }
383 }
Chong Zhang181e6952019-10-09 13:23:39 -0700384 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700385}
386
Brian Lindahl64ee9452022-01-14 13:31:16 +0100387void ResourceManagerService::onFirstAdded(const MediaResourceParcel& resource,
388 const ResourceInfo& clientInfo) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700389 // first time added
Chong Zhang181e6952019-10-09 13:23:39 -0700390 if (resource.type == MediaResource::Type::kCpuBoost
391 && resource.subType == MediaResource::SubType::kUnspecifiedSubType) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700392 // Request it on every new instance of kCpuBoost, as the media.codec
393 // could have died, if we only do it the first time subsequent instances
394 // never gets the boost.
Chong Zhangfdd512a2019-11-22 11:03:14 -0800395 if (mSystemCB->requestCpusetBoost(true) != OK) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700396 ALOGW("couldn't request cpuset boost");
397 }
398 mCpuBoostCount++;
Chong Zhang181e6952019-10-09 13:23:39 -0700399 } else if (resource.type == MediaResource::Type::kBattery
400 && resource.subType == MediaResource::SubType::kVideoCodec) {
Chong Zhangdd726802019-08-21 17:24:13 -0700401 mSystemCB->noteStartVideo(clientInfo.uid);
Chong Zhangfb092d32019-08-12 09:45:44 -0700402 }
403}
404
Brian Lindahl64ee9452022-01-14 13:31:16 +0100405void ResourceManagerService::onLastRemoved(const MediaResourceParcel& resource,
406 const ResourceInfo& clientInfo) {
Chong Zhang181e6952019-10-09 13:23:39 -0700407 if (resource.type == MediaResource::Type::kCpuBoost
408 && resource.subType == MediaResource::SubType::kUnspecifiedSubType
Chong Zhangfb092d32019-08-12 09:45:44 -0700409 && mCpuBoostCount > 0) {
410 if (--mCpuBoostCount == 0) {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800411 mSystemCB->requestCpusetBoost(false);
Chong Zhangfb092d32019-08-12 09:45:44 -0700412 }
Chong Zhang181e6952019-10-09 13:23:39 -0700413 } else if (resource.type == MediaResource::Type::kBattery
414 && resource.subType == MediaResource::SubType::kVideoCodec) {
Chong Zhangdd726802019-08-21 17:24:13 -0700415 mSystemCB->noteStopVideo(clientInfo.uid);
Chong Zhangfb092d32019-08-12 09:45:44 -0700416 }
417}
418
Brian Lindahl64ee9452022-01-14 13:31:16 +0100419void ResourceManagerService::mergeResources(MediaResourceParcel& r1,
420 const MediaResourceParcel& r2) {
Chong Zhang181e6952019-10-09 13:23:39 -0700421 // The resource entry on record is maintained to be in [0,INT64_MAX].
422 // Clamp if merging in the new resource value causes it to go out of bound.
423 // Note that the new resource value could be negative, eg.DrmSession, the
424 // value goes lower when the session is used more often. During reclaim
425 // the session with the highest value (lowest usage) would be closed.
426 if (r2.value < INT64_MAX - r1.value) {
427 r1.value += r2.value;
428 if (r1.value < 0) {
429 r1.value = 0;
430 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700431 } else {
Chong Zhang181e6952019-10-09 13:23:39 -0700432 r1.value = INT64_MAX;
Robert Shihc3af31b2019-09-20 21:45:01 -0700433 }
434}
435
Brian Lindahl64ee9452022-01-14 13:31:16 +0100436Status ResourceManagerService::addResource(int32_t pid, int32_t uid, int64_t clientId,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800437 const std::shared_ptr<IResourceManagerClient>& client,
Chong Zhang181e6952019-10-09 13:23:39 -0700438 const std::vector<MediaResourceParcel>& resources) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700439 String8 log = String8::format("addResource(pid %d, clientId %lld, resources %s)",
Ronghua Wu231c3d12015-03-11 15:10:32 -0700440 pid, (long long) clientId, getString(resources).string());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700441 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700442
443 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100444 if (!mProcessInfo->isPidUidTrusted(pid, uid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800445 pid_t callingPid = IPCThreadState::self()->getCallingPid();
446 uid_t callingUid = IPCThreadState::self()->getCallingUid();
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100447 ALOGW("%s called with untrusted pid %d or uid %d, using calling pid %d, uid %d",
448 __FUNCTION__, pid, uid, callingPid, callingUid);
Chong Zhangc7303e82020-12-02 16:38:52 -0800449 pid = callingPid;
450 uid = callingUid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800451 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700452 ResourceInfos& infos = getResourceInfosForEdit(pid, mMap);
Chong Zhangee33d642019-08-08 14:26:43 -0700453 ResourceInfo& info = getResourceInfoForEdit(uid, clientId, client, infos);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700454 ResourceList resourceAdded;
Chong Zhang79d2b282018-04-17 14:14:31 -0700455
456 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700457 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700458 const auto resType = std::tuple(res.type, res.subType, res.id);
459
460 if (res.value < 0 && res.type != MediaResource::Type::kDrmSession) {
461 ALOGW("Ignoring request to remove negative value of non-drm resource");
462 continue;
463 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700464 if (info.resources.find(resType) == info.resources.end()) {
Chong Zhang181e6952019-10-09 13:23:39 -0700465 if (res.value <= 0) {
466 // We can't init a new entry with negative value, although it's allowed
467 // to merge in negative values after the initial add.
468 ALOGW("Ignoring request to add new resource entry with value <= 0");
469 continue;
470 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700471 onFirstAdded(res, info);
472 info.resources[resType] = res;
Chong Zhangfb092d32019-08-12 09:45:44 -0700473 } else {
Robert Shihc3af31b2019-09-20 21:45:01 -0700474 mergeResources(info.resources[resType], res);
Chong Zhang79d2b282018-04-17 14:14:31 -0700475 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700476 // Add it to the list of added resources for observers.
477 auto it = resourceAdded.find(resType);
478 if (it == resourceAdded.end()) {
479 resourceAdded[resType] = res;
480 } else {
481 mergeResources(it->second, res);
482 }
Chong Zhang79d2b282018-04-17 14:14:31 -0700483 }
Chong Zhang97d367b2020-09-16 12:53:14 -0700484 if (info.cookie == 0 && client != nullptr) {
Arun Johnsond1f59732022-03-25 17:10:29 +0000485 info.cookie = addCookieAndLink_l(client,
Chong Zhang97d367b2020-09-16 12:53:14 -0700486 new DeathNotifier(ref<ResourceManagerService>(), pid, clientId));
Wonsik Kim3e378962017-01-05 17:00:02 +0900487 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700488 if (mObserverService != nullptr && !resourceAdded.empty()) {
489 mObserverService->onResourceAdded(uid, pid, resourceAdded);
490 }
Dongwon Kangfe508d32015-12-15 14:22:05 +0900491 notifyResourceGranted(pid, resources);
Chong Zhang181e6952019-10-09 13:23:39 -0700492 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700493}
494
Brian Lindahl64ee9452022-01-14 13:31:16 +0100495Status ResourceManagerService::removeResource(int32_t pid, int64_t clientId,
Chong Zhang181e6952019-10-09 13:23:39 -0700496 const std::vector<MediaResourceParcel>& resources) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700497 String8 log = String8::format("removeResource(pid %d, clientId %lld, resources %s)",
498 pid, (long long) clientId, getString(resources).string());
499 mServiceLog->add(log);
500
501 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100502 if (!mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800503 pid_t callingPid = IPCThreadState::self()->getCallingPid();
504 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
505 pid, callingPid);
506 pid = callingPid;
Chong Zhangfb092d32019-08-12 09:45:44 -0700507 }
508 ssize_t index = mMap.indexOfKey(pid);
509 if (index < 0) {
510 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700511 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700512 }
513 ResourceInfos &infos = mMap.editValueAt(index);
514
515 index = infos.indexOfKey(clientId);
516 if (index < 0) {
517 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700518 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700519 }
520
521 ResourceInfo &info = infos.editValueAt(index);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700522 ResourceList resourceRemoved;
Chong Zhangfb092d32019-08-12 09:45:44 -0700523 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700524 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700525 const auto resType = std::tuple(res.type, res.subType, res.id);
526
527 if (res.value < 0) {
528 ALOGW("Ignoring request to remove negative value of resource");
529 continue;
530 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700531 // ignore if we don't have it
532 if (info.resources.find(resType) != info.resources.end()) {
Chong Zhang181e6952019-10-09 13:23:39 -0700533 MediaResourceParcel &resource = info.resources[resType];
Chong Zhanga9d45c72020-09-09 12:41:17 -0700534 MediaResourceParcel actualRemoved = res;
Chong Zhang181e6952019-10-09 13:23:39 -0700535 if (resource.value > res.value) {
536 resource.value -= res.value;
Chong Zhangfb092d32019-08-12 09:45:44 -0700537 } else {
Robert Shihc3af31b2019-09-20 21:45:01 -0700538 onLastRemoved(res, info);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700539 actualRemoved.value = resource.value;
Chong Zhang102b3e32020-11-02 12:21:50 -0800540 info.resources.erase(resType);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700541 }
542
543 // Add it to the list of removed resources for observers.
544 auto it = resourceRemoved.find(resType);
545 if (it == resourceRemoved.end()) {
546 resourceRemoved[resType] = actualRemoved;
547 } else {
548 mergeResources(it->second, actualRemoved);
Chong Zhangfb092d32019-08-12 09:45:44 -0700549 }
550 }
551 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700552 if (mObserverService != nullptr && !resourceRemoved.empty()) {
553 mObserverService->onResourceRemoved(info.uid, pid, resourceRemoved);
554 }
Chong Zhang181e6952019-10-09 13:23:39 -0700555 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700556}
557
Chong Zhang181e6952019-10-09 13:23:39 -0700558Status ResourceManagerService::removeClient(int32_t pid, int64_t clientId) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800559 removeResource(pid, clientId, true /*checkValid*/);
Chong Zhang181e6952019-10-09 13:23:39 -0700560 return Status::ok();
Wonsik Kim3e378962017-01-05 17:00:02 +0900561}
562
Chong Zhang181e6952019-10-09 13:23:39 -0700563Status ResourceManagerService::removeResource(int pid, int64_t clientId, bool checkValid) {
Ronghua Wu37c89242015-07-15 12:23:48 -0700564 String8 log = String8::format(
565 "removeResource(pid %d, clientId %lld)",
566 pid, (long long) clientId);
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700567 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700568
569 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100570 if (checkValid && !mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800571 pid_t callingPid = IPCThreadState::self()->getCallingPid();
572 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
573 pid, callingPid);
574 pid = callingPid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800575 }
Ronghua Wu37c89242015-07-15 12:23:48 -0700576 ssize_t index = mMap.indexOfKey(pid);
577 if (index < 0) {
578 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700579 return Status::ok();
Ronghua Wu37c89242015-07-15 12:23:48 -0700580 }
Ronghua Wu37c89242015-07-15 12:23:48 -0700581 ResourceInfos &infos = mMap.editValueAt(index);
Chong Zhangfb092d32019-08-12 09:45:44 -0700582
583 index = infos.indexOfKey(clientId);
584 if (index < 0) {
585 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700586 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700587 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700588
589 const ResourceInfo &info = infos[index];
590 for (auto it = info.resources.begin(); it != info.resources.end(); it++) {
591 onLastRemoved(it->second, info);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700592 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700593
Arun Johnsond1f59732022-03-25 17:10:29 +0000594 removeCookieAndUnlink_l(info.client, info.cookie);
Chong Zhangfb092d32019-08-12 09:45:44 -0700595
Chong Zhanga9d45c72020-09-09 12:41:17 -0700596 if (mObserverService != nullptr && !info.resources.empty()) {
597 mObserverService->onResourceRemoved(info.uid, pid, info.resources);
598 }
599
Chong Zhangfb092d32019-08-12 09:45:44 -0700600 infos.removeItemsAt(index);
Chong Zhang181e6952019-10-09 13:23:39 -0700601 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700602}
603
Brian Lindahl64ee9452022-01-14 13:31:16 +0100604void ResourceManagerService::getClientForResource_l(int callingPid, const MediaResourceParcel *res,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800605 Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700606 if (res == NULL) {
607 return;
608 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800609 std::shared_ptr<IResourceManagerClient> client;
Brian Lindahl64ee9452022-01-14 13:31:16 +0100610 if (getLowestPriorityBiggestClient_l(callingPid, res->type, res->subType, &client)) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700611 clients->push_back(client);
612 }
613}
614
Brian Lindahl64ee9452022-01-14 13:31:16 +0100615Status ResourceManagerService::reclaimResource(int32_t callingPid,
616 const std::vector<MediaResourceParcel>& resources, bool* _aidl_return) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700617 String8 log = String8::format("reclaimResource(callingPid %d, resources %s)",
Ronghua Wu231c3d12015-03-11 15:10:32 -0700618 callingPid, getString(resources).string());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700619 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700620 *_aidl_return = false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700621
Chong Zhangfdd512a2019-11-22 11:03:14 -0800622 Vector<std::shared_ptr<IResourceManagerClient>> clients;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700623 {
624 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100625 if (!mProcessInfo->isPidTrusted(callingPid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800626 pid_t actualCallingPid = IPCThreadState::self()->getCallingPid();
627 ALOGW("%s called with untrusted pid %d, using actual calling pid %d", __FUNCTION__,
628 callingPid, actualCallingPid);
629 callingPid = actualCallingPid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800630 }
Chong Zhang181e6952019-10-09 13:23:39 -0700631 const MediaResourceParcel *secureCodec = NULL;
632 const MediaResourceParcel *nonSecureCodec = NULL;
633 const MediaResourceParcel *graphicMemory = NULL;
634 const MediaResourceParcel *drmSession = NULL;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700635 for (size_t i = 0; i < resources.size(); ++i) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100636 switch (resources[i].type) {
637 case MediaResource::Type::kSecureCodec:
638 secureCodec = &resources[i];
639 break;
640 case MediaResource::Type::kNonSecureCodec:
641 nonSecureCodec = &resources[i];
642 break;
643 case MediaResource::Type::kGraphicMemory:
644 graphicMemory = &resources[i];
645 break;
646 case MediaResource::Type::kDrmSession:
647 drmSession = &resources[i];
648 break;
649 default:
650 break;
Ronghua Wu05d89f12015-07-07 16:47:42 -0700651 }
652 }
653
654 // first pass to handle secure/non-secure codec conflict
655 if (secureCodec != NULL) {
656 if (!mSupportsMultipleSecureCodecs) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100657 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec,
658 secureCodec->subType, &clients)) {
Chong Zhang181e6952019-10-09 13:23:39 -0700659 return Status::ok();
Ronghua Wu05d89f12015-07-07 16:47:42 -0700660 }
661 }
662 if (!mSupportsSecureWithNonSecureCodec) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100663 if (!getAllClients_l(callingPid, MediaResource::Type::kNonSecureCodec,
664 secureCodec->subType, &clients)) {
Chong Zhang181e6952019-10-09 13:23:39 -0700665 return Status::ok();
Ronghua Wu05d89f12015-07-07 16:47:42 -0700666 }
667 }
668 }
669 if (nonSecureCodec != NULL) {
670 if (!mSupportsSecureWithNonSecureCodec) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100671 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec,
672 nonSecureCodec->subType, &clients)) {
Chong Zhang181e6952019-10-09 13:23:39 -0700673 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700674 }
675 }
676 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700677 if (drmSession != NULL) {
678 getClientForResource_l(callingPid, drmSession, &clients);
679 if (clients.size() == 0) {
Chong Zhang181e6952019-10-09 13:23:39 -0700680 return Status::ok();
Robert Shihc3af31b2019-09-20 21:45:01 -0700681 }
682 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700683
684 if (clients.size() == 0) {
685 // if no secure/non-secure codec conflict, run second pass to handle other resources.
Ronghua Wu05d89f12015-07-07 16:47:42 -0700686 getClientForResource_l(callingPid, graphicMemory, &clients);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700687 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700688
689 if (clients.size() == 0) {
690 // if we are here, run the third pass to free one codec with the same type.
Ronghua Wu05d89f12015-07-07 16:47:42 -0700691 getClientForResource_l(callingPid, secureCodec, &clients);
692 getClientForResource_l(callingPid, nonSecureCodec, &clients);
693 }
694
695 if (clients.size() == 0) {
696 // if we are here, run the fourth pass to free one codec with the different type.
697 if (secureCodec != NULL) {
Wonsik Kimb3639012022-03-16 13:57:41 -0700698 MediaResource temp(MediaResource::Type::kNonSecureCodec, secureCodec->subType, 1);
Ronghua Wu05d89f12015-07-07 16:47:42 -0700699 getClientForResource_l(callingPid, &temp, &clients);
700 }
701 if (nonSecureCodec != NULL) {
Wonsik Kimb3639012022-03-16 13:57:41 -0700702 MediaResource temp(MediaResource::Type::kSecureCodec, nonSecureCodec->subType, 1);
Ronghua Wu05d89f12015-07-07 16:47:42 -0700703 getClientForResource_l(callingPid, &temp, &clients);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700704 }
705 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700706 }
707
Brian Lindahl64ee9452022-01-14 13:31:16 +0100708 *_aidl_return = reclaimUnconditionallyFrom(clients);
Wonsik Kim271429d2020-10-01 10:12:56 -0700709 return Status::ok();
710}
711
Brian Lindahl64ee9452022-01-14 13:31:16 +0100712bool ResourceManagerService::reclaimUnconditionallyFrom(
Wonsik Kim271429d2020-10-01 10:12:56 -0700713 const Vector<std::shared_ptr<IResourceManagerClient>> &clients) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700714 if (clients.size() == 0) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700715 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700716 }
717
Chong Zhangfdd512a2019-11-22 11:03:14 -0800718 std::shared_ptr<IResourceManagerClient> failedClient;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700719 for (size_t i = 0; i < clients.size(); ++i) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700720 String8 log = String8::format("reclaimResource from client %p", clients[i].get());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700721 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700722 bool success;
723 Status status = clients[i]->reclaimResource(&success);
724 if (!status.isOk() || !success) {
Ronghua Wu67e7f542015-03-13 10:47:08 -0700725 failedClient = clients[i];
726 break;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700727 }
728 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700729
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700730 if (failedClient == NULL) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700731 return true;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700732 }
733
Brian Lindahl9f626cf2022-04-25 13:29:59 +0200734 int failedClientPid = -1;
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) {
Brian Lindahl9f626cf2022-04-25 13:29:59 +0200749 failedClientPid = mMap.keyAt(i);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700750 break;
751 }
752 }
Brian Lindahl9f626cf2022-04-25 13:29:59 +0200753 if (found) {
754 ALOGW("Failed to reclaim resources from client with pid %d", failedClientPid);
755 } else {
756 ALOGW("Failed to reclaim resources from unlocateable client");
Ronghua Wu67e7f542015-03-13 10:47:08 -0700757 }
758 }
759
Wonsik Kim271429d2020-10-01 10:12:56 -0700760 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700761}
762
Brian Lindahl64ee9452022-01-14 13:31:16 +0100763Status ResourceManagerService::overridePid(int originalPid, int newPid) {
Henry Fang32762922020-01-28 18:40:39 -0800764 String8 log = String8::format("overridePid(originalPid %d, newPid %d)",
765 originalPid, newPid);
766 mServiceLog->add(log);
767
768 // allow if this is called from the same process or the process has
769 // permission.
770 if ((AIBinder_getCallingPid() != getpid()) &&
771 (checkCallingPermission(String16(
772 "android.permission.MEDIA_RESOURCE_OVERRIDE_PID")) == false)) {
773 ALOGE(
774 "Permission Denial: can't access overridePid method from pid=%d, "
775 "self pid=%d\n",
776 AIBinder_getCallingPid(), getpid());
777 return Status::fromServiceSpecificError(PERMISSION_DENIED);
778 }
779
780 {
781 Mutex::Autolock lock(mLock);
782 mOverridePidMap.erase(originalPid);
783 if (newPid != -1) {
784 mOverridePidMap.emplace(originalPid, newPid);
785 }
786 }
787
788 return Status::ok();
789}
790
Chong Zhang97d367b2020-09-16 12:53:14 -0700791Status ResourceManagerService::overrideProcessInfo(
Brian Lindahl64ee9452022-01-14 13:31:16 +0100792 const std::shared_ptr<IResourceManagerClient>& client, int pid, int procState,
Chong Zhang97d367b2020-09-16 12:53:14 -0700793 int oomScore) {
794 String8 log = String8::format("overrideProcessInfo(pid %d, procState %d, oomScore %d)",
795 pid, procState, oomScore);
796 mServiceLog->add(log);
797
798 // Only allow the override if the caller already can access process state and oom scores.
799 int callingPid = AIBinder_getCallingPid();
800 if (callingPid != getpid() && (callingPid != pid || !checkCallingPermission(String16(
801 "android.permission.GET_PROCESS_STATE_AND_OOM_SCORE")))) {
802 ALOGE("Permission Denial: overrideProcessInfo method from pid=%d", callingPid);
803 return Status::fromServiceSpecificError(PERMISSION_DENIED);
804 }
805
806 if (client == nullptr) {
807 return Status::fromServiceSpecificError(BAD_VALUE);
808 }
809
810 Mutex::Autolock lock(mLock);
811 removeProcessInfoOverride_l(pid);
812
813 if (!mProcessInfo->overrideProcessInfo(pid, procState, oomScore)) {
814 // Override value is rejected by ProcessInfo.
815 return Status::fromServiceSpecificError(BAD_VALUE);
816 }
817
Arun Johnsond1f59732022-03-25 17:10:29 +0000818 uintptr_t cookie = addCookieAndLink_l(client,
Chong Zhang97d367b2020-09-16 12:53:14 -0700819 new OverrideProcessInfoDeathNotifier(ref<ResourceManagerService>(), pid));
820
821 mProcessInfoOverrideMap.emplace(pid, ProcessInfoOverride{cookie, client});
822
823 return Status::ok();
824}
825
Arun Johnsond1f59732022-03-25 17:10:29 +0000826uintptr_t ResourceManagerService::addCookieAndLink_l(
827 const std::shared_ptr<IResourceManagerClient>& client, const sp<DeathNotifier>& notifier) {
828 if (client == nullptr) {
829 return 0;
830 }
Chong Zhang97d367b2020-09-16 12:53:14 -0700831 std::scoped_lock lock{sCookieLock};
832
833 uintptr_t cookie;
834 // Need to skip cookie 0 (if it wraps around). ResourceInfo has cookie initialized to 0
835 // indicating the death notifier is not created yet.
836 while ((cookie = ++sCookieCounter) == 0);
Arun Johnsond1f59732022-03-25 17:10:29 +0000837 AIBinder_linkToDeath(client->asBinder().get(), mDeathRecipient.get(), (void*)cookie);
Chong Zhang97d367b2020-09-16 12:53:14 -0700838 sCookieToDeathNotifierMap.emplace(cookie, notifier);
839
840 return cookie;
841}
842
Arun Johnsond1f59732022-03-25 17:10:29 +0000843void ResourceManagerService::removeCookieAndUnlink_l(
844 const std::shared_ptr<IResourceManagerClient>& client, uintptr_t cookie) {
Chong Zhang97d367b2020-09-16 12:53:14 -0700845 std::scoped_lock lock{sCookieLock};
Arun Johnsond1f59732022-03-25 17:10:29 +0000846 if (client != nullptr) {
847 AIBinder_unlinkToDeath(client->asBinder().get(), mDeathRecipient.get(), (void*)cookie);
848 }
Chong Zhang97d367b2020-09-16 12:53:14 -0700849 sCookieToDeathNotifierMap.erase(cookie);
850}
851
852void ResourceManagerService::removeProcessInfoOverride(int pid) {
853 Mutex::Autolock lock(mLock);
854
855 removeProcessInfoOverride_l(pid);
856}
857
858void ResourceManagerService::removeProcessInfoOverride_l(int pid) {
859 auto it = mProcessInfoOverrideMap.find(pid);
860 if (it == mProcessInfoOverrideMap.end()) {
861 return;
862 }
863
864 mProcessInfo->removeProcessInfoOverride(pid);
865
Arun Johnsond1f59732022-03-25 17:10:29 +0000866 removeCookieAndUnlink_l(it->second.client, it->second.cookie);
Chong Zhang97d367b2020-09-16 12:53:14 -0700867
868 mProcessInfoOverrideMap.erase(pid);
869}
870
Wonsik Kimd20e9362020-04-28 10:42:57 -0700871Status ResourceManagerService::markClientForPendingRemoval(int32_t pid, int64_t clientId) {
872 String8 log = String8::format(
873 "markClientForPendingRemoval(pid %d, clientId %lld)",
874 pid, (long long) clientId);
875 mServiceLog->add(log);
876
877 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100878 if (!mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800879 pid_t callingPid = IPCThreadState::self()->getCallingPid();
880 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
881 pid, callingPid);
882 pid = callingPid;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700883 }
884 ssize_t index = mMap.indexOfKey(pid);
885 if (index < 0) {
886 ALOGV("markClientForPendingRemoval: didn't find pid %d for clientId %lld",
887 pid, (long long)clientId);
888 return Status::ok();
889 }
890 ResourceInfos &infos = mMap.editValueAt(index);
891
892 index = infos.indexOfKey(clientId);
893 if (index < 0) {
894 ALOGV("markClientForPendingRemoval: didn't find clientId %lld", (long long) clientId);
895 return Status::ok();
896 }
897
898 ResourceInfo &info = infos.editValueAt(index);
899 info.pendingRemoval = true;
900 return Status::ok();
901}
902
Wonsik Kim271429d2020-10-01 10:12:56 -0700903Status ResourceManagerService::reclaimResourcesFromClientsPendingRemoval(int32_t pid) {
904 String8 log = String8::format("reclaimResourcesFromClientsPendingRemoval(pid %d)", pid);
905 mServiceLog->add(log);
906
907 Vector<std::shared_ptr<IResourceManagerClient>> clients;
908 {
909 Mutex::Autolock lock(mLock);
Brian Lindahlcf3bafb2022-01-27 14:21:38 +0100910 if (!mProcessInfo->isPidTrusted(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800911 pid_t callingPid = IPCThreadState::self()->getCallingPid();
912 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
913 pid, callingPid);
914 pid = callingPid;
Wonsik Kim271429d2020-10-01 10:12:56 -0700915 }
916
917 for (MediaResource::Type type : {MediaResource::Type::kSecureCodec,
918 MediaResource::Type::kNonSecureCodec,
919 MediaResource::Type::kGraphicMemory,
920 MediaResource::Type::kDrmSession}) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100921 switch (type) {
922 // Codec resources are segregated by audio, video and image domains.
923 case MediaResource::Type::kSecureCodec:
924 case MediaResource::Type::kNonSecureCodec:
925 for (MediaResource::SubType subType : {MediaResource::SubType::kAudioCodec,
926 MediaResource::SubType::kVideoCodec,
927 MediaResource::SubType::kImageCodec}) {
928 std::shared_ptr<IResourceManagerClient> client;
929 if (getBiggestClientPendingRemoval_l(pid, type, subType, &client)) {
930 clients.add(client);
931 continue;
932 }
933 }
934 break;
935 // Non-codec resources are shared by audio, video and image codecs (no subtype).
936 default:
937 std::shared_ptr<IResourceManagerClient> client;
938 if (getBiggestClientPendingRemoval_l(pid, type,
939 MediaResource::SubType::kUnspecifiedSubType, &client)) {
940 clients.add(client);
941 }
942 break;
Wonsik Kim271429d2020-10-01 10:12:56 -0700943 }
944 }
945 }
946
947 if (!clients.empty()) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100948 reclaimUnconditionallyFrom(clients);
Wonsik Kim271429d2020-10-01 10:12:56 -0700949 }
950 return Status::ok();
951}
952
Henry Fang32762922020-01-28 18:40:39 -0800953bool ResourceManagerService::getPriority_l(int pid, int* priority) {
954 int newPid = pid;
955
956 if (mOverridePidMap.find(pid) != mOverridePidMap.end()) {
957 newPid = mOverridePidMap[pid];
958 ALOGD("getPriority_l: use override pid %d instead original pid %d",
959 newPid, pid);
960 }
961
962 return mProcessInfo->getPriority(newPid, priority);
963}
964
Brian Lindahl64ee9452022-01-14 13:31:16 +0100965bool ResourceManagerService::getAllClients_l(int callingPid, MediaResource::Type type,
966 MediaResource::SubType subType, Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800967 Vector<std::shared_ptr<IResourceManagerClient>> temp;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700968 for (size_t i = 0; i < mMap.size(); ++i) {
969 ResourceInfos &infos = mMap.editValueAt(i);
970 for (size_t j = 0; j < infos.size(); ++j) {
Brian Lindahl64ee9452022-01-14 13:31:16 +0100971 if (hasResourceType(type, subType, infos[j].resources)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700972 if (!isCallingPriorityHigher_l(callingPid, mMap.keyAt(i))) {
973 // some higher/equal priority process owns the resource,
974 // this request can't be fulfilled.
975 ALOGE("getAllClients_l: can't reclaim resource %s from pid %d",
Ronghua Wuea15fd22016-03-03 13:35:05 -0800976 asString(type), mMap.keyAt(i));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700977 return false;
978 }
979 temp.push_back(infos[j].client);
980 }
981 }
982 }
983 if (temp.size() == 0) {
Ronghua Wuea15fd22016-03-03 13:35:05 -0800984 ALOGV("getAllClients_l: didn't find any resource %s", asString(type));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700985 return true;
986 }
987 clients->appendVector(temp);
988 return true;
989}
990
Brian Lindahl64ee9452022-01-14 13:31:16 +0100991bool ResourceManagerService::getLowestPriorityBiggestClient_l(int callingPid,
992 MediaResource::Type type, MediaResource::SubType subType,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800993 std::shared_ptr<IResourceManagerClient> *client) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700994 int lowestPriorityPid;
995 int lowestPriority;
996 int callingPriority;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700997
998 // Before looking into other processes, check if we have clients marked for
999 // pending removal in the same process.
Brian Lindahl64ee9452022-01-14 13:31:16 +01001000 if (getBiggestClientPendingRemoval_l(callingPid, type, subType, client)) {
Wonsik Kimd20e9362020-04-28 10:42:57 -07001001 return true;
1002 }
Henry Fang32762922020-01-28 18:40:39 -08001003 if (!getPriority_l(callingPid, &callingPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001004 ALOGE("getLowestPriorityBiggestClient_l: can't get process priority for pid %d",
1005 callingPid);
1006 return false;
1007 }
Brian Lindahl64ee9452022-01-14 13:31:16 +01001008 if (!getLowestPriorityPid_l(type, subType, &lowestPriorityPid, &lowestPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001009 return false;
1010 }
1011 if (lowestPriority <= callingPriority) {
1012 ALOGE("getLowestPriorityBiggestClient_l: lowest priority %d vs caller priority %d",
1013 lowestPriority, callingPriority);
1014 return false;
1015 }
1016
Brian Lindahl64ee9452022-01-14 13:31:16 +01001017 if (!getBiggestClient_l(lowestPriorityPid, type, subType, client)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001018 return false;
1019 }
1020 return true;
1021}
1022
Brian Lindahl64ee9452022-01-14 13:31:16 +01001023bool ResourceManagerService::getLowestPriorityPid_l(MediaResource::Type type,
1024 MediaResource::SubType subType, int *lowestPriorityPid, int *lowestPriority) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001025 int pid = -1;
1026 int priority = -1;
1027 for (size_t i = 0; i < mMap.size(); ++i) {
1028 if (mMap.valueAt(i).size() == 0) {
1029 // no client on this process.
1030 continue;
1031 }
Brian Lindahl64ee9452022-01-14 13:31:16 +01001032 if (!hasResourceType(type, subType, mMap.valueAt(i))) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001033 // doesn't have the requested resource type
1034 continue;
1035 }
1036 int tempPid = mMap.keyAt(i);
1037 int tempPriority;
Henry Fang32762922020-01-28 18:40:39 -08001038 if (!getPriority_l(tempPid, &tempPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001039 ALOGV("getLowestPriorityPid_l: can't get priority of pid %d, skipped", tempPid);
1040 // TODO: remove this pid from mMap?
1041 continue;
1042 }
1043 if (pid == -1 || tempPriority > priority) {
1044 // initial the value
1045 pid = tempPid;
1046 priority = tempPriority;
1047 }
1048 }
1049 if (pid != -1) {
1050 *lowestPriorityPid = pid;
1051 *lowestPriority = priority;
1052 }
1053 return (pid != -1);
1054}
1055
1056bool ResourceManagerService::isCallingPriorityHigher_l(int callingPid, int pid) {
1057 int callingPidPriority;
Henry Fang32762922020-01-28 18:40:39 -08001058 if (!getPriority_l(callingPid, &callingPidPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001059 return false;
1060 }
1061
1062 int priority;
Henry Fang32762922020-01-28 18:40:39 -08001063 if (!getPriority_l(pid, &priority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001064 return false;
1065 }
1066
1067 return (callingPidPriority < priority);
1068}
1069
Brian Lindahl64ee9452022-01-14 13:31:16 +01001070bool ResourceManagerService::getBiggestClientPendingRemoval_l(int pid, MediaResource::Type type,
1071 MediaResource::SubType subType, std::shared_ptr<IResourceManagerClient> *client) {
1072 return getBiggestClient_l(pid, type, subType, client, true /* pendingRemovalOnly */);
1073}
1074
1075bool ResourceManagerService::getBiggestClient_l(int pid, MediaResource::Type type,
1076 MediaResource::SubType subType, std::shared_ptr<IResourceManagerClient> *client,
Wonsik Kimd20e9362020-04-28 10:42:57 -07001077 bool pendingRemovalOnly) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001078 ssize_t index = mMap.indexOfKey(pid);
1079 if (index < 0) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001080 ALOGE_IF(!pendingRemovalOnly,
1081 "getBiggestClient_l: can't find resource info for pid %d", pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001082 return false;
1083 }
1084
Chong Zhangfdd512a2019-11-22 11:03:14 -08001085 std::shared_ptr<IResourceManagerClient> clientTemp;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001086 uint64_t largestValue = 0;
1087 const ResourceInfos &infos = mMap.valueAt(index);
1088 for (size_t i = 0; i < infos.size(); ++i) {
Chong Zhangfb092d32019-08-12 09:45:44 -07001089 const ResourceList &resources = infos[i].resources;
Wonsik Kimd20e9362020-04-28 10:42:57 -07001090 if (pendingRemovalOnly && !infos[i].pendingRemoval) {
1091 continue;
1092 }
Chong Zhangfb092d32019-08-12 09:45:44 -07001093 for (auto it = resources.begin(); it != resources.end(); it++) {
Chong Zhang181e6952019-10-09 13:23:39 -07001094 const MediaResourceParcel &resource = it->second;
Brian Lindahl64ee9452022-01-14 13:31:16 +01001095 if (hasResourceType(type, subType, resource)) {
Chong Zhang181e6952019-10-09 13:23:39 -07001096 if (resource.value > largestValue) {
1097 largestValue = resource.value;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001098 clientTemp = infos[i].client;
1099 }
1100 }
1101 }
1102 }
1103
1104 if (clientTemp == NULL) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001105 ALOGE_IF(!pendingRemovalOnly,
Brian Lindahl64ee9452022-01-14 13:31:16 +01001106 "getBiggestClient_l: can't find resource type %s and subtype %s for pid %d",
1107 asString(type), asString(subType), pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001108 return false;
1109 }
1110
1111 *client = clientTemp;
1112 return true;
1113}
1114
Ronghua Wu231c3d12015-03-11 15:10:32 -07001115} // namespace android