refclock_shm.c revision 1.2.4.1 1 /* $NetBSD: refclock_shm.c,v 1.2.4.1 2014/12/24 00:05:21 riz Exp $ */
2
3 /*
4 * refclock_shm - clock driver for utc via shared memory
5 * - under construction -
6 * To add new modes: Extend or union the shmTime-struct. Do not
7 * extend/shrink size, because otherwise existing implementations
8 * will specify wrong size of shared memory-segment
9 * PB 18.3.97
10 */
11
12 #ifdef HAVE_CONFIG_H
13 # include <config.h>
14 #endif
15
16 #include "ntp_types.h"
17
18 #if defined(REFCLOCK) && defined(CLOCK_SHM)
19
20 #include "ntpd.h"
21 #undef fileno
22 #include "ntp_io.h"
23 #undef fileno
24 #include "ntp_refclock.h"
25 #undef fileno
26 #include "timespecops.h"
27 #undef fileno
28 #include "ntp_stdlib.h"
29
30 #undef fileno
31 #include <ctype.h>
32 #undef fileno
33
34 #ifndef SYS_WINNT
35 # include <sys/ipc.h>
36 # include <sys/shm.h>
37 # include <assert.h>
38 # include <unistd.h>
39 # include <stdio.h>
40 #endif
41
42 /*
43 * This driver supports a reference clock attached thru shared memory
44 */
45
46 /*
47 * SHM interface definitions
48 */
49 #define PRECISION (-1) /* precision assumed (0.5 s) */
50 #define REFID "SHM" /* reference ID */
51 #define DESCRIPTION "SHM/Shared memory interface"
52
53 #define NSAMPLES 3 /* stages of median filter */
54
55 /*
56 * Function prototypes
57 */
58 static int shm_start (int unit, struct peer *peer);
59 static void shm_shutdown (int unit, struct peer *peer);
60 static void shm_poll (int unit, struct peer *peer);
61 static void shm_timer (int unit, struct peer *peer);
62 static void shm_peek (int unit, struct peer *peer);
63 static void shm_clockstats (int unit, struct peer *peer);
64 static void shm_control (int unit, const struct refclockstat * in_st,
65 struct refclockstat * out_st, struct peer *peer);
66
67 /*
68 * Transfer vector
69 */
70 struct refclock refclock_shm = {
71 shm_start, /* start up driver */
72 shm_shutdown, /* shut down driver */
73 shm_poll, /* transmit poll message */
74 shm_control, /* control settings */
75 noentry, /* not used: init */
76 noentry, /* not used: buginfo */
77 shm_timer, /* once per second */
78 };
79
80 struct shmTime {
81 int mode; /* 0 - if valid is set:
82 * use values,
83 * clear valid
84 * 1 - if valid is set:
85 * if count before and after read of values is equal,
86 * use values
87 * clear valid
88 */
89 volatile int count;
90 time_t clockTimeStampSec;
91 int clockTimeStampUSec;
92 time_t receiveTimeStampSec;
93 int receiveTimeStampUSec;
94 int leap;
95 int precision;
96 int nsamples;
97 volatile int valid;
98 unsigned clockTimeStampNSec; /* Unsigned ns timestamps */
99 unsigned receiveTimeStampNSec; /* Unsigned ns timestamps */
100 int dummy[8];
101 };
102
103 struct shmunit {
104 struct shmTime *shm; /* pointer to shared memory segment */
105
106 /* debugging/monitoring counters - reset when printed */
107 int ticks; /* number of attempts to read data*/
108 int good; /* number of valid samples */
109 int notready; /* number of peeks without data ready */
110 int bad; /* number of invalid samples */
111 int clash; /* number of access clashes while reading */
112
113 time_t max_delta; /* difference limit */
114 time_t max_delay; /* age/stale limit */
115 };
116
117
118 struct shmTime *getShmTime(int);
119
120 struct shmTime *getShmTime (int unit) {
121 #ifndef SYS_WINNT
122 int shmid=0;
123
124 /* 0x4e545030 is NTP0.
125 * Big units will give non-ascii but that's OK
126 * as long as everybody does it the same way.
127 */
128 shmid=shmget (0x4e545030 + unit, sizeof (struct shmTime),
129 IPC_CREAT | ((unit < 2) ? 0600 : 0666));
130 if (shmid == -1) { /* error */
131 msyslog(LOG_ERR, "SHM shmget (unit %d): %m", unit);
132 return 0;
133 }
134 else { /* no error */
135 struct shmTime *p = (struct shmTime *)shmat (shmid, 0, 0);
136 if (p == (struct shmTime *)-1) { /* error */
137 msyslog(LOG_ERR, "SHM shmat (unit %d): %m", unit);
138 return 0;
139 }
140 return p;
141 }
142 #else
143 char buf[10];
144 LPSECURITY_ATTRIBUTES psec = 0;
145 HANDLE shmid = 0;
146 SECURITY_DESCRIPTOR sd;
147 SECURITY_ATTRIBUTES sa;
148
149 snprintf(buf, sizeof(buf), "NTP%d", unit);
150 if (unit >= 2) { /* world access */
151 if (!InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) {
152 msyslog(LOG_ERR,"SHM InitializeSecurityDescriptor (unit %d): %m", unit);
153 return 0;
154 }
155 if (!SetSecurityDescriptorDacl(&sd, 1, 0, 0)) {
156 msyslog(LOG_ERR, "SHM SetSecurityDescriptorDacl (unit %d): %m", unit);
157 return 0;
158 }
159 sa.nLength=sizeof (SECURITY_ATTRIBUTES);
160 sa.lpSecurityDescriptor = &sd;
161 sa.bInheritHandle = 0;
162 psec = &sa;
163 }
164 shmid = CreateFileMapping ((HANDLE)0xffffffff, psec, PAGE_READWRITE,
165 0, sizeof (struct shmTime), buf);
166 if (!shmid) { /*error*/
167 char buf[1000];
168
169 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM,
170 0, GetLastError (), 0, buf, sizeof (buf), 0);
171 msyslog(LOG_ERR, "SHM CreateFileMapping (unit %d): %s", unit, buf);
172 return 0;
173 } else {
174 struct shmTime *p = (struct shmTime *) MapViewOfFile (shmid,
175 FILE_MAP_WRITE, 0, 0, sizeof (struct shmTime));
176 if (p == 0) { /*error*/
177 char buf[1000];
178
179 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM,
180 0, GetLastError (), 0, buf, sizeof (buf), 0);
181 msyslog(LOG_ERR,"SHM MapViewOfFile (unit %d): %s", unit, buf)
182 return 0;
183 }
184 return p;
185 }
186 #endif
187 }
188 /*
189 * shm_start - attach to shared memory
190 */
191 static int
192 shm_start(
193 int unit,
194 struct peer *peer
195 )
196 {
197 struct refclockproc *pp;
198 struct shmunit *up;
199
200 pp = peer->procptr;
201 pp->io.clock_recv = noentry;
202 pp->io.srcclock = peer;
203 pp->io.datalen = 0;
204 pp->io.fd = -1;
205
206 up = emalloc_zero(sizeof(*up));
207
208 up->shm = getShmTime(unit);
209
210 /*
211 * Initialize miscellaneous peer variables
212 */
213 memcpy((char *)&pp->refid, REFID, 4);
214 if (up->shm != 0) {
215 pp->unitptr = up;
216 up->shm->precision = PRECISION;
217 peer->precision = up->shm->precision;
218 up->shm->valid = 0;
219 up->shm->nsamples = NSAMPLES;
220 pp->clockdesc = DESCRIPTION;
221 /* items to be changed later in 'shm_control()': */
222 up->max_delay = 5;
223 up->max_delta = 4*3600;
224 return 1;
225 } else {
226 free(up);
227 pp->unitptr = NULL;
228 return 0;
229 }
230 }
231
232
233 /*
234 * shm_control - configure flag1/time2 params
235 *
236 * These are not yet available during 'shm_start', so we have to do any
237 * pre-computations we want to avoid during regular poll/timer callbacks
238 * in this callback.
239 */
240 static void
241 shm_control(
242 int unit,
243 const struct refclockstat * in_st,
244 struct refclockstat * out_st,
245 struct peer * peer
246 )
247 {
248 struct refclockproc *pp;
249 struct shmunit *up;
250
251 pp = peer->procptr;
252 up = pp->unitptr;
253
254 if (NULL == up)
255 return;
256 if (pp->sloppyclockflag & CLK_FLAG1)
257 up->max_delta = 0;
258 else if (pp->fudgetime2 < 1. || pp->fudgetime2 > 86400.)
259 up->max_delta = 4*3600;
260 else
261 up->max_delta = (time_t)floor(pp->fudgetime2 + 0.5);
262 }
263
264
265 /*
266 * shm_shutdown - shut down the clock
267 */
268 static void
269 shm_shutdown(
270 int unit,
271 struct peer *peer
272 )
273 {
274 struct refclockproc *pp;
275 struct shmunit *up;
276
277 pp = peer->procptr;
278 up = pp->unitptr;
279
280 if (NULL == up)
281 return;
282 #ifndef SYS_WINNT
283 /* HMS: shmdt() wants char* or const void * */
284 (void) shmdt ((char *)up->shm);
285 #else
286 UnmapViewOfFile (up->shm);
287 #endif
288 free(up);
289 }
290
291
292 /*
293 * shm_timer - called every second
294 */
295 static void
296 shm_timer(int unit, struct peer *peer)
297 {
298 shm_peek(unit, peer);
299 }
300
301
302 /*
303 * shm_poll - called by the transmit procedure
304 */
305 static void
306 shm_poll(
307 int unit,
308 struct peer *peer
309 )
310 {
311 struct refclockproc *pp;
312 struct shmunit *up;
313 int major_error;
314
315 pp = peer->procptr;
316 up = pp->unitptr;
317
318 pp->polls++;
319
320 /* get dominant reason if we have no samples at all */
321 major_error = max(up->notready, up->bad);
322 major_error = max(major_error, up->clash);
323
324 /*
325 * Process median filter samples. If none received, see what
326 * happened, tell the core and keep going.
327 */
328 if (pp->coderecv != pp->codeproc) {
329 /* have some samples, everything OK */
330 pp->lastref = pp->lastrec;
331 refclock_receive(peer);
332 } else if (NULL == up->shm) { /* is this possible at all? */
333 /* we're out of business without SHM access */
334 refclock_report(peer, CEVNT_FAULT);
335 } else if (major_error == up->clash) {
336 /* too many collisions is like a bad signal */
337 refclock_report(peer, CEVNT_PROP);
338 } else if (major_error == up->bad) {
339 /* too much stale/bad/garbled data */
340 refclock_report(peer, CEVNT_BADREPLY);
341 } else {
342 /* in any other case assume it's just a timeout */
343 refclock_report(peer, CEVNT_TIMEOUT);
344 }
345 /* shm_clockstats() clears the tallies, so it must be last... */
346 shm_clockstats(unit, peer);
347 }
348
349 /*
350 * shm_peek - try to grab a sample
351 */
352 static void
353 shm_peek(
354 int unit,
355 struct peer *peer
356 )
357 {
358 struct refclockproc *pp;
359 struct shmunit *up;
360
361 /* access order is important for lock-free SHM access; we
362 ** enforce order by treating the whole structure volatile.
363 **
364 ** IMPORTANT NOTE: This does not protect from reordering on CPU
365 ** level, and it does nothing for cache consistency and
366 ** visibility of changes by other cores. We need atomic and/or
367 ** fence instructions for that.
368 */
369 volatile struct shmTime *shm;
370
371 struct timespec tvr;
372 struct timespec tvt;
373 l_fp tsrcv;
374 l_fp tsref;
375 unsigned int c;
376 unsigned int cns_new, rns_new;
377 int cnt;
378
379 /* for formatting 'a_lastcode': */
380 struct calendar cd;
381 time_t tt, now;
382 vint64 ts;
383
384 /*
385 * This is the main routine. It snatches the time from the shm
386 * board and tacks on a local timestamp.
387 */
388 pp = peer->procptr;
389 up = pp->unitptr;
390 up->ticks++;
391 if (up->shm == 0) {
392 /* try to map again - this may succeed if meanwhile some-
393 body has ipcrm'ed the old (unaccessible) shared mem segment */
394 up->shm = getShmTime(unit);
395 }
396 shm = up->shm;
397 if (shm == 0) {
398 DPRINTF(1, ("%s: no SHM segment\n",
399 refnumtoa(&peer->srcadr)));
400 return;
401 }
402 if ( ! shm->valid) {
403 DPRINTF(1, ("%s: SHM not ready\n",
404 refnumtoa(&peer->srcadr)));
405 up->notready++;
406 return;
407 }
408
409 switch (shm->mode) {
410 case 0:
411 tvr.tv_sec = shm->receiveTimeStampSec;
412 tvr.tv_nsec = shm->receiveTimeStampUSec * 1000;
413 rns_new = shm->receiveTimeStampNSec;
414 tvt.tv_sec = shm->clockTimeStampSec;
415 tvt.tv_nsec = shm->clockTimeStampUSec * 1000;
416 cns_new = shm->clockTimeStampNSec;
417
418 /* Since the following comparisons are between unsigned
419 ** variables they are always well defined, and any
420 ** (signed) underflow will turn into very large unsigned
421 ** values, well above the 1000 cutoff.
422 **
423 ** Note: The usecs *must* be a *truncated*
424 ** representation of the nsecs. This code will fail for
425 ** *rounded* usecs, and the logic to deal with
426 ** wrap-arounds in the presence of rounded values is
427 ** much more convoluted.
428 */
429 if ( ((cns_new - (unsigned)tvt.tv_nsec) < 1000)
430 && ((rns_new - (unsigned)tvr.tv_nsec) < 1000)) {
431 tvt.tv_nsec = cns_new;
432 tvr.tv_nsec = rns_new;
433 }
434 /* At this point tvr and tvt contains valid ns-level
435 ** timestamps, possibly generated by extending the old
436 ** us-level timestamps
437 */
438 DPRINTF(2, ("%s: SHM type 0 sample\n",
439 refnumtoa(&peer->srcadr)));
440 break;
441
442 case 1:
443 cnt = shm->count;
444
445 tvr.tv_sec = shm->receiveTimeStampSec;
446 tvr.tv_nsec = shm->receiveTimeStampUSec * 1000;
447 rns_new = shm->receiveTimeStampNSec;
448 tvt.tv_sec = shm->clockTimeStampSec;
449 tvt.tv_nsec = shm->clockTimeStampUSec * 1000;
450 cns_new = shm->clockTimeStampNSec;
451 if (cnt != shm->count) {
452 DPRINTF(1, ("%s: type 1 access clash\n",
453 refnumtoa(&peer->srcadr)));
454 msyslog (LOG_NOTICE, "SHM: access clash in shared memory");
455 up->clash++;
456 return;
457 }
458
459 /* See the case above for an explanation of the
460 ** following test.
461 */
462 if ( ((cns_new - (unsigned)tvt.tv_nsec) < 1000)
463 && ((rns_new - (unsigned)tvr.tv_nsec) < 1000)) {
464 tvt.tv_nsec = cns_new;
465 tvr.tv_nsec = rns_new;
466 }
467 /* At this point tvr and tvt contains valid ns-level
468 ** timestamps, possibly generated by extending the old
469 ** us-level timestamps
470 */
471 DPRINTF(2, ("%s: SHM type 1 sample\n",
472 refnumtoa(&peer->srcadr)));
473 break;
474
475 default:
476 DPRINTF(1, ("%s: SHM type blooper, mode=%d\n",
477 refnumtoa(&peer->srcadr), shm->mode));
478 up->bad++;
479 msyslog (LOG_ERR, "SHM: bad mode found in shared memory: %d",
480 shm->mode);
481 return;
482 }
483 shm->valid = 0;
484
485 /* format the last time code in human-readable form into
486 * 'pp->a_lastcode'. Someone claimed: "NetBSD has incompatible
487 * tv_sec". I can't find a base for this claim, but we can work
488 * around that potential problem. BTW, simply casting a pointer
489 * is a receipe for disaster on some architectures.
490 */
491 tt = (time_t)tvt.tv_sec;
492 ts = time_to_vint64(&tt);
493 ntpcal_time_to_date(&cd, &ts);
494
495 /* add ntpq -c cv timecode in ISO 8601 format */
496 c = snprintf(pp->a_lastcode, sizeof(pp->a_lastcode),
497 "%04u-%02u-%02uT%02u:%02u:%02u.%09ldZ",
498 cd.year, cd.month, cd.monthday,
499 cd.hour, cd.minute, cd.second,
500 (long)tvt.tv_nsec);
501 pp->lencode = (c < sizeof(pp->a_lastcode)) ? c : 0;
502
503 /* check 1: age control of local time stamp */
504 time(&now);
505 tt = now - tvr.tv_sec;
506 if (tt < 0 || tt > up->max_delay) {
507 DPRINTF(1, ("%s:SHM stale/bad receive time, delay=%llds\n",
508 refnumtoa(&peer->srcadr), (long long)tt));
509 up->bad++;
510 msyslog (LOG_ERR, "SHM: stale/bad receive time, delay=%llds",
511 (long long)tt);
512 return;
513 }
514
515 /* check 2: delta check */
516 tt = tvr.tv_sec - tvt.tv_sec - (tvr.tv_nsec < tvt.tv_nsec);
517 if (tt < 0)
518 tt = -tt;
519 if (up->max_delta > 0 && tt > up->max_delta) {
520 DPRINTF(1, ("%s: SHM diff limit exceeded, delta=%llds\n",
521 refnumtoa(&peer->srcadr), (long long)tt));
522 up->bad++;
523 msyslog (LOG_ERR, "SHM: difference limit exceeded, delta=%llds\n",
524 (long long)tt);
525 return;
526 }
527
528 /* if we really made it to this point... we're winners! */
529 DPRINTF(2, ("%s: SHM feeding data\n",
530 refnumtoa(&peer->srcadr)));
531 tsrcv = tspec_stamp_to_lfp(tvr);
532 tsref = tspec_stamp_to_lfp(tvt);
533 pp->leap = shm->leap;
534 peer->precision = shm->precision;
535 refclock_process_offset(pp, tsref, tsrcv, pp->fudgetime1);
536 up->good++;
537 }
538
539 /*
540 * shm_clockstats - dump and reset counters
541 */
542 static void shm_clockstats(
543 int unit,
544 struct peer *peer
545 )
546 {
547 struct refclockproc *pp;
548 struct shmunit *up;
549 char logbuf[64];
550 unsigned int llen;
551
552 pp = peer->procptr;
553 up = pp->unitptr;
554
555 if (pp->sloppyclockflag & CLK_FLAG4) {
556 /* if snprintf() returns a negative values on errors
557 ** (some older ones do) make sure we are NUL
558 ** terminated. Using an unsigned result does the trick.
559 */
560 llen = snprintf(logbuf, sizeof(logbuf),
561 "%3d %3d %3d %3d %3d",
562 up->ticks, up->good, up->notready,
563 up->bad, up->clash);
564 logbuf[min(llen, sizeof(logbuf)-1)] = '\0';
565 record_clock_stats(&peer->srcadr, logbuf);
566 }
567 up->ticks = up->good = up->notready = up->bad = up->clash = 0;
568
569 }
570
571 #else
572 NONEMPTY_TRANSLATION_UNIT
573 #endif /* REFCLOCK */
574