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 <errno.h>
     23 #include <math.h>
     24 #include <dlfcn.h>
     25 #include <inttypes.h>
     26 #include <stdatomic.h>
     27 
     28 #include <EGL/egl.h>
     29 
     30 #include <cutils/log.h>
     31 #include <cutils/properties.h>
     32 
     33 #include <binder/IPCThreadState.h>
     34 #include <binder/IServiceManager.h>
     35 #include <binder/MemoryHeapBase.h>
     36 #include <binder/PermissionCache.h>
     37 
     38 #include <ui/DisplayInfo.h>
     39 #include <ui/DisplayStatInfo.h>
     40 
     41 #include <gui/BitTube.h>
     42 #include <gui/BufferQueue.h>
     43 #include <gui/GuiConfig.h>
     44 #include <gui/IDisplayEventConnection.h>
     45 #include <gui/Surface.h>
     46 #include <gui/GraphicBufferAlloc.h>
     47 
     48 #include <ui/GraphicBufferAllocator.h>
     49 #include <ui/PixelFormat.h>
     50 #include <ui/UiConfig.h>
     51 
     52 #include <utils/misc.h>
     53 #include <utils/String8.h>
     54 #include <utils/String16.h>
     55 #include <utils/StopWatch.h>
     56 #include <utils/Timers.h>
     57 #include <utils/Trace.h>
     58 
     59 #include <private/android_filesystem_config.h>
     60 #include <private/gui/SyncFeatures.h>
     61 
     62 #include "Client.h"
     63 #include "clz.h"
     64 #include "Colorizer.h"
     65 #include "DdmConnection.h"
     66 #include "DisplayDevice.h"
     67 #include "DispSync.h"
     68 #include "EventControlThread.h"
     69 #include "EventThread.h"
     70 #include "Layer.h"
     71 #include "LayerDim.h"
     72 #include "SurfaceFlinger.h"
     73 
     74 #include "DisplayHardware/FramebufferSurface.h"
     75 #include "DisplayHardware/HWComposer.h"
     76 #include "DisplayHardware/VirtualDisplaySurface.h"
     77 
     78 #include "Effects/Daltonizer.h"
     79 
     80 #include "RenderEngine/RenderEngine.h"
     81 #include <cutils/compiler.h>
     82 
     83 #define DISPLAY_COUNT       1
     84 
     85 /*
     86  * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
     87  * black pixels.
     88  */
     89 #define DEBUG_SCREENSHOTS   false
     90 
     91 EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
     92 
     93 namespace android {
     94 
     95 // This is the phase offset in nanoseconds of the software vsync event
     96 // relative to the vsync event reported by HWComposer.  The software vsync
     97 // event is when SurfaceFlinger and Choreographer-based applications run each
     98 // frame.
     99 //
    100 // This phase offset allows adjustment of the minimum latency from application
    101 // wake-up (by Choregographer) time to the time at which the resulting window
    102 // image is displayed.  This value may be either positive (after the HW vsync)
    103 // or negative (before the HW vsync).  Setting it to 0 will result in a
    104 // minimum latency of two vsync periods because the app and SurfaceFlinger
    105 // will run just after the HW vsync.  Setting it to a positive number will
    106 // result in the minimum latency being:
    107 //
    108 //     (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
    109 //
    110 // Note that reducing this latency makes it more likely for the applications
    111 // to not have their window content image ready in time.  When this happens
    112 // the latency will end up being an additional vsync period, and animations
    113 // will hiccup.  Therefore, this latency should be tuned somewhat
    114 // conservatively (or at least with awareness of the trade-off being made).
    115 static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
    116 
    117 // This is the phase offset at which SurfaceFlinger's composition runs.
    118 static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
    119 
    120 // ---------------------------------------------------------------------------
    121 
    122 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
    123 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
    124 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
    125 const String16 sDump("android.permission.DUMP");
    126 
    127 // ---------------------------------------------------------------------------
    128 
    129 SurfaceFlinger::SurfaceFlinger()
    130     :   BnSurfaceComposer(),
    131         mTransactionFlags(0),
    132         mTransactionPending(false),
    133         mAnimTransactionPending(false),
    134         mLayersRemoved(false),
    135         mRepaintEverything(0),
    136         mRenderEngine(NULL),
    137         mBootTime(systemTime()),
    138         mBuiltinDisplays(),
    139         mVisibleRegionsDirty(false),
    140         mGeometryInvalid(false),
    141         mAnimCompositionPending(false),
    142         mDebugRegion(0),
    143         mDebugDDMS(0),
    144         mDebugDisableHWC(0),
    145         mDebugDisableTransformHint(0),
    146         mDebugInSwapBuffers(0),
    147         mLastSwapBufferTime(0),
    148         mDebugInTransaction(0),
    149         mLastTransactionTime(0),
    150         mBootFinished(false),
    151         mForceFullDamage(false),
    152         mPrimaryDispSync("PrimaryDispSync"),
    153         mPrimaryHWVsyncEnabled(false),
    154         mHWVsyncAvailable(false),
    155         mDaltonize(false),
    156         mHasColorMatrix(false),
    157         mHasPoweredOff(false),
    158         mFrameBuckets(),
    159         mTotalTime(0),
    160         mLastSwapTime(0)
    161 {
    162     ALOGI("SurfaceFlinger is starting");
    163 
    164     // debugging stuff...
    165     char value[PROPERTY_VALUE_MAX];
    166 
    167     property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
    168     mGpuToCpuSupported = !atoi(value);
    169 
    170     property_get("debug.sf.drop_missed_frames", value, "0");
    171     mDropMissedFrames = atoi(value);
    172 
    173     property_get("debug.sf.showupdates", value, "0");
    174     mDebugRegion = atoi(value);
    175 
    176     property_get("debug.sf.ddms", value, "0");
    177     mDebugDDMS = atoi(value);
    178     if (mDebugDDMS) {
    179         if (!startDdmConnection()) {
    180             // start failed, and DDMS debugging not enabled
    181             mDebugDDMS = 0;
    182         }
    183     }
    184     ALOGI_IF(mDebugRegion, "showupdates enabled");
    185     ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
    186 }
    187 
    188 void SurfaceFlinger::onFirstRef()
    189 {
    190     mEventQueue.init(this);
    191 }
    192 
    193 SurfaceFlinger::~SurfaceFlinger()
    194 {
    195     EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    196     eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
    197     eglTerminate(display);
    198 }
    199 
    200 void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
    201 {
    202     // the window manager died on us. prepare its eulogy.
    203 
    204     // restore initial conditions (default device unblank, etc)
    205     initializeDisplays();
    206 
    207     // restart the boot-animation
    208     startBootAnim();
    209 }
    210 
    211 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
    212 {
    213     sp<ISurfaceComposerClient> bclient;
    214     sp<Client> client(new Client(this));
    215     status_t err = client->initCheck();
    216     if (err == NO_ERROR) {
    217         bclient = client;
    218     }
    219     return bclient;
    220 }
    221 
    222 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
    223         bool secure)
    224 {
    225     class DisplayToken : public BBinder {
    226         sp<SurfaceFlinger> flinger;
    227         virtual ~DisplayToken() {
    228              // no more references, this display must be terminated
    229              Mutex::Autolock _l(flinger->mStateLock);
    230              flinger->mCurrentState.displays.removeItem(this);
    231              flinger->setTransactionFlags(eDisplayTransactionNeeded);
    232          }
    233      public:
    234         DisplayToken(const sp<SurfaceFlinger>& flinger)
    235             : flinger(flinger) {
    236         }
    237     };
    238 
    239     sp<BBinder> token = new DisplayToken(this);
    240 
    241     Mutex::Autolock _l(mStateLock);
    242     DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
    243     info.displayName = displayName;
    244     mCurrentState.displays.add(token, info);
    245 
    246     return token;
    247 }
    248 
    249 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
    250     Mutex::Autolock _l(mStateLock);
    251 
    252     ssize_t idx = mCurrentState.displays.indexOfKey(display);
    253     if (idx < 0) {
    254         ALOGW("destroyDisplay: invalid display token");
    255         return;
    256     }
    257 
    258     const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
    259     if (!info.isVirtualDisplay()) {
    260         ALOGE("destroyDisplay called for non-virtual display");
    261         return;
    262     }
    263 
    264     mCurrentState.displays.removeItemsAt(idx);
    265     setTransactionFlags(eDisplayTransactionNeeded);
    266 }
    267 
    268 void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
    269     ALOGV("createBuiltinDisplayLocked(%d)", type);
    270     ALOGW_IF(mBuiltinDisplays[type],
    271             "Overwriting display token for display type %d", type);
    272     mBuiltinDisplays[type] = new BBinder();
    273     // All non-virtual displays are currently considered secure.
    274     DisplayDeviceState info(type, true);
    275     mCurrentState.displays.add(mBuiltinDisplays[type], info);
    276 }
    277 
    278 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
    279     if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
    280         ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
    281         return NULL;
    282     }
    283     return mBuiltinDisplays[id];
    284 }
    285 
    286 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
    287 {
    288     sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
    289     return gba;
    290 }
    291 
    292 void SurfaceFlinger::bootFinished()
    293 {
    294     const nsecs_t now = systemTime();
    295     const nsecs_t duration = now - mBootTime;
    296     ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
    297     mBootFinished = true;
    298 
    299     // wait patiently for the window manager death
    300     const String16 name("window");
    301     sp<IBinder> window(defaultServiceManager()->getService(name));
    302     if (window != 0) {
    303         window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
    304     }
    305 
    306     // stop boot animation
    307     // formerly we would just kill the process, but we now ask it to exit so it
    308     // can choose where to stop the animation.
    309     property_set("service.bootanim.exit", "1");
    310 
    311     const int LOGTAG_SF_STOP_BOOTANIM = 60110;
    312     LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
    313                    ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
    314 }
    315 
    316 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
    317     class MessageDestroyGLTexture : public MessageBase {
    318         RenderEngine& engine;
    319         uint32_t texture;
    320     public:
    321         MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
    322             : engine(engine), texture(texture) {
    323         }
    324         virtual bool handler() {
    325             engine.deleteTextures(1, &texture);
    326             return true;
    327         }
    328     };
    329     postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
    330 }
    331 
    332 class DispSyncSource : public VSyncSource, private DispSync::Callback {
    333 public:
    334     DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
    335         const char* name) :
    336             mName(name),
    337             mValue(0),
    338             mTraceVsync(traceVsync),
    339             mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
    340             mVsyncEventLabel(String8::format("VSYNC-%s", name)),
    341             mDispSync(dispSync),
    342             mCallbackMutex(),
    343             mCallback(),
    344             mVsyncMutex(),
    345             mPhaseOffset(phaseOffset),
    346             mEnabled(false) {}
    347 
    348     virtual ~DispSyncSource() {}
    349 
    350     virtual void setVSyncEnabled(bool enable) {
    351         Mutex::Autolock lock(mVsyncMutex);
    352         if (enable) {
    353             status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
    354                     static_cast<DispSync::Callback*>(this));
    355             if (err != NO_ERROR) {
    356                 ALOGE("error registering vsync callback: %s (%d)",
    357                         strerror(-err), err);
    358             }
    359             //ATRACE_INT(mVsyncOnLabel.string(), 1);
    360         } else {
    361             status_t err = mDispSync->removeEventListener(
    362                     static_cast<DispSync::Callback*>(this));
    363             if (err != NO_ERROR) {
    364                 ALOGE("error unregistering vsync callback: %s (%d)",
    365                         strerror(-err), err);
    366             }
    367             //ATRACE_INT(mVsyncOnLabel.string(), 0);
    368         }
    369         mEnabled = enable;
    370     }
    371 
    372     virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
    373         Mutex::Autolock lock(mCallbackMutex);
    374         mCallback = callback;
    375     }
    376 
    377     virtual void setPhaseOffset(nsecs_t phaseOffset) {
    378         Mutex::Autolock lock(mVsyncMutex);
    379 
    380         // Normalize phaseOffset to [0, period)
    381         auto period = mDispSync->getPeriod();
    382         phaseOffset %= period;
    383         if (phaseOffset < 0) {
    384             // If we're here, then phaseOffset is in (-period, 0). After this
    385             // operation, it will be in (0, period)
    386             phaseOffset += period;
    387         }
    388         mPhaseOffset = phaseOffset;
    389 
    390         // If we're not enabled, we don't need to mess with the listeners
    391         if (!mEnabled) {
    392             return;
    393         }
    394 
    395         // Remove the listener with the old offset
    396         status_t err = mDispSync->removeEventListener(
    397                 static_cast<DispSync::Callback*>(this));
    398         if (err != NO_ERROR) {
    399             ALOGE("error unregistering vsync callback: %s (%d)",
    400                     strerror(-err), err);
    401         }
    402 
    403         // Add a listener with the new offset
    404         err = mDispSync->addEventListener(mName, mPhaseOffset,
    405                 static_cast<DispSync::Callback*>(this));
    406         if (err != NO_ERROR) {
    407             ALOGE("error registering vsync callback: %s (%d)",
    408                     strerror(-err), err);
    409         }
    410     }
    411 
    412 private:
    413     virtual void onDispSyncEvent(nsecs_t when) {
    414         sp<VSyncSource::Callback> callback;
    415         {
    416             Mutex::Autolock lock(mCallbackMutex);
    417             callback = mCallback;
    418 
    419             if (mTraceVsync) {
    420                 mValue = (mValue + 1) % 2;
    421                 ATRACE_INT(mVsyncEventLabel.string(), mValue);
    422             }
    423         }
    424 
    425         if (callback != NULL) {
    426             callback->onVSyncEvent(when);
    427         }
    428     }
    429 
    430     const char* const mName;
    431 
    432     int mValue;
    433 
    434     const bool mTraceVsync;
    435     const String8 mVsyncOnLabel;
    436     const String8 mVsyncEventLabel;
    437 
    438     DispSync* mDispSync;
    439 
    440     Mutex mCallbackMutex; // Protects the following
    441     sp<VSyncSource::Callback> mCallback;
    442 
    443     Mutex mVsyncMutex; // Protects the following
    444     nsecs_t mPhaseOffset;
    445     bool mEnabled;
    446 };
    447 
    448 void SurfaceFlinger::init() {
    449     ALOGI(  "SurfaceFlinger's main thread ready to run. "
    450             "Initializing graphics H/W...");
    451 
    452     { // Autolock scope
    453         Mutex::Autolock _l(mStateLock);
    454 
    455         // initialize EGL for the default display
    456         mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
    457         eglInitialize(mEGLDisplay, NULL, NULL);
    458 
    459         // start the EventThread
    460         sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
    461                 vsyncPhaseOffsetNs, true, "app");
    462         mEventThread = new EventThread(vsyncSrc, *this);
    463         sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
    464                 sfVsyncPhaseOffsetNs, true, "sf");
    465         mSFEventThread = new EventThread(sfVsyncSrc, *this);
    466         mEventQueue.setEventThread(mSFEventThread);
    467 
    468         // Get a RenderEngine for the given display / config (can't fail)
    469         mRenderEngine = RenderEngine::create(mEGLDisplay,
    470                 HAL_PIXEL_FORMAT_RGBA_8888);
    471     }
    472 
    473     // Drop the state lock while we initialize the hardware composer. We drop
    474     // the lock because on creation, it will call back into SurfaceFlinger to
    475     // initialize the primary display.
    476     mHwc = new HWComposer(this);
    477     mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
    478 
    479     Mutex::Autolock _l(mStateLock);
    480 
    481     // retrieve the EGL context that was selected/created
    482     mEGLContext = mRenderEngine->getEGLContext();
    483 
    484     LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
    485             "couldn't create EGLContext");
    486 
    487     // make the GLContext current so that we can create textures when creating
    488     // Layers (which may happens before we render something)
    489     getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
    490 
    491     mEventControlThread = new EventControlThread(this);
    492     mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
    493 
    494     // initialize our drawing state
    495     mDrawingState = mCurrentState;
    496 
    497     // set initial conditions (e.g. unblank default device)
    498     initializeDisplays();
    499 
    500     // start boot animation
    501     startBootAnim();
    502 
    503     ALOGV("Done initializing");
    504 }
    505 
    506 void SurfaceFlinger::startBootAnim() {
    507     // start boot animation
    508     property_set("service.bootanim.exit", "0");
    509     property_set("ctl.start", "bootanim");
    510 }
    511 
    512 size_t SurfaceFlinger::getMaxTextureSize() const {
    513     return mRenderEngine->getMaxTextureSize();
    514 }
    515 
    516 size_t SurfaceFlinger::getMaxViewportDims() const {
    517     return mRenderEngine->getMaxViewportDims();
    518 }
    519 
    520 // ----------------------------------------------------------------------------
    521 
    522 bool SurfaceFlinger::authenticateSurfaceTexture(
    523         const sp<IGraphicBufferProducer>& bufferProducer) const {
    524     Mutex::Autolock _l(mStateLock);
    525     sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
    526     return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
    527 }
    528 
    529 status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
    530         Vector<DisplayInfo>* configs) {
    531     if ((configs == NULL) || (display.get() == NULL)) {
    532         return BAD_VALUE;
    533     }
    534 
    535     if (!display.get())
    536         return NAME_NOT_FOUND;
    537 
    538     int32_t type = NAME_NOT_FOUND;
    539     for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
    540         if (display == mBuiltinDisplays[i]) {
    541             type = i;
    542             break;
    543         }
    544     }
    545 
    546     if (type < 0) {
    547         return type;
    548     }
    549 
    550     // TODO: Not sure if display density should handled by SF any longer
    551     class Density {
    552         static int getDensityFromProperty(char const* propName) {
    553             char property[PROPERTY_VALUE_MAX];
    554             int density = 0;
    555             if (property_get(propName, property, NULL) > 0) {
    556                 density = atoi(property);
    557             }
    558             return density;
    559         }
    560     public:
    561         static int getEmuDensity() {
    562             return getDensityFromProperty("qemu.sf.lcd_density"); }
    563         static int getBuildDensity()  {
    564             return getDensityFromProperty("ro.sf.lcd_density"); }
    565     };
    566 
    567     configs->clear();
    568 
    569     for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
    570         DisplayInfo info = DisplayInfo();
    571 
    572         float xdpi = hwConfig->getDpiX();
    573         float ydpi = hwConfig->getDpiY();
    574 
    575         if (type == DisplayDevice::DISPLAY_PRIMARY) {
    576             // The density of the device is provided by a build property
    577             float density = Density::getBuildDensity() / 160.0f;
    578             if (density == 0) {
    579                 // the build doesn't provide a density -- this is wrong!
    580                 // use xdpi instead
    581                 ALOGE("ro.sf.lcd_density must be defined as a build property");
    582                 density = xdpi / 160.0f;
    583             }
    584             if (Density::getEmuDensity()) {
    585                 // if "qemu.sf.lcd_density" is specified, it overrides everything
    586                 xdpi = ydpi = density = Density::getEmuDensity();
    587                 density /= 160.0f;
    588             }
    589             info.density = density;
    590 
    591             // TODO: this needs to go away (currently needed only by webkit)
    592             sp<const DisplayDevice> hw(getDefaultDisplayDevice());
    593             info.orientation = hw->getOrientation();
    594         } else {
    595             // TODO: where should this value come from?
    596             static const int TV_DENSITY = 213;
    597             info.density = TV_DENSITY / 160.0f;
    598             info.orientation = 0;
    599         }
    600 
    601         info.w = hwConfig->getWidth();
    602         info.h = hwConfig->getHeight();
    603         info.xdpi = xdpi;
    604         info.ydpi = ydpi;
    605         info.fps = 1e9 / hwConfig->getVsyncPeriod();
    606         info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
    607 
    608         // TODO: Hook this back up
    609         info.colorTransform = 0;
    610 
    611         // This is how far in advance a buffer must be queued for
    612         // presentation at a given time.  If you want a buffer to appear
    613         // on the screen at time N, you must submit the buffer before
    614         // (N - presentationDeadline).
    615         //
    616         // Normally it's one full refresh period (to give SF a chance to
    617         // latch the buffer), but this can be reduced by configuring a
    618         // DispSync offset.  Any additional delays introduced by the hardware
    619         // composer or panel must be accounted for here.
    620         //
    621         // We add an additional 1ms to allow for processing time and
    622         // differences between the ideal and actual refresh rate.
    623         info.presentationDeadline = hwConfig->getVsyncPeriod() -
    624                 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
    625 
    626         // All non-virtual displays are currently considered secure.
    627         info.secure = true;
    628 
    629         configs->push_back(info);
    630     }
    631 
    632     return NO_ERROR;
    633 }
    634 
    635 status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
    636         DisplayStatInfo* stats) {
    637     if (stats == NULL) {
    638         return BAD_VALUE;
    639     }
    640 
    641     // FIXME for now we always return stats for the primary display
    642     memset(stats, 0, sizeof(*stats));
    643     stats->vsyncTime   = mPrimaryDispSync.computeNextRefresh(0);
    644     stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
    645     return NO_ERROR;
    646 }
    647 
    648 int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
    649     sp<DisplayDevice> device(getDisplayDevice(display));
    650     if (device != NULL) {
    651         return device->getActiveConfig();
    652     }
    653     return BAD_VALUE;
    654 }
    655 
    656 void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
    657     ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
    658           this);
    659     int32_t type = hw->getDisplayType();
    660     int currentMode = hw->getActiveConfig();
    661 
    662     if (mode == currentMode) {
    663         ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
    664         return;
    665     }
    666 
    667     if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
    668         ALOGW("Trying to set config for virtual display");
    669         return;
    670     }
    671 
    672     hw->setActiveConfig(mode);
    673     getHwComposer().setActiveConfig(type, mode);
    674 }
    675 
    676 status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
    677     class MessageSetActiveConfig: public MessageBase {
    678         SurfaceFlinger& mFlinger;
    679         sp<IBinder> mDisplay;
    680         int mMode;
    681     public:
    682         MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
    683                                int mode) :
    684             mFlinger(flinger), mDisplay(disp) { mMode = mode; }
    685         virtual bool handler() {
    686             Vector<DisplayInfo> configs;
    687             mFlinger.getDisplayConfigs(mDisplay, &configs);
    688             if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
    689                 ALOGE("Attempt to set active config = %d for display with %zu configs",
    690                         mMode, configs.size());
    691             }
    692             sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
    693             if (hw == NULL) {
    694                 ALOGE("Attempt to set active config = %d for null display %p",
    695                         mMode, mDisplay.get());
    696             } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
    697                 ALOGW("Attempt to set active config = %d for virtual display",
    698                         mMode);
    699             } else {
    700                 mFlinger.setActiveConfigInternal(hw, mMode);
    701             }
    702             return true;
    703         }
    704     };
    705     sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
    706     postMessageSync(msg);
    707     return NO_ERROR;
    708 }
    709 
    710 status_t SurfaceFlinger::clearAnimationFrameStats() {
    711     Mutex::Autolock _l(mStateLock);
    712     mAnimFrameTracker.clearStats();
    713     return NO_ERROR;
    714 }
    715 
    716 status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
    717     Mutex::Autolock _l(mStateLock);
    718     mAnimFrameTracker.getStats(outStats);
    719     return NO_ERROR;
    720 }
    721 
    722 status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
    723         HdrCapabilities* outCapabilities) const {
    724     Mutex::Autolock _l(mStateLock);
    725 
    726     sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
    727     if (displayDevice == nullptr) {
    728         ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
    729         return BAD_VALUE;
    730     }
    731 
    732     std::unique_ptr<HdrCapabilities> capabilities =
    733             mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
    734     if (capabilities) {
    735         std::swap(*outCapabilities, *capabilities);
    736     } else {
    737         return BAD_VALUE;
    738     }
    739 
    740     return NO_ERROR;
    741 }
    742 
    743 // ----------------------------------------------------------------------------
    744 
    745 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
    746     return mEventThread->createEventConnection();
    747 }
    748 
    749 // ----------------------------------------------------------------------------
    750 
    751 void SurfaceFlinger::waitForEvent() {
    752     mEventQueue.waitMessage();
    753 }
    754 
    755 void SurfaceFlinger::signalTransaction() {
    756     mEventQueue.invalidate();
    757 }
    758 
    759 void SurfaceFlinger::signalLayerUpdate() {
    760     mEventQueue.invalidate();
    761 }
    762 
    763 void SurfaceFlinger::signalRefresh() {
    764     mEventQueue.refresh();
    765 }
    766 
    767 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
    768         nsecs_t reltime, uint32_t /* flags */) {
    769     return mEventQueue.postMessage(msg, reltime);
    770 }
    771 
    772 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
    773         nsecs_t reltime, uint32_t /* flags */) {
    774     status_t res = mEventQueue.postMessage(msg, reltime);
    775     if (res == NO_ERROR) {
    776         msg->wait();
    777     }
    778     return res;
    779 }
    780 
    781 void SurfaceFlinger::run() {
    782     do {
    783         waitForEvent();
    784     } while (true);
    785 }
    786 
    787 void SurfaceFlinger::enableHardwareVsync() {
    788     Mutex::Autolock _l(mHWVsyncLock);
    789     if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
    790         mPrimaryDispSync.beginResync();
    791         //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
    792         mEventControlThread->setVsyncEnabled(true);
    793         mPrimaryHWVsyncEnabled = true;
    794     }
    795 }
    796 
    797 void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
    798     Mutex::Autolock _l(mHWVsyncLock);
    799 
    800     if (makeAvailable) {
    801         mHWVsyncAvailable = true;
    802     } else if (!mHWVsyncAvailable) {
    803         // Hardware vsync is not currently available, so abort the resync
    804         // attempt for now
    805         return;
    806     }
    807 
    808     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
    809     const nsecs_t period = activeConfig->getVsyncPeriod();
    810 
    811     mPrimaryDispSync.reset();
    812     mPrimaryDispSync.setPeriod(period);
    813 
    814     if (!mPrimaryHWVsyncEnabled) {
    815         mPrimaryDispSync.beginResync();
    816         //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
    817         mEventControlThread->setVsyncEnabled(true);
    818         mPrimaryHWVsyncEnabled = true;
    819     }
    820 }
    821 
    822 void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
    823     Mutex::Autolock _l(mHWVsyncLock);
    824     if (mPrimaryHWVsyncEnabled) {
    825         //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
    826         mEventControlThread->setVsyncEnabled(false);
    827         mPrimaryDispSync.endResync();
    828         mPrimaryHWVsyncEnabled = false;
    829     }
    830     if (makeUnavailable) {
    831         mHWVsyncAvailable = false;
    832     }
    833 }
    834 
    835 void SurfaceFlinger::resyncWithRateLimit() {
    836     static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
    837     if (systemTime() - mLastSwapTime > kIgnoreDelay) {
    838         resyncToHardwareVsync(false);
    839     }
    840 }
    841 
    842 void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
    843     bool needsHwVsync = false;
    844 
    845     { // Scope for the lock
    846         Mutex::Autolock _l(mHWVsyncLock);
    847         if (type == 0 && mPrimaryHWVsyncEnabled) {
    848             needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
    849         }
    850     }
    851 
    852     if (needsHwVsync) {
    853         enableHardwareVsync();
    854     } else {
    855         disableHardwareVsync(false);
    856     }
    857 }
    858 
    859 void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
    860     ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
    861     if (disp == DisplayDevice::DISPLAY_PRIMARY) {
    862         Mutex::Autolock lock(mStateLock);
    863 
    864         // All non-virtual displays are currently considered secure.
    865         bool isSecure = true;
    866 
    867         int32_t type = DisplayDevice::DISPLAY_PRIMARY;
    868         createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
    869         wp<IBinder> token = mBuiltinDisplays[type];
    870 
    871         sp<IGraphicBufferProducer> producer;
    872         sp<IGraphicBufferConsumer> consumer;
    873         BufferQueue::createBufferQueue(&producer, &consumer,
    874                 new GraphicBufferAlloc());
    875 
    876         sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
    877                 DisplayDevice::DISPLAY_PRIMARY, consumer);
    878         sp<DisplayDevice> hw = new DisplayDevice(this,
    879                 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
    880                 producer, mRenderEngine->getEGLConfig());
    881         mDisplays.add(token, hw);
    882     } else {
    883         auto type = DisplayDevice::DISPLAY_EXTERNAL;
    884         Mutex::Autolock _l(mStateLock);
    885         if (connected) {
    886             createBuiltinDisplayLocked(type);
    887         } else {
    888             mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
    889             mBuiltinDisplays[type].clear();
    890         }
    891         setTransactionFlags(eDisplayTransactionNeeded);
    892 
    893         // Defer EventThread notification until SF has updated mDisplays.
    894     }
    895 }
    896 
    897 void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
    898     ATRACE_CALL();
    899     getHwComposer().setVsyncEnabled(disp,
    900             enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
    901 }
    902 
    903 void SurfaceFlinger::onMessageReceived(int32_t what) {
    904     ATRACE_CALL();
    905     switch (what) {
    906         case MessageQueue::INVALIDATE: {
    907             bool refreshNeeded = handleMessageTransaction();
    908             refreshNeeded |= handleMessageInvalidate();
    909             refreshNeeded |= mRepaintEverything;
    910             if (refreshNeeded) {
    911                 // Signal a refresh if a transaction modified the window state,
    912                 // a new buffer was latched, or if HWC has requested a full
    913                 // repaint
    914                 signalRefresh();
    915             }
    916             break;
    917         }
    918         case MessageQueue::REFRESH: {
    919             handleMessageRefresh();
    920             break;
    921         }
    922     }
    923 }
    924 
    925 bool SurfaceFlinger::handleMessageTransaction() {
    926     uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
    927     if (transactionFlags) {
    928         handleTransaction(transactionFlags);
    929         return true;
    930     }
    931     return false;
    932 }
    933 
    934 bool SurfaceFlinger::handleMessageInvalidate() {
    935     ATRACE_CALL();
    936     return handlePageFlip();
    937 }
    938 
    939 void SurfaceFlinger::handleMessageRefresh() {
    940     ATRACE_CALL();
    941 
    942 #ifdef ENABLE_FENCE_TRACKING
    943     nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
    944 #else
    945     nsecs_t refreshStartTime = 0;
    946 #endif
    947     static nsecs_t previousExpectedPresent = 0;
    948     nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
    949     static bool previousFrameMissed = false;
    950     bool frameMissed = (expectedPresent == previousExpectedPresent);
    951     if (frameMissed != previousFrameMissed) {
    952         ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
    953     }
    954     previousFrameMissed = frameMissed;
    955 
    956     if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
    957         // Latch buffers, but don't send anything to HWC, then signal another
    958         // wakeup for the next vsync
    959         preComposition();
    960         repaintEverything();
    961     } else {
    962         preComposition();
    963         rebuildLayerStacks();
    964         setUpHWComposer();
    965         doDebugFlashRegions();
    966         doComposition();
    967         postComposition(refreshStartTime);
    968     }
    969 
    970     // Release any buffers which were replaced this frame
    971     for (auto& layer : mLayersWithQueuedFrames) {
    972         layer->releasePendingBuffer();
    973     }
    974     mLayersWithQueuedFrames.clear();
    975 
    976     previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
    977 }
    978 
    979 void SurfaceFlinger::doDebugFlashRegions()
    980 {
    981     // is debugging enabled
    982     if (CC_LIKELY(!mDebugRegion))
    983         return;
    984 
    985     const bool repaintEverything = mRepaintEverything;
    986     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
    987         const sp<DisplayDevice>& hw(mDisplays[dpy]);
    988         if (hw->isDisplayOn()) {
    989             // transform the dirty region into this screen's coordinate space
    990             const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
    991             if (!dirtyRegion.isEmpty()) {
    992                 // redraw the whole screen
    993                 doComposeSurfaces(hw, Region(hw->bounds()));
    994 
    995                 // and draw the dirty region
    996                 const int32_t height = hw->getHeight();
    997                 RenderEngine& engine(getRenderEngine());
    998                 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
    999 
   1000                 hw->swapBuffers(getHwComposer());
   1001             }
   1002         }
   1003     }
   1004 
   1005     postFramebuffer();
   1006 
   1007     if (mDebugRegion > 1) {
   1008         usleep(mDebugRegion * 1000);
   1009     }
   1010 
   1011     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
   1012         status_t result = mDisplays[displayId]->prepareFrame(*mHwc);
   1013         ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
   1014                 " %d (%s)", displayId, result, strerror(-result));
   1015     }
   1016 }
   1017 
   1018 void SurfaceFlinger::preComposition()
   1019 {
   1020     ATRACE_CALL();
   1021     ALOGV("preComposition");
   1022 
   1023     bool needExtraInvalidate = false;
   1024     const LayerVector& layers(mDrawingState.layersSortedByZ);
   1025     const size_t count = layers.size();
   1026     for (size_t i=0 ; i<count ; i++) {
   1027         if (layers[i]->onPreComposition()) {
   1028             needExtraInvalidate = true;
   1029         }
   1030     }
   1031     if (needExtraInvalidate) {
   1032         signalLayerUpdate();
   1033     }
   1034 }
   1035 
   1036 #ifdef ENABLE_FENCE_TRACKING
   1037 void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
   1038 #else
   1039 void SurfaceFlinger::postComposition(nsecs_t /*refreshStartTime*/)
   1040 #endif
   1041 {
   1042     ATRACE_CALL();
   1043     ALOGV("postComposition");
   1044 
   1045     const LayerVector& layers(mDrawingState.layersSortedByZ);
   1046     const size_t count = layers.size();
   1047     for (size_t i=0 ; i<count ; i++) {
   1048         layers[i]->onPostComposition();
   1049     }
   1050 
   1051     sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
   1052 
   1053     if (presentFence->isValid()) {
   1054         if (mPrimaryDispSync.addPresentFence(presentFence)) {
   1055             enableHardwareVsync();
   1056         } else {
   1057             disableHardwareVsync(false);
   1058         }
   1059     }
   1060 
   1061     const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
   1062     if (kIgnorePresentFences) {
   1063         if (hw->isDisplayOn()) {
   1064             enableHardwareVsync();
   1065         }
   1066     }
   1067 
   1068 #ifdef ENABLE_FENCE_TRACKING
   1069     mFenceTracker.addFrame(refreshStartTime, presentFence,
   1070             hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
   1071 #endif
   1072 
   1073     if (mAnimCompositionPending) {
   1074         mAnimCompositionPending = false;
   1075 
   1076         if (presentFence->isValid()) {
   1077             mAnimFrameTracker.setActualPresentFence(presentFence);
   1078         } else {
   1079             // The HWC doesn't support present fences, so use the refresh
   1080             // timestamp instead.
   1081             nsecs_t presentTime =
   1082                     mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
   1083             mAnimFrameTracker.setActualPresentTime(presentTime);
   1084         }
   1085         mAnimFrameTracker.advanceFrame();
   1086     }
   1087 
   1088     if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
   1089         return;
   1090     }
   1091 
   1092     nsecs_t currentTime = systemTime();
   1093     if (mHasPoweredOff) {
   1094         mHasPoweredOff = false;
   1095     } else {
   1096         nsecs_t period = mPrimaryDispSync.getPeriod();
   1097         nsecs_t elapsedTime = currentTime - mLastSwapTime;
   1098         size_t numPeriods = static_cast<size_t>(elapsedTime / period);
   1099         if (numPeriods < NUM_BUCKETS - 1) {
   1100             mFrameBuckets[numPeriods] += elapsedTime;
   1101         } else {
   1102             mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
   1103         }
   1104         mTotalTime += elapsedTime;
   1105     }
   1106     mLastSwapTime = currentTime;
   1107 }
   1108 
   1109 void SurfaceFlinger::rebuildLayerStacks() {
   1110     ATRACE_CALL();
   1111     ALOGV("rebuildLayerStacks");
   1112 
   1113     // rebuild the visible layer list per screen
   1114     if (CC_UNLIKELY(mVisibleRegionsDirty)) {
   1115         ATRACE_CALL();
   1116         mVisibleRegionsDirty = false;
   1117         invalidateHwcGeometry();
   1118 
   1119         const LayerVector& layers(mDrawingState.layersSortedByZ);
   1120         for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
   1121             Region opaqueRegion;
   1122             Region dirtyRegion;
   1123             Vector<sp<Layer>> layersSortedByZ;
   1124             const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
   1125             const Transform& tr(displayDevice->getTransform());
   1126             const Rect bounds(displayDevice->getBounds());
   1127             if (displayDevice->isDisplayOn()) {
   1128                 SurfaceFlinger::computeVisibleRegions(layers,
   1129                         displayDevice->getLayerStack(), dirtyRegion,
   1130                         opaqueRegion);
   1131 
   1132                 const size_t count = layers.size();
   1133                 for (size_t i=0 ; i<count ; i++) {
   1134                     const sp<Layer>& layer(layers[i]);
   1135                     const Layer::State& s(layer->getDrawingState());
   1136                     if (s.layerStack == displayDevice->getLayerStack()) {
   1137                         Region drawRegion(tr.transform(
   1138                                 layer->visibleNonTransparentRegion));
   1139                         drawRegion.andSelf(bounds);
   1140                         if (!drawRegion.isEmpty()) {
   1141                             layersSortedByZ.add(layer);
   1142                         } else {
   1143                             // Clear out the HWC layer if this layer was
   1144                             // previously visible, but no longer is
   1145                             layer->setHwcLayer(displayDevice->getHwcDisplayId(),
   1146                                     nullptr);
   1147                         }
   1148                     }
   1149                 }
   1150             }
   1151             displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
   1152             displayDevice->undefinedRegion.set(bounds);
   1153             displayDevice->undefinedRegion.subtractSelf(
   1154                     tr.transform(opaqueRegion));
   1155             displayDevice->dirtyRegion.orSelf(dirtyRegion);
   1156         }
   1157     }
   1158 }
   1159 
   1160 void SurfaceFlinger::setUpHWComposer() {
   1161     ATRACE_CALL();
   1162     ALOGV("setUpHWComposer");
   1163 
   1164     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
   1165         bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
   1166         bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
   1167         bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
   1168 
   1169         // If nothing has changed (!dirty), don't recompose.
   1170         // If something changed, but we don't currently have any visible layers,
   1171         //   and didn't when we last did a composition, then skip it this time.
   1172         // The second rule does two things:
   1173         // - When all layers are removed from a display, we'll emit one black
   1174         //   frame, then nothing more until we get new layers.
   1175         // - When a display is created with a private layer stack, we won't
   1176         //   emit any black frames until a layer is added to the layer stack.
   1177         bool mustRecompose = dirty && !(empty && wasEmpty);
   1178 
   1179         ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
   1180                 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
   1181                 mustRecompose ? "doing" : "skipping",
   1182                 dirty ? "+" : "-",
   1183                 empty ? "+" : "-",
   1184                 wasEmpty ? "+" : "-");
   1185 
   1186         mDisplays[dpy]->beginFrame(mustRecompose);
   1187 
   1188         if (mustRecompose) {
   1189             mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
   1190         }
   1191     }
   1192 
   1193     // build the h/w work list
   1194     if (CC_UNLIKELY(mGeometryInvalid)) {
   1195         mGeometryInvalid = false;
   1196         for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
   1197             sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
   1198             const auto hwcId = displayDevice->getHwcDisplayId();
   1199             if (hwcId >= 0) {
   1200                 const Vector<sp<Layer>>& currentLayers(
   1201                         displayDevice->getVisibleLayersSortedByZ());
   1202                 bool foundLayerWithoutHwc = false;
   1203                 for (auto& layer : currentLayers) {
   1204                     if (!layer->hasHwcLayer(hwcId)) {
   1205                         auto hwcLayer = mHwc->createLayer(hwcId);
   1206                         if (hwcLayer) {
   1207                             layer->setHwcLayer(hwcId, std::move(hwcLayer));
   1208                         } else {
   1209                             layer->forceClientComposition(hwcId);
   1210                             foundLayerWithoutHwc = true;
   1211                             continue;
   1212                         }
   1213                     }
   1214 
   1215                     layer->setGeometry(displayDevice);
   1216                     if (mDebugDisableHWC || mDebugRegion || mDaltonize ||
   1217                             mHasColorMatrix) {
   1218                         layer->forceClientComposition(hwcId);
   1219                     }
   1220                 }
   1221             }
   1222         }
   1223     }
   1224 
   1225     // Set the per-frame data
   1226     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
   1227         auto& displayDevice = mDisplays[displayId];
   1228         const auto hwcId = displayDevice->getHwcDisplayId();
   1229         if (hwcId < 0) {
   1230             continue;
   1231         }
   1232         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
   1233             layer->setPerFrameData(displayDevice);
   1234         }
   1235     }
   1236 
   1237     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
   1238         status_t result = mDisplays[displayId]->prepareFrame(*mHwc);
   1239         ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
   1240                 " %d (%s)", displayId, result, strerror(-result));
   1241     }
   1242 }
   1243 
   1244 void SurfaceFlinger::doComposition() {
   1245     ATRACE_CALL();
   1246     ALOGV("doComposition");
   1247 
   1248     const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
   1249     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
   1250         const sp<DisplayDevice>& hw(mDisplays[dpy]);
   1251         if (hw->isDisplayOn()) {
   1252             // transform the dirty region into this screen's coordinate space
   1253             const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
   1254 
   1255             // repaint the framebuffer (if needed)
   1256             doDisplayComposition(hw, dirtyRegion);
   1257 
   1258             hw->dirtyRegion.clear();
   1259             hw->flip(hw->swapRegion);
   1260             hw->swapRegion.clear();
   1261         }
   1262     }
   1263     postFramebuffer();
   1264 }
   1265 
   1266 void SurfaceFlinger::postFramebuffer()
   1267 {
   1268     ATRACE_CALL();
   1269     ALOGV("postFramebuffer");
   1270 
   1271     const nsecs_t now = systemTime();
   1272     mDebugInSwapBuffers = now;
   1273 
   1274     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
   1275         auto& displayDevice = mDisplays[displayId];
   1276         const auto hwcId = displayDevice->getHwcDisplayId();
   1277         if (hwcId >= 0) {
   1278             mHwc->commit(hwcId);
   1279         }
   1280         displayDevice->onSwapBuffersCompleted();
   1281         if (displayId == 0) {
   1282             // Make the default display current because the VirtualDisplayDevice
   1283             // code cannot deal with dequeueBuffer() being called outside of the
   1284             // composition loop; however the code below can call glFlush() which
   1285             // is allowed to (and does in some case) call dequeueBuffer().
   1286             displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
   1287         }
   1288         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
   1289             sp<Fence> releaseFence = Fence::NO_FENCE;
   1290             if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
   1291                 releaseFence = displayDevice->getClientTargetAcquireFence();
   1292             } else {
   1293                 auto hwcLayer = layer->getHwcLayer(hwcId);
   1294                 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
   1295             }
   1296             layer->onLayerDisplayed(releaseFence);
   1297         }
   1298         if (hwcId >= 0) {
   1299             mHwc->clearReleaseFences(hwcId);
   1300         }
   1301     }
   1302 
   1303     mLastSwapBufferTime = systemTime() - now;
   1304     mDebugInSwapBuffers = 0;
   1305 
   1306     uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
   1307     if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
   1308         logFrameStats();
   1309     }
   1310 }
   1311 
   1312 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
   1313 {
   1314     ATRACE_CALL();
   1315 
   1316     // here we keep a copy of the drawing state (that is the state that's
   1317     // going to be overwritten by handleTransactionLocked()) outside of
   1318     // mStateLock so that the side-effects of the State assignment
   1319     // don't happen with mStateLock held (which can cause deadlocks).
   1320     State drawingState(mDrawingState);
   1321 
   1322     Mutex::Autolock _l(mStateLock);
   1323     const nsecs_t now = systemTime();
   1324     mDebugInTransaction = now;
   1325 
   1326     // Here we're guaranteed that some transaction flags are set
   1327     // so we can call handleTransactionLocked() unconditionally.
   1328     // We call getTransactionFlags(), which will also clear the flags,
   1329     // with mStateLock held to guarantee that mCurrentState won't change
   1330     // until the transaction is committed.
   1331 
   1332     transactionFlags = getTransactionFlags(eTransactionMask);
   1333     handleTransactionLocked(transactionFlags);
   1334 
   1335     mLastTransactionTime = systemTime() - now;
   1336     mDebugInTransaction = 0;
   1337     invalidateHwcGeometry();
   1338     // here the transaction has been committed
   1339 }
   1340 
   1341 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
   1342 {
   1343     const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
   1344     const size_t count = currentLayers.size();
   1345 
   1346     // Notify all layers of available frames
   1347     for (size_t i = 0; i < count; ++i) {
   1348         currentLayers[i]->notifyAvailableFrames();
   1349     }
   1350 
   1351     /*
   1352      * Traversal of the children
   1353      * (perform the transaction for each of them if needed)
   1354      */
   1355 
   1356     if (transactionFlags & eTraversalNeeded) {
   1357         for (size_t i=0 ; i<count ; i++) {
   1358             const sp<Layer>& layer(currentLayers[i]);
   1359             uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
   1360             if (!trFlags) continue;
   1361 
   1362             const uint32_t flags = layer->doTransaction(0);
   1363             if (flags & Layer::eVisibleRegion)
   1364                 mVisibleRegionsDirty = true;
   1365         }
   1366     }
   1367 
   1368     /*
   1369      * Perform display own transactions if needed
   1370      */
   1371 
   1372     if (transactionFlags & eDisplayTransactionNeeded) {
   1373         // here we take advantage of Vector's copy-on-write semantics to
   1374         // improve performance by skipping the transaction entirely when
   1375         // know that the lists are identical
   1376         const KeyedVector<  wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
   1377         const KeyedVector<  wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
   1378         if (!curr.isIdenticalTo(draw)) {
   1379             mVisibleRegionsDirty = true;
   1380             const size_t cc = curr.size();
   1381                   size_t dc = draw.size();
   1382 
   1383             // find the displays that were removed
   1384             // (ie: in drawing state but not in current state)
   1385             // also handle displays that changed
   1386             // (ie: displays that are in both lists)
   1387             for (size_t i=0 ; i<dc ; i++) {
   1388                 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
   1389                 if (j < 0) {
   1390                     // in drawing state but not in current state
   1391                     if (!draw[i].isMainDisplay()) {
   1392                         // Call makeCurrent() on the primary display so we can
   1393                         // be sure that nothing associated with this display
   1394                         // is current.
   1395                         const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
   1396                         defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
   1397                         sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
   1398                         if (hw != NULL)
   1399                             hw->disconnect(getHwComposer());
   1400                         if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
   1401                             mEventThread->onHotplugReceived(draw[i].type, false);
   1402                         mDisplays.removeItem(draw.keyAt(i));
   1403                     } else {
   1404                         ALOGW("trying to remove the main display");
   1405                     }
   1406                 } else {
   1407                     // this display is in both lists. see if something changed.
   1408                     const DisplayDeviceState& state(curr[j]);
   1409                     const wp<IBinder>& display(curr.keyAt(j));
   1410                     const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
   1411                     const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
   1412                     if (state_binder != draw_binder) {
   1413                         // changing the surface is like destroying and
   1414                         // recreating the DisplayDevice, so we just remove it
   1415                         // from the drawing state, so that it get re-added
   1416                         // below.
   1417                         sp<DisplayDevice> hw(getDisplayDevice(display));
   1418                         if (hw != NULL)
   1419                             hw->disconnect(getHwComposer());
   1420                         mDisplays.removeItem(display);
   1421                         mDrawingState.displays.removeItemsAt(i);
   1422                         dc--; i--;
   1423                         // at this point we must loop to the next item
   1424                         continue;
   1425                     }
   1426 
   1427                     const sp<DisplayDevice> disp(getDisplayDevice(display));
   1428                     if (disp != NULL) {
   1429                         if (state.layerStack != draw[i].layerStack) {
   1430                             disp->setLayerStack(state.layerStack);
   1431                         }
   1432                         if ((state.orientation != draw[i].orientation)
   1433                                 || (state.viewport != draw[i].viewport)
   1434                                 || (state.frame != draw[i].frame))
   1435                         {
   1436                             disp->setProjection(state.orientation,
   1437                                     state.viewport, state.frame);
   1438                         }
   1439                         if (state.width != draw[i].width || state.height != draw[i].height) {
   1440                             disp->setDisplaySize(state.width, state.height);
   1441                         }
   1442                     }
   1443                 }
   1444             }
   1445 
   1446             // find displays that were added
   1447             // (ie: in current state but not in drawing state)
   1448             for (size_t i=0 ; i<cc ; i++) {
   1449                 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
   1450                     const DisplayDeviceState& state(curr[i]);
   1451 
   1452                     sp<DisplaySurface> dispSurface;
   1453                     sp<IGraphicBufferProducer> producer;
   1454                     sp<IGraphicBufferProducer> bqProducer;
   1455                     sp<IGraphicBufferConsumer> bqConsumer;
   1456                     BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
   1457                             new GraphicBufferAlloc());
   1458 
   1459                     int32_t hwcId = -1;
   1460                     if (state.isVirtualDisplay()) {
   1461                         // Virtual displays without a surface are dormant:
   1462                         // they have external state (layer stack, projection,
   1463                         // etc.) but no internal state (i.e. a DisplayDevice).
   1464                         if (state.surface != NULL) {
   1465 
   1466                             int width = 0;
   1467                             int status = state.surface->query(
   1468                                     NATIVE_WINDOW_WIDTH, &width);
   1469                             ALOGE_IF(status != NO_ERROR,
   1470                                     "Unable to query width (%d)", status);
   1471                             int height = 0;
   1472                             status = state.surface->query(
   1473                                     NATIVE_WINDOW_HEIGHT, &height);
   1474                             ALOGE_IF(status != NO_ERROR,
   1475                                     "Unable to query height (%d)", status);
   1476                             int intFormat = 0;
   1477                             status = state.surface->query(
   1478                                     NATIVE_WINDOW_FORMAT, &intFormat);
   1479                             ALOGE_IF(status != NO_ERROR,
   1480                                     "Unable to query format (%d)", status);
   1481                             auto format = static_cast<android_pixel_format_t>(
   1482                                     intFormat);
   1483 
   1484                             mHwc->allocateVirtualDisplay(width, height, &format,
   1485                                     &hwcId);
   1486 
   1487                             // TODO: Plumb requested format back up to consumer
   1488 
   1489                             sp<VirtualDisplaySurface> vds =
   1490                                     new VirtualDisplaySurface(*mHwc,
   1491                                             hwcId, state.surface, bqProducer,
   1492                                             bqConsumer, state.displayName);
   1493 
   1494                             dispSurface = vds;
   1495                             producer = vds;
   1496                         }
   1497                     } else {
   1498                         ALOGE_IF(state.surface!=NULL,
   1499                                 "adding a supported display, but rendering "
   1500                                 "surface is provided (%p), ignoring it",
   1501                                 state.surface.get());
   1502                         if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
   1503                             hwcId = DisplayDevice::DISPLAY_EXTERNAL;
   1504                             dispSurface = new FramebufferSurface(*mHwc,
   1505                                     DisplayDevice::DISPLAY_EXTERNAL,
   1506                                     bqConsumer);
   1507                             producer = bqProducer;
   1508                         } else {
   1509                             ALOGE("Attempted to add non-external non-virtual"
   1510                                     " display");
   1511                         }
   1512                     }
   1513 
   1514                     const wp<IBinder>& display(curr.keyAt(i));
   1515                     if (dispSurface != NULL) {
   1516                         sp<DisplayDevice> hw = new DisplayDevice(this,
   1517                                 state.type, hwcId, state.isSecure, display,
   1518                                 dispSurface, producer,
   1519                                 mRenderEngine->getEGLConfig());
   1520                         hw->setLayerStack(state.layerStack);
   1521                         hw->setProjection(state.orientation,
   1522                                 state.viewport, state.frame);
   1523                         hw->setDisplayName(state.displayName);
   1524                         mDisplays.add(display, hw);
   1525                         if (!state.isVirtualDisplay()) {
   1526                             mEventThread->onHotplugReceived(state.type, true);
   1527                         }
   1528                     }
   1529                 }
   1530             }
   1531         }
   1532     }
   1533 
   1534     if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
   1535         // The transform hint might have changed for some layers
   1536         // (either because a display has changed, or because a layer
   1537         // as changed).
   1538         //
   1539         // Walk through all the layers in currentLayers,
   1540         // and update their transform hint.
   1541         //
   1542         // If a layer is visible only on a single display, then that
   1543         // display is used to calculate the hint, otherwise we use the
   1544         // default display.
   1545         //
   1546         // NOTE: we do this here, rather than in rebuildLayerStacks() so that
   1547         // the hint is set before we acquire a buffer from the surface texture.
   1548         //
   1549         // NOTE: layer transactions have taken place already, so we use their
   1550         // drawing state. However, SurfaceFlinger's own transaction has not
   1551         // happened yet, so we must use the current state layer list
   1552         // (soon to become the drawing state list).
   1553         //
   1554         sp<const DisplayDevice> disp;
   1555         uint32_t currentlayerStack = 0;
   1556         for (size_t i=0; i<count; i++) {
   1557             // NOTE: we rely on the fact that layers are sorted by
   1558             // layerStack first (so we don't have to traverse the list
   1559             // of displays for every layer).
   1560             const sp<Layer>& layer(currentLayers[i]);
   1561             uint32_t layerStack = layer->getDrawingState().layerStack;
   1562             if (i==0 || currentlayerStack != layerStack) {
   1563                 currentlayerStack = layerStack;
   1564                 // figure out if this layerstack is mirrored
   1565                 // (more than one display) if so, pick the default display,
   1566                 // if not, pick the only display it's on.
   1567                 disp.clear();
   1568                 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
   1569                     sp<const DisplayDevice> hw(mDisplays[dpy]);
   1570                     if (hw->getLayerStack() == currentlayerStack) {
   1571                         if (disp == NULL) {
   1572                             disp = hw;
   1573                         } else {
   1574                             disp = NULL;
   1575                             break;
   1576                         }
   1577                     }
   1578                 }
   1579             }
   1580             if (disp == NULL) {
   1581                 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
   1582                 // redraw after transform hint changes. See bug 8508397.
   1583 
   1584                 // could be null when this layer is using a layerStack
   1585                 // that is not visible on any display. Also can occur at
   1586                 // screen off/on times.
   1587                 disp = getDefaultDisplayDevice();
   1588             }
   1589             layer->updateTransformHint(disp);
   1590         }
   1591     }
   1592 
   1593 
   1594     /*
   1595      * Perform our own transaction if needed
   1596      */
   1597 
   1598     const LayerVector& layers(mDrawingState.layersSortedByZ);
   1599     if (currentLayers.size() > layers.size()) {
   1600         // layers have been added
   1601         mVisibleRegionsDirty = true;
   1602     }
   1603 
   1604     // some layers might have been removed, so
   1605     // we need to update the regions they're exposing.
   1606     if (mLayersRemoved) {
   1607         mLayersRemoved = false;
   1608         mVisibleRegionsDirty = true;
   1609         const size_t count = layers.size();
   1610         for (size_t i=0 ; i<count ; i++) {
   1611             const sp<Layer>& layer(layers[i]);
   1612             if (currentLayers.indexOf(layer) < 0) {
   1613                 // this layer is not visible anymore
   1614                 // TODO: we could traverse the tree from front to back and
   1615                 //       compute the actual visible region
   1616                 // TODO: we could cache the transformed region
   1617                 const Layer::State& s(layer->getDrawingState());
   1618                 Region visibleReg = s.active.transform.transform(
   1619                         Region(Rect(s.active.w, s.active.h)));
   1620                 invalidateLayerStack(s.layerStack, visibleReg);
   1621             }
   1622         }
   1623     }
   1624 
   1625     commitTransaction();
   1626 
   1627     updateCursorAsync();
   1628 }
   1629 
   1630 void SurfaceFlinger::updateCursorAsync()
   1631 {
   1632     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
   1633         auto& displayDevice = mDisplays[displayId];
   1634         if (displayDevice->getHwcDisplayId() < 0) {
   1635             continue;
   1636         }
   1637 
   1638         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
   1639             layer->updateCursorPosition(displayDevice);
   1640         }
   1641     }
   1642 }
   1643 
   1644 void SurfaceFlinger::commitTransaction()
   1645 {
   1646     if (!mLayersPendingRemoval.isEmpty()) {
   1647         // Notify removed layers now that they can't be drawn from
   1648         for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
   1649             mLayersPendingRemoval[i]->onRemoved();
   1650         }
   1651         mLayersPendingRemoval.clear();
   1652     }
   1653 
   1654     // If this transaction is part of a window animation then the next frame
   1655     // we composite should be considered an animation as well.
   1656     mAnimCompositionPending = mAnimTransactionPending;
   1657 
   1658     mDrawingState = mCurrentState;
   1659     mTransactionPending = false;
   1660     mAnimTransactionPending = false;
   1661     mTransactionCV.broadcast();
   1662 }
   1663 
   1664 void SurfaceFlinger::computeVisibleRegions(
   1665         const LayerVector& currentLayers, uint32_t layerStack,
   1666         Region& outDirtyRegion, Region& outOpaqueRegion)
   1667 {
   1668     ATRACE_CALL();
   1669     ALOGV("computeVisibleRegions");
   1670 
   1671     Region aboveOpaqueLayers;
   1672     Region aboveCoveredLayers;
   1673     Region dirty;
   1674 
   1675     outDirtyRegion.clear();
   1676 
   1677     size_t i = currentLayers.size();
   1678     while (i--) {
   1679         const sp<Layer>& layer = currentLayers[i];
   1680 
   1681         // start with the whole surface at its current location
   1682         const Layer::State& s(layer->getDrawingState());
   1683 
   1684         // only consider the layers on the given layer stack
   1685         if (s.layerStack != layerStack)
   1686             continue;
   1687 
   1688         /*
   1689          * opaqueRegion: area of a surface that is fully opaque.
   1690          */
   1691         Region opaqueRegion;
   1692 
   1693         /*
   1694          * visibleRegion: area of a surface that is visible on screen
   1695          * and not fully transparent. This is essentially the layer's
   1696          * footprint minus the opaque regions above it.
   1697          * Areas covered by a translucent surface are considered visible.
   1698          */
   1699         Region visibleRegion;
   1700 
   1701         /*
   1702          * coveredRegion: area of a surface that is covered by all
   1703          * visible regions above it (which includes the translucent areas).
   1704          */
   1705         Region coveredRegion;
   1706 
   1707         /*
   1708          * transparentRegion: area of a surface that is hinted to be completely
   1709          * transparent. This is only used to tell when the layer has no visible
   1710          * non-transparent regions and can be removed from the layer list. It
   1711          * does not affect the visibleRegion of this layer or any layers
   1712          * beneath it. The hint may not be correct if apps don't respect the
   1713          * SurfaceView restrictions (which, sadly, some don't).
   1714          */
   1715         Region transparentRegion;
   1716 
   1717 
   1718         // handle hidden surfaces by setting the visible region to empty
   1719         if (CC_LIKELY(layer->isVisible())) {
   1720             const bool translucent = !layer->isOpaque(s);
   1721             Rect bounds(s.active.transform.transform(layer->computeBounds()));
   1722             visibleRegion.set(bounds);
   1723             if (!visibleRegion.isEmpty()) {
   1724                 // Remove the transparent area from the visible region
   1725                 if (translucent) {
   1726                     const Transform tr(s.active.transform);
   1727                     if (tr.preserveRects()) {
   1728                         // transform the transparent region
   1729                         transparentRegion = tr.transform(s.activeTransparentRegion);
   1730                     } else {
   1731                         // transformation too complex, can't do the
   1732                         // transparent region optimization.
   1733                         transparentRegion.clear();
   1734                     }
   1735                 }
   1736 
   1737                 // compute the opaque region
   1738                 const int32_t layerOrientation = s.active.transform.getOrientation();
   1739                 if (s.alpha == 1.0f && !translucent &&
   1740                         ((layerOrientation & Transform::ROT_INVALID) == false)) {
   1741                     // the opaque region is the layer's footprint
   1742                     opaqueRegion = visibleRegion;
   1743                 }
   1744             }
   1745         }
   1746 
   1747         // Clip the covered region to the visible region
   1748         coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
   1749 
   1750         // Update aboveCoveredLayers for next (lower) layer
   1751         aboveCoveredLayers.orSelf(visibleRegion);
   1752 
   1753         // subtract the opaque region covered by the layers above us
   1754         visibleRegion.subtractSelf(aboveOpaqueLayers);
   1755 
   1756         // compute this layer's dirty region
   1757         if (layer->contentDirty) {
   1758             // we need to invalidate the whole region
   1759             dirty = visibleRegion;
   1760             // as well, as the old visible region
   1761             dirty.orSelf(layer->visibleRegion);
   1762             layer->contentDirty = false;
   1763         } else {
   1764             /* compute the exposed region:
   1765              *   the exposed region consists of two components:
   1766              *   1) what's VISIBLE now and was COVERED before
   1767              *   2) what's EXPOSED now less what was EXPOSED before
   1768              *
   1769              * note that (1) is conservative, we start with the whole
   1770              * visible region but only keep what used to be covered by
   1771              * something -- which mean it may have been exposed.
   1772              *
   1773              * (2) handles areas that were not covered by anything but got
   1774              * exposed because of a resize.
   1775              */
   1776             const Region newExposed = visibleRegion - coveredRegion;
   1777             const Region oldVisibleRegion = layer->visibleRegion;
   1778             const Region oldCoveredRegion = layer->coveredRegion;
   1779             const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
   1780             dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
   1781         }
   1782         dirty.subtractSelf(aboveOpaqueLayers);
   1783 
   1784         // accumulate to the screen dirty region
   1785         outDirtyRegion.orSelf(dirty);
   1786 
   1787         // Update aboveOpaqueLayers for next (lower) layer
   1788         aboveOpaqueLayers.orSelf(opaqueRegion);
   1789 
   1790         // Store the visible region in screen space
   1791         layer->setVisibleRegion(visibleRegion);
   1792         layer->setCoveredRegion(coveredRegion);
   1793         layer->setVisibleNonTransparentRegion(
   1794                 visibleRegion.subtract(transparentRegion));
   1795     }
   1796 
   1797     outOpaqueRegion = aboveOpaqueLayers;
   1798 }
   1799 
   1800 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
   1801         const Region& dirty) {
   1802     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
   1803         const sp<DisplayDevice>& hw(mDisplays[dpy]);
   1804         if (hw->getLayerStack() == layerStack) {
   1805             hw->dirtyRegion.orSelf(dirty);
   1806         }
   1807     }
   1808 }
   1809 
   1810 bool SurfaceFlinger::handlePageFlip()
   1811 {
   1812     ALOGV("handlePageFlip");
   1813 
   1814     Region dirtyRegion;
   1815 
   1816     bool visibleRegions = false;
   1817     const LayerVector& layers(mDrawingState.layersSortedByZ);
   1818     bool frameQueued = false;
   1819 
   1820     // Store the set of layers that need updates. This set must not change as
   1821     // buffers are being latched, as this could result in a deadlock.
   1822     // Example: Two producers share the same command stream and:
   1823     // 1.) Layer 0 is latched
   1824     // 2.) Layer 0 gets a new frame
   1825     // 2.) Layer 1 gets a new frame
   1826     // 3.) Layer 1 is latched.
   1827     // Display is now waiting on Layer 1's frame, which is behind layer 0's
   1828     // second frame. But layer 0's second frame could be waiting on display.
   1829     for (size_t i = 0, count = layers.size(); i<count ; i++) {
   1830         const sp<Layer>& layer(layers[i]);
   1831         if (layer->hasQueuedFrame()) {
   1832             frameQueued = true;
   1833             if (layer->shouldPresentNow(mPrimaryDispSync)) {
   1834                 mLayersWithQueuedFrames.push_back(layer.get());
   1835             } else {
   1836                 layer->useEmptyDamage();
   1837             }
   1838         } else {
   1839             layer->useEmptyDamage();
   1840         }
   1841     }
   1842     for (auto& layer : mLayersWithQueuedFrames) {
   1843         const Region dirty(layer->latchBuffer(visibleRegions));
   1844         layer->useSurfaceDamage();
   1845         const Layer::State& s(layer->getDrawingState());
   1846         invalidateLayerStack(s.layerStack, dirty);
   1847     }
   1848 
   1849     mVisibleRegionsDirty |= visibleRegions;
   1850 
   1851     // If we will need to wake up at some time in the future to deal with a
   1852     // queued frame that shouldn't be displayed during this vsync period, wake
   1853     // up during the next vsync period to check again.
   1854     if (frameQueued && mLayersWithQueuedFrames.empty()) {
   1855         signalLayerUpdate();
   1856     }
   1857 
   1858     // Only continue with the refresh if there is actually new work to do
   1859     return !mLayersWithQueuedFrames.empty();
   1860 }
   1861 
   1862 void SurfaceFlinger::invalidateHwcGeometry()
   1863 {
   1864     mGeometryInvalid = true;
   1865 }
   1866 
   1867 
   1868 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
   1869         const Region& inDirtyRegion)
   1870 {
   1871     // We only need to actually compose the display if:
   1872     // 1) It is being handled by hardware composer, which may need this to
   1873     //    keep its virtual display state machine in sync, or
   1874     // 2) There is work to be done (the dirty region isn't empty)
   1875     bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
   1876     if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
   1877         ALOGV("Skipping display composition");
   1878         return;
   1879     }
   1880 
   1881     ALOGV("doDisplayComposition");
   1882 
   1883     Region dirtyRegion(inDirtyRegion);
   1884 
   1885     // compute the invalid region
   1886     hw->swapRegion.orSelf(dirtyRegion);
   1887 
   1888     uint32_t flags = hw->getFlags();
   1889     if (flags & DisplayDevice::SWAP_RECTANGLE) {
   1890         // we can redraw only what's dirty, but since SWAP_RECTANGLE only
   1891         // takes a rectangle, we must make sure to update that whole
   1892         // rectangle in that case
   1893         dirtyRegion.set(hw->swapRegion.bounds());
   1894     } else {
   1895         if (flags & DisplayDevice::PARTIAL_UPDATES) {
   1896             // We need to redraw the rectangle that will be updated
   1897             // (pushed to the framebuffer).
   1898             // This is needed because PARTIAL_UPDATES only takes one
   1899             // rectangle instead of a region (see DisplayDevice::flip())
   1900             dirtyRegion.set(hw->swapRegion.bounds());
   1901         } else {
   1902             // we need to redraw everything (the whole screen)
   1903             dirtyRegion.set(hw->bounds());
   1904             hw->swapRegion = dirtyRegion;
   1905         }
   1906     }
   1907 
   1908     if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
   1909         if (!doComposeSurfaces(hw, dirtyRegion)) return;
   1910     } else {
   1911         RenderEngine& engine(getRenderEngine());
   1912         mat4 colorMatrix = mColorMatrix;
   1913         if (mDaltonize) {
   1914             colorMatrix = colorMatrix * mDaltonizer();
   1915         }
   1916         mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
   1917         doComposeSurfaces(hw, dirtyRegion);
   1918         engine.setupColorTransform(oldMatrix);
   1919     }
   1920 
   1921     // update the swap region and clear the dirty region
   1922     hw->swapRegion.orSelf(dirtyRegion);
   1923 
   1924     // swap buffers (presentation)
   1925     hw->swapBuffers(getHwComposer());
   1926 }
   1927 
   1928 bool SurfaceFlinger::doComposeSurfaces(
   1929         const sp<const DisplayDevice>& displayDevice, const Region& dirty)
   1930 {
   1931     ALOGV("doComposeSurfaces");
   1932 
   1933     const auto hwcId = displayDevice->getHwcDisplayId();
   1934     bool hasClientComposition = mHwc->hasClientComposition(hwcId);
   1935     if (hasClientComposition) {
   1936         ALOGV("hasClientComposition");
   1937 
   1938         if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
   1939             ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
   1940                   displayDevice->getDisplayName().string());
   1941             eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
   1942             if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
   1943               ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
   1944             }
   1945             return false;
   1946         }
   1947 
   1948         // Never touch the framebuffer if we don't have any framebuffer layers
   1949         const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
   1950         if (hasDeviceComposition) {
   1951             // when using overlays, we assume a fully transparent framebuffer
   1952             // NOTE: we could reduce how much we need to clear, for instance
   1953             // remove where there are opaque FB layers. however, on some
   1954             // GPUs doing a "clean slate" clear might be more efficient.
   1955             // We'll revisit later if needed.
   1956             mRenderEngine->clearWithColor(0, 0, 0, 0);
   1957         } else {
   1958             // we start with the whole screen area
   1959             const Region bounds(displayDevice->getBounds());
   1960 
   1961             // we remove the scissor part
   1962             // we're left with the letterbox region
   1963             // (common case is that letterbox ends-up being empty)
   1964             const Region letterbox(bounds.subtract(displayDevice->getScissor()));
   1965 
   1966             // compute the area to clear
   1967             Region region(displayDevice->undefinedRegion.merge(letterbox));
   1968 
   1969             // but limit it to the dirty region
   1970             region.andSelf(dirty);
   1971 
   1972             // screen is already cleared here
   1973             if (!region.isEmpty()) {
   1974                 // can happen with SurfaceView
   1975                 drawWormhole(displayDevice, region);
   1976             }
   1977         }
   1978 
   1979         if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
   1980             // just to be on the safe side, we don't set the
   1981             // scissor on the main display. It should never be needed
   1982             // anyways (though in theory it could since the API allows it).
   1983             const Rect& bounds(displayDevice->getBounds());
   1984             const Rect& scissor(displayDevice->getScissor());
   1985             if (scissor != bounds) {
   1986                 // scissor doesn't match the screen's dimensions, so we
   1987                 // need to clear everything outside of it and enable
   1988                 // the GL scissor so we don't draw anything where we shouldn't
   1989 
   1990                 // enable scissor for this frame
   1991                 const uint32_t height = displayDevice->getHeight();
   1992                 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
   1993                         scissor.getWidth(), scissor.getHeight());
   1994             }
   1995         }
   1996     }
   1997 
   1998     /*
   1999      * and then, render the layers targeted at the framebuffer
   2000      */
   2001 
   2002     ALOGV("Rendering client layers");
   2003     const Transform& displayTransform = displayDevice->getTransform();
   2004     if (hwcId >= 0) {
   2005         // we're using h/w composer
   2006         bool firstLayer = true;
   2007         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
   2008             const Region clip(dirty.intersect(
   2009                     displayTransform.transform(layer->visibleRegion)));
   2010             ALOGV("Layer: %s", layer->getName().string());
   2011             ALOGV("  Composition type: %s",
   2012                     to_string(layer->getCompositionType(hwcId)).c_str());
   2013             if (!clip.isEmpty()) {
   2014                 switch (layer->getCompositionType(hwcId)) {
   2015                     case HWC2::Composition::Cursor:
   2016                     case HWC2::Composition::Device:
   2017                     case HWC2::Composition::SolidColor: {
   2018                         const Layer::State& state(layer->getDrawingState());
   2019                         if (layer->getClearClientTarget(hwcId) && !firstLayer &&
   2020                                 layer->isOpaque(state) && (state.alpha == 1.0f)
   2021                                 && hasClientComposition) {
   2022                             // never clear the very first layer since we're
   2023                             // guaranteed the FB is already cleared
   2024                             layer->clearWithOpenGL(displayDevice, clip);
   2025                         }
   2026                         break;
   2027                     }
   2028                     case HWC2::Composition::Client: {
   2029                         layer->draw(displayDevice, clip);
   2030                         break;
   2031                     }
   2032                     default:
   2033                         break;
   2034                 }
   2035             } else {
   2036                 ALOGV("  Skipping for empty clip");
   2037             }
   2038             firstLayer = false;
   2039         }
   2040     } else {
   2041         // we're not using h/w composer
   2042         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
   2043             const Region clip(dirty.intersect(
   2044                     displayTransform.transform(layer->visibleRegion)));
   2045             if (!clip.isEmpty()) {
   2046                 layer->draw(displayDevice, clip);
   2047             }
   2048         }
   2049     }
   2050 
   2051     // disable scissor at the end of the frame
   2052     mRenderEngine->disableScissor();
   2053     return true;
   2054 }
   2055 
   2056 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
   2057     const int32_t height = hw->getHeight();
   2058     RenderEngine& engine(getRenderEngine());
   2059     engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
   2060 }
   2061 
   2062 status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
   2063         const sp<IBinder>& handle,
   2064         const sp<IGraphicBufferProducer>& gbc,
   2065         const sp<Layer>& lbc)
   2066 {
   2067     // add this layer to the current state list
   2068     {
   2069         Mutex::Autolock _l(mStateLock);
   2070         if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
   2071             return NO_MEMORY;
   2072         }
   2073         mCurrentState.layersSortedByZ.add(lbc);
   2074         mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
   2075     }
   2076 
   2077     // attach this layer to the client
   2078     client->attachLayer(handle, lbc);
   2079 
   2080     return NO_ERROR;
   2081 }
   2082 
   2083 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
   2084     Mutex::Autolock _l(mStateLock);
   2085     ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
   2086     if (index >= 0) {
   2087         mLayersPendingRemoval.push(layer);
   2088         mLayersRemoved = true;
   2089         setTransactionFlags(eTransactionNeeded);
   2090         return NO_ERROR;
   2091     }
   2092     return status_t(index);
   2093 }
   2094 
   2095 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
   2096     return android_atomic_release_load(&mTransactionFlags);
   2097 }
   2098 
   2099 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
   2100     return android_atomic_and(~flags, &mTransactionFlags) & flags;
   2101 }
   2102 
   2103 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
   2104     uint32_t old = android_atomic_or(flags, &mTransactionFlags);
   2105     if ((old & flags)==0) { // wake the server up
   2106         signalTransaction();
   2107     }
   2108     return old;
   2109 }
   2110 
   2111 void SurfaceFlinger::setTransactionState(
   2112         const Vector<ComposerState>& state,
   2113         const Vector<DisplayState>& displays,
   2114         uint32_t flags)
   2115 {
   2116     ATRACE_CALL();
   2117     Mutex::Autolock _l(mStateLock);
   2118     uint32_t transactionFlags = 0;
   2119 
   2120     if (flags & eAnimation) {
   2121         // For window updates that are part of an animation we must wait for
   2122         // previous animation "frames" to be handled.
   2123         while (mAnimTransactionPending) {
   2124             status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
   2125             if (CC_UNLIKELY(err != NO_ERROR)) {
   2126                 // just in case something goes wrong in SF, return to the
   2127                 // caller after a few seconds.
   2128                 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
   2129                         "waiting for previous animation frame");
   2130                 mAnimTransactionPending = false;
   2131                 break;
   2132             }
   2133         }
   2134     }
   2135 
   2136     size_t count = displays.size();
   2137     for (size_t i=0 ; i<count ; i++) {
   2138         const DisplayState& s(displays[i]);
   2139         transactionFlags |= setDisplayStateLocked(s);
   2140     }
   2141 
   2142     count = state.size();
   2143     for (size_t i=0 ; i<count ; i++) {
   2144         const ComposerState& s(state[i]);
   2145         // Here we need to check that the interface we're given is indeed
   2146         // one of our own. A malicious client could give us a NULL
   2147         // IInterface, or one of its own or even one of our own but a
   2148         // different type. All these situations would cause us to crash.
   2149         //
   2150         // NOTE: it would be better to use RTTI as we could directly check
   2151         // that we have a Client*. however, RTTI is disabled in Android.
   2152         if (s.client != NULL) {
   2153             sp<IBinder> binder = IInterface::asBinder(s.client);
   2154             if (binder != NULL) {
   2155                 String16 desc(binder->getInterfaceDescriptor());
   2156                 if (desc == ISurfaceComposerClient::descriptor) {
   2157                     sp<Client> client( static_cast<Client *>(s.client.get()) );
   2158                     transactionFlags |= setClientStateLocked(client, s.state);
   2159                 }
   2160             }
   2161         }
   2162     }
   2163 
   2164     // If a synchronous transaction is explicitly requested without any changes,
   2165     // force a transaction anyway. This can be used as a flush mechanism for
   2166     // previous async transactions.
   2167     if (transactionFlags == 0 && (flags & eSynchronous)) {
   2168         transactionFlags = eTransactionNeeded;
   2169     }
   2170 
   2171     if (transactionFlags) {
   2172         // this triggers the transaction
   2173         setTransactionFlags(transactionFlags);
   2174 
   2175         // if this is a synchronous transaction, wait for it to take effect
   2176         // before returning.
   2177         if (flags & eSynchronous) {
   2178             mTransactionPending = true;
   2179         }
   2180         if (flags & eAnimation) {
   2181             mAnimTransactionPending = true;
   2182         }
   2183         while (mTransactionPending) {
   2184             status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
   2185             if (CC_UNLIKELY(err != NO_ERROR)) {
   2186                 // just in case something goes wrong in SF, return to the
   2187                 // called after a few seconds.
   2188                 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
   2189                 mTransactionPending = false;
   2190                 break;
   2191             }
   2192         }
   2193     }
   2194 }
   2195 
   2196 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
   2197 {
   2198     ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
   2199     if (dpyIdx < 0)
   2200         return 0;
   2201 
   2202     uint32_t flags = 0;
   2203     DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
   2204     if (disp.isValid()) {
   2205         const uint32_t what = s.what;
   2206         if (what & DisplayState::eSurfaceChanged) {
   2207             if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
   2208                 disp.surface = s.surface;
   2209                 flags |= eDisplayTransactionNeeded;
   2210             }
   2211         }
   2212         if (what & DisplayState::eLayerStackChanged) {
   2213             if (disp.layerStack != s.layerStack) {
   2214                 disp.layerStack = s.layerStack;
   2215                 flags |= eDisplayTransactionNeeded;
   2216             }
   2217         }
   2218         if (what & DisplayState::eDisplayProjectionChanged) {
   2219             if (disp.orientation != s.orientation) {
   2220                 disp.orientation = s.orientation;
   2221                 flags |= eDisplayTransactionNeeded;
   2222             }
   2223             if (disp.frame != s.frame) {
   2224                 disp.frame = s.frame;
   2225                 flags |= eDisplayTransactionNeeded;
   2226             }
   2227             if (disp.viewport != s.viewport) {
   2228                 disp.viewport = s.viewport;
   2229                 flags |= eDisplayTransactionNeeded;
   2230             }
   2231         }
   2232         if (what & DisplayState::eDisplaySizeChanged) {
   2233             if (disp.width != s.width) {
   2234                 disp.width = s.width;
   2235                 flags |= eDisplayTransactionNeeded;
   2236             }
   2237             if (disp.height != s.height) {
   2238                 disp.height = s.height;
   2239                 flags |= eDisplayTransactionNeeded;
   2240             }
   2241         }
   2242     }
   2243     return flags;
   2244 }
   2245 
   2246 uint32_t SurfaceFlinger::setClientStateLocked(
   2247         const sp<Client>& client,
   2248         const layer_state_t& s)
   2249 {
   2250     uint32_t flags = 0;
   2251     sp<Layer> layer(client->getLayerUser(s.surface));
   2252     if (layer != 0) {
   2253         const uint32_t what = s.what;
   2254         bool positionAppliesWithResize =
   2255                 what & layer_state_t::ePositionAppliesWithResize;
   2256         if (what & layer_state_t::ePositionChanged) {
   2257             if (layer->setPosition(s.x, s.y, !positionAppliesWithResize)) {
   2258                 flags |= eTraversalNeeded;
   2259             }
   2260         }
   2261         if (what & layer_state_t::eLayerChanged) {
   2262             // NOTE: index needs to be calculated before we update the state
   2263             ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
   2264             if (layer->setLayer(s.z) && idx >= 0) {
   2265                 mCurrentState.layersSortedByZ.removeAt(idx);
   2266                 mCurrentState.layersSortedByZ.add(layer);
   2267                 // we need traversal (state changed)
   2268                 // AND transaction (list changed)
   2269                 flags |= eTransactionNeeded|eTraversalNeeded;
   2270             }
   2271         }
   2272         if (what & layer_state_t::eSizeChanged) {
   2273             if (layer->setSize(s.w, s.h)) {
   2274                 flags |= eTraversalNeeded;
   2275             }
   2276         }
   2277         if (what & layer_state_t::eAlphaChanged) {
   2278             if (layer->setAlpha(s.alpha))
   2279                 flags |= eTraversalNeeded;
   2280         }
   2281         if (what & layer_state_t::eMatrixChanged) {
   2282             if (layer->setMatrix(s.matrix))
   2283                 flags |= eTraversalNeeded;
   2284         }
   2285         if (what & layer_state_t::eTransparentRegionChanged) {
   2286             if (layer->setTransparentRegionHint(s.transparentRegion))
   2287                 flags |= eTraversalNeeded;
   2288         }
   2289         if (what & layer_state_t::eFlagsChanged) {
   2290             if (layer->setFlags(s.flags, s.mask))
   2291                 flags |= eTraversalNeeded;
   2292         }
   2293         if (what & layer_state_t::eCropChanged) {
   2294             if (layer->setCrop(s.crop))
   2295                 flags |= eTraversalNeeded;
   2296         }
   2297         if (what & layer_state_t::eFinalCropChanged) {
   2298             if (layer->setFinalCrop(s.finalCrop))
   2299                 flags |= eTraversalNeeded;
   2300         }
   2301         if (what & layer_state_t::eLayerStackChanged) {
   2302             // NOTE: index needs to be calculated before we update the state
   2303             ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
   2304             if (layer->setLayerStack(s.layerStack) && idx >= 0) {
   2305                 mCurrentState.layersSortedByZ.removeAt(idx);
   2306                 mCurrentState.layersSortedByZ.add(layer);
   2307                 // we need traversal (state changed)
   2308                 // AND transaction (list changed)
   2309                 flags |= eTransactionNeeded|eTraversalNeeded;
   2310             }
   2311         }
   2312         if (what & layer_state_t::eDeferTransaction) {
   2313             layer->deferTransactionUntil(s.handle, s.frameNumber);
   2314             // We don't trigger a traversal here because if no other state is
   2315             // changed, we don't want this to cause any more work
   2316         }
   2317         if (what & layer_state_t::eOverrideScalingModeChanged) {
   2318             layer->setOverrideScalingMode(s.overrideScalingMode);
   2319             // We don't trigger a traversal here because if no other state is
   2320             // changed, we don't want this to cause any more work
   2321         }
   2322     }
   2323     return flags;
   2324 }
   2325 
   2326 status_t SurfaceFlinger::createLayer(
   2327         const String8& name,
   2328         const sp<Client>& client,
   2329         uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
   2330         sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
   2331 {
   2332     //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
   2333     if (int32_t(w|h) < 0) {
   2334         ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
   2335                 int(w), int(h));
   2336         return BAD_VALUE;
   2337     }
   2338 
   2339     status_t result = NO_ERROR;
   2340 
   2341     sp<Layer> layer;
   2342 
   2343     switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
   2344         case ISurfaceComposerClient::eFXSurfaceNormal:
   2345             result = createNormalLayer(client,
   2346                     name, w, h, flags, format,
   2347                     handle, gbp, &layer);
   2348             break;
   2349         case ISurfaceComposerClient::eFXSurfaceDim:
   2350             result = createDimLayer(client,
   2351                     name, w, h, flags,
   2352                     handle, gbp, &layer);
   2353             break;
   2354         default:
   2355             result = BAD_VALUE;
   2356             break;
   2357     }
   2358 
   2359     if (result != NO_ERROR) {
   2360         return result;
   2361     }
   2362 
   2363     result = addClientLayer(client, *handle, *gbp, layer);
   2364     if (result != NO_ERROR) {
   2365         return result;
   2366     }
   2367 
   2368     setTransactionFlags(eTransactionNeeded);
   2369     return result;
   2370 }
   2371 
   2372 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
   2373         const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
   2374         sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
   2375 {
   2376     // initialize the surfaces
   2377     switch (format) {
   2378     case PIXEL_FORMAT_TRANSPARENT:
   2379     case PIXEL_FORMAT_TRANSLUCENT:
   2380         format = PIXEL_FORMAT_RGBA_8888;
   2381         break;
   2382     case PIXEL_FORMAT_OPAQUE:
   2383         format = PIXEL_FORMAT_RGBX_8888;
   2384         break;
   2385     }
   2386 
   2387     *outLayer = new Layer(this, client, name, w, h, flags);
   2388     status_t err = (*outLayer)->setBuffers(w, h, format, flags);
   2389     if (err == NO_ERROR) {
   2390         *handle = (*outLayer)->getHandle();
   2391         *gbp = (*outLayer)->getProducer();
   2392     }
   2393 
   2394     ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
   2395     return err;
   2396 }
   2397 
   2398 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
   2399         const String8& name, uint32_t w, uint32_t h, uint32_t flags,
   2400         sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
   2401 {
   2402     *outLayer = new LayerDim(this, client, name, w, h, flags);
   2403     *handle = (*outLayer)->getHandle();
   2404     *gbp = (*outLayer)->getProducer();
   2405     return NO_ERROR;
   2406 }
   2407 
   2408 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
   2409 {
   2410     // called by the window manager when it wants to remove a Layer
   2411     status_t err = NO_ERROR;
   2412     sp<Layer> l(client->getLayerUser(handle));
   2413     if (l != NULL) {
   2414         err = removeLayer(l);
   2415         ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
   2416                 "error removing layer=%p (%s)", l.get(), strerror(-err));
   2417     }
   2418     return err;
   2419 }
   2420 
   2421 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
   2422 {
   2423     // called by ~LayerCleaner() when all references to the IBinder (handle)
   2424     // are gone
   2425     status_t err = NO_ERROR;
   2426     sp<Layer> l(layer.promote());
   2427     if (l != NULL) {
   2428         err = removeLayer(l);
   2429         ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
   2430                 "error removing layer=%p (%s)", l.get(), strerror(-err));
   2431     }
   2432     return err;
   2433 }
   2434 
   2435 // ---------------------------------------------------------------------------
   2436 
   2437 void SurfaceFlinger::onInitializeDisplays() {
   2438     // reset screen orientation and use primary layer stack
   2439     Vector<ComposerState> state;
   2440     Vector<DisplayState> displays;
   2441     DisplayState d;
   2442     d.what = DisplayState::eDisplayProjectionChanged |
   2443              DisplayState::eLayerStackChanged;
   2444     d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
   2445     d.layerStack = 0;
   2446     d.orientation = DisplayState::eOrientationDefault;
   2447     d.frame.makeInvalid();
   2448     d.viewport.makeInvalid();
   2449     d.width = 0;
   2450     d.height = 0;
   2451     displays.add(d);
   2452     setTransactionState(state, displays, 0);
   2453     setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
   2454 
   2455     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
   2456     const nsecs_t period = activeConfig->getVsyncPeriod();
   2457     mAnimFrameTracker.setDisplayRefreshPeriod(period);
   2458 }
   2459 
   2460 void SurfaceFlinger::initializeDisplays() {
   2461     class MessageScreenInitialized : public MessageBase {
   2462         SurfaceFlinger* flinger;
   2463     public:
   2464         MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
   2465         virtual bool handler() {
   2466             flinger->onInitializeDisplays();
   2467             return true;
   2468         }
   2469     };
   2470     sp<MessageBase> msg = new MessageScreenInitialized(this);
   2471     postMessageAsync(msg);  // we may be called from main thread, use async message
   2472 }
   2473 
   2474 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
   2475         int mode) {
   2476     ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
   2477             this);
   2478     int32_t type = hw->getDisplayType();
   2479     int currentMode = hw->getPowerMode();
   2480 
   2481     if (mode == currentMode) {
   2482         ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
   2483         return;
   2484     }
   2485 
   2486     hw->setPowerMode(mode);
   2487     if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
   2488         ALOGW("Trying to set power mode for virtual display");
   2489         return;
   2490     }
   2491 
   2492     if (currentMode == HWC_POWER_MODE_OFF) {
   2493         getHwComposer().setPowerMode(type, mode);
   2494         if (type == DisplayDevice::DISPLAY_PRIMARY) {
   2495             // FIXME: eventthread only knows about the main display right now
   2496             mEventThread->onScreenAcquired();
   2497             resyncToHardwareVsync(true);
   2498         }
   2499 
   2500         mVisibleRegionsDirty = true;
   2501         mHasPoweredOff = true;
   2502         repaintEverything();
   2503     } else if (mode == HWC_POWER_MODE_OFF) {
   2504         if (type == DisplayDevice::DISPLAY_PRIMARY) {
   2505             disableHardwareVsync(true); // also cancels any in-progress resync
   2506 
   2507             // FIXME: eventthread only knows about the main display right now
   2508             mEventThread->onScreenReleased();
   2509         }
   2510 
   2511         getHwComposer().setPowerMode(type, mode);
   2512         mVisibleRegionsDirty = true;
   2513         // from this point on, SF will stop drawing on this display
   2514     } else {
   2515         getHwComposer().setPowerMode(type, mode);
   2516     }
   2517 }
   2518 
   2519 void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
   2520     class MessageSetPowerMode: public MessageBase {
   2521         SurfaceFlinger& mFlinger;
   2522         sp<IBinder> mDisplay;
   2523         int mMode;
   2524     public:
   2525         MessageSetPowerMode(SurfaceFlinger& flinger,
   2526                 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
   2527                     mDisplay(disp) { mMode = mode; }
   2528         virtual bool handler() {
   2529             sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
   2530             if (hw == NULL) {
   2531                 ALOGE("Attempt to set power mode = %d for null display %p",
   2532                         mMode, mDisplay.get());
   2533             } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
   2534                 ALOGW("Attempt to set power mode = %d for virtual display",
   2535                         mMode);
   2536             } else {
   2537                 mFlinger.setPowerModeInternal(hw, mMode);
   2538             }
   2539             return true;
   2540         }
   2541     };
   2542     sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
   2543     postMessageSync(msg);
   2544 }
   2545 
   2546 // ---------------------------------------------------------------------------
   2547 
   2548 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
   2549 {
   2550     String8 result;
   2551 
   2552     IPCThreadState* ipc = IPCThreadState::self();
   2553     const int pid = ipc->getCallingPid();
   2554     const int uid = ipc->getCallingUid();
   2555     if ((uid != AID_SHELL) &&
   2556             !PermissionCache::checkPermission(sDump, pid, uid)) {
   2557         result.appendFormat("Permission Denial: "
   2558                 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
   2559     } else {
   2560         // Try to get the main lock, but give up after one second
   2561         // (this would indicate SF is stuck, but we want to be able to
   2562         // print something in dumpsys).
   2563         status_t err = mStateLock.timedLock(s2ns(1));
   2564         bool locked = (err == NO_ERROR);
   2565         if (!locked) {
   2566             result.appendFormat(
   2567                     "SurfaceFlinger appears to be unresponsive (%s [%d]), "
   2568                     "dumping anyways (no locks held)\n", strerror(-err), err);
   2569         }
   2570 
   2571         bool dumpAll = true;
   2572         size_t index = 0;
   2573         size_t numArgs = args.size();
   2574         if (numArgs) {
   2575             if ((index < numArgs) &&
   2576                     (args[index] == String16("--list"))) {
   2577                 index++;
   2578                 listLayersLocked(args, index, result);
   2579                 dumpAll = false;
   2580             }
   2581 
   2582             if ((index < numArgs) &&
   2583                     (args[index] == String16("--latency"))) {
   2584                 index++;
   2585                 dumpStatsLocked(args, index, result);
   2586                 dumpAll = false;
   2587             }
   2588 
   2589             if ((index < numArgs) &&
   2590                     (args[index] == String16("--latency-clear"))) {
   2591                 index++;
   2592                 clearStatsLocked(args, index, result);
   2593                 dumpAll = false;
   2594             }
   2595 
   2596             if ((index < numArgs) &&
   2597                     (args[index] == String16("--dispsync"))) {
   2598                 index++;
   2599                 mPrimaryDispSync.dump(result);
   2600                 dumpAll = false;
   2601             }
   2602 
   2603             if ((index < numArgs) &&
   2604                     (args[index] == String16("--static-screen"))) {
   2605                 index++;
   2606                 dumpStaticScreenStats(result);
   2607                 dumpAll = false;
   2608             }
   2609 
   2610 #ifdef ENABLE_FENCE_TRACKING
   2611             if ((index < numArgs) &&
   2612                     (args[index] == String16("--fences"))) {
   2613                 index++;
   2614                 mFenceTracker.dump(&result);
   2615                 dumpAll = false;
   2616             }
   2617 #endif
   2618         }
   2619 
   2620         if (dumpAll) {
   2621             dumpAllLocked(args, index, result);
   2622         }
   2623 
   2624         if (locked) {
   2625             mStateLock.unlock();
   2626         }
   2627     }
   2628     write(fd, result.string(), result.size());
   2629     return NO_ERROR;
   2630 }
   2631 
   2632 void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
   2633         size_t& /* index */, String8& result) const
   2634 {
   2635     const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
   2636     const size_t count = currentLayers.size();
   2637     for (size_t i=0 ; i<count ; i++) {
   2638         const sp<Layer>& layer(currentLayers[i]);
   2639         result.appendFormat("%s\n", layer->getName().string());
   2640     }
   2641 }
   2642 
   2643 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
   2644         String8& result) const
   2645 {
   2646     String8 name;
   2647     if (index < args.size()) {
   2648         name = String8(args[index]);
   2649         index++;
   2650     }
   2651 
   2652     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
   2653     const nsecs_t period = activeConfig->getVsyncPeriod();
   2654     result.appendFormat("%" PRId64 "\n", period);
   2655 
   2656     if (name.isEmpty()) {
   2657         mAnimFrameTracker.dumpStats(result);
   2658     } else {
   2659         const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
   2660         const size_t count = currentLayers.size();
   2661         for (size_t i=0 ; i<count ; i++) {
   2662             const sp<Layer>& layer(currentLayers[i]);
   2663             if (name == layer->getName()) {
   2664                 layer->dumpFrameStats(result);
   2665             }
   2666         }
   2667     }
   2668 }
   2669 
   2670 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
   2671         String8& /* result */)
   2672 {
   2673     String8 name;
   2674     if (index < args.size()) {
   2675         name = String8(args[index]);
   2676         index++;
   2677     }
   2678 
   2679     const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
   2680     const size_t count = currentLayers.size();
   2681     for (size_t i=0 ; i<count ; i++) {
   2682         const sp<Layer>& layer(currentLayers[i]);
   2683         if (name.isEmpty() || (name == layer->getName())) {
   2684             layer->clearFrameStats();
   2685         }
   2686     }
   2687 
   2688     mAnimFrameTracker.clearStats();
   2689 }
   2690 
   2691 // This should only be called from the main thread.  Otherwise it would need
   2692 // the lock and should use mCurrentState rather than mDrawingState.
   2693 void SurfaceFlinger::logFrameStats() {
   2694     const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
   2695     const size_t count = drawingLayers.size();
   2696     for (size_t i=0 ; i<count ; i++) {
   2697         const sp<Layer>& layer(drawingLayers[i]);
   2698         layer->logFrameStats();
   2699     }
   2700 
   2701     mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
   2702 }
   2703 
   2704 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
   2705 {
   2706     static const char* config =
   2707             " [sf"
   2708 #ifdef HAS_CONTEXT_PRIORITY
   2709             " HAS_CONTEXT_PRIORITY"
   2710 #endif
   2711 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
   2712             " NEVER_DEFAULT_TO_ASYNC_MODE"
   2713 #endif
   2714 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
   2715             " TARGET_DISABLE_TRIPLE_BUFFERING"
   2716 #endif
   2717             "]";
   2718     result.append(config);
   2719 }
   2720 
   2721 void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
   2722 {
   2723     result.appendFormat("Static screen stats:\n");
   2724     for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
   2725         float bucketTimeSec = mFrameBuckets[b] / 1e9;
   2726         float percent = 100.0f *
   2727                 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
   2728         result.appendFormat("  < %zd frames: %.3f s (%.1f%%)\n",
   2729                 b + 1, bucketTimeSec, percent);
   2730     }
   2731     float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
   2732     float percent = 100.0f *
   2733             static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
   2734     result.appendFormat("  %zd+ frames: %.3f s (%.1f%%)\n",
   2735             NUM_BUCKETS - 1, bucketTimeSec, percent);
   2736 }
   2737 
   2738 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
   2739         String8& result) const
   2740 {
   2741     bool colorize = false;
   2742     if (index < args.size()
   2743             && (args[index] == String16("--color"))) {
   2744         colorize = true;
   2745         index++;
   2746     }
   2747 
   2748     Colorizer colorizer(colorize);
   2749 
   2750     // figure out if we're stuck somewhere
   2751     const nsecs_t now = systemTime();
   2752     const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
   2753     const nsecs_t inTransaction(mDebugInTransaction);
   2754     nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
   2755     nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
   2756 
   2757     /*
   2758      * Dump library configuration.
   2759      */
   2760 
   2761     colorizer.bold(result);
   2762     result.append("Build configuration:");
   2763     colorizer.reset(result);
   2764     appendSfConfigString(result);
   2765     appendUiConfigString(result);
   2766     appendGuiConfigString(result);
   2767     result.append("\n");
   2768 
   2769     colorizer.bold(result);
   2770     result.append("Sync configuration: ");
   2771     colorizer.reset(result);
   2772     result.append(SyncFeatures::getInstance().toString());
   2773     result.append("\n");
   2774 
   2775     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
   2776 
   2777     colorizer.bold(result);
   2778     result.append("DispSync configuration: ");
   2779     colorizer.reset(result);
   2780     result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
   2781             "present offset %d ns (refresh %" PRId64 " ns)",
   2782         vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
   2783         PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
   2784     result.append("\n");
   2785 
   2786     // Dump static screen stats
   2787     result.append("\n");
   2788     dumpStaticScreenStats(result);
   2789     result.append("\n");
   2790 
   2791     /*
   2792      * Dump the visible layer list
   2793      */
   2794     const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
   2795     const size_t count = currentLayers.size();
   2796     colorizer.bold(result);
   2797     result.appendFormat("Visible layers (count = %zu)\n", count);
   2798     colorizer.reset(result);
   2799     for (size_t i=0 ; i<count ; i++) {
   2800         const sp<Layer>& layer(currentLayers[i]);
   2801         layer->dump(result, colorizer);
   2802     }
   2803 
   2804     /*
   2805      * Dump Display state
   2806      */
   2807 
   2808     colorizer.bold(result);
   2809     result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
   2810     colorizer.reset(result);
   2811     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
   2812         const sp<const DisplayDevice>& hw(mDisplays[dpy]);
   2813         hw->dump(result);
   2814     }
   2815 
   2816     /*
   2817      * Dump SurfaceFlinger global state
   2818      */
   2819 
   2820     colorizer.bold(result);
   2821     result.append("SurfaceFlinger global state:\n");
   2822     colorizer.reset(result);
   2823 
   2824     HWComposer& hwc(getHwComposer());
   2825     sp<const DisplayDevice> hw(getDefaultDisplayDevice());
   2826 
   2827     colorizer.bold(result);
   2828     result.appendFormat("EGL implementation : %s\n",
   2829             eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
   2830     colorizer.reset(result);
   2831     result.appendFormat("%s\n",
   2832             eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
   2833 
   2834     mRenderEngine->dump(result);
   2835 
   2836     hw->undefinedRegion.dump(result, "undefinedRegion");
   2837     result.appendFormat("  orientation=%d, isDisplayOn=%d\n",
   2838             hw->getOrientation(), hw->isDisplayOn());
   2839     result.appendFormat(
   2840             "  last eglSwapBuffers() time: %f us\n"
   2841             "  last transaction time     : %f us\n"
   2842             "  transaction-flags         : %08x\n"
   2843             "  refresh-rate              : %f fps\n"
   2844             "  x-dpi                     : %f\n"
   2845             "  y-dpi                     : %f\n"
   2846             "  gpu_to_cpu_unsupported    : %d\n"
   2847             ,
   2848             mLastSwapBufferTime/1000.0,
   2849             mLastTransactionTime/1000.0,
   2850             mTransactionFlags,
   2851             1e9 / activeConfig->getVsyncPeriod(),
   2852             activeConfig->getDpiX(),
   2853             activeConfig->getDpiY(),
   2854             !mGpuToCpuSupported);
   2855 
   2856     result.appendFormat("  eglSwapBuffers time: %f us\n",
   2857             inSwapBuffersDuration/1000.0);
   2858 
   2859     result.appendFormat("  transaction time: %f us\n",
   2860             inTransactionDuration/1000.0);
   2861 
   2862     /*
   2863      * VSYNC state
   2864      */
   2865     mEventThread->dump(result);
   2866 
   2867     /*
   2868      * Dump HWComposer state
   2869      */
   2870     colorizer.bold(result);
   2871     result.append("h/w composer state:\n");
   2872     colorizer.reset(result);
   2873     bool hwcDisabled = mDebugDisableHWC || mDebugRegion || mDaltonize ||
   2874             mHasColorMatrix;
   2875     result.appendFormat("  h/w composer %s\n",
   2876             hwcDisabled ? "disabled" : "enabled");
   2877     hwc.dump(result);
   2878 
   2879     /*
   2880      * Dump gralloc state
   2881      */
   2882     const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
   2883     alloc.dump(result);
   2884 }
   2885 
   2886 const Vector< sp<Layer> >&
   2887 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
   2888     // Note: mStateLock is held here
   2889     wp<IBinder> dpy;
   2890     for (size_t i=0 ; i<mDisplays.size() ; i++) {
   2891         if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
   2892             dpy = mDisplays.keyAt(i);
   2893             break;
   2894         }
   2895     }
   2896     if (dpy == NULL) {
   2897         ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
   2898         // Just use the primary display so we have something to return
   2899         dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
   2900     }
   2901     return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
   2902 }
   2903 
   2904 bool SurfaceFlinger::startDdmConnection()
   2905 {
   2906     void* libddmconnection_dso =
   2907             dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
   2908     if (!libddmconnection_dso) {
   2909         return false;
   2910     }
   2911     void (*DdmConnection_start)(const char* name);
   2912     DdmConnection_start =
   2913             (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
   2914     if (!DdmConnection_start) {
   2915         dlclose(libddmconnection_dso);
   2916         return false;
   2917     }
   2918     (*DdmConnection_start)(getServiceName());
   2919     return true;
   2920 }
   2921 
   2922 status_t SurfaceFlinger::onTransact(
   2923     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
   2924 {
   2925     switch (code) {
   2926         case CREATE_CONNECTION:
   2927         case CREATE_DISPLAY:
   2928         case SET_TRANSACTION_STATE:
   2929         case BOOT_FINISHED:
   2930         case CLEAR_ANIMATION_FRAME_STATS:
   2931         case GET_ANIMATION_FRAME_STATS:
   2932         case SET_POWER_MODE:
   2933         case GET_HDR_CAPABILITIES:
   2934         {
   2935             // codes that require permission check
   2936             IPCThreadState* ipc = IPCThreadState::self();
   2937             const int pid = ipc->getCallingPid();
   2938             const int uid = ipc->getCallingUid();
   2939             if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
   2940                     !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
   2941                 ALOGE("Permission Denial: "
   2942                         "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
   2943                 return PERMISSION_DENIED;
   2944             }
   2945             break;
   2946         }
   2947         case CAPTURE_SCREEN:
   2948         {
   2949             // codes that require permission check
   2950             IPCThreadState* ipc = IPCThreadState::self();
   2951             const int pid = ipc->getCallingPid();
   2952             const int uid = ipc->getCallingUid();
   2953             if ((uid != AID_GRAPHICS) &&
   2954                     !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
   2955                 ALOGE("Permission Denial: "
   2956                         "can't read framebuffer pid=%d, uid=%d", pid, uid);
   2957                 return PERMISSION_DENIED;
   2958             }
   2959             break;
   2960         }
   2961     }
   2962 
   2963     status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
   2964     if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
   2965         CHECK_INTERFACE(ISurfaceComposer, data, reply);
   2966         if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
   2967             IPCThreadState* ipc = IPCThreadState::self();
   2968             const int pid = ipc->getCallingPid();
   2969             const int uid = ipc->getCallingUid();
   2970             ALOGE("Permission Denial: "
   2971                     "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
   2972             return PERMISSION_DENIED;
   2973         }
   2974         int n;
   2975         switch (code) {
   2976             case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
   2977             case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
   2978                 return NO_ERROR;
   2979             case 1002:  // SHOW_UPDATES
   2980                 n = data.readInt32();
   2981                 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
   2982                 invalidateHwcGeometry();
   2983                 repaintEverything();
   2984                 return NO_ERROR;
   2985             case 1004:{ // repaint everything
   2986                 repaintEverything();
   2987                 return NO_ERROR;
   2988             }
   2989             case 1005:{ // force transaction
   2990                 setTransactionFlags(
   2991                         eTransactionNeeded|
   2992                         eDisplayTransactionNeeded|
   2993                         eTraversalNeeded);
   2994                 return NO_ERROR;
   2995             }
   2996             case 1006:{ // send empty update
   2997                 signalRefresh();
   2998                 return NO_ERROR;
   2999             }
   3000             case 1008:  // toggle use of hw composer
   3001                 n = data.readInt32();
   3002                 mDebugDisableHWC = n ? 1 : 0;
   3003                 invalidateHwcGeometry();
   3004                 repaintEverything();
   3005                 return NO_ERROR;
   3006             case 1009:  // toggle use of transform hint
   3007                 n = data.readInt32();
   3008                 mDebugDisableTransformHint = n ? 1 : 0;
   3009                 invalidateHwcGeometry();
   3010                 repaintEverything();
   3011                 return NO_ERROR;
   3012             case 1010:  // interrogate.
   3013                 reply->writeInt32(0);
   3014                 reply->writeInt32(0);
   3015                 reply->writeInt32(mDebugRegion);
   3016                 reply->writeInt32(0);
   3017                 reply->writeInt32(mDebugDisableHWC);
   3018                 return NO_ERROR;
   3019             case 1013: {
   3020                 Mutex::Autolock _l(mStateLock);
   3021                 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
   3022                 reply->writeInt32(hw->getPageFlipCount());
   3023                 return NO_ERROR;
   3024             }
   3025             case 1014: {
   3026                 // daltonize
   3027                 n = data.readInt32();
   3028                 switch (n % 10) {
   3029                     case 1: mDaltonizer.setType(Daltonizer::protanomaly);   break;
   3030                     case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
   3031                     case 3: mDaltonizer.setType(Daltonizer::tritanomaly);   break;
   3032                 }
   3033                 if (n >= 10) {
   3034                     mDaltonizer.setMode(Daltonizer::correction);
   3035                 } else {
   3036                     mDaltonizer.setMode(Daltonizer::simulation);
   3037                 }
   3038                 mDaltonize = n > 0;
   3039                 invalidateHwcGeometry();
   3040                 repaintEverything();
   3041                 return NO_ERROR;
   3042             }
   3043             case 1015: {
   3044                 // apply a color matrix
   3045                 n = data.readInt32();
   3046                 mHasColorMatrix = n ? 1 : 0;
   3047                 if (n) {
   3048                     // color matrix is sent as mat3 matrix followed by vec3
   3049                     // offset, then packed into a mat4 where the last row is
   3050                     // the offset and extra values are 0
   3051                     for (size_t i = 0 ; i < 4; i++) {
   3052                       for (size_t j = 0; j < 4; j++) {
   3053                           mColorMatrix[i][j] = data.readFloat();
   3054                       }
   3055                     }
   3056                 } else {
   3057                     mColorMatrix = mat4();
   3058                 }
   3059                 invalidateHwcGeometry();
   3060                 repaintEverything();
   3061                 return NO_ERROR;
   3062             }
   3063             // This is an experimental interface
   3064             // Needs to be shifted to proper binder interface when we productize
   3065             case 1016: {
   3066                 n = data.readInt32();
   3067                 mPrimaryDispSync.setRefreshSkipCount(n);
   3068                 return NO_ERROR;
   3069             }
   3070             case 1017: {
   3071                 n = data.readInt32();
   3072                 mForceFullDamage = static_cast<bool>(n);
   3073                 return NO_ERROR;
   3074             }
   3075             case 1018: { // Modify Choreographer's phase offset
   3076                 n = data.readInt32();
   3077                 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
   3078                 return NO_ERROR;
   3079             }
   3080             case 1019: { // Modify SurfaceFlinger's phase offset
   3081                 n = data.readInt32();
   3082                 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
   3083                 return NO_ERROR;
   3084             }
   3085         }
   3086     }
   3087     return err;
   3088 }
   3089 
   3090 void SurfaceFlinger::repaintEverything() {
   3091     android_atomic_or(1, &mRepaintEverything);
   3092     signalTransaction();
   3093 }
   3094 
   3095 // ---------------------------------------------------------------------------
   3096 // Capture screen into an IGraphiBufferProducer
   3097 // ---------------------------------------------------------------------------
   3098 
   3099 /* The code below is here to handle b/8734824
   3100  *
   3101  * We create a IGraphicBufferProducer wrapper that forwards all calls
   3102  * from the surfaceflinger thread to the calling binder thread, where they
   3103  * are executed. This allows the calling thread in the calling process to be
   3104  * reused and not depend on having "enough" binder threads to handle the
   3105  * requests.
   3106  */
   3107 class GraphicProducerWrapper : public BBinder, public MessageHandler {
   3108     /* Parts of GraphicProducerWrapper are run on two different threads,
   3109      * communicating by sending messages via Looper but also by shared member
   3110      * data. Coherence maintenance is subtle and in places implicit (ugh).
   3111      *
   3112      * Don't rely on Looper's sendMessage/handleMessage providing
   3113      * release/acquire semantics for any data not actually in the Message.
   3114      * Data going from surfaceflinger to binder threads needs to be
   3115      * synchronized explicitly.
   3116      *
   3117      * Barrier open/wait do provide release/acquire semantics. This provides
   3118      * implicit synchronization for data coming back from binder to
   3119      * surfaceflinger threads.
   3120      */
   3121 
   3122     sp<IGraphicBufferProducer> impl;
   3123     sp<Looper> looper;
   3124     status_t result;
   3125     bool exitPending;
   3126     bool exitRequested;
   3127     Barrier barrier;
   3128     uint32_t code;
   3129     Parcel const* data;
   3130     Parcel* reply;
   3131 
   3132     enum {
   3133         MSG_API_CALL,
   3134         MSG_EXIT
   3135     };
   3136 
   3137     /*
   3138      * Called on surfaceflinger thread. This is called by our "fake"
   3139      * BpGraphicBufferProducer. We package the data and reply Parcel and
   3140      * forward them to the binder thread.
   3141      */
   3142     virtual status_t transact(uint32_t code,
   3143             const Parcel& data, Parcel* reply, uint32_t /* flags */) {
   3144         this->code = code;
   3145         this->data = &data;
   3146         this->reply = reply;
   3147         if (exitPending) {
   3148             // if we've exited, we run the message synchronously right here.
   3149             // note (JH): as far as I can tell from looking at the code, this
   3150             // never actually happens. if it does, i'm not sure if it happens
   3151             // on the surfaceflinger or binder thread.
   3152             handleMessage(Message(MSG_API_CALL));
   3153         } else {
   3154             barrier.close();
   3155             // Prevent stores to this->{code, data, reply} from being
   3156             // reordered later than the construction of Message.
   3157             atomic_thread_fence(memory_order_release);
   3158             looper->sendMessage(this, Message(MSG_API_CALL));
   3159             barrier.wait();
   3160         }
   3161         return result;
   3162     }
   3163 
   3164     /*
   3165      * here we run on the binder thread. All we've got to do is
   3166      * call the real BpGraphicBufferProducer.
   3167      */
   3168     virtual void handleMessage(const Message& message) {
   3169         int what = message.what;
   3170         // Prevent reads below from happening before the read from Message
   3171         atomic_thread_fence(memory_order_acquire);
   3172         if (what == MSG_API_CALL) {
   3173             result = IInterface::asBinder(impl)->transact(code, data[0], reply);
   3174             barrier.open();
   3175         } else if (what == MSG_EXIT) {
   3176             exitRequested = true;
   3177         }
   3178     }
   3179 
   3180 public:
   3181     GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
   3182     :   impl(impl),
   3183         looper(new Looper(true)),
   3184         result(NO_ERROR),
   3185         exitPending(false),
   3186         exitRequested(false),
   3187         code(0),
   3188         data(NULL),
   3189         reply(NULL)
   3190     {}
   3191 
   3192     // Binder thread
   3193     status_t waitForResponse() {
   3194         do {
   3195             looper->pollOnce(-1);
   3196         } while (!exitRequested);
   3197         return result;
   3198     }
   3199 
   3200     // Client thread
   3201     void exit(status_t result) {
   3202         this->result = result;
   3203         exitPending = true;
   3204         // Ensure this->result is visible to the binder thread before it
   3205         // handles the message.
   3206         atomic_thread_fence(memory_order_release);
   3207         looper->sendMessage(this, Message(MSG_EXIT));
   3208     }
   3209 };
   3210 
   3211 
   3212 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
   3213         const sp<IGraphicBufferProducer>& producer,
   3214         Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
   3215         uint32_t minLayerZ, uint32_t maxLayerZ,
   3216         bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
   3217 
   3218     if (CC_UNLIKELY(display == 0))
   3219         return BAD_VALUE;
   3220 
   3221     if (CC_UNLIKELY(producer == 0))
   3222         return BAD_VALUE;
   3223 
   3224     // if we have secure windows on this display, never allow the screen capture
   3225     // unless the producer interface is local (i.e.: we can take a screenshot for
   3226     // ourselves).
   3227     bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
   3228 
   3229     // Convert to surfaceflinger's internal rotation type.
   3230     Transform::orientation_flags rotationFlags;
   3231     switch (rotation) {
   3232         case ISurfaceComposer::eRotateNone:
   3233             rotationFlags = Transform::ROT_0;
   3234             break;
   3235         case ISurfaceComposer::eRotate90:
   3236             rotationFlags = Transform::ROT_90;
   3237             break;
   3238         case ISurfaceComposer::eRotate180:
   3239             rotationFlags = Transform::ROT_180;
   3240             break;
   3241         case ISurfaceComposer::eRotate270:
   3242             rotationFlags = Transform::ROT_270;
   3243             break;
   3244         default:
   3245             rotationFlags = Transform::ROT_0;
   3246             ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
   3247             break;
   3248     }
   3249 
   3250     class MessageCaptureScreen : public MessageBase {
   3251         SurfaceFlinger* flinger;
   3252         sp<IBinder> display;
   3253         sp<IGraphicBufferProducer> producer;
   3254         Rect sourceCrop;
   3255         uint32_t reqWidth, reqHeight;
   3256         uint32_t minLayerZ,maxLayerZ;
   3257         bool useIdentityTransform;
   3258         Transform::orientation_flags rotation;
   3259         status_t result;
   3260         bool isLocalScreenshot;
   3261     public:
   3262         MessageCaptureScreen(SurfaceFlinger* flinger,
   3263                 const sp<IBinder>& display,
   3264                 const sp<IGraphicBufferProducer>& producer,
   3265                 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
   3266                 uint32_t minLayerZ, uint32_t maxLayerZ,
   3267                 bool useIdentityTransform,
   3268                 Transform::orientation_flags rotation,
   3269                 bool isLocalScreenshot)
   3270             : flinger(flinger), display(display), producer(producer),
   3271               sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
   3272               minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
   3273               useIdentityTransform(useIdentityTransform),
   3274               rotation(rotation), result(PERMISSION_DENIED),
   3275               isLocalScreenshot(isLocalScreenshot)
   3276         {
   3277         }
   3278         status_t getResult() const {
   3279             return result;
   3280         }
   3281         virtual bool handler() {
   3282             Mutex::Autolock _l(flinger->mStateLock);
   3283             sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
   3284             result = flinger->captureScreenImplLocked(hw, producer,
   3285                     sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
   3286                     useIdentityTransform, rotation, isLocalScreenshot);
   3287             static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
   3288             return true;
   3289         }
   3290     };
   3291 
   3292     // this creates a "fake" BBinder which will serve as a "fake" remote
   3293     // binder to receive the marshaled calls and forward them to the
   3294     // real remote (a BpGraphicBufferProducer)
   3295     sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
   3296 
   3297     // the asInterface() call below creates our "fake" BpGraphicBufferProducer
   3298     // which does the marshaling work forwards to our "fake remote" above.
   3299     sp<MessageBase> msg = new MessageCaptureScreen(this,
   3300             display, IGraphicBufferProducer::asInterface( wrapper ),
   3301             sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
   3302             useIdentityTransform, rotationFlags, isLocalScreenshot);
   3303 
   3304     status_t res = postMessageAsync(msg);
   3305     if (res == NO_ERROR) {
   3306         res = wrapper->waitForResponse();
   3307     }
   3308     return res;
   3309 }
   3310 
   3311 
   3312 void SurfaceFlinger::renderScreenImplLocked(
   3313         const sp<const DisplayDevice>& hw,
   3314         Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
   3315         uint32_t minLayerZ, uint32_t maxLayerZ,
   3316         bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
   3317 {
   3318     ATRACE_CALL();
   3319     RenderEngine& engine(getRenderEngine());
   3320 
   3321     // get screen geometry
   3322     const int32_t hw_w = hw->getWidth();
   3323     const int32_t hw_h = hw->getHeight();
   3324     const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
   3325                            static_cast<int32_t>(reqHeight) != hw_h;
   3326 
   3327     // if a default or invalid sourceCrop is passed in, set reasonable values
   3328     if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
   3329             !sourceCrop.isValid()) {
   3330         sourceCrop.setLeftTop(Point(0, 0));
   3331         sourceCrop.setRightBottom(Point(hw_w, hw_h));
   3332     }
   3333 
   3334     // ensure that sourceCrop is inside screen
   3335     if (sourceCrop.left < 0) {
   3336         ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
   3337     }
   3338     if (sourceCrop.right > hw_w) {
   3339         ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
   3340     }
   3341     if (sourceCrop.top < 0) {
   3342         ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
   3343     }
   3344     if (sourceCrop.bottom > hw_h) {
   3345         ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
   3346     }
   3347 
   3348     // make sure to clear all GL error flags
   3349     engine.checkErrors();
   3350 
   3351     // set-up our viewport
   3352     engine.setViewportAndProjection(
   3353         reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
   3354     engine.disableTexturing();
   3355 
   3356     // redraw the screen entirely...
   3357     engine.clearWithColor(0, 0, 0, 1);
   3358 
   3359     const LayerVector& layers( mDrawingState.layersSortedByZ );
   3360     const size_t count = layers.size();
   3361     for (size_t i=0 ; i<count ; ++i) {
   3362         const sp<Layer>& layer(layers[i]);
   3363         const Layer::State& state(layer->getDrawingState());
   3364         if (state.layerStack == hw->getLayerStack()) {
   3365             if (state.z >= minLayerZ && state.z <= maxLayerZ) {
   3366                 if (layer->isVisible()) {
   3367                     if (filtering) layer->setFiltering(true);
   3368                     layer->draw(hw, useIdentityTransform);
   3369                     if (filtering) layer->setFiltering(false);
   3370                 }
   3371             }
   3372         }
   3373     }
   3374 
   3375     hw->setViewportAndProjection();
   3376 }
   3377 
   3378 
   3379 status_t SurfaceFlinger::captureScreenImplLocked(
   3380         const sp<const DisplayDevice>& hw,
   3381         const sp<IGraphicBufferProducer>& producer,
   3382         Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
   3383         uint32_t minLayerZ, uint32_t maxLayerZ,
   3384         bool useIdentityTransform, Transform::orientation_flags rotation,
   3385         bool isLocalScreenshot)
   3386 {
   3387     ATRACE_CALL();
   3388 
   3389     // get screen geometry
   3390     uint32_t hw_w = hw->getWidth();
   3391     uint32_t hw_h = hw->getHeight();
   3392 
   3393     if (rotation & Transform::ROT_90) {
   3394         std::swap(hw_w, hw_h);
   3395     }
   3396 
   3397     if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
   3398         ALOGE("size mismatch (%d, %d) > (%d, %d)",
   3399                 reqWidth, reqHeight, hw_w, hw_h);
   3400         return BAD_VALUE;
   3401     }
   3402 
   3403     reqWidth  = (!reqWidth)  ? hw_w : reqWidth;
   3404     reqHeight = (!reqHeight) ? hw_h : reqHeight;
   3405 
   3406     bool secureLayerIsVisible = false;
   3407     const LayerVector& layers(mDrawingState.layersSortedByZ);
   3408     const size_t count = layers.size();
   3409     for (size_t i = 0 ; i < count ; ++i) {
   3410         const sp<Layer>& layer(layers[i]);
   3411         const Layer::State& state(layer->getDrawingState());
   3412         if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
   3413                 state.z <= maxLayerZ && layer->isVisible() &&
   3414                 layer->isSecure()) {
   3415             secureLayerIsVisible = true;
   3416         }
   3417     }
   3418 
   3419     if (!isLocalScreenshot && secureLayerIsVisible) {
   3420         ALOGW("FB is protected: PERMISSION_DENIED");
   3421         return PERMISSION_DENIED;
   3422     }
   3423 
   3424     // create a surface (because we're a producer, and we need to
   3425     // dequeue/queue a buffer)
   3426     sp<Surface> sur = new Surface(producer, false);
   3427     ANativeWindow* window = sur.get();
   3428 
   3429     status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
   3430     if (result == NO_ERROR) {
   3431         uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
   3432                         GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
   3433 
   3434         int err = 0;
   3435         err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
   3436         err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
   3437         err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
   3438         err |= native_window_set_usage(window, usage);
   3439 
   3440         if (err == NO_ERROR) {
   3441             ANativeWindowBuffer* buffer;
   3442             /* TODO: Once we have the sync framework everywhere this can use
   3443              * server-side waits on the fence that dequeueBuffer returns.
   3444              */
   3445             result = native_window_dequeue_buffer_and_wait(window,  &buffer);
   3446             if (result == NO_ERROR) {
   3447                 int syncFd = -1;
   3448                 // create an EGLImage from the buffer so we can later
   3449                 // turn it into a texture
   3450                 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
   3451                         EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
   3452                 if (image != EGL_NO_IMAGE_KHR) {
   3453                     // this binds the given EGLImage as a framebuffer for the
   3454                     // duration of this scope.
   3455                     RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
   3456                     if (imageBond.getStatus() == NO_ERROR) {
   3457                         // this will in fact render into our dequeued buffer
   3458                         // via an FBO, which means we didn't have to create
   3459                         // an EGLSurface and therefore we're not
   3460                         // dependent on the context's EGLConfig.
   3461                         renderScreenImplLocked(
   3462                             hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
   3463                             useIdentityTransform, rotation);
   3464 
   3465                         // Attempt to create a sync khr object that can produce a sync point. If that
   3466                         // isn't available, create a non-dupable sync object in the fallback path and
   3467                         // wait on it directly.
   3468                         EGLSyncKHR sync;
   3469                         if (!DEBUG_SCREENSHOTS) {
   3470                            sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
   3471                            // native fence fd will not be populated until flush() is done.
   3472                            getRenderEngine().flush();
   3473                         } else {
   3474                             sync = EGL_NO_SYNC_KHR;
   3475                         }
   3476                         if (sync != EGL_NO_SYNC_KHR) {
   3477                             // get the sync fd
   3478                             syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
   3479                             if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
   3480                                 ALOGW("captureScreen: failed to dup sync khr object");
   3481                                 syncFd = -1;
   3482                             }
   3483                             eglDestroySyncKHR(mEGLDisplay, sync);
   3484                         } else {
   3485                             // fallback path
   3486                             sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
   3487                             if (sync != EGL_NO_SYNC_KHR) {
   3488                                 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
   3489                                     EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
   3490                                 EGLint eglErr = eglGetError();
   3491                                 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
   3492                                     ALOGW("captureScreen: fence wait timed out");
   3493                                 } else {
   3494                                     ALOGW_IF(eglErr != EGL_SUCCESS,
   3495                                             "captureScreen: error waiting on EGL fence: %#x", eglErr);
   3496                                 }
   3497                                 eglDestroySyncKHR(mEGLDisplay, sync);
   3498                             } else {
   3499                                 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
   3500                             }
   3501                         }
   3502                         if (DEBUG_SCREENSHOTS) {
   3503                             uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
   3504                             getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
   3505                             checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
   3506                                     hw, minLayerZ, maxLayerZ);
   3507                             delete [] pixels;
   3508                         }
   3509 
   3510                     } else {
   3511                         ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
   3512                         result = INVALID_OPERATION;
   3513                         window->cancelBuffer(window, buffer, syncFd);
   3514                         buffer = NULL;
   3515                     }
   3516                     // destroy our image
   3517                     eglDestroyImageKHR(mEGLDisplay, image);
   3518                 } else {
   3519                     result = BAD_VALUE;
   3520                 }
   3521                 if (buffer) {
   3522                     // queueBuffer takes ownership of syncFd
   3523                     result = window->queueBuffer(window, buffer, syncFd);
   3524                 }
   3525             }
   3526         } else {
   3527             result = BAD_VALUE;
   3528         }
   3529         native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
   3530     }
   3531 
   3532     return result;
   3533 }
   3534 
   3535 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
   3536         const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
   3537     if (DEBUG_SCREENSHOTS) {
   3538         for (size_t y=0 ; y<h ; y++) {
   3539             uint32_t const * p = (uint32_t const *)vaddr + y*s;
   3540             for (size_t x=0 ; x<w ; x++) {
   3541                 if (p[x] != 0xFF000000) return;
   3542             }
   3543         }
   3544         ALOGE("*** we just took a black screenshot ***\n"
   3545                 "requested minz=%d, maxz=%d, layerStack=%d",
   3546                 minLayerZ, maxLayerZ, hw->getLayerStack());
   3547         const LayerVector& layers( mDrawingState.layersSortedByZ );
   3548         const size_t count = layers.size();
   3549         for (size_t i=0 ; i<count ; ++i) {
   3550             const sp<Layer>& layer(layers[i]);
   3551             const Layer::State& state(layer->getDrawingState());
   3552             const bool visible = (state.layerStack == hw->getLayerStack())
   3553                                 && (state.z >= minLayerZ && state.z <= maxLayerZ)
   3554                                 && (layer->isVisible());
   3555             ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
   3556                     visible ? '+' : '-',
   3557                             i, layer->getName().string(), state.layerStack, state.z,
   3558                             layer->isVisible(), state.flags, state.alpha);
   3559         }
   3560     }
   3561 }
   3562 
   3563 // ---------------------------------------------------------------------------
   3564 
   3565 SurfaceFlinger::LayerVector::LayerVector() {
   3566 }
   3567 
   3568 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
   3569     : SortedVector<sp<Layer> >(rhs) {
   3570 }
   3571 
   3572 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
   3573     const void* rhs) const
   3574 {
   3575     // sort layers per layer-stack, then by z-order and finally by sequence
   3576     const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
   3577     const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
   3578 
   3579     uint32_t ls = l->getCurrentState().layerStack;
   3580     uint32_t rs = r->getCurrentState().layerStack;
   3581     if (ls != rs)
   3582         return ls - rs;
   3583 
   3584     uint32_t lz = l->getCurrentState().z;
   3585     uint32_t rz = r->getCurrentState().z;
   3586     if (lz != rz)
   3587         return lz - rz;
   3588 
   3589     return l->sequence - r->sequence;
   3590 }
   3591 
   3592 // ---------------------------------------------------------------------------
   3593 
   3594 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
   3595     : type(DisplayDevice::DISPLAY_ID_INVALID),
   3596       layerStack(DisplayDevice::NO_LAYER_STACK),
   3597       orientation(0),
   3598       width(0),
   3599       height(0),
   3600       isSecure(false) {
   3601 }
   3602 
   3603 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
   3604     DisplayDevice::DisplayType type, bool isSecure)
   3605     : type(type),
   3606       layerStack(DisplayDevice::NO_LAYER_STACK),
   3607       orientation(0),
   3608       width(0),
   3609       height(0),
   3610       isSecure(isSecure) {
   3611     viewport.makeInvalid();
   3612     frame.makeInvalid();
   3613 }
   3614 
   3615 // ---------------------------------------------------------------------------
   3616 
   3617 }; // namespace android
   3618 
   3619 
   3620 #if defined(__gl_h_)
   3621 #error "don't include gl/gl.h in this file"
   3622 #endif
   3623 
   3624 #if defined(__gl2_h_)
   3625 #error "don't include gl2/gl2.h in this file"
   3626 #endif
   3627