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