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));
85 GARY_FREE(m->timer_table);
86 GARY_FREE(m->poll_table);
88 // FIXME: Some mechanism for cleaning up after fork()
92 main_switch_context(struct main_context *m)
94 struct ucwlib_context *c = ucwlib_thread_context();
95 struct main_context *m0 = c->main_context;
98 * Not only we need to switch the signal sets of the two contexts,
99 * but it is also necessary to avoid invoking a signal handler
100 * in the middle of changing c->main_context.
102 if (m0 && !clist_empty(&m0->signal_list))
103 THREAD_SIGMASK(SIG_BLOCK, &m0->want_signals, NULL);
105 if (m && !clist_empty(&m->signal_list))
106 THREAD_SIGMASK(SIG_UNBLOCK, &m->want_signals, NULL);
111 struct main_context *
114 struct ucwlib_context *c = ucwlib_thread_context();
115 struct main_context *m = c->main_context;
123 struct main_context *m = main_switch_context(main_new());
130 struct main_context *m = main_switch_context(NULL);
137 do_main_get_time(main_current());
141 count_timers(struct main_context *m)
143 return GARY_SIZE(m->timer_table) - 1;
147 timer_add(struct main_timer *tm, timestamp_t expires)
149 struct main_context *m = main_current();
153 GARY_INIT(m->timer_table, 1);
154 m->timer_table[0] = NULL;
158 DBG("MAIN: Setting timer %p (expire at now+%lld)", tm, (long long)(expires - m->now));
160 DBG("MAIN: Clearing timer %p", tm);
161 uns num_timers = count_timers(m);
162 if (tm->expires < expires)
166 tm->expires = expires;
167 tm->index = num_timers + 1;
168 *GARY_PUSH(m->timer_table, 1) = tm;
169 HEAP_INSERT(struct main_timer *, m->timer_table, tm->index, MAIN_TIMER_LESS, MAIN_TIMER_SWAP);
173 tm->expires = expires;
174 HEAP_INCREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
177 else if (tm->expires > expires)
181 ASSERT(tm->index && tm->index <= num_timers);
182 HEAP_DELETE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
185 GARY_POP(m->timer_table, 1);
189 tm->expires = expires;
190 HEAP_DECREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
196 timer_add_rel(struct main_timer *tm, timestamp_t expires_delta)
198 struct main_context *m = main_current();
199 return timer_add(tm, m->now + expires_delta);
203 timer_del(struct main_timer *tm)
209 file_add(struct main_file *fi)
211 struct main_context *m = main_current();
213 DBG("MAIN: Adding file %p (fd=%d)", fi, fi->fd);
214 ASSERT(!clist_is_linked(&fi->n));
215 clist_add_tail(&m->file_list, &fi->n);
217 m->poll_table_obsolete = 1;
218 if (fcntl(fi->fd, F_SETFL, O_NONBLOCK) < 0)
219 msg(L_ERROR, "Error setting fd %d to non-blocking mode: %m. Keep fingers crossed.", fi->fd);
223 file_chg(struct main_file *fi)
225 struct pollfd *p = fi->pollfd;
229 if (fi->read_handler)
230 p->events |= POLLIN | POLLHUP | POLLERR;
231 if (fi->write_handler)
232 p->events |= POLLOUT | POLLERR;
237 file_del(struct main_file *fi)
239 struct main_context *m = main_current();
241 DBG("MAIN: Deleting file %p (fd=%d)", fi, fi->fd);
242 ASSERT(clist_is_linked(&fi->n));
243 clist_unlink(&fi->n);
245 m->poll_table_obsolete = 1;
251 struct main_context *m = main_current();
253 CLIST_FOR_EACH(struct main_file *, f, m->file_list)
258 hook_add(struct main_hook *ho)
260 struct main_context *m = main_current();
262 DBG("MAIN: Adding hook %p", ho);
263 ASSERT(!clist_is_linked(&ho->n));
264 clist_add_tail(&m->hook_list, &ho->n);
268 hook_del(struct main_hook *ho)
270 DBG("MAIN: Deleting hook %p", ho);
271 ASSERT(clist_is_linked(&ho->n));
272 clist_unlink(&ho->n);
276 sigchld_received(struct main_signal *sg UNUSED)
278 struct main_context *m = main_current();
282 while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
284 DBG("MAIN: Child %d exited with status %x", pid, stat);
285 CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
290 format_exit_status(pr->status_msg, pr->status);
291 DBG("MAIN: Calling process exit handler");
299 process_add(struct main_process *mp)
301 struct main_context *m = main_current();
303 DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
304 ASSERT(!clist_is_linked(&mp->n));
306 clist_add_tail(&m->process_list, &mp->n);
307 if (!m->sigchld_handler)
309 struct main_signal *sg = xmalloc_zero(sizeof(*sg));
310 m->sigchld_handler = sg;
311 sg->signum = SIGCHLD;
312 sg->handler = sigchld_received;
318 process_del(struct main_process *mp)
320 DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
321 ASSERT(clist_is_linked(&mp->n));
322 clist_unlink(&mp->n);
326 process_fork(struct main_process *mp)
331 DBG("MAIN: Fork failed");
333 format_exit_status(mp->status_msg, -1);
341 DBG("MAIN: Forked process %d", (int) pid);
349 pipe_read_handler(struct main_file *mf UNUSED)
351 struct main_context *m = main_current();
353 int n = read(m->sig_pipe_recv, &signum, sizeof(signum));
358 msg(L_ERROR, "Error reading signal pipe: %m");
361 ASSERT(n == sizeof(signum));
363 DBG("MAIN: Sigpipe: received signal %d", signum);
364 struct main_signal iter = { .signum = -1 };
365 struct main_signal *sg = clist_head(&m->signal_list);
368 if (sg->signum == signum)
370 DBG("MAIN: Sigpipe: invoking handler %p", sg);
371 clist_insert_after(&iter.n, &sg->n);
373 sg = clist_next(&m->signal_list, &iter.n);
374 clist_remove(&iter.n);
377 sg = clist_next(&m->signal_list, &sg->n);
384 pipe_configure(int fd)
387 if ((flags = fcntl(fd, F_GETFL)) < 0 || fcntl(fd, F_SETFL, flags|O_NONBLOCK) < 0)
388 die("Could not set file descriptor %d to non-blocking: %m", fd);
392 pipe_setup(struct main_context *m)
394 DBG("MAIN: Sigpipe: Setting up the pipe");
397 if (pipe(pipe_result) == -1)
398 die("Could not create signal pipe: %m");
399 pipe_configure(pipe_result[0]);
400 pipe_configure(pipe_result[1]);
401 m->sig_pipe_recv = pipe_result[0];
402 m->sig_pipe_send = pipe_result[1];
404 struct main_file *f = xmalloc_zero(sizeof(*f));
405 m->sig_pipe_file = f;
406 f->fd = m->sig_pipe_recv;
407 f->read_handler = pipe_read_handler;
412 signal_handler_pipe(int signum)
414 struct main_context *m = main_current();
416 msg(L_DEBUG | L_SIGHANDLER, "MAIN: Sigpipe: sending signal %d down the drain", signum);
418 write(m->sig_pipe_send, &signum, sizeof(signum));
422 signal_add(struct main_signal *ms)
424 struct main_context *m = main_current();
426 DBG("MAIN: Adding signal %p (sig=%d)", ms, ms->signum);
428 ASSERT(!clist_is_linked(&ms->n));
429 // Adding at the head of the list is better if we are in the middle of walking the list.
430 clist_add_head(&m->signal_list, &ms->n);
431 if (m->sig_pipe_recv < 0)
434 struct sigaction sa = {
435 .sa_handler = signal_handler_pipe,
436 .sa_flags = SA_NOCLDSTOP | SA_RESTART,
438 sigaction(ms->signum, &sa, NULL);
442 sigaddset(&ss, ms->signum);
443 THREAD_SIGMASK(SIG_UNBLOCK, &ss, NULL);
444 sigaddset(&m->want_signals, ms->signum);
448 signal_del(struct main_signal *ms)
450 struct main_context *m = main_current();
452 DBG("MAIN: Deleting signal %p (sig=%d)", ms, ms->signum);
454 ASSERT(clist_is_linked(&ms->n));
455 clist_unlink(&ms->n);
458 CLIST_FOR_EACH(struct main_signal *, s, m->signal_list)
459 if (s->signum == ms->signum)
465 sigaddset(&ss, ms->signum);
466 THREAD_SIGMASK(SIG_BLOCK, &ss, NULL);
467 sigdelset(&m->want_signals, ms->signum);
472 main_debug_context(struct main_context *m UNUSED)
475 msg(L_DEBUG, "### Main loop status on %lld", (long long) m->now);
476 msg(L_DEBUG, "\tActive timers:");
477 uns num_timers = count_timers(m);
478 for (uns i = 1; i <= num_timers; i++)
480 struct main_timer *tm = m->timer_table[i];
481 msg(L_DEBUG, "\t\t%p (expires %lld, data %p)", tm, (long long)(tm->expires ? tm->expires - m->now : 999999), tm->data);
483 msg(L_DEBUG, "\tActive files:");
484 CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
485 msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p)",
486 fi, fi->fd, fi->read_handler, fi->write_handler, fi->data);
487 // FIXME: Can we display status of block_io requests somehow?
488 msg(L_DEBUG, "\tActive hooks:");
489 CLIST_FOR_EACH(struct main_hook *, ho, m->hook_done_list)
490 msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
491 CLIST_FOR_EACH(struct main_hook *, ho, m->hook_list)
492 msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
493 msg(L_DEBUG, "\tActive processes:");
494 CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
495 msg(L_DEBUG, "\t\t%p (pid %d, func %p, data %p)", pr, pr->pid, pr->handler, pr->data);
496 msg(L_DEBUG, "\tActive signal catchers:");
497 CLIST_FOR_EACH(struct main_signal *, sg, m->signal_list)
499 msg(L_DEBUG, "\t\t(placeholder)");
501 msg(L_DEBUG, "\t\t%p (sig %d, func %p, data %p)", sg, sg->signum, sg->handler, sg->data);
506 main_rebuild_poll_table(struct main_context *m)
508 GARY_INIT_OR_RESIZE(m->poll_table, m->file_cnt);
509 DBG("MAIN: Rebuilding poll table: %d entries", m->file_cnt);
511 struct pollfd *p = m->poll_table;
512 CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
518 m->poll_table_obsolete = 0;
522 process_timers(struct main_context *m)
524 struct main_timer *tm;
525 while (GARY_SIZE(m->timer_table) > 1 && (tm = m->timer_table[1])->expires <= m->now)
527 DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(m->now - tm->expires));
532 static enum main_hook_return
533 process_hooks(struct main_context *m)
535 int hook_min = HOOK_RETRY;
536 int hook_max = HOOK_SHUTDOWN;
537 struct main_hook *ho;
539 while (ho = clist_remove_head(&m->hook_list))
541 clist_add_tail(&m->hook_done_list, &ho->n);
542 DBG("MAIN: Hook %p", ho);
543 int ret = ho->handler(ho);
544 hook_min = MIN(hook_min, ret);
545 hook_max = MAX(hook_max, ret);
547 clist_move(&m->hook_list, &m->hook_done_list);
548 if (hook_min == HOOK_SHUTDOWN ||
549 hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
552 DBG("MAIN: Shut down by %s", m->shutdown ? "main_shutdown" : "a hook");
553 return HOOK_SHUTDOWN;
555 if (hook_max == HOOK_RETRY)
564 DBG("MAIN: Entering main_loop");
565 struct main_context *m = main_current();
570 timestamp_t wake = m->now + 1000000000;
572 switch (process_hooks(m))
581 if (m->poll_table_obsolete)
582 main_rebuild_poll_table(m);
584 wake = MIN(wake, m->timer_table[1]->expires);
586 int timeout = ((wake > m->now) ? wake - m->now : 0);
587 DBG("MAIN: Poll for %d fds and timeout %d ms", m->file_cnt, timeout);
588 int p = poll(m->poll_table, m->file_cnt, timeout);
589 timestamp_t old_now = m->now;
591 m->idle_time += m->now - old_now;
594 struct pollfd *p = m->poll_table;
595 CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
597 if (p->revents & (POLLIN | POLLHUP | POLLERR))
600 DBG("MAIN: Read event on fd %d", p->fd);
601 while (fi->read_handler && fi->read_handler(fi) && !m->poll_table_obsolete);
602 if (m->poll_table_obsolete) /* File entries have been inserted or deleted => better not risk continuing to nowhere */
605 if (p->revents & (POLLOUT | POLLERR))
608 DBG("MAIN: Write event on fd %d", p->fd);
609 while (fi->write_handler && fi->write_handler(fi) && !m->poll_table_obsolete);
610 if (m->poll_table_obsolete)
621 static struct main_process mp;
622 static struct main_block_io fin, fout;
623 static struct main_hook hook;
624 static struct main_timer tm;
625 static struct main_signal sg;
629 static void dread(struct main_block_io *bio)
631 if (bio->rpos < bio->rlen)
633 msg(L_INFO, "Read EOF");
638 msg(L_INFO, "Read done");
639 block_io_read(bio, rb, sizeof(rb));
643 static void derror(struct main_block_io *bio, int cause)
645 msg(L_INFO, "Error: %m !!! (cause %d)", cause);
649 static void dwrite(struct main_block_io *bio UNUSED)
651 msg(L_INFO, "Write done");
654 static int dhook(struct main_hook *ho UNUSED)
656 msg(L_INFO, "Hook called");
660 static void dtimer(struct main_timer *tm)
662 msg(L_INFO, "Timer tick");
663 timer_add_rel(tm, 11000);
664 timer_add_rel(tm, 10000);
667 static void dentry(void)
669 msg(L_INFO, "*** SUBPROCESS START ***");
671 msg(L_INFO, "*** SUBPROCESS FINISH ***");
675 static void dexit(struct main_process *pr)
677 msg(L_INFO, "Subprocess %d exited with status %x", pr->pid, pr->status);
680 static void dsignal(struct main_signal *sg UNUSED)
682 msg(L_INFO, "SIGINT received (use Ctrl-\\ to really quit)");
691 fin.read_done = dread;
692 fin.error_handler = derror;
693 block_io_add(&fin, 0);
694 block_io_read(&fin, rb, sizeof(rb));
696 fout.write_done = dwrite;
697 fout.error_handler = derror;
698 block_io_add(&fout, 1);
699 block_io_write(&fout, "Hello, world!\n", 14);
701 hook.handler = dhook;
705 timer_add_rel(&tm, 1000);
708 sg.handler = dsignal;
712 if (!process_fork(&mp))
718 msg(L_INFO, "Finished.");