ntpd.c 71 KB

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