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