OSDN Git Service

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