Heinrich Schuchardt | 992c1db | 2018-07-07 23:39:11 +0200 | [diff] [blame] | 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 | |
| 13 | #include <common.h> |
| 14 | #include <rtc.h> |
| 15 | #include <linux/math64.h> |
| 16 | |
| 17 | static const unsigned char rtc_days_in_month[] = { |
| 18 | 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 |
| 19 | }; |
| 20 | |
| 21 | #define LEAPS_THRU_END_OF(y) ((y) / 4 - (y) / 100 + (y) / 400) |
| 22 | |
| 23 | /* |
| 24 | * The number of days in the month. |
| 25 | */ |
Heinrich Schuchardt | 3c1889e | 2019-05-31 07:21:03 +0200 | [diff] [blame] | 26 | int rtc_month_days(unsigned int month, unsigned int year) |
Heinrich Schuchardt | 992c1db | 2018-07-07 23:39:11 +0200 | [diff] [blame] | 27 | { |
| 28 | return rtc_days_in_month[month] + (is_leap_year(year) && month == 1); |
| 29 | } |
| 30 | |
| 31 | /* |
| 32 | * rtc_to_tm - Converts u64 to rtc_time. |
| 33 | * Convert seconds since 01-01-1970 00:00:00 to Gregorian date. |
Heinrich Schuchardt | 9520613 | 2018-12-01 23:14:10 +0100 | [diff] [blame] | 34 | * |
| 35 | * This function is copied from rtc_time64_to_tm() in the Linux kernel. |
| 36 | * But in U-Boot January is month 1 and we do not subtract 1900 from the year. |
Heinrich Schuchardt | 992c1db | 2018-07-07 23:39:11 +0200 | [diff] [blame] | 37 | */ |
| 38 | void rtc_to_tm(u64 time, struct rtc_time *tm) |
| 39 | { |
Heinrich Schuchardt | 9520613 | 2018-12-01 23:14:10 +0100 | [diff] [blame] | 40 | unsigned int month, year, secs; |
| 41 | int days; |
Heinrich Schuchardt | 992c1db | 2018-07-07 23:39:11 +0200 | [diff] [blame] | 42 | |
| 43 | days = div_u64_rem(time, 86400, &secs); |
| 44 | |
| 45 | /* day of the week, 1970-01-01 was a Thursday */ |
| 46 | tm->tm_wday = (days + 4) % 7; |
| 47 | |
| 48 | year = 1970 + days / 365; |
| 49 | days -= (year - 1970) * 365 |
| 50 | + LEAPS_THRU_END_OF(year - 1) |
| 51 | - LEAPS_THRU_END_OF(1970 - 1); |
| 52 | while (days < 0) { |
| 53 | year -= 1; |
| 54 | days += 365 + is_leap_year(year); |
| 55 | } |
| 56 | tm->tm_year = year; /* Not year - 1900 */ |
| 57 | tm->tm_yday = days + 1; |
| 58 | |
| 59 | for (month = 0; month < 11; month++) { |
| 60 | int newdays; |
| 61 | |
| 62 | newdays = days - rtc_month_days(month, year); |
| 63 | if (newdays < 0) |
| 64 | break; |
| 65 | days = newdays; |
| 66 | } |
| 67 | tm->tm_mon = month + 1; /* January = 1 */ |
| 68 | tm->tm_mday = days + 1; |
| 69 | |
| 70 | tm->tm_hour = secs / 3600; |
| 71 | secs -= tm->tm_hour * 3600; |
| 72 | tm->tm_min = secs / 60; |
| 73 | tm->tm_sec = secs - tm->tm_min * 60; |
| 74 | |
| 75 | /* Zero unused fields */ |
| 76 | tm->tm_isdst = 0; |
| 77 | } |