timers.txt 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. Kamailio :: timer interface
  2. =============================
  3. 1. Introduction
  4. ---------------
  5. Kamailio's timer interface is based on a 3 level hierarchical timing wheel
  6. (see [1]). Most timeouts will go in the first "wheel" (all timeouts < 1<<14
  7. ticks, which by default mean 1024 s). Each wheel acts as a circular buffer.
  8. The big advantage of this scheme is that most of the time you just run all the
  9. timer handlers from the current entry in the first wheel (no comparisons necessary).
  10. Each 2^14 ticks, all the timers in the second wheel's current entry are redistributed
  11. and each 2^23 ticks all the timers in the third wheel's current entry are redistributed.
  12. The timer interfaces allows adding timers dynamically, supports one shot
  13. and periodic timers, is precise and fast (very low overhead) and supports
  14. "fast" and "slow" timers. For now it uses setitimer to "generate" the ticks and from
  15. time to time it re-adjusts them based on the real system time.
  16. [1] - G. Varghese, T. Lauck, Hashed and Hierarchical Timing Wheels: Efficient
  17. Data Structures for Implementing a Timer Facility, 1996
  18. 2. include files
  19. -----------------
  20. All the public functions are defined in timer.h. timer_ticks.h contains
  21. ticks conversion related macros (ticks to seconds, ms or viceversa).
  22. 3. Example usage
  23. ----------------
  24. #include "../../timer.h"
  25. #include "../../timer_ticks.h"
  26. /* simple periodic timer handler */
  27. static ticks_t timer_h(ticks_t ticks, struct timer_ln* tl, void* data)
  28. {
  29. DBG("timer habdler called at %d ticks, foo is %d \n", ticks, *(int*)data);
  30. return (ticks_t)(-1); /* periodical */
  31. }
  32. struct timer_ln *t;
  33. int foo;
  34. t=timer_alloc();
  35. if (t==0)
  36. goto error;
  37. timer_init(t, timer_handle, &foo, 0);
  38. foo=0;
  39. timer_add(t, MS_TO_TICKS(1500)); /* start it after 1500ms */
  40. /* .... */
  41. /* remove it and change the period to 2 s */
  42. timer_del(t);
  43. timer_reinit(t); /* without init or reinit timer_add will refuse to re-add it*/
  44. timer_add(t, S_TO_TICKS(2));
  45. /* .... */
  46. /* remove it at the end (optional) */
  47. timer_del(t);
  48. timer_free(t);
  49. 4. Notes
  50. ---------
  51. 4.1 alloc & init
  52. ----------------
  53. To use a timer you need a timer_ln structure. This structure must be stored
  54. in shared memory.
  55. You can either use timer_alloc() which will return a pointer to a shared memory
  56. allocated timer_ln structure or you can "attach" timer_ln as a member to one
  57. of your structures which is already stored in the shared memory.
  58. The timer_ln structure must be always initialized. Use the timer_init(...) macro for this.
  59. To the timer_init macro takes as parameters a pointer to the timer_ln structure, a pointer to a timer_handler_f function, a void* parameter for this
  60. function and some timer flags.
  61. Example:
  62. struct foo{
  63. int bar;
  64. struct timer_ln timer;
  65. };
  66. struct foo* f;
  67. f=shm_malloc(sizeof(struct foo));
  68. time_init(&f->timer, timer_handle, &f->bar, 0);
  69. The timer flags can be either 0 (if it's a "slow" timer) or F_TIMER_FAST if
  70. this is a "fast" timer.
  71. A "fast" timer is a timer that does very little work in its timer handler (it always exits fast). You should use a "slow" timer if you don't care so much if your timer call is a little bit delayed or if you do dns lookups, query databases, blocking sends/writes. If you don't know which one to choose, choose "slow".
  72. 4.2 timer handlers
  73. ------------------
  74. The timer handler can be periodic, one shot or it can change from call to call. It all depends on what value you return from it. If you always return (ticks_t)(-1) or timer_ln->initial_timeout you have a periodic timer. If you return 0 you have an one shot timer (the timer will be removed when your timer handler function exits). For any other value v, your timer will be automatically re-added with the next expire set to v (expressed in ticks).
  75. 4.3 timer_add
  76. -------------
  77. The timer becomes active after you add it with timer_add. timer_add takes as parameters a pointer to the corresponding timer_ln structure and an expire interval (in ticks, use the macros from timer_ticks.h to convert from s/ms).
  78. The timer must be initialized (with timer_init()) before adding it the first time.
  79. timer_add returns 0 on success and -1 on error (timer already active or timer not initialized).
  80. If you want to re-add a deleted timer (timer_del was called on it) or an expired one shot timer (the timer handlers returned 0 on the last run), you have to re-init it first, either by calling timer_reinit(t) or by calling again timer_init(...). If you don't re-initialize the timer, timer_add will refuse to add it and it will return -1. So if timer_add returns error (-1) it means that either you're trying to re-add a running timer or a deleted/expired timer that was not re-initialized.
  81. WARNING: do not initialize/re-initialize a running timer!
  82. 4.4 timer_del
  83. -------------
  84. To remove a timer from the active timer list call timer_del(struct timer_ln*).
  85. timer_del is the slowest of all the timer functions. If you are trying to delete a timer whose timer is executing. timer_del will wait until it finishes.
  86. timer_del returns 0 on success and a negative number on error (for now -1 if an attempt to delete and already removed or expired timer is made and -2 if timer_del is called from the timer handle it is supposed to delete).
  87. WARNING: - avoid deleting your own timer from its timer handle (if you try it, you'll get a BUG message in the log). If you _must_ have this, you have a broken design. If you still want it, look at timer_allow_del().
  88. - if you have an one shot timer that frees its memory before exiting, make sure you don't call timer_del afterwards (e.g. use some reference counters and free the memory only if the counter is 0).
  89. Race example (using the struct foo defined above):
  90. /* simple one shot timer handler */
  91. static ticks_t timer_h(ticks_t ticks, struct timer_ln* tl, void* data)
  92. {
  93. /* free the mem. */
  94. shm_free(data);
  95. return 0;
  96. }
  97. struct foo* f;
  98. f=shm_malloc(sizeof(struct foo));
  99. time_init(&f->timer, timer_handle, f, 0);
  100. timer_add(&f->timer, rand());
  101. /* ... */
  102. /* random amount of time spent doing other things */
  103. timer_del(&f->timer); /* if the timer is already expired => f is already
  104. deleted => problems */
  105. The above timer_del/free_in_one_shot_timer race example is very simple, but
  106. consider that you can have much more complex scenarios, when timer_del can be
  107. called from different processes on some asynchronous events. If this looks like your
  108. intended usage, make sure you use some reference counters or some other
  109. protection mechanism to avoid the above race.
  110. 4.5 timer_allow_del
  111. -------------------
  112. Marks a timer as "to be deleted when the handler ends", usefull when the timer handler
  113. knows it won't prolong the timer anymore (it will return 0) and will do some time
  114. consuming work. Calling this function will cause simultaneous timer_dels to return
  115. immediately (they won't wait anymore for the timer handle to finish).
  116. It will also allow self-deleting from the timer handle without logging a bug.
  117. WARNING: - if you rely on timer_del to know when the timer handle execution
  118. finishes (e.g. to free resources used in the timer handle), don't use this function.
  119. - call this function only if this is your last timer handle run
  120. (the timer handle will return 0)
  121. - this function can be called only from a timer handle (in timer context),
  122. all other calls will have no effect and will log a bug message
  123. 4.6 Getting the ticks value
  124. ----------------------------
  125. If you need the current ticks value you can get with get_ticks_raw().
  126. WARNING: don't use get_ticks(). get_ticks() returns the number of ticks converted to seconds and it was kept only for compatibility reasons with the existing code.
  127. 4.7 Conversion
  128. ---------------
  129. To convert between ticks & time and viceversa, include timer_ticks.h and use
  130. one of the following macros:
  131. MS_TO_TICKS(ms) /* converts from milliseconds to ticks, rounds up */
  132. S_TO_TICKS(s) /* convert from seconds to ticks */
  133. TICKS_TO_MS(t) /* converts from ticks to milliseconds, can overflow for
  134. very large values (use long long and
  135. TICKS_TO_MS((long long)t) to try to avoid it if you know
  136. that you'll deal with such large values */
  137. TICKS_TO_S(t) /* converts from ticks to s, rounded down */
  138. 4.8 Ticks value comparison
  139. ---------------------------
  140. The ticks value can (and will) overflow so ticks values should never be compared directly
  141. (e.g. ticks1<ticks2). To compare them include timer_ticks.h and use
  142. one of the macros:
  143. TICKS_LT(t1, t2) /* t1 < t2 */
  144. TICKS_GT(t1, t2) /* t1 > t2 */
  145. TICKS_LE(t1, t2) /* t1 <= t2 */
  146. TICKS_GE(t1, t2) /* t1 >= t2 */
  147. These macros work as long as the difference between t1 and t2 is less than 2^(sizeof(ticks_t)*8-1).
  148. For the default TIMER_TICKS_HZ values, this means 4.25 years.
  149. 4.9 Backward compatibility
  150. --------------------------
  151. The old register_timer and get_ticks() are still supported for backward compatibility.
  152. This means that you don't have to change your existing working code.
  153. 5.0 Debugging
  154. -------------
  155. The timers have built-in debugging information. To activate it you only need to
  156. define TIMER_DEBUG (recompile Kamailio with make CC_EXTRA_OPTS=-DTIMER_DEBUG all).
  157. The timer debug log level is by default L_WARN. [ FIXME: add it as script option]
  158. TIMER_DEBUG enables extra sanity checks and it will log a lot of information
  159. (like the caller of timer_* functions, where a timer was added a.s.o).
  160. [Todo]:
  161. - SLOW, DRIFT, RESYNC, FREQUENCY