ntpd.c 88 KB

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