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