OSDN Git Service

Merge "Fix out-of-order transactions (2/2)" into oc-dr1-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 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> bootFinished = new LambdaMessage([&]() {
395         mBootFinished = true;
396
397         readPersistentProperties();
398
399 #ifdef USE_HWC2
400         sp<DisplayDevice> hw(getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
401         if (hw->getWideColorSupport()) {
402             hw->setCompositionDataSpace(HAL_DATASPACE_V0_SRGB);
403             setActiveColorModeInternal(hw, HAL_COLOR_MODE_SRGB);
404         }
405 #endif
406     });
407     postMessageAsync(bootFinished);
408 }
409
410 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
411     class MessageDestroyGLTexture : public MessageBase {
412         RenderEngine& engine;
413         uint32_t texture;
414     public:
415         MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
416             : engine(engine), texture(texture) {
417         }
418         virtual bool handler() {
419             engine.deleteTextures(1, &texture);
420             return true;
421         }
422     };
423     postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
424 }
425
426 class DispSyncSource : public VSyncSource, private DispSync::Callback {
427 public:
428     DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
429         const char* name) :
430             mName(name),
431             mValue(0),
432             mTraceVsync(traceVsync),
433             mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
434             mVsyncEventLabel(String8::format("VSYNC-%s", name)),
435             mDispSync(dispSync),
436             mCallbackMutex(),
437             mCallback(),
438             mVsyncMutex(),
439             mPhaseOffset(phaseOffset),
440             mEnabled(false) {}
441
442     virtual ~DispSyncSource() {}
443
444     virtual void setVSyncEnabled(bool enable) {
445         Mutex::Autolock lock(mVsyncMutex);
446         if (enable) {
447             status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
448                     static_cast<DispSync::Callback*>(this));
449             if (err != NO_ERROR) {
450                 ALOGE("error registering vsync callback: %s (%d)",
451                         strerror(-err), err);
452             }
453             //ATRACE_INT(mVsyncOnLabel.string(), 1);
454         } else {
455             status_t err = mDispSync->removeEventListener(
456                     static_cast<DispSync::Callback*>(this));
457             if (err != NO_ERROR) {
458                 ALOGE("error unregistering vsync callback: %s (%d)",
459                         strerror(-err), err);
460             }
461             //ATRACE_INT(mVsyncOnLabel.string(), 0);
462         }
463         mEnabled = enable;
464     }
465
466     virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
467         Mutex::Autolock lock(mCallbackMutex);
468         mCallback = callback;
469     }
470
471     virtual void setPhaseOffset(nsecs_t phaseOffset) {
472         Mutex::Autolock lock(mVsyncMutex);
473
474         // Normalize phaseOffset to [0, period)
475         auto period = mDispSync->getPeriod();
476         phaseOffset %= period;
477         if (phaseOffset < 0) {
478             // If we're here, then phaseOffset is in (-period, 0). After this
479             // operation, it will be in (0, period)
480             phaseOffset += period;
481         }
482         mPhaseOffset = phaseOffset;
483
484         // If we're not enabled, we don't need to mess with the listeners
485         if (!mEnabled) {
486             return;
487         }
488
489         // Remove the listener with the old offset
490         status_t err = mDispSync->removeEventListener(
491                 static_cast<DispSync::Callback*>(this));
492         if (err != NO_ERROR) {
493             ALOGE("error unregistering vsync callback: %s (%d)",
494                     strerror(-err), err);
495         }
496
497         // Add a listener with the new offset
498         err = mDispSync->addEventListener(mName, mPhaseOffset,
499                 static_cast<DispSync::Callback*>(this));
500         if (err != NO_ERROR) {
501             ALOGE("error registering vsync callback: %s (%d)",
502                     strerror(-err), err);
503         }
504     }
505
506 private:
507     virtual void onDispSyncEvent(nsecs_t when) {
508         sp<VSyncSource::Callback> callback;
509         {
510             Mutex::Autolock lock(mCallbackMutex);
511             callback = mCallback;
512
513             if (mTraceVsync) {
514                 mValue = (mValue + 1) % 2;
515                 ATRACE_INT(mVsyncEventLabel.string(), mValue);
516             }
517         }
518
519         if (callback != NULL) {
520             callback->onVSyncEvent(when);
521         }
522     }
523
524     const char* const mName;
525
526     int mValue;
527
528     const bool mTraceVsync;
529     const String8 mVsyncOnLabel;
530     const String8 mVsyncEventLabel;
531
532     DispSync* mDispSync;
533
534     Mutex mCallbackMutex; // Protects the following
535     sp<VSyncSource::Callback> mCallback;
536
537     Mutex mVsyncMutex; // Protects the following
538     nsecs_t mPhaseOffset;
539     bool mEnabled;
540 };
541
542 class InjectVSyncSource : public VSyncSource {
543 public:
544     InjectVSyncSource() {}
545
546     virtual ~InjectVSyncSource() {}
547
548     virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
549         std::lock_guard<std::mutex> lock(mCallbackMutex);
550         mCallback = callback;
551     }
552
553     virtual void onInjectSyncEvent(nsecs_t when) {
554         std::lock_guard<std::mutex> lock(mCallbackMutex);
555         mCallback->onVSyncEvent(when);
556     }
557
558     virtual void setVSyncEnabled(bool) {}
559     virtual void setPhaseOffset(nsecs_t) {}
560
561 private:
562     std::mutex mCallbackMutex; // Protects the following
563     sp<VSyncSource::Callback> mCallback;
564 };
565
566 // Do not call property_set on main thread which will be blocked by init
567 // Use StartPropertySetThread instead.
568 void SurfaceFlinger::init() {
569     ALOGI(  "SurfaceFlinger's main thread ready to run. "
570             "Initializing graphics H/W...");
571
572     ALOGI("Phase offset NS: %" PRId64 "", vsyncPhaseOffsetNs);
573
574     Mutex::Autolock _l(mStateLock);
575
576     // initialize EGL for the default display
577     mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
578     eglInitialize(mEGLDisplay, NULL, NULL);
579
580     // start the EventThread
581     sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
582             vsyncPhaseOffsetNs, true, "app");
583     mEventThread = new EventThread(vsyncSrc, *this, false);
584     sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
585             sfVsyncPhaseOffsetNs, true, "sf");
586     mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
587     mEventQueue.setEventThread(mSFEventThread);
588
589     // set EventThread and SFEventThread to SCHED_FIFO to minimize jitter
590     struct sched_param param = {0};
591     param.sched_priority = 2;
592     if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
593         ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
594     }
595     if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
596         ALOGE("Couldn't set SCHED_FIFO for EventThread");
597     }
598
599     // Get a RenderEngine for the given display / config (can't fail)
600     mRenderEngine = RenderEngine::create(mEGLDisplay,
601             HAL_PIXEL_FORMAT_RGBA_8888,
602             hasWideColorDisplay ? RenderEngine::WIDE_COLOR_SUPPORT : 0);
603
604     // retrieve the EGL context that was selected/created
605     mEGLContext = mRenderEngine->getEGLContext();
606
607     LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
608             "couldn't create EGLContext");
609
610     LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
611             "Starting with vr flinger active is not currently supported.");
612     mHwc.reset(new HWComposer(false));
613     mHwc->registerCallback(this, mComposerSequenceId);
614
615     if (useVrFlinger) {
616         auto vrFlingerRequestDisplayCallback = [this] (bool requestDisplay) {
617             ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
618             mVrFlingerRequestsDisplay = requestDisplay;
619             signalTransaction();
620         };
621         mVrFlinger = dvr::VrFlinger::Create(mHwc->getComposer(),
622                                             vrFlingerRequestDisplayCallback);
623         if (!mVrFlinger) {
624             ALOGE("Failed to start vrflinger");
625         }
626     }
627
628     mEventControlThread = new EventControlThread(this);
629     mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
630
631     // initialize our drawing state
632     mDrawingState = mCurrentState;
633
634     // set initial conditions (e.g. unblank default device)
635     initializeDisplays();
636
637     mRenderEngine->primeCache();
638
639     // Inform native graphics APIs whether the present timestamp is supported:
640     if (getHwComposer().hasCapability(
641             HWC2::Capability::PresentFenceIsNotReliable)) {
642         mStartPropertySetThread = new StartPropertySetThread(false);
643     } else {
644         mStartPropertySetThread = new StartPropertySetThread(true);
645     }
646
647     if (mStartPropertySetThread->Start() != NO_ERROR) {
648         ALOGE("Run StartPropertySetThread failed!");
649     }
650
651     ALOGV("Done initializing");
652 }
653
654 void SurfaceFlinger::readPersistentProperties() {
655     char value[PROPERTY_VALUE_MAX];
656
657     property_get("persist.sys.sf.color_saturation", value, "1.0");
658     mSaturation = atof(value);
659     ALOGV("Saturation is set to %.2f", mSaturation);
660 }
661
662 void SurfaceFlinger::startBootAnim() {
663     // Start boot animation service by setting a property mailbox
664     // if property setting thread is already running, Start() will be just a NOP
665     mStartPropertySetThread->Start();
666     // Wait until property was set
667     if (mStartPropertySetThread->join() != NO_ERROR) {
668         ALOGE("Join StartPropertySetThread failed!");
669     }
670 }
671
672 size_t SurfaceFlinger::getMaxTextureSize() const {
673     return mRenderEngine->getMaxTextureSize();
674 }
675
676 size_t SurfaceFlinger::getMaxViewportDims() const {
677     return mRenderEngine->getMaxViewportDims();
678 }
679
680 // ----------------------------------------------------------------------------
681
682 bool SurfaceFlinger::authenticateSurfaceTexture(
683         const sp<IGraphicBufferProducer>& bufferProducer) const {
684     Mutex::Autolock _l(mStateLock);
685     return authenticateSurfaceTextureLocked(bufferProducer);
686 }
687
688 bool SurfaceFlinger::authenticateSurfaceTextureLocked(
689         const sp<IGraphicBufferProducer>& bufferProducer) const {
690     sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
691     return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
692 }
693
694 status_t SurfaceFlinger::getSupportedFrameTimestamps(
695         std::vector<FrameEvent>* outSupported) const {
696     *outSupported = {
697         FrameEvent::REQUESTED_PRESENT,
698         FrameEvent::ACQUIRE,
699         FrameEvent::LATCH,
700         FrameEvent::FIRST_REFRESH_START,
701         FrameEvent::LAST_REFRESH_START,
702         FrameEvent::GPU_COMPOSITION_DONE,
703         FrameEvent::DEQUEUE_READY,
704         FrameEvent::RELEASE,
705     };
706     if (!getHwComposer().hasCapability(
707             HWC2::Capability::PresentFenceIsNotReliable)) {
708         outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
709     }
710     return NO_ERROR;
711 }
712
713 status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
714         Vector<DisplayInfo>* configs) {
715     if ((configs == NULL) || (display.get() == NULL)) {
716         return BAD_VALUE;
717     }
718
719     if (!display.get())
720         return NAME_NOT_FOUND;
721
722     int32_t type = NAME_NOT_FOUND;
723     for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
724         if (display == mBuiltinDisplays[i]) {
725             type = i;
726             break;
727         }
728     }
729
730     if (type < 0) {
731         return type;
732     }
733
734     // TODO: Not sure if display density should handled by SF any longer
735     class Density {
736         static int getDensityFromProperty(char const* propName) {
737             char property[PROPERTY_VALUE_MAX];
738             int density = 0;
739             if (property_get(propName, property, NULL) > 0) {
740                 density = atoi(property);
741             }
742             return density;
743         }
744     public:
745         static int getEmuDensity() {
746             return getDensityFromProperty("qemu.sf.lcd_density"); }
747         static int getBuildDensity()  {
748             return getDensityFromProperty("ro.sf.lcd_density"); }
749     };
750
751     configs->clear();
752
753     for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
754         DisplayInfo info = DisplayInfo();
755
756         float xdpi = hwConfig->getDpiX();
757         float ydpi = hwConfig->getDpiY();
758
759         if (type == DisplayDevice::DISPLAY_PRIMARY) {
760             // The density of the device is provided by a build property
761             float density = Density::getBuildDensity() / 160.0f;
762             if (density == 0) {
763                 // the build doesn't provide a density -- this is wrong!
764                 // use xdpi instead
765                 ALOGE("ro.sf.lcd_density must be defined as a build property");
766                 density = xdpi / 160.0f;
767             }
768             if (Density::getEmuDensity()) {
769                 // if "qemu.sf.lcd_density" is specified, it overrides everything
770                 xdpi = ydpi = density = Density::getEmuDensity();
771                 density /= 160.0f;
772             }
773             info.density = density;
774
775             // TODO: this needs to go away (currently needed only by webkit)
776             sp<const DisplayDevice> hw(getDefaultDisplayDevice());
777             info.orientation = hw->getOrientation();
778         } else {
779             // TODO: where should this value come from?
780             static const int TV_DENSITY = 213;
781             info.density = TV_DENSITY / 160.0f;
782             info.orientation = 0;
783         }
784
785         info.w = hwConfig->getWidth();
786         info.h = hwConfig->getHeight();
787         info.xdpi = xdpi;
788         info.ydpi = ydpi;
789         info.fps = 1e9 / hwConfig->getVsyncPeriod();
790         info.appVsyncOffset = vsyncPhaseOffsetNs;
791
792         // This is how far in advance a buffer must be queued for
793         // presentation at a given time.  If you want a buffer to appear
794         // on the screen at time N, you must submit the buffer before
795         // (N - presentationDeadline).
796         //
797         // Normally it's one full refresh period (to give SF a chance to
798         // latch the buffer), but this can be reduced by configuring a
799         // DispSync offset.  Any additional delays introduced by the hardware
800         // composer or panel must be accounted for here.
801         //
802         // We add an additional 1ms to allow for processing time and
803         // differences between the ideal and actual refresh rate.
804         info.presentationDeadline = hwConfig->getVsyncPeriod() -
805                 sfVsyncPhaseOffsetNs + 1000000;
806
807         // All non-virtual displays are currently considered secure.
808         info.secure = true;
809
810         configs->push_back(info);
811     }
812
813     return NO_ERROR;
814 }
815
816 status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
817         DisplayStatInfo* stats) {
818     if (stats == NULL) {
819         return BAD_VALUE;
820     }
821
822     // FIXME for now we always return stats for the primary display
823     memset(stats, 0, sizeof(*stats));
824     stats->vsyncTime   = mPrimaryDispSync.computeNextRefresh(0);
825     stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
826     return NO_ERROR;
827 }
828
829 int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
830     if (display == NULL) {
831         ALOGE("%s : display is NULL", __func__);
832         return BAD_VALUE;
833     }
834
835     sp<const DisplayDevice> device(getDisplayDevice(display));
836     if (device != NULL) {
837         return device->getActiveConfig();
838     }
839
840     return BAD_VALUE;
841 }
842
843 void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
844     ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
845           this);
846     int32_t type = hw->getDisplayType();
847     int currentMode = hw->getActiveConfig();
848
849     if (mode == currentMode) {
850         ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
851         return;
852     }
853
854     if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
855         ALOGW("Trying to set config for virtual display");
856         return;
857     }
858
859     hw->setActiveConfig(mode);
860     getHwComposer().setActiveConfig(type, mode);
861 }
862
863 status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
864     class MessageSetActiveConfig: public MessageBase {
865         SurfaceFlinger& mFlinger;
866         sp<IBinder> mDisplay;
867         int mMode;
868     public:
869         MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
870                                int mode) :
871             mFlinger(flinger), mDisplay(disp) { mMode = mode; }
872         virtual bool handler() {
873             Vector<DisplayInfo> configs;
874             mFlinger.getDisplayConfigs(mDisplay, &configs);
875             if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
876                 ALOGE("Attempt to set active config = %d for display with %zu configs",
877                         mMode, configs.size());
878                 return true;
879             }
880             sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
881             if (hw == NULL) {
882                 ALOGE("Attempt to set active config = %d for null display %p",
883                         mMode, mDisplay.get());
884             } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
885                 ALOGW("Attempt to set active config = %d for virtual display",
886                         mMode);
887             } else {
888                 mFlinger.setActiveConfigInternal(hw, mMode);
889             }
890             return true;
891         }
892     };
893     sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
894     postMessageSync(msg);
895     return NO_ERROR;
896 }
897 status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
898         Vector<android_color_mode_t>* outColorModes) {
899     if ((outColorModes == nullptr) || (display.get() == nullptr)) {
900         return BAD_VALUE;
901     }
902
903     if (!display.get()) {
904         return NAME_NOT_FOUND;
905     }
906
907     int32_t type = NAME_NOT_FOUND;
908     for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
909         if (display == mBuiltinDisplays[i]) {
910             type = i;
911             break;
912         }
913     }
914
915     if (type < 0) {
916         return type;
917     }
918
919     std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
920     outColorModes->clear();
921     std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
922
923     return NO_ERROR;
924 }
925
926 android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
927     sp<const DisplayDevice> device(getDisplayDevice(display));
928     if (device != nullptr) {
929         return device->getActiveColorMode();
930     }
931     return static_cast<android_color_mode_t>(BAD_VALUE);
932 }
933
934 void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
935         android_color_mode_t mode) {
936     int32_t type = hw->getDisplayType();
937     android_color_mode_t currentMode = hw->getActiveColorMode();
938
939     if (mode == currentMode) {
940         return;
941     }
942
943     if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
944         ALOGW("Trying to set config for virtual display");
945         return;
946     }
947
948     ALOGD("Set active color mode: %s (%d), type=%d", decodeColorMode(mode).c_str(), mode,
949           hw->getDisplayType());
950
951     hw->setActiveColorMode(mode);
952     getHwComposer().setActiveColorMode(type, mode);
953 }
954
955
956 status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
957         android_color_mode_t colorMode) {
958     class MessageSetActiveColorMode: public MessageBase {
959         SurfaceFlinger& mFlinger;
960         sp<IBinder> mDisplay;
961         android_color_mode_t mMode;
962     public:
963         MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
964                                android_color_mode_t mode) :
965             mFlinger(flinger), mDisplay(disp) { mMode = mode; }
966         virtual bool handler() {
967             Vector<android_color_mode_t> modes;
968             mFlinger.getDisplayColorModes(mDisplay, &modes);
969             bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
970             if (mMode < 0 || !exists) {
971                 ALOGE("Attempt to set invalid active color mode %s (%d) for display %p",
972                       decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
973                 return true;
974             }
975             sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
976             if (hw == nullptr) {
977                 ALOGE("Attempt to set active color mode %s (%d) for null display %p",
978                       decodeColorMode(mMode).c_str(), mMode, mDisplay.get());
979             } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
980                 ALOGW("Attempt to set active color mode %s %d for virtual display",
981                       decodeColorMode(mMode).c_str(), mMode);
982             } else {
983                 mFlinger.setActiveColorModeInternal(hw, mMode);
984             }
985             return true;
986         }
987     };
988     sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
989     postMessageSync(msg);
990     return NO_ERROR;
991 }
992
993 status_t SurfaceFlinger::clearAnimationFrameStats() {
994     Mutex::Autolock _l(mStateLock);
995     mAnimFrameTracker.clearStats();
996     return NO_ERROR;
997 }
998
999 status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1000     Mutex::Autolock _l(mStateLock);
1001     mAnimFrameTracker.getStats(outStats);
1002     return NO_ERROR;
1003 }
1004
1005 status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
1006         HdrCapabilities* outCapabilities) const {
1007     Mutex::Autolock _l(mStateLock);
1008
1009     sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
1010     if (displayDevice == nullptr) {
1011         ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
1012         return BAD_VALUE;
1013     }
1014
1015     std::unique_ptr<HdrCapabilities> capabilities =
1016             mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
1017     if (capabilities) {
1018         std::swap(*outCapabilities, *capabilities);
1019     } else {
1020         return BAD_VALUE;
1021     }
1022
1023     return NO_ERROR;
1024 }
1025
1026 status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
1027     if (enable == mInjectVSyncs) {
1028         return NO_ERROR;
1029     }
1030
1031     if (enable) {
1032         mInjectVSyncs = enable;
1033         ALOGV("VSync Injections enabled");
1034         if (mVSyncInjector.get() == nullptr) {
1035             mVSyncInjector = new InjectVSyncSource();
1036             mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
1037         }
1038         mEventQueue.setEventThread(mInjectorEventThread);
1039     } else {
1040         mInjectVSyncs = enable;
1041         ALOGV("VSync Injections disabled");
1042         mEventQueue.setEventThread(mSFEventThread);
1043         mVSyncInjector.clear();
1044     }
1045     return NO_ERROR;
1046 }
1047
1048 status_t SurfaceFlinger::injectVSync(nsecs_t when) {
1049     if (!mInjectVSyncs) {
1050         ALOGE("VSync Injections not enabled");
1051         return BAD_VALUE;
1052     }
1053     if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1054         ALOGV("Injecting VSync inside SurfaceFlinger");
1055         mVSyncInjector->onInjectSyncEvent(when);
1056     }
1057     return NO_ERROR;
1058 }
1059
1060 // ----------------------------------------------------------------------------
1061
1062 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1063         ISurfaceComposer::VsyncSource vsyncSource) {
1064     if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1065         return mSFEventThread->createEventConnection();
1066     } else {
1067         return mEventThread->createEventConnection();
1068     }
1069 }
1070
1071 // ----------------------------------------------------------------------------
1072
1073 void SurfaceFlinger::waitForEvent() {
1074     mEventQueue.waitMessage();
1075 }
1076
1077 void SurfaceFlinger::signalTransaction() {
1078     mEventQueue.invalidate();
1079 }
1080
1081 void SurfaceFlinger::signalLayerUpdate() {
1082     mEventQueue.invalidate();
1083 }
1084
1085 void SurfaceFlinger::signalRefresh() {
1086     mRefreshPending = true;
1087     mEventQueue.refresh();
1088 }
1089
1090 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
1091         nsecs_t reltime, uint32_t /* flags */) {
1092     return mEventQueue.postMessage(msg, reltime);
1093 }
1094
1095 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
1096         nsecs_t reltime, uint32_t /* flags */) {
1097     status_t res = mEventQueue.postMessage(msg, reltime);
1098     if (res == NO_ERROR) {
1099         msg->wait();
1100     }
1101     return res;
1102 }
1103
1104 void SurfaceFlinger::run() {
1105     do {
1106         waitForEvent();
1107     } while (true);
1108 }
1109
1110 void SurfaceFlinger::enableHardwareVsync() {
1111     Mutex::Autolock _l(mHWVsyncLock);
1112     if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
1113         mPrimaryDispSync.beginResync();
1114         //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1115         mEventControlThread->setVsyncEnabled(true);
1116         mPrimaryHWVsyncEnabled = true;
1117     }
1118 }
1119
1120 void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
1121     Mutex::Autolock _l(mHWVsyncLock);
1122
1123     if (makeAvailable) {
1124         mHWVsyncAvailable = true;
1125     } else if (!mHWVsyncAvailable) {
1126         // Hardware vsync is not currently available, so abort the resync
1127         // attempt for now
1128         return;
1129     }
1130
1131     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1132     const nsecs_t period = activeConfig->getVsyncPeriod();
1133
1134     mPrimaryDispSync.reset();
1135     mPrimaryDispSync.setPeriod(period);
1136
1137     if (!mPrimaryHWVsyncEnabled) {
1138         mPrimaryDispSync.beginResync();
1139         //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
1140         mEventControlThread->setVsyncEnabled(true);
1141         mPrimaryHWVsyncEnabled = true;
1142     }
1143 }
1144
1145 void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
1146     Mutex::Autolock _l(mHWVsyncLock);
1147     if (mPrimaryHWVsyncEnabled) {
1148         //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1149         mEventControlThread->setVsyncEnabled(false);
1150         mPrimaryDispSync.endResync();
1151         mPrimaryHWVsyncEnabled = false;
1152     }
1153     if (makeUnavailable) {
1154         mHWVsyncAvailable = false;
1155     }
1156 }
1157
1158 void SurfaceFlinger::resyncWithRateLimit() {
1159     static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1160
1161     // No explicit locking is needed here since EventThread holds a lock while calling this method
1162     static nsecs_t sLastResyncAttempted = 0;
1163     const nsecs_t now = systemTime();
1164     if (now - sLastResyncAttempted > kIgnoreDelay) {
1165         resyncToHardwareVsync(false);
1166     }
1167     sLastResyncAttempted = now;
1168 }
1169
1170 void SurfaceFlinger::onVsyncReceived(int32_t sequenceId,
1171         hwc2_display_t displayId, int64_t timestamp) {
1172     Mutex::Autolock lock(mStateLock);
1173     // Ignore any vsyncs from a previous hardware composer.
1174     if (sequenceId != mComposerSequenceId) {
1175         return;
1176     }
1177
1178     int32_t type;
1179     if (!mHwc->onVsync(displayId, timestamp, &type)) {
1180         return;
1181     }
1182
1183     bool needsHwVsync = false;
1184
1185     { // Scope for the lock
1186         Mutex::Autolock _l(mHWVsyncLock);
1187         if (type == DisplayDevice::DISPLAY_PRIMARY && mPrimaryHWVsyncEnabled) {
1188             needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
1189         }
1190     }
1191
1192     if (needsHwVsync) {
1193         enableHardwareVsync();
1194     } else {
1195         disableHardwareVsync(false);
1196     }
1197 }
1198
1199 void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
1200     std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1201     *compositorTiming = mCompositorTiming;
1202 }
1203
1204 void SurfaceFlinger::createDefaultDisplayDevice() {
1205     const DisplayDevice::DisplayType type = DisplayDevice::DISPLAY_PRIMARY;
1206     wp<IBinder> token = mBuiltinDisplays[type];
1207
1208     // All non-virtual displays are currently considered secure.
1209     const bool isSecure = true;
1210
1211     sp<IGraphicBufferProducer> producer;
1212     sp<IGraphicBufferConsumer> consumer;
1213     BufferQueue::createBufferQueue(&producer, &consumer);
1214
1215     sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, type, consumer);
1216
1217     bool hasWideColorModes = false;
1218     std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
1219     for (android_color_mode_t colorMode : modes) {
1220         switch (colorMode) {
1221             case HAL_COLOR_MODE_DISPLAY_P3:
1222             case HAL_COLOR_MODE_ADOBE_RGB:
1223             case HAL_COLOR_MODE_DCI_P3:
1224                 hasWideColorModes = true;
1225                 break;
1226             default:
1227                 break;
1228         }
1229     }
1230     sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_PRIMARY, type, isSecure,
1231                                              token, fbs, producer, mRenderEngine->getEGLConfig(),
1232                                              hasWideColorModes && hasWideColorDisplay);
1233     mDisplays.add(token, hw);
1234     setActiveColorModeInternal(hw, HAL_COLOR_MODE_NATIVE);
1235     hw->setCompositionDataSpace(HAL_DATASPACE_UNKNOWN);
1236
1237     // Add the primary display token to mDrawingState so we don't try to
1238     // recreate the DisplayDevice for the primary display.
1239     mDrawingState.displays.add(token, DisplayDeviceState(type, true));
1240
1241     // make the GLContext current so that we can create textures when creating
1242     // Layers (which may happens before we render something)
1243     hw->makeCurrent(mEGLDisplay, mEGLContext);
1244 }
1245
1246 void SurfaceFlinger::onHotplugReceived(int32_t sequenceId,
1247         hwc2_display_t display, HWC2::Connection connection,
1248         bool primaryDisplay) {
1249     ALOGV("onHotplugReceived(%d, %" PRIu64 ", %s, %s)",
1250           sequenceId, display,
1251           connection == HWC2::Connection::Connected ?
1252                   "connected" : "disconnected",
1253           primaryDisplay ? "primary" : "external");
1254
1255     // Only lock if we're not on the main thread. This function is normally
1256     // called on a hwbinder thread, but for the primary display it's called on
1257     // the main thread with the state lock already held, so don't attempt to
1258     // acquire it here.
1259     ConditionalLock lock(mStateLock,
1260             std::this_thread::get_id() != mMainThreadId);
1261
1262     if (primaryDisplay) {
1263         mHwc->onHotplug(display, connection);
1264         if (!mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY].get()) {
1265             createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1266         }
1267         createDefaultDisplayDevice();
1268     } else {
1269         if (sequenceId != mComposerSequenceId) {
1270             return;
1271         }
1272         if (mHwc->isUsingVrComposer()) {
1273             ALOGE("External displays are not supported by the vr hardware composer.");
1274             return;
1275         }
1276         mHwc->onHotplug(display, connection);
1277         auto type = DisplayDevice::DISPLAY_EXTERNAL;
1278         if (connection == HWC2::Connection::Connected) {
1279             createBuiltinDisplayLocked(type);
1280         } else {
1281             mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1282             mBuiltinDisplays[type].clear();
1283         }
1284         setTransactionFlags(eDisplayTransactionNeeded);
1285
1286         // Defer EventThread notification until SF has updated mDisplays.
1287     }
1288 }
1289
1290 void SurfaceFlinger::onRefreshReceived(int sequenceId,
1291                                        hwc2_display_t /*display*/) {
1292     Mutex::Autolock lock(mStateLock);
1293     if (sequenceId != mComposerSequenceId) {
1294         return;
1295     }
1296     repaintEverything();
1297 }
1298
1299 void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
1300     ATRACE_CALL();
1301     Mutex::Autolock lock(mStateLock);
1302     getHwComposer().setVsyncEnabled(disp,
1303             enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1304 }
1305
1306 // Note: it is assumed the caller holds |mStateLock| when this is called
1307 void SurfaceFlinger::resetDisplayState() {
1308     disableHardwareVsync(true);
1309     // Clear the drawing state so that the logic inside of
1310     // handleTransactionLocked will fire. It will determine the delta between
1311     // mCurrentState and mDrawingState and re-apply all changes when we make the
1312     // transition.
1313     mDrawingState.displays.clear();
1314     eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1315     mDisplays.clear();
1316 }
1317
1318 void SurfaceFlinger::updateVrFlinger() {
1319     if (!mVrFlinger)
1320         return;
1321     bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
1322     if (vrFlingerRequestsDisplay == mHwc->isUsingVrComposer()) {
1323         return;
1324     }
1325
1326     if (vrFlingerRequestsDisplay && !mHwc->getComposer()->isRemote()) {
1327         ALOGE("Vr flinger is only supported for remote hardware composer"
1328               " service connections. Ignoring request to transition to vr"
1329               " flinger.");
1330         mVrFlingerRequestsDisplay = false;
1331         return;
1332     }
1333
1334     Mutex::Autolock _l(mStateLock);
1335
1336     int currentDisplayPowerMode = getDisplayDeviceLocked(
1337             mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY])->getPowerMode();
1338
1339     if (!vrFlingerRequestsDisplay) {
1340         mVrFlinger->SeizeDisplayOwnership();
1341     }
1342
1343     resetDisplayState();
1344     mHwc.reset();  // Delete the current instance before creating the new one
1345     mHwc.reset(new HWComposer(vrFlingerRequestsDisplay));
1346     mHwc->registerCallback(this, ++mComposerSequenceId);
1347
1348     LOG_ALWAYS_FATAL_IF(!mHwc->getComposer()->isRemote(),
1349             "Switched to non-remote hardware composer");
1350
1351     if (vrFlingerRequestsDisplay) {
1352         mVrFlinger->GrantDisplayOwnership();
1353     } else {
1354         enableHardwareVsync();
1355     }
1356
1357     mVisibleRegionsDirty = true;
1358     invalidateHwcGeometry();
1359
1360     // Re-enable default display.
1361     sp<DisplayDevice> hw(getDisplayDeviceLocked(
1362             mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]));
1363     setPowerModeInternal(hw, currentDisplayPowerMode, /*stateLockHeld*/ true);
1364
1365     // Reset the timing values to account for the period of the swapped in HWC
1366     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
1367     const nsecs_t period = activeConfig->getVsyncPeriod();
1368     mAnimFrameTracker.setDisplayRefreshPeriod(period);
1369
1370     // Use phase of 0 since phase is not known.
1371     // Use latency of 0, which will snap to the ideal latency.
1372     setCompositorTimingSnapped(0, period, 0);
1373
1374     android_atomic_or(1, &mRepaintEverything);
1375     setTransactionFlags(eDisplayTransactionNeeded);
1376 }
1377
1378 void SurfaceFlinger::onMessageReceived(int32_t what) {
1379     ATRACE_CALL();
1380     switch (what) {
1381         case MessageQueue::INVALIDATE: {
1382             bool frameMissed = !mHadClientComposition &&
1383                     mPreviousPresentFence != Fence::NO_FENCE &&
1384                     (mPreviousPresentFence->getSignalTime() ==
1385                             Fence::SIGNAL_TIME_PENDING);
1386             ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1387             if (mPropagateBackpressure && frameMissed) {
1388                 signalLayerUpdate();
1389                 break;
1390             }
1391
1392             // Now that we're going to make it to the handleMessageTransaction()
1393             // call below it's safe to call updateVrFlinger(), which will
1394             // potentially trigger a display handoff.
1395             updateVrFlinger();
1396
1397             bool refreshNeeded = handleMessageTransaction();
1398             refreshNeeded |= handleMessageInvalidate();
1399             refreshNeeded |= mRepaintEverything;
1400             if (refreshNeeded) {
1401                 // Signal a refresh if a transaction modified the window state,
1402                 // a new buffer was latched, or if HWC has requested a full
1403                 // repaint
1404                 signalRefresh();
1405             }
1406             break;
1407         }
1408         case MessageQueue::REFRESH: {
1409             handleMessageRefresh();
1410             break;
1411         }
1412     }
1413 }
1414
1415 bool SurfaceFlinger::handleMessageTransaction() {
1416     uint32_t transactionFlags = peekTransactionFlags();
1417     if (transactionFlags) {
1418         handleTransaction(transactionFlags);
1419         return true;
1420     }
1421     return false;
1422 }
1423
1424 bool SurfaceFlinger::handleMessageInvalidate() {
1425     ATRACE_CALL();
1426     return handlePageFlip();
1427 }
1428
1429 void SurfaceFlinger::handleMessageRefresh() {
1430     ATRACE_CALL();
1431
1432     mRefreshPending = false;
1433
1434     nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1435
1436     preComposition(refreshStartTime);
1437     rebuildLayerStacks();
1438     setUpHWComposer();
1439     doDebugFlashRegions();
1440     doComposition();
1441     postComposition(refreshStartTime);
1442
1443     mPreviousPresentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1444
1445     mHadClientComposition = false;
1446     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1447         const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1448         mHadClientComposition = mHadClientComposition ||
1449                 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1450     }
1451
1452     mLayersWithQueuedFrames.clear();
1453 }
1454
1455 void SurfaceFlinger::doDebugFlashRegions()
1456 {
1457     // is debugging enabled
1458     if (CC_LIKELY(!mDebugRegion))
1459         return;
1460
1461     const bool repaintEverything = mRepaintEverything;
1462     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1463         const sp<DisplayDevice>& hw(mDisplays[dpy]);
1464         if (hw->isDisplayOn()) {
1465             // transform the dirty region into this screen's coordinate space
1466             const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1467             if (!dirtyRegion.isEmpty()) {
1468                 // redraw the whole screen
1469                 doComposeSurfaces(hw, Region(hw->bounds()));
1470
1471                 // and draw the dirty region
1472                 const int32_t height = hw->getHeight();
1473                 RenderEngine& engine(getRenderEngine());
1474                 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1475
1476                 hw->swapBuffers(getHwComposer());
1477             }
1478         }
1479     }
1480
1481     postFramebuffer();
1482
1483     if (mDebugRegion > 1) {
1484         usleep(mDebugRegion * 1000);
1485     }
1486
1487     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1488         auto& displayDevice = mDisplays[displayId];
1489         if (!displayDevice->isDisplayOn()) {
1490             continue;
1491         }
1492
1493         status_t result = displayDevice->prepareFrame(*mHwc);
1494         ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1495                 " %d (%s)", displayId, result, strerror(-result));
1496     }
1497 }
1498
1499 void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
1500 {
1501     ATRACE_CALL();
1502     ALOGV("preComposition");
1503
1504     bool needExtraInvalidate = false;
1505     mDrawingState.traverseInZOrder([&](Layer* layer) {
1506         if (layer->onPreComposition(refreshStartTime)) {
1507             needExtraInvalidate = true;
1508         }
1509     });
1510
1511     if (needExtraInvalidate) {
1512         signalLayerUpdate();
1513     }
1514 }
1515
1516 void SurfaceFlinger::updateCompositorTiming(
1517         nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1518         std::shared_ptr<FenceTime>& presentFenceTime) {
1519     // Update queue of past composite+present times and determine the
1520     // most recently known composite to present latency.
1521     mCompositePresentTimes.push({compositeTime, presentFenceTime});
1522     nsecs_t compositeToPresentLatency = -1;
1523     while (!mCompositePresentTimes.empty()) {
1524         CompositePresentTime& cpt = mCompositePresentTimes.front();
1525         // Cached values should have been updated before calling this method,
1526         // which helps avoid duplicate syscalls.
1527         nsecs_t displayTime = cpt.display->getCachedSignalTime();
1528         if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1529             break;
1530         }
1531         compositeToPresentLatency = displayTime - cpt.composite;
1532         mCompositePresentTimes.pop();
1533     }
1534
1535     // Don't let mCompositePresentTimes grow unbounded, just in case.
1536     while (mCompositePresentTimes.size() > 16) {
1537         mCompositePresentTimes.pop();
1538     }
1539
1540     setCompositorTimingSnapped(
1541             vsyncPhase, vsyncInterval, compositeToPresentLatency);
1542 }
1543
1544 void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1545         nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
1546     // Integer division and modulo round toward 0 not -inf, so we need to
1547     // treat negative and positive offsets differently.
1548     nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
1549             (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1550             ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1551
1552     // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1553     if (idealLatency <= 0) {
1554         idealLatency = vsyncInterval;
1555     }
1556
1557     // Snap the latency to a value that removes scheduling jitter from the
1558     // composition and present times, which often have >1ms of jitter.
1559     // Reducing jitter is important if an app attempts to extrapolate
1560     // something (such as user input) to an accurate diasplay time.
1561     // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1562     // with (presentLatency % interval).
1563     nsecs_t bias = vsyncInterval / 2;
1564     int64_t extraVsyncs =
1565             (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1566     nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1567             idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
1568
1569     std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1570     mCompositorTiming.deadline = vsyncPhase - idealLatency;
1571     mCompositorTiming.interval = vsyncInterval;
1572     mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
1573 }
1574
1575 void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
1576 {
1577     ATRACE_CALL();
1578     ALOGV("postComposition");
1579
1580     // Release any buffers which were replaced this frame
1581     nsecs_t dequeueReadyTime = systemTime();
1582     for (auto& layer : mLayersWithQueuedFrames) {
1583         layer->releasePendingBuffer(dequeueReadyTime);
1584     }
1585
1586     // |mStateLock| not needed as we are on the main thread
1587     const sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
1588
1589     mGlCompositionDoneTimeline.updateSignalTimes();
1590     std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
1591     if (mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY)) {
1592         glCompositionDoneFenceTime =
1593                 std::make_shared<FenceTime>(hw->getClientTargetAcquireFence());
1594         mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
1595     } else {
1596         glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1597     }
1598
1599     mDisplayTimeline.updateSignalTimes();
1600     sp<Fence> presentFence = mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);
1601     auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
1602     mDisplayTimeline.push(presentFenceTime);
1603
1604     nsecs_t vsyncPhase = mPrimaryDispSync.computeNextRefresh(0);
1605     nsecs_t vsyncInterval = mPrimaryDispSync.getPeriod();
1606
1607     // We use the refreshStartTime which might be sampled a little later than
1608     // when we started doing work for this frame, but that should be okay
1609     // since updateCompositorTiming has snapping logic.
1610     updateCompositorTiming(
1611         vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
1612     CompositorTiming compositorTiming;
1613     {
1614         std::lock_guard<std::mutex> lock(mCompositorTimingLock);
1615         compositorTiming = mCompositorTiming;
1616     }
1617
1618     mDrawingState.traverseInZOrder([&](Layer* layer) {
1619         bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
1620                 presentFenceTime, compositorTiming);
1621         if (frameLatched) {
1622             recordBufferingStats(layer->getName().string(),
1623                     layer->getOccupancyHistory(false));
1624         }
1625     });
1626
1627     if (presentFenceTime->isValid()) {
1628         if (mPrimaryDispSync.addPresentFence(presentFenceTime)) {
1629             enableHardwareVsync();
1630         } else {
1631             disableHardwareVsync(false);
1632         }
1633     }
1634
1635     if (!hasSyncFramework) {
1636         if (hw->isDisplayOn()) {
1637             enableHardwareVsync();
1638         }
1639     }
1640
1641     if (mAnimCompositionPending) {
1642         mAnimCompositionPending = false;
1643
1644         if (presentFenceTime->isValid()) {
1645             mAnimFrameTracker.setActualPresentFence(
1646                     std::move(presentFenceTime));
1647         } else {
1648             // The HWC doesn't support present fences, so use the refresh
1649             // timestamp instead.
1650             nsecs_t presentTime =
1651                     mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1652             mAnimFrameTracker.setActualPresentTime(presentTime);
1653         }
1654         mAnimFrameTracker.advanceFrame();
1655     }
1656
1657     if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1658         return;
1659     }
1660
1661     nsecs_t currentTime = systemTime();
1662     if (mHasPoweredOff) {
1663         mHasPoweredOff = false;
1664     } else {
1665         nsecs_t elapsedTime = currentTime - mLastSwapTime;
1666         size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
1667         if (numPeriods < NUM_BUCKETS - 1) {
1668             mFrameBuckets[numPeriods] += elapsedTime;
1669         } else {
1670             mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1671         }
1672         mTotalTime += elapsedTime;
1673     }
1674     mLastSwapTime = currentTime;
1675 }
1676
1677 void SurfaceFlinger::rebuildLayerStacks() {
1678     ATRACE_CALL();
1679     ALOGV("rebuildLayerStacks");
1680
1681     // rebuild the visible layer list per screen
1682     if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1683         ATRACE_CALL();
1684         mVisibleRegionsDirty = false;
1685         invalidateHwcGeometry();
1686
1687         for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1688             Region opaqueRegion;
1689             Region dirtyRegion;
1690             Vector<sp<Layer>> layersSortedByZ;
1691             const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1692             const Transform& tr(displayDevice->getTransform());
1693             const Rect bounds(displayDevice->getBounds());
1694             if (displayDevice->isDisplayOn()) {
1695                 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
1696
1697                 mDrawingState.traverseInZOrder([&](Layer* layer) {
1698                     if (layer->belongsToDisplay(displayDevice->getLayerStack(),
1699                                 displayDevice->isPrimary())) {
1700                         Region drawRegion(tr.transform(
1701                                 layer->visibleNonTransparentRegion));
1702                         drawRegion.andSelf(bounds);
1703                         if (!drawRegion.isEmpty()) {
1704                             layersSortedByZ.add(layer);
1705                         } else {
1706                             // Clear out the HWC layer if this layer was
1707                             // previously visible, but no longer is
1708                             layer->destroyHwcLayer(
1709                                     displayDevice->getHwcDisplayId());
1710                         }
1711                     } else {
1712                         // WM changes displayDevice->layerStack upon sleep/awake.
1713                         // Here we make sure we delete the HWC layers even if
1714                         // WM changed their layer stack.
1715                         layer->destroyHwcLayer(displayDevice->getHwcDisplayId());
1716                     }
1717                 });
1718             }
1719             displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1720             displayDevice->undefinedRegion.set(bounds);
1721             displayDevice->undefinedRegion.subtractSelf(
1722                     tr.transform(opaqueRegion));
1723             displayDevice->dirtyRegion.orSelf(dirtyRegion);
1724         }
1725     }
1726 }
1727
1728 mat4 SurfaceFlinger::computeSaturationMatrix() const {
1729     if (mSaturation == 1.0f) {
1730         return mat4();
1731     }
1732
1733     // Rec.709 luma coefficients
1734     float3 luminance{0.213f, 0.715f, 0.072f};
1735     luminance *= 1.0f - mSaturation;
1736     return mat4(
1737         vec4{luminance.r + mSaturation, luminance.r, luminance.r, 0.0f},
1738         vec4{luminance.g, luminance.g + mSaturation, luminance.g, 0.0f},
1739         vec4{luminance.b, luminance.b, luminance.b + mSaturation, 0.0f},
1740         vec4{0.0f, 0.0f, 0.0f, 1.0f}
1741     );
1742 }
1743
1744 // pickColorMode translates a given dataspace into the best available color mode.
1745 // Currently only support sRGB and Display-P3.
1746 android_color_mode SurfaceFlinger::pickColorMode(android_dataspace dataSpace) const {
1747     switch (dataSpace) {
1748         // treat Unknown as regular SRGB buffer, since that's what the rest of the
1749         // system expects.
1750         case HAL_DATASPACE_UNKNOWN:
1751         case HAL_DATASPACE_SRGB:
1752         case HAL_DATASPACE_V0_SRGB:
1753             return HAL_COLOR_MODE_SRGB;
1754             break;
1755
1756         case HAL_DATASPACE_DISPLAY_P3:
1757             return HAL_COLOR_MODE_DISPLAY_P3;
1758             break;
1759
1760         default:
1761             // TODO (courtneygo): Do we want to assert an error here?
1762             ALOGE("No color mode mapping for %s (%#x)", dataspaceDetails(dataSpace).c_str(),
1763                   dataSpace);
1764             return HAL_COLOR_MODE_SRGB;
1765             break;
1766     }
1767 }
1768
1769 android_dataspace SurfaceFlinger::bestTargetDataSpace(
1770         android_dataspace a, android_dataspace b) const {
1771     // Only support sRGB and Display-P3 right now.
1772     if (a == HAL_DATASPACE_DISPLAY_P3 || b == HAL_DATASPACE_DISPLAY_P3) {
1773         return HAL_DATASPACE_DISPLAY_P3;
1774     }
1775     if (a == HAL_DATASPACE_V0_SCRGB_LINEAR || b == HAL_DATASPACE_V0_SCRGB_LINEAR) {
1776         return HAL_DATASPACE_DISPLAY_P3;
1777     }
1778     if (a == HAL_DATASPACE_V0_SCRGB || b == HAL_DATASPACE_V0_SCRGB) {
1779         return HAL_DATASPACE_DISPLAY_P3;
1780     }
1781
1782     return HAL_DATASPACE_V0_SRGB;
1783 }
1784
1785 void SurfaceFlinger::setUpHWComposer() {
1786     ATRACE_CALL();
1787     ALOGV("setUpHWComposer");
1788
1789     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1790         bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1791         bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1792         bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1793
1794         // If nothing has changed (!dirty), don't recompose.
1795         // If something changed, but we don't currently have any visible layers,
1796         //   and didn't when we last did a composition, then skip it this time.
1797         // The second rule does two things:
1798         // - When all layers are removed from a display, we'll emit one black
1799         //   frame, then nothing more until we get new layers.
1800         // - When a display is created with a private layer stack, we won't
1801         //   emit any black frames until a layer is added to the layer stack.
1802         bool mustRecompose = dirty && !(empty && wasEmpty);
1803
1804         ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1805                 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1806                 mustRecompose ? "doing" : "skipping",
1807                 dirty ? "+" : "-",
1808                 empty ? "+" : "-",
1809                 wasEmpty ? "+" : "-");
1810
1811         mDisplays[dpy]->beginFrame(mustRecompose);
1812
1813         if (mustRecompose) {
1814             mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1815         }
1816     }
1817
1818     // build the h/w work list
1819     if (CC_UNLIKELY(mGeometryInvalid)) {
1820         mGeometryInvalid = false;
1821         for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1822             sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1823             const auto hwcId = displayDevice->getHwcDisplayId();
1824             if (hwcId >= 0) {
1825                 const Vector<sp<Layer>>& currentLayers(
1826                         displayDevice->getVisibleLayersSortedByZ());
1827                 for (size_t i = 0; i < currentLayers.size(); i++) {
1828                     const auto& layer = currentLayers[i];
1829                     if (!layer->hasHwcLayer(hwcId)) {
1830                         if (!layer->createHwcLayer(mHwc.get(), hwcId)) {
1831                             layer->forceClientComposition(hwcId);
1832                             continue;
1833                         }
1834                     }
1835
1836                     layer->setGeometry(displayDevice, i);
1837                     if (mDebugDisableHWC || mDebugRegion) {
1838                         layer->forceClientComposition(hwcId);
1839                     }
1840                 }
1841             }
1842         }
1843     }
1844
1845
1846     mat4 colorMatrix = mColorMatrix * computeSaturationMatrix() * mDaltonizer();
1847
1848     // Set the per-frame data
1849     for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1850         auto& displayDevice = mDisplays[displayId];
1851         const auto hwcId = displayDevice->getHwcDisplayId();
1852
1853         if (hwcId < 0) {
1854             continue;
1855         }
1856         if (colorMatrix != mPreviousColorMatrix) {
1857             status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1858             ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1859                     "display %zd: %d", displayId, result);
1860         }
1861         for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1862             layer->setPerFrameData(displayDevice);
1863         }
1864
1865         if (hasWideColorDisplay) {
1866             android_color_mode newColorMode;
1867             android_dataspace newDataSpace = HAL_DATASPACE_V0_SRGB;
1868
1869             for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1870                 newDataSpace = bestTargetDataSpace(layer->getDataSpace(), newDataSpace);
1871                 ALOGV("layer: %s, dataspace: %s (%#x), newDataSpace: %s (%#x)",
1872                       layer->getName().string(), dataspaceDetails(layer->getDataSpace()).c_str(),
1873                       layer->getDataSpace(), dataspaceDetails(newDataSpace).c_str(), newDataSpace);
1874             }
1875             newColorMode = pickColorMode(newDataSpace);
1876
1877             // We want the color mode of the boot animation to match that of the bootloader
1878             // To achieve this we suppress color mode changes until after the boot animation
1879             if (mBootFinished) {
1880                 setActiveColorModeInternal(displayDevice, newColorMode);
1881                 displayDevice->setCompositionDataSpace(newDataSpace);
1882             }
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     mLayersPendingRemoval.add(layer);
2794     mLayersRemoved = true;
2795     mNumLayers -= 1 + layer->getChildrenCount();
2796     setTransactionFlags(eTransactionNeeded);
2797     return NO_ERROR;
2798 }
2799
2800 uint32_t SurfaceFlinger::peekTransactionFlags() {
2801     return android_atomic_release_load(&mTransactionFlags);
2802 }
2803
2804 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2805     return android_atomic_and(~flags, &mTransactionFlags) & flags;
2806 }
2807
2808 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2809     uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2810     if ((old & flags)==0) { // wake the server up
2811         signalTransaction();
2812     }
2813     return old;
2814 }
2815
2816 void SurfaceFlinger::setTransactionState(
2817         const Vector<ComposerState>& state,
2818         const Vector<DisplayState>& displays,
2819         uint32_t flags)
2820 {
2821     ATRACE_CALL();
2822     Mutex::Autolock _l(mStateLock);
2823     uint32_t transactionFlags = 0;
2824
2825     if (flags & eAnimation) {
2826         // For window updates that are part of an animation we must wait for
2827         // previous animation "frames" to be handled.
2828         while (mAnimTransactionPending) {
2829             status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2830             if (CC_UNLIKELY(err != NO_ERROR)) {
2831                 // just in case something goes wrong in SF, return to the
2832                 // caller after a few seconds.
2833                 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2834                         "waiting for previous animation frame");
2835                 mAnimTransactionPending = false;
2836                 break;
2837             }
2838         }
2839     }
2840
2841     size_t count = displays.size();
2842     for (size_t i=0 ; i<count ; i++) {
2843         const DisplayState& s(displays[i]);
2844         transactionFlags |= setDisplayStateLocked(s);
2845     }
2846
2847     count = state.size();
2848     for (size_t i=0 ; i<count ; i++) {
2849         const ComposerState& s(state[i]);
2850         // Here we need to check that the interface we're given is indeed
2851         // one of our own. A malicious client could give us a NULL
2852         // IInterface, or one of its own or even one of our own but a
2853         // different type. All these situations would cause us to crash.
2854         //
2855         // NOTE: it would be better to use RTTI as we could directly check
2856         // that we have a Client*. however, RTTI is disabled in Android.
2857         if (s.client != NULL) {
2858             sp<IBinder> binder = IInterface::asBinder(s.client);
2859             if (binder != NULL) {
2860                 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) != NULL) {
2861                     sp<Client> client( static_cast<Client *>(s.client.get()) );
2862                     transactionFlags |= setClientStateLocked(client, s.state);
2863                 }
2864             }
2865         }
2866     }
2867
2868     // If a synchronous transaction is explicitly requested without any changes, force a transaction
2869     // anyway. This can be used as a flush mechanism for previous async transactions.
2870     // Empty animation transaction can be used to simulate back-pressure, so also force a
2871     // transaction for empty animation transactions.
2872     if (transactionFlags == 0 &&
2873             ((flags & eSynchronous) || (flags & eAnimation))) {
2874         transactionFlags = eTransactionNeeded;
2875     }
2876
2877     if (transactionFlags) {
2878         if (mInterceptor.isEnabled()) {
2879             mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2880         }
2881
2882         // this triggers the transaction
2883         setTransactionFlags(transactionFlags);
2884
2885         // if this is a synchronous transaction, wait for it to take effect
2886         // before returning.
2887         if (flags & eSynchronous) {
2888             mTransactionPending = true;
2889         }
2890         if (flags & eAnimation) {
2891             mAnimTransactionPending = true;
2892         }
2893         while (mTransactionPending) {
2894             status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2895             if (CC_UNLIKELY(err != NO_ERROR)) {
2896                 // just in case something goes wrong in SF, return to the
2897                 // called after a few seconds.
2898                 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2899                 mTransactionPending = false;
2900                 break;
2901             }
2902         }
2903     }
2904 }
2905
2906 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2907 {
2908     ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2909     if (dpyIdx < 0)
2910         return 0;
2911
2912     uint32_t flags = 0;
2913     DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2914     if (disp.isValid()) {
2915         const uint32_t what = s.what;
2916         if (what & DisplayState::eSurfaceChanged) {
2917             if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2918                 disp.surface = s.surface;
2919                 flags |= eDisplayTransactionNeeded;
2920             }
2921         }
2922         if (what & DisplayState::eLayerStackChanged) {
2923             if (disp.layerStack != s.layerStack) {
2924                 disp.layerStack = s.layerStack;
2925                 flags |= eDisplayTransactionNeeded;
2926             }
2927         }
2928         if (what & DisplayState::eDisplayProjectionChanged) {
2929             if (disp.orientation != s.orientation) {
2930                 disp.orientation = s.orientation;
2931                 flags |= eDisplayTransactionNeeded;
2932             }
2933             if (disp.frame != s.frame) {
2934                 disp.frame = s.frame;
2935                 flags |= eDisplayTransactionNeeded;
2936             }
2937             if (disp.viewport != s.viewport) {
2938                 disp.viewport = s.viewport;
2939                 flags |= eDisplayTransactionNeeded;
2940             }
2941         }
2942         if (what & DisplayState::eDisplaySizeChanged) {
2943             if (disp.width != s.width) {
2944                 disp.width = s.width;
2945                 flags |= eDisplayTransactionNeeded;
2946             }
2947             if (disp.height != s.height) {
2948                 disp.height = s.height;
2949                 flags |= eDisplayTransactionNeeded;
2950             }
2951         }
2952     }
2953     return flags;
2954 }
2955
2956 uint32_t SurfaceFlinger::setClientStateLocked(
2957         const sp<Client>& client,
2958         const layer_state_t& s)
2959 {
2960     uint32_t flags = 0;
2961     sp<Layer> layer(client->getLayerUser(s.surface));
2962     if (layer != 0) {
2963         const uint32_t what = s.what;
2964         bool geometryAppliesWithResize =
2965                 what & layer_state_t::eGeometryAppliesWithResize;
2966         if (what & layer_state_t::ePositionChanged) {
2967             if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
2968                 flags |= eTraversalNeeded;
2969             }
2970         }
2971         if (what & layer_state_t::eLayerChanged) {
2972             // NOTE: index needs to be calculated before we update the state
2973             const auto& p = layer->getParent();
2974             if (p == nullptr) {
2975                 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2976                 if (layer->setLayer(s.z) && idx >= 0) {
2977                     mCurrentState.layersSortedByZ.removeAt(idx);
2978                     mCurrentState.layersSortedByZ.add(layer);
2979                     // we need traversal (state changed)
2980                     // AND transaction (list changed)
2981                     flags |= eTransactionNeeded|eTraversalNeeded;
2982                 }
2983             } else {
2984                 if (p->setChildLayer(layer, s.z)) {
2985                     flags |= eTransactionNeeded|eTraversalNeeded;
2986                 }
2987             }
2988         }
2989         if (what & layer_state_t::eRelativeLayerChanged) {
2990             if (layer->setRelativeLayer(s.relativeLayerHandle, s.z)) {
2991                 flags |= eTransactionNeeded|eTraversalNeeded;
2992             }
2993         }
2994         if (what & layer_state_t::eSizeChanged) {
2995             if (layer->setSize(s.w, s.h)) {
2996                 flags |= eTraversalNeeded;
2997             }
2998         }
2999         if (what & layer_state_t::eAlphaChanged) {
3000             if (layer->setAlpha(s.alpha))
3001                 flags |= eTraversalNeeded;
3002         }
3003         if (what & layer_state_t::eMatrixChanged) {
3004             if (layer->setMatrix(s.matrix))
3005                 flags |= eTraversalNeeded;
3006         }
3007         if (what & layer_state_t::eTransparentRegionChanged) {
3008             if (layer->setTransparentRegionHint(s.transparentRegion))
3009                 flags |= eTraversalNeeded;
3010         }
3011         if (what & layer_state_t::eFlagsChanged) {
3012             if (layer->setFlags(s.flags, s.mask))
3013                 flags |= eTraversalNeeded;
3014         }
3015         if (what & layer_state_t::eCropChanged) {
3016             if (layer->setCrop(s.crop, !geometryAppliesWithResize))
3017                 flags |= eTraversalNeeded;
3018         }
3019         if (what & layer_state_t::eFinalCropChanged) {
3020             if (layer->setFinalCrop(s.finalCrop, !geometryAppliesWithResize))
3021                 flags |= eTraversalNeeded;
3022         }
3023         if (what & layer_state_t::eLayerStackChanged) {
3024             ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3025             // We only allow setting layer stacks for top level layers,
3026             // everything else inherits layer stack from its parent.
3027             if (layer->hasParent()) {
3028                 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3029                         layer->getName().string());
3030             } else if (idx < 0) {
3031                 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3032                         "that also does not appear in the top level layer list. Something"
3033                         " has gone wrong.", layer->getName().string());
3034             } else if (layer->setLayerStack(s.layerStack)) {
3035                 mCurrentState.layersSortedByZ.removeAt(idx);
3036                 mCurrentState.layersSortedByZ.add(layer);
3037                 // we need traversal (state changed)
3038                 // AND transaction (list changed)
3039                 flags |= eTransactionNeeded|eTraversalNeeded;
3040             }
3041         }
3042         if (what & layer_state_t::eDeferTransaction) {
3043             if (s.barrierHandle != nullptr) {
3044                 layer->deferTransactionUntil(s.barrierHandle, s.frameNumber);
3045             } else if (s.barrierGbp != nullptr) {
3046                 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp;
3047                 if (authenticateSurfaceTextureLocked(gbp)) {
3048                     const auto& otherLayer =
3049                         (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
3050                     layer->deferTransactionUntil(otherLayer, s.frameNumber);
3051                 } else {
3052                     ALOGE("Attempt to defer transaction to to an"
3053                             " unrecognized GraphicBufferProducer");
3054                 }
3055             }
3056             // We don't trigger a traversal here because if no other state is
3057             // changed, we don't want this to cause any more work
3058         }
3059         if (what & layer_state_t::eReparentChildren) {
3060             if (layer->reparentChildren(s.reparentHandle)) {
3061                 flags |= eTransactionNeeded|eTraversalNeeded;
3062             }
3063         }
3064         if (what & layer_state_t::eDetachChildren) {
3065             layer->detachChildren();
3066         }
3067         if (what & layer_state_t::eOverrideScalingModeChanged) {
3068             layer->setOverrideScalingMode(s.overrideScalingMode);
3069             // We don't trigger a traversal here because if no other state is
3070             // changed, we don't want this to cause any more work
3071         }
3072     }
3073     return flags;
3074 }
3075
3076 status_t SurfaceFlinger::createLayer(
3077         const String8& name,
3078         const sp<Client>& client,
3079         uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
3080         uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
3081         sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
3082 {
3083     if (int32_t(w|h) < 0) {
3084         ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
3085                 int(w), int(h));
3086         return BAD_VALUE;
3087     }
3088
3089     status_t result = NO_ERROR;
3090
3091     sp<Layer> layer;
3092
3093     String8 uniqueName = getUniqueLayerName(name);
3094
3095     switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
3096         case ISurfaceComposerClient::eFXSurfaceNormal:
3097             result = createNormalLayer(client,
3098                     uniqueName, w, h, flags, format,
3099                     handle, gbp, &layer);
3100             break;
3101         case ISurfaceComposerClient::eFXSurfaceDim:
3102             result = createDimLayer(client,
3103                     uniqueName, w, h, flags,
3104                     handle, gbp, &layer);
3105             break;
3106         default:
3107             result = BAD_VALUE;
3108             break;
3109     }
3110
3111     if (result != NO_ERROR) {
3112         return result;
3113     }
3114
3115     // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3116     // TODO b/64227542
3117     if (windowType == 441731) {
3118         windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3119         layer->setPrimaryDisplayOnly();
3120     }
3121
3122     layer->setInfo(windowType, ownerUid);
3123
3124     result = addClientLayer(client, *handle, *gbp, layer, *parent);
3125     if (result != NO_ERROR) {
3126         return result;
3127     }
3128     mInterceptor.saveSurfaceCreation(layer);
3129
3130     setTransactionFlags(eTransactionNeeded);
3131     return result;
3132 }
3133
3134 String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3135 {
3136     bool matchFound = true;
3137     uint32_t dupeCounter = 0;
3138
3139     // Tack on our counter whether there is a hit or not, so everyone gets a tag
3140     String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3141
3142     // Loop over layers until we're sure there is no matching name
3143     while (matchFound) {
3144         matchFound = false;
3145         mDrawingState.traverseInZOrder([&](Layer* layer) {
3146             if (layer->getName() == uniqueName) {
3147                 matchFound = true;
3148                 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3149             }
3150         });
3151     }
3152
3153     ALOGD_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(), uniqueName.c_str());
3154
3155     return uniqueName;
3156 }
3157
3158 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
3159         const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
3160         sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
3161 {
3162     // initialize the surfaces
3163     switch (format) {
3164     case PIXEL_FORMAT_TRANSPARENT:
3165     case PIXEL_FORMAT_TRANSLUCENT:
3166         format = PIXEL_FORMAT_RGBA_8888;
3167         break;
3168     case PIXEL_FORMAT_OPAQUE:
3169         format = PIXEL_FORMAT_RGBX_8888;
3170         break;
3171     }
3172
3173     *outLayer = new Layer(this, client, name, w, h, flags);
3174     status_t err = (*outLayer)->setBuffers(w, h, format, flags);
3175     if (err == NO_ERROR) {
3176         *handle = (*outLayer)->getHandle();
3177         *gbp = (*outLayer)->getProducer();
3178     }
3179
3180     ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
3181     return err;
3182 }
3183
3184 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
3185         const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3186         sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
3187 {
3188     *outLayer = new LayerDim(this, client, name, w, h, flags);
3189     *handle = (*outLayer)->getHandle();
3190     *gbp = (*outLayer)->getProducer();
3191     return NO_ERROR;
3192 }
3193
3194 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
3195 {
3196     // called by a client when it wants to remove a Layer
3197     status_t err = NO_ERROR;
3198     sp<Layer> l(client->getLayerUser(handle));
3199     if (l != NULL) {
3200         mInterceptor.saveSurfaceDeletion(l);
3201         err = removeLayer(l);
3202         ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3203                 "error removing layer=%p (%s)", l.get(), strerror(-err));
3204     }
3205     return err;
3206 }
3207
3208 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
3209 {
3210     // called by ~LayerCleaner() when all references to the IBinder (handle)
3211     // are gone
3212     sp<Layer> l = layer.promote();
3213     if (l == nullptr) {
3214         // The layer has already been removed, carry on
3215         return NO_ERROR;
3216     }
3217     // If we have a parent, then we can continue to live as long as it does.
3218     return removeLayer(l, true);
3219 }
3220
3221 // ---------------------------------------------------------------------------
3222
3223 void SurfaceFlinger::onInitializeDisplays() {
3224     // reset screen orientation and use primary layer stack
3225     Vector<ComposerState> state;
3226     Vector<DisplayState> displays;
3227     DisplayState d;
3228     d.what = DisplayState::eDisplayProjectionChanged |
3229              DisplayState::eLayerStackChanged;
3230     d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
3231     d.layerStack = 0;
3232     d.orientation = DisplayState::eOrientationDefault;
3233     d.frame.makeInvalid();
3234     d.viewport.makeInvalid();
3235     d.width = 0;
3236     d.height = 0;
3237     displays.add(d);
3238     setTransactionState(state, displays, 0);
3239     setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL,
3240                          /*stateLockHeld*/ false);
3241
3242     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3243     const nsecs_t period = activeConfig->getVsyncPeriod();
3244     mAnimFrameTracker.setDisplayRefreshPeriod(period);
3245
3246     // Use phase of 0 since phase is not known.
3247     // Use latency of 0, which will snap to the ideal latency.
3248     setCompositorTimingSnapped(0, period, 0);
3249 }
3250
3251 void SurfaceFlinger::initializeDisplays() {
3252     class MessageScreenInitialized : public MessageBase {
3253         SurfaceFlinger* flinger;
3254     public:
3255         explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
3256         virtual bool handler() {
3257             flinger->onInitializeDisplays();
3258             return true;
3259         }
3260     };
3261     sp<MessageBase> msg = new MessageScreenInitialized(this);
3262     postMessageAsync(msg);  // we may be called from main thread, use async message
3263 }
3264
3265 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
3266              int mode, bool stateLockHeld) {
3267     ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
3268             this);
3269     int32_t type = hw->getDisplayType();
3270     int currentMode = hw->getPowerMode();
3271
3272     if (mode == currentMode) {
3273         return;
3274     }
3275
3276     hw->setPowerMode(mode);
3277     if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
3278         ALOGW("Trying to set power mode for virtual display");
3279         return;
3280     }
3281
3282     if (mInterceptor.isEnabled()) {
3283         ConditionalLock lock(mStateLock, !stateLockHeld);
3284         ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
3285         if (idx < 0) {
3286             ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3287             return;
3288         }
3289         mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
3290     }
3291
3292     if (currentMode == HWC_POWER_MODE_OFF) {
3293         // Turn on the display
3294         getHwComposer().setPowerMode(type, mode);
3295         if (type == DisplayDevice::DISPLAY_PRIMARY &&
3296             mode != HWC_POWER_MODE_DOZE_SUSPEND) {
3297             // FIXME: eventthread only knows about the main display right now
3298             mEventThread->onScreenAcquired();
3299             resyncToHardwareVsync(true);
3300         }
3301
3302         mVisibleRegionsDirty = true;
3303         mHasPoweredOff = true;
3304         repaintEverything();
3305
3306         struct sched_param param = {0};
3307         param.sched_priority = 1;
3308         if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3309             ALOGW("Couldn't set SCHED_FIFO on display on");
3310         }
3311     } else if (mode == HWC_POWER_MODE_OFF) {
3312         // Turn off the display
3313         struct sched_param param = {0};
3314         if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3315             ALOGW("Couldn't set SCHED_OTHER on display off");
3316         }
3317
3318         if (type == DisplayDevice::DISPLAY_PRIMARY) {
3319             disableHardwareVsync(true); // also cancels any in-progress resync
3320
3321             // FIXME: eventthread only knows about the main display right now
3322             mEventThread->onScreenReleased();
3323         }
3324
3325         getHwComposer().setPowerMode(type, mode);
3326         mVisibleRegionsDirty = true;
3327         // from this point on, SF will stop drawing on this display
3328     } else if (mode == HWC_POWER_MODE_DOZE ||
3329                mode == HWC_POWER_MODE_NORMAL) {
3330         // Update display while dozing
3331         getHwComposer().setPowerMode(type, mode);
3332         if (type == DisplayDevice::DISPLAY_PRIMARY) {
3333             // FIXME: eventthread only knows about the main display right now
3334             mEventThread->onScreenAcquired();
3335             resyncToHardwareVsync(true);
3336         }
3337     } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3338         // Leave display going to doze
3339         if (type == DisplayDevice::DISPLAY_PRIMARY) {
3340             disableHardwareVsync(true); // also cancels any in-progress resync
3341             // FIXME: eventthread only knows about the main display right now
3342             mEventThread->onScreenReleased();
3343         }
3344         getHwComposer().setPowerMode(type, mode);
3345     } else {
3346         ALOGE("Attempting to set unknown power mode: %d\n", mode);
3347         getHwComposer().setPowerMode(type, mode);
3348     }
3349 }
3350
3351 void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
3352     class MessageSetPowerMode: public MessageBase {
3353         SurfaceFlinger& mFlinger;
3354         sp<IBinder> mDisplay;
3355         int mMode;
3356     public:
3357         MessageSetPowerMode(SurfaceFlinger& flinger,
3358                 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
3359                     mDisplay(disp) { mMode = mode; }
3360         virtual bool handler() {
3361             sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
3362             if (hw == NULL) {
3363                 ALOGE("Attempt to set power mode = %d for null display %p",
3364                         mMode, mDisplay.get());
3365             } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
3366                 ALOGW("Attempt to set power mode = %d for virtual display",
3367                         mMode);
3368             } else {
3369                 mFlinger.setPowerModeInternal(
3370                         hw, mMode, /*stateLockHeld*/ false);
3371             }
3372             return true;
3373         }
3374     };
3375     sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
3376     postMessageSync(msg);
3377 }
3378
3379 // ---------------------------------------------------------------------------
3380
3381 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
3382 {
3383     String8 result;
3384
3385     IPCThreadState* ipc = IPCThreadState::self();
3386     const int pid = ipc->getCallingPid();
3387     const int uid = ipc->getCallingUid();
3388     if ((uid != AID_SHELL) &&
3389             !PermissionCache::checkPermission(sDump, pid, uid)) {
3390         result.appendFormat("Permission Denial: "
3391                 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
3392     } else {
3393         // Try to get the main lock, but give up after one second
3394         // (this would indicate SF is stuck, but we want to be able to
3395         // print something in dumpsys).
3396         status_t err = mStateLock.timedLock(s2ns(1));
3397         bool locked = (err == NO_ERROR);
3398         if (!locked) {
3399             result.appendFormat(
3400                     "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3401                     "dumping anyways (no locks held)\n", strerror(-err), err);
3402         }
3403
3404         bool dumpAll = true;
3405         size_t index = 0;
3406         size_t numArgs = args.size();
3407         if (numArgs) {
3408             if ((index < numArgs) &&
3409                     (args[index] == String16("--list"))) {
3410                 index++;
3411                 listLayersLocked(args, index, result);
3412                 dumpAll = false;
3413             }
3414
3415             if ((index < numArgs) &&
3416                     (args[index] == String16("--latency"))) {
3417                 index++;
3418                 dumpStatsLocked(args, index, result);
3419                 dumpAll = false;
3420             }
3421
3422             if ((index < numArgs) &&
3423                     (args[index] == String16("--latency-clear"))) {
3424                 index++;
3425                 clearStatsLocked(args, index, result);
3426                 dumpAll = false;
3427             }
3428
3429             if ((index < numArgs) &&
3430                     (args[index] == String16("--dispsync"))) {
3431                 index++;
3432                 mPrimaryDispSync.dump(result);
3433                 dumpAll = false;
3434             }
3435
3436             if ((index < numArgs) &&
3437                     (args[index] == String16("--static-screen"))) {
3438                 index++;
3439                 dumpStaticScreenStats(result);
3440                 dumpAll = false;
3441             }
3442
3443             if ((index < numArgs) &&
3444                     (args[index] == String16("--frame-events"))) {
3445                 index++;
3446                 dumpFrameEventsLocked(result);
3447                 dumpAll = false;
3448             }
3449
3450             if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3451                 index++;
3452                 dumpWideColorInfo(result);
3453                 dumpAll = false;
3454             }
3455         }
3456
3457         if (dumpAll) {
3458             dumpAllLocked(args, index, result);
3459         }
3460
3461         if (locked) {
3462             mStateLock.unlock();
3463         }
3464     }
3465     write(fd, result.string(), result.size());
3466     return NO_ERROR;
3467 }
3468
3469 void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
3470         size_t& /* index */, String8& result) const
3471 {
3472     mCurrentState.traverseInZOrder([&](Layer* layer) {
3473         result.appendFormat("%s\n", layer->getName().string());
3474     });
3475 }
3476
3477 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
3478         String8& result) const
3479 {
3480     String8 name;
3481     if (index < args.size()) {
3482         name = String8(args[index]);
3483         index++;
3484     }
3485
3486     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3487     const nsecs_t period = activeConfig->getVsyncPeriod();
3488     result.appendFormat("%" PRId64 "\n", period);
3489
3490     if (name.isEmpty()) {
3491         mAnimFrameTracker.dumpStats(result);
3492     } else {
3493         mCurrentState.traverseInZOrder([&](Layer* layer) {
3494             if (name == layer->getName()) {
3495                 layer->dumpFrameStats(result);
3496             }
3497         });
3498     }
3499 }
3500
3501 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
3502         String8& /* result */)
3503 {
3504     String8 name;
3505     if (index < args.size()) {
3506         name = String8(args[index]);
3507         index++;
3508     }
3509
3510     mCurrentState.traverseInZOrder([&](Layer* layer) {
3511         if (name.isEmpty() || (name == layer->getName())) {
3512             layer->clearFrameStats();
3513         }
3514     });
3515
3516     mAnimFrameTracker.clearStats();
3517 }
3518
3519 // This should only be called from the main thread.  Otherwise it would need
3520 // the lock and should use mCurrentState rather than mDrawingState.
3521 void SurfaceFlinger::logFrameStats() {
3522     mDrawingState.traverseInZOrder([&](Layer* layer) {
3523         layer->logFrameStats();
3524     });
3525
3526     mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3527 }
3528
3529 void SurfaceFlinger::appendSfConfigString(String8& result) const
3530 {
3531     result.append(" [sf");
3532     result.appendFormat(" HAS_CONTEXT_PRIORITY=%d", useContextPriority);
3533
3534     if (isLayerTripleBufferingDisabled())
3535         result.append(" DISABLE_TRIPLE_BUFFERING");
3536
3537     result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
3538     result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
3539     result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
3540     result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
3541     result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3542                         maxFrameBufferAcquiredBuffers);
3543     result.append("]");
3544 }
3545
3546 void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
3547 {
3548     result.appendFormat("Static screen stats:\n");
3549     for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
3550         float bucketTimeSec = mFrameBuckets[b] / 1e9;
3551         float percent = 100.0f *
3552                 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
3553         result.appendFormat("  < %zd frames: %.3f s (%.1f%%)\n",
3554                 b + 1, bucketTimeSec, percent);
3555     }
3556     float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
3557     float percent = 100.0f *
3558             static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
3559     result.appendFormat("  %zd+ frames: %.3f s (%.1f%%)\n",
3560             NUM_BUCKETS - 1, bucketTimeSec, percent);
3561 }
3562
3563 void SurfaceFlinger::recordBufferingStats(const char* layerName,
3564         std::vector<OccupancyTracker::Segment>&& history) {
3565     Mutex::Autolock lock(mBufferingStatsMutex);
3566     auto& stats = mBufferingStats[layerName];
3567     for (const auto& segment : history) {
3568         if (!segment.usedThirdBuffer) {
3569             stats.twoBufferTime += segment.totalTime;
3570         }
3571         if (segment.occupancyAverage < 1.0f) {
3572             stats.doubleBufferedTime += segment.totalTime;
3573         } else if (segment.occupancyAverage < 2.0f) {
3574             stats.tripleBufferedTime += segment.totalTime;
3575         }
3576         ++stats.numSegments;
3577         stats.totalTime += segment.totalTime;
3578     }
3579 }
3580
3581 void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
3582     result.appendFormat("Layer frame timestamps:\n");
3583
3584     const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3585     const size_t count = currentLayers.size();
3586     for (size_t i=0 ; i<count ; i++) {
3587         currentLayers[i]->dumpFrameEvents(result);
3588     }
3589 }
3590
3591 void SurfaceFlinger::dumpBufferingStats(String8& result) const {
3592     result.append("Buffering stats:\n");
3593     result.append("  [Layer name] <Active time> <Two buffer> "
3594             "<Double buffered> <Triple buffered>\n");
3595     Mutex::Autolock lock(mBufferingStatsMutex);
3596     typedef std::tuple<std::string, float, float, float> BufferTuple;
3597     std::map<float, BufferTuple, std::greater<float>> sorted;
3598     for (const auto& statsPair : mBufferingStats) {
3599         const char* name = statsPair.first.c_str();
3600         const BufferingStats& stats = statsPair.second;
3601         if (stats.numSegments == 0) {
3602             continue;
3603         }
3604         float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3605         float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3606                 stats.totalTime;
3607         float doubleBufferRatio = static_cast<float>(
3608                 stats.doubleBufferedTime) / stats.totalTime;
3609         float tripleBufferRatio = static_cast<float>(
3610                 stats.tripleBufferedTime) / stats.totalTime;
3611         sorted.insert({activeTime, {name, twoBufferRatio,
3612                 doubleBufferRatio, tripleBufferRatio}});
3613     }
3614     for (const auto& sortedPair : sorted) {
3615         float activeTime = sortedPair.first;
3616         const BufferTuple& values = sortedPair.second;
3617         result.appendFormat("  [%s] %.2f %.3f %.3f %.3f\n",
3618                 std::get<0>(values).c_str(), activeTime,
3619                 std::get<1>(values), std::get<2>(values),
3620                 std::get<3>(values));
3621     }
3622     result.append("\n");
3623 }
3624
3625 void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
3626     result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
3627
3628     // TODO: print out if wide-color mode is active or not
3629
3630     for (size_t d = 0; d < mDisplays.size(); d++) {
3631         const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3632         int32_t hwcId = displayDevice->getHwcDisplayId();
3633         if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3634             continue;
3635         }
3636
3637         result.appendFormat("Display %d color modes:\n", hwcId);
3638         std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(hwcId);
3639         for (auto&& mode : modes) {
3640             result.appendFormat("    %s (%d)\n", decodeColorMode(mode).c_str(), mode);
3641         }
3642
3643         android_color_mode_t currentMode = displayDevice->getActiveColorMode();
3644         result.appendFormat("    Current color mode: %s (%d)\n",
3645                             decodeColorMode(currentMode).c_str(), currentMode);
3646     }
3647     result.append("\n");
3648 }
3649
3650 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3651         String8& result) const
3652 {
3653     bool colorize = false;
3654     if (index < args.size()
3655             && (args[index] == String16("--color"))) {
3656         colorize = true;
3657         index++;
3658     }
3659
3660     Colorizer colorizer(colorize);
3661
3662     // figure out if we're stuck somewhere
3663     const nsecs_t now = systemTime();
3664     const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3665     const nsecs_t inTransaction(mDebugInTransaction);
3666     nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3667     nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3668
3669     /*
3670      * Dump library configuration.
3671      */
3672
3673     colorizer.bold(result);
3674     result.append("Build configuration:");
3675     colorizer.reset(result);
3676     appendSfConfigString(result);
3677     appendUiConfigString(result);
3678     appendGuiConfigString(result);
3679     result.append("\n");
3680
3681     result.append("\nWide-Color information:\n");
3682     dumpWideColorInfo(result);
3683
3684     colorizer.bold(result);
3685     result.append("Sync configuration: ");
3686     colorizer.reset(result);
3687     result.append(SyncFeatures::getInstance().toString());
3688     result.append("\n");
3689
3690     const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3691
3692     colorizer.bold(result);
3693     result.append("DispSync configuration: ");
3694     colorizer.reset(result);
3695     result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3696             "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
3697         vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3698         dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
3699     result.append("\n");
3700
3701     // Dump static screen stats
3702     result.append("\n");
3703     dumpStaticScreenStats(result);
3704     result.append("\n");
3705
3706     dumpBufferingStats(result);
3707
3708     /*
3709      * Dump the visible layer list
3710      */
3711     colorizer.bold(result);
3712     result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
3713     colorizer.reset(result);
3714     mCurrentState.traverseInZOrder([&](Layer* layer) {
3715         layer->dump(result, colorizer);
3716     });
3717
3718     /*
3719      * Dump Display state
3720      */
3721
3722     colorizer.bold(result);
3723     result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
3724     colorizer.reset(result);
3725     for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3726         const sp<const DisplayDevice>& hw(mDisplays[dpy]);
3727         hw->dump(result);
3728     }
3729
3730     /*
3731      * Dump SurfaceFlinger global state
3732      */
3733
3734     colorizer.bold(result);
3735     result.append("SurfaceFlinger global state:\n");
3736     colorizer.reset(result);
3737
3738     HWComposer& hwc(getHwComposer());
3739     sp<const DisplayDevice> hw(getDefaultDisplayDeviceLocked());
3740
3741     colorizer.bold(result);
3742     result.appendFormat("EGL implementation : %s\n",
3743             eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3744     colorizer.reset(result);
3745     result.appendFormat("%s\n",
3746             eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
3747
3748     mRenderEngine->dump(result);
3749
3750     hw->undefinedRegion.dump(result, "undefinedRegion");
3751     result.appendFormat("  orientation=%d, isDisplayOn=%d\n",
3752             hw->getOrientation(), hw->isDisplayOn());
3753     result.appendFormat(
3754             "  last eglSwapBuffers() time: %f us\n"
3755             "  last transaction time     : %f us\n"
3756             "  transaction-flags         : %08x\n"
3757             "  refresh-rate              : %f fps\n"
3758             "  x-dpi                     : %f\n"
3759             "  y-dpi                     : %f\n"
3760             "  gpu_to_cpu_unsupported    : %d\n"
3761             ,
3762             mLastSwapBufferTime/1000.0,
3763             mLastTransactionTime/1000.0,
3764             mTransactionFlags,
3765             1e9 / activeConfig->getVsyncPeriod(),
3766             activeConfig->getDpiX(),
3767             activeConfig->getDpiY(),
3768             !mGpuToCpuSupported);
3769
3770     result.appendFormat("  eglSwapBuffers time: %f us\n",
3771             inSwapBuffersDuration/1000.0);
3772
3773     result.appendFormat("  transaction time: %f us\n",
3774             inTransactionDuration/1000.0);
3775
3776     /*
3777      * VSYNC state
3778      */
3779     mEventThread->dump(result);
3780     result.append("\n");
3781
3782     /*
3783      * HWC layer minidump
3784      */
3785     for (size_t d = 0; d < mDisplays.size(); d++) {
3786         const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3787         int32_t hwcId = displayDevice->getHwcDisplayId();
3788         if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3789             continue;
3790         }
3791
3792         result.appendFormat("Display %d HWC layers:\n", hwcId);
3793         Layer::miniDumpHeader(result);
3794         mCurrentState.traverseInZOrder([&](Layer* layer) {
3795             layer->miniDump(result, hwcId);
3796         });
3797         result.append("\n");
3798     }
3799
3800     /*
3801      * Dump HWComposer state
3802      */
3803     colorizer.bold(result);
3804     result.append("h/w composer state:\n");
3805     colorizer.reset(result);
3806     bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
3807     result.appendFormat("  h/w composer %s\n",
3808             hwcDisabled ? "disabled" : "enabled");
3809     hwc.dump(result);
3810
3811     /*
3812      * Dump gralloc state
3813      */
3814     const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3815     alloc.dump(result);
3816
3817     /*
3818      * Dump VrFlinger state if in use.
3819      */
3820     if (mVrFlingerRequestsDisplay && mVrFlinger) {
3821         result.append("VrFlinger state:\n");
3822         result.append(mVrFlinger->Dump().c_str());
3823         result.append("\n");
3824     }
3825 }
3826
3827 const Vector< sp<Layer> >&
3828 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
3829     // Note: mStateLock is held here
3830     wp<IBinder> dpy;
3831     for (size_t i=0 ; i<mDisplays.size() ; i++) {
3832         if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3833             dpy = mDisplays.keyAt(i);
3834             break;
3835         }
3836     }
3837     if (dpy == NULL) {
3838         ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3839         // Just use the primary display so we have something to return
3840         dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3841     }
3842     return getDisplayDeviceLocked(dpy)->getVisibleLayersSortedByZ();
3843 }
3844
3845 bool SurfaceFlinger::startDdmConnection()
3846 {
3847     void* libddmconnection_dso =
3848             dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3849     if (!libddmconnection_dso) {
3850         return false;
3851     }
3852     void (*DdmConnection_start)(const char* name);
3853     DdmConnection_start =
3854             (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
3855     if (!DdmConnection_start) {
3856         dlclose(libddmconnection_dso);
3857         return false;
3858     }
3859     (*DdmConnection_start)(getServiceName());
3860     return true;
3861 }
3862
3863 status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
3864     switch (code) {
3865         case CREATE_CONNECTION:
3866         case CREATE_DISPLAY:
3867         case BOOT_FINISHED:
3868         case CLEAR_ANIMATION_FRAME_STATS:
3869         case GET_ANIMATION_FRAME_STATS:
3870         case SET_POWER_MODE:
3871         case GET_HDR_CAPABILITIES:
3872         {
3873             // codes that require permission check
3874             IPCThreadState* ipc = IPCThreadState::self();
3875             const int pid = ipc->getCallingPid();
3876             const int uid = ipc->getCallingUid();
3877             if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3878                     !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3879                 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3880                 return PERMISSION_DENIED;
3881             }
3882             break;
3883         }
3884         /*
3885          * Calling setTransactionState is safe, because you need to have been
3886          * granted a reference to Client* and Handle* to do anything with it.
3887          *
3888          * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
3889          */
3890         case SET_TRANSACTION_STATE:
3891         case CREATE_SCOPED_CONNECTION:
3892         {
3893             return OK;
3894         }
3895         case CAPTURE_SCREEN:
3896         {
3897             // codes that require permission check
3898             IPCThreadState* ipc = IPCThreadState::self();
3899             const int pid = ipc->getCallingPid();
3900             const int uid = ipc->getCallingUid();
3901             if ((uid != AID_GRAPHICS) &&
3902                     !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
3903                 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
3904                 return PERMISSION_DENIED;
3905             }
3906             break;
3907         }
3908     }
3909     return OK;
3910 }
3911
3912 status_t SurfaceFlinger::onTransact(
3913     uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3914 {
3915     status_t credentialCheck = CheckTransactCodeCredentials(code);
3916     if (credentialCheck != OK) {
3917         return credentialCheck;
3918     }
3919
3920     status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3921     if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
3922         CHECK_INTERFACE(ISurfaceComposer, data, reply);
3923         IPCThreadState* ipc = IPCThreadState::self();
3924         const int uid = ipc->getCallingUid();
3925         if (CC_UNLIKELY(uid != AID_SYSTEM
3926                 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
3927             const int pid = ipc->getCallingPid();
3928             ALOGE("Permission Denial: "
3929                     "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3930             return PERMISSION_DENIED;
3931         }
3932         int n;
3933         switch (code) {
3934             case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
3935             case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
3936                 return NO_ERROR;
3937             case 1002:  // SHOW_UPDATES
3938                 n = data.readInt32();
3939                 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
3940                 invalidateHwcGeometry();
3941                 repaintEverything();
3942                 return NO_ERROR;
3943             case 1004:{ // repaint everything
3944                 repaintEverything();
3945                 return NO_ERROR;
3946             }
3947             case 1005:{ // force transaction
3948                 setTransactionFlags(
3949                         eTransactionNeeded|
3950                         eDisplayTransactionNeeded|
3951                         eTraversalNeeded);
3952                 return NO_ERROR;
3953             }
3954             case 1006:{ // send empty update
3955                 signalRefresh();
3956                 return NO_ERROR;
3957             }
3958             case 1008:  // toggle use of hw composer
3959                 n = data.readInt32();
3960                 mDebugDisableHWC = n ? 1 : 0;
3961                 invalidateHwcGeometry();
3962                 repaintEverything();
3963                 return NO_ERROR;
3964             case 1009:  // toggle use of transform hint
3965                 n = data.readInt32();
3966                 mDebugDisableTransformHint = n ? 1 : 0;
3967                 invalidateHwcGeometry();
3968                 repaintEverything();
3969                 return NO_ERROR;
3970             case 1010:  // interrogate.
3971                 reply->writeInt32(0);
3972                 reply->writeInt32(0);
3973                 reply->writeInt32(mDebugRegion);
3974                 reply->writeInt32(0);
3975                 reply->writeInt32(mDebugDisableHWC);
3976                 return NO_ERROR;
3977             case 1013: {
3978                 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3979                 reply->writeInt32(hw->getPageFlipCount());
3980                 return NO_ERROR;
3981             }
3982             case 1014: {
3983                 // daltonize
3984                 n = data.readInt32();
3985                 switch (n % 10) {
3986                     case 1:
3987                         mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3988                         break;
3989                     case 2:
3990                         mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3991                         break;
3992                     case 3:
3993                         mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3994                         break;
3995                     default:
3996                         mDaltonizer.setType(ColorBlindnessType::None);
3997                         break;
3998                 }
3999                 if (n >= 10) {
4000                     mDaltonizer.setMode(ColorBlindnessMode::Correction);
4001                 } else {
4002                     mDaltonizer.setMode(ColorBlindnessMode::Simulation);
4003                 }
4004                 invalidateHwcGeometry();
4005                 repaintEverything();
4006                 return NO_ERROR;
4007             }
4008             case 1015: {
4009                 // apply a color matrix
4010                 n = data.readInt32();
4011                 if (n) {
4012                     // color matrix is sent as a column-major mat4 matrix
4013                     for (size_t i = 0 ; i < 4; i++) {
4014                         for (size_t j = 0; j < 4; j++) {
4015                             mColorMatrix[i][j] = data.readFloat();
4016                         }
4017                     }
4018                 } else {
4019                     mColorMatrix = mat4();
4020                 }
4021
4022                 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4023                 // the division by w in the fragment shader
4024                 float4 lastRow(transpose(mColorMatrix)[3]);
4025                 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4026                     ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4027                 }
4028
4029                 invalidateHwcGeometry();
4030                 repaintEverything();
4031                 return NO_ERROR;
4032             }
4033             // This is an experimental interface
4034             // Needs to be shifted to proper binder interface when we productize
4035             case 1016: {
4036                 n = data.readInt32();
4037                 mPrimaryDispSync.setRefreshSkipCount(n);
4038                 return NO_ERROR;
4039             }
4040             case 1017: {
4041                 n = data.readInt32();
4042                 mForceFullDamage = static_cast<bool>(n);
4043                 return NO_ERROR;
4044             }
4045             case 1018: { // Modify Choreographer's phase offset
4046                 n = data.readInt32();
4047                 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4048                 return NO_ERROR;
4049             }
4050             case 1019: { // Modify SurfaceFlinger's phase offset
4051                 n = data.readInt32();
4052                 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4053                 return NO_ERROR;
4054             }
4055             case 1020: { // Layer updates interceptor
4056                 n = data.readInt32();
4057                 if (n) {
4058                     ALOGV("Interceptor enabled");
4059                     mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
4060                 }
4061                 else{
4062                     ALOGV("Interceptor disabled");
4063                     mInterceptor.disable();
4064                 }
4065                 return NO_ERROR;
4066             }
4067             case 1021: { // Disable HWC virtual displays
4068                 n = data.readInt32();
4069                 mUseHwcVirtualDisplays = !n;
4070                 return NO_ERROR;
4071             }
4072             case 1022: { // Set saturation boost
4073                 mSaturation = std::max(0.0f, std::min(data.readFloat(), 2.0f));
4074
4075                 invalidateHwcGeometry();
4076                 repaintEverything();
4077                 return NO_ERROR;
4078             }
4079         }
4080     }
4081     return err;
4082 }
4083
4084 void SurfaceFlinger::repaintEverything() {
4085     android_atomic_or(1, &mRepaintEverything);
4086     signalTransaction();
4087 }
4088
4089 // Checks that the requested width and height are valid and updates them to the display dimensions
4090 // if they are set to 0
4091 static status_t updateDimensionsLocked(const sp<const DisplayDevice>& displayDevice,
4092                                        Transform::orientation_flags rotation,
4093                                        uint32_t* requestedWidth, uint32_t* requestedHeight) {
4094     // get screen geometry
4095     uint32_t displayWidth = displayDevice->getWidth();
4096     uint32_t displayHeight = displayDevice->getHeight();
4097
4098     if (rotation & Transform::ROT_90) {
4099         std::swap(displayWidth, displayHeight);
4100     }
4101
4102     if ((*requestedWidth > displayWidth) || (*requestedHeight > displayHeight)) {
4103         ALOGE("size mismatch (%d, %d) > (%d, %d)",
4104                 *requestedWidth, *requestedHeight, displayWidth, displayHeight);
4105         return BAD_VALUE;
4106     }
4107
4108     if (*requestedWidth == 0) {
4109         *requestedWidth = displayWidth;
4110     }
4111     if (*requestedHeight == 0) {
4112         *requestedHeight = displayHeight;
4113     }
4114
4115     return NO_ERROR;
4116 }
4117
4118 // A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4119 class WindowDisconnector {
4120 public:
4121     WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4122     ~WindowDisconnector() {
4123         native_window_api_disconnect(mWindow, mApi);
4124     }
4125
4126 private:
4127     ANativeWindow* mWindow;
4128     const int mApi;
4129 };
4130
4131 static status_t getWindowBuffer(ANativeWindow* window, uint32_t requestedWidth,
4132                                 uint32_t requestedHeight, bool hasWideColorDisplay,
4133                                 bool renderEngineUsesWideColor, ANativeWindowBuffer** outBuffer) {
4134     const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
4135             GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
4136
4137     int err = 0;
4138     err = native_window_set_buffers_dimensions(window, requestedWidth, requestedHeight);
4139     err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
4140     err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
4141     err |= native_window_set_usage(window, usage);
4142
4143     if (hasWideColorDisplay) {
4144         err |= native_window_set_buffers_data_space(window,
4145                                                     renderEngineUsesWideColor
4146                                                             ? HAL_DATASPACE_DISPLAY_P3
4147                                                             : HAL_DATASPACE_V0_SRGB);
4148     }
4149
4150     if (err != NO_ERROR) {
4151         return BAD_VALUE;
4152     }
4153
4154     /* TODO: Once we have the sync framework everywhere this can use
4155      * server-side waits on the fence that dequeueBuffer returns.
4156      */
4157     err = native_window_dequeue_buffer_and_wait(window, outBuffer);
4158     if (err != NO_ERROR) {
4159         return err;
4160     }
4161
4162     return NO_ERROR;
4163 }
4164
4165 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
4166         const sp<IGraphicBufferProducer>& producer,
4167         Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4168         int32_t minLayerZ, int32_t maxLayerZ,
4169         bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
4170     ATRACE_CALL();
4171
4172     if (CC_UNLIKELY(display == 0))
4173         return BAD_VALUE;
4174
4175     if (CC_UNLIKELY(producer == 0))
4176         return BAD_VALUE;
4177
4178     // if we have secure windows on this display, never allow the screen capture
4179     // unless the producer interface is local (i.e.: we can take a screenshot for
4180     // ourselves).
4181     bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
4182
4183     // Convert to surfaceflinger's internal rotation type.
4184     Transform::orientation_flags rotationFlags;
4185     switch (rotation) {
4186         case ISurfaceComposer::eRotateNone:
4187             rotationFlags = Transform::ROT_0;
4188             break;
4189         case ISurfaceComposer::eRotate90:
4190             rotationFlags = Transform::ROT_90;
4191             break;
4192         case ISurfaceComposer::eRotate180:
4193             rotationFlags = Transform::ROT_180;
4194             break;
4195         case ISurfaceComposer::eRotate270:
4196             rotationFlags = Transform::ROT_270;
4197             break;
4198         default:
4199             rotationFlags = Transform::ROT_0;
4200             ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
4201             break;
4202     }
4203
4204     { // Autolock scope
4205         Mutex::Autolock lock(mStateLock);
4206         sp<const DisplayDevice> displayDevice(getDisplayDeviceLocked(display));
4207         updateDimensionsLocked(displayDevice, rotationFlags, &reqWidth, &reqHeight);
4208     }
4209
4210     // create a surface (because we're a producer, and we need to
4211     // dequeue/queue a buffer)
4212     sp<Surface> surface = new Surface(producer, false);
4213
4214     // Put the screenshot Surface into async mode so that
4215     // Layer::headFenceHasSignaled will always return true and we'll latch the
4216     // first buffer regardless of whether or not its acquire fence has
4217     // signaled. This is needed to avoid a race condition in the rotation
4218     // animation. See b/30209608
4219     surface->setAsyncMode(true);
4220
4221     ANativeWindow* window = surface.get();
4222
4223     status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
4224     if (result != NO_ERROR) {
4225         return result;
4226     }
4227     WindowDisconnector disconnector(window, NATIVE_WINDOW_API_EGL);
4228
4229     ANativeWindowBuffer* buffer = nullptr;
4230     result = getWindowBuffer(window, reqWidth, reqHeight, hasWideColorDisplay,
4231                                       getRenderEngine().usesWideColor(), &buffer);
4232     if (result != NO_ERROR) {
4233         return result;
4234     }
4235
4236     // This mutex protects syncFd and captureResult for communication of the return values from the
4237     // main thread back to this Binder thread
4238     std::mutex captureMutex;
4239     std::condition_variable captureCondition;
4240     std::unique_lock<std::mutex> captureLock(captureMutex);
4241     int syncFd = -1;
4242     std::optional<status_t> captureResult;
4243
4244     sp<LambdaMessage> message = new LambdaMessage([&]() {
4245         // If there is a refresh pending, bug out early and tell the binder thread to try again
4246         // after the refresh.
4247         if (mRefreshPending) {
4248             ATRACE_NAME("Skipping screenshot for now");
4249             std::unique_lock<std::mutex> captureLock(captureMutex);
4250             captureResult = std::make_optional<status_t>(EAGAIN);
4251             captureCondition.notify_one();
4252             return;
4253         }
4254
4255         status_t result = NO_ERROR;
4256         int fd = -1;
4257         {
4258             Mutex::Autolock _l(mStateLock);
4259             sp<const DisplayDevice> device(getDisplayDeviceLocked(display));
4260             result = captureScreenImplLocked(device, buffer, sourceCrop, reqWidth, reqHeight,
4261                                              minLayerZ, maxLayerZ, useIdentityTransform,
4262                                              rotationFlags, isLocalScreenshot, &fd);
4263         }
4264
4265         {
4266             std::unique_lock<std::mutex> captureLock(captureMutex);
4267             syncFd = fd;
4268             captureResult = std::make_optional<status_t>(result);
4269             captureCondition.notify_one();
4270         }
4271     });
4272
4273     result = postMessageAsync(message);
4274     if (result == NO_ERROR) {
4275         captureCondition.wait(captureLock, [&]() { return captureResult; });
4276         while (*captureResult == EAGAIN) {
4277             captureResult.reset();
4278             result = postMessageAsync(message);
4279             if (result != NO_ERROR) {
4280                 return result;
4281             }
4282             captureCondition.wait(captureLock, [&]() { return captureResult; });
4283         }
4284         result = *captureResult;
4285     }
4286
4287     if (result == NO_ERROR) {
4288         // queueBuffer takes ownership of syncFd
4289         result = window->queueBuffer(window, buffer, syncFd);
4290     }
4291
4292     return result;
4293 }
4294
4295
4296 void SurfaceFlinger::renderScreenImplLocked(
4297         const sp<const DisplayDevice>& hw,
4298         Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
4299         int32_t minLayerZ, int32_t maxLayerZ,
4300         bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
4301 {
4302     ATRACE_CALL();
4303     RenderEngine& engine(getRenderEngine());
4304
4305     // get screen geometry
4306     const int32_t hw_w = hw->getWidth();
4307     const int32_t hw_h = hw->getHeight();
4308     const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
4309                            static_cast<int32_t>(reqHeight) != hw_h;
4310
4311     // if a default or invalid sourceCrop is passed in, set reasonable values
4312     if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
4313             !sourceCrop.isValid()) {
4314         sourceCrop.setLeftTop(Point(0, 0));
4315         sourceCrop.setRightBottom(Point(hw_w, hw_h));
4316     }
4317
4318     // ensure that sourceCrop is inside screen
4319     if (sourceCrop.left < 0) {
4320         ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
4321     }
4322     if (sourceCrop.right > hw_w) {
4323         ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
4324     }
4325     if (sourceCrop.top < 0) {
4326         ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
4327     }
4328     if (sourceCrop.bottom > hw_h) {
4329         ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
4330     }
4331
4332 #ifdef USE_HWC2
4333      engine.setWideColor(hw->getWideColorSupport());
4334      engine.setColorMode(hw->getActiveColorMode());
4335 #endif
4336
4337     // make sure to clear all GL error flags
4338     engine.checkErrors();
4339
4340     // set-up our viewport
4341     engine.setViewportAndProjection(
4342         reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
4343     engine.disableTexturing();
4344
4345     // redraw the screen entirely...
4346     engine.clearWithColor(0, 0, 0, 1);
4347
4348     // We loop through the first level of layers without traversing,
4349     // as we need to interpret min/max layer Z in the top level Z space.
4350     for (const auto& layer : mDrawingState.layersSortedByZ) {
4351         if (!layer->belongsToDisplay(hw->getLayerStack(), false)) {
4352             continue;
4353         }
4354         const Layer::State& state(layer->getDrawingState());
4355         if (state.z < minLayerZ || state.z > maxLayerZ) {
4356             continue;
4357         }
4358         layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4359             if (!layer->isVisible()) {
4360                 return;
4361             }
4362             if (filtering) layer->setFiltering(true);
4363             layer->draw(hw, useIdentityTransform);
4364             if (filtering) layer->setFiltering(false);
4365         });
4366     }
4367
4368     hw->setViewportAndProjection();
4369 }
4370
4371 // A simple RAII class that holds an EGLImage and destroys it either:
4372 //   a) When the destroy() method is called
4373 //   b) When the object goes out of scope
4374 class ImageHolder {
4375 public:
4376     ImageHolder(EGLDisplay display, EGLImageKHR image) : mDisplay(display), mImage(image) {}
4377     ~ImageHolder() { destroy(); }
4378
4379     void destroy() {
4380         if (mImage != EGL_NO_IMAGE_KHR) {
4381             eglDestroyImageKHR(mDisplay, mImage);
4382             mImage = EGL_NO_IMAGE_KHR;
4383         }
4384     }
4385
4386 private:
4387     const EGLDisplay mDisplay;
4388     EGLImageKHR mImage;
4389 };
4390
4391 status_t SurfaceFlinger::captureScreenImplLocked(const sp<const DisplayDevice>& hw,
4392                                                  ANativeWindowBuffer* buffer, Rect sourceCrop,
4393                                                  uint32_t reqWidth, uint32_t reqHeight,
4394                                                  int32_t minLayerZ, int32_t maxLayerZ,
4395                                                  bool useIdentityTransform,
4396                                                  Transform::orientation_flags rotation,
4397                                                  bool isLocalScreenshot, int* outSyncFd) {
4398     ATRACE_CALL();
4399
4400     bool secureLayerIsVisible = false;
4401     for (const auto& layer : mDrawingState.layersSortedByZ) {
4402         const Layer::State& state(layer->getDrawingState());
4403         if (!layer->belongsToDisplay(hw->getLayerStack(), false) ||
4404                 (state.z < minLayerZ || state.z > maxLayerZ)) {
4405             continue;
4406         }
4407         layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer *layer) {
4408             secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() &&
4409                     layer->isSecure());
4410         });
4411     }
4412
4413     if (!isLocalScreenshot && secureLayerIsVisible) {
4414         ALOGW("FB is protected: PERMISSION_DENIED");
4415         return PERMISSION_DENIED;
4416     }
4417
4418     int syncFd = -1;
4419     // create an EGLImage from the buffer so we can later
4420     // turn it into a texture
4421     EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
4422             EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
4423     if (image == EGL_NO_IMAGE_KHR) {
4424         return BAD_VALUE;
4425     }
4426
4427     // This will automatically destroy the image if we return before calling its destroy method
4428     ImageHolder imageHolder(mEGLDisplay, image);
4429
4430     // this binds the given EGLImage as a framebuffer for the
4431     // duration of this scope.
4432     RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
4433     if (imageBond.getStatus() != NO_ERROR) {
4434         ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
4435         return INVALID_OPERATION;
4436     }
4437
4438     // this will in fact render into our dequeued buffer
4439     // via an FBO, which means we didn't have to create
4440     // an EGLSurface and therefore we're not
4441     // dependent on the context's EGLConfig.
4442     renderScreenImplLocked(
4443         hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
4444         useIdentityTransform, rotation);
4445
4446     // Attempt to create a sync khr object that can produce a sync point. If that
4447     // isn't available, create a non-dupable sync object in the fallback path and
4448     // wait on it directly.
4449     EGLSyncKHR sync = EGL_NO_SYNC_KHR;
4450     if (!DEBUG_SCREENSHOTS) {
4451        sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
4452        // native fence fd will not be populated until flush() is done.
4453        getRenderEngine().flush();
4454     }
4455
4456     if (sync != EGL_NO_SYNC_KHR) {
4457         // get the sync fd
4458         syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
4459         if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
4460             ALOGW("captureScreen: failed to dup sync khr object");
4461             syncFd = -1;
4462         }
4463         eglDestroySyncKHR(mEGLDisplay, sync);
4464     } else {
4465         // fallback path
4466         sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
4467         if (sync != EGL_NO_SYNC_KHR) {
4468             EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
4469                 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
4470             EGLint eglErr = eglGetError();
4471             if (result == EGL_TIMEOUT_EXPIRED_KHR) {
4472                 ALOGW("captureScreen: fence wait timed out");
4473             } else {
4474                 ALOGW_IF(eglErr != EGL_SUCCESS,
4475                         "captureScreen: error waiting on EGL fence: %#x", eglErr);
4476             }
4477             eglDestroySyncKHR(mEGLDisplay, sync);
4478         } else {
4479             ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
4480         }
4481     }
4482     *outSyncFd = syncFd;
4483
4484     if (DEBUG_SCREENSHOTS) {
4485         uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
4486         getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
4487         checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
4488                 hw, minLayerZ, maxLayerZ);
4489         delete [] pixels;
4490     }
4491
4492     // destroy our image
4493     imageHolder.destroy();
4494
4495     return NO_ERROR;
4496 }
4497
4498 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
4499         const sp<const DisplayDevice>& hw, int32_t minLayerZ, int32_t maxLayerZ) {
4500     if (DEBUG_SCREENSHOTS) {
4501         for (size_t y=0 ; y<h ; y++) {
4502             uint32_t const * p = (uint32_t const *)vaddr + y*s;
4503             for (size_t x=0 ; x<w ; x++) {
4504                 if (p[x] != 0xFF000000) return;
4505             }
4506         }
4507         ALOGE("*** we just took a black screenshot ***\n"
4508                 "requested minz=%d, maxz=%d, layerStack=%d",
4509                 minLayerZ, maxLayerZ, hw->getLayerStack());
4510
4511         size_t i = 0;
4512         for (const auto& layer : mDrawingState.layersSortedByZ) {
4513             const Layer::State& state(layer->getDrawingState());
4514             if (layer->belongsToDisplay(hw->getLayerStack(), false) && state.z >= minLayerZ &&
4515                     state.z <= maxLayerZ) {
4516                 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4517                     ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
4518                             layer->isVisible() ? '+' : '-',
4519                             i, layer->getName().string(), layer->getLayerStack(), state.z,
4520                             layer->isVisible(), state.flags, state.alpha);
4521                     i++;
4522                 });
4523             }
4524         }
4525     }
4526 }
4527
4528 // ---------------------------------------------------------------------------
4529
4530 void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
4531     layersSortedByZ.traverseInZOrder(stateSet, visitor);
4532 }
4533
4534 void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
4535     layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
4536 }
4537
4538 }; // namespace android
4539
4540
4541 #if defined(__gl_h_)
4542 #error "don't include gl/gl.h in this file"
4543 #endif
4544
4545 #if defined(__gl2_h_)
4546 #error "don't include gl2/gl2.h in this file"
4547 #endif