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 #ifndef INCLUDE_PERFETTO_EXT_TRACING_CORE_SHARED_MEMORY_ABI_H_ 18 #define INCLUDE_PERFETTO_EXT_TRACING_CORE_SHARED_MEMORY_ABI_H_ 19 20 #include <stddef.h> 21 #include <stdint.h> 22 23 #include <array> 24 #include <atomic> 25 #include <bitset> 26 #include <thread> 27 #include <type_traits> 28 #include <utility> 29 30 #include "perfetto/base/logging.h" 31 #include "perfetto/protozero/proto_utils.h" 32 33 namespace perfetto { 34 35 // This file defines the binary interface of the memory buffers shared between 36 // Producer and Service. This is a long-term stable ABI and has to be backwards 37 // compatible to deal with mismatching Producer and Service versions. 38 // 39 // Overview 40 // -------- 41 // SMB := "Shared Memory Buffer". 42 // In the most typical case of a multi-process architecture (i.e. Producer and 43 // Service are hosted by different processes), a Producer means almost always 44 // a "client process producing data" (almost: in some cases a process might host 45 // > 1 Producer, if it links two libraries, independent of each other, that both 46 // use Perfetto tracing). 47 // The Service has one SMB for each Producer. 48 // A producer has one or (typically) more data sources. They all share the same 49 // SMB. 50 // The SMB is a staging area to decouple data sources living in the Producer 51 // and allow them to do non-blocking async writes. 52 // The SMB is *not* the ultimate logging buffer seen by the Consumer. That one 53 // is larger (~MBs) and not shared with Producers. 54 // Each SMB is small, typically few KB. Its size is configurable by the producer 55 // within a max limit of ~MB (see kMaxShmSize in tracing_service_impl.cc). 56 // The SMB is partitioned into fixed-size Page(s). The size of the Pages are 57 // determined by each Producer at connection time and cannot be changed. 58 // Hence, different producers can have SMB(s) that have a different Page size 59 // from each other, but the page size will be constant throughout all the 60 // lifetime of the SMB. 61 // Page(s) are partitioned by the Producer into variable size Chunk(s): 62 // 63 // +------------+ +--------------------------+ 64 // | Producer 1 | <-> | SMB 1 [~32K - 1MB] | 65 // +------------+ +--------+--------+--------+ 66 // | Page | Page | Page | 67 // +--------+--------+--------+ 68 // | Chunk | | Chunk | 69 // +--------+ Chunk +--------+ <----+ 70 // | Chunk | | Chunk | | 71 // +--------+--------+--------+ +---------------------+ 72 // | Service | 73 // +------------+ +--------------------------+ +---------------------+ 74 // | Producer 2 | <-> | SMB 2 [~32K - 1MB] | /| large ring buffers | 75 // +------------+ +--------+--------+--------+ <--+ | (100K - several MB) | 76 // | Page | Page | Page | +---------------------+ 77 // +--------+--------+--------+ 78 // | Chunk | | Chunk | 79 // +--------+ Chunk +--------+ 80 // | Chunk | | Chunk | 81 // +--------+--------+--------+ 82 // 83 // * Sizes of both SMB and ring buffers are purely indicative and decided at 84 // configuration time by the Producer (for SMB sizes) and the Consumer (for the 85 // final ring buffer size). 86 87 // Page 88 // ---- 89 // A page is a portion of the shared memory buffer and defines the granularity 90 // of the interaction between the Producer and tracing Service. When scanning 91 // the shared memory buffer to determine if something should be moved to the 92 // central logging buffers, the Service most of the times looks at and moves 93 // whole pages. Similarly, the Producer sends an IPC to invite the Service to 94 // drain the shared memory buffer only when a whole page is filled. 95 // Having fixed the total SMB size (hence the total memory overhead), the page 96 // size is a triangular tradeoff between: 97 // 1) IPC traffic: smaller pages -> more IPCs. 98 // 2) Producer lock freedom: larger pages -> larger chunks -> data sources can 99 // write more data without needing to swap chunks and synchronize. 100 // 3) Risk of write-starving the SMB: larger pages -> higher chance that the 101 // Service won't manage to drain them and the SMB remains full. 102 // The page size, on the other side, has no implications on wasted memory due to 103 // fragmentations (see Chunk below). 104 // The size of the page is chosen by the Service at connection time and stays 105 // fixed throughout all the lifetime of the Producer. Different producers (i.e. 106 // ~ different client processes) can use different page sizes. 107 // The page size must be an integer multiple of 4k (this is to allow VM page 108 // stealing optimizations) and obviously has to be an integer divisor of the 109 // total SMB size. 110 111 // Chunk 112 // ----- 113 // A chunk is a portion of a Page which is written and handled by a Producer. 114 // A chunk contains a linear sequence of TracePacket(s) (the root proto). 115 // A chunk cannot be written concurrently by two data sources. Protobufs must be 116 // encoded as contiguous byte streams and cannot be interleaved. Therefore, on 117 // the Producer side, a chunk is almost always owned exclusively by one thread 118 // (% extremely peculiar slow-path cases). 119 // Chunks are essentially single-writer single-thread lock-free arenas. Locking 120 // happens only when a Chunk is full and a new one needs to be acquired. 121 // Locking happens only within the scope of a Producer process. There is no 122 // inter-process locking. The Producer cannot lock the Service and viceversa. 123 // In the worst case, any of the two can starve the SMB, by marking all chunks 124 // as either being read or written. But that has the only side effect of 125 // losing the trace data. 126 // The Producer can decide to partition each page into a number of limited 127 // configurations (e.g., 1 page == 1 chunk, 1 page == 2 chunks and so on). 128 129 // TracePacket 130 // ----------- 131 // Is the atom of tracing. Putting aside pages and chunks a trace is merely a 132 // sequence of TracePacket(s). TracePacket is the root protobuf message. 133 // A TracePacket can span across several chunks (hence even across several 134 // pages). A TracePacket can therefore be >> chunk size, >> page size and even 135 // >> SMB size. The Chunk header carries metadata to deal with the TracePacket 136 // splitting case. 137 138 // Use only explicitly-sized types below. DO NOT use size_t or any architecture 139 // dependent size (e.g. size_t) in the struct fields. This buffer will be read 140 // and written by processes that have a different bitness in the same OS. 141 // Instead it's fine to assume little-endianess. Big-endian is a dream we are 142 // not currently pursuing. 143 144 class SharedMemoryABI { 145 public: 146 // This is due to Chunk::size being 16 bits. 147 static constexpr size_t kMaxPageSize = 64 * 1024; 148 149 // "14" is the max number that can be encoded in a 32 bit atomic word using 150 // 2 state bits per Chunk and leaving 4 bits for the page layout. 151 // See PageLayout below. 152 static constexpr size_t kMaxChunksPerPage = 14; 153 154 // Each TracePacket in the Chunk is prefixed by a 4 bytes redundant VarInt 155 // (see proto_utils.h) stating its size. 156 static constexpr size_t kPacketHeaderSize = 4; 157 158 // TraceWriter specifies this invalid packet/fragment size to signal to the 159 // service that a packet should be discarded, because the TraceWriter couldn't 160 // write its remaining fragments (e.g. because the SMB was exhausted). 161 static constexpr size_t kPacketSizeDropPacket = 162 protozero::proto_utils::kMaxMessageLength; 163 164 // Chunk states and transitions: 165 // kChunkFree <----------------+ 166 // | (Producer) | 167 // V | 168 // kChunkBeingWritten | 169 // | (Producer) | 170 // V | 171 // kChunkComplete | 172 // | (Service) | 173 // V | 174 // kChunkBeingRead | 175 // | (Service) | 176 // +------------------------+ 177 enum ChunkState : uint32_t { 178 // The Chunk is free. The Service shall never touch it, the Producer can 179 // acquire it and transition it into kChunkBeingWritten. 180 kChunkFree = 0, 181 182 // The Chunk is being used by the Producer and is not complete yet. 183 // The Service shall never touch kChunkBeingWritten pages. 184 kChunkBeingWritten = 1, 185 186 // The Service is moving the page into its non-shared ring buffer. The 187 // Producer shall never touch kChunkBeingRead pages. 188 kChunkBeingRead = 2, 189 190 // The Producer is done writing the page and won't touch it again. The 191 // Service can now move it to its non-shared ring buffer. 192 // kAllChunksComplete relies on this being == 3. 193 kChunkComplete = 3, 194 }; 195 static constexpr const char* kChunkStateStr[] = {"Free", "BeingWritten", 196 "BeingRead", "Complete"}; 197 198 enum PageLayout : uint32_t { 199 // The page is fully free and has not been partitioned yet. 200 kPageNotPartitioned = 0, 201 202 // TODO(primiano): Aligning a chunk @ 16 bytes could allow to use faster 203 // intrinsics based on quad-word moves. Do the math and check what is the 204 // fragmentation loss. 205 206 // align4(X) := the largest integer N s.t. (N % 4) == 0 && N <= X. 207 // 8 == sizeof(PageHeader). 208 kPageDiv1 = 1, // Only one chunk of size: PAGE_SIZE - 8. 209 kPageDiv2 = 2, // Two chunks of size: align4((PAGE_SIZE - 8) / 2). 210 kPageDiv4 = 3, // Four chunks of size: align4((PAGE_SIZE - 8) / 4). 211 kPageDiv7 = 4, // Seven chunks of size: align4((PAGE_SIZE - 8) / 7). 212 kPageDiv14 = 5, // Fourteen chunks of size: align4((PAGE_SIZE - 8) / 14). 213 214 // The rationale for 7 and 14 above is to maximize the page usage for the 215 // likely case of |page_size| == 4096: 216 // (((4096 - 8) / 14) % 4) == 0, while (((4096 - 8) / 16 % 4)) == 3. So 217 // Div16 would waste 3 * 16 = 48 bytes per page for chunk alignment gaps. 218 219 kPageDivReserved1 = 6, 220 kPageDivReserved2 = 7, 221 kNumPageLayouts = 8, 222 }; 223 224 // Keep this consistent with the PageLayout enum above. 225 static constexpr uint32_t kNumChunksForLayout[] = {0, 1, 2, 4, 7, 14, 0, 0}; 226 227 // Layout of a Page. 228 // +===================================================+ 229 // | Page header [8 bytes] | 230 // | Tells how many chunks there are, how big they are | 231 // | and their state (free, read, write, complete). | 232 // +===================================================+ 233 // +***************************************************+ 234 // | Chunk #0 header [8 bytes] | 235 // | Tells how many packets there are and whether the | 236 // | whether the 1st and last ones are fragmented. | 237 // | Also has a chunk id to reassemble fragments. | 238 // +***************************************************+ 239 // +---------------------------------------------------+ 240 // | Packet #0 size [varint, up to 4 bytes] | 241 // + - - - - - - - - - - - - - - - - - - - - - - - - - + 242 // | Packet #0 payload | 243 // | A TracePacket protobuf message | 244 // +---------------------------------------------------+ 245 // ... 246 // + . . . . . . . . . . . . . . . . . . . . . . . . . + 247 // | Optional padding to maintain aligment | 248 // + . . . . . . . . . . . . . . . . . . . . . . . . . + 249 // +---------------------------------------------------+ 250 // | Packet #N size [varint, up to 4 bytes] | 251 // + - - - - - - - - - - - - - - - - - - - - - - - - - + 252 // | Packet #N payload | 253 // | A TracePacket protobuf message | 254 // +---------------------------------------------------+ 255 // ... 256 // +***************************************************+ 257 // | Chunk #M header [8 bytes] | 258 // ... 259 260 // Alignment applies to start offset only. The Chunk size is *not* aligned. 261 static constexpr uint32_t kChunkAlignment = 4; 262 static constexpr uint32_t kChunkShift = 2; 263 static constexpr uint32_t kChunkMask = 0x3; 264 static constexpr uint32_t kLayoutMask = 0x70000000; 265 static constexpr uint32_t kLayoutShift = 28; 266 static constexpr uint32_t kAllChunksMask = 0x0FFFFFFF; 267 268 // This assumes that kChunkComplete == 3. 269 static constexpr uint32_t kAllChunksComplete = 0x0FFFFFFF; 270 static constexpr uint32_t kAllChunksFree = 0; 271 static constexpr size_t kInvalidPageIdx = static_cast<size_t>(-1); 272 273 // There is one page header per page, at the beginning of the page. 274 struct PageHeader { 275 // |layout| bits: 276 // [31] [30:28] [27:26] ... [1:0] 277 // | | | | | 278 // | | | | +---------- ChunkState[0] 279 // | | | +--------------- ChunkState[12..1] 280 // | | +--------------------- ChunkState[13] 281 // | +----------------------------- PageLayout (0 == page fully free) 282 // +------------------------------------ Reserved for future use 283 std::atomic<uint32_t> layout; 284 285 // If we'll ever going to use this in the future it might come handy 286 // reviving the kPageBeingPartitioned logic (look in git log, it was there 287 // at some point in the past). 288 uint32_t reserved; 289 }; 290 291 // There is one Chunk header per chunk (hence PageLayout per page) at the 292 // beginning of each chunk. 293 struct ChunkHeader { 294 enum Flags : uint8_t { 295 // If set, the first TracePacket in the chunk is partial and continues 296 // from |chunk_id| - 1 (within the same |writer_id|). 297 kFirstPacketContinuesFromPrevChunk = 1 << 0, 298 299 // If set, the last TracePacket in the chunk is partial and continues on 300 // |chunk_id| + 1 (within the same |writer_id|). 301 kLastPacketContinuesOnNextChunk = 1 << 1, 302 303 // If set, the last (fragmented) TracePacket in the chunk has holes (even 304 // if the chunk is marked as kChunkComplete) that need to be patched 305 // out-of-band before the chunk can be read. 306 kChunkNeedsPatching = 1 << 2, 307 }; 308 309 struct Packets { 310 // Number of valid TracePacket protobuf messages contained in the chunk. 311 // Each TracePacket is prefixed by its own size. This field is 312 // monotonically updated by the Producer with release store semantic when 313 // the packet at position |count| is started. This last packet may not be 314 // considered complete until |count| is incremented for the subsequent 315 // packet or the chunk is completed. 316 uint16_t count : 10; 317 static constexpr size_t kMaxCount = (1 << 10) - 1; 318 319 // See Flags above. 320 uint16_t flags : 6; 321 }; 322 323 // A monotonic counter of the chunk within the scoped of a |writer_id|. 324 // The tuple (ProducerID, WriterID, ChunkID) allows to figure out if two 325 // chunks are contiguous (and hence a trace packets spanning across them can 326 // be glued) or we had some holes due to the ring buffer wrapping. 327 // This is set only when transitioning from kChunkFree to kChunkBeingWritten 328 // and remains unchanged throughout the remaining lifetime of the chunk. 329 std::atomic<uint32_t> chunk_id; 330 331 // ID of the writer, unique within the producer. 332 // Like |chunk_id|, this is set only when transitioning from kChunkFree to 333 // kChunkBeingWritten. 334 std::atomic<uint16_t> writer_id; 335 336 // There is no ProducerID here. The service figures that out from the IPC 337 // channel, which is unspoofable. 338 339 // Updated with release-store semantics. 340 std::atomic<Packets> packets; 341 }; 342 343 class Chunk { 344 public: 345 Chunk(); // Constructs an invalid chunk. 346 347 // Chunk is move-only, to document the scope of the Acquire/Release 348 // TryLock operations below. 349 Chunk(const Chunk&) = delete; 350 Chunk operator=(const Chunk&) = delete; 351 Chunk(Chunk&&) noexcept; 352 Chunk& operator=(Chunk&&); 353 begin()354 uint8_t* begin() const { return begin_; } end()355 uint8_t* end() const { return begin_ + size_; } 356 357 // Size, including Chunk header. size()358 size_t size() const { return size_; } 359 360 // Begin of the first packet (or packet fragment). payload_begin()361 uint8_t* payload_begin() const { return begin_ + sizeof(ChunkHeader); } payload_size()362 size_t payload_size() const { 363 PERFETTO_DCHECK(size_ >= sizeof(ChunkHeader)); 364 return size_ - sizeof(ChunkHeader); 365 } 366 is_valid()367 bool is_valid() const { return begin_ && size_; } 368 369 // Index of the chunk within the page [0..13] (13 comes from kPageDiv14). chunk_idx()370 uint8_t chunk_idx() const { return chunk_idx_; } 371 header()372 ChunkHeader* header() { return reinterpret_cast<ChunkHeader*>(begin_); } 373 writer_id()374 uint16_t writer_id() { 375 return header()->writer_id.load(std::memory_order_relaxed); 376 } 377 378 // Returns the count of packets and the flags with acquire-load semantics. GetPacketCountAndFlags()379 std::pair<uint16_t, uint8_t> GetPacketCountAndFlags() { 380 auto packets = header()->packets.load(std::memory_order_acquire); 381 const uint16_t packets_count = packets.count; 382 const uint8_t packets_flags = packets.flags; 383 return std::make_pair(packets_count, packets_flags); 384 } 385 386 // Increases |packets.count| with release semantics (note, however, that the 387 // packet count is incremented *before* starting writing a packet). Returns 388 // the new packet count. The increment is atomic but NOT race-free (i.e. no 389 // CAS). Only the Producer is supposed to perform this increment, and it's 390 // supposed to do that in a thread-safe way (holding a lock). A Chunk cannot 391 // be shared by multiple Producer threads without locking. The packet count 392 // is cleared by TryAcquireChunk(), when passing the new header for the 393 // chunk. IncrementPacketCount()394 uint16_t IncrementPacketCount() { 395 ChunkHeader* chunk_header = header(); 396 auto packets = chunk_header->packets.load(std::memory_order_relaxed); 397 packets.count++; 398 chunk_header->packets.store(packets, std::memory_order_release); 399 return packets.count; 400 } 401 402 // Increases |packets.count| to the given |packet_count|, but only if 403 // |packet_count| is larger than the current value of |packets.count|. 404 // Returns the new packet count. Same atomicity guarantees as 405 // IncrementPacketCount(). IncreasePacketCountTo(uint16_t packet_count)406 uint16_t IncreasePacketCountTo(uint16_t packet_count) { 407 ChunkHeader* chunk_header = header(); 408 auto packets = chunk_header->packets.load(std::memory_order_relaxed); 409 if (packets.count < packet_count) 410 packets.count = packet_count; 411 chunk_header->packets.store(packets, std::memory_order_release); 412 return packets.count; 413 } 414 415 // Flags are cleared by TryAcquireChunk(), by passing the new header for 416 // the chunk. SetFlag(ChunkHeader::Flags flag)417 void SetFlag(ChunkHeader::Flags flag) { 418 ChunkHeader* chunk_header = header(); 419 auto packets = chunk_header->packets.load(std::memory_order_relaxed); 420 packets.flags |= flag; 421 chunk_header->packets.store(packets, std::memory_order_release); 422 } 423 424 private: 425 friend class SharedMemoryABI; 426 Chunk(uint8_t* begin, uint16_t size, uint8_t chunk_idx); 427 428 // Don't add extra fields, keep the move operator fast. 429 uint8_t* begin_ = nullptr; 430 uint16_t size_ = 0; 431 uint8_t chunk_idx_ = 0; 432 }; 433 434 // Construct an instance from an existing shared memory buffer. 435 SharedMemoryABI(uint8_t* start, size_t size, size_t page_size); 436 SharedMemoryABI(); 437 438 void Initialize(uint8_t* start, size_t size, size_t page_size); 439 start()440 uint8_t* start() const { return start_; } end()441 uint8_t* end() const { return start_ + size_; } size()442 size_t size() const { return size_; } page_size()443 size_t page_size() const { return page_size_; } num_pages()444 size_t num_pages() const { return num_pages_; } is_valid()445 bool is_valid() { return num_pages() > 0; } 446 page_start(size_t page_idx)447 uint8_t* page_start(size_t page_idx) { 448 PERFETTO_DCHECK(page_idx < num_pages_); 449 return start_ + page_size_ * page_idx; 450 } 451 page_header(size_t page_idx)452 PageHeader* page_header(size_t page_idx) { 453 return reinterpret_cast<PageHeader*>(page_start(page_idx)); 454 } 455 456 // Returns true if the page is fully clear and has not been partitioned yet. 457 // The state of the page can change at any point after this returns (or even 458 // before). The Producer should use this only as a hint to decide out whether 459 // it should TryPartitionPage() or acquire an individual chunk. is_page_free(size_t page_idx)460 bool is_page_free(size_t page_idx) { 461 return page_header(page_idx)->layout.load(std::memory_order_relaxed) == 0; 462 } 463 464 // Returns true if all chunks in the page are kChunkComplete. As above, this 465 // is advisory only. The Service is supposed to use this only to decide 466 // whether to TryAcquireAllChunksForReading() or not. is_page_complete(size_t page_idx)467 bool is_page_complete(size_t page_idx) { 468 auto layout = page_header(page_idx)->layout.load(std::memory_order_relaxed); 469 const uint32_t num_chunks = GetNumChunksForLayout(layout); 470 if (num_chunks == 0) 471 return false; // Non partitioned pages cannot be complete. 472 return (layout & kAllChunksMask) == 473 (kAllChunksComplete & ((1 << (num_chunks * kChunkShift)) - 1)); 474 } 475 476 // For testing / debugging only. page_header_dbg(size_t page_idx)477 std::string page_header_dbg(size_t page_idx) { 478 uint32_t x = page_header(page_idx)->layout.load(std::memory_order_relaxed); 479 return std::bitset<32>(x).to_string(); 480 } 481 482 // Returns the page layout, which is a bitmap that specifies the chunking 483 // layout of the page and each chunk's current state. Reads with an 484 // acquire-load semantic to ensure a producer's writes corresponding to an 485 // update of the layout (e.g. clearing a chunk's header) are observed 486 // consistently. GetPageLayout(size_t page_idx)487 uint32_t GetPageLayout(size_t page_idx) { 488 return page_header(page_idx)->layout.load(std::memory_order_acquire); 489 } 490 491 // Returns a bitmap in which each bit is set if the corresponding Chunk exists 492 // in the page (according to the page layout) and is free. If the page is not 493 // partitioned it returns 0 (as if the page had no free chunks). 494 uint32_t GetFreeChunks(size_t page_idx); 495 496 // Tries to atomically partition a page with the given |layout|. Returns true 497 // if the page was free and has been partitioned with the given |layout|, 498 // false if the page wasn't free anymore by the time we got there. 499 // If succeeds all the chunks are atomically set in the kChunkFree state. 500 bool TryPartitionPage(size_t page_idx, PageLayout layout); 501 502 // Tries to atomically mark a single chunk within the page as 503 // kChunkBeingWritten. Returns an invalid chunk if the page is not partitioned 504 // or the chunk is not in the kChunkFree state. If succeeds sets the chunk 505 // header to |header|. TryAcquireChunkForWriting(size_t page_idx,size_t chunk_idx,const ChunkHeader * header)506 Chunk TryAcquireChunkForWriting(size_t page_idx, 507 size_t chunk_idx, 508 const ChunkHeader* header) { 509 return TryAcquireChunk(page_idx, chunk_idx, kChunkBeingWritten, header); 510 } 511 512 // Similar to TryAcquireChunkForWriting. Fails if the chunk isn't in the 513 // kChunkComplete state. TryAcquireChunkForReading(size_t page_idx,size_t chunk_idx)514 Chunk TryAcquireChunkForReading(size_t page_idx, size_t chunk_idx) { 515 return TryAcquireChunk(page_idx, chunk_idx, kChunkBeingRead, nullptr); 516 } 517 518 // The caller must have successfully TryAcquireAllChunksForReading(). 519 Chunk GetChunkUnchecked(size_t page_idx, 520 uint32_t page_layout, 521 size_t chunk_idx); 522 523 // Puts a chunk into the kChunkComplete state. Returns the page index. ReleaseChunkAsComplete(Chunk chunk)524 size_t ReleaseChunkAsComplete(Chunk chunk) { 525 return ReleaseChunk(std::move(chunk), kChunkComplete); 526 } 527 528 // Puts a chunk into the kChunkFree state. Returns the page index. ReleaseChunkAsFree(Chunk chunk)529 size_t ReleaseChunkAsFree(Chunk chunk) { 530 return ReleaseChunk(std::move(chunk), kChunkFree); 531 } 532 GetChunkState(size_t page_idx,size_t chunk_idx)533 ChunkState GetChunkState(size_t page_idx, size_t chunk_idx) { 534 PageHeader* phdr = page_header(page_idx); 535 uint32_t layout = phdr->layout.load(std::memory_order_relaxed); 536 return GetChunkStateFromLayout(layout, chunk_idx); 537 } 538 539 std::pair<size_t, size_t> GetPageAndChunkIndex(const Chunk& chunk); 540 GetChunkSizeForLayout(uint32_t page_layout)541 uint16_t GetChunkSizeForLayout(uint32_t page_layout) const { 542 return chunk_sizes_[(page_layout & kLayoutMask) >> kLayoutShift]; 543 } 544 GetChunkStateFromLayout(uint32_t page_layout,size_t chunk_idx)545 static ChunkState GetChunkStateFromLayout(uint32_t page_layout, 546 size_t chunk_idx) { 547 return static_cast<ChunkState>((page_layout >> (chunk_idx * kChunkShift)) & 548 kChunkMask); 549 } 550 GetNumChunksForLayout(uint32_t page_layout)551 static constexpr uint32_t GetNumChunksForLayout(uint32_t page_layout) { 552 return kNumChunksForLayout[(page_layout & kLayoutMask) >> kLayoutShift]; 553 } 554 555 // Returns a bitmap in which each bit is set if the corresponding Chunk exists 556 // in the page (according to the page layout) and is not free. If the page is 557 // not partitioned it returns 0 (as if the page had no used chunks). Bit N 558 // corresponds to Chunk N. GetUsedChunks(uint32_t page_layout)559 static uint32_t GetUsedChunks(uint32_t page_layout) { 560 const uint32_t num_chunks = GetNumChunksForLayout(page_layout); 561 uint32_t res = 0; 562 for (uint32_t i = 0; i < num_chunks; i++) { 563 res |= ((page_layout & kChunkMask) != kChunkFree) ? (1 << i) : 0; 564 page_layout >>= kChunkShift; 565 } 566 return res; 567 } 568 569 private: 570 SharedMemoryABI(const SharedMemoryABI&) = delete; 571 SharedMemoryABI& operator=(const SharedMemoryABI&) = delete; 572 573 Chunk TryAcquireChunk(size_t page_idx, 574 size_t chunk_idx, 575 ChunkState, 576 const ChunkHeader*); 577 size_t ReleaseChunk(Chunk chunk, ChunkState); 578 579 uint8_t* start_ = nullptr; 580 size_t size_ = 0; 581 size_t page_size_ = 0; 582 size_t num_pages_ = 0; 583 std::array<uint16_t, kNumPageLayouts> chunk_sizes_; 584 }; 585 586 } // namespace perfetto 587 588 #endif // INCLUDE_PERFETTO_EXT_TRACING_CORE_SHARED_MEMORY_ABI_H_ 589