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