vhost-scsi: unify vhost-scsi get_features implementations
[qemu/ar7.git] / util / aio-posix.c
blob131ba6b4a81b1b1617a3a6825f110991eab736c1
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.
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"
22 #include "trace.h"
23 #ifdef CONFIG_EPOLL_CREATE1
24 #include <sys/epoll.h>
25 #endif
27 struct AioHandler
29 GPollFD pfd;
30 IOHandler *io_read;
31 IOHandler *io_write;
32 AioPollFn *io_poll;
33 IOHandler *io_poll_begin;
34 IOHandler *io_poll_end;
35 int deleted;
36 void *opaque;
37 bool is_external;
38 QLIST_ENTRY(AioHandler) node;
41 #ifdef CONFIG_EPOLL_CREATE1
43 /* The fd number threashold 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) {
50 return;
52 ctx->epoll_available = false;
53 close(ctx->epollfd);
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)
66 AioHandler *node;
67 struct epoll_event event;
69 QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {
70 int r;
71 if (node->deleted || !node->pfd.events) {
72 continue;
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);
77 if (r) {
78 return false;
81 ctx->epoll_enabled = true;
82 return true;
85 static void aio_epoll_update(AioContext *ctx, AioHandler *node, bool is_new)
87 struct epoll_event event;
88 int r;
89 int ctl;
91 if (!ctx->epoll_enabled) {
92 return;
94 if (!node->pfd.events) {
95 ctl = EPOLL_CTL_DEL;
96 } else {
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);
103 if (r) {
104 aio_epoll_disable(ctx);
108 static int aio_epoll(AioContext *ctx, GPollFD *pfds,
109 unsigned npfd, int64_t timeout)
111 AioHandler *node;
112 int i, ret = 0;
113 struct epoll_event events[128];
115 assert(npfd == 1);
116 assert(pfds[0].fd == ctx->epollfd);
117 if (timeout > 0) {
118 ret = qemu_poll_ns(pfds, npfd, timeout);
120 if (timeout <= 0 || ret > 0) {
121 ret = epoll_wait(ctx->epollfd, events,
122 ARRAY_SIZE(events),
123 timeout);
124 if (ret <= 0) {
125 goto out;
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);
136 out:
137 return ret;
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) {
150 return false;
152 if (aio_epoll_enabled(ctx)) {
153 return true;
155 if (npfd >= EPOLL_ENABLE_THRESHOLD) {
156 if (aio_epoll_try_enable(ctx)) {
157 return true;
158 } else {
159 aio_epoll_disable(ctx);
162 return false;
165 #else
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)
174 assert(false);
177 static bool aio_epoll_enabled(AioContext *ctx)
179 return false;
182 static bool aio_epoll_check_poll(AioContext *ctx, GPollFD *pfds,
183 unsigned npfd, int64_t timeout)
185 return false;
188 #endif
190 static AioHandler *find_aio_handler(AioContext *ctx, int fd)
192 AioHandler *node;
194 QLIST_FOREACH(node, &ctx->aio_handlers, node) {
195 if (node->pfd.fd == fd)
196 if (!node->deleted)
197 return node;
200 return NULL;
203 void aio_set_fd_handler(AioContext *ctx,
204 int fd,
205 bool is_external,
206 IOHandler *io_read,
207 IOHandler *io_write,
208 AioPollFn *io_poll,
209 void *opaque)
211 AioHandler *node;
212 bool is_new = false;
213 bool deleted = false;
215 qemu_lockcnt_lock(&ctx->list_lock);
217 node = find_aio_handler(ctx, fd);
219 /* Are we deleting the fd handler? */
220 if (!io_read && !io_write && !io_poll) {
221 if (node == NULL) {
222 qemu_lockcnt_unlock(&ctx->list_lock);
223 return;
226 /* If the GSource is in the process of being destroyed then
227 * g_source_remove_poll() causes an assertion failure. Skip
228 * removal in that case, because glib cleans up its state during
229 * destruction anyway.
231 if (!g_source_is_destroyed(&ctx->source)) {
232 g_source_remove_poll(&ctx->source, &node->pfd);
235 /* If a read is in progress, just mark the node as deleted */
236 if (qemu_lockcnt_count(&ctx->list_lock)) {
237 node->deleted = 1;
238 node->pfd.revents = 0;
239 } else {
240 /* Otherwise, delete it for real. We can't just mark it as
241 * deleted because deleted nodes are only cleaned up while
242 * no one is walking the handlers list.
244 QLIST_REMOVE(node, node);
245 deleted = true;
248 if (!node->io_poll) {
249 ctx->poll_disable_cnt--;
251 } else {
252 if (node == NULL) {
253 /* Alloc and insert if it's not already there */
254 node = g_new0(AioHandler, 1);
255 node->pfd.fd = fd;
256 QLIST_INSERT_HEAD_RCU(&ctx->aio_handlers, node, node);
258 g_source_add_poll(&ctx->source, &node->pfd);
259 is_new = true;
261 ctx->poll_disable_cnt += !io_poll;
262 } else {
263 ctx->poll_disable_cnt += !io_poll - !node->io_poll;
266 /* Update handler with latest information */
267 node->io_read = io_read;
268 node->io_write = io_write;
269 node->io_poll = io_poll;
270 node->opaque = opaque;
271 node->is_external = is_external;
273 node->pfd.events = (io_read ? G_IO_IN | G_IO_HUP | G_IO_ERR : 0);
274 node->pfd.events |= (io_write ? G_IO_OUT | G_IO_ERR : 0);
277 aio_epoll_update(ctx, node, is_new);
278 qemu_lockcnt_unlock(&ctx->list_lock);
279 aio_notify(ctx);
281 if (deleted) {
282 g_free(node);
286 void aio_set_fd_poll(AioContext *ctx, int fd,
287 IOHandler *io_poll_begin,
288 IOHandler *io_poll_end)
290 AioHandler *node = find_aio_handler(ctx, fd);
292 if (!node) {
293 return;
296 node->io_poll_begin = io_poll_begin;
297 node->io_poll_end = io_poll_end;
300 void aio_set_event_notifier(AioContext *ctx,
301 EventNotifier *notifier,
302 bool is_external,
303 EventNotifierHandler *io_read,
304 AioPollFn *io_poll)
306 aio_set_fd_handler(ctx, event_notifier_get_fd(notifier), is_external,
307 (IOHandler *)io_read, NULL, io_poll, notifier);
310 void aio_set_event_notifier_poll(AioContext *ctx,
311 EventNotifier *notifier,
312 EventNotifierHandler *io_poll_begin,
313 EventNotifierHandler *io_poll_end)
315 aio_set_fd_poll(ctx, event_notifier_get_fd(notifier),
316 (IOHandler *)io_poll_begin,
317 (IOHandler *)io_poll_end);
320 static void poll_set_started(AioContext *ctx, bool started)
322 AioHandler *node;
324 if (started == ctx->poll_started) {
325 return;
328 ctx->poll_started = started;
330 qemu_lockcnt_inc(&ctx->list_lock);
331 QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {
332 IOHandler *fn;
334 if (node->deleted) {
335 continue;
338 if (started) {
339 fn = node->io_poll_begin;
340 } else {
341 fn = node->io_poll_end;
344 if (fn) {
345 fn(node->opaque);
348 qemu_lockcnt_dec(&ctx->list_lock);
352 bool aio_prepare(AioContext *ctx)
354 /* Poll mode cannot be used with glib's event loop, disable it. */
355 poll_set_started(ctx, false);
357 return false;
360 bool aio_pending(AioContext *ctx)
362 AioHandler *node;
363 bool result = false;
366 * We have to walk very carefully in case aio_set_fd_handler is
367 * called while we're walking.
369 qemu_lockcnt_inc(&ctx->list_lock);
371 QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {
372 int revents;
374 revents = node->pfd.revents & node->pfd.events;
375 if (revents & (G_IO_IN | G_IO_HUP | G_IO_ERR) && node->io_read &&
376 aio_node_check(ctx, node->is_external)) {
377 result = true;
378 break;
380 if (revents & (G_IO_OUT | G_IO_ERR) && node->io_write &&
381 aio_node_check(ctx, node->is_external)) {
382 result = true;
383 break;
386 qemu_lockcnt_dec(&ctx->list_lock);
388 return result;
391 static bool aio_dispatch_handlers(AioContext *ctx)
393 AioHandler *node, *tmp;
394 bool progress = false;
396 QLIST_FOREACH_SAFE_RCU(node, &ctx->aio_handlers, node, tmp) {
397 int revents;
399 revents = node->pfd.revents & node->pfd.events;
400 node->pfd.revents = 0;
402 if (!node->deleted &&
403 (revents & (G_IO_IN | G_IO_HUP | G_IO_ERR)) &&
404 aio_node_check(ctx, node->is_external) &&
405 node->io_read) {
406 node->io_read(node->opaque);
408 /* aio_notify() does not count as progress */
409 if (node->opaque != &ctx->notifier) {
410 progress = true;
413 if (!node->deleted &&
414 (revents & (G_IO_OUT | G_IO_ERR)) &&
415 aio_node_check(ctx, node->is_external) &&
416 node->io_write) {
417 node->io_write(node->opaque);
418 progress = true;
421 if (node->deleted) {
422 if (qemu_lockcnt_dec_if_lock(&ctx->list_lock)) {
423 QLIST_REMOVE(node, node);
424 g_free(node);
425 qemu_lockcnt_inc_and_unlock(&ctx->list_lock);
430 return progress;
433 void aio_dispatch(AioContext *ctx)
435 qemu_lockcnt_inc(&ctx->list_lock);
436 aio_bh_poll(ctx);
437 aio_dispatch_handlers(ctx);
438 qemu_lockcnt_dec(&ctx->list_lock);
440 timerlistgroup_run_timers(&ctx->tlg);
443 /* These thread-local variables are used only in a small part of aio_poll
444 * around the call to the poll() system call. In particular they are not
445 * used while aio_poll is performing callbacks, which makes it much easier
446 * to think about reentrancy!
448 * Stack-allocated arrays would be perfect but they have size limitations;
449 * heap allocation is expensive enough that we want to reuse arrays across
450 * calls to aio_poll(). And because poll() has to be called without holding
451 * any lock, the arrays cannot be stored in AioContext. Thread-local data
452 * has none of the disadvantages of these three options.
454 static __thread GPollFD *pollfds;
455 static __thread AioHandler **nodes;
456 static __thread unsigned npfd, nalloc;
457 static __thread Notifier pollfds_cleanup_notifier;
459 static void pollfds_cleanup(Notifier *n, void *unused)
461 g_assert(npfd == 0);
462 g_free(pollfds);
463 g_free(nodes);
464 nalloc = 0;
467 static void add_pollfd(AioHandler *node)
469 if (npfd == nalloc) {
470 if (nalloc == 0) {
471 pollfds_cleanup_notifier.notify = pollfds_cleanup;
472 qemu_thread_atexit_add(&pollfds_cleanup_notifier);
473 nalloc = 8;
474 } else {
475 g_assert(nalloc <= INT_MAX);
476 nalloc *= 2;
478 pollfds = g_renew(GPollFD, pollfds, nalloc);
479 nodes = g_renew(AioHandler *, nodes, nalloc);
481 nodes[npfd] = node;
482 pollfds[npfd] = (GPollFD) {
483 .fd = node->pfd.fd,
484 .events = node->pfd.events,
486 npfd++;
489 static bool run_poll_handlers_once(AioContext *ctx)
491 bool progress = false;
492 AioHandler *node;
494 QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {
495 if (!node->deleted && node->io_poll &&
496 aio_node_check(ctx, node->is_external) &&
497 node->io_poll(node->opaque) &&
498 node->opaque != &ctx->notifier) {
499 progress = true;
502 /* Caller handles freeing deleted nodes. Don't do it here. */
505 return progress;
508 /* run_poll_handlers:
509 * @ctx: the AioContext
510 * @max_ns: maximum time to poll for, in nanoseconds
512 * Polls for a given time.
514 * Note that ctx->notify_me must be non-zero so this function can detect
515 * aio_notify().
517 * Note that the caller must have incremented ctx->list_lock.
519 * Returns: true if progress was made, false otherwise
521 static bool run_poll_handlers(AioContext *ctx, int64_t max_ns)
523 bool progress;
524 int64_t end_time;
526 assert(ctx->notify_me);
527 assert(qemu_lockcnt_count(&ctx->list_lock) > 0);
528 assert(ctx->poll_disable_cnt == 0);
530 trace_run_poll_handlers_begin(ctx, max_ns);
532 end_time = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) + max_ns;
534 do {
535 progress = run_poll_handlers_once(ctx);
536 } while (!progress && qemu_clock_get_ns(QEMU_CLOCK_REALTIME) < end_time);
538 trace_run_poll_handlers_end(ctx, progress);
540 return progress;
543 /* try_poll_mode:
544 * @ctx: the AioContext
545 * @blocking: busy polling is only attempted when blocking is true
547 * ctx->notify_me must be non-zero so this function can detect aio_notify().
549 * Note that the caller must have incremented ctx->list_lock.
551 * Returns: true if progress was made, false otherwise
553 static bool try_poll_mode(AioContext *ctx, bool blocking)
555 if (blocking && ctx->poll_max_ns && ctx->poll_disable_cnt == 0) {
556 /* See qemu_soonest_timeout() uint64_t hack */
557 int64_t max_ns = MIN((uint64_t)aio_compute_timeout(ctx),
558 (uint64_t)ctx->poll_ns);
560 if (max_ns) {
561 poll_set_started(ctx, true);
563 if (run_poll_handlers(ctx, max_ns)) {
564 return true;
569 poll_set_started(ctx, false);
571 /* Even if we don't run busy polling, try polling once in case it can make
572 * progress and the caller will be able to avoid ppoll(2)/epoll_wait(2).
574 return run_poll_handlers_once(ctx);
577 bool aio_poll(AioContext *ctx, bool blocking)
579 AioHandler *node;
580 int i;
581 int ret = 0;
582 bool progress;
583 int64_t timeout;
584 int64_t start = 0;
586 /* aio_notify can avoid the expensive event_notifier_set if
587 * everything (file descriptors, bottom halves, timers) will
588 * be re-evaluated before the next blocking poll(). This is
589 * already true when aio_poll is called with blocking == false;
590 * if blocking == true, it is only true after poll() returns,
591 * so disable the optimization now.
593 if (blocking) {
594 assert(in_aio_context_home_thread(ctx));
595 atomic_add(&ctx->notify_me, 2);
598 qemu_lockcnt_inc(&ctx->list_lock);
600 if (ctx->poll_max_ns) {
601 start = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
604 progress = try_poll_mode(ctx, blocking);
605 if (!progress) {
606 assert(npfd == 0);
608 /* fill pollfds */
610 if (!aio_epoll_enabled(ctx)) {
611 QLIST_FOREACH_RCU(node, &ctx->aio_handlers, node) {
612 if (!node->deleted && node->pfd.events
613 && aio_node_check(ctx, node->is_external)) {
614 add_pollfd(node);
619 timeout = blocking ? aio_compute_timeout(ctx) : 0;
621 /* wait until next event */
622 if (aio_epoll_check_poll(ctx, pollfds, npfd, timeout)) {
623 AioHandler epoll_handler;
625 epoll_handler.pfd.fd = ctx->epollfd;
626 epoll_handler.pfd.events = G_IO_IN | G_IO_OUT | G_IO_HUP | G_IO_ERR;
627 npfd = 0;
628 add_pollfd(&epoll_handler);
629 ret = aio_epoll(ctx, pollfds, npfd, timeout);
630 } else {
631 ret = qemu_poll_ns(pollfds, npfd, timeout);
635 if (blocking) {
636 atomic_sub(&ctx->notify_me, 2);
637 aio_notify_accept(ctx);
640 /* Adjust polling time */
641 if (ctx->poll_max_ns) {
642 int64_t block_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - start;
644 if (block_ns <= ctx->poll_ns) {
645 /* This is the sweet spot, no adjustment needed */
646 } else if (block_ns > ctx->poll_max_ns) {
647 /* We'd have to poll for too long, poll less */
648 int64_t old = ctx->poll_ns;
650 if (ctx->poll_shrink) {
651 ctx->poll_ns /= ctx->poll_shrink;
652 } else {
653 ctx->poll_ns = 0;
656 trace_poll_shrink(ctx, old, ctx->poll_ns);
657 } else if (ctx->poll_ns < ctx->poll_max_ns &&
658 block_ns < ctx->poll_max_ns) {
659 /* There is room to grow, poll longer */
660 int64_t old = ctx->poll_ns;
661 int64_t grow = ctx->poll_grow;
663 if (grow == 0) {
664 grow = 2;
667 if (ctx->poll_ns) {
668 ctx->poll_ns *= grow;
669 } else {
670 ctx->poll_ns = 4000; /* start polling at 4 microseconds */
673 if (ctx->poll_ns > ctx->poll_max_ns) {
674 ctx->poll_ns = ctx->poll_max_ns;
677 trace_poll_grow(ctx, old, ctx->poll_ns);
681 /* if we have any readable fds, dispatch event */
682 if (ret > 0) {
683 for (i = 0; i < npfd; i++) {
684 nodes[i]->pfd.revents = pollfds[i].revents;
688 npfd = 0;
690 progress |= aio_bh_poll(ctx);
692 if (ret > 0) {
693 progress |= aio_dispatch_handlers(ctx);
696 qemu_lockcnt_dec(&ctx->list_lock);
698 progress |= timerlistgroup_run_timers(&ctx->tlg);
700 return progress;
703 void aio_context_setup(AioContext *ctx)
705 #ifdef CONFIG_EPOLL_CREATE1
706 assert(!ctx->epollfd);
707 ctx->epollfd = epoll_create1(EPOLL_CLOEXEC);
708 if (ctx->epollfd == -1) {
709 fprintf(stderr, "Failed to create epoll instance: %s", strerror(errno));
710 ctx->epoll_available = false;
711 } else {
712 ctx->epoll_available = true;
714 #endif
717 void aio_context_destroy(AioContext *ctx)
719 #ifdef CONFIG_EPOLL_CREATE1
720 aio_epoll_disable(ctx);
721 #endif
724 void aio_context_set_poll_params(AioContext *ctx, int64_t max_ns,
725 int64_t grow, int64_t shrink, Error **errp)
727 /* No thread synchronization here, it doesn't matter if an incorrect value
728 * is used once.
730 ctx->poll_max_ns = max_ns;
731 ctx->poll_ns = 0;
732 ctx->poll_grow = grow;
733 ctx->poll_shrink = shrink;
735 aio_notify(ctx);