]> git.saurik.com Git - redis.git/blob - src/ae_epoll.c
5680b6a2767617319e1d07732530553d1eb2457b
[redis.git] / src / ae_epoll.c
1 /* Linux epoll(2) based ae.c module
2 * Copyright (C) 2009-2010 Salvatore Sanfilippo - antirez@gmail.com
3 * Released under the BSD license. See the COPYING file for more info. */
4
5 #include <sys/epoll.h>
6
7 typedef struct aeApiState {
8 int epfd;
9 struct epoll_event events[AE_SETSIZE];
10 } aeApiState;
11
12 static int aeApiCreate(aeEventLoop *eventLoop) {
13 aeApiState *state = zmalloc(sizeof(aeApiState));
14
15 if (!state) return -1;
16 state->epfd = epoll_create(1024); /* 1024 is just an hint for the kernel */
17 if (state->epfd == -1) {
18 zfree(state);
19 return -1;
20 }
21 eventLoop->apidata = state;
22 return 0;
23 }
24
25 static void aeApiFree(aeEventLoop *eventLoop) {
26 aeApiState *state = eventLoop->apidata;
27
28 close(state->epfd);
29 zfree(state);
30 }
31
32 static int aeApiAddEvent(aeEventLoop *eventLoop, int fd, int mask) {
33 aeApiState *state = eventLoop->apidata;
34 struct epoll_event ee;
35 /* If the fd was already monitored for some event, we need a MOD
36 * operation. Otherwise we need an ADD operation. */
37 int op = eventLoop->events[fd].mask == AE_NONE ?
38 EPOLL_CTL_ADD : EPOLL_CTL_MOD;
39
40 ee.events = 0;
41 mask |= eventLoop->events[fd].mask; /* Merge old events */
42 if (mask & AE_READABLE) ee.events |= EPOLLIN;
43 if (mask & AE_WRITABLE) ee.events |= EPOLLOUT;
44 ee.data.u64 = 0; /* avoid valgrind warning */
45 ee.data.fd = fd;
46 if (epoll_ctl(state->epfd,op,fd,&ee) == -1) return -1;
47 return 0;
48 }
49
50 static void aeApiDelEvent(aeEventLoop *eventLoop, int fd, int delmask) {
51 aeApiState *state = eventLoop->apidata;
52 struct epoll_event ee;
53 int mask = eventLoop->events[fd].mask & (~delmask);
54
55 ee.events = 0;
56 if (mask & AE_READABLE) ee.events |= EPOLLIN;
57 if (mask & AE_WRITABLE) ee.events |= EPOLLOUT;
58 ee.data.u64 = 0; /* avoid valgrind warning */
59 ee.data.fd = fd;
60 if (mask != AE_NONE) {
61 epoll_ctl(state->epfd,EPOLL_CTL_MOD,fd,&ee);
62 } else {
63 /* Note, Kernel < 2.6.9 requires a non null event pointer even for
64 * EPOLL_CTL_DEL. */
65 epoll_ctl(state->epfd,EPOLL_CTL_DEL,fd,&ee);
66 }
67 }
68
69 static int aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) {
70 aeApiState *state = eventLoop->apidata;
71 int retval, numevents = 0;
72
73 retval = epoll_wait(state->epfd,state->events,AE_SETSIZE,
74 tvp ? (tvp->tv_sec*1000 + tvp->tv_usec/1000) : -1);
75 if (retval > 0) {
76 int j;
77
78 numevents = retval;
79 for (j = 0; j < numevents; j++) {
80 int mask = 0;
81 struct epoll_event *e = state->events+j;
82
83 if (e->events & EPOLLIN) mask |= AE_READABLE;
84 if (e->events & EPOLLOUT) mask |= AE_WRITABLE;
85 eventLoop->fired[j].fd = e->data.fd;
86 eventLoop->fired[j].mask = mask;
87 }
88 }
89 return numevents;
90 }
91
92 static char *aeApiName(void) {
93 return "epoll";
94 }