• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 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_EXT_TRACING_CORE_SHARED_MEMORY_ARBITER_H_
18 #define INCLUDE_PERFETTO_EXT_TRACING_CORE_SHARED_MEMORY_ARBITER_H_
19 
20 #include <stddef.h>
21 
22 #include <functional>
23 #include <memory>
24 #include <vector>
25 
26 #include "perfetto/base/export.h"
27 #include "perfetto/ext/tracing/core/basic_types.h"
28 #include "perfetto/ext/tracing/core/tracing_service.h"
29 #include "perfetto/tracing/buffer_exhausted_policy.h"
30 
31 namespace perfetto {
32 
33 namespace base {
34 class TaskRunner;
35 }
36 
37 class SharedMemory;
38 class TraceWriter;
39 
40 // Used by the Producer-side of the transport layer to vend TraceWriters
41 // from the SharedMemory it receives from the Service-side.
42 class PERFETTO_EXPORT_COMPONENT SharedMemoryArbiter {
43  public:
44   virtual ~SharedMemoryArbiter();
45 
46   // Creates a new TraceWriter and assigns it a new WriterID. The WriterID is
47   // written in each chunk header owned by a given TraceWriter and is used by
48   // the Service to reconstruct TracePackets written by the same TraceWriter.
49   // Returns null impl of TraceWriter if all WriterID slots are exhausted. The
50   // writer will commit to the provided |target_buffer|. If the arbiter was
51   // created via CreateUnbound() or CreateStartupTraceWriter() is later used,
52   // only BufferExhaustedPolicy::kDrop is supported.
53   virtual std::unique_ptr<TraceWriter> CreateTraceWriter(
54       BufferID target_buffer,
55       BufferExhaustedPolicy buffer_exhausted_policy =
56           BufferExhaustedPolicy::kDefault) = 0;
57 
58   // Creates a TraceWriter that will commit to the target buffer with the given
59   // reservation ID (creating a new reservation for this ID if none exists yet).
60   // The buffer reservation should be bound to an actual BufferID via
61   // BindStartupTargetBuffer() once the actual BufferID is known. Calling this
62   // method may transition the arbiter into unbound state (see state diagram in
63   // SharedMemoryArbiterImpl's class comment) and requires that all (past and
64   // future) TraceWriters are created with BufferExhaustedPolicy::kDrop.
65   //
66   // While any unbound buffer reservation exists, all commits will be buffered
67   // until all reservations were bound. Thus, until all reservations are bound,
68   // the data written to the SMB will not be consumed by the service - the SMB
69   // size should be chosen with this in mind. Startup writers always use
70   // BufferExhaustedPolicy::kDrop, as we cannot feasibly stall while not
71   // flushing to the service.
72   //
73   // The |target_buffer_reservation_id| should be greater than 0 but can
74   // otherwise be freely chosen by the producer and is only used to translate
75   // packets into the actual buffer id once
76   // BindStartupTargetBuffer(reservation_id) is called. For example, Chrome uses
77   // startup tracing not only for the first, but also subsequent tracing
78   // sessions (to enable tracing in the browser process before it instructs the
79   // tracing service to start tracing asynchronously, minimizing trace data loss
80   // in the meantime), and increments the reservation ID between sessions.
81   // Similarly, if more than a single target buffer per session is required
82   // (e.g. for two different data sources), different reservation IDs should be
83   // chosen for different target buffers.
84   virtual std::unique_ptr<TraceWriter> CreateStartupTraceWriter(
85       uint16_t target_buffer_reservation_id) = 0;
86 
87   // Should only be called on unbound SharedMemoryArbiters. Binds the arbiter to
88   // the provided ProducerEndpoint and TaskRunner. Should be called only once
89   // and on the provided |TaskRunner|. Usually called by the producer (i.e., no
90   // specific data source) once it connects to the service. Both the endpoint
91   // and task runner should remain valid for the remainder of the arbiter's
92   // lifetime.
93   virtual void BindToProducerEndpoint(TracingService::ProducerEndpoint*,
94                                       base::TaskRunner*) = 0;
95 
96   // Binds commits from TraceWriters created via CreateStartupTraceWriter() with
97   // the given |target_buffer_reservation_id| to |target_buffer_id|. May only be
98   // called once per |target_buffer_reservation_id|. Should be called on the
99   // arbiter's TaskRunner, and after BindToProducerEndpoint() was called.
100   // Usually, it is called by a specific data source, after it received its
101   // configuration (including the target buffer ID) from the service.
102   virtual void BindStartupTargetBuffer(uint16_t target_buffer_reservation_id,
103                                        BufferID target_buffer_id) = 0;
104 
105   // Treat the reservation as resolved to an invalid buffer. Commits for this
106   // reservation will be flushed to the service ASAP. The service will free
107   // committed chunks but otherwise ignore them. The producer can call this
108   // method, for example, if connection to the tracing service failed or the
109   // session was stopped concurrently before the connection was established.
110   virtual void AbortStartupTracingForReservation(
111       uint16_t target_buffer_reservation_id) = 0;
112 
113   // Notifies the service that all data for the given FlushRequestID has been
114   // committed in the shared memory buffer. Should only be called while bound.
115   virtual void NotifyFlushComplete(FlushRequestID) = 0;
116 
117   // Sets the duration during which commits are batched. Args:
118   // |batch_commits_duration_ms|: The length of the period, during which commits
119   // by all trace writers are accumulated, before being sent to the service.
120   // When the period ends, all accumulated commits are flushed. On the first
121   // commit after the last flush, another delayed flush is scheduled to run in
122   // |batch_commits_duration_ms|. If an immediate flush occurs (via
123   // FlushPendingCommitDataRequests()) during a batching period, any
124   // accumulated commits up to that point will be sent to the service
125   // immediately. And when the batching period ends, the commits that occurred
126   // after the immediate flush will also be sent to the service.
127   //
128   // If the duration has already been set to a non-zero value before this method
129   // is called, and there is already a scheduled flush with the previously-set
130   // duration, the new duration will take effect after the scheduled flush
131   // occurs.
132   //
133   // If |batch_commits_duration_ms| is non-zero, batched data that hasn't been
134   // sent could be lost at the end of a tracing session. To avoid this,
135   // producers should make sure that FlushPendingCommitDataRequests is called
136   // after the last TraceWriter write and before the service has stopped
137   // listening for commits from the tracing session's data sources (i.e.
138   // data sources should stop asynchronously, see
139   // DataSourceDescriptor.will_notify_on_stop=true).
140   virtual void SetBatchCommitsDuration(uint32_t batch_commits_duration_ms) = 0;
141 
142   // Called to enable direct producer-side patching of chunks that have not yet
143   // been committed to the service. The return value indicates whether direct
144   // patching was successfully enabled. It will be true if
145   // SharedMemoryArbiter::SetDirectSMBPatchingSupportedByService has been called
146   // and false otherwise.
147   virtual bool EnableDirectSMBPatching() = 0;
148 
149   // When the producer and service live in separate processes, this method
150   // should be called if the producer receives an
151   // InitializeConnectionResponse.direct_smb_patching_supported set to true by
152   // the service (see producer_port.proto) .
153   //
154   // In the in-process case, the service will always support direct SMB patching
155   // and this method should always be called.
156   virtual void SetDirectSMBPatchingSupportedByService() = 0;
157 
158   // Forces an immediate commit of the completed packets, without waiting for
159   // the next task or for a batching period to end. Should only be called while
160   // bound.
161   virtual void FlushPendingCommitDataRequests(
162       std::function<void()> callback = {}) = 0;
163 
164   // Attempts to shut down this arbiter. This function prevents new trace
165   // writers from being created for this this arbiter, but if there are any
166   // existing trace writers, the shutdown cannot proceed and this funtion
167   // returns false. The caller should not delete the arbiter before all of its
168   // associated trace writers have been destroyed and this function returns
169   // true.
170   virtual bool TryShutdown() = 0;
171 
172   // Create a bound arbiter instance. Args:
173   // |SharedMemory|: the shared memory buffer to use.
174   // |page_size|: a multiple of 4KB that defines the granularity of tracing
175   // pages. See tradeoff considerations in shared_memory_abi.h.
176   // |ProducerEndpoint|: The service's producer endpoint used e.g. to commit
177   // chunks and register trace writers.
178   // |TaskRunner|: Task runner for perfetto's main thread, which executes the
179   // OnPagesCompleteCallback and IPC calls to the |ProducerEndpoint|.
180   //
181   // Implemented in src/core/shared_memory_arbiter_impl.cc.
182   static std::unique_ptr<SharedMemoryArbiter> CreateInstance(
183       SharedMemory*,
184       size_t page_size,
185       TracingService::ProducerEndpoint*,
186       base::TaskRunner*);
187 
188   // Create an unbound arbiter instance, which should later be bound to a
189   // ProducerEndpoint and TaskRunner by calling BindToProducerEndpoint(). The
190   // returned arbiter will ONLY support trace writers with
191   // BufferExhaustedPolicy::kDrop.
192   //
193   // An unbound SharedMemoryArbiter can be used to write to a producer-created
194   // SharedMemory buffer before the producer connects to the tracing service.
195   // The producer can then pass this SMB to the service when it connects (see
196   // TracingService::ConnectProducer).
197   //
198   // To trace into the SMB before the service starts the tracing session, trace
199   // writers can be obtained via CreateStartupTraceWriter() and later associated
200   // with a target buffer via BindStartupTargetBuffer(), once the target buffer
201   // is known.
202   //
203   // Implemented in src/core/shared_memory_arbiter_impl.cc. See CreateInstance()
204   // for comments about the arguments.
205   static std::unique_ptr<SharedMemoryArbiter> CreateUnboundInstance(
206       SharedMemory*,
207       size_t page_size);
208 };
209 
210 }  // namespace perfetto
211 
212 #endif  // INCLUDE_PERFETTO_EXT_TRACING_CORE_SHARED_MEMORY_ARBITER_H_
213