1 /*	$NetBSD: ntp_calendar.c,v 1.11 2020/05/25 20:47:24 christos Exp $	*/
2 
3 /*
4  * ntp_calendar.c - calendar and helper functions
5  *
6  * Written by Juergen Perlinger (perlinger@ntp.org) for the NTP project.
7  * The contents of 'html/copyright.html' apply.
8  *
9  * --------------------------------------------------------------------
10  * Some notes on the implementation:
11  *
12  * Calendar algorithms thrive on the division operation, which is one of
13  * the slowest numerical operations in any CPU. What saves us here from
14  * abysmal performance is the fact that all divisions are divisions by
15  * constant numbers, and most compilers can do this by a multiplication
16  * operation.  But this might not work when using the div/ldiv/lldiv
17  * function family, because many compilers are not able to do inline
18  * expansion of the code with following optimisation for the
19  * constant-divider case.
20  *
21  * Also div/ldiv/lldiv are defined in terms of int/long/longlong, which
22  * are inherently target dependent. Nothing that could not be cured with
23  * autoconf, but still a mess...
24  *
25  * Furthermore, we need floor division in many places. C either leaves
26  * the division behaviour undefined (< C99) or demands truncation to
27  * zero (>= C99), so additional steps are required to make sure the
28  * algorithms work. The {l,ll}div function family is requested to
29  * truncate towards zero, which is also the wrong direction for our
30  * purpose.
31  *
32  * For all this, all divisions by constant are coded manually, even when
33  * there is a joined div/mod operation: The optimiser should sort that
34  * out, if possible. Most of the calculations are done with unsigned
35  * types, explicitely using two's complement arithmetics where
36  * necessary. This minimises the dependecies to compiler and target,
37  * while still giving reasonable to good performance.
38  *
39  * The implementation uses a few tricks that exploit properties of the
40  * two's complement: Floor division on negative dividents can be
41  * executed by using the one's complement of the divident. One's
42  * complement can be easily created using XOR and a mask.
43  *
44  * Finally, check for overflow conditions is minimal. There are only two
45  * calculation steps in the whole calendar that potentially suffer from
46  * an internal overflow, and these are coded in a way that avoids
47  * it. All other functions do not suffer from internal overflow and
48  * simply return the result truncated to 32 bits.
49  */
50 
51 #include <config.h>
52 #include <sys/types.h>
53 
54 #include "ntp_types.h"
55 #include "ntp_calendar.h"
56 #include "ntp_stdlib.h"
57 #include "ntp_fp.h"
58 #include "ntp_unixtime.h"
59 
60 #include "ntpd.h"
61 #include "lib_strbuf.h"
62 
63 /* For now, let's take the conservative approach: if the target property
64  * macros are not defined, check a few well-known compiler/architecture
65  * settings. Default is to assume that the representation of signed
66  * integers is unknown and shift-arithmetic-right is not available.
67  */
68 #ifndef TARGET_HAS_2CPL
69 # if defined(__GNUC__)
70 #  if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
71 #   define TARGET_HAS_2CPL 1
72 #  else
73 #   define TARGET_HAS_2CPL 0
74 #  endif
75 # elif defined(_MSC_VER)
76 #  if defined(_M_IX86) || defined(_M_X64) || defined(_M_ARM)
77 #   define TARGET_HAS_2CPL 1
78 #  else
79 #   define TARGET_HAS_2CPL 0
80 #  endif
81 # else
82 #  define TARGET_HAS_2CPL 0
83 # endif
84 #endif
85 
86 #ifndef TARGET_HAS_SAR
87 # define TARGET_HAS_SAR 0
88 #endif
89 
90 #if !defined(HAVE_64BITREGS) && defined(UINT64_MAX) && (SIZE_MAX >= UINT64_MAX)
91 # define HAVE_64BITREGS
92 #endif
93 
94 /*
95  *---------------------------------------------------------------------
96  * replacing the 'time()' function
97  *---------------------------------------------------------------------
98  */
99 
100 static systime_func_ptr systime_func = &time;
101 static inline time_t now(void);
102 
103 
104 systime_func_ptr
ntpcal_set_timefunc(systime_func_ptr nfunc)105 ntpcal_set_timefunc(
106 	systime_func_ptr nfunc
107 	)
108 {
109 	systime_func_ptr res;
110 
111 	res = systime_func;
112 	if (NULL == nfunc)
113 		nfunc = &time;
114 	systime_func = nfunc;
115 
116 	return res;
117 }
118 
119 
120 static inline time_t
now(void)121 now(void)
122 {
123 	return (*systime_func)(NULL);
124 }
125 
126 /*
127  *---------------------------------------------------------------------
128  * Get sign extension mask and unsigned 2cpl rep for a signed integer
129  *---------------------------------------------------------------------
130  */
131 
132 static inline uint32_t
int32_sflag(const int32_t v)133 int32_sflag(
134 	const int32_t v)
135 {
136 #   if TARGET_HAS_2CPL && TARGET_HAS_SAR && SIZEOF_INT >= 4
137 
138 	/* Let's assume that shift is the fastest way to get the sign
139 	 * extension of of a signed integer. This might not always be
140 	 * true, though -- On 8bit CPUs or machines without barrel
141 	 * shifter this will kill the performance. So we make sure
142 	 * we do this only if 'int' has at least 4 bytes.
143 	 */
144 	return (uint32_t)(v >> 31);
145 
146 #   else
147 
148 	/* This should be a rather generic approach for getting a sign
149 	 * extension mask...
150 	 */
151 	return UINT32_C(0) - (uint32_t)(v < 0);
152 
153 #   endif
154 }
155 
156 static inline int32_t
uint32_2cpl_to_int32(const uint32_t vu)157 uint32_2cpl_to_int32(
158 	const uint32_t vu)
159 {
160 	int32_t v;
161 
162 #   if TARGET_HAS_2CPL
163 
164 	/* Just copy through the 32 bits from the unsigned value if
165 	 * we're on a two's complement target.
166 	 */
167 	v = (int32_t)vu;
168 
169 #   else
170 
171 	/* Convert to signed integer, making sure signed integer
172 	 * overflow cannot happen. Again, the optimiser might or might
173 	 * not find out that this is just a copy of 32 bits on a target
174 	 * with two's complement representation for signed integers.
175 	 */
176 	if (vu > INT32_MAX)
177 		v = -(int32_t)(~vu) - 1;
178 	else
179 		v = (int32_t)vu;
180 
181 #   endif
182 
183 	return v;
184 }
185 
186 /*
187  *---------------------------------------------------------------------
188  * Convert between 'time_t' and 'vint64'
189  *---------------------------------------------------------------------
190  */
191 vint64
time_to_vint64(const time_t * ptt)192 time_to_vint64(
193 	const time_t * ptt
194 	)
195 {
196 	vint64 res;
197 	time_t tt;
198 
199 	tt = *ptt;
200 
201 #   if SIZEOF_TIME_T <= 4
202 
203 	res.D_s.hi = 0;
204 	if (tt < 0) {
205 		res.D_s.lo = (uint32_t)-tt;
206 		M_NEG(res.D_s.hi, res.D_s.lo);
207 	} else {
208 		res.D_s.lo = (uint32_t)tt;
209 	}
210 
211 #   elif defined(HAVE_INT64)
212 
213 	res.q_s = tt;
214 
215 #   else
216 	/*
217 	 * shifting negative signed quantities is compiler-dependent, so
218 	 * we better avoid it and do it all manually. And shifting more
219 	 * than the width of a quantity is undefined. Also a don't do!
220 	 */
221 	if (tt < 0) {
222 		tt = -tt;
223 		res.D_s.lo = (uint32_t)tt;
224 		res.D_s.hi = (uint32_t)(tt >> 32);
225 		M_NEG(res.D_s.hi, res.D_s.lo);
226 	} else {
227 		res.D_s.lo = (uint32_t)tt;
228 		res.D_s.hi = (uint32_t)(tt >> 32);
229 	}
230 
231 #   endif
232 
233 	return res;
234 }
235 
236 
237 time_t
vint64_to_time(const vint64 * tv)238 vint64_to_time(
239 	const vint64 *tv
240 	)
241 {
242 	time_t res;
243 
244 #   if SIZEOF_TIME_T <= 4
245 
246 	res = (time_t)tv->D_s.lo;
247 
248 #   elif defined(HAVE_INT64)
249 
250 	res = (time_t)tv->q_s;
251 
252 #   else
253 
254 	res = ((time_t)tv->d_s.hi << 32) | tv->D_s.lo;
255 
256 #   endif
257 
258 	return res;
259 }
260 
261 /*
262  *---------------------------------------------------------------------
263  * Get the build date & time
264  *---------------------------------------------------------------------
265  */
266 int
ntpcal_get_build_date(struct calendar * jd)267 ntpcal_get_build_date(
268 	struct calendar * jd
269 	)
270 {
271 	/* The C standard tells us the format of '__DATE__':
272 	 *
273 	 * __DATE__ The date of translation of the preprocessing
274 	 * translation unit: a character string literal of the form "Mmm
275 	 * dd yyyy", where the names of the months are the same as those
276 	 * generated by the asctime function, and the first character of
277 	 * dd is a space character if the value is less than 10. If the
278 	 * date of translation is not available, an
279 	 * implementation-defined valid date shall be supplied.
280 	 *
281 	 * __TIME__ The time of translation of the preprocessing
282 	 * translation unit: a character string literal of the form
283 	 * "hh:mm:ss" as in the time generated by the asctime
284 	 * function. If the time of translation is not available, an
285 	 * implementation-defined valid time shall be supplied.
286 	 *
287 	 * Note that MSVC declares DATE and TIME to be in the local time
288 	 * zone, while neither the C standard nor the GCC docs make any
289 	 * statement about this. As a result, we may be +/-12hrs off
290 	 * UTC.	 But for practical purposes, this should not be a
291 	 * problem.
292 	 *
293 	 */
294 #   ifdef MKREPRO_DATE
295 	static const char build[] = MKREPRO_TIME "/" MKREPRO_DATE;
296 #   else
297 	static const char build[] = __TIME__ "/" __DATE__;
298 #   endif
299 	static const char mlist[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
300 
301 	char		  monstr[4];
302 	const char *	  cp;
303 	unsigned short	  hour, minute, second, day, year;
304 	/* Note: The above quantities are used for sscanf 'hu' format,
305 	 * so using 'uint16_t' is contra-indicated!
306 	 */
307 
308 #   ifdef DEBUG
309 	static int	  ignore  = 0;
310 #   endif
311 
312 	ZERO(*jd);
313 	jd->year     = 1970;
314 	jd->month    = 1;
315 	jd->monthday = 1;
316 
317 #   ifdef DEBUG
318 	/* check environment if build date should be ignored */
319 	if (0 == ignore) {
320 	    const char * envstr;
321 	    envstr = getenv("NTPD_IGNORE_BUILD_DATE");
322 	    ignore = 1 + (envstr && (!*envstr || !strcasecmp(envstr, "yes")));
323 	}
324 	if (ignore > 1)
325 	    return FALSE;
326 #   endif
327 
328 	if (6 == sscanf(build, "%hu:%hu:%hu/%3s %hu %hu",
329 			&hour, &minute, &second, monstr, &day, &year)) {
330 		cp = strstr(mlist, monstr);
331 		if (NULL != cp) {
332 			jd->year     = year;
333 			jd->month    = (uint8_t)((cp - mlist) / 3 + 1);
334 			jd->monthday = (uint8_t)day;
335 			jd->hour     = (uint8_t)hour;
336 			jd->minute   = (uint8_t)minute;
337 			jd->second   = (uint8_t)second;
338 
339 			return TRUE;
340 		}
341 	}
342 
343 	return FALSE;
344 }
345 
346 
347 /*
348  *---------------------------------------------------------------------
349  * basic calendar stuff
350  *---------------------------------------------------------------------
351  */
352 
353 /*
354  * Some notes on the terminology:
355  *
356  * We use the proleptic Gregorian calendar, which is the Gregorian
357  * calendar extended in both directions ad infinitum. This totally
358  * disregards the fact that this calendar was invented in 1582, and
359  * was adopted at various dates over the world; sometimes even after
360  * the start of the NTP epoch.
361  *
362  * Normally date parts are given as current cycles, while time parts
363  * are given as elapsed cycles:
364  *
365  * 1970-01-01/03:04:05 means 'IN the 1970st. year, IN the first month,
366  * ON the first day, with 3hrs, 4minutes and 5 seconds elapsed.
367  *
368  * The basic calculations for this calendar implementation deal with
369  * ELAPSED date units, which is the number of full years, full months
370  * and full days before a date: 1970-01-01 would be (1969, 0, 0) in
371  * that notation.
372  *
373  * To ease the numeric computations, month and day values outside the
374  * normal range are acceptable: 2001-03-00 will be treated as the day
375  * before 2001-03-01, 2000-13-32 will give the same result as
376  * 2001-02-01 and so on.
377  *
378  * 'rd' or 'RD' is used as an abbreviation for the latin 'rata die'
379  * (day number).  This is the number of days elapsed since 0000-12-31
380  * in the proleptic Gregorian calendar. The begin of the Christian Era
381  * (0001-01-01) is RD(1).
382  */
383 
384 /*
385  * ====================================================================
386  *
387  * General algorithmic stuff
388  *
389  * ====================================================================
390  */
391 
392 /*
393  *---------------------------------------------------------------------
394  * fast modulo 7 operations (floor/mathematical convention)
395  *---------------------------------------------------------------------
396  */
397 int
u32mod7(uint32_t x)398 u32mod7(
399 	uint32_t x
400 	)
401 {
402 	/* This is a combination of tricks from "Hacker's Delight" with
403 	 * some modifications, like a multiplication that rounds up to
404 	 * drop the final adjustment stage.
405 	 *
406 	 * Do a partial reduction by digit sum to keep the value in the
407 	 * range permitted for the mul/shift stage. There are several
408 	 * possible and absolutely equivalent shift/mask combinations;
409 	 * this one is ARM-friendly because of a mask that fits into 16
410 	 * bit.
411 	 */
412 	x = (x >> 15) + (x & UINT32_C(0x7FFF));
413 	/* Take reminder as (mod 8) by mul/shift. Since the multiplier
414 	 * was calculated using ceil() instead of floor(), it skips the
415 	 * value '7' properly.
416 	 *    M <- ceil(ldexp(8/7, 29))
417 	 */
418 	return (int)((x * UINT32_C(0x24924925)) >> 29);
419 }
420 
421 int
i32mod7(int32_t x)422 i32mod7(
423 	int32_t x
424 	)
425 {
426 	/* We add (2**32 - 2**32 % 7), which is (2**32 - 4), to negative
427 	 * numbers to map them into the postive range. Only the term '-4'
428 	 * survives, obviously.
429 	 */
430 	uint32_t ux = (uint32_t)x;
431 	return u32mod7((x < 0) ? (ux - 4u) : ux);
432 }
433 
434 uint32_t
i32fmod(int32_t x,uint32_t d)435 i32fmod(
436 	int32_t	 x,
437 	uint32_t d
438 	)
439 {
440 	uint32_t ux = (uint32_t)x;
441 	uint32_t sf = UINT32_C(0) - (x < 0);
442 	ux = (sf ^ ux ) % d;
443 	return (d & sf) + (sf ^ ux);
444 }
445 
446 /*
447  *---------------------------------------------------------------------
448  * Do a periodic extension of 'value' around 'pivot' with a period of
449  * 'cycle'.
450  *
451  * The result 'res' is a number that holds to the following properties:
452  *
453  *   1)	 res MOD cycle == value MOD cycle
454  *   2)	 pivot <= res < pivot + cycle
455  *	 (replace </<= with >/>= for negative cycles)
456  *
457  * where 'MOD' denotes the modulo operator for FLOOR DIVISION, which
458  * is not the same as the '%' operator in C: C requires division to be
459  * a truncated division, where remainder and dividend have the same
460  * sign if the remainder is not zero, whereas floor division requires
461  * divider and modulus to have the same sign for a non-zero modulus.
462  *
463  * This function has some useful applications:
464  *
465  * + let Y be a calendar year and V a truncated 2-digit year: then
466  *	periodic_extend(Y-50, V, 100)
467  *   is the closest expansion of the truncated year with respect to
468  *   the full year, that is a 4-digit year with a difference of less
469  *   than 50 years to the year Y. ("century unfolding")
470  *
471  * + let T be a UN*X time stamp and V be seconds-of-day: then
472  *	perodic_extend(T-43200, V, 86400)
473  *   is a time stamp that has the same seconds-of-day as the input
474  *   value, with an absolute difference to T of <= 12hrs.  ("day
475  *   unfolding")
476  *
477  * + Wherever you have a truncated periodic value and a non-truncated
478  *   base value and you want to match them somehow...
479  *
480  * Basically, the function delivers 'pivot + (value - pivot) % cycle',
481  * but the implementation takes some pains to avoid internal signed
482  * integer overflows in the '(value - pivot) % cycle' part and adheres
483  * to the floor division convention.
484  *
485  * If 64bit scalars where available on all intended platforms, writing a
486  * version that uses 64 bit ops would be easy; writing a general
487  * division routine for 64bit ops on a platform that can only do
488  * 32/16bit divisions and is still performant is a bit more
489  * difficult. Since most usecases can be coded in a way that does only
490  * require the 32bit version a 64bit version is NOT provided here.
491  *---------------------------------------------------------------------
492  */
493 int32_t
ntpcal_periodic_extend(int32_t pivot,int32_t value,int32_t cycle)494 ntpcal_periodic_extend(
495 	int32_t pivot,
496 	int32_t value,
497 	int32_t cycle
498 	)
499 {
500 	/* Implement a 4-quadrant modulus calculation by 2 2-quadrant
501 	 * branches, one for positive and one for negative dividers.
502 	 * Everything else can be handled by bit level logic and
503 	 * conditional one's complement arithmetic.  By convention, we
504 	 * assume
505 	 *
506 	 * x % b == 0  if  |b| < 2
507 	 *
508 	 * that is, we don't actually divide for cycles of -1,0,1 and
509 	 * return the pivot value in that case.
510 	 */
511 	uint32_t	uv = (uint32_t)value;
512 	uint32_t	up = (uint32_t)pivot;
513 	uint32_t	uc, sf;
514 
515 	if (cycle > 1)
516 	{
517 		uc = (uint32_t)cycle;
518 		sf = UINT32_C(0) - (value < pivot);
519 
520 		uv = sf ^ (uv - up);
521 		uv %= uc;
522 		pivot += (uc & sf) + (sf ^ uv);
523 	}
524 	else if (cycle < -1)
525 	{
526 		uc = ~(uint32_t)cycle + 1;
527 		sf = UINT32_C(0) - (value > pivot);
528 
529 		uv = sf ^ (up - uv);
530 		uv %= uc;
531 		pivot -= (uc & sf) + (sf ^ uv);
532 	}
533 	return pivot;
534 }
535 
536 /*---------------------------------------------------------------------
537  * Note to the casual reader
538  *
539  * In the next two functions you will find (or would have found...)
540  * the expression
541  *
542  *   res.Q_s -= 0x80000000;
543  *
544  * There was some ruckus about a possible programming error due to
545  * integer overflow and sign propagation.
546  *
547  * This assumption is based on a lack of understanding of the C
548  * standard. (Though this is admittedly not one of the most 'natural'
549  * aspects of the 'C' language and easily to get wrong.)
550  *
551  * see
552  *	http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
553  *	"ISO/IEC 9899:201x Committee Draft — April 12, 2011"
554  *	6.4.4.1 Integer constants, clause 5
555  *
556  * why there is no sign extension/overflow problem here.
557  *
558  * But to ease the minds of the doubtful, I added back the 'u' qualifiers
559  * that somehow got lost over the last years.
560  */
561 
562 
563 /*
564  *---------------------------------------------------------------------
565  * Convert a timestamp in NTP scale to a 64bit seconds value in the UN*X
566  * scale with proper epoch unfolding around a given pivot or the current
567  * system time. This function happily accepts negative pivot values as
568  * timestamps before 1970-01-01, so be aware of possible trouble on
569  * platforms with 32bit 'time_t'!
570  *
571  * This is also a periodic extension, but since the cycle is 2^32 and
572  * the shift is 2^31, we can do some *very* fast math without explicit
573  * divisions.
574  *---------------------------------------------------------------------
575  */
576 vint64
ntpcal_ntp_to_time(uint32_t ntp,const time_t * pivot)577 ntpcal_ntp_to_time(
578 	uint32_t	ntp,
579 	const time_t *	pivot
580 	)
581 {
582 	vint64 res;
583 
584 #   if defined(HAVE_INT64)
585 
586 	res.q_s = (pivot != NULL)
587 		      ? *pivot
588 		      : now();
589 	res.Q_s -= 0x80000000u;		/* unshift of half range */
590 	ntp	-= (uint32_t)JAN_1970;	/* warp into UN*X domain */
591 	ntp	-= res.D_s.lo;		/* cycle difference	 */
592 	res.Q_s += (uint64_t)ntp;	/* get expanded time	 */
593 
594 #   else /* no 64bit scalars */
595 
596 	time_t tmp;
597 
598 	tmp = (pivot != NULL)
599 		  ? *pivot
600 		  : now();
601 	res = time_to_vint64(&tmp);
602 	M_SUB(res.D_s.hi, res.D_s.lo, 0, 0x80000000u);
603 	ntp -= (uint32_t)JAN_1970;	/* warp into UN*X domain */
604 	ntp -= res.D_s.lo;		/* cycle difference	 */
605 	M_ADD(res.D_s.hi, res.D_s.lo, 0, ntp);
606 
607 #   endif /* no 64bit scalars */
608 
609 	return res;
610 }
611 
612 /*
613  *---------------------------------------------------------------------
614  * Convert a timestamp in NTP scale to a 64bit seconds value in the NTP
615  * scale with proper epoch unfolding around a given pivot or the current
616  * system time.
617  *
618  * Note: The pivot must be given in the UN*X time domain!
619  *
620  * This is also a periodic extension, but since the cycle is 2^32 and
621  * the shift is 2^31, we can do some *very* fast math without explicit
622  * divisions.
623  *---------------------------------------------------------------------
624  */
625 vint64
ntpcal_ntp_to_ntp(uint32_t ntp,const time_t * pivot)626 ntpcal_ntp_to_ntp(
627 	uint32_t      ntp,
628 	const time_t *pivot
629 	)
630 {
631 	vint64 res;
632 
633 #   if defined(HAVE_INT64)
634 
635 	res.q_s = (pivot)
636 		      ? *pivot
637 		      : now();
638 	res.Q_s -= 0x80000000u;		/* unshift of half range */
639 	res.Q_s += (uint32_t)JAN_1970;	/* warp into NTP domain	 */
640 	ntp	-= res.D_s.lo;		/* cycle difference	 */
641 	res.Q_s += (uint64_t)ntp;	/* get expanded time	 */
642 
643 #   else /* no 64bit scalars */
644 
645 	time_t tmp;
646 
647 	tmp = (pivot)
648 		  ? *pivot
649 		  : now();
650 	res = time_to_vint64(&tmp);
651 	M_SUB(res.D_s.hi, res.D_s.lo, 0, 0x80000000u);
652 	M_ADD(res.D_s.hi, res.D_s.lo, 0, (uint32_t)JAN_1970);/*into NTP */
653 	ntp -= res.D_s.lo;		/* cycle difference	 */
654 	M_ADD(res.D_s.hi, res.D_s.lo, 0, ntp);
655 
656 #   endif /* no 64bit scalars */
657 
658 	return res;
659 }
660 
661 
662 /*
663  * ====================================================================
664  *
665  * Splitting values to composite entities
666  *
667  * ====================================================================
668  */
669 
670 /*
671  *---------------------------------------------------------------------
672  * Split a 64bit seconds value into elapsed days in 'res.hi' and
673  * elapsed seconds since midnight in 'res.lo' using explicit floor
674  * division. This function happily accepts negative time values as
675  * timestamps before the respective epoch start.
676  *---------------------------------------------------------------------
677  */
678 ntpcal_split
ntpcal_daysplit(const vint64 * ts)679 ntpcal_daysplit(
680 	const vint64 *ts
681 	)
682 {
683 	ntpcal_split res;
684 	uint32_t Q, R;
685 
686 #   if defined(HAVE_64BITREGS)
687 
688 	/* Assume we have 64bit registers an can do a divison by
689 	 * constant reasonably fast using the one's complement trick..
690 	 */
691 	uint64_t sf64 = (uint64_t)-(ts->q_s < 0);
692 	Q = (uint32_t)(sf64 ^ ((sf64 ^ ts->Q_s) / SECSPERDAY));
693 	R = (uint32_t)(ts->Q_s - Q * SECSPERDAY);
694 
695 #   elif defined(UINT64_MAX) && !defined(__arm__)
696 
697 	/* We rely on the compiler to do efficient 64bit divisions as
698 	 * good as possible. Which might or might not be true. At least
699 	 * for ARM CPUs, the sum-by-digit code in the next section is
700 	 * faster for many compilers. (This might change over time, but
701 	 * the 64bit-by-32bit division will never outperform the exact
702 	 * division by a substantial factor....)
703 	 */
704 	if (ts->q_s < 0)
705 		Q = ~(uint32_t)(~ts->Q_s / SECSPERDAY);
706 	else
707 		Q =  (uint32_t)( ts->Q_s / SECSPERDAY);
708 	R = ts->D_s.lo - Q * SECSPERDAY;
709 
710 #   else
711 
712 	/* We don't have 64bit regs. That hurts a bit.
713 	 *
714 	 * Here we use a mean trick to get away with just one explicit
715 	 * modulo operation and pure 32bit ops.
716 	 *
717 	 * Remember: 86400 <--> 128 * 675
718 	 *
719 	 * So we discard the lowest 7 bit and do an exact division by
720 	 * 675, modulo 2**32.
721 	 *
722 	 * First we shift out the lower 7 bits.
723 	 *
724 	 * Then we use a digit-wise pseudo-reduction, where a 'digit' is
725 	 * actually a 16-bit group. This is followed by a full reduction
726 	 * with a 'true' division step. This yields the modulus of the
727 	 * full 64bit value. The sign bit gets some extra treatment.
728 	 *
729 	 * Then we decrement the lower limb by that modulus, so it is
730 	 * exactly divisible by 675. [*]
731 	 *
732 	 * Then we multiply with the modular inverse of 675 (mod 2**32)
733 	 * and voila, we have the result.
734 	 *
735 	 * Special Thanks to Henry S. Warren and his "Hacker's delight"
736 	 * for giving that idea.
737 	 *
738 	 * (Note[*]: that's not the full truth. We would have to
739 	 * subtract the modulus from the full 64 bit number to get a
740 	 * number that is divisible by 675. But since we use the
741 	 * multiplicative inverse (mod 2**32) there's no reason to carry
742 	 * the subtraction into the upper bits!)
743 	 */
744 	uint32_t al = ts->D_s.lo;
745 	uint32_t ah = ts->D_s.hi;
746 
747 	/* shift out the lower 7 bits, smash sign bit */
748 	al = (al >> 7) | (ah << 25);
749 	ah = (ah >> 7) & 0x00FFFFFFu;
750 
751 	R  = (ts->d_s.hi < 0) ? 239 : 0;/* sign bit value */
752 	R += (al & 0xFFFF);
753 	R += (al >> 16	 ) * 61u;	/* 2**16 % 675 */
754 	R += (ah & 0xFFFF) * 346u;	/* 2**32 % 675 */
755 	R += (ah >> 16	 ) * 181u;	/* 2**48 % 675 */
756 	R %= 675u;			/* final reduction */
757 	Q  = (al - R) * 0x2D21C10Bu;	/* modinv(675, 2**32) */
758 	R  = (R << 7) | (ts->d_s.lo & 0x07F);
759 
760 #   endif
761 
762 	res.hi = uint32_2cpl_to_int32(Q);
763 	res.lo = R;
764 
765 	return res;
766 }
767 
768 /*
769  *---------------------------------------------------------------------
770  * Split a 64bit seconds value into elapsed weeks in 'res.hi' and
771  * elapsed seconds since week start in 'res.lo' using explicit floor
772  * division. This function happily accepts negative time values as
773  * timestamps before the respective epoch start.
774  *---------------------------------------------------------------------
775  */
776 ntpcal_split
ntpcal_weeksplit(const vint64 * ts)777 ntpcal_weeksplit(
778 	const vint64 *ts
779 	)
780 {
781 	ntpcal_split res;
782 	uint32_t Q, R;
783 
784 	/* This is a very close relative to the day split function; for
785 	 * details, see there!
786 	 */
787 
788 #   if defined(HAVE_64BITREGS)
789 
790 	uint64_t sf64 = (uint64_t)-(ts->q_s < 0);
791 	Q = (uint32_t)(sf64 ^ ((sf64 ^ ts->Q_s) / SECSPERWEEK));
792 	R = (uint32_t)(ts->Q_s - Q * SECSPERWEEK);
793 
794 #   elif defined(UINT64_MAX) && !defined(__arm__)
795 
796 	if (ts->q_s < 0)
797 		Q = ~(uint32_t)(~ts->Q_s / SECSPERWEEK);
798 	else
799 		Q =  (uint32_t)( ts->Q_s / SECSPERWEEK);
800 	R = ts->D_s.lo - Q * SECSPERWEEK;
801 
802 #   else
803 
804 	/* Remember: 7*86400 <--> 604800 <--> 128 * 4725 */
805 	uint32_t al = ts->D_s.lo;
806 	uint32_t ah = ts->D_s.hi;
807 
808 	al = (al >> 7) | (ah << 25);
809 	ah = (ah >> 7) & 0x00FFFFFF;
810 
811 	R  = (ts->d_s.hi < 0) ? 2264 : 0;/* sign bit value */
812 	R += (al & 0xFFFF);
813 	R += (al >> 16	 ) * 4111u;	/* 2**16 % 4725 */
814 	R += (ah & 0xFFFF) * 3721u;	/* 2**32 % 4725 */
815 	R += (ah >> 16	 ) * 2206u;	/* 2**48 % 4725 */
816 	R %= 4725u;			/* final reduction */
817 	Q  = (al - R) * 0x98BBADDDu;	/* modinv(4725, 2**32) */
818 	R  = (R << 7) | (ts->d_s.lo & 0x07F);
819 
820 #   endif
821 
822 	res.hi = uint32_2cpl_to_int32(Q);
823 	res.lo = R;
824 
825 	return res;
826 }
827 
828 /*
829  *---------------------------------------------------------------------
830  * Split a 32bit seconds value into h/m/s and excessive days.  This
831  * function happily accepts negative time values as timestamps before
832  * midnight.
833  *---------------------------------------------------------------------
834  */
835 static int32_t
priv_timesplit(int32_t split[3],int32_t ts)836 priv_timesplit(
837 	int32_t split[3],
838 	int32_t ts
839 	)
840 {
841 	/* Do 3 chained floor divisions by positive constants, using the
842 	 * one's complement trick and factoring out the intermediate XOR
843 	 * ops to reduce the number of operations.
844 	 */
845 	uint32_t us, um, uh, ud, sf32;
846 
847 	sf32 = int32_sflag(ts);
848 
849 	us = (uint32_t)ts;
850 	um = (sf32 ^ us) / SECSPERMIN;
851 	uh = um / MINSPERHR;
852 	ud = uh / HRSPERDAY;
853 
854 	um ^= sf32;
855 	uh ^= sf32;
856 	ud ^= sf32;
857 
858 	split[0] = (int32_t)(uh - ud * HRSPERDAY );
859 	split[1] = (int32_t)(um - uh * MINSPERHR );
860 	split[2] = (int32_t)(us - um * SECSPERMIN);
861 
862 	return uint32_2cpl_to_int32(ud);
863 }
864 
865 /*
866  *---------------------------------------------------------------------
867  * Given the number of elapsed days in the calendar era, split this
868  * number into the number of elapsed years in 'res.hi' and the number
869  * of elapsed days of that year in 'res.lo'.
870  *
871  * if 'isleapyear' is not NULL, it will receive an integer that is 0 for
872  * regular years and a non-zero value for leap years.
873  *---------------------------------------------------------------------
874  */
875 ntpcal_split
ntpcal_split_eradays(int32_t days,int * isleapyear)876 ntpcal_split_eradays(
877 	int32_t days,
878 	int  *isleapyear
879 	)
880 {
881 	/* Use the fast cycle split algorithm here, to calculate the
882 	 * centuries and years in a century with one division each. This
883 	 * reduces the number of division operations to two, but is
884 	 * susceptible to internal range overflow. We take some extra
885 	 * steps to avoid the gap.
886 	 */
887 	ntpcal_split res;
888 	int32_t	 n100, n001; /* calendar year cycles */
889 	uint32_t uday, Q;
890 
891 	/* split off centuries first
892 	 *
893 	 * We want to execute '(days * 4 + 3) /% 146097' under floor
894 	 * division rules in the first step. Well, actually we want to
895 	 * calculate 'floor((days + 0.75) / 36524.25)', but we want to
896 	 * do it in scaled integer calculation.
897 	 */
898 #   if defined(HAVE_64BITREGS)
899 
900 	/* not too complicated with an intermediate 64bit value */
901 	uint64_t	ud64, sf64;
902 	ud64 = ((uint64_t)days << 2) | 3u;
903 	sf64 = (uint64_t)-(days < 0);
904 	Q    = (uint32_t)(sf64 ^ ((sf64 ^ ud64) / GREGORIAN_CYCLE_DAYS));
905 	uday = (uint32_t)(ud64 - Q * GREGORIAN_CYCLE_DAYS);
906 	n100 = uint32_2cpl_to_int32(Q);
907 
908 #   else
909 
910 	/* '4*days+3' suffers from range overflow when going to the
911 	 * limits. We solve this by doing an exact division (mod 2^32)
912 	 * after caclulating the remainder first.
913 	 *
914 	 * We start with a partial reduction by digit sums, extracting
915 	 * the upper bits from the original value before they get lost
916 	 * by scaling, and do one full division step to get the true
917 	 * remainder.  Then a final multiplication with the
918 	 * multiplicative inverse of 146097 (mod 2^32) gives us the full
919 	 * quotient.
920 	 *
921 	 * (-2^33) % 146097	--> 130717    : the sign bit value
922 	 * ( 2^20) % 146097	--> 25897     : the upper digit value
923 	 * modinv(146097, 2^32) --> 660721233 : the inverse
924 	 */
925 	uint32_t ux = ((uint32_t)days << 2) | 3;
926 	uday  = (days < 0) ? 130717u : 0u;	    /* sign dgt */
927 	uday += ((days >> 18) & 0x01FFFu) * 25897u; /* hi dgt (src!) */
928 	uday += (ux & 0xFFFFFu);		    /* lo dgt */
929 	uday %= GREGORIAN_CYCLE_DAYS;		    /* full reduction */
930 	Q     = (ux  - uday) * 660721233u;	    /* exact div */
931 	n100  = uint32_2cpl_to_int32(Q);
932 
933 #   endif
934 
935 	/* Split off years in century -- days >= 0 here, and we're far
936 	 * away from integer overflow trouble now. */
937 	uday |= 3;
938 	n001  = uday / GREGORIAN_NORMAL_LEAP_CYCLE_DAYS;
939 	uday -= n001 * GREGORIAN_NORMAL_LEAP_CYCLE_DAYS;
940 
941 	/* Assemble the year and day in year */
942 	res.hi = n100 * 100 + n001;
943 	res.lo = uday / 4u;
944 
945 	/* Possibly set the leap year flag */
946 	if (isleapyear) {
947 		uint32_t tc = (uint32_t)n100 + 1;
948 		uint32_t ty = (uint32_t)n001 + 1;
949 		*isleapyear = !(ty & 3)
950 		    && ((ty != 100) || !(tc & 3));
951 	}
952 	return res;
953 }
954 
955 /*
956  *---------------------------------------------------------------------
957  * Given a number of elapsed days in a year and a leap year indicator,
958  * split the number of elapsed days into the number of elapsed months in
959  * 'res.hi' and the number of elapsed days of that month in 'res.lo'.
960  *
961  * This function will fail and return {-1,-1} if the number of elapsed
962  * days is not in the valid range!
963  *---------------------------------------------------------------------
964  */
965 ntpcal_split
ntpcal_split_yeardays(int32_t eyd,int isleap)966 ntpcal_split_yeardays(
967 	int32_t eyd,
968 	int	isleap
969 	)
970 {
971 	/* Use the unshifted-year, February-with-30-days approach here.
972 	 * Fractional interpolations are used in both directions, with
973 	 * the smallest power-of-two divider to avoid any true division.
974 	 */
975 	ntpcal_split	res = {-1, -1};
976 
977 	/* convert 'isleap' to number of defective days */
978 	isleap = 1 + !isleap;
979 	/* adjust for February of 30 nominal days */
980 	if (eyd >= 61 - isleap)
981 		eyd += isleap;
982 	/* if in range, convert to months and days in month */
983 	if (eyd >= 0 && eyd < 367) {
984 		res.hi = (eyd * 67 + 32) >> 11;
985 		res.lo = eyd - ((489 * res.hi + 8) >> 4);
986 	}
987 
988 	return res;
989 }
990 
991 /*
992  *---------------------------------------------------------------------
993  * Convert a RD into the date part of a 'struct calendar'.
994  *---------------------------------------------------------------------
995  */
996 int
ntpcal_rd_to_date(struct calendar * jd,int32_t rd)997 ntpcal_rd_to_date(
998 	struct calendar *jd,
999 	int32_t		 rd
1000 	)
1001 {
1002 	ntpcal_split split;
1003 	int	     leapy;
1004 	u_int	     ymask;
1005 
1006 	/* Get day-of-week first. It's simply the RD (mod 7)... */
1007 	jd->weekday = i32mod7(rd);
1008 
1009 	split = ntpcal_split_eradays(rd - 1, &leapy);
1010 	/* Get year and day-of-year, with overflow check. If any of the
1011 	 * upper 16 bits is set after shifting to unity-based years, we
1012 	 * will have an overflow when converting to an unsigned 16bit
1013 	 * year. Shifting to the right is OK here, since it does not
1014 	 * matter if the shift is logic or arithmetic.
1015 	 */
1016 	split.hi += 1;
1017 	ymask = 0u - ((split.hi >> 16) == 0);
1018 	jd->year = (uint16_t)(split.hi & ymask);
1019 	jd->yearday = (uint16_t)split.lo + 1;
1020 
1021 	/* convert to month and mday */
1022 	split = ntpcal_split_yeardays(split.lo, leapy);
1023 	jd->month    = (uint8_t)split.hi + 1;
1024 	jd->monthday = (uint8_t)split.lo + 1;
1025 
1026 	return ymask ? leapy : -1;
1027 }
1028 
1029 /*
1030  *---------------------------------------------------------------------
1031  * Convert a RD into the date part of a 'struct tm'.
1032  *---------------------------------------------------------------------
1033  */
1034 int
ntpcal_rd_to_tm(struct tm * utm,int32_t rd)1035 ntpcal_rd_to_tm(
1036 	struct tm  *utm,
1037 	int32_t	    rd
1038 	)
1039 {
1040 	ntpcal_split split;
1041 	int	     leapy;
1042 
1043 	/* get day-of-week first */
1044 	utm->tm_wday = i32mod7(rd);
1045 
1046 	/* get year and day-of-year */
1047 	split = ntpcal_split_eradays(rd - 1, &leapy);
1048 	utm->tm_year = split.hi - 1899;
1049 	utm->tm_yday = split.lo;	/* 0-based */
1050 
1051 	/* convert to month and mday */
1052 	split = ntpcal_split_yeardays(split.lo, leapy);
1053 	utm->tm_mon  = split.hi;	/* 0-based */
1054 	utm->tm_mday = split.lo + 1;	/* 1-based */
1055 
1056 	return leapy;
1057 }
1058 
1059 /*
1060  *---------------------------------------------------------------------
1061  * Take a value of seconds since midnight and split it into hhmmss in a
1062  * 'struct calendar'.
1063  *---------------------------------------------------------------------
1064  */
1065 int32_t
ntpcal_daysec_to_date(struct calendar * jd,int32_t sec)1066 ntpcal_daysec_to_date(
1067 	struct calendar *jd,
1068 	int32_t		sec
1069 	)
1070 {
1071 	int32_t days;
1072 	int   ts[3];
1073 
1074 	days = priv_timesplit(ts, sec);
1075 	jd->hour   = (uint8_t)ts[0];
1076 	jd->minute = (uint8_t)ts[1];
1077 	jd->second = (uint8_t)ts[2];
1078 
1079 	return days;
1080 }
1081 
1082 /*
1083  *---------------------------------------------------------------------
1084  * Take a value of seconds since midnight and split it into hhmmss in a
1085  * 'struct tm'.
1086  *---------------------------------------------------------------------
1087  */
1088 int32_t
ntpcal_daysec_to_tm(struct tm * utm,int32_t sec)1089 ntpcal_daysec_to_tm(
1090 	struct tm *utm,
1091 	int32_t	   sec
1092 	)
1093 {
1094 	int32_t days;
1095 	int32_t ts[3];
1096 
1097 	days = priv_timesplit(ts, sec);
1098 	utm->tm_hour = ts[0];
1099 	utm->tm_min  = ts[1];
1100 	utm->tm_sec  = ts[2];
1101 
1102 	return days;
1103 }
1104 
1105 /*
1106  *---------------------------------------------------------------------
1107  * take a split representation for day/second-of-day and day offset
1108  * and convert it to a 'struct calendar'. The seconds will be normalised
1109  * into the range of a day, and the day will be adjusted accordingly.
1110  *
1111  * returns >0 if the result is in a leap year, 0 if in a regular
1112  * year and <0 if the result did not fit into the calendar struct.
1113  *---------------------------------------------------------------------
1114  */
1115 int
ntpcal_daysplit_to_date(struct calendar * jd,const ntpcal_split * ds,int32_t dof)1116 ntpcal_daysplit_to_date(
1117 	struct calendar	   *jd,
1118 	const ntpcal_split *ds,
1119 	int32_t		    dof
1120 	)
1121 {
1122 	dof += ntpcal_daysec_to_date(jd, ds->lo);
1123 	return ntpcal_rd_to_date(jd, ds->hi + dof);
1124 }
1125 
1126 /*
1127  *---------------------------------------------------------------------
1128  * take a split representation for day/second-of-day and day offset
1129  * and convert it to a 'struct tm'. The seconds will be normalised
1130  * into the range of a day, and the day will be adjusted accordingly.
1131  *
1132  * returns 1 if the result is in a leap year and zero if in a regular
1133  * year.
1134  *---------------------------------------------------------------------
1135  */
1136 int
ntpcal_daysplit_to_tm(struct tm * utm,const ntpcal_split * ds,int32_t dof)1137 ntpcal_daysplit_to_tm(
1138 	struct tm	   *utm,
1139 	const ntpcal_split *ds ,
1140 	int32_t		    dof
1141 	)
1142 {
1143 	dof += ntpcal_daysec_to_tm(utm, ds->lo);
1144 
1145 	return ntpcal_rd_to_tm(utm, ds->hi + dof);
1146 }
1147 
1148 /*
1149  *---------------------------------------------------------------------
1150  * Take a UN*X time and convert to a calendar structure.
1151  *---------------------------------------------------------------------
1152  */
1153 int
ntpcal_time_to_date(struct calendar * jd,const vint64 * ts)1154 ntpcal_time_to_date(
1155 	struct calendar	*jd,
1156 	const vint64	*ts
1157 	)
1158 {
1159 	ntpcal_split ds;
1160 
1161 	ds = ntpcal_daysplit(ts);
1162 	ds.hi += ntpcal_daysec_to_date(jd, ds.lo);
1163 	ds.hi += DAY_UNIX_STARTS;
1164 
1165 	return ntpcal_rd_to_date(jd, ds.hi);
1166 }
1167 
1168 
1169 /*
1170  * ====================================================================
1171  *
1172  * merging composite entities
1173  *
1174  * ====================================================================
1175  */
1176 
1177 #if !defined(HAVE_INT64)
1178 /* multiplication helper. Seconds in days and weeks are multiples of 128,
1179  * and without that factor fit well into 16 bit. So a multiplication
1180  * of 32bit by 16bit and some shifting can be used on pure 32bit machines
1181  * with compilers that do not support 64bit integers.
1182  *
1183  * Calculate ( hi * mul * 128 ) + lo
1184  */
1185 static vint64
_dwjoin(uint16_t mul,int32_t hi,int32_t lo)1186 _dwjoin(
1187 	uint16_t	mul,
1188 	int32_t		hi,
1189 	int32_t		lo
1190 	)
1191 {
1192 	vint64		res;
1193 	uint32_t	p1, p2, sf;
1194 
1195 	/* get sign flag and absolute value of 'hi' in p1 */
1196 	sf = (uint32_t)-(hi < 0);
1197 	p1 = ((uint32_t)hi + sf) ^ sf;
1198 
1199 	/* assemble major units: res <- |hi| * mul */
1200 	res.D_s.lo = (p1 & 0xFFFF) * mul;
1201 	res.D_s.hi = 0;
1202 	p1 = (p1 >> 16) * mul;
1203 	p2 = p1 >> 16;
1204 	p1 = p1 << 16;
1205 	M_ADD(res.D_s.hi, res.D_s.lo, p2, p1);
1206 
1207 	/* mul by 128, using shift: res <-- res << 7 */
1208 	res.D_s.hi = (res.D_s.hi << 7) | (res.D_s.lo >> 25);
1209 	res.D_s.lo = (res.D_s.lo << 7);
1210 
1211 	/* fix up sign: res <-- (res + [sf|sf]) ^ [sf|sf] */
1212 	M_ADD(res.D_s.hi, res.D_s.lo, sf, sf);
1213 	res.D_s.lo ^= sf;
1214 	res.D_s.hi ^= sf;
1215 
1216 	/* properly add seconds: res <-- res + [sx(lo)|lo] */
1217 	p2 = (uint32_t)-(lo < 0);
1218 	p1 = (uint32_t)lo;
1219 	M_ADD(res.D_s.hi, res.D_s.lo, p2, p1);
1220 	return res;
1221 }
1222 #endif
1223 
1224 /*
1225  *---------------------------------------------------------------------
1226  * Merge a number of days and a number of seconds into seconds,
1227  * expressed in 64 bits to avoid overflow.
1228  *---------------------------------------------------------------------
1229  */
1230 vint64
ntpcal_dayjoin(int32_t days,int32_t secs)1231 ntpcal_dayjoin(
1232 	int32_t days,
1233 	int32_t secs
1234 	)
1235 {
1236 	vint64 res;
1237 
1238 #   if defined(HAVE_INT64)
1239 
1240 	res.q_s	 = days;
1241 	res.q_s *= SECSPERDAY;
1242 	res.q_s += secs;
1243 
1244 #   else
1245 
1246 	res = _dwjoin(675, days, secs);
1247 
1248 #   endif
1249 
1250 	return res;
1251 }
1252 
1253 /*
1254  *---------------------------------------------------------------------
1255  * Merge a number of weeks and a number of seconds into seconds,
1256  * expressed in 64 bits to avoid overflow.
1257  *---------------------------------------------------------------------
1258  */
1259 vint64
ntpcal_weekjoin(int32_t week,int32_t secs)1260 ntpcal_weekjoin(
1261 	int32_t week,
1262 	int32_t secs
1263 	)
1264 {
1265 	vint64 res;
1266 
1267 #   if defined(HAVE_INT64)
1268 
1269 	res.q_s	 = week;
1270 	res.q_s *= SECSPERWEEK;
1271 	res.q_s += secs;
1272 
1273 #   else
1274 
1275 	res = _dwjoin(4725, week, secs);
1276 
1277 #   endif
1278 
1279 	return res;
1280 }
1281 
1282 /*
1283  *---------------------------------------------------------------------
1284  * get leap years since epoch in elapsed years
1285  *---------------------------------------------------------------------
1286  */
1287 int32_t
ntpcal_leapyears_in_years(int32_t years)1288 ntpcal_leapyears_in_years(
1289 	int32_t years
1290 	)
1291 {
1292 	/* We use the in-out-in algorithm here, using the one's
1293 	 * complement division trick for negative numbers. The chained
1294 	 * division sequence by 4/25/4 gives the compiler the chance to
1295 	 * get away with only one true division and doing shifts otherwise.
1296 	 */
1297 
1298 	uint32_t sf32, sum, uyear;
1299 
1300 	sf32  = int32_sflag(years);
1301 	uyear = (uint32_t)years;
1302 	uyear ^= sf32;
1303 
1304 	sum  = (uyear /=  4u);	/*   4yr rule --> IN  */
1305 	sum -= (uyear /= 25u);	/* 100yr rule --> OUT */
1306 	sum += (uyear /=  4u);	/* 400yr rule --> IN  */
1307 
1308 	/* Thanks to the alternation of IN/OUT/IN we can do the sum
1309 	 * directly and have a single one's complement operation
1310 	 * here. (Only if the years are negative, of course.) Otherwise
1311 	 * the one's complement would have to be done when
1312 	 * adding/subtracting the terms.
1313 	 */
1314 	return uint32_2cpl_to_int32(sf32 ^ sum);
1315 }
1316 
1317 /*
1318  *---------------------------------------------------------------------
1319  * Convert elapsed years in Era into elapsed days in Era.
1320  *---------------------------------------------------------------------
1321  */
1322 int32_t
ntpcal_days_in_years(int32_t years)1323 ntpcal_days_in_years(
1324 	int32_t years
1325 	)
1326 {
1327 	return years * DAYSPERYEAR + ntpcal_leapyears_in_years(years);
1328 }
1329 
1330 /*
1331  *---------------------------------------------------------------------
1332  * Convert a number of elapsed month in a year into elapsed days in year.
1333  *
1334  * The month will be normalized, and 'res.hi' will contain the
1335  * excessive years that must be considered when converting the years,
1336  * while 'res.lo' will contain the number of elapsed days since start
1337  * of the year.
1338  *
1339  * This code uses the shifted-month-approach to convert month to days,
1340  * because then there is no need to have explicit leap year
1341  * information.	 The slight disadvantage is that for most month values
1342  * the result is a negative value, and the year excess is one; the
1343  * conversion is then simply based on the start of the following year.
1344  *---------------------------------------------------------------------
1345  */
1346 ntpcal_split
ntpcal_days_in_months(int32_t m)1347 ntpcal_days_in_months(
1348 	int32_t m
1349 	)
1350 {
1351 	ntpcal_split res;
1352 
1353 	/* Add ten months with proper year adjustment. */
1354 	if (m < 2) {
1355 	    res.lo  = m + 10;
1356 	    res.hi  = 0;
1357 	} else {
1358 	    res.lo  = m - 2;
1359 	    res.hi  = 1;
1360 	}
1361 
1362 	/* Possibly normalise by floor division. This does not hapen for
1363 	 * input in normal range. */
1364 	if (res.lo < 0 || res.lo >= 12) {
1365 		uint32_t mu, Q, sf32;
1366 		sf32 = int32_sflag(res.lo);
1367 		mu   = (uint32_t)res.lo;
1368 		Q    = sf32 ^ ((sf32 ^ mu) / 12u);
1369 
1370 		res.hi += uint32_2cpl_to_int32(Q);
1371 		res.lo	= mu - Q * 12u;
1372 	}
1373 
1374 	/* Get cummulated days in year with unshift. Use the fractional
1375 	 * interpolation with smallest possible power of two in the
1376 	 * divider.
1377 	 */
1378 	res.lo = ((res.lo * 979 + 16) >> 5) - 306;
1379 
1380 	return res;
1381 }
1382 
1383 /*
1384  *---------------------------------------------------------------------
1385  * Convert ELAPSED years/months/days of gregorian calendar to elapsed
1386  * days in Gregorian epoch.
1387  *
1388  * If you want to convert years and days-of-year, just give a month of
1389  * zero.
1390  *---------------------------------------------------------------------
1391  */
1392 int32_t
ntpcal_edate_to_eradays(int32_t years,int32_t mons,int32_t mdays)1393 ntpcal_edate_to_eradays(
1394 	int32_t years,
1395 	int32_t mons,
1396 	int32_t mdays
1397 	)
1398 {
1399 	ntpcal_split tmp;
1400 	int32_t	     res;
1401 
1402 	if (mons) {
1403 		tmp = ntpcal_days_in_months(mons);
1404 		res = ntpcal_days_in_years(years + tmp.hi) + tmp.lo;
1405 	} else
1406 		res = ntpcal_days_in_years(years);
1407 	res += mdays;
1408 
1409 	return res;
1410 }
1411 
1412 /*
1413  *---------------------------------------------------------------------
1414  * Convert ELAPSED years/months/days of gregorian calendar to elapsed
1415  * days in year.
1416  *
1417  * Note: This will give the true difference to the start of the given
1418  * year, even if months & days are off-scale.
1419  *---------------------------------------------------------------------
1420  */
1421 int32_t
ntpcal_edate_to_yeardays(int32_t years,int32_t mons,int32_t mdays)1422 ntpcal_edate_to_yeardays(
1423 	int32_t years,
1424 	int32_t mons,
1425 	int32_t mdays
1426 	)
1427 {
1428 	ntpcal_split tmp;
1429 
1430 	if (0 <= mons && mons < 12) {
1431 		if (mons >= 2)
1432 			mdays -= 2 - is_leapyear(years+1);
1433 		mdays += (489 * mons + 8) >> 4;
1434 	} else {
1435 		tmp = ntpcal_days_in_months(mons);
1436 		mdays += tmp.lo
1437 		       + ntpcal_days_in_years(years + tmp.hi)
1438 		       - ntpcal_days_in_years(years);
1439 	}
1440 
1441 	return mdays;
1442 }
1443 
1444 /*
1445  *---------------------------------------------------------------------
1446  * Convert elapsed days and the hour/minute/second information into
1447  * total seconds.
1448  *
1449  * If 'isvalid' is not NULL, do a range check on the time specification
1450  * and tell if the time input is in the normal range, permitting for a
1451  * single leapsecond.
1452  *---------------------------------------------------------------------
1453  */
1454 int32_t
ntpcal_etime_to_seconds(int32_t hours,int32_t minutes,int32_t seconds)1455 ntpcal_etime_to_seconds(
1456 	int32_t hours,
1457 	int32_t minutes,
1458 	int32_t seconds
1459 	)
1460 {
1461 	int32_t res;
1462 
1463 	res = (hours * MINSPERHR + minutes) * SECSPERMIN + seconds;
1464 
1465 	return res;
1466 }
1467 
1468 /*
1469  *---------------------------------------------------------------------
1470  * Convert the date part of a 'struct tm' (that is, year, month,
1471  * day-of-month) into the RD of that day.
1472  *---------------------------------------------------------------------
1473  */
1474 int32_t
ntpcal_tm_to_rd(const struct tm * utm)1475 ntpcal_tm_to_rd(
1476 	const struct tm *utm
1477 	)
1478 {
1479 	return ntpcal_edate_to_eradays(utm->tm_year + 1899,
1480 				       utm->tm_mon,
1481 				       utm->tm_mday - 1) + 1;
1482 }
1483 
1484 /*
1485  *---------------------------------------------------------------------
1486  * Convert the date part of a 'struct calendar' (that is, year, month,
1487  * day-of-month) into the RD of that day.
1488  *---------------------------------------------------------------------
1489  */
1490 int32_t
ntpcal_date_to_rd(const struct calendar * jd)1491 ntpcal_date_to_rd(
1492 	const struct calendar *jd
1493 	)
1494 {
1495 	return ntpcal_edate_to_eradays((int32_t)jd->year - 1,
1496 				       (int32_t)jd->month - 1,
1497 				       (int32_t)jd->monthday - 1) + 1;
1498 }
1499 
1500 /*
1501  *---------------------------------------------------------------------
1502  * convert a year number to rata die of year start
1503  *---------------------------------------------------------------------
1504  */
1505 int32_t
ntpcal_year_to_ystart(int32_t year)1506 ntpcal_year_to_ystart(
1507 	int32_t year
1508 	)
1509 {
1510 	return ntpcal_days_in_years(year - 1) + 1;
1511 }
1512 
1513 /*
1514  *---------------------------------------------------------------------
1515  * For a given RD, get the RD of the associated year start,
1516  * that is, the RD of the last January,1st on or before that day.
1517  *---------------------------------------------------------------------
1518  */
1519 int32_t
ntpcal_rd_to_ystart(int32_t rd)1520 ntpcal_rd_to_ystart(
1521 	int32_t rd
1522 	)
1523 {
1524 	/*
1525 	 * Rather simple exercise: split the day number into elapsed
1526 	 * years and elapsed days, then remove the elapsed days from the
1527 	 * input value. Nice'n sweet...
1528 	 */
1529 	return rd - ntpcal_split_eradays(rd - 1, NULL).lo;
1530 }
1531 
1532 /*
1533  *---------------------------------------------------------------------
1534  * For a given RD, get the RD of the associated month start.
1535  *---------------------------------------------------------------------
1536  */
1537 int32_t
ntpcal_rd_to_mstart(int32_t rd)1538 ntpcal_rd_to_mstart(
1539 	int32_t rd
1540 	)
1541 {
1542 	ntpcal_split split;
1543 	int	     leaps;
1544 
1545 	split = ntpcal_split_eradays(rd - 1, &leaps);
1546 	split = ntpcal_split_yeardays(split.lo, leaps);
1547 
1548 	return rd - split.lo;
1549 }
1550 
1551 /*
1552  *---------------------------------------------------------------------
1553  * take a 'struct calendar' and get the seconds-of-day from it.
1554  *---------------------------------------------------------------------
1555  */
1556 int32_t
ntpcal_date_to_daysec(const struct calendar * jd)1557 ntpcal_date_to_daysec(
1558 	const struct calendar *jd
1559 	)
1560 {
1561 	return ntpcal_etime_to_seconds(jd->hour, jd->minute,
1562 				       jd->second);
1563 }
1564 
1565 /*
1566  *---------------------------------------------------------------------
1567  * take a 'struct tm' and get the seconds-of-day from it.
1568  *---------------------------------------------------------------------
1569  */
1570 int32_t
ntpcal_tm_to_daysec(const struct tm * utm)1571 ntpcal_tm_to_daysec(
1572 	const struct tm *utm
1573 	)
1574 {
1575 	return ntpcal_etime_to_seconds(utm->tm_hour, utm->tm_min,
1576 				       utm->tm_sec);
1577 }
1578 
1579 /*
1580  *---------------------------------------------------------------------
1581  * take a 'struct calendar' and convert it to a 'time_t'
1582  *---------------------------------------------------------------------
1583  */
1584 time_t
ntpcal_date_to_time(const struct calendar * jd)1585 ntpcal_date_to_time(
1586 	const struct calendar *jd
1587 	)
1588 {
1589 	vint64	join;
1590 	int32_t days, secs;
1591 
1592 	days = ntpcal_date_to_rd(jd) - DAY_UNIX_STARTS;
1593 	secs = ntpcal_date_to_daysec(jd);
1594 	join = ntpcal_dayjoin(days, secs);
1595 
1596 	return vint64_to_time(&join);
1597 }
1598 
1599 
1600 /*
1601  * ====================================================================
1602  *
1603  * extended and unchecked variants of caljulian/caltontp
1604  *
1605  * ====================================================================
1606  */
1607 int
ntpcal_ntp64_to_date(struct calendar * jd,const vint64 * ntp)1608 ntpcal_ntp64_to_date(
1609 	struct calendar *jd,
1610 	const vint64	*ntp
1611 	)
1612 {
1613 	ntpcal_split ds;
1614 
1615 	ds = ntpcal_daysplit(ntp);
1616 	ds.hi += ntpcal_daysec_to_date(jd, ds.lo);
1617 
1618 	return ntpcal_rd_to_date(jd, ds.hi + DAY_NTP_STARTS);
1619 }
1620 
1621 int
ntpcal_ntp_to_date(struct calendar * jd,uint32_t ntp,const time_t * piv)1622 ntpcal_ntp_to_date(
1623 	struct calendar *jd,
1624 	uint32_t	 ntp,
1625 	const time_t	*piv
1626 	)
1627 {
1628 	vint64	ntp64;
1629 
1630 	/*
1631 	 * Unfold ntp time around current time into NTP domain. Split
1632 	 * into days and seconds, shift days into CE domain and
1633 	 * process the parts.
1634 	 */
1635 	ntp64 = ntpcal_ntp_to_ntp(ntp, piv);
1636 	return ntpcal_ntp64_to_date(jd, &ntp64);
1637 }
1638 
1639 
1640 vint64
ntpcal_date_to_ntp64(const struct calendar * jd)1641 ntpcal_date_to_ntp64(
1642 	const struct calendar *jd
1643 	)
1644 {
1645 	/*
1646 	 * Convert date to NTP. Ignore yearday, use d/m/y only.
1647 	 */
1648 	return ntpcal_dayjoin(ntpcal_date_to_rd(jd) - DAY_NTP_STARTS,
1649 			      ntpcal_date_to_daysec(jd));
1650 }
1651 
1652 
1653 uint32_t
ntpcal_date_to_ntp(const struct calendar * jd)1654 ntpcal_date_to_ntp(
1655 	const struct calendar *jd
1656 	)
1657 {
1658 	/*
1659 	 * Get lower half of 64bit NTP timestamp from date/time.
1660 	 */
1661 	return ntpcal_date_to_ntp64(jd).d_s.lo;
1662 }
1663 
1664 
1665 
1666 /*
1667  * ====================================================================
1668  *
1669  * day-of-week calculations
1670  *
1671  * ====================================================================
1672  */
1673 /*
1674  * Given a RataDie and a day-of-week, calculate a RDN that is reater-than,
1675  * greater-or equal, closest, less-or-equal or less-than the given RDN
1676  * and denotes the given day-of-week
1677  */
1678 int32_t
ntpcal_weekday_gt(int32_t rdn,int32_t dow)1679 ntpcal_weekday_gt(
1680 	int32_t rdn,
1681 	int32_t dow
1682 	)
1683 {
1684 	return ntpcal_periodic_extend(rdn+1, dow, 7);
1685 }
1686 
1687 int32_t
ntpcal_weekday_ge(int32_t rdn,int32_t dow)1688 ntpcal_weekday_ge(
1689 	int32_t rdn,
1690 	int32_t dow
1691 	)
1692 {
1693 	return ntpcal_periodic_extend(rdn, dow, 7);
1694 }
1695 
1696 int32_t
ntpcal_weekday_close(int32_t rdn,int32_t dow)1697 ntpcal_weekday_close(
1698 	int32_t rdn,
1699 	int32_t dow
1700 	)
1701 {
1702 	return ntpcal_periodic_extend(rdn-3, dow, 7);
1703 }
1704 
1705 int32_t
ntpcal_weekday_le(int32_t rdn,int32_t dow)1706 ntpcal_weekday_le(
1707 	int32_t rdn,
1708 	int32_t dow
1709 	)
1710 {
1711 	return ntpcal_periodic_extend(rdn, dow, -7);
1712 }
1713 
1714 int32_t
ntpcal_weekday_lt(int32_t rdn,int32_t dow)1715 ntpcal_weekday_lt(
1716 	int32_t rdn,
1717 	int32_t dow
1718 	)
1719 {
1720 	return ntpcal_periodic_extend(rdn-1, dow, -7);
1721 }
1722 
1723 /*
1724  * ====================================================================
1725  *
1726  * ISO week-calendar conversions
1727  *
1728  * The ISO8601 calendar defines a calendar of years, weeks and weekdays.
1729  * It is related to the Gregorian calendar, and a ISO year starts at the
1730  * Monday closest to Jan,1st of the corresponding Gregorian year.  A ISO
1731  * calendar year has always 52 or 53 weeks, and like the Grogrian
1732  * calendar the ISO8601 calendar repeats itself every 400 years, or
1733  * 146097 days, or 20871 weeks.
1734  *
1735  * While it is possible to write ISO calendar functions based on the
1736  * Gregorian calendar functions, the following implementation takes a
1737  * different approach, based directly on years and weeks.
1738  *
1739  * Analysis of the tabulated data shows that it is not possible to
1740  * interpolate from years to weeks over a full 400 year range; cyclic
1741  * shifts over 400 years do not provide a solution here. But it *is*
1742  * possible to interpolate over every single century of the 400-year
1743  * cycle. (The centennial leap year rule seems to be the culprit here.)
1744  *
1745  * It can be shown that a conversion from years to weeks can be done
1746  * using a linear transformation of the form
1747  *
1748  *   w = floor( y * a + b )
1749  *
1750  * where the slope a must hold to
1751  *
1752  *  52.1780821918 <= a < 52.1791044776
1753  *
1754  * and b must be chosen according to the selected slope and the number
1755  * of the century in a 400-year period.
1756  *
1757  * The inverse calculation can also be done in this way. Careful scaling
1758  * provides an unlimited set of integer coefficients a,k,b that enable
1759  * us to write the calulation in the form
1760  *
1761  *   w = (y * a	 + b ) / k
1762  *   y = (w * a' + b') / k'
1763  *
1764  * In this implementation the values of k and k' are chosen to be the
1765  * smallest possible powers of two, so the division can be implemented
1766  * as shifts if the optimiser chooses to do so.
1767  *
1768  * ====================================================================
1769  */
1770 
1771 /*
1772  * Given a number of elapsed (ISO-)years since the begin of the
1773  * christian era, return the number of elapsed weeks corresponding to
1774  * the number of years.
1775  */
1776 int32_t
isocal_weeks_in_years(int32_t years)1777 isocal_weeks_in_years(
1778 	int32_t years
1779 	)
1780 {
1781 	/*
1782 	 * use: w = (y * 53431 + b[c]) / 1024 as interpolation
1783 	 */
1784 	static const uint16_t bctab[4] = { 157, 449, 597, 889 };
1785 
1786 	int32_t	 cs, cw;
1787 	uint32_t cc, ci, yu, sf32;
1788 
1789 	sf32 = int32_sflag(years);
1790 	yu   = (uint32_t)years;
1791 
1792 	/* split off centuries, using floor division */
1793 	cc  = sf32 ^ ((sf32 ^ yu) / 100u);
1794 	yu -= cc * 100u;
1795 
1796 	/* calculate century cycles shift and cycle index:
1797 	 * Assuming a century is 5217 weeks, we have to add a cycle
1798 	 * shift that is 3 for every 4 centuries, because 3 of the four
1799 	 * centuries have 5218 weeks. So '(cc*3 + 1) / 4' is the actual
1800 	 * correction, and the second century is the defective one.
1801 	 *
1802 	 * Needs floor division by 4, which is done with masking and
1803 	 * shifting.
1804 	 */
1805 	ci = cc * 3u + 1;
1806 	cs = uint32_2cpl_to_int32(sf32 ^ ((sf32 ^ ci) >> 2));
1807 	ci = ci & 3u;
1808 
1809 	/* Get weeks in century. Can use plain division here as all ops
1810 	 * are >= 0,  and let the compiler sort out the possible
1811 	 * optimisations.
1812 	 */
1813 	cw = (yu * 53431u + bctab[ci]) / 1024u;
1814 
1815 	return uint32_2cpl_to_int32(cc) * 5217 + cs + cw;
1816 }
1817 
1818 /*
1819  * Given a number of elapsed weeks since the begin of the christian
1820  * era, split this number into the number of elapsed years in res.hi
1821  * and the excessive number of weeks in res.lo. (That is, res.lo is
1822  * the number of elapsed weeks in the remaining partial year.)
1823  */
1824 ntpcal_split
isocal_split_eraweeks(int32_t weeks)1825 isocal_split_eraweeks(
1826 	int32_t weeks
1827 	)
1828 {
1829 	/*
1830 	 * use: y = (w * 157 + b[c]) / 8192 as interpolation
1831 	 */
1832 
1833 	static const uint16_t bctab[4] = { 85, 130, 17, 62 };
1834 
1835 	ntpcal_split res;
1836 	int32_t	 cc, ci;
1837 	uint32_t sw, cy, Q;
1838 
1839 	/* Use two fast cycle-split divisions again. Herew e want to
1840 	 * execute '(weeks * 4 + 2) /% 20871' under floor division rules
1841 	 * in the first step.
1842 	 *
1843 	 * This is of course (again) susceptible to internal overflow if
1844 	 * coded directly in 32bit. And again we use 64bit division on
1845 	 * a 64bit target and exact division after calculating the
1846 	 * remainder first on a 32bit target. With the smaller divider,
1847 	 * that's even a bit neater.
1848 	 */
1849 #   if defined(HAVE_64BITREGS)
1850 
1851 	/* Full floor division with 64bit values. */
1852 	uint64_t sf64, sw64;
1853 	sf64 = (uint64_t)-(weeks < 0);
1854 	sw64 = ((uint64_t)weeks << 2) | 2u;
1855 	Q    = (uint32_t)(sf64 ^ ((sf64 ^ sw64) / GREGORIAN_CYCLE_WEEKS));
1856 	sw   = (uint32_t)(sw64 - Q * GREGORIAN_CYCLE_WEEKS);
1857 
1858 #   else
1859 
1860 	/* Exact division after calculating the remainder via partial
1861 	 * reduction by digit sum.
1862 	 * (-2^33) % 20871     --> 5491	     : the sign bit value
1863 	 * ( 2^20) % 20871     --> 5026	     : the upper digit value
1864 	 * modinv(20871, 2^32) --> 330081335 : the inverse
1865 	 */
1866 	uint32_t ux = ((uint32_t)weeks << 2) | 2;
1867 	sw  = (weeks < 0) ? 5491u : 0u;		  /* sign dgt */
1868 	sw += ((weeks >> 18) & 0x01FFFu) * 5026u; /* hi dgt (src!) */
1869 	sw += (ux & 0xFFFFFu);			  /* lo dgt */
1870 	sw %= GREGORIAN_CYCLE_WEEKS;		  /* full reduction */
1871 	Q   = (ux  - sw) * 330081335u;		  /* exact div */
1872 
1873 #   endif
1874 
1875 	ci  = Q & 3u;
1876 	cc  = uint32_2cpl_to_int32(Q);
1877 
1878 	/* Split off years; sw >= 0 here! The scaled weeks in the years
1879 	 * are scaled up by 157 afterwards.
1880 	 */
1881 	sw  = (sw / 4u) * 157u + bctab[ci];
1882 	cy  = sw / 8192u;	/* sw >> 13 , let the compiler sort it out */
1883 	sw  = sw % 8192u;	/* sw & 8191, let the compiler sort it out */
1884 
1885 	/* assemble elapsed years and downscale the elapsed weeks in
1886 	 * the year.
1887 	 */
1888 	res.hi = 100*cc + cy;
1889 	res.lo = sw / 157u;
1890 
1891 	return res;
1892 }
1893 
1894 /*
1895  * Given a second in the NTP time scale and a pivot, expand the NTP
1896  * time stamp around the pivot and convert into an ISO calendar time
1897  * stamp.
1898  */
1899 int
isocal_ntp64_to_date(struct isodate * id,const vint64 * ntp)1900 isocal_ntp64_to_date(
1901 	struct isodate *id,
1902 	const vint64   *ntp
1903 	)
1904 {
1905 	ntpcal_split ds;
1906 	int32_t	     ts[3];
1907 	uint32_t     uw, ud, sf32;
1908 
1909 	/*
1910 	 * Split NTP time into days and seconds, shift days into CE
1911 	 * domain and process the parts.
1912 	 */
1913 	ds = ntpcal_daysplit(ntp);
1914 
1915 	/* split time part */
1916 	ds.hi += priv_timesplit(ts, ds.lo);
1917 	id->hour   = (uint8_t)ts[0];
1918 	id->minute = (uint8_t)ts[1];
1919 	id->second = (uint8_t)ts[2];
1920 
1921 	/* split days into days and weeks, using floor division in unsigned */
1922 	ds.hi += DAY_NTP_STARTS - 1; /* shift from NTP to RDN */
1923 	sf32 = int32_sflag(ds.hi);
1924 	ud   = (uint32_t)ds.hi;
1925 	uw   = sf32 ^ ((sf32 ^ ud) / DAYSPERWEEK);
1926 	ud  -= uw * DAYSPERWEEK;
1927 
1928 	ds.hi = uint32_2cpl_to_int32(uw);
1929 	ds.lo = ud;
1930 
1931 	id->weekday = (uint8_t)ds.lo + 1;	/* weekday result    */
1932 
1933 	/* get year and week in year */
1934 	ds = isocal_split_eraweeks(ds.hi);	/* elapsed years&week*/
1935 	id->year = (uint16_t)ds.hi + 1;		/* shift to current  */
1936 	id->week = (uint8_t )ds.lo + 1;
1937 
1938 	return (ds.hi >= 0 && ds.hi < 0x0000FFFF);
1939 }
1940 
1941 int
isocal_ntp_to_date(struct isodate * id,uint32_t ntp,const time_t * piv)1942 isocal_ntp_to_date(
1943 	struct isodate *id,
1944 	uint32_t	ntp,
1945 	const time_t   *piv
1946 	)
1947 {
1948 	vint64	ntp64;
1949 
1950 	/*
1951 	 * Unfold ntp time around current time into NTP domain, then
1952 	 * convert the full time stamp.
1953 	 */
1954 	ntp64 = ntpcal_ntp_to_ntp(ntp, piv);
1955 	return isocal_ntp64_to_date(id, &ntp64);
1956 }
1957 
1958 /*
1959  * Convert a ISO date spec into a second in the NTP time scale,
1960  * properly truncated to 32 bit.
1961  */
1962 vint64
isocal_date_to_ntp64(const struct isodate * id)1963 isocal_date_to_ntp64(
1964 	const struct isodate *id
1965 	)
1966 {
1967 	int32_t weeks, days, secs;
1968 
1969 	weeks = isocal_weeks_in_years((int32_t)id->year - 1)
1970 	      + (int32_t)id->week - 1;
1971 	days = weeks * 7 + (int32_t)id->weekday;
1972 	/* days is RDN of ISO date now */
1973 	secs = ntpcal_etime_to_seconds(id->hour, id->minute, id->second);
1974 
1975 	return ntpcal_dayjoin(days - DAY_NTP_STARTS, secs);
1976 }
1977 
1978 uint32_t
isocal_date_to_ntp(const struct isodate * id)1979 isocal_date_to_ntp(
1980 	const struct isodate *id
1981 	)
1982 {
1983 	/*
1984 	 * Get lower half of 64bit NTP timestamp from date/time.
1985 	 */
1986 	return isocal_date_to_ntp64(id).d_s.lo;
1987 }
1988 
1989 /*
1990  * ====================================================================
1991  * 'basedate' support functions
1992  * ====================================================================
1993  */
1994 
1995 static int32_t s_baseday = NTP_TO_UNIX_DAYS;
1996 static int32_t s_gpsweek = 0;
1997 
1998 int32_t
basedate_eval_buildstamp(void)1999 basedate_eval_buildstamp(void)
2000 {
2001 	struct calendar jd;
2002 	int32_t		ed;
2003 
2004 	if (!ntpcal_get_build_date(&jd))
2005 		return NTP_TO_UNIX_DAYS;
2006 
2007 	/* The time zone of the build stamp is unspecified; we remove
2008 	 * one day to provide a certain slack. And in case somebody
2009 	 * fiddled with the system clock, we make sure we do not go
2010 	 * before the UNIX epoch (1970-01-01). It's probably not possible
2011 	 * to do this to the clock on most systems, but there are other
2012 	 * ways to tweak the build stamp.
2013 	 */
2014 	jd.monthday -= 1;
2015 	ed = ntpcal_date_to_rd(&jd) - DAY_NTP_STARTS;
2016 	return (ed < NTP_TO_UNIX_DAYS) ? NTP_TO_UNIX_DAYS : ed;
2017 }
2018 
2019 int32_t
basedate_eval_string(const char * str)2020 basedate_eval_string(
2021 	const char * str
2022 	)
2023 {
2024 	u_short	y,m,d;
2025 	u_long	ned;
2026 	int	rc, nc;
2027 	size_t	sl;
2028 
2029 	sl = strlen(str);
2030 	rc = sscanf(str, "%4hu-%2hu-%2hu%n", &y, &m, &d, &nc);
2031 	if (rc == 3 && (size_t)nc == sl) {
2032 		if (m >= 1 && m <= 12 && d >= 1 && d <= 31)
2033 			return ntpcal_edate_to_eradays(y-1, m-1, d)
2034 			    - DAY_NTP_STARTS;
2035 		goto buildstamp;
2036 	}
2037 
2038 	rc = sscanf(str, "%lu%n", &ned, &nc);
2039 	if (rc == 1 && (size_t)nc == sl) {
2040 		if (ned <= INT32_MAX)
2041 			return (int32_t)ned;
2042 		goto buildstamp;
2043 	}
2044 
2045   buildstamp:
2046 	msyslog(LOG_WARNING,
2047 		"basedate string \"%s\" invalid, build date substituted!",
2048 		str);
2049 	return basedate_eval_buildstamp();
2050 }
2051 
2052 uint32_t
basedate_get_day(void)2053 basedate_get_day(void)
2054 {
2055 	return s_baseday;
2056 }
2057 
2058 int32_t
basedate_set_day(int32_t day)2059 basedate_set_day(
2060 	int32_t day
2061 	)
2062 {
2063 	struct calendar	jd;
2064 	int32_t		retv;
2065 
2066 	/* set NTP base date for NTP era unfolding */
2067 	if (day < NTP_TO_UNIX_DAYS) {
2068 		msyslog(LOG_WARNING,
2069 			"baseday_set_day: invalid day (%lu), UNIX epoch substituted",
2070 			(unsigned long)day);
2071 		day = NTP_TO_UNIX_DAYS;
2072 	}
2073 	retv = s_baseday;
2074 	s_baseday = day;
2075 	ntpcal_rd_to_date(&jd, day + DAY_NTP_STARTS);
2076 	msyslog(LOG_INFO, "basedate set to %04hu-%02hu-%02hu",
2077 		jd.year, (u_short)jd.month, (u_short)jd.monthday);
2078 
2079 	/* set GPS base week for GPS week unfolding */
2080 	day = ntpcal_weekday_ge(day + DAY_NTP_STARTS, CAL_SUNDAY)
2081 	    - DAY_NTP_STARTS;
2082 	if (day < NTP_TO_GPS_DAYS)
2083 	    day = NTP_TO_GPS_DAYS;
2084 	s_gpsweek = (day - NTP_TO_GPS_DAYS) / DAYSPERWEEK;
2085 	ntpcal_rd_to_date(&jd, day + DAY_NTP_STARTS);
2086 	msyslog(LOG_INFO, "gps base set to %04hu-%02hu-%02hu (week %d)",
2087 		jd.year, (u_short)jd.month, (u_short)jd.monthday, s_gpsweek);
2088 
2089 	return retv;
2090 }
2091 
2092 time_t
basedate_get_eracenter(void)2093 basedate_get_eracenter(void)
2094 {
2095 	time_t retv;
2096 	retv  = (time_t)(s_baseday - NTP_TO_UNIX_DAYS);
2097 	retv *= SECSPERDAY;
2098 	retv += (UINT32_C(1) << 31);
2099 	return retv;
2100 }
2101 
2102 time_t
basedate_get_erabase(void)2103 basedate_get_erabase(void)
2104 {
2105 	time_t retv;
2106 	retv  = (time_t)(s_baseday - NTP_TO_UNIX_DAYS);
2107 	retv *= SECSPERDAY;
2108 	return retv;
2109 }
2110 
2111 uint32_t
basedate_get_gpsweek(void)2112 basedate_get_gpsweek(void)
2113 {
2114     return s_gpsweek;
2115 }
2116 
2117 uint32_t
basedate_expand_gpsweek(unsigned short weekno)2118 basedate_expand_gpsweek(
2119     unsigned short weekno
2120     )
2121 {
2122     /* We do a fast modulus expansion here. Since all quantities are
2123      * unsigned and we cannot go before the start of the GPS epoch
2124      * anyway, and since the truncated GPS week number is 10 bit, the
2125      * expansion becomes a simple sub/and/add sequence.
2126      */
2127     #if GPSWEEKS != 1024
2128     # error GPSWEEKS defined wrong -- should be 1024!
2129     #endif
2130 
2131     uint32_t diff;
2132     diff = ((uint32_t)weekno - s_gpsweek) & (GPSWEEKS - 1);
2133     return s_gpsweek + diff;
2134 }
2135 
2136 /*
2137  * ====================================================================
2138  * misc. helpers
2139  * ====================================================================
2140  */
2141 
2142 /* --------------------------------------------------------------------
2143  * reconstruct the centrury from a truncated date and a day-of-week
2144  *
2145  * Given a date with truncated year (2-digit, 0..99) and a day-of-week
2146  * from 1(Mon) to 7(Sun), recover the full year between 1900AD and 2300AD.
2147  */
2148 int32_t
ntpcal_expand_century(uint32_t y,uint32_t m,uint32_t d,uint32_t wd)2149 ntpcal_expand_century(
2150 	uint32_t y,
2151 	uint32_t m,
2152 	uint32_t d,
2153 	uint32_t wd)
2154 {
2155 	/* This algorithm is short but tricky... It's related to
2156 	 * Zeller's congruence, partially done backwards.
2157 	 *
2158 	 * A few facts to remember:
2159 	 *  1) The Gregorian calendar has a cycle of 400 years.
2160 	 *  2) The weekday of the 1st day of a century shifts by 5 days
2161 	 *     during a great cycle.
2162 	 *  3) For calendar math, a century starts with the 1st year,
2163 	 *     which is year 1, !not! zero.
2164 	 *
2165 	 * So we start with taking the weekday difference (mod 7)
2166 	 * between the truncated date (which is taken as an absolute
2167 	 * date in the 1st century in the proleptic calendar) and the
2168 	 * weekday given.
2169 	 *
2170 	 * When dividing this residual by 5, we obtain the number of
2171 	 * centuries to add to the base. But since the residual is (mod
2172 	 * 7), we have to make this an exact division by multiplication
2173 	 * with the modular inverse of 5 (mod 7), which is 3:
2174 	 *    3*5 === 1 (mod 7).
2175 	 *
2176 	 * If this yields a result of 4/5/6, the given date/day-of-week
2177 	 * combination is impossible, and we return zero as resulting
2178 	 * year to indicate failure.
2179 	 *
2180 	 * Then we remap the century to the range starting with year
2181 	 * 1900.
2182 	 */
2183 
2184 	uint32_t c;
2185 
2186 	/* check basic constraints */
2187 	if ((y >= 100u) || (--m >= 12u) || (--d >= 31u))
2188 		return 0;
2189 
2190 	if ((m += 10u) >= 12u)		/* shift base to prev. March,1st */
2191 		m -= 12u;
2192 	else if (--y >= 100u)
2193 		y += 100u;
2194 	d += y + (y >> 2) + 2u;		/* year share */
2195 	d += (m * 83u + 16u) >> 5;	/* month share */
2196 
2197 	/* get (wd - d), shifted to positive value, and multiply with
2198 	 * 3(mod 7). (Exact division, see to comment)
2199 	 * Note: 1) d <= 184 at this point.
2200 	 *	 2) 252 % 7 == 0, but 'wd' is off by one since we did
2201 	 *	    '--d' above, so we add just 251 here!
2202 	 */
2203 	c = u32mod7(3 * (251u + wd - d));
2204 	if (c > 3u)
2205 		return 0;
2206 
2207 	if ((m > 9u) && (++y >= 100u)) {/* undo base shift */
2208 		y -= 100u;
2209 		c = (c + 1) & 3u;
2210 	}
2211 	y += (c * 100u);		/* combine into 1st cycle */
2212 	y += (y < 300u) ? 2000 : 1600;	/* map to destination era */
2213 	return (int)y;
2214 }
2215 
2216 char *
ntpcal_iso8601std(char * buf,size_t len,TcCivilDate * cdp)2217 ntpcal_iso8601std(
2218 	char *		buf,
2219 	size_t		len,
2220 	TcCivilDate *	cdp
2221 	)
2222 {
2223 	if (!buf) {
2224 		LIB_GETBUF(buf);
2225 		len = LIB_BUFLENGTH;
2226 	}
2227 	if (len) {
2228 		int slen = snprintf(buf, len, "%04u-%02u-%02uT%02u:%02u:%02u",
2229 			       cdp->year, cdp->month, cdp->monthday,
2230 			       cdp->hour, cdp->minute, cdp->second);
2231 		if (slen < 0)
2232 			*buf = '\0';
2233 	}
2234 	return buf;
2235 }
2236 
2237 /* -*-EOF-*- */
2238