2 * UCW Library -- Main Loop
4 * (c) 2004--2011 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
14 #include "ucw/mainloop.h"
15 #include "ucw/threads.h"
30 #ifdef CONFIG_UCW_THREADS
32 #define THREAD_SIGMASK pthread_sigmask
34 #define THREAD_SIGMASK sigprocmask
37 #ifdef CONFIG_UCW_EPOLL
38 #include <sys/epoll.h>
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))
44 #define EPOLL_BUF_SIZE 256
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);
50 main_get_time_ctx(struct main_context *m)
53 gettimeofday(&tv, NULL);
54 m->now_seconds = tv.tv_sec;
55 m->now = (timestamp_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
58 static struct main_context *
59 main_current_nocheck(void)
61 return ucwlib_thread_context()->main_context;
67 struct main_context *m = main_current_nocheck();
73 main_is_current(struct main_context *m)
75 return (m == main_current_nocheck());
79 count_timers(struct main_context *m)
82 return GARY_SIZE(m->timer_table) - 1;
90 struct main_context *m = xmalloc_zero(sizeof(*m));
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);
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);
106 m->poll_table_obsolete = 1;
108 main_get_time_ctx(m);
109 sigemptyset(&m->want_signals);
110 m->sig_pipe_recv = m->sig_pipe_send = -1;
116 main_prepare_delete(struct main_context *m)
119 * If the context is current, deactivate it first. But beware,
120 * we must not call functions that depend on the current context.
122 if (main_is_current(m))
123 main_switch_context(NULL);
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);
132 GARY_FREE(m->poll_table);
133 GARY_FREE(m->poll_file_table);
136 if (m->sigchld_handler)
138 signal_del_ctx(m, m->sigchld_handler);
139 xfree(m->sigchld_handler);
141 if (m->sig_pipe_file)
143 file_del_ctx(m, m->sig_pipe_file);
144 xfree(m->sig_pipe_file);
146 if (m->sig_pipe_recv >= 0)
148 close(m->sig_pipe_recv);
149 close(m->sig_pipe_send);
154 main_do_delete(struct main_context *m)
156 GARY_FREE(m->timer_table);
161 main_delete(struct main_context *m)
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));
178 main_destroy(struct main_context *m)
182 main_prepare_delete(m);
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);
189 CLIST_FOR_EACH(struct main_file *, f, m->file_list)
195 struct main_context *
196 main_switch_context(struct main_context *m)
198 struct ucwlib_context *c = ucwlib_thread_context();
199 struct main_context *m0 = c->main_context;
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.
206 if (m0 && !clist_empty(&m0->signal_list))
207 THREAD_SIGMASK(SIG_BLOCK, &m0->want_signals, NULL);
209 if (m && !clist_empty(&m->signal_list))
210 THREAD_SIGMASK(SIG_UNBLOCK, &m->want_signals, NULL);
218 struct main_context *m = main_switch_context(main_new());
225 main_delete(main_current_nocheck());
231 main_destroy(main_current_nocheck());
237 main_get_time_ctx(main_current());
241 timer_add(struct main_timer *tm, timestamp_t expires)
243 struct main_context *m = main_current();
247 GARY_INIT(m->timer_table, 1);
248 m->timer_table[0] = NULL;
252 DBG("MAIN: Setting timer %p (expire at now+%lld)", tm, (long long)(expires - m->now));
254 DBG("MAIN: Clearing timer %p", tm);
255 uns num_timers = count_timers(m);
256 if (tm->expires < expires)
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);
267 tm->expires = expires;
268 HEAP_INCREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
271 else if (tm->expires > expires)
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);
279 GARY_POP(m->timer_table, 1);
283 tm->expires = expires;
284 HEAP_DECREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
290 timer_add_rel(struct main_timer *tm, timestamp_t expires_delta)
292 struct main_context *m = main_current();
293 return timer_add(tm, m->now + expires_delta);
297 timer_del(struct main_timer *tm)
303 file_want_events(struct main_file *fi)
306 if (fi->read_handler)
307 events |= POLLIN | POLLHUP | POLLERR;
308 if (fi->write_handler)
309 events |= POLLOUT | POLLERR;
314 file_add(struct main_file *fi)
316 struct main_context *m = main_current();
318 DBG("MAIN: Adding file %p (fd=%d)", fi, fi->fd);
319 ASSERT(!clist_is_linked(&fi->n));
320 clist_add_tail(&m->file_list, &fi->n);
322 #ifdef CONFIG_UCW_EPOLL
323 struct epoll_event evt = {
324 .events = file_want_events(fi),
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;
331 m->poll_table_obsolete = 1;
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);
338 file_chg(struct main_file *fi)
340 #ifdef CONFIG_UCW_EPOLL
341 clist_remove(&fi->n);
342 clist_add_tail(&main_current()->file_recalc_list, &fi->n);
344 struct pollfd *p = fi->pollfd;
346 p->events = file_want_events(fi);
351 file_del_ctx(struct main_context *m, struct main_file *fi)
353 // XXX: Can be called on a non-current context
354 DBG("MAIN: Deleting file %p (fd=%d)", fi, fi->fd);
356 ASSERT(clist_is_linked(&fi->n));
357 clist_unlink(&fi->n);
359 #ifdef CONFIG_UCW_EPOLL
360 if (m->epoll_fd >= 0 && epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, fi->fd, NULL) < 0)
361 die("epoll_ctl() failed: %m");
363 m->poll_table_obsolete = 1;
368 file_del(struct main_file *fi)
370 file_del_ctx(main_current(), fi);
374 hook_add(struct main_hook *ho)
376 struct main_context *m = main_current();
378 DBG("MAIN: Adding hook %p", ho);
379 ASSERT(!clist_is_linked(&ho->n));
380 clist_add_tail(&m->hook_list, &ho->n);
384 hook_del(struct main_hook *ho)
386 DBG("MAIN: Deleting hook %p", ho);
387 ASSERT(clist_is_linked(&ho->n));
388 clist_unlink(&ho->n);
392 sigchld_received(struct main_signal *sg UNUSED)
394 struct main_context *m = main_current();
398 while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
400 DBG("MAIN: Child %d exited with status %x", pid, stat);
401 CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
406 format_exit_status(pr->status_msg, pr->status);
407 DBG("MAIN: Calling process exit handler");
415 process_add(struct main_process *mp)
417 struct main_context *m = main_current();
419 DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
420 ASSERT(!clist_is_linked(&mp->n));
422 clist_add_tail(&m->process_list, &mp->n);
423 if (!m->sigchld_handler)
425 struct main_signal *sg = xmalloc_zero(sizeof(*sg));
426 m->sigchld_handler = sg;
427 sg->signum = SIGCHLD;
428 sg->handler = sigchld_received;
434 process_del(struct main_process *mp)
436 DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
437 ASSERT(clist_is_linked(&mp->n));
438 clist_unlink(&mp->n);
442 process_fork(struct main_process *mp)
447 DBG("MAIN: Fork failed");
449 format_exit_status(mp->status_msg, -1);
457 DBG("MAIN: Forked process %d", (int) pid);
465 pipe_read_handler(struct main_file *mf UNUSED)
467 struct main_context *m = main_current();
469 int n = read(m->sig_pipe_recv, &signum, sizeof(signum));
474 msg(L_ERROR, "Error reading signal pipe: %m");
477 ASSERT(n == sizeof(signum));
479 DBG("MAIN: Sigpipe: received signal %d", signum);
480 struct main_signal iter = { .signum = -1 };
481 struct main_signal *sg = clist_head(&m->signal_list);
484 if (sg->signum == signum)
486 DBG("MAIN: Sigpipe: invoking handler %p", sg);
487 clist_insert_after(&iter.n, &sg->n);
489 sg = clist_next(&m->signal_list, &iter.n);
490 clist_remove(&iter.n);
493 sg = clist_next(&m->signal_list, &sg->n);
500 pipe_configure(int fd)
503 if ((flags = fcntl(fd, F_GETFL)) < 0 || fcntl(fd, F_SETFL, flags|O_NONBLOCK) < 0)
504 die("Could not set file descriptor %d to non-blocking: %m", fd);
508 pipe_setup(struct main_context *m)
510 DBG("MAIN: Sigpipe: Setting up the pipe");
513 if (pipe(pipe_result) == -1)
514 die("Could not create signal pipe: %m");
515 pipe_configure(pipe_result[0]);
516 pipe_configure(pipe_result[1]);
517 m->sig_pipe_recv = pipe_result[0];
518 m->sig_pipe_send = pipe_result[1];
520 struct main_file *f = xmalloc_zero(sizeof(*f));
521 m->sig_pipe_file = f;
522 f->fd = m->sig_pipe_recv;
523 f->read_handler = pipe_read_handler;
528 signal_handler_pipe(int signum)
530 struct main_context *m = main_current();
532 msg(L_DEBUG | L_SIGHANDLER, "MAIN: Sigpipe: sending signal %d down the drain", signum);
534 write(m->sig_pipe_send, &signum, sizeof(signum));
538 signal_add(struct main_signal *ms)
540 struct main_context *m = main_current();
542 DBG("MAIN: Adding signal %p (sig=%d)", ms, ms->signum);
544 ASSERT(!clist_is_linked(&ms->n));
545 // Adding at the head of the list is better if we are in the middle of walking the list.
546 clist_add_head(&m->signal_list, &ms->n);
547 if (m->sig_pipe_recv < 0)
550 struct sigaction sa = {
551 .sa_handler = signal_handler_pipe,
552 .sa_flags = SA_NOCLDSTOP | SA_RESTART,
554 sigaction(ms->signum, &sa, NULL);
558 sigaddset(&ss, ms->signum);
559 THREAD_SIGMASK(SIG_UNBLOCK, &ss, NULL);
560 sigaddset(&m->want_signals, ms->signum);
564 signal_del_ctx(struct main_context *m, struct main_signal *ms)
566 // XXX: Can be called on a non-current context
567 DBG("MAIN: Deleting signal %p (sig=%d)", ms, ms->signum);
569 ASSERT(clist_is_linked(&ms->n));
570 clist_unlink(&ms->n);
573 CLIST_FOR_EACH(struct main_signal *, s, m->signal_list)
574 if (s->signum == ms->signum)
578 if (main_is_current(m))
582 sigaddset(&ss, ms->signum);
583 THREAD_SIGMASK(SIG_BLOCK, &ss, NULL);
585 sigdelset(&m->want_signals, ms->signum);
590 signal_del(struct main_signal *ms)
592 signal_del_ctx(main_current(), ms);
598 file_debug(struct main_file *fi)
600 msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p)",
601 fi, fi->fd, fi->read_handler, fi->write_handler, fi->data);
605 hook_debug(struct main_hook *ho)
607 msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
611 signal_debug(struct main_signal *sg)
614 msg(L_DEBUG, "\t\t(placeholder)");
616 msg(L_DEBUG, "\t\t%p (sig %d, func %p, data %p)", sg, sg->signum, sg->handler, sg->data);
620 timer_debug_ctx(struct main_context *m, struct main_timer *tm)
622 msg(L_DEBUG, "\t\t%p (expires %lld, data %p)", tm, (long long)(tm->expires - m->now), tm->data);
626 timer_debug(struct main_timer *tm)
628 timer_debug_ctx(main_current(), tm);
632 process_debug(struct main_process *pr)
634 msg(L_DEBUG, "\t\t%p (pid %d, func %p, data %p)", pr, pr->pid, pr->handler, pr->data);
638 main_debug_context(struct main_context *m UNUSED)
640 msg(L_DEBUG, "### Main loop status on %lld", (long long) m->now);
641 msg(L_DEBUG, "\tActive timers:");
642 uns num_timers = count_timers(m);
643 for (uns i = 1; i <= num_timers; i++)
644 timer_debug(m->timer_table[i]);
645 msg(L_DEBUG, "\tActive files:");
646 CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
648 CLIST_FOR_EACH(struct main_file *, fi, m->file_active_list)
650 #ifdef CONFIG_UCW_EPOLL
651 CLIST_FOR_EACH(struct main_file *, fi, m->file_recalc_list)
654 msg(L_DEBUG, "\tActive hooks:");
655 CLIST_FOR_EACH(struct main_hook *, ho, m->hook_done_list)
657 CLIST_FOR_EACH(struct main_hook *, ho, m->hook_list)
659 msg(L_DEBUG, "\tActive processes:");
660 CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
662 msg(L_DEBUG, "\tActive signal catchers:");
663 CLIST_FOR_EACH(struct main_signal *, sg, m->signal_list)
670 void file_debug(struct main_file *fi UNUSED) { }
671 void hook_debug(struct main_hook *ho UNUSED) { }
672 void signal_debug(struct main_signal *sg UNUSED) { }
673 void timer_debug(struct main_timer *tm UNUSED) { }
674 void process_debug(struct main_process *pr UNUSED) { }
675 void main_debug_context(struct main_context *m UNUSED) { }
680 process_timers(struct main_context *m)
682 struct main_timer *tm;
683 while (count_timers(m) && (tm = m->timer_table[1])->expires <= m->now)
685 DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(m->now - tm->expires));
690 static enum main_hook_return
691 process_hooks(struct main_context *m)
693 int hook_min = HOOK_RETRY;
694 int hook_max = HOOK_SHUTDOWN;
695 struct main_hook *ho;
697 while (ho = clist_remove_head(&m->hook_list))
699 clist_add_tail(&m->hook_done_list, &ho->n);
700 DBG("MAIN: Hook %p", ho);
701 int ret = ho->handler(ho);
702 hook_min = MIN(hook_min, ret);
703 hook_max = MAX(hook_max, ret);
705 clist_move(&m->hook_list, &m->hook_done_list);
706 if (hook_min == HOOK_SHUTDOWN ||
707 hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
710 DBG("MAIN: Shut down by %s", m->shutdown ? "main_shutdown" : "a hook");
711 return HOOK_SHUTDOWN;
713 if (hook_max == HOOK_RETRY)
719 #ifdef CONFIG_UCW_EPOLL
722 recalc_files(struct main_context *m)
724 struct main_file *fi;
726 while (fi = clist_remove_head(&m->file_recalc_list))
728 struct epoll_event evt = {
729 .events = file_want_events(fi),
732 if (evt.events != fi->last_want_events)
734 DBG("MAIN: Changing requested events for fd %d to %x", fi->fd, evt.events);
735 fi->last_want_events = evt.events;
736 if (epoll_ctl(main_current()->epoll_fd, EPOLL_CTL_MOD, fi->fd, &evt) < 0)
737 die("epoll_ctl() failed: %m");
739 clist_add_tail(&m->file_list, &fi->n);
746 rebuild_poll_table(struct main_context *m)
748 GARY_INIT_OR_RESIZE(m->poll_table, m->file_cnt);
749 GARY_INIT_OR_RESIZE(m->poll_file_table, m->file_cnt);
750 DBG("MAIN: Rebuilding poll table: %d entries", m->file_cnt);
752 struct pollfd *p = m->poll_table;
753 struct main_file **pf = m->poll_file_table;
754 CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
757 p->events = file_want_events(fi);
761 m->poll_table_obsolete = 0;
769 DBG("MAIN: Entering main_loop");
770 struct main_context *m = main_current();
772 main_get_time_ctx(m);
775 timestamp_t wake = m->now + 1000000000;
777 switch (process_hooks(m))
787 wake = MIN(wake, m->timer_table[1]->expires);
788 main_get_time_ctx(m);
789 int timeout = ((wake > m->now) ? wake - m->now : 0);
791 #ifdef CONFIG_UCW_EPOLL
793 DBG("MAIN: Epoll for %d fds and timeout %d ms", m->file_cnt, timeout);
794 int n = epoll_wait(m->epoll_fd, m->epoll_events, EPOLL_BUF_SIZE, timeout);
796 if (m->poll_table_obsolete)
797 rebuild_poll_table(m);
798 DBG("MAIN: Poll for %d fds and timeout %d ms", m->file_cnt, timeout);
799 int n = poll(m->poll_table, m->file_cnt, timeout);
802 DBG("\t-> %d events", n);
803 if (n < 0 && errno != EAGAIN && errno != EINTR)
804 die("(e)poll failed: %m");
805 timestamp_t old_now = m->now;
806 main_get_time_ctx(m);
807 m->idle_time += m->now - old_now;
812 // Relink all files with a pending event to file_active_list
813 #ifdef CONFIG_UCW_EPOLL
814 for (int i=0; i<n; i++)
816 struct epoll_event *e = &m->epoll_events[i];
817 struct main_file *fi = e->data.ptr;
818 clist_remove(&fi->n);
819 clist_add_tail(&m->file_active_list, &fi->n);
820 fi->events = e->events;
823 struct pollfd *p = m->poll_table;
824 struct main_file **pf = m->poll_file_table;
825 for (uns i=0; i < m->file_cnt; i++)
828 struct main_file *fi = pf[i];
829 clist_remove(&fi->n);
830 clist_add_tail(&m->file_active_list, &fi->n);
831 fi->events = p[i].revents;
836 * Process the buffered file events. This is pretty tricky, since
837 * user callbacks can modify the file structure or even destroy it.
838 * In such cases, we detect that the structure was relinked and stop
839 * processing its events, leaving them for the next iteration of the
842 struct main_file *fi;
843 while (fi = clist_head(&m->file_active_list))
845 if (fi->events & (POLLIN | POLLHUP | POLLERR))
847 fi->events &= ~(POLLIN | POLLHUP | POLLERR);
849 DBG("MAIN: Read event on fd %d", fi->fd);
850 while (fi->read_handler && fi->read_handler(fi));
853 if (fi->events & (POLLOUT | POLLERR))
855 fi->events &= ~(POLLOUT | POLLERR);
857 DBG("MAIN: Write event on fd %d", fi->fd);
858 while (fi->write_handler && fi->write_handler(fi));
861 clist_remove(&fi->n);
862 clist_add_tail(&m->file_list, &fi->n);