blob: 460d4a5c3c45e95b7094a47595efaf21ec3fb310 [file] [log] [blame]
Kevin DuBois305bef12019-10-09 13:23:27 -07001/*
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
17#define ATRACE_TAG ATRACE_TAG_GRAPHICS
Ady Abraham5e7371c2020-03-24 14:47:24 -070018#include <android-base/stringprintf.h>
Kevin DuBois305bef12019-10-09 13:23:27 -070019#include <utils/Trace.h>
20#include <vector>
21
22#include "TimeKeeper.h"
Kevin DuBoise4f27a82019-11-12 11:41:41 -080023#include "VSyncDispatchTimerQueue.h"
Kevin DuBois305bef12019-10-09 13:23:27 -070024#include "VSyncTracker.h"
25
26namespace android::scheduler {
Ady Abraham5e7371c2020-03-24 14:47:24 -070027using base::StringAppendF;
Kevin DuBois305bef12019-10-09 13:23:27 -070028
Kevin DuBoise4f27a82019-11-12 11:41:41 -080029VSyncDispatch::~VSyncDispatch() = default;
Kevin DuBois305bef12019-10-09 13:23:27 -070030VSyncTracker::~VSyncTracker() = default;
31TimeKeeper::~TimeKeeper() = default;
32
Kevin DuBoise4f27a82019-11-12 11:41:41 -080033VSyncDispatchTimerQueueEntry::VSyncDispatchTimerQueueEntry(std::string const& name,
Kevin DuBois2968afc2020-01-14 09:48:50 -080034 VSyncDispatch::Callback const& cb,
Kevin DuBoisc94ca832019-11-26 12:56:24 -080035 nsecs_t minVsyncDistance)
36 : mName(name),
37 mCallback(cb),
38 mWorkDuration(0),
39 mEarliestVsync(0),
40 mMinVsyncDistance(minVsyncDistance) {}
Kevin DuBois305bef12019-10-09 13:23:27 -070041
Kevin DuBoise4f27a82019-11-12 11:41:41 -080042std::optional<nsecs_t> VSyncDispatchTimerQueueEntry::lastExecutedVsyncTarget() const {
Kevin DuBois305bef12019-10-09 13:23:27 -070043 return mLastDispatchTime;
44}
45
Kevin DuBoise4f27a82019-11-12 11:41:41 -080046std::string_view VSyncDispatchTimerQueueEntry::name() const {
Kevin DuBois305bef12019-10-09 13:23:27 -070047 return mName;
48}
49
Kevin DuBoise4f27a82019-11-12 11:41:41 -080050std::optional<nsecs_t> VSyncDispatchTimerQueueEntry::wakeupTime() const {
Kevin DuBois305bef12019-10-09 13:23:27 -070051 if (!mArmedInfo) {
52 return {};
53 }
54 return {mArmedInfo->mActualWakeupTime};
55}
56
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -080057std::optional<nsecs_t> VSyncDispatchTimerQueueEntry::targetVsync() const {
58 if (!mArmedInfo) {
59 return {};
60 }
61 return {mArmedInfo->mActualVsyncTime};
62}
63
Kevin DuBois2311b1a2019-11-18 16:19:08 -080064ScheduleResult VSyncDispatchTimerQueueEntry::schedule(nsecs_t workDuration, nsecs_t earliestVsync,
65 VSyncTracker& tracker, nsecs_t now) {
Kevin DuBoisc94ca832019-11-26 12:56:24 -080066 auto nextVsyncTime =
Kevin DuBois2311b1a2019-11-18 16:19:08 -080067 tracker.nextAnticipatedVSyncTimeFrom(std::max(earliestVsync, now + workDuration));
Kevin DuBoisc94ca832019-11-26 12:56:24 -080068
69 bool const wouldSkipAVsyncTarget =
70 mArmedInfo && (nextVsyncTime > (mArmedInfo->mActualVsyncTime + mMinVsyncDistance));
71 if (wouldSkipAVsyncTarget) {
72 return ScheduleResult::Scheduled;
73 }
74
75 bool const alreadyDispatchedForVsync = mLastDispatchTime &&
76 ((*mLastDispatchTime + mMinVsyncDistance) >= nextVsyncTime &&
77 (*mLastDispatchTime - mMinVsyncDistance) <= nextVsyncTime);
78 if (alreadyDispatchedForVsync) {
79 nextVsyncTime =
80 tracker.nextAnticipatedVSyncTimeFrom(*mLastDispatchTime + mMinVsyncDistance);
Kevin DuBois2311b1a2019-11-18 16:19:08 -080081 }
82
83 auto const nextWakeupTime = nextVsyncTime - workDuration;
Kevin DuBois305bef12019-10-09 13:23:27 -070084 mWorkDuration = workDuration;
85 mEarliestVsync = earliestVsync;
Kevin DuBois2311b1a2019-11-18 16:19:08 -080086 mArmedInfo = {nextWakeupTime, nextVsyncTime};
Kevin DuBoisc94ca832019-11-26 12:56:24 -080087 return ScheduleResult::Scheduled;
Kevin DuBois305bef12019-10-09 13:23:27 -070088}
89
Kevin DuBoise4f27a82019-11-12 11:41:41 -080090void VSyncDispatchTimerQueueEntry::update(VSyncTracker& tracker, nsecs_t now) {
Kevin DuBois305bef12019-10-09 13:23:27 -070091 if (!mArmedInfo) {
92 return;
93 }
Kevin DuBois305bef12019-10-09 13:23:27 -070094 auto const nextVsyncTime =
95 tracker.nextAnticipatedVSyncTimeFrom(std::max(mEarliestVsync, now + mWorkDuration));
96 mArmedInfo = {nextVsyncTime - mWorkDuration, nextVsyncTime};
97}
98
Kevin DuBoise4f27a82019-11-12 11:41:41 -080099void VSyncDispatchTimerQueueEntry::disarm() {
Kevin DuBois305bef12019-10-09 13:23:27 -0700100 mArmedInfo.reset();
101}
102
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800103nsecs_t VSyncDispatchTimerQueueEntry::executing() {
Kevin DuBois305bef12019-10-09 13:23:27 -0700104 mLastDispatchTime = mArmedInfo->mActualVsyncTime;
105 disarm();
106 return *mLastDispatchTime;
107}
108
Kevin DuBois2968afc2020-01-14 09:48:50 -0800109void VSyncDispatchTimerQueueEntry::callback(nsecs_t vsyncTimestamp, nsecs_t wakeupTimestamp) {
Kevin DuBois305bef12019-10-09 13:23:27 -0700110 {
111 std::lock_guard<std::mutex> lk(mRunningMutex);
112 mRunning = true;
113 }
114
Kevin DuBois2968afc2020-01-14 09:48:50 -0800115 mCallback(vsyncTimestamp, wakeupTimestamp);
Kevin DuBois305bef12019-10-09 13:23:27 -0700116
117 std::lock_guard<std::mutex> lk(mRunningMutex);
118 mRunning = false;
119 mCv.notify_all();
120}
121
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800122void VSyncDispatchTimerQueueEntry::ensureNotRunning() {
Kevin DuBois305bef12019-10-09 13:23:27 -0700123 std::unique_lock<std::mutex> lk(mRunningMutex);
124 mCv.wait(lk, [this]() REQUIRES(mRunningMutex) { return !mRunning; });
125}
126
Ady Abraham5e7371c2020-03-24 14:47:24 -0700127void VSyncDispatchTimerQueueEntry::dump(std::string& result) const {
128 std::lock_guard<std::mutex> lk(mRunningMutex);
129 std::string armedInfo;
130 if (mArmedInfo) {
131 StringAppendF(&armedInfo, "[wake up in %.2fms for vsync %.2fms from now]",
132 (mArmedInfo->mActualWakeupTime - systemTime()) / 1e6f,
133 (mArmedInfo->mActualVsyncTime - systemTime()) / 1e6f);
134 }
135
136 StringAppendF(&result, "\t\t%s: %s %s\n", mName.c_str(),
137 mRunning ? "(in callback function)" : "", armedInfo.c_str());
138 StringAppendF(&result, "\t\t\tmWorkDuration: %.2fms mEarliestVsync: %.2fms relative to now\n",
139 mWorkDuration / 1e6f, (mEarliestVsync - systemTime()) / 1e6f);
140
141 if (mLastDispatchTime) {
142 StringAppendF(&result, "\t\t\tmLastDispatchTime: %.2fms ago\n",
143 (systemTime() - *mLastDispatchTime) / 1e6f);
144 } else {
145 StringAppendF(&result, "\t\t\tmLastDispatchTime unknown\n");
146 }
147}
148
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800149VSyncDispatchTimerQueue::VSyncDispatchTimerQueue(std::unique_ptr<TimeKeeper> tk,
Kevin DuBoisc94ca832019-11-26 12:56:24 -0800150 VSyncTracker& tracker, nsecs_t timerSlack,
151 nsecs_t minVsyncDistance)
152 : mTimeKeeper(std::move(tk)),
153 mTracker(tracker),
154 mTimerSlack(timerSlack),
155 mMinVsyncDistance(minVsyncDistance) {}
Kevin DuBois305bef12019-10-09 13:23:27 -0700156
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800157VSyncDispatchTimerQueue::~VSyncDispatchTimerQueue() {
Kevin DuBois305bef12019-10-09 13:23:27 -0700158 std::lock_guard<decltype(mMutex)> lk(mMutex);
159 cancelTimer();
160}
161
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800162void VSyncDispatchTimerQueue::cancelTimer() {
Kevin DuBois305bef12019-10-09 13:23:27 -0700163 mIntendedWakeupTime = kInvalidTime;
164 mTimeKeeper->alarmCancel();
165}
166
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800167void VSyncDispatchTimerQueue::setTimer(nsecs_t targetTime, nsecs_t now) {
Kevin DuBois305bef12019-10-09 13:23:27 -0700168 mIntendedWakeupTime = targetTime;
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800169 mTimeKeeper->alarmIn(std::bind(&VSyncDispatchTimerQueue::timerCallback, this),
170 targetTime - now);
Kevin DuBois305bef12019-10-09 13:23:27 -0700171}
172
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800173void VSyncDispatchTimerQueue::rearmTimer(nsecs_t now) {
Kevin DuBois305bef12019-10-09 13:23:27 -0700174 rearmTimerSkippingUpdateFor(now, mCallbacks.end());
175}
176
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800177void VSyncDispatchTimerQueue::TraceBuffer::note(std::string_view name, nsecs_t alarmIn,
178 nsecs_t vsFor) {
179 if (ATRACE_ENABLED()) {
180 snprintf(str_buffer.data(), str_buffer.size(), "%.4s%s%" PRId64 "%s%" PRId64,
181 name.substr(0, kMaxNamePrint).data(), kTraceNamePrefix, alarmIn,
182 kTraceNameSeparator, vsFor);
183 }
184 ATRACE_NAME(str_buffer.data());
185}
186
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800187void VSyncDispatchTimerQueue::rearmTimerSkippingUpdateFor(
188 nsecs_t now, CallbackMap::iterator const& skipUpdateIt) {
Kevin DuBois305bef12019-10-09 13:23:27 -0700189 std::optional<nsecs_t> min;
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800190 std::optional<nsecs_t> targetVsync;
191 std::optional<std::string_view> nextWakeupName;
Kevin DuBois305bef12019-10-09 13:23:27 -0700192 for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) {
193 auto& callback = it->second;
194 if (!callback->wakeupTime()) {
195 continue;
196 }
197
198 if (it != skipUpdateIt) {
199 callback->update(mTracker, now);
200 }
201 auto const wakeupTime = *callback->wakeupTime();
202 if (!min || (min && *min > wakeupTime)) {
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800203 nextWakeupName = callback->name();
Kevin DuBois305bef12019-10-09 13:23:27 -0700204 min = wakeupTime;
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800205 targetVsync = callback->targetVsync();
Kevin DuBois305bef12019-10-09 13:23:27 -0700206 }
207 }
208
209 if (min && (min < mIntendedWakeupTime)) {
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800210 if (targetVsync && nextWakeupName) {
211 mTraceBuffer.note(*nextWakeupName, *min - now, *targetVsync - now);
212 }
Kevin DuBois305bef12019-10-09 13:23:27 -0700213 setTimer(*min, now);
214 } else {
Kevin DuBoisecb1f0d2019-12-12 10:47:41 -0800215 ATRACE_NAME("cancel timer");
Kevin DuBois305bef12019-10-09 13:23:27 -0700216 cancelTimer();
217 }
218}
219
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800220void VSyncDispatchTimerQueue::timerCallback() {
Kevin DuBois305bef12019-10-09 13:23:27 -0700221 struct Invocation {
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800222 std::shared_ptr<VSyncDispatchTimerQueueEntry> callback;
Kevin DuBois2968afc2020-01-14 09:48:50 -0800223 nsecs_t vsyncTimestamp;
224 nsecs_t wakeupTimestamp;
Kevin DuBois305bef12019-10-09 13:23:27 -0700225 };
226 std::vector<Invocation> invocations;
227 {
228 std::lock_guard<decltype(mMutex)> lk(mMutex);
229 for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) {
230 auto& callback = it->second;
231 auto const wakeupTime = callback->wakeupTime();
232 if (!wakeupTime) {
233 continue;
234 }
235
236 if (*wakeupTime < mIntendedWakeupTime + mTimerSlack) {
237 callback->executing();
238 invocations.emplace_back(
Kevin DuBois2968afc2020-01-14 09:48:50 -0800239 Invocation{callback, *callback->lastExecutedVsyncTarget(), *wakeupTime});
Kevin DuBois305bef12019-10-09 13:23:27 -0700240 }
241 }
242
243 mIntendedWakeupTime = kInvalidTime;
244 rearmTimer(mTimeKeeper->now());
245 }
246
247 for (auto const& invocation : invocations) {
Kevin DuBois2968afc2020-01-14 09:48:50 -0800248 invocation.callback->callback(invocation.vsyncTimestamp, invocation.wakeupTimestamp);
Kevin DuBois305bef12019-10-09 13:23:27 -0700249 }
250}
251
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800252VSyncDispatchTimerQueue::CallbackToken VSyncDispatchTimerQueue::registerCallback(
Kevin DuBois2968afc2020-01-14 09:48:50 -0800253 Callback const& callbackFn, std::string callbackName) {
Kevin DuBois305bef12019-10-09 13:23:27 -0700254 std::lock_guard<decltype(mMutex)> lk(mMutex);
255 return CallbackToken{
256 mCallbacks
257 .emplace(++mCallbackToken,
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800258 std::make_shared<VSyncDispatchTimerQueueEntry>(callbackName,
Kevin DuBoisc94ca832019-11-26 12:56:24 -0800259 callbackFn,
260 mMinVsyncDistance))
Kevin DuBois305bef12019-10-09 13:23:27 -0700261 .first->first};
262}
263
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800264void VSyncDispatchTimerQueue::unregisterCallback(CallbackToken token) {
265 std::shared_ptr<VSyncDispatchTimerQueueEntry> entry = nullptr;
Kevin DuBois305bef12019-10-09 13:23:27 -0700266 {
267 std::lock_guard<decltype(mMutex)> lk(mMutex);
268 auto it = mCallbacks.find(token);
269 if (it != mCallbacks.end()) {
270 entry = it->second;
271 mCallbacks.erase(it);
272 }
273 }
274
275 if (entry) {
276 entry->ensureNotRunning();
277 }
278}
279
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800280ScheduleResult VSyncDispatchTimerQueue::schedule(CallbackToken token, nsecs_t workDuration,
281 nsecs_t earliestVsync) {
Kevin DuBois305bef12019-10-09 13:23:27 -0700282 auto result = ScheduleResult::Error;
283 {
284 std::lock_guard<decltype(mMutex)> lk(mMutex);
285
286 auto it = mCallbacks.find(token);
287 if (it == mCallbacks.end()) {
288 return result;
289 }
290 auto& callback = it->second;
Kevin DuBois305bef12019-10-09 13:23:27 -0700291 auto const now = mTimeKeeper->now();
Kevin DuBois2311b1a2019-11-18 16:19:08 -0800292 result = callback->schedule(workDuration, earliestVsync, mTracker, now);
293 if (result == ScheduleResult::CannotSchedule) {
294 return result;
Kevin DuBois305bef12019-10-09 13:23:27 -0700295 }
296
Kevin DuBois2311b1a2019-11-18 16:19:08 -0800297 if (callback->wakeupTime() < mIntendedWakeupTime - mTimerSlack) {
Kevin DuBois305bef12019-10-09 13:23:27 -0700298 rearmTimerSkippingUpdateFor(now, it);
299 }
300 }
301
302 return result;
303}
304
Kevin DuBoise4f27a82019-11-12 11:41:41 -0800305CancelResult VSyncDispatchTimerQueue::cancel(CallbackToken token) {
Kevin DuBois305bef12019-10-09 13:23:27 -0700306 std::lock_guard<decltype(mMutex)> lk(mMutex);
307
308 auto it = mCallbacks.find(token);
309 if (it == mCallbacks.end()) {
310 return CancelResult::Error;
311 }
312 auto& callback = it->second;
313
314 if (callback->wakeupTime()) {
315 callback->disarm();
316 mIntendedWakeupTime = kInvalidTime;
317 rearmTimer(mTimeKeeper->now());
318 return CancelResult::Cancelled;
319 }
320 return CancelResult::TooLate;
321}
322
Ady Abraham5e7371c2020-03-24 14:47:24 -0700323void VSyncDispatchTimerQueue::dump(std::string& result) const {
324 std::lock_guard<decltype(mMutex)> lk(mMutex);
325 StringAppendF(&result, "\tmTimerSlack: %.2fms mMinVsyncDistance: %.2fms\n", mTimerSlack / 1e6f,
326 mMinVsyncDistance / 1e6f);
327 StringAppendF(&result, "\tmIntendedWakeupTime: %.2fms from now\n",
328 (mIntendedWakeupTime - systemTime()) / 1e6f);
329 StringAppendF(&result, "\tCallbacks:\n");
330 for (const auto& [token, entry] : mCallbacks) {
331 entry->dump(result);
332 }
333}
334
Kevin DuBois305bef12019-10-09 13:23:27 -0700335VSyncCallbackRegistration::VSyncCallbackRegistration(VSyncDispatch& dispatch,
Kevin DuBois2968afc2020-01-14 09:48:50 -0800336 VSyncDispatch::Callback const& callbackFn,
Kevin DuBois305bef12019-10-09 13:23:27 -0700337 std::string const& callbackName)
338 : mDispatch(dispatch),
339 mToken(dispatch.registerCallback(callbackFn, callbackName)),
340 mValidToken(true) {}
341
342VSyncCallbackRegistration::VSyncCallbackRegistration(VSyncCallbackRegistration&& other)
343 : mDispatch(other.mDispatch),
344 mToken(std::move(other.mToken)),
345 mValidToken(std::move(other.mValidToken)) {
346 other.mValidToken = false;
347}
348
349VSyncCallbackRegistration& VSyncCallbackRegistration::operator=(VSyncCallbackRegistration&& other) {
350 mDispatch = std::move(other.mDispatch);
351 mToken = std::move(other.mToken);
352 mValidToken = std::move(other.mValidToken);
353 other.mValidToken = false;
354 return *this;
355}
356
357VSyncCallbackRegistration::~VSyncCallbackRegistration() {
358 if (mValidToken) mDispatch.get().unregisterCallback(mToken);
359}
360
361ScheduleResult VSyncCallbackRegistration::schedule(nsecs_t workDuration, nsecs_t earliestVsync) {
Kevin DuBoisc94ca832019-11-26 12:56:24 -0800362 if (!mValidToken) {
363 return ScheduleResult::Error;
364 }
Kevin DuBois305bef12019-10-09 13:23:27 -0700365 return mDispatch.get().schedule(mToken, workDuration, earliestVsync);
366}
367
368CancelResult VSyncCallbackRegistration::cancel() {
Kevin DuBoisc94ca832019-11-26 12:56:24 -0800369 if (!mValidToken) {
370 return CancelResult::Error;
371 }
Kevin DuBois305bef12019-10-09 13:23:27 -0700372 return mDispatch.get().cancel(mToken);
373}
374
375} // namespace android::scheduler