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 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 void aeDeleteEventLoop(aeEventLoop *eventLoop) { 95 aeApiFree(eventLoop); 96 zfree(eventLoop->events); 97 zfree(eventLoop->fired); 98 zfree(eventLoop); 99 } 100 101 void aeStop(aeEventLoop *eventLoop) { 102 eventLoop->stop = 1; 103 } 104 105 int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask, 106 aeFileProc *proc, void *clientData) 107 { 108 if (fd >= eventLoop->setsize) { 109 errno = ERANGE; 110 return AE_ERR; 111 } 112 aeFileEvent *fe = &eventLoop->events[fd]; 113 114 if (aeApiAddEvent(eventLoop, fd, mask) == -1) 115 return AE_ERR; 116 fe->mask |= mask; 117 if (mask & AE_READABLE) fe->rfileProc = proc; 118 if (mask & AE_WRITABLE) fe->wfileProc = proc; 119 fe->clientData = clientData; 120 if (fd > eventLoop->maxfd) 121 eventLoop->maxfd = fd; 122 return AE_OK; 123 } 124 125 void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask) 126 { 127 if (fd >= eventLoop->setsize) return; 128 aeFileEvent *fe = &eventLoop->events[fd]; 129 130 if (fe->mask == AE_NONE) return; 131 fe->mask = fe->mask & (~mask); 132 if (fd == eventLoop->maxfd && fe->mask == AE_NONE) { 133 /* Update the max fd */ 134 int j; 135 136 for (j = eventLoop->maxfd-1; j >= 0; j--) 137 if (eventLoop->events[j].mask != AE_NONE) break; 138 eventLoop->maxfd = j; 139 } 140 aeApiDelEvent(eventLoop, fd, mask); 141 } 142 143 int aeGetFileEvents(aeEventLoop *eventLoop, int fd) { 144 if (fd >= eventLoop->setsize) return 0; 145 aeFileEvent *fe = &eventLoop->events[fd]; 146 147 return fe->mask; 148 } 149 150 static void aeGetTime(long *seconds, long *milliseconds) 151 { 152 struct timeval tv; 153 154 gettimeofday(&tv, NULL); 155 *seconds = tv.tv_sec; 156 *milliseconds = tv.tv_usec/1000; 157 } 158 159 static void aeAddMillisecondsToNow(long long milliseconds, long *sec, long *ms) { 160 long cur_sec, cur_ms, when_sec, when_ms; 161 162 aeGetTime(&cur_sec, &cur_ms); 163 when_sec = cur_sec + milliseconds/1000; 164 when_ms = cur_ms + milliseconds%1000; 165 if (when_ms >= 1000) { 166 when_sec ++; 167 when_ms -= 1000; 168 } 169 *sec = when_sec; 170 *ms = when_ms; 171 } 172 173 long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds, 174 aeTimeProc *proc, void *clientData, 175 aeEventFinalizerProc *finalizerProc) 176 { 177 long long id = eventLoop->timeEventNextId++; 178 aeTimeEvent *te; 179 180 te = zmalloc(sizeof(*te)); 181 if (te == NULL) return AE_ERR; 182 te->id = id; 183 aeAddMillisecondsToNow(milliseconds,&te->when_sec,&te->when_ms); 184 te->timeProc = proc; 185 te->finalizerProc = finalizerProc; 186 te->clientData = clientData; 187 te->next = eventLoop->timeEventHead; 188 eventLoop->timeEventHead = te; 189 return id; 190 } 191 192 int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id) 193 { 194 aeTimeEvent *te, *prev = NULL; 195 196 te = eventLoop->timeEventHead; 197 while(te) { 198 if (te->id == id) { 199 if (prev == NULL) 200 eventLoop->timeEventHead = te->next; 201 else 202 prev->next = te->next; 203 if (te->finalizerProc) 204 te->finalizerProc(eventLoop, te->clientData); 205 zfree(te); 206 return AE_OK; 207 } 208 prev = te; 209 te = te->next; 210 } 211 return AE_ERR; /* NO event with the specified ID found */ 212 } 213 214 /* Search the first timer to fire. 215 * This operation is useful to know how many time the select can be 216 * put in sleep without to delay any event. 217 * If there are no timers NULL is returned. 218 * 219 * Note that's O(N) since time events are unsorted. 220 * Possible optimizations (not needed by Redis so far, but...): 221 * 1) Insert the event in order, so that the nearest is just the head. 222 * Much better but still insertion or deletion of timers is O(N). 223 * 2) Use a skiplist to have this operation as O(1) and insertion as O(log(N)). 224 */ 225 static aeTimeEvent *aeSearchNearestTimer(aeEventLoop *eventLoop) 226 { 227 aeTimeEvent *te = eventLoop->timeEventHead; 228 aeTimeEvent *nearest = NULL; 229 230 while(te) { 231 if (!nearest || te->when_sec < nearest->when_sec || 232 (te->when_sec == nearest->when_sec && 233 te->when_ms < nearest->when_ms)) 234 nearest = te; 235 te = te->next; 236 } 237 return nearest; 238 } 239 240 /* Process time events */ 241 static int processTimeEvents(aeEventLoop *eventLoop) { 242 int processed = 0; 243 aeTimeEvent *te; 244 long long maxId; 245 time_t now = time(NULL); 246 247 /* If the system clock is moved to the future, and then set back to the 248 * right value, time events may be delayed in a random way. Often this 249 * means that scheduled operations will not be performed soon enough. 250 * 251 * Here we try to detect system clock skews, and force all the time 252 * events to be processed ASAP when this happens: the idea is that 253 * processing events earlier is less dangerous than delaying them 254 * indefinitely, and practice suggests it is. */ 255 if (now < eventLoop->lastTime) { 256 te = eventLoop->timeEventHead; 257 while(te) { 258 te->when_sec = 0; 259 te = te->next; 260 } 261 } 262 eventLoop->lastTime = now; 263 264 te = eventLoop->timeEventHead; 265 maxId = eventLoop->timeEventNextId-1; 266 while(te) { 267 long now_sec, now_ms; 268 long long id; 269 270 if (te->id > maxId) { 271 te = te->next; 272 continue; 273 } 274 aeGetTime(&now_sec, &now_ms); 275 if (now_sec > te->when_sec || 276 (now_sec == te->when_sec && now_ms >= te->when_ms)) 277 { 278 int retval; 279 280 id = te->id; 281 retval = te->timeProc(eventLoop, id, te->clientData); 282 processed++; 283 /* After an event is processed our time event list may 284 * no longer be the same, so we restart from head. 285 * Still we make sure to don't process events registered 286 * by event handlers itself in order to don't loop forever. 287 * To do so we saved the max ID we want to handle. 288 * 289 * FUTURE OPTIMIZATIONS: 290 * Note that this is NOT great algorithmically. Redis uses 291 * a single time event so it's not a problem but the right 292 * way to do this is to add the new elements on head, and 293 * to flag deleted elements in a special way for later 294 * deletion (putting references to the nodes to delete into 295 * another linked list). */ 296 if (retval != AE_NOMORE) { 297 aeAddMillisecondsToNow(retval,&te->when_sec,&te->when_ms); 298 } else { 299 aeDeleteTimeEvent(eventLoop, id); 300 } 301 te = eventLoop->timeEventHead; 302 } else { 303 te = te->next; 304 } 305 } 306 return processed; 307 } 308 309 /* Process every pending time event, then every pending file event 310 * (that may be registered by time event callbacks just processed). 311 * Without special flags the function sleeps until some file event 312 * fires, or when the next time event occurs (if any). 313 * 314 * If flags is 0, the function does nothing and returns. 315 * if flags has AE_ALL_EVENTS set, all the kind of events are processed. 316 * if flags has AE_FILE_EVENTS set, file events are processed. 317 * if flags has AE_TIME_EVENTS set, time events are processed. 318 * if flags has AE_DONT_WAIT set the function returns ASAP until all 319 * the events that's possible to process without to wait are processed. 320 * 321 * The function returns the number of events processed. */ 322 int aeProcessEvents(aeEventLoop *eventLoop, int flags) 323 { 324 int processed = 0, numevents; 325 326 /* Nothing to do? return ASAP */ 327 if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS)) return 0; 328 329 /* Note that we want call select() even if there are no 330 * file events to process as long as we want to process time 331 * events, in order to sleep until the next time event is ready 332 * to fire. */ 333 if (eventLoop->maxfd != -1 || 334 ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) { 335 int j; 336 aeTimeEvent *shortest = NULL; 337 struct timeval tv, *tvp; 338 339 if (flags & AE_TIME_EVENTS && !(flags & AE_DONT_WAIT)) 340 shortest = aeSearchNearestTimer(eventLoop); 341 if (shortest) { 342 long now_sec, now_ms; 343 344 /* Calculate the time missing for the nearest 345 * timer to fire. */ 346 aeGetTime(&now_sec, &now_ms); 347 tvp = &tv; 348 tvp->tv_sec = shortest->when_sec - now_sec; 349 if (shortest->when_ms < now_ms) { 350 tvp->tv_usec = ((shortest->when_ms+1000) - now_ms)*1000; 351 tvp->tv_sec --; 352 } else { 353 tvp->tv_usec = (shortest->when_ms - now_ms)*1000; 354 } 355 if (tvp->tv_sec < 0) tvp->tv_sec = 0; 356 if (tvp->tv_usec < 0) tvp->tv_usec = 0; 357 } else { 358 /* If we have to check for events but need to return 359 * ASAP because of AE_DONT_WAIT we need to set the timeout 360 * to zero */ 361 if (flags & AE_DONT_WAIT) { 362 tv.tv_sec = tv.tv_usec = 0; 363 tvp = &tv; 364 } else { 365 /* Otherwise we can block */ 366 tvp = NULL; /* wait forever */ 367 } 368 } 369 370 numevents = aeApiPoll(eventLoop, tvp); 371 for (j = 0; j < numevents; j++) { 372 aeFileEvent *fe = &eventLoop->events[eventLoop->fired[j].fd]; 373 int mask = eventLoop->fired[j].mask; 374 int fd = eventLoop->fired[j].fd; 375 int rfired = 0; 376 377 /* note the fe->mask & mask & ... code: maybe an already processed 378 * event removed an element that fired and we still didn't 379 * processed, so we check if the event is still valid. */ 380 if (fe->mask & mask & AE_READABLE) { 381 rfired = 1; 382 fe->rfileProc(eventLoop,fd,fe->clientData,mask); 383 } 384 if (fe->mask & mask & AE_WRITABLE) { 385 if (!rfired || fe->wfileProc != fe->rfileProc) 386 fe->wfileProc(eventLoop,fd,fe->clientData,mask); 387 } 388 processed++; 389 } 390 } 391 /* Check time events */ 392 if (flags & AE_TIME_EVENTS) 393 processed += processTimeEvents(eventLoop); 394 395 return processed; /* return the number of processed file/time events */ 396 } 397 398 /* Wait for milliseconds until the given file descriptor becomes 399 * writable/readable/exception */ 400 int aeWait(int fd, int mask, long long milliseconds) { 401 struct pollfd pfd; 402 int retmask = 0, retval; 403 404 memset(&pfd, 0, sizeof(pfd)); 405 pfd.fd = fd; 406 if (mask & AE_READABLE) pfd.events |= POLLIN; 407 if (mask & AE_WRITABLE) pfd.events |= POLLOUT; 408 409 if ((retval = poll(&pfd, 1, milliseconds))== 1) { 410 if (pfd.revents & POLLIN) retmask |= AE_READABLE; 411 if (pfd.revents & POLLOUT) retmask |= AE_WRITABLE; 412 if (pfd.revents & POLLERR) retmask |= AE_WRITABLE; 413 if (pfd.revents & POLLHUP) retmask |= AE_WRITABLE; 414 return retmask; 415 } else { 416 return retval; 417 } 418 } 419 420 void aeMain(aeEventLoop *eventLoop) { 421 eventLoop->stop = 0; 422 while (!eventLoop->stop) { 423 if (eventLoop->beforesleep != NULL) 424 eventLoop->beforesleep(eventLoop); 425 aeProcessEvents(eventLoop, AE_ALL_EVENTS); 426 } 427 } 428 429 char *aeGetApiName(void) { 430 return aeApiName(); 431 } 432 433 void aeSetBeforeSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep) { 434 eventLoop->beforesleep = beforesleep; 435 } 436