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