ntpd.c 74 KB

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