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