2 * UCW Library -- Main Loop
4 * (c) 2004--2010 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 #define MAIN_TIMER_LESS(x,y) ((x)->expires < (y)->expires)
38 #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))
41 do_main_get_time(struct main_context *m)
44 gettimeofday(&tv, NULL);
45 m->now_seconds = tv.tv_sec;
46 m->now = (timestamp_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
52 struct main_context *m = xmalloc_zero(sizeof(*m));
54 DBG("MAIN: New context");
55 clist_init(&m->file_list);
56 clist_init(&m->hook_list);
57 clist_init(&m->hook_done_list);
58 clist_init(&m->process_list);
59 clist_init(&m->signal_list);
60 m->poll_table_obsolete = 1;
62 sigemptyset(&m->want_signals);
63 m->sig_pipe_recv = m->sig_pipe_send = -1;
69 main_delete(struct main_context *m)
71 if (m->sigchld_handler)
72 signal_del(m->sigchld_handler);
74 file_del(m->sig_pipe_file);
75 if (m->sig_pipe_recv >= 0)
77 close(m->sig_pipe_recv);
78 close(m->sig_pipe_send);
80 ASSERT(clist_empty(&m->file_list));
81 ASSERT(clist_empty(&m->hook_list));
82 ASSERT(clist_empty(&m->hook_done_list));
83 ASSERT(clist_empty(&m->process_list));
84 ASSERT(clist_empty(&m->signal_list));
86 GARY_FREE(m->timer_table);
89 // FIXME: Some mechanism for cleaning up after fork()
93 main_switch_context(struct main_context *m)
95 struct ucwlib_context *c = ucwlib_thread_context();
96 struct main_context *m0 = c->main_context;
99 * Not only we need to switch the signal sets of the two contexts,
100 * but it is also necessary to avoid invoking a signal handler
101 * in the middle of changing c->main_context.
103 if (m0 && !clist_empty(&m0->signal_list))
104 THREAD_SIGMASK(SIG_BLOCK, &m0->want_signals, NULL);
106 if (m && !clist_empty(&m->signal_list))
107 THREAD_SIGMASK(SIG_UNBLOCK, &m->want_signals, NULL);
112 struct main_context *
115 struct ucwlib_context *c = ucwlib_thread_context();
116 struct main_context *m = c->main_context;
124 struct main_context *m = main_switch_context(main_new());
131 struct main_context *m = main_switch_context(NULL);
138 do_main_get_time(main_current());
142 count_timers(struct main_context *m)
144 return GARY_SIZE(m->timer_table) - 1;
148 timer_add(struct main_timer *tm, timestamp_t expires)
150 struct main_context *m = main_current();
154 GARY_INIT(m->timer_table, 1);
155 m->timer_table[0] = NULL;
159 DBG("MAIN: Setting timer %p (expire at now+%lld)", tm, (long long)(expires - m->now));
161 DBG("MAIN: Clearing timer %p", tm);
162 uns num_timers = count_timers(m);
163 if (tm->expires < expires)
167 tm->expires = expires;
168 tm->index = num_timers + 1;
169 *GARY_PUSH(m->timer_table, 1) = tm;
170 HEAP_INSERT(struct main_timer *, m->timer_table, tm->index, MAIN_TIMER_LESS, MAIN_TIMER_SWAP);
174 tm->expires = expires;
175 HEAP_INCREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
178 else if (tm->expires > expires)
182 ASSERT(tm->index && tm->index <= num_timers);
183 HEAP_DELETE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
186 GARY_POP(m->timer_table, 1);
190 tm->expires = expires;
191 HEAP_DECREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
197 timer_add_rel(struct main_timer *tm, timestamp_t expires_delta)
199 struct main_context *m = main_current();
200 return timer_add(tm, m->now + expires_delta);
204 timer_del(struct main_timer *tm)
210 file_timer_expired(struct main_timer *tm)
212 struct main_file *fi = tm->data;
213 timer_del(&fi->timer);
214 if (fi->error_handler)
215 fi->error_handler(fi, MFERR_TIMEOUT);
219 file_add(struct main_file *fi)
221 struct main_context *m = main_current();
223 DBG("MAIN: Adding file %p (fd=%d)", fi, fi->fd);
225 clist_add_tail(&m->file_list, &fi->n);
226 fi->timer.handler = file_timer_expired;
229 m->poll_table_obsolete = 1;
230 if (fcntl(fi->fd, F_SETFL, O_NONBLOCK) < 0)
231 msg(L_ERROR, "Error setting fd %d to non-blocking mode: %m. Keep fingers crossed.", fi->fd);
235 file_chg(struct main_file *fi)
237 struct pollfd *p = fi->pollfd;
241 if (fi->read_handler)
242 p->events |= POLLIN | POLLHUP | POLLERR;
243 if (fi->write_handler)
244 p->events |= POLLOUT | POLLERR;
249 file_del(struct main_file *fi)
251 struct main_context *m = main_current();
253 DBG("MAIN: Deleting file %p (fd=%d)", fi, fi->fd);
255 timer_del(&fi->timer);
256 clist_remove(&fi->n);
258 m->poll_table_obsolete = 1;
259 fi->n.next = fi->n.prev = NULL;
263 file_read_handler(struct main_file *fi)
265 while (fi->rpos < fi->rlen)
267 int l = read(fi->fd, fi->rbuf + fi->rpos, fi->rlen - fi->rpos);
268 DBG("MAIN: FD %d: read %d", fi->fd, l);
271 if (errno != EINTR && errno != EAGAIN && fi->error_handler)
272 fi->error_handler(fi, MFERR_READ);
279 DBG("MAIN: FD %d done read %d of %d", fi->fd, fi->rpos, fi->rlen);
280 fi->read_handler = NULL;
287 file_write_handler(struct main_file *fi)
289 while (fi->wpos < fi->wlen)
291 int l = write(fi->fd, fi->wbuf + fi->wpos, fi->wlen - fi->wpos);
292 DBG("MAIN: FD %d: write %d", fi->fd, l);
295 if (errno != EINTR && errno != EAGAIN && fi->error_handler)
296 fi->error_handler(fi, MFERR_WRITE);
301 DBG("MAIN: FD %d done write %d", fi->fd, fi->wpos);
302 fi->write_handler = NULL;
309 file_read(struct main_file *fi, void *buf, uns len)
314 fi->read_handler = file_read_handler;
321 fi->read_handler = NULL;
323 fi->rpos = fi->rlen = 0;
329 file_write(struct main_file *fi, void *buf, uns len)
334 fi->write_handler = file_write_handler;
341 fi->write_handler = NULL;
343 fi->wpos = fi->wlen = 0;
349 file_set_timeout(struct main_file *fi, timestamp_t expires)
352 timer_add(&fi->timer, expires);
358 struct main_context *m = main_current();
360 CLIST_FOR_EACH(struct main_file *, f, m->file_list)
365 hook_add(struct main_hook *ho)
367 struct main_context *m = main_current();
369 DBG("MAIN: Adding hook %p", ho);
371 clist_add_tail(&m->hook_list, &ho->n);
375 hook_del(struct main_hook *ho)
377 DBG("MAIN: Deleting hook %p", ho);
379 clist_remove(&ho->n);
380 ho->n.next = ho->n.prev = NULL;
384 sigchld_received(struct main_signal *sg UNUSED)
386 struct main_context *m = main_current();
390 while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
392 DBG("MAIN: Child %d exited with status %x", pid, stat);
393 CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
398 format_exit_status(pr->status_msg, pr->status);
399 DBG("MAIN: Calling process exit handler");
407 process_add(struct main_process *mp)
409 struct main_context *m = main_current();
411 DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
414 clist_add_tail(&m->process_list, &mp->n);
415 if (!m->sigchld_handler)
417 struct main_signal *sg = xmalloc_zero(sizeof(*sg));
418 m->sigchld_handler = sg;
419 sg->signum = SIGCHLD;
420 sg->handler = sigchld_received;
426 process_del(struct main_process *mp)
428 DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
430 clist_remove(&mp->n);
435 process_fork(struct main_process *mp)
440 DBG("MAIN: Fork failed");
442 format_exit_status(mp->status_msg, -1);
450 DBG("MAIN: Forked process %d", (int) pid);
458 pipe_read_handler(struct main_file *mf UNUSED)
460 struct main_context *m = main_current();
462 int n = read(m->sig_pipe_recv, &signum, sizeof(signum));
467 msg(L_ERROR, "Error reading signal pipe: %m");
470 ASSERT(n == sizeof(signum));
472 DBG("MAIN: Sigpipe: received signal %d", signum);
473 struct main_signal *tmp;
474 CLIST_FOR_EACH_DELSAFE(struct main_signal *, sg, m->signal_list, tmp)
475 if (sg->signum == signum)
477 DBG("MAIN: Sigpipe: invoking handler %p", sg);
478 // FIXME: Can the handler disappear from here?
486 pipe_configure(int fd)
489 if ((flags = fcntl(fd, F_GETFL)) < 0 || fcntl(fd, F_SETFL, flags|O_NONBLOCK) < 0)
490 die("Could not set file descriptor %d to non-blocking: %m", fd);
494 pipe_setup(struct main_context *m)
496 DBG("MAIN: Sigpipe: Setting up the pipe");
499 if (pipe(pipe_result) == -1)
500 die("Could not create signal pipe: %m");
501 pipe_configure(pipe_result[0]);
502 pipe_configure(pipe_result[1]);
503 m->sig_pipe_recv = pipe_result[0];
504 m->sig_pipe_send = pipe_result[1];
506 struct main_file *f = xmalloc_zero(sizeof(*f));
507 m->sig_pipe_file = f;
508 f->fd = m->sig_pipe_recv;
509 f->read_handler = pipe_read_handler;
514 signal_handler_pipe(int signum)
516 struct main_context *m = main_current();
518 msg(L_DEBUG | L_SIGHANDLER, "MAIN: Sigpipe: sending signal %d down the drain", signum);
520 write(m->sig_pipe_send, &signum, sizeof(signum));
524 signal_add(struct main_signal *ms)
526 struct main_context *m = main_current();
528 DBG("MAIN: Adding signal %p (sig=%d)", ms, ms->signum);
531 clist_add_tail(&m->signal_list, &ms->n);
532 if (m->sig_pipe_recv < 0)
535 struct sigaction sa = {
536 .sa_handler = signal_handler_pipe,
537 .sa_flags = SA_NOCLDSTOP | SA_RESTART,
539 sigaction(ms->signum, &sa, NULL);
543 sigaddset(&ss, ms->signum);
544 THREAD_SIGMASK(SIG_UNBLOCK, &ss, NULL);
545 sigaddset(&m->want_signals, ms->signum);
549 signal_del(struct main_signal *ms)
551 struct main_context *m = main_current();
553 DBG("MAIN: Deleting signal %p (sig=%d)", ms, ms->signum);
556 clist_remove(&ms->n);
557 ms->n.next = ms->n.prev = NULL;
560 CLIST_FOR_EACH(struct main_signal *, s, m->signal_list)
561 if (s->signum == ms->signum)
567 sigaddset(&ss, ms->signum);
568 THREAD_SIGMASK(SIG_BLOCK, &ss, NULL);
569 sigdelset(&m->want_signals, ms->signum);
574 main_debug_context(struct main_context *m UNUSED)
577 msg(L_DEBUG, "### Main loop status on %lld", (long long) m->now);
578 msg(L_DEBUG, "\tActive timers:");
579 uns num_timers = count_timers(m);
580 for (uns i = 1; i <= num_timers; i++)
582 struct main_timer *tm = m->timer_table[i];
583 msg(L_DEBUG, "\t\t%p (expires %lld, data %p)", tm, (long long)(tm->expires ? tm->expires - m->now : 999999), tm->data);
585 msg(L_DEBUG, "\tActive files:");
586 CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
587 msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, eh %p, expires %lld, data %p)",
588 fi, fi->fd, fi->read_handler, fi->write_handler, fi->error_handler,
589 (long long)(fi->timer.expires ? fi->timer.expires - m->now : 999999), fi->data);
590 msg(L_DEBUG, "\tActive hooks:");
591 CLIST_FOR_EACH(struct main_hook *, ho, m->hook_done_list)
592 msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
593 CLIST_FOR_EACH(struct main_hook *, ho, m->hook_list)
594 msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
595 msg(L_DEBUG, "\tActive processes:");
596 CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
597 msg(L_DEBUG, "\t\t%p (pid %d, func %p, data %p)", pr, pr->pid, pr->handler, pr->data);
598 msg(L_DEBUG, "\tActive signal catchers:");
599 CLIST_FOR_EACH(struct main_signal *, sg, m->signal_list)
600 msg(L_DEBUG, "\t\t%p (sig %d, func %p, data %p)", sg, sg->signum, sg->handler, sg->data);
605 main_rebuild_poll_table(struct main_context *m)
607 struct main_file *fi;
608 if (m->poll_table_size < m->file_cnt)
611 xfree(m->poll_table);
613 m->poll_table_size = 1;
614 while (m->poll_table_size < m->file_cnt)
615 m->poll_table_size *= 2;
616 m->poll_table = xmalloc(sizeof(struct pollfd) * m->poll_table_size);
618 struct pollfd *p = m->poll_table;
619 DBG("MAIN: Rebuilding poll table: %d of %d entries set", m->file_cnt, m->poll_table_size);
620 CLIST_WALK(fi, m->file_list)
626 m->poll_table_obsolete = 0;
632 DBG("MAIN: Entering main_loop");
633 struct main_context *m = main_current();
635 struct main_file *fi;
636 struct main_hook *ho;
637 struct main_timer *tm;
642 timestamp_t wake = m->now + 1000000000;
643 while (GARY_SIZE(m->timer_table) > 1 && (tm = m->timer_table[1])->expires <= m->now)
645 DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(m->now - tm->expires));
648 int hook_min = HOOK_RETRY;
649 int hook_max = HOOK_SHUTDOWN;
650 while (ho = clist_remove_head(&m->hook_list))
652 clist_add_tail(&m->hook_done_list, &ho->n);
653 DBG("MAIN: Hook %p", ho);
654 int ret = ho->handler(ho);
655 hook_min = MIN(hook_min, ret);
656 hook_max = MAX(hook_max, ret);
658 clist_move(&m->hook_list, &m->hook_done_list);
659 if (hook_min == HOOK_SHUTDOWN ||
660 hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
663 DBG("MAIN: Shut down by %s", m->shutdown ? "main_shutdown" : "a hook");
666 if (hook_max == HOOK_RETRY)
668 if (m->poll_table_obsolete)
669 main_rebuild_poll_table(m);
670 if (count_timers(m) && (tm = m->timer_table[1])->expires < wake)
673 int timeout = ((wake > m->now) ? wake - m->now : 0);
674 DBG("MAIN: Poll for %d fds and timeout %d ms", m->file_cnt, timeout);
675 int p = poll(m->poll_table, m->file_cnt, timeout);
676 timestamp_t old_now = m->now;
678 m->idle_time += m->now - old_now;
681 struct pollfd *p = m->poll_table;
682 CLIST_WALK(fi, m->file_list)
684 if (p->revents & (POLLIN | POLLHUP | POLLERR))
687 DBG("MAIN: Read event on fd %d", p->fd);
688 while (fi->read_handler && fi->read_handler(fi) && !m->poll_table_obsolete);
689 if (m->poll_table_obsolete) /* File entries have been inserted or deleted => better not risk continuing to nowhere */
692 if (p->revents & (POLLOUT | POLLERR))
695 DBG("MAIN: Write event on fd %d", p->fd);
696 while (fi->write_handler && fi->write_handler(fi) && !m->poll_table_obsolete);
697 if (m->poll_table_obsolete)
708 static struct main_process mp;
709 static struct main_file fin, fout;
710 static struct main_hook hook;
711 static struct main_timer tm;
712 static struct main_signal sg;
716 static void dread(struct main_file *fi)
718 if (fi->rpos < fi->rlen)
720 msg(L_INFO, "Read EOF");
725 msg(L_INFO, "Read done");
726 file_read(fi, rb, sizeof(rb));
730 static void derror(struct main_file *fi, int cause)
732 msg(L_INFO, "Error: %m !!! (cause %d)", cause);
736 static void dwrite(struct main_file *fi UNUSED)
738 msg(L_INFO, "Write done");
741 static int dhook(struct main_hook *ho UNUSED)
743 msg(L_INFO, "Hook called");
747 static void dtimer(struct main_timer *tm)
749 msg(L_INFO, "Timer tick");
750 timer_add_rel(tm, 11000);
751 timer_add_rel(tm, 10000);
754 static void dentry(void)
756 msg(L_INFO, "*** SUBPROCESS START ***");
758 msg(L_INFO, "*** SUBPROCESS FINISH ***");
762 static void dexit(struct main_process *pr)
764 msg(L_INFO, "Subprocess %d exited with status %x", pr->pid, pr->status);
767 static void dsignal(struct main_signal *sg UNUSED)
769 msg(L_INFO, "SIGINT received (use Ctrl-\\ to really quit)");
779 fin.read_done = dread;
780 fin.error_handler = derror;
782 file_read(&fin, rb, sizeof(rb));
785 fout.write_done = dwrite;
786 fout.error_handler = derror;
788 file_write(&fout, "Hello, world!\n", 14);
790 hook.handler = dhook;
794 timer_add_rel(&tm, 1000);
797 sg.handler = dsignal;
801 if (!process_fork(&mp))
807 msg(L_INFO, "Finished.");