1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30#include <linux/time.h>
31#include <linux/module.h>
32
33
34
35
36
37static int __isleap(long year)
38{
39 return (year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0);
40}
41
42
43static long math_div(long a, long b)
44{
45 return a / b - (a % b < 0);
46}
47
48
49static long leaps_between(long y1, long y2)
50{
51 long leaps1 = math_div(y1 - 1, 4) - math_div(y1 - 1, 100)
52 + math_div(y1 - 1, 400);
53 long leaps2 = math_div(y2 - 1, 4) - math_div(y2 - 1, 100)
54 + math_div(y2 - 1, 400);
55 return leaps2 - leaps1;
56}
57
58
59static const unsigned short __mon_yday[2][13] = {
60
61 {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365},
62
63 {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}
64};
65
66#define SECS_PER_HOUR (60 * 60)
67#define SECS_PER_DAY (SECS_PER_HOUR * 24)
68
69
70
71
72
73
74
75
76
77void time64_to_tm(time64_t totalsecs, int offset, struct tm *result)
78{
79 long days, rem, y;
80 int remainder;
81 const unsigned short *ip;
82
83 days = div_s64_rem(totalsecs, SECS_PER_DAY, &remainder);
84 rem = remainder;
85 rem += offset;
86 while (rem < 0) {
87 rem += SECS_PER_DAY;
88 --days;
89 }
90 while (rem >= SECS_PER_DAY) {
91 rem -= SECS_PER_DAY;
92 ++days;
93 }
94
95 result->tm_hour = rem / SECS_PER_HOUR;
96 rem %= SECS_PER_HOUR;
97 result->tm_min = rem / 60;
98 result->tm_sec = rem % 60;
99
100
101 result->tm_wday = (4 + days) % 7;
102 if (result->tm_wday < 0)
103 result->tm_wday += 7;
104
105 y = 1970;
106
107 while (days < 0 || days >= (__isleap(y) ? 366 : 365)) {
108
109 long yg = y + math_div(days, 365);
110
111
112 days -= (yg - y) * 365 + leaps_between(y, yg);
113 y = yg;
114 }
115
116 result->tm_year = y - 1900;
117
118 result->tm_yday = days;
119
120 ip = __mon_yday[__isleap(y)];
121 for (y = 11; days < ip[y]; y--)
122 continue;
123 days -= ip[y];
124
125 result->tm_mon = y;
126 result->tm_mday = days + 1;
127}
128EXPORT_SYMBOL(time64_to_tm);
129