proc-uptime-002.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * Copyright © 2018 Alexey Dobriyan <adobriyan@gmail.com>
  3. *
  4. * Permission to use, copy, modify, and distribute this software for any
  5. * purpose with or without fee is hereby granted, provided that the above
  6. * copyright notice and this permission notice appear in all copies.
  7. *
  8. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. */
  16. // Test that values in /proc/uptime increment monotonically
  17. // while shifting across CPUs.
  18. #define _GNU_SOURCE
  19. #undef NDEBUG
  20. #include <assert.h>
  21. #include <unistd.h>
  22. #include <sys/syscall.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <stdint.h>
  26. #include <sys/types.h>
  27. #include <sys/stat.h>
  28. #include <fcntl.h>
  29. #include "proc-uptime.h"
  30. static inline int sys_sched_getaffinity(pid_t pid, unsigned int len, unsigned long *m)
  31. {
  32. return syscall(SYS_sched_getaffinity, pid, len, m);
  33. }
  34. static inline int sys_sched_setaffinity(pid_t pid, unsigned int len, unsigned long *m)
  35. {
  36. return syscall(SYS_sched_setaffinity, pid, len, m);
  37. }
  38. int main(void)
  39. {
  40. unsigned int len;
  41. unsigned long *m;
  42. unsigned int cpu;
  43. uint64_t u0, u1, i0, i1;
  44. int fd;
  45. /* find out "nr_cpu_ids" */
  46. m = NULL;
  47. len = 0;
  48. do {
  49. len += sizeof(unsigned long);
  50. free(m);
  51. m = malloc(len);
  52. } while (sys_sched_getaffinity(0, len, m) == -EINVAL);
  53. fd = open("/proc/uptime", O_RDONLY);
  54. assert(fd >= 0);
  55. proc_uptime(fd, &u0, &i0);
  56. for (cpu = 0; cpu < len * 8; cpu++) {
  57. memset(m, 0, len);
  58. m[cpu / (8 * sizeof(unsigned long))] |= 1UL << (cpu % (8 * sizeof(unsigned long)));
  59. /* CPU might not exist, ignore error */
  60. sys_sched_setaffinity(0, len, m);
  61. proc_uptime(fd, &u1, &i1);
  62. assert(u1 >= u0);
  63. assert(i1 >= i0);
  64. u0 = u1;
  65. i0 = i1;
  66. }
  67. return 0;
  68. }