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