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
47 do_main_get_time(struct main_context *m)
50 gettimeofday(&tv, NULL);
51 m->now_seconds = tv.tv_sec;
52 m->now = (timestamp_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
58 struct main_context *m = xmalloc_zero(sizeof(*m));
60 DBG("MAIN: New context");
61 clist_init(&m->file_list);
62 clist_init(&m->file_active_list);
63 clist_init(&m->hook_list);
64 clist_init(&m->hook_done_list);
65 clist_init(&m->process_list);
66 clist_init(&m->signal_list);
67 #ifdef CONFIG_UCW_EPOLL
68 m->epoll_fd = epoll_create(64);
70 die("epoll_create() failed: %m");
71 m->epoll_events = xmalloc(EPOLL_BUF_SIZE * sizeof(struct epoll_event *));
72 clist_init(&m->file_recalc_list);
74 m->poll_table_obsolete = 1;
77 sigemptyset(&m->want_signals);
78 m->sig_pipe_recv = m->sig_pipe_send = -1;
84 main_delete(struct main_context *m)
86 struct main_context *prev = main_switch_context(m);
88 if (m->sigchld_handler)
90 signal_del(m->sigchld_handler);
91 xfree(m->sigchld_handler);
95 file_del(m->sig_pipe_file);
96 xfree(m->sig_pipe_file);
98 if (m->sig_pipe_recv >= 0)
100 close(m->sig_pipe_recv);
101 close(m->sig_pipe_send);
103 ASSERT(clist_empty(&m->file_list));
104 ASSERT(clist_empty(&m->file_active_list));
105 ASSERT(clist_empty(&m->hook_list));
106 ASSERT(clist_empty(&m->hook_done_list));
107 ASSERT(clist_empty(&m->process_list));
108 ASSERT(clist_empty(&m->signal_list));
109 GARY_FREE(m->timer_table);
110 #ifdef CONFIG_UCW_EPOLL
111 ASSERT(clist_empty(&m->file_recalc_list));
112 xfree(m->epoll_events);
115 GARY_FREE(m->poll_table);
116 GARY_FREE(m->poll_file_table);
119 // FIXME: Some mechanism for cleaning up after fork()
121 main_switch_context((prev == m) ? NULL : prev);
124 struct main_context *
125 main_switch_context(struct main_context *m)
127 struct ucwlib_context *c = ucwlib_thread_context();
128 struct main_context *m0 = c->main_context;
131 * Not only we need to switch the signal sets of the two contexts,
132 * but it is also necessary to avoid invoking a signal handler
133 * in the middle of changing c->main_context.
135 if (m0 && !clist_empty(&m0->signal_list))
136 THREAD_SIGMASK(SIG_BLOCK, &m0->want_signals, NULL);
138 if (m && !clist_empty(&m->signal_list))
139 THREAD_SIGMASK(SIG_UNBLOCK, &m->want_signals, NULL);
144 struct main_context *
147 struct ucwlib_context *c = ucwlib_thread_context();
148 struct main_context *m = c->main_context;
156 struct main_context *m = main_switch_context(main_new());
163 main_delete(main_current());
169 do_main_get_time(main_current());
173 count_timers(struct main_context *m)
176 return GARY_SIZE(m->timer_table) - 1;
182 timer_add(struct main_timer *tm, timestamp_t expires)
184 struct main_context *m = main_current();
188 GARY_INIT(m->timer_table, 1);
189 m->timer_table[0] = NULL;
193 DBG("MAIN: Setting timer %p (expire at now+%lld)", tm, (long long)(expires - m->now));
195 DBG("MAIN: Clearing timer %p", tm);
196 uns num_timers = count_timers(m);
197 if (tm->expires < expires)
201 tm->expires = expires;
202 tm->index = num_timers + 1;
203 *GARY_PUSH(m->timer_table, 1) = tm;
204 HEAP_INSERT(struct main_timer *, m->timer_table, tm->index, MAIN_TIMER_LESS, MAIN_TIMER_SWAP);
208 tm->expires = expires;
209 HEAP_INCREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
212 else if (tm->expires > expires)
216 ASSERT(tm->index && tm->index <= num_timers);
217 HEAP_DELETE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
220 GARY_POP(m->timer_table, 1);
224 tm->expires = expires;
225 HEAP_DECREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
231 timer_add_rel(struct main_timer *tm, timestamp_t expires_delta)
233 struct main_context *m = main_current();
234 return timer_add(tm, m->now + expires_delta);
238 timer_del(struct main_timer *tm)
244 file_want_events(struct main_file *fi)
247 if (fi->read_handler)
248 events |= POLLIN | POLLHUP | POLLERR;
249 if (fi->write_handler)
250 events |= POLLOUT | POLLERR;
255 file_add(struct main_file *fi)
257 struct main_context *m = main_current();
259 DBG("MAIN: Adding file %p (fd=%d)", fi, fi->fd);
260 ASSERT(!clist_is_linked(&fi->n));
261 clist_add_tail(&m->file_list, &fi->n);
263 #ifdef CONFIG_UCW_EPOLL
264 struct epoll_event evt = {
265 .events = file_want_events(fi),
268 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, fi->fd, &evt) < 0)
269 die("epoll_ctl() failed: %m");
270 fi->last_want_events = evt.events;
272 m->poll_table_obsolete = 1;
274 if (fcntl(fi->fd, F_SETFL, O_NONBLOCK) < 0)
275 msg(L_ERROR, "Error setting fd %d to non-blocking mode: %m. Keep fingers crossed.", fi->fd);
279 file_chg(struct main_file *fi)
281 #ifdef CONFIG_UCW_EPOLL
282 clist_remove(&fi->n);
283 clist_add_tail(&main_current()->file_recalc_list, &fi->n);
285 struct pollfd *p = fi->pollfd;
287 p->events = file_want_events(fi);
292 file_del(struct main_file *fi)
294 struct main_context *m = main_current();
296 DBG("MAIN: Deleting file %p (fd=%d)", fi, fi->fd);
297 ASSERT(clist_is_linked(&fi->n));
298 clist_unlink(&fi->n);
300 #ifdef CONFIG_UCW_EPOLL
301 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, fi->fd, NULL) < 0)
302 die("epoll_ctl() failed: %m");
304 m->poll_table_obsolete = 1;
311 struct main_context *m = main_current();
313 CLIST_FOR_EACH(struct main_file *, f, m->file_list)
318 hook_add(struct main_hook *ho)
320 struct main_context *m = main_current();
322 DBG("MAIN: Adding hook %p", ho);
323 ASSERT(!clist_is_linked(&ho->n));
324 clist_add_tail(&m->hook_list, &ho->n);
328 hook_del(struct main_hook *ho)
330 DBG("MAIN: Deleting hook %p", ho);
331 ASSERT(clist_is_linked(&ho->n));
332 clist_unlink(&ho->n);
336 sigchld_received(struct main_signal *sg UNUSED)
338 struct main_context *m = main_current();
342 while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
344 DBG("MAIN: Child %d exited with status %x", pid, stat);
345 CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
350 format_exit_status(pr->status_msg, pr->status);
351 DBG("MAIN: Calling process exit handler");
359 process_add(struct main_process *mp)
361 struct main_context *m = main_current();
363 DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
364 ASSERT(!clist_is_linked(&mp->n));
366 clist_add_tail(&m->process_list, &mp->n);
367 if (!m->sigchld_handler)
369 struct main_signal *sg = xmalloc_zero(sizeof(*sg));
370 m->sigchld_handler = sg;
371 sg->signum = SIGCHLD;
372 sg->handler = sigchld_received;
378 process_del(struct main_process *mp)
380 DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
381 ASSERT(clist_is_linked(&mp->n));
382 clist_unlink(&mp->n);
386 process_fork(struct main_process *mp)
391 DBG("MAIN: Fork failed");
393 format_exit_status(mp->status_msg, -1);
401 DBG("MAIN: Forked process %d", (int) pid);
409 pipe_read_handler(struct main_file *mf UNUSED)
411 struct main_context *m = main_current();
413 int n = read(m->sig_pipe_recv, &signum, sizeof(signum));
418 msg(L_ERROR, "Error reading signal pipe: %m");
421 ASSERT(n == sizeof(signum));
423 DBG("MAIN: Sigpipe: received signal %d", signum);
424 struct main_signal iter = { .signum = -1 };
425 struct main_signal *sg = clist_head(&m->signal_list);
428 if (sg->signum == signum)
430 DBG("MAIN: Sigpipe: invoking handler %p", sg);
431 clist_insert_after(&iter.n, &sg->n);
433 sg = clist_next(&m->signal_list, &iter.n);
434 clist_remove(&iter.n);
437 sg = clist_next(&m->signal_list, &sg->n);
444 pipe_configure(int fd)
447 if ((flags = fcntl(fd, F_GETFL)) < 0 || fcntl(fd, F_SETFL, flags|O_NONBLOCK) < 0)
448 die("Could not set file descriptor %d to non-blocking: %m", fd);
452 pipe_setup(struct main_context *m)
454 DBG("MAIN: Sigpipe: Setting up the pipe");
457 if (pipe(pipe_result) == -1)
458 die("Could not create signal pipe: %m");
459 pipe_configure(pipe_result[0]);
460 pipe_configure(pipe_result[1]);
461 m->sig_pipe_recv = pipe_result[0];
462 m->sig_pipe_send = pipe_result[1];
464 struct main_file *f = xmalloc_zero(sizeof(*f));
465 m->sig_pipe_file = f;
466 f->fd = m->sig_pipe_recv;
467 f->read_handler = pipe_read_handler;
472 signal_handler_pipe(int signum)
474 struct main_context *m = main_current();
476 msg(L_DEBUG | L_SIGHANDLER, "MAIN: Sigpipe: sending signal %d down the drain", signum);
478 write(m->sig_pipe_send, &signum, sizeof(signum));
482 signal_add(struct main_signal *ms)
484 struct main_context *m = main_current();
486 DBG("MAIN: Adding signal %p (sig=%d)", ms, ms->signum);
488 ASSERT(!clist_is_linked(&ms->n));
489 // Adding at the head of the list is better if we are in the middle of walking the list.
490 clist_add_head(&m->signal_list, &ms->n);
491 if (m->sig_pipe_recv < 0)
494 struct sigaction sa = {
495 .sa_handler = signal_handler_pipe,
496 .sa_flags = SA_NOCLDSTOP | SA_RESTART,
498 sigaction(ms->signum, &sa, NULL);
502 sigaddset(&ss, ms->signum);
503 THREAD_SIGMASK(SIG_UNBLOCK, &ss, NULL);
504 sigaddset(&m->want_signals, ms->signum);
508 signal_del(struct main_signal *ms)
510 struct main_context *m = main_current();
512 DBG("MAIN: Deleting signal %p (sig=%d)", ms, ms->signum);
514 ASSERT(clist_is_linked(&ms->n));
515 clist_unlink(&ms->n);
518 CLIST_FOR_EACH(struct main_signal *, s, m->signal_list)
519 if (s->signum == ms->signum)
525 sigaddset(&ss, ms->signum);
526 THREAD_SIGMASK(SIG_BLOCK, &ss, NULL);
527 sigdelset(&m->want_signals, ms->signum);
532 main_debug_context(struct main_context *m UNUSED)
535 msg(L_DEBUG, "### Main loop status on %lld", (long long) m->now);
536 msg(L_DEBUG, "\tActive timers:");
537 uns num_timers = count_timers(m);
538 for (uns i = 1; i <= num_timers; i++)
540 struct main_timer *tm = m->timer_table[i];
541 msg(L_DEBUG, "\t\t%p (expires %lld, data %p)", tm, (long long)(tm->expires ? tm->expires - m->now : 999999), tm->data);
543 msg(L_DEBUG, "\tActive files:");
544 CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
545 msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p)",
546 fi, fi->fd, fi->read_handler, fi->write_handler, fi->data);
547 CLIST_FOR_EACH(struct main_file *, fi, m->file_active_list)
548 msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p) [pending events: %x]",
549 fi, fi->fd, fi->read_handler, fi->write_handler, fi->data, fi->events);
550 // FIXME: Can we display status of block_io requests somehow?
551 #ifdef CONFIG_UCW_EPOLL
552 CLIST_FOR_EACH(struct main_file *, fi, m->file_recalc_list)
553 msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p) [pending recalculation]",
554 fi, fi->fd, fi->read_handler, fi->write_handler, fi->data);
556 msg(L_DEBUG, "\tActive hooks:");
557 CLIST_FOR_EACH(struct main_hook *, ho, m->hook_done_list)
558 msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
559 CLIST_FOR_EACH(struct main_hook *, ho, m->hook_list)
560 msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
561 msg(L_DEBUG, "\tActive processes:");
562 CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
563 msg(L_DEBUG, "\t\t%p (pid %d, func %p, data %p)", pr, pr->pid, pr->handler, pr->data);
564 msg(L_DEBUG, "\tActive signal catchers:");
565 CLIST_FOR_EACH(struct main_signal *, sg, m->signal_list)
567 msg(L_DEBUG, "\t\t(placeholder)");
569 msg(L_DEBUG, "\t\t%p (sig %d, func %p, data %p)", sg, sg->signum, sg->handler, sg->data);
574 process_timers(struct main_context *m)
576 struct main_timer *tm;
577 while (count_timers(m) && (tm = m->timer_table[1])->expires <= m->now)
579 DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(m->now - tm->expires));
584 static enum main_hook_return
585 process_hooks(struct main_context *m)
587 int hook_min = HOOK_RETRY;
588 int hook_max = HOOK_SHUTDOWN;
589 struct main_hook *ho;
591 while (ho = clist_remove_head(&m->hook_list))
593 clist_add_tail(&m->hook_done_list, &ho->n);
594 DBG("MAIN: Hook %p", ho);
595 int ret = ho->handler(ho);
596 hook_min = MIN(hook_min, ret);
597 hook_max = MAX(hook_max, ret);
599 clist_move(&m->hook_list, &m->hook_done_list);
600 if (hook_min == HOOK_SHUTDOWN ||
601 hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
604 DBG("MAIN: Shut down by %s", m->shutdown ? "main_shutdown" : "a hook");
605 return HOOK_SHUTDOWN;
607 if (hook_max == HOOK_RETRY)
613 #ifdef CONFIG_UCW_EPOLL
616 recalc_files(struct main_context *m)
618 struct main_file *fi;
620 while (fi = clist_remove_head(&m->file_recalc_list))
622 struct epoll_event evt = {
623 .events = file_want_events(fi),
626 if (evt.events != fi->last_want_events)
628 DBG("MAIN: Changing requested events for fd %d to %x", fi->fd, evt.events);
629 fi->last_want_events = evt.events;
630 if (epoll_ctl(main_current()->epoll_fd, EPOLL_CTL_MOD, fi->fd, &evt) < 0)
631 die("epoll_ctl() failed: %m");
633 clist_add_tail(&m->file_list, &fi->n);
640 rebuild_poll_table(struct main_context *m)
642 GARY_INIT_OR_RESIZE(m->poll_table, m->file_cnt);
643 GARY_INIT_OR_RESIZE(m->poll_file_table, m->file_cnt);
644 DBG("MAIN: Rebuilding poll table: %d entries", m->file_cnt);
646 struct pollfd *p = m->poll_table;
647 struct main_file **pf = m->poll_file_table;
648 CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
651 p->events = file_want_events(fi);
655 m->poll_table_obsolete = 0;
663 DBG("MAIN: Entering main_loop");
664 struct main_context *m = main_current();
669 timestamp_t wake = m->now + 1000000000;
671 switch (process_hooks(m))
681 wake = MIN(wake, m->timer_table[1]->expires);
683 int timeout = ((wake > m->now) ? wake - m->now : 0);
685 #ifdef CONFIG_UCW_EPOLL
687 DBG("MAIN: Epoll for %d fds and timeout %d ms", m->file_cnt, timeout);
688 int n = epoll_wait(m->epoll_fd, m->epoll_events, EPOLL_BUF_SIZE, timeout);
690 if (m->poll_table_obsolete)
691 rebuild_poll_table(m);
692 DBG("MAIN: Poll for %d fds and timeout %d ms", m->file_cnt, timeout);
693 int n = poll(m->poll_table, m->file_cnt, timeout);
696 DBG("\t-> %d events", n);
697 if (n < 0 && errno != EAGAIN && errno != EINTR)
698 die("(e)poll failed: %m");
699 timestamp_t old_now = m->now;
701 m->idle_time += m->now - old_now;
706 // Relink all files with a pending event to file_active_list
707 #ifdef CONFIG_UCW_EPOLL
708 for (int i=0; i<n; i++)
710 struct epoll_event *e = &m->epoll_events[i];
711 struct main_file *fi = e->data.ptr;
712 clist_remove(&fi->n);
713 clist_add_tail(&m->file_active_list, &fi->n);
714 fi->events = e->events;
717 struct pollfd *p = m->poll_table;
718 struct main_file **pf = m->poll_file_table;
719 for (uns i=0; i < m->file_cnt; i++)
722 struct main_file *fi = pf[i];
723 clist_remove(&fi->n);
724 clist_add_tail(&m->file_active_list, &fi->n);
725 fi->events = p[i].revents;
730 * Process the buffered file events. This is pretty tricky, since
731 * user callbacks can modify the file structure or even destroy it.
732 * In such cases, we detect that the structure was relinked and stop
733 * processing its events, leaving them for the next iteration of the
736 struct main_file *fi;
737 while (fi = clist_head(&m->file_active_list))
739 if (fi->events & (POLLIN | POLLHUP | POLLERR))
741 fi->events &= ~(POLLIN | POLLHUP | POLLERR);
743 DBG("MAIN: Read event on fd %d", fi->fd);
744 while (fi->read_handler && fi->read_handler(fi));
747 if (fi->events & (POLLOUT | POLLERR))
749 fi->events &= ~(POLLOUT | POLLERR);
751 DBG("MAIN: Write event on fd %d", fi->fd);
752 while (fi->write_handler && fi->write_handler(fi));
755 clist_remove(&fi->n);
756 clist_add_tail(&m->file_list, &fi->n);