master
h 855 lines 28.8 KB
Raw
1 /*
2 * QEMU aio implementation
3 *
4 * Copyright IBM, Corp. 2008
5 *
6 * Authors:
7 * Anthony Liguori <aliguori@us.ibm.com>
8 *
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
11 *
12 */
13
14 #ifndef QEMU_AIO_H
15 #define QEMU_AIO_H
16
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/lockcnt.h"
24 #include "qemu/thread.h"
25 #include "qemu/timer.h"
26
27 struct MemReentrancyGuard;
28
29 typedef struct AioHandler AioHandler;
30 typedef QLIST_HEAD(, AioHandler) AioHandlerList;
31 typedef void QEMUBHFunc(void *opaque);
32 typedef bool AioPollFn(void *opaque);
33 typedef void IOHandler(void *opaque);
34
35 struct ThreadPoolAio;
36 struct LinuxAioState;
37 typedef struct LuringState LuringState;
38
39 /* Is polling disabled? */
40 bool aio_poll_disabled(AioContext *ctx);
41
42 #ifdef CONFIG_LINUX_IO_URING
43 /*
44 * Each io_uring request must have a unique CqeHandler that processes the cqe.
45 * The lifetime of a CqeHandler must be at least from aio_add_sqe() until
46 * ->cb() invocation.
47 */
48 typedef struct CqeHandler CqeHandler;
49 struct CqeHandler {
50 /* Called by the AioContext when the request has completed */
51 void (*cb)(CqeHandler *handler);
52
53 /* Used internally, do not access this */
54 QSIMPLEQ_ENTRY(CqeHandler) next;
55
56 /* This field is filled in before ->cb() is called */
57 struct io_uring_cqe cqe;
58 };
59
60 typedef QSIMPLEQ_HEAD(, CqeHandler) CqeHandlerSimpleQ;
61 #endif /* CONFIG_LINUX_IO_URING */
62
63 /* Callbacks for file descriptor monitoring implementations */
64 typedef struct {
65 /*
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
72 *
73 * Add/remove/modify a monitored file descriptor.
74 *
75 * Called with ctx->list_lock acquired.
76 */
77 void (*update)(AioContext *ctx, AioHandler *old_node, AioHandler *new_node);
78
79 /*
80 * wait:
81 * @ctx: the AioContext
82 * @ready_list: list for handlers that become ready
83 * @timeout: maximum duration to wait, in nanoseconds
84 *
85 * Wait for file descriptors to become ready and place them on ready_list.
86 *
87 * Called with ctx->list_lock incremented but not locked.
88 *
89 * Returns: number of ready file descriptors.
90 */
91 int (*wait)(AioContext *ctx, AioHandlerList *ready_list, int64_t timeout);
92
93 /*
94 * need_wait:
95 * @ctx: the AioContext
96 *
97 * Tell aio_poll() when to stop userspace polling early because ->wait()
98 * has fds ready.
99 *
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.
104 *
105 * Returns: true if ->wait() should be called, false otherwise.
106 */
107 bool (*need_wait)(AioContext *ctx);
108
109 /*
110 * dispatch:
111 * @ctx: the AioContext
112 *
113 * Dispatch any work that is specific to this file descriptor monitoring
114 * implementation. Usually the event loop's generic file descriptor
115 * monitoring, BH, and timer dispatching code is sufficient, but file
116 * descriptor monitoring implementations offering additional functionality
117 * may need to implement this function for custom behavior. Called at a
118 * point in the event loop when it is safe to invoke user-defined
119 * callbacks.
120 *
121 * This function is optional and may be NULL.
122 *
123 * Returns: true if progress was made (see aio_poll()'s return value),
124 * false otherwise.
125 */
126 bool (*dispatch)(AioContext *ctx);
127
128 /*
129 * gsource_prepare:
130 * @ctx: the AioContext
131 *
132 * Prepare for the glib event loop to wait for events instead of the usual
133 * ->wait() call. See glib's GSourceFuncs->prepare().
134 */
135 void (*gsource_prepare)(AioContext *ctx);
136
137 /*
138 * gsource_check:
139 * @ctx: the AioContext
140 *
141 * Called by the glib event loop from glib's GSourceFuncs->check() after
142 * waiting for events.
143 *
144 * Returns: true when ready to be dispatched.
145 */
146 bool (*gsource_check)(AioContext *ctx);
147
148 /*
149 * gsource_dispatch:
150 * @ctx: the AioContext
151 * @ready_list: list for handlers that become ready
152 *
153 * Place ready AioHandlers on ready_list. Called as part of the glib event
154 * loop from glib's GSourceFuncs->dispatch().
155 *
156 * Called with list_lock incremented.
157 */
158 void (*gsource_dispatch)(AioContext *ctx, AioHandlerList *ready_list);
159
160 #ifdef CONFIG_LINUX_IO_URING
161 /**
162 * add_sqe: Add an io_uring sqe for submission.
163 * @prep_sqe: invoked with an sqe that should be prepared for submission
164 * @opaque: user-defined argument to @prep_sqe()
165 * @cqe_handler: the unique cqe handler associated with this request
166 *
167 * The caller's @prep_sqe() function is invoked to fill in the details of
168 * the sqe. Do not call io_uring_sqe_set_data() on this sqe.
169 *
170 * The kernel may see the sqe as soon as @prep_sqe() returns or it may take
171 * until the next event loop iteration.
172 *
173 * This function is called from the current AioContext and is not
174 * thread-safe.
175 */
176 void (*add_sqe)(AioContext *ctx,
177 void (*prep_sqe)(struct io_uring_sqe *sqe, void *opaque),
178 void *opaque, CqeHandler *cqe_handler);
179 #endif /* CONFIG_LINUX_IO_URING */
180 } FDMonOps;
181
182 /*
183 * Each aio_bh_poll() call carves off a slice of the BH list, so that newly
184 * scheduled BHs are not processed until the next aio_bh_poll() call. All
185 * active aio_bh_poll() calls chain their slices together in a list, so that
186 * nested aio_bh_poll() calls process all scheduled bottom halves.
187 */
188 typedef QSLIST_HEAD(, QEMUBH) BHList;
189 typedef struct BHListSlice BHListSlice;
190 struct BHListSlice {
191 BHList bh_list;
192 QSIMPLEQ_ENTRY(BHListSlice) next;
193 };
194
195 typedef QSLIST_HEAD(, AioHandler) AioHandlerSList;
196
197 typedef struct AioPolledEvent {
198 int64_t ns; /* estimated block time in nanoseconds */
199 } AioPolledEvent;
200
201 struct AioContext {
202 GSource source;
203
204 /* Used by AioContext users to protect from multi-threaded access. */
205 QemuRecMutex lock;
206
207 /*
208 * Keep track of readers and writers of the block layer graph.
209 * This is essential to avoid performing additions and removal
210 * of nodes and edges from block graph while some
211 * other thread is traversing it.
212 */
213 struct BdrvGraphRWlock *bdrv_graph;
214
215 /* The list of registered AIO handlers. Protected by ctx->list_lock. */
216 AioHandlerList aio_handlers;
217
218 /* The list of AIO handlers to be deleted. Protected by ctx->list_lock. */
219 AioHandlerList deleted_aio_handlers;
220
221 /* Used to avoid unnecessary event_notifier_set calls in aio_notify;
222 * only written from the AioContext home thread, or under the BQL in
223 * the case of the main AioContext. However, it is read from any
224 * thread so it is still accessed with atomic primitives.
225 *
226 * If this field is 0, everything (file descriptors, bottom halves,
227 * timers) will be re-evaluated before the next blocking poll() or
228 * io_uring wait; therefore, the event_notifier_set call can be
229 * skipped. If it is non-zero, you may need to wake up a concurrent
230 * aio_poll or the glib main event loop, making event_notifier_set
231 * necessary.
232 *
233 * Bit 0 is reserved for GSource usage of the AioContext, and is 1
234 * between a call to aio_ctx_prepare and the next call to aio_ctx_check.
235 * Bits 1-31 simply count the number of active calls to aio_poll
236 * that are in the prepare or poll phase.
237 *
238 * The GSource and aio_poll must use a different mechanism because
239 * there is no certainty that a call to GSource's prepare callback
240 * (via g_main_context_prepare) is indeed followed by check and
241 * dispatch. It's not clear whether this would be a bug, but let's
242 * play safe and allow it---it will just cause extra calls to
243 * event_notifier_set until the next call to dispatch.
244 *
245 * Instead, the aio_poll calls include both the prepare and the
246 * dispatch phase, hence a simple counter is enough for them.
247 */
248 uint32_t notify_me;
249
250 /* A lock to protect between QEMUBH and AioHandler adders and deleter,
251 * and to ensure that no callbacks are removed while we're walking and
252 * dispatching them.
253 */
254 QemuLockCnt list_lock;
255
256 /* Bottom Halves pending aio_bh_poll() processing */
257 BHList bh_list;
258
259 /* Chained BH list slices for each nested aio_bh_poll() call */
260 QSIMPLEQ_HEAD(, BHListSlice) bh_slice_list;
261
262 /* Used by aio_notify.
263 *
264 * "notified" is used to avoid expensive event_notifier_test_and_clear
265 * calls. When it is clear, the EventNotifier is clear, or one thread
266 * is going to clear "notified" before processing more events. False
267 * positives are possible, i.e. "notified" could be set even though the
268 * EventNotifier is clear.
269 *
270 * Note that event_notifier_set *cannot* be optimized the same way. For
271 * more information on the problem that would result, see "#ifdef BUG2"
272 * in the docs/aio_notify_accept.promela formal model.
273 */
274 bool notified;
275 EventNotifier notifier;
276
277 QSLIST_HEAD(, Coroutine) scheduled_coroutines;
278 QEMUBH *co_schedule_bh;
279
280 int thread_pool_min;
281 int thread_pool_max;
282 /* Thread pool for performing work and receiving completion callbacks.
283 * Has its own locking.
284 */
285 struct ThreadPoolAio *thread_pool;
286
287 #ifdef CONFIG_LINUX_AIO
288 struct LinuxAioState *linux_aio;
289 #endif
290 #ifdef CONFIG_LINUX_IO_URING
291 /* State for file descriptor monitoring using Linux io_uring */
292 struct io_uring fdmon_io_uring;
293 AioHandlerSList submit_list;
294 void *io_uring_fd_tag;
295
296 /* Pending callback state for cqe handlers */
297 CqeHandlerSimpleQ cqe_handler_ready_list;
298 #endif /* CONFIG_LINUX_IO_URING */
299
300 /* TimerLists for calling timers - one per clock type. Has its own
301 * locking.
302 */
303 QEMUTimerListGroup tlg;
304
305 /* Number of AioHandlers without .io_poll() */
306 int poll_disable_cnt;
307
308 /* Polling mode parameters */
309 int64_t poll_ns; /* current polling time in nanoseconds */
310 int64_t poll_max_ns; /* maximum polling time in nanoseconds */
311 int64_t poll_grow; /* polling time growth factor */
312 int64_t poll_shrink; /* polling time shrink factor */
313 int64_t poll_weight; /* weight of current interval in calculation */
314
315 /* AIO engine parameters */
316 int64_t aio_max_batch; /* maximum number of requests in a batch */
317
318 /*
319 * List of handlers participating in userspace polling. Protected by
320 * ctx->list_lock. Iterated and modified mostly by the event loop thread
321 * from aio_poll() with ctx->list_lock incremented. aio_set_fd_handler()
322 * only touches the list to delete nodes if ctx->list_lock's count is zero.
323 */
324 AioHandlerList poll_aio_handlers;
325
326 /* Are we in polling mode or monitoring file descriptors? */
327 bool poll_started;
328
329 /* epoll(7) state used when built with CONFIG_EPOLL */
330 int epollfd;
331
332 /* The GSource unix fd tag for epollfd */
333 void *epollfd_tag;
334
335 const FDMonOps *fdmon_ops;
336
337 /* Was aio_context_new() successful? */
338 bool initialized;
339 };
340
341 /**
342 * aio_context_new: Allocate a new AioContext.
343 *
344 * AioContext provide a mini event-loop that can be waited on synchronously.
345 * They also provide bottom halves, a service to execute a piece of code
346 * as soon as possible.
347 */
348 AioContext *aio_context_new(Error **errp);
349
350 /**
351 * aio_context_ref:
352 * @ctx: The AioContext to operate on.
353 *
354 * Add a reference to an AioContext.
355 */
356 void aio_context_ref(AioContext *ctx);
357
358 /**
359 * aio_context_unref:
360 * @ctx: The AioContext to operate on.
361 *
362 * Drop a reference to an AioContext.
363 */
364 void aio_context_unref(AioContext *ctx);
365
366 /**
367 * aio_bh_schedule_oneshot_full: Allocate a new bottom half structure that will
368 * run only once and as soon as possible.
369 *
370 * @name: A human-readable identifier for debugging purposes.
371 */
372 void aio_bh_schedule_oneshot_full(AioContext *ctx, QEMUBHFunc *cb, void *opaque,
373 const char *name);
374
375 /**
376 * aio_bh_schedule_oneshot: Allocate a new bottom half structure that will run
377 * only once and as soon as possible.
378 *
379 * A convenience wrapper for aio_bh_schedule_oneshot_full() that uses cb as the
380 * name string.
381 */
382 #define aio_bh_schedule_oneshot(ctx, cb, opaque) \
383 aio_bh_schedule_oneshot_full((ctx), (cb), (opaque), (stringify(cb)))
384
385 /**
386 * aio_bh_new_full: Allocate a new bottom half structure.
387 *
388 * Bottom halves are lightweight callbacks whose invocation is guaranteed
389 * to be wait-free, thread-safe and signal-safe. The #QEMUBH structure
390 * is opaque and must be allocated prior to its use.
391 *
392 * @name: A human-readable identifier for debugging purposes.
393 * @reentrancy_guard: A guard set when entering a cb to prevent
394 * device-reentrancy issues
395 */
396 QEMUBH *aio_bh_new_full(AioContext *ctx, QEMUBHFunc *cb, void *opaque,
397 const char *name, struct MemReentrancyGuard *reentrancy_guard);
398
399 /**
400 * aio_bh_new: Allocate a new bottom half structure
401 *
402 * A convenience wrapper for aio_bh_new_full() that uses the cb as the name
403 * string.
404 */
405 #define aio_bh_new(ctx, cb, opaque) \
406 aio_bh_new_full((ctx), (cb), (opaque), (stringify(cb)), NULL)
407
408 /**
409 * aio_bh_new_guarded: Allocate a new bottom half structure with a
410 * reentrancy_guard
411 *
412 * A convenience wrapper for aio_bh_new_full() that uses the cb as the name
413 * string.
414 */
415 #define aio_bh_new_guarded(ctx, cb, opaque, guard) \
416 aio_bh_new_full((ctx), (cb), (opaque), (stringify(cb)), guard)
417
418 /**
419 * aio_notify: Force processing of pending events.
420 *
421 * Similar to signaling a condition variable, aio_notify forces
422 * aio_poll to exit, so that the next call will re-examine pending events.
423 * The caller of aio_notify will usually call aio_poll again very soon,
424 * or go through another iteration of the GLib main loop. Hence, aio_notify
425 * also has the side effect of recalculating the sets of file descriptors
426 * that the main loop waits for.
427 *
428 * Calling aio_notify is rarely necessary, because for example scheduling
429 * a bottom half calls it already.
430 */
431 void aio_notify(AioContext *ctx);
432
433 /**
434 * aio_notify_accept: Acknowledge receiving an aio_notify.
435 *
436 * aio_notify() uses an EventNotifier in order to wake up a sleeping
437 * aio_poll() or g_main_context_iteration(). Calls to aio_notify() are
438 * usually rare, but the AioContext has to clear the EventNotifier on
439 * every aio_poll() or g_main_context_iteration() in order to avoid
440 * busy waiting. This event_notifier_test_and_clear() cannot be done
441 * using the usual aio_context_set_event_notifier(), because it must
442 * be done before processing all events (file descriptors, bottom halves,
443 * timers).
444 *
445 * aio_notify_accept() is an optimized event_notifier_test_and_clear()
446 * that is specific to an AioContext's notifier; it is used internally
447 * to clear the EventNotifier only if aio_notify() had been called.
448 */
449 void aio_notify_accept(AioContext *ctx);
450
451 /**
452 * aio_bh_call: Executes callback function of the specified BH.
453 */
454 void aio_bh_call(QEMUBH *bh);
455
456 /**
457 * aio_bh_poll: Poll bottom halves for an AioContext.
458 *
459 * These are internal functions used by the QEMU main loop.
460 * And notice that multiple occurrences of aio_bh_poll cannot
461 * be called concurrently
462 */
463 int aio_bh_poll(AioContext *ctx);
464
465 /**
466 * qemu_bh_schedule: Schedule a bottom half.
467 *
468 * Scheduling a bottom half interrupts the main loop and causes the
469 * execution of the callback that was passed to qemu_bh_new.
470 *
471 * Bottom halves that are scheduled from a bottom half handler are instantly
472 * invoked. This can create an infinite loop if a bottom half handler
473 * schedules itself.
474 *
475 * @bh: The bottom half to be scheduled.
476 */
477 void qemu_bh_schedule(QEMUBH *bh);
478
479 /**
480 * qemu_bh_cancel: Cancel execution of a bottom half.
481 *
482 * Canceling execution of a bottom half undoes the effect of calls to
483 * qemu_bh_schedule without freeing its resources yet. While cancellation
484 * itself is also wait-free and thread-safe, it can of course race with the
485 * loop that executes bottom halves unless you are holding the iothread
486 * mutex. This makes it mostly useless if you are not holding the mutex.
487 *
488 * @bh: The bottom half to be canceled.
489 */
490 void qemu_bh_cancel(QEMUBH *bh);
491
492 /**
493 *qemu_bh_delete: Cancel execution of a bottom half and free its resources.
494 *
495 * Deleting a bottom half frees the memory that was allocated for it by
496 * qemu_bh_new. It also implies canceling the bottom half if it was
497 * scheduled.
498 * This func is async. The bottom half will do the delete action at the finial
499 * end.
500 *
501 * @bh: The bottom half to be deleted.
502 */
503 void qemu_bh_delete(QEMUBH *bh);
504
505 /* Return whether there are any pending callbacks from the GSource
506 * attached to the AioContext, before g_poll is invoked.
507 *
508 * This is used internally in the implementation of the GSource.
509 */
510 bool aio_prepare(AioContext *ctx);
511
512 /* Return whether there are any pending callbacks from the GSource
513 * attached to the AioContext, after g_poll is invoked.
514 *
515 * This is used internally in the implementation of the GSource.
516 */
517 bool aio_pending(AioContext *ctx);
518
519 /* Dispatch any pending callbacks from the GSource attached to the AioContext.
520 *
521 * This is used internally in the implementation of the GSource.
522 */
523 void aio_dispatch(AioContext *ctx);
524
525 /* Progress in completing AIO work to occur. This can issue new pending
526 * aio as a result of executing I/O completion or bh callbacks.
527 *
528 * Return whether any progress was made by executing AIO or bottom half
529 * handlers. If @blocking == true, this should always be true except
530 * if someone called aio_notify.
531 *
532 * If there are no pending bottom halves, but there are pending AIO
533 * operations, it may not be possible to make any progress without
534 * blocking. If @blocking is true, this function will wait until one
535 * or more AIO events have completed, to ensure something has moved
536 * before returning.
537 */
538 bool no_coroutine_fn aio_poll(AioContext *ctx, bool blocking);
539
540 /* Register a file descriptor and associated callbacks. Behaves very similarly
541 * to qemu_set_fd_handler. Unlike qemu_set_fd_handler, these callbacks will
542 * be invoked when using aio_poll().
543 *
544 * Code that invokes AIO completion functions should rely on this function
545 * instead of qemu_set_fd_handler[2].
546 */
547 void aio_set_fd_handler(AioContext *ctx,
548 int fd,
549 IOHandler *io_read,
550 IOHandler *io_write,
551 AioPollFn *io_poll,
552 IOHandler *io_poll_ready,
553 void *opaque);
554
555 /* Register an event notifier and associated callbacks. Behaves very similarly
556 * to event_notifier_set_handler. Unlike event_notifier_set_handler, these callbacks
557 * will be invoked when using aio_poll().
558 *
559 * Code that invokes AIO completion functions should rely on this function
560 * instead of event_notifier_set_handler.
561 */
562 void aio_set_event_notifier(AioContext *ctx,
563 EventNotifier *notifier,
564 EventNotifierHandler *io_read,
565 AioPollFn *io_poll,
566 EventNotifierHandler *io_poll_ready);
567
568 /*
569 * Set polling begin/end callbacks for an event notifier that has already been
570 * registered with aio_set_event_notifier. Do nothing if the event notifier is
571 * not registered.
572 *
573 * Note that if the io_poll_end() callback (or the entire notifier) is removed
574 * during polling, it will not be called, so an io_poll_begin() is not
575 * necessarily always followed by an io_poll_end().
576 */
577 void aio_set_event_notifier_poll(AioContext *ctx,
578 EventNotifier *notifier,
579 EventNotifierHandler *io_poll_begin,
580 EventNotifierHandler *io_poll_end);
581
582 /* Return a GSource that lets the main loop poll the file descriptors attached
583 * to this AioContext.
584 */
585 GSource *aio_get_g_source(AioContext *ctx);
586
587 /* Return the ThreadPoolAio bound to this AioContext */
588 struct ThreadPoolAio *aio_get_thread_pool(AioContext *ctx);
589
590 /* Setup the LinuxAioState bound to this AioContext */
591 struct LinuxAioState *aio_setup_linux_aio(AioContext *ctx, Error **errp);
592
593 /* Return the LinuxAioState bound to this AioContext */
594 struct LinuxAioState *aio_get_linux_aio(AioContext *ctx);
595
596 /**
597 * aio_timer_new_with_attrs:
598 * @ctx: the aio context
599 * @type: the clock type
600 * @scale: the scale
601 * @attributes: 0, or one to multiple OR'ed QEMU_TIMER_ATTR_<id> values
602 * to assign
603 * @cb: the callback to call on timer expiry
604 * @opaque: the opaque pointer to pass to the callback
605 *
606 * Allocate a new timer (with attributes) attached to the context @ctx.
607 * The function is responsible for memory allocation.
608 *
609 * The preferred interface is aio_timer_init or aio_timer_init_with_attrs.
610 * Use that unless you really need dynamic memory allocation.
611 *
612 * Returns: a pointer to the new timer
613 */
614 static inline QEMUTimer *aio_timer_new_with_attrs(AioContext *ctx,
615 QEMUClockType type,
616 int scale, int attributes,
617 QEMUTimerCB *cb, void *opaque)
618 {
619 return timer_new_full(&ctx->tlg, type, scale, attributes, cb, opaque);
620 }
621
622 /**
623 * aio_timer_new:
624 * @ctx: the aio context
625 * @type: the clock type
626 * @scale: the scale
627 * @cb: the callback to call on timer expiry
628 * @opaque: the opaque pointer to pass to the callback
629 *
630 * Allocate a new timer attached to the context @ctx.
631 * See aio_timer_new_with_attrs for details.
632 *
633 * Returns: a pointer to the new timer
634 */
635 static inline QEMUTimer *aio_timer_new(AioContext *ctx, QEMUClockType type,
636 int scale,
637 QEMUTimerCB *cb, void *opaque)
638 {
639 return timer_new_full(&ctx->tlg, type, scale, 0, cb, opaque);
640 }
641
642 /**
643 * aio_timer_init_with_attrs:
644 * @ctx: the aio context
645 * @ts: the timer
646 * @type: the clock type
647 * @scale: the scale
648 * @attributes: 0, or one to multiple OR'ed QEMU_TIMER_ATTR_<id> values
649 * to assign
650 * @cb: the callback to call on timer expiry
651 * @opaque: the opaque pointer to pass to the callback
652 *
653 * Initialise a new timer (with attributes) attached to the context @ctx.
654 * The caller is responsible for memory allocation.
655 */
656 static inline void aio_timer_init_with_attrs(AioContext *ctx,
657 QEMUTimer *ts, QEMUClockType type,
658 int scale, int attributes,
659 QEMUTimerCB *cb, void *opaque)
660 {
661 timer_init_full(ts, &ctx->tlg, type, scale, attributes, cb, opaque);
662 }
663
664 /**
665 * aio_timer_init:
666 * @ctx: the aio context
667 * @ts: the timer
668 * @type: the clock type
669 * @scale: the scale
670 * @cb: the callback to call on timer expiry
671 * @opaque: the opaque pointer to pass to the callback
672 *
673 * Initialise a new timer attached to the context @ctx.
674 * See aio_timer_init_with_attrs for details.
675 */
676 static inline void aio_timer_init(AioContext *ctx,
677 QEMUTimer *ts, QEMUClockType type,
678 int scale,
679 QEMUTimerCB *cb, void *opaque)
680 {
681 timer_init_full(ts, &ctx->tlg, type, scale, 0, cb, opaque);
682 }
683
684 /**
685 * aio_compute_timeout:
686 * @ctx: the aio context
687 *
688 * Compute the timeout that a blocking aio_poll should use.
689 */
690 int64_t aio_compute_timeout(AioContext *ctx);
691
692 /**
693 * aio_co_schedule:
694 * @ctx: the aio context
695 * @co: the coroutine
696 *
697 * Start a coroutine on a remote AioContext.
698 *
699 * The coroutine must not be entered by anyone else while aio_co_schedule()
700 * is active. In addition the coroutine must have yielded unless ctx
701 * is the context in which the coroutine is running (i.e. the value of
702 * qemu_get_current_aio_context() from the coroutine itself).
703 */
704 void aio_co_schedule(AioContext *ctx, Coroutine *co);
705
706 /**
707 * aio_co_reschedule_self:
708 * @new_ctx: the new context
709 *
710 * Move the currently running coroutine to new_ctx. If the coroutine is already
711 * running in new_ctx, do nothing.
712 *
713 * Note that this function cannot reschedule from iohandler_ctx to
714 * qemu_aio_context.
715 */
716 void coroutine_fn aio_co_reschedule_self(AioContext *new_ctx);
717
718 /**
719 * aio_co_wake:
720 * @co: the coroutine
721 *
722 * Restart a coroutine on the AioContext where it was running last, thus
723 * preventing coroutines from jumping from one context to another when they
724 * go to sleep.
725 *
726 * aio_co_wake may be executed either in coroutine or non-coroutine
727 * context. The coroutine must not be entered by anyone else while
728 * aio_co_wake() is active.
729 *
730 * If `co`'s AioContext differs from the current AioContext, this will call
731 * aio_co_schedule(), which makes this safe to use even when `co` has not
732 * yielded yet. In such a case, it will be entered once it yields.
733 *
734 * In contrast, if `co`'s AioContext is equal to the current one, it is
735 * required for `co` to currently be yielding. This is generally the case
736 * if the caller is not in `co` (i.e. invoked by `co`), because the only
737 * other way for the caller to be running then is for `co` to currently be
738 * yielding.
739 *
740 * Therefore, if there is no way for the caller to be invoked/entered by
741 * `co`, it is generally safe to call this regardless of whether `co` is
742 * known to already be yielding or not -- it only has to yield at some
743 * point.
744 */
745 void aio_co_wake(Coroutine *co);
746
747 /**
748 * aio_co_enter:
749 * @ctx: the context to run the coroutine
750 * @co: the coroutine to run
751 *
752 * Enter a coroutine in the specified AioContext.
753 */
754 void aio_co_enter(AioContext *ctx, Coroutine *co);
755
756 /**
757 * Return the AioContext whose event loop runs in the current thread.
758 *
759 * If called from an IOThread this will be the IOThread's AioContext. If
760 * called from the main thread or with the "big QEMU lock" taken it
761 * will be the main loop AioContext.
762 *
763 * Note that the return value is never the main loop's iohandler_ctx and the
764 * return value is the main loop AioContext instead.
765 */
766 AioContext *qemu_get_current_aio_context(void);
767
768 void qemu_set_current_aio_context(AioContext *ctx);
769
770 /**
771 * aio_context_setup:
772 * @ctx: the aio context
773 * @errp: error pointer
774 *
775 * Initialize the aio context.
776 *
777 * Returns: true on success, false otherwise
778 */
779 bool aio_context_setup(AioContext *ctx, Error **errp);
780
781 /**
782 * aio_context_destroy:
783 * @ctx: the aio context
784 *
785 * Destroy the aio context.
786 */
787 void aio_context_destroy(AioContext *ctx);
788
789 /**
790 * aio_context_set_poll_params:
791 * @ctx: the aio context
792 * @max_ns: how long to busy poll for, in nanoseconds
793 * @grow: polling time growth factor
794 * @shrink: polling time shrink factor
795 * @weight: weight factor applied to the current polling interval
796 *
797 * Poll mode can be disabled by setting poll_max_ns to 0.
798 */
799 void aio_context_set_poll_params(AioContext *ctx, int64_t max_ns,
800 int64_t grow, int64_t shrink,
801 int64_t weight, Error **errp);
802
803 /**
804 * aio_context_set_aio_params:
805 * @ctx: the aio context
806 * @max_batch: maximum number of requests in a batch, 0 means that the
807 * engine will use its default
808 */
809 void aio_context_set_aio_params(AioContext *ctx, int64_t max_batch);
810
811 /**
812 * aio_context_set_thread_pool_params:
813 * @ctx: the aio context
814 * @min: min number of threads to have readily available in the thread pool
815 * @min: max number of threads the thread pool can contain
816 */
817 void aio_context_set_thread_pool_params(AioContext *ctx, int64_t min,
818 int64_t max, Error **errp);
819
820 #ifdef CONFIG_LINUX_IO_URING
821 /**
822 * aio_has_io_uring: Return whether io_uring is available.
823 *
824 * io_uring is either available in all AioContexts or in none, so this only
825 * needs to be called once from within any thread's AioContext.
826 */
827 static inline bool aio_has_io_uring(void)
828 {
829 AioContext *ctx = qemu_get_current_aio_context();
830 return ctx->fdmon_ops->add_sqe;
831 }
832
833 /**
834 * aio_add_sqe: Add an io_uring sqe for submission.
835 * @prep_sqe: invoked with an sqe that should be prepared for submission
836 * @opaque: user-defined argument to @prep_sqe()
837 * @cqe_handler: the unique cqe handler associated with this request
838 *
839 * The caller's @prep_sqe() function is invoked to fill in the details of the
840 * sqe. Do not call io_uring_sqe_set_data() on this sqe.
841 *
842 * The sqe is submitted by the current AioContext. The kernel may see the sqe
843 * as soon as @prep_sqe() returns or it may take until the next event loop
844 * iteration.
845 *
846 * When the AioContext is destroyed, pending sqes are ignored and their
847 * CqeHandlers are not invoked.
848 *
849 * This function must be called only when aio_has_io_uring() returns true.
850 */
851 void aio_add_sqe(void (*prep_sqe)(struct io_uring_sqe *sqe, void *opaque),
852 void *opaque, CqeHandler *cqe_handler);
853 #endif /* CONFIG_LINUX_IO_URING */
854
855 #endif