blob: 73d3c6d246c195ee0d095fefe5d371c84a2e9459 [file]
/*
* Copyright (C) 2022 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 "HintSessionWrapper.h"
#include <android/surface_control.h>
#include <com_android_graphics_hwui_flags.h>
#include <dlfcn.h>
#include <gui/TraceUtils.h>
#include <private/performance_hint_private.h>
#include <utils/Log.h>
#include <utils/Trace.h>
#include <algorithm>
#include <chrono>
#include <string>
#include <vector>
#include "../Properties.h"
#include "RenderThread.h"
#include "thread/CommonPool.h"
using namespace std::chrono_literals;
namespace android {
namespace uirenderer {
namespace renderthread {
#define BIND_SYMBOL(field, name) \
field = reinterpret_cast<decltype(field)>(dlsym(handle_, name)); \
LOG_ALWAYS_FATAL_IF(field == nullptr, "Failed to find required symbol " name)
#define BIND_APH_METHOD(name) BIND_SYMBOL(name, "APerformanceHint_" #name)
#define BIND_ASCC_METHOD(field, name) BIND_SYMBOL(field, "ASessionCreationConfig_" #name)
void HintSessionWrapper::HintSessionBinding::init() {
if (mInitialized) return;
void* handle_ = dlopen("libandroid.so", RTLD_NOW | RTLD_NODELETE);
LOG_ALWAYS_FATAL_IF(handle_ == nullptr, "Failed to dlopen libandroid.so!");
BIND_APH_METHOD(getManager);
BIND_APH_METHOD(createSessionInternal);
BIND_APH_METHOD(closeSession);
BIND_APH_METHOD(updateTargetWorkDuration);
BIND_APH_METHOD(reportActualWorkDuration);
BIND_APH_METHOD(sendHint);
BIND_APH_METHOD(setThreads);
BIND_APH_METHOD(setNativeSurfaces);
BIND_APH_METHOD(isFeatureSupported);
BIND_APH_METHOD(createSessionUsingConfigInternal);
BIND_ASCC_METHOD(createSessionConfig, create);
BIND_ASCC_METHOD(releaseSessionConfig, release);
BIND_ASCC_METHOD(sessionConfigSetTids, setTids);
BIND_ASCC_METHOD(sessionConfigSetTargetWorkDurationNanos, setTargetWorkDurationNanos);
BIND_ASCC_METHOD(sessionConfigSetGraphicsPipeline, setGraphicsPipeline);
BIND_ASCC_METHOD(sessionConfigSetUseAutoTiming, setUseAutoTiming);
mInitialized = true;
}
HintSessionWrapper::HintSessionWrapper(pid_t uiThreadId, pid_t renderThreadId)
: mUiThreadId(uiThreadId)
, mRenderThreadId(renderThreadId)
, mBinding(std::make_shared<HintSessionBinding>()) {}
HintSessionWrapper::~HintSessionWrapper() {
destroy();
}
void HintSessionWrapper::destroy() {
if (mHintSessionFuture.has_value()) {
auto result = mHintSessionFuture->get();
mHintSession = result.session;
mUsesAutoTiming = result.usesAutoTiming;
mHintSessionFuture = std::nullopt;
}
if (mSetThreadsFuture.has_value()) {
mSetThreadsFuture->wait();
mSetThreadsFuture = std::nullopt;
}
if (mHintSession) {
mBinding->closeSession(mHintSession);
mSessionValid = true;
mHintSession = nullptr;
}
mWindow = nullptr;
mSurfaceControl = nullptr;
mUsesAutoTiming = false;
mResetsSinceLastReport = 0;
}
void HintSessionWrapper::setHintSessionEnabled(bool enabled) {
mHintSessionEnabled = enabled;
if (mHintSessionEnabled) {
init();
} else {
destroy();
}
}
bool HintSessionWrapper::init() {
if (mHintSession != nullptr) return true;
// If we're waiting for the session
if (mHintSessionFuture.has_value()) {
// If the session is here
if (mHintSessionFuture->wait_for(0s) == std::future_status::ready) {
auto result = mHintSessionFuture->get();
mHintSession = result.session;
mUsesAutoTiming = result.usesAutoTiming;
mHintSessionFuture = std::nullopt;
if (mHintSession != nullptr) {
mSessionValid = true;
// Automatically bind surface controls if they were cached during async startup
if ((mWindow || mSurfaceControl) &&
com::android::graphics::hwui::flags::adpf_hwui_timeline()) {
sendNativeSurfacesInternal();
}
return true;
}
}
return false;
}
// If it broke last time we tried this, shouldn't be running, or
// has bad argument values, don't even bother
if (!mSessionValid || !mHintSessionEnabled || !Properties::useHintManager ||
!Properties::isDrawingEnabled() || mUiThreadId < 0 || mRenderThreadId < 0) {
return false;
}
// Assume that if we return before the end, it broke
mSessionValid = false;
mBinding->init();
APerformanceHintManager* manager = mBinding->getManager();
if (!manager) return false;
mPermanentSessionTids = CommonPool::getThreadIds();
mPermanentSessionTids.push_back(mUiThreadId);
mPermanentSessionTids.push_back(mRenderThreadId);
// Use the cached target value if there is one, otherwise use a default. This is to ensure
// the cached target and target in PowerHAL are consistent, and that it updates correctly
// whenever there is a change.
int64_t targetDurationNanos =
mLastTargetWorkDuration == 0 ? kDefaultTargetDuration : mLastTargetWorkDuration;
mHintSessionFuture =
CommonPool::async([=, this, tids = mPermanentSessionTids]() -> SessionCreationResult {
if (com::android::graphics::hwui::flags::adpf_hwui_timeline()) {
bool graphicsPipeline =
mBinding->isFeatureSupported(APERF_HINT_GRAPHICS_PIPELINE);
bool autoCpu = mBinding->isFeatureSupported(APERF_HINT_AUTO_CPU);
bool autoGpu = mBinding->isFeatureSupported(APERF_HINT_AUTO_GPU);
if (graphicsPipeline && autoCpu && autoGpu) {
SessionConfigPtr config(mBinding->createSessionConfig(),
mBinding->releaseSessionConfig);
if (config != nullptr) {
mBinding->sessionConfigSetTids(config.get(), tids.data(), tids.size());
mBinding->sessionConfigSetTargetWorkDurationNanos(config.get(),
targetDurationNanos);
mBinding->sessionConfigSetGraphicsPipeline(config.get(), true);
mBinding->sessionConfigSetUseAutoTiming(config.get(), true, true);
APerformanceHintSession* session = nullptr;
int ret = mBinding->createSessionUsingConfigInternal(
manager, config.get(), &session, SessionTag::HWUI);
if (ret == 0 && session != nullptr) {
return SessionCreationResult{session, /*usesAutoTiming=*/true};
}
}
}
}
return SessionCreationResult{
mBinding->createSessionInternal(manager, tids.data(), tids.size(),
targetDurationNanos, SessionTag::HWUI),
/*usesAutoTiming=*/false};
});
return false;
}
void HintSessionWrapper::updateTargetWorkDuration(int64_t targetWorkDurationNanos) {
if (!init()) return;
targetWorkDurationNanos = targetWorkDurationNanos * Properties::targetCpuTimePercentage / 100;
if (targetWorkDurationNanos != mLastTargetWorkDuration &&
targetWorkDurationNanos > kSanityCheckLowerBound &&
targetWorkDurationNanos < kSanityCheckUpperBound) {
mLastTargetWorkDuration = targetWorkDurationNanos;
mBinding->updateTargetWorkDuration(mHintSession, targetWorkDurationNanos);
}
mLastUpdate = systemTime();
}
void HintSessionWrapper::reportActualWorkDuration(int64_t actualDurationNanos) {
mLastUpdate = systemTime();
if (!init() || mUsesAutoTiming) {
return;
}
mResetsSinceLastReport = 0;
if (actualDurationNanos > kSanityCheckLowerBound &&
actualDurationNanos < kSanityCheckUpperBound) {
mBinding->reportActualWorkDuration(mHintSession, actualDurationNanos);
}
}
void HintSessionWrapper::setActiveFunctorThreads(std::vector<pid_t> threadIds) {
if (!init()) return;
if (!mBinding || !mHintSession) return;
// Sort the vector to make sure they're compared as sets.
std::sort(threadIds.begin(), threadIds.end());
if (threadIds == mActiveFunctorTids) return;
mActiveFunctorTids = std::move(threadIds);
std::vector<pid_t> combinedTids = mPermanentSessionTids;
std::copy(mActiveFunctorTids.begin(), mActiveFunctorTids.end(),
std::back_inserter(combinedTids));
mSetThreadsFuture = CommonPool::async([this, tids = std::move(combinedTids)] {
int ret = mBinding->setThreads(mHintSession, tids.data(), tids.size());
ALOGE_IF(ret != 0, "APerformanceHint_setThreads failed: %d", ret);
return ret;
});
}
void HintSessionWrapper::sendCpuLoadResetHint(CpuLoadResetReason reason) {
if (!init()) {
ATRACE_FORMAT_INSTANT("sendCpuLoadResetHint - not sent (session=%s, init=0)",
mName.c_str());
return;
}
nsecs_t now = systemTime();
// We send CPU_LOAD_RESET if the hint cooldown has passed (ensuring we don't send the hint too
// frequently) and one of the following is true:
// * We haven't sent a CPU_LOAD_RESET hint since the last work duration report
// * We've only sent one CPU_LOAD_RESET and the hint reason is PointerMove. This last case
// helps ensure we send CPU_LOAD_RESET before rendering during slow scroll events.
// * The hint reason is FirstFrame. We need this condition because the current
// delayedDestruction logic is racy. There's no guarantee the hint session state will have
// been reset when an app hot starts.
bool isHintCooldownExpired = now - mLastUpdate > kResetHintTimeout;
bool isUnderMaxResetLimit =
mResetsSinceLastReport == 0 || reason == CpuLoadResetReason::FirstFrame ||
(mResetsSinceLastReport == 1 && reason == CpuLoadResetReason::PointerMove);
if (isHintCooldownExpired && isUnderMaxResetLimit) {
++mResetsSinceLastReport;
mBinding->sendHint(mHintSession, static_cast<int32_t>(SessionHint::CPU_LOAD_RESET));
mLastUpdate = now;
ATRACE_FORMAT_INSTANT("sendCpuLoadResetHint - sent (session=%s)", mName.c_str());
} else {
ATRACE_FORMAT_INSTANT(
"sendCpuLoadResetHint - not sent (session=%s, cooldownExpired=%d, underLimit=%d)",
mName.c_str(), isHintCooldownExpired, isUnderMaxResetLimit);
}
}
void HintSessionWrapper::sendCpuLoadIncreaseHint() {
if (!init()) return;
mBinding->sendHint(mHintSession, static_cast<int32_t>(SessionHint::CPU_LOAD_UP));
}
void HintSessionWrapper::sendGpuLoadIncreaseHint() {
if (!init()) return;
mBinding->sendHint(mHintSession, static_cast<int32_t>(SessionHint::GPU_LOAD_UP));
}
bool HintSessionWrapper::alive() {
return mHintSession != nullptr;
}
void HintSessionWrapper::delayedDestroy(RenderThread& rt, nsecs_t delay) {
rt.queue().postDelayed(delay,
[lastUpdateBeforeDelay = mLastUpdate, wrapper = shared_from_this()]() {
if (wrapper->mLastUpdate == lastUpdateBeforeDelay) {
wrapper->destroy();
}
});
}
void HintSessionWrapper::sendNativeSurfacesInternal() {
if (!mBinding || !mHintSession || !mBinding->setNativeSurfaces) {
return;
}
ANativeWindow* const* windowPtr = mWindow ? &mWindow : nullptr;
ASurfaceControl* const* controlPtr = mSurfaceControl ? &mSurfaceControl : nullptr;
mBinding->setNativeSurfaces(mHintSession, windowPtr, mWindow ? 1 : 0, controlPtr,
mSurfaceControl ? 1 : 0);
}
void HintSessionWrapper::setSurfaces(ANativeWindow* window, ASurfaceControl* control) {
if (!com::android::graphics::hwui::flags::adpf_hwui_timeline()) {
return;
}
mWindow = window;
mSurfaceControl = control;
if (!init()) {
return;
}
sendNativeSurfacesInternal();
}
} /* namespace renderthread */
} /* namespace uirenderer */
} /* namespace android */