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