xref: /freebsd/contrib/ntp/ntpd/refclock_parse.c (revision ef0cb5db0af0d5d5b75b74f8e534fe601b7176d7)
1 /*
2  * /src/NTP/REPOSITORY/ntp4-dev/ntpd/refclock_parse.c,v 4.81 2009/05/01 10:15:29 kardel RELEASE_20090105_A
3  *
4  * refclock_parse.c,v 4.81 2009/05/01 10:15:29 kardel RELEASE_20090105_A
5  *
6  * generic reference clock driver for several DCF/GPS/MSF/... receivers
7  *
8  * PPS notes:
9  *   On systems that support PPSAPI (RFC2783) PPSAPI is the
10  *   preferred interface.
11  *
12  *   Optionally make use of a STREAMS module for input processing where
13  *   available and configured. This STREAMS module reduces the time
14  *   stamp latency for serial and PPS events.
15  *   Currently the STREAMS module is only available for Suns running
16  *   SunOS 4.x and SunOS5.x.
17  *
18  * Copyright (c) 1995-2009 by Frank Kardel <kardel <AT> ntp.org>
19  * Copyright (c) 1989-1994 by Frank Kardel, Friedrich-Alexander Universitaet Erlangen-Nuernberg, Germany
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  * 3. Neither the name of the author nor the names of its contributors
30  *    may be used to endorse or promote products derived from this software
31  *    without specific prior written permission.
32  *
33  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
34  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
35  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
37  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
38  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
39  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
40  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
41  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
42  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
43  * SUCH DAMAGE.
44  *
45  */
46 
47 #ifdef HAVE_CONFIG_H
48 # include "config.h"
49 #endif
50 
51 #include "ntp_types.h"
52 
53 #if defined(REFCLOCK) && defined(CLOCK_PARSE)
54 
55 /*
56  * This driver currently provides the support for
57  *   - Meinberg receiver DCF77 PZF535 (TCXO version)        (DCF)
58  *   - Meinberg receiver DCF77 PZF535 (OCXO version)        (DCF)
59  *   - Meinberg receiver DCF77 PZF509                       (DCF)
60  *   - Meinberg receiver DCF77 AM receivers (e.g. C51)      (DCF)
61  *   - IGEL CLOCK                                           (DCF)
62  *   - ELV DCF7000                                          (DCF)
63  *   - Schmid clock                                         (DCF)
64  *   - Conrad DCF77 receiver module                         (DCF)
65  *   - FAU DCF77 NTP receiver (TimeBrick)                   (DCF)
66  *   - WHARTON 400A Series clock                            (DCF)
67  *
68  *   - Meinberg GPS receivers                               (GPS)
69  *   - Trimble (TSIP and TAIP protocol)                     (GPS)
70  *
71  *   - RCC8000 MSF Receiver                                 (MSF)
72  *   - VARITEXT clock                                       (MSF)
73  */
74 
75 /*
76  * Meinberg receivers are usually connected via a
77  * 9600/7E1 or 19200/8N1 serial line.
78  *
79  * The Meinberg GPS receivers also have a special NTP time stamp
80  * format. The firmware release is Uni-Erlangen.
81  *
82  * Meinberg generic receiver setup:
83  *      output time code every second
84  *      Baud rate 9600 7E2S
85  *
86  * Meinberg GPS receiver setup:
87  *      output time code every second
88  *      Baudrate 19200 8N1
89  *
90  * This software supports the standard data formats used
91  * in Meinberg receivers.
92  *
93  * Special software versions are only sensible for the
94  * oldest GPS receiver, GPS16x. For newer receiver types
95  * the output string format can be configured at the device,
96  * and the device name is generally GPSxxx instead of GPS16x.
97  *
98  * Meinberg can be reached via: http://www.meinberg.de/
99  */
100 
101 #include "ntpd.h"
102 #include "ntp_refclock.h"
103 #include "timevalops.h"		/* includes <sys/time.h> */
104 #include "ntp_control.h"
105 #include "ntp_string.h"
106 
107 #include <stdio.h>
108 #include <ctype.h>
109 #ifndef TM_IN_SYS_TIME
110 # include <time.h>
111 #endif
112 
113 #ifdef HAVE_UNISTD_H
114 # include <unistd.h>
115 #endif
116 
117 #if !defined(STREAM) && !defined(HAVE_SYSV_TTYS) && !defined(HAVE_BSD_TTYS) && !defined(HAVE_TERMIOS)
118 # include "Bletch:  Define one of {STREAM,HAVE_SYSV_TTYS,HAVE_TERMIOS}"
119 #endif
120 
121 #ifdef STREAM
122 # include <sys/stream.h>
123 # include <sys/stropts.h>
124 #endif
125 
126 #ifdef HAVE_TERMIOS
127 # include <termios.h>
128 # define TTY_GETATTR(_FD_, _ARG_) tcgetattr((_FD_), (_ARG_))
129 # define TTY_SETATTR(_FD_, _ARG_) tcsetattr((_FD_), TCSANOW, (_ARG_))
130 # undef HAVE_SYSV_TTYS
131 #endif
132 
133 #ifdef HAVE_SYSV_TTYS
134 # define TTY_GETATTR(_FD_, _ARG_) ioctl((_FD_), TCGETA, (_ARG_))
135 # define TTY_SETATTR(_FD_, _ARG_) ioctl((_FD_), TCSETAW, (_ARG_))
136 #endif
137 
138 #ifdef HAVE_BSD_TTYS
139 /* #error CURRENTLY NO BSD TTY SUPPORT */
140 # include "Bletch: BSD TTY not currently supported"
141 #endif
142 
143 #ifdef HAVE_SYS_IOCTL_H
144 # include <sys/ioctl.h>
145 #endif
146 
147 #ifdef HAVE_PPSAPI
148 # include "ppsapi_timepps.h"
149 # include "refclock_atom.h"
150 #endif
151 
152 #ifdef PPS
153 # ifdef HAVE_SYS_PPSCLOCK_H
154 #  include <sys/ppsclock.h>
155 # endif
156 # ifdef HAVE_TIO_SERIAL_STUFF
157 #  include <linux/serial.h>
158 # endif
159 #endif
160 
161 # define BUFFER_SIZE(_BUF, _PTR)       ((int)((_BUF) + sizeof(_BUF) - (_PTR)))
162 # define BUFFER_SIZES(_BUF, _PTR, _SZ) ((int)((_BUF) + (_SZ) - (_PTR)))
163 
164 /*
165  * document type of PPS interfacing - copy of ifdef mechanism in local_input()
166  */
167 #undef PPS_METHOD
168 
169 #ifdef HAVE_PPSAPI
170 #define PPS_METHOD "PPS API"
171 #else
172 #ifdef TIOCDCDTIMESTAMP
173 #define PPS_METHOD "TIOCDCDTIMESTAMP"
174 #else /* TIOCDCDTIMESTAMP */
175 #if defined(HAVE_STRUCT_PPSCLOCKEV) && (defined(HAVE_CIOGETEV) || defined(HAVE_TIOCGPPSEV))
176 #ifdef HAVE_CIOGETEV
177 #define PPS_METHOD "CIOGETEV"
178 #endif
179 #ifdef HAVE_TIOCGPPSEV
180 #define PPS_METHOD "TIOCGPPSEV"
181 #endif
182 #endif
183 #endif /* TIOCDCDTIMESTAMP */
184 #endif /* HAVE_PPSAPI */
185 
186 /*
187  * COND_DEF can be conditionally defined as DEF or 0. If defined as DEF
188  * then some more parse-specific variables are flagged to be printed with
189  * "ntpq -c cv <assid>". This can be lengthy, so by default COND_DEF
190  * should be defined as 0.
191  */
192 #if 0
193 # define COND_DEF   DEF   // enable this for testing
194 #else
195 # define COND_DEF   0     // enable this by default
196 #endif
197 
198 #include "ntp_io.h"
199 #include "ntp_stdlib.h"
200 
201 #include "parse.h"
202 #include "mbg_gps166.h"
203 #include "trimble.h"
204 #include "binio.h"
205 #include "ascii.h"
206 #include "ieee754io.h"
207 #include "recvbuff.h"
208 
209 static char rcsid[] = "refclock_parse.c,v 4.81 2009/05/01 10:15:29 kardel RELEASE_20090105_A+POWERUPTRUST";
210 
211 /**===========================================================================
212  ** external interface to ntp mechanism
213  **/
214 
215 static	int	parse_start	(int, struct peer *);
216 static	void	parse_shutdown	(int, struct peer *);
217 static	void	parse_poll	(int, struct peer *);
218 static	void	parse_control	(int, const struct refclockstat *, struct refclockstat *, struct peer *);
219 
220 struct	refclock refclock_parse = {
221 	parse_start,
222 	parse_shutdown,
223 	parse_poll,
224 	parse_control,
225 	noentry,
226 	noentry,
227 	NOFLAGS
228 };
229 
230 /*
231  * Definitions
232  */
233 #define	MAXUNITS	4	/* maximum number of "PARSE" units permitted */
234 #define PARSEDEVICE	"/dev/refclock-%d" /* device to open %d is unit number */
235 #define PARSEPPSDEVICE	"/dev/refclockpps-%d" /* optional pps device to open %d is unit number */
236 
237 #undef ABS
238 #define ABS(_X_) (((_X_) < 0) ? -(_X_) : (_X_))
239 
240 #define PARSE_HARDPPS_DISABLE 0
241 #define PARSE_HARDPPS_ENABLE  1
242 
243 /**===========================================================================
244  ** function vector for dynamically binding io handling mechanism
245  **/
246 
247 struct parseunit;		/* to keep inquiring minds happy */
248 
249 typedef struct bind
250 {
251   const char *bd_description;	                                /* name of type of binding */
252   int	(*bd_init)     (struct parseunit *);			/* initialize */
253   void	(*bd_end)      (struct parseunit *);			/* end */
254   int   (*bd_setcs)    (struct parseunit *, parsectl_t *);	/* set character size */
255   int	(*bd_disable)  (struct parseunit *);			/* disable */
256   int	(*bd_enable)   (struct parseunit *);			/* enable */
257   int	(*bd_getfmt)   (struct parseunit *, parsectl_t *);	/* get format */
258   int	(*bd_setfmt)   (struct parseunit *, parsectl_t *);	/* setfmt */
259   int	(*bd_timecode) (struct parseunit *, parsectl_t *);	/* get time code */
260   void	(*bd_receive)  (struct recvbuf *);			/* receive operation */
261   int	(*bd_io_input) (struct recvbuf *);			/* input operation */
262 } bind_t;
263 
264 #define PARSE_END(_X_)			(*(_X_)->binding->bd_end)(_X_)
265 #define PARSE_SETCS(_X_, _CS_)		(*(_X_)->binding->bd_setcs)(_X_, _CS_)
266 #define PARSE_ENABLE(_X_)		(*(_X_)->binding->bd_enable)(_X_)
267 #define PARSE_DISABLE(_X_)		(*(_X_)->binding->bd_disable)(_X_)
268 #define PARSE_GETFMT(_X_, _DCT_)	(*(_X_)->binding->bd_getfmt)(_X_, _DCT_)
269 #define PARSE_SETFMT(_X_, _DCT_)	(*(_X_)->binding->bd_setfmt)(_X_, _DCT_)
270 #define PARSE_GETTIMECODE(_X_, _DCT_)	(*(_X_)->binding->bd_timecode)(_X_, _DCT_)
271 
272 /*
273  * special handling flags
274  */
275 #define PARSE_F_PPSONSECOND	0x00000001 /* PPS pulses are on second */
276 #define PARSE_F_POWERUPTRUST	0x00000100 /* POWERUP state ist trusted for */
277                                            /* trusttime after SYNC was seen */
278 /**===========================================================================
279  ** error message regression handling
280  **
281  ** there are quite a few errors that can occur in rapid succession such as
282  ** noisy input data or no data at all. in order to reduce the amount of
283  ** syslog messages in such case, we are using a backoff algorithm. We limit
284  ** the number of error messages of a certain class to 1 per time unit. if a
285  ** configurable number of messages is displayed that way, we move on to the
286  ** next time unit / count for that class. a count of messages that have been
287  ** suppressed is held and displayed whenever a corresponding message is
288  ** displayed. the time units for a message class will also be displayed.
289  ** whenever an error condition clears we reset the error message state,
290  ** thus we would still generate much output on pathological conditions
291  ** where the system oscillates between OK and NOT OK states. coping
292  ** with that condition is currently considered too complicated.
293  **/
294 
295 #define ERR_ALL	        (unsigned)~0	/* "all" errors */
296 #define ERR_BADDATA	(unsigned)0	/* unusable input data/conversion errors */
297 #define ERR_NODATA	(unsigned)1	/* no input data */
298 #define ERR_BADIO	(unsigned)2	/* read/write/select errors */
299 #define ERR_BADSTATUS	(unsigned)3	/* unsync states */
300 #define ERR_BADEVENT	(unsigned)4	/* non nominal events */
301 #define ERR_INTERNAL	(unsigned)5	/* internal error */
302 #define ERR_CNT		(unsigned)(ERR_INTERNAL+1)
303 
304 #define ERR(_X_)	if (list_err(parse, (_X_)))
305 
306 struct errorregression
307 {
308 	u_long err_count;	/* number of repititions per class */
309 	u_long err_delay;	/* minimum delay between messages */
310 };
311 
312 static struct errorregression
313 err_baddata[] =			/* error messages for bad input data */
314 {
315 	{ 1,       0 },		/* output first message immediately */
316 	{ 5,      60 },		/* output next five messages in 60 second intervals */
317 	{ 3,    3600 },		/* output next 3 messages in hour intervals */
318 	{ 0, 12*3600 }		/* repeat messages only every 12 hours */
319 };
320 
321 static struct errorregression
322 err_nodata[] =			/* error messages for missing input data */
323 {
324 	{ 1,       0 },		/* output first message immediately */
325 	{ 5,      60 },		/* output next five messages in 60 second intervals */
326 	{ 3,    3600 },		/* output next 3 messages in hour intervals */
327 	{ 0, 12*3600 }		/* repeat messages only every 12 hours */
328 };
329 
330 static struct errorregression
331 err_badstatus[] =		/* unsynchronized state messages */
332 {
333 	{ 1,       0 },		/* output first message immediately */
334 	{ 5,      60 },		/* output next five messages in 60 second intervals */
335 	{ 3,    3600 },		/* output next 3 messages in hour intervals */
336 	{ 0, 12*3600 }		/* repeat messages only every 12 hours */
337 };
338 
339 static struct errorregression
340 err_badio[] =			/* io failures (bad reads, selects, ...) */
341 {
342 	{ 1,       0 },		/* output first message immediately */
343 	{ 5,      60 },		/* output next five messages in 60 second intervals */
344 	{ 5,    3600 },		/* output next 3 messages in hour intervals */
345 	{ 0, 12*3600 }		/* repeat messages only every 12 hours */
346 };
347 
348 static struct errorregression
349 err_badevent[] =		/* non nominal events */
350 {
351 	{ 20,      0 },		/* output first message immediately */
352 	{ 6,      60 },		/* output next five messages in 60 second intervals */
353 	{ 5,    3600 },		/* output next 3 messages in hour intervals */
354 	{ 0, 12*3600 }		/* repeat messages only every 12 hours */
355 };
356 
357 static struct errorregression
358 err_internal[] =		/* really bad things - basically coding/OS errors */
359 {
360 	{ 0,       0 },		/* output all messages immediately */
361 };
362 
363 static struct errorregression *
364 err_tbl[] =
365 {
366 	err_baddata,
367 	err_nodata,
368 	err_badio,
369 	err_badstatus,
370 	err_badevent,
371 	err_internal
372 };
373 
374 struct errorinfo
375 {
376 	u_long err_started;	/* begin time (ntp) of error condition */
377 	u_long err_last;	/* last time (ntp) error occurred */
378 	u_long err_cnt;	/* number of error repititions */
379 	u_long err_suppressed;	/* number of suppressed messages */
380 	struct errorregression *err_stage; /* current error stage */
381 };
382 
383 /**===========================================================================
384  ** refclock instance data
385  **/
386 
387 struct parseunit
388 {
389 	/*
390 	 * NTP management
391 	 */
392 	struct peer         *peer;		/* backlink to peer structure - refclock inactive if 0  */
393 	struct refclockproc *generic;		/* backlink to refclockproc structure */
394 
395 	/*
396 	 * PARSE io
397 	 */
398 	bind_t	     *binding;	        /* io handling binding */
399 
400 	/*
401 	 * parse state
402 	 */
403 	parse_t	      parseio;	        /* io handling structure (user level parsing) */
404 
405 	/*
406 	 * type specific parameters
407 	 */
408 	struct parse_clockinfo   *parse_type;	        /* link to clock description */
409 
410 	/*
411 	 * clock state handling/reporting
412 	 */
413 	u_char	      flags;	        /* flags (leap_control) */
414 	u_long	      lastchange;       /* time (ntp) when last state change accured */
415 	u_long	      statetime[CEVNT_MAX+1]; /* accumulated time of clock states */
416 	u_long        pollneeddata; 	/* current_time(!=0) for receive sample expected in PPS mode */
417 	u_short	      lastformat;       /* last format used */
418 	u_long        lastsync;		/* time (ntp) when clock was last seen fully synchronized */
419         u_long        maxunsync;        /* max time in seconds a receiver is trusted after loosing synchronisation */
420         double        ppsphaseadjust;   /* phase adjustment of PPS time stamp */
421         u_long        lastmissed;       /* time (ntp) when poll didn't get data (powerup heuristic) */
422 	u_long        ppsserial;        /* magic cookie for ppsclock serials (avoids stale ppsclock data) */
423 	int	      ppsfd;	        /* fd to ise for PPS io */
424 #ifdef HAVE_PPSAPI
425         int           hardppsstate;     /* current hard pps state */
426 	struct refclock_atom atom;      /* PPSAPI structure */
427 #endif
428 	parsetime_t   timedata;		/* last (parse module) data */
429 	void         *localdata;        /* optional local, receiver-specific data */
430         unsigned long localstate;       /* private local state */
431 	struct errorinfo errors[ERR_CNT];  /* error state table for suppressing excessive error messages */
432 	struct ctl_var *kv;	        /* additional pseudo variables */
433 	u_long        laststatistic;    /* time when staticstics where output */
434 };
435 
436 
437 /**===========================================================================
438  ** Clockinfo section all parameter for specific clock types
439  ** includes NTP parameters, TTY parameters and IO handling parameters
440  **/
441 
442 static	void	poll_dpoll	(struct parseunit *);
443 static	void	poll_poll	(struct peer *);
444 static	int	poll_init	(struct parseunit *);
445 
446 typedef struct poll_info
447 {
448 	u_long      rate;		/* poll rate - once every "rate" seconds - 0 off */
449 	const char *string;		/* string to send for polling */
450 	u_long      count;		/* number of characters in string */
451 } poll_info_t;
452 
453 #define NO_CL_FLAGS	0
454 #define NO_POLL		0
455 #define NO_INIT		0
456 #define NO_END		0
457 #define NO_EVENT	0
458 #define NO_LCLDATA	0
459 #define NO_MESSAGE	0
460 #define NO_PPSDELAY     0
461 
462 #define DCF_ID		"DCF"	/* generic DCF */
463 #define DCF_A_ID	"DCFa"	/* AM demodulation */
464 #define DCF_P_ID	"DCFp"	/* psuedo random phase shift */
465 #define GPS_ID		"GPS"	/* GPS receiver */
466 
467 #define NOCLOCK_ROOTDELAY       0.0
468 #define NOCLOCK_BASEDELAY       0.0
469 #define NOCLOCK_DESCRIPTION     0
470 #define NOCLOCK_MAXUNSYNC       0
471 #define NOCLOCK_CFLAG           0
472 #define NOCLOCK_IFLAG           0
473 #define NOCLOCK_OFLAG           0
474 #define NOCLOCK_LFLAG           0
475 #define NOCLOCK_ID              "TILT"
476 #define NOCLOCK_POLL            NO_POLL
477 #define NOCLOCK_INIT            NO_INIT
478 #define NOCLOCK_END             NO_END
479 #define NOCLOCK_DATA            NO_LCLDATA
480 #define NOCLOCK_FORMAT          ""
481 #define NOCLOCK_TYPE            CTL_SST_TS_UNSPEC
482 #define NOCLOCK_SAMPLES         0
483 #define NOCLOCK_KEEP            0
484 
485 #define DCF_TYPE		CTL_SST_TS_LF
486 #define GPS_TYPE		CTL_SST_TS_UHF
487 
488 /*
489  * receiver specific constants
490  */
491 #define MBG_SPEED		(B9600)
492 #define MBG_CFLAG		(CS7|PARENB|CREAD|CLOCAL|HUPCL|CSTOPB)
493 #define MBG_IFLAG		(IGNBRK|IGNPAR|ISTRIP)
494 #define MBG_OFLAG		0
495 #define MBG_LFLAG		0
496 #define MBG_FLAGS               PARSE_F_PPSONSECOND
497 
498 /*
499  * Meinberg DCF77 receivers
500  */
501 #define	DCFUA31_ROOTDELAY	0.0  /* 0 */
502 #define	DCFUA31_BASEDELAY	0.010  /* 10.7421875ms: 10 ms (+/- 3 ms) */
503 #define	DCFUA31_DESCRIPTION	"Meinberg DCF77 C51 or compatible"
504 #define DCFUA31_MAXUNSYNC       60*30       /* only trust clock for 1/2 hour */
505 #define DCFUA31_SPEED		MBG_SPEED
506 #define DCFUA31_CFLAG           MBG_CFLAG
507 #define DCFUA31_IFLAG           MBG_IFLAG
508 #define DCFUA31_OFLAG           MBG_OFLAG
509 #define DCFUA31_LFLAG           MBG_LFLAG
510 #define DCFUA31_SAMPLES		5
511 #define DCFUA31_KEEP		3
512 #define DCFUA31_FORMAT		"Meinberg Standard"
513 
514 /*
515  * Meinberg DCF PZF535/TCXO (FM/PZF) receiver
516  */
517 #define	DCFPZF535_ROOTDELAY	0.0
518 #define	DCFPZF535_BASEDELAY	0.001968  /* 1.968ms +- 104us (oscilloscope) - relative to start (end of STX) */
519 #define	DCFPZF535_DESCRIPTION	"Meinberg DCF PZF 535/509 / TCXO"
520 #define DCFPZF535_MAXUNSYNC     60*60*12           /* only trust clock for 12 hours
521 						    * @ 5e-8df/f we have accumulated
522 						    * at most 2.16 ms (thus we move to
523 						    * NTP synchronisation */
524 #define DCFPZF535_SPEED		MBG_SPEED
525 #define DCFPZF535_CFLAG         MBG_CFLAG
526 #define DCFPZF535_IFLAG         MBG_IFLAG
527 #define DCFPZF535_OFLAG         MBG_OFLAG
528 #define DCFPZF535_LFLAG         MBG_LFLAG
529 #define DCFPZF535_SAMPLES	       5
530 #define DCFPZF535_KEEP		       3
531 #define DCFPZF535_FORMAT	"Meinberg Standard"
532 
533 /*
534  * Meinberg DCF PZF535/OCXO receiver
535  */
536 #define	DCFPZF535OCXO_ROOTDELAY	0.0
537 #define	DCFPZF535OCXO_BASEDELAY	0.001968 /* 1.968ms +- 104us (oscilloscope) - relative to start (end of STX) */
538 #define	DCFPZF535OCXO_DESCRIPTION "Meinberg DCF PZF 535/509 / OCXO"
539 #define DCFPZF535OCXO_MAXUNSYNC     60*60*96       /* only trust clock for 4 days
540 						    * @ 5e-9df/f we have accumulated
541 						    * at most an error of 1.73 ms
542 						    * (thus we move to NTP synchronisation) */
543 #define DCFPZF535OCXO_SPEED	    MBG_SPEED
544 #define DCFPZF535OCXO_CFLAG         MBG_CFLAG
545 #define DCFPZF535OCXO_IFLAG         MBG_IFLAG
546 #define DCFPZF535OCXO_OFLAG         MBG_OFLAG
547 #define DCFPZF535OCXO_LFLAG         MBG_LFLAG
548 #define DCFPZF535OCXO_SAMPLES		   5
549 #define DCFPZF535OCXO_KEEP	           3
550 #define DCFPZF535OCXO_FORMAT	    "Meinberg Standard"
551 
552 /*
553  * Meinberg GPS receivers
554  */
555 static	void	gps16x_message	 (struct parseunit *, parsetime_t *);
556 static  int     gps16x_poll_init (struct parseunit *);
557 
558 #define	GPS16X_ROOTDELAY	0.0         /* nothing here */
559 #define	GPS16X_BASEDELAY	0.001968         /* XXX to be fixed ! 1.968ms +- 104us (oscilloscope) - relative to start (end of STX) */
560 #define	GPS16X_DESCRIPTION      "Meinberg GPS receiver"
561 #define GPS16X_MAXUNSYNC        60*60*96       /* only trust clock for 4 days
562 						* @ 5e-9df/f we have accumulated
563 						* at most an error of 1.73 ms
564 						* (thus we move to NTP synchronisation) */
565 #define GPS16X_SPEED		B19200
566 #define GPS16X_CFLAG            (CS8|CREAD|CLOCAL|HUPCL)
567 #define GPS16X_IFLAG            (IGNBRK|IGNPAR)
568 #define GPS16X_OFLAG            MBG_OFLAG
569 #define GPS16X_LFLAG            MBG_LFLAG
570 #define GPS16X_POLLRATE	6
571 #define GPS16X_POLLCMD	""
572 #define GPS16X_CMDSIZE	0
573 
574 static poll_info_t gps16x_pollinfo = { GPS16X_POLLRATE, GPS16X_POLLCMD, GPS16X_CMDSIZE };
575 
576 #define GPS16X_INIT		gps16x_poll_init
577 #define GPS16X_POLL	        0
578 #define GPS16X_END		0
579 #define GPS16X_DATA		((void *)(&gps16x_pollinfo))
580 #define GPS16X_MESSAGE		gps16x_message
581 #define GPS16X_ID		GPS_ID
582 #define GPS16X_FORMAT		"Meinberg GPS Extended"
583 #define GPS16X_SAMPLES		5
584 #define GPS16X_KEEP		3
585 
586 /*
587  * ELV DCF7000 Wallclock-Receiver/Switching Clock (Kit)
588  *
589  * This is really not the hottest clock - but before you have nothing ...
590  */
591 #define DCF7000_ROOTDELAY	0.0 /* 0 */
592 #define DCF7000_BASEDELAY	0.405 /* slow blow */
593 #define DCF7000_DESCRIPTION	"ELV DCF7000"
594 #define DCF7000_MAXUNSYNC	(60*5) /* sorry - but it just was not build as a clock */
595 #define DCF7000_SPEED		(B9600)
596 #define DCF7000_CFLAG           (CS8|CREAD|PARENB|PARODD|CLOCAL|HUPCL)
597 #define DCF7000_IFLAG		(IGNBRK)
598 #define DCF7000_OFLAG		0
599 #define DCF7000_LFLAG		0
600 #define DCF7000_SAMPLES		5
601 #define DCF7000_KEEP		3
602 #define DCF7000_FORMAT		"ELV DCF7000"
603 
604 /*
605  * Schmid DCF Receiver Kit
606  *
607  * When the WSDCF clock is operating optimally we want the primary clock
608  * distance to come out at 300 ms.  Thus, peer.distance in the WSDCF peer
609  * structure is set to 290 ms and we compute delays which are at least
610  * 10 ms long.  The following are 290 ms and 10 ms expressed in u_fp format
611  */
612 #define WS_POLLRATE	1	/* every second - watch interdependency with poll routine */
613 #define WS_POLLCMD	"\163"
614 #define WS_CMDSIZE	1
615 
616 static poll_info_t wsdcf_pollinfo = { WS_POLLRATE, WS_POLLCMD, WS_CMDSIZE };
617 
618 #define WSDCF_INIT		poll_init
619 #define WSDCF_POLL		poll_dpoll
620 #define WSDCF_END		0
621 #define WSDCF_DATA		((void *)(&wsdcf_pollinfo))
622 #define	WSDCF_ROOTDELAY		0.0	/* 0 */
623 #define	WSDCF_BASEDELAY	 	0.010	/*  ~  10ms */
624 #define WSDCF_DESCRIPTION	"WS/DCF Receiver"
625 #define WSDCF_FORMAT		"Schmid"
626 #define WSDCF_MAXUNSYNC		(60*60)	/* assume this beast hold at 1 h better than 2 ms XXX-must verify */
627 #define WSDCF_SPEED		(B1200)
628 #define WSDCF_CFLAG		(CS8|CREAD|CLOCAL)
629 #define WSDCF_IFLAG		0
630 #define WSDCF_OFLAG		0
631 #define WSDCF_LFLAG		0
632 #define WSDCF_SAMPLES		5
633 #define WSDCF_KEEP		3
634 
635 /*
636  * RAW DCF77 - input of DCF marks via RS232 - many variants
637  */
638 #define RAWDCF_FLAGS		0
639 #define RAWDCF_ROOTDELAY	0.0 /* 0 */
640 #define RAWDCF_BASEDELAY	0.258
641 #define RAWDCF_FORMAT		"RAW DCF77 Timecode"
642 #define RAWDCF_MAXUNSYNC	(0) /* sorry - its a true receiver - no signal - no time */
643 #define RAWDCF_SPEED		(B50)
644 #ifdef NO_PARENB_IGNPAR /* Was: defined(SYS_IRIX4) || defined(SYS_IRIX5) */
645 /* somehow doesn't grok PARENB & IGNPAR (mj) */
646 # define RAWDCF_CFLAG            (CS8|CREAD|CLOCAL)
647 #else
648 # define RAWDCF_CFLAG            (CS8|CREAD|CLOCAL|PARENB)
649 #endif
650 #ifdef RAWDCF_NO_IGNPAR /* Was: defined(SYS_LINUX) && defined(CLOCK_RAWDCF) */
651 # define RAWDCF_IFLAG		0
652 #else
653 # define RAWDCF_IFLAG		(IGNPAR)
654 #endif
655 #define RAWDCF_OFLAG		0
656 #define RAWDCF_LFLAG		0
657 #define RAWDCF_SAMPLES		20
658 #define RAWDCF_KEEP		12
659 #define RAWDCF_INIT		0
660 
661 /*
662  * RAW DCF variants
663  */
664 /*
665  * Conrad receiver
666  *
667  * simplest (cheapest) DCF clock - e. g. DCF77 receiver by Conrad
668  * (~40DM - roughly $30 ) followed by a level converter for RS232
669  */
670 #define CONRAD_BASEDELAY	0.292 /* Conrad receiver @ 50 Baud on a Sun */
671 #define CONRAD_DESCRIPTION	"RAW DCF77 CODE (Conrad DCF77 receiver module)"
672 
673 /* Gude Analog- und Digitalsystem GmbH 'Expert mouseCLOCK USB v2.0' */
674 #define GUDE_EMC_USB_V20_SPEED            (B4800)
675 #define GUDE_EMC_USB_V20_BASEDELAY        0.425 /* USB serial<->USB converter FTDI232R */
676 #define GUDE_EMC_USB_V20_DESCRIPTION      "RAW DCF77 CODE (Expert mouseCLOCK USB v2.0)"
677 
678 /*
679  * TimeBrick receiver
680  */
681 #define TIMEBRICK_BASEDELAY	0.210 /* TimeBrick @ 50 Baud on a Sun */
682 #define TIMEBRICK_DESCRIPTION	"RAW DCF77 CODE (TimeBrick)"
683 
684 /*
685  * IGEL:clock receiver
686  */
687 #define IGELCLOCK_BASEDELAY	0.258 /* IGEL:clock receiver */
688 #define IGELCLOCK_DESCRIPTION	"RAW DCF77 CODE (IGEL:clock)"
689 #define IGELCLOCK_SPEED		(B1200)
690 #define IGELCLOCK_CFLAG		(CS8|CREAD|HUPCL|CLOCAL)
691 
692 /*
693  * RAWDCF receivers that need to be powered from DTR
694  * (like Expert mouse clock)
695  */
696 static	int	rawdcf_init_1	(struct parseunit *);
697 #define RAWDCFDTRSET_DESCRIPTION	"RAW DCF77 CODE (DTR SET/RTS CLR)"
698 #define RAWDCFDTRSET75_DESCRIPTION	"RAW DCF77 CODE (DTR SET/RTS CLR @ 75 baud)"
699 #define RAWDCFDTRSET_INIT 		rawdcf_init_1
700 
701 /*
702  * RAWDCF receivers that need to be powered from
703  * DTR CLR and RTS SET
704  */
705 static	int	rawdcf_init_2	(struct parseunit *);
706 #define RAWDCFDTRCLRRTSSET_DESCRIPTION	"RAW DCF77 CODE (DTR CLR/RTS SET)"
707 #define RAWDCFDTRCLRRTSSET75_DESCRIPTION "RAW DCF77 CODE (DTR CLR/RTS SET @ 75 baud)"
708 #define RAWDCFDTRCLRRTSSET_INIT	rawdcf_init_2
709 
710 /*
711  * Trimble GPS receivers (TAIP and TSIP protocols)
712  */
713 #ifndef TRIM_POLLRATE
714 #define TRIM_POLLRATE	0	/* only true direct polling */
715 #endif
716 
717 #define TRIM_TAIPPOLLCMD	">SRM;FR_FLAG=F;EC_FLAG=F<>QTM<"
718 #define TRIM_TAIPCMDSIZE	(sizeof(TRIM_TAIPPOLLCMD)-1)
719 
720 static poll_info_t trimbletaip_pollinfo = { TRIM_POLLRATE, TRIM_TAIPPOLLCMD, TRIM_TAIPCMDSIZE };
721 static	int	trimbletaip_init	(struct parseunit *);
722 static	void	trimbletaip_event	(struct parseunit *, int);
723 
724 /* query time & UTC correction data */
725 static char tsipquery[] = { DLE, 0x21, DLE, ETX, DLE, 0x2F, DLE, ETX };
726 
727 static poll_info_t trimbletsip_pollinfo = { TRIM_POLLRATE, tsipquery, sizeof(tsipquery) };
728 static	int	trimbletsip_init	(struct parseunit *);
729 static	void	trimbletsip_end   	(struct parseunit *);
730 static	void	trimbletsip_message	(struct parseunit *, parsetime_t *);
731 static	void	trimbletsip_event	(struct parseunit *, int);
732 
733 #define TRIMBLETSIP_IDLE_TIME	    (300) /* 5 minutes silence at most */
734 #define TRIMBLE_RESET_HOLDOFF       TRIMBLETSIP_IDLE_TIME
735 
736 #define TRIMBLETAIP_SPEED	    (B4800)
737 #define TRIMBLETAIP_CFLAG           (CS8|CREAD|CLOCAL)
738 #define TRIMBLETAIP_IFLAG           (BRKINT|IGNPAR|ISTRIP|ICRNL|IXON)
739 #define TRIMBLETAIP_OFLAG           (OPOST|ONLCR)
740 #define TRIMBLETAIP_LFLAG           (0)
741 
742 #define TRIMBLETSIP_SPEED	    (B9600)
743 #define TRIMBLETSIP_CFLAG           (CS8|CLOCAL|CREAD|PARENB|PARODD)
744 #define TRIMBLETSIP_IFLAG           (IGNBRK)
745 #define TRIMBLETSIP_OFLAG           (0)
746 #define TRIMBLETSIP_LFLAG           (ICANON)
747 
748 #define TRIMBLETSIP_SAMPLES	    5
749 #define TRIMBLETSIP_KEEP	    3
750 #define TRIMBLETAIP_SAMPLES	    5
751 #define TRIMBLETAIP_KEEP	    3
752 
753 #define TRIMBLETAIP_FLAGS	    (PARSE_F_PPSONSECOND)
754 #define TRIMBLETSIP_FLAGS	    (TRIMBLETAIP_FLAGS)
755 
756 #define TRIMBLETAIP_POLL	    poll_dpoll
757 #define TRIMBLETSIP_POLL	    poll_dpoll
758 
759 #define TRIMBLETAIP_INIT	    trimbletaip_init
760 #define TRIMBLETSIP_INIT	    trimbletsip_init
761 
762 #define TRIMBLETAIP_EVENT	    trimbletaip_event
763 
764 #define TRIMBLETSIP_EVENT	    trimbletsip_event
765 #define TRIMBLETSIP_MESSAGE	    trimbletsip_message
766 
767 #define TRIMBLETAIP_END		    0
768 #define TRIMBLETSIP_END		    trimbletsip_end
769 
770 #define TRIMBLETAIP_DATA	    ((void *)(&trimbletaip_pollinfo))
771 #define TRIMBLETSIP_DATA	    ((void *)(&trimbletsip_pollinfo))
772 
773 #define TRIMBLETAIP_ID		    GPS_ID
774 #define TRIMBLETSIP_ID		    GPS_ID
775 
776 #define TRIMBLETAIP_FORMAT	    "Trimble TAIP"
777 #define TRIMBLETSIP_FORMAT	    "Trimble TSIP"
778 
779 #define TRIMBLETAIP_ROOTDELAY        0x0
780 #define TRIMBLETSIP_ROOTDELAY        0x0
781 
782 #define TRIMBLETAIP_BASEDELAY        0.0
783 #define TRIMBLETSIP_BASEDELAY        0.020	/* GPS time message latency */
784 
785 #define TRIMBLETAIP_DESCRIPTION      "Trimble GPS (TAIP) receiver"
786 #define TRIMBLETSIP_DESCRIPTION      "Trimble GPS (TSIP) receiver"
787 
788 #define TRIMBLETAIP_MAXUNSYNC        0
789 #define TRIMBLETSIP_MAXUNSYNC        0
790 
791 #define TRIMBLETAIP_EOL		    '<'
792 
793 /*
794  * RadioCode Clocks RCC 800 receiver
795  */
796 #define RCC_POLLRATE   0       /* only true direct polling */
797 #define RCC_POLLCMD    "\r"
798 #define RCC_CMDSIZE    1
799 
800 static poll_info_t rcc8000_pollinfo = { RCC_POLLRATE, RCC_POLLCMD, RCC_CMDSIZE };
801 #define RCC8000_FLAGS		0
802 #define RCC8000_POLL            poll_dpoll
803 #define RCC8000_INIT            poll_init
804 #define RCC8000_END             0
805 #define RCC8000_DATA            ((void *)(&rcc8000_pollinfo))
806 #define RCC8000_ROOTDELAY       0.0
807 #define RCC8000_BASEDELAY       0.0
808 #define RCC8000_ID              "MSF"
809 #define RCC8000_DESCRIPTION     "RCC 8000 MSF Receiver"
810 #define RCC8000_FORMAT          "Radiocode RCC8000"
811 #define RCC8000_MAXUNSYNC       (60*60) /* should be ok for an hour */
812 #define RCC8000_SPEED		(B2400)
813 #define RCC8000_CFLAG           (CS8|CREAD|CLOCAL)
814 #define RCC8000_IFLAG           (IGNBRK|IGNPAR)
815 #define RCC8000_OFLAG           0
816 #define RCC8000_LFLAG           0
817 #define RCC8000_SAMPLES         5
818 #define RCC8000_KEEP	        3
819 
820 /*
821  * Hopf Radio clock 6021 Format
822  *
823  */
824 #define HOPF6021_ROOTDELAY	0.0
825 #define HOPF6021_BASEDELAY	0.0
826 #define HOPF6021_DESCRIPTION	"HOPF 6021"
827 #define HOPF6021_FORMAT         "hopf Funkuhr 6021"
828 #define HOPF6021_MAXUNSYNC	(60*60)  /* should be ok for an hour */
829 #define HOPF6021_SPEED         (B9600)
830 #define HOPF6021_CFLAG          (CS8|CREAD|CLOCAL)
831 #define HOPF6021_IFLAG		(IGNBRK|ISTRIP)
832 #define HOPF6021_OFLAG		0
833 #define HOPF6021_LFLAG		0
834 #define HOPF6021_FLAGS          0
835 #define HOPF6021_SAMPLES        5
836 #define HOPF6021_KEEP	        3
837 
838 /*
839  * Diem's Computime Radio Clock Receiver
840  */
841 #define COMPUTIME_FLAGS       0
842 #define COMPUTIME_ROOTDELAY   0.0
843 #define COMPUTIME_BASEDELAY   0.0
844 #define COMPUTIME_ID          DCF_ID
845 #define COMPUTIME_DESCRIPTION "Diem's Computime receiver"
846 #define COMPUTIME_FORMAT      "Diem's Computime Radio Clock"
847 #define COMPUTIME_TYPE        DCF_TYPE
848 #define COMPUTIME_MAXUNSYNC   (60*60)       /* only trust clock for 1 hour */
849 #define COMPUTIME_SPEED       (B9600)
850 #define COMPUTIME_CFLAG       (CSTOPB|CS7|CREAD|CLOCAL)
851 #define COMPUTIME_IFLAG       (IGNBRK|IGNPAR|ISTRIP)
852 #define COMPUTIME_OFLAG       0
853 #define COMPUTIME_LFLAG       0
854 #define COMPUTIME_SAMPLES     5
855 #define COMPUTIME_KEEP        3
856 
857 /*
858  * Varitext Radio Clock Receiver
859  */
860 #define VARITEXT_FLAGS       0
861 #define VARITEXT_ROOTDELAY   0.0
862 #define VARITEXT_BASEDELAY   0.0
863 #define VARITEXT_ID          "MSF"
864 #define VARITEXT_DESCRIPTION "Varitext receiver"
865 #define VARITEXT_FORMAT      "Varitext Radio Clock"
866 #define VARITEXT_TYPE        DCF_TYPE
867 #define VARITEXT_MAXUNSYNC   (60*60)       /* only trust clock for 1 hour */
868 #define VARITEXT_SPEED       (B9600)
869 #define VARITEXT_CFLAG       (CS7|CREAD|CLOCAL|PARENB|PARODD)
870 #define VARITEXT_IFLAG       (IGNPAR|IGNBRK|INPCK) /*|ISTRIP)*/
871 #define VARITEXT_OFLAG       0
872 #define VARITEXT_LFLAG       0
873 #define VARITEXT_SAMPLES     32
874 #define VARITEXT_KEEP        20
875 
876 /*
877  * SEL240x Satellite Sychronized Clock
878  */
879 #define SEL240X_POLLRATE	0 /* only true direct polling */
880 #define SEL240X_POLLCMD		"BUB8"
881 #define SEL240X_CMDSIZE		4
882 
883 static poll_info_t sel240x_pollinfo = { SEL240X_POLLRATE,
884 	                                SEL240X_POLLCMD,
885 					SEL240X_CMDSIZE };
886 #define SEL240X_FLAGS		(PARSE_F_PPSONSECOND)
887 #define SEL240X_POLL		poll_dpoll
888 #define SEL240X_INIT		poll_init
889 #define SEL240X_END		0
890 #define SEL240X_DATA            ((void *)(&sel240x_pollinfo))
891 #define SEL240X_ROOTDELAY	0.0
892 #define SEL240X_BASEDELAY	0.0
893 #define SEL240X_ID		GPS_ID
894 #define SEL240X_DESCRIPTION	"SEL240x Satellite Synchronized Clock"
895 #define SEL240X_FORMAT		"SEL B8"
896 #define SEL240X_MAXUNSYNC	60*60*12 /* only trust clock for 12 hours */
897 #define SEL240X_SPEED		(B9600)
898 #define SEL240X_CFLAG		(CS8|CREAD|CLOCAL)
899 #define SEL240X_IFLAG		(IGNBRK|IGNPAR)
900 #define SEL240X_OFLAG		(0)
901 #define SEL240X_LFLAG		(0)
902 #define SEL240X_SAMPLES		5
903 #define SEL240X_KEEP		3
904 
905 static struct parse_clockinfo
906 {
907 	u_long  cl_flags;		/* operation flags (PPS interpretation, trust handling) */
908   void  (*cl_poll)    (struct parseunit *);			/* active poll routine */
909   int   (*cl_init)    (struct parseunit *);			/* active poll init routine */
910   void  (*cl_event)   (struct parseunit *, int);		/* special event handling (e.g. reset clock) */
911   void  (*cl_end)     (struct parseunit *);			/* active poll end routine */
912   void  (*cl_message) (struct parseunit *, parsetime_t *);	/* process a lower layer message */
913 	void   *cl_data;		/* local data area for "poll" mechanism */
914 	double    cl_rootdelay;		/* rootdelay */
915 	double    cl_basedelay;		/* current offset by which the RS232
916 				time code is delayed from the actual time */
917 	const char *cl_id;		/* ID code */
918 	const char *cl_description;		/* device name */
919 	const char *cl_format;		/* fixed format */
920 	u_char  cl_type;		/* clock type (ntp control) */
921 	u_long  cl_maxunsync;		/* time to trust oscillator after losing synch */
922 	u_long  cl_speed;		/* terminal input & output baudrate */
923 	u_long  cl_cflag;             /* terminal control flags */
924 	u_long  cl_iflag;             /* terminal input flags */
925 	u_long  cl_oflag;             /* terminal output flags */
926 	u_long  cl_lflag;             /* terminal local flags */
927 	u_long  cl_samples;	      /* samples for median filter */
928 	u_long  cl_keep;              /* samples for median filter to keep */
929 } parse_clockinfo[] =
930 {
931 	{				/* mode 0 */
932 		MBG_FLAGS,
933 		NO_POLL,
934 		NO_INIT,
935 		NO_EVENT,
936 		NO_END,
937 		NO_MESSAGE,
938 		NO_LCLDATA,
939 		DCFPZF535_ROOTDELAY,
940 		DCFPZF535_BASEDELAY,
941 		DCF_P_ID,
942 		DCFPZF535_DESCRIPTION,
943 		DCFPZF535_FORMAT,
944 		DCF_TYPE,
945 		DCFPZF535_MAXUNSYNC,
946 		DCFPZF535_SPEED,
947 		DCFPZF535_CFLAG,
948 		DCFPZF535_IFLAG,
949 		DCFPZF535_OFLAG,
950 		DCFPZF535_LFLAG,
951 		DCFPZF535_SAMPLES,
952 		DCFPZF535_KEEP
953 	},
954 	{				/* mode 1 */
955 		MBG_FLAGS,
956 		NO_POLL,
957 		NO_INIT,
958 		NO_EVENT,
959 		NO_END,
960 		NO_MESSAGE,
961 		NO_LCLDATA,
962 		DCFPZF535OCXO_ROOTDELAY,
963 		DCFPZF535OCXO_BASEDELAY,
964 		DCF_P_ID,
965 		DCFPZF535OCXO_DESCRIPTION,
966 		DCFPZF535OCXO_FORMAT,
967 		DCF_TYPE,
968 		DCFPZF535OCXO_MAXUNSYNC,
969 		DCFPZF535OCXO_SPEED,
970 		DCFPZF535OCXO_CFLAG,
971 		DCFPZF535OCXO_IFLAG,
972 		DCFPZF535OCXO_OFLAG,
973 		DCFPZF535OCXO_LFLAG,
974 		DCFPZF535OCXO_SAMPLES,
975 		DCFPZF535OCXO_KEEP
976 	},
977 	{				/* mode 2 */
978 		MBG_FLAGS,
979 		NO_POLL,
980 		NO_INIT,
981 		NO_EVENT,
982 		NO_END,
983 		NO_MESSAGE,
984 		NO_LCLDATA,
985 		DCFUA31_ROOTDELAY,
986 		DCFUA31_BASEDELAY,
987 		DCF_A_ID,
988 		DCFUA31_DESCRIPTION,
989 		DCFUA31_FORMAT,
990 		DCF_TYPE,
991 		DCFUA31_MAXUNSYNC,
992 		DCFUA31_SPEED,
993 		DCFUA31_CFLAG,
994 		DCFUA31_IFLAG,
995 		DCFUA31_OFLAG,
996 		DCFUA31_LFLAG,
997 		DCFUA31_SAMPLES,
998 		DCFUA31_KEEP
999 	},
1000 	{				/* mode 3 */
1001 		MBG_FLAGS,
1002 		NO_POLL,
1003 		NO_INIT,
1004 		NO_EVENT,
1005 		NO_END,
1006 		NO_MESSAGE,
1007 		NO_LCLDATA,
1008 		DCF7000_ROOTDELAY,
1009 		DCF7000_BASEDELAY,
1010 		DCF_A_ID,
1011 		DCF7000_DESCRIPTION,
1012 		DCF7000_FORMAT,
1013 		DCF_TYPE,
1014 		DCF7000_MAXUNSYNC,
1015 		DCF7000_SPEED,
1016 		DCF7000_CFLAG,
1017 		DCF7000_IFLAG,
1018 		DCF7000_OFLAG,
1019 		DCF7000_LFLAG,
1020 		DCF7000_SAMPLES,
1021 		DCF7000_KEEP
1022 	},
1023 	{				/* mode 4 */
1024 		NO_CL_FLAGS,
1025 		WSDCF_POLL,
1026 		WSDCF_INIT,
1027 		NO_EVENT,
1028 		WSDCF_END,
1029 		NO_MESSAGE,
1030 		WSDCF_DATA,
1031 		WSDCF_ROOTDELAY,
1032 		WSDCF_BASEDELAY,
1033 		DCF_A_ID,
1034 		WSDCF_DESCRIPTION,
1035 		WSDCF_FORMAT,
1036 		DCF_TYPE,
1037 		WSDCF_MAXUNSYNC,
1038 		WSDCF_SPEED,
1039 		WSDCF_CFLAG,
1040 		WSDCF_IFLAG,
1041 		WSDCF_OFLAG,
1042 		WSDCF_LFLAG,
1043 		WSDCF_SAMPLES,
1044 		WSDCF_KEEP
1045 	},
1046 	{				/* mode 5 */
1047 		RAWDCF_FLAGS,
1048 		NO_POLL,
1049 		RAWDCF_INIT,
1050 		NO_EVENT,
1051 		NO_END,
1052 		NO_MESSAGE,
1053 		NO_LCLDATA,
1054 		RAWDCF_ROOTDELAY,
1055 		CONRAD_BASEDELAY,
1056 		DCF_A_ID,
1057 		CONRAD_DESCRIPTION,
1058 		RAWDCF_FORMAT,
1059 		DCF_TYPE,
1060 		RAWDCF_MAXUNSYNC,
1061 		RAWDCF_SPEED,
1062 		RAWDCF_CFLAG,
1063 		RAWDCF_IFLAG,
1064 		RAWDCF_OFLAG,
1065 		RAWDCF_LFLAG,
1066 		RAWDCF_SAMPLES,
1067 		RAWDCF_KEEP
1068 	},
1069 	{				/* mode 6 */
1070 		RAWDCF_FLAGS,
1071 		NO_POLL,
1072 		RAWDCF_INIT,
1073 		NO_EVENT,
1074 		NO_END,
1075 		NO_MESSAGE,
1076 		NO_LCLDATA,
1077 		RAWDCF_ROOTDELAY,
1078 		TIMEBRICK_BASEDELAY,
1079 		DCF_A_ID,
1080 		TIMEBRICK_DESCRIPTION,
1081 		RAWDCF_FORMAT,
1082 		DCF_TYPE,
1083 		RAWDCF_MAXUNSYNC,
1084 		RAWDCF_SPEED,
1085 		RAWDCF_CFLAG,
1086 		RAWDCF_IFLAG,
1087 		RAWDCF_OFLAG,
1088 		RAWDCF_LFLAG,
1089 		RAWDCF_SAMPLES,
1090 		RAWDCF_KEEP
1091 	},
1092 	{				/* mode 7 */
1093 		MBG_FLAGS,
1094 		GPS16X_POLL,
1095 		GPS16X_INIT,
1096 		NO_EVENT,
1097 		GPS16X_END,
1098 		GPS16X_MESSAGE,
1099 		GPS16X_DATA,
1100 		GPS16X_ROOTDELAY,
1101 		GPS16X_BASEDELAY,
1102 		GPS16X_ID,
1103 		GPS16X_DESCRIPTION,
1104 		GPS16X_FORMAT,
1105 		GPS_TYPE,
1106 		GPS16X_MAXUNSYNC,
1107 		GPS16X_SPEED,
1108 		GPS16X_CFLAG,
1109 		GPS16X_IFLAG,
1110 		GPS16X_OFLAG,
1111 		GPS16X_LFLAG,
1112 		GPS16X_SAMPLES,
1113 		GPS16X_KEEP
1114 	},
1115 	{				/* mode 8 */
1116 		RAWDCF_FLAGS,
1117 		NO_POLL,
1118 		NO_INIT,
1119 		NO_EVENT,
1120 		NO_END,
1121 		NO_MESSAGE,
1122 		NO_LCLDATA,
1123 		RAWDCF_ROOTDELAY,
1124 		IGELCLOCK_BASEDELAY,
1125 		DCF_A_ID,
1126 		IGELCLOCK_DESCRIPTION,
1127 		RAWDCF_FORMAT,
1128 		DCF_TYPE,
1129 		RAWDCF_MAXUNSYNC,
1130 		IGELCLOCK_SPEED,
1131 		IGELCLOCK_CFLAG,
1132 		RAWDCF_IFLAG,
1133 		RAWDCF_OFLAG,
1134 		RAWDCF_LFLAG,
1135 		RAWDCF_SAMPLES,
1136 		RAWDCF_KEEP
1137 	},
1138 	{				/* mode 9 */
1139 		TRIMBLETAIP_FLAGS,
1140 #if TRIM_POLLRATE		/* DHD940515: Allow user config */
1141 		NO_POLL,
1142 #else
1143 		TRIMBLETAIP_POLL,
1144 #endif
1145 		TRIMBLETAIP_INIT,
1146 		TRIMBLETAIP_EVENT,
1147 		TRIMBLETAIP_END,
1148 		NO_MESSAGE,
1149 		TRIMBLETAIP_DATA,
1150 		TRIMBLETAIP_ROOTDELAY,
1151 		TRIMBLETAIP_BASEDELAY,
1152 		TRIMBLETAIP_ID,
1153 		TRIMBLETAIP_DESCRIPTION,
1154 		TRIMBLETAIP_FORMAT,
1155 		GPS_TYPE,
1156 		TRIMBLETAIP_MAXUNSYNC,
1157 		TRIMBLETAIP_SPEED,
1158 		TRIMBLETAIP_CFLAG,
1159 		TRIMBLETAIP_IFLAG,
1160 		TRIMBLETAIP_OFLAG,
1161 		TRIMBLETAIP_LFLAG,
1162 		TRIMBLETAIP_SAMPLES,
1163 		TRIMBLETAIP_KEEP
1164 	},
1165 	{				/* mode 10 */
1166 		TRIMBLETSIP_FLAGS,
1167 #if TRIM_POLLRATE		/* DHD940515: Allow user config */
1168 		NO_POLL,
1169 #else
1170 		TRIMBLETSIP_POLL,
1171 #endif
1172 		TRIMBLETSIP_INIT,
1173 		TRIMBLETSIP_EVENT,
1174 		TRIMBLETSIP_END,
1175 		TRIMBLETSIP_MESSAGE,
1176 		TRIMBLETSIP_DATA,
1177 		TRIMBLETSIP_ROOTDELAY,
1178 		TRIMBLETSIP_BASEDELAY,
1179 		TRIMBLETSIP_ID,
1180 		TRIMBLETSIP_DESCRIPTION,
1181 		TRIMBLETSIP_FORMAT,
1182 		GPS_TYPE,
1183 		TRIMBLETSIP_MAXUNSYNC,
1184 		TRIMBLETSIP_SPEED,
1185 		TRIMBLETSIP_CFLAG,
1186 		TRIMBLETSIP_IFLAG,
1187 		TRIMBLETSIP_OFLAG,
1188 		TRIMBLETSIP_LFLAG,
1189 		TRIMBLETSIP_SAMPLES,
1190 		TRIMBLETSIP_KEEP
1191 	},
1192 	{                             /* mode 11 */
1193 		NO_CL_FLAGS,
1194 		RCC8000_POLL,
1195 		RCC8000_INIT,
1196 		NO_EVENT,
1197 		RCC8000_END,
1198 		NO_MESSAGE,
1199 		RCC8000_DATA,
1200 		RCC8000_ROOTDELAY,
1201 		RCC8000_BASEDELAY,
1202 		RCC8000_ID,
1203 		RCC8000_DESCRIPTION,
1204 		RCC8000_FORMAT,
1205 		DCF_TYPE,
1206 		RCC8000_MAXUNSYNC,
1207 		RCC8000_SPEED,
1208 		RCC8000_CFLAG,
1209 		RCC8000_IFLAG,
1210 		RCC8000_OFLAG,
1211 		RCC8000_LFLAG,
1212 		RCC8000_SAMPLES,
1213 		RCC8000_KEEP
1214 	},
1215 	{                             /* mode 12 */
1216 		HOPF6021_FLAGS,
1217 		NO_POLL,
1218 		NO_INIT,
1219 		NO_EVENT,
1220 		NO_END,
1221 		NO_MESSAGE,
1222 		NO_LCLDATA,
1223 		HOPF6021_ROOTDELAY,
1224 		HOPF6021_BASEDELAY,
1225 		DCF_ID,
1226 		HOPF6021_DESCRIPTION,
1227 		HOPF6021_FORMAT,
1228 		DCF_TYPE,
1229 		HOPF6021_MAXUNSYNC,
1230 		HOPF6021_SPEED,
1231 		HOPF6021_CFLAG,
1232 		HOPF6021_IFLAG,
1233 		HOPF6021_OFLAG,
1234 		HOPF6021_LFLAG,
1235 		HOPF6021_SAMPLES,
1236 		HOPF6021_KEEP
1237 	},
1238 	{                            /* mode 13 */
1239 		COMPUTIME_FLAGS,
1240 		NO_POLL,
1241 		NO_INIT,
1242 		NO_EVENT,
1243 		NO_END,
1244 		NO_MESSAGE,
1245 		NO_LCLDATA,
1246 		COMPUTIME_ROOTDELAY,
1247 		COMPUTIME_BASEDELAY,
1248 		COMPUTIME_ID,
1249 		COMPUTIME_DESCRIPTION,
1250 		COMPUTIME_FORMAT,
1251 		COMPUTIME_TYPE,
1252 		COMPUTIME_MAXUNSYNC,
1253 		COMPUTIME_SPEED,
1254 		COMPUTIME_CFLAG,
1255 		COMPUTIME_IFLAG,
1256 		COMPUTIME_OFLAG,
1257 		COMPUTIME_LFLAG,
1258 		COMPUTIME_SAMPLES,
1259 		COMPUTIME_KEEP
1260 	},
1261 	{				/* mode 14 */
1262 		RAWDCF_FLAGS,
1263 		NO_POLL,
1264 		RAWDCFDTRSET_INIT,
1265 		NO_EVENT,
1266 		NO_END,
1267 		NO_MESSAGE,
1268 		NO_LCLDATA,
1269 		RAWDCF_ROOTDELAY,
1270 		RAWDCF_BASEDELAY,
1271 		DCF_A_ID,
1272 		RAWDCFDTRSET_DESCRIPTION,
1273 		RAWDCF_FORMAT,
1274 		DCF_TYPE,
1275 		RAWDCF_MAXUNSYNC,
1276 		RAWDCF_SPEED,
1277 		RAWDCF_CFLAG,
1278 		RAWDCF_IFLAG,
1279 		RAWDCF_OFLAG,
1280 		RAWDCF_LFLAG,
1281 		RAWDCF_SAMPLES,
1282 		RAWDCF_KEEP
1283 	},
1284 	{				/* mode 15 */
1285 		0,				/* operation flags (io modes) */
1286   		NO_POLL,			/* active poll routine */
1287 		NO_INIT,			/* active poll init routine */
1288   		NO_EVENT,		        /* special event handling (e.g. reset clock) */
1289   		NO_END,				/* active poll end routine */
1290   		NO_MESSAGE,			/* process a lower layer message */
1291 		NO_LCLDATA,			/* local data area for "poll" mechanism */
1292 		0,				/* rootdelay */
1293 		11.0 /* bits */ / 9600,		/* current offset by which the RS232
1294 				           	time code is delayed from the actual time */
1295 		DCF_ID,				/* ID code */
1296 		"WHARTON 400A Series clock",	/* device name */
1297 		"WHARTON 400A Series clock Output Format 1",	/* fixed format */
1298 			/* Must match a format-name in a libparse/clk_xxx.c file */
1299 		DCF_TYPE,			/* clock type (ntp control) */
1300 		(1*60*60),		        /* time to trust oscillator after losing synch */
1301 		B9600,				/* terminal input & output baudrate */
1302 		(CS8|CREAD|PARENB|CLOCAL|HUPCL),/* terminal control flags */
1303 		0,				/* terminal input flags */
1304 		0,				/* terminal output flags */
1305 		0,				/* terminal local flags */
1306 		5,				/* samples for median filter */
1307 		3,				/* samples for median filter to keep */
1308 	},
1309 	{				/* mode 16 - RAWDCF RTS set, DTR clr */
1310 		RAWDCF_FLAGS,
1311 		NO_POLL,
1312 		RAWDCFDTRCLRRTSSET_INIT,
1313 		NO_EVENT,
1314 		NO_END,
1315 		NO_MESSAGE,
1316 		NO_LCLDATA,
1317 		RAWDCF_ROOTDELAY,
1318 		RAWDCF_BASEDELAY,
1319 		DCF_A_ID,
1320 		RAWDCFDTRCLRRTSSET_DESCRIPTION,
1321 		RAWDCF_FORMAT,
1322 		DCF_TYPE,
1323 		RAWDCF_MAXUNSYNC,
1324 		RAWDCF_SPEED,
1325 		RAWDCF_CFLAG,
1326 		RAWDCF_IFLAG,
1327 		RAWDCF_OFLAG,
1328 		RAWDCF_LFLAG,
1329 		RAWDCF_SAMPLES,
1330 		RAWDCF_KEEP
1331 	},
1332         {                            /* mode 17 */
1333                 VARITEXT_FLAGS,
1334                 NO_POLL,
1335                 NO_INIT,
1336                 NO_EVENT,
1337                 NO_END,
1338                 NO_MESSAGE,
1339                 NO_LCLDATA,
1340                 VARITEXT_ROOTDELAY,
1341                 VARITEXT_BASEDELAY,
1342                 VARITEXT_ID,
1343                 VARITEXT_DESCRIPTION,
1344                 VARITEXT_FORMAT,
1345                 VARITEXT_TYPE,
1346                 VARITEXT_MAXUNSYNC,
1347                 VARITEXT_SPEED,
1348                 VARITEXT_CFLAG,
1349                 VARITEXT_IFLAG,
1350                 VARITEXT_OFLAG,
1351                 VARITEXT_LFLAG,
1352                 VARITEXT_SAMPLES,
1353                 VARITEXT_KEEP
1354         },
1355 	{				/* mode 18 */
1356 		MBG_FLAGS,
1357 		NO_POLL,
1358 		NO_INIT,
1359 		NO_EVENT,
1360 		GPS16X_END,
1361 		GPS16X_MESSAGE,
1362 		GPS16X_DATA,
1363 		GPS16X_ROOTDELAY,
1364 		GPS16X_BASEDELAY,
1365 		GPS16X_ID,
1366 		GPS16X_DESCRIPTION,
1367 		GPS16X_FORMAT,
1368 		GPS_TYPE,
1369 		GPS16X_MAXUNSYNC,
1370 		GPS16X_SPEED,
1371 		GPS16X_CFLAG,
1372 		GPS16X_IFLAG,
1373 		GPS16X_OFLAG,
1374 		GPS16X_LFLAG,
1375 		GPS16X_SAMPLES,
1376 		GPS16X_KEEP
1377 	},
1378 	{				/* mode 19 */
1379 		RAWDCF_FLAGS,
1380 		NO_POLL,
1381 		RAWDCF_INIT,
1382 		NO_EVENT,
1383 		NO_END,
1384 		NO_MESSAGE,
1385 		NO_LCLDATA,
1386 		RAWDCF_ROOTDELAY,
1387 		GUDE_EMC_USB_V20_BASEDELAY,
1388 		DCF_A_ID,
1389 		GUDE_EMC_USB_V20_DESCRIPTION,
1390 		RAWDCF_FORMAT,
1391 		DCF_TYPE,
1392 		RAWDCF_MAXUNSYNC,
1393 		GUDE_EMC_USB_V20_SPEED,
1394 		RAWDCF_CFLAG,
1395 		RAWDCF_IFLAG,
1396 		RAWDCF_OFLAG,
1397 		RAWDCF_LFLAG,
1398 		RAWDCF_SAMPLES,
1399 		RAWDCF_KEEP
1400 	},
1401 	{				/* mode 20, like mode 14 but driven by 75 baud */
1402 		RAWDCF_FLAGS,
1403 		NO_POLL,
1404 		RAWDCFDTRSET_INIT,
1405 		NO_EVENT,
1406 		NO_END,
1407 		NO_MESSAGE,
1408 		NO_LCLDATA,
1409 		RAWDCF_ROOTDELAY,
1410 		RAWDCF_BASEDELAY,
1411 		DCF_A_ID,
1412 		RAWDCFDTRSET75_DESCRIPTION,
1413 		RAWDCF_FORMAT,
1414 		DCF_TYPE,
1415 		RAWDCF_MAXUNSYNC,
1416 		B75,
1417 		RAWDCF_CFLAG,
1418 		RAWDCF_IFLAG,
1419 		RAWDCF_OFLAG,
1420 		RAWDCF_LFLAG,
1421 		RAWDCF_SAMPLES,
1422 		RAWDCF_KEEP
1423 	},
1424 	{				/* mode 21, like mode 16 but driven by 75 baud
1425 					 - RAWDCF RTS set, DTR clr */
1426 		RAWDCF_FLAGS,
1427 		NO_POLL,
1428 		RAWDCFDTRCLRRTSSET_INIT,
1429 		NO_EVENT,
1430 		NO_END,
1431 		NO_MESSAGE,
1432 		NO_LCLDATA,
1433 		RAWDCF_ROOTDELAY,
1434 		RAWDCF_BASEDELAY,
1435 		DCF_A_ID,
1436 		RAWDCFDTRCLRRTSSET75_DESCRIPTION,
1437 		RAWDCF_FORMAT,
1438 		DCF_TYPE,
1439 		RAWDCF_MAXUNSYNC,
1440 		B75,
1441 		RAWDCF_CFLAG,
1442 		RAWDCF_IFLAG,
1443 		RAWDCF_OFLAG,
1444 		RAWDCF_LFLAG,
1445 		RAWDCF_SAMPLES,
1446 		RAWDCF_KEEP
1447 	},
1448 	{				/* mode 22 - like 2 with POWERUP trust */
1449 		MBG_FLAGS | PARSE_F_POWERUPTRUST,
1450 		NO_POLL,
1451 		NO_INIT,
1452 		NO_EVENT,
1453 		NO_END,
1454 		NO_MESSAGE,
1455 		NO_LCLDATA,
1456 		DCFUA31_ROOTDELAY,
1457 		DCFUA31_BASEDELAY,
1458 		DCF_A_ID,
1459 		DCFUA31_DESCRIPTION,
1460 		DCFUA31_FORMAT,
1461 		DCF_TYPE,
1462 		DCFUA31_MAXUNSYNC,
1463 		DCFUA31_SPEED,
1464 		DCFUA31_CFLAG,
1465 		DCFUA31_IFLAG,
1466 		DCFUA31_OFLAG,
1467 		DCFUA31_LFLAG,
1468 		DCFUA31_SAMPLES,
1469 		DCFUA31_KEEP
1470 	},
1471 	{				/* mode 23 - like 7 with POWERUP trust */
1472 		MBG_FLAGS | PARSE_F_POWERUPTRUST,
1473 		GPS16X_POLL,
1474 		GPS16X_INIT,
1475 		NO_EVENT,
1476 		GPS16X_END,
1477 		GPS16X_MESSAGE,
1478 		GPS16X_DATA,
1479 		GPS16X_ROOTDELAY,
1480 		GPS16X_BASEDELAY,
1481 		GPS16X_ID,
1482 		GPS16X_DESCRIPTION,
1483 		GPS16X_FORMAT,
1484 		GPS_TYPE,
1485 		GPS16X_MAXUNSYNC,
1486 		GPS16X_SPEED,
1487 		GPS16X_CFLAG,
1488 		GPS16X_IFLAG,
1489 		GPS16X_OFLAG,
1490 		GPS16X_LFLAG,
1491 		GPS16X_SAMPLES,
1492 		GPS16X_KEEP
1493 	},
1494 	{				/* mode 24 */
1495 		SEL240X_FLAGS,
1496 		SEL240X_POLL,
1497 		SEL240X_INIT,
1498 		NO_EVENT,
1499 		SEL240X_END,
1500 		NO_MESSAGE,
1501 		SEL240X_DATA,
1502 		SEL240X_ROOTDELAY,
1503 		SEL240X_BASEDELAY,
1504 		SEL240X_ID,
1505 		SEL240X_DESCRIPTION,
1506 		SEL240X_FORMAT,
1507 		GPS_TYPE,
1508 		SEL240X_MAXUNSYNC,
1509 		SEL240X_SPEED,
1510 		SEL240X_CFLAG,
1511 		SEL240X_IFLAG,
1512 		SEL240X_OFLAG,
1513 		SEL240X_LFLAG,
1514 		SEL240X_SAMPLES,
1515 		SEL240X_KEEP
1516 	},
1517 };
1518 
1519 static int ncltypes = sizeof(parse_clockinfo) / sizeof(struct parse_clockinfo);
1520 
1521 #define CLK_REALTYPE(x) ((int)(((x)->ttl) & 0x7F))
1522 #define CLK_TYPE(x)	((CLK_REALTYPE(x) >= ncltypes) ? ~0 : CLK_REALTYPE(x))
1523 #define CLK_UNIT(x)	((int)REFCLOCKUNIT(&(x)->srcadr))
1524 #define CLK_PPS(x)	(((x)->ttl) & 0x80)
1525 
1526 /*
1527  * Other constant stuff
1528  */
1529 #define	PARSEHSREFID	0x7f7f08ff	/* 127.127.8.255 refid for hi strata */
1530 
1531 #define PARSESTATISTICS   (60*60)	        /* output state statistics every hour */
1532 
1533 static int notice = 0;
1534 
1535 #define PARSE_STATETIME(parse, i) ((parse->generic->currentstatus == i) ? parse->statetime[i] + current_time - parse->lastchange : parse->statetime[i])
1536 
1537 static void parse_event   (struct parseunit *, int);
1538 static void parse_process (struct parseunit *, parsetime_t *);
1539 static void clear_err     (struct parseunit *, u_long);
1540 static int  list_err      (struct parseunit *, u_long);
1541 static char * l_mktime    (u_long);
1542 
1543 /**===========================================================================
1544  ** implementation error message regression module
1545  **/
1546 static void
1547 clear_err(
1548 	struct parseunit *parse,
1549 	u_long            lstate
1550 	)
1551 {
1552 	if (lstate == ERR_ALL)
1553 	{
1554 		size_t i;
1555 
1556 		for (i = 0; i < ERR_CNT; i++)
1557 		{
1558 			parse->errors[i].err_stage   = err_tbl[i];
1559 			parse->errors[i].err_cnt     = 0;
1560 			parse->errors[i].err_last    = 0;
1561 			parse->errors[i].err_started = 0;
1562 			parse->errors[i].err_suppressed = 0;
1563 		}
1564 	}
1565 	else
1566 	{
1567 		parse->errors[lstate].err_stage   = err_tbl[lstate];
1568 		parse->errors[lstate].err_cnt     = 0;
1569 		parse->errors[lstate].err_last    = 0;
1570 		parse->errors[lstate].err_started = 0;
1571 		parse->errors[lstate].err_suppressed = 0;
1572 	}
1573 }
1574 
1575 static int
1576 list_err(
1577 	struct parseunit *parse,
1578 	u_long            lstate
1579 	)
1580 {
1581 	int do_it;
1582 	struct errorinfo *err = &parse->errors[lstate];
1583 
1584 	if (err->err_started == 0)
1585 	{
1586 		err->err_started = current_time;
1587 	}
1588 
1589 	do_it = (current_time - err->err_last) >= err->err_stage->err_delay;
1590 
1591 	if (do_it)
1592 	    err->err_cnt++;
1593 
1594 	if (err->err_stage->err_count &&
1595 	    (err->err_cnt >= err->err_stage->err_count))
1596 	{
1597 		err->err_stage++;
1598 		err->err_cnt = 0;
1599 	}
1600 
1601 	if (!err->err_cnt && do_it)
1602 	    msyslog(LOG_INFO, "PARSE receiver #%d: interval for following error message class is at least %s",
1603 		    CLK_UNIT(parse->peer), l_mktime(err->err_stage->err_delay));
1604 
1605 	if (!do_it)
1606 	    err->err_suppressed++;
1607 	else
1608 	    err->err_last = current_time;
1609 
1610 	if (do_it && err->err_suppressed)
1611 	{
1612 		msyslog(LOG_INFO, "PARSE receiver #%d: %ld message%s suppressed, error condition class persists for %s",
1613 			CLK_UNIT(parse->peer), err->err_suppressed, (err->err_suppressed == 1) ? " was" : "s where",
1614 			l_mktime(current_time - err->err_started));
1615 		err->err_suppressed = 0;
1616 	}
1617 
1618 	return do_it;
1619 }
1620 
1621 /*--------------------------------------------------
1622  * mkreadable - make a printable ascii string (without
1623  * embedded quotes so that the ntpq protocol isn't
1624  * fooled
1625  */
1626 #ifndef isprint
1627 #define isprint(_X_) (((_X_) > 0x1F) && ((_X_) < 0x7F))
1628 #endif
1629 
1630 static char *
1631 mkreadable(
1632 	char  *buffer,
1633 	long  blen,
1634 	const char  *src,
1635 	u_long  srclen,
1636 	int hex
1637 	)
1638 {
1639 	static const char ellipsis[] = "...";
1640 	char *b    = buffer;
1641 	char *endb = NULL;
1642 
1643 	if (blen < 4)
1644 		return NULL;		/* don't bother with mini buffers */
1645 
1646 	endb = buffer + blen - sizeof(ellipsis);
1647 
1648 	blen--;			/* account for '\0' */
1649 
1650 	while (blen && srclen--)
1651 	{
1652 		if (!hex &&             /* no binary only */
1653 		    (*src != '\\') &&   /* no plain \ */
1654 		    (*src != '"') &&    /* no " */
1655 		    isprint((unsigned char)*src))	/* only printables */
1656 		{			/* they are easy... */
1657 			*buffer++ = *src++;
1658 			blen--;
1659 		}
1660 		else
1661 		{
1662 			if (blen < 4)
1663 			{
1664 				while (blen--)
1665 				{
1666 					*buffer++ = '.';
1667 				}
1668 				*buffer = '\0';
1669 				return b;
1670 			}
1671 			else
1672 			{
1673 				if (*src == '\\')
1674 				{
1675 					memcpy(buffer, "\\\\", 2);
1676 					buffer += 2;
1677 					blen   -= 2;
1678 					src++;
1679 				}
1680 				else
1681 				{
1682 					snprintf(buffer, blen, "\\x%02x", *src++);
1683 					blen   -= 4;
1684 					buffer += 4;
1685 				}
1686 			}
1687 		}
1688 		if (srclen && !blen && endb) /* overflow - set last chars to ... */
1689 			memcpy(endb, ellipsis, sizeof(ellipsis));
1690 	}
1691 
1692 	*buffer = '\0';
1693 	return b;
1694 }
1695 
1696 
1697 /*--------------------------------------------------
1698  * mkascii - make a printable ascii string
1699  * assumes (unless defined better) 7-bit ASCII
1700  */
1701 static char *
1702 mkascii(
1703 	char  *buffer,
1704 	long  blen,
1705 	const char  *src,
1706 	u_long  srclen
1707 	)
1708 {
1709 	return mkreadable(buffer, blen, src, srclen, 0);
1710 }
1711 
1712 /**===========================================================================
1713  ** implementation of i/o handling methods
1714  ** (all STREAM, partial STREAM, user level)
1715  **/
1716 
1717 /*
1718  * define possible io handling methods
1719  */
1720 #ifdef STREAM
1721 static int  ppsclock_init   (struct parseunit *);
1722 static int  stream_init     (struct parseunit *);
1723 static void stream_end      (struct parseunit *);
1724 static int  stream_enable   (struct parseunit *);
1725 static int  stream_disable  (struct parseunit *);
1726 static int  stream_setcs    (struct parseunit *, parsectl_t *);
1727 static int  stream_getfmt   (struct parseunit *, parsectl_t *);
1728 static int  stream_setfmt   (struct parseunit *, parsectl_t *);
1729 static int  stream_timecode (struct parseunit *, parsectl_t *);
1730 static void stream_receive  (struct recvbuf *);
1731 #endif
1732 
1733 static int  local_init     (struct parseunit *);
1734 static void local_end      (struct parseunit *);
1735 static int  local_nop      (struct parseunit *);
1736 static int  local_setcs    (struct parseunit *, parsectl_t *);
1737 static int  local_getfmt   (struct parseunit *, parsectl_t *);
1738 static int  local_setfmt   (struct parseunit *, parsectl_t *);
1739 static int  local_timecode (struct parseunit *, parsectl_t *);
1740 static void local_receive  (struct recvbuf *);
1741 static int  local_input    (struct recvbuf *);
1742 
1743 static bind_t io_bindings[] =
1744 {
1745 #ifdef STREAM
1746 	{
1747 		"parse STREAM",
1748 		stream_init,
1749 		stream_end,
1750 		stream_setcs,
1751 		stream_disable,
1752 		stream_enable,
1753 		stream_getfmt,
1754 		stream_setfmt,
1755 		stream_timecode,
1756 		stream_receive,
1757 		0,
1758 	},
1759 	{
1760 		"ppsclock STREAM",
1761 		ppsclock_init,
1762 		local_end,
1763 		local_setcs,
1764 		local_nop,
1765 		local_nop,
1766 		local_getfmt,
1767 		local_setfmt,
1768 		local_timecode,
1769 		local_receive,
1770 		local_input,
1771 	},
1772 #endif
1773 	{
1774 		"normal",
1775 		local_init,
1776 		local_end,
1777 		local_setcs,
1778 		local_nop,
1779 		local_nop,
1780 		local_getfmt,
1781 		local_setfmt,
1782 		local_timecode,
1783 		local_receive,
1784 		local_input,
1785 	},
1786 	{
1787 		(char *)0,
1788 		NULL,
1789 		NULL,
1790 		NULL,
1791 		NULL,
1792 		NULL,
1793 		NULL,
1794 		NULL,
1795 		NULL,
1796 		NULL,
1797 		NULL,
1798 	}
1799 };
1800 
1801 #ifdef STREAM
1802 
1803 /*--------------------------------------------------
1804  * ppsclock STREAM init
1805  */
1806 static int
1807 ppsclock_init(
1808 	struct parseunit *parse
1809 	)
1810 {
1811         static char m1[] = "ppsclocd";
1812 	static char m2[] = "ppsclock";
1813 
1814 	/*
1815 	 * now push the parse streams module
1816 	 * it will ensure exclusive access to the device
1817 	 */
1818 	if (ioctl(parse->ppsfd, I_PUSH, (caddr_t)m1) == -1 &&
1819 	    ioctl(parse->ppsfd, I_PUSH, (caddr_t)m2) == -1)
1820 	{
1821 		if (errno != EINVAL)
1822 		{
1823 			msyslog(LOG_ERR, "PARSE receiver #%d: ppsclock_init: ioctl(fd, I_PUSH, \"ppsclock\"): %m",
1824 				CLK_UNIT(parse->peer));
1825 		}
1826 		return 0;
1827 	}
1828 	if (!local_init(parse))
1829 	{
1830 		(void)ioctl(parse->ppsfd, I_POP, (caddr_t)0);
1831 		return 0;
1832 	}
1833 
1834 	parse->flags |= PARSE_PPSCLOCK;
1835 	return 1;
1836 }
1837 
1838 /*--------------------------------------------------
1839  * parse STREAM init
1840  */
1841 static int
1842 stream_init(
1843 	struct parseunit *parse
1844 	)
1845 {
1846 	static char m1[] = "parse";
1847 	/*
1848 	 * now push the parse streams module
1849 	 * to test whether it is there (neat interface 8-( )
1850 	 */
1851 	if (ioctl(parse->generic->io.fd, I_PUSH, (caddr_t)m1) == -1)
1852 	{
1853 		if (errno != EINVAL) /* accept non-existence */
1854 		{
1855 			msyslog(LOG_ERR, "PARSE receiver #%d: stream_init: ioctl(fd, I_PUSH, \"parse\"): %m", CLK_UNIT(parse->peer));
1856 		}
1857 		return 0;
1858 	}
1859 	else
1860 	{
1861 		while(ioctl(parse->generic->io.fd, I_POP, (caddr_t)0) == 0)
1862 		    /* empty loop */;
1863 
1864 		/*
1865 		 * now push it a second time after we have removed all
1866 		 * module garbage
1867 		 */
1868 		if (ioctl(parse->generic->io.fd, I_PUSH, (caddr_t)m1) == -1)
1869 		{
1870 			msyslog(LOG_ERR, "PARSE receiver #%d: stream_init: ioctl(fd, I_PUSH, \"parse\"): %m", CLK_UNIT(parse->peer));
1871 			return 0;
1872 		}
1873 		else
1874 		{
1875 			return 1;
1876 		}
1877 	}
1878 }
1879 
1880 /*--------------------------------------------------
1881  * parse STREAM end
1882  */
1883 static void
1884 stream_end(
1885 	struct parseunit *parse
1886 	)
1887 {
1888 	while(ioctl(parse->generic->io.fd, I_POP, (caddr_t)0) == 0)
1889 	    /* empty loop */;
1890 }
1891 
1892 /*--------------------------------------------------
1893  * STREAM setcs
1894  */
1895 static int
1896 stream_setcs(
1897 	struct parseunit *parse,
1898 	parsectl_t  *tcl
1899 	)
1900 {
1901 	struct strioctl strioc;
1902 
1903 	strioc.ic_cmd     = PARSEIOC_SETCS;
1904 	strioc.ic_timout  = 0;
1905 	strioc.ic_dp      = (char *)tcl;
1906 	strioc.ic_len     = sizeof (*tcl);
1907 
1908 	if (ioctl(parse->generic->io.fd, I_STR, (caddr_t)&strioc) == -1)
1909 	{
1910 		msyslog(LOG_ERR, "PARSE receiver #%d: stream_setcs: ioctl(fd, I_STR, PARSEIOC_SETCS): %m", CLK_UNIT(parse->peer));
1911 		return 0;
1912 	}
1913 	return 1;
1914 }
1915 
1916 /*--------------------------------------------------
1917  * STREAM enable
1918  */
1919 static int
1920 stream_enable(
1921 	struct parseunit *parse
1922 	)
1923 {
1924 	struct strioctl strioc;
1925 
1926 	strioc.ic_cmd     = PARSEIOC_ENABLE;
1927 	strioc.ic_timout  = 0;
1928 	strioc.ic_dp      = (char *)0;
1929 	strioc.ic_len     = 0;
1930 
1931 	if (ioctl(parse->generic->io.fd, I_STR, (caddr_t)&strioc) == -1)
1932 	{
1933 		msyslog(LOG_ERR, "PARSE receiver #%d: stream_enable: ioctl(fd, I_STR, PARSEIOC_ENABLE): %m", CLK_UNIT(parse->peer));
1934 		return 0;
1935 	}
1936 	parse->generic->io.clock_recv = stream_receive; /* ok - parse input in kernel */
1937 	return 1;
1938 }
1939 
1940 /*--------------------------------------------------
1941  * STREAM disable
1942  */
1943 static int
1944 stream_disable(
1945 	struct parseunit *parse
1946 	)
1947 {
1948 	struct strioctl strioc;
1949 
1950 	strioc.ic_cmd     = PARSEIOC_DISABLE;
1951 	strioc.ic_timout  = 0;
1952 	strioc.ic_dp      = (char *)0;
1953 	strioc.ic_len     = 0;
1954 
1955 	if (ioctl(parse->generic->io.fd, I_STR, (caddr_t)&strioc) == -1)
1956 	{
1957 		msyslog(LOG_ERR, "PARSE receiver #%d: stream_disable: ioctl(fd, I_STR, PARSEIOC_DISABLE): %m", CLK_UNIT(parse->peer));
1958 		return 0;
1959 	}
1960 	parse->generic->io.clock_recv = local_receive; /* ok - parse input in daemon */
1961 	return 1;
1962 }
1963 
1964 /*--------------------------------------------------
1965  * STREAM getfmt
1966  */
1967 static int
1968 stream_getfmt(
1969 	struct parseunit *parse,
1970 	parsectl_t  *tcl
1971 	)
1972 {
1973 	struct strioctl strioc;
1974 
1975 	strioc.ic_cmd     = PARSEIOC_GETFMT;
1976 	strioc.ic_timout  = 0;
1977 	strioc.ic_dp      = (char *)tcl;
1978 	strioc.ic_len     = sizeof (*tcl);
1979 	if (ioctl(parse->generic->io.fd, I_STR, (caddr_t)&strioc) == -1)
1980 	{
1981 		msyslog(LOG_ERR, "PARSE receiver #%d: ioctl(fd, I_STR, PARSEIOC_GETFMT): %m", CLK_UNIT(parse->peer));
1982 		return 0;
1983 	}
1984 	return 1;
1985 }
1986 
1987 /*--------------------------------------------------
1988  * STREAM setfmt
1989  */
1990 static int
1991 stream_setfmt(
1992 	struct parseunit *parse,
1993 	parsectl_t  *tcl
1994 	)
1995 {
1996 	struct strioctl strioc;
1997 
1998 	strioc.ic_cmd     = PARSEIOC_SETFMT;
1999 	strioc.ic_timout  = 0;
2000 	strioc.ic_dp      = (char *)tcl;
2001 	strioc.ic_len     = sizeof (*tcl);
2002 
2003 	if (ioctl(parse->generic->io.fd, I_STR, (caddr_t)&strioc) == -1)
2004 	{
2005 		msyslog(LOG_ERR, "PARSE receiver #%d: stream_setfmt: ioctl(fd, I_STR, PARSEIOC_SETFMT): %m", CLK_UNIT(parse->peer));
2006 		return 0;
2007 	}
2008 	return 1;
2009 }
2010 
2011 
2012 /*--------------------------------------------------
2013  * STREAM timecode
2014  */
2015 static int
2016 stream_timecode(
2017 	struct parseunit *parse,
2018 	parsectl_t  *tcl
2019 	)
2020 {
2021 	struct strioctl strioc;
2022 
2023 	strioc.ic_cmd     = PARSEIOC_TIMECODE;
2024 	strioc.ic_timout  = 0;
2025 	strioc.ic_dp      = (char *)tcl;
2026 	strioc.ic_len     = sizeof (*tcl);
2027 
2028 	if (ioctl(parse->generic->io.fd, I_STR, (caddr_t)&strioc) == -1)
2029 	{
2030 		ERR(ERR_INTERNAL)
2031 			msyslog(LOG_ERR, "PARSE receiver #%d: stream_timecode: ioctl(fd, I_STR, PARSEIOC_TIMECODE): %m", CLK_UNIT(parse->peer));
2032 		return 0;
2033 	}
2034 	clear_err(parse, ERR_INTERNAL);
2035 	return 1;
2036 }
2037 
2038 /*--------------------------------------------------
2039  * STREAM receive
2040  */
2041 static void
2042 stream_receive(
2043 	struct recvbuf *rbufp
2044 	)
2045 {
2046 	struct parseunit * parse;
2047 	parsetime_t parsetime;
2048 
2049 	parse = (struct parseunit *)rbufp->recv_peer->procptr->unitptr;
2050 	if (!parse->peer)
2051 	    return;
2052 
2053 	if (rbufp->recv_length != sizeof(parsetime_t))
2054 	{
2055 		ERR(ERR_BADIO)
2056 			msyslog(LOG_ERR,"PARSE receiver #%d: stream_receive: bad size (got %d expected %d)",
2057 				CLK_UNIT(parse->peer), rbufp->recv_length, (int)sizeof(parsetime_t));
2058 		parse_event(parse, CEVNT_BADREPLY);
2059 		return;
2060 	}
2061 	clear_err(parse, ERR_BADIO);
2062 
2063 	memmove((caddr_t)&parsetime,
2064 		(caddr_t)rbufp->recv_buffer,
2065 		sizeof(parsetime_t));
2066 
2067 #ifdef DEBUG
2068 	if (debug > 3)
2069 	  {
2070 	    printf("PARSE receiver #%d: status %06x, state %08x, time %lx.%08lx, stime %lx.%08lx, ptime %lx.%08lx\n",
2071 		   CLK_UNIT(parse->peer),
2072 		   (unsigned int)parsetime.parse_status,
2073 		   (unsigned int)parsetime.parse_state,
2074 		   (unsigned long)parsetime.parse_time.tv.tv_sec,
2075 		   (unsigned long)parsetime.parse_time.tv.tv_usec,
2076 		   (unsigned long)parsetime.parse_stime.tv.tv_sec,
2077 		   (unsigned long)parsetime.parse_stime.tv.tv_usec,
2078 		   (unsigned long)parsetime.parse_ptime.tv.tv_sec,
2079 		   (unsigned long)parsetime.parse_ptime.tv.tv_usec);
2080 	  }
2081 #endif
2082 
2083 	/*
2084 	 * switch time stamp world - be sure to normalize small usec field
2085 	 * errors.
2086 	 */
2087 
2088 	parsetime.parse_stime.fp = tval_stamp_to_lfp(parsetime.parse_stime.tv);
2089 
2090 	if (PARSE_TIMECODE(parsetime.parse_state))
2091 	{
2092 		parsetime.parse_time.fp = tval_stamp_to_lfp(parsetime.parse_time.tv);
2093 	}
2094 
2095 	if (PARSE_PPS(parsetime.parse_state))
2096 	{
2097 		parsetime.parse_ptime.fp = tval_stamp_to_lfp(parsetime.parse_ptime.tv);
2098 	}
2099 
2100 	parse_process(parse, &parsetime);
2101 }
2102 #endif
2103 
2104 /*--------------------------------------------------
2105  * local init
2106  */
2107 static int
2108 local_init(
2109 	struct parseunit *parse
2110 	)
2111 {
2112 	return parse_ioinit(&parse->parseio);
2113 }
2114 
2115 /*--------------------------------------------------
2116  * local end
2117  */
2118 static void
2119 local_end(
2120 	struct parseunit *parse
2121 	)
2122 {
2123 	parse_ioend(&parse->parseio);
2124 }
2125 
2126 
2127 /*--------------------------------------------------
2128  * local nop
2129  */
2130 static int
2131 local_nop(
2132 	struct parseunit *parse
2133 	)
2134 {
2135 	return 1;
2136 }
2137 
2138 /*--------------------------------------------------
2139  * local setcs
2140  */
2141 static int
2142 local_setcs(
2143 	struct parseunit *parse,
2144 	parsectl_t  *tcl
2145 	)
2146 {
2147 	return parse_setcs(tcl, &parse->parseio);
2148 }
2149 
2150 /*--------------------------------------------------
2151  * local getfmt
2152  */
2153 static int
2154 local_getfmt(
2155 	struct parseunit *parse,
2156 	parsectl_t  *tcl
2157 	)
2158 {
2159 	return parse_getfmt(tcl, &parse->parseio);
2160 }
2161 
2162 /*--------------------------------------------------
2163  * local setfmt
2164  */
2165 static int
2166 local_setfmt(
2167 	struct parseunit *parse,
2168 	parsectl_t  *tcl
2169 	)
2170 {
2171 	return parse_setfmt(tcl, &parse->parseio);
2172 }
2173 
2174 /*--------------------------------------------------
2175  * local timecode
2176  */
2177 static int
2178 local_timecode(
2179 	struct parseunit *parse,
2180 	parsectl_t  *tcl
2181 	)
2182 {
2183 	return parse_timecode(tcl, &parse->parseio);
2184 }
2185 
2186 
2187 /*--------------------------------------------------
2188  * local input
2189  */
2190 static int
2191 local_input(
2192 	struct recvbuf *rbufp
2193 	)
2194 {
2195 	struct parseunit * parse;
2196 
2197 	int count;
2198 	unsigned char *s;
2199 	timestamp_t ts;
2200 
2201 	parse = (struct parseunit *)rbufp->recv_peer->procptr->unitptr;
2202 	if (!parse->peer)
2203 		return 0;
2204 
2205 	/*
2206 	 * eat all characters, parsing then and feeding complete samples
2207 	 */
2208 	count = rbufp->recv_length;
2209 	s = (unsigned char *)rbufp->recv_buffer;
2210 	ts.fp = rbufp->recv_time;
2211 
2212 	while (count--)
2213 	{
2214 		if (parse_ioread(&parse->parseio, (unsigned int)(*s++), &ts))
2215 		{
2216 			struct recvbuf *buf;
2217 
2218 			/*
2219 			 * got something good to eat
2220 			 */
2221 			if (!PARSE_PPS(parse->parseio.parse_dtime.parse_state))
2222 			{
2223 #ifdef HAVE_PPSAPI
2224 				if (parse->flags & PARSE_PPSCLOCK)
2225 				{
2226 					struct timespec pps_timeout;
2227 					pps_info_t      pps_info;
2228 
2229 					pps_timeout.tv_sec  = 0;
2230 					pps_timeout.tv_nsec = 0;
2231 
2232 					if (time_pps_fetch(parse->atom.handle, PPS_TSFMT_TSPEC, &pps_info,
2233 							   &pps_timeout) == 0)
2234 					{
2235 						if (pps_info.assert_sequence + pps_info.clear_sequence != parse->ppsserial)
2236 						{
2237 							double dtemp;
2238 
2239 						        struct timespec pts;
2240 							/*
2241 							 * add PPS time stamp if available via ppsclock module
2242 							 * and not supplied already.
2243 							 */
2244 							if (parse->flags & PARSE_CLEAR)
2245 							  pts = pps_info.clear_timestamp;
2246 							else
2247 							  pts = pps_info.assert_timestamp;
2248 
2249 							parse->parseio.parse_dtime.parse_ptime.fp.l_ui = (uint32_t) (pts.tv_sec + JAN_1970);
2250 
2251 							dtemp = (double) pts.tv_nsec / 1e9;
2252 							if (dtemp < 0.) {
2253 								dtemp += 1;
2254 								parse->parseio.parse_dtime.parse_ptime.fp.l_ui--;
2255 							}
2256 							if (dtemp > 1.) {
2257 								dtemp -= 1;
2258 								parse->parseio.parse_dtime.parse_ptime.fp.l_ui++;
2259 							}
2260 							parse->parseio.parse_dtime.parse_ptime.fp.l_uf = (uint32_t)(dtemp * FRAC);
2261 
2262 							parse->parseio.parse_dtime.parse_state |= PARSEB_PPS|PARSEB_S_PPS;
2263 #ifdef DEBUG
2264 							if (debug > 3)
2265 							{
2266 								printf(
2267 								       "parse: local_receive: fd %d PPSAPI seq %ld - PPS %s\n",
2268 								       rbufp->fd,
2269 								       (long)pps_info.assert_sequence + (long)pps_info.clear_sequence,
2270 								       lfptoa(&parse->parseio.parse_dtime.parse_ptime.fp, 6));
2271 							}
2272 #endif
2273 						}
2274 #ifdef DEBUG
2275 						else
2276 						{
2277 							if (debug > 3)
2278 							{
2279 								printf(
2280 								       "parse: local_receive: fd %d PPSAPI seq assert %ld, seq clear %ld - NO PPS event\n",
2281 								       rbufp->fd,
2282 								       (long)pps_info.assert_sequence, (long)pps_info.clear_sequence);
2283 							}
2284 						}
2285 #endif
2286 						parse->ppsserial = pps_info.assert_sequence + pps_info.clear_sequence;
2287 					}
2288 #ifdef DEBUG
2289 					else
2290 					{
2291 						if (debug > 3)
2292 						{
2293 							printf(
2294 							       "parse: local_receive: fd %d PPSAPI time_pps_fetch errno = %d\n",
2295 							       rbufp->fd,
2296 							       errno);
2297 						}
2298 					}
2299 #endif
2300 				}
2301 #else
2302 #ifdef TIOCDCDTIMESTAMP
2303 				struct timeval dcd_time;
2304 
2305 				if (ioctl(parse->ppsfd, TIOCDCDTIMESTAMP, &dcd_time) != -1)
2306 				{
2307 					l_fp tstmp;
2308 
2309 					TVTOTS(&dcd_time, &tstmp);
2310 					tstmp.l_ui += JAN_1970;
2311 					L_SUB(&ts.fp, &tstmp);
2312 					if (ts.fp.l_ui == 0)
2313 					{
2314 #ifdef DEBUG
2315 						if (debug)
2316 						{
2317 							printf(
2318 							       "parse: local_receive: fd %d DCDTIMESTAMP %s\n",
2319 							       parse->ppsfd,
2320 							       lfptoa(&tstmp, 6));
2321 							printf(" sigio %s\n",
2322 							       lfptoa(&ts.fp, 6));
2323 						}
2324 #endif
2325 						parse->parseio.parse_dtime.parse_ptime.fp = tstmp;
2326 						parse->parseio.parse_dtime.parse_state |= PARSEB_PPS|PARSEB_S_PPS;
2327 					}
2328 				}
2329 #else /* TIOCDCDTIMESTAMP */
2330 #if defined(HAVE_STRUCT_PPSCLOCKEV) && (defined(HAVE_CIOGETEV) || defined(HAVE_TIOCGPPSEV))
2331 				if (parse->flags & PARSE_PPSCLOCK)
2332 				  {
2333 				    l_fp tts;
2334 				    struct ppsclockev ev;
2335 
2336 #ifdef HAVE_CIOGETEV
2337 				    if (ioctl(parse->ppsfd, CIOGETEV, (caddr_t)&ev) == 0)
2338 #endif
2339 #ifdef HAVE_TIOCGPPSEV
2340 				    if (ioctl(parse->ppsfd, TIOCGPPSEV, (caddr_t)&ev) == 0)
2341 #endif
2342 					{
2343 					  if (ev.serial != parse->ppsserial)
2344 					    {
2345 					      /*
2346 					       * add PPS time stamp if available via ppsclock module
2347 					       * and not supplied already.
2348 					       */
2349 					      if (!buftvtots((const char *)&ev.tv, &tts))
2350 						{
2351 						  ERR(ERR_BADDATA)
2352 						    msyslog(LOG_ERR,"parse: local_receive: timestamp conversion error (buftvtots) (ppsclockev.tv)");
2353 						}
2354 					      else
2355 						{
2356 						  parse->parseio.parse_dtime.parse_ptime.fp = tts;
2357 						  parse->parseio.parse_dtime.parse_state |= PARSEB_PPS|PARSEB_S_PPS;
2358 						}
2359 					    }
2360 					  parse->ppsserial = ev.serial;
2361 					}
2362 				  }
2363 #endif
2364 #endif /* TIOCDCDTIMESTAMP */
2365 #endif /* !HAVE_PPSAPI */
2366 			}
2367 			if (count)
2368 			{	/* simulate receive */
2369 				buf = get_free_recv_buffer();
2370 				if (buf != NULL) {
2371 					memmove((caddr_t)buf->recv_buffer,
2372 						(caddr_t)&parse->parseio.parse_dtime,
2373 						sizeof(parsetime_t));
2374 					buf->recv_length  = sizeof(parsetime_t);
2375 					buf->recv_time    = rbufp->recv_time;
2376 #ifndef HAVE_IO_COMPLETION_PORT
2377 					buf->srcadr       = rbufp->srcadr;
2378 #endif
2379 					buf->dstadr       = rbufp->dstadr;
2380 					buf->receiver     = rbufp->receiver;
2381 					buf->fd           = rbufp->fd;
2382 					buf->X_from_where = rbufp->X_from_where;
2383 					parse->generic->io.recvcount++;
2384 					packets_received++;
2385 					add_full_recv_buffer(buf);
2386 #ifdef HAVE_IO_COMPLETION_PORT
2387 					SetEvent(WaitableIoEventHandle);
2388 #endif
2389 				}
2390 				parse_iodone(&parse->parseio);
2391 			}
2392 			else
2393 			{
2394 				memmove((caddr_t)rbufp->recv_buffer,
2395 					(caddr_t)&parse->parseio.parse_dtime,
2396 					sizeof(parsetime_t));
2397 				parse_iodone(&parse->parseio);
2398 				rbufp->recv_length = sizeof(parsetime_t);
2399 				return 1; /* got something & in place return */
2400 			}
2401 		}
2402 	}
2403 	return 0;		/* nothing to pass up */
2404 }
2405 
2406 /*--------------------------------------------------
2407  * local receive
2408  */
2409 static void
2410 local_receive(
2411 	struct recvbuf *rbufp
2412 	)
2413 {
2414 	struct parseunit * parse;
2415 	parsetime_t parsetime;
2416 
2417 	parse = (struct parseunit *)rbufp->recv_peer->procptr->unitptr;
2418 	if (!parse->peer)
2419 	    return;
2420 
2421 	if (rbufp->recv_length != sizeof(parsetime_t))
2422 	{
2423 		ERR(ERR_BADIO)
2424 			msyslog(LOG_ERR,"PARSE receiver #%d: local_receive: bad size (got %d expected %d)",
2425 				CLK_UNIT(parse->peer), rbufp->recv_length, (int)sizeof(parsetime_t));
2426 		parse_event(parse, CEVNT_BADREPLY);
2427 		return;
2428 	}
2429 	clear_err(parse, ERR_BADIO);
2430 
2431 	memmove((caddr_t)&parsetime,
2432 		(caddr_t)rbufp->recv_buffer,
2433 		sizeof(parsetime_t));
2434 
2435 #ifdef DEBUG
2436 	if (debug > 3)
2437 	  {
2438 	    printf("PARSE receiver #%d: status %06x, state %08x, time(fp) %lx.%08lx, stime(fp) %lx.%08lx, ptime(fp) %lx.%08lx\n",
2439 		   CLK_UNIT(parse->peer),
2440 		   (unsigned int)parsetime.parse_status,
2441 		   (unsigned int)parsetime.parse_state,
2442 		   (unsigned long)parsetime.parse_time.fp.l_ui,
2443 		   (unsigned long)parsetime.parse_time.fp.l_uf,
2444 		   (unsigned long)parsetime.parse_stime.fp.l_ui,
2445 		   (unsigned long)parsetime.parse_stime.fp.l_uf,
2446 		   (unsigned long)parsetime.parse_ptime.fp.l_ui,
2447 		   (unsigned long)parsetime.parse_ptime.fp.l_uf);
2448 	  }
2449 #endif
2450 
2451 	parse_process(parse, &parsetime);
2452 }
2453 
2454 /*--------------------------------------------------
2455  * init_iobinding - find and initialize lower layers
2456  */
2457 static bind_t *
2458 init_iobinding(
2459 	struct parseunit *parse
2460 	)
2461 {
2462   bind_t *b = io_bindings;
2463 
2464 	while (b->bd_description != (char *)0)
2465 	{
2466 		if ((*b->bd_init)(parse))
2467 		{
2468 			return b;
2469 		}
2470 		b++;
2471 	}
2472 	return (bind_t *)0;
2473 }
2474 
2475 /**===========================================================================
2476  ** support routines
2477  **/
2478 
2479 static NTP_PRINTF(4, 5) char *
2480 ap(char *buffer, size_t len, char *pos, const char *fmt, ...)
2481 {
2482 	va_list va;
2483 	int l;
2484 	size_t rem = len - (pos - buffer);
2485 
2486 	if (rem == 0)
2487 		return pos;
2488 
2489 	va_start(va, fmt);
2490 	l = vsnprintf(pos, rem, fmt, va);
2491 	va_end(va);
2492 
2493 	if (l != -1) {
2494 		rem--;
2495 		if (rem >= (size_t)l)
2496 			pos += l;
2497 		else
2498 			pos += rem;
2499 	}
2500 
2501 	return pos;
2502 }
2503 
2504 /*--------------------------------------------------
2505  * convert a flag field to a string
2506  */
2507 static char *
2508 parsestate(
2509 	u_long lstate,
2510 	char *buffer,
2511 	int size
2512 	)
2513 {
2514 	static struct bits
2515 	{
2516 		u_long      bit;
2517 		const char *name;
2518 	} flagstrings[] =
2519 	  {
2520 		  { PARSEB_ANNOUNCE,   "DST SWITCH WARNING" },
2521 		  { PARSEB_POWERUP,    "NOT SYNCHRONIZED" },
2522 		  { PARSEB_NOSYNC,     "TIME CODE NOT CONFIRMED" },
2523 		  { PARSEB_DST,        "DST" },
2524 		  { PARSEB_UTC,        "UTC DISPLAY" },
2525 		  { PARSEB_LEAPADD,    "LEAP ADD WARNING" },
2526 		  { PARSEB_LEAPDEL,    "LEAP DELETE WARNING" },
2527 		  { PARSEB_LEAPSECOND, "LEAP SECOND" },
2528 		  { PARSEB_CALLBIT,    "CALL BIT" },
2529 		  { PARSEB_TIMECODE,   "TIME CODE" },
2530 		  { PARSEB_PPS,        "PPS" },
2531 		  { PARSEB_POSITION,   "POSITION" },
2532 		  { 0,		       NULL }
2533 	  };
2534 
2535 	static struct sbits
2536 	{
2537 		u_long      bit;
2538 		const char *name;
2539 	} sflagstrings[] =
2540 	  {
2541 		  { PARSEB_S_LEAP,     "LEAP INDICATION" },
2542 		  { PARSEB_S_PPS,      "PPS SIGNAL" },
2543 		  { PARSEB_S_ANTENNA,  "ANTENNA" },
2544 		  { PARSEB_S_POSITION, "POSITION" },
2545 		  { 0,		       NULL }
2546 	  };
2547 	int i;
2548 	char *s, *t;
2549 
2550 	*buffer = '\0';
2551 	s = t = buffer;
2552 
2553 	i = 0;
2554 	while (flagstrings[i].bit)
2555 	{
2556 		if (flagstrings[i].bit & lstate)
2557 		{
2558 			if (s != t)
2559 				t = ap(buffer, size, t, "; ");
2560 			t = ap(buffer, size, t, "%s", flagstrings[i].name);
2561 		}
2562 		i++;
2563 	}
2564 
2565 	if (lstate & (PARSEB_S_LEAP|PARSEB_S_ANTENNA|PARSEB_S_PPS|PARSEB_S_POSITION))
2566 	{
2567 		if (s != t)
2568 			t = ap(buffer, size, t, "; ");
2569 
2570 		t = ap(buffer, size, t, "(");
2571 
2572 		s = t;
2573 
2574 		i = 0;
2575 		while (sflagstrings[i].bit)
2576 		{
2577 			if (sflagstrings[i].bit & lstate)
2578 			{
2579 				if (t != s)
2580 				{
2581 					t = ap(buffer, size, t, "; ");
2582 				}
2583 
2584 				t = ap(buffer, size, t, "%s",
2585 				    sflagstrings[i].name);
2586 			}
2587 			i++;
2588 		}
2589 		t = ap(buffer, size, t, ")");
2590 	}
2591 	return buffer;
2592 }
2593 
2594 /*--------------------------------------------------
2595  * convert a status flag field to a string
2596  */
2597 static char *
2598 parsestatus(
2599 	u_long lstate,
2600 	char *buffer,
2601 	int size
2602 	)
2603 {
2604 	static struct bits
2605 	{
2606 		u_long      bit;
2607 		const char *name;
2608 	} flagstrings[] =
2609 	  {
2610 		  { CVT_OK,      "CONVERSION SUCCESSFUL" },
2611 		  { CVT_NONE,    "NO CONVERSION" },
2612 		  { CVT_FAIL,    "CONVERSION FAILED" },
2613 		  { CVT_BADFMT,  "ILLEGAL FORMAT" },
2614 		  { CVT_BADDATE, "DATE ILLEGAL" },
2615 		  { CVT_BADTIME, "TIME ILLEGAL" },
2616 		  { CVT_ADDITIONAL, "ADDITIONAL DATA" },
2617 		  { 0,		 NULL }
2618 	  };
2619 	int i;
2620 	char *t;
2621 
2622 	t = buffer;
2623 	*buffer = '\0';
2624 
2625 	i = 0;
2626 	while (flagstrings[i].bit)
2627 	{
2628 		if (flagstrings[i].bit & lstate)
2629 		{
2630 			if (t != buffer)
2631 				t = ap(buffer, size, t, "; ");
2632 			t = ap(buffer, size, t, "%s", flagstrings[i].name);
2633 		}
2634 		i++;
2635 	}
2636 
2637 	return buffer;
2638 }
2639 
2640 /*--------------------------------------------------
2641  * convert a clock status flag field to a string
2642  */
2643 static const char *
2644 clockstatus(
2645 	u_long lstate
2646 	)
2647 {
2648 	static char buffer[20];
2649 	static struct status
2650 	{
2651 		u_long      value;
2652 		const char *name;
2653 	} flagstrings[] =
2654 	  {
2655 		  { CEVNT_NOMINAL, "NOMINAL" },
2656 		  { CEVNT_TIMEOUT, "NO RESPONSE" },
2657 		  { CEVNT_BADREPLY,"BAD FORMAT" },
2658 		  { CEVNT_FAULT,   "FAULT" },
2659 		  { CEVNT_PROP,    "PROPAGATION DELAY" },
2660 		  { CEVNT_BADDATE, "ILLEGAL DATE" },
2661 		  { CEVNT_BADTIME, "ILLEGAL TIME" },
2662 		  { (unsigned)~0L, NULL }
2663 	  };
2664 	int i;
2665 
2666 	i = 0;
2667 	while (flagstrings[i].value != (u_int)~0)
2668 	{
2669 		if (flagstrings[i].value == lstate)
2670 		{
2671 			return flagstrings[i].name;
2672 		}
2673 		i++;
2674 	}
2675 
2676 	snprintf(buffer, sizeof(buffer), "unknown #%ld", (u_long)lstate);
2677 
2678 	return buffer;
2679 }
2680 
2681 
2682 /*--------------------------------------------------
2683  * l_mktime - make representation of a relative time
2684  */
2685 static char *
2686 l_mktime(
2687 	u_long delta
2688 	)
2689 {
2690 	u_long tmp, m, s;
2691 	static char buffer[40];
2692 	char *t;
2693 
2694 	buffer[0] = '\0';
2695 	t = buffer;
2696 
2697 	if ((tmp = delta / (60*60*24)) != 0)
2698 	{
2699 		t = ap(buffer, sizeof(buffer), t, "%ldd+", (u_long)tmp);
2700 		delta -= tmp * 60*60*24;
2701 	}
2702 
2703 	s = delta % 60;
2704 	delta /= 60;
2705 	m = delta % 60;
2706 	delta /= 60;
2707 
2708 	t = ap(buffer, sizeof(buffer), t, "%02d:%02d:%02d",
2709 	     (int)delta, (int)m, (int)s);
2710 
2711 	return buffer;
2712 }
2713 
2714 
2715 /*--------------------------------------------------
2716  * parse_statistics - list summary of clock states
2717  */
2718 static void
2719 parse_statistics(
2720 	struct parseunit *parse
2721 	)
2722 {
2723 	int i;
2724 
2725 	NLOG(NLOG_CLOCKSTATIST) /* conditional if clause for conditional syslog */
2726 		{
2727 			msyslog(LOG_INFO, "PARSE receiver #%d: running time: %s",
2728 				CLK_UNIT(parse->peer),
2729 				l_mktime(current_time - parse->generic->timestarted));
2730 
2731 			msyslog(LOG_INFO, "PARSE receiver #%d: current status: %s",
2732 				CLK_UNIT(parse->peer),
2733 				clockstatus(parse->generic->currentstatus));
2734 
2735 			for (i = 0; i <= CEVNT_MAX; i++)
2736 			{
2737 				u_long s_time;
2738 				u_long percent, d = current_time - parse->generic->timestarted;
2739 
2740 				percent = s_time = PARSE_STATETIME(parse, i);
2741 
2742 				while (((u_long)(~0) / 10000) < percent)
2743 				{
2744 					percent /= 10;
2745 					d       /= 10;
2746 				}
2747 
2748 				if (d)
2749 				    percent = (percent * 10000) / d;
2750 				else
2751 				    percent = 10000;
2752 
2753 				if (s_time)
2754 				    msyslog(LOG_INFO, "PARSE receiver #%d: state %18s: %13s (%3ld.%02ld%%)",
2755 					    CLK_UNIT(parse->peer),
2756 					    clockstatus((unsigned int)i),
2757 					    l_mktime(s_time),
2758 					    percent / 100, percent % 100);
2759 			}
2760 		}
2761 }
2762 
2763 /*--------------------------------------------------
2764  * cparse_statistics - wrapper for statistics call
2765  */
2766 static void
2767 cparse_statistics(
2768         struct parseunit *parse
2769 	)
2770 {
2771 	if (parse->laststatistic + PARSESTATISTICS < current_time)
2772 		parse_statistics(parse);
2773 	parse->laststatistic = current_time;
2774 }
2775 
2776 /**===========================================================================
2777  ** ntp interface routines
2778  **/
2779 
2780 /*--------------------------------------------------
2781  * parse_shutdown - shut down a PARSE clock
2782  */
2783 static void
2784 parse_shutdown(
2785 	int unit,
2786 	struct peer *peer
2787 	)
2788 {
2789 	struct parseunit *parse = NULL;
2790 
2791 	if (peer && peer->procptr)
2792 		parse = peer->procptr->unitptr;
2793 
2794 	if (!parse)
2795 	{
2796 		/* nothing to clean up */
2797 		return;
2798 	}
2799 
2800 	if (!parse->peer)
2801 	{
2802 		msyslog(LOG_INFO, "PARSE receiver #%d: INTERNAL ERROR - unit already inactive - shutdown ignored", unit);
2803 		return;
2804 	}
2805 
2806 #ifdef HAVE_PPSAPI
2807 	if (parse->flags & PARSE_PPSCLOCK)
2808 	{
2809 		(void)time_pps_destroy(parse->atom.handle);
2810 	}
2811 #endif
2812 	if (parse->generic->io.fd != parse->ppsfd && parse->ppsfd != -1)
2813 		(void)closeserial(parse->ppsfd);  /* close separate PPS source */
2814 
2815 	/*
2816 	 * print statistics a last time and
2817 	 * stop statistics machine
2818 	 */
2819 	parse_statistics(parse);
2820 
2821 	if (parse->parse_type->cl_end)
2822 	{
2823 		parse->parse_type->cl_end(parse);
2824 	}
2825 
2826 	/*
2827 	 * cleanup before leaving this world
2828 	 */
2829 	if (parse->binding)
2830 	    PARSE_END(parse);
2831 
2832 	/*
2833 	 * Tell the I/O module to turn us off.  We're history.
2834 	 */
2835 	io_closeclock(&parse->generic->io);
2836 
2837 	free_varlist(parse->kv);
2838 
2839 	NLOG(NLOG_CLOCKINFO) /* conditional if clause for conditional syslog */
2840 		msyslog(LOG_INFO, "PARSE receiver #%d: reference clock \"%s\" removed",
2841 			CLK_UNIT(parse->peer), parse->parse_type->cl_description);
2842 
2843 	parse->peer = (struct peer *)0; /* unused now */
2844 	peer->procptr->unitptr = (caddr_t)0;
2845 	free(parse);
2846 }
2847 
2848 #ifdef HAVE_PPSAPI
2849 /*----------------------------------------
2850  * set up HARDPPS via PPSAPI
2851  */
2852 static void
2853 parse_hardpps(
2854 	      struct parseunit *parse,
2855 	      int mode
2856 	      )
2857 {
2858         if (parse->hardppsstate == mode)
2859 	        return;
2860 
2861 	if (CLK_PPS(parse->peer) && (parse->flags & PARSE_PPSKERNEL)) {
2862 		int	i = 0;
2863 
2864 		if (mode == PARSE_HARDPPS_ENABLE)
2865 		        {
2866 			        if (parse->flags & PARSE_CLEAR)
2867 				        i = PPS_CAPTURECLEAR;
2868 				else
2869 				        i = PPS_CAPTUREASSERT;
2870 			}
2871 
2872 		if (time_pps_kcbind(parse->atom.handle, PPS_KC_HARDPPS, i,
2873 		    PPS_TSFMT_TSPEC) < 0) {
2874 		        msyslog(LOG_ERR, "PARSE receiver #%d: time_pps_kcbind failed: %m",
2875 				CLK_UNIT(parse->peer));
2876 		} else {
2877 		        NLOG(NLOG_CLOCKINFO)
2878 		                msyslog(LOG_INFO, "PARSE receiver #%d: kernel PPS synchronisation %sabled",
2879 					CLK_UNIT(parse->peer), (mode == PARSE_HARDPPS_ENABLE) ? "en" : "dis");
2880 			/*
2881 			 * tell the rest, that we have a kernel PPS source, iff we ever enable HARDPPS
2882 			 */
2883 			if (mode == PARSE_HARDPPS_ENABLE)
2884 			        hardpps_enable = 1;
2885 		}
2886 	}
2887 
2888 	parse->hardppsstate = mode;
2889 }
2890 
2891 /*----------------------------------------
2892  * set up PPS via PPSAPI
2893  */
2894 static int
2895 parse_ppsapi(
2896 	     struct parseunit *parse
2897 	)
2898 {
2899 	int cap, mode_ppsoffset;
2900 	const char *cp;
2901 
2902 	parse->flags &= (u_char) (~PARSE_PPSCLOCK);
2903 
2904 	/*
2905 	 * collect PPSAPI offset capability - should move into generic handling
2906 	 */
2907 	if (time_pps_getcap(parse->atom.handle, &cap) < 0) {
2908 		msyslog(LOG_ERR, "PARSE receiver #%d: parse_ppsapi: time_pps_getcap failed: %m",
2909 			CLK_UNIT(parse->peer));
2910 
2911 		return 0;
2912 	}
2913 
2914 	/*
2915 	 * initialize generic PPSAPI interface
2916 	 *
2917 	 * we leave out CLK_FLAG3 as time_pps_kcbind()
2918 	 * is handled here for now. Ideally this should also
2919 	 * be part of the generic PPSAPI interface
2920 	 */
2921 	if (!refclock_params(parse->flags & (CLK_FLAG1|CLK_FLAG2|CLK_FLAG4), &parse->atom))
2922 		return 0;
2923 
2924 	/* nb. only turn things on, if someone else has turned something
2925 	 *	on before we get here, leave it alone!
2926 	 */
2927 
2928 	if (parse->flags & PARSE_CLEAR) {
2929 		cp = "CLEAR";
2930 		mode_ppsoffset = PPS_OFFSETCLEAR;
2931 	} else {
2932 		cp = "ASSERT";
2933 		mode_ppsoffset = PPS_OFFSETASSERT;
2934 	}
2935 
2936 	msyslog(LOG_INFO, "PARSE receiver #%d: initializing PPS to %s",
2937 		CLK_UNIT(parse->peer), cp);
2938 
2939 	if (!(mode_ppsoffset & cap)) {
2940 	  msyslog(LOG_WARNING, "PARSE receiver #%d: Cannot set PPS_%sCLEAR, this will increase jitter (PPS API capabilities=0x%x)",
2941 		  CLK_UNIT(parse->peer), cp, cap);
2942 		mode_ppsoffset = 0;
2943 	} else {
2944 		if (mode_ppsoffset == PPS_OFFSETCLEAR)
2945 			{
2946 				parse->atom.pps_params.clear_offset.tv_sec = (time_t)(-parse->ppsphaseadjust);
2947 				parse->atom.pps_params.clear_offset.tv_nsec = (long)(-1e9*(parse->ppsphaseadjust - (double)(long)parse->ppsphaseadjust));
2948 			}
2949 
2950 		if (mode_ppsoffset == PPS_OFFSETASSERT)
2951 			{
2952 				parse->atom.pps_params.assert_offset.tv_sec = (time_t)(-parse->ppsphaseadjust);
2953 				parse->atom.pps_params.assert_offset.tv_nsec = (long)(-1e9*(parse->ppsphaseadjust - (double)(long)parse->ppsphaseadjust));
2954 			}
2955 	}
2956 
2957 	parse->atom.pps_params.mode |= mode_ppsoffset;
2958 
2959 	if (time_pps_setparams(parse->atom.handle, &parse->atom.pps_params) < 0) {
2960 	  msyslog(LOG_ERR, "PARSE receiver #%d: FAILED set PPS parameters: %m",
2961 		  CLK_UNIT(parse->peer));
2962 		return 0;
2963 	}
2964 
2965 	parse->flags |= PARSE_PPSCLOCK;
2966 	return 1;
2967 }
2968 #else
2969 #define parse_hardpps(_PARSE_, _MODE_) /* empty */
2970 #endif
2971 
2972 /*--------------------------------------------------
2973  * parse_start - open the PARSE devices and initialize data for processing
2974  */
2975 static int
2976 parse_start(
2977 	int sysunit,
2978 	struct peer *peer
2979 	)
2980 {
2981 	u_int unit;
2982 	int fd232;
2983 #ifdef HAVE_TERMIOS
2984 	struct termios tio;		/* NEEDED FOR A LONG TIME ! */
2985 #endif
2986 #ifdef HAVE_SYSV_TTYS
2987 	struct termio tio;		/* NEEDED FOR A LONG TIME ! */
2988 #endif
2989 	struct parseunit * parse;
2990 	char parsedev[sizeof(PARSEDEVICE)+20];
2991 	char parseppsdev[sizeof(PARSEPPSDEVICE)+20];
2992 	parsectl_t tmp_ctl;
2993 	u_int type;
2994 
2995 	/*
2996 	 * get out Copyright information once
2997 	 */
2998 	if (!notice)
2999         {
3000 		NLOG(NLOG_CLOCKINFO) /* conditional if clause for conditional syslog */
3001 			msyslog(LOG_INFO, "NTP PARSE support: Copyright (c) 1989-2009, Frank Kardel");
3002 		notice = 1;
3003 	}
3004 
3005 	type = CLK_TYPE(peer);
3006 	unit = CLK_UNIT(peer);
3007 
3008 	if ((type == (u_int)~0) || (parse_clockinfo[type].cl_description == (char *)0))
3009 	{
3010 		msyslog(LOG_ERR, "PARSE receiver #%d: parse_start: unsupported clock type %d (max %d)",
3011 			unit, CLK_REALTYPE(peer), ncltypes-1);
3012 		return 0;
3013 	}
3014 
3015 	/*
3016 	 * Unit okay, attempt to open the device.
3017 	 */
3018 	(void) snprintf(parsedev, sizeof(parsedev), PARSEDEVICE, unit);
3019 	(void) snprintf(parseppsdev, sizeof(parsedev), PARSEPPSDEVICE, unit);
3020 
3021 #ifndef O_NOCTTY
3022 #define O_NOCTTY 0
3023 #endif
3024 #ifndef O_NONBLOCK
3025 #define O_NONBLOCK 0
3026 #endif
3027 
3028 	fd232 = tty_open(parsedev, O_RDWR | O_NOCTTY | O_NONBLOCK, 0777);
3029 
3030 	if (fd232 == -1)
3031 	{
3032 		msyslog(LOG_ERR, "PARSE receiver #%d: parse_start: open of %s failed: %m", unit, parsedev);
3033 		return 0;
3034 	}
3035 
3036 	parse = emalloc_zero(sizeof(*parse));
3037 
3038 	parse->generic = peer->procptr;	 /* link up */
3039 	parse->generic->unitptr = (caddr_t)parse; /* link down */
3040 
3041 	/*
3042 	 * Set up the structures
3043 	 */
3044 	parse->generic->timestarted    = current_time;
3045 	parse->lastchange     = current_time;
3046 
3047 	parse->flags          = 0;
3048 	parse->pollneeddata   = 0;
3049 	parse->laststatistic  = current_time;
3050 	parse->lastformat     = (unsigned short)~0;	/* assume no format known */
3051 	parse->timedata.parse_status = (unsigned short)~0;	/* be sure to mark initial status change */
3052 	parse->lastmissed     = 0;	/* assume got everything */
3053 	parse->ppsserial      = 0;
3054 	parse->ppsfd	      = -1;
3055 	parse->localdata      = (void *)0;
3056 	parse->localstate     = 0;
3057 	parse->kv             = (struct ctl_var *)0;
3058 
3059 	clear_err(parse, ERR_ALL);
3060 
3061 	parse->parse_type     = &parse_clockinfo[type];
3062 
3063 	parse->maxunsync      = parse->parse_type->cl_maxunsync;
3064 
3065 	parse->generic->fudgetime1 = parse->parse_type->cl_basedelay;
3066 
3067 	parse->generic->fudgetime2 = 0.0;
3068 	parse->ppsphaseadjust = parse->generic->fudgetime2;
3069 
3070 	parse->generic->clockdesc  = parse->parse_type->cl_description;
3071 
3072 	peer->rootdelay       = parse->parse_type->cl_rootdelay;
3073 	peer->sstclktype      = parse->parse_type->cl_type;
3074 	peer->precision       = sys_precision;
3075 
3076 	peer->stratum         = STRATUM_REFCLOCK;
3077 
3078 	if (peer->stratum <= 1)
3079 	    memmove((char *)&parse->generic->refid, parse->parse_type->cl_id, 4);
3080 	else
3081 	    parse->generic->refid = htonl(PARSEHSREFID);
3082 
3083 	parse->generic->io.fd = fd232;
3084 
3085 	parse->peer = peer;		/* marks it also as busy */
3086 
3087 	/*
3088 	 * configure terminal line
3089 	 */
3090 	if (TTY_GETATTR(fd232, &tio) == -1)
3091 	{
3092 		msyslog(LOG_ERR, "PARSE receiver #%d: parse_start: tcgetattr(%d, &tio): %m", unit, fd232);
3093 		parse_shutdown(CLK_UNIT(parse->peer), peer); /* let our cleaning staff do the work */
3094 		return 0;
3095 	}
3096 	else
3097 	{
3098 #ifndef _PC_VDISABLE
3099 		memset((char *)tio.c_cc, 0, sizeof(tio.c_cc));
3100 #else
3101 		int disablec;
3102 		errno = 0;		/* pathconf can deliver -1 without changing errno ! */
3103 
3104 		disablec = fpathconf(parse->generic->io.fd, _PC_VDISABLE);
3105 		if (disablec == -1 && errno)
3106 		{
3107 			msyslog(LOG_ERR, "PARSE receiver #%d: parse_start: fpathconf(fd, _PC_VDISABLE): %m", CLK_UNIT(parse->peer));
3108 			memset((char *)tio.c_cc, 0, sizeof(tio.c_cc)); /* best guess */
3109 		}
3110 		else
3111 		    if (disablec != -1)
3112 			memset((char *)tio.c_cc, disablec, sizeof(tio.c_cc));
3113 #endif
3114 
3115 #if defined (VMIN) || defined(VTIME)
3116 		if ((parse_clockinfo[type].cl_lflag & ICANON) == 0)
3117 		{
3118 #ifdef VMIN
3119 			tio.c_cc[VMIN]   = 1;
3120 #endif
3121 #ifdef VTIME
3122 			tio.c_cc[VTIME]  = 0;
3123 #endif
3124 		}
3125 #endif
3126 
3127 		tio.c_cflag = (tcflag_t) parse_clockinfo[type].cl_cflag;
3128 		tio.c_iflag = (tcflag_t) parse_clockinfo[type].cl_iflag;
3129 		tio.c_oflag = (tcflag_t) parse_clockinfo[type].cl_oflag;
3130 		tio.c_lflag = (tcflag_t) parse_clockinfo[type].cl_lflag;
3131 
3132 
3133 #ifdef HAVE_TERMIOS
3134 		if ((cfsetospeed(&tio, (speed_t) parse_clockinfo[type].cl_speed) == -1) ||
3135 		    (cfsetispeed(&tio, (speed_t) parse_clockinfo[type].cl_speed) == -1))
3136 		{
3137 			msyslog(LOG_ERR, "PARSE receiver #%d: parse_start: tcset{i,o}speed(&tio, speed): %m", unit);
3138 			parse_shutdown(CLK_UNIT(parse->peer), peer); /* let our cleaning staff do the work */
3139 			return 0;
3140 		}
3141 #else
3142 		tio.c_cflag     |= parse_clockinfo[type].cl_speed;
3143 #endif
3144 
3145 		/*
3146 		 * set up pps device
3147 		 * if the PARSEPPSDEVICE can be opened that will be used
3148 		 * for PPS else PARSEDEVICE will be used
3149 		 */
3150 		parse->ppsfd = tty_open(parseppsdev, O_RDWR | O_NOCTTY | O_NONBLOCK, 0777);
3151 
3152 		if (parse->ppsfd == -1)
3153 		{
3154 			parse->ppsfd = fd232;
3155 		}
3156 
3157 /*
3158  * Linux PPS - the old way
3159  */
3160 #if defined(HAVE_TIO_SERIAL_STUFF)		/* Linux hack: define PPS interface */
3161 		{
3162 			struct serial_struct	ss;
3163 			if (ioctl(parse->ppsfd, TIOCGSERIAL, &ss) < 0 ||
3164 			    (
3165 #ifdef ASYNC_LOW_LATENCY
3166 			     ss.flags |= ASYNC_LOW_LATENCY,
3167 #endif
3168 #ifndef HAVE_PPSAPI
3169 #ifdef ASYNC_PPS_CD_NEG
3170 			     ss.flags |= ASYNC_PPS_CD_NEG,
3171 #endif
3172 #endif
3173 			     ioctl(parse->ppsfd, TIOCSSERIAL, &ss)) < 0) {
3174 				msyslog(LOG_NOTICE, "refclock_parse: TIOCSSERIAL fd %d, %m", parse->ppsfd);
3175 				msyslog(LOG_NOTICE,
3176 					"refclock_parse: optional PPS processing not available");
3177 			} else {
3178 				parse->flags    |= PARSE_PPSCLOCK;
3179 #ifdef ASYNC_PPS_CD_NEG
3180 				NLOG(NLOG_CLOCKINFO)
3181 				  msyslog(LOG_INFO,
3182 					  "refclock_parse: PPS detection on");
3183 #endif
3184 			}
3185 		}
3186 #endif
3187 
3188 /*
3189  * SUN the Solaris way
3190  */
3191 #ifdef HAVE_TIOCSPPS			/* SUN PPS support */
3192 		if (CLK_PPS(parse->peer))
3193 		    {
3194 			int i = 1;
3195 
3196 			if (ioctl(parse->ppsfd, TIOCSPPS, (caddr_t)&i) == 0)
3197 			    {
3198 				parse->flags |= PARSE_PPSCLOCK;
3199 			    }
3200 		    }
3201 #endif
3202 
3203 /*
3204  * PPS via PPSAPI
3205  */
3206 #if defined(HAVE_PPSAPI)
3207 		parse->hardppsstate = PARSE_HARDPPS_DISABLE;
3208 		if (CLK_PPS(parse->peer))
3209 		{
3210 		  if (!refclock_ppsapi(parse->ppsfd, &parse->atom))
3211 		    {
3212 		      msyslog(LOG_NOTICE, "PARSE receiver #%d: parse_start: could not set up PPS: %m", CLK_UNIT(parse->peer));
3213 		    }
3214 		  else
3215 		    {
3216 		      parse_ppsapi(parse);
3217 		    }
3218 		}
3219 #endif
3220 
3221 		if (TTY_SETATTR(fd232, &tio) == -1)
3222 		{
3223 			msyslog(LOG_ERR, "PARSE receiver #%d: parse_start: tcsetattr(%d, &tio): %m", unit, fd232);
3224 			parse_shutdown(CLK_UNIT(parse->peer), peer); /* let our cleaning staff do the work */
3225 			return 0;
3226 		}
3227 	}
3228 
3229 	/*
3230 	 * pick correct input machine
3231 	 */
3232 	parse->generic->io.srcclock = peer;
3233 	parse->generic->io.datalen = 0;
3234 
3235 	parse->binding = init_iobinding(parse);
3236 
3237 	if (parse->binding == (bind_t *)0)
3238 		{
3239 			msyslog(LOG_ERR, "PARSE receiver #%d: parse_start: io sub system initialisation failed.", CLK_UNIT(parse->peer));
3240 			parse_shutdown(CLK_UNIT(parse->peer), peer); /* let our cleaning staff do the work */
3241 			return 0;			/* well, ok - special initialisation broke */
3242 		}
3243 
3244 	parse->generic->io.clock_recv = parse->binding->bd_receive; /* pick correct receive routine */
3245 	parse->generic->io.io_input   = parse->binding->bd_io_input; /* pick correct input routine */
3246 
3247 	/*
3248 	 * as we always(?) get 8 bit chars we want to be
3249 	 * sure, that the upper bits are zero for less
3250 	 * than 8 bit I/O - so we pass that information on.
3251 	 * note that there can be only one bit count format
3252 	 * per file descriptor
3253 	 */
3254 
3255 	switch (tio.c_cflag & CSIZE)
3256 	{
3257 	    case CS5:
3258 		tmp_ctl.parsesetcs.parse_cs = PARSE_IO_CS5;
3259 		break;
3260 
3261 	    case CS6:
3262 		tmp_ctl.parsesetcs.parse_cs = PARSE_IO_CS6;
3263 		break;
3264 
3265 	    case CS7:
3266 		tmp_ctl.parsesetcs.parse_cs = PARSE_IO_CS7;
3267 		break;
3268 
3269 	    case CS8:
3270 		tmp_ctl.parsesetcs.parse_cs = PARSE_IO_CS8;
3271 		break;
3272 	}
3273 
3274 	if (!PARSE_SETCS(parse, &tmp_ctl))
3275 	{
3276 		msyslog(LOG_ERR, "PARSE receiver #%d: parse_start: parse_setcs() FAILED.", unit);
3277 		parse_shutdown(CLK_UNIT(parse->peer), peer); /* let our cleaning staff do the work */
3278 		return 0;			/* well, ok - special initialisation broke */
3279 	}
3280 
3281 	strlcpy(tmp_ctl.parseformat.parse_buffer, parse->parse_type->cl_format, sizeof(tmp_ctl.parseformat.parse_buffer));
3282 	tmp_ctl.parseformat.parse_count = (u_short) strlen(tmp_ctl.parseformat.parse_buffer);
3283 
3284 	if (!PARSE_SETFMT(parse, &tmp_ctl))
3285 	{
3286 		msyslog(LOG_ERR, "PARSE receiver #%d: parse_start: parse_setfmt() FAILED.", unit);
3287 		parse_shutdown(CLK_UNIT(parse->peer), peer); /* let our cleaning staff do the work */
3288 		return 0;			/* well, ok - special initialisation broke */
3289 	}
3290 
3291 	/*
3292 	 * get rid of all IO accumulated so far
3293 	 */
3294 #ifdef HAVE_TERMIOS
3295 	(void) tcflush(parse->generic->io.fd, TCIOFLUSH);
3296 #else
3297 #if defined(TCFLSH) && defined(TCIOFLUSH)
3298 	{
3299 		int flshcmd = TCIOFLUSH;
3300 
3301 		(void) ioctl(parse->generic->io.fd, TCFLSH, (caddr_t)&flshcmd);
3302 	}
3303 #endif
3304 #endif
3305 
3306 	/*
3307 	 * try to do any special initializations
3308 	 */
3309 	if (parse->parse_type->cl_init)
3310 		{
3311 			if (parse->parse_type->cl_init(parse))
3312 				{
3313 					parse_shutdown(CLK_UNIT(parse->peer), peer); /* let our cleaning staff do the work */
3314 					return 0;		/* well, ok - special initialisation broke */
3315 				}
3316 		}
3317 
3318 	/*
3319 	 * Insert in async io device list.
3320 	 */
3321 	if (!io_addclock(&parse->generic->io))
3322         {
3323 		msyslog(LOG_ERR,
3324 			"PARSE receiver #%d: parse_start: addclock %s fails (ABORT - clock type requires async io)", CLK_UNIT(parse->peer), parsedev);
3325 		parse_shutdown(CLK_UNIT(parse->peer), peer); /* let our cleaning staff do the work */
3326 		return 0;
3327 	}
3328 
3329 	/*
3330 	 * print out configuration
3331 	 */
3332 	NLOG(NLOG_CLOCKINFO)
3333 		{
3334 			/* conditional if clause for conditional syslog */
3335 			msyslog(LOG_INFO, "PARSE receiver #%d: reference clock \"%s\" (I/O device %s, PPS device %s) added",
3336 				CLK_UNIT(parse->peer),
3337 				parse->parse_type->cl_description, parsedev,
3338 				(parse->ppsfd != parse->generic->io.fd) ? parseppsdev : parsedev);
3339 
3340 			msyslog(LOG_INFO, "PARSE receiver #%d: Stratum %d, trust time %s, precision %d",
3341 				CLK_UNIT(parse->peer),
3342 				parse->peer->stratum,
3343 				l_mktime(parse->maxunsync), parse->peer->precision);
3344 
3345 			msyslog(LOG_INFO, "PARSE receiver #%d: rootdelay %.6f s, phase adjustment %.6f s, PPS phase adjustment %.6f s, %s IO handling",
3346 				CLK_UNIT(parse->peer),
3347 				parse->parse_type->cl_rootdelay,
3348 				parse->generic->fudgetime1,
3349 				parse->ppsphaseadjust,
3350                                 parse->binding->bd_description);
3351 
3352 			msyslog(LOG_INFO, "PARSE receiver #%d: Format recognition: %s", CLK_UNIT(parse->peer),
3353 				parse->parse_type->cl_format);
3354                         msyslog(LOG_INFO, "PARSE receiver #%d: %sPPS support%s", CLK_UNIT(parse->peer),
3355 				CLK_PPS(parse->peer) ? "" : "NO ",
3356 				CLK_PPS(parse->peer) ?
3357 #ifdef PPS_METHOD
3358 				" (implementation " PPS_METHOD ")"
3359 #else
3360 				""
3361 #endif
3362 				: ""
3363 				);
3364 		}
3365 
3366 	return 1;
3367 }
3368 
3369 /*--------------------------------------------------
3370  * parse_ctl - process changes on flags/time values
3371  */
3372 static void
3373 parse_ctl(
3374 	    struct parseunit *parse,
3375 	    const struct refclockstat *in
3376 	    )
3377 {
3378         if (in)
3379 	{
3380 		if (in->haveflags & (CLK_HAVEFLAG1|CLK_HAVEFLAG2|CLK_HAVEFLAG3|CLK_HAVEFLAG4))
3381 		{
3382 		  u_char mask = CLK_FLAG1|CLK_FLAG2|CLK_FLAG3|CLK_FLAG4;
3383 		  parse->flags = (parse->flags & (u_char)(~mask)) | (in->flags & mask);
3384 #if defined(HAVE_PPSAPI)
3385 		  if (CLK_PPS(parse->peer))
3386 		    {
3387 		      parse_ppsapi(parse);
3388 		    }
3389 #endif
3390 		}
3391 
3392 		if (in->haveflags & CLK_HAVETIME1)
3393                 {
3394 		  parse->generic->fudgetime1 = in->fudgetime1;
3395 		  msyslog(LOG_INFO, "PARSE receiver #%d: new phase adjustment %.6f s",
3396 			  CLK_UNIT(parse->peer),
3397 			  parse->generic->fudgetime1);
3398 		}
3399 
3400 		if (in->haveflags & CLK_HAVETIME2)
3401                 {
3402 		  parse->generic->fudgetime2 = in->fudgetime2;
3403 		  if (parse->flags & PARSE_TRUSTTIME)
3404 		    {
3405 		      parse->maxunsync = (u_long)ABS(in->fudgetime2);
3406 		      msyslog(LOG_INFO, "PARSE receiver #%d: new trust time %s",
3407 			      CLK_UNIT(parse->peer),
3408 			      l_mktime(parse->maxunsync));
3409 		    }
3410 		  else
3411 		    {
3412 		      parse->ppsphaseadjust = in->fudgetime2;
3413 		      msyslog(LOG_INFO, "PARSE receiver #%d: new PPS phase adjustment %.6f s",
3414 			  CLK_UNIT(parse->peer),
3415 			      parse->ppsphaseadjust);
3416 #if defined(HAVE_PPSAPI)
3417 		      if (CLK_PPS(parse->peer))
3418 		      {
3419 			      parse_ppsapi(parse);
3420 		      }
3421 #endif
3422 		    }
3423 		}
3424 	}
3425 }
3426 
3427 /*--------------------------------------------------
3428  * parse_poll - called by the transmit procedure
3429  */
3430 static void
3431 parse_poll(
3432 	int unit,
3433 	struct peer *peer
3434 	)
3435 {
3436 	struct parseunit *parse = peer->procptr->unitptr;
3437 
3438 	if (peer != parse->peer)
3439 	{
3440 		msyslog(LOG_ERR,
3441 			"PARSE receiver #%d: poll: INTERNAL: peer incorrect",
3442 			unit);
3443 		return;
3444 	}
3445 
3446 	/*
3447 	 * Update clock stat counters
3448 	 */
3449 	parse->generic->polls++;
3450 
3451 	if (parse->pollneeddata &&
3452 	    ((int)(current_time - parse->pollneeddata) > (1<<(max(min(parse->peer->hpoll, parse->peer->ppoll), parse->peer->minpoll)))))
3453 	{
3454 		/*
3455 		 * start worrying when exceeding a poll inteval
3456 		 * bad news - didn't get a response last time
3457 		 */
3458 		parse->lastmissed = current_time;
3459 		parse_event(parse, CEVNT_TIMEOUT);
3460 
3461 		ERR(ERR_NODATA)
3462 			msyslog(LOG_WARNING, "PARSE receiver #%d: no data from device within poll interval (check receiver / wiring)", CLK_UNIT(parse->peer));
3463 	}
3464 
3465 	/*
3466 	 * we just mark that we want the next sample for the clock filter
3467 	 */
3468 	parse->pollneeddata = current_time;
3469 
3470 	if (parse->parse_type->cl_poll)
3471 	{
3472 		parse->parse_type->cl_poll(parse);
3473 	}
3474 
3475 	cparse_statistics(parse);
3476 
3477 	return;
3478 }
3479 
3480 #define LEN_STATES 300		/* length of state string */
3481 
3482 /*--------------------------------------------------
3483  * parse_control - set fudge factors, return statistics
3484  */
3485 static void
3486 parse_control(
3487 	int unit,
3488 	const struct refclockstat *in,
3489 	struct refclockstat *out,
3490 	struct peer *peer
3491 	)
3492 {
3493 	struct parseunit *parse = peer->procptr->unitptr;
3494 	parsectl_t tmpctl;
3495 
3496 	static char outstatus[400];	/* status output buffer */
3497 
3498 	if (out)
3499 	{
3500 		out->lencode       = 0;
3501 		out->p_lastcode    = 0;
3502 		out->kv_list       = (struct ctl_var *)0;
3503 	}
3504 
3505 	if (!parse || !parse->peer)
3506 	{
3507 		msyslog(LOG_ERR, "PARSE receiver #%d: parse_control: unit invalid (UNIT INACTIVE)",
3508 			unit);
3509 		return;
3510 	}
3511 
3512 	unit = CLK_UNIT(parse->peer);
3513 
3514 	/*
3515 	 * handle changes
3516 	 */
3517 	parse_ctl(parse, in);
3518 
3519 	/*
3520 	 * supply data
3521 	 */
3522 	if (out)
3523 	{
3524 		u_long sum = 0;
3525 		char *tt, *start;
3526 		int i;
3527 
3528 		outstatus[0] = '\0';
3529 
3530 		out->type       = REFCLK_PARSE;
3531 
3532 		/*
3533 		 * keep fudgetime2 in sync with TRUSTTIME/MAXUNSYNC flag1
3534 		 */
3535 		parse->generic->fudgetime2 = (parse->flags & PARSE_TRUSTTIME) ? (double)parse->maxunsync : parse->ppsphaseadjust;
3536 
3537 		/*
3538 		 * figure out skew between PPS and RS232 - just for informational
3539 		 * purposes
3540 		 */
3541 		if (PARSE_SYNC(parse->timedata.parse_state))
3542 		{
3543 			if (PARSE_PPS(parse->timedata.parse_state) && PARSE_TIMECODE(parse->timedata.parse_state))
3544 			{
3545 				l_fp off;
3546 
3547 				/*
3548 				 * we have a PPS and RS232 signal - calculate the skew
3549 				 * WARNING: assumes on TIMECODE == PULSE (timecode after pulse)
3550 				 */
3551 				off = parse->timedata.parse_stime.fp;
3552 				L_SUB(&off, &parse->timedata.parse_ptime.fp); /* true offset */
3553 				tt = add_var(&out->kv_list, 80, RO);
3554 				snprintf(tt, 80, "refclock_ppsskew=%s", lfptoms(&off, 6));
3555 			}
3556 		}
3557 
3558 		if (PARSE_PPS(parse->timedata.parse_state))
3559 		{
3560 			tt = add_var(&out->kv_list, 80, RO|DEF);
3561 			snprintf(tt, 80, "refclock_ppstime=\"%s\"", gmprettydate(&parse->timedata.parse_ptime.fp));
3562 		}
3563 
3564 		start = tt = add_var(&out->kv_list, 128, RO|DEF);
3565 		tt = ap(start, 128, tt, "refclock_time=\"");
3566 
3567 		if (parse->timedata.parse_time.fp.l_ui == 0)
3568 		{
3569 			tt = ap(start, 128, tt, "<UNDEFINED>\"");
3570 		}
3571 		else
3572 		{
3573 			tt = ap(start, 128, tt, "%s\"",
3574 			    gmprettydate(&parse->timedata.parse_time.fp));
3575 		}
3576 
3577 		if (!PARSE_GETTIMECODE(parse, &tmpctl))
3578 		{
3579 			ERR(ERR_INTERNAL)
3580 				msyslog(LOG_ERR, "PARSE receiver #%d: parse_control: parse_timecode() FAILED", unit);
3581 		}
3582 		else
3583 		{
3584 			start = tt = add_var(&out->kv_list, 512, RO|DEF);
3585 			tt = ap(start, 512, tt, "refclock_status=\"");
3586 
3587 			/*
3588 			 * copy PPS flags from last read transaction (informational only)
3589 			 */
3590 			tmpctl.parsegettc.parse_state |= parse->timedata.parse_state &
3591 				(PARSEB_PPS|PARSEB_S_PPS);
3592 
3593 			(void)parsestate(tmpctl.parsegettc.parse_state, tt, BUFFER_SIZES(start, tt, 512));
3594 
3595 			tt += strlen(tt);
3596 
3597 			tt = ap(start, 512, tt, "\"");
3598 
3599 			if (tmpctl.parsegettc.parse_count)
3600 			    mkascii(outstatus+strlen(outstatus), (int)(sizeof(outstatus)- strlen(outstatus) - 1),
3601 				    tmpctl.parsegettc.parse_buffer, (unsigned)(tmpctl.parsegettc.parse_count));
3602 
3603 		}
3604 
3605 		tmpctl.parseformat.parse_format = tmpctl.parsegettc.parse_format;
3606 
3607 		if (!PARSE_GETFMT(parse, &tmpctl))
3608 		{
3609 			ERR(ERR_INTERNAL)
3610 				msyslog(LOG_ERR, "PARSE receiver #%d: parse_control: parse_getfmt() FAILED", unit);
3611 		}
3612 		else
3613 		{
3614 			int count = tmpctl.parseformat.parse_count - 1;
3615 
3616 			start = tt = add_var(&out->kv_list, 80, RO|DEF);
3617 			tt = ap(start, 80, tt, "refclock_format=\"");
3618 
3619 			if (count > 0) {
3620 				tt = ap(start, 80, tt, "%*.*s",
3621 			        	count,
3622 			        	count,
3623 			        	tmpctl.parseformat.parse_buffer);
3624 			}
3625 
3626 			tt = ap(start, 80, tt, "\"");
3627 		}
3628 
3629 		/*
3630 		 * gather state statistics
3631 		 */
3632 
3633 		start = tt = add_var(&out->kv_list, LEN_STATES, RO|DEF);
3634 		tt = ap(start, LEN_STATES, tt, "refclock_states=\"");
3635 
3636 		for (i = 0; i <= CEVNT_MAX; i++)
3637 		{
3638 			u_long s_time;
3639 			u_long d = current_time - parse->generic->timestarted;
3640 			u_long percent;
3641 
3642 			percent = s_time = PARSE_STATETIME(parse, i);
3643 
3644 			while (((u_long)(~0) / 10000) < percent)
3645 			{
3646 				percent /= 10;
3647 				d       /= 10;
3648 			}
3649 
3650 			if (d)
3651 			    percent = (percent * 10000) / d;
3652 			else
3653 			    percent = 10000;
3654 
3655 			if (s_time)
3656 			{
3657 				char item[80];
3658 				int count;
3659 
3660 				snprintf(item, 80, "%s%s%s: %s (%d.%02d%%)",
3661 					sum ? "; " : "",
3662 					(parse->generic->currentstatus == i) ? "*" : "",
3663 					clockstatus((unsigned int)i),
3664 					l_mktime(s_time),
3665 					(int)(percent / 100), (int)(percent % 100));
3666 				if ((count = (int) strlen(item)) < (LEN_STATES - 40 - (tt - start)))
3667 					{
3668 						tt = ap(start, LEN_STATES, tt,
3669 						    "%s", item);
3670 					}
3671 				sum += s_time;
3672 			}
3673 		}
3674 
3675 		tt = ap(start, LEN_STATES, tt,
3676 		    "; running time: %s\"", l_mktime(sum));
3677 
3678 		tt = add_var(&out->kv_list, 32, RO);
3679 		snprintf(tt, 32,  "refclock_id=\"%s\"", parse->parse_type->cl_id);
3680 
3681 		tt = add_var(&out->kv_list, 80, RO);
3682 		snprintf(tt, 80,  "refclock_iomode=\"%s\"", parse->binding->bd_description);
3683 
3684 		tt = add_var(&out->kv_list, 128, RO);
3685 		snprintf(tt, 128, "refclock_driver_version=\"%s\"", rcsid);
3686 
3687 		{
3688 			struct ctl_var *k;
3689 
3690 			k = parse->kv;
3691 			while (k && !(k->flags & EOV))
3692 			{
3693 				set_var(&out->kv_list, k->text, strlen(k->text)+1, k->flags);
3694 				k++;
3695 			}
3696 		}
3697 
3698 		out->lencode       = (u_short) strlen(outstatus);
3699 		out->p_lastcode    = outstatus;
3700 	}
3701 }
3702 
3703 /**===========================================================================
3704  ** processing routines
3705  **/
3706 
3707 /*--------------------------------------------------
3708  * event handling - note that nominal events will also be posted
3709  * keep track of state dwelling times
3710  */
3711 static void
3712 parse_event(
3713 	struct parseunit *parse,
3714 	int event
3715 	)
3716 {
3717 	if (parse->generic->currentstatus != (u_char) event)
3718 	{
3719 		parse->statetime[parse->generic->currentstatus] += current_time - parse->lastchange;
3720 		parse->lastchange              = current_time;
3721 
3722 		if (parse->parse_type->cl_event)
3723 		    parse->parse_type->cl_event(parse, event);
3724 
3725 		if (event == CEVNT_NOMINAL)
3726 		{
3727 			NLOG(NLOG_CLOCKSTATUS)
3728 				msyslog(LOG_INFO, "PARSE receiver #%d: SYNCHRONIZED",
3729 					CLK_UNIT(parse->peer));
3730 		}
3731 
3732 		refclock_report(parse->peer, event);
3733 	}
3734 }
3735 
3736 /*--------------------------------------------------
3737  * process a PARSE time sample
3738  */
3739 static void
3740 parse_process(
3741 	struct parseunit *parse,
3742 	parsetime_t      *parsetime
3743 	)
3744 {
3745 	l_fp off, rectime, reftime;
3746 	double fudge;
3747 
3748 	/* silence warning: 'off.Ul_i.Xl_i' may be used uninitialized in this function */
3749 	ZERO(off);
3750 
3751 	/*
3752 	 * check for changes in conversion status
3753 	 * (only one for each new status !)
3754 	 */
3755 	if (((parsetime->parse_status & CVT_MASK) != CVT_OK) &&
3756 	    ((parsetime->parse_status & CVT_MASK) != CVT_NONE) &&
3757 	    (parse->timedata.parse_status != parsetime->parse_status))
3758 	{
3759 		char buffer[400];
3760 
3761 		NLOG(NLOG_CLOCKINFO) /* conditional if clause for conditional syslog */
3762 			msyslog(LOG_WARNING, "PARSE receiver #%d: conversion status \"%s\"",
3763 				CLK_UNIT(parse->peer), parsestatus(parsetime->parse_status, buffer, sizeof(buffer)));
3764 
3765 		if ((parsetime->parse_status & CVT_MASK) == CVT_FAIL)
3766 		{
3767 			/*
3768 			 * tell more about the story - list time code
3769 			 * there is a slight change for a race condition and
3770 			 * the time code might be overwritten by the next packet
3771 			 */
3772 			parsectl_t tmpctl;
3773 
3774 			if (!PARSE_GETTIMECODE(parse, &tmpctl))
3775 			{
3776 				ERR(ERR_INTERNAL)
3777 					msyslog(LOG_ERR, "PARSE receiver #%d: parse_process: parse_timecode() FAILED", CLK_UNIT(parse->peer));
3778 			}
3779 			else
3780 			{
3781 				ERR(ERR_BADDATA)
3782 					msyslog(LOG_WARNING, "PARSE receiver #%d: FAILED TIMECODE: \"%s\" (check receiver configuration / wiring)",
3783 						CLK_UNIT(parse->peer), mkascii(buffer, sizeof buffer, tmpctl.parsegettc.parse_buffer, (unsigned)(tmpctl.parsegettc.parse_count - 1)));
3784 			}
3785 		}
3786 	}
3787 
3788 	/*
3789 	 * examine status and post appropriate events
3790 	 */
3791 	if ((parsetime->parse_status & CVT_MASK) != CVT_OK)
3792 	{
3793 		/*
3794 		 * got bad data - tell the rest of the system
3795 		 */
3796 		switch (parsetime->parse_status & CVT_MASK)
3797 		{
3798 		case CVT_NONE:
3799 			if ((parsetime->parse_status & CVT_ADDITIONAL) &&
3800 			    parse->parse_type->cl_message)
3801 				parse->parse_type->cl_message(parse, parsetime);
3802 			/*
3803 			 * save PPS information that comes piggyback
3804 			 */
3805 			if (PARSE_PPS(parsetime->parse_state))
3806 			  {
3807 			    parse->timedata.parse_state |= PARSEB_PPS|PARSEB_S_PPS;
3808 			    parse->timedata.parse_ptime  = parsetime->parse_ptime;
3809 			  }
3810 			break; 		/* well, still waiting - timeout is handled at higher levels */
3811 
3812 		case CVT_FAIL:
3813 			if (parsetime->parse_status & CVT_BADFMT)
3814 			{
3815 				parse_event(parse, CEVNT_BADREPLY);
3816 			}
3817 			else
3818 				if (parsetime->parse_status & CVT_BADDATE)
3819 				{
3820 					parse_event(parse, CEVNT_BADDATE);
3821 				}
3822 				else
3823 					if (parsetime->parse_status & CVT_BADTIME)
3824 					{
3825 						parse_event(parse, CEVNT_BADTIME);
3826 					}
3827 					else
3828 					{
3829 						parse_event(parse, CEVNT_BADREPLY); /* for the lack of something better */
3830 					}
3831 		}
3832 		return;			/* skip the rest - useless */
3833 	}
3834 
3835 	/*
3836 	 * check for format changes
3837 	 * (in case somebody has swapped clocks 8-)
3838 	 */
3839 	if (parse->lastformat != parsetime->parse_format)
3840 	{
3841 		parsectl_t tmpctl;
3842 
3843 		tmpctl.parseformat.parse_format = parsetime->parse_format;
3844 
3845 		if (!PARSE_GETFMT(parse, &tmpctl))
3846 		{
3847 			ERR(ERR_INTERNAL)
3848 				msyslog(LOG_ERR, "PARSE receiver #%d: parse_getfmt() FAILED", CLK_UNIT(parse->peer));
3849 		}
3850 		else
3851 		{
3852 			NLOG(NLOG_CLOCKINFO) /* conditional if clause for conditional syslog */
3853 				msyslog(LOG_INFO, "PARSE receiver #%d: packet format \"%s\"",
3854 					CLK_UNIT(parse->peer), tmpctl.parseformat.parse_buffer);
3855 		}
3856 		parse->lastformat = parsetime->parse_format;
3857 	}
3858 
3859 	/*
3860 	 * now, any changes ?
3861 	 */
3862 	if ((parse->timedata.parse_state ^ parsetime->parse_state) &
3863 	    ~(unsigned)(PARSEB_PPS|PARSEB_S_PPS))
3864 	{
3865 		char tmp1[200];
3866 		char tmp2[200];
3867 		/*
3868 		 * something happend - except for PPS events
3869 		 */
3870 
3871 		(void) parsestate(parsetime->parse_state, tmp1, sizeof(tmp1));
3872 		(void) parsestate(parse->timedata.parse_state, tmp2, sizeof(tmp2));
3873 
3874 		NLOG(NLOG_CLOCKINFO) /* conditional if clause for conditional syslog */
3875 			msyslog(LOG_INFO,"PARSE receiver #%d: STATE CHANGE: %s -> %s",
3876 				CLK_UNIT(parse->peer), tmp2, tmp1);
3877 	}
3878 
3879 	/*
3880 	 * carry on PPS information if still usable
3881 	 */
3882 	if (PARSE_PPS(parse->timedata.parse_state) && !PARSE_PPS(parsetime->parse_state))
3883         {
3884 	        parsetime->parse_state |= PARSEB_PPS|PARSEB_S_PPS;
3885 		parsetime->parse_ptime  = parse->timedata.parse_ptime;
3886 	}
3887 
3888 	/*
3889 	 * remember for future
3890 	 */
3891 	parse->timedata = *parsetime;
3892 
3893 	/*
3894 	 * check to see, whether the clock did a complete powerup or lost PZF signal
3895 	 * and post correct events for current condition
3896 	 */
3897 	if (PARSE_POWERUP(parsetime->parse_state))
3898 	{
3899 		/*
3900 		 * this is bad, as we have completely lost synchronisation
3901 		 * well this is a problem with the receiver here
3902 		 * for PARSE Meinberg DCF77 receivers the lost synchronisation
3903 		 * is true as it is the powerup state and the time is taken
3904 		 * from a crude real time clock chip
3905 		 * for the PZF/GPS series this is only partly true, as
3906 		 * PARSE_POWERUP only means that the pseudo random
3907 		 * phase shift sequence cannot be found. this is only
3908 		 * bad, if we have never seen the clock in the SYNC
3909 		 * state, where the PHASE and EPOCH are correct.
3910 		 * for reporting events the above business does not
3911 		 * really matter, but we can use the time code
3912 		 * even in the POWERUP state after having seen
3913 		 * the clock in the synchronized state (PZF class
3914 		 * receivers) unless we have had a telegram disruption
3915 		 * after having seen the clock in the SYNC state. we
3916 		 * thus require having seen the clock in SYNC state
3917 		 * *after* having missed telegrams (noresponse) from
3918 		 * the clock. one problem remains: we might use erroneously
3919 		 * POWERUP data if the disruption is shorter than 1 polling
3920 		 * interval. fortunately powerdowns last usually longer than 64
3921 		 * seconds and the receiver is at least 2 minutes in the
3922 		 * POWERUP or NOSYNC state before switching to SYNC
3923 		 * for GPS receivers this can mean antenna problems and other causes.
3924 		 * the additional grace period can be enables by a clock
3925 		 * mode having the PARSE_F_POWERUPTRUST flag in cl_flag set.
3926 		 */
3927 		parse_event(parse, CEVNT_FAULT);
3928 		NLOG(NLOG_CLOCKSTATUS)
3929 			ERR(ERR_BADSTATUS)
3930 			msyslog(LOG_ERR,"PARSE receiver #%d: NOT SYNCHRONIZED/RECEIVER PROBLEMS",
3931 				CLK_UNIT(parse->peer));
3932 	}
3933 	else
3934 	{
3935 		/*
3936 		 * we have two states left
3937 		 *
3938 		 * SYNC:
3939 		 *  this state means that the EPOCH (timecode) and PHASE
3940 		 *  information has be read correctly (at least two
3941 		 *  successive PARSE timecodes were received correctly)
3942 		 *  this is the best possible state - full trust
3943 		 *
3944 		 * NOSYNC:
3945 		 *  The clock should be on phase with respect to the second
3946 		 *  signal, but the timecode has not been received correctly within
3947 		 *  at least the last two minutes. this is a sort of half baked state
3948 		 *  for PARSE Meinberg DCF77 clocks this is bad news (clock running
3949 		 *  without timecode confirmation)
3950 		 *  PZF 535 has also no time confirmation, but the phase should be
3951 		 *  very precise as the PZF signal can be decoded
3952 		 */
3953 
3954 		if (PARSE_SYNC(parsetime->parse_state))
3955 		{
3956 			/*
3957 			 * currently completely synchronized - best possible state
3958 			 */
3959 			parse->lastsync = current_time;
3960 			clear_err(parse, ERR_BADSTATUS);
3961 		}
3962 		else
3963 		{
3964 			/*
3965 			 * we have had some problems receiving the time code
3966 			 */
3967 			parse_event(parse, CEVNT_PROP);
3968 			NLOG(NLOG_CLOCKSTATUS)
3969 				ERR(ERR_BADSTATUS)
3970 				msyslog(LOG_ERR,"PARSE receiver #%d: TIMECODE NOT CONFIRMED",
3971 					CLK_UNIT(parse->peer));
3972 		}
3973 	}
3974 
3975 	fudge = parse->generic->fudgetime1; /* standard RS232 Fudgefactor */
3976 
3977 	if (PARSE_TIMECODE(parsetime->parse_state))
3978 	{
3979 		rectime = parsetime->parse_stime.fp;
3980 		off = reftime = parsetime->parse_time.fp;
3981 
3982 		L_SUB(&off, &rectime); /* prepare for PPS adjustments logic */
3983 
3984 #ifdef DEBUG
3985 		if (debug > 3)
3986 			printf("PARSE receiver #%d: Reftime %s, Recvtime %s - initial offset %s\n",
3987 			       CLK_UNIT(parse->peer),
3988 			       prettydate(&reftime),
3989 			       prettydate(&rectime),
3990 			       lfptoa(&off,6));
3991 #endif
3992 	}
3993 
3994 	if (PARSE_PPS(parsetime->parse_state) && CLK_PPS(parse->peer))
3995 	{
3996 		l_fp offset;
3997 		double ppsphaseadjust = parse->ppsphaseadjust;
3998 
3999 #ifdef HAVE_PPSAPI
4000 		/*
4001 		 * set fudge = 0.0 if already included in PPS time stamps
4002 		 */
4003 		if (parse->atom.pps_params.mode & (PPS_OFFSETCLEAR|PPS_OFFSETASSERT))
4004 		        {
4005 			        ppsphaseadjust = 0.0;
4006 			}
4007 #endif
4008 
4009 		/*
4010 		 * we have a PPS signal - much better than the RS232 stuff (we hope)
4011 		 */
4012 		offset = parsetime->parse_ptime.fp;
4013 
4014 #ifdef DEBUG
4015 		if (debug > 3)
4016 			printf("PARSE receiver #%d: PPStime %s\n",
4017 				CLK_UNIT(parse->peer),
4018 				prettydate(&offset));
4019 #endif
4020 		if (PARSE_TIMECODE(parsetime->parse_state))
4021 		{
4022 			if (M_ISGEQ(off.l_i, off.l_uf, -1, 0x80000000) &&
4023 			    M_ISGEQ(0, 0x7fffffff, off.l_i, off.l_uf))
4024 			{
4025 				fudge = ppsphaseadjust; /* pick PPS fudge factor */
4026 
4027 				/*
4028 				 * RS232 offsets within [-0.5..0.5[ - take PPS offsets
4029 				 */
4030 
4031 				if (parse->parse_type->cl_flags & PARSE_F_PPSONSECOND)
4032 				{
4033 					reftime = off = offset;
4034 					if (reftime.l_uf & 0x80000000)
4035 						reftime.l_ui++;
4036 					reftime.l_uf = 0;
4037 
4038 
4039 					/*
4040 					 * implied on second offset
4041 					 */
4042 					off.l_uf = ~off.l_uf; /* map [0.5..1[ -> [-0.5..0[ */
4043 					off.l_i = (off.l_uf & 0x80000000) ? -1 : 0; /* sign extend */
4044 				}
4045 				else
4046 				{
4047 					/*
4048 					 * time code describes pulse
4049 					 */
4050 					reftime = off = parsetime->parse_time.fp;
4051 
4052 					L_SUB(&off, &offset); /* true offset */
4053 				}
4054 			}
4055 			/*
4056 			 * take RS232 offset when PPS when out of bounds
4057 			 */
4058 		}
4059 		else
4060 		{
4061 			fudge = ppsphaseadjust; /* pick PPS fudge factor */
4062 			/*
4063 			 * Well, no time code to guide us - assume on second pulse
4064 			 * and pray, that we are within [-0.5..0.5[
4065 			 */
4066 			off = offset;
4067 			reftime = offset;
4068 			if (reftime.l_uf & 0x80000000)
4069 				reftime.l_ui++;
4070 			reftime.l_uf = 0;
4071 			/*
4072 			 * implied on second offset
4073 			 */
4074 			off.l_uf = ~off.l_uf; /* map [0.5..1[ -> [-0.5..0[ */
4075 			off.l_i = (off.l_uf & 0x80000000) ? -1 : 0; /* sign extend */
4076 		}
4077 	}
4078 	else
4079 	{
4080 		if (!PARSE_TIMECODE(parsetime->parse_state))
4081 		{
4082 			/*
4083 			 * Well, no PPS, no TIMECODE, no more work ...
4084 			 */
4085 			if ((parsetime->parse_status & CVT_ADDITIONAL) &&
4086 			    parse->parse_type->cl_message)
4087 				parse->parse_type->cl_message(parse, parsetime);
4088 			return;
4089 		}
4090 	}
4091 
4092 #ifdef DEBUG
4093 	if (debug > 3)
4094 		printf("PARSE receiver #%d: Reftime %s, Recvtime %s - final offset %s\n",
4095 			CLK_UNIT(parse->peer),
4096 			prettydate(&reftime),
4097 			prettydate(&rectime),
4098 			lfptoa(&off,6));
4099 #endif
4100 
4101 
4102 	rectime = reftime;
4103 	L_SUB(&rectime, &off);	/* just to keep the ntp interface happy */
4104 
4105 #ifdef DEBUG
4106 	if (debug > 3)
4107 		printf("PARSE receiver #%d: calculated Reftime %s, Recvtime %s\n",
4108 			CLK_UNIT(parse->peer),
4109 			prettydate(&reftime),
4110 			prettydate(&rectime));
4111 #endif
4112 
4113 	if ((parsetime->parse_status & CVT_ADDITIONAL) &&
4114 	    parse->parse_type->cl_message)
4115 		parse->parse_type->cl_message(parse, parsetime);
4116 
4117 	if (PARSE_SYNC(parsetime->parse_state))
4118 	{
4119 		/*
4120 		 * log OK status
4121 		 */
4122 		parse_event(parse, CEVNT_NOMINAL);
4123 	}
4124 
4125 	clear_err(parse, ERR_BADIO);
4126 	clear_err(parse, ERR_BADDATA);
4127 	clear_err(parse, ERR_NODATA);
4128 	clear_err(parse, ERR_INTERNAL);
4129 
4130 	/*
4131 	 * and now stick it into the clock machine
4132 	 * samples are only valid iff lastsync is not too old and
4133 	 * we have seen the clock in sync at least once
4134 	 * after the last time we didn't see an expected data telegram
4135 	 * at startup being not in sync is also bad just like
4136 	 * POWERUP state unless PARSE_F_POWERUPTRUST is set
4137 	 * see the clock states section above for more reasoning
4138 	 */
4139 	if (((current_time - parse->lastsync) > parse->maxunsync)           ||
4140 	    (parse->lastsync < parse->lastmissed)                           ||
4141 	    ((parse->lastsync == 0) && !PARSE_SYNC(parsetime->parse_state)) ||
4142 	    (((parse->parse_type->cl_flags & PARSE_F_POWERUPTRUST) == 0) &&
4143 	     PARSE_POWERUP(parsetime->parse_state)))
4144 	{
4145 		parse->generic->leap = LEAP_NOTINSYNC;
4146 		parse->lastsync = 0;	/* wait for full sync again */
4147 	}
4148 	else
4149 	{
4150 		if (PARSE_LEAPADD(parsetime->parse_state))
4151 		{
4152 			/*
4153 			 * we pick this state also for time code that pass leap warnings
4154 			 * without direction information (as earth is currently slowing
4155 			 * down).
4156 			 */
4157 			parse->generic->leap = (parse->flags & PARSE_LEAP_DELETE) ? LEAP_DELSECOND : LEAP_ADDSECOND;
4158 		}
4159 		else
4160 		    if (PARSE_LEAPDEL(parsetime->parse_state))
4161 		    {
4162 			    parse->generic->leap = LEAP_DELSECOND;
4163 		    }
4164 		    else
4165 		    {
4166 			    parse->generic->leap = LEAP_NOWARNING;
4167 		    }
4168 	}
4169 
4170 	if (parse->generic->leap != LEAP_NOTINSYNC)
4171 	{
4172 	        /*
4173 		 * only good/trusted samples are interesting
4174 		 */
4175 #ifdef DEBUG
4176 	        if (debug > 2)
4177 			{
4178 				       printf("PARSE receiver #%d: refclock_process_offset(reftime=%s, rectime=%s, Fudge=%f)\n",
4179 				       CLK_UNIT(parse->peer),
4180 				       prettydate(&reftime),
4181 				       prettydate(&rectime),
4182 				       fudge);
4183 			}
4184 #endif
4185 		parse->generic->lastref = reftime;
4186 
4187 		refclock_process_offset(parse->generic, reftime, rectime, fudge);
4188 
4189 #ifdef HAVE_PPSAPI
4190 		/*
4191 		 * pass PPS information on to PPS clock
4192 		 */
4193 		if (PARSE_PPS(parsetime->parse_state) && CLK_PPS(parse->peer))
4194 			{
4195 				parse->peer->flags |= (FLAG_PPS | FLAG_TSTAMP_PPS);
4196 				parse_hardpps(parse, PARSE_HARDPPS_ENABLE);
4197 			}
4198 #endif
4199 	} else {
4200 		parse_hardpps(parse, PARSE_HARDPPS_DISABLE);
4201 		parse->peer->flags &= ~(FLAG_PPS | FLAG_TSTAMP_PPS);
4202 	}
4203 
4204 	/*
4205 	 * ready, unless the machine wants a sample or
4206 	 * we are in fast startup mode (peer->dist > MAXDISTANCE)
4207 	 */
4208 	if (!parse->pollneeddata && parse->peer->disp <= MAXDISTANCE)
4209 	    return;
4210 
4211 	parse->pollneeddata = 0;
4212 
4213 	parse->timedata.parse_state &= ~(unsigned)(PARSEB_PPS|PARSEB_S_PPS);
4214 
4215 	refclock_receive(parse->peer);
4216 }
4217 
4218 /**===========================================================================
4219  ** special code for special clocks
4220  **/
4221 
4222 static void
4223 mk_utcinfo(
4224 	   char *t,  // pointer to the output string buffer
4225 	   int wnt,
4226 	   int wnlsf,
4227 	   int dn,
4228 	   int dtls,
4229 	   int dtlsf,
4230 	   int size  // size of the output string buffer
4231 	   )
4232 {
4233 	/*
4234 	 * The week number transmitted by the GPS satellites for the leap date
4235 	 * is truncated to 8 bits only. If the nearest leap second date is off
4236 	 * the current date by more than +/- 128 weeks then conversion to a
4237 	 * calendar date is ambiguous. On the other hand, if a leap second is
4238 	 * currently being announced (i.e. dtlsf != dtls) then the week number
4239 	 * wnlsf is close enough, and we can unambiguously determine the date
4240 	 * for which the leap second is scheduled.
4241 	 */
4242 	if ( dtlsf != dtls )
4243 	{
4244 		time_t t_ls;
4245 		struct tm *tm;
4246 		int n = 0;
4247 
4248 		if (wnlsf < GPSWRAP)
4249 			wnlsf += GPSWEEKS;
4250 
4251 		if (wnt < GPSWRAP)
4252 			wnt += GPSWEEKS;
4253 
4254 		t_ls = (time_t) wnlsf * SECSPERWEEK
4255 			+ (time_t) dn * SECSPERDAY
4256 			+ GPS_SEC_BIAS - 1;
4257 
4258 		tm = gmtime( &t_ls );
4259 		if (tm == NULL)  // gmtime() failed
4260 		{
4261 			snprintf( t, size, "** (gmtime() failed in mk_utcinfo())" );
4262 			return;
4263 		}
4264 
4265 		n += snprintf( t, size, "UTC offset transition from %is to %is due to leap second %s",
4266 				dtls, dtlsf, ( dtls < dtlsf ) ? "insertion" : "deletion" );
4267 		n += snprintf( t + n, size - n, " at UTC midnight at the end of %s, %04i-%02i-%02i",
4268 				daynames[tm->tm_wday], tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday );
4269 	}
4270 	else
4271 		snprintf( t, size, "UTC offset parameter: %is, no leap second announced.\n", dtls );
4272 
4273 }
4274 
4275 #ifdef CLOCK_MEINBERG
4276 /**===========================================================================
4277  ** Meinberg GPS receiver support
4278  **/
4279 
4280 /*------------------------------------------------------------
4281  * gps16x_message - process messages from Meinberg GPS receiver
4282  */
4283 static void
4284 gps16x_message(
4285 	       struct parseunit *parse,
4286 	       parsetime_t      *parsetime
4287 	       )
4288 {
4289 	if (parse->timedata.parse_msglen && parsetime->parse_msg[0] == SOH)
4290 	{
4291 		GPS_MSG_HDR header;
4292 		unsigned char *bufp = (unsigned char *)parsetime->parse_msg + 1;
4293 
4294 #ifdef DEBUG
4295 		if (debug > 2)
4296 		{
4297 			char msgbuffer[600];
4298 
4299 			mkreadable(msgbuffer, sizeof(msgbuffer), (char *)parsetime->parse_msg, parsetime->parse_msglen, 1);
4300 			printf("PARSE receiver #%d: received message (%d bytes) >%s<\n",
4301 				CLK_UNIT(parse->peer),
4302 				parsetime->parse_msglen,
4303 				msgbuffer);
4304 		}
4305 #endif
4306 		get_mbg_header(&bufp, &header);
4307 		if (header.hdr_csum == mbg_csum(parsetime->parse_msg + 1, 6) &&
4308 		    (header.len == 0 ||
4309 		     (header.len < sizeof(parsetime->parse_msg) &&
4310 		      header.data_csum == mbg_csum(bufp, header.len))))
4311 		{
4312 			/*
4313 			 * clean message
4314 			 */
4315 			switch (header.cmd)
4316 			{
4317 			case GPS_SW_REV:
4318 				{
4319 					char buffer[64];
4320 					SW_REV gps_sw_rev;
4321 
4322 					get_mbg_sw_rev(&bufp, &gps_sw_rev);
4323 					snprintf(buffer, sizeof(buffer), "meinberg_gps_version=\"%x.%02x%s%s\"",
4324 						(gps_sw_rev.code >> 8) & 0xFF,
4325 						gps_sw_rev.code & 0xFF,
4326 						gps_sw_rev.name[0] ? " " : "",
4327 						gps_sw_rev.name);
4328 					set_var(&parse->kv, buffer, strlen(buffer)+1, RO|DEF);
4329 				}
4330 			break;
4331 
4332 			case GPS_BVAR_STAT:
4333 				{
4334 					static struct state
4335 					{
4336 						BVAR_STAT flag; /* status flag */
4337 						const char *string; /* bit name */
4338 					} states[] =
4339 					  {
4340 						  { BVAR_CFGH_INVALID,     "Configuration/Health" },
4341 						  { BVAR_ALM_NOT_COMPLETE, "Almanachs" },
4342 						  { BVAR_UTC_INVALID,      "UTC Correction" },
4343 						  { BVAR_IONO_INVALID,     "Ionospheric Correction" },
4344 						  { BVAR_RCVR_POS_INVALID, "Receiver Position" },
4345 						  { 0, "" }
4346 					  };
4347 					BVAR_STAT status;
4348 					struct state *s = states;
4349 					char buffer[512];
4350 					char *p, *b;
4351 
4352 					status = (BVAR_STAT) get_lsb_short(&bufp);
4353 					p = b = buffer;
4354 					p = ap(buffer, sizeof(buffer), p,
4355 					    "meinberg_gps_status=\"[0x%04x] ",
4356 					    status);
4357 
4358 					if (status)
4359 					{
4360 						p = ap(buffer, sizeof(buffer), p, "incomplete buffered data: ");
4361 						b = p;
4362 						while (s->flag)
4363 						{
4364 							if (status & s->flag)
4365 							{
4366 								if (p != b)
4367 								{
4368 									p = ap(buffer, sizeof(buffer), p, ", ");
4369 								}
4370 
4371 								p = ap(buffer, sizeof(buffer), p, "%s", (const char *)s->string);
4372 							}
4373 							s++;
4374 						}
4375 						p = ap(buffer, sizeof(buffer), p, "\"");
4376 					}
4377 					else
4378 					{
4379 						p = ap(buffer, sizeof(buffer), p, "<all buffered data complete>\"");
4380 					}
4381 
4382 					set_var(&parse->kv, buffer, strlen(buffer)+1, RO|DEF);
4383 				}
4384 			break;
4385 
4386 			case GPS_POS_XYZ:
4387 				{
4388 					XYZ xyz;
4389 					char buffer[256];
4390 
4391 					get_mbg_xyz(&bufp, xyz);
4392 					snprintf(buffer, sizeof(buffer), "gps_position(XYZ)=\"%s m, %s m, %s m\"",
4393 						mfptoa(xyz[XP].l_ui, xyz[XP].l_uf, 1),
4394 						mfptoa(xyz[YP].l_ui, xyz[YP].l_uf, 1),
4395 						mfptoa(xyz[ZP].l_ui, xyz[ZP].l_uf, 1));
4396 
4397 					set_var(&parse->kv, buffer, sizeof(buffer), RO|DEF);
4398 				}
4399 			break;
4400 
4401 			case GPS_POS_LLA:
4402 				{
4403 					LLA lla;
4404 					char buffer[256];
4405 
4406 					get_mbg_lla(&bufp, lla);
4407 
4408 					snprintf(buffer, sizeof(buffer), "gps_position(LLA)=\"%s deg, %s deg, %s m\"",
4409 						mfptoa(lla[LAT].l_ui, lla[LAT].l_uf, 4),
4410 						mfptoa(lla[LON].l_ui, lla[LON].l_uf, 4),
4411 						mfptoa(lla[ALT].l_ui, lla[ALT].l_uf, 1));
4412 
4413 					set_var(&parse->kv, buffer, sizeof(buffer), RO|DEF);
4414 				}
4415 			break;
4416 
4417 			case GPS_TZDL:
4418 				break;
4419 
4420 			case GPS_PORT_PARM:
4421 				break;
4422 
4423 			case GPS_SYNTH:
4424 				break;
4425 
4426 			case GPS_ANT_INFO:
4427 				{
4428 					ANT_INFO antinfo;
4429 					char buffer[512];
4430 					char *p, *q;
4431 
4432 					get_mbg_antinfo(&bufp, &antinfo);
4433 					p = buffer;
4434 					p = ap(buffer, sizeof(buffer), p, "meinberg_antenna_status=\"");
4435 					switch (antinfo.status)
4436 					{
4437 					case ANT_INVALID: // No other fields valid since antenna has not yet been disconnected
4438 						p = ap(buffer, sizeof(buffer),
4439 						    p, "<OK>");
4440 						break;
4441 
4442 					case ANT_DISCONN: // Antenna is disconnected, tm_reconn and delta_t not yet set
4443 						q = ap(buffer, sizeof(buffer),
4444 						    p, "DISCONNECTED since ");
4445 						NLOG(NLOG_CLOCKSTATUS)
4446 							ERR(ERR_BADSTATUS)
4447 							msyslog(LOG_ERR,"PARSE receiver #%d: ANTENNA FAILURE: %s",
4448 								CLK_UNIT(parse->peer), p);
4449 
4450 						p = q;
4451 						mbg_tm_str(&p, &antinfo.tm_disconn, BUFFER_SIZE(buffer, p), 0);
4452 						*p = '\0';
4453 						break;
4454 
4455 					case ANT_RECONN: // Antenna had been disconnect, but receiver sync. after reconnect, so all fields valid
4456 						p = ap(buffer, sizeof(buffer),
4457 						    p, "SYNC AFTER RECONNECT on ");
4458 						mbg_tm_str(&p, &antinfo.tm_reconn, BUFFER_SIZE(buffer, p), 0);
4459 						p = ap(buffer, sizeof(buffer),
4460 							p, ", clock offset at reconnect %c%ld.%07ld s, disconnect time ",
4461 							(antinfo.delta_t < 0) ? '-' : '+',
4462 							(long) ABS(antinfo.delta_t) / 10000,
4463 							(long) ABS(antinfo.delta_t) % 10000);
4464 						mbg_tm_str(&p, &antinfo.tm_disconn, BUFFER_SIZE(buffer, p), 0);
4465 						*p = '\0';
4466 						break;
4467 
4468 					default:
4469 						p = ap(buffer, sizeof(buffer),
4470 						    p, "bad status 0x%04x",
4471 						    antinfo.status);
4472 						break;
4473 					}
4474 
4475 					p = ap(buffer, sizeof(buffer), p, "\"");
4476 
4477 					set_var(&parse->kv, buffer, sizeof(buffer), RO|DEF);
4478 				}
4479 			break;
4480 
4481 			case GPS_UCAP:
4482 				break;
4483 
4484 			case GPS_CFGH:
4485 				{
4486 					CFGH cfgh;
4487 					char buffer[512];
4488 					char *p;
4489 
4490 					get_mbg_cfgh(&bufp, &cfgh);
4491 					if (cfgh.valid)
4492 					{
4493 						const char *cp;
4494 						uint16_t tmp_val;
4495 						int i;
4496 
4497 						p = buffer;
4498 						p = ap(buffer, sizeof(buffer),
4499 						    p, "gps_tot_51=\"");
4500 						mbg_tgps_str(&p, &cfgh.tot_51, BUFFER_SIZE(buffer, p));
4501 						p = ap(buffer, sizeof(buffer),
4502 						    p, "\"");
4503 						set_var(&parse->kv, buffer, sizeof(buffer), RO|COND_DEF);
4504 
4505 						p = buffer;
4506 						p = ap(buffer, sizeof(buffer),
4507 						    p, "gps_tot_63=\"");
4508 						mbg_tgps_str(&p, &cfgh.tot_63, BUFFER_SIZE(buffer, p));
4509 						p = ap(buffer, sizeof(buffer),
4510 						    p, "\"");
4511 						set_var(&parse->kv, buffer, sizeof(buffer), RO|COND_DEF);
4512 
4513 						p = buffer;
4514 						p = ap(buffer, sizeof(buffer),
4515 						    p, "gps_t0a=\"");
4516 						mbg_tgps_str(&p, &cfgh.t0a, BUFFER_SIZE(buffer, p));
4517 						p = ap(buffer, sizeof(buffer),
4518 						    p, "\"");
4519 						set_var(&parse->kv, buffer, sizeof(buffer), RO|COND_DEF);
4520 
4521 						for (i = 0; i < N_SVNO_GPS; i++)
4522 						{
4523 							p = buffer;
4524 							p = ap(buffer, sizeof(buffer), p, "sv_info[%d]=\"PRN%d", i, i + N_SVNO_GPS);
4525 
4526 							tmp_val = cfgh.health[i];  /* a 6 bit SV health code */
4527 							p = ap(buffer, sizeof(buffer), p, "; health=0x%02x (", tmp_val);
4528 							/* "All Ones" has a special meaning" */
4529 							if (tmp_val == 0x3F) /* satellite is unusable or doesn't even exist */
4530 								cp = "SV UNAVAILABLE";
4531 							else {
4532 								/* The MSB contains a summary of the 3 MSBs of the 8 bit health code,
4533 								 * indicating if the data sent by the satellite is OK or not. */
4534 								p = ap(buffer, sizeof(buffer), p, "DATA %s, ", (tmp_val & 0x20) ? "BAD" : "OK" );
4535 
4536 								/* The 5 LSBs contain the status of the different signals sent by the satellite. */
4537 								switch (tmp_val & 0x1F)
4538 								{
4539 									case 0x00: cp = "SIGNAL OK";              break;
4540 									/* codes 0x01 through 0x1B indicate that one or more
4541 									 * specific signal components are weak or dead.
4542 									 * We don't decode this here in detail. */
4543 									case 0x1C: cp = "SV IS TEMP OUT";         break;
4544 									case 0x1D: cp = "SV WILL BE TEMP OUT";    break;
4545 									default:   cp = "TRANSMISSION PROBLEMS";  break;
4546 								}
4547 							}
4548 							p = ap(buffer, sizeof(buffer), p, "%s)", cp );
4549 
4550 							tmp_val = cfgh.cfg[i];  /* a 4 bit SV configuration/type code */
4551 							p = ap(buffer, sizeof(buffer), p, "; cfg=0x%02x (", tmp_val);
4552 							switch (tmp_val & 0x7)
4553 							{
4554 								case 0x00:  cp = "(reserved)";        break;
4555 								case 0x01:  cp = "BLOCK II/IIA/IIR";  break;
4556 								case 0x02:  cp = "BLOCK IIR-M";       break;
4557 								case 0x03:  cp = "BLOCK IIF";         break;
4558 								case 0x04:  cp = "BLOCK III";         break;
4559 								default:   cp = "unknown SV type";   break;
4560 							}
4561 							p = ap(buffer, sizeof(buffer), p, "%s", cp );
4562 							if (tmp_val & 0x08)  /* A-S is on, P-code is encrypted */
4563 								p = ap( buffer, sizeof(buffer), p, ", A-S on" );
4564 
4565 							p = ap(buffer, sizeof(buffer), p, ")\"");
4566 							set_var(&parse->kv, buffer, sizeof(buffer), RO|COND_DEF);
4567 						}
4568 					}
4569 				}
4570 			break;
4571 
4572 			case GPS_ALM:
4573 				break;
4574 
4575 			case GPS_EPH:
4576 				break;
4577 
4578 			case GPS_UTC:
4579 				{
4580 					UTC utc;
4581 					char buffer[512];
4582 					char *p;
4583 
4584 					p = buffer;
4585 
4586 					get_mbg_utc(&bufp, &utc);
4587 
4588 					if (utc.valid)
4589 					{
4590 						p = ap(buffer, sizeof(buffer), p, "gps_utc_correction=\"");
4591 						mk_utcinfo(p, utc.t0t.wn, utc.WNlsf, utc.DNt, utc.delta_tls, utc.delta_tlsf, BUFFER_SIZE(buffer, p));
4592 						p += strlen(p);
4593 						p = ap(buffer, sizeof(buffer), p, "\"");
4594 					}
4595 					else
4596 					{
4597 						p = ap(buffer, sizeof(buffer), p, "gps_utc_correction=\"<NO UTC DATA>\"");
4598 					}
4599 					set_var(&parse->kv, buffer, sizeof(buffer), RO|DEF);
4600 				}
4601 			break;
4602 
4603 			case GPS_IONO:
4604 				break;
4605 
4606 			case GPS_ASCII_MSG:
4607 				{
4608 					ASCII_MSG gps_ascii_msg;
4609 					char buffer[128];
4610 
4611 					get_mbg_ascii_msg(&bufp, &gps_ascii_msg);
4612 
4613 					if (gps_ascii_msg.valid)
4614 						{
4615 							char buffer1[128];
4616 							mkreadable(buffer1, sizeof(buffer1), gps_ascii_msg.s, strlen(gps_ascii_msg.s), (int)0);
4617 
4618 							snprintf(buffer, sizeof(buffer), "gps_message=\"%s\"", buffer1);
4619 						}
4620 					else
4621 						snprintf(buffer, sizeof(buffer), "gps_message=<NONE>");
4622 
4623 					set_var(&parse->kv, buffer, sizeof(buffer), RO|DEF);
4624 				}
4625 
4626 			break;
4627 
4628 			default:
4629 				break;
4630 			}
4631 		}
4632 		else
4633 		{
4634 			msyslog(LOG_DEBUG, "PARSE receiver #%d: gps16x_message: message checksum error: hdr_csum = 0x%x (expected 0x%x), "
4635 			                   "data_len = %d, data_csum = 0x%x (expected 0x%x)",
4636 				CLK_UNIT(parse->peer),
4637 				header.hdr_csum, mbg_csum(parsetime->parse_msg + 1, 6),
4638 				header.len,
4639 				header.data_csum, mbg_csum(bufp, (unsigned)((header.len < sizeof(parsetime->parse_msg)) ? header.len : 0)));
4640 		}
4641 	}
4642 
4643 	return;
4644 }
4645 
4646 /*------------------------------------------------------------
4647  * gps16x_poll - query the reciver peridically
4648  */
4649 static void
4650 gps16x_poll(
4651 	    struct peer *peer
4652 	    )
4653 {
4654 	struct parseunit *parse = peer->procptr->unitptr;
4655 
4656 	static GPS_MSG_HDR sequence[] =
4657 	{
4658 		{ GPS_SW_REV,          0, 0, 0 },
4659 		{ GPS_BVAR_STAT,       0, 0, 0 },
4660 		{ GPS_UTC,             0, 0, 0 },
4661 		{ GPS_ASCII_MSG,       0, 0, 0 },
4662 		{ GPS_ANT_INFO,        0, 0, 0 },
4663 		{ GPS_CFGH,            0, 0, 0 },
4664 		{ GPS_POS_XYZ,         0, 0, 0 },
4665 		{ GPS_POS_LLA,         0, 0, 0 },
4666 		{ (unsigned short)~0,  0, 0, 0 }
4667 	};
4668 
4669 	int rtc;
4670 	unsigned char cmd_buffer[64];
4671 	unsigned char *outp = cmd_buffer;
4672 	GPS_MSG_HDR *header;
4673 
4674 	if (((poll_info_t *)parse->parse_type->cl_data)->rate)
4675 	{
4676 		parse->peer->procptr->nextaction = current_time + ((poll_info_t *)parse->parse_type->cl_data)->rate;
4677 	}
4678 
4679 	if (sequence[parse->localstate].cmd == (unsigned short)~0)
4680 		parse->localstate = 0;
4681 
4682 	header = sequence + parse->localstate++;
4683 
4684 	*outp++ = SOH;		/* start command */
4685 
4686 	put_mbg_header(&outp, header);
4687 	outp = cmd_buffer + 1;
4688 
4689 	header->hdr_csum = (short)mbg_csum(outp, 6);
4690 	put_mbg_header(&outp, header);
4691 
4692 #ifdef DEBUG
4693 	if (debug > 2)
4694 	{
4695 		char buffer[128];
4696 
4697 		mkreadable(buffer, sizeof(buffer), (char *)cmd_buffer, (unsigned)(outp - cmd_buffer), 1);
4698 		printf("PARSE receiver #%d: transmitted message #%ld (%d bytes) >%s<\n",
4699 		       CLK_UNIT(parse->peer),
4700 		       parse->localstate - 1,
4701 		       (int)(outp - cmd_buffer),
4702 		       buffer);
4703 	}
4704 #endif
4705 
4706 	rtc = (int) write(parse->generic->io.fd, cmd_buffer, (unsigned long)(outp - cmd_buffer));
4707 
4708 	if (rtc < 0)
4709 	{
4710 		ERR(ERR_BADIO)
4711 			msyslog(LOG_ERR, "PARSE receiver #%d: gps16x_poll: failed to send cmd to clock: %m", CLK_UNIT(parse->peer));
4712 	}
4713 	else
4714 	if (rtc != outp - cmd_buffer)
4715 	{
4716 		ERR(ERR_BADIO)
4717 			msyslog(LOG_ERR, "PARSE receiver #%d: gps16x_poll: failed to send cmd incomplete (%d of %d bytes sent)", CLK_UNIT(parse->peer), rtc, (int)(outp - cmd_buffer));
4718 	}
4719 
4720 	clear_err(parse, ERR_BADIO);
4721 	return;
4722 }
4723 
4724 /*--------------------------------------------------
4725  * init routine - setup timer
4726  */
4727 static int
4728 gps16x_poll_init(
4729 	struct parseunit *parse
4730 	)
4731 {
4732 	if (((poll_info_t *)parse->parse_type->cl_data)->rate)
4733 	{
4734 		parse->peer->procptr->action = gps16x_poll;
4735 		gps16x_poll(parse->peer);
4736 	}
4737 
4738 	return 0;
4739 }
4740 
4741 #else
4742 static void
4743 gps16x_message(
4744 	       struct parseunit *parse,
4745 	       parsetime_t      *parsetime
4746 	       )
4747 {}
4748 static int
4749 gps16x_poll_init(
4750 	struct parseunit *parse
4751 	)
4752 {
4753 	return 1;
4754 }
4755 #endif /* CLOCK_MEINBERG */
4756 
4757 /**===========================================================================
4758  ** clock polling support
4759  **/
4760 
4761 /*--------------------------------------------------
4762  * direct poll routine
4763  */
4764 static void
4765 poll_dpoll(
4766 	struct parseunit *parse
4767 	)
4768 {
4769 	long rtc;
4770 	const char *ps = ((poll_info_t *)parse->parse_type->cl_data)->string;
4771 	long ct = ((poll_info_t *)parse->parse_type->cl_data)->count;
4772 
4773 	rtc = write(parse->generic->io.fd, ps, ct);
4774 	if (rtc < 0)
4775 	{
4776 		ERR(ERR_BADIO)
4777 			msyslog(LOG_ERR, "PARSE receiver #%d: poll_dpoll: failed to send cmd to clock: %m", CLK_UNIT(parse->peer));
4778 	}
4779 	else
4780 	    if (rtc != ct)
4781 	    {
4782 		    ERR(ERR_BADIO)
4783 			    msyslog(LOG_ERR, "PARSE receiver #%d: poll_dpoll: failed to send cmd incomplete (%ld of %ld bytes sent)", CLK_UNIT(parse->peer), rtc, ct);
4784 	    }
4785 	clear_err(parse, ERR_BADIO);
4786 }
4787 
4788 /*--------------------------------------------------
4789  * periodic poll routine
4790  */
4791 static void
4792 poll_poll(
4793 	struct peer *peer
4794 	)
4795 {
4796 	struct parseunit *parse = peer->procptr->unitptr;
4797 
4798 	if (parse->parse_type->cl_poll)
4799 		parse->parse_type->cl_poll(parse);
4800 
4801 	if (((poll_info_t *)parse->parse_type->cl_data)->rate)
4802 	{
4803 		parse->peer->procptr->nextaction = current_time + ((poll_info_t *)parse->parse_type->cl_data)->rate;
4804 	}
4805 }
4806 
4807 /*--------------------------------------------------
4808  * init routine - setup timer
4809  */
4810 static int
4811 poll_init(
4812 	struct parseunit *parse
4813 	)
4814 {
4815 	if (((poll_info_t *)parse->parse_type->cl_data)->rate)
4816 	{
4817 		parse->peer->procptr->action = poll_poll;
4818 		poll_poll(parse->peer);
4819 	}
4820 
4821 	return 0;
4822 }
4823 
4824 /**===========================================================================
4825  ** Trimble support
4826  **/
4827 
4828 /*-------------------------------------------------------------
4829  * trimble TAIP init routine - setup EOL and then do poll_init.
4830  */
4831 static int
4832 trimbletaip_init(
4833 	struct parseunit *parse
4834 	)
4835 {
4836 #ifdef HAVE_TERMIOS
4837 	struct termios tio;
4838 #endif
4839 #ifdef HAVE_SYSV_TTYS
4840 	struct termio tio;
4841 #endif
4842 	/*
4843 	 * configure terminal line for trimble receiver
4844 	 */
4845 	if (TTY_GETATTR(parse->generic->io.fd, &tio) == -1)
4846 	{
4847 		msyslog(LOG_ERR, "PARSE receiver #%d: trimbletaip_init: tcgetattr(fd, &tio): %m", CLK_UNIT(parse->peer));
4848 		return 0;
4849 	}
4850 	else
4851 	{
4852 		tio.c_cc[VEOL] = TRIMBLETAIP_EOL;
4853 
4854 		if (TTY_SETATTR(parse->generic->io.fd, &tio) == -1)
4855 		{
4856 			msyslog(LOG_ERR, "PARSE receiver #%d: trimbletaip_init: tcsetattr(fd, &tio): %m", CLK_UNIT(parse->peer));
4857 			return 0;
4858 		}
4859 	}
4860 	return poll_init(parse);
4861 }
4862 
4863 /*--------------------------------------------------
4864  * trimble TAIP event routine - reset receiver upon data format trouble
4865  */
4866 static const char *taipinit[] = {
4867 	">FPV00000000<",
4868 	">SRM;ID_FLAG=F;CS_FLAG=T;EC_FLAG=F;FR_FLAG=T;CR_FLAG=F<",
4869 	">FTM00020001<",
4870 	(char *)0
4871 };
4872 
4873 static void
4874 trimbletaip_event(
4875 	struct parseunit *parse,
4876 	int event
4877 	)
4878 {
4879 	switch (event)
4880 	{
4881 	    case CEVNT_BADREPLY:	/* reset on garbled input */
4882 	    case CEVNT_TIMEOUT:		/* reset on no input */
4883 		    {
4884 			    const char **iv;
4885 
4886 			    iv = taipinit;
4887 			    while (*iv)
4888 			    {
4889 				    int rtc = (int) write(parse->generic->io.fd, *iv, strlen(*iv));
4890 				    if (rtc < 0)
4891 				    {
4892 					    msyslog(LOG_ERR, "PARSE receiver #%d: trimbletaip_event: failed to send cmd to clock: %m", CLK_UNIT(parse->peer));
4893 					    return;
4894 				    }
4895 				    else
4896 				    {
4897 					    if (rtc != (int)strlen(*iv))
4898 					    {
4899 						    msyslog(LOG_ERR, "PARSE receiver #%d: trimbletaip_event: failed to send cmd incomplete (%d of %d bytes sent)",
4900 							    CLK_UNIT(parse->peer), rtc, (int)strlen(*iv));
4901 						    return;
4902 					    }
4903 				    }
4904 				    iv++;
4905 			    }
4906 
4907 			    NLOG(NLOG_CLOCKINFO)
4908 				    ERR(ERR_BADIO)
4909 				    msyslog(LOG_ERR, "PARSE receiver #%d: trimbletaip_event: RECEIVER INITIALIZED",
4910 					    CLK_UNIT(parse->peer));
4911 		    }
4912 		    break;
4913 
4914 	    default:			/* ignore */
4915 		break;
4916 	}
4917 }
4918 
4919 /*
4920  * This driver supports the Trimble SVee Six Plus GPS receiver module.
4921  * It should support other Trimble receivers which use the Trimble Standard
4922  * Interface Protocol (see below).
4923  *
4924  * The module has a serial I/O port for command/data and a 1 pulse-per-second
4925  * output, about 1 microsecond wide. The leading edge of the pulse is
4926  * coincident with the change of the GPS second. This is the same as
4927  * the change of the UTC second +/- ~1 microsecond. Some other clocks
4928  * specifically use a feature in the data message as a timing reference, but
4929  * the SVee Six Plus does not do this. In fact there is considerable jitter
4930  * on the timing of the messages, so this driver only supports the use
4931  * of the PPS pulse for accurate timing. Where it is determined that
4932  * the offset is way off, when first starting up ntpd for example,
4933  * the timing of the data stream is used until the offset becomes low enough
4934  * (|offset| < CLOCK_MAX), at which point the pps offset is used.
4935  *
4936  * It can use either option for receiving PPS information - the 'ppsclock'
4937  * stream pushed onto the serial data interface to timestamp the Carrier
4938  * Detect interrupts, where the 1PPS connects to the CD line. This only
4939  * works on SunOS 4.1.x currently. To select this, define PPSPPS in
4940  * Config.local. The other option is to use a pulse-stretcher/level-converter
4941  * to convert the PPS pulse into a RS232 start pulse & feed this into another
4942  * tty port. To use this option, define PPSCLK in Config.local. The pps input,
4943  * by whichever method, is handled in ntp_loopfilter.c
4944  *
4945  * The receiver uses a serial message protocol called Trimble Standard
4946  * Interface Protocol (it can support others but this driver only supports
4947  * TSIP). Messages in this protocol have the following form:
4948  *
4949  * <DLE><id> ... <data> ... <DLE><ETX>
4950  *
4951  * Any bytes within the <data> portion of value 10 hex (<DLE>) are doubled
4952  * on transmission and compressed back to one on reception. Otherwise
4953  * the values of data bytes can be anything. The serial interface is RS-422
4954  * asynchronous using 9600 baud, 8 data bits with odd party (**note** 9 bits
4955  * in total!), and 1 stop bit. The protocol supports byte, integer, single,
4956  * and double datatypes. Integers are two bytes, sent most significant first.
4957  * Singles are IEEE754 single precision floating point numbers (4 byte) sent
4958  * sign & exponent first. Doubles are IEEE754 double precision floating point
4959  * numbers (8 byte) sent sign & exponent first.
4960  * The receiver supports a large set of messages, only a small subset of
4961  * which are used here. From driver to receiver the following are used:
4962  *
4963  *  ID    Description
4964  *
4965  *  21    Request current time
4966  *  22    Mode Select
4967  *  2C    Set/Request operating parameters
4968  *  2F    Request UTC info
4969  *  35    Set/Request I/O options
4970 
4971  * From receiver to driver the following are recognised:
4972  *
4973  *  ID    Description
4974  *
4975  *  41    GPS Time
4976  *  44    Satellite selection, PDOP, mode
4977  *  46    Receiver health
4978  *  4B    Machine code/status
4979  *  4C    Report operating parameters (debug only)
4980  *  4F    UTC correction data (used to get leap second warnings)
4981  *  55    I/O options (debug only)
4982  *
4983  * All others are accepted but ignored.
4984  *
4985  */
4986 
4987 #define PI		3.1415926535898	/* lots of sig figs */
4988 #define D2R		PI/180.0
4989 
4990 /*-------------------------------------------------------------------
4991  * sendcmd, sendbyte, sendetx, sendflt, sendint implement the command
4992  * interface to the receiver.
4993  *
4994  * CAVEAT: the sendflt, sendint routines are byte order dependend and
4995  * float implementation dependend - these must be converted to portable
4996  * versions !
4997  *
4998  * CURRENT LIMITATION: float implementation. This runs only on systems
4999  * with IEEE754 floats as native floats
5000  */
5001 
5002 typedef struct trimble
5003 {
5004 	u_long last_msg;	/* last message received */
5005 	u_long last_reset;	/* last time a reset was issued */
5006 	u_char qtracking;	/* query tracking status */
5007 	u_long ctrack;		/* current tracking set */
5008 	u_long ltrack;		/* last tracking set */
5009 } trimble_t;
5010 
5011 union uval {
5012 	u_char  bd[8];
5013 	int     iv;
5014 	float   fv;
5015 	double  dv;
5016 };
5017 
5018 struct txbuf
5019 {
5020 	short idx;			/* index to first unused byte */
5021 	u_char *txt;			/* pointer to actual data buffer */
5022 };
5023 
5024 void	sendcmd		(struct txbuf *buf, int c);
5025 void	sendbyte	(struct txbuf *buf, int b);
5026 void	sendetx		(struct txbuf *buf, struct parseunit *parse);
5027 void	sendint		(struct txbuf *buf, int a);
5028 void	sendflt		(struct txbuf *buf, double a);
5029 
5030 void
5031 sendcmd(
5032 	struct txbuf *buf,
5033 	int c
5034 	)
5035 {
5036 	buf->txt[0] = DLE;
5037 	buf->txt[1] = (u_char)c;
5038 	buf->idx = 2;
5039 }
5040 
5041 void	sendcmd		(struct txbuf *buf, int c);
5042 void	sendbyte	(struct txbuf *buf, int b);
5043 void	sendetx		(struct txbuf *buf, struct parseunit *parse);
5044 void	sendint		(struct txbuf *buf, int a);
5045 void	sendflt		(struct txbuf *buf, double a);
5046 
5047 void
5048 sendbyte(
5049 	struct txbuf *buf,
5050 	int b
5051 	)
5052 {
5053 	if (b == DLE)
5054 	    buf->txt[buf->idx++] = DLE;
5055 	buf->txt[buf->idx++] = (u_char)b;
5056 }
5057 
5058 void
5059 sendetx(
5060 	struct txbuf *buf,
5061 	struct parseunit *parse
5062 	)
5063 {
5064 	buf->txt[buf->idx++] = DLE;
5065 	buf->txt[buf->idx++] = ETX;
5066 
5067 	if (write(parse->generic->io.fd, buf->txt, (unsigned long)buf->idx) != buf->idx)
5068 	{
5069 		ERR(ERR_BADIO)
5070 			msyslog(LOG_ERR, "PARSE receiver #%d: sendetx: failed to send cmd to clock: %m", CLK_UNIT(parse->peer));
5071 	}
5072 	else
5073 	{
5074 #ifdef DEBUG
5075 	  if (debug > 2)
5076 	  {
5077 		  char buffer[256];
5078 
5079 		  mkreadable(buffer, sizeof(buffer), (char *)buf->txt, (unsigned)buf->idx, 1);
5080 		  printf("PARSE receiver #%d: transmitted message (%d bytes) >%s<\n",
5081 			 CLK_UNIT(parse->peer),
5082 			 buf->idx, buffer);
5083 	  }
5084 #endif
5085 		clear_err(parse, ERR_BADIO);
5086 	}
5087 }
5088 
5089 void
5090 sendint(
5091 	struct txbuf *buf,
5092 	int a
5093 	)
5094 {
5095 	/* send 16bit int, msbyte first */
5096 	sendbyte(buf, (u_char)((a>>8) & 0xff));
5097 	sendbyte(buf, (u_char)(a & 0xff));
5098 }
5099 
5100 void
5101 sendflt(
5102 	struct txbuf *buf,
5103 	double a
5104 	)
5105 {
5106 	int i;
5107 	union uval uval;
5108 
5109 	uval.fv = (float) a;
5110 #ifdef WORDS_BIGENDIAN
5111 	for (i=0; i<=3; i++)
5112 #else
5113 	    for (i=3; i>=0; i--)
5114 #endif
5115 		sendbyte(buf, uval.bd[i]);
5116 }
5117 
5118 #define TRIM_POS_OPT	0x13	/* output position with high precision */
5119 #define TRIM_TIME_OPT	0x03	/* use UTC time stamps, on second */
5120 
5121 /*--------------------------------------------------
5122  * trimble TSIP setup routine
5123  */
5124 static int
5125 trimbletsip_setup(
5126 		  struct parseunit *parse,
5127 		  const char *reason
5128 		  )
5129 {
5130 	u_char buffer[256];
5131 	struct txbuf buf;
5132 	trimble_t *t = parse->localdata;
5133 
5134 	if (t && t->last_reset &&
5135 	    ((t->last_reset + TRIMBLE_RESET_HOLDOFF) > current_time)) {
5136 		return 1;	/* not yet */
5137 	}
5138 
5139 	if (t)
5140 		t->last_reset = current_time;
5141 
5142 	buf.txt = buffer;
5143 
5144 	sendcmd(&buf, CMD_CVERSION);	/* request software versions */
5145 	sendetx(&buf, parse);
5146 
5147 	sendcmd(&buf, CMD_COPERPARAM);	/* set operating parameters */
5148 	sendbyte(&buf, 4);	/* static */
5149 	sendflt(&buf, 5.0*D2R);	/* elevation angle mask = 10 deg XXX */
5150 	sendflt(&buf, 4.0);	/* s/n ratio mask = 6 XXX */
5151 	sendflt(&buf, 12.0);	/* PDOP mask = 12 */
5152 	sendflt(&buf, 8.0);	/* PDOP switch level = 8 */
5153 	sendetx(&buf, parse);
5154 
5155 	sendcmd(&buf, CMD_CMODESEL);	/* fix mode select */
5156 	sendbyte(&buf, 1);	/* time transfer mode */
5157 	sendetx(&buf, parse);
5158 
5159 	sendcmd(&buf, CMD_CMESSAGE);	/* request system message */
5160 	sendetx(&buf, parse);
5161 
5162 	sendcmd(&buf, CMD_CSUPER);	/* superpacket fix */
5163 	sendbyte(&buf, 0x2);	/* binary mode */
5164 	sendetx(&buf, parse);
5165 
5166 	sendcmd(&buf, CMD_CIOOPTIONS);	/* set I/O options */
5167 	sendbyte(&buf, TRIM_POS_OPT);	/* position output */
5168 	sendbyte(&buf, 0x00);	/* no velocity output */
5169 	sendbyte(&buf, TRIM_TIME_OPT);	/* UTC, compute on seconds */
5170 	sendbyte(&buf, 0x00);	/* no raw measurements */
5171 	sendetx(&buf, parse);
5172 
5173 	sendcmd(&buf, CMD_CUTCPARAM);	/* request UTC correction data */
5174 	sendetx(&buf, parse);
5175 
5176 	NLOG(NLOG_CLOCKINFO)
5177 		ERR(ERR_BADIO)
5178 		msyslog(LOG_ERR, "PARSE receiver #%d: trimbletsip_setup: RECEIVER RE-INITIALIZED (%s)", CLK_UNIT(parse->peer), reason);
5179 
5180 	return 0;
5181 }
5182 
5183 /*--------------------------------------------------
5184  * TRIMBLE TSIP check routine
5185  */
5186 static void
5187 trimble_check(
5188 	      struct peer *peer
5189 	      )
5190 {
5191 	struct parseunit *parse = peer->procptr->unitptr;
5192 	trimble_t *t = parse->localdata;
5193 	u_char buffer[256];
5194 	struct txbuf buf;
5195 	buf.txt = buffer;
5196 
5197 	if (t)
5198 	{
5199 		if (current_time > t->last_msg + TRIMBLETSIP_IDLE_TIME)
5200 			(void)trimbletsip_setup(parse, "message timeout");
5201 	}
5202 
5203 	poll_poll(parse->peer);	/* emit query string and re-arm timer */
5204 
5205 	if (t && t->qtracking)
5206 	{
5207 		u_long oldsats = t->ltrack & ~t->ctrack;
5208 
5209 		t->qtracking = 0;
5210 		t->ltrack = t->ctrack;
5211 
5212 		if (oldsats)
5213 		{
5214 			int i;
5215 
5216 			for (i = 0; oldsats; i++) {
5217 				if (oldsats & (1 << i))
5218 					{
5219 						sendcmd(&buf, CMD_CSTATTRACK);
5220 						sendbyte(&buf, i+1);	/* old sat */
5221 						sendetx(&buf, parse);
5222 					}
5223 				oldsats &= ~(1 << i);
5224 			}
5225 		}
5226 
5227 		sendcmd(&buf, CMD_CSTATTRACK);
5228 		sendbyte(&buf, 0x00);	/* current tracking set */
5229 		sendetx(&buf, parse);
5230 	}
5231 }
5232 
5233 /*--------------------------------------------------
5234  * TRIMBLE TSIP end routine
5235  */
5236 static void
5237 trimbletsip_end(
5238 	      struct parseunit *parse
5239 	      )
5240 {	trimble_t *t = parse->localdata;
5241 
5242 	if (t)
5243 	{
5244 		free(t);
5245 		parse->localdata = NULL;
5246 	}
5247 	parse->peer->procptr->nextaction = 0;
5248 	parse->peer->procptr->action = NULL;
5249 }
5250 
5251 /*--------------------------------------------------
5252  * TRIMBLE TSIP init routine
5253  */
5254 static int
5255 trimbletsip_init(
5256 	struct parseunit *parse
5257 	)
5258 {
5259 #if defined(VEOL) || defined(VEOL2)
5260 #ifdef HAVE_TERMIOS
5261 	struct termios tio;		/* NEEDED FOR A LONG TIME ! */
5262 #endif
5263 #ifdef HAVE_SYSV_TTYS
5264 	struct termio tio;		/* NEEDED FOR A LONG TIME ! */
5265 #endif
5266 	/*
5267 	 * allocate local data area
5268 	 */
5269 	if (!parse->localdata)
5270 	{
5271 		trimble_t *t;
5272 
5273 		t = (trimble_t *)(parse->localdata = emalloc(sizeof(trimble_t)));
5274 
5275 		if (t)
5276 		{
5277 			memset((char *)t, 0, sizeof(trimble_t));
5278 			t->last_msg = current_time;
5279 		}
5280 	}
5281 
5282 	parse->peer->procptr->action     = trimble_check;
5283 	parse->peer->procptr->nextaction = current_time;
5284 
5285 	/*
5286 	 * configure terminal line for ICANON mode with VEOL characters
5287 	 */
5288 	if (TTY_GETATTR(parse->generic->io.fd, &tio) == -1)
5289 	{
5290 		msyslog(LOG_ERR, "PARSE receiver #%d: trimbletsip_init: tcgetattr(%d, &tio): %m", CLK_UNIT(parse->peer), parse->generic->io.fd);
5291 		return 0;
5292 	}
5293 	else
5294 	{
5295 		if ((parse_clockinfo[CLK_TYPE(parse->peer)].cl_lflag & ICANON))
5296 		{
5297 #ifdef VEOL
5298 			tio.c_cc[VEOL]  = ETX;
5299 #endif
5300 #ifdef VEOL2
5301 			tio.c_cc[VEOL2]  = DLE;
5302 #endif
5303 		}
5304 
5305 		if (TTY_SETATTR(parse->generic->io.fd, &tio) == -1)
5306 		{
5307 			msyslog(LOG_ERR, "PARSE receiver #%d: trimbletsip_init: tcsetattr(%d, &tio): %m", CLK_UNIT(parse->peer), parse->generic->io.fd);
5308 			return 0;
5309 		}
5310 	}
5311 #endif
5312 	return trimbletsip_setup(parse, "initial startup");
5313 }
5314 
5315 /*------------------------------------------------------------
5316  * trimbletsip_event - handle Trimble events
5317  * simple evente handler - attempt to re-initialize receiver
5318  */
5319 static void
5320 trimbletsip_event(
5321 	struct parseunit *parse,
5322 	int event
5323 	)
5324 {
5325 	switch (event)
5326 	{
5327 	    case CEVNT_BADREPLY:	/* reset on garbled input */
5328 	    case CEVNT_TIMEOUT:		/* reset on no input */
5329 		    (void)trimbletsip_setup(parse, "event BAD_REPLY/TIMEOUT");
5330 		    break;
5331 
5332 	    default:			/* ignore */
5333 		break;
5334 	}
5335 }
5336 
5337 /*
5338  * getflt, getint convert fields in the incoming data into the
5339  * appropriate type of item
5340  *
5341  * CAVEAT: these routines are currently definitely byte order dependent
5342  * and assume Representation(float) == IEEE754
5343  * These functions MUST be converted to portable versions (especially
5344  * converting the float representation into ntp_fp formats in order
5345  * to avoid floating point operations at all!
5346  */
5347 
5348 static float
5349 getflt(
5350 	u_char *bp
5351 	)
5352 {
5353 	union uval uval;
5354 
5355 #ifdef WORDS_BIGENDIAN
5356 	uval.bd[0] = *bp++;
5357 	uval.bd[1] = *bp++;
5358 	uval.bd[2] = *bp++;
5359 	uval.bd[3] = *bp;
5360 #else  /* ! WORDS_BIGENDIAN */
5361 	uval.bd[3] = *bp++;
5362 	uval.bd[2] = *bp++;
5363 	uval.bd[1] = *bp++;
5364 	uval.bd[0] = *bp;
5365 #endif /* ! WORDS_BIGENDIAN */
5366 	return uval.fv;
5367 }
5368 
5369 static double
5370 getdbl(
5371 	u_char *bp
5372 	)
5373 {
5374 	union uval uval;
5375 
5376 #ifdef WORDS_BIGENDIAN
5377 	uval.bd[0] = *bp++;
5378 	uval.bd[1] = *bp++;
5379 	uval.bd[2] = *bp++;
5380 	uval.bd[3] = *bp++;
5381 	uval.bd[4] = *bp++;
5382 	uval.bd[5] = *bp++;
5383 	uval.bd[6] = *bp++;
5384 	uval.bd[7] = *bp;
5385 #else  /* ! WORDS_BIGENDIAN */
5386 	uval.bd[7] = *bp++;
5387 	uval.bd[6] = *bp++;
5388 	uval.bd[5] = *bp++;
5389 	uval.bd[4] = *bp++;
5390 	uval.bd[3] = *bp++;
5391 	uval.bd[2] = *bp++;
5392 	uval.bd[1] = *bp++;
5393 	uval.bd[0] = *bp;
5394 #endif /* ! WORDS_BIGENDIAN */
5395 	return uval.dv;
5396 }
5397 
5398 static int
5399 getshort(
5400 	 unsigned char *p
5401 	 )
5402 {
5403 	return (int) get_msb_short(&p);
5404 }
5405 
5406 /*--------------------------------------------------
5407  * trimbletsip_message - process trimble messages
5408  */
5409 #define RTOD (180.0 / 3.1415926535898)
5410 #define mb(_X_) (buffer[2+(_X_)]) /* shortcut for buffer access */
5411 
5412 static void
5413 trimbletsip_message(
5414 		    struct parseunit *parse,
5415 		    parsetime_t      *parsetime
5416 		    )
5417 {
5418 	unsigned char *buffer = parsetime->parse_msg;
5419 	unsigned int   size   = parsetime->parse_msglen;
5420 
5421 	if ((size < 4) ||
5422 	    (buffer[0]      != DLE) ||
5423 	    (buffer[size-1] != ETX) ||
5424 	    (buffer[size-2] != DLE))
5425 	{
5426 #ifdef DEBUG
5427 		if (debug > 2) {
5428 			size_t i;
5429 
5430 			printf("TRIMBLE BAD packet, size %d:\n	", size);
5431 			for (i = 0; i < size; i++) {
5432 				printf ("%2.2x, ", buffer[i]&0xff);
5433 				if (i%16 == 15) printf("\n\t");
5434 			}
5435 			printf("\n");
5436 		}
5437 #endif
5438 		return;
5439 	}
5440 	else
5441 	{
5442 		u_short var_flag;
5443 		trimble_t *tr = parse->localdata;
5444 		unsigned int cmd = buffer[1];
5445 		char pbuffer[200];
5446 		char *t = pbuffer;
5447 		cmd_info_t *s;
5448 
5449 #ifdef DEBUG
5450 		if (debug > 3) {
5451 			size_t i;
5452 
5453 			printf("TRIMBLE packet 0x%02x, size %d:\n	", cmd, size);
5454 			for (i = 0; i < size; i++) {
5455 				printf ("%2.2x, ", buffer[i]&0xff);
5456 				if (i%16 == 15) printf("\n\t");
5457 			}
5458 			printf("\n");
5459 		}
5460 #endif
5461 
5462 		if (tr)
5463 			tr->last_msg = current_time;
5464 
5465 		s = trimble_convert(cmd, trimble_rcmds);
5466 
5467 		if (s)
5468 		{
5469 			t = ap(pbuffer, sizeof(pbuffer), t, "%s=\"", s->varname);
5470 		}
5471 		else
5472 		{
5473 			DPRINTF(1, ("TRIMBLE UNKNOWN COMMAND 0x%02x\n", cmd));
5474 			return;
5475 		}
5476 
5477 		var_flag = (u_short) s->varmode;
5478 
5479 		switch(cmd)
5480 		{
5481 		case CMD_RCURTIME:
5482 			t = ap(pbuffer, sizeof(pbuffer), t, "%f, %d, %f",
5483 				 getflt((unsigned char *)&mb(0)), getshort((unsigned char *)&mb(4)),
5484 				 getflt((unsigned char *)&mb(6)));
5485 			break;
5486 
5487 		case CMD_RBEST4:
5488 			t = ap(pbuffer, sizeof(pbuffer), t, "mode: ");
5489 			switch (mb(0) & 0xF)
5490 			{
5491 			default:
5492 				t = ap(pbuffer, sizeof(pbuffer), t,
5493 				    "0x%x", mb(0) & 0x7);
5494 				break;
5495 
5496 			case 1:
5497 				t = ap(pbuffer, sizeof(pbuffer), t, "0D");
5498 				break;
5499 
5500 			case 3:
5501 				t = ap(pbuffer, sizeof(pbuffer), t, "2D");
5502 				break;
5503 
5504 			case 4:
5505 				t = ap(pbuffer, sizeof(pbuffer), t, "3D");
5506 				break;
5507 			}
5508 			if (mb(0) & 0x10)
5509 				t = ap(pbuffer, sizeof(pbuffer), t, "-MANUAL, ");
5510 			else
5511 				t = ap(pbuffer, sizeof(pbuffer), t, "-AUTO, ");
5512 
5513 			t = ap(pbuffer, sizeof(pbuffer), t, "satellites %02d %02d %02d %02d, PDOP %.2f, HDOP %.2f, VDOP %.2f, TDOP %.2f",
5514 				mb(1), mb(2), mb(3), mb(4),
5515 				getflt((unsigned char *)&mb(5)),
5516 				getflt((unsigned char *)&mb(9)),
5517 				getflt((unsigned char *)&mb(13)),
5518 				getflt((unsigned char *)&mb(17)));
5519 
5520 			break;
5521 
5522 		case CMD_RVERSION:
5523 			t = ap(pbuffer, sizeof(pbuffer), t, "%d.%d (%d/%d/%d)",
5524 				mb(0)&0xff, mb(1)&0xff, 1900+(mb(4)&0xff), mb(2)&0xff, mb(3)&0xff);
5525 			break;
5526 
5527 		case CMD_RRECVHEALTH:
5528 		{
5529 			static const char *msgs[] =
5530 			{
5531 				"Battery backup failed",
5532 				"Signal processor error",
5533 				"Alignment error, channel or chip 1",
5534 				"Alignment error, channel or chip 2",
5535 				"Antenna feed line fault",
5536 				"Excessive ref freq. error",
5537 				"<BIT 6>",
5538 				"<BIT 7>"
5539 			};
5540 
5541 			int i, bits;
5542 
5543 			switch (mb(0) & 0xFF)
5544 			{
5545 			default:
5546 				t = ap(pbuffer, sizeof(pbuffer), t, "illegal value 0x%02x", mb(0) & 0xFF);
5547 				break;
5548 			case 0x00:
5549 				t = ap(pbuffer, sizeof(pbuffer), t, "doing position fixes");
5550 				break;
5551 			case 0x01:
5552 				t = ap(pbuffer, sizeof(pbuffer), t, "no GPS time yet");
5553 				break;
5554 			case 0x03:
5555 				t = ap(pbuffer, sizeof(pbuffer), t, "PDOP too high");
5556 				break;
5557 			case 0x08:
5558 				t = ap(pbuffer, sizeof(pbuffer), t, "no usable satellites");
5559 				break;
5560 			case 0x09:
5561 				t = ap(pbuffer, sizeof(pbuffer), t, "only ONE usable satellite");
5562 				break;
5563 			case 0x0A:
5564 				t = ap(pbuffer, sizeof(pbuffer), t, "only TWO usable satellites");
5565 				break;
5566 			case 0x0B:
5567 				t = ap(pbuffer, sizeof(pbuffer), t, "only THREE usable satellites");
5568 				break;
5569 			case 0x0C:
5570 				t = ap(pbuffer, sizeof(pbuffer), t, "the chosen satellite is unusable");
5571 				break;
5572 			}
5573 
5574 			bits = mb(1) & 0xFF;
5575 
5576 			for (i = 0; i < 8; i++)
5577 				if (bits & (0x1<<i))
5578 				{
5579 					t = ap(pbuffer, sizeof(pbuffer), t, ", %s", msgs[i]);
5580 				}
5581 		}
5582 		break;
5583 
5584 		case CMD_RMESSAGE:
5585 			mkreadable(t, (int)BUFFER_SIZE(pbuffer, t), (char *)&mb(0), (unsigned)(size - 2 - (&mb(0) - buffer)), 0);
5586 			break;
5587 
5588 		case CMD_RMACHSTAT:
5589 		{
5590 			static const char *msgs[] =
5591 			{
5592 				"Synthesizer Fault",
5593 				"Battery Powered Time Clock Fault",
5594 				"A-to-D Converter Fault",
5595 				"The almanac stored in the receiver is not complete and current",
5596 				"<BIT 4>",
5597 				"<BIT 5",
5598 				"<BIT 6>",
5599 				"<BIT 7>"
5600 			};
5601 
5602 			int i, bits;
5603 
5604 			t = ap(pbuffer, sizeof(pbuffer), t, "machine id 0x%02x", mb(0) & 0xFF);
5605 			bits = mb(1) & 0xFF;
5606 
5607 			for (i = 0; i < 8; i++)
5608 				if (bits & (0x1<<i))
5609 				{
5610 					t = ap(pbuffer, sizeof(pbuffer), t, ", %s", msgs[i]);
5611 				}
5612 
5613 			t = ap(pbuffer, sizeof(pbuffer), t, ", Superpackets %ssupported", (mb(2) & 0xFF) ? "" :"un" );
5614 		}
5615 		break;
5616 
5617 		case CMD_ROPERPARAM:
5618 			t = ap(pbuffer, sizeof(pbuffer), t, "%2x %.1f %.1f %.1f %.1f",
5619 				mb(0), getflt((unsigned char *)&mb(1)), getflt((unsigned char *)&mb(5)),
5620 				getflt((unsigned char *)&mb(9)), getflt((unsigned char *)&mb(13)));
5621 			break;
5622 
5623 		case CMD_RUTCPARAM:
5624 		{
5625 			float t0t = getflt((unsigned char *)&mb(14));
5626 			short wnt = (short) getshort((unsigned char *)&mb(18));
5627 			short dtls = (short) getshort((unsigned char *)&mb(12));
5628 			short wnlsf = (short) getshort((unsigned char *)&mb(20));
5629 			short dn = (short) getshort((unsigned char *)&mb(22));
5630 			short dtlsf = (short) getshort((unsigned char *)&mb(24));
5631 
5632 			if ((int)t0t != 0)
5633 			{
5634 				mk_utcinfo(t, wnt, wnlsf, dn, dtls, dtlsf, BUFFER_SIZE(pbuffer, t));
5635 			}
5636 			else
5637 			{
5638 			        t = ap(pbuffer, sizeof(pbuffer), t, "<NO UTC DATA>");
5639 			}
5640 		}
5641 		break;
5642 
5643 		case CMD_RSAT1BIAS:
5644 			t = ap(pbuffer, sizeof(pbuffer), t, "%.1fm %.2fm/s at %.1fs",
5645 				getflt(&mb(0)), getflt(&mb(4)), getflt(&mb(8)));
5646 			break;
5647 
5648 		case CMD_RIOOPTIONS:
5649 		{
5650 			t = ap(pbuffer, sizeof(pbuffer), t, "%02x %02x %02x %02x",
5651 				mb(0), mb(1), mb(2), mb(3));
5652 			if (mb(0) != TRIM_POS_OPT ||
5653 			    mb(2) != TRIM_TIME_OPT)
5654 			{
5655 				(void)trimbletsip_setup(parse, "bad io options");
5656 			}
5657 		}
5658 		break;
5659 
5660 		case CMD_RSPOSXYZ:
5661 		{
5662 			double x = getflt((unsigned char *)&mb(0));
5663 			double y = getflt((unsigned char *)&mb(4));
5664 			double z = getflt((unsigned char *)&mb(8));
5665 			double f = getflt((unsigned char *)&mb(12));
5666 
5667 			if (f > 0.0)
5668 			  t = ap(pbuffer, sizeof(pbuffer), t, "x= %.1fm, y= %.1fm, z= %.1fm, time_of_fix= %f sec",
5669 				  x, y, z,
5670 				  f);
5671 			else
5672 				return;
5673 		}
5674 		break;
5675 
5676 		case CMD_RSLLAPOS:
5677 		{
5678 			double lat = getflt((unsigned char *)&mb(0));
5679 			double lng = getflt((unsigned char *)&mb(4));
5680 			double f   = getflt((unsigned char *)&mb(12));
5681 
5682 			if (f > 0.0)
5683 			  t = ap(pbuffer, sizeof(pbuffer), t, "lat %f %c, long %f %c, alt %.2fm",
5684 				  ((lat < 0.0) ? (-lat) : (lat))*RTOD, (lat < 0.0 ? 'S' : 'N'),
5685 				  ((lng < 0.0) ? (-lng) : (lng))*RTOD, (lng < 0.0 ? 'W' : 'E'),
5686 				  getflt((unsigned char *)&mb(8)));
5687 			else
5688 				return;
5689 		}
5690 		break;
5691 
5692 		case CMD_RDOUBLEXYZ:
5693 		{
5694 			double x = getdbl((unsigned char *)&mb(0));
5695 			double y = getdbl((unsigned char *)&mb(8));
5696 			double z = getdbl((unsigned char *)&mb(16));
5697 			t = ap(pbuffer, sizeof(pbuffer), t, "x= %.1fm, y= %.1fm, z= %.1fm",
5698 				x, y, z);
5699 		}
5700 		break;
5701 
5702 		case CMD_RDOUBLELLA:
5703 		{
5704 			double lat = getdbl((unsigned char *)&mb(0));
5705 			double lng = getdbl((unsigned char *)&mb(8));
5706 			t = ap(pbuffer, sizeof(pbuffer), t, "lat %f %c, lon %f %c, alt %.2fm",
5707 				((lat < 0.0) ? (-lat) : (lat))*RTOD, (lat < 0.0 ? 'S' : 'N'),
5708 				((lng < 0.0) ? (-lng) : (lng))*RTOD, (lng < 0.0 ? 'W' : 'E'),
5709 				getdbl((unsigned char *)&mb(16)));
5710 		}
5711 		break;
5712 
5713 		case CMD_RALLINVIEW:
5714 		{
5715 			int i, sats;
5716 
5717 			t = ap(pbuffer, sizeof(pbuffer), t, "mode: ");
5718 			switch (mb(0) & 0x7)
5719 			{
5720 			default:
5721 				t = ap(pbuffer, sizeof(pbuffer), t, "0x%x", mb(0) & 0x7);
5722 				break;
5723 
5724 			case 3:
5725 				t = ap(pbuffer, sizeof(pbuffer), t, "2D");
5726 				break;
5727 
5728 			case 4:
5729 				t = ap(pbuffer, sizeof(pbuffer), t, "3D");
5730 				break;
5731 			}
5732 			if (mb(0) & 0x8)
5733 				t = ap(pbuffer, sizeof(pbuffer), t, "-MANUAL, ");
5734 			else
5735 				t = ap(pbuffer, sizeof(pbuffer), t, "-AUTO, ");
5736 
5737 			sats = (mb(0)>>4) & 0xF;
5738 
5739 			t = ap(pbuffer, sizeof(pbuffer), t, "PDOP %.2f, HDOP %.2f, VDOP %.2f, TDOP %.2f, %d satellite%s in view: ",
5740 				getflt((unsigned char *)&mb(1)),
5741 				getflt((unsigned char *)&mb(5)),
5742 				getflt((unsigned char *)&mb(9)),
5743 				getflt((unsigned char *)&mb(13)),
5744 				sats, (sats == 1) ? "" : "s");
5745 
5746 			for (i=0; i < sats; i++)
5747 			{
5748 				t = ap(pbuffer, sizeof(pbuffer), t, "%s%02d", i ? ", " : "", mb(17+i));
5749 				if (tr)
5750 					tr->ctrack |= (1 << (mb(17+i)-1));
5751 			}
5752 
5753 			if (tr)
5754 			{	/* mark for tracking status query */
5755 				tr->qtracking = 1;
5756 			}
5757 		}
5758 		break;
5759 
5760 		case CMD_RSTATTRACK:
5761 		{
5762 			t = ap(pbuffer, sizeof(pbuffer), t-2, "[%02d]=\"", mb(0)); /* add index to var name */
5763 			if (getflt((unsigned char *)&mb(4)) < 0.0)
5764 			{
5765 				t = ap(pbuffer, sizeof(pbuffer), t, "<NO MEASUREMENTS>");
5766 				var_flag &= (u_short)(~DEF);
5767 			}
5768 			else
5769 			{
5770 				t = ap(pbuffer, sizeof(pbuffer), t, "ch=%d, acq=%s, eph=%d, signal_level= %5.2f, elevation= %5.2f, azimuth= %6.2f",
5771 					(mb(1) & 0xFF)>>3,
5772 					mb(2) ? ((mb(2) == 1) ? "ACQ" : "SRCH") : "NEVER",
5773 					mb(3),
5774 					getflt((unsigned char *)&mb(4)),
5775 					getflt((unsigned char *)&mb(12)) * RTOD,
5776 					getflt((unsigned char *)&mb(16)) * RTOD);
5777 				if (mb(20))
5778 				{
5779 					var_flag &= (u_short)(~DEF);
5780 					t = ap(pbuffer, sizeof(pbuffer), t, ", OLD");
5781 				}
5782 				if (mb(22))
5783 				{
5784 					if (mb(22) == 1)
5785 						t = ap(pbuffer, sizeof(pbuffer), t, ", BAD PARITY");
5786 					else
5787 						if (mb(22) == 2)
5788 							t = ap(pbuffer, sizeof(pbuffer), t, ", BAD EPH HEALTH");
5789 				}
5790 				if (mb(23))
5791 					t = ap(pbuffer, sizeof(pbuffer), t, ", collecting data");
5792 			}
5793 		}
5794 		break;
5795 
5796 		default:
5797 			t = ap(pbuffer, sizeof(pbuffer), t, "<UNDECODED>");
5798 			break;
5799 		}
5800 
5801 		t = ap(pbuffer, sizeof(pbuffer), t, "\"");
5802 		set_var(&parse->kv, pbuffer, sizeof(pbuffer), var_flag);
5803 	}
5804 }
5805 
5806 
5807 /**============================================================
5808  ** RAWDCF support
5809  **/
5810 
5811 /*--------------------------------------------------
5812  * rawdcf_init_1 - set up modem lines for RAWDCF receivers
5813  * SET DTR line
5814  */
5815 #if defined(TIOCMSET) && (defined(TIOCM_DTR) || defined(CIOCM_DTR))
5816 static int
5817 rawdcf_init_1(
5818 	struct parseunit *parse
5819 	)
5820 {
5821 	/* fixed 2000 for using with Linux by Wolfram Pienkoss <wp@bszh.de> */
5822 	/*
5823 	 * You can use the RS232 to supply the power for a DCF77 receiver.
5824 	 * Here a voltage between the DTR and the RTS line is used. Unfortunately
5825 	 * the name has changed from CIOCM_DTR to TIOCM_DTR recently.
5826 	 */
5827 	int sl232;
5828 
5829 	if (ioctl(parse->generic->io.fd, TIOCMGET, (caddr_t)&sl232) == -1)
5830 	{
5831 		msyslog(LOG_NOTICE, "PARSE receiver #%d: rawdcf_init_1: WARNING: ioctl(fd, TIOCMGET, [C|T]IOCM_DTR): %m", CLK_UNIT(parse->peer));
5832 		return 0;
5833 	}
5834 
5835 #ifdef TIOCM_DTR
5836 	sl232 = (sl232 & ~TIOCM_RTS) | TIOCM_DTR;	/* turn on DTR, clear RTS for power supply */
5837 #else
5838 	sl232 = (sl232 & ~CIOCM_RTS) | CIOCM_DTR;	/* turn on DTR, clear RTS for power supply */
5839 #endif
5840 
5841 	if (ioctl(parse->generic->io.fd, TIOCMSET, (caddr_t)&sl232) == -1)
5842 	{
5843 		msyslog(LOG_NOTICE, "PARSE receiver #%d: rawdcf_init_1: WARNING: ioctl(fd, TIOCMSET, [C|T]IOCM_DTR): %m", CLK_UNIT(parse->peer));
5844 	}
5845 	return 0;
5846 }
5847 #else
5848 static int
5849 rawdcfdtr_init_1(
5850 	struct parseunit *parse
5851 	)
5852 {
5853 	msyslog(LOG_NOTICE, "PARSE receiver #%d: rawdcf_init_1: WARNING: OS interface incapable of setting DTR to power DCF modules", CLK_UNIT(parse->peer));
5854 	return 0;
5855 }
5856 #endif  /* DTR initialisation type */
5857 
5858 /*--------------------------------------------------
5859  * rawdcf_init_2 - set up modem lines for RAWDCF receivers
5860  * CLR DTR line, SET RTS line
5861  */
5862 #if defined(TIOCMSET) &&  (defined(TIOCM_RTS) || defined(CIOCM_RTS))
5863 static int
5864 rawdcf_init_2(
5865 	struct parseunit *parse
5866 	)
5867 {
5868 	/* fixed 2000 for using with Linux by Wolfram Pienkoss <wp@bszh.de> */
5869 	/*
5870 	 * You can use the RS232 to supply the power for a DCF77 receiver.
5871 	 * Here a voltage between the DTR and the RTS line is used. Unfortunately
5872 	 * the name has changed from CIOCM_DTR to TIOCM_DTR recently.
5873 	 */
5874 	int sl232;
5875 
5876 	if (ioctl(parse->generic->io.fd, TIOCMGET, (caddr_t)&sl232) == -1)
5877 	{
5878 		msyslog(LOG_NOTICE, "PARSE receiver #%d: rawdcf_init_2: WARNING: ioctl(fd, TIOCMGET, [C|T]IOCM_RTS): %m", CLK_UNIT(parse->peer));
5879 		return 0;
5880 	}
5881 
5882 #ifdef TIOCM_RTS
5883 	sl232 = (sl232 & ~TIOCM_DTR) | TIOCM_RTS;	/* turn on RTS, clear DTR for power supply */
5884 #else
5885 	sl232 = (sl232 & ~CIOCM_DTR) | CIOCM_RTS;	/* turn on RTS, clear DTR for power supply */
5886 #endif
5887 
5888 	if (ioctl(parse->generic->io.fd, TIOCMSET, (caddr_t)&sl232) == -1)
5889 	{
5890 		msyslog(LOG_NOTICE, "PARSE receiver #%d: rawdcf_init_2: WARNING: ioctl(fd, TIOCMSET, [C|T]IOCM_RTS): %m", CLK_UNIT(parse->peer));
5891 	}
5892 	return 0;
5893 }
5894 #else
5895 static int
5896 rawdcf_init_2(
5897 	struct parseunit *parse
5898 	)
5899 {
5900 	msyslog(LOG_NOTICE, "PARSE receiver #%d: rawdcf_init_2: WARNING: OS interface incapable of setting RTS to power DCF modules", CLK_UNIT(parse->peer));
5901 	return 0;
5902 }
5903 #endif  /* DTR initialisation type */
5904 
5905 #else	/* defined(REFCLOCK) && defined(PARSE) */
5906 NONEMPTY_TRANSLATION_UNIT
5907 #endif	/* defined(REFCLOCK) && defined(PARSE) */
5908 
5909 /*
5910  * History:
5911  *
5912  * refclock_parse.c,v
5913  * Revision 4.81  2009/05/01 10:15:29  kardel
5914  * use new refclock_ppsapi interface
5915  *
5916  * Revision 4.80  2007/08/11 12:06:29  kardel
5917  * update comments wrt/ to PPS
5918  *
5919  * Revision 4.79  2007/08/11 11:52:23  kardel
5920  * - terminate io bindings before io_closeclock() will close our file descriptor
5921  *
5922  * Revision 4.78  2006/12/22 20:08:27  kardel
5923  * Bug 746 (RFE): add configuration for Expert mouseCLOCK USB v2.0 as mode 19
5924  *
5925  * Revision 4.77  2006/08/05 07:44:49  kardel
5926  * support optionally separate PPS devices via /dev/refclockpps-{0..3}
5927  *
5928  * Revision 4.76  2006/06/22 18:40:47  kardel
5929  * clean up signedness (gcc 4)
5930  *
5931  * Revision 4.75  2006/06/22 16:58:10  kardel
5932  * Bug #632: call parse_ppsapi() in parse_ctl() when updating
5933  * the PPS offset. Fix sign of offset passed to kernel.
5934  *
5935  * Revision 4.74  2006/06/18 21:18:37  kardel
5936  * NetBSD Coverity CID 3796: possible NULL deref
5937  *
5938  * Revision 4.73  2006/05/26 14:23:46  kardel
5939  * cleanup of copyright info
5940  *
5941  * Revision 4.72  2006/05/26 14:19:43  kardel
5942  * cleanup of ioctl cruft
5943  *
5944  * Revision 4.71  2006/05/26 14:15:57  kardel
5945  * delay adding refclock to async refclock io after all initializations
5946  *
5947  * Revision 4.70  2006/05/25 18:20:50  kardel
5948  * bug #619
5949  * terminate parse io engine after de-registering
5950  * from refclock io engine
5951  *
5952  * Revision 4.69  2006/05/25 17:28:02  kardel
5953  * complete refclock io structure initialization *before* inserting it into the
5954  * refclock input machine (avoids null pointer deref) (bug #619)
5955  *
5956  * Revision 4.68  2006/05/01 17:02:51  kardel
5957  * copy receiver method also for newlwy created receive buffers
5958  *
5959  * Revision 4.67  2006/05/01 14:37:29  kardel
5960  * If an input buffer parses into more than one message do insert the
5961  * parsed message in a new input buffer instead of processing it
5962  * directly. This avoids deed complicated processing in signal
5963  * handling.
5964  *
5965  * Revision 4.66  2006/03/18 00:45:30  kardel
5966  * coverity fixes found in NetBSD coverity scan
5967  *
5968  * Revision 4.65  2006/01/26 06:08:33  kardel
5969  * output errno on PPS setup failure
5970  *
5971  * Revision 4.64  2005/11/09 20:44:47  kardel
5972  * utilize full PPS timestamp resolution from PPS API
5973  *
5974  * Revision 4.63  2005/10/07 22:10:25  kardel
5975  * bounded buffer implementation
5976  *
5977  * Revision 4.62.2.2  2005/09/25 10:20:16  kardel
5978  * avoid unexpected buffer overflows due to sprintf("%f") on strange floats:
5979  * replace almost all str* and *printf functions be their buffer bounded
5980  * counterparts
5981  *
5982  * Revision 4.62.2.1  2005/08/27 16:19:27  kardel
5983  * limit re-set rate of trimble clocks
5984  *
5985  * Revision 4.62  2005/08/06 17:40:00  kardel
5986  * cleanup size handling wrt/ to buffer boundaries
5987  *
5988  * Revision 4.61  2005/07/27 21:16:19  kardel
5989  * fix a long (> 11 years) misconfiguration wrt/ Meinberg cflag factory
5990  * default setup. CSTOPB was missing for the 7E2 default data format of
5991  * the DCF77 clocks.
5992  *
5993  * Revision 4.60  2005/07/17 21:14:44  kardel
5994  * change contents of version string to include the RCS/CVS Id
5995  *
5996  * Revision 4.59  2005/07/06 06:56:38  kardel
5997  * syntax error
5998  *
5999  * Revision 4.58  2005/07/04 13:10:40  kardel
6000  * fix bug 455: tripping over NULL pointer on cleanup
6001  * fix shadow storage logic for ppsphaseadjust and trustime wrt/ time2
6002  * fix compiler warnings for some platforms wrt/ printf formatstrings and
6003  *     varying structure element sizes
6004  * reorder assignment in binding to avoid tripping over NULL pointers
6005  *
6006  * Revision 4.57  2005/06/25 09:25:19  kardel
6007  * sort out log output sequence
6008  *
6009  * Revision 4.56  2005/06/14 21:47:27  kardel
6010  * collect samples only if samples are ok (sync or trusted flywheel)
6011  * propagate pps phase adjustment value to kernel via PPSAPI to help HARDPPS
6012  * en- and dis-able HARDPPS in correlation to receiver sync state
6013  *
6014  * Revision 4.55  2005/06/02 21:28:31  kardel
6015  * clarify trust logic
6016  *
6017  * Revision 4.54  2005/06/02 17:06:49  kardel
6018  * change status reporting to use fixed refclock_report()
6019  *
6020  * Revision 4.53  2005/06/02 16:33:31  kardel
6021  * fix acceptance of clocks unsync clocks right at start
6022  *
6023  * Revision 4.52  2005/05/26 21:55:06  kardel
6024  * cleanup status reporting
6025  *
6026  * Revision 4.51  2005/05/26 19:19:14  kardel
6027  * implement fast refclock startup
6028  *
6029  * Revision 4.50  2005/04/16 20:51:35  kardel
6030  * set hardpps_enable = 1 when binding a kernel PPS source
6031  *
6032  * Revision 4.49  2005/04/16 17:29:26  kardel
6033  * add non polling clock type 18 for just listenning to Meinberg clocks
6034  *
6035  * Revision 4.48  2005/04/16 16:22:27  kardel
6036  * bk sync 20050415 ntp-dev
6037  *
6038  * Revision 4.47  2004/11/29 10:42:48  kardel
6039  * bk sync ntp-dev 20041129
6040  *
6041  * Revision 4.46  2004/11/29 10:26:29  kardel
6042  * keep fudgetime2 in sync with trusttime/ppsphaseadjust depending in flag1
6043  *
6044  * Revision 4.45  2004/11/14 20:53:20  kardel
6045  * clear PPS flags after using them
6046  *
6047  * Revision 4.44  2004/11/14 15:29:41  kardel
6048  * support PPSAPI, upgrade Copyright to Berkeley style
6049  *
6050  * Revision 4.43  2001/05/26 22:53:16  kardel
6051  * 20010526 reconcilation
6052  *
6053  * Revision 4.42  2000/05/14 15:31:51  kardel
6054  * PPSAPI && RAWDCF modemline support
6055  *
6056  * Revision 4.41  2000/04/09 19:50:45  kardel
6057  * fixed rawdcfdtr_init() -> rawdcf_init_1
6058  *
6059  * Revision 4.40  2000/04/09 15:27:55  kardel
6060  * modem line fiddle in rawdcf_init_2
6061  *
6062  * Revision 4.39  2000/03/18 09:16:55  kardel
6063  * PPSAPI integration
6064  *
6065  * Revision 4.38  2000/03/05 20:25:06  kardel
6066  * support PPSAPI
6067  *
6068  * Revision 4.37  2000/03/05 20:11:14  kardel
6069  * 4.0.99g reconcilation
6070  *
6071  * Revision 4.36  1999/11/28 17:18:20  kardel
6072  * disabled burst mode
6073  *
6074  * Revision 4.35  1999/11/28 09:14:14  kardel
6075  * RECON_4_0_98F
6076  *
6077  * Revision 4.34  1999/05/14 06:08:05  kardel
6078  * store current_time in a suitable container (u_long)
6079  *
6080  * Revision 4.33  1999/05/13 21:48:38  kardel
6081  * double the no response timeout interval
6082  *
6083  * Revision 4.32  1999/05/13 20:09:13  kardel
6084  * complain only about missing polls after a full poll interval
6085  *
6086  * Revision 4.31  1999/05/13 19:59:32  kardel
6087  * add clock type 16 for RTS set DTR clr in RAWDCF
6088  *
6089  * Revision 4.30  1999/02/28 20:36:43  kardel
6090  * fixed printf fmt
6091  *
6092  * Revision 4.29  1999/02/28 19:58:23  kardel
6093  * updated copyright information
6094  *
6095  * Revision 4.28  1999/02/28 19:01:50  kardel
6096  * improved debug out on sent Meinberg messages
6097  *
6098  * Revision 4.27  1999/02/28 18:05:55  kardel
6099  * no linux/ppsclock.h stuff
6100  *
6101  * Revision 4.26  1999/02/28 15:27:27  kardel
6102  * wharton clock integration
6103  *
6104  * Revision 4.25  1999/02/28 14:04:46  kardel
6105  * added missing double quotes to UTC information string
6106  *
6107  * Revision 4.24  1999/02/28 12:06:50  kardel
6108  * (parse_control): using gmprettydate instead of prettydate()
6109  * (mk_utcinfo): new function for formatting GPS derived UTC information
6110  * (gps16x_message): changed to use mk_utcinfo()
6111  * (trimbletsip_message): changed to use mk_utcinfo()
6112  * ignoring position information in unsynchronized mode
6113  * (parse_start): augument linux support for optional ASYNC_LOW_LATENCY
6114  *
6115  * Revision 4.23  1999/02/23 19:47:53  kardel
6116  * fixed #endifs
6117  * (stream_receive): fixed formats
6118  *
6119  * Revision 4.22  1999/02/22 06:21:02  kardel
6120  * use new autoconfig symbols
6121  *
6122  * Revision 4.21  1999/02/21 12:18:13  kardel
6123  * 4.91f reconcilation
6124  *
6125  * Revision 4.20  1999/02/21 10:53:36  kardel
6126  * initial Linux PPSkit version
6127  *
6128  * Revision 4.19  1999/02/07 09:10:45  kardel
6129  * clarify STREAMS mitigation rules in comment
6130  *
6131  * Revision 4.18  1998/12/20 23:45:34  kardel
6132  * fix types and warnings
6133  *
6134  * Revision 4.17  1998/11/15 21:24:51  kardel
6135  * cannot access mbg_ routines when CLOCK_MEINBERG
6136  * is not defined
6137  *
6138  * Revision 4.16  1998/11/15 20:28:17  kardel
6139  * Release 4.0.73e13 reconcilation
6140  *
6141  * Revision 4.15  1998/08/22 21:56:08  kardel
6142  * fixed IO handling for non-STREAM IO
6143  *
6144  * Revision 4.14  1998/08/16 19:00:48  kardel
6145  * (gps16x_message): reduced UTC parameter information (dropped A0,A1)
6146  * made uval a local variable (killed one of the last globals)
6147  * (sendetx): added logging of messages when in debug mode
6148  * (trimble_check): added periodic checks to facilitate re-initialization
6149  * (trimbletsip_init): made use of EOL character if in non-kernel operation
6150  * (trimbletsip_message): extended message interpretation
6151  * (getdbl): fixed data conversion
6152  *
6153  * Revision 4.13  1998/08/09 22:29:13  kardel
6154  * Trimble TSIP support
6155  *
6156  * Revision 4.12  1998/07/11 10:05:34  kardel
6157  * Release 4.0.73d reconcilation
6158  *
6159  * Revision 4.11  1998/06/14 21:09:42  kardel
6160  * Sun acc cleanup
6161  *
6162  * Revision 4.10  1998/06/13 12:36:45  kardel
6163  * signed/unsigned, name clashes
6164  *
6165  * Revision 4.9  1998/06/12 15:30:00  kardel
6166  * prototype fixes
6167  *
6168  * Revision 4.8  1998/06/12 11:19:42  kardel
6169  * added direct input processing routine for refclocks in
6170  * order to avaiod that single character io gobbles up all
6171  * receive buffers and drops input data. (Problem started
6172  * with fast machines so a character a buffer was possible
6173  * one of the few cases where faster machines break existing
6174  * allocation algorithms)
6175  *
6176  * Revision 4.7  1998/06/06 18:35:20  kardel
6177  * (parse_start): added BURST mode initialisation
6178  *
6179  * Revision 4.6  1998/05/27 06:12:46  kardel
6180  * RAWDCF_BASEDELAY default added
6181  * old comment removed
6182  * casts for ioctl()
6183  *
6184  * Revision 4.5  1998/05/25 22:05:09  kardel
6185  * RAWDCF_SETDTR option removed
6186  * clock type 14 attempts to set DTR for
6187  * power supply of RAWDCF receivers
6188  *
6189  * Revision 4.4  1998/05/24 16:20:47  kardel
6190  * updated comments referencing Meinberg clocks
6191  * added RAWDCF clock with DTR set option as type 14
6192  *
6193  * Revision 4.3  1998/05/24 10:48:33  kardel
6194  * calibrated CONRAD RAWDCF default fudge factor
6195  *
6196  * Revision 4.2  1998/05/24 09:59:35  kardel
6197  * corrected version information (ntpq support)
6198  *
6199  * Revision 4.1  1998/05/24 09:52:31  kardel
6200  * use fixed format only (new IO model)
6201  * output debug to stdout instead of msyslog()
6202  * don't include >"< in ASCII output in order not to confuse
6203  * ntpq parsing
6204  *
6205  * Revision 4.0  1998/04/10 19:52:11  kardel
6206  * Start 4.0 release version numbering
6207  *
6208  * Revision 1.2  1998/04/10 19:28:04  kardel
6209  * initial NTP VERSION 4 integration of PARSE with GPS166 binary support
6210  * derived from 3.105.1.2 from V3 tree
6211  *
6212  * Revision information 3.1 - 3.105 from log deleted 1998/04/10 kardel
6213  *
6214  */
6215