]> mj.ucw.cz Git - libucw.git/blob - ucw/mainloop.c
23eed5e14a4874c6134a4eaed5508bef2438bc6c
[libucw.git] / ucw / mainloop.c
1 /*
2  *      UCW Library -- Main Loop
3  *
4  *      (c) 2004--2012 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #undef LOCAL_DEBUG
11
12 #include "ucw/lib.h"
13 #include "ucw/heap.h"
14 #include "ucw/mainloop.h"
15 #include "ucw/threads.h"
16 #include "ucw/gary.h"
17
18 #include <stdio.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <signal.h>
23 #include <fcntl.h>
24 #include <errno.h>
25 #include <time.h>
26 #include <sys/poll.h>
27 #include <sys/wait.h>
28 #include <sys/time.h>
29
30 #ifdef CONFIG_UCW_THREADS
31 #include <pthread.h>
32 #define THREAD_SIGMASK pthread_sigmask
33 #else
34 #define THREAD_SIGMASK sigprocmask
35 #endif
36
37 #ifdef CONFIG_UCW_EPOLL
38 #include <sys/epoll.h>
39 #endif
40
41 #define MAIN_TIMER_LESS(x,y) ((x)->expires < (y)->expires)
42 #define MAIN_TIMER_SWAP(heap,a,b,t) (t=heap[a], heap[a]=heap[b], heap[b]=t, heap[a]->index=(a), heap[b]->index=(b))
43
44 #define EPOLL_BUF_SIZE 256
45
46 static void file_del_ctx(struct main_context *m, struct main_file *fi);
47 static void signal_del_ctx(struct main_context *m, struct main_signal *ms);
48
49 static void
50 main_get_time_ctx(struct main_context *m)
51 {
52   struct timeval tv;
53   gettimeofday(&tv, NULL);
54   m->now_seconds = tv.tv_sec;
55   m->now = (timestamp_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
56 }
57
58 static struct main_context *
59 main_current_nocheck(void)
60 {
61   return ucwlib_thread_context()->main_context;
62 }
63
64 struct main_context *
65 main_current(void)
66 {
67   struct main_context *m = main_current_nocheck();
68   ASSERT(m);
69   return m;
70 }
71
72 static int
73 main_is_current(struct main_context *m)
74 {
75   return (m == main_current_nocheck());
76 }
77
78 static inline uns
79 count_timers(struct main_context *m)
80 {
81   if (m->timer_table)
82     return GARY_SIZE(m->timer_table) - 1;
83   else
84     return 0;
85 }
86
87 struct main_context *
88 main_new(void)
89 {
90   struct main_context *m = xmalloc_zero(sizeof(*m));
91
92   DBG("MAIN: New context");
93   clist_init(&m->file_list);
94   clist_init(&m->file_active_list);
95   clist_init(&m->hook_list);
96   clist_init(&m->hook_done_list);
97   clist_init(&m->process_list);
98   clist_init(&m->signal_list);
99 #ifdef CONFIG_UCW_EPOLL
100   m->epoll_fd = epoll_create(64);
101   if (m->epoll_fd < 0)
102     die("epoll_create() failed: %m");
103   m->epoll_events = xmalloc(EPOLL_BUF_SIZE * sizeof(struct epoll_event));
104   clist_init(&m->file_recalc_list);
105 #else
106   m->poll_table_obsolete = 1;
107 #endif
108   main_get_time_ctx(m);
109   sigemptyset(&m->want_signals);
110   m->sig_pipe_recv = m->sig_pipe_send = -1;
111
112   return m;
113 }
114
115 static void
116 main_prepare_delete(struct main_context *m)
117 {
118   /*
119    *  If the context is current, deactivate it first. But beware,
120    *  we must not call functions that depend on the current context.
121    */
122   if (main_is_current(m))
123     main_switch_context(NULL);
124
125   // Close epoll descriptor early enough, it might be shared after fork!
126 #ifdef CONFIG_UCW_EPOLL
127   xfree(m->epoll_events);
128   close(m->epoll_fd);
129   m->epoll_fd = -1;
130 #else
131   GARY_FREE(m->poll_table);
132   GARY_FREE(m->poll_file_table);
133 #endif
134
135   if (m->sigchld_handler)
136     {
137       signal_del_ctx(m, m->sigchld_handler);
138       xfree(m->sigchld_handler);
139     }
140   if (m->sig_pipe_file)
141     {
142       file_del_ctx(m, m->sig_pipe_file);
143       xfree(m->sig_pipe_file);
144      }
145   if (m->sig_pipe_recv >= 0)
146     {
147       close(m->sig_pipe_recv);
148       close(m->sig_pipe_send);
149     }
150 }
151
152 static void
153 main_do_delete(struct main_context *m)
154 {
155   GARY_FREE(m->timer_table);
156   xfree(m);
157 }
158
159 void
160 main_delete(struct main_context *m)
161 {
162   if (!m)
163     return;
164
165   main_prepare_delete(m);
166   ASSERT(clist_empty(&m->file_list));
167   ASSERT(clist_empty(&m->file_active_list));
168 #ifdef CONFIG_UCW_EPOLL
169   ASSERT(clist_empty(&m->file_recalc_list));
170 #endif
171   ASSERT(clist_empty(&m->hook_list));
172   ASSERT(clist_empty(&m->hook_done_list));
173   ASSERT(clist_empty(&m->process_list));
174   ASSERT(clist_empty(&m->signal_list));
175   ASSERT(!count_timers(m));
176   main_do_delete(m);
177 }
178
179 void
180 main_destroy(struct main_context *m)
181 {
182   if (!m)
183     return;
184   main_prepare_delete(m);
185
186   // Close all files
187   clist_insert_list_after(&m->file_active_list, m->file_list.head.prev);
188 #ifdef CONFIG_UCW_EPOLL
189   clist_insert_list_after(&m->file_recalc_list, m->file_list.head.prev);
190 #endif
191   CLIST_FOR_EACH(struct main_file *, f, m->file_list)
192     close(f->fd);
193
194   main_do_delete(m);
195 }
196
197 struct main_context *
198 main_switch_context(struct main_context *m)
199 {
200   struct ucwlib_context *c = ucwlib_thread_context();
201   struct main_context *m0 = c->main_context;
202
203   /*
204    *  Not only we need to switch the signal sets of the two contexts,
205    *  but it is also necessary to avoid invoking a signal handler
206    *  in the middle of changing c->main_context.
207    */
208   if (m0 && !clist_empty(&m0->signal_list))
209     THREAD_SIGMASK(SIG_BLOCK, &m0->want_signals, NULL);
210   c->main_context = m;
211   if (m && !clist_empty(&m->signal_list))
212     THREAD_SIGMASK(SIG_UNBLOCK, &m->want_signals, NULL);
213
214   return m0;
215 }
216
217 void
218 main_init(void)
219 {
220   struct main_context *m = main_switch_context(main_new());
221   ASSERT(!m);
222 }
223
224 void
225 main_cleanup(void)
226 {
227   main_delete(main_current_nocheck());
228 }
229
230 void
231 main_teardown(void)
232 {
233   main_destroy(main_current_nocheck());
234 }
235
236 void
237 main_get_time(void)
238 {
239   main_get_time_ctx(main_current());
240 }
241
242 void
243 timer_add(struct main_timer *tm, timestamp_t expires)
244 {
245   struct main_context *m = main_current();
246
247   if (!m->timer_table)
248     {
249       GARY_INIT(m->timer_table, 1);
250       m->timer_table[0] = NULL;
251     }
252
253   if (expires)
254     DBG("MAIN: Setting timer %p (expire at now+%lld)", tm, (long long)(expires - m->now));
255   else
256     DBG("MAIN: Clearing timer %p", tm);
257   uns num_timers = count_timers(m);
258   if (tm->expires < expires)
259     {
260       if (!tm->expires)
261         {
262           tm->expires = expires;
263           tm->index = num_timers + 1;
264           *GARY_PUSH(m->timer_table, 1) = tm;
265           HEAP_INSERT(struct main_timer *, m->timer_table, tm->index, MAIN_TIMER_LESS, MAIN_TIMER_SWAP);
266         }
267       else
268         {
269           tm->expires = expires;
270           HEAP_INCREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
271         }
272     }
273   else if (tm->expires > expires)
274     {
275       if (!expires)
276         {
277           ASSERT(tm->index && tm->index <= num_timers);
278           HEAP_DELETE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
279           tm->index = 0;
280           tm->expires = 0;
281           GARY_POP(m->timer_table, 1);
282         }
283       else
284         {
285           tm->expires = expires;
286           HEAP_DECREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
287         }
288     }
289 }
290
291 void
292 timer_add_rel(struct main_timer *tm, timestamp_t expires_delta)
293 {
294   struct main_context *m = main_current();
295   return timer_add(tm, m->now + expires_delta);
296 }
297
298 void
299 timer_del(struct main_timer *tm)
300 {
301   timer_add(tm, 0);
302 }
303
304 static uns
305 file_want_events(struct main_file *fi)
306 {
307   uns events = 0;
308   if (fi->read_handler)
309     events |= POLLIN;
310   if (fi->write_handler)
311     events |= POLLOUT;
312   return events;
313 }
314
315 void
316 file_add(struct main_file *fi)
317 {
318   struct main_context *m = main_current();
319
320   DBG("MAIN: Adding file %p (fd=%d)", fi, fi->fd);
321   ASSERT(!file_is_active(fi));
322   clist_add_tail(&m->file_list, &fi->n);
323   m->file_cnt++;
324 #ifdef CONFIG_UCW_EPOLL
325   struct epoll_event evt = {
326     .events = file_want_events(fi),
327     .data.ptr = fi,
328   };
329   if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, fi->fd, &evt) < 0)
330     die("epoll_ctl() failed: %m");
331   fi->last_want_events = evt.events;
332 #else
333   m->poll_table_obsolete = 1;
334 #endif
335   if (fcntl(fi->fd, F_SETFL, O_NONBLOCK) < 0)
336     msg(L_ERROR, "Error setting fd %d to non-blocking mode: %m. Keep fingers crossed.", fi->fd);
337 }
338
339 void
340 file_chg(struct main_file *fi)
341 {
342 #ifdef CONFIG_UCW_EPOLL
343   clist_remove(&fi->n);
344   clist_add_tail(&main_current()->file_recalc_list, &fi->n);
345 #else
346   struct pollfd *p = fi->pollfd;
347   if (p)
348     p->events = file_want_events(fi);
349 #endif
350 }
351
352 static void
353 file_del_ctx(struct main_context *m, struct main_file *fi)
354 {
355   // XXX: Can be called on a non-current context
356   DBG("MAIN: Deleting file %p (fd=%d)", fi, fi->fd);
357
358   if (!file_is_active(fi))
359     return;
360   clist_unlink(&fi->n);
361   m->file_cnt--;
362 #ifdef CONFIG_UCW_EPOLL
363   if (m->epoll_fd >= 0 && epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, fi->fd, NULL) < 0)
364     die("epoll_ctl() failed: %m");
365 #else
366   m->poll_table_obsolete = 1;
367 #endif
368 }
369
370 void
371 file_del(struct main_file *fi)
372 {
373   file_del_ctx(main_current(), fi);
374 }
375
376 void
377 hook_add(struct main_hook *ho)
378 {
379   struct main_context *m = main_current();
380
381   DBG("MAIN: Adding hook %p", ho);
382   if (hook_is_active(ho))
383     clist_unlink(&ho->n);
384   clist_add_tail(&m->hook_list, &ho->n);
385 }
386
387 void
388 hook_del(struct main_hook *ho)
389 {
390   DBG("MAIN: Deleting hook %p", ho);
391   if (hook_is_active(ho))
392     clist_unlink(&ho->n);
393 }
394
395 static void
396 sigchld_received(struct main_signal *sg UNUSED)
397 {
398   struct main_context *m = main_current();
399   int stat;
400   pid_t pid;
401
402   while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
403     {
404       DBG("MAIN: Child %d exited with status %x", pid, stat);
405       CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
406         if (pr->pid == pid)
407           {
408             pr->status = stat;
409             process_del(pr);
410             format_exit_status(pr->status_msg, pr->status);
411             DBG("MAIN: Calling process exit handler");
412             pr->handler(pr);
413             break;
414           }
415     }
416 }
417
418 void
419 process_add(struct main_process *mp)
420 {
421   struct main_context *m = main_current();
422
423   DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
424   ASSERT(!process_is_active(mp));
425   ASSERT(mp->handler);
426   clist_add_tail(&m->process_list, &mp->n);
427   if (!m->sigchld_handler)
428     {
429       struct main_signal *sg = xmalloc_zero(sizeof(*sg));
430       m->sigchld_handler = sg;
431       sg->signum = SIGCHLD;
432       sg->handler = sigchld_received;
433       signal_add(sg);
434     }
435 }
436
437 void
438 process_del(struct main_process *mp)
439 {
440   DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
441   if (process_is_active(mp))
442     clist_unlink(&mp->n);
443 }
444
445 int
446 process_fork(struct main_process *mp)
447 {
448   pid_t pid = fork();
449   if (pid < 0)
450     {
451       DBG("MAIN: Fork failed");
452       mp->status = -1;
453       format_exit_status(mp->status_msg, -1);
454       mp->handler(mp);
455       return 1;
456     }
457   else if (!pid)
458     return 0;
459   else
460     {
461       DBG("MAIN: Forked process %d", (int) pid);
462       mp->pid = pid;
463       process_add(mp);
464       return 1;
465     }
466 }
467
468 static int
469 pipe_read_handler(struct main_file *mf UNUSED)
470 {
471   struct main_context *m = main_current();
472   int signum;
473   int n = read(m->sig_pipe_recv, &signum, sizeof(signum));
474
475   if (n < 0)
476     {
477       if (errno != EAGAIN)
478         msg(L_ERROR, "Error reading signal pipe: %m");
479       return 0;
480     }
481   ASSERT(n == sizeof(signum));
482
483   DBG("MAIN: Sigpipe: received signal %d", signum);
484   struct main_signal iter = { .signum = -1 };
485   struct main_signal *sg = clist_head(&m->signal_list);
486   while (sg)
487     {
488       if (sg->signum == signum)
489         {
490           DBG("MAIN: Sigpipe: invoking handler %p", sg);
491           clist_insert_after(&iter.n, &sg->n);
492           sg->handler(sg);
493           sg = clist_next(&m->signal_list, &iter.n);
494           clist_remove(&iter.n);
495         }
496       else
497         sg = clist_next(&m->signal_list, &sg->n);
498     }
499
500   return 1;
501 }
502
503 static void
504 pipe_configure(int fd)
505 {
506   int flags;
507   if ((flags = fcntl(fd, F_GETFL)) < 0 || fcntl(fd, F_SETFL, flags|O_NONBLOCK) < 0)
508     die("Could not set file descriptor %d to non-blocking: %m", fd);
509 }
510
511 static void
512 pipe_setup(struct main_context *m)
513 {
514   DBG("MAIN: Sigpipe: Setting up the pipe");
515
516   int pipe_result[2];
517   if (pipe(pipe_result) == -1)
518     die("Could not create signal pipe: %m");
519   pipe_configure(pipe_result[0]);
520   pipe_configure(pipe_result[1]);
521   m->sig_pipe_recv = pipe_result[0];
522   m->sig_pipe_send = pipe_result[1];
523
524   struct main_file *f = xmalloc_zero(sizeof(*f));
525   m->sig_pipe_file = f;
526   f->fd = m->sig_pipe_recv;
527   f->read_handler = pipe_read_handler;
528   file_add(f);
529 }
530
531 static void
532 signal_handler_pipe(int signum)
533 {
534   struct main_context *m = main_current();
535 #ifdef LOCAL_DEBUG
536   msg(L_DEBUG | L_SIGHANDLER, "MAIN: Sigpipe: sending signal %d down the drain", signum);
537 #endif
538   write(m->sig_pipe_send, &signum, sizeof(signum));
539 }
540
541 void
542 signal_add(struct main_signal *ms)
543 {
544   struct main_context *m = main_current();
545
546   DBG("MAIN: Adding signal %p (sig=%d)", ms, ms->signum);
547
548   ASSERT(!signal_is_active(ms));
549   // Adding at the head of the list is better if we are in the middle of walking the list.
550   clist_add_head(&m->signal_list, &ms->n);
551   if (m->sig_pipe_recv < 0)
552     pipe_setup(m);
553
554   struct sigaction sa = {
555     .sa_handler = signal_handler_pipe,
556     .sa_flags = SA_NOCLDSTOP | SA_RESTART,
557   };
558   sigaction(ms->signum, &sa, NULL);
559
560   sigset_t ss;
561   sigemptyset(&ss);
562   sigaddset(&ss, ms->signum);
563   THREAD_SIGMASK(SIG_UNBLOCK, &ss, NULL);
564   sigaddset(&m->want_signals, ms->signum);
565 }
566
567 static void
568 signal_del_ctx(struct main_context *m, struct main_signal *ms)
569 {
570   // XXX: Can be called on a non-current context
571   DBG("MAIN: Deleting signal %p (sig=%d)", ms, ms->signum);
572
573   if (!signal_is_active(ms))
574     return;
575   clist_unlink(&ms->n);
576
577   int another = 0;
578   CLIST_FOR_EACH(struct main_signal *, s, m->signal_list)
579     if (s->signum == ms->signum)
580       another++;
581   if (!another)
582     {
583       if (main_is_current(m))
584         {
585           sigset_t ss;
586           sigemptyset(&ss);
587           sigaddset(&ss, ms->signum);
588           THREAD_SIGMASK(SIG_BLOCK, &ss, NULL);
589         }
590       sigdelset(&m->want_signals, ms->signum);
591     }
592 }
593
594 void
595 signal_del(struct main_signal *ms)
596 {
597   signal_del_ctx(main_current(), ms);
598 }
599
600 #ifdef CONFIG_DEBUG
601
602 void
603 file_debug(struct main_file *fi)
604 {
605   msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p)",
606     fi, fi->fd, fi->read_handler, fi->write_handler, fi->data);
607 }
608
609 void
610 hook_debug(struct main_hook *ho)
611 {
612   msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
613 }
614
615 void
616 signal_debug(struct main_signal *sg)
617 {
618   if (sg->signum < 0)
619     msg(L_DEBUG, "\t\t(placeholder)");
620   else
621     msg(L_DEBUG, "\t\t%p (sig %d, func %p, data %p)", sg, sg->signum, sg->handler, sg->data);
622 }
623
624 static void
625 timer_debug_ctx(struct main_context *m, struct main_timer *tm)
626 {
627   msg(L_DEBUG, "\t\t%p (expires %lld, data %p)", tm, (long long)(tm->expires - m->now), tm->data);
628 }
629
630 void
631 timer_debug(struct main_timer *tm)
632 {
633   timer_debug_ctx(main_current(), tm);
634 }
635
636 void
637 process_debug(struct main_process *pr)
638 {
639   msg(L_DEBUG, "\t\t%p (pid %d, func %p, data %p)", pr, pr->pid, pr->handler, pr->data);
640 }
641
642 void
643 main_debug_context(struct main_context *m UNUSED)
644 {
645   msg(L_DEBUG, "### Main loop status on %lld", (long long) m->now);
646   msg(L_DEBUG, "\tActive timers:");
647   uns num_timers = count_timers(m);
648   for (uns i = 1; i <= num_timers; i++)
649     timer_debug(m->timer_table[i]);
650   msg(L_DEBUG, "\tActive files:");
651   CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
652     file_debug(fi);
653   CLIST_FOR_EACH(struct main_file *, fi, m->file_active_list)
654     file_debug(fi);
655 #ifdef CONFIG_UCW_EPOLL
656   CLIST_FOR_EACH(struct main_file *, fi, m->file_recalc_list)
657     file_debug(fi);
658 #endif
659   msg(L_DEBUG, "\tActive hooks:");
660   CLIST_FOR_EACH(struct main_hook *, ho, m->hook_done_list)
661     hook_debug(ho);
662   CLIST_FOR_EACH(struct main_hook *, ho, m->hook_list)
663     hook_debug(ho);
664   msg(L_DEBUG, "\tActive processes:");
665   CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
666     process_debug(pr);
667   msg(L_DEBUG, "\tActive signal catchers:");
668   CLIST_FOR_EACH(struct main_signal *, sg, m->signal_list)
669     signal_debug(sg);
670 }
671
672 #else
673
674 // Stubs
675 void file_debug(struct main_file *fi UNUSED) { }
676 void hook_debug(struct main_hook *ho UNUSED) { }
677 void signal_debug(struct main_signal *sg UNUSED) { }
678 void timer_debug(struct main_timer *tm UNUSED) { }
679 void process_debug(struct main_process *pr UNUSED) { }
680 void main_debug_context(struct main_context *m UNUSED) { }
681
682 #endif
683
684 static void
685 process_timers(struct main_context *m)
686 {
687   struct main_timer *tm;
688   while (count_timers(m) && (tm = m->timer_table[1])->expires <= m->now)
689     {
690       DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(m->now - tm->expires));
691       tm->handler(tm);
692     }
693 }
694
695 static enum main_hook_return
696 process_hooks(struct main_context *m)
697 {
698   int hook_min = HOOK_RETRY;
699   int hook_max = HOOK_SHUTDOWN;
700   struct main_hook *ho;
701
702   while (ho = clist_remove_head(&m->hook_list))
703     {
704       clist_add_tail(&m->hook_done_list, &ho->n);
705       DBG("MAIN: Hook %p", ho);
706       int ret = ho->handler(ho);
707       hook_min = MIN(hook_min, ret);
708       hook_max = MAX(hook_max, ret);
709     }
710   clist_move(&m->hook_list, &m->hook_done_list);
711   if (hook_min == HOOK_SHUTDOWN ||
712     hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
713     m->shutdown)
714     {
715       DBG("MAIN: Shut down by %s", m->shutdown ? "main_shut_down" : "a hook");
716       return HOOK_SHUTDOWN;
717     }
718   if (hook_max == HOOK_RETRY)
719     return HOOK_RETRY;
720   else
721     return HOOK_IDLE;
722 }
723
724 #ifdef CONFIG_UCW_EPOLL
725
726 static void
727 recalc_files(struct main_context *m)
728 {
729   struct main_file *fi;
730
731   while (fi = clist_remove_head(&m->file_recalc_list))
732     {
733       struct epoll_event evt = {
734         .events = file_want_events(fi),
735         .data.ptr = fi,
736       };
737       if (evt.events != fi->last_want_events)
738         {
739           DBG("MAIN: Changing requested events for fd %d to %x", fi->fd, evt.events);
740           fi->last_want_events = evt.events;
741           if (epoll_ctl(main_current()->epoll_fd, EPOLL_CTL_MOD, fi->fd, &evt) < 0)
742             die("epoll_ctl() failed: %m");
743         }
744       clist_add_tail(&m->file_list, &fi->n);
745     }
746 }
747
748 #else
749
750 static void
751 rebuild_poll_table(struct main_context *m)
752 {
753   GARY_INIT_OR_RESIZE(m->poll_table, m->file_cnt);
754   GARY_INIT_OR_RESIZE(m->poll_file_table, m->file_cnt);
755   DBG("MAIN: Rebuilding poll table: %d entries", m->file_cnt);
756
757   struct pollfd *p = m->poll_table;
758   struct main_file **pf = m->poll_file_table;
759   CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
760     {
761       p->fd = fi->fd;
762       p->events = file_want_events(fi);
763       fi->pollfd = p++;
764       *pf++ = fi;
765     }
766   m->poll_table_obsolete = 0;
767 }
768
769 #endif
770
771 void
772 main_loop(void)
773 {
774   DBG("MAIN: Entering main_loop");
775   struct main_context *m = main_current();
776
777   main_get_time_ctx(m);
778   m->shutdown = 0;
779
780   for (;;)
781     {
782       timestamp_t wake = m->now + 1000000000;
783       process_timers(m);
784       switch (process_hooks(m))
785         {
786         case HOOK_SHUTDOWN:
787           return;
788         case HOOK_RETRY:
789           wake = 0;
790           break;
791         default: ;
792         }
793
794       int timeout = 0;
795       if (!m->single_step)
796         {
797           if (count_timers(m))
798             wake = MIN(wake, m->timer_table[1]->expires);
799           main_get_time_ctx(m);
800           timeout = ((wake > m->now) ? wake - m->now : 0);
801         }
802
803 #ifdef CONFIG_UCW_EPOLL
804       recalc_files(m);
805       DBG("MAIN: Epoll for %d fds and timeout %d ms", m->file_cnt, timeout);
806       int n = epoll_wait(m->epoll_fd, m->epoll_events, EPOLL_BUF_SIZE, timeout);
807 #else
808       if (m->poll_table_obsolete)
809         rebuild_poll_table(m);
810       DBG("MAIN: Poll for %d fds and timeout %d ms", m->file_cnt, timeout);
811       int n = poll(m->poll_table, m->file_cnt, timeout);
812 #endif
813
814       DBG("\t-> %d events", n);
815       if (n < 0 && errno != EAGAIN && errno != EINTR)
816         die("(e)poll failed: %m");
817       timestamp_t old_now = m->now;
818       main_get_time_ctx(m);
819       m->idle_time += m->now - old_now;
820
821       if (n <= 0)
822         {
823           if (m->single_step)
824             return;
825           else
826             continue;
827         }
828
829       // Relink all files with a pending event to file_active_list
830 #ifdef CONFIG_UCW_EPOLL
831       for (int i=0; i<n; i++)
832         {
833           struct epoll_event *e = &m->epoll_events[i];
834           struct main_file *fi = e->data.ptr;
835           clist_remove(&fi->n);
836           clist_add_tail(&m->file_active_list, &fi->n);
837           fi->events = e->events;
838         }
839 #else
840       struct pollfd *p = m->poll_table;
841       struct main_file **pf = m->poll_file_table;
842       for (uns i=0; i < m->file_cnt; i++)
843         if (p[i].revents)
844           {
845             struct main_file *fi = pf[i];
846             clist_remove(&fi->n);
847             clist_add_tail(&m->file_active_list, &fi->n);
848             fi->events = p[i].revents;
849           }
850 #endif
851
852       /*
853        *  Process the buffered file events. This is pretty tricky, since
854        *  user callbacks can modify the file structure or even destroy it.
855        *  In such cases, we detect that the structure was relinked and stop
856        *  processing its events, leaving them for the next iteration of the
857        *  main loop.
858        */
859       struct main_file *fi;
860       while (fi = clist_head(&m->file_active_list))
861         {
862           if (fi->read_handler && (fi->events & (POLLIN | POLLHUP)))
863             {
864               fi->events &= ~(POLLIN | POLLHUP);
865               do
866                 DBG("MAIN: Read event on fd %d", fi->fd);
867               while (fi->read_handler && fi->read_handler(fi));
868               continue;
869             }
870           if (fi->write_handler && (fi->events & (POLLOUT | POLLHUP | POLLERR)))
871             {
872               fi->events &= ~(POLLOUT | POLLHUP | POLLERR);
873               do
874                 DBG("MAIN: Write event on fd %d", fi->fd);
875               while (fi->write_handler && fi->write_handler(fi));
876               continue;
877             }
878           clist_remove(&fi->n);
879           clist_add_tail(&m->file_list, &fi->n);
880         }
881     }
882 }
883
884 void
885 main_step(void)
886 {
887   struct main_context *m = main_current();
888   m->single_step = 1;
889   main_loop();
890   m->single_step = 0;
891 }