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. uint64_t rdtsc() {
  27. uint32_t lo, hi;
  28. /* We cannot use "=A", since this would use %rax on x86_64 */
  29. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  30. return (uint64_t)hi << 32 | lo;
  31. }
  32. int should_segv = 0;
  33. void sigsegv_cb(int sig)
  34. {
  35. if (!should_segv)
  36. {
  37. fprintf(stderr, "FATAL ERROR, rdtsc() failed while enabled\n");
  38. exit(0);
  39. }
  40. if (prctl(PR_SET_TSC, PR_TSC_ENABLE) < 0)
  41. {
  42. perror("prctl");
  43. exit(0);
  44. }
  45. should_segv = 0;
  46. rdtsc();
  47. }
  48. void task(void)
  49. {
  50. signal(SIGSEGV, sigsegv_cb);
  51. alarm(10);
  52. for(;;)
  53. {
  54. rdtsc();
  55. if (should_segv)
  56. {
  57. fprintf(stderr, "FATAL ERROR, rdtsc() succeeded while disabled\n");
  58. exit(0);
  59. }
  60. if (prctl(PR_SET_TSC, PR_TSC_SIGSEGV) < 0)
  61. {
  62. perror("prctl");
  63. exit(0);
  64. }
  65. should_segv = 1;
  66. }
  67. }
  68. int main(int argc, char **argv)
  69. {
  70. int n_tasks = 100, i;
  71. fprintf(stderr, "[No further output means we're allright]\n");
  72. for (i=0; i<n_tasks; i++)
  73. if (fork() == 0)
  74. task();
  75. for (i=0; i<n_tasks; i++)
  76. wait(NULL);
  77. exit(0);
  78. }