+struct timeval now;
+
+static fd_set readfds;
+static fd_set writefds;
+static volatile bool running;
+
+static int io_compare(const io_t *a, const io_t *b) {
+ return a->fd - b->fd;
+}
+
+static int timeout_compare(const timeout_t *a, const timeout_t *b) {
+ struct timeval diff;
+ timersub(&a->tv, &b->tv, &diff);
+ return diff.tv_sec ?: diff.tv_usec ?: a < b ? -1 : a > b ? 1 : 0;
+}
+
+static int signal_compare(const signal_t *a, const signal_t *b) {
+ return a->signum - b->signum;
+}
+
+static splay_tree_t io_tree = {.compare = (splay_compare_t)io_compare};
+static splay_tree_t timeout_tree = {.compare = (splay_compare_t)timeout_compare};
+static splay_tree_t signal_tree = {.compare = (splay_compare_t)signal_compare};
+
+void io_add(io_t *io, io_cb_t cb, void *data, int fd, int flags) {
+ if(io->cb)
+ return;
+
+ io->fd = fd;
+ io->cb = cb;
+ io->data = data;
+ io->node.data = io;
+
+ io_set(io, flags);
+
+ splay_insert_node(&io_tree, &io->node);
+}
+
+void io_set(io_t *io, int flags) {
+ io->flags = flags;
+
+ if(flags & IO_READ)
+ FD_SET(io->fd, &readfds);
+ else
+ FD_CLR(io->fd, &readfds);
+
+ if(flags & IO_WRITE)
+ FD_SET(io->fd, &writefds);
+ else
+ FD_CLR(io->fd, &writefds);
+}
+
+void io_del(io_t *io) {
+ if(!io->cb)
+ return;
+
+ io_set(io, 0);