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