2 * QEMU aio implementation
4 * Copyright IBM, Corp. 2008
9 * This work is licensed under the terms of the GNU GPL, version 2. See
10 * the COPYING file in the top-level directory.
12 * Contributions after 2012-01-13 are licensed under the terms of the
13 * GNU GPL, version 2 or (at your option) any later version.
16 #include "qemu/osdep.h"
17 #include "qemu-common.h"
18 #include "block/block.h"
19 #include "qemu/rcu_queue.h"
20 #include "qemu/sockets.h"
21 #include "qemu/cutils.h"
23 #ifdef CONFIG_EPOLL_CREATE1
24 #include <sys/epoll.h>
33 IOHandler *io_poll_begin;
34 IOHandler *io_poll_end;
38 QLIST_ENTRY(AioHandler) node;
41 #ifdef CONFIG_EPOLL_CREATE1
43 /* The fd number threshold to switch to epoll */
44 #define EPOLL_ENABLE_THRESHOLD 64
46 static void aio_epoll_disable(AioContext *ctx)
48 ctx->epoll_enabled = false;
49 if (!ctx->epoll_available) {
52 ctx->epoll_available = false;
56 static inline int epoll_events_from_pfd(int pfd_events)
58 return (pfd_events & G_IO_IN ? EPOLLIN : 0) |
59 (pfd_events & G_IO_OUT ? EPOLLOUT : 0) |
60 (pfd_events & G_IO_HUP ? EPOLLHUP : 0) |
61 (pfd_events & G_IO_ERR ? EPOLLERR : 0);
64 static bool aio_epoll_try_enable(AioContext *ctx)
67 struct epoll_event event;
69 QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {
71 if (node->deleted || !node->pfd.events) {
74 event.events = epoll_events_from_pfd(node->pfd.events);
75 event.data.ptr = node;
76 r = epoll_ctl(ctx->epollfd, EPOLL_CTL_ADD, node->pfd.fd, &event);
81 ctx->epoll_enabled = true;
85 static void aio_epoll_update(AioContext *ctx, AioHandler *node, bool is_new)
87 struct epoll_event event;
91 if (!ctx->epoll_enabled) {
94 if (!node->pfd.events) {
97 event.data.ptr = node;
98 event.events = epoll_events_from_pfd(node->pfd.events);
99 ctl = is_new ? EPOLL_CTL_ADD : EPOLL_CTL_MOD;
102 r = epoll_ctl(ctx->epollfd, ctl, node->pfd.fd, &event);
104 aio_epoll_disable(ctx);
108 static int aio_epoll(AioContext *ctx, GPollFD *pfds,
109 unsigned npfd, int64_t timeout)
113 struct epoll_event events[128];
116 assert(pfds[0].fd == ctx->epollfd);
118 ret = qemu_poll_ns(pfds, npfd, timeout);
120 if (timeout <= 0 || ret > 0) {
121 ret = epoll_wait(ctx->epollfd, events,
127 for (i = 0; i < ret; i++) {
128 int ev = events[i].events;
129 node = events[i].data.ptr;
130 node->pfd.revents = (ev & EPOLLIN ? G_IO_IN : 0) |
131 (ev & EPOLLOUT ? G_IO_OUT : 0) |
132 (ev & EPOLLHUP ? G_IO_HUP : 0) |
133 (ev & EPOLLERR ? G_IO_ERR : 0);
140 static bool aio_epoll_enabled(AioContext *ctx)
142 /* Fall back to ppoll when external clients are disabled. */
143 return !aio_external_disabled(ctx) && ctx->epoll_enabled;
146 static bool aio_epoll_check_poll(AioContext *ctx, GPollFD *pfds,
147 unsigned npfd, int64_t timeout)
149 if (!ctx->epoll_available) {
152 if (aio_epoll_enabled(ctx)) {
155 if (npfd >= EPOLL_ENABLE_THRESHOLD) {
156 if (aio_epoll_try_enable(ctx)) {
159 aio_epoll_disable(ctx);
167 static void aio_epoll_update(AioContext *ctx, AioHandler *node, bool is_new)
171 static int aio_epoll(AioContext *ctx, GPollFD *pfds,
172 unsigned npfd, int64_t timeout)
177 static bool aio_epoll_enabled(AioContext *ctx)
182 static bool aio_epoll_check_poll(AioContext *ctx, GPollFD *pfds,
183 unsigned npfd, int64_t timeout)
190 static AioHandler *find_aio_handler(AioContext *ctx, int fd)
194 QLIST_FOREACH(node, &ctx->aio_handlers, node) {
195 if (node->pfd.fd == fd)
203 void aio_set_fd_handler(AioContext *ctx,
213 bool deleted = false;
214 int poll_disable_change;
216 qemu_lockcnt_lock(&ctx->list_lock);
218 node = find_aio_handler(ctx, fd);
220 /* Are we deleting the fd handler? */
221 if (!io_read && !io_write && !io_poll) {
223 qemu_lockcnt_unlock(&ctx->list_lock);
227 /* If the GSource is in the process of being destroyed then
228 * g_source_remove_poll() causes an assertion failure. Skip
229 * removal in that case, because glib cleans up its state during
230 * destruction anyway.
232 if (!g_source_is_destroyed(&ctx->source)) {
233 g_source_remove_poll(&ctx->source, &node->pfd);
236 /* If a read is in progress, just mark the node as deleted */
237 if (qemu_lockcnt_count(&ctx->list_lock)) {
239 node->pfd.revents = 0;
241 /* Otherwise, delete it for real. We can't just mark it as
242 * deleted because deleted nodes are only cleaned up while
243 * no one is walking the handlers list.
245 QLIST_REMOVE(node, node);
248 /* Clean events in order to unregister fd from the ctx epoll. */
249 node->pfd.events = 0;
251 poll_disable_change = -!node->io_poll;
253 poll_disable_change = !io_poll - (node && !node->io_poll);
255 /* Alloc and insert if it's not already there */
256 node = g_new0(AioHandler, 1);
258 QLIST_INSERT_HEAD_RCU(&ctx->aio_handlers, node, node);
260 g_source_add_poll(&ctx->source, &node->pfd);
264 /* Update handler with latest information */
265 node->io_read = io_read;
266 node->io_write = io_write;
267 node->io_poll = io_poll;
268 node->opaque = opaque;
269 node->is_external = is_external;
271 node->pfd.events = (io_read ? G_IO_IN | G_IO_HUP | G_IO_ERR : 0);
272 node->pfd.events |= (io_write ? G_IO_OUT | G_IO_ERR : 0);
275 /* No need to order poll_disable_cnt writes against other updates;
276 * the counter is only used to avoid wasting time and latency on
277 * iterated polling when the system call will be ultimately necessary.
278 * Changing handlers is a rare event, and a little wasted polling until
279 * the aio_notify below is not an issue.
281 atomic_set(&ctx->poll_disable_cnt,
282 atomic_read(&ctx->poll_disable_cnt) + poll_disable_change);
284 aio_epoll_update(ctx, node, is_new);
285 qemu_lockcnt_unlock(&ctx->list_lock);
293 void aio_set_fd_poll(AioContext *ctx, int fd,
294 IOHandler *io_poll_begin,
295 IOHandler *io_poll_end)
297 AioHandler *node = find_aio_handler(ctx, fd);
303 node->io_poll_begin = io_poll_begin;
304 node->io_poll_end = io_poll_end;
307 void aio_set_event_notifier(AioContext *ctx,
308 EventNotifier *notifier,
310 EventNotifierHandler *io_read,
313 aio_set_fd_handler(ctx, event_notifier_get_fd(notifier), is_external,
314 (IOHandler *)io_read, NULL, io_poll, notifier);
317 void aio_set_event_notifier_poll(AioContext *ctx,
318 EventNotifier *notifier,
319 EventNotifierHandler *io_poll_begin,
320 EventNotifierHandler *io_poll_end)
322 aio_set_fd_poll(ctx, event_notifier_get_fd(notifier),
323 (IOHandler *)io_poll_begin,
324 (IOHandler *)io_poll_end);
327 static void poll_set_started(AioContext *ctx, bool started)
331 if (started == ctx->poll_started) {
335 ctx->poll_started = started;
337 qemu_lockcnt_inc(&ctx->list_lock);
338 QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {
346 fn = node->io_poll_begin;
348 fn = node->io_poll_end;
355 qemu_lockcnt_dec(&ctx->list_lock);
359 bool aio_prepare(AioContext *ctx)
361 /* Poll mode cannot be used with glib's event loop, disable it. */
362 poll_set_started(ctx, false);
367 bool aio_pending(AioContext *ctx)
373 * We have to walk very carefully in case aio_set_fd_handler is
374 * called while we're walking.
376 qemu_lockcnt_inc(&ctx->list_lock);
378 QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {
381 revents = node->pfd.revents & node->pfd.events;
382 if (revents & (G_IO_IN | G_IO_HUP | G_IO_ERR) && node->io_read &&
383 aio_node_check(ctx, node->is_external)) {
387 if (revents & (G_IO_OUT | G_IO_ERR) && node->io_write &&
388 aio_node_check(ctx, node->is_external)) {
393 qemu_lockcnt_dec(&ctx->list_lock);
398 static bool aio_dispatch_handlers(AioContext *ctx)
400 AioHandler *node, *tmp;
401 bool progress = false;
403 QLIST_FOREACH_SAFE_RCU(node, &ctx->aio_handlers, node, tmp) {
406 revents = node->pfd.revents & node->pfd.events;
407 node->pfd.revents = 0;
409 if (!node->deleted &&
410 (revents & (G_IO_IN | G_IO_HUP | G_IO_ERR)) &&
411 aio_node_check(ctx, node->is_external) &&
413 node->io_read(node->opaque);
415 /* aio_notify() does not count as progress */
416 if (node->opaque != &ctx->notifier) {
420 if (!node->deleted &&
421 (revents & (G_IO_OUT | G_IO_ERR)) &&
422 aio_node_check(ctx, node->is_external) &&
424 node->io_write(node->opaque);
429 if (qemu_lockcnt_dec_if_lock(&ctx->list_lock)) {
430 QLIST_REMOVE(node, node);
432 qemu_lockcnt_inc_and_unlock(&ctx->list_lock);
440 void aio_dispatch(AioContext *ctx)
442 qemu_lockcnt_inc(&ctx->list_lock);
444 aio_dispatch_handlers(ctx);
445 qemu_lockcnt_dec(&ctx->list_lock);
447 timerlistgroup_run_timers(&ctx->tlg);
450 /* These thread-local variables are used only in a small part of aio_poll
451 * around the call to the poll() system call. In particular they are not
452 * used while aio_poll is performing callbacks, which makes it much easier
453 * to think about reentrancy!
455 * Stack-allocated arrays would be perfect but they have size limitations;
456 * heap allocation is expensive enough that we want to reuse arrays across
457 * calls to aio_poll(). And because poll() has to be called without holding
458 * any lock, the arrays cannot be stored in AioContext. Thread-local data
459 * has none of the disadvantages of these three options.
461 static __thread GPollFD *pollfds;
462 static __thread AioHandler **nodes;
463 static __thread unsigned npfd, nalloc;
464 static __thread Notifier pollfds_cleanup_notifier;
466 static void pollfds_cleanup(Notifier *n, void *unused)
474 static void add_pollfd(AioHandler *node)
476 if (npfd == nalloc) {
478 pollfds_cleanup_notifier.notify = pollfds_cleanup;
479 qemu_thread_atexit_add(&pollfds_cleanup_notifier);
482 g_assert(nalloc <= INT_MAX);
485 pollfds = g_renew(GPollFD, pollfds, nalloc);
486 nodes = g_renew(AioHandler *, nodes, nalloc);
489 pollfds[npfd] = (GPollFD) {
491 .events = node->pfd.events,
496 static bool run_poll_handlers_once(AioContext *ctx, int64_t *timeout)
498 bool progress = false;
501 QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {
502 if (!node->deleted && node->io_poll &&
503 aio_node_check(ctx, node->is_external) &&
504 node->io_poll(node->opaque)) {
506 if (node->opaque != &ctx->notifier) {
511 /* Caller handles freeing deleted nodes. Don't do it here. */
517 /* run_poll_handlers:
518 * @ctx: the AioContext
519 * @max_ns: maximum time to poll for, in nanoseconds
521 * Polls for a given time.
523 * Note that ctx->notify_me must be non-zero so this function can detect
526 * Note that the caller must have incremented ctx->list_lock.
528 * Returns: true if progress was made, false otherwise
530 static bool run_poll_handlers(AioContext *ctx, int64_t max_ns, int64_t *timeout)
533 int64_t start_time, elapsed_time;
535 assert(ctx->notify_me);
536 assert(qemu_lockcnt_count(&ctx->list_lock) > 0);
538 trace_run_poll_handlers_begin(ctx, max_ns, *timeout);
540 start_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
542 progress = run_poll_handlers_once(ctx, timeout);
543 elapsed_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - start_time;
544 } while (!progress && elapsed_time < max_ns
545 && !atomic_read(&ctx->poll_disable_cnt));
547 /* If time has passed with no successful polling, adjust *timeout to
548 * keep the same ending time.
550 if (*timeout != -1) {
551 *timeout -= MIN(*timeout, elapsed_time);
554 trace_run_poll_handlers_end(ctx, progress, *timeout);
559 * @ctx: the AioContext
560 * @timeout: timeout for blocking wait, computed by the caller and updated if
563 * ctx->notify_me must be non-zero so this function can detect aio_notify().
565 * Note that the caller must have incremented ctx->list_lock.
567 * Returns: true if progress was made, false otherwise
569 static bool try_poll_mode(AioContext *ctx, int64_t *timeout)
571 /* See qemu_soonest_timeout() uint64_t hack */
572 int64_t max_ns = MIN((uint64_t)*timeout, (uint64_t)ctx->poll_ns);
574 if (max_ns && !atomic_read(&ctx->poll_disable_cnt)) {
575 poll_set_started(ctx, true);
577 if (run_poll_handlers(ctx, max_ns, timeout)) {
582 poll_set_started(ctx, false);
584 /* Even if we don't run busy polling, try polling once in case it can make
585 * progress and the caller will be able to avoid ppoll(2)/epoll_wait(2).
587 return run_poll_handlers_once(ctx, timeout);
590 bool aio_poll(AioContext *ctx, bool blocking)
599 /* aio_notify can avoid the expensive event_notifier_set if
600 * everything (file descriptors, bottom halves, timers) will
601 * be re-evaluated before the next blocking poll(). This is
602 * already true when aio_poll is called with blocking == false;
603 * if blocking == true, it is only true after poll() returns,
604 * so disable the optimization now.
607 assert(in_aio_context_home_thread(ctx));
608 atomic_add(&ctx->notify_me, 2);
611 qemu_lockcnt_inc(&ctx->list_lock);
613 if (ctx->poll_max_ns) {
614 start = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
617 timeout = blocking ? aio_compute_timeout(ctx) : 0;
618 progress = try_poll_mode(ctx, &timeout);
619 assert(!(timeout && progress));
621 /* If polling is allowed, non-blocking aio_poll does not need the
622 * system call---a single round of run_poll_handlers_once suffices.
624 if (timeout || atomic_read(&ctx->poll_disable_cnt)) {
629 if (!aio_epoll_enabled(ctx)) {
630 QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {
631 if (!node->deleted && node->pfd.events
632 && aio_node_check(ctx, node->is_external)) {
638 /* wait until next event */
639 if (aio_epoll_check_poll(ctx, pollfds, npfd, timeout)) {
640 AioHandler epoll_handler;
642 epoll_handler.pfd.fd = ctx->epollfd;
643 epoll_handler.pfd.events = G_IO_IN | G_IO_OUT | G_IO_HUP | G_IO_ERR;
645 add_pollfd(&epoll_handler);
646 ret = aio_epoll(ctx, pollfds, npfd, timeout);
648 ret = qemu_poll_ns(pollfds, npfd, timeout);
653 atomic_sub(&ctx->notify_me, 2);
654 aio_notify_accept(ctx);
657 /* Adjust polling time */
658 if (ctx->poll_max_ns) {
659 int64_t block_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - start;
661 if (block_ns <= ctx->poll_ns) {
662 /* This is the sweet spot, no adjustment needed */
663 } else if (block_ns > ctx->poll_max_ns) {
664 /* We'd have to poll for too long, poll less */
665 int64_t old = ctx->poll_ns;
667 if (ctx->poll_shrink) {
668 ctx->poll_ns /= ctx->poll_shrink;
673 trace_poll_shrink(ctx, old, ctx->poll_ns);
674 } else if (ctx->poll_ns < ctx->poll_max_ns &&
675 block_ns < ctx->poll_max_ns) {
676 /* There is room to grow, poll longer */
677 int64_t old = ctx->poll_ns;
678 int64_t grow = ctx->poll_grow;
685 ctx->poll_ns *= grow;
687 ctx->poll_ns = 4000; /* start polling at 4 microseconds */
690 if (ctx->poll_ns > ctx->poll_max_ns) {
691 ctx->poll_ns = ctx->poll_max_ns;
694 trace_poll_grow(ctx, old, ctx->poll_ns);
698 /* if we have any readable fds, dispatch event */
700 for (i = 0; i < npfd; i++) {
701 nodes[i]->pfd.revents = pollfds[i].revents;
707 progress |= aio_bh_poll(ctx);
710 progress |= aio_dispatch_handlers(ctx);
713 qemu_lockcnt_dec(&ctx->list_lock);
715 progress |= timerlistgroup_run_timers(&ctx->tlg);
720 void aio_context_setup(AioContext *ctx)
722 #ifdef CONFIG_EPOLL_CREATE1
723 assert(!ctx->epollfd);
724 ctx->epollfd = epoll_create1(EPOLL_CLOEXEC);
725 if (ctx->epollfd == -1) {
726 fprintf(stderr, "Failed to create epoll instance: %s", strerror(errno));
727 ctx->epoll_available = false;
729 ctx->epoll_available = true;
734 void aio_context_destroy(AioContext *ctx)
736 #ifdef CONFIG_EPOLL_CREATE1
737 aio_epoll_disable(ctx);
741 void aio_context_set_poll_params(AioContext *ctx, int64_t max_ns,
742 int64_t grow, int64_t shrink, Error **errp)
744 /* No thread synchronization here, it doesn't matter if an incorrect value
747 ctx->poll_max_ns = max_ns;
749 ctx->poll_grow = grow;
750 ctx->poll_shrink = shrink;