]> mj.ucw.cz Git - libucw.git/blob - ucw/mainloop.c
a8bf0e5e99eb40efe8e298d85f4523c1abde0405
[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
19 #include <stdio.h>
20 #include <string.h>
21 #include <stdlib.h>
22 #include <unistd.h>
23 #include <signal.h>
24 #include <fcntl.h>
25 #include <errno.h>
26 #include <time.h>
27 #include <sys/poll.h>
28 #include <sys/wait.h>
29 #include <sys/time.h>
30
31 #ifdef CONFIG_UCW_THREADS
32 #include <pthread.h>
33 #define THREAD_SIGMASK pthread_sigmask
34 #else
35 #define THREAD_SIGMASK sigprocmask
36 #endif
37
38 #ifdef CONFIG_UCW_EPOLL
39 #include <sys/epoll.h>
40 #endif
41
42 #define MAIN_TIMER_LESS(x,y) ((x)->expires < (y)->expires)
43 #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))
44
45 #define EPOLL_BUF_SIZE 256
46
47 static void file_del_ctx(struct main_context *m, struct main_file *fi);
48 static void signal_del_ctx(struct main_context *m, struct main_signal *ms);
49
50 static void
51 main_get_time_ctx(struct main_context *m)
52 {
53   m->now = get_timestamp();
54 }
55
56 static struct main_context *
57 main_current_nocheck(void)
58 {
59   return ucwlib_thread_context()->main_context;
60 }
61
62 struct main_context *
63 main_current(void)
64 {
65   struct main_context *m = main_current_nocheck();
66   ASSERT(m);
67   return m;
68 }
69
70 static int
71 main_is_current(struct main_context *m)
72 {
73   return (m == main_current_nocheck());
74 }
75
76 static inline uns
77 count_timers(struct main_context *m)
78 {
79   if (m->timer_table)
80     return GARY_SIZE(m->timer_table) - 1;
81   else
82     return 0;
83 }
84
85 struct main_context *
86 main_new(void)
87 {
88   struct main_context *m = xmalloc_zero(sizeof(*m));
89
90   DBG("MAIN: New context");
91   clist_init(&m->file_list);
92   clist_init(&m->file_active_list);
93   clist_init(&m->hook_list);
94   clist_init(&m->hook_done_list);
95   clist_init(&m->process_list);
96   clist_init(&m->signal_list);
97 #ifdef CONFIG_UCW_EPOLL
98   m->epoll_fd = epoll_create(64);
99   if (m->epoll_fd < 0)
100     die("epoll_create() failed: %m");
101   m->epoll_events = xmalloc(EPOLL_BUF_SIZE * sizeof(struct epoll_event));
102   clist_init(&m->file_recalc_list);
103 #else
104   m->poll_table_obsolete = 1;
105 #endif
106   main_get_time_ctx(m);
107   sigemptyset(&m->want_signals);
108   m->sig_pipe_recv = m->sig_pipe_send = -1;
109
110   return m;
111 }
112
113 static void
114 main_prepare_delete(struct main_context *m)
115 {
116   /*
117    *  If the context is current, deactivate it first. But beware,
118    *  we must not call functions that depend on the current context.
119    */
120   if (main_is_current(m))
121     main_switch_context(NULL);
122
123   // Close epoll descriptor early enough, it might be shared after fork!
124 #ifdef CONFIG_UCW_EPOLL
125   xfree(m->epoll_events);
126   close(m->epoll_fd);
127   m->epoll_fd = -1;
128 #else
129   GARY_FREE(m->poll_table);
130   GARY_FREE(m->poll_file_table);
131 #endif
132
133   if (m->sigchld_handler)
134     {
135       signal_del_ctx(m, m->sigchld_handler);
136       xfree(m->sigchld_handler);
137     }
138   if (m->sig_pipe_file)
139     {
140       file_del_ctx(m, m->sig_pipe_file);
141       xfree(m->sig_pipe_file);
142      }
143   if (m->sig_pipe_recv >= 0)
144     {
145       close(m->sig_pipe_recv);
146       close(m->sig_pipe_send);
147     }
148 }
149
150 static void
151 main_do_delete(struct main_context *m)
152 {
153   GARY_FREE(m->timer_table);
154   xfree(m);
155 }
156
157 void
158 main_delete(struct main_context *m)
159 {
160   if (!m)
161     return;
162
163   main_prepare_delete(m);
164   ASSERT(clist_empty(&m->file_list));
165   ASSERT(clist_empty(&m->file_active_list));
166 #ifdef CONFIG_UCW_EPOLL
167   ASSERT(clist_empty(&m->file_recalc_list));
168 #endif
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;
308   if (fi->write_handler)
309     events |= POLLOUT;
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(!file_is_active(fi));
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   if (!file_is_active(fi))
357     return;
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   if (hook_is_active(ho))
381     clist_unlink(&ho->n);
382   clist_add_tail(&m->hook_list, &ho->n);
383 }
384
385 void
386 hook_del(struct main_hook *ho)
387 {
388   DBG("MAIN: Deleting hook %p", ho);
389   if (hook_is_active(ho))
390     clist_unlink(&ho->n);
391 }
392
393 static void
394 sigchld_received(struct main_signal *sg UNUSED)
395 {
396   struct main_context *m = main_current();
397   int stat;
398   pid_t pid;
399
400   while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
401     {
402       DBG("MAIN: Child %d exited with status %x", pid, stat);
403       CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
404         if (pr->pid == pid)
405           {
406             pr->status = stat;
407             process_del(pr);
408             format_exit_status(pr->status_msg, pr->status);
409             DBG("MAIN: Calling process exit handler");
410             pr->handler(pr);
411             break;
412           }
413     }
414 }
415
416 void
417 process_add(struct main_process *mp)
418 {
419   struct main_context *m = main_current();
420
421   DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
422   ASSERT(!process_is_active(mp));
423   ASSERT(mp->handler);
424   clist_add_tail(&m->process_list, &mp->n);
425   if (!m->sigchld_handler)
426     {
427       struct main_signal *sg = xmalloc_zero(sizeof(*sg));
428       m->sigchld_handler = sg;
429       sg->signum = SIGCHLD;
430       sg->handler = sigchld_received;
431       signal_add(sg);
432     }
433 }
434
435 void
436 process_del(struct main_process *mp)
437 {
438   DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
439   if (process_is_active(mp))
440     clist_unlink(&mp->n);
441 }
442
443 int
444 process_fork(struct main_process *mp)
445 {
446   pid_t pid = fork();
447   if (pid < 0)
448     {
449       DBG("MAIN: Fork failed");
450       mp->status = -1;
451       format_exit_status(mp->status_msg, -1);
452       mp->handler(mp);
453       return 1;
454     }
455   else if (!pid)
456     return 0;
457   else
458     {
459       DBG("MAIN: Forked process %d", (int) pid);
460       mp->pid = pid;
461       process_add(mp);
462       return 1;
463     }
464 }
465
466 static int
467 pipe_read_handler(struct main_file *mf UNUSED)
468 {
469   struct main_context *m = main_current();
470   int signum;
471   int n = read(m->sig_pipe_recv, &signum, sizeof(signum));
472
473   if (n < 0)
474     {
475       if (errno != EAGAIN)
476         msg(L_ERROR, "Error reading signal pipe: %m");
477       return 0;
478     }
479   ASSERT(n == sizeof(signum));
480
481   DBG("MAIN: Sigpipe: received signal %d", signum);
482   struct main_signal iter = { .signum = -1 };
483   struct main_signal *sg = clist_head(&m->signal_list);
484   while (sg)
485     {
486       if (sg->signum == signum)
487         {
488           DBG("MAIN: Sigpipe: invoking handler %p", sg);
489           clist_insert_after(&iter.n, &sg->n);
490           sg->handler(sg);
491           sg = clist_next(&m->signal_list, &iter.n);
492           clist_remove(&iter.n);
493         }
494       else
495         sg = clist_next(&m->signal_list, &sg->n);
496     }
497
498   return 1;
499 }
500
501 static void
502 pipe_configure(int fd)
503 {
504   int flags;
505   if ((flags = fcntl(fd, F_GETFL)) < 0 || fcntl(fd, F_SETFL, flags|O_NONBLOCK) < 0)
506     die("Could not set file descriptor %d to non-blocking: %m", fd);
507 }
508
509 static void
510 pipe_setup(struct main_context *m)
511 {
512   DBG("MAIN: Sigpipe: Setting up the pipe");
513
514   int pipe_result[2];
515   if (pipe(pipe_result) == -1)
516     die("Could not create signal pipe: %m");
517   pipe_configure(pipe_result[0]);
518   pipe_configure(pipe_result[1]);
519   m->sig_pipe_recv = pipe_result[0];
520   m->sig_pipe_send = pipe_result[1];
521
522   struct main_file *f = xmalloc_zero(sizeof(*f));
523   m->sig_pipe_file = f;
524   f->fd = m->sig_pipe_recv;
525   f->read_handler = pipe_read_handler;
526   file_add(f);
527 }
528
529 static void
530 signal_handler_pipe(int signum)
531 {
532   struct main_context *m = main_current();
533 #ifdef LOCAL_DEBUG
534   msg(L_DEBUG | L_SIGHANDLER, "MAIN: Sigpipe: sending signal %d down the drain", signum);
535 #endif
536   write(m->sig_pipe_send, &signum, sizeof(signum));
537 }
538
539 void
540 signal_add(struct main_signal *ms)
541 {
542   struct main_context *m = main_current();
543
544   DBG("MAIN: Adding signal %p (sig=%d)", ms, ms->signum);
545
546   ASSERT(!signal_is_active(ms));
547   // Adding at the head of the list is better if we are in the middle of walking the list.
548   clist_add_head(&m->signal_list, &ms->n);
549   if (m->sig_pipe_recv < 0)
550     pipe_setup(m);
551
552   struct sigaction sa = {
553     .sa_handler = signal_handler_pipe,
554     .sa_flags = SA_NOCLDSTOP | SA_RESTART,
555   };
556   sigaction(ms->signum, &sa, NULL);
557
558   sigset_t ss;
559   sigemptyset(&ss);
560   sigaddset(&ss, ms->signum);
561   THREAD_SIGMASK(SIG_UNBLOCK, &ss, NULL);
562   sigaddset(&m->want_signals, ms->signum);
563 }
564
565 static void
566 signal_del_ctx(struct main_context *m, struct main_signal *ms)
567 {
568   // XXX: Can be called on a non-current context
569   DBG("MAIN: Deleting signal %p (sig=%d)", ms, ms->signum);
570
571   if (!signal_is_active(ms))
572     return;
573   clist_unlink(&ms->n);
574
575   int another = 0;
576   CLIST_FOR_EACH(struct main_signal *, s, m->signal_list)
577     if (s->signum == ms->signum)
578       another++;
579   if (!another)
580     {
581       if (main_is_current(m))
582         {
583           sigset_t ss;
584           sigemptyset(&ss);
585           sigaddset(&ss, ms->signum);
586           THREAD_SIGMASK(SIG_BLOCK, &ss, NULL);
587         }
588       sigdelset(&m->want_signals, ms->signum);
589     }
590 }
591
592 void
593 signal_del(struct main_signal *ms)
594 {
595   signal_del_ctx(main_current(), ms);
596 }
597
598 #ifdef CONFIG_UCW_DEBUG
599
600 void
601 file_debug(struct main_file *fi)
602 {
603   msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p)",
604     fi, fi->fd, fi->read_handler, fi->write_handler, fi->data);
605 }
606
607 void
608 hook_debug(struct main_hook *ho)
609 {
610   msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
611 }
612
613 void
614 signal_debug(struct main_signal *sg)
615 {
616   if (sg->signum < 0)
617     msg(L_DEBUG, "\t\t(placeholder)");
618   else
619     msg(L_DEBUG, "\t\t%p (sig %d, func %p, data %p)", sg, sg->signum, sg->handler, sg->data);
620 }
621
622 static void
623 timer_debug_ctx(struct main_context *m, struct main_timer *tm)
624 {
625   msg(L_DEBUG, "\t\t%p (expires %lld, data %p)", tm, (long long)(tm->expires - m->now), tm->data);
626 }
627
628 void
629 timer_debug(struct main_timer *tm)
630 {
631   timer_debug_ctx(main_current(), tm);
632 }
633
634 void
635 process_debug(struct main_process *pr)
636 {
637   msg(L_DEBUG, "\t\t%p (pid %d, func %p, data %p)", pr, pr->pid, pr->handler, pr->data);
638 }
639
640 void
641 main_debug_context(struct main_context *m UNUSED)
642 {
643   msg(L_DEBUG, "### Main loop status on %lld", (long long) m->now);
644   msg(L_DEBUG, "\tActive timers:");
645   uns num_timers = count_timers(m);
646   for (uns i = 1; i <= num_timers; i++)
647     timer_debug(m->timer_table[i]);
648   msg(L_DEBUG, "\tActive files:");
649   CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
650     file_debug(fi);
651   CLIST_FOR_EACH(struct main_file *, fi, m->file_active_list)
652     file_debug(fi);
653 #ifdef CONFIG_UCW_EPOLL
654   CLIST_FOR_EACH(struct main_file *, fi, m->file_recalc_list)
655     file_debug(fi);
656 #endif
657   msg(L_DEBUG, "\tActive hooks:");
658   CLIST_FOR_EACH(struct main_hook *, ho, m->hook_done_list)
659     hook_debug(ho);
660   CLIST_FOR_EACH(struct main_hook *, ho, m->hook_list)
661     hook_debug(ho);
662   msg(L_DEBUG, "\tActive processes:");
663   CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
664     process_debug(pr);
665   msg(L_DEBUG, "\tActive signal catchers:");
666   CLIST_FOR_EACH(struct main_signal *, sg, m->signal_list)
667     signal_debug(sg);
668 }
669
670 #else
671
672 // Stubs
673 void file_debug(struct main_file *fi UNUSED) { }
674 void hook_debug(struct main_hook *ho UNUSED) { }
675 void signal_debug(struct main_signal *sg UNUSED) { }
676 void timer_debug(struct main_timer *tm UNUSED) { }
677 void process_debug(struct main_process *pr UNUSED) { }
678 void main_debug_context(struct main_context *m UNUSED) { }
679
680 #endif
681
682 static void
683 process_timers(struct main_context *m)
684 {
685   struct main_timer *tm;
686   while (count_timers(m) && (tm = m->timer_table[1])->expires <= m->now)
687     {
688       DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(m->now - tm->expires));
689       tm->handler(tm);
690     }
691 }
692
693 static enum main_hook_return
694 process_hooks(struct main_context *m)
695 {
696   int hook_min = HOOK_RETRY;
697   int hook_max = HOOK_SHUTDOWN;
698   struct main_hook *ho;
699
700   while (ho = clist_remove_head(&m->hook_list))
701     {
702       clist_add_tail(&m->hook_done_list, &ho->n);
703       DBG("MAIN: Hook %p", ho);
704       int ret = ho->handler(ho);
705       hook_min = MIN(hook_min, ret);
706       hook_max = MAX(hook_max, ret);
707     }
708   clist_move(&m->hook_list, &m->hook_done_list);
709   if (hook_min == HOOK_SHUTDOWN ||
710     hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
711     m->shutdown)
712     {
713       DBG("MAIN: Shut down by %s", m->shutdown ? "main_shut_down" : "a hook");
714       return HOOK_SHUTDOWN;
715     }
716   if (hook_max == HOOK_RETRY)
717     return HOOK_RETRY;
718   else
719     return HOOK_IDLE;
720 }
721
722 #ifdef CONFIG_UCW_EPOLL
723
724 static void
725 recalc_files(struct main_context *m)
726 {
727   struct main_file *fi;
728
729   while (fi = clist_remove_head(&m->file_recalc_list))
730     {
731       struct epoll_event evt = {
732         .events = file_want_events(fi),
733         .data.ptr = fi,
734       };
735       if (evt.events != fi->last_want_events)
736         {
737           DBG("MAIN: Changing requested events for fd %d to %x", fi->fd, evt.events);
738           fi->last_want_events = evt.events;
739           if (epoll_ctl(main_current()->epoll_fd, EPOLL_CTL_MOD, fi->fd, &evt) < 0)
740             die("epoll_ctl() failed: %m");
741         }
742       clist_add_tail(&m->file_list, &fi->n);
743     }
744 }
745
746 #else
747
748 static void
749 rebuild_poll_table(struct main_context *m)
750 {
751   GARY_INIT_OR_RESIZE(m->poll_table, m->file_cnt);
752   GARY_INIT_OR_RESIZE(m->poll_file_table, m->file_cnt);
753   DBG("MAIN: Rebuilding poll table: %d entries", m->file_cnt);
754
755   struct pollfd *p = m->poll_table;
756   struct main_file **pf = m->poll_file_table;
757   CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
758     {
759       p->fd = fi->fd;
760       p->events = file_want_events(fi);
761       fi->pollfd = p++;
762       *pf++ = fi;
763     }
764   m->poll_table_obsolete = 0;
765 }
766
767 #endif
768
769 void
770 main_loop(void)
771 {
772   DBG("MAIN: Entering main_loop");
773   struct main_context *m = main_current();
774
775   main_get_time_ctx(m);
776   m->shutdown = 0;
777
778   for (;;)
779     {
780       timestamp_t wake = m->now + 1000000000;
781       process_timers(m);
782       switch (process_hooks(m))
783         {
784         case HOOK_SHUTDOWN:
785           return;
786         case HOOK_RETRY:
787           wake = 0;
788           break;
789         default: ;
790         }
791
792       int timeout = 0;
793       if (!m->single_step)
794         {
795           if (count_timers(m))
796             wake = MIN(wake, m->timer_table[1]->expires);
797           main_get_time_ctx(m);
798           timeout = ((wake > m->now) ? wake - m->now : 0);
799         }
800
801 #ifdef CONFIG_UCW_EPOLL
802       recalc_files(m);
803       DBG("MAIN: Epoll for %d fds and timeout %d ms", m->file_cnt, timeout);
804       int n = epoll_wait(m->epoll_fd, m->epoll_events, EPOLL_BUF_SIZE, timeout);
805 #else
806       if (m->poll_table_obsolete)
807         rebuild_poll_table(m);
808       DBG("MAIN: Poll for %d fds and timeout %d ms", m->file_cnt, timeout);
809       int n = poll(m->poll_table, m->file_cnt, timeout);
810 #endif
811
812       DBG("\t-> %d events", n);
813       if (n < 0 && errno != EAGAIN && errno != EINTR)
814         die("(e)poll failed: %m");
815       timestamp_t old_now = m->now;
816       main_get_time_ctx(m);
817       m->idle_time += m->now - old_now;
818
819       if (n <= 0)
820         {
821           if (m->single_step)
822             return;
823           else
824             continue;
825         }
826
827       // Relink all files with a pending event to file_active_list
828 #ifdef CONFIG_UCW_EPOLL
829       for (int i=0; i<n; i++)
830         {
831           struct epoll_event *e = &m->epoll_events[i];
832           struct main_file *fi = e->data.ptr;
833           clist_remove(&fi->n);
834           clist_add_tail(&m->file_active_list, &fi->n);
835           fi->events = e->events;
836         }
837 #else
838       struct pollfd *p = m->poll_table;
839       struct main_file **pf = m->poll_file_table;
840       for (uns i=0; i < m->file_cnt; i++)
841         if (p[i].revents)
842           {
843             struct main_file *fi = pf[i];
844             clist_remove(&fi->n);
845             clist_add_tail(&m->file_active_list, &fi->n);
846             fi->events = p[i].revents;
847           }
848 #endif
849
850       /*
851        *  Process the buffered file events. This is pretty tricky, since
852        *  user callbacks can modify the file structure or even destroy it.
853        *  In such cases, we detect that the structure was relinked and stop
854        *  processing its events, leaving them for the next iteration of the
855        *  main loop.
856        */
857       struct main_file *fi;
858       while (fi = clist_head(&m->file_active_list))
859         {
860           if (fi->read_handler && (fi->events & (POLLIN | POLLHUP)))
861             {
862               fi->events &= ~(POLLIN | POLLHUP);
863               do
864                 DBG("MAIN: Read event on fd %d", fi->fd);
865               while (fi->read_handler && fi->read_handler(fi));
866               continue;
867             }
868           if (fi->write_handler && (fi->events & (POLLOUT | POLLHUP | POLLERR)))
869             {
870               fi->events &= ~(POLLOUT | POLLHUP | POLLERR);
871               do
872                 DBG("MAIN: Write event on fd %d", fi->fd);
873               while (fi->write_handler && fi->write_handler(fi));
874               continue;
875             }
876           clist_remove(&fi->n);
877           clist_add_tail(&m->file_list, &fi->n);
878         }
879     }
880 }
881
882 void
883 main_step(void)
884 {
885   struct main_context *m = main_current();
886   m->single_step = 1;
887   main_loop();
888   m->single_step = 0;
889 }