blob: 6e332721b876bb28368f8e30abdef3ff0de5c8c2 [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
Dominik Laskowski596a2562022-10-28 11:26:12 -0400112 std::scoped_lock lock(mDisplayLock);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500113 promotePacesetterDisplay(pacesetterIdOpt);
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800114}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700115
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400116void Scheduler::registerDisplay(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500117 registerDisplayInternal(displayId, std::move(selectorPtr),
118 std::make_shared<VsyncSchedule>(displayId, mFeatures));
119}
120
121void Scheduler::registerDisplayInternal(PhysicalDisplayId displayId,
122 RefreshRateSelectorPtr selectorPtr,
123 std::shared_ptr<VsyncSchedule> vsyncSchedule) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500124 demotePacesetterDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400125
Dominik Laskowski596a2562022-10-28 11:26:12 -0400126 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400127 mRefreshRateSelectors.emplace_or_replace(displayId, std::move(selectorPtr));
Leon Scroggins III67388622023-02-06 20:36:20 -0500128 mVsyncSchedules.emplace_or_replace(displayId, std::move(vsyncSchedule));
Dominik Laskowski596a2562022-10-28 11:26:12 -0400129
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500130 promotePacesetterDisplay();
Dominik Laskowski01602522022-10-07 19:02:28 -0400131}
132
133void Scheduler::unregisterDisplay(PhysicalDisplayId displayId) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500134 demotePacesetterDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400135
Dominik Laskowski596a2562022-10-28 11:26:12 -0400136 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400137 mRefreshRateSelectors.erase(displayId);
Leon Scroggins III67388622023-02-06 20:36:20 -0500138 mVsyncSchedules.erase(displayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400139
Leon Scroggins IIIda21f422023-01-30 20:17:56 -0500140 // Do not allow removing the final display. Code in the scheduler expects
141 // there to be at least one display. (This may be relaxed in the future with
142 // headless virtual display.)
143 LOG_ALWAYS_FATAL_IF(mRefreshRateSelectors.empty(), "Cannot unregister all displays!");
144
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500145 promotePacesetterDisplay();
Dominik Laskowski01602522022-10-07 19:02:28 -0400146}
147
Dominik Laskowski756b7892021-08-04 12:53:59 -0700148void Scheduler::run() {
149 while (true) {
150 waitMessage();
151 }
152}
153
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700154void Scheduler::onFrameSignal(ICompositor& compositor, VsyncId vsyncId,
155 TimePoint expectedVsyncTime) {
156 const TimePoint frameTime = SchedulerClock::now();
157
158 if (!compositor.commit(frameTime, vsyncId, expectedVsyncTime)) {
159 return;
160 }
161
162 compositor.composite(frameTime, vsyncId);
163 compositor.sample();
164}
165
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500166std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800167 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500168 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800169 return mFrameRateOverrideMappings
170 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800171}
172
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500173bool Scheduler::isVsyncValid(TimePoint expectedVsyncTimestamp, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800174 const auto frameRate = getFrameRateOverride(uid);
175 if (!frameRate.has_value()) {
176 return true;
177 }
178
Ady Abraham9243bba2023-02-10 15:31:14 -0800179 ATRACE_FORMAT("%s uid: %d frameRate: %s", __func__, uid, to_string(*frameRate).c_str());
Leon Scroggins III67388622023-02-06 20:36:20 -0500180 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTimestamp.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700181}
182
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500183bool Scheduler::isVsyncInPhase(TimePoint timePoint, const Fps frameRate) const {
Leon Scroggins III67388622023-02-06 20:36:20 -0500184 return getVsyncSchedule()->getTracker().isVSyncInPhase(timePoint.ns(), frameRate);
Huihong Luo1768cb02022-10-11 11:10:34 -0700185}
186
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500187impl::EventThread::ThrottleVsyncCallback Scheduler::makeThrottleVsyncCallback() const {
188 return [this](nsecs_t expectedVsyncTimestamp, uid_t uid) {
189 return !isVsyncValid(TimePoint::fromNs(expectedVsyncTimestamp), uid);
190 };
191}
Ady Abraham64c2fc02020-12-29 12:07:50 -0800192
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500193impl::EventThread::GetVsyncPeriodFunction Scheduler::makeGetVsyncPeriodFunction() const {
194 return [this](uid_t uid) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500195 const Fps refreshRate = pacesetterSelectorPtr()->getActiveMode().fps;
Leon Scroggins III67388622023-02-06 20:36:20 -0500196 const nsecs_t currentPeriod =
197 getVsyncSchedule()->period().ns() ?: refreshRate.getPeriodNsecs();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800198
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500199 const auto frameRate = getFrameRateOverride(uid);
200 if (!frameRate.has_value()) {
201 return currentPeriod;
202 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100203
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500204 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
205 if (divisor <= 1) {
206 return currentPeriod;
207 }
208 return currentPeriod * divisor;
209 };
Jorim Jaggic0086af2021-02-12 18:18:11 +0100210}
211
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500212ConnectionHandle Scheduler::createEventThread(Cycle cycle,
213 frametimeline::TokenManager* tokenManager,
214 std::chrono::nanoseconds workDuration,
215 std::chrono::nanoseconds readyDuration) {
216 auto eventThread = std::make_unique<impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
Leon Scroggins III67388622023-02-06 20:36:20 -0500217 getVsyncSchedule(), tokenManager,
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500218 makeThrottleVsyncCallback(),
219 makeGetVsyncPeriodFunction(),
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500220 workDuration, readyDuration);
221
222 auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
223 handle = createConnection(std::move(eventThread));
224 return handle;
Dominik Laskowski98041832019-08-01 18:35:59 -0700225}
Ana Krulec98b5b242018-08-10 15:03:23 -0700226
Dominik Laskowski068173d2021-08-11 17:22:59 -0700227ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700228 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
229 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800230
Ady Abraham62f216c2020-10-13 19:07:23 -0700231 auto connection = createConnectionInternal(eventThread.get());
Dominik Laskowski98041832019-08-01 18:35:59 -0700232
Ana Krulec6ddd2612020-09-24 13:06:33 -0700233 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700234 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
235 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700236}
237
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700238sp<EventThreadConnection> Scheduler::createConnectionInternal(
Rachel Lee2248f522023-01-27 16:45:23 -0800239 EventThread* eventThread, EventRegistrationFlags eventRegistration,
240 const sp<IBinder>& layerHandle) {
241 int32_t layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
242 auto connection = eventThread->createEventConnection([&] { resync(); }, eventRegistration);
243 mLayerHistory.attachChoreographer(layerId, connection);
244 return connection;
Ana Krulec0c8cd522018-08-31 12:27:28 -0700245}
246
Ana Krulec98b5b242018-08-10 15:03:23 -0700247sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Rachel Lee2248f522023-01-27 16:45:23 -0800248 ConnectionHandle handle, EventRegistrationFlags eventRegistration,
249 const sp<IBinder>& layerHandle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700250 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700251 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Rachel Lee2248f522023-01-27 16:45:23 -0800252 return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration,
253 layerHandle);
Ana Krulec98b5b242018-08-10 15:03:23 -0700254}
255
Dominik Laskowski98041832019-08-01 18:35:59 -0700256sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
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);
259 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700260}
261
Dominik Laskowski98041832019-08-01 18:35:59 -0700262void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
263 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700264 android::EventThread* thread;
265 {
266 std::lock_guard<std::mutex> lock(mConnectionsLock);
267 RETURN_IF_INVALID_HANDLE(handle);
268 thread = mConnections[handle].thread.get();
269 }
270
271 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700272}
273
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500274void Scheduler::enableSyntheticVsync(bool enable) {
275 // TODO(b/241285945): Remove connection handles.
276 const ConnectionHandle handle = mAppConnectionHandle;
Ana Krulec6ddd2612020-09-24 13:06:33 -0700277 android::EventThread* thread;
278 {
279 std::lock_guard<std::mutex> lock(mConnectionsLock);
280 RETURN_IF_INVALID_HANDLE(handle);
281 thread = mConnections[handle].thread.get();
282 }
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500283 thread->enableSyntheticVsync(enable);
Ana Krulec98b5b242018-08-10 15:03:23 -0700284}
285
Ady Abraham62a0be22020-12-08 16:54:10 -0800286void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800287 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500288 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800289
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800290 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800291 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800292
Ady Abraham62f216c2020-10-13 19:07:23 -0700293 android::EventThread* thread;
294 {
Ady Abraham62a0be22020-12-08 16:54:10 -0800295 std::lock_guard lock(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700296 RETURN_IF_INVALID_HANDLE(handle);
297 thread = mConnections[handle].thread.get();
298 }
299 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
300}
301
Ady Abrahamace3d052022-11-17 16:25:05 -0800302void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800303 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700304 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100305 // Cache the last reported modes for primary display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700306 mPolicy.cachedModeChangedParams = {handle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700307
308 // Invalidate content based refresh rate selection so it could be calculated
309 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700310 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800311 }
Ady Abraham690f4612021-07-01 23:24:03 -0700312 onNonPrimaryDisplayModeChanged(handle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700313}
314
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100315void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700316 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800317 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100318 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700319 return;
320 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700321 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100322 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700323 return;
324 }
325
Ady Abrahamd1591702021-07-27 16:27:56 -0700326 // If the mode is not the current mode, this means that a
327 // mode change is in progress. In that case we shouldn't dispatch an event
328 // as it will be dispatched when the current mode changes.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500329 if (pacesetterSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700330 return;
331 }
332
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100333 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800334 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700335 return;
336 }
337
Ady Abrahamace3d052022-11-17 16:25:05 -0800338 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700339 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
340 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700341}
342
Ady Abrahamace3d052022-11-17 16:25:05 -0800343void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700344 android::EventThread* thread;
345 {
346 std::lock_guard<std::mutex> lock(mConnectionsLock);
347 RETURN_IF_INVALID_HANDLE(handle);
348 thread = mConnections[handle].thread.get();
349 }
Ady Abraham67434eb2022-12-01 17:48:12 -0800350 thread->onModeChanged(mode);
Ady Abraham447052e2019-02-13 16:07:27 -0800351}
352
Alec Mouri717bcb62020-02-10 17:07:19 -0800353size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700354 std::lock_guard<std::mutex> lock(mConnectionsLock);
Alec Mouri717bcb62020-02-10 17:07:19 -0800355 RETURN_IF_INVALID_HANDLE(handle, 0);
356 return mConnections[handle].thread->getEventThreadConnectionCount();
357}
358
Dominik Laskowski98041832019-08-01 18:35:59 -0700359void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700360 android::EventThread* thread;
361 {
362 std::lock_guard<std::mutex> lock(mConnectionsLock);
363 RETURN_IF_INVALID_HANDLE(handle);
364 thread = mConnections.at(handle).thread.get();
365 }
366 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700367}
368
Ady Abraham9c53ee72020-07-22 21:16:18 -0700369void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
370 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700371 android::EventThread* thread;
372 {
373 std::lock_guard<std::mutex> lock(mConnectionsLock);
374 RETURN_IF_INVALID_HANDLE(handle);
375 thread = mConnections[handle].thread.get();
376 }
377 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700378}
Ana Krulece588e312018-09-18 12:32:24 -0700379
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500380void Scheduler::setVsyncConfigSet(const VsyncConfigSet& configs, Period vsyncPeriod) {
381 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(configs), vsyncPeriod);
382}
383
384void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
385 setDuration(mAppConnectionHandle,
386 /* workDuration */ config.appWorkDuration,
387 /* readyDuration */ config.sfWorkDuration);
388 setDuration(mSfConnectionHandle,
389 /* workDuration */ vsyncPeriod,
390 /* readyDuration */ config.sfWorkDuration);
391 setDuration(config.sfWorkDuration);
392}
393
Leon Scroggins III67388622023-02-06 20:36:20 -0500394void Scheduler::enableHardwareVsync(PhysicalDisplayId id) {
395 auto schedule = getVsyncSchedule(id);
396 schedule->enableHardwareVsync(mSchedulerCallback);
Ana Krulece588e312018-09-18 12:32:24 -0700397}
398
Leon Scroggins III67388622023-02-06 20:36:20 -0500399void Scheduler::disableHardwareVsync(PhysicalDisplayId id, bool disallow) {
400 auto schedule = getVsyncSchedule(id);
401 schedule->disableHardwareVsync(mSchedulerCallback, disallow);
Ana Krulece588e312018-09-18 12:32:24 -0700402}
403
Leon Scroggins III67388622023-02-06 20:36:20 -0500404void Scheduler::resyncAllToHardwareVsync(bool allowToEnable) {
Rachel Leea5be3282023-03-08 20:15:54 -0800405 ATRACE_CALL();
Leon Scroggins III67388622023-02-06 20:36:20 -0500406 std::scoped_lock lock(mDisplayLock);
407 ftl::FakeGuard guard(kMainThreadContext);
408
409 for (const auto& [id, _] : mRefreshRateSelectors) {
410 resyncToHardwareVsyncLocked(id, allowToEnable);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500411 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500412}
413
Leon Scroggins III67388622023-02-06 20:36:20 -0500414void Scheduler::resyncToHardwareVsyncLocked(PhysicalDisplayId id, bool allowToEnable,
415 std::optional<Fps> refreshRate) {
416 auto schedule = getVsyncScheduleLocked(id);
417 if (schedule->isHardwareVsyncAllowed(allowToEnable)) {
418 if (!refreshRate) {
419 auto selectorPtr = mRefreshRateSelectors.get(id);
420 LOG_ALWAYS_FATAL_IF(!selectorPtr);
421 refreshRate = selectorPtr->get()->getActiveMode().modePtr->getFps();
422 }
423 if (refreshRate->isValid()) {
424 schedule->startPeriodTransition(mSchedulerCallback, refreshRate->getPeriod(),
425 false /* force */);
426 }
427 }
428}
429
430void Scheduler::setRenderRate(PhysicalDisplayId id, Fps renderFrameRate) {
431 std::scoped_lock lock(mDisplayLock);
432 ftl::FakeGuard guard(kMainThreadContext);
433
434 auto selectorPtr = mRefreshRateSelectors.get(id);
435 LOG_ALWAYS_FATAL_IF(!selectorPtr);
436 const auto mode = selectorPtr->get()->getActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -0800437
438 using fps_approx_ops::operator!=;
439 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
Leon Scroggins III67388622023-02-06 20:36:20 -0500440 "Mismatch in render frame rates. Selector: %s, Scheduler: %s, Display: "
441 "%" PRIu64,
442 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str(), id.value);
Ady Abrahamace3d052022-11-17 16:25:05 -0800443
444 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
445 to_string(mode.modePtr->getFps()).c_str());
446
Leon Scroggins III67388622023-02-06 20:36:20 -0500447 getVsyncScheduleLocked(id)->getTracker().setRenderRate(renderFrameRate);
Ady Abrahamace3d052022-11-17 16:25:05 -0800448}
449
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700450void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700451 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800452
453 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700454 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800455
456 if (now - last > kIgnoreDelay) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500457 resyncAllToHardwareVsync(false /* allowToEnable */);
Ana Krulecc2870422019-01-29 19:00:58 -0800458 }
459}
460
Leon Scroggins III67388622023-02-06 20:36:20 -0500461bool Scheduler::addResyncSample(PhysicalDisplayId id, nsecs_t timestamp,
462 std::optional<nsecs_t> hwcVsyncPeriodIn) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500463 const auto hwcVsyncPeriod = ftl::Optional(hwcVsyncPeriodIn).transform([](nsecs_t nanos) {
464 return Period::fromNs(nanos);
465 });
Leon Scroggins III67388622023-02-06 20:36:20 -0500466 return getVsyncSchedule(id)->addResyncSample(mSchedulerCallback, TimePoint::fromNs(timestamp),
467 hwcVsyncPeriod);
Ana Krulece588e312018-09-18 12:32:24 -0700468}
469
Leon Scroggins III67388622023-02-06 20:36:20 -0500470void Scheduler::addPresentFence(PhysicalDisplayId id, std::shared_ptr<FenceTime> fence) {
471 auto schedule = getVsyncSchedule(id);
472 const bool needMoreSignals = schedule->getController().addPresentFence(std::move(fence));
473 if (needMoreSignals) {
474 schedule->enableHardwareVsync(mSchedulerCallback);
Ana Krulece588e312018-09-18 12:32:24 -0700475 } else {
Leon Scroggins III67388622023-02-06 20:36:20 -0500476 schedule->disableHardwareVsync(mSchedulerCallback, false /* disallow */);
Ana Krulece588e312018-09-18 12:32:24 -0700477 }
478}
479
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700480void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200481 // If the content detection feature is off, we still keep the layer history,
482 // since we use it for other features (like Frame Rate API), so layers
483 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000484 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700485}
486
Ady Abrahambdda8f02021-04-01 16:06:11 -0700487void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700488 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700489}
490
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000491void Scheduler::recordLayerHistory(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
Ady Abraham5def7332020-05-29 16:13:47 -0700492 LayerHistory::LayerUpdateType updateType) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500493 if (pacesetterSelectorPtr()->canSwitch()) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000494 mLayerHistory.record(id, layerProps, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800495 }
Ana Krulec3084c052018-11-21 20:27:17 +0100496}
497
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100498void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700499 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700500}
501
Andy Labrada096227e2022-06-15 16:58:11 +0000502void Scheduler::setDefaultFrameRateCompatibility(Layer* layer) {
503 mLayerHistory.setDefaultFrameRateCompatibility(layer,
504 mFeatures.test(Feature::kContentDetection));
505}
506
Dominik Laskowski49cea512019-11-12 14:13:23 -0800507void Scheduler::chooseRefreshRateForContent() {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500508 const auto selectorPtr = pacesetterSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400509 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800510
Ady Abraham8a82ba62020-01-17 12:43:17 -0800511 ATRACE_CALL();
512
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400513 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800514 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abrahama1a49af2019-02-07 14:36:55 -0800515}
516
Ana Krulecfb772822018-11-30 10:44:07 +0100517void Scheduler::resetIdleTimer() {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500518 pacesetterSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800519}
520
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700521void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700522 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800523 mTouchTimer->reset();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500524 pacesetterSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800525 }
Ady Abraham8532d012019-05-08 14:50:56 -0700526}
527
Leon Scroggins III67388622023-02-06 20:36:20 -0500528void Scheduler::setDisplayPowerMode(PhysicalDisplayId id, hal::PowerMode powerMode) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500529 const bool isPacesetter = [this, id]() REQUIRES(kMainThreadContext) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500530 ftl::FakeGuard guard(mDisplayLock);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500531 return id == mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500532 }();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500533 if (isPacesetter) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500534 // TODO (b/255657128): This needs to be handled per display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700535 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700536 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700537 }
Leon Scroggins III67388622023-02-06 20:36:20 -0500538 {
539 std::scoped_lock lock(mDisplayLock);
540 auto vsyncSchedule = getVsyncScheduleLocked(id);
541 vsyncSchedule->getController().setDisplayPowerMode(powerMode);
542 }
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500543 if (!isPacesetter) return;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700544
545 if (mDisplayPowerTimer) {
546 mDisplayPowerTimer->reset();
547 }
548
549 // Display Power event will boost the refresh rate to performance.
550 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700551 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700552}
553
Leon Scroggins III67388622023-02-06 20:36:20 -0500554std::shared_ptr<const VsyncSchedule> Scheduler::getVsyncSchedule(
555 std::optional<PhysicalDisplayId> idOpt) const {
556 std::scoped_lock lock(mDisplayLock);
557 return getVsyncScheduleLocked(idOpt);
558}
559
560std::shared_ptr<const VsyncSchedule> Scheduler::getVsyncScheduleLocked(
561 std::optional<PhysicalDisplayId> idOpt) const {
562 ftl::FakeGuard guard(kMainThreadContext);
563 if (!idOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500564 LOG_ALWAYS_FATAL_IF(!mPacesetterDisplayId, "Missing a pacesetter!");
565 idOpt = mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500566 }
567 auto scheduleOpt = mVsyncSchedules.get(*idOpt);
568 LOG_ALWAYS_FATAL_IF(!scheduleOpt);
569 return std::const_pointer_cast<const VsyncSchedule>(scheduleOpt->get());
570}
571
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700572void Scheduler::kernelIdleTimerCallback(TimerState state) {
573 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100574
Ady Abraham2139f732019-11-13 18:56:40 -0800575 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
576 // magic number
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500577 const Fps refreshRate = pacesetterSelectorPtr()->getActiveMode().modePtr->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700578
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700579 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
580 using namespace fps_approx_ops;
581
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800582 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700583 // If we're not in performance mode then the kernel timer shouldn't do
584 // anything, as the refresh rate during DPU power collapse will be the
585 // same.
Leon Scroggins III67388622023-02-06 20:36:20 -0500586 resyncAllToHardwareVsync(true /* allowToEnable */);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800587 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700588 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
589 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700590 // need to update the VsyncController model anyway.
Leon Scroggins III67388622023-02-06 20:36:20 -0500591 std::scoped_lock lock(mDisplayLock);
592 ftl::FakeGuard guard(kMainThreadContext);
593 constexpr bool disallow = false;
594 for (auto& [_, schedule] : mVsyncSchedules) {
595 schedule->disableHardwareVsync(mSchedulerCallback, disallow);
596 }
Alec Mouridc28b372019-04-18 21:17:13 -0700597 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800598
599 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700600}
601
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700602void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800603 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700604 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100605}
606
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700607void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700608 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700609 // Touch event will boost the refresh rate to performance.
610 // Clear layer history to get fresh FPS detection.
611 // NOTE: Instead of checking all the layers, we should be checking the layer
612 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800613 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700614 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700615 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700616 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700617}
618
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700619void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800620 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700621 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700622}
623
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400624void Scheduler::dump(utils::Dumper& dumper) const {
625 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700626
627 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400628 utils::Dumper::Section section(dumper, "Features"sv);
629
630 for (Feature feature : ftl::enum_range<Feature>()) {
631 if (const auto flagOpt = ftl::flag_name(feature)) {
632 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
633 }
634 }
635 }
636 {
637 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400638 {
639 std::scoped_lock lock(mDisplayLock);
640 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500641 dumper.dump("pacesetterDisplayId"sv, mPacesetterDisplayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400642 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400643 dumper.dump("layerHistory"sv, mLayerHistory.dump());
644 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
645 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
646 }
647
648 mFrameRateOverrideMappings.dump(dumper);
649 dumper.eol();
Ana Krulecb43429d2019-01-09 14:28:51 -0800650}
651
Dominik Laskowski068173d2021-08-11 17:22:59 -0700652void Scheduler::dumpVsync(std::string& out) const {
Leon Scroggins III67388622023-02-06 20:36:20 -0500653 std::scoped_lock lock(mDisplayLock);
654 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500655 if (mPacesetterDisplayId) {
656 base::StringAppendF(&out, "VsyncSchedule for pacesetter %s:\n",
657 to_string(*mPacesetterDisplayId).c_str());
Leon Scroggins III67388622023-02-06 20:36:20 -0500658 getVsyncScheduleLocked()->dump(out);
659 }
660 for (auto& [id, vsyncSchedule] : mVsyncSchedules) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500661 if (id == mPacesetterDisplayId) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500662 continue;
663 }
664 base::StringAppendF(&out, "VsyncSchedule for follower %s:\n", to_string(id).c_str());
665 vsyncSchedule->dump(out);
666 }
Ady Abraham8735eac2020-08-12 16:35:04 -0700667}
668
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800669bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400670 if (consideredSignals.idle) return false;
671
672 const auto frameRateOverrides =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500673 pacesetterSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
674 displayRefreshRate, consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400675
676 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
677 // the FrameRateOverrideMappings rather than here.
678 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
679}
680
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500681void Scheduler::promotePacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt) {
682 // TODO(b/241286431): Choose the pacesetter display.
683 mPacesetterDisplayId = pacesetterIdOpt.value_or(mRefreshRateSelectors.begin()->first);
684 ALOGI("Display %s is the pacesetter", to_string(*mPacesetterDisplayId).c_str());
Dominik Laskowski596a2562022-10-28 11:26:12 -0400685
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500686 auto vsyncSchedule = getVsyncScheduleLocked(*mPacesetterDisplayId);
687 if (const auto pacesetterPtr = pacesetterSelectorPtrLocked()) {
688 pacesetterPtr->setIdleTimerCallbacks(
Dominik Laskowski596a2562022-10-28 11:26:12 -0400689 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
690 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
691 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
692 .onExpired =
693 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
694
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500695 pacesetterPtr->startIdleTimer();
Leon Scroggins III67388622023-02-06 20:36:20 -0500696
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500697 const Fps refreshRate = pacesetterPtr->getActiveMode().modePtr->getFps();
Leon Scroggins III67388622023-02-06 20:36:20 -0500698 vsyncSchedule->startPeriodTransition(mSchedulerCallback, refreshRate.getPeriod(),
699 true /* force */);
700 }
701
702 onNewVsyncSchedule(vsyncSchedule->getDispatch());
703 {
704 std::lock_guard<std::mutex> lock(mConnectionsLock);
705 for (auto& [_, connection] : mConnections) {
706 connection.thread->onNewVsyncSchedule(vsyncSchedule);
707 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800708 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400709}
710
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500711void Scheduler::demotePacesetterDisplay() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400712 // No need to lock for reads on kMainThreadContext.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500713 if (const auto pacesetterPtr = FTL_FAKE_GUARD(mDisplayLock, pacesetterSelectorPtrLocked())) {
714 pacesetterPtr->stopIdleTimer();
715 pacesetterPtr->clearIdleTimerCallbacks();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400716 }
717
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500718 // Clear state that depends on the pacesetter's RefreshRateSelector.
Dominik Laskowski596a2562022-10-28 11:26:12 -0400719 std::scoped_lock lock(mPolicyLock);
720 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800721}
722
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800723template <typename S, typename T>
724auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Ady Abraham73c3df52023-01-12 18:09:31 -0800725 ATRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400726 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800727 GlobalSignals consideredSignals;
728
Ady Abraham62a0be22020-12-08 16:54:10 -0800729 bool refreshRateChanged = false;
730 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800731
Ady Abraham8532d012019-05-08 14:50:56 -0700732 {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400733 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800734
735 auto& currentState = mPolicy.*statePtr;
736 if (currentState == newState) return {};
737 currentState = std::forward<T>(newState);
738
Dominik Laskowski596a2562022-10-28 11:26:12 -0400739 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -0800740 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400741 {
742 std::scoped_lock lock(mDisplayLock);
743 ftl::FakeGuard guard(kMainThreadContext);
744
745 modeChoices = chooseDisplayModes();
746
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500747 // TODO(b/240743786): The pacesetter display's mode must change for any
748 // DisplayModeRequest to go through. Fix this by tracking per-display Scheduler::Policy
749 // and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -0800750 std::tie(modeOpt, consideredSignals) =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500751 modeChoices.get(*mPacesetterDisplayId)
Dominik Laskowski596a2562022-10-28 11:26:12 -0400752 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800753 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400754 })
755 .value();
756 }
ramindani69b58e82022-09-26 16:48:36 -0700757
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400758 modeRequests.reserve(modeChoices.size());
759 for (auto& [id, choice] : modeChoices) {
760 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -0800761 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400762 .emitEvent = !choice.consideredSignals.idle});
763 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800764
Ady Abrahamace3d052022-11-17 16:25:05 -0800765 frameRateOverridesChanged = updateFrameRateOverrides(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400766
Ady Abrahamace3d052022-11-17 16:25:05 -0800767 if (mPolicy.modeOpt != modeOpt) {
768 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400769 refreshRateChanged = true;
770 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100771 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800772 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700773 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100774 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700775 }
Ady Abraham8532d012019-05-08 14:50:56 -0700776 }
Ady Abraham8532d012019-05-08 14:50:56 -0700777 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800778 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400779 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -0800780 }
781 if (frameRateOverridesChanged) {
782 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
783 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800784 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700785}
786
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400787auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800788 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -0700789
Ady Abraham68636062022-11-16 17:07:25 -0800790 using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400791 display::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -0400792
793 // Tallies the score of a refresh rate across `displayCount` displays.
794 struct RefreshRateTally {
795 explicit RefreshRateTally(float score) : score(score) {}
796
797 float score;
798 size_t displayCount = 1;
799 };
800
801 // Chosen to exceed a typical number of refresh rates across displays.
802 constexpr size_t kStaticCapacity = 8;
803 ftl::SmallMap<Fps, RefreshRateTally, kStaticCapacity, FpsApproxEqual> refreshRateTallies;
804
805 const auto globalSignals = makeGlobalSignals();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800806
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400807 for (const auto& [id, selectorPtr] : mRefreshRateSelectors) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800808 auto rankedFrameRates =
Ady Abraham68636062022-11-16 17:07:25 -0800809 selectorPtr->getRankedFrameRates(mPolicy.contentRequirements, globalSignals);
ramindani69b58e82022-09-26 16:48:36 -0700810
Ady Abrahamace3d052022-11-17 16:25:05 -0800811 for (const auto& [frameRateMode, score] : rankedFrameRates.ranking) {
812 const auto [it, inserted] = refreshRateTallies.try_emplace(frameRateMode.fps, score);
Dominik Laskowski01602522022-10-07 19:02:28 -0400813
814 if (!inserted) {
815 auto& tally = it->second;
816 tally.score += score;
817 tally.displayCount++;
818 }
819 }
820
Ady Abrahamace3d052022-11-17 16:25:05 -0800821 perDisplayRanking.push_back(std::move(rankedFrameRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400822 }
ramindani69b58e82022-09-26 16:48:36 -0700823
Dominik Laskowski01602522022-10-07 19:02:28 -0400824 auto maxScoreIt = refreshRateTallies.cbegin();
ramindani69b58e82022-09-26 16:48:36 -0700825
Dominik Laskowski01602522022-10-07 19:02:28 -0400826 // Find the first refresh rate common to all displays.
827 while (maxScoreIt != refreshRateTallies.cend() &&
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400828 maxScoreIt->second.displayCount != mRefreshRateSelectors.size()) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400829 ++maxScoreIt;
830 }
831
832 if (maxScoreIt != refreshRateTallies.cend()) {
833 // Choose the highest refresh rate common to all displays, if any.
834 for (auto it = maxScoreIt + 1; it != refreshRateTallies.cend(); ++it) {
835 const auto [fps, tally] = *it;
836
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400837 if (tally.displayCount == mRefreshRateSelectors.size() &&
838 tally.score > maxScoreIt->second.score) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400839 maxScoreIt = it;
840 }
ramindani7c487282022-10-10 16:17:51 -0700841 }
842 }
ramindani69b58e82022-09-26 16:48:36 -0700843
Dominik Laskowski01602522022-10-07 19:02:28 -0400844 const std::optional<Fps> chosenFps = maxScoreIt != refreshRateTallies.cend()
845 ? std::make_optional(maxScoreIt->first)
846 : std::nullopt;
847
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400848 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -0400849
ramindani69b58e82022-09-26 16:48:36 -0700850 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -0400851
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400852 for (auto& [ranking, signals] : perDisplayRanking) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400853 if (!chosenFps) {
Ady Abraham68636062022-11-16 17:07:25 -0800854 const auto& [frameRateMode, _] = ranking.front();
Ady Abrahamace3d052022-11-17 16:25:05 -0800855 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
856 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400857 continue;
858 }
859
Ady Abraham68636062022-11-16 17:07:25 -0800860 for (auto& [frameRateMode, _] : ranking) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800861 if (frameRateMode.fps == *chosenFps) {
862 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
863 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400864 break;
865 }
866 }
867 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400868 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -0700869}
870
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400871GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +0000872 const bool powerOnImminent = mDisplayPowerTimer &&
873 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
874 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700875
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400876 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
877 .idle = mPolicy.idleTimer == TimerState::Expired,
878 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800879}
880
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500881FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700882 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500883 const auto frameRateMode =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500884 pacesetterSelectorPtr()
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500885 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
886 .ranking.front()
887 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400888
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500889 // Make sure the stored mode is up to date.
890 mPolicy.modeOpt = frameRateMode;
891
892 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700893}
894
Peiyong Line9d809e2020-04-14 13:10:48 -0700895void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800896 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
897 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
898
899 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
900 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
901 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
902 }
903}
904
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700905bool Scheduler::onPostComposition(nsecs_t presentTime) {
906 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
907 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
908 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
909 // We need to composite again as refreshTimeNanos is still in the future.
910 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700911 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700912
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700913 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800914 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700915 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800916}
917
Ady Abraham7825c682021-05-17 15:12:14 -0700918void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700919 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800920}
921
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800922void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
923 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
924 return;
925 }
926
927 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
928}
929
Ady Abraham62a0be22020-12-08 16:54:10 -0800930void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
931 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
932 return;
933 }
934
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800935 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -0800936}
937
Dominik Laskowski068173d2021-08-11 17:22:59 -0700938} // namespace android::scheduler