]> git.ipfire.org Git - thirdparty/qemu.git/blob - util/event_notifier-posix.c
util: move declarations out of qemu-common.h
[thirdparty/qemu.git] / util / event_notifier-posix.c
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/cutils.h"
16 #include "qemu/event_notifier.h"
17 #include "sysemu/char.h"
18 #include "qemu/main-loop.h"
19
20 #ifdef CONFIG_EVENTFD
21 #include <sys/eventfd.h>
22 #endif
23
24 void event_notifier_init_fd(EventNotifier *e, int fd)
25 {
26 e->rfd = fd;
27 e->wfd = fd;
28 }
29
30 int event_notifier_init(EventNotifier *e, int active)
31 {
32 int fds[2];
33 int ret;
34
35 #ifdef CONFIG_EVENTFD
36 ret = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
37 #else
38 ret = -1;
39 errno = ENOSYS;
40 #endif
41 if (ret >= 0) {
42 e->rfd = e->wfd = ret;
43 } else {
44 if (errno != ENOSYS) {
45 return -errno;
46 }
47 if (qemu_pipe(fds) < 0) {
48 return -errno;
49 }
50 ret = fcntl_setfl(fds[0], O_NONBLOCK);
51 if (ret < 0) {
52 ret = -errno;
53 goto fail;
54 }
55 ret = fcntl_setfl(fds[1], O_NONBLOCK);
56 if (ret < 0) {
57 ret = -errno;
58 goto fail;
59 }
60 e->rfd = fds[0];
61 e->wfd = fds[1];
62 }
63 if (active) {
64 event_notifier_set(e);
65 }
66 return 0;
67
68 fail:
69 close(fds[0]);
70 close(fds[1]);
71 return ret;
72 }
73
74 void event_notifier_cleanup(EventNotifier *e)
75 {
76 if (e->rfd != e->wfd) {
77 close(e->rfd);
78 }
79 close(e->wfd);
80 }
81
82 int event_notifier_get_fd(const EventNotifier *e)
83 {
84 return e->rfd;
85 }
86
87 int event_notifier_set_handler(EventNotifier *e,
88 EventNotifierHandler *handler)
89 {
90 qemu_set_fd_handler(e->rfd, (IOHandler *)handler, NULL, e);
91 return 0;
92 }
93
94 int event_notifier_set(EventNotifier *e)
95 {
96 static const uint64_t value = 1;
97 ssize_t ret;
98
99 do {
100 ret = write(e->wfd, &value, sizeof(value));
101 } while (ret < 0 && errno == EINTR);
102
103 /* EAGAIN is fine, a read must be pending. */
104 if (ret < 0 && errno != EAGAIN) {
105 return -errno;
106 }
107 return 0;
108 }
109
110 int event_notifier_test_and_clear(EventNotifier *e)
111 {
112 int value;
113 ssize_t len;
114 char buffer[512];
115
116 /* Drain the notify pipe. For eventfd, only 8 bytes will be read. */
117 value = 0;
118 do {
119 len = read(e->rfd, buffer, sizeof(buffer));
120 value |= (len > 0);
121 } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));
122
123 return value;
124 }