• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Mesa 3-D graphics library
3  *
4  * Copyright (C) 2010-2011 Chia-I Wu <olvaffe@gmail.com>
5  * Copyright (C) 2010-2011 LunarG Inc.
6  *
7  * Based on platform_x11, which has
8  *
9  * Copyright © 2011 Intel Corporation
10  *
11  * Permission is hereby granted, free of charge, to any person obtaining a
12  * copy of this software and associated documentation files (the "Software"),
13  * to deal in the Software without restriction, including without limitation
14  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
15  * and/or sell copies of the Software, and to permit persons to whom the
16  * Software is furnished to do so, subject to the following conditions:
17  *
18  * The above copyright notice and this permission notice shall be included
19  * in all copies or substantial portions of the Software.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
24  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27  * DEALINGS IN THE SOFTWARE.
28  */
29 
30 #include <cutils/properties.h>
31 #include <errno.h>
32 #include <dirent.h>
33 #include <dlfcn.h>
34 #include <fcntl.h>
35 #include <xf86drm.h>
36 #include <stdbool.h>
37 #include <stdio.h>
38 #include <sync/sync.h>
39 #include <sys/types.h>
40 #include <drm-uapi/drm_fourcc.h>
41 
42 #include "util/os_file.h"
43 
44 #include "loader.h"
45 #include "egl_dri2.h"
46 
47 #ifdef HAVE_DRM_GRALLOC
48 #include <gralloc_drm_handle.h>
49 #include "gralloc_drm.h"
50 #endif /* HAVE_DRM_GRALLOC */
51 
52 #define ALIGN(val, align)	(((val) + (align) - 1) & ~((align) - 1))
53 
54 enum chroma_order {
55    YCbCr,
56    YCrCb,
57 };
58 
59 struct droid_yuv_format {
60    /* Lookup keys */
61    int native; /* HAL_PIXEL_FORMAT_ */
62    enum chroma_order chroma_order; /* chroma order is {Cb, Cr} or {Cr, Cb} */
63    int chroma_step; /* Distance in bytes between subsequent chroma pixels. */
64 
65    /* Result */
66    int fourcc; /* DRM_FORMAT_ */
67 };
68 
69 /* The following table is used to look up a DRI image FourCC based
70  * on native format and information contained in android_ycbcr struct. */
71 static const struct droid_yuv_format droid_yuv_formats[] = {
72    /* Native format, YCrCb, Chroma step, DRI image FourCC */
73    { HAL_PIXEL_FORMAT_YCbCr_420_888, YCbCr, 2, DRM_FORMAT_NV12 },
74    { HAL_PIXEL_FORMAT_YCbCr_420_888, YCbCr, 1, DRM_FORMAT_YUV420 },
75    { HAL_PIXEL_FORMAT_YCbCr_420_888, YCrCb, 1, DRM_FORMAT_YVU420 },
76    { HAL_PIXEL_FORMAT_YV12,          YCrCb, 1, DRM_FORMAT_YVU420 },
77    /* HACK: See droid_create_image_from_prime_fds() and
78     * https://issuetracker.google.com/32077885. */
79    { HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, YCbCr, 2, DRM_FORMAT_NV12 },
80    { HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, YCbCr, 1, DRM_FORMAT_YUV420 },
81    { HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, YCrCb, 1, DRM_FORMAT_YVU420 },
82    { HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, YCrCb, 1, DRM_FORMAT_AYUV },
83    { HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED, YCrCb, 1, DRM_FORMAT_XYUV8888 },
84 };
85 
86 static int
get_fourcc_yuv(int native,enum chroma_order chroma_order,int chroma_step)87 get_fourcc_yuv(int native, enum chroma_order chroma_order, int chroma_step)
88 {
89    for (int i = 0; i < ARRAY_SIZE(droid_yuv_formats); ++i)
90       if (droid_yuv_formats[i].native == native &&
91           droid_yuv_formats[i].chroma_order == chroma_order &&
92           droid_yuv_formats[i].chroma_step == chroma_step)
93          return droid_yuv_formats[i].fourcc;
94 
95    return -1;
96 }
97 
98 static bool
is_yuv(int native)99 is_yuv(int native)
100 {
101    for (int i = 0; i < ARRAY_SIZE(droid_yuv_formats); ++i)
102       if (droid_yuv_formats[i].native == native)
103          return true;
104 
105    return false;
106 }
107 
108 static int
get_format_bpp(int native)109 get_format_bpp(int native)
110 {
111    int bpp;
112 
113    switch (native) {
114    case HAL_PIXEL_FORMAT_RGBA_FP16:
115       bpp = 8;
116       break;
117    case HAL_PIXEL_FORMAT_RGBA_8888:
118    case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
119       /*
120        * HACK: Hardcode this to RGBX_8888 as per cros_gralloc hack.
121        * TODO: Remove this once https://issuetracker.google.com/32077885 is fixed.
122        */
123    case HAL_PIXEL_FORMAT_RGBX_8888:
124    case HAL_PIXEL_FORMAT_BGRA_8888:
125    case HAL_PIXEL_FORMAT_RGBA_1010102:
126       bpp = 4;
127       break;
128    case HAL_PIXEL_FORMAT_RGB_565:
129       bpp = 2;
130       break;
131    default:
132       bpp = 0;
133       break;
134    }
135 
136    return bpp;
137 }
138 
139 /* createImageFromFds requires fourcc format */
get_fourcc(int native)140 static int get_fourcc(int native)
141 {
142    switch (native) {
143    case HAL_PIXEL_FORMAT_RGB_565:   return DRM_FORMAT_RGB565;
144    case HAL_PIXEL_FORMAT_BGRA_8888: return DRM_FORMAT_ARGB8888;
145    case HAL_PIXEL_FORMAT_RGBA_8888: return DRM_FORMAT_ABGR8888;
146    case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
147       /*
148        * HACK: Hardcode this to RGBX_8888 as per cros_gralloc hack.
149        * TODO: Remove this once https://issuetracker.google.com/32077885 is fixed.
150        */
151    case HAL_PIXEL_FORMAT_RGBX_8888: return DRM_FORMAT_XBGR8888;
152    case HAL_PIXEL_FORMAT_RGBA_FP16: return DRM_FORMAT_ABGR16161616F;
153    case HAL_PIXEL_FORMAT_RGBA_1010102: return DRM_FORMAT_ABGR2101010;
154    default:
155       _eglLog(_EGL_WARNING, "unsupported native buffer format 0x%x", native);
156    }
157    return -1;
158 }
159 
160 /* returns # of fds, and by reference the actual fds */
161 static unsigned
get_native_buffer_fds(struct ANativeWindowBuffer * buf,int fds[3])162 get_native_buffer_fds(struct ANativeWindowBuffer *buf, int fds[3])
163 {
164    native_handle_t *handle = (native_handle_t *)buf->handle;
165 
166    if (!handle)
167       return 0;
168 
169    /*
170     * Various gralloc implementations exist, but the dma-buf fd tends
171     * to be first. Access it directly to avoid a dependency on specific
172     * gralloc versions.
173     */
174    for (int i = 0; i < handle->numFds; i++)
175       fds[i] = handle->data[i];
176 
177    return handle->numFds;
178 }
179 
180 #ifdef HAVE_DRM_GRALLOC
181 static int
get_native_buffer_name(struct ANativeWindowBuffer * buf)182 get_native_buffer_name(struct ANativeWindowBuffer *buf)
183 {
184    return gralloc_drm_get_gem_handle(buf->handle);
185 }
186 #endif /* HAVE_DRM_GRALLOC */
187 
188 static __DRIimage *
droid_create_image_from_prime_fds_yuv(_EGLDisplay * disp,struct ANativeWindowBuffer * buf,int num_fds,int fds[3])189 droid_create_image_from_prime_fds_yuv(_EGLDisplay *disp,
190                                      struct ANativeWindowBuffer *buf,
191                                      int num_fds, int fds[3])
192 {
193    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
194    struct android_ycbcr ycbcr;
195    int offsets[3];
196    int pitches[3];
197    enum chroma_order chroma_order;
198    int fourcc;
199    int ret;
200    unsigned error;
201 
202    if (!dri2_dpy->gralloc->lock_ycbcr) {
203       _eglLog(_EGL_WARNING, "Gralloc does not support lock_ycbcr");
204       return NULL;
205    }
206 
207    memset(&ycbcr, 0, sizeof(ycbcr));
208    ret = dri2_dpy->gralloc->lock_ycbcr(dri2_dpy->gralloc, buf->handle,
209                                        0, 0, 0, 0, 0, &ycbcr);
210    if (ret) {
211       /* HACK: See droid_create_image_from_prime_fds() and
212        * https://issuetracker.google.com/32077885.*/
213       if (buf->format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED)
214          return NULL;
215 
216       _eglLog(_EGL_WARNING, "gralloc->lock_ycbcr failed: %d", ret);
217       return NULL;
218    }
219    dri2_dpy->gralloc->unlock(dri2_dpy->gralloc, buf->handle);
220 
221    /* When lock_ycbcr's usage argument contains no SW_READ/WRITE flags
222     * it will return the .y/.cb/.cr pointers based on a NULL pointer,
223     * so they can be interpreted as offsets. */
224    offsets[0] = (size_t)ycbcr.y;
225    /* We assume here that all the planes are located in one DMA-buf. */
226    if ((size_t)ycbcr.cr < (size_t)ycbcr.cb) {
227       chroma_order = YCrCb;
228       offsets[1] = (size_t)ycbcr.cr;
229       offsets[2] = (size_t)ycbcr.cb;
230    } else {
231       chroma_order = YCbCr;
232       offsets[1] = (size_t)ycbcr.cb;
233       offsets[2] = (size_t)ycbcr.cr;
234    }
235 
236    /* .ystride is the line length (in bytes) of the Y plane,
237     * .cstride is the line length (in bytes) of any of the remaining
238     * Cb/Cr/CbCr planes, assumed to be the same for Cb and Cr for fully
239     * planar formats. */
240    pitches[0] = ycbcr.ystride;
241    pitches[1] = pitches[2] = ycbcr.cstride;
242 
243    /* .chroma_step is the byte distance between the same chroma channel
244     * values of subsequent pixels, assumed to be the same for Cb and Cr. */
245    fourcc = get_fourcc_yuv(buf->format, chroma_order, ycbcr.chroma_step);
246    if (fourcc == -1) {
247       _eglLog(_EGL_WARNING, "unsupported YUV format, native = %x, chroma_order = %s, chroma_step = %d",
248               buf->format, chroma_order == YCbCr ? "YCbCr" : "YCrCb", ycbcr.chroma_step);
249       return NULL;
250    }
251 
252    /*
253     * Since this is EGL_NATIVE_BUFFER_ANDROID don't assume that
254     * the single-fd case cannot happen.  So handle eithe single
255     * fd or fd-per-plane case:
256     */
257    int num_planes = (ycbcr.chroma_step == 2) ? 2 : 3;
258    if (num_fds == 1) {
259       fds[2] = fds[1] = fds[0];
260    } else {
261       assert(num_fds == num_planes);
262    }
263 
264    return dri2_dpy->image->createImageFromDmaBufs(dri2_dpy->dri_screen,
265       buf->width, buf->height, fourcc,
266       fds, num_planes, pitches, offsets,
267       EGL_ITU_REC601_EXT,
268       EGL_YUV_NARROW_RANGE_EXT,
269       EGL_YUV_CHROMA_SITING_0_EXT,
270       EGL_YUV_CHROMA_SITING_0_EXT,
271       &error,
272       NULL);
273 }
274 
275 static __DRIimage *
droid_create_image_from_prime_fds(_EGLDisplay * disp,struct ANativeWindowBuffer * buf)276 droid_create_image_from_prime_fds(_EGLDisplay *disp,
277                                   struct ANativeWindowBuffer *buf)
278 {
279    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
280    int pitches[4] = { 0 }, offsets[4] = { 0 };
281    unsigned error;
282    int num_fds;
283    int fds[3];
284 
285    num_fds = get_native_buffer_fds(buf, fds);
286    if (num_fds == 0)
287       return NULL;
288 
289    if (is_yuv(buf->format)) {
290       __DRIimage *image;
291 
292       image = droid_create_image_from_prime_fds_yuv(disp, buf, num_fds, fds);
293       /*
294        * HACK: https://issuetracker.google.com/32077885
295        * There is no API available to properly query the IMPLEMENTATION_DEFINED
296        * format. As a workaround we rely here on gralloc allocating either
297        * an arbitrary YCbCr 4:2:0 or RGBX_8888, with the latter being recognized
298        * by lock_ycbcr failing.
299        */
300       if (image || buf->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED)
301          return image;
302    }
303 
304    /*
305     * Non-YUV formats could *also* have multiple planes, such as ancillary
306     * color compression state buffer, but the rest of the code isn't ready
307     * yet to deal with modifiers:
308     */
309    assert(num_fds == 1);
310 
311    const int fourcc = get_fourcc(buf->format);
312    if (fourcc == -1) {
313       _eglError(EGL_BAD_PARAMETER, "eglCreateEGLImageKHR");
314       return NULL;
315    }
316 
317    pitches[0] = buf->stride * get_format_bpp(buf->format);
318    if (pitches[0] == 0) {
319       _eglError(EGL_BAD_PARAMETER, "eglCreateEGLImageKHR");
320       return NULL;
321    }
322 
323    return dri2_dpy->image->createImageFromDmaBufs(dri2_dpy->dri_screen,
324       buf->width, buf->height, fourcc,
325       fds, num_fds, pitches, offsets,
326       EGL_ITU_REC601_EXT,
327       EGL_YUV_NARROW_RANGE_EXT,
328       EGL_YUV_CHROMA_SITING_0_EXT,
329       EGL_YUV_CHROMA_SITING_0_EXT,
330       &error,
331       NULL);
332 }
333 
334 /* More recent CrOS gralloc has a perform op that fills out the struct below
335  * with canonical information about the buffer and its modifier, planes,
336  * offsets and strides.  If we have this, we can skip straight to
337  * createImageFromDmaBufs2() and avoid all the guessing and recalculations.
338  * This also gives us the modifier and plane offsets/strides for multiplanar
339  * compressed buffers (eg Intel CCS buffers) in order to make that work in Android.
340  */
341 
342 static const char cros_gralloc_module_name[] = "CrOS Gralloc";
343 
344 #define CROS_GRALLOC_DRM_GET_BUFFER_INFO 4
345 
346 struct cros_gralloc0_buffer_info {
347    uint32_t drm_fourcc;
348    int num_fds;
349    int fds[4];
350    uint64_t modifier;
351    int offset[4];
352    int stride[4];
353 };
354 
355 static __DRIimage *
droid_create_image_from_cros_info(_EGLDisplay * disp,struct ANativeWindowBuffer * buf)356 droid_create_image_from_cros_info(_EGLDisplay *disp,
357                                   struct ANativeWindowBuffer *buf)
358 {
359    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
360    struct cros_gralloc0_buffer_info info;
361    unsigned error;
362 
363    if (strcmp(dri2_dpy->gralloc->common.name, cros_gralloc_module_name) == 0 &&
364        dri2_dpy->gralloc->perform &&
365        dri2_dpy->image->base.version >= 15 &&
366        dri2_dpy->image->createImageFromDmaBufs2 != NULL &&
367        dri2_dpy->gralloc->perform(dri2_dpy->gralloc,
368                                   CROS_GRALLOC_DRM_GET_BUFFER_INFO,
369                                   buf->handle, &info) == 0) {
370       return dri2_dpy->image->createImageFromDmaBufs2(dri2_dpy->dri_screen,
371                                                       buf->width, buf->height,
372                                                       info.drm_fourcc, info.modifier,
373                                                       info.fds, info.num_fds,
374                                                       info.stride, info.offset,
375                                                       EGL_ITU_REC601_EXT,
376                                                       EGL_YUV_FULL_RANGE_EXT,
377                                                       EGL_YUV_CHROMA_SITING_0_EXT,
378                                                       EGL_YUV_CHROMA_SITING_0_EXT,
379                                                       &error,
380                                                       NULL);
381    }
382 
383    return NULL;
384 }
385 
386 static __DRIimage *
droid_create_image_from_native_buffer(_EGLDisplay * disp,struct ANativeWindowBuffer * buf)387 droid_create_image_from_native_buffer(_EGLDisplay *disp,
388                                       struct ANativeWindowBuffer *buf)
389 {
390    __DRIimage *dri_image;
391 
392    dri_image = droid_create_image_from_cros_info(disp, buf);
393    if (dri_image)
394       return dri_image;
395 
396    return droid_create_image_from_prime_fds(disp, buf);
397 }
398 
399 static EGLBoolean
droid_window_dequeue_buffer(struct dri2_egl_surface * dri2_surf)400 droid_window_dequeue_buffer(struct dri2_egl_surface *dri2_surf)
401 {
402    int fence_fd;
403 
404    if (dri2_surf->window->dequeueBuffer(dri2_surf->window, &dri2_surf->buffer,
405                                         &fence_fd))
406       return EGL_FALSE;
407 
408    /* If access to the buffer is controlled by a sync fence, then block on the
409     * fence.
410     *
411     * It may be more performant to postpone blocking until there is an
412     * immediate need to write to the buffer. But doing so would require adding
413     * hooks to the DRI2 loader.
414     *
415     * From the ANativeWindow::dequeueBuffer documentation:
416     *
417     *    The libsync fence file descriptor returned in the int pointed to by
418     *    the fenceFd argument will refer to the fence that must signal
419     *    before the dequeued buffer may be written to.  A value of -1
420     *    indicates that the caller may access the buffer immediately without
421     *    waiting on a fence.  If a valid file descriptor is returned (i.e.
422     *    any value except -1) then the caller is responsible for closing the
423     *    file descriptor.
424     */
425     if (fence_fd >= 0) {
426        /* From the SYNC_IOC_WAIT documentation in <linux/sync.h>:
427         *
428         *    Waits indefinitely if timeout < 0.
429         */
430         int timeout = -1;
431         sync_wait(fence_fd, timeout);
432         close(fence_fd);
433    }
434 
435    /* Record all the buffers created by ANativeWindow and update back buffer
436     * for updating buffer's age in swap_buffers.
437     */
438    EGLBoolean updated = EGL_FALSE;
439    for (int i = 0; i < dri2_surf->color_buffers_count; i++) {
440       if (!dri2_surf->color_buffers[i].buffer) {
441          dri2_surf->color_buffers[i].buffer = dri2_surf->buffer;
442       }
443       if (dri2_surf->color_buffers[i].buffer == dri2_surf->buffer) {
444          dri2_surf->back = &dri2_surf->color_buffers[i];
445          updated = EGL_TRUE;
446          break;
447       }
448    }
449 
450    if (!updated) {
451       /* In case of all the buffers were recreated by ANativeWindow, reset
452        * the color_buffers
453        */
454       for (int i = 0; i < dri2_surf->color_buffers_count; i++) {
455          dri2_surf->color_buffers[i].buffer = NULL;
456          dri2_surf->color_buffers[i].age = 0;
457       }
458       dri2_surf->color_buffers[0].buffer = dri2_surf->buffer;
459       dri2_surf->back = &dri2_surf->color_buffers[0];
460    }
461 
462    return EGL_TRUE;
463 }
464 
465 static EGLBoolean
droid_window_enqueue_buffer(_EGLDisplay * disp,struct dri2_egl_surface * dri2_surf)466 droid_window_enqueue_buffer(_EGLDisplay *disp, struct dri2_egl_surface *dri2_surf)
467 {
468    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
469 
470    /* To avoid blocking other EGL calls, release the display mutex before
471     * we enter droid_window_enqueue_buffer() and re-acquire the mutex upon
472     * return.
473     */
474    mtx_unlock(&disp->Mutex);
475 
476    /* Queue the buffer with stored out fence fd. The ANativeWindow or buffer
477     * consumer may choose to wait for the fence to signal before accessing
478     * it. If fence fd value is -1, buffer can be accessed by consumer
479     * immediately. Consumer or application shouldn't rely on timestamp
480     * associated with fence if the fence fd is -1.
481     *
482     * Ownership of fd is transferred to consumer after queueBuffer and the
483     * consumer is responsible for closing it. Caller must not use the fd
484     * after passing it to queueBuffer.
485     */
486    int fence_fd = dri2_surf->out_fence_fd;
487    dri2_surf->out_fence_fd = -1;
488    dri2_surf->window->queueBuffer(dri2_surf->window, dri2_surf->buffer,
489                                   fence_fd);
490 
491    dri2_surf->buffer = NULL;
492    dri2_surf->back = NULL;
493 
494    mtx_lock(&disp->Mutex);
495 
496    if (dri2_surf->dri_image_back) {
497       dri2_dpy->image->destroyImage(dri2_surf->dri_image_back);
498       dri2_surf->dri_image_back = NULL;
499    }
500 
501    return EGL_TRUE;
502 }
503 
504 static void
droid_window_cancel_buffer(struct dri2_egl_surface * dri2_surf)505 droid_window_cancel_buffer(struct dri2_egl_surface *dri2_surf)
506 {
507    int ret;
508    int fence_fd = dri2_surf->out_fence_fd;
509 
510    dri2_surf->out_fence_fd = -1;
511    ret = dri2_surf->window->cancelBuffer(dri2_surf->window,
512                                          dri2_surf->buffer, fence_fd);
513    dri2_surf->buffer = NULL;
514    if (ret < 0) {
515       _eglLog(_EGL_WARNING, "ANativeWindow::cancelBuffer failed");
516       dri2_surf->base.Lost = EGL_TRUE;
517    }
518 }
519 
520 static bool
droid_set_shared_buffer_mode(_EGLDisplay * disp,_EGLSurface * surf,bool mode)521 droid_set_shared_buffer_mode(_EGLDisplay *disp, _EGLSurface *surf, bool mode)
522 {
523 #if ANDROID_API_LEVEL >= 24
524    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
525    struct ANativeWindow *window = dri2_surf->window;
526 
527    assert(surf->Type == EGL_WINDOW_BIT);
528    assert(_eglSurfaceHasMutableRenderBuffer(&dri2_surf->base));
529 
530    _eglLog(_EGL_DEBUG, "%s: mode=%d", __func__, mode);
531 
532    if (native_window_set_shared_buffer_mode(window, mode)) {
533       _eglLog(_EGL_WARNING, "failed native_window_set_shared_buffer_mode"
534               "(window=%p, mode=%d)", window, mode);
535       return false;
536    }
537 
538    return true;
539 #else
540    _eglLog(_EGL_FATAL, "%s:%d: internal error: unreachable", __FILE__, __LINE__);
541    return false;
542 #endif
543 }
544 
545 static _EGLSurface *
droid_create_surface(_EGLDisplay * disp,EGLint type,_EGLConfig * conf,void * native_window,const EGLint * attrib_list)546 droid_create_surface(_EGLDisplay *disp, EGLint type, _EGLConfig *conf,
547                      void *native_window, const EGLint *attrib_list)
548 {
549    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
550    struct dri2_egl_config *dri2_conf = dri2_egl_config(conf);
551    struct dri2_egl_surface *dri2_surf;
552    struct ANativeWindow *window = native_window;
553    const __DRIconfig *config;
554 
555    dri2_surf = calloc(1, sizeof *dri2_surf);
556    if (!dri2_surf) {
557       _eglError(EGL_BAD_ALLOC, "droid_create_surface");
558       return NULL;
559    }
560 
561    if (!dri2_init_surface(&dri2_surf->base, disp, type, conf, attrib_list,
562                           true, native_window))
563       goto cleanup_surface;
564 
565    if (type == EGL_WINDOW_BIT) {
566       int format;
567       int buffer_count;
568       int min_buffer_count, max_buffer_count;
569 
570       /* Prefer triple buffering for performance reasons. */
571       const int preferred_buffer_count = 3;
572 
573       if (window->common.magic != ANDROID_NATIVE_WINDOW_MAGIC) {
574          _eglError(EGL_BAD_NATIVE_WINDOW, "droid_create_surface");
575          goto cleanup_surface;
576       }
577       if (window->query(window, NATIVE_WINDOW_FORMAT, &format)) {
578          _eglError(EGL_BAD_NATIVE_WINDOW, "droid_create_surface");
579          goto cleanup_surface;
580       }
581 
582       /* Query ANativeWindow for MIN_UNDEQUEUED_BUFFER, minimum amount
583        * of undequeued buffers.
584        */
585       if (window->query(window, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
586                         &min_buffer_count)) {
587          _eglError(EGL_BAD_NATIVE_WINDOW, "droid_create_surface");
588          goto cleanup_surface;
589       }
590 
591       /* Query for maximum buffer count, application can set this
592        * to limit the total amount of buffers.
593        */
594       if (window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
595                         &max_buffer_count)) {
596          _eglError(EGL_BAD_NATIVE_WINDOW, "droid_create_surface");
597          goto cleanup_surface;
598       }
599 
600       /* Clamp preferred between minimum (min undequeued + 1 dequeued)
601        * and maximum.
602        */
603       buffer_count = CLAMP(preferred_buffer_count, min_buffer_count + 1,
604                            max_buffer_count);
605 
606       if (native_window_set_buffer_count(window, buffer_count)) {
607          _eglError(EGL_BAD_NATIVE_WINDOW, "droid_create_surface");
608          goto cleanup_surface;
609       }
610       dri2_surf->color_buffers = calloc(buffer_count,
611                                         sizeof(*dri2_surf->color_buffers));
612       if (!dri2_surf->color_buffers) {
613          _eglError(EGL_BAD_ALLOC, "droid_create_surface");
614          goto cleanup_surface;
615       }
616       dri2_surf->color_buffers_count = buffer_count;
617 
618       if (format != dri2_conf->base.NativeVisualID) {
619          _eglLog(_EGL_WARNING, "Native format mismatch: 0x%x != 0x%x",
620                format, dri2_conf->base.NativeVisualID);
621       }
622 
623       window->query(window, NATIVE_WINDOW_WIDTH, &dri2_surf->base.Width);
624       window->query(window, NATIVE_WINDOW_HEIGHT, &dri2_surf->base.Height);
625 
626       uint32_t usage = strcmp(dri2_dpy->driver_name, "kms_swrast") == 0
627             ? GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN
628             : GRALLOC_USAGE_HW_RENDER;
629       native_window_set_usage(window, usage);
630    }
631 
632    config = dri2_get_dri_config(dri2_conf, type,
633                                 dri2_surf->base.GLColorspace);
634    if (!config) {
635       _eglError(EGL_BAD_MATCH, "Unsupported surfacetype/colorspace configuration");
636       goto cleanup_surface;
637    }
638 
639    if (!dri2_create_drawable(dri2_dpy, config, dri2_surf, dri2_surf))
640       goto cleanup_surface;
641 
642    if (window) {
643       window->common.incRef(&window->common);
644       dri2_surf->window = window;
645    }
646 
647    return &dri2_surf->base;
648 
649 cleanup_surface:
650    if (dri2_surf->color_buffers_count)
651       free(dri2_surf->color_buffers);
652    free(dri2_surf);
653 
654    return NULL;
655 }
656 
657 static _EGLSurface *
droid_create_window_surface(_EGLDisplay * disp,_EGLConfig * conf,void * native_window,const EGLint * attrib_list)658 droid_create_window_surface(_EGLDisplay *disp, _EGLConfig *conf,
659                             void *native_window, const EGLint *attrib_list)
660 {
661    return droid_create_surface(disp, EGL_WINDOW_BIT, conf,
662                                native_window, attrib_list);
663 }
664 
665 static _EGLSurface *
droid_create_pbuffer_surface(_EGLDisplay * disp,_EGLConfig * conf,const EGLint * attrib_list)666 droid_create_pbuffer_surface(_EGLDisplay *disp, _EGLConfig *conf,
667                              const EGLint *attrib_list)
668 {
669    return droid_create_surface(disp, EGL_PBUFFER_BIT, conf,
670                                NULL, attrib_list);
671 }
672 
673 static EGLBoolean
droid_destroy_surface(_EGLDisplay * disp,_EGLSurface * surf)674 droid_destroy_surface(_EGLDisplay *disp, _EGLSurface *surf)
675 {
676    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
677    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
678 
679    dri2_egl_surface_free_local_buffers(dri2_surf);
680 
681    if (dri2_surf->base.Type == EGL_WINDOW_BIT) {
682       if (dri2_surf->buffer)
683          droid_window_cancel_buffer(dri2_surf);
684 
685       dri2_surf->window->common.decRef(&dri2_surf->window->common);
686    }
687 
688    if (dri2_surf->dri_image_back) {
689       _eglLog(_EGL_DEBUG, "%s : %d : destroy dri_image_back", __func__, __LINE__);
690       dri2_dpy->image->destroyImage(dri2_surf->dri_image_back);
691       dri2_surf->dri_image_back = NULL;
692    }
693 
694    if (dri2_surf->dri_image_front) {
695       _eglLog(_EGL_DEBUG, "%s : %d : destroy dri_image_front", __func__, __LINE__);
696       dri2_dpy->image->destroyImage(dri2_surf->dri_image_front);
697       dri2_surf->dri_image_front = NULL;
698    }
699 
700    dri2_dpy->core->destroyDrawable(dri2_surf->dri_drawable);
701 
702    dri2_fini_surface(surf);
703    free(dri2_surf->color_buffers);
704    free(dri2_surf);
705 
706    return EGL_TRUE;
707 }
708 
709 static EGLBoolean
droid_swap_interval(_EGLDisplay * disp,_EGLSurface * surf,EGLint interval)710 droid_swap_interval(_EGLDisplay *disp, _EGLSurface *surf, EGLint interval)
711 {
712    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
713    struct ANativeWindow *window = dri2_surf->window;
714 
715    if (window->setSwapInterval(window, interval))
716       return EGL_FALSE;
717 
718    surf->SwapInterval = interval;
719    return EGL_TRUE;
720 }
721 
722 static int
update_buffers(struct dri2_egl_surface * dri2_surf)723 update_buffers(struct dri2_egl_surface *dri2_surf)
724 {
725    if (dri2_surf->base.Lost)
726       return -1;
727 
728    if (dri2_surf->base.Type != EGL_WINDOW_BIT)
729       return 0;
730 
731    /* try to dequeue the next back buffer */
732    if (!dri2_surf->buffer && !droid_window_dequeue_buffer(dri2_surf)) {
733       _eglLog(_EGL_WARNING, "Could not dequeue buffer from native window");
734       dri2_surf->base.Lost = EGL_TRUE;
735       return -1;
736    }
737 
738    /* free outdated buffers and update the surface size */
739    if (dri2_surf->base.Width != dri2_surf->buffer->width ||
740        dri2_surf->base.Height != dri2_surf->buffer->height) {
741       dri2_egl_surface_free_local_buffers(dri2_surf);
742       dri2_surf->base.Width = dri2_surf->buffer->width;
743       dri2_surf->base.Height = dri2_surf->buffer->height;
744    }
745 
746    return 0;
747 }
748 
749 static int
get_front_bo(struct dri2_egl_surface * dri2_surf,unsigned int format)750 get_front_bo(struct dri2_egl_surface *dri2_surf, unsigned int format)
751 {
752    struct dri2_egl_display *dri2_dpy =
753       dri2_egl_display(dri2_surf->base.Resource.Display);
754 
755    if (dri2_surf->dri_image_front)
756       return 0;
757 
758    if (dri2_surf->base.Type == EGL_WINDOW_BIT) {
759       /* According current EGL spec, front buffer rendering
760        * for window surface is not supported now.
761        * and mesa doesn't have the implementation of this case.
762        * Add warning message, but not treat it as error.
763        */
764       _eglLog(_EGL_DEBUG, "DRI driver requested unsupported front buffer for window surface");
765    } else if (dri2_surf->base.Type == EGL_PBUFFER_BIT) {
766       dri2_surf->dri_image_front =
767           dri2_dpy->image->createImage(dri2_dpy->dri_screen,
768                                               dri2_surf->base.Width,
769                                               dri2_surf->base.Height,
770                                               format,
771                                               0,
772                                               dri2_surf);
773       if (!dri2_surf->dri_image_front) {
774          _eglLog(_EGL_WARNING, "dri2_image_front allocation failed");
775          return -1;
776       }
777    }
778 
779    return 0;
780 }
781 
782 static int
get_back_bo(struct dri2_egl_surface * dri2_surf)783 get_back_bo(struct dri2_egl_surface *dri2_surf)
784 {
785    _EGLDisplay *disp = dri2_surf->base.Resource.Display;
786 
787    if (dri2_surf->dri_image_back)
788       return 0;
789 
790    if (dri2_surf->base.Type == EGL_WINDOW_BIT) {
791       if (!dri2_surf->buffer) {
792          _eglLog(_EGL_WARNING, "Could not get native buffer");
793          return -1;
794       }
795 
796       dri2_surf->dri_image_back =
797          droid_create_image_from_native_buffer(disp, dri2_surf->buffer);
798       if (!dri2_surf->dri_image_back) {
799          _eglLog(_EGL_WARNING, "failed to create DRI image from FD");
800          return -1;
801       }
802    } else if (dri2_surf->base.Type == EGL_PBUFFER_BIT) {
803       /* The EGL 1.5 spec states that pbuffers are single-buffered. Specifically,
804        * the spec states that they have a back buffer but no front buffer, in
805        * contrast to pixmaps, which have a front buffer but no back buffer.
806        *
807        * Single-buffered surfaces with no front buffer confuse Mesa; so we deviate
808        * from the spec, following the precedent of Mesa's EGL X11 platform. The
809        * X11 platform correctly assigns pbuffers to single-buffered configs, but
810        * assigns the pbuffer a front buffer instead of a back buffer.
811        *
812        * Pbuffers in the X11 platform mostly work today, so let's just copy its
813        * behavior instead of trying to fix (and hence potentially breaking) the
814        * world.
815        */
816       _eglLog(_EGL_DEBUG, "DRI driver requested unsupported back buffer for pbuffer surface");
817    }
818 
819    return 0;
820 }
821 
822 /* Some drivers will pass multiple bits in buffer_mask.
823  * For such case, will go through all the bits, and
824  * will not return error when unsupported buffer is requested, only
825  * return error when the allocation for supported buffer failed.
826  */
827 static int
droid_image_get_buffers(__DRIdrawable * driDrawable,unsigned int format,uint32_t * stamp,void * loaderPrivate,uint32_t buffer_mask,struct __DRIimageList * images)828 droid_image_get_buffers(__DRIdrawable *driDrawable,
829                   unsigned int format,
830                   uint32_t *stamp,
831                   void *loaderPrivate,
832                   uint32_t buffer_mask,
833                   struct __DRIimageList *images)
834 {
835    struct dri2_egl_surface *dri2_surf = loaderPrivate;
836 
837    images->image_mask = 0;
838    images->front = NULL;
839    images->back = NULL;
840 
841    if (update_buffers(dri2_surf) < 0)
842       return 0;
843 
844    if (_eglSurfaceInSharedBufferMode(&dri2_surf->base)) {
845       if (get_back_bo(dri2_surf) < 0)
846          return 0;
847 
848       /* We have dri_image_back because this is a window surface and
849        * get_back_bo() succeeded.
850        */
851       assert(dri2_surf->dri_image_back);
852       images->back = dri2_surf->dri_image_back;
853       images->image_mask |= __DRI_IMAGE_BUFFER_SHARED;
854 
855       /* There exists no accompanying back nor front buffer. */
856       return 1;
857    }
858 
859    if (buffer_mask & __DRI_IMAGE_BUFFER_FRONT) {
860       if (get_front_bo(dri2_surf, format) < 0)
861          return 0;
862 
863       if (dri2_surf->dri_image_front) {
864          images->front = dri2_surf->dri_image_front;
865          images->image_mask |= __DRI_IMAGE_BUFFER_FRONT;
866       }
867    }
868 
869    if (buffer_mask & __DRI_IMAGE_BUFFER_BACK) {
870       if (get_back_bo(dri2_surf) < 0)
871          return 0;
872 
873       if (dri2_surf->dri_image_back) {
874          images->back = dri2_surf->dri_image_back;
875          images->image_mask |= __DRI_IMAGE_BUFFER_BACK;
876       }
877    }
878 
879    return 1;
880 }
881 
882 static EGLint
droid_query_buffer_age(_EGLDisplay * disp,_EGLSurface * surface)883 droid_query_buffer_age(_EGLDisplay *disp, _EGLSurface *surface)
884 {
885    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surface);
886 
887    if (update_buffers(dri2_surf) < 0) {
888       _eglError(EGL_BAD_ALLOC, "droid_query_buffer_age");
889       return -1;
890    }
891 
892    return dri2_surf->back ? dri2_surf->back->age : 0;
893 }
894 
895 static EGLBoolean
droid_swap_buffers(_EGLDisplay * disp,_EGLSurface * draw)896 droid_swap_buffers(_EGLDisplay *disp, _EGLSurface *draw)
897 {
898    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
899    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(draw);
900    const bool has_mutable_rb = _eglSurfaceHasMutableRenderBuffer(draw);
901 
902    /* From the EGL_KHR_mutable_render_buffer spec (v12):
903     *
904     *    If surface is a single-buffered window, pixmap, or pbuffer surface
905     *    for which there is no pending change to the EGL_RENDER_BUFFER
906     *    attribute, eglSwapBuffers has no effect.
907     */
908    if (has_mutable_rb &&
909        draw->RequestedRenderBuffer == EGL_SINGLE_BUFFER &&
910        draw->ActiveRenderBuffer == EGL_SINGLE_BUFFER) {
911       _eglLog(_EGL_DEBUG, "%s: remain in shared buffer mode", __func__);
912       return EGL_TRUE;
913    }
914 
915    for (int i = 0; i < dri2_surf->color_buffers_count; i++) {
916       if (dri2_surf->color_buffers[i].age > 0)
917          dri2_surf->color_buffers[i].age++;
918    }
919 
920    /* "XXX: we don't use get_back_bo() since it causes regressions in
921     * several dEQP tests.
922     */
923    if (dri2_surf->back)
924       dri2_surf->back->age = 1;
925 
926    dri2_flush_drawable_for_swapbuffers(disp, draw);
927 
928    /* dri2_surf->buffer can be null even when no error has occured. For
929     * example, if the user has called no GL rendering commands since the
930     * previous eglSwapBuffers, then the driver may have not triggered
931     * a callback to ANativeWindow::dequeueBuffer, in which case
932     * dri2_surf->buffer remains null.
933     */
934    if (dri2_surf->buffer)
935       droid_window_enqueue_buffer(disp, dri2_surf);
936 
937    dri2_dpy->flush->invalidate(dri2_surf->dri_drawable);
938 
939    /* Update the shared buffer mode */
940    if (has_mutable_rb &&
941        draw->ActiveRenderBuffer != draw->RequestedRenderBuffer) {
942        bool mode = (draw->RequestedRenderBuffer == EGL_SINGLE_BUFFER);
943       _eglLog(_EGL_DEBUG, "%s: change to shared buffer mode %d",
944               __func__, mode);
945 
946       if (!droid_set_shared_buffer_mode(disp, draw, mode))
947          return EGL_FALSE;
948       draw->ActiveRenderBuffer = draw->RequestedRenderBuffer;
949    }
950 
951    return EGL_TRUE;
952 }
953 
954 #ifdef HAVE_DRM_GRALLOC
get_format(int format)955 static int get_format(int format)
956 {
957    switch (format) {
958    case HAL_PIXEL_FORMAT_BGRA_8888: return __DRI_IMAGE_FORMAT_ARGB8888;
959    case HAL_PIXEL_FORMAT_RGB_565:   return __DRI_IMAGE_FORMAT_RGB565;
960    case HAL_PIXEL_FORMAT_RGBA_8888: return __DRI_IMAGE_FORMAT_ABGR8888;
961    case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
962       /*
963        * HACK: Hardcode this to RGBX_8888 as per cros_gralloc hack.
964        * TODO: Revert this once https://issuetracker.google.com/32077885 is fixed.
965        */
966    case HAL_PIXEL_FORMAT_RGBX_8888: return __DRI_IMAGE_FORMAT_XBGR8888;
967    case HAL_PIXEL_FORMAT_RGBA_FP16: return __DRI_IMAGE_FORMAT_ABGR16161616F;
968    case HAL_PIXEL_FORMAT_RGBA_1010102: return __DRI_IMAGE_FORMAT_ABGR2101010;
969    default:
970       _eglLog(_EGL_WARNING, "unsupported native buffer format 0x%x", format);
971    }
972    return -1;
973 }
974 
975 static __DRIimage *
droid_create_image_from_name(_EGLDisplay * disp,struct ANativeWindowBuffer * buf)976 droid_create_image_from_name(_EGLDisplay *disp,
977                              struct ANativeWindowBuffer *buf)
978 {
979    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
980    int name;
981    int format;
982 
983    name = get_native_buffer_name(buf);
984    if (!name) {
985       _eglError(EGL_BAD_PARAMETER, "eglCreateEGLImageKHR");
986       return NULL;
987    }
988 
989    format = get_format(buf->format);
990    if (format == -1)
991        return NULL;
992 
993    return
994       dri2_dpy->image->createImageFromName(dri2_dpy->dri_screen,
995 					   buf->width,
996 					   buf->height,
997 					   format,
998 					   name,
999 					   buf->stride,
1000 					   NULL);
1001 }
1002 #endif /* HAVE_DRM_GRALLOC */
1003 
1004 static EGLBoolean
droid_query_surface(_EGLDisplay * disp,_EGLSurface * surf,EGLint attribute,EGLint * value)1005 droid_query_surface(_EGLDisplay *disp, _EGLSurface *surf,
1006                     EGLint attribute, EGLint *value)
1007 {
1008    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1009    switch (attribute) {
1010       case EGL_WIDTH:
1011          if (dri2_surf->base.Type == EGL_WINDOW_BIT && dri2_surf->window) {
1012             dri2_surf->window->query(dri2_surf->window,
1013                                      NATIVE_WINDOW_DEFAULT_WIDTH, value);
1014             return EGL_TRUE;
1015          }
1016          break;
1017       case EGL_HEIGHT:
1018          if (dri2_surf->base.Type == EGL_WINDOW_BIT && dri2_surf->window) {
1019             dri2_surf->window->query(dri2_surf->window,
1020                                      NATIVE_WINDOW_DEFAULT_HEIGHT, value);
1021             return EGL_TRUE;
1022          }
1023          break;
1024       default:
1025          break;
1026    }
1027    return _eglQuerySurface(disp, surf, attribute, value);
1028 }
1029 
1030 static _EGLImage *
dri2_create_image_android_native_buffer(_EGLDisplay * disp,_EGLContext * ctx,struct ANativeWindowBuffer * buf)1031 dri2_create_image_android_native_buffer(_EGLDisplay *disp,
1032                                         _EGLContext *ctx,
1033                                         struct ANativeWindowBuffer *buf)
1034 {
1035    if (ctx != NULL) {
1036       /* From the EGL_ANDROID_image_native_buffer spec:
1037        *
1038        *     * If <target> is EGL_NATIVE_BUFFER_ANDROID and <ctx> is not
1039        *       EGL_NO_CONTEXT, the error EGL_BAD_CONTEXT is generated.
1040        */
1041       _eglError(EGL_BAD_CONTEXT, "eglCreateEGLImageKHR: for "
1042                 "EGL_NATIVE_BUFFER_ANDROID, the context must be "
1043                 "EGL_NO_CONTEXT");
1044       return NULL;
1045    }
1046 
1047    if (!buf || buf->common.magic != ANDROID_NATIVE_BUFFER_MAGIC ||
1048        buf->common.version != sizeof(*buf)) {
1049       _eglError(EGL_BAD_PARAMETER, "eglCreateEGLImageKHR");
1050       return NULL;
1051    }
1052 
1053    __DRIimage *dri_image =
1054       droid_create_image_from_native_buffer(disp, buf);
1055 
1056 #ifdef HAVE_DRM_GRALLOC
1057    if (dri_image == NULL)
1058       dri_image = droid_create_image_from_name(disp, buf);
1059 #endif
1060 
1061    if (dri_image)
1062       return dri2_create_image_from_dri(disp, dri_image);
1063 
1064    return NULL;
1065 }
1066 
1067 static _EGLImage *
droid_create_image_khr(_EGLDisplay * disp,_EGLContext * ctx,EGLenum target,EGLClientBuffer buffer,const EGLint * attr_list)1068 droid_create_image_khr(_EGLDisplay *disp, _EGLContext *ctx, EGLenum target,
1069                        EGLClientBuffer buffer, const EGLint *attr_list)
1070 {
1071    switch (target) {
1072    case EGL_NATIVE_BUFFER_ANDROID:
1073       return dri2_create_image_android_native_buffer(disp, ctx,
1074             (struct ANativeWindowBuffer *) buffer);
1075    default:
1076       return dri2_create_image_khr(disp, ctx, target, buffer, attr_list);
1077    }
1078 }
1079 
1080 static void
droid_flush_front_buffer(__DRIdrawable * driDrawable,void * loaderPrivate)1081 droid_flush_front_buffer(__DRIdrawable * driDrawable, void *loaderPrivate)
1082 {
1083 }
1084 
1085 #ifdef HAVE_DRM_GRALLOC
1086 static int
droid_get_buffers_parse_attachments(struct dri2_egl_surface * dri2_surf,unsigned int * attachments,int count)1087 droid_get_buffers_parse_attachments(struct dri2_egl_surface *dri2_surf,
1088                                     unsigned int *attachments, int count)
1089 {
1090    int num_buffers = 0;
1091 
1092    /* fill dri2_surf->buffers */
1093    for (int i = 0; i < count * 2; i += 2) {
1094       __DRIbuffer *buf, *local;
1095 
1096       assert(num_buffers < ARRAY_SIZE(dri2_surf->buffers));
1097       buf = &dri2_surf->buffers[num_buffers];
1098 
1099       switch (attachments[i]) {
1100       case __DRI_BUFFER_BACK_LEFT:
1101          if (dri2_surf->base.Type == EGL_WINDOW_BIT) {
1102             buf->attachment = attachments[i];
1103             buf->name = get_native_buffer_name(dri2_surf->buffer);
1104             buf->cpp = get_format_bpp(dri2_surf->buffer->format);
1105             buf->pitch = dri2_surf->buffer->stride * buf->cpp;
1106             buf->flags = 0;
1107 
1108             if (buf->name)
1109                num_buffers++;
1110 
1111             break;
1112          }
1113          /* fall through for pbuffers */
1114       case __DRI_BUFFER_DEPTH:
1115       case __DRI_BUFFER_STENCIL:
1116       case __DRI_BUFFER_ACCUM:
1117       case __DRI_BUFFER_DEPTH_STENCIL:
1118       case __DRI_BUFFER_HIZ:
1119          local = dri2_egl_surface_alloc_local_buffer(dri2_surf,
1120                attachments[i], attachments[i + 1]);
1121 
1122          if (local) {
1123             *buf = *local;
1124             num_buffers++;
1125          }
1126          break;
1127       case __DRI_BUFFER_FRONT_LEFT:
1128       case __DRI_BUFFER_FRONT_RIGHT:
1129       case __DRI_BUFFER_FAKE_FRONT_LEFT:
1130       case __DRI_BUFFER_FAKE_FRONT_RIGHT:
1131       case __DRI_BUFFER_BACK_RIGHT:
1132       default:
1133          /* no front or right buffers */
1134          break;
1135       }
1136    }
1137 
1138    return num_buffers;
1139 }
1140 
1141 static __DRIbuffer *
droid_get_buffers_with_format(__DRIdrawable * driDrawable,int * width,int * height,unsigned int * attachments,int count,int * out_count,void * loaderPrivate)1142 droid_get_buffers_with_format(__DRIdrawable * driDrawable,
1143 			     int *width, int *height,
1144 			     unsigned int *attachments, int count,
1145 			     int *out_count, void *loaderPrivate)
1146 {
1147    struct dri2_egl_surface *dri2_surf = loaderPrivate;
1148 
1149    if (update_buffers(dri2_surf) < 0)
1150       return NULL;
1151 
1152    *out_count = droid_get_buffers_parse_attachments(dri2_surf, attachments, count);
1153 
1154    if (width)
1155       *width = dri2_surf->base.Width;
1156    if (height)
1157       *height = dri2_surf->base.Height;
1158 
1159    return dri2_surf->buffers;
1160 }
1161 #endif /* HAVE_DRM_GRALLOC */
1162 
1163 static unsigned
droid_get_capability(void * loaderPrivate,enum dri_loader_cap cap)1164 droid_get_capability(void *loaderPrivate, enum dri_loader_cap cap)
1165 {
1166    /* Note: loaderPrivate is _EGLDisplay* */
1167    switch (cap) {
1168    case DRI_LOADER_CAP_RGBA_ORDERING:
1169       return 1;
1170    default:
1171       return 0;
1172    }
1173 }
1174 
1175 static EGLBoolean
droid_add_configs_for_visuals(_EGLDisplay * disp)1176 droid_add_configs_for_visuals(_EGLDisplay *disp)
1177 {
1178    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1179    static const struct {
1180       int format;
1181       int rgba_shifts[4];
1182       unsigned int rgba_sizes[4];
1183    } visuals[] = {
1184       { HAL_PIXEL_FORMAT_RGBA_8888, { 0, 8, 16, 24 }, { 8, 8, 8, 8 } },
1185       { HAL_PIXEL_FORMAT_RGBX_8888, { 0, 8, 16, -1 }, { 8, 8, 8, 0 } },
1186       { HAL_PIXEL_FORMAT_RGB_565,   { 11, 5, 0, -1 }, { 5, 6, 5, 0 } },
1187       /* This must be after HAL_PIXEL_FORMAT_RGBA_8888, we only keep BGRA
1188        * visual if it turns out RGBA visual is not available.
1189        */
1190       { HAL_PIXEL_FORMAT_BGRA_8888, { 16, 8, 0, 24 }, { 8, 8, 8, 8 } },
1191    };
1192 
1193    unsigned int format_count[ARRAY_SIZE(visuals)] = { 0 };
1194    int config_count = 0;
1195 
1196    /* The nesting of loops is significant here. Also significant is the order
1197     * of the HAL pixel formats. Many Android apps (such as Google's official
1198     * NDK GLES2 example app), and even portions the core framework code (such
1199     * as SystemServiceManager in Nougat), incorrectly choose their EGLConfig.
1200     * They neglect to match the EGLConfig's EGL_NATIVE_VISUAL_ID against the
1201     * window's native format, and instead choose the first EGLConfig whose
1202     * channel sizes match those of the native window format while ignoring the
1203     * channel *ordering*.
1204     *
1205     * We can detect such buggy clients in logcat when they call
1206     * eglCreateSurface, by detecting the mismatch between the EGLConfig's
1207     * format and the window's format.
1208     *
1209     * As a workaround, we generate EGLConfigs such that all EGLConfigs for HAL
1210     * pixel format i precede those for HAL pixel format i+1. In my
1211     * (chadversary) testing on Android Nougat, this was good enough to pacify
1212     * the buggy clients.
1213     */
1214    bool has_rgba = false;
1215    for (int i = 0; i < ARRAY_SIZE(visuals); i++) {
1216       /* Only enable BGRA configs when RGBA is not available. BGRA configs are
1217        * buggy on stock Android.
1218        */
1219       if (visuals[i].format == HAL_PIXEL_FORMAT_BGRA_8888 && has_rgba)
1220          continue;
1221       for (int j = 0; dri2_dpy->driver_configs[j]; j++) {
1222          const EGLint surface_type = EGL_WINDOW_BIT | EGL_PBUFFER_BIT;
1223 
1224          const EGLint config_attrs[] = {
1225            EGL_NATIVE_VISUAL_ID,   visuals[i].format,
1226            EGL_NATIVE_VISUAL_TYPE, visuals[i].format,
1227            EGL_FRAMEBUFFER_TARGET_ANDROID, EGL_TRUE,
1228            EGL_RECORDABLE_ANDROID, EGL_TRUE,
1229            EGL_NONE
1230          };
1231 
1232          struct dri2_egl_config *dri2_conf =
1233             dri2_add_config(disp, dri2_dpy->driver_configs[j],
1234                             config_count + 1, surface_type, config_attrs,
1235                             visuals[i].rgba_shifts, visuals[i].rgba_sizes);
1236          if (dri2_conf) {
1237             if (dri2_conf->base.ConfigID == config_count + 1)
1238                config_count++;
1239             format_count[i]++;
1240          }
1241       }
1242       if (visuals[i].format == HAL_PIXEL_FORMAT_RGBA_8888 && format_count[i])
1243          has_rgba = true;
1244    }
1245 
1246    for (int i = 0; i < ARRAY_SIZE(format_count); i++) {
1247       if (!format_count[i]) {
1248          _eglLog(_EGL_DEBUG, "No DRI config supports native format 0x%x",
1249                  visuals[i].format);
1250       }
1251    }
1252 
1253    return (config_count != 0);
1254 }
1255 
1256 static const struct dri2_egl_display_vtbl droid_display_vtbl = {
1257    .authenticate = NULL,
1258    .create_window_surface = droid_create_window_surface,
1259    .create_pbuffer_surface = droid_create_pbuffer_surface,
1260    .destroy_surface = droid_destroy_surface,
1261    .create_image = droid_create_image_khr,
1262    .swap_buffers = droid_swap_buffers,
1263    .swap_interval = droid_swap_interval,
1264    .query_buffer_age = droid_query_buffer_age,
1265    .query_surface = droid_query_surface,
1266    .get_dri_drawable = dri2_surface_get_dri_drawable,
1267    .set_shared_buffer_mode = droid_set_shared_buffer_mode,
1268 };
1269 
1270 #ifdef HAVE_DRM_GRALLOC
1271 static const __DRIdri2LoaderExtension droid_dri2_loader_extension = {
1272    .base = { __DRI_DRI2_LOADER, 4 },
1273 
1274    .getBuffers           = NULL,
1275    .flushFrontBuffer     = droid_flush_front_buffer,
1276    .getBuffersWithFormat = droid_get_buffers_with_format,
1277    .getCapability        = droid_get_capability,
1278 };
1279 
1280 static const __DRIextension *droid_dri2_loader_extensions[] = {
1281    &droid_dri2_loader_extension.base,
1282    &image_lookup_extension.base,
1283    &use_invalidate.base,
1284    /* No __DRI_MUTABLE_RENDER_BUFFER_LOADER because it requires
1285     * __DRI_IMAGE_LOADER.
1286     */
1287    NULL,
1288 };
1289 #endif /* HAVE_DRM_GRALLOC */
1290 
1291 static const __DRIimageLoaderExtension droid_image_loader_extension = {
1292    .base = { __DRI_IMAGE_LOADER, 2 },
1293 
1294    .getBuffers          = droid_image_get_buffers,
1295    .flushFrontBuffer    = droid_flush_front_buffer,
1296    .getCapability       = droid_get_capability,
1297 };
1298 
1299 static void
droid_display_shared_buffer(__DRIdrawable * driDrawable,int fence_fd,void * loaderPrivate)1300 droid_display_shared_buffer(__DRIdrawable *driDrawable, int fence_fd,
1301                             void *loaderPrivate)
1302 {
1303    struct dri2_egl_surface *dri2_surf = loaderPrivate;
1304    struct ANativeWindowBuffer *old_buffer UNUSED = dri2_surf->buffer;
1305 
1306    if (!_eglSurfaceInSharedBufferMode(&dri2_surf->base)) {
1307       _eglLog(_EGL_WARNING, "%s: internal error: buffer is not shared",
1308               __func__);
1309       return;
1310    }
1311 
1312    if (fence_fd >= 0) {
1313       /* The driver's fence is more recent than the surface's out fence, if it
1314        * exists at all. So use the driver's fence.
1315        */
1316       if (dri2_surf->out_fence_fd >= 0) {
1317          close(dri2_surf->out_fence_fd);
1318          dri2_surf->out_fence_fd = -1;
1319       }
1320    } else if (dri2_surf->out_fence_fd >= 0) {
1321       fence_fd = dri2_surf->out_fence_fd;
1322       dri2_surf->out_fence_fd = -1;
1323    }
1324 
1325    if (dri2_surf->window->queueBuffer(dri2_surf->window, dri2_surf->buffer,
1326                                       fence_fd)) {
1327       _eglLog(_EGL_WARNING, "%s: ANativeWindow::queueBuffer failed", __func__);
1328       close(fence_fd);
1329       return;
1330    }
1331 
1332    fence_fd = -1;
1333 
1334    if (dri2_surf->window->dequeueBuffer(dri2_surf->window, &dri2_surf->buffer,
1335                                         &fence_fd)) {
1336       /* Tear down the surface because it no longer has a back buffer. */
1337       struct dri2_egl_display *dri2_dpy =
1338          dri2_egl_display(dri2_surf->base.Resource.Display);
1339 
1340       _eglLog(_EGL_WARNING, "%s: ANativeWindow::dequeueBuffer failed", __func__);
1341 
1342       dri2_surf->base.Lost = true;
1343       dri2_surf->buffer = NULL;
1344       dri2_surf->back = NULL;
1345 
1346       if (dri2_surf->dri_image_back) {
1347          dri2_dpy->image->destroyImage(dri2_surf->dri_image_back);
1348          dri2_surf->dri_image_back = NULL;
1349       }
1350 
1351       dri2_dpy->flush->invalidate(dri2_surf->dri_drawable);
1352       return;
1353    }
1354 
1355    if (fence_fd < 0)
1356       return;
1357 
1358    /* Access to the buffer is controlled by a sync fence. Block on it.
1359     *
1360     * Ideally, we would submit the fence to the driver, and the driver would
1361     * postpone command execution until it signalled. But DRI lacks API for
1362     * that (as of 2018-04-11).
1363     *
1364     *  SYNC_IOC_WAIT waits forever if timeout < 0
1365     */
1366    sync_wait(fence_fd, -1);
1367    close(fence_fd);
1368 }
1369 
1370 static const __DRImutableRenderBufferLoaderExtension droid_mutable_render_buffer_extension = {
1371    .base = { __DRI_MUTABLE_RENDER_BUFFER_LOADER, 1 },
1372    .displaySharedBuffer = droid_display_shared_buffer,
1373 };
1374 
1375 static const __DRIextension *droid_image_loader_extensions[] = {
1376    &droid_image_loader_extension.base,
1377    &image_lookup_extension.base,
1378    &use_invalidate.base,
1379    &droid_mutable_render_buffer_extension.base,
1380    NULL,
1381 };
1382 
1383 static EGLBoolean
droid_load_driver(_EGLDisplay * disp,bool swrast)1384 droid_load_driver(_EGLDisplay *disp, bool swrast)
1385 {
1386    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1387 
1388    dri2_dpy->driver_name = loader_get_driver_for_fd(dri2_dpy->fd);
1389    if (dri2_dpy->driver_name == NULL)
1390       return false;
1391 
1392 #ifdef HAVE_DRM_GRALLOC
1393    /* Handle control nodes using __DRI_DRI2_LOADER extension and GEM names
1394     * for backwards compatibility with drm_gralloc. (Do not use on new
1395     * systems.) */
1396    dri2_dpy->loader_extensions = droid_dri2_loader_extensions;
1397    if (!dri2_load_driver(disp)) {
1398       goto error;
1399    }
1400 #else
1401    if (swrast) {
1402       /* Use kms swrast only with vgem / virtio_gpu.
1403        * virtio-gpu fallbacks to software rendering when 3D features
1404        * are unavailable since 6c5ab.
1405        */
1406       if (strcmp(dri2_dpy->driver_name, "vgem") == 0 ||
1407           strcmp(dri2_dpy->driver_name, "virtio_gpu") == 0) {
1408          free(dri2_dpy->driver_name);
1409          dri2_dpy->driver_name = strdup("kms_swrast");
1410       } else {
1411          goto error;
1412       }
1413    }
1414 
1415    dri2_dpy->loader_extensions = droid_image_loader_extensions;
1416    if (!dri2_load_driver_dri3(disp)) {
1417       goto error;
1418    }
1419 #endif
1420 
1421    return true;
1422 
1423 error:
1424    free(dri2_dpy->driver_name);
1425    dri2_dpy->driver_name = NULL;
1426    return false;
1427 }
1428 
1429 static void
droid_unload_driver(_EGLDisplay * disp)1430 droid_unload_driver(_EGLDisplay *disp)
1431 {
1432    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1433 
1434    dlclose(dri2_dpy->driver);
1435    dri2_dpy->driver = NULL;
1436    free(dri2_dpy->driver_name);
1437    dri2_dpy->driver_name = NULL;
1438 }
1439 
1440 static int
droid_filter_device(_EGLDisplay * disp,int fd,const char * vendor)1441 droid_filter_device(_EGLDisplay *disp, int fd, const char *vendor)
1442 {
1443    drmVersionPtr ver = drmGetVersion(fd);
1444    if (!ver)
1445       return -1;
1446 
1447    if (strcmp(vendor, ver->name) != 0) {
1448       drmFreeVersion(ver);
1449       return -1;
1450    }
1451 
1452    drmFreeVersion(ver);
1453    return 0;
1454 }
1455 
1456 static EGLBoolean
droid_probe_device(_EGLDisplay * disp,bool swrast)1457 droid_probe_device(_EGLDisplay *disp, bool swrast)
1458 {
1459   /* Check that the device is supported, by attempting to:
1460    * - load the dri module
1461    * - and, create a screen
1462    */
1463    if (!droid_load_driver(disp, swrast))
1464       return EGL_FALSE;
1465 
1466    if (!dri2_create_screen(disp)) {
1467       _eglLog(_EGL_WARNING, "DRI2: failed to create screen");
1468       droid_unload_driver(disp);
1469       return EGL_FALSE;
1470    }
1471    return EGL_TRUE;
1472 }
1473 
1474 #ifdef HAVE_DRM_GRALLOC
1475 static EGLBoolean
droid_open_device(_EGLDisplay * disp,bool swrast)1476 droid_open_device(_EGLDisplay *disp, bool swrast)
1477 {
1478    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1479    int fd = -1, err = -EINVAL;
1480 
1481    if (swrast)
1482       return EGL_FALSE;
1483 
1484    if (dri2_dpy->gralloc->perform)
1485       err = dri2_dpy->gralloc->perform(dri2_dpy->gralloc,
1486                                        GRALLOC_MODULE_PERFORM_GET_DRM_FD,
1487                                        &fd);
1488    if (err || fd < 0) {
1489       _eglLog(_EGL_WARNING, "fail to get drm fd");
1490       return EGL_FALSE;
1491    }
1492 
1493    dri2_dpy->fd = os_dupfd_cloexec(fd);
1494    if (dri2_dpy->fd < 0)
1495       return EGL_FALSE;
1496 
1497    if (drmGetNodeTypeFromFd(dri2_dpy->fd) == DRM_NODE_RENDER)
1498       return EGL_FALSE;
1499 
1500    return droid_probe_device(disp, swrast);
1501 }
1502 #else
1503 static EGLBoolean
droid_open_device(_EGLDisplay * disp,bool swrast)1504 droid_open_device(_EGLDisplay *disp, bool swrast)
1505 {
1506 #define MAX_DRM_DEVICES 64
1507    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1508    drmDevicePtr device, devices[MAX_DRM_DEVICES] = { NULL };
1509    int num_devices;
1510 
1511    char *vendor_name = NULL;
1512    char vendor_buf[PROPERTY_VALUE_MAX];
1513 
1514 #ifdef EGL_FORCE_RENDERNODE
1515    const unsigned node_type = DRM_NODE_RENDER;
1516 #else
1517    const unsigned node_type = swrast ? DRM_NODE_PRIMARY : DRM_NODE_RENDER;
1518 #endif
1519 
1520    if (property_get("drm.gpu.vendor_name", vendor_buf, NULL) > 0)
1521       vendor_name = vendor_buf;
1522 
1523    num_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
1524    if (num_devices < 0)
1525       return EGL_FALSE;
1526 
1527    for (int i = 0; i < num_devices; i++) {
1528       device = devices[i];
1529 
1530       if (!(device->available_nodes & (1 << node_type)))
1531          continue;
1532 
1533       dri2_dpy->fd = loader_open_device(device->nodes[node_type]);
1534       if (dri2_dpy->fd < 0) {
1535          _eglLog(_EGL_WARNING, "%s() Failed to open DRM device %s",
1536                  __func__, device->nodes[node_type]);
1537          continue;
1538       }
1539 
1540       /* If a vendor is explicitly provided, we use only that.
1541        * Otherwise we fall-back the first device that is supported.
1542        */
1543       if (vendor_name) {
1544          if (droid_filter_device(disp, dri2_dpy->fd, vendor_name)) {
1545             /* Device does not match - try next device */
1546             close(dri2_dpy->fd);
1547             dri2_dpy->fd = -1;
1548             continue;
1549          }
1550          /* If the requested device matches - use it. Regardless if
1551           * init fails, do not fall-back to any other device.
1552           */
1553          if (!droid_probe_device(disp, false)) {
1554             close(dri2_dpy->fd);
1555             dri2_dpy->fd = -1;
1556          }
1557 
1558          break;
1559       }
1560       if (droid_probe_device(disp, swrast))
1561          break;
1562 
1563       /* No explicit request - attempt the next device */
1564       close(dri2_dpy->fd);
1565       dri2_dpy->fd = -1;
1566    }
1567    drmFreeDevices(devices, num_devices);
1568 
1569    if (dri2_dpy->fd < 0) {
1570       _eglLog(_EGL_WARNING, "Failed to open %s DRM device",
1571             vendor_name ? "desired": "any");
1572       return EGL_FALSE;
1573    }
1574 
1575    return EGL_TRUE;
1576 #undef MAX_DRM_DEVICES
1577 }
1578 
1579 #endif
1580 
1581 EGLBoolean
dri2_initialize_android(_EGLDisplay * disp)1582 dri2_initialize_android(_EGLDisplay *disp)
1583 {
1584    _EGLDevice *dev;
1585    bool device_opened = false;
1586    struct dri2_egl_display *dri2_dpy;
1587    const char *err;
1588    int ret;
1589 
1590    dri2_dpy = calloc(1, sizeof(*dri2_dpy));
1591    if (!dri2_dpy)
1592       return _eglError(EGL_BAD_ALLOC, "eglInitialize");
1593 
1594    dri2_dpy->fd = -1;
1595    ret = hw_get_module(GRALLOC_HARDWARE_MODULE_ID,
1596                        (const hw_module_t **)&dri2_dpy->gralloc);
1597    if (ret) {
1598       err = "DRI2: failed to get gralloc module";
1599       goto cleanup;
1600    }
1601 
1602    disp->DriverData = (void *) dri2_dpy;
1603    device_opened = droid_open_device(disp, disp->Options.ForceSoftware);
1604 
1605    if (!device_opened) {
1606       err = "DRI2: failed to open device";
1607       goto cleanup;
1608    }
1609 
1610    dev = _eglAddDevice(dri2_dpy->fd, false);
1611    if (!dev) {
1612       err = "DRI2: failed to find EGLDevice";
1613       goto cleanup;
1614    }
1615 
1616    disp->Device = dev;
1617 
1618    if (!dri2_setup_extensions(disp)) {
1619       err = "DRI2: failed to setup extensions";
1620       goto cleanup;
1621    }
1622 
1623    dri2_setup_screen(disp);
1624 
1625    /* We set the maximum swap interval as 1 for Android platform, since it is
1626     * the maximum value supported by Android according to the value of
1627     * ANativeWindow::maxSwapInterval.
1628     */
1629    dri2_setup_swap_interval(disp, 1);
1630 
1631    disp->Extensions.ANDROID_framebuffer_target = EGL_TRUE;
1632    disp->Extensions.ANDROID_image_native_buffer = EGL_TRUE;
1633    disp->Extensions.ANDROID_recordable = EGL_TRUE;
1634 
1635    /* Querying buffer age requires a buffer to be dequeued.  Without
1636     * EGL_ANDROID_native_fence_sync, dequeue might call eglClientWaitSync and
1637     * result in a deadlock (the lock is already held by eglQuerySurface).
1638     */
1639    if (disp->Extensions.ANDROID_native_fence_sync) {
1640       disp->Extensions.EXT_buffer_age = EGL_TRUE;
1641    } else {
1642       /* disable KHR_partial_update that might have been enabled in
1643        * dri2_setup_screen
1644        */
1645       disp->Extensions.KHR_partial_update = EGL_FALSE;
1646    }
1647 
1648    disp->Extensions.KHR_image = EGL_TRUE;
1649 #if ANDROID_API_LEVEL >= 24
1650    if (dri2_dpy->mutable_render_buffer &&
1651        dri2_dpy->loader_extensions == droid_image_loader_extensions) {
1652       disp->Extensions.KHR_mutable_render_buffer = EGL_TRUE;
1653    }
1654 #endif
1655 
1656    /* Create configs *after* enabling extensions because presence of DRI
1657     * driver extensions can affect the capabilities of EGLConfigs.
1658     */
1659    if (!droid_add_configs_for_visuals(disp)) {
1660       err = "DRI2: failed to add configs";
1661       goto cleanup;
1662    }
1663 
1664    /* Fill vtbl last to prevent accidentally calling virtual function during
1665     * initialization.
1666     */
1667    dri2_dpy->vtbl = &droid_display_vtbl;
1668 
1669    return EGL_TRUE;
1670 
1671 cleanup:
1672    dri2_display_destroy(disp);
1673    return _eglError(EGL_NOT_INITIALIZED, err);
1674 }
1675