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