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