xref: /openbsd-src/sys/kern/tty_endrun.c (revision 91f110e064cd7c194e59e019b83bb7496c1c84d4)
1 /*	$OpenBSD: tty_endrun.c,v 1.3 2010/04/12 12:57:52 tedu Exp $ */
2 
3 /*
4  * Copyright (c) 2008 Marc Balmer <mbalmer@openbsd.org>
5  * Copyright (c) 2009 Kevin Steves <stevesk@openbsd.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 /*
21  * A tty line discipline to decode the EndRun Technologies native
22  * time-of-day message.
23  * http://www.endruntechnologies.com/
24  */
25 
26 /*
27  * EndRun Format:
28  *
29  * T YYYY DDD HH:MM:SS zZZ m<CR><LF>
30  *
31  * T is the Time Figure of Merit (TFOM) character (described below).
32  * This is the on-time character, transmitted during the first
33  * millisecond of each second.
34  *
35  * YYYY is the year
36  * DDD is the day-of-year
37  * : is the colon character (0x3A)
38  * HH is the hour of the day
39  * MM is the minute of the hour
40  * SS is the second of the minute
41  * z is the sign of the offset to UTC, + implies time is ahead of UTC.
42  * ZZ is the magnitude of the offset to UTC in units of half-hours.
43  * Non-zero only when the Timemode is Local.
44  * m is the Timemode character and is one of:
45  *   G = GPS
46  *   L = Local
47  *   U = UTC
48  * <CR> is the ASCII carriage return character (0x0D)
49  * <LF> is the ASCII line feed character (0x0A)
50  */
51 
52 #include <sys/param.h>
53 #include <sys/systm.h>
54 #include <sys/proc.h>
55 #include <sys/malloc.h>
56 #include <sys/sensors.h>
57 #include <sys/tty.h>
58 #include <sys/conf.h>
59 #include <sys/time.h>
60 
61 #ifdef ENDRUN_DEBUG
62 #define DPRINTFN(n, x)	do { if (endrundebug > (n)) printf x; } while (0)
63 int endrundebug = 0;
64 #else
65 #define DPRINTFN(n, x)
66 #endif
67 #define DPRINTF(x)	DPRINTFN(0, x)
68 
69 int	endrunopen(dev_t, struct tty *, struct proc *p);
70 int	endrunclose(struct tty *, int, struct proc *p);
71 int	endruninput(int, struct tty *);
72 void	endrunattach(int);
73 
74 #define ENDRUNLEN	27 /* strlen("6 2009 018 20:41:17 +00 U\r\n") */
75 #define NUMFLDS		6
76 #ifdef ENDRUN_DEBUG
77 #define TRUSTTIME	30
78 #else
79 #define TRUSTTIME	(10 * 60)	/* 10 minutes */
80 #endif
81 
82 int endrun_count, endrun_nxid;
83 
84 struct endrun {
85 	char			cbuf[ENDRUNLEN];	/* receive buffer */
86 	struct ksensor		time;		/* the timedelta sensor */
87 	struct ksensor		signal;		/* signal status */
88 	struct ksensordev	timedev;
89 	struct timespec		ts;		/* current timestamp */
90 	struct timespec		lts;		/* timestamp of last TFOM */
91 	struct timeout		endrun_tout;	/* invalidate sensor */
92 	int64_t			gap;		/* gap between two sentences */
93 	int64_t			last;		/* last time rcvd */
94 #define SYNC_SCAN	1	/* scanning for '\n' */
95 #define SYNC_EOL	2	/* '\n' seen, next char TFOM */
96 	int			sync;
97 	int			pos;		/* position in rcv buffer */
98 	int			no_pps;		/* no PPS although requested */
99 #ifdef ENDRUN_DEBUG
100 	char			tfom;
101 #endif
102 };
103 
104 /* EndRun decoding */
105 void	endrun_scan(struct endrun *, struct tty *);
106 void	endrun_decode(struct endrun *, struct tty *, char *fld[], int fldcnt);
107 
108 /* date and time conversion */
109 int	endrun_atoi(char *s, int len);
110 int	endrun_date_to_nano(char *s1, char *s2, int64_t *nano);
111 int	endrun_time_to_nano(char *s, int64_t *nano);
112 int	endrun_offset_to_nano(char *s, int64_t *nano);
113 
114 /* degrade the timedelta sensor */
115 void	endrun_timeout(void *);
116 
117 void
118 endrunattach(int dummy)
119 {
120 }
121 
122 int
123 endrunopen(dev_t dev, struct tty *tp, struct proc *p)
124 {
125 	struct endrun *np;
126 	int error;
127 
128 	DPRINTF(("endrunopen\n"));
129 	if (tp->t_line == ENDRUNDISC)
130 		return ENODEV;
131 	if ((error = suser(p, 0)) != 0)
132 		return error;
133 	np = malloc(sizeof(struct endrun), M_DEVBUF, M_WAITOK|M_ZERO);
134 	snprintf(np->timedev.xname, sizeof(np->timedev.xname), "endrun%d",
135 	    endrun_nxid++);
136 	endrun_count++;
137 	np->time.status = SENSOR_S_UNKNOWN;
138 	np->time.type = SENSOR_TIMEDELTA;
139 #ifndef ENDRUN_DEBUG
140 	np->time.flags = SENSOR_FINVALID;
141 #endif
142 	sensor_attach(&np->timedev, &np->time);
143 
144 	np->signal.type = SENSOR_PERCENT;
145 	np->signal.status = SENSOR_S_UNKNOWN;
146 	np->signal.value = 100000LL;
147 	strlcpy(np->signal.desc, "Signal", sizeof(np->signal.desc));
148 	sensor_attach(&np->timedev, &np->signal);
149 
150 	np->sync = SYNC_SCAN;
151 #ifdef ENDRUN_DEBUG
152 	np->tfom = '0';
153 #endif
154 	tp->t_sc = (caddr_t)np;
155 
156 	error = linesw[TTYDISC].l_open(dev, tp, p);
157 	if (error) {
158 		free(np, M_DEVBUF);
159 		tp->t_sc = NULL;
160 	} else {
161 		sensordev_install(&np->timedev);
162 		timeout_set(&np->endrun_tout, endrun_timeout, np);
163 	}
164 
165 	return error;
166 }
167 
168 int
169 endrunclose(struct tty *tp, int flags, struct proc *p)
170 {
171 	struct endrun *np = (struct endrun *)tp->t_sc;
172 
173 	DPRINTF(("endrunclose\n"));
174 	tp->t_line = TTYDISC;	/* switch back to termios */
175 	timeout_del(&np->endrun_tout);
176 	sensordev_deinstall(&np->timedev);
177 	free(np, M_DEVBUF);
178 	tp->t_sc = NULL;
179 	endrun_count--;
180 	if (endrun_count == 0)
181 		endrun_nxid = 0;
182 	return linesw[TTYDISC].l_close(tp, flags, p);
183 }
184 
185 /* collect EndRun sentence from tty */
186 int
187 endruninput(int c, struct tty *tp)
188 {
189 	struct endrun *np = (struct endrun *)tp->t_sc;
190 	struct timespec ts;
191 	int64_t gap;
192 	long tmin, tmax;
193 
194 	if (np->sync == SYNC_EOL) {
195 		nanotime(&ts);
196 		np->pos = 0;
197 		np->sync = SYNC_SCAN;
198 		np->cbuf[np->pos++] = c; /* TFOM char */
199 
200 		gap = (ts.tv_sec * 1000000000LL + ts.tv_nsec) -
201 		    (np->lts.tv_sec * 1000000000LL + np->lts.tv_nsec);
202 
203 		np->lts.tv_sec = ts.tv_sec;
204 		np->lts.tv_nsec = ts.tv_nsec;
205 
206 		if (gap <= np->gap)
207 			goto nogap;
208 
209 		np->ts.tv_sec = ts.tv_sec;
210 		np->ts.tv_nsec = ts.tv_nsec;
211 		np->gap = gap;
212 
213 		/*
214 		 * If a tty timestamp is available, make sure its value is
215 		 * reasonable by comparing against the timestamp just taken.
216 		 * If they differ by more than 2 seconds, assume no PPS signal
217 		 * is present, note the fact, and keep using the timestamp
218 		 * value.  When this happens, the sensor state is set to
219 		 * CRITICAL later when the EndRun sentence is decoded.
220 		 */
221 		if (tp->t_flags & (TS_TSTAMPDCDSET | TS_TSTAMPDCDCLR |
222 		    TS_TSTAMPCTSSET | TS_TSTAMPCTSCLR)) {
223 			tmax = lmax(np->ts.tv_sec, tp->t_tv.tv_sec);
224 			tmin = lmin(np->ts.tv_sec, tp->t_tv.tv_sec);
225 			if (tmax - tmin > 1)
226 				np->no_pps = 1;
227 			else {
228 				np->ts.tv_sec = tp->t_tv.tv_sec;
229 				np->ts.tv_nsec = tp->t_tv.tv_usec *
230 				    1000L;
231 				np->no_pps = 0;
232 			}
233 		}
234 	} else if (c == '\n') {
235 		if (np->pos == ENDRUNLEN - 1) {
236 			/* don't copy '\n' into cbuf */
237 			np->cbuf[np->pos] = '\0';
238 			endrun_scan(np, tp);
239 		}
240 		np->sync = SYNC_EOL;
241 	} else {
242 		if (np->pos < ENDRUNLEN - 1)
243 			np->cbuf[np->pos++] = c;
244 	}
245 
246 nogap:
247 	/* pass data to termios */
248 	return linesw[TTYDISC].l_rint(c, tp);
249 }
250 
251 /* Scan the EndRun sentence just received */
252 void
253 endrun_scan(struct endrun *np, struct tty *tp)
254 {
255 	int fldcnt = 0, n;
256 	char *fld[NUMFLDS], *cs;
257 
258 	DPRINTFN(1, ("%s\n", np->cbuf));
259 	/* split into fields */
260 	fld[fldcnt++] = &np->cbuf[0];
261 	for (cs = NULL, n = 0; n < np->pos && cs == NULL; n++) {
262 		switch (np->cbuf[n]) {
263 		case '\r':
264 			np->cbuf[n] = '\0';
265 			cs = &np->cbuf[n + 1];
266 			break;
267 		case ' ':
268 			if (fldcnt < NUMFLDS) {
269 				np->cbuf[n] = '\0';
270 				fld[fldcnt++] = &np->cbuf[n + 1];
271 			} else {
272 				DPRINTF(("endrun: nr of fields in sentence "
273 				    "exceeds expected: %d\n", NUMFLDS));
274 				return;
275 			}
276 			break;
277 		}
278 	}
279 	endrun_decode(np, tp, fld, fldcnt);
280 }
281 
282 /* Decode the time string */
283 void
284 endrun_decode(struct endrun *np, struct tty *tp, char *fld[], int fldcnt)
285 {
286 	int64_t date_nano, time_nano, offset_nano, endrun_now;
287 	char tfom;
288 	int jumped = 0;
289 
290 	if (fldcnt != NUMFLDS) {
291 		DPRINTF(("endrun: field count mismatch, %d\n", fldcnt));
292 		return;
293 	}
294 	if (endrun_time_to_nano(fld[3], &time_nano) == -1) {
295 		DPRINTF(("endrun: illegal time, %s\n", fld[3]));
296 		return;
297 	}
298 	if (endrun_date_to_nano(fld[1], fld[2], &date_nano) == -1) {
299 		DPRINTF(("endrun: illegal date, %s %s\n", fld[1], fld[2]));
300 		return;
301 	}
302 	offset_nano = 0;
303 	/* only parse offset when timemode is local */
304 	if (fld[5][0] == 'L' &&
305 	    endrun_offset_to_nano(fld[4], &offset_nano) == -1) {
306 		DPRINTF(("endrun: illegal offset, %s\n", fld[4]));
307 		return;
308 	}
309 
310 	endrun_now = date_nano + time_nano + offset_nano;
311 	if (endrun_now <= np->last) {
312 		DPRINTF(("endrun: time not monotonically increasing "
313 		    "last %lld now %lld\n",
314 		    (long long)np->last, (long long)endrun_now));
315 		jumped = 1;
316 	}
317 	np->last = endrun_now;
318 	np->gap = 0LL;
319 #ifdef ENDRUN_DEBUG
320 	if (np->time.status == SENSOR_S_UNKNOWN) {
321 		np->time.status = SENSOR_S_OK;
322 		timeout_add_sec(&np->endrun_tout, TRUSTTIME);
323 	}
324 #endif
325 
326 	np->time.value = np->ts.tv_sec * 1000000000LL +
327 	    np->ts.tv_nsec - endrun_now;
328 	np->time.tv.tv_sec = np->ts.tv_sec;
329 	np->time.tv.tv_usec = np->ts.tv_nsec / 1000L;
330 	if (np->time.status == SENSOR_S_UNKNOWN) {
331 		np->time.status = SENSOR_S_OK;
332 		np->time.flags &= ~SENSOR_FINVALID;
333 		strlcpy(np->time.desc, "EndRun", sizeof(np->time.desc));
334 	}
335 	/*
336 	 * Only update the timeout if the clock reports the time as valid.
337 	 *
338 	 * Time Figure Of Merit (TFOM) values:
339 	 *
340 	 * 6  - time error is < 100 us
341 	 * 7  - time error is < 1 ms
342 	 * 8  - time error is < 10 ms
343 	 * 9  - time error is > 10 ms,
344 	 *      unsynchronized state if never locked to CDMA
345 	 */
346 
347 	switch (tfom = fld[0][0]) {
348 	case '6':
349 	case '7':
350 	case '8':
351 		np->time.status = SENSOR_S_OK;
352 		np->signal.status = SENSOR_S_OK;
353 		break;
354 	case '9':
355 		np->signal.status = SENSOR_S_WARN;
356 		break;
357 	default:
358 		DPRINTF(("endrun: invalid TFOM: '%c'\n", tfom));
359 		np->signal.status = SENSOR_S_CRIT;
360 		break;
361 	}
362 
363 #ifdef ENDRUN_DEBUG
364 	if (np->tfom != tfom) {
365 		DPRINTF(("endrun: TFOM changed from %c to %c\n",
366 		    np->tfom, tfom));
367 		np->tfom = tfom;
368 	}
369 #endif
370 	if (jumped)
371 		np->time.status = SENSOR_S_WARN;
372 	if (np->time.status == SENSOR_S_OK)
373 		timeout_add_sec(&np->endrun_tout, TRUSTTIME);
374 
375 	/*
376 	 * If tty timestamping is requested, but no PPS signal is present, set
377 	 * the sensor state to CRITICAL.
378 	 */
379 	if (np->no_pps)
380 		np->time.status = SENSOR_S_CRIT;
381 }
382 
383 int
384 endrun_atoi(char *s, int len)
385 {
386 	int n;
387 	char *p;
388 
389 	/* make sure the input contains only numbers */
390 	for (n = 0, p = s; n < len && *p && *p >= '0' && *p <= '9'; n++, p++)
391 		;
392 	if (n != len || *p != '\0')
393 		return -1;
394 
395 	for (n = 0; *s; s++)
396 		n = n * 10 + *s - '0';
397 
398 	return n;
399 }
400 
401 /*
402  * Convert date fields from EndRun to nanoseconds since the epoch.
403  * The year string must be of the form YYYY .
404  * The day of year string must be of the form DDD .
405  * Return 0 on success, -1 if illegal characters are encountered.
406  */
407 int
408 endrun_date_to_nano(char *y, char *doy, int64_t *nano)
409 {
410 	struct clock_ymdhms clock;
411 	time_t secs;
412 	int n, i;
413 	int year_days = 365;
414 	int month_days[] = {
415 		0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
416 	};
417 
418 #define FEBRUARY		2
419 
420 #define LEAPYEAR(x)		\
421 	((x) % 4 == 0 &&	\
422 	(x) % 100 != 0) ||	\
423 	(x) % 400 == 0
424 
425 	if ((n = endrun_atoi(y, 4)) == -1)
426 		return -1;
427 	clock.dt_year = n;
428 
429 	if (LEAPYEAR(n)) {
430 		month_days[FEBRUARY]++;
431 		year_days++;
432 	}
433 
434 	if ((n = endrun_atoi(doy, 3)) == -1 || n == 0 || n > year_days)
435 		return -1;
436 
437 	/* convert day of year to month, day */
438 	for (i = 1; n > month_days[i]; i++) {
439 		n -= month_days[i];
440 	}
441 	clock.dt_mon = i;
442 	clock.dt_day = n;
443 
444 	DPRINTFN(1, ("mm/dd %d/%d\n", i, n));
445 
446 	clock.dt_hour = clock.dt_min = clock.dt_sec = 0;
447 
448 	secs = clock_ymdhms_to_secs(&clock);
449 	*nano = secs * 1000000000LL;
450 	return 0;
451 }
452 
453 /*
454  * Convert time field from EndRun to nanoseconds since midnight.
455  * The string must be of the form HH:MM:SS .
456  * Return 0 on success, -1 if illegal characters are encountered.
457  */
458 int
459 endrun_time_to_nano(char *s, int64_t *nano)
460 {
461 	struct clock_ymdhms clock;
462 	time_t secs;
463 	int n;
464 
465 	if (s[2] != ':' || s[5] != ':')
466 		return -1;
467 
468 	s[2] = '\0';
469 	s[5] = '\0';
470 
471 	if ((n = endrun_atoi(&s[0], 2)) == -1 || n > 23)
472 		return -1;
473 	clock.dt_hour = n;
474 	if ((n = endrun_atoi(&s[3], 2)) == -1 || n > 59)
475 		return -1;
476 	clock.dt_min = n;
477 	if ((n = endrun_atoi(&s[6], 2)) == -1 || n > 60)
478 		return -1;
479 	clock.dt_sec = n;
480 
481 	DPRINTFN(1, ("hh:mm:ss %d:%d:%d\n", (int)clock.dt_hour,
482 	    (int)clock.dt_min,
483 	    (int)clock.dt_sec));
484 	secs = clock.dt_hour * 3600
485 	    + clock.dt_min * 60
486 	    + clock.dt_sec;
487 
488 	DPRINTFN(1, ("secs %lu\n", (unsigned long)secs));
489 
490 	*nano = secs * 1000000000LL;
491 	return 0;
492 }
493 
494 int
495 endrun_offset_to_nano(char *s, int64_t *nano)
496 {
497 	time_t secs;
498 	int n;
499 
500 	if (!(s[0] == '+' || s[0] == '-'))
501 		return -1;
502 
503 	if ((n = endrun_atoi(&s[1], 2)) == -1)
504 		return -1;
505 	secs = n * 30 * 60;
506 
507 	*nano = secs * 1000000000LL;
508 	if (s[0] == '+')
509 		*nano = -*nano;
510 
511 	DPRINTFN(1, ("offset secs %lu nanosecs %lld\n",
512 	    (unsigned long)secs, (long long)*nano));
513 
514 	return 0;
515 }
516 
517 /*
518  * Degrade the sensor state if we received no EndRun string for more than
519  * TRUSTTIME seconds.
520  */
521 void
522 endrun_timeout(void *xnp)
523 {
524 	struct endrun *np = xnp;
525 
526 	if (np->time.status == SENSOR_S_OK) {
527 		np->time.status = SENSOR_S_WARN;
528 		/*
529 		 * further degrade in TRUSTTIME seconds if no new valid EndRun
530 		 * strings are received.
531 		 */
532 		timeout_add_sec(&np->endrun_tout, TRUSTTIME);
533 	} else
534 		np->time.status = SENSOR_S_CRIT;
535 }
536