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