]> git.proxmox.com Git - mirror_lxc.git/blob - src/lxc/ringbuf.h
cgroups: use zalloc
[mirror_lxc.git] / src / lxc / ringbuf.h
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #ifndef __LXC_RINGBUF_H
4 #define __LXC_RINGBUF_H
5
6 #include <inttypes.h>
7 #include <stdbool.h>
8 #include <stdio.h>
9 #include <sys/mman.h>
10
11 #include "compiler.h"
12
13 /**
14 * lxc_ringbuf - Implements a simple and efficient memory mapped ringbuffer.
15 * - The "addr" field of struct lxc_ringbuf is considered immutable. Instead the
16 * read and write offsets r_off and w_off are used to calculate the current
17 * read and write addresses. There should never be a need to use any of those
18 * fields directly. Instead use the appropriate helpers below.
19 * - Callers are expected to synchronize read and write accesses to the
20 * ringbuffer.
21 */
22 struct lxc_ringbuf {
23 char *addr; /* start address of the ringbuffer */
24 uint64_t size; /* total size of the ringbuffer in bytes */
25 uint64_t r_off; /* read offset */
26 uint64_t w_off; /* write offset */
27 };
28
29 /**
30 * lxc_ringbuf_create - Initialize a new ringbuffer.
31 *
32 * @param[in] size Size of the new ringbuffer as a power of 2.
33 */
34 __hidden extern int lxc_ringbuf_create(struct lxc_ringbuf *buf, size_t size);
35 __hidden extern void lxc_ringbuf_move_read_addr(struct lxc_ringbuf *buf, size_t len);
36 __hidden extern int lxc_ringbuf_write(struct lxc_ringbuf *buf, const char *msg, size_t len);
37 __hidden extern int lxc_ringbuf_read(struct lxc_ringbuf *buf, char *out, size_t *len);
38
39 static inline void lxc_ringbuf_release(struct lxc_ringbuf *buf)
40 {
41 if (buf->addr)
42 munmap(buf->addr, buf->size * 2);
43 }
44
45 static inline void lxc_ringbuf_clear(struct lxc_ringbuf *buf)
46 {
47 buf->r_off = 0;
48 buf->w_off = 0;
49 }
50
51 static inline uint64_t lxc_ringbuf_used(struct lxc_ringbuf *buf)
52 {
53 return buf->w_off - buf->r_off;
54 }
55
56 static inline uint64_t lxc_ringbuf_free(struct lxc_ringbuf *buf)
57 {
58 return buf->size - lxc_ringbuf_used(buf);
59 }
60
61 static inline char *lxc_ringbuf_get_read_addr(struct lxc_ringbuf *buf)
62 {
63 return buf->addr + buf->r_off;
64 }
65
66 static inline char *lxc_ringbuf_get_write_addr(struct lxc_ringbuf *buf)
67 {
68 return buf->addr + buf->w_off;
69 }
70
71 static inline void lxc_ringbuf_move_write_addr(struct lxc_ringbuf *buf, size_t len)
72 {
73 buf->w_off += len;
74 }
75
76 #endif /* __LXC_RINGBUF_H */