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 std::atomic<bool> trace_lambda_enabled{false}; 63 64 // The overall TracingMuxerImpl instance id, which gets incremented by 65 // ResetForTesting. 66 uint32_t muxer_id_for_testing = 0; 67 68 // The central buffer id that all TraceWriter(s) created by this data source 69 // must target. 70 BufferId buffer_id = 0; 71 72 // The index within TracingMuxerImpl.backends_. Practically it allows to 73 // lookup the Producer object, and hence the IPC channel, for this data 74 // source. 75 TracingBackendId backend_id = 0; 76 77 // Each backend may connect to the tracing service multiple times if a 78 // disconnection occurs. This counter is used to uniquely identify each 79 // connection so that trace writers don't get reused across connections. 80 uint32_t backend_connection_id = 0; 81 82 // The instance id as assigned by the tracing service. Note that because a 83 // process can be connected to >1 services, this ID is not globally unique but 84 // is only unique within the scope of its backend. 85 // Only the tuple (backend_id, data_source_instance_id) is globally unique. 86 uint64_t data_source_instance_id = 0; 87 88 // Set to a non-0 target buffer reservation ID iff startup tracing is 89 // currently enabled for this data source. 90 std::atomic<uint16_t> startup_target_buffer_reservation{0}; 91 92 // If the data source was originally started for startup tracing, this is set 93 // to the startup session's ID. 94 uint64_t startup_session_id = 0; 95 96 // A hash of the trace config used by this instance. This is used to 97 // de-duplicate instances for data sources with identical names (e.g., track 98 // event). 99 uint64_t config_hash = 0; 100 101 // Similar to config_hash, but excludes target buffers and service-set fields 102 // for matching of startup-tracing data source instances to sessions later 103 // started by the service. 104 // Learn more: ComputeStartupConfigHash 105 uint64_t startup_config_hash = 0; 106 107 // If this data source is being intercepted (see Interceptor), this field 108 // contains the non-zero id of a registered interceptor which should receive 109 // trace packets for this session. Note: interceptor id 1 refers to the first 110 // element of TracingMuxerImpl::interceptors_ with successive numbers using 111 // the following slots. 112 uint32_t interceptor_id = 0; 113 114 // This lock is not held to implement Trace() and it's used only if the trace 115 // code wants to access its own data source state. 116 // This is to prevent that accessing the data source on an arbitrary embedder 117 // thread races with the internal IPC thread destroying the data source 118 // because of a end-of-tracing notification from the service. 119 // This lock is also used to protect access to a possible interceptor for this 120 // data source session. 121 std::recursive_mutex lock; 122 std::unique_ptr<DataSourceBase> data_source; 123 std::unique_ptr<InterceptorBase> interceptor; 124 }; 125 126 // This is to allow lazy-initialization and avoid static initializers and 127 // at-exit destructors. All the entries are initialized via placement-new when 128 // DataSource::Register() is called, see TracingMuxerImpl::RegisterDataSource(). 129 struct DataSourceStateStorage { 130 alignas(DataSourceState) char storage[sizeof(DataSourceState)]{}; 131 }; 132 133 // Per-DataSource-type global state. 134 struct DataSourceStaticState { 135 // System-wide unique id of the data source. 136 uint64_t id = 0; 137 138 // Unique index of the data source, assigned at registration time. 139 uint32_t index = kMaxDataSources; 140 141 // A bitmap that tells about the validity of each |instances| entry. When the 142 // i-th bit of the bitmap it's set, instances[i] is valid. 143 std::atomic<uint32_t> valid_instances{}; 144 std::array<DataSourceStateStorage, kMaxDataSourceInstances> instances{}; 145 146 // Incremented whenever incremental state should be reset for any instance of 147 // this data source. 148 std::atomic<uint32_t> incremental_state_generation{}; 149 150 // Can be used with a cached |valid_instances| bitmap. TryGetCachedDataSourceStaticState151 DataSourceState* TryGetCached(uint32_t cached_bitmap, size_t n) { 152 return cached_bitmap & (1 << n) 153 ? reinterpret_cast<DataSourceState*>(&instances[n]) 154 : nullptr; 155 } 156 TryGetDataSourceStaticState157 DataSourceState* TryGet(size_t n) { 158 return TryGetCached(valid_instances.load(std::memory_order_acquire), n); 159 } 160 CompilerAssertsDataSourceStaticState161 void CompilerAsserts() { 162 static_assert(sizeof(valid_instances.load()) * 8 >= kMaxDataSourceInstances, 163 "kMaxDataSourceInstances too high"); 164 } 165 ResetForTestingDataSourceStaticState166 void ResetForTesting() { 167 id = 0; 168 index = kMaxDataSources; 169 valid_instances.store(0, std::memory_order_release); 170 instances = {}; 171 incremental_state_generation.store(0, std::memory_order_release); 172 } 173 }; 174 175 // Per-DataSource-instance thread-local state. 176 struct DataSourceInstanceThreadLocalState { ResetDataSourceInstanceThreadLocalState177 void Reset() { *this = DataSourceInstanceThreadLocalState{}; } 178 179 std::unique_ptr<TraceWriterBase> trace_writer; 180 using ObjectWithDeleter = std::unique_ptr<void, void (*)(void*)>; 181 ObjectWithDeleter incremental_state = {nullptr, [](void*) {}}; 182 ObjectWithDeleter data_source_custom_tls = {nullptr, [](void*) {}}; 183 uint32_t incremental_state_generation = 0; 184 uint32_t muxer_id_for_testing = 0; 185 TracingBackendId backend_id = 0; 186 uint32_t backend_connection_id = 0; 187 BufferId buffer_id = 0; 188 uint64_t data_source_instance_id = 0; 189 bool is_intercepted = false; 190 uint64_t last_empty_packet_position = 0; 191 uint16_t startup_target_buffer_reservation = 0; 192 }; 193 194 // Per-DataSource-type thread-local state. 195 struct DataSourceThreadLocalState { 196 DataSourceStaticState* static_state = nullptr; 197 198 // Pointer to the parent tls object that holds us. Used to retrieve the 199 // generation, which is per-global-TLS and not per data-source. 200 TracingTLS* root_tls = nullptr; 201 202 // One entry per each data source instance. 203 std::array<DataSourceInstanceThreadLocalState, kMaxDataSourceInstances> 204 per_instance{}; 205 }; 206 207 } // namespace internal 208 } // namespace perfetto 209 210 #endif // INCLUDE_PERFETTO_TRACING_INTERNAL_DATA_SOURCE_INTERNAL_H_ 211