blob: eed57ef4f1743f0fc9cab77b20a621af0b686567 [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>
chaviw3277faf2021-05-19 16:45:23 -050031#include <gui/WindowInfo.h>
Ana Krulecfefd6ae2019-02-13 17:53:08 -080032#include <system/window.h>
Ana Krulec3084c052018-11-21 20:27:17 +010033#include <utils/Timers.h>
Ana Krulec7ab56032018-11-02 20:51:06 +010034#include <utils/Trace.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.
Dominik Laskowski596a2562022-10-28 11:26:12 -040084 demoteLeaderDisplay();
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
Dominik Laskowski596a2562022-10-28 11:26:12 -0400109void Scheduler::setLeaderDisplay(std::optional<PhysicalDisplayId> leaderIdOpt) {
110 demoteLeaderDisplay();
Dominik Laskowski59db9562022-10-27 16:18:53 -0400111
Dominik Laskowski596a2562022-10-28 11:26:12 -0400112 std::scoped_lock lock(mDisplayLock);
113 promoteLeaderDisplay(leaderIdOpt);
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 III31d41412022-11-18 16:42:53 -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) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400124 demoteLeaderDisplay();
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 III31d41412022-11-18 16:42:53 -0500128 mVsyncSchedules.emplace_or_replace(displayId, std::move(vsyncSchedule));
Dominik Laskowski596a2562022-10-28 11:26:12 -0400129
130 promoteLeaderDisplay();
Dominik Laskowski01602522022-10-07 19:02:28 -0400131}
132
133void Scheduler::unregisterDisplay(PhysicalDisplayId displayId) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400134 demoteLeaderDisplay();
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 III31d41412022-11-18 16:42:53 -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
Dominik Laskowski596a2562022-10-28 11:26:12 -0400145 promoteLeaderDisplay();
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 III31d41412022-11-18 16:42:53 -0500166std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
167 std::scoped_lock lock(mDisplayLock);
168 return getFrameRateOverrideLocked(uid);
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700169}
170
Leon Scroggins III31d41412022-11-18 16:42:53 -0500171std::optional<Fps> Scheduler::getFrameRateOverrideLocked(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800172 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III31d41412022-11-18 16:42:53 -0500173 leaderSelectorPtrLocked()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800174 return mFrameRateOverrideMappings
175 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800176}
177
Leon Scroggins III31d41412022-11-18 16:42:53 -0500178bool Scheduler::isVsyncTargetForUid(TimePoint expectedVsyncTime, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800179 const auto frameRate = getFrameRateOverride(uid);
180 if (!frameRate.has_value()) {
181 return true;
182 }
183
Leon Scroggins III31d41412022-11-18 16:42:53 -0500184 return isVsyncInPhase(expectedVsyncTime, *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700185}
186
Leon Scroggins III31d41412022-11-18 16:42:53 -0500187bool Scheduler::isVsyncInPhase(TimePoint expectedVsyncTime, Fps frameRate) const {
188 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), frameRate);
Huihong Luo1768cb02022-10-11 11:10:34 -0700189}
190
Leon Scroggins III31d41412022-11-18 16:42:53 -0500191Fps Scheduler::getLeaderRenderFrameRate(uid_t uid) const {
192 std::scoped_lock lock(mDisplayLock);
193 ftl::FakeGuard guard(kMainThreadContext);
194 auto vsyncSchedule = getVsyncScheduleLocked();
Ady Abraham64c2fc02020-12-29 12:07:50 -0800195
Leon Scroggins III31d41412022-11-18 16:42:53 -0500196 const Fps refreshRate = leaderSelectorPtrLocked()->getActiveMode().fps;
197 const nsecs_t currentPeriod = vsyncSchedule->period().ns() ?: refreshRate.getPeriodNsecs();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800198
Leon Scroggins III31d41412022-11-18 16:42:53 -0500199 const auto frameRate = getFrameRateOverrideLocked(uid);
200 if (!frameRate.has_value()) {
201 return Fps::fromPeriodNsecs(currentPeriod);
202 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100203
Leon Scroggins III31d41412022-11-18 16:42:53 -0500204 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
205 if (divisor <= 1) {
206 return Fps::fromPeriodNsecs(currentPeriod);
207 }
208 return Fps::fromPeriodNsecs(currentPeriod * divisor);
Jorim Jaggic0086af2021-02-12 18:18:11 +0100209}
210
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500211ConnectionHandle Scheduler::createEventThread(Cycle cycle,
212 frametimeline::TokenManager* tokenManager,
213 std::chrono::nanoseconds workDuration,
214 std::chrono::nanoseconds readyDuration) {
215 auto eventThread = std::make_unique<impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
Leon Scroggins III31d41412022-11-18 16:42:53 -0500216 getVsyncSchedule(), *this, tokenManager,
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500217 workDuration, readyDuration);
218
219 auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
220 handle = createConnection(std::move(eventThread));
221 return handle;
Dominik Laskowski98041832019-08-01 18:35:59 -0700222}
Ana Krulec98b5b242018-08-10 15:03:23 -0700223
Dominik Laskowski068173d2021-08-11 17:22:59 -0700224ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700225 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
226 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800227
Ady Abraham62f216c2020-10-13 19:07:23 -0700228 auto connection = createConnectionInternal(eventThread.get());
Dominik Laskowski98041832019-08-01 18:35:59 -0700229
Ana Krulec6ddd2612020-09-24 13:06:33 -0700230 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700231 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
232 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700233}
234
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700235sp<EventThreadConnection> Scheduler::createConnectionInternal(
Rachel Lee2248f522023-01-27 16:45:23 -0800236 EventThread* eventThread, EventRegistrationFlags eventRegistration,
237 const sp<IBinder>& layerHandle) {
238 int32_t layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
239 auto connection = eventThread->createEventConnection([&] { resync(); }, eventRegistration);
240 mLayerHistory.attachChoreographer(layerId, connection);
241 return connection;
Ana Krulec0c8cd522018-08-31 12:27:28 -0700242}
243
Ana Krulec98b5b242018-08-10 15:03:23 -0700244sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Rachel Lee2248f522023-01-27 16:45:23 -0800245 ConnectionHandle handle, EventRegistrationFlags eventRegistration,
246 const sp<IBinder>& layerHandle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700247 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700248 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Rachel Lee2248f522023-01-27 16:45:23 -0800249 return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration,
250 layerHandle);
Ana Krulec98b5b242018-08-10 15:03:23 -0700251}
252
Dominik Laskowski98041832019-08-01 18:35:59 -0700253sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700254 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700255 RETURN_IF_INVALID_HANDLE(handle, nullptr);
256 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700257}
258
Dominik Laskowski98041832019-08-01 18:35:59 -0700259void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
260 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700261 android::EventThread* thread;
262 {
263 std::lock_guard<std::mutex> lock(mConnectionsLock);
264 RETURN_IF_INVALID_HANDLE(handle);
265 thread = mConnections[handle].thread.get();
266 }
267
268 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700269}
270
Dominik Laskowski98041832019-08-01 18:35:59 -0700271void Scheduler::onScreenAcquired(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700272 android::EventThread* thread;
273 {
274 std::lock_guard<std::mutex> lock(mConnectionsLock);
275 RETURN_IF_INVALID_HANDLE(handle);
276 thread = mConnections[handle].thread.get();
277 }
278 thread->onScreenAcquired();
Ana Krulec98b5b242018-08-10 15:03:23 -0700279}
280
Dominik Laskowski98041832019-08-01 18:35:59 -0700281void Scheduler::onScreenReleased(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700282 android::EventThread* thread;
283 {
284 std::lock_guard<std::mutex> lock(mConnectionsLock);
285 RETURN_IF_INVALID_HANDLE(handle);
286 thread = mConnections[handle].thread.get();
287 }
288 thread->onScreenReleased();
Ana Krulec98b5b242018-08-10 15:03:23 -0700289}
290
Ady Abraham62a0be22020-12-08 16:54:10 -0800291void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800292 const bool supportsFrameRateOverrideByContent =
Ady Abraham68636062022-11-16 17:07:25 -0800293 leaderSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800294
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800295 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800296 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800297
Ady Abraham62f216c2020-10-13 19:07:23 -0700298 android::EventThread* thread;
299 {
Ady Abraham62a0be22020-12-08 16:54:10 -0800300 std::lock_guard lock(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700301 RETURN_IF_INVALID_HANDLE(handle);
302 thread = mConnections[handle].thread.get();
303 }
304 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
305}
306
Ady Abrahamace3d052022-11-17 16:25:05 -0800307void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800308 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700309 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100310 // Cache the last reported modes for primary display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700311 mPolicy.cachedModeChangedParams = {handle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700312
313 // Invalidate content based refresh rate selection so it could be calculated
314 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700315 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800316 }
Ady Abraham690f4612021-07-01 23:24:03 -0700317 onNonPrimaryDisplayModeChanged(handle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700318}
319
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100320void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700321 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800322 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100323 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700324 return;
325 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700326 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100327 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700328 return;
329 }
330
Ady Abrahamd1591702021-07-27 16:27:56 -0700331 // If the mode is not the current mode, this means that a
332 // mode change is in progress. In that case we shouldn't dispatch an event
333 // as it will be dispatched when the current mode changes.
Ady Abrahamace3d052022-11-17 16:25:05 -0800334 if (leaderSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700335 return;
336 }
337
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100338 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800339 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700340 return;
341 }
342
Ady Abrahamace3d052022-11-17 16:25:05 -0800343 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700344 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
345 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700346}
347
Ady Abrahamace3d052022-11-17 16:25:05 -0800348void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700349 android::EventThread* thread;
350 {
351 std::lock_guard<std::mutex> lock(mConnectionsLock);
352 RETURN_IF_INVALID_HANDLE(handle);
353 thread = mConnections[handle].thread.get();
354 }
Ady Abraham67434eb2022-12-01 17:48:12 -0800355 thread->onModeChanged(mode);
Ady Abraham447052e2019-02-13 16:07:27 -0800356}
357
Alec Mouri717bcb62020-02-10 17:07:19 -0800358size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700359 std::lock_guard<std::mutex> lock(mConnectionsLock);
Alec Mouri717bcb62020-02-10 17:07:19 -0800360 RETURN_IF_INVALID_HANDLE(handle, 0);
361 return mConnections[handle].thread->getEventThreadConnectionCount();
362}
363
Dominik Laskowski98041832019-08-01 18:35:59 -0700364void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700365 android::EventThread* thread;
366 {
367 std::lock_guard<std::mutex> lock(mConnectionsLock);
368 RETURN_IF_INVALID_HANDLE(handle);
369 thread = mConnections.at(handle).thread.get();
370 }
371 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700372}
373
Ady Abraham9c53ee72020-07-22 21:16:18 -0700374void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
375 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700376 android::EventThread* thread;
377 {
378 std::lock_guard<std::mutex> lock(mConnectionsLock);
379 RETURN_IF_INVALID_HANDLE(handle);
380 thread = mConnections[handle].thread.get();
381 }
382 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700383}
Ana Krulece588e312018-09-18 12:32:24 -0700384
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500385void Scheduler::setVsyncConfigSet(const VsyncConfigSet& configs, Period vsyncPeriod) {
386 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(configs), vsyncPeriod);
387}
388
389void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
390 setDuration(mAppConnectionHandle,
391 /* workDuration */ config.appWorkDuration,
392 /* readyDuration */ config.sfWorkDuration);
393 setDuration(mSfConnectionHandle,
394 /* workDuration */ vsyncPeriod,
395 /* readyDuration */ config.sfWorkDuration);
396 setDuration(config.sfWorkDuration);
397}
398
Leon Scroggins III31d41412022-11-18 16:42:53 -0500399void Scheduler::enableHardwareVsync(PhysicalDisplayId id) {
400 auto schedule = getVsyncSchedule(id);
401 schedule->enableHardwareVsync(mSchedulerCallback);
402}
403
404void Scheduler::disableHardwareVsync(PhysicalDisplayId id, bool disallow) {
405 auto schedule = getVsyncSchedule(id);
406 schedule->disableHardwareVsync(mSchedulerCallback, disallow);
407}
408
409void Scheduler::resyncAllToHardwareVsync(bool allowToEnable) {
410 std::scoped_lock lock(mDisplayLock);
411 ftl::FakeGuard guard(kMainThreadContext);
412
413 for (const auto& [id, _] : mRefreshRateSelectors) {
414 resyncToHardwareVsyncLocked(id, allowToEnable);
Ana Krulece588e312018-09-18 12:32:24 -0700415 }
416}
417
Leon Scroggins III31d41412022-11-18 16:42:53 -0500418void Scheduler::resyncToHardwareVsyncLocked(PhysicalDisplayId id, bool allowToEnable,
419 std::optional<Fps> refreshRate) {
420 if (!refreshRate) {
421 auto selectorPtr = mRefreshRateSelectors.get(id);
422 LOG_ALWAYS_FATAL_IF(!selectorPtr);
423 refreshRate = selectorPtr->get()->getActiveMode().modePtr->getFps();
Ana Krulece588e312018-09-18 12:32:24 -0700424 }
Leon Scroggins III31d41412022-11-18 16:42:53 -0500425 auto schedule = getVsyncScheduleLocked(id);
426 if (allowToEnable) {
427 schedule->allowHardwareVsync();
428 } else if (!schedule->isHardwareVsyncAllowed()) {
429 // Hardware vsync is not currently allowed, so abort the resync
430 // attempt for now.
431 return;
Ana Krulece588e312018-09-18 12:32:24 -0700432 }
Leon Scroggins III31d41412022-11-18 16:42:53 -0500433
434 setVsyncPeriod(schedule, refreshRate->getPeriodNsecs(), false /* force */);
Ana Krulece588e312018-09-18 12:32:24 -0700435}
436
Leon Scroggins III31d41412022-11-18 16:42:53 -0500437void Scheduler::setRenderRate(PhysicalDisplayId id, Fps renderFrameRate) {
438 std::scoped_lock lock(mDisplayLock);
439 ftl::FakeGuard guard(kMainThreadContext);
Ana Krulecc2870422019-01-29 19:00:58 -0800440
Leon Scroggins III31d41412022-11-18 16:42:53 -0500441 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 III31d41412022-11-18 16:42:53 -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
454 const auto divisor = RefreshRateSelector::getFrameRateDivisor(mode.modePtr->getFps(), mode.fps);
455 LOG_ALWAYS_FATAL_IF(divisor == 0, "%s <> %s -- not divisors", to_string(mode.fps).c_str(),
456 to_string(mode.fps).c_str());
457
Leon Scroggins III31d41412022-11-18 16:42:53 -0500458 getVsyncScheduleLocked(id)->getTracker().setDivisor(static_cast<unsigned>(divisor));
Ady Abrahamace3d052022-11-17 16:25:05 -0800459}
460
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700461void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700462 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800463
464 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700465 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800466
467 if (now - last > kIgnoreDelay) {
Leon Scroggins III31d41412022-11-18 16:42:53 -0500468 resyncAllToHardwareVsync(false /* allowToEnable */);
Ana Krulecc2870422019-01-29 19:00:58 -0800469 }
470}
471
Leon Scroggins III31d41412022-11-18 16:42:53 -0500472void Scheduler::setVsyncPeriod(const std::shared_ptr<VsyncSchedule>& schedule, nsecs_t period,
473 bool force) {
474 ALOGD("Scheduler::setVsyncPeriod");
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800475 if (period <= 0) return;
476
Leon Scroggins III31d41412022-11-18 16:42:53 -0500477 // TODO (b/266712910):The old code held mHWVsyncLock before calling
478 // startPeriodTransition. Move these into a new method on VsyncSchedule that
479 // encapsulates this behavior there and allows holding the lock the whole
480 // time.
481 schedule->getController().startPeriodTransition(period, force);
482 schedule->enableHardwareVsync(mSchedulerCallback);
Ana Krulece588e312018-09-18 12:32:24 -0700483}
484
Leon Scroggins III31d41412022-11-18 16:42:53 -0500485bool Scheduler::addResyncSample(PhysicalDisplayId id, nsecs_t timestamp,
486 std::optional<nsecs_t> hwcVsyncPeriod) {
487 bool periodFlushed = false;
488 auto schedule = getVsyncSchedule(id);
489 if (schedule->getController().addHwVsyncTimestamp(timestamp, hwcVsyncPeriod, &periodFlushed)) {
490 schedule->enableHardwareVsync(mSchedulerCallback);
491 } else {
492 schedule->disableHardwareVsync(mSchedulerCallback, false /* disallow */);
Ana Krulece588e312018-09-18 12:32:24 -0700493 }
494
Leon Scroggins III31d41412022-11-18 16:42:53 -0500495 return periodFlushed;
Ana Krulece588e312018-09-18 12:32:24 -0700496}
497
Leon Scroggins III31d41412022-11-18 16:42:53 -0500498void Scheduler::addPresentFence(PhysicalDisplayId id, std::shared_ptr<FenceTime> fence) {
499 auto schedule = getVsyncSchedule(id);
500 const bool needMoreSignals = schedule->getController().addPresentFence(std::move(fence));
501 if (needMoreSignals) {
502 schedule->enableHardwareVsync(mSchedulerCallback);
Ana Krulece588e312018-09-18 12:32:24 -0700503 } else {
Leon Scroggins III31d41412022-11-18 16:42:53 -0500504 schedule->disableHardwareVsync(mSchedulerCallback, false /* disallow */);
Ana Krulece588e312018-09-18 12:32:24 -0700505 }
506}
507
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700508void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200509 // If the content detection feature is off, we still keep the layer history,
510 // since we use it for other features (like Frame Rate API), so layers
511 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000512 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700513}
514
Ady Abrahambdda8f02021-04-01 16:06:11 -0700515void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700516 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700517}
518
Ady Abraham5def7332020-05-29 16:13:47 -0700519void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime,
520 LayerHistory::LayerUpdateType updateType) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400521 if (leaderSelectorPtr()->canSwitch()) {
522 mLayerHistory.record(layer, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800523 }
Ana Krulec3084c052018-11-21 20:27:17 +0100524}
525
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100526void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700527 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700528}
529
Andy Labrada096227e2022-06-15 16:58:11 +0000530void Scheduler::setDefaultFrameRateCompatibility(Layer* layer) {
531 mLayerHistory.setDefaultFrameRateCompatibility(layer,
532 mFeatures.test(Feature::kContentDetection));
533}
534
Dominik Laskowski49cea512019-11-12 14:13:23 -0800535void Scheduler::chooseRefreshRateForContent() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400536 const auto selectorPtr = leaderSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400537 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800538
Ady Abraham8a82ba62020-01-17 12:43:17 -0800539 ATRACE_CALL();
540
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400541 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800542 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abrahama1a49af2019-02-07 14:36:55 -0800543}
544
Ana Krulecfb772822018-11-30 10:44:07 +0100545void Scheduler::resetIdleTimer() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400546 leaderSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800547}
548
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700549void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700550 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800551 mTouchTimer->reset();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400552 leaderSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800553 }
Ady Abraham8532d012019-05-08 14:50:56 -0700554}
555
Leon Scroggins III31d41412022-11-18 16:42:53 -0500556void Scheduler::setDisplayPowerMode(PhysicalDisplayId id, hal::PowerMode powerMode) {
557 const bool isLeader = [this, id]() REQUIRES(kMainThreadContext) {
558 ftl::FakeGuard guard(mDisplayLock);
559 return id == mLeaderDisplayId;
560 }();
561 if (isLeader) {
562 // TODO (b/255657128): This needs to be handled per display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700563 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700564 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700565 }
Leon Scroggins III31d41412022-11-18 16:42:53 -0500566 {
567 std::scoped_lock lock(mDisplayLock);
568 auto vsyncSchedule = getVsyncScheduleLocked(id);
569 vsyncSchedule->getController().setDisplayPowerMode(powerMode);
570 }
571 if (!isLeader) return;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700572
573 if (mDisplayPowerTimer) {
574 mDisplayPowerTimer->reset();
575 }
576
577 // Display Power event will boost the refresh rate to performance.
578 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700579 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700580}
581
Leon Scroggins III31d41412022-11-18 16:42:53 -0500582std::shared_ptr<const VsyncSchedule> Scheduler::getVsyncSchedule(
583 std::optional<PhysicalDisplayId> idOpt) const {
584 std::scoped_lock lock(mDisplayLock);
585 return getVsyncScheduleLocked(idOpt);
586}
587
588std::shared_ptr<const VsyncSchedule> Scheduler::getVsyncScheduleLocked(
589 std::optional<PhysicalDisplayId> idOpt) const {
590 ftl::FakeGuard guard(kMainThreadContext);
591 if (!idOpt) {
592 LOG_ALWAYS_FATAL_IF(!mLeaderDisplayId, "Missing a leader!");
593 idOpt = mLeaderDisplayId;
594 }
595 auto scheduleOpt = mVsyncSchedules.get(*idOpt);
596 LOG_ALWAYS_FATAL_IF(!scheduleOpt);
597 return std::const_pointer_cast<const VsyncSchedule>(scheduleOpt->get());
598}
599
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700600void Scheduler::kernelIdleTimerCallback(TimerState state) {
601 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100602
Ady Abraham2139f732019-11-13 18:56:40 -0800603 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
604 // magic number
Ady Abrahamace3d052022-11-17 16:25:05 -0800605 const Fps refreshRate = leaderSelectorPtr()->getActiveMode().modePtr->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700606
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700607 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
608 using namespace fps_approx_ops;
609
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800610 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700611 // If we're not in performance mode then the kernel timer shouldn't do
612 // anything, as the refresh rate during DPU power collapse will be the
613 // same.
Leon Scroggins III31d41412022-11-18 16:42:53 -0500614 resyncAllToHardwareVsync(true /* allowToEnable */);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800615 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700616 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
617 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700618 // need to update the VsyncController model anyway.
Leon Scroggins III31d41412022-11-18 16:42:53 -0500619 std::scoped_lock lock(mDisplayLock);
620 ftl::FakeGuard guard(kMainThreadContext);
621 constexpr bool disallow = false;
622 for (auto& [_, schedule] : mVsyncSchedules) {
623 schedule->disableHardwareVsync(mSchedulerCallback, disallow);
624 }
Alec Mouridc28b372019-04-18 21:17:13 -0700625 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800626
627 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700628}
629
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700630void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800631 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700632 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100633}
634
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700635void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700636 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700637 // Touch event will boost the refresh rate to performance.
638 // Clear layer history to get fresh FPS detection.
639 // NOTE: Instead of checking all the layers, we should be checking the layer
640 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800641 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700642 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700643 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700644 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700645}
646
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700647void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800648 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700649 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700650}
651
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400652void Scheduler::dump(utils::Dumper& dumper) const {
653 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700654
655 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400656 utils::Dumper::Section section(dumper, "Features"sv);
657
658 for (Feature feature : ftl::enum_range<Feature>()) {
659 if (const auto flagOpt = ftl::flag_name(feature)) {
660 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
661 }
662 }
663 }
664 {
665 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400666 {
667 std::scoped_lock lock(mDisplayLock);
668 ftl::FakeGuard guard(kMainThreadContext);
669 dumper.dump("leaderDisplayId"sv, mLeaderDisplayId);
670 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400671 dumper.dump("layerHistory"sv, mLayerHistory.dump());
672 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
673 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
674 }
675
676 mFrameRateOverrideMappings.dump(dumper);
677 dumper.eol();
Ana Krulecb43429d2019-01-09 14:28:51 -0800678}
679
Dominik Laskowski068173d2021-08-11 17:22:59 -0700680void Scheduler::dumpVsync(std::string& out) const {
Leon Scroggins III31d41412022-11-18 16:42:53 -0500681 std::scoped_lock lock(mDisplayLock);
682 ftl::FakeGuard guard(kMainThreadContext);
683 if (mLeaderDisplayId) {
684 base::StringAppendF(&out, "VsyncSchedule for leader %s:\n",
685 to_string(*mLeaderDisplayId).c_str());
686 getVsyncScheduleLocked()->dump(out);
687 }
688 for (auto& [id, vsyncSchedule] : mVsyncSchedules) {
689 if (id == mLeaderDisplayId) {
690 continue;
691 }
692 base::StringAppendF(&out, "VsyncSchedule for follower %s:\n", to_string(id).c_str());
693 vsyncSchedule->dump(out);
694 }
Ady Abraham8735eac2020-08-12 16:35:04 -0700695}
696
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800697bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400698 if (consideredSignals.idle) return false;
699
700 const auto frameRateOverrides =
701 leaderSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
702 displayRefreshRate, consideredSignals);
703
704 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
705 // the FrameRateOverrideMappings rather than here.
706 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
707}
708
709void Scheduler::promoteLeaderDisplay(std::optional<PhysicalDisplayId> leaderIdOpt) {
710 // TODO(b/241286431): Choose the leader display.
711 mLeaderDisplayId = leaderIdOpt.value_or(mRefreshRateSelectors.begin()->first);
712 ALOGI("Display %s is the leader", to_string(*mLeaderDisplayId).c_str());
713
Leon Scroggins III31d41412022-11-18 16:42:53 -0500714 auto vsyncSchedule = getVsyncScheduleLocked(*mLeaderDisplayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400715 if (const auto leaderPtr = leaderSelectorPtrLocked()) {
716 leaderPtr->setIdleTimerCallbacks(
717 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
718 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
719 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
720 .onExpired =
721 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
722
723 leaderPtr->startIdleTimer();
Leon Scroggins III31d41412022-11-18 16:42:53 -0500724
725 const Fps refreshRate = leaderPtr->getActiveMode().modePtr->getFps();
726 setVsyncPeriod(vsyncSchedule, refreshRate.getPeriodNsecs(), true /* force */);
727 }
728
729 updateVsyncRegistration(vsyncSchedule->getDispatch());
730 {
731 std::lock_guard<std::mutex> lock(mConnectionsLock);
732 for (auto& [_, connection] : mConnections) {
733 connection.thread->onNewVsyncSchedule(vsyncSchedule);
734 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800735 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400736}
737
738void Scheduler::demoteLeaderDisplay() {
739 // No need to lock for reads on kMainThreadContext.
740 if (const auto leaderPtr = FTL_FAKE_GUARD(mDisplayLock, leaderSelectorPtrLocked())) {
741 leaderPtr->stopIdleTimer();
742 leaderPtr->clearIdleTimerCallbacks();
743 }
744
745 // Clear state that depends on the leader's RefreshRateSelector.
746 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
774 // TODO(b/240743786): The leader display's mode must change for any DisplayModeRequest
775 // to go through. Fix this by tracking per-display Scheduler::Policy and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -0800776 std::tie(modeOpt, consideredSignals) =
Dominik Laskowski596a2562022-10-28 11:26:12 -0400777 modeChoices.get(*mLeaderDisplayId)
778 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800779 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400780 })
781 .value();
782 }
ramindani69b58e82022-09-26 16:48:36 -0700783
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400784 modeRequests.reserve(modeChoices.size());
785 for (auto& [id, choice] : modeChoices) {
786 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -0800787 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400788 .emitEvent = !choice.consideredSignals.idle});
789 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800790
Ady Abrahamace3d052022-11-17 16:25:05 -0800791 frameRateOverridesChanged = updateFrameRateOverrides(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400792
Ady Abrahamace3d052022-11-17 16:25:05 -0800793 if (mPolicy.modeOpt != modeOpt) {
794 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400795 refreshRateChanged = true;
796 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100797 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800798 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700799 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100800 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700801 }
Ady Abraham8532d012019-05-08 14:50:56 -0700802 }
Ady Abraham8532d012019-05-08 14:50:56 -0700803 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800804 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400805 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -0800806 }
807 if (frameRateOverridesChanged) {
808 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
809 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800810 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700811}
812
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400813auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800814 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -0700815
Ady Abraham68636062022-11-16 17:07:25 -0800816 using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400817 display::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -0400818
819 // Tallies the score of a refresh rate across `displayCount` displays.
820 struct RefreshRateTally {
821 explicit RefreshRateTally(float score) : score(score) {}
822
823 float score;
824 size_t displayCount = 1;
825 };
826
827 // Chosen to exceed a typical number of refresh rates across displays.
828 constexpr size_t kStaticCapacity = 8;
829 ftl::SmallMap<Fps, RefreshRateTally, kStaticCapacity, FpsApproxEqual> refreshRateTallies;
830
831 const auto globalSignals = makeGlobalSignals();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800832
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400833 for (const auto& [id, selectorPtr] : mRefreshRateSelectors) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800834 auto rankedFrameRates =
Ady Abraham68636062022-11-16 17:07:25 -0800835 selectorPtr->getRankedFrameRates(mPolicy.contentRequirements, globalSignals);
ramindani69b58e82022-09-26 16:48:36 -0700836
Ady Abrahamace3d052022-11-17 16:25:05 -0800837 for (const auto& [frameRateMode, score] : rankedFrameRates.ranking) {
838 const auto [it, inserted] = refreshRateTallies.try_emplace(frameRateMode.fps, score);
Dominik Laskowski01602522022-10-07 19:02:28 -0400839
840 if (!inserted) {
841 auto& tally = it->second;
842 tally.score += score;
843 tally.displayCount++;
844 }
845 }
846
Ady Abrahamace3d052022-11-17 16:25:05 -0800847 perDisplayRanking.push_back(std::move(rankedFrameRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400848 }
ramindani69b58e82022-09-26 16:48:36 -0700849
Dominik Laskowski01602522022-10-07 19:02:28 -0400850 auto maxScoreIt = refreshRateTallies.cbegin();
ramindani69b58e82022-09-26 16:48:36 -0700851
Dominik Laskowski01602522022-10-07 19:02:28 -0400852 // Find the first refresh rate common to all displays.
853 while (maxScoreIt != refreshRateTallies.cend() &&
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400854 maxScoreIt->second.displayCount != mRefreshRateSelectors.size()) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400855 ++maxScoreIt;
856 }
857
858 if (maxScoreIt != refreshRateTallies.cend()) {
859 // Choose the highest refresh rate common to all displays, if any.
860 for (auto it = maxScoreIt + 1; it != refreshRateTallies.cend(); ++it) {
861 const auto [fps, tally] = *it;
862
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400863 if (tally.displayCount == mRefreshRateSelectors.size() &&
864 tally.score > maxScoreIt->second.score) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400865 maxScoreIt = it;
866 }
ramindani7c487282022-10-10 16:17:51 -0700867 }
868 }
ramindani69b58e82022-09-26 16:48:36 -0700869
Dominik Laskowski01602522022-10-07 19:02:28 -0400870 const std::optional<Fps> chosenFps = maxScoreIt != refreshRateTallies.cend()
871 ? std::make_optional(maxScoreIt->first)
872 : std::nullopt;
873
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400874 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -0400875
ramindani69b58e82022-09-26 16:48:36 -0700876 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -0400877
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400878 for (auto& [ranking, signals] : perDisplayRanking) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400879 if (!chosenFps) {
Ady Abraham68636062022-11-16 17:07:25 -0800880 const auto& [frameRateMode, _] = ranking.front();
Ady Abrahamace3d052022-11-17 16:25:05 -0800881 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
882 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400883 continue;
884 }
885
Ady Abraham68636062022-11-16 17:07:25 -0800886 for (auto& [frameRateMode, _] : ranking) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800887 if (frameRateMode.fps == *chosenFps) {
888 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
889 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400890 break;
891 }
892 }
893 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400894 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -0700895}
896
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400897GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +0000898 const bool powerOnImminent = mDisplayPowerTimer &&
899 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
900 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700901
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400902 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
903 .idle = mPolicy.idleTimer == TimerState::Expired,
904 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800905}
906
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500907FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700908 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500909 const auto frameRateMode =
910 leaderSelectorPtr()
911 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
912 .ranking.front()
913 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400914
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500915 // Make sure the stored mode is up to date.
916 mPolicy.modeOpt = frameRateMode;
917
918 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700919}
920
Peiyong Line9d809e2020-04-14 13:10:48 -0700921void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800922 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
923 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
924
925 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
926 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
927 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
928 }
929}
930
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700931bool Scheduler::onPostComposition(nsecs_t presentTime) {
932 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
933 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
934 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
935 // We need to composite again as refreshTimeNanos is still in the future.
936 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700937 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700938
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700939 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800940 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700941 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800942}
943
Ady Abraham7825c682021-05-17 15:12:14 -0700944void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700945 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800946}
947
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800948void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
949 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
950 return;
951 }
952
953 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
954}
955
Ady Abraham62a0be22020-12-08 16:54:10 -0800956void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
957 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
958 return;
959 }
960
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800961 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -0800962}
963
Dominik Laskowski068173d2021-08-11 17:22:59 -0700964} // namespace android::scheduler