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