server: fix error handling for shared memory handling
[fio.git] / gettime-thread.c
1 #include <sys/time.h>
2 #include <time.h>
3
4 #include "fio.h"
5 #include "smalloc.h"
6
7 struct timespec *fio_ts = NULL;
8 int fio_gtod_offload = 0;
9 static pthread_t gtod_thread;
10 static os_cpu_mask_t fio_gtod_cpumask;
11
12 void fio_gtod_init(void)
13 {
14         if (fio_ts)
15                 return;
16
17         fio_ts = smalloc(sizeof(*fio_ts));
18         if (!fio_ts)
19                 log_err("fio: smalloc pool exhausted\n");
20 }
21
22 static void fio_gtod_update(void)
23 {
24         if (fio_ts) {
25                 struct timeval __tv;
26
27                 gettimeofday(&__tv, NULL);
28                 fio_ts->tv_sec = __tv.tv_sec;
29                 write_barrier();
30                 fio_ts->tv_nsec = __tv.tv_usec * 1000;
31                 write_barrier();
32         }
33 }
34
35 struct gtod_cpu_data {
36         struct fio_sem *sem;
37         unsigned int cpu;
38 };
39
40 static void *gtod_thread_main(void *data)
41 {
42         struct fio_sem *sem = data;
43         int ret;
44
45         ret = fio_setaffinity(gettid(), fio_gtod_cpumask);
46
47         fio_sem_up(sem);
48
49         if (ret == -1) {
50                 log_err("gtod: setaffinity failed\n");
51                 return NULL;
52         }
53
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
68 int fio_start_gtod_thread(void)
69 {
70         struct fio_sem *sem;
71         pthread_attr_t attr;
72         int ret;
73
74         sem = fio_sem_init(FIO_SEM_LOCKED);
75         if (!sem)
76                 return 1;
77
78         pthread_attr_init(&attr);
79         pthread_attr_setstacksize(&attr, 2 * PTHREAD_STACK_MIN);
80         ret = pthread_create(&gtod_thread, &attr, gtod_thread_main, sem);
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) {
89                 log_err("Can't detach gtod thread: %s\n", strerror(ret));
90                 goto err;
91         }
92
93         dprint(FD_MUTEX, "wait on startup_sem\n");
94         fio_sem_down(sem);
95         dprint(FD_MUTEX, "done waiting on startup_sem\n");
96 err:
97         fio_sem_remove(sem);
98         return ret;
99 }
100
101 void fio_gtod_set_cpu(unsigned int cpu)
102 {
103 #ifdef FIO_HAVE_CPU_AFFINITY
104         fio_cpu_set(&fio_gtod_cpumask, cpu);
105 #endif
106 }