Condy v1.8
C++ Asynchronous System Call Layer for Linux
Loading...
Searching...
No Matches
condy_uring.hpp
Go to the documentation of this file.
1
4
5#pragma once
6
7#include <liburing.h> // IWYU pragma: export
8
9#include <cerrno>
10#include <cstring>
11#include <sys/mman.h>
12
13// liburing <= 2.3 has no version macros, define them here
14
15#ifndef IO_URING_VERSION_MAJOR
16#define IO_URING_VERSION_MAJOR 2
17#endif
18
19#ifndef IO_URING_VERSION_MINOR
20#define IO_URING_VERSION_MINOR 3
21#endif
22
23#ifndef IO_URING_CHECK_VERSION
24#define IO_URING_CHECK_VERSION(major, minor) \
25 (major > IO_URING_VERSION_MAJOR || \
26 (major == IO_URING_VERSION_MAJOR && minor > IO_URING_VERSION_MINOR))
27#endif
28
29// Polyfill for io_uring_prep_uring_cmd (added in liburing 2.13)
30// Opcode exists since 2.3, only the helper function is missing
31#if IO_URING_CHECK_VERSION(2, 13) // < 2.13
32inline void io_uring_prep_uring_cmd(struct io_uring_sqe *sqe, int cmd_op,
33 int fd) noexcept {
34 sqe->opcode = (__u8)IORING_OP_URING_CMD;
35 sqe->fd = fd;
36 sqe->cmd_op = cmd_op;
37 sqe->__pad1 = 0;
38 sqe->addr = 0ul;
39 sqe->len = 0;
40}
41#endif
42
43// Polyfill for io_uring_setup_buf_ring / io_uring_free_buf_ring
44// (added in liburing 2.4)
45#if IO_URING_CHECK_VERSION(2, 4) // < 2.4
46inline struct io_uring_buf_ring *
47io_uring_setup_buf_ring(struct io_uring *ring, unsigned int nentries, int bgid,
48 unsigned int flags, int *err) noexcept {
49 size_t ring_size = nentries * sizeof(struct io_uring_buf);
50 auto *br = static_cast<struct io_uring_buf_ring *>(
51 mmap(nullptr, ring_size, PROT_READ | PROT_WRITE,
52 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0));
53 if (br == MAP_FAILED) {
54 *err = -errno;
55 return nullptr;
56 }
57
58 io_uring_buf_ring_init(br);
59
60 struct io_uring_buf_reg reg = {};
61 reg.ring_addr = reinterpret_cast<uint64_t>(br);
62 reg.ring_entries = nentries;
63 reg.bgid = bgid;
64
65 *err = 0;
66 int ret = io_uring_register_buf_ring(ring, &reg, flags);
67 if (ret != 0) {
68 munmap(br, ring_size);
69 *err = ret;
70 return nullptr;
71 }
72
73 return br;
74}
75
76inline int io_uring_free_buf_ring(struct io_uring *ring,
77 struct io_uring_buf_ring *br,
78 unsigned int nentries, int bgid) noexcept {
79 int ret = io_uring_unregister_buf_ring(ring, bgid);
80 if (ret != 0) {
81 return ret;
82 }
83 munmap(br, nentries * sizeof(struct io_uring_buf));
84 return 0;
85}
86#endif