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