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