blob: 32ac583c7d0c2c4fce1c8b42ccac8eecec3a0a3e [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>
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
38#include "ResourceManagerService.h"
Chong Zhanga9d45c72020-09-09 12:41:17 -070039#include "ResourceObserverService.h"
Ronghua Wua8ec8fc2015-05-07 13:58:22 -070040#include "ServiceLog.h"
Chong Zhangee33d642019-08-08 14:26:43 -070041
Ronghua Wu231c3d12015-03-11 15:10:32 -070042namespace android {
43
Chong Zhang97d367b2020-09-16 12:53:14 -070044//static
45std::mutex ResourceManagerService::sCookieLock;
46//static
47uintptr_t ResourceManagerService::sCookieCounter = 0;
48//static
49std::map<uintptr_t, sp<DeathNotifier> > ResourceManagerService::sCookieToDeathNotifierMap;
50
51class DeathNotifier : public RefBase {
52public:
53 DeathNotifier(const std::shared_ptr<ResourceManagerService> &service,
54 int pid, int64_t clientId);
55
56 virtual ~DeathNotifier() {}
57
58 // Implement death recipient
59 static void BinderDiedCallback(void* cookie);
60 virtual void binderDied();
61
62protected:
63 std::weak_ptr<ResourceManagerService> mService;
64 int mPid;
65 int64_t mClientId;
66};
67
Chong Zhangfdd512a2019-11-22 11:03:14 -080068DeathNotifier::DeathNotifier(const std::shared_ptr<ResourceManagerService> &service,
69 int pid, int64_t clientId)
70 : mService(service), mPid(pid), mClientId(clientId) {}
Wonsik Kim3e378962017-01-05 17:00:02 +090071
Chong Zhangfdd512a2019-11-22 11:03:14 -080072//static
73void DeathNotifier::BinderDiedCallback(void* cookie) {
Chong Zhang97d367b2020-09-16 12:53:14 -070074 sp<DeathNotifier> notifier;
75 {
76 std::scoped_lock lock{ResourceManagerService::sCookieLock};
77 auto it = ResourceManagerService::sCookieToDeathNotifierMap.find(
78 reinterpret_cast<uintptr_t>(cookie));
79 if (it == ResourceManagerService::sCookieToDeathNotifierMap.end()) {
80 return;
81 }
82 notifier = it->second;
83 }
84 if (notifier.get() != nullptr) {
85 notifier->binderDied();
86 }
Chong Zhangfdd512a2019-11-22 11:03:14 -080087}
Wonsik Kim3e378962017-01-05 17:00:02 +090088
Chong Zhangfdd512a2019-11-22 11:03:14 -080089void DeathNotifier::binderDied() {
90 // Don't check for pid validity since we know it's already dead.
91 std::shared_ptr<ResourceManagerService> service = mService.lock();
92 if (service == nullptr) {
93 ALOGW("ResourceManagerService is dead as well.");
94 return;
Wonsik Kim3e378962017-01-05 17:00:02 +090095 }
Henry Fang32762922020-01-28 18:40:39 -080096
97 service->overridePid(mPid, -1);
Henry Fangb35141c2020-06-29 13:11:39 -070098 // thiz is freed in the call below, so it must be last call referring thiz
99 service->removeResource(mPid, mClientId, false);
Chong Zhang97d367b2020-09-16 12:53:14 -0700100}
Henry Fangb35141c2020-06-29 13:11:39 -0700101
Chong Zhang97d367b2020-09-16 12:53:14 -0700102class OverrideProcessInfoDeathNotifier : public DeathNotifier {
103public:
104 OverrideProcessInfoDeathNotifier(const std::shared_ptr<ResourceManagerService> &service,
105 int pid) : DeathNotifier(service, pid, 0) {}
106
107 virtual ~OverrideProcessInfoDeathNotifier() {}
108
109 virtual void binderDied();
110};
111
112void OverrideProcessInfoDeathNotifier::binderDied() {
113 // Don't check for pid validity since we know it's already dead.
114 std::shared_ptr<ResourceManagerService> service = mService.lock();
115 if (service == nullptr) {
116 ALOGW("ResourceManagerService is dead as well.");
117 return;
118 }
119
120 service->removeProcessInfoOverride(mPid);
Chong Zhangfdd512a2019-11-22 11:03:14 -0800121}
Wonsik Kim3e378962017-01-05 17:00:02 +0900122
Ronghua Wu231c3d12015-03-11 15:10:32 -0700123template <typename T>
Chong Zhang181e6952019-10-09 13:23:39 -0700124static String8 getString(const std::vector<T> &items) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700125 String8 itemsStr;
126 for (size_t i = 0; i < items.size(); ++i) {
Chong Zhang181e6952019-10-09 13:23:39 -0700127 itemsStr.appendFormat("%s ", toString(items[i]).string());
Ronghua Wu231c3d12015-03-11 15:10:32 -0700128 }
129 return itemsStr;
130}
131
Chong Zhangfb092d32019-08-12 09:45:44 -0700132static bool hasResourceType(MediaResource::Type type, const ResourceList& resources) {
133 for (auto it = resources.begin(); it != resources.end(); it++) {
Chong Zhang181e6952019-10-09 13:23:39 -0700134 if (it->second.type == type) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700135 return true;
136 }
137 }
138 return false;
139}
140
Chih-Hung Hsieh51873d82016-08-09 14:18:51 -0700141static bool hasResourceType(MediaResource::Type type, const ResourceInfos& infos) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700142 for (size_t i = 0; i < infos.size(); ++i) {
143 if (hasResourceType(type, infos[i].resources)) {
144 return true;
145 }
146 }
147 return false;
148}
149
150static ResourceInfos& getResourceInfosForEdit(
151 int pid,
152 PidResourceInfosMap& map) {
153 ssize_t index = map.indexOfKey(pid);
154 if (index < 0) {
155 // new pid
156 ResourceInfos infosForPid;
157 map.add(pid, infosForPid);
158 }
159
160 return map.editValueFor(pid);
161}
162
163static ResourceInfo& getResourceInfoForEdit(
Chong Zhangee33d642019-08-08 14:26:43 -0700164 uid_t uid,
Ronghua Wu231c3d12015-03-11 15:10:32 -0700165 int64_t clientId,
Chong Zhangfdd512a2019-11-22 11:03:14 -0800166 const std::shared_ptr<IResourceManagerClient>& client,
Ronghua Wu231c3d12015-03-11 15:10:32 -0700167 ResourceInfos& infos) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700168 ssize_t index = infos.indexOfKey(clientId);
169
170 if (index < 0) {
171 ResourceInfo info;
172 info.uid = uid;
173 info.clientId = clientId;
174 info.client = client;
Chong Zhang97d367b2020-09-16 12:53:14 -0700175 info.cookie = 0;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700176 info.pendingRemoval = false;
Chong Zhangfb092d32019-08-12 09:45:44 -0700177
178 index = infos.add(clientId, info);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700179 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700180
181 return infos.editValueAt(index);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700182}
183
Chong Zhang181e6952019-10-09 13:23:39 -0700184static void notifyResourceGranted(int pid, const std::vector<MediaResourceParcel> &resources) {
Dongwon Kangfe508d32015-12-15 14:22:05 +0900185 static const char* const kServiceName = "media_resource_monitor";
Dongwon Kang2642c842016-03-23 18:07:29 -0700186 sp<IBinder> binder = defaultServiceManager()->checkService(String16(kServiceName));
Dongwon Kangfe508d32015-12-15 14:22:05 +0900187 if (binder != NULL) {
188 sp<IMediaResourceMonitor> service = interface_cast<IMediaResourceMonitor>(binder);
189 for (size_t i = 0; i < resources.size(); ++i) {
Chong Zhang181e6952019-10-09 13:23:39 -0700190 if (resources[i].subType == MediaResource::SubType::kAudioCodec) {
Dongwon Kang69c23dd2016-03-22 15:22:45 -0700191 service->notifyResourceGranted(pid, IMediaResourceMonitor::TYPE_AUDIO_CODEC);
Chong Zhang181e6952019-10-09 13:23:39 -0700192 } else if (resources[i].subType == MediaResource::SubType::kVideoCodec) {
Dongwon Kang69c23dd2016-03-22 15:22:45 -0700193 service->notifyResourceGranted(pid, IMediaResourceMonitor::TYPE_VIDEO_CODEC);
194 }
Dongwon Kangfe508d32015-12-15 14:22:05 +0900195 }
196 }
197}
198
Chong Zhangfdd512a2019-11-22 11:03:14 -0800199binder_status_t ResourceManagerService::dump(
200 int fd, const char** /*args*/, uint32_t /*numArgs*/) {
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700201 String8 result;
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700202
dcashman014e91e2015-09-11 09:33:01 -0700203 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
204 result.format("Permission Denial: "
205 "can't dump ResourceManagerService from pid=%d, uid=%d\n",
Chong Zhangfdd512a2019-11-22 11:03:14 -0800206 AIBinder_getCallingPid(),
207 AIBinder_getCallingUid());
dcashman014e91e2015-09-11 09:33:01 -0700208 write(fd, result.string(), result.size());
209 return PERMISSION_DENIED;
210 }
211
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700212 PidResourceInfosMap mapCopy;
213 bool supportsMultipleSecureCodecs;
214 bool supportsSecureWithNonSecureCodec;
Henry Fang32762922020-01-28 18:40:39 -0800215 std::map<int, int> overridePidMapCopy;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700216 String8 serviceLog;
217 {
218 Mutex::Autolock lock(mLock);
219 mapCopy = mMap; // Shadow copy, real copy will happen on write.
220 supportsMultipleSecureCodecs = mSupportsMultipleSecureCodecs;
221 supportsSecureWithNonSecureCodec = mSupportsSecureWithNonSecureCodec;
222 serviceLog = mServiceLog->toString(" " /* linePrefix */);
Henry Fang32762922020-01-28 18:40:39 -0800223 overridePidMapCopy = mOverridePidMap;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700224 }
225
226 const size_t SIZE = 256;
227 char buffer[SIZE];
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700228 snprintf(buffer, SIZE, "ResourceManagerService: %p\n", this);
229 result.append(buffer);
230 result.append(" Policies:\n");
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700231 snprintf(buffer, SIZE, " SupportsMultipleSecureCodecs: %d\n", supportsMultipleSecureCodecs);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700232 result.append(buffer);
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700233 snprintf(buffer, SIZE, " SupportsSecureWithNonSecureCodec: %d\n",
234 supportsSecureWithNonSecureCodec);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700235 result.append(buffer);
236
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700237 result.append(" Processes:\n");
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700238 for (size_t i = 0; i < mapCopy.size(); ++i) {
239 snprintf(buffer, SIZE, " Pid: %d\n", mapCopy.keyAt(i));
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700240 result.append(buffer);
241
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700242 const ResourceInfos &infos = mapCopy.valueAt(i);
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700243 for (size_t j = 0; j < infos.size(); ++j) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700244 result.append(" Client:\n");
Ronghua Wu8f9dd872015-04-23 15:24:25 -0700245 snprintf(buffer, SIZE, " Id: %lld\n", (long long)infos[j].clientId);
246 result.append(buffer);
247
Chong Zhang181e6952019-10-09 13:23:39 -0700248 std::string clientName;
249 Status status = infos[j].client->getName(&clientName);
250 if (!status.isOk()) {
251 clientName = "<unknown client>";
252 }
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)) {
425 ALOGE("Rejected addResource call with invalid pid.");
Chong Zhang181e6952019-10-09 13:23:39 -0700426 return Status::fromServiceSpecificError(BAD_VALUE);
Ronghua Wud11c43a2016-01-27 16:26:12 -0800427 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700428 ResourceInfos& infos = getResourceInfosForEdit(pid, mMap);
Chong Zhangee33d642019-08-08 14:26:43 -0700429 ResourceInfo& info = getResourceInfoForEdit(uid, clientId, client, infos);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700430 ResourceList resourceAdded;
Chong Zhang79d2b282018-04-17 14:14:31 -0700431
432 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700433 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700434 const auto resType = std::tuple(res.type, res.subType, res.id);
435
436 if (res.value < 0 && res.type != MediaResource::Type::kDrmSession) {
437 ALOGW("Ignoring request to remove negative value of non-drm resource");
438 continue;
439 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700440 if (info.resources.find(resType) == info.resources.end()) {
Chong Zhang181e6952019-10-09 13:23:39 -0700441 if (res.value <= 0) {
442 // We can't init a new entry with negative value, although it's allowed
443 // to merge in negative values after the initial add.
444 ALOGW("Ignoring request to add new resource entry with value <= 0");
445 continue;
446 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700447 onFirstAdded(res, info);
448 info.resources[resType] = res;
Chong Zhangfb092d32019-08-12 09:45:44 -0700449 } else {
Robert Shihc3af31b2019-09-20 21:45:01 -0700450 mergeResources(info.resources[resType], res);
Chong Zhang79d2b282018-04-17 14:14:31 -0700451 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700452 // Add it to the list of added resources for observers.
453 auto it = resourceAdded.find(resType);
454 if (it == resourceAdded.end()) {
455 resourceAdded[resType] = res;
456 } else {
457 mergeResources(it->second, res);
458 }
Chong Zhang79d2b282018-04-17 14:14:31 -0700459 }
Chong Zhang97d367b2020-09-16 12:53:14 -0700460 if (info.cookie == 0 && client != nullptr) {
461 info.cookie = addCookieAndLink_l(client->asBinder(),
462 new DeathNotifier(ref<ResourceManagerService>(), pid, clientId));
Wonsik Kim3e378962017-01-05 17:00:02 +0900463 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700464 if (mObserverService != nullptr && !resourceAdded.empty()) {
465 mObserverService->onResourceAdded(uid, pid, resourceAdded);
466 }
Dongwon Kangfe508d32015-12-15 14:22:05 +0900467 notifyResourceGranted(pid, resources);
Chong Zhang181e6952019-10-09 13:23:39 -0700468 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700469}
470
Chong Zhang181e6952019-10-09 13:23:39 -0700471Status ResourceManagerService::removeResource(
472 int32_t pid, int64_t clientId,
473 const std::vector<MediaResourceParcel>& resources) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700474 String8 log = String8::format("removeResource(pid %d, clientId %lld, resources %s)",
475 pid, (long long) clientId, getString(resources).string());
476 mServiceLog->add(log);
477
478 Mutex::Autolock lock(mLock);
479 if (!mProcessInfo->isValidPid(pid)) {
480 ALOGE("Rejected removeResource call with invalid pid.");
Chong Zhang181e6952019-10-09 13:23:39 -0700481 return Status::fromServiceSpecificError(BAD_VALUE);
Chong Zhangfb092d32019-08-12 09:45:44 -0700482 }
483 ssize_t index = mMap.indexOfKey(pid);
484 if (index < 0) {
485 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700486 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700487 }
488 ResourceInfos &infos = mMap.editValueAt(index);
489
490 index = infos.indexOfKey(clientId);
491 if (index < 0) {
492 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700493 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700494 }
495
496 ResourceInfo &info = infos.editValueAt(index);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700497 ResourceList resourceRemoved;
Chong Zhangfb092d32019-08-12 09:45:44 -0700498 for (size_t i = 0; i < resources.size(); ++i) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700499 const auto &res = resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700500 const auto resType = std::tuple(res.type, res.subType, res.id);
501
502 if (res.value < 0) {
503 ALOGW("Ignoring request to remove negative value of resource");
504 continue;
505 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700506 // ignore if we don't have it
507 if (info.resources.find(resType) != info.resources.end()) {
Chong Zhang181e6952019-10-09 13:23:39 -0700508 MediaResourceParcel &resource = info.resources[resType];
Chong Zhanga9d45c72020-09-09 12:41:17 -0700509 MediaResourceParcel actualRemoved = res;
Chong Zhang181e6952019-10-09 13:23:39 -0700510 if (resource.value > res.value) {
511 resource.value -= res.value;
Chong Zhangfb092d32019-08-12 09:45:44 -0700512 } else {
Robert Shihc3af31b2019-09-20 21:45:01 -0700513 onLastRemoved(res, info);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700514 actualRemoved.value = resource.value;
Chong Zhang102b3e32020-11-02 12:21:50 -0800515 info.resources.erase(resType);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700516 }
517
518 // Add it to the list of removed resources for observers.
519 auto it = resourceRemoved.find(resType);
520 if (it == resourceRemoved.end()) {
521 resourceRemoved[resType] = actualRemoved;
522 } else {
523 mergeResources(it->second, actualRemoved);
Chong Zhangfb092d32019-08-12 09:45:44 -0700524 }
525 }
526 }
Chong Zhanga9d45c72020-09-09 12:41:17 -0700527 if (mObserverService != nullptr && !resourceRemoved.empty()) {
528 mObserverService->onResourceRemoved(info.uid, pid, resourceRemoved);
529 }
Chong Zhang181e6952019-10-09 13:23:39 -0700530 return Status::ok();
Chong Zhangfb092d32019-08-12 09:45:44 -0700531}
532
Chong Zhang181e6952019-10-09 13:23:39 -0700533Status ResourceManagerService::removeClient(int32_t pid, int64_t clientId) {
Wonsik Kim3e378962017-01-05 17:00:02 +0900534 removeResource(pid, clientId, true);
Chong Zhang181e6952019-10-09 13:23:39 -0700535 return Status::ok();
Wonsik Kim3e378962017-01-05 17:00:02 +0900536}
537
Chong Zhang181e6952019-10-09 13:23:39 -0700538Status ResourceManagerService::removeResource(int pid, int64_t clientId, bool checkValid) {
Ronghua Wu37c89242015-07-15 12:23:48 -0700539 String8 log = String8::format(
540 "removeResource(pid %d, clientId %lld)",
541 pid, (long long) clientId);
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700542 mServiceLog->add(log);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700543
544 Mutex::Autolock lock(mLock);
Wonsik Kim3e378962017-01-05 17:00:02 +0900545 if (checkValid && !mProcessInfo->isValidPid(pid)) {
Ronghua Wud11c43a2016-01-27 16:26:12 -0800546 ALOGE("Rejected removeResource call with invalid pid.");
Chong Zhang181e6952019-10-09 13:23:39 -0700547 return Status::fromServiceSpecificError(BAD_VALUE);
Ronghua Wud11c43a2016-01-27 16:26:12 -0800548 }
Ronghua Wu37c89242015-07-15 12:23:48 -0700549 ssize_t index = mMap.indexOfKey(pid);
550 if (index < 0) {
551 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700552 return Status::ok();
Ronghua Wu37c89242015-07-15 12:23:48 -0700553 }
Ronghua Wu37c89242015-07-15 12:23:48 -0700554 ResourceInfos &infos = mMap.editValueAt(index);
Chong Zhangfb092d32019-08-12 09:45:44 -0700555
556 index = infos.indexOfKey(clientId);
557 if (index < 0) {
558 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
Chong Zhang181e6952019-10-09 13:23:39 -0700559 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700560 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700561
562 const ResourceInfo &info = infos[index];
563 for (auto it = info.resources.begin(); it != info.resources.end(); it++) {
564 onLastRemoved(it->second, info);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700565 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700566
Chong Zhang97d367b2020-09-16 12:53:14 -0700567 removeCookieAndUnlink_l(info.client->asBinder(), info.cookie);
Chong Zhangfb092d32019-08-12 09:45:44 -0700568
Chong Zhanga9d45c72020-09-09 12:41:17 -0700569 if (mObserverService != nullptr && !info.resources.empty()) {
570 mObserverService->onResourceRemoved(info.uid, pid, info.resources);
571 }
572
Chong Zhangfb092d32019-08-12 09:45:44 -0700573 infos.removeItemsAt(index);
Chong Zhang181e6952019-10-09 13:23:39 -0700574 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700575}
576
Ronghua Wu05d89f12015-07-07 16:47:42 -0700577void ResourceManagerService::getClientForResource_l(
Chong Zhangfdd512a2019-11-22 11:03:14 -0800578 int callingPid, const MediaResourceParcel *res,
579 Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700580 if (res == NULL) {
581 return;
582 }
Chong Zhangfdd512a2019-11-22 11:03:14 -0800583 std::shared_ptr<IResourceManagerClient> client;
Chong Zhang181e6952019-10-09 13:23:39 -0700584 if (getLowestPriorityBiggestClient_l(callingPid, res->type, &client)) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700585 clients->push_back(client);
586 }
587}
588
Chong Zhang181e6952019-10-09 13:23:39 -0700589Status ResourceManagerService::reclaimResource(
590 int32_t callingPid,
591 const std::vector<MediaResourceParcel>& resources,
592 bool* _aidl_return) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700593 String8 log = String8::format("reclaimResource(callingPid %d, resources %s)",
Ronghua Wu231c3d12015-03-11 15:10:32 -0700594 callingPid, getString(resources).string());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700595 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700596 *_aidl_return = false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700597
Chong Zhangfdd512a2019-11-22 11:03:14 -0800598 Vector<std::shared_ptr<IResourceManagerClient>> clients;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700599 {
600 Mutex::Autolock lock(mLock);
Ronghua Wud11c43a2016-01-27 16:26:12 -0800601 if (!mProcessInfo->isValidPid(callingPid)) {
602 ALOGE("Rejected reclaimResource call with invalid callingPid.");
Chong Zhang181e6952019-10-09 13:23:39 -0700603 return Status::fromServiceSpecificError(BAD_VALUE);
Ronghua Wud11c43a2016-01-27 16:26:12 -0800604 }
Chong Zhang181e6952019-10-09 13:23:39 -0700605 const MediaResourceParcel *secureCodec = NULL;
606 const MediaResourceParcel *nonSecureCodec = NULL;
607 const MediaResourceParcel *graphicMemory = NULL;
608 const MediaResourceParcel *drmSession = NULL;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700609 for (size_t i = 0; i < resources.size(); ++i) {
Chong Zhang181e6952019-10-09 13:23:39 -0700610 MediaResource::Type type = resources[i].type;
611 if (resources[i].type == MediaResource::Type::kSecureCodec) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700612 secureCodec = &resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700613 } else if (type == MediaResource::Type::kNonSecureCodec) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700614 nonSecureCodec = &resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700615 } else if (type == MediaResource::Type::kGraphicMemory) {
Ronghua Wu05d89f12015-07-07 16:47:42 -0700616 graphicMemory = &resources[i];
Chong Zhang181e6952019-10-09 13:23:39 -0700617 } else if (type == MediaResource::Type::kDrmSession) {
Robert Shihc3af31b2019-09-20 21:45:01 -0700618 drmSession = &resources[i];
Ronghua Wu05d89f12015-07-07 16:47:42 -0700619 }
620 }
621
622 // first pass to handle secure/non-secure codec conflict
623 if (secureCodec != NULL) {
624 if (!mSupportsMultipleSecureCodecs) {
Chong Zhang181e6952019-10-09 13:23:39 -0700625 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec, &clients)) {
626 return Status::ok();
Ronghua Wu05d89f12015-07-07 16:47:42 -0700627 }
628 }
629 if (!mSupportsSecureWithNonSecureCodec) {
Chong Zhang181e6952019-10-09 13:23:39 -0700630 if (!getAllClients_l(callingPid, MediaResource::Type::kNonSecureCodec, &clients)) {
631 return Status::ok();
Ronghua Wu05d89f12015-07-07 16:47:42 -0700632 }
633 }
634 }
635 if (nonSecureCodec != NULL) {
636 if (!mSupportsSecureWithNonSecureCodec) {
Chong Zhang181e6952019-10-09 13:23:39 -0700637 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec, &clients)) {
638 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700639 }
640 }
641 }
Robert Shihc3af31b2019-09-20 21:45:01 -0700642 if (drmSession != NULL) {
643 getClientForResource_l(callingPid, drmSession, &clients);
644 if (clients.size() == 0) {
Chong Zhang181e6952019-10-09 13:23:39 -0700645 return Status::ok();
Robert Shihc3af31b2019-09-20 21:45:01 -0700646 }
647 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700648
649 if (clients.size() == 0) {
650 // if no secure/non-secure codec conflict, run second pass to handle other resources.
Ronghua Wu05d89f12015-07-07 16:47:42 -0700651 getClientForResource_l(callingPid, graphicMemory, &clients);
Ronghua Wu231c3d12015-03-11 15:10:32 -0700652 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700653
654 if (clients.size() == 0) {
655 // if we are here, run the third pass to free one codec with the same type.
Ronghua Wu05d89f12015-07-07 16:47:42 -0700656 getClientForResource_l(callingPid, secureCodec, &clients);
657 getClientForResource_l(callingPid, nonSecureCodec, &clients);
658 }
659
660 if (clients.size() == 0) {
661 // if we are here, run the fourth pass to free one codec with the different type.
662 if (secureCodec != NULL) {
Chong Zhang181e6952019-10-09 13:23:39 -0700663 MediaResource temp(MediaResource::Type::kNonSecureCodec, 1);
Ronghua Wu05d89f12015-07-07 16:47:42 -0700664 getClientForResource_l(callingPid, &temp, &clients);
665 }
666 if (nonSecureCodec != NULL) {
Chong Zhang181e6952019-10-09 13:23:39 -0700667 MediaResource temp(MediaResource::Type::kSecureCodec, 1);
Ronghua Wu05d89f12015-07-07 16:47:42 -0700668 getClientForResource_l(callingPid, &temp, &clients);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700669 }
670 }
Ronghua Wu231c3d12015-03-11 15:10:32 -0700671 }
672
Wonsik Kim271429d2020-10-01 10:12:56 -0700673 *_aidl_return = reclaimInternal(clients);
674 return Status::ok();
675}
676
677bool ResourceManagerService::reclaimInternal(
678 const Vector<std::shared_ptr<IResourceManagerClient>> &clients) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700679 if (clients.size() == 0) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700680 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700681 }
682
Chong Zhangfdd512a2019-11-22 11:03:14 -0800683 std::shared_ptr<IResourceManagerClient> failedClient;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700684 for (size_t i = 0; i < clients.size(); ++i) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700685 String8 log = String8::format("reclaimResource from client %p", clients[i].get());
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700686 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700687 bool success;
688 Status status = clients[i]->reclaimResource(&success);
689 if (!status.isOk() || !success) {
Ronghua Wu67e7f542015-03-13 10:47:08 -0700690 failedClient = clients[i];
691 break;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700692 }
693 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700694
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700695 if (failedClient == NULL) {
Wonsik Kim271429d2020-10-01 10:12:56 -0700696 return true;
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700697 }
698
Ronghua Wu67e7f542015-03-13 10:47:08 -0700699 {
700 Mutex::Autolock lock(mLock);
701 bool found = false;
702 for (size_t i = 0; i < mMap.size(); ++i) {
703 ResourceInfos &infos = mMap.editValueAt(i);
704 for (size_t j = 0; j < infos.size();) {
705 if (infos[j].client == failedClient) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700706 j = infos.removeItemsAt(j);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700707 found = true;
708 } else {
709 ++j;
710 }
711 }
712 if (found) {
713 break;
714 }
715 }
716 if (!found) {
717 ALOGV("didn't find failed client");
718 }
719 }
720
Wonsik Kim271429d2020-10-01 10:12:56 -0700721 return false;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700722}
723
Henry Fang32762922020-01-28 18:40:39 -0800724Status ResourceManagerService::overridePid(
725 int originalPid,
726 int newPid) {
727 String8 log = String8::format("overridePid(originalPid %d, newPid %d)",
728 originalPid, newPid);
729 mServiceLog->add(log);
730
731 // allow if this is called from the same process or the process has
732 // permission.
733 if ((AIBinder_getCallingPid() != getpid()) &&
734 (checkCallingPermission(String16(
735 "android.permission.MEDIA_RESOURCE_OVERRIDE_PID")) == false)) {
736 ALOGE(
737 "Permission Denial: can't access overridePid method from pid=%d, "
738 "self pid=%d\n",
739 AIBinder_getCallingPid(), getpid());
740 return Status::fromServiceSpecificError(PERMISSION_DENIED);
741 }
742
743 {
744 Mutex::Autolock lock(mLock);
745 mOverridePidMap.erase(originalPid);
746 if (newPid != -1) {
747 mOverridePidMap.emplace(originalPid, newPid);
748 }
749 }
750
751 return Status::ok();
752}
753
Chong Zhang97d367b2020-09-16 12:53:14 -0700754Status ResourceManagerService::overrideProcessInfo(
755 const std::shared_ptr<IResourceManagerClient>& client,
756 int pid,
757 int procState,
758 int oomScore) {
759 String8 log = String8::format("overrideProcessInfo(pid %d, procState %d, oomScore %d)",
760 pid, procState, oomScore);
761 mServiceLog->add(log);
762
763 // Only allow the override if the caller already can access process state and oom scores.
764 int callingPid = AIBinder_getCallingPid();
765 if (callingPid != getpid() && (callingPid != pid || !checkCallingPermission(String16(
766 "android.permission.GET_PROCESS_STATE_AND_OOM_SCORE")))) {
767 ALOGE("Permission Denial: overrideProcessInfo method from pid=%d", callingPid);
768 return Status::fromServiceSpecificError(PERMISSION_DENIED);
769 }
770
771 if (client == nullptr) {
772 return Status::fromServiceSpecificError(BAD_VALUE);
773 }
774
775 Mutex::Autolock lock(mLock);
776 removeProcessInfoOverride_l(pid);
777
778 if (!mProcessInfo->overrideProcessInfo(pid, procState, oomScore)) {
779 // Override value is rejected by ProcessInfo.
780 return Status::fromServiceSpecificError(BAD_VALUE);
781 }
782
783 uintptr_t cookie = addCookieAndLink_l(client->asBinder(),
784 new OverrideProcessInfoDeathNotifier(ref<ResourceManagerService>(), pid));
785
786 mProcessInfoOverrideMap.emplace(pid, ProcessInfoOverride{cookie, client});
787
788 return Status::ok();
789}
790
791uintptr_t ResourceManagerService::addCookieAndLink_l(
792 ::ndk::SpAIBinder binder, const sp<DeathNotifier>& notifier) {
793 std::scoped_lock lock{sCookieLock};
794
795 uintptr_t cookie;
796 // Need to skip cookie 0 (if it wraps around). ResourceInfo has cookie initialized to 0
797 // indicating the death notifier is not created yet.
798 while ((cookie = ++sCookieCounter) == 0);
799 AIBinder_linkToDeath(binder.get(), mDeathRecipient.get(), (void*)cookie);
800 sCookieToDeathNotifierMap.emplace(cookie, notifier);
801
802 return cookie;
803}
804
805void ResourceManagerService::removeCookieAndUnlink_l(
806 ::ndk::SpAIBinder binder, uintptr_t cookie) {
807 std::scoped_lock lock{sCookieLock};
808 AIBinder_unlinkToDeath(binder.get(), mDeathRecipient.get(), (void*)cookie);
809 sCookieToDeathNotifierMap.erase(cookie);
810}
811
812void ResourceManagerService::removeProcessInfoOverride(int pid) {
813 Mutex::Autolock lock(mLock);
814
815 removeProcessInfoOverride_l(pid);
816}
817
818void ResourceManagerService::removeProcessInfoOverride_l(int pid) {
819 auto it = mProcessInfoOverrideMap.find(pid);
820 if (it == mProcessInfoOverrideMap.end()) {
821 return;
822 }
823
824 mProcessInfo->removeProcessInfoOverride(pid);
825
826 removeCookieAndUnlink_l(it->second.client->asBinder(), it->second.cookie);
827
828 mProcessInfoOverrideMap.erase(pid);
829}
830
Wonsik Kimd20e9362020-04-28 10:42:57 -0700831Status ResourceManagerService::markClientForPendingRemoval(int32_t pid, int64_t clientId) {
832 String8 log = String8::format(
833 "markClientForPendingRemoval(pid %d, clientId %lld)",
834 pid, (long long) clientId);
835 mServiceLog->add(log);
836
837 Mutex::Autolock lock(mLock);
838 if (!mProcessInfo->isValidPid(pid)) {
839 ALOGE("Rejected markClientForPendingRemoval call with invalid pid.");
840 return Status::fromServiceSpecificError(BAD_VALUE);
841 }
842 ssize_t index = mMap.indexOfKey(pid);
843 if (index < 0) {
844 ALOGV("markClientForPendingRemoval: didn't find pid %d for clientId %lld",
845 pid, (long long)clientId);
846 return Status::ok();
847 }
848 ResourceInfos &infos = mMap.editValueAt(index);
849
850 index = infos.indexOfKey(clientId);
851 if (index < 0) {
852 ALOGV("markClientForPendingRemoval: didn't find clientId %lld", (long long) clientId);
853 return Status::ok();
854 }
855
856 ResourceInfo &info = infos.editValueAt(index);
857 info.pendingRemoval = true;
858 return Status::ok();
859}
860
Wonsik Kim271429d2020-10-01 10:12:56 -0700861Status ResourceManagerService::reclaimResourcesFromClientsPendingRemoval(int32_t pid) {
862 String8 log = String8::format("reclaimResourcesFromClientsPendingRemoval(pid %d)", pid);
863 mServiceLog->add(log);
864
865 Vector<std::shared_ptr<IResourceManagerClient>> clients;
866 {
867 Mutex::Autolock lock(mLock);
868 if (!mProcessInfo->isValidPid(pid)) {
869 ALOGE("Rejected reclaimResourcesFromClientsPendingRemoval call with invalid pid.");
870 return Status::fromServiceSpecificError(BAD_VALUE);
871 }
872
873 for (MediaResource::Type type : {MediaResource::Type::kSecureCodec,
874 MediaResource::Type::kNonSecureCodec,
875 MediaResource::Type::kGraphicMemory,
876 MediaResource::Type::kDrmSession}) {
877 std::shared_ptr<IResourceManagerClient> client;
878 if (getBiggestClient_l(pid, type, &client, true /* pendingRemovalOnly */)) {
879 clients.add(client);
880 break;
881 }
882 }
883 }
884
885 if (!clients.empty()) {
886 reclaimInternal(clients);
887 }
888 return Status::ok();
889}
890
Henry Fang32762922020-01-28 18:40:39 -0800891bool ResourceManagerService::getPriority_l(int pid, int* priority) {
892 int newPid = pid;
893
894 if (mOverridePidMap.find(pid) != mOverridePidMap.end()) {
895 newPid = mOverridePidMap[pid];
896 ALOGD("getPriority_l: use override pid %d instead original pid %d",
897 newPid, pid);
898 }
899
900 return mProcessInfo->getPriority(newPid, priority);
901}
902
Ronghua Wu231c3d12015-03-11 15:10:32 -0700903bool ResourceManagerService::getAllClients_l(
Chong Zhangfdd512a2019-11-22 11:03:14 -0800904 int callingPid, MediaResource::Type type,
905 Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
906 Vector<std::shared_ptr<IResourceManagerClient>> temp;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700907 for (size_t i = 0; i < mMap.size(); ++i) {
908 ResourceInfos &infos = mMap.editValueAt(i);
909 for (size_t j = 0; j < infos.size(); ++j) {
910 if (hasResourceType(type, infos[j].resources)) {
911 if (!isCallingPriorityHigher_l(callingPid, mMap.keyAt(i))) {
912 // some higher/equal priority process owns the resource,
913 // this request can't be fulfilled.
914 ALOGE("getAllClients_l: can't reclaim resource %s from pid %d",
Ronghua Wuea15fd22016-03-03 13:35:05 -0800915 asString(type), mMap.keyAt(i));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700916 return false;
917 }
918 temp.push_back(infos[j].client);
919 }
920 }
921 }
922 if (temp.size() == 0) {
Ronghua Wuea15fd22016-03-03 13:35:05 -0800923 ALOGV("getAllClients_l: didn't find any resource %s", asString(type));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700924 return true;
925 }
926 clients->appendVector(temp);
927 return true;
928}
929
930bool ResourceManagerService::getLowestPriorityBiggestClient_l(
Chong Zhangfdd512a2019-11-22 11:03:14 -0800931 int callingPid, MediaResource::Type type,
932 std::shared_ptr<IResourceManagerClient> *client) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700933 int lowestPriorityPid;
934 int lowestPriority;
935 int callingPriority;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700936
937 // Before looking into other processes, check if we have clients marked for
938 // pending removal in the same process.
939 if (getBiggestClient_l(callingPid, type, client, true /* pendingRemovalOnly */)) {
940 return true;
941 }
Henry Fang32762922020-01-28 18:40:39 -0800942 if (!getPriority_l(callingPid, &callingPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700943 ALOGE("getLowestPriorityBiggestClient_l: can't get process priority for pid %d",
944 callingPid);
945 return false;
946 }
947 if (!getLowestPriorityPid_l(type, &lowestPriorityPid, &lowestPriority)) {
948 return false;
949 }
950 if (lowestPriority <= callingPriority) {
951 ALOGE("getLowestPriorityBiggestClient_l: lowest priority %d vs caller priority %d",
952 lowestPriority, callingPriority);
953 return false;
954 }
955
956 if (!getBiggestClient_l(lowestPriorityPid, type, client)) {
957 return false;
958 }
959 return true;
960}
961
962bool ResourceManagerService::getLowestPriorityPid_l(
Ronghua Wuea15fd22016-03-03 13:35:05 -0800963 MediaResource::Type type, int *lowestPriorityPid, int *lowestPriority) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700964 int pid = -1;
965 int priority = -1;
966 for (size_t i = 0; i < mMap.size(); ++i) {
967 if (mMap.valueAt(i).size() == 0) {
968 // no client on this process.
969 continue;
970 }
971 if (!hasResourceType(type, mMap.valueAt(i))) {
972 // doesn't have the requested resource type
973 continue;
974 }
975 int tempPid = mMap.keyAt(i);
976 int tempPriority;
Henry Fang32762922020-01-28 18:40:39 -0800977 if (!getPriority_l(tempPid, &tempPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700978 ALOGV("getLowestPriorityPid_l: can't get priority of pid %d, skipped", tempPid);
979 // TODO: remove this pid from mMap?
980 continue;
981 }
982 if (pid == -1 || tempPriority > priority) {
983 // initial the value
984 pid = tempPid;
985 priority = tempPriority;
986 }
987 }
988 if (pid != -1) {
989 *lowestPriorityPid = pid;
990 *lowestPriority = priority;
991 }
992 return (pid != -1);
993}
994
995bool ResourceManagerService::isCallingPriorityHigher_l(int callingPid, int pid) {
996 int callingPidPriority;
Henry Fang32762922020-01-28 18:40:39 -0800997 if (!getPriority_l(callingPid, &callingPidPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700998 return false;
999 }
1000
1001 int priority;
Henry Fang32762922020-01-28 18:40:39 -08001002 if (!getPriority_l(pid, &priority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001003 return false;
1004 }
1005
1006 return (callingPidPriority < priority);
1007}
1008
1009bool ResourceManagerService::getBiggestClient_l(
Wonsik Kimd20e9362020-04-28 10:42:57 -07001010 int pid, MediaResource::Type type, std::shared_ptr<IResourceManagerClient> *client,
1011 bool pendingRemovalOnly) {
Ronghua Wu231c3d12015-03-11 15:10:32 -07001012 ssize_t index = mMap.indexOfKey(pid);
1013 if (index < 0) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001014 ALOGE_IF(!pendingRemovalOnly,
1015 "getBiggestClient_l: can't find resource info for pid %d", pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001016 return false;
1017 }
1018
Chong Zhangfdd512a2019-11-22 11:03:14 -08001019 std::shared_ptr<IResourceManagerClient> clientTemp;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001020 uint64_t largestValue = 0;
1021 const ResourceInfos &infos = mMap.valueAt(index);
1022 for (size_t i = 0; i < infos.size(); ++i) {
Chong Zhangfb092d32019-08-12 09:45:44 -07001023 const ResourceList &resources = infos[i].resources;
Wonsik Kimd20e9362020-04-28 10:42:57 -07001024 if (pendingRemovalOnly && !infos[i].pendingRemoval) {
1025 continue;
1026 }
Chong Zhangfb092d32019-08-12 09:45:44 -07001027 for (auto it = resources.begin(); it != resources.end(); it++) {
Chong Zhang181e6952019-10-09 13:23:39 -07001028 const MediaResourceParcel &resource = it->second;
1029 if (resource.type == type) {
1030 if (resource.value > largestValue) {
1031 largestValue = resource.value;
Ronghua Wu231c3d12015-03-11 15:10:32 -07001032 clientTemp = infos[i].client;
1033 }
1034 }
1035 }
1036 }
1037
1038 if (clientTemp == NULL) {
Wonsik Kim271429d2020-10-01 10:12:56 -07001039 ALOGE_IF(!pendingRemovalOnly,
1040 "getBiggestClient_l: can't find resource type %s for pid %d",
1041 asString(type), pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001042 return false;
1043 }
1044
1045 *client = clientTemp;
1046 return true;
1047}
1048
Ronghua Wu231c3d12015-03-11 15:10:32 -07001049} // namespace android