PageRenderTime 62ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/src/libeio/eio.c

http://github.com/jacksonh/manos
C | 2051 lines | 1504 code | 421 blank | 126 comment | 236 complexity | 9f1d3e9a69f7be9ed4be6d8ca5e65637 MD5 | raw file
Possible License(s): BSD-2-Clause
  1. /*
  2. * libeio implementation
  3. *
  4. * Copyright (c) 2007,2008,2009,2010 Marc Alexander Lehmann <libeio@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. #include "eio.h"
  40. #ifdef EIO_STACKSIZE
  41. # define XTHREAD_STACKSIZE EIO_STACKSIZE
  42. #endif
  43. #include "xthread.h"
  44. #include <errno.h>
  45. #include <stddef.h>
  46. #include <stdlib.h>
  47. #include <string.h>
  48. #include <errno.h>
  49. #include <sys/types.h>
  50. #include <sys/stat.h>
  51. #include <sys/statvfs.h>
  52. #include <limits.h>
  53. #include <fcntl.h>
  54. #include <assert.h>
  55. #ifndef EIO_FINISH
  56. # define EIO_FINISH(req) ((req)->finish) && !EIO_CANCELLED (req) ? (req)->finish (req) : 0
  57. #endif
  58. #ifndef EIO_DESTROY
  59. # define EIO_DESTROY(req) do { if ((req)->destroy) (req)->destroy (req); } while (0)
  60. #endif
  61. #ifndef EIO_FEED
  62. # define EIO_FEED(req) do { if ((req)->feed ) (req)->feed (req); } while (0)
  63. #endif
  64. #ifdef _WIN32
  65. /*doh*/
  66. #else
  67. # include "config.h"
  68. # include <sys/time.h>
  69. # include <sys/select.h>
  70. # include <unistd.h>
  71. # include <utime.h>
  72. # include <signal.h>
  73. # include <dirent.h>
  74. #if _POSIX_MEMLOCK || _POSIX_MEMLOCK_RANGE || _POSIX_MAPPED_FILES
  75. # include <sys/mman.h>
  76. #endif
  77. /* POSIX_SOURCE is useless on bsd's, and XOPEN_SOURCE is unreliable there, too */
  78. # if __FreeBSD__ || defined __NetBSD__ || defined __OpenBSD__
  79. # define _DIRENT_HAVE_D_TYPE /* sigh */
  80. # define D_INO(de) (de)->d_fileno
  81. # define D_NAMLEN(de) (de)->d_namlen
  82. # elif __linux || defined d_ino || _XOPEN_SOURCE >= 600
  83. # define D_INO(de) (de)->d_ino
  84. # endif
  85. #ifdef _D_EXACT_NAMLEN
  86. # undef D_NAMLEN
  87. # define D_NAMLEN(de) _D_EXACT_NAMLEN (de)
  88. #endif
  89. # ifdef _DIRENT_HAVE_D_TYPE
  90. # define D_TYPE(de) (de)->d_type
  91. # endif
  92. # ifndef EIO_STRUCT_DIRENT
  93. # define EIO_STRUCT_DIRENT struct dirent
  94. # endif
  95. #endif
  96. #if HAVE_SENDFILE
  97. # if __linux
  98. # include <sys/sendfile.h>
  99. # elif __FreeBSD__ || defined __APPLE__
  100. # include <sys/socket.h>
  101. # include <sys/uio.h>
  102. # elif __hpux
  103. # include <sys/socket.h>
  104. # elif __solaris
  105. # include <sys/sendfile.h>
  106. # else
  107. # error sendfile support requested but not available
  108. # endif
  109. #endif
  110. #ifndef D_TYPE
  111. # define D_TYPE(de) 0
  112. #endif
  113. #ifndef D_INO
  114. # define D_INO(de) 0
  115. #endif
  116. #ifndef D_NAMLEN
  117. # define D_NAMLEN(de) strlen ((de)->d_name)
  118. #endif
  119. /* number of seconds after which an idle threads exit */
  120. #define IDLE_TIMEOUT 10
  121. /* used for struct dirent, AIX doesn't provide it */
  122. #ifndef NAME_MAX
  123. # define NAME_MAX 4096
  124. #endif
  125. /* used for readlink etc. */
  126. #ifndef PATH_MAX
  127. # define PATH_MAX 4096
  128. #endif
  129. /* buffer size for various temporary buffers */
  130. #define EIO_BUFSIZE 65536
  131. #define dBUF \
  132. char *eio_buf; \
  133. ETP_WORKER_LOCK (self); \
  134. self->dbuf = eio_buf = malloc (EIO_BUFSIZE); \
  135. ETP_WORKER_UNLOCK (self); \
  136. errno = ENOMEM; \
  137. if (!eio_buf) \
  138. return -1;
  139. #define EIO_TICKS ((1000000 + 1023) >> 10)
  140. /*****************************************************************************/
  141. #if __GNUC__ >= 3
  142. # define expect(expr,value) __builtin_expect ((expr),(value))
  143. #else
  144. # define expect(expr,value) (expr)
  145. #endif
  146. #define expect_false(expr) expect ((expr) != 0, 0)
  147. #define expect_true(expr) expect ((expr) != 0, 1)
  148. /*****************************************************************************/
  149. #define ETP_PRI_MIN EIO_PRI_MIN
  150. #define ETP_PRI_MAX EIO_PRI_MAX
  151. struct etp_worker;
  152. #define ETP_REQ eio_req
  153. #define ETP_DESTROY(req) eio_destroy (req)
  154. static int eio_finish (eio_req *req);
  155. #define ETP_FINISH(req) eio_finish (req)
  156. static void eio_execute (struct etp_worker *self, eio_req *req);
  157. #define ETP_EXECUTE(wrk,req) eio_execute (wrk,req)
  158. #define ETP_WORKER_CLEAR(req) \
  159. if (wrk->dbuf) \
  160. { \
  161. free (wrk->dbuf); \
  162. wrk->dbuf = 0; \
  163. } \
  164. \
  165. if (wrk->dirp) \
  166. { \
  167. closedir (wrk->dirp); \
  168. wrk->dirp = 0; \
  169. }
  170. #define ETP_WORKER_COMMON \
  171. void *dbuf; \
  172. DIR *dirp;
  173. /*****************************************************************************/
  174. #define ETP_NUM_PRI (ETP_PRI_MAX - ETP_PRI_MIN + 1)
  175. /* calculate time difference in ~1/EIO_TICKS of a second */
  176. static int tvdiff (struct timeval *tv1, struct timeval *tv2)
  177. {
  178. return (tv2->tv_sec - tv1->tv_sec ) * EIO_TICKS
  179. + ((tv2->tv_usec - tv1->tv_usec) >> 10);
  180. }
  181. static unsigned int started, idle, wanted = 4;
  182. static void (*want_poll_cb) (void);
  183. static void (*done_poll_cb) (void);
  184. static unsigned int max_poll_time; /* reslock */
  185. static unsigned int max_poll_reqs; /* reslock */
  186. static volatile unsigned int nreqs; /* reqlock */
  187. static volatile unsigned int nready; /* reqlock */
  188. static volatile unsigned int npending; /* reqlock */
  189. static volatile unsigned int max_idle = 4;
  190. static xmutex_t wrklock = X_MUTEX_INIT;
  191. static xmutex_t reslock = X_MUTEX_INIT;
  192. static xmutex_t reqlock = X_MUTEX_INIT;
  193. static xcond_t reqwait = X_COND_INIT;
  194. #if !HAVE_PREADWRITE
  195. /*
  196. * make our pread/pwrite emulation safe against themselves, but not against
  197. * normal read/write by using a mutex. slows down execution a lot,
  198. * but that's your problem, not mine.
  199. */
  200. static xmutex_t preadwritelock = X_MUTEX_INIT;
  201. #endif
  202. typedef struct etp_worker
  203. {
  204. /* locked by wrklock */
  205. struct etp_worker *prev, *next;
  206. xthread_t tid;
  207. /* locked by reslock, reqlock or wrklock */
  208. ETP_REQ *req; /* currently processed request */
  209. ETP_WORKER_COMMON
  210. } etp_worker;
  211. static etp_worker wrk_first = { &wrk_first, &wrk_first, 0 }; /* NOT etp */
  212. #define ETP_WORKER_LOCK(wrk) X_LOCK (wrklock)
  213. #define ETP_WORKER_UNLOCK(wrk) X_UNLOCK (wrklock)
  214. /* worker threads management */
  215. static void etp_worker_clear (etp_worker *wrk)
  216. {
  217. ETP_WORKER_CLEAR (wrk);
  218. }
  219. static void etp_worker_free (etp_worker *wrk)
  220. {
  221. wrk->next->prev = wrk->prev;
  222. wrk->prev->next = wrk->next;
  223. free (wrk);
  224. }
  225. static unsigned int etp_nreqs (void)
  226. {
  227. int retval;
  228. if (WORDACCESS_UNSAFE) X_LOCK (reqlock);
  229. retval = nreqs;
  230. if (WORDACCESS_UNSAFE) X_UNLOCK (reqlock);
  231. return retval;
  232. }
  233. static unsigned int etp_nready (void)
  234. {
  235. unsigned int retval;
  236. if (WORDACCESS_UNSAFE) X_LOCK (reqlock);
  237. retval = nready;
  238. if (WORDACCESS_UNSAFE) X_UNLOCK (reqlock);
  239. return retval;
  240. }
  241. static unsigned int etp_npending (void)
  242. {
  243. unsigned int retval;
  244. if (WORDACCESS_UNSAFE) X_LOCK (reqlock);
  245. retval = npending;
  246. if (WORDACCESS_UNSAFE) X_UNLOCK (reqlock);
  247. return retval;
  248. }
  249. static unsigned int etp_nthreads (void)
  250. {
  251. unsigned int retval;
  252. if (WORDACCESS_UNSAFE) X_LOCK (reqlock);
  253. retval = started;
  254. if (WORDACCESS_UNSAFE) X_UNLOCK (reqlock);
  255. return retval;
  256. }
  257. /*
  258. * a somewhat faster data structure might be nice, but
  259. * with 8 priorities this actually needs <20 insns
  260. * per shift, the most expensive operation.
  261. */
  262. typedef struct {
  263. ETP_REQ *qs[ETP_NUM_PRI], *qe[ETP_NUM_PRI]; /* qstart, qend */
  264. int size;
  265. } etp_reqq;
  266. static etp_reqq req_queue;
  267. static etp_reqq res_queue;
  268. static int reqq_push (etp_reqq *q, ETP_REQ *req)
  269. {
  270. int pri = req->pri;
  271. req->next = 0;
  272. if (q->qe[pri])
  273. {
  274. q->qe[pri]->next = req;
  275. q->qe[pri] = req;
  276. }
  277. else
  278. q->qe[pri] = q->qs[pri] = req;
  279. return q->size++;
  280. }
  281. static ETP_REQ *reqq_shift (etp_reqq *q)
  282. {
  283. int pri;
  284. if (!q->size)
  285. return 0;
  286. --q->size;
  287. for (pri = ETP_NUM_PRI; pri--; )
  288. {
  289. eio_req *req = q->qs[pri];
  290. if (req)
  291. {
  292. if (!(q->qs[pri] = (eio_req *)req->next))
  293. q->qe[pri] = 0;
  294. return req;
  295. }
  296. }
  297. abort ();
  298. }
  299. static void etp_atfork_prepare (void)
  300. {
  301. X_LOCK (wrklock);
  302. X_LOCK (reqlock);
  303. X_LOCK (reslock);
  304. #if !HAVE_PREADWRITE
  305. X_LOCK (preadwritelock);
  306. #endif
  307. }
  308. static void etp_atfork_parent (void)
  309. {
  310. #if !HAVE_PREADWRITE
  311. X_UNLOCK (preadwritelock);
  312. #endif
  313. X_UNLOCK (reslock);
  314. X_UNLOCK (reqlock);
  315. X_UNLOCK (wrklock);
  316. }
  317. static void etp_atfork_child (void)
  318. {
  319. ETP_REQ *prv;
  320. while ((prv = reqq_shift (&req_queue)))
  321. ETP_DESTROY (prv);
  322. while ((prv = reqq_shift (&res_queue)))
  323. ETP_DESTROY (prv);
  324. while (wrk_first.next != &wrk_first)
  325. {
  326. etp_worker *wrk = wrk_first.next;
  327. if (wrk->req)
  328. ETP_DESTROY (wrk->req);
  329. etp_worker_clear (wrk);
  330. etp_worker_free (wrk);
  331. }
  332. started = 0;
  333. idle = 0;
  334. nreqs = 0;
  335. nready = 0;
  336. npending = 0;
  337. etp_atfork_parent ();
  338. }
  339. static void
  340. etp_once_init (void)
  341. {
  342. X_THREAD_ATFORK (etp_atfork_prepare, etp_atfork_parent, etp_atfork_child);
  343. }
  344. static int
  345. etp_init (void (*want_poll)(void), void (*done_poll)(void))
  346. {
  347. static pthread_once_t doinit = PTHREAD_ONCE_INIT;
  348. pthread_once (&doinit, etp_once_init);
  349. want_poll_cb = want_poll;
  350. done_poll_cb = done_poll;
  351. return 0;
  352. }
  353. X_THREAD_PROC (etp_proc);
  354. static void etp_start_thread (void)
  355. {
  356. etp_worker *wrk = calloc (1, sizeof (etp_worker));
  357. /*TODO*/
  358. assert (("unable to allocate worker thread data", wrk));
  359. X_LOCK (wrklock);
  360. if (thread_create (&wrk->tid, etp_proc, (void *)wrk))
  361. {
  362. wrk->prev = &wrk_first;
  363. wrk->next = wrk_first.next;
  364. wrk_first.next->prev = wrk;
  365. wrk_first.next = wrk;
  366. ++started;
  367. }
  368. else
  369. free (wrk);
  370. X_UNLOCK (wrklock);
  371. }
  372. static void etp_maybe_start_thread (void)
  373. {
  374. if (expect_true (etp_nthreads () >= wanted))
  375. return;
  376. /* todo: maybe use idle here, but might be less exact */
  377. if (expect_true (0 <= (int)etp_nthreads () + (int)etp_npending () - (int)etp_nreqs ()))
  378. return;
  379. etp_start_thread ();
  380. }
  381. static void etp_end_thread (void)
  382. {
  383. eio_req *req = calloc (1, sizeof (eio_req));
  384. req->type = -1;
  385. req->pri = ETP_PRI_MAX - ETP_PRI_MIN;
  386. X_LOCK (reqlock);
  387. reqq_push (&req_queue, req);
  388. X_COND_SIGNAL (reqwait);
  389. X_UNLOCK (reqlock);
  390. X_LOCK (wrklock);
  391. --started;
  392. X_UNLOCK (wrklock);
  393. }
  394. static int etp_poll (void)
  395. {
  396. unsigned int maxreqs;
  397. unsigned int maxtime;
  398. struct timeval tv_start, tv_now;
  399. X_LOCK (reslock);
  400. maxreqs = max_poll_reqs;
  401. maxtime = max_poll_time;
  402. X_UNLOCK (reslock);
  403. if (maxtime)
  404. gettimeofday (&tv_start, 0);
  405. for (;;)
  406. {
  407. ETP_REQ *req;
  408. etp_maybe_start_thread ();
  409. X_LOCK (reslock);
  410. req = reqq_shift (&res_queue);
  411. if (req)
  412. {
  413. --npending;
  414. if (!res_queue.size && done_poll_cb)
  415. done_poll_cb ();
  416. }
  417. X_UNLOCK (reslock);
  418. if (!req)
  419. return 0;
  420. X_LOCK (reqlock);
  421. --nreqs;
  422. X_UNLOCK (reqlock);
  423. if (expect_false (req->type == EIO_GROUP && req->size))
  424. {
  425. req->int1 = 1; /* mark request as delayed */
  426. continue;
  427. }
  428. else
  429. {
  430. int res = ETP_FINISH (req);
  431. if (expect_false (res))
  432. return res;
  433. }
  434. if (expect_false (maxreqs && !--maxreqs))
  435. break;
  436. if (maxtime)
  437. {
  438. gettimeofday (&tv_now, 0);
  439. if (tvdiff (&tv_start, &tv_now) >= maxtime)
  440. break;
  441. }
  442. }
  443. errno = EAGAIN;
  444. return -1;
  445. }
  446. static void etp_cancel (ETP_REQ *req)
  447. {
  448. X_LOCK (wrklock);
  449. req->flags |= EIO_FLAG_CANCELLED;
  450. X_UNLOCK (wrklock);
  451. eio_grp_cancel (req);
  452. }
  453. static void etp_submit (ETP_REQ *req)
  454. {
  455. req->pri -= ETP_PRI_MIN;
  456. if (expect_false (req->pri < ETP_PRI_MIN - ETP_PRI_MIN)) req->pri = ETP_PRI_MIN - ETP_PRI_MIN;
  457. if (expect_false (req->pri > ETP_PRI_MAX - ETP_PRI_MIN)) req->pri = ETP_PRI_MAX - ETP_PRI_MIN;
  458. if (expect_false (req->type == EIO_GROUP))
  459. {
  460. /* I hope this is worth it :/ */
  461. X_LOCK (reqlock);
  462. ++nreqs;
  463. X_UNLOCK (reqlock);
  464. X_LOCK (reslock);
  465. ++npending;
  466. if (!reqq_push (&res_queue, req) && want_poll_cb)
  467. want_poll_cb ();
  468. X_UNLOCK (reslock);
  469. }
  470. else
  471. {
  472. X_LOCK (reqlock);
  473. ++nreqs;
  474. ++nready;
  475. reqq_push (&req_queue, req);
  476. X_COND_SIGNAL (reqwait);
  477. X_UNLOCK (reqlock);
  478. etp_maybe_start_thread ();
  479. }
  480. }
  481. static void etp_set_max_poll_time (double nseconds)
  482. {
  483. if (WORDACCESS_UNSAFE) X_LOCK (reslock);
  484. max_poll_time = nseconds * EIO_TICKS;
  485. if (WORDACCESS_UNSAFE) X_UNLOCK (reslock);
  486. }
  487. static void etp_set_max_poll_reqs (unsigned int maxreqs)
  488. {
  489. if (WORDACCESS_UNSAFE) X_LOCK (reslock);
  490. max_poll_reqs = maxreqs;
  491. if (WORDACCESS_UNSAFE) X_UNLOCK (reslock);
  492. }
  493. static void etp_set_max_idle (unsigned int nthreads)
  494. {
  495. if (WORDACCESS_UNSAFE) X_LOCK (reqlock);
  496. max_idle = nthreads <= 0 ? 1 : nthreads;
  497. if (WORDACCESS_UNSAFE) X_UNLOCK (reqlock);
  498. }
  499. static void etp_set_min_parallel (unsigned int nthreads)
  500. {
  501. if (wanted < nthreads)
  502. wanted = nthreads;
  503. }
  504. static void etp_set_max_parallel (unsigned int nthreads)
  505. {
  506. if (wanted > nthreads)
  507. wanted = nthreads;
  508. while (started > wanted)
  509. etp_end_thread ();
  510. }
  511. /*****************************************************************************/
  512. static void grp_try_feed (eio_req *grp)
  513. {
  514. while (grp->size < grp->int2 && !EIO_CANCELLED (grp))
  515. {
  516. grp->flags &= ~EIO_FLAG_GROUPADD;
  517. EIO_FEED (grp);
  518. /* stop if no progress has been made */
  519. if (!(grp->flags & EIO_FLAG_GROUPADD))
  520. {
  521. grp->feed = 0;
  522. break;
  523. }
  524. }
  525. }
  526. static int grp_dec (eio_req *grp)
  527. {
  528. --grp->size;
  529. /* call feeder, if applicable */
  530. grp_try_feed (grp);
  531. /* finish, if done */
  532. if (!grp->size && grp->int1)
  533. return eio_finish (grp);
  534. else
  535. return 0;
  536. }
  537. void eio_destroy (eio_req *req)
  538. {
  539. if ((req)->flags & EIO_FLAG_PTR1_FREE) free (req->ptr1);
  540. if ((req)->flags & EIO_FLAG_PTR2_FREE) free (req->ptr2);
  541. EIO_DESTROY (req);
  542. }
  543. static int eio_finish (eio_req *req)
  544. {
  545. int res = EIO_FINISH (req);
  546. if (req->grp)
  547. {
  548. int res2;
  549. eio_req *grp = req->grp;
  550. /* unlink request */
  551. if (req->grp_next) req->grp_next->grp_prev = req->grp_prev;
  552. if (req->grp_prev) req->grp_prev->grp_next = req->grp_next;
  553. if (grp->grp_first == req)
  554. grp->grp_first = req->grp_next;
  555. res2 = grp_dec (grp);
  556. if (!res && res2)
  557. res = res2;
  558. }
  559. eio_destroy (req);
  560. return res;
  561. }
  562. void eio_grp_cancel (eio_req *grp)
  563. {
  564. for (grp = grp->grp_first; grp; grp = grp->grp_next)
  565. eio_cancel (grp);
  566. }
  567. void eio_cancel (eio_req *req)
  568. {
  569. etp_cancel (req);
  570. }
  571. void eio_submit (eio_req *req)
  572. {
  573. etp_submit (req);
  574. }
  575. unsigned int eio_nreqs (void)
  576. {
  577. return etp_nreqs ();
  578. }
  579. unsigned int eio_nready (void)
  580. {
  581. return etp_nready ();
  582. }
  583. unsigned int eio_npending (void)
  584. {
  585. return etp_npending ();
  586. }
  587. unsigned int eio_nthreads (void)
  588. {
  589. return etp_nthreads ();
  590. }
  591. void eio_set_max_poll_time (double nseconds)
  592. {
  593. etp_set_max_poll_time (nseconds);
  594. }
  595. void eio_set_max_poll_reqs (unsigned int maxreqs)
  596. {
  597. etp_set_max_poll_reqs (maxreqs);
  598. }
  599. void eio_set_max_idle (unsigned int nthreads)
  600. {
  601. etp_set_max_idle (nthreads);
  602. }
  603. void eio_set_min_parallel (unsigned int nthreads)
  604. {
  605. etp_set_min_parallel (nthreads);
  606. }
  607. void eio_set_max_parallel (unsigned int nthreads)
  608. {
  609. etp_set_max_parallel (nthreads);
  610. }
  611. int eio_poll (void)
  612. {
  613. return etp_poll ();
  614. }
  615. /*****************************************************************************/
  616. /* work around various missing functions */
  617. #if !HAVE_PREADWRITE
  618. # undef pread
  619. # undef pwrite
  620. # define pread eio__pread
  621. # define pwrite eio__pwrite
  622. static ssize_t
  623. eio__pread (int fd, void *buf, size_t count, off_t offset)
  624. {
  625. ssize_t res;
  626. off_t ooffset;
  627. X_LOCK (preadwritelock);
  628. ooffset = lseek (fd, 0, SEEK_CUR);
  629. lseek (fd, offset, SEEK_SET);
  630. res = read (fd, buf, count);
  631. lseek (fd, ooffset, SEEK_SET);
  632. X_UNLOCK (preadwritelock);
  633. return res;
  634. }
  635. static ssize_t
  636. eio__pwrite (int fd, void *buf, size_t count, off_t offset)
  637. {
  638. ssize_t res;
  639. off_t ooffset;
  640. X_LOCK (preadwritelock);
  641. ooffset = lseek (fd, 0, SEEK_CUR);
  642. lseek (fd, offset, SEEK_SET);
  643. res = write (fd, buf, count);
  644. lseek (fd, ooffset, SEEK_SET);
  645. X_UNLOCK (preadwritelock);
  646. return res;
  647. }
  648. #endif
  649. #ifndef HAVE_UTIMES
  650. # undef utimes
  651. # define utimes(path,times) eio__utimes (path, times)
  652. static int
  653. eio__utimes (const char *filename, const struct timeval times[2])
  654. {
  655. if (times)
  656. {
  657. struct utimbuf buf;
  658. buf.actime = times[0].tv_sec;
  659. buf.modtime = times[1].tv_sec;
  660. return utime (filename, &buf);
  661. }
  662. else
  663. return utime (filename, 0);
  664. }
  665. #endif
  666. #ifndef HAVE_FUTIMES
  667. # undef futimes
  668. # define futimes(fd,times) eio__futimes (fd, times)
  669. static int eio__futimes (int fd, const struct timeval tv[2])
  670. {
  671. errno = ENOSYS;
  672. return -1;
  673. }
  674. #endif
  675. #if !HAVE_FDATASYNC
  676. # undef fdatasync
  677. # define fdatasync(fd) fsync (fd)
  678. #endif
  679. /* sync_file_range always needs emulation */
  680. int
  681. eio__sync_file_range (int fd, off_t offset, size_t nbytes, unsigned int flags)
  682. {
  683. #if HAVE_SYNC_FILE_RANGE
  684. int res;
  685. if (EIO_SYNC_FILE_RANGE_WAIT_BEFORE != SYNC_FILE_RANGE_WAIT_BEFORE
  686. || EIO_SYNC_FILE_RANGE_WRITE != SYNC_FILE_RANGE_WRITE
  687. || EIO_SYNC_FILE_RANGE_WAIT_AFTER != SYNC_FILE_RANGE_WAIT_AFTER)
  688. {
  689. flags = 0
  690. | (flags & EIO_SYNC_FILE_RANGE_WAIT_BEFORE ? SYNC_FILE_RANGE_WAIT_BEFORE : 0)
  691. | (flags & EIO_SYNC_FILE_RANGE_WRITE ? SYNC_FILE_RANGE_WRITE : 0)
  692. | (flags & EIO_SYNC_FILE_RANGE_WAIT_AFTER ? SYNC_FILE_RANGE_WAIT_AFTER : 0);
  693. }
  694. res = sync_file_range (fd, offset, nbytes, flags);
  695. if (!res || errno != ENOSYS)
  696. return res;
  697. #endif
  698. /* even though we could play tricks with the flags, it's better to always
  699. * call fdatasync, as that matches the expectation of its users best */
  700. return fdatasync (fd);
  701. }
  702. #if !HAVE_READAHEAD
  703. # undef readahead
  704. # define readahead(fd,offset,count) eio__readahead (fd, offset, count, self)
  705. static ssize_t
  706. eio__readahead (int fd, off_t offset, size_t count, etp_worker *self)
  707. {
  708. size_t todo = count;
  709. dBUF;
  710. while (todo > 0)
  711. {
  712. size_t len = todo < EIO_BUFSIZE ? todo : EIO_BUFSIZE;
  713. pread (fd, eio_buf, len, offset);
  714. offset += len;
  715. todo -= len;
  716. }
  717. errno = 0;
  718. return count;
  719. }
  720. #endif
  721. /* sendfile always needs emulation */
  722. static ssize_t
  723. eio__sendfile (int ofd, int ifd, off_t offset, size_t count, etp_worker *self)
  724. {
  725. ssize_t res;
  726. if (!count)
  727. return 0;
  728. #if HAVE_SENDFILE
  729. # if __linux
  730. res = sendfile (ofd, ifd, &offset, count);
  731. # elif __FreeBSD__
  732. /*
  733. * Of course, the freebsd sendfile is a dire hack with no thoughts
  734. * wasted on making it similar to other I/O functions.
  735. */
  736. {
  737. off_t sbytes;
  738. res = sendfile (ifd, ofd, offset, count, 0, &sbytes, 0);
  739. #if 0 /* according to the manpage, this is correct, but broken behaviour */
  740. /* freebsd' sendfile will return 0 on success */
  741. /* freebsd 8 documents it as only setting *sbytes on EINTR and EAGAIN, but */
  742. /* not on e.g. EIO or EPIPE - sounds broken */
  743. if ((res < 0 && (errno == EAGAIN || errno == EINTR) && sbytes) || res == 0)
  744. res = sbytes;
  745. #endif
  746. /* according to source inspection, this is correct, and useful behaviour */
  747. if (sbytes)
  748. res = sbytes;
  749. }
  750. # elif defined (__APPLE__)
  751. {
  752. off_t sbytes = count;
  753. res = sendfile (ifd, ofd, offset, &sbytes, 0, 0);
  754. /* according to the manpage, sbytes is always valid */
  755. if (sbytes)
  756. res = sbytes;
  757. }
  758. # elif __hpux
  759. res = sendfile (ofd, ifd, offset, count, 0, 0);
  760. # elif __solaris
  761. {
  762. struct sendfilevec vec;
  763. size_t sbytes;
  764. vec.sfv_fd = ifd;
  765. vec.sfv_flag = 0;
  766. vec.sfv_off = offset;
  767. vec.sfv_len = count;
  768. res = sendfilev (ofd, &vec, 1, &sbytes);
  769. if (res < 0 && sbytes)
  770. res = sbytes;
  771. }
  772. # endif
  773. #elif defined (_WIN32)
  774. /* does not work, just for documentation of what would need to be done */
  775. {
  776. HANDLE h = TO_SOCKET (ifd);
  777. SetFilePointer (h, offset, 0, FILE_BEGIN);
  778. res = TransmitFile (TO_SOCKET (ofd), h, count, 0, 0, 0, 0);
  779. }
  780. #else
  781. res = -1;
  782. errno = ENOSYS;
  783. #endif
  784. if (res < 0
  785. && (errno == ENOSYS || errno == EINVAL || errno == ENOTSOCK
  786. /* BSDs */
  787. #ifdef ENOTSUP /* sigh, if the steenking pile called openbsd would only try to at least compile posix code... */
  788. || errno == ENOTSUP
  789. #endif
  790. || errno == EOPNOTSUPP /* BSDs */
  791. #if __solaris
  792. || errno == EAFNOSUPPORT || errno == EPROTOTYPE
  793. #endif
  794. )
  795. )
  796. {
  797. /* emulate sendfile. this is a major pain in the ass */
  798. dBUF;
  799. res = 0;
  800. while (count)
  801. {
  802. ssize_t cnt;
  803. cnt = pread (ifd, eio_buf, count > EIO_BUFSIZE ? EIO_BUFSIZE : count, offset);
  804. if (cnt <= 0)
  805. {
  806. if (cnt && !res) res = -1;
  807. break;
  808. }
  809. cnt = write (ofd, eio_buf, cnt);
  810. if (cnt <= 0)
  811. {
  812. if (cnt && !res) res = -1;
  813. break;
  814. }
  815. offset += cnt;
  816. res += cnt;
  817. count -= cnt;
  818. }
  819. }
  820. return res;
  821. }
  822. static signed char
  823. eio_dent_cmp (const eio_dirent *a, const eio_dirent *b)
  824. {
  825. return a->score - b->score ? a->score - b->score /* works because our signed char is always 0..100 */
  826. : a->inode < b->inode ? -1 : a->inode > b->inode ? 1 : 0;
  827. }
  828. #define EIO_DENT_CMP(i,op,j) eio_dent_cmp (&i, &j) op 0
  829. #define EIO_SORT_CUTOFF 30 /* quite high, but performs well on many filesystems */
  830. #define EIO_SORT_FAST 60 /* when to only use insertion sort */
  831. static void
  832. eio_dent_radix_sort (eio_dirent *dents, int size, signed char score_bits, ino_t inode_bits)
  833. {
  834. unsigned char bits [9 + sizeof (ino_t) * 8];
  835. unsigned char *bit = bits;
  836. assert (CHAR_BIT == 8);
  837. assert (sizeof (eio_dirent) * 8 < 256);
  838. assert (offsetof (eio_dirent, inode)); /* we use 0 as sentinel */
  839. assert (offsetof (eio_dirent, score)); /* we use 0 as sentinel */
  840. if (size <= EIO_SORT_FAST)
  841. return;
  842. /* first prepare an array of bits to test in our radix sort */
  843. /* try to take endianness into account, as well as differences in ino_t sizes */
  844. /* inode_bits must contain all inodes ORed together */
  845. /* which is used to skip bits that are 0 everywhere, which is very common */
  846. {
  847. ino_t endianness;
  848. int i, j;
  849. /* we store the byte offset of byte n into byte n of "endianness" */
  850. for (i = 0; i < sizeof (ino_t); ++i)
  851. ((unsigned char *)&endianness)[i] = i;
  852. *bit++ = 0;
  853. for (i = 0; i < sizeof (ino_t); ++i)
  854. {
  855. /* shifting off the byte offsets out of "endianness" */
  856. int offs = (offsetof (eio_dirent, inode) + (endianness & 0xff)) * 8;
  857. endianness >>= 8;
  858. for (j = 0; j < 8; ++j)
  859. if (inode_bits & (((ino_t)1) << (i * 8 + j)))
  860. *bit++ = offs + j;
  861. }
  862. for (j = 0; j < 8; ++j)
  863. if (score_bits & (1 << j))
  864. *bit++ = offsetof (eio_dirent, score) * 8 + j;
  865. }
  866. /* now actually do the sorting (a variant of MSD radix sort) */
  867. {
  868. eio_dirent *base_stk [9 + sizeof (ino_t) * 8], *base;
  869. eio_dirent *end_stk [9 + sizeof (ino_t) * 8], *end;
  870. unsigned char *bit_stk [9 + sizeof (ino_t) * 8];
  871. int stk_idx = 0;
  872. base_stk [stk_idx] = dents;
  873. end_stk [stk_idx] = dents + size;
  874. bit_stk [stk_idx] = bit - 1;
  875. do
  876. {
  877. base = base_stk [stk_idx];
  878. end = end_stk [stk_idx];
  879. bit = bit_stk [stk_idx];
  880. for (;;)
  881. {
  882. unsigned char O = *bit >> 3;
  883. unsigned char M = 1 << (*bit & 7);
  884. eio_dirent *a = base;
  885. eio_dirent *b = end;
  886. if (b - a < EIO_SORT_CUTOFF)
  887. break;
  888. /* now bit-partition the array on the bit */
  889. /* this ugly asymmetric loop seems to perform much better than typical */
  890. /* partition algos found in the literature */
  891. do
  892. if (!(((unsigned char *)a)[O] & M))
  893. ++a;
  894. else if (!(((unsigned char *)--b)[O] & M))
  895. {
  896. eio_dirent tmp = *a; *a = *b; *b = tmp;
  897. ++a;
  898. }
  899. while (b > a);
  900. /* next bit, or stop, if no bits left in this path */
  901. if (!*--bit)
  902. break;
  903. base_stk [stk_idx] = a;
  904. end_stk [stk_idx] = end;
  905. bit_stk [stk_idx] = bit;
  906. ++stk_idx;
  907. end = a;
  908. }
  909. }
  910. while (stk_idx--);
  911. }
  912. }
  913. static void
  914. eio_dent_insertion_sort (eio_dirent *dents, int size)
  915. {
  916. /* first move the smallest element to the front, to act as a sentinel */
  917. {
  918. int i;
  919. eio_dirent *min = dents;
  920. /* the radix pre-pass ensures that the minimum element is in the first EIO_SORT_CUTOFF + 1 elements */
  921. for (i = size > EIO_SORT_FAST ? EIO_SORT_CUTOFF + 1 : size; --i; )
  922. if (EIO_DENT_CMP (dents [i], <, *min))
  923. min = &dents [i];
  924. /* swap elements 0 and j (minimum) */
  925. {
  926. eio_dirent tmp = *dents; *dents = *min; *min = tmp;
  927. }
  928. }
  929. /* then do standard insertion sort, assuming that all elements are >= dents [0] */
  930. {
  931. eio_dirent *i, *j;
  932. for (i = dents + 1; i < dents + size; ++i)
  933. {
  934. eio_dirent value = *i;
  935. for (j = i - 1; EIO_DENT_CMP (*j, >, value); --j)
  936. j [1] = j [0];
  937. j [1] = value;
  938. }
  939. }
  940. }
  941. static void
  942. eio_dent_sort (eio_dirent *dents, int size, signed char score_bits, ino_t inode_bits)
  943. {
  944. if (size <= 1)
  945. return; /* our insertion sort relies on size > 0 */
  946. /* first we use a radix sort, but only for dirs >= EIO_SORT_FAST */
  947. /* and stop sorting when the partitions are <= EIO_SORT_CUTOFF */
  948. eio_dent_radix_sort (dents, size, score_bits, inode_bits);
  949. /* use an insertion sort at the end, or for small arrays, */
  950. /* as insertion sort is more efficient for small partitions */
  951. eio_dent_insertion_sort (dents, size);
  952. }
  953. /* read a full directory */
  954. static void
  955. eio__scandir (eio_req *req, etp_worker *self)
  956. {
  957. DIR *dirp;
  958. EIO_STRUCT_DIRENT *entp;
  959. char *name, *names;
  960. int namesalloc = 4096;
  961. int namesoffs = 0;
  962. int flags = req->int1;
  963. eio_dirent *dents = 0;
  964. int dentalloc = 128;
  965. int dentoffs = 0;
  966. ino_t inode_bits = 0;
  967. req->result = -1;
  968. if (!(flags & EIO_READDIR_DENTS))
  969. flags &= ~(EIO_READDIR_DIRS_FIRST | EIO_READDIR_STAT_ORDER);
  970. X_LOCK (wrklock);
  971. /* the corresponding closedir is in ETP_WORKER_CLEAR */
  972. self->dirp = dirp = opendir (req->ptr1);
  973. req->flags |= EIO_FLAG_PTR1_FREE | EIO_FLAG_PTR2_FREE;
  974. req->ptr1 = dents = flags ? malloc (dentalloc * sizeof (eio_dirent)) : 0;
  975. req->ptr2 = names = malloc (namesalloc);
  976. X_UNLOCK (wrklock);
  977. if (dirp && names && (!flags || dents))
  978. for (;;)
  979. {
  980. errno = 0;
  981. entp = readdir (dirp);
  982. if (!entp)
  983. {
  984. if (errno)
  985. break;
  986. /* sort etc. */
  987. req->int1 = flags;
  988. req->result = dentoffs;
  989. if (flags & EIO_READDIR_STAT_ORDER)
  990. eio_dent_sort (dents, dentoffs, 0, inode_bits); /* sort by inode exclusively */
  991. else if (flags & EIO_READDIR_DIRS_FIRST)
  992. if (flags & EIO_READDIR_FOUND_UNKNOWN)
  993. eio_dent_sort (dents, dentoffs, 7, inode_bits); /* sort by score and inode */
  994. else
  995. {
  996. /* in this case, all is known, and we just put dirs first and sort them */
  997. eio_dirent *oth = dents + dentoffs;
  998. eio_dirent *dir = dents;
  999. /* now partition dirs to the front, and non-dirs to the back */
  1000. /* by walking from both sides and swapping if necessary */
  1001. /* also clear score, so it doesn't influence sorting */
  1002. while (oth > dir)
  1003. {
  1004. if (dir->type == EIO_DT_DIR)
  1005. ++dir;
  1006. else if ((--oth)->type == EIO_DT_DIR)
  1007. {
  1008. eio_dirent tmp = *dir; *dir = *oth; *oth = tmp;
  1009. ++dir;
  1010. }
  1011. }
  1012. /* now sort the dirs only */
  1013. eio_dent_sort (dents, dir - dents, 0, inode_bits);
  1014. }
  1015. break;
  1016. }
  1017. /* now add the entry to our list(s) */
  1018. name = entp->d_name;
  1019. /* skip . and .. entries */
  1020. if (name [0] != '.' || (name [1] && (name [1] != '.' || name [2])))
  1021. {
  1022. int len = D_NAMLEN (entp) + 1;
  1023. while (expect_false (namesoffs + len > namesalloc))
  1024. {
  1025. namesalloc *= 2;
  1026. X_LOCK (wrklock);
  1027. req->ptr2 = names = realloc (names, namesalloc);
  1028. X_UNLOCK (wrklock);
  1029. if (!names)
  1030. break;
  1031. }
  1032. memcpy (names + namesoffs, name, len);
  1033. if (dents)
  1034. {
  1035. struct eio_dirent *ent;
  1036. if (expect_false (dentoffs == dentalloc))
  1037. {
  1038. dentalloc *= 2;
  1039. X_LOCK (wrklock);
  1040. req->ptr1 = dents = realloc (dents, dentalloc * sizeof (eio_dirent));
  1041. X_UNLOCK (wrklock);
  1042. if (!dents)
  1043. break;
  1044. }
  1045. ent = dents + dentoffs;
  1046. ent->nameofs = namesoffs; /* rather dirtily we store the offset in the pointer */
  1047. ent->namelen = len - 1;
  1048. ent->inode = D_INO (entp);
  1049. inode_bits |= ent->inode;
  1050. switch (D_TYPE (entp))
  1051. {
  1052. default:
  1053. ent->type = EIO_DT_UNKNOWN;
  1054. flags |= EIO_READDIR_FOUND_UNKNOWN;
  1055. break;
  1056. #ifdef DT_FIFO
  1057. case DT_FIFO: ent->type = EIO_DT_FIFO; break;
  1058. #endif
  1059. #ifdef DT_CHR
  1060. case DT_CHR: ent->type = EIO_DT_CHR; break;
  1061. #endif
  1062. #ifdef DT_MPC
  1063. case DT_MPC: ent->type = EIO_DT_MPC; break;
  1064. #endif
  1065. #ifdef DT_DIR
  1066. case DT_DIR: ent->type = EIO_DT_DIR; break;
  1067. #endif
  1068. #ifdef DT_NAM
  1069. case DT_NAM: ent->type = EIO_DT_NAM; break;
  1070. #endif
  1071. #ifdef DT_BLK
  1072. case DT_BLK: ent->type = EIO_DT_BLK; break;
  1073. #endif
  1074. #ifdef DT_MPB
  1075. case DT_MPB: ent->type = EIO_DT_MPB; break;
  1076. #endif
  1077. #ifdef DT_REG
  1078. case DT_REG: ent->type = EIO_DT_REG; break;
  1079. #endif
  1080. #ifdef DT_NWK
  1081. case DT_NWK: ent->type = EIO_DT_NWK; break;
  1082. #endif
  1083. #ifdef DT_CMP
  1084. case DT_CMP: ent->type = EIO_DT_CMP; break;
  1085. #endif
  1086. #ifdef DT_LNK
  1087. case DT_LNK: ent->type = EIO_DT_LNK; break;
  1088. #endif
  1089. #ifdef DT_SOCK
  1090. case DT_SOCK: ent->type = EIO_DT_SOCK; break;
  1091. #endif
  1092. #ifdef DT_DOOR
  1093. case DT_DOOR: ent->type = EIO_DT_DOOR; break;
  1094. #endif
  1095. #ifdef DT_WHT
  1096. case DT_WHT: ent->type = EIO_DT_WHT; break;
  1097. #endif
  1098. }
  1099. ent->score = 7;
  1100. if (flags & EIO_READDIR_DIRS_FIRST)
  1101. {
  1102. if (ent->type == EIO_DT_UNKNOWN)
  1103. {
  1104. if (*name == '.') /* leading dots are likely directories, and, in any case, rare */
  1105. ent->score = 1;
  1106. else if (!strchr (name, '.')) /* absense of dots indicate likely dirs */
  1107. ent->score = len <= 2 ? 4 - len : len <= 4 ? 4 : len <= 7 ? 5 : 6; /* shorter == more likely dir, but avoid too many classes */
  1108. }
  1109. else if (ent->type == EIO_DT_DIR)
  1110. ent->score = 0;
  1111. }
  1112. }
  1113. namesoffs += len;
  1114. ++dentoffs;
  1115. }
  1116. if (EIO_CANCELLED (req))
  1117. {
  1118. errno = ECANCELED;
  1119. break;
  1120. }
  1121. }
  1122. }
  1123. #ifdef PAGESIZE
  1124. # define eio_pagesize() PAGESIZE
  1125. #else
  1126. static intptr_t
  1127. eio_pagesize (void)
  1128. {
  1129. static intptr_t page;
  1130. if (!page)
  1131. page = sysconf (_SC_PAGESIZE);
  1132. return page;
  1133. }
  1134. #endif
  1135. static void
  1136. eio_page_align (void **addr, size_t *length)
  1137. {
  1138. intptr_t mask = eio_pagesize () - 1;
  1139. /* round down addr */
  1140. intptr_t adj = mask & (intptr_t)*addr;
  1141. *addr = (void *)((intptr_t)*addr - adj);
  1142. *length += adj;
  1143. /* round up length */
  1144. *length = (*length + mask) & ~mask;
  1145. }
  1146. #if !_POSIX_MEMLOCK
  1147. # define eio__mlockall(a) ((errno = ENOSYS), -1)
  1148. #else
  1149. static int
  1150. eio__mlockall (int flags)
  1151. {
  1152. #if __GLIBC__ == 2 && __GLIBC_MINOR__ <= 7
  1153. extern int mallopt (int, int);
  1154. mallopt (-6, 238); /* http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=473812 */
  1155. #endif
  1156. if (EIO_MCL_CURRENT != MCL_CURRENT
  1157. || EIO_MCL_FUTURE != MCL_FUTURE)
  1158. {
  1159. flags = 0
  1160. | (flags & EIO_MCL_CURRENT ? MCL_CURRENT : 0)
  1161. | (flags & EIO_MCL_FUTURE ? MCL_FUTURE : 0);
  1162. }
  1163. return mlockall (flags);
  1164. }
  1165. #endif
  1166. #if !_POSIX_MEMLOCK_RANGE
  1167. # define eio__mlock(a,b) ((errno = ENOSYS), -1)
  1168. #else
  1169. static int
  1170. eio__mlock (void *addr, size_t length)
  1171. {
  1172. eio_page_align (&addr, &length);
  1173. return mlock (addr, length);
  1174. }
  1175. #endif
  1176. #if !(_POSIX_MAPPED_FILES && _POSIX_SYNCHRONIZED_IO)
  1177. # define eio__msync(a,b,c) ((errno = ENOSYS), -1)
  1178. #else
  1179. int
  1180. eio__msync (void *mem, size_t len, int flags)
  1181. {
  1182. eio_page_align (&mem, &len);
  1183. if (EIO_MS_ASYNC != MS_SYNC
  1184. || EIO_MS_INVALIDATE != MS_INVALIDATE
  1185. || EIO_MS_SYNC != MS_SYNC)
  1186. {
  1187. flags = 0
  1188. | (flags & EIO_MS_ASYNC ? MS_ASYNC : 0)
  1189. | (flags & EIO_MS_INVALIDATE ? MS_INVALIDATE : 0)
  1190. | (flags & EIO_MS_SYNC ? MS_SYNC : 0);
  1191. }
  1192. return msync (mem, len, flags);
  1193. }
  1194. #endif
  1195. int
  1196. eio__mtouch (void *mem, size_t len, int flags)
  1197. {
  1198. eio_page_align (&mem, &len);
  1199. {
  1200. intptr_t addr = (intptr_t)mem;
  1201. intptr_t end = addr + len;
  1202. intptr_t page = eio_pagesize ();
  1203. if (addr < end)
  1204. if (flags & EIO_MT_MODIFY) /* modify */
  1205. do { *((volatile sig_atomic_t *)addr) |= 0; } while ((addr += page) < len);
  1206. else
  1207. do { *((volatile sig_atomic_t *)addr) ; } while ((addr += page) < len);
  1208. }
  1209. return 0;
  1210. }
  1211. /*****************************************************************************/
  1212. #define ALLOC(len) \
  1213. if (!req->ptr2) \
  1214. { \
  1215. X_LOCK (wrklock); \
  1216. req->flags |= EIO_FLAG_PTR2_FREE; \
  1217. X_UNLOCK (wrklock); \
  1218. req->ptr2 = malloc (len); \
  1219. if (!req->ptr2) \
  1220. { \
  1221. errno = ENOMEM; \
  1222. req->result = -1; \
  1223. break; \
  1224. } \
  1225. }
  1226. X_THREAD_PROC (etp_proc)
  1227. {
  1228. ETP_REQ *req;
  1229. struct timespec ts;
  1230. etp_worker *self = (etp_worker *)thr_arg;
  1231. /* try to distribute timeouts somewhat randomly */
  1232. ts.tv_nsec = ((unsigned long)self & 1023UL) * (1000000000UL / 1024UL);
  1233. for (;;)
  1234. {
  1235. X_LOCK (reqlock);
  1236. for (;;)
  1237. {
  1238. self->req = req = reqq_shift (&req_queue);
  1239. if (req)
  1240. break;
  1241. ++idle;
  1242. ts.tv_sec = time (0) + IDLE_TIMEOUT;
  1243. if (X_COND_TIMEDWAIT (reqwait, reqlock, ts) == ETIMEDOUT)
  1244. {
  1245. if (idle > max_idle)
  1246. {
  1247. --idle;
  1248. X_UNLOCK (reqlock);
  1249. X_LOCK (wrklock);
  1250. --started;
  1251. X_UNLOCK (wrklock);
  1252. goto quit;
  1253. }
  1254. /* we are allowed to idle, so do so without any timeout */
  1255. X_COND_WAIT (reqwait, reqlock);
  1256. }
  1257. --idle;
  1258. }
  1259. --nready;
  1260. X_UNLOCK (reqlock);
  1261. if (req->type < 0)
  1262. goto quit;
  1263. if (!EIO_CANCELLED (req))
  1264. ETP_EXECUTE (self, req);
  1265. X_LOCK (reslock);
  1266. ++npending;
  1267. if (!reqq_push (&res_queue, req) && want_poll_cb)
  1268. want_poll_cb ();
  1269. self->req = 0;
  1270. etp_worker_clear (self);
  1271. X_UNLOCK (reslock);
  1272. }
  1273. quit:
  1274. X_LOCK (wrklock);
  1275. etp_worker_free (self);
  1276. X_UNLOCK (wrklock);
  1277. return 0;
  1278. }
  1279. /*****************************************************************************/
  1280. int eio_init (void (*want_poll)(void), void (*done_poll)(void))
  1281. {
  1282. return etp_init (want_poll, done_poll);
  1283. }
  1284. static void eio_api_destroy (eio_req *req)
  1285. {
  1286. free (req);
  1287. }
  1288. #define REQ(rtype) \
  1289. eio_req *req; \
  1290. \
  1291. req = (eio_req *)calloc (1, sizeof *req); \
  1292. if (!req) \
  1293. return 0; \
  1294. \
  1295. req->type = rtype; \
  1296. req->pri = pri; \
  1297. req->finish = cb; \
  1298. req->data = data; \
  1299. req->destroy = eio_api_destroy;
  1300. #define SEND eio_submit (req); return req
  1301. #define PATH \
  1302. req->flags |= EIO_FLAG_PTR1_FREE; \
  1303. req->ptr1 = strdup (path); \
  1304. if (!req->ptr1) \
  1305. { \
  1306. eio_api_destroy (req); \
  1307. return 0; \
  1308. }
  1309. static void eio_execute (etp_worker *self, eio_req *req)
  1310. {
  1311. switch (req->type)
  1312. {
  1313. case EIO_READ: ALLOC (req->size);
  1314. req->result = req->offs >= 0
  1315. ? pread (req->int1, req->ptr2, req->size, req->offs)
  1316. : read (req->int1, req->ptr2, req->size); break;
  1317. case EIO_WRITE: req->result = req->offs >= 0
  1318. ? pwrite (req->int1, req->ptr2, req->size, req->offs)
  1319. : write (req->int1, req->ptr2, req->size); break;
  1320. case EIO_READAHEAD: req->result = readahead (req->int1, req->offs, req->size); break;
  1321. case EIO_SENDFILE: req->result = eio__sendfile (req->int1, req->int2, req->offs, req->size, self); break;
  1322. case EIO_STAT: ALLOC (sizeof (EIO_STRUCT_STAT));
  1323. req->result = stat (req->ptr1, (EIO_STRUCT_STAT *)req->ptr2); break;
  1324. case EIO_LSTAT: ALLOC (sizeof (EIO_STRUCT_STAT));
  1325. req->result = lstat (req->ptr1, (EIO_STRUCT_STAT *)req->ptr2); break;
  1326. case EIO_FSTAT: ALLOC (sizeof (EIO_STRUCT_STAT));
  1327. req->result = fstat (req->int1, (EIO_STRUCT_STAT *)req->ptr2); break;
  1328. case EIO_STATVFS: ALLOC (sizeof (EIO_STRUCT_STATVFS));
  1329. req->result = statvfs (req->ptr1, (EIO_STRUCT_STATVFS *)req->ptr2); break;
  1330. case EIO_FSTATVFS: ALLOC (sizeof (EIO_STRUCT_STATVFS));
  1331. req->result = fstatvfs (req->int1, (EIO_STRUCT_STATVFS *)req->ptr2); break;
  1332. case EIO_CHOWN: req->result = chown (req->ptr1, req->int2, req->int3); break;
  1333. case EIO_FCHOWN: req->result = fchown (req->int1, req->int2, req->int3); break;
  1334. case EIO_CHMOD: req->result = chmod (req->ptr1, (mode_t)req->int2); break;
  1335. case EIO_FCHMOD: req->result = fchmod (req->int1, (mode_t)req->int2); break;
  1336. case EIO_TRUNCATE: req->result = truncate (req->ptr1, req->offs); break;
  1337. case EIO_FTRUNCATE: req->result = ftruncate (req->int1, req->offs); break;
  1338. case EIO_OPEN: req->result = open (req->ptr1, req->int1, (mode_t)req->int2); break;
  1339. case EIO_CLOSE: req->result = close (req->int1); break;
  1340. case EIO_DUP2: req->result = dup2 (req->int1, req->int2); break;
  1341. case EIO_UNLINK: req->result = unlink (req->ptr1); break;
  1342. case EIO_RMDIR: req->result = rmdir (req->ptr1); break;
  1343. case EIO_MKDIR: req->result = mkdir (req->ptr1, (mode_t)req->int2); break;
  1344. case EIO_RENAME: req->result = rename (req->ptr1, req->ptr2); break;
  1345. case EIO_LINK: req->result = link (req->ptr1, req->ptr2); break;
  1346. case EIO_SYMLINK: req->result = symlink (req->ptr1, req->ptr2); break;
  1347. case EIO_MKNOD: req->result = mknod (req->ptr1, (mode_t)req->int2, (dev_t)req->int3); break;
  1348. case EIO_READLINK: ALLOC (PATH_MAX);
  1349. req->result = readlink (req->ptr1, req->ptr2, PATH_MAX); break;
  1350. case EIO_SYNC: req->result = 0; sync (); break;
  1351. case EIO_FSYNC: req->result = fsync (req->int1); break;
  1352. case EIO_FDATASYNC: req->result = fdatasync (req->int1); break;
  1353. case EIO_MSYNC: req->result = eio__msync (req->ptr2, req->size, req->int1); break;
  1354. case EIO_MTOUCH: req->result = eio__mtouch (req->ptr2, req->size, req->int1); break;
  1355. case EIO_MLOCK: req->result = eio__mlock (req->ptr2, req->size); break;
  1356. case EIO_MLOCKALL: req->result = eio__mlockall (req->int1); break;
  1357. case EIO_SYNC_FILE_RANGE: req->result = eio__sync_file_range (req->int1, req->offs, req->size, req->int2); break;
  1358. case EIO_READDIR: eio__scandir (req, self); break;
  1359. case EIO_BUSY:
  1360. #ifdef _WIN32
  1361. Sleep (req->nv1 * 1e3);
  1362. #else
  1363. {
  1364. struct timeval tv;
  1365. tv.tv_sec = req->nv1;
  1366. tv.tv_usec = (req->nv1 - tv.tv_sec) * 1e6;
  1367. req->result = select (0, 0, 0, 0, &tv);
  1368. }
  1369. #endif
  1370. break;
  1371. case EIO_UTIME:
  1372. case EIO_FUTIME:
  1373. {
  1374. struct timeval tv[2];
  1375. struct timeval *times;
  1376. if (req->nv1 != -1. || req->nv2 != -1.)
  1377. {
  1378. tv[0].tv_sec = req->nv1;
  1379. tv[0].tv_usec = (req->nv1 - tv[0].tv_sec) * 1000000.;
  1380. tv[1].tv_sec = req->nv2;
  1381. tv[1].tv_usec = (req->nv2 - tv[1].tv_sec) * 1000000.;
  1382. times = tv;
  1383. }
  1384. else
  1385. times = 0;
  1386. req->result = req->type == EIO_FUTIME
  1387. ? futimes (req->int1, times)
  1388. : utimes (req->ptr1, times);
  1389. }
  1390. break;
  1391. case EIO_GROUP:
  1392. abort (); /* handled in eio_request */
  1393. case EIO_NOP:
  1394. req->result = 0;
  1395. break;
  1396. case EIO_CUSTOM:
  1397. ((void (*)(eio_req *))req->feed) (req);
  1398. break;
  1399. default:
  1400. errno = ENOSYS;
  1401. req->result = -1;
  1402. break;
  1403. }
  1404. req->errorno = errno;
  1405. }
  1406. #ifndef EIO_NO_WRAPPERS
  1407. eio_req *eio_nop (int pri, eio_cb cb, void *data)
  1408. {
  1409. REQ (EIO_NOP); SEND;
  1410. }
  1411. eio_req *eio_busy (double delay, int pri, eio_cb cb, void *data)
  1412. {
  1413. REQ (EIO_BUSY); req->nv1 = delay; SEND;
  1414. }
  1415. eio_req *eio_sync (int pri, eio_cb cb, void *data)
  1416. {
  1417. REQ (EIO_SYNC); SEND;
  1418. }
  1419. eio_req *eio_fsync (int fd, int pri, eio_cb cb, void *data)
  1420. {
  1421. REQ (EIO_FSYNC); req->int1 = fd; SEND;
  1422. }
  1423. eio_req *eio_msync (void *addr, size_t length, int flags, int pri, eio_cb cb, void *data)
  1424. {
  1425. REQ (EIO_MSYNC); req->ptr2 = addr; req->size = length; req->int1 = flags; SEND;
  1426. }
  1427. eio_req *eio_mtouch (void *addr, size_t length, int flags, int pri, eio_cb cb, void *data)
  1428. {
  1429. REQ (EIO_MTOUCH); req->ptr2 = addr; req->size = length; req->int1 = flags; SEND;
  1430. }
  1431. eio_req *eio_mlock (void *addr, size_t length, int pri, eio_cb cb, void *data)
  1432. {
  1433. REQ (EIO_MLOCK); req->ptr2 = addr; req->size = length; SEND;
  1434. }
  1435. eio_req *eio_mlockall (int flags, int pri, eio_cb cb, void *data)
  1436. {
  1437. REQ (EIO_MLOCKALL); req->int1 = flags; SEND;
  1438. }
  1439. eio_req *eio_sync_file_range (int fd, off_t offset, size_t nbytes, unsigned int flags, int pri, eio_cb cb, void *data)
  1440. {
  1441. REQ (EIO_SYNC_FILE_RANGE); req->int1 = fd; req->offs = offset; req->size = nbytes; req->int2 = flags; SEND;
  1442. }
  1443. eio_req *eio_fdatasync (int fd, int pri, eio_cb cb, void *data)
  1444. {
  1445. REQ (EIO_FDATASYNC); req->int1 = fd; SEND;
  1446. }
  1447. eio_req *eio_close (int fd, int pri, eio_cb cb, void *data)
  1448. {
  1449. REQ (EIO_CLOSE); req->int1 = fd; SEND;
  1450. }
  1451. eio_req *eio_readahead (int fd, off_t offset, size_t length, int pri, eio_cb cb, void *data)
  1452. {
  1453. REQ (EIO_READAHEAD); req->int1 = fd; req->offs = offset; req->size = length; SEND;
  1454. }
  1455. eio_req *eio_read (int fd, void *buf, size_t length, off_t offset, int pri, eio_cb cb, void *data)
  1456. {
  1457. REQ (EIO_READ); req->int1 = fd; req->offs = offset; req->size = length; req->ptr2 = buf; SEND;
  1458. }
  1459. eio_req *eio_write (int fd, void *buf, size_t length, off_t offset, int pri, eio_cb cb, void *data)
  1460. {
  1461. REQ (EIO_WRITE); req->int1 = fd; req->offs = offset; req->size = length; req->ptr2 = buf; SEND;
  1462. }
  1463. eio_req *eio_fstat (int fd, int pri, eio_cb cb, void *data)
  1464. {
  1465. REQ (EIO_FSTAT); req->int1 = fd; SEND;
  1466. }
  1467. eio_req *eio_fstatvfs (int fd, int pri, eio_cb cb, void *data)
  1468. {
  1469. REQ (EIO_FSTATVFS); req->int1 = fd; SEND;
  1470. }
  1471. eio_req *eio_futime (int fd, double atime, double mtime, int pri, eio_cb cb, void *data)
  1472. {
  1473. REQ (EIO_FUTIME); req->int1 = fd; req->nv1 = atime; req->nv2 = mtime; SEND;
  1474. }
  1475. eio_req *eio_ftruncate (int fd, off_t offset, int pri, eio_cb cb, void *data)
  1476. {
  1477. REQ (EIO_FTRUNCATE); req->int1 = fd; req->offs = offset; SEND;
  1478. }
  1479. eio_req *eio_fchmod (int fd, mode_t mode, int pri, eio_cb cb, void *data)
  1480. {
  1481. REQ (EIO_FCHMOD); req->int1 = fd; req->int2 = (long)mode; SEND;
  1482. }
  1483. eio_req *eio_fchown (int fd, uid_t uid, gid_t gid, int pri, eio_cb cb, void *data)
  1484. {
  1485. REQ (EIO_FCHOWN); req->int1 = fd; req->int2 = (long)uid; req->int3 = (long)gid; SEND;
  1486. }
  1487. eio_req *eio_dup2 (int fd, int fd2, int pri, eio_cb cb, void *data)
  1488. {
  1489. REQ (EIO_DUP2); req->int1 = fd; req->int2 = fd2; SEND;
  1490. }
  1491. eio_req *eio_sendfile (int out_fd, int in_fd, off_t in_offset, size_t length, int pri, eio_cb cb, void *data)
  1492. {
  1493. REQ (EIO_SENDFILE); req->int1 = out_fd; req->int2 = in_fd; req->offs = in_offset; req->size = length; SEND;
  1494. }
  1495. eio_req *eio_open (const char *path, int flags, mode_t mode, int pri, eio_cb cb, void *data)
  1496. {
  1497. REQ (EIO_OPEN); PATH; req->int1 = flags; req->int2 = (long)mode; SEND;
  1498. }
  1499. eio_req *eio_utime (const char *path, double atime, double mtime, int pri, eio_cb cb, void *data)
  1500. {
  1501. REQ (EIO_UTIME); PATH; req->nv1 = atime; req->nv2 = mtime; SEND;
  1502. }
  1503. eio_req *eio_truncate (const char *path, off_t offset, int pri, eio_cb cb, void *data)
  1504. {
  1505. REQ (EIO_TRUNCATE); PATH; req->offs = offset; SEND;
  1506. }
  1507. eio_req *eio_chown (const char *path, uid_t uid, gid_t gid, int pri, eio_cb cb, void *data)
  1508. {
  1509. REQ (EIO_CHOWN); PATH; req->int2 = (long)uid; req->int3 = (long)gid; SEND;
  1510. }
  1511. eio_req *eio_chmod (const char *path, mode_t mode, int pri, eio_cb cb, void *data)
  1512. {
  1513. REQ (EIO_CHMOD); PATH; req->int2 = (long)mode; SEND;
  1514. }
  1515. eio_req *eio_mkdir (const char *path, mode_t mode, int pri, eio_cb cb, void *data)
  1516. {
  1517. REQ (EIO_MKDIR); PATH; req->int2 = (long)mode; SEND;
  1518. }
  1519. static eio_req *
  1520. eio__1path (int type, const char *path, int pri, eio_cb cb, void *data)
  1521. {
  1522. REQ (type); PATH; SEND;
  1523. }
  1524. eio_req *eio_readlink (const char *path, int pri, eio_cb cb, void *data)
  1525. {
  1526. return eio__1path (EIO_READLINK, path, pri, cb, data);
  1527. }
  1528. eio_req *eio_stat (const char *path, int pri, eio_cb cb, void *data)
  1529. {
  1530. return eio__1path (EIO_STAT, path, pri, cb, data);
  1531. }
  1532. eio_req *eio_lstat (const char *path, int pri, eio_cb cb, void *data)
  1533. {
  1534. return eio__1path (EIO_LSTAT, path, pri, cb, data);
  1535. }
  1536. eio_req *eio_statvfs (const char *path, int pri, eio_cb cb, void *data)
  1537. {
  1538. return eio__1path (EIO_STATVFS, path, pri, cb, data);
  1539. }
  1540. eio_req *eio_unlink (const char *path, int pri, eio_cb cb, void *data)
  1541. {
  1542. return eio__1path (EIO_UNLINK, path, pri, cb, data);
  1543. }
  1544. eio_req *eio_rmdir (const char *path, int pri, eio_cb cb, void *data)
  1545. {
  1546. return eio__1path (EIO_RMDIR, path, pri, cb, data);
  1547. }
  1548. eio_req *eio_readdir (const char *path, int flags, int pri, eio_cb cb, void *data)
  1549. {
  1550. REQ (EIO_READDIR); PATH; req->int1 = flags; SEND;
  1551. }
  1552. eio_req *eio_mknod (const char *path, mode_t mode, dev_t dev, int pri, eio_cb cb, void *data)
  1553. {
  1554. REQ (EIO_MKNOD); PATH; req->int2 = (long)mode; req->int3 = (long)dev; SEND;
  1555. }
  1556. static eio_req *
  1557. eio__2path (int type, const char *path, const char *new_path, int pri, eio_cb cb, void *data)
  1558. {
  1559. REQ (type); PATH;
  1560. req->flags |= EIO_FLAG_PTR2_FREE;
  1561. req->ptr2 = strdup (new_path);
  1562. if (!req->ptr2)
  1563. {
  1564. eio_api_destroy (req);
  1565. return 0;
  1566. }
  1567. SEND;
  1568. }
  1569. eio_req *eio_link (const char *path, const char *new_path, int pri, eio_cb cb, void *data)
  1570. {
  1571. return eio__2path (EIO_LINK, path, new_path, pri, cb, data);
  1572. }
  1573. eio_req *eio_symlink (const char *path, const char *new_path, int pri, eio_cb cb, void *data)
  1574. {
  1575. return eio__2path (EIO_SYMLINK, path, new_path, pri, cb, data);
  1576. }
  1577. eio_req *eio_rename (const char *path, const char *new_path, int pri, eio_cb cb, void *data)
  1578. {
  1579. return eio__2path (EIO_RENAME, path, new_path, pri, cb, data);
  1580. }
  1581. eio_req *eio_custom (eio_cb execute, int pri, eio_cb cb, void *data)
  1582. {
  1583. REQ (EIO_CUSTOM); req->feed = (void (*)(eio_req *))execute; SEND;
  1584. }
  1585. #endif
  1586. eio_req *eio_grp (eio_cb cb, void *data)
  1587. {
  1588. const int pri = EIO_PRI_MAX;
  1589. REQ (EIO_GROUP); SEND;
  1590. }
  1591. #undef REQ
  1592. #undef PATH
  1593. #undef SEND
  1594. /*****************************************************************************/
  1595. /* grp functions */
  1596. void eio_grp_feed (eio_req *grp, void (*feed)(eio_req *req), int limit)
  1597. {
  1598. grp->int2 = limit;
  1599. grp->feed = feed;
  1600. grp_try_feed (grp);
  1601. }
  1602. void eio_grp_limit (eio_req *grp, int limit)
  1603. {
  1604. grp->int2 = limit;
  1605. grp_try_feed (grp);
  1606. }
  1607. void eio_grp_add (eio_req *grp, eio_req *req)
  1608. {
  1609. assert (("cannot add requests to IO::AIO::GRP after the group finished", grp->int1 != 2));
  1610. grp->flags |= EIO_FLAG_GROUPADD;
  1611. ++grp->size;
  1612. req->grp = grp;
  1613. req->grp_prev = 0;
  1614. req->grp_next = grp->grp_first;
  1615. if (grp->grp_first)
  1616. grp->grp_first->grp_prev = req;
  1617. grp->grp_first = req;
  1618. }
  1619. /*****************************************************************************/
  1620. /* misc garbage */
  1621. ssize_t eio_sendfile_sync (int ofd, int ifd, off_t offset, size_t count)
  1622. {
  1623. etp_worker wrk;
  1624. ssize_t ret;
  1625. wrk.dbuf = 0;
  1626. ret = eio__sendfile (ofd, ifd, offset, count, &wrk);
  1627. if (wrk.dbuf)
  1628. free (wrk.dbuf);
  1629. return ret;
  1630. }