1#include <unistd.h>
2#include <math.h>
3#include <sys/time.h>
4#include <time.h>
5
6#include "fio.h"
7#include "smalloc.h"
8
9struct timeval *fio_tv = NULL;
10int fio_gtod_offload = 0;
11int fio_gtod_cpu = -1;
12static pthread_t gtod_thread;
13
14void fio_gtod_init(void)
15{
16	fio_tv = smalloc(sizeof(struct timeval));
17	if (!fio_tv)
18		log_err("fio: smalloc pool exhausted\n");
19}
20
21static void fio_gtod_update(void)
22{
23	if (fio_tv)
24		gettimeofday(fio_tv, NULL);
25}
26
27static void *gtod_thread_main(void *data)
28{
29	struct fio_mutex *mutex = data;
30
31	fio_mutex_up(mutex);
32
33	/*
34	 * As long as we have jobs around, update the clock. It would be nice
35	 * to have some way of NOT hammering that CPU with gettimeofday(),
36	 * but I'm not sure what to use outside of a simple CPU nop to relax
37	 * it - we don't want to lose precision.
38	 */
39	while (threads) {
40		fio_gtod_update();
41		nop;
42	}
43
44	return NULL;
45}
46
47int fio_start_gtod_thread(void)
48{
49	struct fio_mutex *mutex;
50	pthread_attr_t attr;
51	int ret;
52
53	mutex = fio_mutex_init(FIO_MUTEX_LOCKED);
54	if (!mutex)
55		return 1;
56
57	pthread_attr_init(&attr);
58	pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN);
59	ret = pthread_create(&gtod_thread, &attr, gtod_thread_main, NULL);
60	pthread_attr_destroy(&attr);
61	if (ret) {
62		log_err("Can't create gtod thread: %s\n", strerror(ret));
63		goto err;
64	}
65
66	ret = pthread_detach(gtod_thread);
67	if (ret) {
68		log_err("Can't detatch gtod thread: %s\n", strerror(ret));
69		goto err;
70	}
71
72	dprint(FD_MUTEX, "wait on startup_mutex\n");
73	fio_mutex_down(mutex);
74	dprint(FD_MUTEX, "done waiting on startup_mutex\n");
75err:
76	fio_mutex_remove(mutex);
77	return ret;
78}
79
80
81