Condy v1.3.0
C++ Asynchronous System Call Layer for Linux
Loading...
Searching...
No Matches
runtime.hpp
Go to the documentation of this file.
1
5
6#pragma once
7
9#include "condy/context.hpp"
11#include "condy/intrusive.hpp"
12#include "condy/invoker.hpp"
13#include "condy/ring.hpp"
15#include "condy/utils.hpp"
16#include "condy/work_type.hpp"
17#include <cstddef>
18#include <cstdint>
19#include <cstring>
20#include <mutex>
21#include <sys/eventfd.h>
22
23namespace condy {
24
25namespace detail {
26
27#if !IO_URING_CHECK_VERSION(2, 12) // >= 2.12
28class AsyncWaiter {
29public:
30 void async_wait(Ring &) {}
31
32 void notify(Ring &ring) {
33 io_uring_sqe sqe = {};
34 io_uring_prep_msg_ring(
35 &sqe, ring.ring()->ring_fd, 0,
36 reinterpret_cast<uint64_t>(encode_work(nullptr, WorkType::Notify)),
37 0);
38 io_uring_register_sync_msg(&sqe);
39 }
40};
41#else
42class AsyncWaiter {
43public:
44 AsyncWaiter() {
45 notify_fd_ = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
46 if (notify_fd_ < 0) {
47 throw make_system_error("eventfd", errno);
48 }
49 }
50
51 ~AsyncWaiter() { close(notify_fd_); }
52
53 void async_wait(Ring &ring) {
54 eventfd_read(notify_fd_, &dummy_);
55 io_uring_sqe *sqe = ring.get_sqe();
56 io_uring_prep_read(sqe, notify_fd_, &dummy_, sizeof(dummy_), 0);
57 io_uring_sqe_set_data(sqe, encode_work(nullptr, WorkType::Notify));
58 }
59
60 void notify(Ring &) { eventfd_write(notify_fd_, 1); }
61
62private:
63 int notify_fd_;
64 eventfd_t dummy_;
65};
66#endif
67
68} // namespace detail
69
76class Runtime {
77public:
82 Runtime(const RuntimeOptions &options = {}) {
83 io_uring_params params;
84 std::memset(&params, 0, sizeof(params));
85
86 params.flags |= IORING_SETUP_CLAMP;
87 params.flags |= IORING_SETUP_SINGLE_ISSUER;
88 params.flags |= IORING_SETUP_SUBMIT_ALL;
89 params.flags |= IORING_SETUP_R_DISABLED;
90
91 size_t ring_entries = options.sq_size_;
92 if (options.cq_size_ != 0) { // 0 means default
93 params.flags |= IORING_SETUP_CQSIZE;
94 params.cq_entries = options.cq_size_;
95 }
96
97 if (options.enable_iopoll_) {
98 params.flags |= IORING_SETUP_IOPOLL;
99#if !IO_URING_CHECK_VERSION(2, 9) // >= 2.9
100 if (options.enable_hybrid_iopoll_) {
101 params.flags |= IORING_SETUP_HYBRID_IOPOLL;
102 }
103#endif
104 }
105
106 if (options.enable_sqpoll_) {
107 params.flags |= IORING_SETUP_SQPOLL;
108 params.sq_thread_idle = options.sqpoll_idle_time_ms_;
109 if (options.sqpoll_thread_cpu_.has_value()) {
110 params.flags |= IORING_SETUP_SQ_AFF;
111 params.sq_thread_cpu = *options.sqpoll_thread_cpu_;
112 }
113 }
114
115 if (options.attach_wq_target_ != nullptr) {
116 params.flags |= IORING_SETUP_ATTACH_WQ;
117 params.wq_fd = options.attach_wq_target_->ring_.ring()->ring_fd;
118 }
119
120 if (options.enable_defer_taskrun_) {
121 params.flags |= IORING_SETUP_DEFER_TASKRUN;
122 params.flags |= IORING_SETUP_TASKRUN_FLAG;
123 }
124
125 if (options.enable_coop_taskrun_) {
126 params.flags |= IORING_SETUP_COOP_TASKRUN;
127 params.flags |= IORING_SETUP_TASKRUN_FLAG;
128 }
129
130 if (options.enable_sqe128_) {
131 params.flags |= IORING_SETUP_SQE128;
132 }
133
134 if (options.enable_cqe32_) {
135 params.flags |= IORING_SETUP_CQE32;
136 }
137
138#if !IO_URING_CHECK_VERSION(2, 13) // >= 2.13
139 if (options.enable_sqe_mixed_) {
140 params.flags |= IORING_SETUP_SQE_MIXED;
141 }
142#endif
143
144#if !IO_URING_CHECK_VERSION(2, 13) // >= 2.13
145 if (options.enable_cqe_mixed_) {
146 params.flags |= IORING_SETUP_CQE_MIXED;
147 }
148#endif
149
150 void *buf = nullptr;
151 size_t buf_size = 0;
152#if !IO_URING_CHECK_VERSION(2, 5) // >= 2.5
153 if (options.enable_no_mmap_) {
154 params.flags |= IORING_SETUP_NO_MMAP;
155 buf = options.no_mmap_buf_;
156 buf_size = options.no_mmap_buf_size_;
157 }
158#endif
159
160 int r = ring_.init(ring_entries, &params, buf, buf_size);
161 if (r < 0) {
162 throw make_system_error("io_uring_queue_init_params", -r);
163 }
164
165 event_interval_ = options.event_interval_;
166 disable_register_ring_fd_ = options.disable_register_ring_fd_;
167 }
168
169 ~Runtime() { ring_.destroy(); }
170
171 Runtime(const Runtime &) = delete;
172 Runtime &operator=(const Runtime &) = delete;
173 Runtime(Runtime &&) = delete;
174 Runtime &operator=(Runtime &&) = delete;
175
176public:
184 void allow_exit() {
185 pending_works_--;
186 notify();
187 }
188
189 void notify() { async_waiter_.notify(ring_); }
190
191 void schedule(WorkInvoker *work) {
192 auto *runtime = detail::Context::current().runtime();
193 if (runtime == this) {
194 local_queue_.push_back(work);
195 return;
196 }
197
198 auto state = state_.load();
199 if (runtime != nullptr && state == State::Enabled) {
200 tsan_release(work);
201 io_uring_sqe *sqe = runtime->ring_.get_sqe();
202 prep_msg_ring_(sqe, work);
203 runtime->pend_work();
204 return;
205 }
206
207#if !IO_URING_CHECK_VERSION(2, 12) // >= 2.12
208 if (runtime == nullptr && state == State::Enabled) {
209 tsan_release(work);
210 io_uring_sqe sqe = {};
211 prep_msg_ring_(&sqe, work);
212 [[maybe_unused]] int r = io_uring_register_sync_msg(&sqe);
213 assert(r == 0);
214 return;
215 }
216#endif
217
218 {
219 std::lock_guard<std::mutex> lock(mutex_);
220 bool need_notify = global_queue_.empty();
221 global_queue_.push_back(work);
222 if (need_notify) {
223 notify();
224 }
225 }
226 }
227
228 void pend_work() { pending_works_++; }
229
230 void resume_work() { pending_works_--; }
231
240 void run() {
241 State expected = State::Idle;
242 if (!state_.compare_exchange_strong(expected, State::Running)) {
243 throw std::logic_error("Runtime is already running or stopped");
244 }
245 auto d1 = defer([this]() { state_.store(State::Stopped); });
246
247 [[maybe_unused]] int r;
248 r = io_uring_enable_rings(ring_.ring());
249 assert(r == 0);
250
251 state_.store(State::Enabled);
252
253 if (!disable_register_ring_fd_) {
254 r = io_uring_register_ring_fd(ring_.ring());
255 if (r != 1) { // 1 indicates success for this call
256 throw make_system_error("io_uring_register_ring_fd", -r);
257 }
258 }
259
260 detail::Context::current().init(&ring_, this);
261 auto d2 = defer([]() { detail::Context::current().reset(); });
262
263 {
264 std::lock_guard<std::mutex> lock(mutex_);
265 flush_global_queue_();
266 }
267
268 while (true) {
269 tick_count_++;
270
271 if (tick_count_ % event_interval_ == 0) {
272 flush_ring_();
273 }
274
275 if (auto *work = local_queue_.pop_front()) {
276 (*work)();
277 continue;
278 }
279
280 if (pending_works_ == 0) {
281 break;
282 }
283 flush_ring_wait_();
284 }
285 }
286
291 auto &fd_table() { return ring_.fd_table(); }
292
297 auto &buffer_table() { return ring_.buffer_table(); }
298
303 auto &settings() { return ring_.settings(); }
304
305private:
306 void flush_global_queue_() {
307 local_queue_.push_back(std::move(global_queue_));
308 async_waiter_.async_wait(ring_);
309 }
310
311 void prep_msg_ring_(io_uring_sqe *sqe, WorkInvoker *work) {
312 auto data = encode_work(work, WorkType::Schedule);
313 io_uring_prep_msg_ring(sqe, this->ring_.ring()->ring_fd, 0,
314 reinterpret_cast<uint64_t>(data), 0);
315 io_uring_sqe_set_data(sqe, encode_work(nullptr, WorkType::Schedule));
316 }
317
318 size_t flush_ring_() {
319 return ring_.reap_completions(
320 [this](io_uring_cqe *cqe) { process_cqe_(cqe); });
321 }
322
323 size_t flush_ring_wait_() {
324 return ring_.reap_completions_wait(
325 [this](io_uring_cqe *cqe) { process_cqe_(cqe); });
326 }
327
328 void process_cqe_(io_uring_cqe *cqe) {
329 auto *data_raw = io_uring_cqe_get_data(cqe);
330 auto [data, type] = decode_work(data_raw);
331
332 if (type == WorkType::Ignore) {
333 // No-op
334 assert(cqe->res != -EINVAL); // If EINVAL, something is wrong
335 } else if (type == WorkType::Notify) {
336 if (cqe->res == -EOPNOTSUPP) {
337 // Notification not supported, ignore. This may happen if we use
338 // eventfd for notification and iopoll is enabled.
339 return;
340 }
341 std::lock_guard<std::mutex> lock(mutex_);
342 flush_global_queue_();
343 } else if (type == WorkType::SendFd) {
344 auto &fd_table = ring_.fd_table();
345 if (fd_table.fd_accepter_ == nullptr) [[unlikely]] {
346 throw std::logic_error("No way to accept sent fd");
347 }
348 uint64_t payload = reinterpret_cast<uint64_t>(data) >> 3;
349 if (payload == 0) { // Auto-allocate
350 fd_table.fd_accepter_(cqe->res);
351 } else {
352 int target_fd = static_cast<int>(payload - 1);
353 fd_table.fd_accepter_(target_fd);
354 }
355 } else if (type == WorkType::Schedule) {
356 if (data == nullptr) {
357 assert(cqe->res == 0);
358 pending_works_--;
359 } else {
360 auto *work = static_cast<WorkInvoker *>(data);
361 tsan_acquire(data);
362 local_queue_.push_back(work);
363 }
364 } else if (type == WorkType::Common) {
365 auto *handle = static_cast<OpFinishHandleBase *>(data);
366 auto action = handle->handle_cqe(cqe);
367 if (action.op_finish) {
368 pending_works_--;
369 }
370 if (action.queue_work) {
371 local_queue_.push_back(handle);
372 }
373 } else {
374 assert(false && "Invalid work type");
375 }
376 }
377
378private:
379 enum class State : uint8_t {
380 Idle, // Not running
381 Running, // Started running
382 Enabled, // Running and ring enabled
383 Stopped, // Stopped
384 };
385 static_assert(std::atomic<State>::is_always_lock_free);
386
387 using WorkListQueue =
388 IntrusiveSingleList<WorkInvoker, &WorkInvoker::work_queue_entry_>;
389
390 // Global state
391 std::mutex mutex_;
392 detail::AsyncWaiter async_waiter_;
393 WorkListQueue global_queue_;
394 std::atomic_size_t pending_works_ = 1;
395 std::atomic<State> state_ = State::Idle;
396
397 // Local state
398 WorkListQueue local_queue_;
399 Ring ring_;
400 size_t tick_count_ = 0;
401
402 // Configurable parameters
403 size_t event_interval_ = 61;
404 bool disable_register_ring_fd_ = false;
405};
406
413inline auto &current_runtime() { return *detail::Context::current().runtime(); }
414
415} // namespace condy
void run()
Run the runtime event loop in the current thread.
Definition runtime.hpp:240
void allow_exit()
Allow the runtime to exit when there are no pending works.
Definition runtime.hpp:184
auto & settings()
Get the ring settings of the runtime.
Definition runtime.hpp:303
auto & buffer_table()
Get the buffer table of the runtime.
Definition runtime.hpp:297
Runtime(const RuntimeOptions &options={})
Construct a new Runtime object.
Definition runtime.hpp:82
auto & fd_table()
Get the file descriptor table of the runtime.
Definition runtime.hpp:291
Definitions of finish handle types for asynchronous operations.
Intrusive single-linked and double-linked list implementations.
Polymorphic invocation utilities.
The main namespace for the Condy library.
Definition condy.hpp:28
auto & current_runtime()
Get the current runtime.
Definition runtime.hpp:413
Defer defer(Func &&func)
Defer the execution of a function until the current scope ends.
Definition utils.hpp:56
Wrapper classes for liburing interfaces.
Internal utility classes and functions used by Condy.