--- libeio/eio.c 2009/06/06 18:06:55 1.32 +++ libeio/eio.c 2011/06/10 12:45:20 1.72 @@ -1,7 +1,7 @@ /* * libeio implementation * - * Copyright (c) 2007,2008,2009 Marc Alexander Lehmann + * Copyright (c) 2007,2008,2009,2010,2011 Marc Alexander Lehmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without modifica- @@ -37,7 +37,12 @@ * either the BSD or the GPL. */ +#ifndef _WIN32 +# include "config.h" +#endif + #include "eio.h" +#include "ecb.h" #ifdef EIO_STACKSIZE # define XTHREAD_STACKSIZE EIO_STACKSIZE @@ -51,10 +56,17 @@ #include #include #include +#include #include #include #include +/* intptr_t comes from unistd.h, says POSIX/UNIX/tradition */ +/* intptr_t only comes form stdint.h, says idiot openbsd coder */ +#if HAVE_STDINT_H +# include +#endif + #ifndef EIO_FINISH # define EIO_FINISH(req) ((req)->finish) && !EIO_CANCELLED (req) ? (req)->finish (req) : 0 #endif @@ -72,7 +84,6 @@ /*doh*/ #else -# include "config.h" # include # include # include @@ -80,14 +91,24 @@ # include # include +#if _POSIX_MEMLOCK || _POSIX_MEMLOCK_RANGE || _POSIX_MAPPED_FILES +# include +#endif + /* POSIX_SOURCE is useless on bsd's, and XOPEN_SOURCE is unreliable there, too */ -# if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) -# define D_INO(de) (de)->d_fileno +# if __FreeBSD__ || defined __NetBSD__ || defined __OpenBSD__ # define _DIRENT_HAVE_D_TYPE /* sigh */ -# elif defined(__linux) || defined(d_ino) || _XOPEN_SOURCE >= 600 +# define D_INO(de) (de)->d_fileno +# define D_NAMLEN(de) (de)->d_namlen +# elif __linux || defined d_ino || _XOPEN_SOURCE >= 600 # define D_INO(de) (de)->d_ino # endif +#ifdef _D_EXACT_NAMLEN +# undef D_NAMLEN +# define D_NAMLEN(de) _D_EXACT_NAMLEN (de) +#endif + # ifdef _DIRENT_HAVE_D_TYPE # define D_TYPE(de) (de)->d_type # endif @@ -101,12 +122,12 @@ #if HAVE_SENDFILE # if __linux # include -# elif __freebsd +# elif __FreeBSD__ || defined __APPLE__ # include # include # elif __hpux # include -# elif __solaris /* not yet */ +# elif __solaris # include # else # error sendfile support requested but not available @@ -116,19 +137,23 @@ #ifndef D_TYPE # define D_TYPE(de) 0 #endif - #ifndef D_INO # define D_INO(de) 0 #endif - -/* number of seconds after which an idle threads exit */ -#define IDLE_TIMEOUT 10 +#ifndef D_NAMLEN +# define D_NAMLEN(de) strlen ((de)->d_name) +#endif /* used for struct dirent, AIX doesn't provide it */ #ifndef NAME_MAX # define NAME_MAX 4096 #endif +/* used for readlink etc. */ +#ifndef PATH_MAX +# define PATH_MAX 4096 +#endif + /* buffer size for various temporary buffers */ #define EIO_BUFSIZE 65536 @@ -143,19 +168,6 @@ #define EIO_TICKS ((1000000 + 1023) >> 10) -/*****************************************************************************/ - -#if __GNUC__ >= 3 -# define expect(expr,value) __builtin_expect ((expr),(value)) -#else -# define expect(expr,value) (expr) -#endif - -#define expect_false(expr) expect ((expr) != 0, 0) -#define expect_true(expr) expect ((expr) != 0, 1) - -/*****************************************************************************/ - #define ETP_PRI_MIN EIO_PRI_MIN #define ETP_PRI_MAX EIO_PRI_MAX @@ -189,8 +201,9 @@ #define ETP_NUM_PRI (ETP_PRI_MAX - ETP_PRI_MIN + 1) -/* calculcate time difference in ~1/EIO_TICKS of a second */ -static int tvdiff (struct timeval *tv1, struct timeval *tv2) +/* calculate time difference in ~1/EIO_TICKS of a second */ +ECB_INLINE int +tvdiff (struct timeval *tv1, struct timeval *tv2) { return (tv2->tv_sec - tv1->tv_sec ) * EIO_TICKS + ((tv2->tv_usec - tv1->tv_usec) >> 10); @@ -207,12 +220,13 @@ static volatile unsigned int nreqs; /* reqlock */ static volatile unsigned int nready; /* reqlock */ static volatile unsigned int npending; /* reqlock */ -static volatile unsigned int max_idle = 4; +static volatile unsigned int max_idle = 4; /* maximum number of threads that can idle indefinitely */ +static volatile unsigned int idle_timeout = 10; /* number of seconds after which an idle threads exit */ -static mutex_t wrklock = X_MUTEX_INIT; -static mutex_t reslock = X_MUTEX_INIT; -static mutex_t reqlock = X_MUTEX_INIT; -static cond_t reqwait = X_COND_INIT; +static xmutex_t wrklock; +static xmutex_t reslock; +static xmutex_t reqlock; +static xcond_t reqwait; #if !HAVE_PREADWRITE /* @@ -220,7 +234,7 @@ * normal read/write by using a mutex. slows down execution a lot, * but that's your problem, not mine. */ -static mutex_t preadwritelock = X_MUTEX_INIT; +static xmutex_t preadwritelock = X_MUTEX_INIT; #endif typedef struct etp_worker @@ -228,7 +242,7 @@ /* locked by wrklock */ struct etp_worker *prev, *next; - thread_t tid; + xthread_t tid; /* locked by reslock, reqlock or wrklock */ ETP_REQ *req; /* currently processed request */ @@ -243,12 +257,14 @@ /* worker threads management */ -static void etp_worker_clear (etp_worker *wrk) +static void ecb_cold +etp_worker_clear (etp_worker *wrk) { ETP_WORKER_CLEAR (wrk); } -static void etp_worker_free (etp_worker *wrk) +static void ecb_cold +etp_worker_free (etp_worker *wrk) { wrk->next->prev = wrk->prev; wrk->prev->next = wrk->next; @@ -256,7 +272,8 @@ free (wrk); } -static unsigned int etp_nreqs (void) +static unsigned int +etp_nreqs (void) { int retval; if (WORDACCESS_UNSAFE) X_LOCK (reqlock); @@ -265,7 +282,8 @@ return retval; } -static unsigned int etp_nready (void) +static unsigned int +etp_nready (void) { unsigned int retval; @@ -276,7 +294,8 @@ return retval; } -static unsigned int etp_npending (void) +static unsigned int +etp_npending (void) { unsigned int retval; @@ -287,7 +306,8 @@ return retval; } -static unsigned int etp_nthreads (void) +static unsigned int +etp_nthreads (void) { unsigned int retval; @@ -311,7 +331,8 @@ static etp_reqq req_queue; static etp_reqq res_queue; -static int reqq_push (etp_reqq *q, ETP_REQ *req) +static int ecb_noinline +reqq_push (etp_reqq *q, ETP_REQ *req) { int pri = req->pri; req->next = 0; @@ -327,7 +348,8 @@ return q->size++; } -static ETP_REQ *reqq_shift (etp_reqq *q) +static ETP_REQ * ecb_noinline +reqq_shift (etp_reqq *q) { int pri; @@ -352,7 +374,17 @@ abort (); } -static void etp_atfork_prepare (void) +static void ecb_cold +etp_thread_init (void) +{ + X_MUTEX_CREATE (wrklock); + X_MUTEX_CREATE (reslock); + X_MUTEX_CREATE (reqlock); + X_COND_CREATE (reqwait); +} + +static void ecb_cold +etp_atfork_prepare (void) { X_LOCK (wrklock); X_LOCK (reqlock); @@ -362,7 +394,8 @@ #endif } -static void etp_atfork_parent (void) +static void ecb_cold +etp_atfork_parent (void) { #if !HAVE_PREADWRITE X_UNLOCK (preadwritelock); @@ -372,7 +405,8 @@ X_UNLOCK (wrklock); } -static void etp_atfork_child (void) +static void ecb_cold +etp_atfork_child (void) { ETP_REQ *prv; @@ -399,16 +433,17 @@ nready = 0; npending = 0; - etp_atfork_parent (); + etp_thread_init (); } -static void +static void ecb_cold etp_once_init (void) -{ +{ + etp_thread_init (); X_THREAD_ATFORK (etp_atfork_prepare, etp_atfork_parent, etp_atfork_child); } -static int +static int ecb_cold etp_init (void (*want_poll)(void), void (*done_poll)(void)) { static pthread_once_t doinit = PTHREAD_ONCE_INIT; @@ -423,7 +458,8 @@ X_THREAD_PROC (etp_proc); -static void etp_start_thread (void) +static void ecb_cold +etp_start_thread (void) { etp_worker *wrk = calloc (1, sizeof (etp_worker)); @@ -446,19 +482,21 @@ X_UNLOCK (wrklock); } -static void etp_maybe_start_thread (void) +static void +etp_maybe_start_thread (void) { - if (expect_true (etp_nthreads () >= wanted)) + if (ecb_expect_true (etp_nthreads () >= wanted)) return; /* todo: maybe use idle here, but might be less exact */ - if (expect_true (0 <= (int)etp_nthreads () + (int)etp_npending () - (int)etp_nreqs ())) + if (ecb_expect_true (0 <= (int)etp_nthreads () + (int)etp_npending () - (int)etp_nreqs ())) return; etp_start_thread (); } -static void etp_end_thread (void) +static void ecb_cold +etp_end_thread (void) { eio_req *req = calloc (1, sizeof (eio_req)); @@ -475,7 +513,8 @@ X_UNLOCK (wrklock); } -static int etp_poll (void) +static int +etp_poll (void) { unsigned int maxreqs; unsigned int maxtime; @@ -515,7 +554,7 @@ --nreqs; X_UNLOCK (reqlock); - if (expect_false (req->type == EIO_GROUP && req->size)) + if (ecb_expect_false (req->type == EIO_GROUP && req->size)) { req->int1 = 1; /* mark request as delayed */ continue; @@ -523,11 +562,11 @@ else { int res = ETP_FINISH (req); - if (expect_false (res)) + if (ecb_expect_false (res)) return res; } - if (expect_false (maxreqs && !--maxreqs)) + if (ecb_expect_false (maxreqs && !--maxreqs)) break; if (maxtime) @@ -543,7 +582,8 @@ return -1; } -static void etp_cancel (ETP_REQ *req) +static void +etp_cancel (ETP_REQ *req) { X_LOCK (wrklock); req->flags |= EIO_FLAG_CANCELLED; @@ -552,14 +592,15 @@ eio_grp_cancel (req); } -static void etp_submit (ETP_REQ *req) +static void +etp_submit (ETP_REQ *req) { req->pri -= ETP_PRI_MIN; - if (expect_false (req->pri < ETP_PRI_MIN - ETP_PRI_MIN)) req->pri = ETP_PRI_MIN - ETP_PRI_MIN; - if (expect_false (req->pri > ETP_PRI_MAX - ETP_PRI_MIN)) req->pri = ETP_PRI_MAX - ETP_PRI_MIN; + if (ecb_expect_false (req->pri < ETP_PRI_MIN - ETP_PRI_MIN)) req->pri = ETP_PRI_MIN - ETP_PRI_MIN; + if (ecb_expect_false (req->pri > ETP_PRI_MAX - ETP_PRI_MIN)) req->pri = ETP_PRI_MAX - ETP_PRI_MIN; - if (expect_false (req->type == EIO_GROUP)) + if (ecb_expect_false (req->type == EIO_GROUP)) { /* I hope this is worth it :/ */ X_LOCK (reqlock); @@ -588,34 +629,47 @@ } } -static void etp_set_max_poll_time (double nseconds) +static void ecb_cold +etp_set_max_poll_time (double nseconds) { if (WORDACCESS_UNSAFE) X_LOCK (reslock); - max_poll_time = nseconds; + max_poll_time = nseconds * EIO_TICKS; if (WORDACCESS_UNSAFE) X_UNLOCK (reslock); } -static void etp_set_max_poll_reqs (unsigned int maxreqs) +static void ecb_cold +etp_set_max_poll_reqs (unsigned int maxreqs) { if (WORDACCESS_UNSAFE) X_LOCK (reslock); max_poll_reqs = maxreqs; if (WORDACCESS_UNSAFE) X_UNLOCK (reslock); } -static void etp_set_max_idle (unsigned int nthreads) +static void ecb_cold +etp_set_max_idle (unsigned int nthreads) +{ + if (WORDACCESS_UNSAFE) X_LOCK (reqlock); + max_idle = nthreads; + if (WORDACCESS_UNSAFE) X_UNLOCK (reqlock); +} + +static void ecb_cold +etp_set_idle_timeout (unsigned int seconds) { if (WORDACCESS_UNSAFE) X_LOCK (reqlock); - max_idle = nthreads <= 0 ? 1 : nthreads; + idle_timeout = seconds; if (WORDACCESS_UNSAFE) X_UNLOCK (reqlock); } -static void etp_set_min_parallel (unsigned int nthreads) +static void ecb_cold +etp_set_min_parallel (unsigned int nthreads) { if (wanted < nthreads) wanted = nthreads; } -static void etp_set_max_parallel (unsigned int nthreads) +static void ecb_cold +etp_set_max_parallel (unsigned int nthreads) { if (wanted > nthreads) wanted = nthreads; @@ -626,7 +680,8 @@ /*****************************************************************************/ -static void grp_try_feed (eio_req *grp) +static void +grp_try_feed (eio_req *grp) { while (grp->size < grp->int2 && !EIO_CANCELLED (grp)) { @@ -643,7 +698,8 @@ } } -static int grp_dec (eio_req *grp) +static int +grp_dec (eio_req *grp) { --grp->size; @@ -657,7 +713,8 @@ return 0; } -void eio_destroy (eio_req *req) +void +eio_destroy (eio_req *req) { if ((req)->flags & EIO_FLAG_PTR1_FREE) free (req->ptr1); if ((req)->flags & EIO_FLAG_PTR2_FREE) free (req->ptr2); @@ -665,7 +722,8 @@ EIO_DESTROY (req); } -static int eio_finish (eio_req *req) +static int +eio_finish (eio_req *req) { int res = EIO_FINISH (req); @@ -692,63 +750,81 @@ return res; } -void eio_grp_cancel (eio_req *grp) +void +eio_grp_cancel (eio_req *grp) { for (grp = grp->grp_first; grp; grp = grp->grp_next) eio_cancel (grp); } -void eio_cancel (eio_req *req) +void +eio_cancel (eio_req *req) { etp_cancel (req); } -void eio_submit (eio_req *req) +void +eio_submit (eio_req *req) { etp_submit (req); } -unsigned int eio_nreqs (void) +unsigned int +eio_nreqs (void) { return etp_nreqs (); } -unsigned int eio_nready (void) +unsigned int +eio_nready (void) { return etp_nready (); } -unsigned int eio_npending (void) +unsigned int +eio_npending (void) { return etp_npending (); } -unsigned int eio_nthreads (void) +unsigned int ecb_cold +eio_nthreads (void) { return etp_nthreads (); } -void eio_set_max_poll_time (double nseconds) +void ecb_cold +eio_set_max_poll_time (double nseconds) { etp_set_max_poll_time (nseconds); } -void eio_set_max_poll_reqs (unsigned int maxreqs) +void ecb_cold +eio_set_max_poll_reqs (unsigned int maxreqs) { etp_set_max_poll_reqs (maxreqs); } -void eio_set_max_idle (unsigned int nthreads) +void ecb_cold +eio_set_max_idle (unsigned int nthreads) { etp_set_max_idle (nthreads); } -void eio_set_min_parallel (unsigned int nthreads) +void ecb_cold +eio_set_idle_timeout (unsigned int seconds) +{ + etp_set_idle_timeout (seconds); +} + +void ecb_cold +eio_set_min_parallel (unsigned int nthreads) { etp_set_min_parallel (nthreads); } -void eio_set_max_parallel (unsigned int nthreads) +void ecb_cold +eio_set_max_parallel (unsigned int nthreads) { etp_set_max_parallel (nthreads); } @@ -800,12 +876,10 @@ } #endif -#ifndef HAVE_FUTIMES +#ifndef HAVE_UTIMES # undef utimes -# undef futimes -# define utimes(path,times) eio__utimes (path, times) -# define futimes(fd,times) eio__futimes (fd, times) +# define utimes(path,times) eio__utimes (path, times) static int eio__utimes (const char *filename, const struct timeval times[2]) @@ -823,7 +897,15 @@ return utime (filename, 0); } -static int eio__futimes (int fd, const struct timeval tv[2]) +#endif + +#ifndef HAVE_FUTIMES + +# undef futimes +# define futimes(fd,times) eio__futimes (fd, times) + +static int +eio__futimes (int fd, const struct timeval tv[2]) { errno = ENOSYS; return -1; @@ -837,7 +919,7 @@ #endif /* sync_file_range always needs emulation */ -int +static int eio__sync_file_range (int fd, off_t offset, size_t nbytes, unsigned int flags) { #if HAVE_SYNC_FILE_RANGE @@ -860,7 +942,7 @@ #endif /* even though we could play tricks with the flags, it's better to always - * call fdatasync, as thta matches the expectation of it's users best */ + * call fdatasync, as that matches the expectation of its users best */ return fdatasync (fd); } @@ -893,56 +975,110 @@ static ssize_t eio__sendfile (int ofd, int ifd, off_t offset, size_t count, etp_worker *self) { + ssize_t written = 0; ssize_t res; if (!count) return 0; + for (;;) + { #if HAVE_SENDFILE # if __linux - res = sendfile (ofd, ifd, &offset, count); + off_t soffset = offset; + res = sendfile (ofd, ifd, &soffset, count); -# elif __freebsd - /* - * Of course, the freebsd sendfile is a dire hack with no thoughts - * wasted on making it similar to other I/O functions. - */ - { - off_t sbytes; - res = sendfile (ifd, ofd, offset, count, 0, &sbytes, 0); - - if (res < 0 && sbytes) - /* maybe only on EAGAIN: as usual, the manpage leaves you guessing */ - res = sbytes; - } +# elif __FreeBSD__ + /* + * Of course, the freebsd sendfile is a dire hack with no thoughts + * wasted on making it similar to other I/O functions. + */ + off_t sbytes; + res = sendfile (ifd, ofd, offset, count, 0, &sbytes, 0); + + #if 0 /* according to the manpage, this is correct, but broken behaviour */ + /* freebsd' sendfile will return 0 on success */ + /* freebsd 8 documents it as only setting *sbytes on EINTR and EAGAIN, but */ + /* not on e.g. EIO or EPIPE - sounds broken */ + if ((res < 0 && (errno == EAGAIN || errno == EINTR) && sbytes) || res == 0) + res = sbytes; + #endif + + /* according to source inspection, this is correct, and useful behaviour */ + if (sbytes) + res = sbytes; + +# elif defined (__APPLE__) + off_t sbytes = count; + res = sendfile (ifd, ofd, offset, &sbytes, 0, 0); + + /* according to the manpage, sbytes is always valid */ + if (sbytes) + res = sbytes; # elif __hpux - res = sendfile (ofd, ifd, offset, count, 0, 0); + res = sendfile (ofd, ifd, offset, count, 0, 0); # elif __solaris - { - struct sendfilevec vec; - size_t sbytes; + struct sendfilevec vec; + size_t sbytes; - vec.sfv_fd = ifd; - vec.sfv_flag = 0; - vec.sfv_off = offset; - vec.sfv_len = count; + vec.sfv_fd = ifd; + vec.sfv_flag = 0; + vec.sfv_off = offset; + vec.sfv_len = count; - res = sendfilev (ofd, &vec, 1, &sbytes); + res = sendfilev (ofd, &vec, 1, &sbytes); - if (res < 0 && sbytes) - res = sbytes; - } + if (res < 0 && sbytes) + res = sbytes; # endif + +#elif defined (_WIN32) + /* does not work, just for documentation of what would need to be done */ + /* actually, cannot be done like this, as TransmitFile changes the file offset, */ + /* libeio guarantees that the file offset does not change, and windows */ + /* has no way to get an independent handle to the same file description */ + HANDLE h = TO_SOCKET (ifd); + SetFilePointer (h, offset, 0, FILE_BEGIN); + res = TransmitFile (TO_SOCKET (ofd), h, count, 0, 0, 0, 0); + #else - res = -1; - errno = ENOSYS; + res = -1; + errno = ENOSYS; #endif - if (res < 0 + /* we assume sendfile can copy at least 128mb in one go */ + if (res <= 128 * 1024 * 1024) + { + if (res > 0) + written += res; + + if (written) + return written; + + break; + } + else + { + /* if we requested more, then probably the kernel was lazy */ + written += res; + offset += res; + count -= res; + + if (!count) + return written; + } + } + + if (res < 0 && (errno == ENOSYS || errno == EINVAL || errno == ENOTSOCK + /* BSDs */ +#ifdef ENOTSUP /* sigh, if the steenking pile called openbsd would only try to at least compile posix code... */ + || errno == ENOTSUP +#endif + || errno == EOPNOTSUPP /* BSDs */ #if __solaris || errno == EAFNOSUPPORT || errno == EPROTOTYPE #endif @@ -983,14 +1119,169 @@ return res; } -static int -eio_dent_cmp (const void *a_, const void *b_) +static signed char +eio_dent_cmp (const eio_dirent *a, const eio_dirent *b) +{ + return a->score - b->score ? a->score - b->score /* works because our signed char is always 0..100 */ + : a->inode < b->inode ? -1 + : a->inode > b->inode ? 1 + : 0; +} + +#define EIO_DENT_CMP(i,op,j) eio_dent_cmp (&i, &j) op 0 + +#define EIO_SORT_CUTOFF 30 /* quite high, but performs well on many filesystems */ +#define EIO_SORT_FAST 60 /* when to only use insertion sort */ + +static void +eio_dent_radix_sort (eio_dirent *dents, int size, signed char score_bits, ino_t inode_bits) { - const eio_dirent *a = (const eio_dirent *)a_; - const eio_dirent *b = (const eio_dirent *)b_; + unsigned char bits [9 + sizeof (ino_t) * 8]; + unsigned char *bit = bits; + + assert (CHAR_BIT == 8); + assert (sizeof (eio_dirent) * 8 < 256); + assert (offsetof (eio_dirent, inode)); /* we use bit #0 as sentinel */ + assert (offsetof (eio_dirent, score)); /* we use bit #0 as sentinel */ + + if (size <= EIO_SORT_FAST) + return; + + /* first prepare an array of bits to test in our radix sort */ + /* try to take endianness into account, as well as differences in ino_t sizes */ + /* inode_bits must contain all inodes ORed together */ + /* which is used to skip bits that are 0 everywhere, which is very common */ + { + ino_t endianness; + int i, j; + + /* we store the byte offset of byte n into byte n of "endianness" */ + for (i = 0; i < sizeof (ino_t); ++i) + ((unsigned char *)&endianness)[i] = i; + + *bit++ = 0; - return (int)b->score - (int)a->score ? (int)b->score - (int)a->score - : a->inode < b->inode ? -1 : a->inode > b->inode ? 1 : 0; /* int might be < ino_t */ + for (i = 0; i < sizeof (ino_t); ++i) + { + /* shifting off the byte offsets out of "endianness" */ + int offs = (offsetof (eio_dirent, inode) + (endianness & 0xff)) * 8; + endianness >>= 8; + + for (j = 0; j < 8; ++j) + if (inode_bits & (((ino_t)1) << (i * 8 + j))) + *bit++ = offs + j; + } + + for (j = 0; j < 8; ++j) + if (score_bits & (1 << j)) + *bit++ = offsetof (eio_dirent, score) * 8 + j; + } + + /* now actually do the sorting (a variant of MSD radix sort) */ + { + eio_dirent *base_stk [9 + sizeof (ino_t) * 8], *base; + eio_dirent *end_stk [9 + sizeof (ino_t) * 8], *end; + unsigned char *bit_stk [9 + sizeof (ino_t) * 8]; + int stk_idx = 0; + + base_stk [stk_idx] = dents; + end_stk [stk_idx] = dents + size; + bit_stk [stk_idx] = bit - 1; + + do + { + base = base_stk [stk_idx]; + end = end_stk [stk_idx]; + bit = bit_stk [stk_idx]; + + for (;;) + { + unsigned char O = *bit >> 3; + unsigned char M = 1 << (*bit & 7); + + eio_dirent *a = base; + eio_dirent *b = end; + + if (b - a < EIO_SORT_CUTOFF) + break; + + /* now bit-partition the array on the bit */ + /* this ugly asymmetric loop seems to perform much better than typical */ + /* partition algos found in the literature */ + do + if (!(((unsigned char *)a)[O] & M)) + ++a; + else if (!(((unsigned char *)--b)[O] & M)) + { + eio_dirent tmp = *a; *a = *b; *b = tmp; + ++a; + } + while (b > a); + + /* next bit, or stop, if no bits left in this path */ + if (!*--bit) + break; + + base_stk [stk_idx] = a; + end_stk [stk_idx] = end; + bit_stk [stk_idx] = bit; + ++stk_idx; + + end = a; + } + } + while (stk_idx--); + } +} + +static void +eio_dent_insertion_sort (eio_dirent *dents, int size) +{ + /* first move the smallest element to the front, to act as a sentinel */ + { + int i; + eio_dirent *min = dents; + + /* the radix pre-pass ensures that the minimum element is in the first EIO_SORT_CUTOFF + 1 elements */ + for (i = size > EIO_SORT_FAST ? EIO_SORT_CUTOFF + 1 : size; --i; ) + if (EIO_DENT_CMP (dents [i], <, *min)) + min = &dents [i]; + + /* swap elements 0 and j (minimum) */ + { + eio_dirent tmp = *dents; *dents = *min; *min = tmp; + } + } + + /* then do standard insertion sort, assuming that all elements are >= dents [0] */ + { + eio_dirent *i, *j; + + for (i = dents + 1; i < dents + size; ++i) + { + eio_dirent value = *i; + + for (j = i - 1; EIO_DENT_CMP (*j, >, value); --j) + j [1] = j [0]; + + j [1] = value; + } + } +} + +static void +eio_dent_sort (eio_dirent *dents, int size, signed char score_bits, ino_t inode_bits) +{ + if (size <= 1) + return; /* our insertion sort relies on size > 0 */ + + /* first we use a radix sort, but only for dirs >= EIO_SORT_FAST */ + /* and stop sorting when the partitions are <= EIO_SORT_CUTOFF */ + eio_dent_radix_sort (dents, size, score_bits, inode_bits); + + /* use an insertion sort at the end, or for small arrays, */ + /* as insertion sort is more efficient for small partitions */ + eio_dent_insertion_sort (dents, size); } /* read a full directory */ @@ -999,13 +1290,14 @@ { DIR *dirp; EIO_STRUCT_DIRENT *entp; - unsigned char *name, *names; + char *name, *names; int namesalloc = 4096; int namesoffs = 0; int flags = req->int1; eio_dirent *dents = 0; int dentalloc = 128; int dentoffs = 0; + ino_t inode_bits = 0; req->result = -1; @@ -1015,9 +1307,10 @@ X_LOCK (wrklock); /* the corresponding closedir is in ETP_WORKER_CLEAR */ self->dirp = dirp = opendir (req->ptr1); + req->flags |= EIO_FLAG_PTR1_FREE | EIO_FLAG_PTR2_FREE; - req->ptr1 = names = malloc (namesalloc); - req->ptr2 = dents = flags ? malloc (dentalloc * sizeof (eio_dirent)) : 0; + req->ptr1 = dents = flags ? malloc (dentalloc * sizeof (eio_dirent)) : 0; + req->ptr2 = names = malloc (namesalloc); X_UNLOCK (wrklock); if (dirp && names && (!flags || dents)) @@ -1035,58 +1328,34 @@ req->int1 = flags; req->result = dentoffs; - if (dents) - { - eio_dirent *ent = dents + dentoffs; - - while (ent > dents) - (--ent)->name = names + (size_t)ent->name; - } - - if (flags & EIO_READDIR_STAT_ORDER - || !(~flags & (EIO_READDIR_DIRS_FIRST | EIO_READDIR_FOUND_UNKNOWN))) - { - /* pray your qsort doesn't use quicksort */ - qsort (dents, dentoffs, sizeof (*dents), eio_dent_cmp); /* score depends of DIRS_FIRST */ - } + if (flags & EIO_READDIR_STAT_ORDER) + eio_dent_sort (dents, dentoffs, flags & EIO_READDIR_DIRS_FIRST ? 7 : 0, inode_bits); else if (flags & EIO_READDIR_DIRS_FIRST) - { - /* in this case, all is known, and we just put dirs first and sort them */ - eio_dirent *ent = dents + dentoffs; - eio_dirent *dir = dents; - - while (ent > dir) - { - if (dir->type == DT_DIR) - ++dir; - else - { - --ent; - - if (ent->type == DT_DIR) - { - eio_dirent tmp = *dir; - *dir = *ent; - *ent = tmp; - - ++dir; - } - } - } - - /* now sort the dirs only */ - qsort (dents, dir - dents, sizeof (*dents), eio_dent_cmp); - } + if (flags & EIO_READDIR_FOUND_UNKNOWN) + eio_dent_sort (dents, dentoffs, 7, inode_bits); /* sort by score and inode */ + else + { + /* in this case, all is known, and we just put dirs first and sort them */ + eio_dirent *oth = dents + dentoffs; + eio_dirent *dir = dents; + + /* now partition dirs to the front, and non-dirs to the back */ + /* by walking from both sides and swapping if necessary */ + while (oth > dir) + { + if (dir->type == EIO_DT_DIR) + ++dir; + else if ((--oth)->type == EIO_DT_DIR) + { + eio_dirent tmp = *dir; *dir = *oth; *oth = tmp; + + ++dir; + } + } - /* only provide the names array unless DENTS is specified */ - if (!(flags & EIO_READDIR_DENTS)) - { - X_LOCK (wrklock); - assert (!dents); - req->ptr1 = 0; - req->ptr2 = names; - X_UNLOCK (wrklock); - } + /* now sort the dirs only (dirs all have the same score) */ + eio_dent_sort (dents, dir - dents, 0, inode_bits); + } break; } @@ -1097,13 +1366,13 @@ /* skip . and .. entries */ if (name [0] != '.' || (name [1] && (name [1] != '.' || name [2]))) { - int len = strlen (name) + 1; + int len = D_NAMLEN (entp) + 1; - while (expect_false (namesoffs + len > namesalloc)) + while (ecb_expect_false (namesoffs + len > namesalloc)) { namesalloc *= 2; X_LOCK (wrklock); - req->ptr1 = names = realloc (names, namesalloc); + req->ptr2 = names = realloc (names, namesalloc); X_UNLOCK (wrklock); if (!names) @@ -1116,11 +1385,11 @@ { struct eio_dirent *ent; - if (expect_false (dentoffs == dentalloc)) + if (ecb_expect_false (dentoffs == dentalloc)) { dentalloc *= 2; X_LOCK (wrklock); - req->ptr2 = dents = realloc (dents, dentalloc * sizeof (eio_dirent)); + req->ptr1 = dents = realloc (dents, dentalloc * sizeof (eio_dirent)); X_UNLOCK (wrklock); if (!dents) @@ -1129,10 +1398,12 @@ ent = dents + dentoffs; - ent->name = (char *)(size_t)namesoffs; /* rather dirtily we store the offset in the pointer */ + ent->nameofs = namesoffs; /* rather dirtily we store the offset in the pointer */ ent->namelen = len - 1; ent->inode = D_INO (entp); + inode_bits |= ent->inode; + switch (D_TYPE (entp)) { default: @@ -1146,76 +1417,184 @@ #ifdef DT_CHR case DT_CHR: ent->type = EIO_DT_CHR; break; #endif + #ifdef DT_MPC + case DT_MPC: ent->type = EIO_DT_MPC; break; + #endif #ifdef DT_DIR case DT_DIR: ent->type = EIO_DT_DIR; break; #endif + #ifdef DT_NAM + case DT_NAM: ent->type = EIO_DT_NAM; break; + #endif #ifdef DT_BLK case DT_BLK: ent->type = EIO_DT_BLK; break; #endif + #ifdef DT_MPB + case DT_MPB: ent->type = EIO_DT_MPB; break; + #endif #ifdef DT_REG case DT_REG: ent->type = EIO_DT_REG; break; #endif + #ifdef DT_NWK + case DT_NWK: ent->type = EIO_DT_NWK; break; + #endif + #ifdef DT_CMP + case DT_CMP: ent->type = EIO_DT_CMP; break; + #endif #ifdef DT_LNK case DT_LNK: ent->type = EIO_DT_LNK; break; #endif #ifdef DT_SOCK case DT_SOCK: ent->type = EIO_DT_SOCK; break; #endif + #ifdef DT_DOOR + case DT_DOOR: ent->type = EIO_DT_DOOR; break; + #endif #ifdef DT_WHT case DT_WHT: ent->type = EIO_DT_WHT; break; #endif } - ent->score = 0; + ent->score = 7; if (flags & EIO_READDIR_DIRS_FIRST) { if (ent->type == EIO_DT_UNKNOWN) { if (*name == '.') /* leading dots are likely directories, and, in any case, rare */ - ent->score = 98; + ent->score = 1; else if (!strchr (name, '.')) /* absense of dots indicate likely dirs */ - ent->score = len <= 4 ? 5 : len <= 7 ? 4 : 1; /* shorter == more likely dir, but avoid too many classes */ + ent->score = len <= 2 ? 4 - len : len <= 4 ? 4 : len <= 7 ? 5 : 6; /* shorter == more likely dir, but avoid too many classes */ } - else if (ent->type == DT_DIR) - ent->score = 100; + else if (ent->type == EIO_DT_DIR) + ent->score = 0; } } namesoffs += len; ++dentoffs; } + + if (EIO_CANCELLED (req)) + { + errno = ECANCELED; + break; + } } - else - req->result = -1; } -#if !(_POSIX_MAPPED_FILES && _POSIX_SYNCHRONIZED_IO) -# undef msync -# define msync(a,b,c) ((errno = ENOSYS), -1) -#endif - -int -eio__mtouch (void *mem, size_t len, int flags) -{ - intptr_t addr = (intptr_t)mem; - intptr_t end = addr + len; #ifdef PAGESIZE - const intptr_t page = PAGESIZE; +# define eio_pagesize() PAGESIZE #else +static intptr_t +eio_pagesize (void) +{ static intptr_t page; if (!page) page = sysconf (_SC_PAGESIZE); + + return page; +} #endif - addr &= ~(page - 1); /* assume page size is always a power of two */ +static void +eio_page_align (void **addr, size_t *length) +{ + intptr_t mask = eio_pagesize () - 1; - if (addr < end) - if (flags) /* modify */ - do { *((volatile sig_atomic_t *)addr) |= 0; } while ((addr += page) < len); - else - do { *((volatile sig_atomic_t *)addr) ; } while ((addr += page) < len); + /* round down addr */ + intptr_t adj = mask & (intptr_t)*addr; + + *addr = (void *)((intptr_t)*addr - adj); + *length += adj; + + /* round up length */ + *length = (*length + mask) & ~mask; +} + +#if !_POSIX_MEMLOCK +# define eio__mlockall(a) ((errno = ENOSYS), -1) +#else + +static int +eio__mlockall (int flags) +{ + #if __GLIBC__ == 2 && __GLIBC_MINOR__ <= 7 + extern int mallopt (int, int); + mallopt (-6, 238); /* http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=473812 */ + #endif + + if (EIO_MCL_CURRENT != MCL_CURRENT + || EIO_MCL_FUTURE != MCL_FUTURE) + { + flags = 0 + | (flags & EIO_MCL_CURRENT ? MCL_CURRENT : 0) + | (flags & EIO_MCL_FUTURE ? MCL_FUTURE : 0); + } + + return mlockall (flags); +} +#endif + +#if !_POSIX_MEMLOCK_RANGE +# define eio__mlock(a,b) ((errno = ENOSYS), -1) +#else + +static int +eio__mlock (void *addr, size_t length) +{ + eio_page_align (&addr, &length); + + return mlock (addr, length); +} + +#endif + +#if !(_POSIX_MAPPED_FILES && _POSIX_SYNCHRONIZED_IO) +# define eio__msync(a,b,c) ((errno = ENOSYS), -1) +#else + +static int +eio__msync (void *mem, size_t len, int flags) +{ + eio_page_align (&mem, &len); + + if (EIO_MS_ASYNC != MS_SYNC + || EIO_MS_INVALIDATE != MS_INVALIDATE + || EIO_MS_SYNC != MS_SYNC) + { + flags = 0 + | (flags & EIO_MS_ASYNC ? MS_ASYNC : 0) + | (flags & EIO_MS_INVALIDATE ? MS_INVALIDATE : 0) + | (flags & EIO_MS_SYNC ? MS_SYNC : 0); + } + + return msync (mem, len, flags); +} + +#endif + +static int +eio__mtouch (eio_req *req) +{ + void *mem = req->ptr2; + size_t len = req->size; + int flags = req->int1; + + eio_page_align (&mem, &len); + + { + intptr_t addr = (intptr_t)mem; + intptr_t end = addr + len; + intptr_t page = eio_pagesize (); + + if (addr < end) + if (flags & EIO_MT_MODIFY) /* modify */ + do { *((volatile sig_atomic_t *)addr) |= 0; } while ((addr += page) < len && !EIO_CANCELLED (req)); + else + do { *((volatile sig_atomic_t *)addr) ; } while ((addr += page) < len && !EIO_CANCELLED (req)); + } return 0; } @@ -1259,7 +1638,7 @@ ++idle; - ts.tv_sec = time (0) + IDLE_TIMEOUT; + ts.tv_sec = time (0) + idle_timeout; if (X_COND_TIMEDWAIT (reqwait, reqlock, ts) == ETIMEDOUT) { if (idle > max_idle) @@ -1312,12 +1691,14 @@ /*****************************************************************************/ -int eio_init (void (*want_poll)(void), void (*done_poll)(void)) +int ecb_cold +eio_init (void (*want_poll)(void), void (*done_poll)(void)) { return etp_init (want_poll, done_poll); } -static void eio_api_destroy (eio_req *req) +ECB_INLINE void +eio_api_destroy (eio_req *req) { free (req); } @@ -1346,10 +1727,9 @@ return 0; \ } -static void eio_execute (etp_worker *self, eio_req *req) +static void +eio_execute (etp_worker *self, eio_req *req) { - errno = 0; - switch (req->type) { case EIO_READ: ALLOC (req->size); @@ -1370,6 +1750,11 @@ case EIO_FSTAT: ALLOC (sizeof (EIO_STRUCT_STAT)); req->result = fstat (req->int1, (EIO_STRUCT_STAT *)req->ptr2); break; + case EIO_STATVFS: ALLOC (sizeof (EIO_STRUCT_STATVFS)); + req->result = statvfs (req->ptr1, (EIO_STRUCT_STATVFS *)req->ptr2); break; + case EIO_FSTATVFS: ALLOC (sizeof (EIO_STRUCT_STATVFS)); + req->result = fstatvfs (req->int1, (EIO_STRUCT_STATVFS *)req->ptr2); break; + case EIO_CHOWN: req->result = chown (req->ptr1, req->int2, req->int3); break; case EIO_FCHOWN: req->result = fchown (req->int1, req->int2, req->int3); break; case EIO_CHMOD: req->result = chmod (req->ptr1, (mode_t)req->int2); break; @@ -1386,29 +1771,31 @@ case EIO_RENAME: req->result = rename (req->ptr1, req->ptr2); break; case EIO_LINK: req->result = link (req->ptr1, req->ptr2); break; case EIO_SYMLINK: req->result = symlink (req->ptr1, req->ptr2); break; - case EIO_MKNOD: req->result = mknod (req->ptr1, (mode_t)req->int2, (dev_t)req->int3); break; + case EIO_MKNOD: req->result = mknod (req->ptr1, (mode_t)req->int2, (dev_t)req->offs); break; - case EIO_READLINK: ALLOC (NAME_MAX); - req->result = readlink (req->ptr1, req->ptr2, NAME_MAX); break; + case EIO_READLINK: ALLOC (PATH_MAX); + req->result = readlink (req->ptr1, req->ptr2, PATH_MAX); break; case EIO_SYNC: req->result = 0; sync (); break; case EIO_FSYNC: req->result = fsync (req->int1); break; case EIO_FDATASYNC: req->result = fdatasync (req->int1); break; - case EIO_MSYNC: req->result = msync (req->ptr2, req->size, req->int1); break; - case EIO_MTOUCH: req->result = eio__mtouch (req->ptr2, req->size, req->int1); break; + case EIO_MSYNC: req->result = eio__msync (req->ptr2, req->size, req->int1); break; + case EIO_MTOUCH: req->result = eio__mtouch (req); break; + case EIO_MLOCK: req->result = eio__mlock (req->ptr2, req->size); break; + case EIO_MLOCKALL: req->result = eio__mlockall (req->int1); break; case EIO_SYNC_FILE_RANGE: req->result = eio__sync_file_range (req->int1, req->offs, req->size, req->int2); break; case EIO_READDIR: eio__scandir (req, self); break; case EIO_BUSY: #ifdef _WIN32 - Sleep (req->nv1 * 1000.); + Sleep (req->nv1 * 1e3); #else { struct timeval tv; tv.tv_sec = req->nv1; - tv.tv_usec = (req->nv1 - tv.tv_sec) * 1000000.; + tv.tv_usec = (req->nv1 - tv.tv_sec) * 1e6; req->result = select (0, 0, 0, 0, &tv); } @@ -1433,7 +1820,6 @@ else times = 0; - req->result = req->type == EIO_FUTIME ? futimes (req->int1, times) : utimes (req->ptr1, times); @@ -1448,10 +1834,11 @@ break; case EIO_CUSTOM: - ((void (*)(eio_req *))req->feed) (req); + req->feed (req); break; default: + errno = ENOSYS; req->result = -1; break; } @@ -1491,6 +1878,16 @@ REQ (EIO_MTOUCH); req->ptr2 = addr; req->size = length; req->int1 = flags; SEND; } +eio_req *eio_mlock (void *addr, size_t length, int pri, eio_cb cb, void *data) +{ + REQ (EIO_MLOCK); req->ptr2 = addr; req->size = length; SEND; +} + +eio_req *eio_mlockall (int flags, int pri, eio_cb cb, void *data) +{ + REQ (EIO_MLOCKALL); req->int1 = flags; SEND; +} + eio_req *eio_sync_file_range (int fd, off_t offset, size_t nbytes, unsigned int flags, int pri, eio_cb cb, void *data) { REQ (EIO_SYNC_FILE_RANGE); req->int1 = fd; req->offs = offset; req->size = nbytes; req->int2 = flags; SEND; @@ -1526,6 +1923,11 @@ REQ (EIO_FSTAT); req->int1 = fd; SEND; } +eio_req *eio_fstatvfs (int fd, int pri, eio_cb cb, void *data) +{ + REQ (EIO_FSTATVFS); req->int1 = fd; SEND; +} + eio_req *eio_futime (int fd, double atime, double mtime, int pri, eio_cb cb, void *data) { REQ (EIO_FUTIME); req->int1 = fd; req->nv1 = atime; req->nv2 = mtime; SEND; @@ -1607,6 +2009,11 @@ return eio__1path (EIO_LSTAT, path, pri, cb, data); } +eio_req *eio_statvfs (const char *path, int pri, eio_cb cb, void *data) +{ + return eio__1path (EIO_STATVFS, path, pri, cb, data); +} + eio_req *eio_unlink (const char *path, int pri, eio_cb cb, void *data) { return eio__1path (EIO_UNLINK, path, pri, cb, data); @@ -1624,7 +2031,7 @@ eio_req *eio_mknod (const char *path, mode_t mode, dev_t dev, int pri, eio_cb cb, void *data) { - REQ (EIO_MKNOD); PATH; req->int2 = (long)mode; req->int3 = (long)dev; SEND; + REQ (EIO_MKNOD); PATH; req->int2 = (long)mode; req->offs = (off_t)dev; SEND; } static eio_req * @@ -1658,9 +2065,9 @@ return eio__2path (EIO_RENAME, path, new_path, pri, cb, data); } -eio_req *eio_custom (eio_cb execute, int pri, eio_cb cb, void *data) +eio_req *eio_custom (void (*execute)(eio_req *), int pri, eio_cb cb, void *data) { - REQ (EIO_CUSTOM); req->feed = (void (*)(eio_req *))execute; SEND; + REQ (EIO_CUSTOM); req->feed = execute; SEND; } #endif @@ -1679,7 +2086,8 @@ /*****************************************************************************/ /* grp functions */ -void eio_grp_feed (eio_req *grp, void (*feed)(eio_req *req), int limit) +void +eio_grp_feed (eio_req *grp, void (*feed)(eio_req *req), int limit) { grp->int2 = limit; grp->feed = feed; @@ -1687,14 +2095,16 @@ grp_try_feed (grp); } -void eio_grp_limit (eio_req *grp, int limit) +void +eio_grp_limit (eio_req *grp, int limit) { grp->int2 = limit; grp_try_feed (grp); } -void eio_grp_add (eio_req *grp, eio_req *req) +void +eio_grp_add (eio_req *grp, eio_req *req) { assert (("cannot add requests to IO::AIO::GRP after the group finished", grp->int1 != 2)); @@ -1715,15 +2125,19 @@ /*****************************************************************************/ /* misc garbage */ -ssize_t eio_sendfile_sync (int ofd, int ifd, off_t offset, size_t count) +ssize_t +eio_sendfile_sync (int ofd, int ifd, off_t offset, size_t count) { etp_worker wrk; + ssize_t ret; wrk.dbuf = 0; - eio__sendfile (ofd, ifd, offset, count, &wrk); + ret = eio__sendfile (ofd, ifd, offset, count, &wrk); if (wrk.dbuf) free (wrk.dbuf); + + return ret; }