• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef ANDROID_SURFACE_FLINGER_H
18 #define ANDROID_SURFACE_FLINGER_H
19 
20 #include <memory>
21 #include <stdint.h>
22 #include <sys/types.h>
23 
24 #include <EGL/egl.h>
25 
26 /*
27  * NOTE: Make sure this file doesn't include  anything from <gl/ > or <gl2/ >
28  */
29 
30 #include <cutils/compiler.h>
31 
32 #include <utils/Atomic.h>
33 #include <utils/Errors.h>
34 #include <utils/KeyedVector.h>
35 #include <utils/RefBase.h>
36 #include <utils/SortedVector.h>
37 #include <utils/threads.h>
38 
39 #include <ui/FenceTime.h>
40 #include <ui/PixelFormat.h>
41 #include <math/mat4.h>
42 
43 #include <gui/FrameTimestamps.h>
44 #include <gui/ISurfaceComposer.h>
45 #include <gui/ISurfaceComposerClient.h>
46 #include <gui/OccupancyTracker.h>
47 
48 #include <hardware/hwcomposer_defs.h>
49 
50 #include <system/graphics.h>
51 
52 #include <private/gui/LayerState.h>
53 
54 #include "Barrier.h"
55 #include "DisplayDevice.h"
56 #include "DispSync.h"
57 #include "FrameTracker.h"
58 #include "LayerVector.h"
59 #include "MessageQueue.h"
60 #include "SurfaceInterceptor.h"
61 #include "StartPropertySetThread.h"
62 
63 #ifdef USE_HWC2
64 #include "DisplayHardware/HWC2.h"
65 #include "DisplayHardware/HWComposer.h"
66 #else
67 #include "DisplayHardware/HWComposer_hwc1.h"
68 #endif
69 
70 #include "Effects/Daltonizer.h"
71 
72 #include <map>
73 #include <mutex>
74 #include <queue>
75 #include <string>
76 #include <thread>
77 #include <utility>
78 
79 namespace android {
80 
81 // ---------------------------------------------------------------------------
82 
83 class Client;
84 class DisplayEventConnection;
85 class EventThread;
86 class Layer;
87 class LayerDim;
88 class Surface;
89 class RenderEngine;
90 class EventControlThread;
91 class VSyncSource;
92 class InjectVSyncSource;
93 
94 namespace dvr {
95 class VrFlinger;
96 } // namespace dvr
97 
98 // ---------------------------------------------------------------------------
99 
100 enum {
101     eTransactionNeeded        = 0x01,
102     eTraversalNeeded          = 0x02,
103     eDisplayTransactionNeeded = 0x04,
104     eTransactionMask          = 0x07
105 };
106 
107 class SurfaceFlinger : public BnSurfaceComposer,
108                        private IBinder::DeathRecipient,
109 #ifdef USE_HWC2
110                        private HWC2::ComposerCallback
111 #else
112                        private HWComposer::EventHandler
113 #endif
114 {
115 public:
116 
117     // This is the phase offset in nanoseconds of the software vsync event
118     // relative to the vsync event reported by HWComposer.  The software vsync
119     // event is when SurfaceFlinger and Choreographer-based applications run each
120     // frame.
121     //
122     // This phase offset allows adjustment of the minimum latency from application
123     // wake-up time (by Choreographer) to the time at which the resulting window
124     // image is displayed.  This value may be either positive (after the HW vsync)
125     // or negative (before the HW vsync). Setting it to 0 will result in a lower
126     // latency bound of two vsync periods because the app and SurfaceFlinger
127     // will run just after the HW vsync.  Setting it to a positive number will
128     // result in the minimum latency being:
129     //
130     //     (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
131     //
132     // Note that reducing this latency makes it more likely for the applications
133     // to not have their window content image ready in time.  When this happens
134     // the latency will end up being an additional vsync period, and animations
135     // will hiccup.  Therefore, this latency should be tuned somewhat
136     // conservatively (or at least with awareness of the trade-off being made).
137     static int64_t vsyncPhaseOffsetNs;
138     static int64_t sfVsyncPhaseOffsetNs;
139 
140     // If fences from sync Framework are supported.
141     static bool hasSyncFramework;
142 
143     // Instruct the Render Engine to use EGL_IMG_context_priority is available.
144     static bool useContextPriority;
145 
146     // The offset in nanoseconds to use when DispSync timestamps present fence
147     // signaling time.
148     static int64_t dispSyncPresentTimeOffset;
149 
150     // Some hardware can do RGB->YUV conversion more efficiently in hardware
151     // controlled by HWC than in hardware controlled by the video encoder.
152     // This instruct VirtualDisplaySurface to use HWC for such conversion on
153     // GL composition.
154     static bool useHwcForRgbToYuv;
155 
156     // Maximum dimension supported by HWC for virtual display.
157     // Equal to min(max_height, max_width).
158     static uint64_t maxVirtualDisplaySize;
159 
160     // Controls the number of buffers SurfaceFlinger will allocate for use in
161     // FramebufferSurface
162     static int64_t maxFrameBufferAcquiredBuffers;
163 
164     // Indicate if platform supports color management on its
165     // wide-color display. This is typically found on devices
166     // with wide gamut (e.g. Display-P3) display.
167     // This also allows devices with wide-color displays that don't
168     // want to support color management to disable color management.
169     static bool hasWideColorDisplay;
170 
getServiceName()171     static char const* getServiceName() ANDROID_API {
172         return "SurfaceFlinger";
173     }
174 
175     SurfaceFlinger() ANDROID_API;
176 
177     // must be called before clients can connect
178     void init() ANDROID_API;
179 
180     // starts SurfaceFlinger main loop in the current thread
181     void run() ANDROID_API;
182 
183     enum {
184         EVENT_VSYNC = HWC_EVENT_VSYNC
185     };
186 
187     // post an asynchronous message to the main thread
188     status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
189 
190     // post a synchronous message to the main thread
191     status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
192 
193     // force full composition on all displays
194     void repaintEverything();
195     // Can only be called from the main thread or with mStateLock held
196     void repaintEverythingLocked();
197 
198     // returns the default Display
getDefaultDisplayDevice()199     sp<const DisplayDevice> getDefaultDisplayDevice() const {
200         Mutex::Autolock _l(mStateLock);
201         return getDefaultDisplayDeviceLocked();
202     }
203 
204     // utility function to delete a texture on the main thread
205     void deleteTextureAsync(uint32_t texture);
206 
207     // enable/disable h/w composer event
208     // TODO: this should be made accessible only to EventThread
209 #ifdef USE_HWC2
210     void setVsyncEnabled(int disp, int enabled);
211 #else
212     void eventControl(int disp, int event, int enabled);
213 #endif
214 
215     // called on the main thread by MessageQueue when an internal message
216     // is received
217     // TODO: this should be made accessible only to MessageQueue
218     void onMessageReceived(int32_t what);
219 
220     // for debugging only
221     // TODO: this should be made accessible only to HWComposer
222     const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
223 
getRenderEngine()224     RenderEngine& getRenderEngine() const {
225         return *mRenderEngine;
226     }
227 
228     bool authenticateSurfaceTextureLocked(
229         const sp<IGraphicBufferProducer>& bufferProducer) const;
230 
231 private:
232     friend class Client;
233     friend class DisplayEventConnection;
234     friend class EventThread;
235     friend class Layer;
236     friend class MonitoredProducer;
237 
238     // This value is specified in number of frames.  Log frame stats at most
239     // every half hour.
240     enum { LOG_FRAME_STATS_PERIOD =  30*60*60 };
241 
242     static const size_t MAX_LAYERS = 4096;
243 
244     // We're reference counted, never destroy SurfaceFlinger directly
245     virtual ~SurfaceFlinger();
246 
247     /* ------------------------------------------------------------------------
248      * Internal data structures
249      */
250 
251     class State {
252     public:
State(LayerVector::StateSet set)253         explicit State(LayerVector::StateSet set) : stateSet(set) {}
254         State& operator=(const State& other) {
255             // We explicitly don't copy stateSet so that, e.g., mDrawingState
256             // always uses the Drawing StateSet.
257             layersSortedByZ = other.layersSortedByZ;
258             displays = other.displays;
259             return *this;
260         }
261 
262         const LayerVector::StateSet stateSet = LayerVector::StateSet::Invalid;
263         LayerVector layersSortedByZ;
264         DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
265 
266         void traverseInZOrder(const LayerVector::Visitor& visitor) const;
267         void traverseInReverseZOrder(const LayerVector::Visitor& visitor) const;
268     };
269 
270     /* ------------------------------------------------------------------------
271      * IBinder interface
272      */
273     virtual status_t onTransact(uint32_t code, const Parcel& data,
274         Parcel* reply, uint32_t flags);
275     virtual status_t dump(int fd, const Vector<String16>& args);
276 
277     /* ------------------------------------------------------------------------
278      * ISurfaceComposer interface
279      */
280     virtual sp<ISurfaceComposerClient> createConnection();
281     virtual sp<ISurfaceComposerClient> createScopedConnection(const sp<IGraphicBufferProducer>& gbp);
282     virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
283     virtual void destroyDisplay(const sp<IBinder>& display);
284     virtual sp<IBinder> getBuiltInDisplay(int32_t id);
285     virtual void setTransactionState(const Vector<ComposerState>& state,
286             const Vector<DisplayState>& displays, uint32_t flags);
287     virtual void bootFinished();
288     virtual bool authenticateSurfaceTexture(
289         const sp<IGraphicBufferProducer>& bufferProducer) const;
290     virtual status_t getSupportedFrameTimestamps(
291             std::vector<FrameEvent>* outSupported) const;
292     virtual sp<IDisplayEventConnection> createDisplayEventConnection(
293             ISurfaceComposer::VsyncSource vsyncSource = eVsyncSourceApp);
294     virtual status_t captureScreen(const sp<IBinder>& display,
295             const sp<IGraphicBufferProducer>& producer,
296             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
297             int32_t minLayerZ, int32_t maxLayerZ,
298             bool useIdentityTransform, ISurfaceComposer::Rotation rotation);
299     virtual status_t getDisplayStats(const sp<IBinder>& display,
300             DisplayStatInfo* stats);
301     virtual status_t getDisplayConfigs(const sp<IBinder>& display,
302             Vector<DisplayInfo>* configs);
303     virtual int getActiveConfig(const sp<IBinder>& display);
304     virtual status_t getDisplayColorModes(const sp<IBinder>& display,
305             Vector<android_color_mode_t>* configs);
306     virtual android_color_mode_t getActiveColorMode(const sp<IBinder>& display);
307     virtual status_t setActiveColorMode(const sp<IBinder>& display, android_color_mode_t colorMode);
308     virtual void setPowerMode(const sp<IBinder>& display, int mode);
309     virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
310     virtual status_t clearAnimationFrameStats();
311     virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
312     virtual status_t getHdrCapabilities(const sp<IBinder>& display,
313             HdrCapabilities* outCapabilities) const;
314     virtual status_t enableVSyncInjections(bool enable);
315     virtual status_t injectVSync(nsecs_t when);
316 
317 
318     /* ------------------------------------------------------------------------
319      * DeathRecipient interface
320      */
321     virtual void binderDied(const wp<IBinder>& who);
322 
323     /* ------------------------------------------------------------------------
324      * RefBase interface
325      */
326     virtual void onFirstRef();
327 
328     /* ------------------------------------------------------------------------
329      * HWC2::ComposerCallback / HWComposer::EventHandler interface
330      */
331 #ifdef USE_HWC2
332     void onVsyncReceived(int32_t sequenceId, hwc2_display_t display,
333                          int64_t timestamp) override;
334     void onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
335                            HWC2::Connection connection,
336                            bool primaryDisplay) override;
337     void onRefreshReceived(int32_t sequenceId, hwc2_display_t display) override;
338 #else
339     void onVSyncReceived(HWComposer* composer, int type, nsecs_t timestamp) override;
340     void onHotplugReceived(HWComposer* composer, int disp, bool connected) override;
341     void onInvalidateReceived(HWComposer* composer) override;
342 #endif
343 
344     /* ------------------------------------------------------------------------
345      * Message handling
346      */
347     void waitForEvent();
348     // Can only be called from the main thread or with mStateLock held
349     void signalTransaction();
350     // Can only be called from the main thread or with mStateLock held
351     void signalLayerUpdate();
352     void signalRefresh();
353 
354     // called on the main thread in response to initializeDisplays()
355     void onInitializeDisplays();
356     // called on the main thread in response to setActiveConfig()
357     void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
358     // called on the main thread in response to setPowerMode()
359 #ifdef USE_HWC2
360     void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode,
361                               bool stateLockHeld);
362 #else
363     void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode);
364 #endif
365 
366     // Called on the main thread in response to setActiveColorMode()
367     void setActiveColorModeInternal(const sp<DisplayDevice>& hw, android_color_mode_t colorMode);
368 
369     // Called on the main thread in response to enableVSyncInjections()
370     void enableVSyncInjectionsInternal(bool enable);
371 
372     // Returns whether the transaction actually modified any state
373     bool handleMessageTransaction();
374 
375     // Returns whether a new buffer has been latched (see handlePageFlip())
376     bool handleMessageInvalidate();
377 
378     void handleMessageRefresh();
379 
380     void handleTransaction(uint32_t transactionFlags);
381     void handleTransactionLocked(uint32_t transactionFlags);
382 
383     void updateCursorAsync();
384 
385     /* handlePageFlip - latch a new buffer if available and compute the dirty
386      * region. Returns whether a new buffer has been latched, i.e., whether it
387      * is necessary to perform a refresh during this vsync.
388      */
389     bool handlePageFlip();
390 
391     /* ------------------------------------------------------------------------
392      * Transactions
393      */
394     uint32_t getTransactionFlags(uint32_t flags);
395     uint32_t peekTransactionFlags();
396     // Can only be called from the main thread or with mStateLock held
397     uint32_t setTransactionFlags(uint32_t flags);
398     void commitTransaction();
399     uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
400     uint32_t setDisplayStateLocked(const DisplayState& s);
401 
402     /* ------------------------------------------------------------------------
403      * Layer management
404      */
405     status_t createLayer(const String8& name, const sp<Client>& client,
406             uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
407             uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
408             sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent);
409 
410     status_t createNormalLayer(const sp<Client>& client, const String8& name,
411             uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
412             sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
413             sp<Layer>* outLayer);
414 
415     status_t createDimLayer(const sp<Client>& client, const String8& name,
416             uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
417             sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
418 
419     String8 getUniqueLayerName(const String8& name);
420 
421     // called in response to the window-manager calling
422     // ISurfaceComposerClient::destroySurface()
423     status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
424 
425     // called when all clients have released all their references to
426     // this layer meaning it is entirely safe to destroy all
427     // resources associated to this layer.
428     status_t onLayerDestroyed(const wp<Layer>& layer);
429 
430     // remove a layer from SurfaceFlinger immediately
431     status_t removeLayer(const sp<Layer>& layer, bool topLevelOnly = false);
432 
433     // add a layer to SurfaceFlinger
434     status_t addClientLayer(const sp<Client>& client,
435             const sp<IBinder>& handle,
436             const sp<IGraphicBufferProducer>& gbc,
437             const sp<Layer>& lbc,
438             const sp<Layer>& parent);
439 
440     /* ------------------------------------------------------------------------
441      * Boot animation, on/off animations and screen capture
442      */
443 
444     void startBootAnim();
445 
446     void renderScreenImplLocked(
447             const sp<const DisplayDevice>& hw,
448             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
449             int32_t minLayerZ, int32_t maxLayerZ,
450             bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation);
451 
452 #ifdef USE_HWC2
453     status_t captureScreenImplLocked(const sp<const DisplayDevice>& device,
454                                      ANativeWindowBuffer* buffer, Rect sourceCrop,
455                                      uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
456                                      int32_t maxLayerZ, bool useIdentityTransform,
457                                      Transform::orientation_flags rotation, bool isLocalScreenshot,
458                                      int* outSyncFd);
459 #else
460     status_t captureScreenImplLocked(
461             const sp<const DisplayDevice>& hw,
462             const sp<IGraphicBufferProducer>& producer,
463             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
464             int32_t minLayerZ, int32_t maxLayerZ,
465             bool useIdentityTransform, Transform::orientation_flags rotation,
466             bool isLocalScreenshot);
467 #endif
468 
469     sp<StartPropertySetThread> mStartPropertySetThread = nullptr;
470 
471     /* ------------------------------------------------------------------------
472      * Properties
473      */
474     void readPersistentProperties();
475 
476     /* ------------------------------------------------------------------------
477      * EGL
478      */
479     size_t getMaxTextureSize() const;
480     size_t getMaxViewportDims() const;
481 
482     /* ------------------------------------------------------------------------
483      * Display and layer stack management
484      */
485     // called when starting, or restarting after system_server death
486     void initializeDisplays();
487 
488     // Create an IBinder for a builtin display and add it to current state
489     void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
490 
491 
getDisplayDevice(const wp<IBinder> & dpy)492     sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
493       Mutex::Autolock _l(mStateLock);
494       return getDisplayDeviceLocked(dpy);
495     }
496 
getDisplayDevice(const wp<IBinder> & dpy)497     sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
498       Mutex::Autolock _l(mStateLock);
499       return getDisplayDeviceLocked(dpy);
500     }
501 
502     // NOTE: can only be called from the main thread or with mStateLock held
getDisplayDeviceLocked(const wp<IBinder> & dpy)503     sp<const DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& dpy) const {
504         return mDisplays.valueFor(dpy);
505     }
506 
507     // NOTE: can only be called from the main thread or with mStateLock held
getDisplayDeviceLocked(const wp<IBinder> & dpy)508     sp<DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& dpy) {
509         return mDisplays.valueFor(dpy);
510     }
511 
getDefaultDisplayDeviceLocked()512     sp<const DisplayDevice> getDefaultDisplayDeviceLocked() const {
513         return getDisplayDeviceLocked(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
514     }
515 
516     void createDefaultDisplayDevice();
517 
getDisplayType(const sp<IBinder> & display)518     int32_t getDisplayType(const sp<IBinder>& display) {
519         if (!display.get()) return NAME_NOT_FOUND;
520         for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
521             if (display == mBuiltinDisplays[i]) {
522                 return i;
523             }
524         }
525         return NAME_NOT_FOUND;
526     }
527 
528     // mark a region of a layer stack dirty. this updates the dirty
529     // region of all screens presenting this layer stack.
530     void invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty);
531 
532 #ifndef USE_HWC2
533     int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
534 #endif
535 
536     /* ------------------------------------------------------------------------
537      * H/W composer
538      */
539 
getHwComposer()540     HWComposer& getHwComposer() const { return *mHwc; }
541 
542     /* ------------------------------------------------------------------------
543      * Compositing
544      */
545     void invalidateHwcGeometry();
546     void computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
547             Region& dirtyRegion, Region& opaqueRegion);
548 
549     void preComposition(nsecs_t refreshStartTime);
550     void postComposition(nsecs_t refreshStartTime);
551     void updateCompositorTiming(
552             nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
553             std::shared_ptr<FenceTime>& presentFenceTime);
554     void setCompositorTimingSnapped(
555             nsecs_t vsyncPhase, nsecs_t vsyncInterval,
556             nsecs_t compositeToPresentLatency);
557     void rebuildLayerStacks();
558 
559     // Given a dataSpace, returns the appropriate color_mode to use
560     // to display that dataSpace.
561     android_color_mode pickColorMode(android_dataspace dataSpace) const;
562     android_dataspace bestTargetDataSpace(android_dataspace a, android_dataspace b) const;
563 
564     mat4 computeSaturationMatrix() const;
565 
566     void setUpHWComposer();
567     void doComposition();
568     void doDebugFlashRegions();
569     void doDisplayComposition(const sp<const DisplayDevice>& displayDevice, const Region& dirtyRegion);
570 
571     // compose surfaces for display hw. this fails if using GL and the surface
572     // has been destroyed and is no longer valid.
573     bool doComposeSurfaces(const sp<const DisplayDevice>& displayDevice, const Region& dirty);
574 
575     void postFramebuffer();
576     void drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const;
577 
578     /* ------------------------------------------------------------------------
579      * Display management
580      */
581 
582     /* ------------------------------------------------------------------------
583      * VSync
584      */
585     void enableHardwareVsync();
586     void resyncToHardwareVsync(bool makeAvailable);
587     void disableHardwareVsync(bool makeUnavailable);
588 
589 public:
590     void resyncWithRateLimit();
591     void getCompositorTiming(CompositorTiming* compositorTiming);
592 private:
593 
594     /* ------------------------------------------------------------------------
595      * Debugging & dumpsys
596      */
597     void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
598     void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
599     void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
600     void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
601     bool startDdmConnection();
602     void appendSfConfigString(String8& result) const;
603     void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
604             const sp<const DisplayDevice>& hw,
605             int32_t minLayerZ, int32_t maxLayerZ);
606 
607     void logFrameStats();
608 
609     void dumpStaticScreenStats(String8& result) const;
610     // Not const because each Layer needs to query Fences and cache timestamps.
611     void dumpFrameEventsLocked(String8& result);
612 
613     void recordBufferingStats(const char* layerName,
614             std::vector<OccupancyTracker::Segment>&& history);
615     void dumpBufferingStats(String8& result) const;
616     void dumpWideColorInfo(String8& result) const;
617 
isLayerTripleBufferingDisabled()618     bool isLayerTripleBufferingDisabled() const {
619         return this->mLayerTripleBufferingDisabled;
620     }
621 
622 #ifdef USE_HWC2
623     /* ------------------------------------------------------------------------
624      * VrFlinger
625      */
626     void resetDisplayState();
627 
628     // Check to see if we should handoff to vr flinger.
629     void updateVrFlinger();
630 #endif
631 
632     /* ------------------------------------------------------------------------
633      * Attributes
634      */
635 
636     // access must be protected by mStateLock
637     mutable Mutex mStateLock;
638     State mCurrentState{LayerVector::StateSet::Current};
639     volatile int32_t mTransactionFlags;
640     Condition mTransactionCV;
641     bool mTransactionPending;
642     bool mAnimTransactionPending;
643     SortedVector< sp<Layer> > mLayersPendingRemoval;
644     SortedVector< wp<IBinder> > mGraphicBufferProducerList;
645 
646     // protected by mStateLock (but we could use another lock)
647     bool mLayersRemoved;
648     bool mLayersAdded;
649 
650     // access must be protected by mInvalidateLock
651     volatile int32_t mRepaintEverything;
652 
653     // The current hardware composer interface.
654     //
655     // The following thread safety rules apply when accessing mHwc, either
656     // directly or via getHwComposer():
657     //
658     // 1. When recreating mHwc, acquire mStateLock. We currently recreate mHwc
659     //    only when switching into and out of vr. Recreating mHwc must only be
660     //    done on the main thread.
661     //
662     // 2. When accessing mHwc on the main thread, it's not necessary to acquire
663     //    mStateLock.
664     //
665     // 3. When accessing mHwc on a thread other than the main thread, we always
666     //    need to acquire mStateLock. This is because the main thread could be
667     //    in the process of destroying the current mHwc instance.
668     //
669     // The above thread safety rules only apply to SurfaceFlinger.cpp. In
670     // SurfaceFlinger_hwc1.cpp we create mHwc at surface flinger init and never
671     // destroy it, so it's always safe to access mHwc from any thread without
672     // acquiring mStateLock.
673     std::unique_ptr<HWComposer> mHwc;
674 
675     // constant members (no synchronization needed for access)
676     RenderEngine* mRenderEngine;
677     nsecs_t mBootTime;
678     bool mGpuToCpuSupported;
679     sp<EventThread> mEventThread;
680     sp<EventThread> mSFEventThread;
681     sp<EventThread> mInjectorEventThread;
682     sp<InjectVSyncSource> mVSyncInjector;
683     sp<EventControlThread> mEventControlThread;
684     EGLContext mEGLContext;
685     EGLDisplay mEGLDisplay;
686     sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
687 
688     // Can only accessed from the main thread, these members
689     // don't need synchronization
690     State mDrawingState{LayerVector::StateSet::Drawing};
691     bool mVisibleRegionsDirty;
692 #ifndef USE_HWC2
693     bool mHwWorkListDirty;
694 #else
695     bool mGeometryInvalid;
696 #endif
697     bool mAnimCompositionPending;
698 #ifdef USE_HWC2
699     std::vector<sp<Layer>> mLayersWithQueuedFrames;
700     sp<Fence> mPreviousPresentFence = Fence::NO_FENCE;
701     bool mHadClientComposition = false;
702 #endif
703     FenceTimeline mGlCompositionDoneTimeline;
704     FenceTimeline mDisplayTimeline;
705 
706     // this may only be written from the main thread with mStateLock held
707     // it may be read from other threads with mStateLock held
708     DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
709 
710     // don't use a lock for these, we don't care
711     int mDebugRegion;
712     int mDebugDDMS;
713     int mDebugDisableHWC;
714     int mDebugDisableTransformHint;
715     volatile nsecs_t mDebugInSwapBuffers;
716     nsecs_t mLastSwapBufferTime;
717     volatile nsecs_t mDebugInTransaction;
718     nsecs_t mLastTransactionTime;
719     bool mBootFinished;
720     bool mForceFullDamage;
721 #ifdef USE_HWC2
722     bool mPropagateBackpressure = true;
723 #endif
724     SurfaceInterceptor mInterceptor;
725     bool mUseHwcVirtualDisplays = false;
726 
727     // Restrict layers to use two buffers in their bufferqueues.
728     bool mLayerTripleBufferingDisabled = false;
729 
730     // these are thread safe
731     mutable MessageQueue mEventQueue;
732     FrameTracker mAnimFrameTracker;
733     DispSync mPrimaryDispSync;
734 
735     // protected by mDestroyedLayerLock;
736     mutable Mutex mDestroyedLayerLock;
737     Vector<Layer const *> mDestroyedLayers;
738 
739     // protected by mHWVsyncLock
740     Mutex mHWVsyncLock;
741     bool mPrimaryHWVsyncEnabled;
742     bool mHWVsyncAvailable;
743 
744     // protected by mCompositorTimingLock;
745     mutable std::mutex mCompositorTimingLock;
746     CompositorTiming mCompositorTiming;
747 
748     // Only accessed from the main thread.
749     struct CompositePresentTime {
750         nsecs_t composite { -1 };
751         std::shared_ptr<FenceTime> display { FenceTime::NO_FENCE };
752     };
753     std::queue<CompositePresentTime> mCompositePresentTimes;
754 
755     std::atomic<bool> mRefreshPending{false};
756 
757     /* ------------------------------------------------------------------------
758      * Feature prototyping
759      */
760 
761     bool mInjectVSyncs;
762 
763     Daltonizer mDaltonizer;
764 #ifndef USE_HWC2
765     bool mDaltonize;
766 #endif
767 
768     mat4 mPreviousColorMatrix;
769     mat4 mColorMatrix;
770     bool mHasColorMatrix;
771 
772     // Static screen stats
773     bool mHasPoweredOff;
774     static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
775     nsecs_t mFrameBuckets[NUM_BUCKETS];
776     nsecs_t mTotalTime;
777     std::atomic<nsecs_t> mLastSwapTime;
778 
779     size_t mNumLayers;
780 
781     // Double- vs. triple-buffering stats
782     struct BufferingStats {
BufferingStatsBufferingStats783         BufferingStats()
784           : numSegments(0),
785             totalTime(0),
786             twoBufferTime(0),
787             doubleBufferedTime(0),
788             tripleBufferedTime(0) {}
789 
790         size_t numSegments;
791         nsecs_t totalTime;
792 
793         // "Two buffer" means that a third buffer was never used, whereas
794         // "double-buffered" means that on average the segment only used two
795         // buffers (though it may have used a third for some part of the
796         // segment)
797         nsecs_t twoBufferTime;
798         nsecs_t doubleBufferedTime;
799         nsecs_t tripleBufferedTime;
800     };
801     mutable Mutex mBufferingStatsMutex;
802     std::unordered_map<std::string, BufferingStats> mBufferingStats;
803 
804     // Verify that transaction is being called by an approved process:
805     // either AID_GRAPHICS or AID_SYSTEM.
806     status_t CheckTransactCodeCredentials(uint32_t code);
807 
808 #ifdef USE_HWC2
809     std::unique_ptr<dvr::VrFlinger> mVrFlinger;
810     std::atomic<bool> mVrFlingerRequestsDisplay;
811     static bool useVrFlinger;
812     std::thread::id mMainThreadId;
813     // The composer sequence id is a monotonically increasing integer that we
814     // use to differentiate callbacks from different hardware composer
815     // instances. Each hardware composer instance gets a different sequence id.
816     int32_t mComposerSequenceId;
817 #endif
818 
819     float mSaturation = 1.0f;
820     bool mForceNativeColorMode = false;
821 };
822 }; // namespace android
823 
824 #endif // ANDROID_SURFACE_FLINGER_H
825