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