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