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 SharedMemoryABI::SharedMemoryABI() = default;
73
SharedMemoryABI(uint8_t * start,size_t size,size_t page_size)74 SharedMemoryABI::SharedMemoryABI(uint8_t* start,
75 size_t size,
76 size_t page_size) {
77 Initialize(start, size, page_size);
78 }
79
Initialize(uint8_t * start,size_t size,size_t page_size)80 void SharedMemoryABI::Initialize(uint8_t* start,
81 size_t size,
82 size_t page_size) {
83 start_ = start;
84 size_ = size;
85 page_size_ = page_size;
86 num_pages_ = size / page_size;
87 chunk_sizes_ = InitChunkSizes(page_size);
88 static_assert(sizeof(PageHeader) == 8, "PageHeader size");
89 static_assert(sizeof(ChunkHeader) == 8, "ChunkHeader size");
90 static_assert(sizeof(ChunkHeader::chunk_id) == sizeof(ChunkID),
91 "ChunkID size");
92
93 static_assert(sizeof(ChunkHeader::Packets) == 2, "ChunkHeader::Packets size");
94 static_assert(alignof(ChunkHeader) == kChunkAlignment,
95 "ChunkHeader alignment");
96
97 // In theory std::atomic does not guarantee that the underlying type
98 // consists only of the actual atomic word. Theoretically it could have
99 // locks or other state. In practice most implementations just implement
100 // them without extra state. The code below overlays the atomic into the
101 // SMB, hence relies on this implementation detail. This should be fine
102 // pragmatically (Chrome's base makes the same assumption), but let's have a
103 // check for this.
104 static_assert(sizeof(std::atomic<uint32_t>) == sizeof(uint32_t) &&
105 sizeof(std::atomic<uint16_t>) == sizeof(uint16_t),
106 "Incompatible STL <atomic> implementation");
107
108 // Chec that the kAllChunks(Complete,Free) are consistent with the
109 // ChunkState enum values.
110
111 // These must be zero because rely on zero-initialized memory being
112 // interpreted as "free".
113 static_assert(kChunkFree == 0 && kAllChunksFree == 0,
114 "kChunkFree/kAllChunksFree and must be 0");
115
116 static_assert((kAllChunksComplete & kChunkMask) == kChunkComplete,
117 "kAllChunksComplete out of sync with kChunkComplete");
118
119 // Check the consistency of the kMax... constants.
120 static_assert(sizeof(ChunkHeader::writer_id) == sizeof(WriterID),
121 "WriterID size");
122 ChunkHeader chunk_header{};
123 chunk_header.chunk_id.store(static_cast<uint32_t>(-1));
124 PERFETTO_CHECK(chunk_header.chunk_id.load() == kMaxChunkID);
125
126 chunk_header.writer_id.store(static_cast<uint16_t>(-1));
127 PERFETTO_CHECK(kMaxWriterID <= chunk_header.writer_id.load());
128
129 PERFETTO_CHECK(page_size >= kMinPageSize);
130 PERFETTO_CHECK(page_size <= kMaxPageSize);
131 PERFETTO_CHECK(page_size % kMinPageSize == 0);
132 PERFETTO_CHECK(reinterpret_cast<uintptr_t>(start) % kMinPageSize == 0);
133 PERFETTO_CHECK(size % page_size == 0);
134 }
135
GetChunkUnchecked(size_t page_idx,uint32_t page_layout,size_t chunk_idx)136 SharedMemoryABI::Chunk SharedMemoryABI::GetChunkUnchecked(size_t page_idx,
137 uint32_t page_layout,
138 size_t chunk_idx) {
139 const size_t num_chunks = GetNumChunksForLayout(page_layout);
140 PERFETTO_DCHECK(chunk_idx < num_chunks);
141 // Compute the chunk virtual address and write it into |chunk|.
142 const uint16_t chunk_size = GetChunkSizeForLayout(page_layout);
143 size_t chunk_offset_in_page = sizeof(PageHeader) + chunk_idx * chunk_size;
144
145 Chunk chunk(page_start(page_idx) + chunk_offset_in_page, chunk_size,
146 static_cast<uint8_t>(chunk_idx));
147 PERFETTO_DCHECK(chunk.end() <= end());
148 return chunk;
149 }
150
TryAcquireChunk(size_t page_idx,size_t chunk_idx,ChunkState desired_chunk_state,const ChunkHeader * header)151 SharedMemoryABI::Chunk SharedMemoryABI::TryAcquireChunk(
152 size_t page_idx,
153 size_t chunk_idx,
154 ChunkState desired_chunk_state,
155 const ChunkHeader* header) {
156 PERFETTO_DCHECK(desired_chunk_state == kChunkBeingRead ||
157 desired_chunk_state == kChunkBeingWritten);
158 PageHeader* phdr = page_header(page_idx);
159 for (int attempt = 0; attempt < kRetryAttempts; attempt++) {
160 uint32_t layout = phdr->layout.load(std::memory_order_acquire);
161 const size_t num_chunks = GetNumChunksForLayout(layout);
162
163 // The page layout has changed (or the page is free).
164 if (chunk_idx >= num_chunks)
165 return Chunk();
166
167 // Verify that the chunk is still in a state that allows the transition to
168 // |desired_chunk_state|. The only allowed transitions are:
169 // 1. kChunkFree -> kChunkBeingWritten (Producer).
170 // 2. kChunkComplete -> kChunkBeingRead (Service).
171 ChunkState expected_chunk_state =
172 desired_chunk_state == kChunkBeingWritten ? kChunkFree : kChunkComplete;
173 auto cur_chunk_state = (layout >> (chunk_idx * kChunkShift)) & kChunkMask;
174 if (cur_chunk_state != expected_chunk_state)
175 return Chunk();
176
177 uint32_t next_layout = layout;
178 next_layout &= ~(kChunkMask << (chunk_idx * kChunkShift));
179 next_layout |= (desired_chunk_state << (chunk_idx * kChunkShift));
180 if (phdr->layout.compare_exchange_strong(layout, next_layout,
181 std::memory_order_acq_rel)) {
182 // Compute the chunk virtual address and write it into |chunk|.
183 Chunk chunk = GetChunkUnchecked(page_idx, layout, chunk_idx);
184 if (desired_chunk_state == kChunkBeingWritten) {
185 PERFETTO_DCHECK(header);
186 ChunkHeader* new_header = chunk.header();
187 new_header->writer_id.store(header->writer_id,
188 std::memory_order_relaxed);
189 new_header->chunk_id.store(header->chunk_id, std::memory_order_relaxed);
190 new_header->packets.store(header->packets, std::memory_order_release);
191 }
192 return chunk;
193 }
194 WaitBeforeNextAttempt(attempt);
195 }
196 return Chunk(); // All our attempts failed.
197 }
198
TryPartitionPage(size_t page_idx,PageLayout layout)199 bool SharedMemoryABI::TryPartitionPage(size_t page_idx, PageLayout layout) {
200 PERFETTO_DCHECK(layout >= kPageDiv1 && layout <= kPageDiv14);
201 uint32_t expected_layout = 0; // Free page.
202 uint32_t next_layout = (layout << kLayoutShift) & kLayoutMask;
203 PageHeader* phdr = page_header(page_idx);
204 if (!phdr->layout.compare_exchange_strong(expected_layout, next_layout,
205 std::memory_order_acq_rel)) {
206 return false;
207 }
208 return true;
209 }
210
GetFreeChunks(size_t page_idx)211 uint32_t SharedMemoryABI::GetFreeChunks(size_t page_idx) {
212 uint32_t layout =
213 page_header(page_idx)->layout.load(std::memory_order_relaxed);
214 const uint32_t num_chunks = GetNumChunksForLayout(layout);
215 uint32_t res = 0;
216 for (uint32_t i = 0; i < num_chunks; i++) {
217 res |= ((layout & kChunkMask) == kChunkFree) ? (1 << i) : 0;
218 layout >>= kChunkShift;
219 }
220 return res;
221 }
222
ReleaseChunk(Chunk chunk,ChunkState desired_chunk_state)223 size_t SharedMemoryABI::ReleaseChunk(Chunk chunk,
224 ChunkState desired_chunk_state) {
225 PERFETTO_DCHECK(desired_chunk_state == kChunkComplete ||
226 desired_chunk_state == kChunkFree);
227
228 size_t page_idx;
229 size_t chunk_idx;
230 std::tie(page_idx, chunk_idx) = GetPageAndChunkIndex(chunk);
231
232 // Reset header fields, so that the service can identify when the chunk's
233 // header has been initialized by the producer.
234 if (desired_chunk_state == kChunkFree)
235 ClearChunkHeader(chunk.header());
236
237 for (int attempt = 0; attempt < kRetryAttempts; attempt++) {
238 PageHeader* phdr = page_header(page_idx);
239 uint32_t layout = phdr->layout.load(std::memory_order_relaxed);
240 const size_t page_chunk_size = GetChunkSizeForLayout(layout);
241
242 // TODO(primiano): this should not be a CHECK, because a malicious producer
243 // could crash us by putting the chunk in an invalid state. This should
244 // gracefully fail. Keep a CHECK until then.
245 PERFETTO_CHECK(chunk.size() == page_chunk_size);
246 const uint32_t chunk_state =
247 ((layout >> (chunk_idx * kChunkShift)) & kChunkMask);
248
249 // Verify that the chunk is still in a state that allows the transition to
250 // |desired_chunk_state|. The only allowed transitions are:
251 // 1. kChunkBeingWritten -> kChunkComplete (Producer).
252 // 2. kChunkBeingRead -> kChunkFree (Service).
253 ChunkState expected_chunk_state;
254 if (desired_chunk_state == kChunkComplete) {
255 expected_chunk_state = kChunkBeingWritten;
256 } else {
257 expected_chunk_state = kChunkBeingRead;
258 }
259
260 // TODO(primiano): should not be a CHECK (same rationale of comment above).
261 PERFETTO_CHECK(chunk_state == expected_chunk_state);
262 uint32_t next_layout = layout;
263 next_layout &= ~(kChunkMask << (chunk_idx * kChunkShift));
264 next_layout |= (desired_chunk_state << (chunk_idx * kChunkShift));
265
266 // If we are freeing a chunk and all the other chunks in the page are free
267 // we should de-partition the page and mark it as clear.
268 if ((next_layout & kAllChunksMask) == kAllChunksFree)
269 next_layout = 0;
270
271 if (phdr->layout.compare_exchange_strong(layout, next_layout,
272 std::memory_order_acq_rel)) {
273 return page_idx;
274 }
275 WaitBeforeNextAttempt(attempt);
276 }
277 // Too much contention on this page. Give up. This page will be left pending
278 // forever but there isn't much more we can do at this point.
279 PERFETTO_DFATAL("Too much contention on page.");
280 return kInvalidPageIdx;
281 }
282
283 SharedMemoryABI::Chunk::Chunk() = default;
284
Chunk(uint8_t * begin,uint16_t size,uint8_t chunk_idx)285 SharedMemoryABI::Chunk::Chunk(uint8_t* begin, uint16_t size, uint8_t chunk_idx)
286 : begin_(begin), size_(size), chunk_idx_(chunk_idx) {
287 PERFETTO_CHECK(reinterpret_cast<uintptr_t>(begin) % kChunkAlignment == 0);
288 PERFETTO_CHECK(size > 0);
289 }
290
Chunk(Chunk && o)291 SharedMemoryABI::Chunk::Chunk(Chunk&& o) noexcept {
292 *this = std::move(o);
293 }
294
operator =(Chunk && o)295 SharedMemoryABI::Chunk& SharedMemoryABI::Chunk::operator=(Chunk&& o) {
296 begin_ = o.begin_;
297 size_ = o.size_;
298 chunk_idx_ = o.chunk_idx_;
299 o.begin_ = nullptr;
300 o.size_ = 0;
301 o.chunk_idx_ = 0;
302 return *this;
303 }
304
GetPageAndChunkIndex(const Chunk & chunk)305 std::pair<size_t, size_t> SharedMemoryABI::GetPageAndChunkIndex(
306 const Chunk& chunk) {
307 PERFETTO_DCHECK(chunk.is_valid());
308 PERFETTO_DCHECK(chunk.begin() >= start_);
309 PERFETTO_DCHECK(chunk.end() <= start_ + size_);
310
311 // TODO(primiano): The divisions below could be avoided if we cached
312 // |page_shift_|.
313 const uintptr_t rel_addr = static_cast<uintptr_t>(chunk.begin() - start_);
314 const size_t page_idx = rel_addr / page_size_;
315 const size_t offset = rel_addr % page_size_;
316 PERFETTO_DCHECK(offset >= sizeof(PageHeader));
317 PERFETTO_DCHECK(offset % kChunkAlignment == 0);
318 PERFETTO_DCHECK((offset - sizeof(PageHeader)) % chunk.size() == 0);
319 const size_t chunk_idx = (offset - sizeof(PageHeader)) / chunk.size();
320 PERFETTO_DCHECK(chunk_idx < kMaxChunksPerPage);
321 PERFETTO_DCHECK(chunk_idx < GetNumChunksForLayout(GetPageLayout(page_idx)));
322 return std::make_pair(page_idx, chunk_idx);
323 }
324
325 } // namespace perfetto
326