tsc.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* kern/i386/tsc.c - x86 TSC time source implementation
  2. * Requires Pentium or better x86 CPU that supports the RDTSC instruction.
  3. * This module uses the RTC (via grub_get_rtc()) to calibrate the TSC to
  4. * real time.
  5. *
  6. * GRUB -- GRand Unified Bootloader
  7. * Copyright (C) 2008 Free Software Foundation, Inc.
  8. *
  9. * GRUB is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation, either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * GRUB is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with GRUB. If not, see <http://www.gnu.org/licenses/>.
  21. */
  22. #include <grub/types.h>
  23. #include <grub/time.h>
  24. #include <grub/misc.h>
  25. #include <grub/i386/tsc.h>
  26. #include <grub/i386/pit.h>
  27. /* This defines the value TSC had at the epoch (that is, when we calibrated it). */
  28. static grub_uint64_t tsc_boot_time;
  29. /* Calibrated TSC rate. (In TSC ticks per millisecond.) */
  30. static grub_uint64_t tsc_ticks_per_ms;
  31. grub_uint64_t
  32. grub_tsc_get_time_ms (void)
  33. {
  34. return tsc_boot_time + grub_divmod64 (grub_get_tsc (), tsc_ticks_per_ms, 0);
  35. }
  36. /* How many RTC ticks to use for calibration loop. (>= 1) */
  37. #define CALIBRATION_TICKS 2
  38. /* Calibrate the TSC based on the RTC. */
  39. static void
  40. calibrate_tsc (void)
  41. {
  42. /* First calibrate the TSC rate (relative, not absolute time). */
  43. grub_uint64_t start_tsc;
  44. grub_uint64_t end_tsc;
  45. start_tsc = grub_get_tsc ();
  46. grub_pit_wait (0xffff);
  47. end_tsc = grub_get_tsc ();
  48. tsc_ticks_per_ms = grub_divmod64 (end_tsc - start_tsc, 55, 0);
  49. }
  50. void
  51. grub_tsc_init (void)
  52. {
  53. if (grub_cpu_is_tsc_supported ())
  54. {
  55. tsc_boot_time = grub_get_tsc ();
  56. calibrate_tsc ();
  57. grub_install_get_time_ms (grub_tsc_get_time_ms);
  58. }
  59. else
  60. {
  61. grub_install_get_time_ms (grub_rtc_get_time_ms);
  62. }
  63. }