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