util/async: make bh_aio_poll() O(1)
[qemu/kevin.git] / include / block / aio.h
blob1a2ce9ca2610627e7f4832b636b17b0f88e0f984
1 /*
2 * QEMU aio implementation
4 * Copyright IBM, Corp. 2008
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.com>
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
14 #ifndef QEMU_AIO_H
15 #define QEMU_AIO_H
17 #include "qemu/queue.h"
18 #include "qemu/event_notifier.h"
19 #include "qemu/thread.h"
20 #include "qemu/timer.h"
22 typedef struct BlockAIOCB BlockAIOCB;
23 typedef void BlockCompletionFunc(void *opaque, int ret);
25 typedef struct AIOCBInfo {
26 void (*cancel_async)(BlockAIOCB *acb);
27 AioContext *(*get_aio_context)(BlockAIOCB *acb);
28 size_t aiocb_size;
29 } AIOCBInfo;
31 struct BlockAIOCB {
32 const AIOCBInfo *aiocb_info;
33 BlockDriverState *bs;
34 BlockCompletionFunc *cb;
35 void *opaque;
36 int refcnt;
39 void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
40 BlockCompletionFunc *cb, void *opaque);
41 void qemu_aio_unref(void *p);
42 void qemu_aio_ref(void *p);
44 typedef struct AioHandler AioHandler;
45 typedef void QEMUBHFunc(void *opaque);
46 typedef bool AioPollFn(void *opaque);
47 typedef void IOHandler(void *opaque);
49 struct Coroutine;
50 struct ThreadPool;
51 struct LinuxAioState;
52 struct LuringState;
55 * Each aio_bh_poll() call carves off a slice of the BH list, so that newly
56 * scheduled BHs are not processed until the next aio_bh_poll() call. All
57 * active aio_bh_poll() calls chain their slices together in a list, so that
58 * nested aio_bh_poll() calls process all scheduled bottom halves.
60 typedef QSLIST_HEAD(, QEMUBH) BHList;
61 typedef struct BHListSlice BHListSlice;
62 struct BHListSlice {
63 BHList bh_list;
64 QSIMPLEQ_ENTRY(BHListSlice) next;
67 struct AioContext {
68 GSource source;
70 /* Used by AioContext users to protect from multi-threaded access. */
71 QemuRecMutex lock;
73 /* The list of registered AIO handlers. Protected by ctx->list_lock. */
74 QLIST_HEAD(, AioHandler) aio_handlers;
76 /* Used to avoid unnecessary event_notifier_set calls in aio_notify;
77 * accessed with atomic primitives. If this field is 0, everything
78 * (file descriptors, bottom halves, timers) will be re-evaluated
79 * before the next blocking poll(), thus the event_notifier_set call
80 * can be skipped. If it is non-zero, you may need to wake up a
81 * concurrent aio_poll or the glib main event loop, making
82 * event_notifier_set necessary.
84 * Bit 0 is reserved for GSource usage of the AioContext, and is 1
85 * between a call to aio_ctx_prepare and the next call to aio_ctx_check.
86 * Bits 1-31 simply count the number of active calls to aio_poll
87 * that are in the prepare or poll phase.
89 * The GSource and aio_poll must use a different mechanism because
90 * there is no certainty that a call to GSource's prepare callback
91 * (via g_main_context_prepare) is indeed followed by check and
92 * dispatch. It's not clear whether this would be a bug, but let's
93 * play safe and allow it---it will just cause extra calls to
94 * event_notifier_set until the next call to dispatch.
96 * Instead, the aio_poll calls include both the prepare and the
97 * dispatch phase, hence a simple counter is enough for them.
99 uint32_t notify_me;
101 /* A lock to protect between QEMUBH and AioHandler adders and deleter,
102 * and to ensure that no callbacks are removed while we're walking and
103 * dispatching them.
105 QemuLockCnt list_lock;
107 /* Bottom Halves pending aio_bh_poll() processing */
108 BHList bh_list;
110 /* Chained BH list slices for each nested aio_bh_poll() call */
111 QSIMPLEQ_HEAD(, BHListSlice) bh_slice_list;
113 /* Used by aio_notify.
115 * "notified" is used to avoid expensive event_notifier_test_and_clear
116 * calls. When it is clear, the EventNotifier is clear, or one thread
117 * is going to clear "notified" before processing more events. False
118 * positives are possible, i.e. "notified" could be set even though the
119 * EventNotifier is clear.
121 * Note that event_notifier_set *cannot* be optimized the same way. For
122 * more information on the problem that would result, see "#ifdef BUG2"
123 * in the docs/aio_notify_accept.promela formal model.
125 bool notified;
126 EventNotifier notifier;
128 QSLIST_HEAD(, Coroutine) scheduled_coroutines;
129 QEMUBH *co_schedule_bh;
131 /* Thread pool for performing work and receiving completion callbacks.
132 * Has its own locking.
134 struct ThreadPool *thread_pool;
136 #ifdef CONFIG_LINUX_AIO
138 * State for native Linux AIO. Uses aio_context_acquire/release for
139 * locking.
141 struct LinuxAioState *linux_aio;
142 #endif
143 #ifdef CONFIG_LINUX_IO_URING
145 * State for Linux io_uring. Uses aio_context_acquire/release for
146 * locking.
148 struct LuringState *linux_io_uring;
149 #endif
151 /* TimerLists for calling timers - one per clock type. Has its own
152 * locking.
154 QEMUTimerListGroup tlg;
156 int external_disable_cnt;
158 /* Number of AioHandlers without .io_poll() */
159 int poll_disable_cnt;
161 /* Polling mode parameters */
162 int64_t poll_ns; /* current polling time in nanoseconds */
163 int64_t poll_max_ns; /* maximum polling time in nanoseconds */
164 int64_t poll_grow; /* polling time growth factor */
165 int64_t poll_shrink; /* polling time shrink factor */
167 /* Are we in polling mode or monitoring file descriptors? */
168 bool poll_started;
170 /* epoll(7) state used when built with CONFIG_EPOLL */
171 int epollfd;
172 bool epoll_enabled;
173 bool epoll_available;
177 * aio_context_new: Allocate a new AioContext.
179 * AioContext provide a mini event-loop that can be waited on synchronously.
180 * They also provide bottom halves, a service to execute a piece of code
181 * as soon as possible.
183 AioContext *aio_context_new(Error **errp);
186 * aio_context_ref:
187 * @ctx: The AioContext to operate on.
189 * Add a reference to an AioContext.
191 void aio_context_ref(AioContext *ctx);
194 * aio_context_unref:
195 * @ctx: The AioContext to operate on.
197 * Drop a reference to an AioContext.
199 void aio_context_unref(AioContext *ctx);
201 /* Take ownership of the AioContext. If the AioContext will be shared between
202 * threads, and a thread does not want to be interrupted, it will have to
203 * take ownership around calls to aio_poll(). Otherwise, aio_poll()
204 * automatically takes care of calling aio_context_acquire and
205 * aio_context_release.
207 * Note that this is separate from bdrv_drained_begin/bdrv_drained_end. A
208 * thread still has to call those to avoid being interrupted by the guest.
210 * Bottom halves, timers and callbacks can be created or removed without
211 * acquiring the AioContext.
213 void aio_context_acquire(AioContext *ctx);
215 /* Relinquish ownership of the AioContext. */
216 void aio_context_release(AioContext *ctx);
219 * aio_bh_schedule_oneshot: Allocate a new bottom half structure that will run
220 * only once and as soon as possible.
222 void aio_bh_schedule_oneshot(AioContext *ctx, QEMUBHFunc *cb, void *opaque);
225 * aio_bh_new: Allocate a new bottom half structure.
227 * Bottom halves are lightweight callbacks whose invocation is guaranteed
228 * to be wait-free, thread-safe and signal-safe. The #QEMUBH structure
229 * is opaque and must be allocated prior to its use.
231 QEMUBH *aio_bh_new(AioContext *ctx, QEMUBHFunc *cb, void *opaque);
234 * aio_notify: Force processing of pending events.
236 * Similar to signaling a condition variable, aio_notify forces
237 * aio_poll to exit, so that the next call will re-examine pending events.
238 * The caller of aio_notify will usually call aio_poll again very soon,
239 * or go through another iteration of the GLib main loop. Hence, aio_notify
240 * also has the side effect of recalculating the sets of file descriptors
241 * that the main loop waits for.
243 * Calling aio_notify is rarely necessary, because for example scheduling
244 * a bottom half calls it already.
246 void aio_notify(AioContext *ctx);
249 * aio_notify_accept: Acknowledge receiving an aio_notify.
251 * aio_notify() uses an EventNotifier in order to wake up a sleeping
252 * aio_poll() or g_main_context_iteration(). Calls to aio_notify() are
253 * usually rare, but the AioContext has to clear the EventNotifier on
254 * every aio_poll() or g_main_context_iteration() in order to avoid
255 * busy waiting. This event_notifier_test_and_clear() cannot be done
256 * using the usual aio_context_set_event_notifier(), because it must
257 * be done before processing all events (file descriptors, bottom halves,
258 * timers).
260 * aio_notify_accept() is an optimized event_notifier_test_and_clear()
261 * that is specific to an AioContext's notifier; it is used internally
262 * to clear the EventNotifier only if aio_notify() had been called.
264 void aio_notify_accept(AioContext *ctx);
267 * aio_bh_call: Executes callback function of the specified BH.
269 void aio_bh_call(QEMUBH *bh);
272 * aio_bh_poll: Poll bottom halves for an AioContext.
274 * These are internal functions used by the QEMU main loop.
275 * And notice that multiple occurrences of aio_bh_poll cannot
276 * be called concurrently
278 int aio_bh_poll(AioContext *ctx);
281 * qemu_bh_schedule: Schedule a bottom half.
283 * Scheduling a bottom half interrupts the main loop and causes the
284 * execution of the callback that was passed to qemu_bh_new.
286 * Bottom halves that are scheduled from a bottom half handler are instantly
287 * invoked. This can create an infinite loop if a bottom half handler
288 * schedules itself.
290 * @bh: The bottom half to be scheduled.
292 void qemu_bh_schedule(QEMUBH *bh);
295 * qemu_bh_cancel: Cancel execution of a bottom half.
297 * Canceling execution of a bottom half undoes the effect of calls to
298 * qemu_bh_schedule without freeing its resources yet. While cancellation
299 * itself is also wait-free and thread-safe, it can of course race with the
300 * loop that executes bottom halves unless you are holding the iothread
301 * mutex. This makes it mostly useless if you are not holding the mutex.
303 * @bh: The bottom half to be canceled.
305 void qemu_bh_cancel(QEMUBH *bh);
308 *qemu_bh_delete: Cancel execution of a bottom half and free its resources.
310 * Deleting a bottom half frees the memory that was allocated for it by
311 * qemu_bh_new. It also implies canceling the bottom half if it was
312 * scheduled.
313 * This func is async. The bottom half will do the delete action at the finial
314 * end.
316 * @bh: The bottom half to be deleted.
318 void qemu_bh_delete(QEMUBH *bh);
320 /* Return whether there are any pending callbacks from the GSource
321 * attached to the AioContext, before g_poll is invoked.
323 * This is used internally in the implementation of the GSource.
325 bool aio_prepare(AioContext *ctx);
327 /* Return whether there are any pending callbacks from the GSource
328 * attached to the AioContext, after g_poll is invoked.
330 * This is used internally in the implementation of the GSource.
332 bool aio_pending(AioContext *ctx);
334 /* Dispatch any pending callbacks from the GSource attached to the AioContext.
336 * This is used internally in the implementation of the GSource.
338 void aio_dispatch(AioContext *ctx);
340 /* Progress in completing AIO work to occur. This can issue new pending
341 * aio as a result of executing I/O completion or bh callbacks.
343 * Return whether any progress was made by executing AIO or bottom half
344 * handlers. If @blocking == true, this should always be true except
345 * if someone called aio_notify.
347 * If there are no pending bottom halves, but there are pending AIO
348 * operations, it may not be possible to make any progress without
349 * blocking. If @blocking is true, this function will wait until one
350 * or more AIO events have completed, to ensure something has moved
351 * before returning.
353 bool aio_poll(AioContext *ctx, bool blocking);
355 /* Register a file descriptor and associated callbacks. Behaves very similarly
356 * to qemu_set_fd_handler. Unlike qemu_set_fd_handler, these callbacks will
357 * be invoked when using aio_poll().
359 * Code that invokes AIO completion functions should rely on this function
360 * instead of qemu_set_fd_handler[2].
362 void aio_set_fd_handler(AioContext *ctx,
363 int fd,
364 bool is_external,
365 IOHandler *io_read,
366 IOHandler *io_write,
367 AioPollFn *io_poll,
368 void *opaque);
370 /* Set polling begin/end callbacks for a file descriptor that has already been
371 * registered with aio_set_fd_handler. Do nothing if the file descriptor is
372 * not registered.
374 void aio_set_fd_poll(AioContext *ctx, int fd,
375 IOHandler *io_poll_begin,
376 IOHandler *io_poll_end);
378 /* Register an event notifier and associated callbacks. Behaves very similarly
379 * to event_notifier_set_handler. Unlike event_notifier_set_handler, these callbacks
380 * will be invoked when using aio_poll().
382 * Code that invokes AIO completion functions should rely on this function
383 * instead of event_notifier_set_handler.
385 void aio_set_event_notifier(AioContext *ctx,
386 EventNotifier *notifier,
387 bool is_external,
388 EventNotifierHandler *io_read,
389 AioPollFn *io_poll);
391 /* Set polling begin/end callbacks for an event notifier that has already been
392 * registered with aio_set_event_notifier. Do nothing if the event notifier is
393 * not registered.
395 void aio_set_event_notifier_poll(AioContext *ctx,
396 EventNotifier *notifier,
397 EventNotifierHandler *io_poll_begin,
398 EventNotifierHandler *io_poll_end);
400 /* Return a GSource that lets the main loop poll the file descriptors attached
401 * to this AioContext.
403 GSource *aio_get_g_source(AioContext *ctx);
405 /* Return the ThreadPool bound to this AioContext */
406 struct ThreadPool *aio_get_thread_pool(AioContext *ctx);
408 /* Setup the LinuxAioState bound to this AioContext */
409 struct LinuxAioState *aio_setup_linux_aio(AioContext *ctx, Error **errp);
411 /* Return the LinuxAioState bound to this AioContext */
412 struct LinuxAioState *aio_get_linux_aio(AioContext *ctx);
414 /* Setup the LuringState bound to this AioContext */
415 struct LuringState *aio_setup_linux_io_uring(AioContext *ctx, Error **errp);
417 /* Return the LuringState bound to this AioContext */
418 struct LuringState *aio_get_linux_io_uring(AioContext *ctx);
420 * aio_timer_new_with_attrs:
421 * @ctx: the aio context
422 * @type: the clock type
423 * @scale: the scale
424 * @attributes: 0, or one to multiple OR'ed QEMU_TIMER_ATTR_<id> values
425 * to assign
426 * @cb: the callback to call on timer expiry
427 * @opaque: the opaque pointer to pass to the callback
429 * Allocate a new timer (with attributes) attached to the context @ctx.
430 * The function is responsible for memory allocation.
432 * The preferred interface is aio_timer_init or aio_timer_init_with_attrs.
433 * Use that unless you really need dynamic memory allocation.
435 * Returns: a pointer to the new timer
437 static inline QEMUTimer *aio_timer_new_with_attrs(AioContext *ctx,
438 QEMUClockType type,
439 int scale, int attributes,
440 QEMUTimerCB *cb, void *opaque)
442 return timer_new_full(&ctx->tlg, type, scale, attributes, cb, opaque);
446 * aio_timer_new:
447 * @ctx: the aio context
448 * @type: the clock type
449 * @scale: the scale
450 * @cb: the callback to call on timer expiry
451 * @opaque: the opaque pointer to pass to the callback
453 * Allocate a new timer attached to the context @ctx.
454 * See aio_timer_new_with_attrs for details.
456 * Returns: a pointer to the new timer
458 static inline QEMUTimer *aio_timer_new(AioContext *ctx, QEMUClockType type,
459 int scale,
460 QEMUTimerCB *cb, void *opaque)
462 return timer_new_full(&ctx->tlg, type, scale, 0, cb, opaque);
466 * aio_timer_init_with_attrs:
467 * @ctx: the aio context
468 * @ts: the timer
469 * @type: the clock type
470 * @scale: the scale
471 * @attributes: 0, or one to multiple OR'ed QEMU_TIMER_ATTR_<id> values
472 * to assign
473 * @cb: the callback to call on timer expiry
474 * @opaque: the opaque pointer to pass to the callback
476 * Initialise a new timer (with attributes) attached to the context @ctx.
477 * The caller is responsible for memory allocation.
479 static inline void aio_timer_init_with_attrs(AioContext *ctx,
480 QEMUTimer *ts, QEMUClockType type,
481 int scale, int attributes,
482 QEMUTimerCB *cb, void *opaque)
484 timer_init_full(ts, &ctx->tlg, type, scale, attributes, cb, opaque);
488 * aio_timer_init:
489 * @ctx: the aio context
490 * @ts: the timer
491 * @type: the clock type
492 * @scale: the scale
493 * @cb: the callback to call on timer expiry
494 * @opaque: the opaque pointer to pass to the callback
496 * Initialise a new timer attached to the context @ctx.
497 * See aio_timer_init_with_attrs for details.
499 static inline void aio_timer_init(AioContext *ctx,
500 QEMUTimer *ts, QEMUClockType type,
501 int scale,
502 QEMUTimerCB *cb, void *opaque)
504 timer_init_full(ts, &ctx->tlg, type, scale, 0, cb, opaque);
508 * aio_compute_timeout:
509 * @ctx: the aio context
511 * Compute the timeout that a blocking aio_poll should use.
513 int64_t aio_compute_timeout(AioContext *ctx);
516 * aio_disable_external:
517 * @ctx: the aio context
519 * Disable the further processing of external clients.
521 static inline void aio_disable_external(AioContext *ctx)
523 atomic_inc(&ctx->external_disable_cnt);
527 * aio_enable_external:
528 * @ctx: the aio context
530 * Enable the processing of external clients.
532 static inline void aio_enable_external(AioContext *ctx)
534 int old;
536 old = atomic_fetch_dec(&ctx->external_disable_cnt);
537 assert(old > 0);
538 if (old == 1) {
539 /* Kick event loop so it re-arms file descriptors */
540 aio_notify(ctx);
545 * aio_external_disabled:
546 * @ctx: the aio context
548 * Return true if the external clients are disabled.
550 static inline bool aio_external_disabled(AioContext *ctx)
552 return atomic_read(&ctx->external_disable_cnt);
556 * aio_node_check:
557 * @ctx: the aio context
558 * @is_external: Whether or not the checked node is an external event source.
560 * Check if the node's is_external flag is okay to be polled by the ctx at this
561 * moment. True means green light.
563 static inline bool aio_node_check(AioContext *ctx, bool is_external)
565 return !is_external || !atomic_read(&ctx->external_disable_cnt);
569 * aio_co_schedule:
570 * @ctx: the aio context
571 * @co: the coroutine
573 * Start a coroutine on a remote AioContext.
575 * The coroutine must not be entered by anyone else while aio_co_schedule()
576 * is active. In addition the coroutine must have yielded unless ctx
577 * is the context in which the coroutine is running (i.e. the value of
578 * qemu_get_current_aio_context() from the coroutine itself).
580 void aio_co_schedule(AioContext *ctx, struct Coroutine *co);
583 * aio_co_wake:
584 * @co: the coroutine
586 * Restart a coroutine on the AioContext where it was running last, thus
587 * preventing coroutines from jumping from one context to another when they
588 * go to sleep.
590 * aio_co_wake may be executed either in coroutine or non-coroutine
591 * context. The coroutine must not be entered by anyone else while
592 * aio_co_wake() is active.
594 void aio_co_wake(struct Coroutine *co);
597 * aio_co_enter:
598 * @ctx: the context to run the coroutine
599 * @co: the coroutine to run
601 * Enter a coroutine in the specified AioContext.
603 void aio_co_enter(AioContext *ctx, struct Coroutine *co);
606 * Return the AioContext whose event loop runs in the current thread.
608 * If called from an IOThread this will be the IOThread's AioContext. If
609 * called from another thread it will be the main loop AioContext.
611 AioContext *qemu_get_current_aio_context(void);
614 * in_aio_context_home_thread:
615 * @ctx: the aio context
617 * Return whether we are running in the thread that normally runs @ctx. Note
618 * that acquiring/releasing ctx does not affect the outcome, each AioContext
619 * still only has one home thread that is responsible for running it.
621 static inline bool in_aio_context_home_thread(AioContext *ctx)
623 return ctx == qemu_get_current_aio_context();
627 * aio_context_setup:
628 * @ctx: the aio context
630 * Initialize the aio context.
632 void aio_context_setup(AioContext *ctx);
635 * aio_context_destroy:
636 * @ctx: the aio context
638 * Destroy the aio context.
640 void aio_context_destroy(AioContext *ctx);
643 * aio_context_set_poll_params:
644 * @ctx: the aio context
645 * @max_ns: how long to busy poll for, in nanoseconds
646 * @grow: polling time growth factor
647 * @shrink: polling time shrink factor
649 * Poll mode can be disabled by setting poll_max_ns to 0.
651 void aio_context_set_poll_params(AioContext *ctx, int64_t max_ns,
652 int64_t grow, int64_t shrink,
653 Error **errp);
655 #endif