• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
6  * License. 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,
11  * software distributed under the License is distributed on an "AS
12  * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
13  * express or implied. See the License for the specific language
14  * governing permissions and limitations under the License.
15  */
16 #include "perfetto/ext/tracing/core/shared_memory_abi.h"
17 
18 #include "perfetto/base/build_config.h"
19 #include "perfetto/base/time.h"
20 
21 #if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
22 #include <sys/mman.h>
23 #endif
24 
25 #include "perfetto/ext/base/utils.h"
26 #include "perfetto/ext/tracing/core/basic_types.h"
27 
28 namespace perfetto {
29 
30 namespace {
31 
32 constexpr int kRetryAttempts = 64;
33 
WaitBeforeNextAttempt(int attempt)34 inline void WaitBeforeNextAttempt(int attempt) {
35   if (attempt < kRetryAttempts / 2) {
36     std::this_thread::yield();
37   } else {
38     base::SleepMicroseconds((unsigned(attempt) / 10) * 1000);
39   }
40 }
41 
42 // Returns the largest 4-bytes aligned chunk size <= |page_size| / |divider|
43 // for each divider in PageLayout.
GetChunkSize(size_t page_size,size_t divider)44 constexpr size_t GetChunkSize(size_t page_size, size_t divider) {
45   return ((page_size - sizeof(SharedMemoryABI::PageHeader)) / divider) & ~3UL;
46 }
47 
48 // Initializer for the const |chunk_sizes_| array.
InitChunkSizes(size_t page_size)49 std::array<uint16_t, SharedMemoryABI::kNumPageLayouts> InitChunkSizes(
50     size_t page_size) {
51   static_assert(SharedMemoryABI::kNumPageLayouts ==
52                     base::ArraySize(SharedMemoryABI::kNumChunksForLayout),
53                 "kNumPageLayouts out of date");
54   std::array<uint16_t, SharedMemoryABI::kNumPageLayouts> res = {};
55   for (size_t i = 0; i < SharedMemoryABI::kNumPageLayouts; i++) {
56     size_t num_chunks = SharedMemoryABI::kNumChunksForLayout[i];
57     size_t size = num_chunks == 0 ? 0 : GetChunkSize(page_size, num_chunks);
58     PERFETTO_CHECK(size <= std::numeric_limits<uint16_t>::max());
59     res[i] = static_cast<uint16_t>(size);
60   }
61   return res;
62 }
63 
ClearChunkHeader(SharedMemoryABI::ChunkHeader * header)64 inline void ClearChunkHeader(SharedMemoryABI::ChunkHeader* header) {
65   header->writer_id.store(0u, std::memory_order_relaxed);
66   header->chunk_id.store(0u, std::memory_order_relaxed);
67   header->packets.store({}, std::memory_order_release);
68 }
69 
70 }  // namespace
71 
72 // static
73 constexpr uint32_t SharedMemoryABI::kNumChunksForLayout[];
74 constexpr const char* SharedMemoryABI::kChunkStateStr[];
75 constexpr const size_t SharedMemoryABI::kInvalidPageIdx;
76 constexpr const size_t SharedMemoryABI::kMaxPageSize;
77 constexpr const size_t SharedMemoryABI::kPacketSizeDropPacket;
78 
79 SharedMemoryABI::SharedMemoryABI() = default;
80 
SharedMemoryABI(uint8_t * start,size_t size,size_t page_size)81 SharedMemoryABI::SharedMemoryABI(uint8_t* start,
82                                  size_t size,
83                                  size_t page_size) {
84   Initialize(start, size, page_size);
85 }
86 
Initialize(uint8_t * start,size_t size,size_t page_size)87 void SharedMemoryABI::Initialize(uint8_t* start,
88                                  size_t size,
89                                  size_t page_size) {
90   start_ = start;
91   size_ = size;
92   page_size_ = page_size;
93   num_pages_ = size / page_size;
94   chunk_sizes_ = InitChunkSizes(page_size);
95   static_assert(sizeof(PageHeader) == 8, "PageHeader size");
96   static_assert(sizeof(ChunkHeader) == 8, "ChunkHeader size");
97   static_assert(sizeof(ChunkHeader::chunk_id) == sizeof(ChunkID),
98                 "ChunkID size");
99 
100   static_assert(sizeof(ChunkHeader::Packets) == 2, "ChunkHeader::Packets size");
101   static_assert(alignof(ChunkHeader) == kChunkAlignment,
102                 "ChunkHeader alignment");
103 
104   // In theory std::atomic does not guarantee that the underlying type
105   // consists only of the actual atomic word. Theoretically it could have
106   // locks or other state. In practice most implementations just implement
107   // them without extra state. The code below overlays the atomic into the
108   // SMB, hence relies on this implementation detail. This should be fine
109   // pragmatically (Chrome's base makes the same assumption), but let's have a
110   // check for this.
111   static_assert(sizeof(std::atomic<uint32_t>) == sizeof(uint32_t) &&
112                     sizeof(std::atomic<uint16_t>) == sizeof(uint16_t),
113                 "Incompatible STL <atomic> implementation");
114 
115   // Chec that the kAllChunks(Complete,Free) are consistent with the
116   // ChunkState enum values.
117 
118   // These must be zero because rely on zero-initialized memory being
119   // interpreted as "free".
120   static_assert(kChunkFree == 0 && kAllChunksFree == 0,
121                 "kChunkFree/kAllChunksFree and must be 0");
122 
123   static_assert((kAllChunksComplete & kChunkMask) == kChunkComplete,
124                 "kAllChunksComplete out of sync with kChunkComplete");
125 
126   // Sanity check the consistency of the kMax... constants.
127   static_assert(sizeof(ChunkHeader::writer_id) == sizeof(WriterID),
128                 "WriterID size");
129   ChunkHeader chunk_header{};
130   chunk_header.chunk_id.store(static_cast<uint32_t>(-1));
131   PERFETTO_CHECK(chunk_header.chunk_id.load() == kMaxChunkID);
132 
133   chunk_header.writer_id.store(static_cast<uint16_t>(-1));
134   PERFETTO_CHECK(kMaxWriterID <= chunk_header.writer_id.load());
135 
136   PERFETTO_CHECK(page_size >= base::kPageSize);
137   PERFETTO_CHECK(page_size <= kMaxPageSize);
138   PERFETTO_CHECK(page_size % base::kPageSize == 0);
139   PERFETTO_CHECK(reinterpret_cast<uintptr_t>(start) % base::kPageSize == 0);
140   PERFETTO_CHECK(size % page_size == 0);
141 }
142 
GetChunkUnchecked(size_t page_idx,uint32_t page_layout,size_t chunk_idx)143 SharedMemoryABI::Chunk SharedMemoryABI::GetChunkUnchecked(size_t page_idx,
144                                                           uint32_t page_layout,
145                                                           size_t chunk_idx) {
146   const size_t num_chunks = GetNumChunksForLayout(page_layout);
147   PERFETTO_DCHECK(chunk_idx < num_chunks);
148   // Compute the chunk virtual address and write it into |chunk|.
149   const uint16_t chunk_size = GetChunkSizeForLayout(page_layout);
150   size_t chunk_offset_in_page = sizeof(PageHeader) + chunk_idx * chunk_size;
151 
152   Chunk chunk(page_start(page_idx) + chunk_offset_in_page, chunk_size,
153               static_cast<uint8_t>(chunk_idx));
154   PERFETTO_DCHECK(chunk.end() <= end());
155   return chunk;
156 }
157 
TryAcquireChunk(size_t page_idx,size_t chunk_idx,ChunkState desired_chunk_state,const ChunkHeader * header)158 SharedMemoryABI::Chunk SharedMemoryABI::TryAcquireChunk(
159     size_t page_idx,
160     size_t chunk_idx,
161     ChunkState desired_chunk_state,
162     const ChunkHeader* header) {
163   PERFETTO_DCHECK(desired_chunk_state == kChunkBeingRead ||
164                   desired_chunk_state == kChunkBeingWritten);
165   PageHeader* phdr = page_header(page_idx);
166   for (int attempt = 0; attempt < kRetryAttempts; attempt++) {
167     uint32_t layout = phdr->layout.load(std::memory_order_acquire);
168     const size_t num_chunks = GetNumChunksForLayout(layout);
169 
170     // The page layout has changed (or the page is free).
171     if (chunk_idx >= num_chunks)
172       return Chunk();
173 
174     // Verify that the chunk is still in a state that allows the transition to
175     // |desired_chunk_state|. The only allowed transitions are:
176     // 1. kChunkFree -> kChunkBeingWritten (Producer).
177     // 2. kChunkComplete -> kChunkBeingRead (Service).
178     ChunkState expected_chunk_state =
179         desired_chunk_state == kChunkBeingWritten ? kChunkFree : kChunkComplete;
180     auto cur_chunk_state = (layout >> (chunk_idx * kChunkShift)) & kChunkMask;
181     if (cur_chunk_state != expected_chunk_state)
182       return Chunk();
183 
184     uint32_t next_layout = layout;
185     next_layout &= ~(kChunkMask << (chunk_idx * kChunkShift));
186     next_layout |= (desired_chunk_state << (chunk_idx * kChunkShift));
187     if (phdr->layout.compare_exchange_strong(layout, next_layout,
188                                              std::memory_order_acq_rel)) {
189       // Compute the chunk virtual address and write it into |chunk|.
190       Chunk chunk = GetChunkUnchecked(page_idx, layout, chunk_idx);
191       if (desired_chunk_state == kChunkBeingWritten) {
192         PERFETTO_DCHECK(header);
193         ChunkHeader* new_header = chunk.header();
194         new_header->writer_id.store(header->writer_id,
195                                     std::memory_order_relaxed);
196         new_header->chunk_id.store(header->chunk_id, std::memory_order_relaxed);
197         new_header->packets.store(header->packets, std::memory_order_release);
198       }
199       return chunk;
200     }
201     WaitBeforeNextAttempt(attempt);
202   }
203   return Chunk();  // All our attempts failed.
204 }
205 
TryPartitionPage(size_t page_idx,PageLayout layout)206 bool SharedMemoryABI::TryPartitionPage(size_t page_idx, PageLayout layout) {
207   PERFETTO_DCHECK(layout >= kPageDiv1 && layout <= kPageDiv14);
208   uint32_t expected_layout = 0;  // Free page.
209   uint32_t next_layout = (layout << kLayoutShift) & kLayoutMask;
210   PageHeader* phdr = page_header(page_idx);
211   if (!phdr->layout.compare_exchange_strong(expected_layout, next_layout,
212                                             std::memory_order_acq_rel)) {
213     return false;
214   }
215   return true;
216 }
217 
GetFreeChunks(size_t page_idx)218 uint32_t SharedMemoryABI::GetFreeChunks(size_t page_idx) {
219   uint32_t layout =
220       page_header(page_idx)->layout.load(std::memory_order_relaxed);
221   const uint32_t num_chunks = GetNumChunksForLayout(layout);
222   uint32_t res = 0;
223   for (uint32_t i = 0; i < num_chunks; i++) {
224     res |= ((layout & kChunkMask) == kChunkFree) ? (1 << i) : 0;
225     layout >>= kChunkShift;
226   }
227   return res;
228 }
229 
ReleaseChunk(Chunk chunk,ChunkState desired_chunk_state)230 size_t SharedMemoryABI::ReleaseChunk(Chunk chunk,
231                                      ChunkState desired_chunk_state) {
232   PERFETTO_DCHECK(desired_chunk_state == kChunkComplete ||
233                   desired_chunk_state == kChunkFree);
234 
235   size_t page_idx;
236   size_t chunk_idx;
237   std::tie(page_idx, chunk_idx) = GetPageAndChunkIndex(chunk);
238 
239   // Reset header fields, so that the service can identify when the chunk's
240   // header has been initialized by the producer.
241   if (desired_chunk_state == kChunkFree)
242     ClearChunkHeader(chunk.header());
243 
244   for (int attempt = 0; attempt < kRetryAttempts; attempt++) {
245     PageHeader* phdr = page_header(page_idx);
246     uint32_t layout = phdr->layout.load(std::memory_order_relaxed);
247     const size_t page_chunk_size = GetChunkSizeForLayout(layout);
248 
249     // TODO(primiano): this should not be a CHECK, because a malicious producer
250     // could crash us by putting the chunk in an invalid state. This should
251     // gracefully fail. Keep a CHECK until then.
252     PERFETTO_CHECK(chunk.size() == page_chunk_size);
253     const uint32_t chunk_state =
254         ((layout >> (chunk_idx * kChunkShift)) & kChunkMask);
255 
256     // Verify that the chunk is still in a state that allows the transition to
257     // |desired_chunk_state|. The only allowed transitions are:
258     // 1. kChunkBeingWritten -> kChunkComplete (Producer).
259     // 2. kChunkBeingRead -> kChunkFree (Service).
260     ChunkState expected_chunk_state;
261     if (desired_chunk_state == kChunkComplete) {
262       expected_chunk_state = kChunkBeingWritten;
263     } else {
264       expected_chunk_state = kChunkBeingRead;
265     }
266 
267     // TODO(primiano): should not be a CHECK (same rationale of comment above).
268     PERFETTO_CHECK(chunk_state == expected_chunk_state);
269     uint32_t next_layout = layout;
270     next_layout &= ~(kChunkMask << (chunk_idx * kChunkShift));
271     next_layout |= (desired_chunk_state << (chunk_idx * kChunkShift));
272 
273     // If we are freeing a chunk and all the other chunks in the page are free
274     // we should de-partition the page and mark it as clear.
275     if ((next_layout & kAllChunksMask) == kAllChunksFree)
276       next_layout = 0;
277 
278     if (phdr->layout.compare_exchange_strong(layout, next_layout,
279                                              std::memory_order_acq_rel)) {
280       return page_idx;
281     }
282     WaitBeforeNextAttempt(attempt);
283   }
284   // Too much contention on this page. Give up. This page will be left pending
285   // forever but there isn't much more we can do at this point.
286   PERFETTO_DFATAL("Too much contention on page.");
287   return kInvalidPageIdx;
288 }
289 
290 SharedMemoryABI::Chunk::Chunk() = default;
291 
Chunk(uint8_t * begin,uint16_t size,uint8_t chunk_idx)292 SharedMemoryABI::Chunk::Chunk(uint8_t* begin, uint16_t size, uint8_t chunk_idx)
293     : begin_(begin), size_(size), chunk_idx_(chunk_idx) {
294   PERFETTO_CHECK(reinterpret_cast<uintptr_t>(begin) % kChunkAlignment == 0);
295   PERFETTO_CHECK(size > 0);
296 }
297 
Chunk(Chunk && o)298 SharedMemoryABI::Chunk::Chunk(Chunk&& o) noexcept {
299   *this = std::move(o);
300 }
301 
operator =(Chunk && o)302 SharedMemoryABI::Chunk& SharedMemoryABI::Chunk::operator=(Chunk&& o) {
303   begin_ = o.begin_;
304   size_ = o.size_;
305   chunk_idx_ = o.chunk_idx_;
306   o.begin_ = nullptr;
307   o.size_ = 0;
308   o.chunk_idx_ = 0;
309   return *this;
310 }
311 
GetPageAndChunkIndex(const Chunk & chunk)312 std::pair<size_t, size_t> SharedMemoryABI::GetPageAndChunkIndex(
313     const Chunk& chunk) {
314   PERFETTO_DCHECK(chunk.is_valid());
315   PERFETTO_DCHECK(chunk.begin() >= start_);
316   PERFETTO_DCHECK(chunk.end() <= start_ + size_);
317 
318   // TODO(primiano): The divisions below could be avoided if we cached
319   // |page_shift_|.
320   const uintptr_t rel_addr = static_cast<uintptr_t>(chunk.begin() - start_);
321   const size_t page_idx = rel_addr / page_size_;
322   const size_t offset = rel_addr % page_size_;
323   PERFETTO_DCHECK(offset >= sizeof(PageHeader));
324   PERFETTO_DCHECK(offset % kChunkAlignment == 0);
325   PERFETTO_DCHECK((offset - sizeof(PageHeader)) % chunk.size() == 0);
326   const size_t chunk_idx = (offset - sizeof(PageHeader)) / chunk.size();
327   PERFETTO_DCHECK(chunk_idx < kMaxChunksPerPage);
328   PERFETTO_DCHECK(chunk_idx < GetNumChunksForLayout(GetPageLayout(page_idx)));
329   return std::make_pair(page_idx, chunk_idx);
330 }
331 
332 }  // namespace perfetto
333