tsc_pit.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 PIT 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. #include <grub/cpu/io.h>
  28. static int
  29. grub_pit_wait (void)
  30. {
  31. int ret = 0;
  32. /* Disable timer2 gate and speaker. */
  33. grub_outb (grub_inb (GRUB_PIT_SPEAKER_PORT)
  34. & ~ (GRUB_PIT_SPK_DATA | GRUB_PIT_SPK_TMR2),
  35. GRUB_PIT_SPEAKER_PORT);
  36. /* Set tics. */
  37. grub_outb (GRUB_PIT_CTRL_SELECT_2 | GRUB_PIT_CTRL_READLOAD_WORD,
  38. GRUB_PIT_CTRL);
  39. /* 0xffff ticks: 55ms. */
  40. grub_outb (0xff, GRUB_PIT_COUNTER_2);
  41. grub_outb (0xff, GRUB_PIT_COUNTER_2);
  42. /* Enable timer2 gate, keep speaker disabled. */
  43. grub_outb ((grub_inb (GRUB_PIT_SPEAKER_PORT) & ~ GRUB_PIT_SPK_DATA)
  44. | GRUB_PIT_SPK_TMR2,
  45. GRUB_PIT_SPEAKER_PORT);
  46. if ((grub_inb (GRUB_PIT_SPEAKER_PORT) & GRUB_PIT_SPK_TMR2_LATCH) == 0x00) {
  47. ret = 1;
  48. /* Wait. */
  49. while ((grub_inb (GRUB_PIT_SPEAKER_PORT) & GRUB_PIT_SPK_TMR2_LATCH) == 0x00);
  50. }
  51. /* Disable timer2 gate and speaker. */
  52. grub_outb (grub_inb (GRUB_PIT_SPEAKER_PORT)
  53. & ~ (GRUB_PIT_SPK_DATA | GRUB_PIT_SPK_TMR2),
  54. GRUB_PIT_SPEAKER_PORT);
  55. return ret;
  56. }
  57. /* Calibrate the TSC based on the RTC. */
  58. int
  59. grub_tsc_calibrate_from_pit (void)
  60. {
  61. /* First calibrate the TSC rate (relative, not absolute time). */
  62. grub_uint64_t start_tsc, end_tsc;
  63. start_tsc = grub_get_tsc ();
  64. if (!grub_pit_wait ())
  65. return 0;
  66. end_tsc = grub_get_tsc ();
  67. grub_tsc_rate = 0;
  68. if (end_tsc > start_tsc)
  69. grub_tsc_rate = grub_divmod64 ((55ULL << 32), end_tsc - start_tsc, 0);
  70. if (grub_tsc_rate == 0)
  71. return 0;
  72. return 1;
  73. }