1
2
3
4
5
6
7
8
9
10
11
12
13
14#include <linux/module.h>
15#include <linux/rtc.h>
16
17static const unsigned char rtc_days_in_month[] = {
18 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
19};
20
21static const unsigned short rtc_ydays[2][13] = {
22
23 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
24
25 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
26};
27
28#define LEAPS_THRU_END_OF(y) ((y)/4 - (y)/100 + (y)/400)
29
30
31
32
33int rtc_month_days(unsigned int month, unsigned int year)
34{
35 return rtc_days_in_month[month] + (is_leap_year(year) && month == 1);
36}
37EXPORT_SYMBOL(rtc_month_days);
38
39
40
41
42int rtc_year_days(unsigned int day, unsigned int month, unsigned int year)
43{
44 return rtc_ydays[is_leap_year(year)][month] + day-1;
45}
46EXPORT_SYMBOL(rtc_year_days);
47
48
49
50
51void rtc_time_to_tm(unsigned long time, struct rtc_time *tm)
52{
53 unsigned int month, year;
54 int days;
55
56 days = time / 86400;
57 time -= (unsigned int) days * 86400;
58
59
60 tm->tm_wday = (days + 4) % 7;
61
62 year = 1970 + days / 365;
63 days -= (year - 1970) * 365
64 + LEAPS_THRU_END_OF(year - 1)
65 - LEAPS_THRU_END_OF(1970 - 1);
66 if (days < 0) {
67 year -= 1;
68 days += 365 + is_leap_year(year);
69 }
70 tm->tm_year = year - 1900;
71 tm->tm_yday = days + 1;
72
73 for (month = 0; month < 11; month++) {
74 int newdays;
75
76 newdays = days - rtc_month_days(month, year);
77 if (newdays < 0)
78 break;
79 days = newdays;
80 }
81 tm->tm_mon = month;
82 tm->tm_mday = days + 1;
83
84 tm->tm_hour = time / 3600;
85 time -= tm->tm_hour * 3600;
86 tm->tm_min = time / 60;
87 tm->tm_sec = time - tm->tm_min * 60;
88}
89EXPORT_SYMBOL(rtc_time_to_tm);
90
91
92
93
94int rtc_valid_tm(struct rtc_time *tm)
95{
96 if (tm->tm_year < 70
97 || ((unsigned)tm->tm_mon) >= 12
98 || tm->tm_mday < 1
99 || tm->tm_mday > rtc_month_days(tm->tm_mon, tm->tm_year + 1900)
100 || ((unsigned)tm->tm_hour) >= 24
101 || ((unsigned)tm->tm_min) >= 60
102 || ((unsigned)tm->tm_sec) >= 60)
103 return -EINVAL;
104
105 return 0;
106}
107EXPORT_SYMBOL(rtc_valid_tm);
108
109
110
111
112int rtc_tm_to_time(struct rtc_time *tm, unsigned long *time)
113{
114 *time = mktime(tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
115 tm->tm_hour, tm->tm_min, tm->tm_sec);
116 return 0;
117}
118EXPORT_SYMBOL(rtc_tm_to_time);
119
120MODULE_LICENSE("GPL");
121