OSDN Git Service

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