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