3
0

ntpd.c 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236
  1. /*
  2. * NTP client/server, based on OpenNTPD 3.9p1
  3. *
  4. * Author: Adam Tkac <vonsch@gmail.com>
  5. *
  6. * Licensed under GPLv2, see file LICENSE in this tarball for details.
  7. *
  8. * Parts of OpenNTPD clock syncronization code is replaced by
  9. * code which is based on ntp-4.2.6, whuch carries the following
  10. * copyright notice:
  11. *
  12. ***********************************************************************
  13. * *
  14. * Copyright (c) University of Delaware 1992-2009 *
  15. * *
  16. * Permission to use, copy, modify, and distribute this software and *
  17. * its documentation for any purpose with or without fee is hereby *
  18. * granted, provided that the above copyright notice appears in all *
  19. * copies and that both the copyright notice and this permission *
  20. * notice appear in supporting documentation, and that the name *
  21. * University of Delaware not be used in advertising or publicity *
  22. * pertaining to distribution of the software without specific, *
  23. * written prior permission. The University of Delaware makes no *
  24. * representations about the suitability this software for any *
  25. * purpose. It is provided "as is" without express or implied *
  26. * warranty. *
  27. * *
  28. ***********************************************************************
  29. */
  30. #include "libbb.h"
  31. #include <math.h>
  32. #include <netinet/ip.h> /* For IPTOS_LOWDELAY definition */
  33. #include <sys/timex.h>
  34. #ifndef IPTOS_LOWDELAY
  35. # define IPTOS_LOWDELAY 0x10
  36. #endif
  37. #ifndef IP_PKTINFO
  38. # error "Sorry, your kernel has to support IP_PKTINFO"
  39. #endif
  40. /* Verbosity control (max level of -dddd options accepted).
  41. * max 5 is very talkative (and bloated). 2 is non-bloated,
  42. * production level setting.
  43. */
  44. #define MAX_VERBOSE 2
  45. /* High-level description of the algorithm:
  46. *
  47. * We start running with very small poll_exp, BURSTPOLL,
  48. * in order to quickly accumulate INITIAL_SAMLPES datapoints
  49. * for each peer. Then, time is stepped if the offset is larger
  50. * than STEP_THRESHOLD, otherwise it isn't; anyway, we enlarge
  51. * poll_exp to MINPOLL and enter frequency measurement step:
  52. * we collect new datapoints but ignore them for WATCH_THRESHOLD
  53. * seconds. After WATCH_THRESHOLD seconds we look at accumulated
  54. * offset and estimate frequency drift.
  55. *
  56. * (frequency measurement step seems to not be strictly needed,
  57. * it is conditionally disabled with USING_INITIAL_FREQ_ESTIMATION
  58. * define set to 0)
  59. *
  60. * After this, we enter "steady state": we collect a datapoint,
  61. * we select the best peer, if this datapoint is not a new one
  62. * (IOW: if this datapoint isn't for selected peer), sleep
  63. * and collect another one; otherwise, use its offset to update
  64. * frequency drift, if offset is somewhat large, reduce poll_exp,
  65. * otherwise increase poll_exp.
  66. *
  67. * If offset is larger than STEP_THRESHOLD, which shouldn't normally
  68. * happen, we assume that something "bad" happened (computer
  69. * was hibernated, someone set totally wrong date, etc),
  70. * then the time is stepped, all datapoints are discarded,
  71. * and we go back to steady state.
  72. */
  73. #define RETRY_INTERVAL 5 /* on error, retry in N secs */
  74. #define RESPONSE_INTERVAL 15 /* wait for reply up to N secs */
  75. #define INITIAL_SAMLPES 4 /* how many samples do we want for init */
  76. /* Clock discipline parameters and constants */
  77. /* Step threshold (sec). std ntpd uses 0.128.
  78. * Using exact power of 2 (1/8) results in smaller code */
  79. #define STEP_THRESHOLD 0.125
  80. #define WATCH_THRESHOLD 128 /* stepout threshold (sec). std ntpd uses 900 (11 mins (!)) */
  81. /* NB: set WATCH_THRESHOLD to ~60 when debugging to save time) */
  82. //UNUSED: #define PANIC_THRESHOLD 1000 /* panic threshold (sec) */
  83. #define FREQ_TOLERANCE 0.000015 /* frequency tolerance (15 PPM) */
  84. #define BURSTPOLL 0 /* initial poll */
  85. #define MINPOLL 5 /* minimum poll interval. std ntpd uses 6 (6: 64 sec) */
  86. #define BIGPOLL 10 /* drop to lower poll at any trouble (10: 17 min) */
  87. #define MAXPOLL 12 /* maximum poll interval (12: 1.1h, 17: 36.4h). std ntpd uses 17 */
  88. /* Actively lower poll when we see such big offsets.
  89. * With STEP_THRESHOLD = 0.125, it means we try to sync more aggressively
  90. * if offset increases over 0.03 sec */
  91. #define POLLDOWN_OFFSET (STEP_THRESHOLD / 4)
  92. #define MINDISP 0.01 /* minimum dispersion (sec) */
  93. #define MAXDISP 16 /* maximum dispersion (sec) */
  94. #define MAXSTRAT 16 /* maximum stratum (infinity metric) */
  95. #define MAXDIST 1 /* distance threshold (sec) */
  96. #define MIN_SELECTED 1 /* minimum intersection survivors */
  97. #define MIN_CLUSTERED 3 /* minimum cluster survivors */
  98. #define MAXDRIFT 0.000500 /* frequency drift we can correct (500 PPM) */
  99. /* Poll-adjust threshold.
  100. * When we see that offset is small enough compared to discipline jitter,
  101. * we grow a counter: += MINPOLL. When it goes over POLLADJ_LIMIT,
  102. * we poll_exp++. If offset isn't small, counter -= poll_exp*2,
  103. * and when it goes below -POLLADJ_LIMIT, we poll_exp--
  104. * (bumped from 30 to 36 since otherwise I often see poll_exp going *2* steps down)
  105. */
  106. #define POLLADJ_LIMIT 36
  107. /* If offset < POLLADJ_GATE * discipline_jitter, then we can increase
  108. * poll interval (we think we can't improve timekeeping
  109. * by staying at smaller poll).
  110. */
  111. #define POLLADJ_GATE 4
  112. /* Compromise Allan intercept (sec). doc uses 1500, std ntpd uses 512 */
  113. #define ALLAN 512
  114. /* PLL loop gain */
  115. #define PLL 65536
  116. /* FLL loop gain [why it depends on MAXPOLL??] */
  117. #define FLL (MAXPOLL + 1)
  118. /* Parameter averaging constant */
  119. #define AVG 4
  120. enum {
  121. NTP_VERSION = 4,
  122. NTP_MAXSTRATUM = 15,
  123. NTP_DIGESTSIZE = 16,
  124. NTP_MSGSIZE_NOAUTH = 48,
  125. NTP_MSGSIZE = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
  126. /* Status Masks */
  127. MODE_MASK = (7 << 0),
  128. VERSION_MASK = (7 << 3),
  129. VERSION_SHIFT = 3,
  130. LI_MASK = (3 << 6),
  131. /* Leap Second Codes (high order two bits of m_status) */
  132. LI_NOWARNING = (0 << 6), /* no warning */
  133. LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
  134. LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
  135. LI_ALARM = (3 << 6), /* alarm condition */
  136. /* Mode values */
  137. MODE_RES0 = 0, /* reserved */
  138. MODE_SYM_ACT = 1, /* symmetric active */
  139. MODE_SYM_PAS = 2, /* symmetric passive */
  140. MODE_CLIENT = 3, /* client */
  141. MODE_SERVER = 4, /* server */
  142. MODE_BROADCAST = 5, /* broadcast */
  143. MODE_RES1 = 6, /* reserved for NTP control message */
  144. MODE_RES2 = 7, /* reserved for private use */
  145. };
  146. //TODO: better base selection
  147. #define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
  148. #define NUM_DATAPOINTS 8
  149. typedef struct {
  150. uint32_t int_partl;
  151. uint32_t fractionl;
  152. } l_fixedpt_t;
  153. typedef struct {
  154. uint16_t int_parts;
  155. uint16_t fractions;
  156. } s_fixedpt_t;
  157. typedef struct {
  158. uint8_t m_status; /* status of local clock and leap info */
  159. uint8_t m_stratum;
  160. uint8_t m_ppoll; /* poll value */
  161. int8_t m_precision_exp;
  162. s_fixedpt_t m_rootdelay;
  163. s_fixedpt_t m_rootdisp;
  164. uint32_t m_refid;
  165. l_fixedpt_t m_reftime;
  166. l_fixedpt_t m_orgtime;
  167. l_fixedpt_t m_rectime;
  168. l_fixedpt_t m_xmttime;
  169. uint32_t m_keyid;
  170. uint8_t m_digest[NTP_DIGESTSIZE];
  171. } msg_t;
  172. typedef struct {
  173. double d_recv_time;
  174. double d_offset;
  175. double d_dispersion;
  176. } datapoint_t;
  177. typedef struct {
  178. len_and_sockaddr *p_lsa;
  179. char *p_dotted;
  180. /* when to send new query (if p_fd == -1)
  181. * or when receive times out (if p_fd >= 0): */
  182. int p_fd;
  183. int datapoint_idx;
  184. uint32_t lastpkt_refid;
  185. uint8_t lastpkt_status;
  186. uint8_t lastpkt_stratum;
  187. uint8_t reachable_bits;
  188. double next_action_time;
  189. double p_xmttime;
  190. double lastpkt_recv_time;
  191. double lastpkt_delay;
  192. double lastpkt_rootdelay;
  193. double lastpkt_rootdisp;
  194. /* produced by filter algorithm: */
  195. double filter_offset;
  196. double filter_dispersion;
  197. double filter_jitter;
  198. datapoint_t filter_datapoint[NUM_DATAPOINTS];
  199. /* last sent packet: */
  200. msg_t p_xmt_msg;
  201. } peer_t;
  202. #define USING_KERNEL_PLL_LOOP 1
  203. #define USING_INITIAL_FREQ_ESTIMATION 0
  204. enum {
  205. OPT_n = (1 << 0),
  206. OPT_q = (1 << 1),
  207. OPT_N = (1 << 2),
  208. OPT_x = (1 << 3),
  209. /* Insert new options above this line. */
  210. /* Non-compat options: */
  211. OPT_w = (1 << 4),
  212. OPT_p = (1 << 5),
  213. OPT_S = (1 << 6),
  214. OPT_l = (1 << 7) * ENABLE_FEATURE_NTPD_SERVER,
  215. };
  216. struct globals {
  217. double cur_time;
  218. /* total round trip delay to currently selected reference clock */
  219. double rootdelay;
  220. /* reference timestamp: time when the system clock was last set or corrected */
  221. double reftime;
  222. /* total dispersion to currently selected reference clock */
  223. double rootdisp;
  224. double last_script_run;
  225. char *script_name;
  226. llist_t *ntp_peers;
  227. #if ENABLE_FEATURE_NTPD_SERVER
  228. int listen_fd;
  229. #endif
  230. unsigned verbose;
  231. unsigned peer_cnt;
  232. /* refid: 32-bit code identifying the particular server or reference clock
  233. * in stratum 0 packets this is a four-character ASCII string,
  234. * called the kiss code, used for debugging and monitoring
  235. * in stratum 1 packets this is a four-character ASCII string
  236. * assigned to the reference clock by IANA. Example: "GPS "
  237. * in stratum 2+ packets, it's IPv4 address or 4 first bytes of MD5 hash of IPv6
  238. */
  239. uint32_t refid;
  240. uint8_t ntp_status;
  241. /* precision is defined as the larger of the resolution and time to
  242. * read the clock, in log2 units. For instance, the precision of a
  243. * mains-frequency clock incrementing at 60 Hz is 16 ms, even when the
  244. * system clock hardware representation is to the nanosecond.
  245. *
  246. * Delays, jitters of various kinds are clamper down to precision.
  247. *
  248. * If precision_sec is too large, discipline_jitter gets clamped to it
  249. * and if offset is much smaller than discipline_jitter, poll interval
  250. * grows even though we really can benefit from staying at smaller one,
  251. * collecting non-lagged datapoits and correcting the offset.
  252. * (Lagged datapoits exist when poll_exp is large but we still have
  253. * systematic offset error - the time distance between datapoints
  254. * is significat and older datapoints have smaller offsets.
  255. * This makes our offset estimation a bit smaller than reality)
  256. * Due to this effect, setting G_precision_sec close to
  257. * STEP_THRESHOLD isn't such a good idea - offsets may grow
  258. * too big and we will step. I observed it with -6.
  259. *
  260. * OTOH, setting precision too small would result in futile attempts
  261. * to syncronize to the unachievable precision.
  262. *
  263. * -6 is 1/64 sec, -7 is 1/128 sec and so on.
  264. */
  265. #define G_precision_exp -8
  266. #define G_precision_sec (1.0 / (1 << (- G_precision_exp)))
  267. uint8_t stratum;
  268. /* Bool. After set to 1, never goes back to 0: */
  269. smallint initial_poll_complete;
  270. #define STATE_NSET 0 /* initial state, "nothing is set" */
  271. //#define STATE_FSET 1 /* frequency set from file */
  272. #define STATE_SPIK 2 /* spike detected */
  273. //#define STATE_FREQ 3 /* initial frequency */
  274. #define STATE_SYNC 4 /* clock synchronized (normal operation) */
  275. uint8_t discipline_state; // doc calls it c.state
  276. uint8_t poll_exp; // s.poll
  277. int polladj_count; // c.count
  278. long kernel_freq_drift;
  279. peer_t *last_update_peer;
  280. double last_update_offset; // c.last
  281. double last_update_recv_time; // s.t
  282. double discipline_jitter; // c.jitter
  283. //double cluster_offset; // s.offset
  284. //double cluster_jitter; // s.jitter
  285. #if !USING_KERNEL_PLL_LOOP
  286. double discipline_freq_drift; // c.freq
  287. /* Maybe conditionally calculate wander? it's used only for logging */
  288. double discipline_wander; // c.wander
  289. #endif
  290. };
  291. #define G (*ptr_to_globals)
  292. static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
  293. #define VERB1 if (MAX_VERBOSE && G.verbose)
  294. #define VERB2 if (MAX_VERBOSE >= 2 && G.verbose >= 2)
  295. #define VERB3 if (MAX_VERBOSE >= 3 && G.verbose >= 3)
  296. #define VERB4 if (MAX_VERBOSE >= 4 && G.verbose >= 4)
  297. #define VERB5 if (MAX_VERBOSE >= 5 && G.verbose >= 5)
  298. static double LOG2D(int a)
  299. {
  300. if (a < 0)
  301. return 1.0 / (1UL << -a);
  302. return 1UL << a;
  303. }
  304. static ALWAYS_INLINE double SQUARE(double x)
  305. {
  306. return x * x;
  307. }
  308. static ALWAYS_INLINE double MAXD(double a, double b)
  309. {
  310. if (a > b)
  311. return a;
  312. return b;
  313. }
  314. static ALWAYS_INLINE double MIND(double a, double b)
  315. {
  316. if (a < b)
  317. return a;
  318. return b;
  319. }
  320. static NOINLINE double my_SQRT(double X)
  321. {
  322. union {
  323. float f;
  324. int32_t i;
  325. } v;
  326. double invsqrt;
  327. double Xhalf = X * 0.5;
  328. /* Fast and good approximation to 1/sqrt(X), black magic */
  329. v.f = X;
  330. /*v.i = 0x5f3759df - (v.i >> 1);*/
  331. v.i = 0x5f375a86 - (v.i >> 1); /* - this constant is slightly better */
  332. invsqrt = v.f; /* better than 0.2% accuracy */
  333. /* Refining it using Newton's method: x1 = x0 - f(x0)/f'(x0)
  334. * f(x) = 1/(x*x) - X (f==0 when x = 1/sqrt(X))
  335. * f'(x) = -2/(x*x*x)
  336. * f(x)/f'(x) = (X - 1/(x*x)) / (2/(x*x*x)) = X*x*x*x/2 - x/2
  337. * x1 = x0 - (X*x0*x0*x0/2 - x0/2) = 1.5*x0 - X*x0*x0*x0/2 = x0*(1.5 - (X/2)*x0*x0)
  338. */
  339. invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); /* ~0.05% accuracy */
  340. /* invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); 2nd iter: ~0.0001% accuracy */
  341. /* With 4 iterations, more than half results will be exact,
  342. * at 6th iterations result stabilizes with about 72% results exact.
  343. * We are well satisfied with 0.05% accuracy.
  344. */
  345. return X * invsqrt; /* X * 1/sqrt(X) ~= sqrt(X) */
  346. }
  347. static ALWAYS_INLINE double SQRT(double X)
  348. {
  349. /* If this arch doesn't use IEEE 754 floats, fall back to using libm */
  350. if (sizeof(float) != 4)
  351. return sqrt(X);
  352. /* This avoids needing libm, saves about 0.5k on x86-32 */
  353. return my_SQRT(X);
  354. }
  355. static double
  356. gettime1900d(void)
  357. {
  358. struct timeval tv;
  359. gettimeofday(&tv, NULL); /* never fails */
  360. G.cur_time = tv.tv_sec + (1.0e-6 * tv.tv_usec) + OFFSET_1900_1970;
  361. return G.cur_time;
  362. }
  363. static void
  364. d_to_tv(double d, struct timeval *tv)
  365. {
  366. tv->tv_sec = (long)d;
  367. tv->tv_usec = (d - tv->tv_sec) * 1000000;
  368. }
  369. static double
  370. lfp_to_d(l_fixedpt_t lfp)
  371. {
  372. double ret;
  373. lfp.int_partl = ntohl(lfp.int_partl);
  374. lfp.fractionl = ntohl(lfp.fractionl);
  375. ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
  376. return ret;
  377. }
  378. static double
  379. sfp_to_d(s_fixedpt_t sfp)
  380. {
  381. double ret;
  382. sfp.int_parts = ntohs(sfp.int_parts);
  383. sfp.fractions = ntohs(sfp.fractions);
  384. ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
  385. return ret;
  386. }
  387. #if ENABLE_FEATURE_NTPD_SERVER
  388. static l_fixedpt_t
  389. d_to_lfp(double d)
  390. {
  391. l_fixedpt_t lfp;
  392. lfp.int_partl = (uint32_t)d;
  393. lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
  394. lfp.int_partl = htonl(lfp.int_partl);
  395. lfp.fractionl = htonl(lfp.fractionl);
  396. return lfp;
  397. }
  398. static s_fixedpt_t
  399. d_to_sfp(double d)
  400. {
  401. s_fixedpt_t sfp;
  402. sfp.int_parts = (uint16_t)d;
  403. sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
  404. sfp.int_parts = htons(sfp.int_parts);
  405. sfp.fractions = htons(sfp.fractions);
  406. return sfp;
  407. }
  408. #endif
  409. static double
  410. dispersion(const datapoint_t *dp)
  411. {
  412. return dp->d_dispersion + FREQ_TOLERANCE * (G.cur_time - dp->d_recv_time);
  413. }
  414. static double
  415. root_distance(peer_t *p)
  416. {
  417. /* The root synchronization distance is the maximum error due to
  418. * all causes of the local clock relative to the primary server.
  419. * It is defined as half the total delay plus total dispersion
  420. * plus peer jitter.
  421. */
  422. return MAXD(MINDISP, p->lastpkt_rootdelay + p->lastpkt_delay) / 2
  423. + p->lastpkt_rootdisp
  424. + p->filter_dispersion
  425. + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time)
  426. + p->filter_jitter;
  427. }
  428. static void
  429. set_next(peer_t *p, unsigned t)
  430. {
  431. p->next_action_time = G.cur_time + t;
  432. }
  433. /*
  434. * Peer clock filter and its helpers
  435. */
  436. static void
  437. filter_datapoints(peer_t *p)
  438. {
  439. int i, idx;
  440. int got_newest;
  441. double minoff, maxoff, wavg, sum, w;
  442. double x = x; /* for compiler */
  443. double oldest_off = oldest_off;
  444. double oldest_age = oldest_age;
  445. double newest_off = newest_off;
  446. double newest_age = newest_age;
  447. minoff = maxoff = p->filter_datapoint[0].d_offset;
  448. for (i = 1; i < NUM_DATAPOINTS; i++) {
  449. if (minoff > p->filter_datapoint[i].d_offset)
  450. minoff = p->filter_datapoint[i].d_offset;
  451. if (maxoff < p->filter_datapoint[i].d_offset)
  452. maxoff = p->filter_datapoint[i].d_offset;
  453. }
  454. idx = p->datapoint_idx; /* most recent datapoint */
  455. /* Average offset:
  456. * Drop two outliers and take weighted average of the rest:
  457. * most_recent/2 + older1/4 + older2/8 ... + older5/32 + older6/32
  458. * we use older6/32, not older6/64 since sum of weights should be 1:
  459. * 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + 1/32 = 1
  460. */
  461. wavg = 0;
  462. w = 0.5;
  463. /* n-1
  464. * --- dispersion(i)
  465. * filter_dispersion = \ -------------
  466. * / (i+1)
  467. * --- 2
  468. * i=0
  469. */
  470. got_newest = 0;
  471. sum = 0;
  472. for (i = 0; i < NUM_DATAPOINTS; i++) {
  473. VERB4 {
  474. bb_error_msg("datapoint[%d]: off:%f disp:%f(%f) age:%f%s",
  475. i,
  476. p->filter_datapoint[idx].d_offset,
  477. p->filter_datapoint[idx].d_dispersion, dispersion(&p->filter_datapoint[idx]),
  478. G.cur_time - p->filter_datapoint[idx].d_recv_time,
  479. (minoff == p->filter_datapoint[idx].d_offset || maxoff == p->filter_datapoint[idx].d_offset)
  480. ? " (outlier by offset)" : ""
  481. );
  482. }
  483. sum += dispersion(&p->filter_datapoint[idx]) / (2 << i);
  484. if (minoff == p->filter_datapoint[idx].d_offset) {
  485. minoff -= 1; /* so that we don't match it ever again */
  486. } else
  487. if (maxoff == p->filter_datapoint[idx].d_offset) {
  488. maxoff += 1;
  489. } else {
  490. oldest_off = p->filter_datapoint[idx].d_offset;
  491. oldest_age = G.cur_time - p->filter_datapoint[idx].d_recv_time;
  492. if (!got_newest) {
  493. got_newest = 1;
  494. newest_off = oldest_off;
  495. newest_age = oldest_age;
  496. }
  497. x = oldest_off * w;
  498. wavg += x;
  499. w /= 2;
  500. }
  501. idx = (idx - 1) & (NUM_DATAPOINTS - 1);
  502. }
  503. p->filter_dispersion = sum;
  504. wavg += x; /* add another older6/64 to form older6/32 */
  505. /* Fix systematic underestimation with large poll intervals.
  506. * Imagine that we still have a bit of uncorrected drift,
  507. * and poll interval is big (say, 100 sec). Offsets form a progression:
  508. * 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 - 0.7 is most recent.
  509. * The algorithm above drops 0.0 and 0.7 as outliers,
  510. * and then we have this estimation, ~25% off from 0.7:
  511. * 0.1/32 + 0.2/32 + 0.3/16 + 0.4/8 + 0.5/4 + 0.6/2 = 0.503125
  512. */
  513. x = oldest_age - newest_age;
  514. if (x != 0) {
  515. x = newest_age / x; /* in above example, 100 / (600 - 100) */
  516. if (x < 1) { /* paranoia check */
  517. x = (newest_off - oldest_off) * x; /* 0.5 * 100/500 = 0.1 */
  518. wavg += x;
  519. }
  520. }
  521. p->filter_offset = wavg;
  522. /* +----- -----+ ^ 1/2
  523. * | n-1 |
  524. * | --- |
  525. * | 1 \ 2 |
  526. * filter_jitter = | --- * / (avg-offset_j) |
  527. * | n --- |
  528. * | j=0 |
  529. * +----- -----+
  530. * where n is the number of valid datapoints in the filter (n > 1);
  531. * if filter_jitter < precision then filter_jitter = precision
  532. */
  533. sum = 0;
  534. for (i = 0; i < NUM_DATAPOINTS; i++) {
  535. sum += SQUARE(wavg - p->filter_datapoint[i].d_offset);
  536. }
  537. sum = SQRT(sum / NUM_DATAPOINTS);
  538. p->filter_jitter = sum > G_precision_sec ? sum : G_precision_sec;
  539. VERB3 bb_error_msg("filter offset:%f(corr:%e) disp:%f jitter:%f",
  540. p->filter_offset, x,
  541. p->filter_dispersion,
  542. p->filter_jitter);
  543. }
  544. static void
  545. reset_peer_stats(peer_t *p, double offset)
  546. {
  547. int i;
  548. bool small_ofs = fabs(offset) < 16 * STEP_THRESHOLD;
  549. for (i = 0; i < NUM_DATAPOINTS; i++) {
  550. if (small_ofs) {
  551. p->filter_datapoint[i].d_recv_time += offset;
  552. if (p->filter_datapoint[i].d_offset != 0) {
  553. p->filter_datapoint[i].d_offset += offset;
  554. }
  555. } else {
  556. p->filter_datapoint[i].d_recv_time = G.cur_time;
  557. p->filter_datapoint[i].d_offset = 0;
  558. p->filter_datapoint[i].d_dispersion = MAXDISP;
  559. }
  560. }
  561. if (small_ofs) {
  562. p->lastpkt_recv_time += offset;
  563. } else {
  564. p->reachable_bits = 0;
  565. p->lastpkt_recv_time = G.cur_time;
  566. }
  567. filter_datapoints(p); /* recalc p->filter_xxx */
  568. VERB5 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
  569. }
  570. static void
  571. add_peers(char *s)
  572. {
  573. peer_t *p;
  574. p = xzalloc(sizeof(*p));
  575. p->p_lsa = xhost2sockaddr(s, 123);
  576. p->p_dotted = xmalloc_sockaddr2dotted_noport(&p->p_lsa->u.sa);
  577. p->p_fd = -1;
  578. p->p_xmt_msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
  579. p->next_action_time = G.cur_time; /* = set_next(p, 0); */
  580. reset_peer_stats(p, 16 * STEP_THRESHOLD);
  581. llist_add_to(&G.ntp_peers, p);
  582. G.peer_cnt++;
  583. }
  584. static int
  585. do_sendto(int fd,
  586. const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
  587. msg_t *msg, ssize_t len)
  588. {
  589. ssize_t ret;
  590. errno = 0;
  591. if (!from) {
  592. ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
  593. } else {
  594. ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
  595. }
  596. if (ret != len) {
  597. bb_perror_msg("send failed");
  598. return -1;
  599. }
  600. return 0;
  601. }
  602. static void
  603. send_query_to_peer(peer_t *p)
  604. {
  605. /* Why do we need to bind()?
  606. * See what happens when we don't bind:
  607. *
  608. * socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
  609. * setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
  610. * gettimeofday({1259071266, 327885}, NULL) = 0
  611. * sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
  612. * ^^^ we sent it from some source port picked by kernel.
  613. * time(NULL) = 1259071266
  614. * write(2, "ntpd: entering poll 15 secs\n", 28) = 28
  615. * poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
  616. * recv(3, "yyy", 68, MSG_DONTWAIT) = 48
  617. * ^^^ this recv will receive packets to any local port!
  618. *
  619. * Uncomment this and use strace to see it in action:
  620. */
  621. #define PROBE_LOCAL_ADDR /* { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); } */
  622. if (p->p_fd == -1) {
  623. int fd, family;
  624. len_and_sockaddr *local_lsa;
  625. family = p->p_lsa->u.sa.sa_family;
  626. p->p_fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
  627. /* local_lsa has "null" address and port 0 now.
  628. * bind() ensures we have a *particular port* selected by kernel
  629. * and remembered in p->p_fd, thus later recv(p->p_fd)
  630. * receives only packets sent to this port.
  631. */
  632. PROBE_LOCAL_ADDR
  633. xbind(fd, &local_lsa->u.sa, local_lsa->len);
  634. PROBE_LOCAL_ADDR
  635. #if ENABLE_FEATURE_IPV6
  636. if (family == AF_INET)
  637. #endif
  638. setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
  639. free(local_lsa);
  640. }
  641. /*
  642. * Send out a random 64-bit number as our transmit time. The NTP
  643. * server will copy said number into the originate field on the
  644. * response that it sends us. This is totally legal per the SNTP spec.
  645. *
  646. * The impact of this is two fold: we no longer send out the current
  647. * system time for the world to see (which may aid an attacker), and
  648. * it gives us a (not very secure) way of knowing that we're not
  649. * getting spoofed by an attacker that can't capture our traffic
  650. * but can spoof packets from the NTP server we're communicating with.
  651. *
  652. * Save the real transmit timestamp locally.
  653. */
  654. p->p_xmt_msg.m_xmttime.int_partl = random();
  655. p->p_xmt_msg.m_xmttime.fractionl = random();
  656. p->p_xmttime = gettime1900d();
  657. if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
  658. &p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
  659. ) {
  660. close(p->p_fd);
  661. p->p_fd = -1;
  662. set_next(p, RETRY_INTERVAL);
  663. return;
  664. }
  665. p->reachable_bits <<= 1;
  666. VERB1 bb_error_msg("sent query to %s", p->p_dotted);
  667. set_next(p, RESPONSE_INTERVAL);
  668. }
  669. /* Note that there is no provision to prevent several run_scripts
  670. * to be done in quick succession. In fact, it happens rather often
  671. * if initial syncronization results in a step.
  672. * You will see "step" and then "stratum" script runs, sometimes
  673. * as close as only 0.002 seconds apart.
  674. * Script should be ready to deal with this.
  675. */
  676. static void run_script(const char *action, double offset)
  677. {
  678. char *argv[3];
  679. char *env1, *env2, *env3, *env4;
  680. if (!G.script_name)
  681. return;
  682. argv[0] = (char*) G.script_name;
  683. argv[1] = (char*) action;
  684. argv[2] = NULL;
  685. VERB1 bb_error_msg("executing '%s %s'", G.script_name, action);
  686. env1 = xasprintf("%s=%u", "stratum", G.stratum);
  687. putenv(env1);
  688. env2 = xasprintf("%s=%ld", "freq_drift_ppm", G.kernel_freq_drift);
  689. putenv(env2);
  690. env3 = xasprintf("%s=%u", "poll_interval", 1 << G.poll_exp);
  691. putenv(env3);
  692. env4 = xasprintf("%s=%f", "offset", offset);
  693. putenv(env4);
  694. /* Other items of potential interest: selected peer,
  695. * rootdelay, reftime, rootdisp, refid, ntp_status,
  696. * last_update_offset, last_update_recv_time, discipline_jitter,
  697. * how many peers have reachable_bits = 0?
  698. */
  699. /* Don't want to wait: it may run hwclock --systohc, and that
  700. * may take some time (seconds): */
  701. /*spawn_and_wait(argv);*/
  702. spawn(argv);
  703. unsetenv("stratum");
  704. unsetenv("freq_drift_ppm");
  705. unsetenv("poll_interval");
  706. unsetenv("offset");
  707. free(env1);
  708. free(env2);
  709. free(env3);
  710. free(env4);
  711. G.last_script_run = G.cur_time;
  712. }
  713. static NOINLINE void
  714. step_time(double offset)
  715. {
  716. llist_t *item;
  717. double dtime;
  718. struct timeval tv;
  719. char buf[80];
  720. time_t tval;
  721. gettimeofday(&tv, NULL); /* never fails */
  722. dtime = offset + tv.tv_sec;
  723. dtime += 1.0e-6 * tv.tv_usec;
  724. d_to_tv(dtime, &tv);
  725. if (settimeofday(&tv, NULL) == -1)
  726. bb_perror_msg_and_die("settimeofday");
  727. tval = tv.tv_sec;
  728. strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
  729. bb_error_msg("setting clock to %s (offset %fs)", buf, offset);
  730. /* Correct various fields which contain time-relative values: */
  731. /* p->lastpkt_recv_time, p->next_action_time and such: */
  732. for (item = G.ntp_peers; item != NULL; item = item->link) {
  733. peer_t *pp = (peer_t *) item->data;
  734. reset_peer_stats(pp, offset);
  735. //bb_error_msg("offset:%f pp->next_action_time:%f -> %f",
  736. // offset, pp->next_action_time, pp->next_action_time + offset);
  737. pp->next_action_time += offset;
  738. }
  739. /* Globals: */
  740. G.cur_time += offset;
  741. G.last_update_recv_time += offset;
  742. G.last_script_run += offset;
  743. }
  744. /*
  745. * Selection and clustering, and their helpers
  746. */
  747. typedef struct {
  748. peer_t *p;
  749. int type;
  750. double edge;
  751. double opt_rd; /* optimization */
  752. } point_t;
  753. static int
  754. compare_point_edge(const void *aa, const void *bb)
  755. {
  756. const point_t *a = aa;
  757. const point_t *b = bb;
  758. if (a->edge < b->edge) {
  759. return -1;
  760. }
  761. return (a->edge > b->edge);
  762. }
  763. typedef struct {
  764. peer_t *p;
  765. double metric;
  766. } survivor_t;
  767. static int
  768. compare_survivor_metric(const void *aa, const void *bb)
  769. {
  770. const survivor_t *a = aa;
  771. const survivor_t *b = bb;
  772. if (a->metric < b->metric) {
  773. return -1;
  774. }
  775. return (a->metric > b->metric);
  776. }
  777. static int
  778. fit(peer_t *p, double rd)
  779. {
  780. if ((p->reachable_bits & (p->reachable_bits-1)) == 0) {
  781. /* One or zero bits in reachable_bits */
  782. VERB3 bb_error_msg("peer %s unfit for selection: unreachable", p->p_dotted);
  783. return 0;
  784. }
  785. #if 0 /* we filter out such packets earlier */
  786. if ((p->lastpkt_status & LI_ALARM) == LI_ALARM
  787. || p->lastpkt_stratum >= MAXSTRAT
  788. ) {
  789. VERB3 bb_error_msg("peer %s unfit for selection: bad status/stratum", p->p_dotted);
  790. return 0;
  791. }
  792. #endif
  793. /* rd is root_distance(p) */
  794. if (rd > MAXDIST + FREQ_TOLERANCE * (1 << G.poll_exp)) {
  795. VERB3 bb_error_msg("peer %s unfit for selection: root distance too high", p->p_dotted);
  796. return 0;
  797. }
  798. //TODO
  799. // /* Do we have a loop? */
  800. // if (p->refid == p->dstaddr || p->refid == s.refid)
  801. // return 0;
  802. return 1;
  803. }
  804. static peer_t*
  805. select_and_cluster(void)
  806. {
  807. peer_t *p;
  808. llist_t *item;
  809. int i, j;
  810. int size = 3 * G.peer_cnt;
  811. /* for selection algorithm */
  812. point_t point[size];
  813. unsigned num_points, num_candidates;
  814. double low, high;
  815. unsigned num_falsetickers;
  816. /* for cluster algorithm */
  817. survivor_t survivor[size];
  818. unsigned num_survivors;
  819. /* Selection */
  820. num_points = 0;
  821. item = G.ntp_peers;
  822. if (G.initial_poll_complete) while (item != NULL) {
  823. double rd, offset;
  824. p = (peer_t *) item->data;
  825. rd = root_distance(p);
  826. offset = p->filter_offset;
  827. if (!fit(p, rd)) {
  828. item = item->link;
  829. continue;
  830. }
  831. VERB4 bb_error_msg("interval: [%f %f %f] %s",
  832. offset - rd,
  833. offset,
  834. offset + rd,
  835. p->p_dotted
  836. );
  837. point[num_points].p = p;
  838. point[num_points].type = -1;
  839. point[num_points].edge = offset - rd;
  840. point[num_points].opt_rd = rd;
  841. num_points++;
  842. point[num_points].p = p;
  843. point[num_points].type = 0;
  844. point[num_points].edge = offset;
  845. point[num_points].opt_rd = rd;
  846. num_points++;
  847. point[num_points].p = p;
  848. point[num_points].type = 1;
  849. point[num_points].edge = offset + rd;
  850. point[num_points].opt_rd = rd;
  851. num_points++;
  852. item = item->link;
  853. }
  854. num_candidates = num_points / 3;
  855. if (num_candidates == 0) {
  856. VERB3 bb_error_msg("no valid datapoints, no peer selected");
  857. return NULL;
  858. }
  859. //TODO: sorting does not seem to be done in reference code
  860. qsort(point, num_points, sizeof(point[0]), compare_point_edge);
  861. /* Start with the assumption that there are no falsetickers.
  862. * Attempt to find a nonempty intersection interval containing
  863. * the midpoints of all truechimers.
  864. * If a nonempty interval cannot be found, increase the number
  865. * of assumed falsetickers by one and try again.
  866. * If a nonempty interval is found and the number of falsetickers
  867. * is less than the number of truechimers, a majority has been found
  868. * and the midpoint of each truechimer represents
  869. * the candidates available to the cluster algorithm.
  870. */
  871. num_falsetickers = 0;
  872. while (1) {
  873. int c;
  874. unsigned num_midpoints = 0;
  875. low = 1 << 9;
  876. high = - (1 << 9);
  877. c = 0;
  878. for (i = 0; i < num_points; i++) {
  879. /* We want to do:
  880. * if (point[i].type == -1) c++;
  881. * if (point[i].type == 1) c--;
  882. * and it's simpler to do it this way:
  883. */
  884. c -= point[i].type;
  885. if (c >= num_candidates - num_falsetickers) {
  886. /* If it was c++ and it got big enough... */
  887. low = point[i].edge;
  888. break;
  889. }
  890. if (point[i].type == 0)
  891. num_midpoints++;
  892. }
  893. c = 0;
  894. for (i = num_points-1; i >= 0; i--) {
  895. c += point[i].type;
  896. if (c >= num_candidates - num_falsetickers) {
  897. high = point[i].edge;
  898. break;
  899. }
  900. if (point[i].type == 0)
  901. num_midpoints++;
  902. }
  903. /* If the number of midpoints is greater than the number
  904. * of allowed falsetickers, the intersection contains at
  905. * least one truechimer with no midpoint - bad.
  906. * Also, interval should be nonempty.
  907. */
  908. if (num_midpoints <= num_falsetickers && low < high)
  909. break;
  910. num_falsetickers++;
  911. if (num_falsetickers * 2 >= num_candidates) {
  912. VERB3 bb_error_msg("too many falsetickers:%d (candidates:%d), no peer selected",
  913. num_falsetickers, num_candidates);
  914. return NULL;
  915. }
  916. }
  917. VERB3 bb_error_msg("selected interval: [%f, %f]; candidates:%d falsetickers:%d",
  918. low, high, num_candidates, num_falsetickers);
  919. /* Clustering */
  920. /* Construct a list of survivors (p, metric)
  921. * from the chime list, where metric is dominated
  922. * first by stratum and then by root distance.
  923. * All other things being equal, this is the order of preference.
  924. */
  925. num_survivors = 0;
  926. for (i = 0; i < num_points; i++) {
  927. if (point[i].edge < low || point[i].edge > high)
  928. continue;
  929. p = point[i].p;
  930. survivor[num_survivors].p = p;
  931. /* x.opt_rd == root_distance(p); */
  932. survivor[num_survivors].metric = MAXDIST * p->lastpkt_stratum + point[i].opt_rd;
  933. VERB4 bb_error_msg("survivor[%d] metric:%f peer:%s",
  934. num_survivors, survivor[num_survivors].metric, p->p_dotted);
  935. num_survivors++;
  936. }
  937. /* There must be at least MIN_SELECTED survivors to satisfy the
  938. * correctness assertions. Ordinarily, the Byzantine criteria
  939. * require four survivors, but for the demonstration here, one
  940. * is acceptable.
  941. */
  942. if (num_survivors < MIN_SELECTED) {
  943. VERB3 bb_error_msg("num_survivors %d < %d, no peer selected",
  944. num_survivors, MIN_SELECTED);
  945. return NULL;
  946. }
  947. //looks like this is ONLY used by the fact that later we pick survivor[0].
  948. //we can avoid sorting then, just find the minimum once!
  949. qsort(survivor, num_survivors, sizeof(survivor[0]), compare_survivor_metric);
  950. /* For each association p in turn, calculate the selection
  951. * jitter p->sjitter as the square root of the sum of squares
  952. * (p->offset - q->offset) over all q associations. The idea is
  953. * to repeatedly discard the survivor with maximum selection
  954. * jitter until a termination condition is met.
  955. */
  956. while (1) {
  957. unsigned max_idx = max_idx;
  958. double max_selection_jitter = max_selection_jitter;
  959. double min_jitter = min_jitter;
  960. if (num_survivors <= MIN_CLUSTERED) {
  961. VERB3 bb_error_msg("num_survivors %d <= %d, not discarding more",
  962. num_survivors, MIN_CLUSTERED);
  963. break;
  964. }
  965. /* To make sure a few survivors are left
  966. * for the clustering algorithm to chew on,
  967. * we stop if the number of survivors
  968. * is less than or equal to MIN_CLUSTERED (3).
  969. */
  970. for (i = 0; i < num_survivors; i++) {
  971. double selection_jitter_sq;
  972. p = survivor[i].p;
  973. if (i == 0 || p->filter_jitter < min_jitter)
  974. min_jitter = p->filter_jitter;
  975. selection_jitter_sq = 0;
  976. for (j = 0; j < num_survivors; j++) {
  977. peer_t *q = survivor[j].p;
  978. selection_jitter_sq += SQUARE(p->filter_offset - q->filter_offset);
  979. }
  980. if (i == 0 || selection_jitter_sq > max_selection_jitter) {
  981. max_selection_jitter = selection_jitter_sq;
  982. max_idx = i;
  983. }
  984. VERB5 bb_error_msg("survivor %d selection_jitter^2:%f",
  985. i, selection_jitter_sq);
  986. }
  987. max_selection_jitter = SQRT(max_selection_jitter / num_survivors);
  988. VERB4 bb_error_msg("max_selection_jitter (at %d):%f min_jitter:%f",
  989. max_idx, max_selection_jitter, min_jitter);
  990. /* If the maximum selection jitter is less than the
  991. * minimum peer jitter, then tossing out more survivors
  992. * will not lower the minimum peer jitter, so we might
  993. * as well stop.
  994. */
  995. if (max_selection_jitter < min_jitter) {
  996. VERB3 bb_error_msg("max_selection_jitter:%f < min_jitter:%f, num_survivors:%d, not discarding more",
  997. max_selection_jitter, min_jitter, num_survivors);
  998. break;
  999. }
  1000. /* Delete survivor[max_idx] from the list
  1001. * and go around again.
  1002. */
  1003. VERB5 bb_error_msg("dropping survivor %d", max_idx);
  1004. num_survivors--;
  1005. while (max_idx < num_survivors) {
  1006. survivor[max_idx] = survivor[max_idx + 1];
  1007. max_idx++;
  1008. }
  1009. }
  1010. if (0) {
  1011. /* Combine the offsets of the clustering algorithm survivors
  1012. * using a weighted average with weight determined by the root
  1013. * distance. Compute the selection jitter as the weighted RMS
  1014. * difference between the first survivor and the remaining
  1015. * survivors. In some cases the inherent clock jitter can be
  1016. * reduced by not using this algorithm, especially when frequent
  1017. * clockhopping is involved. bbox: thus we don't do it.
  1018. */
  1019. double x, y, z, w;
  1020. y = z = w = 0;
  1021. for (i = 0; i < num_survivors; i++) {
  1022. p = survivor[i].p;
  1023. x = root_distance(p);
  1024. y += 1 / x;
  1025. z += p->filter_offset / x;
  1026. w += SQUARE(p->filter_offset - survivor[0].p->filter_offset) / x;
  1027. }
  1028. //G.cluster_offset = z / y;
  1029. //G.cluster_jitter = SQRT(w / y);
  1030. }
  1031. /* Pick the best clock. If the old system peer is on the list
  1032. * and at the same stratum as the first survivor on the list,
  1033. * then don't do a clock hop. Otherwise, select the first
  1034. * survivor on the list as the new system peer.
  1035. */
  1036. p = survivor[0].p;
  1037. if (G.last_update_peer
  1038. && G.last_update_peer->lastpkt_stratum <= p->lastpkt_stratum
  1039. ) {
  1040. /* Starting from 1 is ok here */
  1041. for (i = 1; i < num_survivors; i++) {
  1042. if (G.last_update_peer == survivor[i].p) {
  1043. VERB4 bb_error_msg("keeping old synced peer");
  1044. p = G.last_update_peer;
  1045. goto keep_old;
  1046. }
  1047. }
  1048. }
  1049. G.last_update_peer = p;
  1050. keep_old:
  1051. VERB3 bb_error_msg("selected peer %s filter_offset:%f age:%f",
  1052. p->p_dotted,
  1053. p->filter_offset,
  1054. G.cur_time - p->lastpkt_recv_time
  1055. );
  1056. return p;
  1057. }
  1058. /*
  1059. * Local clock discipline and its helpers
  1060. */
  1061. static void
  1062. set_new_values(int disc_state, double offset, double recv_time)
  1063. {
  1064. /* Enter new state and set state variables. Note we use the time
  1065. * of the last clock filter sample, which must be earlier than
  1066. * the current time.
  1067. */
  1068. VERB3 bb_error_msg("disc_state=%d last update offset=%f recv_time=%f",
  1069. disc_state, offset, recv_time);
  1070. G.discipline_state = disc_state;
  1071. G.last_update_offset = offset;
  1072. G.last_update_recv_time = recv_time;
  1073. }
  1074. /* Return: -1: decrease poll interval, 0: leave as is, 1: increase */
  1075. static NOINLINE int
  1076. update_local_clock(peer_t *p)
  1077. {
  1078. int rc;
  1079. struct timex tmx;
  1080. /* Note: can use G.cluster_offset instead: */
  1081. double offset = p->filter_offset;
  1082. double recv_time = p->lastpkt_recv_time;
  1083. double abs_offset;
  1084. #if !USING_KERNEL_PLL_LOOP
  1085. double freq_drift;
  1086. #endif
  1087. double since_last_update;
  1088. double etemp, dtemp;
  1089. abs_offset = fabs(offset);
  1090. #if 0
  1091. /* If needed, -S script can do it by looking at $offset
  1092. * env var and killing parent */
  1093. /* If the offset is too large, give up and go home */
  1094. if (abs_offset > PANIC_THRESHOLD) {
  1095. bb_error_msg_and_die("offset %f far too big, exiting", offset);
  1096. }
  1097. #endif
  1098. /* If this is an old update, for instance as the result
  1099. * of a system peer change, avoid it. We never use
  1100. * an old sample or the same sample twice.
  1101. */
  1102. if (recv_time <= G.last_update_recv_time) {
  1103. VERB3 bb_error_msg("same or older datapoint: %f >= %f, not using it",
  1104. G.last_update_recv_time, recv_time);
  1105. return 0; /* "leave poll interval as is" */
  1106. }
  1107. /* Clock state machine transition function. This is where the
  1108. * action is and defines how the system reacts to large time
  1109. * and frequency errors.
  1110. */
  1111. since_last_update = recv_time - G.reftime;
  1112. #if !USING_KERNEL_PLL_LOOP
  1113. freq_drift = 0;
  1114. #endif
  1115. #if USING_INITIAL_FREQ_ESTIMATION
  1116. if (G.discipline_state == STATE_FREQ) {
  1117. /* Ignore updates until the stepout threshold */
  1118. if (since_last_update < WATCH_THRESHOLD) {
  1119. VERB3 bb_error_msg("measuring drift, datapoint ignored, %f sec remains",
  1120. WATCH_THRESHOLD - since_last_update);
  1121. return 0; /* "leave poll interval as is" */
  1122. }
  1123. # if !USING_KERNEL_PLL_LOOP
  1124. freq_drift = (offset - G.last_update_offset) / since_last_update;
  1125. # endif
  1126. }
  1127. #endif
  1128. /* There are two main regimes: when the
  1129. * offset exceeds the step threshold and when it does not.
  1130. */
  1131. if (abs_offset > STEP_THRESHOLD) {
  1132. switch (G.discipline_state) {
  1133. case STATE_SYNC:
  1134. /* The first outlyer: ignore it, switch to SPIK state */
  1135. VERB3 bb_error_msg("offset:%f - spike detected", offset);
  1136. G.discipline_state = STATE_SPIK;
  1137. return -1; /* "decrease poll interval" */
  1138. case STATE_SPIK:
  1139. /* Ignore succeeding outlyers until either an inlyer
  1140. * is found or the stepout threshold is exceeded.
  1141. */
  1142. if (since_last_update < WATCH_THRESHOLD) {
  1143. VERB3 bb_error_msg("spike detected, datapoint ignored, %f sec remains",
  1144. WATCH_THRESHOLD - since_last_update);
  1145. return -1; /* "decrease poll interval" */
  1146. }
  1147. /* fall through: we need to step */
  1148. } /* switch */
  1149. /* Step the time and clamp down the poll interval.
  1150. *
  1151. * In NSET state an initial frequency correction is
  1152. * not available, usually because the frequency file has
  1153. * not yet been written. Since the time is outside the
  1154. * capture range, the clock is stepped. The frequency
  1155. * will be set directly following the stepout interval.
  1156. *
  1157. * In FSET state the initial frequency has been set
  1158. * from the frequency file. Since the time is outside
  1159. * the capture range, the clock is stepped immediately,
  1160. * rather than after the stepout interval. Guys get
  1161. * nervous if it takes 17 minutes to set the clock for
  1162. * the first time.
  1163. *
  1164. * In SPIK state the stepout threshold has expired and
  1165. * the phase is still above the step threshold. Note
  1166. * that a single spike greater than the step threshold
  1167. * is always suppressed, even at the longer poll
  1168. * intervals.
  1169. */
  1170. VERB3 bb_error_msg("stepping time by %f; poll_exp=MINPOLL", offset);
  1171. step_time(offset);
  1172. if (option_mask32 & OPT_q) {
  1173. /* We were only asked to set time once. Done. */
  1174. exit(0);
  1175. }
  1176. G.polladj_count = 0;
  1177. G.poll_exp = MINPOLL;
  1178. G.stratum = MAXSTRAT;
  1179. run_script("step", offset);
  1180. #if USING_INITIAL_FREQ_ESTIMATION
  1181. if (G.discipline_state == STATE_NSET) {
  1182. set_new_values(STATE_FREQ, /*offset:*/ 0, recv_time);
  1183. return 1; /* "ok to increase poll interval" */
  1184. }
  1185. #endif
  1186. set_new_values(STATE_SYNC, /*offset:*/ 0, recv_time);
  1187. } else { /* abs_offset <= STEP_THRESHOLD */
  1188. if (G.poll_exp < MINPOLL && G.initial_poll_complete) {
  1189. VERB3 bb_error_msg("small offset:%f, disabling burst mode", offset);
  1190. G.polladj_count = 0;
  1191. G.poll_exp = MINPOLL;
  1192. }
  1193. /* Compute the clock jitter as the RMS of exponentially
  1194. * weighted offset differences. Used by the poll adjust code.
  1195. */
  1196. etemp = SQUARE(G.discipline_jitter);
  1197. dtemp = SQUARE(MAXD(fabs(offset - G.last_update_offset), G_precision_sec));
  1198. G.discipline_jitter = SQRT(etemp + (dtemp - etemp) / AVG);
  1199. VERB3 bb_error_msg("discipline jitter=%f", G.discipline_jitter);
  1200. switch (G.discipline_state) {
  1201. case STATE_NSET:
  1202. if (option_mask32 & OPT_q) {
  1203. /* We were only asked to set time once.
  1204. * The clock is precise enough, no need to step.
  1205. */
  1206. exit(0);
  1207. }
  1208. #if USING_INITIAL_FREQ_ESTIMATION
  1209. /* This is the first update received and the frequency
  1210. * has not been initialized. The first thing to do
  1211. * is directly measure the oscillator frequency.
  1212. */
  1213. set_new_values(STATE_FREQ, offset, recv_time);
  1214. #else
  1215. set_new_values(STATE_SYNC, offset, recv_time);
  1216. #endif
  1217. VERB3 bb_error_msg("transitioning to FREQ, datapoint ignored");
  1218. return 0; /* "leave poll interval as is" */
  1219. #if 0 /* this is dead code for now */
  1220. case STATE_FSET:
  1221. /* This is the first update and the frequency
  1222. * has been initialized. Adjust the phase, but
  1223. * don't adjust the frequency until the next update.
  1224. */
  1225. set_new_values(STATE_SYNC, offset, recv_time);
  1226. /* freq_drift remains 0 */
  1227. break;
  1228. #endif
  1229. #if USING_INITIAL_FREQ_ESTIMATION
  1230. case STATE_FREQ:
  1231. /* since_last_update >= WATCH_THRESHOLD, we waited enough.
  1232. * Correct the phase and frequency and switch to SYNC state.
  1233. * freq_drift was already estimated (see code above)
  1234. */
  1235. set_new_values(STATE_SYNC, offset, recv_time);
  1236. break;
  1237. #endif
  1238. default:
  1239. #if !USING_KERNEL_PLL_LOOP
  1240. /* Compute freq_drift due to PLL and FLL contributions.
  1241. *
  1242. * The FLL and PLL frequency gain constants
  1243. * depend on the poll interval and Allan
  1244. * intercept. The FLL is not used below one-half
  1245. * the Allan intercept. Above that the loop gain
  1246. * increases in steps to 1 / AVG.
  1247. */
  1248. if ((1 << G.poll_exp) > ALLAN / 2) {
  1249. etemp = FLL - G.poll_exp;
  1250. if (etemp < AVG)
  1251. etemp = AVG;
  1252. freq_drift += (offset - G.last_update_offset) / (MAXD(since_last_update, ALLAN) * etemp);
  1253. }
  1254. /* For the PLL the integration interval
  1255. * (numerator) is the minimum of the update
  1256. * interval and poll interval. This allows
  1257. * oversampling, but not undersampling.
  1258. */
  1259. etemp = MIND(since_last_update, (1 << G.poll_exp));
  1260. dtemp = (4 * PLL) << G.poll_exp;
  1261. freq_drift += offset * etemp / SQUARE(dtemp);
  1262. #endif
  1263. set_new_values(STATE_SYNC, offset, recv_time);
  1264. break;
  1265. }
  1266. if (G.stratum != p->lastpkt_stratum + 1) {
  1267. G.stratum = p->lastpkt_stratum + 1;
  1268. run_script("stratum", offset);
  1269. }
  1270. }
  1271. G.reftime = G.cur_time;
  1272. G.ntp_status = p->lastpkt_status;
  1273. G.refid = p->lastpkt_refid;
  1274. G.rootdelay = p->lastpkt_rootdelay + p->lastpkt_delay;
  1275. dtemp = p->filter_jitter; // SQRT(SQUARE(p->filter_jitter) + SQUARE(G.cluster_jitter));
  1276. dtemp += MAXD(p->filter_dispersion + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time) + abs_offset, MINDISP);
  1277. G.rootdisp = p->lastpkt_rootdisp + dtemp;
  1278. VERB3 bb_error_msg("updating leap/refid/reftime/rootdisp from peer %s", p->p_dotted);
  1279. /* We are in STATE_SYNC now, but did not do adjtimex yet.
  1280. * (Any other state does not reach this, they all return earlier)
  1281. * By this time, freq_drift and G.last_update_offset are set
  1282. * to values suitable for adjtimex.
  1283. */
  1284. #if !USING_KERNEL_PLL_LOOP
  1285. /* Calculate the new frequency drift and frequency stability (wander).
  1286. * Compute the clock wander as the RMS of exponentially weighted
  1287. * frequency differences. This is not used directly, but can,
  1288. * along with the jitter, be a highly useful monitoring and
  1289. * debugging tool.
  1290. */
  1291. dtemp = G.discipline_freq_drift + freq_drift;
  1292. G.discipline_freq_drift = MAXD(MIND(MAXDRIFT, dtemp), -MAXDRIFT);
  1293. etemp = SQUARE(G.discipline_wander);
  1294. dtemp = SQUARE(dtemp);
  1295. G.discipline_wander = SQRT(etemp + (dtemp - etemp) / AVG);
  1296. VERB3 bb_error_msg("discipline freq_drift=%.9f(int:%ld corr:%e) wander=%f",
  1297. G.discipline_freq_drift,
  1298. (long)(G.discipline_freq_drift * 65536e6),
  1299. freq_drift,
  1300. G.discipline_wander);
  1301. #endif
  1302. VERB3 {
  1303. memset(&tmx, 0, sizeof(tmx));
  1304. if (adjtimex(&tmx) < 0)
  1305. bb_perror_msg_and_die("adjtimex");
  1306. VERB3 bb_error_msg("p adjtimex freq:%ld offset:%ld constant:%ld status:0x%x",
  1307. tmx.freq, tmx.offset, tmx.constant, tmx.status);
  1308. }
  1309. memset(&tmx, 0, sizeof(tmx));
  1310. #if 0
  1311. //doesn't work, offset remains 0 (!) in kernel:
  1312. //ntpd: set adjtimex freq:1786097 tmx.offset:77487
  1313. //ntpd: prev adjtimex freq:1786097 tmx.offset:0
  1314. //ntpd: cur adjtimex freq:1786097 tmx.offset:0
  1315. tmx.modes = ADJ_FREQUENCY | ADJ_OFFSET;
  1316. /* 65536 is one ppm */
  1317. tmx.freq = G.discipline_freq_drift * 65536e6;
  1318. tmx.offset = G.last_update_offset * 1000000; /* usec */
  1319. #endif
  1320. tmx.modes = ADJ_OFFSET | ADJ_STATUS | ADJ_TIMECONST;// | ADJ_MAXERROR | ADJ_ESTERROR;
  1321. tmx.offset = (G.last_update_offset * 1000000); /* usec */
  1322. /* + (G.last_update_offset < 0 ? -0.5 : 0.5) - too small to bother */
  1323. tmx.status = STA_PLL;
  1324. if (G.ntp_status & LI_PLUSSEC)
  1325. tmx.status |= STA_INS;
  1326. if (G.ntp_status & LI_MINUSSEC)
  1327. tmx.status |= STA_DEL;
  1328. tmx.constant = G.poll_exp - 4;
  1329. //tmx.esterror = (u_int32)(clock_jitter * 1e6);
  1330. //tmx.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
  1331. rc = adjtimex(&tmx);
  1332. if (rc < 0)
  1333. bb_perror_msg_and_die("adjtimex");
  1334. /* NB: here kernel returns constant == G.poll_exp, not == G.poll_exp - 4.
  1335. * Not sure why. Perhaps it is normal.
  1336. */
  1337. VERB3 bb_error_msg("adjtimex:%d freq:%ld offset:%ld constant:%ld status:0x%x",
  1338. rc, tmx.freq, tmx.offset, tmx.constant, tmx.status);
  1339. #if 0
  1340. VERB3 {
  1341. /* always gives the same output as above msg */
  1342. memset(&tmx, 0, sizeof(tmx));
  1343. if (adjtimex(&tmx) < 0)
  1344. bb_perror_msg_and_die("adjtimex");
  1345. VERB3 bb_error_msg("c adjtimex freq:%ld offset:%ld constant:%ld status:0x%x",
  1346. tmx.freq, tmx.offset, tmx.constant, tmx.status);
  1347. }
  1348. #endif
  1349. G.kernel_freq_drift = tmx.freq / 65536;
  1350. VERB2 bb_error_msg("update peer:%s, offset:%f, clock drift:%ld ppm",
  1351. p->p_dotted, G.last_update_offset, G.kernel_freq_drift);
  1352. return 1; /* "ok to increase poll interval" */
  1353. }
  1354. /*
  1355. * We've got a new reply packet from a peer, process it
  1356. * (helpers first)
  1357. */
  1358. static unsigned
  1359. retry_interval(void)
  1360. {
  1361. /* Local problem, want to retry soon */
  1362. unsigned interval, r;
  1363. interval = RETRY_INTERVAL;
  1364. r = random();
  1365. interval += r % (unsigned)(RETRY_INTERVAL / 4);
  1366. VERB3 bb_error_msg("chose retry interval:%u", interval);
  1367. return interval;
  1368. }
  1369. static unsigned
  1370. poll_interval(int exponent)
  1371. {
  1372. unsigned interval, r;
  1373. exponent = G.poll_exp + exponent;
  1374. if (exponent < 0)
  1375. exponent = 0;
  1376. interval = 1 << exponent;
  1377. r = random();
  1378. interval += ((r & (interval-1)) >> 4) + ((r >> 8) & 1); /* + 1/16 of interval, max */
  1379. VERB3 bb_error_msg("chose poll interval:%u (poll_exp:%d exp:%d)", interval, G.poll_exp, exponent);
  1380. return interval;
  1381. }
  1382. static NOINLINE void
  1383. recv_and_process_peer_pkt(peer_t *p)
  1384. {
  1385. int rc;
  1386. ssize_t size;
  1387. msg_t msg;
  1388. double T1, T2, T3, T4;
  1389. unsigned interval;
  1390. datapoint_t *datapoint;
  1391. peer_t *q;
  1392. /* We can recvfrom here and check from.IP, but some multihomed
  1393. * ntp servers reply from their *other IP*.
  1394. * TODO: maybe we should check at least what we can: from.port == 123?
  1395. */
  1396. size = recv(p->p_fd, &msg, sizeof(msg), MSG_DONTWAIT);
  1397. if (size == -1) {
  1398. bb_perror_msg("recv(%s) error", p->p_dotted);
  1399. if (errno == EHOSTUNREACH || errno == EHOSTDOWN
  1400. || errno == ENETUNREACH || errno == ENETDOWN
  1401. || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
  1402. || errno == EAGAIN
  1403. ) {
  1404. //TODO: always do this?
  1405. interval = retry_interval();
  1406. goto set_next_and_close_sock;
  1407. }
  1408. xfunc_die();
  1409. }
  1410. if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
  1411. bb_error_msg("malformed packet received from %s", p->p_dotted);
  1412. goto bail;
  1413. }
  1414. if (msg.m_orgtime.int_partl != p->p_xmt_msg.m_xmttime.int_partl
  1415. || msg.m_orgtime.fractionl != p->p_xmt_msg.m_xmttime.fractionl
  1416. ) {
  1417. goto bail;
  1418. }
  1419. if ((msg.m_status & LI_ALARM) == LI_ALARM
  1420. || msg.m_stratum == 0
  1421. || msg.m_stratum > NTP_MAXSTRATUM
  1422. ) {
  1423. // TODO: stratum 0 responses may have commands in 32-bit m_refid field:
  1424. // "DENY", "RSTR" - peer does not like us at all
  1425. // "RATE" - peer is overloaded, reduce polling freq
  1426. interval = poll_interval(0);
  1427. bb_error_msg("reply from %s: not synced, next query in %us", p->p_dotted, interval);
  1428. goto set_next_and_close_sock;
  1429. }
  1430. // /* Verify valid root distance */
  1431. // if (msg.m_rootdelay / 2 + msg.m_rootdisp >= MAXDISP || p->lastpkt_reftime > msg.m_xmt)
  1432. // return; /* invalid header values */
  1433. p->lastpkt_status = msg.m_status;
  1434. p->lastpkt_stratum = msg.m_stratum;
  1435. p->lastpkt_rootdelay = sfp_to_d(msg.m_rootdelay);
  1436. p->lastpkt_rootdisp = sfp_to_d(msg.m_rootdisp);
  1437. p->lastpkt_refid = msg.m_refid;
  1438. /*
  1439. * From RFC 2030 (with a correction to the delay math):
  1440. *
  1441. * Timestamp Name ID When Generated
  1442. * ------------------------------------------------------------
  1443. * Originate Timestamp T1 time request sent by client
  1444. * Receive Timestamp T2 time request received by server
  1445. * Transmit Timestamp T3 time reply sent by server
  1446. * Destination Timestamp T4 time reply received by client
  1447. *
  1448. * The roundtrip delay and local clock offset are defined as
  1449. *
  1450. * delay = (T4 - T1) - (T3 - T2); offset = ((T2 - T1) + (T3 - T4)) / 2
  1451. */
  1452. T1 = p->p_xmttime;
  1453. T2 = lfp_to_d(msg.m_rectime);
  1454. T3 = lfp_to_d(msg.m_xmttime);
  1455. T4 = G.cur_time;
  1456. p->lastpkt_recv_time = T4;
  1457. VERB5 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
  1458. p->datapoint_idx = p->reachable_bits ? (p->datapoint_idx + 1) % NUM_DATAPOINTS : 0;
  1459. datapoint = &p->filter_datapoint[p->datapoint_idx];
  1460. datapoint->d_recv_time = T4;
  1461. datapoint->d_offset = ((T2 - T1) + (T3 - T4)) / 2;
  1462. /* The delay calculation is a special case. In cases where the
  1463. * server and client clocks are running at different rates and
  1464. * with very fast networks, the delay can appear negative. In
  1465. * order to avoid violating the Principle of Least Astonishment,
  1466. * the delay is clamped not less than the system precision.
  1467. */
  1468. p->lastpkt_delay = (T4 - T1) - (T3 - T2);
  1469. if (p->lastpkt_delay < G_precision_sec)
  1470. p->lastpkt_delay = G_precision_sec;
  1471. datapoint->d_dispersion = LOG2D(msg.m_precision_exp) + G_precision_sec;
  1472. if (!p->reachable_bits) {
  1473. /* 1st datapoint ever - replicate offset in every element */
  1474. int i;
  1475. for (i = 1; i < NUM_DATAPOINTS; i++) {
  1476. p->filter_datapoint[i].d_offset = datapoint->d_offset;
  1477. }
  1478. }
  1479. p->reachable_bits |= 1;
  1480. if ((MAX_VERBOSE && G.verbose) || (option_mask32 & OPT_w)) {
  1481. bb_error_msg("reply from %s: reach 0x%02x offset %f delay %f status 0x%02x strat %d refid 0x%08x rootdelay %f",
  1482. p->p_dotted,
  1483. p->reachable_bits,
  1484. datapoint->d_offset,
  1485. p->lastpkt_delay,
  1486. p->lastpkt_status,
  1487. p->lastpkt_stratum,
  1488. p->lastpkt_refid,
  1489. p->lastpkt_rootdelay
  1490. /* not shown: m_ppoll, m_precision_exp, m_rootdisp,
  1491. * m_reftime, m_orgtime, m_rectime, m_xmttime
  1492. */
  1493. );
  1494. }
  1495. /* Muck with statictics and update the clock */
  1496. filter_datapoints(p);
  1497. q = select_and_cluster();
  1498. rc = -1;
  1499. if (q) {
  1500. rc = 0;
  1501. if (!(option_mask32 & OPT_w)) {
  1502. rc = update_local_clock(q);
  1503. /* If drift is dangerously large, immediately
  1504. * drop poll interval one step down.
  1505. */
  1506. if (fabs(q->filter_offset) >= POLLDOWN_OFFSET) {
  1507. VERB3 bb_error_msg("offset:%f > POLLDOWN_OFFSET", q->filter_offset);
  1508. goto poll_down;
  1509. }
  1510. }
  1511. }
  1512. /* else: no peer selected, rc = -1: we want to poll more often */
  1513. if (rc != 0) {
  1514. /* Adjust the poll interval by comparing the current offset
  1515. * with the clock jitter. If the offset is less than
  1516. * the clock jitter times a constant, then the averaging interval
  1517. * is increased, otherwise it is decreased. A bit of hysteresis
  1518. * helps calm the dance. Works best using burst mode.
  1519. */
  1520. VERB4 if (rc > 0) {
  1521. bb_error_msg("offset:%f POLLADJ_GATE*discipline_jitter:%f poll:%s",
  1522. q->filter_offset, POLLADJ_GATE * G.discipline_jitter,
  1523. fabs(q->filter_offset) < POLLADJ_GATE * G.discipline_jitter
  1524. ? "grows" : "falls"
  1525. );
  1526. }
  1527. if (rc > 0 && fabs(q->filter_offset) < POLLADJ_GATE * G.discipline_jitter) {
  1528. /* was += G.poll_exp but it is a bit
  1529. * too optimistic for my taste at high poll_exp's */
  1530. G.polladj_count += MINPOLL;
  1531. if (G.polladj_count > POLLADJ_LIMIT) {
  1532. G.polladj_count = 0;
  1533. if (G.poll_exp < MAXPOLL) {
  1534. G.poll_exp++;
  1535. VERB3 bb_error_msg("polladj: discipline_jitter:%f ++poll_exp=%d",
  1536. G.discipline_jitter, G.poll_exp);
  1537. }
  1538. } else {
  1539. VERB3 bb_error_msg("polladj: incr:%d", G.polladj_count);
  1540. }
  1541. } else {
  1542. G.polladj_count -= G.poll_exp * 2;
  1543. if (G.polladj_count < -POLLADJ_LIMIT || G.poll_exp >= BIGPOLL) {
  1544. poll_down:
  1545. G.polladj_count = 0;
  1546. if (G.poll_exp > MINPOLL) {
  1547. llist_t *item;
  1548. G.poll_exp--;
  1549. /* Correct p->next_action_time in each peer
  1550. * which waits for sending, so that they send earlier.
  1551. * Old pp->next_action_time are on the order
  1552. * of t + (1 << old_poll_exp) + small_random,
  1553. * we simply need to subtract ~half of that.
  1554. */
  1555. for (item = G.ntp_peers; item != NULL; item = item->link) {
  1556. peer_t *pp = (peer_t *) item->data;
  1557. if (pp->p_fd < 0)
  1558. pp->next_action_time -= (1 << G.poll_exp);
  1559. }
  1560. VERB3 bb_error_msg("polladj: discipline_jitter:%f --poll_exp=%d",
  1561. G.discipline_jitter, G.poll_exp);
  1562. }
  1563. } else {
  1564. VERB3 bb_error_msg("polladj: decr:%d", G.polladj_count);
  1565. }
  1566. }
  1567. }
  1568. /* Decide when to send new query for this peer */
  1569. interval = poll_interval(0);
  1570. set_next_and_close_sock:
  1571. set_next(p, interval);
  1572. /* We do not expect any more packets from this peer for now.
  1573. * Closing the socket informs kernel about it.
  1574. * We open a new socket when we send a new query.
  1575. */
  1576. close(p->p_fd);
  1577. p->p_fd = -1;
  1578. bail:
  1579. return;
  1580. }
  1581. #if ENABLE_FEATURE_NTPD_SERVER
  1582. static NOINLINE void
  1583. recv_and_process_client_pkt(void /*int fd*/)
  1584. {
  1585. ssize_t size;
  1586. uint8_t version;
  1587. len_and_sockaddr *to;
  1588. struct sockaddr *from;
  1589. msg_t msg;
  1590. uint8_t query_status;
  1591. l_fixedpt_t query_xmttime;
  1592. to = get_sock_lsa(G.listen_fd);
  1593. from = xzalloc(to->len);
  1594. size = recv_from_to(G.listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
  1595. if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
  1596. char *addr;
  1597. if (size < 0) {
  1598. if (errno == EAGAIN)
  1599. goto bail;
  1600. bb_perror_msg_and_die("recv");
  1601. }
  1602. addr = xmalloc_sockaddr2dotted_noport(from);
  1603. bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
  1604. free(addr);
  1605. goto bail;
  1606. }
  1607. query_status = msg.m_status;
  1608. query_xmttime = msg.m_xmttime;
  1609. /* Build a reply packet */
  1610. memset(&msg, 0, sizeof(msg));
  1611. msg.m_status = G.stratum < MAXSTRAT ? G.ntp_status : LI_ALARM;
  1612. msg.m_status |= (query_status & VERSION_MASK);
  1613. msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
  1614. MODE_SERVER : MODE_SYM_PAS;
  1615. msg.m_stratum = G.stratum;
  1616. msg.m_ppoll = G.poll_exp;
  1617. msg.m_precision_exp = G_precision_exp;
  1618. /* this time was obtained between poll() and recv() */
  1619. msg.m_rectime = d_to_lfp(G.cur_time);
  1620. msg.m_xmttime = d_to_lfp(gettime1900d()); /* this instant */
  1621. msg.m_reftime = d_to_lfp(G.reftime);
  1622. msg.m_orgtime = query_xmttime;
  1623. msg.m_rootdelay = d_to_sfp(G.rootdelay);
  1624. //simple code does not do this, fix simple code!
  1625. msg.m_rootdisp = d_to_sfp(G.rootdisp);
  1626. version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
  1627. msg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3;
  1628. /* We reply from the local address packet was sent to,
  1629. * this makes to/from look swapped here: */
  1630. do_sendto(G.listen_fd,
  1631. /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
  1632. &msg, size);
  1633. bail:
  1634. free(to);
  1635. free(from);
  1636. }
  1637. #endif
  1638. /* Upstream ntpd's options:
  1639. *
  1640. * -4 Force DNS resolution of host names to the IPv4 namespace.
  1641. * -6 Force DNS resolution of host names to the IPv6 namespace.
  1642. * -a Require cryptographic authentication for broadcast client,
  1643. * multicast client and symmetric passive associations.
  1644. * This is the default.
  1645. * -A Do not require cryptographic authentication for broadcast client,
  1646. * multicast client and symmetric passive associations.
  1647. * This is almost never a good idea.
  1648. * -b Enable the client to synchronize to broadcast servers.
  1649. * -c conffile
  1650. * Specify the name and path of the configuration file,
  1651. * default /etc/ntp.conf
  1652. * -d Specify debugging mode. This option may occur more than once,
  1653. * with each occurrence indicating greater detail of display.
  1654. * -D level
  1655. * Specify debugging level directly.
  1656. * -f driftfile
  1657. * Specify the name and path of the frequency file.
  1658. * This is the same operation as the "driftfile FILE"
  1659. * configuration command.
  1660. * -g Normally, ntpd exits with a message to the system log
  1661. * if the offset exceeds the panic threshold, which is 1000 s
  1662. * by default. This option allows the time to be set to any value
  1663. * without restriction; however, this can happen only once.
  1664. * If the threshold is exceeded after that, ntpd will exit
  1665. * with a message to the system log. This option can be used
  1666. * with the -q and -x options. See the tinker command for other options.
  1667. * -i jaildir
  1668. * Chroot the server to the directory jaildir. This option also implies
  1669. * that the server attempts to drop root privileges at startup
  1670. * (otherwise, chroot gives very little additional security).
  1671. * You may need to also specify a -u option.
  1672. * -k keyfile
  1673. * Specify the name and path of the symmetric key file,
  1674. * default /etc/ntp/keys. This is the same operation
  1675. * as the "keys FILE" configuration command.
  1676. * -l logfile
  1677. * Specify the name and path of the log file. The default
  1678. * is the system log file. This is the same operation as
  1679. * the "logfile FILE" configuration command.
  1680. * -L Do not listen to virtual IPs. The default is to listen.
  1681. * -n Don't fork.
  1682. * -N To the extent permitted by the operating system,
  1683. * run the ntpd at the highest priority.
  1684. * -p pidfile
  1685. * Specify the name and path of the file used to record the ntpd
  1686. * process ID. This is the same operation as the "pidfile FILE"
  1687. * configuration command.
  1688. * -P priority
  1689. * To the extent permitted by the operating system,
  1690. * run the ntpd at the specified priority.
  1691. * -q Exit the ntpd just after the first time the clock is set.
  1692. * This behavior mimics that of the ntpdate program, which is
  1693. * to be retired. The -g and -x options can be used with this option.
  1694. * Note: The kernel time discipline is disabled with this option.
  1695. * -r broadcastdelay
  1696. * Specify the default propagation delay from the broadcast/multicast
  1697. * server to this client. This is necessary only if the delay
  1698. * cannot be computed automatically by the protocol.
  1699. * -s statsdir
  1700. * Specify the directory path for files created by the statistics
  1701. * facility. This is the same operation as the "statsdir DIR"
  1702. * configuration command.
  1703. * -t key
  1704. * Add a key number to the trusted key list. This option can occur
  1705. * more than once.
  1706. * -u user[:group]
  1707. * Specify a user, and optionally a group, to switch to.
  1708. * -v variable
  1709. * -V variable
  1710. * Add a system variable listed by default.
  1711. * -x Normally, the time is slewed if the offset is less than the step
  1712. * threshold, which is 128 ms by default, and stepped if above
  1713. * the threshold. This option sets the threshold to 600 s, which is
  1714. * well within the accuracy window to set the clock manually.
  1715. * Note: since the slew rate of typical Unix kernels is limited
  1716. * to 0.5 ms/s, each second of adjustment requires an amortization
  1717. * interval of 2000 s. Thus, an adjustment as much as 600 s
  1718. * will take almost 14 days to complete. This option can be used
  1719. * with the -g and -q options. See the tinker command for other options.
  1720. * Note: The kernel time discipline is disabled with this option.
  1721. */
  1722. /* By doing init in a separate function we decrease stack usage
  1723. * in main loop.
  1724. */
  1725. static NOINLINE void ntp_init(char **argv)
  1726. {
  1727. unsigned opts;
  1728. llist_t *peers;
  1729. srandom(getpid());
  1730. if (getuid())
  1731. bb_error_msg_and_die(bb_msg_you_must_be_root);
  1732. /* Set some globals */
  1733. G.stratum = MAXSTRAT;
  1734. if (BURSTPOLL != 0)
  1735. G.poll_exp = BURSTPOLL; /* speeds up initial sync */
  1736. G.last_script_run = G.reftime = G.last_update_recv_time = gettime1900d(); /* sets G.cur_time too */
  1737. /* Parse options */
  1738. peers = NULL;
  1739. opt_complementary = "dd:p::wn"; /* d: counter; p: list; -w implies -n */
  1740. opts = getopt32(argv,
  1741. "nqNx" /* compat */
  1742. "wp:S:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
  1743. "d" /* compat */
  1744. "46aAbgL", /* compat, ignored */
  1745. &peers, &G.script_name, &G.verbose);
  1746. if (!(opts & (OPT_p|OPT_l)))
  1747. bb_show_usage();
  1748. // if (opts & OPT_x) /* disable stepping, only slew is allowed */
  1749. // G.time_was_stepped = 1;
  1750. while (peers)
  1751. add_peers(llist_pop(&peers));
  1752. if (!(opts & OPT_n)) {
  1753. bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
  1754. logmode = LOGMODE_NONE;
  1755. }
  1756. #if ENABLE_FEATURE_NTPD_SERVER
  1757. G.listen_fd = -1;
  1758. if (opts & OPT_l) {
  1759. G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
  1760. socket_want_pktinfo(G.listen_fd);
  1761. setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
  1762. }
  1763. #endif
  1764. /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
  1765. if (opts & OPT_N)
  1766. setpriority(PRIO_PROCESS, 0, -15);
  1767. bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
  1768. /* Removed SIGHUP here: */
  1769. bb_signals((1 << SIGPIPE) | (1 << SIGCHLD), SIG_IGN);
  1770. }
  1771. int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1772. int ntpd_main(int argc UNUSED_PARAM, char **argv)
  1773. {
  1774. #undef G
  1775. struct globals G;
  1776. struct pollfd *pfd;
  1777. peer_t **idx2peer;
  1778. unsigned cnt;
  1779. memset(&G, 0, sizeof(G));
  1780. SET_PTR_TO_GLOBALS(&G);
  1781. ntp_init(argv);
  1782. /* If ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
  1783. cnt = G.peer_cnt + ENABLE_FEATURE_NTPD_SERVER;
  1784. idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt);
  1785. pfd = xzalloc(sizeof(pfd[0]) * cnt);
  1786. /* Countdown: we never sync before we sent INITIAL_SAMLPES+1
  1787. * packets to each peer.
  1788. * NB: if some peer is not responding, we may end up sending
  1789. * fewer packets to it and more to other peers.
  1790. * NB2: sync usually happens using INITIAL_SAMLPES packets,
  1791. * since last reply does not come back instantaneously.
  1792. */
  1793. cnt = G.peer_cnt * (INITIAL_SAMLPES + 1);
  1794. while (!bb_got_signal) {
  1795. llist_t *item;
  1796. unsigned i, j;
  1797. int nfds, timeout;
  1798. double nextaction;
  1799. /* Nothing between here and poll() blocks for any significant time */
  1800. nextaction = G.cur_time + 3600;
  1801. i = 0;
  1802. #if ENABLE_FEATURE_NTPD_SERVER
  1803. if (G.listen_fd != -1) {
  1804. pfd[0].fd = G.listen_fd;
  1805. pfd[0].events = POLLIN;
  1806. i++;
  1807. }
  1808. #endif
  1809. /* Pass over peer list, send requests, time out on receives */
  1810. for (item = G.ntp_peers; item != NULL; item = item->link) {
  1811. peer_t *p = (peer_t *) item->data;
  1812. if (p->next_action_time <= G.cur_time) {
  1813. if (p->p_fd == -1) {
  1814. /* Time to send new req */
  1815. if (--cnt == 0) {
  1816. G.initial_poll_complete = 1;
  1817. }
  1818. send_query_to_peer(p);
  1819. } else {
  1820. /* Timed out waiting for reply */
  1821. close(p->p_fd);
  1822. p->p_fd = -1;
  1823. timeout = poll_interval(-2); /* -2: try a bit sooner */
  1824. bb_error_msg("timed out waiting for %s, reach 0x%02x, next query in %us",
  1825. p->p_dotted, p->reachable_bits, timeout);
  1826. set_next(p, timeout);
  1827. }
  1828. }
  1829. if (p->next_action_time < nextaction)
  1830. nextaction = p->next_action_time;
  1831. if (p->p_fd >= 0) {
  1832. /* Wait for reply from this peer */
  1833. pfd[i].fd = p->p_fd;
  1834. pfd[i].events = POLLIN;
  1835. idx2peer[i] = p;
  1836. i++;
  1837. }
  1838. }
  1839. timeout = nextaction - G.cur_time;
  1840. if (timeout < 0)
  1841. timeout = 0;
  1842. timeout++; /* (nextaction - G.cur_time) rounds down, compensating */
  1843. /* Here we may block */
  1844. VERB2 bb_error_msg("poll %us, sockets:%u, poll interval:%us", timeout, i, 1 << G.poll_exp);
  1845. nfds = poll(pfd, i, timeout * 1000);
  1846. gettime1900d(); /* sets G.cur_time */
  1847. if (nfds <= 0) {
  1848. if (G.script_name && G.cur_time - G.last_script_run > 11*60) {
  1849. /* Useful for updating battery-backed RTC and such */
  1850. run_script("periodic", G.last_update_offset);
  1851. gettime1900d(); /* sets G.cur_time */
  1852. }
  1853. continue;
  1854. }
  1855. /* Process any received packets */
  1856. j = 0;
  1857. #if ENABLE_FEATURE_NTPD_SERVER
  1858. if (G.listen_fd != -1) {
  1859. if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
  1860. nfds--;
  1861. recv_and_process_client_pkt(/*G.listen_fd*/);
  1862. gettime1900d(); /* sets G.cur_time */
  1863. }
  1864. j = 1;
  1865. }
  1866. #endif
  1867. for (; nfds != 0 && j < i; j++) {
  1868. if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
  1869. nfds--;
  1870. recv_and_process_peer_pkt(idx2peer[j]);
  1871. gettime1900d(); /* sets G.cur_time */
  1872. }
  1873. }
  1874. } /* while (!bb_got_signal) */
  1875. kill_myself_with_sig(bb_got_signal);
  1876. }
  1877. /*** openntpd-4.6 uses only adjtime, not adjtimex ***/
  1878. /*** ntp-4.2.6/ntpd/ntp_loopfilter.c - adjtimex usage ***/
  1879. #if 0
  1880. static double
  1881. direct_freq(double fp_offset)
  1882. {
  1883. #ifdef KERNEL_PLL
  1884. /*
  1885. * If the kernel is enabled, we need the residual offset to
  1886. * calculate the frequency correction.
  1887. */
  1888. if (pll_control && kern_enable) {
  1889. memset(&ntv, 0, sizeof(ntv));
  1890. ntp_adjtime(&ntv);
  1891. #ifdef STA_NANO
  1892. clock_offset = ntv.offset / 1e9;
  1893. #else /* STA_NANO */
  1894. clock_offset = ntv.offset / 1e6;
  1895. #endif /* STA_NANO */
  1896. drift_comp = FREQTOD(ntv.freq);
  1897. }
  1898. #endif /* KERNEL_PLL */
  1899. set_freq((fp_offset - clock_offset) / (current_time - clock_epoch) + drift_comp);
  1900. wander_resid = 0;
  1901. return drift_comp;
  1902. }
  1903. static void
  1904. set_freq(double freq) /* frequency update */
  1905. {
  1906. char tbuf[80];
  1907. drift_comp = freq;
  1908. #ifdef KERNEL_PLL
  1909. /*
  1910. * If the kernel is enabled, update the kernel frequency.
  1911. */
  1912. if (pll_control && kern_enable) {
  1913. memset(&ntv, 0, sizeof(ntv));
  1914. ntv.modes = MOD_FREQUENCY;
  1915. ntv.freq = DTOFREQ(drift_comp);
  1916. ntp_adjtime(&ntv);
  1917. snprintf(tbuf, sizeof(tbuf), "kernel %.3f PPM", drift_comp * 1e6);
  1918. report_event(EVNT_FSET, NULL, tbuf);
  1919. } else {
  1920. snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
  1921. report_event(EVNT_FSET, NULL, tbuf);
  1922. }
  1923. #else /* KERNEL_PLL */
  1924. snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
  1925. report_event(EVNT_FSET, NULL, tbuf);
  1926. #endif /* KERNEL_PLL */
  1927. }
  1928. ...
  1929. ...
  1930. ...
  1931. #ifdef KERNEL_PLL
  1932. /*
  1933. * This code segment works when clock adjustments are made using
  1934. * precision time kernel support and the ntp_adjtime() system
  1935. * call. This support is available in Solaris 2.6 and later,
  1936. * Digital Unix 4.0 and later, FreeBSD, Linux and specially
  1937. * modified kernels for HP-UX 9 and Ultrix 4. In the case of the
  1938. * DECstation 5000/240 and Alpha AXP, additional kernel
  1939. * modifications provide a true microsecond clock and nanosecond
  1940. * clock, respectively.
  1941. *
  1942. * Important note: The kernel discipline is used only if the
  1943. * step threshold is less than 0.5 s, as anything higher can
  1944. * lead to overflow problems. This might occur if some misguided
  1945. * lad set the step threshold to something ridiculous.
  1946. */
  1947. if (pll_control && kern_enable) {
  1948. #define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | MOD_STATUS | MOD_TIMECONST)
  1949. /*
  1950. * We initialize the structure for the ntp_adjtime()
  1951. * system call. We have to convert everything to
  1952. * microseconds or nanoseconds first. Do not update the
  1953. * system variables if the ext_enable flag is set. In
  1954. * this case, the external clock driver will update the
  1955. * variables, which will be read later by the local
  1956. * clock driver. Afterwards, remember the time and
  1957. * frequency offsets for jitter and stability values and
  1958. * to update the frequency file.
  1959. */
  1960. memset(&ntv, 0, sizeof(ntv));
  1961. if (ext_enable) {
  1962. ntv.modes = MOD_STATUS;
  1963. } else {
  1964. #ifdef STA_NANO
  1965. ntv.modes = MOD_BITS | MOD_NANO;
  1966. #else /* STA_NANO */
  1967. ntv.modes = MOD_BITS;
  1968. #endif /* STA_NANO */
  1969. if (clock_offset < 0)
  1970. dtemp = -.5;
  1971. else
  1972. dtemp = .5;
  1973. #ifdef STA_NANO
  1974. ntv.offset = (int32)(clock_offset * 1e9 + dtemp);
  1975. ntv.constant = sys_poll;
  1976. #else /* STA_NANO */
  1977. ntv.offset = (int32)(clock_offset * 1e6 + dtemp);
  1978. ntv.constant = sys_poll - 4;
  1979. #endif /* STA_NANO */
  1980. ntv.esterror = (u_int32)(clock_jitter * 1e6);
  1981. ntv.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
  1982. ntv.status = STA_PLL;
  1983. /*
  1984. * Enable/disable the PPS if requested.
  1985. */
  1986. if (pps_enable) {
  1987. if (!(pll_status & STA_PPSTIME))
  1988. report_event(EVNT_KERN,
  1989. NULL, "PPS enabled");
  1990. ntv.status |= STA_PPSTIME | STA_PPSFREQ;
  1991. } else {
  1992. if (pll_status & STA_PPSTIME)
  1993. report_event(EVNT_KERN,
  1994. NULL, "PPS disabled");
  1995. ntv.status &= ~(STA_PPSTIME |
  1996. STA_PPSFREQ);
  1997. }
  1998. if (sys_leap == LEAP_ADDSECOND)
  1999. ntv.status |= STA_INS;
  2000. else if (sys_leap == LEAP_DELSECOND)
  2001. ntv.status |= STA_DEL;
  2002. }
  2003. /*
  2004. * Pass the stuff to the kernel. If it squeals, turn off
  2005. * the pps. In any case, fetch the kernel offset,
  2006. * frequency and jitter.
  2007. */
  2008. if (ntp_adjtime(&ntv) == TIME_ERROR) {
  2009. if (!(ntv.status & STA_PPSSIGNAL))
  2010. report_event(EVNT_KERN, NULL,
  2011. "PPS no signal");
  2012. }
  2013. pll_status = ntv.status;
  2014. #ifdef STA_NANO
  2015. clock_offset = ntv.offset / 1e9;
  2016. #else /* STA_NANO */
  2017. clock_offset = ntv.offset / 1e6;
  2018. #endif /* STA_NANO */
  2019. clock_frequency = FREQTOD(ntv.freq);
  2020. /*
  2021. * If the kernel PPS is lit, monitor its performance.
  2022. */
  2023. if (ntv.status & STA_PPSTIME) {
  2024. #ifdef STA_NANO
  2025. clock_jitter = ntv.jitter / 1e9;
  2026. #else /* STA_NANO */
  2027. clock_jitter = ntv.jitter / 1e6;
  2028. #endif /* STA_NANO */
  2029. }
  2030. #if defined(STA_NANO) && NTP_API == 4
  2031. /*
  2032. * If the TAI changes, update the kernel TAI.
  2033. */
  2034. if (loop_tai != sys_tai) {
  2035. loop_tai = sys_tai;
  2036. ntv.modes = MOD_TAI;
  2037. ntv.constant = sys_tai;
  2038. ntp_adjtime(&ntv);
  2039. }
  2040. #endif /* STA_NANO */
  2041. }
  2042. #endif /* KERNEL_PLL */
  2043. #endif