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 if (m->sigchld_handler)
87 signal_del(m->sigchld_handler);
89 file_del(m->sig_pipe_file);
90 if (m->sig_pipe_recv >= 0)
92 close(m->sig_pipe_recv);
93 close(m->sig_pipe_send);
95 ASSERT(clist_empty(&m->file_list));
96 ASSERT(clist_empty(&m->file_active_list));
97 ASSERT(clist_empty(&m->hook_list));
98 ASSERT(clist_empty(&m->hook_done_list));
99 ASSERT(clist_empty(&m->process_list));
100 ASSERT(clist_empty(&m->signal_list));
101 GARY_FREE(m->timer_table);
102 #ifdef CONFIG_UCW_EPOLL
103 ASSERT(clist_empty(&m->file_recalc_list));
104 xfree(m->epoll_events);
107 GARY_FREE(m->poll_table);
108 GARY_FREE(m->poll_file_table);
111 // FIXME: Some mechanism for cleaning up after fork()
114 struct main_context *
115 main_switch_context(struct main_context *m)
117 struct ucwlib_context *c = ucwlib_thread_context();
118 struct main_context *m0 = c->main_context;
121 * Not only we need to switch the signal sets of the two contexts,
122 * but it is also necessary to avoid invoking a signal handler
123 * in the middle of changing c->main_context.
125 if (m0 && !clist_empty(&m0->signal_list))
126 THREAD_SIGMASK(SIG_BLOCK, &m0->want_signals, NULL);
128 if (m && !clist_empty(&m->signal_list))
129 THREAD_SIGMASK(SIG_UNBLOCK, &m->want_signals, NULL);
134 struct main_context *
137 struct ucwlib_context *c = ucwlib_thread_context();
138 struct main_context *m = c->main_context;
146 struct main_context *m = main_switch_context(main_new());
153 struct main_context *m = main_switch_context(NULL);
160 do_main_get_time(main_current());
164 count_timers(struct main_context *m)
167 return GARY_SIZE(m->timer_table) - 1;
173 timer_add(struct main_timer *tm, timestamp_t expires)
175 struct main_context *m = main_current();
179 GARY_INIT(m->timer_table, 1);
180 m->timer_table[0] = NULL;
184 DBG("MAIN: Setting timer %p (expire at now+%lld)", tm, (long long)(expires - m->now));
186 DBG("MAIN: Clearing timer %p", tm);
187 uns num_timers = count_timers(m);
188 if (tm->expires < expires)
192 tm->expires = expires;
193 tm->index = num_timers + 1;
194 *GARY_PUSH(m->timer_table, 1) = tm;
195 HEAP_INSERT(struct main_timer *, m->timer_table, tm->index, MAIN_TIMER_LESS, MAIN_TIMER_SWAP);
199 tm->expires = expires;
200 HEAP_INCREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
203 else if (tm->expires > expires)
207 ASSERT(tm->index && tm->index <= num_timers);
208 HEAP_DELETE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
211 GARY_POP(m->timer_table, 1);
215 tm->expires = expires;
216 HEAP_DECREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
222 timer_add_rel(struct main_timer *tm, timestamp_t expires_delta)
224 struct main_context *m = main_current();
225 return timer_add(tm, m->now + expires_delta);
229 timer_del(struct main_timer *tm)
235 file_want_events(struct main_file *fi)
238 if (fi->read_handler)
239 events |= POLLIN | POLLHUP | POLLERR;
240 if (fi->write_handler)
241 events |= POLLOUT | POLLERR;
246 file_add(struct main_file *fi)
248 struct main_context *m = main_current();
250 DBG("MAIN: Adding file %p (fd=%d)", fi, fi->fd);
251 ASSERT(!clist_is_linked(&fi->n));
252 clist_add_tail(&m->file_list, &fi->n);
254 #ifdef CONFIG_UCW_EPOLL
255 struct epoll_event evt = {
256 .events = file_want_events(fi),
259 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, fi->fd, &evt) < 0)
260 die("epoll_ctl() failed: %m");
261 fi->last_want_events = evt.events;
263 m->poll_table_obsolete = 1;
265 if (fcntl(fi->fd, F_SETFL, O_NONBLOCK) < 0)
266 msg(L_ERROR, "Error setting fd %d to non-blocking mode: %m. Keep fingers crossed.", fi->fd);
270 file_chg(struct main_file *fi)
272 #ifdef CONFIG_UCW_EPOLL
273 clist_remove(&fi->n);
274 clist_add_tail(&main_current()->file_recalc_list, &fi->n);
276 struct pollfd *p = fi->pollfd;
278 p->events = file_want_events(fi);
283 file_del(struct main_file *fi)
285 struct main_context *m = main_current();
287 DBG("MAIN: Deleting file %p (fd=%d)", fi, fi->fd);
288 ASSERT(clist_is_linked(&fi->n));
289 clist_unlink(&fi->n);
291 #ifdef CONFIG_UCW_EPOLL
292 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, fi->fd, NULL) < 0)
293 die("epoll_ctl() failed: %m");
295 m->poll_table_obsolete = 1;
302 struct main_context *m = main_current();
304 CLIST_FOR_EACH(struct main_file *, f, m->file_list)
309 hook_add(struct main_hook *ho)
311 struct main_context *m = main_current();
313 DBG("MAIN: Adding hook %p", ho);
314 ASSERT(!clist_is_linked(&ho->n));
315 clist_add_tail(&m->hook_list, &ho->n);
319 hook_del(struct main_hook *ho)
321 DBG("MAIN: Deleting hook %p", ho);
322 ASSERT(clist_is_linked(&ho->n));
323 clist_unlink(&ho->n);
327 sigchld_received(struct main_signal *sg UNUSED)
329 struct main_context *m = main_current();
333 while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
335 DBG("MAIN: Child %d exited with status %x", pid, stat);
336 CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
341 format_exit_status(pr->status_msg, pr->status);
342 DBG("MAIN: Calling process exit handler");
350 process_add(struct main_process *mp)
352 struct main_context *m = main_current();
354 DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
355 ASSERT(!clist_is_linked(&mp->n));
357 clist_add_tail(&m->process_list, &mp->n);
358 if (!m->sigchld_handler)
360 struct main_signal *sg = xmalloc_zero(sizeof(*sg));
361 m->sigchld_handler = sg;
362 sg->signum = SIGCHLD;
363 sg->handler = sigchld_received;
369 process_del(struct main_process *mp)
371 DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
372 ASSERT(clist_is_linked(&mp->n));
373 clist_unlink(&mp->n);
377 process_fork(struct main_process *mp)
382 DBG("MAIN: Fork failed");
384 format_exit_status(mp->status_msg, -1);
392 DBG("MAIN: Forked process %d", (int) pid);
400 pipe_read_handler(struct main_file *mf UNUSED)
402 struct main_context *m = main_current();
404 int n = read(m->sig_pipe_recv, &signum, sizeof(signum));
409 msg(L_ERROR, "Error reading signal pipe: %m");
412 ASSERT(n == sizeof(signum));
414 DBG("MAIN: Sigpipe: received signal %d", signum);
415 struct main_signal iter = { .signum = -1 };
416 struct main_signal *sg = clist_head(&m->signal_list);
419 if (sg->signum == signum)
421 DBG("MAIN: Sigpipe: invoking handler %p", sg);
422 clist_insert_after(&iter.n, &sg->n);
424 sg = clist_next(&m->signal_list, &iter.n);
425 clist_remove(&iter.n);
428 sg = clist_next(&m->signal_list, &sg->n);
435 pipe_configure(int fd)
438 if ((flags = fcntl(fd, F_GETFL)) < 0 || fcntl(fd, F_SETFL, flags|O_NONBLOCK) < 0)
439 die("Could not set file descriptor %d to non-blocking: %m", fd);
443 pipe_setup(struct main_context *m)
445 DBG("MAIN: Sigpipe: Setting up the pipe");
448 if (pipe(pipe_result) == -1)
449 die("Could not create signal pipe: %m");
450 pipe_configure(pipe_result[0]);
451 pipe_configure(pipe_result[1]);
452 m->sig_pipe_recv = pipe_result[0];
453 m->sig_pipe_send = pipe_result[1];
455 struct main_file *f = xmalloc_zero(sizeof(*f));
456 m->sig_pipe_file = f;
457 f->fd = m->sig_pipe_recv;
458 f->read_handler = pipe_read_handler;
463 signal_handler_pipe(int signum)
465 struct main_context *m = main_current();
467 msg(L_DEBUG | L_SIGHANDLER, "MAIN: Sigpipe: sending signal %d down the drain", signum);
469 write(m->sig_pipe_send, &signum, sizeof(signum));
473 signal_add(struct main_signal *ms)
475 struct main_context *m = main_current();
477 DBG("MAIN: Adding signal %p (sig=%d)", ms, ms->signum);
479 ASSERT(!clist_is_linked(&ms->n));
480 // Adding at the head of the list is better if we are in the middle of walking the list.
481 clist_add_head(&m->signal_list, &ms->n);
482 if (m->sig_pipe_recv < 0)
485 struct sigaction sa = {
486 .sa_handler = signal_handler_pipe,
487 .sa_flags = SA_NOCLDSTOP | SA_RESTART,
489 sigaction(ms->signum, &sa, NULL);
493 sigaddset(&ss, ms->signum);
494 THREAD_SIGMASK(SIG_UNBLOCK, &ss, NULL);
495 sigaddset(&m->want_signals, ms->signum);
499 signal_del(struct main_signal *ms)
501 struct main_context *m = main_current();
503 DBG("MAIN: Deleting signal %p (sig=%d)", ms, ms->signum);
505 ASSERT(clist_is_linked(&ms->n));
506 clist_unlink(&ms->n);
509 CLIST_FOR_EACH(struct main_signal *, s, m->signal_list)
510 if (s->signum == ms->signum)
516 sigaddset(&ss, ms->signum);
517 THREAD_SIGMASK(SIG_BLOCK, &ss, NULL);
518 sigdelset(&m->want_signals, ms->signum);
523 main_debug_context(struct main_context *m UNUSED)
526 msg(L_DEBUG, "### Main loop status on %lld", (long long) m->now);
527 msg(L_DEBUG, "\tActive timers:");
528 uns num_timers = count_timers(m);
529 for (uns i = 1; i <= num_timers; i++)
531 struct main_timer *tm = m->timer_table[i];
532 msg(L_DEBUG, "\t\t%p (expires %lld, data %p)", tm, (long long)(tm->expires ? tm->expires - m->now : 999999), tm->data);
534 msg(L_DEBUG, "\tActive files:");
535 CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
536 msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p)",
537 fi, fi->fd, fi->read_handler, fi->write_handler, fi->data);
538 CLIST_FOR_EACH(struct main_file *, fi, m->file_active_list)
539 msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p) [pending events: %x]",
540 fi, fi->fd, fi->read_handler, fi->write_handler, fi->data, fi->events);
541 // FIXME: Can we display status of block_io requests somehow?
542 #ifdef CONFIG_UCW_EPOLL
543 CLIST_FOR_EACH(struct main_file *, fi, m->file_recalc_list)
544 msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p) [pending recalculation]",
545 fi, fi->fd, fi->read_handler, fi->write_handler, fi->data);
547 msg(L_DEBUG, "\tActive hooks:");
548 CLIST_FOR_EACH(struct main_hook *, ho, m->hook_done_list)
549 msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
550 CLIST_FOR_EACH(struct main_hook *, ho, m->hook_list)
551 msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
552 msg(L_DEBUG, "\tActive processes:");
553 CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
554 msg(L_DEBUG, "\t\t%p (pid %d, func %p, data %p)", pr, pr->pid, pr->handler, pr->data);
555 msg(L_DEBUG, "\tActive signal catchers:");
556 CLIST_FOR_EACH(struct main_signal *, sg, m->signal_list)
558 msg(L_DEBUG, "\t\t(placeholder)");
560 msg(L_DEBUG, "\t\t%p (sig %d, func %p, data %p)", sg, sg->signum, sg->handler, sg->data);
565 process_timers(struct main_context *m)
567 struct main_timer *tm;
568 while (count_timers(m) && (tm = m->timer_table[1])->expires <= m->now)
570 DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(m->now - tm->expires));
575 static enum main_hook_return
576 process_hooks(struct main_context *m)
578 int hook_min = HOOK_RETRY;
579 int hook_max = HOOK_SHUTDOWN;
580 struct main_hook *ho;
582 while (ho = clist_remove_head(&m->hook_list))
584 clist_add_tail(&m->hook_done_list, &ho->n);
585 DBG("MAIN: Hook %p", ho);
586 int ret = ho->handler(ho);
587 hook_min = MIN(hook_min, ret);
588 hook_max = MAX(hook_max, ret);
590 clist_move(&m->hook_list, &m->hook_done_list);
591 if (hook_min == HOOK_SHUTDOWN ||
592 hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
595 DBG("MAIN: Shut down by %s", m->shutdown ? "main_shutdown" : "a hook");
596 return HOOK_SHUTDOWN;
598 if (hook_max == HOOK_RETRY)
604 #ifdef CONFIG_UCW_EPOLL
607 recalc_files(struct main_context *m)
609 struct main_file *fi;
611 while (fi = clist_remove_head(&m->file_recalc_list))
613 struct epoll_event evt = {
614 .events = file_want_events(fi),
617 if (evt.events != fi->last_want_events)
619 DBG("MAIN: Changing requested events for fd %d to %x", fi->fd, evt.events);
620 fi->last_want_events = evt.events;
621 if (epoll_ctl(main_current()->epoll_fd, EPOLL_CTL_MOD, fi->fd, &evt) < 0)
622 die("epoll_ctl() failed: %m");
624 clist_add_tail(&m->file_list, &fi->n);
631 rebuild_poll_table(struct main_context *m)
633 GARY_INIT_OR_RESIZE(m->poll_table, m->file_cnt);
634 GARY_INIT_OR_RESIZE(m->poll_file_table, m->file_cnt);
635 DBG("MAIN: Rebuilding poll table: %d entries", m->file_cnt);
637 struct pollfd *p = m->poll_table;
638 struct main_file **pf = m->poll_file_table;
639 CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
642 p->events = file_want_events(fi);
646 m->poll_table_obsolete = 0;
654 DBG("MAIN: Entering main_loop");
655 struct main_context *m = main_current();
660 timestamp_t wake = m->now + 1000000000;
662 switch (process_hooks(m))
672 wake = MIN(wake, m->timer_table[1]->expires);
674 int timeout = ((wake > m->now) ? wake - m->now : 0);
676 #ifdef CONFIG_UCW_EPOLL
678 DBG("MAIN: Epoll for %d fds and timeout %d ms", m->file_cnt, timeout);
679 int n = epoll_wait(m->epoll_fd, m->epoll_events, EPOLL_BUF_SIZE, timeout);
681 if (m->poll_table_obsolete)
682 rebuild_poll_table(m);
683 DBG("MAIN: Poll for %d fds and timeout %d ms", m->file_cnt, timeout);
684 int n = poll(m->poll_table, m->file_cnt, timeout);
687 DBG("\t-> %d events", n);
688 if (n < 0 && errno != EAGAIN && errno != EINTR)
689 die("(e)poll failed: %m");
690 timestamp_t old_now = m->now;
692 m->idle_time += m->now - old_now;
697 // Relink all files with a pending event to file_active_list
698 #ifdef CONFIG_UCW_EPOLL
699 for (int i=0; i<n; i++)
701 struct epoll_event *e = &m->epoll_events[i];
702 struct main_file *fi = e->data.ptr;
703 clist_remove(&fi->n);
704 clist_add_tail(&m->file_active_list, &fi->n);
705 fi->events = e->events;
708 struct pollfd *p = m->poll_table;
709 struct main_file **pf = m->poll_file_table;
710 for (uns i=0; i < m->file_cnt; i++)
713 struct main_file *fi = pf[i];
714 clist_remove(&fi->n);
715 clist_add_tail(&m->file_active_list, &fi->n);
716 fi->events = p[i].revents;
721 * Process the buffered file events. This is pretty tricky, since
722 * user callbacks can modify the file structure or even destroy it.
723 * In such cases, we detect that the structure was relinked and stop
724 * processing its events, leaving them for the next iteration of the
727 struct main_file *fi;
728 while (fi = clist_head(&m->file_active_list))
730 if (fi->events & (POLLIN | POLLHUP | POLLERR))
732 fi->events &= ~(POLLIN | POLLHUP | POLLERR);
734 DBG("MAIN: Read event on fd %d", fi->fd);
735 while (fi->read_handler && fi->read_handler(fi));
738 if (fi->events & (POLLOUT | POLLERR))
740 fi->events &= ~(POLLOUT | POLLERR);
742 DBG("MAIN: Write event on fd %d", fi->fd);
743 while (fi->write_handler && fi->write_handler(fi));
746 clist_remove(&fi->n);
747 clist_add_tail(&m->file_list, &fi->n);