1 /*
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
22 #include <android/binder_manager.h>
23 #include <android/binder_process.h>
24 #include <binder/IPCThreadState.h>
25 #include <binder/IServiceManager.h>
26 #include <cutils/sched_policy.h>
27 #include <dirent.h>
28 #include <media/MediaResourcePolicy.h>
29 #include <media/stagefright/ProcessInfo.h>
30 #include <mediautils/BatteryNotifier.h>
31 #include <mediautils/SchedulingPolicyService.h>
32 #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 "IMediaResourceMonitor.h"
39 #include "ResourceManagerService.h"
40 #include "ResourceObserverService.h"
41 #include "ServiceLog.h"
42
43 namespace android {
44
45 //static
46 std::mutex ResourceManagerService::sCookieLock;
47 //static
48 uintptr_t ResourceManagerService::sCookieCounter = 0;
49 //static
50 std::map<uintptr_t, sp<DeathNotifier> > ResourceManagerService::sCookieToDeathNotifierMap;
51
52 class DeathNotifier : public RefBase {
53 public:
54 DeathNotifier(const std::shared_ptr<ResourceManagerService> &service,
55 int pid, int64_t clientId);
56
~DeathNotifier()57 virtual ~DeathNotifier() {}
58
59 // Implement death recipient
60 static void BinderDiedCallback(void* cookie);
61 virtual void binderDied();
62
63 protected:
64 std::weak_ptr<ResourceManagerService> mService;
65 int mPid;
66 int64_t mClientId;
67 };
68
DeathNotifier(const std::shared_ptr<ResourceManagerService> & service,int pid,int64_t clientId)69 DeathNotifier::DeathNotifier(const std::shared_ptr<ResourceManagerService> &service,
70 int pid, int64_t clientId)
71 : mService(service), mPid(pid), mClientId(clientId) {}
72
73 //static
BinderDiedCallback(void * cookie)74 void DeathNotifier::BinderDiedCallback(void* cookie) {
75 sp<DeathNotifier> notifier;
76 {
77 std::scoped_lock lock{ResourceManagerService::sCookieLock};
78 auto it = ResourceManagerService::sCookieToDeathNotifierMap.find(
79 reinterpret_cast<uintptr_t>(cookie));
80 if (it == ResourceManagerService::sCookieToDeathNotifierMap.end()) {
81 return;
82 }
83 notifier = it->second;
84 }
85 if (notifier.get() != nullptr) {
86 notifier->binderDied();
87 }
88 }
89
binderDied()90 void DeathNotifier::binderDied() {
91 // Don't check for pid validity since we know it's already dead.
92 std::shared_ptr<ResourceManagerService> service = mService.lock();
93 if (service == nullptr) {
94 ALOGW("ResourceManagerService is dead as well.");
95 return;
96 }
97
98 service->overridePid(mPid, -1);
99 // thiz is freed in the call below, so it must be last call referring thiz
100 service->removeResource(mPid, mClientId, false /*checkValid*/);
101 }
102
103 class OverrideProcessInfoDeathNotifier : public DeathNotifier {
104 public:
OverrideProcessInfoDeathNotifier(const std::shared_ptr<ResourceManagerService> & service,int pid)105 OverrideProcessInfoDeathNotifier(const std::shared_ptr<ResourceManagerService> &service,
106 int pid) : DeathNotifier(service, pid, 0) {}
107
~OverrideProcessInfoDeathNotifier()108 virtual ~OverrideProcessInfoDeathNotifier() {}
109
110 virtual void binderDied();
111 };
112
binderDied()113 void OverrideProcessInfoDeathNotifier::binderDied() {
114 // Don't check for pid validity since we know it's already dead.
115 std::shared_ptr<ResourceManagerService> service = mService.lock();
116 if (service == nullptr) {
117 ALOGW("ResourceManagerService is dead as well.");
118 return;
119 }
120
121 service->removeProcessInfoOverride(mPid);
122 }
123
124 template <typename T>
getString(const std::vector<T> & items)125 static String8 getString(const std::vector<T> &items) {
126 String8 itemsStr;
127 for (size_t i = 0; i < items.size(); ++i) {
128 itemsStr.appendFormat("%s ", toString(items[i]).string());
129 }
130 return itemsStr;
131 }
132
hasResourceType(MediaResource::Type type,const ResourceList & resources)133 static bool hasResourceType(MediaResource::Type type, const ResourceList& resources) {
134 for (auto it = resources.begin(); it != resources.end(); it++) {
135 if (it->second.type == type) {
136 return true;
137 }
138 }
139 return false;
140 }
141
hasResourceType(MediaResource::Type type,const ResourceInfos & infos)142 static bool hasResourceType(MediaResource::Type type, const ResourceInfos& infos) {
143 for (size_t i = 0; i < infos.size(); ++i) {
144 if (hasResourceType(type, infos[i].resources)) {
145 return true;
146 }
147 }
148 return false;
149 }
150
getResourceInfosForEdit(int pid,PidResourceInfosMap & map)151 static ResourceInfos& getResourceInfosForEdit(
152 int pid,
153 PidResourceInfosMap& map) {
154 ssize_t index = map.indexOfKey(pid);
155 if (index < 0) {
156 // new pid
157 ResourceInfos infosForPid;
158 map.add(pid, infosForPid);
159 }
160
161 return map.editValueFor(pid);
162 }
163
getResourceInfoForEdit(uid_t uid,int64_t clientId,const std::shared_ptr<IResourceManagerClient> & client,ResourceInfos & infos)164 static ResourceInfo& getResourceInfoForEdit(
165 uid_t uid,
166 int64_t clientId,
167 const std::shared_ptr<IResourceManagerClient>& client,
168 ResourceInfos& infos) {
169 ssize_t index = infos.indexOfKey(clientId);
170
171 if (index < 0) {
172 ResourceInfo info;
173 info.uid = uid;
174 info.clientId = clientId;
175 info.client = client;
176 info.cookie = 0;
177 info.pendingRemoval = false;
178
179 index = infos.add(clientId, info);
180 }
181
182 return infos.editValueAt(index);
183 }
184
notifyResourceGranted(int pid,const std::vector<MediaResourceParcel> & resources)185 static void notifyResourceGranted(int pid, const std::vector<MediaResourceParcel> &resources) {
186 static const char* const kServiceName = "media_resource_monitor";
187 sp<IBinder> binder = defaultServiceManager()->checkService(String16(kServiceName));
188 if (binder != NULL) {
189 sp<IMediaResourceMonitor> service = interface_cast<IMediaResourceMonitor>(binder);
190 for (size_t i = 0; i < resources.size(); ++i) {
191 if (resources[i].subType == MediaResource::SubType::kAudioCodec) {
192 service->notifyResourceGranted(pid, IMediaResourceMonitor::TYPE_AUDIO_CODEC);
193 } else if (resources[i].subType == MediaResource::SubType::kVideoCodec) {
194 service->notifyResourceGranted(pid, IMediaResourceMonitor::TYPE_VIDEO_CODEC);
195 }
196 }
197 }
198 }
199
dump(int fd,const char **,uint32_t)200 binder_status_t ResourceManagerService::dump(
201 int fd, const char** /*args*/, uint32_t /*numArgs*/) {
202 String8 result;
203
204 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
205 result.format("Permission Denial: "
206 "can't dump ResourceManagerService from pid=%d, uid=%d\n",
207 AIBinder_getCallingPid(),
208 AIBinder_getCallingUid());
209 write(fd, result.string(), result.size());
210 return PERMISSION_DENIED;
211 }
212
213 PidResourceInfosMap mapCopy;
214 bool supportsMultipleSecureCodecs;
215 bool supportsSecureWithNonSecureCodec;
216 std::map<int, int> overridePidMapCopy;
217 String8 serviceLog;
218 {
219 Mutex::Autolock lock(mLock);
220 mapCopy = mMap; // Shadow copy, real copy will happen on write.
221 supportsMultipleSecureCodecs = mSupportsMultipleSecureCodecs;
222 supportsSecureWithNonSecureCodec = mSupportsSecureWithNonSecureCodec;
223 serviceLog = mServiceLog->toString(" " /* linePrefix */);
224 overridePidMapCopy = mOverridePidMap;
225 }
226
227 const size_t SIZE = 256;
228 char buffer[SIZE];
229 snprintf(buffer, SIZE, "ResourceManagerService: %p\n", this);
230 result.append(buffer);
231 result.append(" Policies:\n");
232 snprintf(buffer, SIZE, " SupportsMultipleSecureCodecs: %d\n", supportsMultipleSecureCodecs);
233 result.append(buffer);
234 snprintf(buffer, SIZE, " SupportsSecureWithNonSecureCodec: %d\n",
235 supportsSecureWithNonSecureCodec);
236 result.append(buffer);
237
238 result.append(" Processes:\n");
239 for (size_t i = 0; i < mapCopy.size(); ++i) {
240 snprintf(buffer, SIZE, " Pid: %d\n", mapCopy.keyAt(i));
241 result.append(buffer);
242
243 const ResourceInfos &infos = mapCopy.valueAt(i);
244 for (size_t j = 0; j < infos.size(); ++j) {
245 result.append(" Client:\n");
246 snprintf(buffer, SIZE, " Id: %lld\n", (long long)infos[j].clientId);
247 result.append(buffer);
248
249 std::string clientName;
250 Status status = infos[j].client->getName(&clientName);
251 if (!status.isOk()) {
252 clientName = "<unknown client>";
253 }
254 snprintf(buffer, SIZE, " Name: %s\n", clientName.c_str());
255 result.append(buffer);
256
257 const ResourceList &resources = infos[j].resources;
258 result.append(" Resources:\n");
259 for (auto it = resources.begin(); it != resources.end(); it++) {
260 snprintf(buffer, SIZE, " %s\n", toString(it->second).string());
261 result.append(buffer);
262 }
263 }
264 }
265 result.append(" Process Pid override:\n");
266 for (auto it = overridePidMapCopy.begin(); it != overridePidMapCopy.end(); ++it) {
267 snprintf(buffer, SIZE, " Original Pid: %d, Override Pid: %d\n",
268 it->first, it->second);
269 result.append(buffer);
270 }
271 result.append(" Events logs (most recent at top):\n");
272 result.append(serviceLog);
273
274 write(fd, result.string(), result.size());
275 return OK;
276 }
277
278 struct SystemCallbackImpl :
279 public ResourceManagerService::SystemCallbackInterface {
SystemCallbackImplandroid::SystemCallbackImpl280 SystemCallbackImpl() : mClientToken(new BBinder()) {}
281
noteStartVideoandroid::SystemCallbackImpl282 virtual void noteStartVideo(int uid) override {
283 BatteryNotifier::getInstance().noteStartVideo(uid);
284 }
noteStopVideoandroid::SystemCallbackImpl285 virtual void noteStopVideo(int uid) override {
286 BatteryNotifier::getInstance().noteStopVideo(uid);
287 }
noteResetVideoandroid::SystemCallbackImpl288 virtual void noteResetVideo() override {
289 BatteryNotifier::getInstance().noteResetVideo();
290 }
requestCpusetBoostandroid::SystemCallbackImpl291 virtual bool requestCpusetBoost(bool enable) override {
292 return android::requestCpusetBoost(enable, mClientToken);
293 }
294
295 protected:
~SystemCallbackImplandroid::SystemCallbackImpl296 virtual ~SystemCallbackImpl() {}
297
298 private:
299 DISALLOW_EVIL_CONSTRUCTORS(SystemCallbackImpl);
300 sp<IBinder> mClientToken;
301 };
302
ResourceManagerService()303 ResourceManagerService::ResourceManagerService()
304 : ResourceManagerService(new ProcessInfo(), new SystemCallbackImpl()) {}
305
ResourceManagerService(const sp<ProcessInfoInterface> & processInfo,const sp<SystemCallbackInterface> & systemResource)306 ResourceManagerService::ResourceManagerService(
307 const sp<ProcessInfoInterface> &processInfo,
308 const sp<SystemCallbackInterface> &systemResource)
309 : mProcessInfo(processInfo),
310 mSystemCB(systemResource),
311 mServiceLog(new ServiceLog()),
312 mSupportsMultipleSecureCodecs(true),
313 mSupportsSecureWithNonSecureCodec(true),
314 mCpuBoostCount(0),
315 mDeathRecipient(AIBinder_DeathRecipient_new(DeathNotifier::BinderDiedCallback)) {
316 mSystemCB->noteResetVideo();
317 }
318
319 //static
instantiate()320 void ResourceManagerService::instantiate() {
321 std::shared_ptr<ResourceManagerService> service =
322 ::ndk::SharedRefBase::make<ResourceManagerService>();
323 binder_status_t status =
324 AServiceManager_addService(service->asBinder().get(), getServiceName());
325 if (status != STATUS_OK) {
326 return;
327 }
328
329 std::shared_ptr<ResourceObserverService> observerService =
330 ResourceObserverService::instantiate();
331
332 if (observerService != nullptr) {
333 service->setObserverService(observerService);
334 }
335 // TODO: mediaserver main() is already starting the thread pool,
336 // move this to mediaserver main() when other services in mediaserver
337 // are converted to ndk-platform aidl.
338 //ABinderProcess_startThreadPool();
339 }
340
~ResourceManagerService()341 ResourceManagerService::~ResourceManagerService() {}
342
setObserverService(const std::shared_ptr<ResourceObserverService> & observerService)343 void ResourceManagerService::setObserverService(
344 const std::shared_ptr<ResourceObserverService>& observerService) {
345 mObserverService = observerService;
346 }
347
config(const std::vector<MediaResourcePolicyParcel> & policies)348 Status ResourceManagerService::config(const std::vector<MediaResourcePolicyParcel>& policies) {
349 String8 log = String8::format("config(%s)", getString(policies).string());
350 mServiceLog->add(log);
351
352 Mutex::Autolock lock(mLock);
353 for (size_t i = 0; i < policies.size(); ++i) {
354 const std::string &type = policies[i].type;
355 const std::string &value = policies[i].value;
356 if (type == MediaResourcePolicy::kPolicySupportsMultipleSecureCodecs()) {
357 mSupportsMultipleSecureCodecs = (value == "true");
358 } else if (type == MediaResourcePolicy::kPolicySupportsSecureWithNonSecureCodec()) {
359 mSupportsSecureWithNonSecureCodec = (value == "true");
360 }
361 }
362 return Status::ok();
363 }
364
onFirstAdded(const MediaResourceParcel & resource,const ResourceInfo & clientInfo)365 void ResourceManagerService::onFirstAdded(
366 const MediaResourceParcel& resource, const ResourceInfo& clientInfo) {
367 // first time added
368 if (resource.type == MediaResource::Type::kCpuBoost
369 && resource.subType == MediaResource::SubType::kUnspecifiedSubType) {
370 // Request it on every new instance of kCpuBoost, as the media.codec
371 // could have died, if we only do it the first time subsequent instances
372 // never gets the boost.
373 if (mSystemCB->requestCpusetBoost(true) != OK) {
374 ALOGW("couldn't request cpuset boost");
375 }
376 mCpuBoostCount++;
377 } else if (resource.type == MediaResource::Type::kBattery
378 && resource.subType == MediaResource::SubType::kVideoCodec) {
379 mSystemCB->noteStartVideo(clientInfo.uid);
380 }
381 }
382
onLastRemoved(const MediaResourceParcel & resource,const ResourceInfo & clientInfo)383 void ResourceManagerService::onLastRemoved(
384 const MediaResourceParcel& resource, const ResourceInfo& clientInfo) {
385 if (resource.type == MediaResource::Type::kCpuBoost
386 && resource.subType == MediaResource::SubType::kUnspecifiedSubType
387 && mCpuBoostCount > 0) {
388 if (--mCpuBoostCount == 0) {
389 mSystemCB->requestCpusetBoost(false);
390 }
391 } else if (resource.type == MediaResource::Type::kBattery
392 && resource.subType == MediaResource::SubType::kVideoCodec) {
393 mSystemCB->noteStopVideo(clientInfo.uid);
394 }
395 }
396
mergeResources(MediaResourceParcel & r1,const MediaResourceParcel & r2)397 void ResourceManagerService::mergeResources(
398 MediaResourceParcel& r1, const MediaResourceParcel& r2) {
399 // The resource entry on record is maintained to be in [0,INT64_MAX].
400 // Clamp if merging in the new resource value causes it to go out of bound.
401 // Note that the new resource value could be negative, eg.DrmSession, the
402 // value goes lower when the session is used more often. During reclaim
403 // the session with the highest value (lowest usage) would be closed.
404 if (r2.value < INT64_MAX - r1.value) {
405 r1.value += r2.value;
406 if (r1.value < 0) {
407 r1.value = 0;
408 }
409 } else {
410 r1.value = INT64_MAX;
411 }
412 }
413
addResource(int32_t pid,int32_t uid,int64_t clientId,const std::shared_ptr<IResourceManagerClient> & client,const std::vector<MediaResourceParcel> & resources)414 Status ResourceManagerService::addResource(
415 int32_t pid,
416 int32_t uid,
417 int64_t clientId,
418 const std::shared_ptr<IResourceManagerClient>& client,
419 const std::vector<MediaResourceParcel>& resources) {
420 String8 log = String8::format("addResource(pid %d, clientId %lld, resources %s)",
421 pid, (long long) clientId, getString(resources).string());
422 mServiceLog->add(log);
423
424 Mutex::Autolock lock(mLock);
425 if (!mProcessInfo->isValidPid(pid)) {
426 pid_t callingPid = IPCThreadState::self()->getCallingPid();
427 uid_t callingUid = IPCThreadState::self()->getCallingUid();
428 ALOGW("%s called with untrusted pid %d, using calling pid %d, uid %d", __FUNCTION__,
429 pid, callingPid, callingUid);
430 pid = callingPid;
431 uid = callingUid;
432 }
433 ResourceInfos& infos = getResourceInfosForEdit(pid, mMap);
434 ResourceInfo& info = getResourceInfoForEdit(uid, clientId, client, infos);
435 ResourceList resourceAdded;
436
437 for (size_t i = 0; i < resources.size(); ++i) {
438 const auto &res = resources[i];
439 const auto resType = std::tuple(res.type, res.subType, res.id);
440
441 if (res.value < 0 && res.type != MediaResource::Type::kDrmSession) {
442 ALOGW("Ignoring request to remove negative value of non-drm resource");
443 continue;
444 }
445 if (info.resources.find(resType) == info.resources.end()) {
446 if (res.value <= 0) {
447 // We can't init a new entry with negative value, although it's allowed
448 // to merge in negative values after the initial add.
449 ALOGW("Ignoring request to add new resource entry with value <= 0");
450 continue;
451 }
452 onFirstAdded(res, info);
453 info.resources[resType] = res;
454 } else {
455 mergeResources(info.resources[resType], res);
456 }
457 // Add it to the list of added resources for observers.
458 auto it = resourceAdded.find(resType);
459 if (it == resourceAdded.end()) {
460 resourceAdded[resType] = res;
461 } else {
462 mergeResources(it->second, res);
463 }
464 }
465 if (info.cookie == 0 && client != nullptr) {
466 info.cookie = addCookieAndLink_l(client->asBinder(),
467 new DeathNotifier(ref<ResourceManagerService>(), pid, clientId));
468 }
469 if (mObserverService != nullptr && !resourceAdded.empty()) {
470 mObserverService->onResourceAdded(uid, pid, resourceAdded);
471 }
472 notifyResourceGranted(pid, resources);
473 return Status::ok();
474 }
475
removeResource(int32_t pid,int64_t clientId,const std::vector<MediaResourceParcel> & resources)476 Status ResourceManagerService::removeResource(
477 int32_t pid, int64_t clientId,
478 const std::vector<MediaResourceParcel>& resources) {
479 String8 log = String8::format("removeResource(pid %d, clientId %lld, resources %s)",
480 pid, (long long) clientId, getString(resources).string());
481 mServiceLog->add(log);
482
483 Mutex::Autolock lock(mLock);
484 if (!mProcessInfo->isValidPid(pid)) {
485 pid_t callingPid = IPCThreadState::self()->getCallingPid();
486 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
487 pid, callingPid);
488 pid = callingPid;
489 }
490 ssize_t index = mMap.indexOfKey(pid);
491 if (index < 0) {
492 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
493 return Status::ok();
494 }
495 ResourceInfos &infos = mMap.editValueAt(index);
496
497 index = infos.indexOfKey(clientId);
498 if (index < 0) {
499 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
500 return Status::ok();
501 }
502
503 ResourceInfo &info = infos.editValueAt(index);
504 ResourceList resourceRemoved;
505 for (size_t i = 0; i < resources.size(); ++i) {
506 const auto &res = resources[i];
507 const auto resType = std::tuple(res.type, res.subType, res.id);
508
509 if (res.value < 0) {
510 ALOGW("Ignoring request to remove negative value of resource");
511 continue;
512 }
513 // ignore if we don't have it
514 if (info.resources.find(resType) != info.resources.end()) {
515 MediaResourceParcel &resource = info.resources[resType];
516 MediaResourceParcel actualRemoved = res;
517 if (resource.value > res.value) {
518 resource.value -= res.value;
519 } else {
520 onLastRemoved(res, info);
521 actualRemoved.value = resource.value;
522 info.resources.erase(resType);
523 }
524
525 // Add it to the list of removed resources for observers.
526 auto it = resourceRemoved.find(resType);
527 if (it == resourceRemoved.end()) {
528 resourceRemoved[resType] = actualRemoved;
529 } else {
530 mergeResources(it->second, actualRemoved);
531 }
532 }
533 }
534 if (mObserverService != nullptr && !resourceRemoved.empty()) {
535 mObserverService->onResourceRemoved(info.uid, pid, resourceRemoved);
536 }
537 return Status::ok();
538 }
539
removeClient(int32_t pid,int64_t clientId)540 Status ResourceManagerService::removeClient(int32_t pid, int64_t clientId) {
541 removeResource(pid, clientId, true /*checkValid*/);
542 return Status::ok();
543 }
544
removeResource(int pid,int64_t clientId,bool checkValid)545 Status ResourceManagerService::removeResource(int pid, int64_t clientId, bool checkValid) {
546 String8 log = String8::format(
547 "removeResource(pid %d, clientId %lld)",
548 pid, (long long) clientId);
549 mServiceLog->add(log);
550
551 Mutex::Autolock lock(mLock);
552 if (checkValid && !mProcessInfo->isValidPid(pid)) {
553 pid_t callingPid = IPCThreadState::self()->getCallingPid();
554 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
555 pid, callingPid);
556 pid = callingPid;
557 }
558 ssize_t index = mMap.indexOfKey(pid);
559 if (index < 0) {
560 ALOGV("removeResource: didn't find pid %d for clientId %lld", pid, (long long) clientId);
561 return Status::ok();
562 }
563 ResourceInfos &infos = mMap.editValueAt(index);
564
565 index = infos.indexOfKey(clientId);
566 if (index < 0) {
567 ALOGV("removeResource: didn't find clientId %lld", (long long) clientId);
568 return Status::ok();
569 }
570
571 const ResourceInfo &info = infos[index];
572 for (auto it = info.resources.begin(); it != info.resources.end(); it++) {
573 onLastRemoved(it->second, info);
574 }
575
576 removeCookieAndUnlink_l(info.client->asBinder(), info.cookie);
577
578 if (mObserverService != nullptr && !info.resources.empty()) {
579 mObserverService->onResourceRemoved(info.uid, pid, info.resources);
580 }
581
582 infos.removeItemsAt(index);
583 return Status::ok();
584 }
585
getClientForResource_l(int callingPid,const MediaResourceParcel * res,Vector<std::shared_ptr<IResourceManagerClient>> * clients)586 void ResourceManagerService::getClientForResource_l(
587 int callingPid, const MediaResourceParcel *res,
588 Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
589 if (res == NULL) {
590 return;
591 }
592 std::shared_ptr<IResourceManagerClient> client;
593 if (getLowestPriorityBiggestClient_l(callingPid, res->type, &client)) {
594 clients->push_back(client);
595 }
596 }
597
reclaimResource(int32_t callingPid,const std::vector<MediaResourceParcel> & resources,bool * _aidl_return)598 Status ResourceManagerService::reclaimResource(
599 int32_t callingPid,
600 const std::vector<MediaResourceParcel>& resources,
601 bool* _aidl_return) {
602 String8 log = String8::format("reclaimResource(callingPid %d, resources %s)",
603 callingPid, getString(resources).string());
604 mServiceLog->add(log);
605 *_aidl_return = false;
606
607 Vector<std::shared_ptr<IResourceManagerClient>> clients;
608 {
609 Mutex::Autolock lock(mLock);
610 if (!mProcessInfo->isValidPid(callingPid)) {
611 pid_t actualCallingPid = IPCThreadState::self()->getCallingPid();
612 ALOGW("%s called with untrusted pid %d, using actual calling pid %d", __FUNCTION__,
613 callingPid, actualCallingPid);
614 callingPid = actualCallingPid;
615 }
616 const MediaResourceParcel *secureCodec = NULL;
617 const MediaResourceParcel *nonSecureCodec = NULL;
618 const MediaResourceParcel *graphicMemory = NULL;
619 const MediaResourceParcel *drmSession = NULL;
620 for (size_t i = 0; i < resources.size(); ++i) {
621 MediaResource::Type type = resources[i].type;
622 if (resources[i].type == MediaResource::Type::kSecureCodec) {
623 secureCodec = &resources[i];
624 } else if (type == MediaResource::Type::kNonSecureCodec) {
625 nonSecureCodec = &resources[i];
626 } else if (type == MediaResource::Type::kGraphicMemory) {
627 graphicMemory = &resources[i];
628 } else if (type == MediaResource::Type::kDrmSession) {
629 drmSession = &resources[i];
630 }
631 }
632
633 // first pass to handle secure/non-secure codec conflict
634 if (secureCodec != NULL) {
635 if (!mSupportsMultipleSecureCodecs) {
636 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec, &clients)) {
637 return Status::ok();
638 }
639 }
640 if (!mSupportsSecureWithNonSecureCodec) {
641 if (!getAllClients_l(callingPid, MediaResource::Type::kNonSecureCodec, &clients)) {
642 return Status::ok();
643 }
644 }
645 }
646 if (nonSecureCodec != NULL) {
647 if (!mSupportsSecureWithNonSecureCodec) {
648 if (!getAllClients_l(callingPid, MediaResource::Type::kSecureCodec, &clients)) {
649 return Status::ok();
650 }
651 }
652 }
653 if (drmSession != NULL) {
654 getClientForResource_l(callingPid, drmSession, &clients);
655 if (clients.size() == 0) {
656 return Status::ok();
657 }
658 }
659
660 if (clients.size() == 0) {
661 // if no secure/non-secure codec conflict, run second pass to handle other resources.
662 getClientForResource_l(callingPid, graphicMemory, &clients);
663 }
664
665 if (clients.size() == 0) {
666 // if we are here, run the third pass to free one codec with the same type.
667 getClientForResource_l(callingPid, secureCodec, &clients);
668 getClientForResource_l(callingPid, nonSecureCodec, &clients);
669 }
670
671 if (clients.size() == 0) {
672 // if we are here, run the fourth pass to free one codec with the different type.
673 if (secureCodec != NULL) {
674 MediaResource temp(MediaResource::Type::kNonSecureCodec, 1);
675 getClientForResource_l(callingPid, &temp, &clients);
676 }
677 if (nonSecureCodec != NULL) {
678 MediaResource temp(MediaResource::Type::kSecureCodec, 1);
679 getClientForResource_l(callingPid, &temp, &clients);
680 }
681 }
682 }
683
684 *_aidl_return = reclaimInternal(clients);
685 return Status::ok();
686 }
687
reclaimInternal(const Vector<std::shared_ptr<IResourceManagerClient>> & clients)688 bool ResourceManagerService::reclaimInternal(
689 const Vector<std::shared_ptr<IResourceManagerClient>> &clients) {
690 if (clients.size() == 0) {
691 return false;
692 }
693
694 std::shared_ptr<IResourceManagerClient> failedClient;
695 for (size_t i = 0; i < clients.size(); ++i) {
696 String8 log = String8::format("reclaimResource from client %p", clients[i].get());
697 mServiceLog->add(log);
698 bool success;
699 Status status = clients[i]->reclaimResource(&success);
700 if (!status.isOk() || !success) {
701 failedClient = clients[i];
702 break;
703 }
704 }
705
706 if (failedClient == NULL) {
707 return true;
708 }
709
710 {
711 Mutex::Autolock lock(mLock);
712 bool found = false;
713 for (size_t i = 0; i < mMap.size(); ++i) {
714 ResourceInfos &infos = mMap.editValueAt(i);
715 for (size_t j = 0; j < infos.size();) {
716 if (infos[j].client == failedClient) {
717 j = infos.removeItemsAt(j);
718 found = true;
719 } else {
720 ++j;
721 }
722 }
723 if (found) {
724 break;
725 }
726 }
727 if (!found) {
728 ALOGV("didn't find failed client");
729 }
730 }
731
732 return false;
733 }
734
overridePid(int originalPid,int newPid)735 Status ResourceManagerService::overridePid(
736 int originalPid,
737 int newPid) {
738 String8 log = String8::format("overridePid(originalPid %d, newPid %d)",
739 originalPid, newPid);
740 mServiceLog->add(log);
741
742 // allow if this is called from the same process or the process has
743 // permission.
744 if ((AIBinder_getCallingPid() != getpid()) &&
745 (checkCallingPermission(String16(
746 "android.permission.MEDIA_RESOURCE_OVERRIDE_PID")) == false)) {
747 ALOGE(
748 "Permission Denial: can't access overridePid method from pid=%d, "
749 "self pid=%d\n",
750 AIBinder_getCallingPid(), getpid());
751 return Status::fromServiceSpecificError(PERMISSION_DENIED);
752 }
753
754 {
755 Mutex::Autolock lock(mLock);
756 mOverridePidMap.erase(originalPid);
757 if (newPid != -1) {
758 mOverridePidMap.emplace(originalPid, newPid);
759 }
760 }
761
762 return Status::ok();
763 }
764
overrideProcessInfo(const std::shared_ptr<IResourceManagerClient> & client,int pid,int procState,int oomScore)765 Status ResourceManagerService::overrideProcessInfo(
766 const std::shared_ptr<IResourceManagerClient>& client,
767 int pid,
768 int procState,
769 int oomScore) {
770 String8 log = String8::format("overrideProcessInfo(pid %d, procState %d, oomScore %d)",
771 pid, procState, oomScore);
772 mServiceLog->add(log);
773
774 // Only allow the override if the caller already can access process state and oom scores.
775 int callingPid = AIBinder_getCallingPid();
776 if (callingPid != getpid() && (callingPid != pid || !checkCallingPermission(String16(
777 "android.permission.GET_PROCESS_STATE_AND_OOM_SCORE")))) {
778 ALOGE("Permission Denial: overrideProcessInfo method from pid=%d", callingPid);
779 return Status::fromServiceSpecificError(PERMISSION_DENIED);
780 }
781
782 if (client == nullptr) {
783 return Status::fromServiceSpecificError(BAD_VALUE);
784 }
785
786 Mutex::Autolock lock(mLock);
787 removeProcessInfoOverride_l(pid);
788
789 if (!mProcessInfo->overrideProcessInfo(pid, procState, oomScore)) {
790 // Override value is rejected by ProcessInfo.
791 return Status::fromServiceSpecificError(BAD_VALUE);
792 }
793
794 uintptr_t cookie = addCookieAndLink_l(client->asBinder(),
795 new OverrideProcessInfoDeathNotifier(ref<ResourceManagerService>(), pid));
796
797 mProcessInfoOverrideMap.emplace(pid, ProcessInfoOverride{cookie, client});
798
799 return Status::ok();
800 }
801
addCookieAndLink_l(::ndk::SpAIBinder binder,const sp<DeathNotifier> & notifier)802 uintptr_t ResourceManagerService::addCookieAndLink_l(
803 ::ndk::SpAIBinder binder, const sp<DeathNotifier>& notifier) {
804 std::scoped_lock lock{sCookieLock};
805
806 uintptr_t cookie;
807 // Need to skip cookie 0 (if it wraps around). ResourceInfo has cookie initialized to 0
808 // indicating the death notifier is not created yet.
809 while ((cookie = ++sCookieCounter) == 0);
810 AIBinder_linkToDeath(binder.get(), mDeathRecipient.get(), (void*)cookie);
811 sCookieToDeathNotifierMap.emplace(cookie, notifier);
812
813 return cookie;
814 }
815
removeCookieAndUnlink_l(::ndk::SpAIBinder binder,uintptr_t cookie)816 void ResourceManagerService::removeCookieAndUnlink_l(
817 ::ndk::SpAIBinder binder, uintptr_t cookie) {
818 std::scoped_lock lock{sCookieLock};
819 AIBinder_unlinkToDeath(binder.get(), mDeathRecipient.get(), (void*)cookie);
820 sCookieToDeathNotifierMap.erase(cookie);
821 }
822
removeProcessInfoOverride(int pid)823 void ResourceManagerService::removeProcessInfoOverride(int pid) {
824 Mutex::Autolock lock(mLock);
825
826 removeProcessInfoOverride_l(pid);
827 }
828
removeProcessInfoOverride_l(int pid)829 void ResourceManagerService::removeProcessInfoOverride_l(int pid) {
830 auto it = mProcessInfoOverrideMap.find(pid);
831 if (it == mProcessInfoOverrideMap.end()) {
832 return;
833 }
834
835 mProcessInfo->removeProcessInfoOverride(pid);
836
837 removeCookieAndUnlink_l(it->second.client->asBinder(), it->second.cookie);
838
839 mProcessInfoOverrideMap.erase(pid);
840 }
841
markClientForPendingRemoval(int32_t pid,int64_t clientId)842 Status ResourceManagerService::markClientForPendingRemoval(int32_t pid, int64_t clientId) {
843 String8 log = String8::format(
844 "markClientForPendingRemoval(pid %d, clientId %lld)",
845 pid, (long long) clientId);
846 mServiceLog->add(log);
847
848 Mutex::Autolock lock(mLock);
849 if (!mProcessInfo->isValidPid(pid)) {
850 pid_t callingPid = IPCThreadState::self()->getCallingPid();
851 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
852 pid, callingPid);
853 pid = callingPid;
854 }
855 ssize_t index = mMap.indexOfKey(pid);
856 if (index < 0) {
857 ALOGV("markClientForPendingRemoval: didn't find pid %d for clientId %lld",
858 pid, (long long)clientId);
859 return Status::ok();
860 }
861 ResourceInfos &infos = mMap.editValueAt(index);
862
863 index = infos.indexOfKey(clientId);
864 if (index < 0) {
865 ALOGV("markClientForPendingRemoval: didn't find clientId %lld", (long long) clientId);
866 return Status::ok();
867 }
868
869 ResourceInfo &info = infos.editValueAt(index);
870 info.pendingRemoval = true;
871 return Status::ok();
872 }
873
reclaimResourcesFromClientsPendingRemoval(int32_t pid)874 Status ResourceManagerService::reclaimResourcesFromClientsPendingRemoval(int32_t pid) {
875 String8 log = String8::format("reclaimResourcesFromClientsPendingRemoval(pid %d)", pid);
876 mServiceLog->add(log);
877
878 Vector<std::shared_ptr<IResourceManagerClient>> clients;
879 {
880 Mutex::Autolock lock(mLock);
881 if (!mProcessInfo->isValidPid(pid)) {
882 pid_t callingPid = IPCThreadState::self()->getCallingPid();
883 ALOGW("%s called with untrusted pid %d, using calling pid %d", __FUNCTION__,
884 pid, callingPid);
885 pid = callingPid;
886 }
887
888 for (MediaResource::Type type : {MediaResource::Type::kSecureCodec,
889 MediaResource::Type::kNonSecureCodec,
890 MediaResource::Type::kGraphicMemory,
891 MediaResource::Type::kDrmSession}) {
892 std::shared_ptr<IResourceManagerClient> client;
893 if (getBiggestClient_l(pid, type, &client, true /* pendingRemovalOnly */)) {
894 clients.add(client);
895 break;
896 }
897 }
898 }
899
900 if (!clients.empty()) {
901 reclaimInternal(clients);
902 }
903 return Status::ok();
904 }
905
getPriority_l(int pid,int * priority)906 bool ResourceManagerService::getPriority_l(int pid, int* priority) {
907 int newPid = pid;
908
909 if (mOverridePidMap.find(pid) != mOverridePidMap.end()) {
910 newPid = mOverridePidMap[pid];
911 ALOGD("getPriority_l: use override pid %d instead original pid %d",
912 newPid, pid);
913 }
914
915 return mProcessInfo->getPriority(newPid, priority);
916 }
917
getAllClients_l(int callingPid,MediaResource::Type type,Vector<std::shared_ptr<IResourceManagerClient>> * clients)918 bool ResourceManagerService::getAllClients_l(
919 int callingPid, MediaResource::Type type,
920 Vector<std::shared_ptr<IResourceManagerClient>> *clients) {
921 Vector<std::shared_ptr<IResourceManagerClient>> temp;
922 for (size_t i = 0; i < mMap.size(); ++i) {
923 ResourceInfos &infos = mMap.editValueAt(i);
924 for (size_t j = 0; j < infos.size(); ++j) {
925 if (hasResourceType(type, infos[j].resources)) {
926 if (!isCallingPriorityHigher_l(callingPid, mMap.keyAt(i))) {
927 // some higher/equal priority process owns the resource,
928 // this request can't be fulfilled.
929 ALOGE("getAllClients_l: can't reclaim resource %s from pid %d",
930 asString(type), mMap.keyAt(i));
931 return false;
932 }
933 temp.push_back(infos[j].client);
934 }
935 }
936 }
937 if (temp.size() == 0) {
938 ALOGV("getAllClients_l: didn't find any resource %s", asString(type));
939 return true;
940 }
941 clients->appendVector(temp);
942 return true;
943 }
944
getLowestPriorityBiggestClient_l(int callingPid,MediaResource::Type type,std::shared_ptr<IResourceManagerClient> * client)945 bool ResourceManagerService::getLowestPriorityBiggestClient_l(
946 int callingPid, MediaResource::Type type,
947 std::shared_ptr<IResourceManagerClient> *client) {
948 int lowestPriorityPid;
949 int lowestPriority;
950 int callingPriority;
951
952 // Before looking into other processes, check if we have clients marked for
953 // pending removal in the same process.
954 if (getBiggestClient_l(callingPid, type, client, true /* pendingRemovalOnly */)) {
955 return true;
956 }
957 if (!getPriority_l(callingPid, &callingPriority)) {
958 ALOGE("getLowestPriorityBiggestClient_l: can't get process priority for pid %d",
959 callingPid);
960 return false;
961 }
962 if (!getLowestPriorityPid_l(type, &lowestPriorityPid, &lowestPriority)) {
963 return false;
964 }
965 if (lowestPriority <= callingPriority) {
966 ALOGE("getLowestPriorityBiggestClient_l: lowest priority %d vs caller priority %d",
967 lowestPriority, callingPriority);
968 return false;
969 }
970
971 if (!getBiggestClient_l(lowestPriorityPid, type, client)) {
972 return false;
973 }
974 return true;
975 }
976
getLowestPriorityPid_l(MediaResource::Type type,int * lowestPriorityPid,int * lowestPriority)977 bool ResourceManagerService::getLowestPriorityPid_l(
978 MediaResource::Type type, int *lowestPriorityPid, int *lowestPriority) {
979 int pid = -1;
980 int priority = -1;
981 for (size_t i = 0; i < mMap.size(); ++i) {
982 if (mMap.valueAt(i).size() == 0) {
983 // no client on this process.
984 continue;
985 }
986 if (!hasResourceType(type, mMap.valueAt(i))) {
987 // doesn't have the requested resource type
988 continue;
989 }
990 int tempPid = mMap.keyAt(i);
991 int tempPriority;
992 if (!getPriority_l(tempPid, &tempPriority)) {
993 ALOGV("getLowestPriorityPid_l: can't get priority of pid %d, skipped", tempPid);
994 // TODO: remove this pid from mMap?
995 continue;
996 }
997 if (pid == -1 || tempPriority > priority) {
998 // initial the value
999 pid = tempPid;
1000 priority = tempPriority;
1001 }
1002 }
1003 if (pid != -1) {
1004 *lowestPriorityPid = pid;
1005 *lowestPriority = priority;
1006 }
1007 return (pid != -1);
1008 }
1009
isCallingPriorityHigher_l(int callingPid,int pid)1010 bool ResourceManagerService::isCallingPriorityHigher_l(int callingPid, int pid) {
1011 int callingPidPriority;
1012 if (!getPriority_l(callingPid, &callingPidPriority)) {
1013 return false;
1014 }
1015
1016 int priority;
1017 if (!getPriority_l(pid, &priority)) {
1018 return false;
1019 }
1020
1021 return (callingPidPriority < priority);
1022 }
1023
getBiggestClient_l(int pid,MediaResource::Type type,std::shared_ptr<IResourceManagerClient> * client,bool pendingRemovalOnly)1024 bool ResourceManagerService::getBiggestClient_l(
1025 int pid, MediaResource::Type type, std::shared_ptr<IResourceManagerClient> *client,
1026 bool pendingRemovalOnly) {
1027 ssize_t index = mMap.indexOfKey(pid);
1028 if (index < 0) {
1029 ALOGE_IF(!pendingRemovalOnly,
1030 "getBiggestClient_l: can't find resource info for pid %d", pid);
1031 return false;
1032 }
1033
1034 std::shared_ptr<IResourceManagerClient> clientTemp;
1035 uint64_t largestValue = 0;
1036 const ResourceInfos &infos = mMap.valueAt(index);
1037 for (size_t i = 0; i < infos.size(); ++i) {
1038 const ResourceList &resources = infos[i].resources;
1039 if (pendingRemovalOnly && !infos[i].pendingRemoval) {
1040 continue;
1041 }
1042 for (auto it = resources.begin(); it != resources.end(); it++) {
1043 const MediaResourceParcel &resource = it->second;
1044 if (resource.type == type) {
1045 if (resource.value > largestValue) {
1046 largestValue = resource.value;
1047 clientTemp = infos[i].client;
1048 }
1049 }
1050 }
1051 }
1052
1053 if (clientTemp == NULL) {
1054 ALOGE_IF(!pendingRemovalOnly,
1055 "getBiggestClient_l: can't find resource type %s for pid %d",
1056 asString(type), pid);
1057 return false;
1058 }
1059
1060 *client = clientTemp;
1061 return true;
1062 }
1063
1064 } // namespace android
1065