rtc-lib.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * rtc and date/time utility functions
  4. *
  5. * Copyright (C) 2005-06 Tower Technologies
  6. * Author: Alessandro Zummo <a.zummo@towertech.it>
  7. *
  8. * U-Boot rtc_time differs from Linux rtc_time:
  9. * - The year field takes the actual value, not year - 1900.
  10. * - January is month 1.
  11. */
  12. #include <common.h>
  13. #include <rtc.h>
  14. #include <linux/math64.h>
  15. static const unsigned char rtc_days_in_month[] = {
  16. 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
  17. };
  18. #define LEAPS_THRU_END_OF(y) ((y) / 4 - (y) / 100 + (y) / 400)
  19. /*
  20. * The number of days in the month.
  21. */
  22. int rtc_month_days(unsigned int month, unsigned int year)
  23. {
  24. return rtc_days_in_month[month] + (is_leap_year(year) && month == 1);
  25. }
  26. /*
  27. * rtc_to_tm - Converts u64 to rtc_time.
  28. * Convert seconds since 01-01-1970 00:00:00 to Gregorian date.
  29. *
  30. * This function is copied from rtc_time64_to_tm() in the Linux kernel.
  31. * But in U-Boot January is month 1 and we do not subtract 1900 from the year.
  32. */
  33. void rtc_to_tm(u64 time, struct rtc_time *tm)
  34. {
  35. unsigned int month, year, secs;
  36. int days;
  37. days = div_u64_rem(time, 86400, &secs);
  38. /* day of the week, 1970-01-01 was a Thursday */
  39. tm->tm_wday = (days + 4) % 7;
  40. year = 1970 + days / 365;
  41. days -= (year - 1970) * 365
  42. + LEAPS_THRU_END_OF(year - 1)
  43. - LEAPS_THRU_END_OF(1970 - 1);
  44. while (days < 0) {
  45. year -= 1;
  46. days += 365 + is_leap_year(year);
  47. }
  48. tm->tm_year = year; /* Not year - 1900 */
  49. tm->tm_yday = days + 1;
  50. for (month = 0; month < 11; month++) {
  51. int newdays;
  52. newdays = days - rtc_month_days(month, year);
  53. if (newdays < 0)
  54. break;
  55. days = newdays;
  56. }
  57. tm->tm_mon = month + 1; /* January = 1 */
  58. tm->tm_mday = days + 1;
  59. tm->tm_hour = secs / 3600;
  60. secs -= tm->tm_hour * 3600;
  61. tm->tm_min = secs / 60;
  62. tm->tm_sec = secs - tm->tm_min * 60;
  63. /* Zero unused fields */
  64. tm->tm_isdst = 0;
  65. }