• 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 <dirent.h>
31 #include <dlfcn.h>
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <stdbool.h>
35 #include <stdio.h>
36 #include <xf86drm.h>
37 #include <cutils/properties.h>
38 #include <drm-uapi/drm_fourcc.h>
39 #include <sync/sync.h>
40 #include <sys/types.h>
41 
42 #include "util/compiler.h"
43 #include "util/libsync.h"
44 #include "util/os_file.h"
45 
46 #include "main/glconfig.h"
47 #include "egl_dri2.h"
48 #include "eglglobals.h"
49 #include "loader.h"
50 #include "loader_dri_helper.h"
51 #include "platform_android.h"
52 
53 static __DRIimage *
droid_create_image_from_buffer_info(struct dri2_egl_display * dri2_dpy,int width,int height,struct u_gralloc_buffer_basic_info * buf_info,struct u_gralloc_buffer_color_info * color_info,void * priv)54 droid_create_image_from_buffer_info(
55    struct dri2_egl_display *dri2_dpy, int width, int height,
56    struct u_gralloc_buffer_basic_info *buf_info,
57    struct u_gralloc_buffer_color_info *color_info, void *priv)
58 {
59    unsigned error;
60 
61    if (dri2_dpy->image->base.version >= 15 &&
62        dri2_dpy->image->createImageFromDmaBufs2 != NULL) {
63       return dri2_dpy->image->createImageFromDmaBufs2(
64          dri2_dpy->dri_screen_render_gpu, width, height, buf_info->drm_fourcc,
65          buf_info->modifier, buf_info->fds, buf_info->num_planes,
66          buf_info->strides, buf_info->offsets, color_info->yuv_color_space,
67          color_info->sample_range, color_info->horizontal_siting,
68          color_info->vertical_siting, &error, priv);
69    }
70 
71    return dri2_dpy->image->createImageFromDmaBufs(
72       dri2_dpy->dri_screen_render_gpu, width, height, buf_info->drm_fourcc,
73       buf_info->fds, buf_info->num_planes, buf_info->strides, buf_info->offsets,
74       color_info->yuv_color_space, color_info->sample_range,
75       color_info->horizontal_siting, color_info->vertical_siting, &error, priv);
76 }
77 
78 static __DRIimage *
droid_create_image_from_native_buffer(_EGLDisplay * disp,struct ANativeWindowBuffer * buf,void * priv)79 droid_create_image_from_native_buffer(_EGLDisplay *disp,
80                                       struct ANativeWindowBuffer *buf,
81                                       void *priv)
82 {
83    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
84    struct u_gralloc_buffer_basic_info buf_info;
85    struct u_gralloc_buffer_color_info color_info = {
86       .yuv_color_space = __DRI_YUV_COLOR_SPACE_ITU_REC601,
87       .sample_range = __DRI_YUV_NARROW_RANGE,
88       .horizontal_siting = __DRI_YUV_CHROMA_SITING_0,
89       .vertical_siting = __DRI_YUV_CHROMA_SITING_0,
90    };
91    struct u_gralloc_buffer_handle gr_handle = {
92       .handle = buf->handle,
93       .hal_format = buf->format,
94       .pixel_stride = buf->stride,
95    };
96    __DRIimage *img = NULL;
97 
98    if (u_gralloc_get_buffer_basic_info(dri2_dpy->gralloc, &gr_handle,
99                                        &buf_info))
100       return 0;
101 
102    /* May fail in some cases, defaults will be used in that case */
103    u_gralloc_get_buffer_color_info(dri2_dpy->gralloc, &gr_handle, &color_info);
104 
105    img = droid_create_image_from_buffer_info(dri2_dpy, buf->width, buf->height,
106                                              &buf_info, &color_info, priv);
107 
108    if (!img) {
109       /* If dri driver is gallium virgl, real modifier info queried back from
110        * CrOS info (and potentially mapper metadata if integrated later) cannot
111        * get resolved and the buffer import will fail. Thus the fallback
112        * behavior is preserved so that the buffer can be imported without
113        * modifier info as a last resort.
114        */
115       buf_info.modifier = DRM_FORMAT_MOD_INVALID;
116       img = droid_create_image_from_buffer_info(
117          dri2_dpy, buf->width, buf->height, &buf_info, &color_info, priv);
118    }
119 
120    return img;
121 }
122 
123 static void
handle_in_fence_fd(struct dri2_egl_surface * dri2_surf,__DRIimage * img)124 handle_in_fence_fd(struct dri2_egl_surface *dri2_surf, __DRIimage *img)
125 {
126    _EGLDisplay *disp = dri2_surf->base.Resource.Display;
127    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
128 
129    if (dri2_surf->in_fence_fd < 0)
130       return;
131 
132    validate_fence_fd(dri2_surf->in_fence_fd);
133 
134    if (dri2_dpy->image->base.version >= 21 &&
135        dri2_dpy->image->setInFenceFd != NULL) {
136       dri2_dpy->image->setInFenceFd(img, dri2_surf->in_fence_fd);
137    } else {
138       sync_wait(dri2_surf->in_fence_fd, -1);
139    }
140 }
141 
142 static void
close_in_fence_fd(struct dri2_egl_surface * dri2_surf)143 close_in_fence_fd(struct dri2_egl_surface *dri2_surf)
144 {
145    validate_fence_fd(dri2_surf->in_fence_fd);
146    if (dri2_surf->in_fence_fd >= 0)
147       close(dri2_surf->in_fence_fd);
148    dri2_surf->in_fence_fd = -1;
149 }
150 
151 static EGLBoolean
droid_window_dequeue_buffer(struct dri2_egl_surface * dri2_surf)152 droid_window_dequeue_buffer(struct dri2_egl_surface *dri2_surf)
153 {
154    int fence_fd;
155 
156    if (ANativeWindow_dequeueBuffer(dri2_surf->window, &dri2_surf->buffer,
157                                    &fence_fd))
158       return EGL_FALSE;
159 
160    close_in_fence_fd(dri2_surf);
161 
162    validate_fence_fd(fence_fd);
163 
164    dri2_surf->in_fence_fd = fence_fd;
165 
166    /* Record all the buffers created by ANativeWindow and update back buffer
167     * for updating buffer's age in swap_buffers.
168     */
169    EGLBoolean updated = EGL_FALSE;
170    for (int i = 0; i < dri2_surf->color_buffers_count; i++) {
171       if (!dri2_surf->color_buffers[i].buffer) {
172          dri2_surf->color_buffers[i].buffer = dri2_surf->buffer;
173       }
174       if (dri2_surf->color_buffers[i].buffer == dri2_surf->buffer) {
175          dri2_surf->back = &dri2_surf->color_buffers[i];
176          updated = EGL_TRUE;
177          break;
178       }
179    }
180 
181    if (!updated) {
182       /* In case of all the buffers were recreated by ANativeWindow, reset
183        * the color_buffers
184        */
185       for (int i = 0; i < dri2_surf->color_buffers_count; i++) {
186          dri2_surf->color_buffers[i].buffer = NULL;
187          dri2_surf->color_buffers[i].age = 0;
188       }
189       dri2_surf->color_buffers[0].buffer = dri2_surf->buffer;
190       dri2_surf->back = &dri2_surf->color_buffers[0];
191    }
192 
193    return EGL_TRUE;
194 }
195 
196 static EGLBoolean
droid_window_enqueue_buffer(_EGLDisplay * disp,struct dri2_egl_surface * dri2_surf)197 droid_window_enqueue_buffer(_EGLDisplay *disp,
198                             struct dri2_egl_surface *dri2_surf)
199 {
200    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
201 
202    /* Queue the buffer with stored out fence fd. The ANativeWindow or buffer
203     * consumer may choose to wait for the fence to signal before accessing
204     * it. If fence fd value is -1, buffer can be accessed by consumer
205     * immediately. Consumer or application shouldn't rely on timestamp
206     * associated with fence if the fence fd is -1.
207     *
208     * Ownership of fd is transferred to consumer after queueBuffer and the
209     * consumer is responsible for closing it. Caller must not use the fd
210     * after passing it to queueBuffer.
211     */
212    int fence_fd = dri2_surf->out_fence_fd;
213    dri2_surf->out_fence_fd = -1;
214    ANativeWindow_queueBuffer(dri2_surf->window, dri2_surf->buffer, fence_fd);
215 
216    dri2_surf->buffer = NULL;
217    dri2_surf->back = NULL;
218 
219    if (dri2_surf->dri_image_back) {
220       dri2_dpy->image->destroyImage(dri2_surf->dri_image_back);
221       dri2_surf->dri_image_back = NULL;
222    }
223 
224    return EGL_TRUE;
225 }
226 
227 static void
droid_window_cancel_buffer(struct dri2_egl_surface * dri2_surf)228 droid_window_cancel_buffer(struct dri2_egl_surface *dri2_surf)
229 {
230    int ret;
231    int fence_fd = dri2_surf->out_fence_fd;
232 
233    dri2_surf->out_fence_fd = -1;
234    ret = ANativeWindow_cancelBuffer(dri2_surf->window, dri2_surf->buffer,
235                                     fence_fd);
236    dri2_surf->buffer = NULL;
237    if (ret < 0) {
238       _eglLog(_EGL_WARNING, "ANativeWindow_cancelBuffer failed");
239       dri2_surf->base.Lost = EGL_TRUE;
240    }
241 
242    close_in_fence_fd(dri2_surf);
243 }
244 
245 static bool
droid_set_shared_buffer_mode(_EGLDisplay * disp,_EGLSurface * surf,bool mode)246 droid_set_shared_buffer_mode(_EGLDisplay *disp, _EGLSurface *surf, bool mode)
247 {
248 #if ANDROID_API_LEVEL >= 24
249    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
250    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
251    struct ANativeWindow *window = dri2_surf->window;
252 
253    assert(surf->Type == EGL_WINDOW_BIT);
254    assert(_eglSurfaceHasMutableRenderBuffer(&dri2_surf->base));
255 
256    _eglLog(_EGL_DEBUG, "%s: mode=%d", __func__, mode);
257 
258    if (ANativeWindow_setSharedBufferMode(window, mode)) {
259       _eglLog(_EGL_WARNING,
260               "failed ANativeWindow_setSharedBufferMode"
261               "(window=%p, mode=%d)",
262               window, mode);
263       return false;
264    }
265 
266    if (mode)
267       dri2_surf->gralloc_usage |= dri2_dpy->front_rendering_usage;
268    else
269       dri2_surf->gralloc_usage &= ~dri2_dpy->front_rendering_usage;
270 
271    if (ANativeWindow_setUsage(window, dri2_surf->gralloc_usage)) {
272       _eglLog(_EGL_WARNING,
273               "failed ANativeWindow_setUsage(window=%p, usage=%u)", window,
274               dri2_surf->gralloc_usage);
275       return false;
276    }
277 
278    return true;
279 #else
280    _eglLog(_EGL_FATAL, "%s:%d: internal error: unreachable", __FILE__,
281            __LINE__);
282    return false;
283 #endif
284 }
285 
286 static _EGLSurface *
droid_create_surface(_EGLDisplay * disp,EGLint type,_EGLConfig * conf,void * native_window,const EGLint * attrib_list)287 droid_create_surface(_EGLDisplay *disp, EGLint type, _EGLConfig *conf,
288                      void *native_window, const EGLint *attrib_list)
289 {
290    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
291    struct dri2_egl_config *dri2_conf = dri2_egl_config(conf);
292    struct dri2_egl_surface *dri2_surf;
293    struct ANativeWindow *window = native_window;
294    const __DRIconfig *config;
295 
296    dri2_surf = calloc(1, sizeof *dri2_surf);
297    if (!dri2_surf) {
298       _eglError(EGL_BAD_ALLOC, "droid_create_surface");
299       return NULL;
300    }
301 
302    dri2_surf->in_fence_fd = -1;
303 
304    if (!dri2_init_surface(&dri2_surf->base, disp, type, conf, attrib_list, true,
305                           native_window))
306       goto cleanup_surface;
307 
308    if (type == EGL_WINDOW_BIT) {
309       int format;
310       int buffer_count;
311       int min_undequeued_buffers;
312 
313       format = ANativeWindow_getFormat(window);
314       if (format < 0) {
315          _eglError(EGL_BAD_NATIVE_WINDOW, "droid_create_surface");
316          goto cleanup_surface;
317       }
318 
319       /* Query ANativeWindow for MIN_UNDEQUEUED_BUFFER, minimum amount
320        * of undequeued buffers.
321        */
322       if (ANativeWindow_query(window,
323                               ANATIVEWINDOW_QUERY_MIN_UNDEQUEUED_BUFFERS,
324                               &min_undequeued_buffers)) {
325          _eglError(EGL_BAD_NATIVE_WINDOW, "droid_create_surface");
326          goto cleanup_surface;
327       }
328 
329       /* Required buffer caching slots. */
330       buffer_count = min_undequeued_buffers + 2;
331 
332       dri2_surf->color_buffers =
333          calloc(buffer_count, sizeof(*dri2_surf->color_buffers));
334       if (!dri2_surf->color_buffers) {
335          _eglError(EGL_BAD_ALLOC, "droid_create_surface");
336          goto cleanup_surface;
337       }
338       dri2_surf->color_buffers_count = buffer_count;
339 
340       if (format != dri2_conf->base.NativeVisualID) {
341          _eglLog(_EGL_WARNING, "Native format mismatch: 0x%x != 0x%x", format,
342                  dri2_conf->base.NativeVisualID);
343       }
344 
345       ANativeWindow_query(window, ANATIVEWINDOW_QUERY_DEFAULT_WIDTH,
346                           &dri2_surf->base.Width);
347       ANativeWindow_query(window, ANATIVEWINDOW_QUERY_DEFAULT_HEIGHT,
348                           &dri2_surf->base.Height);
349 
350       dri2_surf->gralloc_usage =
351          strcmp(dri2_dpy->driver_name, "kms_swrast") == 0
352             ? GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN
353             : GRALLOC_USAGE_HW_RENDER;
354 
355       if (dri2_surf->base.ActiveRenderBuffer == EGL_SINGLE_BUFFER)
356          dri2_surf->gralloc_usage |= dri2_dpy->front_rendering_usage;
357 
358       if (ANativeWindow_setUsage(window, dri2_surf->gralloc_usage)) {
359          _eglError(EGL_BAD_NATIVE_WINDOW, "droid_create_surface");
360          goto cleanup_surface;
361       }
362    }
363 
364    config = dri2_get_dri_config(dri2_conf, type, dri2_surf->base.GLColorspace);
365    if (!config) {
366       _eglError(EGL_BAD_MATCH,
367                 "Unsupported surfacetype/colorspace configuration");
368       goto cleanup_surface;
369    }
370 
371    if (!dri2_create_drawable(dri2_dpy, config, dri2_surf, dri2_surf))
372       goto cleanup_surface;
373 
374    if (window) {
375       ANativeWindow_acquire(window);
376       dri2_surf->window = window;
377    }
378 
379    return &dri2_surf->base;
380 
381 cleanup_surface:
382    if (dri2_surf->color_buffers_count)
383       free(dri2_surf->color_buffers);
384    free(dri2_surf);
385 
386    return NULL;
387 }
388 
389 static _EGLSurface *
droid_create_window_surface(_EGLDisplay * disp,_EGLConfig * conf,void * native_window,const EGLint * attrib_list)390 droid_create_window_surface(_EGLDisplay *disp, _EGLConfig *conf,
391                             void *native_window, const EGLint *attrib_list)
392 {
393    return droid_create_surface(disp, EGL_WINDOW_BIT, conf, native_window,
394                                attrib_list);
395 }
396 
397 static _EGLSurface *
droid_create_pbuffer_surface(_EGLDisplay * disp,_EGLConfig * conf,const EGLint * attrib_list)398 droid_create_pbuffer_surface(_EGLDisplay *disp, _EGLConfig *conf,
399                              const EGLint *attrib_list)
400 {
401    return droid_create_surface(disp, EGL_PBUFFER_BIT, conf, NULL, attrib_list);
402 }
403 
404 static EGLBoolean
droid_destroy_surface(_EGLDisplay * disp,_EGLSurface * surf)405 droid_destroy_surface(_EGLDisplay *disp, _EGLSurface *surf)
406 {
407    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
408    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
409 
410    dri2_egl_surface_free_local_buffers(dri2_surf);
411 
412    if (dri2_surf->base.Type == EGL_WINDOW_BIT) {
413       if (dri2_surf->buffer)
414          droid_window_cancel_buffer(dri2_surf);
415 
416       ANativeWindow_release(dri2_surf->window);
417    }
418 
419    if (dri2_surf->dri_image_back) {
420       _eglLog(_EGL_DEBUG, "%s : %d : destroy dri_image_back", __func__,
421               __LINE__);
422       dri2_dpy->image->destroyImage(dri2_surf->dri_image_back);
423       dri2_surf->dri_image_back = NULL;
424    }
425 
426    if (dri2_surf->dri_image_front) {
427       _eglLog(_EGL_DEBUG, "%s : %d : destroy dri_image_front", __func__,
428               __LINE__);
429       dri2_dpy->image->destroyImage(dri2_surf->dri_image_front);
430       dri2_surf->dri_image_front = NULL;
431    }
432 
433    dri2_dpy->core->destroyDrawable(dri2_surf->dri_drawable);
434 
435    close_in_fence_fd(dri2_surf);
436    dri2_fini_surface(surf);
437    free(dri2_surf->color_buffers);
438    free(dri2_surf);
439 
440    return EGL_TRUE;
441 }
442 
443 static EGLBoolean
droid_swap_interval(_EGLDisplay * disp,_EGLSurface * surf,EGLint interval)444 droid_swap_interval(_EGLDisplay *disp, _EGLSurface *surf, EGLint interval)
445 {
446    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
447    struct ANativeWindow *window = dri2_surf->window;
448 
449    if (ANativeWindow_setSwapInterval(window, interval))
450       return EGL_FALSE;
451 
452    surf->SwapInterval = interval;
453    return EGL_TRUE;
454 }
455 
456 static int
update_buffers(struct dri2_egl_surface * dri2_surf)457 update_buffers(struct dri2_egl_surface *dri2_surf)
458 {
459    if (dri2_surf->base.Lost)
460       return -1;
461 
462    if (dri2_surf->base.Type != EGL_WINDOW_BIT)
463       return 0;
464 
465    /* try to dequeue the next back buffer */
466    if (!dri2_surf->buffer && !droid_window_dequeue_buffer(dri2_surf)) {
467       _eglLog(_EGL_WARNING, "Could not dequeue buffer from native window");
468       dri2_surf->base.Lost = EGL_TRUE;
469       return -1;
470    }
471 
472    /* free outdated buffers and update the surface size */
473    if (dri2_surf->base.Width != dri2_surf->buffer->width ||
474        dri2_surf->base.Height != dri2_surf->buffer->height) {
475       dri2_egl_surface_free_local_buffers(dri2_surf);
476       dri2_surf->base.Width = dri2_surf->buffer->width;
477       dri2_surf->base.Height = dri2_surf->buffer->height;
478    }
479 
480    return 0;
481 }
482 
483 static int
get_front_bo(struct dri2_egl_surface * dri2_surf,unsigned int format)484 get_front_bo(struct dri2_egl_surface *dri2_surf, unsigned int format)
485 {
486    struct dri2_egl_display *dri2_dpy =
487       dri2_egl_display(dri2_surf->base.Resource.Display);
488 
489    if (dri2_surf->dri_image_front)
490       return 0;
491 
492    if (dri2_surf->base.Type == EGL_WINDOW_BIT) {
493       /* According current EGL spec, front buffer rendering
494        * for window surface is not supported now.
495        * and mesa doesn't have the implementation of this case.
496        * Add warning message, but not treat it as error.
497        */
498       _eglLog(
499          _EGL_DEBUG,
500          "DRI driver requested unsupported front buffer for window surface");
501    } else if (dri2_surf->base.Type == EGL_PBUFFER_BIT) {
502       dri2_surf->dri_image_front = dri2_dpy->image->createImage(
503          dri2_dpy->dri_screen_render_gpu, dri2_surf->base.Width,
504          dri2_surf->base.Height, format, 0, NULL);
505       if (!dri2_surf->dri_image_front) {
506          _eglLog(_EGL_WARNING, "dri2_image_front allocation failed");
507          return -1;
508       }
509    }
510 
511    return 0;
512 }
513 
514 static int
get_back_bo(struct dri2_egl_surface * dri2_surf)515 get_back_bo(struct dri2_egl_surface *dri2_surf)
516 {
517    _EGLDisplay *disp = dri2_surf->base.Resource.Display;
518 
519    if (dri2_surf->dri_image_back)
520       return 0;
521 
522    if (dri2_surf->base.Type == EGL_WINDOW_BIT) {
523       if (!dri2_surf->buffer) {
524          _eglLog(_EGL_WARNING, "Could not get native buffer");
525          return -1;
526       }
527 
528       dri2_surf->dri_image_back =
529          droid_create_image_from_native_buffer(disp, dri2_surf->buffer, NULL);
530       if (!dri2_surf->dri_image_back) {
531          _eglLog(_EGL_WARNING, "failed to create DRI image from FD");
532          return -1;
533       }
534 
535       handle_in_fence_fd(dri2_surf, dri2_surf->dri_image_back);
536 
537    } else if (dri2_surf->base.Type == EGL_PBUFFER_BIT) {
538       /* The EGL 1.5 spec states that pbuffers are single-buffered.
539        * Specifically, the spec states that they have a back buffer but no front
540        * buffer, in contrast to pixmaps, which have a front buffer but no back
541        * buffer.
542        *
543        * Single-buffered surfaces with no front buffer confuse Mesa; so we
544        * deviate from the spec, following the precedent of Mesa's EGL X11
545        * platform. The X11 platform correctly assigns pbuffers to
546        * single-buffered configs, but assigns the pbuffer a front buffer instead
547        * of a back buffer.
548        *
549        * Pbuffers in the X11 platform mostly work today, so let's just copy its
550        * behavior instead of trying to fix (and hence potentially breaking) the
551        * world.
552        */
553       _eglLog(
554          _EGL_DEBUG,
555          "DRI driver requested unsupported back buffer for pbuffer surface");
556    }
557 
558    return 0;
559 }
560 
561 /* Some drivers will pass multiple bits in buffer_mask.
562  * For such case, will go through all the bits, and
563  * will not return error when unsupported buffer is requested, only
564  * return error when the allocation for supported buffer failed.
565  */
566 static int
droid_image_get_buffers(__DRIdrawable * driDrawable,unsigned int format,uint32_t * stamp,void * loaderPrivate,uint32_t buffer_mask,struct __DRIimageList * images)567 droid_image_get_buffers(__DRIdrawable *driDrawable, unsigned int format,
568                         uint32_t *stamp, void *loaderPrivate,
569                         uint32_t buffer_mask, struct __DRIimageList *images)
570 {
571    struct dri2_egl_surface *dri2_surf = loaderPrivate;
572 
573    images->image_mask = 0;
574    images->front = NULL;
575    images->back = NULL;
576 
577    if (update_buffers(dri2_surf) < 0)
578       return 0;
579 
580    if (_eglSurfaceInSharedBufferMode(&dri2_surf->base)) {
581       if (get_back_bo(dri2_surf) < 0)
582          return 0;
583 
584       /* We have dri_image_back because this is a window surface and
585        * get_back_bo() succeeded.
586        */
587       assert(dri2_surf->dri_image_back);
588       images->back = dri2_surf->dri_image_back;
589       images->image_mask |= __DRI_IMAGE_BUFFER_SHARED;
590 
591       /* There exists no accompanying back nor front buffer. */
592       return 1;
593    }
594 
595    if (buffer_mask & __DRI_IMAGE_BUFFER_FRONT) {
596       if (get_front_bo(dri2_surf, format) < 0)
597          return 0;
598 
599       if (dri2_surf->dri_image_front) {
600          images->front = dri2_surf->dri_image_front;
601          images->image_mask |= __DRI_IMAGE_BUFFER_FRONT;
602       }
603    }
604 
605    if (buffer_mask & __DRI_IMAGE_BUFFER_BACK) {
606       if (get_back_bo(dri2_surf) < 0)
607          return 0;
608 
609       if (dri2_surf->dri_image_back) {
610          images->back = dri2_surf->dri_image_back;
611          images->image_mask |= __DRI_IMAGE_BUFFER_BACK;
612       }
613    }
614 
615    return 1;
616 }
617 
618 static EGLint
droid_query_buffer_age(_EGLDisplay * disp,_EGLSurface * surface)619 droid_query_buffer_age(_EGLDisplay *disp, _EGLSurface *surface)
620 {
621    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surface);
622 
623    if (update_buffers(dri2_surf) < 0) {
624       _eglError(EGL_BAD_ALLOC, "droid_query_buffer_age");
625       return -1;
626    }
627 
628    return dri2_surf->back ? dri2_surf->back->age : 0;
629 }
630 
631 static EGLBoolean
droid_swap_buffers(_EGLDisplay * disp,_EGLSurface * draw)632 droid_swap_buffers(_EGLDisplay *disp, _EGLSurface *draw)
633 {
634    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
635    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(draw);
636    const bool has_mutable_rb = _eglSurfaceHasMutableRenderBuffer(draw);
637 
638    /* From the EGL_KHR_mutable_render_buffer spec (v12):
639     *
640     *    If surface is a single-buffered window, pixmap, or pbuffer surface
641     *    for which there is no pending change to the EGL_RENDER_BUFFER
642     *    attribute, eglSwapBuffers has no effect.
643     */
644    if (has_mutable_rb && draw->RequestedRenderBuffer == EGL_SINGLE_BUFFER &&
645        draw->ActiveRenderBuffer == EGL_SINGLE_BUFFER) {
646       _eglLog(_EGL_DEBUG, "%s: remain in shared buffer mode", __func__);
647       return EGL_TRUE;
648    }
649 
650    for (int i = 0; i < dri2_surf->color_buffers_count; i++) {
651       if (dri2_surf->color_buffers[i].age > 0)
652          dri2_surf->color_buffers[i].age++;
653    }
654 
655    /* "XXX: we don't use get_back_bo() since it causes regressions in
656     * several dEQP tests.
657     */
658    if (dri2_surf->back)
659       dri2_surf->back->age = 1;
660 
661    dri2_flush_drawable_for_swapbuffers_flags(disp, draw,
662                                              __DRI2_NOTHROTTLE_SWAPBUFFER);
663 
664    /* dri2_surf->buffer can be null even when no error has occurred. For
665     * example, if the user has called no GL rendering commands since the
666     * previous eglSwapBuffers, then the driver may have not triggered
667     * a callback to ANativeWindow_dequeueBuffer, in which case
668     * dri2_surf->buffer remains null.
669     */
670    if (dri2_surf->buffer)
671       droid_window_enqueue_buffer(disp, dri2_surf);
672 
673    dri2_dpy->flush->invalidate(dri2_surf->dri_drawable);
674 
675    /* Update the shared buffer mode */
676    if (has_mutable_rb &&
677        draw->ActiveRenderBuffer != draw->RequestedRenderBuffer) {
678       bool mode = (draw->RequestedRenderBuffer == EGL_SINGLE_BUFFER);
679       _eglLog(_EGL_DEBUG, "%s: change to shared buffer mode %d", __func__,
680               mode);
681 
682       if (!droid_set_shared_buffer_mode(disp, draw, mode))
683          return EGL_FALSE;
684       draw->ActiveRenderBuffer = draw->RequestedRenderBuffer;
685    }
686 
687    return EGL_TRUE;
688 }
689 
690 static EGLBoolean
droid_query_surface(_EGLDisplay * disp,_EGLSurface * surf,EGLint attribute,EGLint * value)691 droid_query_surface(_EGLDisplay *disp, _EGLSurface *surf, EGLint attribute,
692                     EGLint *value)
693 {
694    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
695    switch (attribute) {
696    case EGL_WIDTH:
697       if (dri2_surf->base.Type == EGL_WINDOW_BIT && dri2_surf->window) {
698          ANativeWindow_query(dri2_surf->window,
699                              ANATIVEWINDOW_QUERY_DEFAULT_WIDTH, value);
700          return EGL_TRUE;
701       }
702       break;
703    case EGL_HEIGHT:
704       if (dri2_surf->base.Type == EGL_WINDOW_BIT && dri2_surf->window) {
705          ANativeWindow_query(dri2_surf->window,
706                              ANATIVEWINDOW_QUERY_DEFAULT_HEIGHT, value);
707          return EGL_TRUE;
708       }
709       break;
710    default:
711       break;
712    }
713    return _eglQuerySurface(disp, surf, attribute, value);
714 }
715 
716 static _EGLImage *
dri2_create_image_android_native_buffer(_EGLDisplay * disp,_EGLContext * ctx,struct ANativeWindowBuffer * buf)717 dri2_create_image_android_native_buffer(_EGLDisplay *disp, _EGLContext *ctx,
718                                         struct ANativeWindowBuffer *buf)
719 {
720    if (ctx != NULL) {
721       /* From the EGL_ANDROID_image_native_buffer spec:
722        *
723        *     * If <target> is EGL_NATIVE_BUFFER_ANDROID and <ctx> is not
724        *       EGL_NO_CONTEXT, the error EGL_BAD_CONTEXT is generated.
725        */
726       _eglError(EGL_BAD_CONTEXT,
727                 "eglCreateEGLImageKHR: for "
728                 "EGL_NATIVE_BUFFER_ANDROID, the context must be "
729                 "EGL_NO_CONTEXT");
730       return NULL;
731    }
732 
733    if (!buf || buf->common.magic != ANDROID_NATIVE_BUFFER_MAGIC ||
734        buf->common.version != sizeof(*buf)) {
735       _eglError(EGL_BAD_PARAMETER, "eglCreateEGLImageKHR");
736       return NULL;
737    }
738 
739    __DRIimage *dri_image =
740       droid_create_image_from_native_buffer(disp, buf, buf);
741 
742    if (dri_image) {
743 #if ANDROID_API_LEVEL >= 26
744       AHardwareBuffer_acquire(ANativeWindowBuffer_getHardwareBuffer(buf));
745 #endif
746       return dri2_create_image_from_dri(disp, dri_image);
747    }
748 
749    return NULL;
750 }
751 
752 static _EGLImage *
droid_create_image_khr(_EGLDisplay * disp,_EGLContext * ctx,EGLenum target,EGLClientBuffer buffer,const EGLint * attr_list)753 droid_create_image_khr(_EGLDisplay *disp, _EGLContext *ctx, EGLenum target,
754                        EGLClientBuffer buffer, const EGLint *attr_list)
755 {
756    switch (target) {
757    case EGL_NATIVE_BUFFER_ANDROID:
758       return dri2_create_image_android_native_buffer(
759          disp, ctx, (struct ANativeWindowBuffer *)buffer);
760    default:
761       return dri2_create_image_khr(disp, ctx, target, buffer, attr_list);
762    }
763 }
764 
765 static void
droid_flush_front_buffer(__DRIdrawable * driDrawable,void * loaderPrivate)766 droid_flush_front_buffer(__DRIdrawable *driDrawable, void *loaderPrivate)
767 {
768 }
769 
770 static unsigned
droid_get_capability(void * loaderPrivate,enum dri_loader_cap cap)771 droid_get_capability(void *loaderPrivate, enum dri_loader_cap cap)
772 {
773    /* Note: loaderPrivate is _EGLDisplay* */
774    switch (cap) {
775    case DRI_LOADER_CAP_RGBA_ORDERING:
776       return 1;
777    default:
778       return 0;
779    }
780 }
781 
782 static void
droid_destroy_loader_image_state(void * loaderPrivate)783 droid_destroy_loader_image_state(void *loaderPrivate)
784 {
785 #if ANDROID_API_LEVEL >= 26
786    if (loaderPrivate) {
787       AHardwareBuffer_release(
788          ANativeWindowBuffer_getHardwareBuffer(loaderPrivate));
789    }
790 #endif
791 }
792 
793 static void
droid_add_configs_for_visuals(_EGLDisplay * disp)794 droid_add_configs_for_visuals(_EGLDisplay *disp)
795 {
796    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
797    static const struct {
798       int hal_format;
799       enum pipe_format pipe_format;
800    } visuals[] = {
801       {HAL_PIXEL_FORMAT_RGBA_8888, PIPE_FORMAT_RGBA8888_UNORM},
802       {HAL_PIXEL_FORMAT_RGBX_8888, PIPE_FORMAT_RGBX8888_UNORM},
803       {HAL_PIXEL_FORMAT_RGB_565, PIPE_FORMAT_R5G6B5_UNORM},
804       /* This must be after HAL_PIXEL_FORMAT_RGBA_8888, we only keep BGRA
805        * visual if it turns out RGBA visual is not available.
806        */
807       {HAL_PIXEL_FORMAT_BGRA_8888, PIPE_FORMAT_BGRA8888_UNORM},
808    };
809 
810    unsigned int format_count[ARRAY_SIZE(visuals)] = {0};
811 
812    /* The nesting of loops is significant here. Also significant is the order
813     * of the HAL pixel formats. Many Android apps (such as Google's official
814     * NDK GLES2 example app), and even portions the core framework code (such
815     * as SystemServiceManager in Nougat), incorrectly choose their EGLConfig.
816     * They neglect to match the EGLConfig's EGL_NATIVE_VISUAL_ID against the
817     * window's native format, and instead choose the first EGLConfig whose
818     * channel sizes match those of the native window format while ignoring the
819     * channel *ordering*.
820     *
821     * We can detect such buggy clients in logcat when they call
822     * eglCreateSurface, by detecting the mismatch between the EGLConfig's
823     * format and the window's format.
824     *
825     * As a workaround, we generate EGLConfigs such that all EGLConfigs for HAL
826     * pixel format i precede those for HAL pixel format i+1. In my
827     * (chadversary) testing on Android Nougat, this was good enough to pacify
828     * the buggy clients.
829     */
830    bool has_rgba = false;
831    for (int i = 0; i < ARRAY_SIZE(visuals); i++) {
832       /* Only enable BGRA configs when RGBA is not available. BGRA configs are
833        * buggy on stock Android.
834        */
835       if (visuals[i].hal_format == HAL_PIXEL_FORMAT_BGRA_8888 && has_rgba)
836          continue;
837       for (int j = 0; dri2_dpy->driver_configs[j]; j++) {
838          const struct gl_config *gl_config =
839             (struct gl_config *) dri2_dpy->driver_configs;
840 
841          if (gl_config->color_format != visuals[i].pipe_format)
842             continue;
843 
844          const EGLint surface_type = EGL_WINDOW_BIT | EGL_PBUFFER_BIT;
845          const EGLint config_attrs[] = {
846             EGL_NATIVE_VISUAL_ID,
847             visuals[i].hal_format,
848             EGL_NATIVE_VISUAL_TYPE,
849             visuals[i].hal_format,
850             EGL_FRAMEBUFFER_TARGET_ANDROID,
851             EGL_TRUE,
852             EGL_RECORDABLE_ANDROID,
853             EGL_TRUE,
854             EGL_NONE,
855          };
856 
857          struct dri2_egl_config *dri2_conf = dri2_add_config(
858             disp, dri2_dpy->driver_configs[j], surface_type, config_attrs);
859          if (dri2_conf)
860             format_count[i]++;
861       }
862 
863       if (visuals[i].hal_format == HAL_PIXEL_FORMAT_RGBA_8888 && format_count[i])
864          has_rgba = true;
865    }
866 
867    for (int i = 0; i < ARRAY_SIZE(format_count); i++) {
868       if (!format_count[i]) {
869          _eglLog(_EGL_DEBUG, "No DRI config supports native format 0x%x",
870                  visuals[i].hal_format);
871       }
872    }
873 }
874 
875 static const struct dri2_egl_display_vtbl droid_display_vtbl = {
876    .authenticate = NULL,
877    .create_window_surface = droid_create_window_surface,
878    .create_pbuffer_surface = droid_create_pbuffer_surface,
879    .destroy_surface = droid_destroy_surface,
880    .create_image = droid_create_image_khr,
881    .swap_buffers = droid_swap_buffers,
882    .swap_interval = droid_swap_interval,
883    .query_buffer_age = droid_query_buffer_age,
884    .query_surface = droid_query_surface,
885    .get_dri_drawable = dri2_surface_get_dri_drawable,
886    .set_shared_buffer_mode = droid_set_shared_buffer_mode,
887 };
888 
889 static const __DRIimageLoaderExtension droid_image_loader_extension = {
890    .base = {__DRI_IMAGE_LOADER, 4},
891 
892    .getBuffers = droid_image_get_buffers,
893    .flushFrontBuffer = droid_flush_front_buffer,
894    .getCapability = droid_get_capability,
895    .flushSwapBuffers = NULL,
896    .destroyLoaderImageState = droid_destroy_loader_image_state,
897 };
898 
899 static void
droid_display_shared_buffer(__DRIdrawable * driDrawable,int fence_fd,void * loaderPrivate)900 droid_display_shared_buffer(__DRIdrawable *driDrawable, int fence_fd,
901                             void *loaderPrivate)
902 {
903    struct dri2_egl_surface *dri2_surf = loaderPrivate;
904    struct ANativeWindowBuffer *old_buffer UNUSED = dri2_surf->buffer;
905 
906    if (!_eglSurfaceInSharedBufferMode(&dri2_surf->base)) {
907       _eglLog(_EGL_WARNING, "%s: internal error: buffer is not shared",
908               __func__);
909       return;
910    }
911 
912    if (fence_fd >= 0) {
913       /* The driver's fence is more recent than the surface's out fence, if it
914        * exists at all. So use the driver's fence.
915        */
916       if (dri2_surf->out_fence_fd >= 0) {
917          close(dri2_surf->out_fence_fd);
918          dri2_surf->out_fence_fd = -1;
919       }
920    } else if (dri2_surf->out_fence_fd >= 0) {
921       fence_fd = dri2_surf->out_fence_fd;
922       dri2_surf->out_fence_fd = -1;
923    }
924 
925    if (ANativeWindow_queueBuffer(dri2_surf->window, dri2_surf->buffer,
926                                  fence_fd)) {
927       _eglLog(_EGL_WARNING, "%s: ANativeWindow_queueBuffer failed", __func__);
928       close(fence_fd);
929       return;
930    }
931 
932    fence_fd = -1;
933 
934    if (ANativeWindow_dequeueBuffer(dri2_surf->window, &dri2_surf->buffer,
935                                    &fence_fd)) {
936       /* Tear down the surface because it no longer has a back buffer. */
937       struct dri2_egl_display *dri2_dpy =
938          dri2_egl_display(dri2_surf->base.Resource.Display);
939 
940       _eglLog(_EGL_WARNING, "%s: ANativeWindow_dequeueBuffer failed", __func__);
941 
942       dri2_surf->base.Lost = true;
943       dri2_surf->buffer = NULL;
944       dri2_surf->back = NULL;
945 
946       if (dri2_surf->dri_image_back) {
947          dri2_dpy->image->destroyImage(dri2_surf->dri_image_back);
948          dri2_surf->dri_image_back = NULL;
949       }
950 
951       dri2_dpy->flush->invalidate(dri2_surf->dri_drawable);
952       return;
953    }
954 
955    close_in_fence_fd(dri2_surf);
956    validate_fence_fd(fence_fd);
957    dri2_surf->in_fence_fd = fence_fd;
958    handle_in_fence_fd(dri2_surf, dri2_surf->dri_image_back);
959 }
960 
961 static const __DRImutableRenderBufferLoaderExtension
962    droid_mutable_render_buffer_extension = {
963       .base = {__DRI_MUTABLE_RENDER_BUFFER_LOADER, 1},
964       .displaySharedBuffer = droid_display_shared_buffer,
965 };
966 
967 static const __DRIextension *droid_image_loader_extensions[] = {
968    &droid_image_loader_extension.base,
969    &image_lookup_extension.base,
970    &use_invalidate.base,
971    &droid_mutable_render_buffer_extension.base,
972    NULL,
973 };
974 
975 static EGLBoolean
droid_load_driver(_EGLDisplay * disp,bool swrast)976 droid_load_driver(_EGLDisplay *disp, bool swrast)
977 {
978    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
979 
980    dri2_dpy->driver_name = loader_get_driver_for_fd(dri2_dpy->fd_render_gpu);
981    if (dri2_dpy->driver_name == NULL)
982       return false;
983 
984    if (swrast) {
985       /* Use kms swrast only with vgem / virtio_gpu.
986        * virtio-gpu fallbacks to software rendering when 3D features
987        * are unavailable since 6c5ab.
988        */
989       if (strcmp(dri2_dpy->driver_name, "vgem") == 0 ||
990           strcmp(dri2_dpy->driver_name, "virtio_gpu") == 0) {
991          free(dri2_dpy->driver_name);
992          dri2_dpy->driver_name = strdup("kms_swrast");
993       } else {
994          goto error;
995       }
996    }
997 
998    dri2_dpy->loader_extensions = droid_image_loader_extensions;
999    if (!dri2_load_driver_dri3(disp)) {
1000       goto error;
1001    }
1002 
1003    return true;
1004 
1005 error:
1006    free(dri2_dpy->driver_name);
1007    dri2_dpy->driver_name = NULL;
1008    return false;
1009 }
1010 
1011 static void
droid_unload_driver(_EGLDisplay * disp)1012 droid_unload_driver(_EGLDisplay *disp)
1013 {
1014    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1015 
1016    dlclose(dri2_dpy->driver);
1017    dri2_dpy->driver = NULL;
1018    free(dri2_dpy->driver_name);
1019    dri2_dpy->driver_name = NULL;
1020 }
1021 
1022 static int
droid_filter_device(_EGLDisplay * disp,int fd,const char * vendor)1023 droid_filter_device(_EGLDisplay *disp, int fd, const char *vendor)
1024 {
1025    drmVersionPtr ver = drmGetVersion(fd);
1026    if (!ver)
1027       return -1;
1028 
1029    if (strcmp(vendor, ver->name) != 0) {
1030       drmFreeVersion(ver);
1031       return -1;
1032    }
1033 
1034    drmFreeVersion(ver);
1035    return 0;
1036 }
1037 
1038 static EGLBoolean
droid_probe_device(_EGLDisplay * disp,bool swrast)1039 droid_probe_device(_EGLDisplay *disp, bool swrast)
1040 {
1041    /* Check that the device is supported, by attempting to:
1042     * - load the dri module
1043     * - and, create a screen
1044     */
1045    if (!droid_load_driver(disp, swrast))
1046       return EGL_FALSE;
1047 
1048    if (!dri2_create_screen(disp)) {
1049       _eglLog(_EGL_WARNING, "DRI2: failed to create screen");
1050       droid_unload_driver(disp);
1051       return EGL_FALSE;
1052    }
1053    return EGL_TRUE;
1054 }
1055 
1056 static EGLBoolean
droid_open_device(_EGLDisplay * disp,bool swrast)1057 droid_open_device(_EGLDisplay *disp, bool swrast)
1058 {
1059 #define MAX_DRM_DEVICES 64
1060    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1061    _EGLDevice *dev_list = _eglGlobal.DeviceList;
1062    drmDevicePtr device;
1063 
1064    char *vendor_name = NULL;
1065    char vendor_buf[PROPERTY_VALUE_MAX];
1066 
1067 #ifdef EGL_FORCE_RENDERNODE
1068    const unsigned node_type = DRM_NODE_RENDER;
1069 #else
1070    const unsigned node_type = swrast ? DRM_NODE_PRIMARY : DRM_NODE_RENDER;
1071 #endif
1072 
1073    if (property_get("drm.gpu.vendor_name", vendor_buf, NULL) > 0)
1074       vendor_name = vendor_buf;
1075 
1076    while (dev_list) {
1077       if (!_eglDeviceSupports(dev_list, _EGL_DEVICE_DRM))
1078          goto next;
1079 
1080       device = _eglDeviceDrm(dev_list);
1081       assert(device);
1082 
1083       if (!(device->available_nodes & (1 << node_type)))
1084          goto next;
1085 
1086       dri2_dpy->fd_render_gpu = loader_open_device(device->nodes[node_type]);
1087       if (dri2_dpy->fd_render_gpu < 0) {
1088          _eglLog(_EGL_WARNING, "%s() Failed to open DRM device %s", __func__,
1089                  device->nodes[node_type]);
1090          goto next;
1091       }
1092 
1093       /* If a vendor is explicitly provided, we use only that.
1094        * Otherwise we fall-back the first device that is supported.
1095        */
1096       if (vendor_name) {
1097          if (droid_filter_device(disp, dri2_dpy->fd_render_gpu, vendor_name)) {
1098             /* Device does not match - try next device */
1099             close(dri2_dpy->fd_render_gpu);
1100             dri2_dpy->fd_render_gpu = -1;
1101             goto next;
1102          }
1103          /* If the requested device matches - use it. Regardless if
1104           * init fails, do not fall-back to any other device.
1105           */
1106          if (!droid_probe_device(disp, false)) {
1107             close(dri2_dpy->fd_render_gpu);
1108             dri2_dpy->fd_render_gpu = -1;
1109          }
1110 
1111          break;
1112       }
1113       if (droid_probe_device(disp, swrast))
1114          break;
1115 
1116       /* No explicit request - attempt the next device */
1117       close(dri2_dpy->fd_render_gpu);
1118       dri2_dpy->fd_render_gpu = -1;
1119 
1120    next:
1121       dev_list = _eglDeviceNext(dev_list);
1122    }
1123 
1124    if (dri2_dpy->fd_render_gpu < 0) {
1125       _eglLog(_EGL_WARNING, "Failed to open %s DRM device",
1126               vendor_name ? "desired" : "any");
1127       return EGL_FALSE;
1128    }
1129 
1130    return EGL_TRUE;
1131 }
1132 
1133 EGLBoolean
dri2_initialize_android(_EGLDisplay * disp)1134 dri2_initialize_android(_EGLDisplay *disp)
1135 {
1136    bool device_opened = false;
1137    struct dri2_egl_display *dri2_dpy;
1138    const char *err;
1139 
1140    dri2_dpy = calloc(1, sizeof(*dri2_dpy));
1141    if (!dri2_dpy)
1142       return _eglError(EGL_BAD_ALLOC, "eglInitialize");
1143 
1144    dri2_dpy->fd_render_gpu = -1;
1145    dri2_dpy->fd_display_gpu = -1;
1146 
1147    dri2_dpy->gralloc = u_gralloc_create(U_GRALLOC_TYPE_AUTO);
1148    if (dri2_dpy->gralloc == NULL) {
1149       err = "DRI2: failed to get gralloc";
1150       goto cleanup;
1151    }
1152 
1153    disp->DriverData = (void *)dri2_dpy;
1154    device_opened = droid_open_device(disp, disp->Options.ForceSoftware);
1155 
1156    if (!device_opened) {
1157       err = "DRI2: failed to open device";
1158       goto cleanup;
1159    }
1160 
1161    dri2_dpy->fd_display_gpu = dri2_dpy->fd_render_gpu;
1162 
1163    if (!dri2_setup_extensions(disp)) {
1164       err = "DRI2: failed to setup extensions";
1165       goto cleanup;
1166    }
1167 
1168    if (!dri2_setup_device(disp, false)) {
1169       err = "DRI2: failed to setup EGLDevice";
1170       goto cleanup;
1171    }
1172 
1173    dri2_setup_screen(disp);
1174 
1175    /* We set the maximum swap interval as 1 for Android platform, since it is
1176     * the maximum value supported by Android according to the value of
1177     * ANativeWindow::maxSwapInterval.
1178     */
1179    dri2_setup_swap_interval(disp, 1);
1180 
1181    disp->Extensions.ANDROID_framebuffer_target = EGL_TRUE;
1182    disp->Extensions.ANDROID_image_native_buffer = EGL_TRUE;
1183    disp->Extensions.ANDROID_recordable = EGL_TRUE;
1184 
1185    /* Querying buffer age requires a buffer to be dequeued.  Without
1186     * EGL_ANDROID_native_fence_sync, dequeue might call eglClientWaitSync and
1187     * result in a deadlock (the lock is already held by eglQuerySurface).
1188     */
1189    if (disp->Extensions.ANDROID_native_fence_sync) {
1190       disp->Extensions.EXT_buffer_age = EGL_TRUE;
1191    } else {
1192       /* disable KHR_partial_update that might have been enabled in
1193        * dri2_setup_screen
1194        */
1195       disp->Extensions.KHR_partial_update = EGL_FALSE;
1196    }
1197 
1198    disp->Extensions.KHR_image = EGL_TRUE;
1199 
1200    dri2_dpy->front_rendering_usage = 0;
1201 #if ANDROID_API_LEVEL >= 24
1202    if (dri2_dpy->mutable_render_buffer &&
1203        dri2_dpy->loader_extensions == droid_image_loader_extensions &&
1204        /* In big GL, front rendering is done at the core API level by directly
1205         * rendering on the front buffer. However, in ES, the front buffer is
1206         * completely inaccessible through the core ES API.
1207         *
1208         * EGL_KHR_mutable_render_buffer is Android's attempt to re-introduce
1209         * front rendering into ES by squeezing into EGL. Unlike big GL, this
1210         * extension redirects GL_BACK used by ES for front rendering. Thus we
1211         * restrict the enabling of this extension to ES only.
1212         */
1213        (disp->ClientAPIs & ~(EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT |
1214                              EGL_OPENGL_ES3_BIT_KHR)) == 0) {
1215       /* For cros gralloc, if the front rendering query is supported, then all
1216        * available window surface configs support front rendering because:
1217        *
1218        * 1) EGL queries cros gralloc for the front rendering usage bit here
1219        * 2) EGL combines the front rendering usage bit with the existing usage
1220        *    if the window surface requests mutable render buffer
1221        * 3) EGL sets the combined usage onto the ANativeWindow and the next
1222        *    dequeueBuffer will ask gralloc for an allocation/re-allocation with
1223        *    the new combined usage
1224        * 4) cros gralloc(on top of minigbm) resolves the front rendering usage
1225        *    bit into either BO_USE_FRONT_RENDERING or BO_USE_LINEAR based on
1226        *    the format support checking.
1227        *
1228        * So at least we can force BO_USE_LINEAR as the fallback.
1229        */
1230       uint64_t front_rendering_usage = 0;
1231       if (!u_gralloc_get_front_rendering_usage(dri2_dpy->gralloc,
1232                                                &front_rendering_usage)) {
1233          dri2_dpy->front_rendering_usage = front_rendering_usage;
1234          disp->Extensions.KHR_mutable_render_buffer = EGL_TRUE;
1235       }
1236    }
1237 #endif
1238 
1239    /* Create configs *after* enabling extensions because presence of DRI
1240     * driver extensions can affect the capabilities of EGLConfigs.
1241     */
1242    droid_add_configs_for_visuals(disp);
1243 
1244    /* Fill vtbl last to prevent accidentally calling virtual function during
1245     * initialization.
1246     */
1247    dri2_dpy->vtbl = &droid_display_vtbl;
1248 
1249    return EGL_TRUE;
1250 
1251 cleanup:
1252    dri2_display_destroy(disp);
1253    return _eglError(EGL_NOT_INITIALIZED, err);
1254 }
1255