Home | History | Annotate | Download | only in renderthread
      1 /*
      2  * Copyright (C) 2014 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #include "EglManager.h"
     18 
     19 #include <cutils/properties.h>
     20 #include <log/log.h>
     21 #include <private/gui/SyncFeatures.h>
     22 #include <utils/Trace.h>
     23 #include "utils/Color.h"
     24 #include "utils/StringUtils.h"
     25 
     26 #include "Frame.h"
     27 #include "Properties.h"
     28 
     29 #include <EGL/eglext.h>
     30 #include <GLES/gl.h>
     31 
     32 #include <gui/Surface.h>
     33 #include <system/window.h>
     34 #include <string>
     35 #include <vector>
     36 
     37 #define GLES_VERSION 2
     38 
     39 // Android-specific addition that is used to show when frames began in systrace
     40 EGLAPI void EGLAPIENTRY eglBeginFrame(EGLDisplay dpy, EGLSurface surface);
     41 
     42 namespace android {
     43 namespace uirenderer {
     44 namespace renderthread {
     45 
     46 #define ERROR_CASE(x) \
     47     case x:           \
     48         return #x;
     49 static const char* egl_error_str(EGLint error) {
     50     switch (error) {
     51         ERROR_CASE(EGL_SUCCESS)
     52         ERROR_CASE(EGL_NOT_INITIALIZED)
     53         ERROR_CASE(EGL_BAD_ACCESS)
     54         ERROR_CASE(EGL_BAD_ALLOC)
     55         ERROR_CASE(EGL_BAD_ATTRIBUTE)
     56         ERROR_CASE(EGL_BAD_CONFIG)
     57         ERROR_CASE(EGL_BAD_CONTEXT)
     58         ERROR_CASE(EGL_BAD_CURRENT_SURFACE)
     59         ERROR_CASE(EGL_BAD_DISPLAY)
     60         ERROR_CASE(EGL_BAD_MATCH)
     61         ERROR_CASE(EGL_BAD_NATIVE_PIXMAP)
     62         ERROR_CASE(EGL_BAD_NATIVE_WINDOW)
     63         ERROR_CASE(EGL_BAD_PARAMETER)
     64         ERROR_CASE(EGL_BAD_SURFACE)
     65         ERROR_CASE(EGL_CONTEXT_LOST)
     66         default:
     67             return "Unknown error";
     68     }
     69 }
     70 const char* EglManager::eglErrorString() {
     71     return egl_error_str(eglGetError());
     72 }
     73 
     74 static struct {
     75     bool bufferAge = false;
     76     bool setDamage = false;
     77     bool noConfigContext = false;
     78     bool pixelFormatFloat = false;
     79     bool glColorSpace = false;
     80     bool scRGB = false;
     81     bool displayP3 = false;
     82     bool contextPriority = false;
     83     bool surfacelessContext = false;
     84 } EglExtensions;
     85 
     86 EglManager::EglManager()
     87         : mEglDisplay(EGL_NO_DISPLAY)
     88         , mEglConfig(nullptr)
     89         , mEglConfigWideGamut(nullptr)
     90         , mEglContext(EGL_NO_CONTEXT)
     91         , mPBufferSurface(EGL_NO_SURFACE)
     92         , mCurrentSurface(EGL_NO_SURFACE)
     93         , mHasWideColorGamutSupport(false) {}
     94 
     95 EglManager::~EglManager() {
     96     if (hasEglContext()) {
     97         ALOGW("~EglManager() leaked an EGL context");
     98     }
     99 }
    100 
    101 void EglManager::initialize() {
    102     if (hasEglContext()) return;
    103 
    104     ATRACE_NAME("Creating EGLContext");
    105 
    106     mEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    107     LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY, "Failed to get EGL_DEFAULT_DISPLAY! err=%s",
    108                         eglErrorString());
    109 
    110     EGLint major, minor;
    111     LOG_ALWAYS_FATAL_IF(eglInitialize(mEglDisplay, &major, &minor) == EGL_FALSE,
    112                         "Failed to initialize display %p! err=%s", mEglDisplay, eglErrorString());
    113 
    114     ALOGV("Initialized EGL, version %d.%d", (int)major, (int)minor);
    115 
    116     initExtensions();
    117 
    118     // Now that extensions are loaded, pick a swap behavior
    119     if (Properties::enablePartialUpdates) {
    120         // An Adreno driver bug is causing rendering problems for SkiaGL with
    121         // buffer age swap behavior (b/31957043).  To temporarily workaround,
    122         // we will use preserved swap behavior.
    123         if (Properties::useBufferAge && EglExtensions.bufferAge) {
    124             mSwapBehavior = SwapBehavior::BufferAge;
    125         } else {
    126             mSwapBehavior = SwapBehavior::Preserved;
    127         }
    128     }
    129 
    130     loadConfigs();
    131     createContext();
    132     createPBufferSurface();
    133     makeCurrent(mPBufferSurface, nullptr, /* force */ true);
    134 
    135     skcms_Matrix3x3 wideColorGamut;
    136     LOG_ALWAYS_FATAL_IF(!DeviceInfo::get()->getWideColorSpace()->toXYZD50(&wideColorGamut),
    137                         "Could not get gamut matrix from wideColorSpace");
    138     bool hasWideColorSpaceExtension = false;
    139     if (memcmp(&wideColorGamut, &SkNamedGamut::kDCIP3, sizeof(wideColorGamut)) == 0) {
    140         hasWideColorSpaceExtension = EglExtensions.displayP3;
    141     } else if (memcmp(&wideColorGamut, &SkNamedGamut::kSRGB, sizeof(wideColorGamut)) == 0) {
    142         hasWideColorSpaceExtension = EglExtensions.scRGB;
    143     } else {
    144         LOG_ALWAYS_FATAL("Unsupported wide color space.");
    145     }
    146     mHasWideColorGamutSupport = EglExtensions.glColorSpace && hasWideColorSpaceExtension &&
    147                                 mEglConfigWideGamut != EGL_NO_CONFIG_KHR;
    148 }
    149 
    150 EGLConfig EglManager::load8BitsConfig(EGLDisplay display, EglManager::SwapBehavior swapBehavior) {
    151     EGLint eglSwapBehavior =
    152             (swapBehavior == SwapBehavior::Preserved) ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0;
    153     EGLint attribs[] = {EGL_RENDERABLE_TYPE,
    154                         EGL_OPENGL_ES2_BIT,
    155                         EGL_RED_SIZE,
    156                         8,
    157                         EGL_GREEN_SIZE,
    158                         8,
    159                         EGL_BLUE_SIZE,
    160                         8,
    161                         EGL_ALPHA_SIZE,
    162                         8,
    163                         EGL_DEPTH_SIZE,
    164                         0,
    165                         EGL_CONFIG_CAVEAT,
    166                         EGL_NONE,
    167                         EGL_STENCIL_SIZE,
    168                         STENCIL_BUFFER_SIZE,
    169                         EGL_SURFACE_TYPE,
    170                         EGL_WINDOW_BIT | eglSwapBehavior,
    171                         EGL_NONE};
    172     EGLConfig config = EGL_NO_CONFIG_KHR;
    173     EGLint numConfigs = 1;
    174     if (!eglChooseConfig(display, attribs, &config, numConfigs, &numConfigs) || numConfigs != 1) {
    175         return EGL_NO_CONFIG_KHR;
    176     }
    177     return config;
    178 }
    179 
    180 EGLConfig EglManager::loadFP16Config(EGLDisplay display, SwapBehavior swapBehavior) {
    181     EGLint eglSwapBehavior =
    182             (swapBehavior == SwapBehavior::Preserved) ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0;
    183     // If we reached this point, we have a valid swap behavior
    184     EGLint attribs[] = {EGL_RENDERABLE_TYPE,
    185                         EGL_OPENGL_ES2_BIT,
    186                         EGL_COLOR_COMPONENT_TYPE_EXT,
    187                         EGL_COLOR_COMPONENT_TYPE_FLOAT_EXT,
    188                         EGL_RED_SIZE,
    189                         16,
    190                         EGL_GREEN_SIZE,
    191                         16,
    192                         EGL_BLUE_SIZE,
    193                         16,
    194                         EGL_ALPHA_SIZE,
    195                         16,
    196                         EGL_DEPTH_SIZE,
    197                         0,
    198                         EGL_STENCIL_SIZE,
    199                         STENCIL_BUFFER_SIZE,
    200                         EGL_SURFACE_TYPE,
    201                         EGL_WINDOW_BIT | eglSwapBehavior,
    202                         EGL_NONE};
    203     EGLConfig config = EGL_NO_CONFIG_KHR;
    204     EGLint numConfigs = 1;
    205     if (!eglChooseConfig(display, attribs, &config, numConfigs, &numConfigs) || numConfigs != 1) {
    206         return EGL_NO_CONFIG_KHR;
    207     }
    208     return config;
    209 }
    210 
    211 void EglManager::initExtensions() {
    212     auto extensions = StringUtils::split(eglQueryString(mEglDisplay, EGL_EXTENSIONS));
    213 
    214     // For our purposes we don't care if EGL_BUFFER_AGE is a result of
    215     // EGL_EXT_buffer_age or EGL_KHR_partial_update as our usage is covered
    216     // under EGL_KHR_partial_update and we don't need the expanded scope
    217     // that EGL_EXT_buffer_age provides.
    218     EglExtensions.bufferAge =
    219             extensions.has("EGL_EXT_buffer_age") || extensions.has("EGL_KHR_partial_update");
    220     EglExtensions.setDamage = extensions.has("EGL_KHR_partial_update");
    221     LOG_ALWAYS_FATAL_IF(!extensions.has("EGL_KHR_swap_buffers_with_damage"),
    222                         "Missing required extension EGL_KHR_swap_buffers_with_damage");
    223 
    224     EglExtensions.glColorSpace = extensions.has("EGL_KHR_gl_colorspace");
    225     EglExtensions.noConfigContext = extensions.has("EGL_KHR_no_config_context");
    226     EglExtensions.pixelFormatFloat = extensions.has("EGL_EXT_pixel_format_float");
    227     EglExtensions.scRGB = extensions.has("EGL_EXT_gl_colorspace_scrgb");
    228     EglExtensions.displayP3 = extensions.has("EGL_EXT_gl_colorspace_display_p3_passthrough");
    229     EglExtensions.contextPriority = extensions.has("EGL_IMG_context_priority");
    230     EglExtensions.surfacelessContext = extensions.has("EGL_KHR_surfaceless_context");
    231 }
    232 
    233 bool EglManager::hasEglContext() {
    234     return mEglDisplay != EGL_NO_DISPLAY;
    235 }
    236 
    237 void EglManager::loadConfigs() {
    238     // Note: The default pixel format is RGBA_8888, when other formats are
    239     // available, we should check the target pixel format and configure the
    240     // attributes list properly.
    241     mEglConfig = load8BitsConfig(mEglDisplay, mSwapBehavior);
    242     if (mEglConfig == EGL_NO_CONFIG_KHR) {
    243         if (mSwapBehavior == SwapBehavior::Preserved) {
    244             // Try again without dirty regions enabled
    245             ALOGW("Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...");
    246             mSwapBehavior = SwapBehavior::Discard;
    247             mEglConfig = load8BitsConfig(mEglDisplay, mSwapBehavior);
    248         } else {
    249             // Failed to get a valid config
    250             LOG_ALWAYS_FATAL("Failed to choose config, error = %s", eglErrorString());
    251         }
    252     }
    253     SkColorType wideColorType = DeviceInfo::get()->getWideColorType();
    254 
    255     // When we reach this point, we have a valid swap behavior
    256     if (wideColorType == SkColorType::kRGBA_F16_SkColorType && EglExtensions.pixelFormatFloat) {
    257         mEglConfigWideGamut = loadFP16Config(mEglDisplay, mSwapBehavior);
    258         if (mEglConfigWideGamut == EGL_NO_CONFIG_KHR) {
    259             ALOGE("Device claims wide gamut support, cannot find matching config, error = %s",
    260                   eglErrorString());
    261             EglExtensions.pixelFormatFloat = false;
    262         }
    263     } else if (wideColorType == SkColorType::kN32_SkColorType) {
    264         mEglConfigWideGamut = load8BitsConfig(mEglDisplay, mSwapBehavior);
    265     }
    266 }
    267 
    268 void EglManager::createContext() {
    269     std::vector<EGLint> contextAttributes;
    270     contextAttributes.reserve(5);
    271     contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
    272     contextAttributes.push_back(GLES_VERSION);
    273     if (Properties::contextPriority != 0 && EglExtensions.contextPriority) {
    274         contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
    275         contextAttributes.push_back(Properties::contextPriority);
    276     }
    277     contextAttributes.push_back(EGL_NONE);
    278     mEglContext = eglCreateContext(
    279             mEglDisplay, EglExtensions.noConfigContext ? ((EGLConfig) nullptr) : mEglConfig,
    280             EGL_NO_CONTEXT, contextAttributes.data());
    281     LOG_ALWAYS_FATAL_IF(mEglContext == EGL_NO_CONTEXT, "Failed to create context, error = %s",
    282                         eglErrorString());
    283 }
    284 
    285 void EglManager::createPBufferSurface() {
    286     LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY,
    287                         "usePBufferSurface() called on uninitialized GlobalContext!");
    288 
    289     if (mPBufferSurface == EGL_NO_SURFACE && !EglExtensions.surfacelessContext) {
    290         EGLint attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE};
    291         mPBufferSurface = eglCreatePbufferSurface(mEglDisplay, mEglConfig, attribs);
    292     }
    293 }
    294 
    295 Result<EGLSurface, EGLint> EglManager::createSurface(EGLNativeWindowType window,
    296                                                      ColorMode colorMode,
    297                                                      sk_sp<SkColorSpace> colorSpace) {
    298     LOG_ALWAYS_FATAL_IF(!hasEglContext(), "Not initialized");
    299 
    300     bool wideColorGamut = colorMode == ColorMode::WideColorGamut && mHasWideColorGamutSupport &&
    301                           EglExtensions.noConfigContext;
    302 
    303     // The color space we want to use depends on whether linear blending is turned
    304     // on and whether the app has requested wide color gamut rendering. When wide
    305     // color gamut rendering is off, the app simply renders in the display's native
    306     // color gamut.
    307     //
    308     // When wide gamut rendering is off:
    309     // - Blending is done by default in gamma space, which requires using a
    310     //   linear EGL color space (the GPU uses the color values as is)
    311     // - If linear blending is on, we must use the non-linear EGL color space
    312     //   (the GPU will perform sRGB to linear and linear to SRGB conversions
    313     //   before and after blending)
    314     //
    315     // When wide gamut rendering is on we cannot rely on the GPU performing
    316     // linear blending for us. We use two different color spaces to tag the
    317     // surface appropriately for SurfaceFlinger:
    318     // - Gamma blending (default) requires the use of the non-linear color space
    319     // - Linear blending requires the use of the linear color space
    320 
    321     // Not all Android targets support the EGL_GL_COLORSPACE_KHR extension
    322     // We insert to placeholders to set EGL_GL_COLORSPACE_KHR and its value.
    323     // According to section 3.4.1 of the EGL specification, the attributes
    324     // list is considered empty if the first entry is EGL_NONE
    325     EGLint attribs[] = {EGL_NONE, EGL_NONE, EGL_NONE};
    326 
    327     if (EglExtensions.glColorSpace) {
    328         attribs[0] = EGL_GL_COLORSPACE_KHR;
    329         if (wideColorGamut) {
    330             skcms_Matrix3x3 colorGamut;
    331             LOG_ALWAYS_FATAL_IF(!colorSpace->toXYZD50(&colorGamut),
    332                                 "Could not get gamut matrix from color space");
    333             if (memcmp(&colorGamut, &SkNamedGamut::kDCIP3, sizeof(colorGamut)) == 0) {
    334                 attribs[1] = EGL_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH_EXT;
    335             } else if (memcmp(&colorGamut, &SkNamedGamut::kSRGB, sizeof(colorGamut)) == 0) {
    336                 attribs[1] = EGL_GL_COLORSPACE_SCRGB_EXT;
    337             } else {
    338                 LOG_ALWAYS_FATAL("Unreachable: unsupported wide color space.");
    339             }
    340         } else {
    341             attribs[1] = EGL_GL_COLORSPACE_LINEAR_KHR;
    342         }
    343     }
    344 
    345     EGLSurface surface = eglCreateWindowSurface(
    346             mEglDisplay, wideColorGamut ? mEglConfigWideGamut : mEglConfig, window, attribs);
    347     if (surface == EGL_NO_SURFACE) {
    348         return Error<EGLint>{eglGetError()};
    349     }
    350 
    351     if (mSwapBehavior != SwapBehavior::Preserved) {
    352         LOG_ALWAYS_FATAL_IF(eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR,
    353                                              EGL_BUFFER_DESTROYED) == EGL_FALSE,
    354                             "Failed to set swap behavior to destroyed for window %p, eglErr = %s",
    355                             (void*)window, eglErrorString());
    356     }
    357 
    358     return surface;
    359 }
    360 
    361 void EglManager::destroySurface(EGLSurface surface) {
    362     if (isCurrent(surface)) {
    363         makeCurrent(EGL_NO_SURFACE);
    364     }
    365     if (!eglDestroySurface(mEglDisplay, surface)) {
    366         ALOGW("Failed to destroy surface %p, error=%s", (void*)surface, eglErrorString());
    367     }
    368 }
    369 
    370 void EglManager::destroy() {
    371     if (mEglDisplay == EGL_NO_DISPLAY) return;
    372 
    373     eglDestroyContext(mEglDisplay, mEglContext);
    374     if (mPBufferSurface != EGL_NO_SURFACE) {
    375         eglDestroySurface(mEglDisplay, mPBufferSurface);
    376     }
    377     eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
    378     eglTerminate(mEglDisplay);
    379     eglReleaseThread();
    380 
    381     mEglDisplay = EGL_NO_DISPLAY;
    382     mEglContext = EGL_NO_CONTEXT;
    383     mPBufferSurface = EGL_NO_SURFACE;
    384     mCurrentSurface = EGL_NO_SURFACE;
    385 }
    386 
    387 bool EglManager::makeCurrent(EGLSurface surface, EGLint* errOut, bool force) {
    388     if (!force && isCurrent(surface)) return false;
    389 
    390     if (surface == EGL_NO_SURFACE) {
    391         // Ensure we always have a valid surface & context
    392         surface = mPBufferSurface;
    393     }
    394     if (!eglMakeCurrent(mEglDisplay, surface, surface, mEglContext)) {
    395         if (errOut) {
    396             *errOut = eglGetError();
    397             ALOGW("Failed to make current on surface %p, error=%s", (void*)surface,
    398                   egl_error_str(*errOut));
    399         } else {
    400             LOG_ALWAYS_FATAL("Failed to make current on surface %p, error=%s", (void*)surface,
    401                              eglErrorString());
    402         }
    403     }
    404     mCurrentSurface = surface;
    405     if (Properties::disableVsync) {
    406         eglSwapInterval(mEglDisplay, 0);
    407     }
    408     return true;
    409 }
    410 
    411 EGLint EglManager::queryBufferAge(EGLSurface surface) {
    412     switch (mSwapBehavior) {
    413         case SwapBehavior::Discard:
    414             return 0;
    415         case SwapBehavior::Preserved:
    416             return 1;
    417         case SwapBehavior::BufferAge:
    418             EGLint bufferAge;
    419             eglQuerySurface(mEglDisplay, surface, EGL_BUFFER_AGE_EXT, &bufferAge);
    420             return bufferAge;
    421     }
    422     return 0;
    423 }
    424 
    425 Frame EglManager::beginFrame(EGLSurface surface) {
    426     LOG_ALWAYS_FATAL_IF(surface == EGL_NO_SURFACE, "Tried to beginFrame on EGL_NO_SURFACE!");
    427     makeCurrent(surface);
    428     Frame frame;
    429     frame.mSurface = surface;
    430     eglQuerySurface(mEglDisplay, surface, EGL_WIDTH, &frame.mWidth);
    431     eglQuerySurface(mEglDisplay, surface, EGL_HEIGHT, &frame.mHeight);
    432     frame.mBufferAge = queryBufferAge(surface);
    433     eglBeginFrame(mEglDisplay, surface);
    434     return frame;
    435 }
    436 
    437 void EglManager::damageFrame(const Frame& frame, const SkRect& dirty) {
    438 #ifdef EGL_KHR_partial_update
    439     if (EglExtensions.setDamage && mSwapBehavior == SwapBehavior::BufferAge) {
    440         EGLint rects[4];
    441         frame.map(dirty, rects);
    442         if (!eglSetDamageRegionKHR(mEglDisplay, frame.mSurface, rects, 1)) {
    443             LOG_ALWAYS_FATAL("Failed to set damage region on surface %p, error=%s",
    444                              (void*)frame.mSurface, eglErrorString());
    445         }
    446     }
    447 #endif
    448 }
    449 
    450 bool EglManager::damageRequiresSwap() {
    451     return EglExtensions.setDamage && mSwapBehavior == SwapBehavior::BufferAge;
    452 }
    453 
    454 bool EglManager::swapBuffers(const Frame& frame, const SkRect& screenDirty) {
    455     if (CC_UNLIKELY(Properties::waitForGpuCompletion)) {
    456         ATRACE_NAME("Finishing GPU work");
    457         fence();
    458     }
    459 
    460     EGLint rects[4];
    461     frame.map(screenDirty, rects);
    462     eglSwapBuffersWithDamageKHR(mEglDisplay, frame.mSurface, rects, screenDirty.isEmpty() ? 0 : 1);
    463 
    464     EGLint err = eglGetError();
    465     if (CC_LIKELY(err == EGL_SUCCESS)) {
    466         return true;
    467     }
    468     if (err == EGL_BAD_SURFACE || err == EGL_BAD_NATIVE_WINDOW) {
    469         // For some reason our surface was destroyed out from under us
    470         // This really shouldn't happen, but if it does we can recover easily
    471         // by just not trying to use the surface anymore
    472         ALOGW("swapBuffers encountered EGL error %d on %p, halting rendering...", err,
    473               frame.mSurface);
    474         return false;
    475     }
    476     LOG_ALWAYS_FATAL("Encountered EGL error %d %s during rendering", err, egl_error_str(err));
    477     // Impossible to hit this, but the compiler doesn't know that
    478     return false;
    479 }
    480 
    481 void EglManager::fence() {
    482     EGLSyncKHR fence = eglCreateSyncKHR(mEglDisplay, EGL_SYNC_FENCE_KHR, NULL);
    483     eglClientWaitSyncKHR(mEglDisplay, fence, EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, EGL_FOREVER_KHR);
    484     eglDestroySyncKHR(mEglDisplay, fence);
    485 }
    486 
    487 bool EglManager::setPreserveBuffer(EGLSurface surface, bool preserve) {
    488     if (mSwapBehavior != SwapBehavior::Preserved) return false;
    489 
    490     bool preserved = eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR,
    491                                       preserve ? EGL_BUFFER_PRESERVED : EGL_BUFFER_DESTROYED);
    492     if (!preserved) {
    493         ALOGW("Failed to set EGL_SWAP_BEHAVIOR on surface %p, error=%s", (void*)surface,
    494               eglErrorString());
    495         // Maybe it's already set?
    496         EGLint swapBehavior;
    497         if (eglQuerySurface(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, &swapBehavior)) {
    498             preserved = (swapBehavior == EGL_BUFFER_PRESERVED);
    499         } else {
    500             ALOGW("Failed to query EGL_SWAP_BEHAVIOR on surface %p, error=%p", (void*)surface,
    501                   eglErrorString());
    502         }
    503     }
    504 
    505     return preserved;
    506 }
    507 
    508 status_t EglManager::fenceWait(sp<Fence>& fence) {
    509     if (!hasEglContext()) {
    510         ALOGE("EglManager::fenceWait: EGLDisplay not initialized");
    511         return INVALID_OPERATION;
    512     }
    513 
    514     if (SyncFeatures::getInstance().useWaitSync() &&
    515         SyncFeatures::getInstance().useNativeFenceSync()) {
    516         // Block GPU on the fence.
    517         // Create an EGLSyncKHR from the current fence.
    518         int fenceFd = fence->dup();
    519         if (fenceFd == -1) {
    520             ALOGE("EglManager::fenceWait: error dup'ing fence fd: %d", errno);
    521             return -errno;
    522         }
    523         EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd, EGL_NONE};
    524         EGLSyncKHR sync = eglCreateSyncKHR(mEglDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
    525         if (sync == EGL_NO_SYNC_KHR) {
    526             close(fenceFd);
    527             ALOGE("EglManager::fenceWait: error creating EGL fence: %#x", eglGetError());
    528             return UNKNOWN_ERROR;
    529         }
    530 
    531         // XXX: The spec draft is inconsistent as to whether this should
    532         // return an EGLint or void.  Ignore the return value for now, as
    533         // it's not strictly needed.
    534         eglWaitSyncKHR(mEglDisplay, sync, 0);
    535         EGLint eglErr = eglGetError();
    536         eglDestroySyncKHR(mEglDisplay, sync);
    537         if (eglErr != EGL_SUCCESS) {
    538             ALOGE("EglManager::fenceWait: error waiting for EGL fence: %#x", eglErr);
    539             return UNKNOWN_ERROR;
    540         }
    541     } else {
    542         // Block CPU on the fence.
    543         status_t err = fence->waitForever("EglManager::fenceWait");
    544         if (err != NO_ERROR) {
    545             ALOGE("EglManager::fenceWait: error waiting for fence: %d", err);
    546             return err;
    547         }
    548     }
    549     return OK;
    550 }
    551 
    552 status_t EglManager::createReleaseFence(bool useFenceSync, EGLSyncKHR* eglFence,
    553                                         sp<Fence>& nativeFence) {
    554     if (!hasEglContext()) {
    555         ALOGE("EglManager::createReleaseFence: EGLDisplay not initialized");
    556         return INVALID_OPERATION;
    557     }
    558 
    559     if (SyncFeatures::getInstance().useNativeFenceSync()) {
    560         EGLSyncKHR sync = eglCreateSyncKHR(mEglDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
    561         if (sync == EGL_NO_SYNC_KHR) {
    562             ALOGE("EglManager::createReleaseFence: error creating EGL fence: %#x", eglGetError());
    563             return UNKNOWN_ERROR;
    564         }
    565         glFlush();
    566         int fenceFd = eglDupNativeFenceFDANDROID(mEglDisplay, sync);
    567         eglDestroySyncKHR(mEglDisplay, sync);
    568         if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
    569             ALOGE("EglManager::createReleaseFence: error dup'ing native fence "
    570                   "fd: %#x",
    571                   eglGetError());
    572             return UNKNOWN_ERROR;
    573         }
    574         nativeFence = new Fence(fenceFd);
    575         *eglFence = EGL_NO_SYNC_KHR;
    576     } else if (useFenceSync && SyncFeatures::getInstance().useFenceSync()) {
    577         if (*eglFence != EGL_NO_SYNC_KHR) {
    578             // There is already a fence for the current slot.  We need to
    579             // wait on that before replacing it with another fence to
    580             // ensure that all outstanding buffer accesses have completed
    581             // before the producer accesses it.
    582             EGLint result = eglClientWaitSyncKHR(mEglDisplay, *eglFence, 0, 1000000000);
    583             if (result == EGL_FALSE) {
    584                 ALOGE("EglManager::createReleaseFence: error waiting for previous fence: %#x",
    585                       eglGetError());
    586                 return UNKNOWN_ERROR;
    587             } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
    588                 ALOGE("EglManager::createReleaseFence: timeout waiting for previous fence");
    589                 return TIMED_OUT;
    590             }
    591             eglDestroySyncKHR(mEglDisplay, *eglFence);
    592         }
    593 
    594         // Create a fence for the outstanding accesses in the current
    595         // OpenGL ES context.
    596         *eglFence = eglCreateSyncKHR(mEglDisplay, EGL_SYNC_FENCE_KHR, nullptr);
    597         if (*eglFence == EGL_NO_SYNC_KHR) {
    598             ALOGE("EglManager::createReleaseFence: error creating fence: %#x", eglGetError());
    599             return UNKNOWN_ERROR;
    600         }
    601         glFlush();
    602     }
    603     return OK;
    604 }
    605 
    606 } /* namespace renderthread */
    607 } /* namespace uirenderer */
    608 } /* namespace android */
    609