SurfaceFlinger.cpp revision 55801e41e6d7306d75d8134dd69d7d8cbbfbc63c
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
24#include <EGL/egl.h>
25#include <GLES/gl.h>
26
27#include <cutils/log.h>
28#include <cutils/properties.h>
29
30#include <binder/IPCThreadState.h>
31#include <binder/IServiceManager.h>
32#include <binder/MemoryHeapBase.h>
33#include <binder/PermissionCache.h>
34
35#include <ui/DisplayInfo.h>
36
37#include <gui/BitTube.h>
38#include <gui/BufferQueue.h>
39#include <gui/IDisplayEventConnection.h>
40#include <gui/SurfaceTextureClient.h>
41
42#include <ui/GraphicBufferAllocator.h>
43#include <ui/PixelFormat.h>
44
45#include <utils/String8.h>
46#include <utils/String16.h>
47#include <utils/StopWatch.h>
48#include <utils/Trace.h>
49
50#include <private/android_filesystem_config.h>
51
52#include "clz.h"
53#include "DdmConnection.h"
54#include "DisplayDevice.h"
55#include "Client.h"
56#include "EventThread.h"
57#include "GLExtensions.h"
58#include "Layer.h"
59#include "LayerDim.h"
60#include "LayerScreenshot.h"
61#include "SurfaceFlinger.h"
62
63#include "DisplayHardware/FramebufferSurface.h"
64#include "DisplayHardware/HWComposer.h"
65
66
67#define EGL_VERSION_HW_ANDROID  0x3143
68
69#define DISPLAY_COUNT       1
70
71namespace android {
72// ---------------------------------------------------------------------------
73
74const String16 sHardwareTest("android.permission.HARDWARE_TEST");
75const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
76const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
77const String16 sDump("android.permission.DUMP");
78
79// ---------------------------------------------------------------------------
80
81SurfaceFlinger::SurfaceFlinger()
82    :   BnSurfaceComposer(), Thread(false),
83        mTransactionFlags(0),
84        mTransationPending(false),
85        mLayersRemoved(false),
86        mRepaintEverything(0),
87        mBootTime(systemTime()),
88        mVisibleRegionsDirty(false),
89        mHwWorkListDirty(false),
90        mDebugRegion(0),
91        mDebugDDMS(0),
92        mDebugDisableHWC(0),
93        mDebugDisableTransformHint(0),
94        mDebugInSwapBuffers(0),
95        mLastSwapBufferTime(0),
96        mDebugInTransaction(0),
97        mLastTransactionTime(0),
98        mBootFinished(false)
99{
100    ALOGI("SurfaceFlinger is starting");
101
102    // debugging stuff...
103    char value[PROPERTY_VALUE_MAX];
104
105    property_get("debug.sf.showupdates", value, "0");
106    mDebugRegion = atoi(value);
107
108    property_get("debug.sf.ddms", value, "0");
109    mDebugDDMS = atoi(value);
110    if (mDebugDDMS) {
111        DdmConnection::start(getServiceName());
112    }
113
114    ALOGI_IF(mDebugRegion, "showupdates enabled");
115    ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
116}
117
118void SurfaceFlinger::onFirstRef()
119{
120    mEventQueue.init(this);
121
122    run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
123
124    // Wait for the main thread to be done with its initialization
125    mReadyToRunBarrier.wait();
126}
127
128
129SurfaceFlinger::~SurfaceFlinger()
130{
131    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
132    eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
133    eglTerminate(display);
134}
135
136void SurfaceFlinger::binderDied(const wp<IBinder>& who)
137{
138    // the window manager died on us. prepare its eulogy.
139
140    // restore initial conditions (default device unblank, etc)
141    initializeDisplays();
142
143    // restart the boot-animation
144    startBootAnim();
145}
146
147sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
148{
149    sp<ISurfaceComposerClient> bclient;
150    sp<Client> client(new Client(this));
151    status_t err = client->initCheck();
152    if (err == NO_ERROR) {
153        bclient = client;
154    }
155    return bclient;
156}
157
158sp<IBinder> SurfaceFlinger::createDisplay()
159{
160    class DisplayToken : public BBinder {
161        sp<SurfaceFlinger> flinger;
162        virtual ~DisplayToken() {
163             // no more references, this display must be terminated
164             Mutex::Autolock _l(flinger->mStateLock);
165             flinger->mCurrentState.displays.removeItem(this);
166             flinger->setTransactionFlags(eDisplayTransactionNeeded);
167         }
168     public:
169        DisplayToken(const sp<SurfaceFlinger>& flinger)
170            : flinger(flinger) {
171        }
172    };
173
174    sp<BBinder> token = new DisplayToken(this);
175
176    Mutex::Autolock _l(mStateLock);
177    DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
178    mCurrentState.displays.add(token, info);
179
180    return token;
181}
182
183sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
184    if (uint32_t(id) >= DisplayDevice::NUM_DISPLAY_TYPES) {
185        ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
186        return NULL;
187    }
188    return mDefaultDisplays[id];
189}
190
191sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
192{
193    sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
194    return gba;
195}
196
197void SurfaceFlinger::bootFinished()
198{
199    const nsecs_t now = systemTime();
200    const nsecs_t duration = now - mBootTime;
201    ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
202    mBootFinished = true;
203
204    // wait patiently for the window manager death
205    const String16 name("window");
206    sp<IBinder> window(defaultServiceManager()->getService(name));
207    if (window != 0) {
208        window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
209    }
210
211    // stop boot animation
212    // formerly we would just kill the process, but we now ask it to exit so it
213    // can choose where to stop the animation.
214    property_set("service.bootanim.exit", "1");
215}
216
217void SurfaceFlinger::deleteTextureAsync(GLuint texture) {
218    class MessageDestroyGLTexture : public MessageBase {
219        GLuint texture;
220    public:
221        MessageDestroyGLTexture(GLuint texture)
222            : texture(texture) {
223        }
224        virtual bool handler() {
225            glDeleteTextures(1, &texture);
226            return true;
227        }
228    };
229    postMessageAsync(new MessageDestroyGLTexture(texture));
230}
231
232status_t SurfaceFlinger::selectConfigForPixelFormat(
233        EGLDisplay dpy,
234        EGLint const* attrs,
235        PixelFormat format,
236        EGLConfig* outConfig)
237{
238    EGLConfig config = NULL;
239    EGLint numConfigs = -1, n=0;
240    eglGetConfigs(dpy, NULL, 0, &numConfigs);
241    EGLConfig* const configs = new EGLConfig[numConfigs];
242    eglChooseConfig(dpy, attrs, configs, numConfigs, &n);
243    for (int i=0 ; i<n ; i++) {
244        EGLint nativeVisualId = 0;
245        eglGetConfigAttrib(dpy, configs[i], EGL_NATIVE_VISUAL_ID, &nativeVisualId);
246        if (nativeVisualId>0 && format == nativeVisualId) {
247            *outConfig = configs[i];
248            delete [] configs;
249            return NO_ERROR;
250        }
251    }
252    delete [] configs;
253    return NAME_NOT_FOUND;
254}
255
256EGLConfig SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId) {
257    // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
258    // it is to be used with WIFI displays
259    EGLConfig config;
260    EGLint dummy;
261    status_t err;
262    EGLint attribs[] = {
263            EGL_SURFACE_TYPE,           EGL_WINDOW_BIT,
264            EGL_RECORDABLE_ANDROID,     EGL_TRUE,
265            EGL_NONE
266    };
267    err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config);
268    if (err) {
269        // maybe we failed because of EGL_RECORDABLE_ANDROID
270        ALOGW("couldn't find an EGLConfig with EGL_RECORDABLE_ANDROID");
271        attribs[2] = EGL_NONE;
272        err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config);
273    }
274    ALOGE_IF(err, "couldn't find an EGLConfig matching the screen format");
275    if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy) == EGL_TRUE) {
276        ALOGW_IF(dummy == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
277    }
278    return config;
279}
280
281EGLContext SurfaceFlinger::createGLContext(EGLDisplay display, EGLConfig config) {
282    // Also create our EGLContext
283    EGLint contextAttributes[] = {
284#ifdef EGL_IMG_context_priority
285#ifdef HAS_CONTEXT_PRIORITY
286#warning "using EGL_IMG_context_priority"
287            EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_HIGH_IMG,
288#endif
289#endif
290            EGL_NONE, EGL_NONE
291    };
292    EGLContext ctxt = eglCreateContext(display, config, NULL, contextAttributes);
293    ALOGE_IF(ctxt==EGL_NO_CONTEXT, "EGLContext creation failed");
294    return ctxt;
295}
296
297void SurfaceFlinger::initializeGL(EGLDisplay display, EGLSurface surface) {
298    EGLBoolean result = eglMakeCurrent(display, surface, surface, mEGLContext);
299    if (!result) {
300        ALOGE("Couldn't create a working GLES context. check logs. exiting...");
301        exit(0);
302    }
303
304    GLExtensions& extensions(GLExtensions::getInstance());
305    extensions.initWithGLStrings(
306            glGetString(GL_VENDOR),
307            glGetString(GL_RENDERER),
308            glGetString(GL_VERSION),
309            glGetString(GL_EXTENSIONS),
310            eglQueryString(display, EGL_VENDOR),
311            eglQueryString(display, EGL_VERSION),
312            eglQueryString(display, EGL_EXTENSIONS));
313
314    EGLint w, h;
315    eglQuerySurface(display, surface, EGL_WIDTH,  &w);
316    eglQuerySurface(display, surface, EGL_HEIGHT, &h);
317
318    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
319    glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims);
320
321    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
322    glPixelStorei(GL_PACK_ALIGNMENT, 4);
323    glEnableClientState(GL_VERTEX_ARRAY);
324    glShadeModel(GL_FLAT);
325    glDisable(GL_DITHER);
326    glDisable(GL_CULL_FACE);
327
328    struct pack565 {
329        inline uint16_t operator() (int r, int g, int b) const {
330            return (r<<11)|(g<<5)|b;
331        }
332    } pack565;
333
334    const uint16_t protTexData[] = { pack565(0x03, 0x03, 0x03) };
335    glGenTextures(1, &mProtectedTexName);
336    glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
337    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
338    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
339    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
340    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
341    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0,
342            GL_RGB, GL_UNSIGNED_SHORT_5_6_5, protTexData);
343
344    glViewport(0, 0, w, h);
345    glMatrixMode(GL_PROJECTION);
346    glLoadIdentity();
347    // put the origin in the left-bottom corner
348    glOrthof(0, w, 0, h, 0, 1); // l=0, r=w ; b=0, t=h
349
350    // print some debugging info
351    EGLint r,g,b,a;
352    eglGetConfigAttrib(display, mEGLConfig, EGL_RED_SIZE,   &r);
353    eglGetConfigAttrib(display, mEGLConfig, EGL_GREEN_SIZE, &g);
354    eglGetConfigAttrib(display, mEGLConfig, EGL_BLUE_SIZE,  &b);
355    eglGetConfigAttrib(display, mEGLConfig, EGL_ALPHA_SIZE, &a);
356    ALOGI("EGL informations:");
357    ALOGI("vendor    : %s", extensions.getEglVendor());
358    ALOGI("version   : %s", extensions.getEglVersion());
359    ALOGI("extensions: %s", extensions.getEglExtension());
360    ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported");
361    ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig);
362    ALOGI("OpenGL ES informations:");
363    ALOGI("vendor    : %s", extensions.getVendor());
364    ALOGI("renderer  : %s", extensions.getRenderer());
365    ALOGI("version   : %s", extensions.getVersion());
366    ALOGI("extensions: %s", extensions.getExtension());
367    ALOGI("GL_MAX_TEXTURE_SIZE = %d", mMaxTextureSize);
368    ALOGI("GL_MAX_VIEWPORT_DIMS = %d x %d", mMaxViewportDims[0], mMaxViewportDims[1]);
369}
370
371status_t SurfaceFlinger::readyToRun()
372{
373    ALOGI(  "SurfaceFlinger's main thread ready to run. "
374            "Initializing graphics H/W...");
375
376    // initialize EGL
377    mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
378    eglInitialize(mEGLDisplay, NULL, NULL);
379
380    // Initialize the main display
381    // create native window to main display
382    sp<FramebufferSurface> fbs = FramebufferSurface::create();
383    if (fbs == NULL) {
384        ALOGE("Display subsystem failed to initialize. check logs. exiting...");
385        exit(0);
386    }
387
388    sp<SurfaceTextureClient> stc(new SurfaceTextureClient(
389            static_cast<sp<ISurfaceTexture> >(fbs->getBufferQueue())));
390
391    // initialize the config and context
392    int format;
393    ANativeWindow* const anw = stc.get();
394    anw->query(anw, NATIVE_WINDOW_FORMAT, &format);
395    mEGLConfig  = selectEGLConfig(mEGLDisplay, format);
396    mEGLContext = createGLContext(mEGLDisplay, mEGLConfig);
397
398    // initialize our main display hardware
399
400    for (size_t i=0 ; i<DisplayDevice::NUM_DISPLAY_TYPES ; i++) {
401        mDefaultDisplays[i] = new BBinder();
402        mCurrentState.displays.add(mDefaultDisplays[i],
403                DisplayDeviceState((DisplayDevice::DisplayType)i));
404    }
405    sp<DisplayDevice> hw = new DisplayDevice(this,
406            DisplayDevice::DISPLAY_PRIMARY,
407            mDefaultDisplays[DisplayDevice::DISPLAY_PRIMARY],
408            anw, fbs, mEGLConfig);
409    mDisplays.add(mDefaultDisplays[DisplayDevice::DISPLAY_PRIMARY], hw);
410
411    //  initialize OpenGL ES
412    EGLSurface surface = hw->getEGLSurface();
413    initializeGL(mEGLDisplay, surface);
414
415    // start the EventThread
416    mEventThread = new EventThread(this);
417    mEventQueue.setEventThread(mEventThread);
418
419    // initialize the H/W composer
420    mHwc = new HWComposer(this,
421            *static_cast<HWComposer::EventHandler *>(this),
422            fbs->getFbHal());
423
424    // initialize our drawing state
425    mDrawingState = mCurrentState;
426
427    // We're now ready to accept clients...
428    mReadyToRunBarrier.open();
429
430    // set initial conditions (e.g. unblank default device)
431    initializeDisplays();
432
433    // start boot animation
434    startBootAnim();
435
436    return NO_ERROR;
437}
438
439int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
440    return (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) ?
441            type : mHwc->allocateDisplayId();
442}
443
444void SurfaceFlinger::startBootAnim() {
445    // start boot animation
446    property_set("service.bootanim.exit", "0");
447    property_set("ctl.start", "bootanim");
448}
449
450uint32_t SurfaceFlinger::getMaxTextureSize() const {
451    return mMaxTextureSize;
452}
453
454uint32_t SurfaceFlinger::getMaxViewportDims() const {
455    return mMaxViewportDims[0] < mMaxViewportDims[1] ?
456            mMaxViewportDims[0] : mMaxViewportDims[1];
457}
458
459// ----------------------------------------------------------------------------
460
461bool SurfaceFlinger::authenticateSurfaceTexture(
462        const sp<ISurfaceTexture>& surfaceTexture) const {
463    Mutex::Autolock _l(mStateLock);
464    sp<IBinder> surfaceTextureBinder(surfaceTexture->asBinder());
465
466    // Check the visible layer list for the ISurface
467    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
468    size_t count = currentLayers.size();
469    for (size_t i=0 ; i<count ; i++) {
470        const sp<LayerBase>& layer(currentLayers[i]);
471        sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
472        if (lbc != NULL) {
473            wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
474            if (lbcBinder == surfaceTextureBinder) {
475                return true;
476            }
477        }
478    }
479
480    // Check the layers in the purgatory.  This check is here so that if a
481    // SurfaceTexture gets destroyed before all the clients are done using it,
482    // the error will not be reported as "surface XYZ is not authenticated", but
483    // will instead fail later on when the client tries to use the surface,
484    // which should be reported as "surface XYZ returned an -ENODEV".  The
485    // purgatorized layers are no less authentic than the visible ones, so this
486    // should not cause any harm.
487    size_t purgatorySize =  mLayerPurgatory.size();
488    for (size_t i=0 ; i<purgatorySize ; i++) {
489        const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
490        sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
491        if (lbc != NULL) {
492            wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
493            if (lbcBinder == surfaceTextureBinder) {
494                return true;
495            }
496        }
497    }
498
499    return false;
500}
501
502status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info) {
503    // TODO: this is mostly here only for compatibility
504    //       the display size is needed but the display metrics should come from elsewhere
505    if (display != mDefaultDisplays[ISurfaceComposer::eDisplayIdMain]) {
506        // TODO: additional displays not yet supported
507        return BAD_INDEX;
508    }
509
510    const HWComposer& hwc(getHwComposer());
511    float xdpi = hwc.getDpiX();
512    float ydpi = hwc.getDpiY();
513
514    // TODO: Not sure if display density should handled by SF any longer
515    class Density {
516        static int getDensityFromProperty(char const* propName) {
517            char property[PROPERTY_VALUE_MAX];
518            int density = 0;
519            if (property_get(propName, property, NULL) > 0) {
520                density = atoi(property);
521            }
522            return density;
523        }
524    public:
525        static int getEmuDensity() {
526            return getDensityFromProperty("qemu.sf.lcd_density"); }
527        static int getBuildDensity()  {
528            return getDensityFromProperty("ro.sf.lcd_density"); }
529    };
530    // The density of the device is provided by a build property
531    float density = Density::getBuildDensity() / 160.0f;
532    if (density == 0) {
533        // the build doesn't provide a density -- this is wrong!
534        // use xdpi instead
535        ALOGE("ro.sf.lcd_density must be defined as a build property");
536        density = xdpi / 160.0f;
537    }
538    if (Density::getEmuDensity()) {
539        // if "qemu.sf.lcd_density" is specified, it overrides everything
540        xdpi = ydpi = density = Density::getEmuDensity();
541        density /= 160.0f;
542    }
543
544    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
545    info->w = hw->getWidth();
546    info->h = hw->getHeight();
547    info->xdpi = xdpi;
548    info->ydpi = ydpi;
549    info->fps = float(1e9 / hwc.getRefreshPeriod());
550    info->density = density;
551    info->orientation = hw->getOrientation();
552    // TODO: this needs to go away (currently needed only by webkit)
553    getPixelFormatInfo(hw->getFormat(), &info->pixelFormatInfo);
554    return NO_ERROR;
555}
556
557// ----------------------------------------------------------------------------
558
559sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
560    return mEventThread->createEventConnection();
561}
562
563void SurfaceFlinger::connectDisplay(const sp<ISurfaceTexture>& surface) {
564
565    sp<IBinder> token;
566    { // scope for the lock
567        Mutex::Autolock _l(mStateLock);
568        token = mExtDisplayToken;
569    }
570
571    if (token == 0) {
572        token = createDisplay();
573    }
574
575    { // scope for the lock
576        Mutex::Autolock _l(mStateLock);
577        if (surface == 0) {
578            // release our current display. we're guarantee to have
579            // a reference to it (token), while we hold the lock
580            mExtDisplayToken = 0;
581        } else {
582            mExtDisplayToken = token;
583        }
584
585        DisplayDeviceState& info(mCurrentState.displays.editValueFor(token));
586        info.surface = surface;
587        setTransactionFlags(eDisplayTransactionNeeded);
588    }
589}
590
591// ----------------------------------------------------------------------------
592
593void SurfaceFlinger::waitForEvent() {
594    mEventQueue.waitMessage();
595}
596
597void SurfaceFlinger::signalTransaction() {
598    mEventQueue.invalidate();
599}
600
601void SurfaceFlinger::signalLayerUpdate() {
602    mEventQueue.invalidate();
603}
604
605void SurfaceFlinger::signalRefresh() {
606    mEventQueue.refresh();
607}
608
609status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
610        nsecs_t reltime, uint32_t flags) {
611    return mEventQueue.postMessage(msg, reltime);
612}
613
614status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
615        nsecs_t reltime, uint32_t flags) {
616    status_t res = mEventQueue.postMessage(msg, reltime);
617    if (res == NO_ERROR) {
618        msg->wait();
619    }
620    return res;
621}
622
623bool SurfaceFlinger::threadLoop() {
624    waitForEvent();
625    return true;
626}
627
628void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
629    if (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) {
630        // we should only receive DisplayDevice::DisplayType from the vsync callback
631        const wp<IBinder>& token(mDefaultDisplays[type]);
632        mEventThread->onVSyncReceived(token, timestamp);
633    }
634}
635
636void SurfaceFlinger::eventControl(int event, int enabled) {
637    getHwComposer().eventControl(event, enabled);
638}
639
640void SurfaceFlinger::onMessageReceived(int32_t what) {
641    ATRACE_CALL();
642    switch (what) {
643    case MessageQueue::INVALIDATE:
644        handleMessageTransaction();
645        handleMessageInvalidate();
646        signalRefresh();
647        break;
648    case MessageQueue::REFRESH:
649        handleMessageRefresh();
650        break;
651    }
652}
653
654void SurfaceFlinger::handleMessageTransaction() {
655    uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
656    if (transactionFlags) {
657        handleTransaction(transactionFlags);
658    }
659}
660
661void SurfaceFlinger::handleMessageInvalidate() {
662    ATRACE_CALL();
663    handlePageFlip();
664}
665
666void SurfaceFlinger::handleMessageRefresh() {
667    ATRACE_CALL();
668    preComposition();
669    rebuildLayerStacks();
670    setUpHWComposer();
671    doDebugFlashRegions();
672    doComposition();
673    postComposition();
674}
675
676void SurfaceFlinger::doDebugFlashRegions()
677{
678    // is debugging enabled
679    if (CC_LIKELY(!mDebugRegion))
680        return;
681
682    const bool repaintEverything = mRepaintEverything;
683    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
684        const sp<DisplayDevice>& hw(mDisplays[dpy]);
685        if (hw->canDraw()) {
686            // transform the dirty region into this screen's coordinate space
687            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
688            if (!dirtyRegion.isEmpty()) {
689                // redraw the whole screen
690                doComposeSurfaces(hw, Region(hw->bounds()));
691
692                // and draw the dirty region
693                glDisable(GL_TEXTURE_EXTERNAL_OES);
694                glDisable(GL_TEXTURE_2D);
695                glDisable(GL_BLEND);
696                glColor4f(1, 0, 1, 1);
697                const int32_t height = hw->getHeight();
698                Region::const_iterator it = dirtyRegion.begin();
699                Region::const_iterator const end = dirtyRegion.end();
700                while (it != end) {
701                    const Rect& r = *it++;
702                    GLfloat vertices[][2] = {
703                            { r.left,  height - r.top },
704                            { r.left,  height - r.bottom },
705                            { r.right, height - r.bottom },
706                            { r.right, height - r.top }
707                    };
708                    glVertexPointer(2, GL_FLOAT, 0, vertices);
709                    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
710                }
711                hw->compositionComplete();
712                // FIXME
713                if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
714                    eglSwapBuffers(mEGLDisplay, hw->getEGLSurface());
715                }
716            }
717        }
718    }
719
720    postFramebuffer();
721
722    if (mDebugRegion > 1) {
723        usleep(mDebugRegion * 1000);
724    }
725}
726
727void SurfaceFlinger::preComposition()
728{
729    bool needExtraInvalidate = false;
730    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
731    const size_t count = currentLayers.size();
732    for (size_t i=0 ; i<count ; i++) {
733        if (currentLayers[i]->onPreComposition()) {
734            needExtraInvalidate = true;
735        }
736    }
737    if (needExtraInvalidate) {
738        signalLayerUpdate();
739    }
740}
741
742void SurfaceFlinger::postComposition()
743{
744    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
745    const size_t count = currentLayers.size();
746    for (size_t i=0 ; i<count ; i++) {
747        currentLayers[i]->onPostComposition();
748    }
749}
750
751void SurfaceFlinger::rebuildLayerStacks() {
752    // rebuild the visible layer list per screen
753    if (CC_UNLIKELY(mVisibleRegionsDirty)) {
754        ATRACE_CALL();
755        mVisibleRegionsDirty = false;
756        invalidateHwcGeometry();
757        const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
758        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
759            const sp<DisplayDevice>& hw(mDisplays[dpy]);
760            Region opaqueRegion;
761            Region dirtyRegion;
762            computeVisibleRegions(currentLayers,
763                    hw->getLayerStack(), dirtyRegion, opaqueRegion);
764            hw->dirtyRegion.orSelf(dirtyRegion);
765
766            Vector< sp<LayerBase> > layersSortedByZ;
767            const size_t count = currentLayers.size();
768            for (size_t i=0 ; i<count ; i++) {
769                const Layer::State& s(currentLayers[i]->drawingState());
770                if (s.layerStack == hw->getLayerStack()) {
771                    if (!currentLayers[i]->visibleRegion.isEmpty()) {
772                        layersSortedByZ.add(currentLayers[i]);
773                    }
774                }
775            }
776            hw->setVisibleLayersSortedByZ(layersSortedByZ);
777            hw->undefinedRegion.set(hw->getBounds());
778            hw->undefinedRegion.subtractSelf(
779                    hw->getTransform().transform(opaqueRegion));
780        }
781    }
782}
783
784void SurfaceFlinger::setUpHWComposer() {
785    HWComposer& hwc(getHwComposer());
786    if (hwc.initCheck() == NO_ERROR) {
787        // build the h/w work list
788        const bool workListsDirty = mHwWorkListDirty;
789        mHwWorkListDirty = false;
790        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
791            sp<const DisplayDevice> hw(mDisplays[dpy]);
792            const int32_t id = hw->getHwcDisplayId();
793            if (id >= 0) {
794                const Vector< sp<LayerBase> >& currentLayers(
795                    hw->getVisibleLayersSortedByZ());
796                const size_t count = currentLayers.size();
797                if (hwc.createWorkList(id, count) >= 0) {
798                    HWComposer::LayerListIterator cur = hwc.begin(id);
799                    const HWComposer::LayerListIterator end = hwc.end(id);
800                    for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
801                        const sp<LayerBase>& layer(currentLayers[i]);
802
803                        if (CC_UNLIKELY(workListsDirty)) {
804                            layer->setGeometry(hw, *cur);
805                            if (mDebugDisableHWC || mDebugRegion) {
806                                cur->setSkip(true);
807                            }
808                        }
809
810                        /*
811                         * update the per-frame h/w composer data for each layer
812                         * and build the transparent region of the FB
813                         */
814                        layer->setPerFrameData(hw, *cur);
815                    }
816                }
817            }
818        }
819        status_t err = hwc.prepare();
820        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
821    }
822}
823
824void SurfaceFlinger::doComposition() {
825    ATRACE_CALL();
826    const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
827    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
828        const sp<DisplayDevice>& hw(mDisplays[dpy]);
829        if (hw->canDraw()) {
830            // transform the dirty region into this screen's coordinate space
831            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
832            if (!dirtyRegion.isEmpty()) {
833                // repaint the framebuffer (if needed)
834                doDisplayComposition(hw, dirtyRegion);
835            }
836            hw->dirtyRegion.clear();
837            hw->flip(hw->swapRegion);
838            hw->swapRegion.clear();
839        }
840        // inform the h/w that we're done compositing
841        hw->compositionComplete();
842    }
843    postFramebuffer();
844}
845
846void SurfaceFlinger::postFramebuffer()
847{
848    ATRACE_CALL();
849
850    const nsecs_t now = systemTime();
851    mDebugInSwapBuffers = now;
852
853    HWComposer& hwc(getHwComposer());
854    if (hwc.initCheck() == NO_ERROR) {
855        // FIXME: EGL spec says:
856        //   "surface must be bound to the calling thread's current context,
857        //    for the current rendering API."
858        DisplayDevice::makeCurrent(getDefaultDisplayDevice(), mEGLContext);
859        hwc.commit();
860    }
861
862    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
863        sp<const DisplayDevice> hw(mDisplays[dpy]);
864        const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ());
865        const size_t count = currentLayers.size();
866        int32_t id = hw->getHwcDisplayId();
867        if (id >=0 && hwc.initCheck() == NO_ERROR) {
868            HWComposer::LayerListIterator cur = hwc.begin(id);
869            const HWComposer::LayerListIterator end = hwc.end(id);
870            for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
871                currentLayers[i]->onLayerDisplayed(hw, &*cur);
872            }
873        } else {
874            for (size_t i = 0; i < count; i++) {
875                currentLayers[i]->onLayerDisplayed(hw, NULL);
876            }
877        }
878    }
879
880    mLastSwapBufferTime = systemTime() - now;
881    mDebugInSwapBuffers = 0;
882}
883
884void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
885{
886    ATRACE_CALL();
887
888    Mutex::Autolock _l(mStateLock);
889    const nsecs_t now = systemTime();
890    mDebugInTransaction = now;
891
892    // Here we're guaranteed that some transaction flags are set
893    // so we can call handleTransactionLocked() unconditionally.
894    // We call getTransactionFlags(), which will also clear the flags,
895    // with mStateLock held to guarantee that mCurrentState won't change
896    // until the transaction is committed.
897
898    transactionFlags = getTransactionFlags(eTransactionMask);
899    handleTransactionLocked(transactionFlags);
900
901    mLastTransactionTime = systemTime() - now;
902    mDebugInTransaction = 0;
903    invalidateHwcGeometry();
904    // here the transaction has been committed
905}
906
907void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
908{
909    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
910    const size_t count = currentLayers.size();
911
912    /*
913     * Traversal of the children
914     * (perform the transaction for each of them if needed)
915     */
916
917    if (transactionFlags & eTraversalNeeded) {
918        for (size_t i=0 ; i<count ; i++) {
919            const sp<LayerBase>& layer = currentLayers[i];
920            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
921            if (!trFlags) continue;
922
923            const uint32_t flags = layer->doTransaction(0);
924            if (flags & Layer::eVisibleRegion)
925                mVisibleRegionsDirty = true;
926        }
927    }
928
929    /*
930     * Perform display own transactions if needed
931     */
932
933    if (transactionFlags & eDisplayTransactionNeeded) {
934        // here we take advantage of Vector's copy-on-write semantics to
935        // improve performance by skipping the transaction entirely when
936        // know that the lists are identical
937        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
938        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
939        if (!curr.isIdenticalTo(draw)) {
940            mVisibleRegionsDirty = true;
941            const size_t cc = curr.size();
942            const size_t dc = draw.size();
943
944            // find the displays that were removed
945            // (ie: in drawing state but not in current state)
946            // also handle displays that changed
947            // (ie: displays that are in both lists)
948            for (size_t i=0 ; i<dc ; i++) {
949                const ssize_t j = curr.indexOfKey(draw.keyAt(i));
950                if (j < 0) {
951                    // in drawing state but not in current state
952                    if (!draw[i].isMainDisplay()) {
953                        mDisplays.removeItem(draw.keyAt(i));
954                    } else {
955                        ALOGW("trying to remove the main display");
956                    }
957                } else {
958                    // this display is in both lists. see if something changed.
959                    const DisplayDeviceState& state(curr[j]);
960                    const wp<IBinder>& display(curr.keyAt(j));
961                    if (state.surface->asBinder() != draw[i].surface->asBinder()) {
962                        // changing the surface is like destroying and
963                        // recreating the DisplayDevice
964                        sp<SurfaceTextureClient> stc(
965                                new SurfaceTextureClient(state.surface));
966                        sp<DisplayDevice> disp = new DisplayDevice(this,
967                            state.type, display, stc, NULL, mEGLConfig);
968
969                        disp->setLayerStack(state.layerStack);
970                        disp->setOrientation(state.orientation);
971                        // TODO: take viewport and frame into account
972                        mDisplays.replaceValueFor(display, disp);
973                    }
974                    if (state.layerStack != draw[i].layerStack) {
975                        const sp<DisplayDevice>& disp(getDisplayDevice(display));
976                        disp->setLayerStack(state.layerStack);
977                    }
978                    if (state.orientation != draw[i].orientation ||
979                        state.viewport != draw[i].viewport ||
980                        state.frame != draw[i].frame) {
981                        const sp<DisplayDevice>& disp(getDisplayDevice(display));
982                        disp->setOrientation(state.orientation);
983                        // TODO: take viewport and frame into account
984                    }
985                }
986            }
987
988            // find displays that were added
989            // (ie: in current state but not in drawing state)
990            for (size_t i=0 ; i<cc ; i++) {
991                if (draw.indexOfKey(curr.keyAt(i)) < 0) {
992                    const DisplayDeviceState& state(curr[i]);
993                    sp<SurfaceTextureClient> stc(
994                            new SurfaceTextureClient(state.surface));
995                    const wp<IBinder>& display(curr.keyAt(i));
996                    sp<DisplayDevice> disp = new DisplayDevice(this,
997                        state.type, display, stc, 0, mEGLConfig);
998                    mDisplays.add(display, disp);
999                }
1000            }
1001        }
1002    }
1003
1004    /*
1005     * Perform our own transaction if needed
1006     */
1007
1008    const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
1009    if (currentLayers.size() > previousLayers.size()) {
1010        // layers have been added
1011        mVisibleRegionsDirty = true;
1012    }
1013
1014    // some layers might have been removed, so
1015    // we need to update the regions they're exposing.
1016    if (mLayersRemoved) {
1017        mLayersRemoved = false;
1018        mVisibleRegionsDirty = true;
1019        const size_t count = previousLayers.size();
1020        for (size_t i=0 ; i<count ; i++) {
1021            const sp<LayerBase>& layer(previousLayers[i]);
1022            if (currentLayers.indexOf(layer) < 0) {
1023                // this layer is not visible anymore
1024                // TODO: we could traverse the tree from front to back and
1025                //       compute the actual visible region
1026                // TODO: we could cache the transformed region
1027                Layer::State front(layer->drawingState());
1028                Region visibleReg = front.transform.transform(
1029                        Region(Rect(front.active.w, front.active.h)));
1030                invalidateLayerStack(front.layerStack, visibleReg);
1031            }
1032        }
1033    }
1034
1035    commitTransaction();
1036}
1037
1038void SurfaceFlinger::commitTransaction()
1039{
1040    if (!mLayersPendingRemoval.isEmpty()) {
1041        // Notify removed layers now that they can't be drawn from
1042        for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1043            mLayersPendingRemoval[i]->onRemoved();
1044        }
1045        mLayersPendingRemoval.clear();
1046    }
1047
1048    mDrawingState = mCurrentState;
1049    mTransationPending = false;
1050    mTransactionCV.broadcast();
1051}
1052
1053void SurfaceFlinger::computeVisibleRegions(
1054        const LayerVector& currentLayers, uint32_t layerStack,
1055        Region& outDirtyRegion, Region& outOpaqueRegion)
1056{
1057    ATRACE_CALL();
1058
1059    Region aboveOpaqueLayers;
1060    Region aboveCoveredLayers;
1061    Region dirty;
1062
1063    outDirtyRegion.clear();
1064
1065    size_t i = currentLayers.size();
1066    while (i--) {
1067        const sp<LayerBase>& layer = currentLayers[i];
1068
1069        // start with the whole surface at its current location
1070        const Layer::State& s(layer->drawingState());
1071
1072        // only consider the layers on the given later stack
1073        if (s.layerStack != layerStack)
1074            continue;
1075
1076        /*
1077         * opaqueRegion: area of a surface that is fully opaque.
1078         */
1079        Region opaqueRegion;
1080
1081        /*
1082         * visibleRegion: area of a surface that is visible on screen
1083         * and not fully transparent. This is essentially the layer's
1084         * footprint minus the opaque regions above it.
1085         * Areas covered by a translucent surface are considered visible.
1086         */
1087        Region visibleRegion;
1088
1089        /*
1090         * coveredRegion: area of a surface that is covered by all
1091         * visible regions above it (which includes the translucent areas).
1092         */
1093        Region coveredRegion;
1094
1095
1096        // handle hidden surfaces by setting the visible region to empty
1097        if (CC_LIKELY(!(s.flags & layer_state_t::eLayerHidden) && s.alpha)) {
1098            const bool translucent = !layer->isOpaque();
1099            Rect bounds(layer->computeBounds());
1100            visibleRegion.set(bounds);
1101            if (!visibleRegion.isEmpty()) {
1102                // Remove the transparent area from the visible region
1103                if (translucent) {
1104                    Region transparentRegionScreen;
1105                    const Transform tr(s.transform);
1106                    if (tr.transformed()) {
1107                        if (tr.preserveRects()) {
1108                            // transform the transparent region
1109                            transparentRegionScreen = tr.transform(s.transparentRegion);
1110                        } else {
1111                            // transformation too complex, can't do the
1112                            // transparent region optimization.
1113                            transparentRegionScreen.clear();
1114                        }
1115                    } else {
1116                        transparentRegionScreen = s.transparentRegion;
1117                    }
1118                    visibleRegion.subtractSelf(transparentRegionScreen);
1119                }
1120
1121                // compute the opaque region
1122                const int32_t layerOrientation = s.transform.getOrientation();
1123                if (s.alpha==255 && !translucent &&
1124                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
1125                    // the opaque region is the layer's footprint
1126                    opaqueRegion = visibleRegion;
1127                }
1128            }
1129        }
1130
1131        // Clip the covered region to the visible region
1132        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1133
1134        // Update aboveCoveredLayers for next (lower) layer
1135        aboveCoveredLayers.orSelf(visibleRegion);
1136
1137        // subtract the opaque region covered by the layers above us
1138        visibleRegion.subtractSelf(aboveOpaqueLayers);
1139
1140        // compute this layer's dirty region
1141        if (layer->contentDirty) {
1142            // we need to invalidate the whole region
1143            dirty = visibleRegion;
1144            // as well, as the old visible region
1145            dirty.orSelf(layer->visibleRegion);
1146            layer->contentDirty = false;
1147        } else {
1148            /* compute the exposed region:
1149             *   the exposed region consists of two components:
1150             *   1) what's VISIBLE now and was COVERED before
1151             *   2) what's EXPOSED now less what was EXPOSED before
1152             *
1153             * note that (1) is conservative, we start with the whole
1154             * visible region but only keep what used to be covered by
1155             * something -- which mean it may have been exposed.
1156             *
1157             * (2) handles areas that were not covered by anything but got
1158             * exposed because of a resize.
1159             */
1160            const Region newExposed = visibleRegion - coveredRegion;
1161            const Region oldVisibleRegion = layer->visibleRegion;
1162            const Region oldCoveredRegion = layer->coveredRegion;
1163            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1164            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1165        }
1166        dirty.subtractSelf(aboveOpaqueLayers);
1167
1168        // accumulate to the screen dirty region
1169        outDirtyRegion.orSelf(dirty);
1170
1171        // Update aboveOpaqueLayers for next (lower) layer
1172        aboveOpaqueLayers.orSelf(opaqueRegion);
1173
1174        // Store the visible region is screen space
1175        layer->setVisibleRegion(visibleRegion);
1176        layer->setCoveredRegion(coveredRegion);
1177    }
1178
1179    outOpaqueRegion = aboveOpaqueLayers;
1180}
1181
1182void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1183        const Region& dirty) {
1184    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1185        const sp<DisplayDevice>& hw(mDisplays[dpy]);
1186        if (hw->getLayerStack() == layerStack) {
1187            hw->dirtyRegion.orSelf(dirty);
1188        }
1189    }
1190}
1191
1192void SurfaceFlinger::handlePageFlip()
1193{
1194    Region dirtyRegion;
1195
1196    bool visibleRegions = false;
1197    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
1198    const size_t count = currentLayers.size();
1199    for (size_t i=0 ; i<count ; i++) {
1200        const sp<LayerBase>& layer(currentLayers[i]);
1201        const Region dirty(layer->latchBuffer(visibleRegions));
1202        Layer::State s(layer->drawingState());
1203        invalidateLayerStack(s.layerStack, dirty);
1204    }
1205
1206    mVisibleRegionsDirty |= visibleRegions;
1207}
1208
1209void SurfaceFlinger::invalidateHwcGeometry()
1210{
1211    mHwWorkListDirty = true;
1212}
1213
1214
1215void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1216        const Region& inDirtyRegion)
1217{
1218    Region dirtyRegion(inDirtyRegion);
1219
1220    // compute the invalid region
1221    hw->swapRegion.orSelf(dirtyRegion);
1222
1223    uint32_t flags = hw->getFlags();
1224    if (flags & DisplayDevice::SWAP_RECTANGLE) {
1225        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1226        // takes a rectangle, we must make sure to update that whole
1227        // rectangle in that case
1228        dirtyRegion.set(hw->swapRegion.bounds());
1229    } else {
1230        if (flags & DisplayDevice::PARTIAL_UPDATES) {
1231            // We need to redraw the rectangle that will be updated
1232            // (pushed to the framebuffer).
1233            // This is needed because PARTIAL_UPDATES only takes one
1234            // rectangle instead of a region (see DisplayDevice::flip())
1235            dirtyRegion.set(hw->swapRegion.bounds());
1236        } else {
1237            // we need to redraw everything (the whole screen)
1238            dirtyRegion.set(hw->bounds());
1239            hw->swapRegion = dirtyRegion;
1240        }
1241    }
1242
1243    doComposeSurfaces(hw, dirtyRegion);
1244
1245    // FIXME: we need to call eglSwapBuffers() on displays that have
1246    // GL composition and only on those.
1247    // however, currently hwc.commit() already does that for the main
1248    // display and never for the other ones
1249    if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
1250        // FIXME: EGL spec says:
1251        //   "surface must be bound to the calling thread's current context,
1252        //    for the current rendering API."
1253        eglSwapBuffers(mEGLDisplay, hw->getEGLSurface());
1254    }
1255
1256    // update the swap region and clear the dirty region
1257    hw->swapRegion.orSelf(dirtyRegion);
1258}
1259
1260void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1261{
1262    HWComposer& hwc(getHwComposer());
1263    int32_t id = hw->getHwcDisplayId();
1264    HWComposer::LayerListIterator cur = hwc.begin(id);
1265    const HWComposer::LayerListIterator end = hwc.end(id);
1266
1267    const bool hasGlesComposition = hwc.hasGlesComposition(id);
1268    const bool hasHwcComposition = hwc.hasHwcComposition(id);
1269    if (cur==end || hasGlesComposition) {
1270
1271        DisplayDevice::makeCurrent(hw, mEGLContext);
1272
1273        // set the frame buffer
1274        glMatrixMode(GL_MODELVIEW);
1275        glLoadIdentity();
1276
1277        // Never touch the framebuffer if we don't have any framebuffer layers
1278        if (hasHwcComposition) {
1279            // when using overlays, we assume a fully transparent framebuffer
1280            // NOTE: we could reduce how much we need to clear, for instance
1281            // remove where there are opaque FB layers. however, on some
1282            // GPUs doing a "clean slate" glClear might be more efficient.
1283            // We'll revisit later if needed.
1284            glClearColor(0, 0, 0, 0);
1285            glClear(GL_COLOR_BUFFER_BIT);
1286        } else {
1287            const Region region(hw->undefinedRegion.intersect(dirty));
1288            // screen is already cleared here
1289            if (!region.isEmpty()) {
1290                // can happen with SurfaceView
1291                drawWormhole(hw, region);
1292            }
1293        }
1294
1295        /*
1296         * and then, render the layers targeted at the framebuffer
1297         */
1298
1299        const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
1300        const size_t count = layers.size();
1301        const Transform& tr = hw->getTransform();
1302        for (size_t i=0 ; i<count ; ++i) {
1303            const sp<LayerBase>& layer(layers[i]);
1304            const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1305            if (cur != end) {
1306                // we're using h/w composer
1307                if (!clip.isEmpty()) {
1308                    if (cur->getCompositionType() == HWC_OVERLAY) {
1309                        if (i && (cur->getHints() & HWC_HINT_CLEAR_FB)
1310                                && layer->isOpaque()) {
1311                            // never clear the very first layer since we're
1312                            // guaranteed the FB is already cleared
1313                            layer->clearWithOpenGL(hw, clip);
1314                        }
1315                    } else {
1316                        layer->draw(hw, clip);
1317                    }
1318                    layer->setAcquireFence(hw, *cur);
1319                }
1320                ++cur;
1321            } else {
1322                // we're not using h/w composer
1323                if (!clip.isEmpty()) {
1324                    layer->draw(hw, clip);
1325                }
1326            }
1327        }
1328    }
1329}
1330
1331void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw,
1332        const Region& region) const
1333{
1334    glDisable(GL_TEXTURE_EXTERNAL_OES);
1335    glDisable(GL_TEXTURE_2D);
1336    glDisable(GL_BLEND);
1337    glColor4f(0,0,0,0);
1338
1339    const int32_t height = hw->getHeight();
1340    Region::const_iterator it = region.begin();
1341    Region::const_iterator const end = region.end();
1342    while (it != end) {
1343        const Rect& r = *it++;
1344        GLfloat vertices[][2] = {
1345                { r.left,  height - r.top },
1346                { r.left,  height - r.bottom },
1347                { r.right, height - r.bottom },
1348                { r.right, height - r.top }
1349        };
1350        glVertexPointer(2, GL_FLOAT, 0, vertices);
1351        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1352    }
1353}
1354
1355ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1356        const sp<LayerBaseClient>& lbc)
1357{
1358    // attach this layer to the client
1359    size_t name = client->attachLayer(lbc);
1360
1361    // add this layer to the current state list
1362    Mutex::Autolock _l(mStateLock);
1363    mCurrentState.layersSortedByZ.add(lbc);
1364
1365    return ssize_t(name);
1366}
1367
1368status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1369{
1370    Mutex::Autolock _l(mStateLock);
1371    status_t err = purgatorizeLayer_l(layer);
1372    if (err == NO_ERROR)
1373        setTransactionFlags(eTransactionNeeded);
1374    return err;
1375}
1376
1377status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1378{
1379    ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1380    if (index >= 0) {
1381        mLayersRemoved = true;
1382        return NO_ERROR;
1383    }
1384    return status_t(index);
1385}
1386
1387status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1388{
1389    // First add the layer to the purgatory list, which makes sure it won't
1390    // go away, then remove it from the main list (through a transaction).
1391    ssize_t err = removeLayer_l(layerBase);
1392    if (err >= 0) {
1393        mLayerPurgatory.add(layerBase);
1394    }
1395
1396    mLayersPendingRemoval.push(layerBase);
1397
1398    // it's possible that we don't find a layer, because it might
1399    // have been destroyed already -- this is not technically an error
1400    // from the user because there is a race between Client::destroySurface(),
1401    // ~Client() and ~ISurface().
1402    return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1403}
1404
1405uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
1406{
1407    return android_atomic_release_load(&mTransactionFlags);
1408}
1409
1410uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1411{
1412    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1413}
1414
1415uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1416{
1417    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1418    if ((old & flags)==0) { // wake the server up
1419        signalTransaction();
1420    }
1421    return old;
1422}
1423
1424void SurfaceFlinger::setTransactionState(
1425        const Vector<ComposerState>& state,
1426        const Vector<DisplayState>& displays,
1427        uint32_t flags)
1428{
1429    Mutex::Autolock _l(mStateLock);
1430    uint32_t transactionFlags = 0;
1431
1432    size_t count = displays.size();
1433    for (size_t i=0 ; i<count ; i++) {
1434        const DisplayState& s(displays[i]);
1435        transactionFlags |= setDisplayStateLocked(s);
1436    }
1437
1438    count = state.size();
1439    for (size_t i=0 ; i<count ; i++) {
1440        const ComposerState& s(state[i]);
1441        sp<Client> client( static_cast<Client *>(s.client.get()) );
1442        transactionFlags |= setClientStateLocked(client, s.state);
1443    }
1444
1445    if (transactionFlags) {
1446        // this triggers the transaction
1447        setTransactionFlags(transactionFlags);
1448
1449        // if this is a synchronous transaction, wait for it to take effect
1450        // before returning.
1451        if (flags & eSynchronous) {
1452            mTransationPending = true;
1453        }
1454        while (mTransationPending) {
1455            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1456            if (CC_UNLIKELY(err != NO_ERROR)) {
1457                // just in case something goes wrong in SF, return to the
1458                // called after a few seconds.
1459                ALOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1460                mTransationPending = false;
1461                break;
1462            }
1463        }
1464    }
1465}
1466
1467uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1468{
1469    uint32_t flags = 0;
1470    DisplayDeviceState& disp(mCurrentState.displays.editValueFor(s.token));
1471    if (disp.isValid()) {
1472        const uint32_t what = s.what;
1473        if (what & DisplayState::eSurfaceChanged) {
1474            if (disp.surface->asBinder() != s.surface->asBinder()) {
1475                disp.surface = s.surface;
1476                flags |= eDisplayTransactionNeeded;
1477            }
1478        }
1479        if (what & DisplayState::eLayerStackChanged) {
1480            if (disp.layerStack != s.layerStack) {
1481                disp.layerStack = s.layerStack;
1482                flags |= eDisplayTransactionNeeded;
1483            }
1484        }
1485        if (what & DisplayState::eOrientationChanged) {
1486            if (disp.orientation != s.orientation) {
1487                disp.orientation = s.orientation;
1488                flags |= eDisplayTransactionNeeded;
1489            }
1490        }
1491        if (what & DisplayState::eFrameChanged) {
1492            if (disp.frame != s.frame) {
1493                disp.frame = s.frame;
1494                flags |= eDisplayTransactionNeeded;
1495            }
1496        }
1497        if (what & DisplayState::eViewportChanged) {
1498            if (disp.viewport != s.viewport) {
1499                disp.viewport = s.viewport;
1500                flags |= eDisplayTransactionNeeded;
1501            }
1502        }
1503    }
1504    return flags;
1505}
1506
1507uint32_t SurfaceFlinger::setClientStateLocked(
1508        const sp<Client>& client,
1509        const layer_state_t& s)
1510{
1511    uint32_t flags = 0;
1512    sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1513    if (layer != 0) {
1514        const uint32_t what = s.what;
1515        if (what & layer_state_t::ePositionChanged) {
1516            if (layer->setPosition(s.x, s.y))
1517                flags |= eTraversalNeeded;
1518        }
1519        if (what & layer_state_t::eLayerChanged) {
1520            // NOTE: index needs to be calculated before we update the state
1521            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1522            if (layer->setLayer(s.z)) {
1523                mCurrentState.layersSortedByZ.removeAt(idx);
1524                mCurrentState.layersSortedByZ.add(layer);
1525                // we need traversal (state changed)
1526                // AND transaction (list changed)
1527                flags |= eTransactionNeeded|eTraversalNeeded;
1528            }
1529        }
1530        if (what & layer_state_t::eSizeChanged) {
1531            if (layer->setSize(s.w, s.h)) {
1532                flags |= eTraversalNeeded;
1533            }
1534        }
1535        if (what & layer_state_t::eAlphaChanged) {
1536            if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1537                flags |= eTraversalNeeded;
1538        }
1539        if (what & layer_state_t::eMatrixChanged) {
1540            if (layer->setMatrix(s.matrix))
1541                flags |= eTraversalNeeded;
1542        }
1543        if (what & layer_state_t::eTransparentRegionChanged) {
1544            if (layer->setTransparentRegionHint(s.transparentRegion))
1545                flags |= eTraversalNeeded;
1546        }
1547        if (what & layer_state_t::eVisibilityChanged) {
1548            if (layer->setFlags(s.flags, s.mask))
1549                flags |= eTraversalNeeded;
1550        }
1551        if (what & layer_state_t::eCropChanged) {
1552            if (layer->setCrop(s.crop))
1553                flags |= eTraversalNeeded;
1554        }
1555        if (what & layer_state_t::eLayerStackChanged) {
1556            // NOTE: index needs to be calculated before we update the state
1557            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1558            if (layer->setLayerStack(s.layerStack)) {
1559                mCurrentState.layersSortedByZ.removeAt(idx);
1560                mCurrentState.layersSortedByZ.add(layer);
1561                // we need traversal (state changed)
1562                // AND transaction (list changed)
1563                flags |= eTransactionNeeded|eTraversalNeeded;
1564            }
1565        }
1566    }
1567    return flags;
1568}
1569
1570sp<ISurface> SurfaceFlinger::createLayer(
1571        ISurfaceComposerClient::surface_data_t* params,
1572        const String8& name,
1573        const sp<Client>& client,
1574       uint32_t w, uint32_t h, PixelFormat format,
1575        uint32_t flags)
1576{
1577    sp<LayerBaseClient> layer;
1578    sp<ISurface> surfaceHandle;
1579
1580    if (int32_t(w|h) < 0) {
1581        ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
1582                int(w), int(h));
1583        return surfaceHandle;
1584    }
1585
1586    //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
1587    switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
1588        case ISurfaceComposerClient::eFXSurfaceNormal:
1589            layer = createNormalLayer(client, w, h, flags, format);
1590            break;
1591        case ISurfaceComposerClient::eFXSurfaceBlur:
1592        case ISurfaceComposerClient::eFXSurfaceDim:
1593            layer = createDimLayer(client, w, h, flags);
1594            break;
1595        case ISurfaceComposerClient::eFXSurfaceScreenshot:
1596            layer = createScreenshotLayer(client, w, h, flags);
1597            break;
1598    }
1599
1600    if (layer != 0) {
1601        layer->initStates(w, h, flags);
1602        layer->setName(name);
1603        ssize_t token = addClientLayer(client, layer);
1604        surfaceHandle = layer->getSurface();
1605        if (surfaceHandle != 0) {
1606            params->token = token;
1607            params->identity = layer->getIdentity();
1608        }
1609        setTransactionFlags(eTransactionNeeded);
1610    }
1611
1612    return surfaceHandle;
1613}
1614
1615sp<Layer> SurfaceFlinger::createNormalLayer(
1616        const sp<Client>& client,
1617        uint32_t w, uint32_t h, uint32_t flags,
1618        PixelFormat& format)
1619{
1620    // initialize the surfaces
1621    switch (format) {
1622    case PIXEL_FORMAT_TRANSPARENT:
1623    case PIXEL_FORMAT_TRANSLUCENT:
1624        format = PIXEL_FORMAT_RGBA_8888;
1625        break;
1626    case PIXEL_FORMAT_OPAQUE:
1627#ifdef NO_RGBX_8888
1628        format = PIXEL_FORMAT_RGB_565;
1629#else
1630        format = PIXEL_FORMAT_RGBX_8888;
1631#endif
1632        break;
1633    }
1634
1635#ifdef NO_RGBX_8888
1636    if (format == PIXEL_FORMAT_RGBX_8888)
1637        format = PIXEL_FORMAT_RGBA_8888;
1638#endif
1639
1640    sp<Layer> layer = new Layer(this, client);
1641    status_t err = layer->setBuffers(w, h, format, flags);
1642    if (CC_LIKELY(err != NO_ERROR)) {
1643        ALOGE("createNormalLayer() failed (%s)", strerror(-err));
1644        layer.clear();
1645    }
1646    return layer;
1647}
1648
1649sp<LayerDim> SurfaceFlinger::createDimLayer(
1650        const sp<Client>& client,
1651        uint32_t w, uint32_t h, uint32_t flags)
1652{
1653    sp<LayerDim> layer = new LayerDim(this, client);
1654    return layer;
1655}
1656
1657sp<LayerScreenshot> SurfaceFlinger::createScreenshotLayer(
1658        const sp<Client>& client,
1659        uint32_t w, uint32_t h, uint32_t flags)
1660{
1661    sp<LayerScreenshot> layer = new LayerScreenshot(this, client);
1662    return layer;
1663}
1664
1665status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, SurfaceID sid)
1666{
1667    /*
1668     * called by the window manager, when a surface should be marked for
1669     * destruction.
1670     *
1671     * The surface is removed from the current and drawing lists, but placed
1672     * in the purgatory queue, so it's not destroyed right-away (we need
1673     * to wait for all client's references to go away first).
1674     */
1675
1676    status_t err = NAME_NOT_FOUND;
1677    Mutex::Autolock _l(mStateLock);
1678    sp<LayerBaseClient> layer = client->getLayerUser(sid);
1679
1680    if (layer != 0) {
1681        err = purgatorizeLayer_l(layer);
1682        if (err == NO_ERROR) {
1683            setTransactionFlags(eTransactionNeeded);
1684        }
1685    }
1686    return err;
1687}
1688
1689status_t SurfaceFlinger::onLayerDestroyed(const wp<LayerBaseClient>& layer)
1690{
1691    // called by ~ISurface() when all references are gone
1692    status_t err = NO_ERROR;
1693    sp<LayerBaseClient> l(layer.promote());
1694    if (l != NULL) {
1695        Mutex::Autolock _l(mStateLock);
1696        err = removeLayer_l(l);
1697        if (err == NAME_NOT_FOUND) {
1698            // The surface wasn't in the current list, which means it was
1699            // removed already, which means it is in the purgatory,
1700            // and need to be removed from there.
1701            ssize_t idx = mLayerPurgatory.remove(l);
1702            ALOGE_IF(idx < 0,
1703                    "layer=%p is not in the purgatory list", l.get());
1704        }
1705        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
1706                "error removing layer=%p (%s)", l.get(), strerror(-err));
1707    }
1708    return err;
1709}
1710
1711// ---------------------------------------------------------------------------
1712
1713void SurfaceFlinger::onInitializeDisplays() {
1714    // reset screen orientation
1715    Vector<ComposerState> state;
1716    Vector<DisplayState> displays;
1717    DisplayState d;
1718    d.what = DisplayState::eOrientationChanged;
1719    d.token = mDefaultDisplays[DisplayDevice::DISPLAY_PRIMARY];
1720    d.orientation = DisplayState::eOrientationDefault;
1721    displays.add(d);
1722    setTransactionState(state, displays, 0);
1723
1724    // XXX: this should init default device to "unblank" and all other devices to "blank"
1725    onScreenAcquired();
1726}
1727
1728void SurfaceFlinger::initializeDisplays() {
1729    class MessageScreenInitialized : public MessageBase {
1730        SurfaceFlinger* flinger;
1731    public:
1732        MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
1733        virtual bool handler() {
1734            flinger->onInitializeDisplays();
1735            return true;
1736        }
1737    };
1738    sp<MessageBase> msg = new MessageScreenInitialized(this);
1739    postMessageAsync(msg);  // we may be called from main thread, use async message
1740}
1741
1742
1743void SurfaceFlinger::onScreenAcquired() {
1744    ALOGD("Screen about to return, flinger = %p", this);
1745    sp<const DisplayDevice> hw(getDefaultDisplayDevice()); // XXX: this should be per DisplayDevice
1746    getHwComposer().acquire();
1747    hw->acquireScreen();
1748    mEventThread->onScreenAcquired();
1749    mVisibleRegionsDirty = true;
1750    repaintEverything();
1751}
1752
1753void SurfaceFlinger::onScreenReleased() {
1754    ALOGD("About to give-up screen, flinger = %p", this);
1755    sp<const DisplayDevice> hw(getDefaultDisplayDevice()); // XXX: this should be per DisplayDevice
1756    if (hw->isScreenAcquired()) {
1757        mEventThread->onScreenReleased();
1758        hw->releaseScreen();
1759        getHwComposer().release();
1760        // from this point on, SF will stop drawing
1761    }
1762}
1763
1764void SurfaceFlinger::unblank() {
1765    class MessageScreenAcquired : public MessageBase {
1766        SurfaceFlinger* flinger;
1767    public:
1768        MessageScreenAcquired(SurfaceFlinger* flinger) : flinger(flinger) { }
1769        virtual bool handler() {
1770            flinger->onScreenAcquired();
1771            return true;
1772        }
1773    };
1774    sp<MessageBase> msg = new MessageScreenAcquired(this);
1775    postMessageSync(msg);
1776}
1777
1778void SurfaceFlinger::blank() {
1779    class MessageScreenReleased : public MessageBase {
1780        SurfaceFlinger* flinger;
1781    public:
1782        MessageScreenReleased(SurfaceFlinger* flinger) : flinger(flinger) { }
1783        virtual bool handler() {
1784            flinger->onScreenReleased();
1785            return true;
1786        }
1787    };
1788    sp<MessageBase> msg = new MessageScreenReleased(this);
1789    postMessageSync(msg);
1790}
1791
1792// ---------------------------------------------------------------------------
1793
1794status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1795{
1796    const size_t SIZE = 4096;
1797    char buffer[SIZE];
1798    String8 result;
1799
1800    if (!PermissionCache::checkCallingPermission(sDump)) {
1801        snprintf(buffer, SIZE, "Permission Denial: "
1802                "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1803                IPCThreadState::self()->getCallingPid(),
1804                IPCThreadState::self()->getCallingUid());
1805        result.append(buffer);
1806    } else {
1807        // Try to get the main lock, but don't insist if we can't
1808        // (this would indicate SF is stuck, but we want to be able to
1809        // print something in dumpsys).
1810        int retry = 3;
1811        while (mStateLock.tryLock()<0 && --retry>=0) {
1812            usleep(1000000);
1813        }
1814        const bool locked(retry >= 0);
1815        if (!locked) {
1816            snprintf(buffer, SIZE,
1817                    "SurfaceFlinger appears to be unresponsive, "
1818                    "dumping anyways (no locks held)\n");
1819            result.append(buffer);
1820        }
1821
1822        bool dumpAll = true;
1823        size_t index = 0;
1824        size_t numArgs = args.size();
1825        if (numArgs) {
1826            if ((index < numArgs) &&
1827                    (args[index] == String16("--list"))) {
1828                index++;
1829                listLayersLocked(args, index, result, buffer, SIZE);
1830                dumpAll = false;
1831            }
1832
1833            if ((index < numArgs) &&
1834                    (args[index] == String16("--latency"))) {
1835                index++;
1836                dumpStatsLocked(args, index, result, buffer, SIZE);
1837                dumpAll = false;
1838            }
1839
1840            if ((index < numArgs) &&
1841                    (args[index] == String16("--latency-clear"))) {
1842                index++;
1843                clearStatsLocked(args, index, result, buffer, SIZE);
1844                dumpAll = false;
1845            }
1846        }
1847
1848        if (dumpAll) {
1849            dumpAllLocked(result, buffer, SIZE);
1850        }
1851
1852        if (locked) {
1853            mStateLock.unlock();
1854        }
1855    }
1856    write(fd, result.string(), result.size());
1857    return NO_ERROR;
1858}
1859
1860void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
1861        String8& result, char* buffer, size_t SIZE) const
1862{
1863    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1864    const size_t count = currentLayers.size();
1865    for (size_t i=0 ; i<count ; i++) {
1866        const sp<LayerBase>& layer(currentLayers[i]);
1867        snprintf(buffer, SIZE, "%s\n", layer->getName().string());
1868        result.append(buffer);
1869    }
1870}
1871
1872void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
1873        String8& result, char* buffer, size_t SIZE) const
1874{
1875    String8 name;
1876    if (index < args.size()) {
1877        name = String8(args[index]);
1878        index++;
1879    }
1880
1881    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1882    const size_t count = currentLayers.size();
1883    for (size_t i=0 ; i<count ; i++) {
1884        const sp<LayerBase>& layer(currentLayers[i]);
1885        if (name.isEmpty()) {
1886            snprintf(buffer, SIZE, "%s\n", layer->getName().string());
1887            result.append(buffer);
1888        }
1889        if (name.isEmpty() || (name == layer->getName())) {
1890            layer->dumpStats(result, buffer, SIZE);
1891        }
1892    }
1893}
1894
1895void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
1896        String8& result, char* buffer, size_t SIZE) const
1897{
1898    String8 name;
1899    if (index < args.size()) {
1900        name = String8(args[index]);
1901        index++;
1902    }
1903
1904    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1905    const size_t count = currentLayers.size();
1906    for (size_t i=0 ; i<count ; i++) {
1907        const sp<LayerBase>& layer(currentLayers[i]);
1908        if (name.isEmpty() || (name == layer->getName())) {
1909            layer->clearStats();
1910        }
1911    }
1912}
1913
1914void SurfaceFlinger::dumpAllLocked(
1915        String8& result, char* buffer, size_t SIZE) const
1916{
1917    // figure out if we're stuck somewhere
1918    const nsecs_t now = systemTime();
1919    const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1920    const nsecs_t inTransaction(mDebugInTransaction);
1921    nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1922    nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1923
1924    /*
1925     * Dump the visible layer list
1926     */
1927    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1928    const size_t count = currentLayers.size();
1929    snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
1930    result.append(buffer);
1931    for (size_t i=0 ; i<count ; i++) {
1932        const sp<LayerBase>& layer(currentLayers[i]);
1933        layer->dump(result, buffer, SIZE);
1934    }
1935
1936    /*
1937     * Dump the layers in the purgatory
1938     */
1939
1940    const size_t purgatorySize = mLayerPurgatory.size();
1941    snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
1942    result.append(buffer);
1943    for (size_t i=0 ; i<purgatorySize ; i++) {
1944        const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
1945        layer->shortDump(result, buffer, SIZE);
1946    }
1947
1948    /*
1949     * Dump Display state
1950     */
1951
1952    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1953        const sp<const DisplayDevice>& hw(mDisplays[dpy]);
1954        snprintf(buffer, SIZE,
1955                "+ DisplayDevice[%u]\n"
1956                "   id=%x, layerStack=%u, (%4dx%4d), orient=%2d, tr=%08x, "
1957                "flips=%u, secure=%d, numLayers=%u\n",
1958                dpy,
1959                hw->getDisplayType(), hw->getLayerStack(),
1960                hw->getWidth(), hw->getHeight(),
1961                hw->getOrientation(), hw->getTransform().getType(),
1962                hw->getPageFlipCount(),
1963                hw->getSecureLayerVisible(),
1964                hw->getVisibleLayersSortedByZ().size());
1965        result.append(buffer);
1966    }
1967
1968    /*
1969     * Dump SurfaceFlinger global state
1970     */
1971
1972    snprintf(buffer, SIZE, "SurfaceFlinger global state:\n");
1973    result.append(buffer);
1974
1975    HWComposer& hwc(getHwComposer());
1976    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1977    const GLExtensions& extensions(GLExtensions::getInstance());
1978    snprintf(buffer, SIZE, "GLES: %s, %s, %s\n",
1979            extensions.getVendor(),
1980            extensions.getRenderer(),
1981            extensions.getVersion());
1982    result.append(buffer);
1983
1984    snprintf(buffer, SIZE, "EGL : %s\n",
1985            eglQueryString(mEGLDisplay, EGL_VERSION_HW_ANDROID));
1986    result.append(buffer);
1987
1988    snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension());
1989    result.append(buffer);
1990
1991    hw->undefinedRegion.dump(result, "undefinedRegion");
1992    snprintf(buffer, SIZE,
1993            "  orientation=%d, canDraw=%d\n",
1994            hw->getOrientation(), hw->canDraw());
1995    result.append(buffer);
1996    snprintf(buffer, SIZE,
1997            "  last eglSwapBuffers() time: %f us\n"
1998            "  last transaction time     : %f us\n"
1999            "  transaction-flags         : %08x\n"
2000            "  refresh-rate              : %f fps\n"
2001            "  x-dpi                     : %f\n"
2002            "  y-dpi                     : %f\n",
2003            mLastSwapBufferTime/1000.0,
2004            mLastTransactionTime/1000.0,
2005            mTransactionFlags,
2006            1e9 / hwc.getRefreshPeriod(),
2007            hwc.getDpiX(),
2008            hwc.getDpiY());
2009    result.append(buffer);
2010
2011    snprintf(buffer, SIZE, "  eglSwapBuffers time: %f us\n",
2012            inSwapBuffersDuration/1000.0);
2013    result.append(buffer);
2014
2015    snprintf(buffer, SIZE, "  transaction time: %f us\n",
2016            inTransactionDuration/1000.0);
2017    result.append(buffer);
2018
2019    /*
2020     * VSYNC state
2021     */
2022    mEventThread->dump(result, buffer, SIZE);
2023
2024    /*
2025     * Dump HWComposer state
2026     */
2027    snprintf(buffer, SIZE, "h/w composer state:\n");
2028    result.append(buffer);
2029    snprintf(buffer, SIZE, "  h/w composer %s and %s\n",
2030            hwc.initCheck()==NO_ERROR ? "present" : "not present",
2031                    (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
2032    result.append(buffer);
2033    hwc.dump(result, buffer, SIZE, hw->getVisibleLayersSortedByZ());
2034
2035    /*
2036     * Dump gralloc state
2037     */
2038    const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2039    alloc.dump(result);
2040    hw->dump(result);
2041}
2042
2043status_t SurfaceFlinger::onTransact(
2044    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2045{
2046    switch (code) {
2047        case CREATE_CONNECTION:
2048        case SET_TRANSACTION_STATE:
2049        case BOOT_FINISHED:
2050        case BLANK:
2051        case UNBLANK:
2052        {
2053            // codes that require permission check
2054            IPCThreadState* ipc = IPCThreadState::self();
2055            const int pid = ipc->getCallingPid();
2056            const int uid = ipc->getCallingUid();
2057            if ((uid != AID_GRAPHICS) &&
2058                    !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2059                ALOGE("Permission Denial: "
2060                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2061                return PERMISSION_DENIED;
2062            }
2063            break;
2064        }
2065        case CAPTURE_SCREEN:
2066        {
2067            // codes that require permission check
2068            IPCThreadState* ipc = IPCThreadState::self();
2069            const int pid = ipc->getCallingPid();
2070            const int uid = ipc->getCallingUid();
2071            if ((uid != AID_GRAPHICS) &&
2072                    !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2073                ALOGE("Permission Denial: "
2074                        "can't read framebuffer pid=%d, uid=%d", pid, uid);
2075                return PERMISSION_DENIED;
2076            }
2077            break;
2078        }
2079    }
2080
2081    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2082    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2083        CHECK_INTERFACE(ISurfaceComposer, data, reply);
2084        if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2085            IPCThreadState* ipc = IPCThreadState::self();
2086            const int pid = ipc->getCallingPid();
2087            const int uid = ipc->getCallingUid();
2088            ALOGE("Permission Denial: "
2089                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2090            return PERMISSION_DENIED;
2091        }
2092        int n;
2093        switch (code) {
2094            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2095            case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2096                return NO_ERROR;
2097            case 1002:  // SHOW_UPDATES
2098                n = data.readInt32();
2099                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2100                invalidateHwcGeometry();
2101                repaintEverything();
2102                return NO_ERROR;
2103            case 1004:{ // repaint everything
2104                repaintEverything();
2105                return NO_ERROR;
2106            }
2107            case 1005:{ // force transaction
2108                setTransactionFlags(
2109                        eTransactionNeeded|
2110                        eDisplayTransactionNeeded|
2111                        eTraversalNeeded);
2112                return NO_ERROR;
2113            }
2114            case 1006:{ // send empty update
2115                signalRefresh();
2116                return NO_ERROR;
2117            }
2118            case 1008:  // toggle use of hw composer
2119                n = data.readInt32();
2120                mDebugDisableHWC = n ? 1 : 0;
2121                invalidateHwcGeometry();
2122                repaintEverything();
2123                return NO_ERROR;
2124            case 1009:  // toggle use of transform hint
2125                n = data.readInt32();
2126                mDebugDisableTransformHint = n ? 1 : 0;
2127                invalidateHwcGeometry();
2128                repaintEverything();
2129                return NO_ERROR;
2130            case 1010:  // interrogate.
2131                reply->writeInt32(0);
2132                reply->writeInt32(0);
2133                reply->writeInt32(mDebugRegion);
2134                reply->writeInt32(0);
2135                reply->writeInt32(mDebugDisableHWC);
2136                return NO_ERROR;
2137            case 1013: {
2138                Mutex::Autolock _l(mStateLock);
2139                sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2140                reply->writeInt32(hw->getPageFlipCount());
2141            }
2142            return NO_ERROR;
2143        }
2144    }
2145    return err;
2146}
2147
2148void SurfaceFlinger::repaintEverything() {
2149    android_atomic_or(1, &mRepaintEverything);
2150    signalTransaction();
2151}
2152
2153// ---------------------------------------------------------------------------
2154
2155status_t SurfaceFlinger::renderScreenToTexture(uint32_t layerStack,
2156        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2157{
2158    Mutex::Autolock _l(mStateLock);
2159    return renderScreenToTextureLocked(layerStack, textureName, uOut, vOut);
2160}
2161
2162status_t SurfaceFlinger::renderScreenToTextureLocked(uint32_t layerStack,
2163        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2164{
2165    ATRACE_CALL();
2166
2167    if (!GLExtensions::getInstance().haveFramebufferObject())
2168        return INVALID_OPERATION;
2169
2170    // get screen geometry
2171    // FIXME: figure out what it means to have a screenshot texture w/ multi-display
2172    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2173    const uint32_t hw_w = hw->getWidth();
2174    const uint32_t hw_h = hw->getHeight();
2175    GLfloat u = 1;
2176    GLfloat v = 1;
2177
2178    // make sure to clear all GL error flags
2179    while ( glGetError() != GL_NO_ERROR ) ;
2180
2181    // create a FBO
2182    GLuint name, tname;
2183    glGenTextures(1, &tname);
2184    glBindTexture(GL_TEXTURE_2D, tname);
2185    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2186    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2187    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2188            hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2189    if (glGetError() != GL_NO_ERROR) {
2190        while ( glGetError() != GL_NO_ERROR ) ;
2191        GLint tw = (2 << (31 - clz(hw_w)));
2192        GLint th = (2 << (31 - clz(hw_h)));
2193        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2194                tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2195        u = GLfloat(hw_w) / tw;
2196        v = GLfloat(hw_h) / th;
2197    }
2198    glGenFramebuffersOES(1, &name);
2199    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2200    glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
2201            GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
2202
2203    // redraw the screen entirely...
2204    glDisable(GL_TEXTURE_EXTERNAL_OES);
2205    glDisable(GL_TEXTURE_2D);
2206    glClearColor(0,0,0,1);
2207    glClear(GL_COLOR_BUFFER_BIT);
2208    glMatrixMode(GL_MODELVIEW);
2209    glLoadIdentity();
2210    const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2211    const size_t count = layers.size();
2212    for (size_t i=0 ; i<count ; ++i) {
2213        const sp<LayerBase>& layer(layers[i]);
2214        layer->draw(hw);
2215    }
2216
2217    hw->compositionComplete();
2218
2219    // back to main framebuffer
2220    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2221    glDeleteFramebuffersOES(1, &name);
2222
2223    *textureName = tname;
2224    *uOut = u;
2225    *vOut = v;
2226    return NO_ERROR;
2227}
2228
2229// ---------------------------------------------------------------------------
2230
2231status_t SurfaceFlinger::captureScreenImplLocked(const sp<IBinder>& display,
2232        sp<IMemoryHeap>* heap,
2233        uint32_t* w, uint32_t* h, PixelFormat* f,
2234        uint32_t sw, uint32_t sh,
2235        uint32_t minLayerZ, uint32_t maxLayerZ)
2236{
2237    ATRACE_CALL();
2238
2239    status_t result = PERMISSION_DENIED;
2240
2241    if (!GLExtensions::getInstance().haveFramebufferObject()) {
2242        return INVALID_OPERATION;
2243    }
2244
2245    // get screen geometry
2246    sp<const DisplayDevice> hw(getDisplayDevice(display));
2247    const uint32_t hw_w = hw->getWidth();
2248    const uint32_t hw_h = hw->getHeight();
2249
2250    // if we have secure windows on this display, never allow the screen capture
2251    if (hw->getSecureLayerVisible()) {
2252        ALOGW("FB is protected: PERMISSION_DENIED");
2253        return PERMISSION_DENIED;
2254    }
2255
2256    if ((sw > hw_w) || (sh > hw_h)) {
2257        ALOGE("size mismatch (%d, %d) > (%d, %d)", sw, sh, hw_w, hw_h);
2258        return BAD_VALUE;
2259    }
2260
2261    sw = (!sw) ? hw_w : sw;
2262    sh = (!sh) ? hw_h : sh;
2263    const size_t size = sw * sh * 4;
2264    const bool filtering = sw != hw_w || sh != hw_h;
2265
2266//    ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d",
2267//            sw, sh, minLayerZ, maxLayerZ);
2268
2269    // make sure to clear all GL error flags
2270    while ( glGetError() != GL_NO_ERROR ) ;
2271
2272    // create a FBO
2273    GLuint name, tname;
2274    glGenRenderbuffersOES(1, &tname);
2275    glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2276    glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
2277
2278    glGenFramebuffersOES(1, &name);
2279    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2280    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2281            GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2282
2283    GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2284
2285    if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2286
2287        // invert everything, b/c glReadPixel() below will invert the FB
2288        glViewport(0, 0, sw, sh);
2289        glMatrixMode(GL_PROJECTION);
2290        glPushMatrix();
2291        glLoadIdentity();
2292        glOrthof(0, hw_w, hw_h, 0, 0, 1);
2293        glMatrixMode(GL_MODELVIEW);
2294
2295        // redraw the screen entirely...
2296        glClearColor(0,0,0,1);
2297        glClear(GL_COLOR_BUFFER_BIT);
2298
2299        const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2300        const size_t count = layers.size();
2301        for (size_t i=0 ; i<count ; ++i) {
2302            const sp<LayerBase>& layer(layers[i]);
2303            const uint32_t z = layer->drawingState().z;
2304            if (z >= minLayerZ && z <= maxLayerZ) {
2305                if (filtering) layer->setFiltering(true);
2306                layer->draw(hw);
2307                if (filtering) layer->setFiltering(false);
2308            }
2309        }
2310
2311        // check for errors and return screen capture
2312        if (glGetError() != GL_NO_ERROR) {
2313            // error while rendering
2314            result = INVALID_OPERATION;
2315        } else {
2316            // allocate shared memory large enough to hold the
2317            // screen capture
2318            sp<MemoryHeapBase> base(
2319                    new MemoryHeapBase(size, 0, "screen-capture") );
2320            void* const ptr = base->getBase();
2321            if (ptr) {
2322                // capture the screen with glReadPixels()
2323                ScopedTrace _t(ATRACE_TAG, "glReadPixels");
2324                glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
2325                if (glGetError() == GL_NO_ERROR) {
2326                    *heap = base;
2327                    *w = sw;
2328                    *h = sh;
2329                    *f = PIXEL_FORMAT_RGBA_8888;
2330                    result = NO_ERROR;
2331                }
2332            } else {
2333                result = NO_MEMORY;
2334            }
2335        }
2336        glViewport(0, 0, hw_w, hw_h);
2337        glMatrixMode(GL_PROJECTION);
2338        glPopMatrix();
2339        glMatrixMode(GL_MODELVIEW);
2340    } else {
2341        result = BAD_VALUE;
2342    }
2343
2344    // release FBO resources
2345    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2346    glDeleteRenderbuffersOES(1, &tname);
2347    glDeleteFramebuffersOES(1, &name);
2348
2349    hw->compositionComplete();
2350
2351//    ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK");
2352
2353    return result;
2354}
2355
2356
2357status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2358        sp<IMemoryHeap>* heap,
2359        uint32_t* width, uint32_t* height, PixelFormat* format,
2360        uint32_t sw, uint32_t sh,
2361        uint32_t minLayerZ, uint32_t maxLayerZ)
2362{
2363    if (CC_UNLIKELY(display == 0))
2364        return BAD_VALUE;
2365
2366    if (!GLExtensions::getInstance().haveFramebufferObject())
2367        return INVALID_OPERATION;
2368
2369    class MessageCaptureScreen : public MessageBase {
2370        SurfaceFlinger* flinger;
2371        sp<IBinder> display;
2372        sp<IMemoryHeap>* heap;
2373        uint32_t* w;
2374        uint32_t* h;
2375        PixelFormat* f;
2376        uint32_t sw;
2377        uint32_t sh;
2378        uint32_t minLayerZ;
2379        uint32_t maxLayerZ;
2380        status_t result;
2381    public:
2382        MessageCaptureScreen(SurfaceFlinger* flinger, const sp<IBinder>& display,
2383                sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
2384                uint32_t sw, uint32_t sh,
2385                uint32_t minLayerZ, uint32_t maxLayerZ)
2386            : flinger(flinger), display(display),
2387              heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
2388              minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2389              result(PERMISSION_DENIED)
2390        {
2391        }
2392        status_t getResult() const {
2393            return result;
2394        }
2395        virtual bool handler() {
2396            Mutex::Autolock _l(flinger->mStateLock);
2397            result = flinger->captureScreenImplLocked(display,
2398                    heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
2399            return true;
2400        }
2401    };
2402
2403    sp<MessageBase> msg = new MessageCaptureScreen(this,
2404            display, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
2405    status_t res = postMessageSync(msg);
2406    if (res == NO_ERROR) {
2407        res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2408    }
2409    return res;
2410}
2411
2412// ---------------------------------------------------------------------------
2413
2414SurfaceFlinger::LayerVector::LayerVector() {
2415}
2416
2417SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
2418    : SortedVector<sp<LayerBase> >(rhs) {
2419}
2420
2421int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
2422    const void* rhs) const
2423{
2424    // sort layers per layer-stack, then by z-order and finally by sequence
2425    const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs));
2426    const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs));
2427
2428    uint32_t ls = l->currentState().layerStack;
2429    uint32_t rs = r->currentState().layerStack;
2430    if (ls != rs)
2431        return ls - rs;
2432
2433    uint32_t lz = l->currentState().z;
2434    uint32_t rz = r->currentState().z;
2435    if (lz != rz)
2436        return lz - rz;
2437
2438    return l->sequence - r->sequence;
2439}
2440
2441// ---------------------------------------------------------------------------
2442
2443SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
2444    : type(DisplayDevice::DISPLAY_ID_INVALID) {
2445}
2446
2447SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
2448    : type(type), layerStack(0), orientation(0) {
2449}
2450
2451// ---------------------------------------------------------------------------
2452
2453GraphicBufferAlloc::GraphicBufferAlloc() {}
2454
2455GraphicBufferAlloc::~GraphicBufferAlloc() {}
2456
2457sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h,
2458        PixelFormat format, uint32_t usage, status_t* error) {
2459    sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
2460    status_t err = graphicBuffer->initCheck();
2461    *error = err;
2462    if (err != 0 || graphicBuffer->handle == 0) {
2463        if (err == NO_MEMORY) {
2464            GraphicBuffer::dumpAllocationsToSystemLog();
2465        }
2466        ALOGE("GraphicBufferAlloc::createGraphicBuffer(w=%d, h=%d) "
2467             "failed (%s), handle=%p",
2468                w, h, strerror(-err), graphicBuffer->handle);
2469        return 0;
2470    }
2471    return graphicBuffer;
2472}
2473
2474// ---------------------------------------------------------------------------
2475
2476}; // namespace android
2477