1 /*
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 
17 #undef LOG_TAG
18 #define LOG_TAG "Scheduler"
19 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
20 
21 #include "Scheduler.h"
22 
23 #include <android-base/stringprintf.h>
24 #include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
25 #include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
26 #include <configstore/Utils.h>
27 #include <cutils/properties.h>
28 #include <input/InputWindow.h>
29 #include <system/window.h>
30 #include <ui/DisplayStatInfo.h>
31 #include <utils/Timers.h>
32 #include <utils/Trace.h>
33 
34 #include <algorithm>
35 #include <cinttypes>
36 #include <cstdint>
37 #include <functional>
38 #include <memory>
39 #include <numeric>
40 
41 #include "../Layer.h"
42 #include "DispSync.h"
43 #include "DispSyncSource.h"
44 #include "EventControlThread.h"
45 #include "EventThread.h"
46 #include "InjectVSyncSource.h"
47 #include "OneShotTimer.h"
48 #include "SchedulerUtils.h"
49 #include "SurfaceFlingerProperties.h"
50 #include "Timer.h"
51 #include "VSyncDispatchTimerQueue.h"
52 #include "VSyncPredictor.h"
53 #include "VSyncReactor.h"
54 
55 #define RETURN_IF_INVALID_HANDLE(handle, ...)                        \
56     do {                                                             \
57         if (mConnections.count(handle) == 0) {                       \
58             ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
59             return __VA_ARGS__;                                      \
60         }                                                            \
61     } while (false)
62 
63 namespace android {
64 
createDispSync(bool supportKernelTimer)65 std::unique_ptr<DispSync> createDispSync(bool supportKernelTimer) {
66     // TODO (140302863) remove this and use the vsync_reactor system.
67     if (property_get_bool("debug.sf.vsync_reactor", true)) {
68         // TODO (144707443) tune Predictor tunables.
69         static constexpr int defaultRate = 60;
70         static constexpr auto initialPeriod =
71                 std::chrono::duration<nsecs_t, std::ratio<1, defaultRate>>(1);
72         static constexpr size_t vsyncTimestampHistorySize = 20;
73         static constexpr size_t minimumSamplesForPrediction = 6;
74         static constexpr uint32_t discardOutlierPercent = 20;
75         auto tracker = std::make_unique<
76                 scheduler::VSyncPredictor>(std::chrono::duration_cast<std::chrono::nanoseconds>(
77                                                    initialPeriod)
78                                                    .count(),
79                                            vsyncTimestampHistorySize, minimumSamplesForPrediction,
80                                            discardOutlierPercent);
81 
82         static constexpr auto vsyncMoveThreshold =
83                 std::chrono::duration_cast<std::chrono::nanoseconds>(3ms);
84         static constexpr auto timerSlack =
85                 std::chrono::duration_cast<std::chrono::nanoseconds>(500us);
86         auto dispatch = std::make_unique<
87                 scheduler::VSyncDispatchTimerQueue>(std::make_unique<scheduler::Timer>(), *tracker,
88                                                     timerSlack.count(), vsyncMoveThreshold.count());
89 
90         static constexpr size_t pendingFenceLimit = 20;
91         return std::make_unique<scheduler::VSyncReactor>(std::make_unique<scheduler::SystemClock>(),
92                                                          std::move(dispatch), std::move(tracker),
93                                                          pendingFenceLimit, supportKernelTimer);
94     } else {
95         return std::make_unique<impl::DispSync>("SchedulerDispSync",
96                                                 sysprop::running_without_sync_framework(true));
97     }
98 }
99 
Scheduler(impl::EventControlThread::SetVSyncEnabledFunction function,const scheduler::RefreshRateConfigs & refreshRateConfig,ISchedulerCallback & schedulerCallback,bool useContentDetectionV2,bool useContentDetection)100 Scheduler::Scheduler(impl::EventControlThread::SetVSyncEnabledFunction function,
101                      const scheduler::RefreshRateConfigs& refreshRateConfig,
102                      ISchedulerCallback& schedulerCallback, bool useContentDetectionV2,
103                      bool useContentDetection)
104       : mSupportKernelTimer(sysprop::support_kernel_idle_timer(false)),
105         mPrimaryDispSync(createDispSync(mSupportKernelTimer)),
106         mEventControlThread(new impl::EventControlThread(std::move(function))),
107         mSchedulerCallback(schedulerCallback),
108         mRefreshRateConfigs(refreshRateConfig),
109         mUseContentDetection(useContentDetection),
110         mUseContentDetectionV2(useContentDetectionV2) {
111     using namespace sysprop;
112 
113     if (mUseContentDetectionV2) {
114         mLayerHistory = std::make_unique<scheduler::impl::LayerHistoryV2>(refreshRateConfig);
115     } else {
116         mLayerHistory = std::make_unique<scheduler::impl::LayerHistory>();
117     }
118 
119     const int setIdleTimerMs = property_get_int32("debug.sf.set_idle_timer_ms", 0);
120 
121     if (const auto millis = setIdleTimerMs ? setIdleTimerMs : set_idle_timer_ms(0); millis > 0) {
122         const auto callback = mSupportKernelTimer ? &Scheduler::kernelIdleTimerCallback
123                                                   : &Scheduler::idleTimerCallback;
124         mIdleTimer.emplace(
125                 std::chrono::milliseconds(millis),
126                 [this, callback] { std::invoke(callback, this, TimerState::Reset); },
127                 [this, callback] { std::invoke(callback, this, TimerState::Expired); });
128         mIdleTimer->start();
129     }
130 
131     if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
132         // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
133         mTouchTimer.emplace(
134                 std::chrono::milliseconds(millis),
135                 [this] { touchTimerCallback(TimerState::Reset); },
136                 [this] { touchTimerCallback(TimerState::Expired); });
137         mTouchTimer->start();
138     }
139 
140     if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
141         mDisplayPowerTimer.emplace(
142                 std::chrono::milliseconds(millis),
143                 [this] { displayPowerTimerCallback(TimerState::Reset); },
144                 [this] { displayPowerTimerCallback(TimerState::Expired); });
145         mDisplayPowerTimer->start();
146     }
147 }
148 
Scheduler(std::unique_ptr<DispSync> primaryDispSync,std::unique_ptr<EventControlThread> eventControlThread,const scheduler::RefreshRateConfigs & configs,ISchedulerCallback & schedulerCallback,bool useContentDetectionV2,bool useContentDetection)149 Scheduler::Scheduler(std::unique_ptr<DispSync> primaryDispSync,
150                      std::unique_ptr<EventControlThread> eventControlThread,
151                      const scheduler::RefreshRateConfigs& configs,
152                      ISchedulerCallback& schedulerCallback, bool useContentDetectionV2,
153                      bool useContentDetection)
154       : mSupportKernelTimer(false),
155         mPrimaryDispSync(std::move(primaryDispSync)),
156         mEventControlThread(std::move(eventControlThread)),
157         mSchedulerCallback(schedulerCallback),
158         mRefreshRateConfigs(configs),
159         mUseContentDetection(useContentDetection),
160         mUseContentDetectionV2(useContentDetectionV2) {}
161 
~Scheduler()162 Scheduler::~Scheduler() {
163     // Ensure the OneShotTimer threads are joined before we start destroying state.
164     mDisplayPowerTimer.reset();
165     mTouchTimer.reset();
166     mIdleTimer.reset();
167 }
168 
getPrimaryDispSync()169 DispSync& Scheduler::getPrimaryDispSync() {
170     return *mPrimaryDispSync;
171 }
172 
makePrimaryDispSyncSource(const char * name,nsecs_t phaseOffsetNs)173 std::unique_ptr<VSyncSource> Scheduler::makePrimaryDispSyncSource(const char* name,
174                                                                   nsecs_t phaseOffsetNs) {
175     return std::make_unique<DispSyncSource>(mPrimaryDispSync.get(), phaseOffsetNs,
176                                             true /* traceVsync */, name);
177 }
178 
createConnection(const char * connectionName,nsecs_t phaseOffsetNs,impl::EventThread::InterceptVSyncsCallback interceptCallback)179 Scheduler::ConnectionHandle Scheduler::createConnection(
180         const char* connectionName, nsecs_t phaseOffsetNs,
181         impl::EventThread::InterceptVSyncsCallback interceptCallback) {
182     auto vsyncSource = makePrimaryDispSyncSource(connectionName, phaseOffsetNs);
183     auto eventThread = std::make_unique<impl::EventThread>(std::move(vsyncSource),
184                                                            std::move(interceptCallback));
185     return createConnection(std::move(eventThread));
186 }
187 
createConnection(std::unique_ptr<EventThread> eventThread)188 Scheduler::ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
189     const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
190     ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
191 
192     auto connection =
193             createConnectionInternal(eventThread.get(), ISurfaceComposer::eConfigChangedSuppress);
194 
195     mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
196     return handle;
197 }
198 
createConnectionInternal(EventThread * eventThread,ISurfaceComposer::ConfigChanged configChanged)199 sp<EventThreadConnection> Scheduler::createConnectionInternal(
200         EventThread* eventThread, ISurfaceComposer::ConfigChanged configChanged) {
201     return eventThread->createEventConnection([&] { resync(); }, configChanged);
202 }
203 
createDisplayEventConnection(ConnectionHandle handle,ISurfaceComposer::ConfigChanged configChanged)204 sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
205         ConnectionHandle handle, ISurfaceComposer::ConfigChanged configChanged) {
206     RETURN_IF_INVALID_HANDLE(handle, nullptr);
207     return createConnectionInternal(mConnections[handle].thread.get(), configChanged);
208 }
209 
getEventConnection(ConnectionHandle handle)210 sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
211     RETURN_IF_INVALID_HANDLE(handle, nullptr);
212     return mConnections[handle].connection;
213 }
214 
onHotplugReceived(ConnectionHandle handle,PhysicalDisplayId displayId,bool connected)215 void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
216                                   bool connected) {
217     RETURN_IF_INVALID_HANDLE(handle);
218     mConnections[handle].thread->onHotplugReceived(displayId, connected);
219 }
220 
onScreenAcquired(ConnectionHandle handle)221 void Scheduler::onScreenAcquired(ConnectionHandle handle) {
222     RETURN_IF_INVALID_HANDLE(handle);
223     mConnections[handle].thread->onScreenAcquired();
224 }
225 
onScreenReleased(ConnectionHandle handle)226 void Scheduler::onScreenReleased(ConnectionHandle handle) {
227     RETURN_IF_INVALID_HANDLE(handle);
228     mConnections[handle].thread->onScreenReleased();
229 }
230 
onPrimaryDisplayConfigChanged(ConnectionHandle handle,PhysicalDisplayId displayId,HwcConfigIndexType configId,nsecs_t vsyncPeriod)231 void Scheduler::onPrimaryDisplayConfigChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
232                                               HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
233     std::lock_guard<std::mutex> lock(mFeatureStateLock);
234     // Cache the last reported config for primary display.
235     mFeatures.cachedConfigChangedParams = {handle, displayId, configId, vsyncPeriod};
236     onNonPrimaryDisplayConfigChanged(handle, displayId, configId, vsyncPeriod);
237 }
238 
dispatchCachedReportedConfig()239 void Scheduler::dispatchCachedReportedConfig() {
240     const auto configId = *mFeatures.configId;
241     const auto vsyncPeriod =
242             mRefreshRateConfigs.getRefreshRateFromConfigId(configId).getVsyncPeriod();
243 
244     // If there is no change from cached config, there is no need to dispatch an event
245     if (configId == mFeatures.cachedConfigChangedParams->configId &&
246         vsyncPeriod == mFeatures.cachedConfigChangedParams->vsyncPeriod) {
247         return;
248     }
249 
250     mFeatures.cachedConfigChangedParams->configId = configId;
251     mFeatures.cachedConfigChangedParams->vsyncPeriod = vsyncPeriod;
252     onNonPrimaryDisplayConfigChanged(mFeatures.cachedConfigChangedParams->handle,
253                                      mFeatures.cachedConfigChangedParams->displayId,
254                                      mFeatures.cachedConfigChangedParams->configId,
255                                      mFeatures.cachedConfigChangedParams->vsyncPeriod);
256 }
257 
onNonPrimaryDisplayConfigChanged(ConnectionHandle handle,PhysicalDisplayId displayId,HwcConfigIndexType configId,nsecs_t vsyncPeriod)258 void Scheduler::onNonPrimaryDisplayConfigChanged(ConnectionHandle handle,
259                                                  PhysicalDisplayId displayId,
260                                                  HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
261     RETURN_IF_INVALID_HANDLE(handle);
262     mConnections[handle].thread->onConfigChanged(displayId, configId, vsyncPeriod);
263 }
264 
getEventThreadConnectionCount(ConnectionHandle handle)265 size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
266     RETURN_IF_INVALID_HANDLE(handle, 0);
267     return mConnections[handle].thread->getEventThreadConnectionCount();
268 }
269 
dump(ConnectionHandle handle,std::string & result) const270 void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
271     RETURN_IF_INVALID_HANDLE(handle);
272     mConnections.at(handle).thread->dump(result);
273 }
274 
setPhaseOffset(ConnectionHandle handle,nsecs_t phaseOffset)275 void Scheduler::setPhaseOffset(ConnectionHandle handle, nsecs_t phaseOffset) {
276     RETURN_IF_INVALID_HANDLE(handle);
277     mConnections[handle].thread->setPhaseOffset(phaseOffset);
278 }
279 
getDisplayStatInfo(DisplayStatInfo * stats)280 void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats) {
281     stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0, systemTime());
282     stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
283 }
284 
enableVSyncInjection(bool enable)285 Scheduler::ConnectionHandle Scheduler::enableVSyncInjection(bool enable) {
286     if (mInjectVSyncs == enable) {
287         return {};
288     }
289 
290     ALOGV("%s VSYNC injection", enable ? "Enabling" : "Disabling");
291 
292     if (!mInjectorConnectionHandle) {
293         auto vsyncSource = std::make_unique<InjectVSyncSource>();
294         mVSyncInjector = vsyncSource.get();
295 
296         auto eventThread =
297                 std::make_unique<impl::EventThread>(std::move(vsyncSource),
298                                                     impl::EventThread::InterceptVSyncsCallback());
299 
300         mInjectorConnectionHandle = createConnection(std::move(eventThread));
301     }
302 
303     mInjectVSyncs = enable;
304     return mInjectorConnectionHandle;
305 }
306 
injectVSync(nsecs_t when,nsecs_t expectedVSyncTime)307 bool Scheduler::injectVSync(nsecs_t when, nsecs_t expectedVSyncTime) {
308     if (!mInjectVSyncs || !mVSyncInjector) {
309         return false;
310     }
311 
312     mVSyncInjector->onInjectSyncEvent(when, expectedVSyncTime);
313     return true;
314 }
315 
enableHardwareVsync()316 void Scheduler::enableHardwareVsync() {
317     std::lock_guard<std::mutex> lock(mHWVsyncLock);
318     if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
319         mPrimaryDispSync->beginResync();
320         mEventControlThread->setVsyncEnabled(true);
321         mPrimaryHWVsyncEnabled = true;
322     }
323 }
324 
disableHardwareVsync(bool makeUnavailable)325 void Scheduler::disableHardwareVsync(bool makeUnavailable) {
326     std::lock_guard<std::mutex> lock(mHWVsyncLock);
327     if (mPrimaryHWVsyncEnabled) {
328         mEventControlThread->setVsyncEnabled(false);
329         mPrimaryDispSync->endResync();
330         mPrimaryHWVsyncEnabled = false;
331     }
332     if (makeUnavailable) {
333         mHWVsyncAvailable = false;
334     }
335 }
336 
resyncToHardwareVsync(bool makeAvailable,nsecs_t period)337 void Scheduler::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
338     {
339         std::lock_guard<std::mutex> lock(mHWVsyncLock);
340         if (makeAvailable) {
341             mHWVsyncAvailable = makeAvailable;
342         } else if (!mHWVsyncAvailable) {
343             // Hardware vsync is not currently available, so abort the resync
344             // attempt for now
345             return;
346         }
347     }
348 
349     if (period <= 0) {
350         return;
351     }
352 
353     setVsyncPeriod(period);
354 }
355 
resync()356 void Scheduler::resync() {
357     static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
358 
359     const nsecs_t now = systemTime();
360     const nsecs_t last = mLastResyncTime.exchange(now);
361 
362     if (now - last > kIgnoreDelay) {
363         resyncToHardwareVsync(false, mRefreshRateConfigs.getCurrentRefreshRate().getVsyncPeriod());
364     }
365 }
366 
setVsyncPeriod(nsecs_t period)367 void Scheduler::setVsyncPeriod(nsecs_t period) {
368     std::lock_guard<std::mutex> lock(mHWVsyncLock);
369     mPrimaryDispSync->setPeriod(period);
370 
371     if (!mPrimaryHWVsyncEnabled) {
372         mPrimaryDispSync->beginResync();
373         mEventControlThread->setVsyncEnabled(true);
374         mPrimaryHWVsyncEnabled = true;
375     }
376 }
377 
addResyncSample(nsecs_t timestamp,std::optional<nsecs_t> hwcVsyncPeriod,bool * periodFlushed)378 void Scheduler::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
379                                 bool* periodFlushed) {
380     bool needsHwVsync = false;
381     *periodFlushed = false;
382     { // Scope for the lock
383         std::lock_guard<std::mutex> lock(mHWVsyncLock);
384         if (mPrimaryHWVsyncEnabled) {
385             needsHwVsync =
386                     mPrimaryDispSync->addResyncSample(timestamp, hwcVsyncPeriod, periodFlushed);
387         }
388     }
389 
390     if (needsHwVsync) {
391         enableHardwareVsync();
392     } else {
393         disableHardwareVsync(false);
394     }
395 }
396 
addPresentFence(const std::shared_ptr<FenceTime> & fenceTime)397 void Scheduler::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
398     if (mPrimaryDispSync->addPresentFence(fenceTime)) {
399         enableHardwareVsync();
400     } else {
401         disableHardwareVsync(false);
402     }
403 }
404 
setIgnorePresentFences(bool ignore)405 void Scheduler::setIgnorePresentFences(bool ignore) {
406     mPrimaryDispSync->setIgnorePresentFences(ignore);
407 }
408 
getDispSyncExpectedPresentTime(nsecs_t now)409 nsecs_t Scheduler::getDispSyncExpectedPresentTime(nsecs_t now) {
410     return mPrimaryDispSync->expectedPresentTime(now);
411 }
412 
registerLayer(Layer * layer)413 void Scheduler::registerLayer(Layer* layer) {
414     if (!mLayerHistory) return;
415 
416     const auto minFps = mRefreshRateConfigs.getMinRefreshRate().getFps();
417     const auto maxFps = mRefreshRateConfigs.getMaxRefreshRate().getFps();
418 
419     if (layer->getWindowType() == InputWindowInfo::TYPE_STATUS_BAR) {
420         mLayerHistory->registerLayer(layer, minFps, maxFps,
421                                      scheduler::LayerHistory::LayerVoteType::NoVote);
422     } else if (!mUseContentDetection) {
423         // If the content detection feature is off, all layers are registered at Max. We still keep
424         // the layer history, since we use it for other features (like Frame Rate API), so layers
425         // still need to be registered.
426         mLayerHistory->registerLayer(layer, minFps, maxFps,
427                                      scheduler::LayerHistory::LayerVoteType::Max);
428     } else if (!mUseContentDetectionV2) {
429         // In V1 of content detection, all layers are registered as Heuristic (unless it's
430         // wallpaper).
431         const auto highFps =
432                 layer->getWindowType() == InputWindowInfo::TYPE_WALLPAPER ? minFps : maxFps;
433 
434         mLayerHistory->registerLayer(layer, minFps, highFps,
435                                      scheduler::LayerHistory::LayerVoteType::Heuristic);
436     } else {
437         if (layer->getWindowType() == InputWindowInfo::TYPE_WALLPAPER) {
438             // Running Wallpaper at Min is considered as part of content detection.
439             mLayerHistory->registerLayer(layer, minFps, maxFps,
440                                          scheduler::LayerHistory::LayerVoteType::Min);
441         } else {
442             mLayerHistory->registerLayer(layer, minFps, maxFps,
443                                          scheduler::LayerHistory::LayerVoteType::Heuristic);
444         }
445     }
446 }
447 
recordLayerHistory(Layer * layer,nsecs_t presentTime,LayerHistory::LayerUpdateType updateType)448 void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime,
449                                    LayerHistory::LayerUpdateType updateType) {
450     if (mLayerHistory) {
451         mLayerHistory->record(layer, presentTime, systemTime(), updateType);
452     }
453 }
454 
setConfigChangePending(bool pending)455 void Scheduler::setConfigChangePending(bool pending) {
456     if (mLayerHistory) {
457         mLayerHistory->setConfigChangePending(pending);
458     }
459 }
460 
chooseRefreshRateForContent()461 void Scheduler::chooseRefreshRateForContent() {
462     if (!mLayerHistory) return;
463 
464     ATRACE_CALL();
465 
466     scheduler::LayerHistory::Summary summary = mLayerHistory->summarize(systemTime());
467     HwcConfigIndexType newConfigId;
468     {
469         std::lock_guard<std::mutex> lock(mFeatureStateLock);
470         if (mFeatures.contentRequirements == summary) {
471             return;
472         }
473         mFeatures.contentRequirements = summary;
474         mFeatures.contentDetectionV1 =
475                 !summary.empty() ? ContentDetectionState::On : ContentDetectionState::Off;
476 
477         scheduler::RefreshRateConfigs::GlobalSignals consideredSignals;
478         newConfigId = calculateRefreshRateConfigIndexType(&consideredSignals);
479         if (mFeatures.configId == newConfigId) {
480             // We don't need to change the config, but we might need to send an event
481             // about a config change, since it was suppressed due to a previous idleConsidered
482             if (!consideredSignals.idle) {
483                 dispatchCachedReportedConfig();
484             }
485             return;
486         }
487         mFeatures.configId = newConfigId;
488         auto& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
489         mSchedulerCallback.changeRefreshRate(newRefreshRate,
490                                              consideredSignals.idle ? ConfigEvent::None
491                                                                     : ConfigEvent::Changed);
492     }
493 }
494 
resetIdleTimer()495 void Scheduler::resetIdleTimer() {
496     if (mIdleTimer) {
497         mIdleTimer->reset();
498     }
499 }
500 
notifyTouchEvent()501 void Scheduler::notifyTouchEvent() {
502     if (!mTouchTimer) return;
503 
504     // Touch event will boost the refresh rate to performance.
505     // Clear Layer History to get fresh FPS detection.
506     // NOTE: Instead of checking all the layers, we should be checking the layer
507     // that is currently on top. b/142507166 will give us this capability.
508     std::lock_guard<std::mutex> lock(mFeatureStateLock);
509     if (mLayerHistory) {
510         // Layer History will be cleared based on RefreshRateConfigs::getBestRefreshRate
511 
512         mTouchTimer->reset();
513 
514         if (mSupportKernelTimer && mIdleTimer) {
515             mIdleTimer->reset();
516         }
517     }
518 }
519 
setDisplayPowerState(bool normal)520 void Scheduler::setDisplayPowerState(bool normal) {
521     {
522         std::lock_guard<std::mutex> lock(mFeatureStateLock);
523         mFeatures.isDisplayPowerStateNormal = normal;
524     }
525 
526     if (mDisplayPowerTimer) {
527         mDisplayPowerTimer->reset();
528     }
529 
530     // Display Power event will boost the refresh rate to performance.
531     // Clear Layer History to get fresh FPS detection
532     if (mLayerHistory) {
533         mLayerHistory->clear();
534     }
535 }
536 
kernelIdleTimerCallback(TimerState state)537 void Scheduler::kernelIdleTimerCallback(TimerState state) {
538     ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
539 
540     // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
541     // magic number
542     const auto& refreshRate = mRefreshRateConfigs.getCurrentRefreshRate();
543     constexpr float FPS_THRESHOLD_FOR_KERNEL_TIMER = 65.0f;
544     if (state == TimerState::Reset && refreshRate.getFps() > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
545         // If we're not in performance mode then the kernel timer shouldn't do
546         // anything, as the refresh rate during DPU power collapse will be the
547         // same.
548         resyncToHardwareVsync(true /* makeAvailable */, refreshRate.getVsyncPeriod());
549     } else if (state == TimerState::Expired &&
550                refreshRate.getFps() <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
551         // Disable HW VSYNC if the timer expired, as we don't need it enabled if
552         // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
553         // need to update the DispSync model anyway.
554         disableHardwareVsync(false /* makeUnavailable */);
555     }
556 
557     mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
558 }
559 
idleTimerCallback(TimerState state)560 void Scheduler::idleTimerCallback(TimerState state) {
561     handleTimerStateChanged(&mFeatures.idleTimer, state);
562     ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
563 }
564 
touchTimerCallback(TimerState state)565 void Scheduler::touchTimerCallback(TimerState state) {
566     const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
567     if (handleTimerStateChanged(&mFeatures.touch, touch)) {
568         mLayerHistory->clear();
569     }
570     ATRACE_INT("TouchState", static_cast<int>(touch));
571 }
572 
displayPowerTimerCallback(TimerState state)573 void Scheduler::displayPowerTimerCallback(TimerState state) {
574     handleTimerStateChanged(&mFeatures.displayPowerTimer, state);
575     ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
576 }
577 
dump(std::string & result) const578 void Scheduler::dump(std::string& result) const {
579     using base::StringAppendF;
580     const char* const states[] = {"off", "on"};
581 
582     StringAppendF(&result, "+  Idle timer: %s\n",
583                   mIdleTimer ? mIdleTimer->dump().c_str() : states[0]);
584     StringAppendF(&result, "+  Touch timer: %s\n",
585                   mTouchTimer ? mTouchTimer->dump().c_str() : states[0]);
586     StringAppendF(&result, "+  Use content detection: %s\n\n",
587                   sysprop::use_content_detection_for_refresh_rate(false) ? "on" : "off");
588 }
589 
590 template <class T>
handleTimerStateChanged(T * currentState,T newState)591 bool Scheduler::handleTimerStateChanged(T* currentState, T newState) {
592     HwcConfigIndexType newConfigId;
593     scheduler::RefreshRateConfigs::GlobalSignals consideredSignals;
594     {
595         std::lock_guard<std::mutex> lock(mFeatureStateLock);
596         if (*currentState == newState) {
597             return false;
598         }
599         *currentState = newState;
600         newConfigId = calculateRefreshRateConfigIndexType(&consideredSignals);
601         if (mFeatures.configId == newConfigId) {
602             // We don't need to change the config, but we might need to send an event
603             // about a config change, since it was suppressed due to a previous idleConsidered
604             if (!consideredSignals.idle) {
605                 dispatchCachedReportedConfig();
606             }
607             return consideredSignals.touch;
608         }
609         mFeatures.configId = newConfigId;
610     }
611     const RefreshRate& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
612     mSchedulerCallback.changeRefreshRate(newRefreshRate,
613                                          consideredSignals.idle ? ConfigEvent::None
614                                                                 : ConfigEvent::Changed);
615     return consideredSignals.touch;
616 }
617 
calculateRefreshRateConfigIndexType(scheduler::RefreshRateConfigs::GlobalSignals * consideredSignals)618 HwcConfigIndexType Scheduler::calculateRefreshRateConfigIndexType(
619         scheduler::RefreshRateConfigs::GlobalSignals* consideredSignals) {
620     ATRACE_CALL();
621     if (consideredSignals) *consideredSignals = {};
622 
623     // If Display Power is not in normal operation we want to be in performance mode. When coming
624     // back to normal mode, a grace period is given with DisplayPowerTimer.
625     if (mDisplayPowerTimer &&
626         (!mFeatures.isDisplayPowerStateNormal ||
627          mFeatures.displayPowerTimer == TimerState::Reset)) {
628         return mRefreshRateConfigs.getMaxRefreshRateByPolicy().getConfigId();
629     }
630 
631     const bool touchActive = mTouchTimer && mFeatures.touch == TouchState::Active;
632     const bool idle = mIdleTimer && mFeatures.idleTimer == TimerState::Expired;
633 
634     if (!mUseContentDetectionV2) {
635         // As long as touch is active we want to be in performance mode.
636         if (touchActive) {
637             return mRefreshRateConfigs.getMaxRefreshRateByPolicy().getConfigId();
638         }
639 
640         // If timer has expired as it means there is no new content on the screen.
641         if (idle) {
642             if (consideredSignals) consideredSignals->idle = true;
643             return mRefreshRateConfigs.getMinRefreshRateByPolicy().getConfigId();
644         }
645 
646         // If content detection is off we choose performance as we don't know the content fps.
647         if (mFeatures.contentDetectionV1 == ContentDetectionState::Off) {
648             // NOTE: V1 always calls this, but this is not a default behavior for V2.
649             return mRefreshRateConfigs.getMaxRefreshRateByPolicy().getConfigId();
650         }
651 
652         // Content detection is on, find the appropriate refresh rate with minimal error
653         return mRefreshRateConfigs.getRefreshRateForContent(mFeatures.contentRequirements)
654                 .getConfigId();
655     }
656 
657     return mRefreshRateConfigs
658             .getBestRefreshRate(mFeatures.contentRequirements, {.touch = touchActive, .idle = idle},
659                                 consideredSignals)
660             .getConfigId();
661 }
662 
getPreferredConfigId()663 std::optional<HwcConfigIndexType> Scheduler::getPreferredConfigId() {
664     std::lock_guard<std::mutex> lock(mFeatureStateLock);
665     // Make sure that the default config ID is first updated, before returned.
666     if (mFeatures.configId.has_value()) {
667         mFeatures.configId = calculateRefreshRateConfigIndexType();
668     }
669     return mFeatures.configId;
670 }
671 
onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline & timeline)672 void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
673     if (timeline.refreshRequired) {
674         mSchedulerCallback.repaintEverythingForHWC();
675     }
676 
677     std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
678     mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
679 
680     const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
681     if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
682         mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
683     }
684 }
685 
onDisplayRefreshed(nsecs_t timestamp)686 void Scheduler::onDisplayRefreshed(nsecs_t timestamp) {
687     bool callRepaint = false;
688     {
689         std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
690         if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
691             if (mLastVsyncPeriodChangeTimeline->refreshTimeNanos < timestamp) {
692                 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
693             } else {
694                 // We need to send another refresh as refreshTimeNanos is still in the future
695                 callRepaint = true;
696             }
697         }
698     }
699 
700     if (callRepaint) {
701         mSchedulerCallback.repaintEverythingForHWC();
702     }
703 }
704 
onPrimaryDisplayAreaChanged(uint32_t displayArea)705 void Scheduler::onPrimaryDisplayAreaChanged(uint32_t displayArea) {
706     if (mLayerHistory) {
707         mLayerHistory->setDisplayArea(displayArea);
708     }
709 }
710 
711 } // namespace android
712