blob: 3e12db61e7c7b9c0fcce7891d418585dfbe4f8ae [file] [log] [blame]
Ana Krulec98b5b242018-08-10 15:03:23 -07001/*
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
Dominik Laskowski98041832019-08-01 18:35:59 -070017#undef LOG_TAG
18#define LOG_TAG "Scheduler"
Ana Krulec7ab56032018-11-02 20:51:06 +010019#define ATRACE_TAG ATRACE_TAG_GRAPHICS
20
Ana Krulec98b5b242018-08-10 15:03:23 -070021#include "Scheduler.h"
22
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070023#include <android-base/properties.h>
Dominik Laskowski49cea512019-11-12 14:13:23 -080024#include <android-base/stringprintf.h>
Ana Krulece588e312018-09-18 12:32:24 -070025#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
26#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Ana Krulece588e312018-09-18 12:32:24 -070027#include <configstore/Utils.h>
Dominik Laskowski03cfce82022-11-02 12:13:29 -040028#include <ftl/enum.h>
ramindania556d072022-06-14 23:25:11 +000029#include <ftl/fake_guard.h>
Dominik Laskowski01602522022-10-07 19:02:28 -040030#include <ftl/small_map.h>
Ady Abraham9243bba2023-02-10 15:31:14 -080031#include <gui/TraceUtils.h>
chaviw3277faf2021-05-19 16:45:23 -050032#include <gui/WindowInfo.h>
Ana Krulecfefd6ae2019-02-13 17:53:08 -080033#include <system/window.h>
Ana Krulec3084c052018-11-21 20:27:17 +010034#include <utils/Timers.h>
Ana Krulec98b5b242018-08-10 15:03:23 -070035
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070036#include <FrameTimeline/FrameTimeline.h>
Dominik Laskowski63f12792023-01-21 16:58:22 -050037#include <scheduler/interface/ICompositor.h>
38
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -070039#include <algorithm>
40#include <cinttypes>
41#include <cstdint>
42#include <functional>
43#include <memory>
44#include <numeric>
45
46#include "../Layer.h"
Dominik Laskowski01602522022-10-07 19:02:28 -040047#include "Display/DisplayMap.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070048#include "EventThread.h"
Andy Yu2ae6b6b2021-11-18 14:51:06 -080049#include "FrameRateOverrideMappings.h"
Rachel Lee2248f522023-01-27 16:45:23 -080050#include "FrontEnd/LayerHandle.h"
Ana Krulecf2c006d2019-06-21 15:37:07 -070051#include "OneShotTimer.h"
Sundong Ahnd5e08f62018-12-12 20:27:28 +090052#include "SurfaceFlingerProperties.h"
Kevin DuBois00287382019-11-19 15:11:55 -080053#include "VSyncPredictor.h"
54#include "VSyncReactor.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070055
Dominik Laskowski98041832019-08-01 18:35:59 -070056#define RETURN_IF_INVALID_HANDLE(handle, ...) \
57 do { \
58 if (mConnections.count(handle) == 0) { \
59 ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
60 return __VA_ARGS__; \
61 } \
62 } while (false)
63
Dominik Laskowski068173d2021-08-11 17:22:59 -070064namespace android::scheduler {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070065
Dominik Laskowski1c99a002023-01-20 17:10:36 -050066Scheduler::Scheduler(ICompositor& compositor, ISchedulerCallback& callback, FeatureFlags features,
67 sp<VsyncModulator> modulatorPtr)
68 : impl::MessageQueue(compositor),
69 mFeatures(features),
70 mVsyncModulator(std::move(modulatorPtr)),
71 mSchedulerCallback(callback) {}
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070072
Dominik Laskowski83bd7712022-01-07 14:30:53 -080073Scheduler::~Scheduler() {
Ady Abraham011f8ba2022-11-22 15:09:07 -080074 // MessageQueue depends on VsyncSchedule, so first destroy it.
75 // Otherwise, MessageQueue will get destroyed after Scheduler's dtor,
76 // which will cause a use-after-free issue.
77 Impl::destroyVsync();
78
Dominik Laskowski83bd7712022-01-07 14:30:53 -080079 // Stop timers and wait for their threads to exit.
80 mDisplayPowerTimer.reset();
81 mTouchTimer.reset();
82
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040083 // Stop idle timer and clear callbacks, as the RefreshRateSelector may outlive the Scheduler.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -050084 demotePacesetterDisplay();
Dominik Laskowski83bd7712022-01-07 14:30:53 -080085}
86
Dominik Laskowski9c93d602021-10-07 19:38:26 -070087void Scheduler::startTimers() {
Dominik Laskowski98041832019-08-01 18:35:59 -070088 using namespace sysprop;
Dominik Laskowski068173d2021-08-11 17:22:59 -070089 using namespace std::string_literals;
Ady Abraham8532d012019-05-08 14:50:56 -070090
Dominik Laskowski98041832019-08-01 18:35:59 -070091 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -070092 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -070093 mTouchTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080094 "TouchTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -070095 [this] { touchTimerCallback(TimerState::Reset); },
96 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -070097 mTouchTimer->start();
98 }
Ady Abraham6fe2c172019-07-12 12:37:57 -070099
Dominik Laskowski98041832019-08-01 18:35:59 -0700100 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
101 mDisplayPowerTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800102 "DisplayPowerTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700103 [this] { displayPowerTimerCallback(TimerState::Reset); },
104 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700105 mDisplayPowerTimer->start();
106 }
Ana Krulece588e312018-09-18 12:32:24 -0700107}
108
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500109void Scheduler::setPacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt) {
110 demotePacesetterDisplay();
Dominik Laskowski59db9562022-10-27 16:18:53 -0400111
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500112 promotePacesetterDisplay(pacesetterIdOpt);
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800113}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700114
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400115void Scheduler::registerDisplay(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500116 registerDisplayInternal(displayId, std::move(selectorPtr),
117 std::make_shared<VsyncSchedule>(displayId, mFeatures));
118}
119
120void Scheduler::registerDisplayInternal(PhysicalDisplayId displayId,
121 RefreshRateSelectorPtr selectorPtr,
122 std::shared_ptr<VsyncSchedule> vsyncSchedule) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500123 demotePacesetterDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400124
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400125 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
126 {
127 std::scoped_lock lock(mDisplayLock);
128 mRefreshRateSelectors.emplace_or_replace(displayId, std::move(selectorPtr));
129 mVsyncSchedules.emplace_or_replace(displayId, std::move(vsyncSchedule));
Dominik Laskowski596a2562022-10-28 11:26:12 -0400130
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400131 pacesetterVsyncSchedule = promotePacesetterDisplayLocked();
132 }
133 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski01602522022-10-07 19:02:28 -0400134}
135
136void Scheduler::unregisterDisplay(PhysicalDisplayId displayId) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500137 demotePacesetterDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400138
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400139 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
140 {
141 std::scoped_lock lock(mDisplayLock);
142 mRefreshRateSelectors.erase(displayId);
143 mVsyncSchedules.erase(displayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400144
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400145 // Do not allow removing the final display. Code in the scheduler expects
146 // there to be at least one display. (This may be relaxed in the future with
147 // headless virtual display.)
148 LOG_ALWAYS_FATAL_IF(mRefreshRateSelectors.empty(), "Cannot unregister all displays!");
Leon Scroggins IIIda21f422023-01-30 20:17:56 -0500149
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400150 pacesetterVsyncSchedule = promotePacesetterDisplayLocked();
151 }
152 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski01602522022-10-07 19:02:28 -0400153}
154
Dominik Laskowski756b7892021-08-04 12:53:59 -0700155void Scheduler::run() {
156 while (true) {
157 waitMessage();
158 }
159}
160
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700161void Scheduler::onFrameSignal(ICompositor& compositor, VsyncId vsyncId,
162 TimePoint expectedVsyncTime) {
163 const TimePoint frameTime = SchedulerClock::now();
164
165 if (!compositor.commit(frameTime, vsyncId, expectedVsyncTime)) {
166 return;
167 }
168
169 compositor.composite(frameTime, vsyncId);
170 compositor.sample();
171}
172
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500173std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800174 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500175 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800176 return mFrameRateOverrideMappings
177 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800178}
179
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500180bool Scheduler::isVsyncValid(TimePoint expectedVsyncTimestamp, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800181 const auto frameRate = getFrameRateOverride(uid);
182 if (!frameRate.has_value()) {
183 return true;
184 }
185
Ady Abraham9243bba2023-02-10 15:31:14 -0800186 ATRACE_FORMAT("%s uid: %d frameRate: %s", __func__, uid, to_string(*frameRate).c_str());
Leon Scroggins III67388622023-02-06 20:36:20 -0500187 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTimestamp.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700188}
189
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500190bool Scheduler::isVsyncInPhase(TimePoint timePoint, const Fps frameRate) const {
Leon Scroggins III67388622023-02-06 20:36:20 -0500191 return getVsyncSchedule()->getTracker().isVSyncInPhase(timePoint.ns(), frameRate);
Huihong Luo1768cb02022-10-11 11:10:34 -0700192}
193
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500194impl::EventThread::ThrottleVsyncCallback Scheduler::makeThrottleVsyncCallback() const {
195 return [this](nsecs_t expectedVsyncTimestamp, uid_t uid) {
196 return !isVsyncValid(TimePoint::fromNs(expectedVsyncTimestamp), uid);
197 };
198}
Ady Abraham64c2fc02020-12-29 12:07:50 -0800199
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500200impl::EventThread::GetVsyncPeriodFunction Scheduler::makeGetVsyncPeriodFunction() const {
201 return [this](uid_t uid) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500202 const Fps refreshRate = pacesetterSelectorPtr()->getActiveMode().fps;
Leon Scroggins III67388622023-02-06 20:36:20 -0500203 const nsecs_t currentPeriod =
204 getVsyncSchedule()->period().ns() ?: refreshRate.getPeriodNsecs();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800205
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500206 const auto frameRate = getFrameRateOverride(uid);
207 if (!frameRate.has_value()) {
208 return currentPeriod;
209 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100210
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500211 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
212 if (divisor <= 1) {
213 return currentPeriod;
214 }
215 return currentPeriod * divisor;
216 };
Jorim Jaggic0086af2021-02-12 18:18:11 +0100217}
218
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500219ConnectionHandle Scheduler::createEventThread(Cycle cycle,
220 frametimeline::TokenManager* tokenManager,
221 std::chrono::nanoseconds workDuration,
222 std::chrono::nanoseconds readyDuration) {
223 auto eventThread = std::make_unique<impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
Leon Scroggins III67388622023-02-06 20:36:20 -0500224 getVsyncSchedule(), tokenManager,
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500225 makeThrottleVsyncCallback(),
226 makeGetVsyncPeriodFunction(),
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500227 workDuration, readyDuration);
228
229 auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
230 handle = createConnection(std::move(eventThread));
231 return handle;
Dominik Laskowski98041832019-08-01 18:35:59 -0700232}
Ana Krulec98b5b242018-08-10 15:03:23 -0700233
Dominik Laskowski068173d2021-08-11 17:22:59 -0700234ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700235 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
236 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800237
Ady Abraham62f216c2020-10-13 19:07:23 -0700238 auto connection = createConnectionInternal(eventThread.get());
Dominik Laskowski98041832019-08-01 18:35:59 -0700239
Ana Krulec6ddd2612020-09-24 13:06:33 -0700240 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700241 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
242 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700243}
244
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700245sp<EventThreadConnection> Scheduler::createConnectionInternal(
Rachel Lee2248f522023-01-27 16:45:23 -0800246 EventThread* eventThread, EventRegistrationFlags eventRegistration,
247 const sp<IBinder>& layerHandle) {
248 int32_t layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
249 auto connection = eventThread->createEventConnection([&] { resync(); }, eventRegistration);
250 mLayerHistory.attachChoreographer(layerId, connection);
251 return connection;
Ana Krulec0c8cd522018-08-31 12:27:28 -0700252}
253
Ana Krulec98b5b242018-08-10 15:03:23 -0700254sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Rachel Lee2248f522023-01-27 16:45:23 -0800255 ConnectionHandle handle, EventRegistrationFlags eventRegistration,
256 const sp<IBinder>& layerHandle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700257 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700258 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Rachel Lee2248f522023-01-27 16:45:23 -0800259 return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration,
260 layerHandle);
Ana Krulec98b5b242018-08-10 15:03:23 -0700261}
262
Dominik Laskowski98041832019-08-01 18:35:59 -0700263sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700264 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700265 RETURN_IF_INVALID_HANDLE(handle, nullptr);
266 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700267}
268
Dominik Laskowski98041832019-08-01 18:35:59 -0700269void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
270 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700271 android::EventThread* thread;
272 {
273 std::lock_guard<std::mutex> lock(mConnectionsLock);
274 RETURN_IF_INVALID_HANDLE(handle);
275 thread = mConnections[handle].thread.get();
276 }
277
278 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700279}
280
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500281void Scheduler::enableSyntheticVsync(bool enable) {
282 // TODO(b/241285945): Remove connection handles.
283 const ConnectionHandle handle = mAppConnectionHandle;
Ana Krulec6ddd2612020-09-24 13:06:33 -0700284 android::EventThread* thread;
285 {
286 std::lock_guard<std::mutex> lock(mConnectionsLock);
287 RETURN_IF_INVALID_HANDLE(handle);
288 thread = mConnections[handle].thread.get();
289 }
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500290 thread->enableSyntheticVsync(enable);
Ana Krulec98b5b242018-08-10 15:03:23 -0700291}
292
Ady Abraham62a0be22020-12-08 16:54:10 -0800293void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800294 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500295 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800296
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800297 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800298 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800299
Ady Abraham62f216c2020-10-13 19:07:23 -0700300 android::EventThread* thread;
301 {
Ady Abraham62a0be22020-12-08 16:54:10 -0800302 std::lock_guard lock(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700303 RETURN_IF_INVALID_HANDLE(handle);
304 thread = mConnections[handle].thread.get();
305 }
306 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
307}
308
Ady Abrahamace3d052022-11-17 16:25:05 -0800309void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800310 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700311 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100312 // Cache the last reported modes for primary display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700313 mPolicy.cachedModeChangedParams = {handle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700314
315 // Invalidate content based refresh rate selection so it could be calculated
316 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700317 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800318 }
Ady Abraham690f4612021-07-01 23:24:03 -0700319 onNonPrimaryDisplayModeChanged(handle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700320}
321
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100322void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700323 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800324 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100325 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700326 return;
327 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700328 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100329 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700330 return;
331 }
332
Ady Abrahamd1591702021-07-27 16:27:56 -0700333 // If the mode is not the current mode, this means that a
334 // mode change is in progress. In that case we shouldn't dispatch an event
335 // as it will be dispatched when the current mode changes.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500336 if (pacesetterSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700337 return;
338 }
339
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100340 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800341 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700342 return;
343 }
344
Ady Abrahamace3d052022-11-17 16:25:05 -0800345 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700346 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
347 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700348}
349
Ady Abrahamace3d052022-11-17 16:25:05 -0800350void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700351 android::EventThread* thread;
352 {
353 std::lock_guard<std::mutex> lock(mConnectionsLock);
354 RETURN_IF_INVALID_HANDLE(handle);
355 thread = mConnections[handle].thread.get();
356 }
Ady Abraham67434eb2022-12-01 17:48:12 -0800357 thread->onModeChanged(mode);
Ady Abraham447052e2019-02-13 16:07:27 -0800358}
359
Alec Mouri717bcb62020-02-10 17:07:19 -0800360size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700361 std::lock_guard<std::mutex> lock(mConnectionsLock);
Alec Mouri717bcb62020-02-10 17:07:19 -0800362 RETURN_IF_INVALID_HANDLE(handle, 0);
363 return mConnections[handle].thread->getEventThreadConnectionCount();
364}
365
Dominik Laskowski98041832019-08-01 18:35:59 -0700366void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700367 android::EventThread* thread;
368 {
369 std::lock_guard<std::mutex> lock(mConnectionsLock);
370 RETURN_IF_INVALID_HANDLE(handle);
371 thread = mConnections.at(handle).thread.get();
372 }
373 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700374}
375
Ady Abraham9c53ee72020-07-22 21:16:18 -0700376void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
377 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700378 android::EventThread* thread;
379 {
380 std::lock_guard<std::mutex> lock(mConnectionsLock);
381 RETURN_IF_INVALID_HANDLE(handle);
382 thread = mConnections[handle].thread.get();
383 }
384 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700385}
Ana Krulece588e312018-09-18 12:32:24 -0700386
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500387void Scheduler::setVsyncConfigSet(const VsyncConfigSet& configs, Period vsyncPeriod) {
388 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(configs), vsyncPeriod);
389}
390
391void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
392 setDuration(mAppConnectionHandle,
393 /* workDuration */ config.appWorkDuration,
394 /* readyDuration */ config.sfWorkDuration);
395 setDuration(mSfConnectionHandle,
396 /* workDuration */ vsyncPeriod,
397 /* readyDuration */ config.sfWorkDuration);
398 setDuration(config.sfWorkDuration);
399}
400
Leon Scroggins III67388622023-02-06 20:36:20 -0500401void Scheduler::enableHardwareVsync(PhysicalDisplayId id) {
402 auto schedule = getVsyncSchedule(id);
403 schedule->enableHardwareVsync(mSchedulerCallback);
Ana Krulece588e312018-09-18 12:32:24 -0700404}
405
Leon Scroggins III67388622023-02-06 20:36:20 -0500406void Scheduler::disableHardwareVsync(PhysicalDisplayId id, bool disallow) {
407 auto schedule = getVsyncSchedule(id);
408 schedule->disableHardwareVsync(mSchedulerCallback, disallow);
Ana Krulece588e312018-09-18 12:32:24 -0700409}
410
Leon Scroggins III67388622023-02-06 20:36:20 -0500411void Scheduler::resyncAllToHardwareVsync(bool allowToEnable) {
Rachel Leea5be3282023-03-08 20:15:54 -0800412 ATRACE_CALL();
Leon Scroggins III67388622023-02-06 20:36:20 -0500413 std::scoped_lock lock(mDisplayLock);
414 ftl::FakeGuard guard(kMainThreadContext);
415
416 for (const auto& [id, _] : mRefreshRateSelectors) {
417 resyncToHardwareVsyncLocked(id, allowToEnable);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500418 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500419}
420
Leon Scroggins III67388622023-02-06 20:36:20 -0500421void Scheduler::resyncToHardwareVsyncLocked(PhysicalDisplayId id, bool allowToEnable,
422 std::optional<Fps> refreshRate) {
423 auto schedule = getVsyncScheduleLocked(id);
424 if (schedule->isHardwareVsyncAllowed(allowToEnable)) {
425 if (!refreshRate) {
426 auto selectorPtr = mRefreshRateSelectors.get(id);
427 LOG_ALWAYS_FATAL_IF(!selectorPtr);
428 refreshRate = selectorPtr->get()->getActiveMode().modePtr->getFps();
429 }
430 if (refreshRate->isValid()) {
431 schedule->startPeriodTransition(mSchedulerCallback, refreshRate->getPeriod(),
432 false /* force */);
433 }
434 }
435}
436
437void Scheduler::setRenderRate(PhysicalDisplayId id, Fps renderFrameRate) {
438 std::scoped_lock lock(mDisplayLock);
439 ftl::FakeGuard guard(kMainThreadContext);
440
441 auto selectorPtr = mRefreshRateSelectors.get(id);
442 LOG_ALWAYS_FATAL_IF(!selectorPtr);
443 const auto mode = selectorPtr->get()->getActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -0800444
445 using fps_approx_ops::operator!=;
446 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
Leon Scroggins III67388622023-02-06 20:36:20 -0500447 "Mismatch in render frame rates. Selector: %s, Scheduler: %s, Display: "
448 "%" PRIu64,
449 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str(), id.value);
Ady Abrahamace3d052022-11-17 16:25:05 -0800450
451 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
452 to_string(mode.modePtr->getFps()).c_str());
453
Leon Scroggins III67388622023-02-06 20:36:20 -0500454 getVsyncScheduleLocked(id)->getTracker().setRenderRate(renderFrameRate);
Ady Abrahamace3d052022-11-17 16:25:05 -0800455}
456
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700457void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700458 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800459
460 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700461 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800462
463 if (now - last > kIgnoreDelay) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500464 resyncAllToHardwareVsync(false /* allowToEnable */);
Ana Krulecc2870422019-01-29 19:00:58 -0800465 }
466}
467
Leon Scroggins III67388622023-02-06 20:36:20 -0500468bool Scheduler::addResyncSample(PhysicalDisplayId id, nsecs_t timestamp,
469 std::optional<nsecs_t> hwcVsyncPeriodIn) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500470 const auto hwcVsyncPeriod = ftl::Optional(hwcVsyncPeriodIn).transform([](nsecs_t nanos) {
471 return Period::fromNs(nanos);
472 });
Leon Scroggins III67388622023-02-06 20:36:20 -0500473 return getVsyncSchedule(id)->addResyncSample(mSchedulerCallback, TimePoint::fromNs(timestamp),
474 hwcVsyncPeriod);
Ana Krulece588e312018-09-18 12:32:24 -0700475}
476
Leon Scroggins III67388622023-02-06 20:36:20 -0500477void Scheduler::addPresentFence(PhysicalDisplayId id, std::shared_ptr<FenceTime> fence) {
478 auto schedule = getVsyncSchedule(id);
479 const bool needMoreSignals = schedule->getController().addPresentFence(std::move(fence));
480 if (needMoreSignals) {
481 schedule->enableHardwareVsync(mSchedulerCallback);
Ana Krulece588e312018-09-18 12:32:24 -0700482 } else {
Leon Scroggins III67388622023-02-06 20:36:20 -0500483 schedule->disableHardwareVsync(mSchedulerCallback, false /* disallow */);
Ana Krulece588e312018-09-18 12:32:24 -0700484 }
485}
486
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700487void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200488 // If the content detection feature is off, we still keep the layer history,
489 // since we use it for other features (like Frame Rate API), so layers
490 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000491 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700492}
493
Ady Abrahambdda8f02021-04-01 16:06:11 -0700494void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700495 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700496}
497
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000498void Scheduler::recordLayerHistory(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
Ady Abraham5def7332020-05-29 16:13:47 -0700499 LayerHistory::LayerUpdateType updateType) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500500 if (pacesetterSelectorPtr()->canSwitch()) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000501 mLayerHistory.record(id, layerProps, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800502 }
Ana Krulec3084c052018-11-21 20:27:17 +0100503}
504
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100505void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700506 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700507}
508
Andy Labrada096227e2022-06-15 16:58:11 +0000509void Scheduler::setDefaultFrameRateCompatibility(Layer* layer) {
510 mLayerHistory.setDefaultFrameRateCompatibility(layer,
511 mFeatures.test(Feature::kContentDetection));
512}
513
Dominik Laskowski49cea512019-11-12 14:13:23 -0800514void Scheduler::chooseRefreshRateForContent() {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500515 const auto selectorPtr = pacesetterSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400516 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800517
Ady Abraham8a82ba62020-01-17 12:43:17 -0800518 ATRACE_CALL();
519
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400520 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800521 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abrahama1a49af2019-02-07 14:36:55 -0800522}
523
Ana Krulecfb772822018-11-30 10:44:07 +0100524void Scheduler::resetIdleTimer() {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500525 pacesetterSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800526}
527
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700528void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700529 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800530 mTouchTimer->reset();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500531 pacesetterSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800532 }
Ady Abraham8532d012019-05-08 14:50:56 -0700533}
534
Leon Scroggins III67388622023-02-06 20:36:20 -0500535void Scheduler::setDisplayPowerMode(PhysicalDisplayId id, hal::PowerMode powerMode) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500536 const bool isPacesetter = [this, id]() REQUIRES(kMainThreadContext) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500537 ftl::FakeGuard guard(mDisplayLock);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500538 return id == mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500539 }();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500540 if (isPacesetter) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500541 // TODO (b/255657128): This needs to be handled per display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700542 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700543 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700544 }
Leon Scroggins III67388622023-02-06 20:36:20 -0500545 {
546 std::scoped_lock lock(mDisplayLock);
547 auto vsyncSchedule = getVsyncScheduleLocked(id);
548 vsyncSchedule->getController().setDisplayPowerMode(powerMode);
549 }
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500550 if (!isPacesetter) return;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700551
552 if (mDisplayPowerTimer) {
553 mDisplayPowerTimer->reset();
554 }
555
556 // Display Power event will boost the refresh rate to performance.
557 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700558 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700559}
560
Leon Scroggins III67388622023-02-06 20:36:20 -0500561std::shared_ptr<const VsyncSchedule> Scheduler::getVsyncSchedule(
562 std::optional<PhysicalDisplayId> idOpt) const {
563 std::scoped_lock lock(mDisplayLock);
564 return getVsyncScheduleLocked(idOpt);
565}
566
567std::shared_ptr<const VsyncSchedule> Scheduler::getVsyncScheduleLocked(
568 std::optional<PhysicalDisplayId> idOpt) const {
569 ftl::FakeGuard guard(kMainThreadContext);
570 if (!idOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500571 LOG_ALWAYS_FATAL_IF(!mPacesetterDisplayId, "Missing a pacesetter!");
572 idOpt = mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500573 }
574 auto scheduleOpt = mVsyncSchedules.get(*idOpt);
575 LOG_ALWAYS_FATAL_IF(!scheduleOpt);
576 return std::const_pointer_cast<const VsyncSchedule>(scheduleOpt->get());
577}
578
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700579void Scheduler::kernelIdleTimerCallback(TimerState state) {
580 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100581
Ady Abraham2139f732019-11-13 18:56:40 -0800582 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
583 // magic number
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500584 const Fps refreshRate = pacesetterSelectorPtr()->getActiveMode().modePtr->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700585
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700586 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
587 using namespace fps_approx_ops;
588
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800589 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700590 // If we're not in performance mode then the kernel timer shouldn't do
591 // anything, as the refresh rate during DPU power collapse will be the
592 // same.
Leon Scroggins III67388622023-02-06 20:36:20 -0500593 resyncAllToHardwareVsync(true /* allowToEnable */);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800594 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700595 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
596 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700597 // need to update the VsyncController model anyway.
Leon Scroggins III67388622023-02-06 20:36:20 -0500598 std::scoped_lock lock(mDisplayLock);
599 ftl::FakeGuard guard(kMainThreadContext);
600 constexpr bool disallow = false;
601 for (auto& [_, schedule] : mVsyncSchedules) {
602 schedule->disableHardwareVsync(mSchedulerCallback, disallow);
603 }
Alec Mouridc28b372019-04-18 21:17:13 -0700604 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800605
606 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700607}
608
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700609void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800610 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700611 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100612}
613
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700614void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700615 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700616 // Touch event will boost the refresh rate to performance.
617 // Clear layer history to get fresh FPS detection.
618 // NOTE: Instead of checking all the layers, we should be checking the layer
619 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800620 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700621 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700622 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700623 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700624}
625
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700626void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800627 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700628 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700629}
630
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400631void Scheduler::dump(utils::Dumper& dumper) const {
632 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700633
634 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400635 utils::Dumper::Section section(dumper, "Features"sv);
636
637 for (Feature feature : ftl::enum_range<Feature>()) {
638 if (const auto flagOpt = ftl::flag_name(feature)) {
639 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
640 }
641 }
642 }
643 {
644 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400645 {
646 std::scoped_lock lock(mDisplayLock);
647 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500648 dumper.dump("pacesetterDisplayId"sv, mPacesetterDisplayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400649 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400650 dumper.dump("layerHistory"sv, mLayerHistory.dump());
651 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
652 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
653 }
654
655 mFrameRateOverrideMappings.dump(dumper);
656 dumper.eol();
Ana Krulecb43429d2019-01-09 14:28:51 -0800657}
658
Dominik Laskowski068173d2021-08-11 17:22:59 -0700659void Scheduler::dumpVsync(std::string& out) const {
Leon Scroggins III67388622023-02-06 20:36:20 -0500660 std::scoped_lock lock(mDisplayLock);
661 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500662 if (mPacesetterDisplayId) {
663 base::StringAppendF(&out, "VsyncSchedule for pacesetter %s:\n",
664 to_string(*mPacesetterDisplayId).c_str());
Leon Scroggins III67388622023-02-06 20:36:20 -0500665 getVsyncScheduleLocked()->dump(out);
666 }
667 for (auto& [id, vsyncSchedule] : mVsyncSchedules) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500668 if (id == mPacesetterDisplayId) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500669 continue;
670 }
671 base::StringAppendF(&out, "VsyncSchedule for follower %s:\n", to_string(id).c_str());
672 vsyncSchedule->dump(out);
673 }
Ady Abraham8735eac2020-08-12 16:35:04 -0700674}
675
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800676bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400677 if (consideredSignals.idle) return false;
678
679 const auto frameRateOverrides =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500680 pacesetterSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
681 displayRefreshRate, consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400682
683 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
684 // the FrameRateOverrideMappings rather than here.
685 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
686}
687
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500688void Scheduler::promotePacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400689 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
690
691 {
692 std::scoped_lock lock(mDisplayLock);
693 pacesetterVsyncSchedule = promotePacesetterDisplayLocked(pacesetterIdOpt);
694 }
695
696 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
697}
698
699std::shared_ptr<VsyncSchedule> Scheduler::promotePacesetterDisplayLocked(
700 std::optional<PhysicalDisplayId> pacesetterIdOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500701 // TODO(b/241286431): Choose the pacesetter display.
702 mPacesetterDisplayId = pacesetterIdOpt.value_or(mRefreshRateSelectors.begin()->first);
703 ALOGI("Display %s is the pacesetter", to_string(*mPacesetterDisplayId).c_str());
Dominik Laskowski596a2562022-10-28 11:26:12 -0400704
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500705 auto vsyncSchedule = getVsyncScheduleLocked(*mPacesetterDisplayId);
706 if (const auto pacesetterPtr = pacesetterSelectorPtrLocked()) {
707 pacesetterPtr->setIdleTimerCallbacks(
Dominik Laskowski596a2562022-10-28 11:26:12 -0400708 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
709 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
710 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
711 .onExpired =
712 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
713
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500714 pacesetterPtr->startIdleTimer();
Leon Scroggins III67388622023-02-06 20:36:20 -0500715
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500716 const Fps refreshRate = pacesetterPtr->getActiveMode().modePtr->getFps();
Leon Scroggins III67388622023-02-06 20:36:20 -0500717 vsyncSchedule->startPeriodTransition(mSchedulerCallback, refreshRate.getPeriod(),
718 true /* force */);
719 }
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400720 return vsyncSchedule;
721}
Leon Scroggins III67388622023-02-06 20:36:20 -0500722
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400723void Scheduler::applyNewVsyncSchedule(std::shared_ptr<VsyncSchedule> vsyncSchedule) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500724 onNewVsyncSchedule(vsyncSchedule->getDispatch());
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400725 std::vector<android::EventThread*> threads;
Leon Scroggins III67388622023-02-06 20:36:20 -0500726 {
727 std::lock_guard<std::mutex> lock(mConnectionsLock);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400728 threads.reserve(mConnections.size());
Leon Scroggins III67388622023-02-06 20:36:20 -0500729 for (auto& [_, connection] : mConnections) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400730 threads.push_back(connection.thread.get());
Leon Scroggins III67388622023-02-06 20:36:20 -0500731 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800732 }
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400733 for (auto* thread : threads) {
734 thread->onNewVsyncSchedule(vsyncSchedule);
735 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400736}
737
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500738void Scheduler::demotePacesetterDisplay() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400739 // No need to lock for reads on kMainThreadContext.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500740 if (const auto pacesetterPtr = FTL_FAKE_GUARD(mDisplayLock, pacesetterSelectorPtrLocked())) {
741 pacesetterPtr->stopIdleTimer();
742 pacesetterPtr->clearIdleTimerCallbacks();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400743 }
744
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500745 // Clear state that depends on the pacesetter's RefreshRateSelector.
Dominik Laskowski596a2562022-10-28 11:26:12 -0400746 std::scoped_lock lock(mPolicyLock);
747 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800748}
749
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800750template <typename S, typename T>
751auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Ady Abraham73c3df52023-01-12 18:09:31 -0800752 ATRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400753 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800754 GlobalSignals consideredSignals;
755
Ady Abraham62a0be22020-12-08 16:54:10 -0800756 bool refreshRateChanged = false;
757 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800758
Ady Abraham8532d012019-05-08 14:50:56 -0700759 {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400760 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800761
762 auto& currentState = mPolicy.*statePtr;
763 if (currentState == newState) return {};
764 currentState = std::forward<T>(newState);
765
Dominik Laskowski596a2562022-10-28 11:26:12 -0400766 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -0800767 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400768 {
769 std::scoped_lock lock(mDisplayLock);
770 ftl::FakeGuard guard(kMainThreadContext);
771
772 modeChoices = chooseDisplayModes();
773
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500774 // TODO(b/240743786): The pacesetter display's mode must change for any
775 // DisplayModeRequest to go through. Fix this by tracking per-display Scheduler::Policy
776 // and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -0800777 std::tie(modeOpt, consideredSignals) =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500778 modeChoices.get(*mPacesetterDisplayId)
Dominik Laskowski596a2562022-10-28 11:26:12 -0400779 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800780 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400781 })
782 .value();
783 }
ramindani69b58e82022-09-26 16:48:36 -0700784
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400785 modeRequests.reserve(modeChoices.size());
786 for (auto& [id, choice] : modeChoices) {
787 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -0800788 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400789 .emitEvent = !choice.consideredSignals.idle});
790 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800791
Ady Abrahamace3d052022-11-17 16:25:05 -0800792 frameRateOverridesChanged = updateFrameRateOverrides(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400793
Ady Abrahamace3d052022-11-17 16:25:05 -0800794 if (mPolicy.modeOpt != modeOpt) {
795 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400796 refreshRateChanged = true;
797 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100798 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800799 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700800 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100801 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700802 }
Ady Abraham8532d012019-05-08 14:50:56 -0700803 }
Ady Abraham8532d012019-05-08 14:50:56 -0700804 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800805 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400806 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -0800807 }
808 if (frameRateOverridesChanged) {
809 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
810 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800811 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700812}
813
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400814auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800815 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -0700816
Ady Abraham68636062022-11-16 17:07:25 -0800817 using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400818 display::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -0400819
820 // Tallies the score of a refresh rate across `displayCount` displays.
821 struct RefreshRateTally {
822 explicit RefreshRateTally(float score) : score(score) {}
823
824 float score;
825 size_t displayCount = 1;
826 };
827
828 // Chosen to exceed a typical number of refresh rates across displays.
829 constexpr size_t kStaticCapacity = 8;
830 ftl::SmallMap<Fps, RefreshRateTally, kStaticCapacity, FpsApproxEqual> refreshRateTallies;
831
832 const auto globalSignals = makeGlobalSignals();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800833
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400834 for (const auto& [id, selectorPtr] : mRefreshRateSelectors) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800835 auto rankedFrameRates =
Ady Abraham68636062022-11-16 17:07:25 -0800836 selectorPtr->getRankedFrameRates(mPolicy.contentRequirements, globalSignals);
ramindani69b58e82022-09-26 16:48:36 -0700837
Ady Abrahamace3d052022-11-17 16:25:05 -0800838 for (const auto& [frameRateMode, score] : rankedFrameRates.ranking) {
839 const auto [it, inserted] = refreshRateTallies.try_emplace(frameRateMode.fps, score);
Dominik Laskowski01602522022-10-07 19:02:28 -0400840
841 if (!inserted) {
842 auto& tally = it->second;
843 tally.score += score;
844 tally.displayCount++;
845 }
846 }
847
Ady Abrahamace3d052022-11-17 16:25:05 -0800848 perDisplayRanking.push_back(std::move(rankedFrameRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400849 }
ramindani69b58e82022-09-26 16:48:36 -0700850
Dominik Laskowski01602522022-10-07 19:02:28 -0400851 auto maxScoreIt = refreshRateTallies.cbegin();
ramindani69b58e82022-09-26 16:48:36 -0700852
Dominik Laskowski01602522022-10-07 19:02:28 -0400853 // Find the first refresh rate common to all displays.
854 while (maxScoreIt != refreshRateTallies.cend() &&
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400855 maxScoreIt->second.displayCount != mRefreshRateSelectors.size()) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400856 ++maxScoreIt;
857 }
858
859 if (maxScoreIt != refreshRateTallies.cend()) {
860 // Choose the highest refresh rate common to all displays, if any.
861 for (auto it = maxScoreIt + 1; it != refreshRateTallies.cend(); ++it) {
862 const auto [fps, tally] = *it;
863
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400864 if (tally.displayCount == mRefreshRateSelectors.size() &&
865 tally.score > maxScoreIt->second.score) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400866 maxScoreIt = it;
867 }
ramindani7c487282022-10-10 16:17:51 -0700868 }
869 }
ramindani69b58e82022-09-26 16:48:36 -0700870
Dominik Laskowski01602522022-10-07 19:02:28 -0400871 const std::optional<Fps> chosenFps = maxScoreIt != refreshRateTallies.cend()
872 ? std::make_optional(maxScoreIt->first)
873 : std::nullopt;
874
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400875 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -0400876
ramindani69b58e82022-09-26 16:48:36 -0700877 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -0400878
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400879 for (auto& [ranking, signals] : perDisplayRanking) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400880 if (!chosenFps) {
Ady Abraham68636062022-11-16 17:07:25 -0800881 const auto& [frameRateMode, _] = ranking.front();
Ady Abrahamace3d052022-11-17 16:25:05 -0800882 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
883 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400884 continue;
885 }
886
Ady Abraham68636062022-11-16 17:07:25 -0800887 for (auto& [frameRateMode, _] : ranking) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800888 if (frameRateMode.fps == *chosenFps) {
889 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
890 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400891 break;
892 }
893 }
894 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400895 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -0700896}
897
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400898GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +0000899 const bool powerOnImminent = mDisplayPowerTimer &&
900 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
901 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700902
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400903 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
904 .idle = mPolicy.idleTimer == TimerState::Expired,
905 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800906}
907
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500908FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700909 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500910 const auto frameRateMode =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500911 pacesetterSelectorPtr()
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500912 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
913 .ranking.front()
914 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400915
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500916 // Make sure the stored mode is up to date.
917 mPolicy.modeOpt = frameRateMode;
918
919 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700920}
921
Peiyong Line9d809e2020-04-14 13:10:48 -0700922void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800923 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
924 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
925
926 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
927 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
928 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
929 }
930}
931
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700932bool Scheduler::onPostComposition(nsecs_t presentTime) {
933 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
934 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
935 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
936 // We need to composite again as refreshTimeNanos is still in the future.
937 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700938 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700939
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700940 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800941 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700942 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800943}
944
Ady Abraham7825c682021-05-17 15:12:14 -0700945void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700946 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800947}
948
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800949void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
950 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
951 return;
952 }
953
954 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
955}
956
Ady Abraham62a0be22020-12-08 16:54:10 -0800957void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
958 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
959 return;
960 }
961
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800962 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -0800963}
964
Dominik Laskowski068173d2021-08-11 17:22:59 -0700965} // namespace android::scheduler