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