ntpd.c 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778
  1. /*
  2. * NTP client/server, based on OpenNTPD 3.9p1
  3. *
  4. * Busybox port author: Adam Tkac (C) 2009 <vonsch@gmail.com>
  5. *
  6. * OpenNTPd 3.9p1 copyright holders:
  7. * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
  8. * Copyright (c) 2004 Alexander Guy <alexander.guy@andern.org>
  9. *
  10. * OpenNTPd code is licensed under ISC-style licence:
  11. *
  12. * Permission to use, copy, modify, and distribute this software for any
  13. * purpose with or without fee is hereby granted, provided that the above
  14. * copyright notice and this permission notice appear in all copies.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  17. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  19. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  20. * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
  21. * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
  22. * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  23. ***********************************************************************
  24. *
  25. * Parts of OpenNTPD clock syncronization code is replaced by
  26. * code which is based on ntp-4.2.6, which carries the following
  27. * copyright notice:
  28. *
  29. * Copyright (c) University of Delaware 1992-2009
  30. *
  31. * Permission to use, copy, modify, and distribute this software and
  32. * its documentation for any purpose with or without fee is hereby
  33. * granted, provided that the above copyright notice appears in all
  34. * copies and that both the copyright notice and this permission
  35. * notice appear in supporting documentation, and that the name
  36. * University of Delaware not be used in advertising or publicity
  37. * pertaining to distribution of the software without specific,
  38. * written prior permission. The University of Delaware makes no
  39. * representations about the suitability this software for any
  40. * purpose. It is provided "as is" without express or implied warranty.
  41. ***********************************************************************
  42. */
  43. //config:config NTPD
  44. //config: bool "ntpd (17 kb)"
  45. //config: default y
  46. //config: select PLATFORM_LINUX
  47. //config: help
  48. //config: The NTP client/server daemon.
  49. //config:
  50. //config:config FEATURE_NTPD_SERVER
  51. //config: bool "Make ntpd usable as a NTP server"
  52. //config: default y
  53. //config: depends on NTPD
  54. //config: help
  55. //config: Make ntpd usable as a NTP server. If you disable this option
  56. //config: ntpd will be usable only as a NTP client.
  57. //config:
  58. //config:config FEATURE_NTPD_CONF
  59. //config: bool "Make ntpd understand /etc/ntp.conf"
  60. //config: default y
  61. //config: depends on NTPD
  62. //config: help
  63. //config: Make ntpd look in /etc/ntp.conf for peers. Only "server address"
  64. //config: is supported.
  65. //applet:IF_NTPD(APPLET(ntpd, BB_DIR_USR_SBIN, BB_SUID_DROP))
  66. //kbuild:lib-$(CONFIG_NTPD) += ntpd.o
  67. //usage:#define ntpd_trivial_usage
  68. //usage: "[-dnqNw"IF_FEATURE_NTPD_SERVER("l -I IFACE")"] [-S PROG] [-p PEER]..."
  69. //usage:#define ntpd_full_usage "\n\n"
  70. //usage: "NTP client/server\n"
  71. //usage: "\n -d Verbose (may be repeated)"
  72. //usage: "\n -n Do not daemonize"
  73. //usage: "\n -q Quit after clock is set"
  74. //usage: "\n -N Run at high priority"
  75. //usage: "\n -w Do not set time (only query peers), implies -n"
  76. //usage: "\n -S PROG Run PROG after stepping time, stratum change, and every 11 mins"
  77. //usage: "\n -p PEER Obtain time from PEER (may be repeated)"
  78. //usage: IF_FEATURE_NTPD_CONF(
  79. //usage: "\n If -p is not given, 'server HOST' lines"
  80. //usage: "\n from /etc/ntp.conf are used"
  81. //usage: )
  82. //usage: IF_FEATURE_NTPD_SERVER(
  83. //usage: "\n -l Also run as server on port 123"
  84. //usage: "\n -I IFACE Bind server to IFACE, implies -l"
  85. //usage: )
  86. // -l and -p options are not compatible with "standard" ntpd:
  87. // it has them as "-l logfile" and "-p pidfile".
  88. // -S and -w are not compat either, "standard" ntpd has no such opts.
  89. #include "libbb.h"
  90. #include <math.h>
  91. #include <netinet/ip.h> /* For IPTOS_DSCP_AF21 definition */
  92. #include <sys/timex.h>
  93. #ifndef IPTOS_DSCP_AF21
  94. # define IPTOS_DSCP_AF21 0x48
  95. #endif
  96. /* Verbosity control (max level of -dddd options accepted).
  97. * max 6 is very talkative (and bloated). 3 is non-bloated,
  98. * production level setting.
  99. */
  100. #define MAX_VERBOSE 3
  101. /* High-level description of the algorithm:
  102. *
  103. * We start running with very small poll_exp, BURSTPOLL,
  104. * in order to quickly accumulate INITIAL_SAMPLES datapoints
  105. * for each peer. Then, time is stepped if the offset is larger
  106. * than STEP_THRESHOLD, otherwise it isn't; anyway, we enlarge
  107. * poll_exp to MINPOLL and enter frequency measurement step:
  108. * we collect new datapoints but ignore them for WATCH_THRESHOLD
  109. * seconds. After WATCH_THRESHOLD seconds we look at accumulated
  110. * offset and estimate frequency drift.
  111. *
  112. * (frequency measurement step seems to not be strictly needed,
  113. * it is conditionally disabled with USING_INITIAL_FREQ_ESTIMATION
  114. * define set to 0)
  115. *
  116. * After this, we enter "steady state": we collect a datapoint,
  117. * we select the best peer, if this datapoint is not a new one
  118. * (IOW: if this datapoint isn't for selected peer), sleep
  119. * and collect another one; otherwise, use its offset to update
  120. * frequency drift, if offset is somewhat large, reduce poll_exp,
  121. * otherwise increase poll_exp.
  122. *
  123. * If offset is larger than STEP_THRESHOLD, which shouldn't normally
  124. * happen, we assume that something "bad" happened (computer
  125. * was hibernated, someone set totally wrong date, etc),
  126. * then the time is stepped, all datapoints are discarded,
  127. * and we go back to steady state.
  128. *
  129. * Made some changes to speed up re-syncing after our clock goes bad
  130. * (tested with suspending my laptop):
  131. * - if largish offset (>= STEP_THRESHOLD == 1 sec) is seen
  132. * from a peer, schedule next query for this peer soon
  133. * without drastically lowering poll interval for everybody.
  134. * This makes us collect enough data for step much faster:
  135. * e.g. at poll = 10 (1024 secs), step was done within 5 minutes
  136. * after first reply which indicated that our clock is 14 seconds off.
  137. * - on step, do not discard d_dispersion data of the existing datapoints,
  138. * do not clear reachable_bits. This prevents discarding first ~8
  139. * datapoints after the step.
  140. */
  141. #define INITIAL_SAMPLES 4 /* how many samples do we want for init */
  142. #define BAD_DELAY_GROWTH 4 /* drop packet if its delay grew by more than this */
  143. #define RETRY_INTERVAL 32 /* on send/recv error, retry in N secs (need to be power of 2) */
  144. #define NOREPLY_INTERVAL 512 /* sent, but got no reply: cap next query by this many seconds */
  145. #define RESPONSE_INTERVAL 16 /* wait for reply up to N secs */
  146. #define HOSTNAME_INTERVAL 4 /* hostname lookup failed. Wait N * peer->dns_errors secs for next try */
  147. #define DNS_ERRORS_CAP 0x3f /* peer->dns_errors is in [0..63] */
  148. /* Step threshold (sec). std ntpd uses 0.128.
  149. */
  150. #define STEP_THRESHOLD 1
  151. /* Slew threshold (sec): adjtimex() won't accept offsets larger than this.
  152. * Using exact power of 2 (1/8) results in smaller code
  153. */
  154. #define SLEW_THRESHOLD 0.125
  155. //^^^^^^^^^^^^^^^^^^^^^^^^^^ TODO: man adjtimex about tmx.offset:
  156. // "Since Linux 2.6.26, the supplied value is clamped to the range (-0.5s, +0.5s)"
  157. // - can use this larger value instead?
  158. /* Stepout threshold (sec). std ntpd uses 900 (11 mins (!)) */
  159. //UNUSED: #define WATCH_THRESHOLD 128
  160. /* NB: set WATCH_THRESHOLD to ~60 when debugging to save time) */
  161. //UNUSED: #define PANIC_THRESHOLD 1000 /* panic threshold (sec) */
  162. /*
  163. * If we got |offset| > BIGOFF from a peer, cap next query interval
  164. * for this peer by this many seconds:
  165. */
  166. #define BIGOFF STEP_THRESHOLD
  167. #define BIGOFF_INTERVAL (1 << 7) /* 128 s */
  168. #define FREQ_TOLERANCE 0.000015 /* frequency tolerance (15 PPM) */
  169. #define BURSTPOLL 0 /* initial poll */
  170. #define MINPOLL 5 /* minimum poll interval. std ntpd uses 6 (6: 64 sec) */
  171. /*
  172. * If offset > discipline_jitter * POLLADJ_GATE, and poll interval is > 2^BIGPOLL,
  173. * then it is decreased _at once_. (If <= 2^BIGPOLL, it will be decreased _eventually_).
  174. */
  175. #define BIGPOLL 9 /* 2^9 sec ~= 8.5 min */
  176. #define MAXPOLL 12 /* maximum poll interval (12: 1.1h, 17: 36.4h). std ntpd uses 17 */
  177. /*
  178. * Actively lower poll when we see such big offsets.
  179. * With SLEW_THRESHOLD = 0.125, it means we try to sync more aggressively
  180. * if offset increases over ~0.04 sec
  181. */
  182. //#define POLLDOWN_OFFSET (SLEW_THRESHOLD / 3)
  183. #define MINDISP 0.01 /* minimum dispersion (sec) */
  184. #define MAXDISP 16 /* maximum dispersion (sec) */
  185. #define MAXSTRAT 16 /* maximum stratum (infinity metric) */
  186. #define MAXDIST 1 /* distance threshold (sec) */
  187. #define MIN_SELECTED 1 /* minimum intersection survivors */
  188. #define MIN_CLUSTERED 3 /* minimum cluster survivors */
  189. #define MAXDRIFT 0.000500 /* frequency drift we can correct (500 PPM) */
  190. /* Poll-adjust threshold.
  191. * When we see that offset is small enough compared to discipline jitter,
  192. * we grow a counter: += MINPOLL. When counter goes over POLLADJ_LIMIT,
  193. * we poll_exp++. If offset isn't small, counter -= poll_exp*2,
  194. * and when it goes below -POLLADJ_LIMIT, we poll_exp--.
  195. * (Bumped from 30 to 40 since otherwise I often see poll_exp going *2* steps down)
  196. */
  197. #define POLLADJ_LIMIT 40
  198. /* If offset < discipline_jitter * POLLADJ_GATE, then we decide to increase
  199. * poll interval (we think we can't improve timekeeping
  200. * by staying at smaller poll).
  201. */
  202. #define POLLADJ_GATE 4
  203. #define TIMECONST_HACK_GATE 2
  204. /* Compromise Allan intercept (sec). doc uses 1500, std ntpd uses 512 */
  205. #define ALLAN 512
  206. /* PLL loop gain */
  207. #define PLL 65536
  208. /* FLL loop gain [why it depends on MAXPOLL??] */
  209. #define FLL (MAXPOLL + 1)
  210. /* Parameter averaging constant */
  211. #define AVG 4
  212. enum {
  213. NTP_VERSION = 4,
  214. NTP_MAXSTRATUM = 15,
  215. NTP_DIGESTSIZE = 16,
  216. NTP_MSGSIZE_NOAUTH = 48,
  217. NTP_MSGSIZE = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
  218. /* Status Masks */
  219. MODE_MASK = (7 << 0),
  220. VERSION_MASK = (7 << 3),
  221. VERSION_SHIFT = 3,
  222. LI_MASK = (3 << 6),
  223. /* Leap Second Codes (high order two bits of m_status) */
  224. LI_NOWARNING = (0 << 6), /* no warning */
  225. LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
  226. LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
  227. LI_ALARM = (3 << 6), /* alarm condition */
  228. /* Mode values */
  229. MODE_RES0 = 0, /* reserved */
  230. MODE_SYM_ACT = 1, /* symmetric active */
  231. MODE_SYM_PAS = 2, /* symmetric passive */
  232. MODE_CLIENT = 3, /* client */
  233. MODE_SERVER = 4, /* server */
  234. MODE_BROADCAST = 5, /* broadcast */
  235. MODE_RES1 = 6, /* reserved for NTP control message */
  236. MODE_RES2 = 7, /* reserved for private use */
  237. };
  238. //TODO: better base selection
  239. #define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
  240. #define NUM_DATAPOINTS 8
  241. typedef struct {
  242. uint32_t int_partl;
  243. uint32_t fractionl;
  244. } l_fixedpt_t;
  245. typedef struct {
  246. uint16_t int_parts;
  247. uint16_t fractions;
  248. } s_fixedpt_t;
  249. typedef struct {
  250. uint8_t m_status; /* status of local clock and leap info */
  251. uint8_t m_stratum;
  252. uint8_t m_ppoll; /* poll value */
  253. int8_t m_precision_exp;
  254. s_fixedpt_t m_rootdelay;
  255. s_fixedpt_t m_rootdisp;
  256. uint32_t m_refid;
  257. l_fixedpt_t m_reftime;
  258. l_fixedpt_t m_orgtime;
  259. l_fixedpt_t m_rectime;
  260. l_fixedpt_t m_xmttime;
  261. uint32_t m_keyid;
  262. uint8_t m_digest[NTP_DIGESTSIZE];
  263. } msg_t;
  264. typedef struct {
  265. double d_offset;
  266. double d_recv_time;
  267. double d_dispersion;
  268. } datapoint_t;
  269. typedef struct {
  270. len_and_sockaddr *p_lsa;
  271. char *p_dotted;
  272. int p_fd;
  273. int datapoint_idx;
  274. uint32_t lastpkt_refid;
  275. uint8_t lastpkt_status;
  276. uint8_t lastpkt_stratum;
  277. uint8_t reachable_bits;
  278. uint8_t dns_errors;
  279. /* when to send new query (if p_fd == -1)
  280. * or when receive times out (if p_fd >= 0): */
  281. double next_action_time;
  282. double p_xmttime;
  283. double p_raw_delay;
  284. /* p_raw_delay is set even by "high delay" packets */
  285. /* lastpkt_delay isn't */
  286. double lastpkt_recv_time;
  287. double lastpkt_delay;
  288. double lastpkt_rootdelay;
  289. double lastpkt_rootdisp;
  290. /* produced by filter algorithm: */
  291. double filter_offset;
  292. double filter_dispersion;
  293. double filter_jitter;
  294. datapoint_t filter_datapoint[NUM_DATAPOINTS];
  295. /* last sent packet: */
  296. msg_t p_xmt_msg;
  297. char p_hostname[1];
  298. } peer_t;
  299. #define USING_KERNEL_PLL_LOOP 1
  300. #define USING_INITIAL_FREQ_ESTIMATION 0
  301. enum {
  302. OPT_n = (1 << 0),
  303. OPT_q = (1 << 1),
  304. OPT_N = (1 << 2),
  305. OPT_x = (1 << 3),
  306. /* Insert new options above this line. */
  307. /* Non-compat options: */
  308. OPT_w = (1 << 4),
  309. OPT_p = (1 << 5),
  310. OPT_S = (1 << 6),
  311. OPT_l = (1 << 7) * ENABLE_FEATURE_NTPD_SERVER,
  312. OPT_I = (1 << 8) * ENABLE_FEATURE_NTPD_SERVER,
  313. /* We hijack some bits for other purposes */
  314. OPT_qq = (1 << 31),
  315. };
  316. struct globals {
  317. double cur_time;
  318. /* total round trip delay to currently selected reference clock */
  319. double rootdelay;
  320. /* reference timestamp: time when the system clock was last set or corrected */
  321. double reftime;
  322. /* total dispersion to currently selected reference clock */
  323. double rootdisp;
  324. double last_script_run;
  325. char *script_name;
  326. llist_t *ntp_peers;
  327. #if ENABLE_FEATURE_NTPD_SERVER
  328. int listen_fd;
  329. char *if_name;
  330. # define G_listen_fd (G.listen_fd)
  331. #else
  332. # define G_listen_fd (-1)
  333. #endif
  334. unsigned verbose;
  335. unsigned peer_cnt;
  336. /* refid: 32-bit code identifying the particular server or reference clock
  337. * in stratum 0 packets this is a four-character ASCII string,
  338. * called the kiss code, used for debugging and monitoring
  339. * in stratum 1 packets this is a four-character ASCII string
  340. * assigned to the reference clock by IANA. Example: "GPS "
  341. * in stratum 2+ packets, it's IPv4 address or 4 first bytes
  342. * of MD5 hash of IPv6
  343. */
  344. uint32_t refid;
  345. uint8_t ntp_status;
  346. /* precision is defined as the larger of the resolution and time to
  347. * read the clock, in log2 units. For instance, the precision of a
  348. * mains-frequency clock incrementing at 60 Hz is 16 ms, even when the
  349. * system clock hardware representation is to the nanosecond.
  350. *
  351. * Delays, jitters of various kinds are clamped down to precision.
  352. *
  353. * If precision_sec is too large, discipline_jitter gets clamped to it
  354. * and if offset is smaller than discipline_jitter * POLLADJ_GATE, poll
  355. * interval grows even though we really can benefit from staying at
  356. * smaller one, collecting non-lagged datapoits and correcting offset.
  357. * (Lagged datapoits exist when poll_exp is large but we still have
  358. * systematic offset error - the time distance between datapoints
  359. * is significant and older datapoints have smaller offsets.
  360. * This makes our offset estimation a bit smaller than reality)
  361. * Due to this effect, setting G_precision_sec close to
  362. * STEP_THRESHOLD isn't such a good idea - offsets may grow
  363. * too big and we will step. I observed it with -6.
  364. *
  365. * OTOH, setting precision_sec far too small would result in futile
  366. * attempts to synchronize to an unachievable precision.
  367. *
  368. * -6 is 1/64 sec, -7 is 1/128 sec and so on.
  369. * -8 is 1/256 ~= 0.003906 (worked well for me --vda)
  370. * -9 is 1/512 ~= 0.001953 (let's try this for some time)
  371. */
  372. #define G_precision_exp -9
  373. /*
  374. * G_precision_exp is used only for construction outgoing packets.
  375. * It's ok to set G_precision_sec to a slightly different value
  376. * (One which is "nicer looking" in logs).
  377. * Exact value would be (1.0 / (1 << (- G_precision_exp))):
  378. */
  379. #define G_precision_sec 0.002
  380. uint8_t stratum;
  381. #define STATE_NSET 0 /* initial state, "nothing is set" */
  382. //#define STATE_FSET 1 /* frequency set from file */
  383. //#define STATE_SPIK 2 /* spike detected */
  384. //#define STATE_FREQ 3 /* initial frequency */
  385. #define STATE_SYNC 4 /* clock synchronized (normal operation) */
  386. uint8_t discipline_state; // doc calls it c.state
  387. uint8_t poll_exp; // s.poll
  388. int polladj_count; // c.count
  389. int FREQHOLD_cnt;
  390. long kernel_freq_drift;
  391. peer_t *last_update_peer;
  392. double last_update_offset; // c.last
  393. double last_update_recv_time; // s.t
  394. double discipline_jitter; // c.jitter
  395. /* Since we only compare it with ints, can simplify code
  396. * by not making this variable floating point:
  397. */
  398. unsigned offset_to_jitter_ratio;
  399. //double cluster_offset; // s.offset
  400. //double cluster_jitter; // s.jitter
  401. #if !USING_KERNEL_PLL_LOOP
  402. double discipline_freq_drift; // c.freq
  403. /* Maybe conditionally calculate wander? it's used only for logging */
  404. double discipline_wander; // c.wander
  405. #endif
  406. };
  407. #define G (*ptr_to_globals)
  408. #define VERB1 if (MAX_VERBOSE && G.verbose)
  409. #define VERB2 if (MAX_VERBOSE >= 2 && G.verbose >= 2)
  410. #define VERB3 if (MAX_VERBOSE >= 3 && G.verbose >= 3)
  411. #define VERB4 if (MAX_VERBOSE >= 4 && G.verbose >= 4)
  412. #define VERB5 if (MAX_VERBOSE >= 5 && G.verbose >= 5)
  413. #define VERB6 if (MAX_VERBOSE >= 6 && G.verbose >= 6)
  414. static double LOG2D(int a)
  415. {
  416. if (a < 0)
  417. return 1.0 / (1UL << -a);
  418. return 1UL << a;
  419. }
  420. static ALWAYS_INLINE double SQUARE(double x)
  421. {
  422. return x * x;
  423. }
  424. static ALWAYS_INLINE double MAXD(double a, double b)
  425. {
  426. if (a > b)
  427. return a;
  428. return b;
  429. }
  430. static ALWAYS_INLINE double MIND(double a, double b)
  431. {
  432. if (a < b)
  433. return a;
  434. return b;
  435. }
  436. static NOINLINE double my_SQRT(double X)
  437. {
  438. union {
  439. float f;
  440. int32_t i;
  441. } v;
  442. double invsqrt;
  443. double Xhalf = X * 0.5;
  444. /* Fast and good approximation to 1/sqrt(X), black magic */
  445. v.f = X;
  446. /*v.i = 0x5f3759df - (v.i >> 1);*/
  447. v.i = 0x5f375a86 - (v.i >> 1); /* - this constant is slightly better */
  448. invsqrt = v.f; /* better than 0.2% accuracy */
  449. /* Refining it using Newton's method: x1 = x0 - f(x0)/f'(x0)
  450. * f(x) = 1/(x*x) - X (f==0 when x = 1/sqrt(X))
  451. * f'(x) = -2/(x*x*x)
  452. * f(x)/f'(x) = (X - 1/(x*x)) / (2/(x*x*x)) = X*x*x*x/2 - x/2
  453. * x1 = x0 - (X*x0*x0*x0/2 - x0/2) = 1.5*x0 - X*x0*x0*x0/2 = x0*(1.5 - (X/2)*x0*x0)
  454. */
  455. invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); /* ~0.05% accuracy */
  456. /* invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); 2nd iter: ~0.0001% accuracy */
  457. /* With 4 iterations, more than half results will be exact,
  458. * at 6th iterations result stabilizes with about 72% results exact.
  459. * We are well satisfied with 0.05% accuracy.
  460. */
  461. return X * invsqrt; /* X * 1/sqrt(X) ~= sqrt(X) */
  462. }
  463. static ALWAYS_INLINE double SQRT(double X)
  464. {
  465. /* If this arch doesn't use IEEE 754 floats, fall back to using libm */
  466. if (sizeof(float) != 4)
  467. return sqrt(X);
  468. /* This avoids needing libm, saves about 0.5k on x86-32 */
  469. return my_SQRT(X);
  470. }
  471. static double
  472. gettime1900d(void)
  473. {
  474. struct timeval tv;
  475. gettimeofday(&tv, NULL); /* never fails */
  476. G.cur_time = tv.tv_sec + (1.0e-6 * tv.tv_usec) + OFFSET_1900_1970;
  477. return G.cur_time;
  478. }
  479. static void
  480. d_to_tv(double d, struct timeval *tv)
  481. {
  482. tv->tv_sec = (long)d;
  483. tv->tv_usec = (d - tv->tv_sec) * 1000000;
  484. }
  485. static double
  486. lfp_to_d(l_fixedpt_t lfp)
  487. {
  488. double ret;
  489. lfp.int_partl = ntohl(lfp.int_partl);
  490. lfp.fractionl = ntohl(lfp.fractionl);
  491. ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
  492. return ret;
  493. }
  494. static double
  495. sfp_to_d(s_fixedpt_t sfp)
  496. {
  497. double ret;
  498. sfp.int_parts = ntohs(sfp.int_parts);
  499. sfp.fractions = ntohs(sfp.fractions);
  500. ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
  501. return ret;
  502. }
  503. #if ENABLE_FEATURE_NTPD_SERVER
  504. static l_fixedpt_t
  505. d_to_lfp(double d)
  506. {
  507. l_fixedpt_t lfp;
  508. lfp.int_partl = (uint32_t)d;
  509. lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
  510. lfp.int_partl = htonl(lfp.int_partl);
  511. lfp.fractionl = htonl(lfp.fractionl);
  512. return lfp;
  513. }
  514. static s_fixedpt_t
  515. d_to_sfp(double d)
  516. {
  517. s_fixedpt_t sfp;
  518. sfp.int_parts = (uint16_t)d;
  519. sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
  520. sfp.int_parts = htons(sfp.int_parts);
  521. sfp.fractions = htons(sfp.fractions);
  522. return sfp;
  523. }
  524. #endif
  525. static double
  526. dispersion(const datapoint_t *dp)
  527. {
  528. return dp->d_dispersion + FREQ_TOLERANCE * (G.cur_time - dp->d_recv_time);
  529. }
  530. static double
  531. root_distance(peer_t *p)
  532. {
  533. /* The root synchronization distance is the maximum error due to
  534. * all causes of the local clock relative to the primary server.
  535. * It is defined as half the total delay plus total dispersion
  536. * plus peer jitter.
  537. */
  538. return MAXD(MINDISP, p->lastpkt_rootdelay + p->lastpkt_delay) / 2
  539. + p->lastpkt_rootdisp
  540. + p->filter_dispersion
  541. + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time)
  542. + p->filter_jitter;
  543. }
  544. static void
  545. set_next(peer_t *p, unsigned t)
  546. {
  547. p->next_action_time = G.cur_time + t;
  548. }
  549. /*
  550. * Peer clock filter and its helpers
  551. */
  552. static void
  553. filter_datapoints(peer_t *p)
  554. {
  555. int i, idx;
  556. double sum, wavg;
  557. datapoint_t *fdp;
  558. #if 0
  559. /* Simulations have shown that use of *averaged* offset for p->filter_offset
  560. * is in fact worse than simply using last received one: with large poll intervals
  561. * (>= 2048) averaging code uses offset values which are outdated by hours,
  562. * and time/frequency correction goes totally wrong when fed essentially bogus offsets.
  563. */
  564. int got_newest;
  565. double minoff, maxoff, w;
  566. double x = x; /* for compiler */
  567. double oldest_off = oldest_off;
  568. double oldest_age = oldest_age;
  569. double newest_off = newest_off;
  570. double newest_age = newest_age;
  571. fdp = p->filter_datapoint;
  572. minoff = maxoff = fdp[0].d_offset;
  573. for (i = 1; i < NUM_DATAPOINTS; i++) {
  574. if (minoff > fdp[i].d_offset)
  575. minoff = fdp[i].d_offset;
  576. if (maxoff < fdp[i].d_offset)
  577. maxoff = fdp[i].d_offset;
  578. }
  579. idx = p->datapoint_idx; /* most recent datapoint's index */
  580. /* Average offset:
  581. * Drop two outliers and take weighted average of the rest:
  582. * most_recent/2 + older1/4 + older2/8 ... + older5/32 + older6/32
  583. * we use older6/32, not older6/64 since sum of weights should be 1:
  584. * 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + 1/32 = 1
  585. */
  586. wavg = 0;
  587. w = 0.5;
  588. /* n-1
  589. * --- dispersion(i)
  590. * filter_dispersion = \ -------------
  591. * / (i+1)
  592. * --- 2
  593. * i=0
  594. */
  595. got_newest = 0;
  596. sum = 0;
  597. for (i = 0; i < NUM_DATAPOINTS; i++) {
  598. VERB5 {
  599. bb_error_msg("datapoint[%d]: off:%f disp:%f(%f) age:%f%s",
  600. i,
  601. fdp[idx].d_offset,
  602. fdp[idx].d_dispersion, dispersion(&fdp[idx]),
  603. G.cur_time - fdp[idx].d_recv_time,
  604. (minoff == fdp[idx].d_offset || maxoff == fdp[idx].d_offset)
  605. ? " (outlier by offset)" : ""
  606. );
  607. }
  608. sum += dispersion(&fdp[idx]) / (2 << i);
  609. if (minoff == fdp[idx].d_offset) {
  610. minoff -= 1; /* so that we don't match it ever again */
  611. } else
  612. if (maxoff == fdp[idx].d_offset) {
  613. maxoff += 1;
  614. } else {
  615. oldest_off = fdp[idx].d_offset;
  616. oldest_age = G.cur_time - fdp[idx].d_recv_time;
  617. if (!got_newest) {
  618. got_newest = 1;
  619. newest_off = oldest_off;
  620. newest_age = oldest_age;
  621. }
  622. x = oldest_off * w;
  623. wavg += x;
  624. w /= 2;
  625. }
  626. idx = (idx - 1) & (NUM_DATAPOINTS - 1);
  627. }
  628. p->filter_dispersion = sum;
  629. wavg += x; /* add another older6/64 to form older6/32 */
  630. /* Fix systematic underestimation with large poll intervals.
  631. * Imagine that we still have a bit of uncorrected drift,
  632. * and poll interval is big (say, 100 sec). Offsets form a progression:
  633. * 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 - 0.7 is most recent.
  634. * The algorithm above drops 0.0 and 0.7 as outliers,
  635. * and then we have this estimation, ~25% off from 0.7:
  636. * 0.1/32 + 0.2/32 + 0.3/16 + 0.4/8 + 0.5/4 + 0.6/2 = 0.503125
  637. */
  638. x = oldest_age - newest_age;
  639. if (x != 0) {
  640. x = newest_age / x; /* in above example, 100 / (600 - 100) */
  641. if (x < 1) { /* paranoia check */
  642. x = (newest_off - oldest_off) * x; /* 0.5 * 100/500 = 0.1 */
  643. wavg += x;
  644. }
  645. }
  646. p->filter_offset = wavg;
  647. #else
  648. fdp = p->filter_datapoint;
  649. idx = p->datapoint_idx; /* most recent datapoint's index */
  650. /* filter_offset: simply use the most recent value */
  651. p->filter_offset = fdp[idx].d_offset;
  652. /* n-1
  653. * --- dispersion(i)
  654. * filter_dispersion = \ -------------
  655. * / (i+1)
  656. * --- 2
  657. * i=0
  658. */
  659. wavg = 0;
  660. sum = 0;
  661. for (i = 0; i < NUM_DATAPOINTS; i++) {
  662. sum += dispersion(&fdp[idx]) / (2 << i);
  663. wavg += fdp[idx].d_offset;
  664. idx = (idx - 1) & (NUM_DATAPOINTS - 1);
  665. }
  666. wavg /= NUM_DATAPOINTS;
  667. p->filter_dispersion = sum;
  668. #endif
  669. /* +----- -----+ ^ 1/2
  670. * | n-1 |
  671. * | --- |
  672. * | 1 \ 2 |
  673. * filter_jitter = | --- * / (avg-offset_j) |
  674. * | n --- |
  675. * | j=0 |
  676. * +----- -----+
  677. * where n is the number of valid datapoints in the filter (n > 1);
  678. * if filter_jitter < precision then filter_jitter = precision
  679. */
  680. sum = 0;
  681. for (i = 0; i < NUM_DATAPOINTS; i++) {
  682. sum += SQUARE(wavg - fdp[i].d_offset);
  683. }
  684. sum = SQRT(sum / NUM_DATAPOINTS);
  685. p->filter_jitter = sum > G_precision_sec ? sum : G_precision_sec;
  686. VERB4 bb_error_msg("filter offset:%+f disp:%f jitter:%f",
  687. p->filter_offset,
  688. p->filter_dispersion,
  689. p->filter_jitter);
  690. }
  691. static void
  692. reset_peer_stats(peer_t *p, double offset)
  693. {
  694. int i;
  695. bool small_ofs = fabs(offset) < STEP_THRESHOLD;
  696. /* Used to set p->filter_datapoint[i].d_dispersion = MAXDISP
  697. * and clear reachable bits, but this proved to be too aggressive:
  698. * after step (tested with suspending laptop for ~30 secs),
  699. * this caused all previous data to be considered invalid,
  700. * making us needing to collect full ~8 datapoints per peer
  701. * after step in order to start trusting them.
  702. * In turn, this was making poll interval decrease even after
  703. * step was done. (Poll interval decreases already before step
  704. * in this scenario, because we see large offsets and end up with
  705. * no good peer to select).
  706. */
  707. for (i = 0; i < NUM_DATAPOINTS; i++) {
  708. if (small_ofs) {
  709. p->filter_datapoint[i].d_recv_time += offset;
  710. if (p->filter_datapoint[i].d_offset != 0) {
  711. p->filter_datapoint[i].d_offset -= offset;
  712. //bb_error_msg("p->filter_datapoint[%d].d_offset %f -> %f",
  713. // i,
  714. // p->filter_datapoint[i].d_offset + offset,
  715. // p->filter_datapoint[i].d_offset);
  716. }
  717. } else {
  718. p->filter_datapoint[i].d_recv_time = G.cur_time;
  719. p->filter_datapoint[i].d_offset = 0;
  720. /*p->filter_datapoint[i].d_dispersion = MAXDISP;*/
  721. }
  722. }
  723. if (small_ofs) {
  724. p->lastpkt_recv_time += offset;
  725. } else {
  726. /*p->reachable_bits = 0;*/
  727. p->lastpkt_recv_time = G.cur_time;
  728. }
  729. filter_datapoints(p); /* recalc p->filter_xxx */
  730. VERB6 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
  731. }
  732. static len_and_sockaddr*
  733. resolve_peer_hostname(peer_t *p)
  734. {
  735. len_and_sockaddr *lsa = host2sockaddr(p->p_hostname, 123);
  736. if (lsa) {
  737. free(p->p_lsa);
  738. free(p->p_dotted);
  739. p->p_lsa = lsa;
  740. p->p_dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
  741. VERB1 if (strcmp(p->p_hostname, p->p_dotted) != 0)
  742. bb_error_msg("'%s' is %s", p->p_hostname, p->p_dotted);
  743. p->dns_errors = 0;
  744. return lsa;
  745. }
  746. p->dns_errors = ((p->dns_errors << 1) | 1) & DNS_ERRORS_CAP;
  747. return lsa;
  748. }
  749. static void
  750. add_peers(const char *s)
  751. {
  752. llist_t *item;
  753. peer_t *p;
  754. p = xzalloc(sizeof(*p) + strlen(s));
  755. strcpy(p->p_hostname, s);
  756. p->p_fd = -1;
  757. p->p_xmt_msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
  758. p->next_action_time = G.cur_time; /* = set_next(p, 0); */
  759. reset_peer_stats(p, STEP_THRESHOLD);
  760. /* Names like N.<country2chars>.pool.ntp.org are randomly resolved
  761. * to a pool of machines. Sometimes different N's resolve to the same IP.
  762. * It is not useful to have two peers with same IP. We skip duplicates.
  763. */
  764. if (resolve_peer_hostname(p)) {
  765. for (item = G.ntp_peers; item != NULL; item = item->link) {
  766. peer_t *pp = (peer_t *) item->data;
  767. if (pp->p_dotted && strcmp(p->p_dotted, pp->p_dotted) == 0) {
  768. bb_error_msg("duplicate peer %s (%s)", s, p->p_dotted);
  769. free(p->p_lsa);
  770. free(p->p_dotted);
  771. free(p);
  772. return;
  773. }
  774. }
  775. }
  776. llist_add_to(&G.ntp_peers, p);
  777. G.peer_cnt++;
  778. }
  779. static int
  780. do_sendto(int fd,
  781. const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
  782. msg_t *msg, ssize_t len)
  783. {
  784. ssize_t ret;
  785. errno = 0;
  786. if (!from) {
  787. ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
  788. } else {
  789. ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
  790. }
  791. if (ret != len) {
  792. bb_perror_msg("send failed");
  793. return -1;
  794. }
  795. return 0;
  796. }
  797. static void
  798. send_query_to_peer(peer_t *p)
  799. {
  800. if (!p->p_lsa)
  801. return;
  802. /* Why do we need to bind()?
  803. * See what happens when we don't bind:
  804. *
  805. * socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
  806. * setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
  807. * gettimeofday({1259071266, 327885}, NULL) = 0
  808. * sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
  809. * ^^^ we sent it from some source port picked by kernel.
  810. * time(NULL) = 1259071266
  811. * write(2, "ntpd: entering poll 15 secs\n", 28) = 28
  812. * poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
  813. * recv(3, "yyy", 68, MSG_DONTWAIT) = 48
  814. * ^^^ this recv will receive packets to any local port!
  815. *
  816. * Uncomment this and use strace to see it in action:
  817. */
  818. #define PROBE_LOCAL_ADDR /* { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); } */
  819. if (p->p_fd == -1) {
  820. int fd, family;
  821. len_and_sockaddr *local_lsa;
  822. family = p->p_lsa->u.sa.sa_family;
  823. p->p_fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
  824. /* local_lsa has "null" address and port 0 now.
  825. * bind() ensures we have a *particular port* selected by kernel
  826. * and remembered in p->p_fd, thus later recv(p->p_fd)
  827. * receives only packets sent to this port.
  828. */
  829. PROBE_LOCAL_ADDR
  830. xbind(fd, &local_lsa->u.sa, local_lsa->len);
  831. PROBE_LOCAL_ADDR
  832. #if ENABLE_FEATURE_IPV6
  833. if (family == AF_INET)
  834. #endif
  835. setsockopt_int(fd, IPPROTO_IP, IP_TOS, IPTOS_DSCP_AF21);
  836. free(local_lsa);
  837. }
  838. /* Emit message _before_ attempted send. Think of a very short
  839. * roundtrip networks: we need to go back to recv loop ASAP,
  840. * to reduce delay. Printing messages after send works against that.
  841. */
  842. VERB1 bb_error_msg("sending query to %s", p->p_dotted);
  843. /*
  844. * Send out a random 64-bit number as our transmit time. The NTP
  845. * server will copy said number into the originate field on the
  846. * response that it sends us. This is totally legal per the SNTP spec.
  847. *
  848. * The impact of this is two fold: we no longer send out the current
  849. * system time for the world to see (which may aid an attacker), and
  850. * it gives us a (not very secure) way of knowing that we're not
  851. * getting spoofed by an attacker that can't capture our traffic
  852. * but can spoof packets from the NTP server we're communicating with.
  853. *
  854. * Save the real transmit timestamp locally.
  855. */
  856. p->p_xmt_msg.m_xmttime.int_partl = rand();
  857. p->p_xmt_msg.m_xmttime.fractionl = rand();
  858. p->p_xmttime = gettime1900d();
  859. /* Were doing it only if sendto worked, but
  860. * loss of sync detection needs reachable_bits updated
  861. * even if sending fails *locally*:
  862. * "network is unreachable" because cable was pulled?
  863. * We still need to declare "unsync" if this condition persists.
  864. */
  865. p->reachable_bits <<= 1;
  866. if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
  867. &p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
  868. ) {
  869. close(p->p_fd);
  870. p->p_fd = -1;
  871. /*
  872. * We know that we sent nothing.
  873. * We can retry *soon* without fearing
  874. * that we are flooding the peer.
  875. */
  876. set_next(p, RETRY_INTERVAL);
  877. return;
  878. }
  879. set_next(p, RESPONSE_INTERVAL);
  880. }
  881. /* Note that there is no provision to prevent several run_scripts
  882. * to be started in quick succession. In fact, it happens rather often
  883. * if initial syncronization results in a step.
  884. * You will see "step" and then "stratum" script runs, sometimes
  885. * as close as only 0.002 seconds apart.
  886. * Script should be ready to deal with this.
  887. */
  888. static void run_script(const char *action, double offset)
  889. {
  890. char *argv[3];
  891. char *env1, *env2, *env3, *env4;
  892. G.last_script_run = G.cur_time;
  893. if (!G.script_name)
  894. return;
  895. argv[0] = (char*) G.script_name;
  896. argv[1] = (char*) action;
  897. argv[2] = NULL;
  898. VERB1 bb_error_msg("executing '%s %s'", G.script_name, action);
  899. env1 = xasprintf("%s=%u", "stratum", G.stratum);
  900. putenv(env1);
  901. env2 = xasprintf("%s=%ld", "freq_drift_ppm", G.kernel_freq_drift);
  902. putenv(env2);
  903. env3 = xasprintf("%s=%u", "poll_interval", 1 << G.poll_exp);
  904. putenv(env3);
  905. env4 = xasprintf("%s=%f", "offset", offset);
  906. putenv(env4);
  907. /* Other items of potential interest: selected peer,
  908. * rootdelay, reftime, rootdisp, refid, ntp_status,
  909. * last_update_offset, last_update_recv_time, discipline_jitter,
  910. * how many peers have reachable_bits = 0?
  911. */
  912. /* Don't want to wait: it may run hwclock --systohc, and that
  913. * may take some time (seconds): */
  914. /*spawn_and_wait(argv);*/
  915. spawn(argv);
  916. unsetenv("stratum");
  917. unsetenv("freq_drift_ppm");
  918. unsetenv("poll_interval");
  919. unsetenv("offset");
  920. free(env1);
  921. free(env2);
  922. free(env3);
  923. free(env4);
  924. }
  925. static NOINLINE void
  926. step_time(double offset)
  927. {
  928. llist_t *item;
  929. double dtime;
  930. struct timeval tvc, tvn;
  931. char buf[sizeof("yyyy-mm-dd hh:mm:ss") + /*paranoia:*/ 4];
  932. time_t tval;
  933. gettimeofday(&tvc, NULL); /* never fails */
  934. dtime = tvc.tv_sec + (1.0e-6 * tvc.tv_usec) + offset;
  935. d_to_tv(dtime, &tvn);
  936. if (settimeofday(&tvn, NULL) == -1)
  937. bb_perror_msg_and_die("settimeofday");
  938. VERB2 {
  939. tval = tvc.tv_sec;
  940. strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
  941. bb_error_msg("current time is %s.%06u", buf, (unsigned)tvc.tv_usec);
  942. }
  943. tval = tvn.tv_sec;
  944. strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
  945. bb_error_msg("setting time to %s.%06u (offset %+fs)", buf, (unsigned)tvn.tv_usec, offset);
  946. //maybe? G.FREQHOLD_cnt = 0;
  947. /* Correct various fields which contain time-relative values: */
  948. /* Globals: */
  949. G.cur_time += offset;
  950. G.last_update_recv_time += offset;
  951. G.last_script_run += offset;
  952. /* p->lastpkt_recv_time, p->next_action_time and such: */
  953. for (item = G.ntp_peers; item != NULL; item = item->link) {
  954. peer_t *pp = (peer_t *) item->data;
  955. reset_peer_stats(pp, offset);
  956. //bb_error_msg("offset:%+f pp->next_action_time:%f -> %f",
  957. // offset, pp->next_action_time, pp->next_action_time + offset);
  958. pp->next_action_time += offset;
  959. if (pp->p_fd >= 0) {
  960. /* We wait for reply from this peer too.
  961. * But due to step we are doing, reply's data is no longer
  962. * useful (in fact, it'll be bogus). Stop waiting for it.
  963. */
  964. close(pp->p_fd);
  965. pp->p_fd = -1;
  966. set_next(pp, RETRY_INTERVAL);
  967. }
  968. }
  969. }
  970. static void clamp_pollexp_and_set_MAXSTRAT(void)
  971. {
  972. if (G.poll_exp < MINPOLL)
  973. G.poll_exp = MINPOLL;
  974. if (G.poll_exp > BIGPOLL)
  975. G.poll_exp = BIGPOLL;
  976. G.polladj_count = 0;
  977. G.stratum = MAXSTRAT;
  978. }
  979. /*
  980. * Selection and clustering, and their helpers
  981. */
  982. typedef struct {
  983. peer_t *p;
  984. int type;
  985. double edge;
  986. double opt_rd; /* optimization */
  987. } point_t;
  988. static int
  989. compare_point_edge(const void *aa, const void *bb)
  990. {
  991. const point_t *a = aa;
  992. const point_t *b = bb;
  993. if (a->edge < b->edge) {
  994. return -1;
  995. }
  996. return (a->edge > b->edge);
  997. }
  998. typedef struct {
  999. peer_t *p;
  1000. double metric;
  1001. } survivor_t;
  1002. static int
  1003. compare_survivor_metric(const void *aa, const void *bb)
  1004. {
  1005. const survivor_t *a = aa;
  1006. const survivor_t *b = bb;
  1007. if (a->metric < b->metric) {
  1008. return -1;
  1009. }
  1010. return (a->metric > b->metric);
  1011. }
  1012. static int
  1013. fit(peer_t *p, double rd)
  1014. {
  1015. if ((p->reachable_bits & (p->reachable_bits-1)) == 0) {
  1016. /* One or zero bits in reachable_bits */
  1017. VERB4 bb_error_msg("peer %s unfit for selection: unreachable", p->p_dotted);
  1018. return 0;
  1019. }
  1020. #if 0 /* we filter out such packets earlier */
  1021. if ((p->lastpkt_status & LI_ALARM) == LI_ALARM
  1022. || p->lastpkt_stratum >= MAXSTRAT
  1023. ) {
  1024. VERB4 bb_error_msg("peer %s unfit for selection: bad status/stratum", p->p_dotted);
  1025. return 0;
  1026. }
  1027. #endif
  1028. /* rd is root_distance(p) */
  1029. if (rd > MAXDIST + FREQ_TOLERANCE * (1 << G.poll_exp)) {
  1030. VERB4 bb_error_msg("peer %s unfit for selection: root distance too high", p->p_dotted);
  1031. return 0;
  1032. }
  1033. //TODO
  1034. // /* Do we have a loop? */
  1035. // if (p->refid == p->dstaddr || p->refid == s.refid)
  1036. // return 0;
  1037. return 1;
  1038. }
  1039. static peer_t*
  1040. select_and_cluster(void)
  1041. {
  1042. peer_t *p;
  1043. llist_t *item;
  1044. int i, j;
  1045. int size = 3 * G.peer_cnt;
  1046. /* for selection algorithm */
  1047. point_t point[size];
  1048. unsigned num_points, num_candidates;
  1049. double low, high;
  1050. unsigned num_falsetickers;
  1051. /* for cluster algorithm */
  1052. survivor_t survivor[size];
  1053. unsigned num_survivors;
  1054. /* Selection */
  1055. num_points = 0;
  1056. item = G.ntp_peers;
  1057. while (item != NULL) {
  1058. double rd, offset;
  1059. p = (peer_t *) item->data;
  1060. rd = root_distance(p);
  1061. offset = p->filter_offset;
  1062. if (!fit(p, rd)) {
  1063. item = item->link;
  1064. continue;
  1065. }
  1066. VERB5 bb_error_msg("interval: [%f %f %f] %s",
  1067. offset - rd,
  1068. offset,
  1069. offset + rd,
  1070. p->p_dotted
  1071. );
  1072. point[num_points].p = p;
  1073. point[num_points].type = -1;
  1074. point[num_points].edge = offset - rd;
  1075. point[num_points].opt_rd = rd;
  1076. num_points++;
  1077. point[num_points].p = p;
  1078. point[num_points].type = 0;
  1079. point[num_points].edge = offset;
  1080. point[num_points].opt_rd = rd;
  1081. num_points++;
  1082. point[num_points].p = p;
  1083. point[num_points].type = 1;
  1084. point[num_points].edge = offset + rd;
  1085. point[num_points].opt_rd = rd;
  1086. num_points++;
  1087. item = item->link;
  1088. }
  1089. num_candidates = num_points / 3;
  1090. if (num_candidates == 0) {
  1091. VERB3 bb_error_msg("no valid datapoints%s", ", no peer selected");
  1092. return NULL;
  1093. }
  1094. //TODO: sorting does not seem to be done in reference code
  1095. qsort(point, num_points, sizeof(point[0]), compare_point_edge);
  1096. /* Start with the assumption that there are no falsetickers.
  1097. * Attempt to find a nonempty intersection interval containing
  1098. * the midpoints of all truechimers.
  1099. * If a nonempty interval cannot be found, increase the number
  1100. * of assumed falsetickers by one and try again.
  1101. * If a nonempty interval is found and the number of falsetickers
  1102. * is less than the number of truechimers, a majority has been found
  1103. * and the midpoint of each truechimer represents
  1104. * the candidates available to the cluster algorithm.
  1105. */
  1106. num_falsetickers = 0;
  1107. while (1) {
  1108. int c;
  1109. unsigned num_midpoints = 0;
  1110. low = 1 << 9;
  1111. high = - (1 << 9);
  1112. c = 0;
  1113. for (i = 0; i < num_points; i++) {
  1114. /* We want to do:
  1115. * if (point[i].type == -1) c++;
  1116. * if (point[i].type == 1) c--;
  1117. * and it's simpler to do it this way:
  1118. */
  1119. c -= point[i].type;
  1120. if (c >= num_candidates - num_falsetickers) {
  1121. /* If it was c++ and it got big enough... */
  1122. low = point[i].edge;
  1123. break;
  1124. }
  1125. if (point[i].type == 0)
  1126. num_midpoints++;
  1127. }
  1128. c = 0;
  1129. for (i = num_points-1; i >= 0; i--) {
  1130. c += point[i].type;
  1131. if (c >= num_candidates - num_falsetickers) {
  1132. high = point[i].edge;
  1133. break;
  1134. }
  1135. if (point[i].type == 0)
  1136. num_midpoints++;
  1137. }
  1138. /* If the number of midpoints is greater than the number
  1139. * of allowed falsetickers, the intersection contains at
  1140. * least one truechimer with no midpoint - bad.
  1141. * Also, interval should be nonempty.
  1142. */
  1143. if (num_midpoints <= num_falsetickers && low < high)
  1144. break;
  1145. num_falsetickers++;
  1146. if (num_falsetickers * 2 >= num_candidates) {
  1147. VERB3 bb_error_msg("falsetickers:%d, candidates:%d%s",
  1148. num_falsetickers, num_candidates,
  1149. ", no peer selected");
  1150. return NULL;
  1151. }
  1152. }
  1153. VERB4 bb_error_msg("selected interval: [%f, %f]; candidates:%d falsetickers:%d",
  1154. low, high, num_candidates, num_falsetickers);
  1155. /* Clustering */
  1156. /* Construct a list of survivors (p, metric)
  1157. * from the chime list, where metric is dominated
  1158. * first by stratum and then by root distance.
  1159. * All other things being equal, this is the order of preference.
  1160. */
  1161. num_survivors = 0;
  1162. for (i = 0; i < num_points; i++) {
  1163. if (point[i].edge < low || point[i].edge > high)
  1164. continue;
  1165. p = point[i].p;
  1166. survivor[num_survivors].p = p;
  1167. /* x.opt_rd == root_distance(p); */
  1168. survivor[num_survivors].metric = MAXDIST * p->lastpkt_stratum + point[i].opt_rd;
  1169. VERB5 bb_error_msg("survivor[%d] metric:%f peer:%s",
  1170. num_survivors, survivor[num_survivors].metric, p->p_dotted);
  1171. num_survivors++;
  1172. }
  1173. /* There must be at least MIN_SELECTED survivors to satisfy the
  1174. * correctness assertions. Ordinarily, the Byzantine criteria
  1175. * require four survivors, but for the demonstration here, one
  1176. * is acceptable.
  1177. */
  1178. if (num_survivors < MIN_SELECTED) {
  1179. VERB3 bb_error_msg("survivors:%d%s",
  1180. num_survivors,
  1181. ", no peer selected");
  1182. return NULL;
  1183. }
  1184. //looks like this is ONLY used by the fact that later we pick survivor[0].
  1185. //we can avoid sorting then, just find the minimum once!
  1186. qsort(survivor, num_survivors, sizeof(survivor[0]), compare_survivor_metric);
  1187. /* For each association p in turn, calculate the selection
  1188. * jitter p->sjitter as the square root of the sum of squares
  1189. * (p->offset - q->offset) over all q associations. The idea is
  1190. * to repeatedly discard the survivor with maximum selection
  1191. * jitter until a termination condition is met.
  1192. */
  1193. while (1) {
  1194. unsigned max_idx = max_idx;
  1195. double max_selection_jitter = max_selection_jitter;
  1196. double min_jitter = min_jitter;
  1197. if (num_survivors <= MIN_CLUSTERED) {
  1198. VERB4 bb_error_msg("num_survivors %d <= %d, not discarding more",
  1199. num_survivors, MIN_CLUSTERED);
  1200. break;
  1201. }
  1202. /* To make sure a few survivors are left
  1203. * for the clustering algorithm to chew on,
  1204. * we stop if the number of survivors
  1205. * is less than or equal to MIN_CLUSTERED (3).
  1206. */
  1207. for (i = 0; i < num_survivors; i++) {
  1208. double selection_jitter_sq;
  1209. p = survivor[i].p;
  1210. if (i == 0 || p->filter_jitter < min_jitter)
  1211. min_jitter = p->filter_jitter;
  1212. selection_jitter_sq = 0;
  1213. for (j = 0; j < num_survivors; j++) {
  1214. peer_t *q = survivor[j].p;
  1215. selection_jitter_sq += SQUARE(p->filter_offset - q->filter_offset);
  1216. }
  1217. if (i == 0 || selection_jitter_sq > max_selection_jitter) {
  1218. max_selection_jitter = selection_jitter_sq;
  1219. max_idx = i;
  1220. }
  1221. VERB6 bb_error_msg("survivor %d selection_jitter^2:%f",
  1222. i, selection_jitter_sq);
  1223. }
  1224. max_selection_jitter = SQRT(max_selection_jitter / num_survivors);
  1225. VERB5 bb_error_msg("max_selection_jitter (at %d):%f min_jitter:%f",
  1226. max_idx, max_selection_jitter, min_jitter);
  1227. /* If the maximum selection jitter is less than the
  1228. * minimum peer jitter, then tossing out more survivors
  1229. * will not lower the minimum peer jitter, so we might
  1230. * as well stop.
  1231. */
  1232. if (max_selection_jitter < min_jitter) {
  1233. VERB4 bb_error_msg("max_selection_jitter:%f < min_jitter:%f, num_survivors:%d, not discarding more",
  1234. max_selection_jitter, min_jitter, num_survivors);
  1235. break;
  1236. }
  1237. /* Delete survivor[max_idx] from the list
  1238. * and go around again.
  1239. */
  1240. VERB6 bb_error_msg("dropping survivor %d", max_idx);
  1241. num_survivors--;
  1242. while (max_idx < num_survivors) {
  1243. survivor[max_idx] = survivor[max_idx + 1];
  1244. max_idx++;
  1245. }
  1246. }
  1247. if (0) {
  1248. /* Combine the offsets of the clustering algorithm survivors
  1249. * using a weighted average with weight determined by the root
  1250. * distance. Compute the selection jitter as the weighted RMS
  1251. * difference between the first survivor and the remaining
  1252. * survivors. In some cases the inherent clock jitter can be
  1253. * reduced by not using this algorithm, especially when frequent
  1254. * clockhopping is involved. bbox: thus we don't do it.
  1255. */
  1256. double x, y, z, w;
  1257. y = z = w = 0;
  1258. for (i = 0; i < num_survivors; i++) {
  1259. p = survivor[i].p;
  1260. x = root_distance(p);
  1261. y += 1 / x;
  1262. z += p->filter_offset / x;
  1263. w += SQUARE(p->filter_offset - survivor[0].p->filter_offset) / x;
  1264. }
  1265. //G.cluster_offset = z / y;
  1266. //G.cluster_jitter = SQRT(w / y);
  1267. }
  1268. /* Pick the best clock. If the old system peer is on the list
  1269. * and at the same stratum as the first survivor on the list,
  1270. * then don't do a clock hop. Otherwise, select the first
  1271. * survivor on the list as the new system peer.
  1272. */
  1273. p = survivor[0].p;
  1274. if (G.last_update_peer
  1275. && G.last_update_peer->lastpkt_stratum <= p->lastpkt_stratum
  1276. ) {
  1277. /* Starting from 1 is ok here */
  1278. for (i = 1; i < num_survivors; i++) {
  1279. if (G.last_update_peer == survivor[i].p) {
  1280. VERB5 bb_error_msg("keeping old synced peer");
  1281. p = G.last_update_peer;
  1282. goto keep_old;
  1283. }
  1284. }
  1285. }
  1286. G.last_update_peer = p;
  1287. keep_old:
  1288. VERB4 bb_error_msg("selected peer %s filter_offset:%+f age:%f",
  1289. p->p_dotted,
  1290. p->filter_offset,
  1291. G.cur_time - p->lastpkt_recv_time
  1292. );
  1293. return p;
  1294. }
  1295. /*
  1296. * Local clock discipline and its helpers
  1297. */
  1298. static void
  1299. set_new_values(int disc_state, double offset, double recv_time)
  1300. {
  1301. /* Enter new state and set state variables. Note we use the time
  1302. * of the last clock filter sample, which must be earlier than
  1303. * the current time.
  1304. */
  1305. VERB4 bb_error_msg("disc_state=%d last update offset=%f recv_time=%f",
  1306. disc_state, offset, recv_time);
  1307. G.discipline_state = disc_state;
  1308. G.last_update_offset = offset;
  1309. G.last_update_recv_time = recv_time;
  1310. }
  1311. /* Return: -1: decrease poll interval, 0: leave as is, 1: increase */
  1312. static NOINLINE int
  1313. update_local_clock(peer_t *p)
  1314. {
  1315. int rc;
  1316. struct timex tmx;
  1317. /* Note: can use G.cluster_offset instead: */
  1318. double offset = p->filter_offset;
  1319. double recv_time = p->lastpkt_recv_time;
  1320. double abs_offset;
  1321. #if !USING_KERNEL_PLL_LOOP
  1322. double freq_drift;
  1323. #endif
  1324. #if !USING_KERNEL_PLL_LOOP || USING_INITIAL_FREQ_ESTIMATION
  1325. double since_last_update;
  1326. #endif
  1327. double etemp, dtemp;
  1328. abs_offset = fabs(offset);
  1329. #if 0
  1330. /* If needed, -S script can do it by looking at $offset
  1331. * env var and killing parent */
  1332. /* If the offset is too large, give up and go home */
  1333. if (abs_offset > PANIC_THRESHOLD) {
  1334. bb_error_msg_and_die("offset %f far too big, exiting", offset);
  1335. }
  1336. #endif
  1337. /* If this is an old update, for instance as the result
  1338. * of a system peer change, avoid it. We never use
  1339. * an old sample or the same sample twice.
  1340. */
  1341. if (recv_time <= G.last_update_recv_time) {
  1342. VERB3 bb_error_msg("update from %s: same or older datapoint, not using it",
  1343. p->p_dotted);
  1344. return 0; /* "leave poll interval as is" */
  1345. }
  1346. /* Clock state machine transition function. This is where the
  1347. * action is and defines how the system reacts to large time
  1348. * and frequency errors.
  1349. */
  1350. #if !USING_KERNEL_PLL_LOOP || USING_INITIAL_FREQ_ESTIMATION
  1351. since_last_update = recv_time - G.reftime;
  1352. #endif
  1353. #if !USING_KERNEL_PLL_LOOP
  1354. freq_drift = 0;
  1355. #endif
  1356. #if USING_INITIAL_FREQ_ESTIMATION
  1357. if (G.discipline_state == STATE_FREQ) {
  1358. /* Ignore updates until the stepout threshold */
  1359. if (since_last_update < WATCH_THRESHOLD) {
  1360. VERB4 bb_error_msg("measuring drift, datapoint ignored, %f sec remains",
  1361. WATCH_THRESHOLD - since_last_update);
  1362. return 0; /* "leave poll interval as is" */
  1363. }
  1364. # if !USING_KERNEL_PLL_LOOP
  1365. freq_drift = (offset - G.last_update_offset) / since_last_update;
  1366. # endif
  1367. }
  1368. #endif
  1369. /* There are two main regimes: when the
  1370. * offset exceeds the step threshold and when it does not.
  1371. */
  1372. if (abs_offset > STEP_THRESHOLD) {
  1373. #if 0
  1374. double remains;
  1375. // This "spike state" seems to be useless, peer selection already drops
  1376. // occassional "bad" datapoints. If we are here, there were _many_
  1377. // large offsets. When a few first large offsets are seen,
  1378. // we end up in "no valid datapoints, no peer selected" state.
  1379. // Only when enough of them are seen (which means it's not a fluke),
  1380. // we end up here. Looks like _our_ clock is off.
  1381. switch (G.discipline_state) {
  1382. case STATE_SYNC:
  1383. /* The first outlyer: ignore it, switch to SPIK state */
  1384. VERB3 bb_error_msg("update from %s: offset:%+f, spike%s",
  1385. p->p_dotted, offset,
  1386. "");
  1387. G.discipline_state = STATE_SPIK;
  1388. return -1; /* "decrease poll interval" */
  1389. case STATE_SPIK:
  1390. /* Ignore succeeding outlyers until either an inlyer
  1391. * is found or the stepout threshold is exceeded.
  1392. */
  1393. remains = WATCH_THRESHOLD - since_last_update;
  1394. if (remains > 0) {
  1395. VERB3 bb_error_msg("update from %s: offset:%+f, spike%s",
  1396. p->p_dotted, offset,
  1397. ", datapoint ignored");
  1398. return -1; /* "decrease poll interval" */
  1399. }
  1400. /* fall through: we need to step */
  1401. } /* switch */
  1402. #endif
  1403. /* Step the time and clamp down the poll interval.
  1404. *
  1405. * In NSET state an initial frequency correction is
  1406. * not available, usually because the frequency file has
  1407. * not yet been written. Since the time is outside the
  1408. * capture range, the clock is stepped. The frequency
  1409. * will be set directly following the stepout interval.
  1410. *
  1411. * In FSET state the initial frequency has been set
  1412. * from the frequency file. Since the time is outside
  1413. * the capture range, the clock is stepped immediately,
  1414. * rather than after the stepout interval. Guys get
  1415. * nervous if it takes 17 minutes to set the clock for
  1416. * the first time.
  1417. *
  1418. * In SPIK state the stepout threshold has expired and
  1419. * the phase is still above the step threshold. Note
  1420. * that a single spike greater than the step threshold
  1421. * is always suppressed, even at the longer poll
  1422. * intervals.
  1423. */
  1424. VERB4 bb_error_msg("stepping time by %+f; poll_exp=MINPOLL", offset);
  1425. step_time(offset);
  1426. if (option_mask32 & OPT_q) {
  1427. /* We were only asked to set time once. Done. */
  1428. exit(0);
  1429. }
  1430. clamp_pollexp_and_set_MAXSTRAT();
  1431. run_script("step", offset);
  1432. recv_time += offset;
  1433. #if USING_INITIAL_FREQ_ESTIMATION
  1434. if (G.discipline_state == STATE_NSET) {
  1435. set_new_values(STATE_FREQ, /*offset:*/ 0, recv_time);
  1436. return 1; /* "ok to increase poll interval" */
  1437. }
  1438. #endif
  1439. abs_offset = offset = 0;
  1440. set_new_values(STATE_SYNC, offset, recv_time);
  1441. } else { /* abs_offset <= STEP_THRESHOLD */
  1442. /* The ratio is calculated before jitter is updated to make
  1443. * poll adjust code more sensitive to large offsets.
  1444. */
  1445. G.offset_to_jitter_ratio = abs_offset / G.discipline_jitter;
  1446. /* Compute the clock jitter as the RMS of exponentially
  1447. * weighted offset differences. Used by the poll adjust code.
  1448. */
  1449. etemp = SQUARE(G.discipline_jitter);
  1450. dtemp = SQUARE(offset - G.last_update_offset);
  1451. G.discipline_jitter = SQRT(etemp + (dtemp - etemp) / AVG);
  1452. if (G.discipline_jitter < G_precision_sec)
  1453. G.discipline_jitter = G_precision_sec;
  1454. switch (G.discipline_state) {
  1455. case STATE_NSET:
  1456. if (option_mask32 & OPT_q) {
  1457. /* We were only asked to set time once.
  1458. * The clock is precise enough, no need to step.
  1459. */
  1460. exit(0);
  1461. }
  1462. #if USING_INITIAL_FREQ_ESTIMATION
  1463. /* This is the first update received and the frequency
  1464. * has not been initialized. The first thing to do
  1465. * is directly measure the oscillator frequency.
  1466. */
  1467. set_new_values(STATE_FREQ, offset, recv_time);
  1468. #else
  1469. set_new_values(STATE_SYNC, offset, recv_time);
  1470. #endif
  1471. VERB4 bb_error_msg("transitioning to FREQ, datapoint ignored");
  1472. return 0; /* "leave poll interval as is" */
  1473. #if 0 /* this is dead code for now */
  1474. case STATE_FSET:
  1475. /* This is the first update and the frequency
  1476. * has been initialized. Adjust the phase, but
  1477. * don't adjust the frequency until the next update.
  1478. */
  1479. set_new_values(STATE_SYNC, offset, recv_time);
  1480. /* freq_drift remains 0 */
  1481. break;
  1482. #endif
  1483. #if USING_INITIAL_FREQ_ESTIMATION
  1484. case STATE_FREQ:
  1485. /* since_last_update >= WATCH_THRESHOLD, we waited enough.
  1486. * Correct the phase and frequency and switch to SYNC state.
  1487. * freq_drift was already estimated (see code above)
  1488. */
  1489. set_new_values(STATE_SYNC, offset, recv_time);
  1490. break;
  1491. #endif
  1492. default:
  1493. #if !USING_KERNEL_PLL_LOOP
  1494. /* Compute freq_drift due to PLL and FLL contributions.
  1495. *
  1496. * The FLL and PLL frequency gain constants
  1497. * depend on the poll interval and Allan
  1498. * intercept. The FLL is not used below one-half
  1499. * the Allan intercept. Above that the loop gain
  1500. * increases in steps to 1 / AVG.
  1501. */
  1502. if ((1 << G.poll_exp) > ALLAN / 2) {
  1503. etemp = FLL - G.poll_exp;
  1504. if (etemp < AVG)
  1505. etemp = AVG;
  1506. freq_drift += (offset - G.last_update_offset) / (MAXD(since_last_update, ALLAN) * etemp);
  1507. }
  1508. /* For the PLL the integration interval
  1509. * (numerator) is the minimum of the update
  1510. * interval and poll interval. This allows
  1511. * oversampling, but not undersampling.
  1512. */
  1513. etemp = MIND(since_last_update, (1 << G.poll_exp));
  1514. dtemp = (4 * PLL) << G.poll_exp;
  1515. freq_drift += offset * etemp / SQUARE(dtemp);
  1516. #endif
  1517. set_new_values(STATE_SYNC, offset, recv_time);
  1518. break;
  1519. }
  1520. if (G.stratum != p->lastpkt_stratum + 1) {
  1521. G.stratum = p->lastpkt_stratum + 1;
  1522. run_script("stratum", offset);
  1523. }
  1524. }
  1525. G.reftime = G.cur_time;
  1526. G.ntp_status = p->lastpkt_status;
  1527. G.refid = p->lastpkt_refid;
  1528. G.rootdelay = p->lastpkt_rootdelay + p->lastpkt_delay;
  1529. dtemp = p->filter_jitter; // SQRT(SQUARE(p->filter_jitter) + SQUARE(G.cluster_jitter));
  1530. dtemp += MAXD(p->filter_dispersion + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time) + abs_offset, MINDISP);
  1531. G.rootdisp = p->lastpkt_rootdisp + dtemp;
  1532. VERB4 bb_error_msg("updating leap/refid/reftime/rootdisp from peer %s", p->p_dotted);
  1533. /* We are in STATE_SYNC now, but did not do adjtimex yet.
  1534. * (Any other state does not reach this, they all return earlier)
  1535. * By this time, freq_drift and offset are set
  1536. * to values suitable for adjtimex.
  1537. */
  1538. #if !USING_KERNEL_PLL_LOOP
  1539. /* Calculate the new frequency drift and frequency stability (wander).
  1540. * Compute the clock wander as the RMS of exponentially weighted
  1541. * frequency differences. This is not used directly, but can,
  1542. * along with the jitter, be a highly useful monitoring and
  1543. * debugging tool.
  1544. */
  1545. dtemp = G.discipline_freq_drift + freq_drift;
  1546. G.discipline_freq_drift = MAXD(MIND(MAXDRIFT, dtemp), -MAXDRIFT);
  1547. etemp = SQUARE(G.discipline_wander);
  1548. dtemp = SQUARE(dtemp);
  1549. G.discipline_wander = SQRT(etemp + (dtemp - etemp) / AVG);
  1550. VERB4 bb_error_msg("discipline freq_drift=%.9f(int:%ld corr:%e) wander=%f",
  1551. G.discipline_freq_drift,
  1552. (long)(G.discipline_freq_drift * 65536e6),
  1553. freq_drift,
  1554. G.discipline_wander);
  1555. #endif
  1556. VERB4 {
  1557. memset(&tmx, 0, sizeof(tmx));
  1558. if (adjtimex(&tmx) < 0)
  1559. bb_perror_msg_and_die("adjtimex");
  1560. bb_error_msg("p adjtimex freq:%ld offset:%+ld status:0x%x tc:%ld",
  1561. tmx.freq, tmx.offset, tmx.status, tmx.constant);
  1562. }
  1563. memset(&tmx, 0, sizeof(tmx));
  1564. #if 0
  1565. //doesn't work, offset remains 0 (!) in kernel:
  1566. //ntpd: set adjtimex freq:1786097 tmx.offset:77487
  1567. //ntpd: prev adjtimex freq:1786097 tmx.offset:0
  1568. //ntpd: cur adjtimex freq:1786097 tmx.offset:0
  1569. tmx.modes = ADJ_FREQUENCY | ADJ_OFFSET;
  1570. /* 65536 is one ppm */
  1571. tmx.freq = G.discipline_freq_drift * 65536e6;
  1572. #endif
  1573. tmx.modes = ADJ_OFFSET | ADJ_STATUS | ADJ_TIMECONST;// | ADJ_MAXERROR | ADJ_ESTERROR;
  1574. tmx.offset = (long)(offset * 1000000); /* usec */
  1575. if (SLEW_THRESHOLD < STEP_THRESHOLD) {
  1576. if (tmx.offset > (long)(SLEW_THRESHOLD * 1000000)) {
  1577. tmx.offset = (long)(SLEW_THRESHOLD * 1000000);
  1578. }
  1579. if (tmx.offset < -(long)(SLEW_THRESHOLD * 1000000)) {
  1580. tmx.offset = -(long)(SLEW_THRESHOLD * 1000000);
  1581. }
  1582. }
  1583. tmx.status = STA_PLL;
  1584. if (G.FREQHOLD_cnt != 0) {
  1585. /* man adjtimex on STA_FREQHOLD:
  1586. * "Normally adjustments made via ADJ_OFFSET result in dampened
  1587. * frequency adjustments also being made.
  1588. * This flag prevents the small frequency adjustment from being
  1589. * made when correcting for an ADJ_OFFSET value."
  1590. *
  1591. * Use this flag for a few first adjustments at the beginning
  1592. * of ntpd execution, otherwise even relatively small initial
  1593. * offset tend to cause largish changes to in-kernel tmx.freq.
  1594. * If ntpd was restarted due to e.g. switch to another network,
  1595. * this destroys already well-established tmx.freq value.
  1596. */
  1597. if (G.FREQHOLD_cnt < 0) {
  1598. /* Initialize it */
  1599. // Example: a laptop whose clock runs slower when hibernated,
  1600. // after wake up it still has good tmx.freq, but accumulated ~0.5 sec offset:
  1601. // Run with code where initial G.FREQHOLD_cnt was always 8:
  1602. //15:17:52.947 no valid datapoints, no peer selected
  1603. //15:17:56.515 update from:<IP> offset:+0.485133 delay:0.157762 jitter:0.209310 clock drift:-1.393ppm tc:4
  1604. //15:17:57.719 update from:<IP> offset:+0.483825 delay:0.158070 jitter:0.181159 clock drift:-1.393ppm tc:4
  1605. //15:17:59.925 update from:<IP> offset:+0.479504 delay:0.158147 jitter:0.156657 clock drift:-1.393ppm tc:4
  1606. //15:18:33.322 update from:<IP> offset:+0.428119 delay:0.158317 jitter:0.138071 clock drift:-1.393ppm tc:4
  1607. //15:19:06.718 update from:<IP> offset:+0.376932 delay:0.158276 jitter:0.122075 clock drift:-1.393ppm tc:4
  1608. //15:19:39.114 update from:<IP> offset:+0.327022 delay:0.158384 jitter:0.108538 clock drift:-1.393ppm tc:4
  1609. //15:20:12.715 update from:<IP> offset:+0.275596 delay:0.158297 jitter:0.097292 clock drift:-1.393ppm tc:4
  1610. //15:20:45.111 update from:<IP> offset:+0.225715 delay:0.158271 jitter:0.087841 clock drift:-1.393ppm tc:4
  1611. // If allwed to continue, it would start increasing tmx.freq now.
  1612. // Instead, it was ^Ced, and started anew:
  1613. //15:21:15.043 no valid datapoints, no peer selected
  1614. //15:21:17.408 update from:<IP> offset:+0.175910 delay:0.158314 jitter:0.076683 clock drift:-1.393ppm tc:4
  1615. //15:21:19.774 update from:<IP> offset:+0.171784 delay:0.158401 jitter:0.066436 clock drift:-1.393ppm tc:4
  1616. //15:21:22.140 update from:<IP> offset:+0.171660 delay:0.158592 jitter:0.057536 clock drift:-1.393ppm tc:4
  1617. //15:21:22.140 update from:<IP> offset:+0.167126 delay:0.158507 jitter:0.049792 clock drift:-1.393ppm tc:4
  1618. //15:21:55.696 update from:<IP> offset:+0.115223 delay:0.158277 jitter:0.050240 clock drift:-1.393ppm tc:4
  1619. //15:22:29.093 update from:<IP> offset:+0.068051 delay:0.158243 jitter:0.049405 clock drift:-1.393ppm tc:5
  1620. //15:23:02.490 update from:<IP> offset:+0.051632 delay:0.158215 jitter:0.043545 clock drift:-1.393ppm tc:5
  1621. //15:23:34.726 update from:<IP> offset:+0.039984 delay:0.158157 jitter:0.038106 clock drift:-1.393ppm tc:5
  1622. // STA_FREQHOLD no longer set, started increasing tmx.freq now:
  1623. //15:24:06.961 update from:<IP> offset:+0.030968 delay:0.158190 jitter:0.033306 clock drift:+2.387ppm tc:5
  1624. //15:24:40.357 update from:<IP> offset:+0.023648 delay:0.158211 jitter:0.029072 clock drift:+5.454ppm tc:5
  1625. //15:25:13.774 update from:<IP> offset:+0.018068 delay:0.157660 jitter:0.025288 clock drift:+7.728ppm tc:5
  1626. //15:26:19.173 update from:<IP> offset:+0.010057 delay:0.157969 jitter:0.022255 clock drift:+8.361ppm tc:6
  1627. //15:27:26.602 update from:<IP> offset:+0.006737 delay:0.158103 jitter:0.019316 clock drift:+8.792ppm tc:6
  1628. //15:28:33.030 update from:<IP> offset:+0.004513 delay:0.158294 jitter:0.016765 clock drift:+9.080ppm tc:6
  1629. //15:29:40.617 update from:<IP> offset:+0.002787 delay:0.157745 jitter:0.014543 clock drift:+9.258ppm tc:6
  1630. //15:30:47.045 update from:<IP> offset:+0.001324 delay:0.157709 jitter:0.012594 clock drift:+9.342ppm tc:6
  1631. //15:31:53.473 update from:<IP> offset:+0.000007 delay:0.158142 jitter:0.010922 clock drift:+9.343ppm tc:6
  1632. //15:32:58.902 update from:<IP> offset:-0.000728 delay:0.158222 jitter:0.009454 clock drift:+9.298ppm tc:6
  1633. /*
  1634. * This expression would choose 15 in the above example.
  1635. */
  1636. G.FREQHOLD_cnt = 8 + ((unsigned)(abs(tmx.offset)) >> 16);
  1637. }
  1638. G.FREQHOLD_cnt--;
  1639. tmx.status |= STA_FREQHOLD;
  1640. }
  1641. if (G.ntp_status & LI_PLUSSEC)
  1642. tmx.status |= STA_INS;
  1643. if (G.ntp_status & LI_MINUSSEC)
  1644. tmx.status |= STA_DEL;
  1645. tmx.constant = (int)G.poll_exp - 4;
  1646. /* EXPERIMENTAL.
  1647. * The below if statement should be unnecessary, but...
  1648. * It looks like Linux kernel's PLL is far too gentle in changing
  1649. * tmx.freq in response to clock offset. Offset keeps growing
  1650. * and eventually we fall back to smaller poll intervals.
  1651. * We can make correction more aggressive (about x2) by supplying
  1652. * PLL time constant which is one less than the real one.
  1653. * To be on a safe side, let's do it only if offset is significantly
  1654. * larger than jitter.
  1655. */
  1656. if (G.offset_to_jitter_ratio >= TIMECONST_HACK_GATE)
  1657. tmx.constant--;
  1658. if (tmx.constant < 0)
  1659. tmx.constant = 0;
  1660. //tmx.esterror = (uint32_t)(clock_jitter * 1e6);
  1661. //tmx.maxerror = (uint32_t)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
  1662. rc = adjtimex(&tmx);
  1663. if (rc < 0)
  1664. bb_perror_msg_and_die("adjtimex");
  1665. /* NB: here kernel returns constant == G.poll_exp, not == G.poll_exp - 4.
  1666. * Not sure why. Perhaps it is normal.
  1667. */
  1668. VERB4 bb_error_msg("adjtimex:%d freq:%ld offset:%+ld status:0x%x",
  1669. rc, tmx.freq, tmx.offset, tmx.status);
  1670. G.kernel_freq_drift = tmx.freq / 65536;
  1671. VERB2 bb_error_msg("update from:%s offset:%+f delay:%f jitter:%f clock drift:%+.3fppm tc:%d",
  1672. p->p_dotted,
  1673. offset,
  1674. p->lastpkt_delay,
  1675. G.discipline_jitter,
  1676. (double)tmx.freq / 65536,
  1677. (int)tmx.constant
  1678. );
  1679. return 1; /* "ok to increase poll interval" */
  1680. }
  1681. /*
  1682. * We've got a new reply packet from a peer, process it
  1683. * (helpers first)
  1684. */
  1685. static unsigned
  1686. poll_interval(int upper_bound)
  1687. {
  1688. unsigned interval, r, mask;
  1689. interval = 1 << G.poll_exp;
  1690. if (interval > upper_bound)
  1691. interval = upper_bound;
  1692. mask = ((interval-1) >> 4) | 1;
  1693. r = rand();
  1694. interval += r & mask; /* ~ random(0..1) * interval/16 */
  1695. VERB4 bb_error_msg("chose poll interval:%u (poll_exp:%d)", interval, G.poll_exp);
  1696. return interval;
  1697. }
  1698. static void
  1699. adjust_poll(int count)
  1700. {
  1701. G.polladj_count += count;
  1702. if (G.polladj_count > POLLADJ_LIMIT) {
  1703. G.polladj_count = 0;
  1704. if (G.poll_exp < MAXPOLL) {
  1705. G.poll_exp++;
  1706. VERB4 bb_error_msg("polladj: discipline_jitter:%f ++poll_exp=%d",
  1707. G.discipline_jitter, G.poll_exp);
  1708. }
  1709. } else if (G.polladj_count < -POLLADJ_LIMIT || (count < 0 && G.poll_exp > BIGPOLL)) {
  1710. G.polladj_count = 0;
  1711. if (G.poll_exp > MINPOLL) {
  1712. llist_t *item;
  1713. G.poll_exp--;
  1714. /* Correct p->next_action_time in each peer
  1715. * which waits for sending, so that they send earlier.
  1716. * Old pp->next_action_time are on the order
  1717. * of t + (1 << old_poll_exp) + small_random,
  1718. * we simply need to subtract ~half of that.
  1719. */
  1720. for (item = G.ntp_peers; item != NULL; item = item->link) {
  1721. peer_t *pp = (peer_t *) item->data;
  1722. if (pp->p_fd < 0)
  1723. pp->next_action_time -= (1 << G.poll_exp);
  1724. }
  1725. VERB4 bb_error_msg("polladj: discipline_jitter:%f --poll_exp=%d",
  1726. G.discipline_jitter, G.poll_exp);
  1727. }
  1728. } else {
  1729. VERB4 bb_error_msg("polladj: count:%d", G.polladj_count);
  1730. }
  1731. }
  1732. static NOINLINE void
  1733. recv_and_process_peer_pkt(peer_t *p)
  1734. {
  1735. int rc;
  1736. ssize_t size;
  1737. msg_t msg;
  1738. double T1, T2, T3, T4;
  1739. double offset;
  1740. double prev_delay, delay;
  1741. unsigned interval;
  1742. datapoint_t *datapoint;
  1743. peer_t *q;
  1744. offset = 0;
  1745. /* We can recvfrom here and check from.IP, but some multihomed
  1746. * ntp servers reply from their *other IP*.
  1747. * TODO: maybe we should check at least what we can: from.port == 123?
  1748. */
  1749. recv_again:
  1750. size = recv(p->p_fd, &msg, sizeof(msg), MSG_DONTWAIT);
  1751. if (size < 0) {
  1752. if (errno == EINTR)
  1753. /* Signal caught */
  1754. goto recv_again;
  1755. if (errno == EAGAIN)
  1756. /* There was no packet after all
  1757. * (poll() returning POLLIN for a fd
  1758. * is not a ironclad guarantee that data is there)
  1759. */
  1760. return;
  1761. /*
  1762. * If you need a different handling for a specific
  1763. * errno, always explain it in comment.
  1764. */
  1765. bb_perror_msg_and_die("recv(%s) error", p->p_dotted);
  1766. }
  1767. if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
  1768. bb_error_msg("malformed packet received from %s", p->p_dotted);
  1769. return;
  1770. }
  1771. if (msg.m_orgtime.int_partl != p->p_xmt_msg.m_xmttime.int_partl
  1772. || msg.m_orgtime.fractionl != p->p_xmt_msg.m_xmttime.fractionl
  1773. ) {
  1774. /* Somebody else's packet */
  1775. return;
  1776. }
  1777. /* We do not expect any more packets from this peer for now.
  1778. * Closing the socket informs kernel about it.
  1779. * We open a new socket when we send a new query.
  1780. */
  1781. close(p->p_fd);
  1782. p->p_fd = -1;
  1783. if ((msg.m_status & LI_ALARM) == LI_ALARM
  1784. || msg.m_stratum == 0
  1785. || msg.m_stratum > NTP_MAXSTRATUM
  1786. ) {
  1787. bb_error_msg("reply from %s: peer is unsynced", p->p_dotted);
  1788. /*
  1789. * Stratum 0 responses may have commands in 32-bit m_refid field:
  1790. * "DENY", "RSTR" - peer does not like us at all,
  1791. * "RATE" - peer is overloaded, reduce polling freq.
  1792. * If poll interval is small, increase it.
  1793. */
  1794. if (G.poll_exp < BIGPOLL)
  1795. goto increase_interval;
  1796. goto pick_normal_interval;
  1797. }
  1798. // /* Verify valid root distance */
  1799. // if (msg.m_rootdelay / 2 + msg.m_rootdisp >= MAXDISP || p->lastpkt_reftime > msg.m_xmt)
  1800. // return; /* invalid header values */
  1801. /*
  1802. * From RFC 2030 (with a correction to the delay math):
  1803. *
  1804. * Timestamp Name ID When Generated
  1805. * ------------------------------------------------------------
  1806. * Originate Timestamp T1 time request sent by client
  1807. * Receive Timestamp T2 time request received by server
  1808. * Transmit Timestamp T3 time reply sent by server
  1809. * Destination Timestamp T4 time reply received by client
  1810. *
  1811. * The roundtrip delay and local clock offset are defined as
  1812. *
  1813. * delay = (T4 - T1) - (T3 - T2); offset = ((T2 - T1) + (T3 - T4)) / 2
  1814. */
  1815. T1 = p->p_xmttime;
  1816. T2 = lfp_to_d(msg.m_rectime);
  1817. T3 = lfp_to_d(msg.m_xmttime);
  1818. T4 = G.cur_time;
  1819. /* The delay calculation is a special case. In cases where the
  1820. * server and client clocks are running at different rates and
  1821. * with very fast networks, the delay can appear negative. In
  1822. * order to avoid violating the Principle of Least Astonishment,
  1823. * the delay is clamped not less than the system precision.
  1824. */
  1825. delay = (T4 - T1) - (T3 - T2);
  1826. if (delay < G_precision_sec)
  1827. delay = G_precision_sec;
  1828. /*
  1829. * If this packet's delay is much bigger than the last one,
  1830. * it's better to just ignore it than use its much less precise value.
  1831. */
  1832. prev_delay = p->p_raw_delay;
  1833. p->p_raw_delay = delay;
  1834. if (p->reachable_bits && delay > prev_delay * BAD_DELAY_GROWTH) {
  1835. bb_error_msg("reply from %s: delay %f is too high, ignoring", p->p_dotted, delay);
  1836. goto pick_normal_interval;
  1837. }
  1838. p->lastpkt_delay = delay;
  1839. p->lastpkt_recv_time = T4;
  1840. VERB6 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
  1841. p->lastpkt_status = msg.m_status;
  1842. p->lastpkt_stratum = msg.m_stratum;
  1843. p->lastpkt_rootdelay = sfp_to_d(msg.m_rootdelay);
  1844. p->lastpkt_rootdisp = sfp_to_d(msg.m_rootdisp);
  1845. p->lastpkt_refid = msg.m_refid;
  1846. p->datapoint_idx = p->reachable_bits ? (p->datapoint_idx + 1) % NUM_DATAPOINTS : 0;
  1847. datapoint = &p->filter_datapoint[p->datapoint_idx];
  1848. datapoint->d_recv_time = T4;
  1849. datapoint->d_offset = offset = ((T2 - T1) + (T3 - T4)) / 2;
  1850. datapoint->d_dispersion = LOG2D(msg.m_precision_exp) + G_precision_sec;
  1851. if (!p->reachable_bits) {
  1852. /* 1st datapoint ever - replicate offset in every element */
  1853. int i;
  1854. for (i = 0; i < NUM_DATAPOINTS; i++) {
  1855. p->filter_datapoint[i].d_offset = offset;
  1856. }
  1857. }
  1858. p->reachable_bits |= 1;
  1859. if ((MAX_VERBOSE && G.verbose) || (option_mask32 & OPT_w)) {
  1860. bb_error_msg("reply from %s: offset:%+f delay:%f status:0x%02x strat:%d refid:0x%08x rootdelay:%f reach:0x%02x",
  1861. p->p_dotted,
  1862. offset,
  1863. p->lastpkt_delay,
  1864. p->lastpkt_status,
  1865. p->lastpkt_stratum,
  1866. p->lastpkt_refid,
  1867. p->lastpkt_rootdelay,
  1868. p->reachable_bits
  1869. /* not shown: m_ppoll, m_precision_exp, m_rootdisp,
  1870. * m_reftime, m_orgtime, m_rectime, m_xmttime
  1871. */
  1872. );
  1873. }
  1874. /* Muck with statictics and update the clock */
  1875. filter_datapoints(p);
  1876. q = select_and_cluster();
  1877. rc = 0;
  1878. if (q) {
  1879. if (!(option_mask32 & OPT_w)) {
  1880. rc = update_local_clock(q);
  1881. #if 0
  1882. //Disabled this because there is a case where largish offsets
  1883. //are unavoidable: if network round-trip delay is, say, ~0.6s,
  1884. //error in offset estimation would be ~delay/2 ~= 0.3s.
  1885. //Thus, offsets will be usually in -0.3...0.3s range.
  1886. //In this case, this code would keep poll interval small,
  1887. //but it won't be helping.
  1888. //BIGOFF check below deals with a case of seeing multi-second offsets.
  1889. /* If drift is dangerously large, immediately
  1890. * drop poll interval one step down.
  1891. */
  1892. if (fabs(q->filter_offset) >= POLLDOWN_OFFSET) {
  1893. VERB4 bb_error_msg("offset:%+f > POLLDOWN_OFFSET", q->filter_offset);
  1894. adjust_poll(-POLLADJ_LIMIT * 3);
  1895. rc = 0;
  1896. }
  1897. #endif
  1898. }
  1899. } else {
  1900. /* No peer selected.
  1901. * If poll interval is small, increase it.
  1902. */
  1903. if (G.poll_exp < BIGPOLL)
  1904. goto increase_interval;
  1905. }
  1906. if (rc != 0) {
  1907. /* Adjust the poll interval by comparing the current offset
  1908. * with the clock jitter. If the offset is less than
  1909. * the clock jitter times a constant, then the averaging interval
  1910. * is increased, otherwise it is decreased. A bit of hysteresis
  1911. * helps calm the dance. Works best using burst mode.
  1912. */
  1913. if (rc > 0 && G.offset_to_jitter_ratio <= POLLADJ_GATE) {
  1914. /* was += G.poll_exp but it is a bit
  1915. * too optimistic for my taste at high poll_exp's */
  1916. increase_interval:
  1917. adjust_poll(MINPOLL);
  1918. } else {
  1919. VERB3 if (rc > 0)
  1920. bb_error_msg("want smaller interval: offset/jitter = %u",
  1921. G.offset_to_jitter_ratio);
  1922. adjust_poll(-G.poll_exp * 2);
  1923. }
  1924. }
  1925. /* Decide when to send new query for this peer */
  1926. pick_normal_interval:
  1927. interval = poll_interval(INT_MAX);
  1928. if (fabs(offset) >= BIGOFF && interval > BIGOFF_INTERVAL) {
  1929. /* If we are synced, offsets are less than SLEW_THRESHOLD,
  1930. * or at the very least not much larger than it.
  1931. * Now we see a largish one.
  1932. * Either this peer is feeling bad, or packet got corrupted,
  1933. * or _our_ clock is wrong now and _all_ peers will show similar
  1934. * largish offsets too.
  1935. * I observed this with laptop suspend stopping clock.
  1936. * In any case, it makes sense to make next request soonish:
  1937. * cases 1 and 2: get a better datapoint,
  1938. * case 3: allows to resync faster.
  1939. */
  1940. interval = BIGOFF_INTERVAL;
  1941. }
  1942. set_next(p, interval);
  1943. }
  1944. #if ENABLE_FEATURE_NTPD_SERVER
  1945. static NOINLINE void
  1946. recv_and_process_client_pkt(void /*int fd*/)
  1947. {
  1948. ssize_t size;
  1949. //uint8_t version;
  1950. len_and_sockaddr *to;
  1951. struct sockaddr *from;
  1952. msg_t msg;
  1953. uint8_t query_status;
  1954. l_fixedpt_t query_xmttime;
  1955. to = get_sock_lsa(G_listen_fd);
  1956. from = xzalloc(to->len);
  1957. size = recv_from_to(G_listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
  1958. if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
  1959. char *addr;
  1960. if (size < 0) {
  1961. if (errno == EAGAIN)
  1962. goto bail;
  1963. bb_perror_msg_and_die("recv");
  1964. }
  1965. addr = xmalloc_sockaddr2dotted_noport(from);
  1966. bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
  1967. free(addr);
  1968. goto bail;
  1969. }
  1970. /* Respond only to client and symmetric active packets */
  1971. if ((msg.m_status & MODE_MASK) != MODE_CLIENT
  1972. && (msg.m_status & MODE_MASK) != MODE_SYM_ACT
  1973. ) {
  1974. goto bail;
  1975. }
  1976. query_status = msg.m_status;
  1977. query_xmttime = msg.m_xmttime;
  1978. /* Build a reply packet */
  1979. memset(&msg, 0, sizeof(msg));
  1980. msg.m_status = G.stratum < MAXSTRAT ? (G.ntp_status & LI_MASK) : LI_ALARM;
  1981. msg.m_status |= (query_status & VERSION_MASK);
  1982. msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
  1983. MODE_SERVER : MODE_SYM_PAS;
  1984. msg.m_stratum = G.stratum;
  1985. msg.m_ppoll = G.poll_exp;
  1986. msg.m_precision_exp = G_precision_exp;
  1987. /* this time was obtained between poll() and recv() */
  1988. msg.m_rectime = d_to_lfp(G.cur_time);
  1989. msg.m_xmttime = d_to_lfp(gettime1900d()); /* this instant */
  1990. if (G.peer_cnt == 0) {
  1991. /* we have no peers: "stratum 1 server" mode. reftime = our own time */
  1992. G.reftime = G.cur_time;
  1993. }
  1994. msg.m_reftime = d_to_lfp(G.reftime);
  1995. msg.m_orgtime = query_xmttime;
  1996. msg.m_rootdelay = d_to_sfp(G.rootdelay);
  1997. //simple code does not do this, fix simple code!
  1998. msg.m_rootdisp = d_to_sfp(G.rootdisp);
  1999. //version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
  2000. msg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3;
  2001. /* We reply from the local address packet was sent to,
  2002. * this makes to/from look swapped here: */
  2003. do_sendto(G_listen_fd,
  2004. /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
  2005. &msg, size);
  2006. bail:
  2007. free(to);
  2008. free(from);
  2009. }
  2010. #endif
  2011. /* Upstream ntpd's options:
  2012. *
  2013. * -4 Force DNS resolution of host names to the IPv4 namespace.
  2014. * -6 Force DNS resolution of host names to the IPv6 namespace.
  2015. * -a Require cryptographic authentication for broadcast client,
  2016. * multicast client and symmetric passive associations.
  2017. * This is the default.
  2018. * -A Do not require cryptographic authentication for broadcast client,
  2019. * multicast client and symmetric passive associations.
  2020. * This is almost never a good idea.
  2021. * -b Enable the client to synchronize to broadcast servers.
  2022. * -c conffile
  2023. * Specify the name and path of the configuration file,
  2024. * default /etc/ntp.conf
  2025. * -d Specify debugging mode. This option may occur more than once,
  2026. * with each occurrence indicating greater detail of display.
  2027. * -D level
  2028. * Specify debugging level directly.
  2029. * -f driftfile
  2030. * Specify the name and path of the frequency file.
  2031. * This is the same operation as the "driftfile FILE"
  2032. * configuration command.
  2033. * -g Normally, ntpd exits with a message to the system log
  2034. * if the offset exceeds the panic threshold, which is 1000 s
  2035. * by default. This option allows the time to be set to any value
  2036. * without restriction; however, this can happen only once.
  2037. * If the threshold is exceeded after that, ntpd will exit
  2038. * with a message to the system log. This option can be used
  2039. * with the -q and -x options. See the tinker command for other options.
  2040. * -i jaildir
  2041. * Chroot the server to the directory jaildir. This option also implies
  2042. * that the server attempts to drop root privileges at startup
  2043. * (otherwise, chroot gives very little additional security).
  2044. * You may need to also specify a -u option.
  2045. * -k keyfile
  2046. * Specify the name and path of the symmetric key file,
  2047. * default /etc/ntp/keys. This is the same operation
  2048. * as the "keys FILE" configuration command.
  2049. * -l logfile
  2050. * Specify the name and path of the log file. The default
  2051. * is the system log file. This is the same operation as
  2052. * the "logfile FILE" configuration command.
  2053. * -L Do not listen to virtual IPs. The default is to listen.
  2054. * -n Don't fork.
  2055. * -N To the extent permitted by the operating system,
  2056. * run the ntpd at the highest priority.
  2057. * -p pidfile
  2058. * Specify the name and path of the file used to record the ntpd
  2059. * process ID. This is the same operation as the "pidfile FILE"
  2060. * configuration command.
  2061. * -P priority
  2062. * To the extent permitted by the operating system,
  2063. * run the ntpd at the specified priority.
  2064. * -q Exit the ntpd just after the first time the clock is set.
  2065. * This behavior mimics that of the ntpdate program, which is
  2066. * to be retired. The -g and -x options can be used with this option.
  2067. * Note: The kernel time discipline is disabled with this option.
  2068. * -r broadcastdelay
  2069. * Specify the default propagation delay from the broadcast/multicast
  2070. * server to this client. This is necessary only if the delay
  2071. * cannot be computed automatically by the protocol.
  2072. * -s statsdir
  2073. * Specify the directory path for files created by the statistics
  2074. * facility. This is the same operation as the "statsdir DIR"
  2075. * configuration command.
  2076. * -t key
  2077. * Add a key number to the trusted key list. This option can occur
  2078. * more than once.
  2079. * -u user[:group]
  2080. * Specify a user, and optionally a group, to switch to.
  2081. * -v variable
  2082. * -V variable
  2083. * Add a system variable listed by default.
  2084. * -x Normally, the time is slewed if the offset is less than the step
  2085. * threshold, which is 128 ms by default, and stepped if above
  2086. * the threshold. This option sets the threshold to 600 s, which is
  2087. * well within the accuracy window to set the clock manually.
  2088. * Note: since the slew rate of typical Unix kernels is limited
  2089. * to 0.5 ms/s, each second of adjustment requires an amortization
  2090. * interval of 2000 s. Thus, an adjustment as much as 600 s
  2091. * will take almost 14 days to complete. This option can be used
  2092. * with the -g and -q options. See the tinker command for other options.
  2093. * Note: The kernel time discipline is disabled with this option.
  2094. */
  2095. /* By doing init in a separate function we decrease stack usage
  2096. * in main loop.
  2097. */
  2098. static NOINLINE void ntp_init(char **argv)
  2099. {
  2100. unsigned opts;
  2101. llist_t *peers;
  2102. srand(getpid());
  2103. if (getuid())
  2104. bb_error_msg_and_die(bb_msg_you_must_be_root);
  2105. /* Set some globals */
  2106. G.discipline_jitter = G_precision_sec;
  2107. G.stratum = MAXSTRAT;
  2108. if (BURSTPOLL != 0)
  2109. G.poll_exp = BURSTPOLL; /* speeds up initial sync */
  2110. G.last_script_run = G.reftime = G.last_update_recv_time = gettime1900d(); /* sets G.cur_time too */
  2111. G.FREQHOLD_cnt = -1;
  2112. /* Parse options */
  2113. peers = NULL;
  2114. opts = getopt32(argv, "^"
  2115. "nqNx" /* compat */
  2116. "wp:*S:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
  2117. IF_FEATURE_NTPD_SERVER("I:") /* compat */
  2118. "d" /* compat */
  2119. "46aAbgL" /* compat, ignored */
  2120. "\0"
  2121. "dd:wn" /* -d: counter; -p: list; -w implies -n */
  2122. IF_FEATURE_NTPD_SERVER(":Il") /* -I implies -l */
  2123. , &peers, &G.script_name,
  2124. #if ENABLE_FEATURE_NTPD_SERVER
  2125. &G.if_name,
  2126. #endif
  2127. &G.verbose);
  2128. // if (opts & OPT_x) /* disable stepping, only slew is allowed */
  2129. // G.time_was_stepped = 1;
  2130. #if ENABLE_FEATURE_NTPD_SERVER
  2131. G_listen_fd = -1;
  2132. if (opts & OPT_l) {
  2133. G_listen_fd = create_and_bind_dgram_or_die(NULL, 123);
  2134. if (G.if_name) {
  2135. if (setsockopt_bindtodevice(G_listen_fd, G.if_name))
  2136. xfunc_die();
  2137. }
  2138. socket_want_pktinfo(G_listen_fd);
  2139. setsockopt_int(G_listen_fd, IPPROTO_IP, IP_TOS, IPTOS_DSCP_AF21);
  2140. }
  2141. #endif
  2142. /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
  2143. if (opts & OPT_N)
  2144. setpriority(PRIO_PROCESS, 0, -15);
  2145. if (!(opts & OPT_n)) {
  2146. bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
  2147. logmode = LOGMODE_NONE;
  2148. }
  2149. if (peers) {
  2150. while (peers)
  2151. add_peers(llist_pop(&peers));
  2152. }
  2153. #if ENABLE_FEATURE_NTPD_CONF
  2154. else {
  2155. parser_t *parser;
  2156. char *token[3];
  2157. parser = config_open("/etc/ntp.conf");
  2158. while (config_read(parser, token, 3, 1, "# \t", PARSE_NORMAL)) {
  2159. if (strcmp(token[0], "server") == 0 && token[1]) {
  2160. add_peers(token[1]);
  2161. continue;
  2162. }
  2163. bb_error_msg("skipping %s:%u: unimplemented command '%s'",
  2164. "/etc/ntp.conf", parser->lineno, token[0]
  2165. );
  2166. }
  2167. config_close(parser);
  2168. }
  2169. #endif
  2170. if (G.peer_cnt == 0) {
  2171. if (!(opts & OPT_l))
  2172. bb_show_usage();
  2173. /* -l but no peers: "stratum 1 server" mode */
  2174. G.stratum = 1;
  2175. }
  2176. /* If network is up, syncronization occurs in ~10 seconds.
  2177. * We give "ntpd -q" 10 seconds to get first reply,
  2178. * then another 50 seconds to finish syncing.
  2179. *
  2180. * I tested ntpd 4.2.6p1 and apparently it never exits
  2181. * (will try forever), but it does not feel right.
  2182. * The goal of -q is to act like ntpdate: set time
  2183. * after a reasonably small period of polling, or fail.
  2184. */
  2185. if (opts & OPT_q) {
  2186. option_mask32 |= OPT_qq;
  2187. alarm(10);
  2188. }
  2189. bb_signals(0
  2190. | (1 << SIGTERM)
  2191. | (1 << SIGINT)
  2192. | (1 << SIGALRM)
  2193. , record_signo
  2194. );
  2195. bb_signals(0
  2196. | (1 << SIGPIPE)
  2197. | (1 << SIGCHLD)
  2198. , SIG_IGN
  2199. );
  2200. }
  2201. int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
  2202. int ntpd_main(int argc UNUSED_PARAM, char **argv)
  2203. {
  2204. #undef G
  2205. struct globals G;
  2206. struct pollfd *pfd;
  2207. peer_t **idx2peer;
  2208. unsigned cnt;
  2209. memset(&G, 0, sizeof(G));
  2210. SET_PTR_TO_GLOBALS(&G);
  2211. ntp_init(argv);
  2212. /* If ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
  2213. cnt = G.peer_cnt + ENABLE_FEATURE_NTPD_SERVER;
  2214. idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt);
  2215. pfd = xzalloc(sizeof(pfd[0]) * cnt);
  2216. /* Countdown: we never sync before we sent INITIAL_SAMPLES+1
  2217. * packets to each peer.
  2218. * NB: if some peer is not responding, we may end up sending
  2219. * fewer packets to it and more to other peers.
  2220. * NB2: sync usually happens using INITIAL_SAMPLES packets,
  2221. * since last reply does not come back instantaneously.
  2222. */
  2223. cnt = G.peer_cnt * (INITIAL_SAMPLES + 1);
  2224. write_pidfile(CONFIG_PID_FILE_PATH "/ntpd.pid");
  2225. while (!bb_got_signal) {
  2226. llist_t *item;
  2227. unsigned i, j;
  2228. int nfds, timeout;
  2229. double nextaction;
  2230. /* Nothing between here and poll() blocks for any significant time */
  2231. nextaction = G.last_script_run + (11*60);
  2232. if (nextaction < G.cur_time + 1)
  2233. nextaction = G.cur_time + 1;
  2234. i = 0;
  2235. #if ENABLE_FEATURE_NTPD_SERVER
  2236. if (G_listen_fd != -1) {
  2237. pfd[0].fd = G_listen_fd;
  2238. pfd[0].events = POLLIN;
  2239. i++;
  2240. }
  2241. #endif
  2242. /* Pass over peer list, send requests, time out on receives */
  2243. for (item = G.ntp_peers; item != NULL; item = item->link) {
  2244. peer_t *p = (peer_t *) item->data;
  2245. if (p->next_action_time <= G.cur_time) {
  2246. if (p->p_fd == -1) {
  2247. /* Time to send new req */
  2248. if (--cnt == 0) {
  2249. VERB4 bb_error_msg("disabling burst mode");
  2250. G.polladj_count = 0;
  2251. G.poll_exp = MINPOLL;
  2252. }
  2253. send_query_to_peer(p);
  2254. } else {
  2255. /* Timed out waiting for reply */
  2256. close(p->p_fd);
  2257. p->p_fd = -1;
  2258. /* If poll interval is small, increase it */
  2259. if (G.poll_exp < BIGPOLL)
  2260. adjust_poll(MINPOLL);
  2261. timeout = poll_interval(NOREPLY_INTERVAL);
  2262. bb_error_msg("timed out waiting for %s, reach 0x%02x, next query in %us",
  2263. p->p_dotted, p->reachable_bits, timeout);
  2264. /* What if don't see it because it changed its IP? */
  2265. if (p->reachable_bits == 0)
  2266. resolve_peer_hostname(p);
  2267. set_next(p, timeout);
  2268. }
  2269. }
  2270. if (p->next_action_time < nextaction)
  2271. nextaction = p->next_action_time;
  2272. if (p->p_fd >= 0) {
  2273. /* Wait for reply from this peer */
  2274. pfd[i].fd = p->p_fd;
  2275. pfd[i].events = POLLIN;
  2276. idx2peer[i] = p;
  2277. i++;
  2278. }
  2279. }
  2280. timeout = nextaction - G.cur_time;
  2281. if (timeout < 0)
  2282. timeout = 0;
  2283. timeout++; /* (nextaction - G.cur_time) rounds down, compensating */
  2284. /* Here we may block */
  2285. VERB2 {
  2286. if (i > (ENABLE_FEATURE_NTPD_SERVER && G_listen_fd != -1)) {
  2287. /* We wait for at least one reply.
  2288. * Poll for it, without wasting time for message.
  2289. * Since replies often come under 1 second, this also
  2290. * reduces clutter in logs.
  2291. */
  2292. nfds = poll(pfd, i, 1000);
  2293. if (nfds != 0)
  2294. goto did_poll;
  2295. if (--timeout <= 0)
  2296. goto did_poll;
  2297. }
  2298. bb_error_msg("poll:%us sockets:%u interval:%us", timeout, i, 1 << G.poll_exp);
  2299. }
  2300. nfds = poll(pfd, i, timeout * 1000);
  2301. did_poll:
  2302. gettime1900d(); /* sets G.cur_time */
  2303. if (nfds <= 0) {
  2304. double ct;
  2305. int dns_error;
  2306. if (bb_got_signal)
  2307. break; /* poll was interrupted by a signal */
  2308. if (G.cur_time - G.last_script_run > 11*60) {
  2309. /* Useful for updating battery-backed RTC and such */
  2310. run_script("periodic", G.last_update_offset);
  2311. gettime1900d(); /* sets G.cur_time */
  2312. }
  2313. /* Resolve peer names to IPs, if not resolved yet.
  2314. * We do it only when poll timed out:
  2315. * this way, we almost never overlap DNS resolution with
  2316. * "request-reply" packet round trip.
  2317. */
  2318. dns_error = 0;
  2319. ct = G.cur_time;
  2320. for (item = G.ntp_peers; item != NULL; item = item->link) {
  2321. peer_t *p = (peer_t *) item->data;
  2322. if (p->next_action_time <= ct && !p->p_lsa) {
  2323. /* This can take up to ~10 sec per each DNS query */
  2324. dns_error |= (!resolve_peer_hostname(p));
  2325. }
  2326. }
  2327. if (!dns_error)
  2328. goto check_unsync;
  2329. /* Set next time for those which are still not resolved */
  2330. gettime1900d(); /* sets G.cur_time (needed for set_next()) */
  2331. for (item = G.ntp_peers; item != NULL; item = item->link) {
  2332. peer_t *p = (peer_t *) item->data;
  2333. if (p->next_action_time <= ct && !p->p_lsa) {
  2334. set_next(p, HOSTNAME_INTERVAL * p->dns_errors);
  2335. }
  2336. }
  2337. goto check_unsync;
  2338. }
  2339. /* Process any received packets */
  2340. j = 0;
  2341. #if ENABLE_FEATURE_NTPD_SERVER
  2342. if (G.listen_fd != -1) {
  2343. if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
  2344. nfds--;
  2345. recv_and_process_client_pkt(/*G.listen_fd*/);
  2346. gettime1900d(); /* sets G.cur_time */
  2347. }
  2348. j = 1;
  2349. }
  2350. #endif
  2351. for (; nfds != 0 && j < i; j++) {
  2352. if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
  2353. /*
  2354. * At init, alarm was set to 10 sec.
  2355. * Now we did get a reply.
  2356. * Increase timeout to 50 seconds to finish syncing.
  2357. */
  2358. if (option_mask32 & OPT_qq) {
  2359. option_mask32 &= ~OPT_qq;
  2360. alarm(50);
  2361. }
  2362. nfds--;
  2363. recv_and_process_peer_pkt(idx2peer[j]);
  2364. gettime1900d(); /* sets G.cur_time */
  2365. }
  2366. }
  2367. check_unsync:
  2368. if (G.ntp_peers && G.stratum != MAXSTRAT) {
  2369. for (item = G.ntp_peers; item != NULL; item = item->link) {
  2370. peer_t *p = (peer_t *) item->data;
  2371. if (p->reachable_bits)
  2372. goto have_reachable_peer;
  2373. }
  2374. /* No peer responded for last 8 packets, panic */
  2375. clamp_pollexp_and_set_MAXSTRAT();
  2376. run_script("unsync", 0.0);
  2377. have_reachable_peer: ;
  2378. }
  2379. } /* while (!bb_got_signal) */
  2380. remove_pidfile(CONFIG_PID_FILE_PATH "/ntpd.pid");
  2381. kill_myself_with_sig(bb_got_signal);
  2382. }
  2383. /*** openntpd-4.6 uses only adjtime, not adjtimex ***/
  2384. /*** ntp-4.2.6/ntpd/ntp_loopfilter.c - adjtimex usage ***/
  2385. #if 0
  2386. static double
  2387. direct_freq(double fp_offset)
  2388. {
  2389. #ifdef KERNEL_PLL
  2390. /*
  2391. * If the kernel is enabled, we need the residual offset to
  2392. * calculate the frequency correction.
  2393. */
  2394. if (pll_control && kern_enable) {
  2395. memset(&ntv, 0, sizeof(ntv));
  2396. ntp_adjtime(&ntv);
  2397. #ifdef STA_NANO
  2398. clock_offset = ntv.offset / 1e9;
  2399. #else /* STA_NANO */
  2400. clock_offset = ntv.offset / 1e6;
  2401. #endif /* STA_NANO */
  2402. drift_comp = FREQTOD(ntv.freq);
  2403. }
  2404. #endif /* KERNEL_PLL */
  2405. set_freq((fp_offset - clock_offset) / (current_time - clock_epoch) + drift_comp);
  2406. wander_resid = 0;
  2407. return drift_comp;
  2408. }
  2409. static void
  2410. set_freq(double freq) /* frequency update */
  2411. {
  2412. char tbuf[80];
  2413. drift_comp = freq;
  2414. #ifdef KERNEL_PLL
  2415. /*
  2416. * If the kernel is enabled, update the kernel frequency.
  2417. */
  2418. if (pll_control && kern_enable) {
  2419. memset(&ntv, 0, sizeof(ntv));
  2420. ntv.modes = MOD_FREQUENCY;
  2421. ntv.freq = DTOFREQ(drift_comp);
  2422. ntp_adjtime(&ntv);
  2423. snprintf(tbuf, sizeof(tbuf), "kernel %.3f PPM", drift_comp * 1e6);
  2424. report_event(EVNT_FSET, NULL, tbuf);
  2425. } else {
  2426. snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
  2427. report_event(EVNT_FSET, NULL, tbuf);
  2428. }
  2429. #else /* KERNEL_PLL */
  2430. snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
  2431. report_event(EVNT_FSET, NULL, tbuf);
  2432. #endif /* KERNEL_PLL */
  2433. }
  2434. ...
  2435. ...
  2436. ...
  2437. #ifdef KERNEL_PLL
  2438. /*
  2439. * This code segment works when clock adjustments are made using
  2440. * precision time kernel support and the ntp_adjtime() system
  2441. * call. This support is available in Solaris 2.6 and later,
  2442. * Digital Unix 4.0 and later, FreeBSD, Linux and specially
  2443. * modified kernels for HP-UX 9 and Ultrix 4. In the case of the
  2444. * DECstation 5000/240 and Alpha AXP, additional kernel
  2445. * modifications provide a true microsecond clock and nanosecond
  2446. * clock, respectively.
  2447. *
  2448. * Important note: The kernel discipline is used only if the
  2449. * step threshold is less than 0.5 s, as anything higher can
  2450. * lead to overflow problems. This might occur if some misguided
  2451. * lad set the step threshold to something ridiculous.
  2452. */
  2453. if (pll_control && kern_enable) {
  2454. #define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | MOD_STATUS | MOD_TIMECONST)
  2455. /*
  2456. * We initialize the structure for the ntp_adjtime()
  2457. * system call. We have to convert everything to
  2458. * microseconds or nanoseconds first. Do not update the
  2459. * system variables if the ext_enable flag is set. In
  2460. * this case, the external clock driver will update the
  2461. * variables, which will be read later by the local
  2462. * clock driver. Afterwards, remember the time and
  2463. * frequency offsets for jitter and stability values and
  2464. * to update the frequency file.
  2465. */
  2466. memset(&ntv, 0, sizeof(ntv));
  2467. if (ext_enable) {
  2468. ntv.modes = MOD_STATUS;
  2469. } else {
  2470. #ifdef STA_NANO
  2471. ntv.modes = MOD_BITS | MOD_NANO;
  2472. #else /* STA_NANO */
  2473. ntv.modes = MOD_BITS;
  2474. #endif /* STA_NANO */
  2475. if (clock_offset < 0)
  2476. dtemp = -.5;
  2477. else
  2478. dtemp = .5;
  2479. #ifdef STA_NANO
  2480. ntv.offset = (int32)(clock_offset * 1e9 + dtemp);
  2481. ntv.constant = sys_poll;
  2482. #else /* STA_NANO */
  2483. ntv.offset = (int32)(clock_offset * 1e6 + dtemp);
  2484. ntv.constant = sys_poll - 4;
  2485. #endif /* STA_NANO */
  2486. ntv.esterror = (u_int32)(clock_jitter * 1e6);
  2487. ntv.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
  2488. ntv.status = STA_PLL;
  2489. /*
  2490. * Enable/disable the PPS if requested.
  2491. */
  2492. if (pps_enable) {
  2493. if (!(pll_status & STA_PPSTIME))
  2494. report_event(EVNT_KERN,
  2495. NULL, "PPS enabled");
  2496. ntv.status |= STA_PPSTIME | STA_PPSFREQ;
  2497. } else {
  2498. if (pll_status & STA_PPSTIME)
  2499. report_event(EVNT_KERN,
  2500. NULL, "PPS disabled");
  2501. ntv.status &= ~(STA_PPSTIME | STA_PPSFREQ);
  2502. }
  2503. if (sys_leap == LEAP_ADDSECOND)
  2504. ntv.status |= STA_INS;
  2505. else if (sys_leap == LEAP_DELSECOND)
  2506. ntv.status |= STA_DEL;
  2507. }
  2508. /*
  2509. * Pass the stuff to the kernel. If it squeals, turn off
  2510. * the pps. In any case, fetch the kernel offset,
  2511. * frequency and jitter.
  2512. */
  2513. if (ntp_adjtime(&ntv) == TIME_ERROR) {
  2514. if (!(ntv.status & STA_PPSSIGNAL))
  2515. report_event(EVNT_KERN, NULL,
  2516. "PPS no signal");
  2517. }
  2518. pll_status = ntv.status;
  2519. #ifdef STA_NANO
  2520. clock_offset = ntv.offset / 1e9;
  2521. #else /* STA_NANO */
  2522. clock_offset = ntv.offset / 1e6;
  2523. #endif /* STA_NANO */
  2524. clock_frequency = FREQTOD(ntv.freq);
  2525. /*
  2526. * If the kernel PPS is lit, monitor its performance.
  2527. */
  2528. if (ntv.status & STA_PPSTIME) {
  2529. #ifdef STA_NANO
  2530. clock_jitter = ntv.jitter / 1e9;
  2531. #else /* STA_NANO */
  2532. clock_jitter = ntv.jitter / 1e6;
  2533. #endif /* STA_NANO */
  2534. }
  2535. #if defined(STA_NANO) && NTP_API == 4
  2536. /*
  2537. * If the TAI changes, update the kernel TAI.
  2538. */
  2539. if (loop_tai != sys_tai) {
  2540. loop_tai = sys_tai;
  2541. ntv.modes = MOD_TAI;
  2542. ntv.constant = sys_tai;
  2543. ntp_adjtime(&ntv);
  2544. }
  2545. #endif /* STA_NANO */
  2546. }
  2547. #endif /* KERNEL_PLL */
  2548. #endif