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