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