Home | History | Annotate | Download | only in surfaceflinger
      1 /*
      2  * Copyright (C) 2007 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 // #define LOG_NDEBUG 0
     18 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
     19 
     20 #include <stdint.h>
     21 #include <sys/types.h>
     22 #include <algorithm>
     23 #include <errno.h>
     24 #include <math.h>
     25 #include <mutex>
     26 #include <dlfcn.h>
     27 #include <inttypes.h>
     28 #include <stdatomic.h>
     29 #include <optional>
     30 
     31 #include <EGL/egl.h>
     32 
     33 #include <cutils/properties.h>
     34 #include <log/log.h>
     35 
     36 #include <binder/IPCThreadState.h>
     37 #include <binder/IServiceManager.h>
     38 #include <binder/PermissionCache.h>
     39 
     40 #include <dvr/vr_flinger.h>
     41 
     42 #include <ui/DebugUtils.h>
     43 #include <ui/DisplayInfo.h>
     44 #include <ui/DisplayStatInfo.h>
     45 
     46 #include <gui/BufferQueue.h>
     47 #include <gui/GuiConfig.h>
     48 #include <gui/IDisplayEventConnection.h>
     49 #include <gui/Surface.h>
     50 
     51 #include <ui/GraphicBufferAllocator.h>
     52 #include <ui/PixelFormat.h>
     53 #include <ui/UiConfig.h>
     54 
     55 #include <utils/misc.h>
     56 #include <utils/String8.h>
     57 #include <utils/String16.h>
     58 #include <utils/StopWatch.h>
     59 #include <utils/Timers.h>
     60 #include <utils/Trace.h>
     61 
     62 #include <private/android_filesystem_config.h>
     63 #include <private/gui/SyncFeatures.h>
     64 
     65 #include "Client.h"
     66 #include "clz.h"
     67 #include "Colorizer.h"
     68 #include "DdmConnection.h"
     69 #include "DisplayDevice.h"
     70 #include "DispSync.h"
     71 #include "EventControlThread.h"
     72 #include "EventThread.h"
     73 #include "Layer.h"
     74 #include "LayerVector.h"
     75 #include "LayerDim.h"
     76 #include "MonitoredProducer.h"
     77 #include "SurfaceFlinger.h"
     78 
     79 #include "DisplayHardware/ComposerHal.h"
     80 #include "DisplayHardware/FramebufferSurface.h"
     81 #include "DisplayHardware/HWComposer.h"
     82 #include "DisplayHardware/VirtualDisplaySurface.h"
     83 
     84 #include "Effects/Daltonizer.h"
     85 
     86 #include "RenderEngine/RenderEngine.h"
     87 #include <cutils/compiler.h>
     88 
     89 #include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
     90 #include <configstore/Utils.h>
     91 
     92 #define DISPLAY_COUNT       1
     93 
     94 /*
     95  * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
     96  * black pixels.
     97  */
     98 #define DEBUG_SCREENSHOTS   false
     99 
    100 extern "C" EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
    101 
    102 namespace android {
    103 
    104 using namespace android::hardware::configstore;
    105 using namespace android::hardware::configstore::V1_0;
    106 
    107 namespace {
    108 class ConditionalLock {
    109 public:
    110     ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
    111         if (lock) {
    112             mMutex.lock();
    113         }
    114     }
    115     ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
    116 private:
    117     Mutex& mMutex;
    118     bool mLocked;
    119 };
    120 }  // namespace anonymous
    121 
    122 // ---------------------------------------------------------------------------
    123 
    124 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
    125 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
    126 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
    127 const String16 sDump("android.permission.DUMP");
    128 
    129 // ---------------------------------------------------------------------------
    130 int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
    131 int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
    132 bool SurfaceFlinger::useContextPriority;
    133 int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
    134 bool SurfaceFlinger::useHwcForRgbToYuv;
    135 uint64_t SurfaceFlinger::maxVirtualDisplaySize;
    136 bool SurfaceFlinger::hasSyncFramework;
    137 bool SurfaceFlinger::useVrFlinger;
    138 int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
    139 bool SurfaceFlinger::hasWideColorDisplay;
    140 
    141 SurfaceFlinger::SurfaceFlinger()
    142     :   BnSurfaceComposer(),
    143         mTransactionFlags(0),
    144         mTransactionPending(false),
    145         mAnimTransactionPending(false),
    146         mLayersRemoved(false),
    147         mLayersAdded(false),
    148         mRepaintEverything(0),
    149         mRenderEngine(nullptr),
    150         mBootTime(systemTime()),
    151         mBuiltinDisplays(),
    152         mVisibleRegionsDirty(false),
    153         mGeometryInvalid(false),
    154         mAnimCompositionPending(false),
    155         mDebugRegion(0),
    156         mDebugDDMS(0),
    157         mDebugDisableHWC(0),
    158         mDebugDisableTransformHint(0),
    159         mDebugInSwapBuffers(0),
    160         mLastSwapBufferTime(0),
    161         mDebugInTransaction(0),
    162         mLastTransactionTime(0),
    163         mBootFinished(false),
    164         mForceFullDamage(false),
    165         mInterceptor(this),
    166         mPrimaryDispSync("PrimaryDispSync"),
    167         mPrimaryHWVsyncEnabled(false),
    168         mHWVsyncAvailable(false),
    169         mHasColorMatrix(false),
    170         mHasPoweredOff(false),
    171         mFrameBuckets(),
    172         mTotalTime(0),
    173         mLastSwapTime(0),
    174         mNumLayers(0),
    175         mVrFlingerRequestsDisplay(false),
    176         mMainThreadId(std::this_thread::get_id()),
    177         mComposerSequenceId(0)
    178 {
    179     ALOGI("SurfaceFlinger is starting");
    180 
    181     vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
    182             &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
    183 
    184     sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
    185             &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
    186 
    187     hasSyncFramework = getBool< ISurfaceFlingerConfigs,
    188             &ISurfaceFlingerConfigs::hasSyncFramework>(true);
    189 
    190     useContextPriority = getBool< ISurfaceFlingerConfigs,
    191             &ISurfaceFlingerConfigs::useContextPriority>(false);
    192 
    193     dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
    194             &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
    195 
    196     useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
    197             &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
    198 
    199     maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
    200             &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
    201 
    202     // Vr flinger is only enabled on Daydream ready devices.
    203     useVrFlinger = getBool< ISurfaceFlingerConfigs,
    204             &ISurfaceFlingerConfigs::useVrFlinger>(false);
    205 
    206     maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
    207             &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
    208 
    209     hasWideColorDisplay =
    210             getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
    211 
    212     mPrimaryDispSync.init(hasSyncFramework, dispSyncPresentTimeOffset);
    213 
    214     // debugging stuff...
    215     char value[PROPERTY_VALUE_MAX];
    216 
    217     property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
    218     mGpuToCpuSupported = !atoi(value);
    219 
    220     property_get("debug.sf.showupdates", value, "0");
    221     mDebugRegion = atoi(value);
    222 
    223     property_get("debug.sf.ddms", value, "0");
    224     mDebugDDMS = atoi(value);
    225     if (mDebugDDMS) {
    226         if (!startDdmConnection()) {
    227             // start failed, and DDMS debugging not enabled
    228             mDebugDDMS = 0;
    229         }
    230     }
    231     ALOGI_IF(mDebugRegion, "showupdates enabled");
    232     ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
    233 
    234     property_get("debug.sf.disable_backpressure", value, "0");
    235     mPropagateBackpressure = !atoi(value);
    236     ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
    237 
    238     property_get("debug.sf.enable_hwc_vds", value, "0");
    239     mUseHwcVirtualDisplays = atoi(value);
    240     ALOGI_IF(!mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
    241 
    242     property_get("ro.sf.disable_triple_buffer", value, "1");
    243     mLayerTripleBufferingDisabled = atoi(value);
    244     ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
    245 
    246     // We should be reading 'persist.sys.sf.color_saturation' here
    247     // but since /data may be encrypted, we need to wait until after vold
    248     // comes online to attempt to read the property. The property is
    249     // instead read after the boot animation
    250 }
    251 
    252 void SurfaceFlinger::onFirstRef()
    253 {
    254     mEventQueue.init(this);
    255 }
    256 
    257 SurfaceFlinger::~SurfaceFlinger()
    258 {
    259     EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    260     eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
    261     eglTerminate(display);
    262 }
    263 
    264 void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
    265 {
    266     // the window manager died on us. prepare its eulogy.
    267 
    268     // restore initial conditions (default device unblank, etc)
    269     initializeDisplays();
    270 
    271     // restart the boot-animation
    272     startBootAnim();
    273 }
    274 
    275 static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
    276     status_t err = client->initCheck();
    277     if (err == NO_ERROR) {
    278         return client;
    279     }
    280     return nullptr;
    281 }
    282 
    283 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
    284     return initClient(new Client(this));
    285 }
    286 
    287 sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
    288         const sp<IGraphicBufferProducer>& gbp) {
    289     if (authenticateSurfaceTexture(gbp) == false) {
    290         return nullptr;
    291     }
    292     const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
    293     if (layer == nullptr) {
    294         return nullptr;
    295     }
    296 
    297    return initClient(new Client(this, layer));
    298 }
    299 
    300 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
    301         bool secure)
    302 {
    303     class DisplayToken : public BBinder {
    304         sp<SurfaceFlinger> flinger;
    305         virtual ~DisplayToken() {
    306              // no more references, this display must be terminated
    307              Mutex::Autolock _l(flinger->mStateLock);
    308              flinger->mCurrentState.displays.removeItem(this);
    309              flinger->setTransactionFlags(eDisplayTransactionNeeded);
    310          }
    311      public:
    312         explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
    313             : flinger(flinger) {
    314         }
    315     };
    316 
    317     sp<BBinder> token = new DisplayToken(this);
    318 
    319     Mutex::Autolock _l(mStateLock);
    320     DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
    321     info.displayName = displayName;
    322     mCurrentState.displays.add(token, info);
    323     mInterceptor.saveDisplayCreation(info);
    324     return token;
    325 }
    326 
    327 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
    328     Mutex::Autolock _l(mStateLock);
    329 
    330     ssize_t idx = mCurrentState.displays.indexOfKey(display);
    331     if (idx < 0) {
    332         ALOGW("destroyDisplay: invalid display token");
    333         return;
    334     }
    335 
    336     const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
    337     if (!info.isVirtualDisplay()) {
    338         ALOGE("destroyDisplay called for non-virtual display");
    339         return;
    340     }
    341     mInterceptor.saveDisplayDeletion(info.displayId);
    342     mCurrentState.displays.removeItemsAt(idx);
    343     setTransactionFlags(eDisplayTransactionNeeded);
    344 }
    345 
    346 void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
    347     ALOGV("createBuiltinDisplayLocked(%d)", type);
    348     ALOGW_IF(mBuiltinDisplays[type],
    349             "Overwriting display token for display type %d", type);
    350     mBuiltinDisplays[type] = new BBinder();
    351     // All non-virtual displays are currently considered secure.
    352     DisplayDeviceState info(type, true);
    353     mCurrentState.displays.add(mBuiltinDisplays[type], info);
    354     mInterceptor.saveDisplayCreation(info);
    355 }
    356 
    357 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
    358     if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
    359         ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
    360         return NULL;
    361     }
    362     return mBuiltinDisplays[id];
    363 }
    364 
    365 void SurfaceFlinger::bootFinished()
    366 {
    367     if (mStartPropertySetThread->join() != NO_ERROR) {
    368         ALOGE("Join StartPropertySetThread failed!");
    369     }
    370     const nsecs_t now = systemTime();
    371     const nsecs_t duration = now - mBootTime;
    372     ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
    373 
    374     // wait patiently for the window manager death
    375     const String16 name("window");
    376     sp<IBinder> window(defaultServiceManager()->getService(name));
    377     if (window != 0) {
    378         window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
    379     }
    380 
    381     if (mVrFlinger) {
    382       mVrFlinger->OnBootFinished();
    383     }
    384 
    385     // stop boot animation
    386     // formerly we would just kill the process, but we now ask it to exit so it
    387     // can choose where to stop the animation.
    388     property_set("service.bootanim.exit", "1");
    389 
    390     const int LOGTAG_SF_STOP_BOOTANIM = 60110;
    391     LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
    392                    ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
    393 
    394     sp<LambdaMessage> readProperties = new LambdaMessage([&]() {
    395         readPersistentProperties();
    396     });
    397     postMessageAsync(readProperties);
    398 }
    399 
    400 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
    401     class MessageDestroyGLTexture : public MessageBase {
    402         RenderEngine& engine;
    403         uint32_t texture;
    404     public:
    405         MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
    406             : engine(engine), texture(texture) {
    407         }
    408         virtual bool handler() {
    409             engine.deleteTextures(1, &texture);
    410             return true;
    411         }
    412     };
    413     postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
    414 }
    415 
    416 class DispSyncSource : public VSyncSource, private DispSync::Callback {
    417 public:
    418     DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
    419         const char* name) :
    420             mName(name),
    421             mValue(0),
    422             mTraceVsync(traceVsync),
    423             mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
    424             mVsyncEventLabel(String8::format("VSYNC-%s", name)),
    425             mDispSync(dispSync),
    426             mCallbackMutex(),
    427             mCallback(),
    428             mVsyncMutex(),
    429             mPhaseOffset(phaseOffset),
    430             mEnabled(false) {}
    431 
    432     virtual ~DispSyncSource() {}
    433 
    434     virtual void setVSyncEnabled(bool enable) {
    435         Mutex::Autolock lock(mVsyncMutex);
    436         if (enable) {
    437             status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
    438                     static_cast<DispSync::Callback*>(this));
    439             if (err != NO_ERROR) {
    440                 ALOGE("error registering vsync callback: %s (%d)",
    441                         strerror(-err), err);
    442             }
    443             //ATRACE_INT(mVsyncOnLabel.string(), 1);
    444         } else {
    445             status_t err = mDispSync->removeEventListener(
    446                     static_cast<DispSync::Callback*>(this));
    447             if (err != NO_ERROR) {
    448                 ALOGE("error unregistering vsync callback: %s (%d)",
    449                         strerror(-err), err);
    450             }
    451             //ATRACE_INT(mVsyncOnLabel.string(), 0);
    452         }
    453         mEnabled = enable;
    454     }
    455 
    456     virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
    457         Mutex::Autolock lock(mCallbackMutex);
    458         mCallback = callback;
    459     }
    460 
    461     virtual void setPhaseOffset(nsecs_t phaseOffset) {
    462         Mutex::Autolock lock(mVsyncMutex);
    463 
    464         // Normalize phaseOffset to [0, period)
    465         auto period = mDispSync->getPeriod();
    466         phaseOffset %= period;
    467         if (phaseOffset < 0) {
    468             // If we're here, then phaseOffset is in (-period, 0). After this
    469             // operation, it will be in (0, period)
    470             phaseOffset += period;
    471         }
    472         mPhaseOffset = phaseOffset;
    473 
    474         // If we're not enabled, we don't need to mess with the listeners
    475         if (!mEnabled) {
    476             return;
    477         }
    478 
    479         // Remove the listener with the old offset
    480         status_t err = mDispSync->removeEventListener(
    481                 static_cast<DispSync::Callback*>(this));
    482         if (err != NO_ERROR) {
    483             ALOGE("error unregistering vsync callback: %s (%d)",
    484                     strerror(-err), err);
    485         }
    486 
    487         // Add a listener with the new offset
    488         err = mDispSync->addEventListener(mName, mPhaseOffset,
    489                 static_cast<DispSync::Callback*>(this));
    490         if (err != NO_ERROR) {
    491             ALOGE("error registering vsync callback: %s (%d)",
    492                     strerror(-err), err);
    493         }
    494     }
    495 
    496 private:
    497     virtual void onDispSyncEvent(nsecs_t when) {
    498         sp<VSyncSource::Callback> callback;
    499         {
    500             Mutex::Autolock lock(mCallbackMutex);
    501             callback = mCallback;
    502 
    503             if (mTraceVsync) {
    504                 mValue = (mValue + 1) % 2;
    505                 ATRACE_INT(mVsyncEventLabel.string(), mValue);
    506             }
    507         }
    508 
    509         if (callback != NULL) {
    510             callback->onVSyncEvent(when);
    511         }
    512     }
    513 
    514     const char* const mName;
    515 
    516     int mValue;
    517 
    518     const bool mTraceVsync;
    519     const String8 mVsyncOnLabel;
    520     const String8 mVsyncEventLabel;
    521 
    522     DispSync* mDispSync;
    523 
    524     Mutex mCallbackMutex; // Protects the following
    525     sp<VSyncSource::Callback> mCallback;
    526 
    527     Mutex mVsyncMutex; // Protects the following
    528     nsecs_t mPhaseOffset;
    529     bool mEnabled;
    530 };
    531 
    532 class InjectVSyncSource : public VSyncSource {
    533 public:
    534     InjectVSyncSource() {}
    535 
    536     virtual ~InjectVSyncSource() {}
    537 
    538     virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
    539         std::lock_guard<std::mutex> lock(mCallbackMutex);
    540         mCallback = callback;
    541     }
    542 
    543     virtual void onInjectSyncEvent(nsecs_t when) {
    544         std::lock_guard<std::mutex> lock(mCallbackMutex);
    545         mCallback->onVSyncEvent(when);
    546     }
    547 
    548     virtual void setVSyncEnabled(bool) {}
    549     virtual void setPhaseOffset(nsecs_t) {}
    550 
    551 private:
    552     std::mutex mCallbackMutex; // Protects the following
    553     sp<VSyncSource::Callback> mCallback;
    554 };
    555 
    556 // Do not call property_set on main thread which will be blocked by init
    557 // Use StartPropertySetThread instead.
    558 void SurfaceFlinger::init() {
    559     ALOGI(  "SurfaceFlinger's main thread ready to run. "
    560             "Initializing graphics H/W...");
    561 
    562     ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
    563 
    564     Mutex::Autolock _l(mStateLock);
    565 
    566     // initialize EGL for the default display
    567     mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    568     eglInitialize(mEGLDisplay, NULL, NULL);
    569 
    570     // start the EventThread
    571     sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
    572             vsyncPhaseOffsetNs, true, "app");
    573     mEventThread = new EventThread(vsyncSrc, *this, false);
    574     sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
    575             sfVsyncPhaseOffsetNs, true, "sf");
    576     mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
    577     mEventQueue.setEventThread(mSFEventThread);
    578 
    579     // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
    580     struct sched_param param = {0};
    581     param.sched_priority = 2;
    582     if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
    583         ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
    584     }
    585     if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
    586         ALOGE("Couldn't set SCHED_FIFO for EventThread");
    587     }
    588 
    589     // Get a RenderEngine for the given display / config (can't fail)
    590     mRenderEngine = RenderEngine::create(mEGLDisplay,
    591             HAL_PIXEL_FORMAT_RGBA_8888,
    592             hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
    593 
    594     // retrieve the EGL context that was selected/created
    595     mEGLContext = mRenderEngine->getEGLContext();
    596 
    597     LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
    598             "couldn't create EGLContext");
    599 
    600     LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
    601             "Starting with vr flinger active is not currently supported.");
    602     mHwc.reset(new HWComposer(false));
    603     mHwc->registerCallback(this, mComposerSequenceId);
    604 
    605     if (useVrFlinger) {
    606         auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
    607             // This callback is called from the vr flinger dispatch thread. We
    608             // need to call signalTransaction(), which requires holding
    609             // mStateLock when we're not on the main thread. Acquiring
    610             // mStateLock from the vr flinger dispatch thread might trigger a
    611             // deadlock in surface flinger (see b/66916578), so post a message
    612             // to be handled on the main thread instead.
    613             sp<LambdaMessage> message = new LambdaMessage([=]() {
    614                 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
    615                 mVrFlingerRequestsDisplay = requestDisplay;
    616                 signalTransaction();
    617             });
    618             postMessageAsync(message);
    619         };
    620         mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
    621                                             vrFlingerRequestDisplayCallback);
    622         if (!mVrFlinger) {
    623             ALOGE("Failed to start vrflinger");
    624         }
    625     }
    626 
    627     mEventControlThread = new EventControlThread(this);
    628     mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
    629 
    630     // initialize our drawing state
    631     mDrawingState = mCurrentState;
    632 
    633     // set initial conditions (e.g. unblank default device)
    634     initializeDisplays();
    635 
    636     mRenderEngine->primeCache();
    637 
    638     // Inform native graphics APIs whether the present timestamp is supported:
    639     if (getHwComposer().hasCapability(
    640             HWC2::Capability::PresentFenceIsNotReliable)) {
    641         mStartPropertySetThread = new StartPropertySetThread(false);
    642     } else {
    643         mStartPropertySetThread = new StartPropertySetThread(true);
    644     }
    645 
    646     if (mStartPropertySetThread->Start() != NO_ERROR) {
    647         ALOGE("Run StartPropertySetThread failed!");
    648     }
    649 
    650     ALOGV("Done initializing");
    651 }
    652 
    653 void SurfaceFlinger::readPersistentProperties() {
    654     char value[PROPERTY_VALUE_MAX];
    655 
    656     property_get("persist.sys.sf.color_saturation", value, "1.0");
    657     mSaturation = atof(value);
    658     ALOGV("Saturation is set to %.2f", mSaturation);
    659 
    660     property_get("persist.sys.sf.native_mode", value, "0");
    661     mForceNativeColorMode = atoi(value) == 1;
    662     if (mForceNativeColorMode) {
    663         ALOGV("Forcing native color mode");
    664     }
    665 }
    666 
    667 void SurfaceFlinger::startBootAnim() {
    668     // Start boot animation service by setting a property mailbox
    669     // if property setting thread is already running, Start() will be just a NOP
    670     mStartPropertySetThread->Start();
    671     // Wait until property was set
    672     if (mStartPropertySetThread->join() != NO_ERROR) {
    673         ALOGE("Join StartPropertySetThread failed!");
    674     }
    675 }
    676 
    677 size_t SurfaceFlinger::getMaxTextureSize() const {
    678     return mRenderEngine->getMaxTextureSize();
    679 }
    680 
    681 size_t SurfaceFlinger::getMaxViewportDims() const {
    682     return mRenderEngine->getMaxViewportDims();
    683 }
    684 
    685 // ----------------------------------------------------------------------------
    686 
    687 bool SurfaceFlinger::authenticateSurfaceTexture(
    688         const sp<IGraphicBufferProducer>& bufferProducer) const {
    689     Mutex::Autolock _l(mStateLock);
    690     return authenticateSurfaceTextureLocked(bufferProducer);
    691 }
    692 
    693 bool SurfaceFlinger::authenticateSurfaceTextureLocked(
    694         const sp<IGraphicBufferProducer>& bufferProducer) const {
    695     sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
    696     return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
    697 }
    698 
    699 status_t SurfaceFlinger::getSupportedFrameTimestamps(
    700         std::vector<FrameEvent>* outSupported) const {
    701     *outSupported = {
    702         FrameEvent::REQUESTED_PRESENT,
    703         FrameEvent::ACQUIRE,
    704         FrameEvent::LATCH,
    705         FrameEvent::FIRST_REFRESH_START,
    706         FrameEvent::LAST_REFRESH_START,
    707         FrameEvent::GPU_COMPOSITION_DONE,
    708         FrameEvent::DEQUEUE_READY,
    709         FrameEvent::RELEASE,
    710     };
    711     ConditionalLock _l(mStateLock,
    712             std::this_thread::get_id() != mMainThreadId);
    713     if (!getHwComposer().hasCapability(
    714             HWC2::Capability::PresentFenceIsNotReliable)) {
    715         outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
    716     }
    717     return NO_ERROR;
    718 }
    719 
    720 status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
    721         Vector<DisplayInfo>* configs) {
    722     if ((configs == NULL) || (display.get() == NULL)) {
    723         return BAD_VALUE;
    724     }
    725 
    726     if (!display.get())
    727         return NAME_NOT_FOUND;
    728 
    729     int32_t type = NAME_NOT_FOUND;
    730     for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
    731         if (display == mBuiltinDisplays[i]) {
    732             type = i;
    733             break;
    734         }
    735     }
    736 
    737     if (type < 0) {
    738         return type;
    739     }
    740 
    741     // TODO: Not sure if display density should handled by SF any longer
    742     class Density {
    743         static int getDensityFromProperty(char const* propName) {
    744             char property[PROPERTY_VALUE_MAX];
    745             int density = 0;
    746             if (property_get(propName, property, NULL) > 0) {
    747                 density = atoi(property);
    748             }
    749             return density;
    750         }
    751     public:
    752         static int getEmuDensity() {
    753             return getDensityFromProperty("qemu.sf.lcd_density"); }
    754         static int getBuildDensity()  {
    755             return getDensityFromProperty("ro.sf.lcd_density"); }
    756     };
    757 
    758     configs->clear();
    759 
    760     ConditionalLock _l(mStateLock,
    761             std::this_thread::get_id() != mMainThreadId);
    762     for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
    763         DisplayInfo info = DisplayInfo();
    764 
    765         float xdpi = hwConfig->getDpiX();
    766         float ydpi = hwConfig->getDpiY();
    767 
    768         if (type == DisplayDevice::DISPLAY_PRIMARY) {
    769             // The density of the device is provided by a build property
    770             float density = Density::getBuildDensity() / 160.0f;
    771             if (density == 0) {
    772                 // the build doesn't provide a density -- this is wrong!
    773                 // use xdpi instead
    774                 ALOGE("ro.sf.lcd_density must be defined as a build property");
    775                 density = xdpi / 160.0f;
    776             }
    777             if (Density::getEmuDensity()) {
    778                 // if "qemu.sf.lcd_density" is specified, it overrides everything
    779                 xdpi = ydpi = density = Density::getEmuDensity();
    780                 density /= 160.0f;
    781             }
    782             info.density = density;
    783 
    784             // TODO: this needs to go away (currently needed only by webkit)
    785             sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
    786             info.orientation = hw->getOrientation();
    787         } else {
    788             // TODO: where should this value come from?
    789             static const int TV_DENSITY = 213;
    790             info.density = TV_DENSITY / 160.0f;
    791             info.orientation = 0;
    792         }
    793 
    794         info.w = hwConfig->getWidth();
    795         info.h = hwConfig->getHeight();
    796         info.xdpi = xdpi;
    797         info.ydpi = ydpi;
    798         info.fps = 1e9 / hwConfig->getVsyncPeriod();
    799         info.appVsyncOffset = vsyncPhaseOffsetNs;
    800 
    801         // This is how far in advance a buffer must be queued for
    802         // presentation at a given time.  If you want a buffer to appear
    803         // on the screen at time N, you must submit the buffer before
    804         // (N - presentationDeadline).
    805         //
    806         // Normally it's one full refresh period (to give SF a chance to
    807         // latch the buffer), but this can be reduced by configuring a
    808         // DispSync offset.  Any additional delays introduced by the hardware
    809         // composer or panel must be accounted for here.
    810         //
    811         // We add an additional 1ms to allow for processing time and
    812         // differences between the ideal and actual refresh rate.
    813         info.presentationDeadline = hwConfig->getVsyncPeriod() -
    814                 sfVsyncPhaseOffsetNs + 1000000;
    815 
    816         // All non-virtual displays are currently considered secure.
    817         info.secure = true;
    818 
    819         configs->push_back(info);
    820     }
    821 
    822     return NO_ERROR;
    823 }
    824 
    825 status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
    826         DisplayStatInfo* stats) {
    827     if (stats == NULL) {
    828         return BAD_VALUE;
    829     }
    830 
    831     // FIXME for now we always return stats for the primary display
    832     memset(stats, 0, sizeof(*stats));
    833     stats->vsyncTime   = mPrimaryDispSync.computeNextRefresh(0);
    834     stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
    835     return NO_ERROR;
    836 }
    837 
    838 int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
    839     if (display == NULL) {
    840         ALOGE("%s : display is NULL", __func__);
    841         return BAD_VALUE;
    842     }
    843 
    844     sp<const DisplayDevice> device(getDisplayDevice(display));
    845     if (device != NULL) {
    846         return device->getActiveConfig();
    847     }
    848 
    849     return BAD_VALUE;
    850 }
    851 
    852 void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
    853     ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
    854           this);
    855     int32_t type = hw->getDisplayType();
    856     int currentMode = hw->getActiveConfig();
    857 
    858     if (mode == currentMode) {
    859         ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
    860         return;
    861     }
    862 
    863     if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
    864         ALOGW("Trying to set config for virtual display");
    865         return;
    866     }
    867 
    868     hw->setActiveConfig(mode);
    869     getHwComposer().setActiveConfig(type, mode);
    870 }
    871 
    872 status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
    873     class MessageSetActiveConfig: public MessageBase {
    874         SurfaceFlinger& mFlinger;
    875         sp<IBinder> mDisplay;
    876         int mMode;
    877     public:
    878         MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
    879                                int mode) :
    880             mFlinger(flinger), mDisplay(disp) { mMode = mode; }
    881         virtual bool handler() {
    882             Vector<DisplayInfo> configs;
    883             mFlinger.getDisplayConfigs(mDisplay, &configs);
    884             if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
    885                 ALOGE("Attempt to set active config = %d for display with %zu configs",
    886                         mMode, configs.size());
    887                 return true;
    888             }
    889             sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
    890             if (hw == NULL) {
    891                 ALOGE("Attempt to set active config = %d for null display %p",
    892                         mMode, mDisplay.get());
    893             } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
    894                 ALOGW("Attempt to set active config = %d for virtual display",
    895                         mMode);
    896             } else {
    897                 mFlinger.setActiveConfigInternal(hw, mMode);
    898             }
    899             return true;
    900         }
    901     };
    902     sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
    903     postMessageSync(msg);
    904     return NO_ERROR;
    905 }
    906 status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
    907         Vector<android_color_mode_t>* outColorModes) {
    908     if ((outColorModes == nullptr) || (display.get() == nullptr)) {
    909         return BAD_VALUE;
    910     }
    911 
    912     if (!display.get()) {
    913         return NAME_NOT_FOUND;
    914     }
    915 
    916     int32_t type = NAME_NOT_FOUND;
    917     for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
    918         if (display == mBuiltinDisplays[i]) {
    919             type = i;
    920             break;
    921         }
    922     }
    923 
    924     if (type < 0) {
    925         return type;
    926     }
    927 
    928     std::vector<android_color_mode_t> modes;
    929     {
    930         ConditionalLock _l(mStateLock,
    931                 std::this_thread::get_id() != mMainThreadId);
    932         modes = getHwComposer().getColorModes(type);
    933     }
    934     outColorModes->clear();
    935     std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
    936 
    937     return NO_ERROR;
    938 }
    939 
    940 android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
    941     sp<const DisplayDevice> device(getDisplayDevice(display));
    942     if (device != nullptr) {
    943         return device->getActiveColorMode();
    944     }
    945     return static_cast<android_color_mode_t>(BAD_VALUE);
    946 }
    947 
    948 void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
    949         android_color_mode_t mode) {
    950     int32_t type = hw->getDisplayType();
    951     android_color_mode_t currentMode = hw->getActiveColorMode();
    952 
    953     if (mode == currentMode) {
    954         return;
    955     }
    956 
    957     if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
    958         ALOGW("Trying to set config for virtual display");
    959         return;
    960     }
    961 
    962     ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
    963           hw->getDisplayType());
    964 
    965     hw->setActiveColorMode(mode);
    966     getHwComposer().setActiveColorMode(type, mode);
    967 }
    968 
    969 
    970 status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
    971         android_color_mode_t colorMode) {
    972     class MessageSetActiveColorMode: public MessageBase {
    973         SurfaceFlinger& mFlinger;
    974         sp<IBinder> mDisplay;
    975         android_color_mode_t mMode;
    976     public:
    977         MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
    978                                android_color_mode_t mode) :
    979             mFlinger(flinger), mDisplay(disp) { mMode = mode; }
    980         virtual bool handler() {
    981             Vector<android_color_mode_t> modes;
    982             mFlinger.getDisplayColorModes(mDisplay, &modes);
    983             bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
    984             if (mMode < 0 || !exists) {
    985                 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
    986                       decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
    987                 return true;
    988             }
    989             sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
    990             if (hw == nullptr) {
    991                 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
    992                       decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
    993             } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
    994                 ALOGW("Attempt to set active color mode %s %d for virtual display",
    995                       decodeColorMode(mMode).c_str(), mMode);
    996             } else {
    997                 mFlinger.setActiveColorModeInternal(hw, mMode);
    998             }
    999             return true;
   1000         }
   1001     };
   1002     sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
   1003     postMessageSync(msg);
   1004     return NO_ERROR;
   1005 }
   1006 
   1007 status_t SurfaceFlinger::clearAnimationFrameStats() {
   1008     Mutex::Autolock _l(mStateLock);
   1009     mAnimFrameTracker.clearStats();
   1010     return NO_ERROR;
   1011 }
   1012 
   1013 status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
   1014     Mutex::Autolock _l(mStateLock);
   1015     mAnimFrameTracker.getStats(outStats);
   1016     return NO_ERROR;
   1017 }
   1018 
   1019 status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
   1020         HdrCapabilities* outCapabilities) const {
   1021     Mutex::Autolock _l(mStateLock);
   1022 
   1023     sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
   1024     if (displayDevice == nullptr) {
   1025         ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
   1026         return BAD_VALUE;
   1027     }
   1028 
   1029     std::unique_ptr<HdrCapabilities> capabilities =
   1030             mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
   1031     if (capabilities) {
   1032         std::swap(*outCapabilities, *capabilities);
   1033     } else {
   1034         return BAD_VALUE;
   1035     }
   1036 
   1037     return NO_ERROR;
   1038 }
   1039 
   1040 status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
   1041     if (enable == mInjectVSyncs) {
   1042         return NO_ERROR;
   1043     }
   1044 
   1045     if (enable) {
   1046         mInjectVSyncs = enable;
   1047         ALOGV("VSync Injections enabled");
   1048         if (mVSyncInjector.get() == nullptr) {
   1049             mVSyncInjector = new InjectVSyncSource();
   1050             mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
   1051         }
   1052         mEventQueue.setEventThread(mInjectorEventThread);
   1053     } else {
   1054         mInjectVSyncs = enable;
   1055         ALOGV("VSync Injections disabled");
   1056         mEventQueue.setEventThread(mSFEventThread);
   1057         mVSyncInjector.clear();
   1058     }
   1059     return NO_ERROR;
   1060 }
   1061 
   1062 status_t SurfaceFlinger::injectVSync(nsecs_t when) {
   1063     if (!mInjectVSyncs) {
   1064         ALOGE("VSync Injections not enabled");
   1065         return BAD_VALUE;
   1066     }
   1067     if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
   1068         ALOGV("Injecting VSync inside SurfaceFlinger");
   1069         mVSyncInjector->onInjectSyncEvent(when);
   1070     }
   1071     return NO_ERROR;
   1072 }
   1073 
   1074 // ----------------------------------------------------------------------------
   1075 
   1076 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
   1077         ISurfaceComposer::VsyncSource vsyncSource) {
   1078     if (vsyncSource == eVsyncSourceSurfaceFlinger) {
   1079         return mSFEventThread->createEventConnection();
   1080     } else {
   1081         return mEventThread->createEventConnection();
   1082     }
   1083 }
   1084 
   1085 // ----------------------------------------------------------------------------
   1086 
   1087 void SurfaceFlinger::waitForEvent() {
   1088     mEventQueue.waitMessage();
   1089 }
   1090 
   1091 void SurfaceFlinger::signalTransaction() {
   1092     mEventQueue.invalidate();
   1093 }
   1094 
   1095 void SurfaceFlinger::signalLayerUpdate() {
   1096     mEventQueue.invalidate();
   1097 }
   1098 
   1099 void SurfaceFlinger::signalRefresh() {
   1100     mRefreshPending = true;
   1101     mEventQueue.refresh();
   1102 }
   1103 
   1104 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
   1105         nsecs_t reltime, uint32_t /* flags */) {
   1106     return mEventQueue.postMessage(msg, reltime);
   1107 }
   1108 
   1109 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
   1110         nsecs_t reltime, uint32_t /* flags */) {
   1111     status_t res = mEventQueue.postMessage(msg, reltime);
   1112     if (res == NO_ERROR) {
   1113         msg->wait();
   1114     }
   1115     return res;
   1116 }
   1117 
   1118 void SurfaceFlinger::run() {
   1119     do {
   1120         waitForEvent();
   1121     } while (true);
   1122 }
   1123 
   1124 void SurfaceFlinger::enableHardwareVsync() {
   1125     Mutex::Autolock _l(mHWVsyncLock);
   1126     if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
   1127         mPrimaryDispSync.beginResync();
   1128         //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
   1129         mEventControlThread->setVsyncEnabled(true);
   1130         mPrimaryHWVsyncEnabled = true;
   1131     }
   1132 }
   1133 
   1134 void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
   1135     Mutex::Autolock _l(mHWVsyncLock);
   1136 
   1137     if (makeAvailable) {
   1138         mHWVsyncAvailable = true;
   1139     } else if (!mHWVsyncAvailable) {
   1140         // Hardware vsync is not currently available, so abort the resync
   1141         // attempt for now
   1142         return;
   1143     }
   1144 
   1145     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
   1146     const nsecs_t period = activeConfig->getVsyncPeriod();
   1147 
   1148     mPrimaryDispSync.reset();
   1149     mPrimaryDispSync.setPeriod(period);
   1150 
   1151     if (!mPrimaryHWVsyncEnabled) {
   1152         mPrimaryDispSync.beginResync();
   1153         //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
   1154         mEventControlThread->setVsyncEnabled(true);
   1155         mPrimaryHWVsyncEnabled = true;
   1156     }
   1157 }
   1158 
   1159 void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
   1160     Mutex::Autolock _l(mHWVsyncLock);
   1161     if (mPrimaryHWVsyncEnabled) {
   1162         //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
   1163         mEventControlThread->setVsyncEnabled(false);
   1164         mPrimaryDispSync.endResync();
   1165         mPrimaryHWVsyncEnabled = false;
   1166     }
   1167     if (makeUnavailable) {
   1168         mHWVsyncAvailable = false;
   1169     }
   1170 }
   1171 
   1172 void SurfaceFlinger::resyncWithRateLimit() {
   1173     static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
   1174 
   1175     // No explicit locking is needed here since EventThread holds a lock while calling this method
   1176     static nsecs_t sLastResyncAttempted = 0;
   1177     const nsecs_t now = systemTime();
   1178     if (now - sLastResyncAttempted > kIgnoreDelay) {
   1179         resyncToHardwareVsync(false);
   1180     }
   1181     sLastResyncAttempted = now;
   1182 }
   1183 
   1184 void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
   1185         hwc2_display_t displayId, int64_t timestamp) {
   1186     Mutex::Autolock lock(mStateLock);
   1187     // Ignore any vsyncs from a previous hardware composer.
   1188     if (sequenceId != mComposerSequenceId) {
   1189         return;
   1190     }
   1191 
   1192     int32_t type;
   1193     if (!mHwc->onVsync(displayId, timestamp, &type)) {
   1194         return;
   1195     }
   1196 
   1197     bool needsHwVsync = false;
   1198 
   1199     { // Scope for the lock
   1200         Mutex::Autolock _l(mHWVsyncLock);
   1201         if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
   1202             needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
   1203         }
   1204     }
   1205 
   1206     if (needsHwVsync) {
   1207         enableHardwareVsync();
   1208     } else {
   1209         disableHardwareVsync(false);
   1210     }
   1211 }
   1212 
   1213 void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
   1214     std::lock_guard<std::mutex> lock(mCompositorTimingLock);
   1215     *compositorTiming = mCompositorTiming;
   1216 }
   1217 
   1218 void SurfaceFlinger::createDefaultDisplayDevice() {
   1219     const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
   1220     wp<IBinder> token = mBuiltinDisplays[type];
   1221 
   1222     // All non-virtual displays are currently considered secure.
   1223     const bool isSecure = true;
   1224 
   1225     sp<IGraphicBufferProducer> producer;
   1226     sp<IGraphicBufferConsumer> consumer;
   1227     BufferQueue::createBufferQueue(&producer, &consumer);
   1228 
   1229     sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
   1230 
   1231     bool hasWideColorModes = false;
   1232     std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
   1233     for (android_color_mode_t colorMode : modes) {
   1234         switch (colorMode) {
   1235             case HAL_COLOR_MODE_DISPLAY_P3:
   1236             case HAL_COLOR_MODE_ADOBE_RGB:
   1237             case HAL_COLOR_MODE_DCI_P3:
   1238                 hasWideColorModes = true;
   1239                 break;
   1240             default:
   1241                 break;
   1242         }
   1243     }
   1244     bool useWideColorMode = hasWideColorModes && hasWideColorDisplay && !mForceNativeColorMode;
   1245     sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
   1246                                              token, fbs, producer, mRenderEngine->getEGLConfig(),
   1247                                              useWideColorMode);
   1248     mDisplays.add(token, hw);
   1249     android_color_mode defaultColorMode = HAL_COLOR_MODE_NATIVE;
   1250     if (useWideColorMode) {
   1251         defaultColorMode = HAL_COLOR_MODE_SRGB;
   1252     }
   1253     setActiveColorModeInternal(hw, defaultColorMode);
   1254     hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
   1255 
   1256     // Add the primary display token to mDrawingState so we don't try to
   1257     // recreate the DisplayDevice for the primary display.
   1258     mDrawingState.displays.add(token, DisplayDeviceState(type, true));
   1259 
   1260     // make the GLContext current so that we can create textures when creating
   1261     // Layers (which may happens before we render something)
   1262     hw->makeCurrent(mEGLDisplay, mEGLContext);
   1263 }
   1264 
   1265 void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
   1266         hwc2_display_t display, HWC2::Connection connection,
   1267         bool primaryDisplay) {
   1268     ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
   1269           sequenceId, display,
   1270           connection == HWC2::Connection::Connected ?
   1271                   "connected" : "disconnected",
   1272           primaryDisplay ? "primary" : "external");
   1273 
   1274     // Only lock if we're not on the main thread. This function is normally
   1275     // called on a hwbinder thread, but for the primary display it's called on
   1276     // the main thread with the state lock already held, so don't attempt to
   1277     // acquire it here.
   1278     ConditionalLock lock(mStateLock,
   1279             std::this_thread::get_id() != mMainThreadId);
   1280 
   1281     if (primaryDisplay) {
   1282         mHwc->onHotplug(display, connection);
   1283         if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
   1284             createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
   1285         }
   1286         createDefaultDisplayDevice();
   1287     } else {
   1288         if (sequenceId != mComposerSequenceId) {
   1289             return;
   1290         }
   1291         if (mHwc->isUsingVrComposer()) {
   1292             ALOGE("External displays are not supported by the vr hardware composer.");
   1293             return;
   1294         }
   1295         mHwc->onHotplug(display, connection);
   1296         auto type = DisplayDevice::DISPLAY_EXTERNAL;
   1297         if (connection == HWC2::Connection::Connected) {
   1298             createBuiltinDisplayLocked(type);
   1299         } else {
   1300             mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
   1301             mBuiltinDisplays[type].clear();
   1302         }
   1303         setTransactionFlags(eDisplayTransactionNeeded);
   1304 
   1305         // Defer EventThread notification until SF has updated mDisplays.
   1306     }
   1307 }
   1308 
   1309 void SurfaceFlinger::onRefreshReceived(int sequenceId,
   1310                                        hwc2_display_t /*display*/) {
   1311     Mutex::Autolock lock(mStateLock);
   1312     if (sequenceId != mComposerSequenceId) {
   1313         return;
   1314     }
   1315     repaintEverythingLocked();
   1316 }
   1317 
   1318 void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
   1319     ATRACE_CALL();
   1320     Mutex::Autolock lock(mStateLock);
   1321     getHwComposer().setVsyncEnabled(disp,
   1322             enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
   1323 }
   1324 
   1325 // Note: it is assumed the caller holds |mStateLock| when this is called
   1326 void SurfaceFlinger::resetDisplayState() {
   1327     disableHardwareVsync(true);
   1328     // Clear the drawing state so that the logic inside of
   1329     // handleTransactionLocked will fire. It will determine the delta between
   1330     // mCurrentState and mDrawingState and re-apply all changes when we make the
   1331     // transition.
   1332     mDrawingState.displays.clear();
   1333     eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
   1334     mDisplays.clear();
   1335 }
   1336 
   1337 void SurfaceFlinger::updateVrFlinger() {
   1338     if (!mVrFlinger)
   1339         return;
   1340     bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
   1341     if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
   1342         return;
   1343     }
   1344 
   1345     if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
   1346         ALOGE("Vr flinger is only supported for remote hardware composer"
   1347               " service connections. Ignoring request to transition to vr"
   1348               " flinger.");
   1349         mVrFlingerRequestsDisplay = false;
   1350         return;
   1351     }
   1352 
   1353     Mutex::Autolock _l(mStateLock);
   1354 
   1355     int currentDisplayPowerMode = getDisplayDeviceLocked(
   1356             mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
   1357 
   1358     if (!vrFlingerRequestsDisplay) {
   1359         mVrFlinger->SeizeDisplayOwnership();
   1360     }
   1361 
   1362     resetDisplayState();
   1363     mHwc.reset();  // Delete the current instance before creating the new one
   1364     mHwc.reset(new HWComposer(vrFlingerRequestsDisplay));
   1365     mHwc->registerCallback(this, ++mComposerSequenceId);
   1366 
   1367     LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
   1368             "Switched to non-remote hardware composer");
   1369 
   1370     if (vrFlingerRequestsDisplay) {
   1371         mVrFlinger->GrantDisplayOwnership();
   1372     } else {
   1373         enableHardwareVsync();
   1374     }
   1375 
   1376     mVisibleRegionsDirty = true;
   1377     invalidateHwcGeometry();
   1378 
   1379     // Re-enable default display.
   1380     sp<DisplayDevice> hw(getDisplayDeviceLocked(
   1381             mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
   1382     setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
   1383 
   1384     // Reset the timing values to account for the period of the swapped in HWC
   1385     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
   1386     const nsecs_t period = activeConfig->getVsyncPeriod();
   1387     mAnimFrameTracker.setDisplayRefreshPeriod(period);
   1388 
   1389     // Use phase of 0 since phase is not known.
   1390     // Use latency of 0, which will snap to the ideal latency.
   1391     setCompositorTimingSnapped(0, period, 0);
   1392 
   1393     android_atomic_or(1, &mRepaintEverything);
   1394     setTransactionFlags(eDisplayTransactionNeeded);
   1395 }
   1396 
   1397 void SurfaceFlinger::onMessageReceived(int32_t what) {
   1398     ATRACE_CALL();
   1399     switch (what) {
   1400         case MessageQueue::INVALIDATE: {
   1401             bool frameMissed = !mHadClientComposition &&
   1402                     mPreviousPresentFence != Fence::NO_FENCE &&
   1403                     (mPreviousPresentFence->getSignalTime() ==
   1404                             Fence::SIGNAL_TIME_PENDING);
   1405             ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
   1406             if (mPropagateBackpressure && frameMissed) {
   1407                 signalLayerUpdate();
   1408                 break;
   1409             }
   1410 
   1411             // Now that we're going to make it to the handleMessageTransaction()
   1412             // call below it's safe to call updateVrFlinger(), which will
   1413             // potentially trigger a display handoff.
   1414             updateVrFlinger();
   1415 
   1416             bool refreshNeeded = handleMessageTransaction();
   1417             refreshNeeded |= handleMessageInvalidate();
   1418             refreshNeeded |= mRepaintEverything;
   1419             if (refreshNeeded) {
   1420                 // Signal a refresh if a transaction modified the window state,
   1421                 // a new buffer was latched, or if HWC has requested a full
   1422                 // repaint
   1423                 signalRefresh();
   1424             }
   1425             break;
   1426         }
   1427         case MessageQueue::REFRESH: {
   1428             handleMessageRefresh();
   1429             break;
   1430         }
   1431     }
   1432 }
   1433 
   1434 bool SurfaceFlinger::handleMessageTransaction() {
   1435     uint32_t transactionFlags = peekTransactionFlags();
   1436     if (transactionFlags) {
   1437         handleTransaction(transactionFlags);
   1438         return true;
   1439     }
   1440     return false;
   1441 }
   1442 
   1443 bool SurfaceFlinger::handleMessageInvalidate() {
   1444     ATRACE_CALL();
   1445     return handlePageFlip();
   1446 }
   1447 
   1448 void SurfaceFlinger::handleMessageRefresh() {
   1449     ATRACE_CALL();
   1450 
   1451     mRefreshPending = false;
   1452 
   1453     nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
   1454 
   1455     preComposition(refreshStartTime);
   1456     rebuildLayerStacks();
   1457     setUpHWComposer();
   1458     doDebugFlashRegions();
   1459     doComposition();
   1460     postComposition(refreshStartTime);
   1461 
   1462     mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
   1463 
   1464     mHadClientComposition = false;
   1465     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
   1466         const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
   1467         mHadClientComposition = mHadClientComposition ||
   1468                 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
   1469     }
   1470 
   1471     mLayersWithQueuedFrames.clear();
   1472 }
   1473 
   1474 void SurfaceFlinger::doDebugFlashRegions()
   1475 {
   1476     // is debugging enabled
   1477     if (CC_LIKELY(!mDebugRegion))
   1478         return;
   1479 
   1480     const bool repaintEverything = mRepaintEverything;
   1481     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
   1482         const sp<DisplayDevice>& hw(mDisplays[dpy]);
   1483         if (hw->isDisplayOn()) {
   1484             // transform the dirty region into this screen's coordinate space
   1485             const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
   1486             if (!dirtyRegion.isEmpty()) {
   1487                 // redraw the whole screen
   1488                 doComposeSurfaces(hw, Region(hw->bounds()));
   1489 
   1490                 // and draw the dirty region
   1491                 const int32_t height = hw->getHeight();
   1492                 RenderEngine& engine(getRenderEngine());
   1493                 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
   1494 
   1495                 hw->swapBuffers(getHwComposer());
   1496             }
   1497         }
   1498     }
   1499 
   1500     postFramebuffer();
   1501 
   1502     if (mDebugRegion > 1) {
   1503         usleep(mDebugRegion * 1000);
   1504     }
   1505 
   1506     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
   1507         auto& displayDevice = mDisplays[displayId];
   1508         if (!displayDevice->isDisplayOn()) {
   1509             continue;
   1510         }
   1511 
   1512         status_t result = displayDevice->prepareFrame(*mHwc);
   1513         ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
   1514                 " %d (%s)", displayId, result, strerror(-result));
   1515     }
   1516 }
   1517 
   1518 void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
   1519 {
   1520     ATRACE_CALL();
   1521     ALOGV("preComposition");
   1522 
   1523     bool needExtraInvalidate = false;
   1524     mDrawingState.traverseInZOrder([&](Layer* layer) {
   1525         if (layer->onPreComposition(refreshStartTime)) {
   1526             needExtraInvalidate = true;
   1527         }
   1528     });
   1529 
   1530     if (needExtraInvalidate) {
   1531         signalLayerUpdate();
   1532     }
   1533 }
   1534 
   1535 void SurfaceFlinger::updateCompositorTiming(
   1536         nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
   1537         std::shared_ptr<FenceTime>& presentFenceTime) {
   1538     // Update queue of past composite+present times and determine the
   1539     // most recently known composite to present latency.
   1540     mCompositePresentTimes.push({compositeTime, presentFenceTime});
   1541     nsecs_t compositeToPresentLatency = -1;
   1542     while (!mCompositePresentTimes.empty()) {
   1543         CompositePresentTime& cpt = mCompositePresentTimes.front();
   1544         // Cached values should have been updated before calling this method,
   1545         // which helps avoid duplicate syscalls.
   1546         nsecs_t displayTime = cpt.display->getCachedSignalTime();
   1547         if (displayTime == Fence::SIGNAL_TIME_PENDING) {
   1548             break;
   1549         }
   1550         compositeToPresentLatency = displayTime - cpt.composite;
   1551         mCompositePresentTimes.pop();
   1552     }
   1553 
   1554     // Don't let mCompositePresentTimes grow unbounded, just in case.
   1555     while (mCompositePresentTimes.size() > 16) {
   1556         mCompositePresentTimes.pop();
   1557     }
   1558 
   1559     setCompositorTimingSnapped(
   1560             vsyncPhase, vsyncInterval, compositeToPresentLatency);
   1561 }
   1562 
   1563 void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
   1564         nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
   1565     // Integer division and modulo round toward 0 not -inf, so we need to
   1566     // treat negative and positive offsets differently.
   1567     nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
   1568             (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
   1569             ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
   1570 
   1571     // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
   1572     if (idealLatency <= 0) {
   1573         idealLatency = vsyncInterval;
   1574     }
   1575 
   1576     // Snap the latency to a value that removes scheduling jitter from the
   1577     // composition and present times, which often have >1ms of jitter.
   1578     // Reducing jitter is important if an app attempts to extrapolate
   1579     // something (such as user input) to an accurate diasplay time.
   1580     // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
   1581     // with (presentLatency % interval).
   1582     nsecs_t bias = vsyncInterval / 2;
   1583     int64_t extraVsyncs =
   1584             (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
   1585     nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
   1586             idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
   1587 
   1588     std::lock_guard<std::mutex> lock(mCompositorTimingLock);
   1589     mCompositorTiming.deadline = vsyncPhase - idealLatency;
   1590     mCompositorTiming.interval = vsyncInterval;
   1591     mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
   1592 }
   1593 
   1594 void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
   1595 {
   1596     ATRACE_CALL();
   1597     ALOGV("postComposition");
   1598 
   1599     // Release any buffers which were replaced this frame
   1600     nsecs_t dequeueReadyTime = systemTime();
   1601     for (auto& layer : mLayersWithQueuedFrames) {
   1602         layer->releasePendingBuffer(dequeueReadyTime);
   1603     }
   1604 
   1605     // |mStateLock| not needed as we are on the main thread
   1606     const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
   1607 
   1608     mGlCompositionDoneTimeline.updateSignalTimes();
   1609     std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
   1610     if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
   1611         glCompositionDoneFenceTime =
   1612                 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
   1613         mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
   1614     } else {
   1615         glCompositionDoneFenceTime = FenceTime::NO_FENCE;
   1616     }
   1617 
   1618     mDisplayTimeline.updateSignalTimes();
   1619     sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
   1620     auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
   1621     mDisplayTimeline.push(presentFenceTime);
   1622 
   1623     nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
   1624     nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
   1625 
   1626     // We use the refreshStartTime which might be sampled a little later than
   1627     // when we started doing work for this frame, but that should be okay
   1628     // since updateCompositorTiming has snapping logic.
   1629     updateCompositorTiming(
   1630         vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
   1631     CompositorTiming compositorTiming;
   1632     {
   1633         std::lock_guard<std::mutex> lock(mCompositorTimingLock);
   1634         compositorTiming = mCompositorTiming;
   1635     }
   1636 
   1637     mDrawingState.traverseInZOrder([&](Layer* layer) {
   1638         bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
   1639                 presentFenceTime, compositorTiming);
   1640         if (frameLatched) {
   1641             recordBufferingStats(layer->getName().string(),
   1642                     layer->getOccupancyHistory(false));
   1643         }
   1644     });
   1645 
   1646     if (presentFenceTime->isValid()) {
   1647         if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
   1648             enableHardwareVsync();
   1649         } else {
   1650             disableHardwareVsync(false);
   1651         }
   1652     }
   1653 
   1654     if (!hasSyncFramework) {
   1655         if (hw->isDisplayOn()) {
   1656             enableHardwareVsync();
   1657         }
   1658     }
   1659 
   1660     if (mAnimCompositionPending) {
   1661         mAnimCompositionPending = false;
   1662 
   1663         if (presentFenceTime->isValid()) {
   1664             mAnimFrameTracker.setActualPresentFence(
   1665                     std::move(presentFenceTime));
   1666         } else {
   1667             // The HWC doesn't support present fences, so use the refresh
   1668             // timestamp instead.
   1669             nsecs_t presentTime =
   1670                     mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
   1671             mAnimFrameTracker.setActualPresentTime(presentTime);
   1672         }
   1673         mAnimFrameTracker.advanceFrame();
   1674     }
   1675 
   1676     if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
   1677         return;
   1678     }
   1679 
   1680     nsecs_t currentTime = systemTime();
   1681     if (mHasPoweredOff) {
   1682         mHasPoweredOff = false;
   1683     } else {
   1684         nsecs_t elapsedTime = currentTime - mLastSwapTime;
   1685         size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
   1686         if (numPeriods < NUM_BUCKETS - 1) {
   1687             mFrameBuckets[numPeriods] += elapsedTime;
   1688         } else {
   1689             mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
   1690         }
   1691         mTotalTime += elapsedTime;
   1692     }
   1693     mLastSwapTime = currentTime;
   1694 }
   1695 
   1696 void SurfaceFlinger::rebuildLayerStacks() {
   1697     ATRACE_CALL();
   1698     ALOGV("rebuildLayerStacks");
   1699 
   1700     // rebuild the visible layer list per screen
   1701     if (CC_UNLIKELY(mVisibleRegionsDirty)) {
   1702         ATRACE_CALL();
   1703         mVisibleRegionsDirty = false;
   1704         invalidateHwcGeometry();
   1705 
   1706         for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
   1707             Region opaqueRegion;
   1708             Region dirtyRegion;
   1709             Vector<sp<Layer>> layersSortedByZ;
   1710             const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
   1711             const Transform& tr(displayDevice->getTransform());
   1712             const Rect bounds(displayDevice->getBounds());
   1713             if (displayDevice->isDisplayOn()) {
   1714                 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
   1715 
   1716                 mDrawingState.traverseInZOrder([&](Layer* layer) {
   1717                     if (layer->belongsToDisplay(displayDevice->getLayerStack(),
   1718                                 displayDevice->isPrimary())) {
   1719                         Region drawRegion(tr.transform(
   1720                                 layer->visibleNonTransparentRegion));
   1721                         drawRegion.andSelf(bounds);
   1722                         if (!drawRegion.isEmpty()) {
   1723                             layersSortedByZ.add(layer);
   1724                         } else {
   1725                             // Clear out the HWC layer if this layer was
   1726                             // previously visible, but no longer is
   1727                             layer->destroyHwcLayer(
   1728                                     displayDevice->getHwcDisplayId());
   1729                         }
   1730                     } else {
   1731                         // WM changes displayDevice->layerStack upon sleep/awake.
   1732                         // Here we make sure we delete the HWC layers even if
   1733                         // WM changed their layer stack.
   1734                         layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
   1735                     }
   1736                 });
   1737             }
   1738             displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
   1739             displayDevice->undefinedRegion.set(bounds);
   1740             displayDevice->undefinedRegion.subtractSelf(
   1741                     tr.transform(opaqueRegion));
   1742             displayDevice->dirtyRegion.orSelf(dirtyRegion);
   1743         }
   1744     }
   1745 }
   1746 
   1747 mat4 SurfaceFlinger::computeSaturationMatrix() const {
   1748     if (mSaturation == 1.0f) {
   1749         return mat4();
   1750     }
   1751 
   1752     // Rec.709 luma coefficients
   1753     float3 luminance{0.213f, 0.715f, 0.072f};
   1754     luminance *= 1.0f - mSaturation;
   1755     return mat4(
   1756         vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
   1757         vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
   1758         vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
   1759         vec4{0.0f, 0.0f, 0.0f, 1.0f}
   1760     );
   1761 }
   1762 
   1763 // pickColorMode translates a given dataspace into the best available color mode.
   1764 // Currently only support sRGB and Display-P3.
   1765 android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
   1766     if (mForceNativeColorMode) {
   1767         return HAL_COLOR_MODE_NATIVE;
   1768     }
   1769 
   1770     switch (dataSpace) {
   1771         // treat Unknown as regular SRGB buffer, since that's what the rest of the
   1772         // system expects.
   1773         case HAL_DATASPACE_UNKNOWN:
   1774         case HAL_DATASPACE_SRGB:
   1775         case HAL_DATASPACE_V0_SRGB:
   1776             return HAL_COLOR_MODE_SRGB;
   1777             break;
   1778 
   1779         case HAL_DATASPACE_DISPLAY_P3:
   1780             return HAL_COLOR_MODE_DISPLAY_P3;
   1781             break;
   1782 
   1783         default:
   1784             // TODO (courtneygo): Do we want to assert an error here?
   1785             ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
   1786                   dataSpace);
   1787             return HAL_COLOR_MODE_SRGB;
   1788             break;
   1789     }
   1790 }
   1791 
   1792 android_dataspace SurfaceFlinger::bestTargetDataSpace(
   1793         android_dataspace a, android_dataspace b) const {
   1794     // Only support sRGB and Display-P3 right now.
   1795     if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
   1796         return HAL_DATASPACE_DISPLAY_P3;
   1797     }
   1798     if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
   1799         return HAL_DATASPACE_DISPLAY_P3;
   1800     }
   1801     if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
   1802         return HAL_DATASPACE_DISPLAY_P3;
   1803     }
   1804 
   1805     return HAL_DATASPACE_V0_SRGB;
   1806 }
   1807 
   1808 void SurfaceFlinger::setUpHWComposer() {
   1809     ATRACE_CALL();
   1810     ALOGV("setUpHWComposer");
   1811 
   1812     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
   1813         bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
   1814         bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
   1815         bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
   1816 
   1817         // If nothing has changed (!dirty), don't recompose.
   1818         // If something changed, but we don't currently have any visible layers,
   1819         //   and didn't when we last did a composition, then skip it this time.
   1820         // The second rule does two things:
   1821         // - When all layers are removed from a display, we'll emit one black
   1822         //   frame, then nothing more until we get new layers.
   1823         // - When a display is created with a private layer stack, we won't
   1824         //   emit any black frames until a layer is added to the layer stack.
   1825         bool mustRecompose = dirty && !(empty && wasEmpty);
   1826 
   1827         ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
   1828                 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
   1829                 mustRecompose ? "doing" : "skipping",
   1830                 dirty ? "+" : "-",
   1831                 empty ? "+" : "-",
   1832                 wasEmpty ? "+" : "-");
   1833 
   1834         mDisplays[dpy]->beginFrame(mustRecompose);
   1835 
   1836         if (mustRecompose) {
   1837             mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
   1838         }
   1839     }
   1840 
   1841     // build the h/w work list
   1842     if (CC_UNLIKELY(mGeometryInvalid)) {
   1843         mGeometryInvalid = false;
   1844         for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
   1845             sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
   1846             const auto hwcId = displayDevice->getHwcDisplayId();
   1847             if (hwcId >= 0) {
   1848                 const Vector<sp<Layer>>& currentLayers(
   1849                         displayDevice->getVisibleLayersSortedByZ());
   1850                 for (size_t i = 0; i < currentLayers.size(); i++) {
   1851                     const auto& layer = currentLayers[i];
   1852                     if (!layer->hasHwcLayer(hwcId)) {
   1853                         if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
   1854                             layer->forceClientComposition(hwcId);
   1855                             continue;
   1856                         }
   1857                     }
   1858 
   1859                     layer->setGeometry(displayDevice, i);
   1860                     if (mDebugDisableHWC || mDebugRegion) {
   1861                         layer->forceClientComposition(hwcId);
   1862                     }
   1863                 }
   1864             }
   1865         }
   1866     }
   1867 
   1868 
   1869     mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
   1870 
   1871     // Set the per-frame data
   1872     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
   1873         auto& displayDevice = mDisplays[displayId];
   1874         const auto hwcId = displayDevice->getHwcDisplayId();
   1875 
   1876         if (hwcId < 0) {
   1877             continue;
   1878         }
   1879         if (colorMatrix != mPreviousColorMatrix) {
   1880             status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
   1881             ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
   1882                     "display %zd: %d", displayId, result);
   1883         }
   1884         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
   1885             layer->setPerFrameData(displayDevice);
   1886         }
   1887 
   1888         if (hasWideColorDisplay) {
   1889             android_color_mode newColorMode;
   1890             android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
   1891 
   1892             for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
   1893                 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
   1894                 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
   1895                       layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
   1896                       layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
   1897             }
   1898             newColorMode = pickColorMode(newDataSpace);
   1899 
   1900             setActiveColorModeInternal(displayDevice, newColorMode);
   1901         }
   1902     }
   1903 
   1904     mPreviousColorMatrix = colorMatrix;
   1905 
   1906     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
   1907         auto& displayDevice = mDisplays[displayId];
   1908         if (!displayDevice->isDisplayOn()) {
   1909             continue;
   1910         }
   1911 
   1912         status_t result = displayDevice->prepareFrame(*mHwc);
   1913         ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
   1914                 " %d (%s)", displayId, result, strerror(-result));
   1915     }
   1916 }
   1917 
   1918 void SurfaceFlinger::doComposition() {
   1919     ATRACE_CALL();
   1920     ALOGV("doComposition");
   1921 
   1922     const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
   1923     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
   1924         const sp<DisplayDevice>& hw(mDisplays[dpy]);
   1925         if (hw->isDisplayOn()) {
   1926             // transform the dirty region into this screen's coordinate space
   1927             const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
   1928 
   1929             // repaint the framebuffer (if needed)
   1930             doDisplayComposition(hw, dirtyRegion);
   1931 
   1932             hw->dirtyRegion.clear();
   1933             hw->flip(hw->swapRegion);
   1934             hw->swapRegion.clear();
   1935         }
   1936     }
   1937     postFramebuffer();
   1938 }
   1939 
   1940 void SurfaceFlinger::postFramebuffer()
   1941 {
   1942     ATRACE_CALL();
   1943     ALOGV("postFramebuffer");
   1944 
   1945     const nsecs_t now = systemTime();
   1946     mDebugInSwapBuffers = now;
   1947 
   1948     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
   1949         auto& displayDevice = mDisplays[displayId];
   1950         if (!displayDevice->isDisplayOn()) {
   1951             continue;
   1952         }
   1953         const auto hwcId = displayDevice->getHwcDisplayId();
   1954         if (hwcId >= 0) {
   1955             mHwc->presentAndGetReleaseFences(hwcId);
   1956         }
   1957         displayDevice->onSwapBuffersCompleted();
   1958         displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
   1959         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
   1960             sp<Fence> releaseFence = Fence::NO_FENCE;
   1961             if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
   1962                 releaseFence = displayDevice->getClientTargetAcquireFence();
   1963             } else {
   1964                 auto hwcLayer = layer->getHwcLayer(hwcId);
   1965                 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
   1966             }
   1967             layer->onLayerDisplayed(releaseFence);
   1968         }
   1969         if (hwcId >= 0) {
   1970             mHwc->clearReleaseFences(hwcId);
   1971         }
   1972     }
   1973 
   1974     mLastSwapBufferTime = systemTime() - now;
   1975     mDebugInSwapBuffers = 0;
   1976 
   1977     // |mStateLock| not needed as we are on the main thread
   1978     uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
   1979     if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
   1980         logFrameStats();
   1981     }
   1982 }
   1983 
   1984 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
   1985 {
   1986     ATRACE_CALL();
   1987 
   1988     // here we keep a copy of the drawing state (that is the state that's
   1989     // going to be overwritten by handleTransactionLocked()) outside of
   1990     // mStateLock so that the side-effects of the State assignment
   1991     // don't happen with mStateLock held (which can cause deadlocks).
   1992     State drawingState(mDrawingState);
   1993 
   1994     Mutex::Autolock _l(mStateLock);
   1995     const nsecs_t now = systemTime();
   1996     mDebugInTransaction = now;
   1997 
   1998     // Here we're guaranteed that some transaction flags are set
   1999     // so we can call handleTransactionLocked() unconditionally.
   2000     // We call getTransactionFlags(), which will also clear the flags,
   2001     // with mStateLock held to guarantee that mCurrentState won't change
   2002     // until the transaction is committed.
   2003 
   2004     transactionFlags = getTransactionFlags(eTransactionMask);
   2005     handleTransactionLocked(transactionFlags);
   2006 
   2007     mLastTransactionTime = systemTime() - now;
   2008     mDebugInTransaction = 0;
   2009     invalidateHwcGeometry();
   2010     // here the transaction has been committed
   2011 }
   2012 
   2013 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
   2014 {
   2015     // Notify all layers of available frames
   2016     mCurrentState.traverseInZOrder([](Layer* layer) {
   2017         layer->notifyAvailableFrames();
   2018     });
   2019 
   2020     /*
   2021      * Traversal of the children
   2022      * (perform the transaction for each of them if needed)
   2023      */
   2024 
   2025     if (transactionFlags & eTraversalNeeded) {
   2026         mCurrentState.traverseInZOrder([&](Layer* layer) {
   2027             uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
   2028             if (!trFlags) return;
   2029 
   2030             const uint32_t flags = layer->doTransaction(0);
   2031             if (flags & Layer::eVisibleRegion)
   2032                 mVisibleRegionsDirty = true;
   2033         });
   2034     }
   2035 
   2036     /*
   2037      * Perform display own transactions if needed
   2038      */
   2039 
   2040     if (transactionFlags & eDisplayTransactionNeeded) {
   2041         // here we take advantage of Vector's copy-on-write semantics to
   2042         // improve performance by skipping the transaction entirely when
   2043         // know that the lists are identical
   2044         const KeyedVector<  wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
   2045         const KeyedVector<  wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
   2046         if (!curr.isIdenticalTo(draw)) {
   2047             mVisibleRegionsDirty = true;
   2048             const size_t cc = curr.size();
   2049                   size_t dc = draw.size();
   2050 
   2051             // find the displays that were removed
   2052             // (ie: in drawing state but not in current state)
   2053             // also handle displays that changed
   2054             // (ie: displays that are in both lists)
   2055             for (size_t i=0 ; i<dc ; i++) {
   2056                 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
   2057                 if (j < 0) {
   2058                     // in drawing state but not in current state
   2059                     if (!draw[i].isMainDisplay()) {
   2060                         // Call makeCurrent() on the primary display so we can
   2061                         // be sure that nothing associated with this display
   2062                         // is current.
   2063                         const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDeviceLocked());
   2064                         defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
   2065                         sp<DisplayDevice> hw(getDisplayDeviceLocked(draw.keyAt(i)));
   2066                         if (hw != NULL)
   2067                             hw->disconnect(getHwComposer());
   2068                         if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
   2069                             mEventThread->onHotplugReceived(draw[i].type, false);
   2070                         mDisplays.removeItem(draw.keyAt(i));
   2071                     } else {
   2072                         ALOGW("trying to remove the main display");
   2073                     }
   2074                 } else {
   2075                     // this display is in both lists. see if something changed.
   2076                     const DisplayDeviceState& state(curr[j]);
   2077                     const wp<IBinder>& display(curr.keyAt(j));
   2078                     const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
   2079                     const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
   2080                     if (state_binder != draw_binder) {
   2081                         // changing the surface is like destroying and
   2082                         // recreating the DisplayDevice, so we just remove it
   2083                         // from the drawing state, so that it get re-added
   2084                         // below.
   2085                         sp<DisplayDevice> hw(getDisplayDeviceLocked(display));
   2086                         if (hw != NULL)
   2087                             hw->disconnect(getHwComposer());
   2088                         mDisplays.removeItem(display);
   2089                         mDrawingState.displays.removeItemsAt(i);
   2090                         dc--; i--;
   2091                         // at this point we must loop to the next item
   2092                         continue;
   2093                     }
   2094 
   2095                     const sp<DisplayDevice> disp(getDisplayDeviceLocked(display));
   2096                     if (disp != NULL) {
   2097                         if (state.layerStack != draw[i].layerStack) {
   2098                             disp->setLayerStack(state.layerStack);
   2099                         }
   2100                         if ((state.orientation != draw[i].orientation)
   2101                                 || (state.viewport != draw[i].viewport)
   2102                                 || (state.frame != draw[i].frame))
   2103                         {
   2104                             disp->setProjection(state.orientation,
   2105                                     state.viewport, state.frame);
   2106                         }
   2107                         if (state.width != draw[i].width || state.height != draw[i].height) {
   2108                             disp->setDisplaySize(state.width, state.height);
   2109                         }
   2110                     }
   2111                 }
   2112             }
   2113 
   2114             // find displays that were added
   2115             // (ie: in current state but not in drawing state)
   2116             for (size_t i=0 ; i<cc ; i++) {
   2117                 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
   2118                     const DisplayDeviceState& state(curr[i]);
   2119 
   2120                     sp<DisplaySurface> dispSurface;
   2121                     sp<IGraphicBufferProducer> producer;
   2122                     sp<IGraphicBufferProducer> bqProducer;
   2123                     sp<IGraphicBufferConsumer> bqConsumer;
   2124                     BufferQueue::createBufferQueue(&bqProducer, &bqConsumer);
   2125 
   2126                     int32_t hwcId = -1;
   2127                     if (state.isVirtualDisplay()) {
   2128                         // Virtual displays without a surface are dormant:
   2129                         // they have external state (layer stack, projection,
   2130                         // etc.) but no internal state (i.e. a DisplayDevice).
   2131                         if (state.surface != NULL) {
   2132 
   2133                             // Allow VR composer to use virtual displays.
   2134                             if (mUseHwcVirtualDisplays || mHwc->isUsingVrComposer()) {
   2135                                 int width = 0;
   2136                                 int status = state.surface->query(
   2137                                         NATIVE_WINDOW_WIDTH, &width);
   2138                                 ALOGE_IF(status != NO_ERROR,
   2139                                         "Unable to query width (%d)", status);
   2140                                 int height = 0;
   2141                                 status = state.surface->query(
   2142                                         NATIVE_WINDOW_HEIGHT, &height);
   2143                                 ALOGE_IF(status != NO_ERROR,
   2144                                         "Unable to query height (%d)", status);
   2145                                 int intFormat = 0;
   2146                                 status = state.surface->query(
   2147                                         NATIVE_WINDOW_FORMAT, &intFormat);
   2148                                 ALOGE_IF(status != NO_ERROR,
   2149                                         "Unable to query format (%d)", status);
   2150                                 auto format = static_cast<android_pixel_format_t>(
   2151                                         intFormat);
   2152 
   2153                                 mHwc->allocateVirtualDisplay(width, height, &format,
   2154                                         &hwcId);
   2155                             }
   2156 
   2157                             // TODO: Plumb requested format back up to consumer
   2158 
   2159                             sp<VirtualDisplaySurface> vds =
   2160                                     new VirtualDisplaySurface(*mHwc,
   2161                                             hwcId, state.surface, bqProducer,
   2162                                             bqConsumer, state.displayName);
   2163 
   2164                             dispSurface = vds;
   2165                             producer = vds;
   2166                         }
   2167                     } else {
   2168                         ALOGE_IF(state.surface!=NULL,
   2169                                 "adding a supported display, but rendering "
   2170                                 "surface is provided (%p), ignoring it",
   2171                                 state.surface.get());
   2172 
   2173                         hwcId = state.type;
   2174                         dispSurface = new FramebufferSurface(*mHwc, hwcId, bqConsumer);
   2175                         producer = bqProducer;
   2176                     }
   2177 
   2178                     const wp<IBinder>& display(curr.keyAt(i));
   2179                     if (dispSurface != NULL) {
   2180                         sp<DisplayDevice> hw =
   2181                                 new DisplayDevice(this, state.type, hwcId, state.isSecure, display,
   2182                                                   dispSurface, producer,
   2183                                                   mRenderEngine->getEGLConfig(),
   2184                                                   hasWideColorDisplay);
   2185                         hw->setLayerStack(state.layerStack);
   2186                         hw->setProjection(state.orientation,
   2187                                 state.viewport, state.frame);
   2188                         hw->setDisplayName(state.displayName);
   2189                         mDisplays.add(display, hw);
   2190                         if (!state.isVirtualDisplay()) {
   2191                             mEventThread->onHotplugReceived(state.type, true);
   2192                         }
   2193                     }
   2194                 }
   2195             }
   2196         }
   2197     }
   2198 
   2199     if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
   2200         // The transform hint might have changed for some layers
   2201         // (either because a display has changed, or because a layer
   2202         // as changed).
   2203         //
   2204         // Walk through all the layers in currentLayers,
   2205         // and update their transform hint.
   2206         //
   2207         // If a layer is visible only on a single display, then that
   2208         // display is used to calculate the hint, otherwise we use the
   2209         // default display.
   2210         //
   2211         // NOTE: we do this here, rather than in rebuildLayerStacks() so that
   2212         // the hint is set before we acquire a buffer from the surface texture.
   2213         //
   2214         // NOTE: layer transactions have taken place already, so we use their
   2215         // drawing state. However, SurfaceFlinger's own transaction has not
   2216         // happened yet, so we must use the current state layer list
   2217         // (soon to become the drawing state list).
   2218         //
   2219         sp<const DisplayDevice> disp;
   2220         uint32_t currentlayerStack = 0;
   2221         bool first = true;
   2222         mCurrentState.traverseInZOrder([&](Layer* layer) {
   2223             // NOTE: we rely on the fact that layers are sorted by
   2224             // layerStack first (so we don't have to traverse the list
   2225             // of displays for every layer).
   2226             uint32_t layerStack = layer->getLayerStack();
   2227             if (first || currentlayerStack != layerStack) {
   2228                 currentlayerStack = layerStack;
   2229                 // figure out if this layerstack is mirrored
   2230                 // (more than one display) if so, pick the default display,
   2231                 // if not, pick the only display it's on.
   2232                 disp.clear();
   2233                 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
   2234                     sp<const DisplayDevice> hw(mDisplays[dpy]);
   2235                     if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
   2236                         if (disp == NULL) {
   2237                             disp = hw;
   2238                         } else {
   2239                             disp = NULL;
   2240                             break;
   2241                         }
   2242                     }
   2243                 }
   2244             }
   2245             if (disp == NULL) {
   2246                 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
   2247                 // redraw after transform hint changes. See bug 8508397.
   2248 
   2249                 // could be null when this layer is using a layerStack
   2250                 // that is not visible on any display. Also can occur at
   2251                 // screen off/on times.
   2252                 disp = getDefaultDisplayDeviceLocked();
   2253             }
   2254             layer->updateTransformHint(disp);
   2255 
   2256             first = false;
   2257         });
   2258     }
   2259 
   2260 
   2261     /*
   2262      * Perform our own transaction if needed
   2263      */
   2264 
   2265     if (mLayersAdded) {
   2266         mLayersAdded = false;
   2267         // Layers have been added.
   2268         mVisibleRegionsDirty = true;
   2269     }
   2270 
   2271     // some layers might have been removed, so
   2272     // we need to update the regions they're exposing.
   2273     if (mLayersRemoved) {
   2274         mLayersRemoved = false;
   2275         mVisibleRegionsDirty = true;
   2276         mDrawingState.traverseInZOrder([&](Layer* layer) {
   2277             if (mLayersPendingRemoval.indexOf(layer) >= 0) {
   2278                 // this layer is not visible anymore
   2279                 // TODO: we could traverse the tree from front to back and
   2280                 //       compute the actual visible region
   2281                 // TODO: we could cache the transformed region
   2282                 Region visibleReg;
   2283                 visibleReg.set(layer->computeScreenBounds());
   2284                 invalidateLayerStack(layer, visibleReg);
   2285             }
   2286         });
   2287     }
   2288 
   2289     commitTransaction();
   2290 
   2291     updateCursorAsync();
   2292 }
   2293 
   2294 void SurfaceFlinger::updateCursorAsync()
   2295 {
   2296     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
   2297         auto& displayDevice = mDisplays[displayId];
   2298         if (displayDevice->getHwcDisplayId() < 0) {
   2299             continue;
   2300         }
   2301 
   2302         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
   2303             layer->updateCursorPosition(displayDevice);
   2304         }
   2305     }
   2306 }
   2307 
   2308 void SurfaceFlinger::commitTransaction()
   2309 {
   2310     if (!mLayersPendingRemoval.isEmpty()) {
   2311         // Notify removed layers now that they can't be drawn from
   2312         for (const auto& l : mLayersPendingRemoval) {
   2313             recordBufferingStats(l->getName().string(),
   2314                     l->getOccupancyHistory(true));
   2315             l->onRemoved();
   2316         }
   2317         mLayersPendingRemoval.clear();
   2318     }
   2319 
   2320     // If this transaction is part of a window animation then the next frame
   2321     // we composite should be considered an animation as well.
   2322     mAnimCompositionPending = mAnimTransactionPending;
   2323 
   2324     mDrawingState = mCurrentState;
   2325     mDrawingState.traverseInZOrder([](Layer* layer) {
   2326         layer->commitChildList();
   2327     });
   2328     mTransactionPending = false;
   2329     mAnimTransactionPending = false;
   2330     mTransactionCV.broadcast();
   2331 }
   2332 
   2333 void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
   2334         Region& outDirtyRegion, Region& outOpaqueRegion)
   2335 {
   2336     ATRACE_CALL();
   2337     ALOGV("computeVisibleRegions");
   2338 
   2339     Region aboveOpaqueLayers;
   2340     Region aboveCoveredLayers;
   2341     Region dirty;
   2342 
   2343     outDirtyRegion.clear();
   2344 
   2345     mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
   2346         // start with the whole surface at its current location
   2347         const Layer::State& s(layer->getDrawingState());
   2348 
   2349         // only consider the layers on the given layer stack
   2350         if (!layer->belongsToDisplay(displayDevice->getLayerStack(), displayDevice->isPrimary()))
   2351             return;
   2352 
   2353         /*
   2354          * opaqueRegion: area of a surface that is fully opaque.
   2355          */
   2356         Region opaqueRegion;
   2357 
   2358         /*
   2359          * visibleRegion: area of a surface that is visible on screen
   2360          * and not fully transparent. This is essentially the layer's
   2361          * footprint minus the opaque regions above it.
   2362          * Areas covered by a translucent surface are considered visible.
   2363          */
   2364         Region visibleRegion;
   2365 
   2366         /*
   2367          * coveredRegion: area of a surface that is covered by all
   2368          * visible regions above it (which includes the translucent areas).
   2369          */
   2370         Region coveredRegion;
   2371 
   2372         /*
   2373          * transparentRegion: area of a surface that is hinted to be completely
   2374          * transparent. This is only used to tell when the layer has no visible
   2375          * non-transparent regions and can be removed from the layer list. It
   2376          * does not affect the visibleRegion of this layer or any layers
   2377          * beneath it. The hint may not be correct if apps don't respect the
   2378          * SurfaceView restrictions (which, sadly, some don't).
   2379          */
   2380         Region transparentRegion;
   2381 
   2382 
   2383         // handle hidden surfaces by setting the visible region to empty
   2384         if (CC_LIKELY(layer->isVisible())) {
   2385             const bool translucent = !layer->isOpaque(s);
   2386             Rect bounds(layer->computeScreenBounds());
   2387             visibleRegion.set(bounds);
   2388             Transform tr = layer->getTransform();
   2389             if (!visibleRegion.isEmpty()) {
   2390                 // Remove the transparent area from the visible region
   2391                 if (translucent) {
   2392                     if (tr.preserveRects()) {
   2393                         // transform the transparent region
   2394                         transparentRegion = tr.transform(s.activeTransparentRegion);
   2395                     } else {
   2396                         // transformation too complex, can't do the
   2397                         // transparent region optimization.
   2398                         transparentRegion.clear();
   2399                     }
   2400                 }
   2401 
   2402                 // compute the opaque region
   2403                 const int32_t layerOrientation = tr.getOrientation();
   2404                 if (s.alpha == 1.0f && !translucent &&
   2405                         ((layerOrientation & Transform::ROT_INVALID) == false)) {
   2406                     // the opaque region is the layer's footprint
   2407                     opaqueRegion = visibleRegion;
   2408                 }
   2409             }
   2410         }
   2411 
   2412         // Clip the covered region to the visible region
   2413         coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
   2414 
   2415         // Update aboveCoveredLayers for next (lower) layer
   2416         aboveCoveredLayers.orSelf(visibleRegion);
   2417 
   2418         // subtract the opaque region covered by the layers above us
   2419         visibleRegion.subtractSelf(aboveOpaqueLayers);
   2420 
   2421         // compute this layer's dirty region
   2422         if (layer->contentDirty) {
   2423             // we need to invalidate the whole region
   2424             dirty = visibleRegion;
   2425             // as well, as the old visible region
   2426             dirty.orSelf(layer->visibleRegion);
   2427             layer->contentDirty = false;
   2428         } else {
   2429             /* compute the exposed region:
   2430              *   the exposed region consists of two components:
   2431              *   1) what's VISIBLE now and was COVERED before
   2432              *   2) what's EXPOSED now less what was EXPOSED before
   2433              *
   2434              * note that (1) is conservative, we start with the whole
   2435              * visible region but only keep what used to be covered by
   2436              * something -- which mean it may have been exposed.
   2437              *
   2438              * (2) handles areas that were not covered by anything but got
   2439              * exposed because of a resize.
   2440              */
   2441             const Region newExposed = visibleRegion - coveredRegion;
   2442             const Region oldVisibleRegion = layer->visibleRegion;
   2443             const Region oldCoveredRegion = layer->coveredRegion;
   2444             const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
   2445             dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
   2446         }
   2447         dirty.subtractSelf(aboveOpaqueLayers);
   2448 
   2449         // accumulate to the screen dirty region
   2450         outDirtyRegion.orSelf(dirty);
   2451 
   2452         // Update aboveOpaqueLayers for next (lower) layer
   2453         aboveOpaqueLayers.orSelf(opaqueRegion);
   2454 
   2455         // Store the visible region in screen space
   2456         layer->setVisibleRegion(visibleRegion);
   2457         layer->setCoveredRegion(coveredRegion);
   2458         layer->setVisibleNonTransparentRegion(
   2459                 visibleRegion.subtract(transparentRegion));
   2460     });
   2461 
   2462     outOpaqueRegion = aboveOpaqueLayers;
   2463 }
   2464 
   2465 void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
   2466     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
   2467         const sp<DisplayDevice>& hw(mDisplays[dpy]);
   2468         if (layer->belongsToDisplay(hw->getLayerStack(), hw->isPrimary())) {
   2469             hw->dirtyRegion.orSelf(dirty);
   2470         }
   2471     }
   2472 }
   2473 
   2474 bool SurfaceFlinger::handlePageFlip()
   2475 {
   2476     ALOGV("handlePageFlip");
   2477 
   2478     nsecs_t latchTime = systemTime();
   2479 
   2480     bool visibleRegions = false;
   2481     bool frameQueued = false;
   2482     bool newDataLatched = false;
   2483 
   2484     // Store the set of layers that need updates. This set must not change as
   2485     // buffers are being latched, as this could result in a deadlock.
   2486     // Example: Two producers share the same command stream and:
   2487     // 1.) Layer 0 is latched
   2488     // 2.) Layer 0 gets a new frame
   2489     // 2.) Layer 1 gets a new frame
   2490     // 3.) Layer 1 is latched.
   2491     // Display is now waiting on Layer 1's frame, which is behind layer 0's
   2492     // second frame. But layer 0's second frame could be waiting on display.
   2493     mDrawingState.traverseInZOrder([&](Layer* layer) {
   2494         if (layer->hasQueuedFrame()) {
   2495             frameQueued = true;
   2496             if (layer->shouldPresentNow(mPrimaryDispSync)) {
   2497                 mLayersWithQueuedFrames.push_back(layer);
   2498             } else {
   2499                 layer->useEmptyDamage();
   2500             }
   2501         } else {
   2502             layer->useEmptyDamage();
   2503         }
   2504     });
   2505 
   2506     for (auto& layer : mLayersWithQueuedFrames) {
   2507         const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
   2508         layer->useSurfaceDamage();
   2509         invalidateLayerStack(layer, dirty);
   2510         if (layer->isBufferLatched()) {
   2511             newDataLatched = true;
   2512         }
   2513     }
   2514 
   2515     mVisibleRegionsDirty |= visibleRegions;
   2516 
   2517     // If we will need to wake up at some time in the future to deal with a
   2518     // queued frame that shouldn't be displayed during this vsync period, wake
   2519     // up during the next vsync period to check again.
   2520     if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
   2521         signalLayerUpdate();
   2522     }
   2523 
   2524     // Only continue with the refresh if there is actually new work to do
   2525     return !mLayersWithQueuedFrames.empty() && newDataLatched;
   2526 }
   2527 
   2528 void SurfaceFlinger::invalidateHwcGeometry()
   2529 {
   2530     mGeometryInvalid = true;
   2531 }
   2532 
   2533 
   2534 void SurfaceFlinger::doDisplayComposition(
   2535         const sp<const DisplayDevice>& displayDevice,
   2536         const Region& inDirtyRegion)
   2537 {
   2538     // We only need to actually compose the display if:
   2539     // 1) It is being handled by hardware composer, which may need this to
   2540     //    keep its virtual display state machine in sync, or
   2541     // 2) There is work to be done (the dirty region isn't empty)
   2542     bool isHwcDisplay = displayDevice->getHwcDisplayId() >= 0;
   2543     if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
   2544         ALOGV("Skipping display composition");
   2545         return;
   2546     }
   2547 
   2548     ALOGV("doDisplayComposition");
   2549 
   2550     Region dirtyRegion(inDirtyRegion);
   2551 
   2552     // compute the invalid region
   2553     displayDevice->swapRegion.orSelf(dirtyRegion);
   2554 
   2555     uint32_t flags = displayDevice->getFlags();
   2556     if (flags & DisplayDevice::SWAP_RECTANGLE) {
   2557         // we can redraw only what's dirty, but since SWAP_RECTANGLE only
   2558         // takes a rectangle, we must make sure to update that whole
   2559         // rectangle in that case
   2560         dirtyRegion.set(displayDevice->swapRegion.bounds());
   2561     } else {
   2562         if (flags & DisplayDevice::PARTIAL_UPDATES) {
   2563             // We need to redraw the rectangle that will be updated
   2564             // (pushed to the framebuffer).
   2565             // This is needed because PARTIAL_UPDATES only takes one
   2566             // rectangle instead of a region (see DisplayDevice::flip())
   2567             dirtyRegion.set(displayDevice->swapRegion.bounds());
   2568         } else {
   2569             // we need to redraw everything (the whole screen)
   2570             dirtyRegion.set(displayDevice->bounds());
   2571             displayDevice->swapRegion = dirtyRegion;
   2572         }
   2573     }
   2574 
   2575     if (!doComposeSurfaces(displayDevice, dirtyRegion)) return;
   2576 
   2577     // update the swap region and clear the dirty region
   2578     displayDevice->swapRegion.orSelf(dirtyRegion);
   2579 
   2580     // swap buffers (presentation)
   2581     displayDevice->swapBuffers(getHwComposer());
   2582 }
   2583 
   2584 bool SurfaceFlinger::doComposeSurfaces(
   2585         const sp<const DisplayDevice>& displayDevice, const Region& dirty)
   2586 {
   2587     ALOGV("doComposeSurfaces");
   2588 
   2589     const auto hwcId = displayDevice->getHwcDisplayId();
   2590 
   2591     mat4 oldColorMatrix;
   2592     const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
   2593             !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
   2594     if (applyColorMatrix) {
   2595         mat4 colorMatrix = mColorMatrix * mDaltonizer();
   2596         oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
   2597     }
   2598 
   2599     bool hasClientComposition = mHwc->hasClientComposition(hwcId);
   2600     if (hasClientComposition) {
   2601         ALOGV("hasClientComposition");
   2602 
   2603 #ifdef USE_HWC2
   2604         mRenderEngine->setWideColor(
   2605                 displayDevice->getWideColorSupport() && !mForceNativeColorMode);
   2606         mRenderEngine->setColorMode(mForceNativeColorMode ?
   2607                 HAL_COLOR_MODE_NATIVE : displayDevice->getActiveColorMode());
   2608 #endif
   2609         if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
   2610             ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
   2611                   displayDevice->getDisplayName().string());
   2612             eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
   2613 
   2614             // |mStateLock| not needed as we are on the main thread
   2615             if(!getDefaultDisplayDeviceLocked()->makeCurrent(mEGLDisplay, mEGLContext)) {
   2616               ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
   2617             }
   2618             return false;
   2619         }
   2620 
   2621         // Never touch the framebuffer if we don't have any framebuffer layers
   2622         const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
   2623         if (hasDeviceComposition) {
   2624             // when using overlays, we assume a fully transparent framebuffer
   2625             // NOTE: we could reduce how much we need to clear, for instance
   2626             // remove where there are opaque FB layers. however, on some
   2627             // GPUs doing a "clean slate" clear might be more efficient.
   2628             // We'll revisit later if needed.
   2629             mRenderEngine->clearWithColor(0, 0, 0, 0);
   2630         } else {
   2631             // we start with the whole screen area
   2632             const Region bounds(displayDevice->getBounds());
   2633 
   2634             // we remove the scissor part
   2635             // we're left with the letterbox region
   2636             // (common case is that letterbox ends-up being empty)
   2637             const Region letterbox(bounds.subtract(displayDevice->getScissor()));
   2638 
   2639             // compute the area to clear
   2640             Region region(displayDevice->undefinedRegion.merge(letterbox));
   2641 
   2642             // but limit it to the dirty region
   2643             region.andSelf(dirty);
   2644 
   2645             // screen is already cleared here
   2646             if (!region.isEmpty()) {
   2647                 // can happen with SurfaceView
   2648                 drawWormhole(displayDevice, region);
   2649             }
   2650         }
   2651 
   2652         if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
   2653             // just to be on the safe side, we don't set the
   2654             // scissor on the main display. It should never be needed
   2655             // anyways (though in theory it could since the API allows it).
   2656             const Rect& bounds(displayDevice->getBounds());
   2657             const Rect& scissor(displayDevice->getScissor());
   2658             if (scissor != bounds) {
   2659                 // scissor doesn't match the screen's dimensions, so we
   2660                 // need to clear everything outside of it and enable
   2661                 // the GL scissor so we don't draw anything where we shouldn't
   2662 
   2663                 // enable scissor for this frame
   2664                 const uint32_t height = displayDevice->getHeight();
   2665                 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
   2666                         scissor.getWidth(), scissor.getHeight());
   2667             }
   2668         }
   2669     }
   2670 
   2671     /*
   2672      * and then, render the layers targeted at the framebuffer
   2673      */
   2674 
   2675     ALOGV("Rendering client layers");
   2676     const Transform& displayTransform = displayDevice->getTransform();
   2677     if (hwcId >= 0) {
   2678         // we're using h/w composer
   2679         bool firstLayer = true;
   2680         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
   2681             const Region clip(dirty.intersect(
   2682                     displayTransform.transform(layer->visibleRegion)));
   2683             ALOGV("Layer: %s", layer->getName().string());
   2684             ALOGV("  Composition type: %s",
   2685                     to_string(layer->getCompositionType(hwcId)).c_str());
   2686             if (!clip.isEmpty()) {
   2687                 switch (layer->getCompositionType(hwcId)) {
   2688                     case HWC2::Composition::Cursor:
   2689                     case HWC2::Composition::Device:
   2690                     case HWC2::Composition::Sideband:
   2691                     case HWC2::Composition::SolidColor: {
   2692                         const Layer::State& state(layer->getDrawingState());
   2693                         if (layer->getClearClientTarget(hwcId) && !firstLayer &&
   2694                                 layer->isOpaque(state) && (state.alpha == 1.0f)
   2695                                 && hasClientComposition) {
   2696                             // never clear the very first layer since we're
   2697                             // guaranteed the FB is already cleared
   2698                             layer->clearWithOpenGL(displayDevice);
   2699                         }
   2700                         break;
   2701                     }
   2702                     case HWC2::Composition::Client: {
   2703                         layer->draw(displayDevice, clip);
   2704                         break;
   2705                     }
   2706                     default:
   2707                         break;
   2708                 }
   2709             } else {
   2710                 ALOGV("  Skipping for empty clip");
   2711             }
   2712             firstLayer = false;
   2713         }
   2714     } else {
   2715         // we're not using h/w composer
   2716         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
   2717             const Region clip(dirty.intersect(
   2718                     displayTransform.transform(layer->visibleRegion)));
   2719             if (!clip.isEmpty()) {
   2720                 layer->draw(displayDevice, clip);
   2721             }
   2722         }
   2723     }
   2724 
   2725     if (applyColorMatrix) {
   2726         getRenderEngine().setupColorTransform(oldColorMatrix);
   2727     }
   2728 
   2729     // disable scissor at the end of the frame
   2730     mRenderEngine->disableScissor();
   2731     return true;
   2732 }
   2733 
   2734 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const {
   2735     const int32_t height = displayDevice->getHeight();
   2736     RenderEngine& engine(getRenderEngine());
   2737     engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
   2738 }
   2739 
   2740 status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
   2741         const sp<IBinder>& handle,
   2742         const sp<IGraphicBufferProducer>& gbc,
   2743         const sp<Layer>& lbc,
   2744         const sp<Layer>& parent)
   2745 {
   2746     // add this layer to the current state list
   2747     {
   2748         Mutex::Autolock _l(mStateLock);
   2749         if (mNumLayers >= MAX_LAYERS) {
   2750             ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
   2751                   MAX_LAYERS);
   2752             return NO_MEMORY;
   2753         }
   2754         if (parent == nullptr) {
   2755             mCurrentState.layersSortedByZ.add(lbc);
   2756         } else {
   2757             if (mCurrentState.layersSortedByZ.indexOf(parent) < 0) {
   2758                 ALOGE("addClientLayer called with a removed parent");
   2759                 return NAME_NOT_FOUND;
   2760             }
   2761             parent->addChild(lbc);
   2762         }
   2763 
   2764         mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
   2765         mLayersAdded = true;
   2766         mNumLayers++;
   2767     }
   2768 
   2769     // attach this layer to the client
   2770     client->attachLayer(handle, lbc);
   2771 
   2772     return NO_ERROR;
   2773 }
   2774 
   2775 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
   2776     Mutex::Autolock _l(mStateLock);
   2777 
   2778     const auto& p = layer->getParent();
   2779     ssize_t index;
   2780     if (p != nullptr) {
   2781         if (topLevelOnly) {
   2782             return NO_ERROR;
   2783         }
   2784 
   2785         sp<Layer> ancestor = p;
   2786         while (ancestor->getParent() != nullptr) {
   2787             ancestor = ancestor->getParent();
   2788         }
   2789         if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
   2790             ALOGE("removeLayer called with a layer whose parent has been removed");
   2791             return NAME_NOT_FOUND;
   2792         }
   2793 
   2794         index = p->removeChild(layer);
   2795     } else {
   2796         index = mCurrentState.layersSortedByZ.remove(layer);
   2797     }
   2798 
   2799     // As a matter of normal operation, the LayerCleaner will produce a second
   2800     // attempt to remove the surface. The Layer will be kept alive in mDrawingState
   2801     // so we will succeed in promoting it, but it's already been removed
   2802     // from mCurrentState. As long as we can find it in mDrawingState we have no problem
   2803     // otherwise something has gone wrong and we are leaking the layer.
   2804     if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
   2805         ALOGE("Failed to find layer (%s) in layer parent (%s).",
   2806                 layer->getName().string(),
   2807                 (p != nullptr) ? p->getName().string() : "no-parent");
   2808         return BAD_VALUE;
   2809     } else if (index < 0) {
   2810         return NO_ERROR;
   2811     }
   2812 
   2813     layer->onRemovedFromCurrentState();
   2814     mLayersPendingRemoval.add(layer);
   2815     mLayersRemoved = true;
   2816     mNumLayers -= 1 + layer->getChildrenCount();
   2817     setTransactionFlags(eTransactionNeeded);
   2818     return NO_ERROR;
   2819 }
   2820 
   2821 uint32_t SurfaceFlinger::peekTransactionFlags() {
   2822     return android_atomic_release_load(&mTransactionFlags);
   2823 }
   2824 
   2825 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
   2826     return android_atomic_and(~flags, &mTransactionFlags) & flags;
   2827 }
   2828 
   2829 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
   2830     uint32_t old = android_atomic_or(flags, &mTransactionFlags);
   2831     if ((old & flags)==0) { // wake the server up
   2832         signalTransaction();
   2833     }
   2834     return old;
   2835 }
   2836 
   2837 void SurfaceFlinger::setTransactionState(
   2838         const Vector<ComposerState>& state,
   2839         const Vector<DisplayState>& displays,
   2840         uint32_t flags)
   2841 {
   2842     ATRACE_CALL();
   2843     Mutex::Autolock _l(mStateLock);
   2844     uint32_t transactionFlags = 0;
   2845 
   2846     if (flags & eAnimation) {
   2847         // For window updates that are part of an animation we must wait for
   2848         // previous animation "frames" to be handled.
   2849         while (mAnimTransactionPending) {
   2850             status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
   2851             if (CC_UNLIKELY(err != NO_ERROR)) {
   2852                 // just in case something goes wrong in SF, return to the
   2853                 // caller after a few seconds.
   2854                 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
   2855                         "waiting for previous animation frame");
   2856                 mAnimTransactionPending = false;
   2857                 break;
   2858             }
   2859         }
   2860     }
   2861 
   2862     size_t count = displays.size();
   2863     for (size_t i=0 ; i<count ; i++) {
   2864         const DisplayState& s(displays[i]);
   2865         transactionFlags |= setDisplayStateLocked(s);
   2866     }
   2867 
   2868     count = state.size();
   2869     for (size_t i=0 ; i<count ; i++) {
   2870         const ComposerState& s(state[i]);
   2871         // Here we need to check that the interface we're given is indeed
   2872         // one of our own. A malicious client could give us a NULL
   2873         // IInterface, or one of its own or even one of our own but a
   2874         // different type. All these situations would cause us to crash.
   2875         //
   2876         // NOTE: it would be better to use RTTI as we could directly check
   2877         // that we have a Client*. however, RTTI is disabled in Android.
   2878         if (s.client != NULL) {
   2879             sp<IBinder> binder = IInterface::asBinder(s.client);
   2880             if (binder != NULL) {
   2881                 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
   2882                     sp<Client> client( static_cast<Client *>(s.client.get()) );
   2883                     transactionFlags |= setClientStateLocked(client, s.state);
   2884                 }
   2885             }
   2886         }
   2887     }
   2888 
   2889     // If a synchronous transaction is explicitly requested without any changes, force a transaction
   2890     // anyway. This can be used as a flush mechanism for previous async transactions.
   2891     // Empty animation transaction can be used to simulate back-pressure, so also force a
   2892     // transaction for empty animation transactions.
   2893     if (transactionFlags == 0 &&
   2894             ((flags & eSynchronous) || (flags & eAnimation))) {
   2895         transactionFlags = eTransactionNeeded;
   2896     }
   2897 
   2898     if (transactionFlags) {
   2899         if (mInterceptor.isEnabled()) {
   2900             mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
   2901         }
   2902 
   2903         // this triggers the transaction
   2904         setTransactionFlags(transactionFlags);
   2905 
   2906         // if this is a synchronous transaction, wait for it to take effect
   2907         // before returning.
   2908         if (flags & eSynchronous) {
   2909             mTransactionPending = true;
   2910         }
   2911         if (flags & eAnimation) {
   2912             mAnimTransactionPending = true;
   2913         }
   2914         while (mTransactionPending) {
   2915             status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
   2916             if (CC_UNLIKELY(err != NO_ERROR)) {
   2917                 // just in case something goes wrong in SF, return to the
   2918                 // called after a few seconds.
   2919                 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
   2920                 mTransactionPending = false;
   2921                 break;
   2922             }
   2923         }
   2924     }
   2925 }
   2926 
   2927 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
   2928 {
   2929     ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
   2930     if (dpyIdx < 0)
   2931         return 0;
   2932 
   2933     uint32_t flags = 0;
   2934     DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
   2935     if (disp.isValid()) {
   2936         const uint32_t what = s.what;
   2937         if (what & DisplayState::eSurfaceChanged) {
   2938             if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
   2939                 disp.surface = s.surface;
   2940                 flags |= eDisplayTransactionNeeded;
   2941             }
   2942         }
   2943         if (what & DisplayState::eLayerStackChanged) {
   2944             if (disp.layerStack != s.layerStack) {
   2945                 disp.layerStack = s.layerStack;
   2946                 flags |= eDisplayTransactionNeeded;
   2947             }
   2948         }
   2949         if (what & DisplayState::eDisplayProjectionChanged) {
   2950             if (disp.orientation != s.orientation) {
   2951                 disp.orientation = s.orientation;
   2952                 flags |= eDisplayTransactionNeeded;
   2953             }
   2954             if (disp.frame != s.frame) {
   2955                 disp.frame = s.frame;
   2956                 flags |= eDisplayTransactionNeeded;
   2957             }
   2958             if (disp.viewport != s.viewport) {
   2959                 disp.viewport = s.viewport;
   2960                 flags |= eDisplayTransactionNeeded;
   2961             }
   2962         }
   2963         if (what & DisplayState::eDisplaySizeChanged) {
   2964             if (disp.width != s.width) {
   2965                 disp.width = s.width;
   2966                 flags |= eDisplayTransactionNeeded;
   2967             }
   2968             if (disp.height != s.height) {
   2969                 disp.height = s.height;
   2970                 flags |= eDisplayTransactionNeeded;
   2971             }
   2972         }
   2973     }
   2974     return flags;
   2975 }
   2976 
   2977 uint32_t SurfaceFlinger::setClientStateLocked(
   2978         const sp<Client>& client,
   2979         const layer_state_t& s)
   2980 {
   2981     uint32_t flags = 0;
   2982     sp<Layer> layer(client->getLayerUser(s.surface));
   2983     if (layer != 0) {
   2984         const uint32_t what = s.what;
   2985         bool geometryAppliesWithResize =
   2986                 what & layer_state_t::eGeometryAppliesWithResize;
   2987         if (what & layer_state_t::ePositionChanged) {
   2988             if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
   2989                 flags |= eTraversalNeeded;
   2990             }
   2991         }
   2992         if (what & layer_state_t::eLayerChanged) {
   2993             // NOTE: index needs to be calculated before we update the state
   2994             const auto& p = layer->getParent();
   2995             if (p == nullptr) {
   2996                 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
   2997                 if (layer->setLayer(s.z) && idx >= 0) {
   2998                     mCurrentState.layersSortedByZ.removeAt(idx);
   2999                     mCurrentState.layersSortedByZ.add(layer);
   3000                     // we need traversal (state changed)
   3001                     // AND transaction (list changed)
   3002                     flags |= eTransactionNeeded|eTraversalNeeded;
   3003                 }
   3004             } else {
   3005                 if (p->setChildLayer(layer, s.z)) {
   3006                     flags |= eTransactionNeeded|eTraversalNeeded;
   3007                 }
   3008             }
   3009         }
   3010         if (what & layer_state_t::eRelativeLayerChanged) {
   3011             if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
   3012                 flags |= eTransactionNeeded|eTraversalNeeded;
   3013             }
   3014         }
   3015         if (what & layer_state_t::eSizeChanged) {
   3016             if (layer->setSize(s.w, s.h)) {
   3017                 flags |= eTraversalNeeded;
   3018             }
   3019         }
   3020         if (what & layer_state_t::eAlphaChanged) {
   3021             if (layer->setAlpha(s.alpha))
   3022                 flags |= eTraversalNeeded;
   3023         }
   3024         if (what & layer_state_t::eMatrixChanged) {
   3025             if (layer->setMatrix(s.matrix))
   3026                 flags |= eTraversalNeeded;
   3027         }
   3028         if (what & layer_state_t::eTransparentRegionChanged) {
   3029             if (layer->setTransparentRegionHint(s.transparentRegion))
   3030                 flags |= eTraversalNeeded;
   3031         }
   3032         if (what & layer_state_t::eFlagsChanged) {
   3033             if (layer->setFlags(s.flags, s.mask))
   3034                 flags |= eTraversalNeeded;
   3035         }
   3036         if (what & layer_state_t::eCropChanged) {
   3037             if (layer->setCrop(s.crop, !geometryAppliesWithResize))
   3038                 flags |= eTraversalNeeded;
   3039         }
   3040         if (what & layer_state_t::eFinalCropChanged) {
   3041             if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
   3042                 flags |= eTraversalNeeded;
   3043         }
   3044         if (what & layer_state_t::eLayerStackChanged) {
   3045             ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
   3046             // We only allow setting layer stacks for top level layers,
   3047             // everything else inherits layer stack from its parent.
   3048             if (layer->hasParent()) {
   3049                 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
   3050                         layer->getName().string());
   3051             } else if (idx < 0) {
   3052                 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
   3053                         "that also does not appear in the top level layer list. Something"
   3054                         " has gone wrong.", layer->getName().string());
   3055             } else if (layer->setLayerStack(s.layerStack)) {
   3056                 mCurrentState.layersSortedByZ.removeAt(idx);
   3057                 mCurrentState.layersSortedByZ.add(layer);
   3058                 // we need traversal (state changed)
   3059                 // AND transaction (list changed)
   3060                 flags |= eTransactionNeeded|eTraversalNeeded;
   3061             }
   3062         }
   3063         if (what & layer_state_t::eDeferTransaction) {
   3064             if (s.barrierHandle != nullptr) {
   3065                 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
   3066             } else if (s.barrierGbp != nullptr) {
   3067                 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
   3068                 if (authenticateSurfaceTextureLocked(gbp)) {
   3069                     const auto& otherLayer =
   3070                         (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
   3071                     layer->deferTransactionUntil(otherLayer, s.frameNumber);
   3072                 } else {
   3073                     ALOGE("Attempt to defer transaction to to an"
   3074                             " unrecognized GraphicBufferProducer");
   3075                 }
   3076             }
   3077             // We don't trigger a traversal here because if no other state is
   3078             // changed, we don't want this to cause any more work
   3079         }
   3080         if (what & layer_state_t::eReparentChildren) {
   3081             if (layer->reparentChildren(s.reparentHandle)) {
   3082                 flags |= eTransactionNeeded|eTraversalNeeded;
   3083             }
   3084         }
   3085         if (what & layer_state_t::eDetachChildren) {
   3086             layer->detachChildren();
   3087         }
   3088         if (what & layer_state_t::eOverrideScalingModeChanged) {
   3089             layer->setOverrideScalingMode(s.overrideScalingMode);
   3090             // We don't trigger a traversal here because if no other state is
   3091             // changed, we don't want this to cause any more work
   3092         }
   3093     }
   3094     return flags;
   3095 }
   3096 
   3097 status_t SurfaceFlinger::createLayer(
   3098         const String8& name,
   3099         const sp<Client>& client,
   3100         uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
   3101         uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
   3102         sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
   3103 {
   3104     if (int32_t(w|h) < 0) {
   3105         ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
   3106                 int(w), int(h));
   3107         return BAD_VALUE;
   3108     }
   3109 
   3110     status_t result = NO_ERROR;
   3111 
   3112     sp<Layer> layer;
   3113 
   3114     String8 uniqueName = getUniqueLayerName(name);
   3115 
   3116     switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
   3117         case ISurfaceComposerClient::eFXSurfaceNormal:
   3118             result = createNormalLayer(client,
   3119                     uniqueName, w, h, flags, format,
   3120                     handle, gbp, &layer);
   3121             break;
   3122         case ISurfaceComposerClient::eFXSurfaceDim:
   3123             result = createDimLayer(client,
   3124                     uniqueName, w, h, flags,
   3125                     handle, gbp, &layer);
   3126             break;
   3127         default:
   3128             result = BAD_VALUE;
   3129             break;
   3130     }
   3131 
   3132     if (result != NO_ERROR) {
   3133         return result;
   3134     }
   3135 
   3136     // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
   3137     // TODO b/64227542
   3138     if (windowType == 441731) {
   3139         windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
   3140         layer->setPrimaryDisplayOnly();
   3141     }
   3142 
   3143     layer->setInfo(windowType, ownerUid);
   3144 
   3145     result = addClientLayer(client, *handle, *gbp, layer, *parent);
   3146     if (result != NO_ERROR) {
   3147         return result;
   3148     }
   3149     mInterceptor.saveSurfaceCreation(layer);
   3150 
   3151     setTransactionFlags(eTransactionNeeded);
   3152     return result;
   3153 }
   3154 
   3155 String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
   3156 {
   3157     bool matchFound = true;
   3158     uint32_t dupeCounter = 0;
   3159 
   3160     // Tack on our counter whether there is a hit or not, so everyone gets a tag
   3161     String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
   3162 
   3163     // Loop over layers until we're sure there is no matching name
   3164     while (matchFound) {
   3165         matchFound = false;
   3166         mDrawingState.traverseInZOrder([&](Layer* layer) {
   3167             if (layer->getName() == uniqueName) {
   3168                 matchFound = true;
   3169                 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
   3170             }
   3171         });
   3172     }
   3173 
   3174     ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
   3175 
   3176     return uniqueName;
   3177 }
   3178 
   3179 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
   3180         const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
   3181         sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
   3182 {
   3183     // initialize the surfaces
   3184     switch (format) {
   3185     case PIXEL_FORMAT_TRANSPARENT:
   3186     case PIXEL_FORMAT_TRANSLUCENT:
   3187         format = PIXEL_FORMAT_RGBA_8888;
   3188         break;
   3189     case PIXEL_FORMAT_OPAQUE:
   3190         format = PIXEL_FORMAT_RGBX_8888;
   3191         break;
   3192     }
   3193 
   3194     *outLayer = new Layer(this, client, name, w, h, flags);
   3195     status_t err = (*outLayer)->setBuffers(w, h, format, flags);
   3196     if (err == NO_ERROR) {
   3197         *handle = (*outLayer)->getHandle();
   3198         *gbp = (*outLayer)->getProducer();
   3199     }
   3200 
   3201     ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
   3202     return err;
   3203 }
   3204 
   3205 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
   3206         const String8& name, uint32_t w, uint32_t h, uint32_t flags,
   3207         sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
   3208 {
   3209     *outLayer = new LayerDim(this, client, name, w, h, flags);
   3210     *handle = (*outLayer)->getHandle();
   3211     *gbp = (*outLayer)->getProducer();
   3212     return NO_ERROR;
   3213 }
   3214 
   3215 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
   3216 {
   3217     // called by a client when it wants to remove a Layer
   3218     status_t err = NO_ERROR;
   3219     sp<Layer> l(client->getLayerUser(handle));
   3220     if (l != NULL) {
   3221         mInterceptor.saveSurfaceDeletion(l);
   3222         err = removeLayer(l);
   3223         ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
   3224                 "error removing layer=%p (%s)", l.get(), strerror(-err));
   3225     }
   3226     return err;
   3227 }
   3228 
   3229 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
   3230 {
   3231     // called by ~LayerCleaner() when all references to the IBinder (handle)
   3232     // are gone
   3233     sp<Layer> l = layer.promote();
   3234     if (l == nullptr) {
   3235         // The layer has already been removed, carry on
   3236         return NO_ERROR;
   3237     }
   3238     // If we have a parent, then we can continue to live as long as it does.
   3239     return removeLayer(l, true);
   3240 }
   3241 
   3242 // ---------------------------------------------------------------------------
   3243 
   3244 void SurfaceFlinger::onInitializeDisplays() {
   3245     // reset screen orientation and use primary layer stack
   3246     Vector<ComposerState> state;
   3247     Vector<DisplayState> displays;
   3248     DisplayState d;
   3249     d.what = DisplayState::eDisplayProjectionChanged |
   3250              DisplayState::eLayerStackChanged;
   3251     d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
   3252     d.layerStack = 0;
   3253     d.orientation = DisplayState::eOrientationDefault;
   3254     d.frame.makeInvalid();
   3255     d.viewport.makeInvalid();
   3256     d.width = 0;
   3257     d.height = 0;
   3258     displays.add(d);
   3259     setTransactionState(state, displays, 0);
   3260     setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
   3261                          /*stateLockHeld*/ false);
   3262 
   3263     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
   3264     const nsecs_t period = activeConfig->getVsyncPeriod();
   3265     mAnimFrameTracker.setDisplayRefreshPeriod(period);
   3266 
   3267     // Use phase of 0 since phase is not known.
   3268     // Use latency of 0, which will snap to the ideal latency.
   3269     setCompositorTimingSnapped(0, period, 0);
   3270 }
   3271 
   3272 void SurfaceFlinger::initializeDisplays() {
   3273     class MessageScreenInitialized : public MessageBase {
   3274         SurfaceFlinger* flinger;
   3275     public:
   3276         explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
   3277         virtual bool handler() {
   3278             flinger->onInitializeDisplays();
   3279             return true;
   3280         }
   3281     };
   3282     sp<MessageBase> msg = new MessageScreenInitialized(this);
   3283     postMessageAsync(msg);  // we may be called from main thread, use async message
   3284 }
   3285 
   3286 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
   3287              int mode, bool stateLockHeld) {
   3288     ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
   3289             this);
   3290     int32_t type = hw->getDisplayType();
   3291     int currentMode = hw->getPowerMode();
   3292 
   3293     if (mode == currentMode) {
   3294         return;
   3295     }
   3296 
   3297     hw->setPowerMode(mode);
   3298     if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
   3299         ALOGW("Trying to set power mode for virtual display");
   3300         return;
   3301     }
   3302 
   3303     if (mInterceptor.isEnabled()) {
   3304         ConditionalLock lock(mStateLock, !stateLockHeld);
   3305         ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
   3306         if (idx < 0) {
   3307             ALOGW("Surface Interceptor SavePowerMode: invalid display token");
   3308             return;
   3309         }
   3310         mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
   3311     }
   3312 
   3313     if (currentMode == HWC_POWER_MODE_OFF) {
   3314         // Turn on the display
   3315         getHwComposer().setPowerMode(type, mode);
   3316         if (type == DisplayDevice::DISPLAY_PRIMARY &&
   3317             mode != HWC_POWER_MODE_DOZE_SUSPEND) {
   3318             // FIXME: eventthread only knows about the main display right now
   3319             mEventThread->onScreenAcquired();
   3320             resyncToHardwareVsync(true);
   3321         }
   3322 
   3323         mVisibleRegionsDirty = true;
   3324         mHasPoweredOff = true;
   3325         repaintEverythingLocked();
   3326 
   3327         struct sched_param param = {0};
   3328         param.sched_priority = 1;
   3329         if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
   3330             ALOGW("Couldn't set SCHED_FIFO on display on");
   3331         }
   3332     } else if (mode == HWC_POWER_MODE_OFF) {
   3333         // Turn off the display
   3334         struct sched_param param = {0};
   3335         if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
   3336             ALOGW("Couldn't set SCHED_OTHER on display off");
   3337         }
   3338 
   3339         if (type == DisplayDevice::DISPLAY_PRIMARY) {
   3340             disableHardwareVsync(true); // also cancels any in-progress resync
   3341 
   3342             // FIXME: eventthread only knows about the main display right now
   3343             mEventThread->onScreenReleased();
   3344         }
   3345 
   3346         getHwComposer().setPowerMode(type, mode);
   3347         mVisibleRegionsDirty = true;
   3348         // from this point on, SF will stop drawing on this display
   3349     } else if (mode == HWC_POWER_MODE_DOZE ||
   3350                mode == HWC_POWER_MODE_NORMAL) {
   3351         // Update display while dozing
   3352         getHwComposer().setPowerMode(type, mode);
   3353         if (type == DisplayDevice::DISPLAY_PRIMARY) {
   3354             // FIXME: eventthread only knows about the main display right now
   3355             mEventThread->onScreenAcquired();
   3356             resyncToHardwareVsync(true);
   3357         }
   3358     } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
   3359         // Leave display going to doze
   3360         if (type == DisplayDevice::DISPLAY_PRIMARY) {
   3361             disableHardwareVsync(true); // also cancels any in-progress resync
   3362             // FIXME: eventthread only knows about the main display right now
   3363             mEventThread->onScreenReleased();
   3364         }
   3365         getHwComposer().setPowerMode(type, mode);
   3366     } else {
   3367         ALOGE("Attempting to set unknown power mode: %d\n", mode);
   3368         getHwComposer().setPowerMode(type, mode);
   3369     }
   3370 }
   3371 
   3372 void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
   3373     class MessageSetPowerMode: public MessageBase {
   3374         SurfaceFlinger& mFlinger;
   3375         sp<IBinder> mDisplay;
   3376         int mMode;
   3377     public:
   3378         MessageSetPowerMode(SurfaceFlinger& flinger,
   3379                 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
   3380                     mDisplay(disp) { mMode = mode; }
   3381         virtual bool handler() {
   3382             sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
   3383             if (hw == NULL) {
   3384                 ALOGE("Attempt to set power mode = %d for null display %p",
   3385                         mMode, mDisplay.get());
   3386             } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
   3387                 ALOGW("Attempt to set power mode = %d for virtual display",
   3388                         mMode);
   3389             } else {
   3390                 mFlinger.setPowerModeInternal(
   3391                         hw, mMode, /*stateLockHeld*/ false);
   3392             }
   3393             return true;
   3394         }
   3395     };
   3396     sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
   3397     postMessageSync(msg);
   3398 }
   3399 
   3400 // ---------------------------------------------------------------------------
   3401 
   3402 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
   3403 {
   3404     String8 result;
   3405 
   3406     IPCThreadState* ipc = IPCThreadState::self();
   3407     const int pid = ipc->getCallingPid();
   3408     const int uid = ipc->getCallingUid();
   3409     if ((uid != AID_SHELL) &&
   3410             !PermissionCache::checkPermission(sDump, pid, uid)) {
   3411         result.appendFormat("Permission Denial: "
   3412                 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
   3413     } else {
   3414         // Try to get the main lock, but give up after one second
   3415         // (this would indicate SF is stuck, but we want to be able to
   3416         // print something in dumpsys).
   3417         status_t err = mStateLock.timedLock(s2ns(1));
   3418         bool locked = (err == NO_ERROR);
   3419         if (!locked) {
   3420             result.appendFormat(
   3421                     "SurfaceFlinger appears to be unresponsive (%s [%d]), "
   3422                     "dumping anyways (no locks held)\n", strerror(-err), err);
   3423         }
   3424 
   3425         bool dumpAll = true;
   3426         size_t index = 0;
   3427         size_t numArgs = args.size();
   3428         if (numArgs) {
   3429             if ((index < numArgs) &&
   3430                     (args[index] == String16("--list"))) {
   3431                 index++;
   3432                 listLayersLocked(args, index, result);
   3433                 dumpAll = false;
   3434             }
   3435 
   3436             if ((index < numArgs) &&
   3437                     (args[index] == String16("--latency"))) {
   3438                 index++;
   3439                 dumpStatsLocked(args, index, result);
   3440                 dumpAll = false;
   3441             }
   3442 
   3443             if ((index < numArgs) &&
   3444                     (args[index] == String16("--latency-clear"))) {
   3445                 index++;
   3446                 clearStatsLocked(args, index, result);
   3447                 dumpAll = false;
   3448             }
   3449 
   3450             if ((index < numArgs) &&
   3451                     (args[index] == String16("--dispsync"))) {
   3452                 index++;
   3453                 mPrimaryDispSync.dump(result);
   3454                 dumpAll = false;
   3455             }
   3456 
   3457             if ((index < numArgs) &&
   3458                     (args[index] == String16("--static-screen"))) {
   3459                 index++;
   3460                 dumpStaticScreenStats(result);
   3461                 dumpAll = false;
   3462             }
   3463 
   3464             if ((index < numArgs) &&
   3465                     (args[index] == String16("--frame-events"))) {
   3466                 index++;
   3467                 dumpFrameEventsLocked(result);
   3468                 dumpAll = false;
   3469             }
   3470 
   3471             if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
   3472                 index++;
   3473                 dumpWideColorInfo(result);
   3474                 dumpAll = false;
   3475             }
   3476         }
   3477 
   3478         if (dumpAll) {
   3479             dumpAllLocked(args, index, result);
   3480         }
   3481 
   3482         if (locked) {
   3483             mStateLock.unlock();
   3484         }
   3485     }
   3486     write(fd, result.string(), result.size());
   3487     return NO_ERROR;
   3488 }
   3489 
   3490 void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
   3491         size_t& /* index */, String8& result) const
   3492 {
   3493     mCurrentState.traverseInZOrder([&](Layer* layer) {
   3494         result.appendFormat("%s\n", layer->getName().string());
   3495     });
   3496 }
   3497 
   3498 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
   3499         String8& result) const
   3500 {
   3501     String8 name;
   3502     if (index < args.size()) {
   3503         name = String8(args[index]);
   3504         index++;
   3505     }
   3506 
   3507     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
   3508     const nsecs_t period = activeConfig->getVsyncPeriod();
   3509     result.appendFormat("%" PRId64 "\n", period);
   3510 
   3511     if (name.isEmpty()) {
   3512         mAnimFrameTracker.dumpStats(result);
   3513     } else {
   3514         mCurrentState.traverseInZOrder([&](Layer* layer) {
   3515             if (name == layer->getName()) {
   3516                 layer->dumpFrameStats(result);
   3517             }
   3518         });
   3519     }
   3520 }
   3521 
   3522 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
   3523         String8& /* result */)
   3524 {
   3525     String8 name;
   3526     if (index < args.size()) {
   3527         name = String8(args[index]);
   3528         index++;
   3529     }
   3530 
   3531     mCurrentState.traverseInZOrder([&](Layer* layer) {
   3532         if (name.isEmpty() || (name == layer->getName())) {
   3533             layer->clearFrameStats();
   3534         }
   3535     });
   3536 
   3537     mAnimFrameTracker.clearStats();
   3538 }
   3539 
   3540 // This should only be called from the main thread.  Otherwise it would need
   3541 // the lock and should use mCurrentState rather than mDrawingState.
   3542 void SurfaceFlinger::logFrameStats() {
   3543     mDrawingState.traverseInZOrder([&](Layer* layer) {
   3544         layer->logFrameStats();
   3545     });
   3546 
   3547     mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
   3548 }
   3549 
   3550 void SurfaceFlinger::appendSfConfigString(String8& result) const
   3551 {
   3552     result.append(" [sf");
   3553     result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
   3554 
   3555     if (isLayerTripleBufferingDisabled())
   3556         result.append(" DISABLE_TRIPLE_BUFFERING");
   3557 
   3558     result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
   3559     result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
   3560     result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
   3561     result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
   3562     result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
   3563                         maxFrameBufferAcquiredBuffers);
   3564     result.append("]");
   3565 }
   3566 
   3567 void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
   3568 {
   3569     result.appendFormat("Static screen stats:\n");
   3570     for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
   3571         float bucketTimeSec = mFrameBuckets[b] / 1e9;
   3572         float percent = 100.0f *
   3573                 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
   3574         result.appendFormat("  < %zd frames: %.3f s (%.1f%%)\n",
   3575                 b + 1, bucketTimeSec, percent);
   3576     }
   3577     float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
   3578     float percent = 100.0f *
   3579             static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
   3580     result.appendFormat("  %zd+ frames: %.3f s (%.1f%%)\n",
   3581             NUM_BUCKETS - 1, bucketTimeSec, percent);
   3582 }
   3583 
   3584 void SurfaceFlinger::recordBufferingStats(const char* layerName,
   3585         std::vector<OccupancyTracker::Segment>&& history) {
   3586     Mutex::Autolock lock(mBufferingStatsMutex);
   3587     auto& stats = mBufferingStats[layerName];
   3588     for (const auto& segment : history) {
   3589         if (!segment.usedThirdBuffer) {
   3590             stats.twoBufferTime += segment.totalTime;
   3591         }
   3592         if (segment.occupancyAverage < 1.0f) {
   3593             stats.doubleBufferedTime += segment.totalTime;
   3594         } else if (segment.occupancyAverage < 2.0f) {
   3595             stats.tripleBufferedTime += segment.totalTime;
   3596         }
   3597         ++stats.numSegments;
   3598         stats.totalTime += segment.totalTime;
   3599     }
   3600 }
   3601 
   3602 void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
   3603     result.appendFormat("Layer frame timestamps:\n");
   3604 
   3605     const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
   3606     const size_t count = currentLayers.size();
   3607     for (size_t i=0 ; i<count ; i++) {
   3608         currentLayers[i]->dumpFrameEvents(result);
   3609     }
   3610 }
   3611 
   3612 void SurfaceFlinger::dumpBufferingStats(String8& result) const {
   3613     result.append("Buffering stats:\n");
   3614     result.append("  [Layer name] <Active time> <Two buffer> "
   3615             "<Double buffered> <Triple buffered>\n");
   3616     Mutex::Autolock lock(mBufferingStatsMutex);
   3617     typedef std::tuple<std::string, float, float, float> BufferTuple;
   3618     std::map<float, BufferTuple, std::greater<float>> sorted;
   3619     for (const auto& statsPair : mBufferingStats) {
   3620         const char* name = statsPair.first.c_str();
   3621         const BufferingStats& stats = statsPair.second;
   3622         if (stats.numSegments == 0) {
   3623             continue;
   3624         }
   3625         float activeTime = ns2ms(stats.totalTime) / 1000.0f;
   3626         float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
   3627                 stats.totalTime;
   3628         float doubleBufferRatio = static_cast<float>(
   3629                 stats.doubleBufferedTime) / stats.totalTime;
   3630         float tripleBufferRatio = static_cast<float>(
   3631                 stats.tripleBufferedTime) / stats.totalTime;
   3632         sorted.insert({activeTime, {name, twoBufferRatio,
   3633                 doubleBufferRatio, tripleBufferRatio}});
   3634     }
   3635     for (const auto& sortedPair : sorted) {
   3636         float activeTime = sortedPair.first;
   3637         const BufferTuple& values = sortedPair.second;
   3638         result.appendFormat("  [%s] %.2f %.3f %.3f %.3f\n",
   3639                 std::get<0>(values).c_str(), activeTime,
   3640                 std::get<1>(values), std::get<2>(values),
   3641                 std::get<3>(values));
   3642     }
   3643     result.append("\n");
   3644 }
   3645 
   3646 void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
   3647     result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
   3648     result.appendFormat("forceNativeColorMode: %d\n", mForceNativeColorMode);
   3649 
   3650     // TODO: print out if wide-color mode is active or not
   3651 
   3652     for (size_t d = 0; d < mDisplays.size(); d++) {
   3653         const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
   3654         int32_t hwcId = displayDevice->getHwcDisplayId();
   3655         if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
   3656             continue;
   3657         }
   3658 
   3659         result.appendFormat("Display %d color modes:\n", hwcId);
   3660         std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
   3661         for (auto&& mode : modes) {
   3662             result.appendFormat("    %s (%d)\n", decodeColorMode(mode).c_str(), mode);
   3663         }
   3664 
   3665         android_color_mode_t currentMode = displayDevice->getActiveColorMode();
   3666         result.appendFormat("    Current color mode: %s (%d)\n",
   3667                             decodeColorMode(currentMode).c_str(), currentMode);
   3668     }
   3669     result.append("\n");
   3670 }
   3671 
   3672 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
   3673         String8& result) const
   3674 {
   3675     bool colorize = false;
   3676     if (index < args.size()
   3677             && (args[index] == String16("--color"))) {
   3678         colorize = true;
   3679         index++;
   3680     }
   3681 
   3682     Colorizer colorizer(colorize);
   3683 
   3684     // figure out if we're stuck somewhere
   3685     const nsecs_t now = systemTime();
   3686     const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
   3687     const nsecs_t inTransaction(mDebugInTransaction);
   3688     nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
   3689     nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
   3690 
   3691     /*
   3692      * Dump library configuration.
   3693      */
   3694 
   3695     colorizer.bold(result);
   3696     result.append("Build configuration:");
   3697     colorizer.reset(result);
   3698     appendSfConfigString(result);
   3699     appendUiConfigString(result);
   3700     appendGuiConfigString(result);
   3701     result.append("\n");
   3702 
   3703     result.append("\nWide-Color information:\n");
   3704     dumpWideColorInfo(result);
   3705 
   3706     colorizer.bold(result);
   3707     result.append("Sync configuration: ");
   3708     colorizer.reset(result);
   3709     result.append(SyncFeatures::getInstance().toString());
   3710     result.append("\n");
   3711 
   3712     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
   3713 
   3714     colorizer.bold(result);
   3715     result.append("DispSync configuration: ");
   3716     colorizer.reset(result);
   3717     result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
   3718             "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
   3719         vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
   3720         dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
   3721     result.append("\n");
   3722 
   3723     // Dump static screen stats
   3724     result.append("\n");
   3725     dumpStaticScreenStats(result);
   3726     result.append("\n");
   3727 
   3728     dumpBufferingStats(result);
   3729 
   3730     /*
   3731      * Dump the visible layer list
   3732      */
   3733     colorizer.bold(result);
   3734     result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
   3735     colorizer.reset(result);
   3736     mCurrentState.traverseInZOrder([&](Layer* layer) {
   3737         layer->dump(result, colorizer);
   3738     });
   3739 
   3740     /*
   3741      * Dump Display state
   3742      */
   3743 
   3744     colorizer.bold(result);
   3745     result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
   3746     colorizer.reset(result);
   3747     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
   3748         const sp<const DisplayDevice>& hw(mDisplays[dpy]);
   3749         hw->dump(result);
   3750     }
   3751 
   3752     /*
   3753      * Dump SurfaceFlinger global state
   3754      */
   3755 
   3756     colorizer.bold(result);
   3757     result.append("SurfaceFlinger global state:\n");
   3758     colorizer.reset(result);
   3759 
   3760     HWComposer& hwc(getHwComposer());
   3761     sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
   3762 
   3763     colorizer.bold(result);
   3764     result.appendFormat("EGL implementation : %s\n",
   3765             eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
   3766     colorizer.reset(result);
   3767     result.appendFormat("%s\n",
   3768             eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
   3769 
   3770     mRenderEngine->dump(result);
   3771 
   3772     hw->undefinedRegion.dump(result, "undefinedRegion");
   3773     result.appendFormat("  orientation=%d, isDisplayOn=%d\n",
   3774             hw->getOrientation(), hw->isDisplayOn());
   3775     result.appendFormat(
   3776             "  last eglSwapBuffers() time: %f us\n"
   3777             "  last transaction time     : %f us\n"
   3778             "  transaction-flags         : %08x\n"
   3779             "  refresh-rate              : %f fps\n"
   3780             "  x-dpi                     : %f\n"
   3781             "  y-dpi                     : %f\n"
   3782             "  gpu_to_cpu_unsupported    : %d\n"
   3783             ,
   3784             mLastSwapBufferTime/1000.0,
   3785             mLastTransactionTime/1000.0,
   3786             mTransactionFlags,
   3787             1e9 / activeConfig->getVsyncPeriod(),
   3788             activeConfig->getDpiX(),
   3789             activeConfig->getDpiY(),
   3790             !mGpuToCpuSupported);
   3791 
   3792     result.appendFormat("  eglSwapBuffers time: %f us\n",
   3793             inSwapBuffersDuration/1000.0);
   3794 
   3795     result.appendFormat("  transaction time: %f us\n",
   3796             inTransactionDuration/1000.0);
   3797 
   3798     /*
   3799      * VSYNC state
   3800      */
   3801     mEventThread->dump(result);
   3802     result.append("\n");
   3803 
   3804     /*
   3805      * HWC layer minidump
   3806      */
   3807     for (size_t d = 0; d < mDisplays.size(); d++) {
   3808         const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
   3809         int32_t hwcId = displayDevice->getHwcDisplayId();
   3810         if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
   3811             continue;
   3812         }
   3813 
   3814         result.appendFormat("Display %d HWC layers:\n", hwcId);
   3815         Layer::miniDumpHeader(result);
   3816         mCurrentState.traverseInZOrder([&](Layer* layer) {
   3817             layer->miniDump(result, hwcId);
   3818         });
   3819         result.append("\n");
   3820     }
   3821 
   3822     /*
   3823      * Dump HWComposer state
   3824      */
   3825     colorizer.bold(result);
   3826     result.append("h/w composer state:\n");
   3827     colorizer.reset(result);
   3828     bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
   3829     result.appendFormat("  h/w composer %s\n",
   3830             hwcDisabled ? "disabled" : "enabled");
   3831     hwc.dump(result);
   3832 
   3833     /*
   3834      * Dump gralloc state
   3835      */
   3836     const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
   3837     alloc.dump(result);
   3838 
   3839     /*
   3840      * Dump VrFlinger state if in use.
   3841      */
   3842     if (mVrFlingerRequestsDisplay && mVrFlinger) {
   3843         result.append("VrFlinger state:\n");
   3844         result.append(mVrFlinger->Dump().c_str());
   3845         result.append("\n");
   3846     }
   3847 }
   3848 
   3849 const Vector< sp<Layer> >&
   3850 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
   3851     // Note: mStateLock is held here
   3852     wp<IBinder> dpy;
   3853     for (size_t i=0 ; i<mDisplays.size() ; i++) {
   3854         if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
   3855             dpy = mDisplays.keyAt(i);
   3856             break;
   3857         }
   3858     }
   3859     if (dpy == NULL) {
   3860         ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
   3861         // Just use the primary display so we have something to return
   3862         dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
   3863     }
   3864     return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
   3865 }
   3866 
   3867 bool SurfaceFlinger::startDdmConnection()
   3868 {
   3869     void* libddmconnection_dso =
   3870             dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
   3871     if (!libddmconnection_dso) {
   3872         return false;
   3873     }
   3874     void (*DdmConnection_start)(const char* name);
   3875     DdmConnection_start =
   3876             (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
   3877     if (!DdmConnection_start) {
   3878         dlclose(libddmconnection_dso);
   3879         return false;
   3880     }
   3881     (*DdmConnection_start)(getServiceName());
   3882     return true;
   3883 }
   3884 
   3885 status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
   3886     switch (code) {
   3887         case CREATE_CONNECTION:
   3888         case CREATE_DISPLAY:
   3889         case BOOT_FINISHED:
   3890         case CLEAR_ANIMATION_FRAME_STATS:
   3891         case GET_ANIMATION_FRAME_STATS:
   3892         case SET_POWER_MODE:
   3893         case GET_HDR_CAPABILITIES:
   3894         {
   3895             // codes that require permission check
   3896             IPCThreadState* ipc = IPCThreadState::self();
   3897             const int pid = ipc->getCallingPid();
   3898             const int uid = ipc->getCallingUid();
   3899             if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
   3900                     !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
   3901                 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
   3902                 return PERMISSION_DENIED;
   3903             }
   3904             break;
   3905         }
   3906         /*
   3907          * Calling setTransactionState is safe, because you need to have been
   3908          * granted a reference to Client* and Handle* to do anything with it.
   3909          *
   3910          * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
   3911          */
   3912         case SET_TRANSACTION_STATE:
   3913         case CREATE_SCOPED_CONNECTION:
   3914         {
   3915             return OK;
   3916         }
   3917         case CAPTURE_SCREEN:
   3918         {
   3919             // codes that require permission check
   3920             IPCThreadState* ipc = IPCThreadState::self();
   3921             const int pid = ipc->getCallingPid();
   3922             const int uid = ipc->getCallingUid();
   3923             if ((uid != AID_GRAPHICS) &&
   3924                     !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
   3925                 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
   3926                 return PERMISSION_DENIED;
   3927             }
   3928             break;
   3929         }
   3930     }
   3931     return OK;
   3932 }
   3933 
   3934 status_t SurfaceFlinger::onTransact(
   3935     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
   3936 {
   3937     status_t credentialCheck = CheckTransactCodeCredentials(code);
   3938     if (credentialCheck != OK) {
   3939         return credentialCheck;
   3940     }
   3941 
   3942     status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
   3943     if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
   3944         CHECK_INTERFACE(ISurfaceComposer, data, reply);
   3945         IPCThreadState* ipc = IPCThreadState::self();
   3946         const int uid = ipc->getCallingUid();
   3947         if (CC_UNLIKELY(uid != AID_SYSTEM
   3948                 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
   3949             const int pid = ipc->getCallingPid();
   3950             ALOGE("Permission Denial: "
   3951                     "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
   3952             return PERMISSION_DENIED;
   3953         }
   3954         int n;
   3955         switch (code) {
   3956             case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
   3957             case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
   3958                 return NO_ERROR;
   3959             case 1002:  // SHOW_UPDATES
   3960                 n = data.readInt32();
   3961                 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
   3962                 invalidateHwcGeometry();
   3963                 repaintEverything();
   3964                 return NO_ERROR;
   3965             case 1004:{ // repaint everything
   3966                 repaintEverything();
   3967                 return NO_ERROR;
   3968             }
   3969             case 1005:{ // force transaction
   3970                 Mutex::Autolock _l(mStateLock);
   3971                 setTransactionFlags(
   3972                         eTransactionNeeded|
   3973                         eDisplayTransactionNeeded|
   3974                         eTraversalNeeded);
   3975                 return NO_ERROR;
   3976             }
   3977             case 1006:{ // send empty update
   3978                 signalRefresh();
   3979                 return NO_ERROR;
   3980             }
   3981             case 1008:  // toggle use of hw composer
   3982                 n = data.readInt32();
   3983                 mDebugDisableHWC = n ? 1 : 0;
   3984                 invalidateHwcGeometry();
   3985                 repaintEverything();
   3986                 return NO_ERROR;
   3987             case 1009:  // toggle use of transform hint
   3988                 n = data.readInt32();
   3989                 mDebugDisableTransformHint = n ? 1 : 0;
   3990                 invalidateHwcGeometry();
   3991                 repaintEverything();
   3992                 return NO_ERROR;
   3993             case 1010:  // interrogate.
   3994                 reply->writeInt32(0);
   3995                 reply->writeInt32(0);
   3996                 reply->writeInt32(mDebugRegion);
   3997                 reply->writeInt32(0);
   3998                 reply->writeInt32(mDebugDisableHWC);
   3999                 return NO_ERROR;
   4000             case 1013: {
   4001                 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
   4002                 reply->writeInt32(hw->getPageFlipCount());
   4003                 return NO_ERROR;
   4004             }
   4005             case 1014: {
   4006                 // daltonize
   4007                 n = data.readInt32();
   4008                 switch (n % 10) {
   4009                     case 1:
   4010                         mDaltonizer.setType(ColorBlindnessType::Protanomaly);
   4011                         break;
   4012                     case 2:
   4013                         mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
   4014                         break;
   4015                     case 3:
   4016                         mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
   4017                         break;
   4018                     default:
   4019                         mDaltonizer.setType(ColorBlindnessType::None);
   4020                         break;
   4021                 }
   4022                 if (n >= 10) {
   4023                     mDaltonizer.setMode(ColorBlindnessMode::Correction);
   4024                 } else {
   4025                     mDaltonizer.setMode(ColorBlindnessMode::Simulation);
   4026                 }
   4027                 invalidateHwcGeometry();
   4028                 repaintEverything();
   4029                 return NO_ERROR;
   4030             }
   4031             case 1015: {
   4032                 // apply a color matrix
   4033                 n = data.readInt32();
   4034                 if (n) {
   4035                     // color matrix is sent as a column-major mat4 matrix
   4036                     for (size_t i = 0 ; i < 4; i++) {
   4037                         for (size_t j = 0; j < 4; j++) {
   4038                             mColorMatrix[i][j] = data.readFloat();
   4039                         }
   4040                     }
   4041                 } else {
   4042                     mColorMatrix = mat4();
   4043                 }
   4044 
   4045                 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
   4046                 // the division by w in the fragment shader
   4047                 float4 lastRow(transpose(mColorMatrix)[3]);
   4048                 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
   4049                     ALOGE("The color transform's last row must be (0, 0, 0, 1)");
   4050                 }
   4051 
   4052                 invalidateHwcGeometry();
   4053                 repaintEverything();
   4054                 return NO_ERROR;
   4055             }
   4056             // This is an experimental interface
   4057             // Needs to be shifted to proper binder interface when we productize
   4058             case 1016: {
   4059                 n = data.readInt32();
   4060                 mPrimaryDispSync.setRefreshSkipCount(n);
   4061                 return NO_ERROR;
   4062             }
   4063             case 1017: {
   4064                 n = data.readInt32();
   4065                 mForceFullDamage = static_cast<bool>(n);
   4066                 return NO_ERROR;
   4067             }
   4068             case 1018: { // Modify Choreographer's phase offset
   4069                 n = data.readInt32();
   4070                 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
   4071                 return NO_ERROR;
   4072             }
   4073             case 1019: { // Modify SurfaceFlinger's phase offset
   4074                 n = data.readInt32();
   4075                 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
   4076                 return NO_ERROR;
   4077             }
   4078             case 1020: { // Layer updates interceptor
   4079                 n = data.readInt32();
   4080                 if (n) {
   4081                     ALOGV("Interceptor enabled");
   4082                     mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
   4083                 }
   4084                 else{
   4085                     ALOGV("Interceptor disabled");
   4086                     mInterceptor.disable();
   4087                 }
   4088                 return NO_ERROR;
   4089             }
   4090             case 1021: { // Disable HWC virtual displays
   4091                 n = data.readInt32();
   4092                 mUseHwcVirtualDisplays = !n;
   4093                 return NO_ERROR;
   4094             }
   4095             case 1022: { // Set saturation boost
   4096                 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
   4097 
   4098                 invalidateHwcGeometry();
   4099                 repaintEverything();
   4100                 return NO_ERROR;
   4101             }
   4102             case 1023: { // Set native mode
   4103                 mForceNativeColorMode = data.readInt32() == 1;
   4104 
   4105                 invalidateHwcGeometry();
   4106                 repaintEverything();
   4107                 return NO_ERROR;
   4108             }
   4109             case 1024: { // Is wide color gamut rendering/color management supported?
   4110                 reply->writeBool(hasWideColorDisplay);
   4111                 return NO_ERROR;
   4112             }
   4113         }
   4114     }
   4115     return err;
   4116 }
   4117 
   4118 void SurfaceFlinger::repaintEverythingLocked() {
   4119     android_atomic_or(1, &mRepaintEverything);
   4120     signalTransaction();
   4121 }
   4122 
   4123 void SurfaceFlinger::repaintEverything() {
   4124     ConditionalLock _l(mStateLock,
   4125             std::this_thread::get_id() != mMainThreadId);
   4126     repaintEverythingLocked();
   4127 }
   4128 
   4129 // Checks that the requested width and height are valid and updates them to the display dimensions
   4130 // if they are set to 0
   4131 static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
   4132                                        Transform::orientation_flags rotation,
   4133                                        uint32_t* requestedWidth, uint32_t* requestedHeight) {
   4134     // get screen geometry
   4135     uint32_t displayWidth = displayDevice->getWidth();
   4136     uint32_t displayHeight = displayDevice->getHeight();
   4137 
   4138     if (rotation & Transform::ROT_90) {
   4139         std::swap(displayWidth, displayHeight);
   4140     }
   4141 
   4142     if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
   4143         ALOGE("size mismatch (%d, %d) > (%d, %d)",
   4144                 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
   4145         return BAD_VALUE;
   4146     }
   4147 
   4148     if (*requestedWidth == 0) {
   4149         *requestedWidth = displayWidth;
   4150     }
   4151     if (*requestedHeight == 0) {
   4152         *requestedHeight = displayHeight;
   4153     }
   4154 
   4155     return NO_ERROR;
   4156 }
   4157 
   4158 // A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
   4159 class WindowDisconnector {
   4160 public:
   4161     WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
   4162     ~WindowDisconnector() {
   4163         native_window_api_disconnect(mWindow, mApi);
   4164     }
   4165 
   4166 private:
   4167     ANativeWindow* mWindow;
   4168     const int mApi;
   4169 };
   4170 
   4171 static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
   4172                                 uint32_t requestedHeight, bool hasWideColorDisplay,
   4173                                 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
   4174     const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
   4175             GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
   4176 
   4177     int err = 0;
   4178     err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
   4179     err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
   4180     err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
   4181     err |= native_window_set_usage(window, usage);
   4182 
   4183     if (hasWideColorDisplay) {
   4184         err |= native_window_set_buffers_data_space(window,
   4185                                                     renderEngineUsesWideColor
   4186                                                             ? HAL_DATASPACE_DISPLAY_P3
   4187                                                             : HAL_DATASPACE_V0_SRGB);
   4188     }
   4189 
   4190     if (err != NO_ERROR) {
   4191         return BAD_VALUE;
   4192     }
   4193 
   4194     /* TODO: Once we have the sync framework everywhere this can use
   4195      * server-side waits on the fence that dequeueBuffer returns.
   4196      */
   4197     err = native_window_dequeue_buffer_and_wait(window, outBuffer);
   4198     if (err != NO_ERROR) {
   4199         return err;
   4200     }
   4201 
   4202     return NO_ERROR;
   4203 }
   4204 
   4205 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
   4206         const sp<IGraphicBufferProducer>& producer,
   4207         Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
   4208         int32_t minLayerZ, int32_t maxLayerZ,
   4209         bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
   4210     ATRACE_CALL();
   4211 
   4212     if (CC_UNLIKELY(display == 0))
   4213         return BAD_VALUE;
   4214 
   4215     if (CC_UNLIKELY(producer == 0))
   4216         return BAD_VALUE;
   4217 
   4218     // if we have secure windows on this display, never allow the screen capture
   4219     // unless the producer interface is local (i.e.: we can take a screenshot for
   4220     // ourselves).
   4221     bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
   4222 
   4223     // Convert to surfaceflinger's internal rotation type.
   4224     Transform::orientation_flags rotationFlags;
   4225     switch (rotation) {
   4226         case ISurfaceComposer::eRotateNone:
   4227             rotationFlags = Transform::ROT_0;
   4228             break;
   4229         case ISurfaceComposer::eRotate90:
   4230             rotationFlags = Transform::ROT_90;
   4231             break;
   4232         case ISurfaceComposer::eRotate180:
   4233             rotationFlags = Transform::ROT_180;
   4234             break;
   4235         case ISurfaceComposer::eRotate270:
   4236             rotationFlags = Transform::ROT_270;
   4237             break;
   4238         default:
   4239             rotationFlags = Transform::ROT_0;
   4240             ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
   4241             break;
   4242     }
   4243 
   4244     { // Autolock scope
   4245         Mutex::Autolock lock(mStateLock);
   4246         sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
   4247         updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
   4248     }
   4249 
   4250     // create a surface (because we're a producer, and we need to
   4251     // dequeue/queue a buffer)
   4252     sp<Surface> surface = new Surface(producer, false);
   4253 
   4254     // Put the screenshot Surface into async mode so that
   4255     // Layer::headFenceHasSignaled will always return true and we'll latch the
   4256     // first buffer regardless of whether or not its acquire fence has
   4257     // signaled. This is needed to avoid a race condition in the rotation
   4258     // animation. See b/30209608
   4259     surface->setAsyncMode(true);
   4260 
   4261     ANativeWindow* window = surface.get();
   4262 
   4263     status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
   4264     if (result != NO_ERROR) {
   4265         return result;
   4266     }
   4267     WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
   4268 
   4269     ANativeWindowBuffer* buffer = nullptr;
   4270     result = getWindowBuffer(window, reqWidth, reqHeight,
   4271             hasWideColorDisplay && !mForceNativeColorMode,
   4272             getRenderEngine().usesWideColor(), &buffer);
   4273     if (result != NO_ERROR) {
   4274         return result;
   4275     }
   4276 
   4277     // This mutex protects syncFd and captureResult for communication of the return values from the
   4278     // main thread back to this Binder thread
   4279     std::mutex captureMutex;
   4280     std::condition_variable captureCondition;
   4281     std::unique_lock<std::mutex> captureLock(captureMutex);
   4282     int syncFd = -1;
   4283     std::optional<status_t> captureResult;
   4284 
   4285     sp<LambdaMessage> message = new LambdaMessage([&]() {
   4286         // If there is a refresh pending, bug out early and tell the binder thread to try again
   4287         // after the refresh.
   4288         if (mRefreshPending) {
   4289             ATRACE_NAME("Skipping screenshot for now");
   4290             std::unique_lock<std::mutex> captureLock(captureMutex);
   4291             captureResult = std::make_optional<status_t>(EAGAIN);
   4292             captureCondition.notify_one();
   4293             return;
   4294         }
   4295 
   4296         status_t result = NO_ERROR;
   4297         int fd = -1;
   4298         {
   4299             Mutex::Autolock _l(mStateLock);
   4300             sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
   4301             result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
   4302                                              minLayerZ, maxLayerZ, useIdentityTransform,
   4303                                              rotationFlags, isLocalScreenshot, &fd);
   4304         }
   4305 
   4306         {
   4307             std::unique_lock<std::mutex> captureLock(captureMutex);
   4308             syncFd = fd;
   4309             captureResult = std::make_optional<status_t>(result);
   4310             captureCondition.notify_one();
   4311         }
   4312     });
   4313 
   4314     result = postMessageAsync(message);
   4315     if (result == NO_ERROR) {
   4316         captureCondition.wait(captureLock, [&]() { return captureResult; });
   4317         while (*captureResult == EAGAIN) {
   4318             captureResult.reset();
   4319             result = postMessageAsync(message);
   4320             if (result != NO_ERROR) {
   4321                 return result;
   4322             }
   4323             captureCondition.wait(captureLock, [&]() { return captureResult; });
   4324         }
   4325         result = *captureResult;
   4326     }
   4327 
   4328     if (result == NO_ERROR) {
   4329         // queueBuffer takes ownership of syncFd
   4330         result = window->queueBuffer(window, buffer, syncFd);
   4331     }
   4332 
   4333     return result;
   4334 }
   4335 
   4336 
   4337 void SurfaceFlinger::renderScreenImplLocked(
   4338         const sp<const DisplayDevice>& hw,
   4339         Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
   4340         int32_t minLayerZ, int32_t maxLayerZ,
   4341         bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
   4342 {
   4343     ATRACE_CALL();
   4344     RenderEngine& engine(getRenderEngine());
   4345 
   4346     // get screen geometry
   4347     const int32_t hw_w = hw->getWidth();
   4348     const int32_t hw_h = hw->getHeight();
   4349     const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
   4350                            static_cast<int32_t>(reqHeight) != hw_h;
   4351 
   4352     // if a default or invalid sourceCrop is passed in, set reasonable values
   4353     if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
   4354             !sourceCrop.isValid()) {
   4355         sourceCrop.setLeftTop(Point(0, 0));
   4356         sourceCrop.setRightBottom(Point(hw_w, hw_h));
   4357     }
   4358 
   4359     // ensure that sourceCrop is inside screen
   4360     if (sourceCrop.left < 0) {
   4361         ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
   4362     }
   4363     if (sourceCrop.right > hw_w) {
   4364         ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
   4365     }
   4366     if (sourceCrop.top < 0) {
   4367         ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
   4368     }
   4369     if (sourceCrop.bottom > hw_h) {
   4370         ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
   4371     }
   4372 
   4373 #ifdef USE_HWC2
   4374      engine.setWideColor(hw->getWideColorSupport() && !mForceNativeColorMode);
   4375      engine.setColorMode(mForceNativeColorMode ? HAL_COLOR_MODE_NATIVE : hw->getActiveColorMode());
   4376 #endif
   4377 
   4378     // make sure to clear all GL error flags
   4379     engine.checkErrors();
   4380 
   4381     // set-up our viewport
   4382     engine.setViewportAndProjection(
   4383         reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
   4384     engine.disableTexturing();
   4385 
   4386     // redraw the screen entirely...
   4387     engine.clearWithColor(0, 0, 0, 1);
   4388 
   4389     // We loop through the first level of layers without traversing,
   4390     // as we need to interpret min/max layer Z in the top level Z space.
   4391     for (const auto& layer : mDrawingState.layersSortedByZ) {
   4392         if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
   4393             continue;
   4394         }
   4395         const Layer::State& state(layer->getDrawingState());
   4396         if (state.z < minLayerZ || state.z > maxLayerZ) {
   4397             continue;
   4398         }
   4399         layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
   4400             if (!layer->isVisible()) {
   4401                 return;
   4402             }
   4403             if (filtering) layer->setFiltering(true);
   4404             layer->draw(hw, useIdentityTransform);
   4405             if (filtering) layer->setFiltering(false);
   4406         });
   4407     }
   4408 
   4409     hw->setViewportAndProjection();
   4410 }
   4411 
   4412 // A simple RAII class that holds an EGLImage and destroys it either:
   4413 //   a) When the destroy() method is called
   4414 //   b) When the object goes out of scope
   4415 class ImageHolder {
   4416 public:
   4417     ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
   4418     ~ImageHolder() { destroy(); }
   4419 
   4420     void destroy() {
   4421         if (mImage != EGL_NO_IMAGE_KHR) {
   4422             eglDestroyImageKHR(mDisplay, mImage);
   4423             mImage = EGL_NO_IMAGE_KHR;
   4424         }
   4425     }
   4426 
   4427 private:
   4428     const EGLDisplay mDisplay;
   4429     EGLImageKHR mImage;
   4430 };
   4431 
   4432 status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
   4433                                                  ANativeWindowBuffer* buffer, Rect sourceCrop,
   4434                                                  uint32_t reqWidth, uint32_t reqHeight,
   4435                                                  int32_t minLayerZ, int32_t maxLayerZ,
   4436                                                  bool useIdentityTransform,
   4437                                                  Transform::orientation_flags rotation,
   4438                                                  bool isLocalScreenshot, int* outSyncFd) {
   4439     ATRACE_CALL();
   4440 
   4441     bool secureLayerIsVisible = false;
   4442     for (const auto& layer : mDrawingState.layersSortedByZ) {
   4443         const Layer::State& state(layer->getDrawingState());
   4444         if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
   4445                 (state.z < minLayerZ || state.z > maxLayerZ)) {
   4446             continue;
   4447         }
   4448         layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
   4449             secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
   4450                     layer->isSecure());
   4451         });
   4452     }
   4453 
   4454     if (!isLocalScreenshot && secureLayerIsVisible) {
   4455         ALOGW("FB is protected: PERMISSION_DENIED");
   4456         return PERMISSION_DENIED;
   4457     }
   4458 
   4459     int syncFd = -1;
   4460     // create an EGLImage from the buffer so we can later
   4461     // turn it into a texture
   4462     EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
   4463             EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
   4464     if (image == EGL_NO_IMAGE_KHR) {
   4465         return BAD_VALUE;
   4466     }
   4467 
   4468     // This will automatically destroy the image if we return before calling its destroy method
   4469     ImageHolder imageHolder(mEGLDisplay, image);
   4470 
   4471     // this binds the given EGLImage as a framebuffer for the
   4472     // duration of this scope.
   4473     RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
   4474     if (imageBond.getStatus() != NO_ERROR) {
   4475         ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
   4476         return INVALID_OPERATION;
   4477     }
   4478 
   4479     // this will in fact render into our dequeued buffer
   4480     // via an FBO, which means we didn't have to create
   4481     // an EGLSurface and therefore we're not
   4482     // dependent on the context's EGLConfig.
   4483     renderScreenImplLocked(
   4484         hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
   4485         useIdentityTransform, rotation);
   4486 
   4487     // Attempt to create a sync khr object that can produce a sync point. If that
   4488     // isn't available, create a non-dupable sync object in the fallback path and
   4489     // wait on it directly.
   4490     EGLSyncKHR sync = EGL_NO_SYNC_KHR;
   4491     if (!DEBUG_SCREENSHOTS) {
   4492        sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
   4493        // native fence fd will not be populated until flush() is done.
   4494        getRenderEngine().flush();
   4495     }
   4496 
   4497     if (sync != EGL_NO_SYNC_KHR) {
   4498         // get the sync fd
   4499         syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
   4500         if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
   4501             ALOGW("captureScreen: failed to dup sync khr object");
   4502             syncFd = -1;
   4503         }
   4504         eglDestroySyncKHR(mEGLDisplay, sync);
   4505     } else {
   4506         // fallback path
   4507         sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
   4508         if (sync != EGL_NO_SYNC_KHR) {
   4509             EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
   4510                 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
   4511             EGLint eglErr = eglGetError();
   4512             if (result == EGL_TIMEOUT_EXPIRED_KHR) {
   4513                 ALOGW("captureScreen: fence wait timed out");
   4514             } else {
   4515                 ALOGW_IF(eglErr != EGL_SUCCESS,
   4516                         "captureScreen: error waiting on EGL fence: %#x", eglErr);
   4517             }
   4518             eglDestroySyncKHR(mEGLDisplay, sync);
   4519         } else {
   4520             ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
   4521         }
   4522     }
   4523     *outSyncFd = syncFd;
   4524 
   4525     if (DEBUG_SCREENSHOTS) {
   4526         uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
   4527         getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
   4528         checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
   4529                 hw, minLayerZ, maxLayerZ);
   4530         delete [] pixels;
   4531     }
   4532 
   4533     // destroy our image
   4534     imageHolder.destroy();
   4535 
   4536     return NO_ERROR;
   4537 }
   4538 
   4539 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
   4540         const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
   4541     if (DEBUG_SCREENSHOTS) {
   4542         for (size_t y=0 ; y<h ; y++) {
   4543             uint32_t const * p = (uint32_t const *)vaddr + y*s;
   4544             for (size_t x=0 ; x<w ; x++) {
   4545                 if (p[x] != 0xFF000000) return;
   4546             }
   4547         }
   4548         ALOGE("*** we just took a black screenshot ***\n"
   4549                 "requested minz=%d, maxz=%d, layerStack=%d",
   4550                 minLayerZ, maxLayerZ, hw->getLayerStack());
   4551 
   4552         size_t i = 0;
   4553         for (const auto& layer : mDrawingState.layersSortedByZ) {
   4554             const Layer::State& state(layer->getDrawingState());
   4555             if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
   4556                     state.z <= maxLayerZ) {
   4557                 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
   4558                     ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
   4559                             layer->isVisible() ? '+' : '-',
   4560                             i, layer->getName().string(), layer->getLayerStack(), state.z,
   4561                             layer->isVisible(), state.flags, state.alpha);
   4562                     i++;
   4563                 });
   4564             }
   4565         }
   4566     }
   4567 }
   4568 
   4569 // ---------------------------------------------------------------------------
   4570 
   4571 void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
   4572     layersSortedByZ.traverseInZOrder(stateSet, visitor);
   4573 }
   4574 
   4575 void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
   4576     layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
   4577 }
   4578 
   4579 }; // namespace android
   4580 
   4581 
   4582 #if defined(__gl_h_)
   4583 #error "don't include gl/gl.h in this file"
   4584 #endif
   4585 
   4586 #if defined(__gl2_h_)
   4587 #error "don't include gl2/gl2.h in this file"
   4588 #endif
   4589