ntpd.c 80 KB

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