OSDN Git Service

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