4 * This module tracks any timers set up by schedule_timer(). It
5 * keeps all the currently active timers in a list; it informs the
6 * front end of when the next timer is due to go off if that
7 * changes; and, very importantly, it tracks the context pointers
8 * passed to schedule_timer(), so that if a context is freed all
9 * the timers associated with it can be immediately annulled.
24 static tree234
*timers
= NULL
;
25 static tree234
*timer_contexts
= NULL
;
28 static int compare_timers(void *av
, void *bv
)
30 struct timer
*a
= (struct timer
*)av
;
31 struct timer
*b
= (struct timer
*)bv
;
32 long at
= a
->now
- now
;
33 long bt
= b
->now
- now
;
41 * Failing that, compare on the other two fields, just so that
42 * we don't get unwanted equality.
45 /* lcc won't let us compare function pointers. Legal, but annoying. */
47 int c
= memcmp(&a
->fn
, &b
->fn
, sizeof(a
->fn
));
56 else if (a
->fn
> b
->fn
)
62 else if (a
->ctx
> b
->ctx
)
66 * Failing _that_, the two entries genuinely are equal, and we
67 * never have a need to store them separately in the tree.
72 static int compare_timer_contexts(void *av
, void *bv
)
83 static void init_timers(void)
86 timers
= newtree234(compare_timers
);
87 timer_contexts
= newtree234(compare_timer_contexts
);
92 long schedule_timer(int ticks
, timer_fn_t fn
, void *ctx
)
95 struct timer
*t
, *first
;
99 when
= ticks
+ GETTICKCOUNT();
100 assert(when
- now
> 0);
102 t
= snew(struct timer
);
107 if (t
!= add234(timers
, t
)) {
108 sfree(t
); /* identical timer already exists */
110 add234(timer_contexts
, t
->ctx
);/* don't care if this fails */
113 first
= (struct timer
*)index234(timers
, 0);
116 * This timer is the very first on the list, so we must
117 * notify the front end.
119 timer_change_notify(first
->now
);
126 * Call to run any timers whose time has reached the present.
127 * Returns the time (in ticks) expected until the next timer after
130 int run_timers(long anow
, long *next
)
139 first
= (struct timer
*)index234(timers
, 0);
142 return FALSE
; /* no timers remaining */
144 if (find234(timer_contexts
, first
->ctx
, NULL
) == NULL
) {
146 * This timer belongs to a context that has been
147 * expired. Delete it without running.
149 delpos234(timers
, 0);
151 } else if (first
->now
- now
<= 0) {
153 * This timer is active and has reached its running
156 delpos234(timers
, 0);
157 first
->fn(first
->ctx
, first
->now
);
161 * This is the first still-active timer that is in the
162 * future. Return how long it has yet to go.
171 * Call to expire all timers associated with a given context.
173 void expire_timer_context(void *ctx
)
178 * We don't bother to check the return value; if the context
179 * already wasn't in the tree (presumably because no timers
180 * ever actually got scheduled for it) then that's fine and we
181 * simply don't need to do anything.
183 del234(timer_contexts
, ctx
);