powerpccpuinfo.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include <time.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <sys/time.h>
  5. #include <sys/types.h>
  6. #include "osfreq.c"
  7. static long myround(double u)
  8. {
  9. long result = u;
  10. while (result + 0.5 < u) result += 1;
  11. while (result - 0.5 > u) result -= 1;
  12. return result;
  13. }
  14. static long long microseconds(void)
  15. {
  16. struct timeval t;
  17. gettimeofday(&t,(struct timezone *) 0);
  18. return t.tv_sec * (long long) 1000000 + t.tv_usec;
  19. }
  20. static int tbshift = 0;
  21. static long long timebase(void)
  22. {
  23. unsigned long high;
  24. unsigned long low;
  25. unsigned long newhigh;
  26. unsigned long long result;
  27. asm volatile(
  28. "7:mftbu %0;mftb %1;mftbu %2;cmpw %0,%2;bne 7b"
  29. : "=r" (high), "=r" (low), "=r" (newhigh)
  30. );
  31. result = high;
  32. result <<= 32;
  33. result |= low;
  34. return result >> tbshift;
  35. }
  36. static double cpufrequency = 0;
  37. static long tbcycles = 0;
  38. static double guesstbcycles(void)
  39. {
  40. long long tb0; long long us0;
  41. long long tb1; long long us1;
  42. tb0 = timebase();
  43. us0 = microseconds();
  44. do {
  45. tb1 = timebase();
  46. us1 = microseconds();
  47. } while (us1 - us0 < 10000 || tb1 - tb0 < 1000);
  48. if (tb1 <= tb0) return 0;
  49. tb1 -= tb0;
  50. us1 -= us0;
  51. return (cpufrequency * 0.000001 * (double) us1) / (double) tb1;
  52. }
  53. static void init(void)
  54. {
  55. int loop;
  56. double guess1;
  57. double guess2;
  58. cpufrequency = osfreq();
  59. if (!cpufrequency) return;
  60. for (tbshift = 0;tbshift < 10;++tbshift) {
  61. for (loop = 0;loop < 100;++loop) {
  62. guess1 = guesstbcycles();
  63. guess2 = guesstbcycles();
  64. tbcycles = myround(guess1);
  65. if (guess1 - tbcycles > 0.1) continue;
  66. if (tbcycles - guess1 > 0.1) continue;
  67. if (guess2 - tbcycles > 0.1) continue;
  68. if (tbcycles - guess2 > 0.1) continue;
  69. return;
  70. }
  71. }
  72. tbcycles = 0;
  73. }
  74. long long cpucycles_powerpccpuinfo(void)
  75. {
  76. if (!tbcycles) init();
  77. return timebase() * tbcycles;
  78. }
  79. long long cpucycles_powerpccpuinfo_persecond(void)
  80. {
  81. if (!tbcycles) init();
  82. return cpufrequency;
  83. }