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