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