SurfaceFlinger.cpp revision 7cc6df59572582652078df5aeac9e6c67d7fa81e
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#include <dlfcn.h>
24
25#include <EGL/egl.h>
26#include <GLES/gl.h>
27
28#include <cutils/log.h>
29#include <cutils/properties.h>
30
31#include <binder/IPCThreadState.h>
32#include <binder/IServiceManager.h>
33#include <binder/MemoryHeapBase.h>
34#include <binder/PermissionCache.h>
35
36#include <ui/DisplayInfo.h>
37
38#include <gui/BitTube.h>
39#include <gui/BufferQueue.h>
40#include <gui/GuiConfig.h>
41#include <gui/IDisplayEventConnection.h>
42#include <gui/Surface.h>
43#include <gui/GraphicBufferAlloc.h>
44
45#include <ui/GraphicBufferAllocator.h>
46#include <ui/PixelFormat.h>
47#include <ui/UiConfig.h>
48
49#include <utils/misc.h>
50#include <utils/String8.h>
51#include <utils/String16.h>
52#include <utils/StopWatch.h>
53#include <utils/Trace.h>
54
55#include <private/android_filesystem_config.h>
56#include <private/gui/SyncFeatures.h>
57
58#include "Client.h"
59#include "clz.h"
60#include "Colorizer.h"
61#include "DdmConnection.h"
62#include "DisplayDevice.h"
63#include "EventThread.h"
64#include "GLExtensions.h"
65#include "Layer.h"
66#include "LayerDim.h"
67#include "SurfaceFlinger.h"
68
69#include "DisplayHardware/FramebufferSurface.h"
70#include "DisplayHardware/HWComposer.h"
71#include "DisplayHardware/VirtualDisplaySurface.h"
72
73#define DISPLAY_COUNT       1
74
75EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
76
77namespace android {
78// ---------------------------------------------------------------------------
79
80const String16 sHardwareTest("android.permission.HARDWARE_TEST");
81const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
82const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
83const String16 sDump("android.permission.DUMP");
84
85// ---------------------------------------------------------------------------
86
87SurfaceFlinger::SurfaceFlinger()
88    :   BnSurfaceComposer(), Thread(false),
89        mTransactionFlags(0),
90        mTransactionPending(false),
91        mAnimTransactionPending(false),
92        mLayersRemoved(false),
93        mRepaintEverything(0),
94        mBootTime(systemTime()),
95        mVisibleRegionsDirty(false),
96        mHwWorkListDirty(false),
97        mAnimCompositionPending(false),
98        mDebugRegion(0),
99        mDebugDDMS(0),
100        mDebugDisableHWC(0),
101        mDebugDisableTransformHint(0),
102        mDebugInSwapBuffers(0),
103        mLastSwapBufferTime(0),
104        mDebugInTransaction(0),
105        mLastTransactionTime(0),
106        mBootFinished(false)
107{
108    ALOGI("SurfaceFlinger is starting");
109
110    // debugging stuff...
111    char value[PROPERTY_VALUE_MAX];
112
113    property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
114    mGpuToCpuSupported = !atoi(value);
115
116    property_get("debug.sf.showupdates", value, "0");
117    mDebugRegion = atoi(value);
118
119    property_get("debug.sf.ddms", value, "0");
120    mDebugDDMS = atoi(value);
121    if (mDebugDDMS) {
122        if (!startDdmConnection()) {
123            // start failed, and DDMS debugging not enabled
124            mDebugDDMS = 0;
125        }
126    }
127    ALOGI_IF(mDebugRegion, "showupdates enabled");
128    ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
129}
130
131void SurfaceFlinger::onFirstRef()
132{
133    mEventQueue.init(this);
134
135    run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
136
137    // Wait for the main thread to be done with its initialization
138    mReadyToRunBarrier.wait();
139}
140
141
142SurfaceFlinger::~SurfaceFlinger()
143{
144    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
145    eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
146    eglTerminate(display);
147}
148
149void SurfaceFlinger::binderDied(const wp<IBinder>& who)
150{
151    // the window manager died on us. prepare its eulogy.
152
153    // restore initial conditions (default device unblank, etc)
154    initializeDisplays();
155
156    // restart the boot-animation
157    startBootAnim();
158}
159
160sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
161{
162    sp<ISurfaceComposerClient> bclient;
163    sp<Client> client(new Client(this));
164    status_t err = client->initCheck();
165    if (err == NO_ERROR) {
166        bclient = client;
167    }
168    return bclient;
169}
170
171sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
172        bool secure)
173{
174    class DisplayToken : public BBinder {
175        sp<SurfaceFlinger> flinger;
176        virtual ~DisplayToken() {
177             // no more references, this display must be terminated
178             Mutex::Autolock _l(flinger->mStateLock);
179             flinger->mCurrentState.displays.removeItem(this);
180             flinger->setTransactionFlags(eDisplayTransactionNeeded);
181         }
182     public:
183        DisplayToken(const sp<SurfaceFlinger>& flinger)
184            : flinger(flinger) {
185        }
186    };
187
188    sp<BBinder> token = new DisplayToken(this);
189
190    Mutex::Autolock _l(mStateLock);
191    DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
192    info.displayName = displayName;
193    info.isSecure = secure;
194    mCurrentState.displays.add(token, info);
195
196    return token;
197}
198
199void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
200    ALOGW_IF(mBuiltinDisplays[type],
201            "Overwriting display token for display type %d", type);
202    mBuiltinDisplays[type] = new BBinder();
203    DisplayDeviceState info(type);
204    // All non-virtual displays are currently considered secure.
205    info.isSecure = true;
206    mCurrentState.displays.add(mBuiltinDisplays[type], info);
207}
208
209sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
210    if (uint32_t(id) >= DisplayDevice::NUM_DISPLAY_TYPES) {
211        ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
212        return NULL;
213    }
214    return mBuiltinDisplays[id];
215}
216
217sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
218{
219    sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
220    return gba;
221}
222
223void SurfaceFlinger::bootFinished()
224{
225    const nsecs_t now = systemTime();
226    const nsecs_t duration = now - mBootTime;
227    ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
228    mBootFinished = true;
229
230    // wait patiently for the window manager death
231    const String16 name("window");
232    sp<IBinder> window(defaultServiceManager()->getService(name));
233    if (window != 0) {
234        window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
235    }
236
237    // stop boot animation
238    // formerly we would just kill the process, but we now ask it to exit so it
239    // can choose where to stop the animation.
240    property_set("service.bootanim.exit", "1");
241}
242
243void SurfaceFlinger::deleteTextureAsync(GLuint texture) {
244    class MessageDestroyGLTexture : public MessageBase {
245        GLuint texture;
246    public:
247        MessageDestroyGLTexture(GLuint texture)
248            : texture(texture) {
249        }
250        virtual bool handler() {
251            glDeleteTextures(1, &texture);
252            return true;
253        }
254    };
255    postMessageAsync(new MessageDestroyGLTexture(texture));
256}
257
258status_t SurfaceFlinger::selectConfigForAttribute(
259        EGLDisplay dpy,
260        EGLint const* attrs,
261        EGLint attribute, EGLint wanted,
262        EGLConfig* outConfig)
263{
264    EGLConfig config = NULL;
265    EGLint numConfigs = -1, n=0;
266    eglGetConfigs(dpy, NULL, 0, &numConfigs);
267    EGLConfig* const configs = new EGLConfig[numConfigs];
268    eglChooseConfig(dpy, attrs, configs, numConfigs, &n);
269
270    if (n) {
271        if (attribute != EGL_NONE) {
272            for (int i=0 ; i<n ; i++) {
273                EGLint value = 0;
274                eglGetConfigAttrib(dpy, configs[i], attribute, &value);
275                if (wanted == value) {
276                    *outConfig = configs[i];
277                    delete [] configs;
278                    return NO_ERROR;
279                }
280            }
281        } else {
282            // just pick the first one
283            *outConfig = configs[0];
284            delete [] configs;
285            return NO_ERROR;
286        }
287    }
288    delete [] configs;
289    return NAME_NOT_FOUND;
290}
291
292class EGLAttributeVector {
293    struct Attribute;
294    class Adder;
295    friend class Adder;
296    KeyedVector<Attribute, EGLint> mList;
297    struct Attribute {
298        Attribute() {};
299        Attribute(EGLint v) : v(v) { }
300        EGLint v;
301        bool operator < (const Attribute& other) const {
302            // this places EGL_NONE at the end
303            EGLint lhs(v);
304            EGLint rhs(other.v);
305            if (lhs == EGL_NONE) lhs = 0x7FFFFFFF;
306            if (rhs == EGL_NONE) rhs = 0x7FFFFFFF;
307            return lhs < rhs;
308        }
309    };
310    class Adder {
311        friend class EGLAttributeVector;
312        EGLAttributeVector& v;
313        EGLint attribute;
314        Adder(EGLAttributeVector& v, EGLint attribute)
315            : v(v), attribute(attribute) {
316        }
317    public:
318        void operator = (EGLint value) {
319            if (attribute != EGL_NONE) {
320                v.mList.add(attribute, value);
321            }
322        }
323        operator EGLint () const { return v.mList[attribute]; }
324    };
325public:
326    EGLAttributeVector() {
327        mList.add(EGL_NONE, EGL_NONE);
328    }
329    void remove(EGLint attribute) {
330        if (attribute != EGL_NONE) {
331            mList.removeItem(attribute);
332        }
333    }
334    Adder operator [] (EGLint attribute) {
335        return Adder(*this, attribute);
336    }
337    EGLint operator [] (EGLint attribute) const {
338       return mList[attribute];
339    }
340    // cast-operator to (EGLint const*)
341    operator EGLint const* () const { return &mList.keyAt(0).v; }
342};
343
344EGLConfig SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId) {
345    // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
346    // it is to be used with WIFI displays
347    EGLConfig config;
348    EGLint dummy;
349    status_t err;
350
351    EGLAttributeVector attribs;
352    attribs[EGL_SURFACE_TYPE]               = EGL_WINDOW_BIT;
353    attribs[EGL_RECORDABLE_ANDROID]         = EGL_TRUE;
354    attribs[EGL_FRAMEBUFFER_TARGET_ANDROID] = EGL_TRUE;
355    attribs[EGL_RED_SIZE]                   = 8;
356    attribs[EGL_GREEN_SIZE]                 = 8;
357    attribs[EGL_BLUE_SIZE]                  = 8;
358
359    err = selectConfigForAttribute(display, attribs, EGL_NONE, EGL_NONE, &config);
360    if (!err)
361        goto success;
362
363    // maybe we failed because of EGL_FRAMEBUFFER_TARGET_ANDROID
364    ALOGW("no suitable EGLConfig found, trying without EGL_FRAMEBUFFER_TARGET_ANDROID");
365    attribs.remove(EGL_FRAMEBUFFER_TARGET_ANDROID);
366    err = selectConfigForAttribute(display, attribs,
367            EGL_NATIVE_VISUAL_ID, nativeVisualId, &config);
368    if (!err)
369        goto success;
370
371    // maybe we failed because of EGL_RECORDABLE_ANDROID
372    ALOGW("no suitable EGLConfig found, trying without EGL_RECORDABLE_ANDROID");
373    attribs.remove(EGL_RECORDABLE_ANDROID);
374    err = selectConfigForAttribute(display, attribs,
375            EGL_NATIVE_VISUAL_ID, nativeVisualId, &config);
376    if (!err)
377        goto success;
378
379    // allow less than 24-bit color; the non-gpu-accelerated emulator only
380    // supports 16-bit color
381    ALOGW("no suitable EGLConfig found, trying with 16-bit color allowed");
382    attribs.remove(EGL_RED_SIZE);
383    attribs.remove(EGL_GREEN_SIZE);
384    attribs.remove(EGL_BLUE_SIZE);
385    err = selectConfigForAttribute(display, attribs,
386            EGL_NATIVE_VISUAL_ID, nativeVisualId, &config);
387    if (!err)
388        goto success;
389
390    // this EGL is too lame for Android
391    ALOGE("no suitable EGLConfig found, giving up");
392
393    return 0;
394
395success:
396    if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy))
397        ALOGW_IF(dummy == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
398    return config;
399}
400
401EGLContext SurfaceFlinger::createGLContext(EGLDisplay display, EGLConfig config) {
402    // Also create our EGLContext
403    EGLint contextAttributes[] = {
404#ifdef EGL_IMG_context_priority
405#ifdef HAS_CONTEXT_PRIORITY
406#warning "using EGL_IMG_context_priority"
407            EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_HIGH_IMG,
408#endif
409#endif
410            EGL_NONE, EGL_NONE
411    };
412    EGLContext ctxt = eglCreateContext(display, config, NULL, contextAttributes);
413    ALOGE_IF(ctxt==EGL_NO_CONTEXT, "EGLContext creation failed");
414    return ctxt;
415}
416
417static GlesVersion parseGlesVersion(const char* str) {
418    int major, minor;
419    if (sscanf(str, "OpenGL ES-CM %d.%d", &major, &minor) != 2) {
420        ALOGW("Unable to parse GL_VERSION string: \"%s\"", str);
421        return GLES_VERSION_1_0;
422    }
423
424    if (major == 1 && minor == 0) return GLES_VERSION_1_0;
425    if (major == 1 && minor >= 1) return GLES_VERSION_1_1;
426    if (major == 2 && minor >= 0) return GLES_VERSION_2_0;
427    if (major == 3 && minor >= 0) return GLES_VERSION_3_0;
428
429    ALOGW("Unrecognized OpenGL ES version: %d.%d", major, minor);
430    return GLES_VERSION_1_0;
431}
432
433void SurfaceFlinger::initializeGL(EGLDisplay display) {
434    GLExtensions& extensions(GLExtensions::getInstance());
435    extensions.initWithGLStrings(
436            glGetString(GL_VENDOR),
437            glGetString(GL_RENDERER),
438            glGetString(GL_VERSION),
439            glGetString(GL_EXTENSIONS),
440            eglQueryString(display, EGL_VENDOR),
441            eglQueryString(display, EGL_VERSION),
442            eglQueryString(display, EGL_EXTENSIONS));
443
444    mGlesVersion = parseGlesVersion(extensions.getVersion());
445
446    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
447    glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims);
448
449    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
450    glPixelStorei(GL_PACK_ALIGNMENT, 4);
451    glEnableClientState(GL_VERTEX_ARRAY);
452    glShadeModel(GL_FLAT);
453    glDisable(GL_DITHER);
454    glDisable(GL_CULL_FACE);
455
456    struct pack565 {
457        inline uint16_t operator() (int r, int g, int b) const {
458            return (r<<11)|(g<<5)|b;
459        }
460    } pack565;
461
462    const uint16_t protTexData[] = { pack565(0x03, 0x03, 0x03) };
463    glGenTextures(1, &mProtectedTexName);
464    glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
465    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
466    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
467    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
468    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
469    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0,
470            GL_RGB, GL_UNSIGNED_SHORT_5_6_5, protTexData);
471
472    // print some debugging info
473    EGLint r,g,b,a;
474    eglGetConfigAttrib(display, mEGLConfig, EGL_RED_SIZE,   &r);
475    eglGetConfigAttrib(display, mEGLConfig, EGL_GREEN_SIZE, &g);
476    eglGetConfigAttrib(display, mEGLConfig, EGL_BLUE_SIZE,  &b);
477    eglGetConfigAttrib(display, mEGLConfig, EGL_ALPHA_SIZE, &a);
478    ALOGI("EGL informations:");
479    ALOGI("vendor    : %s", extensions.getEglVendor());
480    ALOGI("version   : %s", extensions.getEglVersion());
481    ALOGI("extensions: %s", extensions.getEglExtension());
482    ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported");
483    ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig);
484    ALOGI("OpenGL ES informations:");
485    ALOGI("vendor    : %s", extensions.getVendor());
486    ALOGI("renderer  : %s", extensions.getRenderer());
487    ALOGI("version   : %s", extensions.getVersion());
488    ALOGI("extensions: %s", extensions.getExtension());
489    ALOGI("GL_MAX_TEXTURE_SIZE = %d", mMaxTextureSize);
490    ALOGI("GL_MAX_VIEWPORT_DIMS = %d x %d", mMaxViewportDims[0], mMaxViewportDims[1]);
491}
492
493status_t SurfaceFlinger::readyToRun()
494{
495    ALOGI(  "SurfaceFlinger's main thread ready to run. "
496            "Initializing graphics H/W...");
497
498    Mutex::Autolock _l(mStateLock);
499
500    // initialize EGL for the default display
501    mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
502    eglInitialize(mEGLDisplay, NULL, NULL);
503
504    // Initialize the H/W composer object.  There may or may not be an
505    // actual hardware composer underneath.
506    mHwc = new HWComposer(this,
507            *static_cast<HWComposer::EventHandler *>(this));
508
509    // initialize the config and context
510    EGLint format = mHwc->getVisualID();
511    mEGLConfig  = selectEGLConfig(mEGLDisplay, format);
512    mEGLContext = createGLContext(mEGLDisplay, mEGLConfig);
513
514    // figure out which format we got
515    eglGetConfigAttrib(mEGLDisplay, mEGLConfig,
516            EGL_NATIVE_VISUAL_ID, &mEGLNativeVisualId);
517
518    LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
519            "couldn't create EGLContext");
520
521    // initialize our non-virtual displays
522    for (size_t i=0 ; i<DisplayDevice::NUM_DISPLAY_TYPES ; i++) {
523        DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
524        // set-up the displays that are already connected
525        if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
526            // All non-virtual displays are currently considered secure.
527            bool isSecure = true;
528            createBuiltinDisplayLocked(type);
529            wp<IBinder> token = mBuiltinDisplays[i];
530
531            sp<DisplayDevice> hw = new DisplayDevice(this,
532                    type, allocateHwcDisplayId(type), isSecure, token,
533                    new FramebufferSurface(*mHwc, i),
534                    mEGLConfig);
535            if (i > DisplayDevice::DISPLAY_PRIMARY) {
536                // FIXME: currently we don't get blank/unblank requests
537                // for displays other than the main display, so we always
538                // assume a connected display is unblanked.
539                ALOGD("marking display %d as acquired/unblanked", i);
540                hw->acquireScreen();
541            }
542            mDisplays.add(token, hw);
543        }
544    }
545
546    //  we need a GL context current in a few places, when initializing
547    //  OpenGL ES (see below), or creating a layer,
548    //  or when a texture is (asynchronously) destroyed, and for that
549    //  we need a valid surface, so it's convenient to use the main display
550    //  for that.
551    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
552
553    //  initialize OpenGL ES
554    DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
555    initializeGL(mEGLDisplay);
556
557    // start the EventThread
558    mEventThread = new EventThread(this);
559    mEventQueue.setEventThread(mEventThread);
560
561    // initialize our drawing state
562    mDrawingState = mCurrentState;
563
564
565    // We're now ready to accept clients...
566    mReadyToRunBarrier.open();
567
568    // set initial conditions (e.g. unblank default device)
569    initializeDisplays();
570
571    // start boot animation
572    startBootAnim();
573
574    return NO_ERROR;
575}
576
577int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
578    return (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) ?
579            type : mHwc->allocateDisplayId();
580}
581
582void SurfaceFlinger::startBootAnim() {
583    // start boot animation
584    property_set("service.bootanim.exit", "0");
585    property_set("ctl.start", "bootanim");
586}
587
588uint32_t SurfaceFlinger::getMaxTextureSize() const {
589    return mMaxTextureSize;
590}
591
592uint32_t SurfaceFlinger::getMaxViewportDims() const {
593    return mMaxViewportDims[0] < mMaxViewportDims[1] ?
594            mMaxViewportDims[0] : mMaxViewportDims[1];
595}
596
597// ----------------------------------------------------------------------------
598
599bool SurfaceFlinger::authenticateSurfaceTexture(
600        const sp<IGraphicBufferProducer>& bufferProducer) const {
601    Mutex::Autolock _l(mStateLock);
602    sp<IBinder> surfaceTextureBinder(bufferProducer->asBinder());
603    return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
604}
605
606status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info) {
607    int32_t type = NAME_NOT_FOUND;
608    for (int i=0 ; i<DisplayDevice::NUM_DISPLAY_TYPES ; i++) {
609        if (display == mBuiltinDisplays[i]) {
610            type = i;
611            break;
612        }
613    }
614
615    if (type < 0) {
616        return type;
617    }
618
619    const HWComposer& hwc(getHwComposer());
620    float xdpi = hwc.getDpiX(type);
621    float ydpi = hwc.getDpiY(type);
622
623    // TODO: Not sure if display density should handled by SF any longer
624    class Density {
625        static int getDensityFromProperty(char const* propName) {
626            char property[PROPERTY_VALUE_MAX];
627            int density = 0;
628            if (property_get(propName, property, NULL) > 0) {
629                density = atoi(property);
630            }
631            return density;
632        }
633    public:
634        static int getEmuDensity() {
635            return getDensityFromProperty("qemu.sf.lcd_density"); }
636        static int getBuildDensity()  {
637            return getDensityFromProperty("ro.sf.lcd_density"); }
638    };
639
640    if (type == DisplayDevice::DISPLAY_PRIMARY) {
641        // The density of the device is provided by a build property
642        float density = Density::getBuildDensity() / 160.0f;
643        if (density == 0) {
644            // the build doesn't provide a density -- this is wrong!
645            // use xdpi instead
646            ALOGE("ro.sf.lcd_density must be defined as a build property");
647            density = xdpi / 160.0f;
648        }
649        if (Density::getEmuDensity()) {
650            // if "qemu.sf.lcd_density" is specified, it overrides everything
651            xdpi = ydpi = density = Density::getEmuDensity();
652            density /= 160.0f;
653        }
654        info->density = density;
655
656        // TODO: this needs to go away (currently needed only by webkit)
657        sp<const DisplayDevice> hw(getDefaultDisplayDevice());
658        info->orientation = hw->getOrientation();
659        getPixelFormatInfo(hw->getFormat(), &info->pixelFormatInfo);
660    } else {
661        // TODO: where should this value come from?
662        static const int TV_DENSITY = 213;
663        info->density = TV_DENSITY / 160.0f;
664        info->orientation = 0;
665    }
666
667    info->w = hwc.getWidth(type);
668    info->h = hwc.getHeight(type);
669    info->xdpi = xdpi;
670    info->ydpi = ydpi;
671    info->fps = float(1e9 / hwc.getRefreshPeriod(type));
672
673    // All non-virtual displays are currently considered secure.
674    info->secure = true;
675
676    return NO_ERROR;
677}
678
679// ----------------------------------------------------------------------------
680
681sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
682    return mEventThread->createEventConnection();
683}
684
685// ----------------------------------------------------------------------------
686
687void SurfaceFlinger::waitForEvent() {
688    mEventQueue.waitMessage();
689}
690
691void SurfaceFlinger::signalTransaction() {
692    mEventQueue.invalidate();
693}
694
695void SurfaceFlinger::signalLayerUpdate() {
696    mEventQueue.invalidate();
697}
698
699void SurfaceFlinger::signalRefresh() {
700    mEventQueue.refresh();
701}
702
703status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
704        nsecs_t reltime, uint32_t flags) {
705    return mEventQueue.postMessage(msg, reltime);
706}
707
708status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
709        nsecs_t reltime, uint32_t flags) {
710    status_t res = mEventQueue.postMessage(msg, reltime);
711    if (res == NO_ERROR) {
712        msg->wait();
713    }
714    return res;
715}
716
717bool SurfaceFlinger::threadLoop() {
718    waitForEvent();
719    return true;
720}
721
722void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
723    if (mEventThread == NULL) {
724        // This is a temporary workaround for b/7145521.  A non-null pointer
725        // does not mean EventThread has finished initializing, so this
726        // is not a correct fix.
727        ALOGW("WARNING: EventThread not started, ignoring vsync");
728        return;
729    }
730    if (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) {
731        // we should only receive DisplayDevice::DisplayType from the vsync callback
732        mEventThread->onVSyncReceived(type, timestamp);
733    }
734}
735
736void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
737    if (mEventThread == NULL) {
738        // This is a temporary workaround for b/7145521.  A non-null pointer
739        // does not mean EventThread has finished initializing, so this
740        // is not a correct fix.
741        ALOGW("WARNING: EventThread not started, ignoring hotplug");
742        return;
743    }
744
745    if (uint32_t(type) < DisplayDevice::NUM_DISPLAY_TYPES) {
746        Mutex::Autolock _l(mStateLock);
747        if (connected) {
748            createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
749        } else {
750            mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
751            mBuiltinDisplays[type].clear();
752        }
753        setTransactionFlags(eDisplayTransactionNeeded);
754
755        // Defer EventThread notification until SF has updated mDisplays.
756    }
757}
758
759void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
760    getHwComposer().eventControl(disp, event, enabled);
761}
762
763void SurfaceFlinger::onMessageReceived(int32_t what) {
764    ATRACE_CALL();
765    switch (what) {
766    case MessageQueue::TRANSACTION:
767        handleMessageTransaction();
768        break;
769    case MessageQueue::INVALIDATE:
770        handleMessageTransaction();
771        handleMessageInvalidate();
772        signalRefresh();
773        break;
774    case MessageQueue::REFRESH:
775        handleMessageRefresh();
776        break;
777    }
778}
779
780void SurfaceFlinger::handleMessageTransaction() {
781    uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
782    if (transactionFlags) {
783        handleTransaction(transactionFlags);
784    }
785}
786
787void SurfaceFlinger::handleMessageInvalidate() {
788    ATRACE_CALL();
789    handlePageFlip();
790}
791
792void SurfaceFlinger::handleMessageRefresh() {
793    ATRACE_CALL();
794    preComposition();
795    rebuildLayerStacks();
796    setUpHWComposer();
797    doDebugFlashRegions();
798    doComposition();
799    postComposition();
800}
801
802void SurfaceFlinger::doDebugFlashRegions()
803{
804    // is debugging enabled
805    if (CC_LIKELY(!mDebugRegion))
806        return;
807
808    const bool repaintEverything = mRepaintEverything;
809    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
810        const sp<DisplayDevice>& hw(mDisplays[dpy]);
811        if (hw->canDraw()) {
812            // transform the dirty region into this screen's coordinate space
813            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
814            if (!dirtyRegion.isEmpty()) {
815                // redraw the whole screen
816                doComposeSurfaces(hw, Region(hw->bounds()));
817
818                // and draw the dirty region
819                glDisable(GL_TEXTURE_EXTERNAL_OES);
820                glDisable(GL_TEXTURE_2D);
821                glDisable(GL_BLEND);
822                glColor4f(1, 0, 1, 1);
823                const int32_t height = hw->getHeight();
824                Region::const_iterator it = dirtyRegion.begin();
825                Region::const_iterator const end = dirtyRegion.end();
826                while (it != end) {
827                    const Rect& r = *it++;
828                    GLfloat vertices[][2] = {
829                            { (GLfloat) r.left,  (GLfloat) (height - r.top) },
830                            { (GLfloat) r.left,  (GLfloat) (height - r.bottom) },
831                            { (GLfloat) r.right, (GLfloat) (height - r.bottom) },
832                            { (GLfloat) r.right, (GLfloat) (height - r.top) }
833                    };
834                    glVertexPointer(2, GL_FLOAT, 0, vertices);
835                    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
836                }
837                hw->compositionComplete();
838                hw->swapBuffers(getHwComposer());
839            }
840        }
841    }
842
843    postFramebuffer();
844
845    if (mDebugRegion > 1) {
846        usleep(mDebugRegion * 1000);
847    }
848
849    HWComposer& hwc(getHwComposer());
850    if (hwc.initCheck() == NO_ERROR) {
851        status_t err = hwc.prepare();
852        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
853    }
854}
855
856void SurfaceFlinger::preComposition()
857{
858    bool needExtraInvalidate = false;
859    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
860    const size_t count = currentLayers.size();
861    for (size_t i=0 ; i<count ; i++) {
862        if (currentLayers[i]->onPreComposition()) {
863            needExtraInvalidate = true;
864        }
865    }
866    if (needExtraInvalidate) {
867        signalLayerUpdate();
868    }
869}
870
871void SurfaceFlinger::postComposition()
872{
873    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
874    const size_t count = currentLayers.size();
875    for (size_t i=0 ; i<count ; i++) {
876        currentLayers[i]->onPostComposition();
877    }
878
879    if (mAnimCompositionPending) {
880        mAnimCompositionPending = false;
881
882        const HWComposer& hwc = getHwComposer();
883        sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
884        if (presentFence->isValid()) {
885            mAnimFrameTracker.setActualPresentFence(presentFence);
886        } else {
887            // The HWC doesn't support present fences, so use the refresh
888            // timestamp instead.
889            nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
890            mAnimFrameTracker.setActualPresentTime(presentTime);
891        }
892        mAnimFrameTracker.advanceFrame();
893    }
894}
895
896void SurfaceFlinger::rebuildLayerStacks() {
897    // rebuild the visible layer list per screen
898    if (CC_UNLIKELY(mVisibleRegionsDirty)) {
899        ATRACE_CALL();
900        mVisibleRegionsDirty = false;
901        invalidateHwcGeometry();
902
903        const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
904        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
905            Region opaqueRegion;
906            Region dirtyRegion;
907            Vector< sp<Layer> > layersSortedByZ;
908            const sp<DisplayDevice>& hw(mDisplays[dpy]);
909            const Transform& tr(hw->getTransform());
910            const Rect bounds(hw->getBounds());
911            if (hw->canDraw()) {
912                SurfaceFlinger::computeVisibleRegions(currentLayers,
913                        hw->getLayerStack(), dirtyRegion, opaqueRegion);
914
915                const size_t count = currentLayers.size();
916                for (size_t i=0 ; i<count ; i++) {
917                    const sp<Layer>& layer(currentLayers[i]);
918                    const Layer::State& s(layer->drawingState());
919                    if (s.layerStack == hw->getLayerStack()) {
920                        Region drawRegion(tr.transform(
921                                layer->visibleNonTransparentRegion));
922                        drawRegion.andSelf(bounds);
923                        if (!drawRegion.isEmpty()) {
924                            layersSortedByZ.add(layer);
925                        }
926                    }
927                }
928            }
929            hw->setVisibleLayersSortedByZ(layersSortedByZ);
930            hw->undefinedRegion.set(bounds);
931            hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
932            hw->dirtyRegion.orSelf(dirtyRegion);
933        }
934    }
935}
936
937void SurfaceFlinger::setUpHWComposer() {
938    HWComposer& hwc(getHwComposer());
939    if (hwc.initCheck() == NO_ERROR) {
940        // build the h/w work list
941        if (CC_UNLIKELY(mHwWorkListDirty)) {
942            mHwWorkListDirty = false;
943            for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
944                sp<const DisplayDevice> hw(mDisplays[dpy]);
945                const int32_t id = hw->getHwcDisplayId();
946                if (id >= 0) {
947                    const Vector< sp<Layer> >& currentLayers(
948                        hw->getVisibleLayersSortedByZ());
949                    const size_t count = currentLayers.size();
950                    if (hwc.createWorkList(id, count) == NO_ERROR) {
951                        HWComposer::LayerListIterator cur = hwc.begin(id);
952                        const HWComposer::LayerListIterator end = hwc.end(id);
953                        for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
954                            const sp<Layer>& layer(currentLayers[i]);
955                            layer->setGeometry(hw, *cur);
956                            if (mDebugDisableHWC || mDebugRegion) {
957                                cur->setSkip(true);
958                            }
959                        }
960                    }
961                }
962            }
963        }
964
965        // set the per-frame data
966        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
967            sp<const DisplayDevice> hw(mDisplays[dpy]);
968            const int32_t id = hw->getHwcDisplayId();
969            if (id >= 0) {
970                const Vector< sp<Layer> >& currentLayers(
971                    hw->getVisibleLayersSortedByZ());
972                const size_t count = currentLayers.size();
973                HWComposer::LayerListIterator cur = hwc.begin(id);
974                const HWComposer::LayerListIterator end = hwc.end(id);
975                for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
976                    /*
977                     * update the per-frame h/w composer data for each layer
978                     * and build the transparent region of the FB
979                     */
980                    const sp<Layer>& layer(currentLayers[i]);
981                    layer->setPerFrameData(hw, *cur);
982                }
983            }
984        }
985
986        status_t err = hwc.prepare();
987        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
988    }
989}
990
991void SurfaceFlinger::doComposition() {
992    ATRACE_CALL();
993    const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
994    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
995        const sp<DisplayDevice>& hw(mDisplays[dpy]);
996        if (hw->canDraw()) {
997            // transform the dirty region into this screen's coordinate space
998            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
999
1000            // repaint the framebuffer (if needed)
1001            doDisplayComposition(hw, dirtyRegion);
1002
1003            hw->dirtyRegion.clear();
1004            hw->flip(hw->swapRegion);
1005            hw->swapRegion.clear();
1006        }
1007        // inform the h/w that we're done compositing
1008        hw->compositionComplete();
1009    }
1010    postFramebuffer();
1011}
1012
1013void SurfaceFlinger::postFramebuffer()
1014{
1015    ATRACE_CALL();
1016
1017    const nsecs_t now = systemTime();
1018    mDebugInSwapBuffers = now;
1019
1020    HWComposer& hwc(getHwComposer());
1021    if (hwc.initCheck() == NO_ERROR) {
1022        if (!hwc.supportsFramebufferTarget()) {
1023            // EGL spec says:
1024            //   "surface must be bound to the calling thread's current context,
1025            //    for the current rendering API."
1026            DisplayDevice::makeCurrent(mEGLDisplay,
1027                    getDefaultDisplayDevice(), mEGLContext);
1028        }
1029        hwc.commit();
1030    }
1031
1032    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1033        sp<const DisplayDevice> hw(mDisplays[dpy]);
1034        const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1035        hw->onSwapBuffersCompleted(hwc);
1036        const size_t count = currentLayers.size();
1037        int32_t id = hw->getHwcDisplayId();
1038        if (id >=0 && hwc.initCheck() == NO_ERROR) {
1039            HWComposer::LayerListIterator cur = hwc.begin(id);
1040            const HWComposer::LayerListIterator end = hwc.end(id);
1041            for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1042                currentLayers[i]->onLayerDisplayed(hw, &*cur);
1043            }
1044        } else {
1045            for (size_t i = 0; i < count; i++) {
1046                currentLayers[i]->onLayerDisplayed(hw, NULL);
1047            }
1048        }
1049    }
1050
1051    mLastSwapBufferTime = systemTime() - now;
1052    mDebugInSwapBuffers = 0;
1053}
1054
1055void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1056{
1057    ATRACE_CALL();
1058
1059    // here we keep a copy of the drawing state (that is the state that's
1060    // going to be overwritten by handleTransactionLocked()) outside of
1061    // mStateLock so that the side-effects of the State assignment
1062    // don't happen with mStateLock held (which can cause deadlocks).
1063    State drawingState(mDrawingState);
1064
1065    Mutex::Autolock _l(mStateLock);
1066    const nsecs_t now = systemTime();
1067    mDebugInTransaction = now;
1068
1069    // Here we're guaranteed that some transaction flags are set
1070    // so we can call handleTransactionLocked() unconditionally.
1071    // We call getTransactionFlags(), which will also clear the flags,
1072    // with mStateLock held to guarantee that mCurrentState won't change
1073    // until the transaction is committed.
1074
1075    transactionFlags = getTransactionFlags(eTransactionMask);
1076    handleTransactionLocked(transactionFlags);
1077
1078    mLastTransactionTime = systemTime() - now;
1079    mDebugInTransaction = 0;
1080    invalidateHwcGeometry();
1081    // here the transaction has been committed
1082}
1083
1084void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1085{
1086    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1087    const size_t count = currentLayers.size();
1088
1089    /*
1090     * Traversal of the children
1091     * (perform the transaction for each of them if needed)
1092     */
1093
1094    if (transactionFlags & eTraversalNeeded) {
1095        for (size_t i=0 ; i<count ; i++) {
1096            const sp<Layer>& layer(currentLayers[i]);
1097            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1098            if (!trFlags) continue;
1099
1100            const uint32_t flags = layer->doTransaction(0);
1101            if (flags & Layer::eVisibleRegion)
1102                mVisibleRegionsDirty = true;
1103        }
1104    }
1105
1106    /*
1107     * Perform display own transactions if needed
1108     */
1109
1110    if (transactionFlags & eDisplayTransactionNeeded) {
1111        // here we take advantage of Vector's copy-on-write semantics to
1112        // improve performance by skipping the transaction entirely when
1113        // know that the lists are identical
1114        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1115        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1116        if (!curr.isIdenticalTo(draw)) {
1117            mVisibleRegionsDirty = true;
1118            const size_t cc = curr.size();
1119                  size_t dc = draw.size();
1120
1121            // find the displays that were removed
1122            // (ie: in drawing state but not in current state)
1123            // also handle displays that changed
1124            // (ie: displays that are in both lists)
1125            for (size_t i=0 ; i<dc ; i++) {
1126                const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1127                if (j < 0) {
1128                    // in drawing state but not in current state
1129                    if (!draw[i].isMainDisplay()) {
1130                        // Call makeCurrent() on the primary display so we can
1131                        // be sure that nothing associated with this display
1132                        // is current.
1133                        const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1134                        DisplayDevice::makeCurrent(mEGLDisplay, defaultDisplay, mEGLContext);
1135                        sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1136                        if (hw != NULL)
1137                            hw->disconnect(getHwComposer());
1138                        if (draw[i].type < DisplayDevice::NUM_DISPLAY_TYPES)
1139                            mEventThread->onHotplugReceived(draw[i].type, false);
1140                        mDisplays.removeItem(draw.keyAt(i));
1141                    } else {
1142                        ALOGW("trying to remove the main display");
1143                    }
1144                } else {
1145                    // this display is in both lists. see if something changed.
1146                    const DisplayDeviceState& state(curr[j]);
1147                    const wp<IBinder>& display(curr.keyAt(j));
1148                    if (state.surface->asBinder() != draw[i].surface->asBinder()) {
1149                        // changing the surface is like destroying and
1150                        // recreating the DisplayDevice, so we just remove it
1151                        // from the drawing state, so that it get re-added
1152                        // below.
1153                        sp<DisplayDevice> hw(getDisplayDevice(display));
1154                        if (hw != NULL)
1155                            hw->disconnect(getHwComposer());
1156                        mDisplays.removeItem(display);
1157                        mDrawingState.displays.removeItemsAt(i);
1158                        dc--; i--;
1159                        // at this point we must loop to the next item
1160                        continue;
1161                    }
1162
1163                    const sp<DisplayDevice> disp(getDisplayDevice(display));
1164                    if (disp != NULL) {
1165                        if (state.layerStack != draw[i].layerStack) {
1166                            disp->setLayerStack(state.layerStack);
1167                        }
1168                        if ((state.orientation != draw[i].orientation)
1169                                || (state.viewport != draw[i].viewport)
1170                                || (state.frame != draw[i].frame))
1171                        {
1172                            disp->setProjection(state.orientation,
1173                                    state.viewport, state.frame);
1174                        }
1175                    }
1176                }
1177            }
1178
1179            // find displays that were added
1180            // (ie: in current state but not in drawing state)
1181            for (size_t i=0 ; i<cc ; i++) {
1182                if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1183                    const DisplayDeviceState& state(curr[i]);
1184
1185                    sp<DisplaySurface> dispSurface;
1186                    int32_t hwcDisplayId = -1;
1187                    if (state.isVirtualDisplay()) {
1188                        // Virtual displays without a surface are dormant:
1189                        // they have external state (layer stack, projection,
1190                        // etc.) but no internal state (i.e. a DisplayDevice).
1191                        if (state.surface != NULL) {
1192                            hwcDisplayId = allocateHwcDisplayId(state.type);
1193                            dispSurface = new VirtualDisplaySurface(
1194                                    *mHwc, hwcDisplayId, state.surface,
1195                                    state.displayName);
1196                        }
1197                    } else {
1198                        ALOGE_IF(state.surface!=NULL,
1199                                "adding a supported display, but rendering "
1200                                "surface is provided (%p), ignoring it",
1201                                state.surface.get());
1202                        hwcDisplayId = allocateHwcDisplayId(state.type);
1203                        // for supported (by hwc) displays we provide our
1204                        // own rendering surface
1205                        dispSurface = new FramebufferSurface(*mHwc, state.type);
1206                    }
1207
1208                    const wp<IBinder>& display(curr.keyAt(i));
1209                    if (dispSurface != NULL) {
1210                        sp<DisplayDevice> hw = new DisplayDevice(this,
1211                                state.type, hwcDisplayId, state.isSecure,
1212                                display, dispSurface, mEGLConfig);
1213                        hw->setLayerStack(state.layerStack);
1214                        hw->setProjection(state.orientation,
1215                                state.viewport, state.frame);
1216                        hw->setDisplayName(state.displayName);
1217                        mDisplays.add(display, hw);
1218                        if (state.isVirtualDisplay()) {
1219                            if (hwcDisplayId >= 0) {
1220                                mHwc->setVirtualDisplayProperties(hwcDisplayId,
1221                                        hw->getWidth(), hw->getHeight(),
1222                                        hw->getFormat());
1223                            }
1224                        } else {
1225                            mEventThread->onHotplugReceived(state.type, true);
1226                        }
1227                    }
1228                }
1229            }
1230        }
1231    }
1232
1233    if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1234        // The transform hint might have changed for some layers
1235        // (either because a display has changed, or because a layer
1236        // as changed).
1237        //
1238        // Walk through all the layers in currentLayers,
1239        // and update their transform hint.
1240        //
1241        // If a layer is visible only on a single display, then that
1242        // display is used to calculate the hint, otherwise we use the
1243        // default display.
1244        //
1245        // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1246        // the hint is set before we acquire a buffer from the surface texture.
1247        //
1248        // NOTE: layer transactions have taken place already, so we use their
1249        // drawing state. However, SurfaceFlinger's own transaction has not
1250        // happened yet, so we must use the current state layer list
1251        // (soon to become the drawing state list).
1252        //
1253        sp<const DisplayDevice> disp;
1254        uint32_t currentlayerStack = 0;
1255        for (size_t i=0; i<count; i++) {
1256            // NOTE: we rely on the fact that layers are sorted by
1257            // layerStack first (so we don't have to traverse the list
1258            // of displays for every layer).
1259            const sp<Layer>& layer(currentLayers[i]);
1260            uint32_t layerStack = layer->drawingState().layerStack;
1261            if (i==0 || currentlayerStack != layerStack) {
1262                currentlayerStack = layerStack;
1263                // figure out if this layerstack is mirrored
1264                // (more than one display) if so, pick the default display,
1265                // if not, pick the only display it's on.
1266                disp.clear();
1267                for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1268                    sp<const DisplayDevice> hw(mDisplays[dpy]);
1269                    if (hw->getLayerStack() == currentlayerStack) {
1270                        if (disp == NULL) {
1271                            disp = hw;
1272                        } else {
1273                            disp = NULL;
1274                            break;
1275                        }
1276                    }
1277                }
1278            }
1279            if (disp == NULL) {
1280                // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1281                // redraw after transform hint changes. See bug 8508397.
1282
1283                // could be null when this layer is using a layerStack
1284                // that is not visible on any display. Also can occur at
1285                // screen off/on times.
1286                disp = getDefaultDisplayDevice();
1287            }
1288            layer->updateTransformHint(disp);
1289        }
1290    }
1291
1292
1293    /*
1294     * Perform our own transaction if needed
1295     */
1296
1297    const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
1298    if (currentLayers.size() > previousLayers.size()) {
1299        // layers have been added
1300        mVisibleRegionsDirty = true;
1301    }
1302
1303    // some layers might have been removed, so
1304    // we need to update the regions they're exposing.
1305    if (mLayersRemoved) {
1306        mLayersRemoved = false;
1307        mVisibleRegionsDirty = true;
1308        const size_t count = previousLayers.size();
1309        for (size_t i=0 ; i<count ; i++) {
1310            const sp<Layer>& layer(previousLayers[i]);
1311            if (currentLayers.indexOf(layer) < 0) {
1312                // this layer is not visible anymore
1313                // TODO: we could traverse the tree from front to back and
1314                //       compute the actual visible region
1315                // TODO: we could cache the transformed region
1316                const Layer::State& s(layer->drawingState());
1317                Region visibleReg = s.transform.transform(
1318                        Region(Rect(s.active.w, s.active.h)));
1319                invalidateLayerStack(s.layerStack, visibleReg);
1320            }
1321        }
1322    }
1323
1324    commitTransaction();
1325}
1326
1327void SurfaceFlinger::commitTransaction()
1328{
1329    if (!mLayersPendingRemoval.isEmpty()) {
1330        // Notify removed layers now that they can't be drawn from
1331        for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1332            mLayersPendingRemoval[i]->onRemoved();
1333        }
1334        mLayersPendingRemoval.clear();
1335    }
1336
1337    // If this transaction is part of a window animation then the next frame
1338    // we composite should be considered an animation as well.
1339    mAnimCompositionPending = mAnimTransactionPending;
1340
1341    mDrawingState = mCurrentState;
1342    mTransactionPending = false;
1343    mAnimTransactionPending = false;
1344    mTransactionCV.broadcast();
1345}
1346
1347void SurfaceFlinger::computeVisibleRegions(
1348        const LayerVector& currentLayers, uint32_t layerStack,
1349        Region& outDirtyRegion, Region& outOpaqueRegion)
1350{
1351    ATRACE_CALL();
1352
1353    Region aboveOpaqueLayers;
1354    Region aboveCoveredLayers;
1355    Region dirty;
1356
1357    outDirtyRegion.clear();
1358
1359    size_t i = currentLayers.size();
1360    while (i--) {
1361        const sp<Layer>& layer = currentLayers[i];
1362
1363        // start with the whole surface at its current location
1364        const Layer::State& s(layer->drawingState());
1365
1366        // only consider the layers on the given layer stack
1367        if (s.layerStack != layerStack)
1368            continue;
1369
1370        /*
1371         * opaqueRegion: area of a surface that is fully opaque.
1372         */
1373        Region opaqueRegion;
1374
1375        /*
1376         * visibleRegion: area of a surface that is visible on screen
1377         * and not fully transparent. This is essentially the layer's
1378         * footprint minus the opaque regions above it.
1379         * Areas covered by a translucent surface are considered visible.
1380         */
1381        Region visibleRegion;
1382
1383        /*
1384         * coveredRegion: area of a surface that is covered by all
1385         * visible regions above it (which includes the translucent areas).
1386         */
1387        Region coveredRegion;
1388
1389        /*
1390         * transparentRegion: area of a surface that is hinted to be completely
1391         * transparent. This is only used to tell when the layer has no visible
1392         * non-transparent regions and can be removed from the layer list. It
1393         * does not affect the visibleRegion of this layer or any layers
1394         * beneath it. The hint may not be correct if apps don't respect the
1395         * SurfaceView restrictions (which, sadly, some don't).
1396         */
1397        Region transparentRegion;
1398
1399
1400        // handle hidden surfaces by setting the visible region to empty
1401        if (CC_LIKELY(layer->isVisible())) {
1402            const bool translucent = !layer->isOpaque();
1403            Rect bounds(s.transform.transform(layer->computeBounds()));
1404            visibleRegion.set(bounds);
1405            if (!visibleRegion.isEmpty()) {
1406                // Remove the transparent area from the visible region
1407                if (translucent) {
1408                    const Transform tr(s.transform);
1409                    if (tr.transformed()) {
1410                        if (tr.preserveRects()) {
1411                            // transform the transparent region
1412                            transparentRegion = tr.transform(s.activeTransparentRegion);
1413                        } else {
1414                            // transformation too complex, can't do the
1415                            // transparent region optimization.
1416                            transparentRegion.clear();
1417                        }
1418                    } else {
1419                        transparentRegion = s.activeTransparentRegion;
1420                    }
1421                }
1422
1423                // compute the opaque region
1424                const int32_t layerOrientation = s.transform.getOrientation();
1425                if (s.alpha==255 && !translucent &&
1426                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
1427                    // the opaque region is the layer's footprint
1428                    opaqueRegion = visibleRegion;
1429                }
1430            }
1431        }
1432
1433        // Clip the covered region to the visible region
1434        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1435
1436        // Update aboveCoveredLayers for next (lower) layer
1437        aboveCoveredLayers.orSelf(visibleRegion);
1438
1439        // subtract the opaque region covered by the layers above us
1440        visibleRegion.subtractSelf(aboveOpaqueLayers);
1441
1442        // compute this layer's dirty region
1443        if (layer->contentDirty) {
1444            // we need to invalidate the whole region
1445            dirty = visibleRegion;
1446            // as well, as the old visible region
1447            dirty.orSelf(layer->visibleRegion);
1448            layer->contentDirty = false;
1449        } else {
1450            /* compute the exposed region:
1451             *   the exposed region consists of two components:
1452             *   1) what's VISIBLE now and was COVERED before
1453             *   2) what's EXPOSED now less what was EXPOSED before
1454             *
1455             * note that (1) is conservative, we start with the whole
1456             * visible region but only keep what used to be covered by
1457             * something -- which mean it may have been exposed.
1458             *
1459             * (2) handles areas that were not covered by anything but got
1460             * exposed because of a resize.
1461             */
1462            const Region newExposed = visibleRegion - coveredRegion;
1463            const Region oldVisibleRegion = layer->visibleRegion;
1464            const Region oldCoveredRegion = layer->coveredRegion;
1465            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1466            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1467        }
1468        dirty.subtractSelf(aboveOpaqueLayers);
1469
1470        // accumulate to the screen dirty region
1471        outDirtyRegion.orSelf(dirty);
1472
1473        // Update aboveOpaqueLayers for next (lower) layer
1474        aboveOpaqueLayers.orSelf(opaqueRegion);
1475
1476        // Store the visible region in screen space
1477        layer->setVisibleRegion(visibleRegion);
1478        layer->setCoveredRegion(coveredRegion);
1479        layer->setVisibleNonTransparentRegion(
1480                visibleRegion.subtract(transparentRegion));
1481    }
1482
1483    outOpaqueRegion = aboveOpaqueLayers;
1484}
1485
1486void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1487        const Region& dirty) {
1488    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1489        const sp<DisplayDevice>& hw(mDisplays[dpy]);
1490        if (hw->getLayerStack() == layerStack) {
1491            hw->dirtyRegion.orSelf(dirty);
1492        }
1493    }
1494}
1495
1496void SurfaceFlinger::handlePageFlip()
1497{
1498    Region dirtyRegion;
1499
1500    bool visibleRegions = false;
1501    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
1502    const size_t count = currentLayers.size();
1503    for (size_t i=0 ; i<count ; i++) {
1504        const sp<Layer>& layer(currentLayers[i]);
1505        const Region dirty(layer->latchBuffer(visibleRegions));
1506        const Layer::State& s(layer->drawingState());
1507        invalidateLayerStack(s.layerStack, dirty);
1508    }
1509
1510    mVisibleRegionsDirty |= visibleRegions;
1511}
1512
1513void SurfaceFlinger::invalidateHwcGeometry()
1514{
1515    mHwWorkListDirty = true;
1516}
1517
1518
1519void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1520        const Region& inDirtyRegion)
1521{
1522    Region dirtyRegion(inDirtyRegion);
1523
1524    // compute the invalid region
1525    hw->swapRegion.orSelf(dirtyRegion);
1526
1527    uint32_t flags = hw->getFlags();
1528    if (flags & DisplayDevice::SWAP_RECTANGLE) {
1529        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1530        // takes a rectangle, we must make sure to update that whole
1531        // rectangle in that case
1532        dirtyRegion.set(hw->swapRegion.bounds());
1533    } else {
1534        if (flags & DisplayDevice::PARTIAL_UPDATES) {
1535            // We need to redraw the rectangle that will be updated
1536            // (pushed to the framebuffer).
1537            // This is needed because PARTIAL_UPDATES only takes one
1538            // rectangle instead of a region (see DisplayDevice::flip())
1539            dirtyRegion.set(hw->swapRegion.bounds());
1540        } else {
1541            // we need to redraw everything (the whole screen)
1542            dirtyRegion.set(hw->bounds());
1543            hw->swapRegion = dirtyRegion;
1544        }
1545    }
1546
1547    doComposeSurfaces(hw, dirtyRegion);
1548
1549    // update the swap region and clear the dirty region
1550    hw->swapRegion.orSelf(dirtyRegion);
1551
1552    // swap buffers (presentation)
1553    hw->swapBuffers(getHwComposer());
1554}
1555
1556void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1557{
1558    const int32_t id = hw->getHwcDisplayId();
1559    HWComposer& hwc(getHwComposer());
1560    HWComposer::LayerListIterator cur = hwc.begin(id);
1561    const HWComposer::LayerListIterator end = hwc.end(id);
1562
1563    const bool hasGlesComposition = hwc.hasGlesComposition(id) || (cur==end);
1564    if (hasGlesComposition) {
1565        if (!DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext)) {
1566            ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1567                  hw->getDisplayName().string());
1568            return;
1569        }
1570
1571        // set the frame buffer
1572        glMatrixMode(GL_MODELVIEW);
1573        glLoadIdentity();
1574
1575        // Never touch the framebuffer if we don't have any framebuffer layers
1576        const bool hasHwcComposition = hwc.hasHwcComposition(id);
1577        if (hasHwcComposition) {
1578            // when using overlays, we assume a fully transparent framebuffer
1579            // NOTE: we could reduce how much we need to clear, for instance
1580            // remove where there are opaque FB layers. however, on some
1581            // GPUs doing a "clean slate" glClear might be more efficient.
1582            // We'll revisit later if needed.
1583            glClearColor(0, 0, 0, 0);
1584            glClear(GL_COLOR_BUFFER_BIT);
1585        } else {
1586            // we start with the whole screen area
1587            const Region bounds(hw->getBounds());
1588
1589            // we remove the scissor part
1590            // we're left with the letterbox region
1591            // (common case is that letterbox ends-up being empty)
1592            const Region letterbox(bounds.subtract(hw->getScissor()));
1593
1594            // compute the area to clear
1595            Region region(hw->undefinedRegion.merge(letterbox));
1596
1597            // but limit it to the dirty region
1598            region.andSelf(dirty);
1599
1600            // screen is already cleared here
1601            if (!region.isEmpty()) {
1602                // can happen with SurfaceView
1603                drawWormhole(hw, region);
1604            }
1605        }
1606
1607        if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1608            // just to be on the safe side, we don't set the
1609            // scissor on the main display. It should never be needed
1610            // anyways (though in theory it could since the API allows it).
1611            const Rect& bounds(hw->getBounds());
1612            const Rect& scissor(hw->getScissor());
1613            if (scissor != bounds) {
1614                // scissor doesn't match the screen's dimensions, so we
1615                // need to clear everything outside of it and enable
1616                // the GL scissor so we don't draw anything where we shouldn't
1617                const GLint height = hw->getHeight();
1618                glScissor(scissor.left, height - scissor.bottom,
1619                        scissor.getWidth(), scissor.getHeight());
1620                // enable scissor for this frame
1621                glEnable(GL_SCISSOR_TEST);
1622            }
1623        }
1624    }
1625
1626    /*
1627     * and then, render the layers targeted at the framebuffer
1628     */
1629
1630    const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
1631    const size_t count = layers.size();
1632    const Transform& tr = hw->getTransform();
1633    if (cur != end) {
1634        // we're using h/w composer
1635        for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1636            const sp<Layer>& layer(layers[i]);
1637            const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1638            if (!clip.isEmpty()) {
1639                switch (cur->getCompositionType()) {
1640                    case HWC_OVERLAY: {
1641                        if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1642                                && i
1643                                && layer->isOpaque()
1644                                && hasGlesComposition) {
1645                            // never clear the very first layer since we're
1646                            // guaranteed the FB is already cleared
1647                            layer->clearWithOpenGL(hw, clip);
1648                        }
1649                        break;
1650                    }
1651                    case HWC_FRAMEBUFFER: {
1652                        layer->draw(hw, clip);
1653                        break;
1654                    }
1655                    case HWC_FRAMEBUFFER_TARGET: {
1656                        // this should not happen as the iterator shouldn't
1657                        // let us get there.
1658                        ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%d)", i);
1659                        break;
1660                    }
1661                }
1662            }
1663            layer->setAcquireFence(hw, *cur);
1664        }
1665    } else {
1666        // we're not using h/w composer
1667        for (size_t i=0 ; i<count ; ++i) {
1668            const sp<Layer>& layer(layers[i]);
1669            const Region clip(dirty.intersect(
1670                    tr.transform(layer->visibleRegion)));
1671            if (!clip.isEmpty()) {
1672                layer->draw(hw, clip);
1673            }
1674        }
1675    }
1676
1677    // disable scissor at the end of the frame
1678    glDisable(GL_SCISSOR_TEST);
1679}
1680
1681void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw,
1682        const Region& region) const
1683{
1684    glDisable(GL_TEXTURE_EXTERNAL_OES);
1685    glDisable(GL_TEXTURE_2D);
1686    glDisable(GL_BLEND);
1687    glColor4f(0,0,0,0);
1688
1689    const int32_t height = hw->getHeight();
1690    Region::const_iterator it = region.begin();
1691    Region::const_iterator const end = region.end();
1692    while (it != end) {
1693        const Rect& r = *it++;
1694        GLfloat vertices[][2] = {
1695                { (GLfloat) r.left,  (GLfloat) (height - r.top) },
1696                { (GLfloat) r.left,  (GLfloat) (height - r.bottom) },
1697                { (GLfloat) r.right, (GLfloat) (height - r.bottom) },
1698                { (GLfloat) r.right, (GLfloat) (height - r.top) }
1699        };
1700        glVertexPointer(2, GL_FLOAT, 0, vertices);
1701        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1702    }
1703}
1704
1705void SurfaceFlinger::addClientLayer(const sp<Client>& client,
1706        const sp<IBinder>& handle,
1707        const sp<IGraphicBufferProducer>& gbc,
1708        const sp<Layer>& lbc)
1709{
1710    // attach this layer to the client
1711    client->attachLayer(handle, lbc);
1712
1713    // add this layer to the current state list
1714    Mutex::Autolock _l(mStateLock);
1715    mCurrentState.layersSortedByZ.add(lbc);
1716    mGraphicBufferProducerList.add(gbc->asBinder());
1717}
1718
1719status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer)
1720{
1721    Mutex::Autolock _l(mStateLock);
1722    ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
1723    if (index >= 0) {
1724        mLayersPendingRemoval.push(layer);
1725        mLayersRemoved = true;
1726        setTransactionFlags(eTransactionNeeded);
1727        return NO_ERROR;
1728    }
1729    return status_t(index);
1730}
1731
1732uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
1733{
1734    return android_atomic_release_load(&mTransactionFlags);
1735}
1736
1737uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1738{
1739    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1740}
1741
1742uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1743{
1744    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1745    if ((old & flags)==0) { // wake the server up
1746        signalTransaction();
1747    }
1748    return old;
1749}
1750
1751void SurfaceFlinger::setTransactionState(
1752        const Vector<ComposerState>& state,
1753        const Vector<DisplayState>& displays,
1754        uint32_t flags)
1755{
1756    ATRACE_CALL();
1757    Mutex::Autolock _l(mStateLock);
1758    uint32_t transactionFlags = 0;
1759
1760    if (flags & eAnimation) {
1761        // For window updates that are part of an animation we must wait for
1762        // previous animation "frames" to be handled.
1763        while (mAnimTransactionPending) {
1764            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1765            if (CC_UNLIKELY(err != NO_ERROR)) {
1766                // just in case something goes wrong in SF, return to the
1767                // caller after a few seconds.
1768                ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
1769                        "waiting for previous animation frame");
1770                mAnimTransactionPending = false;
1771                break;
1772            }
1773        }
1774    }
1775
1776    size_t count = displays.size();
1777    for (size_t i=0 ; i<count ; i++) {
1778        const DisplayState& s(displays[i]);
1779        transactionFlags |= setDisplayStateLocked(s);
1780    }
1781
1782    count = state.size();
1783    for (size_t i=0 ; i<count ; i++) {
1784        const ComposerState& s(state[i]);
1785        // Here we need to check that the interface we're given is indeed
1786        // one of our own. A malicious client could give us a NULL
1787        // IInterface, or one of its own or even one of our own but a
1788        // different type. All these situations would cause us to crash.
1789        //
1790        // NOTE: it would be better to use RTTI as we could directly check
1791        // that we have a Client*. however, RTTI is disabled in Android.
1792        if (s.client != NULL) {
1793            sp<IBinder> binder = s.client->asBinder();
1794            if (binder != NULL) {
1795                String16 desc(binder->getInterfaceDescriptor());
1796                if (desc == ISurfaceComposerClient::descriptor) {
1797                    sp<Client> client( static_cast<Client *>(s.client.get()) );
1798                    transactionFlags |= setClientStateLocked(client, s.state);
1799                }
1800            }
1801        }
1802    }
1803
1804    if (transactionFlags) {
1805        // this triggers the transaction
1806        setTransactionFlags(transactionFlags);
1807
1808        // if this is a synchronous transaction, wait for it to take effect
1809        // before returning.
1810        if (flags & eSynchronous) {
1811            mTransactionPending = true;
1812        }
1813        if (flags & eAnimation) {
1814            mAnimTransactionPending = true;
1815        }
1816        while (mTransactionPending) {
1817            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1818            if (CC_UNLIKELY(err != NO_ERROR)) {
1819                // just in case something goes wrong in SF, return to the
1820                // called after a few seconds.
1821                ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
1822                mTransactionPending = false;
1823                break;
1824            }
1825        }
1826    }
1827}
1828
1829uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1830{
1831    ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
1832    if (dpyIdx < 0)
1833        return 0;
1834
1835    uint32_t flags = 0;
1836    DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
1837    if (disp.isValid()) {
1838        const uint32_t what = s.what;
1839        if (what & DisplayState::eSurfaceChanged) {
1840            if (disp.surface->asBinder() != s.surface->asBinder()) {
1841                disp.surface = s.surface;
1842                flags |= eDisplayTransactionNeeded;
1843            }
1844        }
1845        if (what & DisplayState::eLayerStackChanged) {
1846            if (disp.layerStack != s.layerStack) {
1847                disp.layerStack = s.layerStack;
1848                flags |= eDisplayTransactionNeeded;
1849            }
1850        }
1851        if (what & DisplayState::eDisplayProjectionChanged) {
1852            if (disp.orientation != s.orientation) {
1853                disp.orientation = s.orientation;
1854                flags |= eDisplayTransactionNeeded;
1855            }
1856            if (disp.frame != s.frame) {
1857                disp.frame = s.frame;
1858                flags |= eDisplayTransactionNeeded;
1859            }
1860            if (disp.viewport != s.viewport) {
1861                disp.viewport = s.viewport;
1862                flags |= eDisplayTransactionNeeded;
1863            }
1864        }
1865    }
1866    return flags;
1867}
1868
1869uint32_t SurfaceFlinger::setClientStateLocked(
1870        const sp<Client>& client,
1871        const layer_state_t& s)
1872{
1873    uint32_t flags = 0;
1874    sp<Layer> layer(client->getLayerUser(s.surface));
1875    if (layer != 0) {
1876        const uint32_t what = s.what;
1877        if (what & layer_state_t::ePositionChanged) {
1878            if (layer->setPosition(s.x, s.y))
1879                flags |= eTraversalNeeded;
1880        }
1881        if (what & layer_state_t::eLayerChanged) {
1882            // NOTE: index needs to be calculated before we update the state
1883            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1884            if (layer->setLayer(s.z)) {
1885                mCurrentState.layersSortedByZ.removeAt(idx);
1886                mCurrentState.layersSortedByZ.add(layer);
1887                // we need traversal (state changed)
1888                // AND transaction (list changed)
1889                flags |= eTransactionNeeded|eTraversalNeeded;
1890            }
1891        }
1892        if (what & layer_state_t::eSizeChanged) {
1893            if (layer->setSize(s.w, s.h)) {
1894                flags |= eTraversalNeeded;
1895            }
1896        }
1897        if (what & layer_state_t::eAlphaChanged) {
1898            if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1899                flags |= eTraversalNeeded;
1900        }
1901        if (what & layer_state_t::eMatrixChanged) {
1902            if (layer->setMatrix(s.matrix))
1903                flags |= eTraversalNeeded;
1904        }
1905        if (what & layer_state_t::eTransparentRegionChanged) {
1906            if (layer->setTransparentRegionHint(s.transparentRegion))
1907                flags |= eTraversalNeeded;
1908        }
1909        if (what & layer_state_t::eVisibilityChanged) {
1910            if (layer->setFlags(s.flags, s.mask))
1911                flags |= eTraversalNeeded;
1912        }
1913        if (what & layer_state_t::eCropChanged) {
1914            if (layer->setCrop(s.crop))
1915                flags |= eTraversalNeeded;
1916        }
1917        if (what & layer_state_t::eLayerStackChanged) {
1918            // NOTE: index needs to be calculated before we update the state
1919            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1920            if (layer->setLayerStack(s.layerStack)) {
1921                mCurrentState.layersSortedByZ.removeAt(idx);
1922                mCurrentState.layersSortedByZ.add(layer);
1923                // we need traversal (state changed)
1924                // AND transaction (list changed)
1925                flags |= eTransactionNeeded|eTraversalNeeded;
1926            }
1927        }
1928    }
1929    return flags;
1930}
1931
1932status_t SurfaceFlinger::createLayer(
1933        const String8& name,
1934        const sp<Client>& client,
1935        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
1936        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
1937{
1938    //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
1939    if (int32_t(w|h) < 0) {
1940        ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
1941                int(w), int(h));
1942        return BAD_VALUE;
1943    }
1944
1945    status_t result = NO_ERROR;
1946
1947    sp<Layer> layer;
1948
1949    switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
1950        case ISurfaceComposerClient::eFXSurfaceNormal:
1951            result = createNormalLayer(client,
1952                    name, w, h, flags, format,
1953                    handle, gbp, &layer);
1954            break;
1955        case ISurfaceComposerClient::eFXSurfaceDim:
1956            result = createDimLayer(client,
1957                    name, w, h, flags,
1958                    handle, gbp, &layer);
1959            break;
1960        default:
1961            result = BAD_VALUE;
1962            break;
1963    }
1964
1965    if (result == NO_ERROR) {
1966        addClientLayer(client, *handle, *gbp, layer);
1967        setTransactionFlags(eTransactionNeeded);
1968    }
1969    return result;
1970}
1971
1972status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
1973        const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
1974        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
1975{
1976    // initialize the surfaces
1977    switch (format) {
1978    case PIXEL_FORMAT_TRANSPARENT:
1979    case PIXEL_FORMAT_TRANSLUCENT:
1980        format = PIXEL_FORMAT_RGBA_8888;
1981        break;
1982    case PIXEL_FORMAT_OPAQUE:
1983#ifdef NO_RGBX_8888
1984        format = PIXEL_FORMAT_RGB_565;
1985#else
1986        format = PIXEL_FORMAT_RGBX_8888;
1987#endif
1988        break;
1989    }
1990
1991#ifdef NO_RGBX_8888
1992    if (format == PIXEL_FORMAT_RGBX_8888)
1993        format = PIXEL_FORMAT_RGBA_8888;
1994#endif
1995
1996    *outLayer = new Layer(this, client, name, w, h, flags);
1997    status_t err = (*outLayer)->setBuffers(w, h, format, flags);
1998    if (err == NO_ERROR) {
1999        *handle = (*outLayer)->getHandle();
2000        *gbp = (*outLayer)->getBufferQueue();
2001    }
2002
2003    ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2004    return err;
2005}
2006
2007status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2008        const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2009        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2010{
2011    *outLayer = new LayerDim(this, client, name, w, h, flags);
2012    *handle = (*outLayer)->getHandle();
2013    *gbp = (*outLayer)->getBufferQueue();
2014    return NO_ERROR;
2015}
2016
2017status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2018{
2019    // called by the window manager when it wants to remove a Layer
2020    status_t err = NO_ERROR;
2021    sp<Layer> l(client->getLayerUser(handle));
2022    if (l != NULL) {
2023        err = removeLayer(l);
2024        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2025                "error removing layer=%p (%s)", l.get(), strerror(-err));
2026    }
2027    return err;
2028}
2029
2030status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2031{
2032    // called by ~LayerCleaner() when all references to the IBinder (handle)
2033    // are gone
2034    status_t err = NO_ERROR;
2035    sp<Layer> l(layer.promote());
2036    if (l != NULL) {
2037        err = removeLayer(l);
2038        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2039                "error removing layer=%p (%s)", l.get(), strerror(-err));
2040    }
2041    return err;
2042}
2043
2044// ---------------------------------------------------------------------------
2045
2046void SurfaceFlinger::onInitializeDisplays() {
2047    // reset screen orientation and use primary layer stack
2048    Vector<ComposerState> state;
2049    Vector<DisplayState> displays;
2050    DisplayState d;
2051    d.what = DisplayState::eDisplayProjectionChanged |
2052             DisplayState::eLayerStackChanged;
2053    d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2054    d.layerStack = 0;
2055    d.orientation = DisplayState::eOrientationDefault;
2056    d.frame.makeInvalid();
2057    d.viewport.makeInvalid();
2058    displays.add(d);
2059    setTransactionState(state, displays, 0);
2060    onScreenAcquired(getDefaultDisplayDevice());
2061}
2062
2063void SurfaceFlinger::initializeDisplays() {
2064    class MessageScreenInitialized : public MessageBase {
2065        SurfaceFlinger* flinger;
2066    public:
2067        MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2068        virtual bool handler() {
2069            flinger->onInitializeDisplays();
2070            return true;
2071        }
2072    };
2073    sp<MessageBase> msg = new MessageScreenInitialized(this);
2074    postMessageAsync(msg);  // we may be called from main thread, use async message
2075}
2076
2077
2078void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) {
2079    ALOGD("Screen acquired, type=%d flinger=%p", hw->getDisplayType(), this);
2080    if (hw->isScreenAcquired()) {
2081        // this is expected, e.g. when power manager wakes up during boot
2082        ALOGD(" screen was previously acquired");
2083        return;
2084    }
2085
2086    hw->acquireScreen();
2087    int32_t type = hw->getDisplayType();
2088    if (type < DisplayDevice::NUM_DISPLAY_TYPES) {
2089        // built-in display, tell the HWC
2090        getHwComposer().acquire(type);
2091
2092        if (type == DisplayDevice::DISPLAY_PRIMARY) {
2093            // FIXME: eventthread only knows about the main display right now
2094            mEventThread->onScreenAcquired();
2095        }
2096    }
2097    mVisibleRegionsDirty = true;
2098    repaintEverything();
2099}
2100
2101void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) {
2102    ALOGD("Screen released, type=%d flinger=%p", hw->getDisplayType(), this);
2103    if (!hw->isScreenAcquired()) {
2104        ALOGD(" screen was previously released");
2105        return;
2106    }
2107
2108    hw->releaseScreen();
2109    int32_t type = hw->getDisplayType();
2110    if (type < DisplayDevice::NUM_DISPLAY_TYPES) {
2111        if (type == DisplayDevice::DISPLAY_PRIMARY) {
2112            // FIXME: eventthread only knows about the main display right now
2113            mEventThread->onScreenReleased();
2114        }
2115
2116        // built-in display, tell the HWC
2117        getHwComposer().release(type);
2118    }
2119    mVisibleRegionsDirty = true;
2120    // from this point on, SF will stop drawing on this display
2121}
2122
2123void SurfaceFlinger::unblank(const sp<IBinder>& display) {
2124    class MessageScreenAcquired : public MessageBase {
2125        SurfaceFlinger& mFlinger;
2126        sp<IBinder> mDisplay;
2127    public:
2128        MessageScreenAcquired(SurfaceFlinger& flinger,
2129                const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2130        virtual bool handler() {
2131            const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2132            if (hw == NULL) {
2133                ALOGE("Attempt to unblank null display %p", mDisplay.get());
2134            } else if (hw->getDisplayType() >= DisplayDevice::NUM_DISPLAY_TYPES) {
2135                ALOGW("Attempt to unblank virtual display");
2136            } else {
2137                mFlinger.onScreenAcquired(hw);
2138            }
2139            return true;
2140        }
2141    };
2142    sp<MessageBase> msg = new MessageScreenAcquired(*this, display);
2143    postMessageSync(msg);
2144}
2145
2146void SurfaceFlinger::blank(const sp<IBinder>& display) {
2147    class MessageScreenReleased : public MessageBase {
2148        SurfaceFlinger& mFlinger;
2149        sp<IBinder> mDisplay;
2150    public:
2151        MessageScreenReleased(SurfaceFlinger& flinger,
2152                const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2153        virtual bool handler() {
2154            const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2155            if (hw == NULL) {
2156                ALOGE("Attempt to blank null display %p", mDisplay.get());
2157            } else if (hw->getDisplayType() >= DisplayDevice::NUM_DISPLAY_TYPES) {
2158                ALOGW("Attempt to blank virtual display");
2159            } else {
2160                mFlinger.onScreenReleased(hw);
2161            }
2162            return true;
2163        }
2164    };
2165    sp<MessageBase> msg = new MessageScreenReleased(*this, display);
2166    postMessageSync(msg);
2167}
2168
2169// ---------------------------------------------------------------------------
2170
2171status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2172{
2173    String8 result;
2174
2175    IPCThreadState* ipc = IPCThreadState::self();
2176    const int pid = ipc->getCallingPid();
2177    const int uid = ipc->getCallingUid();
2178    if ((uid != AID_SHELL) &&
2179            !PermissionCache::checkPermission(sDump, pid, uid)) {
2180        result.appendFormat("Permission Denial: "
2181                "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2182    } else {
2183        // Try to get the main lock, but don't insist if we can't
2184        // (this would indicate SF is stuck, but we want to be able to
2185        // print something in dumpsys).
2186        int retry = 3;
2187        while (mStateLock.tryLock()<0 && --retry>=0) {
2188            usleep(1000000);
2189        }
2190        const bool locked(retry >= 0);
2191        if (!locked) {
2192            result.append(
2193                    "SurfaceFlinger appears to be unresponsive, "
2194                    "dumping anyways (no locks held)\n");
2195        }
2196
2197        bool dumpAll = true;
2198        size_t index = 0;
2199        size_t numArgs = args.size();
2200        if (numArgs) {
2201            if ((index < numArgs) &&
2202                    (args[index] == String16("--list"))) {
2203                index++;
2204                listLayersLocked(args, index, result);
2205                dumpAll = false;
2206            }
2207
2208            if ((index < numArgs) &&
2209                    (args[index] == String16("--latency"))) {
2210                index++;
2211                dumpStatsLocked(args, index, result);
2212                dumpAll = false;
2213            }
2214
2215            if ((index < numArgs) &&
2216                    (args[index] == String16("--latency-clear"))) {
2217                index++;
2218                clearStatsLocked(args, index, result);
2219                dumpAll = false;
2220            }
2221        }
2222
2223        if (dumpAll) {
2224            dumpAllLocked(args, index, result);
2225        }
2226
2227        if (locked) {
2228            mStateLock.unlock();
2229        }
2230    }
2231    write(fd, result.string(), result.size());
2232    return NO_ERROR;
2233}
2234
2235void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
2236        String8& result) const
2237{
2238    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2239    const size_t count = currentLayers.size();
2240    for (size_t i=0 ; i<count ; i++) {
2241        const sp<Layer>& layer(currentLayers[i]);
2242        result.appendFormat("%s\n", layer->getName().string());
2243    }
2244}
2245
2246void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2247        String8& result) const
2248{
2249    String8 name;
2250    if (index < args.size()) {
2251        name = String8(args[index]);
2252        index++;
2253    }
2254
2255    const nsecs_t period =
2256            getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2257    result.appendFormat("%lld\n", period);
2258
2259    if (name.isEmpty()) {
2260        mAnimFrameTracker.dump(result);
2261    } else {
2262        const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2263        const size_t count = currentLayers.size();
2264        for (size_t i=0 ; i<count ; i++) {
2265            const sp<Layer>& layer(currentLayers[i]);
2266            if (name == layer->getName()) {
2267                layer->dumpStats(result);
2268            }
2269        }
2270    }
2271}
2272
2273void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2274        String8& result)
2275{
2276    String8 name;
2277    if (index < args.size()) {
2278        name = String8(args[index]);
2279        index++;
2280    }
2281
2282    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2283    const size_t count = currentLayers.size();
2284    for (size_t i=0 ; i<count ; i++) {
2285        const sp<Layer>& layer(currentLayers[i]);
2286        if (name.isEmpty() || (name == layer->getName())) {
2287            layer->clearStats();
2288        }
2289    }
2290
2291    mAnimFrameTracker.clear();
2292}
2293
2294/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2295{
2296    static const char* config =
2297            " [sf"
2298#ifdef NO_RGBX_8888
2299            " NO_RGBX_8888"
2300#endif
2301#ifdef HAS_CONTEXT_PRIORITY
2302            " HAS_CONTEXT_PRIORITY"
2303#endif
2304#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2305            " NEVER_DEFAULT_TO_ASYNC_MODE"
2306#endif
2307#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2308            " TARGET_DISABLE_TRIPLE_BUFFERING"
2309#endif
2310            "]";
2311    result.append(config);
2312}
2313
2314void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2315        String8& result) const
2316{
2317    bool colorize = false;
2318    if (index < args.size()
2319            && (args[index] == String16("--color"))) {
2320        colorize = true;
2321        index++;
2322    }
2323
2324    Colorizer colorizer(colorize);
2325
2326    // figure out if we're stuck somewhere
2327    const nsecs_t now = systemTime();
2328    const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2329    const nsecs_t inTransaction(mDebugInTransaction);
2330    nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2331    nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2332
2333    /*
2334     * Dump library configuration.
2335     */
2336
2337    colorizer.bold(result);
2338    result.append("Build configuration:");
2339    colorizer.reset(result);
2340    appendSfConfigString(result);
2341    appendUiConfigString(result);
2342    appendGuiConfigString(result);
2343    result.append("\n");
2344
2345    colorizer.bold(result);
2346    result.append("Sync configuration: ");
2347    colorizer.reset(result);
2348    result.append(SyncFeatures::getInstance().toString());
2349    result.append("\n");
2350
2351    /*
2352     * Dump the visible layer list
2353     */
2354    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2355    const size_t count = currentLayers.size();
2356    colorizer.bold(result);
2357    result.appendFormat("Visible layers (count = %d)\n", count);
2358    colorizer.reset(result);
2359    for (size_t i=0 ; i<count ; i++) {
2360        const sp<Layer>& layer(currentLayers[i]);
2361        layer->dump(result, colorizer);
2362    }
2363
2364    /*
2365     * Dump Display state
2366     */
2367
2368    colorizer.bold(result);
2369    result.appendFormat("Displays (%d entries)\n", mDisplays.size());
2370    colorizer.reset(result);
2371    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2372        const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2373        hw->dump(result);
2374    }
2375
2376    /*
2377     * Dump SurfaceFlinger global state
2378     */
2379
2380    colorizer.bold(result);
2381    result.append("SurfaceFlinger global state:\n");
2382    colorizer.reset(result);
2383
2384    HWComposer& hwc(getHwComposer());
2385    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2386    const GLExtensions& extensions(GLExtensions::getInstance());
2387
2388    colorizer.bold(result);
2389    result.appendFormat("EGL implementation : %s\n",
2390            eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2391    colorizer.reset(result);
2392    result.appendFormat("%s\n",
2393            eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2394
2395    colorizer.bold(result);
2396    result.appendFormat("GLES: %s, %s, %s\n",
2397            extensions.getVendor(),
2398            extensions.getRenderer(),
2399            extensions.getVersion());
2400    colorizer.reset(result);
2401    result.appendFormat("%s\n", extensions.getExtension());
2402
2403    hw->undefinedRegion.dump(result, "undefinedRegion");
2404    result.appendFormat("  orientation=%d, canDraw=%d\n",
2405            hw->getOrientation(), hw->canDraw());
2406    result.appendFormat(
2407            "  last eglSwapBuffers() time: %f us\n"
2408            "  last transaction time     : %f us\n"
2409            "  transaction-flags         : %08x\n"
2410            "  refresh-rate              : %f fps\n"
2411            "  x-dpi                     : %f\n"
2412            "  y-dpi                     : %f\n"
2413            "  EGL_NATIVE_VISUAL_ID      : %d\n"
2414            "  gpu_to_cpu_unsupported    : %d\n"
2415            ,
2416            mLastSwapBufferTime/1000.0,
2417            mLastTransactionTime/1000.0,
2418            mTransactionFlags,
2419            1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2420            hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2421            hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2422            mEGLNativeVisualId,
2423            !mGpuToCpuSupported);
2424
2425    result.appendFormat("  eglSwapBuffers time: %f us\n",
2426            inSwapBuffersDuration/1000.0);
2427
2428    result.appendFormat("  transaction time: %f us\n",
2429            inTransactionDuration/1000.0);
2430
2431    /*
2432     * VSYNC state
2433     */
2434    mEventThread->dump(result);
2435
2436    /*
2437     * Dump HWComposer state
2438     */
2439    colorizer.bold(result);
2440    result.append("h/w composer state:\n");
2441    colorizer.reset(result);
2442    result.appendFormat("  h/w composer %s and %s\n",
2443            hwc.initCheck()==NO_ERROR ? "present" : "not present",
2444                    (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
2445    hwc.dump(result);
2446
2447    /*
2448     * Dump gralloc state
2449     */
2450    const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2451    alloc.dump(result);
2452}
2453
2454const Vector< sp<Layer> >&
2455SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2456    // Note: mStateLock is held here
2457    wp<IBinder> dpy;
2458    for (size_t i=0 ; i<mDisplays.size() ; i++) {
2459        if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2460            dpy = mDisplays.keyAt(i);
2461            break;
2462        }
2463    }
2464    if (dpy == NULL) {
2465        ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2466        // Just use the primary display so we have something to return
2467        dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2468    }
2469    return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2470}
2471
2472bool SurfaceFlinger::startDdmConnection()
2473{
2474    void* libddmconnection_dso =
2475            dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2476    if (!libddmconnection_dso) {
2477        return false;
2478    }
2479    void (*DdmConnection_start)(const char* name);
2480    DdmConnection_start =
2481            (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start");
2482    if (!DdmConnection_start) {
2483        dlclose(libddmconnection_dso);
2484        return false;
2485    }
2486    (*DdmConnection_start)(getServiceName());
2487    return true;
2488}
2489
2490status_t SurfaceFlinger::onTransact(
2491    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2492{
2493    switch (code) {
2494        case CREATE_CONNECTION:
2495        case CREATE_DISPLAY:
2496        case SET_TRANSACTION_STATE:
2497        case BOOT_FINISHED:
2498        case BLANK:
2499        case UNBLANK:
2500        {
2501            // codes that require permission check
2502            IPCThreadState* ipc = IPCThreadState::self();
2503            const int pid = ipc->getCallingPid();
2504            const int uid = ipc->getCallingUid();
2505            if ((uid != AID_GRAPHICS) &&
2506                    !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2507                ALOGE("Permission Denial: "
2508                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2509                return PERMISSION_DENIED;
2510            }
2511            break;
2512        }
2513        case CAPTURE_SCREEN:
2514        {
2515            // codes that require permission check
2516            IPCThreadState* ipc = IPCThreadState::self();
2517            const int pid = ipc->getCallingPid();
2518            const int uid = ipc->getCallingUid();
2519            if ((uid != AID_GRAPHICS) &&
2520                    !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2521                ALOGE("Permission Denial: "
2522                        "can't read framebuffer pid=%d, uid=%d", pid, uid);
2523                return PERMISSION_DENIED;
2524            }
2525            break;
2526        }
2527    }
2528
2529    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2530    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2531        CHECK_INTERFACE(ISurfaceComposer, data, reply);
2532        if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2533            IPCThreadState* ipc = IPCThreadState::self();
2534            const int pid = ipc->getCallingPid();
2535            const int uid = ipc->getCallingUid();
2536            ALOGE("Permission Denial: "
2537                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2538            return PERMISSION_DENIED;
2539        }
2540        int n;
2541        switch (code) {
2542            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2543            case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2544                return NO_ERROR;
2545            case 1002:  // SHOW_UPDATES
2546                n = data.readInt32();
2547                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2548                invalidateHwcGeometry();
2549                repaintEverything();
2550                return NO_ERROR;
2551            case 1004:{ // repaint everything
2552                repaintEverything();
2553                return NO_ERROR;
2554            }
2555            case 1005:{ // force transaction
2556                setTransactionFlags(
2557                        eTransactionNeeded|
2558                        eDisplayTransactionNeeded|
2559                        eTraversalNeeded);
2560                return NO_ERROR;
2561            }
2562            case 1006:{ // send empty update
2563                signalRefresh();
2564                return NO_ERROR;
2565            }
2566            case 1008:  // toggle use of hw composer
2567                n = data.readInt32();
2568                mDebugDisableHWC = n ? 1 : 0;
2569                invalidateHwcGeometry();
2570                repaintEverything();
2571                return NO_ERROR;
2572            case 1009:  // toggle use of transform hint
2573                n = data.readInt32();
2574                mDebugDisableTransformHint = n ? 1 : 0;
2575                invalidateHwcGeometry();
2576                repaintEverything();
2577                return NO_ERROR;
2578            case 1010:  // interrogate.
2579                reply->writeInt32(0);
2580                reply->writeInt32(0);
2581                reply->writeInt32(mDebugRegion);
2582                reply->writeInt32(0);
2583                reply->writeInt32(mDebugDisableHWC);
2584                return NO_ERROR;
2585            case 1013: {
2586                Mutex::Autolock _l(mStateLock);
2587                sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2588                reply->writeInt32(hw->getPageFlipCount());
2589            }
2590            return NO_ERROR;
2591        }
2592    }
2593    return err;
2594}
2595
2596void SurfaceFlinger::repaintEverything() {
2597    android_atomic_or(1, &mRepaintEverything);
2598    signalTransaction();
2599}
2600
2601// ---------------------------------------------------------------------------
2602// Capture screen into an IGraphiBufferProducer
2603// ---------------------------------------------------------------------------
2604
2605status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2606        const sp<IGraphicBufferProducer>& producer,
2607        uint32_t reqWidth, uint32_t reqHeight,
2608        uint32_t minLayerZ, uint32_t maxLayerZ,
2609        bool isCpuConsumer) {
2610
2611    if (CC_UNLIKELY(display == 0))
2612        return BAD_VALUE;
2613
2614    if (CC_UNLIKELY(producer == 0))
2615        return BAD_VALUE;
2616
2617    class MessageCaptureScreen : public MessageBase {
2618        SurfaceFlinger* flinger;
2619        sp<IBinder> display;
2620        sp<IGraphicBufferProducer> producer;
2621        uint32_t reqWidth, reqHeight;
2622        uint32_t minLayerZ,maxLayerZ;
2623        bool isCpuConsumer;
2624        status_t result;
2625    public:
2626        MessageCaptureScreen(SurfaceFlinger* flinger,
2627                const sp<IBinder>& display,
2628                const sp<IGraphicBufferProducer>& producer,
2629                uint32_t reqWidth, uint32_t reqHeight,
2630                uint32_t minLayerZ, uint32_t maxLayerZ, bool isCpuConsumer)
2631            : flinger(flinger), display(display), producer(producer),
2632              reqWidth(reqWidth), reqHeight(reqHeight),
2633              minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2634              isCpuConsumer(isCpuConsumer),
2635              result(PERMISSION_DENIED)
2636        {
2637        }
2638        status_t getResult() const {
2639            return result;
2640        }
2641        virtual bool handler() {
2642            Mutex::Autolock _l(flinger->mStateLock);
2643            sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
2644            bool useReadPixels = isCpuConsumer && !flinger->mGpuToCpuSupported;
2645            result = flinger->captureScreenImplLocked(hw,
2646                    producer, reqWidth, reqHeight, minLayerZ, maxLayerZ,
2647                    useReadPixels);
2648
2649            return true;
2650        }
2651    };
2652
2653    // make sure to process transactions before screenshots -- a transaction
2654    // might already be pending but scheduled for VSYNC; this guarantees we
2655    // will handle it before the screenshot. When VSYNC finally arrives
2656    // the scheduled transaction will be a no-op. If no transactions are
2657    // scheduled at this time, this will end-up being a no-op as well.
2658    mEventQueue.invalidateTransactionNow();
2659
2660    sp<MessageBase> msg = new MessageCaptureScreen(this,
2661            display, producer, reqWidth, reqHeight, minLayerZ, maxLayerZ,
2662            isCpuConsumer);
2663    status_t res = postMessageSync(msg);
2664    if (res == NO_ERROR) {
2665        res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2666    }
2667    return res;
2668}
2669
2670
2671void SurfaceFlinger::renderScreenImplLocked(
2672        const sp<const DisplayDevice>& hw,
2673        uint32_t reqWidth, uint32_t reqHeight,
2674        uint32_t minLayerZ, uint32_t maxLayerZ,
2675        bool yswap)
2676{
2677    ATRACE_CALL();
2678
2679    // get screen geometry
2680    const uint32_t hw_w = hw->getWidth();
2681    const uint32_t hw_h = hw->getHeight();
2682
2683    const bool filtering = reqWidth != hw_w || reqWidth != hw_h;
2684
2685    // make sure to clear all GL error flags
2686    while ( glGetError() != GL_NO_ERROR ) ;
2687
2688    // set-up our viewport
2689    glViewport(0, 0, reqWidth, reqHeight);
2690    glMatrixMode(GL_PROJECTION);
2691    glLoadIdentity();
2692    if (yswap)  glOrthof(0, hw_w, hw_h, 0, 0, 1);
2693    else        glOrthof(0, hw_w, 0, hw_h, 0, 1);
2694    glMatrixMode(GL_MODELVIEW);
2695    glLoadIdentity();
2696
2697    // redraw the screen entirely...
2698    glDisable(GL_SCISSOR_TEST);
2699    glClearColor(0,0,0,1);
2700    glClear(GL_COLOR_BUFFER_BIT);
2701    glDisable(GL_TEXTURE_EXTERNAL_OES);
2702    glDisable(GL_TEXTURE_2D);
2703
2704    const LayerVector& layers( mDrawingState.layersSortedByZ );
2705    const size_t count = layers.size();
2706    for (size_t i=0 ; i<count ; ++i) {
2707        const sp<Layer>& layer(layers[i]);
2708        const Layer::State& state(layer->drawingState());
2709        if (state.layerStack == hw->getLayerStack()) {
2710            if (state.z >= minLayerZ && state.z <= maxLayerZ) {
2711                if (layer->isVisible()) {
2712                    if (filtering) layer->setFiltering(true);
2713                    layer->draw(hw);
2714                    if (filtering) layer->setFiltering(false);
2715                }
2716            }
2717        }
2718    }
2719
2720    // compositionComplete is needed for older driver
2721    hw->compositionComplete();
2722}
2723
2724
2725status_t SurfaceFlinger::captureScreenImplLocked(
2726        const sp<const DisplayDevice>& hw,
2727        const sp<IGraphicBufferProducer>& producer,
2728        uint32_t reqWidth, uint32_t reqHeight,
2729        uint32_t minLayerZ, uint32_t maxLayerZ,
2730        bool useReadPixels)
2731{
2732    ATRACE_CALL();
2733
2734    if (!GLExtensions::getInstance().haveFramebufferObject()) {
2735        return INVALID_OPERATION;
2736    }
2737
2738    // get screen geometry
2739    const uint32_t hw_w = hw->getWidth();
2740    const uint32_t hw_h = hw->getHeight();
2741
2742    // if we have secure windows on this display, never allow the screen capture
2743    if (hw->getSecureLayerVisible()) {
2744        ALOGW("FB is protected: PERMISSION_DENIED");
2745        return PERMISSION_DENIED;
2746    }
2747
2748    if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
2749        ALOGE("size mismatch (%d, %d) > (%d, %d)",
2750                reqWidth, reqHeight, hw_w, hw_h);
2751        return BAD_VALUE;
2752    }
2753
2754    reqWidth  = (!reqWidth)  ? hw_w : reqWidth;
2755    reqHeight = (!reqHeight) ? hw_h : reqHeight;
2756
2757    // create a surface (because we're a producer, and we need to
2758    // dequeue/queue a buffer)
2759    sp<Surface> sur = new Surface(producer);
2760    ANativeWindow* window = sur.get();
2761
2762    status_t result = NO_ERROR;
2763    if (native_window_api_connect(window, NATIVE_WINDOW_API_EGL) == NO_ERROR) {
2764        uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN;
2765        if (!useReadPixels) {
2766            usage = GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
2767        }
2768
2769        int err = 0;
2770        err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
2771        err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
2772        err |= native_window_set_usage(window, usage);
2773
2774        if (err == NO_ERROR) {
2775            ANativeWindowBuffer* buffer;
2776            /* TODO: Once we have the sync framework everywhere this can use
2777             * server-side waits on the fence that dequeueBuffer returns.
2778             */
2779            result = native_window_dequeue_buffer_and_wait(window,  &buffer);
2780            if (result == NO_ERROR) {
2781                // create an EGLImage from the buffer so we can later
2782                // turn it into a texture
2783                EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
2784                        EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
2785                if (image != EGL_NO_IMAGE_KHR) {
2786                    GLuint tname, name;
2787                    if (!useReadPixels) {
2788                        // turn our EGLImage into a texture
2789                        glGenTextures(1, &tname);
2790                        glBindTexture(GL_TEXTURE_2D, tname);
2791                        glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, (GLeglImageOES)image);
2792                        // create a Framebuffer Object to render into
2793                        glGenFramebuffersOES(1, &name);
2794                        glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2795                        glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
2796                                GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tname, 0);
2797                    } else {
2798                        // since we're going to use glReadPixels() anyways,
2799                        // use an intermediate renderbuffer instead
2800                        glGenRenderbuffersOES(1, &tname);
2801                        glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2802                        glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, reqWidth, reqHeight);
2803                        // create a FBO to render into
2804                        glGenFramebuffersOES(1, &name);
2805                        glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2806                        glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2807                                GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2808                    }
2809
2810                    GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2811                    if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2812                        // this will in fact render into our dequeued buffer
2813                        // via an FBO, which means we didn't have to create
2814                        // an EGLSurface and therefore we're not
2815                        // dependent on the context's EGLConfig.
2816                        renderScreenImplLocked(hw, reqWidth, reqHeight,
2817                                minLayerZ, maxLayerZ, true);
2818
2819                        if (useReadPixels) {
2820                            sp<GraphicBuffer> buf = static_cast<GraphicBuffer*>(buffer);
2821                            void* vaddr;
2822                            if (buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, &vaddr) == NO_ERROR) {
2823                                glReadPixels(0, 0, buffer->stride, reqHeight,
2824                                        GL_RGBA, GL_UNSIGNED_BYTE, vaddr);
2825                                buf->unlock();
2826                            }
2827                        }
2828                    } else {
2829                        ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
2830                        result = INVALID_OPERATION;
2831                    }
2832
2833                    // back to main framebuffer
2834                    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2835                    glDeleteFramebuffersOES(1, &name);
2836                    if (!useReadPixels) {
2837                        glDeleteTextures(1, &tname);
2838                    } else {
2839                        glDeleteRenderbuffersOES(1, &tname);
2840                    }
2841                    // destroy our image
2842                    eglDestroyImageKHR(mEGLDisplay, image);
2843                } else {
2844                    result = BAD_VALUE;
2845                }
2846                window->queueBuffer(window, buffer, -1);
2847            }
2848        } else {
2849            result = BAD_VALUE;
2850        }
2851        native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
2852    }
2853
2854    DisplayDevice::setViewportAndProjection(hw);
2855
2856    return result;
2857}
2858
2859// ---------------------------------------------------------------------------
2860
2861SurfaceFlinger::LayerVector::LayerVector() {
2862}
2863
2864SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
2865    : SortedVector<sp<Layer> >(rhs) {
2866}
2867
2868int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
2869    const void* rhs) const
2870{
2871    // sort layers per layer-stack, then by z-order and finally by sequence
2872    const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
2873    const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
2874
2875    uint32_t ls = l->currentState().layerStack;
2876    uint32_t rs = r->currentState().layerStack;
2877    if (ls != rs)
2878        return ls - rs;
2879
2880    uint32_t lz = l->currentState().z;
2881    uint32_t rz = r->currentState().z;
2882    if (lz != rz)
2883        return lz - rz;
2884
2885    return l->sequence - r->sequence;
2886}
2887
2888// ---------------------------------------------------------------------------
2889
2890SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
2891    : type(DisplayDevice::DISPLAY_ID_INVALID) {
2892}
2893
2894SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
2895    : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0) {
2896    viewport.makeInvalid();
2897    frame.makeInvalid();
2898}
2899
2900// ---------------------------------------------------------------------------
2901
2902}; // namespace android
2903