Debian Codegraph @

src/libsysprof-capture/mapped-ring-buffer.c

raw
1 /* mapped-ring-buffer.c
2 *
3 * Copyright 2020-2025 Christian Hergert <[email protected]>
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met:
8 *
9 * 1. Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 *
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 *
16 * Subject to the terms and conditions of this license, each copyright holder
17 * and contributor hereby grants to those receiving rights under this license
18 * a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
19 * irrevocable (except for failure to satisfy the conditions of this license)
20 * patent license to make, have made, use, offer to sell, sell, import, and
21 * otherwise transfer this software, where such license applies only to those
22 * patent claims, already acquired or hereafter acquired, licensable by such
23 * copyright holder or contributor that are necessarily infringed by:
24 *
25 * (a) their Contribution(s) (the licensed copyrights of copyright holders
26 * and non-copyrightable additions of contributors, in source or binary
27 * form) alone; or
28 *
29 * (b) combination of their Contribution(s) with the work of authorship to
30 * which such Contribution(s) was added by such copyright holder or
31 * contributor, if, at the time the Contribution is added, such addition
32 * causes such combination to be necessarily infringed. The patent license
33 * shall not apply to any other combinations which include the
34 * Contribution.
35 *
36 * Except as expressly stated above, no rights or licenses from any copyright
37 * holder or contributor is granted under this license, whether expressly, by
38 * implication, estoppel or otherwise.
39 *
40 * DISCLAIMER
41 *
42 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
43 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
44 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
45 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
46 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
47 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
48 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
49 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
50 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
51 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
52 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
53 *
54 * SPDX-License-Identifier: BSD-2-Clause-Patent
55 */
56
57 #include "config.h"
58
59 #include <assert.h>
60 #include <stdint.h>
61 #include <stdio.h>
62 #include <sys/mman.h>
63 #include <sys/types.h>
64 #include <unistd.h>
65
66 #include "sysprof-capture-util-private.h"
67 #include "sysprof-macros-internal.h"
68 #include "sysprof-platform.h"
69
70 #include "mapped-ring-buffer.h"
71
72 #define DEFAULT_N_PAGES 63
73 #define BUFFER_MAX_SIZE ((UINT32_MAX/2)-_sysprof_getpagesize())
74 #define SHM_COLOUR 0x00400000
75
76 enum {
77 MODE_READER = 1,
78 MODE_WRITER = 2,
79 MODE_READWRITE = 3,
80 };
81
82 /*
83 * MappedRingHeader is the header of the first page of the
84 * buffer. We use the whole buffer so that we can double map
85 * the body of the buffer.
86 */
87 typedef struct _MappedRingHeader
88 {
89 uint32_t head;
90 uint32_t tail;
91 uint32_t offset;
92 uint32_t size;
93 } MappedRingHeader;
94
95 SYSPROF_STATIC_ASSERT (sizeof (MappedRingHeader) == 16, "MappedRingHeader changed size");
96
97 /*
98 * MappedRingBuffer is used to wrap both the reader and writer
99 * mapping structures.
100 */
101 struct _MappedRingBuffer
102 {
103 volatile int ref_count;
104 int mode;
105 int fd;
106 void *map;
107 size_t body_size;
108 size_t page_size;
109 unsigned has_failed : 1;
110 };
111
112 static inline MappedRingHeader *
113 get_header (MappedRingBuffer *self)
114 {
115 return (MappedRingHeader *)self->map;
116 }
117
118 static inline void *
119 get_body_at_pos (MappedRingBuffer *self,
120 size_t pos)
121 {
122 assert (pos < (self->body_size + self->body_size));
123
124 return (uint8_t *)self->map + self->page_size + pos;
125 }
126
127 static void *
128 map_head_and_body_twice (int fd,
129 size_t head_size,
130 size_t body_size)
131 {
132 void *map;
133 void *second;
134
135 /* First we map FD to the total size we want so that we can be
136 * certain the OS will give us a contiguous mapping for our buffers
137 * even though we can't dereference a portion of the mapping yet.
138 *
139 * We'll overwrite the secondary mapping in a moment to deal with
140 * wraparound for the ring buffer.
141 */
142 map = mmap (NULL,
143 head_size + body_size + body_size,
144 PROT_READ | PROT_WRITE,
145 MAP_SHARED,
146 fd,
147 0);
148
149 if (map == MAP_FAILED)
150 return NULL;
151
152 /* At this point, we have [HEAD|BODY|BUSERR] mapped. But we want to map
153 * the body again over what would currently cause a BusError. That way
154 * when we need to wraparound we don't need to copy anything, we just
155 * have to check in mapped_ring_buffer_allocate() that the size does not
156 * step over what would be the real reader position.
157 *
158 * By mmap()'ing over the old region, the previous region is automatically
159 * munmap()'d for us.
160 */
161 second = mmap ((uint8_t *)map + head_size + body_size,
162 body_size,
163 PROT_READ | PROT_WRITE,
164 MAP_SHARED | MAP_FIXED,
165 fd,
166 head_size);
167
168 if (second == MAP_FAILED)
169 {
170 munmap (map, head_size + body_size + body_size);
171 return NULL;
172 }
173
174 assert (second == (void *)((uint8_t *)map + head_size + body_size));
175
176 return map;
177 }
178
179 /**
180 * mapped_ring_buffer_new_reader:
181 * @buffer_size: the size of the buffer, which must be page-aligned
182 *
183 * Creates a new #MappedRingBuffer.
184 *
185 * This should be called by the process reading the buffer. It should
186 * then pass the FD of the buffer to another process or thread to
187 * advance the ring buffer by writing data.
188 *
189 * The other process or thread should create a new #MappedRingBuffer
190 * using mapped_ring_buffer_new_writer() with the FD retrieved from
191 * the reader using mapped_ring_buffer_get_fd(). If crossing a process
192 * boundary, you probably also want to dup() the FD and set O_CLOEXEC.
193 *
194 * @buffer_size must be a multiple of the system's page size which can
195 * be retrieved using sysprof_getpagesize().
196 *
197 * Returns: (transfer full): a #MappedRingBuffer
198 */
199 MappedRingBuffer *
200 mapped_ring_buffer_new_reader (size_t buffer_size)
201 {
202 MappedRingBuffer *self;
203 MappedRingHeader *header;
204 size_t page_size;
205 void *map;
206 int fd;
207
208 assert ((buffer_size % _sysprof_getpagesize ()) == 0);
209 assert (buffer_size < BUFFER_MAX_SIZE);
210
211 page_size = _sysprof_getpagesize ();
212
213 if (buffer_size == 0)
214 buffer_size = page_size * DEFAULT_N_PAGES;
215
216 #ifdef __hppa__
217 /* Round buffer_size up to the shared memory colour boundary */
218 buffer_size += SHM_COLOUR - 1;
219 buffer_size &= ~(SHM_COLOUR - 1);
220 #endif
221
222 /* Add 1 page for coordination header */
223 buffer_size += page_size;
224
225 /* Create our memfd (or tmpfs) for writing */
226 if ((fd = sysprof_memfd_create ("[sysprof-ring-buffer]")) == -1)
227 return NULL;
228
229 /* Size our memfd to reserve space */
230 if (ftruncate (fd, buffer_size) != 0)
231 {
232 close (fd);
233 return NULL;
234 }
235
236 /* Map ring buffer [HEAD|BODY|BODY] */
237 if (!(map = map_head_and_body_twice (fd, page_size, buffer_size - page_size)))
238 {
239 close (fd);
240 return NULL;
241 }
242
243 /* Setup initial header */
244 header = map;
245 header->head = 0;
246 header->tail = 0;
247 header->offset = page_size;
248 header->size = buffer_size - page_size;
249
250 self = sysprof_malloc0 (sizeof (MappedRingBuffer));
251 if (self == NULL)
252 return NULL;
253
254 self->ref_count = 1;
255 self->mode = MODE_READER;
256 self->body_size = buffer_size - page_size;
257 self->fd = fd;
258 self->map = map;
259 self->page_size = page_size;
260
261 return sysprof_steal_pointer (&self);
262 }
263
264 MappedRingBuffer *
265 mapped_ring_buffer_new_readwrite (size_t buffer_size)
266 {
267 MappedRingBuffer *self;
268
269 if ((self = mapped_ring_buffer_new_reader (buffer_size)))
270 self->mode = MODE_READWRITE;
271
272 return self;
273 }
274
275 /**
276 * mapped_ring_buffer_new_writer:
277 * @fd: a FD to map
278 *
279 * Creates a new #MappedRingBuffer using a copy of @fd.
280 *
281 * The caller may close(fd) after calling this function regardless of
282 * success creating the #MappedRingBuffer.
283 *
284 * Returns: (transfer full) (nullable): a new #MappedRingBuffer
285 */
286 MappedRingBuffer *
287 mapped_ring_buffer_new_writer (int fd)
288 {
289 MappedRingBuffer *self;
290 MappedRingHeader *header;
291 ssize_t buffer_size;
292 size_t page_size;
293 void *map;
294
295 assert (fd > -1);
296
297 page_size = _sysprof_getpagesize ();
298
299 /* Make our own copy of the FD */
300 if ((fd = dup (fd)) < 0)
301 {
302 fprintf (stderr, "Failed to dup() fd, cannot continue\n");
303 return NULL;
304 }
305
306 /* Seek to end to get buffer size */
307 if ((buffer_size = lseek (fd, 0, SEEK_END)) < 0)
308 {
309 fprintf (stderr, "Failed to seek to end of file. Cannot determine buffer size.\n");
310 return NULL;
311 }
312
313 /* Ensure non-zero sized buffer */
314 if (buffer_size < (page_size + page_size))
315 {
316 fprintf (stderr, "Buffer is too small, cannot continue.\n");
317 return NULL;
318 }
319
320 /* Make sure it is less than our max size */
321 if ((buffer_size - page_size) > BUFFER_MAX_SIZE)
322 {
323 fprintf (stderr, "Buffer is too large, cannot continue.\n");
324 return NULL;
325 }
326
327 /* Ensure we have page-aligned buffer */
328 if ((buffer_size % page_size) != 0)
329 {
330 fprintf (stderr, "Invalid buffer size, not page aligned.\n");
331 return NULL;
332 }
333
334 /* Map ring buffer [HEAD|BODY|BODY] */
335 if (!(map = map_head_and_body_twice (fd, page_size, buffer_size - page_size)))
336 {
337 close (fd);
338 return NULL;
339 }
340
341 /* Validate we got proper data in header */
342 header = map;
343 if (header->offset != page_size ||
344 header->size != (buffer_size - page_size))
345 {
346 munmap (map, page_size + ((buffer_size - page_size) * 2));
347 close (fd);
348 return NULL;
349 }
350
351 self = sysprof_malloc0 (sizeof (MappedRingBuffer));
352 if (self == NULL)
353 {
354 munmap (map, page_size + ((buffer_size - page_size) * 2));
355 close (fd);
356 return NULL;
357 }
358
359 self->ref_count = 1;
360 self->mode = MODE_WRITER;
361 self->fd = fd;
362 self->body_size = buffer_size - page_size;
363 self->map = map;
364 self->page_size = page_size;
365
366 return sysprof_steal_pointer (&self);
367 }
368
369 static void
370 mapped_ring_buffer_finalize (MappedRingBuffer *self)
371 {
372 if (self->map != NULL)
373 {
374 munmap (self->map, self->page_size + self->body_size + self->body_size);
375 self->map = NULL;
376 }
377
378 if (self->fd != -1)
379 {
380 close (self->fd);
381 self->fd = -1;
382 }
383
384 free (self);
385 }
386
387 void
388 mapped_ring_buffer_unref (MappedRingBuffer *self)
389 {
390 assert (self != NULL);
391 assert (self->ref_count > 0);
392
393 if (__atomic_fetch_sub (&self->ref_count, 1, __ATOMIC_SEQ_CST) == 1)
394 mapped_ring_buffer_finalize (self);
395 }
396
397 MappedRingBuffer *
398 mapped_ring_buffer_ref (MappedRingBuffer *self)
399 {
400 assert (self != NULL);
401 assert (self->ref_count > 0);
402
403 __atomic_fetch_add (&self->ref_count, 1, __ATOMIC_SEQ_CST);
404
405 return self;
406 }
407
408 int
409 mapped_ring_buffer_get_fd (MappedRingBuffer *self)
410 {
411 assert (self != NULL);
412
413 return self->fd;
414 }
415
416 /**
417 * mapped_ring_buffer_allocate:
418 * @self: a #MappedRingBuffer
419 *
420 * Ensures that @length bytes are available at the next position in
421 * the ring buffer and returns a pointer to the beginning of that zone.
422 *
423 * If the reader has not read enough bytes to allow @length to be added
424 * then a mark will be added or incremented notifying the peer of how
425 * many records they have lost and %NULL is returned.
426 *
427 * You must always check for %NULL before dereferencing the result of
428 * this function as space may not be immediately available.
429 *
430 * This only ensure that the space is available for you to write. To
431 * notify the peer that the zone is ready for reading you must call
432 * mapped_ring_buffer_advance() with the number of bytes to advance.
433 * This is useful in case you need to allocate more memory than you
434 * might need up-front but commit a smaller amount.
435 *
436 * Returns: (nullable): a pointer to data of at least @length bytes
437 * or %NULL if there is not enough space.
438 */
439 void *
440 mapped_ring_buffer_allocate (MappedRingBuffer *self,
441 size_t length)
442 {
443 MappedRingHeader *header;
444 uint32_t headpos;
445 uint32_t tailpos;
446
447 assert (self != NULL);
448 assert (self->mode & MODE_WRITER);
449 assert (length > 0);
450 assert (length < self->body_size);
451 assert ((length & 0x7) == 0);
452
453 for (unsigned i = 0; i < 1000; i++)
454 {
455 header = get_header (self);
456 __atomic_load (&header->head, &headpos, __ATOMIC_SEQ_CST);
457 __atomic_load (&header->tail, &tailpos, __ATOMIC_SEQ_CST);
458
459 /* We need to check that there is enough space for @length at the
460 * current position in the write buffer. We cannot fully catch up
461 * to head, we must be at least one byte short of it. If we do not
462 * have enough space, then return NULL.
463 *
464 * When we have finished writing our frame data, we will push the tail
465 * forward with an atomic write.
466 */
467
468 if (tailpos == headpos)
469 return get_body_at_pos (self, tailpos);
470
471 if (headpos < tailpos)
472 headpos += self->body_size;
473
474 if (tailpos + length < headpos)
475 return get_body_at_pos (self, tailpos);
476
477 if (self->has_failed)
478 break;
479
480 usleep (1000); /* 1 msec */
481 }
482
483 self->has_failed = true;
484
485 return NULL;
486 }
487
488 /**
489 * mapped_ring_buffer_advance:
490 * @self: a #MappedRingBuffer
491 * @length: a 8-byte aligned length
492 *
493 * Advances the ring buffer @length bytes forward. @length must be
494 * 8-byte aligned so that the buffer may avoid memcpy() to read
495 * framing data.
496 *
497 * This should only be called by a writer created with
498 * mapped_ring_buffer_new_writer().
499 *
500 * Call this after writing your data into the buffer using
501 * mapped_ring_buffer_allocate().
502 *
503 * It is a programming error to call this with a value greater
504 * than was called to mapped_ring_buffer_allocate().
505 */
506 void
507 mapped_ring_buffer_advance (MappedRingBuffer *self,
508 size_t length)
509 {
510 MappedRingHeader *header;
511 uint32_t tail;
512
513 assert (self != NULL);
514 assert (self->mode & MODE_WRITER);
515 assert (length > 0);
516 assert (length < self->body_size);
517 assert ((length & 0x7) == 0);
518
519 header = get_header (self);
520 tail = header->tail;
521
522 /* Calculate the new tail position */
523 tail = tail + length;
524 if (tail >= self->body_size)
525 tail -= self->body_size;
526
527 /* We have already checked that we could advance the buffer when the
528 * application called mapped_ring_buffer_allocate(), so at this point
529 * we just update the position as the only way the head could have
530 * moved is forward.
531 */
532 __atomic_store (&header->tail, &tail, __ATOMIC_SEQ_CST);
533 }
534
535 /**
536 * mapped_ring_buffer_drain:
537 * @self: a #MappedRingBuffer
538 * @callback: (scope call): a callback to execute for each frame
539 * @user_data: closure data for @callback
540 *
541 * Drains the buffer by calling @callback for each frame.
542 *
543 * This should only be called by a reader created with
544 * mapped_ring_buffer_new_reader().
545 *
546 * Returns: %TRUE if the buffer was drained, %FALSE if @callback prematurely
547 * returned while draining.
548 */
549 bool
550 mapped_ring_buffer_drain (MappedRingBuffer *self,
551 MappedRingBufferCallback callback,
552 void *user_data)
553 {
554 MappedRingHeader *header;
555 uint32_t headpos;
556 uint32_t tailpos;
557
558 assert (self != NULL);
559 assert (self->mode & MODE_READER);
560 assert (callback != NULL);
561
562 header = get_header (self);
563 __atomic_load (&header->head, &headpos, __ATOMIC_SEQ_CST);
564 __atomic_load (&header->tail, &tailpos, __ATOMIC_SEQ_CST);
565
566 assert (headpos < self->body_size);
567 assert (tailpos < self->body_size);
568
569 if (headpos == tailpos)
570 return true;
571
572 /* If head needs to wrap around to get to tail, we can just rely on
573 * our double mapping instead actually manually wrapping/copying data.
574 */
575 if (tailpos < headpos)
576 tailpos += self->body_size;
577
578 assert (headpos < tailpos);
579
580 while (headpos < tailpos)
581 {
582 const void *data = get_body_at_pos (self, headpos);
583 size_t len = tailpos - headpos;
584 uint32_t new_headpos;
585
586 if (!callback (data, &len, user_data))
587 return false;
588
589 if (len > (tailpos - headpos))
590 return false;
591
592 headpos += len;
593
594 if (headpos >= self->body_size)
595 new_headpos = headpos - self->body_size;
596 else
597 new_headpos = headpos;
598
599 __atomic_store (&header->head, &new_headpos, __ATOMIC_SEQ_CST);
600 }
601
602 return true;
603 }
604
605 /**
606 * mapped_ring_buffer_is_empty:
607 * @self: a #MappedRingBuffer
608 *
609 * Checks whether the ring buffer is currently empty.
610 *
611 * This should only be called by a reader created with
612 * mapped_ring_buffer_new_reader().
613 *
614 * Returns: %TRUE if the buffer is empty, %FALSE otherwise
615 */
616 bool
617 mapped_ring_buffer_is_empty (MappedRingBuffer *self)
618 {
619 MappedRingHeader *header;
620 uint32_t headpos, tailpos;
621
622 header = get_header (self);
623
624 __atomic_load (&header->head, &headpos, __ATOMIC_SEQ_CST);
625 __atomic_load (&header->tail, &tailpos, __ATOMIC_SEQ_CST);
626
627 return headpos == tailpos;
628 }
629
630 /**
631 * mapped_ring_buffer_clear:
632 * @self: a #MappedRingBuffer
633 *
634 * Resets the head and tail positions back to 0.
635 *
636 * This function is only safe to call when you control both the reader
637 * and writer sides with mapped_ring_buffer_new_readwrite(), or are in
638 * control of when each side reads or writes.
639 */
640 void
641 mapped_ring_buffer_clear (MappedRingBuffer *self)
642 {
643 MappedRingHeader *header;
644
645 assert (self != NULL);
646
647 header = get_header (self);
648 header->head = 0;
649 header->tail = 0;
650 }