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