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