OSDN Git Service

st/dri: Fix RGB565 EGLImage creation
[android-x86/external-mesa.git] / src / gallium / state_trackers / dri / dri2.c
1 /*
2  * Mesa 3-D graphics library
3  *
4  * Copyright 2009, VMware, Inc.
5  * All Rights Reserved.
6  * Copyright (C) 2010 LunarG Inc.
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a
9  * copy of this software and associated documentation files (the "Software"),
10  * to deal in the Software without restriction, including without limitation
11  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
12  * and/or sell copies of the Software, and to permit persons to whom the
13  * Software is furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included
16  * in all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
21  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
22  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
23  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24  * OTHER DEALINGS IN THE SOFTWARE.
25  *
26  * Authors:
27  *    Keith Whitwell <keithw@vmware.com> Jakob Bornecrantz
28  *    <wallbraker@gmail.com> Chia-I Wu <olv@lunarg.com>
29  */
30
31 #include <xf86drm.h>
32 #include <dlfcn.h>
33 #include "util/u_memory.h"
34 #include "util/u_inlines.h"
35 #include "util/u_format.h"
36 #include "util/u_debug.h"
37 #include "state_tracker/drm_driver.h"
38 #include "state_tracker/st_texture.h"
39 #include "state_tracker/st_context.h"
40 #include "pipe-loader/pipe_loader.h"
41 #include "main/texobj.h"
42
43 #include "dri_screen.h"
44 #include "dri_context.h"
45 #include "dri_drawable.h"
46 #include "dri_query_renderer.h"
47 #include "dri2_buffer.h"
48
49 static int convert_fourcc(int format, int *dri_components_p)
50 {
51    int dri_components;
52    switch(format) {
53    case __DRI_IMAGE_FOURCC_RGB565:
54       format = __DRI_IMAGE_FORMAT_RGB565;
55       dri_components = __DRI_IMAGE_COMPONENTS_RGB;
56       break;
57    case __DRI_IMAGE_FOURCC_ARGB8888:
58       format = __DRI_IMAGE_FORMAT_ARGB8888;
59       dri_components = __DRI_IMAGE_COMPONENTS_RGBA;
60       break;
61    case __DRI_IMAGE_FOURCC_XRGB8888:
62       format = __DRI_IMAGE_FORMAT_XRGB8888;
63       dri_components = __DRI_IMAGE_COMPONENTS_RGB;
64       break;
65    case __DRI_IMAGE_FOURCC_ABGR8888:
66       format = __DRI_IMAGE_FORMAT_ABGR8888;
67       dri_components = __DRI_IMAGE_COMPONENTS_RGBA;
68       break;
69    case __DRI_IMAGE_FOURCC_XBGR8888:
70       format = __DRI_IMAGE_FORMAT_XBGR8888;
71       dri_components = __DRI_IMAGE_COMPONENTS_RGB;
72       break;
73    default:
74       return -1;
75    }
76    *dri_components_p = dri_components;
77    return format;
78 }
79
80 static int convert_to_fourcc(int format)
81 {
82    switch(format) {
83    case __DRI_IMAGE_FORMAT_RGB565:
84       format = __DRI_IMAGE_FOURCC_RGB565;
85       break;
86    case __DRI_IMAGE_FORMAT_ARGB8888:
87       format = __DRI_IMAGE_FOURCC_ARGB8888;
88       break;
89    case __DRI_IMAGE_FORMAT_XRGB8888:
90       format = __DRI_IMAGE_FOURCC_XRGB8888;
91       break;
92    case __DRI_IMAGE_FORMAT_ABGR8888:
93       format = __DRI_IMAGE_FOURCC_ABGR8888;
94       break;
95    case __DRI_IMAGE_FORMAT_XBGR8888:
96       format = __DRI_IMAGE_FOURCC_XBGR8888;
97       break;
98    default:
99       return -1;
100    }
101    return format;
102 }
103
104 static enum pipe_format dri2_format_to_pipe_format (int format)
105 {
106    enum pipe_format pf;
107
108    switch (format) {
109    case __DRI_IMAGE_FORMAT_RGB565:
110       pf = PIPE_FORMAT_B5G6R5_UNORM;
111       break;
112    case __DRI_IMAGE_FORMAT_XRGB8888:
113       pf = PIPE_FORMAT_BGRX8888_UNORM;
114       break;
115    case __DRI_IMAGE_FORMAT_ARGB8888:
116       pf = PIPE_FORMAT_BGRA8888_UNORM;
117       break;
118    case __DRI_IMAGE_FORMAT_ABGR8888:
119       pf = PIPE_FORMAT_RGBA8888_UNORM;
120       break;
121    default:
122       pf = PIPE_FORMAT_NONE;
123       break;
124    }
125
126    return pf;
127 }
128
129 /**
130  * DRI2 flush extension.
131  */
132 static void
133 dri2_flush_drawable(__DRIdrawable *dPriv)
134 {
135    dri_flush(dPriv->driContextPriv, dPriv, __DRI2_FLUSH_DRAWABLE, -1);
136 }
137
138 static void
139 dri2_invalidate_drawable(__DRIdrawable *dPriv)
140 {
141    struct dri_drawable *drawable = dri_drawable(dPriv);
142
143    dri2InvalidateDrawable(dPriv);
144    drawable->dPriv->lastStamp = drawable->dPriv->dri2.stamp;
145
146    p_atomic_inc(&drawable->base.stamp);
147 }
148
149 static const __DRI2flushExtension dri2FlushExtension = {
150     .base = { __DRI2_FLUSH, 4 },
151
152     .flush                = dri2_flush_drawable,
153     .invalidate           = dri2_invalidate_drawable,
154     .flush_with_flags     = dri_flush,
155 };
156
157 /**
158  * Retrieve __DRIbuffer from the DRI loader.
159  */
160 static __DRIbuffer *
161 dri2_drawable_get_buffers(struct dri_drawable *drawable,
162                           const enum st_attachment_type *atts,
163                           unsigned *count)
164 {
165    __DRIdrawable *dri_drawable = drawable->dPriv;
166    const __DRIdri2LoaderExtension *loader = drawable->sPriv->dri2.loader;
167    boolean with_format;
168    __DRIbuffer *buffers;
169    int num_buffers;
170    unsigned attachments[10];
171    unsigned num_attachments, i;
172
173    assert(loader);
174    with_format = dri_with_format(drawable->sPriv);
175
176    num_attachments = 0;
177
178    /* for Xserver 1.6.0 (DRI2 version 1) we always need to ask for the front */
179    if (!with_format)
180       attachments[num_attachments++] = __DRI_BUFFER_FRONT_LEFT;
181
182    for (i = 0; i < *count; i++) {
183       enum pipe_format format;
184       unsigned bind;
185       int att, depth;
186
187       dri_drawable_get_format(drawable, atts[i], &format, &bind);
188       if (format == PIPE_FORMAT_NONE)
189          continue;
190
191       switch (atts[i]) {
192       case ST_ATTACHMENT_FRONT_LEFT:
193          /* already added */
194          if (!with_format)
195             continue;
196          att = __DRI_BUFFER_FRONT_LEFT;
197          break;
198       case ST_ATTACHMENT_BACK_LEFT:
199          att = __DRI_BUFFER_BACK_LEFT;
200          break;
201       case ST_ATTACHMENT_FRONT_RIGHT:
202          att = __DRI_BUFFER_FRONT_RIGHT;
203          break;
204       case ST_ATTACHMENT_BACK_RIGHT:
205          att = __DRI_BUFFER_BACK_RIGHT;
206          break;
207       default:
208          continue;
209       }
210
211       /*
212        * In this switch statement we must support all formats that
213        * may occur as the stvis->color_format.
214        */
215       switch(format) {
216       case PIPE_FORMAT_BGRA8888_UNORM:
217          depth = 32;
218          break;
219       case PIPE_FORMAT_BGRX8888_UNORM:
220          depth = 24;
221          break;
222       case PIPE_FORMAT_B5G6R5_UNORM:
223          depth = 16;
224          break;
225       default:
226          depth = util_format_get_blocksizebits(format);
227          assert(!"Unexpected format in dri2_drawable_get_buffers()");
228       }
229
230       attachments[num_attachments++] = att;
231       if (with_format) {
232          attachments[num_attachments++] = depth;
233       }
234    }
235
236    if (with_format) {
237       num_attachments /= 2;
238       buffers = loader->getBuffersWithFormat(dri_drawable,
239             &dri_drawable->w, &dri_drawable->h,
240             attachments, num_attachments,
241             &num_buffers, dri_drawable->loaderPrivate);
242    }
243    else {
244       buffers = loader->getBuffers(dri_drawable,
245             &dri_drawable->w, &dri_drawable->h,
246             attachments, num_attachments,
247             &num_buffers, dri_drawable->loaderPrivate);
248    }
249
250    if (buffers)
251       *count = num_buffers;
252
253    return buffers;
254 }
255
256 static bool
257 dri_image_drawable_get_buffers(struct dri_drawable *drawable,
258                                struct __DRIimageList *images,
259                                const enum st_attachment_type *statts,
260                                unsigned statts_count)
261 {
262    __DRIdrawable *dPriv = drawable->dPriv;
263    __DRIscreen *sPriv = drawable->sPriv;
264    unsigned int image_format = __DRI_IMAGE_FORMAT_NONE;
265    enum pipe_format pf;
266    uint32_t buffer_mask = 0;
267    unsigned i, bind;
268
269    for (i = 0; i < statts_count; i++) {
270       dri_drawable_get_format(drawable, statts[i], &pf, &bind);
271       if (pf == PIPE_FORMAT_NONE)
272          continue;
273
274       switch (statts[i]) {
275       case ST_ATTACHMENT_FRONT_LEFT:
276          buffer_mask |= __DRI_IMAGE_BUFFER_FRONT;
277          break;
278       case ST_ATTACHMENT_BACK_LEFT:
279          buffer_mask |= __DRI_IMAGE_BUFFER_BACK;
280          break;
281       default:
282          continue;
283       }
284
285       switch (pf) {
286       case PIPE_FORMAT_B5G6R5_UNORM:
287          image_format = __DRI_IMAGE_FORMAT_RGB565;
288          break;
289       case PIPE_FORMAT_BGRX8888_UNORM:
290          image_format = __DRI_IMAGE_FORMAT_XRGB8888;
291          break;
292       case PIPE_FORMAT_BGRA8888_UNORM:
293          image_format = __DRI_IMAGE_FORMAT_ARGB8888;
294          break;
295       case PIPE_FORMAT_RGBA8888_UNORM:
296          image_format = __DRI_IMAGE_FORMAT_ABGR8888;
297          break;
298       default:
299          image_format = __DRI_IMAGE_FORMAT_NONE;
300          break;
301       }
302    }
303
304    return (*sPriv->image.loader->getBuffers) (dPriv, image_format,
305                                        (uint32_t *) &drawable->base.stamp,
306                                        dPriv->loaderPrivate, buffer_mask,
307                                        images);
308 }
309
310 static __DRIbuffer *
311 dri2_allocate_buffer(__DRIscreen *sPriv,
312                      unsigned attachment, unsigned format,
313                      int width, int height)
314 {
315    struct dri_screen *screen = dri_screen(sPriv);
316    struct dri2_buffer *buffer;
317    struct pipe_resource templ;
318    enum pipe_format pf;
319    unsigned bind = 0;
320    struct winsys_handle whandle;
321
322    switch (attachment) {
323       case __DRI_BUFFER_FRONT_LEFT:
324       case __DRI_BUFFER_FAKE_FRONT_LEFT:
325          bind = PIPE_BIND_RENDER_TARGET | PIPE_BIND_SAMPLER_VIEW;
326          break;
327       case __DRI_BUFFER_BACK_LEFT:
328          bind = PIPE_BIND_RENDER_TARGET | PIPE_BIND_SAMPLER_VIEW;
329          break;
330       case __DRI_BUFFER_DEPTH:
331       case __DRI_BUFFER_DEPTH_STENCIL:
332       case __DRI_BUFFER_STENCIL:
333             bind = PIPE_BIND_DEPTH_STENCIL; /* XXX sampler? */
334          break;
335    }
336
337    /* because we get the handle and stride */
338    bind |= PIPE_BIND_SHARED;
339
340    switch (format) {
341       case 32:
342          pf = PIPE_FORMAT_BGRA8888_UNORM;
343          break;
344       case 24:
345          pf = PIPE_FORMAT_BGRX8888_UNORM;
346          break;
347       case 16:
348          pf = PIPE_FORMAT_Z16_UNORM;
349          break;
350       default:
351          return NULL;
352    }
353
354    buffer = CALLOC_STRUCT(dri2_buffer);
355    if (!buffer)
356       return NULL;
357
358    memset(&templ, 0, sizeof(templ));
359    templ.bind = bind;
360    templ.format = pf;
361    templ.target = PIPE_TEXTURE_2D;
362    templ.last_level = 0;
363    templ.width0 = width;
364    templ.height0 = height;
365    templ.depth0 = 1;
366    templ.array_size = 1;
367
368    buffer->resource =
369       screen->base.screen->resource_create(screen->base.screen, &templ);
370    if (!buffer->resource) {
371       FREE(buffer);
372       return NULL;
373    }
374
375    memset(&whandle, 0, sizeof(whandle));
376    if (screen->can_share_buffer)
377       whandle.type = DRM_API_HANDLE_TYPE_SHARED;
378    else
379       whandle.type = DRM_API_HANDLE_TYPE_KMS;
380
381    screen->base.screen->resource_get_handle(screen->base.screen,
382          buffer->resource, &whandle,
383          PIPE_HANDLE_USAGE_EXPLICIT_FLUSH | PIPE_HANDLE_USAGE_READ);
384
385    buffer->base.attachment = attachment;
386    buffer->base.name = whandle.handle;
387    buffer->base.cpp = util_format_get_blocksize(pf);
388    buffer->base.pitch = whandle.stride;
389
390    return &buffer->base;
391 }
392
393 static void
394 dri2_release_buffer(__DRIscreen *sPriv, __DRIbuffer *bPriv)
395 {
396    struct dri2_buffer *buffer = dri2_buffer(bPriv);
397
398    pipe_resource_reference(&buffer->resource, NULL);
399    FREE(buffer);
400 }
401
402 /*
403  * Backend functions for st_framebuffer interface.
404  */
405
406 static void
407 dri2_allocate_textures(struct dri_context *ctx,
408                        struct dri_drawable *drawable,
409                        const enum st_attachment_type *statts,
410                        unsigned statts_count)
411 {
412    __DRIscreen *sPriv = drawable->sPriv;
413    __DRIdrawable *dri_drawable = drawable->dPriv;
414    struct dri_screen *screen = dri_screen(sPriv);
415    struct pipe_resource templ;
416    boolean alloc_depthstencil = FALSE;
417    unsigned i, j, bind;
418    const __DRIimageLoaderExtension *image = sPriv->image.loader;
419    /* Image specific variables */
420    struct __DRIimageList images;
421    /* Dri2 specific variables */
422    __DRIbuffer *buffers = NULL;
423    struct winsys_handle whandle;
424    unsigned num_buffers = statts_count;
425
426    /* First get the buffers from the loader */
427    if (image) {
428       if (!dri_image_drawable_get_buffers(drawable, &images,
429                                           statts, statts_count))
430          return;
431    }
432    else {
433       buffers = dri2_drawable_get_buffers(drawable, statts, &num_buffers);
434       if (!buffers || (drawable->old_num == num_buffers &&
435                        drawable->old_w == dri_drawable->w &&
436                        drawable->old_h == dri_drawable->h &&
437                        memcmp(drawable->old, buffers,
438                               sizeof(__DRIbuffer) * num_buffers) == 0))
439          return;
440    }
441
442    /* Second clean useless resources*/
443
444    /* See if we need a depth-stencil buffer. */
445    for (i = 0; i < statts_count; i++) {
446       if (statts[i] == ST_ATTACHMENT_DEPTH_STENCIL) {
447          alloc_depthstencil = TRUE;
448          break;
449       }
450    }
451
452    /* Delete the resources we won't need. */
453    for (i = 0; i < ST_ATTACHMENT_COUNT; i++) {
454       /* Don't delete the depth-stencil buffer, we can reuse it. */
455       if (i == ST_ATTACHMENT_DEPTH_STENCIL && alloc_depthstencil)
456          continue;
457
458       /* Flush the texture before unreferencing, so that other clients can
459        * see what the driver has rendered.
460        */
461       if (i != ST_ATTACHMENT_DEPTH_STENCIL && drawable->textures[i]) {
462          struct pipe_context *pipe = ctx->st->pipe;
463          pipe->flush_resource(pipe, drawable->textures[i]);
464       }
465
466       pipe_resource_reference(&drawable->textures[i], NULL);
467    }
468
469    if (drawable->stvis.samples > 1) {
470       for (i = 0; i < ST_ATTACHMENT_COUNT; i++) {
471          boolean del = TRUE;
472
473          /* Don't delete MSAA resources for the attachments which are enabled,
474           * we can reuse them. */
475          for (j = 0; j < statts_count; j++) {
476             if (i == statts[j]) {
477                del = FALSE;
478                break;
479             }
480          }
481
482          if (del) {
483             pipe_resource_reference(&drawable->msaa_textures[i], NULL);
484          }
485       }
486    }
487
488    /* Third use the buffers retrieved to fill the drawable info */
489
490    memset(&templ, 0, sizeof(templ));
491    templ.target = screen->target;
492    templ.last_level = 0;
493    templ.depth0 = 1;
494    templ.array_size = 1;
495
496    if (image) {
497       if (images.image_mask & __DRI_IMAGE_BUFFER_FRONT) {
498          struct pipe_resource **buf =
499             &drawable->textures[ST_ATTACHMENT_FRONT_LEFT];
500          struct pipe_resource *texture = images.front->texture;
501
502          dri_drawable->w = texture->width0;
503          dri_drawable->h = texture->height0;
504
505          pipe_resource_reference(buf, texture);
506       }
507
508       if (images.image_mask & __DRI_IMAGE_BUFFER_BACK) {
509          struct pipe_resource **buf =
510             &drawable->textures[ST_ATTACHMENT_BACK_LEFT];
511          struct pipe_resource *texture = images.back->texture;
512
513          dri_drawable->w = texture->width0;
514          dri_drawable->h = texture->height0;
515
516          pipe_resource_reference(buf, texture);
517       }
518
519       /* Note: if there is both a back and a front buffer,
520        * then they have the same size.
521        */
522       templ.width0 = dri_drawable->w;
523       templ.height0 = dri_drawable->h;
524    }
525    else {
526       memset(&whandle, 0, sizeof(whandle));
527
528       /* Process DRI-provided buffers and get pipe_resources. */
529       for (i = 0; i < num_buffers; i++) {
530          __DRIbuffer *buf = &buffers[i];
531          enum st_attachment_type statt;
532          enum pipe_format format;
533
534          switch (buf->attachment) {
535          case __DRI_BUFFER_FRONT_LEFT:
536             if (!screen->auto_fake_front) {
537                continue; /* invalid attachment */
538             }
539             /* fallthrough */
540          case __DRI_BUFFER_FAKE_FRONT_LEFT:
541             statt = ST_ATTACHMENT_FRONT_LEFT;
542             break;
543          case __DRI_BUFFER_BACK_LEFT:
544             statt = ST_ATTACHMENT_BACK_LEFT;
545             break;
546          default:
547             continue; /* invalid attachment */
548          }
549
550          dri_drawable_get_format(drawable, statt, &format, &bind);
551          if (format == PIPE_FORMAT_NONE)
552             continue;
553
554          /* dri2_drawable_get_buffers has already filled dri_drawable->w
555           * and dri_drawable->h */
556          templ.width0 = dri_drawable->w;
557          templ.height0 = dri_drawable->h;
558          templ.format = format;
559          templ.bind = bind;
560          whandle.handle = buf->name;
561          whandle.stride = buf->pitch;
562          whandle.offset = 0;
563          if (screen->can_share_buffer)
564             whandle.type = DRM_API_HANDLE_TYPE_SHARED;
565          else
566             whandle.type = DRM_API_HANDLE_TYPE_KMS;
567          drawable->textures[statt] =
568             screen->base.screen->resource_from_handle(screen->base.screen,
569                   &templ, &whandle,
570                   PIPE_HANDLE_USAGE_EXPLICIT_FLUSH | PIPE_HANDLE_USAGE_READ);
571          assert(drawable->textures[statt]);
572       }
573    }
574
575    /* Allocate private MSAA colorbuffers. */
576    if (drawable->stvis.samples > 1) {
577       for (i = 0; i < statts_count; i++) {
578          enum st_attachment_type statt = statts[i];
579
580          if (statt == ST_ATTACHMENT_DEPTH_STENCIL)
581             continue;
582
583          if (drawable->textures[statt]) {
584             templ.format = drawable->textures[statt]->format;
585             templ.bind = drawable->textures[statt]->bind & ~PIPE_BIND_SCANOUT;
586             templ.nr_samples = drawable->stvis.samples;
587
588             /* Try to reuse the resource.
589              * (the other resource parameters should be constant)
590              */
591             if (!drawable->msaa_textures[statt] ||
592                 drawable->msaa_textures[statt]->width0 != templ.width0 ||
593                 drawable->msaa_textures[statt]->height0 != templ.height0) {
594                /* Allocate a new one. */
595                pipe_resource_reference(&drawable->msaa_textures[statt], NULL);
596
597                drawable->msaa_textures[statt] =
598                   screen->base.screen->resource_create(screen->base.screen,
599                                                        &templ);
600                assert(drawable->msaa_textures[statt]);
601
602                /* If there are any MSAA resources, we should initialize them
603                 * such that they contain the same data as the single-sample
604                 * resources we just got from the X server.
605                 *
606                 * The reason for this is that the state tracker (and
607                 * therefore the app) can access the MSAA resources only.
608                 * The single-sample resources are not exposed
609                 * to the state tracker.
610                 *
611                 */
612                dri_pipe_blit(ctx->st->pipe,
613                              drawable->msaa_textures[statt],
614                              drawable->textures[statt]);
615             }
616          }
617          else {
618             pipe_resource_reference(&drawable->msaa_textures[statt], NULL);
619          }
620       }
621    }
622
623    /* Allocate a private depth-stencil buffer. */
624    if (alloc_depthstencil) {
625       enum st_attachment_type statt = ST_ATTACHMENT_DEPTH_STENCIL;
626       struct pipe_resource **zsbuf;
627       enum pipe_format format;
628       unsigned bind;
629
630       dri_drawable_get_format(drawable, statt, &format, &bind);
631
632       if (format) {
633          templ.format = format;
634          templ.bind = bind;
635
636          if (drawable->stvis.samples > 1) {
637             templ.nr_samples = drawable->stvis.samples;
638             zsbuf = &drawable->msaa_textures[statt];
639          }
640          else {
641             templ.nr_samples = 0;
642             zsbuf = &drawable->textures[statt];
643          }
644
645          /* Try to reuse the resource.
646           * (the other resource parameters should be constant)
647           */
648          if (!*zsbuf ||
649              (*zsbuf)->width0 != templ.width0 ||
650              (*zsbuf)->height0 != templ.height0) {
651             /* Allocate a new one. */
652             pipe_resource_reference(zsbuf, NULL);
653             *zsbuf = screen->base.screen->resource_create(screen->base.screen,
654                                                           &templ);
655             assert(*zsbuf);
656          }
657       }
658       else {
659          pipe_resource_reference(&drawable->msaa_textures[statt], NULL);
660          pipe_resource_reference(&drawable->textures[statt], NULL);
661       }
662    }
663
664    /* For DRI2, we may get the same buffers again from the server.
665     * To prevent useless imports of gem names, drawable->old* is used
666     * to bypass the import if we get the same buffers. This doesn't apply
667     * to DRI3/Wayland, users of image.loader, since the buffer is managed
668     * by the client (no import), and the back buffer is going to change
669     * at every redraw.
670     */
671    if (!image) {
672       drawable->old_num = num_buffers;
673       drawable->old_w = dri_drawable->w;
674       drawable->old_h = dri_drawable->h;
675       memcpy(drawable->old, buffers, sizeof(__DRIbuffer) * num_buffers);
676    }
677 }
678
679 static void
680 dri2_flush_frontbuffer(struct dri_context *ctx,
681                        struct dri_drawable *drawable,
682                        enum st_attachment_type statt)
683 {
684    __DRIdrawable *dri_drawable = drawable->dPriv;
685    const __DRIimageLoaderExtension *image = drawable->sPriv->image.loader;
686    const __DRIdri2LoaderExtension *loader = drawable->sPriv->dri2.loader;
687    struct pipe_context *pipe = ctx->st->pipe;
688
689    if (statt != ST_ATTACHMENT_FRONT_LEFT)
690       return;
691
692    if (drawable->stvis.samples > 1) {
693       /* Resolve the front buffer. */
694       dri_pipe_blit(ctx->st->pipe,
695                     drawable->textures[ST_ATTACHMENT_FRONT_LEFT],
696                     drawable->msaa_textures[ST_ATTACHMENT_FRONT_LEFT]);
697    }
698
699    if (drawable->textures[ST_ATTACHMENT_FRONT_LEFT]) {
700       pipe->flush_resource(pipe, drawable->textures[ST_ATTACHMENT_FRONT_LEFT]);
701    }
702
703    pipe->flush(pipe, NULL, 0);
704
705    if (image) {
706       image->flushFrontBuffer(dri_drawable, dri_drawable->loaderPrivate);
707    }
708    else if (loader->flushFrontBuffer) {
709       loader->flushFrontBuffer(dri_drawable, dri_drawable->loaderPrivate);
710    }
711 }
712
713 static void
714 dri2_update_tex_buffer(struct dri_drawable *drawable,
715                        struct dri_context *ctx,
716                        struct pipe_resource *res)
717 {
718    /* no-op */
719 }
720
721 static __DRIimage *
722 dri2_lookup_egl_image(struct dri_screen *screen, void *handle)
723 {
724    const __DRIimageLookupExtension *loader = screen->sPriv->dri2.image;
725    __DRIimage *img;
726
727    if (!loader->lookupEGLImage)
728       return NULL;
729
730    img = loader->lookupEGLImage(screen->sPriv,
731                                 handle, screen->sPriv->loaderPrivate);
732
733    return img;
734 }
735
736 static __DRIimage *
737 dri2_create_image_from_winsys(__DRIscreen *_screen,
738                               int width, int height, int format,
739                               struct winsys_handle *whandle,
740                               void *loaderPrivate)
741 {
742    struct dri_screen *screen = dri_screen(_screen);
743    __DRIimage *img;
744    struct pipe_resource templ;
745    unsigned tex_usage;
746    enum pipe_format pf;
747
748    tex_usage = PIPE_BIND_RENDER_TARGET | PIPE_BIND_SAMPLER_VIEW;
749
750    pf = dri2_format_to_pipe_format (format);
751    if (pf == PIPE_FORMAT_NONE)
752       return NULL;
753
754    img = CALLOC_STRUCT(__DRIimageRec);
755    if (!img)
756       return NULL;
757
758    memset(&templ, 0, sizeof(templ));
759    templ.bind = tex_usage;
760    templ.format = pf;
761    templ.target = screen->target;
762    templ.last_level = 0;
763    templ.width0 = width;
764    templ.height0 = height;
765    templ.depth0 = 1;
766    templ.array_size = 1;
767
768    whandle->offset = 0;
769
770    img->texture = screen->base.screen->resource_from_handle(screen->base.screen,
771          &templ, whandle, PIPE_HANDLE_USAGE_READ_WRITE);
772    if (!img->texture) {
773       FREE(img);
774       return NULL;
775    }
776
777    img->level = 0;
778    img->layer = 0;
779    img->dri_format = format;
780    img->use = 0;
781    img->loader_private = loaderPrivate;
782
783    return img;
784 }
785
786 static __DRIimage *
787 dri2_create_image_from_name(__DRIscreen *_screen,
788                             int width, int height, int format,
789                             int name, int pitch, void *loaderPrivate)
790 {
791    struct winsys_handle whandle;
792    enum pipe_format pf;
793
794    memset(&whandle, 0, sizeof(whandle));
795    whandle.type = DRM_API_HANDLE_TYPE_SHARED;
796    whandle.handle = name;
797
798    pf = dri2_format_to_pipe_format (format);
799    if (pf == PIPE_FORMAT_NONE)
800       return NULL;
801
802    whandle.stride = pitch * util_format_get_blocksize(pf);
803
804    return dri2_create_image_from_winsys(_screen, width, height, format,
805                                         &whandle, loaderPrivate);
806 }
807
808 static __DRIimage *
809 dri2_create_image_from_fd(__DRIscreen *_screen,
810                           int width, int height, int format,
811                           int fd, int stride, void *loaderPrivate)
812 {
813    struct winsys_handle whandle;
814
815    if (fd < 0)
816       return NULL;
817
818    memset(&whandle, 0, sizeof(whandle));
819    whandle.type = DRM_API_HANDLE_TYPE_FD;
820    whandle.handle = (unsigned)fd;
821    whandle.stride = stride;
822
823    return dri2_create_image_from_winsys(_screen, width, height, format,
824                                         &whandle, loaderPrivate);
825 }
826
827 static __DRIimage *
828 dri2_create_image_from_renderbuffer(__DRIcontext *context,
829                                     int renderbuffer, void *loaderPrivate)
830 {
831    struct dri_context *ctx = dri_context(context);
832
833    if (!ctx->st->get_resource_for_egl_image)
834       return NULL;
835
836    /* TODO */
837    return NULL;
838 }
839
840 static __DRIimage *
841 dri2_create_image(__DRIscreen *_screen,
842                    int width, int height, int format,
843                    unsigned int use, void *loaderPrivate)
844 {
845    struct dri_screen *screen = dri_screen(_screen);
846    __DRIimage *img;
847    struct pipe_resource templ;
848    unsigned tex_usage;
849    enum pipe_format pf;
850
851    tex_usage = PIPE_BIND_RENDER_TARGET | PIPE_BIND_SAMPLER_VIEW;
852    if (use & __DRI_IMAGE_USE_SCANOUT)
853       tex_usage |= PIPE_BIND_SCANOUT;
854    if (use & __DRI_IMAGE_USE_SHARE)
855       tex_usage |= PIPE_BIND_SHARED;
856    if (use & __DRI_IMAGE_USE_LINEAR)
857       tex_usage |= PIPE_BIND_LINEAR;
858    if (use & __DRI_IMAGE_USE_CURSOR) {
859       if (width != 64 || height != 64)
860          return NULL;
861       tex_usage |= PIPE_BIND_CURSOR;
862    }
863
864    pf = dri2_format_to_pipe_format (format);
865    if (pf == PIPE_FORMAT_NONE)
866       return NULL;
867
868    img = CALLOC_STRUCT(__DRIimageRec);
869    if (!img)
870       return NULL;
871
872    memset(&templ, 0, sizeof(templ));
873    templ.bind = tex_usage;
874    templ.format = pf;
875    templ.target = PIPE_TEXTURE_2D;
876    templ.last_level = 0;
877    templ.width0 = width;
878    templ.height0 = height;
879    templ.depth0 = 1;
880    templ.array_size = 1;
881
882    img->texture = screen->base.screen->resource_create(screen->base.screen, &templ);
883    if (!img->texture) {
884       FREE(img);
885       return NULL;
886    }
887
888    img->level = 0;
889    img->layer = 0;
890    img->dri_format = format;
891    img->dri_components = 0;
892    img->use = use;
893
894    img->loader_private = loaderPrivate;
895    return img;
896 }
897
898 static GLboolean
899 dri2_query_image(__DRIimage *image, int attrib, int *value)
900 {
901    struct winsys_handle whandle;
902    unsigned usage;
903
904    if (image->use & __DRI_IMAGE_USE_BACKBUFFER)
905       usage = PIPE_HANDLE_USAGE_EXPLICIT_FLUSH | PIPE_HANDLE_USAGE_READ;
906    else
907       usage = PIPE_HANDLE_USAGE_READ_WRITE;
908
909    memset(&whandle, 0, sizeof(whandle));
910
911    switch (attrib) {
912    case __DRI_IMAGE_ATTRIB_STRIDE:
913       whandle.type = DRM_API_HANDLE_TYPE_KMS;
914       image->texture->screen->resource_get_handle(image->texture->screen,
915             image->texture, &whandle, usage);
916       *value = whandle.stride;
917       return GL_TRUE;
918    case __DRI_IMAGE_ATTRIB_HANDLE:
919       whandle.type = DRM_API_HANDLE_TYPE_KMS;
920       image->texture->screen->resource_get_handle(image->texture->screen,
921          image->texture, &whandle, usage);
922       *value = whandle.handle;
923       return GL_TRUE;
924    case __DRI_IMAGE_ATTRIB_NAME:
925       whandle.type = DRM_API_HANDLE_TYPE_SHARED;
926       image->texture->screen->resource_get_handle(image->texture->screen,
927          image->texture, &whandle, usage);
928       *value = whandle.handle;
929       return GL_TRUE;
930    case __DRI_IMAGE_ATTRIB_FD:
931       whandle.type= DRM_API_HANDLE_TYPE_FD;
932       image->texture->screen->resource_get_handle(image->texture->screen,
933          image->texture, &whandle, usage);
934       *value = whandle.handle;
935       return GL_TRUE;
936    case __DRI_IMAGE_ATTRIB_FORMAT:
937       *value = image->dri_format;
938       return GL_TRUE;
939    case __DRI_IMAGE_ATTRIB_WIDTH:
940       *value = image->texture->width0;
941       return GL_TRUE;
942    case __DRI_IMAGE_ATTRIB_HEIGHT:
943       *value = image->texture->height0;
944       return GL_TRUE;
945    case __DRI_IMAGE_ATTRIB_COMPONENTS:
946       if (image->dri_components == 0)
947          return GL_FALSE;
948       *value = image->dri_components;
949       return GL_TRUE;
950    case __DRI_IMAGE_ATTRIB_FOURCC:
951       *value = convert_to_fourcc(image->dri_format);
952       return GL_TRUE;
953    case __DRI_IMAGE_ATTRIB_NUM_PLANES:
954       *value = 1;
955       return GL_TRUE;
956    default:
957       return GL_FALSE;
958    }
959 }
960
961 static __DRIimage *
962 dri2_dup_image(__DRIimage *image, void *loaderPrivate)
963 {
964    __DRIimage *img;
965
966    img = CALLOC_STRUCT(__DRIimageRec);
967    if (!img)
968       return NULL;
969
970    img->texture = NULL;
971    pipe_resource_reference(&img->texture, image->texture);
972    img->level = image->level;
973    img->layer = image->layer;
974    img->dri_format = image->dri_format;
975    /* This should be 0 for sub images, but dup is also used for base images. */
976    img->dri_components = image->dri_components;
977    img->loader_private = loaderPrivate;
978
979    return img;
980 }
981
982 static GLboolean
983 dri2_validate_usage(__DRIimage *image, unsigned int use)
984 {
985    /*
986     * Gallium drivers are bad at adding usages to the resources
987     * once opened again in another process, which is the main use
988     * case for this, so we have to lie.
989     */
990    if (image != NULL)
991       return GL_TRUE;
992    else
993       return GL_FALSE;
994 }
995
996 static __DRIimage *
997 dri2_from_names(__DRIscreen *screen, int width, int height, int format,
998                 int *names, int num_names, int *strides, int *offsets,
999                 void *loaderPrivate)
1000 {
1001    __DRIimage *img;
1002    int dri_components;
1003    struct winsys_handle whandle;
1004
1005    if (num_names != 1)
1006       return NULL;
1007    if (offsets[0] != 0)
1008       return NULL;
1009
1010    format = convert_fourcc(format, &dri_components);
1011    if (format == -1)
1012       return NULL;
1013
1014    memset(&whandle, 0, sizeof(whandle));
1015    whandle.type = DRM_API_HANDLE_TYPE_SHARED;
1016    whandle.handle = names[0];
1017    whandle.stride = strides[0];
1018
1019    img = dri2_create_image_from_winsys(screen, width, height, format,
1020                                        &whandle, loaderPrivate);
1021    if (img == NULL)
1022       return NULL;
1023
1024    img->dri_components = dri_components;
1025    return img;
1026 }
1027
1028 static __DRIimage *
1029 dri2_from_planar(__DRIimage *image, int plane, void *loaderPrivate)
1030 {
1031    __DRIimage *img;
1032
1033    if (plane != 0)
1034       return NULL;
1035
1036    if (image->dri_components == 0)
1037       return NULL;
1038
1039    img = dri2_dup_image(image, loaderPrivate);
1040    if (img == NULL)
1041       return NULL;
1042
1043    /* set this to 0 for sub images. */
1044    img->dri_components = 0;
1045    return img;
1046 }
1047
1048 static __DRIimage *
1049 dri2_create_from_texture(__DRIcontext *context, int target, unsigned texture,
1050                          int depth, int level, unsigned *error,
1051                          void *loaderPrivate)
1052 {
1053    __DRIimage *img;
1054    struct gl_context *ctx = ((struct st_context *)dri_context(context)->st)->ctx;
1055    struct gl_texture_object *obj;
1056    struct pipe_resource *tex;
1057    GLuint face = 0;
1058
1059    obj = _mesa_lookup_texture(ctx, texture);
1060    if (!obj || obj->Target != target) {
1061       *error = __DRI_IMAGE_ERROR_BAD_PARAMETER;
1062       return NULL;
1063    }
1064
1065    tex = st_get_texobj_resource(obj);
1066    if (!tex) {
1067       *error = __DRI_IMAGE_ERROR_BAD_PARAMETER;
1068       return NULL;
1069    }
1070
1071    if (target == GL_TEXTURE_CUBE_MAP)
1072       face = depth;
1073
1074    _mesa_test_texobj_completeness(ctx, obj);
1075    if (!obj->_BaseComplete || (level > 0 && !obj->_MipmapComplete)) {
1076       *error = __DRI_IMAGE_ERROR_BAD_PARAMETER;
1077       return NULL;
1078    }
1079
1080    if (level < obj->BaseLevel || level > obj->_MaxLevel) {
1081       *error = __DRI_IMAGE_ERROR_BAD_MATCH;
1082       return NULL;
1083    }
1084
1085    if (target == GL_TEXTURE_3D && obj->Image[face][level]->Depth < depth) {
1086       *error = __DRI_IMAGE_ERROR_BAD_MATCH;
1087       return NULL;
1088    }
1089
1090    img = CALLOC_STRUCT(__DRIimageRec);
1091    if (!img) {
1092       *error = __DRI_IMAGE_ERROR_BAD_ALLOC;
1093       return NULL;
1094    }
1095
1096    img->level = level;
1097    img->layer = depth;
1098    img->dri_format = driGLFormatToImageFormat(obj->Image[face][level]->TexFormat);
1099
1100    img->loader_private = loaderPrivate;
1101
1102    if (img->dri_format == __DRI_IMAGE_FORMAT_NONE) {
1103       *error = __DRI_IMAGE_ERROR_BAD_PARAMETER;
1104       free(img);
1105       return NULL;
1106    }
1107
1108    pipe_resource_reference(&img->texture, tex);
1109
1110    *error = __DRI_IMAGE_ERROR_SUCCESS;
1111    return img;
1112 }
1113
1114 static __DRIimage *
1115 dri2_from_fds(__DRIscreen *screen, int width, int height, int fourcc,
1116               int *fds, int num_fds, int *strides, int *offsets,
1117               void *loaderPrivate)
1118 {
1119    __DRIimage *img;
1120    int format, dri_components;
1121
1122    if (num_fds != 1)
1123       return NULL;
1124    if (offsets[0] != 0)
1125       return NULL;
1126
1127    format = convert_fourcc(fourcc, &dri_components);
1128    if (format == -1)
1129       return NULL;
1130
1131    img = dri2_create_image_from_fd(screen, width, height, format,
1132                                    fds[0], strides[0], loaderPrivate);
1133    if (img == NULL)
1134       return NULL;
1135
1136    img->dri_components = dri_components;
1137    return img;
1138 }
1139
1140 static __DRIimage *
1141 dri2_from_dma_bufs(__DRIscreen *screen,
1142                    int width, int height, int fourcc,
1143                    int *fds, int num_fds,
1144                    int *strides, int *offsets,
1145                    enum __DRIYUVColorSpace yuv_color_space,
1146                    enum __DRISampleRange sample_range,
1147                    enum __DRIChromaSiting horizontal_siting,
1148                    enum __DRIChromaSiting vertical_siting,
1149                    unsigned *error,
1150                    void *loaderPrivate)
1151 {
1152    __DRIimage *img;
1153    int format, dri_components;
1154
1155    if (num_fds != 1 || offsets[0] != 0) {
1156       *error = __DRI_IMAGE_ERROR_BAD_MATCH;
1157       return NULL;
1158    }
1159
1160    format = convert_fourcc(fourcc, &dri_components);
1161    if (format == -1) {
1162       *error = __DRI_IMAGE_ERROR_BAD_MATCH;
1163       return NULL;
1164    }
1165
1166    img = dri2_create_image_from_fd(screen, width, height, format,
1167                                    fds[0], strides[0], loaderPrivate);
1168    if (img == NULL) {
1169       *error = __DRI_IMAGE_ERROR_BAD_ALLOC;
1170       return NULL;
1171    }
1172
1173    img->yuv_color_space = yuv_color_space;
1174    img->sample_range = sample_range;
1175    img->horizontal_siting = horizontal_siting;
1176    img->vertical_siting = vertical_siting;
1177    img->dri_components = dri_components;
1178
1179    *error = __DRI_IMAGE_ERROR_SUCCESS;
1180    return img;
1181 }
1182
1183 static void
1184 dri2_blit_image(__DRIcontext *context, __DRIimage *dst, __DRIimage *src,
1185                 int dstx0, int dsty0, int dstwidth, int dstheight,
1186                 int srcx0, int srcy0, int srcwidth, int srcheight,
1187                 int flush_flag)
1188 {
1189    struct dri_context *ctx = dri_context(context);
1190    struct pipe_context *pipe = ctx->st->pipe;
1191    struct pipe_screen *screen;
1192    struct pipe_fence_handle *fence;
1193    struct pipe_blit_info blit;
1194
1195    if (!dst || !src)
1196       return;
1197
1198    memset(&blit, 0, sizeof(blit));
1199    blit.dst.resource = dst->texture;
1200    blit.dst.box.x = dstx0;
1201    blit.dst.box.y = dsty0;
1202    blit.dst.box.width = dstwidth;
1203    blit.dst.box.height = dstheight;
1204    blit.dst.box.depth = 1;
1205    blit.dst.format = dst->texture->format;
1206    blit.src.resource = src->texture;
1207    blit.src.box.x = srcx0;
1208    blit.src.box.y = srcy0;
1209    blit.src.box.width = srcwidth;
1210    blit.src.box.height = srcheight;
1211    blit.src.box.depth = 1;
1212    blit.src.format = src->texture->format;
1213    blit.mask = PIPE_MASK_RGBA;
1214    blit.filter = PIPE_TEX_FILTER_NEAREST;
1215
1216    pipe->blit(pipe, &blit);
1217
1218    if (flush_flag == __BLIT_FLAG_FLUSH) {
1219       pipe->flush_resource(pipe, dst->texture);
1220       ctx->st->flush(ctx->st, 0, NULL);
1221    } else if (flush_flag == __BLIT_FLAG_FINISH) {
1222       screen = dri_screen(ctx->sPriv)->base.screen;
1223       pipe->flush_resource(pipe, dst->texture);
1224       ctx->st->flush(ctx->st, 0, &fence);
1225       (void) screen->fence_finish(screen, fence, PIPE_TIMEOUT_INFINITE);
1226       screen->fence_reference(screen, &fence, NULL);
1227    }
1228 }
1229
1230 static void
1231 dri2_destroy_image(__DRIimage *img)
1232 {
1233    pipe_resource_reference(&img->texture, NULL);
1234    FREE(img);
1235 }
1236
1237 static int
1238 dri2_get_capabilities(__DRIscreen *_screen)
1239 {
1240    struct dri_screen *screen = dri_screen(_screen);
1241
1242    return (screen->can_share_buffer ? __DRI_IMAGE_CAP_GLOBAL_NAMES : 0);
1243 }
1244
1245 /* The extension is modified during runtime if DRI_PRIME is detected */
1246 static __DRIimageExtension dri2ImageExtension = {
1247     .base = { __DRI_IMAGE, 11 },
1248
1249     .createImageFromName          = dri2_create_image_from_name,
1250     .createImageFromRenderbuffer  = dri2_create_image_from_renderbuffer,
1251     .destroyImage                 = dri2_destroy_image,
1252     .createImage                  = dri2_create_image,
1253     .queryImage                   = dri2_query_image,
1254     .dupImage                     = dri2_dup_image,
1255     .validateUsage                = dri2_validate_usage,
1256     .createImageFromNames         = dri2_from_names,
1257     .fromPlanar                   = dri2_from_planar,
1258     .createImageFromTexture       = dri2_create_from_texture,
1259     .createImageFromFds           = NULL,
1260     .createImageFromDmaBufs       = NULL,
1261     .blitImage                    = dri2_blit_image,
1262     .getCapabilities              = dri2_get_capabilities,
1263 };
1264
1265
1266 static bool
1267 dri2_is_opencl_interop_loaded_locked(struct dri_screen *screen)
1268 {
1269    return screen->opencl_dri_event_add_ref &&
1270           screen->opencl_dri_event_release &&
1271           screen->opencl_dri_event_wait &&
1272           screen->opencl_dri_event_get_fence;
1273 }
1274
1275 static bool
1276 dri2_load_opencl_interop(struct dri_screen *screen)
1277 {
1278 #if defined(RTLD_DEFAULT)
1279    bool success;
1280
1281    pipe_mutex_lock(screen->opencl_func_mutex);
1282
1283    if (dri2_is_opencl_interop_loaded_locked(screen)) {
1284       pipe_mutex_unlock(screen->opencl_func_mutex);
1285       return true;
1286    }
1287
1288    screen->opencl_dri_event_add_ref =
1289       dlsym(RTLD_DEFAULT, "opencl_dri_event_add_ref");
1290    screen->opencl_dri_event_release =
1291       dlsym(RTLD_DEFAULT, "opencl_dri_event_release");
1292    screen->opencl_dri_event_wait =
1293       dlsym(RTLD_DEFAULT, "opencl_dri_event_wait");
1294    screen->opencl_dri_event_get_fence =
1295       dlsym(RTLD_DEFAULT, "opencl_dri_event_get_fence");
1296
1297    success = dri2_is_opencl_interop_loaded_locked(screen);
1298    pipe_mutex_unlock(screen->opencl_func_mutex);
1299    return success;
1300 #else
1301    return false;
1302 #endif
1303 }
1304
1305 struct dri2_fence {
1306    struct dri_screen *driscreen;
1307    struct pipe_fence_handle *pipe_fence;
1308    void *cl_event;
1309 };
1310
1311 static void *
1312 dri2_create_fence(__DRIcontext *_ctx)
1313 {
1314    struct pipe_context *ctx = dri_context(_ctx)->st->pipe;
1315    struct dri2_fence *fence = CALLOC_STRUCT(dri2_fence);
1316
1317    if (!fence)
1318       return NULL;
1319
1320    ctx->flush(ctx, &fence->pipe_fence, 0);
1321
1322    if (!fence->pipe_fence) {
1323       FREE(fence);
1324       return NULL;
1325    }
1326
1327    fence->driscreen = dri_screen(_ctx->driScreenPriv);
1328    return fence;
1329 }
1330
1331 static void *
1332 dri2_get_fence_from_cl_event(__DRIscreen *_screen, intptr_t cl_event)
1333 {
1334    struct dri_screen *driscreen = dri_screen(_screen);
1335    struct dri2_fence *fence;
1336
1337    if (!dri2_load_opencl_interop(driscreen))
1338       return NULL;
1339
1340    fence = CALLOC_STRUCT(dri2_fence);
1341    if (!fence)
1342       return NULL;
1343
1344    fence->cl_event = (void*)cl_event;
1345
1346    if (!driscreen->opencl_dri_event_add_ref(fence->cl_event)) {
1347       free(fence);
1348       return NULL;
1349    }
1350
1351    fence->driscreen = driscreen;
1352    return fence;
1353 }
1354
1355 static void
1356 dri2_destroy_fence(__DRIscreen *_screen, void *_fence)
1357 {
1358    struct dri_screen *driscreen = dri_screen(_screen);
1359    struct pipe_screen *screen = driscreen->base.screen;
1360    struct dri2_fence *fence = (struct dri2_fence*)_fence;
1361
1362    if (fence->pipe_fence)
1363       screen->fence_reference(screen, &fence->pipe_fence, NULL);
1364    else if (fence->cl_event)
1365       driscreen->opencl_dri_event_release(fence->cl_event);
1366    else
1367       assert(0);
1368
1369    FREE(fence);
1370 }
1371
1372 static GLboolean
1373 dri2_client_wait_sync(__DRIcontext *_ctx, void *_fence, unsigned flags,
1374                       uint64_t timeout)
1375 {
1376    struct dri2_fence *fence = (struct dri2_fence*)_fence;
1377    struct dri_screen *driscreen = fence->driscreen;
1378    struct pipe_screen *screen = driscreen->base.screen;
1379
1380    /* No need to flush. The context was flushed when the fence was created. */
1381
1382    if (fence->pipe_fence)
1383       return screen->fence_finish(screen, fence->pipe_fence, timeout);
1384    else if (fence->cl_event) {
1385       struct pipe_fence_handle *pipe_fence =
1386          driscreen->opencl_dri_event_get_fence(fence->cl_event);
1387
1388       if (pipe_fence)
1389          return screen->fence_finish(screen, pipe_fence, timeout);
1390       else
1391          return driscreen->opencl_dri_event_wait(fence->cl_event, timeout);
1392    }
1393    else {
1394       assert(0);
1395       return false;
1396    }
1397 }
1398
1399 static void
1400 dri2_server_wait_sync(__DRIcontext *_ctx, void *_fence, unsigned flags)
1401 {
1402    /* AFAIK, no driver currently supports parallel context execution. */
1403 }
1404
1405 static __DRI2fenceExtension dri2FenceExtension = {
1406    .base = { __DRI2_FENCE, 1 },
1407
1408    .create_fence = dri2_create_fence,
1409    .get_fence_from_cl_event = dri2_get_fence_from_cl_event,
1410    .destroy_fence = dri2_destroy_fence,
1411    .client_wait_sync = dri2_client_wait_sync,
1412    .server_wait_sync = dri2_server_wait_sync
1413 };
1414
1415 static const __DRIrobustnessExtension dri2Robustness = {
1416    .base = { __DRI2_ROBUSTNESS, 1 }
1417 };
1418
1419 /*
1420  * Backend function init_screen.
1421  */
1422
1423 static const __DRIextension *dri_screen_extensions[] = {
1424    &driTexBufferExtension.base,
1425    &dri2FlushExtension.base,
1426    &dri2ImageExtension.base,
1427    &dri2RendererQueryExtension.base,
1428    &dri2ConfigQueryExtension.base,
1429    &dri2ThrottleExtension.base,
1430    &dri2FenceExtension.base,
1431    NULL
1432 };
1433
1434 static const __DRIextension *dri_robust_screen_extensions[] = {
1435    &driTexBufferExtension.base,
1436    &dri2FlushExtension.base,
1437    &dri2ImageExtension.base,
1438    &dri2RendererQueryExtension.base,
1439    &dri2ConfigQueryExtension.base,
1440    &dri2ThrottleExtension.base,
1441    &dri2FenceExtension.base,
1442    &dri2Robustness.base,
1443    NULL
1444 };
1445
1446 /**
1447  * This is the driver specific part of the createNewScreen entry point.
1448  *
1449  * Returns the struct gl_config supported by this driver.
1450  */
1451 static const __DRIconfig **
1452 dri2_init_screen(__DRIscreen * sPriv)
1453 {
1454    const __DRIconfig **configs;
1455    struct dri_screen *screen;
1456    struct pipe_screen *pscreen = NULL;
1457    const struct drm_conf_ret *throttle_ret;
1458    const struct drm_conf_ret *dmabuf_ret;
1459    int fd = -1;
1460
1461    screen = CALLOC_STRUCT(dri_screen);
1462    if (!screen)
1463       return NULL;
1464
1465    screen->sPriv = sPriv;
1466    screen->fd = sPriv->fd;
1467    pipe_mutex_init(screen->opencl_func_mutex);
1468
1469    sPriv->driverPrivate = (void *)screen;
1470
1471    if (screen->fd < 0 || (fd = dup(screen->fd)) < 0)
1472       goto fail;
1473
1474    if (pipe_loader_drm_probe_fd(&screen->dev, fd))
1475       pscreen = pipe_loader_create_screen(screen->dev);
1476
1477    if (!pscreen)
1478        goto fail;
1479
1480    throttle_ret = pipe_loader_configuration(screen->dev, DRM_CONF_THROTTLE);
1481    dmabuf_ret = pipe_loader_configuration(screen->dev, DRM_CONF_SHARE_FD);
1482
1483    if (throttle_ret && throttle_ret->val.val_int != -1) {
1484       screen->throttling_enabled = TRUE;
1485       screen->default_throttle_frames = throttle_ret->val.val_int;
1486    }
1487
1488    if (dmabuf_ret && dmabuf_ret->val.val_bool) {
1489       uint64_t cap;
1490
1491       if (drmGetCap(sPriv->fd, DRM_CAP_PRIME, &cap) == 0 &&
1492           (cap & DRM_PRIME_CAP_IMPORT)) {
1493          dri2ImageExtension.createImageFromFds = dri2_from_fds;
1494          dri2ImageExtension.createImageFromDmaBufs = dri2_from_dma_bufs;
1495       }
1496    }
1497
1498    if (pscreen->get_param(pscreen, PIPE_CAP_DEVICE_RESET_STATUS_QUERY)) {
1499       sPriv->extensions = dri_robust_screen_extensions;
1500       screen->has_reset_status_query = true;
1501    }
1502    else
1503       sPriv->extensions = dri_screen_extensions;
1504
1505    configs = dri_init_screen_helper(screen, pscreen, screen->dev->driver_name);
1506    if (!configs)
1507       goto fail;
1508
1509    screen->can_share_buffer = true;
1510    screen->auto_fake_front = dri_with_format(sPriv);
1511    screen->broken_invalidate = !sPriv->dri2.useInvalidate;
1512    screen->lookup_egl_image = dri2_lookup_egl_image;
1513
1514    return configs;
1515 fail:
1516    dri_destroy_screen_helper(screen);
1517    if (screen->dev)
1518       pipe_loader_release(&screen->dev, 1);
1519    else
1520       close(fd);
1521    FREE(screen);
1522    return NULL;
1523 }
1524
1525 /**
1526  * This is the driver specific part of the createNewScreen entry point.
1527  *
1528  * Returns the struct gl_config supported by this driver.
1529  */
1530 static const __DRIconfig **
1531 dri_kms_init_screen(__DRIscreen * sPriv)
1532 {
1533 #if defined(GALLIUM_SOFTPIPE)
1534    const __DRIconfig **configs;
1535    struct dri_screen *screen;
1536    struct pipe_screen *pscreen = NULL;
1537    uint64_t cap;
1538    int fd = -1;
1539
1540    screen = CALLOC_STRUCT(dri_screen);
1541    if (!screen)
1542       return NULL;
1543
1544    screen->sPriv = sPriv;
1545    screen->fd = sPriv->fd;
1546
1547    sPriv->driverPrivate = (void *)screen;
1548
1549    if (screen->fd < 0 || (fd = dup(screen->fd)) < 0)
1550       goto fail;
1551
1552    if (pipe_loader_sw_probe_kms(&screen->dev, fd))
1553       pscreen = pipe_loader_create_screen(screen->dev);
1554
1555    if (!pscreen)
1556        goto fail;
1557
1558    if (drmGetCap(sPriv->fd, DRM_CAP_PRIME, &cap) == 0 &&
1559           (cap & DRM_PRIME_CAP_IMPORT)) {
1560       dri2ImageExtension.createImageFromFds = dri2_from_fds;
1561       dri2ImageExtension.createImageFromDmaBufs = dri2_from_dma_bufs;
1562    }
1563
1564    sPriv->extensions = dri_screen_extensions;
1565
1566    configs = dri_init_screen_helper(screen, pscreen, "swrast");
1567    if (!configs)
1568       goto fail;
1569
1570    screen->can_share_buffer = false;
1571    screen->auto_fake_front = dri_with_format(sPriv);
1572    screen->broken_invalidate = !sPriv->dri2.useInvalidate;
1573    screen->lookup_egl_image = dri2_lookup_egl_image;
1574
1575    return configs;
1576 fail:
1577    dri_destroy_screen_helper(screen);
1578    if (screen->dev)
1579       pipe_loader_release(&screen->dev, 1);
1580    else
1581       close(fd);
1582    FREE(screen);
1583 #endif // GALLIUM_SOFTPIPE
1584    return NULL;
1585 }
1586
1587 static boolean
1588 dri2_create_buffer(__DRIscreen * sPriv,
1589                    __DRIdrawable * dPriv,
1590                    const struct gl_config * visual, boolean isPixmap)
1591 {
1592    struct dri_drawable *drawable = NULL;
1593
1594    if (!dri_create_buffer(sPriv, dPriv, visual, isPixmap))
1595       return FALSE;
1596
1597    drawable = dPriv->driverPrivate;
1598
1599    drawable->allocate_textures = dri2_allocate_textures;
1600    drawable->flush_frontbuffer = dri2_flush_frontbuffer;
1601    drawable->update_tex_buffer = dri2_update_tex_buffer;
1602
1603    return TRUE;
1604 }
1605
1606 /**
1607  * DRI driver virtual function table.
1608  *
1609  * DRI versions differ in their implementation of init_screen and swap_buffers.
1610  */
1611 const struct __DriverAPIRec galliumdrm_driver_api = {
1612    .InitScreen = dri2_init_screen,
1613    .DestroyScreen = dri_destroy_screen,
1614    .CreateContext = dri_create_context,
1615    .DestroyContext = dri_destroy_context,
1616    .CreateBuffer = dri2_create_buffer,
1617    .DestroyBuffer = dri_destroy_buffer,
1618    .MakeCurrent = dri_make_current,
1619    .UnbindContext = dri_unbind_context,
1620
1621    .AllocateBuffer = dri2_allocate_buffer,
1622    .ReleaseBuffer  = dri2_release_buffer,
1623 };
1624
1625 /**
1626  * DRI driver virtual function table.
1627  *
1628  * KMS/DRM version of the DriverAPI above sporting a different InitScreen
1629  * hook. The latter is used to explicitly initialise the kms_swrast driver
1630  * rather than selecting the approapriate driver as suggested by the loader.
1631  */
1632 const struct __DriverAPIRec dri_kms_driver_api = {
1633    .InitScreen = dri_kms_init_screen,
1634    .DestroyScreen = dri_destroy_screen,
1635    .CreateContext = dri_create_context,
1636    .DestroyContext = dri_destroy_context,
1637    .CreateBuffer = dri2_create_buffer,
1638    .DestroyBuffer = dri_destroy_buffer,
1639    .MakeCurrent = dri_make_current,
1640    .UnbindContext = dri_unbind_context,
1641
1642    .AllocateBuffer = dri2_allocate_buffer,
1643    .ReleaseBuffer  = dri2_release_buffer,
1644 };
1645
1646 /* This is the table of extensions that the loader will dlsym() for. */
1647 const __DRIextension *galliumdrm_driver_extensions[] = {
1648     &driCoreExtension.base,
1649     &driImageDriverExtension.base,
1650     &driDRI2Extension.base,
1651     &gallium_config_options.base,
1652     NULL
1653 };
1654
1655 /* vim: set sw=3 ts=8 sts=3 expandtab: */