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