blob: 566537b576b7f55b90dc0f23ef5f7a8036bb823f [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();
Shao-Chuan Lee65a2c192022-07-27 09:53:41 +0900190 mSupportsPowerHint = halWrapper && halWrapper->supportsPowerHintSession();
Matt Buckley06f299a2021-09-24 19:43:51 +0000191 }
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) {
Matt Buckleyffabce92022-06-17 13:52:46 -0700241 halWrapper->sendActualWorkDuration(*predictedDuration + kTargetSafetyMargin.count(),
242 systemTime());
Matt Buckley50c44062022-01-17 20:48:10 +0000243 }
244 }
245}
246
Matt Buckley06f299a2021-09-24 19:43:51 +0000247void PowerAdvisor::enablePowerHint(bool enabled) {
248 mPowerHintEnabled = enabled;
249}
250
Matt Buckleyef51fba2021-10-12 19:30:12 +0000251bool PowerAdvisor::startPowerHintSession(const std::vector<int32_t>& threadIds) {
252 if (!usePowerHintSession()) {
253 ALOGI("Power hint session cannot be started, skipping");
254 }
255 {
256 std::lock_guard lock(mPowerHalMutex);
257 HalWrapper* halWrapper = getPowerHal();
258 if (halWrapper != nullptr && usePowerHintSession()) {
259 halWrapper->setPowerHintSessionThreadIds(threadIds);
260 mPowerHintSessionRunning = halWrapper->startPowerHintSession();
261 }
262 }
263 return mPowerHintSessionRunning;
264}
265
Matt Buckley50c44062022-01-17 20:48:10 +0000266void PowerAdvisor::setGpuFenceTime(DisplayId displayId, std::unique_ptr<FenceTime>&& fenceTime) {
267 DisplayTimingData& displayData = mDisplayTimingData[displayId];
268 if (displayData.gpuEndFenceTime) {
269 nsecs_t signalTime = displayData.gpuEndFenceTime->getSignalTime();
270 if (signalTime != Fence::SIGNAL_TIME_INVALID && signalTime != Fence::SIGNAL_TIME_PENDING) {
271 for (auto&& [_, otherDisplayData] : mDisplayTimingData) {
272 // If the previous display started before us but ended after we should have
273 // started, then it likely delayed our start time and we must compensate for that.
274 // Displays finishing earlier should have already made their way through this call
275 // and swapped their timing into "lastValid" from "latest", so we check that here.
276 if (!otherDisplayData.lastValidGpuStartTime.has_value()) continue;
277 if ((*otherDisplayData.lastValidGpuStartTime < *displayData.gpuStartTime) &&
278 (*otherDisplayData.lastValidGpuEndTime > *displayData.gpuStartTime)) {
279 displayData.lastValidGpuStartTime = *otherDisplayData.lastValidGpuEndTime;
280 break;
281 }
282 }
283 displayData.lastValidGpuStartTime = displayData.gpuStartTime;
284 displayData.lastValidGpuEndTime = signalTime;
285 }
286 }
287 displayData.gpuEndFenceTime = std::move(fenceTime);
288 displayData.gpuStartTime = systemTime();
289}
290
Matt Buckley16dec1f2022-06-07 21:46:20 +0000291void PowerAdvisor::setHwcValidateTiming(DisplayId displayId, nsecs_t validateStartTime,
292 nsecs_t validateEndTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000293 DisplayTimingData& displayData = mDisplayTimingData[displayId];
Matt Buckley16dec1f2022-06-07 21:46:20 +0000294 displayData.hwcValidateStartTime = validateStartTime;
295 displayData.hwcValidateEndTime = validateEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000296}
297
Matt Buckley16dec1f2022-06-07 21:46:20 +0000298void PowerAdvisor::setHwcPresentTiming(DisplayId displayId, nsecs_t presentStartTime,
299 nsecs_t presentEndTime) {
Matt Buckley50c44062022-01-17 20:48:10 +0000300 DisplayTimingData& displayData = mDisplayTimingData[displayId];
Matt Buckley16dec1f2022-06-07 21:46:20 +0000301 displayData.hwcPresentStartTime = presentStartTime;
302 displayData.hwcPresentEndTime = presentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000303}
304
305void PowerAdvisor::setSkippedValidate(DisplayId displayId, bool skipped) {
306 mDisplayTimingData[displayId].skippedValidate = skipped;
307}
308
309void PowerAdvisor::setRequiresClientComposition(DisplayId displayId,
310 bool requiresClientComposition) {
311 mDisplayTimingData[displayId].usedClientComposition = requiresClientComposition;
312}
313
314void PowerAdvisor::setExpectedPresentTime(nsecs_t expectedPresentTime) {
315 mExpectedPresentTimes.append(expectedPresentTime);
316}
317
Matt Buckley1809d902022-08-05 06:51:43 +0000318void PowerAdvisor::setSfPresentTiming(nsecs_t presentFenceTime, nsecs_t presentEndTime) {
319 mLastSfPresentEndTime = presentEndTime;
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700320 mLastPresentFenceTime = presentFenceTime;
321}
322
Matt Buckley50c44062022-01-17 20:48:10 +0000323void PowerAdvisor::setFrameDelay(nsecs_t frameDelayDuration) {
324 mFrameDelayDuration = frameDelayDuration;
325}
326
Matt Buckley16dec1f2022-06-07 21:46:20 +0000327void PowerAdvisor::setHwcPresentDelayedTime(
Matt Buckley50c44062022-01-17 20:48:10 +0000328 DisplayId displayId, std::chrono::steady_clock::time_point earliestFrameStartTime) {
Matt Buckley16dec1f2022-06-07 21:46:20 +0000329 mDisplayTimingData[displayId].hwcPresentDelayedTime =
Matt Buckley50c44062022-01-17 20:48:10 +0000330 (earliestFrameStartTime - std::chrono::steady_clock::now()).count() + systemTime();
331}
332
333void PowerAdvisor::setCommitStart(nsecs_t commitStartTime) {
334 mCommitStartTimes.append(commitStartTime);
335}
336
337void PowerAdvisor::setCompositeEnd(nsecs_t compositeEnd) {
Matt Buckley1809d902022-08-05 06:51:43 +0000338 mLastPostcompDuration = compositeEnd - mLastSfPresentEndTime;
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
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700386 // When the prior frame should be presenting to the display
387 // If we're predicting at the start of the frame, we use last frame's expected present time
388 // If we're predicting at the end of the frame, the present fence time is already known
389 nsecs_t lastFramePresentTime = (earlyHint ? mExpectedPresentTimes[-1] : mLastPresentFenceTime);
390
Matt Buckley50c44062022-01-17 20:48:10 +0000391 // 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
Matt Buckley1809d902022-08-05 06:51:43 +0000397 // Iterate over the displays that use hwc in the same order they are presented
Matt Buckley50c44062022-01-17 20:48:10 +0000398 for (DisplayId displayId : displayIds) {
399 if (mDisplayTimingData.count(displayId) == 0) {
400 continue;
401 }
402
403 auto& displayData = mDisplayTimingData.at(displayId);
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700404
405 // mLastPresentFenceTime should always be the time of the reference frame, since it will be
406 // the previous frame's present fence if called at the start, and current frame's if called
407 // at the end
408 referenceTiming = displayData.calculateDisplayTimeline(mLastPresentFenceTime);
Matt Buckley50c44062022-01-17 20:48:10 +0000409
Matt Buckley16dec1f2022-06-07 21:46:20 +0000410 // If this is the first display, include the duration before hwc present starts
Matt Buckley50c44062022-01-17 20:48:10 +0000411 if (!previousDisplayReferenceTiming.has_value()) {
Matt Buckley16dec1f2022-06-07 21:46:20 +0000412 estimatedEndTime += referenceTiming.hwcPresentStartTime - referenceFrameStartTime;
413 } else { // Otherwise add the time since last display's hwc present finished
414 estimatedEndTime += referenceTiming.hwcPresentStartTime -
415 previousDisplayReferenceTiming->hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000416 }
417
Matt Buckley50689e82022-06-21 13:23:27 -0700418 // Late hint can re-use reference timing here since it's estimating its own reference frame
419 estimatedTiming = earlyHint
420 ? referenceTiming.estimateTimelineFromReference(lastFramePresentTime,
421 estimatedEndTime)
422 : referenceTiming;
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700423
Matt Buckley50c44062022-01-17 20:48:10 +0000424 // Update predicted present finish time with this display's present time
Matt Buckley16dec1f2022-06-07 21:46:20 +0000425 estimatedEndTime = estimatedTiming.hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000426
427 // Track how long we spent waiting for the fence, can be excluded from the timing estimate
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700428 idleDuration += estimatedTiming.probablyWaitsForPresentFence
429 ? lastFramePresentTime - estimatedTiming.presentFenceWaitStartTime
Matt Buckley50c44062022-01-17 20:48:10 +0000430 : 0;
431
432 // Track how long we spent waiting to present, can be excluded from the timing estimate
Matt Buckley16dec1f2022-06-07 21:46:20 +0000433 idleDuration += earlyHint ? 0 : referenceTiming.hwcPresentDelayDuration;
Matt Buckley50c44062022-01-17 20:48:10 +0000434
435 // Estimate the reference frame's gpu timing
436 auto gpuTiming = displayData.estimateGpuTiming(previousValidGpuEndTime);
437 if (gpuTiming.has_value()) {
438 previousValidGpuEndTime = gpuTiming->startTime + gpuTiming->duration;
439
440 // Estimate the prediction frame's gpu end time from the reference frame
441 estimatedGpuEndTime =
Matt Buckley16dec1f2022-06-07 21:46:20 +0000442 std::max(estimatedTiming.hwcPresentStartTime, estimatedGpuEndTime.value_or(0)) +
Matt Buckley50c44062022-01-17 20:48:10 +0000443 gpuTiming->duration;
444 }
445 previousDisplayReferenceTiming = referenceTiming;
446 }
447 ATRACE_INT64("Idle duration", idleDuration);
448
Matt Buckley1809d902022-08-05 06:51:43 +0000449 nsecs_t estimatedFlingerEndTime = earlyHint ? estimatedEndTime : mLastSfPresentEndTime;
450
Matt Buckley50c44062022-01-17 20:48:10 +0000451 // Don't count time spent idly waiting in the estimate as we could do more work in that time
452 estimatedEndTime -= idleDuration;
Matt Buckley1809d902022-08-05 06:51:43 +0000453 estimatedFlingerEndTime -= idleDuration;
Matt Buckley50c44062022-01-17 20:48:10 +0000454
455 // We finish the frame when both present and the gpu are done, so wait for the later of the two
456 // Also add the frame delay duration since the target did not move while we were delayed
457 nsecs_t totalDuration = mFrameDelayDuration +
458 std::max(estimatedEndTime, estimatedGpuEndTime.value_or(0)) - mCommitStartTimes[0];
459
460 // We finish SurfaceFlinger when post-composition finishes, so add that in here
Matt Buckley1809d902022-08-05 06:51:43 +0000461 nsecs_t flingerDuration =
462 estimatedFlingerEndTime + mLastPostcompDuration - mCommitStartTimes[0];
463
464 // Combine the two timings into a single normalized one
Matt Buckley50c44062022-01-17 20:48:10 +0000465 nsecs_t combinedDuration = combineTimingEstimates(totalDuration, flingerDuration);
466
467 return std::make_optional(combinedDuration);
468}
469
470nsecs_t PowerAdvisor::combineTimingEstimates(nsecs_t totalDuration, nsecs_t flingerDuration) {
471 nsecs_t targetDuration;
472 {
473 std::lock_guard lock(mPowerHalMutex);
474 targetDuration = *getPowerHal()->getTargetWorkDuration();
475 }
476 if (!mTotalFrameTargetDuration.has_value()) return flingerDuration;
477
478 // Normalize total to the flinger target (vsync period) since that's how often we actually send
479 // hints
480 nsecs_t normalizedTotalDuration = (targetDuration * totalDuration) / *mTotalFrameTargetDuration;
481 return std::max(flingerDuration, normalizedTotalDuration);
482}
483
484PowerAdvisor::DisplayTimeline PowerAdvisor::DisplayTimeline::estimateTimelineFromReference(
485 nsecs_t fenceTime, nsecs_t displayStartTime) {
486 DisplayTimeline estimated;
Matt Buckley16dec1f2022-06-07 21:46:20 +0000487 estimated.hwcPresentStartTime = displayStartTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000488
489 // We don't predict waiting for vsync alignment yet
Matt Buckley16dec1f2022-06-07 21:46:20 +0000490 estimated.hwcPresentDelayDuration = 0;
Matt Buckley50c44062022-01-17 20:48:10 +0000491
Matt Buckley50c44062022-01-17 20:48:10 +0000492 // How long we expect to run before we start waiting for the fence
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700493 // For now just re-use last frame's post-present duration and assume it will not change much
494 // Excludes time spent waiting for vsync since that's not going to be consistent
495 estimated.presentFenceWaitStartTime = estimated.hwcPresentStartTime +
496 (presentFenceWaitStartTime - (hwcPresentStartTime + hwcPresentDelayDuration));
497 estimated.probablyWaitsForPresentFence = fenceTime > estimated.presentFenceWaitStartTime;
498 estimated.hwcPresentEndTime = postPresentFenceHwcPresentDuration +
499 (estimated.probablyWaitsForPresentFence ? fenceTime
500 : estimated.presentFenceWaitStartTime);
Matt Buckley50c44062022-01-17 20:48:10 +0000501 return estimated;
502}
503
504PowerAdvisor::DisplayTimeline PowerAdvisor::DisplayTimingData::calculateDisplayTimeline(
505 nsecs_t fenceTime) {
506 DisplayTimeline timeline;
Matt Buckley16dec1f2022-06-07 21:46:20 +0000507 // How long between calling hwc present and trying to wait on the fence
508 const nsecs_t fenceWaitStartDelay =
509 (skippedValidate ? kFenceWaitStartDelaySkippedValidate : kFenceWaitStartDelayValidated)
510 .count();
Matt Buckley50c44062022-01-17 20:48:10 +0000511
Matt Buckley16dec1f2022-06-07 21:46:20 +0000512 // Did our reference frame wait for an appropriate vsync before calling into hwc
513 const bool waitedOnHwcPresentTime = hwcPresentDelayedTime.has_value() &&
514 *hwcPresentDelayedTime > *hwcPresentStartTime &&
515 *hwcPresentDelayedTime < *hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000516
517 // Use validate start here if we skipped it because we did validate + present together
Matt Buckley16dec1f2022-06-07 21:46:20 +0000518 timeline.hwcPresentStartTime = skippedValidate ? *hwcValidateStartTime : *hwcPresentStartTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000519
520 // Use validate end here if we skipped it because we did validate + present together
Matt Buckley16dec1f2022-06-07 21:46:20 +0000521 timeline.hwcPresentEndTime = skippedValidate ? *hwcValidateEndTime : *hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000522
Matt Buckley16dec1f2022-06-07 21:46:20 +0000523 // How long hwc present was delayed waiting for the next appropriate vsync
524 timeline.hwcPresentDelayDuration =
525 (waitedOnHwcPresentTime ? *hwcPresentDelayedTime - *hwcPresentStartTime : 0);
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700526 // When we started waiting for the present fence after calling into hwc present
527 timeline.presentFenceWaitStartTime =
Matt Buckley16dec1f2022-06-07 21:46:20 +0000528 timeline.hwcPresentStartTime + timeline.hwcPresentDelayDuration + fenceWaitStartDelay;
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700529 timeline.probablyWaitsForPresentFence = fenceTime > timeline.presentFenceWaitStartTime &&
Matt Buckley16dec1f2022-06-07 21:46:20 +0000530 fenceTime < timeline.hwcPresentEndTime;
Matt Buckley50c44062022-01-17 20:48:10 +0000531
Matt Buckley16dec1f2022-06-07 21:46:20 +0000532 // How long we ran after we finished waiting for the fence but before hwc present finished
Matt Buckleyc6b9d382022-06-17 15:28:07 -0700533 timeline.postPresentFenceHwcPresentDuration = timeline.hwcPresentEndTime -
534 (timeline.probablyWaitsForPresentFence ? fenceTime
535 : timeline.presentFenceWaitStartTime);
Matt Buckley50c44062022-01-17 20:48:10 +0000536 return timeline;
537}
538
539std::optional<PowerAdvisor::GpuTimeline> PowerAdvisor::DisplayTimingData::estimateGpuTiming(
540 std::optional<nsecs_t> previousEnd) {
541 if (!(usedClientComposition && lastValidGpuStartTime.has_value() && gpuEndFenceTime)) {
542 return std::nullopt;
543 }
544 const nsecs_t latestGpuStartTime = std::max(previousEnd.value_or(0), *gpuStartTime);
545 const nsecs_t latestGpuEndTime = gpuEndFenceTime->getSignalTime();
546 nsecs_t gpuDuration = 0;
547 if (latestGpuEndTime != Fence::SIGNAL_TIME_INVALID &&
548 latestGpuEndTime != Fence::SIGNAL_TIME_PENDING) {
549 // If we know how long the most recent gpu duration was, use that
550 gpuDuration = latestGpuEndTime - latestGpuStartTime;
551 } else if (lastValidGpuEndTime.has_value()) {
552 // If we don't have the fence data, use the most recent information we do have
553 gpuDuration = *lastValidGpuEndTime - *lastValidGpuStartTime;
554 if (latestGpuEndTime == Fence::SIGNAL_TIME_PENDING) {
555 // If pending but went over the previous duration, use current time as the end
556 gpuDuration = std::max(gpuDuration, systemTime() - latestGpuStartTime);
557 }
558 }
559 return GpuTimeline{.duration = gpuDuration, .startTime = latestGpuStartTime};
560}
561
Dan Stoza030fbc12020-02-19 15:32:01 -0800562class HidlPowerHalWrapper : public PowerAdvisor::HalWrapper {
563public:
564 HidlPowerHalWrapper(sp<V1_3::IPower> powerHal) : mPowerHal(std::move(powerHal)) {}
565
566 ~HidlPowerHalWrapper() override = default;
567
568 static std::unique_ptr<HalWrapper> connect() {
569 // Power HAL 1.3 is not guaranteed to be available, thus we need to query
570 // Power HAL 1.0 first and try to cast it to Power HAL 1.3.
Dan Stoza030fbc12020-02-19 15:32:01 -0800571 sp<V1_3::IPower> powerHal = nullptr;
Dan Stoza9c051c02020-02-28 10:19:07 -0800572 sp<V1_0::IPower> powerHal_1_0 = V1_0::IPower::getService();
573 if (powerHal_1_0 != nullptr) {
574 // Try to cast to Power HAL 1.3
575 powerHal = V1_3::IPower::castFrom(powerHal_1_0);
576 if (powerHal == nullptr) {
577 ALOGW("No Power HAL 1.3 service in system, disabling PowerAdvisor");
578 } else {
579 ALOGI("Loaded Power HAL 1.3 service");
Dan Stoza030fbc12020-02-19 15:32:01 -0800580 }
Dan Stoza9c051c02020-02-28 10:19:07 -0800581 } else {
582 ALOGW("No Power HAL found, disabling PowerAdvisor");
Dan Stoza030fbc12020-02-19 15:32:01 -0800583 }
Dan Stoza9c051c02020-02-28 10:19:07 -0800584
Dan Stoza030fbc12020-02-19 15:32:01 -0800585 if (powerHal == nullptr) {
586 return nullptr;
587 }
588
589 return std::make_unique<HidlPowerHalWrapper>(std::move(powerHal));
590 }
591
592 bool setExpensiveRendering(bool enabled) override {
593 ALOGV("HIDL setExpensiveRendering %s", enabled ? "T" : "F");
594 auto ret = mPowerHal->powerHintAsync_1_3(PowerHint::EXPENSIVE_RENDERING, enabled);
Ady Abrahamabce1652022-02-24 10:51:19 -0800595 if (ret.isOk()) {
596 traceExpensiveRendering(enabled);
597 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800598 return ret.isOk();
599 }
600
601 bool notifyDisplayUpdateImminent() override {
602 // Power HAL 1.x doesn't have a notification for this
603 ALOGV("HIDL notifyUpdateImminent received but can't send");
604 return true;
605 }
606
Matt Buckley06f299a2021-09-24 19:43:51 +0000607 bool supportsPowerHintSession() override { return false; }
608
609 bool isPowerHintSessionRunning() override { return false; }
610
611 void restartPowerHintSession() override {}
612
613 void setPowerHintSessionThreadIds(const std::vector<int32_t>&) override {}
614
615 bool startPowerHintSession() override { return false; }
616
617 void setTargetWorkDuration(int64_t) override {}
618
619 void sendActualWorkDuration(int64_t, nsecs_t) override {}
620
621 bool shouldReconnectHAL() override { return false; }
622
623 std::vector<int32_t> getPowerHintSessionThreadIds() override { return std::vector<int32_t>{}; }
624
625 std::optional<int64_t> getTargetWorkDuration() override { return std::nullopt; }
626
Dan Stoza030fbc12020-02-19 15:32:01 -0800627private:
Dan Stoza030fbc12020-02-19 15:32:01 -0800628 const sp<V1_3::IPower> mPowerHal = nullptr;
629};
630
Xiang Wange12b4fa2022-03-25 23:48:40 +0000631AidlPowerHalWrapper::AidlPowerHalWrapper(sp<IPower> powerHal) : mPowerHal(std::move(powerHal)) {
632 auto ret = mPowerHal->isModeSupported(Mode::EXPENSIVE_RENDERING, &mHasExpensiveRendering);
633 if (!ret.isOk()) {
634 mHasExpensiveRendering = false;
Dan Stoza030fbc12020-02-19 15:32:01 -0800635 }
636
Xiang Wange12b4fa2022-03-25 23:48:40 +0000637 ret = mPowerHal->isBoostSupported(Boost::DISPLAY_UPDATE_IMMINENT, &mHasDisplayUpdateImminent);
638 if (!ret.isOk()) {
639 mHasDisplayUpdateImminent = false;
Dan Stoza030fbc12020-02-19 15:32:01 -0800640 }
641
Xiang Wange12b4fa2022-03-25 23:48:40 +0000642 mSupportsPowerHint = checkPowerHintSessionSupported();
Matt Buckley50c44062022-01-17 20:48:10 +0000643
Matt Buckley10ee4502022-08-10 23:09:04 +0000644 // Currently set to 0 to disable rate limiter by default
Matt Buckley111de032022-08-09 22:19:51 +0000645 mAllowedActualDeviation = base::GetIntProperty<nsecs_t>("debug.sf.allowed_actual_deviation", 0);
Xiang Wange12b4fa2022-03-25 23:48:40 +0000646}
Dan Stoza030fbc12020-02-19 15:32:01 -0800647
Xiang Wange12b4fa2022-03-25 23:48:40 +0000648AidlPowerHalWrapper::~AidlPowerHalWrapper() {
649 if (mPowerHintSession != nullptr) {
650 mPowerHintSession->close();
651 mPowerHintSession = nullptr;
Dan Stoza030fbc12020-02-19 15:32:01 -0800652 }
Matt Buckley50c44062022-01-17 20:48:10 +0000653}
Dan Stoza030fbc12020-02-19 15:32:01 -0800654
Xiang Wange12b4fa2022-03-25 23:48:40 +0000655std::unique_ptr<PowerAdvisor::HalWrapper> AidlPowerHalWrapper::connect() {
656 // This only waits if the service is actually declared
657 sp<IPower> powerHal = waitForVintfService<IPower>();
658 if (powerHal == nullptr) {
659 return nullptr;
660 }
661 ALOGI("Loaded AIDL Power HAL service");
662
663 return std::make_unique<AidlPowerHalWrapper>(std::move(powerHal));
664}
665
666bool AidlPowerHalWrapper::setExpensiveRendering(bool enabled) {
667 ALOGV("AIDL setExpensiveRendering %s", enabled ? "T" : "F");
668 if (!mHasExpensiveRendering) {
669 ALOGV("Skipped sending EXPENSIVE_RENDERING because HAL doesn't support it");
670 return true;
671 }
672
673 auto ret = mPowerHal->setMode(Mode::EXPENSIVE_RENDERING, enabled);
674 if (ret.isOk()) {
675 traceExpensiveRendering(enabled);
676 }
677 return ret.isOk();
678}
679
680bool AidlPowerHalWrapper::notifyDisplayUpdateImminent() {
681 ALOGV("AIDL notifyDisplayUpdateImminent");
682 if (!mHasDisplayUpdateImminent) {
683 ALOGV("Skipped sending DISPLAY_UPDATE_IMMINENT because HAL doesn't support it");
684 return true;
685 }
686
687 auto ret = mPowerHal->setBoost(Boost::DISPLAY_UPDATE_IMMINENT, 0);
688 return ret.isOk();
689}
690
Matt Buckley50c44062022-01-17 20:48:10 +0000691// Only version 2+ of the aidl supports power hint sessions, hidl has no support
Xiang Wange12b4fa2022-03-25 23:48:40 +0000692bool AidlPowerHalWrapper::supportsPowerHintSession() {
693 return mSupportsPowerHint;
694}
695
696bool AidlPowerHalWrapper::checkPowerHintSessionSupported() {
697 int64_t unused;
698 // Try to get preferred rate to determine if hint sessions are supported
699 // We check for isOk not EX_UNSUPPORTED_OPERATION to lump together errors
700 return mPowerHal->getHintSessionPreferredRate(&unused).isOk();
701}
702
703bool AidlPowerHalWrapper::isPowerHintSessionRunning() {
704 return mPowerHintSession != nullptr;
705}
706
707void AidlPowerHalWrapper::closePowerHintSession() {
708 if (mPowerHintSession != nullptr) {
709 mPowerHintSession->close();
710 mPowerHintSession = nullptr;
711 }
712}
713
714void AidlPowerHalWrapper::restartPowerHintSession() {
715 closePowerHintSession();
716 startPowerHintSession();
717}
718
719void AidlPowerHalWrapper::setPowerHintSessionThreadIds(const std::vector<int32_t>& threadIds) {
720 if (threadIds != mPowerHintThreadIds) {
721 mPowerHintThreadIds = threadIds;
722 if (isPowerHintSessionRunning()) {
723 restartPowerHintSession();
724 }
725 }
726}
727
728bool AidlPowerHalWrapper::startPowerHintSession() {
729 if (mPowerHintSession != nullptr || mPowerHintThreadIds.empty()) {
730 ALOGV("Cannot start power hint session, skipping");
731 return false;
732 }
733 auto ret =
734 mPowerHal->createHintSession(getpid(), static_cast<int32_t>(getuid()),
735 mPowerHintThreadIds, mTargetDuration, &mPowerHintSession);
736 if (!ret.isOk()) {
737 ALOGW("Failed to start power hint session with error: %s",
738 ret.exceptionToString(ret.exceptionCode()).c_str());
739 } else {
740 mLastTargetDurationSent = mTargetDuration;
741 }
742 return isPowerHintSessionRunning();
743}
744
Matt Buckley50c44062022-01-17 20:48:10 +0000745void AidlPowerHalWrapper::setTargetWorkDuration(int64_t targetDuration) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000746 ATRACE_CALL();
Matt Buckley50c44062022-01-17 20:48:10 +0000747 mTargetDuration = targetDuration;
748 if (sTraceHintSessionData) ATRACE_INT64("Time target", targetDuration);
749 if (isPowerHintSessionRunning() && (targetDuration != mLastTargetDurationSent)) {
750 ALOGV("Sending target time: %" PRId64 "ns", targetDuration);
751 mLastTargetDurationSent = targetDuration;
752 auto ret = mPowerHintSession->updateTargetWorkDuration(targetDuration);
Xiang Wange12b4fa2022-03-25 23:48:40 +0000753 if (!ret.isOk()) {
754 ALOGW("Failed to set power hint target work duration with error: %s",
755 ret.exceptionMessage().c_str());
756 mShouldReconnectHal = true;
757 }
758 }
759}
760
Matt Buckley50c44062022-01-17 20:48:10 +0000761bool AidlPowerHalWrapper::shouldReportActualDurations() {
Matt Buckleya8a45972022-07-27 22:01:27 +0000762 // Report if we have never reported before or will go stale next frame
Xiang Wange12b4fa2022-03-25 23:48:40 +0000763 if (!mLastActualDurationSent.has_value() ||
Matt Buckleya8a45972022-07-27 22:01:27 +0000764 (mLastTargetDurationSent + systemTime() - mLastActualReportTimestamp) >
765 kStaleTimeout.count()) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000766 return true;
767 }
768
769 if (!mActualDuration.has_value()) {
770 return false;
771 }
Matt Buckley50c44062022-01-17 20:48:10 +0000772 // Report if the change in actual duration exceeds the threshold
773 return abs(*mActualDuration - *mLastActualDurationSent) > mAllowedActualDeviation;
Xiang Wange12b4fa2022-03-25 23:48:40 +0000774}
775
Matt Buckley50c44062022-01-17 20:48:10 +0000776void AidlPowerHalWrapper::sendActualWorkDuration(int64_t actualDuration, nsecs_t timestamp) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000777 ATRACE_CALL();
778
Matt Buckley50c44062022-01-17 20:48:10 +0000779 if (actualDuration < 0 || !isPowerHintSessionRunning()) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000780 ALOGV("Failed to send actual work duration, skipping");
781 return;
782 }
Matt Buckley50c44062022-01-17 20:48:10 +0000783 const nsecs_t reportedDuration = actualDuration;
Xiang Wange12b4fa2022-03-25 23:48:40 +0000784
Xiang Wang0aba49e2022-04-06 16:13:59 +0000785 mActualDuration = reportedDuration;
786 WorkDuration duration;
787 duration.durationNanos = reportedDuration;
Matt Buckley50c44062022-01-17 20:48:10 +0000788 duration.timeStampNanos = timestamp;
Xiang Wange12b4fa2022-03-25 23:48:40 +0000789 mPowerHintQueue.push_back(duration);
790
Xiang Wange12b4fa2022-03-25 23:48:40 +0000791 if (sTraceHintSessionData) {
Matt Buckley50c44062022-01-17 20:48:10 +0000792 ATRACE_INT64("Measured duration", actualDuration);
793 ATRACE_INT64("Target error term", actualDuration - mTargetDuration);
Xiang Wang0aba49e2022-04-06 16:13:59 +0000794
795 ATRACE_INT64("Reported duration", reportedDuration);
796 ATRACE_INT64("Reported target", mLastTargetDurationSent);
Matt Buckley50c44062022-01-17 20:48:10 +0000797 ATRACE_INT64("Reported target error term", reportedDuration - mLastTargetDurationSent);
Xiang Wange12b4fa2022-03-25 23:48:40 +0000798 }
799
Xiang Wang0aba49e2022-04-06 16:13:59 +0000800 ALOGV("Sending actual work duration of: %" PRId64 " on reported target: %" PRId64
Xiang Wange12b4fa2022-03-25 23:48:40 +0000801 " with error: %" PRId64,
Matt Buckley50c44062022-01-17 20:48:10 +0000802 reportedDuration, mLastTargetDurationSent, reportedDuration - mLastTargetDurationSent);
Xiang Wange12b4fa2022-03-25 23:48:40 +0000803
804 // This rate limiter queues similar duration reports to the powerhal into
805 // batches to avoid excessive binder calls. The criteria to send a given batch
806 // are outlined in shouldReportActualDurationsNow()
Matt Buckley50c44062022-01-17 20:48:10 +0000807 if (shouldReportActualDurations()) {
Xiang Wange12b4fa2022-03-25 23:48:40 +0000808 ALOGV("Sending hint update batch");
809 mLastActualReportTimestamp = systemTime();
810 auto ret = mPowerHintSession->reportActualWorkDuration(mPowerHintQueue);
811 if (!ret.isOk()) {
812 ALOGW("Failed to report actual work durations with error: %s",
813 ret.exceptionMessage().c_str());
814 mShouldReconnectHal = true;
815 }
816 mPowerHintQueue.clear();
Matt Buckley50c44062022-01-17 20:48:10 +0000817 // We save the actual duration here for rate limiting
818 mLastActualDurationSent = actualDuration;
Xiang Wange12b4fa2022-03-25 23:48:40 +0000819 }
820}
821
822bool AidlPowerHalWrapper::shouldReconnectHAL() {
823 return mShouldReconnectHal;
824}
825
826std::vector<int32_t> AidlPowerHalWrapper::getPowerHintSessionThreadIds() {
827 return mPowerHintThreadIds;
828}
829
830std::optional<int64_t> AidlPowerHalWrapper::getTargetWorkDuration() {
831 return mTargetDuration;
832}
833
Matt Buckley50c44062022-01-17 20:48:10 +0000834void AidlPowerHalWrapper::setAllowedActualDeviation(nsecs_t allowedDeviation) {
835 mAllowedActualDeviation = allowedDeviation;
836}
837
Matt Buckleyef51fba2021-10-12 19:30:12 +0000838const bool AidlPowerHalWrapper::sTraceHintSessionData =
839 base::GetBoolProperty(std::string("debug.sf.trace_hint_sessions"), false);
840
Dan Stoza030fbc12020-02-19 15:32:01 -0800841PowerAdvisor::HalWrapper* PowerAdvisor::getPowerHal() {
Matt Buckley57274052022-08-12 21:54:23 +0000842 if (!mHasHal) {
Dan Stoza9c051c02020-02-28 10:19:07 -0800843 return nullptr;
844 }
845
Matt Buckley50c44062022-01-17 20:48:10 +0000846 // Grab old hint session values before we destroy any existing wrapper
Matt Buckley06f299a2021-09-24 19:43:51 +0000847 std::vector<int32_t> oldPowerHintSessionThreadIds;
848 std::optional<int64_t> oldTargetWorkDuration;
849
Matt Buckley57274052022-08-12 21:54:23 +0000850 if (mHalWrapper != nullptr) {
851 oldPowerHintSessionThreadIds = mHalWrapper->getPowerHintSessionThreadIds();
852 oldTargetWorkDuration = mHalWrapper->getTargetWorkDuration();
Matt Buckley06f299a2021-09-24 19:43:51 +0000853 }
854
Dan Stoza9c051c02020-02-28 10:19:07 -0800855 // If we used to have a HAL, but it stopped responding, attempt to reconnect
Michael Wright1509a232018-06-21 02:50:34 +0100856 if (mReconnectPowerHal) {
Matt Buckley57274052022-08-12 21:54:23 +0000857 mHalWrapper = nullptr;
Michael Wright1509a232018-06-21 02:50:34 +0100858 mReconnectPowerHal = false;
859 }
860
Matt Buckley57274052022-08-12 21:54:23 +0000861 if (mHalWrapper != nullptr) {
862 auto wrapper = mHalWrapper.get();
Matt Buckley50c44062022-01-17 20:48:10 +0000863 // If the wrapper is fine, return it, but if it indicates a reconnect, remake it
Matt Buckley06f299a2021-09-24 19:43:51 +0000864 if (!wrapper->shouldReconnectHAL()) {
865 return wrapper;
866 }
Xiang Wang65a2e6f2022-04-18 21:19:17 +0000867 ALOGD("Reconnecting Power HAL");
Matt Buckley57274052022-08-12 21:54:23 +0000868 mHalWrapper = nullptr;
Michael Wright1509a232018-06-21 02:50:34 +0100869 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800870
Matt Buckley50c44062022-01-17 20:48:10 +0000871 // At this point, we know for sure there is no running session
Matt Buckley06f299a2021-09-24 19:43:51 +0000872 mPowerHintSessionRunning = false;
873
Dan Stoza030fbc12020-02-19 15:32:01 -0800874 // First attempt to connect to the AIDL Power HAL
Matt Buckley57274052022-08-12 21:54:23 +0000875 mHalWrapper = AidlPowerHalWrapper::connect();
Dan Stoza030fbc12020-02-19 15:32:01 -0800876
877 // If that didn't succeed, attempt to connect to the HIDL Power HAL
Matt Buckley57274052022-08-12 21:54:23 +0000878 if (mHalWrapper == nullptr) {
879 mHalWrapper = HidlPowerHalWrapper::connect();
Xiang Wang65a2e6f2022-04-18 21:19:17 +0000880 } else {
881 ALOGD("Successfully connecting AIDL Power HAL");
Matt Buckley50c44062022-01-17 20:48:10 +0000882 // If AIDL, pass on any existing hint session values
Matt Buckley57274052022-08-12 21:54:23 +0000883 mHalWrapper->setPowerHintSessionThreadIds(oldPowerHintSessionThreadIds);
Matt Buckley50c44062022-01-17 20:48:10 +0000884 // Only set duration and start if duration is defined
Matt Buckley06f299a2021-09-24 19:43:51 +0000885 if (oldTargetWorkDuration.has_value()) {
Matt Buckley57274052022-08-12 21:54:23 +0000886 mHalWrapper->setTargetWorkDuration(*oldTargetWorkDuration);
Matt Buckley50c44062022-01-17 20:48:10 +0000887 // Only start if possible to run and both threadids and duration are defined
Matt Buckley06f299a2021-09-24 19:43:51 +0000888 if (usePowerHintSession() && !oldPowerHintSessionThreadIds.empty()) {
Matt Buckley57274052022-08-12 21:54:23 +0000889 mPowerHintSessionRunning = mHalWrapper->startPowerHintSession();
Matt Buckley06f299a2021-09-24 19:43:51 +0000890 }
891 }
Dan Stoza030fbc12020-02-19 15:32:01 -0800892 }
893
Dan Stoza9c051c02020-02-28 10:19:07 -0800894 // If we make it to this point and still don't have a HAL, it's unlikely we
895 // will, so stop trying
Matt Buckley57274052022-08-12 21:54:23 +0000896 if (mHalWrapper == nullptr) {
897 mHasHal = false;
Dan Stoza9c051c02020-02-28 10:19:07 -0800898 }
899
Matt Buckley57274052022-08-12 21:54:23 +0000900 return mHalWrapper.get();
Michael Wright1509a232018-06-21 02:50:34 +0100901}
902
903} // namespace impl
904} // namespace Hwc2
905} // namespace android