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   static constexpr size_t kMinPageSize = 4 * 1024;
147 
148   // This is due to Chunk::size being 16 bits.
149   static constexpr size_t kMaxPageSize = 64 * 1024;
150 
151   // "14" is the max number that can be encoded in a 32 bit atomic word using
152   // 2 state bits per Chunk and leaving 4 bits for the page layout.
153   // See PageLayout below.
154   static constexpr size_t kMaxChunksPerPage = 14;
155 
156   // Each TracePacket in the Chunk is prefixed by a 4 bytes redundant VarInt
157   // (see proto_utils.h) stating its size.
158   static constexpr size_t kPacketHeaderSize = 4;
159 
160   // TraceWriter specifies this invalid packet/fragment size to signal to the
161   // service that a packet should be discarded, because the TraceWriter couldn't
162   // write its remaining fragments (e.g. because the SMB was exhausted).
163   static constexpr size_t kPacketSizeDropPacket =
164       protozero::proto_utils::kMaxMessageLength;
165 
166   // Chunk states and transitions:
167   //    kChunkFree  <----------------+
168   //         |  (Producer)           |
169   //         V                       |
170   //  kChunkBeingWritten             |
171   //         |  (Producer)           |
172   //         V                       |
173   //  kChunkComplete                 |
174   //         |  (Service)            |
175   //         V                       |
176   //  kChunkBeingRead                |
177   //        |   (Service)            |
178   //        +------------------------+
179   enum ChunkState : uint32_t {
180     // The Chunk is free. The Service shall never touch it, the Producer can
181     // acquire it and transition it into kChunkBeingWritten.
182     kChunkFree = 0,
183 
184     // The Chunk is being used by the Producer and is not complete yet.
185     // The Service shall never touch kChunkBeingWritten pages.
186     kChunkBeingWritten = 1,
187 
188     // The Service is moving the page into its non-shared ring buffer. The
189     // Producer shall never touch kChunkBeingRead pages.
190     kChunkBeingRead = 2,
191 
192     // The Producer is done writing the page and won't touch it again. The
193     // Service can now move it to its non-shared ring buffer.
194     // kAllChunksComplete relies on this being == 3.
195     kChunkComplete = 3,
196   };
197   static constexpr const char* kChunkStateStr[] = {"Free", "BeingWritten",
198                                                    "BeingRead", "Complete"};
199 
200   enum PageLayout : uint32_t {
201     // The page is fully free and has not been partitioned yet.
202     kPageNotPartitioned = 0,
203 
204     // TODO(primiano): Aligning a chunk @ 16 bytes could allow to use faster
205     // intrinsics based on quad-word moves. Do the math and check what is the
206     // fragmentation loss.
207 
208     // align4(X) := the largest integer N s.t. (N % 4) == 0 && N <= X.
209     // 8 == sizeof(PageHeader).
210     kPageDiv1 = 1,   // Only one chunk of size: PAGE_SIZE - 8.
211     kPageDiv2 = 2,   // Two chunks of size: align4((PAGE_SIZE - 8) / 2).
212     kPageDiv4 = 3,   // Four chunks of size: align4((PAGE_SIZE - 8) / 4).
213     kPageDiv7 = 4,   // Seven chunks of size: align4((PAGE_SIZE - 8) / 7).
214     kPageDiv14 = 5,  // Fourteen chunks of size: align4((PAGE_SIZE - 8) / 14).
215 
216     // The rationale for 7 and 14 above is to maximize the page usage for the
217     // likely case of |page_size| == 4096:
218     // (((4096 - 8) / 14) % 4) == 0, while (((4096 - 8) / 16 % 4)) == 3. So
219     // Div16 would waste 3 * 16 = 48 bytes per page for chunk alignment gaps.
220 
221     kPageDivReserved1 = 6,
222     kPageDivReserved2 = 7,
223     kNumPageLayouts = 8,
224   };
225 
226   // Keep this consistent with the PageLayout enum above.
227   static constexpr uint32_t kNumChunksForLayout[] = {0, 1, 2, 4, 7, 14, 0, 0};
228 
229   // Layout of a Page.
230   // +===================================================+
231   // | Page header [8 bytes]                             |
232   // | Tells how many chunks there are, how big they are |
233   // | and their state (free, read, write, complete).    |
234   // +===================================================+
235   // +***************************************************+
236   // | Chunk #0 header [8 bytes]                         |
237   // | Tells how many packets there are and whether the  |
238   // | whether the 1st and last ones are fragmented.     |
239   // | Also has a chunk id to reassemble fragments.    |
240   // +***************************************************+
241   // +---------------------------------------------------+
242   // | Packet #0 size [varint, up to 4 bytes]            |
243   // + - - - - - - - - - - - - - - - - - - - - - - - - - +
244   // | Packet #0 payload                                 |
245   // | A TracePacket protobuf message                    |
246   // +---------------------------------------------------+
247   //                         ...
248   // + . . . . . . . . . . . . . . . . . . . . . . . . . +
249   // |      Optional padding to maintain aligment        |
250   // + . . . . . . . . . . . . . . . . . . . . . . . . . +
251   // +---------------------------------------------------+
252   // | Packet #N size [varint, up to 4 bytes]            |
253   // + - - - - - - - - - - - - - - - - - - - - - - - - - +
254   // | Packet #N payload                                 |
255   // | A TracePacket protobuf message                    |
256   // +---------------------------------------------------+
257   //                         ...
258   // +***************************************************+
259   // | Chunk #M header [8 bytes]                         |
260   //                         ...
261 
262   // Alignment applies to start offset only. The Chunk size is *not* aligned.
263   static constexpr uint32_t kChunkAlignment = 4;
264   static constexpr uint32_t kChunkShift = 2;
265   static constexpr uint32_t kChunkMask = 0x3;
266   static constexpr uint32_t kLayoutMask = 0x70000000;
267   static constexpr uint32_t kLayoutShift = 28;
268   static constexpr uint32_t kAllChunksMask = 0x0FFFFFFF;
269 
270   // This assumes that kChunkComplete == 3.
271   static constexpr uint32_t kAllChunksComplete = 0x0FFFFFFF;
272   static constexpr uint32_t kAllChunksFree = 0;
273   static constexpr size_t kInvalidPageIdx = static_cast<size_t>(-1);
274 
275   // There is one page header per page, at the beginning of the page.
276   struct PageHeader {
277     // |layout| bits:
278     // [31] [30:28] [27:26] ... [1:0]
279     //  |      |       |     |    |
280     //  |      |       |     |    +---------- ChunkState[0]
281     //  |      |       |     +--------------- ChunkState[12..1]
282     //  |      |       +--------------------- ChunkState[13]
283     //  |      +----------------------------- PageLayout (0 == page fully free)
284     //  +------------------------------------ Reserved for future use
285     std::atomic<uint32_t> layout;
286 
287     // If we'll ever going to use this in the future it might come handy
288     // reviving the kPageBeingPartitioned logic (look in git log, it was there
289     // at some point in the past).
290     uint32_t reserved;
291   };
292 
293   // There is one Chunk header per chunk (hence PageLayout per page) at the
294   // beginning of each chunk.
295   struct ChunkHeader {
296     enum Flags : uint8_t {
297       // If set, the first TracePacket in the chunk is partial and continues
298       // from |chunk_id| - 1 (within the same |writer_id|).
299       kFirstPacketContinuesFromPrevChunk = 1 << 0,
300 
301       // If set, the last TracePacket in the chunk is partial and continues on
302       // |chunk_id| + 1 (within the same |writer_id|).
303       kLastPacketContinuesOnNextChunk = 1 << 1,
304 
305       // If set, the last (fragmented) TracePacket in the chunk has holes (even
306       // if the chunk is marked as kChunkComplete) that need to be patched
307       // out-of-band before the chunk can be read.
308       kChunkNeedsPatching = 1 << 2,
309     };
310 
311     struct Packets {
312       // Number of valid TracePacket protobuf messages contained in the chunk.
313       // Each TracePacket is prefixed by its own size. This field is
314       // monotonically updated by the Producer with release store semantic when
315       // the packet at position |count| is started. This last packet may not be
316       // considered complete until |count| is incremented for the subsequent
317       // packet or the chunk is completed.
318       uint16_t count : 10;
319       static constexpr size_t kMaxCount = (1 << 10) - 1;
320 
321       // See Flags above.
322       uint16_t flags : 6;
323     };
324 
325     // A monotonic counter of the chunk within the scoped of a |writer_id|.
326     // The tuple (ProducerID, WriterID, ChunkID) allows to figure out if two
327     // chunks are contiguous (and hence a trace packets spanning across them can
328     // be glued) or we had some holes due to the ring buffer wrapping.
329     // This is set only when transitioning from kChunkFree to kChunkBeingWritten
330     // and remains unchanged throughout the remaining lifetime of the chunk.
331     std::atomic<uint32_t> chunk_id;
332 
333     // ID of the writer, unique within the producer.
334     // Like |chunk_id|, this is set only when transitioning from kChunkFree to
335     // kChunkBeingWritten.
336     std::atomic<uint16_t> writer_id;
337 
338     // There is no ProducerID here. The service figures that out from the IPC
339     // channel, which is unspoofable.
340 
341     // Updated with release-store semantics.
342     std::atomic<Packets> packets;
343   };
344 
345   class Chunk {
346    public:
347     Chunk();  // Constructs an invalid chunk.
348 
349     // Chunk is move-only, to document the scope of the Acquire/Release
350     // TryLock operations below.
351     Chunk(const Chunk&) = delete;
352     Chunk operator=(const Chunk&) = delete;
353     Chunk(Chunk&&) noexcept;
354     Chunk& operator=(Chunk&&);
355 
begin()356     uint8_t* begin() const { return begin_; }
end()357     uint8_t* end() const { return begin_ + size_; }
358 
359     // Size, including Chunk header.
size()360     size_t size() const { return size_; }
361 
362     // Begin of the first packet (or packet fragment).
payload_begin()363     uint8_t* payload_begin() const { return begin_ + sizeof(ChunkHeader); }
payload_size()364     size_t payload_size() const {
365       PERFETTO_DCHECK(size_ >= sizeof(ChunkHeader));
366       return size_ - sizeof(ChunkHeader);
367     }
368 
is_valid()369     bool is_valid() const { return begin_ && size_; }
370 
371     // Index of the chunk within the page [0..13] (13 comes from kPageDiv14).
chunk_idx()372     uint8_t chunk_idx() const { return chunk_idx_; }
373 
header()374     ChunkHeader* header() { return reinterpret_cast<ChunkHeader*>(begin_); }
375 
writer_id()376     uint16_t writer_id() {
377       return header()->writer_id.load(std::memory_order_relaxed);
378     }
379 
380     // Returns the count of packets and the flags with acquire-load semantics.
GetPacketCountAndFlags()381     std::pair<uint16_t, uint8_t> GetPacketCountAndFlags() {
382       auto packets = header()->packets.load(std::memory_order_acquire);
383       const uint16_t packets_count = packets.count;
384       const uint8_t packets_flags = packets.flags;
385       return std::make_pair(packets_count, packets_flags);
386     }
387 
388     // Increases |packets.count| with release semantics (note, however, that the
389     // packet count is incremented *before* starting writing a packet). Returns
390     // the new packet count. The increment is atomic but NOT race-free (i.e. no
391     // CAS). Only the Producer is supposed to perform this increment, and it's
392     // supposed to do that in a thread-safe way (holding a lock). A Chunk cannot
393     // be shared by multiple Producer threads without locking. The packet count
394     // is cleared by TryAcquireChunk(), when passing the new header for the
395     // chunk.
IncrementPacketCount()396     uint16_t IncrementPacketCount() {
397       ChunkHeader* chunk_header = header();
398       auto packets = chunk_header->packets.load(std::memory_order_relaxed);
399       packets.count++;
400       chunk_header->packets.store(packets, std::memory_order_release);
401       return packets.count;
402     }
403 
404     // Increases |packets.count| to the given |packet_count|, but only if
405     // |packet_count| is larger than the current value of |packets.count|.
406     // Returns the new packet count. Same atomicity guarantees as
407     // IncrementPacketCount().
IncreasePacketCountTo(uint16_t packet_count)408     uint16_t IncreasePacketCountTo(uint16_t packet_count) {
409       ChunkHeader* chunk_header = header();
410       auto packets = chunk_header->packets.load(std::memory_order_relaxed);
411       if (packets.count < packet_count)
412         packets.count = packet_count;
413       chunk_header->packets.store(packets, std::memory_order_release);
414       return packets.count;
415     }
416 
417     // Flags are cleared by TryAcquireChunk(), by passing the new header for
418     // the chunk, or through ClearNeedsPatchingFlag.
SetFlag(ChunkHeader::Flags flag)419     void SetFlag(ChunkHeader::Flags flag) {
420       ChunkHeader* chunk_header = header();
421       auto packets = chunk_header->packets.load(std::memory_order_relaxed);
422       packets.flags |= flag;
423       chunk_header->packets.store(packets, std::memory_order_release);
424     }
425 
426     // This flag can only be cleared by the producer while it is still holding
427     // on to the chunk - i.e. while the chunk is still in state
428     // ChunkState::kChunkBeingWritten and hasn't been transitioned to
429     // ChunkState::kChunkComplete. This is ok, because the service is oblivious
430     // to the needs patching flag before the chunk is released as complete.
ClearNeedsPatchingFlag()431     void ClearNeedsPatchingFlag() {
432       ChunkHeader* chunk_header = header();
433       auto packets = chunk_header->packets.load(std::memory_order_relaxed);
434       packets.flags &= ~ChunkHeader::kChunkNeedsPatching;
435       chunk_header->packets.store(packets, std::memory_order_release);
436     }
437 
438    private:
439     friend class SharedMemoryABI;
440     Chunk(uint8_t* begin, uint16_t size, uint8_t chunk_idx);
441 
442     // Don't add extra fields, keep the move operator fast.
443     uint8_t* begin_ = nullptr;
444     uint16_t size_ = 0;
445     uint8_t chunk_idx_ = 0;
446   };
447 
448   // Construct an instance from an existing shared memory buffer.
449   SharedMemoryABI(uint8_t* start, size_t size, size_t page_size);
450   SharedMemoryABI();
451 
452   void Initialize(uint8_t* start, size_t size, size_t page_size);
453 
start()454   uint8_t* start() const { return start_; }
end()455   uint8_t* end() const { return start_ + size_; }
size()456   size_t size() const { return size_; }
page_size()457   size_t page_size() const { return page_size_; }
num_pages()458   size_t num_pages() const { return num_pages_; }
is_valid()459   bool is_valid() { return num_pages() > 0; }
460 
page_start(size_t page_idx)461   uint8_t* page_start(size_t page_idx) {
462     PERFETTO_DCHECK(page_idx < num_pages_);
463     return start_ + page_size_ * page_idx;
464   }
465 
page_header(size_t page_idx)466   PageHeader* page_header(size_t page_idx) {
467     return reinterpret_cast<PageHeader*>(page_start(page_idx));
468   }
469 
470   // Returns true if the page is fully clear and has not been partitioned yet.
471   // The state of the page can change at any point after this returns (or even
472   // before). The Producer should use this only as a hint to decide out whether
473   // it should TryPartitionPage() or acquire an individual chunk.
is_page_free(size_t page_idx)474   bool is_page_free(size_t page_idx) {
475     return page_header(page_idx)->layout.load(std::memory_order_relaxed) == 0;
476   }
477 
478   // Returns true if all chunks in the page are kChunkComplete. As above, this
479   // is advisory only. The Service is supposed to use this only to decide
480   // whether to TryAcquireAllChunksForReading() or not.
is_page_complete(size_t page_idx)481   bool is_page_complete(size_t page_idx) {
482     auto layout = page_header(page_idx)->layout.load(std::memory_order_relaxed);
483     const uint32_t num_chunks = GetNumChunksForLayout(layout);
484     if (num_chunks == 0)
485       return false;  // Non partitioned pages cannot be complete.
486     return (layout & kAllChunksMask) ==
487            (kAllChunksComplete & ((1 << (num_chunks * kChunkShift)) - 1));
488   }
489 
490   // For testing / debugging only.
page_header_dbg(size_t page_idx)491   std::string page_header_dbg(size_t page_idx) {
492     uint32_t x = page_header(page_idx)->layout.load(std::memory_order_relaxed);
493     return std::bitset<32>(x).to_string();
494   }
495 
496   // Returns the page layout, which is a bitmap that specifies the chunking
497   // layout of the page and each chunk's current state. Reads with an
498   // acquire-load semantic to ensure a producer's writes corresponding to an
499   // update of the layout (e.g. clearing a chunk's header) are observed
500   // consistently.
GetPageLayout(size_t page_idx)501   uint32_t GetPageLayout(size_t page_idx) {
502     return page_header(page_idx)->layout.load(std::memory_order_acquire);
503   }
504 
505   // Returns a bitmap in which each bit is set if the corresponding Chunk exists
506   // in the page (according to the page layout) and is free. If the page is not
507   // partitioned it returns 0 (as if the page had no free chunks).
508   uint32_t GetFreeChunks(size_t page_idx);
509 
510   // Tries to atomically partition a page with the given |layout|. Returns true
511   // if the page was free and has been partitioned with the given |layout|,
512   // false if the page wasn't free anymore by the time we got there.
513   // If succeeds all the chunks are atomically set in the kChunkFree state.
514   bool TryPartitionPage(size_t page_idx, PageLayout layout);
515 
516   // Tries to atomically mark a single chunk within the page as
517   // kChunkBeingWritten. Returns an invalid chunk if the page is not partitioned
518   // or the chunk is not in the kChunkFree state. If succeeds sets the chunk
519   // header to |header|.
TryAcquireChunkForWriting(size_t page_idx,size_t chunk_idx,const ChunkHeader * header)520   Chunk TryAcquireChunkForWriting(size_t page_idx,
521                                   size_t chunk_idx,
522                                   const ChunkHeader* header) {
523     return TryAcquireChunk(page_idx, chunk_idx, kChunkBeingWritten, header);
524   }
525 
526   // Similar to TryAcquireChunkForWriting. Fails if the chunk isn't in the
527   // kChunkComplete state.
TryAcquireChunkForReading(size_t page_idx,size_t chunk_idx)528   Chunk TryAcquireChunkForReading(size_t page_idx, size_t chunk_idx) {
529     return TryAcquireChunk(page_idx, chunk_idx, kChunkBeingRead, nullptr);
530   }
531 
532   // The caller must have successfully TryAcquireAllChunksForReading() or it
533   // needs to guarantee that the chunk is already in the kChunkBeingWritten
534   // state.
535   Chunk GetChunkUnchecked(size_t page_idx,
536                           uint32_t page_layout,
537                           size_t chunk_idx);
538 
539   // Puts a chunk into the kChunkComplete state. Returns the page index.
ReleaseChunkAsComplete(Chunk chunk)540   size_t ReleaseChunkAsComplete(Chunk chunk) {
541     return ReleaseChunk(std::move(chunk), kChunkComplete);
542   }
543 
544   // Puts a chunk into the kChunkFree state. Returns the page index.
ReleaseChunkAsFree(Chunk chunk)545   size_t ReleaseChunkAsFree(Chunk chunk) {
546     return ReleaseChunk(std::move(chunk), kChunkFree);
547   }
548 
GetChunkState(size_t page_idx,size_t chunk_idx)549   ChunkState GetChunkState(size_t page_idx, size_t chunk_idx) {
550     PageHeader* phdr = page_header(page_idx);
551     uint32_t layout = phdr->layout.load(std::memory_order_relaxed);
552     return GetChunkStateFromLayout(layout, chunk_idx);
553   }
554 
555   std::pair<size_t, size_t> GetPageAndChunkIndex(const Chunk& chunk);
556 
GetChunkSizeForLayout(uint32_t page_layout)557   uint16_t GetChunkSizeForLayout(uint32_t page_layout) const {
558     return chunk_sizes_[(page_layout & kLayoutMask) >> kLayoutShift];
559   }
560 
GetChunkStateFromLayout(uint32_t page_layout,size_t chunk_idx)561   static ChunkState GetChunkStateFromLayout(uint32_t page_layout,
562                                             size_t chunk_idx) {
563     return static_cast<ChunkState>((page_layout >> (chunk_idx * kChunkShift)) &
564                                    kChunkMask);
565   }
566 
GetNumChunksForLayout(uint32_t page_layout)567   static constexpr uint32_t GetNumChunksForLayout(uint32_t page_layout) {
568     return kNumChunksForLayout[(page_layout & kLayoutMask) >> kLayoutShift];
569   }
570 
571   // Returns a bitmap in which each bit is set if the corresponding Chunk exists
572   // in the page (according to the page layout) and is not free. If the page is
573   // not partitioned it returns 0 (as if the page had no used chunks). Bit N
574   // corresponds to Chunk N.
GetUsedChunks(uint32_t page_layout)575   static uint32_t GetUsedChunks(uint32_t page_layout) {
576     const uint32_t num_chunks = GetNumChunksForLayout(page_layout);
577     uint32_t res = 0;
578     for (uint32_t i = 0; i < num_chunks; i++) {
579       res |= ((page_layout & kChunkMask) != kChunkFree) ? (1 << i) : 0;
580       page_layout >>= kChunkShift;
581     }
582     return res;
583   }
584 
585  private:
586   SharedMemoryABI(const SharedMemoryABI&) = delete;
587   SharedMemoryABI& operator=(const SharedMemoryABI&) = delete;
588 
589   Chunk TryAcquireChunk(size_t page_idx,
590                         size_t chunk_idx,
591                         ChunkState,
592                         const ChunkHeader*);
593   size_t ReleaseChunk(Chunk chunk, ChunkState);
594 
595   uint8_t* start_ = nullptr;
596   size_t size_ = 0;
597   size_t page_size_ = 0;
598   size_t num_pages_ = 0;
599   std::array<uint16_t, kNumPageLayouts> chunk_sizes_;
600 };
601 
602 }  // namespace perfetto
603 
604 #endif  // INCLUDE_PERFETTO_EXT_TRACING_CORE_SHARED_MEMORY_ABI_H_
605