jshn: properly support JSON "null" type
[project/libubox.git] / uloop-epoll.c
1 /*
2 * uloop - event loop implementation
3 *
4 * Copyright (C) 2010-2016 Felix Fietkau <nbd@openwrt.org>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19 /**
20 * FIXME: uClibc < 0.9.30.3 does not define EPOLLRDHUP for Linux >= 2.6.17
21 */
22 #ifndef EPOLLRDHUP
23 #define EPOLLRDHUP 0x2000
24 #endif
25
26 static int uloop_init_pollfd(void)
27 {
28 if (poll_fd >= 0)
29 return 0;
30
31 poll_fd = epoll_create(32);
32 if (poll_fd < 0)
33 return -1;
34
35 fcntl(poll_fd, F_SETFD, fcntl(poll_fd, F_GETFD) | FD_CLOEXEC);
36 return 0;
37 }
38
39 static int register_poll(struct uloop_fd *fd, unsigned int flags)
40 {
41 struct epoll_event ev;
42 int op = fd->registered ? EPOLL_CTL_MOD : EPOLL_CTL_ADD;
43
44 memset(&ev, 0, sizeof(struct epoll_event));
45
46 if (flags & ULOOP_READ)
47 ev.events |= EPOLLIN | EPOLLRDHUP;
48
49 if (flags & ULOOP_WRITE)
50 ev.events |= EPOLLOUT;
51
52 if (flags & ULOOP_EDGE_TRIGGER)
53 ev.events |= EPOLLET;
54
55 ev.data.ptr = fd;
56 fd->flags = flags;
57
58 return epoll_ctl(poll_fd, op, fd->fd, &ev);
59 }
60
61 static struct epoll_event events[ULOOP_MAX_EVENTS];
62
63 static int __uloop_fd_delete(struct uloop_fd *sock)
64 {
65 sock->flags = 0;
66 return epoll_ctl(poll_fd, EPOLL_CTL_DEL, sock->fd, 0);
67 }
68
69 static int uloop_fetch_events(int timeout)
70 {
71 int n, nfds;
72
73 nfds = epoll_wait(poll_fd, events, ARRAY_SIZE(events), timeout);
74 for (n = 0; n < nfds; ++n) {
75 struct uloop_fd_event *cur = &cur_fds[n];
76 struct uloop_fd *u = events[n].data.ptr;
77 unsigned int ev = 0;
78
79 cur->fd = u;
80 if (!u)
81 continue;
82
83 if (events[n].events & (EPOLLERR|EPOLLHUP)) {
84 u->error = true;
85 if (!(u->flags & ULOOP_ERROR_CB))
86 uloop_fd_delete(u);
87 }
88
89 if(!(events[n].events & (EPOLLRDHUP|EPOLLIN|EPOLLOUT|EPOLLERR|EPOLLHUP))) {
90 cur->fd = NULL;
91 continue;
92 }
93
94 if(events[n].events & EPOLLRDHUP)
95 u->eof = true;
96
97 if(events[n].events & EPOLLIN)
98 ev |= ULOOP_READ;
99
100 if(events[n].events & EPOLLOUT)
101 ev |= ULOOP_WRITE;
102
103 cur->events = ev;
104 }
105
106 return nfds;
107 }