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 xfree(m->epoll_events);
131 GARY_FREE(m->poll_table);
132 GARY_FREE(m->poll_file_table);
135 if (m->sigchld_handler)
137 signal_del_ctx(m, m->sigchld_handler);
138 xfree(m->sigchld_handler);
140 if (m->sig_pipe_file)
142 file_del_ctx(m, m->sig_pipe_file);
143 xfree(m->sig_pipe_file);
145 if (m->sig_pipe_recv >= 0)
147 close(m->sig_pipe_recv);
148 close(m->sig_pipe_send);
153 main_do_delete(struct main_context *m)
155 GARY_FREE(m->timer_table);
160 main_delete(struct main_context *m)
165 main_prepare_delete(m);
166 ASSERT(clist_empty(&m->file_list));
167 ASSERT(clist_empty(&m->file_active_list));
168 #ifdef CONFIG_UCW_EPOLL
169 ASSERT(clist_empty(&m->file_recalc_list));
171 ASSERT(clist_empty(&m->hook_list));
172 ASSERT(clist_empty(&m->hook_done_list));
173 ASSERT(clist_empty(&m->process_list));
174 ASSERT(clist_empty(&m->signal_list));
175 ASSERT(!count_timers(m));
180 main_destroy(struct main_context *m)
184 main_prepare_delete(m);
187 clist_insert_list_after(&m->file_active_list, m->file_list.head.prev);
188 #ifdef CONFIG_UCW_EPOLL
189 clist_insert_list_after(&m->file_recalc_list, m->file_list.head.prev);
191 CLIST_FOR_EACH(struct main_file *, f, m->file_list)
197 struct main_context *
198 main_switch_context(struct main_context *m)
200 struct ucwlib_context *c = ucwlib_thread_context();
201 struct main_context *m0 = c->main_context;
204 * Not only we need to switch the signal sets of the two contexts,
205 * but it is also necessary to avoid invoking a signal handler
206 * in the middle of changing c->main_context.
208 if (m0 && !clist_empty(&m0->signal_list))
209 THREAD_SIGMASK(SIG_BLOCK, &m0->want_signals, NULL);
211 if (m && !clist_empty(&m->signal_list))
212 THREAD_SIGMASK(SIG_UNBLOCK, &m->want_signals, NULL);
220 struct main_context *m = main_switch_context(main_new());
227 main_delete(main_current_nocheck());
233 main_destroy(main_current_nocheck());
239 main_get_time_ctx(main_current());
243 timer_add(struct main_timer *tm, timestamp_t expires)
245 struct main_context *m = main_current();
249 GARY_INIT(m->timer_table, 1);
250 m->timer_table[0] = NULL;
254 DBG("MAIN: Setting timer %p (expire at now+%lld)", tm, (long long)(expires - m->now));
256 DBG("MAIN: Clearing timer %p", tm);
257 uns num_timers = count_timers(m);
258 if (tm->expires < expires)
262 tm->expires = expires;
263 tm->index = num_timers + 1;
264 *GARY_PUSH(m->timer_table, 1) = tm;
265 HEAP_INSERT(struct main_timer *, m->timer_table, tm->index, MAIN_TIMER_LESS, MAIN_TIMER_SWAP);
269 tm->expires = expires;
270 HEAP_INCREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
273 else if (tm->expires > expires)
277 ASSERT(tm->index && tm->index <= num_timers);
278 HEAP_DELETE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
281 GARY_POP(m->timer_table, 1);
285 tm->expires = expires;
286 HEAP_DECREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
292 timer_add_rel(struct main_timer *tm, timestamp_t expires_delta)
294 struct main_context *m = main_current();
295 return timer_add(tm, m->now + expires_delta);
299 timer_del(struct main_timer *tm)
305 file_want_events(struct main_file *fi)
308 if (fi->read_handler)
309 events |= POLLIN | POLLHUP | POLLERR;
310 if (fi->write_handler)
311 events |= POLLOUT | POLLERR;
316 file_add(struct main_file *fi)
318 struct main_context *m = main_current();
320 DBG("MAIN: Adding file %p (fd=%d)", fi, fi->fd);
321 ASSERT(!clist_is_linked(&fi->n));
322 clist_add_tail(&m->file_list, &fi->n);
324 #ifdef CONFIG_UCW_EPOLL
325 struct epoll_event evt = {
326 .events = file_want_events(fi),
329 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, fi->fd, &evt) < 0)
330 die("epoll_ctl() failed: %m");
331 fi->last_want_events = evt.events;
333 m->poll_table_obsolete = 1;
335 if (fcntl(fi->fd, F_SETFL, O_NONBLOCK) < 0)
336 msg(L_ERROR, "Error setting fd %d to non-blocking mode: %m. Keep fingers crossed.", fi->fd);
340 file_chg(struct main_file *fi)
342 #ifdef CONFIG_UCW_EPOLL
343 clist_remove(&fi->n);
344 clist_add_tail(&main_current()->file_recalc_list, &fi->n);
346 struct pollfd *p = fi->pollfd;
348 p->events = file_want_events(fi);
353 file_del_ctx(struct main_context *m, struct main_file *fi)
355 // XXX: Can be called on a non-current context
356 DBG("MAIN: Deleting file %p (fd=%d)", fi, fi->fd);
358 ASSERT(clist_is_linked(&fi->n));
359 clist_unlink(&fi->n);
361 #ifdef CONFIG_UCW_EPOLL
362 if (m->epoll_fd >= 0 && epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, fi->fd, NULL) < 0)
363 die("epoll_ctl() failed: %m");
365 m->poll_table_obsolete = 1;
370 file_del(struct main_file *fi)
372 file_del_ctx(main_current(), fi);
376 hook_add(struct main_hook *ho)
378 struct main_context *m = main_current();
380 DBG("MAIN: Adding hook %p", ho);
381 ASSERT(!clist_is_linked(&ho->n));
382 clist_add_tail(&m->hook_list, &ho->n);
386 hook_del(struct main_hook *ho)
388 DBG("MAIN: Deleting hook %p", ho);
389 ASSERT(clist_is_linked(&ho->n));
390 clist_unlink(&ho->n);
394 sigchld_received(struct main_signal *sg UNUSED)
396 struct main_context *m = main_current();
400 while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
402 DBG("MAIN: Child %d exited with status %x", pid, stat);
403 CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
408 format_exit_status(pr->status_msg, pr->status);
409 DBG("MAIN: Calling process exit handler");
417 process_add(struct main_process *mp)
419 struct main_context *m = main_current();
421 DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
422 ASSERT(!clist_is_linked(&mp->n));
424 clist_add_tail(&m->process_list, &mp->n);
425 if (!m->sigchld_handler)
427 struct main_signal *sg = xmalloc_zero(sizeof(*sg));
428 m->sigchld_handler = sg;
429 sg->signum = SIGCHLD;
430 sg->handler = sigchld_received;
436 process_del(struct main_process *mp)
438 DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
439 ASSERT(clist_is_linked(&mp->n));
440 clist_unlink(&mp->n);
444 process_fork(struct main_process *mp)
449 DBG("MAIN: Fork failed");
451 format_exit_status(mp->status_msg, -1);
459 DBG("MAIN: Forked process %d", (int) pid);
467 pipe_read_handler(struct main_file *mf UNUSED)
469 struct main_context *m = main_current();
471 int n = read(m->sig_pipe_recv, &signum, sizeof(signum));
476 msg(L_ERROR, "Error reading signal pipe: %m");
479 ASSERT(n == sizeof(signum));
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);
486 if (sg->signum == signum)
488 DBG("MAIN: Sigpipe: invoking handler %p", sg);
489 clist_insert_after(&iter.n, &sg->n);
491 sg = clist_next(&m->signal_list, &iter.n);
492 clist_remove(&iter.n);
495 sg = clist_next(&m->signal_list, &sg->n);
502 pipe_configure(int fd)
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);
510 pipe_setup(struct main_context *m)
512 DBG("MAIN: Sigpipe: Setting up the pipe");
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];
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;
530 signal_handler_pipe(int signum)
532 struct main_context *m = main_current();
534 msg(L_DEBUG | L_SIGHANDLER, "MAIN: Sigpipe: sending signal %d down the drain", signum);
536 write(m->sig_pipe_send, &signum, sizeof(signum));
540 signal_add(struct main_signal *ms)
542 struct main_context *m = main_current();
544 DBG("MAIN: Adding signal %p (sig=%d)", ms, ms->signum);
546 ASSERT(!clist_is_linked(&ms->n));
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)
552 struct sigaction sa = {
553 .sa_handler = signal_handler_pipe,
554 .sa_flags = SA_NOCLDSTOP | SA_RESTART,
556 sigaction(ms->signum, &sa, NULL);
560 sigaddset(&ss, ms->signum);
561 THREAD_SIGMASK(SIG_UNBLOCK, &ss, NULL);
562 sigaddset(&m->want_signals, ms->signum);
566 signal_del_ctx(struct main_context *m, struct main_signal *ms)
568 // XXX: Can be called on a non-current context
569 DBG("MAIN: Deleting signal %p (sig=%d)", ms, ms->signum);
571 ASSERT(clist_is_linked(&ms->n));
572 clist_unlink(&ms->n);
575 CLIST_FOR_EACH(struct main_signal *, s, m->signal_list)
576 if (s->signum == ms->signum)
580 if (main_is_current(m))
584 sigaddset(&ss, ms->signum);
585 THREAD_SIGMASK(SIG_BLOCK, &ss, NULL);
587 sigdelset(&m->want_signals, ms->signum);
592 signal_del(struct main_signal *ms)
594 signal_del_ctx(main_current(), ms);
600 file_debug(struct main_file *fi)
602 msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p)",
603 fi, fi->fd, fi->read_handler, fi->write_handler, fi->data);
607 hook_debug(struct main_hook *ho)
609 msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
613 signal_debug(struct main_signal *sg)
616 msg(L_DEBUG, "\t\t(placeholder)");
618 msg(L_DEBUG, "\t\t%p (sig %d, func %p, data %p)", sg, sg->signum, sg->handler, sg->data);
622 timer_debug_ctx(struct main_context *m, struct main_timer *tm)
624 msg(L_DEBUG, "\t\t%p (expires %lld, data %p)", tm, (long long)(tm->expires - m->now), tm->data);
628 timer_debug(struct main_timer *tm)
630 timer_debug_ctx(main_current(), tm);
634 process_debug(struct main_process *pr)
636 msg(L_DEBUG, "\t\t%p (pid %d, func %p, data %p)", pr, pr->pid, pr->handler, pr->data);
640 main_debug_context(struct main_context *m UNUSED)
642 msg(L_DEBUG, "### Main loop status on %lld", (long long) m->now);
643 msg(L_DEBUG, "\tActive timers:");
644 uns num_timers = count_timers(m);
645 for (uns i = 1; i <= num_timers; i++)
646 timer_debug(m->timer_table[i]);
647 msg(L_DEBUG, "\tActive files:");
648 CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
650 CLIST_FOR_EACH(struct main_file *, fi, m->file_active_list)
652 #ifdef CONFIG_UCW_EPOLL
653 CLIST_FOR_EACH(struct main_file *, fi, m->file_recalc_list)
656 msg(L_DEBUG, "\tActive hooks:");
657 CLIST_FOR_EACH(struct main_hook *, ho, m->hook_done_list)
659 CLIST_FOR_EACH(struct main_hook *, ho, m->hook_list)
661 msg(L_DEBUG, "\tActive processes:");
662 CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
664 msg(L_DEBUG, "\tActive signal catchers:");
665 CLIST_FOR_EACH(struct main_signal *, sg, m->signal_list)
672 void file_debug(struct main_file *fi UNUSED) { }
673 void hook_debug(struct main_hook *ho UNUSED) { }
674 void signal_debug(struct main_signal *sg UNUSED) { }
675 void timer_debug(struct main_timer *tm UNUSED) { }
676 void process_debug(struct main_process *pr UNUSED) { }
677 void main_debug_context(struct main_context *m UNUSED) { }
682 process_timers(struct main_context *m)
684 struct main_timer *tm;
685 while (count_timers(m) && (tm = m->timer_table[1])->expires <= m->now)
687 DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(m->now - tm->expires));
692 static enum main_hook_return
693 process_hooks(struct main_context *m)
695 int hook_min = HOOK_RETRY;
696 int hook_max = HOOK_SHUTDOWN;
697 struct main_hook *ho;
699 while (ho = clist_remove_head(&m->hook_list))
701 clist_add_tail(&m->hook_done_list, &ho->n);
702 DBG("MAIN: Hook %p", ho);
703 int ret = ho->handler(ho);
704 hook_min = MIN(hook_min, ret);
705 hook_max = MAX(hook_max, ret);
707 clist_move(&m->hook_list, &m->hook_done_list);
708 if (hook_min == HOOK_SHUTDOWN ||
709 hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
712 DBG("MAIN: Shut down by %s", m->shutdown ? "main_shut_down" : "a hook");
713 return HOOK_SHUTDOWN;
715 if (hook_max == HOOK_RETRY)
721 #ifdef CONFIG_UCW_EPOLL
724 recalc_files(struct main_context *m)
726 struct main_file *fi;
728 while (fi = clist_remove_head(&m->file_recalc_list))
730 struct epoll_event evt = {
731 .events = file_want_events(fi),
734 if (evt.events != fi->last_want_events)
736 DBG("MAIN: Changing requested events for fd %d to %x", fi->fd, evt.events);
737 fi->last_want_events = evt.events;
738 if (epoll_ctl(main_current()->epoll_fd, EPOLL_CTL_MOD, fi->fd, &evt) < 0)
739 die("epoll_ctl() failed: %m");
741 clist_add_tail(&m->file_list, &fi->n);
748 rebuild_poll_table(struct main_context *m)
750 GARY_INIT_OR_RESIZE(m->poll_table, m->file_cnt);
751 GARY_INIT_OR_RESIZE(m->poll_file_table, m->file_cnt);
752 DBG("MAIN: Rebuilding poll table: %d entries", m->file_cnt);
754 struct pollfd *p = m->poll_table;
755 struct main_file **pf = m->poll_file_table;
756 CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
759 p->events = file_want_events(fi);
763 m->poll_table_obsolete = 0;
771 DBG("MAIN: Entering main_loop");
772 struct main_context *m = main_current();
774 main_get_time_ctx(m);
779 timestamp_t wake = m->now + 1000000000;
781 switch (process_hooks(m))
795 wake = MIN(wake, m->timer_table[1]->expires);
796 main_get_time_ctx(m);
797 timeout = ((wake > m->now) ? wake - m->now : 0);
800 #ifdef CONFIG_UCW_EPOLL
802 DBG("MAIN: Epoll for %d fds and timeout %d ms", m->file_cnt, timeout);
803 int n = epoll_wait(m->epoll_fd, m->epoll_events, EPOLL_BUF_SIZE, timeout);
805 if (m->poll_table_obsolete)
806 rebuild_poll_table(m);
807 DBG("MAIN: Poll for %d fds and timeout %d ms", m->file_cnt, timeout);
808 int n = poll(m->poll_table, m->file_cnt, timeout);
811 DBG("\t-> %d events", n);
812 if (n < 0 && errno != EAGAIN && errno != EINTR)
813 die("(e)poll failed: %m");
814 timestamp_t old_now = m->now;
815 main_get_time_ctx(m);
816 m->idle_time += m->now - old_now;
826 // Relink all files with a pending event to file_active_list
827 #ifdef CONFIG_UCW_EPOLL
828 for (int i=0; i<n; i++)
830 struct epoll_event *e = &m->epoll_events[i];
831 struct main_file *fi = e->data.ptr;
832 clist_remove(&fi->n);
833 clist_add_tail(&m->file_active_list, &fi->n);
834 fi->events = e->events;
837 struct pollfd *p = m->poll_table;
838 struct main_file **pf = m->poll_file_table;
839 for (uns i=0; i < m->file_cnt; i++)
842 struct main_file *fi = pf[i];
843 clist_remove(&fi->n);
844 clist_add_tail(&m->file_active_list, &fi->n);
845 fi->events = p[i].revents;
850 * Process the buffered file events. This is pretty tricky, since
851 * user callbacks can modify the file structure or even destroy it.
852 * In such cases, we detect that the structure was relinked and stop
853 * processing its events, leaving them for the next iteration of the
856 struct main_file *fi;
857 while (fi = clist_head(&m->file_active_list))
859 if (fi->events & (POLLIN | POLLHUP | POLLERR))
861 fi->events &= ~(POLLIN | POLLHUP | POLLERR);
863 DBG("MAIN: Read event on fd %d", fi->fd);
864 while (fi->read_handler && fi->read_handler(fi));
867 if (fi->events & (POLLOUT | POLLERR))
869 fi->events &= ~(POLLOUT | POLLERR);
871 DBG("MAIN: Write event on fd %d", fi->fd);
872 while (fi->write_handler && fi->write_handler(fi));
875 clist_remove(&fi->n);
876 clist_add_tail(&m->file_list, &fi->n);
884 struct main_context *m = main_current();