disable-tsc-on-off-stress-test.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Tests for prctl(PR_GET_TSC, ...) / prctl(PR_SET_TSC, ...)
  3. *
  4. * Tests if the control register is updated correctly
  5. * when set with prctl()
  6. *
  7. * Warning: this test will cause a very high load for a few seconds
  8. *
  9. */
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <unistd.h>
  13. #include <signal.h>
  14. #include <inttypes.h>
  15. #include <wait.h>
  16. #include <sys/prctl.h>
  17. #include <linux/prctl.h>
  18. /* Get/set the process' ability to use the timestamp counter instruction */
  19. #ifndef PR_GET_TSC
  20. #define PR_GET_TSC 25
  21. #define PR_SET_TSC 26
  22. # define PR_TSC_ENABLE 1 /* allow the use of the timestamp counter */
  23. # define PR_TSC_SIGSEGV 2 /* throw a SIGSEGV instead of reading the TSC */
  24. #endif
  25. /* snippet from wikipedia :-) */
  26. static uint64_t rdtsc(void)
  27. {
  28. uint32_t lo, hi;
  29. /* We cannot use "=A", since this would use %rax on x86_64 */
  30. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  31. return (uint64_t)hi << 32 | lo;
  32. }
  33. int should_segv = 0;
  34. static void sigsegv_cb(int sig)
  35. {
  36. if (!should_segv)
  37. {
  38. fprintf(stderr, "FATAL ERROR, rdtsc() failed while enabled\n");
  39. exit(0);
  40. }
  41. if (prctl(PR_SET_TSC, PR_TSC_ENABLE) < 0)
  42. {
  43. perror("prctl");
  44. exit(0);
  45. }
  46. should_segv = 0;
  47. rdtsc();
  48. }
  49. static void task(void)
  50. {
  51. signal(SIGSEGV, sigsegv_cb);
  52. alarm(10);
  53. for(;;)
  54. {
  55. rdtsc();
  56. if (should_segv)
  57. {
  58. fprintf(stderr, "FATAL ERROR, rdtsc() succeeded while disabled\n");
  59. exit(0);
  60. }
  61. if (prctl(PR_SET_TSC, PR_TSC_SIGSEGV) < 0)
  62. {
  63. perror("prctl");
  64. exit(0);
  65. }
  66. should_segv = 1;
  67. }
  68. }
  69. int main(int argc, char **argv)
  70. {
  71. int n_tasks = 100, i;
  72. fprintf(stderr, "[No further output means we're allright]\n");
  73. for (i=0; i<n_tasks; i++)
  74. if (fork() == 0)
  75. task();
  76. for (i=0; i<n_tasks; i++)
  77. wait(NULL);
  78. exit(0);
  79. }