• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <EGL/eglext.h>
20 #include <GLES/gl.h>
21 #include <cutils/properties.h>
22 #include <log/log.h>
23 #include <sync/sync.h>
24 #include <utils/Trace.h>
25 
26 #include <string>
27 #include <vector>
28 
29 #include "Frame.h"
30 #include "Properties.h"
31 #include "utils/Color.h"
32 #include "utils/StringUtils.h"
33 
34 #define GLES_VERSION 2
35 
36 // Android-specific addition that is used to show when frames began in systrace
37 EGLAPI void EGLAPIENTRY eglBeginFrame(EGLDisplay dpy, EGLSurface surface);
38 
39 namespace android {
40 namespace uirenderer {
41 namespace renderthread {
42 
43 #define ERROR_CASE(x) \
44     case x:           \
45         return #x;
egl_error_str(EGLint error)46 static const char* egl_error_str(EGLint error) {
47     switch (error) {
48         ERROR_CASE(EGL_SUCCESS)
49         ERROR_CASE(EGL_NOT_INITIALIZED)
50         ERROR_CASE(EGL_BAD_ACCESS)
51         ERROR_CASE(EGL_BAD_ALLOC)
52         ERROR_CASE(EGL_BAD_ATTRIBUTE)
53         ERROR_CASE(EGL_BAD_CONFIG)
54         ERROR_CASE(EGL_BAD_CONTEXT)
55         ERROR_CASE(EGL_BAD_CURRENT_SURFACE)
56         ERROR_CASE(EGL_BAD_DISPLAY)
57         ERROR_CASE(EGL_BAD_MATCH)
58         ERROR_CASE(EGL_BAD_NATIVE_PIXMAP)
59         ERROR_CASE(EGL_BAD_NATIVE_WINDOW)
60         ERROR_CASE(EGL_BAD_PARAMETER)
61         ERROR_CASE(EGL_BAD_SURFACE)
62         ERROR_CASE(EGL_CONTEXT_LOST)
63         default:
64             return "Unknown error";
65     }
66 }
eglErrorString()67 const char* EglManager::eglErrorString() {
68     return egl_error_str(eglGetError());
69 }
70 
71 static struct {
72     bool bufferAge = false;
73     bool setDamage = false;
74     bool noConfigContext = false;
75     bool pixelFormatFloat = false;
76     bool glColorSpace = false;
77     bool scRGB = false;
78     bool displayP3 = false;
79     bool contextPriority = false;
80     bool surfacelessContext = false;
81     bool nativeFenceSync = false;
82     bool fenceSync = false;
83     bool waitSync = false;
84 } EglExtensions;
85 
EglManager()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 
~EglManager()95 EglManager::~EglManager() {
96     if (hasEglContext()) {
97         ALOGW("~EglManager() leaked an EGL context");
98     }
99 }
100 
initialize()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 
load8BitsConfig(EGLDisplay display,EglManager::SwapBehavior swapBehavior)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 
loadFP16Config(EGLDisplay display,SwapBehavior swapBehavior)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 extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
212 
initExtensions()213 void EglManager::initExtensions() {
214     auto extensions = StringUtils::split(eglQueryString(mEglDisplay, EGL_EXTENSIONS));
215     auto extensionsAndroid =
216             StringUtils::split(eglQueryStringImplementationANDROID(mEglDisplay, EGL_EXTENSIONS));
217 
218     // For our purposes we don't care if EGL_BUFFER_AGE is a result of
219     // EGL_EXT_buffer_age or EGL_KHR_partial_update as our usage is covered
220     // under EGL_KHR_partial_update and we don't need the expanded scope
221     // that EGL_EXT_buffer_age provides.
222     EglExtensions.bufferAge =
223             extensions.has("EGL_EXT_buffer_age") || extensions.has("EGL_KHR_partial_update");
224     EglExtensions.setDamage = extensions.has("EGL_KHR_partial_update");
225     LOG_ALWAYS_FATAL_IF(!extensions.has("EGL_KHR_swap_buffers_with_damage"),
226                         "Missing required extension EGL_KHR_swap_buffers_with_damage");
227 
228     EglExtensions.glColorSpace = extensions.has("EGL_KHR_gl_colorspace");
229     EglExtensions.noConfigContext = extensions.has("EGL_KHR_no_config_context");
230     EglExtensions.pixelFormatFloat = extensions.has("EGL_EXT_pixel_format_float");
231     EglExtensions.scRGB = extensions.has("EGL_EXT_gl_colorspace_scrgb");
232     EglExtensions.displayP3 = extensions.has("EGL_EXT_gl_colorspace_display_p3_passthrough");
233     EglExtensions.contextPriority = extensions.has("EGL_IMG_context_priority");
234     EglExtensions.surfacelessContext = extensions.has("EGL_KHR_surfaceless_context");
235     EglExtensions.fenceSync = extensions.has("EGL_KHR_fence_sync");
236     EglExtensions.waitSync = extensions.has("EGL_KHR_wait_sync");
237 
238     // EGL_ANDROID_native_fence_sync is not exposed to applications, so access
239     // this through the private Android-specific query instead.
240     EglExtensions.nativeFenceSync = extensionsAndroid.has("EGL_ANDROID_native_fence_sync");
241 }
242 
hasEglContext()243 bool EglManager::hasEglContext() {
244     return mEglDisplay != EGL_NO_DISPLAY;
245 }
246 
loadConfigs()247 void EglManager::loadConfigs() {
248     // Note: The default pixel format is RGBA_8888, when other formats are
249     // available, we should check the target pixel format and configure the
250     // attributes list properly.
251     mEglConfig = load8BitsConfig(mEglDisplay, mSwapBehavior);
252     if (mEglConfig == EGL_NO_CONFIG_KHR) {
253         if (mSwapBehavior == SwapBehavior::Preserved) {
254             // Try again without dirty regions enabled
255             ALOGW("Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...");
256             mSwapBehavior = SwapBehavior::Discard;
257             mEglConfig = load8BitsConfig(mEglDisplay, mSwapBehavior);
258         } else {
259             // Failed to get a valid config
260             LOG_ALWAYS_FATAL("Failed to choose config, error = %s", eglErrorString());
261         }
262     }
263     SkColorType wideColorType = DeviceInfo::get()->getWideColorType();
264 
265     // When we reach this point, we have a valid swap behavior
266     if (wideColorType == SkColorType::kRGBA_F16_SkColorType && EglExtensions.pixelFormatFloat) {
267         mEglConfigWideGamut = loadFP16Config(mEglDisplay, mSwapBehavior);
268         if (mEglConfigWideGamut == EGL_NO_CONFIG_KHR) {
269             ALOGE("Device claims wide gamut support, cannot find matching config, error = %s",
270                   eglErrorString());
271             EglExtensions.pixelFormatFloat = false;
272         }
273     } else if (wideColorType == SkColorType::kN32_SkColorType) {
274         mEglConfigWideGamut = load8BitsConfig(mEglDisplay, mSwapBehavior);
275     }
276 }
277 
createContext()278 void EglManager::createContext() {
279     std::vector<EGLint> contextAttributes;
280     contextAttributes.reserve(5);
281     contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
282     contextAttributes.push_back(GLES_VERSION);
283     if (Properties::contextPriority != 0 && EglExtensions.contextPriority) {
284         contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
285         contextAttributes.push_back(Properties::contextPriority);
286     }
287     contextAttributes.push_back(EGL_NONE);
288     mEglContext = eglCreateContext(
289             mEglDisplay, EglExtensions.noConfigContext ? ((EGLConfig) nullptr) : mEglConfig,
290             EGL_NO_CONTEXT, contextAttributes.data());
291     LOG_ALWAYS_FATAL_IF(mEglContext == EGL_NO_CONTEXT, "Failed to create context, error = %s",
292                         eglErrorString());
293 }
294 
createPBufferSurface()295 void EglManager::createPBufferSurface() {
296     LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY,
297                         "usePBufferSurface() called on uninitialized GlobalContext!");
298 
299     if (mPBufferSurface == EGL_NO_SURFACE && !EglExtensions.surfacelessContext) {
300         EGLint attribs[] = {EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE};
301         mPBufferSurface = eglCreatePbufferSurface(mEglDisplay, mEglConfig, attribs);
302         LOG_ALWAYS_FATAL_IF(mPBufferSurface == EGL_NO_SURFACE,
303                             "Failed to create a pixel buffer display=%p, "
304                             "mEglConfig=%p, error=%s",
305                             mEglDisplay, mEglConfig, eglErrorString());
306     }
307 }
308 
createSurface(EGLNativeWindowType window,ColorMode colorMode,sk_sp<SkColorSpace> colorSpace)309 Result<EGLSurface, EGLint> EglManager::createSurface(EGLNativeWindowType window,
310                                                      ColorMode colorMode,
311                                                      sk_sp<SkColorSpace> colorSpace) {
312     LOG_ALWAYS_FATAL_IF(!hasEglContext(), "Not initialized");
313 
314     bool wideColorGamut = colorMode == ColorMode::WideColorGamut && mHasWideColorGamutSupport &&
315                           EglExtensions.noConfigContext;
316 
317     // The color space we want to use depends on whether linear blending is turned
318     // on and whether the app has requested wide color gamut rendering. When wide
319     // color gamut rendering is off, the app simply renders in the display's native
320     // color gamut.
321     //
322     // When wide gamut rendering is off:
323     // - Blending is done by default in gamma space, which requires using a
324     //   linear EGL color space (the GPU uses the color values as is)
325     // - If linear blending is on, we must use the non-linear EGL color space
326     //   (the GPU will perform sRGB to linear and linear to SRGB conversions
327     //   before and after blending)
328     //
329     // When wide gamut rendering is on we cannot rely on the GPU performing
330     // linear blending for us. We use two different color spaces to tag the
331     // surface appropriately for SurfaceFlinger:
332     // - Gamma blending (default) requires the use of the non-linear color space
333     // - Linear blending requires the use of the linear color space
334 
335     // Not all Android targets support the EGL_GL_COLORSPACE_KHR extension
336     // We insert to placeholders to set EGL_GL_COLORSPACE_KHR and its value.
337     // According to section 3.4.1 of the EGL specification, the attributes
338     // list is considered empty if the first entry is EGL_NONE
339     EGLint attribs[] = {EGL_NONE, EGL_NONE, EGL_NONE};
340 
341     if (EglExtensions.glColorSpace) {
342         attribs[0] = EGL_GL_COLORSPACE_KHR;
343         if (wideColorGamut) {
344             skcms_Matrix3x3 colorGamut;
345             LOG_ALWAYS_FATAL_IF(!colorSpace->toXYZD50(&colorGamut),
346                                 "Could not get gamut matrix from color space");
347             if (memcmp(&colorGamut, &SkNamedGamut::kDCIP3, sizeof(colorGamut)) == 0) {
348                 attribs[1] = EGL_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH_EXT;
349             } else if (memcmp(&colorGamut, &SkNamedGamut::kSRGB, sizeof(colorGamut)) == 0) {
350                 attribs[1] = EGL_GL_COLORSPACE_SCRGB_EXT;
351             } else {
352                 LOG_ALWAYS_FATAL("Unreachable: unsupported wide color space.");
353             }
354         } else {
355             attribs[1] = EGL_GL_COLORSPACE_LINEAR_KHR;
356         }
357     }
358 
359     EGLSurface surface = eglCreateWindowSurface(
360             mEglDisplay, wideColorGamut ? mEglConfigWideGamut : mEglConfig, window, attribs);
361     if (surface == EGL_NO_SURFACE) {
362         return Error<EGLint>{eglGetError()};
363     }
364 
365     if (mSwapBehavior != SwapBehavior::Preserved) {
366         LOG_ALWAYS_FATAL_IF(eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR,
367                                              EGL_BUFFER_DESTROYED) == EGL_FALSE,
368                             "Failed to set swap behavior to destroyed for window %p, eglErr = %s",
369                             (void*)window, eglErrorString());
370     }
371 
372     return surface;
373 }
374 
destroySurface(EGLSurface surface)375 void EglManager::destroySurface(EGLSurface surface) {
376     if (isCurrent(surface)) {
377         makeCurrent(EGL_NO_SURFACE);
378     }
379     if (!eglDestroySurface(mEglDisplay, surface)) {
380         ALOGW("Failed to destroy surface %p, error=%s", (void*)surface, eglErrorString());
381     }
382 }
383 
destroy()384 void EglManager::destroy() {
385     if (mEglDisplay == EGL_NO_DISPLAY) return;
386 
387     eglDestroyContext(mEglDisplay, mEglContext);
388     if (mPBufferSurface != EGL_NO_SURFACE) {
389         eglDestroySurface(mEglDisplay, mPBufferSurface);
390     }
391     eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
392     eglTerminate(mEglDisplay);
393     eglReleaseThread();
394 
395     mEglDisplay = EGL_NO_DISPLAY;
396     mEglContext = EGL_NO_CONTEXT;
397     mPBufferSurface = EGL_NO_SURFACE;
398     mCurrentSurface = EGL_NO_SURFACE;
399 }
400 
makeCurrent(EGLSurface surface,EGLint * errOut,bool force)401 bool EglManager::makeCurrent(EGLSurface surface, EGLint* errOut, bool force) {
402     if (!force && isCurrent(surface)) return false;
403 
404     if (surface == EGL_NO_SURFACE) {
405         // Ensure we always have a valid surface & context
406         surface = mPBufferSurface;
407     }
408     if (!eglMakeCurrent(mEglDisplay, surface, surface, mEglContext)) {
409         if (errOut) {
410             *errOut = eglGetError();
411             ALOGW("Failed to make current on surface %p, error=%s", (void*)surface,
412                   egl_error_str(*errOut));
413         } else {
414             LOG_ALWAYS_FATAL("Failed to make current on surface %p, error=%s", (void*)surface,
415                              eglErrorString());
416         }
417     }
418     mCurrentSurface = surface;
419     if (Properties::disableVsync) {
420         eglSwapInterval(mEglDisplay, 0);
421     }
422     return true;
423 }
424 
queryBufferAge(EGLSurface surface)425 EGLint EglManager::queryBufferAge(EGLSurface surface) {
426     switch (mSwapBehavior) {
427         case SwapBehavior::Discard:
428             return 0;
429         case SwapBehavior::Preserved:
430             return 1;
431         case SwapBehavior::BufferAge:
432             EGLint bufferAge;
433             eglQuerySurface(mEglDisplay, surface, EGL_BUFFER_AGE_EXT, &bufferAge);
434             return bufferAge;
435     }
436     return 0;
437 }
438 
beginFrame(EGLSurface surface)439 Frame EglManager::beginFrame(EGLSurface surface) {
440     LOG_ALWAYS_FATAL_IF(surface == EGL_NO_SURFACE, "Tried to beginFrame on EGL_NO_SURFACE!");
441     makeCurrent(surface);
442     Frame frame;
443     frame.mSurface = surface;
444     eglQuerySurface(mEglDisplay, surface, EGL_WIDTH, &frame.mWidth);
445     eglQuerySurface(mEglDisplay, surface, EGL_HEIGHT, &frame.mHeight);
446     frame.mBufferAge = queryBufferAge(surface);
447     eglBeginFrame(mEglDisplay, surface);
448     return frame;
449 }
450 
damageFrame(const Frame & frame,const SkRect & dirty)451 void EglManager::damageFrame(const Frame& frame, const SkRect& dirty) {
452 #ifdef EGL_KHR_partial_update
453     if (EglExtensions.setDamage && mSwapBehavior == SwapBehavior::BufferAge) {
454         EGLint rects[4];
455         frame.map(dirty, rects);
456         if (!eglSetDamageRegionKHR(mEglDisplay, frame.mSurface, rects, 1)) {
457             LOG_ALWAYS_FATAL("Failed to set damage region on surface %p, error=%s",
458                              (void*)frame.mSurface, eglErrorString());
459         }
460     }
461 #endif
462 }
463 
damageRequiresSwap()464 bool EglManager::damageRequiresSwap() {
465     return EglExtensions.setDamage && mSwapBehavior == SwapBehavior::BufferAge;
466 }
467 
swapBuffers(const Frame & frame,const SkRect & screenDirty)468 bool EglManager::swapBuffers(const Frame& frame, const SkRect& screenDirty) {
469     if (CC_UNLIKELY(Properties::waitForGpuCompletion)) {
470         ATRACE_NAME("Finishing GPU work");
471         fence();
472     }
473 
474     EGLint rects[4];
475     frame.map(screenDirty, rects);
476     eglSwapBuffersWithDamageKHR(mEglDisplay, frame.mSurface, rects, screenDirty.isEmpty() ? 0 : 1);
477 
478     EGLint err = eglGetError();
479     if (CC_LIKELY(err == EGL_SUCCESS)) {
480         return true;
481     }
482     if (err == EGL_BAD_SURFACE || err == EGL_BAD_NATIVE_WINDOW) {
483         // For some reason our surface was destroyed out from under us
484         // This really shouldn't happen, but if it does we can recover easily
485         // by just not trying to use the surface anymore
486         ALOGW("swapBuffers encountered EGL error %d on %p, halting rendering...", err,
487               frame.mSurface);
488         return false;
489     }
490     LOG_ALWAYS_FATAL("Encountered EGL error %d %s during rendering", err, egl_error_str(err));
491     // Impossible to hit this, but the compiler doesn't know that
492     return false;
493 }
494 
fence()495 void EglManager::fence() {
496     EGLSyncKHR fence = eglCreateSyncKHR(mEglDisplay, EGL_SYNC_FENCE_KHR, NULL);
497     eglClientWaitSyncKHR(mEglDisplay, fence, EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, EGL_FOREVER_KHR);
498     eglDestroySyncKHR(mEglDisplay, fence);
499 }
500 
setPreserveBuffer(EGLSurface surface,bool preserve)501 bool EglManager::setPreserveBuffer(EGLSurface surface, bool preserve) {
502     if (mSwapBehavior != SwapBehavior::Preserved) return false;
503 
504     bool preserved = eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR,
505                                       preserve ? EGL_BUFFER_PRESERVED : EGL_BUFFER_DESTROYED);
506     if (!preserved) {
507         ALOGW("Failed to set EGL_SWAP_BEHAVIOR on surface %p, error=%s", (void*)surface,
508               eglErrorString());
509         // Maybe it's already set?
510         EGLint swapBehavior;
511         if (eglQuerySurface(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, &swapBehavior)) {
512             preserved = (swapBehavior == EGL_BUFFER_PRESERVED);
513         } else {
514             ALOGW("Failed to query EGL_SWAP_BEHAVIOR on surface %p, error=%p", (void*)surface,
515                   eglErrorString());
516         }
517     }
518 
519     return preserved;
520 }
521 
waitForeverOnFence(int fence,const char * logname)522 static status_t waitForeverOnFence(int fence, const char* logname) {
523     ATRACE_CALL();
524     if (fence == -1) {
525         return NO_ERROR;
526     }
527     constexpr int warningTimeout = 3000;
528     int err = sync_wait(fence, warningTimeout);
529     if (err < 0 && errno == ETIME) {
530         ALOGE("%s: fence %d didn't signal in %d ms", logname, fence, warningTimeout);
531         err = sync_wait(fence, -1);
532     }
533     return err < 0 ? -errno : status_t(NO_ERROR);
534 }
535 
fenceWait(int fence)536 status_t EglManager::fenceWait(int fence) {
537     if (!hasEglContext()) {
538         ALOGE("EglManager::fenceWait: EGLDisplay not initialized");
539         return INVALID_OPERATION;
540     }
541 
542     if (EglExtensions.waitSync && EglExtensions.nativeFenceSync) {
543         // Block GPU on the fence.
544         // Create an EGLSyncKHR from the current fence.
545         int fenceFd = ::dup(fence);
546         if (fenceFd == -1) {
547             ALOGE("EglManager::fenceWait: error dup'ing fence fd: %d", errno);
548             return -errno;
549         }
550         EGLint attribs[] = {EGL_SYNC_NATIVE_FENCE_FD_ANDROID, fenceFd, EGL_NONE};
551         EGLSyncKHR sync = eglCreateSyncKHR(mEglDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, attribs);
552         if (sync == EGL_NO_SYNC_KHR) {
553             close(fenceFd);
554             ALOGE("EglManager::fenceWait: error creating EGL fence: %#x", eglGetError());
555             return UNKNOWN_ERROR;
556         }
557 
558         // XXX: The spec draft is inconsistent as to whether this should
559         // return an EGLint or void.  Ignore the return value for now, as
560         // it's not strictly needed.
561         eglWaitSyncKHR(mEglDisplay, sync, 0);
562         EGLint eglErr = eglGetError();
563         eglDestroySyncKHR(mEglDisplay, sync);
564         if (eglErr != EGL_SUCCESS) {
565             ALOGE("EglManager::fenceWait: error waiting for EGL fence: %#x", eglErr);
566             return UNKNOWN_ERROR;
567         }
568     } else {
569         // Block CPU on the fence.
570         status_t err = waitForeverOnFence(fence, "EglManager::fenceWait");
571         if (err != NO_ERROR) {
572             ALOGE("EglManager::fenceWait: error waiting for fence: %d", err);
573             return err;
574         }
575     }
576     return OK;
577 }
578 
createReleaseFence(bool useFenceSync,EGLSyncKHR * eglFence,int * nativeFence)579 status_t EglManager::createReleaseFence(bool useFenceSync, EGLSyncKHR* eglFence, int* nativeFence) {
580     *nativeFence = -1;
581     if (!hasEglContext()) {
582         ALOGE("EglManager::createReleaseFence: EGLDisplay not initialized");
583         return INVALID_OPERATION;
584     }
585 
586     if (EglExtensions.nativeFenceSync) {
587         EGLSyncKHR sync = eglCreateSyncKHR(mEglDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, nullptr);
588         if (sync == EGL_NO_SYNC_KHR) {
589             ALOGE("EglManager::createReleaseFence: error creating EGL fence: %#x", eglGetError());
590             return UNKNOWN_ERROR;
591         }
592         glFlush();
593         int fenceFd = eglDupNativeFenceFDANDROID(mEglDisplay, sync);
594         eglDestroySyncKHR(mEglDisplay, sync);
595         if (fenceFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
596             ALOGE("EglManager::createReleaseFence: error dup'ing native fence "
597                   "fd: %#x",
598                   eglGetError());
599             return UNKNOWN_ERROR;
600         }
601         *nativeFence = fenceFd;
602         *eglFence = EGL_NO_SYNC_KHR;
603     } else if (useFenceSync && EglExtensions.fenceSync) {
604         if (*eglFence != EGL_NO_SYNC_KHR) {
605             // There is already a fence for the current slot.  We need to
606             // wait on that before replacing it with another fence to
607             // ensure that all outstanding buffer accesses have completed
608             // before the producer accesses it.
609             EGLint result = eglClientWaitSyncKHR(mEglDisplay, *eglFence, 0, 1000000000);
610             if (result == EGL_FALSE) {
611                 ALOGE("EglManager::createReleaseFence: error waiting for previous fence: %#x",
612                       eglGetError());
613                 return UNKNOWN_ERROR;
614             } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
615                 ALOGE("EglManager::createReleaseFence: timeout waiting for previous fence");
616                 return TIMED_OUT;
617             }
618             eglDestroySyncKHR(mEglDisplay, *eglFence);
619         }
620 
621         // Create a fence for the outstanding accesses in the current
622         // OpenGL ES context.
623         *eglFence = eglCreateSyncKHR(mEglDisplay, EGL_SYNC_FENCE_KHR, nullptr);
624         if (*eglFence == EGL_NO_SYNC_KHR) {
625             ALOGE("EglManager::createReleaseFence: error creating fence: %#x", eglGetError());
626             return UNKNOWN_ERROR;
627         }
628         glFlush();
629     }
630     return OK;
631 }
632 
633 } /* namespace renderthread */
634 } /* namespace uirenderer */
635 } /* namespace android */
636