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