2 * Copyright (c)1996-2002 by Hartmut Brandt
5 * Author: Hartmut Brandt
7 * Redistribution of this software and documentation and use in source and
8 * binary forms, with or without modification, are permitted provided that
9 * the following conditions are met:
11 * 1. Redistributions of source code or documentation must retain the above
12 * copyright notice, this list of conditions and the following disclaimer.
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.
17 * THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE AUTHOR
18 * AND ITS CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
19 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21 * THE AUTHOR OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
24 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
27 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 * These functions try to hide the poll/select/setitimer interface from the
31 * user. You associate callback functions with file descriptors and timers.
33 * $Begemot: libbegemot/rpoll.c,v 1.14 2004/09/21 15:59:00 brandt Exp $
45 # include <sys/time.h>
48 * There happens to be linuxes which read siginfo.h when including
49 * signal.h, which, for no appearent reason, defines these symbols.
65 # ifdef NEED_POLL_XOPEN_TWIDDLE
69 # ifdef NEED_POLL_XOPEN_TWIDDLE
76 * the second define is for Linux, which sometimes fails to
79 # if defined(USE_SELECT) || !defined(INFTIM)
84 # define SIGNAL SIGPOLL
92 # define poll_in (POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI)
93 # define poll_out (POLLOUT | POLLWRNORM | POLLWRBAND)
94 # define poll_except (POLLERR | POLLHUP)
97 # ifdef BROKEN_SELECT_PROTO
98 # define SELECT_CAST(P) (int *)P
100 # define SELECT_CAST(P) P
104 typedef signed long long tval_t;
106 static inline tval_t GETMSECS(void);
112 (void)gettimeofday(&tval, NULL);
113 return (tval_t)tval.tv_sec*1000+tval.tv_usec/1000;
120 _panic(const char *fmt, ...)
125 fprintf(stderr, "panic: ");
126 vfprintf(stderr, fmt, ap);
127 fprintf(stderr, "\n");
134 _xrealloc(void *p, size_t s)
139 if((ptr=malloc(s)) == NULL && (s!=0 || (ptr=malloc(1)) == NULL))
140 _panic("out of memory: xrealloc(%lx, %lu)",
141 (unsigned long)p, (unsigned long)s);
144 if((ptr=malloc(s)) == NULL && (ptr=malloc(1)) == NULL)
145 _panic("out of memory: xrealloc(%lx, %lu)",
146 (unsigned long)p, (unsigned long)s);
148 if((ptr = realloc(p, s)) == NULL)
149 _panic("out of memory: xrealloc(%lx, %lu)",
150 (unsigned long)p, (unsigned long)s);
157 * This structure holds one registration record for files
160 int fd; /* file descriptor (-1 if struct unused) */
161 int mask; /* event flags */
162 void * arg; /* client arg */
163 poll_f func; /* handler */
165 struct pollfd *pfd; /* pointer to corresponding poll() structure */
173 u_int msecs; /* millisecond value of the timer */
174 int repeat; /* one shot or repeat? */
175 void *arg; /* client arg */
176 timer_f func; /* handler, 0 means disfunct */
177 tval_t when; /* next time to trigger in msecs! */
180 /* how many records should our table grow at once? */
181 # define POLL_REG_GROW 100
184 static struct pollfd * pfd; /* fd list for poll() */
188 static fd_set rset, wset, xset; /* file descriptor sets for select() */
189 static int maxfd; /* maximum fd number */
192 static int in_dispatch;
194 static PollReg_t * regs; /* registration records */
195 static u_int regs_alloc; /* how many are allocated */
196 static u_int regs_used; /* upper used limit */
197 static sigset_t bset; /* blocked signals */
198 static int rebuild; /* rebuild table on next dispatch() */
200 static int * tfd; /* sorted entries */
201 static u_int tfd_alloc; /* number of entries allocated */
202 static u_int tfd_used; /* number of entries used */
203 static PollTim_t * tims; /* timer registration records */
204 static u_int tims_alloc; /* how many are allocated */
205 static u_int tims_used; /* how many are used */
206 static int resort; /* resort on next dispatch */
209 int rpoll_policy; /* if 0 start sched callbacks from 0 else try round robin */
211 static void poll_build(void);
212 static void poll_blocksig(void);
213 static void poll_unblocksig(void);
214 static void sort_timers(void);
218 * Private function to block SIGPOLL or SIGIO for a short time.
219 * Don't forget to call poll_unblock before return from the calling function.
220 * Don't change the mask between this calls (your changes will be lost).
228 sigaddset(&set, SIGNAL);
230 if(sigprocmask(SIG_BLOCK, &set, &bset))
231 _panic("sigprocmask(SIG_BLOCK): %s", strerror(errno));
235 * unblock the previously blocked signal
238 poll_unblocksig(void)
240 if(sigprocmask(SIG_SETMASK, &bset, NULL))
241 _panic("sigprocmask(SIG_SETMASK): %s", strerror(errno));
245 * Register the file descriptor fd. If the event corresponding to
246 * mask arrives func is called with arg.
247 * If fd is already registered with that func and arg, only the mask
249 * We block the IO-signal, so the dispatch function can be called from
250 * within the signal handler.
253 poll_register(int fd, poll_f func, void *arg, int mask)
259 /* already registered? */
260 for(p = regs; p < ®s[regs_alloc]; p++)
261 if(p->fd == fd && p->func == func && p->arg == arg) {
266 if(p == ®s[regs_alloc]) {
269 /* find a free slot */
270 for(p = regs; p < ®s[regs_alloc]; p++)
274 if(p == ®s[regs_alloc]) {
275 size_t newsize = regs_alloc + POLL_REG_GROW;
276 regs = _xrealloc(regs, sizeof(regs[0]) * newsize);
277 for(p = ®s[regs_alloc]; p < ®s[newsize]; p++) {
283 p = ®s[regs_alloc];
284 regs_alloc = newsize;
299 fprintf(stderr, "poll_register(%d, %#lx, %#lx, %#x)->%d",
300 fd, (u_long)func, (u_long)arg, mask, p - regs);
305 * remove registration
308 poll_unregister(int handle)
311 fprintf(stderr, "poll_unregister(%d)", handle);
315 regs[handle].fd = -1;
317 regs[handle].pfd = NULL;
326 * Build the structures used by poll() or select()
336 f = pfd = _xrealloc(pfd, sizeof(pfd[0]) * regs_used);
338 for(p = regs; p < ®s[regs_alloc]; p++)
342 if(p->mask & POLL_IN)
343 f->events |= poll_in;
344 if(p->mask & POLL_OUT)
345 f->events |= poll_out;
346 if(p->mask & POLL_EXCEPT)
347 f->events |= poll_except;
351 assert(f == &pfd[regs_used]);
359 for(p = regs; p < ®s[regs_alloc]; p++)
363 if(p->mask & POLL_IN)
364 FD_SET(p->fd, &rset);
365 if(p->mask & POLL_OUT)
366 FD_SET(p->fd, &wset);
367 if(p->mask & POLL_EXCEPT)
368 FD_SET(p->fd, &xset);
374 poll_start_timer(u_int msecs, int repeat, timer_f func, void *arg)
378 /* find unused entry */
379 for(p = tims; p < &tims[tims_alloc]; p++)
383 if(p == &tims[tims_alloc]) {
384 if(tims_alloc == tims_used) {
385 size_t newsize = tims_alloc + POLL_REG_GROW;
386 tims = _xrealloc(tims, sizeof(tims[0]) * newsize);
387 for(p = &tims[tims_alloc]; p < &tims[newsize]; p++)
389 p = &tims[tims_alloc];
390 tims_alloc = newsize;
399 p->when = GETMSECS() + msecs;
406 fprintf(stderr, "poll_start_timer(%u, %d, %#lx, %#lx)->%u",
407 msecs, repeat, (u_long)func, (u_long)arg, p - tims);
413 * Here we have to look into the sorted table, whether any entry there points
414 * into the registration table for the deleted entry. This is needed,
415 * because a unregistration can occure while we are scanning through the
416 * table in dispatch(). Do this only, if we are really there - resorting
417 * will sort out things if we are called from outside the loop.
420 poll_stop_timer(int handle)
425 fprintf(stderr, "poll_stop_timer(%d)", handle);
427 tims[handle].func = NULL;
435 for(i = 0; i < tfd_used; i++)
436 if(tfd[i] == handle) {
443 * Squeeze and sort timer table.
444 * Should perhaps use a custom sort.
447 tim_cmp(const void *p1, const void *p2)
449 int t1 = *(const int *)p1;
450 int t2 = *(const int *)p2;
452 return tims[t1].when < tims[t2].when ? -1
453 : tims[t1].when > tims[t2].when ? +1
458 * Reconstruct the tfd-array. This will be an sorted array of indexes
459 * to the used entries in tims. The next timer to expire will be infront
460 * of the array. tfd_used is the number of used entries. The array is
461 * re-allocated if needed.
469 if(tims_used > tfd_alloc) {
470 tfd_alloc = tims_used;
471 tfd = _xrealloc(tfd, sizeof(int *) * tfd_alloc);
476 for(i = 0; i < tims_alloc; i++)
479 assert(pp - tfd == (ptrdiff_t)tims_used);
481 tfd_used = tims_used;
483 qsort(tfd, tfd_used, sizeof(int), tim_cmp);
487 * Poll the file descriptors and dispatch to the right function
488 * If wait is true the poll blocks until somewhat happens.
489 * Don't use a pointer here, because the called function may cause
490 * a reallocation! The check for pfd != NULL is required, because
491 * a sequence of unregister/register could make the wrong callback
492 * to be called. So we clear pfd in unregister and check here.
495 poll_dispatch(int wait)
501 static u_int last_index;
504 fd_set nrset, nwset, nxset;
519 /* in wait mode - compute the timeout */
525 fprintf(stderr, "now=%"QUADFMT"u", now);
526 for(i = 0; i < tims_used; i++)
527 fprintf(stderr, "timers[%2d] = %"QUADFMT"d", i, tfd[i]->when - now);
530 if((tout = tims[tfd[0]].when - now) < 0)
538 fprintf(stderr, "rpoll -- selecting with tout=%u", tout);
542 ret = poll(pfd, regs_used, tout);
550 tv.tv_sec = tout / 1000;
551 tv.tv_usec = (tout % 1000) * 1000;
553 ret = select(maxfd+1,
556 SELECT_CAST(&nxset), (tout==INFTIM) ? 0 : &tv);
562 _panic("poll/select: %s", strerror(errno));
567 for(i = 0; i < regs_alloc; i++) {
568 idx = rpoll_policy ? ((last_index+i) % regs_alloc) : i;
570 assert(idx < regs_alloc);
572 if(regs[idx].fd >= 0) {
577 if(regs[idx].pfd->revents & poll_in)
579 if(regs[idx].pfd->revents & poll_out)
581 if(regs[idx].pfd->revents & poll_except)
586 if(FD_ISSET(regs[idx].fd, &nrset))
588 if(FD_ISSET(regs[idx].fd, &nwset))
590 if(FD_ISSET(regs[idx].fd, &nxset))
593 assert(idx < regs_alloc);
597 fprintf(stderr, "poll_dispatch() -- "
600 (*regs[idx].func)(regs[idx].fd, mask, regs[idx].arg);
608 /* dispatch timeouts */
611 for(i = 0; i < tfd_used; i++) {
614 if(tims[tfd[i]].when > now)
617 fprintf(stderr, "rpoll_dispatch() -- timeout %d",tfd[i]);
618 (*tims[tfd[i]].func)(tfd[i], tims[tfd[i]].arg);
621 if(tims[tfd[i]].repeat)
622 tims[tfd[i]].when = now + tims[tfd[i]].msecs;
624 tims[tfd[i]].func = NULL;
636 struct timeval start, now;
640 void infunc(int fd, int mask, void *arg);
645 gettimeofday(&now, NULL);
647 return (double)(10 * now.tv_sec + now.tv_usec / 100000 - 10 * start.tv_sec - start.tv_usec / 100000)
652 infunc(int fd, int mask, void *arg)
659 if((ret = read(fd, buf, sizeof(buf))) < 0)
660 _panic("read: %s", strerror(errno));
661 write(1, "stdin:", 6);
665 void tfunc0(int tid, void *arg);
666 void tfunc1(int tid, void *arg);
669 tfunc0(int tid, void *arg)
671 printf("%4.1f -- %d: %s\n", elaps(), tid, (char *)arg);
674 tfunc1(int tid, void *arg)
676 printf("%4.1f -- %d: %s\n", elaps(), tid, (char *)arg);
679 void first(int tid, void *arg);
680 void second(int tid, void *arg);
683 second(int tid, void *arg)
685 printf("%4.1f -- %d: %s\n", elaps(), tid, (char *)arg);
686 poll_start_timer(5500, 0, first, "first");
688 t0 = poll_start_timer(1000, 1, tfunc0, "1 second");
691 first(int tid, void *arg)
693 printf("%4.1f -- %d: %s\n", elaps(), tid, (char *)arg);
694 poll_start_timer(3700, 0, second, "second");
696 t1 = poll_start_timer(250, 1, tfunc1, "1/4 second");
700 main(int argc, char *argv[])
704 gettimeofday(&start, NULL);
705 poll_register(0, infunc, NULL, POLL_IN);
706 t0 = poll_start_timer(1000, 1, tfunc0, "1 second");
707 poll_start_timer(2500, 0, first, "first");