proc-uptime-002.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. #undef NDEBUG
  19. #include <assert.h>
  20. #include <unistd.h>
  21. #include <sys/syscall.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <stdint.h>
  25. #include <sys/types.h>
  26. #include <sys/stat.h>
  27. #include <fcntl.h>
  28. #include "proc-uptime.h"
  29. static inline int sys_sched_getaffinity(pid_t pid, unsigned int len, unsigned long *m)
  30. {
  31. return syscall(SYS_sched_getaffinity, pid, len, m);
  32. }
  33. static inline int sys_sched_setaffinity(pid_t pid, unsigned int len, unsigned long *m)
  34. {
  35. return syscall(SYS_sched_setaffinity, pid, len, m);
  36. }
  37. int main(void)
  38. {
  39. unsigned int len;
  40. unsigned long *m;
  41. unsigned int cpu;
  42. uint64_t u0, u1, i0, i1;
  43. int fd;
  44. /* find out "nr_cpu_ids" */
  45. m = NULL;
  46. len = 0;
  47. do {
  48. len += sizeof(unsigned long);
  49. free(m);
  50. m = malloc(len);
  51. } while (sys_sched_getaffinity(0, len, m) == -EINVAL);
  52. fd = open("/proc/uptime", O_RDONLY);
  53. assert(fd >= 0);
  54. proc_uptime(fd, &u0, &i0);
  55. for (cpu = 0; cpu < len * 8; cpu++) {
  56. memset(m, 0, len);
  57. m[cpu / (8 * sizeof(unsigned long))] |= 1UL << (cpu % (8 * sizeof(unsigned long)));
  58. /* CPU might not exist, ignore error */
  59. sys_sched_setaffinity(0, len, m);
  60. proc_uptime(fd, &u1, &i1);
  61. assert(u1 >= u0);
  62. assert(i1 >= i0);
  63. u0 = u1;
  64. i0 = i1;
  65. }
  66. return 0;
  67. }