blob: 4c0a9429763e84652640a3a70c9a4635dc89704f [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 <android/hardware/power/1.3/IPower.h>
Matt Buckley06f299a2021-09-24 19:43:51 +000035#include <android/hardware/power/IPowerHintSession.h>
36#include <android/hardware/power/WorkDuration.h>
37
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
52namespace V1_0 = android::hardware::power::V1_0;
Dan Stoza030fbc12020-02-19 15:32:01 -080053namespace V1_3 = android::hardware::power::V1_3;
Michael Wright1509a232018-06-21 02:50:34 +010054using V1_3::PowerHint;
55
Dan Stoza030fbc12020-02-19 15:32:01 -080056using android::hardware::power::Boost;
57using android::hardware::power::IPower;
Matt Buckley06f299a2021-09-24 19:43:51 +000058using android::hardware::power::IPowerHintSession;
Dan Stoza030fbc12020-02-19 15:32:01 -080059using android::hardware::power::Mode;
Matt Buckley06f299a2021-09-24 19:43:51 +000060using android::hardware::power::WorkDuration;
61
Dan Stoza030fbc12020-02-19 15:32:01 -080062using scheduler::OneShotTimer;
63
Michael Wright1509a232018-06-21 02:50:34 +010064PowerAdvisor::~PowerAdvisor() = default;
65
Dan Stoza030fbc12020-02-19 15:32:01 -080066namespace {
Alec Mouri29382ad2022-05-11 18:38:38 +000067std::chrono::milliseconds getUpdateTimeout() {
Dan Stoza030fbc12020-02-19 15:32:01 -080068 // Default to a timeout of 80ms if nothing else is specified
Alec Mouri29382ad2022-05-11 18:38:38 +000069 static std::chrono::milliseconds timeout =
70 std::chrono::milliseconds(sysprop::display_update_imminent_timeout_ms(80));
Dan Stoza030fbc12020-02-19 15:32:01 -080071 return timeout;
72}
73
Ady Abrahamabce1652022-02-24 10:51:19 -080074void traceExpensiveRendering(bool enabled) {
75 if (enabled) {
76 ATRACE_ASYNC_BEGIN("ExpensiveRendering", 0);
77 } else {
78 ATRACE_ASYNC_END("ExpensiveRendering", 0);
79 }
80}
81
Dan Stoza030fbc12020-02-19 15:32:01 -080082} // namespace
83
Alec Mouric059dcf2022-05-05 23:40:07 +000084PowerAdvisor::PowerAdvisor(SurfaceFlinger& flinger) : mFlinger(flinger) {
Alec Mouri29382ad2022-05-11 18:38:38 +000085 if (getUpdateTimeout() > 0ms) {
86 mScreenUpdateTimer.emplace("UpdateImminentTimer", getUpdateTimeout(),
Alec Mouric059dcf2022-05-05 23:40:07 +000087 /* resetCallback */ nullptr,
88 /* timeoutCallback */
89 [this] {
Alec Mouri29382ad2022-05-11 18:38:38 +000090 while (true) {
91 auto timeSinceLastUpdate = std::chrono::nanoseconds(
92 systemTime() - mLastScreenUpdatedTime.load());
93 if (timeSinceLastUpdate >= getUpdateTimeout()) {
94 break;
95 }
Alec Mouric059dcf2022-05-05 23:40:07 +000096 // We may try to disable expensive rendering and allow
97 // for sending DISPLAY_UPDATE_IMMINENT hints too early if
98 // we idled very shortly after updating the screen, so
99 // make sure we wait enough time.
Alec Mouri29382ad2022-05-11 18:38:38 +0000100 std::this_thread::sleep_for(getUpdateTimeout() -
101 timeSinceLastUpdate);
Alec Mouric059dcf2022-05-05 23:40:07 +0000102 }
103 mSendUpdateImminent.store(true);
104 mFlinger.disableExpensiveRendering();
105 });
106 }
107}
Alec Mouridea1ac52021-06-23 18:12:18 -0700108
109void PowerAdvisor::init() {
110 // Defer starting the screen update timer until SurfaceFlinger finishes construction.
Alec Mouric059dcf2022-05-05 23:40:07 +0000111 if (mScreenUpdateTimer) {
112 mScreenUpdateTimer->start();
Dan Stoza030fbc12020-02-19 15:32:01 -0800113 }
114}
Michael Wright1509a232018-06-21 02:50:34 +0100115
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700116void PowerAdvisor::onBootFinished() {
117 mBootFinished.store(true);
118}
119
Peiyong Lin74ca2f42019-01-14 19:36:57 -0800120void PowerAdvisor::setExpensiveRenderingExpected(DisplayId displayId, bool expected) {
Michael Wright1509a232018-06-21 02:50:34 +0100121 if (expected) {
122 mExpensiveDisplays.insert(displayId);
123 } else {
124 mExpensiveDisplays.erase(displayId);
125 }
126
Michael Wright1509a232018-06-21 02:50:34 +0100127 const bool expectsExpensiveRendering = !mExpensiveDisplays.empty();
128 if (mNotifiedExpensiveRendering != expectsExpensiveRendering) {
Dan Stoza20950002020-06-18 14:56:58 -0700129 std::lock_guard lock(mPowerHalMutex);
Dan Stoza030fbc12020-02-19 15:32:01 -0800130 HalWrapper* const halWrapper = getPowerHal();
131 if (halWrapper == nullptr) {
Peiyong Lin81934972018-07-02 11:00:54 -0700132 return;
133 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800134
135 if (!halWrapper->setExpensiveRendering(expectsExpensiveRendering)) {
136 // The HAL has become unavailable; attempt to reconnect later
Michael Wright1509a232018-06-21 02:50:34 +0100137 mReconnectPowerHal = true;
138 return;
139 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800140
Michael Wright1509a232018-06-21 02:50:34 +0100141 mNotifiedExpensiveRendering = expectsExpensiveRendering;
142 }
143}
144
Dan Stoza030fbc12020-02-19 15:32:01 -0800145void PowerAdvisor::notifyDisplayUpdateImminent() {
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700146 // Only start sending this notification once the system has booted so we don't introduce an
147 // early-boot dependency on Power HAL
148 if (!mBootFinished.load()) {
149 return;
150 }
151
Alec Mouric059dcf2022-05-05 23:40:07 +0000152 if (mSendUpdateImminent.exchange(false)) {
Dan Stoza20950002020-06-18 14:56:58 -0700153 std::lock_guard lock(mPowerHalMutex);
Dan Stoza030fbc12020-02-19 15:32:01 -0800154 HalWrapper* const halWrapper = getPowerHal();
155 if (halWrapper == nullptr) {
156 return;
157 }
158
159 if (!halWrapper->notifyDisplayUpdateImminent()) {
160 // The HAL has become unavailable; attempt to reconnect later
161 mReconnectPowerHal = true;
162 return;
163 }
Alec Mouric059dcf2022-05-05 23:40:07 +0000164
165 if (mScreenUpdateTimer) {
166 mScreenUpdateTimer->reset();
167 } else {
168 // If we don't have a screen update timer, then we don't throttle power hal calls so
169 // flip this bit back to allow for calling into power hal again.
170 mSendUpdateImminent.store(true);
171 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800172 }
173
Alec Mouric059dcf2022-05-05 23:40:07 +0000174 if (mScreenUpdateTimer) {
175 mLastScreenUpdatedTime.store(systemTime());
Dan Stoza030fbc12020-02-19 15:32:01 -0800176 }
177}
178
Matt Buckley06f299a2021-09-24 19:43:51 +0000179// checks both if it supports and if it's enabled
180bool PowerAdvisor::usePowerHintSession() {
181 // uses cached value since the underlying support and flag are unlikely to change at runtime
Matt Buckley06f299a2021-09-24 19:43:51 +0000182 return mPowerHintEnabled.value_or(false) && supportsPowerHintSession();
183}
184
185bool PowerAdvisor::supportsPowerHintSession() {
186 // cache to avoid needing lock every time
187 if (!mSupportsPowerHint.has_value()) {
188 std::lock_guard lock(mPowerHalMutex);
189 HalWrapper* const halWrapper = getPowerHal();
190 mSupportsPowerHint = halWrapper->supportsPowerHintSession();
191 }
192 return *mSupportsPowerHint;
193}
194
195bool PowerAdvisor::isPowerHintSessionRunning() {
196 return mPowerHintSessionRunning;
197}
198
Matt Buckley50c44062022-01-17 20:48:10 +0000199void PowerAdvisor::setTargetWorkDuration(int64_t targetDuration) {
Matt Buckleyef51fba2021-10-12 19:30:12 +0000200 if (!usePowerHintSession()) {
Matt Buckley06f299a2021-09-24 19:43:51 +0000201 ALOGV("Power hint session target duration cannot be set, skipping");
202 return;
203 }
204 {
205 std::lock_guard lock(mPowerHalMutex);
206 HalWrapper* const halWrapper = getPowerHal();
207 if (halWrapper != nullptr) {
Matt Buckley50c44062022-01-17 20:48:10 +0000208 halWrapper->setTargetWorkDuration(targetDuration);
Matt Buckley06f299a2021-09-24 19:43:51 +0000209 }
210 }
211}
212
Matt Buckley50c44062022-01-17 20:48:10 +0000213void PowerAdvisor::sendActualWorkDuration() {
Matt Buckley06f299a2021-09-24 19:43:51 +0000214 if (!mBootFinished || !usePowerHintSession()) {
215 ALOGV("Actual work duration power hint cannot be sent, skipping");
216 return;
217 }
Matt Buckley50c44062022-01-17 20:48:10 +0000218 const std::optional<nsecs_t> actualDuration = estimateWorkDuration(false);
219 if (actualDuration.has_value()) {
Matt Buckley06f299a2021-09-24 19:43:51 +0000220 std::lock_guard lock(mPowerHalMutex);
221 HalWrapper* const halWrapper = getPowerHal();
222 if (halWrapper != nullptr) {
Matt Buckley50c44062022-01-17 20:48:10 +0000223 halWrapper->sendActualWorkDuration(*actualDuration + kTargetSafetyMargin.count(),
224 systemTime());
Matt Buckley06f299a2021-09-24 19:43:51 +0000225 }
226 }
227}
228
Matt Buckley50c44062022-01-17 20:48:10 +0000229void PowerAdvisor::sendPredictedWorkDuration() {
230 if (!mBootFinished || !usePowerHintSession()) {
231 ALOGV("Actual work duration power hint cannot be sent, skipping");
232 return;
233 }
234
235 const std::optional<nsecs_t> predictedDuration = estimateWorkDuration(true);
236
237 if (predictedDuration.has_value()) {
238 std::lock_guard lock(mPowerHalMutex);
239 HalWrapper* const halWrapper = getPowerHal();
240 if (halWrapper != nullptr) {
241 halWrapper->sendActualWorkDuration(*predictedDuration, systemTime());
242 }
243 }
244}
245
Matt Buckley06f299a2021-09-24 19:43:51 +0000246void PowerAdvisor::enablePowerHint(bool enabled) {
247 mPowerHintEnabled = enabled;
248}
249
Matt Buckleyef51fba2021-10-12 19:30:12 +0000250bool PowerAdvisor::startPowerHintSession(const std::vector<int32_t>& threadIds) {
251 if (!usePowerHintSession()) {
252 ALOGI("Power hint session cannot be started, skipping");
253 }
254 {
255 std::lock_guard lock(mPowerHalMutex);
256 HalWrapper* halWrapper = getPowerHal();
257 if (halWrapper != nullptr && usePowerHintSession()) {
258 halWrapper->setPowerHintSessionThreadIds(threadIds);
259 mPowerHintSessionRunning = halWrapper->startPowerHintSession();
260 }
261 }
262 return mPowerHintSessionRunning;
263}
264
Matt Buckley50c44062022-01-17 20:48:10 +0000265void PowerAdvisor::setGpuFenceTime(DisplayId displayId, std::unique_ptr<FenceTime>&& fenceTime) {
266 DisplayTimingData& displayData = mDisplayTimingData[displayId];
267 if (displayData.gpuEndFenceTime) {
268 nsecs_t signalTime = displayData.gpuEndFenceTime->getSignalTime();
269 if (signalTime != Fence::SIGNAL_TIME_INVALID && signalTime != Fence::SIGNAL_TIME_PENDING) {
270 for (auto&& [_, otherDisplayData] : mDisplayTimingData) {
271 // If the previous display started before us but ended after we should have
272 // started, then it likely delayed our start time and we must compensate for that.
273 // Displays finishing earlier should have already made their way through this call
274 // and swapped their timing into "lastValid" from "latest", so we check that here.
275 if (!otherDisplayData.lastValidGpuStartTime.has_value()) continue;
276 if ((*otherDisplayData.lastValidGpuStartTime < *displayData.gpuStartTime) &&
277 (*otherDisplayData.lastValidGpuEndTime > *displayData.gpuStartTime)) {
278 displayData.lastValidGpuStartTime = *otherDisplayData.lastValidGpuEndTime;
279 break;
280 }
281 }
282 displayData.lastValidGpuStartTime = displayData.gpuStartTime;
283 displayData.lastValidGpuEndTime = signalTime;
284 }
285 }
286 displayData.gpuEndFenceTime = std::move(fenceTime);
287 displayData.gpuStartTime = systemTime();
288}
289
290void PowerAdvisor::setValidateTiming(DisplayId displayId, nsecs_t validateStartTime,
291 nsecs_t validateEndTime) {
292 DisplayTimingData& displayData = mDisplayTimingData[displayId];
293 displayData.validateStartTime = validateStartTime;
294 displayData.validateEndTime = validateEndTime;
295}
296
297void PowerAdvisor::setPresentTiming(DisplayId displayId, nsecs_t presentStartTime,
298 nsecs_t presentEndTime) {
299 DisplayTimingData& displayData = mDisplayTimingData[displayId];
300 displayData.presentStartTime = presentStartTime;
301 displayData.presentEndTime = presentEndTime;
302}
303
304void PowerAdvisor::setSkippedValidate(DisplayId displayId, bool skipped) {
305 mDisplayTimingData[displayId].skippedValidate = skipped;
306}
307
308void PowerAdvisor::setRequiresClientComposition(DisplayId displayId,
309 bool requiresClientComposition) {
310 mDisplayTimingData[displayId].usedClientComposition = requiresClientComposition;
311}
312
313void PowerAdvisor::setExpectedPresentTime(nsecs_t expectedPresentTime) {
314 mExpectedPresentTimes.append(expectedPresentTime);
315}
316
317void PowerAdvisor::setFrameDelay(nsecs_t frameDelayDuration) {
318 mFrameDelayDuration = frameDelayDuration;
319}
320
321void PowerAdvisor::setPresentDelayedTime(
322 DisplayId displayId, std::chrono::steady_clock::time_point earliestFrameStartTime) {
323 mDisplayTimingData[displayId].presentDelayedTime =
324 (earliestFrameStartTime - std::chrono::steady_clock::now()).count() + systemTime();
325}
326
327void PowerAdvisor::setCommitStart(nsecs_t commitStartTime) {
328 mCommitStartTimes.append(commitStartTime);
329}
330
331void PowerAdvisor::setCompositeEnd(nsecs_t compositeEnd) {
332 mLastCompositeEndTime = compositeEnd;
333 // calculate the postcomp time here as well
334 std::vector<DisplayId>&& displays = getOrderedDisplayIds(&DisplayTimingData::presentEndTime);
335 DisplayTimingData& timingData = mDisplayTimingData[displays.back()];
336 mLastPostcompDuration = compositeEnd -
337 (timingData.skippedValidate ? *timingData.validateEndTime : *timingData.presentEndTime);
338}
339
340void PowerAdvisor::setDisplays(std::vector<DisplayId>& displayIds) {
341 mDisplayIds = displayIds;
342}
343
344void PowerAdvisor::setTotalFrameTargetWorkDuration(nsecs_t targetDuration) {
345 mTotalFrameTargetDuration = targetDuration;
346}
347
348std::vector<DisplayId> PowerAdvisor::getOrderedDisplayIds(
349 std::optional<nsecs_t> DisplayTimingData::*sortBy) {
350 std::vector<DisplayId> sortedDisplays;
351 std::copy_if(mDisplayIds.begin(), mDisplayIds.end(), std::back_inserter(sortedDisplays),
352 [&](DisplayId id) {
353 return mDisplayTimingData.count(id) &&
354 (mDisplayTimingData[id].*sortBy).has_value();
355 });
356 std::sort(sortedDisplays.begin(), sortedDisplays.end(), [&](DisplayId idA, DisplayId idB) {
357 return *(mDisplayTimingData[idA].*sortBy) < *(mDisplayTimingData[idB].*sortBy);
358 });
359 return sortedDisplays;
360}
361
362std::optional<nsecs_t> PowerAdvisor::estimateWorkDuration(bool earlyHint) {
363 if (earlyHint && (!mExpectedPresentTimes.isFull() || !mCommitStartTimes.isFull())) {
364 return std::nullopt;
365 }
366
367 // Tracks when we finish presenting to hwc
368 nsecs_t estimatedEndTime = mCommitStartTimes[0];
369
370 // How long we spent this frame not doing anything, waiting for fences or vsync
371 nsecs_t idleDuration = 0;
372
373 // Most recent previous gpu end time in the current frame, probably from a prior display, used
374 // as the start time for the next gpu operation if it ran over time since it probably blocked
375 std::optional<nsecs_t> previousValidGpuEndTime;
376
377 // The currently estimated gpu end time for the frame,
378 // used to accumulate gpu time as we iterate over the active displays
379 std::optional<nsecs_t> estimatedGpuEndTime;
380
381 // If we're predicting at the start of the frame, we use last frame as our reference point
382 // If we're predicting at the end of the frame, we use the current frame as a reference point
383 nsecs_t referenceFrameStartTime = (earlyHint ? mCommitStartTimes[-1] : mCommitStartTimes[0]);
384
385 // We need an idea of when the last present fence fired and how long it made us wait
386 // If we're predicting at the start of the frame, we want frame n-2's present fence time
387 // If we're predicting at the end of the frame we want frame n-1's present time
388 nsecs_t referenceFenceTime =
389 (earlyHint ? mExpectedPresentTimes[-2] : mExpectedPresentTimes[-1]);
390 // The timing info for the previously calculated display, if there was one
391 std::optional<DisplayTimeline> previousDisplayReferenceTiming;
392 std::vector<DisplayId>&& displayIds =
393 getOrderedDisplayIds(&DisplayTimingData::presentStartTime);
394 DisplayTimeline referenceTiming, estimatedTiming;
395
396 // Iterate over the displays in the same order they are presented
397 for (DisplayId displayId : displayIds) {
398 if (mDisplayTimingData.count(displayId) == 0) {
399 continue;
400 }
401
402 auto& displayData = mDisplayTimingData.at(displayId);
403 referenceTiming = displayData.calculateDisplayTimeline(referenceFenceTime);
404
405 // If this is the first display, add the pre-present time to the total
406 if (!previousDisplayReferenceTiming.has_value()) {
407 estimatedEndTime += referenceTiming.prePresentTime - referenceFrameStartTime;
408 } else { // Otherwise add last display's postprocessing time to the total
409 estimatedEndTime += referenceTiming.prePresentTime -
410 previousDisplayReferenceTiming->postPresentTime;
411 }
412
413 estimatedTiming = referenceTiming.estimateTimelineFromReference(mExpectedPresentTimes[-1],
414 estimatedEndTime);
415 // Update predicted present finish time with this display's present time
416 estimatedEndTime = estimatedTiming.postPresentTime;
417
418 // Track how long we spent waiting for the fence, can be excluded from the timing estimate
419 idleDuration += estimatedTiming.probablyWaitsForFence
420 ? mExpectedPresentTimes[-1] - estimatedTiming.preFenceWaitTime
421 : 0;
422
423 // Track how long we spent waiting to present, can be excluded from the timing estimate
424 idleDuration +=
425 !earlyHint ? referenceTiming.presentStartTime - referenceTiming.prePresentTime : 0;
426
427 // Estimate the reference frame's gpu timing
428 auto gpuTiming = displayData.estimateGpuTiming(previousValidGpuEndTime);
429 if (gpuTiming.has_value()) {
430 previousValidGpuEndTime = gpuTiming->startTime + gpuTiming->duration;
431
432 // Estimate the prediction frame's gpu end time from the reference frame
433 estimatedGpuEndTime =
434 std::max(estimatedTiming.prePresentTime, estimatedGpuEndTime.value_or(0)) +
435 gpuTiming->duration;
436 }
437 previousDisplayReferenceTiming = referenceTiming;
438 }
439 ATRACE_INT64("Idle duration", idleDuration);
440
441 // Don't count time spent idly waiting in the estimate as we could do more work in that time
442 estimatedEndTime -= idleDuration;
443
444 // We finish the frame when both present and the gpu are done, so wait for the later of the two
445 // Also add the frame delay duration since the target did not move while we were delayed
446 nsecs_t totalDuration = mFrameDelayDuration +
447 std::max(estimatedEndTime, estimatedGpuEndTime.value_or(0)) - mCommitStartTimes[0];
448
449 // We finish SurfaceFlinger when post-composition finishes, so add that in here
450 nsecs_t flingerDuration = estimatedEndTime + mLastPostcompDuration - mCommitStartTimes[0];
451 nsecs_t combinedDuration = combineTimingEstimates(totalDuration, flingerDuration);
452
453 return std::make_optional(combinedDuration);
454}
455
456nsecs_t PowerAdvisor::combineTimingEstimates(nsecs_t totalDuration, nsecs_t flingerDuration) {
457 nsecs_t targetDuration;
458 {
459 std::lock_guard lock(mPowerHalMutex);
460 targetDuration = *getPowerHal()->getTargetWorkDuration();
461 }
462 if (!mTotalFrameTargetDuration.has_value()) return flingerDuration;
463
464 // Normalize total to the flinger target (vsync period) since that's how often we actually send
465 // hints
466 nsecs_t normalizedTotalDuration = (targetDuration * totalDuration) / *mTotalFrameTargetDuration;
467 return std::max(flingerDuration, normalizedTotalDuration);
468}
469
470PowerAdvisor::DisplayTimeline PowerAdvisor::DisplayTimeline::estimateTimelineFromReference(
471 nsecs_t fenceTime, nsecs_t displayStartTime) {
472 DisplayTimeline estimated;
473 estimated.prePresentTime = displayStartTime;
474
475 // We don't predict waiting for vsync alignment yet
476 estimated.presentStartTime = estimated.prePresentTime;
477
478 // For now just re-use last frame's post-present duration and assume it will not change much
479 // How long we expect to run before we start waiting for the fence
480 estimated.preFenceWaitTime = estimated.presentStartTime + (preFenceWaitTime - presentStartTime);
481 estimated.probablyWaitsForFence = fenceTime > estimated.preFenceWaitTime;
482 estimated.postPresentTime = postFenceDuration +
483 (estimated.probablyWaitsForFence ? fenceTime : estimated.preFenceWaitTime);
484 return estimated;
485}
486
487PowerAdvisor::DisplayTimeline PowerAdvisor::DisplayTimingData::calculateDisplayTimeline(
488 nsecs_t fenceTime) {
489 DisplayTimeline timeline;
490 // How long between calling present from flinger and trying to wait on the fence in HWC
491 const nsecs_t preFenceWaitDelay =
492 (skippedValidate ? kPrefenceDelaySkippedValidate : kPrefenceDelayValidated).count();
493
494 // Did our reference frame wait for an earliest present time before calling the HWC
495 const bool waitedOnPresentTime = presentDelayedTime.has_value() &&
496 *presentDelayedTime > *presentStartTime && *presentDelayedTime < *presentEndTime;
497
498 // Use validate start here if we skipped it because we did validate + present together
499 timeline.prePresentTime = skippedValidate ? *validateStartTime : *presentStartTime;
500
501 // Use validate end here if we skipped it because we did validate + present together
502 timeline.postPresentTime = skippedValidate ? *validateEndTime : *presentEndTime;
503
504 // When we think we started waiting for the fence after calling into present
505 // This is after any time spent waiting for the earliest present time
506 timeline.presentStartTime =
507 (waitedOnPresentTime ? *presentDelayedTime : timeline.prePresentTime);
508 timeline.preFenceWaitTime = timeline.presentStartTime + preFenceWaitDelay;
509 timeline.probablyWaitsForFence =
510 fenceTime > timeline.preFenceWaitTime && fenceTime < timeline.postPresentTime;
511
512 // How long we ran after we finished waiting for the fence but before present happened
513 timeline.postFenceDuration = timeline.postPresentTime -
514 (timeline.probablyWaitsForFence ? fenceTime : timeline.preFenceWaitTime);
515 return timeline;
516}
517
518std::optional<PowerAdvisor::GpuTimeline> PowerAdvisor::DisplayTimingData::estimateGpuTiming(
519 std::optional<nsecs_t> previousEnd) {
520 if (!(usedClientComposition && lastValidGpuStartTime.has_value() && gpuEndFenceTime)) {
521 return std::nullopt;
522 }
523 const nsecs_t latestGpuStartTime = std::max(previousEnd.value_or(0), *gpuStartTime);
524 const nsecs_t latestGpuEndTime = gpuEndFenceTime->getSignalTime();
525 nsecs_t gpuDuration = 0;
526 if (latestGpuEndTime != Fence::SIGNAL_TIME_INVALID &&
527 latestGpuEndTime != Fence::SIGNAL_TIME_PENDING) {
528 // If we know how long the most recent gpu duration was, use that
529 gpuDuration = latestGpuEndTime - latestGpuStartTime;
530 } else if (lastValidGpuEndTime.has_value()) {
531 // If we don't have the fence data, use the most recent information we do have
532 gpuDuration = *lastValidGpuEndTime - *lastValidGpuStartTime;
533 if (latestGpuEndTime == Fence::SIGNAL_TIME_PENDING) {
534 // If pending but went over the previous duration, use current time as the end
535 gpuDuration = std::max(gpuDuration, systemTime() - latestGpuStartTime);
536 }
537 }
538 return GpuTimeline{.duration = gpuDuration, .startTime = latestGpuStartTime};
539}
540
Dan Stoza030fbc12020-02-19 15:32:01 -0800541class HidlPowerHalWrapper : public PowerAdvisor::HalWrapper {
542public:
543 HidlPowerHalWrapper(sp<V1_3::IPower> powerHal) : mPowerHal(std::move(powerHal)) {}
544
545 ~HidlPowerHalWrapper() override = default;
546
547 static std::unique_ptr<HalWrapper> connect() {
548 // Power HAL 1.3 is not guaranteed to be available, thus we need to query
549 // Power HAL 1.0 first and try to cast it to Power HAL 1.3.
Dan Stoza030fbc12020-02-19 15:32:01 -0800550 sp<V1_3::IPower> powerHal = nullptr;
Dan Stoza9c051c02020-02-28 10:19:07 -0800551 sp<V1_0::IPower> powerHal_1_0 = V1_0::IPower::getService();
552 if (powerHal_1_0 != nullptr) {
553 // Try to cast to Power HAL 1.3
554 powerHal = V1_3::IPower::castFrom(powerHal_1_0);
555 if (powerHal == nullptr) {
556 ALOGW("No Power HAL 1.3 service in system, disabling PowerAdvisor");
557 } else {
558 ALOGI("Loaded Power HAL 1.3 service");
Dan Stoza030fbc12020-02-19 15:32:01 -0800559 }
Dan Stoza9c051c02020-02-28 10:19:07 -0800560 } else {
561 ALOGW("No Power HAL found, disabling PowerAdvisor");
Dan Stoza030fbc12020-02-19 15:32:01 -0800562 }
Dan Stoza9c051c02020-02-28 10:19:07 -0800563
Dan Stoza030fbc12020-02-19 15:32:01 -0800564 if (powerHal == nullptr) {
565 return nullptr;
566 }
567
568 return std::make_unique<HidlPowerHalWrapper>(std::move(powerHal));
569 }
570
571 bool setExpensiveRendering(bool enabled) override {
572 ALOGV("HIDL setExpensiveRendering %s", enabled ? "T" : "F");
573 auto ret = mPowerHal->powerHintAsync_1_3(PowerHint::EXPENSIVE_RENDERING, enabled);
Ady Abrahamabce1652022-02-24 10:51:19 -0800574 if (ret.isOk()) {
575 traceExpensiveRendering(enabled);
576 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800577 return ret.isOk();
578 }
579
580 bool notifyDisplayUpdateImminent() override {
581 // Power HAL 1.x doesn't have a notification for this
582 ALOGV("HIDL notifyUpdateImminent received but can't send");
583 return true;
584 }
585
Matt Buckley06f299a2021-09-24 19:43:51 +0000586 bool supportsPowerHintSession() override { return false; }
587
588 bool isPowerHintSessionRunning() override { return false; }
589
590 void restartPowerHintSession() override {}
591
592 void setPowerHintSessionThreadIds(const std::vector<int32_t>&) override {}
593
594 bool startPowerHintSession() override { return false; }
595
596 void setTargetWorkDuration(int64_t) override {}
597
598 void sendActualWorkDuration(int64_t, nsecs_t) override {}
599
600 bool shouldReconnectHAL() override { return false; }
601
602 std::vector<int32_t> getPowerHintSessionThreadIds() override { return std::vector<int32_t>{}; }
603
604 std::optional<int64_t> getTargetWorkDuration() override { return std::nullopt; }
605
Dan Stoza030fbc12020-02-19 15:32:01 -0800606private:
Dan Stoza030fbc12020-02-19 15:32:01 -0800607 const sp<V1_3::IPower> mPowerHal = nullptr;
608};
609
Xiang Wange12b4fa2022-03-25 23:48:40 +0000610AidlPowerHalWrapper::AidlPowerHalWrapper(sp<IPower> powerHal) : mPowerHal(std::move(powerHal)) {
611 auto ret = mPowerHal->isModeSupported(Mode::EXPENSIVE_RENDERING, &mHasExpensiveRendering);
612 if (!ret.isOk()) {
613 mHasExpensiveRendering = false;
Dan Stoza030fbc12020-02-19 15:32:01 -0800614 }
615
Xiang Wange12b4fa2022-03-25 23:48:40 +0000616 ret = mPowerHal->isBoostSupported(Boost::DISPLAY_UPDATE_IMMINENT, &mHasDisplayUpdateImminent);
617 if (!ret.isOk()) {
618 mHasDisplayUpdateImminent = false;
Dan Stoza030fbc12020-02-19 15:32:01 -0800619 }
620
Xiang Wange12b4fa2022-03-25 23:48:40 +0000621 mSupportsPowerHint = checkPowerHintSessionSupported();
Matt Buckley50c44062022-01-17 20:48:10 +0000622
623 mAllowedActualDeviation =
624 base::GetIntProperty<nsecs_t>("debug.sf.allowed_actual_deviation",
625 std::chrono::nanoseconds(250us).count());
Xiang Wange12b4fa2022-03-25 23:48:40 +0000626}
Dan Stoza030fbc12020-02-19 15:32:01 -0800627
Xiang Wange12b4fa2022-03-25 23:48:40 +0000628AidlPowerHalWrapper::~AidlPowerHalWrapper() {
629 if (mPowerHintSession != nullptr) {
630 mPowerHintSession->close();
631 mPowerHintSession = nullptr;
Dan Stoza030fbc12020-02-19 15:32:01 -0800632 }
Matt Buckley50c44062022-01-17 20:48:10 +0000633}
Dan Stoza030fbc12020-02-19 15:32:01 -0800634
Xiang Wange12b4fa2022-03-25 23:48:40 +0000635std::unique_ptr<PowerAdvisor::HalWrapper> AidlPowerHalWrapper::connect() {
636 // This only waits if the service is actually declared
637 sp<IPower> powerHal = waitForVintfService<IPower>();
638 if (powerHal == nullptr) {
639 return nullptr;
640 }
641 ALOGI("Loaded AIDL Power HAL service");
642
643 return std::make_unique<AidlPowerHalWrapper>(std::move(powerHal));
644}
645
646bool AidlPowerHalWrapper::setExpensiveRendering(bool enabled) {
647 ALOGV("AIDL setExpensiveRendering %s", enabled ? "T" : "F");
648 if (!mHasExpensiveRendering) {
649 ALOGV("Skipped sending EXPENSIVE_RENDERING because HAL doesn't support it");
650 return true;
651 }
652
653 auto ret = mPowerHal->setMode(Mode::EXPENSIVE_RENDERING, enabled);
654 if (ret.isOk()) {
655 traceExpensiveRendering(enabled);
656 }
657 return ret.isOk();
658}
659
660bool AidlPowerHalWrapper::notifyDisplayUpdateImminent() {
661 ALOGV("AIDL notifyDisplayUpdateImminent");
662 if (!mHasDisplayUpdateImminent) {
663 ALOGV("Skipped sending DISPLAY_UPDATE_IMMINENT because HAL doesn't support it");
664 return true;
665 }
666
667 auto ret = mPowerHal->setBoost(Boost::DISPLAY_UPDATE_IMMINENT, 0);
668 return ret.isOk();
669}
670
Matt Buckley50c44062022-01-17 20:48:10 +0000671// Only version 2+ of the aidl supports power hint sessions, hidl has no support
Xiang Wange12b4fa2022-03-25 23:48:40 +0000672bool AidlPowerHalWrapper::supportsPowerHintSession() {
673 return mSupportsPowerHint;
674}
675
676bool AidlPowerHalWrapper::checkPowerHintSessionSupported() {
677 int64_t unused;
678 // Try to get preferred rate to determine if hint sessions are supported
679 // We check for isOk not EX_UNSUPPORTED_OPERATION to lump together errors
680 return mPowerHal->getHintSessionPreferredRate(&unused).isOk();
681}
682
683bool AidlPowerHalWrapper::isPowerHintSessionRunning() {
684 return mPowerHintSession != nullptr;
685}
686
687void AidlPowerHalWrapper::closePowerHintSession() {
688 if (mPowerHintSession != nullptr) {
689 mPowerHintSession->close();
690 mPowerHintSession = nullptr;
691 }
692}
693
694void AidlPowerHalWrapper::restartPowerHintSession() {
695 closePowerHintSession();
696 startPowerHintSession();
697}
698
699void AidlPowerHalWrapper::setPowerHintSessionThreadIds(const std::vector<int32_t>& threadIds) {
700 if (threadIds != mPowerHintThreadIds) {
701 mPowerHintThreadIds = threadIds;
702 if (isPowerHintSessionRunning()) {
703 restartPowerHintSession();
704 }
705 }
706}
707
708bool AidlPowerHalWrapper::startPowerHintSession() {
709 if (mPowerHintSession != nullptr || mPowerHintThreadIds.empty()) {
710 ALOGV("Cannot start power hint session, skipping");
711 return false;
712 }
713 auto ret =
714 mPowerHal->createHintSession(getpid(), static_cast<int32_t>(getuid()),
715 mPowerHintThreadIds, mTargetDuration, &mPowerHintSession);
716 if (!ret.isOk()) {
717 ALOGW("Failed to start power hint session with error: %s",
718 ret.exceptionToString(ret.exceptionCode()).c_str());
719 } else {
720 mLastTargetDurationSent = mTargetDuration;
721 }
722 return isPowerHintSessionRunning();
723}
724
Matt Buckley50c44062022-01-17 20:48:10 +0000725void AidlPowerHalWrapper::setTargetWorkDuration(int64_t targetDuration) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000726 ATRACE_CALL();
Matt Buckley50c44062022-01-17 20:48:10 +0000727 mTargetDuration = targetDuration;
728 if (sTraceHintSessionData) ATRACE_INT64("Time target", targetDuration);
729 if (isPowerHintSessionRunning() && (targetDuration != mLastTargetDurationSent)) {
730 ALOGV("Sending target time: %" PRId64 "ns", targetDuration);
731 mLastTargetDurationSent = targetDuration;
732 auto ret = mPowerHintSession->updateTargetWorkDuration(targetDuration);
Xiang Wange12b4fa2022-03-25 23:48:40 +0000733 if (!ret.isOk()) {
734 ALOGW("Failed to set power hint target work duration with error: %s",
735 ret.exceptionMessage().c_str());
736 mShouldReconnectHal = true;
737 }
738 }
739}
740
Matt Buckley50c44062022-01-17 20:48:10 +0000741bool AidlPowerHalWrapper::shouldReportActualDurations() {
742 // Report if we have never reported before or are approaching a stale session
Xiang Wange12b4fa2022-03-25 23:48:40 +0000743 if (!mLastActualDurationSent.has_value() ||
744 (systemTime() - mLastActualReportTimestamp) > kStaleTimeout.count()) {
745 return true;
746 }
747
748 if (!mActualDuration.has_value()) {
749 return false;
750 }
Matt Buckley50c44062022-01-17 20:48:10 +0000751 // Report if the change in actual duration exceeds the threshold
752 return abs(*mActualDuration - *mLastActualDurationSent) > mAllowedActualDeviation;
Xiang Wange12b4fa2022-03-25 23:48:40 +0000753}
754
Matt Buckley50c44062022-01-17 20:48:10 +0000755void AidlPowerHalWrapper::sendActualWorkDuration(int64_t actualDuration, nsecs_t timestamp) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000756 ATRACE_CALL();
757
Matt Buckley50c44062022-01-17 20:48:10 +0000758 if (actualDuration < 0 || !isPowerHintSessionRunning()) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000759 ALOGV("Failed to send actual work duration, skipping");
760 return;
761 }
Matt Buckley50c44062022-01-17 20:48:10 +0000762 const nsecs_t reportedDuration = actualDuration;
Xiang Wange12b4fa2022-03-25 23:48:40 +0000763
Xiang Wang0aba49e2022-04-06 16:13:59 +0000764 mActualDuration = reportedDuration;
765 WorkDuration duration;
766 duration.durationNanos = reportedDuration;
Matt Buckley50c44062022-01-17 20:48:10 +0000767 duration.timeStampNanos = timestamp;
Xiang Wange12b4fa2022-03-25 23:48:40 +0000768 mPowerHintQueue.push_back(duration);
769
Xiang Wange12b4fa2022-03-25 23:48:40 +0000770 if (sTraceHintSessionData) {
Matt Buckley50c44062022-01-17 20:48:10 +0000771 ATRACE_INT64("Measured duration", actualDuration);
772 ATRACE_INT64("Target error term", actualDuration - mTargetDuration);
Xiang Wang0aba49e2022-04-06 16:13:59 +0000773
774 ATRACE_INT64("Reported duration", reportedDuration);
775 ATRACE_INT64("Reported target", mLastTargetDurationSent);
Matt Buckley50c44062022-01-17 20:48:10 +0000776 ATRACE_INT64("Reported target error term", reportedDuration - mLastTargetDurationSent);
Xiang Wange12b4fa2022-03-25 23:48:40 +0000777 }
778
Xiang Wang0aba49e2022-04-06 16:13:59 +0000779 ALOGV("Sending actual work duration of: %" PRId64 " on reported target: %" PRId64
Xiang Wange12b4fa2022-03-25 23:48:40 +0000780 " with error: %" PRId64,
Matt Buckley50c44062022-01-17 20:48:10 +0000781 reportedDuration, mLastTargetDurationSent, reportedDuration - mLastTargetDurationSent);
Xiang Wange12b4fa2022-03-25 23:48:40 +0000782
783 // This rate limiter queues similar duration reports to the powerhal into
784 // batches to avoid excessive binder calls. The criteria to send a given batch
785 // are outlined in shouldReportActualDurationsNow()
Matt Buckley50c44062022-01-17 20:48:10 +0000786 if (shouldReportActualDurations()) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000787 ALOGV("Sending hint update batch");
788 mLastActualReportTimestamp = systemTime();
789 auto ret = mPowerHintSession->reportActualWorkDuration(mPowerHintQueue);
790 if (!ret.isOk()) {
791 ALOGW("Failed to report actual work durations with error: %s",
792 ret.exceptionMessage().c_str());
793 mShouldReconnectHal = true;
794 }
795 mPowerHintQueue.clear();
Matt Buckley50c44062022-01-17 20:48:10 +0000796 // We save the actual duration here for rate limiting
797 mLastActualDurationSent = actualDuration;
Xiang Wange12b4fa2022-03-25 23:48:40 +0000798 }
799}
800
801bool AidlPowerHalWrapper::shouldReconnectHAL() {
802 return mShouldReconnectHal;
803}
804
805std::vector<int32_t> AidlPowerHalWrapper::getPowerHintSessionThreadIds() {
806 return mPowerHintThreadIds;
807}
808
809std::optional<int64_t> AidlPowerHalWrapper::getTargetWorkDuration() {
810 return mTargetDuration;
811}
812
Matt Buckley50c44062022-01-17 20:48:10 +0000813void AidlPowerHalWrapper::setAllowedActualDeviation(nsecs_t allowedDeviation) {
814 mAllowedActualDeviation = allowedDeviation;
815}
816
Matt Buckleyef51fba2021-10-12 19:30:12 +0000817const bool AidlPowerHalWrapper::sTraceHintSessionData =
818 base::GetBoolProperty(std::string("debug.sf.trace_hint_sessions"), false);
819
Dan Stoza030fbc12020-02-19 15:32:01 -0800820PowerAdvisor::HalWrapper* PowerAdvisor::getPowerHal() {
821 static std::unique_ptr<HalWrapper> sHalWrapper = nullptr;
Dan Stoza9c051c02020-02-28 10:19:07 -0800822 static bool sHasHal = true;
Michael Wright1509a232018-06-21 02:50:34 +0100823
Dan Stoza9c051c02020-02-28 10:19:07 -0800824 if (!sHasHal) {
825 return nullptr;
826 }
827
Matt Buckley50c44062022-01-17 20:48:10 +0000828 // Grab old hint session values before we destroy any existing wrapper
Matt Buckley06f299a2021-09-24 19:43:51 +0000829 std::vector<int32_t> oldPowerHintSessionThreadIds;
830 std::optional<int64_t> oldTargetWorkDuration;
831
832 if (sHalWrapper != nullptr) {
833 oldPowerHintSessionThreadIds = sHalWrapper->getPowerHintSessionThreadIds();
834 oldTargetWorkDuration = sHalWrapper->getTargetWorkDuration();
835 }
836
Dan Stoza9c051c02020-02-28 10:19:07 -0800837 // If we used to have a HAL, but it stopped responding, attempt to reconnect
Michael Wright1509a232018-06-21 02:50:34 +0100838 if (mReconnectPowerHal) {
Dan Stoza030fbc12020-02-19 15:32:01 -0800839 sHalWrapper = nullptr;
Michael Wright1509a232018-06-21 02:50:34 +0100840 mReconnectPowerHal = false;
841 }
842
Dan Stoza030fbc12020-02-19 15:32:01 -0800843 if (sHalWrapper != nullptr) {
Matt Buckley06f299a2021-09-24 19:43:51 +0000844 auto wrapper = sHalWrapper.get();
Matt Buckley50c44062022-01-17 20:48:10 +0000845 // If the wrapper is fine, return it, but if it indicates a reconnect, remake it
Matt Buckley06f299a2021-09-24 19:43:51 +0000846 if (!wrapper->shouldReconnectHAL()) {
847 return wrapper;
848 }
Xiang Wang65a2e6f2022-04-18 21:19:17 +0000849 ALOGD("Reconnecting Power HAL");
Matt Buckley06f299a2021-09-24 19:43:51 +0000850 sHalWrapper = nullptr;
Michael Wright1509a232018-06-21 02:50:34 +0100851 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800852
Matt Buckley50c44062022-01-17 20:48:10 +0000853 // At this point, we know for sure there is no running session
Matt Buckley06f299a2021-09-24 19:43:51 +0000854 mPowerHintSessionRunning = false;
855
Dan Stoza030fbc12020-02-19 15:32:01 -0800856 // First attempt to connect to the AIDL Power HAL
857 sHalWrapper = AidlPowerHalWrapper::connect();
858
859 // If that didn't succeed, attempt to connect to the HIDL Power HAL
860 if (sHalWrapper == nullptr) {
861 sHalWrapper = HidlPowerHalWrapper::connect();
Xiang Wang65a2e6f2022-04-18 21:19:17 +0000862 } else {
863 ALOGD("Successfully connecting AIDL Power HAL");
Matt Buckley50c44062022-01-17 20:48:10 +0000864 // If AIDL, pass on any existing hint session values
Matt Buckley06f299a2021-09-24 19:43:51 +0000865 sHalWrapper->setPowerHintSessionThreadIds(oldPowerHintSessionThreadIds);
Matt Buckley50c44062022-01-17 20:48:10 +0000866 // Only set duration and start if duration is defined
Matt Buckley06f299a2021-09-24 19:43:51 +0000867 if (oldTargetWorkDuration.has_value()) {
868 sHalWrapper->setTargetWorkDuration(*oldTargetWorkDuration);
Matt Buckley50c44062022-01-17 20:48:10 +0000869 // Only start if possible to run and both threadids and duration are defined
Matt Buckley06f299a2021-09-24 19:43:51 +0000870 if (usePowerHintSession() && !oldPowerHintSessionThreadIds.empty()) {
871 mPowerHintSessionRunning = sHalWrapper->startPowerHintSession();
872 }
873 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800874 }
875
Dan Stoza9c051c02020-02-28 10:19:07 -0800876 // If we make it to this point and still don't have a HAL, it's unlikely we
877 // will, so stop trying
878 if (sHalWrapper == nullptr) {
879 sHasHal = false;
880 }
881
Dan Stoza030fbc12020-02-19 15:32:01 -0800882 return sHalWrapper.get();
Michael Wright1509a232018-06-21 02:50:34 +0100883}
884
885} // namespace impl
886} // namespace Hwc2
887} // namespace android