1 /* Licensed under BSD-MIT - see LICENSE file for details */
8 #include <sys/socket.h>
10 static size_t num_fds = 0, max_fds = 0, num_next = 0, num_finished = 0;
11 static struct pollfd *pollfds = NULL;
12 static struct fd **fds = NULL;
14 static bool add_fd(struct fd *fd, short events)
16 if (num_fds + 1 > max_fds) {
17 struct pollfd *newpollfds;
19 size_t num = max_fds ? max_fds * 2 : 8;
21 newpollfds = realloc(pollfds, sizeof(*newpollfds) * num);
25 newfds = realloc(fds, sizeof(*newfds) * num);
32 pollfds[num_fds].fd = fd->fd;
33 pollfds[num_fds].events = events;
34 pollfds[num_fds].revents = 0; /* In case we're iterating now */
36 fd->backend_info = num_fds;
41 static void del_fd(struct fd *fd)
43 size_t n = fd->backend_info;
47 if (n != num_fds - 1) {
48 /* Move last one over us. */
49 pollfds[n] = pollfds[num_fds-1];
50 fds[n] = fds[num_fds-1];
51 assert(fds[n]->backend_info == num_fds-1);
52 fds[n]->backend_info = n;
53 } else if (num_fds == 1) {
54 /* Free everything when no more fds. */
62 fd->backend_info = -1;
66 bool add_listener(struct io_listener *l)
68 return add_fd(&l->fd, POLLIN);
71 bool add_conn(struct io_conn *c)
73 if (!add_fd(&c->fd, 0))
79 static void del_conn(struct io_conn *conn)
82 conn->fd.finish(conn, conn->fd.finish_arg);
84 if (conn->state == FINISHED)
86 else if (conn->state == NEXT)
90 void del_listener(struct io_listener *l)
95 void backend_set_state(struct io_conn *conn, struct io_op *op)
97 enum io_state state = from_ioop(op);
98 struct pollfd *pfd = &pollfds[conn->fd.backend_info];
103 pfd->events = POLLIN;
107 pfd->events = POLLOUT;
124 static void accept_conn(struct io_listener *l)
127 int fd = accept(l->fd.fd, NULL, NULL);
129 /* FIXME: What to do here? */
132 c = io_new_conn(fd, l->fd.next, l->fd.finish, l->fd.next_arg);
139 /* It's OK to miss some, as long as we make progress. */
140 static void finish_and_next(bool finished_only)
144 for (i = 0; !io_loop_return && i < num_fds; i++) {
148 if (finished_only || num_next == 0)
151 if (fds[i]->listener)
154 if (c->state == FINISHED) {
158 } else if (!finished_only && c->state == NEXT) {
159 backend_set_state(c, c->fd.next(c, c->fd.next_arg));
165 /* This is the main loop. */
170 while (!io_loop_return) {
173 if (num_finished || num_next) {
174 finish_and_next(false);
175 /* Could have started/finished more. */
182 r = poll(pollfds, num_fds, -1);
186 for (i = 0; i < num_fds && !io_loop_return; i++) {
187 struct io_conn *c = (void *)fds[i];
188 if (pollfds[i].revents & POLLOUT)
189 backend_set_state(c, do_writeable(c));
190 else if (pollfds[i].revents & POLLIN) {
191 if (fds[i]->listener)
192 accept_conn((void *)c);
194 backend_set_state(c, do_readable(c));
195 } else if (pollfds[i].revents & POLLHUP) {
196 backend_set_state(c, io_close(c, NULL));
202 finish_and_next(true);
204 ret = io_loop_return;
205 io_loop_return = NULL;