Mirror of :pserver:anonymous@cvs.schmorp.de/schmorpforge libev http://software.schmorp.de/pkg/libev.html
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1507 lines
31 KiB

14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
14 years ago
  1. /*
  2. * libev event processing core, watcher management
  3. *
  4. * Copyright (c) 2007 Marc Alexander Lehmann <libev@schmorp.de>
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are
  9. * met:
  10. *
  11. * * Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * * Redistributions in binary form must reproduce the above
  15. * copyright notice, this list of conditions and the following
  16. * disclaimer in the documentation and/or other materials provided
  17. * with the distribution.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. */
  31. #ifndef EV_STANDALONE
  32. # include "config.h"
  33. # if HAVE_CLOCK_GETTIME
  34. # define EV_USE_MONOTONIC 1
  35. # define EV_USE_REALTIME 1
  36. # endif
  37. # if HAVE_SELECT && HAVE_SYS_SELECT_H
  38. # define EV_USE_SELECT 1
  39. # endif
  40. # if HAVE_POLL && HAVE_POLL_H
  41. # define EV_USE_POLL 1
  42. # endif
  43. # if HAVE_EPOLL && HAVE_EPOLL_CTL && HAVE_SYS_EPOLL_H
  44. # define EV_USE_EPOLL 1
  45. # endif
  46. # if HAVE_KQUEUE && HAVE_WORKING_KQUEUE && HAVE_SYS_EVENT_H && HAVE_SYS_QUEUE_H
  47. # define EV_USE_KQUEUE 1
  48. # endif
  49. #endif
  50. #include <math.h>
  51. #include <stdlib.h>
  52. #include <unistd.h>
  53. #include <fcntl.h>
  54. #include <signal.h>
  55. #include <stddef.h>
  56. #include <stdio.h>
  57. #include <assert.h>
  58. #include <errno.h>
  59. #include <sys/types.h>
  60. #ifndef WIN32
  61. # include <sys/wait.h>
  62. #endif
  63. #include <sys/time.h>
  64. #include <time.h>
  65. /**/
  66. #ifndef EV_USE_MONOTONIC
  67. # define EV_USE_MONOTONIC 1
  68. #endif
  69. #ifndef EV_USE_SELECT
  70. # define EV_USE_SELECT 1
  71. #endif
  72. #ifndef EV_USE_POLL
  73. # define EV_USE_POLL 0 /* poll is usually slower than select, and not as well tested */
  74. #endif
  75. #ifndef EV_USE_EPOLL
  76. # define EV_USE_EPOLL 0
  77. #endif
  78. #ifndef EV_USE_KQUEUE
  79. # define EV_USE_KQUEUE 0
  80. #endif
  81. #ifndef EV_USE_WIN32
  82. # ifdef WIN32
  83. # define EV_USE_WIN32 1
  84. # else
  85. # define EV_USE_WIN32 0
  86. # endif
  87. #endif
  88. #ifndef EV_USE_REALTIME
  89. # define EV_USE_REALTIME 1
  90. #endif
  91. /**/
  92. #ifndef CLOCK_MONOTONIC
  93. # undef EV_USE_MONOTONIC
  94. # define EV_USE_MONOTONIC 0
  95. #endif
  96. #ifndef CLOCK_REALTIME
  97. # undef EV_USE_REALTIME
  98. # define EV_USE_REALTIME 0
  99. #endif
  100. /**/
  101. #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
  102. #define MAX_BLOCKTIME 59.731 /* never wait longer than this time (to detect time jumps) */
  103. #define PID_HASHSIZE 16 /* size of pid hash table, must be power of two */
  104. /*#define CLEANUP_INTERVAL 300. /* how often to try to free memory and re-check fds */
  105. #include "ev.h"
  106. #if __GNUC__ >= 3
  107. # define expect(expr,value) __builtin_expect ((expr),(value))
  108. # define inline inline
  109. #else
  110. # define expect(expr,value) (expr)
  111. # define inline static
  112. #endif
  113. #define expect_false(expr) expect ((expr) != 0, 0)
  114. #define expect_true(expr) expect ((expr) != 0, 1)
  115. #define NUMPRI (EV_MAXPRI - EV_MINPRI + 1)
  116. #define ABSPRI(w) ((w)->priority - EV_MINPRI)
  117. typedef struct ev_watcher *W;
  118. typedef struct ev_watcher_list *WL;
  119. typedef struct ev_watcher_time *WT;
  120. static int have_monotonic; /* did clock_gettime (CLOCK_MONOTONIC) work? */
  121. #if WIN32
  122. /* note: the comment below could not be substantiated, but what would I care */
  123. /* MSDN says this is required to handle SIGFPE */
  124. volatile double SIGFPE_REQ = 0.0f;
  125. #endif
  126. /*****************************************************************************/
  127. static void (*syserr_cb)(const char *msg);
  128. void ev_set_syserr_cb (void (*cb)(const char *msg))
  129. {
  130. syserr_cb = cb;
  131. }
  132. static void
  133. syserr (const char *msg)
  134. {
  135. if (!msg)
  136. msg = "(libev) system error";
  137. if (syserr_cb)
  138. syserr_cb (msg);
  139. else
  140. {
  141. perror (msg);
  142. abort ();
  143. }
  144. }
  145. static void *(*alloc)(void *ptr, long size);
  146. void ev_set_allocator (void *(*cb)(void *ptr, long size))
  147. {
  148. alloc = cb;
  149. }
  150. static void *
  151. ev_realloc (void *ptr, long size)
  152. {
  153. ptr = alloc ? alloc (ptr, size) : realloc (ptr, size);
  154. if (!ptr && size)
  155. {
  156. fprintf (stderr, "libev: cannot allocate %ld bytes, aborting.", size);
  157. abort ();
  158. }
  159. return ptr;
  160. }
  161. #define ev_malloc(size) ev_realloc (0, (size))
  162. #define ev_free(ptr) ev_realloc ((ptr), 0)
  163. /*****************************************************************************/
  164. typedef struct
  165. {
  166. WL head;
  167. unsigned char events;
  168. unsigned char reify;
  169. } ANFD;
  170. typedef struct
  171. {
  172. W w;
  173. int events;
  174. } ANPENDING;
  175. #if EV_MULTIPLICITY
  176. struct ev_loop
  177. {
  178. # define VAR(name,decl) decl;
  179. # include "ev_vars.h"
  180. };
  181. # undef VAR
  182. # include "ev_wrap.h"
  183. #else
  184. # define VAR(name,decl) static decl;
  185. # include "ev_vars.h"
  186. # undef VAR
  187. #endif
  188. /*****************************************************************************/
  189. inline ev_tstamp
  190. ev_time (void)
  191. {
  192. #if EV_USE_REALTIME
  193. struct timespec ts;
  194. clock_gettime (CLOCK_REALTIME, &ts);
  195. return ts.tv_sec + ts.tv_nsec * 1e-9;
  196. #else
  197. struct timeval tv;
  198. gettimeofday (&tv, 0);
  199. return tv.tv_sec + tv.tv_usec * 1e-6;
  200. #endif
  201. }
  202. inline ev_tstamp
  203. get_clock (void)
  204. {
  205. #if EV_USE_MONOTONIC
  206. if (expect_true (have_monotonic))
  207. {
  208. struct timespec ts;
  209. clock_gettime (CLOCK_MONOTONIC, &ts);
  210. return ts.tv_sec + ts.tv_nsec * 1e-9;
  211. }
  212. #endif
  213. return ev_time ();
  214. }
  215. ev_tstamp
  216. ev_now (EV_P)
  217. {
  218. return rt_now;
  219. }
  220. #define array_roundsize(base,n) ((n) | 4 & ~3)
  221. #define array_needsize(base,cur,cnt,init) \
  222. if (expect_false ((cnt) > cur)) \
  223. { \
  224. int newcnt = cur; \
  225. do \
  226. { \
  227. newcnt = array_roundsize (base, newcnt << 1); \
  228. } \
  229. while ((cnt) > newcnt); \
  230. \
  231. base = ev_realloc (base, sizeof (*base) * (newcnt)); \
  232. init (base + cur, newcnt - cur); \
  233. cur = newcnt; \
  234. }
  235. #define array_slim(stem) \
  236. if (stem ## max < array_roundsize (stem ## cnt >> 2)) \
  237. { \
  238. stem ## max = array_roundsize (stem ## cnt >> 1); \
  239. base = ev_realloc (base, sizeof (*base) * (stem ## max)); \
  240. fprintf (stderr, "slimmed down " # stem " to %d\n", stem ## max);/*D*/\
  241. }
  242. #define array_free(stem, idx) \
  243. ev_free (stem ## s idx); stem ## cnt idx = stem ## max idx = 0;
  244. /*****************************************************************************/
  245. static void
  246. anfds_init (ANFD *base, int count)
  247. {
  248. while (count--)
  249. {
  250. base->head = 0;
  251. base->events = EV_NONE;
  252. base->reify = 0;
  253. ++base;
  254. }
  255. }
  256. static void
  257. event (EV_P_ W w, int events)
  258. {
  259. if (w->pending)
  260. {
  261. pendings [ABSPRI (w)][w->pending - 1].events |= events;
  262. return;
  263. }
  264. w->pending = ++pendingcnt [ABSPRI (w)];
  265. array_needsize (pendings [ABSPRI (w)], pendingmax [ABSPRI (w)], pendingcnt [ABSPRI (w)], );
  266. pendings [ABSPRI (w)][w->pending - 1].w = w;
  267. pendings [ABSPRI (w)][w->pending - 1].events = events;
  268. }
  269. static void
  270. queue_events (EV_P_ W *events, int eventcnt, int type)
  271. {
  272. int i;
  273. for (i = 0; i < eventcnt; ++i)
  274. event (EV_A_ events [i], type);
  275. }
  276. static void
  277. fd_event (EV_P_ int fd, int events)
  278. {
  279. ANFD *anfd = anfds + fd;
  280. struct ev_io *w;
  281. for (w = (struct ev_io *)anfd->head; w; w = (struct ev_io *)((WL)w)->next)
  282. {
  283. int ev = w->events & events;
  284. if (ev)
  285. event (EV_A_ (W)w, ev);
  286. }
  287. }
  288. /*****************************************************************************/
  289. static void
  290. fd_reify (EV_P)
  291. {
  292. int i;
  293. for (i = 0; i < fdchangecnt; ++i)
  294. {
  295. int fd = fdchanges [i];
  296. ANFD *anfd = anfds + fd;
  297. struct ev_io *w;
  298. int events = 0;
  299. for (w = (struct ev_io *)anfd->head; w; w = (struct ev_io *)((WL)w)->next)
  300. events |= w->events;
  301. anfd->reify = 0;
  302. method_modify (EV_A_ fd, anfd->events, events);
  303. anfd->events = events;
  304. }
  305. fdchangecnt = 0;
  306. }
  307. static void
  308. fd_change (EV_P_ int fd)
  309. {
  310. if (anfds [fd].reify)
  311. return;
  312. anfds [fd].reify = 1;
  313. ++fdchangecnt;
  314. array_needsize (fdchanges, fdchangemax, fdchangecnt, );
  315. fdchanges [fdchangecnt - 1] = fd;
  316. }
  317. static void
  318. fd_kill (EV_P_ int fd)
  319. {
  320. struct ev_io *w;
  321. while ((w = (struct ev_io *)anfds [fd].head))
  322. {
  323. ev_io_stop (EV_A_ w);
  324. event (EV_A_ (W)w, EV_ERROR | EV_READ | EV_WRITE);
  325. }
  326. }
  327. /* called on EBADF to verify fds */
  328. static void
  329. fd_ebadf (EV_P)
  330. {
  331. int fd;
  332. for (fd = 0; fd < anfdmax; ++fd)
  333. if (anfds [fd].events)
  334. if (fcntl (fd, F_GETFD) == -1 && errno == EBADF)
  335. fd_kill (EV_A_ fd);
  336. }
  337. /* called on ENOMEM in select/poll to kill some fds and retry */
  338. static void
  339. fd_enomem (EV_P)
  340. {
  341. int fd;
  342. for (fd = anfdmax; fd--; )
  343. if (anfds [fd].events)
  344. {
  345. fd_kill (EV_A_ fd);
  346. return;
  347. }
  348. }
  349. /* usually called after fork if method needs to re-arm all fds from scratch */
  350. static void
  351. fd_rearm_all (EV_P)
  352. {
  353. int fd;
  354. /* this should be highly optimised to not do anything but set a flag */
  355. for (fd = 0; fd < anfdmax; ++fd)
  356. if (anfds [fd].events)
  357. {
  358. anfds [fd].events = 0;
  359. fd_change (EV_A_ fd);
  360. }
  361. }
  362. /*****************************************************************************/
  363. static void
  364. upheap (WT *heap, int k)
  365. {
  366. WT w = heap [k];
  367. while (k && heap [k >> 1]->at > w->at)
  368. {
  369. heap [k] = heap [k >> 1];
  370. ((W)heap [k])->active = k + 1;
  371. k >>= 1;
  372. }
  373. heap [k] = w;
  374. ((W)heap [k])->active = k + 1;
  375. }
  376. static void
  377. downheap (WT *heap, int N, int k)
  378. {
  379. WT w = heap [k];
  380. while (k < (N >> 1))
  381. {
  382. int j = k << 1;
  383. if (j + 1 < N && heap [j]->at > heap [j + 1]->at)
  384. ++j;
  385. if (w->at <= heap [j]->at)
  386. break;
  387. heap [k] = heap [j];
  388. ((W)heap [k])->active = k + 1;
  389. k = j;
  390. }
  391. heap [k] = w;
  392. ((W)heap [k])->active = k + 1;
  393. }
  394. /*****************************************************************************/
  395. typedef struct
  396. {
  397. WL head;
  398. sig_atomic_t volatile gotsig;
  399. } ANSIG;
  400. static ANSIG *signals;
  401. static int signalmax;
  402. static int sigpipe [2];
  403. static sig_atomic_t volatile gotsig;
  404. static struct ev_io sigev;
  405. static void
  406. signals_init (ANSIG *base, int count)
  407. {
  408. while (count--)
  409. {
  410. base->head = 0;
  411. base->gotsig = 0;
  412. ++base;
  413. }
  414. }
  415. static void
  416. sighandler (int signum)
  417. {
  418. #if WIN32
  419. signal (signum, sighandler);
  420. #endif
  421. signals [signum - 1].gotsig = 1;
  422. if (!gotsig)
  423. {
  424. int old_errno = errno;
  425. gotsig = 1;
  426. write (sigpipe [1], &signum, 1);
  427. errno = old_errno;
  428. }
  429. }
  430. static void
  431. sigcb (EV_P_ struct ev_io *iow, int revents)
  432. {
  433. WL w;
  434. int signum;
  435. read (sigpipe [0], &revents, 1);
  436. gotsig = 0;
  437. for (signum = signalmax; signum--; )
  438. if (signals [signum].gotsig)
  439. {
  440. signals [signum].gotsig = 0;
  441. for (w = signals [signum].head; w; w = w->next)
  442. event (EV_A_ (W)w, EV_SIGNAL);
  443. }
  444. }
  445. static void
  446. siginit (EV_P)
  447. {
  448. #ifndef WIN32
  449. fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
  450. fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
  451. /* rather than sort out wether we really need nb, set it */
  452. fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
  453. fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
  454. #endif
  455. ev_io_set (&sigev, sigpipe [0], EV_READ);
  456. ev_io_start (EV_A_ &sigev);
  457. ev_unref (EV_A); /* child watcher should not keep loop alive */
  458. }
  459. /*****************************************************************************/
  460. #ifndef WIN32
  461. static struct ev_child *childs [PID_HASHSIZE];
  462. static struct ev_signal childev;
  463. #ifndef WCONTINUED
  464. # define WCONTINUED 0
  465. #endif
  466. static void
  467. child_reap (EV_P_ struct ev_signal *sw, int chain, int pid, int status)
  468. {
  469. struct ev_child *w;
  470. for (w = (struct ev_child *)childs [chain & (PID_HASHSIZE - 1)]; w; w = (struct ev_child *)((WL)w)->next)
  471. if (w->pid == pid || !w->pid)
  472. {
  473. ev_priority (w) = ev_priority (sw); /* need to do it *now* */
  474. w->rpid = pid;
  475. w->rstatus = status;
  476. event (EV_A_ (W)w, EV_CHILD);
  477. }
  478. }
  479. static void
  480. childcb (EV_P_ struct ev_signal *sw, int revents)
  481. {
  482. int pid, status;
  483. if (0 < (pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)))
  484. {
  485. /* make sure we are called again until all childs have been reaped */
  486. event (EV_A_ (W)sw, EV_SIGNAL);
  487. child_reap (EV_A_ sw, pid, pid, status);
  488. child_reap (EV_A_ sw, 0, pid, status); /* this might trigger a watcher twice, but event catches that */
  489. }
  490. }
  491. #endif
  492. /*****************************************************************************/
  493. #if EV_USE_KQUEUE
  494. # include "ev_kqueue.c"
  495. #endif
  496. #if EV_USE_EPOLL
  497. # include "ev_epoll.c"
  498. #endif
  499. #if EV_USE_POLL
  500. # include "ev_poll.c"
  501. #endif
  502. #if EV_USE_SELECT
  503. # include "ev_select.c"
  504. #endif
  505. int
  506. ev_version_major (void)
  507. {
  508. return EV_VERSION_MAJOR;
  509. }
  510. int
  511. ev_version_minor (void)
  512. {
  513. return EV_VERSION_MINOR;
  514. }
  515. /* return true if we are running with elevated privileges and should ignore env variables */
  516. static int
  517. enable_secure (void)
  518. {
  519. #ifdef WIN32
  520. return 0;
  521. #else
  522. return getuid () != geteuid ()
  523. || getgid () != getegid ();
  524. #endif
  525. }
  526. int
  527. ev_method (EV_P)
  528. {
  529. return method;
  530. }
  531. static void
  532. loop_init (EV_P_ int methods)
  533. {
  534. if (!method)
  535. {
  536. #if EV_USE_MONOTONIC
  537. {
  538. struct timespec ts;
  539. if (!clock_gettime (CLOCK_MONOTONIC, &ts))
  540. have_monotonic = 1;
  541. }
  542. #endif
  543. rt_now = ev_time ();
  544. mn_now = get_clock ();
  545. now_floor = mn_now;
  546. rtmn_diff = rt_now - mn_now;
  547. if (methods == EVMETHOD_AUTO)
  548. if (!enable_secure () && getenv ("LIBEV_METHODS"))
  549. methods = atoi (getenv ("LIBEV_METHODS"));
  550. else
  551. methods = EVMETHOD_ANY;
  552. method = 0;
  553. #if EV_USE_WIN32
  554. if (!method && (methods & EVMETHOD_WIN32 )) method = win32_init (EV_A_ methods);
  555. #endif
  556. #if EV_USE_KQUEUE
  557. if (!method && (methods & EVMETHOD_KQUEUE)) method = kqueue_init (EV_A_ methods);
  558. #endif
  559. #if EV_USE_EPOLL
  560. if (!method && (methods & EVMETHOD_EPOLL )) method = epoll_init (EV_A_ methods);
  561. #endif
  562. #if EV_USE_POLL
  563. if (!method && (methods & EVMETHOD_POLL )) method = poll_init (EV_A_ methods);
  564. #endif
  565. #if EV_USE_SELECT
  566. if (!method && (methods & EVMETHOD_SELECT)) method = select_init (EV_A_ methods);
  567. #endif
  568. ev_watcher_init (&sigev, sigcb);
  569. ev_set_priority (&sigev, EV_MAXPRI);
  570. }
  571. }
  572. void
  573. loop_destroy (EV_P)
  574. {
  575. int i;
  576. #if EV_USE_WIN32
  577. if (method == EVMETHOD_WIN32 ) win32_destroy (EV_A);
  578. #endif
  579. #if EV_USE_KQUEUE
  580. if (method == EVMETHOD_KQUEUE) kqueue_destroy (EV_A);
  581. #endif
  582. #if EV_USE_EPOLL
  583. if (method == EVMETHOD_EPOLL ) epoll_destroy (EV_A);
  584. #endif
  585. #if EV_USE_POLL
  586. if (method == EVMETHOD_POLL ) poll_destroy (EV_A);
  587. #endif
  588. #if EV_USE_SELECT
  589. if (method == EVMETHOD_SELECT) select_destroy (EV_A);
  590. #endif
  591. for (i = NUMPRI; i--; )
  592. array_free (pending, [i]);
  593. array_free (fdchange, );
  594. array_free (timer, );
  595. array_free (periodic, );
  596. array_free (idle, );
  597. array_free (prepare, );
  598. array_free (check, );
  599. method = 0;
  600. }
  601. static void
  602. loop_fork (EV_P)
  603. {
  604. #if EV_USE_EPOLL
  605. if (method == EVMETHOD_EPOLL ) epoll_fork (EV_A);
  606. #endif
  607. #if EV_USE_KQUEUE
  608. if (method == EVMETHOD_KQUEUE) kqueue_fork (EV_A);
  609. #endif
  610. if (ev_is_active (&sigev))
  611. {
  612. /* default loop */
  613. ev_ref (EV_A);
  614. ev_io_stop (EV_A_ &sigev);
  615. close (sigpipe [0]);
  616. close (sigpipe [1]);
  617. while (pipe (sigpipe))
  618. syserr ("(libev) error creating pipe");
  619. siginit (EV_A);
  620. }
  621. postfork = 0;
  622. }
  623. #if EV_MULTIPLICITY
  624. struct ev_loop *
  625. ev_loop_new (int methods)
  626. {
  627. struct ev_loop *loop = (struct ev_loop *)ev_malloc (sizeof (struct ev_loop));
  628. memset (loop, 0, sizeof (struct ev_loop));
  629. loop_init (EV_A_ methods);
  630. if (ev_method (EV_A))
  631. return loop;
  632. return 0;
  633. }
  634. void
  635. ev_loop_destroy (EV_P)
  636. {
  637. loop_destroy (EV_A);
  638. ev_free (loop);
  639. }
  640. void
  641. ev_loop_fork (EV_P)
  642. {
  643. postfork = 1;
  644. }
  645. #endif
  646. #if EV_MULTIPLICITY
  647. struct ev_loop default_loop_struct;
  648. static struct ev_loop *default_loop;
  649. struct ev_loop *
  650. #else
  651. static int default_loop;
  652. int
  653. #endif
  654. ev_default_loop (int methods)
  655. {
  656. if (sigpipe [0] == sigpipe [1])
  657. if (pipe (sigpipe))
  658. return 0;
  659. if (!default_loop)
  660. {
  661. #if EV_MULTIPLICITY
  662. struct ev_loop *loop = default_loop = &default_loop_struct;
  663. #else
  664. default_loop = 1;
  665. #endif
  666. loop_init (EV_A_ methods);
  667. if (ev_method (EV_A))
  668. {
  669. siginit (EV_A);
  670. #ifndef WIN32
  671. ev_signal_init (&childev, childcb, SIGCHLD);
  672. ev_set_priority (&childev, EV_MAXPRI);
  673. ev_signal_start (EV_A_ &childev);
  674. ev_unref (EV_A); /* child watcher should not keep loop alive */
  675. #endif
  676. }
  677. else
  678. default_loop = 0;
  679. }
  680. return default_loop;
  681. }
  682. void
  683. ev_default_destroy (void)
  684. {
  685. #if EV_MULTIPLICITY
  686. struct ev_loop *loop = default_loop;
  687. #endif
  688. ev_ref (EV_A); /* child watcher */
  689. ev_signal_stop (EV_A_ &childev);
  690. ev_ref (EV_A); /* signal watcher */
  691. ev_io_stop (EV_A_ &sigev);
  692. close (sigpipe [0]); sigpipe [0] = 0;
  693. close (sigpipe [1]); sigpipe [1] = 0;
  694. loop_destroy (EV_A);
  695. }
  696. void
  697. ev_default_fork (void)
  698. {
  699. #if EV_MULTIPLICITY
  700. struct ev_loop *loop = default_loop;
  701. #endif
  702. if (method)
  703. postfork = 1;
  704. }
  705. /*****************************************************************************/
  706. static void
  707. call_pending (EV_P)
  708. {
  709. int pri;
  710. for (pri = NUMPRI; pri--; )
  711. while (pendingcnt [pri])
  712. {
  713. ANPENDING *p = pendings [pri] + --pendingcnt [pri];
  714. if (p->w)
  715. {
  716. p->w->pending = 0;
  717. p->w->cb (EV_A_ p->w, p->events);
  718. }
  719. }
  720. }
  721. static void
  722. timers_reify (EV_P)
  723. {
  724. while (timercnt && ((WT)timers [0])->at <= mn_now)
  725. {
  726. struct ev_timer *w = timers [0];
  727. assert (("inactive timer on timer heap detected", ev_is_active (w)));
  728. /* first reschedule or stop timer */
  729. if (w->repeat)
  730. {
  731. assert (("negative ev_timer repeat value found while processing timers", w->repeat > 0.));
  732. ((WT)w)->at = mn_now + w->repeat;
  733. downheap ((WT *)timers, timercnt, 0);
  734. }
  735. else
  736. ev_timer_stop (EV_A_ w); /* nonrepeating: stop timer */
  737. event (EV_A_ (W)w, EV_TIMEOUT);
  738. }
  739. }
  740. static void
  741. periodics_reify (EV_P)
  742. {
  743. while (periodiccnt && ((WT)periodics [0])->at <= rt_now)
  744. {
  745. struct ev_periodic *w = periodics [0];
  746. assert (("inactive timer on periodic heap detected", ev_is_active (w)));
  747. /* first reschedule or stop timer */
  748. if (w->interval)
  749. {
  750. ((WT)w)->at += floor ((rt_now - ((WT)w)->at) / w->interval + 1.) * w->interval;
  751. assert (("ev_periodic timeout in the past detected while processing timers, negative interval?", ((WT)w)->at > rt_now));
  752. downheap ((WT *)periodics, periodiccnt, 0);
  753. }
  754. else
  755. ev_periodic_stop (EV_A_ w); /* nonrepeating: stop timer */
  756. event (EV_A_ (W)w, EV_PERIODIC);
  757. }
  758. }
  759. static void
  760. periodics_reschedule (EV_P)
  761. {
  762. int i;
  763. /* adjust periodics after time jump */
  764. for (i = 0; i < periodiccnt; ++i)
  765. {
  766. struct ev_periodic *w = periodics [i];
  767. if (w->interval)
  768. {
  769. ev_tstamp diff = ceil ((rt_now - ((WT)w)->at) / w->interval) * w->interval;
  770. if (fabs (diff) >= 1e-4)
  771. {
  772. ev_periodic_stop (EV_A_ w);
  773. ev_periodic_start (EV_A_ w);
  774. i = 0; /* restart loop, inefficient, but time jumps should be rare */
  775. }
  776. }
  777. }
  778. }
  779. inline int
  780. time_update_monotonic (EV_P)
  781. {
  782. mn_now = get_clock ();
  783. if (expect_true (mn_now - now_floor < MIN_TIMEJUMP * .5))
  784. {
  785. rt_now = rtmn_diff + mn_now;
  786. return 0;
  787. }
  788. else
  789. {
  790. now_floor = mn_now;
  791. rt_now = ev_time ();
  792. return 1;
  793. }
  794. }
  795. static void
  796. time_update (EV_P)
  797. {
  798. int i;
  799. #if EV_USE_MONOTONIC
  800. if (expect_true (have_monotonic))
  801. {
  802. if (time_update_monotonic (EV_A))
  803. {
  804. ev_tstamp odiff = rtmn_diff;
  805. for (i = 4; --i; ) /* loop a few times, before making important decisions */
  806. {
  807. rtmn_diff = rt_now - mn_now;
  808. if (fabs (odiff - rtmn_diff) < MIN_TIMEJUMP)
  809. return; /* all is well */
  810. rt_now = ev_time ();
  811. mn_now = get_clock ();
  812. now_floor = mn_now;
  813. }
  814. periodics_reschedule (EV_A);
  815. /* no timer adjustment, as the monotonic clock doesn't jump */
  816. /* timers_reschedule (EV_A_ rtmn_diff - odiff) */
  817. }
  818. }
  819. else
  820. #endif
  821. {
  822. rt_now = ev_time ();
  823. if (expect_false (mn_now > rt_now || mn_now < rt_now - MAX_BLOCKTIME - MIN_TIMEJUMP))
  824. {
  825. periodics_reschedule (EV_A);
  826. /* adjust timers. this is easy, as the offset is the same for all */
  827. for (i = 0; i < timercnt; ++i)
  828. ((WT)timers [i])->at += rt_now - mn_now;
  829. }
  830. mn_now = rt_now;
  831. }
  832. }
  833. void
  834. ev_ref (EV_P)
  835. {
  836. ++activecnt;
  837. }
  838. void
  839. ev_unref (EV_P)
  840. {
  841. --activecnt;
  842. }
  843. static int loop_done;
  844. void
  845. ev_loop (EV_P_ int flags)
  846. {
  847. double block;
  848. loop_done = flags & (EVLOOP_ONESHOT | EVLOOP_NONBLOCK) ? 1 : 0;
  849. do
  850. {
  851. /* queue check watchers (and execute them) */
  852. if (expect_false (preparecnt))
  853. {
  854. queue_events (EV_A_ (W *)prepares, preparecnt, EV_PREPARE);
  855. call_pending (EV_A);
  856. }
  857. /* we might have forked, so reify kernel state if necessary */
  858. if (expect_false (postfork))
  859. loop_fork (EV_A);
  860. /* update fd-related kernel structures */
  861. fd_reify (EV_A);
  862. /* calculate blocking time */
  863. /* we only need this for !monotonic clockor timers, but as we basically
  864. always have timers, we just calculate it always */
  865. #if EV_USE_MONOTONIC
  866. if (expect_true (have_monotonic))
  867. time_update_monotonic (EV_A);
  868. else
  869. #endif
  870. {
  871. rt_now = ev_time ();
  872. mn_now = rt_now;
  873. }
  874. if (flags & EVLOOP_NONBLOCK || idlecnt)
  875. block = 0.;
  876. else
  877. {
  878. block = MAX_BLOCKTIME;
  879. if (timercnt)
  880. {
  881. ev_tstamp to = ((WT)timers [0])->at - mn_now + method_fudge;
  882. if (block > to) block = to;
  883. }
  884. if (periodiccnt)
  885. {
  886. ev_tstamp to = ((WT)periodics [0])->at - rt_now + method_fudge;
  887. if (block > to) block = to;
  888. }
  889. if (block < 0.) block = 0.;
  890. }
  891. method_poll (EV_A_ block);
  892. /* update rt_now, do magic */
  893. time_update (EV_A);
  894. /* queue pending timers and reschedule them */
  895. timers_reify (EV_A); /* relative timers called last */
  896. periodics_reify (EV_A); /* absolute timers called first */
  897. /* queue idle watchers unless io or timers are pending */
  898. if (!pendingcnt)
  899. queue_events (EV_A_ (W *)idles, idlecnt, EV_IDLE);
  900. /* queue check watchers, to be executed first */
  901. if (checkcnt)
  902. queue_events (EV_A_ (W *)checks, checkcnt, EV_CHECK);
  903. call_pending (EV_A);
  904. }
  905. while (activecnt && !loop_done);
  906. if (loop_done != 2)
  907. loop_done = 0;
  908. }
  909. void
  910. ev_unloop (EV_P_ int how)
  911. {
  912. loop_done = how;
  913. }
  914. /*****************************************************************************/
  915. inline void
  916. wlist_add (WL *head, WL elem)
  917. {
  918. elem->next = *head;
  919. *head = elem;
  920. }
  921. inline void
  922. wlist_del (WL *head, WL elem)
  923. {
  924. while (*head)
  925. {
  926. if (*head == elem)
  927. {
  928. *head = elem->next;
  929. return;
  930. }
  931. head = &(*head)->next;
  932. }
  933. }
  934. inline void
  935. ev_clear_pending (EV_P_ W w)
  936. {
  937. if (w->pending)
  938. {
  939. pendings [ABSPRI (w)][w->pending - 1].w = 0;
  940. w->pending = 0;
  941. }
  942. }
  943. inline void
  944. ev_start (EV_P_ W w, int active)
  945. {
  946. if (w->priority < EV_MINPRI) w->priority = EV_MINPRI;
  947. if (w->priority > EV_MAXPRI) w->priority = EV_MAXPRI;
  948. w->active = active;
  949. ev_ref (EV_A);
  950. }
  951. inline void
  952. ev_stop (EV_P_ W w)
  953. {
  954. ev_unref (EV_A);
  955. w->active = 0;
  956. }
  957. /*****************************************************************************/
  958. void
  959. ev_io_start (EV_P_ struct ev_io *w)
  960. {
  961. int fd = w->fd;
  962. if (ev_is_active (w))
  963. return;
  964. assert (("ev_io_start called with negative fd", fd >= 0));
  965. ev_start (EV_A_ (W)w, 1);
  966. array_needsize (anfds, anfdmax, fd + 1, anfds_init);
  967. wlist_add ((WL *)&anfds[fd].head, (WL)w);
  968. fd_change (EV_A_ fd);
  969. }
  970. void
  971. ev_io_stop (EV_P_ struct ev_io *w)
  972. {
  973. ev_clear_pending (EV_A_ (W)w);
  974. if (!ev_is_active (w))
  975. return;
  976. wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
  977. ev_stop (EV_A_ (W)w);
  978. fd_change (EV_A_ w->fd);
  979. }
  980. void
  981. ev_timer_start (EV_P_ struct ev_timer *w)
  982. {
  983. if (ev_is_active (w))
  984. return;
  985. ((WT)w)->at += mn_now;
  986. assert (("ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
  987. ev_start (EV_A_ (W)w, ++timercnt);
  988. array_needsize (timers, timermax, timercnt, );
  989. timers [timercnt - 1] = w;
  990. upheap ((WT *)timers, timercnt - 1);
  991. assert (("internal timer heap corruption", timers [((W)w)->active - 1] == w));
  992. }
  993. void
  994. ev_timer_stop (EV_P_ struct ev_timer *w)
  995. {
  996. ev_clear_pending (EV_A_ (W)w);
  997. if (!ev_is_active (w))
  998. return;
  999. assert (("internal timer heap corruption", timers [((W)w)->active - 1] == w));
  1000. if (((W)w)->active < timercnt--)
  1001. {
  1002. timers [((W)w)->active - 1] = timers [timercnt];
  1003. downheap ((WT *)timers, timercnt, ((W)w)->active - 1);
  1004. }
  1005. ((WT)w)->at = w->repeat;
  1006. ev_stop (EV_A_ (W)w);
  1007. }
  1008. void
  1009. ev_timer_again (EV_P_ struct ev_timer *w)
  1010. {
  1011. if (ev_is_active (w))
  1012. {
  1013. if (w->repeat)
  1014. {
  1015. ((WT)w)->at = mn_now + w->repeat;
  1016. downheap ((WT *)timers, timercnt, ((W)w)->active - 1);
  1017. }
  1018. else
  1019. ev_timer_stop (EV_A_ w);
  1020. }
  1021. else if (w->repeat)
  1022. ev_timer_start (EV_A_ w);
  1023. }
  1024. void
  1025. ev_periodic_start (EV_P_ struct ev_periodic *w)
  1026. {
  1027. if (ev_is_active (w))
  1028. return;
  1029. assert (("ev_periodic_start called with negative interval value", w->interval >= 0.));
  1030. /* this formula differs from the one in periodic_reify because we do not always round up */
  1031. if (w->interval)
  1032. ((WT)w)->at += ceil ((rt_now - ((WT)w)->at) / w->interval) * w->interval;
  1033. ev_start (EV_A_ (W)w, ++periodiccnt);
  1034. array_needsize (periodics, periodicmax, periodiccnt, );
  1035. periodics [periodiccnt - 1] = w;
  1036. upheap ((WT *)periodics, periodiccnt - 1);
  1037. assert (("internal periodic heap corruption", periodics [((W)w)->active - 1] == w));
  1038. }
  1039. void
  1040. ev_periodic_stop (EV_P_ struct ev_periodic *w)
  1041. {
  1042. ev_clear_pending (EV_A_ (W)w);
  1043. if (!ev_is_active (w))
  1044. return;
  1045. assert (("internal periodic heap corruption", periodics [((W)w)->active - 1] == w));
  1046. if (((W)w)->active < periodiccnt--)
  1047. {
  1048. periodics [((W)w)->active - 1] = periodics [periodiccnt];
  1049. downheap ((WT *)periodics, periodiccnt, ((W)w)->active - 1);
  1050. }
  1051. ev_stop (EV_A_ (W)w);
  1052. }
  1053. void
  1054. ev_idle_start (EV_P_ struct ev_idle *w)
  1055. {
  1056. if (ev_is_active (w))
  1057. return;
  1058. ev_start (EV_A_ (W)w, ++idlecnt);
  1059. array_needsize (idles, idlemax, idlecnt, );
  1060. idles [idlecnt - 1] = w;
  1061. }
  1062. void
  1063. ev_idle_stop (EV_P_ struct ev_idle *w)
  1064. {
  1065. ev_clear_pending (EV_A_ (W)w);
  1066. if (ev_is_active (w))
  1067. return;
  1068. idles [((W)w)->active - 1] = idles [--idlecnt];
  1069. ev_stop (EV_A_ (W)w);
  1070. }
  1071. void
  1072. ev_prepare_start (EV_P_ struct ev_prepare *w)
  1073. {
  1074. if (ev_is_active (w))
  1075. return;
  1076. ev_start (EV_A_ (W)w, ++preparecnt);
  1077. array_needsize (prepares, preparemax, preparecnt, );
  1078. prepares [preparecnt - 1] = w;
  1079. }
  1080. void
  1081. ev_prepare_stop (EV_P_ struct ev_prepare *w)
  1082. {
  1083. ev_clear_pending (EV_A_ (W)w);
  1084. if (ev_is_active (w))
  1085. return;
  1086. prepares [((W)w)->active - 1] = prepares [--preparecnt];
  1087. ev_stop (EV_A_ (W)w);
  1088. }
  1089. void
  1090. ev_check_start (EV_P_ struct ev_check *w)
  1091. {
  1092. if (ev_is_active (w))
  1093. return;
  1094. ev_start (EV_A_ (W)w, ++checkcnt);
  1095. array_needsize (checks, checkmax, checkcnt, );
  1096. checks [checkcnt - 1] = w;
  1097. }
  1098. void
  1099. ev_check_stop (EV_P_ struct ev_check *w)
  1100. {
  1101. ev_clear_pending (EV_A_ (W)w);
  1102. if (ev_is_active (w))
  1103. return;
  1104. checks [((W)w)->active - 1] = checks [--checkcnt];
  1105. ev_stop (EV_A_ (W)w);
  1106. }
  1107. #ifndef SA_RESTART
  1108. # define SA_RESTART 0
  1109. #endif
  1110. void
  1111. ev_signal_start (EV_P_ struct ev_signal *w)
  1112. {
  1113. #if EV_MULTIPLICITY
  1114. assert (("signal watchers are only supported in the default loop", loop == default_loop));
  1115. #endif
  1116. if (ev_is_active (w))
  1117. return;
  1118. assert (("ev_signal_start called with illegal signal number", w->signum > 0));
  1119. ev_start (EV_A_ (W)w, 1);
  1120. array_needsize (signals, signalmax, w->signum, signals_init);
  1121. wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
  1122. if (!((WL)w)->next)
  1123. {
  1124. #if WIN32
  1125. signal (w->signum, sighandler);
  1126. #else
  1127. struct sigaction sa;
  1128. sa.sa_handler = sighandler;
  1129. sigfillset (&sa.sa_mask);
  1130. sa.sa_flags = SA_RESTART; /* if restarting works we save one iteration */
  1131. sigaction (w->signum, &sa, 0);
  1132. #endif
  1133. }
  1134. }
  1135. void
  1136. ev_signal_stop (EV_P_ struct ev_signal *w)
  1137. {
  1138. ev_clear_pending (EV_A_ (W)w);
  1139. if (!ev_is_active (w))
  1140. return;
  1141. wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
  1142. ev_stop (EV_A_ (W)w);
  1143. if (!signals [w->signum - 1].head)
  1144. signal (w->signum, SIG_DFL);
  1145. }
  1146. void
  1147. ev_child_start (EV_P_ struct ev_child *w)
  1148. {
  1149. #if EV_MULTIPLICITY
  1150. assert (("child watchers are only supported in the default loop", loop == default_loop));
  1151. #endif
  1152. if (ev_is_active (w))
  1153. return;
  1154. ev_start (EV_A_ (W)w, 1);
  1155. wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
  1156. }
  1157. void
  1158. ev_child_stop (EV_P_ struct ev_child *w)
  1159. {
  1160. ev_clear_pending (EV_A_ (W)w);
  1161. if (ev_is_active (w))
  1162. return;
  1163. wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
  1164. ev_stop (EV_A_ (W)w);
  1165. }
  1166. /*****************************************************************************/
  1167. struct ev_once
  1168. {
  1169. struct ev_io io;
  1170. struct ev_timer to;
  1171. void (*cb)(int revents, void *arg);
  1172. void *arg;
  1173. };
  1174. static void
  1175. once_cb (EV_P_ struct ev_once *once, int revents)
  1176. {
  1177. void (*cb)(int revents, void *arg) = once->cb;
  1178. void *arg = once->arg;
  1179. ev_io_stop (EV_A_ &once->io);
  1180. ev_timer_stop (EV_A_ &once->to);
  1181. ev_free (once);
  1182. cb (revents, arg);
  1183. }
  1184. static void
  1185. once_cb_io (EV_P_ struct ev_io *w, int revents)
  1186. {
  1187. once_cb (EV_A_ (struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
  1188. }
  1189. static void
  1190. once_cb_to (EV_P_ struct ev_timer *w, int revents)
  1191. {
  1192. once_cb (EV_A_ (struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
  1193. }
  1194. void
  1195. ev_once (EV_P_ int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
  1196. {
  1197. struct ev_once *once = ev_malloc (sizeof (struct ev_once));
  1198. if (!once)
  1199. cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT, arg);
  1200. else
  1201. {
  1202. once->cb = cb;
  1203. once->arg = arg;
  1204. ev_watcher_init (&once->io, once_cb_io);
  1205. if (fd >= 0)
  1206. {
  1207. ev_io_set (&once->io, fd, events);
  1208. ev_io_start (EV_A_ &once->io);
  1209. }
  1210. ev_watcher_init (&once->to, once_cb_to);
  1211. if (timeout >= 0.)
  1212. {
  1213. ev_timer_set (&once->to, timeout, 0.);
  1214. ev_timer_start (EV_A_ &once->to);
  1215. }
  1216. }
  1217. }