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