1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (C) 2002 Andi Kleen
4 * Copyright (C) 2017 Cyril Hrubis <chrubis@suse.cz>
5 */
6
7 /*
8 * DESCRIPTION
9 * Check if gettimeofday is monotonous
10 *
11 * ALGORITHM
12 * Call gettimeofday() to get a t1 (fist value)
13 * call it again to get t2, see if t2 < t1, set t2 = t1, repeat for 10 sec
14 */
15
16 #include <stdint.h>
17 #include <sys/time.h>
18 #include <stdlib.h>
19 #include <sys/syscall.h>
20 #include <unistd.h>
21 #include <time.h>
22 #include <errno.h>
23
24 #include "tst_test.h"
25
26 #define gettimeofday(a,b) syscall(__NR_gettimeofday,a,b)
27
28 static volatile sig_atomic_t done;
29 static char *str_rtime;
30 static int rtime = 10;
31
32 static struct tst_option options[] = {
33 {"T:", &str_rtime, "-T len Test iteration runtime in seconds"},
34 {NULL, NULL, NULL},
35 };
36
breakout(int sig)37 static void breakout(int sig)
38 {
39 done = sig;
40 }
41
verify_gettimeofday(void)42 static void verify_gettimeofday(void)
43 {
44 struct timeval tv1, tv2;
45 unsigned long long cnt = 0;
46
47 done = 0;
48
49 alarm(rtime);
50
51 if (gettimeofday(&tv1, NULL)) {
52 tst_res(TBROK | TERRNO, "gettimeofday() failed");
53 return;
54 }
55
56 while (!done) {
57 if (gettimeofday(&tv2, NULL)) {
58 tst_res(TBROK | TERRNO, "gettimeofday() failed");
59 return;
60 }
61
62 if (tv2.tv_sec < tv1.tv_sec ||
63 (tv2.tv_sec == tv1.tv_sec && tv2.tv_usec < tv1.tv_usec)) {
64 tst_res(TFAIL,
65 "Time is going backwards: old %jd.%jd vs new %jd.%jd!",
66 (intmax_t) tv1.tv_sec, (intmax_t) tv1.tv_usec,
67 (intmax_t) tv2.tv_sec, (intmax_t) tv2.tv_usec);
68 return;
69 }
70
71 tv1 = tv2;
72 cnt++;
73 }
74
75
76 tst_res(TINFO, "gettimeofday() called %llu times", cnt);
77 tst_res(TPASS, "gettimeofday() monotonous in %i seconds", rtime);
78 }
79
setup(void)80 static void setup(void)
81 {
82 if (str_rtime) {
83 rtime = atoi(str_rtime);
84 if (rtime <= 0)
85 tst_brk(TBROK, "Invalid runtime '%s'", str_rtime);
86 tst_set_timeout(rtime + 60);
87 }
88
89 SAFE_SIGNAL(SIGALRM, breakout);
90 }
91
92 static struct tst_test test = {
93 .setup = setup,
94 .options = options,
95 .test_all = verify_gettimeofday,
96 };
97