RTC.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Assertions.h>
  7. #include <AK/Time.h>
  8. #include <Kernel/CMOS.h>
  9. #include <Kernel/RTC.h>
  10. namespace RTC {
  11. static time_t s_boot_time;
  12. void initialize()
  13. {
  14. s_boot_time = now();
  15. }
  16. time_t boot_time()
  17. {
  18. return s_boot_time;
  19. }
  20. static bool update_in_progress()
  21. {
  22. return CMOS::read(0x0a) & 0x80;
  23. }
  24. static u8 bcd_to_binary(u8 bcd)
  25. {
  26. return (bcd & 0x0F) + ((bcd >> 4) * 10);
  27. }
  28. void read_registers(unsigned& year, unsigned& month, unsigned& day, unsigned& hour, unsigned& minute, unsigned& second)
  29. {
  30. while (update_in_progress())
  31. ;
  32. u8 status_b = CMOS::read(0x0b);
  33. second = CMOS::read(0x00);
  34. minute = CMOS::read(0x02);
  35. hour = CMOS::read(0x04);
  36. day = CMOS::read(0x07);
  37. month = CMOS::read(0x08);
  38. year = CMOS::read(0x09);
  39. bool is_pm = hour & 0x80;
  40. if (!(status_b & 0x04)) {
  41. second = bcd_to_binary(second);
  42. minute = bcd_to_binary(minute);
  43. hour = bcd_to_binary(hour & 0x7F);
  44. day = bcd_to_binary(day);
  45. month = bcd_to_binary(month);
  46. year = bcd_to_binary(year);
  47. }
  48. if (!(status_b & 0x02)) {
  49. // In the 12 hour clock, midnight and noon are 12, not 0. Map it to 0.
  50. hour %= 12;
  51. if (is_pm)
  52. hour += 12;
  53. }
  54. year += 2000;
  55. }
  56. time_t now()
  57. {
  58. // FIXME: We should probably do something more robust here.
  59. // Perhaps read all the values twice and verify that they were identical.
  60. // We don't want to be caught in the middle of an RTC register update.
  61. while (update_in_progress())
  62. ;
  63. unsigned year, month, day, hour, minute, second;
  64. read_registers(year, month, day, hour, minute, second);
  65. dmesgln("RTC: Year: {}, month: {}, day: {}, hour: {}, minute: {}, second: {}", year, month, day, hour, minute, second);
  66. time_t days_since_epoch = years_to_days_since_epoch(year) + day_of_year(year, month, day);
  67. return ((days_since_epoch * 24 + hour) * 60 + minute) * 60 + second;
  68. }
  69. }