]> mj.ucw.cz Git - libucw.git/blob - lib/mainloop.c
5b5fb45a8b2077f765aa3bcf73d23b5abc635ea3
[libucw.git] / lib / mainloop.c
1 /*
2  *      UCW Library -- Main Loop
3  *
4  *      (c) 2004--2005 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 "lib/lib.h"
13 #include "lib/mainloop.h"
14
15 #include <stdio.h>
16 #include <string.h>
17 #include <stdlib.h>
18 #include <unistd.h>
19 #include <signal.h>
20 #include <fcntl.h>
21 #include <errno.h>
22 #include <time.h>
23 #include <sys/poll.h>
24 #include <sys/wait.h>
25 #include <sys/time.h>
26
27 timestamp_t main_now;
28 sh_time_t main_now_seconds;
29 uns main_shutdown;
30
31 clist main_timer_list, main_file_list, main_hook_list, main_process_list;
32 static uns main_file_cnt;
33 static uns main_poll_table_obsolete, main_poll_table_size;
34 static struct pollfd *main_poll_table;
35 static uns main_sigchld_set_up;
36
37 void
38 main_get_time(void)
39 {
40   struct timeval tv;
41   gettimeofday(&tv, NULL);
42   main_now_seconds = tv.tv_sec;
43   main_now = (timestamp_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
44   DBG("It's %Ld o'clock", (long long) main_now);
45 }
46
47 void
48 main_init(void)
49 {
50   DBG("MAIN: Initializing");
51   clist_init(&main_timer_list);
52   clist_init(&main_file_list);
53   clist_init(&main_hook_list);
54   clist_init(&main_process_list);
55   main_get_time();
56 }
57
58 void
59 timer_add(struct main_timer *tm, timestamp_t expires)
60 {
61   if (tm->expires)
62     clist_remove(&tm->n);
63   tm->expires = expires;
64   if (expires)
65     {
66       cnode *t = main_timer_list.head.next;
67       while (t != &main_timer_list.head && ((struct main_timer *) t)->expires < expires)
68         t = t->next;
69       clist_insert_before(&tm->n, t);
70     }
71 }
72
73 void
74 timer_del(struct main_timer *tm)
75 {
76   timer_add(tm, 0);
77 }
78
79 static void
80 file_timer_expired(struct main_timer *tm)
81 {
82   struct main_file *fi = tm->data;
83   timer_del(&fi->timer);
84   if (fi->error_handler)
85     fi->error_handler(fi, MFERR_TIMEOUT);
86 }
87
88 void
89 file_add(struct main_file *fi)
90 {
91   ASSERT(!fi->n.next);
92   clist_add_tail(&main_file_list, &fi->n);
93   fi->timer.handler = file_timer_expired;
94   fi->timer.data = fi;
95   main_file_cnt++;
96   main_poll_table_obsolete = 1;
97   if (fcntl(fi->fd, F_SETFL, O_NONBLOCK) < 0)
98     log(L_ERROR, "Error setting fd %d to non-blocking mode: %m. Keep fingers crossed.", fi->fd);
99 }
100
101 void
102 file_chg(struct main_file *fi)
103 {
104   struct pollfd *p = fi->pollfd;
105   if (p)
106     {
107       p->events = 0;
108       if (fi->read_handler)
109         p->events |= POLLIN | POLLHUP | POLLERR;
110       if (fi->write_handler)
111         p->events |= POLLOUT | POLLERR;
112     }
113 }
114
115 void
116 file_del(struct main_file *fi)
117 {
118   ASSERT(fi->n.next);
119   timer_del(&fi->timer);
120   clist_remove(&fi->n);
121   main_file_cnt--;
122   main_poll_table_obsolete = 1;
123   fi->n.next = fi->n.prev = NULL;
124 }
125
126 static int
127 file_read_handler(struct main_file *fi)
128 {
129   while (fi->rpos < fi->rlen)
130     {
131       int l = read(fi->fd, fi->rbuf + fi->rpos, fi->rlen - fi->rpos);
132       DBG("MAIN: FD %d: read %d", fi->fd, l);
133       if (l < 0)
134         {
135           if (errno != EINTR && errno != EAGAIN && fi->error_handler)
136             fi->error_handler(fi, MFERR_READ);
137           return 0;
138         }
139       else if (!l)
140         break;
141       fi->rpos += l;
142     }
143   DBG("MAIN: FD %d done read %d of %d", fi->fd, fi->rpos, fi->rlen);
144   fi->read_handler = NULL;
145   file_chg(fi);
146   fi->read_done(fi);
147   return 1;
148 }
149
150 static int
151 file_write_handler(struct main_file *fi)
152 {
153   while (fi->wpos < fi->wlen)
154     {
155       int l = write(fi->fd, fi->wbuf + fi->wpos, fi->wlen - fi->wpos);
156       DBG("MAIN: FD %d: write %d", fi->fd, l);
157       if (l < 0)
158         {
159           if (errno != EINTR && errno != EAGAIN && fi->error_handler)
160             fi->error_handler(fi, MFERR_WRITE);
161           return 0;
162         }
163       fi->wpos += l;
164     }
165   DBG("MAIN: FD %d done write %d", fi->fd, fi->wpos);
166   fi->write_handler = NULL;
167   file_chg(fi);
168   fi->write_done(fi);
169   return 1;
170 }
171
172 void
173 file_read(struct main_file *fi, void *buf, uns len)
174 {
175   ASSERT(fi->n.next);
176   if (len)
177     {
178       fi->read_handler = file_read_handler;
179       fi->rbuf = buf;
180       fi->rpos = 0;
181       fi->rlen = len;
182     }
183   else
184     {
185       fi->read_handler = NULL;
186       fi->rbuf = NULL;
187       fi->rpos = fi->rlen = 0;
188     }
189   file_chg(fi);
190 }
191
192 void
193 file_write(struct main_file *fi, void *buf, uns len)
194 {
195   ASSERT(fi->n.next);
196   if (len)
197     {
198       fi->write_handler = file_write_handler;
199       fi->wbuf = buf;
200       fi->wpos = 0;
201       fi->wlen = len;
202     }
203   else
204     {
205       fi->write_handler = NULL;
206       fi->wbuf = NULL;
207       fi->wpos = fi->wlen = 0;
208     }
209   file_chg(fi);
210 }
211
212 void
213 file_set_timeout(struct main_file *fi, timestamp_t expires)
214 {
215   ASSERT(fi->n.next);
216   timer_add(&fi->timer, expires);
217 }
218
219 void
220 file_close_all(void)
221 {
222   CLIST_FOR_EACH(struct main_file *, f, main_file_list)
223     close(f->fd);
224 }
225
226 void
227 hook_add(struct main_hook *ho)
228 {
229   ASSERT(!ho->n.next);
230   clist_add_tail(&main_hook_list, &ho->n);
231 }
232
233 void
234 hook_del(struct main_hook *ho)
235 {
236   ASSERT(ho->n.next);
237   clist_remove(&ho->n);
238   ho->n.next = ho->n.prev = NULL;
239 }
240
241 static void
242 main_sigchld_handler(int x UNUSED)
243 {
244   DBG("SIGCHLD received");
245 }
246
247 void
248 process_add(struct main_process *mp)
249 {
250   ASSERT(!mp->n.next);
251   ASSERT(mp->handler);
252   clist_add_tail(&main_process_list, &mp->n);
253   if (!main_sigchld_set_up)
254     {
255       struct sigaction sa;
256       bzero(&sa, sizeof(sa));
257       sa.sa_handler = main_sigchld_handler;
258       sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
259       sigaction(SIGCHLD, &sa, NULL);
260       main_sigchld_set_up = 1;
261     }
262 }
263
264 void
265 process_del(struct main_process *mp)
266 {
267   ASSERT(mp->n.next);
268   clist_remove(&mp->n);
269   mp->pid = 0;
270   mp->n.next = NULL;
271 }
272
273 int
274 process_fork(struct main_process *mp)
275 {
276   ASSERT(!mp->pid);
277   pid_t pid = fork();
278   if (pid < 0)
279     {
280       DBG("MAIN: Fork failed");
281       mp->status = -1;
282       format_exit_status(mp->status_msg, -1);
283       mp->handler(mp);
284       return 1;
285     }
286   else if (!pid)
287     return 0;
288   else
289     {
290       DBG("MAIN: Forked process %d", (int) pid);
291       mp->pid = pid;
292       process_add(mp);
293       return 1;
294     }
295 }
296
297 void
298 main_debug(void)
299 {
300 #ifdef CONFIG_DEBUG
301   log(L_DEBUG, "### Main loop status on %Ld", (long long)main_now);
302   log(L_DEBUG, "\tActive timers:");
303   struct main_timer *tm;
304   CLIST_WALK(tm, main_timer_list)
305     log(L_DEBUG, "\t\t%p (expires %Ld, data %p)", tm, (long long)(tm->expires ? tm->expires-main_now : 999999), tm->data);
306   struct main_file *fi;
307   log(L_DEBUG, "\tActive files:");
308   CLIST_WALK(fi, main_file_list)
309     log(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, eh %p, expires %Ld, data %p)",
310         fi, fi->fd, fi->read_handler, fi->write_handler, fi->error_handler,
311         (long long)(fi->timer.expires ? fi->timer.expires-main_now : 999999), fi->data);
312   log(L_DEBUG, "\tActive hooks:");
313   struct main_hook *ho;
314   CLIST_WALK(ho, main_hook_list)
315     log(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
316   log(L_DEBUG, "\tActive processes:");
317   struct main_process *pr;
318   CLIST_WALK(pr, main_process_list)
319     log(L_DEBUG, "\t\t%p (pid %d, data %p)", pr, pr->pid, pr->data);
320 #endif
321 }
322
323 static void
324 main_rebuild_poll_table(void)
325 {
326   struct main_file *fi;
327   if (main_poll_table_size < main_file_cnt)
328     {
329       if (main_poll_table)
330         xfree(main_poll_table);
331       else
332         main_poll_table_size = 1;
333       while (main_poll_table_size < main_file_cnt)
334         main_poll_table_size *= 2;
335       main_poll_table = xmalloc(sizeof(struct pollfd) * main_poll_table_size);
336     }
337   struct pollfd *p = main_poll_table;
338   DBG("MAIN: Rebuliding poll table: %d of %d entries set", main_file_cnt, main_poll_table_size);
339   CLIST_WALK(fi, main_file_list)
340     {
341       p->fd = fi->fd;
342       fi->pollfd = p++;
343       file_chg(fi);
344     }
345   main_poll_table_obsolete = 0;
346 }
347
348 void
349 main_loop(void)
350 {
351   DBG("MAIN: Entering main_loop");
352   ASSERT(main_timer_list.head.next);
353
354   struct main_file *fi;
355   struct main_hook *ho;
356   struct main_timer *tm;
357   struct main_process *pr;
358   cnode *tmp;
359
360   for (;;)
361     {
362       main_get_time();
363       timestamp_t wake = main_now + 1000000000;
364       while ((tm = clist_head(&main_timer_list)) && tm->expires <= main_now)
365         {
366           DBG("MAIN: Timer %p expired at %Ld", tm, (long long) tm->expires);
367           tm->handler(tm);
368         }
369       int hook_min = HOOK_RETRY;
370       int hook_max = HOOK_SHUTDOWN;
371       CLIST_WALK_DELSAFE(ho, main_hook_list, tmp)
372         {
373           DBG("MAIN: Hook %p", ho);
374           int ret = ho->handler(ho);
375           hook_min = MIN(hook_min, ret);
376           hook_max = MAX(hook_max, ret);
377         }
378       if (hook_min == HOOK_SHUTDOWN ||
379           hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
380           main_shutdown)
381         {
382           DBG("MAIN: Shut down by %s", main_shutdown ? "main_shutdown" : "a hook");
383           return;
384         }
385       if (hook_max == HOOK_RETRY)
386         wake = 0;
387       if (main_poll_table_obsolete)
388         main_rebuild_poll_table();
389       if (!clist_empty(&main_process_list))
390         {
391           int stat;
392           pid_t pid;
393           wake = MIN(wake, main_now + 10000);
394           while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
395             {
396               DBG("MAIN: Child %d exited with status %x", pid, stat);
397               CLIST_WALK(pr, main_process_list)
398                 if (pr->pid == pid)
399                   {
400                     pr->status = stat;
401                     process_del(pr);
402                     format_exit_status(pr->status_msg, pr->status);
403                     DBG("MAIN: Calling process exit handler");
404                     pr->handler(pr);
405                     break;
406                   }
407               wake = 0;
408             }
409         }
410       /* FIXME: Here is a small race window where SIGCHLD can come unnoticed. */
411       if ((tm = clist_head(&main_timer_list)) && tm->expires < wake)
412         wake = tm->expires;
413       int timeout = (wake ? wake - main_now : 0);
414       DBG("MAIN: Poll for %d fds and timeout %d ms", main_file_cnt, timeout);
415       if (poll(main_poll_table, main_file_cnt, timeout))
416         {
417           struct pollfd *p = main_poll_table;
418           main_get_time();
419           CLIST_WALK(fi, main_file_list)
420             {
421               if (p->revents & (POLLIN | POLLHUP | POLLERR))
422                 {
423                   do
424                     DBG("MAIN: Read event on fd %d", p->fd);
425                   while (fi->read_handler && fi->read_handler(fi) && !main_poll_table_obsolete);
426                   if (main_poll_table_obsolete) /* File entries have been inserted or deleted => better not risk continuing to nowhere */
427                     break;
428                 }
429               if (p->revents & (POLLOUT | POLLERR))
430                 {
431                   do
432                     DBG("MAIN: Write event on fd %d", p->fd);
433                   while (fi->write_handler && fi->write_handler(fi) && !main_poll_table_obsolete);
434                   if (main_poll_table_obsolete)
435                     break;
436                 }
437               p++;
438             }
439         }
440     }
441 }
442
443 #ifdef TEST
444
445 static struct main_process mp;
446 static struct main_file fin, fout;
447 static struct main_hook hook;
448 static struct main_timer tm;
449
450 static byte rb[16];
451
452 static void dread(struct main_file *fi)
453 {
454   if (fi->rpos < fi->rlen)
455     {
456       log(L_INFO, "Read EOF");
457       file_del(fi);
458     }
459   else
460     {
461       log(L_INFO, "Read done");
462       file_read(fi, rb, sizeof(rb));
463     }
464 }
465
466 static void derror(struct main_file *fi, int cause)
467 {
468   log(L_INFO, "Error: %m !!! (cause %d)", cause);
469   file_del(fi);
470 }
471
472 static void dwrite(struct main_file *fi UNUSED)
473 {
474   log(L_INFO, "Write done");
475 }
476
477 static int dhook(struct main_hook *ho UNUSED)
478 {
479   log(L_INFO, "Hook called");
480   return 0;
481 }
482
483 static void dtimer(struct main_timer *tm)
484 {
485   log(L_INFO, "Timer tick");
486   timer_add(tm, main_now + 10000);
487 }
488
489 static void dentry(void)
490 {
491   log(L_INFO, "*** SUBPROCESS START ***");
492   sleep(2);
493   log(L_INFO, "*** SUBPROCESS FINISH ***");
494   exit(0);
495 }
496
497 static void dexit(struct main_process *pr)
498 {
499   log(L_INFO, "Subprocess %d exited with status %x", pr->pid, pr->status);
500 }
501
502 int
503 main(void)
504 {
505   log_init(NULL);
506   main_init();
507
508   fin.fd = 0;
509   fin.read_done = dread;
510   fin.error_handler = derror;
511   file_add(&fin);
512   file_read(&fin, rb, sizeof(rb));
513
514   fout.fd = 1;
515   fout.write_done = dwrite;
516   fout.error_handler = derror;
517   file_add(&fout);
518   file_write(&fout, "Hello, world!\n", 14);
519
520   hook.handler = dhook;
521   hook_add(&hook);
522
523   tm.handler = dtimer;
524   timer_add(&tm, main_now + 1000);
525
526   mp.handler = dexit;
527   if (!process_fork(&mp))
528     dentry();
529
530   main_debug();
531
532   main_loop();
533   log(L_INFO, "Finished.");
534 }
535
536 #endif