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