refclock_shm.c revision 1.4 1 /* $NetBSD: refclock_shm.c,v 1.4 2015/04/07 17:34:19 christos 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 #endif
201
202 return p;
203 }
204 /*
205 * shm_start - attach to shared memory
206 */
207 static int
208 shm_start(
209 int unit,
210 struct peer *peer
211 )
212 {
213 struct refclockproc * const pp = peer->procptr;
214 struct shmunit * const up = emalloc_zero(sizeof(*up));
215
216 pp->io.clock_recv = noentry;
217 pp->io.srcclock = peer;
218 pp->io.datalen = 0;
219 pp->io.fd = -1;
220
221 up->forall = (unit >= 2) && !(peer->ttl & SHM_MODE_PRIVATE);
222
223 up->shm = getShmTime(unit, up->forall);
224
225 /*
226 * Initialize miscellaneous peer variables
227 */
228 memcpy((char *)&pp->refid, REFID, 4);
229 if (up->shm != 0) {
230 pp->unitptr = up;
231 up->shm->precision = PRECISION;
232 peer->precision = up->shm->precision;
233 up->shm->valid = 0;
234 up->shm->nsamples = NSAMPLES;
235 pp->clockdesc = DESCRIPTION;
236 /* items to be changed later in 'shm_control()': */
237 up->max_delay = 5;
238 up->max_delta = 4*3600;
239 return 1;
240 } else {
241 free(up);
242 pp->unitptr = NULL;
243 return 0;
244 }
245 }
246
247
248 /*
249 * shm_control - configure flag1/time2 params
250 *
251 * These are not yet available during 'shm_start', so we have to do any
252 * pre-computations we want to avoid during regular poll/timer callbacks
253 * in this callback.
254 */
255 static void
256 shm_control(
257 int unit,
258 const struct refclockstat * in_st,
259 struct refclockstat * out_st,
260 struct peer * peer
261 )
262 {
263 struct refclockproc * const pp = peer->procptr;
264 struct shmunit * const up = pp->unitptr;
265
266 UNUSED_ARG(unit);
267 UNUSED_ARG(in_st);
268 UNUSED_ARG(out_st);
269 if (NULL == up)
270 return;
271 if (pp->sloppyclockflag & CLK_FLAG1)
272 up->max_delta = 0;
273 else if (pp->fudgetime2 < 1. || pp->fudgetime2 > 86400.)
274 up->max_delta = 4*3600;
275 else
276 up->max_delta = (time_t)floor(pp->fudgetime2 + 0.5);
277 }
278
279
280 /*
281 * shm_shutdown - shut down the clock
282 */
283 static void
284 shm_shutdown(
285 int unit,
286 struct peer *peer
287 )
288 {
289 struct refclockproc * const pp = peer->procptr;
290 struct shmunit * const up = pp->unitptr;
291
292 UNUSED_ARG(unit);
293 if (NULL == up)
294 return;
295 #ifndef SYS_WINNT
296
297 /* HMS: shmdt() wants char* or const void * */
298 (void)shmdt((char *)up->shm);
299
300 #else
301
302 UnmapViewOfFile(up->shm);
303
304 #endif
305 free(up);
306 }
307
308
309 /*
310 * shm_poll - called by the transmit procedure
311 */
312 static void
313 shm_poll(
314 int unit,
315 struct peer *peer
316 )
317 {
318 struct refclockproc * const pp = peer->procptr;
319 struct shmunit * const up = pp->unitptr;
320 int major_error;
321
322 pp->polls++;
323
324 /* get dominant reason if we have no samples at all */
325 major_error = max(up->notready, up->bad);
326 major_error = max(major_error, up->clash);
327
328 /*
329 * Process median filter samples. If none received, see what
330 * happened, tell the core and keep going.
331 */
332 if (pp->coderecv != pp->codeproc) {
333 /* have some samples, everything OK */
334 pp->lastref = pp->lastrec;
335 refclock_receive(peer);
336 } else if (NULL == up->shm) { /* is this possible at all? */
337 /* we're out of business without SHM access */
338 refclock_report(peer, CEVNT_FAULT);
339 } else if (major_error == up->clash) {
340 /* too many collisions is like a bad signal */
341 refclock_report(peer, CEVNT_PROP);
342 } else if (major_error == up->bad) {
343 /* too much stale/bad/garbled data */
344 refclock_report(peer, CEVNT_BADREPLY);
345 } else {
346 /* in any other case assume it's just a timeout */
347 refclock_report(peer, CEVNT_TIMEOUT);
348 }
349 /* shm_clockstats() clears the tallies, so it must be last... */
350 shm_clockstats(unit, peer);
351 }
352
353 /*
354 * shm_timer - called onece every second.
355 *
356 * This tries to grab a sample from the SHM segment
357 */
358 static void
359 shm_timer(
360 int unit,
361 struct peer *peer
362 )
363 {
364 struct refclockproc * const pp = peer->procptr;
365 struct shmunit * const up = pp->unitptr;
366
367 /* access order is important for lock-free SHM access; we
368 ** enforce order by treating the whole structure volatile.
369 **
370 ** IMPORTANT NOTE: This does not protect from reordering on CPU
371 ** level, and it does nothing for cache consistency and
372 ** visibility of changes by other cores. We need atomic and/or
373 ** fence instructions for that.
374 */
375 volatile struct shmTime *shm;
376
377 struct timespec tvr;
378 struct timespec tvt;
379 l_fp tsrcv;
380 l_fp tsref;
381 unsigned int c;
382 unsigned int cns_new, rns_new;
383 int cnt;
384
385 /* for formatting 'a_lastcode': */
386 struct calendar cd;
387 time_t tt, now;
388 vint64 ts;
389
390 /*
391 * This is the main routine. It snatches the time from the shm
392 * board and tacks on a local timestamp.
393 */
394 up->ticks++;
395 if ((shm = up->shm) == NULL) {
396 /* try to map again - this may succeed if meanwhile some-
397 body has ipcrm'ed the old (unaccessible) shared mem segment */
398 shm = up->shm = getShmTime(unit, up->forall);
399 if (shm == NULL) {
400 DPRINTF(1, ("%s: no SHM segment\n",
401 refnumtoa(&peer->srcadr)));
402 return;
403 }
404 }
405 if ( ! shm->valid) {
406 DPRINTF(1, ("%s: SHM not ready\n",
407 refnumtoa(&peer->srcadr)));
408 up->notready++;
409 return;
410 }
411
412 switch (shm->mode) {
413 case 0:
414 tvr.tv_sec = shm->receiveTimeStampSec;
415 tvr.tv_nsec = shm->receiveTimeStampUSec * 1000;
416 rns_new = shm->receiveTimeStampNSec;
417 tvt.tv_sec = shm->clockTimeStampSec;
418 tvt.tv_nsec = shm->clockTimeStampUSec * 1000;
419 cns_new = shm->clockTimeStampNSec;
420
421 /* Since the following comparisons are between unsigned
422 ** variables they are always well defined, and any
423 ** (signed) underflow will turn into very large unsigned
424 ** values, well above the 1000 cutoff.
425 **
426 ** Note: The usecs *must* be a *truncated*
427 ** representation of the nsecs. This code will fail for
428 ** *rounded* usecs, and the logic to deal with
429 ** wrap-arounds in the presence of rounded values is
430 ** much more convoluted.
431 */
432 if ( ((cns_new - (unsigned)tvt.tv_nsec) < 1000)
433 && ((rns_new - (unsigned)tvr.tv_nsec) < 1000)) {
434 tvt.tv_nsec = cns_new;
435 tvr.tv_nsec = rns_new;
436 }
437 /* At this point tvr and tvt contains valid ns-level
438 ** timestamps, possibly generated by extending the old
439 ** us-level timestamps
440 */
441 DPRINTF(2, ("%s: SHM type 0 sample\n",
442 refnumtoa(&peer->srcadr)));
443 break;
444
445 case 1:
446 cnt = shm->count;
447
448 tvr.tv_sec = shm->receiveTimeStampSec;
449 tvr.tv_nsec = shm->receiveTimeStampUSec * 1000;
450 rns_new = shm->receiveTimeStampNSec;
451 tvt.tv_sec = shm->clockTimeStampSec;
452 tvt.tv_nsec = shm->clockTimeStampUSec * 1000;
453 cns_new = shm->clockTimeStampNSec;
454 if (cnt != shm->count) {
455 DPRINTF(1, ("%s: type 1 access clash\n",
456 refnumtoa(&peer->srcadr)));
457 msyslog (LOG_NOTICE, "SHM: access clash in shared memory");
458 up->clash++;
459 return;
460 }
461
462 /* See the case above for an explanation of the
463 ** following test.
464 */
465 if ( ((cns_new - (unsigned)tvt.tv_nsec) < 1000)
466 && ((rns_new - (unsigned)tvr.tv_nsec) < 1000)) {
467 tvt.tv_nsec = cns_new;
468 tvr.tv_nsec = rns_new;
469 }
470 /* At this point tvr and tvt contains valid ns-level
471 ** timestamps, possibly generated by extending the old
472 ** us-level timestamps
473 */
474 DPRINTF(2, ("%s: SHM type 1 sample\n",
475 refnumtoa(&peer->srcadr)));
476 break;
477
478 default:
479 DPRINTF(1, ("%s: SHM type blooper, mode=%d\n",
480 refnumtoa(&peer->srcadr), shm->mode));
481 up->bad++;
482 msyslog (LOG_ERR, "SHM: bad mode found in shared memory: %d",
483 shm->mode);
484 return;
485 }
486 shm->valid = 0;
487
488 /* format the last time code in human-readable form into
489 * 'pp->a_lastcode'. Someone claimed: "NetBSD has incompatible
490 * tv_sec". I can't find a base for this claim, but we can work
491 * around that potential problem. BTW, simply casting a pointer
492 * is a receipe for disaster on some architectures.
493 */
494 tt = (time_t)tvt.tv_sec;
495 ts = time_to_vint64(&tt);
496 ntpcal_time_to_date(&cd, &ts);
497
498 /* add ntpq -c cv timecode in ISO 8601 format */
499 c = snprintf(pp->a_lastcode, sizeof(pp->a_lastcode),
500 "%04u-%02u-%02uT%02u:%02u:%02u.%09ldZ",
501 cd.year, cd.month, cd.monthday,
502 cd.hour, cd.minute, cd.second,
503 (long)tvt.tv_nsec);
504 pp->lencode = (c < sizeof(pp->a_lastcode)) ? c : 0;
505
506 /* check 1: age control of local time stamp */
507 time(&now);
508 tt = now - tvr.tv_sec;
509 if (tt < 0 || tt > up->max_delay) {
510 DPRINTF(1, ("%s:SHM stale/bad receive time, delay=%llds\n",
511 refnumtoa(&peer->srcadr), (long long)tt));
512 up->bad++;
513 msyslog (LOG_ERR, "SHM: stale/bad receive time, delay=%llds",
514 (long long)tt);
515 return;
516 }
517
518 /* check 2: delta check */
519 tt = tvr.tv_sec - tvt.tv_sec - (tvr.tv_nsec < tvt.tv_nsec);
520 if (tt < 0)
521 tt = -tt;
522 if (up->max_delta > 0 && tt > up->max_delta) {
523 DPRINTF(1, ("%s: SHM diff limit exceeded, delta=%llds\n",
524 refnumtoa(&peer->srcadr), (long long)tt));
525 up->bad++;
526 msyslog (LOG_ERR, "SHM: difference limit exceeded, delta=%llds\n",
527 (long long)tt);
528 return;
529 }
530
531 /* if we really made it to this point... we're winners! */
532 DPRINTF(2, ("%s: SHM feeding data\n",
533 refnumtoa(&peer->srcadr)));
534 tsrcv = tspec_stamp_to_lfp(tvr);
535 tsref = tspec_stamp_to_lfp(tvt);
536 pp->leap = shm->leap;
537 peer->precision = shm->precision;
538 refclock_process_offset(pp, tsref, tsrcv, pp->fudgetime1);
539 up->good++;
540 }
541
542 /*
543 * shm_clockstats - dump and reset counters
544 */
545 static void shm_clockstats(
546 int unit,
547 struct peer *peer
548 )
549 {
550 struct refclockproc * const pp = peer->procptr;
551 struct shmunit * const up = pp->unitptr;
552
553 UNUSED_ARG(unit);
554 if (pp->sloppyclockflag & CLK_FLAG4) {
555 mprintf_clock_stats(
556 &peer->srcadr, "%3d %3d %3d %3d %3d",
557 up->ticks, up->good, up->notready,
558 up->bad, up->clash);
559 }
560 up->ticks = up->good = up->notready = up->bad = up->clash = 0;
561 }
562
563 #else
564 NONEMPTY_TRANSLATION_UNIT
565 #endif /* REFCLOCK */
566