/contrib/ntp/ntpd/refclock_arc.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 1569 lines · 843 code · 137 blank · 589 comment · 187 complexity · 130da5e193b623246fd19c992dfd06b7 MD5 · raw file

  1. /*
  2. * refclock_arc - clock driver for ARCRON MSF/DCF/WWVB receivers
  3. */
  4. #ifdef HAVE_CONFIG_H
  5. #include <config.h>
  6. #endif
  7. #if defined(REFCLOCK) && defined(CLOCK_ARCRON_MSF)
  8. static const char arc_version[] = { "V1.3 2003/02/21" };
  9. /* define PRE_NTP420 for compatibility to previous versions of NTP (at least
  10. to 4.1.0 */
  11. #undef PRE_NTP420
  12. #ifndef ARCRON_NOT_KEEN
  13. #define ARCRON_KEEN 1 /* Be keen, and trusting of the clock, if defined. */
  14. #endif
  15. #ifndef ARCRON_NOT_MULTIPLE_SAMPLES
  16. #define ARCRON_MULTIPLE_SAMPLES 1 /* Use all timestamp bytes as samples. */
  17. #endif
  18. #ifndef ARCRON_NOT_LEAPSECOND_KEEN
  19. #ifndef ARCRON_LEAPSECOND_KEEN
  20. #undef ARCRON_LEAPSECOND_KEEN /* Respond quickly to leap seconds: doesn't work yet. */
  21. #endif
  22. #endif
  23. /*
  24. Code by Derek Mulcahy, <derek@toybox.demon.co.uk>, 1997.
  25. Modifications by Damon Hart-Davis, <d@hd.org>, 1997.
  26. Modifications by Paul Alfille, <palfille@partners.org>, 2003.
  27. Modifications by Christopher Price, <cprice@cs-home.com>, 2003.
  28. Modifications by Nigel Roles <nigel@9fs.org>, 2003.
  29. THIS CODE IS SUPPLIED AS IS, WITH NO WARRANTY OF ANY KIND. USE AT
  30. YOUR OWN RISK.
  31. Orginally developed and used with ntp3-5.85 by Derek Mulcahy.
  32. Built against ntp3-5.90 on Solaris 2.5 using gcc 2.7.2.
  33. This code may be freely copied and used and incorporated in other
  34. systems providing the disclaimer and notice of authorship are
  35. reproduced.
  36. -------------------------------------------------------------------------------
  37. Nigel's notes:
  38. 1) Called tcgetattr() before modifying, so that fields correctly initialised
  39. for all operating systems
  40. 2) Altered parsing of timestamp line so that it copes with fields which are
  41. not always ASCII digits (e.g. status field when battery low)
  42. -------------------------------------------------------------------------------
  43. Christopher's notes:
  44. MAJOR CHANGES SINCE V1.2
  45. ========================
  46. 1) Applied patch by Andrey Bray <abuse@madhouse.demon.co.uk>
  47. 2001-02-17 comp.protocols.time.ntp
  48. 2) Added WWVB support via clock mode command, localtime/UTC time configured
  49. via flag1=(0=UTC, 1=localtime)
  50. 3) Added ignore resync request via flag2=(0=resync, 1=ignore resync)
  51. 4) Added simplified conversion from localtime to UTC with dst/bst translation
  52. 5) Added average signal quality poll
  53. 6) Fixed a badformat error when no code is available due to stripping
  54. \n & \r's
  55. 7) Fixed a badformat error when clearing lencode & memset a_lastcode in poll
  56. routine
  57. 8) Lots of code cleanup, including standardized DEBUG macros and removal
  58. of unused code
  59. -------------------------------------------------------------------------------
  60. Author's original note:
  61. I enclose my ntp driver for the Galleon Systems Arc MSF receiver.
  62. It works (after a fashion) on both Solaris-1 and Solaris-2.
  63. I am currently using ntp3-5.85. I have been running the code for
  64. about 7 months without any problems. Even coped with the change to BST!
  65. I had to do some funky things to read from the clock because it uses the
  66. power from the receive lines to drive the transmit lines. This makes the
  67. code look a bit stupid but it works. I also had to put in some delays to
  68. allow for the turnaround time from receive to transmit. These delays
  69. are between characters when requesting a time stamp so that shouldn't affect
  70. the results too drastically.
  71. ...
  72. The bottom line is that it works but could easily be improved. You are
  73. free to do what you will with the code. I haven't been able to determine
  74. how good the clock is. I think that this requires a known good clock
  75. to compare it against.
  76. -------------------------------------------------------------------------------
  77. Damon's notes for adjustments:
  78. MAJOR CHANGES SINCE V1.0
  79. ========================
  80. 1) Removal of pollcnt variable that made the clock go permanently
  81. off-line once two time polls failed to gain responses.
  82. 2) Avoiding (at least on Solaris-2) terminal becoming the controlling
  83. terminal of the process when we do a low-level open().
  84. 3) Additional logic (conditional on ARCRON_LEAPSECOND_KEEN being
  85. defined) to try to resync quickly after a potential leap-second
  86. insertion or deletion.
  87. 4) Code significantly slimmer at run-time than V1.0.
  88. GENERAL
  89. =======
  90. 1) The C preprocessor symbol to have the clock built has been changed
  91. from ARC to ARCRON_MSF to CLOCK_ARCRON_MSF to minimise the
  92. possiblity of clashes with other symbols in the future.
  93. 2) PRECISION should be -4/-5 (63ms/31ms) for the following reasons:
  94. a) The ARC documentation claims the internal clock is (only)
  95. accurate to about 20ms relative to Rugby (plus there must be
  96. noticable drift and delay in the ms range due to transmission
  97. delays and changing atmospheric effects). This clock is not
  98. designed for ms accuracy as NTP has spoilt us all to expect.
  99. b) The clock oscillator looks like a simple uncompensated quartz
  100. crystal of the sort used in digital watches (ie 32768Hz) which
  101. can have large temperature coefficients and drifts; it is not
  102. clear if this oscillator is properly disciplined to the MSF
  103. transmission, but as the default is to resync only once per
  104. *day*, we can imagine that it is not, and is free-running. We
  105. can minimise drift by resyncing more often (at the cost of
  106. reduced battery life), but drift/wander may still be
  107. significant.
  108. c) Note that the bit time of 3.3ms adds to the potential error in
  109. the the clock timestamp, since the bit clock of the serial link
  110. may effectively be free-running with respect to the host clock
  111. and the MSF clock. Actually, the error is probably 1/16th of
  112. the above, since the input data is probably sampled at at least
  113. 16x the bit rate.
  114. By keeping the clock marked as not very precise, it will have a
  115. fairly large dispersion, and thus will tend to be used as a
  116. `backup' time source and sanity checker, which this clock is
  117. probably ideal for. For an isolated network without other time
  118. sources, this clock can probably be expected to provide *much*
  119. better than 1s accuracy, which will be fine.
  120. By default, PRECISION is set to -4, but experience, especially at a
  121. particular geographic location with a particular clock, may allow
  122. this to be altered to -5. (Note that skews of +/- 10ms are to be
  123. expected from the clock from time-to-time.) This improvement of
  124. reported precision can be instigated by setting flag3 to 1, though
  125. the PRECISION will revert to the normal value while the clock
  126. signal quality is unknown whatever the flag3 setting.
  127. IN ANY CASE, BE SURE TO SET AN APPROPRIATE FUDGE FACTOR TO REMOVE
  128. ANY RESIDUAL SKEW, eg:
  129. server 127.127.27.0 # ARCRON MSF radio clock unit 0.
  130. # Fudge timestamps by about 20ms.
  131. fudge 127.127.27.0 time1 0.020
  132. You will need to observe your system's behaviour, assuming you have
  133. some other NTP source to compare it with, to work out what the
  134. fudge factor should be. For my Sun SS1 running SunOS 4.1.3_U1 with
  135. my MSF clock with my distance from the MSF transmitter, +20ms
  136. seemed about right, after some observation.
  137. 3) REFID has been made "MSFa" to reflect the MSF time source and the
  138. ARCRON receiver.
  139. 4) DEFAULT_RESYNC_TIME is the time in seconds (by default) before
  140. forcing a resync since the last attempt. This is picked to give a
  141. little less than an hour between resyncs and to try to avoid
  142. clashing with any regular event at a regular time-past-the-hour
  143. which might cause systematic errors.
  144. The INITIAL_RESYNC_DELAY is to avoid bothering the clock and
  145. running down its batteries unnecesarily if ntpd is going to crash
  146. or be killed or reconfigured quickly. If ARCRON_KEEN is defined
  147. then this period is long enough for (with normal polling rates)
  148. enough time samples to have been taken to allow ntpd to sync to
  149. the clock before the interruption for the clock to resync to MSF.
  150. This avoids ntpd syncing to another peer first and then
  151. almost immediately hopping to the MSF clock.
  152. The RETRY_RESYNC_TIME is used before rescheduling a resync after a
  153. resync failed to reveal a statisfatory signal quality (too low or
  154. unknown).
  155. 5) The clock seems quite jittery, so I have increased the
  156. median-filter size from the typical (previous) value of 3. I
  157. discard up to half the results in the filter. It looks like maybe
  158. 1 sample in 10 or so (maybe less) is a spike, so allow the median
  159. filter to discard at least 10% of its entries or 1 entry, whichever
  160. is greater.
  161. 6) Sleeping *before* each character sent to the unit to allow required
  162. inter-character time but without introducting jitter and delay in
  163. handling the response if possible.
  164. 7) If the flag ARCRON_KEEN is defined, take time samples whenever
  165. possible, even while resyncing, etc. We rely, in this case, on the
  166. clock always giving us a reasonable time or else telling us in the
  167. status byte at the end of the timestamp that it failed to sync to
  168. MSF---thus we should never end up syncing to completely the wrong
  169. time.
  170. 8) If the flag ARCRON_OWN_FILTER is defined, use own versions of
  171. refclock median-filter routines to get round small bug in 3-5.90
  172. code which does not return the median offset. XXX Removed this
  173. bit due NTP Version 4 upgrade - dlm.
  174. 9) We would appear to have a year-2000 problem with this clock since
  175. it returns only the two least-significant digits of the year. But
  176. ntpd ignores the year and uses the local-system year instead, so
  177. this is in fact not a problem. Nevertheless, we attempt to do a
  178. sensible thing with the dates, wrapping them into a 100-year
  179. window.
  180. 10)Logs stats information that can be used by Derek's Tcl/Tk utility
  181. to show the status of the clock.
  182. 11)The clock documentation insists that the number of bits per
  183. character to be sent to the clock, and sent by it, is 11, including
  184. one start bit and two stop bits. The data format is either 7+even
  185. or 8+none.
  186. TO-DO LIST
  187. ==========
  188. * Eliminate use of scanf(), and maybe sprintf().
  189. * Allow user setting of resync interval to trade battery life for
  190. accuracy; maybe could be done via fudge factor or unit number.
  191. * Possibly note the time since the last resync of the MSF clock to
  192. MSF as the age of the last reference timestamp, ie trust the
  193. clock's oscillator not very much...
  194. * Add very slow auto-adjustment up to a value of +/- time2 to correct
  195. for long-term errors in the clock value (time2 defaults to 0 so the
  196. correction would be disabled by default).
  197. * Consider trying to use the tty_clk/ppsclock support.
  198. * Possibly use average or maximum signal quality reported during
  199. resync, rather than just the last one, which may be atypical.
  200. */
  201. /* Notes for HKW Elektronik GmBH Radio clock driver */
  202. /* Author Lyndon David, Sentinet Ltd, Feb 1997 */
  203. /* These notes seem also to apply usefully to the ARCRON clock. */
  204. /* The HKW clock module is a radio receiver tuned into the Rugby */
  205. /* MSF time signal tranmitted on 60 kHz. The clock module connects */
  206. /* to the computer via a serial line and transmits the time encoded */
  207. /* in 15 bytes at 300 baud 7 bits two stop bits even parity */
  208. /* Clock communications, from the datasheet */
  209. /* All characters sent to the clock are echoed back to the controlling */
  210. /* device. */
  211. /* Transmit time/date information */
  212. /* syntax ASCII o<cr> */
  213. /* Character o may be replaced if neccesary by a character whose code */
  214. /* contains the lowest four bits f(hex) eg */
  215. /* syntax binary: xxxx1111 00001101 */
  216. /* DHD note:
  217. You have to wait for character echo + 10ms before sending next character.
  218. */
  219. /* The clock replies to this command with a sequence of 15 characters */
  220. /* which contain the complete time and a final <cr> making 16 characters */
  221. /* in total. */
  222. /* The RC computer clock will not reply immediately to this command because */
  223. /* the start bit edge of the first reply character marks the beginning of */
  224. /* the second. So the RC Computer Clock will reply to this command at the */
  225. /* start of the next second */
  226. /* The characters have the following meaning */
  227. /* 1. hours tens */
  228. /* 2. hours units */
  229. /* 3. minutes tens */
  230. /* 4. minutes units */
  231. /* 5. seconds tens */
  232. /* 6. seconds units */
  233. /* 7. day of week 1-monday 7-sunday */
  234. /* 8. day of month tens */
  235. /* 9. day of month units */
  236. /* 10. month tens */
  237. /* 11. month units */
  238. /* 12. year tens */
  239. /* 13. year units */
  240. /* 14. BST/UTC status */
  241. /* bit 7 parity */
  242. /* bit 6 always 0 */
  243. /* bit 5 always 1 */
  244. /* bit 4 always 1 */
  245. /* bit 3 always 0 */
  246. /* bit 2 =1 if UTC is in effect, complementary to the BST bit */
  247. /* bit 1 =1 if BST is in effect, according to the BST bit */
  248. /* bit 0 BST/UTC change impending bit=1 in case of change impending */
  249. /* 15. status */
  250. /* bit 7 parity */
  251. /* bit 6 always 0 */
  252. /* bit 5 always 1 */
  253. /* bit 4 always 1 */
  254. /* bit 3 =1 if low battery is detected */
  255. /* bit 2 =1 if the very last reception attempt failed and a valid */
  256. /* time information already exists (bit0=1) */
  257. /* =0 if the last reception attempt was successful */
  258. /* bit 1 =1 if at least one reception since 2:30 am was successful */
  259. /* =0 if no reception attempt since 2:30 am was successful */
  260. /* bit 0 =1 if the RC Computer Clock contains valid time information */
  261. /* This bit is zero after reset and one after the first */
  262. /* successful reception attempt */
  263. /* DHD note:
  264. Also note g<cr> command which confirms that a resync is in progress, and
  265. if so what signal quality (0--5) is available.
  266. Also note h<cr> command which starts a resync to MSF signal.
  267. */
  268. #include "ntpd.h"
  269. #include "ntp_io.h"
  270. #include "ntp_refclock.h"
  271. #include "ntp_calendar.h"
  272. #include "ntp_stdlib.h"
  273. #include <stdio.h>
  274. #include <ctype.h>
  275. #if defined(HAVE_BSD_TTYS)
  276. #include <sgtty.h>
  277. #endif /* HAVE_BSD_TTYS */
  278. #if defined(HAVE_SYSV_TTYS)
  279. #include <termio.h>
  280. #endif /* HAVE_SYSV_TTYS */
  281. #if defined(HAVE_TERMIOS)
  282. #include <termios.h>
  283. #endif
  284. /*
  285. * This driver supports the ARCRON MSF/DCF/WWVB Radio Controlled Clock
  286. */
  287. /*
  288. * Interface definitions
  289. */
  290. #define DEVICE "/dev/arc%d" /* Device name and unit. */
  291. #define SPEED B300 /* UART speed (300 baud) */
  292. #define PRECISION (-4) /* Precision (~63 ms). */
  293. #define HIGHPRECISION (-5) /* If things are going well... */
  294. #define REFID "MSFa" /* Reference ID. */
  295. #define REFID_MSF "MSF" /* Reference ID. */
  296. #define REFID_DCF77 "DCF" /* Reference ID. */
  297. #define REFID_WWVB "WWVB" /* Reference ID. */
  298. #define DESCRIPTION "ARCRON MSF/DCF/WWVB Receiver"
  299. #ifdef PRE_NTP420
  300. #define MODE ttlmax
  301. #else
  302. #define MODE ttl
  303. #endif
  304. #define LENARC 16 /* Format `o' timecode length. */
  305. #define BITSPERCHAR 11 /* Bits per character. */
  306. #define BITTIME 0x0DA740E /* Time for 1 bit at 300bps. */
  307. #define CHARTIME10 0x8888888 /* Time for 10-bit char at 300bps. */
  308. #define CHARTIME11 0x962FC96 /* Time for 11-bit char at 300bps. */
  309. #define CHARTIME /* Time for char at 300bps. */ \
  310. ( (BITSPERCHAR == 11) ? CHARTIME11 : ( (BITSPERCHAR == 10) ? CHARTIME10 : \
  311. (BITSPERCHAR * BITTIME) ) )
  312. /* Allow for UART to accept char half-way through final stop bit. */
  313. #define INITIALOFFSET (u_int32)(-BITTIME/2)
  314. /*
  315. charoffsets[x] is the time after the start of the second that byte
  316. x (with the first byte being byte 1) is received by the UART,
  317. assuming that the initial edge of the start bit of the first byte
  318. is on-time. The values are represented as the fractional part of
  319. an l_fp.
  320. We store enough values to have the offset of each byte including
  321. the trailing \r, on the assumption that the bytes follow one
  322. another without gaps.
  323. */
  324. static const u_int32 charoffsets[LENARC+1] = {
  325. #if BITSPERCHAR == 11 /* Usual case. */
  326. /* Offsets computed as accurately as possible... */
  327. 0,
  328. INITIALOFFSET + 0x0962fc96, /* 1 chars, 11 bits */
  329. INITIALOFFSET + 0x12c5f92c, /* 2 chars, 22 bits */
  330. INITIALOFFSET + 0x1c28f5c3, /* 3 chars, 33 bits */
  331. INITIALOFFSET + 0x258bf259, /* 4 chars, 44 bits */
  332. INITIALOFFSET + 0x2eeeeeef, /* 5 chars, 55 bits */
  333. INITIALOFFSET + 0x3851eb85, /* 6 chars, 66 bits */
  334. INITIALOFFSET + 0x41b4e81b, /* 7 chars, 77 bits */
  335. INITIALOFFSET + 0x4b17e4b1, /* 8 chars, 88 bits */
  336. INITIALOFFSET + 0x547ae148, /* 9 chars, 99 bits */
  337. INITIALOFFSET + 0x5dddddde, /* 10 chars, 110 bits */
  338. INITIALOFFSET + 0x6740da74, /* 11 chars, 121 bits */
  339. INITIALOFFSET + 0x70a3d70a, /* 12 chars, 132 bits */
  340. INITIALOFFSET + 0x7a06d3a0, /* 13 chars, 143 bits */
  341. INITIALOFFSET + 0x8369d037, /* 14 chars, 154 bits */
  342. INITIALOFFSET + 0x8ccccccd, /* 15 chars, 165 bits */
  343. INITIALOFFSET + 0x962fc963 /* 16 chars, 176 bits */
  344. #else
  345. /* Offsets computed with a small rounding error... */
  346. 0,
  347. INITIALOFFSET + 1 * CHARTIME,
  348. INITIALOFFSET + 2 * CHARTIME,
  349. INITIALOFFSET + 3 * CHARTIME,
  350. INITIALOFFSET + 4 * CHARTIME,
  351. INITIALOFFSET + 5 * CHARTIME,
  352. INITIALOFFSET + 6 * CHARTIME,
  353. INITIALOFFSET + 7 * CHARTIME,
  354. INITIALOFFSET + 8 * CHARTIME,
  355. INITIALOFFSET + 9 * CHARTIME,
  356. INITIALOFFSET + 10 * CHARTIME,
  357. INITIALOFFSET + 11 * CHARTIME,
  358. INITIALOFFSET + 12 * CHARTIME,
  359. INITIALOFFSET + 13 * CHARTIME,
  360. INITIALOFFSET + 14 * CHARTIME,
  361. INITIALOFFSET + 15 * CHARTIME,
  362. INITIALOFFSET + 16 * CHARTIME
  363. #endif
  364. };
  365. #define DEFAULT_RESYNC_TIME (57*60) /* Gap between resync attempts (s). */
  366. #define RETRY_RESYNC_TIME (27*60) /* Gap to emergency resync attempt. */
  367. #ifdef ARCRON_KEEN
  368. #define INITIAL_RESYNC_DELAY 500 /* Delay before first resync. */
  369. #else
  370. #define INITIAL_RESYNC_DELAY 50 /* Delay before first resync. */
  371. #endif
  372. static const int moff[12] =
  373. { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
  374. /* Flags for a raw open() of the clock serial device. */
  375. #ifdef O_NOCTTY /* Good, we can avoid tty becoming controlling tty. */
  376. #define OPEN_FLAGS (O_RDWR | O_NOCTTY)
  377. #else /* Oh well, it may not matter... */
  378. #define OPEN_FLAGS (O_RDWR)
  379. #endif
  380. /* Length of queue of command bytes to be sent. */
  381. #define CMDQUEUELEN 4 /* Enough for two cmds + each \r. */
  382. /* Queue tick time; interval in seconds between chars taken off queue. */
  383. /* Must be >= 2 to allow o\r response to come back uninterrupted. */
  384. #define QUEUETICK 2 /* Allow o\r reply to finish. */
  385. /*
  386. * ARC unit control structure
  387. */
  388. struct arcunit {
  389. l_fp lastrec; /* Time tag for the receive time (system). */
  390. int status; /* Clock status. */
  391. int quality; /* Quality of reception 0--5 for unit. */
  392. /* We may also use the values -1 or 6 internally. */
  393. u_long quality_stamp; /* Next time to reset quality average. */
  394. u_long next_resync; /* Next resync time (s) compared to current_time. */
  395. int resyncing; /* Resync in progress if true. */
  396. /* In the outgoing queue, cmdqueue[0] is next to be sent. */
  397. char cmdqueue[CMDQUEUELEN+1]; /* Queue of outgoing commands + \0. */
  398. u_long saved_flags; /* Saved fudge flags. */
  399. };
  400. #ifdef ARCRON_LEAPSECOND_KEEN
  401. /* The flag `possible_leap' is set non-zero when any MSF unit
  402. thinks a leap-second may have happened.
  403. Set whenever we receive a valid time sample in the first hour of
  404. the first day of the first/seventh months.
  405. Outside the special hour this value is unconditionally set
  406. to zero by the receive routine.
  407. On finding itself in this timeslot, as long as the value is
  408. non-negative, the receive routine sets it to a positive value to
  409. indicate a resync to MSF should be performed.
  410. In the poll routine, if this value is positive and we are not
  411. already resyncing (eg from a sync that started just before
  412. midnight), start resyncing and set this value negative to
  413. indicate that a leap-triggered resync has been started. Having
  414. set this negative prevents the receive routine setting it
  415. positive and thus prevents multiple resyncs during the witching
  416. hour.
  417. */
  418. static int possible_leap = 0; /* No resync required by default. */
  419. #endif
  420. #if 0
  421. static void dummy_event_handler P((struct peer *));
  422. static void arc_event_handler P((struct peer *));
  423. #endif /* 0 */
  424. #define QUALITY_UNKNOWN -1 /* Indicates unknown clock quality. */
  425. #define MIN_CLOCK_QUALITY 0 /* Min quality clock will return. */
  426. #define MIN_CLOCK_QUALITY_OK 3 /* Min quality for OK reception. */
  427. #define MAX_CLOCK_QUALITY 5 /* Max quality clock will return. */
  428. /*
  429. * Function prototypes
  430. */
  431. static int arc_start P((int, struct peer *));
  432. static void arc_shutdown P((int, struct peer *));
  433. static void arc_receive P((struct recvbuf *));
  434. static void arc_poll P((int, struct peer *));
  435. /*
  436. * Transfer vector
  437. */
  438. struct refclock refclock_arc = {
  439. arc_start, /* start up driver */
  440. arc_shutdown, /* shut down driver */
  441. arc_poll, /* transmit poll message */
  442. noentry, /* not used (old arc_control) */
  443. noentry, /* initialize driver (not used) */
  444. noentry, /* not used (old arc_buginfo) */
  445. NOFLAGS /* not used */
  446. };
  447. /* Queue us up for the next tick. */
  448. #define ENQUEUE(up) \
  449. do { \
  450. peer->nextaction = current_time + QUEUETICK; \
  451. } while(0)
  452. /* Placeholder event handler---does nothing safely---soaks up loose tick. */
  453. static void
  454. dummy_event_handler(
  455. struct peer *peer
  456. )
  457. {
  458. #ifdef DEBUG
  459. if(debug) { printf("arc: dummy_event_handler() called.\n"); }
  460. #endif
  461. }
  462. /*
  463. Normal event handler.
  464. Take first character off queue and send to clock if not a null.
  465. Shift characters down and put a null on the end.
  466. We assume that there is no parallelism so no race condition, but even
  467. if there is nothing bad will happen except that we might send some bad
  468. data to the clock once in a while.
  469. */
  470. static void
  471. arc_event_handler(
  472. struct peer *peer
  473. )
  474. {
  475. struct refclockproc *pp = peer->procptr;
  476. register struct arcunit *up = (struct arcunit *)pp->unitptr;
  477. int i;
  478. char c;
  479. #ifdef DEBUG
  480. if(debug > 2) { printf("arc: arc_event_handler() called.\n"); }
  481. #endif
  482. c = up->cmdqueue[0]; /* Next char to be sent. */
  483. /* Shift down characters, shifting trailing \0 in at end. */
  484. for(i = 0; i < CMDQUEUELEN; ++i)
  485. { up->cmdqueue[i] = up->cmdqueue[i+1]; }
  486. /* Don't send '\0' characters. */
  487. if(c != '\0') {
  488. if(write(pp->io.fd, &c, 1) != 1) {
  489. msyslog(LOG_NOTICE, "ARCRON: write to fd %d failed", pp->io.fd);
  490. }
  491. #ifdef DEBUG
  492. else if(debug) { printf("arc: sent `%2.2x', fd %d.\n", c, pp->io.fd); }
  493. #endif
  494. }
  495. ENQUEUE(up);
  496. }
  497. /*
  498. * arc_start - open the devices and initialize data for processing
  499. */
  500. static int
  501. arc_start(
  502. int unit,
  503. struct peer *peer
  504. )
  505. {
  506. register struct arcunit *up;
  507. struct refclockproc *pp;
  508. int fd;
  509. char device[20];
  510. #ifdef HAVE_TERMIOS
  511. struct termios arg;
  512. #endif
  513. msyslog(LOG_NOTICE, "ARCRON: %s: opening unit %d", arc_version, unit);
  514. #ifdef DEBUG
  515. if(debug) {
  516. printf("arc: %s: attempt to open unit %d.\n", arc_version, unit);
  517. }
  518. #endif
  519. /* Prevent a ridiculous device number causing overflow of device[]. */
  520. if((unit < 0) || (unit > 255)) { return(0); }
  521. /*
  522. * Open serial port. Use CLK line discipline, if available.
  523. */
  524. (void)sprintf(device, DEVICE, unit);
  525. if (!(fd = refclock_open(device, SPEED, LDISC_CLK)))
  526. return(0);
  527. #ifdef DEBUG
  528. if(debug) { printf("arc: unit %d using open().\n", unit); }
  529. #endif
  530. fd = open(device, OPEN_FLAGS);
  531. if(fd < 0) {
  532. #ifdef DEBUG
  533. if(debug) { printf("arc: failed [open()] to open %s.\n", device); }
  534. #endif
  535. return(0);
  536. }
  537. fcntl(fd, F_SETFL, 0); /* clear the descriptor flags */
  538. #ifdef DEBUG
  539. if(debug)
  540. { printf("arc: opened RS232 port with file descriptor %d.\n", fd); }
  541. #endif
  542. #ifdef HAVE_TERMIOS
  543. tcgetattr(fd, &arg);
  544. arg.c_iflag = IGNBRK | ISTRIP;
  545. arg.c_oflag = 0;
  546. arg.c_cflag = B300 | CS8 | CREAD | CLOCAL | CSTOPB;
  547. arg.c_lflag = 0;
  548. arg.c_cc[VMIN] = 1;
  549. arg.c_cc[VTIME] = 0;
  550. tcsetattr(fd, TCSANOW, &arg);
  551. #else
  552. msyslog(LOG_ERR, "ARCRON: termios not supported in this driver");
  553. (void)close(fd);
  554. return 0;
  555. #endif
  556. up = (struct arcunit *) emalloc(sizeof(struct arcunit));
  557. if(!up) { (void) close(fd); return(0); }
  558. /* Set structure to all zeros... */
  559. memset((char *)up, 0, sizeof(struct arcunit));
  560. pp = peer->procptr;
  561. pp->io.clock_recv = arc_receive;
  562. pp->io.srcclock = (caddr_t)peer;
  563. pp->io.datalen = 0;
  564. pp->io.fd = fd;
  565. if(!io_addclock(&pp->io)) { (void) close(fd); free(up); return(0); }
  566. pp->unitptr = (caddr_t)up;
  567. /*
  568. * Initialize miscellaneous variables
  569. */
  570. peer->precision = PRECISION;
  571. peer->stratum = 2; /* Default to stratum 2 not 0. */
  572. pp->clockdesc = DESCRIPTION;
  573. if (peer->MODE > 3) {
  574. msyslog(LOG_NOTICE, "ARCRON: Invalid mode %d", peer->MODE);
  575. return 0;
  576. }
  577. #ifdef DEBUG
  578. if(debug) { printf("arc: mode = %d.\n", peer->MODE); }
  579. #endif
  580. switch (peer->MODE) {
  581. case 1:
  582. memcpy((char *)&pp->refid, REFID_MSF, 4);
  583. break;
  584. case 2:
  585. memcpy((char *)&pp->refid, REFID_DCF77, 4);
  586. break;
  587. case 3:
  588. memcpy((char *)&pp->refid, REFID_WWVB, 4);
  589. break;
  590. default:
  591. memcpy((char *)&pp->refid, REFID, 4);
  592. break;
  593. }
  594. /* Spread out resyncs so that they should remain separated. */
  595. up->next_resync = current_time + INITIAL_RESYNC_DELAY + (67*unit)%1009;
  596. #if 0 /* Not needed because of zeroing of arcunit structure... */
  597. up->resyncing = 0; /* Not resyncing yet. */
  598. up->saved_flags = 0; /* Default is all flags off. */
  599. /* Clear send buffer out... */
  600. {
  601. int i;
  602. for(i = CMDQUEUELEN; i >= 0; --i) { up->cmdqueue[i] = '\0'; }
  603. }
  604. #endif
  605. #ifdef ARCRON_KEEN
  606. up->quality = QUALITY_UNKNOWN; /* Trust the clock immediately. */
  607. #else
  608. up->quality = MIN_CLOCK_QUALITY;/* Don't trust the clock yet. */
  609. #endif
  610. peer->action = arc_event_handler;
  611. ENQUEUE(up);
  612. return(1);
  613. }
  614. /*
  615. * arc_shutdown - shut down the clock
  616. */
  617. static void
  618. arc_shutdown(
  619. int unit,
  620. struct peer *peer
  621. )
  622. {
  623. register struct arcunit *up;
  624. struct refclockproc *pp;
  625. peer->action = dummy_event_handler;
  626. pp = peer->procptr;
  627. up = (struct arcunit *)pp->unitptr;
  628. io_closeclock(&pp->io);
  629. free(up);
  630. }
  631. /*
  632. Compute space left in output buffer.
  633. */
  634. static int
  635. space_left(
  636. register struct arcunit *up
  637. )
  638. {
  639. int spaceleft;
  640. /* Compute space left in buffer after any pending output. */
  641. for(spaceleft = 0; spaceleft < CMDQUEUELEN; ++spaceleft)
  642. { if(up->cmdqueue[CMDQUEUELEN - 1 - spaceleft] != '\0') { break; } }
  643. return(spaceleft);
  644. }
  645. /*
  646. Send command by copying into command buffer as far forward as possible,
  647. after any pending output.
  648. Indicate an error by returning 0 if there is not space for the command.
  649. */
  650. static int
  651. send_slow(
  652. register struct arcunit *up,
  653. int fd,
  654. const char *s
  655. )
  656. {
  657. int sl = strlen(s);
  658. int spaceleft = space_left(up);
  659. #ifdef DEBUG
  660. if(debug > 1) { printf("arc: spaceleft = %d.\n", spaceleft); }
  661. #endif
  662. if(spaceleft < sl) { /* Should not normally happen... */
  663. #ifdef DEBUG
  664. msyslog(LOG_NOTICE, "ARCRON: send-buffer overrun (%d/%d)",
  665. sl, spaceleft);
  666. #endif
  667. return(0); /* FAILED! */
  668. }
  669. /* Copy in the command to be sent. */
  670. while(*s && spaceleft > 0) { up->cmdqueue[CMDQUEUELEN - spaceleft--] = *s++; }
  671. return(1);
  672. }
  673. static int
  674. get2(char *p, int *val)
  675. {
  676. if (!isdigit((int)p[0]) || !isdigit((int)p[1])) return 0;
  677. *val = (p[0] - '0') * 10 + p[1] - '0';
  678. return 1;
  679. }
  680. static int
  681. get1(char *p, int *val)
  682. {
  683. if (!isdigit((int)p[0])) return 0;
  684. *val = p[0] - '0';
  685. return 1;
  686. }
  687. /* Macro indicating action we will take for different quality values. */
  688. #define quality_action(q) \
  689. (((q) == QUALITY_UNKNOWN) ? "UNKNOWN, will use clock anyway" : \
  690. (((q) < MIN_CLOCK_QUALITY_OK) ? "TOO POOR, will not use clock" : \
  691. "OK, will use clock"))
  692. /*
  693. * arc_receive - receive data from the serial interface
  694. */
  695. static void
  696. arc_receive(
  697. struct recvbuf *rbufp
  698. )
  699. {
  700. register struct arcunit *up;
  701. struct refclockproc *pp;
  702. struct peer *peer;
  703. char c;
  704. int i, n, wday, month, flags, status;
  705. int arc_last_offset;
  706. static int quality_average = 0;
  707. static int quality_sum = 0;
  708. static int quality_polls = 0;
  709. /*
  710. * Initialize pointers and read the timecode and timestamp
  711. */
  712. peer = (struct peer *)rbufp->recv_srcclock;
  713. pp = peer->procptr;
  714. up = (struct arcunit *)pp->unitptr;
  715. /*
  716. If the command buffer is empty, and we are resyncing, insert a
  717. g\r quality request into it to poll for signal quality again.
  718. */
  719. if((up->resyncing) && (space_left(up) == CMDQUEUELEN)) {
  720. #ifdef DEBUG
  721. if(debug > 1) { printf("arc: inserting signal-quality poll.\n"); }
  722. #endif
  723. send_slow(up, pp->io.fd, "g\r");
  724. }
  725. /*
  726. The `arc_last_offset' is the offset in lastcode[] of the last byte
  727. received, and which we assume actually received the input
  728. timestamp.
  729. (When we get round to using tty_clk and it is available, we
  730. assume that we will receive the whole timecode with the
  731. trailing \r, and that that \r will be timestamped. But this
  732. assumption also works if receive the characters one-by-one.)
  733. */
  734. arc_last_offset = pp->lencode+rbufp->recv_length - 1;
  735. /*
  736. We catch a timestamp iff:
  737. * The command code is `o' for a timestamp.
  738. * If ARCRON_MULTIPLE_SAMPLES is undefined then we must have
  739. exactly char in the buffer (the command code) so that we
  740. only sample the first character of the timecode as our
  741. `on-time' character.
  742. * The first character in the buffer is not the echoed `\r'
  743. from the `o` command (so if we are to timestamp an `\r' it
  744. must not be first in the receive buffer with lencode==1.
  745. (Even if we had other characters following it, we probably
  746. would have a premature timestamp on the '\r'.)
  747. * We have received at least one character (I cannot imagine
  748. how it could be otherwise, but anyway...).
  749. */
  750. c = rbufp->recv_buffer[0];
  751. if((pp->a_lastcode[0] == 'o') &&
  752. #ifndef ARCRON_MULTIPLE_SAMPLES
  753. (pp->lencode == 1) &&
  754. #endif
  755. ((pp->lencode != 1) || (c != '\r')) &&
  756. (arc_last_offset >= 1)) {
  757. /* Note that the timestamp should be corrected if >1 char rcvd. */
  758. l_fp timestamp;
  759. timestamp = rbufp->recv_time;
  760. #ifdef DEBUG
  761. if(debug) { /* Show \r as `R', other non-printing char as `?'. */
  762. printf("arc: stamp -->%c<-- (%d chars rcvd)\n",
  763. ((c == '\r') ? 'R' : (isgraph((int)c) ? c : '?')),
  764. rbufp->recv_length);
  765. }
  766. #endif
  767. /*
  768. Now correct timestamp by offset of last byte received---we
  769. subtract from the receive time the delay implied by the
  770. extra characters received.
  771. Reject the input if the resulting code is too long, but
  772. allow for the trailing \r, normally not used but a good
  773. handle for tty_clk or somesuch kernel timestamper.
  774. */
  775. if(arc_last_offset > LENARC) {
  776. #ifdef DEBUG
  777. if(debug) {
  778. printf("arc: input code too long (%d cf %d); rejected.\n",
  779. arc_last_offset, LENARC);
  780. }
  781. #endif
  782. pp->lencode = 0;
  783. refclock_report(peer, CEVNT_BADREPLY);
  784. return;
  785. }
  786. L_SUBUF(&timestamp, charoffsets[arc_last_offset]);
  787. #ifdef DEBUG
  788. if(debug > 1) {
  789. printf(
  790. "arc: %s%d char(s) rcvd, the last for lastcode[%d]; -%sms offset applied.\n",
  791. ((rbufp->recv_length > 1) ? "*** " : ""),
  792. rbufp->recv_length,
  793. arc_last_offset,
  794. mfptoms((unsigned long)0,
  795. charoffsets[arc_last_offset],
  796. 1));
  797. }
  798. #endif
  799. #ifdef ARCRON_MULTIPLE_SAMPLES
  800. /*
  801. If taking multiple samples, capture the current adjusted
  802. sample iff:
  803. * No timestamp has yet been captured (it is zero), OR
  804. * This adjusted timestamp is earlier than the one already
  805. captured, on the grounds that this one suffered less
  806. delay in being delivered to us and is more accurate.
  807. */
  808. if(L_ISZERO(&(up->lastrec)) ||
  809. L_ISGEQ(&(up->lastrec), &timestamp))
  810. #endif
  811. {
  812. #ifdef DEBUG
  813. if(debug > 1) {
  814. printf("arc: system timestamp captured.\n");
  815. #ifdef ARCRON_MULTIPLE_SAMPLES
  816. if(!L_ISZERO(&(up->lastrec))) {
  817. l_fp diff;
  818. diff = up->lastrec;
  819. L_SUB(&diff, &timestamp);
  820. printf("arc: adjusted timestamp by -%sms.\n",
  821. mfptoms(diff.l_i, diff.l_f, 3));
  822. }
  823. #endif
  824. }
  825. #endif
  826. up->lastrec = timestamp;
  827. }
  828. }
  829. /* Just in case we still have lots of rubbish in the buffer... */
  830. /* ...and to avoid the same timestamp being reused by mistake, */
  831. /* eg on receipt of the \r coming in on its own after the */
  832. /* timecode. */
  833. if(pp->lencode >= LENARC) {
  834. #ifdef DEBUG
  835. if(debug && (rbufp->recv_buffer[0] != '\r'))
  836. { printf("arc: rubbish in pp->a_lastcode[].\n"); }
  837. #endif
  838. pp->lencode = 0;
  839. return;
  840. }
  841. /* Append input to code buffer, avoiding overflow. */
  842. for(i = 0; i < rbufp->recv_length; i++) {
  843. if(pp->lencode >= LENARC) { break; } /* Avoid overflow... */
  844. c = rbufp->recv_buffer[i];
  845. /* Drop trailing '\r's and drop `h' command echo totally. */
  846. if(c != '\r' && c != 'h') { pp->a_lastcode[pp->lencode++] = c; }
  847. /*
  848. If we've just put an `o' in the lastcode[0], clear the
  849. timestamp in anticipation of a timecode arriving soon.
  850. We would expect to get to process this before any of the
  851. timecode arrives.
  852. */
  853. if((c == 'o') && (pp->lencode == 1)) {
  854. L_CLR(&(up->lastrec));
  855. #ifdef DEBUG
  856. if(debug > 1) { printf("arc: clearing timestamp.\n"); }
  857. #endif
  858. }
  859. }
  860. if (pp->lencode == 0) return;
  861. /* Handle a quality message. */
  862. if(pp->a_lastcode[0] == 'g') {
  863. int r, q;
  864. if(pp->lencode < 3) { return; } /* Need more data... */
  865. r = (pp->a_lastcode[1] & 0x7f); /* Strip parity. */
  866. q = (pp->a_lastcode[2] & 0x7f); /* Strip parity. */
  867. if(((q & 0x70) != 0x30) || ((q & 0xf) > MAX_CLOCK_QUALITY) ||
  868. ((r & 0x70) != 0x30)) {
  869. /* Badly formatted response. */
  870. #ifdef DEBUG
  871. if(debug) { printf("arc: bad `g' response %2x %2x.\n", r, q); }
  872. #endif
  873. return;
  874. }
  875. if(r == '3') { /* Only use quality value whilst sync in progress. */
  876. if (up->quality_stamp < current_time) {
  877. struct calendar cal;
  878. l_fp new_stamp;
  879. get_systime (&new_stamp);
  880. caljulian (new_stamp.l_ui, &cal);
  881. up->quality_stamp =
  882. current_time + 60 - cal.second + 5;
  883. quality_sum = 0;
  884. quality_polls = 0;
  885. }
  886. quality_sum += (q & 0xf);
  887. quality_polls++;
  888. quality_average = (quality_sum / quality_polls);
  889. #ifdef DEBUG
  890. if(debug) { printf("arc: signal quality %d (%d).\n", quality_average, (q & 0xf)); }
  891. #endif
  892. } else if( /* (r == '2') && */ up->resyncing) {
  893. up->quality = quality_average;
  894. #ifdef DEBUG
  895. if(debug)
  896. {
  897. printf("arc: sync finished, signal quality %d: %s\n",
  898. up->quality,
  899. quality_action(up->quality));
  900. }
  901. #endif
  902. msyslog(LOG_NOTICE,
  903. "ARCRON: sync finished, signal quality %d: %s",
  904. up->quality,
  905. quality_action(up->quality));
  906. up->resyncing = 0; /* Resync is over. */
  907. quality_average = 0;
  908. quality_sum = 0;
  909. quality_polls = 0;
  910. #ifdef ARCRON_KEEN
  911. /* Clock quality dubious; resync earlier than usual. */
  912. if((up->quality == QUALITY_UNKNOWN) ||
  913. (up->quality < MIN_CLOCK_QUALITY_OK))
  914. { up->next_resync = current_time + RETRY_RESYNC_TIME; }
  915. #endif
  916. }
  917. pp->lencode = 0;
  918. return;
  919. }
  920. /* Stop now if this is not a timecode message. */
  921. if(pp->a_lastcode[0] != 'o') {
  922. pp->lencode = 0;
  923. refclock_report(peer, CEVNT_BADREPLY);
  924. return;
  925. }
  926. /* If we don't have enough data, wait for more... */
  927. if(pp->lencode < LENARC) { return; }
  928. /* WE HAVE NOW COLLECTED ONE TIMESTAMP (phew)... */
  929. #ifdef DEBUG
  930. if(debug > 1) { printf("arc: NOW HAVE TIMESTAMP...\n"); }
  931. #endif
  932. /* But check that we actually captured a system timestamp on it. */
  933. if(L_ISZERO(&(up->lastrec))) {
  934. #ifdef DEBUG
  935. if(debug) { printf("arc: FAILED TO GET SYSTEM TIMESTAMP\n"); }
  936. #endif
  937. pp->lencode = 0;
  938. refclock_report(peer, CEVNT_BADREPLY);
  939. return;
  940. }
  941. /*
  942. Append a mark of the clock's received signal quality for the
  943. benefit of Derek Mulcahy's Tcl/Tk utility (we map the `unknown'
  944. quality value to `6' for his s/w) and terminate the string for
  945. sure. This should not go off the buffer end.
  946. */
  947. pp->a_lastcode[pp->lencode] = ((up->quality == QUALITY_UNKNOWN) ?
  948. '6' : ('0' + up->quality));
  949. pp->a_lastcode[pp->lencode + 1] = '\0'; /* Terminate for printf(). */
  950. #ifdef PRE_NTP420
  951. /* We don't use the micro-/milli- second part... */
  952. pp->usec = 0;
  953. pp->msec = 0;
  954. #else
  955. /* We don't use the nano-second part... */
  956. pp->nsec = 0;
  957. #endif
  958. /* Validate format and numbers. */
  959. if (pp->a_lastcode[0] != 'o'
  960. || !get2(pp->a_lastcode + 1, &pp->hour)
  961. || !get2(pp->a_lastcode + 3, &pp->minute)
  962. || !get2(pp->a_lastcode + 5, &pp->second)
  963. || !get1(pp->a_lastcode + 7, &wday)
  964. || !get2(pp->a_lastcode + 8, &pp->day)
  965. || !get2(pp->a_lastcode + 10, &month)
  966. || !get2(pp->a_lastcode + 12, &pp->year)) {
  967. #ifdef DEBUG
  968. /* Would expect to have caught major problems already... */
  969. if(debug) { printf("arc: badly formatted data.\n"); }
  970. #endif
  971. pp->lencode = 0;
  972. refclock_report(peer, CEVNT_BADREPLY);
  973. return;
  974. }
  975. flags = pp->a_lastcode[14];
  976. status = pp->a_lastcode[15];
  977. #ifdef DEBUG
  978. if(debug) { printf("arc: status 0x%.2x flags 0x%.2x\n", flags, status); }
  979. #endif
  980. n = 9;
  981. /*
  982. Validate received values at least enough to prevent internal
  983. array-bounds problems, etc.
  984. */
  985. if((pp->hour < 0) || (pp->hour > 23) ||
  986. (pp->minute < 0) || (pp->minute > 59) ||
  987. (pp->second < 0) || (pp->second > 60) /*Allow for leap seconds.*/ ||
  988. (wday < 1) || (wday > 7) ||
  989. (pp->day < 1) || (pp->day > 31) ||
  990. (month < 1) || (month > 12) ||
  991. (pp->year < 0) || (pp->year > 99)) {
  992. /* Data out of range. */
  993. pp->lencode = 0;
  994. refclock_report(peer, CEVNT_BADREPLY);
  995. return;
  996. }
  997. if(peer->MODE == 0) { /* compatiblity to original version */
  998. int bst = flags;
  999. /* Check that BST/UTC bits are the complement of one another. */
  1000. if(!(bst & 2) == !(bst & 4)) {
  1001. pp->lencode = 0;
  1002. refclock_report(peer, CEVNT_BADREPLY);
  1003. return;
  1004. }
  1005. }
  1006. if(status & 0x8) { msyslog(LOG_NOTICE, "ARCRON: battery low"); }
  1007. /* Year-2000 alert! */
  1008. /* Attempt to wrap 2-digit date into sensible window. */
  1009. if(pp->year < YEAR_PIVOT) { pp->year += 100; } /* Y2KFixes */
  1010. pp->year += 1900; /* use full four-digit year */ /* Y2KFixes */
  1011. /*
  1012. Attempt to do the right thing by screaming that the code will
  1013. soon break when we get to the end of its useful life. What a
  1014. hero I am... PLEASE FIX LEAP-YEAR AND WRAP CODE IN 209X!
  1015. */
  1016. if(pp->year >= YEAR_PIVOT+2000-2 ) { /* Y2KFixes */
  1017. /*This should get attention B^> */
  1018. msyslog(LOG_NOTICE,
  1019. "ARCRON: fix me! EITHER YOUR DATE IS BADLY WRONG or else I will break soon!");
  1020. }
  1021. #ifdef DEBUG
  1022. if(debug) {
  1023. printf("arc: n=%d %02d:%02d:%02d %02d/%02d/%04d %1d %1d\n",
  1024. n,
  1025. pp->hour, pp->minute, pp->second,
  1026. pp->day, month, pp->year, flags, status);
  1027. }
  1028. #endif
  1029. /*
  1030. The status value tested for is not strictly supported by the
  1031. clock spec since the value of bit 2 (0x4) is claimed to be
  1032. undefined for MSF, yet does seem to indicate if the last resync
  1033. was successful or not.
  1034. */
  1035. pp->leap = LEAP_NOWARNING;
  1036. status &= 0x7;
  1037. if(status == 0x3) {
  1038. if(status != up->status)
  1039. { msyslog(LOG_NOTICE, "ARCRON: signal acquired"); }
  1040. } else {
  1041. if(status != up->status) {
  1042. msyslog(LOG_NOTICE, "ARCRON: signal lost");
  1043. pp->leap = LEAP_NOTINSYNC; /* MSF clock is free-running. */
  1044. up->status = status;
  1045. pp->lencode = 0;
  1046. refclock_report(peer, CEVNT_FAULT);
  1047. return;
  1048. }
  1049. }
  1050. up->status = status;
  1051. if (peer->MODE == 0) { /* compatiblity to original version */
  1052. int bst = flags;
  1053. pp->day += moff[month - 1];
  1054. if(isleap_4(pp->year) && month > 2) { pp->day++; }/* Y2KFixes */
  1055. /* Convert to UTC if required */
  1056. if(bst & 2) {
  1057. pp->hour--;
  1058. if (pp->hour < 0) {
  1059. pp->hour = 23;
  1060. pp->day--;
  1061. /* If we try to wrap round the year
  1062. * (BST on 1st Jan), reject.*/
  1063. if(pp->day < 0) {
  1064. pp->lencode = 0;
  1065. refclock_report(peer, CEVNT_BADTIME);
  1066. return;
  1067. }
  1068. }
  1069. }
  1070. }
  1071. if(peer->MODE > 0) {
  1072. if(pp->sloppyclockflag & CLK_FLAG1) {
  1073. struct tm local;
  1074. struct tm *gmtp;
  1075. time_t unixtime;
  1076. /*
  1077. * Convert to GMT for sites that distribute localtime.
  1078. * This means we have to do Y2K conversion on the
  1079. * 2-digit year; otherwise, we get the time wrong.
  1080. */
  1081. local.tm_year = pp->year-1900;
  1082. local.tm_mon = month-1;
  1083. local.tm_mday = pp->day;
  1084. local.tm_hour = pp->hour;
  1085. local.tm_min = pp->minute;
  1086. local.tm_sec = pp->second;
  1087. switch (peer->MODE) {
  1088. case 1:
  1089. local.tm_isdst = (flags & 2);
  1090. break;
  1091. case 2:
  1092. local.tm_isdst = (flags & 2);
  1093. break;
  1094. case 3:
  1095. switch (flags & 3) {
  1096. case 0: /* It is unclear exactly when the
  1097. Arcron changes from DST->ST and
  1098. ST->DST. Testing has shown this
  1099. to be irregular. For the time
  1100. being, let the OS decide. */
  1101. local.tm_isdst = 0;
  1102. #ifdef DEBUG
  1103. if (debug)
  1104. printf ("arc: DST = 00 (0)\n");
  1105. #endif
  1106. break;
  1107. case 1: /* dst->st time */
  1108. local.tm_isdst = -1;
  1109. #ifdef DEBUG
  1110. if (debug)
  1111. printf ("arc: DST = 01 (1)\n");
  1112. #endif
  1113. break;
  1114. case 2: /* st->dst time */
  1115. local.tm_isdst = -1;
  1116. #ifdef DEBUG
  1117. if (debug)
  1118. printf ("arc: DST = 10 (2)\n");
  1119. #endif
  1120. break;
  1121. case 3: /* dst time */
  1122. local.tm_isdst = 1;
  1123. #ifdef DEBUG
  1124. if (debug)
  1125. printf ("arc: DST = 11 (3)\n");
  1126. #endif
  1127. break;
  1128. }
  1129. break;
  1130. default:
  1131. msyslog(LOG_NOTICE, "ARCRON: Invalid mode %d",
  1132. peer->MODE);
  1133. return;
  1134. break;
  1135. }
  1136. unixtime = mktime (&local);
  1137. if ((gmtp = gmtime (&unixtime)) == NULL)
  1138. {
  1139. pp->lencode = 0;
  1140. refclock_report (peer, CEVNT_FAULT);
  1141. return;
  1142. }
  1143. pp->year = gmtp->tm_year+1900;
  1144. month = gmtp->tm_mon+1;
  1145. pp->day = ymd2yd(pp->year,month,gmtp->tm_mday);
  1146. /* pp->day = gmtp->tm_yday; */
  1147. pp->hour = gmtp->tm_hour;
  1148. pp->minute = gmtp->tm_min;
  1149. pp->second = gmtp->tm_sec;
  1150. #ifdef DEBUG
  1151. if (debug)
  1152. {
  1153. printf ("arc: time is %04d/%02d/%02d %02d:%02d:%02d UTC\n",
  1154. pp->year,month,gmtp->tm_mday,pp->hour,pp->minute,
  1155. pp->second);
  1156. }
  1157. #endif
  1158. } else
  1159. {
  1160. /*
  1161. * For more rational sites distributing UTC
  1162. */
  1163. pp->day = ymd2yd(pp->year,month,pp->day);
  1164. }
  1165. }
  1166. if (peer->MODE == 0) { /* compatiblity to original version */
  1167. /* If clock signal quality is
  1168. * unknown, revert to default PRECISION...*/
  1169. if(up->quality == QUALITY_UNKNOWN) {
  1170. peer->precision = PRECISION;
  1171. } else { /* ...else improve precision if flag3 is set... */
  1172. peer->precision = ((pp->sloppyclockflag & CLK_FLAG3) ?
  1173. HIGHPRECISION : PRECISION);
  1174. }
  1175. } else {
  1176. if ((status == 0x3) && (pp->sloppyclockflag & CLK_FLAG2)) {
  1177. peer->precision = ((pp->sloppyclockflag & CLK_FLAG3) ?
  1178. HIGHPRECISION : PRECISION);
  1179. } else if (up->quality == QUALITY_UNKNOWN) {
  1180. peer->precision = PRECISION;
  1181. } else {
  1182. peer->precision = ((pp->sloppyclockflag & CLK_FLAG3) ?
  1183. HIGHPRECISION : PRECISION);
  1184. }
  1185. }
  1186. /* Notice and log any change (eg from initial defaults) for flags. */
  1187. if(up->saved_flags != pp->sloppyclockflag) {
  1188. #ifdef DEBUG
  1189. msyslog(LOG_NOTICE, "ARCRON: flags enabled: %s%s%s%s",
  1190. ((pp->sloppyclockflag & CLK_FLAG1) ? "1" : "."),
  1191. ((pp->sloppyclockflag & CLK_FLAG2) ? "2" : "."),
  1192. ((pp->sloppyclockflag & CLK_FLAG3) ? "3" : "."),
  1193. ((pp->sloppyclockflag & CLK_FLAG4) ? "4" : "."));
  1194. /* Note effects of flags changing... */
  1195. if(debug) {
  1196. printf("arc: PRECISION = %d.\n", peer->precision);
  1197. }
  1198. #endif
  1199. up->saved_flags = pp->sloppyclockflag;
  1200. }
  1201. /* Note time of last believable timestamp. */
  1202. pp->lastrec = up->lastrec;
  1203. #ifdef ARCRON_LEAPSECOND_KEEN
  1204. /* Find out if a leap-second might just have happened...
  1205. (ie is this the first hour of the first day of Jan or Jul?)
  1206. */
  1207. if((pp->hour == 0) &&
  1208. (pp->day == 1) &&
  1209. ((month == 1) || (month == 7))) {
  1210. if(possible_leap >= 0) {
  1211. /* A leap may have happened, and no resync has started yet...*/
  1212. possible_leap = 1;
  1213. }
  1214. } else {
  1215. /* Definitely not leap-second territory... */
  1216. possible_leap = 0;
  1217. }
  1218. #endif
  1219. if (!refclock_process(pp)) {
  1220. pp->lencode = 0;
  1221. refclock_report(peer, CEVNT_BADTIME);
  1222. return;
  1223. }
  1224. record_clock_stats(&peer->srcadr, pp->a_lastcode);
  1225. refclock_receive(peer);
  1226. }
  1227. /* request_time() sends a time request to the clock with given peer. */
  1228. /* This automatically reports a fault if necessary. */
  1229. /* No data should be sent after this until arc_poll() returns. */
  1230. static void request_time P((int, struct peer *));
  1231. static void
  1232. request_time(
  1233. int unit,
  1234. struct peer *peer
  1235. )
  1236. {
  1237. struct refclockproc *pp = peer->procptr;
  1238. register struct arcunit *up = (struct arcunit *)pp->unitptr;
  1239. #ifdef DEBUG
  1240. if(debug) { printf("arc: unit %d: requesting time.\n", unit); }
  1241. #endif
  1242. if (!send_slow(up, pp->io.fd, "o\r")) {
  1243. #ifdef DEBUG
  1244. if (debug) {
  1245. printf("arc: unit %d: problem sending", unit);
  1246. }
  1247. #endif
  1248. pp->lencode = 0;
  1249. refclock_report(peer, CEVNT_FAULT);
  1250. return;
  1251. }
  1252. pp->polls++;
  1253. }
  1254. /*
  1255. * arc_poll - called by the transmit procedure
  1256. */
  1257. static void
  1258. arc_poll(
  1259. int unit,
  1260. struct peer *peer
  1261. )
  1262. {
  1263. register struct arcunit *up;
  1264. struct refclockproc *pp;
  1265. int resync_needed; /* Should we start a resync? */
  1266. pp = peer->procptr;
  1267. up = (struct arcunit *)pp->unitptr;
  1268. #if 0
  1269. pp->lencode = 0;
  1270. memset(pp->a_lastcode, 0, sizeof(pp->a_lastcode));
  1271. #endif
  1272. #if 0
  1273. /* Flush input. */
  1274. tcflush(pp->io.fd, TCIFLUSH);
  1275. #endif
  1276. /* Resync if our next scheduled resync time is here or has passed. */
  1277. resync_needed = ( !(pp->sloppyclockflag & CLK_FLAG2) &&
  1278. (up->next_resync <= current_time) );
  1279. #ifdef ARCRON_LEAPSECOND_KEEN
  1280. /*
  1281. Try to catch a potential leap-second insertion or deletion quickly.
  1282. In addition to the normal NTP fun of clocks that don't report
  1283. leap-seconds spooking their hosts, this clock does not even
  1284. sample the radio sugnal the whole time, so may miss a
  1285. leap-second insertion or deletion for up to a whole sample
  1286. time.
  1287. To try to minimise this effect, if in the first few minutes of
  1288. the day immediately following a leap-second-insertion point
  1289. (ie in the first hour of the first day of the first and sixth
  1290. months), and if the last resync was in the previous day, and a
  1291. resync is not already in progress, resync the clock
  1292. immediately.
  1293. */
  1294. if((possible_leap > 0) && /* Must be 00:XX 01/0{1,7}/XXXX. */
  1295. (!up->resyncing)) { /* No resync in progress yet. */
  1296. resync_needed = 1;
  1297. possible_leap = -1; /* Prevent multiple resyncs. */
  1298. msyslog(LOG_NOTICE,"ARCRON: unit %d: checking for leap second",unit);
  1299. }
  1300. #endif
  1301. /* Do a resync if required... */
  1302. if(resync_needed) {
  1303. /* First, reset quality value to `unknown' so we can detect */
  1304. /* when a quality message has been responded to by this */
  1305. /* being set to some other value. */
  1306. up->quality = QUALITY_UNKNOWN;
  1307. /* Note that we are resyncing... */
  1308. up->resyncing = 1;
  1309. /* Now actually send the resync command and an immediate poll. */
  1310. #ifdef DEBUG
  1311. if(debug) { printf("arc: sending resync command (h\\r).\n"); }
  1312. #endif
  1313. msyslog(LOG_NOTICE, "ARCRON: unit %d: sending resync command", unit);
  1314. send_slow(up, pp->io.fd, "h\r");
  1315. /* Schedule our next resync... */
  1316. up->next_resync = current_time + DEFAULT_RESYNC_TIME;
  1317. /* Drop through to request time if appropriate. */
  1318. }
  1319. /* If clock quality is too poor to trust, indicate a fault. */
  1320. /* If quality is QUALITY_UNKNOWN and ARCRON_KEEN is defined,*/
  1321. /* we'll cross our fingers and just hope that the thing */
  1322. /* synced so quickly we did not catch it---we'll */
  1323. /* double-check the clock is OK elsewhere. */
  1324. if(
  1325. #ifdef ARCRON_KEEN
  1326. (up->quality != QUALITY_UNKNOWN) &&
  1327. #else
  1328. (up->quality == QUALITY_UNKNOWN) ||
  1329. #endif
  1330. (up->quality < MIN_CLOCK_QUALITY_OK)) {
  1331. #ifdef DEBUG
  1332. if(debug) {
  1333. printf("arc: clock quality %d too poor.\n", up->quality);
  1334. }
  1335. #endif
  1336. pp->lencode = 0;
  1337. refclock_report(peer, CEVNT_FAULT);
  1338. return;
  1339. }
  1340. /* This is the normal case: request a timestamp. */
  1341. request_time(unit, peer);
  1342. }
  1343. #else
  1344. int refclock_arc_bs;
  1345. #endif