blob: e005ad3e0331148d56c1ccb2e3a4cda8836edbaf [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
Xiang Wang99f6f3c2023-05-22 13:12:16 -070034#include <aidl/android/hardware/power/IPower.h>
35#include <aidl/android/hardware/power/IPowerHintSession.h>
36#include <aidl/android/hardware/power/WorkDuration.h>
Matt Buckley06f299a2021-09-24 19:43:51 +000037
Dan Stoza030fbc12020-02-19 15:32:01 -080038#include <binder/IServiceManager.h>
39
40#include "../SurfaceFlingerProperties.h"
41
Michael Wright1509a232018-06-21 02:50:34 +010042#include "PowerAdvisor.h"
Alec Mouridea1ac52021-06-23 18:12:18 -070043#include "SurfaceFlinger.h"
Michael Wright1509a232018-06-21 02:50:34 +010044
45namespace android {
46namespace Hwc2 {
47
48PowerAdvisor::~PowerAdvisor() = default;
49
50namespace impl {
51
Xiang Wang99f6f3c2023-05-22 13:12:16 -070052using aidl::android::hardware::power::Boost;
53using aidl::android::hardware::power::IPowerHintSession;
54using aidl::android::hardware::power::Mode;
55using aidl::android::hardware::power::SessionHint;
56using aidl::android::hardware::power::WorkDuration;
Matt Buckley06f299a2021-09-24 19:43:51 +000057
Michael Wright1509a232018-06-21 02:50:34 +010058PowerAdvisor::~PowerAdvisor() = default;
59
Dan Stoza030fbc12020-02-19 15:32:01 -080060namespace {
Alec Mouri29382ad2022-05-11 18:38:38 +000061std::chrono::milliseconds getUpdateTimeout() {
Dan Stoza030fbc12020-02-19 15:32:01 -080062 // Default to a timeout of 80ms if nothing else is specified
Alec Mouri29382ad2022-05-11 18:38:38 +000063 static std::chrono::milliseconds timeout =
64 std::chrono::milliseconds(sysprop::display_update_imminent_timeout_ms(80));
Dan Stoza030fbc12020-02-19 15:32:01 -080065 return timeout;
66}
67
Ady Abrahamabce1652022-02-24 10:51:19 -080068void traceExpensiveRendering(bool enabled) {
69 if (enabled) {
70 ATRACE_ASYNC_BEGIN("ExpensiveRendering", 0);
71 } else {
72 ATRACE_ASYNC_END("ExpensiveRendering", 0);
73 }
74}
75
Dan Stoza030fbc12020-02-19 15:32:01 -080076} // namespace
77
Matt Buckley0538cae2022-11-08 23:12:04 +000078PowerAdvisor::PowerAdvisor(SurfaceFlinger& flinger)
79 : mPowerHal(std::make_unique<power::PowerHalController>()), mFlinger(flinger) {
Alec Mouri29382ad2022-05-11 18:38:38 +000080 if (getUpdateTimeout() > 0ms) {
81 mScreenUpdateTimer.emplace("UpdateImminentTimer", getUpdateTimeout(),
Alec Mouric059dcf2022-05-05 23:40:07 +000082 /* resetCallback */ nullptr,
83 /* timeoutCallback */
84 [this] {
Alec Mouri29382ad2022-05-11 18:38:38 +000085 while (true) {
86 auto timeSinceLastUpdate = std::chrono::nanoseconds(
87 systemTime() - mLastScreenUpdatedTime.load());
88 if (timeSinceLastUpdate >= getUpdateTimeout()) {
89 break;
90 }
Alec Mouric059dcf2022-05-05 23:40:07 +000091 // We may try to disable expensive rendering and allow
92 // for sending DISPLAY_UPDATE_IMMINENT hints too early if
93 // we idled very shortly after updating the screen, so
94 // make sure we wait enough time.
Alec Mouri29382ad2022-05-11 18:38:38 +000095 std::this_thread::sleep_for(getUpdateTimeout() -
96 timeSinceLastUpdate);
Alec Mouric059dcf2022-05-05 23:40:07 +000097 }
98 mSendUpdateImminent.store(true);
99 mFlinger.disableExpensiveRendering();
100 });
101 }
102}
Alec Mouridea1ac52021-06-23 18:12:18 -0700103
104void PowerAdvisor::init() {
105 // Defer starting the screen update timer until SurfaceFlinger finishes construction.
Alec Mouric059dcf2022-05-05 23:40:07 +0000106 if (mScreenUpdateTimer) {
107 mScreenUpdateTimer->start();
Dan Stoza030fbc12020-02-19 15:32:01 -0800108 }
109}
Michael Wright1509a232018-06-21 02:50:34 +0100110
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700111void PowerAdvisor::onBootFinished() {
112 mBootFinished.store(true);
113}
114
Peiyong Lin74ca2f42019-01-14 19:36:57 -0800115void PowerAdvisor::setExpensiveRenderingExpected(DisplayId displayId, bool expected) {
Matt Buckley0538cae2022-11-08 23:12:04 +0000116 if (!mHasExpensiveRendering) {
117 ALOGV("Skipped sending EXPENSIVE_RENDERING because HAL doesn't support it");
118 return;
119 }
Michael Wright1509a232018-06-21 02:50:34 +0100120 if (expected) {
121 mExpensiveDisplays.insert(displayId);
122 } else {
123 mExpensiveDisplays.erase(displayId);
124 }
125
Michael Wright1509a232018-06-21 02:50:34 +0100126 const bool expectsExpensiveRendering = !mExpensiveDisplays.empty();
127 if (mNotifiedExpensiveRendering != expectsExpensiveRendering) {
Matt Buckley0538cae2022-11-08 23:12:04 +0000128 auto ret = getPowerHal().setMode(Mode::EXPENSIVE_RENDERING, expectsExpensiveRendering);
129 if (!ret.isOk()) {
130 if (ret.isUnsupported()) {
131 mHasExpensiveRendering = false;
132 }
Michael Wright1509a232018-06-21 02:50:34 +0100133 return;
134 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800135
Michael Wright1509a232018-06-21 02:50:34 +0100136 mNotifiedExpensiveRendering = expectsExpensiveRendering;
Matt Buckley0538cae2022-11-08 23:12:04 +0000137 traceExpensiveRendering(mNotifiedExpensiveRendering);
Michael Wright1509a232018-06-21 02:50:34 +0100138 }
139}
140
jimmyshiu4e211772023-06-15 15:18:38 +0000141void PowerAdvisor::notifyCpuLoadUp() {
142 // Only start sending this notification once the system has booted so we don't introduce an
143 // early-boot dependency on Power HAL
144 if (!mBootFinished.load()) {
145 return;
146 }
147 if (usePowerHintSession() && ensurePowerHintSessionRunning()) {
148 std::lock_guard lock(mHintSessionMutex);
149 auto ret = mHintSession->sendHint(SessionHint::CPU_LOAD_UP);
150 if (!ret.isOk()) {
151 mHintSessionRunning = false;
152 }
153 }
154}
155
Matt Buckley15ecd1c2022-11-01 21:57:16 +0000156void PowerAdvisor::notifyDisplayUpdateImminentAndCpuReset() {
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700157 // Only start sending this notification once the system has booted so we don't introduce an
158 // early-boot dependency on Power HAL
159 if (!mBootFinished.load()) {
160 return;
161 }
162
Alec Mouric059dcf2022-05-05 23:40:07 +0000163 if (mSendUpdateImminent.exchange(false)) {
Matt Buckley0538cae2022-11-08 23:12:04 +0000164 ALOGV("AIDL notifyDisplayUpdateImminentAndCpuReset");
165 if (usePowerHintSession() && ensurePowerHintSessionRunning()) {
166 std::lock_guard lock(mHintSessionMutex);
167 auto ret = mHintSession->sendHint(SessionHint::CPU_LOAD_RESET);
168 if (!ret.isOk()) {
169 mHintSessionRunning = false;
170 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800171 }
172
Matt Buckley0538cae2022-11-08 23:12:04 +0000173 if (!mHasDisplayUpdateImminent) {
174 ALOGV("Skipped sending DISPLAY_UPDATE_IMMINENT because HAL doesn't support it");
175 } else {
176 auto ret = getPowerHal().setBoost(Boost::DISPLAY_UPDATE_IMMINENT, 0);
177 if (ret.isUnsupported()) {
178 mHasDisplayUpdateImminent = false;
179 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800180 }
Alec Mouric059dcf2022-05-05 23:40:07 +0000181
182 if (mScreenUpdateTimer) {
183 mScreenUpdateTimer->reset();
184 } else {
185 // If we don't have a screen update timer, then we don't throttle power hal calls so
186 // flip this bit back to allow for calling into power hal again.
187 mSendUpdateImminent.store(true);
188 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800189 }
190
Alec Mouric059dcf2022-05-05 23:40:07 +0000191 if (mScreenUpdateTimer) {
192 mLastScreenUpdatedTime.store(systemTime());
Dan Stoza030fbc12020-02-19 15:32:01 -0800193 }
194}
195
Matt Buckley06f299a2021-09-24 19:43:51 +0000196// checks both if it supports and if it's enabled
197bool PowerAdvisor::usePowerHintSession() {
198 // uses cached value since the underlying support and flag are unlikely to change at runtime
Matt Buckley0538cae2022-11-08 23:12:04 +0000199 return mHintSessionEnabled.value_or(false) && supportsPowerHintSession();
Matt Buckley06f299a2021-09-24 19:43:51 +0000200}
201
202bool PowerAdvisor::supportsPowerHintSession() {
203 // cache to avoid needing lock every time
Matt Buckley0538cae2022-11-08 23:12:04 +0000204 if (!mSupportsHintSession.has_value()) {
205 mSupportsHintSession = getPowerHal().getHintSessionPreferredRate().isOk();
Matt Buckley06f299a2021-09-24 19:43:51 +0000206 }
Matt Buckley0538cae2022-11-08 23:12:04 +0000207 return *mSupportsHintSession;
Matt Buckley06f299a2021-09-24 19:43:51 +0000208}
209
Matt Buckley0538cae2022-11-08 23:12:04 +0000210bool PowerAdvisor::ensurePowerHintSessionRunning() {
211 if (!mHintSessionRunning && !mHintSessionThreadIds.empty() && usePowerHintSession()) {
212 startPowerHintSession(mHintSessionThreadIds);
213 }
214 return mHintSessionRunning;
Matt Buckley06f299a2021-09-24 19:43:51 +0000215}
216
Matt Buckley0538cae2022-11-08 23:12:04 +0000217void PowerAdvisor::updateTargetWorkDuration(Duration targetDuration) {
Matt Buckleyef51fba2021-10-12 19:30:12 +0000218 if (!usePowerHintSession()) {
Matt Buckley06f299a2021-09-24 19:43:51 +0000219 ALOGV("Power hint session target duration cannot be set, skipping");
220 return;
221 }
Matt Buckley0538cae2022-11-08 23:12:04 +0000222 ATRACE_CALL();
Matt Buckley06f299a2021-09-24 19:43:51 +0000223 {
Matt Buckley0538cae2022-11-08 23:12:04 +0000224 mTargetDuration = targetDuration;
225 if (sTraceHintSessionData) ATRACE_INT64("Time target", targetDuration.ns());
226 if (ensurePowerHintSessionRunning() && (targetDuration != mLastTargetDurationSent)) {
227 ALOGV("Sending target time: %" PRId64 "ns", targetDuration.ns());
228 mLastTargetDurationSent = targetDuration;
229 std::lock_guard lock(mHintSessionMutex);
230 auto ret = mHintSession->updateTargetWorkDuration(targetDuration.ns());
231 if (!ret.isOk()) {
232 ALOGW("Failed to set power hint target work duration with error: %s",
Xiang Wang99f6f3c2023-05-22 13:12:16 -0700233 ret.getDescription().c_str());
Matt Buckley0538cae2022-11-08 23:12:04 +0000234 mHintSessionRunning = false;
235 }
Matt Buckley06f299a2021-09-24 19:43:51 +0000236 }
237 }
238}
239
Matt Buckley0538cae2022-11-08 23:12:04 +0000240void PowerAdvisor::reportActualWorkDuration() {
Matt Buckley676e4392023-05-25 22:09:26 +0000241 if (!mBootFinished || !sUseReportActualDuration || !usePowerHintSession()) {
Matt Buckley06f299a2021-09-24 19:43:51 +0000242 ALOGV("Actual work duration power hint cannot be sent, skipping");
243 return;
244 }
Matt Buckley0538cae2022-11-08 23:12:04 +0000245 ATRACE_CALL();
246 std::optional<Duration> actualDuration = estimateWorkDuration();
247 if (!actualDuration.has_value() || actualDuration < 0ns || !ensurePowerHintSessionRunning()) {
248 ALOGV("Failed to send actual work duration, skipping");
Matt Buckley50c44062022-01-17 20:48:10 +0000249 return;
250 }
Matt Buckley0538cae2022-11-08 23:12:04 +0000251 actualDuration = std::make_optional(*actualDuration + sTargetSafetyMargin);
252 mActualDuration = actualDuration;
253 WorkDuration duration;
Peiyong Lin81780c42023-10-08 21:11:26 +0000254 duration.workPeriodStartTimestampNanos = mCommitStartTimes[0].ns();
255 // TODO(b/284324521): Correctly calculate total duration.
Matt Buckley0538cae2022-11-08 23:12:04 +0000256 duration.durationNanos = actualDuration->ns();
Peiyong Lin81780c42023-10-08 21:11:26 +0000257 duration.cpuDurationNanos = actualDuration->ns();
258 // TODO(b/284324521): Calculate RenderEngine GPU time.
259 duration.gpuDurationNanos = 0;
Matt Buckley0538cae2022-11-08 23:12:04 +0000260 duration.timeStampNanos = TimePoint::now().ns();
261 mHintSessionQueue.push_back(duration);
Matt Buckley50c44062022-01-17 20:48:10 +0000262
Matt Buckley0538cae2022-11-08 23:12:04 +0000263 if (sTraceHintSessionData) {
264 ATRACE_INT64("Measured duration", actualDuration->ns());
265 ATRACE_INT64("Target error term", Duration{*actualDuration - mTargetDuration}.ns());
266 ATRACE_INT64("Reported duration", actualDuration->ns());
267 ATRACE_INT64("Reported target", mLastTargetDurationSent.ns());
268 ATRACE_INT64("Reported target error term",
269 Duration{*actualDuration - mLastTargetDurationSent}.ns());
270 }
271
272 ALOGV("Sending actual work duration of: %" PRId64 " on reported target: %" PRId64
273 " with error: %" PRId64,
274 actualDuration->ns(), mLastTargetDurationSent.ns(),
275 Duration{*actualDuration - mLastTargetDurationSent}.ns());
276
277 {
278 std::lock_guard lock(mHintSessionMutex);
279 auto ret = mHintSession->reportActualWorkDuration(mHintSessionQueue);
280 if (!ret.isOk()) {
281 ALOGW("Failed to report actual work durations with error: %s",
Xiang Wang99f6f3c2023-05-22 13:12:16 -0700282 ret.getDescription().c_str());
Matt Buckley0538cae2022-11-08 23:12:04 +0000283 mHintSessionRunning = false;
284 return;
Matt Buckley50c44062022-01-17 20:48:10 +0000285 }
286 }
Matt Buckley0538cae2022-11-08 23:12:04 +0000287 mHintSessionQueue.clear();
Matt Buckley50c44062022-01-17 20:48:10 +0000288}
289
Matt Buckley0538cae2022-11-08 23:12:04 +0000290void PowerAdvisor::enablePowerHintSession(bool enabled) {
291 mHintSessionEnabled = enabled;
Matt Buckley06f299a2021-09-24 19:43:51 +0000292}
293
Matt Buckleyef51fba2021-10-12 19:30:12 +0000294bool PowerAdvisor::startPowerHintSession(const std::vector<int32_t>& threadIds) {
Matt Buckley0538cae2022-11-08 23:12:04 +0000295 if (!mBootFinished.load()) {
296 return false;
Matt Buckleyef51fba2021-10-12 19:30:12 +0000297 }
Matt Buckley0538cae2022-11-08 23:12:04 +0000298 if (!usePowerHintSession()) {
299 ALOGI("Cannot start power hint session: disabled or unsupported");
300 return false;
301 }
302 if (mHintSessionRunning) {
303 ALOGE("Cannot start power hint session: already running");
304 return false;
305 }
306 LOG_ALWAYS_FATAL_IF(threadIds.empty(), "No thread IDs provided to power hint session!");
Matt Buckleyef51fba2021-10-12 19:30:12 +0000307 {
Matt Buckley0538cae2022-11-08 23:12:04 +0000308 std::lock_guard lock(mHintSessionMutex);
309 mHintSession = nullptr;
310 mHintSessionThreadIds = threadIds;
311
312 auto ret = getPowerHal().createHintSession(getpid(), static_cast<int32_t>(getuid()),
313 threadIds, mTargetDuration.ns());
314
315 if (ret.isOk()) {
316 mHintSessionRunning = true;
317 mHintSession = ret.value();
Matt Buckleyef51fba2021-10-12 19:30:12 +0000318 }
319 }
Matt Buckley0538cae2022-11-08 23:12:04 +0000320 return mHintSessionRunning;
Matt Buckleyef51fba2021-10-12 19:30:12 +0000321}
322
Matt Buckley50c44062022-01-17 20:48:10 +0000323void PowerAdvisor::setGpuFenceTime(DisplayId displayId, std::unique_ptr<FenceTime>&& fenceTime) {
324 DisplayTimingData& displayData = mDisplayTimingData[displayId];
325 if (displayData.gpuEndFenceTime) {
326 nsecs_t signalTime = displayData.gpuEndFenceTime->getSignalTime();
327 if (signalTime != Fence::SIGNAL_TIME_INVALID && signalTime != Fence::SIGNAL_TIME_PENDING) {
328 for (auto&& [_, otherDisplayData] : mDisplayTimingData) {
329 // If the previous display started before us but ended after we should have
330 // started, then it likely delayed our start time and we must compensate for that.
331 // Displays finishing earlier should have already made their way through this call
332 // and swapped their timing into "lastValid" from "latest", so we check that here.
333 if (!otherDisplayData.lastValidGpuStartTime.has_value()) continue;
334 if ((*otherDisplayData.lastValidGpuStartTime < *displayData.gpuStartTime) &&
335 (*otherDisplayData.lastValidGpuEndTime > *displayData.gpuStartTime)) {
336 displayData.lastValidGpuStartTime = *otherDisplayData.lastValidGpuEndTime;
337 break;
338 }
339 }
340 displayData.lastValidGpuStartTime = displayData.gpuStartTime;
Matt Buckley2fa85012022-08-30 22:38:45 +0000341 displayData.lastValidGpuEndTime = TimePoint::fromNs(signalTime);
Matt Buckley50c44062022-01-17 20:48:10 +0000342 }
343 }
344 displayData.gpuEndFenceTime = std::move(fenceTime);
Matt Buckley2fa85012022-08-30 22:38:45 +0000345 displayData.gpuStartTime = TimePoint::now();
Matt Buckley50c44062022-01-17 20:48:10 +0000346}
347
Matt Buckley2fa85012022-08-30 22:38:45 +0000348void PowerAdvisor::setHwcValidateTiming(DisplayId displayId, TimePoint validateStartTime,
349 TimePoint validateEndTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000350 DisplayTimingData& displayData = mDisplayTimingData[displayId];
Matt Buckley16dec1f2022-06-07 21:46:20 +0000351 displayData.hwcValidateStartTime = validateStartTime;
352 displayData.hwcValidateEndTime = validateEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000353}
354
Matt Buckley2fa85012022-08-30 22:38:45 +0000355void PowerAdvisor::setHwcPresentTiming(DisplayId displayId, TimePoint presentStartTime,
356 TimePoint presentEndTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000357 DisplayTimingData& displayData = mDisplayTimingData[displayId];
Matt Buckley16dec1f2022-06-07 21:46:20 +0000358 displayData.hwcPresentStartTime = presentStartTime;
359 displayData.hwcPresentEndTime = presentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000360}
361
362void PowerAdvisor::setSkippedValidate(DisplayId displayId, bool skipped) {
363 mDisplayTimingData[displayId].skippedValidate = skipped;
364}
365
366void PowerAdvisor::setRequiresClientComposition(DisplayId displayId,
367 bool requiresClientComposition) {
368 mDisplayTimingData[displayId].usedClientComposition = requiresClientComposition;
369}
370
Matt Buckley2fa85012022-08-30 22:38:45 +0000371void PowerAdvisor::setExpectedPresentTime(TimePoint expectedPresentTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000372 mExpectedPresentTimes.append(expectedPresentTime);
373}
374
Matt Buckley2fa85012022-08-30 22:38:45 +0000375void PowerAdvisor::setSfPresentTiming(TimePoint presentFenceTime, TimePoint presentEndTime) {
Matt Buckley1809d902022-08-05 06:51:43 +0000376 mLastSfPresentEndTime = presentEndTime;
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700377 mLastPresentFenceTime = presentFenceTime;
378}
379
Matt Buckley2fa85012022-08-30 22:38:45 +0000380void PowerAdvisor::setFrameDelay(Duration frameDelayDuration) {
Matt Buckley50c44062022-01-17 20:48:10 +0000381 mFrameDelayDuration = frameDelayDuration;
382}
383
Matt Buckley2fa85012022-08-30 22:38:45 +0000384void PowerAdvisor::setHwcPresentDelayedTime(DisplayId displayId, TimePoint earliestFrameStartTime) {
385 mDisplayTimingData[displayId].hwcPresentDelayedTime = earliestFrameStartTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000386}
387
Matt Buckley2fa85012022-08-30 22:38:45 +0000388void PowerAdvisor::setCommitStart(TimePoint commitStartTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000389 mCommitStartTimes.append(commitStartTime);
390}
391
Matt Buckley2fa85012022-08-30 22:38:45 +0000392void PowerAdvisor::setCompositeEnd(TimePoint compositeEndTime) {
393 mLastPostcompDuration = compositeEndTime - mLastSfPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000394}
395
396void PowerAdvisor::setDisplays(std::vector<DisplayId>& displayIds) {
397 mDisplayIds = displayIds;
398}
399
Matt Buckley2fa85012022-08-30 22:38:45 +0000400void PowerAdvisor::setTotalFrameTargetWorkDuration(Duration targetDuration) {
Matt Buckley50c44062022-01-17 20:48:10 +0000401 mTotalFrameTargetDuration = targetDuration;
402}
403
404std::vector<DisplayId> PowerAdvisor::getOrderedDisplayIds(
Matt Buckley2fa85012022-08-30 22:38:45 +0000405 std::optional<TimePoint> DisplayTimingData::*sortBy) {
Matt Buckley50c44062022-01-17 20:48:10 +0000406 std::vector<DisplayId> sortedDisplays;
407 std::copy_if(mDisplayIds.begin(), mDisplayIds.end(), std::back_inserter(sortedDisplays),
408 [&](DisplayId id) {
409 return mDisplayTimingData.count(id) &&
410 (mDisplayTimingData[id].*sortBy).has_value();
411 });
412 std::sort(sortedDisplays.begin(), sortedDisplays.end(), [&](DisplayId idA, DisplayId idB) {
413 return *(mDisplayTimingData[idA].*sortBy) < *(mDisplayTimingData[idB].*sortBy);
414 });
415 return sortedDisplays;
416}
417
Matt Buckley0538cae2022-11-08 23:12:04 +0000418std::optional<Duration> PowerAdvisor::estimateWorkDuration() {
419 if (!mExpectedPresentTimes.isFull() || !mCommitStartTimes.isFull()) {
Matt Buckley50c44062022-01-17 20:48:10 +0000420 return std::nullopt;
421 }
422
423 // Tracks when we finish presenting to hwc
Matt Buckley0538cae2022-11-08 23:12:04 +0000424 TimePoint estimatedHwcEndTime = mCommitStartTimes[0];
Matt Buckley50c44062022-01-17 20:48:10 +0000425
426 // How long we spent this frame not doing anything, waiting for fences or vsync
Matt Buckley2fa85012022-08-30 22:38:45 +0000427 Duration idleDuration = 0ns;
Matt Buckley50c44062022-01-17 20:48:10 +0000428
429 // Most recent previous gpu end time in the current frame, probably from a prior display, used
430 // 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 +0000431 std::optional<TimePoint> previousValidGpuEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000432
433 // The currently estimated gpu end time for the frame,
434 // used to accumulate gpu time as we iterate over the active displays
Matt Buckley2fa85012022-08-30 22:38:45 +0000435 std::optional<TimePoint> estimatedGpuEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000436
Matt Buckley50c44062022-01-17 20:48:10 +0000437 // The timing info for the previously calculated display, if there was one
Matt Buckley0538cae2022-11-08 23:12:04 +0000438 std::optional<DisplayTimeline> previousDisplayTiming;
Matt Buckley50c44062022-01-17 20:48:10 +0000439 std::vector<DisplayId>&& displayIds =
Matt Buckley16dec1f2022-06-07 21:46:20 +0000440 getOrderedDisplayIds(&DisplayTimingData::hwcPresentStartTime);
Matt Buckley0538cae2022-11-08 23:12:04 +0000441 DisplayTimeline displayTiming;
Matt Buckley50c44062022-01-17 20:48:10 +0000442
Matt Buckley1809d902022-08-05 06:51:43 +0000443 // Iterate over the displays that use hwc in the same order they are presented
Matt Buckley50c44062022-01-17 20:48:10 +0000444 for (DisplayId displayId : displayIds) {
445 if (mDisplayTimingData.count(displayId) == 0) {
446 continue;
447 }
448
449 auto& displayData = mDisplayTimingData.at(displayId);
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700450
Matt Buckley0538cae2022-11-08 23:12:04 +0000451 displayTiming = displayData.calculateDisplayTimeline(mLastPresentFenceTime);
Matt Buckley50c44062022-01-17 20:48:10 +0000452
Matt Buckley16dec1f2022-06-07 21:46:20 +0000453 // If this is the first display, include the duration before hwc present starts
Matt Buckley0538cae2022-11-08 23:12:04 +0000454 if (!previousDisplayTiming.has_value()) {
455 estimatedHwcEndTime += displayTiming.hwcPresentStartTime - mCommitStartTimes[0];
Matt Buckley16dec1f2022-06-07 21:46:20 +0000456 } else { // Otherwise add the time since last display's hwc present finished
Matt Buckley0538cae2022-11-08 23:12:04 +0000457 estimatedHwcEndTime +=
458 displayTiming.hwcPresentStartTime - previousDisplayTiming->hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000459 }
460
Matt Buckley50c44062022-01-17 20:48:10 +0000461 // Update predicted present finish time with this display's present time
Matt Buckley0538cae2022-11-08 23:12:04 +0000462 estimatedHwcEndTime = displayTiming.hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000463
464 // Track how long we spent waiting for the fence, can be excluded from the timing estimate
Matt Buckley0538cae2022-11-08 23:12:04 +0000465 idleDuration += displayTiming.probablyWaitsForPresentFence
466 ? mLastPresentFenceTime - displayTiming.presentFenceWaitStartTime
Matt Buckley2fa85012022-08-30 22:38:45 +0000467 : 0ns;
Matt Buckley50c44062022-01-17 20:48:10 +0000468
469 // Track how long we spent waiting to present, can be excluded from the timing estimate
Matt Buckley0538cae2022-11-08 23:12:04 +0000470 idleDuration += displayTiming.hwcPresentDelayDuration;
Matt Buckley50c44062022-01-17 20:48:10 +0000471
472 // Estimate the reference frame's gpu timing
473 auto gpuTiming = displayData.estimateGpuTiming(previousValidGpuEndTime);
474 if (gpuTiming.has_value()) {
475 previousValidGpuEndTime = gpuTiming->startTime + gpuTiming->duration;
476
477 // Estimate the prediction frame's gpu end time from the reference frame
Matt Buckley0538cae2022-11-08 23:12:04 +0000478 estimatedGpuEndTime = std::max(displayTiming.hwcPresentStartTime,
Matt Buckley2fa85012022-08-30 22:38:45 +0000479 estimatedGpuEndTime.value_or(TimePoint{0ns})) +
Matt Buckley50c44062022-01-17 20:48:10 +0000480 gpuTiming->duration;
481 }
Matt Buckley0538cae2022-11-08 23:12:04 +0000482 previousDisplayTiming = displayTiming;
Matt Buckley50c44062022-01-17 20:48:10 +0000483 }
Matt Buckley2fa85012022-08-30 22:38:45 +0000484 ATRACE_INT64("Idle duration", idleDuration.ns());
Matt Buckley50c44062022-01-17 20:48:10 +0000485
Matt Buckley0538cae2022-11-08 23:12:04 +0000486 TimePoint estimatedFlingerEndTime = mLastSfPresentEndTime;
Matt Buckley1809d902022-08-05 06:51:43 +0000487
Matt Buckley50c44062022-01-17 20:48:10 +0000488 // 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 +0000489 estimatedHwcEndTime -= idleDuration;
Matt Buckley1809d902022-08-05 06:51:43 +0000490 estimatedFlingerEndTime -= idleDuration;
Matt Buckley50c44062022-01-17 20:48:10 +0000491
492 // We finish the frame when both present and the gpu are done, so wait for the later of the two
493 // Also add the frame delay duration since the target did not move while we were delayed
Matt Buckley2fa85012022-08-30 22:38:45 +0000494 Duration totalDuration = mFrameDelayDuration +
Matt Buckley0538cae2022-11-08 23:12:04 +0000495 std::max(estimatedHwcEndTime, estimatedGpuEndTime.value_or(TimePoint{0ns})) -
Matt Buckley2fa85012022-08-30 22:38:45 +0000496 mCommitStartTimes[0];
Matt Buckley50c44062022-01-17 20:48:10 +0000497
498 // We finish SurfaceFlinger when post-composition finishes, so add that in here
Matt Buckley2fa85012022-08-30 22:38:45 +0000499 Duration flingerDuration =
Matt Buckley1809d902022-08-05 06:51:43 +0000500 estimatedFlingerEndTime + mLastPostcompDuration - mCommitStartTimes[0];
501
502 // Combine the two timings into a single normalized one
Matt Buckley2fa85012022-08-30 22:38:45 +0000503 Duration combinedDuration = combineTimingEstimates(totalDuration, flingerDuration);
Matt Buckley50c44062022-01-17 20:48:10 +0000504
505 return std::make_optional(combinedDuration);
506}
507
Matt Buckley2fa85012022-08-30 22:38:45 +0000508Duration PowerAdvisor::combineTimingEstimates(Duration totalDuration, Duration flingerDuration) {
509 Duration targetDuration{0ns};
Matt Buckley0538cae2022-11-08 23:12:04 +0000510 targetDuration = mTargetDuration;
Matt Buckley50c44062022-01-17 20:48:10 +0000511 if (!mTotalFrameTargetDuration.has_value()) return flingerDuration;
512
513 // Normalize total to the flinger target (vsync period) since that's how often we actually send
514 // hints
Matt Buckley2fa85012022-08-30 22:38:45 +0000515 Duration normalizedTotalDuration = Duration::fromNs((targetDuration.ns() * totalDuration.ns()) /
516 mTotalFrameTargetDuration->ns());
Matt Buckley50c44062022-01-17 20:48:10 +0000517 return std::max(flingerDuration, normalizedTotalDuration);
518}
519
Matt Buckley50c44062022-01-17 20:48:10 +0000520PowerAdvisor::DisplayTimeline PowerAdvisor::DisplayTimingData::calculateDisplayTimeline(
Matt Buckley2fa85012022-08-30 22:38:45 +0000521 TimePoint fenceTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000522 DisplayTimeline timeline;
Matt Buckley16dec1f2022-06-07 21:46:20 +0000523 // How long between calling hwc present and trying to wait on the fence
Matt Buckley2fa85012022-08-30 22:38:45 +0000524 const Duration fenceWaitStartDelay =
525 (skippedValidate ? kFenceWaitStartDelaySkippedValidate : kFenceWaitStartDelayValidated);
Matt Buckley50c44062022-01-17 20:48:10 +0000526
Matt Buckley16dec1f2022-06-07 21:46:20 +0000527 // Did our reference frame wait for an appropriate vsync before calling into hwc
528 const bool waitedOnHwcPresentTime = hwcPresentDelayedTime.has_value() &&
529 *hwcPresentDelayedTime > *hwcPresentStartTime &&
530 *hwcPresentDelayedTime < *hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000531
532 // Use validate start here if we skipped it because we did validate + present together
Matt Buckley16dec1f2022-06-07 21:46:20 +0000533 timeline.hwcPresentStartTime = skippedValidate ? *hwcValidateStartTime : *hwcPresentStartTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000534
535 // Use validate end here if we skipped it because we did validate + present together
Matt Buckley16dec1f2022-06-07 21:46:20 +0000536 timeline.hwcPresentEndTime = skippedValidate ? *hwcValidateEndTime : *hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000537
Matt Buckley16dec1f2022-06-07 21:46:20 +0000538 // How long hwc present was delayed waiting for the next appropriate vsync
539 timeline.hwcPresentDelayDuration =
Matt Buckley2fa85012022-08-30 22:38:45 +0000540 (waitedOnHwcPresentTime ? *hwcPresentDelayedTime - *hwcPresentStartTime : 0ns);
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700541 // When we started waiting for the present fence after calling into hwc present
542 timeline.presentFenceWaitStartTime =
Matt Buckley16dec1f2022-06-07 21:46:20 +0000543 timeline.hwcPresentStartTime + timeline.hwcPresentDelayDuration + fenceWaitStartDelay;
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700544 timeline.probablyWaitsForPresentFence = fenceTime > timeline.presentFenceWaitStartTime &&
Matt Buckley16dec1f2022-06-07 21:46:20 +0000545 fenceTime < timeline.hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000546
Matt Buckley16dec1f2022-06-07 21:46:20 +0000547 // How long we ran after we finished waiting for the fence but before hwc present finished
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700548 timeline.postPresentFenceHwcPresentDuration = timeline.hwcPresentEndTime -
549 (timeline.probablyWaitsForPresentFence ? fenceTime
550 : timeline.presentFenceWaitStartTime);
Matt Buckley50c44062022-01-17 20:48:10 +0000551 return timeline;
552}
553
554std::optional<PowerAdvisor::GpuTimeline> PowerAdvisor::DisplayTimingData::estimateGpuTiming(
Matt Buckley2fa85012022-08-30 22:38:45 +0000555 std::optional<TimePoint> previousEndTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000556 if (!(usedClientComposition && lastValidGpuStartTime.has_value() && gpuEndFenceTime)) {
557 return std::nullopt;
558 }
Matt Buckley2fa85012022-08-30 22:38:45 +0000559 const TimePoint latestGpuStartTime =
560 std::max(previousEndTime.value_or(TimePoint{0ns}), *gpuStartTime);
561 const nsecs_t gpuEndFenceSignal = gpuEndFenceTime->getSignalTime();
562 Duration gpuDuration{0ns};
563 if (gpuEndFenceSignal != Fence::SIGNAL_TIME_INVALID &&
564 gpuEndFenceSignal != Fence::SIGNAL_TIME_PENDING) {
565 const TimePoint latestGpuEndTime = TimePoint::fromNs(gpuEndFenceSignal);
566
Matt Buckley50c44062022-01-17 20:48:10 +0000567 // If we know how long the most recent gpu duration was, use that
568 gpuDuration = latestGpuEndTime - latestGpuStartTime;
569 } else if (lastValidGpuEndTime.has_value()) {
570 // If we don't have the fence data, use the most recent information we do have
571 gpuDuration = *lastValidGpuEndTime - *lastValidGpuStartTime;
Matt Buckley2fa85012022-08-30 22:38:45 +0000572 if (gpuEndFenceSignal == Fence::SIGNAL_TIME_PENDING) {
Matt Buckley50c44062022-01-17 20:48:10 +0000573 // If pending but went over the previous duration, use current time as the end
Matt Buckley2fa85012022-08-30 22:38:45 +0000574 gpuDuration = std::max(gpuDuration, Duration{TimePoint::now() - latestGpuStartTime});
Matt Buckley50c44062022-01-17 20:48:10 +0000575 }
576 }
577 return GpuTimeline{.duration = gpuDuration, .startTime = latestGpuStartTime};
578}
579
Matt Buckley0538cae2022-11-08 23:12:04 +0000580const bool PowerAdvisor::sTraceHintSessionData =
Matt Buckleyef51fba2021-10-12 19:30:12 +0000581 base::GetBoolProperty(std::string("debug.sf.trace_hint_sessions"), false);
582
Matt Buckleyac15a1b2023-02-28 06:51:28 +0000583const Duration PowerAdvisor::sTargetSafetyMargin = std::chrono::microseconds(
584 base::GetIntProperty<int64_t>("debug.sf.hint_margin_us",
585 ticks<std::micro>(PowerAdvisor::kDefaultTargetSafetyMargin)));
586
Matt Buckley676e4392023-05-25 22:09:26 +0000587const bool PowerAdvisor::sUseReportActualDuration =
588 base::GetBoolProperty(std::string("debug.adpf.use_report_actual_duration"), true);
589
Matt Buckley0538cae2022-11-08 23:12:04 +0000590power::PowerHalController& PowerAdvisor::getPowerHal() {
591 static std::once_flag halFlag;
592 std::call_once(halFlag, [this] { mPowerHal->init(); });
593 return *mPowerHal;
Michael Wright1509a232018-06-21 02:50:34 +0100594}
595
596} // namespace impl
597} // namespace Hwc2
598} // namespace android