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