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