]> mj.ucw.cz Git - libucw.git/blob - ucw/mainloop.c
9228024bb50874c1cc6061f21448e6f5c8538825
[libucw.git] / ucw / mainloop.c
1 /*
2  *      UCW Library -- Main Loop
3  *
4  *      (c) 2004--2010 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #undef LOCAL_DEBUG
11
12 #include "ucw/lib.h"
13 #include "ucw/heap.h"
14 #include "ucw/mainloop.h"
15 #include "ucw/threads.h"
16 #include "ucw/gary.h"
17
18 #include <stdio.h>
19 #include <string.h>
20 #include <stdlib.h>
21 #include <unistd.h>
22 #include <signal.h>
23 #include <fcntl.h>
24 #include <errno.h>
25 #include <time.h>
26 #include <sys/poll.h>
27 #include <sys/wait.h>
28 #include <sys/time.h>
29
30 #ifdef CONFIG_UCW_THREADS
31 #include <pthread.h>
32 #define THREAD_SIGMASK pthread_sigmask
33 #else
34 #define THREAD_SIGMASK sigprocmask
35 #endif
36
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))
39
40 static void
41 do_main_get_time(struct main_context *m)
42 {
43   struct timeval tv;
44   gettimeofday(&tv, NULL);
45   m->now_seconds = tv.tv_sec;
46   m->now = (timestamp_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
47 }
48
49 struct main_context *
50 main_new(void)
51 {
52   struct main_context *m = xmalloc_zero(sizeof(*m));
53
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;
61   do_main_get_time(m);
62   sigemptyset(&m->want_signals);
63   m->sig_pipe_recv = m->sig_pipe_send = -1;
64
65   return m;
66 }
67
68 void
69 main_delete(struct main_context *m)
70 {
71   if (m->sigchld_handler)
72     signal_del(m->sigchld_handler);
73   if (m->sig_pipe_file)
74     file_del(m->sig_pipe_file);
75   if (m->sig_pipe_recv >= 0)
76     {
77       close(m->sig_pipe_recv);
78       close(m->sig_pipe_send);
79     }
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   if (m->timer_table)
86     GARY_FREE(m->timer_table);
87   xfree(m->poll_table);
88   xfree(m);
89   // FIXME: Some mechanism for cleaning up after fork()
90 }
91
92 struct main_context *
93 main_switch_context(struct main_context *m)
94 {
95   struct ucwlib_context *c = ucwlib_thread_context();
96   struct main_context *m0 = c->main_context;
97
98   /*
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.
102    */
103   if (m0 && !clist_empty(&m0->signal_list))
104     THREAD_SIGMASK(SIG_BLOCK, &m0->want_signals, NULL);
105   c->main_context = m;
106   if (m && !clist_empty(&m->signal_list))
107     THREAD_SIGMASK(SIG_UNBLOCK, &m->want_signals, NULL);
108
109   return m0;
110 }
111
112 struct main_context *
113 main_current(void)
114 {
115   struct ucwlib_context *c = ucwlib_thread_context();
116   struct main_context *m = c->main_context;
117   ASSERT(m);
118   return m;
119 }
120
121 void
122 main_init(void)
123 {
124   struct main_context *m = main_switch_context(main_new());
125   ASSERT(!m);
126 }
127
128 void
129 main_cleanup(void)
130 {
131   struct main_context *m = main_switch_context(NULL);
132   main_delete(m);
133 }
134
135 void
136 main_get_time(void)
137 {
138   do_main_get_time(main_current());
139 }
140
141 static inline uns
142 count_timers(struct main_context *m)
143 {
144   return GARY_SIZE(m->timer_table) - 1;
145 }
146
147 void
148 timer_add(struct main_timer *tm, timestamp_t expires)
149 {
150   struct main_context *m = main_current();
151
152   if (!m->timer_table)
153     {
154       GARY_INIT(m->timer_table, 1);
155       m->timer_table[0] = NULL;
156     }
157
158   if (expires)
159     DBG("MAIN: Setting timer %p (expire at now+%lld)", tm, (long long)(expires - m->now));
160   else
161     DBG("MAIN: Clearing timer %p", tm);
162   uns num_timers = count_timers(m);
163   if (tm->expires < expires)
164     {
165       if (!tm->expires)
166         {
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);
171         }
172       else
173         {
174           tm->expires = expires;
175           HEAP_INCREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
176         }
177     }
178   else if (tm->expires > expires)
179     {
180       if (!expires)
181         {
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);
184           tm->index = 0;
185           tm->expires = 0;
186           GARY_POP(m->timer_table, 1);
187         }
188       else
189         {
190           tm->expires = expires;
191           HEAP_DECREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
192         }
193     }
194 }
195
196 void
197 timer_add_rel(struct main_timer *tm, timestamp_t expires_delta)
198 {
199   struct main_context *m = main_current();
200   return timer_add(tm, m->now + expires_delta);
201 }
202
203 void
204 timer_del(struct main_timer *tm)
205 {
206   timer_add(tm, 0);
207 }
208
209 void
210 file_add(struct main_file *fi)
211 {
212   struct main_context *m = main_current();
213
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);
217   m->file_cnt++;
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);
221 }
222
223 void
224 file_chg(struct main_file *fi)
225 {
226   struct pollfd *p = fi->pollfd;
227   if (p)
228     {
229       p->events = 0;
230       if (fi->read_handler)
231         p->events |= POLLIN | POLLHUP | POLLERR;
232       if (fi->write_handler)
233         p->events |= POLLOUT | POLLERR;
234     }
235 }
236
237 void
238 file_del(struct main_file *fi)
239 {
240   struct main_context *m = main_current();
241
242   DBG("MAIN: Deleting file %p (fd=%d)", fi, fi->fd);
243   ASSERT(clist_is_linked(&fi->n));
244   clist_unlink(&fi->n);
245   m->file_cnt--;
246   m->poll_table_obsolete = 1;
247 }
248
249 void
250 file_close_all(void)
251 {
252   struct main_context *m = main_current();
253
254   CLIST_FOR_EACH(struct main_file *, f, m->file_list)
255     close(f->fd);
256 }
257
258 void
259 hook_add(struct main_hook *ho)
260 {
261   struct main_context *m = main_current();
262
263   DBG("MAIN: Adding hook %p", ho);
264   ASSERT(!clist_is_linked(&ho->n));
265   clist_add_tail(&m->hook_list, &ho->n);
266 }
267
268 void
269 hook_del(struct main_hook *ho)
270 {
271   DBG("MAIN: Deleting hook %p", ho);
272   ASSERT(clist_is_linked(&ho->n));
273   clist_unlink(&ho->n);
274 }
275
276 static void
277 sigchld_received(struct main_signal *sg UNUSED)
278 {
279   struct main_context *m = main_current();
280   int stat;
281   pid_t pid;
282
283   while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
284     {
285       DBG("MAIN: Child %d exited with status %x", pid, stat);
286       CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
287         if (pr->pid == pid)
288           {
289             pr->status = stat;
290             process_del(pr);
291             format_exit_status(pr->status_msg, pr->status);
292             DBG("MAIN: Calling process exit handler");
293             pr->handler(pr);
294             break;
295           }
296     }
297 }
298
299 void
300 process_add(struct main_process *mp)
301 {
302   struct main_context *m = main_current();
303
304   DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
305   ASSERT(!clist_is_linked(&mp->n));
306   ASSERT(mp->handler);
307   clist_add_tail(&m->process_list, &mp->n);
308   if (!m->sigchld_handler)
309     {
310       struct main_signal *sg = xmalloc_zero(sizeof(*sg));
311       m->sigchld_handler = sg;
312       sg->signum = SIGCHLD;
313       sg->handler = sigchld_received;
314       signal_add(sg);
315     }
316 }
317
318 void
319 process_del(struct main_process *mp)
320 {
321   DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
322   ASSERT(clist_is_linked(&mp->n));
323   clist_unlink(&mp->n);
324 }
325
326 int
327 process_fork(struct main_process *mp)
328 {
329   pid_t pid = fork();
330   if (pid < 0)
331     {
332       DBG("MAIN: Fork failed");
333       mp->status = -1;
334       format_exit_status(mp->status_msg, -1);
335       mp->handler(mp);
336       return 1;
337     }
338   else if (!pid)
339     return 0;
340   else
341     {
342       DBG("MAIN: Forked process %d", (int) pid);
343       mp->pid = pid;
344       process_add(mp);
345       return 1;
346     }
347 }
348
349 static int
350 pipe_read_handler(struct main_file *mf UNUSED)
351 {
352   struct main_context *m = main_current();
353   int signum;
354   int n = read(m->sig_pipe_recv, &signum, sizeof(signum));
355
356   if (n < 0)
357     {
358       if (errno != EAGAIN)
359         msg(L_ERROR, "Error reading signal pipe: %m");
360       return 0;
361     }
362   ASSERT(n == sizeof(signum));
363
364   DBG("MAIN: Sigpipe: received signal %d", signum);
365   struct main_signal iter = { .signum = -1 };
366   struct main_signal *sg = clist_head(&m->signal_list);
367   while (sg)
368     {
369       if (sg->signum == signum)
370         {
371           DBG("MAIN: Sigpipe: invoking handler %p", sg);
372           clist_insert_after(&iter.n, &sg->n);
373           sg->handler(sg);
374           sg = clist_next(&m->signal_list, &iter.n);
375           clist_remove(&iter.n);
376         }
377       else
378         sg = clist_next(&m->signal_list, &sg->n);
379     }
380
381   return 1;
382 }
383
384 static void
385 pipe_configure(int fd)
386 {
387   int flags;
388   if ((flags = fcntl(fd, F_GETFL)) < 0 || fcntl(fd, F_SETFL, flags|O_NONBLOCK) < 0)
389     die("Could not set file descriptor %d to non-blocking: %m", fd);
390 }
391
392 static void
393 pipe_setup(struct main_context *m)
394 {
395   DBG("MAIN: Sigpipe: Setting up the pipe");
396
397   int pipe_result[2];
398   if (pipe(pipe_result) == -1)
399     die("Could not create signal pipe: %m");
400   pipe_configure(pipe_result[0]);
401   pipe_configure(pipe_result[1]);
402   m->sig_pipe_recv = pipe_result[0];
403   m->sig_pipe_send = pipe_result[1];
404
405   struct main_file *f = xmalloc_zero(sizeof(*f));
406   m->sig_pipe_file = f;
407   f->fd = m->sig_pipe_recv;
408   f->read_handler = pipe_read_handler;
409   file_add(f);
410 }
411
412 static void
413 signal_handler_pipe(int signum)
414 {
415   struct main_context *m = main_current();
416 #ifdef LOCAL_DEBUG
417   msg(L_DEBUG | L_SIGHANDLER, "MAIN: Sigpipe: sending signal %d down the drain", signum);
418 #endif
419   write(m->sig_pipe_send, &signum, sizeof(signum));
420 }
421
422 void
423 signal_add(struct main_signal *ms)
424 {
425   struct main_context *m = main_current();
426
427   DBG("MAIN: Adding signal %p (sig=%d)", ms, ms->signum);
428
429   ASSERT(!clist_is_linked(&ms->n));
430   // Adding at the head of the list is better if we are in the middle of walking the list.
431   clist_add_head(&m->signal_list, &ms->n);
432   if (m->sig_pipe_recv < 0)
433     pipe_setup(m);
434
435   struct sigaction sa = {
436     .sa_handler = signal_handler_pipe,
437     .sa_flags = SA_NOCLDSTOP | SA_RESTART,
438   };
439   sigaction(ms->signum, &sa, NULL);
440
441   sigset_t ss;
442   sigemptyset(&ss);
443   sigaddset(&ss, ms->signum);
444   THREAD_SIGMASK(SIG_UNBLOCK, &ss, NULL);
445   sigaddset(&m->want_signals, ms->signum);
446 }
447
448 void
449 signal_del(struct main_signal *ms)
450 {
451   struct main_context *m = main_current();
452
453   DBG("MAIN: Deleting signal %p (sig=%d)", ms, ms->signum);
454
455   ASSERT(clist_is_linked(&ms->n));
456   clist_unlink(&ms->n);
457
458   int another = 0;
459   CLIST_FOR_EACH(struct main_signal *, s, m->signal_list)
460     if (s->signum == ms->signum)
461       another++;
462   if (!another)
463     {
464       sigset_t ss;
465       sigemptyset(&ss);
466       sigaddset(&ss, ms->signum);
467       THREAD_SIGMASK(SIG_BLOCK, &ss, NULL);
468       sigdelset(&m->want_signals, ms->signum);
469     }
470 }
471
472 void
473 main_debug_context(struct main_context *m UNUSED)
474 {
475 #ifdef CONFIG_DEBUG
476   msg(L_DEBUG, "### Main loop status on %lld", (long long) m->now);
477   msg(L_DEBUG, "\tActive timers:");
478   uns num_timers = count_timers(m);
479   for (uns i = 1; i <= num_timers; i++)
480     {
481       struct main_timer *tm = m->timer_table[i];
482       msg(L_DEBUG, "\t\t%p (expires %lld, data %p)", tm, (long long)(tm->expires ? tm->expires - m->now : 999999), tm->data);
483     }
484   msg(L_DEBUG, "\tActive files:");
485   CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
486     msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, data %p)",
487         fi, fi->fd, fi->read_handler, fi->write_handler, fi->data);
488     // FIXME: Can we display status of block_io requests somehow?
489   msg(L_DEBUG, "\tActive hooks:");
490   CLIST_FOR_EACH(struct main_hook *, ho, m->hook_done_list)
491     msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
492   CLIST_FOR_EACH(struct main_hook *, ho, m->hook_list)
493     msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
494   msg(L_DEBUG, "\tActive processes:");
495   CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
496     msg(L_DEBUG, "\t\t%p (pid %d, func %p, data %p)", pr, pr->pid, pr->handler, pr->data);
497   msg(L_DEBUG, "\tActive signal catchers:");
498   CLIST_FOR_EACH(struct main_signal *, sg, m->signal_list)
499     if (sg->signum < 0)
500       msg(L_DEBUG, "\t\t(placeholder)");
501     else
502       msg(L_DEBUG, "\t\t%p (sig %d, func %p, data %p)", sg, sg->signum, sg->handler, sg->data);
503 #endif
504 }
505
506 static void
507 main_rebuild_poll_table(struct main_context *m)
508 {
509   struct main_file *fi;
510   if (m->poll_table_size < m->file_cnt)
511     {
512       if (m->poll_table)
513         xfree(m->poll_table);
514       else
515         m->poll_table_size = 1;
516       while (m->poll_table_size < m->file_cnt)
517         m->poll_table_size *= 2;
518       m->poll_table = xmalloc(sizeof(struct pollfd) * m->poll_table_size);
519     }
520   struct pollfd *p = m->poll_table;
521   DBG("MAIN: Rebuilding poll table: %d of %d entries set", m->file_cnt, m->poll_table_size);
522   CLIST_WALK(fi, m->file_list)
523     {
524       p->fd = fi->fd;
525       fi->pollfd = p++;
526       file_chg(fi);
527     }
528   m->poll_table_obsolete = 0;
529 }
530
531 static void
532 process_timers(struct main_context *m)
533 {
534   struct main_timer *tm;
535   while (GARY_SIZE(m->timer_table) > 1 && (tm = m->timer_table[1])->expires <= m->now)
536     {
537       DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(m->now - tm->expires));
538       tm->handler(tm);
539     }
540 }
541
542 static enum main_hook_return
543 process_hooks(struct main_context *m)
544 {
545   int hook_min = HOOK_RETRY;
546   int hook_max = HOOK_SHUTDOWN;
547   struct main_hook *ho;
548
549   while (ho = clist_remove_head(&m->hook_list))
550     {
551       clist_add_tail(&m->hook_done_list, &ho->n);
552       DBG("MAIN: Hook %p", ho);
553       int ret = ho->handler(ho);
554       hook_min = MIN(hook_min, ret);
555       hook_max = MAX(hook_max, ret);
556     }
557   clist_move(&m->hook_list, &m->hook_done_list);
558   if (hook_min == HOOK_SHUTDOWN ||
559     hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
560     m->shutdown)
561     {
562       DBG("MAIN: Shut down by %s", m->shutdown ? "main_shutdown" : "a hook");
563       return HOOK_SHUTDOWN;
564     }
565   if (hook_max == HOOK_RETRY)
566     return HOOK_RETRY;
567   else
568     return HOOK_IDLE;
569 }
570
571 void
572 main_loop(void)
573 {
574   DBG("MAIN: Entering main_loop");
575   struct main_context *m = main_current();
576
577   do_main_get_time(m);
578   for (;;)
579     {
580       timestamp_t wake = m->now + 1000000000;
581       process_timers(m);
582       switch (process_hooks(m))
583         {
584         case HOOK_SHUTDOWN:
585           return;
586         case HOOK_RETRY:
587           wake = 0;
588           break;
589         default: ;
590         }
591       if (m->poll_table_obsolete)
592         main_rebuild_poll_table(m);
593       if (count_timers(m))
594         wake = MIN(wake, m->timer_table[1]->expires);
595       do_main_get_time(m);
596       int timeout = ((wake > m->now) ? wake - m->now : 0);
597       DBG("MAIN: Poll for %d fds and timeout %d ms", m->file_cnt, timeout);
598       int p = poll(m->poll_table, m->file_cnt, timeout);
599       timestamp_t old_now = m->now;
600       do_main_get_time(m);
601       m->idle_time += m->now - old_now;
602       if (p > 0)
603         {
604           struct pollfd *p = m->poll_table;
605           CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
606             {
607               if (p->revents & (POLLIN | POLLHUP | POLLERR))
608                 {
609                   do
610                     DBG("MAIN: Read event on fd %d", p->fd);
611                   while (fi->read_handler && fi->read_handler(fi) && !m->poll_table_obsolete);
612                   if (m->poll_table_obsolete)   /* File entries have been inserted or deleted => better not risk continuing to nowhere */
613                     break;
614                 }
615               if (p->revents & (POLLOUT | POLLERR))
616                 {
617                   do
618                     DBG("MAIN: Write event on fd %d", p->fd);
619                   while (fi->write_handler && fi->write_handler(fi) && !m->poll_table_obsolete);
620                   if (m->poll_table_obsolete)
621                     break;
622                 }
623               p++;
624             }
625         }
626     }
627 }
628
629 #ifdef TEST
630
631 static struct main_process mp;
632 static struct main_block_io fin, fout;
633 static struct main_hook hook;
634 static struct main_timer tm;
635 static struct main_signal sg;
636
637 static byte rb[16];
638
639 static void dread(struct main_block_io *bio)
640 {
641   if (bio->rpos < bio->rlen)
642     {
643       msg(L_INFO, "Read EOF");
644       block_io_del(bio);
645     }
646   else
647     {
648       msg(L_INFO, "Read done");
649       block_io_read(bio, rb, sizeof(rb));
650     }
651 }
652
653 static void derror(struct main_block_io *bio, int cause)
654 {
655   msg(L_INFO, "Error: %m !!! (cause %d)", cause);
656   block_io_del(bio);
657 }
658
659 static void dwrite(struct main_block_io *bio UNUSED)
660 {
661   msg(L_INFO, "Write done");
662 }
663
664 static int dhook(struct main_hook *ho UNUSED)
665 {
666   msg(L_INFO, "Hook called");
667   return 0;
668 }
669
670 static void dtimer(struct main_timer *tm)
671 {
672   msg(L_INFO, "Timer tick");
673   timer_add_rel(tm, 11000);
674   timer_add_rel(tm, 10000);
675 }
676
677 static void dentry(void)
678 {
679   msg(L_INFO, "*** SUBPROCESS START ***");
680   sleep(2);
681   msg(L_INFO, "*** SUBPROCESS FINISH ***");
682   exit(0);
683 }
684
685 static void dexit(struct main_process *pr)
686 {
687   msg(L_INFO, "Subprocess %d exited with status %x", pr->pid, pr->status);
688 }
689
690 static void dsignal(struct main_signal *sg UNUSED)
691 {
692   msg(L_INFO, "SIGINT received (use Ctrl-\\ to really quit)");
693 }
694
695 int
696 main(void)
697 {
698   log_init(NULL);
699   main_init();
700
701   fin.read_done = dread;
702   fin.error_handler = derror;
703   block_io_add(&fin, 0);
704   block_io_read(&fin, rb, sizeof(rb));
705
706   fout.write_done = dwrite;
707   fout.error_handler = derror;
708   block_io_add(&fout, 1);
709   block_io_write(&fout, "Hello, world!\n", 14);
710
711   hook.handler = dhook;
712   hook_add(&hook);
713
714   tm.handler = dtimer;
715   timer_add_rel(&tm,  1000);
716
717   sg.signum = SIGINT;
718   sg.handler = dsignal;
719   signal_add(&sg);
720
721   mp.handler = dexit;
722   if (!process_fork(&mp))
723     dentry();
724
725   main_debug();
726
727   main_loop();
728   msg(L_INFO, "Finished.");
729 }
730
731 #endif