1 /* A simple event-driven programming library. Originally I wrote this code
2  * for the Jim's event-loop (Jim is a Tcl interpreter) but later translated
3  * it in form of a library for easy reuse.
4  *
5  * Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  *   * Redistributions of source code must retain the above copyright notice,
12  *     this list of conditions and the following disclaimer.
13  *   * Redistributions in binary form must reproduce the above copyright
14  *     notice, this list of conditions and the following disclaimer in the
15  *     documentation and/or other materials provided with the distribution.
16  *   * Neither the name of Redis nor the names of its contributors may be used
17  *     to endorse or promote products derived from this software without
18  *     specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 #include <stdio.h>
34 #include <sys/time.h>
35 #include <sys/types.h>
36 #include <unistd.h>
37 #include <stdlib.h>
38 #include <poll.h>
39 #include <string.h>
40 #include <time.h>
41 #include <errno.h>
42 
43 #include "ae.h"
44 #include "zmalloc.h"
45 #include "config.h"
46 
47 /* Include the best multiplexing layer supported by this system.
48  * The following should be ordered by performances, descending. */
49 #ifdef HAVE_EVPORT
50 #include "ae_evport.c"
51 #else
52     #ifdef HAVE_EPOLL
53     #include "ae_epoll.c"
54     #else
55         #ifdef HAVE_KQUEUE
56         #include "ae_kqueue.c"
57         #else
58         #include "ae_select.c"
59         #endif
60     #endif
61 #endif
62 
aeCreateEventLoop(int setsize)63 aeEventLoop *aeCreateEventLoop(int setsize) {
64     aeEventLoop *eventLoop;
65     int i;
66 
67     if ((eventLoop = zmalloc(sizeof(*eventLoop))) == NULL) goto err;
68     eventLoop->events = zmalloc(sizeof(aeFileEvent)*setsize);
69     eventLoop->fired = zmalloc(sizeof(aeFiredEvent)*setsize);
70     if (eventLoop->events == NULL || eventLoop->fired == NULL) goto err;
71     eventLoop->setsize = setsize;
72     eventLoop->lastTime = time(NULL);
73     eventLoop->timeEventHead = NULL;
74     eventLoop->timeEventNextId = 0;
75     eventLoop->stop = 0;
76     eventLoop->maxfd = -1;
77     eventLoop->beforesleep = NULL;
78     if (aeApiCreate(eventLoop) == -1) goto err;
79     /* Events with mask == AE_NONE are not set. So let's initialize the
80      * vector with it. */
81     for (i = 0; i < setsize; i++)
82         eventLoop->events[i].mask = AE_NONE;
83     return eventLoop;
84 
85 err:
86     if (eventLoop) {
87         zfree(eventLoop->events);
88         zfree(eventLoop->fired);
89         zfree(eventLoop);
90     }
91     return NULL;
92 }
93 
94 /* Return the current set size. */
aeGetSetSize(aeEventLoop * eventLoop)95 int aeGetSetSize(aeEventLoop *eventLoop) {
96     return eventLoop->setsize;
97 }
98 
99 /* Resize the maximum set size of the event loop.
100  * If the requested set size is smaller than the current set size, but
101  * there is already a file descriptor in use that is >= the requested
102  * set size minus one, AE_ERR is returned and the operation is not
103  * performed at all.
104  *
105  * Otherwise AE_OK is returned and the operation is successful. */
aeResizeSetSize(aeEventLoop * eventLoop,int setsize)106 int aeResizeSetSize(aeEventLoop *eventLoop, int setsize) {
107     int i;
108 
109     if (setsize == eventLoop->setsize) return AE_OK;
110     if (eventLoop->maxfd >= setsize) return AE_ERR;
111     if (aeApiResize(eventLoop,setsize) == -1) return AE_ERR;
112 
113     eventLoop->events = zrealloc(eventLoop->events,sizeof(aeFileEvent)*setsize);
114     eventLoop->fired = zrealloc(eventLoop->fired,sizeof(aeFiredEvent)*setsize);
115     eventLoop->setsize = setsize;
116 
117     /* Make sure that if we created new slots, they are initialized with
118      * an AE_NONE mask. */
119     for (i = eventLoop->maxfd+1; i < setsize; i++)
120         eventLoop->events[i].mask = AE_NONE;
121     return AE_OK;
122 }
123 
aeDeleteEventLoop(aeEventLoop * eventLoop)124 void aeDeleteEventLoop(aeEventLoop *eventLoop) {
125     aeApiFree(eventLoop);
126     zfree(eventLoop->events);
127     zfree(eventLoop->fired);
128     zfree(eventLoop);
129 }
130 
aeStop(aeEventLoop * eventLoop)131 void aeStop(aeEventLoop *eventLoop) {
132     eventLoop->stop = 1;
133 }
134 
aeCreateFileEvent(aeEventLoop * eventLoop,int fd,int mask,aeFileProc * proc,void * clientData)135 int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask,
136         aeFileProc *proc, void *clientData)
137 {
138     if (fd >= eventLoop->setsize) {
139         errno = ERANGE;
140         return AE_ERR;
141     }
142     aeFileEvent *fe = &eventLoop->events[fd];
143 
144     if (aeApiAddEvent(eventLoop, fd, mask) == -1)
145         return AE_ERR;
146     fe->mask |= mask;
147     if (mask & AE_READABLE) fe->rfileProc = proc;
148     if (mask & AE_WRITABLE) fe->wfileProc = proc;
149     fe->clientData = clientData;
150     if (fd > eventLoop->maxfd)
151         eventLoop->maxfd = fd;
152     return AE_OK;
153 }
154 
aeDeleteFileEvent(aeEventLoop * eventLoop,int fd,int mask)155 void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask)
156 {
157     if (fd >= eventLoop->setsize) return;
158     aeFileEvent *fe = &eventLoop->events[fd];
159     if (fe->mask == AE_NONE) return;
160 
161     aeApiDelEvent(eventLoop, fd, mask);
162     fe->mask = fe->mask & (~mask);
163     if (fd == eventLoop->maxfd && fe->mask == AE_NONE) {
164         /* Update the max fd */
165         int j;
166 
167         for (j = eventLoop->maxfd-1; j >= 0; j--)
168             if (eventLoop->events[j].mask != AE_NONE) break;
169         eventLoop->maxfd = j;
170     }
171 }
172 
aeGetFileEvents(aeEventLoop * eventLoop,int fd)173 int aeGetFileEvents(aeEventLoop *eventLoop, int fd) {
174     if (fd >= eventLoop->setsize) return 0;
175     aeFileEvent *fe = &eventLoop->events[fd];
176 
177     return fe->mask;
178 }
179 
aeGetTime(long * seconds,long * milliseconds)180 static void aeGetTime(long *seconds, long *milliseconds)
181 {
182     struct timeval tv;
183 
184     gettimeofday(&tv, NULL);
185     *seconds = tv.tv_sec;
186     *milliseconds = tv.tv_usec/1000;
187 }
188 
aeAddMillisecondsToNow(long long milliseconds,long * sec,long * ms)189 static void aeAddMillisecondsToNow(long long milliseconds, long *sec, long *ms) {
190     long cur_sec, cur_ms, when_sec, when_ms;
191 
192     aeGetTime(&cur_sec, &cur_ms);
193     when_sec = cur_sec + milliseconds/1000;
194     when_ms = cur_ms + milliseconds%1000;
195     if (when_ms >= 1000) {
196         when_sec ++;
197         when_ms -= 1000;
198     }
199     *sec = when_sec;
200     *ms = when_ms;
201 }
202 
aeCreateTimeEvent(aeEventLoop * eventLoop,long long milliseconds,aeTimeProc * proc,void * clientData,aeEventFinalizerProc * finalizerProc)203 long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds,
204         aeTimeProc *proc, void *clientData,
205         aeEventFinalizerProc *finalizerProc)
206 {
207     long long id = eventLoop->timeEventNextId++;
208     aeTimeEvent *te;
209 
210     te = zmalloc(sizeof(*te));
211     if (te == NULL) return AE_ERR;
212     te->id = id;
213     aeAddMillisecondsToNow(milliseconds,&te->when_sec,&te->when_ms);
214     te->timeProc = proc;
215     te->finalizerProc = finalizerProc;
216     te->clientData = clientData;
217     te->next = eventLoop->timeEventHead;
218     eventLoop->timeEventHead = te;
219     return id;
220 }
221 
aeDeleteTimeEvent(aeEventLoop * eventLoop,long long id)222 int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id)
223 {
224     aeTimeEvent *te, *prev = NULL;
225 
226     te = eventLoop->timeEventHead;
227     while(te) {
228         if (te->id == id) {
229             if (prev == NULL)
230                 eventLoop->timeEventHead = te->next;
231             else
232                 prev->next = te->next;
233             if (te->finalizerProc)
234                 te->finalizerProc(eventLoop, te->clientData);
235             zfree(te);
236             return AE_OK;
237         }
238         prev = te;
239         te = te->next;
240     }
241     return AE_ERR; /* NO event with the specified ID found */
242 }
243 
244 /* Search the first timer to fire.
245  * This operation is useful to know how many time the select can be
246  * put in sleep without to delay any event.
247  * If there are no timers NULL is returned.
248  *
249  * Note that's O(N) since time events are unsorted.
250  * Possible optimizations (not needed by Redis so far, but...):
251  * 1) Insert the event in order, so that the nearest is just the head.
252  *    Much better but still insertion or deletion of timers is O(N).
253  * 2) Use a skiplist to have this operation as O(1) and insertion as O(log(N)).
254  */
aeSearchNearestTimer(aeEventLoop * eventLoop)255 static aeTimeEvent *aeSearchNearestTimer(aeEventLoop *eventLoop)
256 {
257     aeTimeEvent *te = eventLoop->timeEventHead;
258     aeTimeEvent *nearest = NULL;
259 
260     while(te) {
261         if (!nearest || te->when_sec < nearest->when_sec ||
262                 (te->when_sec == nearest->when_sec &&
263                  te->when_ms < nearest->when_ms))
264             nearest = te;
265         te = te->next;
266     }
267     return nearest;
268 }
269 
270 /* Process time events */
processTimeEvents(aeEventLoop * eventLoop)271 static int processTimeEvents(aeEventLoop *eventLoop) {
272     int processed = 0;
273     aeTimeEvent *te;
274     long long maxId;
275     time_t now = time(NULL);
276 
277     /* If the system clock is moved to the future, and then set back to the
278      * right value, time events may be delayed in a random way. Often this
279      * means that scheduled operations will not be performed soon enough.
280      *
281      * Here we try to detect system clock skews, and force all the time
282      * events to be processed ASAP when this happens: the idea is that
283      * processing events earlier is less dangerous than delaying them
284      * indefinitely, and practice suggests it is. */
285     if (now < eventLoop->lastTime) {
286         te = eventLoop->timeEventHead;
287         while(te) {
288             te->when_sec = 0;
289             te = te->next;
290         }
291     }
292     eventLoop->lastTime = now;
293 
294     te = eventLoop->timeEventHead;
295     maxId = eventLoop->timeEventNextId-1;
296     while(te) {
297         long now_sec, now_ms;
298         long long id;
299 
300         if (te->id > maxId) {
301             te = te->next;
302             continue;
303         }
304         aeGetTime(&now_sec, &now_ms);
305         if (now_sec > te->when_sec ||
306             (now_sec == te->when_sec && now_ms >= te->when_ms))
307         {
308             int retval;
309 
310             id = te->id;
311             retval = te->timeProc(eventLoop, id, te->clientData);
312             processed++;
313             /* After an event is processed our time event list may
314              * no longer be the same, so we restart from head.
315              * Still we make sure to don't process events registered
316              * by event handlers itself in order to don't loop forever.
317              * To do so we saved the max ID we want to handle.
318              *
319              * FUTURE OPTIMIZATIONS:
320              * Note that this is NOT great algorithmically. Redis uses
321              * a single time event so it's not a problem but the right
322              * way to do this is to add the new elements on head, and
323              * to flag deleted elements in a special way for later
324              * deletion (putting references to the nodes to delete into
325              * another linked list). */
326             if (retval != AE_NOMORE) {
327                 aeAddMillisecondsToNow(retval,&te->when_sec,&te->when_ms);
328             } else {
329                 aeDeleteTimeEvent(eventLoop, id);
330             }
331             te = eventLoop->timeEventHead;
332         } else {
333             te = te->next;
334         }
335     }
336     return processed;
337 }
338 
339 /* Process every pending time event, then every pending file event
340  * (that may be registered by time event callbacks just processed).
341  * Without special flags the function sleeps until some file event
342  * fires, or when the next time event occurs (if any).
343  *
344  * If flags is 0, the function does nothing and returns.
345  * if flags has AE_ALL_EVENTS set, all the kind of events are processed.
346  * if flags has AE_FILE_EVENTS set, file events are processed.
347  * if flags has AE_TIME_EVENTS set, time events are processed.
348  * if flags has AE_DONT_WAIT set the function returns ASAP until all
349  * the events that's possible to process without to wait are processed.
350  *
351  * The function returns the number of events processed. */
aeProcessEvents(aeEventLoop * eventLoop,int flags)352 int aeProcessEvents(aeEventLoop *eventLoop, int flags)
353 {
354     int processed = 0, numevents;
355 
356     /* Nothing to do? return ASAP */
357     if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS)) return 0;
358 
359     /* Note that we want call select() even if there are no
360      * file events to process as long as we want to process time
361      * events, in order to sleep until the next time event is ready
362      * to fire. */
363     if (eventLoop->maxfd != -1 ||
364         ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) {
365         int j;
366         aeTimeEvent *shortest = NULL;
367         struct timeval tv, *tvp;
368 
369         if (flags & AE_TIME_EVENTS && !(flags & AE_DONT_WAIT))
370             shortest = aeSearchNearestTimer(eventLoop);
371         if (shortest) {
372             long now_sec, now_ms;
373 
374             /* Calculate the time missing for the nearest
375              * timer to fire. */
376             aeGetTime(&now_sec, &now_ms);
377             tvp = &tv;
378             tvp->tv_sec = shortest->when_sec - now_sec;
379             if (shortest->when_ms < now_ms) {
380                 tvp->tv_usec = ((shortest->when_ms+1000) - now_ms)*1000;
381                 tvp->tv_sec --;
382             } else {
383                 tvp->tv_usec = (shortest->when_ms - now_ms)*1000;
384             }
385             if (tvp->tv_sec < 0) tvp->tv_sec = 0;
386             if (tvp->tv_usec < 0) tvp->tv_usec = 0;
387         } else {
388             /* If we have to check for events but need to return
389              * ASAP because of AE_DONT_WAIT we need to set the timeout
390              * to zero */
391             if (flags & AE_DONT_WAIT) {
392                 tv.tv_sec = tv.tv_usec = 0;
393                 tvp = &tv;
394             } else {
395                 /* Otherwise we can block */
396                 tvp = NULL; /* wait forever */
397             }
398         }
399 
400         numevents = aeApiPoll(eventLoop, tvp);
401         for (j = 0; j < numevents; j++) {
402             aeFileEvent *fe = &eventLoop->events[eventLoop->fired[j].fd];
403             int mask = eventLoop->fired[j].mask;
404             int fd = eventLoop->fired[j].fd;
405             int rfired = 0;
406 
407 	    /* note the fe->mask & mask & ... code: maybe an already processed
408              * event removed an element that fired and we still didn't
409              * processed, so we check if the event is still valid. */
410             if (fe->mask & mask & AE_READABLE) {
411                 rfired = 1;
412                 fe->rfileProc(eventLoop,fd,fe->clientData,mask);
413             }
414             if (fe->mask & mask & AE_WRITABLE) {
415                 if (!rfired || fe->wfileProc != fe->rfileProc)
416                     fe->wfileProc(eventLoop,fd,fe->clientData,mask);
417             }
418             processed++;
419         }
420     }
421     /* Check time events */
422     if (flags & AE_TIME_EVENTS)
423         processed += processTimeEvents(eventLoop);
424 
425     return processed; /* return the number of processed file/time events */
426 }
427 
428 /* Wait for milliseconds until the given file descriptor becomes
429  * writable/readable/exception */
aeWait(int fd,int mask,long long milliseconds)430 int aeWait(int fd, int mask, long long milliseconds) {
431     struct pollfd pfd;
432     int retmask = 0, retval;
433 
434     memset(&pfd, 0, sizeof(pfd));
435     pfd.fd = fd;
436     if (mask & AE_READABLE) pfd.events |= POLLIN;
437     if (mask & AE_WRITABLE) pfd.events |= POLLOUT;
438 
439     if ((retval = poll(&pfd, 1, milliseconds))== 1) {
440         if (pfd.revents & POLLIN) retmask |= AE_READABLE;
441         if (pfd.revents & POLLOUT) retmask |= AE_WRITABLE;
442 	if (pfd.revents & POLLERR) retmask |= AE_WRITABLE;
443         if (pfd.revents & POLLHUP) retmask |= AE_WRITABLE;
444         return retmask;
445     } else {
446         return retval;
447     }
448 }
449 
aeMain(aeEventLoop * eventLoop)450 void aeMain(aeEventLoop *eventLoop) {
451     eventLoop->stop = 0;
452     while (!eventLoop->stop) {
453         if (eventLoop->beforesleep != NULL)
454             eventLoop->beforesleep(eventLoop);
455         aeProcessEvents(eventLoop, AE_ALL_EVENTS);
456     }
457 }
458 
aeGetApiName(void)459 char *aeGetApiName(void) {
460     return aeApiName();
461 }
462 
aeSetBeforeSleepProc(aeEventLoop * eventLoop,aeBeforeSleepProc * beforesleep)463 void aeSetBeforeSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep) {
464     eventLoop->beforesleep = beforesleep;
465 }
466