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