blob: 16d102cac19bba5e5a8d1e6705be91bd1560fe5e [file] [log] [blame]
Kevin DuBoisb2501ba2019-11-12 14:20:29 -08001/*
2 * Copyright 2019 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
Kevin DuBois5988f482020-01-17 09:03:32 -080017#define ATRACE_TAG ATRACE_TAG_GRAPHICS
Kevin DuBoisc94ca832019-11-26 12:56:24 -080018#undef LOG_TAG
19#define LOG_TAG "VSyncReactor"
Kevin DuBoisf91e9232019-11-21 10:51:23 -080020//#define LOG_NDEBUG 0
Kevin DuBoisb2501ba2019-11-12 14:20:29 -080021#include "VSyncReactor.h"
Ady Abraham13bc0be2020-02-27 16:48:20 -080022#include <cutils/properties.h>
Kevin DuBoisf91e9232019-11-21 10:51:23 -080023#include <log/log.h>
Kevin DuBois5988f482020-01-17 09:03:32 -080024#include <utils/Trace.h>
Ady Abraham13bc0be2020-02-27 16:48:20 -080025#include "../TracedOrdinal.h"
Kevin DuBois2fd3cea2019-11-14 08:52:45 -080026#include "TimeKeeper.h"
Kevin DuBoisb2501ba2019-11-12 14:20:29 -080027#include "VSyncDispatch.h"
28#include "VSyncTracker.h"
29
30namespace android::scheduler {
Ady Abraham5e7371c2020-03-24 14:47:24 -070031using base::StringAppendF;
Kevin DuBoisb2501ba2019-11-12 14:20:29 -080032
Kevin DuBois2fd3cea2019-11-14 08:52:45 -080033Clock::~Clock() = default;
Kevin DuBois00287382019-11-19 15:11:55 -080034nsecs_t SystemClock::now() const {
35 return systemTime(SYSTEM_TIME_MONOTONIC);
36}
Kevin DuBois2fd3cea2019-11-14 08:52:45 -080037
Ady Abraham13bc0be2020-02-27 16:48:20 -080038class PredictedVsyncTracer {
39public:
40 PredictedVsyncTracer(VSyncDispatch& dispatch)
41 : mRegistration(dispatch,
42 std::bind(&PredictedVsyncTracer::callback, this, std::placeholders::_1,
43 std::placeholders::_2),
44 "PredictedVsyncTracer") {
45 mRegistration.schedule(0, 0);
46 }
47
48private:
49 TracedOrdinal<bool> mParity = {"VSYNC-predicted", 0};
50 VSyncCallbackRegistration mRegistration;
51
52 void callback(nsecs_t /*vsyncTime*/, nsecs_t /*targetWakeupTim*/) {
53 mParity = !mParity;
54 mRegistration.schedule(0, 0);
55 }
56};
57
Kevin DuBois2fd3cea2019-11-14 08:52:45 -080058VSyncReactor::VSyncReactor(std::unique_ptr<Clock> clock, std::unique_ptr<VSyncDispatch> dispatch,
Dan Stoza027d3652020-05-26 17:26:34 -070059 std::unique_ptr<VSyncTracker> tracker, size_t pendingFenceLimit,
60 bool supportKernelIdleTimer)
Kevin DuBois2fd3cea2019-11-14 08:52:45 -080061 : mClock(std::move(clock)),
Kevin DuBoisb2501ba2019-11-12 14:20:29 -080062 mTracker(std::move(tracker)),
Kevin DuBois00287382019-11-19 15:11:55 -080063 mDispatch(std::move(dispatch)),
Ady Abraham13bc0be2020-02-27 16:48:20 -080064 mPendingLimit(pendingFenceLimit),
65 mPredictedVsyncTracer(property_get_bool("debug.sf.show_predicted_vsync", false)
66 ? std::make_unique<PredictedVsyncTracer>(*mDispatch)
Dan Stoza027d3652020-05-26 17:26:34 -070067 : nullptr),
68 mSupportKernelIdleTimer(supportKernelIdleTimer) {}
Kevin DuBoisb2501ba2019-11-12 14:20:29 -080069
Kevin DuBoisf91e9232019-11-21 10:51:23 -080070VSyncReactor::~VSyncReactor() = default;
71
72// The DispSync interface has a 'repeat this callback at rate' semantic. This object adapts
73// VSyncDispatch's individually-scheduled callbacks so as to meet DispSync's existing semantic
74// for now.
75class CallbackRepeater {
76public:
77 CallbackRepeater(VSyncDispatch& dispatch, DispSync::Callback* cb, const char* name,
78 nsecs_t period, nsecs_t offset, nsecs_t notBefore)
Ady Abraham5e7371c2020-03-24 14:47:24 -070079 : mName(name),
80 mCallback(cb),
Kevin DuBoisf91e9232019-11-21 10:51:23 -080081 mRegistration(dispatch,
Kevin DuBois2968afc2020-01-14 09:48:50 -080082 std::bind(&CallbackRepeater::callback, this, std::placeholders::_1,
83 std::placeholders::_2),
Ady Abraham5e7371c2020-03-24 14:47:24 -070084 mName),
Kevin DuBoisf91e9232019-11-21 10:51:23 -080085 mPeriod(period),
86 mOffset(offset),
87 mLastCallTime(notBefore) {}
88
89 ~CallbackRepeater() {
90 std::lock_guard<std::mutex> lk(mMutex);
91 mRegistration.cancel();
92 }
93
94 void start(nsecs_t offset) {
95 std::lock_guard<std::mutex> lk(mMutex);
96 mStopped = false;
97 mOffset = offset;
98
Kevin DuBoisc94ca832019-11-26 12:56:24 -080099 auto const schedule_result = mRegistration.schedule(calculateWorkload(), mLastCallTime);
100 LOG_ALWAYS_FATAL_IF((schedule_result != ScheduleResult::Scheduled),
101 "Error scheduling callback: rc %X", schedule_result);
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800102 }
103
104 void setPeriod(nsecs_t period) {
105 std::lock_guard<std::mutex> lk(mMutex);
106 if (period == mPeriod) {
107 return;
108 }
109 mPeriod = period;
110 }
111
112 void stop() {
113 std::lock_guard<std::mutex> lk(mMutex);
114 LOG_ALWAYS_FATAL_IF(mStopped, "DispSyncInterface misuse: callback already stopped");
115 mStopped = true;
116 mRegistration.cancel();
117 }
118
Ady Abraham5e7371c2020-03-24 14:47:24 -0700119 void dump(std::string& result) const {
120 std::lock_guard<std::mutex> lk(mMutex);
121 StringAppendF(&result, "\t%s: mPeriod=%.2f last vsync time %.2fms relative to now (%s)\n",
122 mName.c_str(), mPeriod / 1e6f, (mLastCallTime - systemTime()) / 1e6f,
123 mStopped ? "stopped" : "running");
124 }
125
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800126private:
Kevin DuBois2968afc2020-01-14 09:48:50 -0800127 void callback(nsecs_t vsynctime, nsecs_t wakeupTime) {
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800128 {
129 std::lock_guard<std::mutex> lk(mMutex);
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800130 mLastCallTime = vsynctime;
131 }
132
Ady Abraham5facfb12020-04-22 15:18:31 -0700133 mCallback->onDispSyncEvent(wakeupTime, vsynctime);
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800134
135 {
136 std::lock_guard<std::mutex> lk(mMutex);
Kevin DuBoisbf7632e2020-02-13 10:11:53 -0800137 if (mStopped) {
138 return;
139 }
Kevin DuBoisc94ca832019-11-26 12:56:24 -0800140 auto const schedule_result = mRegistration.schedule(calculateWorkload(), vsynctime);
141 LOG_ALWAYS_FATAL_IF((schedule_result != ScheduleResult::Scheduled),
142 "Error rescheduling callback: rc %X", schedule_result);
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800143 }
144 }
145
146 // DispSync offsets are defined as time after the vsync before presentation.
147 // VSyncReactor workloads are defined as time before the intended presentation vsync.
148 // Note change in sign between the two defnitions.
149 nsecs_t calculateWorkload() REQUIRES(mMutex) { return mPeriod - mOffset; }
150
Ady Abraham5e7371c2020-03-24 14:47:24 -0700151 const std::string mName;
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800152 DispSync::Callback* const mCallback;
153
154 std::mutex mutable mMutex;
155 VSyncCallbackRegistration mRegistration GUARDED_BY(mMutex);
156 bool mStopped GUARDED_BY(mMutex) = false;
157 nsecs_t mPeriod GUARDED_BY(mMutex);
158 nsecs_t mOffset GUARDED_BY(mMutex);
159 nsecs_t mLastCallTime GUARDED_BY(mMutex);
160};
161
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800162bool VSyncReactor::addPresentFence(const std::shared_ptr<FenceTime>& fence) {
163 if (!fence) {
164 return false;
165 }
166
167 nsecs_t const signalTime = fence->getCachedSignalTime();
168 if (signalTime == Fence::SIGNAL_TIME_INVALID) {
169 return true;
170 }
171
172 std::lock_guard<std::mutex> lk(mMutex);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800173 if (mExternalIgnoreFences || mInternalIgnoreFences) {
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800174 return true;
175 }
176
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800177 bool timestampAccepted = true;
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800178 for (auto it = mUnfiredFences.begin(); it != mUnfiredFences.end();) {
179 auto const time = (*it)->getCachedSignalTime();
180 if (time == Fence::SIGNAL_TIME_PENDING) {
181 it++;
182 } else if (time == Fence::SIGNAL_TIME_INVALID) {
183 it = mUnfiredFences.erase(it);
184 } else {
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800185 timestampAccepted &= mTracker->addVsyncTimestamp(time);
186
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800187 it = mUnfiredFences.erase(it);
188 }
189 }
190
191 if (signalTime == Fence::SIGNAL_TIME_PENDING) {
192 if (mPendingLimit == mUnfiredFences.size()) {
193 mUnfiredFences.erase(mUnfiredFences.begin());
194 }
195 mUnfiredFences.push_back(fence);
196 } else {
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800197 timestampAccepted &= mTracker->addVsyncTimestamp(signalTime);
198 }
199
200 if (!timestampAccepted) {
201 mMoreSamplesNeeded = true;
202 setIgnorePresentFencesInternal(true);
203 mPeriodConfirmationInProgress = true;
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800204 }
205
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800206 return mMoreSamplesNeeded;
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800207}
208
209void VSyncReactor::setIgnorePresentFences(bool ignoration) {
210 std::lock_guard<std::mutex> lk(mMutex);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800211 mExternalIgnoreFences = ignoration;
212 updateIgnorePresentFencesInternal();
213}
214
215void VSyncReactor::setIgnorePresentFencesInternal(bool ignoration) {
216 mInternalIgnoreFences = ignoration;
217 updateIgnorePresentFencesInternal();
218}
219
220void VSyncReactor::updateIgnorePresentFencesInternal() {
221 if (mExternalIgnoreFences || mInternalIgnoreFences) {
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800222 mUnfiredFences.clear();
223 }
224}
225
Ady Abraham0ed31c92020-04-16 11:48:45 -0700226nsecs_t VSyncReactor::computeNextRefresh(int periodOffset, nsecs_t now) const {
Kevin DuBois2fd3cea2019-11-14 08:52:45 -0800227 auto const currentPeriod = periodOffset ? mTracker->currentPeriod() : 0;
228 return mTracker->nextAnticipatedVSyncTimeFrom(now + periodOffset * currentPeriod);
229}
230
Ady Abraham0ed31c92020-04-16 11:48:45 -0700231nsecs_t VSyncReactor::expectedPresentTime(nsecs_t now) {
232 return mTracker->nextAnticipatedVSyncTimeFrom(now);
Kevin DuBois2fd3cea2019-11-14 08:52:45 -0800233}
234
Kevin DuBoisc4cdd372020-01-09 14:12:02 -0800235void VSyncReactor::startPeriodTransition(nsecs_t newPeriod) {
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800236 mPeriodConfirmationInProgress = true;
Kevin DuBoisc4cdd372020-01-09 14:12:02 -0800237 mPeriodTransitioningTo = newPeriod;
238 mMoreSamplesNeeded = true;
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800239 setIgnorePresentFencesInternal(true);
Kevin DuBoisc4cdd372020-01-09 14:12:02 -0800240}
241
242void VSyncReactor::endPeriodTransition() {
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800243 setIgnorePresentFencesInternal(false);
Kevin DuBoisc4cdd372020-01-09 14:12:02 -0800244 mMoreSamplesNeeded = false;
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800245 mPeriodTransitioningTo.reset();
246 mPeriodConfirmationInProgress = false;
247 mLastHwVsync.reset();
Kevin DuBoisc4cdd372020-01-09 14:12:02 -0800248}
249
Kevin DuBoisee2ad9f2019-11-21 11:10:57 -0800250void VSyncReactor::setPeriod(nsecs_t period) {
Kevin DuBois5988f482020-01-17 09:03:32 -0800251 ATRACE_INT64("VSR-setPeriod", period);
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800252 std::lock_guard lk(mMutex);
253 mLastHwVsync.reset();
Dan Stoza027d3652020-05-26 17:26:34 -0700254
255 if (!mSupportKernelIdleTimer && period == getPeriod()) {
Kevin DuBoisc4cdd372020-01-09 14:12:02 -0800256 endPeriodTransition();
257 } else {
258 startPeriodTransition(period);
259 }
Kevin DuBoisee2ad9f2019-11-21 11:10:57 -0800260}
261
262nsecs_t VSyncReactor::getPeriod() {
263 return mTracker->currentPeriod();
264}
265
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800266void VSyncReactor::beginResync() {
267 mTracker->resetModel();
268}
Kevin DuBoisa9fdab72019-11-14 09:44:14 -0800269
270void VSyncReactor::endResync() {}
271
Ady Abraham5dee2f12020-02-05 17:49:47 -0800272bool VSyncReactor::periodConfirmed(nsecs_t vsync_timestamp, std::optional<nsecs_t> HwcVsyncPeriod) {
273 if (!mPeriodConfirmationInProgress) {
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800274 return false;
275 }
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800276
Ady Abraham5dee2f12020-02-05 17:49:47 -0800277 if (!mLastHwVsync && !HwcVsyncPeriod) {
278 return false;
279 }
280
Dan Stoza027d3652020-05-26 17:26:34 -0700281 if (mSupportKernelIdleTimer) {
282 // Clear out the Composer-provided period and use the allowance logic below
283 HwcVsyncPeriod = {};
284 }
285
Ady Abraham5dee2f12020-02-05 17:49:47 -0800286 auto const period = mPeriodTransitioningTo ? *mPeriodTransitioningTo : getPeriod();
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800287 static constexpr int allowancePercent = 10;
288 static constexpr std::ratio<allowancePercent, 100> allowancePercentRatio;
289 auto const allowance = period * allowancePercentRatio.num / allowancePercentRatio.den;
Ady Abraham5dee2f12020-02-05 17:49:47 -0800290 if (HwcVsyncPeriod) {
291 return std::abs(*HwcVsyncPeriod - period) < allowance;
292 }
293
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800294 auto const distance = vsync_timestamp - *mLastHwVsync;
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800295 return std::abs(distance - period) < allowance;
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800296}
297
Ady Abraham5dee2f12020-02-05 17:49:47 -0800298bool VSyncReactor::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
299 bool* periodFlushed) {
Kevin DuBoisa9fdab72019-11-14 09:44:14 -0800300 assert(periodFlushed);
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800301
302 std::lock_guard<std::mutex> lk(mMutex);
Ady Abraham5dee2f12020-02-05 17:49:47 -0800303 if (periodConfirmed(timestamp, hwcVsyncPeriod)) {
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800304 if (mPeriodTransitioningTo) {
305 mTracker->setPeriod(*mPeriodTransitioningTo);
306 for (auto& entry : mCallbacks) {
307 entry.second->setPeriod(*mPeriodTransitioningTo);
308 }
309 *periodFlushed = true;
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800310 }
Kevin DuBoisc4cdd372020-01-09 14:12:02 -0800311 endPeriodTransition();
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800312 } else if (mPeriodConfirmationInProgress) {
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800313 mLastHwVsync = timestamp;
314 mMoreSamplesNeeded = true;
315 *periodFlushed = false;
316 } else {
317 mMoreSamplesNeeded = false;
318 *periodFlushed = false;
Kevin DuBoisa9fdab72019-11-14 09:44:14 -0800319 }
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800320
321 mTracker->addVsyncTimestamp(timestamp);
322 return mMoreSamplesNeeded;
Kevin DuBoisa9fdab72019-11-14 09:44:14 -0800323}
324
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800325status_t VSyncReactor::addEventListener(const char* name, nsecs_t phase,
326 DispSync::Callback* callback,
327 nsecs_t /* lastCallbackTime */) {
328 std::lock_guard<std::mutex> lk(mMutex);
329 auto it = mCallbacks.find(callback);
330 if (it == mCallbacks.end()) {
331 // TODO (b/146557561): resolve lastCallbackTime semantics in DispSync i/f.
Ady Abraham13bc0be2020-02-27 16:48:20 -0800332 static auto constexpr maxListeners = 4;
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800333 if (mCallbacks.size() >= maxListeners) {
334 ALOGE("callback %s not added, exceeded callback limit of %i (currently %zu)", name,
335 maxListeners, mCallbacks.size());
336 return NO_MEMORY;
337 }
338
339 auto const period = mTracker->currentPeriod();
340 auto repeater = std::make_unique<CallbackRepeater>(*mDispatch, callback, name, period,
341 phase, mClock->now());
342 it = mCallbacks.emplace(std::pair(callback, std::move(repeater))).first;
343 }
344
345 it->second->start(phase);
346 return NO_ERROR;
347}
348
349status_t VSyncReactor::removeEventListener(DispSync::Callback* callback,
350 nsecs_t* /* outLastCallback */) {
351 std::lock_guard<std::mutex> lk(mMutex);
352 auto const it = mCallbacks.find(callback);
353 LOG_ALWAYS_FATAL_IF(it == mCallbacks.end(), "callback %p not registered", callback);
354
355 it->second->stop();
356 return NO_ERROR;
357}
358
359status_t VSyncReactor::changePhaseOffset(DispSync::Callback* callback, nsecs_t phase) {
360 std::lock_guard<std::mutex> lk(mMutex);
361 auto const it = mCallbacks.find(callback);
362 LOG_ALWAYS_FATAL_IF(it == mCallbacks.end(), "callback was %p not registered", callback);
363
364 it->second->start(phase);
365 return NO_ERROR;
366}
367
Kevin DuBois00287382019-11-19 15:11:55 -0800368void VSyncReactor::dump(std::string& result) const {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700369 std::lock_guard<std::mutex> lk(mMutex);
370 StringAppendF(&result, "VsyncReactor in use\n");
371 StringAppendF(&result, "Has %zu unfired fences\n", mUnfiredFences.size());
372 StringAppendF(&result, "mInternalIgnoreFences=%d mExternalIgnoreFences=%d\n",
373 mInternalIgnoreFences, mExternalIgnoreFences);
374 StringAppendF(&result, "mMoreSamplesNeeded=%d mPeriodConfirmationInProgress=%d\n",
375 mMoreSamplesNeeded, mPeriodConfirmationInProgress);
376 if (mPeriodTransitioningTo) {
377 StringAppendF(&result, "mPeriodTransitioningTo=%" PRId64 "\n", *mPeriodTransitioningTo);
378 } else {
379 StringAppendF(&result, "mPeriodTransitioningTo=nullptr\n");
380 }
381
382 if (mLastHwVsync) {
383 StringAppendF(&result, "Last HW vsync was %.2fms ago\n",
384 (mClock->now() - *mLastHwVsync) / 1e6f);
385 } else {
386 StringAppendF(&result, "No Last HW vsync\n");
387 }
388
389 StringAppendF(&result, "CallbackRepeaters:\n");
390 for (const auto& [callback, repeater] : mCallbacks) {
391 repeater->dump(result);
392 }
393
394 StringAppendF(&result, "VSyncTracker:\n");
395 mTracker->dump(result);
396 StringAppendF(&result, "VSyncDispatch:\n");
397 mDispatch->dump(result);
Kevin DuBois00287382019-11-19 15:11:55 -0800398}
399
400void VSyncReactor::reset() {}
401
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800402} // namespace android::scheduler