You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
libev/ev.c

3025 lines
64 KiB
C

16 years ago
/*
* libev event processing core, watcher management
*
* Copyright (c) 2007,2008 Marc Alexander Lehmann <libev@schmorp.de>
16 years ago
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modifica-
* tion, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
* CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
* CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
* ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
16 years ago
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License ("GPL") version 2 or any later version,
* in which case the provisions of the GPL are applicable instead of
* the above. If you wish to allow the use of your version of this file
* only under the terms of the GPL and not to allow others to use your
* version of this file under the BSD license, indicate your decision
* by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete the
* provisions above, a recipient may use your version of this file under
* either the BSD or the GPL.
16 years ago
*/
#ifdef __cplusplus
extern "C" {
#endif
/* this big block deduces configuration from config.h */
#ifndef EV_STANDALONE
# ifdef EV_CONFIG_H
# include EV_CONFIG_H
# else
# include "config.h"
# endif
# if HAVE_CLOCK_GETTIME
# ifndef EV_USE_MONOTONIC
# define EV_USE_MONOTONIC 1
# endif
# ifndef EV_USE_REALTIME
# define EV_USE_REALTIME 1
# endif
# else
# ifndef EV_USE_MONOTONIC
# define EV_USE_MONOTONIC 0
# endif
# ifndef EV_USE_REALTIME
# define EV_USE_REALTIME 0
# endif
# endif
# ifndef EV_USE_NANOSLEEP
# if HAVE_NANOSLEEP
# define EV_USE_NANOSLEEP 1
# else
# define EV_USE_NANOSLEEP 0
# endif
# endif
# ifndef EV_USE_SELECT
# if HAVE_SELECT && HAVE_SYS_SELECT_H
# define EV_USE_SELECT 1
# else
# define EV_USE_SELECT 0
# endif
# endif
# ifndef EV_USE_POLL
# if HAVE_POLL && HAVE_POLL_H
# define EV_USE_POLL 1
# else
# define EV_USE_POLL 0
# endif
# endif
# ifndef EV_USE_EPOLL
# if HAVE_EPOLL_CTL && HAVE_SYS_EPOLL_H
# define EV_USE_EPOLL 1
# else
# define EV_USE_EPOLL 0
# endif
# endif
# ifndef EV_USE_KQUEUE
# if HAVE_KQUEUE && HAVE_SYS_EVENT_H && HAVE_SYS_QUEUE_H
# define EV_USE_KQUEUE 1
# else
# define EV_USE_KQUEUE 0
# endif
# endif
# ifndef EV_USE_PORT
# if HAVE_PORT_H && HAVE_PORT_CREATE
# define EV_USE_PORT 1
# else
# define EV_USE_PORT 0
# endif
# endif
# ifndef EV_USE_INOTIFY
# if HAVE_INOTIFY_INIT && HAVE_SYS_INOTIFY_H
# define EV_USE_INOTIFY 1
# else
# define EV_USE_INOTIFY 0
# endif
# endif
# ifndef EV_USE_EVENTFD
# if HAVE_EVENTFD
# define EV_USE_EVENTFD 1
# else
# define EV_USE_EVENTFD 0
# endif
# endif
#endif
16 years ago
#include <math.h>
#include <stdlib.h>
16 years ago
#include <fcntl.h>
#include <stddef.h>
#include <stdio.h>
16 years ago
#include <assert.h>
#include <errno.h>
#include <sys/types.h>
#include <time.h>
#include <signal.h>
#ifdef EV_H
# include EV_H
#else
# include "ev.h"
#endif
#ifndef _WIN32
# include <sys/time.h>
16 years ago
# include <sys/wait.h>
# include <unistd.h>
#else
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
# ifndef EV_SELECT_IS_WINSOCKET
# define EV_SELECT_IS_WINSOCKET 1
# endif
16 years ago
#endif
/* this block tries to deduce configuration from header-defined symbols and defaults */
#ifndef EV_USE_MONOTONIC
# define EV_USE_MONOTONIC 0
#endif
#ifndef EV_USE_REALTIME
# define EV_USE_REALTIME 0
#endif
#ifndef EV_USE_NANOSLEEP
# define EV_USE_NANOSLEEP 0
#endif
#ifndef EV_USE_SELECT
# define EV_USE_SELECT 1
#endif
#ifndef EV_USE_POLL
# ifdef _WIN32
# define EV_USE_POLL 0
# else
# define EV_USE_POLL 1
# endif
#endif
#ifndef EV_USE_EPOLL
# if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 4))
# define EV_USE_EPOLL 1
# else
# define EV_USE_EPOLL 0
# endif
#endif
#ifndef EV_USE_KQUEUE
# define EV_USE_KQUEUE 0
#endif
#ifndef EV_USE_PORT
# define EV_USE_PORT 0
#endif
#ifndef EV_USE_INOTIFY
# if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 4))
# define EV_USE_INOTIFY 1
# else
# define EV_USE_INOTIFY 0
# endif
#endif
#ifndef EV_PID_HASHSIZE
# if EV_MINIMAL
# define EV_PID_HASHSIZE 1
# else
# define EV_PID_HASHSIZE 16
# endif
#endif
#ifndef EV_INOTIFY_HASHSIZE
# if EV_MINIMAL
# define EV_INOTIFY_HASHSIZE 1
# else
# define EV_INOTIFY_HASHSIZE 16
# endif
#endif
#ifndef EV_USE_EVENTFD
# if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7))
# define EV_USE_EVENTFD 1
# else
# define EV_USE_EVENTFD 0
# endif
#endif
#if 0 /* debugging */
# define EV_VERIFY 3
# define EV_USE_4HEAP 1
# define EV_HEAP_CACHE_AT 1
#endif
#ifndef EV_VERIFY
# define EV_VERIFY !EV_MINIMAL
#endif
#ifndef EV_USE_4HEAP
# define EV_USE_4HEAP !EV_MINIMAL
#endif
#ifndef EV_HEAP_CACHE_AT
# define EV_HEAP_CACHE_AT !EV_MINIMAL
#endif
/* this block fixes any misconfiguration where we know we run into trouble otherwise */
#ifndef CLOCK_MONOTONIC
# undef EV_USE_MONOTONIC
# define EV_USE_MONOTONIC 0
#endif
#ifndef CLOCK_REALTIME
# undef EV_USE_REALTIME
# define EV_USE_REALTIME 0
#endif
#if !EV_STAT_ENABLE
16 years ago
# undef EV_USE_INOTIFY
# define EV_USE_INOTIFY 0
#endif
#if !EV_USE_NANOSLEEP
# ifndef _WIN32
# include <sys/select.h>
# endif
#endif
#if EV_USE_INOTIFY
# include <sys/inotify.h>
#endif
16 years ago
#if EV_SELECT_IS_WINSOCKET
# include <winsock.h>
#endif
#if EV_USE_EVENTFD
/* our minimum requirement is glibc 2.7 which has the stub, but not the header */
# include <stdint.h>
# ifdef __cplusplus
extern "C" {
# endif
int eventfd (unsigned int initval, int flags);
# ifdef __cplusplus
}
# endif
#endif
/**/
#if EV_VERIFY >= 3
# define EV_FREQUENT_CHECK ev_loop_verify (EV_A)
#else
# define EV_FREQUENT_CHECK do { } while (0)
#endif
/*
* This is used to avoid floating point rounding problems.
* It is added to ev_rt_now when scheduling periodics
* to ensure progress, time-wise, even when rounding
* errors are against us.
* This value is good at least till the year 4000.
* Better solutions welcome.
*/
#define TIME_EPSILON 0.0001220703125 /* 1/8192 */
16 years ago
#define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
#define MAX_BLOCKTIME 59.743 /* never wait longer than this time (to detect time jumps) */
/*#define CLEANUP_INTERVAL (MAX_BLOCKTIME * 5.) /* how often to try to free memory and re-check fds, TODO */
16 years ago
#if __GNUC__ >= 4
# define expect(expr,value) __builtin_expect ((expr),(value))
16 years ago
# define noinline __attribute__ ((noinline))
#else
# define expect(expr,value) (expr)
# define noinline
# if __STDC_VERSION__ < 199901L && __GNUC__ < 2
16 years ago
# define inline
# endif
#endif
#define expect_false(expr) expect ((expr) != 0, 0)
#define expect_true(expr) expect ((expr) != 0, 1)
16 years ago
#define inline_size static inline
#if EV_MINIMAL
# define inline_speed static noinline
#else
# define inline_speed static inline
#endif
#define NUMPRI (EV_MAXPRI - EV_MINPRI + 1)
#define ABSPRI(w) (((W)w)->priority - EV_MINPRI)
#define EMPTY /* required for microsofts broken pseudo-c compiler */
#define EMPTY2(a,b) /* used to suppress some warnings */
typedef ev_watcher *W;
typedef ev_watcher_list *WL;
typedef ev_watcher_time *WT;
#define ev_active(w) ((W)(w))->active
#define ev_at(w) ((WT)(w))->at
#if EV_USE_MONOTONIC
/* sig_atomic_t is used to avoid per-thread variables or locking but still */
/* giving it a reasonably high chance of working on typical architetcures */
static EV_ATOMIC_T have_monotonic; /* did clock_gettime (CLOCK_MONOTONIC) work? */
#endif
#ifdef _WIN32
# include "ev_win32.c"
#endif
/*****************************************************************************/
16 years ago
static void (*syserr_cb)(const char *msg);
16 years ago
void
ev_set_syserr_cb (void (*cb)(const char *msg))
{
syserr_cb = cb;
}
16 years ago
static void noinline
16 years ago
syserr (const char *msg)
{
16 years ago
if (!msg)
msg = "(libev) system error";
if (syserr_cb)
16 years ago
syserr_cb (msg);
else
{
16 years ago
perror (msg);
abort ();
}
}
static void *
ev_realloc_emul (void *ptr, long size)
{
/* some systems, notably openbsd and darwin, fail to properly
* implement realloc (x, 0) (as required by both ansi c-98 and
* the single unix specification, so work around them here.
*/
if (size)
return realloc (ptr, size);
free (ptr);
return 0;
}
static void *(*alloc)(void *ptr, long size) = ev_realloc_emul;
16 years ago
void
ev_set_allocator (void *(*cb)(void *ptr, long size))
{
alloc = cb;
}
16 years ago
inline_speed void *
ev_realloc (void *ptr, long size)
{
ptr = alloc (ptr, size);
if (!ptr && size)
{
fprintf (stderr, "libev: cannot allocate %ld bytes, aborting.", size);
abort ();
}
return ptr;
}
#define ev_malloc(size) ev_realloc (0, (size))
#define ev_free(ptr) ev_realloc ((ptr), 0)
/*****************************************************************************/
typedef struct
{
WL head;
unsigned char events;
unsigned char reify;
#if EV_SELECT_IS_WINSOCKET
SOCKET handle;
#endif
} ANFD;
typedef struct
{
W w;
int events;
} ANPENDING;
#if EV_USE_INOTIFY
/* hash table entry per inotify-id */
typedef struct
{
WL head;
} ANFS;
#endif
/* Heap Entry */
#if EV_HEAP_CACHE_AT
typedef struct {
ev_tstamp at;
WT w;
} ANHE;
#define ANHE_w(he) (he).w /* access watcher, read-write */
#define ANHE_at(he) (he).at /* access cached at, read-only */
#define ANHE_at_cache(he) (he).at = (he).w->at /* update at from watcher */
#else
typedef WT ANHE;
#define ANHE_w(he) (he)
#define ANHE_at(he) (he)->at
#define ANHE_at_cache(he)
#endif
#if EV_MULTIPLICITY
struct ev_loop
{
ev_tstamp ev_rt_now;
#define ev_rt_now ((loop)->ev_rt_now)
#define VAR(name,decl) decl;
#include "ev_vars.h"
#undef VAR
};
#include "ev_wrap.h"
static struct ev_loop default_loop_struct;
struct ev_loop *ev_default_loop_ptr;
#else
ev_tstamp ev_rt_now;
#define VAR(name,decl) static decl;
#include "ev_vars.h"
#undef VAR
static int ev_default_loop_ptr;
#endif
/*****************************************************************************/
16 years ago
ev_tstamp
ev_time (void)
{
#if EV_USE_REALTIME
struct timespec ts;
clock_gettime (CLOCK_REALTIME, &ts);
return ts.tv_sec + ts.tv_nsec * 1e-9;
#else
struct timeval tv;
gettimeofday (&tv, 0);
return tv.tv_sec + tv.tv_usec * 1e-6;
#endif
}
ev_tstamp inline_size
get_clock (void)
{
#if EV_USE_MONOTONIC
if (expect_true (have_monotonic))
{
struct timespec ts;
clock_gettime (CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec * 1e-9;
}
#endif
return ev_time ();
}
#if EV_MULTIPLICITY
ev_tstamp
ev_now (EV_P)
{
return ev_rt_now;
}
#endif
void
ev_sleep (ev_tstamp delay)
{
if (delay > 0.)
{
#if EV_USE_NANOSLEEP
struct timespec ts;
ts.tv_sec = (time_t)delay;
ts.tv_nsec = (long)((delay - (ev_tstamp)(ts.tv_sec)) * 1e9);
nanosleep (&ts, 0);
#elif defined(_WIN32)
Sleep ((unsigned long)(delay * 1e3));
#else
struct timeval tv;
tv.tv_sec = (time_t)delay;
tv.tv_usec = (long)((delay - (ev_tstamp)(tv.tv_sec)) * 1e6);
select (0, 0, 0, 0, &tv);
#endif
}
}
/*****************************************************************************/
#define MALLOC_ROUND 4096 /* prefer to allocate in chunks of this size, must be 2**n and >> 4 longs */
int inline_size
array_nextsize (int elem, int cur, int cnt)
{
int ncur = cur + 1;
do
ncur <<= 1;
while (cnt > ncur);
/* if size is large, round to MALLOC_ROUND - 4 * longs to accomodate malloc overhead */
if (elem * ncur > MALLOC_ROUND - sizeof (void *) * 4)
{
ncur *= elem;
ncur = (ncur + elem + (MALLOC_ROUND - 1) + sizeof (void *) * 4) & ~(MALLOC_ROUND - 1);
ncur = ncur - sizeof (void *) * 4;
ncur /= elem;
}
return ncur;
}
16 years ago
static noinline void *
array_realloc (int elem, void *base, int *cur, int cnt)
{
*cur = array_nextsize (elem, *cur, cnt);
return ev_realloc (base, elem * *cur);
}
#define array_needsize(type,base,cur,cnt,init) \
if (expect_false ((cnt) > (cur))) \
{ \
int ocur_ = (cur); \
(base) = (type *)array_realloc \
(sizeof (type), (base), &(cur), (cnt)); \
init ((base) + (ocur_), (cur) - ocur_); \
}
#if 0
#define array_slim(type,stem) \
if (stem ## max < array_roundsize (stem ## cnt >> 2)) \
{ \
stem ## max = array_roundsize (stem ## cnt >> 1); \
base = (type *)ev_realloc (base, sizeof (type) * (stem ## max));\
fprintf (stderr, "slimmed down " # stem " to %d\n", stem ## max);/*D*/\
}
#endif
#define array_free(stem, idx) \
ev_free (stem ## s idx); stem ## cnt idx = stem ## max idx = 0;
/*****************************************************************************/
void noinline
16 years ago
ev_feed_event (EV_P_ void *w, int revents)
{
16 years ago
W w_ = (W)w;
16 years ago
int pri = ABSPRI (w_);
16 years ago
if (expect_false (w_->pending))
16 years ago
pendings [pri][w_->pending - 1].events |= revents;
else
{
16 years ago
w_->pending = ++pendingcnt [pri];
array_needsize (ANPENDING, pendings [pri], pendingmax [pri], w_->pending, EMPTY2);
pendings [pri][w_->pending - 1].w = w_;
pendings [pri][w_->pending - 1].events = revents;
}
}
void inline_speed
queue_events (EV_P_ W *events, int eventcnt, int type)
{
int i;
for (i = 0; i < eventcnt; ++i)
16 years ago
ev_feed_event (EV_A_ events [i], type);
}
16 years ago
/*****************************************************************************/
void inline_size
anfds_init (ANFD *base, int count)
{
while (count--)
{
base->head = 0;
base->events = EV_NONE;
base->reify = 0;
++base;
}
}
void inline_speed
fd_event (EV_P_ int fd, int revents)
{
ANFD *anfd = anfds + fd;
ev_io *w;
for (w = (ev_io *)anfd->head; w; w = (ev_io *)((WL)w)->next)
{
int ev = w->events & revents;
if (ev)
16 years ago
ev_feed_event (EV_A_ (W)w, ev);
}
}
void
ev_feed_fd_event (EV_P_ int fd, int revents)
{
if (fd >= 0 && fd < anfdmax)
fd_event (EV_A_ fd, revents);
}
void inline_size
fd_reify (EV_P)
{
int i;
for (i = 0; i < fdchangecnt; ++i)
{
int fd = fdchanges [i];
ANFD *anfd = anfds + fd;
ev_io *w;
unsigned char events = 0;
for (w = (ev_io *)anfd->head; w; w = (ev_io *)((WL)w)->next)
events |= (unsigned char)w->events;
#if EV_SELECT_IS_WINSOCKET
if (events)
{
unsigned long argp;
#ifdef EV_FD_TO_WIN32_HANDLE
anfd->handle = EV_FD_TO_WIN32_HANDLE (fd);
#else
anfd->handle = _get_osfhandle (fd);
#endif
assert (("libev only supports socket fds in this configuration", ioctlsocket (anfd->handle, FIONREAD, &argp) == 0));
}
#endif
{
unsigned char o_events = anfd->events;
unsigned char o_reify = anfd->reify;
anfd->reify = 0;
anfd->events = events;
if (o_events != events || o_reify & EV_IOFDSET)
backend_modify (EV_A_ fd, o_events, events);
}
}
fdchangecnt = 0;
}
void inline_size
fd_change (EV_P_ int fd, int flags)
{
unsigned char reify = anfds [fd].reify;
anfds [fd].reify |= flags;
if (expect_true (!reify))
{
++fdchangecnt;
array_needsize (int, fdchanges, fdchangemax, fdchangecnt, EMPTY2);
fdchanges [fdchangecnt - 1] = fd;
}
}
void inline_speed
fd_kill (EV_P_ int fd)
{
ev_io *w;
while ((w = (ev_io *)anfds [fd].head))
{
ev_io_stop (EV_A_ w);
16 years ago
ev_feed_event (EV_A_ (W)w, EV_ERROR | EV_READ | EV_WRITE);