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