ntpd.c 82 KB

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