1 /*
2 * Copyright (C) 2015 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 | ATRACE_TAG_HAL)
18
19 #define LOG_TAG "hwc-vsync-worker"
20
21 #include "vsyncworker.h"
22
23 #include <hardware/hardware.h>
24 #include <log/log.h>
25 #include <stdlib.h>
26 #include <time.h>
27 #include <utils/Trace.h>
28 #include <xf86drm.h>
29 #include <xf86drmMode.h>
30
31 #include <map>
32
33 #include "drmdevice.h"
34 #include "worker.h"
35
36 using namespace std::chrono_literals;
37
38 constexpr auto nsecsPerSec = std::chrono::nanoseconds(1s).count();
39
40 namespace android {
41
VSyncWorker()42 VSyncWorker::VSyncWorker()
43 : Worker("vsync", 2, true),
44 drm_(NULL),
45 display_(-1),
46 enabled_(false),
47 last_timestamp_(-1) {
48 }
49
~VSyncWorker()50 VSyncWorker::~VSyncWorker() {
51 Exit();
52 }
53
Init(DrmDevice * drm,int display,const String8 & display_trace_name)54 int VSyncWorker::Init(DrmDevice *drm, int display, const String8 &display_trace_name) {
55 drm_ = drm;
56 display_ = display;
57 display_trace_name_ = display_trace_name;
58 hw_vsync_period_tag_.appendFormat("HWVsyncPeriod for %s", display_trace_name.string());
59 hw_vsync_enabled_tag_.appendFormat("HWCVsync for %s", display_trace_name.string());
60
61 return InitWorker();
62 }
63
RegisterCallback(std::shared_ptr<VsyncCallback> callback)64 void VSyncWorker::RegisterCallback(std::shared_ptr<VsyncCallback> callback) {
65 Lock();
66 callback_ = callback;
67 Unlock();
68 }
69
VSyncControl(bool enabled)70 void VSyncWorker::VSyncControl(bool enabled) {
71 Lock();
72 enabled_ = enabled;
73 last_timestamp_ = -1;
74 Unlock();
75
76 ATRACE_INT(hw_vsync_enabled_tag_.string(), static_cast<int32_t>(enabled));
77 ATRACE_INT64(hw_vsync_period_tag_.string(), 0);
78 Signal();
79 }
80
81 /*
82 * Returns the timestamp of the next vsync in phase with last_timestamp_.
83 * For example:
84 * last_timestamp_ = 137
85 * frame_ns = 50
86 * current = 683
87 *
88 * expect = (50 * ((683 - 137)/50 + 1)) + 137
89 * expect = 687
90 *
91 * Thus, we must sleep until timestamp 687 to maintain phase with the last
92 * timestamp. But if we don't know last vblank timestamp, sleep one vblank
93 * then try to get vblank from driver again.
94 */
GetPhasedVSync(int64_t frame_ns,int64_t & expect)95 int VSyncWorker::GetPhasedVSync(int64_t frame_ns, int64_t &expect) {
96 struct timespec now;
97 if (clock_gettime(CLOCK_MONOTONIC, &now)) {
98 ALOGE("clock_gettime failed %d", errno);
99 return -EPERM;
100 }
101
102 int64_t current = now.tv_sec * nsecsPerSec + now.tv_nsec;
103 if (last_timestamp_ < 0) {
104 expect = current + frame_ns;
105 return -EAGAIN;
106 }
107
108 expect = frame_ns * ((current - last_timestamp_) / frame_ns + 1) + last_timestamp_;
109
110 return 0;
111 }
112
SyntheticWaitVBlank(int64_t & timestamp)113 int VSyncWorker::SyntheticWaitVBlank(int64_t ×tamp) {
114 float refresh = 60.0f; // Default to 60Hz refresh rate
115
116 DrmConnector *conn = drm_->GetConnectorForDisplay(display_);
117 if (conn && conn->active_mode().v_refresh() != 0.0f) {
118 refresh = conn->active_mode().v_refresh();
119 } else {
120 ALOGW("Vsync worker active with conn=%p refresh=%f\n", conn,
121 conn ? conn->active_mode().v_refresh() : 0.0f);
122 }
123
124 int64_t phased_timestamp;
125 int ret = GetPhasedVSync(nsecsPerSec / refresh, phased_timestamp);
126 if (ret && ret != -EAGAIN) return -1;
127
128 struct timespec vsync;
129 vsync.tv_sec = phased_timestamp / nsecsPerSec;
130 vsync.tv_nsec = phased_timestamp % nsecsPerSec;
131
132 int err;
133 do {
134 err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &vsync, nullptr);
135 } while (err == EINTR);
136 if (err || ret) return -1;
137
138 timestamp = (int64_t)vsync.tv_sec * nsecsPerSec + (int64_t)vsync.tv_nsec;
139
140 return 0;
141 }
142
Routine()143 void VSyncWorker::Routine() {
144 int ret;
145
146 Lock();
147 if (!enabled_) {
148 ret = WaitForSignalOrExitLocked();
149 if (ret == -EINTR) {
150 Unlock();
151 return;
152 }
153 }
154
155 int display = display_;
156 std::shared_ptr<VsyncCallback> callback(callback_);
157 Unlock();
158
159 DrmCrtc *crtc = drm_->GetCrtcForDisplay(display);
160 if (!crtc) {
161 ALOGE("Failed to get crtc for display");
162 return;
163 }
164 uint32_t high_crtc = (crtc->pipe() << DRM_VBLANK_HIGH_CRTC_SHIFT);
165
166 drmVBlank vblank;
167 memset(&vblank, 0, sizeof(vblank));
168 vblank.request.type =
169 (drmVBlankSeqType)(DRM_VBLANK_RELATIVE | (high_crtc & DRM_VBLANK_HIGH_CRTC_MASK));
170 vblank.request.sequence = 1;
171
172 int64_t timestamp;
173 ret = drmWaitVBlank(drm_->fd(), &vblank);
174 if (ret) {
175 if (SyntheticWaitVBlank(timestamp)) {
176 // postpone the callback until we get a real value from the hardware
177 return;
178 }
179 } else {
180 timestamp = (int64_t)vblank.reply.tval_sec * nsecsPerSec +
181 (int64_t)vblank.reply.tval_usec * 1000;
182 }
183
184 /*
185 * VSync could be disabled during routine execution so it could potentially
186 * lead to crash since callback's inner hook could be invalid anymore. We have
187 * no control over lifetime of this hook, therefore we can't rely that it'll
188 * be valid after vsync disabling.
189 *
190 * Blocking VSyncControl to wait until routine
191 * will finish execution is logically correct way to fix this issue, but it
192 * creates visible lags and stutters, so we have to resort to other ways of
193 * mitigating this issue.
194 *
195 * Doing check before attempt to invoke callback drastically shortens the
196 * window when such situation could happen and that allows us to practically
197 * avoid this issue.
198 *
199 * Please note that issue described below is different one and it is related
200 * to RegisterCallback, not to disabling vsync via VSyncControl.
201 */
202 if (!enabled_) return;
203 /*
204 * There's a race here where a change in callback_ will not take effect until
205 * the next subsequent requested vsync. This is unavoidable since we can't
206 * call the vsync hook while holding the thread lock.
207 *
208 * We could shorten the race window by caching callback_ right before calling
209 * the hook. However, in practice, callback_ is only updated once, so it's not
210 * worth the overhead.
211 */
212 if (callback) callback->Callback(display, timestamp);
213
214 if (last_timestamp_ >= 0) {
215 int64_t period = timestamp - last_timestamp_;
216 ATRACE_INT64(hw_vsync_period_tag_.string(), period);
217 ALOGV("HW vsync period %" PRId64 "ns for %s", period, display_trace_name_.string());
218 }
219
220 last_timestamp_ = timestamp;
221 }
222 } // namespace android
223