blob: c9b2e778712dd8d26ea017ee3d7051bbcc80ed16 [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
18#include <utils/Trace.h>
19#include <vector>
20
21#include "TimeKeeper.h"
22#include "VSyncDispatch.h"
23#include "VSyncTracker.h"
24
25namespace android::scheduler {
26
27VSyncTracker::~VSyncTracker() = default;
28TimeKeeper::~TimeKeeper() = default;
29
30impl::VSyncDispatchEntry::VSyncDispatchEntry(std::string const& name,
31 std::function<void(nsecs_t)> const& cb)
32 : mName(name), mCallback(cb), mWorkDuration(0), mEarliestVsync(0) {}
33
34std::optional<nsecs_t> impl::VSyncDispatchEntry::lastExecutedVsyncTarget() const {
35 return mLastDispatchTime;
36}
37
38std::string_view impl::VSyncDispatchEntry::name() const {
39 return mName;
40}
41
42std::optional<nsecs_t> impl::VSyncDispatchEntry::wakeupTime() const {
43 if (!mArmedInfo) {
44 return {};
45 }
46 return {mArmedInfo->mActualWakeupTime};
47}
48
49nsecs_t impl::VSyncDispatchEntry::schedule(nsecs_t workDuration, nsecs_t earliestVsync,
50 VSyncTracker& tracker, nsecs_t now) {
51 mWorkDuration = workDuration;
52 mEarliestVsync = earliestVsync;
53 arm(tracker, now);
54 return mArmedInfo->mActualWakeupTime;
55}
56
57void impl::VSyncDispatchEntry::update(VSyncTracker& tracker, nsecs_t now) {
58 if (!mArmedInfo) {
59 return;
60 }
61 arm(tracker, now);
62}
63
64void impl::VSyncDispatchEntry::arm(VSyncTracker& tracker, nsecs_t now) {
65 auto const nextVsyncTime =
66 tracker.nextAnticipatedVSyncTimeFrom(std::max(mEarliestVsync, now + mWorkDuration));
67 mArmedInfo = {nextVsyncTime - mWorkDuration, nextVsyncTime};
68}
69
70void impl::VSyncDispatchEntry::disarm() {
71 mArmedInfo.reset();
72}
73
74nsecs_t impl::VSyncDispatchEntry::executing() {
75 mLastDispatchTime = mArmedInfo->mActualVsyncTime;
76 disarm();
77 return *mLastDispatchTime;
78}
79
80void impl::VSyncDispatchEntry::callback(nsecs_t t) {
81 {
82 std::lock_guard<std::mutex> lk(mRunningMutex);
83 mRunning = true;
84 }
85
86 mCallback(t);
87
88 std::lock_guard<std::mutex> lk(mRunningMutex);
89 mRunning = false;
90 mCv.notify_all();
91}
92
93void impl::VSyncDispatchEntry::ensureNotRunning() {
94 std::unique_lock<std::mutex> lk(mRunningMutex);
95 mCv.wait(lk, [this]() REQUIRES(mRunningMutex) { return !mRunning; });
96}
97
98VSyncDispatch::VSyncDispatch(std::unique_ptr<TimeKeeper> tk, VSyncTracker& tracker,
99 nsecs_t timerSlack)
100 : mTimeKeeper(std::move(tk)), mTracker(tracker), mTimerSlack(timerSlack) {}
101
102VSyncDispatch::~VSyncDispatch() {
103 std::lock_guard<decltype(mMutex)> lk(mMutex);
104 cancelTimer();
105}
106
107void VSyncDispatch::cancelTimer() {
108 mIntendedWakeupTime = kInvalidTime;
109 mTimeKeeper->alarmCancel();
110}
111
112void VSyncDispatch::setTimer(nsecs_t targetTime, nsecs_t now) {
113 mIntendedWakeupTime = targetTime;
114 mTimeKeeper->alarmIn(std::bind(&VSyncDispatch::timerCallback, this), targetTime - now);
115}
116
117void VSyncDispatch::rearmTimer(nsecs_t now) {
118 rearmTimerSkippingUpdateFor(now, mCallbacks.end());
119}
120
121void VSyncDispatch::rearmTimerSkippingUpdateFor(nsecs_t now,
122 CallbackMap::iterator const& skipUpdateIt) {
123 std::optional<nsecs_t> min;
124 for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) {
125 auto& callback = it->second;
126 if (!callback->wakeupTime()) {
127 continue;
128 }
129
130 if (it != skipUpdateIt) {
131 callback->update(mTracker, now);
132 }
133 auto const wakeupTime = *callback->wakeupTime();
134 if (!min || (min && *min > wakeupTime)) {
135 min = wakeupTime;
136 }
137 }
138
139 if (min && (min < mIntendedWakeupTime)) {
140 setTimer(*min, now);
141 } else {
142 cancelTimer();
143 }
144}
145
146void VSyncDispatch::timerCallback() {
147 struct Invocation {
148 std::shared_ptr<impl::VSyncDispatchEntry> callback;
149 nsecs_t timestamp;
150 };
151 std::vector<Invocation> invocations;
152 {
153 std::lock_guard<decltype(mMutex)> lk(mMutex);
154 for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) {
155 auto& callback = it->second;
156 auto const wakeupTime = callback->wakeupTime();
157 if (!wakeupTime) {
158 continue;
159 }
160
161 if (*wakeupTime < mIntendedWakeupTime + mTimerSlack) {
162 callback->executing();
163 invocations.emplace_back(
164 Invocation{callback, *callback->lastExecutedVsyncTarget()});
165 }
166 }
167
168 mIntendedWakeupTime = kInvalidTime;
169 rearmTimer(mTimeKeeper->now());
170 }
171
172 for (auto const& invocation : invocations) {
173 invocation.callback->callback(invocation.timestamp);
174 }
175}
176
177VSyncDispatch::CallbackToken VSyncDispatch::registerCallback(
178 std::function<void(nsecs_t)> const& callbackFn, std::string callbackName) {
179 std::lock_guard<decltype(mMutex)> lk(mMutex);
180 return CallbackToken{
181 mCallbacks
182 .emplace(++mCallbackToken,
183 std::make_shared<impl::VSyncDispatchEntry>(callbackName, callbackFn))
184 .first->first};
185}
186
187void VSyncDispatch::unregisterCallback(CallbackToken token) {
188 std::shared_ptr<impl::VSyncDispatchEntry> entry = nullptr;
189 {
190 std::lock_guard<decltype(mMutex)> lk(mMutex);
191 auto it = mCallbacks.find(token);
192 if (it != mCallbacks.end()) {
193 entry = it->second;
194 mCallbacks.erase(it);
195 }
196 }
197
198 if (entry) {
199 entry->ensureNotRunning();
200 }
201}
202
203ScheduleResult VSyncDispatch::schedule(CallbackToken token, nsecs_t workDuration,
204 nsecs_t earliestVsync) {
205 auto result = ScheduleResult::Error;
206 {
207 std::lock_guard<decltype(mMutex)> lk(mMutex);
208
209 auto it = mCallbacks.find(token);
210 if (it == mCallbacks.end()) {
211 return result;
212 }
213 auto& callback = it->second;
214 result = callback->wakeupTime() ? ScheduleResult::ReScheduled : ScheduleResult::Scheduled;
215
216 auto const now = mTimeKeeper->now();
217 auto const wakeupTime = callback->schedule(workDuration, earliestVsync, mTracker, now);
218
219 if (wakeupTime < now - mTimerSlack || callback->lastExecutedVsyncTarget() > wakeupTime) {
220 return ScheduleResult::CannotSchedule;
221 }
222
223 if (wakeupTime < mIntendedWakeupTime - mTimerSlack) {
224 rearmTimerSkippingUpdateFor(now, it);
225 }
226 }
227
228 return result;
229}
230
231CancelResult VSyncDispatch::cancel(CallbackToken token) {
232 std::lock_guard<decltype(mMutex)> lk(mMutex);
233
234 auto it = mCallbacks.find(token);
235 if (it == mCallbacks.end()) {
236 return CancelResult::Error;
237 }
238 auto& callback = it->second;
239
240 if (callback->wakeupTime()) {
241 callback->disarm();
242 mIntendedWakeupTime = kInvalidTime;
243 rearmTimer(mTimeKeeper->now());
244 return CancelResult::Cancelled;
245 }
246 return CancelResult::TooLate;
247}
248
249VSyncCallbackRegistration::VSyncCallbackRegistration(VSyncDispatch& dispatch,
250 std::function<void(nsecs_t)> const& callbackFn,
251 std::string const& callbackName)
252 : mDispatch(dispatch),
253 mToken(dispatch.registerCallback(callbackFn, callbackName)),
254 mValidToken(true) {}
255
256VSyncCallbackRegistration::VSyncCallbackRegistration(VSyncCallbackRegistration&& other)
257 : mDispatch(other.mDispatch),
258 mToken(std::move(other.mToken)),
259 mValidToken(std::move(other.mValidToken)) {
260 other.mValidToken = false;
261}
262
263VSyncCallbackRegistration& VSyncCallbackRegistration::operator=(VSyncCallbackRegistration&& other) {
264 mDispatch = std::move(other.mDispatch);
265 mToken = std::move(other.mToken);
266 mValidToken = std::move(other.mValidToken);
267 other.mValidToken = false;
268 return *this;
269}
270
271VSyncCallbackRegistration::~VSyncCallbackRegistration() {
272 if (mValidToken) mDispatch.get().unregisterCallback(mToken);
273}
274
275ScheduleResult VSyncCallbackRegistration::schedule(nsecs_t workDuration, nsecs_t earliestVsync) {
276 if (!mValidToken) return ScheduleResult::Error;
277 return mDispatch.get().schedule(mToken, workDuration, earliestVsync);
278}
279
280CancelResult VSyncCallbackRegistration::cancel() {
281 if (!mValidToken) return CancelResult::Error;
282 return mDispatch.get().cancel(mToken);
283}
284
285} // namespace android::scheduler