1 /*
2 * Copyright (C) 2017 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 #include "src/tracing/core/shared_memory_arbiter_impl.h"
18
19 #include <algorithm>
20 #include <limits>
21 #include <utility>
22
23 #include "perfetto/base/logging.h"
24 #include "perfetto/base/task_runner.h"
25 #include "perfetto/base/time.h"
26 #include "perfetto/ext/tracing/core/commit_data_request.h"
27 #include "perfetto/ext/tracing/core/shared_memory.h"
28 #include "perfetto/ext/tracing/core/shared_memory_abi.h"
29 #include "src/tracing/core/null_trace_writer.h"
30 #include "src/tracing/core/trace_writer_impl.h"
31
32 namespace perfetto {
33
34 using Chunk = SharedMemoryABI::Chunk;
35
36 namespace {
37 static_assert(sizeof(BufferID) == sizeof(uint16_t),
38 "The MaybeUnboundBufferID logic requires BufferID not to grow "
39 "above uint16_t.");
40
MakeTargetBufferIdForReservation(uint16_t reservation_id)41 MaybeUnboundBufferID MakeTargetBufferIdForReservation(uint16_t reservation_id) {
42 // Reservation IDs are stored in the upper bits.
43 PERFETTO_CHECK(reservation_id > 0);
44 return static_cast<MaybeUnboundBufferID>(reservation_id) << 16;
45 }
46
IsReservationTargetBufferId(MaybeUnboundBufferID buffer_id)47 bool IsReservationTargetBufferId(MaybeUnboundBufferID buffer_id) {
48 return (buffer_id >> 16) > 0;
49 }
50 } // namespace
51
52 // static
53 SharedMemoryABI::PageLayout SharedMemoryArbiterImpl::default_page_layout =
54 SharedMemoryABI::PageLayout::kPageDiv1;
55
56 // static
CreateInstance(SharedMemory * shared_memory,size_t page_size,ShmemMode mode,TracingService::ProducerEndpoint * producer_endpoint,base::TaskRunner * task_runner)57 std::unique_ptr<SharedMemoryArbiter> SharedMemoryArbiter::CreateInstance(
58 SharedMemory* shared_memory,
59 size_t page_size,
60 ShmemMode mode,
61 TracingService::ProducerEndpoint* producer_endpoint,
62 base::TaskRunner* task_runner) {
63 return std::unique_ptr<SharedMemoryArbiterImpl>(new SharedMemoryArbiterImpl(
64 shared_memory->start(), shared_memory->size(), mode, page_size,
65 producer_endpoint, task_runner));
66 }
67
68 // static
CreateUnboundInstance(SharedMemory * shared_memory,size_t page_size,ShmemMode mode)69 std::unique_ptr<SharedMemoryArbiter> SharedMemoryArbiter::CreateUnboundInstance(
70 SharedMemory* shared_memory,
71 size_t page_size,
72 ShmemMode mode) {
73 return std::unique_ptr<SharedMemoryArbiterImpl>(new SharedMemoryArbiterImpl(
74 shared_memory->start(), shared_memory->size(), mode, page_size,
75 /*producer_endpoint=*/nullptr, /*task_runner=*/nullptr));
76 }
77
SharedMemoryArbiterImpl(void * start,size_t size,ShmemMode mode,size_t page_size,TracingService::ProducerEndpoint * producer_endpoint,base::TaskRunner * task_runner)78 SharedMemoryArbiterImpl::SharedMemoryArbiterImpl(
79 void* start,
80 size_t size,
81 ShmemMode mode,
82 size_t page_size,
83 TracingService::ProducerEndpoint* producer_endpoint,
84 base::TaskRunner* task_runner)
85 : producer_endpoint_(producer_endpoint),
86 use_shmem_emulation_(mode == ShmemMode::kShmemEmulation),
87 task_runner_(task_runner),
88 shmem_abi_(reinterpret_cast<uint8_t*>(start), size, page_size, mode),
89 active_writer_ids_(kMaxWriterID),
90 fully_bound_(task_runner && producer_endpoint),
91 was_always_bound_(fully_bound_),
92 weak_ptr_factory_(this) {}
93
GetNewChunk(const SharedMemoryABI::ChunkHeader & header,BufferExhaustedPolicy buffer_exhausted_policy)94 Chunk SharedMemoryArbiterImpl::GetNewChunk(
95 const SharedMemoryABI::ChunkHeader& header,
96 BufferExhaustedPolicy buffer_exhausted_policy) {
97 int stall_count = 0;
98 unsigned stall_interval_us = 0;
99 bool task_runner_runs_on_current_thread = false;
100 static const unsigned kMaxStallIntervalUs = 100000;
101 static const int kLogAfterNStalls = 3;
102 static const int kFlushCommitsAfterEveryNStalls = 2;
103 static const int kAssertAtNStalls = 200;
104
105 for (;;) {
106 // TODO(primiano): Probably this lock is not really required and this code
107 // could be rewritten leveraging only the Try* atomic operations in
108 // SharedMemoryABI. But let's not be too adventurous for the moment.
109 {
110 std::unique_lock<std::mutex> scoped_lock(lock_);
111
112 // If ever unbound, we do not support stalling. In theory, we could
113 // support stalling for TraceWriters created after the arbiter and startup
114 // buffer reservations were bound, but to avoid raciness between the
115 // creation of startup writers and binding, we categorically forbid kStall
116 // mode.
117 PERFETTO_DCHECK(was_always_bound_ ||
118 buffer_exhausted_policy == BufferExhaustedPolicy::kDrop);
119
120 task_runner_runs_on_current_thread =
121 task_runner_ && task_runner_->RunsTasksOnCurrentThread();
122
123 // If more than half of the SMB.size() is filled with completed chunks for
124 // which we haven't notified the service yet (i.e. they are still enqueued
125 // in |commit_data_req_|), force a synchronous CommitDataRequest() even if
126 // we acquire a chunk, to reduce the likeliness of stalling the writer.
127 //
128 // We can only do this if we're writing on the same thread that we access
129 // the producer endpoint on, since we cannot notify the producer endpoint
130 // to commit synchronously on a different thread. Attempting to flush
131 // synchronously on another thread will lead to subtle bugs caused by
132 // out-of-order commit requests (crbug.com/919187#c28).
133 bool should_commit_synchronously =
134 task_runner_runs_on_current_thread &&
135 buffer_exhausted_policy == BufferExhaustedPolicy::kStall &&
136 commit_data_req_ && bytes_pending_commit_ >= shmem_abi_.size() / 2;
137
138 const size_t initial_page_idx = page_idx_;
139 for (size_t i = 0; i < shmem_abi_.num_pages(); i++) {
140 page_idx_ = (initial_page_idx + i) % shmem_abi_.num_pages();
141 bool is_new_page = false;
142
143 // TODO(primiano): make the page layout dynamic.
144 auto layout = SharedMemoryArbiterImpl::default_page_layout;
145
146 if (shmem_abi_.is_page_free(page_idx_)) {
147 // TODO(primiano): Use the |size_hint| here to decide the layout.
148 is_new_page = shmem_abi_.TryPartitionPage(page_idx_, layout);
149 }
150 uint32_t free_chunks;
151 if (is_new_page) {
152 free_chunks = (1 << SharedMemoryABI::kNumChunksForLayout[layout]) - 1;
153 } else {
154 free_chunks = shmem_abi_.GetFreeChunks(page_idx_);
155 }
156
157 for (uint32_t chunk_idx = 0; free_chunks;
158 chunk_idx++, free_chunks >>= 1) {
159 if (!(free_chunks & 1))
160 continue;
161 // We found a free chunk.
162 Chunk chunk = shmem_abi_.TryAcquireChunkForWriting(
163 page_idx_, chunk_idx, &header);
164 if (!chunk.is_valid())
165 continue;
166 if (stall_count > kLogAfterNStalls) {
167 PERFETTO_LOG("Recovered from stall after %d iterations",
168 stall_count);
169 }
170
171 if (should_commit_synchronously) {
172 // We can't flush while holding the lock.
173 scoped_lock.unlock();
174 FlushPendingCommitDataRequests();
175 return chunk;
176 } else {
177 return chunk;
178 }
179 }
180 }
181 } // scoped_lock
182
183 if (buffer_exhausted_policy == BufferExhaustedPolicy::kDrop) {
184 PERFETTO_DLOG("Shared memory buffer exhausted, returning invalid Chunk!");
185 return Chunk();
186 }
187
188 // Stalling is not supported if we were ever unbound (see earlier comment).
189 PERFETTO_CHECK(was_always_bound_);
190
191 // All chunks are taken (either kBeingWritten by us or kBeingRead by the
192 // Service).
193 if (stall_count++ == kLogAfterNStalls) {
194 PERFETTO_LOG("Shared memory buffer overrun! Stalling");
195 }
196
197 if (stall_count == kAssertAtNStalls) {
198 PERFETTO_FATAL(
199 "Shared memory buffer max stall count exceeded; possible deadlock");
200 }
201
202 // If the IPC thread itself is stalled because the current process has
203 // filled up the SMB, we need to make sure that the service can process and
204 // purge the chunks written by our process, by flushing any pending commit
205 // requests. Because other threads in our process can continue to
206 // concurrently grab, fill and commit any chunks purged by the service, it
207 // is possible that the SMB remains full and the IPC thread remains stalled,
208 // needing to flush the concurrently queued up commits again. This is
209 // particularly likely with in-process perfetto service where the IPC thread
210 // is the service thread. To avoid remaining stalled forever in such a
211 // situation, we attempt to flush periodically after every N stalls.
212 if (stall_count % kFlushCommitsAfterEveryNStalls == 0 &&
213 task_runner_runs_on_current_thread) {
214 // TODO(primiano): sending the IPC synchronously is a temporary workaround
215 // until the backpressure logic in probes_producer is sorted out. Until
216 // then the risk is that we stall the message loop waiting for the tracing
217 // service to consume the shared memory buffer (SMB) and, for this reason,
218 // never run the task that tells the service to purge the SMB. This must
219 // happen iff we are on the IPC thread, not doing this will cause
220 // deadlocks, doing this on the wrong thread causes out-of-order data
221 // commits (crbug.com/919187#c28).
222 FlushPendingCommitDataRequests();
223 } else {
224 base::SleepMicroseconds(stall_interval_us);
225 stall_interval_us =
226 std::min(kMaxStallIntervalUs, (stall_interval_us + 1) * 8);
227 }
228 }
229 }
230
ReturnCompletedChunk(Chunk chunk,MaybeUnboundBufferID target_buffer,PatchList * patch_list)231 void SharedMemoryArbiterImpl::ReturnCompletedChunk(
232 Chunk chunk,
233 MaybeUnboundBufferID target_buffer,
234 PatchList* patch_list) {
235 PERFETTO_DCHECK(chunk.is_valid());
236 const WriterID writer_id = chunk.writer_id();
237 UpdateCommitDataRequest(std::move(chunk), writer_id, target_buffer,
238 patch_list);
239 }
240
SendPatches(WriterID writer_id,MaybeUnboundBufferID target_buffer,PatchList * patch_list)241 void SharedMemoryArbiterImpl::SendPatches(WriterID writer_id,
242 MaybeUnboundBufferID target_buffer,
243 PatchList* patch_list) {
244 PERFETTO_DCHECK(!patch_list->empty() && patch_list->front().is_patched());
245 UpdateCommitDataRequest(Chunk(), writer_id, target_buffer, patch_list);
246 }
247
UpdateCommitDataRequest(Chunk chunk,WriterID writer_id,MaybeUnboundBufferID target_buffer,PatchList * patch_list)248 void SharedMemoryArbiterImpl::UpdateCommitDataRequest(
249 Chunk chunk,
250 WriterID writer_id,
251 MaybeUnboundBufferID target_buffer,
252 PatchList* patch_list) {
253 // Note: chunk will be invalid if the call came from SendPatches().
254 base::TaskRunner* task_runner_to_post_delayed_callback_on = nullptr;
255 // The delay with which the flush will be posted.
256 uint32_t flush_delay_ms = 0;
257 base::WeakPtr<SharedMemoryArbiterImpl> weak_this;
258 {
259 std::lock_guard<std::mutex> scoped_lock(lock_);
260
261 if (!commit_data_req_) {
262 commit_data_req_.reset(new CommitDataRequest());
263
264 // Flushing the commit is only supported while we're |fully_bound_|. If we
265 // aren't, we'll flush when |fully_bound_| is updated.
266 if (fully_bound_ && !delayed_flush_scheduled_) {
267 weak_this = weak_ptr_factory_.GetWeakPtr();
268 task_runner_to_post_delayed_callback_on = task_runner_;
269 flush_delay_ms = batch_commits_duration_ms_;
270 delayed_flush_scheduled_ = true;
271 }
272 }
273
274 CommitDataRequest::ChunksToMove* ctm = nullptr; // Set if chunk is valid.
275 // If a valid chunk is specified, return it and attach it to the request.
276 if (chunk.is_valid()) {
277 PERFETTO_DCHECK(chunk.writer_id() == writer_id);
278 uint8_t chunk_idx = chunk.chunk_idx();
279 bytes_pending_commit_ += chunk.size();
280 size_t page_idx;
281
282 ctm = commit_data_req_->add_chunks_to_move();
283 // If the chunk needs patching, it should not be marked as complete yet,
284 // because this would indicate to the service that the producer will not
285 // be writing to it anymore, while the producer might still apply patches
286 // to the chunk later on. In particular, when re-reading (e.g. because of
287 // periodic scraping) a completed chunk, the service expects the flags of
288 // that chunk not to be removed between reads. So, let's say the producer
289 // marked the chunk as complete here and the service then read it for the
290 // first time. If the producer then fully patched the chunk, thus removing
291 // the kChunkNeedsPatching flag, and the service re-read the chunk after
292 // the patching, the service would be thrown off by the removed flag.
293 if (direct_patching_enabled_ &&
294 (chunk.GetPacketCountAndFlags().second &
295 SharedMemoryABI::ChunkHeader::kChunkNeedsPatching)) {
296 page_idx = shmem_abi_.GetPageAndChunkIndex(std::move(chunk)).first;
297 } else {
298 // If the chunk doesn't need patching, we can mark it as complete
299 // immediately. This allows the service to read it in full while
300 // scraping, which would not be the case if the chunk was left in a
301 // kChunkBeingWritten state.
302 page_idx = shmem_abi_.ReleaseChunkAsComplete(std::move(chunk));
303 }
304
305 // DO NOT access |chunk| after this point, it has been std::move()-d
306 // above.
307 ctm->set_page(static_cast<uint32_t>(page_idx));
308 ctm->set_chunk(chunk_idx);
309 ctm->set_target_buffer(target_buffer);
310 }
311
312 // Process the completed patches for previous chunks from the |patch_list|.
313 CommitDataRequest::ChunkToPatch* last_patch_req = nullptr;
314 while (!patch_list->empty() && patch_list->front().is_patched()) {
315 Patch curr_patch = patch_list->front();
316 patch_list->pop_front();
317 // Patches for the same chunk are contiguous in the |patch_list|. So, to
318 // determine if there are any other patches that apply to the chunk that
319 // is being patched, check if the next patch in the |patch_list| applies
320 // to the same chunk.
321 bool chunk_needs_more_patching =
322 !patch_list->empty() &&
323 patch_list->front().chunk_id == curr_patch.chunk_id;
324
325 if (direct_patching_enabled_ &&
326 TryDirectPatchLocked(writer_id, curr_patch,
327 chunk_needs_more_patching)) {
328 continue;
329 }
330
331 // The chunk that this patch applies to has already been released to the
332 // service, so it cannot be patches here. Add the patch to the commit data
333 // request, so that it can be sent to the service and applied there.
334 if (!last_patch_req ||
335 last_patch_req->chunk_id() != curr_patch.chunk_id) {
336 last_patch_req = commit_data_req_->add_chunks_to_patch();
337 last_patch_req->set_writer_id(writer_id);
338 last_patch_req->set_chunk_id(curr_patch.chunk_id);
339 last_patch_req->set_target_buffer(target_buffer);
340 }
341 auto* patch = last_patch_req->add_patches();
342 patch->set_offset(curr_patch.offset);
343 patch->set_data(&curr_patch.size_field[0], curr_patch.size_field.size());
344 }
345
346 // Patches are enqueued in the |patch_list| in order and are notified to
347 // the service when the chunk is returned. The only case when the current
348 // patch list is incomplete is if there is an unpatched entry at the head of
349 // the |patch_list| that belongs to the same ChunkID as the last one we are
350 // about to send to the service.
351 if (last_patch_req && !patch_list->empty() &&
352 patch_list->front().chunk_id == last_patch_req->chunk_id()) {
353 last_patch_req->set_has_more_patches(true);
354 }
355
356 // If the buffer is filling up or if we are given a patch for a chunk
357 // that was already sent to the service, we don't want to wait for the next
358 // delayed flush to happen and we flush immediately. Otherwise, if we
359 // accumulate the patch and a crash occurs before the patch is sent, the
360 // service will not know of the patch and won't be able to reconstruct the
361 // trace.
362 if (fully_bound_ &&
363 (last_patch_req || bytes_pending_commit_ >= shmem_abi_.size() / 2)) {
364 weak_this = weak_ptr_factory_.GetWeakPtr();
365 task_runner_to_post_delayed_callback_on = task_runner_;
366 flush_delay_ms = 0;
367 }
368 } // scoped_lock(lock_)
369
370 // We shouldn't post tasks while locked.
371 // |task_runner_to_post_delayed_callback_on| remains valid after unlocking,
372 // because |task_runner_| is never reset.
373 if (task_runner_to_post_delayed_callback_on) {
374 task_runner_to_post_delayed_callback_on->PostDelayedTask(
375 [weak_this] {
376 if (!weak_this)
377 return;
378 {
379 std::lock_guard<std::mutex> scoped_lock(weak_this->lock_);
380 // Clear |delayed_flush_scheduled_|, allowing the next call to
381 // UpdateCommitDataRequest to start another batching period.
382 weak_this->delayed_flush_scheduled_ = false;
383 }
384 weak_this->FlushPendingCommitDataRequests();
385 },
386 flush_delay_ms);
387 }
388 }
389
TryDirectPatchLocked(WriterID writer_id,const Patch & patch,bool chunk_needs_more_patching)390 bool SharedMemoryArbiterImpl::TryDirectPatchLocked(
391 WriterID writer_id,
392 const Patch& patch,
393 bool chunk_needs_more_patching) {
394 // Search the chunks that are being batched in |commit_data_req_| for a chunk
395 // that needs patching and that matches the provided |writer_id| and
396 // |patch.chunk_id|. Iterate |commit_data_req_| in reverse, since
397 // |commit_data_req_| is appended to at the end with newly-returned chunks,
398 // and patches are more likely to apply to chunks that have been returned
399 // recently.
400 SharedMemoryABI::Chunk chunk;
401 bool chunk_found = false;
402 auto& chunks_to_move = commit_data_req_->chunks_to_move();
403 for (auto ctm_it = chunks_to_move.rbegin(); ctm_it != chunks_to_move.rend();
404 ++ctm_it) {
405 uint32_t layout = shmem_abi_.GetPageLayout(ctm_it->page());
406 auto chunk_state =
407 shmem_abi_.GetChunkStateFromLayout(layout, ctm_it->chunk());
408 // Note: the subset of |commit_data_req_| chunks that still need patching is
409 // also the subset of chunks that are still being written to. The rest of
410 // the chunks in |commit_data_req_| do not need patching and have already
411 // been marked as complete.
412 if (chunk_state != SharedMemoryABI::kChunkBeingWritten)
413 continue;
414
415 chunk =
416 shmem_abi_.GetChunkUnchecked(ctm_it->page(), layout, ctm_it->chunk());
417 if (chunk.writer_id() == writer_id &&
418 chunk.header()->chunk_id.load(std::memory_order_relaxed) ==
419 patch.chunk_id) {
420 chunk_found = true;
421 break;
422 }
423 }
424
425 if (!chunk_found) {
426 // The chunk has already been committed to the service and the patch cannot
427 // be applied in the producer.
428 return false;
429 }
430
431 // Apply the patch.
432 size_t page_idx;
433 uint8_t chunk_idx;
434 std::tie(page_idx, chunk_idx) = shmem_abi_.GetPageAndChunkIndex(chunk);
435 PERFETTO_DCHECK(shmem_abi_.GetChunkState(page_idx, chunk_idx) ==
436 SharedMemoryABI::ChunkState::kChunkBeingWritten);
437 auto chunk_begin = chunk.payload_begin();
438 uint8_t* ptr = chunk_begin + patch.offset;
439 PERFETTO_CHECK(ptr <= chunk.end() - SharedMemoryABI::kPacketHeaderSize);
440 // DCHECK that we are writing into a zero-filled size field and not into
441 // valid data. It relies on ScatteredStreamWriter::ReserveBytes() to
442 // zero-fill reservations in debug builds.
443 const char zero[SharedMemoryABI::kPacketHeaderSize]{};
444 PERFETTO_DCHECK(memcmp(ptr, &zero, SharedMemoryABI::kPacketHeaderSize) == 0);
445
446 memcpy(ptr, &patch.size_field[0], SharedMemoryABI::kPacketHeaderSize);
447
448 if (!chunk_needs_more_patching) {
449 // Mark that the chunk doesn't need more patching and mark it as complete,
450 // as the producer will not write to it anymore. This allows the service to
451 // read the chunk in full while scraping, which would not be the case if the
452 // chunk was left in a kChunkBeingWritten state.
453 chunk.ClearNeedsPatchingFlag();
454 shmem_abi_.ReleaseChunkAsComplete(std::move(chunk));
455 }
456
457 return true;
458 }
459
SetBatchCommitsDuration(uint32_t batch_commits_duration_ms)460 void SharedMemoryArbiterImpl::SetBatchCommitsDuration(
461 uint32_t batch_commits_duration_ms) {
462 std::lock_guard<std::mutex> scoped_lock(lock_);
463 batch_commits_duration_ms_ = batch_commits_duration_ms;
464 }
465
EnableDirectSMBPatching()466 bool SharedMemoryArbiterImpl::EnableDirectSMBPatching() {
467 std::lock_guard<std::mutex> scoped_lock(lock_);
468 if (!direct_patching_supported_by_service_) {
469 return false;
470 }
471
472 return direct_patching_enabled_ = true;
473 }
474
SetDirectSMBPatchingSupportedByService()475 void SharedMemoryArbiterImpl::SetDirectSMBPatchingSupportedByService() {
476 std::lock_guard<std::mutex> scoped_lock(lock_);
477 direct_patching_supported_by_service_ = true;
478 }
479
480 // This function is quite subtle. When making changes keep in mind these two
481 // challenges:
482 // 1) If the producer stalls and we happen to be on the |task_runner_| IPC
483 // thread (or, for in-process cases, on the same thread where
484 // TracingServiceImpl lives), the CommitData() call must be synchronous and
485 // not posted, to avoid deadlocks.
486 // 2) When different threads hit this function, we must guarantee that we don't
487 // accidentally make commits out of order. See commit 4e4fe8f56ef and
488 // crbug.com/919187 for more context.
FlushPendingCommitDataRequests(std::function<void ()> callback)489 void SharedMemoryArbiterImpl::FlushPendingCommitDataRequests(
490 std::function<void()> callback) {
491 std::unique_ptr<CommitDataRequest> req;
492 {
493 std::unique_lock<std::mutex> scoped_lock(lock_);
494
495 // Flushing is only supported while |fully_bound_|, and there may still be
496 // unbound startup trace writers. If so, skip the commit for now - it'll be
497 // done when |fully_bound_| is updated.
498 if (!fully_bound_) {
499 if (callback)
500 pending_flush_callbacks_.push_back(callback);
501 return;
502 }
503
504 // May be called by TraceWriterImpl on any thread.
505 base::TaskRunner* task_runner = task_runner_;
506 if (!task_runner->RunsTasksOnCurrentThread()) {
507 // We shouldn't post a task while holding a lock. |task_runner| remains
508 // valid after unlocking, because |task_runner_| is never reset.
509 scoped_lock.unlock();
510
511 auto weak_this = weak_ptr_factory_.GetWeakPtr();
512 task_runner->PostTask([weak_this, callback] {
513 if (weak_this)
514 weak_this->FlushPendingCommitDataRequests(std::move(callback));
515 });
516 return;
517 }
518
519 // |commit_data_req_| could have become a nullptr, for example when a forced
520 // sync flush happens in GetNewChunk().
521 if (commit_data_req_) {
522 // Make sure any placeholder buffer IDs from StartupWriters are replaced
523 // before sending the request.
524 bool all_placeholders_replaced =
525 ReplaceCommitPlaceholderBufferIdsLocked();
526 // We're |fully_bound_|, thus all writers are bound and all placeholders
527 // should have been replaced.
528 PERFETTO_DCHECK(all_placeholders_replaced);
529
530 // In order to allow patching in the producer we delay the kChunkComplete
531 // transition and keep batched chunks in the kChunkBeingWritten state.
532 // Since we are about to notify the service of all batched chunks, it will
533 // not be possible to apply any more patches to them and we need to move
534 // them to kChunkComplete - otherwise the service won't look at them.
535 for (auto& ctm : *commit_data_req_->mutable_chunks_to_move()) {
536 uint32_t layout = shmem_abi_.GetPageLayout(ctm.page());
537 auto chunk_state =
538 shmem_abi_.GetChunkStateFromLayout(layout, ctm.chunk());
539 // Note: the subset of |commit_data_req_| chunks that still need
540 // patching is also the subset of chunks that are still being written
541 // to. The rest of the chunks in |commit_data_req_| do not need patching
542 // and have already been marked as complete.
543 if (chunk_state == SharedMemoryABI::kChunkBeingWritten) {
544 auto chunk =
545 shmem_abi_.GetChunkUnchecked(ctm.page(), layout, ctm.chunk());
546 shmem_abi_.ReleaseChunkAsComplete(std::move(chunk));
547 }
548
549 if (use_shmem_emulation_) {
550 // When running in the emulation mode:
551 // 1. serialize the chunk data to |ctm| as we won't modify the chunk
552 // anymore.
553 // 2. free the chunk as the service won't be able to do this.
554 auto chunk =
555 shmem_abi_.GetChunkUnchecked(ctm.page(), layout, ctm.chunk());
556 PERFETTO_CHECK(chunk.is_valid());
557 ctm.set_data(chunk.begin(), chunk.size());
558 shmem_abi_.ReleaseChunkAsFree(std::move(chunk));
559 }
560 }
561
562 req = std::move(commit_data_req_);
563 bytes_pending_commit_ = 0;
564 }
565 } // scoped_lock
566
567 if (req) {
568 producer_endpoint_->CommitData(*req, callback);
569 } else if (callback) {
570 // If |req| was nullptr, it means that an enqueued deferred commit was
571 // executed just before this. At this point send an empty commit request
572 // to the service, just to linearize with it and give the guarantee to the
573 // caller that the data has been flushed into the service.
574 producer_endpoint_->CommitData(CommitDataRequest(), std::move(callback));
575 }
576 }
577
TryShutdown()578 bool SharedMemoryArbiterImpl::TryShutdown() {
579 std::lock_guard<std::mutex> scoped_lock(lock_);
580 did_shutdown_ = true;
581 // Shutdown is safe if there are no active trace writers for this arbiter.
582 return active_writer_ids_.IsEmpty();
583 }
584
CreateTraceWriter(BufferID target_buffer,BufferExhaustedPolicy buffer_exhausted_policy)585 std::unique_ptr<TraceWriter> SharedMemoryArbiterImpl::CreateTraceWriter(
586 BufferID target_buffer,
587 BufferExhaustedPolicy buffer_exhausted_policy) {
588 PERFETTO_CHECK(target_buffer > 0);
589 return CreateTraceWriterInternal(target_buffer, buffer_exhausted_policy);
590 }
591
CreateStartupTraceWriter(uint16_t target_buffer_reservation_id)592 std::unique_ptr<TraceWriter> SharedMemoryArbiterImpl::CreateStartupTraceWriter(
593 uint16_t target_buffer_reservation_id) {
594 return CreateTraceWriterInternal(
595 MakeTargetBufferIdForReservation(target_buffer_reservation_id),
596 BufferExhaustedPolicy::kDrop);
597 }
598
BindToProducerEndpoint(TracingService::ProducerEndpoint * producer_endpoint,base::TaskRunner * task_runner)599 void SharedMemoryArbiterImpl::BindToProducerEndpoint(
600 TracingService::ProducerEndpoint* producer_endpoint,
601 base::TaskRunner* task_runner) {
602 PERFETTO_DCHECK(producer_endpoint && task_runner);
603 PERFETTO_DCHECK(task_runner->RunsTasksOnCurrentThread());
604
605 bool should_flush = false;
606 std::function<void()> flush_callback;
607 {
608 std::lock_guard<std::mutex> scoped_lock(lock_);
609 PERFETTO_CHECK(!fully_bound_);
610 PERFETTO_CHECK(!producer_endpoint_ && !task_runner_);
611
612 producer_endpoint_ = producer_endpoint;
613 task_runner_ = task_runner;
614
615 // Now that we're bound to a task runner, also reset the WeakPtrFactory to
616 // it. Because this code runs on the task runner, the factory's weak
617 // pointers will be valid on it.
618 weak_ptr_factory_.Reset(this);
619
620 // All writers registered so far should be startup trace writers, since
621 // the producer cannot feasibly know the target buffer for any future
622 // session yet.
623 for (const auto& entry : pending_writers_) {
624 PERFETTO_CHECK(IsReservationTargetBufferId(entry.second));
625 }
626
627 // If all buffer reservations are bound, we can flush pending commits.
628 if (UpdateFullyBoundLocked()) {
629 should_flush = true;
630 flush_callback = TakePendingFlushCallbacksLocked();
631 }
632 } // scoped_lock
633
634 // Attempt to flush any pending commits (and run pending flush callbacks). If
635 // there are none, this will have no effect. If we ended up in a race that
636 // changed |fully_bound_| back to false, the commit will happen once we become
637 // |fully_bound_| again.
638 if (should_flush)
639 FlushPendingCommitDataRequests(flush_callback);
640 }
641
BindStartupTargetBuffer(uint16_t target_buffer_reservation_id,BufferID target_buffer_id)642 void SharedMemoryArbiterImpl::BindStartupTargetBuffer(
643 uint16_t target_buffer_reservation_id,
644 BufferID target_buffer_id) {
645 PERFETTO_DCHECK(target_buffer_id > 0);
646
647 std::unique_lock<std::mutex> scoped_lock(lock_);
648
649 // We should already be bound to an endpoint.
650 PERFETTO_CHECK(producer_endpoint_);
651 PERFETTO_CHECK(task_runner_);
652 PERFETTO_CHECK(task_runner_->RunsTasksOnCurrentThread());
653
654 BindStartupTargetBufferImpl(std::move(scoped_lock),
655 target_buffer_reservation_id, target_buffer_id);
656 }
657
AbortStartupTracingForReservation(uint16_t target_buffer_reservation_id)658 void SharedMemoryArbiterImpl::AbortStartupTracingForReservation(
659 uint16_t target_buffer_reservation_id) {
660 std::unique_lock<std::mutex> scoped_lock(lock_);
661
662 // If we are already bound to an arbiter, we may need to flush after aborting
663 // the session, and thus should be running on the arbiter's task runner.
664 if (task_runner_ && !task_runner_->RunsTasksOnCurrentThread()) {
665 // We shouldn't post tasks while locked.
666 auto* task_runner = task_runner_;
667 scoped_lock.unlock();
668
669 auto weak_this = weak_ptr_factory_.GetWeakPtr();
670 task_runner->PostTask([weak_this, target_buffer_reservation_id]() {
671 if (!weak_this)
672 return;
673 weak_this->AbortStartupTracingForReservation(
674 target_buffer_reservation_id);
675 });
676 return;
677 }
678
679 // Bind the target buffer reservation to an invalid buffer (ID 0), so that
680 // existing commits, as well as future commits (of currently acquired chunks),
681 // will be released as free free by the service but otherwise ignored (i.e.
682 // not copied into any valid target buffer).
683 BindStartupTargetBufferImpl(std::move(scoped_lock),
684 target_buffer_reservation_id,
685 /*target_buffer_id=*/kInvalidBufferId);
686 }
687
BindStartupTargetBufferImpl(std::unique_lock<std::mutex> scoped_lock,uint16_t target_buffer_reservation_id,BufferID target_buffer_id)688 void SharedMemoryArbiterImpl::BindStartupTargetBufferImpl(
689 std::unique_lock<std::mutex> scoped_lock,
690 uint16_t target_buffer_reservation_id,
691 BufferID target_buffer_id) {
692 // We should already be bound to an endpoint if the target buffer is valid.
693 PERFETTO_DCHECK((producer_endpoint_ && task_runner_) ||
694 target_buffer_id == kInvalidBufferId);
695
696 PERFETTO_DLOG("Binding startup target buffer reservation %" PRIu16
697 " to buffer %" PRIu16,
698 target_buffer_reservation_id, target_buffer_id);
699
700 MaybeUnboundBufferID reserved_id =
701 MakeTargetBufferIdForReservation(target_buffer_reservation_id);
702
703 bool should_flush = false;
704 std::function<void()> flush_callback;
705 std::vector<std::pair<WriterID, BufferID>> writers_to_register;
706
707 TargetBufferReservation& reservation =
708 target_buffer_reservations_[reserved_id];
709 PERFETTO_CHECK(!reservation.resolved);
710 reservation.resolved = true;
711 reservation.target_buffer = target_buffer_id;
712
713 // Collect trace writers associated with the reservation.
714 for (auto it = pending_writers_.begin(); it != pending_writers_.end();) {
715 if (it->second == reserved_id) {
716 // No need to register writers that have an invalid target buffer.
717 if (target_buffer_id != kInvalidBufferId) {
718 writers_to_register.push_back(
719 std::make_pair(it->first, target_buffer_id));
720 }
721 it = pending_writers_.erase(it);
722 } else {
723 it++;
724 }
725 }
726
727 // If all buffer reservations are bound, we can flush pending commits.
728 if (UpdateFullyBoundLocked()) {
729 should_flush = true;
730 flush_callback = TakePendingFlushCallbacksLocked();
731 }
732
733 scoped_lock.unlock();
734
735 // Register any newly bound trace writers with the service.
736 for (const auto& writer_and_target_buffer : writers_to_register) {
737 producer_endpoint_->RegisterTraceWriter(writer_and_target_buffer.first,
738 writer_and_target_buffer.second);
739 }
740
741 // Attempt to flush any pending commits (and run pending flush callbacks). If
742 // there are none, this will have no effect. If we ended up in a race that
743 // changed |fully_bound_| back to false, the commit will happen once we become
744 // |fully_bound_| again.
745 if (should_flush)
746 FlushPendingCommitDataRequests(flush_callback);
747 }
748
749 std::function<void()>
TakePendingFlushCallbacksLocked()750 SharedMemoryArbiterImpl::TakePendingFlushCallbacksLocked() {
751 if (pending_flush_callbacks_.empty())
752 return std::function<void()>();
753
754 std::vector<std::function<void()>> pending_flush_callbacks;
755 pending_flush_callbacks.swap(pending_flush_callbacks_);
756 // Capture the callback list into the lambda by copy.
757 return [pending_flush_callbacks]() {
758 for (auto& callback : pending_flush_callbacks)
759 callback();
760 };
761 }
762
NotifyFlushComplete(FlushRequestID req_id)763 void SharedMemoryArbiterImpl::NotifyFlushComplete(FlushRequestID req_id) {
764 base::TaskRunner* task_runner_to_commit_on = nullptr;
765
766 {
767 std::lock_guard<std::mutex> scoped_lock(lock_);
768 // If a commit_data_req_ exists it means that somebody else already posted a
769 // FlushPendingCommitDataRequests() task.
770 if (!commit_data_req_) {
771 commit_data_req_.reset(new CommitDataRequest());
772
773 // Flushing the commit is only supported while we're |fully_bound_|. If we
774 // aren't, we'll flush when |fully_bound_| is updated.
775 if (fully_bound_)
776 task_runner_to_commit_on = task_runner_;
777 } else {
778 // If there is another request queued and that also contains is a reply
779 // to a flush request, reply with the highest id.
780 req_id = std::max(req_id, commit_data_req_->flush_request_id());
781 }
782 commit_data_req_->set_flush_request_id(req_id);
783 } // scoped_lock
784
785 // We shouldn't post tasks while locked. |task_runner_to_commit_on|
786 // remains valid after unlocking, because |task_runner_| is never reset.
787 if (task_runner_to_commit_on) {
788 auto weak_this = weak_ptr_factory_.GetWeakPtr();
789 task_runner_to_commit_on->PostTask([weak_this] {
790 if (weak_this)
791 weak_this->FlushPendingCommitDataRequests();
792 });
793 }
794 }
795
CreateTraceWriterInternal(MaybeUnboundBufferID target_buffer,BufferExhaustedPolicy buffer_exhausted_policy)796 std::unique_ptr<TraceWriter> SharedMemoryArbiterImpl::CreateTraceWriterInternal(
797 MaybeUnboundBufferID target_buffer,
798 BufferExhaustedPolicy buffer_exhausted_policy) {
799 WriterID id;
800 base::TaskRunner* task_runner_to_register_on = nullptr;
801
802 {
803 std::lock_guard<std::mutex> scoped_lock(lock_);
804 if (did_shutdown_)
805 return std::unique_ptr<TraceWriter>(new NullTraceWriter());
806
807 id = active_writer_ids_.Allocate();
808 if (!id)
809 return std::unique_ptr<TraceWriter>(new NullTraceWriter());
810
811 PERFETTO_DCHECK(!pending_writers_.count(id));
812
813 if (IsReservationTargetBufferId(target_buffer)) {
814 // If the reservation is new, mark it as unbound in
815 // |target_buffer_reservations_|. Otherwise, if the reservation was
816 // already bound, choose the bound buffer ID now.
817 auto it_and_inserted = target_buffer_reservations_.insert(
818 {target_buffer, TargetBufferReservation()});
819 if (it_and_inserted.first->second.resolved)
820 target_buffer = it_and_inserted.first->second.target_buffer;
821 }
822
823 if (IsReservationTargetBufferId(target_buffer)) {
824 // The arbiter and/or startup buffer reservations are not bound yet, so
825 // buffer the registration of the writer until after we're bound.
826 pending_writers_[id] = target_buffer;
827
828 // Mark the arbiter as not fully bound, since we now have at least one
829 // unbound trace writer / target buffer reservation.
830 fully_bound_ = false;
831 was_always_bound_ = false;
832 } else if (target_buffer != kInvalidBufferId) {
833 // Trace writer is bound, so arbiter should be bound to an endpoint, too.
834 PERFETTO_CHECK(producer_endpoint_ && task_runner_);
835 task_runner_to_register_on = task_runner_;
836 }
837
838 // All trace writers must use kDrop policy if the arbiter ever becomes
839 // unbound.
840 bool uses_drop_policy =
841 buffer_exhausted_policy == BufferExhaustedPolicy::kDrop;
842 all_writers_have_drop_policy_ &= uses_drop_policy;
843 PERFETTO_DCHECK(fully_bound_ || uses_drop_policy);
844 PERFETTO_CHECK(fully_bound_ || all_writers_have_drop_policy_);
845 PERFETTO_CHECK(was_always_bound_ || uses_drop_policy);
846 } // scoped_lock
847
848 // We shouldn't post tasks while locked. |task_runner_to_register_on|
849 // remains valid after unlocking, because |task_runner_| is never reset.
850 if (task_runner_to_register_on) {
851 auto weak_this = weak_ptr_factory_.GetWeakPtr();
852 task_runner_to_register_on->PostTask([weak_this, id, target_buffer] {
853 if (weak_this)
854 weak_this->producer_endpoint_->RegisterTraceWriter(id, target_buffer);
855 });
856 }
857
858 return std::unique_ptr<TraceWriter>(
859 new TraceWriterImpl(this, id, target_buffer, buffer_exhausted_policy));
860 }
861
ReleaseWriterID(WriterID id)862 void SharedMemoryArbiterImpl::ReleaseWriterID(WriterID id) {
863 base::TaskRunner* task_runner = nullptr;
864 {
865 std::lock_guard<std::mutex> scoped_lock(lock_);
866 active_writer_ids_.Free(id);
867
868 auto it = pending_writers_.find(id);
869 if (it != pending_writers_.end()) {
870 // Writer hasn't been bound yet and thus also not yet registered with the
871 // service.
872 pending_writers_.erase(it);
873 return;
874 }
875
876 // A trace writer from an aborted session may be destroyed before the
877 // arbiter is bound to a task runner. In that case, it was never registered
878 // with the service.
879 if (!task_runner_)
880 return;
881
882 task_runner = task_runner_;
883 } // scoped_lock
884
885 // We shouldn't post tasks while locked. |task_runner| remains valid after
886 // unlocking, because |task_runner_| is never reset.
887 auto weak_this = weak_ptr_factory_.GetWeakPtr();
888 task_runner->PostTask([weak_this, id] {
889 if (weak_this)
890 weak_this->producer_endpoint_->UnregisterTraceWriter(id);
891 });
892 }
893
ReplaceCommitPlaceholderBufferIdsLocked()894 bool SharedMemoryArbiterImpl::ReplaceCommitPlaceholderBufferIdsLocked() {
895 if (!commit_data_req_)
896 return true;
897
898 bool all_placeholders_replaced = true;
899 for (auto& chunk : *commit_data_req_->mutable_chunks_to_move()) {
900 if (!IsReservationTargetBufferId(chunk.target_buffer()))
901 continue;
902 const auto it = target_buffer_reservations_.find(chunk.target_buffer());
903 PERFETTO_DCHECK(it != target_buffer_reservations_.end());
904 if (!it->second.resolved) {
905 all_placeholders_replaced = false;
906 continue;
907 }
908 chunk.set_target_buffer(it->second.target_buffer);
909 }
910 for (auto& chunk : *commit_data_req_->mutable_chunks_to_patch()) {
911 if (!IsReservationTargetBufferId(chunk.target_buffer()))
912 continue;
913 const auto it = target_buffer_reservations_.find(chunk.target_buffer());
914 PERFETTO_DCHECK(it != target_buffer_reservations_.end());
915 if (!it->second.resolved) {
916 all_placeholders_replaced = false;
917 continue;
918 }
919 chunk.set_target_buffer(it->second.target_buffer);
920 }
921 return all_placeholders_replaced;
922 }
923
UpdateFullyBoundLocked()924 bool SharedMemoryArbiterImpl::UpdateFullyBoundLocked() {
925 if (!producer_endpoint_) {
926 PERFETTO_DCHECK(!fully_bound_);
927 return false;
928 }
929 // We're fully bound if all target buffer reservations have a valid associated
930 // BufferID.
931 fully_bound_ = std::none_of(
932 target_buffer_reservations_.begin(), target_buffer_reservations_.end(),
933 [](std::pair<MaybeUnboundBufferID, TargetBufferReservation> entry) {
934 return !entry.second.resolved;
935 });
936 if (!fully_bound_)
937 was_always_bound_ = false;
938 return fully_bound_;
939 }
940
941 } // namespace perfetto
942