refclock_jupiter.c revision 225736
1/*
2 * Copyright (c) 1997, 1998, 2003
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Lawrence Berkeley Laboratory.
17 * 4. The name of the University may not be used to endorse or promote
18 *    products derived from this software without specific prior
19 *    written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#ifdef HAVE_CONFIG_H
35# include <config.h>
36#endif
37
38#if defined(REFCLOCK) && defined(CLOCK_JUPITER) && defined(HAVE_PPSAPI)
39
40#include "ntpd.h"
41#include "ntp_io.h"
42#include "ntp_refclock.h"
43#include "ntp_unixtime.h"
44#include "ntp_stdlib.h"
45
46#include <stdio.h>
47#include <ctype.h>
48
49#include "jupiter.h"
50
51#ifdef HAVE_PPSAPI
52# include "ppsapi_timepps.h"
53#endif
54
55#ifdef XNTP_BIG_ENDIAN
56#define getshort(s) ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff))
57#define putshort(s) ((((s) & 0xff) << 8) | (((s) >> 8) & 0xff))
58#else
59#define getshort(s) (s)
60#define putshort(s) (s)
61#endif
62
63/* XXX */
64#ifdef sun
65char *strerror(int);
66#endif
67
68/*
69 * This driver supports the Rockwell Jupiter GPS Receiver board
70 * adapted to precision timing applications.  It requires the
71 * ppsclock line discipline or streams module described in the
72 * Line Disciplines and Streams Drivers page. It also requires a
73 * gadget box and 1-PPS level converter, such as described in the
74 * Pulse-per-second (PPS) Signal Interfacing page.
75 *
76 * It may work (with minor modifications) with other Rockwell GPS
77 * receivers such as the CityTracker.
78 */
79
80/*
81 * GPS Definitions
82 */
83#define	DEVICE		"/dev/gps%d"	/* device name and unit */
84#define	SPEED232	B9600		/* baud */
85
86/*
87 * Radio interface parameters
88 */
89#define	PRECISION	(-18)	/* precision assumed (about 4 us) */
90#define	REFID	"GPS\0"		/* reference id */
91#define	DESCRIPTION	"Rockwell Jupiter GPS Receiver" /* who we are */
92#define	DEFFUDGETIME	0	/* default fudge time (ms) */
93
94/* Unix timestamp for the GPS epoch: January 6, 1980 */
95#define GPS_EPOCH 315964800
96
97/* Double short to unsigned int */
98#define DS2UI(p) ((getshort((p)[1]) << 16) | getshort((p)[0]))
99
100/* Double short to signed int */
101#define DS2I(p) ((getshort((p)[1]) << 16) | getshort((p)[0]))
102
103/* One week's worth of seconds */
104#define WEEKSECS (7 * 24 * 60 * 60)
105
106/*
107 * Jupiter unit control structure.
108 */
109struct instance {
110	struct peer *peer;		/* peer */
111	u_int  pollcnt;			/* poll message counter */
112	u_int  polled;			/* Hand in a time sample? */
113#ifdef HAVE_PPSAPI
114	pps_params_t pps_params;	/* pps parameters */
115	pps_info_t pps_info;		/* last pps data */
116	pps_handle_t pps_handle;	/* pps handle */
117	u_int assert;			/* pps edge to use */
118	u_int hardpps;			/* enable kernel mode */
119	struct timespec ts;		/* last timestamp */
120#endif
121	l_fp limit;
122	u_int gpos_gweek;		/* Current GPOS GPS week number */
123	u_int gpos_sweek;		/* Current GPOS GPS seconds into week */
124	u_int gweek;			/* current GPS week number */
125	u_int32 lastsweek;		/* last seconds into GPS week */
126	time_t timecode;		/* current ntp timecode */
127	u_int32 stime;			/* used to detect firmware bug */
128	int wantid;			/* don't reconfig on channel id msg */
129	u_int  moving;			/* mobile platform? */
130	u_char sloppyclockflag;		/* fudge flags */
131	u_short sbuf[512];		/* local input buffer */
132	int ssize;			/* space used in sbuf */
133};
134
135/*
136 * Function prototypes
137 */
138static	void	jupiter_canmsg	P((struct instance *, u_int));
139static	u_short	jupiter_cksum	P((u_short *, u_int));
140static	int	jupiter_config	P((struct instance *));
141static	void	jupiter_debug	P((struct peer *, char *, char *, ...))
142    __attribute__ ((format (printf, 3, 4)));
143static	char *	jupiter_parse_t	P((struct instance *, u_short *));
144static	char *	jupiter_parse_gpos	P((struct instance *, u_short *));
145static	void	jupiter_platform	P((struct instance *, u_int));
146static	void	jupiter_poll	P((int, struct peer *));
147static	void	jupiter_control	P((int, struct refclockstat *, struct
148				    refclockstat *, struct peer *));
149#ifdef HAVE_PPSAPI
150static	int	jupiter_ppsapi	P((struct instance *));
151static	int	jupiter_pps	P((struct instance *));
152#endif /* HAVE_PPSAPI */
153static	int	jupiter_recv	P((struct instance *));
154static	void	jupiter_receive P((struct recvbuf *rbufp));
155static	void	jupiter_reqmsg	P((struct instance *, u_int, u_int));
156static	void	jupiter_reqonemsg	P((struct instance *, u_int));
157static	char *	jupiter_send	P((struct instance *, struct jheader *));
158static	void	jupiter_shutdown	P((int, struct peer *));
159static	int	jupiter_start	P((int, struct peer *));
160
161/*
162 * Transfer vector
163 */
164struct	refclock refclock_jupiter = {
165	jupiter_start,		/* start up driver */
166	jupiter_shutdown,	/* shut down driver */
167	jupiter_poll,		/* transmit poll message */
168	jupiter_control,	/* (clock control) */
169	noentry,		/* (clock init) */
170	noentry,		/* (clock buginfo) */
171	NOFLAGS			/* not used */
172};
173
174/*
175 * jupiter_start - open the devices and initialize data for processing
176 */
177static int
178jupiter_start(
179	int unit,
180	struct peer *peer
181	)
182{
183	struct refclockproc *pp;
184	struct instance *instance;
185	int fd = -1;
186	char gpsdev[20];
187
188	/*
189	 * Open serial port
190	 */
191	(void)sprintf(gpsdev, DEVICE, unit);
192	fd = refclock_open(gpsdev, SPEED232, LDISC_RAW);
193	if (fd == 0) {
194		jupiter_debug(peer, "jupiter_start", "open %s: %s",
195		    gpsdev, strerror(errno));
196		return (0);
197	}
198
199	/* Allocate unit structure */
200	if ((instance = (struct instance *)
201	    emalloc(sizeof(struct instance))) == NULL) {
202		(void) close(fd);
203		return (0);
204	}
205	memset((char *)instance, 0, sizeof(struct instance));
206	instance->peer = peer;
207	pp = peer->procptr;
208	pp->io.clock_recv = jupiter_receive;
209	pp->io.srcclock = (caddr_t)peer;
210	pp->io.datalen = 0;
211	pp->io.fd = fd;
212	if (!io_addclock(&pp->io)) {
213		(void) close(fd);
214		free(instance);
215		return (0);
216	}
217	pp->unitptr = (caddr_t)instance;
218
219	/*
220	 * Initialize miscellaneous variables
221	 */
222	peer->precision = PRECISION;
223	pp->clockdesc = DESCRIPTION;
224	memcpy((char *)&pp->refid, REFID, 4);
225
226#ifdef HAVE_PPSAPI
227	instance->assert = 1;
228	instance->hardpps = 0;
229	/*
230	 * Start the PPSAPI interface if it is there. Default to use
231	 * the assert edge and do not enable the kernel hardpps.
232	 */
233	if (time_pps_create(fd, &instance->pps_handle) < 0) {
234		instance->pps_handle = 0;
235		msyslog(LOG_ERR,
236			"refclock_jupiter: time_pps_create failed: %m");
237	}
238	else if (!jupiter_ppsapi(instance))
239		goto clean_up;
240#endif /* HAVE_PPSAPI */
241
242	/* Ensure the receiver is properly configured */
243	if (!jupiter_config(instance))
244		goto clean_up;
245
246	return (1);
247
248clean_up:
249	jupiter_shutdown(unit, peer);
250	pp->unitptr = 0;
251	return (0);
252}
253
254/*
255 * jupiter_shutdown - shut down the clock
256 */
257static void
258jupiter_shutdown(int unit, struct peer *peer)
259{
260	struct instance *instance;
261	struct refclockproc *pp;
262
263	pp = peer->procptr;
264	instance = (struct instance *)pp->unitptr;
265	if (!instance)
266		return;
267
268#ifdef HAVE_PPSAPI
269	if (instance->pps_handle) {
270		time_pps_destroy(instance->pps_handle);
271		instance->pps_handle = 0;
272	}
273#endif /* HAVE_PPSAPI */
274
275	io_closeclock(&pp->io);
276	free(instance);
277}
278
279/*
280 * jupiter_config - Configure the receiver
281 */
282static int
283jupiter_config(struct instance *instance)
284{
285	jupiter_debug(instance->peer, "jupiter_config", "init receiver");
286
287	/*
288	 * Initialize the unit variables
289	 */
290	instance->sloppyclockflag = instance->peer->procptr->sloppyclockflag;
291	instance->moving = !!(instance->sloppyclockflag & CLK_FLAG2);
292	if (instance->moving)
293		jupiter_debug(instance->peer, "jupiter_config",
294			"mobile platform");
295
296	instance->pollcnt     = 2;
297	instance->polled      = 0;
298	instance->gpos_gweek = 0;
299	instance->gpos_sweek = 0;
300	instance->gweek = 0;
301	instance->lastsweek = 2 * WEEKSECS;
302	instance->timecode = 0;
303	instance->stime = 0;
304	instance->ssize = 0;
305
306	/* Stop outputting all messages */
307	jupiter_canmsg(instance, JUPITER_ALL);
308
309	/* Request the receiver id so we can syslog the firmware version */
310	jupiter_reqonemsg(instance, JUPITER_O_ID);
311
312	/* Flag that this the id was requested (so we don't get called again) */
313	instance->wantid = 1;
314
315	/* Request perodic time mark pulse messages */
316	jupiter_reqmsg(instance, JUPITER_O_PULSE, 1);
317
318	/* Request perodic geodetic position status */
319	jupiter_reqmsg(instance, JUPITER_O_GPOS, 1);
320
321	/* Set application platform type */
322	if (instance->moving)
323		jupiter_platform(instance, JUPITER_I_PLAT_MED);
324	else
325		jupiter_platform(instance, JUPITER_I_PLAT_LOW);
326
327	return (1);
328}
329
330#ifdef HAVE_PPSAPI
331/*
332 * Initialize PPSAPI
333 */
334int
335jupiter_ppsapi(
336	struct instance *instance	/* unit structure pointer */
337	)
338{
339	int capability;
340
341	if (time_pps_getcap(instance->pps_handle, &capability) < 0) {
342		msyslog(LOG_ERR,
343		    "refclock_jupiter: time_pps_getcap failed: %m");
344		return (0);
345	}
346	memset(&instance->pps_params, 0, sizeof(pps_params_t));
347	if (!instance->assert)
348		instance->pps_params.mode = capability & PPS_CAPTURECLEAR;
349	else
350		instance->pps_params.mode = capability & PPS_CAPTUREASSERT;
351	if (!(instance->pps_params.mode & (PPS_CAPTUREASSERT | PPS_CAPTURECLEAR))) {
352		msyslog(LOG_ERR,
353		    "refclock_jupiter: invalid capture edge %d",
354		    instance->assert);
355		return (0);
356	}
357	instance->pps_params.mode |= PPS_TSFMT_TSPEC;
358	if (time_pps_setparams(instance->pps_handle, &instance->pps_params) < 0) {
359		msyslog(LOG_ERR,
360		    "refclock_jupiter: time_pps_setparams failed: %m");
361		return (0);
362	}
363	if (instance->hardpps) {
364		if (time_pps_kcbind(instance->pps_handle, PPS_KC_HARDPPS,
365				    instance->pps_params.mode & ~PPS_TSFMT_TSPEC,
366				    PPS_TSFMT_TSPEC) < 0) {
367			msyslog(LOG_ERR,
368			    "refclock_jupiter: time_pps_kcbind failed: %m");
369			return (0);
370		}
371		pps_enable = 1;
372	}
373/*	instance->peer->precision = PPS_PRECISION; */
374
375#if DEBUG
376	if (debug) {
377		time_pps_getparams(instance->pps_handle, &instance->pps_params);
378		jupiter_debug(instance->peer, "refclock_jupiter",
379			"pps capability 0x%x version %d mode 0x%x kern %d",
380			capability, instance->pps_params.api_version,
381			instance->pps_params.mode, instance->hardpps);
382	}
383#endif
384
385	return (1);
386}
387
388/*
389 * Get PPSAPI timestamps.
390 *
391 * Return 0 on failure and 1 on success.
392 */
393static int
394jupiter_pps(struct instance *instance)
395{
396	pps_info_t pps_info;
397	struct timespec timeout, ts;
398	double dtemp;
399	l_fp tstmp;
400
401	/*
402	 * Convert the timespec nanoseconds field to ntp l_fp units.
403	 */
404	if (instance->pps_handle == 0)
405		return 1;
406	timeout.tv_sec = 0;
407	timeout.tv_nsec = 0;
408	memcpy(&pps_info, &instance->pps_info, sizeof(pps_info_t));
409	if (time_pps_fetch(instance->pps_handle, PPS_TSFMT_TSPEC, &instance->pps_info,
410	    &timeout) < 0)
411		return 1;
412	if (instance->pps_params.mode & PPS_CAPTUREASSERT) {
413		if (pps_info.assert_sequence ==
414		    instance->pps_info.assert_sequence)
415			return 1;
416		ts = instance->pps_info.assert_timestamp;
417	} else if (instance->pps_params.mode & PPS_CAPTURECLEAR) {
418		if (pps_info.clear_sequence ==
419		    instance->pps_info.clear_sequence)
420			return 1;
421		ts = instance->pps_info.clear_timestamp;
422	} else {
423		return 1;
424	}
425	if ((instance->ts.tv_sec == ts.tv_sec) && (instance->ts.tv_nsec == ts.tv_nsec))
426		return 1;
427	instance->ts = ts;
428
429	tstmp.l_ui = ts.tv_sec + JAN_1970;
430	dtemp = ts.tv_nsec * FRAC / 1e9;
431	tstmp.l_uf = (u_int32)dtemp;
432	instance->peer->procptr->lastrec = tstmp;
433	return 0;
434}
435#endif /* HAVE_PPSAPI */
436
437/*
438 * jupiter_poll - jupiter watchdog routine
439 */
440static void
441jupiter_poll(int unit, struct peer *peer)
442{
443	struct instance *instance;
444	struct refclockproc *pp;
445
446	pp = peer->procptr;
447	instance = (struct instance *)pp->unitptr;
448
449	/*
450	 * You don't need to poll this clock.  It puts out timecodes
451	 * once per second.  If asked for a timestamp, take note.
452	 * The next time a timecode comes in, it will be fed back.
453	 */
454
455	/*
456	 * If we haven't had a response in a while, reset the receiver.
457	 */
458	if (instance->pollcnt > 0) {
459		instance->pollcnt--;
460	} else {
461		refclock_report(peer, CEVNT_TIMEOUT);
462
463		/* Request the receiver id to trigger a reconfig */
464		jupiter_reqonemsg(instance, JUPITER_O_ID);
465		instance->wantid = 0;
466	}
467
468	/*
469	 * polled every 64 seconds. Ask jupiter_receive to hand in
470	 * a timestamp.
471	 */
472	instance->polled = 1;
473	pp->polls++;
474}
475
476/*
477 * jupiter_control - fudge control
478 */
479static void
480jupiter_control(
481	int unit,		/* unit (not used) */
482	struct refclockstat *in, /* input parameters (not used) */
483	struct refclockstat *out, /* output parameters (not used) */
484	struct peer *peer	/* peer structure pointer */
485	)
486{
487	struct refclockproc *pp;
488	struct instance *instance;
489	u_char sloppyclockflag;
490
491	pp = peer->procptr;
492	instance = (struct instance *)pp->unitptr;
493
494	DTOLFP(pp->fudgetime2, &instance->limit);
495	/* Force positive value. */
496	if (L_ISNEG(&instance->limit))
497		L_NEG(&instance->limit);
498
499#ifdef HAVE_PPSAPI
500	instance->assert = !(pp->sloppyclockflag & CLK_FLAG3);
501	jupiter_ppsapi(instance);
502#endif /* HAVE_PPSAPI */
503
504	sloppyclockflag = instance->sloppyclockflag;
505	instance->sloppyclockflag = pp->sloppyclockflag;
506	if ((instance->sloppyclockflag & CLK_FLAG2) !=
507	    (sloppyclockflag & CLK_FLAG2)) {
508		jupiter_debug(peer,
509		    "jupiter_control",
510		    "mode switch: reset receiver");
511		jupiter_config(instance);
512		return;
513	}
514}
515
516/*
517 * jupiter_receive - receive gps data
518 * Gag me!
519 */
520static void
521jupiter_receive(struct recvbuf *rbufp)
522{
523	int bpcnt, cc, size, ppsret;
524	time_t last_timecode;
525	u_int32 laststime;
526	char *cp;
527	u_char *bp;
528	u_short *sp;
529	struct jid *ip;
530	struct jheader *hp;
531	struct peer *peer;
532	struct refclockproc *pp;
533	struct instance *instance;
534	l_fp tstamp;
535
536	/* Initialize pointers and read the timecode and timestamp */
537	peer = (struct peer *)rbufp->recv_srcclock;
538	pp = peer->procptr;
539	instance = (struct instance *)pp->unitptr;
540
541	bp = (u_char *)rbufp->recv_buffer;
542	bpcnt = rbufp->recv_length;
543
544	/* This shouldn't happen */
545	if (bpcnt > sizeof(instance->sbuf) - instance->ssize)
546		bpcnt = sizeof(instance->sbuf) - instance->ssize;
547
548	/* Append to input buffer */
549	memcpy((u_char *)instance->sbuf + instance->ssize, bp, bpcnt);
550	instance->ssize += bpcnt;
551
552	/* While there's at least a header and we parse an intact message */
553	while (instance->ssize > sizeof(*hp) && (cc = jupiter_recv(instance)) > 0) {
554		instance->pollcnt = 2;
555
556		tstamp = rbufp->recv_time;
557		hp = (struct jheader *)instance->sbuf;
558		sp = (u_short *)(hp + 1);
559		size = cc - sizeof(*hp);
560		switch (getshort(hp->id)) {
561
562		case JUPITER_O_PULSE:
563			if (size != sizeof(struct jpulse)) {
564				jupiter_debug(peer,
565				    "jupiter_receive", "pulse: len %d != %u",
566				    size, (int)sizeof(struct jpulse));
567				refclock_report(peer, CEVNT_BADREPLY);
568				break;
569			}
570
571			/*
572			 * There appears to be a firmware bug related
573			 * to the pulse message; in addition to the one
574			 * per second messages, we get an extra pulse
575			 * message once an hour (on the anniversary of
576			 * the cold start). It seems to come 200 ms
577			 * after the one requested. So if we've seen a
578			 * pulse message in the last 210 ms, we skip
579			 * this one.
580			 */
581			laststime = instance->stime;
582			instance->stime = DS2UI(((struct jpulse *)sp)->stime);
583			if (laststime != 0 && instance->stime - laststime <= 21) {
584				jupiter_debug(peer, "jupiter_receive",
585				"avoided firmware bug (stime %.2f, laststime %.2f)",
586				(double)instance->stime * 0.01, (double)laststime * 0.01);
587				break;
588			}
589
590			/* Retrieve pps timestamp */
591			ppsret = jupiter_pps(instance);
592
593			/*
594			 * Add one second if msg received early
595			 * (i.e. before limit, a.k.a. fudgetime2) in
596			 * the second.
597			 */
598			L_SUB(&tstamp, &pp->lastrec);
599			if (!L_ISGEQ(&tstamp, &instance->limit))
600				++pp->lastrec.l_ui;
601
602			/* Parse timecode (even when there's no pps) */
603			last_timecode = instance->timecode;
604			if ((cp = jupiter_parse_t(instance, sp)) != NULL) {
605				jupiter_debug(peer,
606				    "jupiter_receive", "pulse: %s", cp);
607				break;
608			}
609
610			/* Bail if we didn't get a pps timestamp */
611			if (ppsret)
612				break;
613
614			/* Bail if we don't have the last timecode yet */
615			if (last_timecode == 0)
616				break;
617
618			/* Add the new sample to a median filter */
619			tstamp.l_ui = JAN_1970 + last_timecode;
620			tstamp.l_uf = 0;
621
622			refclock_process_offset(pp, tstamp, pp->lastrec, pp->fudgetime1);
623
624			/*
625			 * The clock will blurt a timecode every second
626			 * but we only want one when polled.  If we
627			 * havn't been polled, bail out.
628			 */
629			if (!instance->polled)
630				break;
631			instance->polled = 0;
632
633			/*
634			 * It's a live one!  Remember this time.
635			 */
636
637			pp->lastref = pp->lastrec;
638			refclock_receive(peer);
639
640			/*
641			 * If we get here - what we got from the clock is
642			 * OK, so say so
643			 */
644			refclock_report(peer, CEVNT_NOMINAL);
645
646			/*
647			 * We have succeeded in answering the poll.
648			 * Turn off the flag and return
649			 */
650			instance->polled = 0;
651			break;
652
653		case JUPITER_O_GPOS:
654			if (size != sizeof(struct jgpos)) {
655				jupiter_debug(peer,
656				    "jupiter_receive", "gpos: len %d != %u",
657				    size, (int)sizeof(struct jgpos));
658				refclock_report(peer, CEVNT_BADREPLY);
659				break;
660			}
661
662			if ((cp = jupiter_parse_gpos(instance, sp)) != NULL) {
663				jupiter_debug(peer,
664				    "jupiter_receive", "gpos: %s", cp);
665				break;
666			}
667			break;
668
669		case JUPITER_O_ID:
670			if (size != sizeof(struct jid)) {
671				jupiter_debug(peer,
672				    "jupiter_receive", "id: len %d != %u",
673				    size, (int)sizeof(struct jid));
674				refclock_report(peer, CEVNT_BADREPLY);
675				break;
676			}
677			/*
678			 * If we got this message because the Jupiter
679			 * just powered instance, it needs to be reconfigured.
680			 */
681			ip = (struct jid *)sp;
682			jupiter_debug(peer,
683			    "jupiter_receive", "%s chan ver %s, %s (%s)",
684			    ip->chans, ip->vers, ip->date, ip->opts);
685			msyslog(LOG_DEBUG,
686			    "jupiter_receive: %s chan ver %s, %s (%s)",
687			    ip->chans, ip->vers, ip->date, ip->opts);
688			if (instance->wantid)
689				instance->wantid = 0;
690			else {
691				jupiter_debug(peer,
692				    "jupiter_receive", "reset receiver");
693				jupiter_config(instance);
694				/*
695				 * Restore since jupiter_config() just
696				 * zeroed it
697				 */
698				instance->ssize = cc;
699			}
700			break;
701
702		default:
703			jupiter_debug(peer,
704			    "jupiter_receive", "unknown message id %d",
705			    getshort(hp->id));
706			break;
707		}
708		instance->ssize -= cc;
709		if (instance->ssize < 0) {
710			fprintf(stderr, "jupiter_recv: negative ssize!\n");
711			abort();
712		} else if (instance->ssize > 0)
713			memcpy(instance->sbuf, (u_char *)instance->sbuf + cc, instance->ssize);
714	}
715}
716
717static char *
718jupiter_parse_t(struct instance *instance, u_short *sp)
719{
720	struct tm *tm;
721	char *cp;
722	struct jpulse *jp;
723	u_int32 sweek;
724	time_t last_timecode;
725	u_short flags;
726
727	jp = (struct jpulse *)sp;
728
729	/* The timecode is presented as seconds into the current GPS week */
730	sweek = DS2UI(jp->sweek) % WEEKSECS;
731
732	/*
733	 * If we don't know the current GPS week, calculate it from the
734	 * current time. (It's too bad they didn't include this
735	 * important value in the pulse message). We'd like to pick it
736	 * up from one of the other messages like gpos or chan but they
737	 * don't appear to be synchronous with time keeping and changes
738	 * too soon (something like 10 seconds before the new GPS
739	 * week).
740	 *
741	 * If we already know the current GPS week, increment it when
742	 * we wrap into a new week.
743	 */
744	if (instance->gweek == 0) {
745		if (!instance->gpos_gweek) {
746			return ("jupiter_parse_t: Unknown gweek");
747		}
748
749		instance->gweek = instance->gpos_gweek;
750
751		/*
752		 * Fix warps. GPOS has GPS time and PULSE has UTC.
753		 * Plus, GPOS need not be completely in synch with
754		 * the PPS signal.
755		 */
756		if (instance->gpos_sweek >= sweek) {
757			if ((instance->gpos_sweek - sweek) > WEEKSECS / 2)
758				++instance->gweek;
759		}
760		else {
761			if ((sweek - instance->gpos_sweek) > WEEKSECS / 2)
762				--instance->gweek;
763		}
764	}
765	else if (sweek == 0 && instance->lastsweek == WEEKSECS - 1) {
766		++instance->gweek;
767		jupiter_debug(instance->peer,
768		    "jupiter_parse_t", "NEW gps week %u", instance->gweek);
769	}
770
771	/*
772	 * See if the sweek stayed the same (this happens when there is
773	 * no pps pulse).
774	 *
775	 * Otherwise, look for time warps:
776	 *
777	 *   - we have stored at least one lastsweek and
778	 *   - the sweek didn't increase by one and
779	 *   - we didn't wrap to a new GPS week
780	 *
781	 * Then we warped.
782	 */
783	if (instance->lastsweek == sweek)
784		jupiter_debug(instance->peer,
785		    "jupiter_parse_t", "gps sweek not incrementing (%d)",
786		    sweek);
787	else if (instance->lastsweek != 2 * WEEKSECS &&
788	    instance->lastsweek + 1 != sweek &&
789	    !(sweek == 0 && instance->lastsweek == WEEKSECS - 1))
790		jupiter_debug(instance->peer,
791		    "jupiter_parse_t", "gps sweek jumped (was %d, now %d)",
792		    instance->lastsweek, sweek);
793	instance->lastsweek = sweek;
794
795	/* This timecode describes next pulse */
796	last_timecode = instance->timecode;
797	instance->timecode =
798	    GPS_EPOCH + (instance->gweek * WEEKSECS) + sweek;
799
800	if (last_timecode == 0)
801		/* XXX debugging */
802		jupiter_debug(instance->peer,
803		    "jupiter_parse_t", "UTC <none> (gweek/sweek %u/%u)",
804		    instance->gweek, sweek);
805	else {
806		/* XXX debugging */
807		tm = gmtime(&last_timecode);
808		cp = asctime(tm);
809
810		jupiter_debug(instance->peer,
811		    "jupiter_parse_t", "UTC %.24s (gweek/sweek %u/%u)",
812		    cp, instance->gweek, sweek);
813
814		/* Billboard last_timecode (which is now the current time) */
815		instance->peer->procptr->year   = tm->tm_year + 1900;
816		instance->peer->procptr->day    = tm->tm_yday + 1;
817		instance->peer->procptr->hour   = tm->tm_hour;
818		instance->peer->procptr->minute = tm->tm_min;
819		instance->peer->procptr->second = tm->tm_sec;
820	}
821
822	flags = getshort(jp->flags);
823
824	/* Toss if not designated "valid" by the gps */
825	if ((flags & JUPITER_O_PULSE_VALID) == 0) {
826		refclock_report(instance->peer, CEVNT_BADTIME);
827		return ("time mark not valid");
828	}
829
830	/* We better be sync'ed to UTC... */
831	if ((flags & JUPITER_O_PULSE_UTC) == 0) {
832		refclock_report(instance->peer, CEVNT_BADTIME);
833		return ("time mark not sync'ed to UTC");
834	}
835
836	return (NULL);
837}
838
839static char *
840jupiter_parse_gpos(struct instance *instance, u_short *sp)
841{
842	struct jgpos *jg;
843	time_t t;
844	struct tm *tm;
845	char *cp;
846
847	jg = (struct jgpos *)sp;
848
849	if (jg->navval != 0) {
850		/*
851		 * Solution not valid. Use caution and refuse
852		 * to determine GPS week from this message.
853		 */
854		instance->gpos_gweek = 0;
855		instance->gpos_sweek = 0;
856		return ("Navigation solution not valid");
857	}
858
859	instance->gpos_gweek = jg->gweek;
860	instance->gpos_sweek = DS2UI(jg->sweek);
861	while(instance->gpos_sweek >= WEEKSECS) {
862		instance->gpos_sweek -= WEEKSECS;
863		++instance->gpos_gweek;
864	}
865	instance->gweek = 0;
866
867	t = GPS_EPOCH + (instance->gpos_gweek * WEEKSECS) + instance->gpos_sweek;
868	tm = gmtime(&t);
869	cp = asctime(tm);
870
871	jupiter_debug(instance->peer,
872		"jupiter_parse_g", "GPS %.24s (gweek/sweek %u/%u)",
873		cp, instance->gpos_gweek, instance->gpos_sweek);
874	return (NULL);
875}
876
877/*
878 * jupiter_debug - print debug messages
879 */
880#if defined(__STDC__) || defined(SYS_WINNT)
881static void
882jupiter_debug(struct peer *peer, char *function, char *fmt, ...)
883#else
884static void
885jupiter_debug(peer, function, fmt, va_alist)
886	struct peer *peer;
887	char *function;
888	char *fmt;
889#endif /* __STDC__ */
890{
891	char buffer[200];
892	va_list ap;
893
894#if defined(__STDC__) || defined(SYS_WINNT)
895	va_start(ap, fmt);
896#else
897	va_start(ap);
898#endif /* __STDC__ */
899	/*
900	 * Print debug message to stdout
901	 * In the future, we may want to get get more creative...
902	 */
903	vsnprintf(buffer, sizeof(buffer), fmt, ap);
904	record_clock_stats(&(peer->srcadr), buffer);
905#ifdef DEBUG
906	if (debug) {
907		fprintf(stdout, "%s: ", function);
908		fprintf(stdout, buffer);
909		fprintf(stdout, "\n");
910		fflush(stdout);
911	}
912#endif
913
914	va_end(ap);
915}
916
917/* Checksum and transmit a message to the Jupiter */
918static char *
919jupiter_send(struct instance *instance, struct jheader *hp)
920{
921	u_int len, size;
922	int cc;
923	u_short *sp;
924	static char errstr[132];
925
926	size = sizeof(*hp);
927	hp->hsum = putshort(jupiter_cksum((u_short *)hp,
928	    (size / sizeof(u_short)) - 1));
929	len = getshort(hp->len);
930	if (len > 0) {
931		sp = (u_short *)(hp + 1);
932		sp[len] = putshort(jupiter_cksum(sp, len));
933		size += (len + 1) * sizeof(u_short);
934	}
935
936	if ((cc = write(instance->peer->procptr->io.fd, (char *)hp, size)) < 0) {
937		(void)sprintf(errstr, "write: %s", strerror(errno));
938		return (errstr);
939	} else if (cc != size) {
940		(void)sprintf(errstr, "short write (%d != %d)", cc, size);
941		return (errstr);
942	}
943	return (NULL);
944}
945
946/* Request periodic message output */
947static struct {
948	struct jheader jheader;
949	struct jrequest jrequest;
950} reqmsg = {
951	{ putshort(JUPITER_SYNC), 0,
952	    putshort((sizeof(struct jrequest) / sizeof(u_short)) - 1),
953	    0, JUPITER_FLAG_REQUEST | JUPITER_FLAG_NAK |
954	    JUPITER_FLAG_CONN | JUPITER_FLAG_LOG, 0 },
955	{ 0, 0, 0, 0 }
956};
957
958/* An interval of zero means to output on trigger */
959static void
960jupiter_reqmsg(struct instance *instance, u_int id,
961    u_int interval)
962{
963	struct jheader *hp;
964	struct jrequest *rp;
965	char *cp;
966
967	hp = &reqmsg.jheader;
968	hp->id = putshort(id);
969	rp = &reqmsg.jrequest;
970	rp->trigger = putshort(interval == 0);
971	rp->interval = putshort(interval);
972	if ((cp = jupiter_send(instance, hp)) != NULL)
973		jupiter_debug(instance->peer, "jupiter_reqmsg", "%u: %s", id, cp);
974}
975
976/* Cancel periodic message output */
977static struct jheader canmsg = {
978	putshort(JUPITER_SYNC), 0, 0, 0,
979	JUPITER_FLAG_REQUEST | JUPITER_FLAG_NAK | JUPITER_FLAG_DISC,
980	0
981};
982
983static void
984jupiter_canmsg(struct instance *instance, u_int id)
985{
986	struct jheader *hp;
987	char *cp;
988
989	hp = &canmsg;
990	hp->id = putshort(id);
991	if ((cp = jupiter_send(instance, hp)) != NULL)
992		jupiter_debug(instance->peer, "jupiter_canmsg", "%u: %s", id, cp);
993}
994
995/* Request a single message output */
996static struct jheader reqonemsg = {
997	putshort(JUPITER_SYNC), 0, 0, 0,
998	JUPITER_FLAG_REQUEST | JUPITER_FLAG_NAK | JUPITER_FLAG_QUERY,
999	0
1000};
1001
1002static void
1003jupiter_reqonemsg(struct instance *instance, u_int id)
1004{
1005	struct jheader *hp;
1006	char *cp;
1007
1008	hp = &reqonemsg;
1009	hp->id = putshort(id);
1010	if ((cp = jupiter_send(instance, hp)) != NULL)
1011		jupiter_debug(instance->peer, "jupiter_reqonemsg", "%u: %s", id, cp);
1012}
1013
1014/* Set the platform dynamics */
1015static struct {
1016	struct jheader jheader;
1017	struct jplat jplat;
1018} platmsg = {
1019	{ putshort(JUPITER_SYNC), putshort(JUPITER_I_PLAT),
1020	    putshort((sizeof(struct jplat) / sizeof(u_short)) - 1), 0,
1021	    JUPITER_FLAG_REQUEST | JUPITER_FLAG_NAK, 0 },
1022	{ 0, 0, 0 }
1023};
1024
1025static void
1026jupiter_platform(struct instance *instance, u_int platform)
1027{
1028	struct jheader *hp;
1029	struct jplat *pp;
1030	char *cp;
1031
1032	hp = &platmsg.jheader;
1033	pp = &platmsg.jplat;
1034	pp->platform = putshort(platform);
1035	if ((cp = jupiter_send(instance, hp)) != NULL)
1036		jupiter_debug(instance->peer, "jupiter_platform", "%u: %s", platform, cp);
1037}
1038
1039/* Checksum "len" shorts */
1040static u_short
1041jupiter_cksum(u_short *sp, u_int len)
1042{
1043	u_short sum, x;
1044
1045	sum = 0;
1046	while (len-- > 0) {
1047		x = *sp++;
1048		sum += getshort(x);
1049	}
1050	return (~sum + 1);
1051}
1052
1053/* Return the size of the next message (or zero if we don't have it all yet) */
1054static int
1055jupiter_recv(struct instance *instance)
1056{
1057	int n, len, size, cc;
1058	struct jheader *hp;
1059	u_char *bp;
1060	u_short *sp;
1061
1062	/* Must have at least a header's worth */
1063	cc = sizeof(*hp);
1064	size = instance->ssize;
1065	if (size < cc)
1066		return (0);
1067
1068	/* Search for the sync short if missing */
1069	sp = instance->sbuf;
1070	hp = (struct jheader *)sp;
1071	if (getshort(hp->sync) != JUPITER_SYNC) {
1072		/* Wasn't at the front, sync up */
1073		jupiter_debug(instance->peer, "jupiter_recv", "syncing");
1074		bp = (u_char *)sp;
1075		n = size;
1076		while (n >= 2) {
1077			if (bp[0] != (JUPITER_SYNC & 0xff)) {
1078				/*
1079				jupiter_debug(instance->peer, "{0x%x}", bp[0]);
1080				*/
1081				++bp;
1082				--n;
1083				continue;
1084			}
1085			if (bp[1] == ((JUPITER_SYNC >> 8) & 0xff))
1086				break;
1087			/*
1088			jupiter_debug(instance->peer, "{0x%x 0x%x}", bp[0], bp[1]);
1089			*/
1090			bp += 2;
1091			n -= 2;
1092		}
1093		/*
1094		jupiter_debug(instance->peer, "\n");
1095		*/
1096		/* Shuffle data to front of input buffer */
1097		if (n > 0)
1098			memcpy(sp, bp, n);
1099		size = n;
1100		instance->ssize = size;
1101		if (size < cc || hp->sync != JUPITER_SYNC)
1102			return (0);
1103	}
1104
1105	if (jupiter_cksum(sp, (cc / sizeof(u_short) - 1)) !=
1106	    getshort(hp->hsum)) {
1107	    jupiter_debug(instance->peer, "jupiter_recv", "bad header checksum!");
1108		/* This is drastic but checksum errors should be rare */
1109		instance->ssize = 0;
1110		return (0);
1111	}
1112
1113	/* Check for a payload */
1114	len = getshort(hp->len);
1115	if (len > 0) {
1116		n = (len + 1) * sizeof(u_short);
1117		/* Not enough data yet */
1118		if (size < cc + n)
1119			return (0);
1120
1121		/* Check payload checksum */
1122		sp = (u_short *)(hp + 1);
1123		if (jupiter_cksum(sp, len) != getshort(sp[len])) {
1124			jupiter_debug(instance->peer,
1125			    "jupiter_recv", "bad payload checksum!");
1126			/* This is drastic but checksum errors should be rare */
1127			instance->ssize = 0;
1128			return (0);
1129		}
1130		cc += n;
1131	}
1132	return (cc);
1133}
1134
1135#else /* not (REFCLOCK && CLOCK_JUPITER && HAVE_PPSAPI) */
1136int refclock_jupiter_bs;
1137#endif /* not (REFCLOCK && CLOCK_JUPITER && HAVE_PPSAPI) */
1138