]> git.ozlabs.org Git - ccan/blob - ccan/timer/timer.c
timer: brute force corruption fix.
[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 timeabs t)
16 {
17         return t.ts.tv_sec * ((uint64_t)1000000000 / TIMER_GRANULARITY)
18                 + (t.ts.tv_nsec / TIMER_GRANULARITY);
19 }
20
21 static struct timeabs grains_to_time(uint64_t grains)
22 {
23         struct timeabs t;
24
25         t.ts.tv_sec = grains / (1000000000 / TIMER_GRANULARITY);
26         t.ts.tv_nsec = (grains % (1000000000 / TIMER_GRANULARITY))
27                 * TIMER_GRANULARITY;
28         return t;
29 }
30
31 void timers_init(struct timers *timers, struct timeabs 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_init(struct timer *t)
67 {
68         list_node_init(&t->list);
69 }
70
71 static bool list_node_initted(const struct list_node *n)
72 {
73         return n->prev == n;
74 }
75
76 void timer_add(struct timers *timers, struct timer *t, struct timeabs when)
77 {
78         assert(list_node_initted(&t->list));
79
80         t->time = time_to_grains(when);
81
82         /* Added in the past?  Treat it as imminent. */
83         if (t->time < timers->base)
84                 t->time = timers->base;
85         if (t->time < timers->first)
86                 timers->first = t->time;
87
88         timer_add_raw(timers, t);
89 }
90
91 /* FIXME: inline */
92 void timer_del(struct timers *timers, struct timer *t)
93 {
94         list_del_init(&t->list);
95 }
96
97 static void timers_far_get(struct timers *timers,
98                            struct list_head *list,
99                            uint64_t when)
100 {
101         struct timer *i, *next;
102
103         list_for_each_safe(&timers->far, i, next, list) {
104                 if (i->time <= when) {
105                         list_del_from(&timers->far, &i->list);
106                         list_add_tail(list, &i->list);
107                 }
108         }
109 }
110
111 static void add_level(struct timers *timers, unsigned int level)
112 {
113         struct timer_level *l;
114         struct timer *t;
115         unsigned int i;
116         struct list_head from_far;
117
118         l = malloc(sizeof(*l));
119         if (!l)
120                 return;
121
122         for (i = 0; i < ARRAY_SIZE(l->list); i++)
123                 list_head_init(&l->list[i]);
124         timers->level[level] = l;
125
126         list_head_init(&from_far);
127         timers_far_get(timers, &from_far,
128                        timers->base + (1ULL << ((level+1)*TIMER_LEVEL_BITS)) - 1);
129
130         while ((t = list_pop(&from_far, struct timer, list)) != NULL)
131                 timer_add_raw(timers, t);
132 }
133
134 /* We don't need to search past the first at level 0, since the
135  * bucket range is 1; they're all the same. */
136 static const struct timer *find_first(const struct list_head *list,
137                                       unsigned int level,
138                                       const struct timer *prev)
139 {
140         struct timer *t;
141
142         list_for_each(list, t, list) {
143                 if (!prev || t->time < prev->time)
144                         prev = t;
145                 if (level == 0)
146                         break;
147         }
148         return prev;
149 }
150
151 /* FIXME: Suboptimal */
152 static const struct timer *brute_force_first(const struct timers *timers)
153 {
154         unsigned int l, i;
155         const struct timer *found = NULL;
156
157         for (l = 0; l < ARRAY_SIZE(timers->level) && timers->level[l]; l++) {
158                 for (i = 0; i < PER_LEVEL; i++)
159                         found = find_first(&timers->level[l]->list[i], l,
160                                            found);
161         }
162
163         found = find_first(&timers->far, -1U, found);
164         return found;
165 }
166                         
167 static const struct timer *get_first(const struct timers *timers)
168 {
169         uint64_t time;
170         
171         /* Where can we start from? */
172         if (timers->first < timers->base)
173                 time = timers->base;
174         else
175                 time = timers->first;
176
177         /* We can have just far timers, for example. */
178         if (timers->level[0]) {
179                 /* First search rest of lower buckets; we've already spilled
180                  * so if we find one there we don't need to search further. */
181                 unsigned int i, off = time % PER_LEVEL;
182
183                 for (i = off; i < PER_LEVEL; i++) {
184                         struct list_head *h = &timers->level[0]->list[i];
185                         if (!list_empty(h))
186                                 return find_first(h, 0, NULL);
187                 }
188         }
189
190         /* From here on, we're searching non-normalized parts of the
191          * data structure, which is much subtler.
192          *
193          * So we brute force. */
194         return brute_force_first(timers);
195 }
196
197 static bool update_first(struct timers *timers)
198 {
199         const struct timer *found = get_first(timers);
200
201         if (!found) {
202                 timers->first = -1ULL;
203                 return false;
204         }
205
206         timers->first = found->time;
207         return true;
208 }
209
210 bool timer_earliest(struct timers *timers, struct timeabs *first)
211 {
212         if (!update_first(timers))
213                 return false;
214
215         *first = grains_to_time(timers->first);
216         return true;
217 }
218
219 /* Assume no timers before 'time', cascade down and update base time. */
220 static void timer_fast_forward(struct timers *timers, uint64_t time)
221 {
222         unsigned int level, changed;
223         int need_level = -1;
224         struct list_head list;
225         struct timer *i;
226
227         /* How many bits changed between base and time?
228          * Each time we wrap, we need to empty buckets from above. */
229         if (time == timers->base)
230                 return;
231
232         changed = ilog64_nz(time ^ timers->base);
233         level = (changed - 1) / TIMER_LEVEL_BITS;
234
235         /* Buckets always empty downwards, so we could cascade manually,
236          * but it's rarely very many so we just remove and re-add */
237         list_head_init(&list);
238
239         do {
240                 if (!timers->level[level]) {
241                         /* We need any which belong on this level. */
242                         timers_far_get(timers, &list,
243                                        timers->base
244                                        + (1ULL << ((level+1)*TIMER_LEVEL_BITS))-1);
245                         need_level = level;
246                 } else {
247                         unsigned src;
248
249                         /* Get all timers from this bucket. */
250                         src = (time >> (level * TIMER_LEVEL_BITS)) % PER_LEVEL;
251                         list_append_list(&list,
252                                          &timers->level[level]->list[src]);
253                 }
254         } while (level--);
255
256         /* Did we hit the last level?  If so, add. */
257         if (need_level != -1)
258                 add_level(timers, need_level);
259
260         /* Fast-forward the time, and re-add everyone. */
261         timers->base = time;
262         while ((i = list_pop(&list, struct timer, list)) != NULL)
263                 timer_add_raw(timers, i);
264 }
265
266 /* Returns an expired timer. */
267 struct timer *timers_expire(struct timers *timers, struct timeabs expire)
268 {
269         uint64_t now = time_to_grains(expire);
270         unsigned int off;
271         struct timer *t;
272
273         assert(now >= timers->base);
274
275         if (!timers->level[0]) {
276                 if (list_empty(&timers->far))
277                         return NULL;
278                 add_level(timers, 0);
279         }
280
281         do {
282                 if (timers->first > now) {
283                         timer_fast_forward(timers, now);
284                         return NULL;
285                 }
286
287                 timer_fast_forward(timers, timers->first);
288                 off = timers->base % PER_LEVEL;
289
290                 /* This *may* be NULL, if we deleted the first timer */
291                 t = list_pop(&timers->level[0]->list[off], struct timer, list);
292                 if (t)
293                         list_node_init(&t->list);
294         } while (!t && update_first(timers));
295
296         return t;
297 }
298
299 static bool timer_list_check(const struct list_head *l,
300                              uint64_t min, uint64_t max, uint64_t first,
301                              const char *abortstr)
302 {
303         const struct timer *t;
304
305         if (!list_check(l, abortstr))
306                 return false;
307
308         list_for_each(l, t, list) {
309                 if (t->time < min || t->time > max) {
310                         if (abortstr) {
311                                 fprintf(stderr,
312                                         "%s: timer %p %llu not %llu-%llu\n",
313                                         abortstr, t, (long long)t->time,
314                                         (long long)min, (long long)max);
315                                 abort();
316                         }
317                         return false;
318                 }
319                 if (t->time < first) {
320                         if (abortstr) {
321                                 fprintf(stderr,
322                                         "%s: timer %p %llu < minimum %llu\n",
323                                         abortstr, t, (long long)t->time,
324                                         (long long)first);
325                                 abort();
326                         }
327                         return false;
328                 }
329         }
330         return true;
331 }
332
333 struct timers *timers_check(const struct timers *timers, const char *abortstr)
334 {
335         unsigned int l, i, off;
336         uint64_t base;
337
338         l = 0;
339         if (!timers->level[0])
340                 goto past_levels;
341
342         /* First level is simple. */
343         off = timers->base % PER_LEVEL;
344         for (i = 0; i < PER_LEVEL; i++) {
345                 struct list_head *h;
346
347                 h = &timers->level[l]->list[(i+off) % PER_LEVEL];
348                 if (!timer_list_check(h, timers->base + i, timers->base + i,
349                                       timers->first, abortstr))
350                         return NULL;
351         }
352
353         /* For other levels, "current" bucket has been emptied, and may contain
354          * entries for the current + level_size bucket. */
355         for (l = 1; l < ARRAY_SIZE(timers->level) && timers->level[l]; l++) {
356                 uint64_t per_bucket = 1ULL << (TIMER_LEVEL_BITS * l);
357
358                 off = ((timers->base >> (l*TIMER_LEVEL_BITS)) % PER_LEVEL);
359                 /* We start at *next* bucket. */
360                 base = (timers->base & ~(per_bucket - 1)) + per_bucket;
361
362                 for (i = 1; i <= PER_LEVEL; i++) {
363                         struct list_head *h;
364
365                         h = &timers->level[l]->list[(i+off) % PER_LEVEL];
366                         if (!timer_list_check(h, base, base + per_bucket - 1,
367                                               timers->first, abortstr))
368                                 return NULL;
369                         base += per_bucket;
370                 }
371         }
372
373 past_levels:
374         base = (timers->base & ~((1ULL << (TIMER_LEVEL_BITS * l)) - 1))
375                 + (1ULL << (TIMER_LEVEL_BITS * l)) - 1;
376         if (!timer_list_check(&timers->far, base, -1ULL, timers->first,
377                               abortstr))
378                 return NULL;
379
380         return (struct timers *)timers;
381 }
382
383 #ifdef CCAN_TIMER_DEBUG
384 static void dump_bucket_stats(FILE *fp, const struct list_head *h)
385 {
386         unsigned long long min, max, num;
387         struct timer *t;
388
389         if (list_empty(h)) {
390                 printf("\n");
391                 return;
392         }
393
394         min = -1ULL;
395         max = 0;
396         num = 0;
397         list_for_each(h, t, list) {
398                 if (t->time < min)
399                         min = t->time;
400                 if (t->time > max)
401                         max = t->time;
402                 num++;
403         }
404         fprintf(fp, " %llu (%llu-%llu)\n",
405                 num, min, max);
406 }
407
408 void timers_dump(const struct timers *timers, FILE *fp)
409 {
410         unsigned int l, i, off;
411         unsigned long long base;
412
413         if (!fp)
414                 fp = stderr;
415
416         fprintf(fp, "Base: %llu\n", (unsigned long long)timers->base);
417
418         if (!timers->level[0])
419                 goto past_levels;
420
421         fprintf(fp, "Level 0:\n");
422
423         /* First level is simple. */
424         off = timers->base % PER_LEVEL;
425         for (i = 0; i < PER_LEVEL; i++) {
426                 const struct list_head *h;
427
428                 fprintf(fp, "  Bucket %llu (%lu):",
429                         (i+off) % PER_LEVEL, timers->base + i);
430                 h = &timers->level[0]->list[(i+off) % PER_LEVEL];
431                 dump_bucket_stats(fp, h);
432         }
433
434         /* For other levels, "current" bucket has been emptied, and may contain
435          * entries for the current + level_size bucket. */
436         for (l = 1; l < ARRAY_SIZE(timers->level) && timers->level[l]; l++) {
437                 uint64_t per_bucket = 1ULL << (TIMER_LEVEL_BITS * l);
438
439                 off = ((timers->base >> (l*TIMER_LEVEL_BITS)) % PER_LEVEL);
440                 /* We start at *next* bucket. */
441                 base = (timers->base & ~(per_bucket - 1)) + per_bucket;
442
443                 fprintf(fp, "Level %u:\n", l);
444                 for (i = 1; i <= PER_LEVEL; i++) {
445                         const struct list_head *h;
446
447                         fprintf(fp, "  Bucket %llu (%llu - %llu):",
448                                 (i+off) % PER_LEVEL,
449                                 base, base + per_bucket - 1);
450
451                         h = &timers->level[l]->list[(i+off) % PER_LEVEL];
452                         dump_bucket_stats(fp, h);
453                         base += per_bucket;
454                 }
455         }
456
457 past_levels:
458         if (!list_empty(&timers->far)) {
459                 fprintf(fp, "Far timers:");
460                 dump_bucket_stats(fp, &timers->far);
461         }
462 }
463 #endif
464
465 void timers_cleanup(struct timers *timers)
466 {
467         unsigned int l;
468
469         for (l = 0; l < ARRAY_SIZE(timers->level); l++)
470                 free(timers->level[l]);
471 }