]> git.proxmox.com Git - mirror_qemu.git/blame - util/event_notifier-posix.c
util: Clean up includes
[mirror_qemu.git] / util / event_notifier-posix.c
CommitLineData
2292b339
MT
1/*
2 * event notifier support
3 *
4 * Copyright Red Hat, Inc. 2010
5 *
6 * Authors:
7 * Michael S. Tsirkin <mst@redhat.com>
8 *
6b620ca3
PB
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.
2292b339
MT
11 */
12
aafd7584 13#include "qemu/osdep.h"
e80c262b 14#include "qemu-common.h"
1de7afc9 15#include "qemu/event_notifier.h"
dccfcd0e 16#include "sysemu/char.h"
1de7afc9 17#include "qemu/main-loop.h"
e80c262b 18
2292b339
MT
19#ifdef CONFIG_EVENTFD
20#include <sys/eventfd.h>
21#endif
22
e80c262b
PB
23void event_notifier_init_fd(EventNotifier *e, int fd)
24{
d0cc2fbf
PB
25 e->rfd = fd;
26 e->wfd = fd;
e80c262b
PB
27}
28
2292b339
MT
29int event_notifier_init(EventNotifier *e, int active)
30{
d0cc2fbf
PB
31 int fds[2];
32 int ret;
33
2292b339 34#ifdef CONFIG_EVENTFD
d0cc2fbf 35 ret = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
2292b339 36#else
d0cc2fbf
PB
37 ret = -1;
38 errno = ENOSYS;
2292b339 39#endif
d0cc2fbf
PB
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
67fail:
68 close(fds[0]);
69 close(fds[1]);
70 return ret;
2292b339
MT
71}
72
73void event_notifier_cleanup(EventNotifier *e)
74{
d0cc2fbf
PB
75 if (e->rfd != e->wfd) {
76 close(e->rfd);
77 }
78 close(e->wfd);
2292b339
MT
79}
80
12f0b68c 81int event_notifier_get_fd(const EventNotifier *e)
2292b339 82{
d0cc2fbf 83 return e->rfd;
2292b339
MT
84}
85
6bf819f0
PB
86int event_notifier_set_handler(EventNotifier *e,
87 EventNotifierHandler *handler)
88{
1e354528
FZ
89 qemu_set_fd_handler(e->rfd, (IOHandler *)handler, NULL, e);
90 return 0;
6bf819f0
PB
91}
92
2ec10b95
PB
93int event_notifier_set(EventNotifier *e)
94{
d0cc2fbf
PB
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;
2ec10b95
PB
107}
108
2292b339
MT
109int event_notifier_test_and_clear(EventNotifier *e)
110{
d0cc2fbf
PB
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;
2292b339 123}