Add include-what-you-use pragmas
[fio.git] / gettime-thread.c
CommitLineData
39ab7da2
JA
1#include <sys/time.h>
2#include <time.h>
3
4#include "fio.h"
5#include "smalloc.h"
6
8b6a404c 7struct timespec *fio_ts = NULL;
39ab7da2 8int fio_gtod_offload = 0;
39ab7da2 9static pthread_t gtod_thread;
8a2b393b 10static os_cpu_mask_t fio_gtod_cpumask;
39ab7da2
JA
11
12void fio_gtod_init(void)
13{
8b6a404c 14 if (fio_ts)
79c896a1
JA
15 return;
16
8b6a404c
VF
17 fio_ts = smalloc(sizeof(*fio_ts));
18 if (!fio_ts)
fba5c5ff 19 log_err("fio: smalloc pool exhausted\n");
39ab7da2
JA
20}
21
22static void fio_gtod_update(void)
23{
8b6a404c 24 if (fio_ts) {
27325ed5
JA
25 struct timeval __tv;
26
27 gettimeofday(&__tv, NULL);
8b6a404c 28 fio_ts->tv_sec = __tv.tv_sec;
27325ed5 29 write_barrier();
8b6a404c 30 fio_ts->tv_nsec = __tv.tv_usec * 1000;
27325ed5
JA
31 write_barrier();
32 }
39ab7da2
JA
33}
34
79c896a1 35struct gtod_cpu_data {
971caeb1 36 struct fio_sem *sem;
79c896a1
JA
37 unsigned int cpu;
38};
39
39ab7da2
JA
40static void *gtod_thread_main(void *data)
41{
971caeb1 42 struct fio_sem *sem = data;
48d86be5
JA
43 int ret;
44
45 ret = fio_setaffinity(gettid(), fio_gtod_cpumask);
39ab7da2 46
971caeb1 47 fio_sem_up(sem);
39ab7da2 48
48d86be5
JA
49 if (ret == -1) {
50 log_err("gtod: setaffinity failed\n");
51 return NULL;
52 }
53
39ab7da2
JA
54 /*
55 * As long as we have jobs around, update the clock. It would be nice
56 * to have some way of NOT hammering that CPU with gettimeofday(),
57 * but I'm not sure what to use outside of a simple CPU nop to relax
58 * it - we don't want to lose precision.
59 */
60 while (threads) {
61 fio_gtod_update();
62 nop;
63 }
64
65 return NULL;
66}
67
68int fio_start_gtod_thread(void)
69{
971caeb1 70 struct fio_sem *sem;
39ab7da2
JA
71 pthread_attr_t attr;
72 int ret;
73
971caeb1
BVA
74 sem = fio_sem_init(FIO_SEM_LOCKED);
75 if (!sem)
39ab7da2
JA
76 return 1;
77
78 pthread_attr_init(&attr);
45213f1b 79 pthread_attr_setstacksize(&attr, 2 * PTHREAD_STACK_MIN);
971caeb1 80 ret = pthread_create(&gtod_thread, &attr, gtod_thread_main, sem);
39ab7da2
JA
81 pthread_attr_destroy(&attr);
82 if (ret) {
83 log_err("Can't create gtod thread: %s\n", strerror(ret));
84 goto err;
85 }
86
87 ret = pthread_detach(gtod_thread);
88 if (ret) {
bc0fe8b8 89 log_err("Can't detach gtod thread: %s\n", strerror(ret));
39ab7da2
JA
90 goto err;
91 }
92
971caeb1
BVA
93 dprint(FD_MUTEX, "wait on startup_sem\n");
94 fio_sem_down(sem);
95 dprint(FD_MUTEX, "done waiting on startup_sem\n");
39ab7da2 96err:
971caeb1 97 fio_sem_remove(sem);
39ab7da2
JA
98 return ret;
99}
100
79c896a1
JA
101void fio_gtod_set_cpu(unsigned int cpu)
102{
2a2f27b8 103#ifdef FIO_HAVE_CPU_AFFINITY
79c896a1 104 fio_cpu_set(&fio_gtod_cpumask, cpu);
2a2f27b8 105#endif
79c896a1 106}