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