2 * UCW Library -- Main Loop
4 * (c) 2004--2012 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.
10 #ifndef _UCW_MAINLOOP_H
11 #define _UCW_MAINLOOP_H
13 #include "ucw/clists.h"
14 #include "ucw/process.h"
23 * First of all, let us take a look at the basic operations with main loop contexts.
26 /** The main loop context **/
28 timestamp_t now; /* [*] Current time in milliseconds since the UNIX epoch. See main_get_time(). */
29 ucw_time_t now_seconds; /* [*] Current time in seconds since the epoch. */
30 timestamp_t idle_time; /* [*] Total time in milliseconds spent by waiting for events. */
31 uns shutdown; /* [*] Setting this to nonzero forces the main_loop() function to terminate. */
33 clist file_active_list;
40 #ifdef CONFIG_UCW_EPOLL
41 int epoll_fd; /* File descriptor used for epoll */
42 struct epoll_event *epoll_events;
43 clist file_recalc_list;
45 uns poll_table_obsolete;
46 struct pollfd *poll_table;
47 struct main_file **poll_file_table;
49 struct main_timer **timer_table; /* Growing array containing the heap of timers */
50 sigset_t want_signals;
53 struct main_file *sig_pipe_file;
54 struct main_signal *sigchld_handler;
57 struct main_context *main_new(void); /** Create a new context. **/
60 * Delete a context, assuming it does have any event handlers attached. Does nothing if @m is NULL.
61 * It is allowed to call @main_delete() from a hook function of the same context, but you must
62 * never return to the main loop -- e.g., you can exit() the process instead.
64 void main_delete(struct main_context *m);
67 * Delete a context. If there are any event handlers attached, they are deactivated
68 * (but the responsibility to free the memory there were allocated from lies upon you).
69 * If there are any file handlers, the corresponding file descriptors are closed.
71 void main_destroy(struct main_context *m);
73 /** Switch the current context of the calling thread. Returns the previous current context. **/
74 struct main_context *main_switch_context(struct main_context *m);
76 /** Return the current context. Dies if there is none or if the context has been deleted. **/
77 struct main_context *main_current(void);
79 /** Initialize the main loop module and create a top-level context. **/
82 /** Deinitialize the main loop module, calling @main_delete() on the top-level context. **/
83 void main_cleanup(void);
86 * Deinitialize the main loop module, calling @main_destroy() on the top-level context.
87 * This is especially useful in a freshly forked-off child process.
89 void main_teardown(void);
92 * Start the event loop on the current context.
93 * It will watch the provided objects and call callbacks.
94 * Terminates when someone calls @main_shut_down(),
95 * or when all <<hook,hooks>> return <<enum_main_hook_return,`HOOK_DONE`>>
96 * or at last one <<hook,hook>> returns <<enum_main_hook_return,`HOOK_SHUTDOWN`>>.
101 * Perform a single iteration of the main loop.
102 * Check if there are any events ready and process them.
103 * If there are none, do not wait.
105 void main_step(void);
107 /** Ask the main loop to terminate at the nearest occasion. **/
108 static inline void main_shut_down(void)
110 main_current()->shutdown = 1;
114 * Show the current state of a given context (use @main_debug() for the current context).
115 * Available only if LibUCW has been compiled with `CONFIG_DEBUG`.
117 void main_debug_context(struct main_context *m);
122 main_debug_context(main_current());
130 * The event loop provides the current time, measured as a 64-bit number
131 * of milliseconds since the system epoch (represented in the type `timestamp_t`).
133 * You can also register timers, which call a handler function at a given moment.
134 * The handler function must either call @timer_del() to delete the timer, or call
135 * @timer_add() with a different expiration time.
139 * Get the current timestamp cached in the current context. It is refreshed in every
140 * iteration of the event loop, or explicitly by calling @main_get_time().
142 static inline timestamp_t main_get_now(void)
144 return main_current()->now;
147 /** An analog of @main_get_now() returning the number of seconds since the system epoch. **/
148 static inline ucw_time_t main_get_now_seconds(void)
150 return main_current()->now_seconds;
154 * This is a description of a timer.
155 * You define the handler function and possibly user-defined data you wish
156 * to pass to the handler, and then you invoke @timer_add().
162 void (*handler)(struct main_timer *tm); /* [*] Function to be called when the timer expires. */
163 void *data; /* [*] Data for use by the handler */
167 * Add a new timer into the main loop to be watched and called
168 * when it expires. It can also be used to modify an already running
169 * timer. It is permitted (and usual) to call this function from the
170 * timer's handler itself if you want the timer to trigger again.
172 * The @expire parameter is absolute, use @timer_add_rel() for a relative version.
174 void timer_add(struct main_timer *tm, timestamp_t expires);
176 /** Like @timer_add(), but the expiration time is relative to the current time. **/
177 void timer_add_rel(struct main_timer *tm, timestamp_t expires_delta);
180 * Removes a timer from the active ones. It is permitted (and common) to call
181 * this function from the timer's handler itself if you want to deactivate
182 * the timer. Removing an already removed timer does nothing.
184 void timer_del(struct main_timer *tm);
186 /** Tells whether a timer is running. **/
187 static inline int timer_is_active(struct main_timer *tm)
189 return !!tm->expires;
193 * Forces refresh of the current timestamp cached in the active context.
194 * You usually do not need to call this, since it is called every time the
195 * loop polls for events. It is here if you need extra precision or some of the
196 * hooks takes a long time.
198 void main_get_time(void);
200 /** Show current state of a timer. Available only if LibUCW has been compiled with `CONFIG_DEBUG`. **/
201 void timer_debug(struct main_timer *tm);
208 * The hooks are called whenever the main loop performs an iteration.
209 * You can shutdown the main loop from within them or request an iteration
210 * to happen without sleeping (just poll, no waiting for events).
214 * A hook. It contains the function to call and some user data.
216 * The handler() must return one value from
217 * <<enum_main_hook_return,`main_hook_return`>>.
219 * Fill with the hook and data and pass it to @hook_add().
223 int (*handler)(struct main_hook *ho); /* [*] Hook function; returns HOOK_xxx */
224 void *data; /* [*] For use by the handler */
228 * Return value of the hook handler().
229 * Specifies what should happen next.
231 * - `HOOK_IDLE` -- Let the loop sleep until something happens, call after that.
232 * - `HOOK_RETRY` -- Force the loop to perform another iteration without sleeping.
233 * This will cause calling of all the hooks again soon.
234 * - `HOOK_DONE` -- The loop will terminate if all hooks return this.
235 * - `HOOK_SHUTDOWN` -- Shuts down the loop.
237 * The `HOOK_IDLE` and `HOOK_RETRY` constants are also used as return values
240 enum main_hook_return {
248 * Inserts a new hook into the loop.
249 * The hook will be scheduled at least once before next sleep.
250 * May be called from inside a hook handler too.
251 * Adding an already added hook is permitted and if the hook has been run,
252 * it will be run again before next sleep.
254 void hook_add(struct main_hook *ho);
257 * Removes an existing hook from the loop.
258 * May be called from inside a hook handler (to delete itself or another hook).
259 * Removing an already removed hook does nothing.
261 void hook_del(struct main_hook *ho);
263 /** Tells if a hook is active (i.e., added). **/
264 static inline int hook_is_active(struct main_hook *ho)
266 return clist_is_linked(&ho->n);
269 /** Show current state of a hook. Available only if LibUCW has been compiled with `CONFIG_DEBUG`. **/
270 void hook_debug(struct main_hook *ho);
275 * Activity on file descriptors
276 * ----------------------------
278 * You can ask the main loop to watch a set of file descriptors for activity.
279 * (This is a generalization of the select() and poll() system calls. Internally,
280 * it uses either poll() or the more efficient epoll().)
282 * You create a <<struct_main_file,`struct main_file`>>, fill in a file descriptor
283 * and pointers to handler functions to be called when the descriptor becomes
284 * ready for reading and/or writing, and call @file_add(). When you need to
285 * modify the handlers (e.g., to set them to NULL if you are no longer interested
286 * in a given event), you should call @file_chg() to notify the main loop about
289 * From within the handler functions, you are allowed to call @file_chg() and even
292 * The return value of a handler function should be either <<enum_main_hook_return,`HOOK_RETRY`>>
293 * or <<enum_main_hook_return,`HOOK_IDLE`>>. <<enum_main_hook_return,`HOOK_RETRY`>>
294 * signals that the function would like to consume more data immediately
295 * (i.e., it wants to be called again soon, but the event loop can postpone it after
296 * processing other events to avoid starvation). <<enum_main_hook_return,`HOOK_IDLE`>>
297 * tells that the handler wants to be called when the descriptor becomes ready again.
299 * For backward compatibility, 0 can be used instead of <<enum_main_hook_return,`HOOK_IDLE`>>
300 * and 1 for <<enum_main_hook_return,`HOOK_RETRY`>>.
302 * If you want to read/write fixed-size blocks of data asynchronously, the
303 * <<blockio,Asynchronous block I/O>> interface could be more convenient.
307 * This structure describes a file descriptor to be watched and the handlers
308 * to be called when the descriptor is ready for reading and/or writing.
312 int fd; /* [*] File descriptor */
313 int (*read_handler)(struct main_file *fi); /* [*] To be called when ready for reading/writing; must call file_chg() afterwards */
314 int (*write_handler)(struct main_file *fi);
315 void *data; /* [*] Data for use by the handlers */
317 #ifdef CONFIG_UCW_EPOLL
318 uns last_want_events;
320 struct pollfd *pollfd;
325 * Insert a <<struct_main_file,`main_file`>> structure into the main loop to be
326 * watched for activity. You can call this at any time, even inside a handler
327 * (of course for a different file descriptor than the one of the handler).
329 * The file descriptor is automatically set to the non-blocking mode.
331 void file_add(struct main_file *fi);
334 * Tell the main loop that the file structure has changed. Call it whenever you
335 * change any of the handlers.
337 * Can be called only on active files (only the ones added by @file_add()).
339 void file_chg(struct main_file *fi);
342 * Removes a file from the watched set. If you want to close a descriptor,
343 * please use this function first.
345 * Can be called from a handler.
346 * Removing an already removed file does nothing.
348 void file_del(struct main_file *fi);
350 /** Tells if a file is active (i.e., added). **/
351 static inline int file_is_active(struct main_file *fi)
353 return clist_is_linked(&fi->n);
356 /** Show current state of a file. Available only if LibUCW has been compiled with `CONFIG_DEBUG`. **/
357 void file_debug(struct main_file *fi);
361 * Asynchronous block I/O
362 * ----------------------
364 * If you are reading or writing fixed-size blocks of data, you can let the
365 * block I/O interface handle the boring routine of handling partial reads
366 * and writes for you.
368 * You just create <<struct_main_block_io,`struct main_block_io`>> and call
369 * @block_io_add() on it, which sets up some <<struct_main_file,`main_file`>>s internally.
370 * Then you can just call @block_io_read() or @block_io_write() to ask for
371 * reading or writing of a given block. When the operation is finished,
372 * your handler function is called.
374 * Additionally, the block I/O is equipped with a timer, which can be used
375 * to detect communication timeouts. The timer is not touched internally
376 * (except that it gets added and deleted at the right places), feel free
377 * to adjust it from your handler functions by @block_io_set_timeout().
378 * When the timer expires, the error handler is automatically called with
379 * <<enum_block_io_err_cause,`BIO_ERR_TIMEOUT`>>.
382 /** The block I/O structure. **/
383 struct main_block_io {
384 struct main_file file;
385 byte *rbuf; /* Read/write pointers for use by file_read/write */
389 void (*read_done)(struct main_block_io *bio); /* [*] Called when file_read is finished; rpos < rlen if EOF */
390 void (*write_done)(struct main_block_io *bio); /* [*] Called when file_write is finished */
391 void (*error_handler)(struct main_block_io *bio, int cause); /* [*] Handler to call on errors */
392 struct main_timer timer;
393 void *data; /* [*] Data for use by the handlers */
396 /** Activate a block I/O structure. **/
397 void block_io_add(struct main_block_io *bio, int fd);
399 /** Deactivate a block I/O structure. Calling twice is safe. **/
400 void block_io_del(struct main_block_io *bio);
403 * Specifies when or why an error happened. This is passed to the error handler.
404 * `errno` is still set to the original source of error. The only exception
405 * is `BIO_ERR_TIMEOUT`, in which case `errno` is not set and the only possible
406 * cause of it is timeout of the timer associated with the block_io
407 * (see @block_io_set_timeout()).
409 enum block_io_err_cause {
416 * Ask the main loop to read @len bytes of data from @bio into @buf.
417 * It cancels any previous unfinished read requested in this way.
419 * When the read is done, the read_done() handler is called. If an EOF occurred,
420 * `rpos < rlen` (eg. not all data were read).
422 * Can be called from a handler.
424 * You can use a call with zero @len to cancel the current read, but all read data
425 * will be thrown away.
427 void block_io_read(struct main_block_io *bio, void *buf, uns len);
430 * Request that the main loop writes @len bytes of data from @buf to @bio.
431 * Cancels any previous unfinished write and overwrites `write_handler`.
433 * When it is written, the write_done() handler is called.
435 * Can be called from a handler.
437 * If you call it with zero @len, it will cancel the previous write, but note
438 * that some data may already be written.
440 void block_io_write(struct main_block_io *bio, void *buf, uns len);
443 * Sets a timer for a file @bio. If the timer is not overwritten or disabled
444 * until @expires_delta milliseconds, the file timeouts and error_handler() is called with
445 * <<enum_block_io_err_cause,`BIO_ERR_TIMEOUT`>>. A value of `0` stops the timer.
447 * Previous setting of the timeout on the same file will be overwritten.
449 * The use-cases for this are mainly sockets or pipes, when:
451 * - You want to drop inactive connections (no data comes in or out for a given time, not
452 * incomplete messages).
453 * - You want to enforce answer in a given time (for example authentication).
454 * - Watching maximum time for a whole connection.
456 void block_io_set_timeout(struct main_block_io *bio, timestamp_t expires_delta);
458 /** Tells if a @bio is active (i.e., added). **/
459 static inline int block_io_is_active(struct main_block_io *bio)
461 return file_is_active(&bio->file);
466 * Asynchronous record I/O
467 * -----------------------
469 * Record-based I/O is another front-end to the main loop file operations.
470 * Unlike its older cousin `main_block_io`, it is able to process records
471 * of variable length.
473 * To set it up, you create <<struct_main_rec_io,`struct main_rec_io`>> and call
474 * @rec_io_add() on it, which sets up some <<struct_main_file,`main_file`>>s internally.
476 * To read data from the file, call @rec_io_start_read() first. Whenever any data
477 * arrive from the file, they are appended to an internal buffer and the `read_handler`
478 * hook is called. The hook checks if the buffer already contains a complete record.
479 * If it is so, it processes the record and returns the number of bytes consumed.
480 * Otherwise, it returns 0 to tell the buffering machinery that more data are needed.
481 * When the read handler decides to destroy the `main_rec_io`, it must return `~0U`.
483 * On the write side, `main_rec_io` maintains a buffer keeping all data that should
484 * be written to the file. The @rec_io_write() function appends data to this buffer
485 * and it is written on background. A simple flow-control mechanism can be asked
486 * for: when more than `write_throttle_read` data are buffered for writing, reading
487 * is temporarily suspended.
489 * Additionally, the record I/O is equipped with a timer, which can be used
490 * to detect communication timeouts. The timer is not touched internally
491 * (except that it gets added and deleted at the right places), feel free
492 * to adjust it from your handler functions by @rec_io_set_timeout().
494 * All important events are passed to the `notify_handler`: errors when
495 * reading or writing, timeouts, the write buffer becoming empty, ... See
496 * <<enum_rec_io_notify_status,`enum rec_io_notify_status`>> for a complete list.
499 /** The record I/O structure. **/
501 struct main_file file;
503 byte *read_rec_start; /* [*] Start of current record */
504 uns read_avail; /* [*] How much data is available */
505 uns read_prev_avail; /* [*] How much data was available in previous read_handler */
506 uns read_buf_size; /* [*] Read buffer size allocated (can be set before rec_io_add()) */
507 uns read_started; /* Reading requested by user */
508 uns read_running; /* Reading really runs (read_started && not stopped by write_throttle_read) */
509 uns read_rec_max; /* [*] Maximum record size (0=unlimited) */
510 clist busy_write_buffers;
511 clist idle_write_buffers;
512 uns write_buf_size; /* [*] Write buffer size allocated (can be set before rec_io_add()) */
513 uns write_watermark; /* [*] How much data are waiting to be written */
514 uns write_throttle_read; /* [*] If more than write_throttle_read bytes are buffered, stop reading; 0=no stopping */
515 uns (*read_handler)(struct main_rec_io *rio); /* [*] Called whenever more bytes are read; returns 0 (want more) or number of bytes eaten */
516 int (*notify_handler)(struct main_rec_io *rio, int status); /* [*] Called to notify about errors and other events */
517 /* Returns either HOOK_RETRY or HOOK_IDLE. */
518 struct main_timer timer;
519 struct main_hook start_read_hook; /* Used internally to defer rec_io_start_read() */
520 void *data; /* [*] Data for use by the handlers */
523 /** Activate a record I/O structure. **/
524 void rec_io_add(struct main_rec_io *rio, int fd);
526 /** Deactivate a record I/O structure. Calling twice is safe. **/
527 void rec_io_del(struct main_rec_io *rio);
532 * When there were some data in the buffer (e.g., because @rec_io_stop_read()
533 * was called from the `read_handler`), it is processed as if it were read
534 * from the file once again. That is, `read_prev_avail` is reset to 0 and
535 * the `read_handler` is called to process all buffered data.
537 void rec_io_start_read(struct main_rec_io *rio);
539 /** Stop reading. **/
540 void rec_io_stop_read(struct main_rec_io *rio);
542 /** Analogous to @block_io_set_timeout(). **/
543 void rec_io_set_timeout(struct main_rec_io *bio, timestamp_t expires_delta);
545 void rec_io_write(struct main_rec_io *rio, void *data, uns len);
548 * An auxiliary function used for parsing of lines. When called in the @read_handler,
549 * it searches for the end of line character. When a complete line is found, the length
550 * of the line (including the end of line character) is returned. Otherwise, it returns zero.
552 uns rec_io_parse_line(struct main_rec_io *rio);
555 * Specifies what kind of error or other event happened, when the @notify_handler
556 * is called. In case of I/O errors, `errno` is still set.
558 * Upon @RIO_ERR_READ, @RIO_ERR_RECORD_TOO_LARGE and @RIO_EVENT_EOF, reading is stopped
559 * automatically. Upon @RIO_ERR_WRITE, writing is stopped. Upon @RIO_ERR_TIMEOUT, only the
560 * timer is deactivated.
562 * In all cases, the notification handler is allowed to call @rec_io_del(), but it
563 * must return @HOOK_IDLE in such cases.
565 enum rec_io_notify_status {
566 RIO_ERR_READ = -1, /* read() returned an error, errno set */
567 RIO_ERR_WRITE = -2, /* write() returned an error, errno set */
568 RIO_ERR_TIMEOUT = -3, /* A timeout has occurred */
569 RIO_ERR_RECORD_TOO_LARGE = -4, /* Read: read_rec_max has been exceeded */
570 RIO_EVENT_ALL_WRITTEN = 1, /* All buffered data has been written */
571 RIO_EVENT_PART_WRITTEN = 2, /* Some buffered data has been written, but more remains */
572 RIO_EVENT_EOF = 3, /* Read: EOF seen */
575 /** Tells if a @rio is active (i.e., added). **/
576 static inline int rec_io_is_active(struct main_rec_io *rio)
578 return file_is_active(&rio->file);
586 * The main loop can watch child processes and notify you,
587 * when some of them terminates.
591 * Description of a watched process.
592 * You fill in the handler() and `data`.
593 * The rest is set with @process_fork().
595 struct main_process {
597 int pid; /* Process id (0=not running) */
598 int status; /* Exit status (-1=fork failed) */
599 char status_msg[EXIT_STATUS_MSG_SIZE];
600 void (*handler)(struct main_process *mp); /* [*] Called when the process exits; process_del done automatically */
601 void *data; /* [*] For use by the handler */
605 * Asks the main loop to watch this process.
606 * As it is done automatically in @process_fork(), you need this only
607 * if you removed the process previously by @process_del().
609 void process_add(struct main_process *mp);
612 * Removes the process from the watched set. This is done
613 * automatically, when the process terminates, so you need it only
614 * when you do not want to watch a running process any more.
615 * Removing an already removed process does nothing.
617 void process_del(struct main_process *mp);
620 * Forks and fills the @mp with information about the new process.
622 * If the fork() succeeds, it:
624 * - Returns 0 in the child.
625 * - Returns 1 in the parent and calls @process_add() on it.
627 * In the case of unsuccessful fork(), it:
629 * - Fills in the `status_msg` and sets `status` to -1.
630 * - Calls the handler() as if the process terminated.
633 int process_fork(struct main_process *mp);
635 /** Tells if a process is active (i.e., added). **/
636 static inline int process_is_active(struct main_process *mp)
638 return clist_is_linked(&mp->n);
641 /** Show current state of a process. Available only if LibUCW has been compiled with `CONFIG_DEBUG`. **/
642 void process_debug(struct main_process *pr);
646 * Synchronous delivery of signals
647 * -------------------------------
649 * UNIX signals are delivered to processes in an asynchronous way: when a signal
650 * arrives (and it is not blocked), the process is interrupted and the corresponding
651 * signal handler function is called. However, most data structures and even most
652 * system library calls are not safe with respect to interrupts, so most program
653 * using signals contain subtle race conditions and may fail once in a long while.
655 * To avoid this problem, the event loop can be asked for synchronous delivery
656 * of signals. When a signal registered with @signal_add() arrives, it wakes up
657 * the loop (if it is not already awake) and it is processed in the same way
658 * as all other events.
660 * When used in a multi-threaded program, the signals are delivered to the thread
661 * which is currently using the particular main loop context. If the context is not
662 * current in any thread, the signals are blocked.
664 * As usually with UNIX signals, multiple instances of a single signal can be
665 * merged and delivered only once. (Some implementations of the main loop can even
666 * drop a signal completely during very intensive signal traffic, when an internal
667 * signal queue overflows.)
670 /** Description of a signal to catch. **/
673 int signum; /* [*] Signal to catch */
674 void (*handler)(struct main_signal *ms); /* [*] Called when the signal arrives */
675 void *data; /* [*] For use by the handler */
678 /** Request a signal to be caught and delivered synchronously. **/
679 void signal_add(struct main_signal *ms);
681 /** Cancel a request for signal catching. Calling twice is safe. **/
682 void signal_del(struct main_signal *ms);
684 /** Tells if a signal catcher is active (i.e., added). **/
685 static inline int signal_is_active(struct main_signal *ms)
687 return clist_is_linked(&ms->n);
690 /** Show current state of a signal catcher. Available only if LibUCW has been compiled with `CONFIG_DEBUG`. **/
691 void signal_debug(struct main_signal *sg);