xref: /netbsd-src/external/bsd/ntp/dist/ntpd/refclock_nmea.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: refclock_nmea.c,v 1.12 2017/04/13 20:17:42 christos Exp $	*/
2 
3 /*
4  * refclock_nmea.c - clock driver for an NMEA GPS CLOCK
5  *		Michael Petry Jun 20, 1994
6  *		 based on refclock_heathn.c
7  *
8  * Updated to add support for Accord GPS Clock
9  *		Venu Gopal Dec 05, 2007
10  *		neo.venu@gmail.com, venugopal_d@pgad.gov.in
11  *
12  * Updated to process 'time1' fudge factor
13  *		Venu Gopal May 05, 2008
14  *
15  * Converted to common PPSAPI code, separate PPS fudge time1
16  * from serial timecode fudge time2.
17  *		Dave Hart July 1, 2009
18  *		hart@ntp.org, davehart@davehart.com
19  */
20 
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24 
25 #include "ntp_types.h"
26 
27 #if defined(REFCLOCK) && defined(CLOCK_NMEA)
28 
29 #define NMEA_WRITE_SUPPORT 0 /* no write support at the moment */
30 
31 #include <sys/stat.h>
32 #include <stdio.h>
33 #include <ctype.h>
34 #ifdef HAVE_SYS_SOCKET_H
35 #include <sys/socket.h>
36 #endif
37 
38 #include "ntpd.h"
39 #include "ntp_io.h"
40 #include "ntp_unixtime.h"
41 #include "ntp_refclock.h"
42 #include "ntp_stdlib.h"
43 #include "ntp_calendar.h"
44 #include "timespecops.h"
45 
46 #ifdef HAVE_PPSAPI
47 # include "ppsapi_timepps.h"
48 # include "refclock_atom.h"
49 #endif /* HAVE_PPSAPI */
50 
51 
52 /*
53  * This driver supports NMEA-compatible GPS receivers
54  *
55  * Prototype was refclock_trak.c, Thanks a lot.
56  *
57  * The receiver used spits out the NMEA sentences for boat navigation.
58  * And you thought it was an information superhighway.	Try a raging river
59  * filled with rapids and whirlpools that rip away your data and warp time.
60  *
61  * If HAVE_PPSAPI is defined code to use the PPSAPI will be compiled in.
62  * On startup if initialization of the PPSAPI fails, it will fall back
63  * to the "normal" timestamps.
64  *
65  * The PPSAPI part of the driver understands fudge flag2 and flag3. If
66  * flag2 is set, it will use the clear edge of the pulse. If flag3 is
67  * set, kernel hardpps is enabled.
68  *
69  * GPS sentences other than RMC (the default) may be enabled by setting
70  * the relevent bits of 'mode' in the server configuration line
71  * server 127.127.20.x mode X
72  *
73  * bit 0 - enables RMC (1)
74  * bit 1 - enables GGA (2)
75  * bit 2 - enables GLL (4)
76  * bit 3 - enables ZDA (8) - Standard Time & Date
77  * bit 3 - enables ZDG (8) - Accord GPS Clock's custom sentence with GPS time
78  *			     very close to standard ZDA
79  *
80  * Multiple sentences may be selected except when ZDG/ZDA is selected.
81  *
82  * bit 4/5/6 - selects the baudrate for serial port :
83  *		0 for 4800 (default)
84  *		1 for 9600
85  *		2 for 19200
86  *		3 for 38400
87  *		4 for 57600
88  *		5 for 115200
89  */
90 #define NMEA_MESSAGE_MASK	0x0000FF0FU
91 #define NMEA_BAUDRATE_MASK	0x00000070U
92 #define NMEA_BAUDRATE_SHIFT	4
93 
94 #define NMEA_DELAYMEAS_MASK	0x80
95 #define NMEA_EXTLOG_MASK	0x00010000U
96 #define NMEA_DATETRUST_MASK	0x02000000U
97 
98 #define NMEA_PROTO_IDLEN	5	/* tag name must be at least 5 chars */
99 #define NMEA_PROTO_MINLEN	6	/* min chars in sentence, excluding CS */
100 #define NMEA_PROTO_MAXLEN	80	/* max chars in sentence, excluding CS */
101 #define NMEA_PROTO_FIELDS	32	/* not official; limit on fields per record */
102 
103 /*
104  * We check the timecode format and decode its contents.  We only care
105  * about a few of them, the most important being the $GPRMC format:
106  *
107  * $GPRMC,hhmmss,a,fddmm.xx,n,dddmmm.xx,w,zz.z,yyy.,ddmmyy,dd,v*CC
108  *
109  * mode (0,1,2,3) selects sentence ANY/ALL, RMC, GGA, GLL, ZDA
110  * $GPGLL,3513.8385,S,14900.7851,E,232420.594,A*21
111  * $GPGGA,232420.59,3513.8385,S,14900.7851,E,1,05,3.4,00519,M,,,,*3F
112  * $GPRMC,232418.19,A,3513.8386,S,14900.7853,E,00.0,000.0,121199,12.,E*77
113  *
114  * Defining GPZDA to support Standard Time & Date
115  * sentence. The sentence has the following format
116  *
117  *  $--ZDA,HHMMSS.SS,DD,MM,YYYY,TH,TM,*CS<CR><LF>
118  *
119  *  Apart from the familiar fields,
120  *  'TH'    Time zone Hours
121  *  'TM'    Time zone Minutes
122  *
123  * Defining GPZDG to support Accord GPS Clock's custom NMEA
124  * sentence. The sentence has the following format
125  *
126  *  $GPZDG,HHMMSS.S,DD,MM,YYYY,AA.BB,V*CS<CR><LF>
127  *
128  *  It contains the GPS timestamp valid for next PPS pulse.
129  *  Apart from the familiar fields,
130  *  'AA.BB' denotes the signal strength( should be < 05.00 )
131  *  'V'	    denotes the GPS sync status :
132  *	   '0' indicates INVALID time,
133  *	   '1' indicates accuracy of +/-20 ms
134  *	   '2' indicates accuracy of +/-100 ns
135  *
136  * Defining PGRMF for Garmin GPS Fix Data
137  * $PGRMF,WN,WS,DATE,TIME,LS,LAT,LAT_DIR,LON,LON_DIR,MODE,FIX,SPD,DIR,PDOP,TDOP
138  * WN  -- GPS week number (weeks since 1980-01-06, mod 1024)
139  * WS  -- GPS seconds in week
140  * LS  -- GPS leap seconds, accumulated ( UTC + LS == GPS )
141  * FIX -- Fix type: 0=nofix, 1=2D, 2=3D
142  * DATE/TIME are standard date/time strings in UTC time scale
143  *
144  * The GPS time can be used to get the full century for the truncated
145  * date spec.
146  */
147 
148 /*
149  * Definitions
150  */
151 #define	DEVICE		"/dev/gps%d"	/* GPS serial device */
152 #define	PPSDEV		"/dev/gpspps%d"	/* PPSAPI device override */
153 #define	SPEED232	B4800	/* uart speed (4800 bps) */
154 #define	PRECISION	(-9)	/* precision assumed (about 2 ms) */
155 #define	PPS_PRECISION	(-20)	/* precision assumed (about 1 us) */
156 #define	REFID		"GPS\0"	/* reference id */
157 #define	DESCRIPTION	"NMEA GPS Clock" /* who we are */
158 #ifndef O_NOCTTY
159 #define M_NOCTTY	0
160 #else
161 #define M_NOCTTY	O_NOCTTY
162 #endif
163 #ifndef O_NONBLOCK
164 #define M_NONBLOCK	0
165 #else
166 #define M_NONBLOCK	O_NONBLOCK
167 #endif
168 #define PPSOPENMODE	(O_RDWR | M_NOCTTY | M_NONBLOCK)
169 
170 /* NMEA sentence array indexes for those we use */
171 #define NMEA_GPRMC	0	/* recommended min. nav. */
172 #define NMEA_GPGGA	1	/* fix and quality */
173 #define NMEA_GPGLL	2	/* geo. lat/long */
174 #define NMEA_GPZDA	3	/* date/time */
175 /*
176  * $GPZDG is a proprietary sentence that violates the spec, by not
177  * using $P and an assigned company identifier to prefix the sentence
178  * identifier.	When used with this driver, the system needs to be
179  * isolated from other NTP networks, as it operates in GPS time, not
180  * UTC as is much more common.	GPS time is >15 seconds different from
181  * UTC due to not respecting leap seconds since 1970 or so.  Other
182  * than the different timebase, $GPZDG is similar to $GPZDA.
183  */
184 #define NMEA_GPZDG	4
185 #define NMEA_PGRMF	5
186 #define NMEA_ARRAY_SIZE (NMEA_PGRMF + 1)
187 
188 /*
189  * Sentence selection mode bits
190  */
191 #define USE_GPRMC		0x00000001u
192 #define USE_GPGGA		0x00000002u
193 #define USE_GPGLL		0x00000004u
194 #define USE_GPZDA		0x00000008u
195 #define USE_PGRMF		0x00000100u
196 
197 /* mapping from sentence index to controlling mode bit */
198 static const u_int32 sentence_mode[NMEA_ARRAY_SIZE] =
199 {
200 	USE_GPRMC,
201 	USE_GPGGA,
202 	USE_GPGLL,
203 	USE_GPZDA,
204 	USE_GPZDA,
205 	USE_PGRMF
206 };
207 
208 /* date formats we support */
209 enum date_fmt {
210 	DATE_1_DDMMYY,	/* use 1 field	with 2-digit year */
211 	DATE_3_DDMMYYYY	/* use 3 fields with 4-digit year */
212 };
213 
214 /* results for 'field_init()'
215  *
216  * Note: If a checksum is present, the checksum test must pass OK or the
217  * sentence is tagged invalid.
218  */
219 #define CHECK_EMPTY  -1	/* no data			*/
220 #define CHECK_INVALID 0	/* not a valid NMEA sentence	*/
221 #define CHECK_VALID   1	/* valid but without checksum	*/
222 #define CHECK_CSVALID 2	/* valid with checksum OK	*/
223 
224 /*
225  * Unit control structure
226  */
227 typedef struct {
228 #ifdef HAVE_PPSAPI
229 	struct refclock_atom atom; /* PPSAPI structure */
230 	int	ppsapi_fd;	/* fd used with PPSAPI */
231 	u_char	ppsapi_tried;	/* attempt PPSAPI once */
232 	u_char	ppsapi_lit;	/* time_pps_create() worked */
233 	u_char	ppsapi_gate;	/* system is on PPS */
234 #endif /* HAVE_PPSAPI */
235 	u_char  gps_time;	/* use GPS time, not UTC */
236 	u_short century_cache;	/* cached current century */
237 	l_fp	last_reftime;	/* last processed reference stamp */
238 	short 	epoch_warp;	/* last epoch warp, for logging */
239 	/* tally stats, reset each poll cycle */
240 	struct
241 	{
242 		u_int total;
243 		u_int accepted;
244 		u_int rejected;   /* GPS said not enough signal */
245 		u_int malformed;  /* Bad checksum, invalid date or time */
246 		u_int filtered;   /* mode bits, not GPZDG, same second */
247 		u_int pps_used;
248 	}
249 		tally;
250 	/* per sentence checksum seen flag */
251 	u_char	cksum_type[NMEA_ARRAY_SIZE];
252 } nmea_unit;
253 
254 /*
255  * helper for faster field access
256  */
257 typedef struct {
258 	char  *base;	/* buffer base		*/
259 	char  *cptr;	/* current field ptr	*/
260 	int    blen;	/* buffer length	*/
261 	int    cidx;	/* current field index	*/
262 } nmea_data;
263 
264 /*
265  * NMEA gps week/time information
266  * This record contains the number of weeks since 1980-01-06 modulo
267  * 1024, the seconds elapsed since start of the week, and the number of
268  * leap seconds that are the difference between GPS and UTC time scale.
269  */
270 typedef struct {
271 	u_int32 wt_time;	/* seconds since weekstart */
272 	u_short wt_week;	/* week number */
273 	short	wt_leap;	/* leap seconds */
274 } gps_weektm;
275 
276 /*
277  * The GPS week time scale starts on Sunday, 1980-01-06. We need the
278  * rata die number of this day.
279  */
280 #ifndef DAY_GPS_STARTS
281 #define DAY_GPS_STARTS 722820
282 #endif
283 
284 /*
285  * Function prototypes
286  */
287 static	void	nmea_init	(void);
288 static	int	nmea_start	(int, struct peer *);
289 static	void	nmea_shutdown	(int, struct peer *);
290 static	void	nmea_receive	(struct recvbuf *);
291 static	void	nmea_poll	(int, struct peer *);
292 #ifdef HAVE_PPSAPI
293 static	void	nmea_control	(int, const struct refclockstat *,
294 				 struct refclockstat *, struct peer *);
295 #define		NMEA_CONTROL	nmea_control
296 #else
297 #define		NMEA_CONTROL	noentry
298 #endif /* HAVE_PPSAPI */
299 static	void	nmea_timer	(int, struct peer *);
300 
301 /* parsing helpers */
302 static int	field_init	(nmea_data * data, char * cp, int len);
303 static char *	field_parse	(nmea_data * data, int fn);
304 static void	field_wipe	(nmea_data * data, ...);
305 static u_char	parse_qual	(nmea_data * data, int idx,
306 				 char tag, int inv);
307 static int	parse_time	(struct calendar * jd, long * nsec,
308 				 nmea_data *, int idx);
309 static int	parse_date	(struct calendar *jd, nmea_data*,
310 				 int idx, enum date_fmt fmt);
311 static int	parse_weekdata	(gps_weektm *, nmea_data *,
312 				 int weekidx, int timeidx, int leapidx);
313 /* calendar / date helpers */
314 static int	unfold_day	(struct calendar * jd, u_int32 rec_ui);
315 static int	unfold_century	(struct calendar * jd, u_int32 rec_ui);
316 static int	gpsfix_century	(struct calendar * jd, const gps_weektm * wd,
317 				 u_short * ccentury);
318 static l_fp     eval_gps_time	(struct peer * peer, const struct calendar * gpst,
319 				 const struct timespec * gpso, const l_fp * xrecv);
320 
321 static int	nmead_open	(const char * device);
322 static void     save_ltc        (struct refclockproc * const, const char * const,
323 				 size_t);
324 
325 /*
326  * If we want the driver to ouput sentences, too: re-enable the send
327  * support functions by defining NMEA_WRITE_SUPPORT to non-zero...
328  */
329 #if NMEA_WRITE_SUPPORT
330 
331 static	void gps_send(int, const char *, struct peer *);
332 # ifdef SYS_WINNT
333 #  undef write	/* ports/winnt/include/config.h: #define write _write */
334 extern int async_write(int, const void *, unsigned int);
335 #  define write(fd, data, octets)	async_write(fd, data, octets)
336 # endif /* SYS_WINNT */
337 
338 #endif /* NMEA_WRITE_SUPPORT */
339 
340 static int32_t g_gpsMinBase;
341 static int32_t g_gpsMinYear;
342 
343 /*
344  * -------------------------------------------------------------------
345  * Transfer vector
346  * -------------------------------------------------------------------
347  */
348 struct refclock refclock_nmea = {
349 	nmea_start,		/* start up driver */
350 	nmea_shutdown,		/* shut down driver */
351 	nmea_poll,		/* transmit poll message */
352 	NMEA_CONTROL,		/* fudge control */
353 	nmea_init,		/* initialize driver */
354 	noentry,		/* buginfo */
355 	nmea_timer		/* called once per second */
356 };
357 
358 /*
359  * -------------------------------------------------------------------
360  * nmea_init - initialise data
361  *
362  * calculates a few runtime constants that cannot be made compile time
363  * constants.
364  * -------------------------------------------------------------------
365  */
366 static void
367 nmea_init(void)
368 {
369 	struct calendar date;
370 
371 	/* - calculate min. base value for GPS epoch & century unfolding
372 	 * This assumes that the build system was roughly in sync with
373 	 * the world, and that really synchronising to a time before the
374 	 * program was created would be unsafe or insane. If the build
375 	 * date cannot be stablished, at least use the start of GPS
376 	 * (1980-01-06) as minimum, because GPS can surely NOT
377 	 * synchronise beyond it's own big bang. We add a little safety
378 	 * margin for the fuzziness of the build date, which is in an
379 	 * undefined time zone. */
380 	if (ntpcal_get_build_date(&date))
381 		g_gpsMinBase = ntpcal_date_to_rd(&date) - 2;
382 	else
383 		g_gpsMinBase = 0;
384 
385 	if (g_gpsMinBase < DAY_GPS_STARTS)
386 		g_gpsMinBase = DAY_GPS_STARTS;
387 
388 	ntpcal_rd_to_date(&date, g_gpsMinBase);
389 	g_gpsMinYear  = date.year;
390 	g_gpsMinBase -= DAY_NTP_STARTS;
391 }
392 
393 /*
394  * -------------------------------------------------------------------
395  * nmea_start - open the GPS devices and initialize data for processing
396  *
397  * return 0 on error, 1 on success. Even on error the peer structures
398  * must be in a state that permits 'nmea_shutdown()' to clean up all
399  * resources, because it will be called immediately to do so.
400  * -------------------------------------------------------------------
401  */
402 static int
403 nmea_start(
404 	int		unit,
405 	struct peer *	peer
406 	)
407 {
408 	struct refclockproc * const	pp = peer->procptr;
409 	nmea_unit * const		up = emalloc_zero(sizeof(*up));
410 	char				device[20];
411 	size_t				devlen;
412 	u_int32				rate;
413 	int				baudrate;
414 	const char *			baudtext;
415 
416 
417 	/* Get baudrate choice from mode byte bits 4/5/6 */
418 	rate = (peer->ttl & NMEA_BAUDRATE_MASK) >> NMEA_BAUDRATE_SHIFT;
419 
420 	switch (rate) {
421 	case 0:
422 		baudrate = SPEED232;
423 		baudtext = "4800";
424 		break;
425 	case 1:
426 		baudrate = B9600;
427 		baudtext = "9600";
428 		break;
429 	case 2:
430 		baudrate = B19200;
431 		baudtext = "19200";
432 		break;
433 	case 3:
434 		baudrate = B38400;
435 		baudtext = "38400";
436 		break;
437 #ifdef B57600
438 	case 4:
439 		baudrate = B57600;
440 		baudtext = "57600";
441 		break;
442 #endif
443 #ifdef B115200
444 	case 5:
445 		baudrate = B115200;
446 		baudtext = "115200";
447 		break;
448 #endif
449 	default:
450 		baudrate = SPEED232;
451 		baudtext = "4800 (fallback)";
452 		break;
453 	}
454 
455 	/* Allocate and initialize unit structure */
456 	pp->unitptr = (caddr_t)up;
457 	pp->io.fd = -1;
458 	pp->io.clock_recv = nmea_receive;
459 	pp->io.srcclock = peer;
460 	pp->io.datalen = 0;
461 	/* force change detection on first valid message */
462 	memset(&up->last_reftime, 0xFF, sizeof(up->last_reftime));
463 	/* force checksum on GPRMC, see below */
464 	up->cksum_type[NMEA_GPRMC] = CHECK_CSVALID;
465 #ifdef HAVE_PPSAPI
466 	up->ppsapi_fd = -1;
467 #endif
468 	ZERO(up->tally);
469 
470 	/* Initialize miscellaneous variables */
471 	peer->precision = PRECISION;
472 	pp->clockdesc = DESCRIPTION;
473 	memcpy(&pp->refid, REFID, 4);
474 
475 	/* Open serial port. Use CLK line discipline, if available. */
476 	devlen = snprintf(device, sizeof(device), DEVICE, unit);
477 	if (devlen >= sizeof(device)) {
478 		msyslog(LOG_ERR, "%s clock device name too long",
479 			refnumtoa(&peer->srcadr));
480 		return FALSE; /* buffer overflow */
481 	}
482 	pp->io.fd = refclock_open(device, baudrate, LDISC_CLK);
483 	if (0 >= pp->io.fd) {
484 		pp->io.fd = nmead_open(device);
485 		if (-1 == pp->io.fd)
486 			return FALSE;
487 	}
488 	LOGIF(CLOCKINFO, (LOG_NOTICE, "%s serial %s open at %s bps",
489 	      refnumtoa(&peer->srcadr), device, baudtext));
490 
491 	/* succeed if this clock can be added */
492 	return io_addclock(&pp->io) != 0;
493 }
494 
495 
496 /*
497  * -------------------------------------------------------------------
498  * nmea_shutdown - shut down a GPS clock
499  *
500  * NOTE this routine is called after nmea_start() returns failure,
501  * as well as during a normal shutdown due to ntpq :config unpeer.
502  * -------------------------------------------------------------------
503  */
504 static void
505 nmea_shutdown(
506 	int           unit,
507 	struct peer * peer
508 	)
509 {
510 	struct refclockproc * const pp = peer->procptr;
511 	nmea_unit	    * const up = (nmea_unit *)pp->unitptr;
512 
513 	UNUSED_ARG(unit);
514 
515 	if (up != NULL) {
516 #ifdef HAVE_PPSAPI
517 		if (up->ppsapi_lit)
518 			time_pps_destroy(up->atom.handle);
519 		if (up->ppsapi_tried && up->ppsapi_fd != pp->io.fd)
520 			close(up->ppsapi_fd);
521 #endif
522 		free(up);
523 	}
524 	pp->unitptr = (caddr_t)NULL;
525 	if (-1 != pp->io.fd)
526 		io_closeclock(&pp->io);
527 	pp->io.fd = -1;
528 }
529 
530 /*
531  * -------------------------------------------------------------------
532  * nmea_control - configure fudge params
533  * -------------------------------------------------------------------
534  */
535 #ifdef HAVE_PPSAPI
536 static void
537 nmea_control(
538 	int                         unit,
539 	const struct refclockstat * in_st,
540 	struct refclockstat       * out_st,
541 	struct peer               * peer
542 	)
543 {
544 	struct refclockproc * const pp = peer->procptr;
545 	nmea_unit	    * const up = (nmea_unit *)pp->unitptr;
546 
547 	char   device[32];
548 	size_t devlen;
549 
550 	UNUSED_ARG(in_st);
551 	UNUSED_ARG(out_st);
552 
553 	/*
554 	 * PPS control
555 	 *
556 	 * If /dev/gpspps$UNIT can be opened that will be used for
557 	 * PPSAPI.  Otherwise, the GPS serial device /dev/gps$UNIT
558 	 * already opened is used for PPSAPI as well. (This might not
559 	 * work, in which case the PPS API remains unavailable...)
560 	 */
561 
562 	/* Light up the PPSAPI interface if not yet attempted. */
563 	if ((CLK_FLAG1 & pp->sloppyclockflag) && !up->ppsapi_tried) {
564 		up->ppsapi_tried = TRUE;
565 		devlen = snprintf(device, sizeof(device), PPSDEV, unit);
566 		if (devlen < sizeof(device)) {
567 			up->ppsapi_fd = open(device, PPSOPENMODE,
568 					     S_IRUSR | S_IWUSR);
569 		} else {
570 			up->ppsapi_fd = -1;
571 			msyslog(LOG_ERR, "%s PPS device name too long",
572 				refnumtoa(&peer->srcadr));
573 		}
574 		if (-1 == up->ppsapi_fd)
575 			up->ppsapi_fd = pp->io.fd;
576 		if (refclock_ppsapi(up->ppsapi_fd, &up->atom)) {
577 			/* use the PPS API for our own purposes now. */
578 			up->ppsapi_lit = refclock_params(
579 				pp->sloppyclockflag, &up->atom);
580 			if (!up->ppsapi_lit) {
581 				/* failed to configure, drop PPS unit */
582 				time_pps_destroy(up->atom.handle);
583 				msyslog(LOG_WARNING,
584 					"%s set PPSAPI params fails",
585 					refnumtoa(&peer->srcadr));
586 			}
587 			/* note: the PPS I/O handle remains valid until
588 			 * flag1 is cleared or the clock is shut down.
589 			 */
590 		} else {
591 			msyslog(LOG_WARNING,
592 				"%s flag1 1 but PPSAPI fails",
593 				refnumtoa(&peer->srcadr));
594 		}
595 	}
596 
597 	/* shut down PPS API if activated */
598 	if (!(CLK_FLAG1 & pp->sloppyclockflag) && up->ppsapi_tried) {
599 		/* shutdown PPS API */
600 		if (up->ppsapi_lit)
601 			time_pps_destroy(up->atom.handle);
602 		up->atom.handle = 0;
603 		/* close/drop PPS fd */
604 		if (up->ppsapi_fd != pp->io.fd)
605 			close(up->ppsapi_fd);
606 		up->ppsapi_fd = -1;
607 
608 		/* clear markers and peer items */
609 		up->ppsapi_gate  = FALSE;
610 		up->ppsapi_lit   = FALSE;
611 		up->ppsapi_tried = FALSE;
612 
613 		peer->flags &= ~FLAG_PPS;
614 		peer->precision = PRECISION;
615 	}
616 }
617 #endif	/* HAVE_PPSAPI */
618 
619 /*
620  * -------------------------------------------------------------------
621  * nmea_timer - called once per second
622  *		this only polls (older?) Oncore devices now
623  *
624  * Usually 'nmea_receive()' can get a timestamp every second, but at
625  * least one Motorola unit needs prompting each time. Doing so in
626  * 'nmea_poll()' gives only one sample per poll cycle, which actually
627  * defeats the purpose of the median filter. Polling once per second
628  * seems a much better idea.
629  * -------------------------------------------------------------------
630  */
631 static void
632 nmea_timer(
633 	int	      unit,
634 	struct peer * peer
635 	)
636 {
637 #if NMEA_WRITE_SUPPORT
638 
639 	struct refclockproc * const pp = peer->procptr;
640 
641 	UNUSED_ARG(unit);
642 
643 	if (-1 != pp->io.fd) /* any mode bits to evaluate here? */
644 		gps_send(pp->io.fd, "$PMOTG,RMC,0000*1D\r\n", peer);
645 #else
646 
647 	UNUSED_ARG(unit);
648 	UNUSED_ARG(peer);
649 
650 #endif /* NMEA_WRITE_SUPPORT */
651 }
652 
653 #ifdef HAVE_PPSAPI
654 /*
655  * -------------------------------------------------------------------
656  * refclock_ppsrelate(...) -- correlate with PPS edge
657  *
658  * This function is used to correlate a receive time stamp and a
659  * reference time with a PPS edge time stamp. It applies the necessary
660  * fudges (fudge1 for PPS, fudge2 for receive time) and then tries to
661  * move the receive time stamp to the corresponding edge. This can warp
662  * into future, if a transmission delay of more than 500ms is not
663  * compensated with a corresponding fudge time2 value, because then the
664  * next PPS edge is nearer than the last. (Similiar to what the PPS ATOM
665  * driver does, but we deal with full time stamps here, not just phase
666  * shift information.) Likewise, a negative fudge time2 value must be
667  * used if the reference time stamp correlates with the *following* PPS
668  * pulse.
669  *
670  * Note that the receive time fudge value only needs to move the receive
671  * stamp near a PPS edge but that close proximity is not required;
672  * +/-100ms precision should be enough. But since the fudge value will
673  * probably also be used to compensate the transmission delay when no
674  * PPS edge can be related to the time stamp, it's best to get it as
675  * close as possible.
676  *
677  * It should also be noted that the typical use case is matching to the
678  * preceeding edge, as most units relate their sentences to the current
679  * second.
680  *
681  * The function returns PPS_RELATE_NONE (0) if no PPS edge correlation
682  * can be fixed; PPS_RELATE_EDGE (1) when a PPS edge could be fixed, but
683  * the distance to the reference time stamp is too big (exceeds
684  * +/-400ms) and the ATOM driver PLL cannot be used to fix the phase;
685  * and PPS_RELATE_PHASE (2) when the ATOM driver PLL code can be used.
686  *
687  * On output, the receive time stamp is replaced with the corresponding
688  * PPS edge time if a fix could be made; the PPS fudge is updated to
689  * reflect the proper fudge time to apply. (This implies that
690  * 'refclock_process_offset()' must be used!)
691  * -------------------------------------------------------------------
692  */
693 #define PPS_RELATE_NONE	 0	/* no pps correlation possible	  */
694 #define PPS_RELATE_EDGE	 1	/* recv time fixed, no phase lock */
695 #define PPS_RELATE_PHASE 2	/* recv time fixed, phase lock ok */
696 
697 static int
698 refclock_ppsrelate(
699 	const struct refclockproc  * pp	    ,	/* for sanity	  */
700 	const struct refclock_atom * ap	    ,	/* for PPS io	  */
701 	const l_fp		   * reftime ,
702 	l_fp			   * rd_stamp,	/* i/o read stamp */
703 	double			     pp_fudge,	/* pps fudge	  */
704 	double			   * rd_fudge	/* i/o read fudge */
705 	)
706 {
707 	pps_info_t	pps_info;
708 	struct timespec timeout;
709 	l_fp		pp_stamp, pp_delta;
710 	double		delta, idelta;
711 
712 	if (pp->leap == LEAP_NOTINSYNC)
713 		return PPS_RELATE_NONE; /* clock is insane, no chance */
714 
715 	ZERO(timeout);
716 	ZERO(pps_info);
717 	if (time_pps_fetch(ap->handle, PPS_TSFMT_TSPEC,
718 			   &pps_info, &timeout) < 0)
719 		return PPS_RELATE_NONE; /* can't get time stamps */
720 
721 	/* get last active PPS edge before receive */
722 	if (ap->pps_params.mode & PPS_CAPTUREASSERT)
723 		timeout = pps_info.assert_timestamp;
724 	else if (ap->pps_params.mode & PPS_CAPTURECLEAR)
725 		timeout = pps_info.clear_timestamp;
726 	else
727 		return PPS_RELATE_NONE; /* WHICH edge, please?!? */
728 
729 	/* get delta between receive time and PPS time */
730 	pp_stamp = tspec_stamp_to_lfp(timeout);
731 	pp_delta = *rd_stamp;
732 	L_SUB(&pp_delta, &pp_stamp);
733 	LFPTOD(&pp_delta, delta);
734 	delta += pp_fudge - *rd_fudge;
735 	if (fabs(delta) > 1.5)
736 		return PPS_RELATE_NONE; /* PPS timeout control */
737 
738 	/* eventually warp edges, check phase */
739 	idelta	  = floor(delta + 0.5);
740 	pp_fudge -= idelta;
741 	delta	 -= idelta;
742 	if (fabs(delta) > 0.45)
743 		return PPS_RELATE_NONE; /* dead band control */
744 
745 	/* we actually have a PPS edge to relate with! */
746 	*rd_stamp = pp_stamp;
747 	*rd_fudge = pp_fudge;
748 
749 	/* if whole system out-of-sync, do not try to PLL */
750 	if (sys_leap == LEAP_NOTINSYNC)
751 		return PPS_RELATE_EDGE; /* cannot PLL with atom code */
752 
753 	/* check against reftime if ATOM PLL can be used */
754 	pp_delta = *reftime;
755 	L_SUB(&pp_delta, &pp_stamp);
756 	LFPTOD(&pp_delta, delta);
757 	delta += pp_fudge;
758 	if (fabs(delta) > 0.45)
759 		return PPS_RELATE_EDGE; /* cannot PLL with atom code */
760 
761 	/* all checks passed, gets an AAA rating here! */
762 	return PPS_RELATE_PHASE; /* can PLL with atom code */
763 }
764 #endif	/* HAVE_PPSAPI */
765 
766 /*
767  * -------------------------------------------------------------------
768  * nmea_receive - receive data from the serial interface
769  *
770  * This is the workhorse for NMEA data evaluation:
771  *
772  * + it checks all NMEA data, and rejects sentences that are not valid
773  *   NMEA sentences
774  * + it checks whether a sentence is known and to be used
775  * + it parses the time and date data from the NMEA data string and
776  *   augments the missing bits. (century in dat, whole date, ...)
777  * + it rejects data that is not from the first accepted sentence in a
778  *   burst
779  * + it eventually replaces the receive time with the PPS edge time.
780  * + it feeds the data to the internal processing stages.
781  * -------------------------------------------------------------------
782  */
783 static void
784 nmea_receive(
785 	struct recvbuf * rbufp
786 	)
787 {
788 	/* declare & init control structure ptrs */
789 	struct peer	    * const peer = rbufp->recv_peer;
790 	struct refclockproc * const pp = peer->procptr;
791 	nmea_unit	    * const up = (nmea_unit*)pp->unitptr;
792 
793 	/* Use these variables to hold data until we decide its worth keeping */
794 	nmea_data rdata;
795 	char 	  rd_lastcode[BMAX];
796 	l_fp 	  rd_timestamp, rd_reftime;
797 	int	  rd_lencode;
798 	double	  rd_fudge;
799 
800 	/* working stuff */
801 	struct calendar date;	/* to keep & convert the time stamp */
802 	struct timespec tofs;	/* offset to full-second reftime */
803 	gps_weektm      gpsw;	/* week time storage */
804 	/* results of sentence/date/time parsing */
805 	u_char		sentence;	/* sentence tag */
806 	int		checkres;
807 	char *		cp;
808 	int		rc_date;
809 	int		rc_time;
810 
811 	/* make sure data has defined pristine state */
812 	ZERO(tofs);
813 	ZERO(date);
814 	ZERO(gpsw);
815 
816 	/*
817 	 * Read the timecode and timestamp, then initialise field
818 	 * processing. The <CR><LF> at the NMEA line end is translated
819 	 * to <LF><LF> by the terminal input routines on most systems,
820 	 * and this gives us one spurious empty read per record which we
821 	 * better ignore silently.
822 	 */
823 	rd_lencode = refclock_gtlin(rbufp, rd_lastcode,
824 				    sizeof(rd_lastcode), &rd_timestamp);
825 	checkres = field_init(&rdata, rd_lastcode, rd_lencode);
826 	switch (checkres) {
827 
828 	case CHECK_INVALID:
829 		DPRINTF(1, ("%s invalid data: '%s'\n",
830 			refnumtoa(&peer->srcadr), rd_lastcode));
831 		refclock_report(peer, CEVNT_BADREPLY);
832 		return;
833 
834 	case CHECK_EMPTY:
835 		return;
836 
837 	default:
838 		DPRINTF(1, ("%s gpsread: %d '%s'\n",
839 			refnumtoa(&peer->srcadr), rd_lencode,
840 			rd_lastcode));
841 		break;
842 	}
843 	up->tally.total++;
844 
845 	/*
846 	 * --> below this point we have a valid NMEA sentence <--
847 	 *
848 	 * Check sentence name. Skip first 2 chars (talker ID) in most
849 	 * cases, to allow for $GLGGA and $GPGGA etc. Since the name
850 	 * field has at least 5 chars we can simply shift the field
851 	 * start.
852 	 */
853 	cp = field_parse(&rdata, 0);
854 	if      (strncmp(cp + 2, "RMC,", 4) == 0)
855 		sentence = NMEA_GPRMC;
856 	else if (strncmp(cp + 2, "GGA,", 4) == 0)
857 		sentence = NMEA_GPGGA;
858 	else if (strncmp(cp + 2, "GLL,", 4) == 0)
859 		sentence = NMEA_GPGLL;
860 	else if (strncmp(cp + 2, "ZDA,", 4) == 0)
861 		sentence = NMEA_GPZDA;
862 	else if (strncmp(cp + 2, "ZDG,", 4) == 0)
863 		sentence = NMEA_GPZDG;
864 	else if (strncmp(cp,   "PGRMF,", 6) == 0)
865 		sentence = NMEA_PGRMF;
866 	else
867 		return;	/* not something we know about */
868 
869 	/* Eventually output delay measurement now. */
870 	if (peer->ttl & NMEA_DELAYMEAS_MASK) {
871 		mprintf_clock_stats(&peer->srcadr, "delay %0.6f %.*s",
872 			 ldexp(rd_timestamp.l_uf, -32),
873 			 (int)(strchr(rd_lastcode, ',') - rd_lastcode),
874 			 rd_lastcode);
875 	}
876 
877 	/* See if I want to process this message type */
878 	if ((peer->ttl & NMEA_MESSAGE_MASK) &&
879 	    !(peer->ttl & sentence_mode[sentence])) {
880 		up->tally.filtered++;
881 		return;
882 	}
883 
884 	/*
885 	 * make sure it came in clean
886 	 *
887 	 * Apparently, older NMEA specifications (which are expensive)
888 	 * did not require the checksum for all sentences.  $GPMRC is
889 	 * the only one so far identified which has always been required
890 	 * to include a checksum.
891 	 *
892 	 * Today, most NMEA GPS receivers checksum every sentence.  To
893 	 * preserve its error-detection capabilities with modern GPSes
894 	 * while allowing operation without checksums on all but $GPMRC,
895 	 * we keep track of whether we've ever seen a valid checksum on
896 	 * a given sentence, and if so, reject future instances without
897 	 * checksum.  ('up->cksum_type[NMEA_GPRMC]' is set in
898 	 * 'nmea_start()' to enforce checksums for $GPRMC right from the
899 	 * start.)
900 	 */
901 	if (up->cksum_type[sentence] <= (u_char)checkres) {
902 		up->cksum_type[sentence] = (u_char)checkres;
903 	} else {
904 		DPRINTF(1, ("%s checksum missing: '%s'\n",
905 			refnumtoa(&peer->srcadr), rd_lastcode));
906 		refclock_report(peer, CEVNT_BADREPLY);
907 		up->tally.malformed++;
908 		return;
909 	}
910 
911 	/*
912 	 * $GPZDG provides GPS time not UTC, and the two mix poorly.
913 	 * Once have processed a $GPZDG, do not process any further UTC
914 	 * sentences (all but $GPZDG currently).
915 	 */
916 	if (up->gps_time && NMEA_GPZDG != sentence) {
917 		up->tally.filtered++;
918 		return;
919 	}
920 
921 	DPRINTF(1, ("%s processing %d bytes, timecode '%s'\n",
922 		refnumtoa(&peer->srcadr), rd_lencode, rd_lastcode));
923 
924 	/*
925 	 * Grab fields depending on clock string type and possibly wipe
926 	 * sensitive data from the last timecode.
927 	 */
928 	switch (sentence) {
929 
930 	case NMEA_GPRMC:
931 		/* Check quality byte, fetch data & time */
932 		rc_time	 = parse_time(&date, &tofs.tv_nsec, &rdata, 1);
933 		pp->leap = parse_qual(&rdata, 2, 'A', 0);
934 		rc_date	 = parse_date(&date, &rdata, 9, DATE_1_DDMMYY)
935 			&& unfold_century(&date, rd_timestamp.l_ui);
936 		if (CLK_FLAG4 & pp->sloppyclockflag)
937 			field_wipe(&rdata, 3, 4, 5, 6, -1);
938 		break;
939 
940 	case NMEA_GPGGA:
941 		/* Check quality byte, fetch time only */
942 		rc_time	 = parse_time(&date, &tofs.tv_nsec, &rdata, 1);
943 		pp->leap = parse_qual(&rdata, 6, '0', 1);
944 		rc_date	 = unfold_day(&date, rd_timestamp.l_ui);
945 		if (CLK_FLAG4 & pp->sloppyclockflag)
946 			field_wipe(&rdata, 2, 4, -1);
947 		break;
948 
949 	case NMEA_GPGLL:
950 		/* Check quality byte, fetch time only */
951 		rc_time	 = parse_time(&date, &tofs.tv_nsec, &rdata, 5);
952 		pp->leap = parse_qual(&rdata, 6, 'A', 0);
953 		rc_date	 = unfold_day(&date, rd_timestamp.l_ui);
954 		if (CLK_FLAG4 & pp->sloppyclockflag)
955 			field_wipe(&rdata, 1, 3, -1);
956 		break;
957 
958 	case NMEA_GPZDA:
959 		/* No quality.	Assume best, fetch time & full date */
960 		pp->leap = LEAP_NOWARNING;
961 		rc_time	 = parse_time(&date, &tofs.tv_nsec, &rdata, 1);
962 		rc_date	 = parse_date(&date, &rdata, 2, DATE_3_DDMMYYYY);
963 		break;
964 
965 	case NMEA_GPZDG:
966 		/* Check quality byte, fetch time & full date */
967 		rc_time	 = parse_time(&date, &tofs.tv_nsec, &rdata, 1);
968 		rc_date	 = parse_date(&date, &rdata, 2, DATE_3_DDMMYYYY);
969 		pp->leap = parse_qual(&rdata, 4, '0', 1);
970 		tofs.tv_sec = -1; /* GPZDG is following second */
971 		break;
972 
973 	case NMEA_PGRMF:
974 		/* get date, time, qualifier and GPS weektime. We need
975 		 * date and time-of-day for the century fix, so we read
976 		 * them first.
977 		 */
978 		rc_date  = parse_weekdata(&gpsw, &rdata, 1, 2, 5)
979 		        && parse_date(&date, &rdata, 3, DATE_1_DDMMYY);
980 		rc_time  = parse_time(&date, &tofs.tv_nsec, &rdata, 4);
981 		pp->leap = parse_qual(&rdata, 11, '0', 1);
982 		rc_date  = rc_date
983 		        && gpsfix_century(&date, &gpsw, &up->century_cache);
984 		if (CLK_FLAG4 & pp->sloppyclockflag)
985 			field_wipe(&rdata, 6, 8, -1);
986 		break;
987 
988 	default:
989 		INVARIANT(0);	/* Coverity 97123 */
990 		return;
991 	}
992 
993 	/* Check sanity of time-of-day. */
994 	if (rc_time == 0) {	/* no time or conversion error? */
995 		checkres = CEVNT_BADTIME;
996 		up->tally.malformed++;
997 	}
998 	/* Check sanity of date. */
999 	else if (rc_date == 0) {/* no date or conversion error? */
1000 		checkres = CEVNT_BADDATE;
1001 		up->tally.malformed++;
1002 	}
1003 	/* check clock sanity; [bug 2143] */
1004 	else if (pp->leap == LEAP_NOTINSYNC) { /* no good status? */
1005 		checkres = CEVNT_BADREPLY;
1006 		up->tally.rejected++;
1007 	}
1008 	else
1009 		checkres = -1;
1010 
1011 	if (checkres != -1) {
1012 		save_ltc(pp, rd_lastcode, rd_lencode);
1013 		refclock_report(peer, checkres);
1014 		return;
1015 	}
1016 
1017 	DPRINTF(1, ("%s effective timecode: %04u-%02u-%02u %02d:%02d:%02d\n",
1018 		refnumtoa(&peer->srcadr),
1019 		date.year, date.month, date.monthday,
1020 		date.hour, date.minute, date.second));
1021 
1022 	/* Check if we must enter GPS time mode; log so if we do */
1023 	if (!up->gps_time && (sentence == NMEA_GPZDG)) {
1024 		msyslog(LOG_INFO, "%s using GPS time as if it were UTC",
1025 			refnumtoa(&peer->srcadr));
1026 		up->gps_time = 1;
1027 	}
1028 
1029 	/*
1030 	 * Get the reference time stamp from the calendar buffer.
1031 	 * Process the new sample in the median filter and determine the
1032 	 * timecode timestamp, but only if the PPS is not in control.
1033 	 * Discard sentence if reference time did not change.
1034 	 */
1035 	rd_reftime = eval_gps_time(peer, &date, &tofs, &rd_timestamp);
1036 	if (L_ISEQU(&up->last_reftime, &rd_reftime)) {
1037 		/* Do not touch pp->a_lastcode on purpose! */
1038 		up->tally.filtered++;
1039 		return;
1040 	}
1041 	up->last_reftime = rd_reftime;
1042 	rd_fudge = pp->fudgetime2;
1043 
1044 	DPRINTF(1, ("%s using '%s'\n",
1045 		    refnumtoa(&peer->srcadr), rd_lastcode));
1046 
1047 	/* Data will be accepted. Update stats & log data. */
1048 	up->tally.accepted++;
1049 	save_ltc(pp, rd_lastcode, rd_lencode);
1050 	pp->lastrec = rd_timestamp;
1051 
1052 #ifdef HAVE_PPSAPI
1053 	/*
1054 	 * If we have PPS running, we try to associate the sentence
1055 	 * with the last active edge of the PPS signal.
1056 	 */
1057 	if (up->ppsapi_lit)
1058 		switch (refclock_ppsrelate(
1059 				pp, &up->atom, &rd_reftime, &rd_timestamp,
1060 				pp->fudgetime1,	&rd_fudge))
1061 		{
1062 		case PPS_RELATE_PHASE:
1063 			up->ppsapi_gate = TRUE;
1064 			peer->precision = PPS_PRECISION;
1065 			peer->flags |= FLAG_PPS;
1066 			DPRINTF(2, ("%s PPS_RELATE_PHASE\n",
1067 				    refnumtoa(&peer->srcadr)));
1068 			up->tally.pps_used++;
1069 			break;
1070 
1071 		case PPS_RELATE_EDGE:
1072 			up->ppsapi_gate = TRUE;
1073 			peer->precision = PPS_PRECISION;
1074 			DPRINTF(2, ("%s PPS_RELATE_EDGE\n",
1075 				    refnumtoa(&peer->srcadr)));
1076 			break;
1077 
1078 		case PPS_RELATE_NONE:
1079 		default:
1080 			/*
1081 			 * Resetting precision and PPS flag is done in
1082 			 * 'nmea_poll', since it might be a glitch. But
1083 			 * at the end of the poll cycle we know...
1084 			 */
1085 			DPRINTF(2, ("%s PPS_RELATE_NONE\n",
1086 				    refnumtoa(&peer->srcadr)));
1087 			break;
1088 		}
1089 #endif /* HAVE_PPSAPI */
1090 
1091 	refclock_process_offset(pp, rd_reftime, rd_timestamp, rd_fudge);
1092 }
1093 
1094 
1095 /*
1096  * -------------------------------------------------------------------
1097  * nmea_poll - called by the transmit procedure
1098  *
1099  * Does the necessary bookkeeping stuff to keep the reported state of
1100  * the clock in sync with reality.
1101  *
1102  * We go to great pains to avoid changing state here, since there may
1103  * be more than one eavesdropper receiving the same timecode.
1104  * -------------------------------------------------------------------
1105  */
1106 static void
1107 nmea_poll(
1108 	int           unit,
1109 	struct peer * peer
1110 	)
1111 {
1112 	struct refclockproc * const pp = peer->procptr;
1113 	nmea_unit	    * const up = (nmea_unit *)pp->unitptr;
1114 
1115 	/*
1116 	 * Process median filter samples. If none received, declare a
1117 	 * timeout and keep going.
1118 	 */
1119 #ifdef HAVE_PPSAPI
1120 	/*
1121 	 * If we don't have PPS pulses and time stamps, turn PPS down
1122 	 * for now.
1123 	 */
1124 	if (!up->ppsapi_gate) {
1125 		peer->flags &= ~FLAG_PPS;
1126 		peer->precision = PRECISION;
1127 	} else {
1128 		up->ppsapi_gate = FALSE;
1129 	}
1130 #endif /* HAVE_PPSAPI */
1131 
1132 	/*
1133 	 * If the median filter is empty, claim a timeout. Else process
1134 	 * the input data and keep the stats going.
1135 	 */
1136 	if (pp->coderecv == pp->codeproc) {
1137 		refclock_report(peer, CEVNT_TIMEOUT);
1138 	} else {
1139 		pp->polls++;
1140 		pp->lastref = pp->lastrec;
1141 		refclock_receive(peer);
1142 	}
1143 
1144 	/*
1145 	 * If extended logging is required, write the tally stats to the
1146 	 * clockstats file; otherwise just do a normal clock stats
1147 	 * record. Clear the tally stats anyway.
1148 	*/
1149 	if (peer->ttl & NMEA_EXTLOG_MASK) {
1150 		/* Log & reset counters with extended logging */
1151 		const char *nmea = pp->a_lastcode;
1152 		if (*nmea == '\0') nmea = "(none)";
1153 		mprintf_clock_stats(
1154 		  &peer->srcadr, "%s  %u %u %u %u %u %u",
1155 		  nmea,
1156 		  up->tally.total, up->tally.accepted,
1157 		  up->tally.rejected, up->tally.malformed,
1158 		  up->tally.filtered, up->tally.pps_used);
1159 	} else {
1160 		record_clock_stats(&peer->srcadr, pp->a_lastcode);
1161 	}
1162 	ZERO(up->tally);
1163 }
1164 
1165 /*
1166  * -------------------------------------------------------------------
1167  * Save the last timecode string, making sure it's properly truncated
1168  * if necessary and NUL terminated in any case.
1169  */
1170 static void
1171 save_ltc(
1172 	struct refclockproc * const pp,
1173 	const char * const          tc,
1174 	size_t                      len
1175 	)
1176 {
1177 	if (len >= sizeof(pp->a_lastcode))
1178 		len = sizeof(pp->a_lastcode) - 1;
1179 	pp->lencode = (u_short)len;
1180 	memcpy(pp->a_lastcode, tc, len);
1181 	pp->a_lastcode[len] = '\0';
1182 }
1183 
1184 
1185 #if NMEA_WRITE_SUPPORT
1186 /*
1187  * -------------------------------------------------------------------
1188  *  gps_send(fd, cmd, peer)	Sends a command to the GPS receiver.
1189  *   as in gps_send(fd, "rqts,u", peer);
1190  *
1191  * If 'cmd' starts with a '$' it is assumed that this command is in raw
1192  * format, that is, starts with '$', ends with '<cr><lf>' and that any
1193  * checksum is correctly provided; the command will be send 'as is' in
1194  * that case. Otherwise the function will create the necessary frame
1195  * (start char, chksum, final CRLF) on the fly.
1196  *
1197  * We don't currently send any data, but would like to send RTCM SC104
1198  * messages for differential positioning. It should also give us better
1199  * time. Without a PPS output, we're Just fooling ourselves because of
1200  * the serial code paths
1201  * -------------------------------------------------------------------
1202  */
1203 static void
1204 gps_send(
1205 	int           fd,
1206 	const char  * cmd,
1207 	struct peer * peer
1208 	)
1209 {
1210 	/* $...*xy<CR><LF><NUL> add 7 */
1211 	char	      buf[NMEA_PROTO_MAXLEN + 7];
1212 	int	      len;
1213 	u_char	      dcs;
1214 	const u_char *beg, *end;
1215 
1216 	if (*cmd != '$') {
1217 		/* get checksum and length */
1218 		beg = end = (const u_char*)cmd;
1219 		dcs = 0;
1220 		while (*end >= ' ' && *end != '*')
1221 			dcs ^= *end++;
1222 		len = end - beg;
1223 		/* format into output buffer with overflow check */
1224 		len = snprintf(buf, sizeof(buf), "$%.*s*%02X\r\n",
1225 			       len, beg, dcs);
1226 		if ((size_t)len >= sizeof(buf)) {
1227 			DPRINTF(1, ("%s gps_send: buffer overflow for command '%s'\n",
1228 				    refnumtoa(&peer->srcadr), cmd));
1229 			return;	/* game over player 1 */
1230 		}
1231 		cmd = buf;
1232 	} else {
1233 		len = strlen(cmd);
1234 	}
1235 
1236 	DPRINTF(1, ("%s gps_send: '%.*s'\n", refnumtoa(&peer->srcadr),
1237 		len - 2, cmd));
1238 
1239 	/* send out the whole stuff */
1240 	if (write(fd, cmd, len) == -1)
1241 		refclock_report(peer, CEVNT_FAULT);
1242 }
1243 #endif /* NMEA_WRITE_SUPPORT */
1244 
1245 /*
1246  * -------------------------------------------------------------------
1247  * helpers for faster field splitting
1248  * -------------------------------------------------------------------
1249  *
1250  * set up a field record, check syntax and verify checksum
1251  *
1252  * format is $XXXXX,1,2,3,4*ML
1253  *
1254  * 8-bit XOR of characters between $ and * noninclusive is transmitted
1255  * in last two chars M and L holding most and least significant nibbles
1256  * in hex representation such as:
1257  *
1258  *   $GPGLL,5057.970,N,00146.110,E,142451,A*27
1259  *   $GPVTG,089.0,T,,,15.2,N,,*7F
1260  *
1261  * Some other constraints:
1262  * + The field name must at least 5 upcase characters or digits and must
1263  *   start with a character.
1264  * + The checksum (if present) must be uppercase hex digits.
1265  * + The length of a sentence is limited to 80 characters (not including
1266  *   the final CR/LF nor the checksum, but including the leading '$')
1267  *
1268  * Return values:
1269  *  + CHECK_INVALID
1270  *	The data does not form a valid NMEA sentence or a checksum error
1271  *	occurred.
1272  *  + CHECK_VALID
1273  *	The data is a valid NMEA sentence but contains no checksum.
1274  *  + CHECK_CSVALID
1275  *	The data is a valid NMEA sentence and passed the checksum test.
1276  * -------------------------------------------------------------------
1277  */
1278 static int
1279 field_init(
1280 	nmea_data * data,	/* context structure		       */
1281 	char 	  * cptr,	/* start of raw data		       */
1282 	int	    dlen	/* data len, not counting trailing NUL */
1283 	)
1284 {
1285 	u_char cs_l;	/* checksum local computed	*/
1286 	u_char cs_r;	/* checksum remote given	*/
1287 	char * eptr;	/* buffer end end pointer	*/
1288 	char   tmp;	/* char buffer 			*/
1289 
1290 	cs_l = 0;
1291 	cs_r = 0;
1292 	/* some basic input constraints */
1293 	if (dlen < 0)
1294 		dlen = 0;
1295 	eptr = cptr + dlen;
1296 	*eptr = '\0';
1297 
1298 	/* load data context */
1299 	data->base = cptr;
1300 	data->cptr = cptr;
1301 	data->cidx = 0;
1302 	data->blen = dlen;
1303 
1304 	/* syntax check follows here. check allowed character
1305 	 * sequences, updating the local computed checksum as we go.
1306 	 *
1307 	 * regex equiv: '^\$[A-Z][A-Z0-9]{4,}[^*]*(\*[0-9A-F]{2})?$'
1308 	 */
1309 
1310 	/* -*- start character: '^\$' */
1311 	if (*cptr == '\0')
1312 		return CHECK_EMPTY;
1313 	if (*cptr++ != '$')
1314 		return CHECK_INVALID;
1315 
1316 	/* -*- advance context beyond start character */
1317 	data->base++;
1318 	data->cptr++;
1319 	data->blen--;
1320 
1321 	/* -*- field name: '[A-Z][A-Z0-9]{4,},' */
1322 	if (*cptr < 'A' || *cptr > 'Z')
1323 		return CHECK_INVALID;
1324 	cs_l ^= *cptr++;
1325 	while ((*cptr >= 'A' && *cptr <= 'Z') ||
1326 	       (*cptr >= '0' && *cptr <= '9')  )
1327 		cs_l ^= *cptr++;
1328 	if (*cptr != ',' || (cptr - data->base) < NMEA_PROTO_IDLEN)
1329 		return CHECK_INVALID;
1330 	cs_l ^= *cptr++;
1331 
1332 	/* -*- data: '[^*]*' */
1333 	while (*cptr && *cptr != '*')
1334 		cs_l ^= *cptr++;
1335 
1336 	/* -*- checksum field: (\*[0-9A-F]{2})?$ */
1337 	if (*cptr == '\0')
1338 		return CHECK_VALID;
1339 	if (*cptr != '*' || cptr != eptr - 3 ||
1340 	    (cptr - data->base) >= NMEA_PROTO_MAXLEN)
1341 		return CHECK_INVALID;
1342 
1343 	for (cptr++; (tmp = *cptr) != '\0'; cptr++) {
1344 		if (tmp >= '0' && tmp <= '9')
1345 			cs_r = (cs_r << 4) + (tmp - '0');
1346 		else if (tmp >= 'A' && tmp <= 'F')
1347 			cs_r = (cs_r << 4) + (tmp - 'A' + 10);
1348 		else
1349 			break;
1350 	}
1351 
1352 	/* -*- make sure we are at end of string and csum matches */
1353 	if (cptr != eptr || cs_l != cs_r)
1354 		return CHECK_INVALID;
1355 
1356 	return CHECK_CSVALID;
1357 }
1358 
1359 /*
1360  * -------------------------------------------------------------------
1361  * fetch a data field by index, zero being the name field. If this
1362  * function is called repeatedly with increasing indices, the total load
1363  * is O(n), n being the length of the string; if it is called with
1364  * decreasing indices, the total load is O(n^2). Try not to go backwards
1365  * too often.
1366  * -------------------------------------------------------------------
1367  */
1368 static char *
1369 field_parse(
1370 	nmea_data * data,
1371 	int 	    fn
1372 	)
1373 {
1374 	char tmp;
1375 
1376 	if (fn < data->cidx) {
1377 		data->cidx = 0;
1378 		data->cptr = data->base;
1379 	}
1380 	while ((fn > data->cidx) && (tmp = *data->cptr) != '\0') {
1381 		data->cidx += (tmp == ',');
1382 		data->cptr++;
1383 	}
1384 	return data->cptr;
1385 }
1386 
1387 /*
1388  * -------------------------------------------------------------------
1389  * Wipe (that is, overwrite with '_') data fields and the checksum in
1390  * the last timecode.  The list of field indices is given as integers
1391  * in a varargs list, preferrably in ascending order, in any case
1392  * terminated by a negative field index.
1393  *
1394  * A maximum number of 8 fields can be overwritten at once to guard
1395  * against runaway (that is, unterminated) argument lists.
1396  *
1397  * This function affects what a remote user can see with
1398  *
1399  * ntpq -c clockvar <server>
1400  *
1401  * Note that this also removes the wiped fields from any clockstats
1402  * log.	 Some NTP operators monitor their NMEA GPS using the change in
1403  * location in clockstats over time as as a proxy for the quality of
1404  * GPS reception and thereby time reported.
1405  * -------------------------------------------------------------------
1406  */
1407 static void
1408 field_wipe(
1409 	nmea_data * data,
1410 	...
1411 	)
1412 {
1413 	va_list	va;		/* vararg index list */
1414 	int	fcnt;		/* safeguard against runaway arglist */
1415 	int	fidx;		/* field to nuke, or -1 for checksum */
1416 	char  * cp;		/* overwrite destination */
1417 
1418 	fcnt = 8;
1419 	cp = NULL;
1420 	va_start(va, data);
1421 	do {
1422 		fidx = va_arg(va, int);
1423 		if (fidx >= 0 && fidx <= NMEA_PROTO_FIELDS) {
1424 			cp = field_parse(data, fidx);
1425 		} else {
1426 			cp = data->base + data->blen;
1427 			if (data->blen >= 3 && cp[-3] == '*')
1428 				cp -= 2;
1429 		}
1430 		for ( ; '\0' != *cp && '*' != *cp && ',' != *cp; cp++)
1431 			if ('.' != *cp)
1432 				*cp = '_';
1433 	} while (fcnt-- && fidx >= 0);
1434 	va_end(va);
1435 }
1436 
1437 /*
1438  * -------------------------------------------------------------------
1439  * PARSING HELPERS
1440  * -------------------------------------------------------------------
1441  *
1442  * Check sync status
1443  *
1444  * If the character at the data field start matches the tag value,
1445  * return LEAP_NOWARNING and LEAP_NOTINSYNC otherwise. If the 'inverted'
1446  * flag is given, just the opposite value is returned. If there is no
1447  * data field (*cp points to the NUL byte) the result is LEAP_NOTINSYNC.
1448  * -------------------------------------------------------------------
1449  */
1450 static u_char
1451 parse_qual(
1452 	nmea_data * rd,
1453 	int         idx,
1454 	char        tag,
1455 	int         inv
1456 	)
1457 {
1458 	static const u_char table[2] =
1459 				{ LEAP_NOTINSYNC, LEAP_NOWARNING };
1460 	char * dp;
1461 
1462 	dp = field_parse(rd, idx);
1463 
1464 	return table[ *dp && ((*dp == tag) == !inv) ];
1465 }
1466 
1467 /*
1468  * -------------------------------------------------------------------
1469  * Parse a time stamp in HHMMSS[.sss] format with error checking.
1470  *
1471  * returns 1 on success, 0 on failure
1472  * -------------------------------------------------------------------
1473  */
1474 static int
1475 parse_time(
1476 	struct calendar * jd,	/* result calendar pointer */
1477 	long		* ns,	/* storage for nsec fraction */
1478 	nmea_data       * rd,
1479 	int		  idx
1480 	)
1481 {
1482 	static const unsigned long weight[4] = {
1483 		0, 100000000, 10000000, 1000000
1484 	};
1485 
1486 	int	rc;
1487 	u_int	h;
1488 	u_int	m;
1489 	u_int	s;
1490 	int	p1;
1491 	int	p2;
1492 	u_long	f;
1493 	char  * dp;
1494 
1495 	dp = field_parse(rd, idx);
1496 	rc = sscanf(dp, "%2u%2u%2u%n.%3lu%n", &h, &m, &s, &p1, &f, &p2);
1497 	if (rc < 3 || p1 != 6) {
1498 		DPRINTF(1, ("nmea: invalid time code: '%.6s'\n", dp));
1499 		return FALSE;
1500 	}
1501 
1502 	/* value sanity check */
1503 	if (h > 23 || m > 59 || s > 60) {
1504 		DPRINTF(1, ("nmea: invalid time spec %02u:%02u:%02u\n",
1505 			    h, m, s));
1506 		return FALSE;
1507 	}
1508 
1509 	jd->hour   = (u_char)h;
1510 	jd->minute = (u_char)m;
1511 	jd->second = (u_char)s;
1512 	/* if we have a fraction, scale it up to nanoseconds. */
1513 	if (rc == 4)
1514 		*ns = f * weight[p2 - p1 - 1];
1515 	else
1516 		*ns = 0;
1517 
1518 	return TRUE;
1519 }
1520 
1521 /*
1522  * -------------------------------------------------------------------
1523  * Parse a date string from an NMEA sentence. This could either be a
1524  * partial date in DDMMYY format in one field, or DD,MM,YYYY full date
1525  * spec spanning three fields. This function does some extensive error
1526  * checking to make sure the date string was consistent.
1527  *
1528  * returns 1 on success, 0 on failure
1529  * -------------------------------------------------------------------
1530  */
1531 static int
1532 parse_date(
1533 	struct calendar * jd,	/* result pointer */
1534 	nmea_data       * rd,
1535 	int		  idx,
1536 	enum date_fmt	  fmt
1537 	)
1538 {
1539 	int	rc;
1540 	u_int	y;
1541 	u_int	m;
1542 	u_int	d;
1543 	int	p;
1544 	char  * dp;
1545 
1546 	dp = field_parse(rd, idx);
1547 	switch (fmt) {
1548 
1549 	case DATE_1_DDMMYY:
1550 		rc = sscanf(dp, "%2u%2u%2u%n", &d, &m, &y, &p);
1551 		if (rc != 3 || p != 6) {
1552 			DPRINTF(1, ("nmea: invalid date code: '%.6s'\n",
1553 				    dp));
1554 			return FALSE;
1555 		}
1556 		break;
1557 
1558 	case DATE_3_DDMMYYYY:
1559 		rc = sscanf(dp, "%2u,%2u,%4u%n", &d, &m, &y, &p);
1560 		if (rc != 3 || p != 10) {
1561 			DPRINTF(1, ("nmea: invalid date code: '%.10s'\n",
1562 				    dp));
1563 			return FALSE;
1564 		}
1565 		break;
1566 
1567 	default:
1568 		DPRINTF(1, ("nmea: invalid parse format: %d\n", fmt));
1569 		return FALSE;
1570 	}
1571 
1572 	/* value sanity check */
1573 	if (d < 1 || d > 31 || m < 1 || m > 12) {
1574 		DPRINTF(1, ("nmea: invalid date spec (YMD) %04u:%02u:%02u\n",
1575 			    y, m, d));
1576 		return FALSE;
1577 	}
1578 
1579 	/* store results */
1580 	jd->monthday = (u_char)d;
1581 	jd->month    = (u_char)m;
1582 	jd->year     = (u_short)y;
1583 
1584 	return TRUE;
1585 }
1586 
1587 /*
1588  * -------------------------------------------------------------------
1589  * Parse GPS week time info from an NMEA sentence. This info contains
1590  * the GPS week number, the GPS time-of-week and the leap seconds GPS
1591  * to UTC.
1592  *
1593  * returns 1 on success, 0 on failure
1594  * -------------------------------------------------------------------
1595  */
1596 static int
1597 parse_weekdata(
1598 	gps_weektm * wd,
1599 	nmea_data  * rd,
1600 	int          weekidx,
1601 	int          timeidx,
1602 	int          leapidx
1603 	)
1604 {
1605 	u_long secs;
1606 	int    fcnt;
1607 
1608 	/* parse fields and count success */
1609 	fcnt  = sscanf(field_parse(rd, weekidx), "%hu", &wd->wt_week);
1610 	fcnt += sscanf(field_parse(rd, timeidx), "%lu", &secs);
1611 	fcnt += sscanf(field_parse(rd, leapidx), "%hd", &wd->wt_leap);
1612 	if (fcnt != 3 || wd->wt_week >= 1024 || secs >= 7*SECSPERDAY) {
1613 		DPRINTF(1, ("nmea: parse_weekdata: invalid weektime spec\n"));
1614 		return FALSE;
1615 	}
1616 	wd->wt_time = (u_int32)secs;
1617 
1618 	return TRUE;
1619 }
1620 
1621 /*
1622  * -------------------------------------------------------------------
1623  * funny calendar-oriented stuff -- perhaps a bit hard to grok.
1624  * -------------------------------------------------------------------
1625  *
1626  * Unfold a time-of-day (seconds since midnight) around the current
1627  * system time in a manner that guarantees an absolute difference of
1628  * less than 12hrs.
1629  *
1630  * This function is used for NMEA sentences that contain no date
1631  * information. This requires the system clock to be in +/-12hrs
1632  * around the true time, or the clock will synchronize the system 1day
1633  * off if not augmented with a time sources that also provide the
1634  * necessary date information.
1635  *
1636  * The function updates the calendar structure it also uses as
1637  * input to fetch the time from.
1638  *
1639  * returns 1 on success, 0 on failure
1640  * -------------------------------------------------------------------
1641  */
1642 static int
1643 unfold_day(
1644 	struct calendar * jd,
1645 	u_int32		  rec_ui
1646 	)
1647 {
1648 	vint64	     rec_qw;
1649 	ntpcal_split rec_ds;
1650 
1651 	/*
1652 	 * basically this is the peridiodic extension of the receive
1653 	 * time - 12hrs to the time-of-day with a period of 1 day.
1654 	 * But we would have to execute this in 64bit arithmetic, and we
1655 	 * cannot assume we can do this; therefore this is done
1656 	 * in split representation.
1657 	 */
1658 	rec_qw = ntpcal_ntp_to_ntp(rec_ui - SECSPERDAY/2, NULL);
1659 	rec_ds = ntpcal_daysplit(&rec_qw);
1660 	rec_ds.lo = ntpcal_periodic_extend(rec_ds.lo,
1661 					   ntpcal_date_to_daysec(jd),
1662 					   SECSPERDAY);
1663 	rec_ds.hi += ntpcal_daysec_to_date(jd, rec_ds.lo);
1664 	return (ntpcal_rd_to_date(jd, rec_ds.hi + DAY_NTP_STARTS) >= 0);
1665 }
1666 
1667 /*
1668  * -------------------------------------------------------------------
1669  * A 2-digit year is expanded into full year spec around the year found
1670  * in 'jd->year'. This should be in +79/-19 years around the system time,
1671  * or the result will be off by 100 years.  The assymetric behaviour was
1672  * chosen to enable inital sync for systems that do not have a
1673  * battery-backup clock and start with a date that is typically years in
1674  * the past.
1675  *
1676  * Since the GPS epoch starts at 1980-01-06, the resulting year will be
1677  * not be before 1980 in any case.
1678  *
1679  * returns 1 on success, 0 on failure
1680  * -------------------------------------------------------------------
1681  */
1682 static int
1683 unfold_century(
1684 	struct calendar * jd,
1685 	u_int32		  rec_ui
1686 	)
1687 {
1688 	struct calendar rec;
1689 	int32		baseyear;
1690 
1691 	ntpcal_ntp_to_date(&rec, rec_ui, NULL);
1692 	baseyear = rec.year - 20;
1693 	if (baseyear < g_gpsMinYear)
1694 		baseyear = g_gpsMinYear;
1695 	jd->year = (u_short)ntpcal_periodic_extend(baseyear, jd->year,
1696 						   100);
1697 
1698 	return ((baseyear <= jd->year) && (baseyear + 100 > jd->year));
1699 }
1700 
1701 /*
1702  * -------------------------------------------------------------------
1703  * A 2-digit year is expanded into a full year spec by correlation with
1704  * a GPS week number and the current leap second count.
1705  *
1706  * The GPS week time scale counts weeks since Sunday, 1980-01-06, modulo
1707  * 1024 and seconds since start of the week. The GPS time scale is based
1708  * on international atomic time (TAI), so the leap second difference to
1709  * UTC is also needed for a proper conversion.
1710  *
1711  * A brute-force analysis (that is, test for every date) shows that a
1712  * wrong assignment of the century can not happen between the years 1900
1713  * to 2399 when comparing the week signatures for different
1714  * centuries. (I *think* that will not happen for 400*1024 years, but I
1715  * have no valid proof. -*-perlinger@ntp.org-*-)
1716  *
1717  * This function is bound to to work between years 1980 and 2399
1718  * (inclusive), which should suffice for now ;-)
1719  *
1720  * Note: This function needs a full date&time spec on input due to the
1721  * necessary leap second corrections!
1722  *
1723  * returns 1 on success, 0 on failure
1724  * -------------------------------------------------------------------
1725  */
1726 static int
1727 gpsfix_century(
1728 	struct calendar  * jd,
1729 	const gps_weektm * wd,
1730 	u_short          * century
1731 	)
1732 {
1733 	int32	days;
1734 	int32	doff;
1735 	u_short week;
1736 	u_short year;
1737 	int     loop;
1738 
1739 	/* Get day offset. Assumes that the input time is in range and
1740 	 * that the leap seconds do not shift more than +/-1 day.
1741 	 */
1742 	doff = ntpcal_date_to_daysec(jd) + wd->wt_leap;
1743 	doff = (doff >= SECSPERDAY) - (doff < 0);
1744 
1745 	/*
1746 	 * Loop over centuries to get a match, starting with the last
1747 	 * successful one. (Or with the 19th century if the cached value
1748 	 * is out of range...)
1749 	 */
1750 	year = jd->year % 100;
1751 	for (loop = 5; loop > 0; loop--,(*century)++) {
1752 		if (*century < 19 || *century >= 24)
1753 			*century = 19;
1754 		/* Get days and week in GPS epoch */
1755 		jd->year = year + *century * 100;
1756 		days = ntpcal_date_to_rd(jd) - DAY_GPS_STARTS + doff;
1757 		week = (days / 7) % 1024;
1758 		if (days >= 0 && wd->wt_week == week)
1759 			return TRUE; /* matched... */
1760 	}
1761 
1762 	jd->year = year;
1763 	return FALSE; /* match failed... */
1764 }
1765 
1766 /*
1767  * -------------------------------------------------------------------
1768  * And now the final execise: Considering the fact that many (most?)
1769  * GPS receivers cannot handle a GPS epoch wrap well, we try to
1770  * compensate for that problem by unwrapping a GPS epoch around the
1771  * receive stamp. Another execise in periodic unfolding, of course,
1772  * but with enough points to take care of.
1773  *
1774  * Note: The integral part of 'tofs' is intended to handle small(!)
1775  * systematic offsets, as -1 for handling $GPZDG, which gives the
1776  * following second. (sigh...) The absolute value shall be less than a
1777  * day (86400 seconds).
1778  * -------------------------------------------------------------------
1779  */
1780 static l_fp
1781 eval_gps_time(
1782 	struct peer           * peer, /* for logging etc */
1783 	const struct calendar * gpst, /* GPS time stamp  */
1784 	const struct timespec * tofs, /* GPS frac second & offset */
1785 	const l_fp            * xrecv /* receive time stamp */
1786 	)
1787 {
1788 	struct refclockproc * const pp = peer->procptr;
1789 	nmea_unit	    * const up = (nmea_unit *)pp->unitptr;
1790 
1791 	l_fp    retv;
1792 
1793 	/* components of calculation */
1794 	int32_t rcv_sec, rcv_day; /* receive ToD and day */
1795 	int32_t gps_sec, gps_day; /* GPS ToD and day in NTP epoch */
1796 	int32_t adj_day, weeks;   /* adjusted GPS day and week shift */
1797 
1798 	/* some temporaries to shuffle data */
1799 	vint64       vi64;
1800 	ntpcal_split rs64;
1801 
1802 	/* evaluate time stamp from receiver. */
1803 	gps_sec = ntpcal_date_to_daysec(gpst);
1804 	gps_day = ntpcal_date_to_rd(gpst) - DAY_NTP_STARTS;
1805 
1806 	/* merge in fractional offset */
1807 	retv = tspec_intv_to_lfp(*tofs);
1808 	gps_sec += retv.l_i;
1809 
1810 	/* If we fully trust the GPS receiver, just combine days and
1811 	 * seconds and be done. */
1812 	if (peer->ttl & NMEA_DATETRUST_MASK) {
1813 		retv.l_ui = ntpcal_dayjoin(gps_day, gps_sec).D_s.lo;
1814 		return retv;
1815 	}
1816 
1817 	/* So we do not trust the GPS receiver to deliver a correct date
1818 	 * due to the GPS epoch changes. We map the date from the
1819 	 * receiver into the +/-512 week interval around the receive
1820 	 * time in that case. This would be a tad easier with 64bit
1821 	 * calculations, but again, we restrict the code to 32bit ops
1822 	 * when possible. */
1823 
1824 	/* - make sure the GPS fractional day is normalised
1825 	 * Applying the offset value might have put us slightly over the
1826 	 * edge of the allowed range for seconds-of-day. Doing a full
1827 	 * division with floor correction is overkill here; a simple
1828 	 * addition or subtraction step is sufficient. Using WHILE loops
1829 	 * gives the right result even if the offset exceeds one day,
1830 	 * which is NOT what it's intented for! */
1831 	while (gps_sec >= SECSPERDAY) {
1832 		gps_sec -= SECSPERDAY;
1833 		gps_day += 1;
1834 	}
1835 	while (gps_sec < 0) {
1836 		gps_sec += SECSPERDAY;
1837 		gps_day -= 1;
1838 	}
1839 
1840 	/* - get unfold base: day of full recv time - 512 weeks */
1841 	vi64 = ntpcal_ntp_to_ntp(xrecv->l_ui, NULL);
1842 	rs64 = ntpcal_daysplit(&vi64);
1843 	rcv_sec = rs64.lo;
1844 	rcv_day = rs64.hi - 512 * 7;
1845 
1846 	/* - take the fractional days into account
1847 	 * If the fractional day of the GPS time is smaller than the
1848 	 * fractional day of the receive time, we shift the base day for
1849 	 * the unfold by 1. */
1850 	if (   gps_sec  < rcv_sec
1851 	   || (gps_sec == rcv_sec && retv.l_uf < xrecv->l_uf))
1852 		rcv_day += 1;
1853 
1854 	/* - don't warp ahead of GPS invention! */
1855 	if (rcv_day < g_gpsMinBase)
1856 		rcv_day = g_gpsMinBase;
1857 
1858 	/* - let the magic happen: */
1859 	adj_day = ntpcal_periodic_extend(rcv_day, gps_day, 1024*7);
1860 
1861 	/* - check if we should log a GPS epoch warp */
1862 	weeks = (adj_day - gps_day) / 7;
1863 	if (weeks != up->epoch_warp) {
1864 		up->epoch_warp = weeks;
1865 		LOGIF(CLOCKINFO, (LOG_INFO,
1866 				  "%s Changed GPS epoch warp to %d weeks",
1867 				  refnumtoa(&peer->srcadr), weeks));
1868 	}
1869 
1870 	/* - build result and be done */
1871 	retv.l_ui = ntpcal_dayjoin(adj_day, gps_sec).D_s.lo;
1872 	return retv;
1873 }
1874 
1875 /*
1876  * ===================================================================
1877  *
1878  * NMEAD support
1879  *
1880  * original nmead support added by Jon Miner (cp_n18@yahoo.com)
1881  *
1882  * See http://home.hiwaay.net/~taylorc/gps/nmea-server/
1883  * for information about nmead
1884  *
1885  * To use this, you need to create a link from /dev/gpsX to
1886  * the server:port where nmead is running.  Something like this:
1887  *
1888  * ln -s server:port /dev/gps1
1889  *
1890  * Split into separate function by Juergen Perlinger
1891  * (perlinger-at-ntp-dot-org)
1892  *
1893  * ===================================================================
1894  */
1895 static int
1896 nmead_open(
1897 	const char * device
1898 	)
1899 {
1900 	int	fd = -1;		/* result file descriptor */
1901 
1902 #ifdef HAVE_READLINK
1903 	char	host[80];		/* link target buffer	*/
1904 	char  * port;			/* port name or number	*/
1905 	int	rc;			/* result code (several)*/
1906 	int     sh;			/* socket handle	*/
1907 	struct addrinfo	 ai_hint;	/* resolution hint	*/
1908 	struct addrinfo	*ai_list;	/* resolution result	*/
1909 	struct addrinfo *ai;		/* result scan ptr	*/
1910 
1911 	fd = -1;
1912 
1913 	/* try to read as link, make sure no overflow occurs */
1914 	rc = readlink(device, host, sizeof(host));
1915 	if ((size_t)rc >= sizeof(host))
1916 		return fd;	/* error / overflow / truncation */
1917 	host[rc] = '\0';	/* readlink does not place NUL	*/
1918 
1919 	/* get port */
1920 	port = strchr(host, ':');
1921 	if (!port)
1922 		return fd; /* not 'host:port' syntax ? */
1923 	*port++ = '\0';	/* put in separator */
1924 
1925 	/* get address infos and try to open socket
1926 	 *
1927 	 * This getaddrinfo() is naughty in ntpd's nonblocking main
1928 	 * thread, but you have to go out of your wary to use this code
1929 	 * and typically the blocking is at startup where its impact is
1930 	 * reduced. The same holds for the 'connect()', as it is
1931 	 * blocking, too...
1932 	 */
1933 	ZERO(ai_hint);
1934 	ai_hint.ai_protocol = IPPROTO_TCP;
1935 	ai_hint.ai_socktype = SOCK_STREAM;
1936 	if (getaddrinfo(host, port, &ai_hint, &ai_list))
1937 		return fd;
1938 
1939 	for (ai = ai_list; ai && (fd == -1); ai = ai->ai_next) {
1940 		sh = socket(ai->ai_family, ai->ai_socktype,
1941 			    ai->ai_protocol);
1942 		if (INVALID_SOCKET == sh)
1943 			continue;
1944 		rc = connect(sh, ai->ai_addr, ai->ai_addrlen);
1945 		if (-1 != rc)
1946 			fd = sh;
1947 		else
1948 			close(sh);
1949 	}
1950 	freeaddrinfo(ai_list);
1951 #else
1952 	fd = -1;
1953 #endif
1954 
1955 	return fd;
1956 }
1957 #else
1958 NONEMPTY_TRANSLATION_UNIT
1959 #endif /* REFCLOCK && CLOCK_NMEA */
1960