1 // SPDX-License-Identifier: GPL-2.0 2 #define _GNU_SOURCE 3 #include <sched.h> 4 5 #include <sys/timerfd.h> 6 #include <sys/syscall.h> 7 #include <sys/types.h> 8 #include <sys/wait.h> 9 #include <time.h> 10 #include <unistd.h> 11 #include <stdlib.h> 12 #include <stdio.h> 13 #include <stdint.h> 14 15 #include "log.h" 16 #include "timens.h" 17 18 static int tclock_gettime(clock_t clockid, struct timespec *now) 19 { 20 if (clockid == CLOCK_BOOTTIME_ALARM) 21 clockid = CLOCK_BOOTTIME; 22 return clock_gettime(clockid, now); 23 } 24 25 int run_test(int clockid, struct timespec now) 26 { 27 struct itimerspec new_value; 28 long long elapsed; 29 int fd, i; 30 31 if (tclock_gettime(clockid, &now)) 32 return pr_perror("clock_gettime(%d)", clockid); 33 34 for (i = 0; i < 2; i++) { 35 int flags = 0; 36 37 new_value.it_value.tv_sec = 3600; 38 new_value.it_value.tv_nsec = 0; 39 new_value.it_interval.tv_sec = 1; 40 new_value.it_interval.tv_nsec = 0; 41 42 if (i == 1) { 43 new_value.it_value.tv_sec += now.tv_sec; 44 new_value.it_value.tv_nsec += now.tv_nsec; 45 } 46 47 fd = timerfd_create(clockid, 0); 48 if (fd == -1) 49 return pr_perror("timerfd_create(%d)", clockid); 50 51 if (i == 1) 52 flags |= TFD_TIMER_ABSTIME; 53 54 if (timerfd_settime(fd, flags, &new_value, NULL)) 55 return pr_perror("timerfd_settime(%d)", clockid); 56 57 if (timerfd_gettime(fd, &new_value)) 58 return pr_perror("timerfd_gettime(%d)", clockid); 59 60 elapsed = new_value.it_value.tv_sec; 61 if (abs(elapsed - 3600) > 60) { 62 ksft_test_result_fail("clockid: %d elapsed: %lld\n", 63 clockid, elapsed); 64 return 1; 65 } 66 67 close(fd); 68 } 69 70 ksft_test_result_pass("clockid=%d\n", clockid); 71 72 return 0; 73 } 74 75 int main(int argc, char *argv[]) 76 { 77 int ret, status, len, fd; 78 char buf[4096]; 79 pid_t pid; 80 struct timespec btime_now, mtime_now; 81 82 nscheck(); 83 84 ksft_set_plan(3); 85 86 clock_gettime(CLOCK_MONOTONIC, &mtime_now); 87 clock_gettime(CLOCK_BOOTTIME, &btime_now); 88 89 if (unshare_timens()) 90 return 1; 91 92 len = snprintf(buf, sizeof(buf), "%d %d 0\n%d %d 0", 93 CLOCK_MONOTONIC, 70 * 24 * 3600, 94 CLOCK_BOOTTIME, 9 * 24 * 3600); 95 fd = open("/proc/self/timens_offsets", O_WRONLY); 96 if (fd < 0) 97 return pr_perror("/proc/self/timens_offsets"); 98 99 if (write(fd, buf, len) != len) 100 return pr_perror("/proc/self/timens_offsets"); 101 102 close(fd); 103 mtime_now.tv_sec += 70 * 24 * 3600; 104 btime_now.tv_sec += 9 * 24 * 3600; 105 106 pid = fork(); 107 if (pid < 0) 108 return pr_perror("Unable to fork"); 109 if (pid == 0) { 110 ret = 0; 111 ret |= run_test(CLOCK_BOOTTIME, btime_now); 112 ret |= run_test(CLOCK_MONOTONIC, mtime_now); 113 ret |= run_test(CLOCK_BOOTTIME_ALARM, btime_now); 114 115 if (ret) 116 ksft_exit_fail(); 117 ksft_exit_pass(); 118 return ret; 119 } 120 121 if (waitpid(pid, &status, 0) != pid) 122 return pr_perror("Unable to wait the child process"); 123 124 if (WIFEXITED(status)) 125 return WEXITSTATUS(status); 126 127 return 1; 128 } 129