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