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