Debian Codegraph @

src/vblank.c

raw symbols SCIP
1 // SPDX-License-Identifier: MPL-2.0
2 // Copyright (c) Yuxuan Shui <[email protected]>
3
4 #include <assert.h>
5
6 #include <ev.h>
7 #include <inttypes.h>
8 #include <stdatomic.h>
9 #include <string.h>
10 #include <time.h>
11 #include <xcb/xcb.h>
12 #include <xcb/xproto.h>
13 #include "config.h"
14
15 #ifdef CONFIG_OPENGL
16 // Enable sgi_video_sync_vblank_scheduler
17 #include <X11/X.h>
18 #include <X11/Xlib-xcb.h>
19 #include <X11/Xlib.h>
20 #include <X11/Xutil.h>
21 #include <epoxy/glx.h>
22 #include <pthread.h>
23
24 #endif
25
26 #include "compiler.h"
27 #include "log.h"
28 #include "utils/dynarr.h"
29 #include "vblank.h"
30 #include "x.h"
31
32 struct vblank_closure {
33 vblank_callback_t fn;
34 void *user_data;
35 };
36
37 #define VBLANK_WIND_DOWN 4
38
39 struct vblank_scheduler {
40 struct x_connection *c;
41 /// List of scheduled vblank callbacks, this is a dynarr
42 struct vblank_closure *callbacks;
43 struct ev_loop *loop;
44 /// Request extra vblank events even when no callbacks are scheduled.
45 /// This is because when callbacks are scheduled too close to a vblank,
46 /// we might send PresentNotifyMsc request too late and miss the vblank event.
47 /// So we request extra vblank events right after the last vblank event
48 /// to make sure this doesn't happen.
49 unsigned int wind_down;
50 xcb_window_t target_window;
51 enum vblank_scheduler_type type;
52 bool vblank_event_requested;
53 bool use_realtime_scheduling;
54 };
55
56 struct present_vblank_scheduler {
57 struct vblank_scheduler base;
58
59 uint64_t last_msc;
60 /// The timestamp for the end of last vblank.
61 uint64_t last_ust;
62 ev_timer callback_timer;
63 xcb_present_event_t event_id;
64 xcb_special_event_t *event;
65 };
66
67 struct vblank_scheduler_ops {
68 size_t size;
69 bool (*init)(struct vblank_scheduler *self);
70 void (*deinit)(struct vblank_scheduler *self);
71 bool (*schedule)(struct vblank_scheduler *self);
72 bool (*handle_x_events)(struct vblank_scheduler *self);
73 };
74
75 static void
76 vblank_scheduler_invoke_callbacks(struct vblank_scheduler *self, struct vblank_event *event);
77
78 #ifdef CONFIG_OPENGL
79 struct sgi_video_sync_vblank_scheduler {
80 struct vblank_scheduler base;
81
82 // Since glXWaitVideoSyncSGI blocks, we need to run it in a separate thread.
83 // ... and all the thread shenanigans that come with it.
84 _Atomic unsigned int current_msc;
85 alignas(8) _Atomic uint64_t current_ust;
86 ev_async notify;
87 pthread_t sync_thread;
88 bool running, error, vblank_requested;
89 unsigned int last_msc;
90 /// Number of synthesized vblank event. Currently these are being inserted when
91 /// the driver reports duplicate msc to us.
92 ///
93 /// This is because the NVIDIA driver has been observed to recover from a
94 /// duplicated msc loop by us rendering a new frame. So we insert a fake vblank
95 /// event so the render loop can progress, but doing so makes our msc desync from
96 /// the driver's msc. An hypothetical sequence of events go like this:
97 ///
98 /// - driver -> msc 1, we report msc 1
99 /// - driver -> msc 1 (duplicate msc! if we don't render a new frame, we'll
100 /// be stuck here forever)
101 /// - we report msc 2
102 /// - new frame rendered, driver recover
103 /// - driver -> msc 2, but we already reported msc 2, so we have to report msc 3
104 unsigned int vblank_inserted;
105
106 /// Protects `running`, and `vblank_requested`
107 pthread_mutex_t vblank_requested_mtx;
108 pthread_cond_t vblank_requested_cnd;
109 };
110
111 struct sgi_video_sync_thread_args {
112 struct sgi_video_sync_vblank_scheduler *self;
113 int start_status;
114 bool use_realtime_scheduling;
115 pthread_mutex_t start_mtx;
116 pthread_cond_t start_cnd;
117 };
118
119 static bool check_sgi_video_sync_extension(Display *dpy, int screen) {
120 const char *glx_ext = glXQueryExtensionsString(dpy, screen);
121 const char *needle = "GLX_SGI_video_sync";
122 char *found = strstr(glx_ext, needle);
123 if (!found) {
124 return false;
125 }
126 if (found != glx_ext && found[-1] != ' ') {
127 return false;
128 }
129 if (found[strlen(needle)] != ' ' && found[strlen(needle)] != '\0') {
130 return false;
131 }
132
133 return true;
134 }
135
136 static void *sgi_video_sync_thread(void *data) {
137 auto args = (struct sgi_video_sync_thread_args *)data;
138 auto self = args->self;
139 Display *dpy = XOpenDisplay(NULL);
140 int error_code = 0;
141 GLXContext ctx = NULL;
142 GLXDrawable drawable = None;
143 Window root = DefaultRootWindow(dpy), dummy = None;
144 if (!dpy) {
145 error_code = 1;
146 goto start_failed;
147 }
148 int screen = DefaultScreen(dpy);
149 int ncfg = 0;
150 GLXFBConfig *cfg_ = glXChooseFBConfig(
151 dpy, screen,
152 (int[]){GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, 0},
153 &ncfg);
154
155 if (!cfg_) {
156 error_code = 2;
157 goto start_failed;
158 }
159 GLXFBConfig cfg = cfg_[0];
160 XFree(cfg_);
161
162 XVisualInfo *vi = glXGetVisualFromFBConfig(dpy, cfg);
163 if (!vi) {
164 error_code = 3;
165 goto start_failed;
166 }
167
168 Visual *visual = vi->visual;
169 const int depth = vi->depth;
170 XFree(vi);
171
172 Colormap colormap = XCreateColormap(dpy, root, visual, AllocNone);
173 XSetWindowAttributes attributes;
174 attributes.colormap = colormap;
175
176 dummy = XCreateWindow(dpy, root, 0, 0, 1, 1, 0, depth, InputOutput, visual,
177 CWColormap, &attributes);
178 XFreeColormap(dpy, colormap);
179 if (dummy == None) {
180 error_code = 4;
181 goto start_failed;
182 }
183
184 drawable = glXCreateWindow(dpy, cfg, dummy, NULL);
185 if (drawable == None) {
186 error_code = 5;
187 goto start_failed;
188 }
189
190 ctx = glXCreateNewContext(dpy, cfg, GLX_RGBA_TYPE, 0, true);
191 if (ctx == NULL) {
192 error_code = 6;
193 goto start_failed;
194 }
195
196 if (!glXMakeContextCurrent(dpy, drawable, drawable, ctx)) {
197 error_code = 7;
198 goto start_failed;
199 }
200
201 if (!check_sgi_video_sync_extension(dpy, screen)) {
202 error_code = 8;
203 goto start_failed;
204 }
205
206 log_init_tls();
207
208 if (args->use_realtime_scheduling) {
209 set_rr_scheduling();
210 }
211
212 pthread_mutex_lock(&args->start_mtx);
213 args->start_status = 0;
214 pthread_cond_signal(&args->start_cnd);
215 pthread_mutex_unlock(&args->start_mtx);
216
217 unsigned int last_msc = 0;
218
219 pthread_mutex_lock(&self->vblank_requested_mtx);
220 while (self->running) {
221 if (!self->vblank_requested) {
222 pthread_cond_wait(&self->vblank_requested_cnd,
223 &self->vblank_requested_mtx);
224 continue;
225 }
226 pthread_mutex_unlock(&self->vblank_requested_mtx);
227
228 glXWaitVideoSyncSGI(1, 0, &last_msc);
229
230 struct timespec now = {};
231 clock_gettime(CLOCK_MONOTONIC, &now);
232 atomic_store(&self->current_msc, last_msc);
233 atomic_store(&self->current_ust,
234 (uint64_t)(now.tv_sec * 1000000 + now.tv_nsec / 1000));
235 pthread_mutex_lock(&self->vblank_requested_mtx);
236 self->vblank_requested = false;
237 ev_async_send(self->base.loop, &self->notify);
238 }
239 pthread_mutex_unlock(&self->vblank_requested_mtx);
240 goto cleanup;
241
242 start_failed:
243 pthread_mutex_lock(&args->start_mtx);
244 args->start_status = error_code;
245 pthread_cond_signal(&args->start_cnd);
246 pthread_mutex_unlock(&args->start_mtx);
247
248 cleanup:
249 log_deinit_tls();
250 if (dpy) {
251 glXMakeCurrent(dpy, None, NULL);
252 if (ctx) {
253 glXDestroyContext(dpy, ctx);
254 }
255 if (drawable) {
256 glXDestroyWindow(dpy, drawable);
257 }
258 if (dummy) {
259 XDestroyWindow(dpy, dummy);
260 }
261 XCloseDisplay(dpy);
262 }
263 return NULL;
264 }
265
266 static bool sgi_video_sync_scheduler_schedule(struct vblank_scheduler *base) {
267 auto self = (struct sgi_video_sync_vblank_scheduler *)base;
268 if (self->error) {
269 return false;
270 }
271 assert(!base->vblank_event_requested);
272
273 log_verbose("Requesting vblank event for msc %d", self->current_msc + 1);
274 pthread_mutex_lock(&self->vblank_requested_mtx);
275 self->vblank_requested = true;
276 pthread_cond_signal(&self->vblank_requested_cnd);
277 pthread_mutex_unlock(&self->vblank_requested_mtx);
278
279 base->vblank_event_requested = true;
280 return true;
281 }
282
283 static void
284 sgi_video_sync_scheduler_callback(EV_P attr_unused, ev_async *w, int attr_unused revents);
285
286 static bool sgi_video_sync_scheduler_init(struct vblank_scheduler *base) {
287 auto self = (struct sgi_video_sync_vblank_scheduler *)base;
288 auto args = (struct sgi_video_sync_thread_args){
289 .self = self,
290 .start_status = -1,
291 .use_realtime_scheduling = base->use_realtime_scheduling,
292 };
293 bool succeeded = true;
294 pthread_mutex_init(&args.start_mtx, NULL);
295 pthread_cond_init(&args.start_cnd, NULL);
296
297 base->type = VBLANK_SCHEDULER_SGI_VIDEO_SYNC;
298 ev_async_init(&self->notify, sgi_video_sync_scheduler_callback);
299 ev_async_start(base->loop, &self->notify);
300 pthread_mutex_init(&self->vblank_requested_mtx, NULL);
301 pthread_cond_init(&self->vblank_requested_cnd, NULL);
302
303 self->vblank_requested = false;
304 self->running = true;
305 pthread_create(&self->sync_thread, NULL, sgi_video_sync_thread, &args);
306
307 pthread_mutex_lock(&args.start_mtx);
308 while (args.start_status == -1) {
309 pthread_cond_wait(&args.start_cnd, &args.start_mtx);
310 }
311 if (args.start_status != 0) {
312 log_fatal("Failed to start sgi_video_sync_thread, error code: %d",
313 args.start_status);
314 succeeded = false;
315 } else {
316 log_info("Started sgi_video_sync_thread");
317 }
318 self->error = !succeeded;
319 self->last_msc = 0;
320 pthread_mutex_destroy(&args.start_mtx);
321 pthread_cond_destroy(&args.start_cnd);
322 return succeeded;
323 }
324
325 static void sgi_video_sync_scheduler_deinit(struct vblank_scheduler *base) {
326 auto self = (struct sgi_video_sync_vblank_scheduler *)base;
327 ev_async_stop(base->loop, &self->notify);
328 pthread_mutex_lock(&self->vblank_requested_mtx);
329 self->running = false;
330 pthread_cond_signal(&self->vblank_requested_cnd);
331 pthread_mutex_unlock(&self->vblank_requested_mtx);
332
333 pthread_join(self->sync_thread, NULL);
334
335 pthread_mutex_destroy(&self->vblank_requested_mtx);
336 pthread_cond_destroy(&self->vblank_requested_cnd);
337 }
338
339 static void
340 sgi_video_sync_scheduler_callback(EV_P attr_unused, ev_async *w, int attr_unused revents) {
341 auto sched = container_of(w, struct sgi_video_sync_vblank_scheduler, notify);
342 auto msc = atomic_load(&sched->current_msc) + sched->vblank_inserted;
343 auto ust = atomic_load(&sched->current_ust);
344 if (sched->last_msc >= msc) {
345 // NVIDIA spams us with duplicate vblank events after a suspend/resume
346 // cycle, or when the monitor turns off.
347 // Fake a vblank event in this case. See comments on `vblank_inserted`
348 // for more details.
349 enum log_level level =
350 sched->vblank_inserted == 0 ? LOG_LEVEL_WARN : LOG_LEVEL_DEBUG;
351 LOG_(level,
352 "Duplicate vblank event found with msc %d. Possible NVIDIA bug? "
353 "Number of duplicates so far: %d",
354 msc, sched->vblank_inserted);
355 sched->last_msc++;
356 sched->vblank_inserted++;
357
358 struct timespec now;
359 clock_gettime(CLOCK_MONOTONIC, &now);
360 ust = (uint64_t)(now.tv_sec * 1000000 + now.tv_nsec / 1000);
361 } else {
362 sched->last_msc = msc;
363 }
364 auto event = (struct vblank_event){
365 .msc = sched->last_msc,
366 .ust = ust,
367 };
368 sched->base.vblank_event_requested = false;
369 log_verbose("Received vblank event for msc %" PRIu64, event.msc);
370 vblank_scheduler_invoke_callbacks(&sched->base, &event);
371 }
372 #endif
373
374 static bool present_vblank_scheduler_schedule(struct vblank_scheduler *base) {
375 auto self = (struct present_vblank_scheduler *)base;
376 log_verbose("Requesting vblank event for window 0x%08x, msc %" PRIu64,
377 base->target_window, self->last_msc + 1);
378 assert(!base->vblank_event_requested);
379 x_request_vblank_event(base->c, base->target_window, self->last_msc + 1);
380 base->vblank_event_requested = true;
381 return true;
382 }
383
384 static void present_vblank_callback(EV_P attr_unused, ev_timer *w, int attr_unused revents) {
385 auto sched = container_of(w, struct present_vblank_scheduler, callback_timer);
386 auto event = (struct vblank_event){
387 .msc = sched->last_msc,
388 .ust = sched->last_ust,
389 };
390 sched->base.vblank_event_requested = false;
391 vblank_scheduler_invoke_callbacks(&sched->base, &event);
392 }
393
394 static bool present_vblank_scheduler_init(struct vblank_scheduler *base) {
395 auto self = (struct present_vblank_scheduler *)base;
396 base->type = VBLANK_SCHEDULER_PRESENT;
397 ev_timer_init(&self->callback_timer, present_vblank_callback, 0, 0);
398
399 self->event_id = x_new_id(base->c);
400 auto select_input =
401 xcb_present_select_input(base->c->c, self->event_id, base->target_window,
402 XCB_PRESENT_EVENT_MASK_COMPLETE_NOTIFY);
403 x_set_error_action_abort(base->c, select_input);
404 self->event =
405 xcb_register_for_special_xge(base->c->c, &xcb_present_id, self->event_id, NULL);
406 return true;
407 }
408
409 static void present_vblank_scheduler_deinit(struct vblank_scheduler *base) {
410 auto self = (struct present_vblank_scheduler *)base;
411 ev_timer_stop(base->loop, &self->callback_timer);
412 auto select_input =
413 xcb_present_select_input(base->c->c, self->event_id, base->target_window, 0);
414 x_set_error_action_abort(base->c, select_input);
415 xcb_unregister_for_special_event(base->c->c, self->event);
416 }
417
418 /// Handle PresentCompleteNotify events
419 ///
420 /// Schedule the registered callback to be called when the current vblank ends.
421 static void handle_present_complete_notify(struct present_vblank_scheduler *self,
422 xcb_present_complete_notify_event_t *cne) {
423 assert(self->base.type == VBLANK_SCHEDULER_PRESENT);
424
425 if (cne->kind != XCB_PRESENT_COMPLETE_KIND_NOTIFY_MSC) {
426 return;
427 }
428
429 assert(self->base.vblank_event_requested);
430
431 struct timespec now;
432 clock_gettime(CLOCK_MONOTONIC, &now);
433 auto now_us = (uint64_t)now.tv_sec * 1000000UL + (uint64_t)now.tv_nsec / 1000;
434
435 // X sometimes sends duplicate/bogus MSC events, when screen has just been turned
436 // off. Don't use the msc value in these events. We treat this as not receiving a
437 // vblank event at all, and try to get a new one.
438 //
439 // See:
440 // https://gitlab.freedesktop.org/xorg/xserver/-/issues/1418
441 bool event_is_invalid = cne->msc <= self->last_msc || cne->ust == 0;
442 if (event_is_invalid) {
443 log_debug("Invalid PresentCompleteNotify event, %" PRIu64 " %" PRIu64
444 ". Trying to recover, reporting a fake vblank.",
445 cne->msc, cne->ust);
446 self->last_ust = now_us;
447 self->last_msc += 1;
448 } else {
449 self->last_ust = cne->ust;
450 self->last_msc = cne->msc;
451 }
452 double delay_sec = 0.0;
453 if (now_us < cne->ust) {
454 log_trace("The end of this vblank is %" PRIu64 " us into the "
455 "future",
456 cne->ust - now_us);
457 delay_sec = (double)(cne->ust - now_us) / 1000000.0;
458 }
459 // Wait until the end of the current vblank to invoke callbacks. If we
460 // call it too early, it can mistakenly think the render missed the
461 // vblank, and doesn't schedule render for the next vblank, causing frame
462 // drops.
463 assert(!ev_is_active(&self->callback_timer));
464 ev_timer_set(&self->callback_timer, delay_sec, 0);
465 ev_timer_start(self->base.loop, &self->callback_timer);
466 }
467
468 static bool handle_present_events(struct vblank_scheduler *base) {
469 auto self = (struct present_vblank_scheduler *)base;
470 xcb_present_generic_event_t *ev;
471 while ((ev = (void *)xcb_poll_for_special_event(base->c->c, self->event))) {
472 if (ev->event != self->event_id) {
473 // This event doesn't have the right event context, it's not meant
474 // for us.
475 goto next;
476 }
477
478 // We only subscribed to the complete notify event.
479 assert(ev->evtype == XCB_PRESENT_EVENT_COMPLETE_NOTIFY);
480 handle_present_complete_notify(self, (void *)ev);
481 next:
482 free(ev);
483 }
484 return true;
485 }
486
487 static const struct vblank_scheduler_ops vblank_scheduler_ops[LAST_VBLANK_SCHEDULER] = {
488 [VBLANK_SCHEDULER_PRESENT] =
489 {
490 .size = sizeof(struct present_vblank_scheduler),
491 .init = present_vblank_scheduler_init,
492 .deinit = present_vblank_scheduler_deinit,
493 .schedule = present_vblank_scheduler_schedule,
494 .handle_x_events = handle_present_events,
495 },
496 #ifdef CONFIG_OPENGL
497 [VBLANK_SCHEDULER_SGI_VIDEO_SYNC] =
498 {
499 .size = sizeof(struct sgi_video_sync_vblank_scheduler),
500 .init = sgi_video_sync_scheduler_init,
501 .deinit = sgi_video_sync_scheduler_deinit,
502 .schedule = sgi_video_sync_scheduler_schedule,
503 .handle_x_events = NULL,
504 },
505 #endif
506 };
507
508 static bool vblank_scheduler_schedule_internal(struct vblank_scheduler *self) {
509 assert(self->type < LAST_VBLANK_SCHEDULER);
510 auto fn = vblank_scheduler_ops[self->type].schedule;
511 assert(fn != NULL);
512 return fn(self);
513 }
514
515 bool vblank_scheduler_schedule(struct vblank_scheduler *self,
516 vblank_callback_t vblank_callback, void *user_data) {
517 // Schedule a new vblank event if there are no callbacks currently scheduled.
518 if (dynarr_len(self->callbacks) == 0 && self->wind_down == 0 &&
519 !vblank_scheduler_schedule_internal(self)) {
520 return false;
521 }
522 struct vblank_closure closure = {
523 .fn = vblank_callback,
524 .user_data = user_data,
525 };
526 dynarr_push(self->callbacks, closure);
527 return true;
528 }
529
530 static void
531 vblank_scheduler_invoke_callbacks(struct vblank_scheduler *self, struct vblank_event *event) {
532 // callbacks might be added during callback invocation, so we need to
533 // copy the callback_count.
534 size_t count = dynarr_len(self->callbacks), write_head = 0;
535 if (count == 0) {
536 self->wind_down--;
537 } else {
538 self->wind_down = VBLANK_WIND_DOWN;
539 }
540 for (size_t i = 0; i < count; i++) {
541 auto action = self->callbacks[i].fn(event, self->callbacks[i].user_data);
542 switch (action) {
543 case VBLANK_CALLBACK_AGAIN:
544 if (i != write_head) {
545 self->callbacks[write_head] = self->callbacks[i];
546 }
547 write_head++;
548 case VBLANK_CALLBACK_DONE:
549 default: // nothing to do
550 break;
551 }
552 }
553 memset(self->callbacks + write_head, 0,
554 (count - write_head) * sizeof(*self->callbacks));
555 assert(count == dynarr_len(self->callbacks) && "callbacks should not be added "
556 "when callbacks are being "
557 "invoked.");
558 dynarr_len(self->callbacks) = write_head;
559 if (write_head || self->wind_down) {
560 vblank_scheduler_schedule_internal(self);
561 }
562 }
563
564 void vblank_scheduler_free(struct vblank_scheduler *self) {
565 assert(self->type < LAST_VBLANK_SCHEDULER);
566 auto fn = vblank_scheduler_ops[self->type].deinit;
567 if (fn != NULL) {
568 fn(self);
569 }
570 dynarr_free_pod(self->callbacks);
571 free(self);
572 }
573
574 struct vblank_scheduler *
575 vblank_scheduler_new(struct ev_loop *loop, struct x_connection *c, xcb_window_t target_window,
576 enum vblank_scheduler_type type, bool use_realtime_scheduling) {
577 size_t object_size = vblank_scheduler_ops[type].size;
578 auto init_fn = vblank_scheduler_ops[type].init;
579 if (!object_size || !init_fn) {
580 log_error("Unsupported or invalid vblank scheduler type: %d", type);
581 return NULL;
582 }
583
584 assert(object_size >= sizeof(struct vblank_scheduler));
585 struct vblank_scheduler *self = calloc(1, object_size);
586 self->target_window = target_window;
587 self->c = c;
588 self->loop = loop;
589 self->use_realtime_scheduling = use_realtime_scheduling;
590 self->callbacks = dynarr_new(struct vblank_closure, 1);
591 init_fn(self);
592 return self;
593 }
594
595 bool vblank_handle_x_events(struct vblank_scheduler *self) {
596 assert(self->type < LAST_VBLANK_SCHEDULER);
597 auto fn = vblank_scheduler_ops[self->type].handle_x_events;
598 if (fn != NULL) {
599 return fn(self);
600 }
601 return true;
602 }