blob: 6c1a81314db0e73b3f94438617c873a9f48f7b35 [file] [log] [blame]
Michael Wright1509a232018-06-21 02:50:34 +01001/*
2 * Copyright 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza030fbc12020-02-19 15:32:01 -080017//#define LOG_NDEBUG 0
18
Ady Abrahamabce1652022-02-24 10:51:19 -080019#define ATRACE_TAG ATRACE_TAG_GRAPHICS
20
Michael Wright1509a232018-06-21 02:50:34 +010021#undef LOG_TAG
22#define LOG_TAG "PowerAdvisor"
23
Matt Buckley06f299a2021-09-24 19:43:51 +000024#include <unistd.h>
Michael Wright1509a232018-06-21 02:50:34 +010025#include <cinttypes>
Matt Buckley06f299a2021-09-24 19:43:51 +000026#include <cstdint>
27#include <optional>
Michael Wright1509a232018-06-21 02:50:34 +010028
Dan Stoza030fbc12020-02-19 15:32:01 -080029#include <android-base/properties.h>
Michael Wright1509a232018-06-21 02:50:34 +010030#include <utils/Log.h>
31#include <utils/Mutex.h>
Ady Abrahamabce1652022-02-24 10:51:19 -080032#include <utils/Trace.h>
Michael Wright1509a232018-06-21 02:50:34 +010033
Dan Stoza030fbc12020-02-19 15:32:01 -080034#include <binder/IServiceManager.h>
35
36#include "../SurfaceFlingerProperties.h"
37
Michael Wright1509a232018-06-21 02:50:34 +010038#include "PowerAdvisor.h"
Alec Mouridea1ac52021-06-23 18:12:18 -070039#include "SurfaceFlinger.h"
Michael Wright1509a232018-06-21 02:50:34 +010040
41namespace android {
42namespace Hwc2 {
43
44PowerAdvisor::~PowerAdvisor() = default;
45
46namespace impl {
47
Xiang Wang99f6f3c2023-05-22 13:12:16 -070048using aidl::android::hardware::power::Boost;
Xiang Wang154fc042024-04-02 14:17:53 -070049using aidl::android::hardware::power::ChannelConfig;
Xiang Wang99f6f3c2023-05-22 13:12:16 -070050using aidl::android::hardware::power::Mode;
51using aidl::android::hardware::power::SessionHint;
Matt Buckley52dfaad2024-03-07 20:20:07 +000052using aidl::android::hardware::power::SessionTag;
Xiang Wang99f6f3c2023-05-22 13:12:16 -070053using aidl::android::hardware::power::WorkDuration;
Xiang Wang154fc042024-04-02 14:17:53 -070054using aidl::android::hardware::power::WorkDurationFixedV1;
55
56using aidl::android::hardware::common::fmq::MQDescriptor;
57using aidl::android::hardware::common::fmq::SynchronizedReadWrite;
58using aidl::android::hardware::power::ChannelMessage;
59using android::hardware::EventFlag;
60
61using ChannelMessageContents = ChannelMessage::ChannelMessageContents;
62using MsgQueue = android::AidlMessageQueue<ChannelMessage, SynchronizedReadWrite>;
63using FlagQueue = android::AidlMessageQueue<int8_t, SynchronizedReadWrite>;
Matt Buckley06f299a2021-09-24 19:43:51 +000064
Michael Wright1509a232018-06-21 02:50:34 +010065PowerAdvisor::~PowerAdvisor() = default;
66
Dan Stoza030fbc12020-02-19 15:32:01 -080067namespace {
Alec Mouri29382ad2022-05-11 18:38:38 +000068std::chrono::milliseconds getUpdateTimeout() {
Dan Stoza030fbc12020-02-19 15:32:01 -080069 // Default to a timeout of 80ms if nothing else is specified
Alec Mouri29382ad2022-05-11 18:38:38 +000070 static std::chrono::milliseconds timeout =
71 std::chrono::milliseconds(sysprop::display_update_imminent_timeout_ms(80));
Dan Stoza030fbc12020-02-19 15:32:01 -080072 return timeout;
73}
74
Ady Abrahamabce1652022-02-24 10:51:19 -080075void traceExpensiveRendering(bool enabled) {
76 if (enabled) {
77 ATRACE_ASYNC_BEGIN("ExpensiveRendering", 0);
78 } else {
79 ATRACE_ASYNC_END("ExpensiveRendering", 0);
80 }
81}
82
Dan Stoza030fbc12020-02-19 15:32:01 -080083} // namespace
84
Matt Buckley0538cae2022-11-08 23:12:04 +000085PowerAdvisor::PowerAdvisor(SurfaceFlinger& flinger)
86 : mPowerHal(std::make_unique<power::PowerHalController>()), mFlinger(flinger) {
Alec Mouri29382ad2022-05-11 18:38:38 +000087 if (getUpdateTimeout() > 0ms) {
88 mScreenUpdateTimer.emplace("UpdateImminentTimer", getUpdateTimeout(),
Alec Mouric059dcf2022-05-05 23:40:07 +000089 /* resetCallback */ nullptr,
90 /* timeoutCallback */
91 [this] {
Alec Mouri29382ad2022-05-11 18:38:38 +000092 while (true) {
93 auto timeSinceLastUpdate = std::chrono::nanoseconds(
94 systemTime() - mLastScreenUpdatedTime.load());
95 if (timeSinceLastUpdate >= getUpdateTimeout()) {
96 break;
97 }
Alec Mouric059dcf2022-05-05 23:40:07 +000098 // We may try to disable expensive rendering and allow
99 // for sending DISPLAY_UPDATE_IMMINENT hints too early if
100 // we idled very shortly after updating the screen, so
101 // make sure we wait enough time.
Alec Mouri29382ad2022-05-11 18:38:38 +0000102 std::this_thread::sleep_for(getUpdateTimeout() -
103 timeSinceLastUpdate);
Alec Mouric059dcf2022-05-05 23:40:07 +0000104 }
105 mSendUpdateImminent.store(true);
106 mFlinger.disableExpensiveRendering();
107 });
108 }
109}
Alec Mouridea1ac52021-06-23 18:12:18 -0700110
111void PowerAdvisor::init() {
112 // Defer starting the screen update timer until SurfaceFlinger finishes construction.
Alec Mouric059dcf2022-05-05 23:40:07 +0000113 if (mScreenUpdateTimer) {
114 mScreenUpdateTimer->start();
Dan Stoza030fbc12020-02-19 15:32:01 -0800115 }
116}
Michael Wright1509a232018-06-21 02:50:34 +0100117
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700118void PowerAdvisor::onBootFinished() {
119 mBootFinished.store(true);
120}
121
Peiyong Lin74ca2f42019-01-14 19:36:57 -0800122void PowerAdvisor::setExpensiveRenderingExpected(DisplayId displayId, bool expected) {
Matt Buckley0538cae2022-11-08 23:12:04 +0000123 if (!mHasExpensiveRendering) {
124 ALOGV("Skipped sending EXPENSIVE_RENDERING because HAL doesn't support it");
125 return;
126 }
Michael Wright1509a232018-06-21 02:50:34 +0100127 if (expected) {
128 mExpensiveDisplays.insert(displayId);
129 } else {
130 mExpensiveDisplays.erase(displayId);
131 }
132
Michael Wright1509a232018-06-21 02:50:34 +0100133 const bool expectsExpensiveRendering = !mExpensiveDisplays.empty();
134 if (mNotifiedExpensiveRendering != expectsExpensiveRendering) {
Matt Buckley0538cae2022-11-08 23:12:04 +0000135 auto ret = getPowerHal().setMode(Mode::EXPENSIVE_RENDERING, expectsExpensiveRendering);
136 if (!ret.isOk()) {
137 if (ret.isUnsupported()) {
138 mHasExpensiveRendering = false;
139 }
Michael Wright1509a232018-06-21 02:50:34 +0100140 return;
141 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800142
Michael Wright1509a232018-06-21 02:50:34 +0100143 mNotifiedExpensiveRendering = expectsExpensiveRendering;
Matt Buckley0538cae2022-11-08 23:12:04 +0000144 traceExpensiveRendering(mNotifiedExpensiveRendering);
Michael Wright1509a232018-06-21 02:50:34 +0100145 }
146}
147
jimmyshiu4e211772023-06-15 15:18:38 +0000148void PowerAdvisor::notifyCpuLoadUp() {
149 // Only start sending this notification once the system has booted so we don't introduce an
150 // early-boot dependency on Power HAL
151 if (!mBootFinished.load()) {
152 return;
153 }
Xiang Wang154fc042024-04-02 14:17:53 -0700154 sendHintSessionHint(SessionHint::CPU_LOAD_UP);
jimmyshiu4e211772023-06-15 15:18:38 +0000155}
156
Matt Buckley15ecd1c2022-11-01 21:57:16 +0000157void PowerAdvisor::notifyDisplayUpdateImminentAndCpuReset() {
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700158 // Only start sending this notification once the system has booted so we don't introduce an
159 // early-boot dependency on Power HAL
160 if (!mBootFinished.load()) {
161 return;
162 }
163
Alec Mouric059dcf2022-05-05 23:40:07 +0000164 if (mSendUpdateImminent.exchange(false)) {
Matt Buckley0538cae2022-11-08 23:12:04 +0000165 ALOGV("AIDL notifyDisplayUpdateImminentAndCpuReset");
Xiang Wang154fc042024-04-02 14:17:53 -0700166 sendHintSessionHint(SessionHint::CPU_LOAD_RESET);
Dan Stoza030fbc12020-02-19 15:32:01 -0800167
Matt Buckley0538cae2022-11-08 23:12:04 +0000168 if (!mHasDisplayUpdateImminent) {
169 ALOGV("Skipped sending DISPLAY_UPDATE_IMMINENT because HAL doesn't support it");
170 } else {
171 auto ret = getPowerHal().setBoost(Boost::DISPLAY_UPDATE_IMMINENT, 0);
172 if (ret.isUnsupported()) {
173 mHasDisplayUpdateImminent = false;
174 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800175 }
Alec Mouric059dcf2022-05-05 23:40:07 +0000176
177 if (mScreenUpdateTimer) {
178 mScreenUpdateTimer->reset();
179 } else {
180 // If we don't have a screen update timer, then we don't throttle power hal calls so
181 // flip this bit back to allow for calling into power hal again.
182 mSendUpdateImminent.store(true);
183 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800184 }
185
Alec Mouric059dcf2022-05-05 23:40:07 +0000186 if (mScreenUpdateTimer) {
187 mLastScreenUpdatedTime.store(systemTime());
Dan Stoza030fbc12020-02-19 15:32:01 -0800188 }
189}
190
Matt Buckley06f299a2021-09-24 19:43:51 +0000191bool PowerAdvisor::usePowerHintSession() {
192 // uses cached value since the underlying support and flag are unlikely to change at runtime
Matt Buckley0538cae2022-11-08 23:12:04 +0000193 return mHintSessionEnabled.value_or(false) && supportsPowerHintSession();
Matt Buckley06f299a2021-09-24 19:43:51 +0000194}
195
196bool PowerAdvisor::supportsPowerHintSession() {
Matt Buckley0538cae2022-11-08 23:12:04 +0000197 if (!mSupportsHintSession.has_value()) {
198 mSupportsHintSession = getPowerHal().getHintSessionPreferredRate().isOk();
Matt Buckley06f299a2021-09-24 19:43:51 +0000199 }
Matt Buckley0538cae2022-11-08 23:12:04 +0000200 return *mSupportsHintSession;
Matt Buckley06f299a2021-09-24 19:43:51 +0000201}
202
Matt Buckley52dfaad2024-03-07 20:20:07 +0000203bool PowerAdvisor::shouldCreateSessionWithConfig() {
Xiang Wangcb50bbd2024-04-18 16:57:54 -0700204 return mSessionConfigSupported && mBootFinished &&
205 FlagManager::getInstance().adpf_use_fmq_channel();
Matt Buckley52dfaad2024-03-07 20:20:07 +0000206}
207
Xiang Wang154fc042024-04-02 14:17:53 -0700208void PowerAdvisor::sendHintSessionHint(SessionHint hint) {
209 if (!mBootFinished || !usePowerHintSession()) {
210 ALOGV("Power hint session is not enabled, skip sending session hint");
211 return;
212 }
213 ATRACE_CALL();
214 if (sTraceHintSessionData) ATRACE_INT("Session hint", static_cast<int>(hint));
215 {
216 std::scoped_lock lock(mHintSessionMutex);
217 if (!ensurePowerHintSessionRunning()) {
218 ALOGV("Hint session not running and could not be started, skip sending session hint");
219 return;
220 }
221 ALOGV("Sending session hint: %d", static_cast<int>(hint));
222 if (!writeHintSessionMessage<ChannelMessageContents::Tag::hint>(&hint, 1)) {
223 auto ret = mHintSession->sendHint(hint);
224 if (!ret.isOk()) {
225 ALOGW("Failed to send session hint with error: %s", ret.errorMessage());
226 mHintSession = nullptr;
227 }
228 }
229 }
230}
231
Matt Buckley0538cae2022-11-08 23:12:04 +0000232bool PowerAdvisor::ensurePowerHintSessionRunning() {
Matt Buckley547cc0c2023-10-27 22:22:36 +0000233 if (mHintSession == nullptr && !mHintSessionThreadIds.empty() && usePowerHintSession()) {
Matt Buckley52dfaad2024-03-07 20:20:07 +0000234 if (shouldCreateSessionWithConfig()) {
235 auto ret = getPowerHal().createHintSessionWithConfig(getpid(),
236 static_cast<int32_t>(getuid()),
237 mHintSessionThreadIds,
238 mTargetDuration.ns(),
239 SessionTag::SURFACEFLINGER,
240 &mSessionConfig);
241 if (ret.isOk()) {
242 mHintSession = ret.value();
Xiang Wang154fc042024-04-02 14:17:53 -0700243 if (FlagManager::getInstance().adpf_use_fmq_channel_fixed()) {
244 setUpFmq();
245 }
Matt Buckley52dfaad2024-03-07 20:20:07 +0000246 }
247 // If it fails the first time we try, or ever returns unsupported, assume unsupported
248 else if (mFirstConfigSupportCheck || ret.isUnsupported()) {
249 ALOGI("Hint session with config is unsupported, falling back to a legacy session");
250 mSessionConfigSupported = false;
251 }
252 mFirstConfigSupportCheck = false;
253 }
254 // Immediately try original method after, in case the first way returned unsupported
255 if (mHintSession == nullptr && !shouldCreateSessionWithConfig()) {
256 auto ret = getPowerHal().createHintSession(getpid(), static_cast<int32_t>(getuid()),
257 mHintSessionThreadIds, mTargetDuration.ns());
258 if (ret.isOk()) {
259 mHintSession = ret.value();
260 }
Matt Buckley547cc0c2023-10-27 22:22:36 +0000261 }
Matt Buckley0538cae2022-11-08 23:12:04 +0000262 }
Matt Buckley547cc0c2023-10-27 22:22:36 +0000263 return mHintSession != nullptr;
Matt Buckley06f299a2021-09-24 19:43:51 +0000264}
265
Xiang Wang154fc042024-04-02 14:17:53 -0700266void PowerAdvisor::setUpFmq() {
267 auto&& channelRet = getPowerHal().getSessionChannel(getpid(), static_cast<int32_t>(getuid()));
268 if (!channelRet.isOk()) {
269 ALOGE("Failed to get session channel with error: %s", channelRet.errorMessage());
270 return;
271 }
272 auto& channelConfig = channelRet.value();
273 mMsgQueue = std::make_unique<MsgQueue>(std::move(channelConfig.channelDescriptor), true);
274 LOG_ALWAYS_FATAL_IF(!mMsgQueue->isValid(), "Failed to set up hint session msg queue");
275 LOG_ALWAYS_FATAL_IF(channelConfig.writeFlagBitmask <= 0,
276 "Invalid flag bit masks found in channel config: writeBitMask(%d)",
277 channelConfig.writeFlagBitmask);
278 mFmqWriteMask = static_cast<uint32_t>(channelConfig.writeFlagBitmask);
279 if (!channelConfig.eventFlagDescriptor.has_value()) {
280 // For FMQ v1 in Android 15 we will force using shared event flag since the default
281 // no-op FMQ impl in Power HAL v5 will always return a valid channel config with
282 // non-zero masks but no shared flag.
283 mMsgQueue = nullptr;
284 ALOGE("No event flag descriptor found in channel config");
285 return;
286 }
287 mFlagQueue = std::make_unique<FlagQueue>(std::move(*channelConfig.eventFlagDescriptor), true);
288 LOG_ALWAYS_FATAL_IF(!mFlagQueue->isValid(), "Failed to set up hint session flag queue");
289 auto status = EventFlag::createEventFlag(mFlagQueue->getEventFlagWord(), &mEventFlag);
290 LOG_ALWAYS_FATAL_IF(status != OK, "Failed to set up hint session event flag");
291}
292
Matt Buckley0538cae2022-11-08 23:12:04 +0000293void PowerAdvisor::updateTargetWorkDuration(Duration targetDuration) {
Xiang Wangcb50bbd2024-04-18 16:57:54 -0700294 if (!mBootFinished || !usePowerHintSession()) {
Xiang Wang154fc042024-04-02 14:17:53 -0700295 ALOGV("Power hint session is not enabled, skipping target update");
Matt Buckley06f299a2021-09-24 19:43:51 +0000296 return;
297 }
Matt Buckley0538cae2022-11-08 23:12:04 +0000298 ATRACE_CALL();
Matt Buckley06f299a2021-09-24 19:43:51 +0000299 {
Matt Buckley0538cae2022-11-08 23:12:04 +0000300 mTargetDuration = targetDuration;
301 if (sTraceHintSessionData) ATRACE_INT64("Time target", targetDuration.ns());
Matt Buckley547cc0c2023-10-27 22:22:36 +0000302 if (targetDuration == mLastTargetDurationSent) return;
Xiang Wang154fc042024-04-02 14:17:53 -0700303 std::scoped_lock lock(mHintSessionMutex);
304 if (!ensurePowerHintSessionRunning()) {
305 ALOGV("Hint session not running and could not be started, skip updating target");
306 return;
307 }
308 ALOGV("Sending target time: %" PRId64 "ns", targetDuration.ns());
309 mLastTargetDurationSent = targetDuration;
310 auto target = targetDuration.ns();
311 if (!writeHintSessionMessage<ChannelMessageContents::Tag::targetDuration>(&target, 1)) {
Matt Buckley0538cae2022-11-08 23:12:04 +0000312 auto ret = mHintSession->updateTargetWorkDuration(targetDuration.ns());
313 if (!ret.isOk()) {
314 ALOGW("Failed to set power hint target work duration with error: %s",
Matt Buckley6c18e6d2024-02-07 23:39:50 +0000315 ret.errorMessage());
Matt Buckley547cc0c2023-10-27 22:22:36 +0000316 mHintSession = nullptr;
Matt Buckley0538cae2022-11-08 23:12:04 +0000317 }
Matt Buckley06f299a2021-09-24 19:43:51 +0000318 }
319 }
320}
321
Matt Buckley0538cae2022-11-08 23:12:04 +0000322void PowerAdvisor::reportActualWorkDuration() {
Matt Buckley676e4392023-05-25 22:09:26 +0000323 if (!mBootFinished || !sUseReportActualDuration || !usePowerHintSession()) {
Matt Buckley06f299a2021-09-24 19:43:51 +0000324 ALOGV("Actual work duration power hint cannot be sent, skipping");
325 return;
326 }
Matt Buckley0538cae2022-11-08 23:12:04 +0000327 ATRACE_CALL();
Xiang Wangaab31162024-03-12 19:48:08 -0700328 std::optional<WorkDuration> actualDuration = estimateWorkDuration();
329 if (!actualDuration.has_value() || actualDuration->durationNanos < 0) {
Matt Buckley0538cae2022-11-08 23:12:04 +0000330 ALOGV("Failed to send actual work duration, skipping");
Matt Buckley50c44062022-01-17 20:48:10 +0000331 return;
332 }
Xiang Wangaab31162024-03-12 19:48:08 -0700333 actualDuration->durationNanos += sTargetSafetyMargin.ns();
Matt Buckley0538cae2022-11-08 23:12:04 +0000334 if (sTraceHintSessionData) {
Xiang Wangaab31162024-03-12 19:48:08 -0700335 ATRACE_INT64("Measured duration", actualDuration->durationNanos);
336 ATRACE_INT64("Target error term", actualDuration->durationNanos - mTargetDuration.ns());
337 ATRACE_INT64("Reported duration", actualDuration->durationNanos);
Xiang Wangcb50bbd2024-04-18 16:57:54 -0700338 if (supportsGpuReporting()) {
Xiang Wangaab31162024-03-12 19:48:08 -0700339 ATRACE_INT64("Reported cpu duration", actualDuration->cpuDurationNanos);
340 ATRACE_INT64("Reported gpu duration", actualDuration->gpuDurationNanos);
341 }
Matt Buckley0538cae2022-11-08 23:12:04 +0000342 ATRACE_INT64("Reported target", mLastTargetDurationSent.ns());
343 ATRACE_INT64("Reported target error term",
Xiang Wangaab31162024-03-12 19:48:08 -0700344 actualDuration->durationNanos - mLastTargetDurationSent.ns());
Matt Buckley0538cae2022-11-08 23:12:04 +0000345 }
346
Xiang Wangaab31162024-03-12 19:48:08 -0700347 ALOGV("Sending actual work duration of: %" PRId64 " with cpu: %" PRId64 " and gpu: %" PRId64
348 " on reported target: %" PRId64 " with error: %" PRId64,
349 actualDuration->durationNanos, actualDuration->cpuDurationNanos,
350 actualDuration->gpuDurationNanos, mLastTargetDurationSent.ns(),
351 actualDuration->durationNanos - mLastTargetDurationSent.ns());
Matt Buckley0538cae2022-11-08 23:12:04 +0000352
Matt Buckley547cc0c2023-10-27 22:22:36 +0000353 if (mTimingTestingMode) {
354 mDelayReportActualMutexAcquisitonPromise.get_future().wait();
355 mDelayReportActualMutexAcquisitonPromise = std::promise<bool>{};
356 }
357
Matt Buckley0538cae2022-11-08 23:12:04 +0000358 {
Xiang Wang154fc042024-04-02 14:17:53 -0700359 std::scoped_lock lock(mHintSessionMutex);
Matt Buckley547cc0c2023-10-27 22:22:36 +0000360 if (!ensurePowerHintSessionRunning()) {
Xiang Wang154fc042024-04-02 14:17:53 -0700361 ALOGV("Hint session not running and could not be started, skip reporting durations");
Matt Buckley547cc0c2023-10-27 22:22:36 +0000362 return;
363 }
Xiang Wangaab31162024-03-12 19:48:08 -0700364 mHintSessionQueue.push_back(*actualDuration);
Xiang Wang154fc042024-04-02 14:17:53 -0700365 if (!writeHintSessionMessage<
366 ChannelMessageContents::Tag::workDuration>(mHintSessionQueue.data(),
367 mHintSessionQueue.size())) {
368 auto ret = mHintSession->reportActualWorkDuration(mHintSessionQueue);
369 if (!ret.isOk()) {
370 ALOGW("Failed to report actual work durations with error: %s", ret.errorMessage());
371 mHintSession = nullptr;
372 return;
373 }
Matt Buckley50c44062022-01-17 20:48:10 +0000374 }
375 }
Matt Buckley0538cae2022-11-08 23:12:04 +0000376 mHintSessionQueue.clear();
Matt Buckley50c44062022-01-17 20:48:10 +0000377}
378
Xiang Wang154fc042024-04-02 14:17:53 -0700379template <ChannelMessage::ChannelMessageContents::Tag T, class In>
380bool PowerAdvisor::writeHintSessionMessage(In* contents, size_t count) {
381 if (!mMsgQueue) {
382 ALOGV("Skip using FMQ with message tag %hhd as it's not supported", T);
383 return false;
384 }
385 auto availableSize = mMsgQueue->availableToWrite();
386 if (availableSize < count) {
387 ALOGW("Skip using FMQ with message tag %hhd as there isn't enough space", T);
388 return false;
389 }
390 MsgQueue::MemTransaction tx;
391 if (!mMsgQueue->beginWrite(count, &tx)) {
392 ALOGW("Failed to begin writing message with tag %hhd", T);
393 return false;
394 }
395 for (size_t i = 0; i < count; ++i) {
396 if constexpr (T == ChannelMessageContents::Tag::workDuration) {
397 const WorkDuration& duration = contents[i];
398 new (tx.getSlot(i)) ChannelMessage{
399 .sessionID = static_cast<int32_t>(mSessionConfig.id),
400 .timeStampNanos =
401 (i == count - 1) ? ::android::uptimeNanos() : duration.timeStampNanos,
402 .data = ChannelMessageContents::make<ChannelMessageContents::Tag::workDuration,
403 WorkDurationFixedV1>({
404 .durationNanos = duration.durationNanos,
405 .workPeriodStartTimestampNanos = duration.workPeriodStartTimestampNanos,
406 .cpuDurationNanos = duration.cpuDurationNanos,
407 .gpuDurationNanos = duration.gpuDurationNanos,
408 }),
409 };
410 } else {
411 new (tx.getSlot(i)) ChannelMessage{
412 .sessionID = static_cast<int32_t>(mSessionConfig.id),
413 .timeStampNanos = ::android::uptimeNanos(),
414 .data = ChannelMessageContents::make<T, In>(std::move(contents[i])),
415 };
416 }
417 }
418 if (!mMsgQueue->commitWrite(count)) {
419 ALOGW("Failed to send message with tag %hhd, fall back to binder call", T);
420 return false;
421 }
422 mEventFlag->wake(mFmqWriteMask);
423 return true;
424}
425
Matt Buckley0538cae2022-11-08 23:12:04 +0000426void PowerAdvisor::enablePowerHintSession(bool enabled) {
427 mHintSessionEnabled = enabled;
Matt Buckley06f299a2021-09-24 19:43:51 +0000428}
429
Matt Buckley547cc0c2023-10-27 22:22:36 +0000430bool PowerAdvisor::startPowerHintSession(std::vector<int32_t>&& threadIds) {
431 mHintSessionThreadIds = threadIds;
Matt Buckley0538cae2022-11-08 23:12:04 +0000432 if (!mBootFinished.load()) {
433 return false;
Matt Buckleyef51fba2021-10-12 19:30:12 +0000434 }
Matt Buckley0538cae2022-11-08 23:12:04 +0000435 if (!usePowerHintSession()) {
436 ALOGI("Cannot start power hint session: disabled or unsupported");
437 return false;
438 }
Matt Buckley547cc0c2023-10-27 22:22:36 +0000439 LOG_ALWAYS_FATAL_IF(mHintSessionThreadIds.empty(),
440 "No thread IDs provided to power hint session!");
Xiang Wang154fc042024-04-02 14:17:53 -0700441 {
442 std::scoped_lock lock(mHintSessionMutex);
443 if (mHintSession != nullptr) {
444 ALOGE("Cannot start power hint session: already running");
445 return false;
446 }
447 return ensurePowerHintSessionRunning();
Matt Buckley0538cae2022-11-08 23:12:04 +0000448 }
Matt Buckleyef51fba2021-10-12 19:30:12 +0000449}
450
Xiang Wangcb50bbd2024-04-18 16:57:54 -0700451bool PowerAdvisor::supportsGpuReporting() {
452 return mBootFinished && FlagManager::getInstance().adpf_gpu_sf();
453}
454
Xiang Wangaab31162024-03-12 19:48:08 -0700455void PowerAdvisor::setGpuStartTime(DisplayId displayId, TimePoint startTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000456 DisplayTimingData& displayData = mDisplayTimingData[displayId];
457 if (displayData.gpuEndFenceTime) {
458 nsecs_t signalTime = displayData.gpuEndFenceTime->getSignalTime();
459 if (signalTime != Fence::SIGNAL_TIME_INVALID && signalTime != Fence::SIGNAL_TIME_PENDING) {
Xiang Wangaab31162024-03-12 19:48:08 -0700460 displayData.lastValidGpuStartTime = displayData.gpuStartTime;
461 displayData.lastValidGpuEndTime = TimePoint::fromNs(signalTime);
462 for (auto&& [_, otherDisplayData] : mDisplayTimingData) {
463 if (!otherDisplayData.lastValidGpuStartTime.has_value() ||
464 !otherDisplayData.lastValidGpuEndTime.has_value())
465 continue;
466 if ((*otherDisplayData.lastValidGpuStartTime < *displayData.gpuStartTime) &&
467 (*otherDisplayData.lastValidGpuEndTime > *displayData.gpuStartTime)) {
468 displayData.lastValidGpuStartTime = *otherDisplayData.lastValidGpuEndTime;
469 break;
470 }
471 }
472 }
473 displayData.gpuEndFenceTime = nullptr;
474 }
475 displayData.gpuStartTime = startTime;
476}
477
478void PowerAdvisor::setGpuFenceTime(DisplayId displayId, std::unique_ptr<FenceTime>&& fenceTime) {
479 DisplayTimingData& displayData = mDisplayTimingData[displayId];
Xiang Wangcb50bbd2024-04-18 16:57:54 -0700480 if (displayData.gpuEndFenceTime && !supportsGpuReporting()) {
Xiang Wangaab31162024-03-12 19:48:08 -0700481 nsecs_t signalTime = displayData.gpuEndFenceTime->getSignalTime();
482 if (signalTime != Fence::SIGNAL_TIME_INVALID && signalTime != Fence::SIGNAL_TIME_PENDING) {
483 displayData.lastValidGpuStartTime = displayData.gpuStartTime;
484 displayData.lastValidGpuEndTime = TimePoint::fromNs(signalTime);
Matt Buckley50c44062022-01-17 20:48:10 +0000485 for (auto&& [_, otherDisplayData] : mDisplayTimingData) {
486 // If the previous display started before us but ended after we should have
487 // started, then it likely delayed our start time and we must compensate for that.
488 // Displays finishing earlier should have already made their way through this call
489 // and swapped their timing into "lastValid" from "latest", so we check that here.
490 if (!otherDisplayData.lastValidGpuStartTime.has_value()) continue;
491 if ((*otherDisplayData.lastValidGpuStartTime < *displayData.gpuStartTime) &&
492 (*otherDisplayData.lastValidGpuEndTime > *displayData.gpuStartTime)) {
493 displayData.lastValidGpuStartTime = *otherDisplayData.lastValidGpuEndTime;
494 break;
495 }
496 }
Matt Buckley50c44062022-01-17 20:48:10 +0000497 }
498 }
499 displayData.gpuEndFenceTime = std::move(fenceTime);
Xiang Wangcb50bbd2024-04-18 16:57:54 -0700500 if (!supportsGpuReporting()) {
Xiang Wangaab31162024-03-12 19:48:08 -0700501 displayData.gpuStartTime = TimePoint::now();
502 }
Matt Buckley50c44062022-01-17 20:48:10 +0000503}
504
Matt Buckley2fa85012022-08-30 22:38:45 +0000505void PowerAdvisor::setHwcValidateTiming(DisplayId displayId, TimePoint validateStartTime,
506 TimePoint validateEndTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000507 DisplayTimingData& displayData = mDisplayTimingData[displayId];
Matt Buckley16dec1f2022-06-07 21:46:20 +0000508 displayData.hwcValidateStartTime = validateStartTime;
509 displayData.hwcValidateEndTime = validateEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000510}
511
Matt Buckley2fa85012022-08-30 22:38:45 +0000512void PowerAdvisor::setHwcPresentTiming(DisplayId displayId, TimePoint presentStartTime,
513 TimePoint presentEndTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000514 DisplayTimingData& displayData = mDisplayTimingData[displayId];
Matt Buckley16dec1f2022-06-07 21:46:20 +0000515 displayData.hwcPresentStartTime = presentStartTime;
516 displayData.hwcPresentEndTime = presentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000517}
518
519void PowerAdvisor::setSkippedValidate(DisplayId displayId, bool skipped) {
520 mDisplayTimingData[displayId].skippedValidate = skipped;
521}
522
Xiang Wangaab31162024-03-12 19:48:08 -0700523void PowerAdvisor::setRequiresRenderEngine(DisplayId displayId, bool requiresRenderEngine) {
524 mDisplayTimingData[displayId].requiresRenderEngine = requiresRenderEngine;
Matt Buckley50c44062022-01-17 20:48:10 +0000525}
526
Matt Buckley2fa85012022-08-30 22:38:45 +0000527void PowerAdvisor::setExpectedPresentTime(TimePoint expectedPresentTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000528 mExpectedPresentTimes.append(expectedPresentTime);
529}
530
Matt Buckley2fa85012022-08-30 22:38:45 +0000531void PowerAdvisor::setSfPresentTiming(TimePoint presentFenceTime, TimePoint presentEndTime) {
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700532 mLastPresentFenceTime = presentFenceTime;
Xiang Wangaab31162024-03-12 19:48:08 -0700533 mLastSfPresentEndTime = presentEndTime;
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700534}
535
Matt Buckley2fa85012022-08-30 22:38:45 +0000536void PowerAdvisor::setFrameDelay(Duration frameDelayDuration) {
Matt Buckley50c44062022-01-17 20:48:10 +0000537 mFrameDelayDuration = frameDelayDuration;
538}
539
Matt Buckley2fa85012022-08-30 22:38:45 +0000540void PowerAdvisor::setHwcPresentDelayedTime(DisplayId displayId, TimePoint earliestFrameStartTime) {
541 mDisplayTimingData[displayId].hwcPresentDelayedTime = earliestFrameStartTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000542}
543
Matt Buckley2fa85012022-08-30 22:38:45 +0000544void PowerAdvisor::setCommitStart(TimePoint commitStartTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000545 mCommitStartTimes.append(commitStartTime);
546}
547
Matt Buckley2fa85012022-08-30 22:38:45 +0000548void PowerAdvisor::setCompositeEnd(TimePoint compositeEndTime) {
549 mLastPostcompDuration = compositeEndTime - mLastSfPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000550}
551
552void PowerAdvisor::setDisplays(std::vector<DisplayId>& displayIds) {
553 mDisplayIds = displayIds;
554}
555
Matt Buckley2fa85012022-08-30 22:38:45 +0000556void PowerAdvisor::setTotalFrameTargetWorkDuration(Duration targetDuration) {
Matt Buckley50c44062022-01-17 20:48:10 +0000557 mTotalFrameTargetDuration = targetDuration;
558}
559
560std::vector<DisplayId> PowerAdvisor::getOrderedDisplayIds(
Matt Buckley2fa85012022-08-30 22:38:45 +0000561 std::optional<TimePoint> DisplayTimingData::*sortBy) {
Matt Buckley50c44062022-01-17 20:48:10 +0000562 std::vector<DisplayId> sortedDisplays;
563 std::copy_if(mDisplayIds.begin(), mDisplayIds.end(), std::back_inserter(sortedDisplays),
564 [&](DisplayId id) {
565 return mDisplayTimingData.count(id) &&
566 (mDisplayTimingData[id].*sortBy).has_value();
567 });
568 std::sort(sortedDisplays.begin(), sortedDisplays.end(), [&](DisplayId idA, DisplayId idB) {
569 return *(mDisplayTimingData[idA].*sortBy) < *(mDisplayTimingData[idB].*sortBy);
570 });
571 return sortedDisplays;
572}
573
Xiang Wangaab31162024-03-12 19:48:08 -0700574std::optional<WorkDuration> PowerAdvisor::estimateWorkDuration() {
Matt Buckley0538cae2022-11-08 23:12:04 +0000575 if (!mExpectedPresentTimes.isFull() || !mCommitStartTimes.isFull()) {
Matt Buckley50c44062022-01-17 20:48:10 +0000576 return std::nullopt;
577 }
578
579 // Tracks when we finish presenting to hwc
Matt Buckley0538cae2022-11-08 23:12:04 +0000580 TimePoint estimatedHwcEndTime = mCommitStartTimes[0];
Matt Buckley50c44062022-01-17 20:48:10 +0000581
582 // How long we spent this frame not doing anything, waiting for fences or vsync
Matt Buckley2fa85012022-08-30 22:38:45 +0000583 Duration idleDuration = 0ns;
Matt Buckley50c44062022-01-17 20:48:10 +0000584
585 // Most recent previous gpu end time in the current frame, probably from a prior display, used
586 // as the start time for the next gpu operation if it ran over time since it probably blocked
Matt Buckley2fa85012022-08-30 22:38:45 +0000587 std::optional<TimePoint> previousValidGpuEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000588
589 // The currently estimated gpu end time for the frame,
590 // used to accumulate gpu time as we iterate over the active displays
Matt Buckley2fa85012022-08-30 22:38:45 +0000591 std::optional<TimePoint> estimatedGpuEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000592
Matt Buckley50c44062022-01-17 20:48:10 +0000593 std::vector<DisplayId>&& displayIds =
Matt Buckley16dec1f2022-06-07 21:46:20 +0000594 getOrderedDisplayIds(&DisplayTimingData::hwcPresentStartTime);
Matt Buckley0538cae2022-11-08 23:12:04 +0000595 DisplayTimeline displayTiming;
Xiang Wangaab31162024-03-12 19:48:08 -0700596 std::optional<GpuTimeline> firstGpuTimeline;
Matt Buckley50c44062022-01-17 20:48:10 +0000597
Matt Buckley1809d902022-08-05 06:51:43 +0000598 // Iterate over the displays that use hwc in the same order they are presented
Matt Buckley50c44062022-01-17 20:48:10 +0000599 for (DisplayId displayId : displayIds) {
600 if (mDisplayTimingData.count(displayId) == 0) {
601 continue;
602 }
603
604 auto& displayData = mDisplayTimingData.at(displayId);
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700605
Matt Buckley0538cae2022-11-08 23:12:04 +0000606 displayTiming = displayData.calculateDisplayTimeline(mLastPresentFenceTime);
Matt Buckley50c44062022-01-17 20:48:10 +0000607
Matt Buckley50c44062022-01-17 20:48:10 +0000608 // Update predicted present finish time with this display's present time
Matt Buckley0538cae2022-11-08 23:12:04 +0000609 estimatedHwcEndTime = displayTiming.hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000610
611 // Track how long we spent waiting for the fence, can be excluded from the timing estimate
Matt Buckley0538cae2022-11-08 23:12:04 +0000612 idleDuration += displayTiming.probablyWaitsForPresentFence
613 ? mLastPresentFenceTime - displayTiming.presentFenceWaitStartTime
Matt Buckley2fa85012022-08-30 22:38:45 +0000614 : 0ns;
Matt Buckley50c44062022-01-17 20:48:10 +0000615
616 // Track how long we spent waiting to present, can be excluded from the timing estimate
Matt Buckley0538cae2022-11-08 23:12:04 +0000617 idleDuration += displayTiming.hwcPresentDelayDuration;
Matt Buckley50c44062022-01-17 20:48:10 +0000618
619 // Estimate the reference frame's gpu timing
620 auto gpuTiming = displayData.estimateGpuTiming(previousValidGpuEndTime);
621 if (gpuTiming.has_value()) {
Xiang Wangaab31162024-03-12 19:48:08 -0700622 if (!firstGpuTimeline.has_value()) {
623 firstGpuTimeline = gpuTiming;
624 }
Matt Buckley50c44062022-01-17 20:48:10 +0000625 previousValidGpuEndTime = gpuTiming->startTime + gpuTiming->duration;
626
627 // Estimate the prediction frame's gpu end time from the reference frame
Matt Buckley0538cae2022-11-08 23:12:04 +0000628 estimatedGpuEndTime = std::max(displayTiming.hwcPresentStartTime,
Matt Buckley2fa85012022-08-30 22:38:45 +0000629 estimatedGpuEndTime.value_or(TimePoint{0ns})) +
Matt Buckley50c44062022-01-17 20:48:10 +0000630 gpuTiming->duration;
631 }
Matt Buckley50c44062022-01-17 20:48:10 +0000632 }
Matt Buckley50c44062022-01-17 20:48:10 +0000633
Matt Buckley0538cae2022-11-08 23:12:04 +0000634 TimePoint estimatedFlingerEndTime = mLastSfPresentEndTime;
Matt Buckley1809d902022-08-05 06:51:43 +0000635
Matt Buckley50c44062022-01-17 20:48:10 +0000636 // Don't count time spent idly waiting in the estimate as we could do more work in that time
Matt Buckley0538cae2022-11-08 23:12:04 +0000637 estimatedHwcEndTime -= idleDuration;
Matt Buckley1809d902022-08-05 06:51:43 +0000638 estimatedFlingerEndTime -= idleDuration;
Matt Buckley50c44062022-01-17 20:48:10 +0000639
640 // We finish the frame when both present and the gpu are done, so wait for the later of the two
641 // Also add the frame delay duration since the target did not move while we were delayed
Matt Buckley2fa85012022-08-30 22:38:45 +0000642 Duration totalDuration = mFrameDelayDuration +
Matt Buckley0538cae2022-11-08 23:12:04 +0000643 std::max(estimatedHwcEndTime, estimatedGpuEndTime.value_or(TimePoint{0ns})) -
Matt Buckley2fa85012022-08-30 22:38:45 +0000644 mCommitStartTimes[0];
Xiang Wangaab31162024-03-12 19:48:08 -0700645 Duration totalDurationWithoutGpu =
646 mFrameDelayDuration + estimatedHwcEndTime - mCommitStartTimes[0];
Matt Buckley50c44062022-01-17 20:48:10 +0000647
648 // We finish SurfaceFlinger when post-composition finishes, so add that in here
Matt Buckley2fa85012022-08-30 22:38:45 +0000649 Duration flingerDuration =
Matt Buckley1809d902022-08-05 06:51:43 +0000650 estimatedFlingerEndTime + mLastPostcompDuration - mCommitStartTimes[0];
Xiang Wangaab31162024-03-12 19:48:08 -0700651 Duration estimatedGpuDuration = firstGpuTimeline.has_value()
652 ? estimatedGpuEndTime.value_or(TimePoint{0ns}) - firstGpuTimeline->startTime
653 : Duration::fromNs(0);
Matt Buckley1809d902022-08-05 06:51:43 +0000654
655 // Combine the two timings into a single normalized one
Matt Buckley2fa85012022-08-30 22:38:45 +0000656 Duration combinedDuration = combineTimingEstimates(totalDuration, flingerDuration);
Xiang Wangaab31162024-03-12 19:48:08 -0700657 Duration cpuDuration = combineTimingEstimates(totalDurationWithoutGpu, flingerDuration);
Matt Buckley50c44062022-01-17 20:48:10 +0000658
Xiang Wangaab31162024-03-12 19:48:08 -0700659 WorkDuration duration{
660 .timeStampNanos = TimePoint::now().ns(),
661 .durationNanos = combinedDuration.ns(),
662 .workPeriodStartTimestampNanos = mCommitStartTimes[0].ns(),
Xiang Wangcb50bbd2024-04-18 16:57:54 -0700663 .cpuDurationNanos = supportsGpuReporting() ? cpuDuration.ns() : 0,
664 .gpuDurationNanos = supportsGpuReporting() ? estimatedGpuDuration.ns() : 0,
Xiang Wangaab31162024-03-12 19:48:08 -0700665 };
666 if (sTraceHintSessionData) {
667 ATRACE_INT64("Idle duration", idleDuration.ns());
Xiang Wangaab31162024-03-12 19:48:08 -0700668 ATRACE_INT64("Total duration", totalDuration.ns());
669 ATRACE_INT64("Flinger duration", flingerDuration.ns());
670 }
671 return std::make_optional(duration);
Matt Buckley50c44062022-01-17 20:48:10 +0000672}
673
Matt Buckley2fa85012022-08-30 22:38:45 +0000674Duration PowerAdvisor::combineTimingEstimates(Duration totalDuration, Duration flingerDuration) {
675 Duration targetDuration{0ns};
Matt Buckley0538cae2022-11-08 23:12:04 +0000676 targetDuration = mTargetDuration;
Matt Buckley50c44062022-01-17 20:48:10 +0000677 if (!mTotalFrameTargetDuration.has_value()) return flingerDuration;
678
679 // Normalize total to the flinger target (vsync period) since that's how often we actually send
680 // hints
Matt Buckley2fa85012022-08-30 22:38:45 +0000681 Duration normalizedTotalDuration = Duration::fromNs((targetDuration.ns() * totalDuration.ns()) /
682 mTotalFrameTargetDuration->ns());
Matt Buckley50c44062022-01-17 20:48:10 +0000683 return std::max(flingerDuration, normalizedTotalDuration);
684}
685
Matt Buckley50c44062022-01-17 20:48:10 +0000686PowerAdvisor::DisplayTimeline PowerAdvisor::DisplayTimingData::calculateDisplayTimeline(
Matt Buckley2fa85012022-08-30 22:38:45 +0000687 TimePoint fenceTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000688 DisplayTimeline timeline;
Matt Buckley16dec1f2022-06-07 21:46:20 +0000689 // How long between calling hwc present and trying to wait on the fence
Matt Buckley2fa85012022-08-30 22:38:45 +0000690 const Duration fenceWaitStartDelay =
691 (skippedValidate ? kFenceWaitStartDelaySkippedValidate : kFenceWaitStartDelayValidated);
Matt Buckley50c44062022-01-17 20:48:10 +0000692
Matt Buckley16dec1f2022-06-07 21:46:20 +0000693 // Did our reference frame wait for an appropriate vsync before calling into hwc
694 const bool waitedOnHwcPresentTime = hwcPresentDelayedTime.has_value() &&
695 *hwcPresentDelayedTime > *hwcPresentStartTime &&
696 *hwcPresentDelayedTime < *hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000697
698 // Use validate start here if we skipped it because we did validate + present together
Matt Buckley16dec1f2022-06-07 21:46:20 +0000699 timeline.hwcPresentStartTime = skippedValidate ? *hwcValidateStartTime : *hwcPresentStartTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000700
701 // Use validate end here if we skipped it because we did validate + present together
Matt Buckley16dec1f2022-06-07 21:46:20 +0000702 timeline.hwcPresentEndTime = skippedValidate ? *hwcValidateEndTime : *hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000703
Matt Buckley16dec1f2022-06-07 21:46:20 +0000704 // How long hwc present was delayed waiting for the next appropriate vsync
705 timeline.hwcPresentDelayDuration =
Matt Buckley2fa85012022-08-30 22:38:45 +0000706 (waitedOnHwcPresentTime ? *hwcPresentDelayedTime - *hwcPresentStartTime : 0ns);
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700707 // When we started waiting for the present fence after calling into hwc present
708 timeline.presentFenceWaitStartTime =
Matt Buckley16dec1f2022-06-07 21:46:20 +0000709 timeline.hwcPresentStartTime + timeline.hwcPresentDelayDuration + fenceWaitStartDelay;
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700710 timeline.probablyWaitsForPresentFence = fenceTime > timeline.presentFenceWaitStartTime &&
Matt Buckley16dec1f2022-06-07 21:46:20 +0000711 fenceTime < timeline.hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000712
Matt Buckley16dec1f2022-06-07 21:46:20 +0000713 // How long we ran after we finished waiting for the fence but before hwc present finished
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700714 timeline.postPresentFenceHwcPresentDuration = timeline.hwcPresentEndTime -
715 (timeline.probablyWaitsForPresentFence ? fenceTime
716 : timeline.presentFenceWaitStartTime);
Matt Buckley50c44062022-01-17 20:48:10 +0000717 return timeline;
718}
719
720std::optional<PowerAdvisor::GpuTimeline> PowerAdvisor::DisplayTimingData::estimateGpuTiming(
Matt Buckley2fa85012022-08-30 22:38:45 +0000721 std::optional<TimePoint> previousEndTime) {
Xiang Wangaab31162024-03-12 19:48:08 -0700722 if (!(requiresRenderEngine && lastValidGpuStartTime.has_value() && gpuEndFenceTime)) {
Matt Buckley50c44062022-01-17 20:48:10 +0000723 return std::nullopt;
724 }
Matt Buckley2fa85012022-08-30 22:38:45 +0000725 const TimePoint latestGpuStartTime =
726 std::max(previousEndTime.value_or(TimePoint{0ns}), *gpuStartTime);
727 const nsecs_t gpuEndFenceSignal = gpuEndFenceTime->getSignalTime();
728 Duration gpuDuration{0ns};
729 if (gpuEndFenceSignal != Fence::SIGNAL_TIME_INVALID &&
730 gpuEndFenceSignal != Fence::SIGNAL_TIME_PENDING) {
731 const TimePoint latestGpuEndTime = TimePoint::fromNs(gpuEndFenceSignal);
732
Matt Buckley50c44062022-01-17 20:48:10 +0000733 // If we know how long the most recent gpu duration was, use that
734 gpuDuration = latestGpuEndTime - latestGpuStartTime;
735 } else if (lastValidGpuEndTime.has_value()) {
736 // If we don't have the fence data, use the most recent information we do have
737 gpuDuration = *lastValidGpuEndTime - *lastValidGpuStartTime;
Matt Buckley2fa85012022-08-30 22:38:45 +0000738 if (gpuEndFenceSignal == Fence::SIGNAL_TIME_PENDING) {
Matt Buckley50c44062022-01-17 20:48:10 +0000739 // If pending but went over the previous duration, use current time as the end
Matt Buckley2fa85012022-08-30 22:38:45 +0000740 gpuDuration = std::max(gpuDuration, Duration{TimePoint::now() - latestGpuStartTime});
Matt Buckley50c44062022-01-17 20:48:10 +0000741 }
742 }
743 return GpuTimeline{.duration = gpuDuration, .startTime = latestGpuStartTime};
744}
745
Matt Buckley0538cae2022-11-08 23:12:04 +0000746const bool PowerAdvisor::sTraceHintSessionData =
Xiang Wang56dc1042024-03-22 03:58:46 +0000747 base::GetBoolProperty(std::string("debug.sf.trace_hint_sessions"), false);
Matt Buckleyef51fba2021-10-12 19:30:12 +0000748
Matt Buckleyac15a1b2023-02-28 06:51:28 +0000749const Duration PowerAdvisor::sTargetSafetyMargin = std::chrono::microseconds(
750 base::GetIntProperty<int64_t>("debug.sf.hint_margin_us",
751 ticks<std::micro>(PowerAdvisor::kDefaultTargetSafetyMargin)));
752
Matt Buckley676e4392023-05-25 22:09:26 +0000753const bool PowerAdvisor::sUseReportActualDuration =
754 base::GetBoolProperty(std::string("debug.adpf.use_report_actual_duration"), true);
755
Matt Buckley0538cae2022-11-08 23:12:04 +0000756power::PowerHalController& PowerAdvisor::getPowerHal() {
757 static std::once_flag halFlag;
758 std::call_once(halFlag, [this] { mPowerHal->init(); });
759 return *mPowerHal;
Michael Wright1509a232018-06-21 02:50:34 +0100760}
761
762} // namespace impl
763} // namespace Hwc2
764} // namespace android