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