1 /*
2  * Copyright (C) 2019 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 INCLUDE_PERFETTO_TRACING_INTERNAL_DATA_SOURCE_INTERNAL_H_
18 #define INCLUDE_PERFETTO_TRACING_INTERNAL_DATA_SOURCE_INTERNAL_H_
19 
20 #include <stddef.h>
21 #include <stdint.h>
22 
23 #include <array>
24 #include <atomic>
25 #include <functional>
26 #include <memory>
27 #include <mutex>
28 
29 // No perfetto headers (other than tracing/api and protozero) should be here.
30 #include "perfetto/tracing/buffer_exhausted_policy.h"
31 #include "perfetto/tracing/internal/basic_types.h"
32 #include "perfetto/tracing/trace_writer_base.h"
33 
34 namespace perfetto {
35 
36 class DataSourceBase;
37 class InterceptorBase;
38 class TraceWriterBase;
39 
40 namespace internal {
41 
42 class TracingTLS;
43 
44 // This maintains the internal state of a data source instance that is used only
45 // to implement the tracing mechanics and is not exposed to the API client.
46 // There is one of these object per DataSource instance (up to
47 // kMaxDataSourceInstances).
48 struct DataSourceState {
49   // This boolean flag determines whether the DataSource::Trace() method should
50   // do something or be a no-op. This flag doesn't give the full guarantee
51   // that tracing data will be visible in the trace, it just makes it so that
52   // the client attemps writing trace data and interacting with the service.
53   // For instance, when a tracing session ends the service will reject data
54   // commits that arrive too late even if the producer hasn't received the stop
55   // IPC message.
56   // This flag is set right before calling OnStart() and cleared right before
57   // calling OnStop(), unless using HandleStopAsynchronously() (see comments
58   // in data_source.h).
59   // Keep this flag as the first field. This allows the compiler to directly
60   // dereference the DataSourceState* pointer in the trace fast-path without
61   // doing extra pointr arithmetic.
62   bool trace_lambda_enabled = false;
63 
64   // The central buffer id that all TraceWriter(s) created by this data source
65   // must target.
66   BufferId buffer_id = 0;
67 
68   // The index within TracingMuxerImpl.backends_. Practically it allows to
69   // lookup the Producer object, and hence the IPC channel, for this data
70   // source.
71   TracingBackendId backend_id = 0;
72 
73   // Each backend may connect to the tracing service multiple times if a
74   // disconnection occurs. This counter is used to uniquely identify each
75   // connection so that trace writers don't get reused across connections.
76   uint32_t backend_connection_id = 0;
77 
78   // The instance id as assigned by the tracing service. Note that because a
79   // process can be connected to >1 services, this ID is not globally unique but
80   // is only unique within the scope of its backend.
81   // Only the tuple (backend_id, data_source_instance_id) is globally unique.
82   uint64_t data_source_instance_id = 0;
83 
84   // A hash of the trace config used by this instance. This is used to
85   // de-duplicate instances for data sources with identical names (e.g., track
86   // event).
87   uint64_t config_hash = 0;
88 
89   // If this data source is being intercepted (see Interceptor), this field
90   // contains the non-zero id of a registered interceptor which should receive
91   // trace packets for this session. Note: interceptor id 1 refers to the first
92   // element of TracingMuxerImpl::interceptors_ with successive numbers using
93   // the following slots.
94   uint32_t interceptor_id = 0;
95 
96   // This lock is not held to implement Trace() and it's used only if the trace
97   // code wants to access its own data source state.
98   // This is to prevent that accessing the data source on an arbitrary embedder
99   // thread races with the internal IPC thread destroying the data source
100   // because of a end-of-tracing notification from the service.
101   // This lock is also used to protect access to a possible interceptor for this
102   // data source session.
103   std::recursive_mutex lock;
104   std::unique_ptr<DataSourceBase> data_source;
105   std::unique_ptr<InterceptorBase> interceptor;
106 };
107 
108 // This is to allow lazy-initialization and avoid static initializers and
109 // at-exit destructors. All the entries are initialized via placement-new when
110 // DataSource::Register() is called, see TracingMuxerImpl::RegisterDataSource().
111 struct DataSourceStateStorage {
112   alignas(DataSourceState) char storage[sizeof(DataSourceState)]{};
113 };
114 
115 // Per-DataSource-type global state.
116 struct DataSourceStaticState {
117   // Unique index of the data source, assigned at registration time.
118   uint32_t index = kMaxDataSources;
119 
120   // A bitmap that tells about the validity of each |instances| entry. When the
121   // i-th bit of the bitmap it's set, instances[i] is valid.
122   std::atomic<uint32_t> valid_instances{};
123   std::array<DataSourceStateStorage, kMaxDataSourceInstances> instances{};
124 
125   // Incremented whenever incremental state should be reset for any instance of
126   // this data source.
127   std::atomic<uint32_t> incremental_state_generation{};
128 
129   // Can be used with a cached |valid_instances| bitmap.
TryGetCachedDataSourceStaticState130   DataSourceState* TryGetCached(uint32_t cached_bitmap, size_t n) {
131     return cached_bitmap & (1 << n)
132                ? reinterpret_cast<DataSourceState*>(&instances[n])
133                : nullptr;
134   }
135 
TryGetDataSourceStaticState136   DataSourceState* TryGet(size_t n) {
137     return TryGetCached(valid_instances.load(std::memory_order_acquire), n);
138   }
139 
CompilerAssertsDataSourceStaticState140   void CompilerAsserts() {
141     static_assert(sizeof(valid_instances.load()) * 8 >= kMaxDataSourceInstances,
142                   "kMaxDataSourceInstances too high");
143   }
144 };
145 
146 // Per-DataSource-instance thread-local state.
147 struct DataSourceInstanceThreadLocalState {
148   using IncrementalStatePointer = std::unique_ptr<void, void (*)(void*)>;
149 
ResetDataSourceInstanceThreadLocalState150   void Reset() {
151     trace_writer.reset();
152     incremental_state.reset();
153     backend_id = 0;
154     backend_connection_id = 0;
155     buffer_id = 0;
156     data_source_instance_id = 0;
157     incremental_state_generation = 0;
158     is_intercepted = false;
159   }
160 
161   std::unique_ptr<TraceWriterBase> trace_writer;
162   IncrementalStatePointer incremental_state = {nullptr, [](void*) {}};
163   uint32_t incremental_state_generation;
164   TracingBackendId backend_id;
165   uint32_t backend_connection_id;
166   BufferId buffer_id;
167   uint64_t data_source_instance_id;
168   bool is_intercepted;
169 };
170 
171 // Per-DataSource-type thread-local state.
172 struct DataSourceThreadLocalState {
173   DataSourceStaticState* static_state = nullptr;
174 
175   // Pointer to the parent tls object that holds us. Used to retrieve the
176   // generation, which is per-global-TLS and not per data-source.
177   TracingTLS* root_tls = nullptr;
178 
179   // One entry per each data source instance.
180   std::array<DataSourceInstanceThreadLocalState, kMaxDataSourceInstances>
181       per_instance{};
182 };
183 
184 }  // namespace internal
185 }  // namespace perfetto
186 
187 #endif  // INCLUDE_PERFETTO_TRACING_INTERNAL_DATA_SOURCE_INTERNAL_H_
188