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