blob: 33a30d559a751e24f0ca13173b14c52c74893ebb [file]
/*
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "PowerAdvisor/SessionManager.h"
#include <android/binder_libbinder.h>
#include <android/binder_status.h>
#include <binder/IPCThreadState.h>
#include <log/log.h>
#include <unordered_set>
#include "FrontEnd/LayerHandle.h"
#include "Layer.h"
namespace android::adpf {
constexpr size_t kMaxPendingQueueSize = 1024;
constexpr size_t kMaxUnsignaledLayersSize = 1024;
SessionManager::SessionManager([[maybe_unused]] uid_t uid, const SessionManager::Settings settings)
: mSettings(settings) {}
ndk::ScopedAStatus SessionManager::associateSessionToLayers(
int32_t sessionId, int32_t ownerUid, const std::vector<::ndk::SpAIBinder>& layerTokens) {
std::vector<int32_t> layerIds;
layerIds.reserve(layerTokens.size());
for (const auto& token : layerTokens) {
if (token == nullptr) {
continue;
}
const auto platformToken = AIBinder_toPlatformBinder(token.get());
if (platformToken == nullptr) {
continue;
}
const int32_t layerId =
static_cast<int32_t>(surfaceflinger::LayerHandle::getLayerId(platformToken));
if (static_cast<uint32_t>(layerId) == UNASSIGNED_LAYER_ID) {
continue;
}
layerIds.push_back(layerId);
}
if (layerIds.empty() && !layerTokens.empty()) {
return ndk::ScopedAStatus::ok();
}
const std::scoped_lock lock{mSessionManagerMutex};
if (mPendingLayerAssociations.size() < kMaxPendingQueueSize) {
mPendingLayerAssociations.push_back(
{.sessionId = sessionId, .uid = ownerUid, .layerIds = std::move(layerIds)});
} else {
ALOGW("Dropping layer association for session %d: pending queue size limit reached",
sessionId);
}
updateActiveLocked();
return ndk::ScopedAStatus::ok();
}
ndk::ScopedAStatus SessionManager::trackedSessionsDied(const std::vector<int32_t>& sessionIds) {
const std::scoped_lock lock{mSessionManagerMutex};
mDeadSessions.insert(mDeadSessions.end(), sessionIds.begin(), sessionIds.end());
updateActiveLocked();
return ndk::ScopedAStatus::ok();
}
void SessionManager::updateTrackingState(
const std::vector<std::pair<uint32_t, std::string>>& destroyedHandles,
const nsecs_t latchTime) REQUIRES(kMainThreadContext) {
const std::scoped_lock lock{mSessionManagerMutex};
// Recorded during updateTrackingState and applied to mCompositionDataWrapper in initForFrame()
mLastLatchTime = latchTime;
updateBoundSessions();
std::vector<int32_t> deadLayers;
deadLayers.reserve(destroyedHandles.size());
for (const auto& handle : destroyedHandles) {
const int32_t handleId = static_cast<int32_t>(handle.first);
if (mTrackedLayerData.erase(handleId) > 0) {
deadLayers.push_back(handleId);
mDeadLayersPendingNotification.push_back(handleId);
}
}
if (!deadLayers.empty()) {
mMap.notifyLayersDied(deadLayers);
}
removeDeadSessions(mDeadSessions);
mDeadSessions.clear();
}
std::vector<hal::CompositionData>& SessionManager::getCompositionDataBatch()
REQUIRES(kMainThreadContext) {
return mCompositionDataBatch;
}
void SessionManager::initForFrame() REQUIRES(kMainThreadContext) {
// Only become active at the start of a frame
const std::scoped_lock lock{mSessionManagerMutex};
if (mSettings.fpsUpdatesOnly) {
// If we're in "FPS only" mode, we might go a long time without
// sending an update, so we only hold onto one update at a time
// in case the FPS changed
mCompositionDataBatch.clear();
}
mCompositionDataBatch.push_back({});
mCompositionDataWrapper.emplace(mCompositionDataBatch.back(), mMap, mGetParentIdFn);
mCompositionDataWrapper->setLatchTime(mLastLatchTime);
// Retrieve and populate mapping updates while mCompositionDataWrapper is active
const auto updatedLayers = mMap.extractUpdatedLayers();
for (const auto layerId : updatedLayers) {
mCompositionDataWrapper->setLayerSessions(layerId, mMap.getAssociatedSessions(layerId));
}
for (const auto& deadLayerId : mDeadLayersPendingNotification) {
mCompositionDataWrapper->setDeadLayer(deadLayerId);
}
mDeadLayersPendingNotification.clear();
updateActiveLocked();
}
bool SessionManager::isActive() const REQUIRES(kMainThreadContext) {
return mActive;
}
CompositionDataWrapper* SessionManager::getPowerTimeline() {
return mCompositionDataWrapper.has_value() ? &(*mCompositionDataWrapper) : nullptr;
}
bool SessionManager::updateActive() REQUIRES(kMainThreadContext) {
const std::scoped_lock lock{mSessionManagerMutex};
return updateActiveLocked();
}
void SessionManager::setLayersWithUnsignaledFences(std::vector<int32_t>&& unsignaledLayers)
REQUIRES(kMainThreadContext) {
if (mUnsignaledLayerIds.size() < kMaxUnsignaledLayersSize) {
mUnsignaledLayerIds.insert(mUnsignaledLayerIds.end(), unsignaledLayers.begin(),
unsignaledLayers.end());
if (mUnsignaledLayerIds.size() > kMaxUnsignaledLayersSize) {
mUnsignaledLayerIds.resize(kMaxUnsignaledLayersSize);
}
}
}
bool SessionManager::finalizeCompositionData() REQUIRES(kMainThreadContext) {
std::vector<int32_t> unsignaledLayerIds = std::move(mUnsignaledLayerIds);
mUnsignaledLayerIds.clear();
if (!mCompositionDataWrapper) {
return false;
}
CompositionDataWrapper& wrapper = *mCompositionDataWrapper;
std::scoped_lock lock(mSessionManagerMutex);
std::unordered_set<int32_t> latchedLayerIds;
for (const auto& producer : wrapper.getCompositionData().producers) {
const int32_t layerId = wrapper.getLayerId(producer.producerId);
// We only want to know about unsignaled frames that didn't latch
if (producer.currentlyLatchedFrame.has_value()) {
latchedLayerIds.insert(layerId);
}
const auto it = mTrackedLayerData.find(layerId);
if (it != mTrackedLayerData.end() && isLayerRelevantLocked(layerId)) {
if (producer.fps != it->second.fps) {
wrapper.setFpsChanged(true);
it->second.fps = producer.fps;
}
}
}
if (!latchedLayerIds.empty() && !unsignaledLayerIds.empty()) {
std::erase_if(unsignaledLayerIds, [&](int32_t id) { return latchedLayerIds.contains(id); });
}
for (const auto& unsignaledLayerId : unsignaledLayerIds) {
const auto it = mTrackedLayerData.find(unsignaledLayerId);
if (it == mTrackedLayerData.end()) {
continue;
}
if (!isLayerRelevantLocked(unsignaledLayerId)) {
continue;
}
const LayerData& layerData = it->second;
wrapper.insertFrameProducer(
{
.uid = static_cast<int32_t>(layerData.uid),
.fps = layerData.fps.value_or(-1),
.gpuDeadlineMissed = true,
},
unsignaledLayerId);
// Deadline was missed, should send an update
wrapper.setIsForcedUpdate(true);
}
wrapper.setTimestamp(TimePoint::now().ns());
const bool shouldSend = shouldSendCompositionDataBatch();
mCompositionDataWrapper.reset();
// Clean up if we didn't end up sending any data
if (!shouldSend && !mCompositionDataBatch.empty() &&
!mCompositionDataBatch.back().updateData.has_value() &&
mCompositionDataBatch.back().producers.empty() &&
mCompositionDataBatch.back().outputIds.empty()) {
mCompositionDataBatch.pop_back();
}
return shouldSend;
}
void SessionManager::updateSettings(const SessionManager::Settings& settings) {
const std::scoped_lock lock{mSessionManagerMutex};
mSettings = settings;
}
bool SessionManager::isLayerRelevantLocked(const int32_t layerId) const
REQUIRES(kMainThreadContext, mSessionManagerMutex) {
int32_t currentId = layerId;
int depth = 0;
constexpr int kMaxParentDepth = 32;
while (currentId >= 0 && depth++ < kMaxParentDepth) {
if (mMap.isLayerRelevant(currentId)) {
return true;
}
if (!mGetParentIdFn) {
break;
}
int32_t parentId = mGetParentIdFn(currentId);
if (parentId == currentId) {
break;
}
currentId = parentId;
}
return false;
}
bool SessionManager::isLayerRelevant(const int32_t layerId) const REQUIRES(kMainThreadContext) {
const std::scoped_lock lock(mSessionManagerMutex);
return isLayerRelevantLocked(layerId);
}
bool SessionManager::shouldSendCompositionDataBatch() REQUIRES(mSessionManagerMutex) {
// If we only care about FPS updates, only check FPS
if (mSettings.fpsUpdatesOnly) {
return mCompositionDataWrapper->hasFpsChanged();
}
const bool batchFull =
mCompositionDataBatch.size() >= static_cast<size_t>(mSettings.maxBatchSize);
// If the batch must be full, only check the batch size
if (mSettings.preferBatchingToMaxSize) {
return batchFull;
}
return mCompositionDataWrapper->hasFpsChanged() || mCompositionDataWrapper->isForcedUpdate() ||
mCompositionDataWrapper->hasLifecycleUpdates() || batchFull;
}
bool SessionManager::updateActiveLocked() REQUIRES(mSessionManagerMutex) {
mActive = !mTrackedSessionData.empty() || !mTrackedLayerData.empty() || !mMap.isIdle() ||
!mPendingLayerAssociations.empty() || !mDeadLayersPendingNotification.empty();
return mActive;
}
void SessionManager::removeDeadSessions(const std::vector<int32_t>& deadSessions)
REQUIRES(mSessionManagerMutex) {
mMap.notifySessionsDied(deadSessions);
for (const auto& session : deadSessions) {
mTrackedSessionData.erase(session);
// Dead session notifications are already sent through an entirely different API on
// IPower, so we don't need to duplicate that for the HAL. They've likely already
// been informed that the session died.
}
}
void SessionManager::updateBoundSessions() REQUIRES(mSessionManagerMutex) {
for (const auto& binding : mPendingLayerAssociations) {
if (!mDeadSessions.empty() &&
std::find(mDeadSessions.begin(), mDeadSessions.end(), binding.sessionId) !=
mDeadSessions.end()) {
continue;
}
// Register the session then track it
if (mMap.bindSessionIDToLayers(binding.sessionId, binding.layerIds)) {
for (const auto& layerId : binding.layerIds) {
mTrackedLayerData.try_emplace(layerId,
LayerData{.uid = binding.uid, .fps = std::nullopt});
}
mTrackedSessionData.try_emplace(binding.sessionId, SessionData{.uid = binding.uid});
}
}
mPendingLayerAssociations.clear();
}
} // namespace android::adpf