ntpd.c 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262
  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 source tree.
  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_SAMPLES 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_SAMPLES 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. if (G.peer_cnt == 0) {
  1622. /* we have no peers: "stratum 1 server" mode. reftime = our own time */
  1623. G.reftime = G.cur_time;
  1624. }
  1625. msg.m_reftime = d_to_lfp(G.reftime);
  1626. msg.m_orgtime = query_xmttime;
  1627. msg.m_rootdelay = d_to_sfp(G.rootdelay);
  1628. //simple code does not do this, fix simple code!
  1629. msg.m_rootdisp = d_to_sfp(G.rootdisp);
  1630. version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
  1631. msg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3;
  1632. /* We reply from the local address packet was sent to,
  1633. * this makes to/from look swapped here: */
  1634. do_sendto(G.listen_fd,
  1635. /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
  1636. &msg, size);
  1637. bail:
  1638. free(to);
  1639. free(from);
  1640. }
  1641. #endif
  1642. /* Upstream ntpd's options:
  1643. *
  1644. * -4 Force DNS resolution of host names to the IPv4 namespace.
  1645. * -6 Force DNS resolution of host names to the IPv6 namespace.
  1646. * -a Require cryptographic authentication for broadcast client,
  1647. * multicast client and symmetric passive associations.
  1648. * This is the default.
  1649. * -A Do not require cryptographic authentication for broadcast client,
  1650. * multicast client and symmetric passive associations.
  1651. * This is almost never a good idea.
  1652. * -b Enable the client to synchronize to broadcast servers.
  1653. * -c conffile
  1654. * Specify the name and path of the configuration file,
  1655. * default /etc/ntp.conf
  1656. * -d Specify debugging mode. This option may occur more than once,
  1657. * with each occurrence indicating greater detail of display.
  1658. * -D level
  1659. * Specify debugging level directly.
  1660. * -f driftfile
  1661. * Specify the name and path of the frequency file.
  1662. * This is the same operation as the "driftfile FILE"
  1663. * configuration command.
  1664. * -g Normally, ntpd exits with a message to the system log
  1665. * if the offset exceeds the panic threshold, which is 1000 s
  1666. * by default. This option allows the time to be set to any value
  1667. * without restriction; however, this can happen only once.
  1668. * If the threshold is exceeded after that, ntpd will exit
  1669. * with a message to the system log. This option can be used
  1670. * with the -q and -x options. See the tinker command for other options.
  1671. * -i jaildir
  1672. * Chroot the server to the directory jaildir. This option also implies
  1673. * that the server attempts to drop root privileges at startup
  1674. * (otherwise, chroot gives very little additional security).
  1675. * You may need to also specify a -u option.
  1676. * -k keyfile
  1677. * Specify the name and path of the symmetric key file,
  1678. * default /etc/ntp/keys. This is the same operation
  1679. * as the "keys FILE" configuration command.
  1680. * -l logfile
  1681. * Specify the name and path of the log file. The default
  1682. * is the system log file. This is the same operation as
  1683. * the "logfile FILE" configuration command.
  1684. * -L Do not listen to virtual IPs. The default is to listen.
  1685. * -n Don't fork.
  1686. * -N To the extent permitted by the operating system,
  1687. * run the ntpd at the highest priority.
  1688. * -p pidfile
  1689. * Specify the name and path of the file used to record the ntpd
  1690. * process ID. This is the same operation as the "pidfile FILE"
  1691. * configuration command.
  1692. * -P priority
  1693. * To the extent permitted by the operating system,
  1694. * run the ntpd at the specified priority.
  1695. * -q Exit the ntpd just after the first time the clock is set.
  1696. * This behavior mimics that of the ntpdate program, which is
  1697. * to be retired. The -g and -x options can be used with this option.
  1698. * Note: The kernel time discipline is disabled with this option.
  1699. * -r broadcastdelay
  1700. * Specify the default propagation delay from the broadcast/multicast
  1701. * server to this client. This is necessary only if the delay
  1702. * cannot be computed automatically by the protocol.
  1703. * -s statsdir
  1704. * Specify the directory path for files created by the statistics
  1705. * facility. This is the same operation as the "statsdir DIR"
  1706. * configuration command.
  1707. * -t key
  1708. * Add a key number to the trusted key list. This option can occur
  1709. * more than once.
  1710. * -u user[:group]
  1711. * Specify a user, and optionally a group, to switch to.
  1712. * -v variable
  1713. * -V variable
  1714. * Add a system variable listed by default.
  1715. * -x Normally, the time is slewed if the offset is less than the step
  1716. * threshold, which is 128 ms by default, and stepped if above
  1717. * the threshold. This option sets the threshold to 600 s, which is
  1718. * well within the accuracy window to set the clock manually.
  1719. * Note: since the slew rate of typical Unix kernels is limited
  1720. * to 0.5 ms/s, each second of adjustment requires an amortization
  1721. * interval of 2000 s. Thus, an adjustment as much as 600 s
  1722. * will take almost 14 days to complete. This option can be used
  1723. * with the -g and -q options. See the tinker command for other options.
  1724. * Note: The kernel time discipline is disabled with this option.
  1725. */
  1726. /* By doing init in a separate function we decrease stack usage
  1727. * in main loop.
  1728. */
  1729. static NOINLINE void ntp_init(char **argv)
  1730. {
  1731. unsigned opts;
  1732. llist_t *peers;
  1733. srandom(getpid());
  1734. if (getuid())
  1735. bb_error_msg_and_die(bb_msg_you_must_be_root);
  1736. /* Set some globals */
  1737. G.stratum = MAXSTRAT;
  1738. if (BURSTPOLL != 0)
  1739. G.poll_exp = BURSTPOLL; /* speeds up initial sync */
  1740. G.last_script_run = G.reftime = G.last_update_recv_time = gettime1900d(); /* sets G.cur_time too */
  1741. /* Parse options */
  1742. peers = NULL;
  1743. opt_complementary = "dd:p::wn"; /* d: counter; p: list; -w implies -n */
  1744. opts = getopt32(argv,
  1745. "nqNx" /* compat */
  1746. "wp:S:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
  1747. "d" /* compat */
  1748. "46aAbgL", /* compat, ignored */
  1749. &peers, &G.script_name, &G.verbose);
  1750. if (!(opts & (OPT_p|OPT_l)))
  1751. bb_show_usage();
  1752. // if (opts & OPT_x) /* disable stepping, only slew is allowed */
  1753. // G.time_was_stepped = 1;
  1754. if (peers) {
  1755. while (peers)
  1756. add_peers(llist_pop(&peers));
  1757. } else {
  1758. /* -l but no peers: "stratum 1 server" mode */
  1759. G.stratum = 1;
  1760. }
  1761. if (!(opts & OPT_n)) {
  1762. bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
  1763. logmode = LOGMODE_NONE;
  1764. }
  1765. #if ENABLE_FEATURE_NTPD_SERVER
  1766. G.listen_fd = -1;
  1767. if (opts & OPT_l) {
  1768. G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
  1769. socket_want_pktinfo(G.listen_fd);
  1770. setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
  1771. }
  1772. #endif
  1773. /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
  1774. if (opts & OPT_N)
  1775. setpriority(PRIO_PROCESS, 0, -15);
  1776. /* If network is up, syncronization occurs in ~10 seconds.
  1777. * We give "ntpd -q" a full minute to finish, then we exit.
  1778. *
  1779. * I tested ntpd 4.2.6p1 and apparently it never exits
  1780. * (will try forever), but it does not feel right.
  1781. * The goal of -q is to act like ntpdate: set time
  1782. * after a reasonably small period of polling, or fail.
  1783. */
  1784. if (opts & OPT_q)
  1785. alarm(60);
  1786. bb_signals(0
  1787. | (1 << SIGTERM)
  1788. | (1 << SIGINT)
  1789. | (1 << SIGALRM)
  1790. , record_signo
  1791. );
  1792. bb_signals(0
  1793. | (1 << SIGPIPE)
  1794. | (1 << SIGCHLD)
  1795. , SIG_IGN
  1796. );
  1797. }
  1798. int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
  1799. int ntpd_main(int argc UNUSED_PARAM, char **argv)
  1800. {
  1801. #undef G
  1802. struct globals G;
  1803. struct pollfd *pfd;
  1804. peer_t **idx2peer;
  1805. unsigned cnt;
  1806. memset(&G, 0, sizeof(G));
  1807. SET_PTR_TO_GLOBALS(&G);
  1808. ntp_init(argv);
  1809. /* If ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
  1810. cnt = G.peer_cnt + ENABLE_FEATURE_NTPD_SERVER;
  1811. idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt);
  1812. pfd = xzalloc(sizeof(pfd[0]) * cnt);
  1813. /* Countdown: we never sync before we sent INITIAL_SAMPLES+1
  1814. * packets to each peer.
  1815. * NB: if some peer is not responding, we may end up sending
  1816. * fewer packets to it and more to other peers.
  1817. * NB2: sync usually happens using INITIAL_SAMPLES packets,
  1818. * since last reply does not come back instantaneously.
  1819. */
  1820. cnt = G.peer_cnt * (INITIAL_SAMPLES + 1);
  1821. while (!bb_got_signal) {
  1822. llist_t *item;
  1823. unsigned i, j;
  1824. int nfds, timeout;
  1825. double nextaction;
  1826. /* Nothing between here and poll() blocks for any significant time */
  1827. nextaction = G.cur_time + 3600;
  1828. i = 0;
  1829. #if ENABLE_FEATURE_NTPD_SERVER
  1830. if (G.listen_fd != -1) {
  1831. pfd[0].fd = G.listen_fd;
  1832. pfd[0].events = POLLIN;
  1833. i++;
  1834. }
  1835. #endif
  1836. /* Pass over peer list, send requests, time out on receives */
  1837. for (item = G.ntp_peers; item != NULL; item = item->link) {
  1838. peer_t *p = (peer_t *) item->data;
  1839. if (p->next_action_time <= G.cur_time) {
  1840. if (p->p_fd == -1) {
  1841. /* Time to send new req */
  1842. if (--cnt == 0) {
  1843. G.initial_poll_complete = 1;
  1844. }
  1845. send_query_to_peer(p);
  1846. } else {
  1847. /* Timed out waiting for reply */
  1848. close(p->p_fd);
  1849. p->p_fd = -1;
  1850. timeout = poll_interval(-2); /* -2: try a bit sooner */
  1851. bb_error_msg("timed out waiting for %s, reach 0x%02x, next query in %us",
  1852. p->p_dotted, p->reachable_bits, timeout);
  1853. set_next(p, timeout);
  1854. }
  1855. }
  1856. if (p->next_action_time < nextaction)
  1857. nextaction = p->next_action_time;
  1858. if (p->p_fd >= 0) {
  1859. /* Wait for reply from this peer */
  1860. pfd[i].fd = p->p_fd;
  1861. pfd[i].events = POLLIN;
  1862. idx2peer[i] = p;
  1863. i++;
  1864. }
  1865. }
  1866. timeout = nextaction - G.cur_time;
  1867. if (timeout < 0)
  1868. timeout = 0;
  1869. timeout++; /* (nextaction - G.cur_time) rounds down, compensating */
  1870. /* Here we may block */
  1871. VERB2 bb_error_msg("poll %us, sockets:%u, poll interval:%us", timeout, i, 1 << G.poll_exp);
  1872. nfds = poll(pfd, i, timeout * 1000);
  1873. gettime1900d(); /* sets G.cur_time */
  1874. if (nfds <= 0) {
  1875. if (G.script_name && G.cur_time - G.last_script_run > 11*60) {
  1876. /* Useful for updating battery-backed RTC and such */
  1877. run_script("periodic", G.last_update_offset);
  1878. gettime1900d(); /* sets G.cur_time */
  1879. }
  1880. continue;
  1881. }
  1882. /* Process any received packets */
  1883. j = 0;
  1884. #if ENABLE_FEATURE_NTPD_SERVER
  1885. if (G.listen_fd != -1) {
  1886. if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
  1887. nfds--;
  1888. recv_and_process_client_pkt(/*G.listen_fd*/);
  1889. gettime1900d(); /* sets G.cur_time */
  1890. }
  1891. j = 1;
  1892. }
  1893. #endif
  1894. for (; nfds != 0 && j < i; j++) {
  1895. if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
  1896. nfds--;
  1897. recv_and_process_peer_pkt(idx2peer[j]);
  1898. gettime1900d(); /* sets G.cur_time */
  1899. }
  1900. }
  1901. } /* while (!bb_got_signal) */
  1902. kill_myself_with_sig(bb_got_signal);
  1903. }
  1904. /*** openntpd-4.6 uses only adjtime, not adjtimex ***/
  1905. /*** ntp-4.2.6/ntpd/ntp_loopfilter.c - adjtimex usage ***/
  1906. #if 0
  1907. static double
  1908. direct_freq(double fp_offset)
  1909. {
  1910. #ifdef KERNEL_PLL
  1911. /*
  1912. * If the kernel is enabled, we need the residual offset to
  1913. * calculate the frequency correction.
  1914. */
  1915. if (pll_control && kern_enable) {
  1916. memset(&ntv, 0, sizeof(ntv));
  1917. ntp_adjtime(&ntv);
  1918. #ifdef STA_NANO
  1919. clock_offset = ntv.offset / 1e9;
  1920. #else /* STA_NANO */
  1921. clock_offset = ntv.offset / 1e6;
  1922. #endif /* STA_NANO */
  1923. drift_comp = FREQTOD(ntv.freq);
  1924. }
  1925. #endif /* KERNEL_PLL */
  1926. set_freq((fp_offset - clock_offset) / (current_time - clock_epoch) + drift_comp);
  1927. wander_resid = 0;
  1928. return drift_comp;
  1929. }
  1930. static void
  1931. set_freq(double freq) /* frequency update */
  1932. {
  1933. char tbuf[80];
  1934. drift_comp = freq;
  1935. #ifdef KERNEL_PLL
  1936. /*
  1937. * If the kernel is enabled, update the kernel frequency.
  1938. */
  1939. if (pll_control && kern_enable) {
  1940. memset(&ntv, 0, sizeof(ntv));
  1941. ntv.modes = MOD_FREQUENCY;
  1942. ntv.freq = DTOFREQ(drift_comp);
  1943. ntp_adjtime(&ntv);
  1944. snprintf(tbuf, sizeof(tbuf), "kernel %.3f PPM", drift_comp * 1e6);
  1945. report_event(EVNT_FSET, NULL, tbuf);
  1946. } else {
  1947. snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
  1948. report_event(EVNT_FSET, NULL, tbuf);
  1949. }
  1950. #else /* KERNEL_PLL */
  1951. snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
  1952. report_event(EVNT_FSET, NULL, tbuf);
  1953. #endif /* KERNEL_PLL */
  1954. }
  1955. ...
  1956. ...
  1957. ...
  1958. #ifdef KERNEL_PLL
  1959. /*
  1960. * This code segment works when clock adjustments are made using
  1961. * precision time kernel support and the ntp_adjtime() system
  1962. * call. This support is available in Solaris 2.6 and later,
  1963. * Digital Unix 4.0 and later, FreeBSD, Linux and specially
  1964. * modified kernels for HP-UX 9 and Ultrix 4. In the case of the
  1965. * DECstation 5000/240 and Alpha AXP, additional kernel
  1966. * modifications provide a true microsecond clock and nanosecond
  1967. * clock, respectively.
  1968. *
  1969. * Important note: The kernel discipline is used only if the
  1970. * step threshold is less than 0.5 s, as anything higher can
  1971. * lead to overflow problems. This might occur if some misguided
  1972. * lad set the step threshold to something ridiculous.
  1973. */
  1974. if (pll_control && kern_enable) {
  1975. #define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | MOD_STATUS | MOD_TIMECONST)
  1976. /*
  1977. * We initialize the structure for the ntp_adjtime()
  1978. * system call. We have to convert everything to
  1979. * microseconds or nanoseconds first. Do not update the
  1980. * system variables if the ext_enable flag is set. In
  1981. * this case, the external clock driver will update the
  1982. * variables, which will be read later by the local
  1983. * clock driver. Afterwards, remember the time and
  1984. * frequency offsets for jitter and stability values and
  1985. * to update the frequency file.
  1986. */
  1987. memset(&ntv, 0, sizeof(ntv));
  1988. if (ext_enable) {
  1989. ntv.modes = MOD_STATUS;
  1990. } else {
  1991. #ifdef STA_NANO
  1992. ntv.modes = MOD_BITS | MOD_NANO;
  1993. #else /* STA_NANO */
  1994. ntv.modes = MOD_BITS;
  1995. #endif /* STA_NANO */
  1996. if (clock_offset < 0)
  1997. dtemp = -.5;
  1998. else
  1999. dtemp = .5;
  2000. #ifdef STA_NANO
  2001. ntv.offset = (int32)(clock_offset * 1e9 + dtemp);
  2002. ntv.constant = sys_poll;
  2003. #else /* STA_NANO */
  2004. ntv.offset = (int32)(clock_offset * 1e6 + dtemp);
  2005. ntv.constant = sys_poll - 4;
  2006. #endif /* STA_NANO */
  2007. ntv.esterror = (u_int32)(clock_jitter * 1e6);
  2008. ntv.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
  2009. ntv.status = STA_PLL;
  2010. /*
  2011. * Enable/disable the PPS if requested.
  2012. */
  2013. if (pps_enable) {
  2014. if (!(pll_status & STA_PPSTIME))
  2015. report_event(EVNT_KERN,
  2016. NULL, "PPS enabled");
  2017. ntv.status |= STA_PPSTIME | STA_PPSFREQ;
  2018. } else {
  2019. if (pll_status & STA_PPSTIME)
  2020. report_event(EVNT_KERN,
  2021. NULL, "PPS disabled");
  2022. ntv.status &= ~(STA_PPSTIME |
  2023. STA_PPSFREQ);
  2024. }
  2025. if (sys_leap == LEAP_ADDSECOND)
  2026. ntv.status |= STA_INS;
  2027. else if (sys_leap == LEAP_DELSECOND)
  2028. ntv.status |= STA_DEL;
  2029. }
  2030. /*
  2031. * Pass the stuff to the kernel. If it squeals, turn off
  2032. * the pps. In any case, fetch the kernel offset,
  2033. * frequency and jitter.
  2034. */
  2035. if (ntp_adjtime(&ntv) == TIME_ERROR) {
  2036. if (!(ntv.status & STA_PPSSIGNAL))
  2037. report_event(EVNT_KERN, NULL,
  2038. "PPS no signal");
  2039. }
  2040. pll_status = ntv.status;
  2041. #ifdef STA_NANO
  2042. clock_offset = ntv.offset / 1e9;
  2043. #else /* STA_NANO */
  2044. clock_offset = ntv.offset / 1e6;
  2045. #endif /* STA_NANO */
  2046. clock_frequency = FREQTOD(ntv.freq);
  2047. /*
  2048. * If the kernel PPS is lit, monitor its performance.
  2049. */
  2050. if (ntv.status & STA_PPSTIME) {
  2051. #ifdef STA_NANO
  2052. clock_jitter = ntv.jitter / 1e9;
  2053. #else /* STA_NANO */
  2054. clock_jitter = ntv.jitter / 1e6;
  2055. #endif /* STA_NANO */
  2056. }
  2057. #if defined(STA_NANO) && NTP_API == 4
  2058. /*
  2059. * If the TAI changes, update the kernel TAI.
  2060. */
  2061. if (loop_tai != sys_tai) {
  2062. loop_tai = sys_tai;
  2063. ntv.modes = MOD_TAI;
  2064. ntv.constant = sys_tai;
  2065. ntp_adjtime(&ntv);
  2066. }
  2067. #endif /* STA_NANO */
  2068. }
  2069. #endif /* KERNEL_PLL */
  2070. #endif