]> mj.ucw.cz Git - libucw.git/blob - ucw/mainloop.c
de40fc5cabd72b38718f8fe748169c7bb41bbb4d
[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   // FIXME: Add a doc note on calling from a running mainloop
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   uns 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_PUSH(m->timer_table, 1) = tm;
264           HEAP_INSERT(struct main_timer *, m->timer_table, tm->index, MAIN_TIMER_LESS, MAIN_TIMER_SWAP);
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);
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, 1);
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);
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 uns
304 file_want_events(struct main_file *fi)
305 {
306   uns events = 0;
307   if (fi->read_handler)
308     events |= POLLIN | POLLHUP | POLLERR;
309   if (fi->write_handler)
310     events |= POLLOUT | POLLERR;
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(!clist_is_linked(&fi->n));
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   ASSERT(clist_is_linked(&fi->n));
358   clist_unlink(&fi->n);
359   m->file_cnt--;
360 #ifdef CONFIG_UCW_EPOLL
361   if (m->epoll_fd >= 0 && epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, fi->fd, NULL) < 0)
362     die("epoll_ctl() failed: %m");
363 #else
364   m->poll_table_obsolete = 1;
365 #endif
366 }
367
368 void
369 file_del(struct main_file *fi)
370 {
371   file_del_ctx(main_current(), fi);
372 }
373
374 void
375 hook_add(struct main_hook *ho)
376 {
377   struct main_context *m = main_current();
378
379   DBG("MAIN: Adding hook %p", ho);
380   ASSERT(!clist_is_linked(&ho->n));
381   clist_add_tail(&m->hook_list, &ho->n);
382 }
383
384 void
385 hook_del(struct main_hook *ho)
386 {
387   DBG("MAIN: Deleting hook %p", ho);
388   ASSERT(clist_is_linked(&ho->n));
389   clist_unlink(&ho->n);
390 }
391
392 static void
393 sigchld_received(struct main_signal *sg UNUSED)
394 {
395   struct main_context *m = main_current();
396   int stat;
397   pid_t pid;
398
399   while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
400     {
401       DBG("MAIN: Child %d exited with status %x", pid, stat);
402       CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
403         if (pr->pid == pid)
404           {
405             pr->status = stat;
406             process_del(pr);
407             format_exit_status(pr->status_msg, pr->status);
408             DBG("MAIN: Calling process exit handler");
409             pr->handler(pr);
410             break;
411           }
412     }
413 }
414
415 void
416 process_add(struct main_process *mp)
417 {
418   struct main_context *m = main_current();
419
420   DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
421   ASSERT(!clist_is_linked(&mp->n));
422   ASSERT(mp->handler);
423   clist_add_tail(&m->process_list, &mp->n);
424   if (!m->sigchld_handler)
425     {
426       struct main_signal *sg = xmalloc_zero(sizeof(*sg));
427       m->sigchld_handler = sg;
428       sg->signum = SIGCHLD;
429       sg->handler = sigchld_received;
430       signal_add(sg);
431     }
432 }
433
434 void
435 process_del(struct main_process *mp)
436 {
437   DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
438   ASSERT(clist_is_linked(&mp->n));
439   clist_unlink(&mp->n);
440 }
441
442 int
443 process_fork(struct main_process *mp)
444 {
445   pid_t pid = fork();
446   if (pid < 0)
447     {
448       DBG("MAIN: Fork failed");
449       mp->status = -1;
450       format_exit_status(mp->status_msg, -1);
451       mp->handler(mp);
452       return 1;
453     }
454   else if (!pid)
455     return 0;
456   else
457     {
458       DBG("MAIN: Forked process %d", (int) pid);
459       mp->pid = pid;
460       process_add(mp);
461       return 1;
462     }
463 }
464
465 static int
466 pipe_read_handler(struct main_file *mf UNUSED)
467 {
468   struct main_context *m = main_current();
469   int signum;
470   int n = read(m->sig_pipe_recv, &signum, sizeof(signum));
471
472   if (n < 0)
473     {
474       if (errno != EAGAIN)
475         msg(L_ERROR, "Error reading signal pipe: %m");
476       return 0;
477     }
478   ASSERT(n == sizeof(signum));
479
480   DBG("MAIN: Sigpipe: received signal %d", signum);
481   struct main_signal iter = { .signum = -1 };
482   struct main_signal *sg = clist_head(&m->signal_list);
483   while (sg)
484     {
485       if (sg->signum == signum)
486         {
487           DBG("MAIN: Sigpipe: invoking handler %p", sg);
488           clist_insert_after(&iter.n, &sg->n);
489           sg->handler(sg);
490           sg = clist_next(&m->signal_list, &iter.n);
491           clist_remove(&iter.n);
492         }
493       else
494         sg = clist_next(&m->signal_list, &sg->n);
495     }
496
497   return 1;
498 }
499
500 static void
501 pipe_configure(int fd)
502 {
503   int flags;
504   if ((flags = fcntl(fd, F_GETFL)) < 0 || fcntl(fd, F_SETFL, flags|O_NONBLOCK) < 0)
505     die("Could not set file descriptor %d to non-blocking: %m", fd);
506 }
507
508 static void
509 pipe_setup(struct main_context *m)
510 {
511   DBG("MAIN: Sigpipe: Setting up the pipe");
512
513   int pipe_result[2];
514   if (pipe(pipe_result) == -1)
515     die("Could not create signal pipe: %m");
516   pipe_configure(pipe_result[0]);
517   pipe_configure(pipe_result[1]);
518   m->sig_pipe_recv = pipe_result[0];
519   m->sig_pipe_send = pipe_result[1];
520
521   struct main_file *f = xmalloc_zero(sizeof(*f));
522   m->sig_pipe_file = f;
523   f->fd = m->sig_pipe_recv;
524   f->read_handler = pipe_read_handler;
525   file_add(f);
526 }
527
528 static void
529 signal_handler_pipe(int signum)
530 {
531   struct main_context *m = main_current();
532 #ifdef LOCAL_DEBUG
533   msg(L_DEBUG | L_SIGHANDLER, "MAIN: Sigpipe: sending signal %d down the drain", signum);
534 #endif
535   write(m->sig_pipe_send, &signum, sizeof(signum));
536 }
537
538 void
539 signal_add(struct main_signal *ms)
540 {
541   struct main_context *m = main_current();
542
543   DBG("MAIN: Adding signal %p (sig=%d)", ms, ms->signum);
544
545   ASSERT(!clist_is_linked(&ms->n));
546   // Adding at the head of the list is better if we are in the middle of walking the list.
547   clist_add_head(&m->signal_list, &ms->n);
548   if (m->sig_pipe_recv < 0)
549     pipe_setup(m);
550
551   struct sigaction sa = {
552     .sa_handler = signal_handler_pipe,
553     .sa_flags = SA_NOCLDSTOP | SA_RESTART,
554   };
555   sigaction(ms->signum, &sa, NULL);
556
557   sigset_t ss;
558   sigemptyset(&ss);
559   sigaddset(&ss, ms->signum);
560   THREAD_SIGMASK(SIG_UNBLOCK, &ss, NULL);
561   sigaddset(&m->want_signals, ms->signum);
562 }
563
564 static void
565 signal_del_ctx(struct main_context *m, struct main_signal *ms)
566 {
567   // XXX: Can be called on a non-current context
568   DBG("MAIN: Deleting signal %p (sig=%d)", ms, ms->signum);
569
570   ASSERT(clist_is_linked(&ms->n));
571   clist_unlink(&ms->n);
572
573   int another = 0;
574   CLIST_FOR_EACH(struct main_signal *, s, m->signal_list)
575     if (s->signum == ms->signum)
576       another++;
577   if (!another)
578     {
579       if (main_is_current(m))
580         {
581           sigset_t ss;
582           sigemptyset(&ss);
583           sigaddset(&ss, ms->signum);
584           THREAD_SIGMASK(SIG_BLOCK, &ss, NULL);
585         }
586       sigdelset(&m->want_signals, ms->signum);
587     }
588 }
589
590 void
591 signal_del(struct main_signal *ms)
592 {
593   signal_del_ctx(main_current(), ms);
594 }
595
596 void
597 main_debug_context(struct main_context *m UNUSED)
598 {
599 #ifdef CONFIG_DEBUG
600   msg(L_DEBUG, "### Main loop status on %lld", (long long) m->now);
601   msg(L_DEBUG, "\tActive timers:");
602   uns num_timers = count_timers(m);
603   for (uns i = 1; i <= num_timers; i++)
604     {
605       struct main_timer *tm = m->timer_table[i];
606       msg(L_DEBUG, "\t\t%p (expires %lld, data %p)", tm, (long long)(tm->expires ? tm->expires - m->now : 999999), tm->data);
607     }
608   msg(L_DEBUG, "\tActive files:");
609   CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
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   CLIST_FOR_EACH(struct main_file *, fi, m->file_active_list)
613     msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p) [pending events: %x]",
614         fi, fi->fd, fi->read_handler, fi->write_handler, fi->data, fi->events);
615     // FIXME: Can we display status of block_io requests somehow?
616 #ifdef CONFIG_UCW_EPOLL
617   CLIST_FOR_EACH(struct main_file *, fi, m->file_recalc_list)
618     msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p) [pending recalculation]",
619         fi, fi->fd, fi->read_handler, fi->write_handler, fi->data);
620 #endif
621   msg(L_DEBUG, "\tActive hooks:");
622   CLIST_FOR_EACH(struct main_hook *, ho, m->hook_done_list)
623     msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
624   CLIST_FOR_EACH(struct main_hook *, ho, m->hook_list)
625     msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
626   msg(L_DEBUG, "\tActive processes:");
627   CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
628     msg(L_DEBUG, "\t\t%p (pid %d, func %p, data %p)", pr, pr->pid, pr->handler, pr->data);
629   msg(L_DEBUG, "\tActive signal catchers:");
630   CLIST_FOR_EACH(struct main_signal *, sg, m->signal_list)
631     if (sg->signum < 0)
632       msg(L_DEBUG, "\t\t(placeholder)");
633     else
634       msg(L_DEBUG, "\t\t%p (sig %d, func %p, data %p)", sg, sg->signum, sg->handler, sg->data);
635 #endif
636 }
637
638 static void
639 process_timers(struct main_context *m)
640 {
641   struct main_timer *tm;
642   while (count_timers(m) && (tm = m->timer_table[1])->expires <= m->now)
643     {
644       DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(m->now - tm->expires));
645       tm->handler(tm);
646     }
647 }
648
649 static enum main_hook_return
650 process_hooks(struct main_context *m)
651 {
652   int hook_min = HOOK_RETRY;
653   int hook_max = HOOK_SHUTDOWN;
654   struct main_hook *ho;
655
656   while (ho = clist_remove_head(&m->hook_list))
657     {
658       clist_add_tail(&m->hook_done_list, &ho->n);
659       DBG("MAIN: Hook %p", ho);
660       int ret = ho->handler(ho);
661       hook_min = MIN(hook_min, ret);
662       hook_max = MAX(hook_max, ret);
663     }
664   clist_move(&m->hook_list, &m->hook_done_list);
665   if (hook_min == HOOK_SHUTDOWN ||
666     hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
667     m->shutdown)
668     {
669       DBG("MAIN: Shut down by %s", m->shutdown ? "main_shutdown" : "a hook");
670       return HOOK_SHUTDOWN;
671     }
672   if (hook_max == HOOK_RETRY)
673     return HOOK_RETRY;
674   else
675     return HOOK_IDLE;
676 }
677
678 #ifdef CONFIG_UCW_EPOLL
679
680 static void
681 recalc_files(struct main_context *m)
682 {
683   struct main_file *fi;
684
685   while (fi = clist_remove_head(&m->file_recalc_list))
686     {
687       struct epoll_event evt = {
688         .events = file_want_events(fi),
689         .data.ptr = fi,
690       };
691       if (evt.events != fi->last_want_events)
692         {
693           DBG("MAIN: Changing requested events for fd %d to %x", fi->fd, evt.events);
694           fi->last_want_events = evt.events;
695           if (epoll_ctl(main_current()->epoll_fd, EPOLL_CTL_MOD, fi->fd, &evt) < 0)
696             die("epoll_ctl() failed: %m");
697         }
698       clist_add_tail(&m->file_list, &fi->n);
699     }
700 }
701
702 #else
703
704 static void
705 rebuild_poll_table(struct main_context *m)
706 {
707   GARY_INIT_OR_RESIZE(m->poll_table, m->file_cnt);
708   GARY_INIT_OR_RESIZE(m->poll_file_table, m->file_cnt);
709   DBG("MAIN: Rebuilding poll table: %d entries", m->file_cnt);
710
711   struct pollfd *p = m->poll_table;
712   struct main_file **pf = m->poll_file_table;
713   CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
714     {
715       p->fd = fi->fd;
716       p->events = file_want_events(fi);
717       fi->pollfd = p++;
718       *pf++ = fi;
719     }
720   m->poll_table_obsolete = 0;
721 }
722
723 #endif
724
725 void
726 main_loop(void)
727 {
728   DBG("MAIN: Entering main_loop");
729   struct main_context *m = main_current();
730
731   main_get_time_ctx(m);
732   for (;;)
733     {
734       timestamp_t wake = m->now + 1000000000;
735       process_timers(m);
736       switch (process_hooks(m))
737         {
738         case HOOK_SHUTDOWN:
739           return;
740         case HOOK_RETRY:
741           wake = 0;
742           break;
743         default: ;
744         }
745       if (count_timers(m))
746         wake = MIN(wake, m->timer_table[1]->expires);
747       main_get_time_ctx(m);
748       int timeout = ((wake > m->now) ? wake - m->now : 0);
749
750 #ifdef CONFIG_UCW_EPOLL
751       recalc_files(m);
752       DBG("MAIN: Epoll for %d fds and timeout %d ms", m->file_cnt, timeout);
753       int n = epoll_wait(m->epoll_fd, m->epoll_events, EPOLL_BUF_SIZE, timeout);
754 #else
755       if (m->poll_table_obsolete)
756         rebuild_poll_table(m);
757       DBG("MAIN: Poll for %d fds and timeout %d ms", m->file_cnt, timeout);
758       int n = poll(m->poll_table, m->file_cnt, timeout);
759 #endif
760
761       DBG("\t-> %d events", n);
762       if (n < 0 && errno != EAGAIN && errno != EINTR)
763         die("(e)poll failed: %m");
764       timestamp_t old_now = m->now;
765       main_get_time_ctx(m);
766       m->idle_time += m->now - old_now;
767
768       if (n <= 0)
769         continue;
770
771       // Relink all files with a pending event to file_active_list
772 #ifdef CONFIG_UCW_EPOLL
773       for (int i=0; i<n; i++)
774         {
775           struct epoll_event *e = &m->epoll_events[i];
776           struct main_file *fi = e->data.ptr;
777           clist_remove(&fi->n);
778           clist_add_tail(&m->file_active_list, &fi->n);
779           fi->events = e->events;
780         }
781 #else
782       struct pollfd *p = m->poll_table;
783       struct main_file **pf = m->poll_file_table;
784       for (uns i=0; i < m->file_cnt; i++)
785         if (p[i].revents)
786           {
787             struct main_file *fi = pf[i];
788             clist_remove(&fi->n);
789             clist_add_tail(&m->file_active_list, &fi->n);
790             fi->events = p[i].revents;
791           }
792 #endif
793
794       /*
795        *  Process the buffered file events. This is pretty tricky, since
796        *  user callbacks can modify the file structure or even destroy it.
797        *  In such cases, we detect that the structure was relinked and stop
798        *  processing its events, leaving them for the next iteration of the
799        *  main loop.
800        */
801       struct main_file *fi;
802       while (fi = clist_head(&m->file_active_list))
803         {
804           if (fi->events & (POLLIN | POLLHUP | POLLERR))
805             {
806               fi->events &= ~(POLLIN | POLLHUP | POLLERR);
807               do
808                 DBG("MAIN: Read event on fd %d", fi->fd);
809               while (fi->read_handler && fi->read_handler(fi));
810               continue;
811             }
812           if (fi->events & (POLLOUT | POLLERR))
813             {
814               fi->events &= ~(POLLOUT | POLLERR);
815               do
816                 DBG("MAIN: Write event on fd %d", fi->fd);
817               while (fi->write_handler && fi->write_handler(fi));
818               continue;
819             }
820           clist_remove(&fi->n);
821           clist_add_tail(&m->file_list, &fi->n);
822         }
823     }
824 }