1 /* 2 * event notifier support 3 * 4 * Copyright Red Hat, Inc. 2010 5 * 6 * Authors: 7 * Michael S. Tsirkin <mst@redhat.com> 8 * 9 * This work is licensed under the terms of the GNU GPL, version 2 or later. 10 * See the COPYING file in the top-level directory. 11 */ 12 13 #include "qemu/osdep.h" 14 #include "qemu-common.h" 15 #include "qemu/event_notifier.h" 16 #include "sysemu/char.h" 17 #include "qemu/main-loop.h" 18 19 #ifdef CONFIG_EVENTFD 20 #include <sys/eventfd.h> 21 #endif 22 23 void event_notifier_init_fd(EventNotifier *e, int fd) 24 { 25 e->rfd = fd; 26 e->wfd = fd; 27 } 28 29 int event_notifier_init(EventNotifier *e, int active) 30 { 31 int fds[2]; 32 int ret; 33 34 #ifdef CONFIG_EVENTFD 35 ret = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); 36 #else 37 ret = -1; 38 errno = ENOSYS; 39 #endif 40 if (ret >= 0) { 41 e->rfd = e->wfd = ret; 42 } else { 43 if (errno != ENOSYS) { 44 return -errno; 45 } 46 if (qemu_pipe(fds) < 0) { 47 return -errno; 48 } 49 ret = fcntl_setfl(fds[0], O_NONBLOCK); 50 if (ret < 0) { 51 ret = -errno; 52 goto fail; 53 } 54 ret = fcntl_setfl(fds[1], O_NONBLOCK); 55 if (ret < 0) { 56 ret = -errno; 57 goto fail; 58 } 59 e->rfd = fds[0]; 60 e->wfd = fds[1]; 61 } 62 if (active) { 63 event_notifier_set(e); 64 } 65 return 0; 66 67 fail: 68 close(fds[0]); 69 close(fds[1]); 70 return ret; 71 } 72 73 void event_notifier_cleanup(EventNotifier *e) 74 { 75 if (e->rfd != e->wfd) { 76 close(e->rfd); 77 } 78 close(e->wfd); 79 } 80 81 int event_notifier_get_fd(const EventNotifier *e) 82 { 83 return e->rfd; 84 } 85 86 int event_notifier_set_handler(EventNotifier *e, 87 EventNotifierHandler *handler) 88 { 89 qemu_set_fd_handler(e->rfd, (IOHandler *)handler, NULL, e); 90 return 0; 91 } 92 93 int event_notifier_set(EventNotifier *e) 94 { 95 static const uint64_t value = 1; 96 ssize_t ret; 97 98 do { 99 ret = write(e->wfd, &value, sizeof(value)); 100 } while (ret < 0 && errno == EINTR); 101 102 /* EAGAIN is fine, a read must be pending. */ 103 if (ret < 0 && errno != EAGAIN) { 104 return -errno; 105 } 106 return 0; 107 } 108 109 int event_notifier_test_and_clear(EventNotifier *e) 110 { 111 int value; 112 ssize_t len; 113 char buffer[512]; 114 115 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */ 116 value = 0; 117 do { 118 len = read(e->rfd, buffer, sizeof(buffer)); 119 value |= (len > 0); 120 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer)); 121 122 return value; 123 } 124