]> mj.ucw.cz Git - libucw.git/blob - ucw/mainloop.c
50eb636dc0488eca21e471ecdda399712706bb1b
[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 #define MAIN_TIMER_LESS(x,y) ((x)->expires < (y)->expires)
31 #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))
32
33 // FIXME: Delivery of signals to threads?
34 static uns main_sigchld_set_up;
35 static volatile sig_atomic_t chld_received = 0;
36
37 #ifdef O_CLOEXEC
38 // On recent Linux systems, O_CLOEXEC flag is available and we can get around
39 // the race condition of poll().
40 #define USE_SELF_PIPE
41 static int sig_pipe_recv, sig_pipe_send;
42 #endif
43
44 static void
45 do_main_get_time(struct main_context *m)
46 {
47   struct timeval tv;
48   gettimeofday(&tv, NULL);
49   m->now_seconds = tv.tv_sec;
50   m->now = (timestamp_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
51 }
52
53 struct main_context *
54 main_new(void)
55 {
56   struct main_context *m = xmalloc_zero(sizeof(*m));
57
58   DBG("MAIN: New context");
59   clist_init(&m->file_list);
60   clist_init(&m->hook_list);
61   clist_init(&m->hook_done_list);
62   clist_init(&m->process_list);
63   m->poll_table_obsolete = 1;
64   do_main_get_time(m);
65
66   return m;
67 }
68
69 void
70 main_delete(struct main_context *m)
71 {
72   ASSERT(clist_empty(&m->file_list));
73   ASSERT(clist_empty(&m->hook_list));
74   ASSERT(clist_empty(&m->hook_done_list));
75   ASSERT(clist_empty(&m->process_list));
76   if (m->timer_table)
77     GARY_FREE(m->timer_table);
78   xfree(m->poll_table);
79   xfree(m);
80   // FIXME: Some mechanism for cleaning up after fork()
81 }
82
83 struct main_context *
84 main_switch_context(struct main_context *m)
85 {
86   struct ucwlib_context *c = ucwlib_thread_context();
87   struct main_context *m0 = c->main_context;
88   c->main_context = m;
89   return m0;
90 }
91
92 struct main_context *
93 main_current(void)
94 {
95   struct ucwlib_context *c = ucwlib_thread_context();
96   struct main_context *m = c->main_context;
97   ASSERT(m);
98   return m;
99 }
100
101 void
102 main_init(void)
103 {
104   struct main_context *m = main_switch_context(main_new());
105   ASSERT(!m);
106 }
107
108 void
109 main_cleanup(void)
110 {
111   struct main_context *m = main_switch_context(NULL);
112   main_delete(m);
113 }
114
115 void
116 main_get_time(void)
117 {
118   do_main_get_time(main_current());
119 }
120
121 static inline uns
122 count_timers(struct main_context *m)
123 {
124   return GARY_SIZE(m->timer_table) - 1;
125 }
126
127 void
128 timer_add(struct main_timer *tm, timestamp_t expires)
129 {
130   struct main_context *m = main_current();
131
132   if (!m->timer_table)
133     {
134       GARY_INIT(m->timer_table, 1);
135       m->timer_table[0] = NULL;
136     }
137
138   if (expires)
139     DBG("MAIN: Setting timer %p (expire at now+%lld)", tm, (long long)(expires - m->now));
140   else
141     DBG("MAIN: Clearing timer %p", tm);
142   uns num_timers = count_timers(m);
143   if (tm->expires < expires)
144     {
145       if (!tm->expires)
146         {
147           tm->expires = expires;
148           tm->index = num_timers + 1;
149           *GARY_PUSH(m->timer_table, 1) = tm;
150           HEAP_INSERT(struct main_timer *, m->timer_table, tm->index, MAIN_TIMER_LESS, MAIN_TIMER_SWAP);
151         }
152       else
153         {
154           tm->expires = expires;
155           HEAP_INCREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
156         }
157     }
158   else if (tm->expires > expires)
159     {
160       if (!expires)
161         {
162           ASSERT(tm->index && tm->index <= num_timers);
163           HEAP_DELETE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
164           tm->index = 0;
165           tm->expires = 0;
166           GARY_POP(m->timer_table, 1);
167         }
168       else
169         {
170           tm->expires = expires;
171           HEAP_DECREASE(struct main_timer *, m->timer_table, num_timers, MAIN_TIMER_LESS, MAIN_TIMER_SWAP, tm->index);
172         }
173     }
174 }
175
176 void
177 timer_add_rel(struct main_timer *tm, timestamp_t expires_delta)
178 {
179   struct main_context *m = main_current();
180   return timer_add(tm, m->now + expires_delta);
181 }
182
183 void
184 timer_del(struct main_timer *tm)
185 {
186   timer_add(tm, 0);
187 }
188
189 static void
190 file_timer_expired(struct main_timer *tm)
191 {
192   struct main_file *fi = tm->data;
193   timer_del(&fi->timer);
194   if (fi->error_handler)
195     fi->error_handler(fi, MFERR_TIMEOUT);
196 }
197
198 void
199 file_add(struct main_file *fi)
200 {
201   struct main_context *m = main_current();
202
203   DBG("MAIN: Adding file %p (fd=%d)", fi, fi->fd);
204   ASSERT(!fi->n.next);
205   clist_add_tail(&m->file_list, &fi->n);
206   fi->timer.handler = file_timer_expired;
207   fi->timer.data = fi;
208   m->file_cnt++;
209   m->poll_table_obsolete = 1;
210   if (fcntl(fi->fd, F_SETFL, O_NONBLOCK) < 0)
211     msg(L_ERROR, "Error setting fd %d to non-blocking mode: %m. Keep fingers crossed.", fi->fd);
212 }
213
214 void
215 file_chg(struct main_file *fi)
216 {
217   struct pollfd *p = fi->pollfd;
218   if (p)
219     {
220       p->events = 0;
221       if (fi->read_handler)
222         p->events |= POLLIN | POLLHUP | POLLERR;
223       if (fi->write_handler)
224         p->events |= POLLOUT | POLLERR;
225     }
226 }
227
228 void
229 file_del(struct main_file *fi)
230 {
231   struct main_context *m = main_current();
232
233   DBG("MAIN: Deleting file %p (fd=%d)", fi, fi->fd);
234   ASSERT(fi->n.next);
235   timer_del(&fi->timer);
236   clist_remove(&fi->n);
237   m->file_cnt--;
238   m->poll_table_obsolete = 1;
239   fi->n.next = fi->n.prev = NULL;
240 }
241
242 static int
243 file_read_handler(struct main_file *fi)
244 {
245   while (fi->rpos < fi->rlen)
246     {
247       int l = read(fi->fd, fi->rbuf + fi->rpos, fi->rlen - fi->rpos);
248       DBG("MAIN: FD %d: read %d", fi->fd, l);
249       if (l < 0)
250         {
251           if (errno != EINTR && errno != EAGAIN && fi->error_handler)
252             fi->error_handler(fi, MFERR_READ);
253           return 0;
254         }
255       else if (!l)
256         break;
257       fi->rpos += l;
258     }
259   DBG("MAIN: FD %d done read %d of %d", fi->fd, fi->rpos, fi->rlen);
260   fi->read_handler = NULL;
261   file_chg(fi);
262   fi->read_done(fi);
263   return 1;
264 }
265
266 static int
267 file_write_handler(struct main_file *fi)
268 {
269   while (fi->wpos < fi->wlen)
270     {
271       int l = write(fi->fd, fi->wbuf + fi->wpos, fi->wlen - fi->wpos);
272       DBG("MAIN: FD %d: write %d", fi->fd, l);
273       if (l < 0)
274         {
275           if (errno != EINTR && errno != EAGAIN && fi->error_handler)
276             fi->error_handler(fi, MFERR_WRITE);
277           return 0;
278         }
279       fi->wpos += l;
280     }
281   DBG("MAIN: FD %d done write %d", fi->fd, fi->wpos);
282   fi->write_handler = NULL;
283   file_chg(fi);
284   fi->write_done(fi);
285   return 1;
286 }
287
288 void
289 file_read(struct main_file *fi, void *buf, uns len)
290 {
291   ASSERT(fi->n.next);
292   if (len)
293     {
294       fi->read_handler = file_read_handler;
295       fi->rbuf = buf;
296       fi->rpos = 0;
297       fi->rlen = len;
298     }
299   else
300     {
301       fi->read_handler = NULL;
302       fi->rbuf = NULL;
303       fi->rpos = fi->rlen = 0;
304     }
305   file_chg(fi);
306 }
307
308 void
309 file_write(struct main_file *fi, void *buf, uns len)
310 {
311   ASSERT(fi->n.next);
312   if (len)
313     {
314       fi->write_handler = file_write_handler;
315       fi->wbuf = buf;
316       fi->wpos = 0;
317       fi->wlen = len;
318     }
319   else
320     {
321       fi->write_handler = NULL;
322       fi->wbuf = NULL;
323       fi->wpos = fi->wlen = 0;
324     }
325   file_chg(fi);
326 }
327
328 void
329 file_set_timeout(struct main_file *fi, timestamp_t expires)
330 {
331   ASSERT(fi->n.next);
332   timer_add(&fi->timer, expires);
333 }
334
335 void
336 file_close_all(void)
337 {
338   struct main_context *m = main_current();
339
340   CLIST_FOR_EACH(struct main_file *, f, m->file_list)
341     close(f->fd);
342 }
343
344 void
345 hook_add(struct main_hook *ho)
346 {
347   struct main_context *m = main_current();
348
349   DBG("MAIN: Adding hook %p", ho);
350   ASSERT(!ho->n.next);
351   clist_add_tail(&m->hook_list, &ho->n);
352 }
353
354 void
355 hook_del(struct main_hook *ho)
356 {
357   DBG("MAIN: Deleting hook %p", ho);
358   ASSERT(ho->n.next);
359   clist_remove(&ho->n);
360   ho->n.next = ho->n.prev = NULL;
361 }
362
363 #ifdef USE_SELF_PIPE
364 static void
365 main_sigchld_handler(int x UNUSED)
366 {
367   int old_errno = errno;
368   DBG("SIGCHLD received");
369   chld_received = 1;
370   ssize_t result;
371   while((result = write(sig_pipe_send, "c", 1)) == -1 && errno == EINTR);
372   if(result == -1 && errno != EAGAIN)
373     msg(L_SIGHANDLER|L_ERROR, "Could not write to self-pipe: %m");
374   errno = old_errno;
375 }
376
377 static int
378 dummy_read_handler(struct main_file *mp)
379 {
380   char buffer[1024];
381   ssize_t result = read(mp->fd, buffer, 1024);
382   if(result == -1 && errno != EAGAIN)
383     msg(L_ERROR, "Could not read from selfpipe: %m");
384   file_chg(mp);
385   return result == 1024;
386 }
387
388 static void
389 pipe_configure(int fd)
390 {
391   int flags;
392   if((flags = fcntl(fd, F_GETFL)) == -1 || fcntl(fd, F_SETFL, flags|O_NONBLOCK))
393     die("Could not set file descriptor %d to non-blocking: %m", fd);
394   if((flags = fcntl(fd, F_GETFD)) == -1 || fcntl(fd, F_SETFD, flags|O_CLOEXEC))
395     die("Could not set file descriptor %d to close-on-exec: %m", fd);
396 }
397 #else
398 static void
399 main_sigchld_handler(int x UNUSED)
400 {
401   DBG("SIGCHLD received");
402 }
403 #endif
404
405 void
406 process_add(struct main_process *mp)
407 {
408   struct main_context *m = main_current();
409
410   DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
411   ASSERT(!mp->n.next);
412   ASSERT(mp->handler);
413   clist_add_tail(&m->process_list, &mp->n);
414   if (!main_sigchld_set_up)
415     {
416 #ifdef USE_SELF_PIPE
417       int pipe_result[2];
418       if(pipe(pipe_result) == -1)
419         die("Could not create selfpipe:%m");
420       pipe_configure(pipe_result[0]);
421       pipe_configure(pipe_result[1]);
422       sig_pipe_recv = pipe_result[0];
423       sig_pipe_send = pipe_result[1];
424       static struct main_file self_pipe;
425       self_pipe = (struct main_file) {
426         .fd = sig_pipe_recv,
427         .read_handler = dummy_read_handler
428       };
429       file_add(&self_pipe);
430 #endif
431       struct sigaction sa;
432       bzero(&sa, sizeof(sa));
433       sa.sa_handler = main_sigchld_handler;
434       sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
435       sigaction(SIGCHLD, &sa, NULL);
436       main_sigchld_set_up = 1;
437       chld_received = 1; // The signal may have come before the handler
438     }
439 }
440
441 void
442 process_del(struct main_process *mp)
443 {
444   DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
445   ASSERT(mp->n.next);
446   clist_remove(&mp->n);
447   mp->n.next = NULL;
448 }
449
450 int
451 process_fork(struct main_process *mp)
452 {
453   pid_t pid = fork();
454   if (pid < 0)
455     {
456       DBG("MAIN: Fork failed");
457       mp->status = -1;
458       format_exit_status(mp->status_msg, -1);
459       mp->handler(mp);
460       return 1;
461     }
462   else if (!pid)
463     return 0;
464   else
465     {
466       DBG("MAIN: Forked process %d", (int) pid);
467       mp->pid = pid;
468       process_add(mp);
469       return 1;
470     }
471 }
472
473 void
474 main_debug_context(struct main_context *m UNUSED)
475 {
476 #ifdef CONFIG_DEBUG
477   msg(L_DEBUG, "### Main loop status on %lld", (long long) m->now);
478   msg(L_DEBUG, "\tActive timers:");
479   uns num_timers = count_timers(m);
480   for (uns i = 1; i <= num_timers; i++)
481     {
482       struct main_timer *tm = m->timer_table[i];
483       msg(L_DEBUG, "\t\t%p (expires %lld, data %p)", tm, (long long)(tm->expires ? tm->expires - m->now : 999999), tm->data);
484     }
485   struct main_file *fi;
486   msg(L_DEBUG, "\tActive files:");
487   CLIST_WALK(fi, m->file_list)
488     msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, eh %p, expires %lld, data %p)",
489         fi, fi->fd, fi->read_handler, fi->write_handler, fi->error_handler,
490         (long long)(fi->timer.expires ? fi->timer.expires - m->now : 999999), fi->data);
491   msg(L_DEBUG, "\tActive hooks:");
492   struct main_hook *ho;
493   CLIST_WALK(ho, m->hook_done_list)
494     msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
495   CLIST_WALK(ho, m->hook_list)
496     msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
497   msg(L_DEBUG, "\tActive processes:");
498   struct main_process *pr;
499   CLIST_WALK(pr, m->process_list)
500     msg(L_DEBUG, "\t\t%p (pid %d, data %p)", pr, pr->pid, pr->data);
501 #endif
502 }
503
504 static void
505 main_rebuild_poll_table(struct main_context *m)
506 {
507   struct main_file *fi;
508   if (m->poll_table_size < m->file_cnt)
509     {
510       if (m->poll_table)
511         xfree(m->poll_table);
512       else
513         m->poll_table_size = 1;
514       while (m->poll_table_size < m->file_cnt)
515         m->poll_table_size *= 2;
516       m->poll_table = xmalloc(sizeof(struct pollfd) * m->poll_table_size);
517     }
518   struct pollfd *p = m->poll_table;
519   DBG("MAIN: Rebuilding poll table: %d of %d entries set", m->file_cnt, m->poll_table_size);
520   CLIST_WALK(fi, m->file_list)
521     {
522       p->fd = fi->fd;
523       fi->pollfd = p++;
524       file_chg(fi);
525     }
526   m->poll_table_obsolete = 0;
527 }
528
529 void
530 main_loop(void)
531 {
532   DBG("MAIN: Entering main_loop");
533   struct main_context *m = main_current();
534
535   struct main_file *fi;
536   struct main_hook *ho;
537   struct main_timer *tm;
538   struct main_process *pr;
539
540   do_main_get_time(m);
541   for (;;)
542     {
543       timestamp_t wake = m->now + 1000000000;
544       while (GARY_SIZE(m->timer_table) > 1 && (tm = m->timer_table[1])->expires <= m->now)
545         {
546           DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(m->now - tm->expires));
547           tm->handler(tm);
548         }
549       int hook_min = HOOK_RETRY;
550       int hook_max = HOOK_SHUTDOWN;
551       while (ho = clist_remove_head(&m->hook_list))
552         {
553           clist_add_tail(&m->hook_done_list, &ho->n);
554           DBG("MAIN: Hook %p", ho);
555           int ret = ho->handler(ho);
556           hook_min = MIN(hook_min, ret);
557           hook_max = MAX(hook_max, ret);
558         }
559       clist_move(&m->hook_list, &m->hook_done_list);
560       if (hook_min == HOOK_SHUTDOWN ||
561           hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
562           m->shutdown)
563         {
564           DBG("MAIN: Shut down by %s", m->shutdown ? "main_shutdown" : "a hook");
565           return;
566         }
567       if (hook_max == HOOK_RETRY)
568         wake = 0;
569       if (m->poll_table_obsolete)
570         main_rebuild_poll_table(m);
571 #ifndef USE_SELF_PIPE
572       // We don't have a reliable flag without the self-pipe.
573       chld_received = 1;
574 #endif
575       if (chld_received && !clist_empty(&m->process_list))
576         {
577           int stat;
578           pid_t pid;
579           wake = MIN(wake, m->now + 10000);
580           chld_received = 0;
581           while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
582             {
583               DBG("MAIN: Child %d exited with status %x", pid, stat);
584               CLIST_WALK(pr, m->process_list)
585                 if (pr->pid == pid)
586                   {
587                     pr->status = stat;
588                     process_del(pr);
589                     format_exit_status(pr->status_msg, pr->status);
590                     DBG("MAIN: Calling process exit handler");
591                     pr->handler(pr);
592                     break;
593                   }
594               wake = 0;
595             }
596         }
597       if (count_timers(m) && (tm = m->timer_table[1])->expires < wake)
598         wake = tm->expires;
599       do_main_get_time(m);
600       int timeout = ((wake > m->now) ? wake - m->now : 0);
601       DBG("MAIN: Poll for %d fds and timeout %d ms", m->file_cnt, timeout);
602       int p = poll(m->poll_table, m->file_cnt, timeout);
603       timestamp_t old_now = m->now;
604       do_main_get_time(m);
605       m->idle_time += m->now - old_now;
606       if (p > 0)
607         {
608           struct pollfd *p = m->poll_table;
609           CLIST_WALK(fi, m->file_list)
610             {
611               if (p->revents & (POLLIN | POLLHUP | POLLERR))
612                 {
613                   do
614                     DBG("MAIN: Read event on fd %d", p->fd);
615                   while (fi->read_handler && fi->read_handler(fi) && !m->poll_table_obsolete);
616                   if (m->poll_table_obsolete)   /* File entries have been inserted or deleted => better not risk continuing to nowhere */
617                     break;
618                 }
619               if (p->revents & (POLLOUT | POLLERR))
620                 {
621                   do
622                     DBG("MAIN: Write event on fd %d", p->fd);
623                   while (fi->write_handler && fi->write_handler(fi) && !m->poll_table_obsolete);
624                   if (m->poll_table_obsolete)
625                     break;
626                 }
627               p++;
628             }
629         }
630     }
631 }
632
633 #ifdef TEST
634
635 static struct main_process mp;
636 static struct main_file fin, fout;
637 static struct main_hook hook;
638 static struct main_timer tm;
639
640 static byte rb[16];
641
642 static void dread(struct main_file *fi)
643 {
644   if (fi->rpos < fi->rlen)
645     {
646       msg(L_INFO, "Read EOF");
647       file_del(fi);
648     }
649   else
650     {
651       msg(L_INFO, "Read done");
652       file_read(fi, rb, sizeof(rb));
653     }
654 }
655
656 static void derror(struct main_file *fi, int cause)
657 {
658   msg(L_INFO, "Error: %m !!! (cause %d)", cause);
659   file_del(fi);
660 }
661
662 static void dwrite(struct main_file *fi UNUSED)
663 {
664   msg(L_INFO, "Write done");
665 }
666
667 static int dhook(struct main_hook *ho UNUSED)
668 {
669   msg(L_INFO, "Hook called");
670   return 0;
671 }
672
673 static void dtimer(struct main_timer *tm)
674 {
675   msg(L_INFO, "Timer tick");
676   timer_add_rel(tm, 11000);
677   timer_add_rel(tm, 10000);
678 }
679
680 static void dentry(void)
681 {
682   msg(L_INFO, "*** SUBPROCESS START ***");
683   sleep(2);
684   msg(L_INFO, "*** SUBPROCESS FINISH ***");
685   exit(0);
686 }
687
688 static void dexit(struct main_process *pr)
689 {
690   msg(L_INFO, "Subprocess %d exited with status %x", pr->pid, pr->status);
691 }
692
693 int
694 main(void)
695 {
696   log_init(NULL);
697   main_init();
698
699   fin.fd = 0;
700   fin.read_done = dread;
701   fin.error_handler = derror;
702   file_add(&fin);
703   file_read(&fin, rb, sizeof(rb));
704
705   fout.fd = 1;
706   fout.write_done = dwrite;
707   fout.error_handler = derror;
708   file_add(&fout);
709   file_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   mp.handler = dexit;
718   if (!process_fork(&mp))
719     dentry();
720
721   main_debug();
722
723   main_loop();
724   msg(L_INFO, "Finished.");
725 }
726
727 #endif