platform_android.c 50.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/*
 * Mesa 3-D graphics library
 *
 * Copyright (C) 2010-2011 Chia-I Wu <olvaffe@gmail.com>
 * Copyright (C) 2010-2011 LunarG Inc.
 *
 * Based on platform_x11, which has
 *
 * Copyright © 2011 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

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

41
#include "loader.h"
42
#include "egl_dri2.h"
43
#include "egl_dri2_fallbacks.h"
44 45 46

#ifdef HAVE_DRM_GRALLOC
#include <gralloc_drm_handle.h>
47
#include "gralloc_drm.h"
48
#endif /* HAVE_DRM_GRALLOC */
49

50 51
#define ALIGN(val, align)	(((val) + (align) - 1) & ~((align) - 1))

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
struct droid_yuv_format {
   /* Lookup keys */
   int native; /* HAL_PIXEL_FORMAT_ */
   int is_ycrcb; /* 0 if chroma order is {Cb, Cr}, 1 if {Cr, Cb} */
   int chroma_step; /* Distance in bytes between subsequent chroma pixels. */

   /* Result */
   int fourcc; /* __DRI_IMAGE_FOURCC_ */
};

/* The following table is used to look up a DRI image FourCC based
 * on native format and information contained in android_ycbcr struct. */
static const struct droid_yuv_format droid_yuv_formats[] = {
   /* Native format, YCrCb, Chroma step, DRI image FourCC */
   { HAL_PIXEL_FORMAT_YCbCr_420_888,   0, 2, __DRI_IMAGE_FOURCC_NV12 },
   { HAL_PIXEL_FORMAT_YCbCr_420_888,   0, 1, __DRI_IMAGE_FOURCC_YUV420 },
   { HAL_PIXEL_FORMAT_YCbCr_420_888,   1, 1, __DRI_IMAGE_FOURCC_YVU420 },
   { HAL_PIXEL_FORMAT_YV12,            1, 1, __DRI_IMAGE_FOURCC_YVU420 },
70 71 72 73 74
   /* HACK: See droid_create_image_from_prime_fd() and
    * https://issuetracker.google.com/32077885. */
   { HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED,   0, 2, __DRI_IMAGE_FOURCC_NV12 },
   { HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED,   0, 1, __DRI_IMAGE_FOURCC_YUV420 },
   { HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED,   1, 1, __DRI_IMAGE_FOURCC_YVU420 },
Lionel Landwerlin's avatar
Lionel Landwerlin committed
75
   { HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED,   1, 1, __DRI_IMAGE_FOURCC_AYUV },
76 77 78 79 80
};

static int
get_fourcc_yuv(int native, int is_ycrcb, int chroma_step)
{
81
   for (int i = 0; i < ARRAY_SIZE(droid_yuv_formats); ++i)
82 83 84 85 86 87 88 89 90 91 92
      if (droid_yuv_formats[i].native == native &&
          droid_yuv_formats[i].is_ycrcb == is_ycrcb &&
          droid_yuv_formats[i].chroma_step == chroma_step)
         return droid_yuv_formats[i].fourcc;

   return -1;
}

static bool
is_yuv(int native)
{
93
   for (int i = 0; i < ARRAY_SIZE(droid_yuv_formats); ++i)
94 95 96 97 98 99
      if (droid_yuv_formats[i].native == native)
         return true;

   return false;
}

100 101 102 103 104 105 106
static int
get_format_bpp(int native)
{
   int bpp;

   switch (native) {
   case HAL_PIXEL_FORMAT_RGBA_8888:
107 108 109 110 111
   case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
      /*
       * HACK: Hardcode this to RGBX_8888 as per cros_gralloc hack.
       * TODO: Remove this once https://issuetracker.google.com/32077885 is fixed.
       */
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
   case HAL_PIXEL_FORMAT_RGBX_8888:
   case HAL_PIXEL_FORMAT_BGRA_8888:
      bpp = 4;
      break;
   case HAL_PIXEL_FORMAT_RGB_565:
      bpp = 2;
      break;
   default:
      bpp = 0;
      break;
   }

   return bpp;
}

127
/* createImageFromFds requires fourcc format */
128
static int get_fourcc(int native)
129
{
130 131 132 133
   switch (native) {
   case HAL_PIXEL_FORMAT_RGB_565:   return __DRI_IMAGE_FOURCC_RGB565;
   case HAL_PIXEL_FORMAT_BGRA_8888: return __DRI_IMAGE_FOURCC_ARGB8888;
   case HAL_PIXEL_FORMAT_RGBA_8888: return __DRI_IMAGE_FOURCC_ABGR8888;
134 135 136 137 138
   case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
      /*
       * HACK: Hardcode this to RGBX_8888 as per cros_gralloc hack.
       * TODO: Remove this once https://issuetracker.google.com/32077885 is fixed.
       */
139 140 141
   case HAL_PIXEL_FORMAT_RGBX_8888: return __DRI_IMAGE_FOURCC_XBGR8888;
   default:
      _eglLog(_EGL_WARNING, "unsupported native buffer format 0x%x", native);
142 143 144 145
   }
   return -1;
}

146 147 148 149 150 151
static int get_format(int format)
{
   switch (format) {
   case HAL_PIXEL_FORMAT_BGRA_8888: return __DRI_IMAGE_FORMAT_ARGB8888;
   case HAL_PIXEL_FORMAT_RGB_565:   return __DRI_IMAGE_FORMAT_RGB565;
   case HAL_PIXEL_FORMAT_RGBA_8888: return __DRI_IMAGE_FORMAT_ABGR8888;
152 153 154 155 156
   case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
      /*
       * HACK: Hardcode this to RGBX_8888 as per cros_gralloc hack.
       * TODO: Revert this once https://issuetracker.google.com/32077885 is fixed.
       */
157 158 159 160 161 162
   case HAL_PIXEL_FORMAT_RGBX_8888: return __DRI_IMAGE_FORMAT_XBGR8888;
   default:
      _eglLog(_EGL_WARNING, "unsupported native buffer format 0x%x", format);
   }
   return -1;
}
163

164 165 166 167 168 169 170 171 172 173 174 175
static int
get_native_buffer_fd(struct ANativeWindowBuffer *buf)
{
   native_handle_t *handle = (native_handle_t *)buf->handle;
   /*
    * Various gralloc implementations exist, but the dma-buf fd tends
    * to be first. Access it directly to avoid a dependency on specific
    * gralloc versions.
    */
   return (handle && handle->numFds) ? handle->data[0] : -1;
}

176
#ifdef HAVE_DRM_GRALLOC
177
static int
Chia-I Wu's avatar
Chia-I Wu committed
178
get_native_buffer_name(struct ANativeWindowBuffer *buf)
179
{
180
   return gralloc_drm_get_gem_handle(buf->handle);
181
}
182
#endif /* HAVE_DRM_GRALLOC */
183 184 185 186

static EGLBoolean
droid_window_dequeue_buffer(struct dri2_egl_surface *dri2_surf)
{
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
   int fence_fd;

   if (dri2_surf->window->dequeueBuffer(dri2_surf->window, &dri2_surf->buffer,
                                        &fence_fd))
      return EGL_FALSE;

   /* If access to the buffer is controlled by a sync fence, then block on the
    * fence.
    *
    * It may be more performant to postpone blocking until there is an
    * immediate need to write to the buffer. But doing so would require adding
    * hooks to the DRI2 loader.
    *
    * From the ANativeWindow::dequeueBuffer documentation:
    *
    *    The libsync fence file descriptor returned in the int pointed to by
    *    the fenceFd argument will refer to the fence that must signal
    *    before the dequeued buffer may be written to.  A value of -1
    *    indicates that the caller may access the buffer immediately without
    *    waiting on a fence.  If a valid file descriptor is returned (i.e.
    *    any value except -1) then the caller is responsible for closing the
    *    file descriptor.
    */
    if (fence_fd >= 0) {
       /* From the SYNC_IOC_WAIT documentation in <linux/sync.h>:
        *
        *    Waits indefinitely if timeout < 0.
        */
        int timeout = -1;
        sync_wait(fence_fd, timeout);
        close(fence_fd);
   }

   dri2_surf->buffer->common.incRef(&dri2_surf->buffer->common);
221

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
   /* Record all the buffers created by ANativeWindow and update back buffer
    * for updating buffer's age in swap_buffers.
    */
   EGLBoolean updated = EGL_FALSE;
   for (int i = 0; i < ARRAY_SIZE(dri2_surf->color_buffers); i++) {
      if (!dri2_surf->color_buffers[i].buffer) {
         dri2_surf->color_buffers[i].buffer = dri2_surf->buffer;
      }
      if (dri2_surf->color_buffers[i].buffer == dri2_surf->buffer) {
         dri2_surf->back = &dri2_surf->color_buffers[i];
         updated = EGL_TRUE;
         break;
      }
   }

   if (!updated) {
      /* In case of all the buffers were recreated by ANativeWindow, reset
       * the color_buffers
       */
      for (int i = 0; i < ARRAY_SIZE(dri2_surf->color_buffers); i++) {
         dri2_surf->color_buffers[i].buffer = NULL;
         dri2_surf->color_buffers[i].age = 0;
      }
      dri2_surf->color_buffers[0].buffer = dri2_surf->buffer;
      dri2_surf->back = &dri2_surf->color_buffers[0];
   }

249 250 251 252
   return EGL_TRUE;
}

static EGLBoolean
253
droid_window_enqueue_buffer(_EGLDisplay *disp, struct dri2_egl_surface *dri2_surf)
254
{
255 256
   struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);

257 258 259 260 261 262
   /* To avoid blocking other EGL calls, release the display mutex before
    * we enter droid_window_enqueue_buffer() and re-acquire the mutex upon
    * return.
    */
   mtx_unlock(&disp->Mutex);

263 264 265 266 267
   /* Queue the buffer with stored out fence fd. The ANativeWindow or buffer
    * consumer may choose to wait for the fence to signal before accessing
    * it. If fence fd value is -1, buffer can be accessed by consumer
    * immediately. Consumer or application shouldn't rely on timestamp
    * associated with fence if the fence fd is -1.
268
    *
269 270 271
    * Ownership of fd is transferred to consumer after queueBuffer and the
    * consumer is responsible for closing it. Caller must not use the fd
    * after passing it to queueBuffer.
272
    */
273 274
   int fence_fd = dri2_surf->out_fence_fd;
   dri2_surf->out_fence_fd = -1;
275 276
   dri2_surf->window->queueBuffer(dri2_surf->window, dri2_surf->buffer,
                                  fence_fd);
277 278 279

   dri2_surf->buffer->common.decRef(&dri2_surf->buffer->common);
   dri2_surf->buffer = NULL;
280
   dri2_surf->back = NULL;
281

282
   mtx_lock(&disp->Mutex);
283

284 285 286
   if (dri2_surf->dri_image_back) {
      dri2_dpy->image->destroyImage(dri2_surf->dri_image_back);
      dri2_surf->dri_image_back = NULL;
287 288
   }

289 290 291 292
   return EGL_TRUE;
}

static void
293
droid_window_cancel_buffer(struct dri2_egl_surface *dri2_surf)
294
{
295
   int ret;
296
   int fence_fd = dri2_surf->out_fence_fd;
297

298 299 300
   dri2_surf->out_fence_fd = -1;
   ret = dri2_surf->window->cancelBuffer(dri2_surf->window,
                                         dri2_surf->buffer, fence_fd);
301 302
   if (ret < 0) {
      _eglLog(_EGL_WARNING, "ANativeWindow::cancelBuffer failed");
303
      dri2_surf->base.Lost = EGL_TRUE;
304
   }
305 306
}

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
static bool
droid_set_shared_buffer_mode(_EGLDisplay *disp, _EGLSurface *surf, bool mode)
{
#if ANDROID_API_LEVEL >= 24
   struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
   struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
   struct ANativeWindow *window = dri2_surf->window;

   assert(surf->Type == EGL_WINDOW_BIT);
   assert(_eglSurfaceHasMutableRenderBuffer(&dri2_surf->base));

   _eglLog(_EGL_DEBUG, "%s: mode=%d", __func__, mode);

   if (native_window_set_shared_buffer_mode(window, mode)) {
      _eglLog(_EGL_WARNING, "failed native_window_set_shared_buffer_mode"
              "(window=%p, mode=%d)", window, mode);
      return false;
   }

   return true;
#else
   _eglLog(_EGL_FATAL, "%s:%d: internal error: unreachable", __FILE__, __LINE__);
   return false;
#endif
}

333 334
static _EGLSurface *
droid_create_surface(_EGLDriver *drv, _EGLDisplay *disp, EGLint type,
335
		    _EGLConfig *conf, void *native_window,
336 337
		    const EGLint *attrib_list)
{
338
   __DRIcreateNewDrawableFunc createNewDrawable;
339 340 341
   struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
   struct dri2_egl_config *dri2_conf = dri2_egl_config(conf);
   struct dri2_egl_surface *dri2_surf;
342
   struct ANativeWindow *window = native_window;
343
   const __DRIconfig *config;
344

345 346 347 348 349 350
   dri2_surf = calloc(1, sizeof *dri2_surf);
   if (!dri2_surf) {
      _eglError(EGL_BAD_ALLOC, "droid_create_surface");
      return NULL;
   }

351
   if (!dri2_init_surface(&dri2_surf->base, disp, type, conf, attrib_list, true))
352 353 354 355 356
      goto cleanup_surface;

   if (type == EGL_WINDOW_BIT) {
      int format;

357
      if (window->common.magic != ANDROID_NATIVE_WINDOW_MAGIC) {
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
         _eglError(EGL_BAD_NATIVE_WINDOW, "droid_create_surface");
         goto cleanup_surface;
      }
      if (window->query(window, NATIVE_WINDOW_FORMAT, &format)) {
         _eglError(EGL_BAD_NATIVE_WINDOW, "droid_create_surface");
         goto cleanup_surface;
      }

      if (format != dri2_conf->base.NativeVisualID) {
         _eglLog(_EGL_WARNING, "Native format mismatch: 0x%x != 0x%x",
               format, dri2_conf->base.NativeVisualID);
      }

      window->query(window, NATIVE_WINDOW_WIDTH, &dri2_surf->base.Width);
      window->query(window, NATIVE_WINDOW_HEIGHT, &dri2_surf->base.Height);
   }
374

375
   config = dri2_get_dri_config(dri2_conf, type,
376
                                dri2_surf->base.GLColorspace);
377 378
   if (!config) {
      _eglError(EGL_BAD_MATCH, "Unsupported surfacetype/colorspace configuration");
379
      goto cleanup_surface;
380
   }
381

382 383 384 385 386 387 388
   if (dri2_dpy->image_driver)
      createNewDrawable = dri2_dpy->image_driver->createNewDrawable;
   else
      createNewDrawable = dri2_dpy->dri2->createNewDrawable;

   dri2_surf->dri_drawable = (*createNewDrawable)(dri2_dpy->dri_screen, config,
                                                  dri2_surf);
389
   if (dri2_surf->dri_drawable == NULL) {
390
      _eglError(EGL_BAD_ALLOC, "createNewDrawable");
391
      goto cleanup_surface;
392 393
   }

394 395 396 397
   if (window) {
      window->common.incRef(&window->common);
      dri2_surf->window = window;
   }
398 399 400

   return &dri2_surf->base;

401
cleanup_surface:
402 403 404 405 406 407 408
   free(dri2_surf);

   return NULL;
}

static _EGLSurface *
droid_create_window_surface(_EGLDriver *drv, _EGLDisplay *disp,
409 410
                            _EGLConfig *conf, void *native_window,
                            const EGLint *attrib_list)
411 412
{
   return droid_create_surface(drv, disp, EGL_WINDOW_BIT, conf,
413
                               native_window, attrib_list);
414 415 416 417 418 419
}

static _EGLSurface *
droid_create_pbuffer_surface(_EGLDriver *drv, _EGLDisplay *disp,
			    _EGLConfig *conf, const EGLint *attrib_list)
{
420 421
   return droid_create_surface(drv, disp, EGL_PBUFFER_BIT, conf,
			      NULL, attrib_list);
422 423 424 425 426 427 428 429
}

static EGLBoolean
droid_destroy_surface(_EGLDriver *drv, _EGLDisplay *disp, _EGLSurface *surf)
{
   struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
   struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);

430
   dri2_egl_surface_free_local_buffers(dri2_surf);
431

432 433
   if (dri2_surf->base.Type == EGL_WINDOW_BIT) {
      if (dri2_surf->buffer)
434
         droid_window_cancel_buffer(dri2_surf);
435

436 437
      dri2_surf->window->common.decRef(&dri2_surf->window->common);
   }
438

439 440 441 442 443 444 445 446 447 448 449 450
   if (dri2_surf->dri_image_back) {
      _eglLog(_EGL_DEBUG, "%s : %d : destroy dri_image_back", __func__, __LINE__);
      dri2_dpy->image->destroyImage(dri2_surf->dri_image_back);
      dri2_surf->dri_image_back = NULL;
   }

   if (dri2_surf->dri_image_front) {
      _eglLog(_EGL_DEBUG, "%s : %d : destroy dri_image_front", __func__, __LINE__);
      dri2_dpy->image->destroyImage(dri2_surf->dri_image_front);
      dri2_surf->dri_image_front = NULL;
   }

451
   dri2_dpy->core->destroyDrawable(dri2_surf->dri_drawable);
452

453
   dri2_fini_surface(surf);
454 455 456 457 458
   free(dri2_surf);

   return EGL_TRUE;
}

459 460 461 462 463 464 465 466 467 468 469 470 471 472
static EGLBoolean
droid_swap_interval(_EGLDriver *drv, _EGLDisplay *dpy,
                   _EGLSurface *surf, EGLint interval)
{
   struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
   struct ANativeWindow *window = dri2_surf->window;

   if (window->setSwapInterval(window, interval))
      return EGL_FALSE;

   surf->SwapInterval = interval;
   return EGL_TRUE;
}

473 474 475
static int
update_buffers(struct dri2_egl_surface *dri2_surf)
{
476 477 478
   if (dri2_surf->base.Lost)
      return -1;

479 480 481 482
   if (dri2_surf->base.Type != EGL_WINDOW_BIT)
      return 0;

   /* try to dequeue the next back buffer */
483 484
   if (!dri2_surf->buffer && !droid_window_dequeue_buffer(dri2_surf)) {
      _eglLog(_EGL_WARNING, "Could not dequeue buffer from native window");
485
      dri2_surf->base.Lost = EGL_TRUE;
486
      return -1;
487
   }
488 489 490 491

   /* free outdated buffers and update the surface size */
   if (dri2_surf->base.Width != dri2_surf->buffer->width ||
       dri2_surf->base.Height != dri2_surf->buffer->height) {
492
      dri2_egl_surface_free_local_buffers(dri2_surf);
493 494 495 496 497 498 499
      dri2_surf->base.Width = dri2_surf->buffer->width;
      dri2_surf->base.Height = dri2_surf->buffer->height;
   }

   return 0;
}

500
static int
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
get_front_bo(struct dri2_egl_surface *dri2_surf, unsigned int format)
{
   struct dri2_egl_display *dri2_dpy =
      dri2_egl_display(dri2_surf->base.Resource.Display);

   if (dri2_surf->dri_image_front)
      return 0;

   if (dri2_surf->base.Type == EGL_WINDOW_BIT) {
      /* According current EGL spec, front buffer rendering
       * for window surface is not supported now.
       * and mesa doesn't have the implementation of this case.
       * Add warning message, but not treat it as error.
       */
      _eglLog(_EGL_DEBUG, "DRI driver requested unsupported front buffer for window surface");
   } else if (dri2_surf->base.Type == EGL_PBUFFER_BIT) {
      dri2_surf->dri_image_front =
          dri2_dpy->image->createImage(dri2_dpy->dri_screen,
                                              dri2_surf->base.Width,
                                              dri2_surf->base.Height,
                                              format,
                                              0,
                                              dri2_surf);
      if (!dri2_surf->dri_image_front) {
         _eglLog(_EGL_WARNING, "dri2_image_front allocation failed");
         return -1;
      }
   }

   return 0;
}

static int
534
get_back_bo(struct dri2_egl_surface *dri2_surf)
535 536 537
{
   struct dri2_egl_display *dri2_dpy =
      dri2_egl_display(dri2_surf->base.Resource.Display);
538
   int fourcc, pitch;
539 540
   int offset = 0, fd;

541 542
   if (dri2_surf->dri_image_back)
      return 0;
543

544 545 546 547 548
   if (dri2_surf->base.Type == EGL_WINDOW_BIT) {
      if (!dri2_surf->buffer) {
         _eglLog(_EGL_WARNING, "Could not get native buffer");
         return -1;
      }
549

550 551 552 553 554
      fd = get_native_buffer_fd(dri2_surf->buffer);
      if (fd < 0) {
         _eglLog(_EGL_WARNING, "Could not get native buffer FD");
         return -1;
      }
555

556
      fourcc = get_fourcc(dri2_surf->buffer->format);
557

558 559
      pitch = dri2_surf->buffer->stride *
         get_format_bpp(dri2_surf->buffer->format);
560

561 562 563 564 565
      if (fourcc == -1 || pitch == 0) {
         _eglLog(_EGL_WARNING, "Invalid buffer fourcc(%x) or pitch(%d)",
                 fourcc, pitch);
         return -1;
      }
566

567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
      dri2_surf->dri_image_back =
         dri2_dpy->image->createImageFromFds(dri2_dpy->dri_screen,
                                             dri2_surf->base.Width,
                                             dri2_surf->base.Height,
                                             fourcc,
                                             &fd,
                                             1,
                                             &pitch,
                                             &offset,
                                             dri2_surf);
      if (!dri2_surf->dri_image_back) {
         _eglLog(_EGL_WARNING, "failed to create DRI image from FD");
         return -1;
      }
   } else if (dri2_surf->base.Type == EGL_PBUFFER_BIT) {
      /* The EGL 1.5 spec states that pbuffers are single-buffered. Specifically,
       * the spec states that they have a back buffer but no front buffer, in
       * contrast to pixmaps, which have a front buffer but no back buffer.
       *
       * Single-buffered surfaces with no front buffer confuse Mesa; so we deviate
       * from the spec, following the precedent of Mesa's EGL X11 platform. The
       * X11 platform correctly assigns pbuffers to single-buffered configs, but
       * assigns the pbuffer a front buffer instead of a back buffer.
       *
       * Pbuffers in the X11 platform mostly work today, so let's just copy its
       * behavior instead of trying to fix (and hence potentially breaking) the
       * world.
       */
      _eglLog(_EGL_DEBUG, "DRI driver requested unsupported back buffer for pbuffer surface");
   }
597 598 599 600

   return 0;
}

601 602 603 604 605
/* Some drivers will pass multiple bits in buffer_mask.
 * For such case, will go through all the bits, and
 * will not return error when unsupported buffer is requested, only
 * return error when the allocation for supported buffer failed.
 */
606 607 608 609 610 611 612 613 614 615
static int
droid_image_get_buffers(__DRIdrawable *driDrawable,
                  unsigned int format,
                  uint32_t *stamp,
                  void *loaderPrivate,
                  uint32_t buffer_mask,
                  struct __DRIimageList *images)
{
   struct dri2_egl_surface *dri2_surf = loaderPrivate;

616
   images->image_mask = 0;
617 618
   images->front = NULL;
   images->back = NULL;
619

620 621 622
   if (update_buffers(dri2_surf) < 0)
      return 0;

623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
   if (_eglSurfaceInSharedBufferMode(&dri2_surf->base)) {
      if (get_back_bo(dri2_surf) < 0)
         return 0;

      /* We have dri_image_back because this is a window surface and
       * get_back_bo() succeeded.
       */
      assert(dri2_surf->dri_image_back);
      images->back = dri2_surf->dri_image_back;
      images->image_mask |= __DRI_IMAGE_BUFFER_SHARED;

      /* There exists no accompanying back nor front buffer. */
      return 1;
   }

638
   if (buffer_mask & __DRI_IMAGE_BUFFER_FRONT) {
639
      if (get_front_bo(dri2_surf, format) < 0)
640 641
         return 0;

642 643 644
      if (dri2_surf->dri_image_front) {
         images->front = dri2_surf->dri_image_front;
         images->image_mask |= __DRI_IMAGE_BUFFER_FRONT;
645
      }
646 647
   }

648
   if (buffer_mask & __DRI_IMAGE_BUFFER_BACK) {
649
      if (get_back_bo(dri2_surf) < 0)
650 651
         return 0;

652 653 654 655
      if (dri2_surf->dri_image_back) {
         images->back = dri2_surf->dri_image_back;
         images->image_mask |= __DRI_IMAGE_BUFFER_BACK;
      }
656
   }
657 658 659 660

   return 1;
}

661 662 663 664 665 666 667 668
static EGLint
droid_query_buffer_age(_EGLDriver *drv,
                          _EGLDisplay *disp, _EGLSurface *surface)
{
   struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surface);

   if (update_buffers(dri2_surf) < 0) {
      _eglError(EGL_BAD_ALLOC, "droid_query_buffer_age");
669
      return -1;
670 671
   }

672
   return dri2_surf->back ? dri2_surf->back->age : 0;
673 674
}

675 676 677 678 679
static EGLBoolean
droid_swap_buffers(_EGLDriver *drv, _EGLDisplay *disp, _EGLSurface *draw)
{
   struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
   struct dri2_egl_surface *dri2_surf = dri2_egl_surface(draw);
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
   const bool has_mutable_rb = _eglSurfaceHasMutableRenderBuffer(draw);

   /* From the EGL_KHR_mutable_render_buffer spec (v12):
    *
    *    If surface is a single-buffered window, pixmap, or pbuffer surface
    *    for which there is no pending change to the EGL_RENDER_BUFFER
    *    attribute, eglSwapBuffers has no effect.
    */
   if (has_mutable_rb &&
       draw->RequestedRenderBuffer == EGL_SINGLE_BUFFER &&
       draw->ActiveRenderBuffer == EGL_SINGLE_BUFFER) {
      _eglLog(_EGL_DEBUG, "%s: remain in shared buffer mode", __func__);
      return EGL_TRUE;
   }

695 696 697 698
   for (int i = 0; i < ARRAY_SIZE(dri2_surf->color_buffers); i++) {
      if (dri2_surf->color_buffers[i].age > 0)
         dri2_surf->color_buffers[i].age++;
   }
699 700 701 702 703 704

   /* "XXX: we don't use get_back_bo() since it causes regressions in
    * several dEQP tests.
    */
   if (dri2_surf->back)
      dri2_surf->back->age = 1;
705

706
   dri2_flush_drawable_for_swapbuffers(disp, draw);
707

708 709 710 711 712 713
   /* dri2_surf->buffer can be null even when no error has occured. For
    * example, if the user has called no GL rendering commands since the
    * previous eglSwapBuffers, then the driver may have not triggered
    * a callback to ANativeWindow::dequeueBuffer, in which case
    * dri2_surf->buffer remains null.
    */
714
   if (dri2_surf->buffer)
715
      droid_window_enqueue_buffer(disp, dri2_surf);
716

717
   dri2_dpy->flush->invalidate(dri2_surf->dri_drawable);
718

719 720 721 722 723 724 725 726 727 728 729 730
   /* Update the shared buffer mode */
   if (has_mutable_rb &&
       draw->ActiveRenderBuffer != draw->RequestedRenderBuffer) {
       bool mode = (draw->RequestedRenderBuffer == EGL_SINGLE_BUFFER);
      _eglLog(_EGL_DEBUG, "%s: change to shared buffer mode %d",
              __func__, mode);

      if (!droid_set_shared_buffer_mode(disp, draw, mode))
         return EGL_FALSE;
      draw->ActiveRenderBuffer = draw->RequestedRenderBuffer;
   }

731 732 733
   return EGL_TRUE;
}

734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
#if ANDROID_API_LEVEL >= 23
static EGLBoolean
droid_set_damage_region(_EGLDriver *drv,
                        _EGLDisplay *disp,
                        _EGLSurface *draw, const EGLint* rects, EGLint n_rects)
{
   struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
   struct dri2_egl_surface *dri2_surf = dri2_egl_surface(draw);
   android_native_rect_t* droid_rects = NULL;
   int ret;

   if (n_rects == 0)
      return EGL_TRUE;

   droid_rects = malloc(n_rects * sizeof(android_native_rect_t));
749 750
   if (droid_rects == NULL)
     return _eglError(EGL_BAD_ALLOC, "eglSetDamageRegionKHR");
751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770

   for (EGLint num_drects = 0; num_drects < n_rects; num_drects++) {
      EGLint i = num_drects * 4;
      droid_rects[num_drects].left = rects[i];
      droid_rects[num_drects].bottom = rects[i + 1];
      droid_rects[num_drects].right = rects[i] + rects[i + 2];
      droid_rects[num_drects].top = rects[i + 1] + rects[i + 3];
   }

   /*
    * XXX/TODO: Need to check for other return values
    */

   ret = native_window_set_surface_damage(dri2_surf->window, droid_rects, n_rects);
   free(droid_rects);

   return ret == 0 ? EGL_TRUE : EGL_FALSE;
}
#endif

771
static _EGLImage *
772 773
droid_create_image_from_prime_fd_yuv(_EGLDisplay *disp, _EGLContext *ctx,
                                     struct ANativeWindowBuffer *buf, int fd)
774
{
775 776 777 778 779 780 781 782 783 784 785 786
   struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
   struct android_ycbcr ycbcr;
   size_t offsets[3];
   size_t pitches[3];
   int is_ycrcb;
   int fourcc;
   int ret;

   if (!dri2_dpy->gralloc->lock_ycbcr) {
      _eglLog(_EGL_WARNING, "Gralloc does not support lock_ycbcr");
      return NULL;
   }
787

788 789 790 791
   memset(&ycbcr, 0, sizeof(ycbcr));
   ret = dri2_dpy->gralloc->lock_ycbcr(dri2_dpy->gralloc, buf->handle,
                                       0, 0, 0, 0, 0, &ycbcr);
   if (ret) {
792 793 794 795 796
      /* HACK: See droid_create_image_from_prime_fd() and
       * https://issuetracker.google.com/32077885.*/
      if (buf->format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED)
         return NULL;

797
      _eglLog(_EGL_WARNING, "gralloc->lock_ycbcr failed: %d", ret);
798 799
      return NULL;
   }
800 801 802 803 804 805 806
   dri2_dpy->gralloc->unlock(dri2_dpy->gralloc, buf->handle);

   /* When lock_ycbcr's usage argument contains no SW_READ/WRITE flags
    * it will return the .y/.cb/.cr pointers based on a NULL pointer,
    * so they can be interpreted as offsets. */
   offsets[0] = (size_t)ycbcr.y;
   /* We assume here that all the planes are located in one DMA-buf. */
807
   is_ycrcb = (size_t)ycbcr.cr < (size_t)ycbcr.cb;
808 809 810 811 812 813 814
   if (is_ycrcb) {
      offsets[1] = (size_t)ycbcr.cr;
      offsets[2] = (size_t)ycbcr.cb;
   } else {
      offsets[1] = (size_t)ycbcr.cb;
      offsets[2] = (size_t)ycbcr.cr;
   }
815

816 817 818 819 820 821 822 823 824 825 826 827 828
   /* .ystride is the line length (in bytes) of the Y plane,
    * .cstride is the line length (in bytes) of any of the remaining
    * Cb/Cr/CbCr planes, assumed to be the same for Cb and Cr for fully
    * planar formats. */
   pitches[0] = ycbcr.ystride;
   pitches[1] = pitches[2] = ycbcr.cstride;

   /* .chroma_step is the byte distance between the same chroma channel
    * values of subsequent pixels, assumed to be the same for Cb and Cr. */
   fourcc = get_fourcc_yuv(buf->format, is_ycrcb, ycbcr.chroma_step);
   if (fourcc == -1) {
      _eglLog(_EGL_WARNING, "unsupported YUV format, native = %x, is_ycrcb = %d, chroma_step = %d",
              buf->format, is_ycrcb, ycbcr.chroma_step);
829 830
      return NULL;
   }
831

832
   if (ycbcr.chroma_step == 2) {
Robert Foss's avatar
Robert Foss committed
833
      /* Semi-planar Y + CbCr or Y + CrCb format. */
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850
      const EGLint attr_list_2plane[] = {
         EGL_WIDTH, buf->width,
         EGL_HEIGHT, buf->height,
         EGL_LINUX_DRM_FOURCC_EXT, fourcc,
         EGL_DMA_BUF_PLANE0_FD_EXT, fd,
         EGL_DMA_BUF_PLANE0_PITCH_EXT, pitches[0],
         EGL_DMA_BUF_PLANE0_OFFSET_EXT, offsets[0],
         EGL_DMA_BUF_PLANE1_FD_EXT, fd,
         EGL_DMA_BUF_PLANE1_PITCH_EXT, pitches[1],
         EGL_DMA_BUF_PLANE1_OFFSET_EXT, offsets[1],
         EGL_NONE, 0
      };

      return dri2_create_image_dma_buf(disp, ctx, NULL, attr_list_2plane);
   } else {
      /* Fully planar Y + Cb + Cr or Y + Cr + Cb format. */
      const EGLint attr_list_3plane[] = {
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
         EGL_WIDTH, buf->width,
         EGL_HEIGHT, buf->height,
         EGL_LINUX_DRM_FOURCC_EXT, fourcc,
         EGL_DMA_BUF_PLANE0_FD_EXT, fd,
         EGL_DMA_BUF_PLANE0_PITCH_EXT, pitches[0],
         EGL_DMA_BUF_PLANE0_OFFSET_EXT, offsets[0],
         EGL_DMA_BUF_PLANE1_FD_EXT, fd,
         EGL_DMA_BUF_PLANE1_PITCH_EXT, pitches[1],
         EGL_DMA_BUF_PLANE1_OFFSET_EXT, offsets[1],
         EGL_DMA_BUF_PLANE2_FD_EXT, fd,
         EGL_DMA_BUF_PLANE2_PITCH_EXT, pitches[2],
         EGL_DMA_BUF_PLANE2_OFFSET_EXT, offsets[2],
         EGL_NONE, 0
      };

866 867 868 869 870 871 872 873 874 875
      return dri2_create_image_dma_buf(disp, ctx, NULL, attr_list_3plane);
   }
}

static _EGLImage *
droid_create_image_from_prime_fd(_EGLDisplay *disp, _EGLContext *ctx,
                                 struct ANativeWindowBuffer *buf, int fd)
{
   unsigned int pitch;

876 877 878 879 880 881 882 883 884 885 886 887 888 889
   if (is_yuv(buf->format)) {
      _EGLImage *image;

      image = droid_create_image_from_prime_fd_yuv(disp, ctx, buf, fd);
      /*
       * HACK: https://issuetracker.google.com/32077885
       * There is no API available to properly query the IMPLEMENTATION_DEFINED
       * format. As a workaround we rely here on gralloc allocating either
       * an arbitrary YCbCr 4:2:0 or RGBX_8888, with the latter being recognized
       * by lock_ycbcr failing.
       */
      if (image || buf->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED)
         return image;
   }
890 891 892 893 894 895 896 897 898 899 900

   const int fourcc = get_fourcc(buf->format);
   if (fourcc == -1) {
      _eglError(EGL_BAD_PARAMETER, "eglCreateEGLImageKHR");
      return NULL;
   }

   pitch = buf->stride * get_format_bpp(buf->format);
   if (pitch == 0) {
      _eglError(EGL_BAD_PARAMETER, "eglCreateEGLImageKHR");
      return NULL;
901 902 903
   }

   const EGLint attr_list[] = {
904 905 906 907
      EGL_WIDTH, buf->width,
      EGL_HEIGHT, buf->height,
      EGL_LINUX_DRM_FOURCC_EXT, fourcc,
      EGL_DMA_BUF_PLANE0_FD_EXT, fd,
908
      EGL_DMA_BUF_PLANE0_PITCH_EXT, pitch,
909 910 911 912 913 914
      EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0,
      EGL_NONE, 0
   };

   return dri2_create_image_dma_buf(disp, ctx, NULL, attr_list);
}
915

916
#ifdef HAVE_DRM_GRALLOC
917 918 919 920 921 922 923 924
static _EGLImage *
droid_create_image_from_name(_EGLDisplay *disp, _EGLContext *ctx,
                             struct ANativeWindowBuffer *buf)
{
   struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
   struct dri2_egl_image *dri2_img;
   int name;
   int format;
925

926 927 928 929 930 931
   name = get_native_buffer_name(buf);
   if (!name) {
      _eglError(EGL_BAD_PARAMETER, "eglCreateEGLImageKHR");
      return NULL;
   }

932 933 934 935
   format = get_format(buf->format);
   if (format == -1)
       return NULL;

936 937 938 939 940 941
   dri2_img = calloc(1, sizeof(*dri2_img));
   if (!dri2_img) {
      _eglError(EGL_BAD_ALLOC, "droid_create_image_mesa_drm");
      return NULL;
   }

942
   _eglInitImage(&dri2_img->base, disp);
943 944 945 946 947

   dri2_img->dri_image =
      dri2_dpy->image->createImageFromName(dri2_dpy->dri_screen,
					   buf->width,
					   buf->height,
948
					   format,
949 950 951 952 953 954 955 956 957 958 959
					   name,
					   buf->stride,
					   dri2_img);
   if (!dri2_img->dri_image) {
      free(dri2_img);
      _eglError(EGL_BAD_ALLOC, "droid_create_image_mesa_drm");
      return NULL;
   }

   return &dri2_img->base;
}
960
#endif /* HAVE_DRM_GRALLOC */
961

962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
static EGLBoolean
droid_query_surface(_EGLDriver *drv, _EGLDisplay *dpy, _EGLSurface *surf,
                    EGLint attribute, EGLint *value)
{
   struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
   switch (attribute) {
      case EGL_WIDTH:
         if (dri2_surf->base.Type == EGL_WINDOW_BIT && dri2_surf->window) {
            dri2_surf->window->query(dri2_surf->window,
                                     NATIVE_WINDOW_DEFAULT_WIDTH, value);
            return EGL_TRUE;
         }
         break;
      case EGL_HEIGHT:
         if (dri2_surf->base.Type == EGL_WINDOW_BIT && dri2_surf->window) {
            dri2_surf->window->query(dri2_surf->window,
                                     NATIVE_WINDOW_DEFAULT_HEIGHT, value);
            return EGL_TRUE;
         }
         break;
      default:
         break;
   }
   return _eglQuerySurface(drv, dpy, surf, attribute, value);
}

988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
static _EGLImage *
dri2_create_image_android_native_buffer(_EGLDisplay *disp,
                                        _EGLContext *ctx,
                                        struct ANativeWindowBuffer *buf)
{
   int fd;

   if (ctx != NULL) {
      /* From the EGL_ANDROID_image_native_buffer spec:
       *
       *     * If <target> is EGL_NATIVE_BUFFER_ANDROID and <ctx> is not
       *       EGL_NO_CONTEXT, the error EGL_BAD_CONTEXT is generated.
       */
      _eglError(EGL_BAD_CONTEXT, "eglCreateEGLImageKHR: for "
                "EGL_NATIVE_BUFFER_ANDROID, the context must be "
                "EGL_NO_CONTEXT");
      return NULL;
   }

   if (!buf || buf->common.magic != ANDROID_NATIVE_BUFFER_MAGIC ||
       buf->common.version != sizeof(*buf)) {
      _eglError(EGL_BAD_PARAMETER, "eglCreateEGLImageKHR");
      return NULL;
   }

   fd = get_native_buffer_fd(buf);
   if (fd >= 0)
      return droid_create_image_from_prime_fd(disp, ctx, buf, fd);

1017
#ifdef HAVE_DRM_GRALLOC
1018
   return droid_create_image_from_name(disp, ctx, buf);
1019 1020 1021
#else
   return NULL;
#endif
1022 1023
}

1024 1025 1026 1027 1028 1029 1030
static _EGLImage *
droid_create_image_khr(_EGLDriver *drv, _EGLDisplay *disp,
		       _EGLContext *ctx, EGLenum target,
		       EGLClientBuffer buffer, const EGLint *attr_list)
{
   switch (target) {
   case EGL_NATIVE_BUFFER_ANDROID:
1031
      return dri2_create_image_android_native_buffer(disp, ctx,
Chia-I Wu's avatar
Chia-I Wu committed
1032
            (struct ANativeWindowBuffer *) buffer);
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
   default:
      return dri2_create_image_khr(drv, disp, ctx, target, buffer, attr_list);
   }
}

static void
droid_flush_front_buffer(__DRIdrawable * driDrawable, void *loaderPrivate)
{
}

1043
#ifdef HAVE_DRM_GRALLOC
1044 1045 1046
static int
droid_get_buffers_parse_attachments(struct dri2_egl_surface *dri2_surf,
                                    unsigned int *attachments, int count)
1047
{
1048
   int num_buffers = 0;
1049

1050
   /* fill dri2_surf->buffers */
1051
   for (int i = 0; i < count * 2; i += 2) {
1052 1053
      __DRIbuffer *buf, *local;

1054 1055
      assert(num_buffers < ARRAY_SIZE(dri2_surf->buffers));
      buf = &dri2_surf->buffers[num_buffers];
1056 1057 1058

      switch (attachments[i]) {
      case __DRI_BUFFER_BACK_LEFT:
1059 1060 1061 1062 1063 1064 1065 1066 1067
         if (dri2_surf->base.Type == EGL_WINDOW_BIT) {
            buf->attachment = attachments[i];
            buf->name = get_native_buffer_name(dri2_surf->buffer);
            buf->cpp = get_format_bpp(dri2_surf->buffer->format);
            buf->pitch = dri2_surf->buffer->stride * buf->cpp;
            buf->flags = 0;

            if (buf->name)
               num_buffers++;
1068 1069

            break;
1070
         }
1071
         /* fall through for pbuffers */
1072 1073 1074 1075 1076
      case __DRI_BUFFER_DEPTH:
      case __DRI_BUFFER_STENCIL:
      case __DRI_BUFFER_ACCUM:
      case __DRI_BUFFER_DEPTH_STENCIL:
      case __DRI_BUFFER_HIZ:
1077
         local = dri2_egl_surface_alloc_local_buffer(dri2_surf,
1078 1079 1080 1081
               attachments[i], attachments[i + 1]);

         if (local) {
            *buf = *local;
1082
            num_buffers++;
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
         }
         break;
      case __DRI_BUFFER_FRONT_LEFT:
      case __DRI_BUFFER_FRONT_RIGHT:
      case __DRI_BUFFER_FAKE_FRONT_LEFT:
      case __DRI_BUFFER_FAKE_FRONT_RIGHT:
      case __DRI_BUFFER_BACK_RIGHT:
      default:
         /* no front or right buffers */
         break;
      }
   }

1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
   return num_buffers;
}

static __DRIbuffer *
droid_get_buffers_with_format(__DRIdrawable * driDrawable,
			     int *width, int *height,
			     unsigned int *attachments, int count,
			     int *out_count, void *loaderPrivate)
{
   struct dri2_egl_surface *dri2_surf = loaderPrivate;

1107 1108
   if (update_buffers(dri2_surf) < 0)
      return NULL;
1109

1110
   *out_count = droid_get_buffers_parse_attachments(dri2_surf, attachments, count);
1111

1112 1113 1114 1115 1116 1117 1118
   if (width)
      *width = dri2_surf->base.Width;
   if (height)
      *height = dri2_surf->base.Height;

   return dri2_surf->buffers;
}
1119
#endif /* HAVE_DRM_GRALLOC */
1120

1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
static unsigned
droid_get_capability(void *loaderPrivate, enum dri_loader_cap cap)
{
   /* Note: loaderPrivate is _EGLDisplay* */
   switch (cap) {
   case DRI_LOADER_CAP_RGBA_ORDERING:
      return 1;
   default:
      return 0;
   }
}

1133 1134 1135 1136
static EGLBoolean
droid_add_configs_for_visuals(_EGLDriver *drv, _EGLDisplay *dpy)
{
   struct dri2_egl_display *dri2_dpy = dri2_egl_display(dpy);
1137
   static const struct {
1138 1139 1140
      int format;
      unsigned int rgba_masks[4];
   } visuals[] = {
1141 1142 1143 1144
      { HAL_PIXEL_FORMAT_RGBA_8888, { 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 } },
      { HAL_PIXEL_FORMAT_RGBX_8888, { 0x000000ff, 0x0000ff00, 0x00ff0000, 0x00000000 } },
      { HAL_PIXEL_FORMAT_RGB_565,   { 0x0000f800, 0x000007e0, 0x0000001f, 0x00000000 } },
      { HAL_PIXEL_FORMAT_BGRA_8888, { 0x00ff0000, 0x0000ff00, 0x000000ff, 0xff000000 } },
1145
   };
1146

1147
   unsigned int format_count[ARRAY_SIZE(visuals)] = { 0 };
1148
   int config_count = 0;
1149

1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
   /* The nesting of loops is significant here. Also significant is the order
    * of the HAL pixel formats. Many Android apps (such as Google's official
    * NDK GLES2 example app), and even portions the core framework code (such
    * as SystemServiceManager in Nougat), incorrectly choose their EGLConfig.
    * They neglect to match the EGLConfig's EGL_NATIVE_VISUAL_ID against the
    * window's native format, and instead choose the first EGLConfig whose
    * channel sizes match those of the native window format while ignoring the
    * channel *ordering*.
    *
    * We can detect such buggy clients in logcat when they call
    * eglCreateSurface, by detecting the mismatch between the EGLConfig's
    * format and the window's format.
    *
    * As a workaround, we generate EGLConfigs such that all EGLConfigs for HAL
    * pixel format i precede those for HAL pixel format i+1. In my
    * (chadversary) testing on Android Nougat, this was good enough to pacify
    * the buggy clients.
    */
1168 1169 1170
   for (int i = 0; i < ARRAY_SIZE(visuals); i++) {
      for (int j = 0; dri2_dpy->driver_configs[j]; j++) {
         const EGLint surface_type = EGL_WINDOW_BIT | EGL_PBUFFER_BIT;
1171

1172 1173 1174 1175 1176 1177 1178
         const EGLint config_attrs[] = {
           EGL_NATIVE_VISUAL_ID,   visuals[i].format,
           EGL_NATIVE_VISUAL_TYPE, visuals[i].format,
           EGL_FRAMEBUFFER_TARGET_ANDROID, EGL_TRUE,
           EGL_RECORDABLE_ANDROID, EGL_TRUE,
           EGL_NONE
         };
1179

1180 1181
         struct dri2_egl_config *dri2_conf =
            dri2_add_config(dpy, dri2_dpy->driver_configs[j],
1182
                            config_count + 1, surface_type, config_attrs,
1183
                            visuals[i].rgba_masks);
1184
         if (dri2_conf) {
1185 1186
            if (dri2_conf->base.ConfigID == config_count + 1)
               config_count++;
1187
            format_count[i]++;
1188 1189
         }
      }
1190
   }
1191

1192
   for (int i = 0; i < ARRAY_SIZE(format_count); i++) {
1193
      if (!format_count[i]) {
1194
         _eglLog(_EGL_DEBUG, "No DRI config supports native format 0x%x",
1195
                 visuals[i].format);
1196 1197 1198
      }
   }

1199
   return (config_count != 0);
1200 1201
}

1202 1203 1204
static EGLBoolean
droid_probe_device(_EGLDisplay *disp);

1205
#ifdef HAVE_DRM_GRALLOC
1206 1207
static EGLBoolean
droid_open_device_drm_gralloc(_EGLDisplay *disp)
1208
{
1209
   struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1210 1211 1212 1213 1214 1215 1216 1217
   int fd = -1, err = -EINVAL;

   if (dri2_dpy->gralloc->perform)
         err = dri2_dpy->gralloc->perform(dri2_dpy->gralloc,
                                          GRALLOC_MODULE_PERFORM_GET_DRM_FD,
                                          &fd);
   if (err || fd < 0) {
      _eglLog(_EGL_WARNING, "fail to get drm fd");
1218
      return EGL_FALSE;
1219 1220
   }

1221 1222 1223 1224 1225
   dri2_dpy->fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
   if (dri2_dpy->fd < 0)
     return EGL_FALSE;

   return droid_probe_device(disp);
1226 1227 1228
}
#endif /* HAVE_DRM_GRALLOC */

1229
static const struct dri2_egl_display_vtbl droid_display_vtbl = {
1230
   .authenticate = NULL,
1231
   .create_window_surface = droid_create_window_surface,
1232
   .create_pixmap_surface = dri2_fallback_create_pixmap_surface,
1233
   .create_pbuffer_surface = droid_create_pbuffer_surface,
1234
   .destroy_surface = droid_destroy_surface,
1235
   .create_image = droid_create_image_khr,
1236
   .swap_buffers = droid_swap_buffers,
1237
   .swap_buffers_with_damage = dri2_fallback_swap_buffers_with_damage, /* Android implements the function */
1238
   .swap_buffers_region = dri2_fallback_swap_buffers_region,
1239
   .swap_interval = droid_swap_interval,
1240 1241 1242 1243 1244
#if ANDROID_API_LEVEL >= 23
   .set_damage_region = droid_set_damage_region,
#else
   .set_damage_region = dri2_fallback_set_damage_region,
#endif
1245
   .post_sub_buffer = dri2_fallback_post_sub_buffer,
1246
   .copy_buffers = dri2_fallback_copy_buffers,
1247
   .query_buffer_age = droid_query_buffer_age,
1248
   .query_surface = droid_query_surface,
1249
   .create_wayland_buffer_from_image = dri2_fallback_create_wayland_buffer_from_image,
1250
   .get_sync_values = dri2_fallback_get_sync_values,
1251
   .get_dri_drawable = dri2_surface_get_dri_drawable,
1252
   .set_shared_buffer_mode = droid_set_shared_buffer_mode,
1253 1254
};

1255
#ifdef HAVE_DRM_GRALLOC
1256
static const __DRIdri2LoaderExtension droid_dri2_loader_extension = {
1257
   .base = { __DRI_DRI2_LOADER, 4 },
1258 1259 1260 1261

   .getBuffers           = NULL,
   .flushFrontBuffer     = droid_flush_front_buffer,
   .getBuffersWithFormat = droid_get_buffers_with_format,
1262
   .getCapability        = droid_get_capability,
1263
};
1264
#endif /* HAVE_DRM_GRALLOC */
1265

1266
static const __DRIimageLoaderExtension droid_image_loader_extension = {
1267
   .base = { __DRI_IMAGE_LOADER, 2 },
1268 1269 1270

   .getBuffers          = droid_image_get_buffers,
   .flushFrontBuffer    = droid_flush_front_buffer,
1271
   .getCapability       = droid_get_capability,
1272 1273
};

1274
#ifdef HAVE_DRM_GRALLOC
1275 1276 1277 1278
static const __DRIextension *droid_dri2_loader_extensions[] = {
   &droid_dri2_loader_extension.base,
   &image_lookup_extension.base,
   &use_invalidate.base,
1279 1280 1281
   /* No __DRI_MUTABLE_RENDER_BUFFER_LOADER because it requires
    * __DRI_IMAGE_LOADER.
    */
1282 1283
   NULL,
};
1284
#endif /* HAVE_DRM_GRALLOC */
1285

1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
static void
droid_display_shared_buffer(__DRIdrawable *driDrawable, int fence_fd,
                            void *loaderPrivate)
{
   struct dri2_egl_surface *dri2_surf = loaderPrivate;
   struct ANativeWindowBuffer *old_buffer UNUSED = dri2_surf->buffer;

   if (!_eglSurfaceInSharedBufferMode(&dri2_surf->base)) {
      _eglLog(_EGL_WARNING, "%s: internal error: buffer is not shared",
              __func__);
      return;
   }

   if (fence_fd >= 0) {
      /* The driver's fence is more recent than the surface's out fence, if it
       * exists at all. So use the driver's fence.
       */
      if (dri2_surf->out_fence_fd >= 0) {
         close(dri2_surf->out_fence_fd);
         dri2_surf->out_fence_fd = -1;
      }
   } else if (dri2_surf->out_fence_fd >= 0) {
      fence_fd = dri2_surf->out_fence_fd;
      dri2_surf->out_fence_fd = -1;
   }

   if (dri2_surf->window->queueBuffer(dri2_surf->window, dri2_surf->buffer,
                                      fence_fd)) {
      _eglLog(_EGL_WARNING, "%s: ANativeWindow::queueBuffer failed", __func__);
      close(fence_fd);
      return;
   }

   fence_fd = -1;

   if (dri2_surf->window->dequeueBuffer(dri2_surf->window, &dri2_surf->buffer,
                                        &fence_fd)) {
      /* Tear down the surface because it no longer has a back buffer. */
      struct dri2_egl_display *dri2_dpy =
         dri2_egl_display(dri2_surf->base.Resource.Display);

      _eglLog(_EGL_WARNING, "%s: ANativeWindow::dequeueBuffer failed", __func__);

      dri2_surf->base.Lost = true;
      dri2_surf->buffer = NULL;
      dri2_surf->back = NULL;

      if (dri2_surf->dri_image_back) {
         dri2_dpy->image->destroyImage(dri2_surf->dri_image_back);
         dri2_surf->dri_image_back = NULL;
      }

      dri2_dpy->flush->invalidate(dri2_surf->dri_drawable);
      return;
   }

   if (fence_fd < 0)
      return;

   /* Access to the buffer is controlled by a sync fence. Block on it.
    *
    * Ideally, we would submit the fence to the driver, and the driver would
    * postpone command execution until it signalled. But DRI lacks API for
    * that (as of 2018-04-11).
    *
    *  SYNC_IOC_WAIT waits forever if timeout < 0
    */
   sync_wait(fence_fd, -1);
   close(fence_fd);
}

static const __DRImutableRenderBufferLoaderExtension droid_mutable_render_buffer_extension = {
   .base = { __DRI_MUTABLE_RENDER_BUFFER_LOADER, 1 },
   .displaySharedBuffer = droid_display_shared_buffer,
};

1362 1363 1364 1365
static const __DRIextension *droid_image_loader_extensions[] = {
   &droid_image_loader_extension.base,
   &image_lookup_extension.base,
   &use_invalidate.base,
1366
   &droid_mutable_render_buffer_extension.base,
1367 1368 1369
   NULL,
};

1370
static EGLBoolean
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
droid_load_driver(_EGLDisplay *disp)
{
   struct dri2_egl_display *dri2_dpy = disp->DriverData;
   const char *err;

   dri2_dpy->driver_name = loader_get_driver_for_fd(dri2_dpy->fd);
   if (dri2_dpy->driver_name == NULL)
      return false;

   dri2_dpy->is_render_node = drmGetNodeTypeFromFd(dri2_dpy->fd) == DRM_NODE_RENDER;

   if (!dri2_dpy->is_render_node) {
1383
#ifdef HAVE_DRM_GRALLOC
1384 1385 1386 1387 1388 1389 1390 1391
       /* Handle control nodes using __DRI_DRI2_LOADER extension and GEM names
        * for backwards compatibility with drm_gralloc. (Do not use on new
        * systems.) */
       dri2_dpy->loader_extensions = droid_dri2_loader_extensions;
       if (!dri2_load_driver(disp)) {
          err = "DRI2: failed to load driver";
          goto error;
       }
1392
#else
1393 1394
       err = "DRI2: handle is not for a render node";
       goto error;
1395
#endif
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
   } else {
       dri2_dpy->loader_extensions = droid_image_loader_extensions;
       if (!dri2_load_driver_dri3(disp)) {
          err = "DRI3: failed to load driver";
          goto error;
       }
    }

   return true;

error:
   free(dri2_dpy->driver_name);
   dri2_dpy->driver_name = NULL;
   return false;
}

1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
static void
droid_unload_driver(_EGLDisplay *disp)
{
   struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);

   dlclose(dri2_dpy->driver);
   dri2_dpy->driver = NULL;
   free(dri2_dpy->driver_name);
   dri2_dpy->driver_name = NULL;
}

1423 1424
static int
droid_filter_device(_EGLDisplay *disp, int fd, const char *vendor)
1425 1426 1427
{
   drmVersionPtr ver = drmGetVersion(fd);
   if (!ver)
1428
      return -1;
1429

1430 1431 1432
   if (strcmp(vendor, ver->name) != 0) {
      drmFreeVersion(ver);
      return -1;
1433 1434 1435
   }

   drmFreeVersion(ver);
1436
   return 0;
1437 1438
}

1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
static EGLBoolean
droid_probe_device(_EGLDisplay *disp)
{
  /* Check that the device is supported, by attempting to:
   * - load the dri module
   * - and, create a screen
   */
   if (!droid_load_driver(disp))
      return EGL_FALSE;

   if (!dri2_create_screen(disp)) {
      _eglLog(_EGL_WARNING, "DRI2: failed to create screen");
      droid_unload_driver(disp);
      return EGL_FALSE;
   }
   return EGL_TRUE;
}

static EGLBoolean
1458 1459
droid_open_device(_EGLDisplay *disp)
{
1460
#define MAX_DRM_DEVICES 32
1461
   struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1462
   drmDevicePtr device, devices[MAX_DRM_DEVICES] = { NULL };
1463
   int num_devices;
1464 1465 1466 1467 1468 1469 1470

   char *vendor_name = NULL;
   char vendor_buf[PROPERTY_VALUE_MAX];

   if (property_get("drm.gpu.vendor_name", vendor_buf, NULL) > 0)
      vendor_name = vendor_buf;

1471 1472
   num_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
   if (num_devices < 0)
1473
      return EGL_FALSE;
1474

1475 1476
   for (int i = 0; i < num_devices; i++) {
      device = devices[i];
1477

1478
      if (!(device->available_nodes & (1 << DRM_NODE_RENDER)))
1479 1480
         continue;

1481 1482
      dri2_dpy->fd = loader_open_device(device->nodes[DRM_NODE_RENDER]);
      if (dri2_dpy->fd < 0) {
1483
         _eglLog(_EGL_WARNING, "%s() Failed to open DRM device %s",
1484
                 __func__, device->nodes[DRM_NODE_RENDER]);
1485 1486 1487
         continue;
      }

1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
      /* If a vendor is explicitly provided, we use only that.
       * Otherwise we fall-back the first device that is supported.
       */
      if (vendor_name) {
         if (droid_filter_device(disp, dri2_dpy->fd, vendor_name)) {
            /* Device does not match - try next device */
            close(dri2_dpy->fd);
            dri2_dpy->fd = -1;
            continue;
         }
         /* If the requested device matches - use it. Regardless if
          * init fails, do not fall-back to any other device.
          */
         if (!droid_probe_device(disp)) {
            close(dri2_dpy->fd);
            dri2_dpy->fd = -1;
1504
         }
1505

1506
         break;
1507
      }
1508 1509
      if (droid_probe_device(disp))
         break;
1510

1511 1512 1513
      /* No explicit request - attempt the next device */
      close(dri2_dpy->fd);
      dri2_dpy->fd = -1;
1514
   }
1515
   drmFreeDevices(devices, num_devices);
1516

1517 1518 1519 1520
   if (dri2_dpy->fd < 0) {
      _eglLog(_EGL_WARNING, "Failed to open %s DRM device",
            vendor_name ? "desired": "any");
      return EGL_FALSE;
1521 1522
   }

1523
   return EGL_TRUE;
1524
#undef MAX_DRM_DEVICES
1525 1526
}

1527
EGLBoolean
1528
dri2_initialize_android(_EGLDriver *drv, _EGLDisplay *disp)
1529
{
1530
   _EGLDevice *dev;
1531 1532
   struct dri2_egl_display *dri2_dpy;
   const char *err;
1533
   int ret;
1534

1535
   /* Not supported yet */
1536
   if (disp->Options.ForceSoftware)
1537 1538
      return EGL_FALSE;

1539 1540
   loader_set_logger(_eglLog);

1541 1542 1543 1544
   dri2_dpy = calloc(1, sizeof(*dri2_dpy));
   if (!dri2_dpy)
      return _eglError(EGL_BAD_ALLOC, "eglInitialize");

1545
   dri2_dpy->fd = -1;
1546 1547 1548 1549
   ret = hw_get_module(GRALLOC_HARDWARE_MODULE_ID,
                       (const hw_module_t **)&dri2_dpy->gralloc);
   if (ret) {
      err = "DRI2: failed to get gralloc module";
1550
      goto cleanup;
1551 1552
   }

1553
   disp->DriverData = (void *) dri2_dpy;
1554

1555
#ifdef HAVE_DRM_GRALLOC
1556
   if (!droid_open_device_drm_gralloc(disp)) {
1557
#else
1558
   if (!droid_open_device(disp)) {
1559
#endif
1560
      err = "DRI2: failed to open device";
1561
      goto cleanup;
1562 1563
   }

1564 1565 1566 1567 1568 1569 1570 1571
   dev = _eglAddDevice(dri2_dpy->fd, false);
   if (!dev) {
      err = "DRI2: failed to find EGLDevice";
      goto cleanup;
   }

   disp->Device = dev;

1572
   if (!dri2_setup_extensions(disp)) {
1573
      err = "DRI2: failed to setup extensions";
1574
      goto cleanup;
1575
   }
1576

1577
   dri2_setup_screen(disp);
1578

1579 1580 1581 1582 1583 1584
   /* We set the maximum swap interval as 1 for Android platform, since it is
    * the maximum value supported by Android according to the value of
    * ANativeWindow::maxSwapInterval.
    */
   dri2_setup_swap_interval(disp, 1);