| 1 | #pragma once |
| 2 | /* Support for multithreaded write() operations */ |
| 3 | |
| 4 | #include "vmprof.h" |
| 5 | |
| 6 | #include <string.h> |
| 7 | #include <sys/mman.h> |
| 8 | |
| 9 | /* The idea is that we have MAX_NUM_BUFFERS available, all of size |
| 10 | SINGLE_BUF_SIZE. Threads and signal handlers can ask to reserve a |
| 11 | buffer, fill it, and finally "commit" it, at which point its |
| 12 | content is written into the profile file. There is no hard |
| 13 | guarantee about the order in which the committed blocks are |
| 14 | actually written. We do this with two constrains: |
| 15 | |
| 16 | - write() calls should not overlap; only one thread can be |
| 17 | currently calling it. |
| 18 | |
| 19 | - the code needs to be multithread-safe *and* signal-handler-safe, |
| 20 | which means it must be written in a wait-free style: never have |
| 21 | spin loops waiting for some lock to be released, from any of |
| 22 | the functions that can be called from the signal handler! The |
| 23 | code holding the lock could be running in the same thread, |
| 24 | currently interrupted by the signal handler. |
| 25 | |
| 26 | The value of MAX_NUM_BUFFERS is a trade-off between too high |
| 27 | (lots of unnecessary memory, lots of checking all of them) |
| 28 | and too low (risk that there is none left). |
| 29 | */ |
| 30 | #define MAX_NUM_BUFFERS 20 |
| 31 | |
| 32 | #ifndef MAP_ANONYMOUS |
| 33 | #define MAP_ANONYMOUS MAP_ANON |
| 34 | #endif |
| 35 | |
| 36 | #define PROFBUF_UNUSED 0 |
| 37 | #define PROFBUF_FILLING 1 |
| 38 | #define PROFBUF_READY 2 |
| 39 | |
| 40 | |
| 41 | struct profbuf_s { |
| 42 | unsigned int data_size; |
| 43 | unsigned int data_offset; |
| 44 | char data[SINGLE_BUF_SIZE]; |
| 45 | }; |
| 46 | |
| 47 | int prepare_concurrent_bufs(void); |
| 48 | struct profbuf_s *reserve_buffer(int fd); |
| 49 | void commit_buffer(int fd, struct profbuf_s *buf); |
| 50 | void cancel_buffer(struct profbuf_s *buf); |
| 51 | int shutdown_concurrent_bufs(int fd); |