blob: 5c49bc263e81c344b45e49fcb0e640f9426de68e [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.
*/
#define ATRACE_TAG ATRACE_TAG_GRAPHICS
#include "Display/DisplayModeController.h"
#include "Display/DebugDisplayModeConstraints.h"
#include "Display/DisplaySnapshot.h"
#include "DisplayHardware/HWComposer.h"
#include <android-base/properties.h>
#include <common/FlagManager.h>
#include <common/trace.h>
#include <ftl/concat.h>
#include <ftl/expected.h>
#include <ftl/fake_guard.h>
#include <log/log.h>
#include <utils/Errors.h>
#include <utils/Timers.h>
namespace android::display {
using namespace std::string_literals;
template <size_t N>
inline std::string DisplayModeController::Display::concatId(const char (&str)[N]) const {
return std::string(ftl::Concat(str, ' ', snapshot.get().displayId().value).str());
}
DisplayModeController::Display::Display(DisplaySnapshotRef snapshot,
RefreshRateSelectorPtr selectorPtr)
: snapshot(snapshot),
selectorPtr(std::move(selectorPtr)),
pendingModeFpsTrace(concatId("PendingModeFps")),
activeModeFpsTrace(concatId("ActiveModeFps")),
renderRateFpsTrace(concatId("RenderRateFps")),
hasDesiredModeTrace(concatId("HasDesiredMode"), false) {}
void DisplayModeController::registerDisplay(PhysicalDisplayId displayId,
DisplaySnapshotRef snapshotRef,
RefreshRateSelectorPtr selectorPtr) {
DisplayPtr displayPtr = std::make_unique<Display>(snapshotRef, selectorPtr);
displayPtr->setSecure(!supportsHdcp() ||
snapshotRef.get().connectionType() ==
ui::DisplayConnectionType::Internal);
std::lock_guard lock(mDisplayLock);
mDisplays.emplace_or_replace(displayId, std::move(displayPtr));
}
void DisplayModeController::registerDisplay(DisplaySnapshotRef snapshotRef,
DisplayModeId activeModeId,
scheduler::RefreshRateSelector::Config config) {
const auto& snapshot = snapshotRef.get();
const auto displayId = snapshot.displayId();
DisplayPtr displayPtr =
std::make_unique<Display>(snapshotRef, snapshot.displayModes(), activeModeId, config);
displayPtr->setSecure(!supportsHdcp() ||
snapshotRef.get().connectionType() ==
ui::DisplayConnectionType::Internal);
std::lock_guard lock(mDisplayLock);
mDisplays.emplace_or_replace(displayId, std::move(displayPtr));
}
void DisplayModeController::unregisterDisplay(PhysicalDisplayId displayId) {
std::lock_guard lock(mDisplayLock);
const bool ok = mDisplays.erase(displayId);
ALOGE_IF(!ok, "%s: Unknown display %s", __func__, to_string(displayId).c_str());
}
void DisplayModeController::setDebugModeConstraints(
std::optional<std::vector<DebugDisplayModeConstraint>> constraints) {
std::lock_guard lock(mDisplayLock);
if (!constraints) {
mDebugModeConstraintVerifier.reset();
return;
}
auto isExternalLocked = [this](PhysicalDisplayId id) REQUIRES(mDisplayLock) {
return mDisplays.get(id)
.transform([](const DisplayPtr& display) {
return display->snapshot.get().connectionType() ==
ui::DisplayConnectionType::External;
})
.value_or(false);
};
mDebugModeConstraintVerifier =
std::make_shared<DebugModeConstraintVerifier>(std::move(*constraints),
std::move(isExternalLocked));
}
auto DisplayModeController::selectorPtrFor(PhysicalDisplayId displayId) const
-> RefreshRateSelectorPtr {
std::lock_guard lock(mDisplayLock);
return mDisplays.get(displayId)
.transform([](const DisplayPtr& displayPtr) { return displayPtr->selectorPtr; })
.value_or(nullptr);
}
auto DisplayModeController::setDesiredMode(PhysicalDisplayId displayId,
DisplayModeRequest&& desiredMode) -> DesiredModeAction {
std::lock_guard lock(mDisplayLock);
const auto& displayPtr =
FTL_EXPECT(mDisplays.get(displayId).ok_or(DesiredModeAction::None)).get();
{
SFTRACE_NAME(displayPtr->concatId(__func__).c_str());
ALOGD("%s %s", displayPtr->concatId(__func__).c_str(), to_string(desiredMode).c_str());
std::scoped_lock lock(displayPtr->desiredModeLock);
if (auto& desiredModeOpt = displayPtr->desiredModeOpt) {
if (desiredMode.mode.matchesResolution(desiredModeOpt->mode)) {
// A mode transition was already scheduled, so just override the desired mode.
const bool emitEvent = desiredModeOpt->emitEvent;
const bool force = desiredModeOpt->force;
const bool seamless = desiredModeOpt->seamless;
const auto displaySynchronizationToken = desiredModeOpt->displaySynchronizationToken
? desiredModeOpt->displaySynchronizationToken
: desiredMode.displaySynchronizationToken;
desiredModeOpt = std::move(desiredMode);
desiredModeOpt->emitEvent |= emitEvent;
desiredModeOpt->force |= force;
desiredModeOpt->displaySynchronizationToken = displaySynchronizationToken;
desiredModeOpt->seamless &= seamless;
return DesiredModeAction::MergeDisplayModeSwitch;
}
}
// If the desired mode is already active...
const auto activeMode = displayPtr->selectorPtr->getActiveMode();
if (const auto& desiredModePtr = desiredMode.mode.modePtr;
!desiredMode.force && activeMode.modePtr->getId() == desiredModePtr->getId()) {
ftl::FakeGuard guard(kMainThreadContext);
// ...and there is no pending resolution change...
if (!displayPtr->pendingModeOpt && desiredMode.mode.matchesResolution(activeMode)) {
if (activeMode == desiredMode.mode) {
return DesiredModeAction::None;
}
// ...but the render rate changed:
setActiveModeLocked(displayId, desiredModePtr->getId(),
desiredModePtr->getVsyncRate(), desiredMode.mode.fps);
return DesiredModeAction::InitiateRenderRateSwitch;
}
}
// Restore peak render rate to schedule the next frame as soon as possible.
setActiveModeLocked(displayId, activeMode.modePtr->getId(),
activeMode.modePtr->getVsyncRate(), activeMode.modePtr->getPeakFps());
// Initiate a mode change.
displayPtr->desiredModeOpt = std::move(desiredMode);
displayPtr->hasDesiredModeTrace = true;
}
return DesiredModeAction::InitiateDisplayModeSwitch;
}
auto DisplayModeController::getDesiredMode(PhysicalDisplayId displayId) const
-> DisplayModeRequestOpt {
std::lock_guard lock(mDisplayLock);
const auto& displayPtr =
FTL_EXPECT(mDisplays.get(displayId).ok_or(DisplayModeRequestOpt())).get();
{
std::scoped_lock lock(displayPtr->desiredModeLock);
return displayPtr->desiredModeOpt;
}
}
auto DisplayModeController::getDisplayIdForRequest(sp<IBinder> displaySynchronizationToken) const
-> std::vector<PhysicalDisplayId> {
if (!displaySynchronizationToken) {
return {};
}
std::lock_guard lock(mDisplayLock);
std::vector<PhysicalDisplayId> result;
for (const auto& [displayId, displayPtr] : mDisplays) {
std::scoped_lock lock(displayPtr->desiredModeLock);
if (displayPtr->desiredModeOpt &&
displayPtr->desiredModeOpt->displaySynchronizationToken ==
displaySynchronizationToken) {
result.push_back(displayId);
}
}
return result;
}
auto DisplayModeController::getPendingMode(PhysicalDisplayId displayId) const
-> DisplayModeRequestOpt {
std::lock_guard lock(mDisplayLock);
const auto& displayPtr =
FTL_EXPECT(mDisplays.get(displayId).ok_or(DisplayModeRequestOpt())).get();
return displayPtr->pendingModeOpt;
}
bool DisplayModeController::isModeSetPending(PhysicalDisplayId displayId) const {
return getPendingMode(displayId).has_value();
}
ftl::Optional<scheduler::FrameRateMode> DisplayModeController::getActiveMode(
PhysicalDisplayId displayId) const {
std::lock_guard lock(mDisplayLock);
return mDisplays.get(displayId).transform(
[](const DisplayPtr& displayPtr) { return displayPtr->selectorPtr->getActiveMode(); });
}
auto DisplayModeController::desiredModeMatches(PhysicalDisplayId displayId,
ui::Size expectedResolution) -> bool {
std::lock_guard lock(mDisplayLock);
const auto& displayPtr = FTL_EXPECT(mDisplays.get(displayId).ok_or(false)).get();
{
std::scoped_lock lock(displayPtr->desiredModeLock);
if (const auto desiredModeOpt = displayPtr->desiredModeOpt.transform(
[](const auto& request) { return request.mode; })) {
const bool activeResolutionMatch =
displayPtr->selectorPtr->getActiveMode().matchesResolution(*desiredModeOpt);
// If the resolution doesn't match but the desired resolution matches the expected
// resolution, it should be forced and considered as matching.
const bool shouldForceDesiredMode =
expectedResolution == desiredModeOpt->modePtr->getResolution();
return activeResolutionMatch || shouldForceDesiredMode;
}
}
// no desired mode;
return false;
}
auto DisplayModeController::takeDesiredModeIfMatches(PhysicalDisplayId displayId,
ui::Size expectedResolution,
bool shouldSyncResolutionSwitch)
-> DisplayModeRequestOpt {
std::lock_guard lock(mDisplayLock);
const auto& displayPtr =
FTL_EXPECT(mDisplays.get(displayId).ok_or(DisplayModeRequestOpt())).get();
DisplayModeRequestOpt desiredModeOpt;
{
std::scoped_lock lock(displayPtr->desiredModeLock);
if (shouldSyncResolutionSwitch) {
if (const auto modeOpt = displayPtr->desiredModeOpt.transform(
[](const auto& request) { return request.mode; })) {
const bool resolutionMatch =
displayPtr->selectorPtr->getActiveMode().matchesResolution(*modeOpt);
if (!resolutionMatch) {
if (expectedResolution == modeOpt->modePtr->getResolution()) {
displayPtr->desiredModeOpt->force = true;
} else {
// When initiating a resolution change, wait until the commit that resizes
// the display.
return std::nullopt;
}
}
}
}
std::swap(displayPtr->desiredModeOpt, desiredModeOpt);
displayPtr->hasDesiredModeTrace = false;
}
return desiredModeOpt;
}
void DisplayModeController::clearDesiredMode(PhysicalDisplayId displayId) {
std::lock_guard lock(mDisplayLock);
const auto& displayPtr = FTL_TRY(mDisplays.get(displayId).ok_or(ftl::Unit())).get();
{
std::scoped_lock lock(displayPtr->desiredModeLock);
displayPtr->desiredModeOpt.reset();
displayPtr->hasDesiredModeTrace = false;
}
}
void DisplayModeController::clearPendingMode(PhysicalDisplayId displayId) {
std::lock_guard lock(mDisplayLock);
const auto& displayPtr = FTL_TRY(mDisplays.get(displayId).ok_or(ftl::Unit())).get();
displayPtr->pendingModeOpt.reset();
}
auto DisplayModeController::initiateModeChange(PhysicalDisplayId displayId,
DisplayModeRequest&& desiredMode,
const hal::VsyncPeriodChangeConstraints& constraints,
hal::VsyncPeriodChangeTimeline& outTimeline)
-> ModeChangeResult {
std::lock_guard lock(mDisplayLock);
const auto& displayPtr =
FTL_EXPECT(mDisplays.get(displayId).ok_or(ModeChangeResult::Aborted)).get();
ALOGD("%s %s", displayPtr->concatId(__func__).c_str(), to_string(desiredMode).c_str());
displayPtr->pendingModeOpt = std::move(desiredMode);
const auto& mode = *displayPtr->pendingModeOpt->mode.modePtr;
status_t error;
if (CC_UNLIKELY(mDebugModeConstraintVerifier)) {
auto [width, height] = mode.getResolution();
std::vector<std::pair<PhysicalDisplayId, DisplayModePtr>> currentModes;
for (const auto& [id, disp] : mDisplays) {
currentModes.push_back({id, disp->selectorPtr->getActiveMode().modePtr.get()});
}
std::vector<std::pair<PhysicalDisplayId, DisplayModePtr>> proposedModes;
proposedModes.push_back({displayId, displayPtr->pendingModeOpt->mode.modePtr.get()});
if (!mDebugModeConstraintVerifier->shouldAccept(currentModes, proposedModes)) {
ALOGW("Proposed mode %dx%d @ %.2fHz on display %s rejected by debug constraints.",
width, height, mode.getVsyncRate().getValue(), to_string(displayId).c_str());
return ModeChangeResult::Rejected;
}
}
if (!mComposerPtr->getComposer()->isDisplayCommandModesetSupported()) {
error = mComposerPtr->setActiveModeWithConstraints(displayId, mode.getHwcId().value(),
constraints, &outTimeline);
} else {
error = mComposerPtr->setDisplayMode(displayId, mode.getHwcId().value(),
constraints.seamlessRequired);
// DisplayCommand modeset, when successful, is immediate and doesn't need a refresh.
outTimeline.refreshRequired = false;
outTimeline.newVsyncAppliedTimeNanos = systemTime();
}
if (error != OK) {
displayPtr->pendingModeOpt.reset();
}
switch (error) {
case FAILED_TRANSACTION:
return ModeChangeResult::Rejected;
case OK:
SFTRACE_INT(displayPtr->pendingModeFpsTrace.c_str(), mode.getVsyncRate().getIntValue());
return ModeChangeResult::Changed;
default:
return ModeChangeResult::Aborted;
}
}
auto DisplayModeController::initiateModeChange(
ui::PhysicalDisplayMap<PhysicalDisplayId, DisplayModeRequest>&& modeRequestMap)
-> ModeChangeResult {
std::lock_guard lock(mDisplayLock);
std::vector<std::pair<PhysicalDisplayId, hal::HWConfigId>> displayModes;
ui::PhysicalDisplayVector<Display*> displayPtrs;
bool seamlessRequired = true;
std::vector<std::pair<PhysicalDisplayId, DisplayModePtr>> currentModes;
std::vector<std::pair<PhysicalDisplayId, DisplayModePtr>> proposedModes;
if (CC_UNLIKELY(mDebugModeConstraintVerifier)) {
for (const auto& [id, disp] : mDisplays) {
currentModes.push_back({id, disp->selectorPtr->getActiveMode().modePtr.get()});
}
}
for (auto& [displayId, desiredMode] : modeRequestMap) {
const auto& displayPtr =
FTL_EXPECT(mDisplays.get(displayId).ok_or(ModeChangeResult::Aborted)).get();
displayPtrs.push_back(displayPtr.get());
ALOGD("%s %s", displayPtr->concatId(__func__).c_str(), to_string(desiredMode).c_str());
displayPtr->pendingModeOpt = std::move(desiredMode);
const auto& mode = *displayPtr->pendingModeOpt->mode.modePtr;
if (CC_UNLIKELY(mDebugModeConstraintVerifier)) {
proposedModes.push_back({displayId, displayPtr->pendingModeOpt->mode.modePtr.get()});
}
// Either all display(s) are seamless or none of them are.
seamlessRequired &= displayPtr->pendingModeOpt->seamless;
displayModes.push_back({displayId, mode.getHwcId().value()});
}
if (CC_UNLIKELY(mDebugModeConstraintVerifier)) {
if (!mDebugModeConstraintVerifier->shouldAccept(currentModes, proposedModes)) {
ALOGW("Proposed modes rejected by debug constraints.");
for (auto displayPtr : displayPtrs) {
displayPtr->pendingModeOpt.reset();
}
return ModeChangeResult::Rejected;
}
}
const auto error = mComposerPtr->setDisplayModes(displayModes, seamlessRequired);
for (auto displayPtr : displayPtrs) {
if (error != OK) {
displayPtr->pendingModeOpt.reset();
} else {
const auto& mode = *displayPtr->pendingModeOpt->mode.modePtr;
SFTRACE_INT(displayPtr->pendingModeFpsTrace.c_str(), mode.getVsyncRate().getIntValue());
}
}
switch (error) {
case FAILED_TRANSACTION:
return ModeChangeResult::Rejected;
case OK:
return ModeChangeResult::Changed;
default:
return ModeChangeResult::Aborted;
}
}
auto DisplayModeController::finalizeModeChange(PhysicalDisplayId displayId) -> ModeChange {
std::lock_guard lock(mDisplayLock);
const auto& displayPtr =
FTL_EXPECT(mDisplays.get(displayId).ok_or(NoModeChange{"Unknown display"})).get();
if (!displayPtr->pendingModeOpt) return NoModeChange{"No pending mode"};
auto pendingMode = *std::exchange(displayPtr->pendingModeOpt, std::nullopt);
auto& pendingModePtr = pendingMode.mode.modePtr;
if (!displayPtr->selectorPtr->displayModes().contains(pendingModePtr->getId())) {
return NoModeChange{"Unknown pending mode"};
}
const bool resolutionMatch =
displayPtr->selectorPtr->getActiveMode().matchesResolution(pendingMode.mode);
setActiveModeLocked(displayId, pendingModePtr->getId(), pendingModePtr->getVsyncRate(),
pendingMode.mode.fps);
if (resolutionMatch) {
return RefreshRateChange{std::move(pendingMode)};
} else {
return ResolutionChange{std::move(pendingMode)};
}
}
void DisplayModeController::setActiveMode(PhysicalDisplayId displayId, DisplayModeId modeId,
Fps vsyncRate, Fps renderFps) {
std::lock_guard lock(mDisplayLock);
setActiveModeLocked(displayId, modeId, vsyncRate, renderFps);
}
void DisplayModeController::setActiveModeLocked(PhysicalDisplayId displayId, DisplayModeId modeId,
Fps vsyncRate, Fps renderFps) {
const auto& displayPtr = FTL_TRY(mDisplays.get(displayId).ok_or(ftl::Unit())).get();
SFTRACE_INT(displayPtr->activeModeFpsTrace.c_str(), vsyncRate.getIntValue());
SFTRACE_INT(displayPtr->renderRateFpsTrace.c_str(), renderFps.getIntValue());
displayPtr->selectorPtr->setActiveMode(modeId, renderFps);
if (mActiveModeListener) {
mActiveModeListener(displayId, vsyncRate, renderFps);
}
}
void DisplayModeController::updateKernelIdleTimer(PhysicalDisplayId displayId) {
std::lock_guard lock(mDisplayLock);
const auto& displayPtr = FTL_TRY(mDisplays.get(displayId).ok_or(ftl::Unit())).get();
const auto controllerOpt = displayPtr->selectorPtr->kernelIdleTimerController();
if (!controllerOpt) return;
using KernelIdleTimerAction = scheduler::RefreshRateSelector::KernelIdleTimerAction;
switch (displayPtr->selectorPtr->getIdleTimerAction()) {
case KernelIdleTimerAction::TurnOff:
if (displayPtr->isKernelIdleTimerEnabled) {
SFTRACE_INT("KernelIdleTimer", 0);
updateKernelIdleTimer(displayId, std::chrono::milliseconds::zero(), *controllerOpt);
displayPtr->isKernelIdleTimerEnabled = false;
}
break;
case KernelIdleTimerAction::TurnOn:
if (!displayPtr->isKernelIdleTimerEnabled) {
SFTRACE_INT("KernelIdleTimer", 1);
const auto timeout = displayPtr->selectorPtr->getIdleTimerTimeout();
updateKernelIdleTimer(displayId, timeout, *controllerOpt);
displayPtr->isKernelIdleTimerEnabled = true;
}
break;
}
}
void DisplayModeController::updateKernelIdleTimer(PhysicalDisplayId displayId,
std::chrono::milliseconds timeout,
KernelIdleTimerController controller) {
switch (controller) {
case KernelIdleTimerController::HwcApi:
mComposerPtr->setIdleTimerEnabled(displayId, timeout);
break;
case KernelIdleTimerController::Sysprop:
using namespace std::string_literals;
base::SetProperty("graphics.display.kernel_idle_timer.enabled"s,
timeout > std::chrono::milliseconds::zero() ? "true"s : "false"s);
break;
}
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-value" // b/369277774
auto DisplayModeController::getKernelIdleTimerState(PhysicalDisplayId displayId) const
-> KernelIdleTimerState {
std::lock_guard lock(mDisplayLock);
const auto& displayPtr =
FTL_EXPECT(mDisplays.get(displayId).ok_or(KernelIdleTimerState())).get();
const auto desiredModeIdOpt =
(std::scoped_lock(displayPtr->desiredModeLock), displayPtr->desiredModeOpt)
.transform([](const display::DisplayModeRequest& request) {
return request.mode.modePtr->getId();
});
return {desiredModeIdOpt, displayPtr->isKernelIdleTimerEnabled};
}
bool DisplayModeController::supportsHdcp() const {
static const bool kVendorApiLevelSupportsHdcp =
base::GetIntProperty("ro.vendor.api_level", -1) >= 202604;
static const bool kVendorSupportsHdcp =
base::GetBoolProperty("debug.sf.hdcp_negotiation"s, false);
return kVendorApiLevelSupportsHdcp || kVendorSupportsHdcp;
}
void DisplayModeController::startHdcpNegotiation(PhysicalDisplayId displayId) {
if (!supportsHdcp()) return;
using aidl::android::hardware::drm::HdcpLevel;
using aidl::android::hardware::drm::HdcpLevels;
constexpr HdcpLevels kLevels = {.connectedLevel = HdcpLevel::HDCP_V2_1,
.maxLevel = HdcpLevel::HDCP_V2_3};
std::lock_guard lock(mDisplayLock);
const auto& displayPtr = FTL_TRY(mDisplays.get(displayId).ok_or(ftl::Unit())).get();
if (displayPtr->hdcpState == HdcpState::Desired) {
const auto status = mComposerPtr->startHdcpNegotiation(displayId, kLevels);
displayPtr->hdcpState = (status == NO_ERROR) ? HdcpState::Enabled : HdcpState::Undesired;
}
}
void DisplayModeController::setSecure(PhysicalDisplayId displayId, bool secure) {
std::lock_guard lock(mDisplayLock);
const auto& displayPtr = FTL_TRY(mDisplays.get(displayId).ok_or(ftl::Unit())).get();
displayPtr->setSecure(secure);
}
#pragma clang diagnostic pop
} // namespace android::display