]> mj.ucw.cz Git - libucw.git/blob - ucw/mainloop.c
6bdf1e014203e160bd37fda173dbd15ecd0bcc07
[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   GARY_FREE(m->timer_table);
86   GARY_FREE(m->poll_table);
87   xfree(m);
88   // FIXME: Some mechanism for cleaning up after fork()
89 }
90
91 struct main_context *
92 main_switch_context(struct main_context *m)
93 {
94   struct ucwlib_context *c = ucwlib_thread_context();
95   struct main_context *m0 = c->main_context;
96
97   /*
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.
101    */
102   if (m0 && !clist_empty(&m0->signal_list))
103     THREAD_SIGMASK(SIG_BLOCK, &m0->want_signals, NULL);
104   c->main_context = m;
105   if (m && !clist_empty(&m->signal_list))
106     THREAD_SIGMASK(SIG_UNBLOCK, &m->want_signals, NULL);
107
108   return m0;
109 }
110
111 struct main_context *
112 main_current(void)
113 {
114   struct ucwlib_context *c = ucwlib_thread_context();
115   struct main_context *m = c->main_context;
116   ASSERT(m);
117   return m;
118 }
119
120 void
121 main_init(void)
122 {
123   struct main_context *m = main_switch_context(main_new());
124   ASSERT(!m);
125 }
126
127 void
128 main_cleanup(void)
129 {
130   struct main_context *m = main_switch_context(NULL);
131   main_delete(m);
132 }
133
134 void
135 main_get_time(void)
136 {
137   do_main_get_time(main_current());
138 }
139
140 static inline uns
141 count_timers(struct main_context *m)
142 {
143   return GARY_SIZE(m->timer_table) - 1;
144 }
145
146 void
147 timer_add(struct main_timer *tm, timestamp_t expires)
148 {
149   struct main_context *m = main_current();
150
151   if (!m->timer_table)
152     {
153       GARY_INIT(m->timer_table, 1);
154       m->timer_table[0] = NULL;
155     }
156
157   if (expires)
158     DBG("MAIN: Setting timer %p (expire at now+%lld)", tm, (long long)(expires - m->now));
159   else
160     DBG("MAIN: Clearing timer %p", tm);
161   uns num_timers = count_timers(m);
162   if (tm->expires < expires)
163     {
164       if (!tm->expires)
165         {
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);
170         }
171       else
172         {
173           tm->expires = expires;
174           HEAP_INCREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
175         }
176     }
177   else if (tm->expires > expires)
178     {
179       if (!expires)
180         {
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);
183           tm->index = 0;
184           tm->expires = 0;
185           GARY_POP(m->timer_table, 1);
186         }
187       else
188         {
189           tm->expires = expires;
190           HEAP_DECREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
191         }
192     }
193 }
194
195 void
196 timer_add_rel(struct main_timer *tm, timestamp_t expires_delta)
197 {
198   struct main_context *m = main_current();
199   return timer_add(tm, m->now + expires_delta);
200 }
201
202 void
203 timer_del(struct main_timer *tm)
204 {
205   timer_add(tm, 0);
206 }
207
208 void
209 file_add(struct main_file *fi)
210 {
211   struct main_context *m = main_current();
212
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);
216   m->file_cnt++;
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);
220 }
221
222 void
223 file_chg(struct main_file *fi)
224 {
225   struct pollfd *p = fi->pollfd;
226   if (p)
227     {
228       p->events = 0;
229       if (fi->read_handler)
230         p->events |= POLLIN | POLLHUP | POLLERR;
231       if (fi->write_handler)
232         p->events |= POLLOUT | POLLERR;
233     }
234 }
235
236 void
237 file_del(struct main_file *fi)
238 {
239   struct main_context *m = main_current();
240
241   DBG("MAIN: Deleting file %p (fd=%d)", fi, fi->fd);
242   ASSERT(clist_is_linked(&fi->n));
243   clist_unlink(&fi->n);
244   m->file_cnt--;
245   m->poll_table_obsolete = 1;
246 }
247
248 void
249 file_close_all(void)
250 {
251   struct main_context *m = main_current();
252
253   CLIST_FOR_EACH(struct main_file *, f, m->file_list)
254     close(f->fd);
255 }
256
257 void
258 hook_add(struct main_hook *ho)
259 {
260   struct main_context *m = main_current();
261
262   DBG("MAIN: Adding hook %p", ho);
263   ASSERT(!clist_is_linked(&ho->n));
264   clist_add_tail(&m->hook_list, &ho->n);
265 }
266
267 void
268 hook_del(struct main_hook *ho)
269 {
270   DBG("MAIN: Deleting hook %p", ho);
271   ASSERT(clist_is_linked(&ho->n));
272   clist_unlink(&ho->n);
273 }
274
275 static void
276 sigchld_received(struct main_signal *sg UNUSED)
277 {
278   struct main_context *m = main_current();
279   int stat;
280   pid_t pid;
281
282   while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
283     {
284       DBG("MAIN: Child %d exited with status %x", pid, stat);
285       CLIST_FOR_EACH(struct main_process *, pr, m->process_list)
286         if (pr->pid == pid)
287           {
288             pr->status = stat;
289             process_del(pr);
290             format_exit_status(pr->status_msg, pr->status);
291             DBG("MAIN: Calling process exit handler");
292             pr->handler(pr);
293             break;
294           }
295     }
296 }
297
298 void
299 process_add(struct main_process *mp)
300 {
301   struct main_context *m = main_current();
302
303   DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
304   ASSERT(!clist_is_linked(&mp->n));
305   ASSERT(mp->handler);
306   clist_add_tail(&m->process_list, &mp->n);
307   if (!m->sigchld_handler)
308     {
309       struct main_signal *sg = xmalloc_zero(sizeof(*sg));
310       m->sigchld_handler = sg;
311       sg->signum = SIGCHLD;
312       sg->handler = sigchld_received;
313       signal_add(sg);
314     }
315 }
316
317 void
318 process_del(struct main_process *mp)
319 {
320   DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
321   ASSERT(clist_is_linked(&mp->n));
322   clist_unlink(&mp->n);
323 }
324
325 int
326 process_fork(struct main_process *mp)
327 {
328   pid_t pid = fork();
329   if (pid < 0)
330     {
331       DBG("MAIN: Fork failed");
332       mp->status = -1;
333       format_exit_status(mp->status_msg, -1);
334       mp->handler(mp);
335       return 1;
336     }
337   else if (!pid)
338     return 0;
339   else
340     {
341       DBG("MAIN: Forked process %d", (int) pid);
342       mp->pid = pid;
343       process_add(mp);
344       return 1;
345     }
346 }
347
348 static int
349 pipe_read_handler(struct main_file *mf UNUSED)
350 {
351   struct main_context *m = main_current();
352   int signum;
353   int n = read(m->sig_pipe_recv, &signum, sizeof(signum));
354
355   if (n < 0)
356     {
357       if (errno != EAGAIN)
358         msg(L_ERROR, "Error reading signal pipe: %m");
359       return 0;
360     }
361   ASSERT(n == sizeof(signum));
362
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);
366   while (sg)
367     {
368       if (sg->signum == signum)
369         {
370           DBG("MAIN: Sigpipe: invoking handler %p", sg);
371           clist_insert_after(&iter.n, &sg->n);
372           sg->handler(sg);
373           sg = clist_next(&m->signal_list, &iter.n);
374           clist_remove(&iter.n);
375         }
376       else
377         sg = clist_next(&m->signal_list, &sg->n);
378     }
379
380   return 1;
381 }
382
383 static void
384 pipe_configure(int fd)
385 {
386   int flags;
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);
389 }
390
391 static void
392 pipe_setup(struct main_context *m)
393 {
394   DBG("MAIN: Sigpipe: Setting up the pipe");
395
396   int pipe_result[2];
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];
403
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;
408   file_add(f);
409 }
410
411 static void
412 signal_handler_pipe(int signum)
413 {
414   struct main_context *m = main_current();
415 #ifdef LOCAL_DEBUG
416   msg(L_DEBUG | L_SIGHANDLER, "MAIN: Sigpipe: sending signal %d down the drain", signum);
417 #endif
418   write(m->sig_pipe_send, &signum, sizeof(signum));
419 }
420
421 void
422 signal_add(struct main_signal *ms)
423 {
424   struct main_context *m = main_current();
425
426   DBG("MAIN: Adding signal %p (sig=%d)", ms, ms->signum);
427
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)
432     pipe_setup(m);
433
434   struct sigaction sa = {
435     .sa_handler = signal_handler_pipe,
436     .sa_flags = SA_NOCLDSTOP | SA_RESTART,
437   };
438   sigaction(ms->signum, &sa, NULL);
439
440   sigset_t ss;
441   sigemptyset(&ss);
442   sigaddset(&ss, ms->signum);
443   THREAD_SIGMASK(SIG_UNBLOCK, &ss, NULL);
444   sigaddset(&m->want_signals, ms->signum);
445 }
446
447 void
448 signal_del(struct main_signal *ms)
449 {
450   struct main_context *m = main_current();
451
452   DBG("MAIN: Deleting signal %p (sig=%d)", ms, ms->signum);
453
454   ASSERT(clist_is_linked(&ms->n));
455   clist_unlink(&ms->n);
456
457   int another = 0;
458   CLIST_FOR_EACH(struct main_signal *, s, m->signal_list)
459     if (s->signum == ms->signum)
460       another++;
461   if (!another)
462     {
463       sigset_t ss;
464       sigemptyset(&ss);
465       sigaddset(&ss, ms->signum);
466       THREAD_SIGMASK(SIG_BLOCK, &ss, NULL);
467       sigdelset(&m->want_signals, ms->signum);
468     }
469 }
470
471 void
472 main_debug_context(struct main_context *m UNUSED)
473 {
474 #ifdef CONFIG_DEBUG
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++)
479     {
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);
482     }
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)
498     if (sg->signum < 0)
499       msg(L_DEBUG, "\t\t(placeholder)");
500     else
501       msg(L_DEBUG, "\t\t%p (sig %d, func %p, data %p)", sg, sg->signum, sg->handler, sg->data);
502 #endif
503 }
504
505 static void
506 main_rebuild_poll_table(struct main_context *m)
507 {
508   GARY_INIT_OR_RESIZE(m->poll_table, m->file_cnt);
509   DBG("MAIN: Rebuilding poll table: %d entries", m->file_cnt);
510
511   struct pollfd *p = m->poll_table;
512   CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
513     {
514       p->fd = fi->fd;
515       fi->pollfd = p++;
516       file_chg(fi);
517     }
518   m->poll_table_obsolete = 0;
519 }
520
521 static void
522 process_timers(struct main_context *m)
523 {
524   struct main_timer *tm;
525   while (GARY_SIZE(m->timer_table) > 1 && (tm = m->timer_table[1])->expires <= m->now)
526     {
527       DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(m->now - tm->expires));
528       tm->handler(tm);
529     }
530 }
531
532 static enum main_hook_return
533 process_hooks(struct main_context *m)
534 {
535   int hook_min = HOOK_RETRY;
536   int hook_max = HOOK_SHUTDOWN;
537   struct main_hook *ho;
538
539   while (ho = clist_remove_head(&m->hook_list))
540     {
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);
546     }
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 ||
550     m->shutdown)
551     {
552       DBG("MAIN: Shut down by %s", m->shutdown ? "main_shutdown" : "a hook");
553       return HOOK_SHUTDOWN;
554     }
555   if (hook_max == HOOK_RETRY)
556     return HOOK_RETRY;
557   else
558     return HOOK_IDLE;
559 }
560
561 void
562 main_loop(void)
563 {
564   DBG("MAIN: Entering main_loop");
565   struct main_context *m = main_current();
566
567   do_main_get_time(m);
568   for (;;)
569     {
570       timestamp_t wake = m->now + 1000000000;
571       process_timers(m);
572       switch (process_hooks(m))
573         {
574         case HOOK_SHUTDOWN:
575           return;
576         case HOOK_RETRY:
577           wake = 0;
578           break;
579         default: ;
580         }
581       if (m->poll_table_obsolete)
582         main_rebuild_poll_table(m);
583       if (count_timers(m))
584         wake = MIN(wake, m->timer_table[1]->expires);
585       do_main_get_time(m);
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;
590       do_main_get_time(m);
591       m->idle_time += m->now - old_now;
592       if (p > 0)
593         {
594           struct pollfd *p = m->poll_table;
595           CLIST_FOR_EACH(struct main_file *, fi, m->file_list)
596             {
597               if (p->revents & (POLLIN | POLLHUP | POLLERR))
598                 {
599                   do
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 */
603                     break;
604                 }
605               if (p->revents & (POLLOUT | POLLERR))
606                 {
607                   do
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)
611                     break;
612                 }
613               p++;
614             }
615         }
616     }
617 }
618
619 #ifdef TEST
620
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;
626
627 static byte rb[16];
628
629 static void dread(struct main_block_io *bio)
630 {
631   if (bio->rpos < bio->rlen)
632     {
633       msg(L_INFO, "Read EOF");
634       block_io_del(bio);
635     }
636   else
637     {
638       msg(L_INFO, "Read done");
639       block_io_read(bio, rb, sizeof(rb));
640     }
641 }
642
643 static void derror(struct main_block_io *bio, int cause)
644 {
645   msg(L_INFO, "Error: %m !!! (cause %d)", cause);
646   block_io_del(bio);
647 }
648
649 static void dwrite(struct main_block_io *bio UNUSED)
650 {
651   msg(L_INFO, "Write done");
652 }
653
654 static int dhook(struct main_hook *ho UNUSED)
655 {
656   msg(L_INFO, "Hook called");
657   return 0;
658 }
659
660 static void dtimer(struct main_timer *tm)
661 {
662   msg(L_INFO, "Timer tick");
663   timer_add_rel(tm, 11000);
664   timer_add_rel(tm, 10000);
665 }
666
667 static void dentry(void)
668 {
669   msg(L_INFO, "*** SUBPROCESS START ***");
670   sleep(2);
671   msg(L_INFO, "*** SUBPROCESS FINISH ***");
672   exit(0);
673 }
674
675 static void dexit(struct main_process *pr)
676 {
677   msg(L_INFO, "Subprocess %d exited with status %x", pr->pid, pr->status);
678 }
679
680 static void dsignal(struct main_signal *sg UNUSED)
681 {
682   msg(L_INFO, "SIGINT received (use Ctrl-\\ to really quit)");
683 }
684
685 int
686 main(void)
687 {
688   log_init(NULL);
689   main_init();
690
691   fin.read_done = dread;
692   fin.error_handler = derror;
693   block_io_add(&fin, 0);
694   block_io_read(&fin, rb, sizeof(rb));
695
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);
700
701   hook.handler = dhook;
702   hook_add(&hook);
703
704   tm.handler = dtimer;
705   timer_add_rel(&tm,  1000);
706
707   sg.signum = SIGINT;
708   sg.handler = dsignal;
709   signal_add(&sg);
710
711   mp.handler = dexit;
712   if (!process_fork(&mp))
713     dentry();
714
715   main_debug();
716
717   main_loop();
718   msg(L_INFO, "Finished.");
719 }
720
721 #endif