1 /*
2  * Copyright 2023 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 "LayerTracing.h"
20 
21 #include <perfetto/tracing.h>
22 
23 #include <atomic>
24 
25 namespace android {
26 
27 /*
28  * Thread local storage used for fast (lock free) read of data source's properties.
29  *
30  */
31 struct LayerDataSourceTlsState {
32     template <typename TraceContext>
LayerDataSourceTlsStateLayerDataSourceTlsState33     explicit LayerDataSourceTlsState(const TraceContext& trace_context) {
34         auto dataSource = trace_context.GetDataSourceLocked();
35         mMode = dataSource.valid()
36                 ? dataSource->GetMode()
37                 : perfetto::protos::pbzero::SurfaceFlingerLayersConfig::Mode::MODE_GENERATED;
38     }
39 
40     LayerTracing::Mode mMode;
41 };
42 
43 struct LayerDataSourceTraits : public perfetto::DefaultDataSourceTraits {
44     using TlsStateType = LayerDataSourceTlsState;
45 };
46 
47 /*
48  * Defines the Perfetto custom data source 'android.surfaceflinger.layers'.
49  *
50  * Registers the data source with Perfetto, listens to Perfetto events (setup/start/flush/stop)
51  * and writes trace packets to Perfetto.
52  *
53  */
54 class LayerDataSource : public perfetto::DataSource<LayerDataSource, LayerDataSourceTraits> {
55 public:
56     static void Initialize(LayerTracing&);
57     static void UnregisterLayerTracing();
58     void OnSetup(const SetupArgs&) override;
59     void OnStart(const StartArgs&) override;
60     void OnFlush(const FlushArgs&) override;
61     void OnStop(const StopArgs&) override;
62     LayerTracing::Mode GetMode() const;
63 
64     static constexpr auto* kName = "android.surfaceflinger.layers";
65     static constexpr perfetto::BufferExhaustedPolicy kBufferExhaustedPolicy =
66             perfetto::BufferExhaustedPolicy::kStall;
67     static constexpr bool kRequiresCallbacksUnderLock = false;
68 
69 private:
70     static std::atomic<LayerTracing*> mLayerTracing;
71     LayerTracing::Mode mMode;
72     std::uint32_t mFlags;
73 };
74 
75 } // namespace android
76 
77 PERFETTO_DECLARE_DATA_SOURCE_STATIC_MEMBERS(android::LayerDataSource);
78