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