991ec643926f330a897ba383265343f1ae280e65
[ccan] / ccan / timer / timer.c
1 /* LGPL (v2.1 or any later version) - see LICENSE file for details */
2 #include <ccan/timer/timer.h>
3 #include <ccan/array_size/array_size.h>
4 #include <ccan/ilog/ilog.h>
5 #include <ccan/likely/likely.h>
6 #include <stdlib.h>
7 #include <stdio.h>
8
9 #define PER_LEVEL (1ULL << TIMER_LEVEL_BITS)
10
11 struct timer_level {
12         struct list_head list[PER_LEVEL];
13 };
14
15 static uint64_t time_to_grains(struct timespec ts)
16 {
17         return ts.tv_sec * ((uint64_t)1000000000 / TIMER_GRANULARITY)
18                 + (ts.tv_nsec / TIMER_GRANULARITY);
19 }
20
21 static struct timespec grains_to_time(uint64_t grains)
22 {
23         struct timespec ts;
24
25         ts.tv_sec = grains / (1000000000 / TIMER_GRANULARITY);
26         ts.tv_nsec = (grains % (1000000000 / TIMER_GRANULARITY))
27                 * TIMER_GRANULARITY;
28         return ts;
29 }
30
31 void timers_init(struct timers *timers, struct timespec start)
32 {
33         unsigned int i;
34
35         list_head_init(&timers->far);
36         timers->base = time_to_grains(start);
37         timers->first = -1ULL;
38         for (i = 0; i < ARRAY_SIZE(timers->level); i++)
39                 timers->level[i] = NULL;
40 }
41
42 static unsigned int level_of(const struct timers *timers, uint64_t time)
43 {
44         uint64_t diff;
45
46         /* Level depends how far away it is. */
47         diff = time - timers->base;
48         return ilog64(diff / 2) / TIMER_LEVEL_BITS;
49 }
50
51 static void timer_add_raw(struct timers *timers, struct timer *t)
52 {
53         struct list_head *l;
54         unsigned int level = level_of(timers, t->time);
55
56         if (!timers->level[level])
57                 l = &timers->far;
58         else {
59                 int off = (t->time >> (level*TIMER_LEVEL_BITS)) & (PER_LEVEL-1);
60                 l = &timers->level[level]->list[off];
61         }
62
63         list_add_tail(l, &t->list);
64 }
65
66 void timer_add(struct timers *timers, struct timer *t, struct timespec when)
67 {
68         t->time = time_to_grains(when);
69
70         /* Added in the past?  Treat it as imminent. */
71         if (t->time < timers->base)
72                 t->time = timers->base;
73         if (t->time < timers->first)
74                 timers->first = t->time;
75
76         timer_add_raw(timers, t);
77 }
78
79 /* FIXME: inline */
80 void timer_del(struct timers *timers, struct timer *t)
81 {
82         list_del(&t->list);
83 }
84
85 static void timers_far_get(struct timers *timers,
86                            struct list_head *list,
87                            uint64_t when)
88 {
89         struct timer *i, *next;
90
91         list_for_each_safe(&timers->far, i, next, list) {
92                 if (i->time <= when) {
93                         list_del_from(&timers->far, &i->list);
94                         list_add_tail(list, &i->list);
95                 }
96         }
97 }
98
99 static void add_level(struct timers *timers, unsigned int level)
100 {
101         struct timer_level *l;
102         struct timer *t;
103         unsigned int i;
104         struct list_head from_far;
105
106         l = malloc(sizeof(*l));
107         if (!l)
108                 return;
109
110         for (i = 0; i < ARRAY_SIZE(l->list); i++)
111                 list_head_init(&l->list[i]);
112         timers->level[level] = l;
113
114         list_head_init(&from_far);
115         timers_far_get(timers, &from_far,
116                        timers->base + (1ULL << ((level+1)*TIMER_LEVEL_BITS)) - 1);
117
118         while ((t = list_pop(&from_far, struct timer, list)) != NULL)
119                 timer_add_raw(timers, t);
120 }
121
122 static const struct timer *find_first(const struct list_head *list,
123                                       const struct timer *prev)
124 {
125         struct timer *t;
126
127         list_for_each(list, t, list) {
128                 if (!prev || t->time < prev->time)
129                         prev = t;
130         }
131         return prev;
132 }
133
134 static const struct timer *get_first(const struct timers *timers)
135 {
136         unsigned int level, i, off;
137         bool need_next;
138         uint64_t base;
139         const struct timer *found = NULL;
140         struct list_head *h;
141
142         if (timers->first < timers->base) {
143                 base = timers->base;
144                 level = 0;
145         } else {
146                 /* May not be accurate, due to timer_del / expiry. */
147                 level = level_of(timers, timers->first);
148                 base = timers->first >> (TIMER_LEVEL_BITS * level);
149         }
150
151 next:
152         if (!timers->level[level])
153                 return find_first(&timers->far, NULL);
154
155         need_next = false;
156         off = base % PER_LEVEL;
157         for (i = 0; i < PER_LEVEL; i++) {
158                 h = &timers->level[level]->list[(i+off) % PER_LEVEL];
159
160                 if (!list_empty(h))
161                         break;
162
163                 /* We haven't cascaded yet, so if we wrap, we'll need to
164                  * check next level, too. */
165                 if (i + off == PER_LEVEL)
166                         need_next = true;
167         }
168         if (i == PER_LEVEL) {
169                 level++;
170                 base >>= TIMER_LEVEL_BITS;
171                 goto next;
172         }
173
174         /* Level 0 is exact, so they're all the same. */
175         if (level == 0)
176                 found = list_top(h, struct timer, list);
177         else
178                 found = find_first(h, NULL);
179
180         if (need_next) {
181                 if (!timers->level[level+1]) {
182                         found = find_first(&timers->far, found);
183                 } else {
184                         base >>= TIMER_LEVEL_BITS;
185                         off = base % PER_LEVEL;
186                         h = &timers->level[level+1]->list[off];
187                         found = find_first(h, found);
188                 }
189         }
190         return found;
191 }
192
193 static bool update_first(struct timers *timers)
194 {
195         const struct timer *found = get_first(timers);
196
197         if (!found) {
198                 timers->first = -1ULL;
199                 return false;
200         }
201
202         timers->first = found->time;
203         return true;
204 }
205
206 bool timer_earliest(struct timers *timers, struct timespec *first)
207 {
208         if (!update_first(timers))
209                 return false;
210
211         *first = grains_to_time(timers->first);
212         return true;
213 }
214
215 /* Assume no timers before 'time', cascade down and update base time. */
216 static void timer_fast_forward(struct timers *timers, uint64_t time)
217 {
218         unsigned int level, changed;
219         int need_level = -1;
220         struct list_head list;
221         struct timer *i;
222
223         /* How many bits changed between base and time?
224          * Each time we wrap, we need to empty buckets from above. */
225         if (time == timers->base)
226                 return;
227
228         changed = ilog64_nz(time ^ timers->base);
229         level = (changed - 1) / TIMER_LEVEL_BITS;
230
231         /* Buckets always empty downwards, so we could cascade manually,
232          * but it's rarely very many so we just remove and re-add */
233         list_head_init(&list);
234
235         do {
236                 if (!timers->level[level]) {
237                         /* We need any which belong on this level. */
238                         timers_far_get(timers, &list,
239                                        timers->base
240                                        + (1ULL << ((level+1)*TIMER_LEVEL_BITS))-1);
241                         need_level = level;
242                 } else {
243                         unsigned src;
244
245                         /* Get all timers from this bucket. */
246                         src = (time >> (level * TIMER_LEVEL_BITS)) % PER_LEVEL;
247                         list_append_list(&list,
248                                          &timers->level[level]->list[src]);
249                 }
250         } while (level--);
251
252         /* Did we hit the last level?  If so, add. */
253         if (need_level != -1)
254                 add_level(timers, need_level);
255
256         /* Fast-forward the time, and re-add everyone. */
257         timers->base = time;
258         while ((i = list_pop(&list, struct timer, list)) != NULL)
259                 timer_add_raw(timers, i);
260 }
261
262 /* Fills list of expired timers. */
263 void timers_expire(struct timers *timers,
264                    struct timespec expire,
265                    struct list_head *list)
266 {
267         uint64_t now = time_to_grains(expire);
268         unsigned int off;
269
270         assert(now >= timers->base);
271
272         list_head_init(list);
273
274         if (!timers->level[0]) {
275                 if (list_empty(&timers->far))
276                         return;
277                 add_level(timers, 0);
278         }
279
280         do {
281                 if (timers->first > now) {
282                         timer_fast_forward(timers, now);
283                         break;
284                 }
285
286                 timer_fast_forward(timers, timers->first);
287                 off = timers->base % PER_LEVEL;
288
289                 list_append_list(list, &timers->level[0]->list[off]);
290                 if (timers->base == now)
291                         break;
292         } while (update_first(timers));
293 }
294
295 static bool timer_list_check(const struct list_head *l,
296                              uint64_t min, uint64_t max, uint64_t first,
297                              const char *abortstr)
298 {
299         const struct timer *t;
300
301         if (!list_check(l, abortstr))
302                 return false;
303
304         list_for_each(l, t, list) {
305                 if (t->time < min || t->time > max) {
306                         if (abortstr) {
307                                 fprintf(stderr,
308                                         "%s: timer %p %llu not %llu-%llu\n",
309                                         abortstr, t, t->time, min, max);
310                                 abort();
311                         }
312                         return false;
313                 }
314                 if (t->time < first) {
315                         if (abortstr) {
316                                 fprintf(stderr,
317                                         "%s: timer %p %llu < minimum %llu\n",
318                                         abortstr, t, t->time, first);
319                                 abort();
320                         }
321                         return false;
322                 }
323         }
324         return true;
325 }
326
327 struct timers *timers_check(const struct timers *timers, const char *abortstr)
328 {
329         unsigned int l, i, off;
330         uint64_t base;
331
332         l = 0;
333         if (!timers->level[0])
334                 goto past_levels;
335
336         /* First level is simple. */
337         off = timers->base % PER_LEVEL;
338         for (i = 0; i < PER_LEVEL; i++) {
339                 struct list_head *h;
340
341                 h = &timers->level[l]->list[(i+off) % PER_LEVEL];
342                 if (!timer_list_check(h, timers->base + i, timers->base + i,
343                                       timers->first, abortstr))
344                         return NULL;
345         }
346
347         /* For other levels, "current" bucket has been emptied, and may contain
348          * entries for the current + level_size bucket. */
349         for (l = 1; timers->level[l] && l < PER_LEVEL; l++) {
350                 uint64_t per_bucket = 1ULL << (TIMER_LEVEL_BITS * l);
351
352                 off = ((timers->base >> (l*TIMER_LEVEL_BITS)) % PER_LEVEL);
353                 /* We start at *next* bucket. */
354                 base = (timers->base & ~(per_bucket - 1)) + per_bucket;
355
356                 for (i = 1; i <= PER_LEVEL; i++) {
357                         struct list_head *h;
358
359                         h = &timers->level[l]->list[(i+off) % PER_LEVEL];
360                         if (!timer_list_check(h, base, base + per_bucket - 1,
361                                               timers->first, abortstr))
362                                 return NULL;
363                         base += per_bucket;
364                 }
365         }
366
367 past_levels:
368         base = (timers->base & ~((1ULL << (TIMER_LEVEL_BITS * l)) - 1))
369                 + (1ULL << (TIMER_LEVEL_BITS * l)) - 1;
370         if (!timer_list_check(&timers->far, base, -1ULL, timers->first,
371                               abortstr))
372                 return NULL;
373
374         return (struct timers *)timers;
375 }
376
377 #ifdef CCAN_TIMER_DEBUG
378 void timers_dump(const struct timers *timers, FILE *fp)
379 {
380         unsigned int l, i;
381         uint64_t min, max, num;
382         struct timer *t;
383
384         if (!fp)
385                 fp = stderr;
386
387         fprintf(fp, "Base: %llu\n", timers->base);
388
389         for (l = 0; timers->level[l] && l < ARRAY_SIZE(timers->level); l++) {
390                 fprintf(fp, "Level %i (+%llu):\n",
391                         l, (uint64_t)1 << (TIMER_LEVEL_BITS * l));
392                 for (i = 0; i < (1 << TIMER_LEVEL_BITS); i++) {
393
394                         if (list_empty(&timers->level[l]->list[i]))
395                                 continue;
396                         min = -1ULL;
397                         max = 0;
398                         num = 0;
399                         list_for_each(&timers->level[l]->list[i], t, list) {
400                                 if (t->time < min)
401                                         min = t->time;
402                                 if (t->time > max)
403                                         max = t->time;
404                                 num++;
405                         }
406                         fprintf(stderr, "  %llu (+%llu-+%llu)\n",
407                                 num, min - timers->base, max - timers->base);
408                 }
409         }
410
411         min = -1ULL;
412         max = 0;
413         num = 0;
414         list_for_each(&timers->far, t, list) {
415                 if (t->time < min)
416                         min = t->time;
417                 if (t->time > max)
418                         max = t->time;
419                 num++;
420         }
421         fprintf(stderr, "Far: %llu (%llu-%llu)\n", num, min, max);
422 }
423 #endif
424
425 void timers_cleanup(struct timers *timers)
426 {
427         unsigned int l;
428
429         for (l = 0; l < ARRAY_SIZE(timers->level); l++)
430                 free(timers->level[l]);
431 }