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