7e3e2e5b4375724dcb826c2c34523b994b0d3034
[fio.git] / gettime.c
1 /*
2  * Clock functions
3  */
4
5 #include <unistd.h>
6 #include <math.h>
7 #include <sys/time.h>
8 #include <time.h>
9
10 #include "fio.h"
11 #include "smalloc.h"
12
13 #include "hash.h"
14 #include "os/os.h"
15
16 #if defined(ARCH_HAVE_CPU_CLOCK) && !defined(ARCH_CPU_CLOCK_CYCLES_PER_USEC)
17 static unsigned long cycles_per_usec;
18 static unsigned long inv_cycles_per_usec;
19 static uint64_t max_cycles_for_mult;
20 #endif
21 int tsc_reliable = 0;
22
23 struct tv_valid {
24         uint64_t last_cycles;
25         int last_tv_valid;
26         int warned;
27 };
28 #ifdef CONFIG_TLS_THREAD
29 static __thread struct tv_valid static_tv_valid;
30 #else
31 static pthread_key_t tv_tls_key;
32 #endif
33
34 enum fio_cs fio_clock_source = FIO_PREFERRED_CLOCK_SOURCE;
35 int fio_clock_source_set = 0;
36 static enum fio_cs fio_clock_source_inited = CS_INVAL;
37
38 #ifdef FIO_DEBUG_TIME
39
40 #define HASH_BITS       8
41 #define HASH_SIZE       (1 << HASH_BITS)
42
43 static struct flist_head hash[HASH_SIZE];
44 static int gtod_inited;
45
46 struct gtod_log {
47         struct flist_head list;
48         void *caller;
49         unsigned long calls;
50 };
51
52 static struct gtod_log *find_hash(void *caller)
53 {
54         unsigned long h = hash_ptr(caller, HASH_BITS);
55         struct flist_head *entry;
56
57         flist_for_each(entry, &hash[h]) {
58                 struct gtod_log *log = flist_entry(entry, struct gtod_log,
59                                                                         list);
60
61                 if (log->caller == caller)
62                         return log;
63         }
64
65         return NULL;
66 }
67
68 static void inc_caller(void *caller)
69 {
70         struct gtod_log *log = find_hash(caller);
71
72         if (!log) {
73                 unsigned long h;
74
75                 log = malloc(sizeof(*log));
76                 INIT_FLIST_HEAD(&log->list);
77                 log->caller = caller;
78                 log->calls = 0;
79
80                 h = hash_ptr(caller, HASH_BITS);
81                 flist_add_tail(&log->list, &hash[h]);
82         }
83
84         log->calls++;
85 }
86
87 static void gtod_log_caller(void *caller)
88 {
89         if (gtod_inited)
90                 inc_caller(caller);
91 }
92
93 static void fio_exit fio_dump_gtod(void)
94 {
95         unsigned long total_calls = 0;
96         int i;
97
98         for (i = 0; i < HASH_SIZE; i++) {
99                 struct flist_head *entry;
100                 struct gtod_log *log;
101
102                 flist_for_each(entry, &hash[i]) {
103                         log = flist_entry(entry, struct gtod_log, list);
104
105                         printf("function %p, calls %lu\n", log->caller,
106                                                                 log->calls);
107                         total_calls += log->calls;
108                 }
109         }
110
111         printf("Total %lu gettimeofday\n", total_calls);
112 }
113
114 static void fio_init gtod_init(void)
115 {
116         int i;
117
118         for (i = 0; i < HASH_SIZE; i++)
119                 INIT_FLIST_HEAD(&hash[i]);
120
121         gtod_inited = 1;
122 }
123
124 #endif /* FIO_DEBUG_TIME */
125
126 #ifdef CONFIG_CLOCK_GETTIME
127 static int fill_clock_gettime(struct timespec *ts)
128 {
129 #ifdef CONFIG_CLOCK_MONOTONIC
130         return clock_gettime(CLOCK_MONOTONIC, ts);
131 #else
132         return clock_gettime(CLOCK_REALTIME, ts);
133 #endif
134 }
135 #endif
136
137 static void __fio_gettime(struct timeval *tp)
138 {
139         struct tv_valid *tv;
140
141 #ifdef CONFIG_TLS_THREAD
142         tv = &static_tv_valid;
143 #else
144         tv = pthread_getspecific(tv_tls_key);
145 #endif
146
147         switch (fio_clock_source) {
148 #ifdef CONFIG_GETTIMEOFDAY
149         case CS_GTOD:
150                 gettimeofday(tp, NULL);
151                 break;
152 #endif
153 #ifdef CONFIG_CLOCK_GETTIME
154         case CS_CGETTIME: {
155                 struct timespec ts;
156
157                 if (fill_clock_gettime(&ts) < 0) {
158                         log_err("fio: clock_gettime fails\n");
159                         assert(0);
160                 }
161
162                 tp->tv_sec = ts.tv_sec;
163                 tp->tv_usec = ts.tv_nsec / 1000;
164                 break;
165                 }
166 #endif
167 #ifdef ARCH_HAVE_CPU_CLOCK
168         case CS_CPUCLOCK: {
169                 uint64_t usecs, t;
170
171                 t = get_cpu_clock();
172                 if (t < tv->last_cycles && tv->last_tv_valid &&
173                     !tv->warned) {
174                         log_err("fio: CPU clock going back in time\n");
175                         tv->warned = 1;
176                 }
177
178                 tv->last_cycles = t;
179                 tv->last_tv_valid = 1;
180 #ifdef ARCH_CPU_CLOCK_CYCLES_PER_USEC
181                 usecs = t / ARCH_CPU_CLOCK_CYCLES_PER_USEC;
182 #else
183                 if (t < max_cycles_for_mult)
184                         usecs = (t * inv_cycles_per_usec) / 16777216UL;
185                 else
186                         usecs = t / cycles_per_usec;
187 #endif
188                 tp->tv_sec = usecs / 1000000;
189                 tp->tv_usec = usecs % 1000000;
190                 break;
191                 }
192 #endif
193         default:
194                 log_err("fio: invalid clock source %d\n", fio_clock_source);
195                 break;
196         }
197 }
198
199 #ifdef FIO_DEBUG_TIME
200 void fio_gettime(struct timeval *tp, void *caller)
201 #else
202 void fio_gettime(struct timeval *tp, void fio_unused *caller)
203 #endif
204 {
205 #ifdef FIO_DEBUG_TIME
206         if (!caller)
207                 caller = __builtin_return_address(0);
208
209         gtod_log_caller(caller);
210 #endif
211         if (fio_unlikely(fio_gettime_offload(tp)))
212                 return;
213
214         __fio_gettime(tp);
215 }
216
217 #if defined(ARCH_HAVE_CPU_CLOCK) && !defined(ARCH_CPU_CLOCK_CYCLES_PER_USEC)
218 static unsigned long get_cycles_per_usec(void)
219 {
220         struct timeval s, e;
221         uint64_t c_s, c_e;
222         enum fio_cs old_cs = fio_clock_source;
223
224 #ifdef CONFIG_CLOCK_GETTIME
225         fio_clock_source = CS_CGETTIME;
226 #else
227         fio_clock_source = CS_GTOD;
228 #endif
229         __fio_gettime(&s);
230
231         c_s = get_cpu_clock();
232         do {
233                 uint64_t elapsed;
234
235                 __fio_gettime(&e);
236
237                 elapsed = utime_since(&s, &e);
238                 if (elapsed >= 1280) {
239                         c_e = get_cpu_clock();
240                         break;
241                 }
242         } while (1);
243
244         fio_clock_source = old_cs;
245         return (c_e - c_s + 127) >> 7;
246 }
247
248 #define NR_TIME_ITERS   50
249
250 static int calibrate_cpu_clock(void)
251 {
252         double delta, mean, S;
253         uint64_t avg, cycles[NR_TIME_ITERS];
254         int i, samples;
255
256         cycles[0] = get_cycles_per_usec();
257         S = delta = mean = 0.0;
258         for (i = 0; i < NR_TIME_ITERS; i++) {
259                 cycles[i] = get_cycles_per_usec();
260                 delta = cycles[i] - mean;
261                 if (delta) {
262                         mean += delta / (i + 1.0);
263                         S += delta * (cycles[i] - mean);
264                 }
265         }
266
267         /*
268          * The most common platform clock breakage is returning zero
269          * indefinitely. Check for that and return failure.
270          */
271         if (!cycles[0] && !cycles[NR_TIME_ITERS - 1])
272                 return 1;
273
274         S = sqrt(S / (NR_TIME_ITERS - 1.0));
275
276         samples = avg = 0;
277         for (i = 0; i < NR_TIME_ITERS; i++) {
278                 double this = cycles[i];
279
280                 if ((fmax(this, mean) - fmin(this, mean)) > S)
281                         continue;
282                 samples++;
283                 avg += this;
284         }
285
286         S /= (double) NR_TIME_ITERS;
287         mean /= 10.0;
288
289         for (i = 0; i < NR_TIME_ITERS; i++)
290                 dprint(FD_TIME, "cycles[%d]=%llu\n", i,
291                                         (unsigned long long) cycles[i] / 10);
292
293         avg /= samples;
294         avg = (avg + 5) / 10;
295         dprint(FD_TIME, "avg: %llu\n", (unsigned long long) avg);
296         dprint(FD_TIME, "mean=%f, S=%f\n", mean, S);
297
298         cycles_per_usec = avg;
299         inv_cycles_per_usec = 16777216UL / cycles_per_usec;
300         max_cycles_for_mult = ~0ULL / inv_cycles_per_usec;
301         dprint(FD_TIME, "inv_cycles_per_usec=%lu\n", inv_cycles_per_usec);
302         return 0;
303 }
304 #else
305 static int calibrate_cpu_clock(void)
306 {
307 #ifdef ARCH_CPU_CLOCK_CYCLES_PER_USEC
308         return 0;
309 #else
310         return 1;
311 #endif
312 }
313 #endif // ARCH_HAVE_CPU_CLOCK
314
315 #ifndef CONFIG_TLS_THREAD
316 void fio_local_clock_init(int is_thread)
317 {
318         struct tv_valid *t;
319
320         t = calloc(1, sizeof(*t));
321         if (pthread_setspecific(tv_tls_key, t)) {
322                 log_err("fio: can't set TLS key\n");
323                 assert(0);
324         }
325 }
326
327 static void kill_tv_tls_key(void *data)
328 {
329         free(data);
330 }
331 #else
332 void fio_local_clock_init(int is_thread)
333 {
334 }
335 #endif
336
337 void fio_clock_init(void)
338 {
339         if (fio_clock_source == fio_clock_source_inited)
340                 return;
341
342 #ifndef CONFIG_TLS_THREAD
343         if (pthread_key_create(&tv_tls_key, kill_tv_tls_key))
344                 log_err("fio: can't create TLS key\n");
345 #endif
346
347         fio_clock_source_inited = fio_clock_source;
348
349         if (calibrate_cpu_clock())
350                 tsc_reliable = 0;
351
352         /*
353          * If the arch sets tsc_reliable != 0, then it must be good enough
354          * to use as THE clock source. For x86 CPUs, this means the TSC
355          * runs at a constant rate and is synced across CPU cores.
356          */
357         if (tsc_reliable) {
358                 if (!fio_clock_source_set)
359                         fio_clock_source = CS_CPUCLOCK;
360         } else if (fio_clock_source == CS_CPUCLOCK)
361                 log_info("fio: clocksource=cpu may not be reliable\n");
362 }
363
364 uint64_t utime_since(const struct timeval *s, const struct timeval *e)
365 {
366         long sec, usec;
367         uint64_t ret;
368
369         sec = e->tv_sec - s->tv_sec;
370         usec = e->tv_usec - s->tv_usec;
371         if (sec > 0 && usec < 0) {
372                 sec--;
373                 usec += 1000000;
374         }
375
376         /*
377          * time warp bug on some kernels?
378          */
379         if (sec < 0 || (sec == 0 && usec < 0))
380                 return 0;
381
382         ret = sec * 1000000ULL + usec;
383
384         return ret;
385 }
386
387 uint64_t utime_since_now(const struct timeval *s)
388 {
389         struct timeval t;
390
391         fio_gettime(&t, NULL);
392         return utime_since(s, &t);
393 }
394
395 uint64_t mtime_since(const struct timeval *s, const struct timeval *e)
396 {
397         long sec, usec, ret;
398
399         sec = e->tv_sec - s->tv_sec;
400         usec = e->tv_usec - s->tv_usec;
401         if (sec > 0 && usec < 0) {
402                 sec--;
403                 usec += 1000000;
404         }
405
406         if (sec < 0 || (sec == 0 && usec < 0))
407                 return 0;
408
409         sec *= 1000UL;
410         usec /= 1000UL;
411         ret = sec + usec;
412
413         return ret;
414 }
415
416 uint64_t mtime_since_now(const struct timeval *s)
417 {
418         struct timeval t;
419         void *p = __builtin_return_address(0);
420
421         fio_gettime(&t, p);
422         return mtime_since(s, &t);
423 }
424
425 uint64_t time_since_now(const struct timeval *s)
426 {
427         return mtime_since_now(s) / 1000;
428 }
429
430 #if defined(FIO_HAVE_CPU_AFFINITY) && defined(ARCH_HAVE_CPU_CLOCK)  && \
431     defined(CONFIG_SFAA)
432
433 #define CLOCK_ENTRIES   100000
434
435 struct clock_entry {
436         uint32_t seq;
437         uint32_t cpu;
438         uint64_t tsc;
439 };
440
441 struct clock_thread {
442         pthread_t thread;
443         int cpu;
444         pthread_mutex_t lock;
445         pthread_mutex_t started;
446         uint32_t *seq;
447         struct clock_entry *entries;
448 };
449
450 static inline uint32_t atomic32_inc_return(uint32_t *seq)
451 {
452         return 1 + __sync_fetch_and_add(seq, 1);
453 }
454
455 static void *clock_thread_fn(void *data)
456 {
457         struct clock_thread *t = data;
458         struct clock_entry *c;
459         os_cpu_mask_t cpu_mask;
460         uint32_t last_seq;
461         int i;
462
463         memset(&cpu_mask, 0, sizeof(cpu_mask));
464         fio_cpu_set(&cpu_mask, t->cpu);
465
466         if (fio_setaffinity(gettid(), cpu_mask) == -1) {
467                 log_err("clock setaffinity failed\n");
468                 return (void *) 1;
469         }
470
471         pthread_mutex_lock(&t->lock);
472         pthread_mutex_unlock(&t->started);
473
474         last_seq = 0;
475         c = &t->entries[0];
476         for (i = 0; i < CLOCK_ENTRIES; i++, c++) {
477                 uint32_t seq;
478                 uint64_t tsc;
479
480                 c->cpu = t->cpu;
481                 do {
482                         seq = atomic32_inc_return(t->seq);
483                         if (seq < last_seq)
484                                 break;
485                         tsc = get_cpu_clock();
486                 } while (seq != *t->seq);
487
488                 c->seq = seq;
489                 c->tsc = tsc;
490         }
491
492         log_info("cs: cpu%3d: %llu clocks seen\n", t->cpu,
493                 (unsigned long long) t->entries[i - 1].tsc - t->entries[0].tsc);
494
495         /*
496          * The most common platform clock breakage is returning zero
497          * indefinitely. Check for that and return failure.
498          */
499         if (!t->entries[i - 1].tsc && !t->entries[0].tsc)
500                 return (void *) 1;
501
502         return NULL;
503 }
504
505 static int clock_cmp(const void *p1, const void *p2)
506 {
507         const struct clock_entry *c1 = p1;
508         const struct clock_entry *c2 = p2;
509
510         if (c1->seq == c2->seq)
511                 log_err("cs: bug in atomic sequence!\n");
512
513         return c1->seq - c2->seq;
514 }
515
516 int fio_monotonic_clocktest(void)
517 {
518         struct clock_thread *cthreads;
519         unsigned int nr_cpus = cpus_online();
520         struct clock_entry *entries;
521         unsigned long tentries, failed = 0;
522         struct clock_entry *prev, *this;
523         uint32_t seq = 0;
524         unsigned int i;
525
526         log_info("cs: reliable_tsc: %s\n", tsc_reliable ? "yes" : "no");
527
528 #ifdef FIO_INC_DEBUG
529         fio_debug |= 1U << FD_TIME;
530 #endif
531         calibrate_cpu_clock();
532 #ifdef FIO_INC_DEBUG
533         fio_debug &= ~(1U << FD_TIME);
534 #endif
535
536         cthreads = malloc(nr_cpus * sizeof(struct clock_thread));
537         tentries = CLOCK_ENTRIES * nr_cpus;
538         entries = malloc(tentries * sizeof(struct clock_entry));
539
540         log_info("cs: Testing %u CPUs\n", nr_cpus);
541
542         for (i = 0; i < nr_cpus; i++) {
543                 struct clock_thread *t = &cthreads[i];
544
545                 t->cpu = i;
546                 t->seq = &seq;
547                 t->entries = &entries[i * CLOCK_ENTRIES];
548                 pthread_mutex_init(&t->lock, NULL);
549                 pthread_mutex_init(&t->started, NULL);
550                 pthread_mutex_lock(&t->lock);
551                 if (pthread_create(&t->thread, NULL, clock_thread_fn, t)) {
552                         failed++;
553                         nr_cpus = i;
554                         break;
555                 }
556         }
557
558         for (i = 0; i < nr_cpus; i++) {
559                 struct clock_thread *t = &cthreads[i];
560
561                 pthread_mutex_lock(&t->started);
562         }
563
564         for (i = 0; i < nr_cpus; i++) {
565                 struct clock_thread *t = &cthreads[i];
566
567                 pthread_mutex_unlock(&t->lock);
568         }
569
570         for (i = 0; i < nr_cpus; i++) {
571                 struct clock_thread *t = &cthreads[i];
572                 void *ret;
573
574                 pthread_join(t->thread, &ret);
575                 if (ret)
576                         failed++;
577         }
578         free(cthreads);
579
580         if (failed) {
581                 log_err("Clocksource test: %lu threads failed\n", failed);
582                 goto err;
583         }
584
585         qsort(entries, tentries, sizeof(struct clock_entry), clock_cmp);
586
587         for (failed = i = 0; i < tentries; i++) {
588                 this = &entries[i];
589
590                 if (!i) {
591                         prev = this;
592                         continue;
593                 }
594
595                 if (prev->tsc > this->tsc) {
596                         uint64_t diff = prev->tsc - this->tsc;
597
598                         log_info("cs: CPU clock mismatch (diff=%llu):\n",
599                                                 (unsigned long long) diff);
600                         log_info("\t CPU%3u: TSC=%llu, SEQ=%u\n", prev->cpu, (unsigned long long) prev->tsc, prev->seq);
601                         log_info("\t CPU%3u: TSC=%llu, SEQ=%u\n", this->cpu, (unsigned long long) this->tsc, this->seq);
602                         failed++;
603                 }
604
605                 prev = this;
606         }
607
608         if (failed)
609                 log_info("cs: Failed: %lu\n", failed);
610         else
611                 log_info("cs: Pass!\n");
612
613 err:
614         free(entries);
615         return !!failed;
616 }
617
618 #else /* defined(FIO_HAVE_CPU_AFFINITY) && defined(ARCH_HAVE_CPU_CLOCK) */
619
620 int fio_monotonic_clocktest(void)
621 {
622         log_info("cs: current platform does not support CPU clocks\n");
623         return 0;
624 }
625
626 #endif