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