Fix a long standing locking issue with tracing thread

If winscope tracing is enabled, the tracing thread will read the drawing
state if the visible region changes and writes the state it to a proto.
This has a few issues: layer drawing state was being committed without
holding the tracing lock, layers could be destroyed when
finalizePendingOutputLayers (without holding the tracing lock) making
access to offscreenlayers invalid, finally we could get miss a trace
entry or have invalid entries.

This fix takes the tracing lock while committing the layer drawing
states and removes accessing the drawing states which are modified
later. It also identifies any missed entries.

In S, we will look at simplifying the tracing model to store a delta
of changes per layer.

Fixes: b/152010382, b/144918813, b/140854698

Test: w/ hwasan build and winscope enabled atest SurfaceFlinger_test libgui_test
Test: w/ hwasan build and winscope enabled go/wm-tests

Change-Id: I71c7b8e6567767ef97d82c5ea2e06a82ecc3c17a
diff --git a/services/surfaceflinger/SurfaceTracing.h b/services/surfaceflinger/SurfaceTracing.h
index 83872ed..a00e5d6 100644
--- a/services/surfaceflinger/SurfaceTracing.h
+++ b/services/surfaceflinger/SurfaceTracing.h
@@ -49,6 +49,7 @@
     status_t writeToFile();
     bool isEnabled() const;
     void notify(const char* where);
+    void notifyLocked(const char* where) NO_THREAD_SAFETY_ANALYSIS /* REQUIRES(mSfLock) */;
 
     void setBufferSize(size_t bufferSizeInByte);
     void writeToFileAsync();
@@ -57,11 +58,15 @@
     enum : uint32_t {
         TRACE_CRITICAL = 1 << 0,
         TRACE_INPUT = 1 << 1,
-        TRACE_EXTRA = 1 << 2,
-        TRACE_HWC = 1 << 3,
+        TRACE_COMPOSITION = 1 << 2,
+        TRACE_EXTRA = 1 << 3,
+        TRACE_HWC = 1 << 4,
         TRACE_ALL = 0xffffffff
     };
     void setTraceFlags(uint32_t flags);
+    bool flagIsSetLocked(uint32_t flags) NO_THREAD_SAFETY_ANALYSIS /* REQUIRES(mSfLock) */ {
+        return (mTraceFlags & flags) == flags;
+    }
 
 private:
     static constexpr auto kDefaultBufferCapInByte = 5_MB;
@@ -103,6 +108,8 @@
     std::mutex& mSfLock;
     uint32_t mTraceFlags GUARDED_BY(mSfLock) = TRACE_CRITICAL | TRACE_INPUT;
     const char* mWhere GUARDED_BY(mSfLock) = "";
+    uint32_t mMissedTraceEntries GUARDED_BY(mSfLock) = 0;
+    bool mTracingInProgress GUARDED_BY(mSfLock) = false;
 
     mutable std::mutex mTraceLock;
     LayersTraceBuffer mBuffer GUARDED_BY(mTraceLock);