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