xref: /freebsd-src/contrib/ntp/libntp/ntp_calendar.c (revision f5f40dd63bc7acbb5312b26ac1ea1103c12352a6)
12b15cb3dSCy Schubert /*
22b15cb3dSCy Schubert  * ntp_calendar.c - calendar and helper functions
32b15cb3dSCy Schubert  *
42b15cb3dSCy Schubert  * Written by Juergen Perlinger (perlinger@ntp.org) for the NTP project.
52b15cb3dSCy Schubert  * The contents of 'html/copyright.html' apply.
69034852cSGleb Smirnoff  *
79034852cSGleb Smirnoff  * --------------------------------------------------------------------
89034852cSGleb Smirnoff  * Some notes on the implementation:
99034852cSGleb Smirnoff  *
109034852cSGleb Smirnoff  * Calendar algorithms thrive on the division operation, which is one of
119034852cSGleb Smirnoff  * the slowest numerical operations in any CPU. What saves us here from
129034852cSGleb Smirnoff  * abysmal performance is the fact that all divisions are divisions by
139034852cSGleb Smirnoff  * constant numbers, and most compilers can do this by a multiplication
149034852cSGleb Smirnoff  * operation.  But this might not work when using the div/ldiv/lldiv
159034852cSGleb Smirnoff  * function family, because many compilers are not able to do inline
169034852cSGleb Smirnoff  * expansion of the code with following optimisation for the
179034852cSGleb Smirnoff  * constant-divider case.
189034852cSGleb Smirnoff  *
199034852cSGleb Smirnoff  * Also div/ldiv/lldiv are defined in terms of int/long/longlong, which
209034852cSGleb Smirnoff  * are inherently target dependent. Nothing that could not be cured with
219034852cSGleb Smirnoff  * autoconf, but still a mess...
229034852cSGleb Smirnoff  *
239034852cSGleb Smirnoff  * Furthermore, we need floor division in many places. C either leaves
249034852cSGleb Smirnoff  * the division behaviour undefined (< C99) or demands truncation to
259034852cSGleb Smirnoff  * zero (>= C99), so additional steps are required to make sure the
269034852cSGleb Smirnoff  * algorithms work. The {l,ll}div function family is requested to
279034852cSGleb Smirnoff  * truncate towards zero, which is also the wrong direction for our
289034852cSGleb Smirnoff  * purpose.
299034852cSGleb Smirnoff  *
309034852cSGleb Smirnoff  * For all this, all divisions by constant are coded manually, even when
319034852cSGleb Smirnoff  * there is a joined div/mod operation: The optimiser should sort that
329034852cSGleb Smirnoff  * out, if possible. Most of the calculations are done with unsigned
339034852cSGleb Smirnoff  * types, explicitely using two's complement arithmetics where
349034852cSGleb Smirnoff  * necessary. This minimises the dependecies to compiler and target,
359034852cSGleb Smirnoff  * while still giving reasonable to good performance.
369034852cSGleb Smirnoff  *
379034852cSGleb Smirnoff  * The implementation uses a few tricks that exploit properties of the
389034852cSGleb Smirnoff  * two's complement: Floor division on negative dividents can be
399034852cSGleb Smirnoff  * executed by using the one's complement of the divident. One's
409034852cSGleb Smirnoff  * complement can be easily created using XOR and a mask.
419034852cSGleb Smirnoff  *
429034852cSGleb Smirnoff  * Finally, check for overflow conditions is minimal. There are only two
43*2d4e511cSCy Schubert  * calculation steps in the whole calendar that potentially suffer from
44*2d4e511cSCy Schubert  * an internal overflow, and these are coded in a way that avoids
45*2d4e511cSCy Schubert  * it. All other functions do not suffer from internal overflow and
46*2d4e511cSCy Schubert  * simply return the result truncated to 32 bits.
472b15cb3dSCy Schubert  */
489034852cSGleb Smirnoff 
492b15cb3dSCy Schubert #include <config.h>
502b15cb3dSCy Schubert #include <sys/types.h>
512b15cb3dSCy Schubert 
522b15cb3dSCy Schubert #include "ntp_types.h"
532b15cb3dSCy Schubert #include "ntp_calendar.h"
542b15cb3dSCy Schubert #include "ntp_stdlib.h"
552b15cb3dSCy Schubert #include "ntp_fp.h"
562b15cb3dSCy Schubert #include "ntp_unixtime.h"
572b15cb3dSCy Schubert 
58*2d4e511cSCy Schubert #include "ntpd.h"
59*2d4e511cSCy Schubert 
609034852cSGleb Smirnoff /* For now, let's take the conservative approach: if the target property
619034852cSGleb Smirnoff  * macros are not defined, check a few well-known compiler/architecture
629034852cSGleb Smirnoff  * settings. Default is to assume that the representation of signed
639034852cSGleb Smirnoff  * integers is unknown and shift-arithmetic-right is not available.
649034852cSGleb Smirnoff  */
659034852cSGleb Smirnoff #ifndef TARGET_HAS_2CPL
669034852cSGleb Smirnoff # if defined(__GNUC__)
679034852cSGleb Smirnoff #  if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
689034852cSGleb Smirnoff #   define TARGET_HAS_2CPL 1
699034852cSGleb Smirnoff #  else
709034852cSGleb Smirnoff #   define TARGET_HAS_2CPL 0
719034852cSGleb Smirnoff #  endif
729034852cSGleb Smirnoff # elif defined(_MSC_VER)
739034852cSGleb Smirnoff #  if defined(_M_IX86) || defined(_M_X64) || defined(_M_ARM)
749034852cSGleb Smirnoff #   define TARGET_HAS_2CPL 1
759034852cSGleb Smirnoff #  else
769034852cSGleb Smirnoff #   define TARGET_HAS_2CPL 0
779034852cSGleb Smirnoff #  endif
789034852cSGleb Smirnoff # else
799034852cSGleb Smirnoff #  define TARGET_HAS_2CPL 0
809034852cSGleb Smirnoff # endif
819034852cSGleb Smirnoff #endif
829034852cSGleb Smirnoff 
839034852cSGleb Smirnoff #ifndef TARGET_HAS_SAR
849034852cSGleb Smirnoff # define TARGET_HAS_SAR 0
859034852cSGleb Smirnoff #endif
869034852cSGleb Smirnoff 
87*2d4e511cSCy Schubert #if !defined(HAVE_64BITREGS) && defined(UINT64_MAX) && (SIZE_MAX >= UINT64_MAX)
88*2d4e511cSCy Schubert # define HAVE_64BITREGS
89*2d4e511cSCy Schubert #endif
90*2d4e511cSCy Schubert 
912b15cb3dSCy Schubert /*
922b15cb3dSCy Schubert  *---------------------------------------------------------------------
932b15cb3dSCy Schubert  * replacing the 'time()' function
94f391d6bcSXin LI  *---------------------------------------------------------------------
952b15cb3dSCy Schubert  */
962b15cb3dSCy Schubert 
972b15cb3dSCy Schubert static systime_func_ptr systime_func = &time;
982b15cb3dSCy Schubert static inline time_t now(void);
992b15cb3dSCy Schubert 
1002b15cb3dSCy Schubert 
1012b15cb3dSCy Schubert systime_func_ptr
ntpcal_set_timefunc(systime_func_ptr nfunc)1022b15cb3dSCy Schubert ntpcal_set_timefunc(
1032b15cb3dSCy Schubert 	systime_func_ptr nfunc
1042b15cb3dSCy Schubert 	)
1052b15cb3dSCy Schubert {
1062b15cb3dSCy Schubert 	systime_func_ptr res;
1072b15cb3dSCy Schubert 
1082b15cb3dSCy Schubert 	res = systime_func;
1092b15cb3dSCy Schubert 	if (NULL == nfunc)
1102b15cb3dSCy Schubert 		nfunc = &time;
1112b15cb3dSCy Schubert 	systime_func = nfunc;
1122b15cb3dSCy Schubert 
1132b15cb3dSCy Schubert 	return res;
1142b15cb3dSCy Schubert }
1152b15cb3dSCy Schubert 
1162b15cb3dSCy Schubert 
1172b15cb3dSCy Schubert static inline time_t
now(void)1182b15cb3dSCy Schubert now(void)
1192b15cb3dSCy Schubert {
1202b15cb3dSCy Schubert 	return (*systime_func)(NULL);
1212b15cb3dSCy Schubert }
1222b15cb3dSCy Schubert 
1232b15cb3dSCy Schubert /*
1242b15cb3dSCy Schubert  *---------------------------------------------------------------------
1259034852cSGleb Smirnoff  * Get sign extension mask and unsigned 2cpl rep for a signed integer
1269034852cSGleb Smirnoff  *---------------------------------------------------------------------
1279034852cSGleb Smirnoff  */
1289034852cSGleb Smirnoff 
1299034852cSGleb Smirnoff static inline uint32_t
int32_sflag(const int32_t v)1309034852cSGleb Smirnoff int32_sflag(
1319034852cSGleb Smirnoff 	const int32_t v)
1329034852cSGleb Smirnoff {
1339034852cSGleb Smirnoff #   if TARGET_HAS_2CPL && TARGET_HAS_SAR && SIZEOF_INT >= 4
1349034852cSGleb Smirnoff 
1359034852cSGleb Smirnoff 	/* Let's assume that shift is the fastest way to get the sign
1369034852cSGleb Smirnoff 	 * extension of of a signed integer. This might not always be
1379034852cSGleb Smirnoff 	 * true, though -- On 8bit CPUs or machines without barrel
1389034852cSGleb Smirnoff 	 * shifter this will kill the performance. So we make sure
1399034852cSGleb Smirnoff 	 * we do this only if 'int' has at least 4 bytes.
1409034852cSGleb Smirnoff 	 */
1419034852cSGleb Smirnoff 	return (uint32_t)(v >> 31);
1429034852cSGleb Smirnoff 
1439034852cSGleb Smirnoff #   else
1449034852cSGleb Smirnoff 
1459034852cSGleb Smirnoff 	/* This should be a rather generic approach for getting a sign
1469034852cSGleb Smirnoff 	 * extension mask...
1479034852cSGleb Smirnoff 	 */
1489034852cSGleb Smirnoff 	return UINT32_C(0) - (uint32_t)(v < 0);
1499034852cSGleb Smirnoff 
1509034852cSGleb Smirnoff #   endif
1519034852cSGleb Smirnoff }
1529034852cSGleb Smirnoff 
1539034852cSGleb Smirnoff static inline int32_t
uint32_2cpl_to_int32(const uint32_t vu)1549034852cSGleb Smirnoff uint32_2cpl_to_int32(
1559034852cSGleb Smirnoff 	const uint32_t vu)
1569034852cSGleb Smirnoff {
1579034852cSGleb Smirnoff 	int32_t v;
1589034852cSGleb Smirnoff 
1599034852cSGleb Smirnoff #   if TARGET_HAS_2CPL
1609034852cSGleb Smirnoff 
1619034852cSGleb Smirnoff 	/* Just copy through the 32 bits from the unsigned value if
1629034852cSGleb Smirnoff 	 * we're on a two's complement target.
1639034852cSGleb Smirnoff 	 */
1649034852cSGleb Smirnoff 	v = (int32_t)vu;
1659034852cSGleb Smirnoff 
1669034852cSGleb Smirnoff #   else
1679034852cSGleb Smirnoff 
1689034852cSGleb Smirnoff 	/* Convert to signed integer, making sure signed integer
1699034852cSGleb Smirnoff 	 * overflow cannot happen. Again, the optimiser might or might
1709034852cSGleb Smirnoff 	 * not find out that this is just a copy of 32 bits on a target
1719034852cSGleb Smirnoff 	 * with two's complement representation for signed integers.
1729034852cSGleb Smirnoff 	 */
1739034852cSGleb Smirnoff 	if (vu > INT32_MAX)
1749034852cSGleb Smirnoff 		v = -(int32_t)(~vu) - 1;
1759034852cSGleb Smirnoff 	else
1769034852cSGleb Smirnoff 		v = (int32_t)vu;
1779034852cSGleb Smirnoff 
1789034852cSGleb Smirnoff #   endif
1799034852cSGleb Smirnoff 
1809034852cSGleb Smirnoff 	return v;
1819034852cSGleb Smirnoff }
1829034852cSGleb Smirnoff 
1839034852cSGleb Smirnoff /*
1849034852cSGleb Smirnoff  *---------------------------------------------------------------------
1852b15cb3dSCy Schubert  * Convert between 'time_t' and 'vint64'
1862b15cb3dSCy Schubert  *---------------------------------------------------------------------
1872b15cb3dSCy Schubert  */
1882b15cb3dSCy Schubert vint64
time_to_vint64(const time_t * ptt)1892b15cb3dSCy Schubert time_to_vint64(
1902b15cb3dSCy Schubert 	const time_t * ptt
1912b15cb3dSCy Schubert 	)
1922b15cb3dSCy Schubert {
1932b15cb3dSCy Schubert 	vint64 res;
1942b15cb3dSCy Schubert 	time_t tt;
1952b15cb3dSCy Schubert 
1962b15cb3dSCy Schubert 	tt = *ptt;
1972b15cb3dSCy Schubert 
1982b15cb3dSCy Schubert #   if SIZEOF_TIME_T <= 4
1992b15cb3dSCy Schubert 
2002b15cb3dSCy Schubert 	res.D_s.hi = 0;
2012b15cb3dSCy Schubert 	if (tt < 0) {
2022b15cb3dSCy Schubert 		res.D_s.lo = (uint32_t)-tt;
2032b15cb3dSCy Schubert 		M_NEG(res.D_s.hi, res.D_s.lo);
2042b15cb3dSCy Schubert 	} else {
2052b15cb3dSCy Schubert 		res.D_s.lo = (uint32_t)tt;
2062b15cb3dSCy Schubert 	}
2072b15cb3dSCy Schubert 
2082b15cb3dSCy Schubert #   elif defined(HAVE_INT64)
2092b15cb3dSCy Schubert 
2102b15cb3dSCy Schubert 	res.q_s = tt;
2112b15cb3dSCy Schubert 
2122b15cb3dSCy Schubert #   else
2132b15cb3dSCy Schubert 	/*
2142b15cb3dSCy Schubert 	 * shifting negative signed quantities is compiler-dependent, so
2152b15cb3dSCy Schubert 	 * we better avoid it and do it all manually. And shifting more
2162b15cb3dSCy Schubert 	 * than the width of a quantity is undefined. Also a don't do!
2172b15cb3dSCy Schubert 	 */
2182b15cb3dSCy Schubert 	if (tt < 0) {
2192b15cb3dSCy Schubert 		tt = -tt;
2202b15cb3dSCy Schubert 		res.D_s.lo = (uint32_t)tt;
2212b15cb3dSCy Schubert 		res.D_s.hi = (uint32_t)(tt >> 32);
2222b15cb3dSCy Schubert 		M_NEG(res.D_s.hi, res.D_s.lo);
2232b15cb3dSCy Schubert 	} else {
2242b15cb3dSCy Schubert 		res.D_s.lo = (uint32_t)tt;
2252b15cb3dSCy Schubert 		res.D_s.hi = (uint32_t)(tt >> 32);
2262b15cb3dSCy Schubert 	}
2272b15cb3dSCy Schubert 
2282b15cb3dSCy Schubert #   endif
2292b15cb3dSCy Schubert 
2302b15cb3dSCy Schubert 	return res;
2312b15cb3dSCy Schubert }
2322b15cb3dSCy Schubert 
2332b15cb3dSCy Schubert 
2342b15cb3dSCy Schubert time_t
vint64_to_time(const vint64 * tv)2352b15cb3dSCy Schubert vint64_to_time(
2362b15cb3dSCy Schubert 	const vint64 *tv
2372b15cb3dSCy Schubert 	)
2382b15cb3dSCy Schubert {
2392b15cb3dSCy Schubert 	time_t res;
2402b15cb3dSCy Schubert 
2412b15cb3dSCy Schubert #   if SIZEOF_TIME_T <= 4
2422b15cb3dSCy Schubert 
2432b15cb3dSCy Schubert 	res = (time_t)tv->D_s.lo;
2442b15cb3dSCy Schubert 
2452b15cb3dSCy Schubert #   elif defined(HAVE_INT64)
2462b15cb3dSCy Schubert 
2472b15cb3dSCy Schubert 	res = (time_t)tv->q_s;
2482b15cb3dSCy Schubert 
2492b15cb3dSCy Schubert #   else
2502b15cb3dSCy Schubert 
2512b15cb3dSCy Schubert 	res = ((time_t)tv->d_s.hi << 32) | tv->D_s.lo;
2522b15cb3dSCy Schubert 
2532b15cb3dSCy Schubert #   endif
2542b15cb3dSCy Schubert 
2552b15cb3dSCy Schubert 	return res;
2562b15cb3dSCy Schubert }
2572b15cb3dSCy Schubert 
2582b15cb3dSCy Schubert /*
2592b15cb3dSCy Schubert  *---------------------------------------------------------------------
2602b15cb3dSCy Schubert  * Get the build date & time
2612b15cb3dSCy Schubert  *---------------------------------------------------------------------
2622b15cb3dSCy Schubert  */
2632b15cb3dSCy Schubert int
ntpcal_get_build_date(struct calendar * jd)2642b15cb3dSCy Schubert ntpcal_get_build_date(
2652b15cb3dSCy Schubert 	struct calendar * jd
2662b15cb3dSCy Schubert 	)
2672b15cb3dSCy Schubert {
2682b15cb3dSCy Schubert 	/* The C standard tells us the format of '__DATE__':
2692b15cb3dSCy Schubert 	 *
2702b15cb3dSCy Schubert 	 * __DATE__ The date of translation of the preprocessing
2712b15cb3dSCy Schubert 	 * translation unit: a character string literal of the form "Mmm
2722b15cb3dSCy Schubert 	 * dd yyyy", where the names of the months are the same as those
2732b15cb3dSCy Schubert 	 * generated by the asctime function, and the first character of
2742b15cb3dSCy Schubert 	 * dd is a space character if the value is less than 10. If the
2752b15cb3dSCy Schubert 	 * date of translation is not available, an
2762b15cb3dSCy Schubert 	 * implementation-defined valid date shall be supplied.
2772b15cb3dSCy Schubert 	 *
2782b15cb3dSCy Schubert 	 * __TIME__ The time of translation of the preprocessing
2792b15cb3dSCy Schubert 	 * translation unit: a character string literal of the form
2802b15cb3dSCy Schubert 	 * "hh:mm:ss" as in the time generated by the asctime
2812b15cb3dSCy Schubert 	 * function. If the time of translation is not available, an
2822b15cb3dSCy Schubert 	 * implementation-defined valid time shall be supplied.
2832b15cb3dSCy Schubert 	 *
2842b15cb3dSCy Schubert 	 * Note that MSVC declares DATE and TIME to be in the local time
2852b15cb3dSCy Schubert 	 * zone, while neither the C standard nor the GCC docs make any
2862b15cb3dSCy Schubert 	 * statement about this. As a result, we may be +/-12hrs off
2872b15cb3dSCy Schubert 	 * UTC.	 But for practical purposes, this should not be a
2882b15cb3dSCy Schubert 	 * problem.
2892b15cb3dSCy Schubert 	 *
2902b15cb3dSCy Schubert 	 */
2912b15cb3dSCy Schubert #   ifdef MKREPRO_DATE
2922b15cb3dSCy Schubert 	static const char build[] = MKREPRO_TIME "/" MKREPRO_DATE;
2932b15cb3dSCy Schubert #   else
2942b15cb3dSCy Schubert 	static const char build[] = __TIME__ "/" __DATE__;
2952b15cb3dSCy Schubert #   endif
2962b15cb3dSCy Schubert 	static const char mlist[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
2972b15cb3dSCy Schubert 
2982b15cb3dSCy Schubert 	char		  monstr[4];
2992b15cb3dSCy Schubert 	const char *	  cp;
3002b15cb3dSCy Schubert 	unsigned short	  hour, minute, second, day, year;
3012b15cb3dSCy Schubert 	/* Note: The above quantities are used for sscanf 'hu' format,
3022b15cb3dSCy Schubert 	 * so using 'uint16_t' is contra-indicated!
3032b15cb3dSCy Schubert 	 */
3042b15cb3dSCy Schubert 
3052b15cb3dSCy Schubert #   ifdef DEBUG
3062b15cb3dSCy Schubert 	static int	  ignore  = 0;
3072b15cb3dSCy Schubert #   endif
3082b15cb3dSCy Schubert 
3092b15cb3dSCy Schubert 	ZERO(*jd);
3102b15cb3dSCy Schubert 	jd->year     = 1970;
3112b15cb3dSCy Schubert 	jd->month    = 1;
3122b15cb3dSCy Schubert 	jd->monthday = 1;
3132b15cb3dSCy Schubert 
3142b15cb3dSCy Schubert #   ifdef DEBUG
3152b15cb3dSCy Schubert 	/* check environment if build date should be ignored */
3162b15cb3dSCy Schubert 	if (0 == ignore) {
3172b15cb3dSCy Schubert 	    const char * envstr;
3182b15cb3dSCy Schubert 	    envstr = getenv("NTPD_IGNORE_BUILD_DATE");
3192b15cb3dSCy Schubert 	    ignore = 1 + (envstr && (!*envstr || !strcasecmp(envstr, "yes")));
3202b15cb3dSCy Schubert 	}
3212b15cb3dSCy Schubert 	if (ignore > 1)
3222b15cb3dSCy Schubert 	    return FALSE;
3232b15cb3dSCy Schubert #   endif
3242b15cb3dSCy Schubert 
3252b15cb3dSCy Schubert 	if (6 == sscanf(build, "%hu:%hu:%hu/%3s %hu %hu",
3262b15cb3dSCy Schubert 			&hour, &minute, &second, monstr, &day, &year)) {
3272b15cb3dSCy Schubert 		cp = strstr(mlist, monstr);
3282b15cb3dSCy Schubert 		if (NULL != cp) {
3292b15cb3dSCy Schubert 			jd->year     = year;
3302b15cb3dSCy Schubert 			jd->month    = (uint8_t)((cp - mlist) / 3 + 1);
3312b15cb3dSCy Schubert 			jd->monthday = (uint8_t)day;
3322b15cb3dSCy Schubert 			jd->hour     = (uint8_t)hour;
3332b15cb3dSCy Schubert 			jd->minute   = (uint8_t)minute;
3342b15cb3dSCy Schubert 			jd->second   = (uint8_t)second;
3352b15cb3dSCy Schubert 
3362b15cb3dSCy Schubert 			return TRUE;
3372b15cb3dSCy Schubert 		}
3382b15cb3dSCy Schubert 	}
3392b15cb3dSCy Schubert 
3402b15cb3dSCy Schubert 	return FALSE;
3412b15cb3dSCy Schubert }
3422b15cb3dSCy Schubert 
3432b15cb3dSCy Schubert 
3442b15cb3dSCy Schubert /*
3452b15cb3dSCy Schubert  *---------------------------------------------------------------------
3462b15cb3dSCy Schubert  * basic calendar stuff
347f391d6bcSXin LI  *---------------------------------------------------------------------
3482b15cb3dSCy Schubert  */
3492b15cb3dSCy Schubert 
3502b15cb3dSCy Schubert /*
3512b15cb3dSCy Schubert  * Some notes on the terminology:
3522b15cb3dSCy Schubert  *
3532b15cb3dSCy Schubert  * We use the proleptic Gregorian calendar, which is the Gregorian
3542b15cb3dSCy Schubert  * calendar extended in both directions ad infinitum. This totally
3552b15cb3dSCy Schubert  * disregards the fact that this calendar was invented in 1582, and
3562b15cb3dSCy Schubert  * was adopted at various dates over the world; sometimes even after
3572b15cb3dSCy Schubert  * the start of the NTP epoch.
3582b15cb3dSCy Schubert  *
3592b15cb3dSCy Schubert  * Normally date parts are given as current cycles, while time parts
3602b15cb3dSCy Schubert  * are given as elapsed cycles:
3612b15cb3dSCy Schubert  *
3622b15cb3dSCy Schubert  * 1970-01-01/03:04:05 means 'IN the 1970st. year, IN the first month,
3632b15cb3dSCy Schubert  * ON the first day, with 3hrs, 4minutes and 5 seconds elapsed.
3642b15cb3dSCy Schubert  *
3652b15cb3dSCy Schubert  * The basic calculations for this calendar implementation deal with
3662b15cb3dSCy Schubert  * ELAPSED date units, which is the number of full years, full months
3672b15cb3dSCy Schubert  * and full days before a date: 1970-01-01 would be (1969, 0, 0) in
3682b15cb3dSCy Schubert  * that notation.
3692b15cb3dSCy Schubert  *
3702b15cb3dSCy Schubert  * To ease the numeric computations, month and day values outside the
3712b15cb3dSCy Schubert  * normal range are acceptable: 2001-03-00 will be treated as the day
3722b15cb3dSCy Schubert  * before 2001-03-01, 2000-13-32 will give the same result as
3732b15cb3dSCy Schubert  * 2001-02-01 and so on.
3742b15cb3dSCy Schubert  *
3752b15cb3dSCy Schubert  * 'rd' or 'RD' is used as an abbreviation for the latin 'rata die'
3762b15cb3dSCy Schubert  * (day number).  This is the number of days elapsed since 0000-12-31
3772b15cb3dSCy Schubert  * in the proleptic Gregorian calendar. The begin of the Christian Era
3782b15cb3dSCy Schubert  * (0001-01-01) is RD(1).
3792b15cb3dSCy Schubert  */
3802b15cb3dSCy Schubert 
3812b15cb3dSCy Schubert /*
382f391d6bcSXin LI  * ====================================================================
3832b15cb3dSCy Schubert  *
3842b15cb3dSCy Schubert  * General algorithmic stuff
3852b15cb3dSCy Schubert  *
386f391d6bcSXin LI  * ====================================================================
3872b15cb3dSCy Schubert  */
3882b15cb3dSCy Schubert 
3892b15cb3dSCy Schubert /*
3902b15cb3dSCy Schubert  *---------------------------------------------------------------------
391*2d4e511cSCy Schubert  * fast modulo 7 operations (floor/mathematical convention)
392*2d4e511cSCy Schubert  *---------------------------------------------------------------------
393*2d4e511cSCy Schubert  */
394*2d4e511cSCy Schubert int
u32mod7(uint32_t x)395*2d4e511cSCy Schubert u32mod7(
396*2d4e511cSCy Schubert 	uint32_t x
397*2d4e511cSCy Schubert 	)
398*2d4e511cSCy Schubert {
399*2d4e511cSCy Schubert 	/* This is a combination of tricks from "Hacker's Delight" with
400*2d4e511cSCy Schubert 	 * some modifications, like a multiplication that rounds up to
401*2d4e511cSCy Schubert 	 * drop the final adjustment stage.
402*2d4e511cSCy Schubert 	 *
403*2d4e511cSCy Schubert 	 * Do a partial reduction by digit sum to keep the value in the
404*2d4e511cSCy Schubert 	 * range permitted for the mul/shift stage. There are several
405*2d4e511cSCy Schubert 	 * possible and absolutely equivalent shift/mask combinations;
406*2d4e511cSCy Schubert 	 * this one is ARM-friendly because of a mask that fits into 16
407*2d4e511cSCy Schubert 	 * bit.
408*2d4e511cSCy Schubert 	 */
409*2d4e511cSCy Schubert 	x = (x >> 15) + (x & UINT32_C(0x7FFF));
410*2d4e511cSCy Schubert 	/* Take reminder as (mod 8) by mul/shift. Since the multiplier
411*2d4e511cSCy Schubert 	 * was calculated using ceil() instead of floor(), it skips the
412*2d4e511cSCy Schubert 	 * value '7' properly.
413*2d4e511cSCy Schubert 	 *    M <- ceil(ldexp(8/7, 29))
414*2d4e511cSCy Schubert 	 */
415*2d4e511cSCy Schubert 	return (int)((x * UINT32_C(0x24924925)) >> 29);
416*2d4e511cSCy Schubert }
417*2d4e511cSCy Schubert 
418*2d4e511cSCy Schubert int
i32mod7(int32_t x)419*2d4e511cSCy Schubert i32mod7(
420*2d4e511cSCy Schubert 	int32_t x
421*2d4e511cSCy Schubert 	)
422*2d4e511cSCy Schubert {
423*2d4e511cSCy Schubert 	/* We add (2**32 - 2**32 % 7), which is (2**32 - 4), to negative
424*2d4e511cSCy Schubert 	 * numbers to map them into the postive range. Only the term '-4'
425*2d4e511cSCy Schubert 	 * survives, obviously.
426*2d4e511cSCy Schubert 	 */
427*2d4e511cSCy Schubert 	uint32_t ux = (uint32_t)x;
428*2d4e511cSCy Schubert 	return u32mod7((x < 0) ? (ux - 4u) : ux);
429*2d4e511cSCy Schubert }
430*2d4e511cSCy Schubert 
431*2d4e511cSCy Schubert uint32_t
i32fmod(int32_t x,uint32_t d)432*2d4e511cSCy Schubert i32fmod(
433*2d4e511cSCy Schubert 	int32_t	 x,
434*2d4e511cSCy Schubert 	uint32_t d
435*2d4e511cSCy Schubert 	)
436*2d4e511cSCy Schubert {
437*2d4e511cSCy Schubert 	uint32_t ux = (uint32_t)x;
438*2d4e511cSCy Schubert 	uint32_t sf = UINT32_C(0) - (x < 0);
439*2d4e511cSCy Schubert 	ux = (sf ^ ux ) % d;
440*2d4e511cSCy Schubert 	return (d & sf) + (sf ^ ux);
441*2d4e511cSCy Schubert }
442*2d4e511cSCy Schubert 
443*2d4e511cSCy Schubert /*
444*2d4e511cSCy Schubert  *---------------------------------------------------------------------
4452b15cb3dSCy Schubert  * Do a periodic extension of 'value' around 'pivot' with a period of
4462b15cb3dSCy Schubert  * 'cycle'.
4472b15cb3dSCy Schubert  *
4482b15cb3dSCy Schubert  * The result 'res' is a number that holds to the following properties:
4492b15cb3dSCy Schubert  *
4502b15cb3dSCy Schubert  *   1)	 res MOD cycle == value MOD cycle
4512b15cb3dSCy Schubert  *   2)	 pivot <= res < pivot + cycle
4522b15cb3dSCy Schubert  *	 (replace </<= with >/>= for negative cycles)
4532b15cb3dSCy Schubert  *
4542b15cb3dSCy Schubert  * where 'MOD' denotes the modulo operator for FLOOR DIVISION, which
4552b15cb3dSCy Schubert  * is not the same as the '%' operator in C: C requires division to be
4562b15cb3dSCy Schubert  * a truncated division, where remainder and dividend have the same
4572b15cb3dSCy Schubert  * sign if the remainder is not zero, whereas floor division requires
4582b15cb3dSCy Schubert  * divider and modulus to have the same sign for a non-zero modulus.
4592b15cb3dSCy Schubert  *
4602b15cb3dSCy Schubert  * This function has some useful applications:
4612b15cb3dSCy Schubert  *
4622b15cb3dSCy Schubert  * + let Y be a calendar year and V a truncated 2-digit year: then
4632b15cb3dSCy Schubert  *	periodic_extend(Y-50, V, 100)
4642b15cb3dSCy Schubert  *   is the closest expansion of the truncated year with respect to
4652b15cb3dSCy Schubert  *   the full year, that is a 4-digit year with a difference of less
4662b15cb3dSCy Schubert  *   than 50 years to the year Y. ("century unfolding")
4672b15cb3dSCy Schubert  *
4682b15cb3dSCy Schubert  * + let T be a UN*X time stamp and V be seconds-of-day: then
4692b15cb3dSCy Schubert  *	perodic_extend(T-43200, V, 86400)
4702b15cb3dSCy Schubert  *   is a time stamp that has the same seconds-of-day as the input
4712b15cb3dSCy Schubert  *   value, with an absolute difference to T of <= 12hrs.  ("day
4722b15cb3dSCy Schubert  *   unfolding")
4732b15cb3dSCy Schubert  *
4742b15cb3dSCy Schubert  * + Wherever you have a truncated periodic value and a non-truncated
4752b15cb3dSCy Schubert  *   base value and you want to match them somehow...
4762b15cb3dSCy Schubert  *
4772b15cb3dSCy Schubert  * Basically, the function delivers 'pivot + (value - pivot) % cycle',
4782b15cb3dSCy Schubert  * but the implementation takes some pains to avoid internal signed
4792b15cb3dSCy Schubert  * integer overflows in the '(value - pivot) % cycle' part and adheres
4802b15cb3dSCy Schubert  * to the floor division convention.
4812b15cb3dSCy Schubert  *
4822b15cb3dSCy Schubert  * If 64bit scalars where available on all intended platforms, writing a
4832b15cb3dSCy Schubert  * version that uses 64 bit ops would be easy; writing a general
4842b15cb3dSCy Schubert  * division routine for 64bit ops on a platform that can only do
4852b15cb3dSCy Schubert  * 32/16bit divisions and is still performant is a bit more
4862b15cb3dSCy Schubert  * difficult. Since most usecases can be coded in a way that does only
487*2d4e511cSCy Schubert  * require the 32bit version a 64bit version is NOT provided here.
4882b15cb3dSCy Schubert  *---------------------------------------------------------------------
4892b15cb3dSCy Schubert  */
4902b15cb3dSCy Schubert int32_t
ntpcal_periodic_extend(int32_t pivot,int32_t value,int32_t cycle)4912b15cb3dSCy Schubert ntpcal_periodic_extend(
4922b15cb3dSCy Schubert 	int32_t pivot,
4932b15cb3dSCy Schubert 	int32_t value,
4942b15cb3dSCy Schubert 	int32_t cycle
4952b15cb3dSCy Schubert 	)
4962b15cb3dSCy Schubert {
497*2d4e511cSCy Schubert 	/* Implement a 4-quadrant modulus calculation by 2 2-quadrant
498*2d4e511cSCy Schubert 	 * branches, one for positive and one for negative dividers.
499*2d4e511cSCy Schubert 	 * Everything else can be handled by bit level logic and
500*2d4e511cSCy Schubert 	 * conditional one's complement arithmetic.  By convention, we
501*2d4e511cSCy Schubert 	 * assume
502*2d4e511cSCy Schubert 	 *
503*2d4e511cSCy Schubert 	 * x % b == 0  if  |b| < 2
504*2d4e511cSCy Schubert 	 *
505*2d4e511cSCy Schubert 	 * that is, we don't actually divide for cycles of -1,0,1 and
506*2d4e511cSCy Schubert 	 * return the pivot value in that case.
5072b15cb3dSCy Schubert 	 */
508*2d4e511cSCy Schubert 	uint32_t	uv = (uint32_t)value;
509*2d4e511cSCy Schubert 	uint32_t	up = (uint32_t)pivot;
510*2d4e511cSCy Schubert 	uint32_t	uc, sf;
511*2d4e511cSCy Schubert 
512*2d4e511cSCy Schubert 	if (cycle > 1)
513*2d4e511cSCy Schubert 	{
514*2d4e511cSCy Schubert 		uc = (uint32_t)cycle;
515*2d4e511cSCy Schubert 		sf = UINT32_C(0) - (value < pivot);
516*2d4e511cSCy Schubert 
517*2d4e511cSCy Schubert 		uv = sf ^ (uv - up);
518*2d4e511cSCy Schubert 		uv %= uc;
519*2d4e511cSCy Schubert 		pivot += (uc & sf) + (sf ^ uv);
5202b15cb3dSCy Schubert 	}
521*2d4e511cSCy Schubert 	else if (cycle < -1)
522*2d4e511cSCy Schubert 	{
523*2d4e511cSCy Schubert 		uc = ~(uint32_t)cycle + 1;
524*2d4e511cSCy Schubert 		sf = UINT32_C(0) - (value > pivot);
525*2d4e511cSCy Schubert 
526*2d4e511cSCy Schubert 		uv = sf ^ (up - uv);
527*2d4e511cSCy Schubert 		uv %= uc;
528*2d4e511cSCy Schubert 		pivot -= (uc & sf) + (sf ^ uv);
5292b15cb3dSCy Schubert 	}
5302b15cb3dSCy Schubert 	return pivot;
5312b15cb3dSCy Schubert }
5322b15cb3dSCy Schubert 
533f391d6bcSXin LI /*---------------------------------------------------------------------
534f391d6bcSXin LI  * Note to the casual reader
535f391d6bcSXin LI  *
536f391d6bcSXin LI  * In the next two functions you will find (or would have found...)
537f391d6bcSXin LI  * the expression
538f391d6bcSXin LI  *
539f391d6bcSXin LI  *   res.Q_s -= 0x80000000;
540f391d6bcSXin LI  *
541f391d6bcSXin LI  * There was some ruckus about a possible programming error due to
542f391d6bcSXin LI  * integer overflow and sign propagation.
543f391d6bcSXin LI  *
544f391d6bcSXin LI  * This assumption is based on a lack of understanding of the C
545f391d6bcSXin LI  * standard. (Though this is admittedly not one of the most 'natural'
546f391d6bcSXin LI  * aspects of the 'C' language and easily to get wrong.)
547f391d6bcSXin LI  *
548f391d6bcSXin LI  * see
549f391d6bcSXin LI  *	http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
550f391d6bcSXin LI  *	"ISO/IEC 9899:201x Committee Draft — April 12, 2011"
551f391d6bcSXin LI  *	6.4.4.1 Integer constants, clause 5
552f391d6bcSXin LI  *
553f391d6bcSXin LI  * why there is no sign extension/overflow problem here.
554f391d6bcSXin LI  *
555f391d6bcSXin LI  * But to ease the minds of the doubtful, I added back the 'u' qualifiers
556f391d6bcSXin LI  * that somehow got lost over the last years.
557f391d6bcSXin LI  */
558f391d6bcSXin LI 
559f391d6bcSXin LI 
5602b15cb3dSCy Schubert /*
561f391d6bcSXin LI  *---------------------------------------------------------------------
5622b15cb3dSCy Schubert  * Convert a timestamp in NTP scale to a 64bit seconds value in the UN*X
5632b15cb3dSCy Schubert  * scale with proper epoch unfolding around a given pivot or the current
5642b15cb3dSCy Schubert  * system time. This function happily accepts negative pivot values as
565*2d4e511cSCy Schubert  * timestamps before 1970-01-01, so be aware of possible trouble on
5662b15cb3dSCy Schubert  * platforms with 32bit 'time_t'!
5672b15cb3dSCy Schubert  *
5682b15cb3dSCy Schubert  * This is also a periodic extension, but since the cycle is 2^32 and
5692b15cb3dSCy Schubert  * the shift is 2^31, we can do some *very* fast math without explicit
5702b15cb3dSCy Schubert  * divisions.
571f391d6bcSXin LI  *---------------------------------------------------------------------
5722b15cb3dSCy Schubert  */
5732b15cb3dSCy Schubert vint64
ntpcal_ntp_to_time(uint32_t ntp,const time_t * pivot)5742b15cb3dSCy Schubert ntpcal_ntp_to_time(
5752b15cb3dSCy Schubert 	uint32_t	ntp,
5762b15cb3dSCy Schubert 	const time_t *	pivot
5772b15cb3dSCy Schubert 	)
5782b15cb3dSCy Schubert {
5792b15cb3dSCy Schubert 	vint64 res;
5802b15cb3dSCy Schubert 
5819034852cSGleb Smirnoff #   if defined(HAVE_INT64)
5822b15cb3dSCy Schubert 
5832b15cb3dSCy Schubert 	res.q_s = (pivot != NULL)
5842b15cb3dSCy Schubert 		      ? *pivot
5852b15cb3dSCy Schubert 		      : now();
586f391d6bcSXin LI 	res.Q_s -= 0x80000000u;		/* unshift of half range */
5872b15cb3dSCy Schubert 	ntp	-= (uint32_t)JAN_1970;	/* warp into UN*X domain */
5882b15cb3dSCy Schubert 	ntp	-= res.D_s.lo;		/* cycle difference	 */
5892b15cb3dSCy Schubert 	res.Q_s += (uint64_t)ntp;	/* get expanded time	 */
5902b15cb3dSCy Schubert 
5912b15cb3dSCy Schubert #   else /* no 64bit scalars */
5922b15cb3dSCy Schubert 
5932b15cb3dSCy Schubert 	time_t tmp;
5942b15cb3dSCy Schubert 
5952b15cb3dSCy Schubert 	tmp = (pivot != NULL)
5962b15cb3dSCy Schubert 		  ? *pivot
5972b15cb3dSCy Schubert 		  : now();
5982b15cb3dSCy Schubert 	res = time_to_vint64(&tmp);
599f391d6bcSXin LI 	M_SUB(res.D_s.hi, res.D_s.lo, 0, 0x80000000u);
6002b15cb3dSCy Schubert 	ntp -= (uint32_t)JAN_1970;	/* warp into UN*X domain */
6012b15cb3dSCy Schubert 	ntp -= res.D_s.lo;		/* cycle difference	 */
6022b15cb3dSCy Schubert 	M_ADD(res.D_s.hi, res.D_s.lo, 0, ntp);
6032b15cb3dSCy Schubert 
6042b15cb3dSCy Schubert #   endif /* no 64bit scalars */
6052b15cb3dSCy Schubert 
6062b15cb3dSCy Schubert 	return res;
6072b15cb3dSCy Schubert }
6082b15cb3dSCy Schubert 
6092b15cb3dSCy Schubert /*
610f391d6bcSXin LI  *---------------------------------------------------------------------
6112b15cb3dSCy Schubert  * Convert a timestamp in NTP scale to a 64bit seconds value in the NTP
6122b15cb3dSCy Schubert  * scale with proper epoch unfolding around a given pivot or the current
6132b15cb3dSCy Schubert  * system time.
6142b15cb3dSCy Schubert  *
6152b15cb3dSCy Schubert  * Note: The pivot must be given in the UN*X time domain!
6162b15cb3dSCy Schubert  *
6172b15cb3dSCy Schubert  * This is also a periodic extension, but since the cycle is 2^32 and
6182b15cb3dSCy Schubert  * the shift is 2^31, we can do some *very* fast math without explicit
6192b15cb3dSCy Schubert  * divisions.
620f391d6bcSXin LI  *---------------------------------------------------------------------
6212b15cb3dSCy Schubert  */
6222b15cb3dSCy Schubert vint64
ntpcal_ntp_to_ntp(uint32_t ntp,const time_t * pivot)6232b15cb3dSCy Schubert ntpcal_ntp_to_ntp(
6242b15cb3dSCy Schubert 	uint32_t      ntp,
6252b15cb3dSCy Schubert 	const time_t *pivot
6262b15cb3dSCy Schubert 	)
6272b15cb3dSCy Schubert {
6282b15cb3dSCy Schubert 	vint64 res;
6292b15cb3dSCy Schubert 
6309034852cSGleb Smirnoff #   if defined(HAVE_INT64)
6312b15cb3dSCy Schubert 
6322b15cb3dSCy Schubert 	res.q_s = (pivot)
6332b15cb3dSCy Schubert 		      ? *pivot
6342b15cb3dSCy Schubert 		      : now();
635f391d6bcSXin LI 	res.Q_s -= 0x80000000u;		/* unshift of half range */
6362b15cb3dSCy Schubert 	res.Q_s += (uint32_t)JAN_1970;	/* warp into NTP domain	 */
6372b15cb3dSCy Schubert 	ntp	-= res.D_s.lo;		/* cycle difference	 */
6382b15cb3dSCy Schubert 	res.Q_s += (uint64_t)ntp;	/* get expanded time	 */
6392b15cb3dSCy Schubert 
6402b15cb3dSCy Schubert #   else /* no 64bit scalars */
6412b15cb3dSCy Schubert 
6422b15cb3dSCy Schubert 	time_t tmp;
6432b15cb3dSCy Schubert 
6442b15cb3dSCy Schubert 	tmp = (pivot)
6452b15cb3dSCy Schubert 		  ? *pivot
6462b15cb3dSCy Schubert 		  : now();
6472b15cb3dSCy Schubert 	res = time_to_vint64(&tmp);
6482b15cb3dSCy Schubert 	M_SUB(res.D_s.hi, res.D_s.lo, 0, 0x80000000u);
6492b15cb3dSCy Schubert 	M_ADD(res.D_s.hi, res.D_s.lo, 0, (uint32_t)JAN_1970);/*into NTP */
6502b15cb3dSCy Schubert 	ntp -= res.D_s.lo;		/* cycle difference	 */
6512b15cb3dSCy Schubert 	M_ADD(res.D_s.hi, res.D_s.lo, 0, ntp);
6522b15cb3dSCy Schubert 
6532b15cb3dSCy Schubert #   endif /* no 64bit scalars */
6542b15cb3dSCy Schubert 
6552b15cb3dSCy Schubert 	return res;
6562b15cb3dSCy Schubert }
6572b15cb3dSCy Schubert 
6582b15cb3dSCy Schubert 
6592b15cb3dSCy Schubert /*
660f391d6bcSXin LI  * ====================================================================
6612b15cb3dSCy Schubert  *
6622b15cb3dSCy Schubert  * Splitting values to composite entities
6632b15cb3dSCy Schubert  *
664f391d6bcSXin LI  * ====================================================================
6652b15cb3dSCy Schubert  */
6662b15cb3dSCy Schubert 
6672b15cb3dSCy Schubert /*
668f391d6bcSXin LI  *---------------------------------------------------------------------
6692b15cb3dSCy Schubert  * Split a 64bit seconds value into elapsed days in 'res.hi' and
6702b15cb3dSCy Schubert  * elapsed seconds since midnight in 'res.lo' using explicit floor
6712b15cb3dSCy Schubert  * division. This function happily accepts negative time values as
6722b15cb3dSCy Schubert  * timestamps before the respective epoch start.
673f391d6bcSXin LI  *---------------------------------------------------------------------
6742b15cb3dSCy Schubert  */
6752b15cb3dSCy Schubert ntpcal_split
ntpcal_daysplit(const vint64 * ts)6762b15cb3dSCy Schubert ntpcal_daysplit(
6772b15cb3dSCy Schubert 	const vint64 *ts
6782b15cb3dSCy Schubert 	)
6792b15cb3dSCy Schubert {
6802b15cb3dSCy Schubert 	ntpcal_split res;
681*2d4e511cSCy Schubert 	uint32_t Q, R;
6822b15cb3dSCy Schubert 
683*2d4e511cSCy Schubert #   if defined(HAVE_64BITREGS)
6842b15cb3dSCy Schubert 
685*2d4e511cSCy Schubert 	/* Assume we have 64bit registers an can do a divison by
686*2d4e511cSCy Schubert 	 * constant reasonably fast using the one's complement trick..
687*2d4e511cSCy Schubert 	 */
688*2d4e511cSCy Schubert 	uint64_t sf64 = (uint64_t)-(ts->q_s < 0);
689*2d4e511cSCy Schubert 	Q = (uint32_t)(sf64 ^ ((sf64 ^ ts->Q_s) / SECSPERDAY));
690*2d4e511cSCy Schubert 	R = (uint32_t)(ts->Q_s - Q * SECSPERDAY);
691*2d4e511cSCy Schubert 
692*2d4e511cSCy Schubert #   elif defined(UINT64_MAX) && !defined(__arm__)
693*2d4e511cSCy Schubert 
694*2d4e511cSCy Schubert 	/* We rely on the compiler to do efficient 64bit divisions as
695*2d4e511cSCy Schubert 	 * good as possible. Which might or might not be true. At least
696*2d4e511cSCy Schubert 	 * for ARM CPUs, the sum-by-digit code in the next section is
697*2d4e511cSCy Schubert 	 * faster for many compilers. (This might change over time, but
698*2d4e511cSCy Schubert 	 * the 64bit-by-32bit division will never outperform the exact
699*2d4e511cSCy Schubert 	 * division by a substantial factor....)
7009034852cSGleb Smirnoff 	 */
7019034852cSGleb Smirnoff 	if (ts->q_s < 0)
7029034852cSGleb Smirnoff 		Q = ~(uint32_t)(~ts->Q_s / SECSPERDAY);
7039034852cSGleb Smirnoff 	else
7049034852cSGleb Smirnoff 		Q =  (uint32_t)( ts->Q_s / SECSPERDAY);
705*2d4e511cSCy Schubert 	R = ts->D_s.lo - Q * SECSPERDAY;
7062b15cb3dSCy Schubert 
7072b15cb3dSCy Schubert #   else
7082b15cb3dSCy Schubert 
709*2d4e511cSCy Schubert 	/* We don't have 64bit regs. That hurts a bit.
7109034852cSGleb Smirnoff 	 *
711*2d4e511cSCy Schubert 	 * Here we use a mean trick to get away with just one explicit
712*2d4e511cSCy Schubert 	 * modulo operation and pure 32bit ops.
713*2d4e511cSCy Schubert 	 *
714*2d4e511cSCy Schubert 	 * Remember: 86400 <--> 128 * 675
715*2d4e511cSCy Schubert 	 *
716*2d4e511cSCy Schubert 	 * So we discard the lowest 7 bit and do an exact division by
717*2d4e511cSCy Schubert 	 * 675, modulo 2**32.
718*2d4e511cSCy Schubert 	 *
719*2d4e511cSCy Schubert 	 * First we shift out the lower 7 bits.
720*2d4e511cSCy Schubert 	 *
721*2d4e511cSCy Schubert 	 * Then we use a digit-wise pseudo-reduction, where a 'digit' is
722*2d4e511cSCy Schubert 	 * actually a 16-bit group. This is followed by a full reduction
723*2d4e511cSCy Schubert 	 * with a 'true' division step. This yields the modulus of the
724*2d4e511cSCy Schubert 	 * full 64bit value. The sign bit gets some extra treatment.
725*2d4e511cSCy Schubert 	 *
726*2d4e511cSCy Schubert 	 * Then we decrement the lower limb by that modulus, so it is
727*2d4e511cSCy Schubert 	 * exactly divisible by 675. [*]
728*2d4e511cSCy Schubert 	 *
729*2d4e511cSCy Schubert 	 * Then we multiply with the modular inverse of 675 (mod 2**32)
730*2d4e511cSCy Schubert 	 * and voila, we have the result.
731*2d4e511cSCy Schubert 	 *
732*2d4e511cSCy Schubert 	 * Special Thanks to Henry S. Warren and his "Hacker's delight"
733*2d4e511cSCy Schubert 	 * for giving that idea.
734*2d4e511cSCy Schubert 	 *
735*2d4e511cSCy Schubert 	 * (Note[*]: that's not the full truth. We would have to
736*2d4e511cSCy Schubert 	 * subtract the modulus from the full 64 bit number to get a
737*2d4e511cSCy Schubert 	 * number that is divisible by 675. But since we use the
738*2d4e511cSCy Schubert 	 * multiplicative inverse (mod 2**32) there's no reason to carry
739*2d4e511cSCy Schubert 	 * the subtraction into the upper bits!)
7402b15cb3dSCy Schubert 	 */
741*2d4e511cSCy Schubert 	uint32_t al = ts->D_s.lo;
742*2d4e511cSCy Schubert 	uint32_t ah = ts->D_s.hi;
7432b15cb3dSCy Schubert 
744*2d4e511cSCy Schubert 	/* shift out the lower 7 bits, smash sign bit */
745*2d4e511cSCy Schubert 	al = (al >> 7) | (ah << 25);
746*2d4e511cSCy Schubert 	ah = (ah >> 7) & 0x00FFFFFFu;
7472b15cb3dSCy Schubert 
748*2d4e511cSCy Schubert 	R  = (ts->d_s.hi < 0) ? 239 : 0;/* sign bit value */
749*2d4e511cSCy Schubert 	R += (al & 0xFFFF);
750*2d4e511cSCy Schubert 	R += (al >> 16	 ) * 61u;	/* 2**16 % 675 */
751*2d4e511cSCy Schubert 	R += (ah & 0xFFFF) * 346u;	/* 2**32 % 675 */
752*2d4e511cSCy Schubert 	R += (ah >> 16	 ) * 181u;	/* 2**48 % 675 */
753*2d4e511cSCy Schubert 	R %= 675u;			/* final reduction */
754*2d4e511cSCy Schubert 	Q  = (al - R) * 0x2D21C10Bu;	/* modinv(675, 2**32) */
755*2d4e511cSCy Schubert 	R  = (R << 7) | (ts->d_s.lo & 0x07F);
7562b15cb3dSCy Schubert 
7572b15cb3dSCy Schubert #   endif
7589034852cSGleb Smirnoff 
7599034852cSGleb Smirnoff 	res.hi = uint32_2cpl_to_int32(Q);
760*2d4e511cSCy Schubert 	res.lo = R;
761*2d4e511cSCy Schubert 
762*2d4e511cSCy Schubert 	return res;
763*2d4e511cSCy Schubert }
764*2d4e511cSCy Schubert 
765*2d4e511cSCy Schubert /*
766*2d4e511cSCy Schubert  *---------------------------------------------------------------------
767*2d4e511cSCy Schubert  * Split a 64bit seconds value into elapsed weeks in 'res.hi' and
768*2d4e511cSCy Schubert  * elapsed seconds since week start in 'res.lo' using explicit floor
769*2d4e511cSCy Schubert  * division. This function happily accepts negative time values as
770*2d4e511cSCy Schubert  * timestamps before the respective epoch start.
771*2d4e511cSCy Schubert  *---------------------------------------------------------------------
772*2d4e511cSCy Schubert  */
773*2d4e511cSCy Schubert ntpcal_split
ntpcal_weeksplit(const vint64 * ts)774*2d4e511cSCy Schubert ntpcal_weeksplit(
775*2d4e511cSCy Schubert 	const vint64 *ts
776*2d4e511cSCy Schubert 	)
777*2d4e511cSCy Schubert {
778*2d4e511cSCy Schubert 	ntpcal_split res;
779*2d4e511cSCy Schubert 	uint32_t Q, R;
780*2d4e511cSCy Schubert 
781*2d4e511cSCy Schubert 	/* This is a very close relative to the day split function; for
782*2d4e511cSCy Schubert 	 * details, see there!
783*2d4e511cSCy Schubert 	 */
784*2d4e511cSCy Schubert 
785*2d4e511cSCy Schubert #   if defined(HAVE_64BITREGS)
786*2d4e511cSCy Schubert 
787*2d4e511cSCy Schubert 	uint64_t sf64 = (uint64_t)-(ts->q_s < 0);
788*2d4e511cSCy Schubert 	Q = (uint32_t)(sf64 ^ ((sf64 ^ ts->Q_s) / SECSPERWEEK));
789*2d4e511cSCy Schubert 	R = (uint32_t)(ts->Q_s - Q * SECSPERWEEK);
790*2d4e511cSCy Schubert 
791*2d4e511cSCy Schubert #   elif defined(UINT64_MAX) && !defined(__arm__)
792*2d4e511cSCy Schubert 
793*2d4e511cSCy Schubert 	if (ts->q_s < 0)
794*2d4e511cSCy Schubert 		Q = ~(uint32_t)(~ts->Q_s / SECSPERWEEK);
795*2d4e511cSCy Schubert 	else
796*2d4e511cSCy Schubert 		Q =  (uint32_t)( ts->Q_s / SECSPERWEEK);
797*2d4e511cSCy Schubert 	R = ts->D_s.lo - Q * SECSPERWEEK;
798*2d4e511cSCy Schubert 
799*2d4e511cSCy Schubert #   else
800*2d4e511cSCy Schubert 
801*2d4e511cSCy Schubert 	/* Remember: 7*86400 <--> 604800 <--> 128 * 4725 */
802*2d4e511cSCy Schubert 	uint32_t al = ts->D_s.lo;
803*2d4e511cSCy Schubert 	uint32_t ah = ts->D_s.hi;
804*2d4e511cSCy Schubert 
805*2d4e511cSCy Schubert 	al = (al >> 7) | (ah << 25);
806*2d4e511cSCy Schubert 	ah = (ah >> 7) & 0x00FFFFFF;
807*2d4e511cSCy Schubert 
808*2d4e511cSCy Schubert 	R  = (ts->d_s.hi < 0) ? 2264 : 0;/* sign bit value */
809*2d4e511cSCy Schubert 	R += (al & 0xFFFF);
810*2d4e511cSCy Schubert 	R += (al >> 16	 ) * 4111u;	/* 2**16 % 4725 */
811*2d4e511cSCy Schubert 	R += (ah & 0xFFFF) * 3721u;	/* 2**32 % 4725 */
812*2d4e511cSCy Schubert 	R += (ah >> 16	 ) * 2206u;	/* 2**48 % 4725 */
813*2d4e511cSCy Schubert 	R %= 4725u;			/* final reduction */
814*2d4e511cSCy Schubert 	Q  = (al - R) * 0x98BBADDDu;	/* modinv(4725, 2**32) */
815*2d4e511cSCy Schubert 	R  = (R << 7) | (ts->d_s.lo & 0x07F);
816*2d4e511cSCy Schubert 
817*2d4e511cSCy Schubert #   endif
818*2d4e511cSCy Schubert 
819*2d4e511cSCy Schubert 	res.hi = uint32_2cpl_to_int32(Q);
820*2d4e511cSCy Schubert 	res.lo = R;
8219034852cSGleb Smirnoff 
8222b15cb3dSCy Schubert 	return res;
8232b15cb3dSCy Schubert }
8242b15cb3dSCy Schubert 
8252b15cb3dSCy Schubert /*
826f391d6bcSXin LI  *---------------------------------------------------------------------
8272b15cb3dSCy Schubert  * Split a 32bit seconds value into h/m/s and excessive days.  This
8282b15cb3dSCy Schubert  * function happily accepts negative time values as timestamps before
8292b15cb3dSCy Schubert  * midnight.
830f391d6bcSXin LI  *---------------------------------------------------------------------
8312b15cb3dSCy Schubert  */
8322b15cb3dSCy Schubert static int32_t
priv_timesplit(int32_t split[3],int32_t ts)8332b15cb3dSCy Schubert priv_timesplit(
8342b15cb3dSCy Schubert 	int32_t split[3],
8352b15cb3dSCy Schubert 	int32_t ts
8362b15cb3dSCy Schubert 	)
8372b15cb3dSCy Schubert {
8389034852cSGleb Smirnoff 	/* Do 3 chained floor divisions by positive constants, using the
8399034852cSGleb Smirnoff 	 * one's complement trick and factoring out the intermediate XOR
8409034852cSGleb Smirnoff 	 * ops to reduce the number of operations.
8419034852cSGleb Smirnoff 	 */
842*2d4e511cSCy Schubert 	uint32_t us, um, uh, ud, sf32;
8432b15cb3dSCy Schubert 
844*2d4e511cSCy Schubert 	sf32 = int32_sflag(ts);
8452b15cb3dSCy Schubert 
846*2d4e511cSCy Schubert 	us = (uint32_t)ts;
847*2d4e511cSCy Schubert 	um = (sf32 ^ us) / SECSPERMIN;
8489034852cSGleb Smirnoff 	uh = um / MINSPERHR;
8499034852cSGleb Smirnoff 	ud = uh / HRSPERDAY;
8502b15cb3dSCy Schubert 
851*2d4e511cSCy Schubert 	um ^= sf32;
852*2d4e511cSCy Schubert 	uh ^= sf32;
853*2d4e511cSCy Schubert 	ud ^= sf32;
8549034852cSGleb Smirnoff 
8559034852cSGleb Smirnoff 	split[0] = (int32_t)(uh - ud * HRSPERDAY );
8569034852cSGleb Smirnoff 	split[1] = (int32_t)(um - uh * MINSPERHR );
8579034852cSGleb Smirnoff 	split[2] = (int32_t)(us - um * SECSPERMIN);
8589034852cSGleb Smirnoff 
8599034852cSGleb Smirnoff 	return uint32_2cpl_to_int32(ud);
8602b15cb3dSCy Schubert }
8612b15cb3dSCy Schubert 
8622b15cb3dSCy Schubert /*
8632b15cb3dSCy Schubert  *---------------------------------------------------------------------
8642b15cb3dSCy Schubert  * Given the number of elapsed days in the calendar era, split this
8652b15cb3dSCy Schubert  * number into the number of elapsed years in 'res.hi' and the number
8662b15cb3dSCy Schubert  * of elapsed days of that year in 'res.lo'.
8672b15cb3dSCy Schubert  *
8682b15cb3dSCy Schubert  * if 'isleapyear' is not NULL, it will receive an integer that is 0 for
8692b15cb3dSCy Schubert  * regular years and a non-zero value for leap years.
8702b15cb3dSCy Schubert  *---------------------------------------------------------------------
8712b15cb3dSCy Schubert  */
8722b15cb3dSCy Schubert ntpcal_split
ntpcal_split_eradays(int32_t days,int * isleapyear)8732b15cb3dSCy Schubert ntpcal_split_eradays(
8742b15cb3dSCy Schubert 	int32_t days,
8752b15cb3dSCy Schubert 	int  *isleapyear
8762b15cb3dSCy Schubert 	)
8772b15cb3dSCy Schubert {
8789034852cSGleb Smirnoff 	/* Use the fast cycle split algorithm here, to calculate the
8799034852cSGleb Smirnoff 	 * centuries and years in a century with one division each. This
8809034852cSGleb Smirnoff 	 * reduces the number of division operations to two, but is
881*2d4e511cSCy Schubert 	 * susceptible to internal range overflow. We take some extra
882*2d4e511cSCy Schubert 	 * steps to avoid the gap.
8839034852cSGleb Smirnoff 	 */
8842b15cb3dSCy Schubert 	ntpcal_split res;
8859034852cSGleb Smirnoff 	int32_t	 n100, n001; /* calendar year cycles */
886*2d4e511cSCy Schubert 	uint32_t uday, Q;
8872b15cb3dSCy Schubert 
888*2d4e511cSCy Schubert 	/* split off centuries first
889*2d4e511cSCy Schubert 	 *
890*2d4e511cSCy Schubert 	 * We want to execute '(days * 4 + 3) /% 146097' under floor
891*2d4e511cSCy Schubert 	 * division rules in the first step. Well, actually we want to
892*2d4e511cSCy Schubert 	 * calculate 'floor((days + 0.75) / 36524.25)', but we want to
893*2d4e511cSCy Schubert 	 * do it in scaled integer calculation.
894*2d4e511cSCy Schubert 	 */
895*2d4e511cSCy Schubert #   if defined(HAVE_64BITREGS)
896*2d4e511cSCy Schubert 
897*2d4e511cSCy Schubert 	/* not too complicated with an intermediate 64bit value */
898*2d4e511cSCy Schubert 	uint64_t	ud64, sf64;
899*2d4e511cSCy Schubert 	ud64 = ((uint64_t)days << 2) | 3u;
900*2d4e511cSCy Schubert 	sf64 = (uint64_t)-(days < 0);
901*2d4e511cSCy Schubert 	Q    = (uint32_t)(sf64 ^ ((sf64 ^ ud64) / GREGORIAN_CYCLE_DAYS));
902*2d4e511cSCy Schubert 	uday = (uint32_t)(ud64 - Q * GREGORIAN_CYCLE_DAYS);
9039034852cSGleb Smirnoff 	n100 = uint32_2cpl_to_int32(Q);
9042b15cb3dSCy Schubert 
905*2d4e511cSCy Schubert #   else
906*2d4e511cSCy Schubert 
907*2d4e511cSCy Schubert 	/* '4*days+3' suffers from range overflow when going to the
908*2d4e511cSCy Schubert 	 * limits. We solve this by doing an exact division (mod 2^32)
909*2d4e511cSCy Schubert 	 * after caclulating the remainder first.
910*2d4e511cSCy Schubert 	 *
911*2d4e511cSCy Schubert 	 * We start with a partial reduction by digit sums, extracting
912*2d4e511cSCy Schubert 	 * the upper bits from the original value before they get lost
913*2d4e511cSCy Schubert 	 * by scaling, and do one full division step to get the true
914*2d4e511cSCy Schubert 	 * remainder.  Then a final multiplication with the
915*2d4e511cSCy Schubert 	 * multiplicative inverse of 146097 (mod 2^32) gives us the full
916*2d4e511cSCy Schubert 	 * quotient.
917*2d4e511cSCy Schubert 	 *
918*2d4e511cSCy Schubert 	 * (-2^33) % 146097	--> 130717    : the sign bit value
919*2d4e511cSCy Schubert 	 * ( 2^20) % 146097	--> 25897     : the upper digit value
920*2d4e511cSCy Schubert 	 * modinv(146097, 2^32) --> 660721233 : the inverse
921*2d4e511cSCy Schubert 	 */
922*2d4e511cSCy Schubert 	uint32_t ux = ((uint32_t)days << 2) | 3;
923*2d4e511cSCy Schubert 	uday  = (days < 0) ? 130717u : 0u;	    /* sign dgt */
924*2d4e511cSCy Schubert 	uday += ((days >> 18) & 0x01FFFu) * 25897u; /* hi dgt (src!) */
925*2d4e511cSCy Schubert 	uday += (ux & 0xFFFFFu);		    /* lo dgt */
926*2d4e511cSCy Schubert 	uday %= GREGORIAN_CYCLE_DAYS;		    /* full reduction */
927*2d4e511cSCy Schubert 	Q     = (ux  - uday) * 660721233u;	    /* exact div */
928*2d4e511cSCy Schubert 	n100  = uint32_2cpl_to_int32(Q);
929*2d4e511cSCy Schubert 
930*2d4e511cSCy Schubert #   endif
931*2d4e511cSCy Schubert 
9329034852cSGleb Smirnoff 	/* Split off years in century -- days >= 0 here, and we're far
9339034852cSGleb Smirnoff 	 * away from integer overflow trouble now. */
9349034852cSGleb Smirnoff 	uday |= 3;
9359034852cSGleb Smirnoff 	n001  = uday / GREGORIAN_NORMAL_LEAP_CYCLE_DAYS;
936*2d4e511cSCy Schubert 	uday -= n001 * GREGORIAN_NORMAL_LEAP_CYCLE_DAYS;
9379034852cSGleb Smirnoff 
9389034852cSGleb Smirnoff 	/* Assemble the year and day in year */
9399034852cSGleb Smirnoff 	res.hi = n100 * 100 + n001;
9409034852cSGleb Smirnoff 	res.lo = uday / 4u;
9419034852cSGleb Smirnoff 
942*2d4e511cSCy Schubert 	/* Possibly set the leap year flag */
943*2d4e511cSCy Schubert 	if (isleapyear) {
944*2d4e511cSCy Schubert 		uint32_t tc = (uint32_t)n100 + 1;
945*2d4e511cSCy Schubert 		uint32_t ty = (uint32_t)n001 + 1;
946*2d4e511cSCy Schubert 		*isleapyear = !(ty & 3)
947*2d4e511cSCy Schubert 		    && ((ty != 100) || !(tc & 3));
948*2d4e511cSCy Schubert 	}
9492b15cb3dSCy Schubert 	return res;
9502b15cb3dSCy Schubert }
9512b15cb3dSCy Schubert 
9522b15cb3dSCy Schubert /*
9532b15cb3dSCy Schubert  *---------------------------------------------------------------------
9542b15cb3dSCy Schubert  * Given a number of elapsed days in a year and a leap year indicator,
9552b15cb3dSCy Schubert  * split the number of elapsed days into the number of elapsed months in
9562b15cb3dSCy Schubert  * 'res.hi' and the number of elapsed days of that month in 'res.lo'.
9572b15cb3dSCy Schubert  *
9582b15cb3dSCy Schubert  * This function will fail and return {-1,-1} if the number of elapsed
9592b15cb3dSCy Schubert  * days is not in the valid range!
9602b15cb3dSCy Schubert  *---------------------------------------------------------------------
9612b15cb3dSCy Schubert  */
9622b15cb3dSCy Schubert ntpcal_split
ntpcal_split_yeardays(int32_t eyd,int isleap)9632b15cb3dSCy Schubert ntpcal_split_yeardays(
9642b15cb3dSCy Schubert 	int32_t eyd,
965*2d4e511cSCy Schubert 	int	isleap
9662b15cb3dSCy Schubert 	)
9672b15cb3dSCy Schubert {
968*2d4e511cSCy Schubert 	/* Use the unshifted-year, February-with-30-days approach here.
969*2d4e511cSCy Schubert 	 * Fractional interpolations are used in both directions, with
970*2d4e511cSCy Schubert 	 * the smallest power-of-two divider to avoid any true division.
971*2d4e511cSCy Schubert 	 */
972*2d4e511cSCy Schubert 	ntpcal_split	res = {-1, -1};
9732b15cb3dSCy Schubert 
974*2d4e511cSCy Schubert 	/* convert 'isleap' to number of defective days */
975*2d4e511cSCy Schubert 	isleap = 1 + !isleap;
976*2d4e511cSCy Schubert 	/* adjust for February of 30 nominal days */
977*2d4e511cSCy Schubert 	if (eyd >= 61 - isleap)
978*2d4e511cSCy Schubert 		eyd += isleap;
979*2d4e511cSCy Schubert 	/* if in range, convert to months and days in month */
980*2d4e511cSCy Schubert 	if (eyd >= 0 && eyd < 367) {
981*2d4e511cSCy Schubert 		res.hi = (eyd * 67 + 32) >> 11;
982*2d4e511cSCy Schubert 		res.lo = eyd - ((489 * res.hi + 8) >> 4);
9832b15cb3dSCy Schubert 	}
9842b15cb3dSCy Schubert 
9852b15cb3dSCy Schubert 	return res;
9862b15cb3dSCy Schubert }
9872b15cb3dSCy Schubert 
9882b15cb3dSCy Schubert /*
9892b15cb3dSCy Schubert  *---------------------------------------------------------------------
9902b15cb3dSCy Schubert  * Convert a RD into the date part of a 'struct calendar'.
9912b15cb3dSCy Schubert  *---------------------------------------------------------------------
9922b15cb3dSCy Schubert  */
9932b15cb3dSCy Schubert int
ntpcal_rd_to_date(struct calendar * jd,int32_t rd)9942b15cb3dSCy Schubert ntpcal_rd_to_date(
9952b15cb3dSCy Schubert 	struct calendar *jd,
9962b15cb3dSCy Schubert 	int32_t		 rd
9972b15cb3dSCy Schubert 	)
9982b15cb3dSCy Schubert {
9992b15cb3dSCy Schubert 	ntpcal_split split;
10009034852cSGleb Smirnoff 	int	     leapy;
10019034852cSGleb Smirnoff 	u_int	     ymask;
10022b15cb3dSCy Schubert 
1003*2d4e511cSCy Schubert 	/* Get day-of-week first. It's simply the RD (mod 7)... */
1004*2d4e511cSCy Schubert 	jd->weekday = i32mod7(rd);
10052b15cb3dSCy Schubert 
10069034852cSGleb Smirnoff 	split = ntpcal_split_eradays(rd - 1, &leapy);
10079034852cSGleb Smirnoff 	/* Get year and day-of-year, with overflow check. If any of the
10089034852cSGleb Smirnoff 	 * upper 16 bits is set after shifting to unity-based years, we
10099034852cSGleb Smirnoff 	 * will have an overflow when converting to an unsigned 16bit
10109034852cSGleb Smirnoff 	 * year. Shifting to the right is OK here, since it does not
10119034852cSGleb Smirnoff 	 * matter if the shift is logic or arithmetic.
10129034852cSGleb Smirnoff 	 */
10139034852cSGleb Smirnoff 	split.hi += 1;
10149034852cSGleb Smirnoff 	ymask = 0u - ((split.hi >> 16) == 0);
10159034852cSGleb Smirnoff 	jd->year = (uint16_t)(split.hi & ymask);
10162b15cb3dSCy Schubert 	jd->yearday = (uint16_t)split.lo + 1;
10172b15cb3dSCy Schubert 
10182b15cb3dSCy Schubert 	/* convert to month and mday */
10199034852cSGleb Smirnoff 	split = ntpcal_split_yeardays(split.lo, leapy);
10202b15cb3dSCy Schubert 	jd->month    = (uint8_t)split.hi + 1;
10212b15cb3dSCy Schubert 	jd->monthday = (uint8_t)split.lo + 1;
10222b15cb3dSCy Schubert 
10239034852cSGleb Smirnoff 	return ymask ? leapy : -1;
10242b15cb3dSCy Schubert }
10252b15cb3dSCy Schubert 
10262b15cb3dSCy Schubert /*
10272b15cb3dSCy Schubert  *---------------------------------------------------------------------
10282b15cb3dSCy Schubert  * Convert a RD into the date part of a 'struct tm'.
10292b15cb3dSCy Schubert  *---------------------------------------------------------------------
10302b15cb3dSCy Schubert  */
10312b15cb3dSCy Schubert int
ntpcal_rd_to_tm(struct tm * utm,int32_t rd)10322b15cb3dSCy Schubert ntpcal_rd_to_tm(
10332b15cb3dSCy Schubert 	struct tm  *utm,
10342b15cb3dSCy Schubert 	int32_t	    rd
10352b15cb3dSCy Schubert 	)
10362b15cb3dSCy Schubert {
10372b15cb3dSCy Schubert 	ntpcal_split split;
10389034852cSGleb Smirnoff 	int	     leapy;
10392b15cb3dSCy Schubert 
10402b15cb3dSCy Schubert 	/* get day-of-week first */
1041*2d4e511cSCy Schubert 	utm->tm_wday = i32mod7(rd);
10422b15cb3dSCy Schubert 
10432b15cb3dSCy Schubert 	/* get year and day-of-year */
10449034852cSGleb Smirnoff 	split = ntpcal_split_eradays(rd - 1, &leapy);
10452b15cb3dSCy Schubert 	utm->tm_year = split.hi - 1899;
10462b15cb3dSCy Schubert 	utm->tm_yday = split.lo;	/* 0-based */
10472b15cb3dSCy Schubert 
10482b15cb3dSCy Schubert 	/* convert to month and mday */
10499034852cSGleb Smirnoff 	split = ntpcal_split_yeardays(split.lo, leapy);
10502b15cb3dSCy Schubert 	utm->tm_mon  = split.hi;	/* 0-based */
10512b15cb3dSCy Schubert 	utm->tm_mday = split.lo + 1;	/* 1-based */
10522b15cb3dSCy Schubert 
10539034852cSGleb Smirnoff 	return leapy;
10542b15cb3dSCy Schubert }
10552b15cb3dSCy Schubert 
10562b15cb3dSCy Schubert /*
10572b15cb3dSCy Schubert  *---------------------------------------------------------------------
10582b15cb3dSCy Schubert  * Take a value of seconds since midnight and split it into hhmmss in a
10592b15cb3dSCy Schubert  * 'struct calendar'.
10602b15cb3dSCy Schubert  *---------------------------------------------------------------------
10612b15cb3dSCy Schubert  */
10622b15cb3dSCy Schubert int32_t
ntpcal_daysec_to_date(struct calendar * jd,int32_t sec)10632b15cb3dSCy Schubert ntpcal_daysec_to_date(
10642b15cb3dSCy Schubert 	struct calendar *jd,
10652b15cb3dSCy Schubert 	int32_t		sec
10662b15cb3dSCy Schubert 	)
10672b15cb3dSCy Schubert {
10682b15cb3dSCy Schubert 	int32_t days;
10692b15cb3dSCy Schubert 	int   ts[3];
10702b15cb3dSCy Schubert 
10712b15cb3dSCy Schubert 	days = priv_timesplit(ts, sec);
10722b15cb3dSCy Schubert 	jd->hour   = (uint8_t)ts[0];
10732b15cb3dSCy Schubert 	jd->minute = (uint8_t)ts[1];
10742b15cb3dSCy Schubert 	jd->second = (uint8_t)ts[2];
10752b15cb3dSCy Schubert 
10762b15cb3dSCy Schubert 	return days;
10772b15cb3dSCy Schubert }
10782b15cb3dSCy Schubert 
10792b15cb3dSCy Schubert /*
10802b15cb3dSCy Schubert  *---------------------------------------------------------------------
10812b15cb3dSCy Schubert  * Take a value of seconds since midnight and split it into hhmmss in a
10822b15cb3dSCy Schubert  * 'struct tm'.
10832b15cb3dSCy Schubert  *---------------------------------------------------------------------
10842b15cb3dSCy Schubert  */
10852b15cb3dSCy Schubert int32_t
ntpcal_daysec_to_tm(struct tm * utm,int32_t sec)10862b15cb3dSCy Schubert ntpcal_daysec_to_tm(
10872b15cb3dSCy Schubert 	struct tm *utm,
10882b15cb3dSCy Schubert 	int32_t	   sec
10892b15cb3dSCy Schubert 	)
10902b15cb3dSCy Schubert {
10912b15cb3dSCy Schubert 	int32_t days;
10922b15cb3dSCy Schubert 	int32_t ts[3];
10932b15cb3dSCy Schubert 
10942b15cb3dSCy Schubert 	days = priv_timesplit(ts, sec);
10952b15cb3dSCy Schubert 	utm->tm_hour = ts[0];
10962b15cb3dSCy Schubert 	utm->tm_min  = ts[1];
10972b15cb3dSCy Schubert 	utm->tm_sec  = ts[2];
10982b15cb3dSCy Schubert 
10992b15cb3dSCy Schubert 	return days;
11002b15cb3dSCy Schubert }
11012b15cb3dSCy Schubert 
11022b15cb3dSCy Schubert /*
11032b15cb3dSCy Schubert  *---------------------------------------------------------------------
11042b15cb3dSCy Schubert  * take a split representation for day/second-of-day and day offset
11052b15cb3dSCy Schubert  * and convert it to a 'struct calendar'. The seconds will be normalised
11062b15cb3dSCy Schubert  * into the range of a day, and the day will be adjusted accordingly.
11072b15cb3dSCy Schubert  *
11082b15cb3dSCy Schubert  * returns >0 if the result is in a leap year, 0 if in a regular
11092b15cb3dSCy Schubert  * year and <0 if the result did not fit into the calendar struct.
11102b15cb3dSCy Schubert  *---------------------------------------------------------------------
11112b15cb3dSCy Schubert  */
11122b15cb3dSCy Schubert int
ntpcal_daysplit_to_date(struct calendar * jd,const ntpcal_split * ds,int32_t dof)11132b15cb3dSCy Schubert ntpcal_daysplit_to_date(
11142b15cb3dSCy Schubert 	struct calendar	   *jd,
11152b15cb3dSCy Schubert 	const ntpcal_split *ds,
11162b15cb3dSCy Schubert 	int32_t		    dof
11172b15cb3dSCy Schubert 	)
11182b15cb3dSCy Schubert {
11192b15cb3dSCy Schubert 	dof += ntpcal_daysec_to_date(jd, ds->lo);
11202b15cb3dSCy Schubert 	return ntpcal_rd_to_date(jd, ds->hi + dof);
11212b15cb3dSCy Schubert }
11222b15cb3dSCy Schubert 
11232b15cb3dSCy Schubert /*
11242b15cb3dSCy Schubert  *---------------------------------------------------------------------
11252b15cb3dSCy Schubert  * take a split representation for day/second-of-day and day offset
11262b15cb3dSCy Schubert  * and convert it to a 'struct tm'. The seconds will be normalised
11272b15cb3dSCy Schubert  * into the range of a day, and the day will be adjusted accordingly.
11282b15cb3dSCy Schubert  *
11292b15cb3dSCy Schubert  * returns 1 if the result is in a leap year and zero if in a regular
11302b15cb3dSCy Schubert  * year.
11312b15cb3dSCy Schubert  *---------------------------------------------------------------------
11322b15cb3dSCy Schubert  */
11332b15cb3dSCy Schubert int
ntpcal_daysplit_to_tm(struct tm * utm,const ntpcal_split * ds,int32_t dof)11342b15cb3dSCy Schubert ntpcal_daysplit_to_tm(
11352b15cb3dSCy Schubert 	struct tm	   *utm,
11362b15cb3dSCy Schubert 	const ntpcal_split *ds ,
11372b15cb3dSCy Schubert 	int32_t		    dof
11382b15cb3dSCy Schubert 	)
11392b15cb3dSCy Schubert {
11402b15cb3dSCy Schubert 	dof += ntpcal_daysec_to_tm(utm, ds->lo);
11412b15cb3dSCy Schubert 
11422b15cb3dSCy Schubert 	return ntpcal_rd_to_tm(utm, ds->hi + dof);
11432b15cb3dSCy Schubert }
11442b15cb3dSCy Schubert 
11452b15cb3dSCy Schubert /*
11462b15cb3dSCy Schubert  *---------------------------------------------------------------------
11472b15cb3dSCy Schubert  * Take a UN*X time and convert to a calendar structure.
11482b15cb3dSCy Schubert  *---------------------------------------------------------------------
11492b15cb3dSCy Schubert  */
11502b15cb3dSCy Schubert int
ntpcal_time_to_date(struct calendar * jd,const vint64 * ts)11512b15cb3dSCy Schubert ntpcal_time_to_date(
11522b15cb3dSCy Schubert 	struct calendar	*jd,
11532b15cb3dSCy Schubert 	const vint64	*ts
11542b15cb3dSCy Schubert 	)
11552b15cb3dSCy Schubert {
11562b15cb3dSCy Schubert 	ntpcal_split ds;
11572b15cb3dSCy Schubert 
11582b15cb3dSCy Schubert 	ds = ntpcal_daysplit(ts);
11592b15cb3dSCy Schubert 	ds.hi += ntpcal_daysec_to_date(jd, ds.lo);
11602b15cb3dSCy Schubert 	ds.hi += DAY_UNIX_STARTS;
11612b15cb3dSCy Schubert 
11622b15cb3dSCy Schubert 	return ntpcal_rd_to_date(jd, ds.hi);
11632b15cb3dSCy Schubert }
11642b15cb3dSCy Schubert 
11652b15cb3dSCy Schubert 
11662b15cb3dSCy Schubert /*
1167f391d6bcSXin LI  * ====================================================================
11682b15cb3dSCy Schubert  *
11692b15cb3dSCy Schubert  * merging composite entities
11702b15cb3dSCy Schubert  *
1171f391d6bcSXin LI  * ====================================================================
11722b15cb3dSCy Schubert  */
11732b15cb3dSCy Schubert 
1174*2d4e511cSCy Schubert #if !defined(HAVE_INT64)
1175*2d4e511cSCy Schubert /* multiplication helper. Seconds in days and weeks are multiples of 128,
1176*2d4e511cSCy Schubert  * and without that factor fit well into 16 bit. So a multiplication
1177*2d4e511cSCy Schubert  * of 32bit by 16bit and some shifting can be used on pure 32bit machines
1178*2d4e511cSCy Schubert  * with compilers that do not support 64bit integers.
1179*2d4e511cSCy Schubert  *
1180*2d4e511cSCy Schubert  * Calculate ( hi * mul * 128 ) + lo
1181*2d4e511cSCy Schubert  */
1182*2d4e511cSCy Schubert static vint64
_dwjoin(uint16_t mul,int32_t hi,int32_t lo)1183*2d4e511cSCy Schubert _dwjoin(
1184*2d4e511cSCy Schubert 	uint16_t	mul,
1185*2d4e511cSCy Schubert 	int32_t		hi,
1186*2d4e511cSCy Schubert 	int32_t		lo
1187*2d4e511cSCy Schubert 	)
1188*2d4e511cSCy Schubert {
1189*2d4e511cSCy Schubert 	vint64		res;
1190*2d4e511cSCy Schubert 	uint32_t	p1, p2, sf;
1191*2d4e511cSCy Schubert 
1192*2d4e511cSCy Schubert 	/* get sign flag and absolute value of 'hi' in p1 */
1193*2d4e511cSCy Schubert 	sf = (uint32_t)-(hi < 0);
1194*2d4e511cSCy Schubert 	p1 = ((uint32_t)hi + sf) ^ sf;
1195*2d4e511cSCy Schubert 
1196*2d4e511cSCy Schubert 	/* assemble major units: res <- |hi| * mul */
1197*2d4e511cSCy Schubert 	res.D_s.lo = (p1 & 0xFFFF) * mul;
1198*2d4e511cSCy Schubert 	res.D_s.hi = 0;
1199*2d4e511cSCy Schubert 	p1 = (p1 >> 16) * mul;
1200*2d4e511cSCy Schubert 	p2 = p1 >> 16;
1201*2d4e511cSCy Schubert 	p1 = p1 << 16;
1202*2d4e511cSCy Schubert 	M_ADD(res.D_s.hi, res.D_s.lo, p2, p1);
1203*2d4e511cSCy Schubert 
1204*2d4e511cSCy Schubert 	/* mul by 128, using shift: res <-- res << 7 */
1205*2d4e511cSCy Schubert 	res.D_s.hi = (res.D_s.hi << 7) | (res.D_s.lo >> 25);
1206*2d4e511cSCy Schubert 	res.D_s.lo = (res.D_s.lo << 7);
1207*2d4e511cSCy Schubert 
1208*2d4e511cSCy Schubert 	/* fix up sign: res <-- (res + [sf|sf]) ^ [sf|sf] */
1209*2d4e511cSCy Schubert 	M_ADD(res.D_s.hi, res.D_s.lo, sf, sf);
1210*2d4e511cSCy Schubert 	res.D_s.lo ^= sf;
1211*2d4e511cSCy Schubert 	res.D_s.hi ^= sf;
1212*2d4e511cSCy Schubert 
1213*2d4e511cSCy Schubert 	/* properly add seconds: res <-- res + [sx(lo)|lo] */
1214*2d4e511cSCy Schubert 	p2 = (uint32_t)-(lo < 0);
1215*2d4e511cSCy Schubert 	p1 = (uint32_t)lo;
1216*2d4e511cSCy Schubert 	M_ADD(res.D_s.hi, res.D_s.lo, p2, p1);
1217*2d4e511cSCy Schubert 	return res;
1218*2d4e511cSCy Schubert }
1219*2d4e511cSCy Schubert #endif
1220*2d4e511cSCy Schubert 
12212b15cb3dSCy Schubert /*
12222b15cb3dSCy Schubert  *---------------------------------------------------------------------
12232b15cb3dSCy Schubert  * Merge a number of days and a number of seconds into seconds,
12242b15cb3dSCy Schubert  * expressed in 64 bits to avoid overflow.
12252b15cb3dSCy Schubert  *---------------------------------------------------------------------
12262b15cb3dSCy Schubert  */
12272b15cb3dSCy Schubert vint64
ntpcal_dayjoin(int32_t days,int32_t secs)12282b15cb3dSCy Schubert ntpcal_dayjoin(
12292b15cb3dSCy Schubert 	int32_t days,
12302b15cb3dSCy Schubert 	int32_t secs
12312b15cb3dSCy Schubert 	)
12322b15cb3dSCy Schubert {
12332b15cb3dSCy Schubert 	vint64 res;
12342b15cb3dSCy Schubert 
12359034852cSGleb Smirnoff #   if defined(HAVE_INT64)
12362b15cb3dSCy Schubert 
12372b15cb3dSCy Schubert 	res.q_s	 = days;
12382b15cb3dSCy Schubert 	res.q_s *= SECSPERDAY;
12392b15cb3dSCy Schubert 	res.q_s += secs;
12402b15cb3dSCy Schubert 
12412b15cb3dSCy Schubert #   else
12422b15cb3dSCy Schubert 
1243*2d4e511cSCy Schubert 	res = _dwjoin(675, days, secs);
1244*2d4e511cSCy Schubert 
1245*2d4e511cSCy Schubert #   endif
1246*2d4e511cSCy Schubert 
1247*2d4e511cSCy Schubert 	return res;
1248*2d4e511cSCy Schubert }
12492b15cb3dSCy Schubert 
12502b15cb3dSCy Schubert /*
1251*2d4e511cSCy Schubert  *---------------------------------------------------------------------
1252*2d4e511cSCy Schubert  * Merge a number of weeks and a number of seconds into seconds,
1253*2d4e511cSCy Schubert  * expressed in 64 bits to avoid overflow.
1254*2d4e511cSCy Schubert  *---------------------------------------------------------------------
12552b15cb3dSCy Schubert  */
1256*2d4e511cSCy Schubert vint64
ntpcal_weekjoin(int32_t week,int32_t secs)1257*2d4e511cSCy Schubert ntpcal_weekjoin(
1258*2d4e511cSCy Schubert 	int32_t week,
1259*2d4e511cSCy Schubert 	int32_t secs
1260*2d4e511cSCy Schubert 	)
1261*2d4e511cSCy Schubert {
1262*2d4e511cSCy Schubert 	vint64 res;
12632b15cb3dSCy Schubert 
1264*2d4e511cSCy Schubert #   if defined(HAVE_INT64)
12652b15cb3dSCy Schubert 
1266*2d4e511cSCy Schubert 	res.q_s	 = week;
1267*2d4e511cSCy Schubert 	res.q_s *= SECSPERWEEK;
1268*2d4e511cSCy Schubert 	res.q_s += secs;
12692b15cb3dSCy Schubert 
1270*2d4e511cSCy Schubert #   else
12712b15cb3dSCy Schubert 
1272*2d4e511cSCy Schubert 	res = _dwjoin(4725, week, secs);
12732b15cb3dSCy Schubert 
12742b15cb3dSCy Schubert #   endif
12752b15cb3dSCy Schubert 
12762b15cb3dSCy Schubert 	return res;
12772b15cb3dSCy Schubert }
12782b15cb3dSCy Schubert 
12792b15cb3dSCy Schubert /*
12802b15cb3dSCy Schubert  *---------------------------------------------------------------------
12819034852cSGleb Smirnoff  * get leap years since epoch in elapsed years
12829034852cSGleb Smirnoff  *---------------------------------------------------------------------
12839034852cSGleb Smirnoff  */
12849034852cSGleb Smirnoff int32_t
ntpcal_leapyears_in_years(int32_t years)12859034852cSGleb Smirnoff ntpcal_leapyears_in_years(
12869034852cSGleb Smirnoff 	int32_t years
12879034852cSGleb Smirnoff 	)
12889034852cSGleb Smirnoff {
12899034852cSGleb Smirnoff 	/* We use the in-out-in algorithm here, using the one's
12909034852cSGleb Smirnoff 	 * complement division trick for negative numbers. The chained
12919034852cSGleb Smirnoff 	 * division sequence by 4/25/4 gives the compiler the chance to
12929034852cSGleb Smirnoff 	 * get away with only one true division and doing shifts otherwise.
12939034852cSGleb Smirnoff 	 */
12949034852cSGleb Smirnoff 
1295*2d4e511cSCy Schubert 	uint32_t sf32, sum, uyear;
12969034852cSGleb Smirnoff 
1297*2d4e511cSCy Schubert 	sf32  = int32_sflag(years);
1298*2d4e511cSCy Schubert 	uyear = (uint32_t)years;
1299*2d4e511cSCy Schubert 	uyear ^= sf32;
13009034852cSGleb Smirnoff 
13019034852cSGleb Smirnoff 	sum  = (uyear /=  4u);	/*   4yr rule --> IN  */
13029034852cSGleb Smirnoff 	sum -= (uyear /= 25u);	/* 100yr rule --> OUT */
13039034852cSGleb Smirnoff 	sum += (uyear /=  4u);	/* 400yr rule --> IN  */
13049034852cSGleb Smirnoff 
13059034852cSGleb Smirnoff 	/* Thanks to the alternation of IN/OUT/IN we can do the sum
13069034852cSGleb Smirnoff 	 * directly and have a single one's complement operation
13079034852cSGleb Smirnoff 	 * here. (Only if the years are negative, of course.) Otherwise
13089034852cSGleb Smirnoff 	 * the one's complement would have to be done when
13099034852cSGleb Smirnoff 	 * adding/subtracting the terms.
13109034852cSGleb Smirnoff 	 */
1311*2d4e511cSCy Schubert 	return uint32_2cpl_to_int32(sf32 ^ sum);
13129034852cSGleb Smirnoff }
13139034852cSGleb Smirnoff 
13149034852cSGleb Smirnoff /*
13159034852cSGleb Smirnoff  *---------------------------------------------------------------------
13162b15cb3dSCy Schubert  * Convert elapsed years in Era into elapsed days in Era.
13172b15cb3dSCy Schubert  *---------------------------------------------------------------------
13182b15cb3dSCy Schubert  */
13192b15cb3dSCy Schubert int32_t
ntpcal_days_in_years(int32_t years)13202b15cb3dSCy Schubert ntpcal_days_in_years(
13212b15cb3dSCy Schubert 	int32_t years
13222b15cb3dSCy Schubert 	)
13232b15cb3dSCy Schubert {
13249034852cSGleb Smirnoff 	return years * DAYSPERYEAR + ntpcal_leapyears_in_years(years);
13252b15cb3dSCy Schubert }
13262b15cb3dSCy Schubert 
13272b15cb3dSCy Schubert /*
13282b15cb3dSCy Schubert  *---------------------------------------------------------------------
13292b15cb3dSCy Schubert  * Convert a number of elapsed month in a year into elapsed days in year.
13302b15cb3dSCy Schubert  *
13312b15cb3dSCy Schubert  * The month will be normalized, and 'res.hi' will contain the
13322b15cb3dSCy Schubert  * excessive years that must be considered when converting the years,
13332b15cb3dSCy Schubert  * while 'res.lo' will contain the number of elapsed days since start
13342b15cb3dSCy Schubert  * of the year.
13352b15cb3dSCy Schubert  *
13362b15cb3dSCy Schubert  * This code uses the shifted-month-approach to convert month to days,
13372b15cb3dSCy Schubert  * because then there is no need to have explicit leap year
13382b15cb3dSCy Schubert  * information.	 The slight disadvantage is that for most month values
13392b15cb3dSCy Schubert  * the result is a negative value, and the year excess is one; the
13402b15cb3dSCy Schubert  * conversion is then simply based on the start of the following year.
13412b15cb3dSCy Schubert  *---------------------------------------------------------------------
13422b15cb3dSCy Schubert  */
13432b15cb3dSCy Schubert ntpcal_split
ntpcal_days_in_months(int32_t m)13442b15cb3dSCy Schubert ntpcal_days_in_months(
13452b15cb3dSCy Schubert 	int32_t m
13462b15cb3dSCy Schubert 	)
13472b15cb3dSCy Schubert {
13482b15cb3dSCy Schubert 	ntpcal_split res;
13492b15cb3dSCy Schubert 
1350*2d4e511cSCy Schubert 	/* Add ten months with proper year adjustment. */
1351*2d4e511cSCy Schubert 	if (m < 2) {
13529034852cSGleb Smirnoff 	    res.lo  = m + 10;
1353*2d4e511cSCy Schubert 	    res.hi  = 0;
1354*2d4e511cSCy Schubert 	} else {
1355*2d4e511cSCy Schubert 	    res.lo  = m - 2;
1356*2d4e511cSCy Schubert 	    res.hi  = 1;
1357*2d4e511cSCy Schubert 	}
13582b15cb3dSCy Schubert 
1359*2d4e511cSCy Schubert 	/* Possibly normalise by floor division. This does not hapen for
1360*2d4e511cSCy Schubert 	 * input in normal range. */
13619034852cSGleb Smirnoff 	if (res.lo < 0 || res.lo >= 12) {
1362*2d4e511cSCy Schubert 		uint32_t mu, Q, sf32;
1363*2d4e511cSCy Schubert 		sf32 = int32_sflag(res.lo);
1364*2d4e511cSCy Schubert 		mu   = (uint32_t)res.lo;
1365*2d4e511cSCy Schubert 		Q    = sf32 ^ ((sf32 ^ mu) / 12u);
1366*2d4e511cSCy Schubert 
13679034852cSGleb Smirnoff 		res.hi += uint32_2cpl_to_int32(Q);
13689034852cSGleb Smirnoff 		res.lo	= mu - Q * 12u;
13692b15cb3dSCy Schubert 	}
13702b15cb3dSCy Schubert 
1371*2d4e511cSCy Schubert 	/* Get cummulated days in year with unshift. Use the fractional
1372*2d4e511cSCy Schubert 	 * interpolation with smallest possible power of two in the
1373*2d4e511cSCy Schubert 	 * divider.
1374*2d4e511cSCy Schubert 	 */
1375*2d4e511cSCy Schubert 	res.lo = ((res.lo * 979 + 16) >> 5) - 306;
13762b15cb3dSCy Schubert 
13772b15cb3dSCy Schubert 	return res;
13782b15cb3dSCy Schubert }
13792b15cb3dSCy Schubert 
13802b15cb3dSCy Schubert /*
13812b15cb3dSCy Schubert  *---------------------------------------------------------------------
13822b15cb3dSCy Schubert  * Convert ELAPSED years/months/days of gregorian calendar to elapsed
13832b15cb3dSCy Schubert  * days in Gregorian epoch.
13842b15cb3dSCy Schubert  *
13852b15cb3dSCy Schubert  * If you want to convert years and days-of-year, just give a month of
13862b15cb3dSCy Schubert  * zero.
13872b15cb3dSCy Schubert  *---------------------------------------------------------------------
13882b15cb3dSCy Schubert  */
13892b15cb3dSCy Schubert int32_t
ntpcal_edate_to_eradays(int32_t years,int32_t mons,int32_t mdays)13902b15cb3dSCy Schubert ntpcal_edate_to_eradays(
13912b15cb3dSCy Schubert 	int32_t years,
13922b15cb3dSCy Schubert 	int32_t mons,
13932b15cb3dSCy Schubert 	int32_t mdays
13942b15cb3dSCy Schubert 	)
13952b15cb3dSCy Schubert {
13962b15cb3dSCy Schubert 	ntpcal_split tmp;
13972b15cb3dSCy Schubert 	int32_t	     res;
13982b15cb3dSCy Schubert 
13992b15cb3dSCy Schubert 	if (mons) {
14002b15cb3dSCy Schubert 		tmp = ntpcal_days_in_months(mons);
14012b15cb3dSCy Schubert 		res = ntpcal_days_in_years(years + tmp.hi) + tmp.lo;
14022b15cb3dSCy Schubert 	} else
14032b15cb3dSCy Schubert 		res = ntpcal_days_in_years(years);
14042b15cb3dSCy Schubert 	res += mdays;
14052b15cb3dSCy Schubert 
14062b15cb3dSCy Schubert 	return res;
14072b15cb3dSCy Schubert }
14082b15cb3dSCy Schubert 
14092b15cb3dSCy Schubert /*
14102b15cb3dSCy Schubert  *---------------------------------------------------------------------
14112b15cb3dSCy Schubert  * Convert ELAPSED years/months/days of gregorian calendar to elapsed
14122b15cb3dSCy Schubert  * days in year.
14132b15cb3dSCy Schubert  *
1414f391d6bcSXin LI  * Note: This will give the true difference to the start of the given
1415f391d6bcSXin LI  * year, even if months & days are off-scale.
14162b15cb3dSCy Schubert  *---------------------------------------------------------------------
14172b15cb3dSCy Schubert  */
14182b15cb3dSCy Schubert int32_t
ntpcal_edate_to_yeardays(int32_t years,int32_t mons,int32_t mdays)14192b15cb3dSCy Schubert ntpcal_edate_to_yeardays(
14202b15cb3dSCy Schubert 	int32_t years,
14212b15cb3dSCy Schubert 	int32_t mons,
14222b15cb3dSCy Schubert 	int32_t mdays
14232b15cb3dSCy Schubert 	)
14242b15cb3dSCy Schubert {
14252b15cb3dSCy Schubert 	ntpcal_split tmp;
14262b15cb3dSCy Schubert 
14272b15cb3dSCy Schubert 	if (0 <= mons && mons < 12) {
1428*2d4e511cSCy Schubert 		if (mons >= 2)
1429*2d4e511cSCy Schubert 			mdays -= 2 - is_leapyear(years+1);
1430*2d4e511cSCy Schubert 		mdays += (489 * mons + 8) >> 4;
14312b15cb3dSCy Schubert 	} else {
14322b15cb3dSCy Schubert 		tmp = ntpcal_days_in_months(mons);
14332b15cb3dSCy Schubert 		mdays += tmp.lo
14342b15cb3dSCy Schubert 		       + ntpcal_days_in_years(years + tmp.hi)
14352b15cb3dSCy Schubert 		       - ntpcal_days_in_years(years);
14362b15cb3dSCy Schubert 	}
14372b15cb3dSCy Schubert 
14382b15cb3dSCy Schubert 	return mdays;
14392b15cb3dSCy Schubert }
14402b15cb3dSCy Schubert 
14412b15cb3dSCy Schubert /*
14422b15cb3dSCy Schubert  *---------------------------------------------------------------------
14432b15cb3dSCy Schubert  * Convert elapsed days and the hour/minute/second information into
14442b15cb3dSCy Schubert  * total seconds.
14452b15cb3dSCy Schubert  *
14462b15cb3dSCy Schubert  * If 'isvalid' is not NULL, do a range check on the time specification
14472b15cb3dSCy Schubert  * and tell if the time input is in the normal range, permitting for a
14482b15cb3dSCy Schubert  * single leapsecond.
14492b15cb3dSCy Schubert  *---------------------------------------------------------------------
14502b15cb3dSCy Schubert  */
14512b15cb3dSCy Schubert int32_t
ntpcal_etime_to_seconds(int32_t hours,int32_t minutes,int32_t seconds)14522b15cb3dSCy Schubert ntpcal_etime_to_seconds(
14532b15cb3dSCy Schubert 	int32_t hours,
14542b15cb3dSCy Schubert 	int32_t minutes,
14552b15cb3dSCy Schubert 	int32_t seconds
14562b15cb3dSCy Schubert 	)
14572b15cb3dSCy Schubert {
14582b15cb3dSCy Schubert 	int32_t res;
14592b15cb3dSCy Schubert 
14602b15cb3dSCy Schubert 	res = (hours * MINSPERHR + minutes) * SECSPERMIN + seconds;
14612b15cb3dSCy Schubert 
14622b15cb3dSCy Schubert 	return res;
14632b15cb3dSCy Schubert }
14642b15cb3dSCy Schubert 
14652b15cb3dSCy Schubert /*
14662b15cb3dSCy Schubert  *---------------------------------------------------------------------
14672b15cb3dSCy Schubert  * Convert the date part of a 'struct tm' (that is, year, month,
14682b15cb3dSCy Schubert  * day-of-month) into the RD of that day.
14692b15cb3dSCy Schubert  *---------------------------------------------------------------------
14702b15cb3dSCy Schubert  */
14712b15cb3dSCy Schubert int32_t
ntpcal_tm_to_rd(const struct tm * utm)14722b15cb3dSCy Schubert ntpcal_tm_to_rd(
14732b15cb3dSCy Schubert 	const struct tm *utm
14742b15cb3dSCy Schubert 	)
14752b15cb3dSCy Schubert {
14762b15cb3dSCy Schubert 	return ntpcal_edate_to_eradays(utm->tm_year + 1899,
14772b15cb3dSCy Schubert 				       utm->tm_mon,
14782b15cb3dSCy Schubert 				       utm->tm_mday - 1) + 1;
14792b15cb3dSCy Schubert }
14802b15cb3dSCy Schubert 
14812b15cb3dSCy Schubert /*
14822b15cb3dSCy Schubert  *---------------------------------------------------------------------
14832b15cb3dSCy Schubert  * Convert the date part of a 'struct calendar' (that is, year, month,
14842b15cb3dSCy Schubert  * day-of-month) into the RD of that day.
14852b15cb3dSCy Schubert  *---------------------------------------------------------------------
14862b15cb3dSCy Schubert  */
14872b15cb3dSCy Schubert int32_t
ntpcal_date_to_rd(const struct calendar * jd)14882b15cb3dSCy Schubert ntpcal_date_to_rd(
14892b15cb3dSCy Schubert 	const struct calendar *jd
14902b15cb3dSCy Schubert 	)
14912b15cb3dSCy Schubert {
14922b15cb3dSCy Schubert 	return ntpcal_edate_to_eradays((int32_t)jd->year - 1,
14932b15cb3dSCy Schubert 				       (int32_t)jd->month - 1,
14942b15cb3dSCy Schubert 				       (int32_t)jd->monthday - 1) + 1;
14952b15cb3dSCy Schubert }
14962b15cb3dSCy Schubert 
14972b15cb3dSCy Schubert /*
14982b15cb3dSCy Schubert  *---------------------------------------------------------------------
14992b15cb3dSCy Schubert  * convert a year number to rata die of year start
15002b15cb3dSCy Schubert  *---------------------------------------------------------------------
15012b15cb3dSCy Schubert  */
15022b15cb3dSCy Schubert int32_t
ntpcal_year_to_ystart(int32_t year)15032b15cb3dSCy Schubert ntpcal_year_to_ystart(
15042b15cb3dSCy Schubert 	int32_t year
15052b15cb3dSCy Schubert 	)
15062b15cb3dSCy Schubert {
15072b15cb3dSCy Schubert 	return ntpcal_days_in_years(year - 1) + 1;
15082b15cb3dSCy Schubert }
15092b15cb3dSCy Schubert 
15102b15cb3dSCy Schubert /*
15112b15cb3dSCy Schubert  *---------------------------------------------------------------------
15122b15cb3dSCy Schubert  * For a given RD, get the RD of the associated year start,
15132b15cb3dSCy Schubert  * that is, the RD of the last January,1st on or before that day.
15142b15cb3dSCy Schubert  *---------------------------------------------------------------------
15152b15cb3dSCy Schubert  */
15162b15cb3dSCy Schubert int32_t
ntpcal_rd_to_ystart(int32_t rd)15172b15cb3dSCy Schubert ntpcal_rd_to_ystart(
15182b15cb3dSCy Schubert 	int32_t rd
15192b15cb3dSCy Schubert 	)
15202b15cb3dSCy Schubert {
15212b15cb3dSCy Schubert 	/*
15222b15cb3dSCy Schubert 	 * Rather simple exercise: split the day number into elapsed
15232b15cb3dSCy Schubert 	 * years and elapsed days, then remove the elapsed days from the
15242b15cb3dSCy Schubert 	 * input value. Nice'n sweet...
15252b15cb3dSCy Schubert 	 */
15262b15cb3dSCy Schubert 	return rd - ntpcal_split_eradays(rd - 1, NULL).lo;
15272b15cb3dSCy Schubert }
15282b15cb3dSCy Schubert 
15292b15cb3dSCy Schubert /*
15302b15cb3dSCy Schubert  *---------------------------------------------------------------------
15312b15cb3dSCy Schubert  * For a given RD, get the RD of the associated month start.
15322b15cb3dSCy Schubert  *---------------------------------------------------------------------
15332b15cb3dSCy Schubert  */
15342b15cb3dSCy Schubert int32_t
ntpcal_rd_to_mstart(int32_t rd)15352b15cb3dSCy Schubert ntpcal_rd_to_mstart(
15362b15cb3dSCy Schubert 	int32_t rd
15372b15cb3dSCy Schubert 	)
15382b15cb3dSCy Schubert {
15392b15cb3dSCy Schubert 	ntpcal_split split;
15402b15cb3dSCy Schubert 	int	     leaps;
15412b15cb3dSCy Schubert 
15422b15cb3dSCy Schubert 	split = ntpcal_split_eradays(rd - 1, &leaps);
15432b15cb3dSCy Schubert 	split = ntpcal_split_yeardays(split.lo, leaps);
15442b15cb3dSCy Schubert 
15452b15cb3dSCy Schubert 	return rd - split.lo;
15462b15cb3dSCy Schubert }
15472b15cb3dSCy Schubert 
15482b15cb3dSCy Schubert /*
15492b15cb3dSCy Schubert  *---------------------------------------------------------------------
15502b15cb3dSCy Schubert  * take a 'struct calendar' and get the seconds-of-day from it.
15512b15cb3dSCy Schubert  *---------------------------------------------------------------------
15522b15cb3dSCy Schubert  */
15532b15cb3dSCy Schubert int32_t
ntpcal_date_to_daysec(const struct calendar * jd)15542b15cb3dSCy Schubert ntpcal_date_to_daysec(
15552b15cb3dSCy Schubert 	const struct calendar *jd
15562b15cb3dSCy Schubert 	)
15572b15cb3dSCy Schubert {
15582b15cb3dSCy Schubert 	return ntpcal_etime_to_seconds(jd->hour, jd->minute,
15592b15cb3dSCy Schubert 				       jd->second);
15602b15cb3dSCy Schubert }
15612b15cb3dSCy Schubert 
15622b15cb3dSCy Schubert /*
15632b15cb3dSCy Schubert  *---------------------------------------------------------------------
15642b15cb3dSCy Schubert  * take a 'struct tm' and get the seconds-of-day from it.
15652b15cb3dSCy Schubert  *---------------------------------------------------------------------
15662b15cb3dSCy Schubert  */
15672b15cb3dSCy Schubert int32_t
ntpcal_tm_to_daysec(const struct tm * utm)15682b15cb3dSCy Schubert ntpcal_tm_to_daysec(
15692b15cb3dSCy Schubert 	const struct tm *utm
15702b15cb3dSCy Schubert 	)
15712b15cb3dSCy Schubert {
15722b15cb3dSCy Schubert 	return ntpcal_etime_to_seconds(utm->tm_hour, utm->tm_min,
15732b15cb3dSCy Schubert 				       utm->tm_sec);
15742b15cb3dSCy Schubert }
15752b15cb3dSCy Schubert 
15762b15cb3dSCy Schubert /*
15772b15cb3dSCy Schubert  *---------------------------------------------------------------------
15782b15cb3dSCy Schubert  * take a 'struct calendar' and convert it to a 'time_t'
15792b15cb3dSCy Schubert  *---------------------------------------------------------------------
15802b15cb3dSCy Schubert  */
15812b15cb3dSCy Schubert time_t
ntpcal_date_to_time(const struct calendar * jd)15822b15cb3dSCy Schubert ntpcal_date_to_time(
15832b15cb3dSCy Schubert 	const struct calendar *jd
15842b15cb3dSCy Schubert 	)
15852b15cb3dSCy Schubert {
15862b15cb3dSCy Schubert 	vint64	join;
15872b15cb3dSCy Schubert 	int32_t days, secs;
15882b15cb3dSCy Schubert 
15892b15cb3dSCy Schubert 	days = ntpcal_date_to_rd(jd) - DAY_UNIX_STARTS;
15902b15cb3dSCy Schubert 	secs = ntpcal_date_to_daysec(jd);
15912b15cb3dSCy Schubert 	join = ntpcal_dayjoin(days, secs);
15922b15cb3dSCy Schubert 
15932b15cb3dSCy Schubert 	return vint64_to_time(&join);
15942b15cb3dSCy Schubert }
15952b15cb3dSCy Schubert 
15962b15cb3dSCy Schubert 
15972b15cb3dSCy Schubert /*
1598f391d6bcSXin LI  * ====================================================================
15992b15cb3dSCy Schubert  *
16002b15cb3dSCy Schubert  * extended and unchecked variants of caljulian/caltontp
16012b15cb3dSCy Schubert  *
1602f391d6bcSXin LI  * ====================================================================
16032b15cb3dSCy Schubert  */
16042b15cb3dSCy Schubert int
ntpcal_ntp64_to_date(struct calendar * jd,const vint64 * ntp)16052b15cb3dSCy Schubert ntpcal_ntp64_to_date(
16062b15cb3dSCy Schubert 	struct calendar *jd,
16072b15cb3dSCy Schubert 	const vint64	*ntp
16082b15cb3dSCy Schubert 	)
16092b15cb3dSCy Schubert {
16102b15cb3dSCy Schubert 	ntpcal_split ds;
16112b15cb3dSCy Schubert 
16122b15cb3dSCy Schubert 	ds = ntpcal_daysplit(ntp);
16132b15cb3dSCy Schubert 	ds.hi += ntpcal_daysec_to_date(jd, ds.lo);
16142b15cb3dSCy Schubert 
16152b15cb3dSCy Schubert 	return ntpcal_rd_to_date(jd, ds.hi + DAY_NTP_STARTS);
16162b15cb3dSCy Schubert }
16172b15cb3dSCy Schubert 
16182b15cb3dSCy Schubert int
ntpcal_ntp_to_date(struct calendar * jd,uint32_t ntp,const time_t * piv)16192b15cb3dSCy Schubert ntpcal_ntp_to_date(
16202b15cb3dSCy Schubert 	struct calendar *jd,
16212b15cb3dSCy Schubert 	uint32_t	 ntp,
16222b15cb3dSCy Schubert 	const time_t	*piv
16232b15cb3dSCy Schubert 	)
16242b15cb3dSCy Schubert {
16252b15cb3dSCy Schubert 	vint64	ntp64;
16262b15cb3dSCy Schubert 
16272b15cb3dSCy Schubert 	/*
16282b15cb3dSCy Schubert 	 * Unfold ntp time around current time into NTP domain. Split
16292b15cb3dSCy Schubert 	 * into days and seconds, shift days into CE domain and
16302b15cb3dSCy Schubert 	 * process the parts.
16312b15cb3dSCy Schubert 	 */
16322b15cb3dSCy Schubert 	ntp64 = ntpcal_ntp_to_ntp(ntp, piv);
16332b15cb3dSCy Schubert 	return ntpcal_ntp64_to_date(jd, &ntp64);
16342b15cb3dSCy Schubert }
16352b15cb3dSCy Schubert 
16362b15cb3dSCy Schubert 
16372b15cb3dSCy Schubert vint64
ntpcal_date_to_ntp64(const struct calendar * jd)16382b15cb3dSCy Schubert ntpcal_date_to_ntp64(
16392b15cb3dSCy Schubert 	const struct calendar *jd
16402b15cb3dSCy Schubert 	)
16412b15cb3dSCy Schubert {
16422b15cb3dSCy Schubert 	/*
16432b15cb3dSCy Schubert 	 * Convert date to NTP. Ignore yearday, use d/m/y only.
16442b15cb3dSCy Schubert 	 */
16452b15cb3dSCy Schubert 	return ntpcal_dayjoin(ntpcal_date_to_rd(jd) - DAY_NTP_STARTS,
16462b15cb3dSCy Schubert 			      ntpcal_date_to_daysec(jd));
16472b15cb3dSCy Schubert }
16482b15cb3dSCy Schubert 
16492b15cb3dSCy Schubert 
16502b15cb3dSCy Schubert uint32_t
ntpcal_date_to_ntp(const struct calendar * jd)16512b15cb3dSCy Schubert ntpcal_date_to_ntp(
16522b15cb3dSCy Schubert 	const struct calendar *jd
16532b15cb3dSCy Schubert 	)
16542b15cb3dSCy Schubert {
16552b15cb3dSCy Schubert 	/*
1656*2d4e511cSCy Schubert 	 * Get lower half of 64bit NTP timestamp from date/time.
16572b15cb3dSCy Schubert 	 */
16582b15cb3dSCy Schubert 	return ntpcal_date_to_ntp64(jd).d_s.lo;
16592b15cb3dSCy Schubert }
16602b15cb3dSCy Schubert 
16612b15cb3dSCy Schubert 
16622b15cb3dSCy Schubert 
16632b15cb3dSCy Schubert /*
1664f391d6bcSXin LI  * ====================================================================
16652b15cb3dSCy Schubert  *
16662b15cb3dSCy Schubert  * day-of-week calculations
16672b15cb3dSCy Schubert  *
1668f391d6bcSXin LI  * ====================================================================
16692b15cb3dSCy Schubert  */
16702b15cb3dSCy Schubert /*
16712b15cb3dSCy Schubert  * Given a RataDie and a day-of-week, calculate a RDN that is reater-than,
16722b15cb3dSCy Schubert  * greater-or equal, closest, less-or-equal or less-than the given RDN
16732b15cb3dSCy Schubert  * and denotes the given day-of-week
16742b15cb3dSCy Schubert  */
16752b15cb3dSCy Schubert int32_t
ntpcal_weekday_gt(int32_t rdn,int32_t dow)16762b15cb3dSCy Schubert ntpcal_weekday_gt(
16772b15cb3dSCy Schubert 	int32_t rdn,
16782b15cb3dSCy Schubert 	int32_t dow
16792b15cb3dSCy Schubert 	)
16802b15cb3dSCy Schubert {
16812b15cb3dSCy Schubert 	return ntpcal_periodic_extend(rdn+1, dow, 7);
16822b15cb3dSCy Schubert }
16832b15cb3dSCy Schubert 
16842b15cb3dSCy Schubert int32_t
ntpcal_weekday_ge(int32_t rdn,int32_t dow)16852b15cb3dSCy Schubert ntpcal_weekday_ge(
16862b15cb3dSCy Schubert 	int32_t rdn,
16872b15cb3dSCy Schubert 	int32_t dow
16882b15cb3dSCy Schubert 	)
16892b15cb3dSCy Schubert {
16902b15cb3dSCy Schubert 	return ntpcal_periodic_extend(rdn, dow, 7);
16912b15cb3dSCy Schubert }
16922b15cb3dSCy Schubert 
16932b15cb3dSCy Schubert int32_t
ntpcal_weekday_close(int32_t rdn,int32_t dow)16942b15cb3dSCy Schubert ntpcal_weekday_close(
16952b15cb3dSCy Schubert 	int32_t rdn,
16962b15cb3dSCy Schubert 	int32_t dow
16972b15cb3dSCy Schubert 	)
16982b15cb3dSCy Schubert {
16992b15cb3dSCy Schubert 	return ntpcal_periodic_extend(rdn-3, dow, 7);
17002b15cb3dSCy Schubert }
17012b15cb3dSCy Schubert 
17022b15cb3dSCy Schubert int32_t
ntpcal_weekday_le(int32_t rdn,int32_t dow)17032b15cb3dSCy Schubert ntpcal_weekday_le(
17042b15cb3dSCy Schubert 	int32_t rdn,
17052b15cb3dSCy Schubert 	int32_t dow
17062b15cb3dSCy Schubert 	)
17072b15cb3dSCy Schubert {
17082b15cb3dSCy Schubert 	return ntpcal_periodic_extend(rdn, dow, -7);
17092b15cb3dSCy Schubert }
17102b15cb3dSCy Schubert 
17112b15cb3dSCy Schubert int32_t
ntpcal_weekday_lt(int32_t rdn,int32_t dow)17122b15cb3dSCy Schubert ntpcal_weekday_lt(
17132b15cb3dSCy Schubert 	int32_t rdn,
17142b15cb3dSCy Schubert 	int32_t dow
17152b15cb3dSCy Schubert 	)
17162b15cb3dSCy Schubert {
17172b15cb3dSCy Schubert 	return ntpcal_periodic_extend(rdn-1, dow, -7);
17182b15cb3dSCy Schubert }
17192b15cb3dSCy Schubert 
17202b15cb3dSCy Schubert /*
1721f391d6bcSXin LI  * ====================================================================
17222b15cb3dSCy Schubert  *
17232b15cb3dSCy Schubert  * ISO week-calendar conversions
17242b15cb3dSCy Schubert  *
17252b15cb3dSCy Schubert  * The ISO8601 calendar defines a calendar of years, weeks and weekdays.
17262b15cb3dSCy Schubert  * It is related to the Gregorian calendar, and a ISO year starts at the
17272b15cb3dSCy Schubert  * Monday closest to Jan,1st of the corresponding Gregorian year.  A ISO
17282b15cb3dSCy Schubert  * calendar year has always 52 or 53 weeks, and like the Grogrian
17292b15cb3dSCy Schubert  * calendar the ISO8601 calendar repeats itself every 400 years, or
17302b15cb3dSCy Schubert  * 146097 days, or 20871 weeks.
17312b15cb3dSCy Schubert  *
17322b15cb3dSCy Schubert  * While it is possible to write ISO calendar functions based on the
17332b15cb3dSCy Schubert  * Gregorian calendar functions, the following implementation takes a
17342b15cb3dSCy Schubert  * different approach, based directly on years and weeks.
17352b15cb3dSCy Schubert  *
17362b15cb3dSCy Schubert  * Analysis of the tabulated data shows that it is not possible to
17372b15cb3dSCy Schubert  * interpolate from years to weeks over a full 400 year range; cyclic
17382b15cb3dSCy Schubert  * shifts over 400 years do not provide a solution here. But it *is*
17392b15cb3dSCy Schubert  * possible to interpolate over every single century of the 400-year
17402b15cb3dSCy Schubert  * cycle. (The centennial leap year rule seems to be the culprit here.)
17412b15cb3dSCy Schubert  *
17422b15cb3dSCy Schubert  * It can be shown that a conversion from years to weeks can be done
17432b15cb3dSCy Schubert  * using a linear transformation of the form
17442b15cb3dSCy Schubert  *
17452b15cb3dSCy Schubert  *   w = floor( y * a + b )
17462b15cb3dSCy Schubert  *
17472b15cb3dSCy Schubert  * where the slope a must hold to
17482b15cb3dSCy Schubert  *
17492b15cb3dSCy Schubert  *  52.1780821918 <= a < 52.1791044776
17502b15cb3dSCy Schubert  *
17512b15cb3dSCy Schubert  * and b must be chosen according to the selected slope and the number
17522b15cb3dSCy Schubert  * of the century in a 400-year period.
17532b15cb3dSCy Schubert  *
17542b15cb3dSCy Schubert  * The inverse calculation can also be done in this way. Careful scaling
17552b15cb3dSCy Schubert  * provides an unlimited set of integer coefficients a,k,b that enable
17562b15cb3dSCy Schubert  * us to write the calulation in the form
17572b15cb3dSCy Schubert  *
17582b15cb3dSCy Schubert  *   w = (y * a	 + b ) / k
17592b15cb3dSCy Schubert  *   y = (w * a' + b') / k'
17602b15cb3dSCy Schubert  *
1761*2d4e511cSCy Schubert  * In this implementation the values of k and k' are chosen to be the
17622b15cb3dSCy Schubert  * smallest possible powers of two, so the division can be implemented
17632b15cb3dSCy Schubert  * as shifts if the optimiser chooses to do so.
17642b15cb3dSCy Schubert  *
1765f391d6bcSXin LI  * ====================================================================
17662b15cb3dSCy Schubert  */
17672b15cb3dSCy Schubert 
17682b15cb3dSCy Schubert /*
17692b15cb3dSCy Schubert  * Given a number of elapsed (ISO-)years since the begin of the
17702b15cb3dSCy Schubert  * christian era, return the number of elapsed weeks corresponding to
17712b15cb3dSCy Schubert  * the number of years.
17722b15cb3dSCy Schubert  */
17732b15cb3dSCy Schubert int32_t
isocal_weeks_in_years(int32_t years)17742b15cb3dSCy Schubert isocal_weeks_in_years(
17752b15cb3dSCy Schubert 	int32_t years
17762b15cb3dSCy Schubert 	)
17772b15cb3dSCy Schubert {
17782b15cb3dSCy Schubert 	/*
17792b15cb3dSCy Schubert 	 * use: w = (y * 53431 + b[c]) / 1024 as interpolation
17802b15cb3dSCy Schubert 	 */
17819034852cSGleb Smirnoff 	static const uint16_t bctab[4] = { 157, 449, 597, 889 };
17822b15cb3dSCy Schubert 
17839034852cSGleb Smirnoff 	int32_t	 cs, cw;
1784*2d4e511cSCy Schubert 	uint32_t cc, ci, yu, sf32;
17852b15cb3dSCy Schubert 
1786*2d4e511cSCy Schubert 	sf32 = int32_sflag(years);
1787*2d4e511cSCy Schubert 	yu   = (uint32_t)years;
17882b15cb3dSCy Schubert 
17899034852cSGleb Smirnoff 	/* split off centuries, using floor division */
1790*2d4e511cSCy Schubert 	cc  = sf32 ^ ((sf32 ^ yu) / 100u);
17919034852cSGleb Smirnoff 	yu -= cc * 100u;
17929034852cSGleb Smirnoff 
17939034852cSGleb Smirnoff 	/* calculate century cycles shift and cycle index:
17949034852cSGleb Smirnoff 	 * Assuming a century is 5217 weeks, we have to add a cycle
17959034852cSGleb Smirnoff 	 * shift that is 3 for every 4 centuries, because 3 of the four
17969034852cSGleb Smirnoff 	 * centuries have 5218 weeks. So '(cc*3 + 1) / 4' is the actual
17979034852cSGleb Smirnoff 	 * correction, and the second century is the defective one.
17989034852cSGleb Smirnoff 	 *
17999034852cSGleb Smirnoff 	 * Needs floor division by 4, which is done with masking and
18009034852cSGleb Smirnoff 	 * shifting.
18012b15cb3dSCy Schubert 	 */
18029034852cSGleb Smirnoff 	ci = cc * 3u + 1;
1803*2d4e511cSCy Schubert 	cs = uint32_2cpl_to_int32(sf32 ^ ((sf32 ^ ci) >> 2));
1804*2d4e511cSCy Schubert 	ci = ci & 3u;
18052b15cb3dSCy Schubert 
18069034852cSGleb Smirnoff 	/* Get weeks in century. Can use plain division here as all ops
18079034852cSGleb Smirnoff 	 * are >= 0,  and let the compiler sort out the possible
18089034852cSGleb Smirnoff 	 * optimisations.
18099034852cSGleb Smirnoff 	 */
18109034852cSGleb Smirnoff 	cw = (yu * 53431u + bctab[ci]) / 1024u;
18119034852cSGleb Smirnoff 
18129034852cSGleb Smirnoff 	return uint32_2cpl_to_int32(cc) * 5217 + cs + cw;
18132b15cb3dSCy Schubert }
18142b15cb3dSCy Schubert 
18152b15cb3dSCy Schubert /*
18162b15cb3dSCy Schubert  * Given a number of elapsed weeks since the begin of the christian
18172b15cb3dSCy Schubert  * era, split this number into the number of elapsed years in res.hi
18182b15cb3dSCy Schubert  * and the excessive number of weeks in res.lo. (That is, res.lo is
18192b15cb3dSCy Schubert  * the number of elapsed weeks in the remaining partial year.)
18202b15cb3dSCy Schubert  */
18212b15cb3dSCy Schubert ntpcal_split
isocal_split_eraweeks(int32_t weeks)18222b15cb3dSCy Schubert isocal_split_eraweeks(
18232b15cb3dSCy Schubert 	int32_t weeks
18242b15cb3dSCy Schubert 	)
18252b15cb3dSCy Schubert {
18262b15cb3dSCy Schubert 	/*
18272b15cb3dSCy Schubert 	 * use: y = (w * 157 + b[c]) / 8192 as interpolation
18282b15cb3dSCy Schubert 	 */
18299034852cSGleb Smirnoff 
18309034852cSGleb Smirnoff 	static const uint16_t bctab[4] = { 85, 130, 17, 62 };
18319034852cSGleb Smirnoff 
18322b15cb3dSCy Schubert 	ntpcal_split res;
18339034852cSGleb Smirnoff 	int32_t	 cc, ci;
1834*2d4e511cSCy Schubert 	uint32_t sw, cy, Q;
18352b15cb3dSCy Schubert 
1836*2d4e511cSCy Schubert 	/* Use two fast cycle-split divisions again. Herew e want to
1837*2d4e511cSCy Schubert 	 * execute '(weeks * 4 + 2) /% 20871' under floor division rules
1838*2d4e511cSCy Schubert 	 * in the first step.
18399034852cSGleb Smirnoff 	 *
1840*2d4e511cSCy Schubert 	 * This is of course (again) susceptible to internal overflow if
1841*2d4e511cSCy Schubert 	 * coded directly in 32bit. And again we use 64bit division on
1842*2d4e511cSCy Schubert 	 * a 64bit target and exact division after calculating the
1843*2d4e511cSCy Schubert 	 * remainder first on a 32bit target. With the smaller divider,
1844*2d4e511cSCy Schubert 	 * that's even a bit neater.
18452b15cb3dSCy Schubert 	 */
1846*2d4e511cSCy Schubert #   if defined(HAVE_64BITREGS)
1847*2d4e511cSCy Schubert 
1848*2d4e511cSCy Schubert 	/* Full floor division with 64bit values. */
1849*2d4e511cSCy Schubert 	uint64_t sf64, sw64;
1850*2d4e511cSCy Schubert 	sf64 = (uint64_t)-(weeks < 0);
1851*2d4e511cSCy Schubert 	sw64 = ((uint64_t)weeks << 2) | 2u;
1852*2d4e511cSCy Schubert 	Q    = (uint32_t)(sf64 ^ ((sf64 ^ sw64) / GREGORIAN_CYCLE_WEEKS));
1853*2d4e511cSCy Schubert 	sw   = (uint32_t)(sw64 - Q * GREGORIAN_CYCLE_WEEKS);
1854*2d4e511cSCy Schubert 
1855*2d4e511cSCy Schubert #   else
1856*2d4e511cSCy Schubert 
1857*2d4e511cSCy Schubert 	/* Exact division after calculating the remainder via partial
1858*2d4e511cSCy Schubert 	 * reduction by digit sum.
1859*2d4e511cSCy Schubert 	 * (-2^33) % 20871     --> 5491	     : the sign bit value
1860*2d4e511cSCy Schubert 	 * ( 2^20) % 20871     --> 5026	     : the upper digit value
1861*2d4e511cSCy Schubert 	 * modinv(20871, 2^32) --> 330081335 : the inverse
1862*2d4e511cSCy Schubert 	 */
1863*2d4e511cSCy Schubert 	uint32_t ux = ((uint32_t)weeks << 2) | 2;
1864*2d4e511cSCy Schubert 	sw  = (weeks < 0) ? 5491u : 0u;		  /* sign dgt */
1865*2d4e511cSCy Schubert 	sw += ((weeks >> 18) & 0x01FFFu) * 5026u; /* hi dgt (src!) */
1866*2d4e511cSCy Schubert 	sw += (ux & 0xFFFFFu);			  /* lo dgt */
1867*2d4e511cSCy Schubert 	sw %= GREGORIAN_CYCLE_WEEKS;		  /* full reduction */
1868*2d4e511cSCy Schubert 	Q   = (ux  - sw) * 330081335u;		  /* exact div */
1869*2d4e511cSCy Schubert 
1870*2d4e511cSCy Schubert #   endif
1871*2d4e511cSCy Schubert 
1872*2d4e511cSCy Schubert 	ci  = Q & 3u;
18739034852cSGleb Smirnoff 	cc  = uint32_2cpl_to_int32(Q);
18742b15cb3dSCy Schubert 
18759034852cSGleb Smirnoff 	/* Split off years; sw >= 0 here! The scaled weeks in the years
18769034852cSGleb Smirnoff 	 * are scaled up by 157 afterwards.
18772b15cb3dSCy Schubert 	 */
18789034852cSGleb Smirnoff 	sw  = (sw / 4u) * 157u + bctab[ci];
1879*2d4e511cSCy Schubert 	cy  = sw / 8192u;	/* sw >> 13 , let the compiler sort it out */
1880*2d4e511cSCy Schubert 	sw  = sw % 8192u;	/* sw & 8191, let the compiler sort it out */
18812b15cb3dSCy Schubert 
18829034852cSGleb Smirnoff 	/* assemble elapsed years and downscale the elapsed weeks in
18839034852cSGleb Smirnoff 	 * the year.
18849034852cSGleb Smirnoff 	 */
18859034852cSGleb Smirnoff 	res.hi = 100*cc + cy;
18869034852cSGleb Smirnoff 	res.lo = sw / 157u;
18872b15cb3dSCy Schubert 
18882b15cb3dSCy Schubert 	return res;
18892b15cb3dSCy Schubert }
18902b15cb3dSCy Schubert 
18912b15cb3dSCy Schubert /*
18922b15cb3dSCy Schubert  * Given a second in the NTP time scale and a pivot, expand the NTP
18932b15cb3dSCy Schubert  * time stamp around the pivot and convert into an ISO calendar time
18942b15cb3dSCy Schubert  * stamp.
18952b15cb3dSCy Schubert  */
18962b15cb3dSCy Schubert int
isocal_ntp64_to_date(struct isodate * id,const vint64 * ntp)18972b15cb3dSCy Schubert isocal_ntp64_to_date(
18982b15cb3dSCy Schubert 	struct isodate *id,
18992b15cb3dSCy Schubert 	const vint64   *ntp
19002b15cb3dSCy Schubert 	)
19012b15cb3dSCy Schubert {
19022b15cb3dSCy Schubert 	ntpcal_split ds;
19032b15cb3dSCy Schubert 	int32_t	     ts[3];
1904*2d4e511cSCy Schubert 	uint32_t     uw, ud, sf32;
19052b15cb3dSCy Schubert 
19062b15cb3dSCy Schubert 	/*
19072b15cb3dSCy Schubert 	 * Split NTP time into days and seconds, shift days into CE
19082b15cb3dSCy Schubert 	 * domain and process the parts.
19092b15cb3dSCy Schubert 	 */
19102b15cb3dSCy Schubert 	ds = ntpcal_daysplit(ntp);
19112b15cb3dSCy Schubert 
19122b15cb3dSCy Schubert 	/* split time part */
19132b15cb3dSCy Schubert 	ds.hi += priv_timesplit(ts, ds.lo);
19142b15cb3dSCy Schubert 	id->hour   = (uint8_t)ts[0];
19152b15cb3dSCy Schubert 	id->minute = (uint8_t)ts[1];
19162b15cb3dSCy Schubert 	id->second = (uint8_t)ts[2];
19172b15cb3dSCy Schubert 
19189034852cSGleb Smirnoff 	/* split days into days and weeks, using floor division in unsigned */
19199034852cSGleb Smirnoff 	ds.hi += DAY_NTP_STARTS - 1; /* shift from NTP to RDN */
1920*2d4e511cSCy Schubert 	sf32 = int32_sflag(ds.hi);
1921*2d4e511cSCy Schubert 	ud   = (uint32_t)ds.hi;
1922*2d4e511cSCy Schubert 	uw   = sf32 ^ ((sf32 ^ ud) / DAYSPERWEEK);
19239034852cSGleb Smirnoff 	ud  -= uw * DAYSPERWEEK;
1924*2d4e511cSCy Schubert 
19259034852cSGleb Smirnoff 	ds.hi = uint32_2cpl_to_int32(uw);
19269034852cSGleb Smirnoff 	ds.lo = ud;
19279034852cSGleb Smirnoff 
19282b15cb3dSCy Schubert 	id->weekday = (uint8_t)ds.lo + 1;	/* weekday result    */
19292b15cb3dSCy Schubert 
19309034852cSGleb Smirnoff 	/* get year and week in year */
19312b15cb3dSCy Schubert 	ds = isocal_split_eraweeks(ds.hi);	/* elapsed years&week*/
19322b15cb3dSCy Schubert 	id->year = (uint16_t)ds.hi + 1;		/* shift to current  */
19332b15cb3dSCy Schubert 	id->week = (uint8_t )ds.lo + 1;
19342b15cb3dSCy Schubert 
19352b15cb3dSCy Schubert 	return (ds.hi >= 0 && ds.hi < 0x0000FFFF);
19362b15cb3dSCy Schubert }
19372b15cb3dSCy Schubert 
19382b15cb3dSCy Schubert int
isocal_ntp_to_date(struct isodate * id,uint32_t ntp,const time_t * piv)19392b15cb3dSCy Schubert isocal_ntp_to_date(
19402b15cb3dSCy Schubert 	struct isodate *id,
19412b15cb3dSCy Schubert 	uint32_t	ntp,
19422b15cb3dSCy Schubert 	const time_t   *piv
19432b15cb3dSCy Schubert 	)
19442b15cb3dSCy Schubert {
19452b15cb3dSCy Schubert 	vint64	ntp64;
19462b15cb3dSCy Schubert 
19472b15cb3dSCy Schubert 	/*
19482b15cb3dSCy Schubert 	 * Unfold ntp time around current time into NTP domain, then
19492b15cb3dSCy Schubert 	 * convert the full time stamp.
19502b15cb3dSCy Schubert 	 */
19512b15cb3dSCy Schubert 	ntp64 = ntpcal_ntp_to_ntp(ntp, piv);
19522b15cb3dSCy Schubert 	return isocal_ntp64_to_date(id, &ntp64);
19532b15cb3dSCy Schubert }
19542b15cb3dSCy Schubert 
19552b15cb3dSCy Schubert /*
19562b15cb3dSCy Schubert  * Convert a ISO date spec into a second in the NTP time scale,
19572b15cb3dSCy Schubert  * properly truncated to 32 bit.
19582b15cb3dSCy Schubert  */
19592b15cb3dSCy Schubert vint64
isocal_date_to_ntp64(const struct isodate * id)19602b15cb3dSCy Schubert isocal_date_to_ntp64(
19612b15cb3dSCy Schubert 	const struct isodate *id
19622b15cb3dSCy Schubert 	)
19632b15cb3dSCy Schubert {
19642b15cb3dSCy Schubert 	int32_t weeks, days, secs;
19652b15cb3dSCy Schubert 
19662b15cb3dSCy Schubert 	weeks = isocal_weeks_in_years((int32_t)id->year - 1)
19672b15cb3dSCy Schubert 	      + (int32_t)id->week - 1;
19682b15cb3dSCy Schubert 	days = weeks * 7 + (int32_t)id->weekday;
19692b15cb3dSCy Schubert 	/* days is RDN of ISO date now */
19702b15cb3dSCy Schubert 	secs = ntpcal_etime_to_seconds(id->hour, id->minute, id->second);
19712b15cb3dSCy Schubert 
19722b15cb3dSCy Schubert 	return ntpcal_dayjoin(days - DAY_NTP_STARTS, secs);
19732b15cb3dSCy Schubert }
19742b15cb3dSCy Schubert 
19752b15cb3dSCy Schubert uint32_t
isocal_date_to_ntp(const struct isodate * id)19762b15cb3dSCy Schubert isocal_date_to_ntp(
19772b15cb3dSCy Schubert 	const struct isodate *id
19782b15cb3dSCy Schubert 	)
19792b15cb3dSCy Schubert {
19802b15cb3dSCy Schubert 	/*
1981*2d4e511cSCy Schubert 	 * Get lower half of 64bit NTP timestamp from date/time.
19822b15cb3dSCy Schubert 	 */
19832b15cb3dSCy Schubert 	return isocal_date_to_ntp64(id).d_s.lo;
19842b15cb3dSCy Schubert }
19852b15cb3dSCy Schubert 
198609100258SXin LI /*
198709100258SXin LI  * ====================================================================
198809100258SXin LI  * 'basedate' support functions
198909100258SXin LI  * ====================================================================
199009100258SXin LI  */
199109100258SXin LI 
199209100258SXin LI static int32_t s_baseday = NTP_TO_UNIX_DAYS;
1993052d159aSCy Schubert static int32_t s_gpsweek = 0;
199409100258SXin LI 
199509100258SXin LI int32_t
basedate_eval_buildstamp(void)199609100258SXin LI basedate_eval_buildstamp(void)
199709100258SXin LI {
199809100258SXin LI 	struct calendar jd;
199909100258SXin LI 	int32_t		ed;
200009100258SXin LI 
200109100258SXin LI 	if (!ntpcal_get_build_date(&jd))
200209100258SXin LI 		return NTP_TO_UNIX_DAYS;
200309100258SXin LI 
200409100258SXin LI 	/* The time zone of the build stamp is unspecified; we remove
200509100258SXin LI 	 * one day to provide a certain slack. And in case somebody
200609100258SXin LI 	 * fiddled with the system clock, we make sure we do not go
200709100258SXin LI 	 * before the UNIX epoch (1970-01-01). It's probably not possible
200809100258SXin LI 	 * to do this to the clock on most systems, but there are other
200909100258SXin LI 	 * ways to tweak the build stamp.
201009100258SXin LI 	 */
201109100258SXin LI 	jd.monthday -= 1;
201209100258SXin LI 	ed = ntpcal_date_to_rd(&jd) - DAY_NTP_STARTS;
201309100258SXin LI 	return (ed < NTP_TO_UNIX_DAYS) ? NTP_TO_UNIX_DAYS : ed;
201409100258SXin LI }
201509100258SXin LI 
201609100258SXin LI int32_t
basedate_eval_string(const char * str)201709100258SXin LI basedate_eval_string(
201809100258SXin LI 	const char * str
201909100258SXin LI 	)
202009100258SXin LI {
202109100258SXin LI 	u_short	y,m,d;
202209100258SXin LI 	u_long	ned;
202309100258SXin LI 	int	rc, nc;
202409100258SXin LI 	size_t	sl;
202509100258SXin LI 
202609100258SXin LI 	sl = strlen(str);
202709100258SXin LI 	rc = sscanf(str, "%4hu-%2hu-%2hu%n", &y, &m, &d, &nc);
202809100258SXin LI 	if (rc == 3 && (size_t)nc == sl) {
202909100258SXin LI 		if (m >= 1 && m <= 12 && d >= 1 && d <= 31)
203009100258SXin LI 			return ntpcal_edate_to_eradays(y-1, m-1, d)
203109100258SXin LI 			    - DAY_NTP_STARTS;
203209100258SXin LI 		goto buildstamp;
203309100258SXin LI 	}
203409100258SXin LI 
20354e1ef62aSXin LI 	rc = sscanf(str, "%lu%n", &ned, &nc);
203609100258SXin LI 	if (rc == 1 && (size_t)nc == sl) {
203709100258SXin LI 		if (ned <= INT32_MAX)
203809100258SXin LI 			return (int32_t)ned;
203909100258SXin LI 		goto buildstamp;
204009100258SXin LI 	}
204109100258SXin LI 
204209100258SXin LI   buildstamp:
204309100258SXin LI 	msyslog(LOG_WARNING,
204409100258SXin LI 		"basedate string \"%s\" invalid, build date substituted!",
204509100258SXin LI 		str);
204609100258SXin LI 	return basedate_eval_buildstamp();
204709100258SXin LI }
204809100258SXin LI 
204909100258SXin LI uint32_t
basedate_get_day(void)205009100258SXin LI basedate_get_day(void)
205109100258SXin LI {
205209100258SXin LI 	return s_baseday;
205309100258SXin LI }
205409100258SXin LI 
205509100258SXin LI int32_t
basedate_set_day(int32_t day)205609100258SXin LI basedate_set_day(
205709100258SXin LI 	int32_t day
205809100258SXin LI 	)
205909100258SXin LI {
206009100258SXin LI 	struct calendar	jd;
206109100258SXin LI 	int32_t		retv;
206209100258SXin LI 
2063052d159aSCy Schubert 	/* set NTP base date for NTP era unfolding */
206409100258SXin LI 	if (day < NTP_TO_UNIX_DAYS) {
206509100258SXin LI 		msyslog(LOG_WARNING,
206609100258SXin LI 			"baseday_set_day: invalid day (%lu), UNIX epoch substituted",
206709100258SXin LI 			(unsigned long)day);
206809100258SXin LI 		day = NTP_TO_UNIX_DAYS;
206909100258SXin LI 	}
207009100258SXin LI 	retv = s_baseday;
207109100258SXin LI 	s_baseday = day;
207209100258SXin LI 	ntpcal_rd_to_date(&jd, day + DAY_NTP_STARTS);
207309100258SXin LI 	msyslog(LOG_INFO, "basedate set to %04hu-%02hu-%02hu",
207409100258SXin LI 		jd.year, (u_short)jd.month, (u_short)jd.monthday);
2075052d159aSCy Schubert 
2076052d159aSCy Schubert 	/* set GPS base week for GPS week unfolding */
2077052d159aSCy Schubert 	day = ntpcal_weekday_ge(day + DAY_NTP_STARTS, CAL_SUNDAY)
2078052d159aSCy Schubert 	    - DAY_NTP_STARTS;
2079052d159aSCy Schubert 	if (day < NTP_TO_GPS_DAYS)
2080052d159aSCy Schubert 	    day = NTP_TO_GPS_DAYS;
2081052d159aSCy Schubert 	s_gpsweek = (day - NTP_TO_GPS_DAYS) / DAYSPERWEEK;
2082052d159aSCy Schubert 	ntpcal_rd_to_date(&jd, day + DAY_NTP_STARTS);
2083052d159aSCy Schubert 	msyslog(LOG_INFO, "gps base set to %04hu-%02hu-%02hu (week %d)",
2084052d159aSCy Schubert 		jd.year, (u_short)jd.month, (u_short)jd.monthday, s_gpsweek);
2085052d159aSCy Schubert 
208609100258SXin LI 	return retv;
208709100258SXin LI }
208809100258SXin LI 
208909100258SXin LI time_t
basedate_get_eracenter(void)209009100258SXin LI basedate_get_eracenter(void)
209109100258SXin LI {
209209100258SXin LI 	time_t retv;
209309100258SXin LI 	retv  = (time_t)(s_baseday - NTP_TO_UNIX_DAYS);
209409100258SXin LI 	retv *= SECSPERDAY;
209509100258SXin LI 	retv += (UINT32_C(1) << 31);
209609100258SXin LI 	return retv;
209709100258SXin LI }
209809100258SXin LI 
209909100258SXin LI time_t
basedate_get_erabase(void)210009100258SXin LI basedate_get_erabase(void)
210109100258SXin LI {
210209100258SXin LI 	time_t retv;
210309100258SXin LI 	retv  = (time_t)(s_baseday - NTP_TO_UNIX_DAYS);
210409100258SXin LI 	retv *= SECSPERDAY;
210509100258SXin LI 	return retv;
210609100258SXin LI }
210709100258SXin LI 
2108052d159aSCy Schubert uint32_t
basedate_get_gpsweek(void)2109052d159aSCy Schubert basedate_get_gpsweek(void)
2110052d159aSCy Schubert {
2111052d159aSCy Schubert     return s_gpsweek;
2112052d159aSCy Schubert }
2113052d159aSCy Schubert 
2114052d159aSCy Schubert uint32_t
basedate_expand_gpsweek(unsigned short weekno)2115052d159aSCy Schubert basedate_expand_gpsweek(
2116052d159aSCy Schubert     unsigned short weekno
2117052d159aSCy Schubert     )
2118052d159aSCy Schubert {
2119052d159aSCy Schubert     /* We do a fast modulus expansion here. Since all quantities are
2120052d159aSCy Schubert      * unsigned and we cannot go before the start of the GPS epoch
2121052d159aSCy Schubert      * anyway, and since the truncated GPS week number is 10 bit, the
2122052d159aSCy Schubert      * expansion becomes a simple sub/and/add sequence.
2123052d159aSCy Schubert      */
2124052d159aSCy Schubert     #if GPSWEEKS != 1024
2125052d159aSCy Schubert     # error GPSWEEKS defined wrong -- should be 1024!
2126052d159aSCy Schubert     #endif
2127052d159aSCy Schubert 
2128052d159aSCy Schubert     uint32_t diff;
2129052d159aSCy Schubert     diff = ((uint32_t)weekno - s_gpsweek) & (GPSWEEKS - 1);
2130052d159aSCy Schubert     return s_gpsweek + diff;
2131052d159aSCy Schubert }
2132052d159aSCy Schubert 
2133*2d4e511cSCy Schubert /*
2134*2d4e511cSCy Schubert  * ====================================================================
2135*2d4e511cSCy Schubert  * misc. helpers
2136*2d4e511cSCy Schubert  * ====================================================================
2137*2d4e511cSCy Schubert  */
2138*2d4e511cSCy Schubert 
2139*2d4e511cSCy Schubert /* --------------------------------------------------------------------
2140*2d4e511cSCy Schubert  * reconstruct the centrury from a truncated date and a day-of-week
2141*2d4e511cSCy Schubert  *
2142*2d4e511cSCy Schubert  * Given a date with truncated year (2-digit, 0..99) and a day-of-week
2143*2d4e511cSCy Schubert  * from 1(Mon) to 7(Sun), recover the full year between 1900AD and 2300AD.
2144*2d4e511cSCy Schubert  */
2145*2d4e511cSCy Schubert int32_t
ntpcal_expand_century(uint32_t y,uint32_t m,uint32_t d,uint32_t wd)2146*2d4e511cSCy Schubert ntpcal_expand_century(
2147*2d4e511cSCy Schubert 	uint32_t y,
2148*2d4e511cSCy Schubert 	uint32_t m,
2149*2d4e511cSCy Schubert 	uint32_t d,
2150*2d4e511cSCy Schubert 	uint32_t wd)
2151*2d4e511cSCy Schubert {
2152*2d4e511cSCy Schubert 	/* This algorithm is short but tricky... It's related to
2153*2d4e511cSCy Schubert 	 * Zeller's congruence, partially done backwards.
2154*2d4e511cSCy Schubert 	 *
2155*2d4e511cSCy Schubert 	 * A few facts to remember:
2156*2d4e511cSCy Schubert 	 *  1) The Gregorian calendar has a cycle of 400 years.
2157*2d4e511cSCy Schubert 	 *  2) The weekday of the 1st day of a century shifts by 5 days
2158*2d4e511cSCy Schubert 	 *     during a great cycle.
2159*2d4e511cSCy Schubert 	 *  3) For calendar math, a century starts with the 1st year,
2160*2d4e511cSCy Schubert 	 *     which is year 1, !not! zero.
2161*2d4e511cSCy Schubert 	 *
2162*2d4e511cSCy Schubert 	 * So we start with taking the weekday difference (mod 7)
2163*2d4e511cSCy Schubert 	 * between the truncated date (which is taken as an absolute
2164*2d4e511cSCy Schubert 	 * date in the 1st century in the proleptic calendar) and the
2165*2d4e511cSCy Schubert 	 * weekday given.
2166*2d4e511cSCy Schubert 	 *
2167*2d4e511cSCy Schubert 	 * When dividing this residual by 5, we obtain the number of
2168*2d4e511cSCy Schubert 	 * centuries to add to the base. But since the residual is (mod
2169*2d4e511cSCy Schubert 	 * 7), we have to make this an exact division by multiplication
2170*2d4e511cSCy Schubert 	 * with the modular inverse of 5 (mod 7), which is 3:
2171*2d4e511cSCy Schubert 	 *    3*5 === 1 (mod 7).
2172*2d4e511cSCy Schubert 	 *
2173*2d4e511cSCy Schubert 	 * If this yields a result of 4/5/6, the given date/day-of-week
2174*2d4e511cSCy Schubert 	 * combination is impossible, and we return zero as resulting
2175*2d4e511cSCy Schubert 	 * year to indicate failure.
2176*2d4e511cSCy Schubert 	 *
2177*2d4e511cSCy Schubert 	 * Then we remap the century to the range starting with year
2178*2d4e511cSCy Schubert 	 * 1900.
2179*2d4e511cSCy Schubert 	 */
2180*2d4e511cSCy Schubert 
2181*2d4e511cSCy Schubert 	uint32_t c;
2182*2d4e511cSCy Schubert 
2183*2d4e511cSCy Schubert 	/* check basic constraints */
2184*2d4e511cSCy Schubert 	if ((y >= 100u) || (--m >= 12u) || (--d >= 31u))
2185*2d4e511cSCy Schubert 		return 0;
2186*2d4e511cSCy Schubert 
2187*2d4e511cSCy Schubert 	if ((m += 10u) >= 12u)		/* shift base to prev. March,1st */
2188*2d4e511cSCy Schubert 		m -= 12u;
2189*2d4e511cSCy Schubert 	else if (--y >= 100u)
2190*2d4e511cSCy Schubert 		y += 100u;
2191*2d4e511cSCy Schubert 	d += y + (y >> 2) + 2u;		/* year share */
2192*2d4e511cSCy Schubert 	d += (m * 83u + 16u) >> 5;	/* month share */
2193*2d4e511cSCy Schubert 
2194*2d4e511cSCy Schubert 	/* get (wd - d), shifted to positive value, and multiply with
2195*2d4e511cSCy Schubert 	 * 3(mod 7). (Exact division, see to comment)
2196*2d4e511cSCy Schubert 	 * Note: 1) d <= 184 at this point.
2197*2d4e511cSCy Schubert 	 *	 2) 252 % 7 == 0, but 'wd' is off by one since we did
2198*2d4e511cSCy Schubert 	 *	    '--d' above, so we add just 251 here!
2199*2d4e511cSCy Schubert 	 */
2200*2d4e511cSCy Schubert 	c = u32mod7(3 * (251u + wd - d));
2201*2d4e511cSCy Schubert 	if (c > 3u)
2202*2d4e511cSCy Schubert 		return 0;
2203*2d4e511cSCy Schubert 
2204*2d4e511cSCy Schubert 	if ((m > 9u) && (++y >= 100u)) {/* undo base shift */
2205*2d4e511cSCy Schubert 		y -= 100u;
2206*2d4e511cSCy Schubert 		c = (c + 1) & 3u;
2207*2d4e511cSCy Schubert 	}
2208*2d4e511cSCy Schubert 	y += (c * 100u);		/* combine into 1st cycle */
2209*2d4e511cSCy Schubert 	y += (y < 300u) ? 2000 : 1600;	/* map to destination era */
2210*2d4e511cSCy Schubert 	return (int)y;
2211*2d4e511cSCy Schubert }
2212*2d4e511cSCy Schubert 
2213*2d4e511cSCy Schubert char *
ntpcal_iso8601std(char * buf,size_t len,TcCivilDate * cdp)2214*2d4e511cSCy Schubert ntpcal_iso8601std(
2215*2d4e511cSCy Schubert 	char *		buf,
2216*2d4e511cSCy Schubert 	size_t		len,
2217*2d4e511cSCy Schubert 	TcCivilDate *	cdp
2218*2d4e511cSCy Schubert 	)
2219*2d4e511cSCy Schubert {
2220*2d4e511cSCy Schubert 	if (!buf) {
2221*2d4e511cSCy Schubert 		LIB_GETBUF(buf);
2222*2d4e511cSCy Schubert 		len = LIB_BUFLENGTH;
2223*2d4e511cSCy Schubert 	}
2224*2d4e511cSCy Schubert 	if (len) {
2225*2d4e511cSCy Schubert 		len = snprintf(buf, len, "%04u-%02u-%02uT%02u:%02u:%02u",
2226*2d4e511cSCy Schubert 			       cdp->year, cdp->month, cdp->monthday,
2227*2d4e511cSCy Schubert 			       cdp->hour, cdp->minute, cdp->second);
2228*2d4e511cSCy Schubert 		if (len < 0)
2229*2d4e511cSCy Schubert 			*buf = '\0';
2230*2d4e511cSCy Schubert 	}
2231*2d4e511cSCy Schubert 	return buf;
2232*2d4e511cSCy Schubert }
2233*2d4e511cSCy Schubert 
22342b15cb3dSCy Schubert /* -*-EOF-*- */
2235