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_add(struct main_file *fi)
212 struct main_context *m = main_current();
214 DBG("MAIN: Adding file %p (fd=%d)", fi, fi->fd);
215 ASSERT(!clist_is_linked(&fi->n));
216 clist_add_tail(&m->file_list, &fi->n);
218 m->poll_table_obsolete = 1;
219 if (fcntl(fi->fd, F_SETFL, O_NONBLOCK) < 0)
220 msg(L_ERROR, "Error setting fd %d to non-blocking mode: %m. Keep fingers crossed.", fi->fd);
224 file_chg(struct main_file *fi)
226 struct pollfd *p = fi->pollfd;
230 if (fi->read_handler)
231 p->events |= POLLIN | POLLHUP | POLLERR;
232 if (fi->write_handler)
233 p->events |= POLLOUT | POLLERR;
238 file_del(struct main_file *fi)
240 struct main_context *m = main_current();
242 DBG("MAIN: Deleting file %p (fd=%d)", fi, fi->fd);
243 ASSERT(clist_is_linked(&fi->n));
244 clist_unlink(&fi->n);
246 m->poll_table_obsolete = 1;
252 struct main_context *m = main_current();
254 CLIST_FOR_EACH(struct main_file *, f, m->file_list)
259 hook_add(struct main_hook *ho)
261 struct main_context *m = main_current();
263 DBG("MAIN: Adding hook %p", ho);
264 ASSERT(!clist_is_linked(&ho->n));
265 clist_add_tail(&m->hook_list, &ho->n);
269 hook_del(struct main_hook *ho)
271 DBG("MAIN: Deleting hook %p", ho);
272 ASSERT(clist_is_linked(&ho->n));
273 clist_unlink(&ho->n);
277 sigchld_received(struct main_signal *sg UNUSED)
279 struct main_context *m = main_current();
283 while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
285 DBG("MAIN: Child %d exited with status %x", pid, stat);
286 CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
291 format_exit_status(pr->status_msg, pr->status);
292 DBG("MAIN: Calling process exit handler");
300 process_add(struct main_process *mp)
302 struct main_context *m = main_current();
304 DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
305 ASSERT(!clist_is_linked(&mp->n));
307 clist_add_tail(&m->process_list, &mp->n);
308 if (!m->sigchld_handler)
310 struct main_signal *sg = xmalloc_zero(sizeof(*sg));
311 m->sigchld_handler = sg;
312 sg->signum = SIGCHLD;
313 sg->handler = sigchld_received;
319 process_del(struct main_process *mp)
321 DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
322 ASSERT(clist_is_linked(&mp->n));
323 clist_unlink(&mp->n);
327 process_fork(struct main_process *mp)
332 DBG("MAIN: Fork failed");
334 format_exit_status(mp->status_msg, -1);
342 DBG("MAIN: Forked process %d", (int) pid);
350 pipe_read_handler(struct main_file *mf UNUSED)
352 struct main_context *m = main_current();
354 int n = read(m->sig_pipe_recv, &signum, sizeof(signum));
359 msg(L_ERROR, "Error reading signal pipe: %m");
362 ASSERT(n == sizeof(signum));
364 DBG("MAIN: Sigpipe: received signal %d", signum);
365 struct main_signal *tmp;
366 CLIST_FOR_EACH_DELSAFE(struct main_signal *, sg, m->signal_list, tmp)
367 if (sg->signum == signum)
369 DBG("MAIN: Sigpipe: invoking handler %p", sg);
370 // FIXME: Can the handler disappear from here?
378 pipe_configure(int fd)
381 if ((flags = fcntl(fd, F_GETFL)) < 0 || fcntl(fd, F_SETFL, flags|O_NONBLOCK) < 0)
382 die("Could not set file descriptor %d to non-blocking: %m", fd);
386 pipe_setup(struct main_context *m)
388 DBG("MAIN: Sigpipe: Setting up the pipe");
391 if (pipe(pipe_result) == -1)
392 die("Could not create signal pipe: %m");
393 pipe_configure(pipe_result[0]);
394 pipe_configure(pipe_result[1]);
395 m->sig_pipe_recv = pipe_result[0];
396 m->sig_pipe_send = pipe_result[1];
398 struct main_file *f = xmalloc_zero(sizeof(*f));
399 m->sig_pipe_file = f;
400 f->fd = m->sig_pipe_recv;
401 f->read_handler = pipe_read_handler;
406 signal_handler_pipe(int signum)
408 struct main_context *m = main_current();
410 msg(L_DEBUG | L_SIGHANDLER, "MAIN: Sigpipe: sending signal %d down the drain", signum);
412 write(m->sig_pipe_send, &signum, sizeof(signum));
416 signal_add(struct main_signal *ms)
418 struct main_context *m = main_current();
420 DBG("MAIN: Adding signal %p (sig=%d)", ms, ms->signum);
422 ASSERT(!clist_is_linked(&ms->n));
423 clist_add_tail(&m->signal_list, &ms->n);
424 if (m->sig_pipe_recv < 0)
427 struct sigaction sa = {
428 .sa_handler = signal_handler_pipe,
429 .sa_flags = SA_NOCLDSTOP | SA_RESTART,
431 sigaction(ms->signum, &sa, NULL);
435 sigaddset(&ss, ms->signum);
436 THREAD_SIGMASK(SIG_UNBLOCK, &ss, NULL);
437 sigaddset(&m->want_signals, ms->signum);
441 signal_del(struct main_signal *ms)
443 struct main_context *m = main_current();
445 DBG("MAIN: Deleting signal %p (sig=%d)", ms, ms->signum);
447 ASSERT(clist_is_linked(&ms->n));
448 clist_unlink(&ms->n);
451 CLIST_FOR_EACH(struct main_signal *, s, m->signal_list)
452 if (s->signum == ms->signum)
458 sigaddset(&ss, ms->signum);
459 THREAD_SIGMASK(SIG_BLOCK, &ss, NULL);
460 sigdelset(&m->want_signals, ms->signum);
465 main_debug_context(struct main_context *m UNUSED)
468 msg(L_DEBUG, "### Main loop status on %lld", (long long) m->now);
469 msg(L_DEBUG, "\tActive timers:");
470 uns num_timers = count_timers(m);
471 for (uns i = 1; i <= num_timers; i++)
473 struct main_timer *tm = m->timer_table[i];
474 msg(L_DEBUG, "\t\t%p (expires %lld, data %p)", tm, (long long)(tm->expires ? tm->expires - m->now : 999999), tm->data);
476 msg(L_DEBUG, "\tActive files:");
477 CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
478 msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p)",
479 fi, fi->fd, fi->read_handler, fi->write_handler, fi->data);
480 // FIXME: Can we display status of block_io requests somehow?
481 msg(L_DEBUG, "\tActive hooks:");
482 CLIST_FOR_EACH(struct main_hook *, ho, m->hook_done_list)
483 msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
484 CLIST_FOR_EACH(struct main_hook *, ho, m->hook_list)
485 msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
486 msg(L_DEBUG, "\tActive processes:");
487 CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
488 msg(L_DEBUG, "\t\t%p (pid %d, func %p, data %p)", pr, pr->pid, pr->handler, pr->data);
489 msg(L_DEBUG, "\tActive signal catchers:");
490 CLIST_FOR_EACH(struct main_signal *, sg, m->signal_list)
491 msg(L_DEBUG, "\t\t%p (sig %d, func %p, data %p)", sg, sg->signum, sg->handler, sg->data);
496 main_rebuild_poll_table(struct main_context *m)
498 struct main_file *fi;
499 if (m->poll_table_size < m->file_cnt)
502 xfree(m->poll_table);
504 m->poll_table_size = 1;
505 while (m->poll_table_size < m->file_cnt)
506 m->poll_table_size *= 2;
507 m->poll_table = xmalloc(sizeof(struct pollfd) * m->poll_table_size);
509 struct pollfd *p = m->poll_table;
510 DBG("MAIN: Rebuilding poll table: %d of %d entries set", m->file_cnt, m->poll_table_size);
511 CLIST_WALK(fi, m->file_list)
517 m->poll_table_obsolete = 0;
521 process_timers(struct main_context *m)
523 struct main_timer *tm;
524 while (GARY_SIZE(m->timer_table) > 1 && (tm = m->timer_table[1])->expires <= m->now)
526 DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(m->now - tm->expires));
531 static enum main_hook_return
532 process_hooks(struct main_context *m)
534 int hook_min = HOOK_RETRY;
535 int hook_max = HOOK_SHUTDOWN;
536 struct main_hook *ho;
538 while (ho = clist_remove_head(&m->hook_list))
540 clist_add_tail(&m->hook_done_list, &ho->n);
541 DBG("MAIN: Hook %p", ho);
542 int ret = ho->handler(ho);
543 hook_min = MIN(hook_min, ret);
544 hook_max = MAX(hook_max, ret);
546 clist_move(&m->hook_list, &m->hook_done_list);
547 if (hook_min == HOOK_SHUTDOWN ||
548 hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
551 DBG("MAIN: Shut down by %s", m->shutdown ? "main_shutdown" : "a hook");
552 return HOOK_SHUTDOWN;
554 if (hook_max == HOOK_RETRY)
563 DBG("MAIN: Entering main_loop");
564 struct main_context *m = main_current();
569 timestamp_t wake = m->now + 1000000000;
571 switch (process_hooks(m))
580 if (m->poll_table_obsolete)
581 main_rebuild_poll_table(m);
583 wake = MIN(wake, m->timer_table[1]->expires);
585 int timeout = ((wake > m->now) ? wake - m->now : 0);
586 DBG("MAIN: Poll for %d fds and timeout %d ms", m->file_cnt, timeout);
587 int p = poll(m->poll_table, m->file_cnt, timeout);
588 timestamp_t old_now = m->now;
590 m->idle_time += m->now - old_now;
593 struct pollfd *p = m->poll_table;
594 CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
596 if (p->revents & (POLLIN | POLLHUP | POLLERR))
599 DBG("MAIN: Read event on fd %d", p->fd);
600 while (fi->read_handler && fi->read_handler(fi) && !m->poll_table_obsolete);
601 if (m->poll_table_obsolete) /* File entries have been inserted or deleted => better not risk continuing to nowhere */
604 if (p->revents & (POLLOUT | POLLERR))
607 DBG("MAIN: Write event on fd %d", p->fd);
608 while (fi->write_handler && fi->write_handler(fi) && !m->poll_table_obsolete);
609 if (m->poll_table_obsolete)
620 static struct main_process mp;
621 static struct main_block_io fin, fout;
622 static struct main_hook hook;
623 static struct main_timer tm;
624 static struct main_signal sg;
628 static void dread(struct main_block_io *bio)
630 if (bio->rpos < bio->rlen)
632 msg(L_INFO, "Read EOF");
637 msg(L_INFO, "Read done");
638 block_io_read(bio, rb, sizeof(rb));
642 static void derror(struct main_block_io *bio, int cause)
644 msg(L_INFO, "Error: %m !!! (cause %d)", cause);
648 static void dwrite(struct main_block_io *bio UNUSED)
650 msg(L_INFO, "Write done");
653 static int dhook(struct main_hook *ho UNUSED)
655 msg(L_INFO, "Hook called");
659 static void dtimer(struct main_timer *tm)
661 msg(L_INFO, "Timer tick");
662 timer_add_rel(tm, 11000);
663 timer_add_rel(tm, 10000);
666 static void dentry(void)
668 msg(L_INFO, "*** SUBPROCESS START ***");
670 msg(L_INFO, "*** SUBPROCESS FINISH ***");
674 static void dexit(struct main_process *pr)
676 msg(L_INFO, "Subprocess %d exited with status %x", pr->pid, pr->status);
679 static void dsignal(struct main_signal *sg UNUSED)
681 msg(L_INFO, "SIGINT received (use Ctrl-\\ to really quit)");
690 fin.read_done = dread;
691 fin.error_handler = derror;
692 block_io_add(&fin, 0);
693 block_io_read(&fin, rb, sizeof(rb));
695 fout.write_done = dwrite;
696 fout.error_handler = derror;
697 block_io_add(&fout, 1);
698 block_io_write(&fout, "Hello, world!\n", 14);
700 hook.handler = dhook;
704 timer_add_rel(&tm, 1000);
707 sg.handler = dsignal;
711 if (!process_fork(&mp))
717 msg(L_INFO, "Finished.");