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