Merge tag 'v9.0.0-rc3'
[qemu/ar7.git] / include / block / aio.h
blob8378553eb9dde7dac7a149de4ca1751ad2a068bb
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 #ifdef CONFIG_LINUX_IO_URING
18 #include <liburing.h>
19 #endif
20 #include "qemu/coroutine-core.h"
21 #include "qemu/queue.h"
22 #include "qemu/event_notifier.h"
23 #include "qemu/thread.h"
24 #include "qemu/timer.h"
25 #include "block/graph-lock.h"
26 #include "hw/qdev-core.h"
29 typedef struct BlockAIOCB BlockAIOCB;
30 typedef void BlockCompletionFunc(void *opaque, int ret);
32 typedef struct AIOCBInfo {
33 void (*cancel_async)(BlockAIOCB *acb);
34 size_t aiocb_size;
35 } AIOCBInfo;
37 struct BlockAIOCB {
38 const AIOCBInfo *aiocb_info;
39 BlockDriverState *bs;
40 BlockCompletionFunc *cb;
41 void *opaque;
42 int refcnt;
45 void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
46 BlockCompletionFunc *cb, void *opaque);
47 void qemu_aio_unref(void *p);
48 void qemu_aio_ref(void *p);
50 typedef struct AioHandler AioHandler;
51 typedef QLIST_HEAD(, AioHandler) AioHandlerList;
52 typedef void QEMUBHFunc(void *opaque);
53 typedef bool AioPollFn(void *opaque);
54 typedef void IOHandler(void *opaque);
56 struct ThreadPool;
57 struct LinuxAioState;
58 typedef struct LuringState LuringState;
60 /* Is polling disabled? */
61 bool aio_poll_disabled(AioContext *ctx);
63 /* Callbacks for file descriptor monitoring implementations */
64 typedef struct {
66 * update:
67 * @ctx: the AioContext
68 * @old_node: the existing handler or NULL if this file descriptor is being
69 * monitored for the first time
70 * @new_node: the new handler or NULL if this file descriptor is being
71 * removed
73 * Add/remove/modify a monitored file descriptor.
75 * Called with ctx->list_lock acquired.
77 void (*update)(AioContext *ctx, AioHandler *old_node, AioHandler *new_node);
80 * wait:
81 * @ctx: the AioContext
82 * @ready_list: list for handlers that become ready
83 * @timeout: maximum duration to wait, in nanoseconds
85 * Wait for file descriptors to become ready and place them on ready_list.
87 * Called with ctx->list_lock incremented but not locked.
89 * Returns: number of ready file descriptors.
91 int (*wait)(AioContext *ctx, AioHandlerList *ready_list, int64_t timeout);
94 * need_wait:
95 * @ctx: the AioContext
97 * Tell aio_poll() when to stop userspace polling early because ->wait()
98 * has fds ready.
100 * File descriptor monitoring implementations that cannot poll fd readiness
101 * from userspace should use aio_poll_disabled() here. This ensures that
102 * file descriptors are not starved by handlers that frequently make
103 * progress via userspace polling.
105 * Returns: true if ->wait() should be called, false otherwise.
107 bool (*need_wait)(AioContext *ctx);
108 } FDMonOps;
111 * Each aio_bh_poll() call carves off a slice of the BH list, so that newly
112 * scheduled BHs are not processed until the next aio_bh_poll() call. All
113 * active aio_bh_poll() calls chain their slices together in a list, so that
114 * nested aio_bh_poll() calls process all scheduled bottom halves.
116 typedef QSLIST_HEAD(, QEMUBH) BHList;
117 typedef struct BHListSlice BHListSlice;
118 struct BHListSlice {
119 BHList bh_list;
120 QSIMPLEQ_ENTRY(BHListSlice) next;
123 typedef QSLIST_HEAD(, AioHandler) AioHandlerSList;
125 struct AioContext {
126 GSource source;
128 /* Used by AioContext users to protect from multi-threaded access. */
129 QemuRecMutex lock;
132 * Keep track of readers and writers of the block layer graph.
133 * This is essential to avoid performing additions and removal
134 * of nodes and edges from block graph while some
135 * other thread is traversing it.
137 BdrvGraphRWlock *bdrv_graph;
139 /* The list of registered AIO handlers. Protected by ctx->list_lock. */
140 AioHandlerList aio_handlers;
142 /* The list of AIO handlers to be deleted. Protected by ctx->list_lock. */
143 AioHandlerList deleted_aio_handlers;
145 /* Used to avoid unnecessary event_notifier_set calls in aio_notify;
146 * only written from the AioContext home thread, or under the BQL in
147 * the case of the main AioContext. However, it is read from any
148 * thread so it is still accessed with atomic primitives.
150 * If this field is 0, everything (file descriptors, bottom halves,
151 * timers) will be re-evaluated before the next blocking poll() or
152 * io_uring wait; therefore, the event_notifier_set call can be
153 * skipped. If it is non-zero, you may need to wake up a concurrent
154 * aio_poll or the glib main event loop, making event_notifier_set
155 * necessary.
157 * Bit 0 is reserved for GSource usage of the AioContext, and is 1
158 * between a call to aio_ctx_prepare and the next call to aio_ctx_check.
159 * Bits 1-31 simply count the number of active calls to aio_poll
160 * that are in the prepare or poll phase.
162 * The GSource and aio_poll must use a different mechanism because
163 * there is no certainty that a call to GSource's prepare callback
164 * (via g_main_context_prepare) is indeed followed by check and
165 * dispatch. It's not clear whether this would be a bug, but let's
166 * play safe and allow it---it will just cause extra calls to
167 * event_notifier_set until the next call to dispatch.
169 * Instead, the aio_poll calls include both the prepare and the
170 * dispatch phase, hence a simple counter is enough for them.
172 uint32_t notify_me;
174 /* A lock to protect between QEMUBH and AioHandler adders and deleter,
175 * and to ensure that no callbacks are removed while we're walking and
176 * dispatching them.
178 QemuLockCnt list_lock;
180 /* Bottom Halves pending aio_bh_poll() processing */
181 BHList bh_list;
183 /* Chained BH list slices for each nested aio_bh_poll() call */
184 QSIMPLEQ_HEAD(, BHListSlice) bh_slice_list;
186 /* Used by aio_notify.
188 * "notified" is used to avoid expensive event_notifier_test_and_clear
189 * calls. When it is clear, the EventNotifier is clear, or one thread
190 * is going to clear "notified" before processing more events. False
191 * positives are possible, i.e. "notified" could be set even though the
192 * EventNotifier is clear.
194 * Note that event_notifier_set *cannot* be optimized the same way. For
195 * more information on the problem that would result, see "#ifdef BUG2"
196 * in the docs/aio_notify_accept.promela formal model.
198 bool notified;
199 EventNotifier notifier;
201 QSLIST_HEAD(, Coroutine) scheduled_coroutines;
202 QEMUBH *co_schedule_bh;
204 int thread_pool_min;
205 int thread_pool_max;
206 /* Thread pool for performing work and receiving completion callbacks.
207 * Has its own locking.
209 struct ThreadPool *thread_pool;
211 #ifdef CONFIG_LINUX_AIO
212 struct LinuxAioState *linux_aio;
213 #endif
214 #ifdef CONFIG_LINUX_IO_URING
215 LuringState *linux_io_uring;
217 /* State for file descriptor monitoring using Linux io_uring */
218 struct io_uring fdmon_io_uring;
219 AioHandlerSList submit_list;
220 #endif
222 /* TimerLists for calling timers - one per clock type. Has its own
223 * locking.
225 QEMUTimerListGroup tlg;
227 /* Number of AioHandlers without .io_poll() */
228 int poll_disable_cnt;
230 /* Polling mode parameters */
231 int64_t poll_ns; /* current polling time in nanoseconds */
232 int64_t poll_max_ns; /* maximum polling time in nanoseconds */
233 int64_t poll_grow; /* polling time growth factor */
234 int64_t poll_shrink; /* polling time shrink factor */
236 /* AIO engine parameters */
237 int64_t aio_max_batch; /* maximum number of requests in a batch */
240 * List of handlers participating in userspace polling. Protected by
241 * ctx->list_lock. Iterated and modified mostly by the event loop thread
242 * from aio_poll() with ctx->list_lock incremented. aio_set_fd_handler()
243 * only touches the list to delete nodes if ctx->list_lock's count is zero.
245 AioHandlerList poll_aio_handlers;
247 /* Are we in polling mode or monitoring file descriptors? */
248 bool poll_started;
250 /* epoll(7) state used when built with CONFIG_EPOLL */
251 int epollfd;
253 const FDMonOps *fdmon_ops;
257 * aio_context_new: Allocate a new AioContext.
259 * AioContext provide a mini event-loop that can be waited on synchronously.
260 * They also provide bottom halves, a service to execute a piece of code
261 * as soon as possible.
263 AioContext *aio_context_new(Error **errp);
266 * aio_context_ref:
267 * @ctx: The AioContext to operate on.
269 * Add a reference to an AioContext.
271 void aio_context_ref(AioContext *ctx);
274 * aio_context_unref:
275 * @ctx: The AioContext to operate on.
277 * Drop a reference to an AioContext.
279 void aio_context_unref(AioContext *ctx);
282 * aio_bh_schedule_oneshot_full: Allocate a new bottom half structure that will
283 * run only once and as soon as possible.
285 * @name: A human-readable identifier for debugging purposes.
287 void aio_bh_schedule_oneshot_full(AioContext *ctx, QEMUBHFunc *cb, void *opaque,
288 const char *name);
291 * aio_bh_schedule_oneshot: Allocate a new bottom half structure that will run
292 * only once and as soon as possible.
294 * A convenience wrapper for aio_bh_schedule_oneshot_full() that uses cb as the
295 * name string.
297 #define aio_bh_schedule_oneshot(ctx, cb, opaque) \
298 aio_bh_schedule_oneshot_full((ctx), (cb), (opaque), (stringify(cb)))
301 * aio_bh_new_full: Allocate a new bottom half structure.
303 * Bottom halves are lightweight callbacks whose invocation is guaranteed
304 * to be wait-free, thread-safe and signal-safe. The #QEMUBH structure
305 * is opaque and must be allocated prior to its use.
307 * @name: A human-readable identifier for debugging purposes.
308 * @reentrancy_guard: A guard set when entering a cb to prevent
309 * device-reentrancy issues
311 QEMUBH *aio_bh_new_full(AioContext *ctx, QEMUBHFunc *cb, void *opaque,
312 const char *name, MemReentrancyGuard *reentrancy_guard);
315 * aio_bh_new: Allocate a new bottom half structure
317 * A convenience wrapper for aio_bh_new_full() that uses the cb as the name
318 * string.
320 #define aio_bh_new(ctx, cb, opaque) \
321 aio_bh_new_full((ctx), (cb), (opaque), (stringify(cb)), NULL)
324 * aio_bh_new_guarded: Allocate a new bottom half structure with a
325 * reentrancy_guard
327 * A convenience wrapper for aio_bh_new_full() that uses the cb as the name
328 * string.
330 #define aio_bh_new_guarded(ctx, cb, opaque, guard) \
331 aio_bh_new_full((ctx), (cb), (opaque), (stringify(cb)), guard)
334 * aio_notify: Force processing of pending events.
336 * Similar to signaling a condition variable, aio_notify forces
337 * aio_poll to exit, so that the next call will re-examine pending events.
338 * The caller of aio_notify will usually call aio_poll again very soon,
339 * or go through another iteration of the GLib main loop. Hence, aio_notify
340 * also has the side effect of recalculating the sets of file descriptors
341 * that the main loop waits for.
343 * Calling aio_notify is rarely necessary, because for example scheduling
344 * a bottom half calls it already.
346 void aio_notify(AioContext *ctx);
349 * aio_notify_accept: Acknowledge receiving an aio_notify.
351 * aio_notify() uses an EventNotifier in order to wake up a sleeping
352 * aio_poll() or g_main_context_iteration(). Calls to aio_notify() are
353 * usually rare, but the AioContext has to clear the EventNotifier on
354 * every aio_poll() or g_main_context_iteration() in order to avoid
355 * busy waiting. This event_notifier_test_and_clear() cannot be done
356 * using the usual aio_context_set_event_notifier(), because it must
357 * be done before processing all events (file descriptors, bottom halves,
358 * timers).
360 * aio_notify_accept() is an optimized event_notifier_test_and_clear()
361 * that is specific to an AioContext's notifier; it is used internally
362 * to clear the EventNotifier only if aio_notify() had been called.
364 void aio_notify_accept(AioContext *ctx);
367 * aio_bh_call: Executes callback function of the specified BH.
369 void aio_bh_call(QEMUBH *bh);
372 * aio_bh_poll: Poll bottom halves for an AioContext.
374 * These are internal functions used by the QEMU main loop.
375 * And notice that multiple occurrences of aio_bh_poll cannot
376 * be called concurrently
378 int aio_bh_poll(AioContext *ctx);
381 * qemu_bh_schedule: Schedule a bottom half.
383 * Scheduling a bottom half interrupts the main loop and causes the
384 * execution of the callback that was passed to qemu_bh_new.
386 * Bottom halves that are scheduled from a bottom half handler are instantly
387 * invoked. This can create an infinite loop if a bottom half handler
388 * schedules itself.
390 * @bh: The bottom half to be scheduled.
392 void qemu_bh_schedule(QEMUBH *bh);
395 * qemu_bh_cancel: Cancel execution of a bottom half.
397 * Canceling execution of a bottom half undoes the effect of calls to
398 * qemu_bh_schedule without freeing its resources yet. While cancellation
399 * itself is also wait-free and thread-safe, it can of course race with the
400 * loop that executes bottom halves unless you are holding the iothread
401 * mutex. This makes it mostly useless if you are not holding the mutex.
403 * @bh: The bottom half to be canceled.
405 void qemu_bh_cancel(QEMUBH *bh);
408 *qemu_bh_delete: Cancel execution of a bottom half and free its resources.
410 * Deleting a bottom half frees the memory that was allocated for it by
411 * qemu_bh_new. It also implies canceling the bottom half if it was
412 * scheduled.
413 * This func is async. The bottom half will do the delete action at the finial
414 * end.
416 * @bh: The bottom half to be deleted.
418 void qemu_bh_delete(QEMUBH *bh);
420 /* Return whether there are any pending callbacks from the GSource
421 * attached to the AioContext, before g_poll is invoked.
423 * This is used internally in the implementation of the GSource.
425 bool aio_prepare(AioContext *ctx);
427 /* Return whether there are any pending callbacks from the GSource
428 * attached to the AioContext, after g_poll is invoked.
430 * This is used internally in the implementation of the GSource.
432 bool aio_pending(AioContext *ctx);
434 /* Dispatch any pending callbacks from the GSource attached to the AioContext.
436 * This is used internally in the implementation of the GSource.
438 void aio_dispatch(AioContext *ctx);
440 /* Progress in completing AIO work to occur. This can issue new pending
441 * aio as a result of executing I/O completion or bh callbacks.
443 * Return whether any progress was made by executing AIO or bottom half
444 * handlers. If @blocking == true, this should always be true except
445 * if someone called aio_notify.
447 * If there are no pending bottom halves, but there are pending AIO
448 * operations, it may not be possible to make any progress without
449 * blocking. If @blocking is true, this function will wait until one
450 * or more AIO events have completed, to ensure something has moved
451 * before returning.
453 bool no_coroutine_fn aio_poll(AioContext *ctx, bool blocking);
455 /* Register a file descriptor and associated callbacks. Behaves very similarly
456 * to qemu_set_fd_handler. Unlike qemu_set_fd_handler, these callbacks will
457 * be invoked when using aio_poll().
459 * Code that invokes AIO completion functions should rely on this function
460 * instead of qemu_set_fd_handler[2].
462 void aio_set_fd_handler(AioContext *ctx,
463 int fd,
464 IOHandler *io_read,
465 IOHandler *io_write,
466 AioPollFn *io_poll,
467 IOHandler *io_poll_ready,
468 void *opaque);
470 /* Register an event notifier and associated callbacks. Behaves very similarly
471 * to event_notifier_set_handler. Unlike event_notifier_set_handler, these callbacks
472 * will be invoked when using aio_poll().
474 * Code that invokes AIO completion functions should rely on this function
475 * instead of event_notifier_set_handler.
477 void aio_set_event_notifier(AioContext *ctx,
478 EventNotifier *notifier,
479 EventNotifierHandler *io_read,
480 AioPollFn *io_poll,
481 EventNotifierHandler *io_poll_ready);
484 * Set polling begin/end callbacks for an event notifier that has already been
485 * registered with aio_set_event_notifier. Do nothing if the event notifier is
486 * not registered.
488 * Note that if the io_poll_end() callback (or the entire notifier) is removed
489 * during polling, it will not be called, so an io_poll_begin() is not
490 * necessarily always followed by an io_poll_end().
492 void aio_set_event_notifier_poll(AioContext *ctx,
493 EventNotifier *notifier,
494 EventNotifierHandler *io_poll_begin,
495 EventNotifierHandler *io_poll_end);
497 /* Return a GSource that lets the main loop poll the file descriptors attached
498 * to this AioContext.
500 GSource *aio_get_g_source(AioContext *ctx);
502 /* Return the ThreadPool bound to this AioContext */
503 struct ThreadPool *aio_get_thread_pool(AioContext *ctx);
505 /* Setup the LinuxAioState bound to this AioContext */
506 struct LinuxAioState *aio_setup_linux_aio(AioContext *ctx, Error **errp);
508 /* Return the LinuxAioState bound to this AioContext */
509 struct LinuxAioState *aio_get_linux_aio(AioContext *ctx);
511 /* Setup the LuringState bound to this AioContext */
512 LuringState *aio_setup_linux_io_uring(AioContext *ctx, Error **errp);
514 /* Return the LuringState bound to this AioContext */
515 LuringState *aio_get_linux_io_uring(AioContext *ctx);
517 * aio_timer_new_with_attrs:
518 * @ctx: the aio context
519 * @type: the clock type
520 * @scale: the scale
521 * @attributes: 0, or one to multiple OR'ed QEMU_TIMER_ATTR_<id> values
522 * to assign
523 * @cb: the callback to call on timer expiry
524 * @opaque: the opaque pointer to pass to the callback
526 * Allocate a new timer (with attributes) attached to the context @ctx.
527 * The function is responsible for memory allocation.
529 * The preferred interface is aio_timer_init or aio_timer_init_with_attrs.
530 * Use that unless you really need dynamic memory allocation.
532 * Returns: a pointer to the new timer
534 static inline QEMUTimer *aio_timer_new_with_attrs(AioContext *ctx,
535 QEMUClockType type,
536 int scale, int attributes,
537 QEMUTimerCB *cb, void *opaque)
539 return timer_new_full(&ctx->tlg, type, scale, attributes, cb, opaque);
543 * aio_timer_new:
544 * @ctx: the aio context
545 * @type: the clock type
546 * @scale: the scale
547 * @cb: the callback to call on timer expiry
548 * @opaque: the opaque pointer to pass to the callback
550 * Allocate a new timer attached to the context @ctx.
551 * See aio_timer_new_with_attrs for details.
553 * Returns: a pointer to the new timer
555 static inline QEMUTimer *aio_timer_new(AioContext *ctx, QEMUClockType type,
556 int scale,
557 QEMUTimerCB *cb, void *opaque)
559 return timer_new_full(&ctx->tlg, type, scale, 0, cb, opaque);
563 * aio_timer_init_with_attrs:
564 * @ctx: the aio context
565 * @ts: the timer
566 * @type: the clock type
567 * @scale: the scale
568 * @attributes: 0, or one to multiple OR'ed QEMU_TIMER_ATTR_<id> values
569 * to assign
570 * @cb: the callback to call on timer expiry
571 * @opaque: the opaque pointer to pass to the callback
573 * Initialise a new timer (with attributes) attached to the context @ctx.
574 * The caller is responsible for memory allocation.
576 static inline void aio_timer_init_with_attrs(AioContext *ctx,
577 QEMUTimer *ts, QEMUClockType type,
578 int scale, int attributes,
579 QEMUTimerCB *cb, void *opaque)
581 timer_init_full(ts, &ctx->tlg, type, scale, attributes, cb, opaque);
585 * aio_timer_init:
586 * @ctx: the aio context
587 * @ts: the timer
588 * @type: the clock type
589 * @scale: the scale
590 * @cb: the callback to call on timer expiry
591 * @opaque: the opaque pointer to pass to the callback
593 * Initialise a new timer attached to the context @ctx.
594 * See aio_timer_init_with_attrs for details.
596 static inline void aio_timer_init(AioContext *ctx,
597 QEMUTimer *ts, QEMUClockType type,
598 int scale,
599 QEMUTimerCB *cb, void *opaque)
601 timer_init_full(ts, &ctx->tlg, type, scale, 0, cb, opaque);
605 * aio_compute_timeout:
606 * @ctx: the aio context
608 * Compute the timeout that a blocking aio_poll should use.
610 int64_t aio_compute_timeout(AioContext *ctx);
613 * aio_co_schedule:
614 * @ctx: the aio context
615 * @co: the coroutine
617 * Start a coroutine on a remote AioContext.
619 * The coroutine must not be entered by anyone else while aio_co_schedule()
620 * is active. In addition the coroutine must have yielded unless ctx
621 * is the context in which the coroutine is running (i.e. the value of
622 * qemu_get_current_aio_context() from the coroutine itself).
624 void aio_co_schedule(AioContext *ctx, Coroutine *co);
627 * aio_co_reschedule_self:
628 * @new_ctx: the new context
630 * Move the currently running coroutine to new_ctx. If the coroutine is already
631 * running in new_ctx, do nothing.
633 void coroutine_fn aio_co_reschedule_self(AioContext *new_ctx);
636 * aio_co_wake:
637 * @co: the coroutine
639 * Restart a coroutine on the AioContext where it was running last, thus
640 * preventing coroutines from jumping from one context to another when they
641 * go to sleep.
643 * aio_co_wake may be executed either in coroutine or non-coroutine
644 * context. The coroutine must not be entered by anyone else while
645 * aio_co_wake() is active.
647 void aio_co_wake(Coroutine *co);
650 * aio_co_enter:
651 * @ctx: the context to run the coroutine
652 * @co: the coroutine to run
654 * Enter a coroutine in the specified AioContext.
656 void aio_co_enter(AioContext *ctx, Coroutine *co);
659 * Return the AioContext whose event loop runs in the current thread.
661 * If called from an IOThread this will be the IOThread's AioContext. If
662 * called from the main thread or with the "big QEMU lock" taken it
663 * will be the main loop AioContext.
665 AioContext *qemu_get_current_aio_context(void);
667 void qemu_set_current_aio_context(AioContext *ctx);
670 * aio_context_setup:
671 * @ctx: the aio context
673 * Initialize the aio context.
675 void aio_context_setup(AioContext *ctx);
678 * aio_context_destroy:
679 * @ctx: the aio context
681 * Destroy the aio context.
683 void aio_context_destroy(AioContext *ctx);
685 /* Used internally, do not call outside AioContext code */
686 void aio_context_use_g_source(AioContext *ctx);
689 * aio_context_set_poll_params:
690 * @ctx: the aio context
691 * @max_ns: how long to busy poll for, in nanoseconds
692 * @grow: polling time growth factor
693 * @shrink: polling time shrink factor
695 * Poll mode can be disabled by setting poll_max_ns to 0.
697 void aio_context_set_poll_params(AioContext *ctx, int64_t max_ns,
698 int64_t grow, int64_t shrink,
699 Error **errp);
702 * aio_context_set_aio_params:
703 * @ctx: the aio context
704 * @max_batch: maximum number of requests in a batch, 0 means that the
705 * engine will use its default
707 void aio_context_set_aio_params(AioContext *ctx, int64_t max_batch);
710 * aio_context_set_thread_pool_params:
711 * @ctx: the aio context
712 * @min: min number of threads to have readily available in the thread pool
713 * @min: max number of threads the thread pool can contain
715 void aio_context_set_thread_pool_params(AioContext *ctx, int64_t min,
716 int64_t max, Error **errp);
717 #endif