PageRenderTime 70ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/src/libev/ev.c

http://github.com/jacksonh/manos
C | 3878 lines | 2930 code | 703 blank | 245 comment | 505 complexity | 8beea16dda02c1d1b8b9d1c7d1de7e57 MD5 | raw file
Possible License(s): BSD-2-Clause
  1. /*
  2. * libev event processing core, watcher management
  3. *
  4. * Copyright (c) 2007,2008,2009,2010,2011 Marc Alexander Lehmann <libev@schmorp.de>
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without modifica-
  8. * tion, are permitted provided that the following conditions are met:
  9. *
  10. * 1. Redistributions of source code must retain the above copyright notice,
  11. * this list of conditions and the following disclaimer.
  12. *
  13. * 2. 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. *
  17. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  18. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
  19. * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  20. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
  21. * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  22. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  23. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  24. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
  25. * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  26. * OF THE POSSIBILITY OF SUCH DAMAGE.
  27. *
  28. * Alternatively, the contents of this file may be used under the terms of
  29. * the GNU General Public License ("GPL") version 2 or any later version,
  30. * in which case the provisions of the GPL are applicable instead of
  31. * the above. If you wish to allow the use of your version of this file
  32. * only under the terms of the GPL and not to allow others to use your
  33. * version of this file under the BSD license, indicate your decision
  34. * by deleting the provisions above and replace them with the notice
  35. * and other provisions required by the GPL. If you do not delete the
  36. * provisions above, a recipient may use your version of this file under
  37. * either the BSD or the GPL.
  38. */
  39. /* this big block deduces configuration from config.h */
  40. #ifndef EV_STANDALONE
  41. # ifdef EV_CONFIG_H
  42. # include EV_CONFIG_H
  43. # else
  44. # include "config.h"
  45. # endif
  46. # if HAVE_CLOCK_SYSCALL
  47. # ifndef EV_USE_CLOCK_SYSCALL
  48. # define EV_USE_CLOCK_SYSCALL 1
  49. # ifndef EV_USE_REALTIME
  50. # define EV_USE_REALTIME 0
  51. # endif
  52. # ifndef EV_USE_MONOTONIC
  53. # define EV_USE_MONOTONIC 1
  54. # endif
  55. # endif
  56. # elif !defined(EV_USE_CLOCK_SYSCALL)
  57. # define EV_USE_CLOCK_SYSCALL 0
  58. # endif
  59. # if HAVE_CLOCK_GETTIME
  60. # ifndef EV_USE_MONOTONIC
  61. # define EV_USE_MONOTONIC 1
  62. # endif
  63. # ifndef EV_USE_REALTIME
  64. # define EV_USE_REALTIME 0
  65. # endif
  66. # else
  67. # ifndef EV_USE_MONOTONIC
  68. # define EV_USE_MONOTONIC 0
  69. # endif
  70. # ifndef EV_USE_REALTIME
  71. # define EV_USE_REALTIME 0
  72. # endif
  73. # endif
  74. # if HAVE_NANOSLEEP
  75. # ifndef EV_USE_NANOSLEEP
  76. # define EV_USE_NANOSLEEP EV_FEATURE_OS
  77. # endif
  78. # else
  79. # undef EV_USE_NANOSLEEP
  80. # define EV_USE_NANOSLEEP 0
  81. # endif
  82. # if HAVE_SELECT && HAVE_SYS_SELECT_H
  83. # ifndef EV_USE_SELECT
  84. # define EV_USE_SELECT EV_FEATURE_BACKENDS
  85. # endif
  86. # else
  87. # undef EV_USE_SELECT
  88. # define EV_USE_SELECT 0
  89. # endif
  90. # if HAVE_POLL && HAVE_POLL_H
  91. # ifndef EV_USE_POLL
  92. # define EV_USE_POLL EV_FEATURE_BACKENDS
  93. # endif
  94. # else
  95. # undef EV_USE_POLL
  96. # define EV_USE_POLL 0
  97. # endif
  98. # if HAVE_EPOLL_CTL && HAVE_SYS_EPOLL_H
  99. # ifndef EV_USE_EPOLL
  100. # define EV_USE_EPOLL EV_FEATURE_BACKENDS
  101. # endif
  102. # else
  103. # undef EV_USE_EPOLL
  104. # define EV_USE_EPOLL 0
  105. # endif
  106. # if HAVE_KQUEUE && HAVE_SYS_EVENT_H
  107. # ifndef EV_USE_KQUEUE
  108. # define EV_USE_KQUEUE EV_FEATURE_BACKENDS
  109. # endif
  110. # else
  111. # undef EV_USE_KQUEUE
  112. # define EV_USE_KQUEUE 0
  113. # endif
  114. # if HAVE_PORT_H && HAVE_PORT_CREATE
  115. # ifndef EV_USE_PORT
  116. # define EV_USE_PORT EV_FEATURE_BACKENDS
  117. # endif
  118. # else
  119. # undef EV_USE_PORT
  120. # define EV_USE_PORT 0
  121. # endif
  122. # if HAVE_INOTIFY_INIT && HAVE_SYS_INOTIFY_H
  123. # ifndef EV_USE_INOTIFY
  124. # define EV_USE_INOTIFY EV_FEATURE_OS
  125. # endif
  126. # else
  127. # undef EV_USE_INOTIFY
  128. # define EV_USE_INOTIFY 0
  129. # endif
  130. # if HAVE_SIGNALFD && HAVE_SYS_SIGNALFD_H
  131. # ifndef EV_USE_SIGNALFD
  132. # define EV_USE_SIGNALFD EV_FEATURE_OS
  133. # endif
  134. # else
  135. # undef EV_USE_SIGNALFD
  136. # define EV_USE_SIGNALFD 0
  137. # endif
  138. # if HAVE_EVENTFD
  139. # ifndef EV_USE_EVENTFD
  140. # define EV_USE_EVENTFD EV_FEATURE_OS
  141. # endif
  142. # else
  143. # undef EV_USE_EVENTFD
  144. # define EV_USE_EVENTFD 0
  145. # endif
  146. #endif
  147. #include <math.h>
  148. #include <stdlib.h>
  149. #include <string.h>
  150. #include <fcntl.h>
  151. #include <stddef.h>
  152. #include <stdio.h>
  153. #include <assert.h>
  154. #include <errno.h>
  155. #include <sys/types.h>
  156. #include <time.h>
  157. #include <limits.h>
  158. #include <signal.h>
  159. #ifdef EV_H
  160. # include EV_H
  161. #else
  162. # include "ev.h"
  163. #endif
  164. EV_CPP(extern "C" {)
  165. #ifndef _WIN32
  166. # include <sys/time.h>
  167. # include <sys/wait.h>
  168. # include <unistd.h>
  169. #else
  170. # include <io.h>
  171. # define WIN32_LEAN_AND_MEAN
  172. # include <windows.h>
  173. # ifndef EV_SELECT_IS_WINSOCKET
  174. # define EV_SELECT_IS_WINSOCKET 1
  175. # endif
  176. # undef EV_AVOID_STDIO
  177. #endif
  178. /* OS X, in its infinite idiocy, actually HARDCODES
  179. * a limit of 1024 into their select. Where people have brains,
  180. * OS X engineers apparently have a vacuum. Or maybe they were
  181. * ordered to have a vacuum, or they do anything for money.
  182. * This might help. Or not.
  183. */
  184. #define _DARWIN_UNLIMITED_SELECT 1
  185. /* this block tries to deduce configuration from header-defined symbols and defaults */
  186. /* try to deduce the maximum number of signals on this platform */
  187. #if defined (EV_NSIG)
  188. /* use what's provided */
  189. #elif defined (NSIG)
  190. # define EV_NSIG (NSIG)
  191. #elif defined(_NSIG)
  192. # define EV_NSIG (_NSIG)
  193. #elif defined (SIGMAX)
  194. # define EV_NSIG (SIGMAX+1)
  195. #elif defined (SIG_MAX)
  196. # define EV_NSIG (SIG_MAX+1)
  197. #elif defined (_SIG_MAX)
  198. # define EV_NSIG (_SIG_MAX+1)
  199. #elif defined (MAXSIG)
  200. # define EV_NSIG (MAXSIG+1)
  201. #elif defined (MAX_SIG)
  202. # define EV_NSIG (MAX_SIG+1)
  203. #elif defined (SIGARRAYSIZE)
  204. # define EV_NSIG (SIGARRAYSIZE) /* Assume ary[SIGARRAYSIZE] */
  205. #elif defined (_sys_nsig)
  206. # define EV_NSIG (_sys_nsig) /* Solaris 2.5 */
  207. #else
  208. # error "unable to find value for NSIG, please report"
  209. /* to make it compile regardless, just remove the above line, */
  210. /* but consider reporting it, too! :) */
  211. # define EV_NSIG 65
  212. #endif
  213. #ifndef EV_USE_CLOCK_SYSCALL
  214. # if __linux && __GLIBC__ >= 2
  215. # define EV_USE_CLOCK_SYSCALL EV_FEATURE_OS
  216. # else
  217. # define EV_USE_CLOCK_SYSCALL 0
  218. # endif
  219. #endif
  220. #ifndef EV_USE_MONOTONIC
  221. # if defined (_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
  222. # define EV_USE_MONOTONIC EV_FEATURE_OS
  223. # else
  224. # define EV_USE_MONOTONIC 0
  225. # endif
  226. #endif
  227. #ifndef EV_USE_REALTIME
  228. # define EV_USE_REALTIME !EV_USE_CLOCK_SYSCALL
  229. #endif
  230. #ifndef EV_USE_NANOSLEEP
  231. # if _POSIX_C_SOURCE >= 199309L
  232. # define EV_USE_NANOSLEEP EV_FEATURE_OS
  233. # else
  234. # define EV_USE_NANOSLEEP 0
  235. # endif
  236. #endif
  237. #ifndef EV_USE_SELECT
  238. # define EV_USE_SELECT EV_FEATURE_BACKENDS
  239. #endif
  240. #ifndef EV_USE_POLL
  241. # ifdef _WIN32
  242. # define EV_USE_POLL 0
  243. # else
  244. # define EV_USE_POLL EV_FEATURE_BACKENDS
  245. # endif
  246. #endif
  247. #ifndef EV_USE_EPOLL
  248. # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 4))
  249. # define EV_USE_EPOLL EV_FEATURE_BACKENDS
  250. # else
  251. # define EV_USE_EPOLL 0
  252. # endif
  253. #endif
  254. #ifndef EV_USE_KQUEUE
  255. # define EV_USE_KQUEUE 0
  256. #endif
  257. #ifndef EV_USE_PORT
  258. # define EV_USE_PORT 0
  259. #endif
  260. #ifndef EV_USE_INOTIFY
  261. # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 4))
  262. # define EV_USE_INOTIFY EV_FEATURE_OS
  263. # else
  264. # define EV_USE_INOTIFY 0
  265. # endif
  266. #endif
  267. #ifndef EV_PID_HASHSIZE
  268. # define EV_PID_HASHSIZE EV_FEATURE_DATA ? 16 : 1
  269. #endif
  270. #ifndef EV_INOTIFY_HASHSIZE
  271. # define EV_INOTIFY_HASHSIZE EV_FEATURE_DATA ? 16 : 1
  272. #endif
  273. #ifndef EV_USE_EVENTFD
  274. # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7))
  275. # define EV_USE_EVENTFD EV_FEATURE_OS
  276. # else
  277. # define EV_USE_EVENTFD 0
  278. # endif
  279. #endif
  280. #ifndef EV_USE_SIGNALFD
  281. # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7))
  282. # define EV_USE_SIGNALFD EV_FEATURE_OS
  283. # else
  284. # define EV_USE_SIGNALFD 0
  285. # endif
  286. #endif
  287. #if 0 /* debugging */
  288. # define EV_VERIFY 3
  289. # define EV_USE_4HEAP 1
  290. # define EV_HEAP_CACHE_AT 1
  291. #endif
  292. #ifndef EV_VERIFY
  293. # define EV_VERIFY (EV_FEATURE_API ? 1 : 0)
  294. #endif
  295. #ifndef EV_USE_4HEAP
  296. # define EV_USE_4HEAP EV_FEATURE_DATA
  297. #endif
  298. #ifndef EV_HEAP_CACHE_AT
  299. # define EV_HEAP_CACHE_AT EV_FEATURE_DATA
  300. #endif
  301. /* on linux, we can use a (slow) syscall to avoid a dependency on pthread, */
  302. /* which makes programs even slower. might work on other unices, too. */
  303. #if EV_USE_CLOCK_SYSCALL
  304. # include <syscall.h>
  305. # ifdef SYS_clock_gettime
  306. # define clock_gettime(id, ts) syscall (SYS_clock_gettime, (id), (ts))
  307. # undef EV_USE_MONOTONIC
  308. # define EV_USE_MONOTONIC 1
  309. # else
  310. # undef EV_USE_CLOCK_SYSCALL
  311. # define EV_USE_CLOCK_SYSCALL 0
  312. # endif
  313. #endif
  314. /* this block fixes any misconfiguration where we know we run into trouble otherwise */
  315. #ifdef _AIX
  316. /* AIX has a completely broken poll.h header */
  317. # undef EV_USE_POLL
  318. # define EV_USE_POLL 0
  319. #endif
  320. #ifndef CLOCK_MONOTONIC
  321. # undef EV_USE_MONOTONIC
  322. # define EV_USE_MONOTONIC 0
  323. #endif
  324. #ifndef CLOCK_REALTIME
  325. # undef EV_USE_REALTIME
  326. # define EV_USE_REALTIME 0
  327. #endif
  328. #if !EV_STAT_ENABLE
  329. # undef EV_USE_INOTIFY
  330. # define EV_USE_INOTIFY 0
  331. #endif
  332. #if !EV_USE_NANOSLEEP
  333. # ifndef _WIN32
  334. # include <sys/select.h>
  335. # endif
  336. #endif
  337. #if EV_USE_INOTIFY
  338. # include <sys/statfs.h>
  339. # include <sys/inotify.h>
  340. /* some very old inotify.h headers don't have IN_DONT_FOLLOW */
  341. # ifndef IN_DONT_FOLLOW
  342. # undef EV_USE_INOTIFY
  343. # define EV_USE_INOTIFY 0
  344. # endif
  345. #endif
  346. #if EV_SELECT_IS_WINSOCKET
  347. # include <winsock.h>
  348. #endif
  349. #if EV_USE_EVENTFD
  350. /* our minimum requirement is glibc 2.7 which has the stub, but not the header */
  351. # include <stdint.h>
  352. # ifndef EFD_NONBLOCK
  353. # define EFD_NONBLOCK O_NONBLOCK
  354. # endif
  355. # ifndef EFD_CLOEXEC
  356. # ifdef O_CLOEXEC
  357. # define EFD_CLOEXEC O_CLOEXEC
  358. # else
  359. # define EFD_CLOEXEC 02000000
  360. # endif
  361. # endif
  362. EV_CPP(extern "C") int (eventfd) (unsigned int initval, int flags);
  363. #endif
  364. #if EV_USE_SIGNALFD
  365. /* our minimum requirement is glibc 2.7 which has the stub, but not the header */
  366. # include <stdint.h>
  367. # ifndef SFD_NONBLOCK
  368. # define SFD_NONBLOCK O_NONBLOCK
  369. # endif
  370. # ifndef SFD_CLOEXEC
  371. # ifdef O_CLOEXEC
  372. # define SFD_CLOEXEC O_CLOEXEC
  373. # else
  374. # define SFD_CLOEXEC 02000000
  375. # endif
  376. # endif
  377. EV_CPP (extern "C") int signalfd (int fd, const sigset_t *mask, int flags);
  378. struct signalfd_siginfo
  379. {
  380. uint32_t ssi_signo;
  381. char pad[128 - sizeof (uint32_t)];
  382. };
  383. #endif
  384. /**/
  385. #if EV_VERIFY >= 3
  386. # define EV_FREQUENT_CHECK ev_verify (EV_A)
  387. #else
  388. # define EV_FREQUENT_CHECK do { } while (0)
  389. #endif
  390. /*
  391. * This is used to avoid floating point rounding problems.
  392. * It is added to ev_rt_now when scheduling periodics
  393. * to ensure progress, time-wise, even when rounding
  394. * errors are against us.
  395. * This value is good at least till the year 4000.
  396. * Better solutions welcome.
  397. */
  398. #define TIME_EPSILON 0.0001220703125 /* 1/8192 */
  399. #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
  400. #define MAX_BLOCKTIME 59.743 /* never wait longer than this time (to detect time jumps) */
  401. #define EV_TV_SET(tv,t) do { tv.tv_sec = (long)t; tv.tv_usec = (long)((t - tv.tv_sec) * 1e6); } while (0)
  402. #define EV_TS_SET(ts,t) do { ts.tv_sec = (long)t; ts.tv_nsec = (long)((t - ts.tv_sec) * 1e9); } while (0)
  403. #if __GNUC__ >= 4
  404. # define expect(expr,value) __builtin_expect ((expr),(value))
  405. # define noinline __attribute__ ((noinline))
  406. #else
  407. # define expect(expr,value) (expr)
  408. # define noinline
  409. # if __STDC_VERSION__ < 199901L && __GNUC__ < 2
  410. # define inline
  411. # endif
  412. #endif
  413. #define expect_false(expr) expect ((expr) != 0, 0)
  414. #define expect_true(expr) expect ((expr) != 0, 1)
  415. #define inline_size static inline
  416. #if EV_FEATURE_CODE
  417. # define inline_speed static inline
  418. #else
  419. # define inline_speed static noinline
  420. #endif
  421. #define NUMPRI (EV_MAXPRI - EV_MINPRI + 1)
  422. #if EV_MINPRI == EV_MAXPRI
  423. # define ABSPRI(w) (((W)w), 0)
  424. #else
  425. # define ABSPRI(w) (((W)w)->priority - EV_MINPRI)
  426. #endif
  427. #define EMPTY /* required for microsofts broken pseudo-c compiler */
  428. #define EMPTY2(a,b) /* used to suppress some warnings */
  429. typedef ev_watcher *W;
  430. typedef ev_watcher_list *WL;
  431. typedef ev_watcher_time *WT;
  432. #define ev_active(w) ((W)(w))->active
  433. #define ev_at(w) ((WT)(w))->at
  434. #if EV_USE_REALTIME
  435. /* sig_atomic_t is used to avoid per-thread variables or locking but still */
  436. /* giving it a reasonably high chance of working on typical architectures */
  437. static EV_ATOMIC_T have_realtime; /* did clock_gettime (CLOCK_REALTIME) work? */
  438. #endif
  439. #if EV_USE_MONOTONIC
  440. static EV_ATOMIC_T have_monotonic; /* did clock_gettime (CLOCK_MONOTONIC) work? */
  441. #endif
  442. #ifndef EV_FD_TO_WIN32_HANDLE
  443. # define EV_FD_TO_WIN32_HANDLE(fd) _get_osfhandle (fd)
  444. #endif
  445. #ifndef EV_WIN32_HANDLE_TO_FD
  446. # define EV_WIN32_HANDLE_TO_FD(handle) _open_osfhandle (handle, 0)
  447. #endif
  448. #ifndef EV_WIN32_CLOSE_FD
  449. # define EV_WIN32_CLOSE_FD(fd) close (fd)
  450. #endif
  451. #ifdef _WIN32
  452. # include "ev_win32.c"
  453. #endif
  454. /*****************************************************************************/
  455. #ifdef __linux
  456. # include <sys/utsname.h>
  457. #endif
  458. static unsigned int noinline
  459. ev_linux_version (void)
  460. {
  461. #ifdef __linux
  462. unsigned int v = 0;
  463. struct utsname buf;
  464. int i;
  465. char *p = buf.release;
  466. if (uname (&buf))
  467. return 0;
  468. for (i = 3+1; --i; )
  469. {
  470. unsigned int c = 0;
  471. for (;;)
  472. {
  473. if (*p >= '0' && *p <= '9')
  474. c = c * 10 + *p++ - '0';
  475. else
  476. {
  477. p += *p == '.';
  478. break;
  479. }
  480. }
  481. v = (v << 8) | c;
  482. }
  483. return v;
  484. #else
  485. return 0;
  486. #endif
  487. }
  488. /*****************************************************************************/
  489. #if EV_AVOID_STDIO
  490. static void noinline
  491. ev_printerr (const char *msg)
  492. {
  493. write (STDERR_FILENO, msg, strlen (msg));
  494. }
  495. #endif
  496. static void (*syserr_cb)(const char *msg);
  497. void
  498. ev_set_syserr_cb (void (*cb)(const char *msg))
  499. {
  500. syserr_cb = cb;
  501. }
  502. static void noinline
  503. ev_syserr (const char *msg)
  504. {
  505. if (!msg)
  506. msg = "(libev) system error";
  507. if (syserr_cb)
  508. syserr_cb (msg);
  509. else
  510. {
  511. #if EV_AVOID_STDIO
  512. ev_printerr (msg);
  513. ev_printerr (": ");
  514. ev_printerr (strerror (errno));
  515. ev_printerr ("\n");
  516. #else
  517. perror (msg);
  518. #endif
  519. abort ();
  520. }
  521. }
  522. static void *
  523. ev_realloc_emul (void *ptr, long size)
  524. {
  525. #if __GLIBC__
  526. return realloc (ptr, size);
  527. #else
  528. /* some systems, notably openbsd and darwin, fail to properly
  529. * implement realloc (x, 0) (as required by both ansi c-89 and
  530. * the single unix specification, so work around them here.
  531. */
  532. if (size)
  533. return realloc (ptr, size);
  534. free (ptr);
  535. return 0;
  536. #endif
  537. }
  538. static void *(*alloc)(void *ptr, long size) = ev_realloc_emul;
  539. void
  540. ev_set_allocator (void *(*cb)(void *ptr, long size))
  541. {
  542. alloc = cb;
  543. }
  544. inline_speed void *
  545. ev_realloc (void *ptr, long size)
  546. {
  547. ptr = alloc (ptr, size);
  548. if (!ptr && size)
  549. {
  550. #if EV_AVOID_STDIO
  551. ev_printerr ("(libev) memory allocation failed, aborting.\n");
  552. #else
  553. fprintf (stderr, "(libev) cannot allocate %ld bytes, aborting.", size);
  554. #endif
  555. abort ();
  556. }
  557. return ptr;
  558. }
  559. #define ev_malloc(size) ev_realloc (0, (size))
  560. #define ev_free(ptr) ev_realloc ((ptr), 0)
  561. /*****************************************************************************/
  562. /* set in reify when reification needed */
  563. #define EV_ANFD_REIFY 1
  564. /* file descriptor info structure */
  565. typedef struct
  566. {
  567. WL head;
  568. unsigned char events; /* the events watched for */
  569. unsigned char reify; /* flag set when this ANFD needs reification (EV_ANFD_REIFY, EV__IOFDSET) */
  570. unsigned char emask; /* the epoll backend stores the actual kernel mask in here */
  571. unsigned char unused;
  572. #if EV_USE_EPOLL
  573. unsigned int egen; /* generation counter to counter epoll bugs */
  574. #endif
  575. #if EV_SELECT_IS_WINSOCKET || EV_USE_IOCP
  576. SOCKET handle;
  577. #endif
  578. #if EV_USE_IOCP
  579. OVERLAPPED or, ow;
  580. #endif
  581. } ANFD;
  582. /* stores the pending event set for a given watcher */
  583. typedef struct
  584. {
  585. W w;
  586. int events; /* the pending event set for the given watcher */
  587. } ANPENDING;
  588. #if EV_USE_INOTIFY
  589. /* hash table entry per inotify-id */
  590. typedef struct
  591. {
  592. WL head;
  593. } ANFS;
  594. #endif
  595. /* Heap Entry */
  596. #if EV_HEAP_CACHE_AT
  597. /* a heap element */
  598. typedef struct {
  599. ev_tstamp at;
  600. WT w;
  601. } ANHE;
  602. #define ANHE_w(he) (he).w /* access watcher, read-write */
  603. #define ANHE_at(he) (he).at /* access cached at, read-only */
  604. #define ANHE_at_cache(he) (he).at = (he).w->at /* update at from watcher */
  605. #else
  606. /* a heap element */
  607. typedef WT ANHE;
  608. #define ANHE_w(he) (he)
  609. #define ANHE_at(he) (he)->at
  610. #define ANHE_at_cache(he)
  611. #endif
  612. #if EV_MULTIPLICITY
  613. struct ev_loop
  614. {
  615. ev_tstamp ev_rt_now;
  616. #define ev_rt_now ((loop)->ev_rt_now)
  617. #define VAR(name,decl) decl;
  618. #include "ev_vars.h"
  619. #undef VAR
  620. };
  621. #include "ev_wrap.h"
  622. static struct ev_loop default_loop_struct;
  623. struct ev_loop *ev_default_loop_ptr;
  624. #else
  625. ev_tstamp ev_rt_now;
  626. #define VAR(name,decl) static decl;
  627. #include "ev_vars.h"
  628. #undef VAR
  629. static int ev_default_loop_ptr;
  630. #endif
  631. #if EV_FEATURE_API
  632. # define EV_RELEASE_CB if (expect_false (release_cb)) release_cb (EV_A)
  633. # define EV_ACQUIRE_CB if (expect_false (acquire_cb)) acquire_cb (EV_A)
  634. # define EV_INVOKE_PENDING invoke_cb (EV_A)
  635. #else
  636. # define EV_RELEASE_CB (void)0
  637. # define EV_ACQUIRE_CB (void)0
  638. # define EV_INVOKE_PENDING ev_invoke_pending (EV_A)
  639. #endif
  640. #define EVBREAK_RECURSE 0x80
  641. /*****************************************************************************/
  642. #ifndef EV_HAVE_EV_TIME
  643. ev_tstamp
  644. ev_time (void)
  645. {
  646. #if EV_USE_REALTIME
  647. if (expect_true (have_realtime))
  648. {
  649. struct timespec ts;
  650. clock_gettime (CLOCK_REALTIME, &ts);
  651. return ts.tv_sec + ts.tv_nsec * 1e-9;
  652. }
  653. #endif
  654. struct timeval tv;
  655. gettimeofday (&tv, 0);
  656. return tv.tv_sec + tv.tv_usec * 1e-6;
  657. }
  658. #endif
  659. inline_size ev_tstamp
  660. get_clock (void)
  661. {
  662. #if EV_USE_MONOTONIC
  663. if (expect_true (have_monotonic))
  664. {
  665. struct timespec ts;
  666. clock_gettime (CLOCK_MONOTONIC, &ts);
  667. return ts.tv_sec + ts.tv_nsec * 1e-9;
  668. }
  669. #endif
  670. return ev_time ();
  671. }
  672. #if EV_MULTIPLICITY
  673. ev_tstamp
  674. ev_now (EV_P)
  675. {
  676. return ev_rt_now;
  677. }
  678. #endif
  679. void
  680. ev_sleep (ev_tstamp delay)
  681. {
  682. if (delay > 0.)
  683. {
  684. #if EV_USE_NANOSLEEP
  685. struct timespec ts;
  686. EV_TS_SET (ts, delay);
  687. nanosleep (&ts, 0);
  688. #elif defined(_WIN32)
  689. Sleep ((unsigned long)(delay * 1e3));
  690. #else
  691. struct timeval tv;
  692. /* here we rely on sys/time.h + sys/types.h + unistd.h providing select */
  693. /* something not guaranteed by newer posix versions, but guaranteed */
  694. /* by older ones */
  695. EV_TV_SET (tv, delay);
  696. select (0, 0, 0, 0, &tv);
  697. #endif
  698. }
  699. }
  700. /*****************************************************************************/
  701. #define MALLOC_ROUND 4096 /* prefer to allocate in chunks of this size, must be 2**n and >> 4 longs */
  702. /* find a suitable new size for the given array, */
  703. /* hopefully by rounding to a nice-to-malloc size */
  704. inline_size int
  705. array_nextsize (int elem, int cur, int cnt)
  706. {
  707. int ncur = cur + 1;
  708. do
  709. ncur <<= 1;
  710. while (cnt > ncur);
  711. /* if size is large, round to MALLOC_ROUND - 4 * longs to accomodate malloc overhead */
  712. if (elem * ncur > MALLOC_ROUND - sizeof (void *) * 4)
  713. {
  714. ncur *= elem;
  715. ncur = (ncur + elem + (MALLOC_ROUND - 1) + sizeof (void *) * 4) & ~(MALLOC_ROUND - 1);
  716. ncur = ncur - sizeof (void *) * 4;
  717. ncur /= elem;
  718. }
  719. return ncur;
  720. }
  721. static noinline void *
  722. array_realloc (int elem, void *base, int *cur, int cnt)
  723. {
  724. *cur = array_nextsize (elem, *cur, cnt);
  725. return ev_realloc (base, elem * *cur);
  726. }
  727. #define array_init_zero(base,count) \
  728. memset ((void *)(base), 0, sizeof (*(base)) * (count))
  729. #define array_needsize(type,base,cur,cnt,init) \
  730. if (expect_false ((cnt) > (cur))) \
  731. { \
  732. int ocur_ = (cur); \
  733. (base) = (type *)array_realloc \
  734. (sizeof (type), (base), &(cur), (cnt)); \
  735. init ((base) + (ocur_), (cur) - ocur_); \
  736. }
  737. #if 0
  738. #define array_slim(type,stem) \
  739. if (stem ## max < array_roundsize (stem ## cnt >> 2)) \
  740. { \
  741. stem ## max = array_roundsize (stem ## cnt >> 1); \
  742. base = (type *)ev_realloc (base, sizeof (type) * (stem ## max));\
  743. fprintf (stderr, "slimmed down " # stem " to %d\n", stem ## max);/*D*/\
  744. }
  745. #endif
  746. #define array_free(stem, idx) \
  747. ev_free (stem ## s idx); stem ## cnt idx = stem ## max idx = 0; stem ## s idx = 0
  748. /*****************************************************************************/
  749. /* dummy callback for pending events */
  750. static void noinline
  751. pendingcb (EV_P_ ev_prepare *w, int revents)
  752. {
  753. }
  754. void noinline
  755. ev_feed_event (EV_P_ void *w, int revents)
  756. {
  757. W w_ = (W)w;
  758. int pri = ABSPRI (w_);
  759. if (expect_false (w_->pending))
  760. pendings [pri][w_->pending - 1].events |= revents;
  761. else
  762. {
  763. w_->pending = ++pendingcnt [pri];
  764. array_needsize (ANPENDING, pendings [pri], pendingmax [pri], w_->pending, EMPTY2);
  765. pendings [pri][w_->pending - 1].w = w_;
  766. pendings [pri][w_->pending - 1].events = revents;
  767. }
  768. }
  769. inline_speed void
  770. feed_reverse (EV_P_ W w)
  771. {
  772. array_needsize (W, rfeeds, rfeedmax, rfeedcnt + 1, EMPTY2);
  773. rfeeds [rfeedcnt++] = w;
  774. }
  775. inline_size void
  776. feed_reverse_done (EV_P_ int revents)
  777. {
  778. do
  779. ev_feed_event (EV_A_ rfeeds [--rfeedcnt], revents);
  780. while (rfeedcnt);
  781. }
  782. inline_speed void
  783. queue_events (EV_P_ W *events, int eventcnt, int type)
  784. {
  785. int i;
  786. for (i = 0; i < eventcnt; ++i)
  787. ev_feed_event (EV_A_ events [i], type);
  788. }
  789. /*****************************************************************************/
  790. inline_speed void
  791. fd_event_nocheck (EV_P_ int fd, int revents)
  792. {
  793. ANFD *anfd = anfds + fd;
  794. ev_io *w;
  795. for (w = (ev_io *)anfd->head; w; w = (ev_io *)((WL)w)->next)
  796. {
  797. int ev = w->events & revents;
  798. if (ev)
  799. ev_feed_event (EV_A_ (W)w, ev);
  800. }
  801. }
  802. /* do not submit kernel events for fds that have reify set */
  803. /* because that means they changed while we were polling for new events */
  804. inline_speed void
  805. fd_event (EV_P_ int fd, int revents)
  806. {
  807. ANFD *anfd = anfds + fd;
  808. if (expect_true (!anfd->reify))
  809. fd_event_nocheck (EV_A_ fd, revents);
  810. }
  811. void
  812. ev_feed_fd_event (EV_P_ int fd, int revents)
  813. {
  814. if (fd >= 0 && fd < anfdmax)
  815. fd_event_nocheck (EV_A_ fd, revents);
  816. }
  817. /* make sure the external fd watch events are in-sync */
  818. /* with the kernel/libev internal state */
  819. inline_size void
  820. fd_reify (EV_P)
  821. {
  822. int i;
  823. for (i = 0; i < fdchangecnt; ++i)
  824. {
  825. int fd = fdchanges [i];
  826. ANFD *anfd = anfds + fd;
  827. ev_io *w;
  828. unsigned char o_events = anfd->events;
  829. unsigned char o_reify = anfd->reify;
  830. anfd->reify = 0;
  831. #if EV_SELECT_IS_WINSOCKET || EV_USE_IOCP
  832. if (o_reify & EV__IOFDSET)
  833. {
  834. unsigned long arg;
  835. anfd->handle = EV_FD_TO_WIN32_HANDLE (fd);
  836. assert (("libev: only socket fds supported in this configuration", ioctlsocket (anfd->handle, FIONREAD, &arg) == 0));
  837. printf ("oi %d %x\n", fd, anfd->handle);//D
  838. }
  839. #endif
  840. /*if (expect_true (o_reify & EV_ANFD_REIFY)) probably a deoptimisation */
  841. {
  842. anfd->events = 0;
  843. for (w = (ev_io *)anfd->head; w; w = (ev_io *)((WL)w)->next)
  844. anfd->events |= (unsigned char)w->events;
  845. if (o_events != anfd->events)
  846. o_reify = EV__IOFDSET; /* actually |= */
  847. }
  848. if (o_reify & EV__IOFDSET)
  849. backend_modify (EV_A_ fd, o_events, anfd->events);
  850. }
  851. fdchangecnt = 0;
  852. }
  853. /* something about the given fd changed */
  854. inline_size void
  855. fd_change (EV_P_ int fd, int flags)
  856. {
  857. unsigned char reify = anfds [fd].reify;
  858. anfds [fd].reify |= flags;
  859. if (expect_true (!reify))
  860. {
  861. ++fdchangecnt;
  862. array_needsize (int, fdchanges, fdchangemax, fdchangecnt, EMPTY2);
  863. fdchanges [fdchangecnt - 1] = fd;
  864. }
  865. }
  866. /* the given fd is invalid/unusable, so make sure it doesn't hurt us anymore */
  867. inline_speed void
  868. fd_kill (EV_P_ int fd)
  869. {
  870. ev_io *w;
  871. while ((w = (ev_io *)anfds [fd].head))
  872. {
  873. ev_io_stop (EV_A_ w);
  874. ev_feed_event (EV_A_ (W)w, EV_ERROR | EV_READ | EV_WRITE);
  875. }
  876. }
  877. /* check whether the given fd is actually valid, for error recovery */
  878. inline_size int
  879. fd_valid (int fd)
  880. {
  881. #ifdef _WIN32
  882. return EV_FD_TO_WIN32_HANDLE (fd) != -1;
  883. #else
  884. return fcntl (fd, F_GETFD) != -1;
  885. #endif
  886. }
  887. /* called on EBADF to verify fds */
  888. static void noinline
  889. fd_ebadf (EV_P)
  890. {
  891. int fd;
  892. for (fd = 0; fd < anfdmax; ++fd)
  893. if (anfds [fd].events)
  894. if (!fd_valid (fd) && errno == EBADF)
  895. fd_kill (EV_A_ fd);
  896. }
  897. /* called on ENOMEM in select/poll to kill some fds and retry */
  898. static void noinline
  899. fd_enomem (EV_P)
  900. {
  901. int fd;
  902. for (fd = anfdmax; fd--; )
  903. if (anfds [fd].events)
  904. {
  905. fd_kill (EV_A_ fd);
  906. break;
  907. }
  908. }
  909. /* usually called after fork if backend needs to re-arm all fds from scratch */
  910. static void noinline
  911. fd_rearm_all (EV_P)
  912. {
  913. int fd;
  914. for (fd = 0; fd < anfdmax; ++fd)
  915. if (anfds [fd].events)
  916. {
  917. anfds [fd].events = 0;
  918. anfds [fd].emask = 0;
  919. fd_change (EV_A_ fd, EV__IOFDSET | EV_ANFD_REIFY);
  920. }
  921. }
  922. /* used to prepare libev internal fd's */
  923. /* this is not fork-safe */
  924. inline_speed void
  925. fd_intern (int fd)
  926. {
  927. #ifdef _WIN32
  928. unsigned long arg = 1;
  929. ioctlsocket (EV_FD_TO_WIN32_HANDLE (fd), FIONBIO, &arg);
  930. #else
  931. fcntl (fd, F_SETFD, FD_CLOEXEC);
  932. fcntl (fd, F_SETFL, O_NONBLOCK);
  933. #endif
  934. }
  935. /*****************************************************************************/
  936. /*
  937. * the heap functions want a real array index. array index 0 is guaranteed to not
  938. * be in-use at any time. the first heap entry is at array [HEAP0]. DHEAP gives
  939. * the branching factor of the d-tree.
  940. */
  941. /*
  942. * at the moment we allow libev the luxury of two heaps,
  943. * a small-code-size 2-heap one and a ~1.5kb larger 4-heap
  944. * which is more cache-efficient.
  945. * the difference is about 5% with 50000+ watchers.
  946. */
  947. #if EV_USE_4HEAP
  948. #define DHEAP 4
  949. #define HEAP0 (DHEAP - 1) /* index of first element in heap */
  950. #define HPARENT(k) ((((k) - HEAP0 - 1) / DHEAP) + HEAP0)
  951. #define UPHEAP_DONE(p,k) ((p) == (k))
  952. /* away from the root */
  953. inline_speed void
  954. downheap (ANHE *heap, int N, int k)
  955. {
  956. ANHE he = heap [k];
  957. ANHE *E = heap + N + HEAP0;
  958. for (;;)
  959. {
  960. ev_tstamp minat;
  961. ANHE *minpos;
  962. ANHE *pos = heap + DHEAP * (k - HEAP0) + HEAP0 + 1;
  963. /* find minimum child */
  964. if (expect_true (pos + DHEAP - 1 < E))
  965. {
  966. /* fast path */ (minpos = pos + 0), (minat = ANHE_at (*minpos));
  967. if ( ANHE_at (pos [1]) < minat) (minpos = pos + 1), (minat = ANHE_at (*minpos));
  968. if ( ANHE_at (pos [2]) < minat) (minpos = pos + 2), (minat = ANHE_at (*minpos));
  969. if ( ANHE_at (pos [3]) < minat) (minpos = pos + 3), (minat = ANHE_at (*minpos));
  970. }
  971. else if (pos < E)
  972. {
  973. /* slow path */ (minpos = pos + 0), (minat = ANHE_at (*minpos));
  974. if (pos + 1 < E && ANHE_at (pos [1]) < minat) (minpos = pos + 1), (minat = ANHE_at (*minpos));
  975. if (pos + 2 < E && ANHE_at (pos [2]) < minat) (minpos = pos + 2), (minat = ANHE_at (*minpos));
  976. if (pos + 3 < E && ANHE_at (pos [3]) < minat) (minpos = pos + 3), (minat = ANHE_at (*minpos));
  977. }
  978. else
  979. break;
  980. if (ANHE_at (he) <= minat)
  981. break;
  982. heap [k] = *minpos;
  983. ev_active (ANHE_w (*minpos)) = k;
  984. k = minpos - heap;
  985. }
  986. heap [k] = he;
  987. ev_active (ANHE_w (he)) = k;
  988. }
  989. #else /* 4HEAP */
  990. #define HEAP0 1
  991. #define HPARENT(k) ((k) >> 1)
  992. #define UPHEAP_DONE(p,k) (!(p))
  993. /* away from the root */
  994. inline_speed void
  995. downheap (ANHE *heap, int N, int k)
  996. {
  997. ANHE he = heap [k];
  998. for (;;)
  999. {
  1000. int c = k << 1;
  1001. if (c >= N + HEAP0)
  1002. break;
  1003. c += c + 1 < N + HEAP0 && ANHE_at (heap [c]) > ANHE_at (heap [c + 1])
  1004. ? 1 : 0;
  1005. if (ANHE_at (he) <= ANHE_at (heap [c]))
  1006. break;
  1007. heap [k] = heap [c];
  1008. ev_active (ANHE_w (heap [k])) = k;
  1009. k = c;
  1010. }
  1011. heap [k] = he;
  1012. ev_active (ANHE_w (he)) = k;
  1013. }
  1014. #endif
  1015. /* towards the root */
  1016. inline_speed void
  1017. upheap (ANHE *heap, int k)
  1018. {
  1019. ANHE he = heap [k];
  1020. for (;;)
  1021. {
  1022. int p = HPARENT (k);
  1023. if (UPHEAP_DONE (p, k) || ANHE_at (heap [p]) <= ANHE_at (he))
  1024. break;
  1025. heap [k] = heap [p];
  1026. ev_active (ANHE_w (heap [k])) = k;
  1027. k = p;
  1028. }
  1029. heap [k] = he;
  1030. ev_active (ANHE_w (he)) = k;
  1031. }
  1032. /* move an element suitably so it is in a correct place */
  1033. inline_size void
  1034. adjustheap (ANHE *heap, int N, int k)
  1035. {
  1036. if (k > HEAP0 && ANHE_at (heap [k]) <= ANHE_at (heap [HPARENT (k)]))
  1037. upheap (heap, k);
  1038. else
  1039. downheap (heap, N, k);
  1040. }
  1041. /* rebuild the heap: this function is used only once and executed rarely */
  1042. inline_size void
  1043. reheap (ANHE *heap, int N)
  1044. {
  1045. int i;
  1046. /* we don't use floyds algorithm, upheap is simpler and is more cache-efficient */
  1047. /* also, this is easy to implement and correct for both 2-heaps and 4-heaps */
  1048. for (i = 0; i < N; ++i)
  1049. upheap (heap, i + HEAP0);
  1050. }
  1051. /*****************************************************************************/
  1052. /* associate signal watchers to a signal signal */
  1053. typedef struct
  1054. {
  1055. EV_ATOMIC_T pending;
  1056. #if EV_MULTIPLICITY
  1057. EV_P;
  1058. #endif
  1059. WL head;
  1060. } ANSIG;
  1061. static ANSIG signals [EV_NSIG - 1];
  1062. /*****************************************************************************/
  1063. #if EV_SIGNAL_ENABLE || EV_ASYNC_ENABLE
  1064. static void noinline
  1065. evpipe_init (EV_P)
  1066. {
  1067. if (!ev_is_active (&pipe_w))
  1068. {
  1069. # if EV_USE_EVENTFD
  1070. evfd = eventfd (0, EFD_NONBLOCK | EFD_CLOEXEC);
  1071. if (evfd < 0 && errno == EINVAL)
  1072. evfd = eventfd (0, 0);
  1073. if (evfd >= 0)
  1074. {
  1075. evpipe [0] = -1;
  1076. fd_intern (evfd); /* doing it twice doesn't hurt */
  1077. ev_io_set (&pipe_w, evfd, EV_READ);
  1078. }
  1079. else
  1080. # endif
  1081. {
  1082. while (pipe (evpipe))
  1083. ev_syserr ("(libev) error creating signal/async pipe");
  1084. fd_intern (evpipe [0]);
  1085. fd_intern (evpipe [1]);
  1086. ev_io_set (&pipe_w, evpipe [0], EV_READ);
  1087. }
  1088. ev_io_start (EV_A_ &pipe_w);
  1089. ev_unref (EV_A); /* watcher should not keep loop alive */
  1090. }
  1091. }
  1092. inline_size void
  1093. evpipe_write (EV_P_ EV_ATOMIC_T *flag)
  1094. {
  1095. if (!*flag)
  1096. {
  1097. int old_errno = errno; /* save errno because write might clobber it */
  1098. char dummy;
  1099. *flag = 1;
  1100. #if EV_USE_EVENTFD
  1101. if (evfd >= 0)
  1102. {
  1103. uint64_t counter = 1;
  1104. write (evfd, &counter, sizeof (uint64_t));
  1105. }
  1106. else
  1107. #endif
  1108. /* win32 people keep sending patches that change this write() to send() */
  1109. /* and then run away. but send() is wrong, it wants a socket handle on win32 */
  1110. /* so when you think this write should be a send instead, please find out */
  1111. /* where your send() is from - it's definitely not the microsoft send, and */
  1112. /* tell me. thank you. */
  1113. write (evpipe [1], &dummy, 1);
  1114. errno = old_errno;
  1115. }
  1116. }
  1117. /* called whenever the libev signal pipe */
  1118. /* got some events (signal, async) */
  1119. static void
  1120. pipecb (EV_P_ ev_io *iow, int revents)
  1121. {
  1122. int i;
  1123. #if EV_USE_EVENTFD
  1124. if (evfd >= 0)
  1125. {
  1126. uint64_t counter;
  1127. read (evfd, &counter, sizeof (uint64_t));
  1128. }
  1129. else
  1130. #endif
  1131. {
  1132. char dummy;
  1133. /* see discussion in evpipe_write when you think this read should be recv in win32 */
  1134. read (evpipe [0], &dummy, 1);
  1135. }
  1136. if (sig_pending)
  1137. {
  1138. sig_pending = 0;
  1139. for (i = EV_NSIG - 1; i--; )
  1140. if (expect_false (signals [i].pending))
  1141. ev_feed_signal_event (EV_A_ i + 1);
  1142. }
  1143. #if EV_ASYNC_ENABLE
  1144. if (async_pending)
  1145. {
  1146. async_pending = 0;
  1147. for (i = asynccnt; i--; )
  1148. if (asyncs [i]->sent)
  1149. {
  1150. asyncs [i]->sent = 0;
  1151. ev_feed_event (EV_A_ asyncs [i], EV_ASYNC);
  1152. }
  1153. }
  1154. #endif
  1155. }
  1156. /*****************************************************************************/
  1157. void
  1158. ev_feed_signal (int signum)
  1159. {
  1160. #if EV_MULTIPLICITY
  1161. EV_P = signals [signum - 1].loop;
  1162. if (!EV_A)
  1163. return;
  1164. #endif
  1165. signals [signum - 1].pending = 1;
  1166. evpipe_write (EV_A_ &sig_pending);
  1167. }
  1168. static void
  1169. ev_sighandler (int signum)
  1170. {
  1171. #ifdef _WIN32
  1172. signal (signum, ev_sighandler);
  1173. #endif
  1174. ev_feed_signal (signum);
  1175. }
  1176. void noinline
  1177. ev_feed_signal_event (EV_P_ int signum)
  1178. {
  1179. WL w;
  1180. if (expect_false (signum <= 0 || signum > EV_NSIG))
  1181. return;
  1182. --signum;
  1183. #if EV_MULTIPLICITY
  1184. /* it is permissible to try to feed a signal to the wrong loop */
  1185. /* or, likely more useful, feeding a signal nobody is waiting for */
  1186. if (expect_false (signals [signum].loop != EV_A))
  1187. return;
  1188. #endif
  1189. signals [signum].pending = 0;
  1190. for (w = signals [signum].head; w; w = w->next)
  1191. ev_feed_event (EV_A_ (W)w, EV_SIGNAL);
  1192. }
  1193. #if EV_USE_SIGNALFD
  1194. static void
  1195. sigfdcb (EV_P_ ev_io *iow, int revents)
  1196. {
  1197. struct signalfd_siginfo si[2], *sip; /* these structs are big */
  1198. for (;;)
  1199. {
  1200. ssize_t res = read (sigfd, si, sizeof (si));
  1201. /* not ISO-C, as res might be -1, but works with SuS */
  1202. for (sip = si; (char *)sip < (char *)si + res; ++sip)
  1203. ev_feed_signal_event (EV_A_ sip->ssi_signo);
  1204. if (res < (ssize_t)sizeof (si))
  1205. break;
  1206. }
  1207. }
  1208. #endif
  1209. #endif
  1210. /*****************************************************************************/
  1211. #if EV_CHILD_ENABLE
  1212. static WL childs [EV_PID_HASHSIZE];
  1213. static ev_signal childev;
  1214. #ifndef WIFCONTINUED
  1215. # define WIFCONTINUED(status) 0
  1216. #endif
  1217. /* handle a single child status event */
  1218. inline_speed void
  1219. child_reap (EV_P_ int chain, int pid, int status)
  1220. {
  1221. ev_child *w;
  1222. int traced = WIFSTOPPED (status) || WIFCONTINUED (status);
  1223. for (w = (ev_child *)childs [chain & ((EV_PID_HASHSIZE) - 1)]; w; w = (ev_child *)((WL)w)->next)
  1224. {
  1225. if ((w->pid == pid || !w->pid)
  1226. && (!traced || (w->flags & 1)))
  1227. {
  1228. ev_set_priority (w, EV_MAXPRI); /* need to do it *now*, this *must* be the same prio as the signal watcher itself */
  1229. w->rpid = pid;
  1230. w->rstatus = status;
  1231. ev_feed_event (EV_A_ (W)w, EV_CHILD);
  1232. }
  1233. }
  1234. }
  1235. #ifndef WCONTINUED
  1236. # define WCONTINUED 0
  1237. #endif
  1238. /* called on sigchld etc., calls waitpid */
  1239. static void
  1240. childcb (EV_P_ ev_signal *sw, int revents)
  1241. {
  1242. int pid, status;
  1243. /* some systems define WCONTINUED but then fail to support it (linux 2.4) */
  1244. if (0 >= (pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)))
  1245. if (!WCONTINUED
  1246. || errno != EINVAL
  1247. || 0 >= (pid = waitpid (-1, &status, WNOHANG | WUNTRACED)))
  1248. return;
  1249. /* make sure we are called again until all children have been reaped */
  1250. /* we need to do it this way so that the callback gets called before we continue */
  1251. ev_feed_event (EV_A_ (W)sw, EV_SIGNAL);
  1252. child_reap (EV_A_ pid, pid, status);
  1253. if ((EV_PID_HASHSIZE) > 1)
  1254. child_reap (EV_A_ 0, pid, status); /* this might trigger a watcher twice, but feed_event catches that */
  1255. }
  1256. #endif
  1257. /*****************************************************************************/
  1258. #if EV_USE_IOCP
  1259. # include "ev_iocp.c"
  1260. #endif
  1261. #if EV_USE_PORT
  1262. # include "ev_port.c"
  1263. #endif
  1264. #if EV_USE_KQUEUE
  1265. # include "ev_kqueue.c"
  1266. #endif
  1267. #if EV_USE_EPOLL
  1268. # include "ev_epoll.c"
  1269. #endif
  1270. #if EV_USE_POLL
  1271. # include "ev_poll.c"
  1272. #endif
  1273. #if EV_USE_SELECT
  1274. # include "ev_select.c"
  1275. #endif
  1276. int
  1277. ev_version_major (void)
  1278. {
  1279. return EV_VERSION_MAJOR;
  1280. }
  1281. int
  1282. ev_version_minor (void)
  1283. {
  1284. return EV_VERSION_MINOR;
  1285. }
  1286. /* return true if we are running with elevated privileges and should ignore env variables */
  1287. int inline_size
  1288. enable_secure (void)
  1289. {
  1290. #ifdef _WIN32
  1291. return 0;
  1292. #else
  1293. return getuid () != geteuid ()
  1294. || getgid () != getegid ();
  1295. #endif
  1296. }
  1297. unsigned int
  1298. ev_supported_backends (void)
  1299. {
  1300. unsigned int flags = 0;
  1301. if (EV_USE_PORT ) flags |= EVBACKEND_PORT;
  1302. if (EV_USE_KQUEUE) flags |= EVBACKEND_KQUEUE;
  1303. if (EV_USE_EPOLL ) flags |= EVBACKEND_EPOLL;
  1304. if (EV_USE_POLL ) flags |= EVBACKEND_POLL;
  1305. if (EV_USE_SELECT) flags |= EVBACKEND_SELECT;
  1306. return flags;
  1307. }
  1308. unsigned int
  1309. ev_recommended_backends (void)
  1310. {
  1311. unsigned int flags = ev_supported_backends ();
  1312. #ifndef __NetBSD__
  1313. /* kqueue is borked on everything but netbsd apparently */
  1314. /* it usually doesn't work correctly on anything but sockets and pipes */
  1315. flags &= ~EVBACKEND_KQUEUE;
  1316. #endif
  1317. #ifdef __APPLE__
  1318. /* only select works correctly on that "unix-certified" platform */
  1319. flags &= ~EVBACKEND_KQUEUE; /* horribly broken, even for sockets */
  1320. flags &= ~EVBACKEND_POLL; /* poll is based on kqueue from 10.5 onwards */
  1321. #endif
  1322. #ifdef __FreeBSD__
  1323. flags &= ~EVBACKEND_POLL; /* poll return value is unusable (http://forums.freebsd.org/archive/index.php/t-10270.html) */
  1324. #endif
  1325. return flags;
  1326. }
  1327. unsigned int
  1328. ev_embeddable_backends (void)
  1329. {
  1330. int flags = EVBACKEND_EPOLL | EVBACKEND_KQUEUE | EVBACKEND_PORT;
  1331. /* epoll embeddability broken on all linux versions up to at least 2.6.23 */
  1332. if (ev_linux_version () < 0x020620) /* disable it on linux < 2.6.32 */
  1333. flags &= ~EVBACKEND_EPOLL;
  1334. return flags;
  1335. }
  1336. unsigned int
  1337. ev_backend (EV_P)
  1338. {
  1339. return backend;
  1340. }
  1341. #if EV_FEATURE_API
  1342. unsigned int
  1343. ev_iteration (EV_P)
  1344. {
  1345. return loop_count;
  1346. }
  1347. unsigned int
  1348. ev_depth (EV_P)
  1349. {
  1350. return loop_depth;
  1351. }
  1352. void
  1353. ev_set_io_collect_interval (EV_P_ ev_tstamp interval)
  1354. {
  1355. io_blocktime = interval;
  1356. }
  1357. void
  1358. ev_set_timeout_collect_interval (EV_P_ ev_tstamp interval)
  1359. {
  1360. timeout_blocktime = interval;
  1361. }
  1362. void
  1363. ev_set_userdata (EV_P_ void *data)
  1364. {
  1365. userdata = data;
  1366. }
  1367. void *
  1368. ev_userdata (EV_P)
  1369. {
  1370. return userdata;
  1371. }
  1372. void ev_set_invoke_pending_cb (EV_P_ void (*invoke_pending_cb)(EV_P))
  1373. {
  1374. invoke_cb = invoke_pending_cb;
  1375. }
  1376. void ev_set_loop_release_cb (EV_P_ void (*release)(EV_P), void (*acquire)(EV_P))
  1377. {
  1378. release_cb = release;
  1379. acquire_cb = acquire;
  1380. }
  1381. #endif
  1382. /* initialise a loop structure, must be zero-initialised */
  1383. static void noinline
  1384. loop_init (EV_P_ unsigned int flags)
  1385. {
  1386. if (!backend)
  1387. {
  1388. origflags = flags;
  1389. #if EV_USE_REALTIME
  1390. if (!have_realtime)
  1391. {
  1392. struct timespec ts;
  1393. if (!clock_gettime (CLOCK_REALTIME, &ts))
  1394. have_realtime = 1;
  1395. }
  1396. #endif
  1397. #if EV_USE_MONOTONIC
  1398. if (!have_monotonic)
  1399. {
  1400. struct timespec ts;
  1401. if (!clock_gettime (CLOCK_MONOTONIC, &ts))
  1402. have_monotonic = 1;
  1403. }
  1404. #endif
  1405. /* pid check not overridable via env */
  1406. #ifndef _WIN32
  1407. if (flags & EVFLAG_FORKCHECK)
  1408. curpid = getpid ();
  1409. #endif
  1410. if (!(flags & EVFLAG_NOENV)
  1411. && !enable_secure ()
  1412. && getenv ("LIBEV_FLAGS"))
  1413. flags = atoi (getenv ("LIBEV_FLAGS"));
  1414. ev_rt_now = ev_time ();
  1415. mn_now = get_clock ();
  1416. now_floor = mn_now;
  1417. rtmn_diff = ev_rt_now - mn_now;
  1418. #if EV_FEATURE_API
  1419. invoke_cb = ev_invoke_pending;
  1420. #endif
  1421. io_blocktime = 0.;
  1422. timeout_blocktime = 0.;
  1423. backend = 0;
  1424. backend_fd = -1;
  1425. sig_pending = 0;
  1426. #if EV_ASYNC_ENABLE
  1427. async_pending = 0;
  1428. #endif
  1429. #if EV_USE_INOTIFY
  1430. fs_fd = flags & EVFLAG_NOINOTIFY ? -1 : -2;
  1431. #endif
  1432. #if EV_USE_SIGNALFD
  1433. sigfd = flags & EVFLAG_SIGNALFD ? -2 : -1;
  1434. #endif
  1435. if (!(flags & EVBACKEND_MASK))
  1436. flags |= ev_recommended_backends ();
  1437. #if EV_USE_IOCP
  1438. if (!backend && (flags & EVBACKEND_IOCP )) backend = iocp_init (EV_A_ flags);
  1439. #endif
  1440. #if EV_USE_PORT
  1441. if (!backend && (flags & EVBACKEND_PORT )) backend = port_init (EV_A_ flags);
  1442. #endif
  1443. #if EV_USE_KQUEUE
  1444. if (!backend && (flags & EVBACKEND_KQUEUE)) backend = kqueue_init (EV_A_ flags);
  1445. #endif
  1446. #if EV_USE_EPOLL
  1447. if (!backend && (flags & EVBACKEND_EPOLL )) backend = epoll_init (EV_A_ flags);
  1448. #endif
  1449. #if EV_USE_POLL
  1450. if (!backend && (flags & EVBACKEND_POLL )) backend = poll_init (EV_A_ flags);
  1451. #endif
  1452. #if EV_USE_SELECT
  1453. if (!backend && (flags & EVBACKEND_SELECT)) backend = select_init (EV_A_ flags);
  1454. #endif
  1455. ev_prepare_init (&pending_w, pendingcb);
  1456. #if EV_SIGNAL_ENABLE || EV_ASYNC_ENABLE
  1457. ev_init (&pipe_w, pipecb);
  1458. ev_set_priority (&pipe_w, EV_MAXPRI);
  1459. #endif
  1460. }
  1461. }
  1462. /* free up a loop structure */
  1463. void
  1464. ev_loop_destroy (EV_P)
  1465. {
  1466. int i;
  1467. #if EV_MULTIPLICITY
  1468. /* mimic free (0) */
  1469. if (!EV_A)
  1470. return;
  1471. #endif
  1472. #if EV_CLEANUP_ENABLE
  1473. /* queue cleanup watchers (and execute them) */
  1474. if (expect_false (cleanupcnt))
  1475. {
  1476. queue_events (EV_A_ (W *)cleanups, cleanupcnt, EV_CLEANUP);
  1477. EV_INVOKE_PENDING;
  1478. }
  1479. #endif
  1480. #if EV_CHILD_ENABLE
  1481. if (ev_is_active (&childev))
  1482. {
  1483. ev_ref (EV_A); /* child watcher */
  1484. ev_signal_stop (EV_A_ &childev);
  1485. }
  1486. #endif
  1487. if (ev_is_active (&pipe_w))
  1488. {
  1489. /*ev_ref (EV_A);*/
  1490. /*ev_io_stop (EV_A_ &pipe_w);*/
  1491. #if EV_USE_EVENTFD
  1492. if (evfd >= 0)
  1493. close (evfd);
  1494. #endif
  1495. if (evpipe [0] >= 0)
  1496. {
  1497. EV_WIN32_CLOSE_FD (evpipe [0]);
  1498. EV_WIN32_CLOSE_FD (evpipe [1]);
  1499. }
  1500. }
  1501. #if EV_USE_SIGNALFD
  1502. if (ev_is_active (&sigfd_w))
  1503. close (sigfd);
  1504. #endif
  1505. #if EV_USE_INOTIFY
  1506. if (fs_fd >= 0)
  1507. close (fs_fd);
  1508. #endif
  1509. if (backend_fd >= 0)
  1510. close (backend_fd);
  1511. #if EV_USE_IOCP
  1512. if (backend == EVBACKEND_IOCP ) iocp_destroy (EV_A);
  1513. #endif
  1514. #if EV_USE_PORT
  1515. if (backend == EVBACKEND_PORT ) port_destroy (EV_A);
  1516. #endif
  1517. #if EV_USE_KQUEUE
  1518. if (backend == EVBACKEND_KQUEUE) kqueue_destroy (EV_A);
  1519. #endif
  1520. #if EV_USE_EPOLL
  1521. if (backend == EVBACKEND_EPOLL ) epoll_destroy (EV_A);
  1522. #endif
  1523. #if EV_USE_POLL
  1524. if (backend == EVBACKEND_POLL ) poll_destroy (EV_A);
  1525. #endif
  1526. #if EV_USE_SELECT
  1527. if (backend == EVBACKEND_SELECT) select_destroy (EV_A);
  1528. #endif
  1529. for (i = NUMPRI; i--; )
  1530. {
  1531. array_free (pending, [i]);
  1532. #if EV_IDLE_ENABLE
  1533. array_free (idle, [i]);
  1534. #endif
  1535. }
  1536. ev_free (anfds); anfds = 0; anfdmax = 0;
  1537. /* have to use the microsoft-never-gets-it-right macro */
  1538. array_free (rfeed, EMPTY);
  1539. array_free (fdchange, EMPTY);
  1540. array_free (timer, EMPTY);
  1541. #if EV_PERIODIC_ENABLE
  1542. array_free (periodic, EMPTY);
  1543. #endif
  1544. #if EV_FORK_ENABLE
  1545. array_free (fork, EMPTY);
  1546. #endif
  1547. #if EV_CLEANUP_ENABLE
  1548. array_free (cleanup, EMPTY);
  1549. #endif
  1550. array_free (prepare, EMPTY);
  1551. array_free (check, EMPTY);
  1552. #if EV_ASYNC_ENABLE
  1553. array_free (async, EMPTY);
  1554. #endif
  1555. backend = 0;
  1556. #if EV_MULTIPLICITY
  1557. if (ev_is_default_loop (EV_A))
  1558. #endif
  1559. ev_default_loop_ptr = 0;
  1560. #if EV_MULTIPLICITY
  1561. else
  1562. ev_free (EV_A);
  1563. #endif
  1564. }
  1565. #if EV_USE_INOTIFY
  1566. inline_size void infy_fork (EV_P);
  1567. #endif
  1568. inline_size void
  1569. loop_fork (EV_P)
  1570. {
  1571. #if EV_USE_PORT
  1572. if (backend == EVBACKEND_PORT ) port_fork (EV_A);
  1573. #endif
  1574. #if EV_USE_KQUEUE
  1575. if (backend == EVBACKEND_KQUEUE) kqueue_fork (EV_A);
  1576. #endif
  1577. #if EV_USE_EPOLL
  1578. if (backend == EVBACKEND_EPOLL ) epoll_fork (EV_A);
  1579. #endif
  1580. #if EV_USE_INOTIFY
  1581. infy_fork (EV_A);
  1582. #endif
  1583. if (ev_is_active (&pipe_w))
  1584. {
  1585. /* this "locks" the handlers against writing to the pipe */
  1586. /* while we modify the fd vars */
  1587. sig_pending = 1;
  1588. #if EV_ASYNC_ENABLE
  1589. async_pending = 1;
  1590. #endif
  1591. ev_ref (EV_A);
  1592. ev_io_stop (EV_A_ &pipe_w);
  1593. #if EV_USE_EVENTFD
  1594. if (evfd >= 0)
  1595. close (evfd);
  1596. #endif
  1597. if (evpipe [0] >= 0)
  1598. {
  1599. EV_WIN32_CLOSE_FD (evpipe [0]);
  1600. EV_WIN32_CLOSE_FD (evpipe [1]);
  1601. }
  1602. #if EV_SIGNAL_ENABLE || EV_ASYNC_ENABLE
  1603. evpipe_init (EV_A);
  1604. /* now iterate over everything, in case we missed something */
  1605. pipecb (EV_A_ &pipe_w, EV_READ);
  1606. #endif
  1607. }
  1608. postfork = 0;
  1609. }
  1610. #if EV_MULTIPLICITY
  1611. struct ev_loop *
  1612. ev_loop_new (unsigned int flags)
  1613. {
  1614. EV_P = (struct ev_loop *)ev_malloc (sizeof (struct ev_loop));
  1615. memset (EV_A, 0, sizeof (struct ev_loop));
  1616. loop_init (EV_A_ flags);
  1617. if (ev_backend (EV_A))
  1618. return EV_A;
  1619. ev_free (EV_A);
  1620. return 0;
  1621. }
  1622. #endif /* multiplicity */
  1623. #if EV_VERIFY
  1624. static void noinline
  1625. verify_watcher (EV_P_ W w)
  1626. {
  1627. assert (("libev: watcher has invalid priority", ABSPRI (w) >= 0 && ABSPRI (w) < NUMPRI));
  1628. if (w->pending)
  1629. assert (("libev: pending watcher not on pending queue", pendings [ABSPRI (w)][w->pending - 1].w == w));
  1630. }
  1631. static void noinline
  1632. verify_heap (EV_P_ ANHE *heap, int N)
  1633. {
  1634. int i;
  1635. for (i = HEAP0; i < N + HEAP0; ++i)
  1636. {
  1637. assert (("libev: active index mismatch in heap", ev_active (ANHE_w (heap [i])) == i));
  1638. assert (("libev: heap condition violated", i == HEAP0 || ANHE_at (heap [HPARENT (i)]) <= ANHE_at (heap [i])));
  1639. assert (("libev: heap at cache mismatch", ANHE_at (heap [i]) == ev_at (ANHE_w (heap [i]))));
  1640. verify_watcher (EV_A_ (W)ANHE_w (heap [i]));
  1641. }
  1642. }
  1643. static void noinline
  1644. array_verify (EV_P_ W *ws, int cnt)
  1645. {
  1646. while (cnt--)
  1647. {
  1648. assert (("libev: active index mismatch", ev_active (ws [cnt]) == cnt + 1));
  1649. verify_watcher (EV_A_ ws [cnt]);
  1650. }
  1651. }
  1652. #endif
  1653. #if EV_FEATURE_API
  1654. void
  1655. ev_verify (EV_P)
  1656. {
  1657. #if EV_VERIFY
  1658. int i;
  1659. WL w;
  1660. assert (activecnt >= -1);
  1661. assert (fdchangemax >= fdchangecnt);
  1662. for (i = 0; i < fdchangecnt; ++i)
  1663. assert (("libev: negative fd in fdchanges", fdchanges [i] >= 0));
  1664. assert (anfdmax >= 0);
  1665. for (i = 0; i < anfdmax; ++i)
  1666. for (w = anfds [i].head; w; w = w->next)
  1667. {
  1668. verify_watcher (EV_A_ (W)w);
  1669. assert (("libev: inactive fd watcher on anfd list", ev_active (w) == 1));
  1670. assert (("libev: fd mismatch between watcher and anfd", ((ev_io *)w)->fd == i));
  1671. }
  1672. assert (timermax >= timercnt);
  1673. verify_heap (EV_A_ timers, timercnt);
  1674. #if EV_PERIODIC_ENABLE
  1675. assert (periodicmax >= periodiccnt);
  1676. verify_heap (EV_A_ periodics, periodiccnt);
  1677. #endif
  1678. for (i = NUMPRI; i--; )
  1679. {
  1680. assert (pendingmax [i] >= pendingcnt [i]);
  1681. #if EV_IDLE_ENABLE
  1682. assert (idleall >= 0);
  1683. assert (idlemax [i] >= idlecnt [i]);
  1684. array_verify (EV_A_ (W *)idles [i], idlecnt [i]);
  1685. #endif
  1686. }
  1687. #if EV_FORK_ENABLE
  1688. assert (forkmax >= forkcnt);
  1689. array_verify (EV_A_ (W *)forks, forkcnt);
  1690. #endif
  1691. #if EV_CLEANUP_ENABLE
  1692. assert (cleanupmax >= cleanupcnt);
  1693. array_verify (EV_A_ (W *)cleanups, cleanupcnt);
  1694. #endif
  1695. #if EV_ASYNC_ENABLE
  1696. assert (asyncmax >= asynccnt);
  1697. array_verify (EV_A_ (W *)asyncs, asynccnt);
  1698. #endif
  1699. #if EV_PREPARE_ENABLE
  1700. assert (preparemax >= preparecnt);
  1701. array_verify (EV_A_ (W *)prepares, preparecnt);
  1702. #endif
  1703. #if EV_CHECK_ENABLE
  1704. assert (checkmax >= checkcnt);
  1705. array_verify (EV_A_ (W *)checks, checkcnt);
  1706. #endif
  1707. # if 0
  1708. #if EV_CHILD_ENABLE
  1709. for (w = (ev_child *)childs [chain & ((EV_PID_HASHSIZE) - 1)]; w; w = (ev_child *)((WL)w)->next)
  1710. for (signum = EV_NSIG; signum--; ) if (signals [signum].pending)
  1711. #endif
  1712. # endif
  1713. #endif
  1714. }
  1715. #endif
  1716. #if EV_MULTIPLICITY
  1717. struct ev_loop *
  1718. #else
  1719. int
  1720. #endif
  1721. ev_default_loop (unsigned int flags)
  1722. {
  1723. if (!ev_default_loop_ptr)
  1724. {
  1725. #if EV_MULTIPLICITY
  1726. EV_P = ev_default_loop_ptr = &default_loop_struct;
  1727. #else
  1728. ev_default_loop_ptr = 1;
  1729. #endif
  1730. loop_init (EV_A_ flags);
  1731. if (ev_backend (EV_A))
  1732. {
  1733. #if EV_CHILD_ENABLE
  1734. ev_signal_init (&childev, childcb, SIGCHLD);
  1735. ev_set_priority (&childev, EV_MAXPRI);
  1736. ev_signal_start (EV_A_ &childev);
  1737. ev_unref (EV_A); /* child watcher should not keep loop alive */
  1738. #endif
  1739. }
  1740. else
  1741. ev_default_loop_ptr = 0;
  1742. }
  1743. return ev_default_loop_ptr;
  1744. }
  1745. void
  1746. ev_loop_fork (EV_P)
  1747. {
  1748. postfork = 1; /* must be in line with ev_default_fork */
  1749. }
  1750. /*****************************************************************************/
  1751. void
  1752. ev_invoke (EV_P_ void *w, int revents)
  1753. {
  1754. EV_CB_INVOKE ((W)w, revents);
  1755. }
  1756. unsigned int
  1757. ev_pending_count (EV_P)
  1758. {
  1759. int pri;
  1760. unsigned int count = 0;
  1761. for (pri = NUMPRI; pri--; )
  1762. count += pendingcnt [pri];
  1763. return count;
  1764. }
  1765. void noinline
  1766. ev_invoke_pending (EV_P)
  1767. {
  1768. int pri;
  1769. for (pri = NUMPRI; pri--; )
  1770. while (pendingcnt [pri])
  1771. {
  1772. ANPENDING *p = pendings [pri] + --pendingcnt [pri];
  1773. p->w->pending = 0;
  1774. EV_CB_INVOKE (p->w, p->events);
  1775. EV_FREQUENT_CHECK;
  1776. }
  1777. }
  1778. #if EV_IDLE_ENABLE
  1779. /* make idle watchers pending. this handles the "call-idle */
  1780. /* only when higher priorities are idle" logic */
  1781. inline_size void
  1782. idle_reify (EV_P)
  1783. {
  1784. if (expect_false (idleall))
  1785. {
  1786. int pri;
  1787. for (pri = NUMPRI; pri--; )
  1788. {
  1789. if (pendingcnt [pri])
  1790. break;
  1791. if (idlecnt [pri])
  1792. {
  1793. queue_events (EV_A_ (W *)idles [pri], idlecnt [pri], EV_IDLE);
  1794. break;
  1795. }
  1796. }
  1797. }
  1798. }
  1799. #endif
  1800. /* make timers pending */
  1801. inline_size void
  1802. timers_reify (EV_P)
  1803. {
  1804. EV_FREQUENT_CHECK;
  1805. if (timercnt && ANHE_at (timers [HEAP0]) < mn_now)
  1806. {
  1807. do
  1808. {
  1809. ev_timer *w = (ev_timer *)ANHE_w (timers [HEAP0]);
  1810. /*assert (("libev: inactive timer on timer heap detected", ev_is_active (w)));*/
  1811. /* first reschedule or stop timer */
  1812. if (w->repeat)
  1813. {
  1814. ev_at (w) += w->repeat;
  1815. if (ev_at (w) < mn_now)
  1816. ev_at (w) = mn_now;
  1817. assert (("libev: negative ev_timer repeat value found while processing timers", w->repeat > 0.));
  1818. ANHE_at_cache (timers [HEAP0]);
  1819. downheap (timers, timercnt, HEAP0);
  1820. }
  1821. else
  1822. ev_timer_stop (EV_A_ w); /* nonrepeating: stop timer */
  1823. EV_FREQUENT_CHECK;
  1824. feed_reverse (EV_A_ (W)w);
  1825. }
  1826. while (timercnt && ANHE_at (timers [HEAP0]) < mn_now);
  1827. feed_reverse_done (EV_A_ EV_TIMER);
  1828. }
  1829. }
  1830. #if EV_PERIODIC_ENABLE
  1831. /* make periodics pending */
  1832. inline_size void
  1833. periodics_reify (EV_P)
  1834. {
  1835. EV_FREQUENT_CHECK;
  1836. while (periodiccnt && ANHE_at (periodics [HEAP0]) < ev_rt_now)
  1837. {
  1838. int feed_count = 0;
  1839. do
  1840. {
  1841. ev_periodic *w = (ev_periodic *)ANHE_w (periodics [HEAP0]);
  1842. /*assert (("libev: inactive timer on periodic heap detected", ev_is_active (w)));*/
  1843. /* first reschedule or stop timer */
  1844. if (w->reschedule_cb)
  1845. {
  1846. ev_at (w) = w->reschedule_cb (w, ev_rt_now);
  1847. assert (("libev: ev_periodic reschedule callback returned time in the past", ev_at (w) >= ev_rt_now));
  1848. ANHE_at_cache (periodics [HEAP0]);
  1849. downheap (periodics, periodiccnt, HEAP0);
  1850. }
  1851. else if (w->interval)
  1852. {
  1853. ev_at (w) = w->offset + ceil ((ev_rt_now - w->offset) / w->interval) * w->interval;
  1854. /* if next trigger time is not sufficiently in the future, put it there */
  1855. /* this might happen because of floating point inexactness */
  1856. if (ev_at (w) - ev_rt_now < TIME_EPSILON)
  1857. {
  1858. ev_at (w) += w->interval;
  1859. /* if interval is unreasonably low we might still have a time in the past */
  1860. /* so correct this. this will make the periodic very inexact, but the user */
  1861. /* has effectively asked to get triggered more often than possible */
  1862. if (ev_at (w) < ev_rt_now)
  1863. ev_at (w) = ev_rt_now;
  1864. }
  1865. ANHE_at_cache (periodics [HEAP0]);
  1866. downheap (periodics, periodiccnt, HEAP0);
  1867. }
  1868. else
  1869. ev_periodic_stop (EV_A_ w); /* nonrepeating: stop timer */
  1870. EV_FREQUENT_CHECK;
  1871. feed_reverse (EV_A_ (W)w);
  1872. }
  1873. while (periodiccnt && ANHE_at (periodics [HEAP0]) < ev_rt_now);
  1874. feed_reverse_done (EV_A_ EV_PERIODIC);
  1875. }
  1876. }
  1877. /* simply recalculate all periodics */
  1878. /* TODO: maybe ensure that at least one event happens when jumping forward? */
  1879. static void noinline
  1880. periodics_reschedule (EV_P)
  1881. {
  1882. int i;
  1883. /* adjust periodics after time jump */
  1884. for (i = HEAP0; i < periodiccnt + HEAP0; ++i)
  1885. {
  1886. ev_periodic *w = (ev_periodic *)ANHE_w (periodics [i]);
  1887. if (w->reschedule_cb)
  1888. ev_at (w) = w->reschedule_cb (w, ev_rt_now);
  1889. else if (w->interval)
  1890. ev_at (w) = w->offset + ceil ((ev_rt_now - w->offset) / w->interval) * w->interval;
  1891. ANHE_at_cache (periodics [i]);
  1892. }
  1893. reheap (periodics, periodiccnt);
  1894. }
  1895. #endif
  1896. /* adjust all timers by a given offset */
  1897. static void noinline
  1898. timers_reschedule (EV_P_ ev_tstamp adjust)
  1899. {
  1900. int i;
  1901. for (i = 0; i < timercnt; ++i)
  1902. {
  1903. ANHE *he = timers + i + HEAP0;
  1904. ANHE_w (*he)->at += adjust;
  1905. ANHE_at_cache (*he);
  1906. }
  1907. }
  1908. /* fetch new monotonic and realtime times from the kernel */
  1909. /* also detect if there was a timejump, and act accordingly */
  1910. inline_speed void
  1911. time_update (EV_P_ ev_tstamp max_block)
  1912. {
  1913. #if EV_USE_MONOTONIC
  1914. if (expect_true (have_monotonic))
  1915. {
  1916. int i;
  1917. ev_tstamp odiff = rtmn_diff;
  1918. mn_now = get_clock ();
  1919. /* only fetch the realtime clock every 0.5*MIN_TIMEJUMP seconds */
  1920. /* interpolate in the meantime */
  1921. if (expect_true (mn_now - now_floor < MIN_TIMEJUMP * .5))
  1922. {
  1923. ev_rt_now = rtmn_diff + mn_now;
  1924. return;
  1925. }
  1926. now_floor = mn_now;
  1927. ev_rt_now = ev_time ();
  1928. /* loop a few times, before making important decisions.
  1929. * on the choice of "4": one iteration isn't enough,
  1930. * in case we get preempted during the calls to
  1931. * ev_time and get_clock. a second call is almost guaranteed
  1932. * to succeed in that case, though. and looping a few more times
  1933. * doesn't hurt either as we only do this on time-jumps or
  1934. * in the unlikely event of having been preempted here.
  1935. */
  1936. for (i = 4; --i; )
  1937. {
  1938. rtmn_diff = ev_rt_now - mn_now;
  1939. if (expect_true (fabs (odiff - rtmn_diff) < MIN_TIMEJUMP))
  1940. return; /* all is well */
  1941. ev_rt_now = ev_time ();
  1942. mn_now = get_clock ();
  1943. now_floor = mn_now;
  1944. }
  1945. /* no timer adjustment, as the monotonic clock doesn't jump */
  1946. /* timers_reschedule (EV_A_ rtmn_diff - odiff) */
  1947. # if EV_PERIODIC_ENABLE
  1948. periodics_reschedule (EV_A);
  1949. # endif
  1950. }
  1951. else
  1952. #endif
  1953. {
  1954. ev_rt_now = ev_time ();
  1955. if (expect_false (mn_now > ev_rt_now || ev_rt_now > mn_now + max_block + MIN_TIMEJUMP))
  1956. {
  1957. /* adjust timers. this is easy, as the offset is the same for all of them */
  1958. timers_reschedule (EV_A_ ev_rt_now - mn_now);
  1959. #if EV_PERIODIC_ENABLE
  1960. periodics_reschedule (EV_A);
  1961. #endif
  1962. }
  1963. mn_now = ev_rt_now;
  1964. }
  1965. }
  1966. void
  1967. ev_run (EV_P_ int flags)
  1968. {
  1969. #if EV_FEATURE_API
  1970. ++loop_depth;
  1971. #endif
  1972. assert (("libev: ev_loop recursion during release detected", loop_done != EVBREAK_RECURSE));
  1973. loop_done = EVBREAK_CANCEL;
  1974. EV_INVOKE_PENDING; /* in case we recurse, ensure ordering stays nice and clean */
  1975. do
  1976. {
  1977. #if EV_VERIFY >= 2
  1978. ev_verify (EV_A);
  1979. #endif
  1980. #ifndef _WIN32
  1981. if (expect_false (curpid)) /* penalise the forking check even more */
  1982. if (expect_false (getpid () != curpid))
  1983. {
  1984. curpid = getpid ();
  1985. postfork = 1;
  1986. }
  1987. #endif
  1988. #if EV_FORK_ENABLE
  1989. /* we might have forked, so queue fork handlers */
  1990. if (expect_false (postfork))
  1991. if (forkcnt)
  1992. {
  1993. queue_events (EV_A_ (W *)forks, forkcnt, EV_FORK);
  1994. EV_INVOKE_PENDING;
  1995. }
  1996. #endif
  1997. #if EV_PREPARE_ENABLE
  1998. /* queue prepare watchers (and execute them) */
  1999. if (expect_false (preparecnt))
  2000. {
  2001. queue_events (EV_A_ (W *)prepares, preparecnt, EV_PREPARE);
  2002. EV_INVOKE_PENDING;
  2003. }
  2004. #endif
  2005. if (expect_false (loop_done))
  2006. break;
  2007. /* we might have forked, so reify kernel state if necessary */
  2008. if (expect_false (postfork))
  2009. loop_fork (EV_A);
  2010. /* update fd-related kernel structures */
  2011. fd_reify (EV_A);
  2012. /* calculate blocking time */
  2013. {
  2014. ev_tstamp waittime = 0.;
  2015. ev_tstamp sleeptime = 0.;
  2016. /* remember old timestamp for io_blocktime calculation */
  2017. ev_tstamp prev_mn_now = mn_now;
  2018. /* update time to cancel out callback processing overhead */
  2019. time_update (EV_A_ 1e100);
  2020. if (expect_true (!(flags & EVRUN_NOWAIT || idleall || !activecnt)))
  2021. {
  2022. waittime = MAX_BLOCKTIME;
  2023. if (timercnt)
  2024. {
  2025. ev_tstamp to = ANHE_at (timers [HEAP0]) - mn_now + backend_fudge;
  2026. if (waittime > to) waittime = to;
  2027. }
  2028. #if EV_PERIODIC_ENABLE
  2029. if (periodiccnt)
  2030. {
  2031. ev_tstamp to = ANHE_at (periodics [HEAP0]) - ev_rt_now + backend_fudge;
  2032. if (waittime > to) waittime = to;
  2033. }
  2034. #endif
  2035. /* don't let timeouts decrease the waittime below timeout_blocktime */
  2036. if (expect_false (waittime < timeout_blocktime))
  2037. waittime = timeout_blocktime;
  2038. /* extra check because io_blocktime is commonly 0 */
  2039. if (expect_false (io_blocktime))
  2040. {
  2041. sleeptime = io_blocktime - (mn_now - prev_mn_now);
  2042. if (sleeptime > waittime - backend_fudge)
  2043. sleeptime = waittime - backend_fudge;
  2044. if (expect_true (sleeptime > 0.))
  2045. {
  2046. ev_sleep (sleeptime);
  2047. waittime -= sleeptime;
  2048. }
  2049. }
  2050. }
  2051. #if EV_FEATURE_API
  2052. ++loop_count;
  2053. #endif
  2054. assert ((loop_done = EVBREAK_RECURSE, 1)); /* assert for side effect */
  2055. backend_poll (EV_A_ waittime);
  2056. assert ((loop_done = EVBREAK_CANCEL, 1)); /* assert for side effect */
  2057. /* update ev_rt_now, do magic */
  2058. time_update (EV_A_ waittime + sleeptime);
  2059. }
  2060. /* queue pending timers and reschedule them */
  2061. timers_reify (EV_A); /* relative timers called last */
  2062. #if EV_PERIODIC_ENABLE
  2063. periodics_reify (EV_A); /* absolute timers called first */
  2064. #endif
  2065. #if EV_IDLE_ENABLE
  2066. /* queue idle watchers unless other events are pending */
  2067. idle_reify (EV_A);
  2068. #endif
  2069. #if EV_CHECK_ENABLE
  2070. /* queue check watchers, to be executed first */
  2071. if (expect_false (checkcnt))
  2072. queue_events (EV_A_ (W *)checks, checkcnt, EV_CHECK);
  2073. #endif
  2074. EV_INVOKE_PENDING;
  2075. }
  2076. while (expect_true (
  2077. activecnt
  2078. && !loop_done
  2079. && !(flags & (EVRUN_ONCE | EVRUN_NOWAIT))
  2080. ));
  2081. if (loop_done == EVBREAK_ONE)
  2082. loop_done = EVBREAK_CANCEL;
  2083. #if EV_FEATURE_API
  2084. --loop_depth;
  2085. #endif
  2086. }
  2087. void
  2088. ev_break (EV_P_ int how)
  2089. {
  2090. loop_done = how;
  2091. }
  2092. void
  2093. ev_ref (EV_P)
  2094. {
  2095. ++activecnt;
  2096. }
  2097. void
  2098. ev_unref (EV_P)
  2099. {
  2100. --activecnt;
  2101. }
  2102. void
  2103. ev_now_update (EV_P)
  2104. {
  2105. time_update (EV_A_ 1e100);
  2106. }
  2107. void
  2108. ev_suspend (EV_P)
  2109. {
  2110. ev_now_update (EV_A);
  2111. }
  2112. void
  2113. ev_resume (EV_P)
  2114. {
  2115. ev_tstamp mn_prev = mn_now;
  2116. ev_now_update (EV_A);
  2117. timers_reschedule (EV_A_ mn_now - mn_prev);
  2118. #if EV_PERIODIC_ENABLE
  2119. /* TODO: really do this? */
  2120. periodics_reschedule (EV_A);
  2121. #endif
  2122. }
  2123. /*****************************************************************************/
  2124. /* singly-linked list management, used when the expected list length is short */
  2125. inline_size void
  2126. wlist_add (WL *head, WL elem)
  2127. {
  2128. elem->next = *head;
  2129. *head = elem;
  2130. }
  2131. inline_size void
  2132. wlist_del (WL *head, WL elem)
  2133. {
  2134. while (*head)
  2135. {
  2136. if (expect_true (*head == elem))
  2137. {
  2138. *head = elem->next;
  2139. break;
  2140. }
  2141. head = &(*head)->next;
  2142. }
  2143. }
  2144. /* internal, faster, version of ev_clear_pending */
  2145. inline_speed void
  2146. clear_pending (EV_P_ W w)
  2147. {
  2148. if (w->pending)
  2149. {
  2150. pendings [ABSPRI (w)][w->pending - 1].w = (W)&pending_w;
  2151. w->pending = 0;
  2152. }
  2153. }
  2154. int
  2155. ev_clear_pending (EV_P_ void *w)
  2156. {
  2157. W w_ = (W)w;
  2158. int pending = w_->pending;
  2159. if (expect_true (pending))
  2160. {
  2161. ANPENDING *p = pendings [ABSPRI (w_)] + pending - 1;
  2162. p->w = (W)&pending_w;
  2163. w_->pending = 0;
  2164. return p->events;
  2165. }
  2166. else
  2167. return 0;
  2168. }
  2169. inline_size void
  2170. pri_adjust (EV_P_ W w)
  2171. {
  2172. int pri = ev_priority (w);
  2173. pri = pri < EV_MINPRI ? EV_MINPRI : pri;
  2174. pri = pri > EV_MAXPRI ? EV_MAXPRI : pri;
  2175. ev_set_priority (w, pri);
  2176. }
  2177. inline_speed void
  2178. ev_start (EV_P_ W w, int active)
  2179. {
  2180. pri_adjust (EV_A_ w);
  2181. w->active = active;
  2182. ev_ref (EV_A);
  2183. }
  2184. inline_size void
  2185. ev_stop (EV_P_ W w)
  2186. {
  2187. ev_unref (EV_A);
  2188. w->active = 0;
  2189. }
  2190. /*****************************************************************************/
  2191. void noinline
  2192. ev_io_start (EV_P_ ev_io *w)
  2193. {
  2194. int fd = w->fd;
  2195. if (expect_false (ev_is_active (w)))
  2196. return;
  2197. assert (("libev: ev_io_start called with negative fd", fd >= 0));
  2198. assert (("libev: ev_io_start called with illegal event mask", !(w->events & ~(EV__IOFDSET | EV_READ | EV_WRITE))));
  2199. EV_FREQUENT_CHECK;
  2200. ev_start (EV_A_ (W)w, 1);
  2201. array_needsize (ANFD, anfds, anfdmax, fd + 1, array_init_zero);
  2202. wlist_add (&anfds[fd].head, (WL)w);
  2203. fd_change (EV_A_ fd, w->events & EV__IOFDSET | EV_ANFD_REIFY);
  2204. w->events &= ~EV__IOFDSET;
  2205. EV_FREQUENT_CHECK;
  2206. }
  2207. void noinline
  2208. ev_io_stop (EV_P_ ev_io *w)
  2209. {
  2210. clear_pending (EV_A_ (W)w);
  2211. if (expect_false (!ev_is_active (w)))
  2212. return;
  2213. assert (("libev: ev_io_stop called with illegal fd (must stay constant after start!)", w->fd >= 0 && w->fd < anfdmax));
  2214. EV_FREQUENT_CHECK;
  2215. wlist_del (&anfds[w->fd].head, (WL)w);
  2216. ev_stop (EV_A_ (W)w);
  2217. fd_change (EV_A_ w->fd, EV_ANFD_REIFY);
  2218. EV_FREQUENT_CHECK;
  2219. }
  2220. void noinline
  2221. ev_timer_start (EV_P_ ev_timer *w)
  2222. {
  2223. if (expect_false (ev_is_active (w)))
  2224. return;
  2225. ev_at (w) += mn_now;
  2226. assert (("libev: ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
  2227. EV_FREQUENT_CHECK;
  2228. ++timercnt;
  2229. ev_start (EV_A_ (W)w, timercnt + HEAP0 - 1);
  2230. array_needsize (ANHE, timers, timermax, ev_active (w) + 1, EMPTY2);
  2231. ANHE_w (timers [ev_active (w)]) = (WT)w;
  2232. ANHE_at_cache (timers [ev_active (w)]);
  2233. upheap (timers, ev_active (w));
  2234. EV_FREQUENT_CHECK;
  2235. /*assert (("libev: internal timer heap corruption", timers [ev_active (w)] == (WT)w));*/
  2236. }
  2237. void noinline
  2238. ev_timer_stop (EV_P_ ev_timer *w)
  2239. {
  2240. clear_pending (EV_A_ (W)w);
  2241. if (expect_false (!ev_is_active (w)))
  2242. return;
  2243. EV_FREQUENT_CHECK;
  2244. {
  2245. int active = ev_active (w);
  2246. assert (("libev: internal timer heap corruption", ANHE_w (timers [active]) == (WT)w));
  2247. --timercnt;
  2248. if (expect_true (active < timercnt + HEAP0))
  2249. {
  2250. timers [active] = timers [timercnt + HEAP0];
  2251. adjustheap (timers, timercnt, active);
  2252. }
  2253. }
  2254. ev_at (w) -= mn_now;
  2255. ev_stop (EV_A_ (W)w);
  2256. EV_FREQUENT_CHECK;
  2257. }
  2258. void noinline
  2259. ev_timer_again (EV_P_ ev_timer *w)
  2260. {
  2261. EV_FREQUENT_CHECK;
  2262. if (ev_is_active (w))
  2263. {
  2264. if (w->repeat)
  2265. {
  2266. ev_at (w) = mn_now + w->repeat;
  2267. ANHE_at_cache (timers [ev_active (w)]);
  2268. adjustheap (timers, timercnt, ev_active (w));
  2269. }
  2270. else
  2271. ev_timer_stop (EV_A_ w);
  2272. }
  2273. else if (w->repeat)
  2274. {
  2275. ev_at (w) = w->repeat;
  2276. ev_timer_start (EV_A_ w);
  2277. }
  2278. EV_FREQUENT_CHECK;
  2279. }
  2280. ev_tstamp
  2281. ev_timer_remaining (EV_P_ ev_timer *w)
  2282. {
  2283. return ev_at (w) - (ev_is_active (w) ? mn_now : 0.);
  2284. }
  2285. #if EV_PERIODIC_ENABLE
  2286. void noinline
  2287. ev_periodic_start (EV_P_ ev_periodic *w)
  2288. {
  2289. if (expect_false (ev_is_active (w)))
  2290. return;
  2291. if (w->reschedule_cb)
  2292. ev_at (w) = w->reschedule_cb (w, ev_rt_now);
  2293. else if (w->interval)
  2294. {
  2295. assert (("libev: ev_periodic_start called with negative interval value", w->interval >= 0.));
  2296. /* this formula differs from the one in periodic_reify because we do not always round up */
  2297. ev_at (w) = w->offset + ceil ((ev_rt_now - w->offset) / w->interval) * w->interval;
  2298. }
  2299. else
  2300. ev_at (w) = w->offset;
  2301. EV_FREQUENT_CHECK;
  2302. ++periodiccnt;
  2303. ev_start (EV_A_ (W)w, periodiccnt + HEAP0 - 1);
  2304. array_needsize (ANHE, periodics, periodicmax, ev_active (w) + 1, EMPTY2);
  2305. ANHE_w (periodics [ev_active (w)]) = (WT)w;
  2306. ANHE_at_cache (periodics [ev_active (w)]);
  2307. upheap (periodics, ev_active (w));
  2308. EV_FREQUENT_CHECK;
  2309. /*assert (("libev: internal periodic heap corruption", ANHE_w (periodics [ev_active (w)]) == (WT)w));*/
  2310. }
  2311. void noinline
  2312. ev_periodic_stop (EV_P_ ev_periodic *w)
  2313. {
  2314. clear_pending (EV_A_ (W)w);
  2315. if (expect_false (!ev_is_active (w)))
  2316. return;
  2317. EV_FREQUENT_CHECK;
  2318. {
  2319. int active = ev_active (w);
  2320. assert (("libev: internal periodic heap corruption", ANHE_w (periodics [active]) == (WT)w));
  2321. --periodiccnt;
  2322. if (expect_true (active < periodiccnt + HEAP0))
  2323. {
  2324. periodics [active] = periodics [periodiccnt + HEAP0];
  2325. adjustheap (periodics, periodiccnt, active);
  2326. }
  2327. }
  2328. ev_stop (EV_A_ (W)w);
  2329. EV_FREQUENT_CHECK;
  2330. }
  2331. void noinline
  2332. ev_periodic_again (EV_P_ ev_periodic *w)
  2333. {
  2334. /* TODO: use adjustheap and recalculation */
  2335. ev_periodic_stop (EV_A_ w);
  2336. ev_periodic_start (EV_A_ w);
  2337. }
  2338. #endif
  2339. #ifndef SA_RESTART
  2340. # define SA_RESTART 0
  2341. #endif
  2342. #if EV_SIGNAL_ENABLE
  2343. void noinline
  2344. ev_signal_start (EV_P_ ev_signal *w)
  2345. {
  2346. if (expect_false (ev_is_active (w)))
  2347. return;
  2348. assert (("libev: ev_signal_start called with illegal signal number", w->signum > 0 && w->signum < EV_NSIG));
  2349. #if EV_MULTIPLICITY
  2350. assert (("libev: a signal must not be attached to two different loops",
  2351. !signals [w->signum - 1].loop || signals [w->signum - 1].loop == loop));
  2352. signals [w->signum - 1].loop = EV_A;
  2353. #endif
  2354. EV_FREQUENT_CHECK;
  2355. #if EV_USE_SIGNALFD
  2356. if (sigfd == -2)
  2357. {
  2358. sigfd = signalfd (-1, &sigfd_set, SFD_NONBLOCK | SFD_CLOEXEC);
  2359. if (sigfd < 0 && errno == EINVAL)
  2360. sigfd = signalfd (-1, &sigfd_set, 0); /* retry without flags */
  2361. if (sigfd >= 0)
  2362. {
  2363. fd_intern (sigfd); /* doing it twice will not hurt */
  2364. sigemptyset (&sigfd_set);
  2365. ev_io_init (&sigfd_w, sigfdcb, sigfd, EV_READ);
  2366. ev_set_priority (&sigfd_w, EV_MAXPRI);
  2367. ev_io_start (EV_A_ &sigfd_w);
  2368. ev_unref (EV_A); /* signalfd watcher should not keep loop alive */
  2369. }
  2370. }
  2371. if (sigfd >= 0)
  2372. {
  2373. /* TODO: check .head */
  2374. sigaddset (&sigfd_set, w->signum);
  2375. sigprocmask (SIG_BLOCK, &sigfd_set, 0);
  2376. signalfd (sigfd, &sigfd_set, 0);
  2377. }
  2378. #endif
  2379. ev_start (EV_A_ (W)w, 1);
  2380. wlist_add (&signals [w->signum - 1].head, (WL)w);
  2381. if (!((WL)w)->next)
  2382. # if EV_USE_SIGNALFD
  2383. if (sigfd < 0) /*TODO*/
  2384. # endif
  2385. {
  2386. # ifdef _WIN32
  2387. evpipe_init (EV_A);
  2388. signal (w->signum, ev_sighandler);
  2389. # else
  2390. struct sigaction sa;
  2391. evpipe_init (EV_A);
  2392. sa.sa_handler = ev_sighandler;
  2393. sigfillset (&sa.sa_mask);
  2394. sa.sa_flags = SA_RESTART; /* if restarting works we save one iteration */
  2395. sigaction (w->signum, &sa, 0);
  2396. if (origflags & EVFLAG_NOSIGMASK)
  2397. {
  2398. sigemptyset (&sa.sa_mask);
  2399. sigaddset (&sa.sa_mask, w->signum);
  2400. sigprocmask (SIG_UNBLOCK, &sa.sa_mask, 0);
  2401. }
  2402. #endif
  2403. }
  2404. EV_FREQUENT_CHECK;
  2405. }
  2406. void noinline
  2407. ev_signal_stop (EV_P_ ev_signal *w)
  2408. {
  2409. clear_pending (EV_A_ (W)w);
  2410. if (expect_false (!ev_is_active (w)))
  2411. return;
  2412. EV_FREQUENT_CHECK;
  2413. wlist_del (&signals [w->signum - 1].head, (WL)w);
  2414. ev_stop (EV_A_ (W)w);
  2415. if (!signals [w->signum - 1].head)
  2416. {
  2417. #if EV_MULTIPLICITY
  2418. signals [w->signum - 1].loop = 0; /* unattach from signal */
  2419. #endif
  2420. #if EV_USE_SIGNALFD
  2421. if (sigfd >= 0)
  2422. {
  2423. sigset_t ss;
  2424. sigemptyset (&ss);
  2425. sigaddset (&ss, w->signum);
  2426. sigdelset (&sigfd_set, w->signum);
  2427. signalfd (sigfd, &sigfd_set, 0);
  2428. sigprocmask (SIG_UNBLOCK, &ss, 0);
  2429. }
  2430. else
  2431. #endif
  2432. signal (w->signum, SIG_DFL);
  2433. }
  2434. EV_FREQUENT_CHECK;
  2435. }
  2436. #endif
  2437. #if EV_CHILD_ENABLE
  2438. void
  2439. ev_child_start (EV_P_ ev_child *w)
  2440. {
  2441. #if EV_MULTIPLICITY
  2442. assert (("libev: child watchers are only supported in the default loop", loop == ev_default_loop_ptr));
  2443. #endif
  2444. if (expect_false (ev_is_active (w)))
  2445. return;
  2446. EV_FREQUENT_CHECK;
  2447. ev_start (EV_A_ (W)w, 1);
  2448. wlist_add (&childs [w->pid & ((EV_PID_HASHSIZE) - 1)], (WL)w);
  2449. EV_FREQUENT_CHECK;
  2450. }
  2451. void
  2452. ev_child_stop (EV_P_ ev_child *w)
  2453. {
  2454. clear_pending (EV_A_ (W)w);
  2455. if (expect_false (!ev_is_active (w)))
  2456. return;
  2457. EV_FREQUENT_CHECK;
  2458. wlist_del (&childs [w->pid & ((EV_PID_HASHSIZE) - 1)], (WL)w);
  2459. ev_stop (EV_A_ (W)w);
  2460. EV_FREQUENT_CHECK;
  2461. }
  2462. #endif
  2463. #if EV_STAT_ENABLE
  2464. # ifdef _WIN32
  2465. # undef lstat
  2466. # define lstat(a,b) _stati64 (a,b)
  2467. # endif
  2468. #define DEF_STAT_INTERVAL 5.0074891
  2469. #define NFS_STAT_INTERVAL 30.1074891 /* for filesystems potentially failing inotify */
  2470. #define MIN_STAT_INTERVAL 0.1074891
  2471. static void noinline stat_timer_cb (EV_P_ ev_timer *w_, int revents);
  2472. #if EV_USE_INOTIFY
  2473. /* the * 2 is to allow for alignment padding, which for some reason is >> 8 */
  2474. # define EV_INOTIFY_BUFSIZE (sizeof (struct inotify_event) * 2 + NAME_MAX)
  2475. static void noinline
  2476. infy_add (EV_P_ ev_stat *w)
  2477. {
  2478. w->wd = inotify_add_watch (fs_fd, w->path, IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF | IN_MODIFY | IN_DONT_FOLLOW | IN_MASK_ADD);
  2479. if (w->wd >= 0)
  2480. {
  2481. struct statfs sfs;
  2482. /* now local changes will be tracked by inotify, but remote changes won't */
  2483. /* unless the filesystem is known to be local, we therefore still poll */
  2484. /* also do poll on <2.6.25, but with normal frequency */
  2485. if (!fs_2625)
  2486. w->timer.repeat = w->interval ? w->interval : DEF_STAT_INTERVAL;
  2487. else if (!statfs (w->path, &sfs)
  2488. && (sfs.f_type == 0x1373 /* devfs */
  2489. || sfs.f_type == 0xEF53 /* ext2/3 */
  2490. || sfs.f_type == 0x3153464a /* jfs */
  2491. || sfs.f_type == 0x52654973 /* reiser3 */
  2492. || sfs.f_type == 0x01021994 /* tempfs */
  2493. || sfs.f_type == 0x58465342 /* xfs */))
  2494. w->timer.repeat = 0.; /* filesystem is local, kernel new enough */
  2495. else
  2496. w->timer.repeat = w->interval ? w->interval : NFS_STAT_INTERVAL; /* remote, use reduced frequency */
  2497. }
  2498. else
  2499. {
  2500. /* can't use inotify, continue to stat */
  2501. w->timer.repeat = w->interval ? w->interval : DEF_STAT_INTERVAL;
  2502. /* if path is not there, monitor some parent directory for speedup hints */
  2503. /* note that exceeding the hardcoded path limit is not a correctness issue, */
  2504. /* but an efficiency issue only */
  2505. if ((errno == ENOENT || errno == EACCES) && strlen (w->path) < 4096)
  2506. {
  2507. char path [4096];
  2508. strcpy (path, w->path);
  2509. do
  2510. {
  2511. int mask = IN_MASK_ADD | IN_DELETE_SELF | IN_MOVE_SELF
  2512. | (errno == EACCES ? IN_ATTRIB : IN_CREATE | IN_MOVED_TO);
  2513. char *pend = strrchr (path, '/');
  2514. if (!pend || pend == path)
  2515. break;
  2516. *pend = 0;
  2517. w->wd = inotify_add_watch (fs_fd, path, mask);
  2518. }
  2519. while (w->wd < 0 && (errno == ENOENT || errno == EACCES));
  2520. }
  2521. }
  2522. if (w->wd >= 0)
  2523. wlist_add (&fs_hash [w->wd & ((EV_INOTIFY_HASHSIZE) - 1)].head, (WL)w);
  2524. /* now re-arm timer, if required */
  2525. if (ev_is_active (&w->timer)) ev_ref (EV_A);
  2526. ev_timer_again (EV_A_ &w->timer);
  2527. if (ev_is_active (&w->timer)) ev_unref (EV_A);
  2528. }
  2529. static void noinline
  2530. infy_del (EV_P_ ev_stat *w)
  2531. {
  2532. int slot;
  2533. int wd = w->wd;
  2534. if (wd < 0)
  2535. return;
  2536. w->wd = -2;
  2537. slot = wd & ((EV_INOTIFY_HASHSIZE) - 1);
  2538. wlist_del (&fs_hash [slot].head, (WL)w);
  2539. /* remove this watcher, if others are watching it, they will rearm */
  2540. inotify_rm_watch (fs_fd, wd);
  2541. }
  2542. static void noinline
  2543. infy_wd (EV_P_ int slot, int wd, struct inotify_event *ev)
  2544. {
  2545. if (slot < 0)
  2546. /* overflow, need to check for all hash slots */
  2547. for (slot = 0; slot < (EV_INOTIFY_HASHSIZE); ++slot)
  2548. infy_wd (EV_A_ slot, wd, ev);
  2549. else
  2550. {
  2551. WL w_;
  2552. for (w_ = fs_hash [slot & ((EV_INOTIFY_HASHSIZE) - 1)].head; w_; )
  2553. {
  2554. ev_stat *w = (ev_stat *)w_;
  2555. w_ = w_->next; /* lets us remove this watcher and all before it */
  2556. if (w->wd == wd || wd == -1)
  2557. {
  2558. if (ev->mask & (IN_IGNORED | IN_UNMOUNT | IN_DELETE_SELF))
  2559. {
  2560. wlist_del (&fs_hash [slot & ((EV_INOTIFY_HASHSIZE) - 1)].head, (WL)w);
  2561. w->wd = -1;
  2562. infy_add (EV_A_ w); /* re-add, no matter what */
  2563. }
  2564. stat_timer_cb (EV_A_ &w->timer, 0);
  2565. }
  2566. }
  2567. }
  2568. }
  2569. static void
  2570. infy_cb (EV_P_ ev_io *w, int revents)
  2571. {
  2572. char buf [EV_INOTIFY_BUFSIZE];
  2573. int ofs;
  2574. int len = read (fs_fd, buf, sizeof (buf));
  2575. for (ofs = 0; ofs < len; )
  2576. {
  2577. struct inotify_event *ev = (struct inotify_event *)(buf + ofs);
  2578. infy_wd (EV_A_ ev->wd, ev->wd, ev);
  2579. ofs += sizeof (struct inotify_event) + ev->len;
  2580. }
  2581. }
  2582. inline_size void
  2583. ev_check_2625 (EV_P)
  2584. {
  2585. /* kernels < 2.6.25 are borked
  2586. * http://www.ussg.indiana.edu/hypermail/linux/kernel/0711.3/1208.html
  2587. */
  2588. if (ev_linux_version () < 0x020619)
  2589. return;
  2590. fs_2625 = 1;
  2591. }
  2592. inline_size int
  2593. infy_newfd (void)
  2594. {
  2595. #if defined (IN_CLOEXEC) && defined (IN_NONBLOCK)
  2596. int fd = inotify_init1 (IN_CLOEXEC | IN_NONBLOCK);
  2597. if (fd >= 0)
  2598. return fd;
  2599. #endif
  2600. return inotify_init ();
  2601. }
  2602. inline_size void
  2603. infy_init (EV_P)
  2604. {
  2605. if (fs_fd != -2)
  2606. return;
  2607. fs_fd = -1;
  2608. ev_check_2625 (EV_A);
  2609. fs_fd = infy_newfd ();
  2610. if (fs_fd >= 0)
  2611. {
  2612. fd_intern (fs_fd);
  2613. ev_io_init (&fs_w, infy_cb, fs_fd, EV_READ);
  2614. ev_set_priority (&fs_w, EV_MAXPRI);
  2615. ev_io_start (EV_A_ &fs_w);
  2616. ev_unref (EV_A);
  2617. }
  2618. }
  2619. inline_size void
  2620. infy_fork (EV_P)
  2621. {
  2622. int slot;
  2623. if (fs_fd < 0)
  2624. return;
  2625. ev_ref (EV_A);
  2626. ev_io_stop (EV_A_ &fs_w);
  2627. close (fs_fd);
  2628. fs_fd = infy_newfd ();
  2629. if (fs_fd >= 0)
  2630. {
  2631. fd_intern (fs_fd);
  2632. ev_io_set (&fs_w, fs_fd, EV_READ);
  2633. ev_io_start (EV_A_ &fs_w);
  2634. ev_unref (EV_A);
  2635. }
  2636. for (slot = 0; slot < (EV_INOTIFY_HASHSIZE); ++slot)
  2637. {
  2638. WL w_ = fs_hash [slot].head;
  2639. fs_hash [slot].head = 0;
  2640. while (w_)
  2641. {
  2642. ev_stat *w = (ev_stat *)w_;
  2643. w_ = w_->next; /* lets us add this watcher */
  2644. w->wd = -1;
  2645. if (fs_fd >= 0)
  2646. infy_add (EV_A_ w); /* re-add, no matter what */
  2647. else
  2648. {
  2649. w->timer.repeat = w->interval ? w->interval : DEF_STAT_INTERVAL;
  2650. if (ev_is_active (&w->timer)) ev_ref (EV_A);
  2651. ev_timer_again (EV_A_ &w->timer);
  2652. if (ev_is_active (&w->timer)) ev_unref (EV_A);
  2653. }
  2654. }
  2655. }
  2656. }
  2657. #endif
  2658. #ifdef _WIN32
  2659. # define EV_LSTAT(p,b) _stati64 (p, b)
  2660. #else
  2661. # define EV_LSTAT(p,b) lstat (p, b)
  2662. #endif
  2663. void
  2664. ev_stat_stat (EV_P_ ev_stat *w)
  2665. {
  2666. if (lstat (w->path, &w->attr) < 0)
  2667. w->attr.st_nlink = 0;
  2668. else if (!w->attr.st_nlink)
  2669. w->attr.st_nlink = 1;
  2670. }
  2671. static void noinline
  2672. stat_timer_cb (EV_P_ ev_timer *w_, int revents)
  2673. {
  2674. ev_stat *w = (ev_stat *)(((char *)w_) - offsetof (ev_stat, timer));
  2675. ev_statdata prev = w->attr;
  2676. ev_stat_stat (EV_A_ w);
  2677. /* memcmp doesn't work on netbsd, they.... do stuff to their struct stat */
  2678. if (
  2679. prev.st_dev != w->attr.st_dev
  2680. || prev.st_ino != w->attr.st_ino
  2681. || prev.st_mode != w->attr.st_mode
  2682. || prev.st_nlink != w->attr.st_nlink
  2683. || prev.st_uid != w->attr.st_uid
  2684. || prev.st_gid != w->attr.st_gid
  2685. || prev.st_rdev != w->attr.st_rdev
  2686. || prev.st_size != w->attr.st_size
  2687. || prev.st_atime != w->attr.st_atime
  2688. || prev.st_mtime != w->attr.st_mtime
  2689. || prev.st_ctime != w->attr.st_ctime
  2690. ) {
  2691. /* we only update w->prev on actual differences */
  2692. /* in case we test more often than invoke the callback, */
  2693. /* to ensure that prev is always different to attr */
  2694. w->prev = prev;
  2695. #if EV_USE_INOTIFY
  2696. if (fs_fd >= 0)
  2697. {
  2698. infy_del (EV_A_ w);
  2699. infy_add (EV_A_ w);
  2700. ev_stat_stat (EV_A_ w); /* avoid race... */
  2701. }
  2702. #endif
  2703. ev_feed_event (EV_A_ w, EV_STAT);
  2704. }
  2705. }
  2706. void
  2707. ev_stat_start (EV_P_ ev_stat *w)
  2708. {
  2709. if (expect_false (ev_is_active (w)))
  2710. return;
  2711. ev_stat_stat (EV_A_ w);
  2712. if (w->interval < MIN_STAT_INTERVAL && w->interval)
  2713. w->interval = MIN_STAT_INTERVAL;
  2714. ev_timer_init (&w->timer, stat_timer_cb, 0., w->interval ? w->interval : DEF_STAT_INTERVAL);
  2715. ev_set_priority (&w->timer, ev_priority (w));
  2716. #if EV_USE_INOTIFY
  2717. infy_init (EV_A);
  2718. if (fs_fd >= 0)
  2719. infy_add (EV_A_ w);
  2720. else
  2721. #endif
  2722. {
  2723. ev_timer_again (EV_A_ &w->timer);
  2724. ev_unref (EV_A);
  2725. }
  2726. ev_start (EV_A_ (W)w, 1);
  2727. EV_FREQUENT_CHECK;
  2728. }
  2729. void
  2730. ev_stat_stop (EV_P_ ev_stat *w)
  2731. {
  2732. clear_pending (EV_A_ (W)w);
  2733. if (expect_false (!ev_is_active (w)))
  2734. return;
  2735. EV_FREQUENT_CHECK;
  2736. #if EV_USE_INOTIFY
  2737. infy_del (EV_A_ w);
  2738. #endif
  2739. if (ev_is_active (&w->timer))
  2740. {
  2741. ev_ref (EV_A);
  2742. ev_timer_stop (EV_A_ &w->timer);
  2743. }
  2744. ev_stop (EV_A_ (W)w);
  2745. EV_FREQUENT_CHECK;
  2746. }
  2747. #endif
  2748. #if EV_IDLE_ENABLE
  2749. void
  2750. ev_idle_start (EV_P_ ev_idle *w)
  2751. {
  2752. if (expect_false (ev_is_active (w)))
  2753. return;
  2754. pri_adjust (EV_A_ (W)w);
  2755. EV_FREQUENT_CHECK;
  2756. {
  2757. int active = ++idlecnt [ABSPRI (w)];
  2758. ++idleall;
  2759. ev_start (EV_A_ (W)w, active);
  2760. array_needsize (ev_idle *, idles [ABSPRI (w)], idlemax [ABSPRI (w)], active, EMPTY2);
  2761. idles [ABSPRI (w)][active - 1] = w;
  2762. }
  2763. EV_FREQUENT_CHECK;
  2764. }
  2765. void
  2766. ev_idle_stop (EV_P_ ev_idle *w)
  2767. {
  2768. clear_pending (EV_A_ (W)w);
  2769. if (expect_false (!ev_is_active (w)))
  2770. return;
  2771. EV_FREQUENT_CHECK;
  2772. {
  2773. int active = ev_active (w);
  2774. idles [ABSPRI (w)][active - 1] = idles [ABSPRI (w)][--idlecnt [ABSPRI (w)]];
  2775. ev_active (idles [ABSPRI (w)][active - 1]) = active;
  2776. ev_stop (EV_A_ (W)w);
  2777. --idleall;
  2778. }
  2779. EV_FREQUENT_CHECK;
  2780. }
  2781. #endif
  2782. #if EV_PREPARE_ENABLE
  2783. void
  2784. ev_prepare_start (EV_P_ ev_prepare *w)
  2785. {
  2786. if (expect_false (ev_is_active (w)))
  2787. return;
  2788. EV_FREQUENT_CHECK;
  2789. ev_start (EV_A_ (W)w, ++preparecnt);
  2790. array_needsize (ev_prepare *, prepares, preparemax, preparecnt, EMPTY2);
  2791. prepares [preparecnt - 1] = w;
  2792. EV_FREQUENT_CHECK;
  2793. }
  2794. void
  2795. ev_prepare_stop (EV_P_ ev_prepare *w)
  2796. {
  2797. clear_pending (EV_A_ (W)w);
  2798. if (expect_false (!ev_is_active (w)))
  2799. return;
  2800. EV_FREQUENT_CHECK;
  2801. {
  2802. int active = ev_active (w);
  2803. prepares [active - 1] = prepares [--preparecnt];
  2804. ev_active (prepares [active - 1]) = active;
  2805. }
  2806. ev_stop (EV_A_ (W)w);
  2807. EV_FREQUENT_CHECK;
  2808. }
  2809. #endif
  2810. #if EV_CHECK_ENABLE
  2811. void
  2812. ev_check_start (EV_P_ ev_check *w)
  2813. {
  2814. if (expect_false (ev_is_active (w)))
  2815. return;
  2816. EV_FREQUENT_CHECK;
  2817. ev_start (EV_A_ (W)w, ++checkcnt);
  2818. array_needsize (ev_check *, checks, checkmax, checkcnt, EMPTY2);
  2819. checks [checkcnt - 1] = w;
  2820. EV_FREQUENT_CHECK;
  2821. }
  2822. void
  2823. ev_check_stop (EV_P_ ev_check *w)
  2824. {
  2825. clear_pending (EV_A_ (W)w);
  2826. if (expect_false (!ev_is_active (w)))
  2827. return;
  2828. EV_FREQUENT_CHECK;
  2829. {
  2830. int active = ev_active (w);
  2831. checks [active - 1] = checks [--checkcnt];
  2832. ev_active (checks [active - 1]) = active;
  2833. }
  2834. ev_stop (EV_A_ (W)w);
  2835. EV_FREQUENT_CHECK;
  2836. }
  2837. #endif
  2838. #if EV_EMBED_ENABLE
  2839. void noinline
  2840. ev_embed_sweep (EV_P_ ev_embed *w)
  2841. {
  2842. ev_run (w->other, EVRUN_NOWAIT);
  2843. }
  2844. static void
  2845. embed_io_cb (EV_P_ ev_io *io, int revents)
  2846. {
  2847. ev_embed *w = (ev_embed *)(((char *)io) - offsetof (ev_embed, io));
  2848. if (ev_cb (w))
  2849. ev_feed_event (EV_A_ (W)w, EV_EMBED);
  2850. else
  2851. ev_run (w->other, EVRUN_NOWAIT);
  2852. }
  2853. static void
  2854. embed_prepare_cb (EV_P_ ev_prepare *prepare, int revents)
  2855. {
  2856. ev_embed *w = (ev_embed *)(((char *)prepare) - offsetof (ev_embed, prepare));
  2857. {
  2858. EV_P = w->other;
  2859. while (fdchangecnt)
  2860. {
  2861. fd_reify (EV_A);
  2862. ev_run (EV_A_ EVRUN_NOWAIT);
  2863. }
  2864. }
  2865. }
  2866. static void
  2867. embed_fork_cb (EV_P_ ev_fork *fork_w, int revents)
  2868. {
  2869. ev_embed *w = (ev_embed *)(((char *)fork_w) - offsetof (ev_embed, fork));
  2870. ev_embed_stop (EV_A_ w);
  2871. {
  2872. EV_P = w->other;
  2873. ev_loop_fork (EV_A);
  2874. ev_run (EV_A_ EVRUN_NOWAIT);
  2875. }
  2876. ev_embed_start (EV_A_ w);
  2877. }
  2878. #if 0
  2879. static void
  2880. embed_idle_cb (EV_P_ ev_idle *idle, int revents)
  2881. {
  2882. ev_idle_stop (EV_A_ idle);
  2883. }
  2884. #endif
  2885. void
  2886. ev_embed_start (EV_P_ ev_embed *w)
  2887. {
  2888. if (expect_false (ev_is_active (w)))
  2889. return;
  2890. {
  2891. EV_P = w->other;
  2892. assert (("libev: loop to be embedded is not embeddable", backend & ev_embeddable_backends ()));
  2893. ev_io_init (&w->io, embed_io_cb, backend_fd, EV_READ);
  2894. }
  2895. EV_FREQUENT_CHECK;
  2896. ev_set_priority (&w->io, ev_priority (w));
  2897. ev_io_start (EV_A_ &w->io);
  2898. ev_prepare_init (&w->prepare, embed_prepare_cb);
  2899. ev_set_priority (&w->prepare, EV_MINPRI);
  2900. ev_prepare_start (EV_A_ &w->prepare);
  2901. ev_fork_init (&w->fork, embed_fork_cb);
  2902. ev_fork_start (EV_A_ &w->fork);
  2903. /*ev_idle_init (&w->idle, e,bed_idle_cb);*/
  2904. ev_start (EV_A_ (W)w, 1);
  2905. EV_FREQUENT_CHECK;
  2906. }
  2907. void
  2908. ev_embed_stop (EV_P_ ev_embed *w)
  2909. {
  2910. clear_pending (EV_A_ (W)w);
  2911. if (expect_false (!ev_is_active (w)))
  2912. return;
  2913. EV_FREQUENT_CHECK;
  2914. ev_io_stop (EV_A_ &w->io);
  2915. ev_prepare_stop (EV_A_ &w->prepare);
  2916. ev_fork_stop (EV_A_ &w->fork);
  2917. ev_stop (EV_A_ (W)w);
  2918. EV_FREQUENT_CHECK;
  2919. }
  2920. #endif
  2921. #if EV_FORK_ENABLE
  2922. void
  2923. ev_fork_start (EV_P_ ev_fork *w)
  2924. {
  2925. if (expect_false (ev_is_active (w)))
  2926. return;
  2927. EV_FREQUENT_CHECK;
  2928. ev_start (EV_A_ (W)w, ++forkcnt);
  2929. array_needsize (ev_fork *, forks, forkmax, forkcnt, EMPTY2);
  2930. forks [forkcnt - 1] = w;
  2931. EV_FREQUENT_CHECK;
  2932. }
  2933. void
  2934. ev_fork_stop (EV_P_ ev_fork *w)
  2935. {
  2936. clear_pending (EV_A_ (W)w);
  2937. if (expect_false (!ev_is_active (w)))
  2938. return;
  2939. EV_FREQUENT_CHECK;
  2940. {
  2941. int active = ev_active (w);
  2942. forks [active - 1] = forks [--forkcnt];
  2943. ev_active (forks [active - 1]) = active;
  2944. }
  2945. ev_stop (EV_A_ (W)w);
  2946. EV_FREQUENT_CHECK;
  2947. }
  2948. #endif
  2949. #if EV_CLEANUP_ENABLE
  2950. void
  2951. ev_cleanup_start (EV_P_ ev_cleanup *w)
  2952. {
  2953. if (expect_false (ev_is_active (w)))
  2954. return;
  2955. EV_FREQUENT_CHECK;
  2956. ev_start (EV_A_ (W)w, ++cleanupcnt);
  2957. array_needsize (ev_cleanup *, cleanups, cleanupmax, cleanupcnt, EMPTY2);
  2958. cleanups [cleanupcnt - 1] = w;
  2959. /* cleanup watchers should never keep a refcount on the loop */
  2960. ev_unref (EV_A);
  2961. EV_FREQUENT_CHECK;
  2962. }
  2963. void
  2964. ev_cleanup_stop (EV_P_ ev_cleanup *w)
  2965. {
  2966. clear_pending (EV_A_ (W)w);
  2967. if (expect_false (!ev_is_active (w)))
  2968. return;
  2969. EV_FREQUENT_CHECK;
  2970. ev_ref (EV_A);
  2971. {
  2972. int active = ev_active (w);
  2973. cleanups [active - 1] = cleanups [--cleanupcnt];
  2974. ev_active (cleanups [active - 1]) = active;
  2975. }
  2976. ev_stop (EV_A_ (W)w);
  2977. EV_FREQUENT_CHECK;
  2978. }
  2979. #endif
  2980. #if EV_ASYNC_ENABLE
  2981. void
  2982. ev_async_start (EV_P_ ev_async *w)
  2983. {
  2984. if (expect_false (ev_is_active (w)))
  2985. return;
  2986. w->sent = 0;
  2987. evpipe_init (EV_A);
  2988. EV_FREQUENT_CHECK;
  2989. ev_start (EV_A_ (W)w, ++asynccnt);
  2990. array_needsize (ev_async *, asyncs, asyncmax, asynccnt, EMPTY2);
  2991. asyncs [asynccnt - 1] = w;
  2992. EV_FREQUENT_CHECK;
  2993. }
  2994. void
  2995. ev_async_stop (EV_P_ ev_async *w)
  2996. {
  2997. clear_pending (EV_A_ (W)w);
  2998. if (expect_false (!ev_is_active (w)))
  2999. return;
  3000. EV_FREQUENT_CHECK;
  3001. {
  3002. int active = ev_active (w);
  3003. asyncs [active - 1] = asyncs [--asynccnt];
  3004. ev_active (asyncs [active - 1]) = active;
  3005. }
  3006. ev_stop (EV_A_ (W)w);
  3007. EV_FREQUENT_CHECK;
  3008. }
  3009. void
  3010. ev_async_send (EV_P_ ev_async *w)
  3011. {
  3012. w->sent = 1;
  3013. evpipe_write (EV_A_ &async_pending);
  3014. }
  3015. #endif
  3016. /*****************************************************************************/
  3017. struct ev_once
  3018. {
  3019. ev_io io;
  3020. ev_timer to;
  3021. void (*cb)(int revents, void *arg);
  3022. void *arg;
  3023. };
  3024. static void
  3025. once_cb (EV_P_ struct ev_once *once, int revents)
  3026. {
  3027. void (*cb)(int revents, void *arg) = once->cb;
  3028. void *arg = once->arg;
  3029. ev_io_stop (EV_A_ &once->io);
  3030. ev_timer_stop (EV_A_ &once->to);
  3031. ev_free (once);
  3032. cb (revents, arg);
  3033. }
  3034. static void
  3035. once_cb_io (EV_P_ ev_io *w, int revents)
  3036. {
  3037. struct ev_once *once = (struct ev_once *)(((char *)w) - offsetof (struct ev_once, io));
  3038. once_cb (EV_A_ once, revents | ev_clear_pending (EV_A_ &once->to));
  3039. }
  3040. static void
  3041. once_cb_to (EV_P_ ev_timer *w, int revents)
  3042. {
  3043. struct ev_once *once = (struct ev_once *)(((char *)w) - offsetof (struct ev_once, to));
  3044. once_cb (EV_A_ once, revents | ev_clear_pending (EV_A_ &once->io));
  3045. }
  3046. void
  3047. ev_once (EV_P_ int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
  3048. {
  3049. struct ev_once *once = (struct ev_once *)ev_malloc (sizeof (struct ev_once));
  3050. if (expect_false (!once))
  3051. {
  3052. cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMER, arg);
  3053. return;
  3054. }
  3055. once->cb = cb;
  3056. once->arg = arg;
  3057. ev_init (&once->io, once_cb_io);
  3058. if (fd >= 0)
  3059. {
  3060. ev_io_set (&once->io, fd, events);
  3061. ev_io_start (EV_A_ &once->io);
  3062. }
  3063. ev_init (&once->to, once_cb_to);
  3064. if (timeout >= 0.)
  3065. {
  3066. ev_timer_set (&once->to, timeout, 0.);
  3067. ev_timer_start (EV_A_ &once->to);
  3068. }
  3069. }
  3070. /*****************************************************************************/
  3071. #if EV_WALK_ENABLE
  3072. void
  3073. ev_walk (EV_P_ int types, void (*cb)(EV_P_ int type, void *w))
  3074. {
  3075. int i, j;
  3076. ev_watcher_list *wl, *wn;
  3077. if (types & (EV_IO | EV_EMBED))
  3078. for (i = 0; i < anfdmax; ++i)
  3079. for (wl = anfds [i].head; wl; )
  3080. {
  3081. wn = wl->next;
  3082. #if EV_EMBED_ENABLE
  3083. if (ev_cb ((ev_io *)wl) == embed_io_cb)
  3084. {
  3085. if (types & EV_EMBED)
  3086. cb (EV_A_ EV_EMBED, ((char *)wl) - offsetof (struct ev_embed, io));
  3087. }
  3088. else
  3089. #endif
  3090. #if EV_USE_INOTIFY
  3091. if (ev_cb ((ev_io *)wl) == infy_cb)
  3092. ;
  3093. else
  3094. #endif
  3095. if ((ev_io *)wl != &pipe_w)
  3096. if (types & EV_IO)
  3097. cb (EV_A_ EV_IO, wl);
  3098. wl = wn;
  3099. }
  3100. if (types & (EV_TIMER | EV_STAT))
  3101. for (i = timercnt + HEAP0; i-- > HEAP0; )
  3102. #if EV_STAT_ENABLE
  3103. /*TODO: timer is not always active*/
  3104. if (ev_cb ((ev_timer *)ANHE_w (timers [i])) == stat_timer_cb)
  3105. {
  3106. if (types & EV_STAT)
  3107. cb (EV_A_ EV_STAT, ((char *)ANHE_w (timers [i])) - offsetof (struct ev_stat, timer));
  3108. }
  3109. else
  3110. #endif
  3111. if (types & EV_TIMER)
  3112. cb (EV_A_ EV_TIMER, ANHE_w (timers [i]));
  3113. #if EV_PERIODIC_ENABLE
  3114. if (types & EV_PERIODIC)
  3115. for (i = periodiccnt + HEAP0; i-- > HEAP0; )
  3116. cb (EV_A_ EV_PERIODIC, ANHE_w (periodics [i]));
  3117. #endif
  3118. #if EV_IDLE_ENABLE
  3119. if (types & EV_IDLE)
  3120. for (j = NUMPRI; i--; )
  3121. for (i = idlecnt [j]; i--; )
  3122. cb (EV_A_ EV_IDLE, idles [j][i]);
  3123. #endif
  3124. #if EV_FORK_ENABLE
  3125. if (types & EV_FORK)
  3126. for (i = forkcnt; i--; )
  3127. if (ev_cb (forks [i]) != embed_fork_cb)
  3128. cb (EV_A_ EV_FORK, forks [i]);
  3129. #endif
  3130. #if EV_ASYNC_ENABLE
  3131. if (types & EV_ASYNC)
  3132. for (i = asynccnt; i--; )
  3133. cb (EV_A_ EV_ASYNC, asyncs [i]);
  3134. #endif
  3135. #if EV_PREPARE_ENABLE
  3136. if (types & EV_PREPARE)
  3137. for (i = preparecnt; i--; )
  3138. # if EV_EMBED_ENABLE
  3139. if (ev_cb (prepares [i]) != embed_prepare_cb)
  3140. # endif
  3141. cb (EV_A_ EV_PREPARE, prepares [i]);
  3142. #endif
  3143. #if EV_CHECK_ENABLE
  3144. if (types & EV_CHECK)
  3145. for (i = checkcnt; i--; )
  3146. cb (EV_A_ EV_CHECK, checks [i]);
  3147. #endif
  3148. #if EV_SIGNAL_ENABLE
  3149. if (types & EV_SIGNAL)
  3150. for (i = 0; i < EV_NSIG - 1; ++i)
  3151. for (wl = signals [i].head; wl; )
  3152. {
  3153. wn = wl->next;
  3154. cb (EV_A_ EV_SIGNAL, wl);
  3155. wl = wn;
  3156. }
  3157. #endif
  3158. #if EV_CHILD_ENABLE
  3159. if (types & EV_CHILD)
  3160. for (i = (EV_PID_HASHSIZE); i--; )
  3161. for (wl = childs [i]; wl; )
  3162. {
  3163. wn = wl->next;
  3164. cb (EV_A_ EV_CHILD, wl);
  3165. wl = wn;
  3166. }
  3167. #endif
  3168. /* EV_STAT 0x00001000 /* stat data changed */
  3169. /* EV_EMBED 0x00010000 /* embedded event loop needs sweep */
  3170. }
  3171. #endif
  3172. #if EV_MULTIPLICITY
  3173. #include "ev_wrap.h"
  3174. #endif
  3175. EV_CPP(})