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