blob: f844845c82ef1be207ef4ba007d3f8a65d4a8fba [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
Matt Buckley16dec1f2022-06-07 21:46:20 +0000290void PowerAdvisor::setHwcValidateTiming(DisplayId displayId, nsecs_t validateStartTime,
291 nsecs_t validateEndTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000292 DisplayTimingData& displayData = mDisplayTimingData[displayId];
Matt Buckley16dec1f2022-06-07 21:46:20 +0000293 displayData.hwcValidateStartTime = validateStartTime;
294 displayData.hwcValidateEndTime = validateEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000295}
296
Matt Buckley16dec1f2022-06-07 21:46:20 +0000297void PowerAdvisor::setHwcPresentTiming(DisplayId displayId, nsecs_t presentStartTime,
298 nsecs_t presentEndTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000299 DisplayTimingData& displayData = mDisplayTimingData[displayId];
Matt Buckley16dec1f2022-06-07 21:46:20 +0000300 displayData.hwcPresentStartTime = presentStartTime;
301 displayData.hwcPresentEndTime = presentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000302}
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
Matt Buckley16dec1f2022-06-07 21:46:20 +0000321void PowerAdvisor::setHwcPresentDelayedTime(
Matt Buckley50c44062022-01-17 20:48:10 +0000322 DisplayId displayId, std::chrono::steady_clock::time_point earliestFrameStartTime) {
Matt Buckley16dec1f2022-06-07 21:46:20 +0000323 mDisplayTimingData[displayId].hwcPresentDelayedTime =
Matt Buckley50c44062022-01-17 20:48:10 +0000324 (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
Matt Buckley16dec1f2022-06-07 21:46:20 +0000334 std::vector<DisplayId>&& displays = getOrderedDisplayIds(&DisplayTimingData::hwcPresentEndTime);
Matt Buckley50c44062022-01-17 20:48:10 +0000335 DisplayTimingData& timingData = mDisplayTimingData[displays.back()];
336 mLastPostcompDuration = compositeEnd -
Matt Buckley16dec1f2022-06-07 21:46:20 +0000337 (timingData.skippedValidate ? *timingData.hwcValidateEndTime
338 : *timingData.hwcPresentEndTime);
Matt Buckley50c44062022-01-17 20:48:10 +0000339}
340
341void PowerAdvisor::setDisplays(std::vector<DisplayId>& displayIds) {
342 mDisplayIds = displayIds;
343}
344
345void PowerAdvisor::setTotalFrameTargetWorkDuration(nsecs_t targetDuration) {
346 mTotalFrameTargetDuration = targetDuration;
347}
348
349std::vector<DisplayId> PowerAdvisor::getOrderedDisplayIds(
350 std::optional<nsecs_t> DisplayTimingData::*sortBy) {
351 std::vector<DisplayId> sortedDisplays;
352 std::copy_if(mDisplayIds.begin(), mDisplayIds.end(), std::back_inserter(sortedDisplays),
353 [&](DisplayId id) {
354 return mDisplayTimingData.count(id) &&
355 (mDisplayTimingData[id].*sortBy).has_value();
356 });
357 std::sort(sortedDisplays.begin(), sortedDisplays.end(), [&](DisplayId idA, DisplayId idB) {
358 return *(mDisplayTimingData[idA].*sortBy) < *(mDisplayTimingData[idB].*sortBy);
359 });
360 return sortedDisplays;
361}
362
363std::optional<nsecs_t> PowerAdvisor::estimateWorkDuration(bool earlyHint) {
364 if (earlyHint && (!mExpectedPresentTimes.isFull() || !mCommitStartTimes.isFull())) {
365 return std::nullopt;
366 }
367
368 // Tracks when we finish presenting to hwc
369 nsecs_t estimatedEndTime = mCommitStartTimes[0];
370
371 // How long we spent this frame not doing anything, waiting for fences or vsync
372 nsecs_t idleDuration = 0;
373
374 // Most recent previous gpu end time in the current frame, probably from a prior display, used
375 // as the start time for the next gpu operation if it ran over time since it probably blocked
376 std::optional<nsecs_t> previousValidGpuEndTime;
377
378 // The currently estimated gpu end time for the frame,
379 // used to accumulate gpu time as we iterate over the active displays
380 std::optional<nsecs_t> estimatedGpuEndTime;
381
382 // If we're predicting at the start of the frame, we use last frame as our reference point
383 // If we're predicting at the end of the frame, we use the current frame as a reference point
384 nsecs_t referenceFrameStartTime = (earlyHint ? mCommitStartTimes[-1] : mCommitStartTimes[0]);
385
386 // We need an idea of when the last present fence fired and how long it made us wait
387 // If we're predicting at the start of the frame, we want frame n-2's present fence time
388 // If we're predicting at the end of the frame we want frame n-1's present time
389 nsecs_t referenceFenceTime =
390 (earlyHint ? mExpectedPresentTimes[-2] : mExpectedPresentTimes[-1]);
391 // The timing info for the previously calculated display, if there was one
392 std::optional<DisplayTimeline> previousDisplayReferenceTiming;
393 std::vector<DisplayId>&& displayIds =
Matt Buckley16dec1f2022-06-07 21:46:20 +0000394 getOrderedDisplayIds(&DisplayTimingData::hwcPresentStartTime);
Matt Buckley50c44062022-01-17 20:48:10 +0000395 DisplayTimeline referenceTiming, estimatedTiming;
396
397 // Iterate over the displays in the same order they are presented
398 for (DisplayId displayId : displayIds) {
399 if (mDisplayTimingData.count(displayId) == 0) {
400 continue;
401 }
402
403 auto& displayData = mDisplayTimingData.at(displayId);
404 referenceTiming = displayData.calculateDisplayTimeline(referenceFenceTime);
405
Matt Buckley16dec1f2022-06-07 21:46:20 +0000406 // If this is the first display, include the duration before hwc present starts
Matt Buckley50c44062022-01-17 20:48:10 +0000407 if (!previousDisplayReferenceTiming.has_value()) {
Matt Buckley16dec1f2022-06-07 21:46:20 +0000408 estimatedEndTime += referenceTiming.hwcPresentStartTime - referenceFrameStartTime;
409 } else { // Otherwise add the time since last display's hwc present finished
410 estimatedEndTime += referenceTiming.hwcPresentStartTime -
411 previousDisplayReferenceTiming->hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000412 }
413
414 estimatedTiming = referenceTiming.estimateTimelineFromReference(mExpectedPresentTimes[-1],
415 estimatedEndTime);
416 // Update predicted present finish time with this display's present time
Matt Buckley16dec1f2022-06-07 21:46:20 +0000417 estimatedEndTime = estimatedTiming.hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000418
419 // Track how long we spent waiting for the fence, can be excluded from the timing estimate
Matt Buckley16dec1f2022-06-07 21:46:20 +0000420 idleDuration += estimatedTiming.probablyWaitsForReleaseFence
421 ? mExpectedPresentTimes[-1] - estimatedTiming.releaseFenceWaitStartTime
Matt Buckley50c44062022-01-17 20:48:10 +0000422 : 0;
423
424 // Track how long we spent waiting to present, can be excluded from the timing estimate
Matt Buckley16dec1f2022-06-07 21:46:20 +0000425 idleDuration += earlyHint ? 0 : referenceTiming.hwcPresentDelayDuration;
Matt Buckley50c44062022-01-17 20:48:10 +0000426
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 =
Matt Buckley16dec1f2022-06-07 21:46:20 +0000434 std::max(estimatedTiming.hwcPresentStartTime, estimatedGpuEndTime.value_or(0)) +
Matt Buckley50c44062022-01-17 20:48:10 +0000435 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;
Matt Buckley16dec1f2022-06-07 21:46:20 +0000473 estimated.hwcPresentStartTime = displayStartTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000474
475 // We don't predict waiting for vsync alignment yet
Matt Buckley16dec1f2022-06-07 21:46:20 +0000476 estimated.hwcPresentDelayDuration = 0;
Matt Buckley50c44062022-01-17 20:48:10 +0000477
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
Matt Buckley16dec1f2022-06-07 21:46:20 +0000480 // If it's the early hint we exclude time we spent waiting for a vsync, otherwise don't
481 estimated.releaseFenceWaitStartTime = estimated.hwcPresentStartTime +
482 (releaseFenceWaitStartTime - (hwcPresentStartTime + hwcPresentDelayDuration));
483 estimated.probablyWaitsForReleaseFence = fenceTime > estimated.releaseFenceWaitStartTime;
484 estimated.hwcPresentEndTime = postReleaseFenceHwcPresentDuration +
485 (estimated.probablyWaitsForReleaseFence ? fenceTime
486 : estimated.releaseFenceWaitStartTime);
Matt Buckley50c44062022-01-17 20:48:10 +0000487 return estimated;
488}
489
490PowerAdvisor::DisplayTimeline PowerAdvisor::DisplayTimingData::calculateDisplayTimeline(
491 nsecs_t fenceTime) {
492 DisplayTimeline timeline;
Matt Buckley16dec1f2022-06-07 21:46:20 +0000493 // How long between calling hwc present and trying to wait on the fence
494 const nsecs_t fenceWaitStartDelay =
495 (skippedValidate ? kFenceWaitStartDelaySkippedValidate : kFenceWaitStartDelayValidated)
496 .count();
Matt Buckley50c44062022-01-17 20:48:10 +0000497
Matt Buckley16dec1f2022-06-07 21:46:20 +0000498 // Did our reference frame wait for an appropriate vsync before calling into hwc
499 const bool waitedOnHwcPresentTime = hwcPresentDelayedTime.has_value() &&
500 *hwcPresentDelayedTime > *hwcPresentStartTime &&
501 *hwcPresentDelayedTime < *hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000502
503 // Use validate start here if we skipped it because we did validate + present together
Matt Buckley16dec1f2022-06-07 21:46:20 +0000504 timeline.hwcPresentStartTime = skippedValidate ? *hwcValidateStartTime : *hwcPresentStartTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000505
506 // Use validate end here if we skipped it because we did validate + present together
Matt Buckley16dec1f2022-06-07 21:46:20 +0000507 timeline.hwcPresentEndTime = skippedValidate ? *hwcValidateEndTime : *hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000508
Matt Buckley16dec1f2022-06-07 21:46:20 +0000509 // How long hwc present was delayed waiting for the next appropriate vsync
510 timeline.hwcPresentDelayDuration =
511 (waitedOnHwcPresentTime ? *hwcPresentDelayedTime - *hwcPresentStartTime : 0);
512 // When we started waiting for the release fence after calling into hwc present
513 timeline.releaseFenceWaitStartTime =
514 timeline.hwcPresentStartTime + timeline.hwcPresentDelayDuration + fenceWaitStartDelay;
515 timeline.probablyWaitsForReleaseFence = fenceTime > timeline.releaseFenceWaitStartTime &&
516 fenceTime < timeline.hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000517
Matt Buckley16dec1f2022-06-07 21:46:20 +0000518 // How long we ran after we finished waiting for the fence but before hwc present finished
519 timeline.postReleaseFenceHwcPresentDuration = timeline.hwcPresentEndTime -
520 (timeline.probablyWaitsForReleaseFence ? fenceTime
521 : timeline.releaseFenceWaitStartTime);
Matt Buckley50c44062022-01-17 20:48:10 +0000522 return timeline;
523}
524
525std::optional<PowerAdvisor::GpuTimeline> PowerAdvisor::DisplayTimingData::estimateGpuTiming(
526 std::optional<nsecs_t> previousEnd) {
527 if (!(usedClientComposition && lastValidGpuStartTime.has_value() && gpuEndFenceTime)) {
528 return std::nullopt;
529 }
530 const nsecs_t latestGpuStartTime = std::max(previousEnd.value_or(0), *gpuStartTime);
531 const nsecs_t latestGpuEndTime = gpuEndFenceTime->getSignalTime();
532 nsecs_t gpuDuration = 0;
533 if (latestGpuEndTime != Fence::SIGNAL_TIME_INVALID &&
534 latestGpuEndTime != Fence::SIGNAL_TIME_PENDING) {
535 // If we know how long the most recent gpu duration was, use that
536 gpuDuration = latestGpuEndTime - latestGpuStartTime;
537 } else if (lastValidGpuEndTime.has_value()) {
538 // If we don't have the fence data, use the most recent information we do have
539 gpuDuration = *lastValidGpuEndTime - *lastValidGpuStartTime;
540 if (latestGpuEndTime == Fence::SIGNAL_TIME_PENDING) {
541 // If pending but went over the previous duration, use current time as the end
542 gpuDuration = std::max(gpuDuration, systemTime() - latestGpuStartTime);
543 }
544 }
545 return GpuTimeline{.duration = gpuDuration, .startTime = latestGpuStartTime};
546}
547
Dan Stoza030fbc12020-02-19 15:32:01 -0800548class HidlPowerHalWrapper : public PowerAdvisor::HalWrapper {
549public:
550 HidlPowerHalWrapper(sp<V1_3::IPower> powerHal) : mPowerHal(std::move(powerHal)) {}
551
552 ~HidlPowerHalWrapper() override = default;
553
554 static std::unique_ptr<HalWrapper> connect() {
555 // Power HAL 1.3 is not guaranteed to be available, thus we need to query
556 // Power HAL 1.0 first and try to cast it to Power HAL 1.3.
Dan Stoza030fbc12020-02-19 15:32:01 -0800557 sp<V1_3::IPower> powerHal = nullptr;
Dan Stoza9c051c02020-02-28 10:19:07 -0800558 sp<V1_0::IPower> powerHal_1_0 = V1_0::IPower::getService();
559 if (powerHal_1_0 != nullptr) {
560 // Try to cast to Power HAL 1.3
561 powerHal = V1_3::IPower::castFrom(powerHal_1_0);
562 if (powerHal == nullptr) {
563 ALOGW("No Power HAL 1.3 service in system, disabling PowerAdvisor");
564 } else {
565 ALOGI("Loaded Power HAL 1.3 service");
Dan Stoza030fbc12020-02-19 15:32:01 -0800566 }
Dan Stoza9c051c02020-02-28 10:19:07 -0800567 } else {
568 ALOGW("No Power HAL found, disabling PowerAdvisor");
Dan Stoza030fbc12020-02-19 15:32:01 -0800569 }
Dan Stoza9c051c02020-02-28 10:19:07 -0800570
Dan Stoza030fbc12020-02-19 15:32:01 -0800571 if (powerHal == nullptr) {
572 return nullptr;
573 }
574
575 return std::make_unique<HidlPowerHalWrapper>(std::move(powerHal));
576 }
577
578 bool setExpensiveRendering(bool enabled) override {
579 ALOGV("HIDL setExpensiveRendering %s", enabled ? "T" : "F");
580 auto ret = mPowerHal->powerHintAsync_1_3(PowerHint::EXPENSIVE_RENDERING, enabled);
Ady Abrahamabce1652022-02-24 10:51:19 -0800581 if (ret.isOk()) {
582 traceExpensiveRendering(enabled);
583 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800584 return ret.isOk();
585 }
586
587 bool notifyDisplayUpdateImminent() override {
588 // Power HAL 1.x doesn't have a notification for this
589 ALOGV("HIDL notifyUpdateImminent received but can't send");
590 return true;
591 }
592
Matt Buckley06f299a2021-09-24 19:43:51 +0000593 bool supportsPowerHintSession() override { return false; }
594
595 bool isPowerHintSessionRunning() override { return false; }
596
597 void restartPowerHintSession() override {}
598
599 void setPowerHintSessionThreadIds(const std::vector<int32_t>&) override {}
600
601 bool startPowerHintSession() override { return false; }
602
603 void setTargetWorkDuration(int64_t) override {}
604
605 void sendActualWorkDuration(int64_t, nsecs_t) override {}
606
607 bool shouldReconnectHAL() override { return false; }
608
609 std::vector<int32_t> getPowerHintSessionThreadIds() override { return std::vector<int32_t>{}; }
610
611 std::optional<int64_t> getTargetWorkDuration() override { return std::nullopt; }
612
Dan Stoza030fbc12020-02-19 15:32:01 -0800613private:
Dan Stoza030fbc12020-02-19 15:32:01 -0800614 const sp<V1_3::IPower> mPowerHal = nullptr;
615};
616
Xiang Wange12b4fa2022-03-25 23:48:40 +0000617AidlPowerHalWrapper::AidlPowerHalWrapper(sp<IPower> powerHal) : mPowerHal(std::move(powerHal)) {
618 auto ret = mPowerHal->isModeSupported(Mode::EXPENSIVE_RENDERING, &mHasExpensiveRendering);
619 if (!ret.isOk()) {
620 mHasExpensiveRendering = false;
Dan Stoza030fbc12020-02-19 15:32:01 -0800621 }
622
Xiang Wange12b4fa2022-03-25 23:48:40 +0000623 ret = mPowerHal->isBoostSupported(Boost::DISPLAY_UPDATE_IMMINENT, &mHasDisplayUpdateImminent);
624 if (!ret.isOk()) {
625 mHasDisplayUpdateImminent = false;
Dan Stoza030fbc12020-02-19 15:32:01 -0800626 }
627
Xiang Wange12b4fa2022-03-25 23:48:40 +0000628 mSupportsPowerHint = checkPowerHintSessionSupported();
Matt Buckley50c44062022-01-17 20:48:10 +0000629
630 mAllowedActualDeviation =
631 base::GetIntProperty<nsecs_t>("debug.sf.allowed_actual_deviation",
632 std::chrono::nanoseconds(250us).count());
Xiang Wange12b4fa2022-03-25 23:48:40 +0000633}
Dan Stoza030fbc12020-02-19 15:32:01 -0800634
Xiang Wange12b4fa2022-03-25 23:48:40 +0000635AidlPowerHalWrapper::~AidlPowerHalWrapper() {
636 if (mPowerHintSession != nullptr) {
637 mPowerHintSession->close();
638 mPowerHintSession = nullptr;
Dan Stoza030fbc12020-02-19 15:32:01 -0800639 }
Matt Buckley50c44062022-01-17 20:48:10 +0000640}
Dan Stoza030fbc12020-02-19 15:32:01 -0800641
Xiang Wange12b4fa2022-03-25 23:48:40 +0000642std::unique_ptr<PowerAdvisor::HalWrapper> AidlPowerHalWrapper::connect() {
643 // This only waits if the service is actually declared
644 sp<IPower> powerHal = waitForVintfService<IPower>();
645 if (powerHal == nullptr) {
646 return nullptr;
647 }
648 ALOGI("Loaded AIDL Power HAL service");
649
650 return std::make_unique<AidlPowerHalWrapper>(std::move(powerHal));
651}
652
653bool AidlPowerHalWrapper::setExpensiveRendering(bool enabled) {
654 ALOGV("AIDL setExpensiveRendering %s", enabled ? "T" : "F");
655 if (!mHasExpensiveRendering) {
656 ALOGV("Skipped sending EXPENSIVE_RENDERING because HAL doesn't support it");
657 return true;
658 }
659
660 auto ret = mPowerHal->setMode(Mode::EXPENSIVE_RENDERING, enabled);
661 if (ret.isOk()) {
662 traceExpensiveRendering(enabled);
663 }
664 return ret.isOk();
665}
666
667bool AidlPowerHalWrapper::notifyDisplayUpdateImminent() {
668 ALOGV("AIDL notifyDisplayUpdateImminent");
669 if (!mHasDisplayUpdateImminent) {
670 ALOGV("Skipped sending DISPLAY_UPDATE_IMMINENT because HAL doesn't support it");
671 return true;
672 }
673
674 auto ret = mPowerHal->setBoost(Boost::DISPLAY_UPDATE_IMMINENT, 0);
675 return ret.isOk();
676}
677
Matt Buckley50c44062022-01-17 20:48:10 +0000678// Only version 2+ of the aidl supports power hint sessions, hidl has no support
Xiang Wange12b4fa2022-03-25 23:48:40 +0000679bool AidlPowerHalWrapper::supportsPowerHintSession() {
680 return mSupportsPowerHint;
681}
682
683bool AidlPowerHalWrapper::checkPowerHintSessionSupported() {
684 int64_t unused;
685 // Try to get preferred rate to determine if hint sessions are supported
686 // We check for isOk not EX_UNSUPPORTED_OPERATION to lump together errors
687 return mPowerHal->getHintSessionPreferredRate(&unused).isOk();
688}
689
690bool AidlPowerHalWrapper::isPowerHintSessionRunning() {
691 return mPowerHintSession != nullptr;
692}
693
694void AidlPowerHalWrapper::closePowerHintSession() {
695 if (mPowerHintSession != nullptr) {
696 mPowerHintSession->close();
697 mPowerHintSession = nullptr;
698 }
699}
700
701void AidlPowerHalWrapper::restartPowerHintSession() {
702 closePowerHintSession();
703 startPowerHintSession();
704}
705
706void AidlPowerHalWrapper::setPowerHintSessionThreadIds(const std::vector<int32_t>& threadIds) {
707 if (threadIds != mPowerHintThreadIds) {
708 mPowerHintThreadIds = threadIds;
709 if (isPowerHintSessionRunning()) {
710 restartPowerHintSession();
711 }
712 }
713}
714
715bool AidlPowerHalWrapper::startPowerHintSession() {
716 if (mPowerHintSession != nullptr || mPowerHintThreadIds.empty()) {
717 ALOGV("Cannot start power hint session, skipping");
718 return false;
719 }
720 auto ret =
721 mPowerHal->createHintSession(getpid(), static_cast<int32_t>(getuid()),
722 mPowerHintThreadIds, mTargetDuration, &mPowerHintSession);
723 if (!ret.isOk()) {
724 ALOGW("Failed to start power hint session with error: %s",
725 ret.exceptionToString(ret.exceptionCode()).c_str());
726 } else {
727 mLastTargetDurationSent = mTargetDuration;
728 }
729 return isPowerHintSessionRunning();
730}
731
Matt Buckley50c44062022-01-17 20:48:10 +0000732void AidlPowerHalWrapper::setTargetWorkDuration(int64_t targetDuration) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000733 ATRACE_CALL();
Matt Buckley50c44062022-01-17 20:48:10 +0000734 mTargetDuration = targetDuration;
735 if (sTraceHintSessionData) ATRACE_INT64("Time target", targetDuration);
736 if (isPowerHintSessionRunning() && (targetDuration != mLastTargetDurationSent)) {
737 ALOGV("Sending target time: %" PRId64 "ns", targetDuration);
738 mLastTargetDurationSent = targetDuration;
739 auto ret = mPowerHintSession->updateTargetWorkDuration(targetDuration);
Xiang Wange12b4fa2022-03-25 23:48:40 +0000740 if (!ret.isOk()) {
741 ALOGW("Failed to set power hint target work duration with error: %s",
742 ret.exceptionMessage().c_str());
743 mShouldReconnectHal = true;
744 }
745 }
746}
747
Matt Buckley50c44062022-01-17 20:48:10 +0000748bool AidlPowerHalWrapper::shouldReportActualDurations() {
749 // Report if we have never reported before or are approaching a stale session
Xiang Wange12b4fa2022-03-25 23:48:40 +0000750 if (!mLastActualDurationSent.has_value() ||
751 (systemTime() - mLastActualReportTimestamp) > kStaleTimeout.count()) {
752 return true;
753 }
754
755 if (!mActualDuration.has_value()) {
756 return false;
757 }
Matt Buckley50c44062022-01-17 20:48:10 +0000758 // Report if the change in actual duration exceeds the threshold
759 return abs(*mActualDuration - *mLastActualDurationSent) > mAllowedActualDeviation;
Xiang Wange12b4fa2022-03-25 23:48:40 +0000760}
761
Matt Buckley50c44062022-01-17 20:48:10 +0000762void AidlPowerHalWrapper::sendActualWorkDuration(int64_t actualDuration, nsecs_t timestamp) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000763 ATRACE_CALL();
764
Matt Buckley50c44062022-01-17 20:48:10 +0000765 if (actualDuration < 0 || !isPowerHintSessionRunning()) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000766 ALOGV("Failed to send actual work duration, skipping");
767 return;
768 }
Matt Buckley50c44062022-01-17 20:48:10 +0000769 const nsecs_t reportedDuration = actualDuration;
Xiang Wange12b4fa2022-03-25 23:48:40 +0000770
Xiang Wang0aba49e2022-04-06 16:13:59 +0000771 mActualDuration = reportedDuration;
772 WorkDuration duration;
773 duration.durationNanos = reportedDuration;
Matt Buckley50c44062022-01-17 20:48:10 +0000774 duration.timeStampNanos = timestamp;
Xiang Wange12b4fa2022-03-25 23:48:40 +0000775 mPowerHintQueue.push_back(duration);
776
Xiang Wange12b4fa2022-03-25 23:48:40 +0000777 if (sTraceHintSessionData) {
Matt Buckley50c44062022-01-17 20:48:10 +0000778 ATRACE_INT64("Measured duration", actualDuration);
779 ATRACE_INT64("Target error term", actualDuration - mTargetDuration);
Xiang Wang0aba49e2022-04-06 16:13:59 +0000780
781 ATRACE_INT64("Reported duration", reportedDuration);
782 ATRACE_INT64("Reported target", mLastTargetDurationSent);
Matt Buckley50c44062022-01-17 20:48:10 +0000783 ATRACE_INT64("Reported target error term", reportedDuration - mLastTargetDurationSent);
Xiang Wange12b4fa2022-03-25 23:48:40 +0000784 }
785
Xiang Wang0aba49e2022-04-06 16:13:59 +0000786 ALOGV("Sending actual work duration of: %" PRId64 " on reported target: %" PRId64
Xiang Wange12b4fa2022-03-25 23:48:40 +0000787 " with error: %" PRId64,
Matt Buckley50c44062022-01-17 20:48:10 +0000788 reportedDuration, mLastTargetDurationSent, reportedDuration - mLastTargetDurationSent);
Xiang Wange12b4fa2022-03-25 23:48:40 +0000789
790 // This rate limiter queues similar duration reports to the powerhal into
791 // batches to avoid excessive binder calls. The criteria to send a given batch
792 // are outlined in shouldReportActualDurationsNow()
Matt Buckley50c44062022-01-17 20:48:10 +0000793 if (shouldReportActualDurations()) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000794 ALOGV("Sending hint update batch");
795 mLastActualReportTimestamp = systemTime();
796 auto ret = mPowerHintSession->reportActualWorkDuration(mPowerHintQueue);
797 if (!ret.isOk()) {
798 ALOGW("Failed to report actual work durations with error: %s",
799 ret.exceptionMessage().c_str());
800 mShouldReconnectHal = true;
801 }
802 mPowerHintQueue.clear();
Matt Buckley50c44062022-01-17 20:48:10 +0000803 // We save the actual duration here for rate limiting
804 mLastActualDurationSent = actualDuration;
Xiang Wange12b4fa2022-03-25 23:48:40 +0000805 }
806}
807
808bool AidlPowerHalWrapper::shouldReconnectHAL() {
809 return mShouldReconnectHal;
810}
811
812std::vector<int32_t> AidlPowerHalWrapper::getPowerHintSessionThreadIds() {
813 return mPowerHintThreadIds;
814}
815
816std::optional<int64_t> AidlPowerHalWrapper::getTargetWorkDuration() {
817 return mTargetDuration;
818}
819
Matt Buckley50c44062022-01-17 20:48:10 +0000820void AidlPowerHalWrapper::setAllowedActualDeviation(nsecs_t allowedDeviation) {
821 mAllowedActualDeviation = allowedDeviation;
822}
823
Matt Buckleyef51fba2021-10-12 19:30:12 +0000824const bool AidlPowerHalWrapper::sTraceHintSessionData =
825 base::GetBoolProperty(std::string("debug.sf.trace_hint_sessions"), false);
826
Dan Stoza030fbc12020-02-19 15:32:01 -0800827PowerAdvisor::HalWrapper* PowerAdvisor::getPowerHal() {
828 static std::unique_ptr<HalWrapper> sHalWrapper = nullptr;
Dan Stoza9c051c02020-02-28 10:19:07 -0800829 static bool sHasHal = true;
Michael Wright1509a232018-06-21 02:50:34 +0100830
Dan Stoza9c051c02020-02-28 10:19:07 -0800831 if (!sHasHal) {
832 return nullptr;
833 }
834
Matt Buckley50c44062022-01-17 20:48:10 +0000835 // Grab old hint session values before we destroy any existing wrapper
Matt Buckley06f299a2021-09-24 19:43:51 +0000836 std::vector<int32_t> oldPowerHintSessionThreadIds;
837 std::optional<int64_t> oldTargetWorkDuration;
838
839 if (sHalWrapper != nullptr) {
840 oldPowerHintSessionThreadIds = sHalWrapper->getPowerHintSessionThreadIds();
841 oldTargetWorkDuration = sHalWrapper->getTargetWorkDuration();
842 }
843
Dan Stoza9c051c02020-02-28 10:19:07 -0800844 // If we used to have a HAL, but it stopped responding, attempt to reconnect
Michael Wright1509a232018-06-21 02:50:34 +0100845 if (mReconnectPowerHal) {
Dan Stoza030fbc12020-02-19 15:32:01 -0800846 sHalWrapper = nullptr;
Michael Wright1509a232018-06-21 02:50:34 +0100847 mReconnectPowerHal = false;
848 }
849
Dan Stoza030fbc12020-02-19 15:32:01 -0800850 if (sHalWrapper != nullptr) {
Matt Buckley06f299a2021-09-24 19:43:51 +0000851 auto wrapper = sHalWrapper.get();
Matt Buckley50c44062022-01-17 20:48:10 +0000852 // If the wrapper is fine, return it, but if it indicates a reconnect, remake it
Matt Buckley06f299a2021-09-24 19:43:51 +0000853 if (!wrapper->shouldReconnectHAL()) {
854 return wrapper;
855 }
Xiang Wang65a2e6f2022-04-18 21:19:17 +0000856 ALOGD("Reconnecting Power HAL");
Matt Buckley06f299a2021-09-24 19:43:51 +0000857 sHalWrapper = nullptr;
Michael Wright1509a232018-06-21 02:50:34 +0100858 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800859
Matt Buckley50c44062022-01-17 20:48:10 +0000860 // At this point, we know for sure there is no running session
Matt Buckley06f299a2021-09-24 19:43:51 +0000861 mPowerHintSessionRunning = false;
862
Dan Stoza030fbc12020-02-19 15:32:01 -0800863 // First attempt to connect to the AIDL Power HAL
864 sHalWrapper = AidlPowerHalWrapper::connect();
865
866 // If that didn't succeed, attempt to connect to the HIDL Power HAL
867 if (sHalWrapper == nullptr) {
868 sHalWrapper = HidlPowerHalWrapper::connect();
Xiang Wang65a2e6f2022-04-18 21:19:17 +0000869 } else {
870 ALOGD("Successfully connecting AIDL Power HAL");
Matt Buckley50c44062022-01-17 20:48:10 +0000871 // If AIDL, pass on any existing hint session values
Matt Buckley06f299a2021-09-24 19:43:51 +0000872 sHalWrapper->setPowerHintSessionThreadIds(oldPowerHintSessionThreadIds);
Matt Buckley50c44062022-01-17 20:48:10 +0000873 // Only set duration and start if duration is defined
Matt Buckley06f299a2021-09-24 19:43:51 +0000874 if (oldTargetWorkDuration.has_value()) {
875 sHalWrapper->setTargetWorkDuration(*oldTargetWorkDuration);
Matt Buckley50c44062022-01-17 20:48:10 +0000876 // Only start if possible to run and both threadids and duration are defined
Matt Buckley06f299a2021-09-24 19:43:51 +0000877 if (usePowerHintSession() && !oldPowerHintSessionThreadIds.empty()) {
878 mPowerHintSessionRunning = sHalWrapper->startPowerHintSession();
879 }
880 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800881 }
882
Dan Stoza9c051c02020-02-28 10:19:07 -0800883 // If we make it to this point and still don't have a HAL, it's unlikely we
884 // will, so stop trying
885 if (sHalWrapper == nullptr) {
886 sHasHal = false;
887 }
888
Dan Stoza030fbc12020-02-19 15:32:01 -0800889 return sHalWrapper.get();
Michael Wright1509a232018-06-21 02:50:34 +0100890}
891
892} // namespace impl
893} // namespace Hwc2
894} // namespace android