blob: 6a60aad38ed0bf13ca7f935d2cb25c7a2a250911 [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:
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
Arun Johnsonaabe0142022-07-18 19:16:04 +0000249 std::string clientName = "<unknown client>";
250 if (infos[j].client != nullptr) {
251 Status status = infos[j].client->getName(&clientName);
Chong Zhang181e6952019-10-09 13:23:39 -0700252 }
253 snprintf(buffer, SIZE, " Name: %s\n", clientName.c_str());
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700254 result.append(buffer);
255
Chong Zhangfb092d32019-08-12 09:45:44 -0700256 const ResourceList &resources = infos[j].resources;
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700257 result.append(" Resources:\n");
Chong Zhangfb092d32019-08-12 09:45:44 -0700258 for (auto it = resources.begin(); it != resources.end(); it++) {
Chong Zhang181e6952019-10-09 13:23:39 -0700259 snprintf(buffer, SIZE, " %s\n", toString(it->second).string());
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700260 result.append(buffer);
261 }
262 }
263 }
Henry Fang32762922020-01-28 18:40:39 -0800264 result.append(" Process Pid override:\n");
265 for (auto it = overridePidMapCopy.begin(); it != overridePidMapCopy.end(); ++it) {
266 snprintf(buffer, SIZE, " Original Pid: %d, Override Pid: %d\n",
267 it->first, it->second);
268 result.append(buffer);
269 }
Ronghua Wu022ed722015-05-11 15:15:09 -0700270 result.append(" Events logs (most recent at top):\n");
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700271 result.append(serviceLog);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700272
273 write(fd, result.string(), result.size());
274 return OK;
275}
276
Chong Zhangdd726802019-08-21 17:24:13 -0700277struct SystemCallbackImpl :
278 public ResourceManagerService::SystemCallbackInterface {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800279 SystemCallbackImpl() : mClientToken(new BBinder()) {}
Ronghua Wu231c3d12015-03-11 15:10:32 -0700280
Chong Zhangdd726802019-08-21 17:24:13 -0700281 virtual void noteStartVideo(int uid) override {
282 BatteryNotifier::getInstance().noteStartVideo(uid);
283 }
284 virtual void noteStopVideo(int uid) override {
285 BatteryNotifier::getInstance().noteStopVideo(uid);
286 }
287 virtual void noteResetVideo() override {
288 BatteryNotifier::getInstance().noteResetVideo();
289 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800290 virtual bool requestCpusetBoost(bool enable) override {
291 return android::requestCpusetBoost(enable, mClientToken);
Chong Zhangdd726802019-08-21 17:24:13 -0700292 }
293
294protected:
295 virtual ~SystemCallbackImpl() {}
296
297private:
298 DISALLOW_EVIL_CONSTRUCTORS(SystemCallbackImpl);
Chong Zhangfdd512a2019-11-22 11:03:14 -0800299 sp<IBinder> mClientToken;
Chong Zhangdd726802019-08-21 17:24:13 -0700300};
301
302ResourceManagerService::ResourceManagerService()
303 : ResourceManagerService(new ProcessInfo(), new SystemCallbackImpl()) {}
304
305ResourceManagerService::ResourceManagerService(
306 const sp<ProcessInfoInterface> &processInfo,
307 const sp<SystemCallbackInterface> &systemResource)
Ronghua Wu231c3d12015-03-11 15:10:32 -0700308 : mProcessInfo(processInfo),
Chong Zhangdd726802019-08-21 17:24:13 -0700309 mSystemCB(systemResource),
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700310 mServiceLog(new ServiceLog()),
Ronghua Wu231c3d12015-03-11 15:10:32 -0700311 mSupportsMultipleSecureCodecs(true),
Chong Zhang79d2b282018-04-17 14:14:31 -0700312 mSupportsSecureWithNonSecureCodec(true),
Chong Zhangfdd512a2019-11-22 11:03:14 -0800313 mCpuBoostCount(0),
314 mDeathRecipient(AIBinder_DeathRecipient_new(DeathNotifier::BinderDiedCallback)) {
Chong Zhangdd726802019-08-21 17:24:13 -0700315 mSystemCB->noteResetVideo();
Chong Zhangee33d642019-08-08 14:26:43 -0700316}
Ronghua Wu231c3d12015-03-11 15:10:32 -0700317
Chong Zhangfdd512a2019-11-22 11:03:14 -0800318//static
319void ResourceManagerService::instantiate() {
320 std::shared_ptr<ResourceManagerService> service =
321 ::ndk::SharedRefBase::make<ResourceManagerService>();
322 binder_status_t status =
323 AServiceManager_addService(service->asBinder().get(), getServiceName());
324 if (status != STATUS_OK) {
325 return;
326 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700327
328 std::shared_ptr<ResourceObserverService> observerService =
329 ResourceObserverService::instantiate();
330
331 if (observerService != nullptr) {
332 service->setObserverService(observerService);
333 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800334 // TODO: mediaserver main() is already starting the thread pool,
335 // move this to mediaserver main() when other services in mediaserver
336 // are converted to ndk-platform aidl.
337 //ABinderProcess_startThreadPool();
338}
339
Ronghua Wu231c3d12015-03-11 15:10:32 -0700340ResourceManagerService::~ResourceManagerService() {}
341
Chong Zhanga9d45c72020-09-09 12:41:17 -0700342void ResourceManagerService::setObserverService(
343 const std::shared_ptr<ResourceObserverService>& observerService) {
344 mObserverService = observerService;
345}
346
Chong Zhang181e6952019-10-09 13:23:39 -0700347Status ResourceManagerService::config(const std::vector<MediaResourcePolicyParcel>& policies) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700348 String8 log = String8::format("config(%s)", getString(policies).string());
349 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700350
351 Mutex::Autolock lock(mLock);
352 for (size_t i = 0; i < policies.size(); ++i) {
Chong Zhang181e6952019-10-09 13:23:39 -0700353 const std::string &type = policies[i].type;
354 const std::string &value = policies[i].value;
355 if (type == MediaResourcePolicy::kPolicySupportsMultipleSecureCodecs()) {
Ronghua Wu9ba21b92015-04-21 14:23:06 -0700356 mSupportsMultipleSecureCodecs = (value == "true");
Chong Zhang181e6952019-10-09 13:23:39 -0700357 } else if (type == MediaResourcePolicy::kPolicySupportsSecureWithNonSecureCodec()) {
Ronghua Wu9ba21b92015-04-21 14:23:06 -0700358 mSupportsSecureWithNonSecureCodec = (value == "true");
Ronghua Wu231c3d12015-03-11 15:10:32 -0700359 }
360 }
Chong Zhang181e6952019-10-09 13:23:39 -0700361 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700362}
363
Chong Zhangfb092d32019-08-12 09:45:44 -0700364void ResourceManagerService::onFirstAdded(
Chong Zhang181e6952019-10-09 13:23:39 -0700365 const MediaResourceParcel& resource, const ResourceInfo& clientInfo) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700366 // first time added
Chong Zhang181e6952019-10-09 13:23:39 -0700367 if (resource.type == MediaResource::Type::kCpuBoost
368 && resource.subType == MediaResource::SubType::kUnspecifiedSubType) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700369 // Request it on every new instance of kCpuBoost, as the media.codec
370 // could have died, if we only do it the first time subsequent instances
371 // never gets the boost.
Chong Zhangfdd512a2019-11-22 11:03:14 -0800372 if (mSystemCB->requestCpusetBoost(true) != OK) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700373 ALOGW("couldn't request cpuset boost");
374 }
375 mCpuBoostCount++;
Chong Zhang181e6952019-10-09 13:23:39 -0700376 } else if (resource.type == MediaResource::Type::kBattery
377 && resource.subType == MediaResource::SubType::kVideoCodec) {
Chong Zhangdd726802019-08-21 17:24:13 -0700378 mSystemCB->noteStartVideo(clientInfo.uid);
Chong Zhangfb092d32019-08-12 09:45:44 -0700379 }
380}
381
382void ResourceManagerService::onLastRemoved(
Chong Zhang181e6952019-10-09 13:23:39 -0700383 const MediaResourceParcel& resource, const ResourceInfo& clientInfo) {
384 if (resource.type == MediaResource::Type::kCpuBoost
385 && resource.subType == MediaResource::SubType::kUnspecifiedSubType
Chong Zhangfb092d32019-08-12 09:45:44 -0700386 && mCpuBoostCount > 0) {
387 if (--mCpuBoostCount == 0) {
Chong Zhangfdd512a2019-11-22 11:03:14 -0800388 mSystemCB->requestCpusetBoost(false);
Chong Zhangfb092d32019-08-12 09:45:44 -0700389 }
Chong Zhang181e6952019-10-09 13:23:39 -0700390 } else if (resource.type == MediaResource::Type::kBattery
391 && resource.subType == MediaResource::SubType::kVideoCodec) {
Chong Zhangdd726802019-08-21 17:24:13 -0700392 mSystemCB->noteStopVideo(clientInfo.uid);
Chong Zhangfb092d32019-08-12 09:45:44 -0700393 }
394}
395
Robert Shihc3af31b2019-09-20 21:45:01 -0700396void ResourceManagerService::mergeResources(
Chong Zhang181e6952019-10-09 13:23:39 -0700397 MediaResourceParcel& r1, const MediaResourceParcel& r2) {
398 // The resource entry on record is maintained to be in [0,INT64_MAX].
399 // Clamp if merging in the new resource value causes it to go out of bound.
400 // Note that the new resource value could be negative, eg.DrmSession, the
401 // value goes lower when the session is used more often. During reclaim
402 // the session with the highest value (lowest usage) would be closed.
403 if (r2.value < INT64_MAX - r1.value) {
404 r1.value += r2.value;
405 if (r1.value < 0) {
406 r1.value = 0;
407 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700408 } else {
Chong Zhang181e6952019-10-09 13:23:39 -0700409 r1.value = INT64_MAX;
Robert Shihc3af31b2019-09-20 21:45:01 -0700410 }
411}
412
Chong Zhang181e6952019-10-09 13:23:39 -0700413Status ResourceManagerService::addResource(
414 int32_t pid,
415 int32_t uid,
Ronghua Wu231c3d12015-03-11 15:10:32 -0700416 int64_t clientId,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800417 const std::shared_ptr<IResourceManagerClient>& client,
Chong Zhang181e6952019-10-09 13:23:39 -0700418 const std::vector<MediaResourceParcel>& resources) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700419 String8 log = String8::format("addResource(pid %d, clientId %lld, resources %s)",
Ronghua Wu231c3d12015-03-11 15:10:32 -0700420 pid, (long long) clientId, getString(resources).string());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700421 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700422
423 Mutex::Autolock lock(mLock);
Ronghua Wud11c43a2016-01-27 16:26:12 -0800424 if (!mProcessInfo->isValidPid(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800425 pid_t callingPid = IPCThreadState::self()->getCallingPid();
426 uid_t callingUid = IPCThreadState::self()->getCallingUid();
427 ALOGW("%s called with untrusted pid %d, using calling pid %d, uid %d", __FUNCTION__,
428 pid, callingPid, callingUid);
429 pid = callingPid;
430 uid = callingUid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800431 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700432 ResourceInfos& infos = getResourceInfosForEdit(pid, mMap);
Chong Zhangee33d642019-08-08 14:26:43 -0700433 ResourceInfo& info = getResourceInfoForEdit(uid, clientId, client, infos);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700434 ResourceList resourceAdded;
Chong Zhang79d2b282018-04-17 14:14:31 -0700435
436 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700437 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700438 const auto resType = std::tuple(res.type, res.subType, res.id);
439
440 if (res.value < 0 && res.type != MediaResource::Type::kDrmSession) {
441 ALOGW("Ignoring request to remove negative value of non-drm resource");
442 continue;
443 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700444 if (info.resources.find(resType) == info.resources.end()) {
Chong Zhang181e6952019-10-09 13:23:39 -0700445 if (res.value <= 0) {
446 // We can't init a new entry with negative value, although it's allowed
447 // to merge in negative values after the initial add.
448 ALOGW("Ignoring request to add new resource entry with value <= 0");
449 continue;
450 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700451 onFirstAdded(res, info);
452 info.resources[resType] = res;
Chong Zhangfb092d32019-08-12 09:45:44 -0700453 } else {
Robert Shihc3af31b2019-09-20 21:45:01 -0700454 mergeResources(info.resources[resType], res);
Chong Zhang79d2b282018-04-17 14:14:31 -0700455 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700456 // Add it to the list of added resources for observers.
457 auto it = resourceAdded.find(resType);
458 if (it == resourceAdded.end()) {
459 resourceAdded[resType] = res;
460 } else {
461 mergeResources(it->second, res);
462 }
Chong Zhang79d2b282018-04-17 14:14:31 -0700463 }
Chong Zhang97d367b2020-09-16 12:53:14 -0700464 if (info.cookie == 0 && client != nullptr) {
465 info.cookie = addCookieAndLink_l(client->asBinder(),
466 new DeathNotifier(ref<ResourceManagerService>(), pid, clientId));
Wonsik Kim3e378962017-01-05 17:00:02 +0900467 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700468 if (mObserverService != nullptr && !resourceAdded.empty()) {
469 mObserverService->onResourceAdded(uid, pid, resourceAdded);
470 }
Dongwon Kangfe508d32015-12-15 14:22:05 +0900471 notifyResourceGranted(pid, resources);
Chong Zhang181e6952019-10-09 13:23:39 -0700472 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700473}
474
Chong Zhang181e6952019-10-09 13:23:39 -0700475Status ResourceManagerService::removeResource(
476 int32_t pid, int64_t clientId,
477 const std::vector<MediaResourceParcel>& resources) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700478 String8 log = String8::format("removeResource(pid %d, clientId %lld, resources %s)",
479 pid, (long long) clientId, getString(resources).string());
480 mServiceLog->add(log);
481
482 Mutex::Autolock lock(mLock);
483 if (!mProcessInfo->isValidPid(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800484 pid_t callingPid = IPCThreadState::self()->getCallingPid();
485 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
486 pid, callingPid);
487 pid = callingPid;
Chong Zhangfb092d32019-08-12 09:45:44 -0700488 }
489 ssize_t index = mMap.indexOfKey(pid);
490 if (index < 0) {
491 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700492 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700493 }
494 ResourceInfos &infos = mMap.editValueAt(index);
495
496 index = infos.indexOfKey(clientId);
497 if (index < 0) {
498 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700499 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700500 }
501
502 ResourceInfo &info = infos.editValueAt(index);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700503 ResourceList resourceRemoved;
Chong Zhangfb092d32019-08-12 09:45:44 -0700504 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700505 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700506 const auto resType = std::tuple(res.type, res.subType, res.id);
507
508 if (res.value < 0) {
509 ALOGW("Ignoring request to remove negative value of resource");
510 continue;
511 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700512 // ignore if we don't have it
513 if (info.resources.find(resType) != info.resources.end()) {
Chong Zhang181e6952019-10-09 13:23:39 -0700514 MediaResourceParcel &resource = info.resources[resType];
Chong Zhanga9d45c72020-09-09 12:41:17 -0700515 MediaResourceParcel actualRemoved = res;
Chong Zhang181e6952019-10-09 13:23:39 -0700516 if (resource.value > res.value) {
517 resource.value -= res.value;
Chong Zhangfb092d32019-08-12 09:45:44 -0700518 } else {
Robert Shihc3af31b2019-09-20 21:45:01 -0700519 onLastRemoved(res, info);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700520 actualRemoved.value = resource.value;
Chong Zhang102b3e32020-11-02 12:21:50 -0800521 info.resources.erase(resType);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700522 }
523
524 // Add it to the list of removed resources for observers.
525 auto it = resourceRemoved.find(resType);
526 if (it == resourceRemoved.end()) {
527 resourceRemoved[resType] = actualRemoved;
528 } else {
529 mergeResources(it->second, actualRemoved);
Chong Zhangfb092d32019-08-12 09:45:44 -0700530 }
531 }
532 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700533 if (mObserverService != nullptr && !resourceRemoved.empty()) {
534 mObserverService->onResourceRemoved(info.uid, pid, resourceRemoved);
535 }
Chong Zhang181e6952019-10-09 13:23:39 -0700536 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700537}
538
Chong Zhang181e6952019-10-09 13:23:39 -0700539Status ResourceManagerService::removeClient(int32_t pid, int64_t clientId) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800540 removeResource(pid, clientId, true /*checkValid*/);
Chong Zhang181e6952019-10-09 13:23:39 -0700541 return Status::ok();
Wonsik Kim3e378962017-01-05 17:00:02 +0900542}
543
Chong Zhang181e6952019-10-09 13:23:39 -0700544Status ResourceManagerService::removeResource(int pid, int64_t clientId, bool checkValid) {
Ronghua Wu37c89242015-07-15 12:23:48 -0700545 String8 log = String8::format(
546 "removeResource(pid %d, clientId %lld)",
547 pid, (long long) clientId);
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700548 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700549
550 Mutex::Autolock lock(mLock);
Wonsik Kim3e378962017-01-05 17:00:02 +0900551 if (checkValid && !mProcessInfo->isValidPid(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800552 pid_t callingPid = IPCThreadState::self()->getCallingPid();
553 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
554 pid, callingPid);
555 pid = callingPid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800556 }
Ronghua Wu37c89242015-07-15 12:23:48 -0700557 ssize_t index = mMap.indexOfKey(pid);
558 if (index < 0) {
559 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700560 return Status::ok();
Ronghua Wu37c89242015-07-15 12:23:48 -0700561 }
Ronghua Wu37c89242015-07-15 12:23:48 -0700562 ResourceInfos &infos = mMap.editValueAt(index);
Chong Zhangfb092d32019-08-12 09:45:44 -0700563
564 index = infos.indexOfKey(clientId);
565 if (index < 0) {
566 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700567 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700568 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700569
570 const ResourceInfo &info = infos[index];
571 for (auto it = info.resources.begin(); it != info.resources.end(); it++) {
572 onLastRemoved(it->second, info);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700573 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700574
Chong Zhang97d367b2020-09-16 12:53:14 -0700575 removeCookieAndUnlink_l(info.client->asBinder(), info.cookie);
Chong Zhangfb092d32019-08-12 09:45:44 -0700576
Chong Zhanga9d45c72020-09-09 12:41:17 -0700577 if (mObserverService != nullptr && !info.resources.empty()) {
578 mObserverService->onResourceRemoved(info.uid, pid, info.resources);
579 }
580
Chong Zhangfb092d32019-08-12 09:45:44 -0700581 infos.removeItemsAt(index);
Chong Zhang181e6952019-10-09 13:23:39 -0700582 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700583}
584
Ronghua Wu05d89f12015-07-07 16:47:42 -0700585void ResourceManagerService::getClientForResource_l(
Chong Zhangfdd512a2019-11-22 11:03:14 -0800586 int callingPid, const MediaResourceParcel *res,
587 Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700588 if (res == NULL) {
589 return;
590 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800591 std::shared_ptr<IResourceManagerClient> client;
Chong Zhang181e6952019-10-09 13:23:39 -0700592 if (getLowestPriorityBiggestClient_l(callingPid, res->type, &client)) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700593 clients->push_back(client);
594 }
595}
596
Chong Zhang181e6952019-10-09 13:23:39 -0700597Status ResourceManagerService::reclaimResource(
598 int32_t callingPid,
599 const std::vector<MediaResourceParcel>& resources,
600 bool* _aidl_return) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700601 String8 log = String8::format("reclaimResource(callingPid %d, resources %s)",
Ronghua Wu231c3d12015-03-11 15:10:32 -0700602 callingPid, getString(resources).string());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700603 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700604 *_aidl_return = false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700605
Chong Zhangfdd512a2019-11-22 11:03:14 -0800606 Vector<std::shared_ptr<IResourceManagerClient>> clients;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700607 {
608 Mutex::Autolock lock(mLock);
Ronghua Wud11c43a2016-01-27 16:26:12 -0800609 if (!mProcessInfo->isValidPid(callingPid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800610 pid_t actualCallingPid = IPCThreadState::self()->getCallingPid();
611 ALOGW("%s called with untrusted pid %d, using actual calling pid %d", __FUNCTION__,
612 callingPid, actualCallingPid);
613 callingPid = actualCallingPid;
Ronghua Wud11c43a2016-01-27 16:26:12 -0800614 }
Chong Zhang181e6952019-10-09 13:23:39 -0700615 const MediaResourceParcel *secureCodec = NULL;
616 const MediaResourceParcel *nonSecureCodec = NULL;
617 const MediaResourceParcel *graphicMemory = NULL;
618 const MediaResourceParcel *drmSession = NULL;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700619 for (size_t i = 0; i < resources.size(); ++i) {
Chong Zhang181e6952019-10-09 13:23:39 -0700620 MediaResource::Type type = resources[i].type;
621 if (resources[i].type == MediaResource::Type::kSecureCodec) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700622 secureCodec = &resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700623 } else if (type == MediaResource::Type::kNonSecureCodec) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700624 nonSecureCodec = &resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700625 } else if (type == MediaResource::Type::kGraphicMemory) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700626 graphicMemory = &resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700627 } else if (type == MediaResource::Type::kDrmSession) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700628 drmSession = &resources[i];
Ronghua Wu05d89f12015-07-07 16:47:42 -0700629 }
630 }
631
632 // first pass to handle secure/non-secure codec conflict
633 if (secureCodec != NULL) {
634 if (!mSupportsMultipleSecureCodecs) {
Chong Zhang181e6952019-10-09 13:23:39 -0700635 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec, &clients)) {
636 return Status::ok();
Ronghua Wu05d89f12015-07-07 16:47:42 -0700637 }
638 }
639 if (!mSupportsSecureWithNonSecureCodec) {
Chong Zhang181e6952019-10-09 13:23:39 -0700640 if (!getAllClients_l(callingPid, MediaResource::Type::kNonSecureCodec, &clients)) {
641 return Status::ok();
Ronghua Wu05d89f12015-07-07 16:47:42 -0700642 }
643 }
644 }
645 if (nonSecureCodec != NULL) {
646 if (!mSupportsSecureWithNonSecureCodec) {
Chong Zhang181e6952019-10-09 13:23:39 -0700647 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec, &clients)) {
648 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700649 }
650 }
651 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700652 if (drmSession != NULL) {
653 getClientForResource_l(callingPid, drmSession, &clients);
654 if (clients.size() == 0) {
Chong Zhang181e6952019-10-09 13:23:39 -0700655 return Status::ok();
Robert Shihc3af31b2019-09-20 21:45:01 -0700656 }
657 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700658
659 if (clients.size() == 0) {
660 // if no secure/non-secure codec conflict, run second pass to handle other resources.
Ronghua Wu05d89f12015-07-07 16:47:42 -0700661 getClientForResource_l(callingPid, graphicMemory, &clients);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700662 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700663
664 if (clients.size() == 0) {
665 // if we are here, run the third pass to free one codec with the same type.
Ronghua Wu05d89f12015-07-07 16:47:42 -0700666 getClientForResource_l(callingPid, secureCodec, &clients);
667 getClientForResource_l(callingPid, nonSecureCodec, &clients);
668 }
669
670 if (clients.size() == 0) {
671 // if we are here, run the fourth pass to free one codec with the different type.
672 if (secureCodec != NULL) {
Wonsik Kimb3639012022-03-16 13:57:41 -0700673 MediaResource temp(MediaResource::Type::kNonSecureCodec, secureCodec->subType, 1);
Ronghua Wu05d89f12015-07-07 16:47:42 -0700674 getClientForResource_l(callingPid, &temp, &clients);
675 }
676 if (nonSecureCodec != NULL) {
Wonsik Kimb3639012022-03-16 13:57:41 -0700677 MediaResource temp(MediaResource::Type::kSecureCodec, nonSecureCodec->subType, 1);
Ronghua Wu05d89f12015-07-07 16:47:42 -0700678 getClientForResource_l(callingPid, &temp, &clients);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700679 }
680 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700681 }
682
Wonsik Kim271429d2020-10-01 10:12:56 -0700683 *_aidl_return = reclaimInternal(clients);
684 return Status::ok();
685}
686
687bool ResourceManagerService::reclaimInternal(
688 const Vector<std::shared_ptr<IResourceManagerClient>> &clients) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700689 if (clients.size() == 0) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700690 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700691 }
692
Chong Zhangfdd512a2019-11-22 11:03:14 -0800693 std::shared_ptr<IResourceManagerClient> failedClient;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700694 for (size_t i = 0; i < clients.size(); ++i) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700695 String8 log = String8::format("reclaimResource from client %p", clients[i].get());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700696 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700697 bool success;
698 Status status = clients[i]->reclaimResource(&success);
699 if (!status.isOk() || !success) {
Ronghua Wu67e7f542015-03-13 10:47:08 -0700700 failedClient = clients[i];
701 break;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700702 }
703 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700704
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700705 if (failedClient == NULL) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700706 return true;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700707 }
708
Ronghua Wu67e7f542015-03-13 10:47:08 -0700709 {
710 Mutex::Autolock lock(mLock);
711 bool found = false;
712 for (size_t i = 0; i < mMap.size(); ++i) {
713 ResourceInfos &infos = mMap.editValueAt(i);
714 for (size_t j = 0; j < infos.size();) {
715 if (infos[j].client == failedClient) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700716 j = infos.removeItemsAt(j);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700717 found = true;
718 } else {
719 ++j;
720 }
721 }
722 if (found) {
723 break;
724 }
725 }
726 if (!found) {
727 ALOGV("didn't find failed client");
728 }
729 }
730
Wonsik Kim271429d2020-10-01 10:12:56 -0700731 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700732}
733
Henry Fang32762922020-01-28 18:40:39 -0800734Status ResourceManagerService::overridePid(
735 int originalPid,
736 int newPid) {
737 String8 log = String8::format("overridePid(originalPid %d, newPid %d)",
738 originalPid, newPid);
739 mServiceLog->add(log);
740
741 // allow if this is called from the same process or the process has
742 // permission.
743 if ((AIBinder_getCallingPid() != getpid()) &&
744 (checkCallingPermission(String16(
745 "android.permission.MEDIA_RESOURCE_OVERRIDE_PID")) == false)) {
746 ALOGE(
747 "Permission Denial: can't access overridePid method from pid=%d, "
748 "self pid=%d\n",
749 AIBinder_getCallingPid(), getpid());
750 return Status::fromServiceSpecificError(PERMISSION_DENIED);
751 }
752
753 {
754 Mutex::Autolock lock(mLock);
755 mOverridePidMap.erase(originalPid);
756 if (newPid != -1) {
757 mOverridePidMap.emplace(originalPid, newPid);
758 }
759 }
760
761 return Status::ok();
762}
763
Chong Zhang97d367b2020-09-16 12:53:14 -0700764Status ResourceManagerService::overrideProcessInfo(
765 const std::shared_ptr<IResourceManagerClient>& client,
766 int pid,
767 int procState,
768 int oomScore) {
769 String8 log = String8::format("overrideProcessInfo(pid %d, procState %d, oomScore %d)",
770 pid, procState, oomScore);
771 mServiceLog->add(log);
772
773 // Only allow the override if the caller already can access process state and oom scores.
774 int callingPid = AIBinder_getCallingPid();
775 if (callingPid != getpid() && (callingPid != pid || !checkCallingPermission(String16(
776 "android.permission.GET_PROCESS_STATE_AND_OOM_SCORE")))) {
777 ALOGE("Permission Denial: overrideProcessInfo method from pid=%d", callingPid);
778 return Status::fromServiceSpecificError(PERMISSION_DENIED);
779 }
780
781 if (client == nullptr) {
782 return Status::fromServiceSpecificError(BAD_VALUE);
783 }
784
785 Mutex::Autolock lock(mLock);
786 removeProcessInfoOverride_l(pid);
787
788 if (!mProcessInfo->overrideProcessInfo(pid, procState, oomScore)) {
789 // Override value is rejected by ProcessInfo.
790 return Status::fromServiceSpecificError(BAD_VALUE);
791 }
792
793 uintptr_t cookie = addCookieAndLink_l(client->asBinder(),
794 new OverrideProcessInfoDeathNotifier(ref<ResourceManagerService>(), pid));
795
796 mProcessInfoOverrideMap.emplace(pid, ProcessInfoOverride{cookie, client});
797
798 return Status::ok();
799}
800
801uintptr_t ResourceManagerService::addCookieAndLink_l(
802 ::ndk::SpAIBinder binder, const sp<DeathNotifier>& notifier) {
803 std::scoped_lock lock{sCookieLock};
804
805 uintptr_t cookie;
806 // Need to skip cookie 0 (if it wraps around). ResourceInfo has cookie initialized to 0
807 // indicating the death notifier is not created yet.
808 while ((cookie = ++sCookieCounter) == 0);
809 AIBinder_linkToDeath(binder.get(), mDeathRecipient.get(), (void*)cookie);
810 sCookieToDeathNotifierMap.emplace(cookie, notifier);
811
812 return cookie;
813}
814
815void ResourceManagerService::removeCookieAndUnlink_l(
816 ::ndk::SpAIBinder binder, uintptr_t cookie) {
817 std::scoped_lock lock{sCookieLock};
818 AIBinder_unlinkToDeath(binder.get(), mDeathRecipient.get(), (void*)cookie);
819 sCookieToDeathNotifierMap.erase(cookie);
820}
821
822void ResourceManagerService::removeProcessInfoOverride(int pid) {
823 Mutex::Autolock lock(mLock);
824
825 removeProcessInfoOverride_l(pid);
826}
827
828void ResourceManagerService::removeProcessInfoOverride_l(int pid) {
829 auto it = mProcessInfoOverrideMap.find(pid);
830 if (it == mProcessInfoOverrideMap.end()) {
831 return;
832 }
833
834 mProcessInfo->removeProcessInfoOverride(pid);
835
836 removeCookieAndUnlink_l(it->second.client->asBinder(), it->second.cookie);
837
838 mProcessInfoOverrideMap.erase(pid);
839}
840
Wonsik Kimd20e9362020-04-28 10:42:57 -0700841Status ResourceManagerService::markClientForPendingRemoval(int32_t pid, int64_t clientId) {
842 String8 log = String8::format(
843 "markClientForPendingRemoval(pid %d, clientId %lld)",
844 pid, (long long) clientId);
845 mServiceLog->add(log);
846
847 Mutex::Autolock lock(mLock);
848 if (!mProcessInfo->isValidPid(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800849 pid_t callingPid = IPCThreadState::self()->getCallingPid();
850 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
851 pid, callingPid);
852 pid = callingPid;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700853 }
854 ssize_t index = mMap.indexOfKey(pid);
855 if (index < 0) {
856 ALOGV("markClientForPendingRemoval: didn't find pid %d for clientId %lld",
857 pid, (long long)clientId);
858 return Status::ok();
859 }
860 ResourceInfos &infos = mMap.editValueAt(index);
861
862 index = infos.indexOfKey(clientId);
863 if (index < 0) {
864 ALOGV("markClientForPendingRemoval: didn't find clientId %lld", (long long) clientId);
865 return Status::ok();
866 }
867
868 ResourceInfo &info = infos.editValueAt(index);
869 info.pendingRemoval = true;
870 return Status::ok();
871}
872
Wonsik Kim271429d2020-10-01 10:12:56 -0700873Status ResourceManagerService::reclaimResourcesFromClientsPendingRemoval(int32_t pid) {
874 String8 log = String8::format("reclaimResourcesFromClientsPendingRemoval(pid %d)", pid);
875 mServiceLog->add(log);
876
877 Vector<std::shared_ptr<IResourceManagerClient>> clients;
878 {
879 Mutex::Autolock lock(mLock);
880 if (!mProcessInfo->isValidPid(pid)) {
Chong Zhangc7303e82020-12-02 16:38:52 -0800881 pid_t callingPid = IPCThreadState::self()->getCallingPid();
882 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
883 pid, callingPid);
884 pid = callingPid;
Wonsik Kim271429d2020-10-01 10:12:56 -0700885 }
886
887 for (MediaResource::Type type : {MediaResource::Type::kSecureCodec,
888 MediaResource::Type::kNonSecureCodec,
889 MediaResource::Type::kGraphicMemory,
890 MediaResource::Type::kDrmSession}) {
891 std::shared_ptr<IResourceManagerClient> client;
892 if (getBiggestClient_l(pid, type, &client, true /* pendingRemovalOnly */)) {
893 clients.add(client);
894 break;
895 }
896 }
897 }
898
899 if (!clients.empty()) {
900 reclaimInternal(clients);
901 }
902 return Status::ok();
903}
904
Henry Fang32762922020-01-28 18:40:39 -0800905bool ResourceManagerService::getPriority_l(int pid, int* priority) {
906 int newPid = pid;
907
908 if (mOverridePidMap.find(pid) != mOverridePidMap.end()) {
909 newPid = mOverridePidMap[pid];
910 ALOGD("getPriority_l: use override pid %d instead original pid %d",
911 newPid, pid);
912 }
913
914 return mProcessInfo->getPriority(newPid, priority);
915}
916
Ronghua Wu231c3d12015-03-11 15:10:32 -0700917bool ResourceManagerService::getAllClients_l(
Chong Zhangfdd512a2019-11-22 11:03:14 -0800918 int callingPid, MediaResource::Type type,
919 Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
920 Vector<std::shared_ptr<IResourceManagerClient>> temp;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700921 for (size_t i = 0; i < mMap.size(); ++i) {
922 ResourceInfos &infos = mMap.editValueAt(i);
923 for (size_t j = 0; j < infos.size(); ++j) {
924 if (hasResourceType(type, infos[j].resources)) {
925 if (!isCallingPriorityHigher_l(callingPid, mMap.keyAt(i))) {
926 // some higher/equal priority process owns the resource,
927 // this request can't be fulfilled.
928 ALOGE("getAllClients_l: can't reclaim resource %s from pid %d",
Ronghua Wuea15fd22016-03-03 13:35:05 -0800929 asString(type), mMap.keyAt(i));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700930 return false;
931 }
932 temp.push_back(infos[j].client);
933 }
934 }
935 }
936 if (temp.size() == 0) {
Ronghua Wuea15fd22016-03-03 13:35:05 -0800937 ALOGV("getAllClients_l: didn't find any resource %s", asString(type));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700938 return true;
939 }
940 clients->appendVector(temp);
941 return true;
942}
943
944bool ResourceManagerService::getLowestPriorityBiggestClient_l(
Chong Zhangfdd512a2019-11-22 11:03:14 -0800945 int callingPid, MediaResource::Type type,
946 std::shared_ptr<IResourceManagerClient> *client) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700947 int lowestPriorityPid;
948 int lowestPriority;
949 int callingPriority;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700950
951 // Before looking into other processes, check if we have clients marked for
952 // pending removal in the same process.
953 if (getBiggestClient_l(callingPid, type, client, true /* pendingRemovalOnly */)) {
954 return true;
955 }
Henry Fang32762922020-01-28 18:40:39 -0800956 if (!getPriority_l(callingPid, &callingPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700957 ALOGE("getLowestPriorityBiggestClient_l: can't get process priority for pid %d",
958 callingPid);
959 return false;
960 }
961 if (!getLowestPriorityPid_l(type, &lowestPriorityPid, &lowestPriority)) {
962 return false;
963 }
964 if (lowestPriority <= callingPriority) {
965 ALOGE("getLowestPriorityBiggestClient_l: lowest priority %d vs caller priority %d",
966 lowestPriority, callingPriority);
967 return false;
968 }
969
970 if (!getBiggestClient_l(lowestPriorityPid, type, client)) {
971 return false;
972 }
973 return true;
974}
975
976bool ResourceManagerService::getLowestPriorityPid_l(
Ronghua Wuea15fd22016-03-03 13:35:05 -0800977 MediaResource::Type type, int *lowestPriorityPid, int *lowestPriority) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700978 int pid = -1;
979 int priority = -1;
980 for (size_t i = 0; i < mMap.size(); ++i) {
981 if (mMap.valueAt(i).size() == 0) {
982 // no client on this process.
983 continue;
984 }
985 if (!hasResourceType(type, mMap.valueAt(i))) {
986 // doesn't have the requested resource type
987 continue;
988 }
989 int tempPid = mMap.keyAt(i);
990 int tempPriority;
Henry Fang32762922020-01-28 18:40:39 -0800991 if (!getPriority_l(tempPid, &tempPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700992 ALOGV("getLowestPriorityPid_l: can't get priority of pid %d, skipped", tempPid);
993 // TODO: remove this pid from mMap?
994 continue;
995 }
996 if (pid == -1 || tempPriority > priority) {
997 // initial the value
998 pid = tempPid;
999 priority = tempPriority;
1000 }
1001 }
1002 if (pid != -1) {
1003 *lowestPriorityPid = pid;
1004 *lowestPriority = priority;
1005 }
1006 return (pid != -1);
1007}
1008
1009bool ResourceManagerService::isCallingPriorityHigher_l(int callingPid, int pid) {
1010 int callingPidPriority;
Henry Fang32762922020-01-28 18:40:39 -08001011 if (!getPriority_l(callingPid, &callingPidPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001012 return false;
1013 }
1014
1015 int priority;
Henry Fang32762922020-01-28 18:40:39 -08001016 if (!getPriority_l(pid, &priority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001017 return false;
1018 }
1019
1020 return (callingPidPriority < priority);
1021}
1022
1023bool ResourceManagerService::getBiggestClient_l(
Wonsik Kimd20e9362020-04-28 10:42:57 -07001024 int pid, MediaResource::Type type, std::shared_ptr<IResourceManagerClient> *client,
1025 bool pendingRemovalOnly) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001026 ssize_t index = mMap.indexOfKey(pid);
1027 if (index < 0) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001028 ALOGE_IF(!pendingRemovalOnly,
1029 "getBiggestClient_l: can't find resource info for pid %d", pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001030 return false;
1031 }
1032
Chong Zhangfdd512a2019-11-22 11:03:14 -08001033 std::shared_ptr<IResourceManagerClient> clientTemp;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001034 uint64_t largestValue = 0;
1035 const ResourceInfos &infos = mMap.valueAt(index);
1036 for (size_t i = 0; i < infos.size(); ++i) {
Chong Zhangfb092d32019-08-12 09:45:44 -07001037 const ResourceList &resources = infos[i].resources;
Wonsik Kimd20e9362020-04-28 10:42:57 -07001038 if (pendingRemovalOnly && !infos[i].pendingRemoval) {
1039 continue;
1040 }
Chong Zhangfb092d32019-08-12 09:45:44 -07001041 for (auto it = resources.begin(); it != resources.end(); it++) {
Chong Zhang181e6952019-10-09 13:23:39 -07001042 const MediaResourceParcel &resource = it->second;
1043 if (resource.type == type) {
1044 if (resource.value > largestValue) {
1045 largestValue = resource.value;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001046 clientTemp = infos[i].client;
1047 }
1048 }
1049 }
1050 }
1051
1052 if (clientTemp == NULL) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001053 ALOGE_IF(!pendingRemovalOnly,
1054 "getBiggestClient_l: can't find resource type %s for pid %d",
1055 asString(type), pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001056 return false;
1057 }
1058
1059 *client = clientTemp;
1060 return true;
1061}
1062
Ronghua Wu231c3d12015-03-11 15:10:32 -07001063} // namespace android