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