blob: ab8bff1a32878a62a9522bdb62c79423792c9277 [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>
Ady Abraham8f1ee7f2019-04-05 10:32:50 -070028#include <input/InputWindow.h>
Ana Krulecfefd6ae2019-02-13 17:53:08 -080029#include <system/window.h>
Ana Krulece588e312018-09-18 12:32:24 -070030#include <ui/DisplayStatInfo.h>
Ana Krulec3084c052018-11-21 20:27:17 +010031#include <utils/Timers.h>
Ana Krulec7ab56032018-11-02 20:51:06 +010032#include <utils/Trace.h>
Ana Krulec98b5b242018-08-10 15:03:23 -070033
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070034#include <FrameTimeline/FrameTimeline.h>
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -070035#include <algorithm>
36#include <cinttypes>
37#include <cstdint>
38#include <functional>
39#include <memory>
40#include <numeric>
41
42#include "../Layer.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070043#include "DispSyncSource.h"
44#include "EventThread.h"
Dominik Laskowski6505f792019-09-18 11:10:05 -070045#include "InjectVSyncSource.h"
Ana Krulecf2c006d2019-06-21 15:37:07 -070046#include "OneShotTimer.h"
Ana Krulec434c22d2018-11-28 13:48:36 +010047#include "SchedulerUtils.h"
Sundong Ahnd5e08f62018-12-12 20:27:28 +090048#include "SurfaceFlingerProperties.h"
Kevin DuBois00287382019-11-19 15:11:55 -080049#include "Timer.h"
50#include "VSyncDispatchTimerQueue.h"
51#include "VSyncPredictor.h"
52#include "VSyncReactor.h"
Ady Abraham8cb21882020-08-26 18:22:05 -070053#include "VsyncController.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070054
Dominik Laskowski98041832019-08-01 18:35:59 -070055#define RETURN_IF_INVALID_HANDLE(handle, ...) \
56 do { \
57 if (mConnections.count(handle) == 0) { \
58 ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
59 return __VA_ARGS__; \
60 } \
61 } while (false)
62
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070063using namespace std::string_literals;
64
Ana Krulec98b5b242018-08-10 15:03:23 -070065namespace android {
Ady Abraham5a858552020-03-31 17:54:56 -070066
Dominik Laskowski983f2b52020-06-25 16:54:06 -070067namespace {
Ana Krulec98b5b242018-08-10 15:03:23 -070068
Ady Abraham5a858552020-03-31 17:54:56 -070069std::unique_ptr<scheduler::VSyncTracker> createVSyncTracker() {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070070 // TODO(b/144707443): Tune constants.
71 constexpr int kDefaultRate = 60;
72 constexpr auto initialPeriod = std::chrono::duration<nsecs_t, std::ratio<1, kDefaultRate>>(1);
73 constexpr nsecs_t idealPeriod =
74 std::chrono::duration_cast<std::chrono::nanoseconds>(initialPeriod).count();
75 constexpr size_t vsyncTimestampHistorySize = 20;
76 constexpr size_t minimumSamplesForPrediction = 6;
77 constexpr uint32_t discardOutlierPercent = 20;
78 return std::make_unique<scheduler::VSyncPredictor>(idealPeriod, vsyncTimestampHistorySize,
79 minimumSamplesForPrediction,
80 discardOutlierPercent);
Ady Abraham5a858552020-03-31 17:54:56 -070081}
82
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070083std::unique_ptr<scheduler::VSyncDispatch> createVSyncDispatch(scheduler::VSyncTracker& tracker) {
84 // TODO(b/144707443): Tune constants.
85 constexpr std::chrono::nanoseconds vsyncMoveThreshold = 3ms;
86 constexpr std::chrono::nanoseconds timerSlack = 500us;
Ady Abraham5a858552020-03-31 17:54:56 -070087 return std::make_unique<
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070088 scheduler::VSyncDispatchTimerQueue>(std::make_unique<scheduler::Timer>(), tracker,
Ady Abraham5a858552020-03-31 17:54:56 -070089 timerSlack.count(), vsyncMoveThreshold.count());
90}
91
Marin Shalamanov27fa3de2020-11-20 16:22:48 +010092const char* toContentDetectionString(bool useContentDetection) {
93 return useContentDetection ? "on" : "off";
Dominik Laskowski983f2b52020-06-25 16:54:06 -070094}
95
96} // namespace
97
Ady Abraham8735eac2020-08-12 16:35:04 -070098class PredictedVsyncTracer {
99public:
100 PredictedVsyncTracer(scheduler::VSyncDispatch& dispatch)
101 : mRegistration(dispatch, std::bind(&PredictedVsyncTracer::callback, this),
102 "PredictedVsyncTracer") {
103 scheduleRegistration();
104 }
105
106private:
107 TracedOrdinal<bool> mParity = {"VSYNC-predicted", 0};
108 scheduler::VSyncCallbackRegistration mRegistration;
109
110 void scheduleRegistration() { mRegistration.schedule({0, 0, 0}); }
111
112 void callback() {
113 mParity = !mParity;
114 scheduleRegistration();
115 }
116};
117
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700118Scheduler::Scheduler(const scheduler::RefreshRateConfigs& configs, ISchedulerCallback& callback)
119 : Scheduler(configs, callback,
120 {.supportKernelTimer = sysprop::support_kernel_idle_timer(false),
Marin Shalamanov27fa3de2020-11-20 16:22:48 +0100121 .useContentDetection = sysprop::use_content_detection_for_refresh_rate(false)}) {
122}
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700123
124Scheduler::Scheduler(const scheduler::RefreshRateConfigs& configs, ISchedulerCallback& callback,
125 Options options)
Ady Abraham8cb21882020-08-26 18:22:05 -0700126 : Scheduler(createVsyncSchedule(options.supportKernelTimer), configs, callback,
Marin Shalamanov27fa3de2020-11-20 16:22:48 +0100127 createLayerHistory(configs), options) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700128 using namespace sysprop;
Ady Abraham8532d012019-05-08 14:50:56 -0700129
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700130 const int setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms"s, 0);
Ana Krulecfb772822018-11-30 10:44:07 +0100131
Dominik Laskowski98041832019-08-01 18:35:59 -0700132 if (const auto millis = setIdleTimerMs ? setIdleTimerMs : set_idle_timer_ms(0); millis > 0) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700133 const auto callback = mOptions.supportKernelTimer ? &Scheduler::kernelIdleTimerCallback
134 : &Scheduler::idleTimerCallback;
Dominik Laskowski98041832019-08-01 18:35:59 -0700135 mIdleTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800136 "IdleTimer", std::chrono::milliseconds(millis),
Dominik Laskowski98041832019-08-01 18:35:59 -0700137 [this, callback] { std::invoke(callback, this, TimerState::Reset); },
138 [this, callback] { std::invoke(callback, this, TimerState::Expired); });
Ana Krulecfb772822018-11-30 10:44:07 +0100139 mIdleTimer->start();
140 }
Ady Abraham8532d012019-05-08 14:50:56 -0700141
Dominik Laskowski98041832019-08-01 18:35:59 -0700142 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -0700143 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -0700144 mTouchTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800145 "TouchTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700146 [this] { touchTimerCallback(TimerState::Reset); },
147 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -0700148 mTouchTimer->start();
149 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700150
Dominik Laskowski98041832019-08-01 18:35:59 -0700151 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
152 mDisplayPowerTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800153 "DisplayPowerTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700154 [this] { displayPowerTimerCallback(TimerState::Reset); },
155 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700156 mDisplayPowerTimer->start();
157 }
Ana Krulece588e312018-09-18 12:32:24 -0700158}
159
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700160Scheduler::Scheduler(VsyncSchedule schedule, const scheduler::RefreshRateConfigs& configs,
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700161 ISchedulerCallback& schedulerCallback,
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700162 std::unique_ptr<LayerHistory> layerHistory, Options options)
163 : mOptions(options),
164 mVsyncSchedule(std::move(schedule)),
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700165 mLayerHistory(std::move(layerHistory)),
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800166 mSchedulerCallback(schedulerCallback),
Ady Abraham8735eac2020-08-12 16:35:04 -0700167 mRefreshRateConfigs(configs),
168 mPredictedVsyncTracer(
169 base::GetBoolProperty("debug.sf.show_predicted_vsync", false)
170 ? std::make_unique<PredictedVsyncTracer>(*mVsyncSchedule.dispatch)
171 : nullptr) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700172 mSchedulerCallback.setVsyncEnabled(false);
173}
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700174
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800175Scheduler::~Scheduler() {
Ana Krulecf2c006d2019-06-21 15:37:07 -0700176 // Ensure the OneShotTimer threads are joined before we start destroying state.
Ady Abraham6fe2c172019-07-12 12:37:57 -0700177 mDisplayPowerTimer.reset();
Ady Abraham8532d012019-05-08 14:50:56 -0700178 mTouchTimer.reset();
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800179 mIdleTimer.reset();
180}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700181
Ady Abraham8cb21882020-08-26 18:22:05 -0700182Scheduler::VsyncSchedule Scheduler::createVsyncSchedule(bool supportKernelTimer) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700183 auto clock = std::make_unique<scheduler::SystemClock>();
184 auto tracker = createVSyncTracker();
185 auto dispatch = createVSyncDispatch(*tracker);
186
187 // TODO(b/144707443): Tune constants.
188 constexpr size_t pendingFenceLimit = 20;
Ady Abraham8cb21882020-08-26 18:22:05 -0700189 auto controller =
Ady Abraham8735eac2020-08-12 16:35:04 -0700190 std::make_unique<scheduler::VSyncReactor>(std::move(clock), *tracker, pendingFenceLimit,
Ady Abraham8cb21882020-08-26 18:22:05 -0700191 supportKernelTimer);
192 return {std::move(controller), std::move(tracker), std::move(dispatch)};
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700193}
194
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700195std::unique_ptr<LayerHistory> Scheduler::createLayerHistory(
Marin Shalamanov27fa3de2020-11-20 16:22:48 +0100196 const scheduler::RefreshRateConfigs& configs) {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700197 if (!configs.canSwitch()) return nullptr;
198
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100199 return std::make_unique<scheduler::LayerHistory>(configs);
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700200}
201
Ady Abraham9c53ee72020-07-22 21:16:18 -0700202std::unique_ptr<VSyncSource> Scheduler::makePrimaryDispSyncSource(
203 const char* name, std::chrono::nanoseconds workDuration,
204 std::chrono::nanoseconds readyDuration, bool traceVsync) {
205 return std::make_unique<scheduler::DispSyncSource>(*mVsyncSchedule.dispatch, workDuration,
206 readyDuration, traceVsync, name);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700207}
208
Ady Abraham2c6716b2020-12-08 16:54:10 -0800209std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
210 std::lock_guard lock(mFeatureStateLock);
211 {
212 const auto iter = mFrameRateOverridesFromBackdoor.find(uid);
213 if (iter != mFrameRateOverridesFromBackdoor.end()) {
214 return std::make_optional<Fps>(iter->second);
215 }
216 }
217
218 {
219 const auto iter = mFeatures.frameRateOverrides.find(uid);
220 if (iter != mFeatures.frameRateOverrides.end()) {
221 return std::make_optional<Fps>(iter->second);
222 }
223 }
224
225 return std::nullopt;
226}
227
Ady Abraham0bb6a472020-10-12 10:22:13 -0700228bool Scheduler::isVsyncValid(nsecs_t expectedVsyncTimestamp, uid_t uid) const {
Ady Abraham2c6716b2020-12-08 16:54:10 -0800229 const auto frameRate = getFrameRateOverride(uid);
230 if (!frameRate.has_value()) {
231 return true;
232 }
233
234 const auto divider = mRefreshRateConfigs.getRefreshRateDivider(*frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700235 if (divider <= 1) {
236 return true;
237 }
238
239 return mVsyncSchedule.tracker->isVSyncInPhase(expectedVsyncTimestamp, divider);
240}
241
Dominik Laskowski98041832019-08-01 18:35:59 -0700242Scheduler::ConnectionHandle Scheduler::createConnection(
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700243 const char* connectionName, frametimeline::TokenManager* tokenManager,
244 std::chrono::nanoseconds workDuration, std::chrono::nanoseconds readyDuration,
Ana Krulec98b5b242018-08-10 15:03:23 -0700245 impl::EventThread::InterceptVSyncsCallback interceptCallback) {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700246 auto vsyncSource = makePrimaryDispSyncSource(connectionName, workDuration, readyDuration);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700247 auto throttleVsync = [this](nsecs_t expectedVsyncTimestamp, uid_t uid) {
248 return !isVsyncValid(expectedVsyncTimestamp, uid);
249 };
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700250 auto eventThread = std::make_unique<impl::EventThread>(std::move(vsyncSource), tokenManager,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700251 std::move(interceptCallback),
252 std::move(throttleVsync));
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700253 return createConnection(std::move(eventThread));
Dominik Laskowski98041832019-08-01 18:35:59 -0700254}
Ana Krulec98b5b242018-08-10 15:03:23 -0700255
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700256Scheduler::ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700257 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
258 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800259
Ady Abraham62f216c2020-10-13 19:07:23 -0700260 auto connection = createConnectionInternal(eventThread.get());
Dominik Laskowski98041832019-08-01 18:35:59 -0700261
Ana Krulec6ddd2612020-09-24 13:06:33 -0700262 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700263 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
264 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700265}
266
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700267sp<EventThreadConnection> Scheduler::createConnectionInternal(
Ady Abraham62f216c2020-10-13 19:07:23 -0700268 EventThread* eventThread, ISurfaceComposer::EventRegistrationFlags eventRegistration) {
269 return eventThread->createEventConnection([&] { resync(); }, eventRegistration);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700270}
271
Ana Krulec98b5b242018-08-10 15:03:23 -0700272sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Ady Abraham62f216c2020-10-13 19:07:23 -0700273 ConnectionHandle handle, ISurfaceComposer::EventRegistrationFlags eventRegistration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700274 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700275 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Ady Abraham62f216c2020-10-13 19:07:23 -0700276 return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700277}
278
Dominik Laskowski98041832019-08-01 18:35:59 -0700279sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700280 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700281 RETURN_IF_INVALID_HANDLE(handle, nullptr);
282 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700283}
284
Dominik Laskowski98041832019-08-01 18:35:59 -0700285void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
286 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700287 android::EventThread* thread;
288 {
289 std::lock_guard<std::mutex> lock(mConnectionsLock);
290 RETURN_IF_INVALID_HANDLE(handle);
291 thread = mConnections[handle].thread.get();
292 }
293
294 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700295}
296
Dominik Laskowski98041832019-08-01 18:35:59 -0700297void Scheduler::onScreenAcquired(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700298 android::EventThread* thread;
299 {
300 std::lock_guard<std::mutex> lock(mConnectionsLock);
301 RETURN_IF_INVALID_HANDLE(handle);
302 thread = mConnections[handle].thread.get();
303 }
304 thread->onScreenAcquired();
Ana Krulec98b5b242018-08-10 15:03:23 -0700305}
306
Dominik Laskowski98041832019-08-01 18:35:59 -0700307void Scheduler::onScreenReleased(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700308 android::EventThread* thread;
309 {
310 std::lock_guard<std::mutex> lock(mConnectionsLock);
311 RETURN_IF_INVALID_HANDLE(handle);
312 thread = mConnections[handle].thread.get();
313 }
314 thread->onScreenReleased();
Ana Krulec98b5b242018-08-10 15:03:23 -0700315}
316
Ady Abraham2c6716b2020-12-08 16:54:10 -0800317void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
318 std::vector<FrameRateOverride> overrides;
319 {
320 std::lock_guard<std::mutex> lock(mFeatureStateLock);
321 for (const auto& [uid, frameRate] : mFrameRateOverridesFromBackdoor) {
322 overrides.emplace_back(FrameRateOverride{uid, frameRate.getValue()});
323 }
324 for (const auto& [uid, frameRate] : mFeatures.frameRateOverrides) {
325 if (mFrameRateOverridesFromBackdoor.count(uid) == 0) {
326 overrides.emplace_back(FrameRateOverride{uid, frameRate.getValue()});
327 }
328 }
329 }
Ady Abraham62f216c2020-10-13 19:07:23 -0700330 android::EventThread* thread;
331 {
332 std::lock_guard<std::mutex> lock(mConnectionsLock);
333 RETURN_IF_INVALID_HANDLE(handle);
334 thread = mConnections[handle].thread.get();
335 }
336 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
337}
338
Ady Abrahamdfd62162020-06-10 16:11:56 -0700339void Scheduler::onPrimaryDisplayConfigChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
340 HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
Ady Abraham2c6716b2020-12-08 16:54:10 -0800341 {
342 std::lock_guard<std::mutex> lock(mFeatureStateLock);
343 // Cache the last reported config for primary display.
344 mFeatures.cachedConfigChangedParams = {handle, displayId, configId, vsyncPeriod};
345 }
Ady Abrahamdfd62162020-06-10 16:11:56 -0700346 onNonPrimaryDisplayConfigChanged(handle, displayId, configId, vsyncPeriod);
347}
348
349void Scheduler::dispatchCachedReportedConfig() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700350 // Check optional fields first.
351 if (!mFeatures.configId.has_value()) {
352 ALOGW("No config ID found, not dispatching cached config.");
353 return;
354 }
355 if (!mFeatures.cachedConfigChangedParams.has_value()) {
356 ALOGW("No config changed params found, not dispatching cached config.");
357 return;
358 }
359
Ady Abrahamdfd62162020-06-10 16:11:56 -0700360 const auto configId = *mFeatures.configId;
361 const auto vsyncPeriod =
362 mRefreshRateConfigs.getRefreshRateFromConfigId(configId).getVsyncPeriod();
363
364 // If there is no change from cached config, there is no need to dispatch an event
365 if (configId == mFeatures.cachedConfigChangedParams->configId &&
366 vsyncPeriod == mFeatures.cachedConfigChangedParams->vsyncPeriod) {
367 return;
368 }
369
370 mFeatures.cachedConfigChangedParams->configId = configId;
371 mFeatures.cachedConfigChangedParams->vsyncPeriod = vsyncPeriod;
372 onNonPrimaryDisplayConfigChanged(mFeatures.cachedConfigChangedParams->handle,
373 mFeatures.cachedConfigChangedParams->displayId,
374 mFeatures.cachedConfigChangedParams->configId,
375 mFeatures.cachedConfigChangedParams->vsyncPeriod);
376}
377
378void Scheduler::onNonPrimaryDisplayConfigChanged(ConnectionHandle handle,
379 PhysicalDisplayId displayId,
380 HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700381 android::EventThread* thread;
382 {
383 std::lock_guard<std::mutex> lock(mConnectionsLock);
384 RETURN_IF_INVALID_HANDLE(handle);
385 thread = mConnections[handle].thread.get();
386 }
387 thread->onConfigChanged(displayId, configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800388}
389
Alec Mouri717bcb62020-02-10 17:07:19 -0800390size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700391 std::lock_guard<std::mutex> lock(mConnectionsLock);
Alec Mouri717bcb62020-02-10 17:07:19 -0800392 RETURN_IF_INVALID_HANDLE(handle, 0);
393 return mConnections[handle].thread->getEventThreadConnectionCount();
394}
395
Dominik Laskowski98041832019-08-01 18:35:59 -0700396void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700397 android::EventThread* thread;
398 {
399 std::lock_guard<std::mutex> lock(mConnectionsLock);
400 RETURN_IF_INVALID_HANDLE(handle);
401 thread = mConnections.at(handle).thread.get();
402 }
403 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700404}
405
Ady Abraham9c53ee72020-07-22 21:16:18 -0700406void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
407 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700408 android::EventThread* thread;
409 {
410 std::lock_guard<std::mutex> lock(mConnectionsLock);
411 RETURN_IF_INVALID_HANDLE(handle);
412 thread = mConnections[handle].thread.get();
413 }
414 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700415}
Ana Krulece588e312018-09-18 12:32:24 -0700416
Ady Abraham8cb21882020-08-26 18:22:05 -0700417void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats, nsecs_t now) {
418 stats->vsyncTime = mVsyncSchedule.tracker->nextAnticipatedVSyncTimeFrom(now);
419 stats->vsyncPeriod = mVsyncSchedule.tracker->currentPeriod();
Ana Krulece588e312018-09-18 12:32:24 -0700420}
421
Dominik Laskowski6505f792019-09-18 11:10:05 -0700422Scheduler::ConnectionHandle Scheduler::enableVSyncInjection(bool enable) {
423 if (mInjectVSyncs == enable) {
424 return {};
425 }
426
427 ALOGV("%s VSYNC injection", enable ? "Enabling" : "Disabling");
428
429 if (!mInjectorConnectionHandle) {
430 auto vsyncSource = std::make_unique<InjectVSyncSource>();
431 mVSyncInjector = vsyncSource.get();
432
433 auto eventThread =
434 std::make_unique<impl::EventThread>(std::move(vsyncSource),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700435 /*tokenManager=*/nullptr,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700436 impl::EventThread::InterceptVSyncsCallback(),
437 impl::EventThread::ThrottleVsyncCallback());
Dominik Laskowski6505f792019-09-18 11:10:05 -0700438
Dominik Laskowski208235c2020-12-03 15:38:51 -0800439 // EventThread does not dispatch VSYNC unless the display is connected and powered on.
440 eventThread->onHotplugReceived(PhysicalDisplayId::fromPort(0), true);
441 eventThread->onScreenAcquired();
442
Dominik Laskowski6505f792019-09-18 11:10:05 -0700443 mInjectorConnectionHandle = createConnection(std::move(eventThread));
444 }
445
446 mInjectVSyncs = enable;
447 return mInjectorConnectionHandle;
448}
449
Ady Abraham9c53ee72020-07-22 21:16:18 -0700450bool Scheduler::injectVSync(nsecs_t when, nsecs_t expectedVSyncTime, nsecs_t deadlineTimestamp) {
Dominik Laskowski6505f792019-09-18 11:10:05 -0700451 if (!mInjectVSyncs || !mVSyncInjector) {
452 return false;
453 }
454
Ady Abraham9c53ee72020-07-22 21:16:18 -0700455 mVSyncInjector->onInjectSyncEvent(when, expectedVSyncTime, deadlineTimestamp);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700456 return true;
457}
458
Ana Krulece588e312018-09-18 12:32:24 -0700459void Scheduler::enableHardwareVsync() {
460 std::lock_guard<std::mutex> lock(mHWVsyncLock);
461 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700462 mVsyncSchedule.tracker->resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700463 mSchedulerCallback.setVsyncEnabled(true);
Ana Krulece588e312018-09-18 12:32:24 -0700464 mPrimaryHWVsyncEnabled = true;
465 }
466}
467
468void Scheduler::disableHardwareVsync(bool makeUnavailable) {
469 std::lock_guard<std::mutex> lock(mHWVsyncLock);
470 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700471 mSchedulerCallback.setVsyncEnabled(false);
Ana Krulece588e312018-09-18 12:32:24 -0700472 mPrimaryHWVsyncEnabled = false;
473 }
474 if (makeUnavailable) {
475 mHWVsyncAvailable = false;
476 }
477}
478
Ana Krulecc2870422019-01-29 19:00:58 -0800479void Scheduler::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
480 {
481 std::lock_guard<std::mutex> lock(mHWVsyncLock);
482 if (makeAvailable) {
483 mHWVsyncAvailable = makeAvailable;
484 } else if (!mHWVsyncAvailable) {
485 // Hardware vsync is not currently available, so abort the resync
486 // attempt for now
487 return;
488 }
489 }
490
491 if (period <= 0) {
492 return;
493 }
494
495 setVsyncPeriod(period);
496}
497
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700498void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700499 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800500
501 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700502 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800503
504 if (now - last > kIgnoreDelay) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700505 resyncToHardwareVsync(false, mRefreshRateConfigs.getCurrentRefreshRate().getVsyncPeriod());
Ana Krulecc2870422019-01-29 19:00:58 -0800506 }
507}
508
Dominik Laskowski98041832019-08-01 18:35:59 -0700509void Scheduler::setVsyncPeriod(nsecs_t period) {
Ady Abraham3aff9172019-02-07 19:10:26 -0800510 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Ady Abraham8cb21882020-08-26 18:22:05 -0700511 mVsyncSchedule.controller->startPeriodTransition(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800512
513 if (!mPrimaryHWVsyncEnabled) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700514 mVsyncSchedule.tracker->resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700515 mSchedulerCallback.setVsyncEnabled(true);
Ady Abraham3aff9172019-02-07 19:10:26 -0800516 mPrimaryHWVsyncEnabled = true;
517 }
Ana Krulece588e312018-09-18 12:32:24 -0700518}
519
Ady Abraham5dee2f12020-02-05 17:49:47 -0800520void Scheduler::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
521 bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700522 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700523 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700524 { // Scope for the lock
525 std::lock_guard<std::mutex> lock(mHWVsyncLock);
526 if (mPrimaryHWVsyncEnabled) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700527 needsHwVsync = mVsyncSchedule.controller->addHwVsyncTimestamp(timestamp, hwcVsyncPeriod,
528 periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700529 }
530 }
531
532 if (needsHwVsync) {
533 enableHardwareVsync();
534 } else {
535 disableHardwareVsync(false);
536 }
537}
538
539void Scheduler::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700540 if (mVsyncSchedule.controller->addPresentFence(fenceTime)) {
Ana Krulece588e312018-09-18 12:32:24 -0700541 enableHardwareVsync();
542 } else {
543 disableHardwareVsync(false);
544 }
545}
546
547void Scheduler::setIgnorePresentFences(bool ignore) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700548 mVsyncSchedule.controller->setIgnorePresentFences(ignore);
Ady Abrahamc3e21312019-02-07 14:30:23 -0800549}
550
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700551void Scheduler::registerLayer(Layer* layer) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800552 if (!mLayerHistory) return;
553
Michael Wright44753b12020-07-08 13:48:11 +0100554 if (layer->getWindowType() == InputWindowInfo::Type::STATUS_BAR) {
Marin Shalamanov4ad8b302020-12-11 15:50:08 +0100555 mLayerHistory->registerLayer(layer, scheduler::LayerHistory::LayerVoteType::NoVote);
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700556 } else if (!mOptions.useContentDetection) {
Steven Thomasdebafed2020-05-18 17:30:35 -0700557 // If the content detection feature is off, all layers are registered at Max. We still keep
558 // the layer history, since we use it for other features (like Frame Rate API), so layers
559 // still need to be registered.
Marin Shalamanov4ad8b302020-12-11 15:50:08 +0100560 mLayerHistory->registerLayer(layer, scheduler::LayerHistory::LayerVoteType::Max);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800561 } else {
Michael Wright44753b12020-07-08 13:48:11 +0100562 if (layer->getWindowType() == InputWindowInfo::Type::WALLPAPER) {
Ana Krulec3d367c82020-02-25 15:02:01 -0800563 // Running Wallpaper at Min is considered as part of content detection.
Marin Shalamanov4ad8b302020-12-11 15:50:08 +0100564 mLayerHistory->registerLayer(layer, scheduler::LayerHistory::LayerVoteType::Min);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800565 } else {
Marin Shalamanov4ad8b302020-12-11 15:50:08 +0100566 mLayerHistory->registerLayer(layer, scheduler::LayerHistory::LayerVoteType::Heuristic);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800567 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800568 }
Ady Abraham09bd3922019-04-08 10:44:56 -0700569}
570
Ady Abraham5def7332020-05-29 16:13:47 -0700571void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime,
572 LayerHistory::LayerUpdateType updateType) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800573 if (mLayerHistory) {
Ady Abraham5def7332020-05-29 16:13:47 -0700574 mLayerHistory->record(layer, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800575 }
Ana Krulec3084c052018-11-21 20:27:17 +0100576}
577
Ady Abraham32efd542020-05-19 17:49:26 -0700578void Scheduler::setConfigChangePending(bool pending) {
579 if (mLayerHistory) {
580 mLayerHistory->setConfigChangePending(pending);
581 }
582}
583
Dominik Laskowski49cea512019-11-12 14:13:23 -0800584void Scheduler::chooseRefreshRateForContent() {
585 if (!mLayerHistory) return;
586
Ady Abraham8a82ba62020-01-17 12:43:17 -0800587 ATRACE_CALL();
588
589 scheduler::LayerHistory::Summary summary = mLayerHistory->summarize(systemTime());
Ady Abraham2c6716b2020-12-08 16:54:10 -0800590 scheduler::RefreshRateConfigs::GlobalSignals consideredSignals;
Ady Abraham2139f732019-11-13 18:56:40 -0800591 HwcConfigIndexType newConfigId;
Ady Abraham2c6716b2020-12-08 16:54:10 -0800592 bool frameRateChanged;
593 bool frameRateOverridesChanged;
Ady Abraham6398a0a2019-04-18 19:30:44 -0700594 {
595 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800596 if (mFeatures.contentRequirements == summary) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700597 return;
598 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800599 mFeatures.contentRequirements = summary;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800600
Ady Abrahamdfd62162020-06-10 16:11:56 -0700601 newConfigId = calculateRefreshRateConfigIndexType(&consideredSignals);
Ady Abraham2c6716b2020-12-08 16:54:10 -0800602 auto& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
603 frameRateOverridesChanged =
604 updateFrameRateOverrides(consideredSignals, newRefreshRate.getFps());
605
Ady Abraham2139f732019-11-13 18:56:40 -0800606 if (mFeatures.configId == newConfigId) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700607 // We don't need to change the config, but we might need to send an event
608 // about a config change, since it was suppressed due to a previous idleConsidered
609 if (!consideredSignals.idle) {
610 dispatchCachedReportedConfig();
611 }
Ady Abraham2c6716b2020-12-08 16:54:10 -0800612 frameRateChanged = false;
613 } else {
614 mFeatures.configId = newConfigId;
615 frameRateChanged = true;
Ady Abraham6398a0a2019-04-18 19:30:44 -0700616 }
Ady Abraham2c6716b2020-12-08 16:54:10 -0800617 }
618 if (frameRateChanged) {
Ady Abraham2e1dd892020-03-05 13:48:36 -0800619 auto& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700620 mSchedulerCallback.changeRefreshRate(newRefreshRate,
621 consideredSignals.idle ? ConfigEvent::None
622 : ConfigEvent::Changed);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800623 }
Ady Abraham2c6716b2020-12-08 16:54:10 -0800624 if (frameRateOverridesChanged) {
625 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
626 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800627}
628
Ana Krulecfb772822018-11-30 10:44:07 +0100629void Scheduler::resetIdleTimer() {
630 if (mIdleTimer) {
631 mIdleTimer->reset();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800632 }
633}
634
Ady Abraham8532d012019-05-08 14:50:56 -0700635void Scheduler::notifyTouchEvent() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700636 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800637 mTouchTimer->reset();
Steven Thomas540730a2020-01-08 20:12:42 -0800638
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700639 if (mOptions.supportKernelTimer && mIdleTimer) {
Steven Thomas540730a2020-01-08 20:12:42 -0800640 mIdleTimer->reset();
641 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800642 }
Ady Abraham8532d012019-05-08 14:50:56 -0700643}
644
Ady Abraham6fe2c172019-07-12 12:37:57 -0700645void Scheduler::setDisplayPowerState(bool normal) {
646 {
647 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700648 mFeatures.isDisplayPowerStateNormal = normal;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700649 }
650
651 if (mDisplayPowerTimer) {
652 mDisplayPowerTimer->reset();
653 }
654
655 // Display Power event will boost the refresh rate to performance.
656 // Clear Layer History to get fresh FPS detection
Dominik Laskowski49cea512019-11-12 14:13:23 -0800657 if (mLayerHistory) {
658 mLayerHistory->clear();
659 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700660}
661
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700662void Scheduler::kernelIdleTimerCallback(TimerState state) {
663 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100664
Ady Abraham2139f732019-11-13 18:56:40 -0800665 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
666 // magic number
Ady Abraham2e1dd892020-03-05 13:48:36 -0800667 const auto& refreshRate = mRefreshRateConfigs.getCurrentRefreshRate();
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100668 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER{65.0f};
669 if (state == TimerState::Reset &&
670 refreshRate.getFps().greaterThanWithMargin(FPS_THRESHOLD_FOR_KERNEL_TIMER)) {
Alec Mouri7f015182019-07-11 13:56:22 -0700671 // If we're not in performance mode then the kernel timer shouldn't do
672 // anything, as the refresh rate during DPU power collapse will be the
673 // same.
Ady Abrahamabc27602020-04-08 17:20:29 -0700674 resyncToHardwareVsync(true /* makeAvailable */, refreshRate.getVsyncPeriod());
675 } else if (state == TimerState::Expired &&
Marin Shalamanove8a663d2020-11-24 17:48:00 +0100676 refreshRate.getFps().lessThanOrEqualWithMargin(FPS_THRESHOLD_FOR_KERNEL_TIMER)) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700677 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
678 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700679 // need to update the VsyncController model anyway.
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700680 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700681 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800682
683 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700684}
685
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700686void Scheduler::idleTimerCallback(TimerState state) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700687 handleTimerStateChanged(&mFeatures.idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700688 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100689}
690
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700691void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700692 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700693 // Touch event will boost the refresh rate to performance.
694 // Clear layer history to get fresh FPS detection.
695 // NOTE: Instead of checking all the layers, we should be checking the layer
696 // that is currently on top. b/142507166 will give us this capability.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700697 if (handleTimerStateChanged(&mFeatures.touch, touch)) {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700698 if (mLayerHistory) {
699 mLayerHistory->clear();
700 }
Ady Abraham1adbb722020-05-15 11:51:48 -0700701 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700702 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700703}
704
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700705void Scheduler::displayPowerTimerCallback(TimerState state) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700706 handleTimerStateChanged(&mFeatures.displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700707 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700708}
709
Dominik Laskowski98041832019-08-01 18:35:59 -0700710void Scheduler::dump(std::string& result) const {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800711 using base::StringAppendF;
Dominik Laskowski98041832019-08-01 18:35:59 -0700712
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700713 StringAppendF(&result, "+ Idle timer: %s\n", mIdleTimer ? mIdleTimer->dump().c_str() : "off");
Ana Krulec3d367c82020-02-25 15:02:01 -0800714 StringAppendF(&result, "+ Touch timer: %s\n",
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700715 mTouchTimer ? mTouchTimer->dump().c_str() : "off");
716 StringAppendF(&result, "+ Content detection: %s %s\n\n",
Marin Shalamanov27fa3de2020-11-20 16:22:48 +0100717 toContentDetectionString(mOptions.useContentDetection),
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700718 mLayerHistory ? mLayerHistory->dump().c_str() : "(no layer history)");
Ady Abraham2c6716b2020-12-08 16:54:10 -0800719
720 {
721 std::lock_guard lock(mFeatureStateLock);
722 StringAppendF(&result, "Frame Rate Overrides (backdoor): {");
723 for (const auto& [uid, frameRate] : mFrameRateOverridesFromBackdoor) {
724 StringAppendF(&result, "[uid: %d frameRate: %s], ", uid, to_string(frameRate).c_str());
725 }
726 StringAppendF(&result, "}\n");
727
728 StringAppendF(&result, "Frame Rate Overrides (setFrameRate): {");
729 for (const auto& [uid, frameRate] : mFeatures.frameRateOverrides) {
730 StringAppendF(&result, "[uid: %d frameRate: %s], ", uid, to_string(frameRate).c_str());
731 }
732 StringAppendF(&result, "}\n");
733 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800734}
735
Ady Abraham8cb21882020-08-26 18:22:05 -0700736void Scheduler::dumpVsync(std::string& s) const {
Ady Abraham8735eac2020-08-12 16:35:04 -0700737 using base::StringAppendF;
738
739 StringAppendF(&s, "VSyncReactor:\n");
Ady Abraham8cb21882020-08-26 18:22:05 -0700740 mVsyncSchedule.controller->dump(s);
Ady Abraham8735eac2020-08-12 16:35:04 -0700741 StringAppendF(&s, "VSyncDispatch:\n");
742 mVsyncSchedule.dispatch->dump(s);
743}
744
Ady Abraham2c6716b2020-12-08 16:54:10 -0800745bool Scheduler::updateFrameRateOverrides(
746 scheduler::RefreshRateConfigs::GlobalSignals consideredSignals, Fps displayRefreshRate) {
747 if (consideredSignals.touch) {
748 const bool changed = !mFeatures.frameRateOverrides.empty();
749 mFeatures.frameRateOverrides.clear();
750 return changed;
751 }
752
753 if (!consideredSignals.idle) {
754 const auto frameRateOverrides =
755 mRefreshRateConfigs.getFrameRateOverrides(mFeatures.contentRequirements,
756 displayRefreshRate);
757 if (!std::equal(mFeatures.frameRateOverrides.begin(), mFeatures.frameRateOverrides.end(),
758 frameRateOverrides.begin(), frameRateOverrides.end(),
759 [](const std::pair<uid_t, Fps>& a, const std::pair<uid_t, Fps>& b) {
760 return a.first == b.first && a.second.equalsWithMargin(b.second);
761 })) {
762 mFeatures.frameRateOverrides = frameRateOverrides;
763 return true;
764 }
765 }
766 return false;
767}
768
Ady Abraham6fe2c172019-07-12 12:37:57 -0700769template <class T>
Ady Abrahamdfd62162020-06-10 16:11:56 -0700770bool Scheduler::handleTimerStateChanged(T* currentState, T newState) {
Ady Abraham2139f732019-11-13 18:56:40 -0800771 HwcConfigIndexType newConfigId;
Ady Abraham2c6716b2020-12-08 16:54:10 -0800772 bool refreshRateChanged = false;
773 bool frameRateOverridesChanged;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700774 scheduler::RefreshRateConfigs::GlobalSignals consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700775 {
776 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700777 if (*currentState == newState) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700778 return false;
Ady Abraham8532d012019-05-08 14:50:56 -0700779 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700780 *currentState = newState;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700781 newConfigId = calculateRefreshRateConfigIndexType(&consideredSignals);
Ady Abraham2c6716b2020-12-08 16:54:10 -0800782 const RefreshRate& newRefreshRate =
783 mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
784 frameRateOverridesChanged =
785 updateFrameRateOverrides(consideredSignals, newRefreshRate.getFps());
Ady Abraham2139f732019-11-13 18:56:40 -0800786 if (mFeatures.configId == newConfigId) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700787 // We don't need to change the config, but we might need to send an event
788 // about a config change, since it was suppressed due to a previous idleConsidered
789 if (!consideredSignals.idle) {
790 dispatchCachedReportedConfig();
791 }
Ady Abraham2c6716b2020-12-08 16:54:10 -0800792 } else {
793 mFeatures.configId = newConfigId;
794 refreshRateChanged = true;
Ady Abraham8532d012019-05-08 14:50:56 -0700795 }
Ady Abraham8532d012019-05-08 14:50:56 -0700796 }
Ady Abraham2c6716b2020-12-08 16:54:10 -0800797 if (refreshRateChanged) {
798 const RefreshRate& newRefreshRate =
799 mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
800
801 mSchedulerCallback.changeRefreshRate(newRefreshRate,
802 consideredSignals.idle ? ConfigEvent::None
803 : ConfigEvent::Changed);
804 }
805 if (frameRateOverridesChanged) {
806 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
807 }
Ady Abrahamdfd62162020-06-10 16:11:56 -0700808 return consideredSignals.touch;
Ady Abraham8532d012019-05-08 14:50:56 -0700809}
810
Ady Abrahamdfd62162020-06-10 16:11:56 -0700811HwcConfigIndexType Scheduler::calculateRefreshRateConfigIndexType(
812 scheduler::RefreshRateConfigs::GlobalSignals* consideredSignals) {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800813 ATRACE_CALL();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700814 if (consideredSignals) *consideredSignals = {};
Ady Abraham09bd3922019-04-08 10:44:56 -0700815
Steven Thomasf734df42020-04-13 21:09:28 -0700816 // If Display Power is not in normal operation we want to be in performance mode. When coming
817 // back to normal mode, a grace period is given with DisplayPowerTimer.
Ana Krulec3f6a2062020-01-23 15:48:01 -0800818 if (mDisplayPowerTimer &&
819 (!mFeatures.isDisplayPowerStateNormal ||
820 mFeatures.displayPowerTimer == TimerState::Reset)) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700821 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().getConfigId();
Ana Krulec3f6a2062020-01-23 15:48:01 -0800822 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700823
Steven Thomasbb374322020-04-28 22:47:16 -0700824 const bool touchActive = mTouchTimer && mFeatures.touch == TouchState::Active;
825 const bool idle = mIdleTimer && mFeatures.idleTimer == TimerState::Expired;
826
Ady Abraham1adbb722020-05-15 11:51:48 -0700827 return mRefreshRateConfigs
Ady Abrahamdfd62162020-06-10 16:11:56 -0700828 .getBestRefreshRate(mFeatures.contentRequirements, {.touch = touchActive, .idle = idle},
829 consideredSignals)
Ady Abraham1adbb722020-05-15 11:51:48 -0700830 .getConfigId();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800831}
832
Ady Abraham2139f732019-11-13 18:56:40 -0800833std::optional<HwcConfigIndexType> Scheduler::getPreferredConfigId() {
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700834 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ana Krulec3f6a2062020-01-23 15:48:01 -0800835 // Make sure that the default config ID is first updated, before returned.
836 if (mFeatures.configId.has_value()) {
Ana Krulec3803b8d2020-02-03 16:35:46 -0800837 mFeatures.configId = calculateRefreshRateConfigIndexType();
Ana Krulec3f6a2062020-01-23 15:48:01 -0800838 }
Ady Abraham2139f732019-11-13 18:56:40 -0800839 return mFeatures.configId;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700840}
841
Peiyong Line9d809e2020-04-14 13:10:48 -0700842void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800843 if (timeline.refreshRequired) {
844 mSchedulerCallback.repaintEverythingForHWC();
845 }
846
847 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
848 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
849
850 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
851 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
852 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
853 }
854}
855
856void Scheduler::onDisplayRefreshed(nsecs_t timestamp) {
857 bool callRepaint = false;
858 {
859 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
860 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
861 if (mLastVsyncPeriodChangeTimeline->refreshTimeNanos < timestamp) {
862 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
863 } else {
864 // We need to send another refresh as refreshTimeNanos is still in the future
865 callRepaint = true;
866 }
867 }
868 }
869
870 if (callRepaint) {
871 mSchedulerCallback.repaintEverythingForHWC();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800872 }
873}
874
Ady Abraham8a82ba62020-01-17 12:43:17 -0800875void Scheduler::onPrimaryDisplayAreaChanged(uint32_t displayArea) {
876 if (mLayerHistory) {
877 mLayerHistory->setDisplayArea(displayArea);
878 }
879}
880
Ady Abraham2c6716b2020-12-08 16:54:10 -0800881void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
882 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
883 return;
884 }
885
886 std::lock_guard lock(mFeatureStateLock);
887 if (frameRateOverride.frameRateHz != 0.f) {
888 mFrameRateOverridesFromBackdoor[frameRateOverride.uid] = Fps(frameRateOverride.frameRateHz);
889 } else {
890 mFrameRateOverridesFromBackdoor.erase(frameRateOverride.uid);
891 }
892}
893
Ana Krulec98b5b242018-08-10 15:03:23 -0700894} // namespace android