xref: /freebsd/sys/kern/subr_fattime.c (revision 42249ef2)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2006 Poul-Henning Kamp
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  *
30  * Convert MS-DOS FAT format timestamps to and from unix timespecs
31  *
32  * FAT filestamps originally consisted of two 16 bit integers, encoded like
33  * this:
34  *
35  *	yyyyyyymmmmddddd (year - 1980, month, day)
36  *
37  *      hhhhhmmmmmmsssss (hour, minutes, seconds divided by two)
38  *
39  * Subsequently even Microsoft realized that files could be accessed in less
40  * than two seconds and a byte was added containing:
41  *
42  *      sfffffff	 (second mod two, 100ths of second)
43  *
44  * FAT timestamps are in the local timezone, with no indication of which
45  * timezone much less if daylight savings time applies.
46  *
47  * Later on again, in Windows NT, timestamps were defined relative to GMT.
48  *
49  * Purists will point out that UTC replaced GMT for such uses around
50  * half a century ago, already then.  Ironically "NT" was an abbreviation of
51  * "New Technology".  Anyway...
52  *
53  * The 'utc' argument determines if the resulting FATTIME timestamp
54  * should be on the UTC or local timezone calendar.
55  *
56  * The conversion functions below cut time into four-year leap-year
57  * cycles rather than single years and uses table lookups inside those
58  * cycles to get the months and years sorted out.
59  *
60  * Obviously we cannot calculate the correct table index going from
61  * a posix seconds count to Y/M/D, but we can get pretty close by
62  * dividing the daycount by 32 (giving a too low index), and then
63  * adjusting upwards a couple of steps if necessary.
64  *
65  * FAT timestamps have 7 bits for the year and starts at 1980, so
66  * they can represent up to 2107 which means that the non-leap-year
67  * 2100 must be handled.
68  *
69  * XXX: As long as time_t is 32 bits this is not relevant or easily
70  * XXX: testable.  Revisit when time_t grows bigger.
71  * XXX: grepfodder: 64 bit time_t, y2100, y2.1k, 2100, leap year
72  *
73  */
74 
75 #include <sys/param.h>
76 #include <sys/types.h>
77 #include <sys/time.h>
78 #include <sys/clock.h>
79 
80 #define DAY	(24 * 60 * 60)	/* Length of day in seconds */
81 #define YEAR	365		/* Length of normal year */
82 #define LYC	(4 * YEAR + 1)	/* Length of 4 year leap-year cycle */
83 #define T1980	(10 * 365 + 2)	/* Days from 1970 to 1980 */
84 
85 /* End of month is N days from start of (normal) year */
86 #define JAN	31
87 #define FEB	(JAN + 28)
88 #define MAR	(FEB + 31)
89 #define APR	(MAR + 30)
90 #define MAY	(APR + 31)
91 #define JUN	(MAY + 30)
92 #define JUL	(JUN + 31)
93 #define AUG	(JUL + 31)
94 #define SEP	(AUG + 30)
95 #define OCT	(SEP + 31)
96 #define NOV	(OCT + 30)
97 #define DEC	(NOV + 31)
98 
99 /* Table of months in a 4 year leap-year cycle */
100 
101 #define ENC(y,m)	(((y) << 9) | ((m) << 5))
102 
103 static const struct {
104 	uint16_t	days;	/* month start in days relative to cycle */
105 	uint16_t	coded;	/* encoded year + month information */
106 } mtab[48] = {
107 	{   0 + 0 * YEAR,     ENC(0, 1)  },
108 
109 	{ JAN + 0 * YEAR,     ENC(0, 2)  }, { FEB + 0 * YEAR + 1, ENC(0, 3)  },
110 	{ MAR + 0 * YEAR + 1, ENC(0, 4)  }, { APR + 0 * YEAR + 1, ENC(0, 5)  },
111 	{ MAY + 0 * YEAR + 1, ENC(0, 6)  }, { JUN + 0 * YEAR + 1, ENC(0, 7)  },
112 	{ JUL + 0 * YEAR + 1, ENC(0, 8)  }, { AUG + 0 * YEAR + 1, ENC(0, 9)  },
113 	{ SEP + 0 * YEAR + 1, ENC(0, 10) }, { OCT + 0 * YEAR + 1, ENC(0, 11) },
114 	{ NOV + 0 * YEAR + 1, ENC(0, 12) }, { DEC + 0 * YEAR + 1, ENC(1, 1)  },
115 
116 	{ JAN + 1 * YEAR + 1, ENC(1, 2)  }, { FEB + 1 * YEAR + 1, ENC(1, 3)  },
117 	{ MAR + 1 * YEAR + 1, ENC(1, 4)  }, { APR + 1 * YEAR + 1, ENC(1, 5)  },
118 	{ MAY + 1 * YEAR + 1, ENC(1, 6)  }, { JUN + 1 * YEAR + 1, ENC(1, 7)  },
119 	{ JUL + 1 * YEAR + 1, ENC(1, 8)  }, { AUG + 1 * YEAR + 1, ENC(1, 9)  },
120 	{ SEP + 1 * YEAR + 1, ENC(1, 10) }, { OCT + 1 * YEAR + 1, ENC(1, 11) },
121 	{ NOV + 1 * YEAR + 1, ENC(1, 12) }, { DEC + 1 * YEAR + 1, ENC(2, 1)  },
122 
123 	{ JAN + 2 * YEAR + 1, ENC(2, 2)  }, { FEB + 2 * YEAR + 1, ENC(2, 3)  },
124 	{ MAR + 2 * YEAR + 1, ENC(2, 4)  }, { APR + 2 * YEAR + 1, ENC(2, 5)  },
125 	{ MAY + 2 * YEAR + 1, ENC(2, 6)  }, { JUN + 2 * YEAR + 1, ENC(2, 7)  },
126 	{ JUL + 2 * YEAR + 1, ENC(2, 8)  }, { AUG + 2 * YEAR + 1, ENC(2, 9)  },
127 	{ SEP + 2 * YEAR + 1, ENC(2, 10) }, { OCT + 2 * YEAR + 1, ENC(2, 11) },
128 	{ NOV + 2 * YEAR + 1, ENC(2, 12) }, { DEC + 2 * YEAR + 1, ENC(3, 1)  },
129 
130 	{ JAN + 3 * YEAR + 1, ENC(3, 2)  }, { FEB + 3 * YEAR + 1, ENC(3, 3)  },
131 	{ MAR + 3 * YEAR + 1, ENC(3, 4)  }, { APR + 3 * YEAR + 1, ENC(3, 5)  },
132 	{ MAY + 3 * YEAR + 1, ENC(3, 6)  }, { JUN + 3 * YEAR + 1, ENC(3, 7)  },
133 	{ JUL + 3 * YEAR + 1, ENC(3, 8)  }, { AUG + 3 * YEAR + 1, ENC(3, 9)  },
134 	{ SEP + 3 * YEAR + 1, ENC(3, 10) }, { OCT + 3 * YEAR + 1, ENC(3, 11) },
135 	{ NOV + 3 * YEAR + 1, ENC(3, 12) }
136 };
137 
138 
139 void
140 timespec2fattime(const struct timespec *tsp, int utc, uint16_t *ddp,
141     uint16_t *dtp, uint8_t *dhp)
142 {
143 	time_t t1;
144 	unsigned t2, l, m;
145 
146 	t1 = tsp->tv_sec;
147 	if (!utc)
148 		t1 -= utc_offset();
149 
150 	if (dhp != NULL)
151 		*dhp = (tsp->tv_sec & 1) * 100 + tsp->tv_nsec / 10000000;
152 	if (dtp != NULL) {
153 		*dtp = (t1 / 2) % 30;
154 		*dtp |= ((t1 / 60) % 60) << 5;
155 		*dtp |= ((t1 / 3600) % 24) << 11;
156 	}
157 	if (ddp != NULL) {
158 		t2 = t1 / DAY;
159 		if (t2 < T1980) {
160 			/* Impossible date, truncate to 1980-01-01 */
161 			*ddp = 0x0021;
162 		} else {
163 			t2 -= T1980;
164 
165 			/*
166 			 * 2100 is not a leap year.
167 			 * XXX: a 32 bit time_t can not get us here.
168 			 */
169 			if (t2 >= ((2100 - 1980) / 4 * LYC + FEB))
170 				t2++;
171 
172 			/* Account for full leapyear cycles */
173 			l = t2 / LYC;
174 			*ddp = (l * 4) << 9;
175 			t2 -= l * LYC;
176 
177 			/* Find approximate table entry */
178 			m = t2 / 32;
179 
180 			/* Find correct table entry */
181 			while (m < 47 && mtab[m + 1].days <= t2)
182 				m++;
183 
184 			/* Get year + month from the table */
185 			*ddp += mtab[m].coded;
186 
187 			/* And apply the day in the month */
188 			t2 -= mtab[m].days - 1;
189 			*ddp |= t2;
190 		}
191 	}
192 }
193 
194 /*
195  * Table indexed by the bottom two bits of year + four bits of the month
196  * from the FAT timestamp, returning number of days into 4 year long
197  * leap-year cycle
198  */
199 
200 #define DCOD(m, y, l)	((m) + YEAR * (y) + (l))
201 static const uint16_t daytab[64] = {
202 	0, 		 DCOD(  0, 0, 0), DCOD(JAN, 0, 0), DCOD(FEB, 0, 1),
203 	DCOD(MAR, 0, 1), DCOD(APR, 0, 1), DCOD(MAY, 0, 1), DCOD(JUN, 0, 1),
204 	DCOD(JUL, 0, 1), DCOD(AUG, 0, 1), DCOD(SEP, 0, 1), DCOD(OCT, 0, 1),
205 	DCOD(NOV, 0, 1), DCOD(DEC, 0, 1), 0,               0,
206 	0, 		 DCOD(  0, 1, 1), DCOD(JAN, 1, 1), DCOD(FEB, 1, 1),
207 	DCOD(MAR, 1, 1), DCOD(APR, 1, 1), DCOD(MAY, 1, 1), DCOD(JUN, 1, 1),
208 	DCOD(JUL, 1, 1), DCOD(AUG, 1, 1), DCOD(SEP, 1, 1), DCOD(OCT, 1, 1),
209 	DCOD(NOV, 1, 1), DCOD(DEC, 1, 1), 0,               0,
210 	0,		 DCOD(  0, 2, 1), DCOD(JAN, 2, 1), DCOD(FEB, 2, 1),
211 	DCOD(MAR, 2, 1), DCOD(APR, 2, 1), DCOD(MAY, 2, 1), DCOD(JUN, 2, 1),
212 	DCOD(JUL, 2, 1), DCOD(AUG, 2, 1), DCOD(SEP, 2, 1), DCOD(OCT, 2, 1),
213 	DCOD(NOV, 2, 1), DCOD(DEC, 2, 1), 0,               0,
214 	0,		 DCOD(  0, 3, 1), DCOD(JAN, 3, 1), DCOD(FEB, 3, 1),
215 	DCOD(MAR, 3, 1), DCOD(APR, 3, 1), DCOD(MAY, 3, 1), DCOD(JUN, 3, 1),
216 	DCOD(JUL, 3, 1), DCOD(AUG, 3, 1), DCOD(SEP, 3, 1), DCOD(OCT, 3, 1),
217 	DCOD(NOV, 3, 1), DCOD(DEC, 3, 1), 0,               0
218 };
219 
220 void
221 fattime2timespec(unsigned dd, unsigned dt, unsigned dh, int utc,
222     struct timespec *tsp)
223 {
224 	unsigned day;
225 
226 	/* Unpack time fields */
227 	tsp->tv_sec = (dt & 0x1f) << 1;
228 	tsp->tv_sec += ((dt & 0x7e0) >> 5) * 60;
229 	tsp->tv_sec += ((dt & 0xf800) >> 11) * 3600;
230 	tsp->tv_sec += dh / 100;
231 	tsp->tv_nsec = (dh % 100) * 10000000;
232 
233 	/* Day of month */
234 	day = (dd & 0x1f) - 1;
235 
236 	/* Full leap-year cycles */
237 	day += LYC * ((dd >> 11) & 0x1f);
238 
239 	/* Month offset from leap-year cycle */
240 	day += daytab[(dd >> 5) & 0x3f];
241 
242 	/*
243 	 * 2100 is not a leap year.
244 	 * XXX: a 32 bit time_t can not get us here.
245 	 */
246 	if (day >= ((2100 - 1980) / 4 * LYC + FEB))
247 		day--;
248 
249 	/* Align with time_t epoch */
250 	day += T1980;
251 
252 	tsp->tv_sec += DAY * day;
253 	if (!utc)
254 		tsp->tv_sec += utc_offset();
255 }
256 
257 #ifdef TEST_DRIVER
258 
259 #include <stdio.h>
260 #include <unistd.h>
261 #include <stdlib.h>
262 
263 int
264 main(int argc __unused, char **argv __unused)
265 {
266 	int i;
267 	struct timespec ts;
268 	struct tm tm;
269 	double a;
270 	uint16_t d, t;
271 	uint8_t p;
272 	char buf[100];
273 
274 	for (i = 0; i < 10000; i++) {
275 		do {
276 			ts.tv_sec = random();
277 		} while (ts.tv_sec < T1980 * 86400);
278 		ts.tv_nsec = random() % 1000000000;
279 
280 		printf("%10d.%03ld -- ", ts.tv_sec, ts.tv_nsec / 1000000);
281 
282 		gmtime_r(&ts.tv_sec, &tm);
283 		strftime(buf, sizeof buf, "%Y %m %d %H %M %S", &tm);
284 		printf("%s -- ", buf);
285 
286 		a = ts.tv_sec + ts.tv_nsec * 1e-9;
287 		d = t = p = 0;
288 		timet2fattime(&ts, &d, &t, &p);
289 		printf("%04x %04x %02x -- ", d, t, p);
290 		printf("%3d %02d %02d %02d %02d %02d -- ",
291 		    ((d >> 9)  & 0x7f) + 1980,
292 		    (d >> 5)  & 0x0f,
293 		    (d >> 0)  & 0x1f,
294 		    (t >> 11) & 0x1f,
295 		    (t >> 5)  & 0x3f,
296 		    ((t >> 0)  & 0x1f) * 2);
297 
298 		ts.tv_sec = ts.tv_nsec = 0;
299 		fattime2timet(d, t, p, &ts);
300 		printf("%10d.%03ld == ", ts.tv_sec, ts.tv_nsec / 1000000);
301 		gmtime_r(&ts.tv_sec, &tm);
302 		strftime(buf, sizeof buf, "%Y %m %d %H %M %S", &tm);
303 		printf("%s -- ", buf);
304 		a -= ts.tv_sec + ts.tv_nsec * 1e-9;
305 		printf("%.3f", a);
306 		printf("\n");
307 	}
308 	return (0);
309 }
310 
311 #endif /* TEST_DRIVER */
312