]> git.ozlabs.org Git - ccan/blob - ccan/timer/timer.c
2685d3efde96f780fbbc3dc946d6acc4b9def9e1
[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 <stdlib.h>
6 #include <stdio.h>
7
8 #define PER_LEVEL (1ULL << TIMER_LEVEL_BITS)
9
10 struct timer_level {
11         struct list_head list[PER_LEVEL];
12 };
13
14 static void *timer_default_alloc(struct timers *timers, size_t len)
15 {
16         return malloc(len);
17 }
18
19 static void timer_default_free(struct timers *timers, void *p)
20 {
21         free(p);
22 }
23
24 static void *(*timer_alloc)(struct timers *, size_t) = timer_default_alloc;
25 static void (*timer_free)(struct timers *, void *) = timer_default_free;
26
27 void timers_set_allocator(void *(*alloc)(struct timers *, size_t len),
28                           void (*free)(struct timers *, void *p))
29 {
30         if (!alloc)
31                 alloc = timer_default_alloc;
32         if (!free)
33                 free = timer_default_free;
34         timer_alloc = alloc;
35         timer_free = free;
36 }
37
38 static uint64_t time_to_grains(struct timemono t)
39 {
40         return t.ts.tv_sec * ((uint64_t)1000000000 / TIMER_GRANULARITY)
41                 + (t.ts.tv_nsec / TIMER_GRANULARITY);
42 }
43
44 static struct timemono grains_to_time(uint64_t grains)
45 {
46         struct timemono t;
47
48         t.ts.tv_sec = grains / (1000000000 / TIMER_GRANULARITY);
49         t.ts.tv_nsec = (grains % (1000000000 / TIMER_GRANULARITY))
50                 * TIMER_GRANULARITY;
51         return t;
52 }
53
54 void timers_init(struct timers *timers, struct timemono start)
55 {
56         unsigned int i;
57
58         list_head_init(&timers->far);
59         timers->base = time_to_grains(start);
60         timers->first = -1ULL;
61         memset(timers->firsts, 0xFF, sizeof(timers->firsts));
62         for (i = 0; i < ARRAY_SIZE(timers->level); i++)
63                 timers->level[i] = NULL;
64 }
65
66 static unsigned int level_of(const struct timers *timers, uint64_t time)
67 {
68         uint64_t diff;
69
70         /* Level depends how far away it is. */
71         diff = time - timers->base;
72         return ilog64(diff / 2) / TIMER_LEVEL_BITS;
73 }
74
75 static void timer_add_raw(struct timers *timers, struct timer *t)
76 {
77         struct list_head *l;
78         unsigned int level = level_of(timers, t->time);
79         uint64_t *first;
80
81         if (!timers->level[level]) {
82                 l = &timers->far;
83                 first = &timers->firsts[ARRAY_SIZE(timers->level)];
84         } else {
85                 int off = (t->time >> (level*TIMER_LEVEL_BITS)) & (PER_LEVEL-1);
86                 l = &timers->level[level]->list[off];
87                 first = &timers->firsts[level];
88         }
89
90         list_add_tail(l, &t->list);
91         if (t->time < *first)
92                 *first = t->time;
93 }
94
95 void timer_init(struct timer *t)
96 {
97         list_node_init(&t->list);
98 }
99
100 static bool list_node_initted(const struct list_node *n)
101 {
102         return n->prev == n;
103 }
104
105 void timer_addrel(struct timers *timers, struct timer *t, struct timerel rel)
106 {
107         assert(list_node_initted(&t->list));
108
109         t->time = time_to_grains(timemono_add(time_mono(), rel));
110
111 #if TIME_HAVE_MONOTONIC
112         assert(t->time >= timers->base);
113 #else
114         /* Added in the past?  Treat it as imminent. */
115         if (t->time < timers->base)
116                 t->time = timers->base;
117 #endif
118         if (t->time < timers->first)
119                 timers->first = t->time;
120
121         timer_add_raw(timers, t);
122 }
123
124 void timer_addmono(struct timers *timers, struct timer *t, struct timemono when)
125 {
126         assert(list_node_initted(&t->list));
127
128         t->time = time_to_grains(when);
129
130         /* Added in the past?  Treat it as imminent. */
131         if (t->time < timers->base)
132                 t->time = timers->base;
133         if (t->time < timers->first)
134                 timers->first = t->time;
135
136         timer_add_raw(timers, t);
137 }
138
139 /* FIXME: inline */
140 void timer_del(struct timers *timers UNNEEDED, struct timer *t)
141 {
142         list_del_init(&t->list);
143 }
144
145 static void timers_far_get(struct timers *timers,
146                            struct list_head *list,
147                            uint64_t when)
148 {
149         struct timer *i, *next;
150
151         list_for_each_safe(&timers->far, i, next, list) {
152                 if (i->time <= when) {
153                         list_del_from(&timers->far, &i->list);
154                         list_add_tail(list, &i->list);
155                 }
156         }
157 }
158
159 static void add_level(struct timers *timers, unsigned int level)
160 {
161         struct timer_level *l;
162         struct timer *t;
163         unsigned int i;
164         struct list_head from_far;
165
166         l = timer_alloc(timers, sizeof(*l));
167         if (!l)
168                 return;
169
170         for (i = 0; i < ARRAY_SIZE(l->list); i++)
171                 list_head_init(&l->list[i]);
172         timers->level[level] = l;
173
174         list_head_init(&from_far);
175         timers_far_get(timers, &from_far,
176                        timers->base + (1ULL << ((level+1)*TIMER_LEVEL_BITS)) - 1);
177
178         while ((t = list_pop(&from_far, struct timer, list)) != NULL)
179                 timer_add_raw(timers, t);
180 }
181
182 /* We don't need to search past the first at level 0, since the
183  * bucket range is 1; they're all the same. */
184 static const struct timer *find_first(const struct list_head *list,
185                                       unsigned int level,
186                                       const struct timer *prev)
187 {
188         struct timer *t;
189
190         list_for_each(list, t, list) {
191                 if (!prev || t->time < prev->time)
192                         prev = t;
193                 if (level == 0)
194                         break;
195         }
196         return prev;
197 }
198
199 /* Update level's first watermark, and return overall first. */
200 static const struct timer *first_for_level(struct timers *timers,
201                                            size_t level,
202                                            const struct timer *level_first,
203                                            const struct timer *first)
204 {
205         if (level_first) {
206                 timers->firsts[level] = level_first->time;
207                 if (!first || level_first->time < first->time)
208                         first = level_first;
209         } else {
210                 timers->firsts[level] = -1ULL;
211         }
212         return first;
213 }
214
215 static bool level_may_beat(const struct timers *timers, size_t level,
216                            const struct timer *first)
217 {
218         return !first || timers->firsts[level] < first->time;
219 }
220
221 /* FIXME: Suboptimal */
222 static const struct timer *brute_force_first(struct timers *timers)
223 {
224         unsigned int l, i;
225         const struct timer *found = NULL;
226
227         for (l = 0; l < ARRAY_SIZE(timers->level) && timers->level[l]; l++) {
228                 const struct timer *t = NULL;
229
230                 /* Do we know they don't have a better one? */
231                 if (!level_may_beat(timers, l, found))
232                         continue;
233
234                 /* Find first timer on this level. */
235                 for (i = 0; i < PER_LEVEL; i++)
236                         t = find_first(&timers->level[l]->list[i], l, t);
237
238                 found = first_for_level(timers, l, t, found);
239         }
240
241         /* Check (and update) far list if there's a chance. */
242         l = ARRAY_SIZE(timers->level);
243         if (level_may_beat(timers, l, found)) {
244                 const struct timer *t = find_first(&timers->far, l, NULL);
245                 found = first_for_level(timers, l, t, found);
246         }
247
248         return found;
249 }
250
251 static const struct timer *get_first(struct timers *timers)
252 {
253         /* We can have just far timers, for example. */
254         if (timers->level[0]) {
255                 /* First search rest of lower buckets; we've already spilled
256                  * so if we find one there we don't need to search further. */
257                 unsigned int i, off = timers->base % PER_LEVEL;
258
259                 for (i = off; i < PER_LEVEL; i++) {
260                         struct list_head *h = &timers->level[0]->list[i];
261                         if (!list_empty(h))
262                                 return find_first(h, 0, NULL);
263                 }
264         }
265
266         /* From here on, we're searching non-normalized parts of the
267          * data structure, which is much subtler.
268          *
269          * So we brute force. */
270         return brute_force_first(timers);
271 }
272
273 static bool update_first(struct timers *timers)
274 {
275         const struct timer *found = get_first(timers);
276
277         if (!found) {
278                 timers->first = -1ULL;
279                 return false;
280         }
281
282         timers->first = found->time;
283         return true;
284 }
285
286 bool timer_earliest(struct timers *timers, struct timemono *first)
287 {
288         if (!update_first(timers))
289                 return false;
290
291         *first = grains_to_time(timers->first);
292         return true;
293 }
294
295 /* Assume no timers before 'time', cascade down and update base time. */
296 static void timer_fast_forward(struct timers *timers, uint64_t time)
297 {
298         unsigned int level, changed;
299         int need_level = -1;
300         struct list_head list;
301         struct timer *i;
302
303         /* How many bits changed between base and time?
304          * Each time we wrap, we need to empty buckets from above. */
305         if (time == timers->base)
306                 return;
307
308         changed = ilog64_nz(time ^ timers->base);
309         level = (changed - 1) / TIMER_LEVEL_BITS;
310
311         /* Buckets always empty downwards, so we could cascade manually,
312          * but it's rarely very many so we just remove and re-add */
313         list_head_init(&list);
314
315         do {
316                 if (!timers->level[level]) {
317                         /* We need any which belong on this level. */
318                         timers_far_get(timers, &list,
319                                        timers->base
320                                        + (1ULL << ((level+1)*TIMER_LEVEL_BITS))-1);
321                         need_level = level;
322                 } else {
323                         unsigned src;
324
325                         /* Get all timers from this bucket. */
326                         src = (time >> (level * TIMER_LEVEL_BITS)) % PER_LEVEL;
327                         list_append_list(&list,
328                                          &timers->level[level]->list[src]);
329                 }
330         } while (level--);
331
332         /* Did we hit the last level?  If so, add. */
333         if (need_level != -1)
334                 add_level(timers, need_level);
335
336         /* Fast-forward the time, and re-add everyone. */
337         timers->base = time;
338         while ((i = list_pop(&list, struct timer, list)) != NULL)
339                 timer_add_raw(timers, i);
340 }
341
342 /* Returns an expired timer. */
343 struct timer *timers_expire(struct timers *timers, struct timemono expire)
344 {
345         uint64_t now = time_to_grains(expire);
346         unsigned int off;
347         struct timer *t;
348
349         assert(now >= timers->base);
350
351         if (!timers->level[0]) {
352                 if (list_empty(&timers->far))
353                         return NULL;
354                 add_level(timers, 0);
355         }
356
357         do {
358                 if (timers->first > now) {
359                         timer_fast_forward(timers, now);
360                         return NULL;
361                 }
362
363                 timer_fast_forward(timers, timers->first);
364                 off = timers->base % PER_LEVEL;
365
366                 /* This *may* be NULL, if we deleted the first timer */
367                 t = list_pop(&timers->level[0]->list[off], struct timer, list);
368                 if (t)
369                         list_node_init(&t->list);
370         } while (!t && update_first(timers));
371
372         return t;
373 }
374
375 static bool timer_list_check(const struct list_head *l,
376                              uint64_t min, uint64_t max, uint64_t first,
377                              const char *abortstr)
378 {
379         const struct timer *t;
380
381         if (!list_check(l, abortstr))
382                 return false;
383
384         list_for_each(l, t, list) {
385                 if (t->time < min || t->time > max) {
386                         if (abortstr) {
387                                 fprintf(stderr,
388                                         "%s: timer %p %llu not %llu-%llu\n",
389                                         abortstr, t, (long long)t->time,
390                                         (long long)min, (long long)max);
391                                 abort();
392                         }
393                         return false;
394                 }
395                 if (t->time < first) {
396                         if (abortstr) {
397                                 fprintf(stderr,
398                                         "%s: timer %p %llu < minimum %llu\n",
399                                         abortstr, t, (long long)t->time,
400                                         (long long)first);
401                                 abort();
402                         }
403                         return false;
404                 }
405         }
406         return true;
407 }
408
409 struct timers *timers_check(const struct timers *timers, const char *abortstr)
410 {
411         unsigned int l, i, off;
412         uint64_t base;
413
414         l = 0;
415         if (!timers->level[0])
416                 goto past_levels;
417
418         /* First level is simple. */
419         off = timers->base % PER_LEVEL;
420         for (i = 0; i < PER_LEVEL; i++) {
421                 struct list_head *h;
422
423                 h = &timers->level[l]->list[(i+off) % PER_LEVEL];
424                 if (!timer_list_check(h, timers->base + i, timers->base + i,
425                                       timers->firsts[l], abortstr))
426                         return NULL;
427         }
428
429         /* For other levels, "current" bucket has been emptied, and may contain
430          * entries for the current + level_size bucket. */
431         for (l = 1; l < ARRAY_SIZE(timers->level) && timers->level[l]; l++) {
432                 uint64_t per_bucket = 1ULL << (TIMER_LEVEL_BITS * l);
433
434                 off = ((timers->base >> (l*TIMER_LEVEL_BITS)) % PER_LEVEL);
435                 /* We start at *next* bucket. */
436                 base = (timers->base & ~(per_bucket - 1)) + per_bucket;
437
438                 for (i = 1; i <= PER_LEVEL; i++) {
439                         struct list_head *h;
440
441                         h = &timers->level[l]->list[(i+off) % PER_LEVEL];
442                         if (!timer_list_check(h, base, base + per_bucket - 1,
443                                               timers->firsts[l], abortstr))
444                                 return NULL;
445                         base += per_bucket;
446                 }
447         }
448
449 past_levels:
450         base = (timers->base & ~((1ULL << (TIMER_LEVEL_BITS * l)) - 1))
451                 + (1ULL << (TIMER_LEVEL_BITS * l)) - 1;
452         if (!timer_list_check(&timers->far, base, -1ULL,
453                               timers->firsts[ARRAY_SIZE(timers->level)],
454                               abortstr))
455                 return NULL;
456
457         return (struct timers *)timers;
458 }
459
460 #ifdef CCAN_TIMER_DEBUG
461 static void dump_bucket_stats(FILE *fp, const struct list_head *h)
462 {
463         unsigned long long min, max, num;
464         struct timer *t;
465
466         if (list_empty(h)) {
467                 printf("\n");
468                 return;
469         }
470
471         min = -1ULL;
472         max = 0;
473         num = 0;
474         list_for_each(h, t, list) {
475                 if (t->time < min)
476                         min = t->time;
477                 if (t->time > max)
478                         max = t->time;
479                 num++;
480         }
481         fprintf(fp, " %llu (%llu-%llu)\n",
482                 num, min, max);
483 }
484
485 void timers_dump(const struct timers *timers, FILE *fp)
486 {
487         unsigned int l, i, off;
488         unsigned long long base;
489
490         if (!fp)
491                 fp = stderr;
492
493         fprintf(fp, "Base: %llu\n", (unsigned long long)timers->base);
494
495         if (!timers->level[0])
496                 goto past_levels;
497
498         fprintf(fp, "Level 0:\n");
499
500         /* First level is simple. */
501         off = timers->base % PER_LEVEL;
502         for (i = 0; i < PER_LEVEL; i++) {
503                 const struct list_head *h;
504
505                 fprintf(fp, "  Bucket %llu (%lu):",
506                         (i+off) % PER_LEVEL, timers->base + i);
507                 h = &timers->level[0]->list[(i+off) % PER_LEVEL];
508                 dump_bucket_stats(fp, h);
509         }
510
511         /* For other levels, "current" bucket has been emptied, and may contain
512          * entries for the current + level_size bucket. */
513         for (l = 1; l < ARRAY_SIZE(timers->level) && timers->level[l]; l++) {
514                 uint64_t per_bucket = 1ULL << (TIMER_LEVEL_BITS * l);
515
516                 off = ((timers->base >> (l*TIMER_LEVEL_BITS)) % PER_LEVEL);
517                 /* We start at *next* bucket. */
518                 base = (timers->base & ~(per_bucket - 1)) + per_bucket;
519
520                 fprintf(fp, "Level %u:\n", l);
521                 for (i = 1; i <= PER_LEVEL; i++) {
522                         const struct list_head *h;
523
524                         fprintf(fp, "  Bucket %llu (%llu - %llu):",
525                                 (i+off) % PER_LEVEL,
526                                 base, base + per_bucket - 1);
527
528                         h = &timers->level[l]->list[(i+off) % PER_LEVEL];
529                         dump_bucket_stats(fp, h);
530                         base += per_bucket;
531                 }
532         }
533
534 past_levels:
535         if (!list_empty(&timers->far)) {
536                 fprintf(fp, "Far timers:");
537                 dump_bucket_stats(fp, &timers->far);
538         }
539 }
540 #endif
541
542 void timers_cleanup(struct timers *timers)
543 {
544         unsigned int l;
545
546         for (l = 0; l < ARRAY_SIZE(timers->level); l++)
547                 timer_free(timers, timers->level[l]);
548 }