blob: 90a04acf93622d79df0d3a265df247c3bb05f0ea [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 Zhangfb092d32019-08-12 09:45:44 -0700514 info.resources.erase(resType);
Chong Zhanga9d45c72020-09-09 12:41:17 -0700515 actualRemoved.value = resource.value;
516 }
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
673 if (clients.size() == 0) {
Chong Zhang181e6952019-10-09 13:23:39 -0700674 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700675 }
676
Chong Zhangfdd512a2019-11-22 11:03:14 -0800677 std::shared_ptr<IResourceManagerClient> failedClient;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700678 for (size_t i = 0; i < clients.size(); ++i) {
Ronghua Wua8ec8fc2015-05-07 13:58:22 -0700679 log = String8::format("reclaimResource from client %p", clients[i].get());
680 mServiceLog->add(log);
Chong Zhang181e6952019-10-09 13:23:39 -0700681 bool success;
682 Status status = clients[i]->reclaimResource(&success);
683 if (!status.isOk() || !success) {
Ronghua Wu67e7f542015-03-13 10:47:08 -0700684 failedClient = clients[i];
685 break;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700686 }
687 }
Ronghua Wu67e7f542015-03-13 10:47:08 -0700688
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700689 if (failedClient == NULL) {
Chong Zhang181e6952019-10-09 13:23:39 -0700690 *_aidl_return = true;
691 return Status::ok();
Ronghua Wu76d4c7f2015-10-23 15:01:53 -0700692 }
693
Ronghua Wu67e7f542015-03-13 10:47:08 -0700694 {
695 Mutex::Autolock lock(mLock);
696 bool found = false;
697 for (size_t i = 0; i < mMap.size(); ++i) {
698 ResourceInfos &infos = mMap.editValueAt(i);
699 for (size_t j = 0; j < infos.size();) {
700 if (infos[j].client == failedClient) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700701 j = infos.removeItemsAt(j);
Ronghua Wu67e7f542015-03-13 10:47:08 -0700702 found = true;
703 } else {
704 ++j;
705 }
706 }
707 if (found) {
708 break;
709 }
710 }
711 if (!found) {
712 ALOGV("didn't find failed client");
713 }
714 }
715
Chong Zhang181e6952019-10-09 13:23:39 -0700716 return Status::ok();
Ronghua Wu231c3d12015-03-11 15:10:32 -0700717}
718
Henry Fang32762922020-01-28 18:40:39 -0800719Status ResourceManagerService::overridePid(
720 int originalPid,
721 int newPid) {
722 String8 log = String8::format("overridePid(originalPid %d, newPid %d)",
723 originalPid, newPid);
724 mServiceLog->add(log);
725
726 // allow if this is called from the same process or the process has
727 // permission.
728 if ((AIBinder_getCallingPid() != getpid()) &&
729 (checkCallingPermission(String16(
730 "android.permission.MEDIA_RESOURCE_OVERRIDE_PID")) == false)) {
731 ALOGE(
732 "Permission Denial: can't access overridePid method from pid=%d, "
733 "self pid=%d\n",
734 AIBinder_getCallingPid(), getpid());
735 return Status::fromServiceSpecificError(PERMISSION_DENIED);
736 }
737
738 {
739 Mutex::Autolock lock(mLock);
740 mOverridePidMap.erase(originalPid);
741 if (newPid != -1) {
742 mOverridePidMap.emplace(originalPid, newPid);
743 }
744 }
745
746 return Status::ok();
747}
748
Chong Zhang97d367b2020-09-16 12:53:14 -0700749Status ResourceManagerService::overrideProcessInfo(
750 const std::shared_ptr<IResourceManagerClient>& client,
751 int pid,
752 int procState,
753 int oomScore) {
754 String8 log = String8::format("overrideProcessInfo(pid %d, procState %d, oomScore %d)",
755 pid, procState, oomScore);
756 mServiceLog->add(log);
757
758 // Only allow the override if the caller already can access process state and oom scores.
759 int callingPid = AIBinder_getCallingPid();
760 if (callingPid != getpid() && (callingPid != pid || !checkCallingPermission(String16(
761 "android.permission.GET_PROCESS_STATE_AND_OOM_SCORE")))) {
762 ALOGE("Permission Denial: overrideProcessInfo method from pid=%d", callingPid);
763 return Status::fromServiceSpecificError(PERMISSION_DENIED);
764 }
765
766 if (client == nullptr) {
767 return Status::fromServiceSpecificError(BAD_VALUE);
768 }
769
770 Mutex::Autolock lock(mLock);
771 removeProcessInfoOverride_l(pid);
772
773 if (!mProcessInfo->overrideProcessInfo(pid, procState, oomScore)) {
774 // Override value is rejected by ProcessInfo.
775 return Status::fromServiceSpecificError(BAD_VALUE);
776 }
777
778 uintptr_t cookie = addCookieAndLink_l(client->asBinder(),
779 new OverrideProcessInfoDeathNotifier(ref<ResourceManagerService>(), pid));
780
781 mProcessInfoOverrideMap.emplace(pid, ProcessInfoOverride{cookie, client});
782
783 return Status::ok();
784}
785
786uintptr_t ResourceManagerService::addCookieAndLink_l(
787 ::ndk::SpAIBinder binder, const sp<DeathNotifier>& notifier) {
788 std::scoped_lock lock{sCookieLock};
789
790 uintptr_t cookie;
791 // Need to skip cookie 0 (if it wraps around). ResourceInfo has cookie initialized to 0
792 // indicating the death notifier is not created yet.
793 while ((cookie = ++sCookieCounter) == 0);
794 AIBinder_linkToDeath(binder.get(), mDeathRecipient.get(), (void*)cookie);
795 sCookieToDeathNotifierMap.emplace(cookie, notifier);
796
797 return cookie;
798}
799
800void ResourceManagerService::removeCookieAndUnlink_l(
801 ::ndk::SpAIBinder binder, uintptr_t cookie) {
802 std::scoped_lock lock{sCookieLock};
803 AIBinder_unlinkToDeath(binder.get(), mDeathRecipient.get(), (void*)cookie);
804 sCookieToDeathNotifierMap.erase(cookie);
805}
806
807void ResourceManagerService::removeProcessInfoOverride(int pid) {
808 Mutex::Autolock lock(mLock);
809
810 removeProcessInfoOverride_l(pid);
811}
812
813void ResourceManagerService::removeProcessInfoOverride_l(int pid) {
814 auto it = mProcessInfoOverrideMap.find(pid);
815 if (it == mProcessInfoOverrideMap.end()) {
816 return;
817 }
818
819 mProcessInfo->removeProcessInfoOverride(pid);
820
821 removeCookieAndUnlink_l(it->second.client->asBinder(), it->second.cookie);
822
823 mProcessInfoOverrideMap.erase(pid);
824}
825
Wonsik Kimd20e9362020-04-28 10:42:57 -0700826Status ResourceManagerService::markClientForPendingRemoval(int32_t pid, int64_t clientId) {
827 String8 log = String8::format(
828 "markClientForPendingRemoval(pid %d, clientId %lld)",
829 pid, (long long) clientId);
830 mServiceLog->add(log);
831
832 Mutex::Autolock lock(mLock);
833 if (!mProcessInfo->isValidPid(pid)) {
834 ALOGE("Rejected markClientForPendingRemoval call with invalid pid.");
835 return Status::fromServiceSpecificError(BAD_VALUE);
836 }
837 ssize_t index = mMap.indexOfKey(pid);
838 if (index < 0) {
839 ALOGV("markClientForPendingRemoval: didn't find pid %d for clientId %lld",
840 pid, (long long)clientId);
841 return Status::ok();
842 }
843 ResourceInfos &infos = mMap.editValueAt(index);
844
845 index = infos.indexOfKey(clientId);
846 if (index < 0) {
847 ALOGV("markClientForPendingRemoval: didn't find clientId %lld", (long long) clientId);
848 return Status::ok();
849 }
850
851 ResourceInfo &info = infos.editValueAt(index);
852 info.pendingRemoval = true;
853 return Status::ok();
854}
855
Henry Fang32762922020-01-28 18:40:39 -0800856bool ResourceManagerService::getPriority_l(int pid, int* priority) {
857 int newPid = pid;
858
859 if (mOverridePidMap.find(pid) != mOverridePidMap.end()) {
860 newPid = mOverridePidMap[pid];
861 ALOGD("getPriority_l: use override pid %d instead original pid %d",
862 newPid, pid);
863 }
864
865 return mProcessInfo->getPriority(newPid, priority);
866}
867
Ronghua Wu231c3d12015-03-11 15:10:32 -0700868bool ResourceManagerService::getAllClients_l(
Chong Zhangfdd512a2019-11-22 11:03:14 -0800869 int callingPid, MediaResource::Type type,
870 Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
871 Vector<std::shared_ptr<IResourceManagerClient>> temp;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700872 for (size_t i = 0; i < mMap.size(); ++i) {
873 ResourceInfos &infos = mMap.editValueAt(i);
874 for (size_t j = 0; j < infos.size(); ++j) {
875 if (hasResourceType(type, infos[j].resources)) {
876 if (!isCallingPriorityHigher_l(callingPid, mMap.keyAt(i))) {
877 // some higher/equal priority process owns the resource,
878 // this request can't be fulfilled.
879 ALOGE("getAllClients_l: can't reclaim resource %s from pid %d",
Ronghua Wuea15fd22016-03-03 13:35:05 -0800880 asString(type), mMap.keyAt(i));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700881 return false;
882 }
883 temp.push_back(infos[j].client);
884 }
885 }
886 }
887 if (temp.size() == 0) {
Ronghua Wuea15fd22016-03-03 13:35:05 -0800888 ALOGV("getAllClients_l: didn't find any resource %s", asString(type));
Ronghua Wu231c3d12015-03-11 15:10:32 -0700889 return true;
890 }
891 clients->appendVector(temp);
892 return true;
893}
894
895bool ResourceManagerService::getLowestPriorityBiggestClient_l(
Chong Zhangfdd512a2019-11-22 11:03:14 -0800896 int callingPid, MediaResource::Type type,
897 std::shared_ptr<IResourceManagerClient> *client) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700898 int lowestPriorityPid;
899 int lowestPriority;
900 int callingPriority;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700901
902 // Before looking into other processes, check if we have clients marked for
903 // pending removal in the same process.
904 if (getBiggestClient_l(callingPid, type, client, true /* pendingRemovalOnly */)) {
905 return true;
906 }
Henry Fang32762922020-01-28 18:40:39 -0800907 if (!getPriority_l(callingPid, &callingPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700908 ALOGE("getLowestPriorityBiggestClient_l: can't get process priority for pid %d",
909 callingPid);
910 return false;
911 }
912 if (!getLowestPriorityPid_l(type, &lowestPriorityPid, &lowestPriority)) {
913 return false;
914 }
915 if (lowestPriority <= callingPriority) {
916 ALOGE("getLowestPriorityBiggestClient_l: lowest priority %d vs caller priority %d",
917 lowestPriority, callingPriority);
918 return false;
919 }
920
921 if (!getBiggestClient_l(lowestPriorityPid, type, client)) {
922 return false;
923 }
924 return true;
925}
926
927bool ResourceManagerService::getLowestPriorityPid_l(
Ronghua Wuea15fd22016-03-03 13:35:05 -0800928 MediaResource::Type type, int *lowestPriorityPid, int *lowestPriority) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700929 int pid = -1;
930 int priority = -1;
931 for (size_t i = 0; i < mMap.size(); ++i) {
932 if (mMap.valueAt(i).size() == 0) {
933 // no client on this process.
934 continue;
935 }
936 if (!hasResourceType(type, mMap.valueAt(i))) {
937 // doesn't have the requested resource type
938 continue;
939 }
940 int tempPid = mMap.keyAt(i);
941 int tempPriority;
Henry Fang32762922020-01-28 18:40:39 -0800942 if (!getPriority_l(tempPid, &tempPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700943 ALOGV("getLowestPriorityPid_l: can't get priority of pid %d, skipped", tempPid);
944 // TODO: remove this pid from mMap?
945 continue;
946 }
947 if (pid == -1 || tempPriority > priority) {
948 // initial the value
949 pid = tempPid;
950 priority = tempPriority;
951 }
952 }
953 if (pid != -1) {
954 *lowestPriorityPid = pid;
955 *lowestPriority = priority;
956 }
957 return (pid != -1);
958}
959
960bool ResourceManagerService::isCallingPriorityHigher_l(int callingPid, int pid) {
961 int callingPidPriority;
Henry Fang32762922020-01-28 18:40:39 -0800962 if (!getPriority_l(callingPid, &callingPidPriority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700963 return false;
964 }
965
966 int priority;
Henry Fang32762922020-01-28 18:40:39 -0800967 if (!getPriority_l(pid, &priority)) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700968 return false;
969 }
970
971 return (callingPidPriority < priority);
972}
973
974bool ResourceManagerService::getBiggestClient_l(
Wonsik Kimd20e9362020-04-28 10:42:57 -0700975 int pid, MediaResource::Type type, std::shared_ptr<IResourceManagerClient> *client,
976 bool pendingRemovalOnly) {
Ronghua Wu231c3d12015-03-11 15:10:32 -0700977 ssize_t index = mMap.indexOfKey(pid);
978 if (index < 0) {
979 ALOGE("getBiggestClient_l: can't find resource info for pid %d", pid);
980 return false;
981 }
982
Chong Zhangfdd512a2019-11-22 11:03:14 -0800983 std::shared_ptr<IResourceManagerClient> clientTemp;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700984 uint64_t largestValue = 0;
985 const ResourceInfos &infos = mMap.valueAt(index);
986 for (size_t i = 0; i < infos.size(); ++i) {
Chong Zhangfb092d32019-08-12 09:45:44 -0700987 const ResourceList &resources = infos[i].resources;
Wonsik Kimd20e9362020-04-28 10:42:57 -0700988 if (pendingRemovalOnly && !infos[i].pendingRemoval) {
989 continue;
990 }
Chong Zhangfb092d32019-08-12 09:45:44 -0700991 for (auto it = resources.begin(); it != resources.end(); it++) {
Chong Zhang181e6952019-10-09 13:23:39 -0700992 const MediaResourceParcel &resource = it->second;
993 if (resource.type == type) {
994 if (resource.value > largestValue) {
995 largestValue = resource.value;
Ronghua Wu231c3d12015-03-11 15:10:32 -0700996 clientTemp = infos[i].client;
997 }
998 }
999 }
1000 }
1001
1002 if (clientTemp == NULL) {
Ronghua Wuea15fd22016-03-03 13:35:05 -08001003 ALOGE("getBiggestClient_l: can't find resource type %s for pid %d", asString(type), pid);
Ronghua Wu231c3d12015-03-11 15:10:32 -07001004 return false;
1005 }
1006
1007 *client = clientTemp;
1008 return true;
1009}
1010
Ronghua Wu231c3d12015-03-11 15:10:32 -07001011} // namespace android