timens.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. #ifndef __TIMENS_H__
  3. #define __TIMENS_H__
  4. #include <fcntl.h>
  5. #include <unistd.h>
  6. #include <stdlib.h>
  7. #include <stdbool.h>
  8. #include "../kselftest.h"
  9. #ifndef CLONE_NEWTIME
  10. # define CLONE_NEWTIME 0x00000080
  11. #endif
  12. static int config_posix_timers = true;
  13. static int config_alarm_timers = true;
  14. static inline void check_supported_timers(void)
  15. {
  16. struct timespec ts;
  17. if (timer_create(-1, 0, 0) == -1 && errno == ENOSYS)
  18. config_posix_timers = false;
  19. if (clock_gettime(CLOCK_BOOTTIME_ALARM, &ts) == -1 && errno == EINVAL)
  20. config_alarm_timers = false;
  21. }
  22. static inline bool check_skip(int clockid)
  23. {
  24. if (!config_alarm_timers && clockid == CLOCK_BOOTTIME_ALARM) {
  25. ksft_test_result_skip("CLOCK_BOOTTIME_ALARM isn't supported\n");
  26. return true;
  27. }
  28. if (config_posix_timers)
  29. return false;
  30. switch (clockid) {
  31. /* Only these clocks are supported without CONFIG_POSIX_TIMERS. */
  32. case CLOCK_BOOTTIME:
  33. case CLOCK_MONOTONIC:
  34. case CLOCK_REALTIME:
  35. return false;
  36. default:
  37. ksft_test_result_skip("Posix Clocks & timers are not supported\n");
  38. return true;
  39. }
  40. return false;
  41. }
  42. static inline int unshare_timens(void)
  43. {
  44. if (unshare(CLONE_NEWTIME)) {
  45. if (errno == EPERM)
  46. ksft_exit_skip("need to run as root\n");
  47. return pr_perror("Can't unshare() timens");
  48. }
  49. return 0;
  50. }
  51. static inline int _settime(clockid_t clk_id, time_t offset)
  52. {
  53. int fd, len;
  54. char buf[4096];
  55. if (clk_id == CLOCK_MONOTONIC_COARSE || clk_id == CLOCK_MONOTONIC_RAW)
  56. clk_id = CLOCK_MONOTONIC;
  57. len = snprintf(buf, sizeof(buf), "%d %ld 0", clk_id, offset);
  58. fd = open("/proc/self/timens_offsets", O_WRONLY);
  59. if (fd < 0)
  60. return pr_perror("/proc/self/timens_offsets");
  61. if (write(fd, buf, len) != len)
  62. return pr_perror("/proc/self/timens_offsets");
  63. close(fd);
  64. return 0;
  65. }
  66. static inline int _gettime(clockid_t clk_id, struct timespec *res, bool raw_syscall)
  67. {
  68. int err;
  69. if (!raw_syscall) {
  70. if (clock_gettime(clk_id, res)) {
  71. pr_perror("clock_gettime(%d)", (int)clk_id);
  72. return -1;
  73. }
  74. return 0;
  75. }
  76. err = syscall(SYS_clock_gettime, clk_id, res);
  77. if (err)
  78. pr_perror("syscall(SYS_clock_gettime(%d))", (int)clk_id);
  79. return err;
  80. }
  81. static inline void nscheck(void)
  82. {
  83. if (access("/proc/self/ns/time", F_OK) < 0)
  84. ksft_exit_skip("Time namespaces are not supported\n");
  85. }
  86. #endif