ntpd.c 83 KB

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