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 #pragma once
18 
19 #include <sys/types.h>
20 
21 /*
22  * NOTE: Make sure this file doesn't include  anything from <gl/ > or <gl2/ >
23  */
24 
25 #include <android-base/thread_annotations.h>
26 #include <cutils/atomic.h>
27 #include <cutils/compiler.h>
28 #include <gui/BufferQueue.h>
29 #include <gui/FrameTimestamps.h>
30 #include <gui/ISurfaceComposer.h>
31 #include <gui/ISurfaceComposerClient.h>
32 #include <gui/LayerState.h>
33 #include <gui/OccupancyTracker.h>
34 #include <hardware/hwcomposer_defs.h>
35 #include <input/ISetInputWindowsListener.h>
36 #include <layerproto/LayerProtoHeader.h>
37 #include <math/mat4.h>
38 #include <serviceutils/PriorityDumper.h>
39 #include <system/graphics.h>
40 #include <ui/FenceTime.h>
41 #include <ui/PixelFormat.h>
42 #include <utils/Errors.h>
43 #include <utils/KeyedVector.h>
44 #include <utils/RefBase.h>
45 #include <utils/SortedVector.h>
46 #include <utils/Trace.h>
47 #include <utils/threads.h>
48 
49 #include "ClientCache.h"
50 #include "DisplayDevice.h"
51 #include "DisplayHardware/HWC2.h"
52 #include "DisplayHardware/PowerAdvisor.h"
53 #include "Effects/Daltonizer.h"
54 #include "FrameTracker.h"
55 #include "LayerStats.h"
56 #include "LayerVector.h"
57 #include "Scheduler/RefreshRateConfigs.h"
58 #include "Scheduler/RefreshRateStats.h"
59 #include "Scheduler/Scheduler.h"
60 #include "Scheduler/VSyncModulator.h"
61 #include "SurfaceFlingerFactory.h"
62 #include "SurfaceTracing.h"
63 #include "TransactionCompletedThread.h"
64 
65 #include <atomic>
66 #include <cstdint>
67 #include <functional>
68 #include <map>
69 #include <memory>
70 #include <mutex>
71 #include <queue>
72 #include <set>
73 #include <string>
74 #include <thread>
75 #include <type_traits>
76 #include <unordered_map>
77 #include <unordered_set>
78 #include <utility>
79 
80 using namespace android::surfaceflinger;
81 
82 namespace android {
83 
84 class Client;
85 class EventThread;
86 class HWComposer;
87 class IGraphicBufferProducer;
88 class IInputFlinger;
89 class InjectVSyncSource;
90 class Layer;
91 class MessageBase;
92 class RefreshRateOverlay;
93 class RegionSamplingThread;
94 class TimeStats;
95 
96 namespace compositionengine {
97 class DisplaySurface;
98 } // namespace compositionengine
99 
100 namespace renderengine {
101 class RenderEngine;
102 } // namespace renderengine
103 
104 namespace dvr {
105 class VrFlinger;
106 } // namespace dvr
107 
108 enum {
109     eTransactionNeeded = 0x01,
110     eTraversalNeeded = 0x02,
111     eDisplayTransactionNeeded = 0x04,
112     eDisplayLayerStackChanged = 0x08,
113     eTransactionFlushNeeded = 0x10,
114     eTransactionMask = 0x1f,
115 };
116 
117 enum class DisplayColorSetting : int32_t {
118     MANAGED = 0,
119     UNMANAGED = 1,
120     ENHANCED = 2,
121 };
122 
123 class SurfaceFlingerBE
124 {
125 public:
126     SurfaceFlingerBE();
127 
128     const std::string mHwcServiceName; // "default" for real use, something else for testing.
129 
130     FenceTimeline mGlCompositionDoneTimeline;
131     FenceTimeline mDisplayTimeline;
132 
133     // protected by mCompositorTimingLock;
134     mutable std::mutex mCompositorTimingLock;
135     CompositorTiming mCompositorTiming;
136 
137     // Only accessed from the main thread.
138     struct CompositePresentTime {
139         nsecs_t composite = -1;
140         std::shared_ptr<FenceTime> display = FenceTime::NO_FENCE;
141     };
142     std::queue<CompositePresentTime> mCompositePresentTimes;
143 
144     static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
145     nsecs_t mFrameBuckets[NUM_BUCKETS] = {};
146     nsecs_t mTotalTime = 0;
147     std::atomic<nsecs_t> mLastSwapTime = 0;
148 
149     // Double- vs. triple-buffering stats
150     struct BufferingStats {
151         size_t numSegments = 0;
152         nsecs_t totalTime = 0;
153 
154         // "Two buffer" means that a third buffer was never used, whereas
155         // "double-buffered" means that on average the segment only used two
156         // buffers (though it may have used a third for some part of the
157         // segment)
158         nsecs_t twoBufferTime = 0;
159         nsecs_t doubleBufferedTime = 0;
160         nsecs_t tripleBufferedTime = 0;
161     };
162     mutable Mutex mBufferingStatsMutex;
163     std::unordered_map<std::string, BufferingStats> mBufferingStats;
164 
165     // The composer sequence id is a monotonically increasing integer that we
166     // use to differentiate callbacks from different hardware composer
167     // instances. Each hardware composer instance gets a different sequence id.
168     int32_t mComposerSequenceId = 0;
169 };
170 
171 class SurfaceFlinger : public BnSurfaceComposer,
172                        public PriorityDumper,
173                        public ClientCache::ErasedRecipient,
174                        private IBinder::DeathRecipient,
175                        private HWC2::ComposerCallback {
176 public:
getBE()177     SurfaceFlingerBE& getBE() { return mBE; }
getBE()178     const SurfaceFlingerBE& getBE() const { return mBE; }
179 
180     // This is the phase offset in nanoseconds of the software vsync event
181     // relative to the vsync event reported by HWComposer.  The software vsync
182     // event is when SurfaceFlinger and Choreographer-based applications run each
183     // frame.
184     //
185     // This phase offset allows adjustment of the minimum latency from application
186     // wake-up time (by Choreographer) to the time at which the resulting window
187     // image is displayed.  This value may be either positive (after the HW vsync)
188     // or negative (before the HW vsync). Setting it to 0 will result in a lower
189     // latency bound of two vsync periods because the app and SurfaceFlinger
190     // will run just after the HW vsync.  Setting it to a positive number will
191     // result in the minimum latency being:
192     //
193     //     (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
194     //
195     // Note that reducing this latency makes it more likely for the applications
196     // to not have their window content image ready in time.  When this happens
197     // the latency will end up being an additional vsync period, and animations
198     // will hiccup.  Therefore, this latency should be tuned somewhat
199     // conservatively (or at least with awareness of the trade-off being made).
200     static int64_t vsyncPhaseOffsetNs;
201     static int64_t sfVsyncPhaseOffsetNs;
202 
203     // If fences from sync Framework are supported.
204     static bool hasSyncFramework;
205 
206     // The offset in nanoseconds to use when DispSync timestamps present fence
207     // signaling time.
208     static int64_t dispSyncPresentTimeOffset;
209 
210     // Some hardware can do RGB->YUV conversion more efficiently in hardware
211     // controlled by HWC than in hardware controlled by the video encoder.
212     // This instruct VirtualDisplaySurface to use HWC for such conversion on
213     // GL composition.
214     static bool useHwcForRgbToYuv;
215 
216     // Maximum dimension supported by HWC for virtual display.
217     // Equal to min(max_height, max_width).
218     static uint64_t maxVirtualDisplaySize;
219 
220     // Controls the number of buffers SurfaceFlinger will allocate for use in
221     // FramebufferSurface
222     static int64_t maxFrameBufferAcquiredBuffers;
223 
224     // Indicate if a device has wide color gamut display. This is typically
225     // found on devices with wide color gamut (e.g. Display-P3) display.
226     static bool hasWideColorDisplay;
227 
228     static int primaryDisplayOrientation;
229 
230     // Indicate if device wants color management on its display.
231     static bool useColorManagement;
232 
233     static bool useContextPriority;
234 
235     // The data space and pixel format that SurfaceFlinger expects hardware composer
236     // to composite efficiently. Meaning under most scenarios, hardware composer
237     // will accept layers with the data space and pixel format.
238     static ui::Dataspace defaultCompositionDataspace;
239     static ui::PixelFormat defaultCompositionPixelFormat;
240 
241     // The data space and pixel format that SurfaceFlinger expects hardware composer
242     // to composite efficiently for wide color gamut surfaces. Meaning under most scenarios,
243     // hardware composer will accept layers with the data space and pixel format.
244     static ui::Dataspace wideColorGamutCompositionDataspace;
245     static ui::PixelFormat wideColorGamutCompositionPixelFormat;
246 
getServiceName()247     static char const* getServiceName() ANDROID_API {
248         return "SurfaceFlinger";
249     }
250 
251     struct SkipInitializationTag {};
252     static constexpr SkipInitializationTag SkipInitialization;
253     SurfaceFlinger(surfaceflinger::Factory&, SkipInitializationTag) ANDROID_API;
254     explicit SurfaceFlinger(surfaceflinger::Factory&) ANDROID_API;
255 
256     // must be called before clients can connect
257     void init() ANDROID_API;
258 
259     // starts SurfaceFlinger main loop in the current thread
260     void run() ANDROID_API;
261 
262     // post an asynchronous message to the main thread
263     status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
264 
265     // post a synchronous message to the main thread
266     status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0)
267             EXCLUDES(mStateLock);
268 
269     // force full composition on all displays
270     void repaintEverything();
271 
272     // force full composition on all displays without resetting the scheduler idle timer.
273     void repaintEverythingForHWC();
274 
getFactory()275     surfaceflinger::Factory& getFactory() { return mFactory; }
276 
277     // The CompositionEngine encapsulates all composition related interfaces and actions.
278     compositionengine::CompositionEngine& getCompositionEngine() const;
279 
280     // returns the default Display
getDefaultDisplayDevice()281     sp<const DisplayDevice> getDefaultDisplayDevice() {
282         Mutex::Autolock _l(mStateLock);
283         return getDefaultDisplayDeviceLocked();
284     }
285 
286     // Obtains a name from the texture pool, or, if the pool is empty, posts a
287     // synchronous message to the main thread to obtain one on the fly
288     uint32_t getNewTexture();
289 
290     // utility function to delete a texture on the main thread
291     void deleteTextureAsync(uint32_t texture);
292 
293     // enable/disable h/w composer event
294     // TODO: this should be made accessible only to EventThread
295     void setPrimaryVsyncEnabled(bool enabled);
296 
297     // main thread function to enable/disable h/w composer event
298     void setPrimaryVsyncEnabledInternal(bool enabled);
299 
300     // called on the main thread by MessageQueue when an internal message
301     // is received
302     // TODO: this should be made accessible only to MessageQueue
303     void onMessageReceived(int32_t what);
304 
305     // populates the expected present time for this frame.
306     // When we are in negative offsets, we perform a correction so that the
307     // predicted vsync for the *next* frame is used instead.
308     void populateExpectedPresentTime();
getExpectedPresentTime()309     nsecs_t getExpectedPresentTime() const { return mExpectedPresentTime; }
310 
311     // for debugging only
312     // TODO: this should be made accessible only to HWComposer
313     const Vector<sp<Layer>>& getLayerSortedByZForHwcDisplay(DisplayId displayId);
314 
315     renderengine::RenderEngine& getRenderEngine() const;
316 
317     bool authenticateSurfaceTextureLocked(
318         const sp<IGraphicBufferProducer>& bufferProducer) const;
319 
onLayerCreated()320     inline void onLayerCreated() { mNumLayers++; }
onLayerDestroyed(Layer * layer)321     inline void onLayerDestroyed(Layer* layer) {
322         mNumLayers--;
323         mOffscreenLayers.erase(layer);
324     }
325 
getTransactionCompletedThread()326     TransactionCompletedThread& getTransactionCompletedThread() {
327         return mTransactionCompletedThread;
328     }
329 
330     sp<Layer> fromHandle(const sp<IBinder>& handle) REQUIRES(mStateLock);
331 
332     // Inherit from ClientCache::ErasedRecipient
333     void bufferErased(const client_cache_t& clientCacheId) override;
334 
335 private:
336     friend class BufferLayer;
337     friend class BufferQueueLayer;
338     friend class BufferStateLayer;
339     friend class Client;
340     friend class Layer;
341     friend class MonitoredProducer;
342     friend class RefreshRateOverlay;
343     friend class RegionSamplingThread;
344     friend class SurfaceTracing;
345 
346     // For unit tests
347     friend class TestableSurfaceFlinger;
348 
349     // This value is specified in number of frames.  Log frame stats at most
350     // every half hour.
351     enum { LOG_FRAME_STATS_PERIOD =  30*60*60 };
352 
353     static const size_t MAX_LAYERS = 4096;
354     static const int MAX_TRACING_MEMORY = 100 * 1024 * 1024; // 100MB
355 
356     // We're reference counted, never destroy SurfaceFlinger directly
357     virtual ~SurfaceFlinger();
358 
359     /* ------------------------------------------------------------------------
360      * Internal data structures
361      */
362 
363     class State {
364     public:
State(LayerVector::StateSet set)365         explicit State(LayerVector::StateSet set) : stateSet(set), layersSortedByZ(set) {}
366         State& operator=(const State& other) {
367             // We explicitly don't copy stateSet so that, e.g., mDrawingState
368             // always uses the Drawing StateSet.
369             layersSortedByZ = other.layersSortedByZ;
370             displays = other.displays;
371             colorMatrixChanged = other.colorMatrixChanged;
372             if (colorMatrixChanged) {
373                 colorMatrix = other.colorMatrix;
374             }
375             return *this;
376         }
377 
378         const LayerVector::StateSet stateSet = LayerVector::StateSet::Invalid;
379         LayerVector layersSortedByZ;
380         DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
381 
382         bool colorMatrixChanged = true;
383         mat4 colorMatrix;
384 
385         void traverseInZOrder(const LayerVector::Visitor& visitor) const;
386         void traverseInReverseZOrder(const LayerVector::Visitor& visitor) const;
387     };
388 
389     /* ------------------------------------------------------------------------
390      * IBinder interface
391      */
392     status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) override;
dump(int fd,const Vector<String16> & args)393     status_t dump(int fd, const Vector<String16>& args) override { return priorityDump(fd, args); }
394     bool callingThreadHasUnscopedSurfaceFlingerAccess() EXCLUDES(mStateLock);
395 
396     /* ------------------------------------------------------------------------
397      * ISurfaceComposer interface
398      */
399     sp<ISurfaceComposerClient> createConnection() override;
400     sp<IBinder> createDisplay(const String8& displayName, bool secure) override;
401     void destroyDisplay(const sp<IBinder>& displayToken) override;
402     std::vector<PhysicalDisplayId> getPhysicalDisplayIds() const override;
403     sp<IBinder> getPhysicalDisplayToken(PhysicalDisplayId displayId) const override;
404     void setTransactionState(const Vector<ComposerState>& state,
405                              const Vector<DisplayState>& displays, uint32_t flags,
406                              const sp<IBinder>& applyToken,
407                              const InputWindowCommands& inputWindowCommands,
408                              int64_t desiredPresentTime, const client_cache_t& uncacheBuffer,
409                              const std::vector<ListenerCallbacks>& listenerCallbacks) override;
410     void bootFinished() override;
411     bool authenticateSurfaceTexture(
412             const sp<IGraphicBufferProducer>& bufferProducer) const override;
413     status_t getSupportedFrameTimestamps(std::vector<FrameEvent>* outSupported) const override;
414     sp<IDisplayEventConnection> createDisplayEventConnection(
415             ISurfaceComposer::VsyncSource vsyncSource = eVsyncSourceApp,
416             ISurfaceComposer::ConfigChanged configChanged =
417                     ISurfaceComposer::eConfigChangedSuppress) override;
418     status_t captureScreen(const sp<IBinder>& displayToken, sp<GraphicBuffer>* outBuffer,
419             bool& outCapturedSecureLayers, const ui::Dataspace reqDataspace,
420             const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
421             uint32_t reqWidth, uint32_t reqHeight,
422             bool useIdentityTransform, ISurfaceComposer::Rotation rotation, bool captureSecureLayers) override;
423     status_t captureScreen(uint64_t displayOrLayerStack, ui::Dataspace* outDataspace,
424                            sp<GraphicBuffer>* outBuffer) override;
425     status_t captureLayers(
426             const sp<IBinder>& parentHandle, sp<GraphicBuffer>* outBuffer,
427             const ui::Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat,
428             const Rect& sourceCrop,
429             const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& exclude,
430             float frameScale, bool childrenOnly) override;
431 
432     status_t getDisplayStats(const sp<IBinder>& displayToken, DisplayStatInfo* stats) override;
433     status_t getDisplayConfigs(const sp<IBinder>& displayToken,
434                                Vector<DisplayInfo>* configs) override;
435     int getActiveConfig(const sp<IBinder>& displayToken) override;
436     status_t getDisplayColorModes(const sp<IBinder>& displayToken,
437                                   Vector<ui::ColorMode>* configs) override;
438     status_t getDisplayNativePrimaries(const sp<IBinder>& displayToken,
439                                        ui::DisplayPrimaries &primaries);
440     ui::ColorMode getActiveColorMode(const sp<IBinder>& displayToken) override;
441     status_t setActiveColorMode(const sp<IBinder>& displayToken, ui::ColorMode colorMode) override;
442     void setPowerMode(const sp<IBinder>& displayToken, int mode) override;
443     status_t setActiveConfig(const sp<IBinder>& displayToken, int id) override;
444     status_t clearAnimationFrameStats() override;
445     status_t getAnimationFrameStats(FrameStats* outStats) const override;
446     status_t getHdrCapabilities(const sp<IBinder>& displayToken,
447                                 HdrCapabilities* outCapabilities) const override;
448     status_t enableVSyncInjections(bool enable) override;
449     status_t injectVSync(nsecs_t when) override;
450     status_t getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const override;
451     status_t getColorManagement(bool* outGetColorManagement) const override;
452     status_t getCompositionPreference(ui::Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
453                                       ui::Dataspace* outWideColorGamutDataspace,
454                                       ui::PixelFormat* outWideColorGamutPixelFormat) const override;
455     status_t getDisplayedContentSamplingAttributes(const sp<IBinder>& display,
456                                                    ui::PixelFormat* outFormat,
457                                                    ui::Dataspace* outDataspace,
458                                                    uint8_t* outComponentMask) const override;
459     status_t setDisplayContentSamplingEnabled(const sp<IBinder>& display, bool enable,
460                                               uint8_t componentMask,
461                                               uint64_t maxFrames) const override;
462     status_t getDisplayedContentSample(const sp<IBinder>& display, uint64_t maxFrames,
463                                        uint64_t timestamp,
464                                        DisplayedFrameStats* outStats) const override;
465     status_t getProtectedContentSupport(bool* outSupported) const override;
466     status_t isWideColorDisplay(const sp<IBinder>& displayToken,
467                                 bool* outIsWideColorDisplay) const override;
468     status_t addRegionSamplingListener(const Rect& samplingArea, const sp<IBinder>& stopLayerHandle,
469                                        const sp<IRegionSamplingListener>& listener) override;
470     status_t removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) override;
471     status_t setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
472                                       const std::vector<int32_t>& allowedConfigs) override;
473     status_t getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
474                                       std::vector<int32_t>* outAllowedConfigs) override;
475     status_t getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
476                                          bool* outSupport) const override;
477     status_t setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) const override;
478     status_t notifyPowerHint(int32_t hintId) override;
479 
480     /* ------------------------------------------------------------------------
481      * DeathRecipient interface
482      */
483     void binderDied(const wp<IBinder>& who) override;
484 
485     /* ------------------------------------------------------------------------
486      * RefBase interface
487      */
488     void onFirstRef() override;
489 
490     /* ------------------------------------------------------------------------
491      * HWC2::ComposerCallback / HWComposer::EventHandler interface
492      */
493     void onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
494                          int64_t timestamp) override;
495     void onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
496                            HWC2::Connection connection) override;
497     void onRefreshReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId) override;
498 
499     /* ------------------------------------------------------------------------
500      * Message handling
501      */
502     void waitForEvent();
503     // Can only be called from the main thread or with mStateLock held
504     void signalTransaction();
505     // Can only be called from the main thread or with mStateLock held
506     void signalLayerUpdate();
507     void signalRefresh();
508 
509     using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
510 
511     struct ActiveConfigInfo {
512         RefreshRateType type = RefreshRateType::DEFAULT;
513         int configId = 0;
514         Scheduler::ConfigEvent event = Scheduler::ConfigEvent::None;
515 
516         bool operator!=(const ActiveConfigInfo& other) const {
517             return type != other.type || configId != other.configId || event != other.event;
518         }
519     };
520 
521     // called on the main thread in response to initializeDisplays()
522     void onInitializeDisplays() REQUIRES(mStateLock);
523     // Sets the desired active config bit. It obtains the lock, and sets mDesiredActiveConfig.
524     void setDesiredActiveConfig(const ActiveConfigInfo& info) REQUIRES(mStateLock);
525     // Once HWC has returned the present fence, this sets the active config and a new refresh
526     // rate in SF.
527     void setActiveConfigInternal() REQUIRES(mStateLock);
528     // Active config is updated on INVALIDATE call in a state machine-like manner. When the
529     // desired config was set, HWC needs to update the panel on the next refresh, and when
530     // we receive the fence back, we know that the process was complete. It returns whether
531     // we need to wait for the next invalidate
532     bool performSetActiveConfig() REQUIRES(mStateLock);
533     // Called when active config is no longer is progress
534     void desiredActiveConfigChangeDone() REQUIRES(mStateLock);
535     // called on the main thread in response to setPowerMode()
536     void setPowerModeInternal(const sp<DisplayDevice>& display, int mode) REQUIRES(mStateLock);
537 
538     // called on the main thread in response to setAllowedDisplayConfigs()
539     void setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
540                                           const std::vector<int32_t>& allowedConfigs)
541             REQUIRES(mStateLock);
542 
543     // Returns whether the transaction actually modified any state
544     bool handleMessageTransaction();
545 
546     // Returns whether a new buffer has been latched (see handlePageFlip())
547     bool handleMessageInvalidate();
548 
549     void handleMessageRefresh();
550 
551     void handleTransaction(uint32_t transactionFlags);
552     void handleTransactionLocked(uint32_t transactionFlags) REQUIRES(mStateLock);
553 
554     void updateInputFlinger();
555     void updateInputWindowInfo();
556     void commitInputWindowCommands() REQUIRES(mStateLock);
557     void setInputWindowsFinished();
558     void updateCursorAsync();
559     void initScheduler(DisplayId primaryDisplayId);
560 
561     /* handlePageFlip - latch a new buffer if available and compute the dirty
562      * region. Returns whether a new buffer has been latched, i.e., whether it
563      * is necessary to perform a refresh during this vsync.
564      */
565     bool handlePageFlip();
566 
567     /* ------------------------------------------------------------------------
568      * Transactions
569      */
570     void applyTransactionState(const Vector<ComposerState>& state,
571                                const Vector<DisplayState>& displays, uint32_t flags,
572                                const InputWindowCommands& inputWindowCommands,
573                                const int64_t desiredPresentTime,
574                                const client_cache_t& uncacheBuffer,
575                                const std::vector<ListenerCallbacks>& listenerCallbacks,
576                                const int64_t postTime, bool privileged, bool isMainThread = false)
577             REQUIRES(mStateLock);
578     // Returns true if at least one transaction was flushed
579     bool flushTransactionQueues();
580     // Returns true if there is at least one transaction that needs to be flushed
581     bool transactionFlushNeeded();
582     uint32_t getTransactionFlags(uint32_t flags);
583     uint32_t peekTransactionFlags();
584     // Can only be called from the main thread or with mStateLock held
585     uint32_t setTransactionFlags(uint32_t flags);
586     uint32_t setTransactionFlags(uint32_t flags, Scheduler::TransactionStart transactionStart);
587     void latchAndReleaseBuffer(const sp<Layer>& layer);
588     void commitTransaction() REQUIRES(mStateLock);
589     void commitOffscreenLayers();
590     bool containsAnyInvalidClientState(const Vector<ComposerState>& states);
591     bool transactionIsReadyToBeApplied(int64_t desiredPresentTime,
592                                        const Vector<ComposerState>& states);
593     uint32_t setClientStateLocked(const ComposerState& composerState, int64_t desiredPresentTime,
594                                   const std::vector<ListenerCallbacks>& listenerCallbacks,
595                                   int64_t postTime, bool privileged) REQUIRES(mStateLock);
596     uint32_t setDisplayStateLocked(const DisplayState& s) REQUIRES(mStateLock);
597     uint32_t addInputWindowCommands(const InputWindowCommands& inputWindowCommands)
598             REQUIRES(mStateLock);
599 
600     /* ------------------------------------------------------------------------
601      * Layer management
602      */
603     status_t createLayer(const String8& name, const sp<Client>& client, uint32_t w, uint32_t h,
604                          PixelFormat format, uint32_t flags, LayerMetadata metadata,
605                          sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp,
606                          const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer = nullptr);
607 
608     status_t createBufferQueueLayer(const sp<Client>& client, const String8& name, uint32_t w,
609                                     uint32_t h, uint32_t flags, LayerMetadata metadata,
610                                     PixelFormat& format, sp<IBinder>* outHandle,
611                                     sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
612 
613     status_t createBufferStateLayer(const sp<Client>& client, const String8& name, uint32_t w,
614                                     uint32_t h, uint32_t flags, LayerMetadata metadata,
615                                     sp<IBinder>* outHandle, sp<Layer>* outLayer);
616 
617     status_t createColorLayer(const sp<Client>& client, const String8& name, uint32_t w, uint32_t h,
618                               uint32_t flags, LayerMetadata metadata, sp<IBinder>* outHandle,
619                               sp<Layer>* outLayer);
620 
621     status_t createContainerLayer(const sp<Client>& client, const String8& name, uint32_t w,
622                                   uint32_t h, uint32_t flags, LayerMetadata metadata,
623                                   sp<IBinder>* outHandle, sp<Layer>* outLayer);
624 
625     String8 getUniqueLayerName(const String8& name);
626 
627     // called when all clients have released all their references to
628     // this layer meaning it is entirely safe to destroy all
629     // resources associated to this layer.
630     void onHandleDestroyed(sp<Layer>& layer);
631     void markLayerPendingRemovalLocked(const sp<Layer>& layer);
632 
633     // add a layer to SurfaceFlinger
634     status_t addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
635                             const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
636                             const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
637                             bool addToCurrentState);
638 
639     // Traverse through all the layers and compute and cache its bounds.
640     void computeLayerBounds();
641 
642     /* ------------------------------------------------------------------------
643      * Boot animation, on/off animations and screen capture
644      */
645 
646     void startBootAnim();
647 
648     using TraverseLayersFunction = std::function<void(const LayerVector::Visitor&)>;
649 
650     void renderScreenImplLocked(const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
651                                 ANativeWindowBuffer* buffer, bool useIdentityTransform,
652                                 int* outSyncFd);
653     status_t captureScreenCommon(RenderArea& renderArea, TraverseLayersFunction traverseLayers,
654                                  sp<GraphicBuffer>* outBuffer, const ui::PixelFormat reqPixelFormat,
655                                  bool useIdentityTransform, bool& outCapturedSecureLayers);
656     status_t captureScreenCommon(RenderArea& renderArea, TraverseLayersFunction traverseLayers,
657                                  const sp<GraphicBuffer>& buffer, bool useIdentityTransform,
658                                  bool& outCapturedSecureLayers);
659     const sp<DisplayDevice> getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack);
660     status_t captureScreenImplLocked(const RenderArea& renderArea,
661                                      TraverseLayersFunction traverseLayers,
662                                      ANativeWindowBuffer* buffer, bool useIdentityTransform,
663                                      bool forSystem, int* outSyncFd, bool& outCapturedSecureLayers);
664     void traverseLayersInDisplay(const sp<const DisplayDevice>& display,
665                                  const LayerVector::Visitor& visitor);
666 
667     sp<StartPropertySetThread> mStartPropertySetThread;
668 
669     /* ------------------------------------------------------------------------
670      * Properties
671      */
672     void readPersistentProperties();
673 
674     /* ------------------------------------------------------------------------
675      * EGL
676      */
677     size_t getMaxTextureSize() const;
678     size_t getMaxViewportDims() const;
679 
680     /* ------------------------------------------------------------------------
681      * Display and layer stack management
682      */
683     // called when starting, or restarting after system_server death
684     void initializeDisplays();
685 
getDisplayDevice(const wp<IBinder> & displayToken)686     sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& displayToken) const {
687         Mutex::Autolock _l(mStateLock);
688         return getDisplayDeviceLocked(displayToken);
689     }
690 
getDisplayDevice(const wp<IBinder> & displayToken)691     sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& displayToken) {
692         Mutex::Autolock _l(mStateLock);
693         return getDisplayDeviceLocked(displayToken);
694     }
695 
696     // NOTE: can only be called from the main thread or with mStateLock held
getDisplayDeviceLocked(const wp<IBinder> & displayToken)697     sp<const DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& displayToken) const {
698         return const_cast<SurfaceFlinger*>(this)->getDisplayDeviceLocked(displayToken);
699     }
700 
701     // NOTE: can only be called from the main thread or with mStateLock held
getDisplayDeviceLocked(const wp<IBinder> & displayToken)702     sp<DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& displayToken) {
703         const auto it = mDisplays.find(displayToken);
704         return it == mDisplays.end() ? nullptr : it->second;
705     }
706 
getDefaultDisplayDeviceLocked()707     sp<const DisplayDevice> getDefaultDisplayDeviceLocked() const {
708         return const_cast<SurfaceFlinger*>(this)->getDefaultDisplayDeviceLocked();
709     }
710 
getDefaultDisplayDeviceLocked()711     sp<DisplayDevice> getDefaultDisplayDeviceLocked() {
712         if (const auto token = getInternalDisplayTokenLocked()) {
713             return getDisplayDeviceLocked(token);
714         }
715         return nullptr;
716     }
717 
718     // mark a region of a layer stack dirty. this updates the dirty
719     // region of all screens presenting this layer stack.
720     void invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty);
721 
722     /* ------------------------------------------------------------------------
723      * H/W composer
724      */
725 
726     // The current hardware composer interface.
727     //
728     // The following thread safety rules apply when accessing mHwc, either
729     // directly or via getHwComposer():
730     //
731     // 1. When recreating mHwc, acquire mStateLock. We currently recreate mHwc
732     //    only when switching into and out of vr. Recreating mHwc must only be
733     //    done on the main thread.
734     //
735     // 2. When accessing mHwc on the main thread, it's not necessary to acquire
736     //    mStateLock.
737     //
738     // 3. When accessing mHwc on a thread other than the main thread, we always
739     //    need to acquire mStateLock. This is because the main thread could be
740     //    in the process of destroying the current mHwc instance.
741     //
742     // The above thread safety rules only apply to SurfaceFlinger.cpp. In
743     // SurfaceFlinger_hwc1.cpp we create mHwc at surface flinger init and never
744     // destroy it, so it's always safe to access mHwc from any thread without
745     // acquiring mStateLock.
746     HWComposer& getHwComposer() const;
747 
748     /* ------------------------------------------------------------------------
749      * Compositing
750      */
751     void invalidateHwcGeometry();
752     void computeVisibleRegions(const sp<const DisplayDevice>& display, Region& dirtyRegion,
753                                Region& opaqueRegion);
754 
755     void preComposition();
756     void postComposition();
757     void getCompositorTiming(CompositorTiming* compositorTiming);
758     void updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
759                                 std::shared_ptr<FenceTime>& presentFenceTime);
760     void setCompositorTimingSnapped(const DisplayStatInfo& stats,
761                                     nsecs_t compositeToPresentLatency);
762     void rebuildLayerStacks();
763 
764     ui::Dataspace getBestDataspace(const sp<DisplayDevice>& display, ui::Dataspace* outHdrDataSpace,
765                                    bool* outIsHdrClientComposition) const;
766 
767     // Returns the appropriate ColorMode, Dataspace and RenderIntent for the
768     // DisplayDevice. The function only returns the supported ColorMode,
769     // Dataspace and RenderIntent.
770     void pickColorMode(const sp<DisplayDevice>& display, ui::ColorMode* outMode,
771                        ui::Dataspace* outDataSpace, ui::RenderIntent* outRenderIntent) const;
772 
773     void calculateWorkingSet();
774     /*
775      * beginFrame - This function handles any pre-frame processing that needs to be
776      * prior to any CompositionInfo handling and is not dependent on data in
777      * CompositionInfo
778      */
779     void beginFrame(const sp<DisplayDevice>& display);
780     /* prepareFrame - This function will call into the DisplayDevice to prepare a
781      * frame after CompositionInfo has been programmed.   This provides a mechanism
782      * to prepare the hardware composer
783      */
784     void prepareFrame(const sp<DisplayDevice>& display);
785     void doComposition(const sp<DisplayDevice>& display, bool repainEverything);
786     void doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything);
787     void logLayerStats();
788     void doDisplayComposition(const sp<DisplayDevice>& display, const Region& dirtyRegion);
789 
790     // This fails if using GL and the surface has been destroyed. readyFence
791     // will be populated if using GL and native fence sync is supported, to
792     // signal when drawing has completed.
793     bool doComposeSurfaces(const sp<DisplayDevice>& display, const Region& debugRegionm,
794                            base::unique_fd* readyFence);
795 
796     void postFramebuffer(const sp<DisplayDevice>& display);
797     void postFrame();
798     void drawWormhole(const Region& region) const;
799 
800     /* ------------------------------------------------------------------------
801      * Display management
802      */
803     sp<DisplayDevice> setupNewDisplayDeviceInternal(
804             const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
805             const DisplayDeviceState& state,
806             const sp<compositionengine::DisplaySurface>& dispSurface,
807             const sp<IGraphicBufferProducer>& producer);
808     void processDisplayChangesLocked();
809     void processDisplayHotplugEventsLocked();
810 
811     void dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected);
812 
813     /* ------------------------------------------------------------------------
814      * VSync
815      */
816     nsecs_t getVsyncPeriod() const REQUIRES(mStateLock);
817 
818     // Sets the refresh rate by switching active configs, if they are available for
819     // the desired refresh rate.
820     void setRefreshRateTo(RefreshRateType, Scheduler::ConfigEvent event) REQUIRES(mStateLock);
821 
822     bool isDisplayConfigAllowed(int32_t configId) REQUIRES(mStateLock);
823 
824     /*
825      * Display identification
826      */
getPhysicalDisplayTokenLocked(DisplayId displayId)827     sp<IBinder> getPhysicalDisplayTokenLocked(DisplayId displayId) const {
828         const auto it = mPhysicalDisplayTokens.find(displayId);
829         return it != mPhysicalDisplayTokens.end() ? it->second : nullptr;
830     }
831 
getPhysicalDisplayIdLocked(const sp<IBinder> & displayToken)832     std::optional<DisplayId> getPhysicalDisplayIdLocked(const sp<IBinder>& displayToken) const {
833         for (const auto& [id, token] : mPhysicalDisplayTokens) {
834             if (token == displayToken) {
835                 return id;
836             }
837         }
838         return {};
839     }
840 
841     // TODO(b/74619554): Remove special cases for primary display.
getInternalDisplayTokenLocked()842     sp<IBinder> getInternalDisplayTokenLocked() const {
843         const auto displayId = getInternalDisplayIdLocked();
844         return displayId ? getPhysicalDisplayTokenLocked(*displayId) : nullptr;
845     }
846 
getInternalDisplayIdLocked()847     std::optional<DisplayId> getInternalDisplayIdLocked() const {
848         const auto hwcDisplayId = getHwComposer().getInternalHwcDisplayId();
849         return hwcDisplayId ? getHwComposer().toPhysicalDisplayId(*hwcDisplayId) : std::nullopt;
850     }
851 
852     bool previousFrameMissed(int graceTimeMs = 0);
853     void setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled);
854 
855     /*
856      * Debugging & dumpsys
857      */
858     using DumpArgs = Vector<String16>;
859     using Dumper = std::function<void(const DumpArgs&, bool asProto, std::string&)>;
860 
861     template <typename F, std::enable_if_t<!std::is_member_function_pointer_v<F>>* = nullptr>
dumper(F && dump)862     static Dumper dumper(F&& dump) {
863         using namespace std::placeholders;
864         return std::bind(std::forward<F>(dump), _3);
865     }
866 
867     template <typename F, std::enable_if_t<std::is_member_function_pointer_v<F>>* = nullptr>
dumper(F dump)868     Dumper dumper(F dump) {
869         using namespace std::placeholders;
870         return std::bind(dump, this, _3);
871     }
872 
873     template <typename F>
argsDumper(F dump)874     Dumper argsDumper(F dump) {
875         using namespace std::placeholders;
876         return std::bind(dump, this, _1, _3);
877     }
878 
879     template <typename F>
protoDumper(F dump)880     Dumper protoDumper(F dump) {
881         using namespace std::placeholders;
882         return std::bind(dump, this, _1, _2, _3);
883     }
884 
885     void dumpAllLocked(const DumpArgs& args, std::string& result) const REQUIRES(mStateLock);
886 
887     void appendSfConfigString(std::string& result) const;
888     void listLayersLocked(std::string& result) const;
889     void dumpStatsLocked(const DumpArgs& args, std::string& result) const REQUIRES(mStateLock);
890     void clearStatsLocked(const DumpArgs& args, std::string& result);
891     void dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const;
892     void logFrameStats();
893 
894     void dumpVSync(std::string& result) const REQUIRES(mStateLock);
895     void dumpStaticScreenStats(std::string& result) const;
896     // Not const because each Layer needs to query Fences and cache timestamps.
897     void dumpFrameEventsLocked(std::string& result);
898 
899     void recordBufferingStats(const char* layerName,
900             std::vector<OccupancyTracker::Segment>&& history);
901     void dumpBufferingStats(std::string& result) const;
902     void dumpDisplayIdentificationData(std::string& result) const;
903     void dumpWideColorInfo(std::string& result) const;
904     LayersProto dumpDrawingStateProto(uint32_t traceFlags = SurfaceTracing::TRACE_ALL) const;
905     LayersProto dumpProtoFromMainThread(uint32_t traceFlags = SurfaceTracing::TRACE_ALL)
906             EXCLUDES(mStateLock);
907     void withTracingLock(std::function<void()> operation) REQUIRES(mStateLock);
908     LayersProto dumpVisibleLayersProtoInfo(const sp<DisplayDevice>& display) const;
909 
isLayerTripleBufferingDisabled()910     bool isLayerTripleBufferingDisabled() const {
911         return this->mLayerTripleBufferingDisabled;
912     }
913 
914     status_t doDump(int fd, const DumpArgs& args, bool asProto);
915 
916     status_t dumpCritical(int fd, const DumpArgs&, bool asProto);
917 
dumpAll(int fd,const DumpArgs & args,bool asProto)918     status_t dumpAll(int fd, const DumpArgs& args, bool asProto) override {
919         return doDump(fd, args, asProto);
920     }
921 
922     /* ------------------------------------------------------------------------
923      * VrFlinger
924      */
925     void resetDisplayState();
926 
927     // Check to see if we should handoff to vr flinger.
928     void updateVrFlinger();
929 
930     void updateColorMatrixLocked();
931 
932     /* ------------------------------------------------------------------------
933      * Attributes
934      */
935 
936     surfaceflinger::Factory& mFactory;
937 
938     // access must be protected by mStateLock
939     mutable Mutex mStateLock;
940     State mCurrentState{LayerVector::StateSet::Current};
941     std::atomic<int32_t> mTransactionFlags = 0;
942     Condition mTransactionCV;
943     bool mTransactionPending = false;
944     bool mAnimTransactionPending = false;
945     SortedVector<sp<Layer>> mLayersPendingRemoval;
946     bool mTraversalNeededMainThread = false;
947 
948     // guards access to the mDrawing state if tracing is enabled.
949     mutable std::mutex mDrawingStateLock;
950 
951     // global color transform states
952     Daltonizer mDaltonizer;
953     float mGlobalSaturationFactor = 1.0f;
954     mat4 mClientColorMatrix;
955 
956     // Can't be unordered_set because wp<> isn't hashable
957     std::set<wp<IBinder>> mGraphicBufferProducerList;
958     size_t mMaxGraphicBufferProducerListSize = MAX_LAYERS;
959 
960     // protected by mStateLock (but we could use another lock)
961     bool mLayersRemoved = false;
962     bool mLayersAdded = false;
963 
964     std::atomic<bool> mRepaintEverything = false;
965 
966     // constant members (no synchronization needed for access)
967     const nsecs_t mBootTime = systemTime();
968     bool mGpuToCpuSupported = false;
969     std::unique_ptr<EventThread> mInjectorEventThread;
970     std::unique_ptr<InjectVSyncSource> mVSyncInjector;
971 
972     // Calculates correct offsets.
973     VSyncModulator mVsyncModulator;
974     // Keeps track of all available phase offsets for different refresh types.
975     const std::unique_ptr<scheduler::PhaseOffsets> mPhaseOffsets;
976 
977     // Can only accessed from the main thread, these members
978     // don't need synchronization
979     State mDrawingState{LayerVector::StateSet::Drawing};
980     bool mVisibleRegionsDirty = false;
981     // Set during transaction commit stage to track if the input info for a layer has changed.
982     bool mInputInfoChanged = false;
983     bool mGeometryInvalid = false;
984     bool mAnimCompositionPending = false;
985     std::vector<sp<Layer>> mLayersWithQueuedFrames;
986     // Tracks layers that need to update a display's dirty region.
987     std::vector<sp<Layer>> mLayersPendingRefresh;
988     std::array<sp<Fence>, 2> mPreviousPresentFences = {Fence::NO_FENCE, Fence::NO_FENCE};
989     // True if in the previous frame at least one layer was composed via the GPU.
990     bool mHadClientComposition = false;
991     // True if in the previous frame at least one layer was composed via HW Composer.
992     // Note that it is possible for a frame to be composed via both client and device
993     // composition, for example in the case of overlays.
994     bool mHadDeviceComposition = false;
995 
996     enum class BootStage {
997         BOOTLOADER,
998         BOOTANIMATION,
999         FINISHED,
1000     };
1001     BootStage mBootStage = BootStage::BOOTLOADER;
1002 
1003     struct HotplugEvent {
1004         hwc2_display_t hwcDisplayId;
1005         HWC2::Connection connection = HWC2::Connection::Invalid;
1006     };
1007     // protected by mStateLock
1008     std::vector<HotplugEvent> mPendingHotplugEvents;
1009 
1010     // this may only be written from the main thread with mStateLock held
1011     // it may be read from other threads with mStateLock held
1012     std::map<wp<IBinder>, sp<DisplayDevice>> mDisplays;
1013     std::unordered_map<DisplayId, sp<IBinder>> mPhysicalDisplayTokens;
1014 
1015     // protected by mStateLock
1016     std::unordered_map<BBinder*, wp<Layer>> mLayersByLocalBinderToken;
1017 
1018     // don't use a lock for these, we don't care
1019     int mDebugRegion = 0;
1020     bool mDebugDisableHWC = false;
1021     bool mDebugDisableTransformHint = false;
1022     volatile nsecs_t mDebugInTransaction = 0;
1023     bool mForceFullDamage = false;
1024     bool mPropagateBackpressure = true;
1025     bool mPropagateBackpressureClientComposition = false;
1026     std::unique_ptr<SurfaceInterceptor> mInterceptor;
1027     SurfaceTracing mTracing{*this};
1028     bool mTracingEnabled = false;
1029     bool mTracingEnabledChanged GUARDED_BY(mStateLock) = false;
1030     LayerStats mLayerStats;
1031     const std::shared_ptr<TimeStats> mTimeStats;
1032     bool mUseHwcVirtualDisplays = false;
1033     std::atomic<uint32_t> mFrameMissedCount = 0;
1034     std::atomic<uint32_t> mHwcFrameMissedCount = 0;
1035     std::atomic<uint32_t> mGpuFrameMissedCount = 0;
1036 
1037     TransactionCompletedThread mTransactionCompletedThread;
1038 
1039     // Restrict layers to use two buffers in their bufferqueues.
1040     bool mLayerTripleBufferingDisabled = false;
1041 
1042     // these are thread safe
1043     std::unique_ptr<MessageQueue> mEventQueue;
1044     FrameTracker mAnimFrameTracker;
1045 
1046     // protected by mDestroyedLayerLock;
1047     mutable Mutex mDestroyedLayerLock;
1048     Vector<Layer const *> mDestroyedLayers;
1049 
1050     nsecs_t mRefreshStartTime = 0;
1051 
1052     std::atomic<bool> mRefreshPending = false;
1053 
1054     // We maintain a pool of pre-generated texture names to hand out to avoid
1055     // layer creation needing to run on the main thread (which it would
1056     // otherwise need to do to access RenderEngine).
1057     std::mutex mTexturePoolMutex;
1058     uint32_t mTexturePoolSize = 0;
1059     std::vector<uint32_t> mTexturePool;
1060 
1061     struct IBinderHash {
operatorIBinderHash1062         std::size_t operator()(const sp<IBinder>& strongPointer) const {
1063             return std::hash<IBinder*>{}(strongPointer.get());
1064         }
1065     };
1066     struct TransactionState {
TransactionStateTransactionState1067         TransactionState(const Vector<ComposerState>& composerStates,
1068                          const Vector<DisplayState>& displayStates, uint32_t transactionFlags,
1069                          int64_t desiredPresentTime, const client_cache_t& uncacheBuffer,
1070                          const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
1071                          bool privileged)
1072               : states(composerStates),
1073                 displays(displayStates),
1074                 flags(transactionFlags),
1075                 desiredPresentTime(desiredPresentTime),
1076                 buffer(uncacheBuffer),
1077                 callback(listenerCallbacks),
1078                 postTime(postTime),
1079                 privileged(privileged) {}
1080 
1081         Vector<ComposerState> states;
1082         Vector<DisplayState> displays;
1083         uint32_t flags;
1084         const int64_t desiredPresentTime;
1085         client_cache_t buffer;
1086         std::vector<ListenerCallbacks> callback;
1087         const int64_t postTime;
1088         bool privileged;
1089     };
1090     std::unordered_map<sp<IBinder>, std::queue<TransactionState>, IBinderHash> mTransactionQueues;
1091 
1092     /* ------------------------------------------------------------------------
1093      * Feature prototyping
1094      */
1095 
1096     bool mInjectVSyncs = false;
1097 
1098     // Static screen stats
1099     bool mHasPoweredOff = false;
1100 
1101     size_t mNumLayers = 0;
1102 
1103     // Verify that transaction is being called by an approved process:
1104     // either AID_GRAPHICS or AID_SYSTEM.
1105     status_t CheckTransactCodeCredentials(uint32_t code);
1106 
1107     // to linkToDeath
1108     sp<IBinder> mWindowManager;
1109 
1110     std::unique_ptr<dvr::VrFlinger> mVrFlinger;
1111     std::atomic<bool> mVrFlingerRequestsDisplay = false;
1112     static bool useVrFlinger;
1113     std::thread::id mMainThreadId = std::this_thread::get_id();
1114 
1115     DisplayColorSetting mDisplayColorSetting = DisplayColorSetting::ENHANCED;
1116 
1117     // Color mode forced by setting persist.sys.sf.color_mode, it must:
1118     //     1. not be NATIVE color mode, NATIVE color mode means no forced color mode;
1119     //     2. be one of the supported color modes returned by hardware composer, otherwise
1120     //        it will not be respected.
1121     // persist.sys.sf.color_mode will only take effect when persist.sys.sf.native_mode
1122     // is not set to 1.
1123     // This property can be used to force SurfaceFlinger to always pick a certain color mode.
1124     ui::ColorMode mForceColorMode = ui::ColorMode::NATIVE;
1125 
1126     ui::Dataspace mDefaultCompositionDataspace;
1127     ui::Dataspace mWideColorGamutCompositionDataspace;
1128     ui::Dataspace mColorSpaceAgnosticDataspace;
1129 
1130     SurfaceFlingerBE mBE;
1131     std::unique_ptr<compositionengine::CompositionEngine> mCompositionEngine;
1132 
1133     /* ------------------------------------------------------------------------
1134      * Scheduler
1135      */
1136     bool mUseSmart90ForVideo = false;
1137     std::unique_ptr<Scheduler> mScheduler;
1138     sp<Scheduler::ConnectionHandle> mAppConnectionHandle;
1139     sp<Scheduler::ConnectionHandle> mSfConnectionHandle;
1140 
1141     std::unique_ptr<scheduler::RefreshRateConfigs> mRefreshRateConfigs;
1142     std::unique_ptr<scheduler::RefreshRateStats> mRefreshRateStats;
1143 
1144     // All configs are allowed if the set is empty.
1145     using DisplayConfigs = std::set<int32_t>;
1146     DisplayConfigs mAllowedDisplayConfigs GUARDED_BY(mStateLock);
1147 
1148     std::mutex mActiveConfigLock;
1149     // This bit is set once we start setting the config. We read from this bit during the
1150     // process. If at the end, this bit is different than mDesiredActiveConfig, we restart
1151     // the process.
1152     ActiveConfigInfo mUpcomingActiveConfig; // Always read and written on the main thread.
1153     // This bit can be set at any point in time when the system wants the new config.
1154     ActiveConfigInfo mDesiredActiveConfig GUARDED_BY(mActiveConfigLock);
1155 
1156     // below flags are set by main thread only
1157     bool mDesiredActiveConfigChanged GUARDED_BY(mActiveConfigLock) = false;
1158     bool mCheckPendingFence = false;
1159 
1160     bool mLumaSampling = true;
1161     sp<RegionSamplingThread> mRegionSamplingThread;
1162     ui::DisplayPrimaries mInternalDisplayPrimaries;
1163 
1164     sp<IInputFlinger> mInputFlinger;
1165     InputWindowCommands mPendingInputWindowCommands GUARDED_BY(mStateLock);
1166     // Should only be accessed by the main thread.
1167     InputWindowCommands mInputWindowCommands;
1168 
1169     struct SetInputWindowsListener : BnSetInputWindowsListener {
SetInputWindowsListenerSetInputWindowsListener1170         explicit SetInputWindowsListener(sp<SurfaceFlinger> flinger)
1171               : mFlinger(std::move(flinger)) {}
1172 
1173         void onSetInputWindowsFinished() override;
1174 
1175         const sp<SurfaceFlinger> mFlinger;
1176     };
1177 
1178     const sp<SetInputWindowsListener> mSetInputWindowsListener = new SetInputWindowsListener(this);
1179 
1180     bool mPendingSyncInputWindows GUARDED_BY(mStateLock);
1181     Hwc2::impl::PowerAdvisor mPowerAdvisor;
1182 
1183     std::unique_ptr<RefreshRateOverlay> mRefreshRateOverlay;
1184 
1185     // Flag used to set override allowed display configs from backdoor
1186     bool mDebugDisplayConfigSetByBackdoor = false;
1187 
1188     // A set of layers that have no parent so they are not drawn on screen.
1189     // Should only be accessed by the main thread.
1190     // The Layer pointer is removed from the set when the destructor is called so there shouldn't
1191     // be any issues with a raw pointer referencing an invalid object.
1192     std::unordered_set<Layer*> mOffscreenLayers;
1193 
1194     // Flags to capture the state of Vsync in HWC
1195     HWC2::Vsync mHWCVsyncState = HWC2::Vsync::Disable;
1196     HWC2::Vsync mHWCVsyncPendingState = HWC2::Vsync::Disable;
1197 
1198     nsecs_t mExpectedPresentTime;
1199 };
1200 
1201 } // namespace android
1202