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