2 * ntp_calendar.c - calendar and helper functions
4 * Written by Juergen Perlinger (perlinger@ntp.org) for the NTP project.
5 * The contents of 'html/copyright.html' apply.
7 * --------------------------------------------------------------------
8 * Some notes on the implementation:
10 * Calendar algorithms thrive on the division operation, which is one of
11 * the slowest numerical operations in any CPU. What saves us here from
12 * abysmal performance is the fact that all divisions are divisions by
13 * constant numbers, and most compilers can do this by a multiplication
14 * operation. But this might not work when using the div/ldiv/lldiv
15 * function family, because many compilers are not able to do inline
16 * expansion of the code with following optimisation for the
17 * constant-divider case.
19 * Also div/ldiv/lldiv are defined in terms of int/long/longlong, which
20 * are inherently target dependent. Nothing that could not be cured with
21 * autoconf, but still a mess...
23 * Furthermore, we need floor division in many places. C either leaves
24 * the division behaviour undefined (< C99) or demands truncation to
25 * zero (>= C99), so additional steps are required to make sure the
26 * algorithms work. The {l,ll}div function family is requested to
27 * truncate towards zero, which is also the wrong direction for our
30 * For all this, all divisions by constant are coded manually, even when
31 * there is a joined div/mod operation: The optimiser should sort that
32 * out, if possible. Most of the calculations are done with unsigned
33 * types, explicitely using two's complement arithmetics where
34 * necessary. This minimises the dependecies to compiler and target,
35 * while still giving reasonable to good performance.
37 * The implementation uses a few tricks that exploit properties of the
38 * two's complement: Floor division on negative dividents can be
39 * executed by using the one's complement of the divident. One's
40 * complement can be easily created using XOR and a mask.
42 * Finally, check for overflow conditions is minimal. There are only two
43 * calculation steps in the whole calendar that potentially suffer from
44 * an internal overflow, and these are coded in a way that avoids
45 * it. All other functions do not suffer from internal overflow and
46 * simply return the result truncated to 32 bits.
50 #include <sys/types.h>
52 #include "ntp_types.h"
53 #include "ntp_calendar.h"
54 #include "ntp_stdlib.h"
56 #include "ntp_unixtime.h"
59 #include "lib_strbuf.h"
61 /* For now, let's take the conservative approach: if the target property
62 * macros are not defined, check a few well-known compiler/architecture
63 * settings. Default is to assume that the representation of signed
64 * integers is unknown and shift-arithmetic-right is not available.
66 #ifndef TARGET_HAS_2CPL
67 # if defined(__GNUC__)
68 # if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
69 # define TARGET_HAS_2CPL 1
71 # define TARGET_HAS_2CPL 0
73 # elif defined(_MSC_VER)
74 # if defined(_M_IX86) || defined(_M_X64) || defined(_M_ARM)
75 # define TARGET_HAS_2CPL 1
77 # define TARGET_HAS_2CPL 0
80 # define TARGET_HAS_2CPL 0
84 #ifndef TARGET_HAS_SAR
85 # define TARGET_HAS_SAR 0
88 #if !defined(HAVE_64BITREGS) && defined(UINT64_MAX) && (SIZE_MAX >= UINT64_MAX)
89 # define HAVE_64BITREGS
93 *---------------------------------------------------------------------
94 * replacing the 'time()' function
95 *---------------------------------------------------------------------
98 static systime_func_ptr systime_func = &time;
99 static inline time_t now(void);
104 systime_func_ptr nfunc
107 systime_func_ptr res;
112 systime_func = nfunc;
121 return (*systime_func)(NULL);
125 *---------------------------------------------------------------------
126 * Get sign extension mask and unsigned 2cpl rep for a signed integer
127 *---------------------------------------------------------------------
130 static inline uint32_t
134 # if TARGET_HAS_2CPL && TARGET_HAS_SAR && SIZEOF_INT >= 4
136 /* Let's assume that shift is the fastest way to get the sign
137 * extension of of a signed integer. This might not always be
138 * true, though -- On 8bit CPUs or machines without barrel
139 * shifter this will kill the performance. So we make sure
140 * we do this only if 'int' has at least 4 bytes.
142 return (uint32_t)(v >> 31);
146 /* This should be a rather generic approach for getting a sign
149 return UINT32_C(0) - (uint32_t)(v < 0);
154 static inline int32_t
155 uint32_2cpl_to_int32(
162 /* Just copy through the 32 bits from the unsigned value if
163 * we're on a two's complement target.
169 /* Convert to signed integer, making sure signed integer
170 * overflow cannot happen. Again, the optimiser might or might
171 * not find out that this is just a copy of 32 bits on a target
172 * with two's complement representation for signed integers.
175 v = -(int32_t)(~vu) - 1;
185 *---------------------------------------------------------------------
186 * Convert between 'time_t' and 'vint64'
187 *---------------------------------------------------------------------
199 # if SIZEOF_TIME_T <= 4
203 res.D_s.lo = (uint32_t)-tt;
204 M_NEG(res.D_s.hi, res.D_s.lo);
206 res.D_s.lo = (uint32_t)tt;
209 # elif defined(HAVE_INT64)
215 * shifting negative signed quantities is compiler-dependent, so
216 * we better avoid it and do it all manually. And shifting more
217 * than the width of a quantity is undefined. Also a don't do!
221 res.D_s.lo = (uint32_t)tt;
222 res.D_s.hi = (uint32_t)(tt >> 32);
223 M_NEG(res.D_s.hi, res.D_s.lo);
225 res.D_s.lo = (uint32_t)tt;
226 res.D_s.hi = (uint32_t)(tt >> 32);
242 # if SIZEOF_TIME_T <= 4
244 res = (time_t)tv->D_s.lo;
246 # elif defined(HAVE_INT64)
248 res = (time_t)tv->q_s;
252 res = ((time_t)tv->d_s.hi << 32) | tv->D_s.lo;
260 *---------------------------------------------------------------------
261 * Get the build date & time
262 *---------------------------------------------------------------------
265 ntpcal_get_build_date(
269 /* The C standard tells us the format of '__DATE__':
271 * __DATE__ The date of translation of the preprocessing
272 * translation unit: a character string literal of the form "Mmm
273 * dd yyyy", where the names of the months are the same as those
274 * generated by the asctime function, and the first character of
275 * dd is a space character if the value is less than 10. If the
276 * date of translation is not available, an
277 * implementation-defined valid date shall be supplied.
279 * __TIME__ The time of translation of the preprocessing
280 * translation unit: a character string literal of the form
281 * "hh:mm:ss" as in the time generated by the asctime
282 * function. If the time of translation is not available, an
283 * implementation-defined valid time shall be supplied.
285 * Note that MSVC declares DATE and TIME to be in the local time
286 * zone, while neither the C standard nor the GCC docs make any
287 * statement about this. As a result, we may be +/-12hrs off
288 * UTC. But for practical purposes, this should not be a
293 static const char build[] = MKREPRO_TIME "/" MKREPRO_DATE;
295 static const char build[] = __TIME__ "/" __DATE__;
297 static const char mlist[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
301 unsigned short hour, minute, second, day, year;
302 /* Note: The above quantities are used for sscanf 'hu' format,
303 * so using 'uint16_t' is contra-indicated!
307 static int ignore = 0;
316 /* check environment if build date should be ignored */
319 envstr = getenv("NTPD_IGNORE_BUILD_DATE");
320 ignore = 1 + (envstr && (!*envstr || !strcasecmp(envstr, "yes")));
326 if (6 == sscanf(build, "%hu:%hu:%hu/%3s %hu %hu",
327 &hour, &minute, &second, monstr, &day, &year)) {
328 cp = strstr(mlist, monstr);
331 jd->month = (uint8_t)((cp - mlist) / 3 + 1);
332 jd->monthday = (uint8_t)day;
333 jd->hour = (uint8_t)hour;
334 jd->minute = (uint8_t)minute;
335 jd->second = (uint8_t)second;
346 *---------------------------------------------------------------------
347 * basic calendar stuff
348 *---------------------------------------------------------------------
352 * Some notes on the terminology:
354 * We use the proleptic Gregorian calendar, which is the Gregorian
355 * calendar extended in both directions ad infinitum. This totally
356 * disregards the fact that this calendar was invented in 1582, and
357 * was adopted at various dates over the world; sometimes even after
358 * the start of the NTP epoch.
360 * Normally date parts are given as current cycles, while time parts
361 * are given as elapsed cycles:
363 * 1970-01-01/03:04:05 means 'IN the 1970st. year, IN the first month,
364 * ON the first day, with 3hrs, 4minutes and 5 seconds elapsed.
366 * The basic calculations for this calendar implementation deal with
367 * ELAPSED date units, which is the number of full years, full months
368 * and full days before a date: 1970-01-01 would be (1969, 0, 0) in
371 * To ease the numeric computations, month and day values outside the
372 * normal range are acceptable: 2001-03-00 will be treated as the day
373 * before 2001-03-01, 2000-13-32 will give the same result as
374 * 2001-02-01 and so on.
376 * 'rd' or 'RD' is used as an abbreviation for the latin 'rata die'
377 * (day number). This is the number of days elapsed since 0000-12-31
378 * in the proleptic Gregorian calendar. The begin of the Christian Era
379 * (0001-01-01) is RD(1).
383 * ====================================================================
385 * General algorithmic stuff
387 * ====================================================================
391 *---------------------------------------------------------------------
392 * fast modulo 7 operations (floor/mathematical convention)
393 *---------------------------------------------------------------------
400 /* This is a combination of tricks from "Hacker's Delight" with
401 * some modifications, like a multiplication that rounds up to
402 * drop the final adjustment stage.
404 * Do a partial reduction by digit sum to keep the value in the
405 * range permitted for the mul/shift stage. There are several
406 * possible and absolutely equivalent shift/mask combinations;
407 * this one is ARM-friendly because of a mask that fits into 16
410 x = (x >> 15) + (x & UINT32_C(0x7FFF));
411 /* Take reminder as (mod 8) by mul/shift. Since the multiplier
412 * was calculated using ceil() instead of floor(), it skips the
413 * value '7' properly.
414 * M <- ceil(ldexp(8/7, 29))
416 return (int)((x * UINT32_C(0x24924925)) >> 29);
424 /* We add (2**32 - 2**32 % 7), which is (2**32 - 4), to negative
425 * numbers to map them into the postive range. Only the term '-4'
426 * survives, obviously.
428 uint32_t ux = (uint32_t)x;
429 return u32mod7((x < 0) ? (ux - 4u) : ux);
438 uint32_t ux = (uint32_t)x;
439 uint32_t sf = UINT32_C(0) - (x < 0);
441 return (d & sf) + (sf ^ ux);
445 *---------------------------------------------------------------------
446 * Do a periodic extension of 'value' around 'pivot' with a period of
449 * The result 'res' is a number that holds to the following properties:
451 * 1) res MOD cycle == value MOD cycle
452 * 2) pivot <= res < pivot + cycle
453 * (replace </<= with >/>= for negative cycles)
455 * where 'MOD' denotes the modulo operator for FLOOR DIVISION, which
456 * is not the same as the '%' operator in C: C requires division to be
457 * a truncated division, where remainder and dividend have the same
458 * sign if the remainder is not zero, whereas floor division requires
459 * divider and modulus to have the same sign for a non-zero modulus.
461 * This function has some useful applications:
463 * + let Y be a calendar year and V a truncated 2-digit year: then
464 * periodic_extend(Y-50, V, 100)
465 * is the closest expansion of the truncated year with respect to
466 * the full year, that is a 4-digit year with a difference of less
467 * than 50 years to the year Y. ("century unfolding")
469 * + let T be a UN*X time stamp and V be seconds-of-day: then
470 * perodic_extend(T-43200, V, 86400)
471 * is a time stamp that has the same seconds-of-day as the input
472 * value, with an absolute difference to T of <= 12hrs. ("day
475 * + Wherever you have a truncated periodic value and a non-truncated
476 * base value and you want to match them somehow...
478 * Basically, the function delivers 'pivot + (value - pivot) % cycle',
479 * but the implementation takes some pains to avoid internal signed
480 * integer overflows in the '(value - pivot) % cycle' part and adheres
481 * to the floor division convention.
483 * If 64bit scalars where available on all intended platforms, writing a
484 * version that uses 64 bit ops would be easy; writing a general
485 * division routine for 64bit ops on a platform that can only do
486 * 32/16bit divisions and is still performant is a bit more
487 * difficult. Since most usecases can be coded in a way that does only
488 * require the 32bit version a 64bit version is NOT provided here.
489 *---------------------------------------------------------------------
492 ntpcal_periodic_extend(
498 /* Implement a 4-quadrant modulus calculation by 2 2-quadrant
499 * branches, one for positive and one for negative dividers.
500 * Everything else can be handled by bit level logic and
501 * conditional one's complement arithmetic. By convention, we
504 * x % b == 0 if |b| < 2
506 * that is, we don't actually divide for cycles of -1,0,1 and
507 * return the pivot value in that case.
509 uint32_t uv = (uint32_t)value;
510 uint32_t up = (uint32_t)pivot;
515 uc = (uint32_t)cycle;
516 sf = UINT32_C(0) - (value < pivot);
520 pivot += (uc & sf) + (sf ^ uv);
524 uc = ~(uint32_t)cycle + 1;
525 sf = UINT32_C(0) - (value > pivot);
529 pivot -= (uc & sf) + (sf ^ uv);
534 /*---------------------------------------------------------------------
535 * Note to the casual reader
537 * In the next two functions you will find (or would have found...)
540 * res.Q_s -= 0x80000000;
542 * There was some ruckus about a possible programming error due to
543 * integer overflow and sign propagation.
545 * This assumption is based on a lack of understanding of the C
546 * standard. (Though this is admittedly not one of the most 'natural'
547 * aspects of the 'C' language and easily to get wrong.)
550 * http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
551 * "ISO/IEC 9899:201x Committee Draft — April 12, 2011"
552 * 6.4.4.1 Integer constants, clause 5
554 * why there is no sign extension/overflow problem here.
556 * But to ease the minds of the doubtful, I added back the 'u' qualifiers
557 * that somehow got lost over the last years.
562 *---------------------------------------------------------------------
563 * Convert a timestamp in NTP scale to a 64bit seconds value in the UN*X
564 * scale with proper epoch unfolding around a given pivot or the current
565 * system time. This function happily accepts negative pivot values as
566 * timestamps before 1970-01-01, so be aware of possible trouble on
567 * platforms with 32bit 'time_t'!
569 * This is also a periodic extension, but since the cycle is 2^32 and
570 * the shift is 2^31, we can do some *very* fast math without explicit
572 *---------------------------------------------------------------------
582 # if defined(HAVE_INT64)
584 res.q_s = (pivot != NULL)
587 res.Q_s -= 0x80000000u; /* unshift of half range */
588 ntp -= (uint32_t)JAN_1970; /* warp into UN*X domain */
589 ntp -= res.D_s.lo; /* cycle difference */
590 res.Q_s += (uint64_t)ntp; /* get expanded time */
592 # else /* no 64bit scalars */
596 tmp = (pivot != NULL)
599 res = time_to_vint64(&tmp);
600 M_SUB(res.D_s.hi, res.D_s.lo, 0, 0x80000000u);
601 ntp -= (uint32_t)JAN_1970; /* warp into UN*X domain */
602 ntp -= res.D_s.lo; /* cycle difference */
603 M_ADD(res.D_s.hi, res.D_s.lo, 0, ntp);
605 # endif /* no 64bit scalars */
611 *---------------------------------------------------------------------
612 * Convert a timestamp in NTP scale to a 64bit seconds value in the NTP
613 * scale with proper epoch unfolding around a given pivot or the current
616 * Note: The pivot must be given in the UN*X time domain!
618 * This is also a periodic extension, but since the cycle is 2^32 and
619 * the shift is 2^31, we can do some *very* fast math without explicit
621 *---------------------------------------------------------------------
631 # if defined(HAVE_INT64)
636 res.Q_s -= 0x80000000u; /* unshift of half range */
637 res.Q_s += (uint32_t)JAN_1970; /* warp into NTP domain */
638 ntp -= res.D_s.lo; /* cycle difference */
639 res.Q_s += (uint64_t)ntp; /* get expanded time */
641 # else /* no 64bit scalars */
648 res = time_to_vint64(&tmp);
649 M_SUB(res.D_s.hi, res.D_s.lo, 0, 0x80000000u);
650 M_ADD(res.D_s.hi, res.D_s.lo, 0, (uint32_t)JAN_1970);/*into NTP */
651 ntp -= res.D_s.lo; /* cycle difference */
652 M_ADD(res.D_s.hi, res.D_s.lo, 0, ntp);
654 # endif /* no 64bit scalars */
661 * ====================================================================
663 * Splitting values to composite entities
665 * ====================================================================
669 *---------------------------------------------------------------------
670 * Split a 64bit seconds value into elapsed days in 'res.hi' and
671 * elapsed seconds since midnight in 'res.lo' using explicit floor
672 * division. This function happily accepts negative time values as
673 * timestamps before the respective epoch start.
674 *---------------------------------------------------------------------
684 # if defined(HAVE_64BITREGS)
686 /* Assume we have 64bit registers an can do a divison by
687 * constant reasonably fast using the one's complement trick..
689 uint64_t sf64 = (uint64_t)-(ts->q_s < 0);
690 Q = (uint32_t)(sf64 ^ ((sf64 ^ ts->Q_s) / SECSPERDAY));
691 R = (uint32_t)(ts->Q_s - Q * SECSPERDAY);
693 # elif defined(UINT64_MAX) && !defined(__arm__)
695 /* We rely on the compiler to do efficient 64bit divisions as
696 * good as possible. Which might or might not be true. At least
697 * for ARM CPUs, the sum-by-digit code in the next section is
698 * faster for many compilers. (This might change over time, but
699 * the 64bit-by-32bit division will never outperform the exact
700 * division by a substantial factor....)
703 Q = ~(uint32_t)(~ts->Q_s / SECSPERDAY);
705 Q = (uint32_t)( ts->Q_s / SECSPERDAY);
706 R = ts->D_s.lo - Q * SECSPERDAY;
710 /* We don't have 64bit regs. That hurts a bit.
712 * Here we use a mean trick to get away with just one explicit
713 * modulo operation and pure 32bit ops.
715 * Remember: 86400 <--> 128 * 675
717 * So we discard the lowest 7 bit and do an exact division by
720 * First we shift out the lower 7 bits.
722 * Then we use a digit-wise pseudo-reduction, where a 'digit' is
723 * actually a 16-bit group. This is followed by a full reduction
724 * with a 'true' division step. This yields the modulus of the
725 * full 64bit value. The sign bit gets some extra treatment.
727 * Then we decrement the lower limb by that modulus, so it is
728 * exactly divisible by 675. [*]
730 * Then we multiply with the modular inverse of 675 (mod 2**32)
731 * and voila, we have the result.
733 * Special Thanks to Henry S. Warren and his "Hacker's delight"
734 * for giving that idea.
736 * (Note[*]: that's not the full truth. We would have to
737 * subtract the modulus from the full 64 bit number to get a
738 * number that is divisible by 675. But since we use the
739 * multiplicative inverse (mod 2**32) there's no reason to carry
740 * the subtraction into the upper bits!)
742 uint32_t al = ts->D_s.lo;
743 uint32_t ah = ts->D_s.hi;
745 /* shift out the lower 7 bits, smash sign bit */
746 al = (al >> 7) | (ah << 25);
747 ah = (ah >> 7) & 0x00FFFFFFu;
749 R = (ts->d_s.hi < 0) ? 239 : 0;/* sign bit value */
751 R += (al >> 16 ) * 61u; /* 2**16 % 675 */
752 R += (ah & 0xFFFF) * 346u; /* 2**32 % 675 */
753 R += (ah >> 16 ) * 181u; /* 2**48 % 675 */
754 R %= 675u; /* final reduction */
755 Q = (al - R) * 0x2D21C10Bu; /* modinv(675, 2**32) */
756 R = (R << 7) | (ts->d_s.lo & 0x07F);
760 res.hi = uint32_2cpl_to_int32(Q);
767 *---------------------------------------------------------------------
768 * Split a 64bit seconds value into elapsed weeks in 'res.hi' and
769 * elapsed seconds since week start in 'res.lo' using explicit floor
770 * division. This function happily accepts negative time values as
771 * timestamps before the respective epoch start.
772 *---------------------------------------------------------------------
782 /* This is a very close relative to the day split function; for
783 * details, see there!
786 # if defined(HAVE_64BITREGS)
788 uint64_t sf64 = (uint64_t)-(ts->q_s < 0);
789 Q = (uint32_t)(sf64 ^ ((sf64 ^ ts->Q_s) / SECSPERWEEK));
790 R = (uint32_t)(ts->Q_s - Q * SECSPERWEEK);
792 # elif defined(UINT64_MAX) && !defined(__arm__)
795 Q = ~(uint32_t)(~ts->Q_s / SECSPERWEEK);
797 Q = (uint32_t)( ts->Q_s / SECSPERWEEK);
798 R = ts->D_s.lo - Q * SECSPERWEEK;
802 /* Remember: 7*86400 <--> 604800 <--> 128 * 4725 */
803 uint32_t al = ts->D_s.lo;
804 uint32_t ah = ts->D_s.hi;
806 al = (al >> 7) | (ah << 25);
807 ah = (ah >> 7) & 0x00FFFFFF;
809 R = (ts->d_s.hi < 0) ? 2264 : 0;/* sign bit value */
811 R += (al >> 16 ) * 4111u; /* 2**16 % 4725 */
812 R += (ah & 0xFFFF) * 3721u; /* 2**32 % 4725 */
813 R += (ah >> 16 ) * 2206u; /* 2**48 % 4725 */
814 R %= 4725u; /* final reduction */
815 Q = (al - R) * 0x98BBADDDu; /* modinv(4725, 2**32) */
816 R = (R << 7) | (ts->d_s.lo & 0x07F);
820 res.hi = uint32_2cpl_to_int32(Q);
827 *---------------------------------------------------------------------
828 * Split a 32bit seconds value into h/m/s and excessive days. This
829 * function happily accepts negative time values as timestamps before
831 *---------------------------------------------------------------------
839 /* Do 3 chained floor divisions by positive constants, using the
840 * one's complement trick and factoring out the intermediate XOR
841 * ops to reduce the number of operations.
843 uint32_t us, um, uh, ud, sf32;
845 sf32 = int32_sflag(ts);
848 um = (sf32 ^ us) / SECSPERMIN;
856 split[0] = (int32_t)(uh - ud * HRSPERDAY );
857 split[1] = (int32_t)(um - uh * MINSPERHR );
858 split[2] = (int32_t)(us - um * SECSPERMIN);
860 return uint32_2cpl_to_int32(ud);
864 *---------------------------------------------------------------------
865 * Given the number of elapsed days in the calendar era, split this
866 * number into the number of elapsed years in 'res.hi' and the number
867 * of elapsed days of that year in 'res.lo'.
869 * if 'isleapyear' is not NULL, it will receive an integer that is 0 for
870 * regular years and a non-zero value for leap years.
871 *---------------------------------------------------------------------
874 ntpcal_split_eradays(
879 /* Use the fast cycle split algorithm here, to calculate the
880 * centuries and years in a century with one division each. This
881 * reduces the number of division operations to two, but is
882 * susceptible to internal range overflow. We take some extra
883 * steps to avoid the gap.
886 int32_t n100, n001; /* calendar year cycles */
889 /* split off centuries first
891 * We want to execute '(days * 4 + 3) /% 146097' under floor
892 * division rules in the first step. Well, actually we want to
893 * calculate 'floor((days + 0.75) / 36524.25)', but we want to
894 * do it in scaled integer calculation.
896 # if defined(HAVE_64BITREGS)
898 /* not too complicated with an intermediate 64bit value */
900 ud64 = ((uint64_t)days << 2) | 3u;
901 sf64 = (uint64_t)-(days < 0);
902 Q = (uint32_t)(sf64 ^ ((sf64 ^ ud64) / GREGORIAN_CYCLE_DAYS));
903 uday = (uint32_t)(ud64 - Q * GREGORIAN_CYCLE_DAYS);
904 n100 = uint32_2cpl_to_int32(Q);
908 /* '4*days+3' suffers from range overflow when going to the
909 * limits. We solve this by doing an exact division (mod 2^32)
910 * after caclulating the remainder first.
912 * We start with a partial reduction by digit sums, extracting
913 * the upper bits from the original value before they get lost
914 * by scaling, and do one full division step to get the true
915 * remainder. Then a final multiplication with the
916 * multiplicative inverse of 146097 (mod 2^32) gives us the full
919 * (-2^33) % 146097 --> 130717 : the sign bit value
920 * ( 2^20) % 146097 --> 25897 : the upper digit value
921 * modinv(146097, 2^32) --> 660721233 : the inverse
923 uint32_t ux = ((uint32_t)days << 2) | 3;
924 uday = (days < 0) ? 130717u : 0u; /* sign dgt */
925 uday += ((days >> 18) & 0x01FFFu) * 25897u; /* hi dgt (src!) */
926 uday += (ux & 0xFFFFFu); /* lo dgt */
927 uday %= GREGORIAN_CYCLE_DAYS; /* full reduction */
928 Q = (ux - uday) * 660721233u; /* exact div */
929 n100 = uint32_2cpl_to_int32(Q);
933 /* Split off years in century -- days >= 0 here, and we're far
934 * away from integer overflow trouble now. */
936 n001 = uday / GREGORIAN_NORMAL_LEAP_CYCLE_DAYS;
937 uday -= n001 * GREGORIAN_NORMAL_LEAP_CYCLE_DAYS;
939 /* Assemble the year and day in year */
940 res.hi = n100 * 100 + n001;
943 /* Possibly set the leap year flag */
945 uint32_t tc = (uint32_t)n100 + 1;
946 uint32_t ty = (uint32_t)n001 + 1;
947 *isleapyear = !(ty & 3)
948 && ((ty != 100) || !(tc & 3));
954 *---------------------------------------------------------------------
955 * Given a number of elapsed days in a year and a leap year indicator,
956 * split the number of elapsed days into the number of elapsed months in
957 * 'res.hi' and the number of elapsed days of that month in 'res.lo'.
959 * This function will fail and return {-1,-1} if the number of elapsed
960 * days is not in the valid range!
961 *---------------------------------------------------------------------
964 ntpcal_split_yeardays(
969 /* Use the unshifted-year, February-with-30-days approach here.
970 * Fractional interpolations are used in both directions, with
971 * the smallest power-of-two divider to avoid any true division.
973 ntpcal_split res = {-1, -1};
975 /* convert 'isleap' to number of defective days */
976 isleap = 1 + !isleap;
977 /* adjust for February of 30 nominal days */
978 if (eyd >= 61 - isleap)
980 /* if in range, convert to months and days in month */
981 if (eyd >= 0 && eyd < 367) {
982 res.hi = (eyd * 67 + 32) >> 11;
983 res.lo = eyd - ((489 * res.hi + 8) >> 4);
990 *---------------------------------------------------------------------
991 * Convert a RD into the date part of a 'struct calendar'.
992 *---------------------------------------------------------------------
1004 /* Get day-of-week first. It's simply the RD (mod 7)... */
1005 jd->weekday = i32mod7(rd);
1007 split = ntpcal_split_eradays(rd - 1, &leapy);
1008 /* Get year and day-of-year, with overflow check. If any of the
1009 * upper 16 bits is set after shifting to unity-based years, we
1010 * will have an overflow when converting to an unsigned 16bit
1011 * year. Shifting to the right is OK here, since it does not
1012 * matter if the shift is logic or arithmetic.
1015 ymask = 0u - ((split.hi >> 16) == 0);
1016 jd->year = (uint16_t)(split.hi & ymask);
1017 jd->yearday = (uint16_t)split.lo + 1;
1019 /* convert to month and mday */
1020 split = ntpcal_split_yeardays(split.lo, leapy);
1021 jd->month = (uint8_t)split.hi + 1;
1022 jd->monthday = (uint8_t)split.lo + 1;
1024 return ymask ? leapy : -1;
1028 *---------------------------------------------------------------------
1029 * Convert a RD into the date part of a 'struct tm'.
1030 *---------------------------------------------------------------------
1041 /* get day-of-week first */
1042 utm->tm_wday = i32mod7(rd);
1044 /* get year and day-of-year */
1045 split = ntpcal_split_eradays(rd - 1, &leapy);
1046 utm->tm_year = split.hi - 1899;
1047 utm->tm_yday = split.lo; /* 0-based */
1049 /* convert to month and mday */
1050 split = ntpcal_split_yeardays(split.lo, leapy);
1051 utm->tm_mon = split.hi; /* 0-based */
1052 utm->tm_mday = split.lo + 1; /* 1-based */
1058 *---------------------------------------------------------------------
1059 * Take a value of seconds since midnight and split it into hhmmss in a
1060 * 'struct calendar'.
1061 *---------------------------------------------------------------------
1064 ntpcal_daysec_to_date(
1065 struct calendar *jd,
1072 days = priv_timesplit(ts, sec);
1073 jd->hour = (uint8_t)ts[0];
1074 jd->minute = (uint8_t)ts[1];
1075 jd->second = (uint8_t)ts[2];
1081 *---------------------------------------------------------------------
1082 * Take a value of seconds since midnight and split it into hhmmss in a
1084 *---------------------------------------------------------------------
1087 ntpcal_daysec_to_tm(
1095 days = priv_timesplit(ts, sec);
1096 utm->tm_hour = ts[0];
1097 utm->tm_min = ts[1];
1098 utm->tm_sec = ts[2];
1104 *---------------------------------------------------------------------
1105 * take a split representation for day/second-of-day and day offset
1106 * and convert it to a 'struct calendar'. The seconds will be normalised
1107 * into the range of a day, and the day will be adjusted accordingly.
1109 * returns >0 if the result is in a leap year, 0 if in a regular
1110 * year and <0 if the result did not fit into the calendar struct.
1111 *---------------------------------------------------------------------
1114 ntpcal_daysplit_to_date(
1115 struct calendar *jd,
1116 const ntpcal_split *ds,
1120 dof += ntpcal_daysec_to_date(jd, ds->lo);
1121 return ntpcal_rd_to_date(jd, ds->hi + dof);
1125 *---------------------------------------------------------------------
1126 * take a split representation for day/second-of-day and day offset
1127 * and convert it to a 'struct tm'. The seconds will be normalised
1128 * into the range of a day, and the day will be adjusted accordingly.
1130 * returns 1 if the result is in a leap year and zero if in a regular
1132 *---------------------------------------------------------------------
1135 ntpcal_daysplit_to_tm(
1137 const ntpcal_split *ds ,
1141 dof += ntpcal_daysec_to_tm(utm, ds->lo);
1143 return ntpcal_rd_to_tm(utm, ds->hi + dof);
1147 *---------------------------------------------------------------------
1148 * Take a UN*X time and convert to a calendar structure.
1149 *---------------------------------------------------------------------
1152 ntpcal_time_to_date(
1153 struct calendar *jd,
1159 ds = ntpcal_daysplit(ts);
1160 ds.hi += ntpcal_daysec_to_date(jd, ds.lo);
1161 ds.hi += DAY_UNIX_STARTS;
1163 return ntpcal_rd_to_date(jd, ds.hi);
1168 * ====================================================================
1170 * merging composite entities
1172 * ====================================================================
1175 #if !defined(HAVE_INT64)
1176 /* multiplication helper. Seconds in days and weeks are multiples of 128,
1177 * and without that factor fit well into 16 bit. So a multiplication
1178 * of 32bit by 16bit and some shifting can be used on pure 32bit machines
1179 * with compilers that do not support 64bit integers.
1181 * Calculate ( hi * mul * 128 ) + lo
1191 uint32_t p1, p2, sf;
1193 /* get sign flag and absolute value of 'hi' in p1 */
1194 sf = (uint32_t)-(hi < 0);
1195 p1 = ((uint32_t)hi + sf) ^ sf;
1197 /* assemble major units: res <- |hi| * mul */
1198 res.D_s.lo = (p1 & 0xFFFF) * mul;
1200 p1 = (p1 >> 16) * mul;
1203 M_ADD(res.D_s.hi, res.D_s.lo, p2, p1);
1205 /* mul by 128, using shift: res <-- res << 7 */
1206 res.D_s.hi = (res.D_s.hi << 7) | (res.D_s.lo >> 25);
1207 res.D_s.lo = (res.D_s.lo << 7);
1209 /* fix up sign: res <-- (res + [sf|sf]) ^ [sf|sf] */
1210 M_ADD(res.D_s.hi, res.D_s.lo, sf, sf);
1214 /* properly add seconds: res <-- res + [sx(lo)|lo] */
1215 p2 = (uint32_t)-(lo < 0);
1217 M_ADD(res.D_s.hi, res.D_s.lo, p2, p1);
1223 *---------------------------------------------------------------------
1224 * Merge a number of days and a number of seconds into seconds,
1225 * expressed in 64 bits to avoid overflow.
1226 *---------------------------------------------------------------------
1236 # if defined(HAVE_INT64)
1239 res.q_s *= SECSPERDAY;
1244 res = _dwjoin(675, days, secs);
1252 *---------------------------------------------------------------------
1253 * Merge a number of weeks and a number of seconds into seconds,
1254 * expressed in 64 bits to avoid overflow.
1255 *---------------------------------------------------------------------
1265 # if defined(HAVE_INT64)
1268 res.q_s *= SECSPERWEEK;
1273 res = _dwjoin(4725, week, secs);
1281 *---------------------------------------------------------------------
1282 * get leap years since epoch in elapsed years
1283 *---------------------------------------------------------------------
1286 ntpcal_leapyears_in_years(
1290 /* We use the in-out-in algorithm here, using the one's
1291 * complement division trick for negative numbers. The chained
1292 * division sequence by 4/25/4 gives the compiler the chance to
1293 * get away with only one true division and doing shifts otherwise.
1296 uint32_t sf32, sum, uyear;
1298 sf32 = int32_sflag(years);
1299 uyear = (uint32_t)years;
1302 sum = (uyear /= 4u); /* 4yr rule --> IN */
1303 sum -= (uyear /= 25u); /* 100yr rule --> OUT */
1304 sum += (uyear /= 4u); /* 400yr rule --> IN */
1306 /* Thanks to the alternation of IN/OUT/IN we can do the sum
1307 * directly and have a single one's complement operation
1308 * here. (Only if the years are negative, of course.) Otherwise
1309 * the one's complement would have to be done when
1310 * adding/subtracting the terms.
1312 return uint32_2cpl_to_int32(sf32 ^ sum);
1316 *---------------------------------------------------------------------
1317 * Convert elapsed years in Era into elapsed days in Era.
1318 *---------------------------------------------------------------------
1321 ntpcal_days_in_years(
1325 return years * DAYSPERYEAR + ntpcal_leapyears_in_years(years);
1329 *---------------------------------------------------------------------
1330 * Convert a number of elapsed month in a year into elapsed days in year.
1332 * The month will be normalized, and 'res.hi' will contain the
1333 * excessive years that must be considered when converting the years,
1334 * while 'res.lo' will contain the number of elapsed days since start
1337 * This code uses the shifted-month-approach to convert month to days,
1338 * because then there is no need to have explicit leap year
1339 * information. The slight disadvantage is that for most month values
1340 * the result is a negative value, and the year excess is one; the
1341 * conversion is then simply based on the start of the following year.
1342 *---------------------------------------------------------------------
1345 ntpcal_days_in_months(
1351 /* Add ten months with proper year adjustment. */
1360 /* Possibly normalise by floor division. This does not hapen for
1361 * input in normal range. */
1362 if (res.lo < 0 || res.lo >= 12) {
1363 uint32_t mu, Q, sf32;
1364 sf32 = int32_sflag(res.lo);
1365 mu = (uint32_t)res.lo;
1366 Q = sf32 ^ ((sf32 ^ mu) / 12u);
1368 res.hi += uint32_2cpl_to_int32(Q);
1369 res.lo = mu - Q * 12u;
1372 /* Get cummulated days in year with unshift. Use the fractional
1373 * interpolation with smallest possible power of two in the
1376 res.lo = ((res.lo * 979 + 16) >> 5) - 306;
1382 *---------------------------------------------------------------------
1383 * Convert ELAPSED years/months/days of gregorian calendar to elapsed
1384 * days in Gregorian epoch.
1386 * If you want to convert years and days-of-year, just give a month of
1388 *---------------------------------------------------------------------
1391 ntpcal_edate_to_eradays(
1401 tmp = ntpcal_days_in_months(mons);
1402 res = ntpcal_days_in_years(years + tmp.hi) + tmp.lo;
1404 res = ntpcal_days_in_years(years);
1411 *---------------------------------------------------------------------
1412 * Convert ELAPSED years/months/days of gregorian calendar to elapsed
1415 * Note: This will give the true difference to the start of the given
1416 * year, even if months & days are off-scale.
1417 *---------------------------------------------------------------------
1420 ntpcal_edate_to_yeardays(
1428 if (0 <= mons && mons < 12) {
1430 mdays -= 2 - is_leapyear(years+1);
1431 mdays += (489 * mons + 8) >> 4;
1433 tmp = ntpcal_days_in_months(mons);
1435 + ntpcal_days_in_years(years + tmp.hi)
1436 - ntpcal_days_in_years(years);
1443 *---------------------------------------------------------------------
1444 * Convert elapsed days and the hour/minute/second information into
1447 * If 'isvalid' is not NULL, do a range check on the time specification
1448 * and tell if the time input is in the normal range, permitting for a
1449 * single leapsecond.
1450 *---------------------------------------------------------------------
1453 ntpcal_etime_to_seconds(
1461 res = (hours * MINSPERHR + minutes) * SECSPERMIN + seconds;
1467 *---------------------------------------------------------------------
1468 * Convert the date part of a 'struct tm' (that is, year, month,
1469 * day-of-month) into the RD of that day.
1470 *---------------------------------------------------------------------
1474 const struct tm *utm
1477 return ntpcal_edate_to_eradays(utm->tm_year + 1899,
1479 utm->tm_mday - 1) + 1;
1483 *---------------------------------------------------------------------
1484 * Convert the date part of a 'struct calendar' (that is, year, month,
1485 * day-of-month) into the RD of that day.
1486 *---------------------------------------------------------------------
1490 const struct calendar *jd
1493 return ntpcal_edate_to_eradays((int32_t)jd->year - 1,
1494 (int32_t)jd->month - 1,
1495 (int32_t)jd->monthday - 1) + 1;
1499 *---------------------------------------------------------------------
1500 * convert a year number to rata die of year start
1501 *---------------------------------------------------------------------
1504 ntpcal_year_to_ystart(
1508 return ntpcal_days_in_years(year - 1) + 1;
1512 *---------------------------------------------------------------------
1513 * For a given RD, get the RD of the associated year start,
1514 * that is, the RD of the last January,1st on or before that day.
1515 *---------------------------------------------------------------------
1518 ntpcal_rd_to_ystart(
1523 * Rather simple exercise: split the day number into elapsed
1524 * years and elapsed days, then remove the elapsed days from the
1525 * input value. Nice'n sweet...
1527 return rd - ntpcal_split_eradays(rd - 1, NULL).lo;
1531 *---------------------------------------------------------------------
1532 * For a given RD, get the RD of the associated month start.
1533 *---------------------------------------------------------------------
1536 ntpcal_rd_to_mstart(
1543 split = ntpcal_split_eradays(rd - 1, &leaps);
1544 split = ntpcal_split_yeardays(split.lo, leaps);
1546 return rd - split.lo;
1550 *---------------------------------------------------------------------
1551 * take a 'struct calendar' and get the seconds-of-day from it.
1552 *---------------------------------------------------------------------
1555 ntpcal_date_to_daysec(
1556 const struct calendar *jd
1559 return ntpcal_etime_to_seconds(jd->hour, jd->minute,
1564 *---------------------------------------------------------------------
1565 * take a 'struct tm' and get the seconds-of-day from it.
1566 *---------------------------------------------------------------------
1569 ntpcal_tm_to_daysec(
1570 const struct tm *utm
1573 return ntpcal_etime_to_seconds(utm->tm_hour, utm->tm_min,
1578 *---------------------------------------------------------------------
1579 * take a 'struct calendar' and convert it to a 'time_t'
1580 *---------------------------------------------------------------------
1583 ntpcal_date_to_time(
1584 const struct calendar *jd
1590 days = ntpcal_date_to_rd(jd) - DAY_UNIX_STARTS;
1591 secs = ntpcal_date_to_daysec(jd);
1592 join = ntpcal_dayjoin(days, secs);
1594 return vint64_to_time(&join);
1599 * ====================================================================
1601 * extended and unchecked variants of caljulian/caltontp
1603 * ====================================================================
1606 ntpcal_ntp64_to_date(
1607 struct calendar *jd,
1613 ds = ntpcal_daysplit(ntp);
1614 ds.hi += ntpcal_daysec_to_date(jd, ds.lo);
1616 return ntpcal_rd_to_date(jd, ds.hi + DAY_NTP_STARTS);
1621 struct calendar *jd,
1629 * Unfold ntp time around current time into NTP domain. Split
1630 * into days and seconds, shift days into CE domain and
1631 * process the parts.
1633 ntp64 = ntpcal_ntp_to_ntp(ntp, piv);
1634 return ntpcal_ntp64_to_date(jd, &ntp64);
1639 ntpcal_date_to_ntp64(
1640 const struct calendar *jd
1644 * Convert date to NTP. Ignore yearday, use d/m/y only.
1646 return ntpcal_dayjoin(ntpcal_date_to_rd(jd) - DAY_NTP_STARTS,
1647 ntpcal_date_to_daysec(jd));
1653 const struct calendar *jd
1657 * Get lower half of 64bit NTP timestamp from date/time.
1659 return ntpcal_date_to_ntp64(jd).d_s.lo;
1665 * ====================================================================
1667 * day-of-week calculations
1669 * ====================================================================
1672 * Given a RataDie and a day-of-week, calculate a RDN that is reater-than,
1673 * greater-or equal, closest, less-or-equal or less-than the given RDN
1674 * and denotes the given day-of-week
1682 return ntpcal_periodic_extend(rdn+1, dow, 7);
1691 return ntpcal_periodic_extend(rdn, dow, 7);
1695 ntpcal_weekday_close(
1700 return ntpcal_periodic_extend(rdn-3, dow, 7);
1709 return ntpcal_periodic_extend(rdn, dow, -7);
1718 return ntpcal_periodic_extend(rdn-1, dow, -7);
1722 * ====================================================================
1724 * ISO week-calendar conversions
1726 * The ISO8601 calendar defines a calendar of years, weeks and weekdays.
1727 * It is related to the Gregorian calendar, and a ISO year starts at the
1728 * Monday closest to Jan,1st of the corresponding Gregorian year. A ISO
1729 * calendar year has always 52 or 53 weeks, and like the Grogrian
1730 * calendar the ISO8601 calendar repeats itself every 400 years, or
1731 * 146097 days, or 20871 weeks.
1733 * While it is possible to write ISO calendar functions based on the
1734 * Gregorian calendar functions, the following implementation takes a
1735 * different approach, based directly on years and weeks.
1737 * Analysis of the tabulated data shows that it is not possible to
1738 * interpolate from years to weeks over a full 400 year range; cyclic
1739 * shifts over 400 years do not provide a solution here. But it *is*
1740 * possible to interpolate over every single century of the 400-year
1741 * cycle. (The centennial leap year rule seems to be the culprit here.)
1743 * It can be shown that a conversion from years to weeks can be done
1744 * using a linear transformation of the form
1746 * w = floor( y * a + b )
1748 * where the slope a must hold to
1750 * 52.1780821918 <= a < 52.1791044776
1752 * and b must be chosen according to the selected slope and the number
1753 * of the century in a 400-year period.
1755 * The inverse calculation can also be done in this way. Careful scaling
1756 * provides an unlimited set of integer coefficients a,k,b that enable
1757 * us to write the calulation in the form
1759 * w = (y * a + b ) / k
1760 * y = (w * a' + b') / k'
1762 * In this implementation the values of k and k' are chosen to be the
1763 * smallest possible powers of two, so the division can be implemented
1764 * as shifts if the optimiser chooses to do so.
1766 * ====================================================================
1770 * Given a number of elapsed (ISO-)years since the begin of the
1771 * christian era, return the number of elapsed weeks corresponding to
1772 * the number of years.
1775 isocal_weeks_in_years(
1780 * use: w = (y * 53431 + b[c]) / 1024 as interpolation
1782 static const uint16_t bctab[4] = { 157, 449, 597, 889 };
1785 uint32_t cc, ci, yu, sf32;
1787 sf32 = int32_sflag(years);
1788 yu = (uint32_t)years;
1790 /* split off centuries, using floor division */
1791 cc = sf32 ^ ((sf32 ^ yu) / 100u);
1794 /* calculate century cycles shift and cycle index:
1795 * Assuming a century is 5217 weeks, we have to add a cycle
1796 * shift that is 3 for every 4 centuries, because 3 of the four
1797 * centuries have 5218 weeks. So '(cc*3 + 1) / 4' is the actual
1798 * correction, and the second century is the defective one.
1800 * Needs floor division by 4, which is done with masking and
1804 cs = uint32_2cpl_to_int32(sf32 ^ ((sf32 ^ ci) >> 2));
1807 /* Get weeks in century. Can use plain division here as all ops
1808 * are >= 0, and let the compiler sort out the possible
1811 cw = (yu * 53431u + bctab[ci]) / 1024u;
1813 return uint32_2cpl_to_int32(cc) * 5217 + cs + cw;
1817 * Given a number of elapsed weeks since the begin of the christian
1818 * era, split this number into the number of elapsed years in res.hi
1819 * and the excessive number of weeks in res.lo. (That is, res.lo is
1820 * the number of elapsed weeks in the remaining partial year.)
1823 isocal_split_eraweeks(
1828 * use: y = (w * 157 + b[c]) / 8192 as interpolation
1831 static const uint16_t bctab[4] = { 85, 130, 17, 62 };
1837 /* Use two fast cycle-split divisions again. Herew e want to
1838 * execute '(weeks * 4 + 2) /% 20871' under floor division rules
1839 * in the first step.
1841 * This is of course (again) susceptible to internal overflow if
1842 * coded directly in 32bit. And again we use 64bit division on
1843 * a 64bit target and exact division after calculating the
1844 * remainder first on a 32bit target. With the smaller divider,
1845 * that's even a bit neater.
1847 # if defined(HAVE_64BITREGS)
1849 /* Full floor division with 64bit values. */
1850 uint64_t sf64, sw64;
1851 sf64 = (uint64_t)-(weeks < 0);
1852 sw64 = ((uint64_t)weeks << 2) | 2u;
1853 Q = (uint32_t)(sf64 ^ ((sf64 ^ sw64) / GREGORIAN_CYCLE_WEEKS));
1854 sw = (uint32_t)(sw64 - Q * GREGORIAN_CYCLE_WEEKS);
1858 /* Exact division after calculating the remainder via partial
1859 * reduction by digit sum.
1860 * (-2^33) % 20871 --> 5491 : the sign bit value
1861 * ( 2^20) % 20871 --> 5026 : the upper digit value
1862 * modinv(20871, 2^32) --> 330081335 : the inverse
1864 uint32_t ux = ((uint32_t)weeks << 2) | 2;
1865 sw = (weeks < 0) ? 5491u : 0u; /* sign dgt */
1866 sw += ((weeks >> 18) & 0x01FFFu) * 5026u; /* hi dgt (src!) */
1867 sw += (ux & 0xFFFFFu); /* lo dgt */
1868 sw %= GREGORIAN_CYCLE_WEEKS; /* full reduction */
1869 Q = (ux - sw) * 330081335u; /* exact div */
1874 cc = uint32_2cpl_to_int32(Q);
1876 /* Split off years; sw >= 0 here! The scaled weeks in the years
1877 * are scaled up by 157 afterwards.
1879 sw = (sw / 4u) * 157u + bctab[ci];
1880 cy = sw / 8192u; /* sw >> 13 , let the compiler sort it out */
1881 sw = sw % 8192u; /* sw & 8191, let the compiler sort it out */
1883 /* assemble elapsed years and downscale the elapsed weeks in
1886 res.hi = 100*cc + cy;
1893 * Given a second in the NTP time scale and a pivot, expand the NTP
1894 * time stamp around the pivot and convert into an ISO calendar time
1898 isocal_ntp64_to_date(
1905 uint32_t uw, ud, sf32;
1908 * Split NTP time into days and seconds, shift days into CE
1909 * domain and process the parts.
1911 ds = ntpcal_daysplit(ntp);
1913 /* split time part */
1914 ds.hi += priv_timesplit(ts, ds.lo);
1915 id->hour = (uint8_t)ts[0];
1916 id->minute = (uint8_t)ts[1];
1917 id->second = (uint8_t)ts[2];
1919 /* split days into days and weeks, using floor division in unsigned */
1920 ds.hi += DAY_NTP_STARTS - 1; /* shift from NTP to RDN */
1921 sf32 = int32_sflag(ds.hi);
1922 ud = (uint32_t)ds.hi;
1923 uw = sf32 ^ ((sf32 ^ ud) / DAYSPERWEEK);
1924 ud -= uw * DAYSPERWEEK;
1926 ds.hi = uint32_2cpl_to_int32(uw);
1929 id->weekday = (uint8_t)ds.lo + 1; /* weekday result */
1931 /* get year and week in year */
1932 ds = isocal_split_eraweeks(ds.hi); /* elapsed years&week*/
1933 id->year = (uint16_t)ds.hi + 1; /* shift to current */
1934 id->week = (uint8_t )ds.lo + 1;
1936 return (ds.hi >= 0 && ds.hi < 0x0000FFFF);
1949 * Unfold ntp time around current time into NTP domain, then
1950 * convert the full time stamp.
1952 ntp64 = ntpcal_ntp_to_ntp(ntp, piv);
1953 return isocal_ntp64_to_date(id, &ntp64);
1957 * Convert a ISO date spec into a second in the NTP time scale,
1958 * properly truncated to 32 bit.
1961 isocal_date_to_ntp64(
1962 const struct isodate *id
1965 int32_t weeks, days, secs;
1967 weeks = isocal_weeks_in_years((int32_t)id->year - 1)
1968 + (int32_t)id->week - 1;
1969 days = weeks * 7 + (int32_t)id->weekday;
1970 /* days is RDN of ISO date now */
1971 secs = ntpcal_etime_to_seconds(id->hour, id->minute, id->second);
1973 return ntpcal_dayjoin(days - DAY_NTP_STARTS, secs);
1978 const struct isodate *id
1982 * Get lower half of 64bit NTP timestamp from date/time.
1984 return isocal_date_to_ntp64(id).d_s.lo;
1988 * ====================================================================
1989 * 'basedate' support functions
1990 * ====================================================================
1993 static int32_t s_baseday = NTP_TO_UNIX_DAYS;
1994 static int32_t s_gpsweek = 0;
1997 basedate_eval_buildstamp(void)
2002 if (!ntpcal_get_build_date(&jd))
2003 return NTP_TO_UNIX_DAYS;
2005 /* The time zone of the build stamp is unspecified; we remove
2006 * one day to provide a certain slack. And in case somebody
2007 * fiddled with the system clock, we make sure we do not go
2008 * before the UNIX epoch (1970-01-01). It's probably not possible
2009 * to do this to the clock on most systems, but there are other
2010 * ways to tweak the build stamp.
2013 ed = ntpcal_date_to_rd(&jd) - DAY_NTP_STARTS;
2014 return (ed < NTP_TO_UNIX_DAYS) ? NTP_TO_UNIX_DAYS : ed;
2018 basedate_eval_string(
2028 rc = sscanf(str, "%4hu-%2hu-%2hu%n", &y, &m, &d, &nc);
2029 if (rc == 3 && (size_t)nc == sl) {
2030 if (m >= 1 && m <= 12 && d >= 1 && d <= 31)
2031 return ntpcal_edate_to_eradays(y-1, m-1, d)
2036 rc = sscanf(str, "%lu%n", &ned, &nc);
2037 if (rc == 1 && (size_t)nc == sl) {
2038 if (ned <= INT32_MAX)
2039 return (int32_t)ned;
2044 msyslog(LOG_WARNING,
2045 "basedate string \"%s\" invalid, build date substituted!",
2047 return basedate_eval_buildstamp();
2051 basedate_get_day(void)
2064 /* set NTP base date for NTP era unfolding */
2065 if (day < NTP_TO_UNIX_DAYS) {
2066 msyslog(LOG_WARNING,
2067 "baseday_set_day: invalid day (%lu), UNIX epoch substituted",
2068 (unsigned long)day);
2069 day = NTP_TO_UNIX_DAYS;
2073 ntpcal_rd_to_date(&jd, day + DAY_NTP_STARTS);
2074 msyslog(LOG_INFO, "basedate set to %04hu-%02hu-%02hu",
2075 jd.year, (u_short)jd.month, (u_short)jd.monthday);
2077 /* set GPS base week for GPS week unfolding */
2078 day = ntpcal_weekday_ge(day + DAY_NTP_STARTS, CAL_SUNDAY)
2080 if (day < NTP_TO_GPS_DAYS)
2081 day = NTP_TO_GPS_DAYS;
2082 s_gpsweek = (day - NTP_TO_GPS_DAYS) / DAYSPERWEEK;
2083 ntpcal_rd_to_date(&jd, day + DAY_NTP_STARTS);
2084 msyslog(LOG_INFO, "gps base set to %04hu-%02hu-%02hu (week %d)",
2085 jd.year, (u_short)jd.month, (u_short)jd.monthday, s_gpsweek);
2091 basedate_get_eracenter(void)
2094 retv = (time_t)(s_baseday - NTP_TO_UNIX_DAYS);
2096 retv += (UINT32_C(1) << 31);
2101 basedate_get_erabase(void)
2104 retv = (time_t)(s_baseday - NTP_TO_UNIX_DAYS);
2110 basedate_get_gpsweek(void)
2116 basedate_expand_gpsweek(
2117 unsigned short weekno
2120 /* We do a fast modulus expansion here. Since all quantities are
2121 * unsigned and we cannot go before the start of the GPS epoch
2122 * anyway, and since the truncated GPS week number is 10 bit, the
2123 * expansion becomes a simple sub/and/add sequence.
2125 #if GPSWEEKS != 1024
2126 # error GPSWEEKS defined wrong -- should be 1024!
2130 diff = ((uint32_t)weekno - s_gpsweek) & (GPSWEEKS - 1);
2131 return s_gpsweek + diff;
2135 * ====================================================================
2137 * ====================================================================
2140 /* --------------------------------------------------------------------
2141 * reconstruct the centrury from a truncated date and a day-of-week
2143 * Given a date with truncated year (2-digit, 0..99) and a day-of-week
2144 * from 1(Mon) to 7(Sun), recover the full year between 1900AD and 2300AD.
2147 ntpcal_expand_century(
2153 /* This algorithm is short but tricky... It's related to
2154 * Zeller's congruence, partially done backwards.
2156 * A few facts to remember:
2157 * 1) The Gregorian calendar has a cycle of 400 years.
2158 * 2) The weekday of the 1st day of a century shifts by 5 days
2159 * during a great cycle.
2160 * 3) For calendar math, a century starts with the 1st year,
2161 * which is year 1, !not! zero.
2163 * So we start with taking the weekday difference (mod 7)
2164 * between the truncated date (which is taken as an absolute
2165 * date in the 1st century in the proleptic calendar) and the
2168 * When dividing this residual by 5, we obtain the number of
2169 * centuries to add to the base. But since the residual is (mod
2170 * 7), we have to make this an exact division by multiplication
2171 * with the modular inverse of 5 (mod 7), which is 3:
2172 * 3*5 === 1 (mod 7).
2174 * If this yields a result of 4/5/6, the given date/day-of-week
2175 * combination is impossible, and we return zero as resulting
2176 * year to indicate failure.
2178 * Then we remap the century to the range starting with year
2184 /* check basic constraints */
2185 if ((y >= 100u) || (--m >= 12u) || (--d >= 31u))
2188 if ((m += 10u) >= 12u) /* shift base to prev. March,1st */
2190 else if (--y >= 100u)
2192 d += y + (y >> 2) + 2u; /* year share */
2193 d += (m * 83u + 16u) >> 5; /* month share */
2195 /* get (wd - d), shifted to positive value, and multiply with
2196 * 3(mod 7). (Exact division, see to comment)
2197 * Note: 1) d <= 184 at this point.
2198 * 2) 252 % 7 == 0, but 'wd' is off by one since we did
2199 * '--d' above, so we add just 251 here!
2201 c = u32mod7(3 * (251u + wd - d));
2205 if ((m > 9u) && (++y >= 100u)) {/* undo base shift */
2209 y += (c * 100u); /* combine into 1st cycle */
2210 y += (y < 300u) ? 2000 : 1600; /* map to destination era */
2223 len = LIB_BUFLENGTH;
2226 len = snprintf(buf, len, "%04u-%02u-%02uT%02u:%02u:%02u",
2227 cdp->year, cdp->month, cdp->monthday,
2228 cdp->hour, cdp->minute, cdp->second);