blob: 289cffd2c56af0d78796f9fbd8970d94cf77506f [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>
Dongwon Kangfe508d32015-12-15 14:22:05 +090024#include <binder/IMediaResourceMonitor.h>
Chong Zhangc7303e82020-12-02 16:38:52 -080025#include <binder/IPCThreadState.h>
Ronghua Wu231c3d12015-03-11 15:10:32 -070026#include <binder/IServiceManager.h>
Chong Zhangee33d642019-08-08 14:26:43 -070027#include <cutils/sched_policy.h>
Ronghua Wu231c3d12015-03-11 15:10:32 -070028#include <dirent.h>
Chong Zhang181e6952019-10-09 13:23:39 -070029#include <media/MediaResourcePolicy.h>
Ronghua Wu231c3d12015-03-11 15:10:32 -070030#include <media/stagefright/ProcessInfo.h>
Chong Zhangee33d642019-08-08 14:26:43 -070031#include <mediautils/BatteryNotifier.h>
32#include <mediautils/SchedulingPolicyService.h>
Ronghua Wu231c3d12015-03-11 15:10:32 -070033#include <string.h>
34#include <sys/types.h>
35#include <sys/stat.h>
36#include <sys/time.h>
37#include <unistd.h>
38
39#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:
54 DeathNotifier(const std::shared_ptr<ResourceManagerService> &service,
55 int pid, int64_t clientId);
56
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
Chong Zhangfb092d32019-08-12 09:45:44 -0700133static bool hasResourceType(MediaResource::Type type, const ResourceList& resources) {
134 for (auto it = resources.begin(); it != resources.end(); it++) {
Chong Zhang181e6952019-10-09 13:23:39 -0700135 if (it->second.type == type) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700136 return true;
137 }
138 }
139 return false;
140}
141
Chih-Hung Hsieh51873d82016-08-09 14:18:51 -0700142static bool hasResourceType(MediaResource::Type type, const ResourceInfos& infos) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700143 for (size_t i = 0; i < infos.size(); ++i) {
144 if (hasResourceType(type, infos[i].resources)) {
145 return true;
146 }
147 }
148 return false;
149}
150
151static ResourceInfos& getResourceInfosForEdit(
152 int pid,
153 PidResourceInfosMap& map) {
154 ssize_t index = map.indexOfKey(pid);
155 if (index < 0) {
156 // new pid
157 ResourceInfos infosForPid;
158 map.add(pid, infosForPid);
159 }
160
161 return map.editValueFor(pid);
162}
163
164static ResourceInfo& getResourceInfoForEdit(
Chong Zhangee33d642019-08-08 14:26:43 -0700165 uid_t uid,
Ronghua Wu231c3d12015-03-11 15:10:32 -0700166 int64_t clientId,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800167 const std::shared_ptr<IResourceManagerClient>& client,
Ronghua Wu231c3d12015-03-11 15:10:32 -0700168 ResourceInfos& infos) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700169 ssize_t index = infos.indexOfKey(clientId);
170
171 if (index < 0) {
172 ResourceInfo info;
173 info.uid = uid;
174 info.clientId = clientId;
175 info.client = client;
Chong Zhang97d367b2020-09-16 12:53:14 -0700176 info.cookie = 0;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700177 info.pendingRemoval = false;
Chong Zhangfb092d32019-08-12 09:45:44 -0700178
179 index = infos.add(clientId, info);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700180 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700181
182 return infos.editValueAt(index);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700183}
184
Chong Zhang181e6952019-10-09 13:23:39 -0700185static void notifyResourceGranted(int pid, const std::vector<MediaResourceParcel> &resources) {
Dongwon Kangfe508d32015-12-15 14:22:05 +0900186 static const char* const kServiceName = "media_resource_monitor";
Dongwon Kang2642c842016-03-23 18:07:29 -0700187 sp<IBinder> binder = defaultServiceManager()->checkService(String16(kServiceName));
Dongwon Kangfe508d32015-12-15 14:22:05 +0900188 if (binder != NULL) {
189 sp<IMediaResourceMonitor> service = interface_cast<IMediaResourceMonitor>(binder);
190 for (size_t i = 0; i < resources.size(); ++i) {
Chong Zhang181e6952019-10-09 13:23:39 -0700191 if (resources[i].subType == MediaResource::SubType::kAudioCodec) {
Dongwon Kang69c23dd2016-03-22 15:22:45 -0700192 service->notifyResourceGranted(pid, IMediaResourceMonitor::TYPE_AUDIO_CODEC);
Chong Zhang181e6952019-10-09 13:23:39 -0700193 } else if (resources[i].subType == MediaResource::SubType::kVideoCodec) {
Dongwon Kang69c23dd2016-03-22 15:22:45 -0700194 service->notifyResourceGranted(pid, IMediaResourceMonitor::TYPE_VIDEO_CODEC);
195 }
Dongwon Kangfe508d32015-12-15 14:22:05 +0900196 }
197 }
198}
199
Chong Zhangfdd512a2019-11-22 11:03:14 -0800200binder_status_t ResourceManagerService::dump(
201 int fd, const char** /*args*/, uint32_t /*numArgs*/) {
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700202 String8 result;
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700203
dcashman014e91e2015-09-11 09:33:01 -0700204 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
205 result.format("Permission Denial: "
206 "can't dump ResourceManagerService from pid=%d, uid=%d\n",
Chong Zhangfdd512a2019-11-22 11:03:14 -0800207 AIBinder_getCallingPid(),
208 AIBinder_getCallingUid());
dcashman014e91e2015-09-11 09:33:01 -0700209 write(fd, result.string(), result.size());
210 return PERMISSION_DENIED;
211 }
212
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700213 PidResourceInfosMap mapCopy;
214 bool supportsMultipleSecureCodecs;
215 bool supportsSecureWithNonSecureCodec;
Henry Fang32762922020-01-28 18:40:39 -0800216 std::map<int, int> overridePidMapCopy;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700217 String8 serviceLog;
218 {
219 Mutex::Autolock lock(mLock);
220 mapCopy = mMap; // Shadow copy, real copy will happen on write.
221 supportsMultipleSecureCodecs = mSupportsMultipleSecureCodecs;
222 supportsSecureWithNonSecureCodec = mSupportsSecureWithNonSecureCodec;
223 serviceLog = mServiceLog->toString(" " /* linePrefix */);
Henry Fang32762922020-01-28 18:40:39 -0800224 overridePidMapCopy = mOverridePidMap;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700225 }
226
227 const size_t SIZE = 256;
228 char buffer[SIZE];
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700229 snprintf(buffer, SIZE, "ResourceManagerService: %p\n", this);
230 result.append(buffer);
231 result.append(" Policies:\n");
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700232 snprintf(buffer, SIZE, " SupportsMultipleSecureCodecs: %d\n", supportsMultipleSecureCodecs);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700233 result.append(buffer);
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700234 snprintf(buffer, SIZE, " SupportsSecureWithNonSecureCodec: %d\n",
235 supportsSecureWithNonSecureCodec);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700236 result.append(buffer);
237
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700238 result.append(" Processes:\n");
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700239 for (size_t i = 0; i < mapCopy.size(); ++i) {
240 snprintf(buffer, SIZE, " Pid: %d\n", mapCopy.keyAt(i));
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700241 result.append(buffer);
242
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700243 const ResourceInfos &infos = mapCopy.valueAt(i);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700244 for (size_t j = 0; j < infos.size(); ++j) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700245 result.append(" Client:\n");
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700246 snprintf(buffer, SIZE, " Id: %lld\n", (long long)infos[j].clientId);
247 result.append(buffer);
248
Chong Zhang181e6952019-10-09 13:23:39 -0700249 std::string clientName;
250 Status status = infos[j].client->getName(&clientName);
251 if (!status.isOk()) {
252 clientName = "<unknown client>";
253 }
254 snprintf(buffer, SIZE, " Name: %s\n", clientName.c_str());
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700255 result.append(buffer);
256
Chong Zhangfb092d32019-08-12 09:45:44 -0700257 const ResourceList &resources = infos[j].resources;
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700258 result.append(" Resources:\n");
Chong Zhangfb092d32019-08-12 09:45:44 -0700259 for (auto it = resources.begin(); it != resources.end(); it++) {
Chong Zhang181e6952019-10-09 13:23:39 -0700260 snprintf(buffer, SIZE, " %s\n", toString(it->second).string());
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700261 result.append(buffer);
262 }
263 }
264 }
Henry Fang32762922020-01-28 18:40:39 -0800265 result.append(" Process Pid override:\n");
266 for (auto it = overridePidMapCopy.begin(); it != overridePidMapCopy.end(); ++it) {
267 snprintf(buffer, SIZE, " Original Pid: %d, Override Pid: %d\n",
268 it->first, it->second);
269 result.append(buffer);
270 }
Ronghua Wu022ed722015-05-11 15:15:09 -0700271 result.append(" Events logs (most recent at top):\n");
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700272 result.append(serviceLog);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700273
274 write(fd, result.string(), result.size());
275 return OK;
276}
277
Chong Zhangdd726802019-08-21 17:24:13 -0700278struct SystemCallbackImpl :
279 public ResourceManagerService::SystemCallbackInterface {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800280 SystemCallbackImpl() : mClientToken(new BBinder()) {}
Ronghua Wu231c3d12015-03-11 15:10:32 -0700281
Chong Zhangdd726802019-08-21 17:24:13 -0700282 virtual void noteStartVideo(int uid) override {
283 BatteryNotifier::getInstance().noteStartVideo(uid);
284 }
285 virtual void noteStopVideo(int uid) override {
286 BatteryNotifier::getInstance().noteStopVideo(uid);
287 }
288 virtual void noteResetVideo() override {
289 BatteryNotifier::getInstance().noteResetVideo();
290 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800291 virtual bool requestCpusetBoost(bool enable) override {
292 return android::requestCpusetBoost(enable, mClientToken);
Chong Zhangdd726802019-08-21 17:24:13 -0700293 }
294
295protected:
296 virtual ~SystemCallbackImpl() {}
297
298private:
299 DISALLOW_EVIL_CONSTRUCTORS(SystemCallbackImpl);
Chong Zhangfdd512a2019-11-22 11:03:14 -0800300 sp<IBinder> mClientToken;
Chong Zhangdd726802019-08-21 17:24:13 -0700301};
302
303ResourceManagerService::ResourceManagerService()
304 : ResourceManagerService(new ProcessInfo(), new SystemCallbackImpl()) {}
305
306ResourceManagerService::ResourceManagerService(
307 const sp<ProcessInfoInterface> &processInfo,
308 const sp<SystemCallbackInterface> &systemResource)
Ronghua Wu231c3d12015-03-11 15:10:32 -0700309 : mProcessInfo(processInfo),
Chong Zhangdd726802019-08-21 17:24:13 -0700310 mSystemCB(systemResource),
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700311 mServiceLog(new ServiceLog()),
Ronghua Wu231c3d12015-03-11 15:10:32 -0700312 mSupportsMultipleSecureCodecs(true),
Chong Zhang79d2b282018-04-17 14:14:31 -0700313 mSupportsSecureWithNonSecureCodec(true),
Chong Zhangfdd512a2019-11-22 11:03:14 -0800314 mCpuBoostCount(0),
315 mDeathRecipient(AIBinder_DeathRecipient_new(DeathNotifier::BinderDiedCallback)) {
Chong Zhangdd726802019-08-21 17:24:13 -0700316 mSystemCB->noteResetVideo();
Chong Zhangee33d642019-08-08 14:26:43 -0700317}
Ronghua Wu231c3d12015-03-11 15:10:32 -0700318
Chong Zhangfdd512a2019-11-22 11:03:14 -0800319//static
320void ResourceManagerService::instantiate() {
321 std::shared_ptr<ResourceManagerService> service =
322 ::ndk::SharedRefBase::make<ResourceManagerService>();
323 binder_status_t status =
324 AServiceManager_addService(service->asBinder().get(), getServiceName());
325 if (status != STATUS_OK) {
326 return;
327 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700328
329 std::shared_ptr<ResourceObserverService> observerService =
330 ResourceObserverService::instantiate();
331
332 if (observerService != nullptr) {
333 service->setObserverService(observerService);
334 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800335 // TODO: mediaserver main() is already starting the thread pool,
336 // move this to mediaserver main() when other services in mediaserver
337 // are converted to ndk-platform aidl.
338 //ABinderProcess_startThreadPool();
339}
340
Ronghua Wu231c3d12015-03-11 15:10:32 -0700341ResourceManagerService::~ResourceManagerService() {}
342
Chong Zhanga9d45c72020-09-09 12:41:17 -0700343void ResourceManagerService::setObserverService(
344 const std::shared_ptr<ResourceObserverService>& observerService) {
345 mObserverService = observerService;
346}
347
Chong Zhang181e6952019-10-09 13:23:39 -0700348Status ResourceManagerService::config(const std::vector<MediaResourcePolicyParcel>& policies) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700349 String8 log = String8::format("config(%s)", getString(policies).string());
350 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700351
352 Mutex::Autolock lock(mLock);
353 for (size_t i = 0; i < policies.size(); ++i) {
Chong Zhang181e6952019-10-09 13:23:39 -0700354 const std::string &type = policies[i].type;
355 const std::string &value = policies[i].value;
356 if (type == MediaResourcePolicy::kPolicySupportsMultipleSecureCodecs()) {
Ronghua Wu9ba21b92015-04-21 14:23:06 -0700357 mSupportsMultipleSecureCodecs = (value == "true");
Chong Zhang181e6952019-10-09 13:23:39 -0700358 } else if (type == MediaResourcePolicy::kPolicySupportsSecureWithNonSecureCodec()) {
Ronghua Wu9ba21b92015-04-21 14:23:06 -0700359 mSupportsSecureWithNonSecureCodec = (value == "true");
Ronghua Wu231c3d12015-03-11 15:10:32 -0700360 }
361 }
Chong Zhang181e6952019-10-09 13:23:39 -0700362 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700363}
364
Chong Zhangfb092d32019-08-12 09:45:44 -0700365void ResourceManagerService::onFirstAdded(
Chong Zhang181e6952019-10-09 13:23:39 -0700366 const MediaResourceParcel& resource, const ResourceInfo& clientInfo) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700367 // first time added
Chong Zhang181e6952019-10-09 13:23:39 -0700368 if (resource.type == MediaResource::Type::kCpuBoost
369 && resource.subType == MediaResource::SubType::kUnspecifiedSubType) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700370 // Request it on every new instance of kCpuBoost, as the media.codec
371 // could have died, if we only do it the first time subsequent instances
372 // never gets the boost.
Chong Zhangfdd512a2019-11-22 11:03:14 -0800373 if (mSystemCB->requestCpusetBoost(true) != OK) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700374 ALOGW("couldn't request cpuset boost");
375 }
376 mCpuBoostCount++;
Chong Zhang181e6952019-10-09 13:23:39 -0700377 } else if (resource.type == MediaResource::Type::kBattery
378 && resource.subType == MediaResource::SubType::kVideoCodec) {
Chong Zhangdd726802019-08-21 17:24:13 -0700379 mSystemCB->noteStartVideo(clientInfo.uid);
Chong Zhangfb092d32019-08-12 09:45:44 -0700380 }
381}
382
383void ResourceManagerService::onLastRemoved(
Chong Zhang181e6952019-10-09 13:23:39 -0700384 const MediaResourceParcel& resource, const ResourceInfo& clientInfo) {
385 if (resource.type == MediaResource::Type::kCpuBoost
386 && resource.subType == MediaResource::SubType::kUnspecifiedSubType
Chong Zhangfb092d32019-08-12 09:45:44 -0700387 && mCpuBoostCount > 0) {
388 if (--mCpuBoostCount == 0) {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800389 mSystemCB->requestCpusetBoost(false);
Chong Zhangfb092d32019-08-12 09:45:44 -0700390 }
Chong Zhang181e6952019-10-09 13:23:39 -0700391 } else if (resource.type == MediaResource::Type::kBattery
392 && resource.subType == MediaResource::SubType::kVideoCodec) {
Chong Zhangdd726802019-08-21 17:24:13 -0700393 mSystemCB->noteStopVideo(clientInfo.uid);
Chong Zhangfb092d32019-08-12 09:45:44 -0700394 }
395}
396
Robert Shihc3af31b2019-09-20 21:45:01 -0700397void ResourceManagerService::mergeResources(
Chong Zhang181e6952019-10-09 13:23:39 -0700398 MediaResourceParcel& r1, const MediaResourceParcel& r2) {
399 // The resource entry on record is maintained to be in [0,INT64_MAX].
400 // Clamp if merging in the new resource value causes it to go out of bound.
401 // Note that the new resource value could be negative, eg.DrmSession, the
402 // value goes lower when the session is used more often. During reclaim
403 // the session with the highest value (lowest usage) would be closed.
404 if (r2.value < INT64_MAX - r1.value) {
405 r1.value += r2.value;
406 if (r1.value < 0) {
407 r1.value = 0;
408 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700409 } else {
Chong Zhang181e6952019-10-09 13:23:39 -0700410 r1.value = INT64_MAX;
Robert Shihc3af31b2019-09-20 21:45:01 -0700411 }
412}
413
Chong Zhang181e6952019-10-09 13:23:39 -0700414Status ResourceManagerService::addResource(
415 int32_t pid,
416 int32_t uid,
Ronghua Wu231c3d12015-03-11 15:10:32 -0700417 int64_t clientId,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800418 const std::shared_ptr<IResourceManagerClient>& client,
Chong Zhang181e6952019-10-09 13:23:39 -0700419 const std::vector<MediaResourceParcel>& resources) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700420 String8 log = String8::format("addResource(pid %d, clientId %lld, resources %s)",
Ronghua Wu231c3d12015-03-11 15:10:32 -0700421 pid, (long long) clientId, getString(resources).string());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700422 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700423
424 Mutex::Autolock lock(mLock);
Ronghua Wud11c43a2016-01-27 16:26:12 -0800425 if (!mProcessInfo->isValidPid(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800426 pid_t callingPid = IPCThreadState::self()->getCallingPid();
427 uid_t callingUid = IPCThreadState::self()->getCallingUid();
428 ALOGW("%s called with untrusted pid %d, using calling pid %d, uid %d", __FUNCTION__,
429 pid, callingPid, callingUid);
430 pid = callingPid;
431 uid = callingUid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800432 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700433 ResourceInfos& infos = getResourceInfosForEdit(pid, mMap);
Chong Zhangee33d642019-08-08 14:26:43 -0700434 ResourceInfo& info = getResourceInfoForEdit(uid, clientId, client, infos);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700435 ResourceList resourceAdded;
Chong Zhang79d2b282018-04-17 14:14:31 -0700436
437 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700438 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700439 const auto resType = std::tuple(res.type, res.subType, res.id);
440
441 if (res.value < 0 && res.type != MediaResource::Type::kDrmSession) {
442 ALOGW("Ignoring request to remove negative value of non-drm resource");
443 continue;
444 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700445 if (info.resources.find(resType) == info.resources.end()) {
Chong Zhang181e6952019-10-09 13:23:39 -0700446 if (res.value <= 0) {
447 // We can't init a new entry with negative value, although it's allowed
448 // to merge in negative values after the initial add.
449 ALOGW("Ignoring request to add new resource entry with value <= 0");
450 continue;
451 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700452 onFirstAdded(res, info);
453 info.resources[resType] = res;
Chong Zhangfb092d32019-08-12 09:45:44 -0700454 } else {
Robert Shihc3af31b2019-09-20 21:45:01 -0700455 mergeResources(info.resources[resType], res);
Chong Zhang79d2b282018-04-17 14:14:31 -0700456 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700457 // Add it to the list of added resources for observers.
458 auto it = resourceAdded.find(resType);
459 if (it == resourceAdded.end()) {
460 resourceAdded[resType] = res;
461 } else {
462 mergeResources(it->second, res);
463 }
Chong Zhang79d2b282018-04-17 14:14:31 -0700464 }
Chong Zhang97d367b2020-09-16 12:53:14 -0700465 if (info.cookie == 0 && client != nullptr) {
466 info.cookie = addCookieAndLink_l(client->asBinder(),
467 new DeathNotifier(ref<ResourceManagerService>(), pid, clientId));
Wonsik Kim3e378962017-01-05 17:00:02 +0900468 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700469 if (mObserverService != nullptr && !resourceAdded.empty()) {
470 mObserverService->onResourceAdded(uid, pid, resourceAdded);
471 }
Dongwon Kangfe508d32015-12-15 14:22:05 +0900472 notifyResourceGranted(pid, resources);
Chong Zhang181e6952019-10-09 13:23:39 -0700473 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700474}
475
Chong Zhang181e6952019-10-09 13:23:39 -0700476Status ResourceManagerService::removeResource(
477 int32_t pid, int64_t clientId,
478 const std::vector<MediaResourceParcel>& resources) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700479 String8 log = String8::format("removeResource(pid %d, clientId %lld, resources %s)",
480 pid, (long long) clientId, getString(resources).string());
481 mServiceLog->add(log);
482
483 Mutex::Autolock lock(mLock);
484 if (!mProcessInfo->isValidPid(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800485 pid_t callingPid = IPCThreadState::self()->getCallingPid();
486 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
487 pid, callingPid);
488 pid = callingPid;
Chong Zhangfb092d32019-08-12 09:45:44 -0700489 }
490 ssize_t index = mMap.indexOfKey(pid);
491 if (index < 0) {
492 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700493 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700494 }
495 ResourceInfos &infos = mMap.editValueAt(index);
496
497 index = infos.indexOfKey(clientId);
498 if (index < 0) {
499 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700500 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700501 }
502
503 ResourceInfo &info = infos.editValueAt(index);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700504 ResourceList resourceRemoved;
Chong Zhangfb092d32019-08-12 09:45:44 -0700505 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700506 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700507 const auto resType = std::tuple(res.type, res.subType, res.id);
508
509 if (res.value < 0) {
510 ALOGW("Ignoring request to remove negative value of resource");
511 continue;
512 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700513 // ignore if we don't have it
514 if (info.resources.find(resType) != info.resources.end()) {
Chong Zhang181e6952019-10-09 13:23:39 -0700515 MediaResourceParcel &resource = info.resources[resType];
Chong Zhanga9d45c72020-09-09 12:41:17 -0700516 MediaResourceParcel actualRemoved = res;
Chong Zhang181e6952019-10-09 13:23:39 -0700517 if (resource.value > res.value) {
518 resource.value -= res.value;
Chong Zhangfb092d32019-08-12 09:45:44 -0700519 } else {
Robert Shihc3af31b2019-09-20 21:45:01 -0700520 onLastRemoved(res, info);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700521 actualRemoved.value = resource.value;
Chong Zhang102b3e32020-11-02 12:21:50 -0800522 info.resources.erase(resType);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700523 }
524
525 // Add it to the list of removed resources for observers.
526 auto it = resourceRemoved.find(resType);
527 if (it == resourceRemoved.end()) {
528 resourceRemoved[resType] = actualRemoved;
529 } else {
530 mergeResources(it->second, actualRemoved);
Chong Zhangfb092d32019-08-12 09:45:44 -0700531 }
532 }
533 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700534 if (mObserverService != nullptr && !resourceRemoved.empty()) {
535 mObserverService->onResourceRemoved(info.uid, pid, resourceRemoved);
536 }
Chong Zhang181e6952019-10-09 13:23:39 -0700537 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700538}
539
Chong Zhang181e6952019-10-09 13:23:39 -0700540Status ResourceManagerService::removeClient(int32_t pid, int64_t clientId) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800541 removeResource(pid, clientId, true /*checkValid*/);
Chong Zhang181e6952019-10-09 13:23:39 -0700542 return Status::ok();
Wonsik Kim3e378962017-01-05 17:00:02 +0900543}
544
Chong Zhang181e6952019-10-09 13:23:39 -0700545Status ResourceManagerService::removeResource(int pid, int64_t clientId, bool checkValid) {
Ronghua Wu37c89242015-07-15 12:23:48 -0700546 String8 log = String8::format(
547 "removeResource(pid %d, clientId %lld)",
548 pid, (long long) clientId);
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700549 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700550
551 Mutex::Autolock lock(mLock);
Wonsik Kim3e378962017-01-05 17:00:02 +0900552 if (checkValid && !mProcessInfo->isValidPid(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800553 pid_t callingPid = IPCThreadState::self()->getCallingPid();
554 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
555 pid, callingPid);
556 pid = callingPid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800557 }
Ronghua Wu37c89242015-07-15 12:23:48 -0700558 ssize_t index = mMap.indexOfKey(pid);
559 if (index < 0) {
560 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700561 return Status::ok();
Ronghua Wu37c89242015-07-15 12:23:48 -0700562 }
Ronghua Wu37c89242015-07-15 12:23:48 -0700563 ResourceInfos &infos = mMap.editValueAt(index);
Chong Zhangfb092d32019-08-12 09:45:44 -0700564
565 index = infos.indexOfKey(clientId);
566 if (index < 0) {
567 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700568 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700569 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700570
571 const ResourceInfo &info = infos[index];
572 for (auto it = info.resources.begin(); it != info.resources.end(); it++) {
573 onLastRemoved(it->second, info);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700574 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700575
Chong Zhang97d367b2020-09-16 12:53:14 -0700576 removeCookieAndUnlink_l(info.client->asBinder(), info.cookie);
Chong Zhangfb092d32019-08-12 09:45:44 -0700577
Chong Zhanga9d45c72020-09-09 12:41:17 -0700578 if (mObserverService != nullptr && !info.resources.empty()) {
579 mObserverService->onResourceRemoved(info.uid, pid, info.resources);
580 }
581
Chong Zhangfb092d32019-08-12 09:45:44 -0700582 infos.removeItemsAt(index);
Chong Zhang181e6952019-10-09 13:23:39 -0700583 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700584}
585
Ronghua Wu05d89f12015-07-07 16:47:42 -0700586void ResourceManagerService::getClientForResource_l(
Chong Zhangfdd512a2019-11-22 11:03:14 -0800587 int callingPid, const MediaResourceParcel *res,
588 Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700589 if (res == NULL) {
590 return;
591 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800592 std::shared_ptr<IResourceManagerClient> client;
Chong Zhang181e6952019-10-09 13:23:39 -0700593 if (getLowestPriorityBiggestClient_l(callingPid, res->type, &client)) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700594 clients->push_back(client);
595 }
596}
597
Chong Zhang181e6952019-10-09 13:23:39 -0700598Status ResourceManagerService::reclaimResource(
599 int32_t callingPid,
600 const std::vector<MediaResourceParcel>& resources,
601 bool* _aidl_return) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700602 String8 log = String8::format("reclaimResource(callingPid %d, resources %s)",
Ronghua Wu231c3d12015-03-11 15:10:32 -0700603 callingPid, getString(resources).string());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700604 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700605 *_aidl_return = false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700606
Chong Zhangfdd512a2019-11-22 11:03:14 -0800607 Vector<std::shared_ptr<IResourceManagerClient>> clients;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700608 {
609 Mutex::Autolock lock(mLock);
Ronghua Wud11c43a2016-01-27 16:26:12 -0800610 if (!mProcessInfo->isValidPid(callingPid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800611 pid_t actualCallingPid = IPCThreadState::self()->getCallingPid();
612 ALOGW("%s called with untrusted pid %d, using actual calling pid %d", __FUNCTION__,
613 callingPid, actualCallingPid);
614 callingPid = actualCallingPid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800615 }
Chong Zhang181e6952019-10-09 13:23:39 -0700616 const MediaResourceParcel *secureCodec = NULL;
617 const MediaResourceParcel *nonSecureCodec = NULL;
618 const MediaResourceParcel *graphicMemory = NULL;
619 const MediaResourceParcel *drmSession = NULL;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700620 for (size_t i = 0; i < resources.size(); ++i) {
Chong Zhang181e6952019-10-09 13:23:39 -0700621 MediaResource::Type type = resources[i].type;
622 if (resources[i].type == MediaResource::Type::kSecureCodec) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700623 secureCodec = &resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700624 } else if (type == MediaResource::Type::kNonSecureCodec) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700625 nonSecureCodec = &resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700626 } else if (type == MediaResource::Type::kGraphicMemory) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700627 graphicMemory = &resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700628 } else if (type == MediaResource::Type::kDrmSession) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700629 drmSession = &resources[i];
Ronghua Wu05d89f12015-07-07 16:47:42 -0700630 }
631 }
632
633 // first pass to handle secure/non-secure codec conflict
634 if (secureCodec != NULL) {
635 if (!mSupportsMultipleSecureCodecs) {
Chong Zhang181e6952019-10-09 13:23:39 -0700636 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec, &clients)) {
637 return Status::ok();
Ronghua Wu05d89f12015-07-07 16:47:42 -0700638 }
639 }
640 if (!mSupportsSecureWithNonSecureCodec) {
Chong Zhang181e6952019-10-09 13:23:39 -0700641 if (!getAllClients_l(callingPid, MediaResource::Type::kNonSecureCodec, &clients)) {
642 return Status::ok();
Ronghua Wu05d89f12015-07-07 16:47:42 -0700643 }
644 }
645 }
646 if (nonSecureCodec != NULL) {
647 if (!mSupportsSecureWithNonSecureCodec) {
Chong Zhang181e6952019-10-09 13:23:39 -0700648 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec, &clients)) {
649 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700650 }
651 }
652 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700653 if (drmSession != NULL) {
654 getClientForResource_l(callingPid, drmSession, &clients);
655 if (clients.size() == 0) {
Chong Zhang181e6952019-10-09 13:23:39 -0700656 return Status::ok();
Robert Shihc3af31b2019-09-20 21:45:01 -0700657 }
658 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700659
660 if (clients.size() == 0) {
661 // if no secure/non-secure codec conflict, run second pass to handle other resources.
Ronghua Wu05d89f12015-07-07 16:47:42 -0700662 getClientForResource_l(callingPid, graphicMemory, &clients);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700663 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700664
665 if (clients.size() == 0) {
666 // if we are here, run the third pass to free one codec with the same type.
Ronghua Wu05d89f12015-07-07 16:47:42 -0700667 getClientForResource_l(callingPid, secureCodec, &clients);
668 getClientForResource_l(callingPid, nonSecureCodec, &clients);
669 }
670
671 if (clients.size() == 0) {
672 // if we are here, run the fourth pass to free one codec with the different type.
673 if (secureCodec != NULL) {
Chong Zhang181e6952019-10-09 13:23:39 -0700674 MediaResource temp(MediaResource::Type::kNonSecureCodec, 1);
Ronghua Wu05d89f12015-07-07 16:47:42 -0700675 getClientForResource_l(callingPid, &temp, &clients);
676 }
677 if (nonSecureCodec != NULL) {
Chong Zhang181e6952019-10-09 13:23:39 -0700678 MediaResource temp(MediaResource::Type::kSecureCodec, 1);
Ronghua Wu05d89f12015-07-07 16:47:42 -0700679 getClientForResource_l(callingPid, &temp, &clients);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700680 }
681 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700682 }
683
Wonsik Kim271429d2020-10-01 10:12:56 -0700684 *_aidl_return = reclaimInternal(clients);
685 return Status::ok();
686}
687
688bool ResourceManagerService::reclaimInternal(
689 const Vector<std::shared_ptr<IResourceManagerClient>> &clients) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700690 if (clients.size() == 0) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700691 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700692 }
693
Chong Zhangfdd512a2019-11-22 11:03:14 -0800694 std::shared_ptr<IResourceManagerClient> failedClient;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700695 for (size_t i = 0; i < clients.size(); ++i) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700696 String8 log = String8::format("reclaimResource from client %p", clients[i].get());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700697 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700698 bool success;
699 Status status = clients[i]->reclaimResource(&success);
700 if (!status.isOk() || !success) {
Ronghua Wu67e7f542015-03-13 10:47:08 -0700701 failedClient = clients[i];
702 break;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700703 }
704 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700705
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700706 if (failedClient == NULL) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700707 return true;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700708 }
709
Ronghua Wu67e7f542015-03-13 10:47:08 -0700710 {
711 Mutex::Autolock lock(mLock);
712 bool found = false;
713 for (size_t i = 0; i < mMap.size(); ++i) {
714 ResourceInfos &infos = mMap.editValueAt(i);
715 for (size_t j = 0; j < infos.size();) {
716 if (infos[j].client == failedClient) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700717 j = infos.removeItemsAt(j);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700718 found = true;
719 } else {
720 ++j;
721 }
722 }
723 if (found) {
724 break;
725 }
726 }
727 if (!found) {
728 ALOGV("didn't find failed client");
729 }
730 }
731
Wonsik Kim271429d2020-10-01 10:12:56 -0700732 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700733}
734
Henry Fang32762922020-01-28 18:40:39 -0800735Status ResourceManagerService::overridePid(
736 int originalPid,
737 int newPid) {
738 String8 log = String8::format("overridePid(originalPid %d, newPid %d)",
739 originalPid, newPid);
740 mServiceLog->add(log);
741
742 // allow if this is called from the same process or the process has
743 // permission.
744 if ((AIBinder_getCallingPid() != getpid()) &&
745 (checkCallingPermission(String16(
746 "android.permission.MEDIA_RESOURCE_OVERRIDE_PID")) == false)) {
747 ALOGE(
748 "Permission Denial: can't access overridePid method from pid=%d, "
749 "self pid=%d\n",
750 AIBinder_getCallingPid(), getpid());
751 return Status::fromServiceSpecificError(PERMISSION_DENIED);
752 }
753
754 {
755 Mutex::Autolock lock(mLock);
756 mOverridePidMap.erase(originalPid);
757 if (newPid != -1) {
758 mOverridePidMap.emplace(originalPid, newPid);
759 }
760 }
761
762 return Status::ok();
763}
764
Chong Zhang97d367b2020-09-16 12:53:14 -0700765Status ResourceManagerService::overrideProcessInfo(
766 const std::shared_ptr<IResourceManagerClient>& client,
767 int pid,
768 int procState,
769 int oomScore) {
770 String8 log = String8::format("overrideProcessInfo(pid %d, procState %d, oomScore %d)",
771 pid, procState, oomScore);
772 mServiceLog->add(log);
773
774 // Only allow the override if the caller already can access process state and oom scores.
775 int callingPid = AIBinder_getCallingPid();
776 if (callingPid != getpid() && (callingPid != pid || !checkCallingPermission(String16(
777 "android.permission.GET_PROCESS_STATE_AND_OOM_SCORE")))) {
778 ALOGE("Permission Denial: overrideProcessInfo method from pid=%d", callingPid);
779 return Status::fromServiceSpecificError(PERMISSION_DENIED);
780 }
781
782 if (client == nullptr) {
783 return Status::fromServiceSpecificError(BAD_VALUE);
784 }
785
786 Mutex::Autolock lock(mLock);
787 removeProcessInfoOverride_l(pid);
788
789 if (!mProcessInfo->overrideProcessInfo(pid, procState, oomScore)) {
790 // Override value is rejected by ProcessInfo.
791 return Status::fromServiceSpecificError(BAD_VALUE);
792 }
793
794 uintptr_t cookie = addCookieAndLink_l(client->asBinder(),
795 new OverrideProcessInfoDeathNotifier(ref<ResourceManagerService>(), pid));
796
797 mProcessInfoOverrideMap.emplace(pid, ProcessInfoOverride{cookie, client});
798
799 return Status::ok();
800}
801
802uintptr_t ResourceManagerService::addCookieAndLink_l(
803 ::ndk::SpAIBinder binder, const sp<DeathNotifier>& notifier) {
804 std::scoped_lock lock{sCookieLock};
805
806 uintptr_t cookie;
807 // Need to skip cookie 0 (if it wraps around). ResourceInfo has cookie initialized to 0
808 // indicating the death notifier is not created yet.
809 while ((cookie = ++sCookieCounter) == 0);
810 AIBinder_linkToDeath(binder.get(), mDeathRecipient.get(), (void*)cookie);
811 sCookieToDeathNotifierMap.emplace(cookie, notifier);
812
813 return cookie;
814}
815
816void ResourceManagerService::removeCookieAndUnlink_l(
817 ::ndk::SpAIBinder binder, uintptr_t cookie) {
818 std::scoped_lock lock{sCookieLock};
819 AIBinder_unlinkToDeath(binder.get(), mDeathRecipient.get(), (void*)cookie);
820 sCookieToDeathNotifierMap.erase(cookie);
821}
822
823void ResourceManagerService::removeProcessInfoOverride(int pid) {
824 Mutex::Autolock lock(mLock);
825
826 removeProcessInfoOverride_l(pid);
827}
828
829void ResourceManagerService::removeProcessInfoOverride_l(int pid) {
830 auto it = mProcessInfoOverrideMap.find(pid);
831 if (it == mProcessInfoOverrideMap.end()) {
832 return;
833 }
834
835 mProcessInfo->removeProcessInfoOverride(pid);
836
837 removeCookieAndUnlink_l(it->second.client->asBinder(), it->second.cookie);
838
839 mProcessInfoOverrideMap.erase(pid);
840}
841
Wonsik Kimd20e9362020-04-28 10:42:57 -0700842Status ResourceManagerService::markClientForPendingRemoval(int32_t pid, int64_t clientId) {
843 String8 log = String8::format(
844 "markClientForPendingRemoval(pid %d, clientId %lld)",
845 pid, (long long) clientId);
846 mServiceLog->add(log);
847
848 Mutex::Autolock lock(mLock);
849 if (!mProcessInfo->isValidPid(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800850 pid_t callingPid = IPCThreadState::self()->getCallingPid();
851 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
852 pid, callingPid);
853 pid = callingPid;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700854 }
855 ssize_t index = mMap.indexOfKey(pid);
856 if (index < 0) {
857 ALOGV("markClientForPendingRemoval: didn't find pid %d for clientId %lld",
858 pid, (long long)clientId);
859 return Status::ok();
860 }
861 ResourceInfos &infos = mMap.editValueAt(index);
862
863 index = infos.indexOfKey(clientId);
864 if (index < 0) {
865 ALOGV("markClientForPendingRemoval: didn't find clientId %lld", (long long) clientId);
866 return Status::ok();
867 }
868
869 ResourceInfo &info = infos.editValueAt(index);
870 info.pendingRemoval = true;
871 return Status::ok();
872}
873
Wonsik Kim271429d2020-10-01 10:12:56 -0700874Status ResourceManagerService::reclaimResourcesFromClientsPendingRemoval(int32_t pid) {
875 String8 log = String8::format("reclaimResourcesFromClientsPendingRemoval(pid %d)", pid);
876 mServiceLog->add(log);
877
878 Vector<std::shared_ptr<IResourceManagerClient>> clients;
879 {
880 Mutex::Autolock lock(mLock);
881 if (!mProcessInfo->isValidPid(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800882 pid_t callingPid = IPCThreadState::self()->getCallingPid();
883 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
884 pid, callingPid);
885 pid = callingPid;
Wonsik Kim271429d2020-10-01 10:12:56 -0700886 }
887
888 for (MediaResource::Type type : {MediaResource::Type::kSecureCodec,
889 MediaResource::Type::kNonSecureCodec,
890 MediaResource::Type::kGraphicMemory,
891 MediaResource::Type::kDrmSession}) {
892 std::shared_ptr<IResourceManagerClient> client;
893 if (getBiggestClient_l(pid, type, &client, true /* pendingRemovalOnly */)) {
894 clients.add(client);
895 break;
896 }
897 }
898 }
899
900 if (!clients.empty()) {
901 reclaimInternal(clients);
902 }
903 return Status::ok();
904}
905
Henry Fang32762922020-01-28 18:40:39 -0800906bool ResourceManagerService::getPriority_l(int pid, int* priority) {
907 int newPid = pid;
908
909 if (mOverridePidMap.find(pid) != mOverridePidMap.end()) {
910 newPid = mOverridePidMap[pid];
911 ALOGD("getPriority_l: use override pid %d instead original pid %d",
912 newPid, pid);
913 }
914
915 return mProcessInfo->getPriority(newPid, priority);
916}
917
Ronghua Wu231c3d12015-03-11 15:10:32 -0700918bool ResourceManagerService::getAllClients_l(
Chong Zhangfdd512a2019-11-22 11:03:14 -0800919 int callingPid, MediaResource::Type type,
920 Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
921 Vector<std::shared_ptr<IResourceManagerClient>> temp;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700922 for (size_t i = 0; i < mMap.size(); ++i) {
923 ResourceInfos &infos = mMap.editValueAt(i);
924 for (size_t j = 0; j < infos.size(); ++j) {
925 if (hasResourceType(type, infos[j].resources)) {
926 if (!isCallingPriorityHigher_l(callingPid, mMap.keyAt(i))) {
927 // some higher/equal priority process owns the resource,
928 // this request can't be fulfilled.
929 ALOGE("getAllClients_l: can't reclaim resource %s from pid %d",
Ronghua Wuea15fd22016-03-03 13:35:05 -0800930 asString(type), mMap.keyAt(i));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700931 return false;
932 }
933 temp.push_back(infos[j].client);
934 }
935 }
936 }
937 if (temp.size() == 0) {
Ronghua Wuea15fd22016-03-03 13:35:05 -0800938 ALOGV("getAllClients_l: didn't find any resource %s", asString(type));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700939 return true;
940 }
941 clients->appendVector(temp);
942 return true;
943}
944
945bool ResourceManagerService::getLowestPriorityBiggestClient_l(
Chong Zhangfdd512a2019-11-22 11:03:14 -0800946 int callingPid, MediaResource::Type type,
947 std::shared_ptr<IResourceManagerClient> *client) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700948 int lowestPriorityPid;
949 int lowestPriority;
950 int callingPriority;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700951
952 // Before looking into other processes, check if we have clients marked for
953 // pending removal in the same process.
954 if (getBiggestClient_l(callingPid, type, client, true /* pendingRemovalOnly */)) {
955 return true;
956 }
Henry Fang32762922020-01-28 18:40:39 -0800957 if (!getPriority_l(callingPid, &callingPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700958 ALOGE("getLowestPriorityBiggestClient_l: can't get process priority for pid %d",
959 callingPid);
960 return false;
961 }
962 if (!getLowestPriorityPid_l(type, &lowestPriorityPid, &lowestPriority)) {
963 return false;
964 }
965 if (lowestPriority <= callingPriority) {
966 ALOGE("getLowestPriorityBiggestClient_l: lowest priority %d vs caller priority %d",
967 lowestPriority, callingPriority);
968 return false;
969 }
970
971 if (!getBiggestClient_l(lowestPriorityPid, type, client)) {
972 return false;
973 }
974 return true;
975}
976
977bool ResourceManagerService::getLowestPriorityPid_l(
Ronghua Wuea15fd22016-03-03 13:35:05 -0800978 MediaResource::Type type, int *lowestPriorityPid, int *lowestPriority) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700979 int pid = -1;
980 int priority = -1;
981 for (size_t i = 0; i < mMap.size(); ++i) {
982 if (mMap.valueAt(i).size() == 0) {
983 // no client on this process.
984 continue;
985 }
986 if (!hasResourceType(type, mMap.valueAt(i))) {
987 // doesn't have the requested resource type
988 continue;
989 }
990 int tempPid = mMap.keyAt(i);
991 int tempPriority;
Henry Fang32762922020-01-28 18:40:39 -0800992 if (!getPriority_l(tempPid, &tempPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700993 ALOGV("getLowestPriorityPid_l: can't get priority of pid %d, skipped", tempPid);
994 // TODO: remove this pid from mMap?
995 continue;
996 }
997 if (pid == -1 || tempPriority > priority) {
998 // initial the value
999 pid = tempPid;
1000 priority = tempPriority;
1001 }
1002 }
1003 if (pid != -1) {
1004 *lowestPriorityPid = pid;
1005 *lowestPriority = priority;
1006 }
1007 return (pid != -1);
1008}
1009
1010bool ResourceManagerService::isCallingPriorityHigher_l(int callingPid, int pid) {
1011 int callingPidPriority;
Henry Fang32762922020-01-28 18:40:39 -08001012 if (!getPriority_l(callingPid, &callingPidPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001013 return false;
1014 }
1015
1016 int priority;
Henry Fang32762922020-01-28 18:40:39 -08001017 if (!getPriority_l(pid, &priority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001018 return false;
1019 }
1020
1021 return (callingPidPriority < priority);
1022}
1023
1024bool ResourceManagerService::getBiggestClient_l(
Wonsik Kimd20e9362020-04-28 10:42:57 -07001025 int pid, MediaResource::Type type, std::shared_ptr<IResourceManagerClient> *client,
1026 bool pendingRemovalOnly) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001027 ssize_t index = mMap.indexOfKey(pid);
1028 if (index < 0) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001029 ALOGE_IF(!pendingRemovalOnly,
1030 "getBiggestClient_l: can't find resource info for pid %d", pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001031 return false;
1032 }
1033
Chong Zhangfdd512a2019-11-22 11:03:14 -08001034 std::shared_ptr<IResourceManagerClient> clientTemp;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001035 uint64_t largestValue = 0;
1036 const ResourceInfos &infos = mMap.valueAt(index);
1037 for (size_t i = 0; i < infos.size(); ++i) {
Chong Zhangfb092d32019-08-12 09:45:44 -07001038 const ResourceList &resources = infos[i].resources;
Wonsik Kimd20e9362020-04-28 10:42:57 -07001039 if (pendingRemovalOnly && !infos[i].pendingRemoval) {
1040 continue;
1041 }
Chong Zhangfb092d32019-08-12 09:45:44 -07001042 for (auto it = resources.begin(); it != resources.end(); it++) {
Chong Zhang181e6952019-10-09 13:23:39 -07001043 const MediaResourceParcel &resource = it->second;
1044 if (resource.type == type) {
1045 if (resource.value > largestValue) {
1046 largestValue = resource.value;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001047 clientTemp = infos[i].client;
1048 }
1049 }
1050 }
1051 }
1052
1053 if (clientTemp == NULL) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001054 ALOGE_IF(!pendingRemovalOnly,
1055 "getBiggestClient_l: can't find resource type %s for pid %d",
1056 asString(type), pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001057 return false;
1058 }
1059
1060 *client = clientTemp;
1061 return true;
1062}
1063
Ronghua Wu231c3d12015-03-11 15:10:32 -07001064} // namespace android