summaryrefslogtreecommitdiff
path: root/src/dri2.c
blob: c734dc7c6a2e83b7de727e2e474a833d1265a9df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
#include "driver.h"

enum tegra_dri2_frame_event_type {
    MS_DRI2_QUEUE_SWAP,
    MS_DRI2_WAIT_MSC,
};

typedef struct tegra_dri2_frame_event {
    ScreenPtr screen;

    DrawablePtr drawable;
    ClientPtr client;
    enum tegra_dri2_frame_event_type type;
    int frame;
    xf86CrtcPtr crtc;

    struct xorg_list drawable_resource, client_resource;

    /* for swaps & flips only */
    DRI2SwapEventPtr event_complete;
    void *event_data;
    DRI2BufferPtr front;
    DRI2BufferPtr back;
} tegra_dri2_frame_event_rec, *tegra_dri2_frame_event_ptr;

typedef struct {
    int refcnt;
    PixmapPtr pixmap;
} tegra_dri2_buffer_private_rec, *tegra_dri2_buffer_private_ptr;

static DevPrivateKeyRec tegra_dri2_client_key;
static RESTYPE frame_event_client_type, frame_event_drawable_type;
static int tegra_dri2_server_generation;

struct tegra_dri2_resource {
    XID id;
    RESTYPE type;
    struct xorg_list list;
};

static uint32_t
drmmode_crtc_vblank_pipe(int crtc_id)
{
    if (crtc_id > 1)
        return crtc_id << DRM_VBLANK_HIGH_CRTC_SHIFT;
    else if (crtc_id > 0)
        return DRM_VBLANK_SECONDARY;
    else
        return 0;
}

static struct tegra_dri2_resource *
tegra_get_resource(XID id, RESTYPE type)
{
    struct tegra_dri2_resource *resource;
    void *ptr;

    ptr = NULL;
    dixLookupResourceByType(&ptr, id, type, NULL, DixWriteAccess);
    if (ptr)
        return ptr;

    resource = malloc(sizeof(*resource));
    if (resource == NULL)
        return NULL;

    if (!AddResource(id, type, resource))
        return NULL;

    resource->id = id;
    resource->type = type;
    xorg_list_init(&resource->list);
    return resource;
}

static inline PixmapPtr
get_drawable_pixmap(DrawablePtr drawable)
{
    ScreenPtr screen = drawable->pScreen;

    if (drawable->type == DRAWABLE_PIXMAP)
        return (PixmapPtr) drawable;
    else
        return screen->GetWindowPixmap((WindowPtr) drawable);
}

static DRI2Buffer2Ptr
tegra_dri2_create_buffer(DrawablePtr drawable, unsigned int attachment,
                         unsigned int format)
{
    ScreenPtr screen = drawable->pScreen;
    ScrnInfoPtr scrn = xf86ScreenToScrn(screen);
    DRI2Buffer2Ptr buffer;
    PixmapPtr pixmap;
    tegra_dri2_buffer_private_ptr private;
    TegraPixmapPtr tegra;

    if (!TegraPTR(scrn)->exa)
        return NULL;

    buffer = calloc(1, sizeof *buffer);
    if (buffer == NULL)
        return NULL;

    private = calloc(1, sizeof(*private));
    if (private == NULL) {
        free(buffer);
        return NULL;
    }

    pixmap = NULL;
    if (attachment == DRI2BufferFrontLeft) {
        pixmap = get_drawable_pixmap(drawable);
        if (pixmap && pixmap->drawable.pScreen != screen)
            pixmap = NULL;
        if (pixmap)
            pixmap->refcnt++;
    }

    if (pixmap == NULL) {
        int pixmap_width = drawable->width;
        int pixmap_height = drawable->height;
        int pixmap_cpp = (format != 0) ? format : drawable->depth;

        /* Assume that non-color-buffers require special
         * device-specific handling.  Mesa currently makes no requests
         * for non-color aux buffers.
         */
        switch (attachment) {
        case DRI2BufferAccum:
        case DRI2BufferBackLeft:
        case DRI2BufferBackRight:
        case DRI2BufferFakeFrontLeft:
        case DRI2BufferFakeFrontRight:
        case DRI2BufferFrontLeft:
        case DRI2BufferFrontRight:
            break;

        case DRI2BufferStencil:
        case DRI2BufferDepth:
        case DRI2BufferDepthStencil:
        case DRI2BufferHiz:
        default:
            xf86DrvMsg(scrn->scrnIndex, X_WARNING,
                       "Request for DRI2 buffer attachment %d unsupported\n",
                       attachment);
            free(private);
            free(buffer);
            return NULL;
        }

        pixmap = screen->CreatePixmap(screen,
                                      pixmap_width,
                                      pixmap_height,
                                      pixmap_cpp,
                                      TEGRA_DRI_USAGE_HINT);
        if (pixmap == NULL) {
            free(private);
            free(buffer);
            return NULL;
        }
    }

    buffer->attachment = attachment;
    buffer->cpp = pixmap->drawable.bitsPerPixel / 8;
    buffer->format = format;
    /* The buffer's flags field is unused by the client drivers in
     * Mesa currently.
     */
    buffer->flags = 0;
    buffer->name = -1;

    tegra = exaGetPixmapDriverPrivate(pixmap);

    drm_tegra_bo_get_name(tegra->bo, &buffer->name);

    if (buffer->name == -1) {
        xf86DrvMsg(scrn->scrnIndex, X_ERROR,
                   "Failed to get DRI2 name for pixmap\n");
        screen->DestroyPixmap(pixmap);
        free(private);
        free(buffer);
        return NULL;
    }

    drm_tegra_bo_forbid_caching(tegra->bo);

    buffer->pitch = pixmap->devKind;
    buffer->driverPrivate = private;
    private->refcnt = 1;
    private->pixmap = pixmap;

    return buffer;
}

unsigned refed;

static void
tegra_dri2_reference_buffer(DRI2Buffer2Ptr buffer)
{
    if (buffer) {
        tegra_dri2_buffer_private_ptr private = buffer->driverPrivate;
        private->refcnt++;
    }
}

static void tegra_dri2_destroy_buffer(DrawablePtr drawable,
                                      DRI2Buffer2Ptr buffer)
{
    if (!buffer)
        return;

    if (buffer->driverPrivate) {
        tegra_dri2_buffer_private_ptr private = buffer->driverPrivate;
        if (--private->refcnt == 0) {
            ScreenPtr screen = private->pixmap->drawable.pScreen;
            screen->DestroyPixmap(private->pixmap);
            free(private);
            free(buffer);
        }
    } else {
        free(buffer);
    }
}

static void
tegra_dri2_copy_region(DrawablePtr drawable, RegionPtr pRegion,
                       DRI2BufferPtr destBuffer, DRI2BufferPtr sourceBuffer)
{
    tegra_dri2_buffer_private_ptr src_priv = sourceBuffer->driverPrivate;
    tegra_dri2_buffer_private_ptr dst_priv = destBuffer->driverPrivate;
    PixmapPtr src_pixmap = src_priv->pixmap;
    PixmapPtr dst_pixmap = dst_priv->pixmap;
    ScreenPtr screen = drawable->pScreen;
    DrawablePtr src = (sourceBuffer->attachment == DRI2BufferFrontLeft)
        ? drawable : &src_pixmap->drawable;
    DrawablePtr dst = (destBuffer->attachment == DRI2BufferFrontLeft)
        ? drawable : &dst_pixmap->drawable;
    RegionPtr pCopyClip;
    GCPtr gc;

    gc = GetScratchGC(dst->depth, screen);
    if (!gc)
        return;

    pCopyClip = REGION_CREATE(screen, NULL, 0);
    REGION_COPY(screen, pCopyClip, pRegion);
    (*gc->funcs->ChangeClip) (gc, CT_REGION, pCopyClip, 0);
    ValidateGC(dst, gc);

    /* It's important that this copy gets submitted before the direct
     * rendering client submits rendering for the next frame, but we
     * don't actually need to submit right now.  The client will wait
     * for the DRI2CopyRegion reply or the swap buffer event before
     * rendering, and we'll hit the flush callback chain before those
     * messages are sent.  We submit our batch buffers from the flush
     * callback chain so we know that will happen before the client
     * tries to render again.
     */
    gc->ops->CopyArea(src, dst, gc,
                      0, 0,
                      drawable->width, drawable->height,
                      0, 0);

    FreeScratchGC(gc);
}

static uint64_t
gettime_us(void)
{
    struct timespec tv;

    if (clock_gettime(CLOCK_MONOTONIC, &tv))
        return 0;

    return (uint64_t)tv.tv_sec * 1000000 + tv.tv_nsec / 1000;
}

/**
 * Get current frame count and frame count timestamp, based on drawable's
 * crtc.
 */
static int
tegra_dri2_get_msc(DrawablePtr draw, CARD64 *ust, CARD64 *msc)
{
    int ret;
    xf86CrtcPtr crtc = tegra_crtc_covering_drawable(draw);

    /* Drawable not displayed, make up a *monotonic* value */
    if (crtc == NULL) {
        *ust = gettime_us();
        *msc = 0;
        return TRUE;
    }

    ret = tegra_get_crtc_ust_msc(crtc, ust, msc);

    if (ret)
        return FALSE;

    return TRUE;
}

static XID
get_client_id(ClientPtr client)
{
    XID *ptr = dixGetPrivateAddr(&client->devPrivates, &tegra_dri2_client_key);
    if (*ptr == 0)
        *ptr = FakeClientID(client->index);
    return *ptr;
}

/*
 * Hook this frame event into the server resource
 * database so we can clean it up if the drawable or
 * client exits while the swap is pending
 */
static Bool
tegra_dri2_add_frame_event(tegra_dri2_frame_event_ptr info)
{
    struct tegra_dri2_resource *resource;

    resource = tegra_get_resource(get_client_id(info->client),
                                  frame_event_client_type);
    if (resource == NULL)
        return FALSE;

    xorg_list_add(&info->client_resource, &resource->list);

    resource = tegra_get_resource(info->drawable->id, frame_event_drawable_type);
    if (resource == NULL) {
        xorg_list_del(&info->client_resource);
        return FALSE;
    }

    xorg_list_add(&info->drawable_resource, &resource->list);

    return TRUE;
}

static void
tegra_dri2_del_frame_event(tegra_dri2_frame_event_rec *info)
{
    xorg_list_del(&info->client_resource);
    xorg_list_del(&info->drawable_resource);

    if (info->front)
        tegra_dri2_destroy_buffer(NULL, info->front);
    if (info->back)
        tegra_dri2_destroy_buffer(NULL, info->back);

    free(info);
}

static void
tegra_dri2_blit_swap(DrawablePtr drawable,
                     DRI2BufferPtr dst,
                     DRI2BufferPtr src)
{
    BoxRec box;
    RegionRec region;

    box.x1 = 0;
    box.y1 = 0;
    box.x2 = drawable->width;
    box.y2 = drawable->height;
    REGION_INIT(pScreen, &region, &box, 0);

    tegra_dri2_copy_region(drawable, &region, dst, src);
}

static void
tegra_dri2_frame_event_handler(uint64_t msc,
                               uint64_t usec,
                               void *data)
{
    tegra_dri2_frame_event_ptr frame_info = data;
    DrawablePtr drawable = frame_info->drawable;
    ScreenPtr screen = frame_info->screen;
    ScrnInfoPtr scrn = xf86ScreenToScrn(screen);
    uint32_t tv_sec = usec / 1000000;
    uint32_t tv_usec = usec % 1000000;

    if (!drawable) {
        tegra_dri2_del_frame_event(frame_info);
        return;
    }

    switch (frame_info->type) {
    case MS_DRI2_QUEUE_SWAP:
        tegra_dri2_blit_swap(drawable, frame_info->front, frame_info->back);
        DRI2SwapComplete(frame_info->client, drawable, msc, tv_sec, tv_usec,
                         DRI2_BLIT_COMPLETE,
                         frame_info->client ? frame_info->event_complete : NULL,
                         frame_info->event_data);
        break;

    case MS_DRI2_WAIT_MSC:
        if (frame_info->client)
            DRI2WaitMSCComplete(frame_info->client, drawable,
                                msc, tv_sec, tv_usec);
        break;

    default:
        xf86DrvMsg(scrn->scrnIndex, X_WARNING,
                   "%s: unknown vblank event (type %d) received\n", __func__,
                   frame_info->type);
        break;
    }

    tegra_dri2_del_frame_event(frame_info);
}

static void
tegra_dri2_frame_event_abort(void *data)
{
    tegra_dri2_frame_event_ptr frame_info = data;

    tegra_dri2_del_frame_event(frame_info);
}

/**
 * Request a DRM event when the requested conditions will be satisfied.
 *
 * We need to handle the event and ask the server to wake up the client when
 * we receive it.
 */
static int
tegra_dri2_schedule_wait_msc(ClientPtr client, DrawablePtr draw,
                             CARD64 target_msc, CARD64 divisor,
                             CARD64 _remainder)
{
    ScreenPtr screen = draw->pScreen;
    ScrnInfoPtr scrn = xf86ScreenToScrn(screen);
    TegraPtr tegra = TegraPTR(scrn);
    tegra_dri2_frame_event_ptr wait_info;
    drmVBlank vbl;
    int ret;
    xf86CrtcPtr crtc = tegra_crtc_covering_drawable(draw);
    drmmode_crtc_private_ptr drmmode_crtc;
    CARD64 current_msc, current_ust, request_msc;
    uint32_t seq;

    /* Drawable not visible, return immediately */
    if (!crtc)
        goto out_complete;
    drmmode_crtc = crtc->driver_private;

    wait_info = calloc(1, sizeof(*wait_info));
    if (!wait_info)
        goto out_complete;

    wait_info->screen = screen;
    wait_info->drawable = draw;
    wait_info->client = client;
    wait_info->type = MS_DRI2_WAIT_MSC;

    if (!tegra_dri2_add_frame_event(wait_info)) {
        free(wait_info);
        wait_info = NULL;
        goto out_complete;
    }

    /* Get current count */
    ret = tegra_get_crtc_ust_msc(crtc, &current_ust, &current_msc);

    /*
     * If divisor is zero, or current_msc is smaller than target_msc,
     * we just need to make sure target_msc passes  before waking up the
     * client.
     */
    if (divisor == 0 || current_msc < target_msc) {
        /* If target_msc already reached or passed, set it to
         * current_msc to ensure we return a reasonable value back
         * to the caller. This keeps the client from continually
         * sending us MSC targets from the past by forcibly updating
         * their count on this call.
         */
        seq = tegra_drm_queue_alloc(crtc, wait_info,
                                    tegra_dri2_frame_event_handler,
                                    tegra_dri2_frame_event_abort);
        if (!seq)
            goto out_free;

        if (current_msc >= target_msc)
            target_msc = current_msc;
        vbl.request.type = (DRM_VBLANK_ABSOLUTE |
                            DRM_VBLANK_EVENT |
                            drmmode_crtc_vblank_pipe(drmmode_crtc->crtc_pipe));
        vbl.request.sequence = tegra_crtc_msc_to_kernel_msc(crtc, target_msc);
        vbl.request.signal = (unsigned long)seq;

        ret = drmWaitVBlank(tegra->fd, &vbl);
        if (ret) {
            static int limit = 5;
            if (limit) {
                xf86DrvMsg(scrn->scrnIndex, X_WARNING,
                           "%s:%d get vblank counter failed: %s\n",
                           __FUNCTION__, __LINE__,
                           strerror(errno));
                limit--;
            }
            goto out_free;
        }

        wait_info->frame = tegra_kernel_msc_to_crtc_msc(crtc, vbl.reply.sequence);
        DRI2BlockClient(client, draw);
        return TRUE;
    }

    /*
     * If we get here, target_msc has already passed or we don't have one,
     * so we queue an event that will satisfy the divisor/remainder equation.
     */
    vbl.request.type =
        DRM_VBLANK_ABSOLUTE | DRM_VBLANK_EVENT | drmmode_crtc_vblank_pipe(drmmode_crtc->crtc_pipe);

    request_msc = current_msc - (current_msc % divisor) +
        _remainder;
    /*
     * If calculated remainder is larger than requested remainder,
     * it means we've passed the last point where
     * seq % divisor == remainder, so we need to wait for the next time
     * that will happen.
     */
    if ((current_msc % divisor) >= _remainder)
        request_msc += divisor;

    seq = tegra_drm_queue_alloc(crtc, wait_info,
                                tegra_dri2_frame_event_handler,
                                tegra_dri2_frame_event_abort);
    if (!seq)
        goto out_free;

    vbl.request.sequence = tegra_crtc_msc_to_kernel_msc(crtc, request_msc);
    vbl.request.signal = (unsigned long)seq;

    ret = drmWaitVBlank(tegra->fd, &vbl);
    if (ret) {
        static int limit = 5;
        if (limit) {
            xf86DrvMsg(scrn->scrnIndex, X_WARNING,
                       "%s:%d get vblank counter failed: %s\n",
                       __FUNCTION__, __LINE__,
                       strerror(errno));
            limit--;
        }
        goto out_free;
    }

    wait_info->frame = tegra_kernel_msc_to_crtc_msc(crtc, vbl.reply.sequence);
    DRI2BlockClient(client, draw);

    return TRUE;

 out_free:
    tegra_dri2_del_frame_event(wait_info);
 out_complete:
    DRI2WaitMSCComplete(client, draw, target_msc, 0, 0);
    return TRUE;
}

/**
 * ScheduleSwap is responsible for requesting a DRM vblank event for
 * the appropriate frame, or executing the swap immediately if it
 * doesn't need to wait.
 *
 * When the swap is complete, the driver should call into the server so it
 * can send any swap complete events that have been requested.
 */
static int
tegra_dri2_schedule_swap(ClientPtr client, DrawablePtr draw,
                         DRI2BufferPtr front, DRI2BufferPtr back,
                         CARD64 *target_msc, CARD64 divisor,
                         CARD64 _remainder, DRI2SwapEventPtr func, void *data)
{
    ScreenPtr screen = draw->pScreen;
    ScrnInfoPtr scrn = xf86ScreenToScrn(screen);
    TegraPtr tegra = TegraPTR(scrn);
    drmVBlank vbl;
    int ret;
    xf86CrtcPtr crtc = tegra_crtc_covering_drawable(draw);
    drmmode_crtc_private_ptr drmmode_crtc;
    tegra_dri2_frame_event_ptr frame_info = NULL;
    uint64_t current_msc, current_ust;
    uint64_t request_msc;
    uint32_t seq;

    /* Drawable not displayed... just complete the swap */
    if (!crtc)
        goto blit_fallback;
    drmmode_crtc = crtc->driver_private;

    frame_info = calloc(1, sizeof(*frame_info));
    if (!frame_info)
        goto blit_fallback;

    frame_info->screen = screen;
    frame_info->drawable = draw;
    frame_info->client = client;
    frame_info->event_complete = func;
    frame_info->event_data = data;
    frame_info->front = front;
    frame_info->back = back;
    frame_info->crtc = crtc;
    frame_info->type = MS_DRI2_QUEUE_SWAP;

    if (!tegra_dri2_add_frame_event(frame_info)) {
        free(frame_info);
        frame_info = NULL;
        goto blit_fallback;
    }

    tegra_dri2_reference_buffer(front);
    tegra_dri2_reference_buffer(back);

    ret = tegra_get_crtc_ust_msc(crtc, &current_ust, &current_msc);

    /*
     * If divisor is zero, or current_msc is smaller than target_msc
     * we just need to make sure target_msc passes before initiating
     * the swap.
     */
    if (divisor == 0 || current_msc < *target_msc) {
        /* We need to use DRM_VBLANK_NEXTONMISS to avoid unreliable
         * timestamping later on.
         */
        vbl.request.type = (DRM_VBLANK_ABSOLUTE |
                            DRM_VBLANK_NEXTONMISS |
                            DRM_VBLANK_EVENT |
                            drmmode_crtc_vblank_pipe(drmmode_crtc->crtc_pipe));

        /* If target_msc already reached or passed, set it to
         * current_msc to ensure we return a reasonable value back
         * to the caller. This makes swap_interval logic more robust.
         */
        if (current_msc >= *target_msc)
            *target_msc = current_msc;

        seq = tegra_drm_queue_alloc(crtc, frame_info,
                                    tegra_dri2_frame_event_handler,
                                    tegra_dri2_frame_event_abort);
        if (!seq)
            goto blit_fallback;

        vbl.request.sequence = tegra_crtc_msc_to_kernel_msc(crtc, *target_msc);
        vbl.request.signal = (unsigned long)seq;

        ret = drmWaitVBlank(tegra->fd, &vbl);
        if (ret) {
            xf86DrvMsg(scrn->scrnIndex, X_WARNING,
                       "divisor 0 get vblank counter failed: %s\n",
                       strerror(errno));
            tegra_drm_abort_seq(scrn, seq);
            frame_info = NULL;
            goto blit_fallback;
        }

        *target_msc = tegra_kernel_msc_to_crtc_msc(crtc, vbl.reply.sequence);
        frame_info->frame = *target_msc;

        return TRUE;
    }

    /*
     * If we get here, target_msc has already passed or we don't have one,
     * and we need to queue an event that will satisfy the divisor/_remainder
     * equation.
     */
    vbl.request.type = (DRM_VBLANK_ABSOLUTE |
                        DRM_VBLANK_NEXTONMISS |
                        DRM_VBLANK_EVENT |
                        drmmode_crtc_vblank_pipe(drmmode_crtc->crtc_pipe));

    request_msc = current_msc - (current_msc % divisor) +
        _remainder;

    /*
     * If the calculated deadline vbl.request.sequence is smaller than
     * or equal to current_msc, it means we've passed the last point
     * when effective onset frame seq could satisfy
     * seq % divisor == remainder, so we need to wait for the next time
     * this will happen.

     * This comparison takes the DRM_VBLANK_NEXTONMISS delay into account.
     */
    if (request_msc <= current_msc)
        request_msc += divisor;


    seq = tegra_drm_queue_alloc(crtc, frame_info,
                                tegra_dri2_frame_event_handler,
                                tegra_dri2_frame_event_abort);
    if (!seq)
        goto blit_fallback;

    vbl.request.sequence = tegra_crtc_msc_to_kernel_msc(crtc, request_msc);
    vbl.request.signal = (unsigned long)seq;

    ret = drmWaitVBlank(tegra->fd, &vbl);
    if (ret) {
        xf86DrvMsg(scrn->scrnIndex, X_WARNING,
                   "final get vblank counter failed: %s\n",
                   strerror(errno));
        tegra_drm_abort_seq(scrn, seq);
        frame_info = NULL;
        goto blit_fallback;
    }

    *target_msc = tegra_kernel_msc_to_crtc_msc(crtc, vbl.reply.sequence);
    frame_info->frame = *target_msc;

    return TRUE;

 blit_fallback:
    tegra_dri2_blit_swap(draw, front, back);
    DRI2SwapComplete(client, draw, 0, 0, 0, DRI2_BLIT_COMPLETE, func, data);
    if (frame_info)
        tegra_dri2_del_frame_event(frame_info);
    *target_msc = 0; /* offscreen, so zero out target vblank count */
    return TRUE;
}

static Bool
tegra_dri2_frame_info_match(void *data, void *match_data)
{
    tegra_dri2_frame_event_ptr info = data;
    tegra_dri2_frame_event_ptr match = match_data;

    return (info == match);
}

static int
tegra_dri2_frame_event_client_gone(void *data, XID id)
{
    struct tegra_dri2_resource *resource = data;

    while (!xorg_list_is_empty(&resource->list)) {
        tegra_dri2_frame_event_ptr info =
            xorg_list_first_entry(&resource->list,
                                  tegra_dri2_frame_event_rec,
                                  client_resource);

        tegra_drm_abort(NULL, tegra_dri2_frame_info_match, info);

        xorg_list_del(&info->client_resource);
        info->client = NULL;
    }
    free(resource);

    return Success;
}

static int
tegra_dri2_frame_event_drawable_gone(void *data, XID id)
{
    struct tegra_dri2_resource *resource = data;

    while (!xorg_list_is_empty(&resource->list)) {
        tegra_dri2_frame_event_ptr info =
            xorg_list_first_entry(&resource->list,
                                  tegra_dri2_frame_event_rec,
                                  drawable_resource);

        xorg_list_del(&info->drawable_resource);
        info->drawable = NULL;
    }
    free(resource);

    return Success;
}

static Bool
tegra_dri2_register_frame_event_resource_types(void)
{
    frame_event_client_type =
        CreateNewResourceType(tegra_dri2_frame_event_client_gone,
                              "Frame Event Client");
    if (!frame_event_client_type)
        return FALSE;

    frame_event_drawable_type =
        CreateNewResourceType(tegra_dri2_frame_event_drawable_gone,
                              "Frame Event Drawable");
    if (!frame_event_drawable_type)
        return FALSE;

    return TRUE;
}

void TegraDRI2ScreenInit(ScreenPtr screen)
{
    ScrnInfoPtr scrn = xf86ScreenToScrn(screen);
    TegraPtr tegra = TegraPTR(scrn);
    DRI2InfoRec info;
    const char *drivernames[2] = {
        "tegra", /* DRI */
        "tegra", /* VDPAU */
    };

    if (tegra->dri2_enabled)
        return;

    if (!xf86LoaderCheckSymbol("DRI2Version"))
        return;

    if (!dixRegisterPrivateKey(&tegra_dri2_client_key,
                               PRIVATE_CLIENT, sizeof(XID)))
        return;

    if (serverGeneration != tegra_dri2_server_generation) {
        tegra_dri2_server_generation = serverGeneration;
        if (!tegra_dri2_register_frame_event_resource_types()) {
            xf86DrvMsg(scrn->scrnIndex, X_WARNING,
                       "Cannot register DRI2 frame event resources\n");
            return;
        }
    }

    memset(&info, '\0', sizeof(info));
    info.fd = tegra->fd;
    info.driverName = "tegra"; /* Compat field, unused. */
    info.deviceName = drmGetDeviceNameFromFd(tegra->fd);

    info.version = 4;
    info.CreateBuffer = tegra_dri2_create_buffer;
    info.DestroyBuffer = tegra_dri2_destroy_buffer;
    info.CopyRegion = tegra_dri2_copy_region;
    info.ScheduleSwap = tegra_dri2_schedule_swap;
    info.GetMSC = tegra_dri2_get_msc;
    info.ScheduleWaitMSC = tegra_dri2_schedule_wait_msc;

    /* These two will be filled in by dri2.c */
    info.numDrivers = 2;
    info.driverNames = drivernames;

    DRI2ScreenInit(screen, &info);

    tegra->dri2_enabled = TRUE;
}

void TegraDRI2ScreenExit(ScreenPtr screen)
{
    ScrnInfoPtr scrn = xf86ScreenToScrn(screen);
    TegraPtr tegra = TegraPTR(scrn);

    if (!tegra->dri2_enabled)
        return;

    DRI2CloseScreen(screen);

    tegra->dri2_enabled = FALSE;
}