blob: 892ae620276fc06da959f11380837a58af847152 [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,
Kevin DuBoisb2501ba2019-11-12 14:20:29 -080059 std::unique_ptr<VSyncTracker> tracker, size_t pendingFenceLimit)
Kevin DuBois2fd3cea2019-11-14 08:52:45 -080060 : mClock(std::move(clock)),
Kevin DuBoisb2501ba2019-11-12 14:20:29 -080061 mTracker(std::move(tracker)),
Kevin DuBois00287382019-11-19 15:11:55 -080062 mDispatch(std::move(dispatch)),
Ady Abraham13bc0be2020-02-27 16:48:20 -080063 mPendingLimit(pendingFenceLimit),
64 mPredictedVsyncTracer(property_get_bool("debug.sf.show_predicted_vsync", false)
65 ? std::make_unique<PredictedVsyncTracer>(*mDispatch)
66 : nullptr) {}
Kevin DuBoisb2501ba2019-11-12 14:20:29 -080067
Kevin DuBoisf91e9232019-11-21 10:51:23 -080068VSyncReactor::~VSyncReactor() = default;
69
70// The DispSync interface has a 'repeat this callback at rate' semantic. This object adapts
71// VSyncDispatch's individually-scheduled callbacks so as to meet DispSync's existing semantic
72// for now.
73class CallbackRepeater {
74public:
75 CallbackRepeater(VSyncDispatch& dispatch, DispSync::Callback* cb, const char* name,
76 nsecs_t period, nsecs_t offset, nsecs_t notBefore)
Ady Abraham5e7371c2020-03-24 14:47:24 -070077 : mName(name),
78 mCallback(cb),
Kevin DuBoisf91e9232019-11-21 10:51:23 -080079 mRegistration(dispatch,
Kevin DuBois2968afc2020-01-14 09:48:50 -080080 std::bind(&CallbackRepeater::callback, this, std::placeholders::_1,
81 std::placeholders::_2),
Ady Abraham5e7371c2020-03-24 14:47:24 -070082 mName),
Kevin DuBoisf91e9232019-11-21 10:51:23 -080083 mPeriod(period),
84 mOffset(offset),
85 mLastCallTime(notBefore) {}
86
87 ~CallbackRepeater() {
88 std::lock_guard<std::mutex> lk(mMutex);
89 mRegistration.cancel();
90 }
91
92 void start(nsecs_t offset) {
93 std::lock_guard<std::mutex> lk(mMutex);
94 mStopped = false;
95 mOffset = offset;
96
Kevin DuBoisc94ca832019-11-26 12:56:24 -080097 auto const schedule_result = mRegistration.schedule(calculateWorkload(), mLastCallTime);
98 LOG_ALWAYS_FATAL_IF((schedule_result != ScheduleResult::Scheduled),
99 "Error scheduling callback: rc %X", schedule_result);
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800100 }
101
102 void setPeriod(nsecs_t period) {
103 std::lock_guard<std::mutex> lk(mMutex);
104 if (period == mPeriod) {
105 return;
106 }
107 mPeriod = period;
108 }
109
110 void stop() {
111 std::lock_guard<std::mutex> lk(mMutex);
112 LOG_ALWAYS_FATAL_IF(mStopped, "DispSyncInterface misuse: callback already stopped");
113 mStopped = true;
114 mRegistration.cancel();
115 }
116
Ady Abraham5e7371c2020-03-24 14:47:24 -0700117 void dump(std::string& result) const {
118 std::lock_guard<std::mutex> lk(mMutex);
119 StringAppendF(&result, "\t%s: mPeriod=%.2f last vsync time %.2fms relative to now (%s)\n",
120 mName.c_str(), mPeriod / 1e6f, (mLastCallTime - systemTime()) / 1e6f,
121 mStopped ? "stopped" : "running");
122 }
123
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800124private:
Kevin DuBois2968afc2020-01-14 09:48:50 -0800125 void callback(nsecs_t vsynctime, nsecs_t wakeupTime) {
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800126 {
127 std::lock_guard<std::mutex> lk(mMutex);
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800128 mLastCallTime = vsynctime;
129 }
130
Kevin DuBois2968afc2020-01-14 09:48:50 -0800131 mCallback->onDispSyncEvent(wakeupTime);
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800132
133 {
134 std::lock_guard<std::mutex> lk(mMutex);
Kevin DuBoisbf7632e2020-02-13 10:11:53 -0800135 if (mStopped) {
136 return;
137 }
Kevin DuBoisc94ca832019-11-26 12:56:24 -0800138 auto const schedule_result = mRegistration.schedule(calculateWorkload(), vsynctime);
139 LOG_ALWAYS_FATAL_IF((schedule_result != ScheduleResult::Scheduled),
140 "Error rescheduling callback: rc %X", schedule_result);
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800141 }
142 }
143
144 // DispSync offsets are defined as time after the vsync before presentation.
145 // VSyncReactor workloads are defined as time before the intended presentation vsync.
146 // Note change in sign between the two defnitions.
147 nsecs_t calculateWorkload() REQUIRES(mMutex) { return mPeriod - mOffset; }
148
Ady Abraham5e7371c2020-03-24 14:47:24 -0700149 const std::string mName;
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800150 DispSync::Callback* const mCallback;
151
152 std::mutex mutable mMutex;
153 VSyncCallbackRegistration mRegistration GUARDED_BY(mMutex);
154 bool mStopped GUARDED_BY(mMutex) = false;
155 nsecs_t mPeriod GUARDED_BY(mMutex);
156 nsecs_t mOffset GUARDED_BY(mMutex);
157 nsecs_t mLastCallTime GUARDED_BY(mMutex);
158};
159
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800160bool VSyncReactor::addPresentFence(const std::shared_ptr<FenceTime>& fence) {
161 if (!fence) {
162 return false;
163 }
164
165 nsecs_t const signalTime = fence->getCachedSignalTime();
166 if (signalTime == Fence::SIGNAL_TIME_INVALID) {
167 return true;
168 }
169
170 std::lock_guard<std::mutex> lk(mMutex);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800171 if (mExternalIgnoreFences || mInternalIgnoreFences) {
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800172 return true;
173 }
174
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800175 bool timestampAccepted = true;
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800176 for (auto it = mUnfiredFences.begin(); it != mUnfiredFences.end();) {
177 auto const time = (*it)->getCachedSignalTime();
178 if (time == Fence::SIGNAL_TIME_PENDING) {
179 it++;
180 } else if (time == Fence::SIGNAL_TIME_INVALID) {
181 it = mUnfiredFences.erase(it);
182 } else {
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800183 timestampAccepted &= mTracker->addVsyncTimestamp(time);
184
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800185 it = mUnfiredFences.erase(it);
186 }
187 }
188
189 if (signalTime == Fence::SIGNAL_TIME_PENDING) {
190 if (mPendingLimit == mUnfiredFences.size()) {
191 mUnfiredFences.erase(mUnfiredFences.begin());
192 }
193 mUnfiredFences.push_back(fence);
194 } else {
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800195 timestampAccepted &= mTracker->addVsyncTimestamp(signalTime);
196 }
197
198 if (!timestampAccepted) {
199 mMoreSamplesNeeded = true;
200 setIgnorePresentFencesInternal(true);
201 mPeriodConfirmationInProgress = true;
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800202 }
203
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800204 return mMoreSamplesNeeded;
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800205}
206
207void VSyncReactor::setIgnorePresentFences(bool ignoration) {
208 std::lock_guard<std::mutex> lk(mMutex);
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800209 mExternalIgnoreFences = ignoration;
210 updateIgnorePresentFencesInternal();
211}
212
213void VSyncReactor::setIgnorePresentFencesInternal(bool ignoration) {
214 mInternalIgnoreFences = ignoration;
215 updateIgnorePresentFencesInternal();
216}
217
218void VSyncReactor::updateIgnorePresentFencesInternal() {
219 if (mExternalIgnoreFences || mInternalIgnoreFences) {
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800220 mUnfiredFences.clear();
221 }
222}
223
Kevin DuBois2fd3cea2019-11-14 08:52:45 -0800224nsecs_t VSyncReactor::computeNextRefresh(int periodOffset) const {
225 auto const now = mClock->now();
226 auto const currentPeriod = periodOffset ? mTracker->currentPeriod() : 0;
227 return mTracker->nextAnticipatedVSyncTimeFrom(now + periodOffset * currentPeriod);
228}
229
230nsecs_t VSyncReactor::expectedPresentTime() {
231 return mTracker->nextAnticipatedVSyncTimeFrom(mClock->now());
232}
233
Kevin DuBoisc4cdd372020-01-09 14:12:02 -0800234void VSyncReactor::startPeriodTransition(nsecs_t newPeriod) {
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800235 mPeriodConfirmationInProgress = true;
Kevin DuBoisc4cdd372020-01-09 14:12:02 -0800236 mPeriodTransitioningTo = newPeriod;
237 mMoreSamplesNeeded = true;
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800238 setIgnorePresentFencesInternal(true);
Kevin DuBoisc4cdd372020-01-09 14:12:02 -0800239}
240
241void VSyncReactor::endPeriodTransition() {
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800242 setIgnorePresentFencesInternal(false);
Kevin DuBoisc4cdd372020-01-09 14:12:02 -0800243 mMoreSamplesNeeded = false;
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800244 mPeriodTransitioningTo.reset();
245 mPeriodConfirmationInProgress = false;
246 mLastHwVsync.reset();
Kevin DuBoisc4cdd372020-01-09 14:12:02 -0800247}
248
Kevin DuBoisee2ad9f2019-11-21 11:10:57 -0800249void VSyncReactor::setPeriod(nsecs_t period) {
Kevin DuBois5988f482020-01-17 09:03:32 -0800250 ATRACE_INT64("VSR-setPeriod", period);
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800251 std::lock_guard lk(mMutex);
252 mLastHwVsync.reset();
Kevin DuBoisc4cdd372020-01-09 14:12:02 -0800253 if (period == getPeriod()) {
254 endPeriodTransition();
255 } else {
256 startPeriodTransition(period);
257 }
Kevin DuBoisee2ad9f2019-11-21 11:10:57 -0800258}
259
260nsecs_t VSyncReactor::getPeriod() {
261 return mTracker->currentPeriod();
262}
263
Kevin DuBoisc3e9e8e2020-01-07 09:06:52 -0800264void VSyncReactor::beginResync() {
265 mTracker->resetModel();
266}
Kevin DuBoisa9fdab72019-11-14 09:44:14 -0800267
268void VSyncReactor::endResync() {}
269
Ady Abraham5dee2f12020-02-05 17:49:47 -0800270bool VSyncReactor::periodConfirmed(nsecs_t vsync_timestamp, std::optional<nsecs_t> HwcVsyncPeriod) {
271 if (!mPeriodConfirmationInProgress) {
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800272 return false;
273 }
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800274
Ady Abraham5dee2f12020-02-05 17:49:47 -0800275 if (!mLastHwVsync && !HwcVsyncPeriod) {
276 return false;
277 }
278
279 auto const period = mPeriodTransitioningTo ? *mPeriodTransitioningTo : getPeriod();
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800280 static constexpr int allowancePercent = 10;
281 static constexpr std::ratio<allowancePercent, 100> allowancePercentRatio;
282 auto const allowance = period * allowancePercentRatio.num / allowancePercentRatio.den;
Ady Abraham5dee2f12020-02-05 17:49:47 -0800283 if (HwcVsyncPeriod) {
284 return std::abs(*HwcVsyncPeriod - period) < allowance;
285 }
286
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800287 auto const distance = vsync_timestamp - *mLastHwVsync;
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800288 return std::abs(distance - period) < allowance;
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800289}
290
Ady Abraham5dee2f12020-02-05 17:49:47 -0800291bool VSyncReactor::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
292 bool* periodFlushed) {
Kevin DuBoisa9fdab72019-11-14 09:44:14 -0800293 assert(periodFlushed);
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800294
295 std::lock_guard<std::mutex> lk(mMutex);
Ady Abraham5dee2f12020-02-05 17:49:47 -0800296 if (periodConfirmed(timestamp, hwcVsyncPeriod)) {
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800297 if (mPeriodTransitioningTo) {
298 mTracker->setPeriod(*mPeriodTransitioningTo);
299 for (auto& entry : mCallbacks) {
300 entry.second->setPeriod(*mPeriodTransitioningTo);
301 }
302 *periodFlushed = true;
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800303 }
Kevin DuBoisc4cdd372020-01-09 14:12:02 -0800304 endPeriodTransition();
Kevin DuBois02d5ed92020-01-27 11:05:46 -0800305 } else if (mPeriodConfirmationInProgress) {
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800306 mLastHwVsync = timestamp;
307 mMoreSamplesNeeded = true;
308 *periodFlushed = false;
309 } else {
310 mMoreSamplesNeeded = false;
311 *periodFlushed = false;
Kevin DuBoisa9fdab72019-11-14 09:44:14 -0800312 }
Kevin DuBoisf77025c2019-12-18 16:13:24 -0800313
314 mTracker->addVsyncTimestamp(timestamp);
315 return mMoreSamplesNeeded;
Kevin DuBoisa9fdab72019-11-14 09:44:14 -0800316}
317
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800318status_t VSyncReactor::addEventListener(const char* name, nsecs_t phase,
319 DispSync::Callback* callback,
320 nsecs_t /* lastCallbackTime */) {
321 std::lock_guard<std::mutex> lk(mMutex);
322 auto it = mCallbacks.find(callback);
323 if (it == mCallbacks.end()) {
324 // TODO (b/146557561): resolve lastCallbackTime semantics in DispSync i/f.
Ady Abraham13bc0be2020-02-27 16:48:20 -0800325 static auto constexpr maxListeners = 4;
Kevin DuBoisf91e9232019-11-21 10:51:23 -0800326 if (mCallbacks.size() >= maxListeners) {
327 ALOGE("callback %s not added, exceeded callback limit of %i (currently %zu)", name,
328 maxListeners, mCallbacks.size());
329 return NO_MEMORY;
330 }
331
332 auto const period = mTracker->currentPeriod();
333 auto repeater = std::make_unique<CallbackRepeater>(*mDispatch, callback, name, period,
334 phase, mClock->now());
335 it = mCallbacks.emplace(std::pair(callback, std::move(repeater))).first;
336 }
337
338 it->second->start(phase);
339 return NO_ERROR;
340}
341
342status_t VSyncReactor::removeEventListener(DispSync::Callback* callback,
343 nsecs_t* /* outLastCallback */) {
344 std::lock_guard<std::mutex> lk(mMutex);
345 auto const it = mCallbacks.find(callback);
346 LOG_ALWAYS_FATAL_IF(it == mCallbacks.end(), "callback %p not registered", callback);
347
348 it->second->stop();
349 return NO_ERROR;
350}
351
352status_t VSyncReactor::changePhaseOffset(DispSync::Callback* callback, nsecs_t phase) {
353 std::lock_guard<std::mutex> lk(mMutex);
354 auto const it = mCallbacks.find(callback);
355 LOG_ALWAYS_FATAL_IF(it == mCallbacks.end(), "callback was %p not registered", callback);
356
357 it->second->start(phase);
358 return NO_ERROR;
359}
360
Kevin DuBois00287382019-11-19 15:11:55 -0800361void VSyncReactor::dump(std::string& result) const {
Ady Abraham5e7371c2020-03-24 14:47:24 -0700362 std::lock_guard<std::mutex> lk(mMutex);
363 StringAppendF(&result, "VsyncReactor in use\n");
364 StringAppendF(&result, "Has %zu unfired fences\n", mUnfiredFences.size());
365 StringAppendF(&result, "mInternalIgnoreFences=%d mExternalIgnoreFences=%d\n",
366 mInternalIgnoreFences, mExternalIgnoreFences);
367 StringAppendF(&result, "mMoreSamplesNeeded=%d mPeriodConfirmationInProgress=%d\n",
368 mMoreSamplesNeeded, mPeriodConfirmationInProgress);
369 if (mPeriodTransitioningTo) {
370 StringAppendF(&result, "mPeriodTransitioningTo=%" PRId64 "\n", *mPeriodTransitioningTo);
371 } else {
372 StringAppendF(&result, "mPeriodTransitioningTo=nullptr\n");
373 }
374
375 if (mLastHwVsync) {
376 StringAppendF(&result, "Last HW vsync was %.2fms ago\n",
377 (mClock->now() - *mLastHwVsync) / 1e6f);
378 } else {
379 StringAppendF(&result, "No Last HW vsync\n");
380 }
381
382 StringAppendF(&result, "CallbackRepeaters:\n");
383 for (const auto& [callback, repeater] : mCallbacks) {
384 repeater->dump(result);
385 }
386
387 StringAppendF(&result, "VSyncTracker:\n");
388 mTracker->dump(result);
389 StringAppendF(&result, "VSyncDispatch:\n");
390 mDispatch->dump(result);
Kevin DuBois00287382019-11-19 15:11:55 -0800391}
392
393void VSyncReactor::reset() {}
394
Kevin DuBoisb2501ba2019-11-12 14:20:29 -0800395} // namespace android::scheduler