1 /*
2  * PTP 1588 clock support - User space test program
3  *
4  * Copyright (C) 2010 OMICRON electronics GmbH
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20 #define _GNU_SOURCE
21 #define __SANE_USERSPACE_TYPES__        /* For PPC64, to get LL64 types */
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <inttypes.h>
25 #include <math.h>
26 #include <signal.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/ioctl.h>
31 #include <sys/mman.h>
32 #include <sys/stat.h>
33 #include <sys/time.h>
34 #include <sys/timex.h>
35 #include <sys/types.h>
36 #include <time.h>
37 #include <unistd.h>
38 
39 #include <linux/ptp_clock.h>
40 
41 #define DEVICE "/dev/ptp0"
42 
43 #ifndef ADJ_SETOFFSET
44 #define ADJ_SETOFFSET 0x0100
45 #endif
46 
47 #ifndef CLOCK_INVALID
48 #define CLOCK_INVALID -1
49 #endif
50 
51 /* clock_adjtime is not available in GLIBC < 2.14 */
52 #if !__GLIBC_PREREQ(2, 14)
53 #include <sys/syscall.h>
54 static int clock_adjtime(clockid_t id, struct timex *tx)
55 {
56 	return syscall(__NR_clock_adjtime, id, tx);
57 }
58 #endif
59 
60 static clockid_t get_clockid(int fd)
61 {
62 #define CLOCKFD 3
63 	return (((unsigned int) ~fd) << 3) | CLOCKFD;
64 }
65 
66 static void handle_alarm(int s)
67 {
68 	printf("received signal %d\n", s);
69 }
70 
71 static int install_handler(int signum, void (*handler)(int))
72 {
73 	struct sigaction action;
74 	sigset_t mask;
75 
76 	/* Unblock the signal. */
77 	sigemptyset(&mask);
78 	sigaddset(&mask, signum);
79 	sigprocmask(SIG_UNBLOCK, &mask, NULL);
80 
81 	/* Install the signal handler. */
82 	action.sa_handler = handler;
83 	action.sa_flags = 0;
84 	sigemptyset(&action.sa_mask);
85 	sigaction(signum, &action, NULL);
86 
87 	return 0;
88 }
89 
90 static long ppb_to_scaled_ppm(int ppb)
91 {
92 	/*
93 	 * The 'freq' field in the 'struct timex' is in parts per
94 	 * million, but with a 16 bit binary fractional field.
95 	 * Instead of calculating either one of
96 	 *
97 	 *    scaled_ppm = (ppb / 1000) << 16  [1]
98 	 *    scaled_ppm = (ppb << 16) / 1000  [2]
99 	 *
100 	 * we simply use double precision math, in order to avoid the
101 	 * truncation in [1] and the possible overflow in [2].
102 	 */
103 	return (long) (ppb * 65.536);
104 }
105 
106 static int64_t pctns(struct ptp_clock_time *t)
107 {
108 	return t->sec * 1000000000LL + t->nsec;
109 }
110 
111 static void usage(char *progname)
112 {
113 	fprintf(stderr,
114 		"usage: %s [options]\n"
115 		" -a val     request a one-shot alarm after 'val' seconds\n"
116 		" -A val     request a periodic alarm every 'val' seconds\n"
117 		" -c         query the ptp clock's capabilities\n"
118 		" -d name    device to open\n"
119 		" -e val     read 'val' external time stamp events\n"
120 		" -f val     adjust the ptp clock frequency by 'val' ppb\n"
121 		" -g         get the ptp clock time\n"
122 		" -h         prints this message\n"
123 		" -i val     index for event/trigger\n"
124 		" -k val     measure the time offset between system and phc clock\n"
125 		"            for 'val' times (Maximum 25)\n"
126 		" -l         list the current pin configuration\n"
127 		" -L pin,val configure pin index 'pin' with function 'val'\n"
128 		"            the channel index is taken from the '-i' option\n"
129 		"            'val' specifies the auxiliary function:\n"
130 		"            0 - none\n"
131 		"            1 - external time stamp\n"
132 		"            2 - periodic output\n"
133 		" -p val     enable output with a period of 'val' nanoseconds\n"
134 		" -P val     enable or disable (val=1|0) the system clock PPS\n"
135 		" -s         set the ptp clock time from the system time\n"
136 		" -S         set the system time from the ptp clock time\n"
137 		" -t val     shift the ptp clock time by 'val' seconds\n"
138 		" -T val     set the ptp clock time to 'val' seconds\n",
139 		progname);
140 }
141 
142 int main(int argc, char *argv[])
143 {
144 	struct ptp_clock_caps caps;
145 	struct ptp_extts_event event;
146 	struct ptp_extts_request extts_request;
147 	struct ptp_perout_request perout_request;
148 	struct ptp_pin_desc desc;
149 	struct timespec ts;
150 	struct timex tx;
151 
152 	static timer_t timerid;
153 	struct itimerspec timeout;
154 	struct sigevent sigevent;
155 
156 	struct ptp_clock_time *pct;
157 	struct ptp_sys_offset *sysoff;
158 
159 
160 	char *progname;
161 	unsigned int i;
162 	int c, cnt, fd;
163 
164 	char *device = DEVICE;
165 	clockid_t clkid;
166 	int adjfreq = 0x7fffffff;
167 	int adjtime = 0;
168 	int capabilities = 0;
169 	int extts = 0;
170 	int gettime = 0;
171 	int index = 0;
172 	int list_pins = 0;
173 	int oneshot = 0;
174 	int pct_offset = 0;
175 	int n_samples = 0;
176 	int periodic = 0;
177 	int perout = -1;
178 	int pin_index = -1, pin_func;
179 	int pps = -1;
180 	int seconds = 0;
181 	int settime = 0;
182 
183 	int64_t t1, t2, tp;
184 	int64_t interval, offset;
185 
186 	progname = strrchr(argv[0], '/');
187 	progname = progname ? 1+progname : argv[0];
188 	while (EOF != (c = getopt(argc, argv, "a:A:cd:e:f:ghi:k:lL:p:P:sSt:T:v"))) {
189 		switch (c) {
190 		case 'a':
191 			oneshot = atoi(optarg);
192 			break;
193 		case 'A':
194 			periodic = atoi(optarg);
195 			break;
196 		case 'c':
197 			capabilities = 1;
198 			break;
199 		case 'd':
200 			device = optarg;
201 			break;
202 		case 'e':
203 			extts = atoi(optarg);
204 			break;
205 		case 'f':
206 			adjfreq = atoi(optarg);
207 			break;
208 		case 'g':
209 			gettime = 1;
210 			break;
211 		case 'i':
212 			index = atoi(optarg);
213 			break;
214 		case 'k':
215 			pct_offset = 1;
216 			n_samples = atoi(optarg);
217 			break;
218 		case 'l':
219 			list_pins = 1;
220 			break;
221 		case 'L':
222 			cnt = sscanf(optarg, "%d,%d", &pin_index, &pin_func);
223 			if (cnt != 2) {
224 				usage(progname);
225 				return -1;
226 			}
227 			break;
228 		case 'p':
229 			perout = atoi(optarg);
230 			break;
231 		case 'P':
232 			pps = atoi(optarg);
233 			break;
234 		case 's':
235 			settime = 1;
236 			break;
237 		case 'S':
238 			settime = 2;
239 			break;
240 		case 't':
241 			adjtime = atoi(optarg);
242 			break;
243 		case 'T':
244 			settime = 3;
245 			seconds = atoi(optarg);
246 			break;
247 		case 'h':
248 			usage(progname);
249 			return 0;
250 		case '?':
251 		default:
252 			usage(progname);
253 			return -1;
254 		}
255 	}
256 
257 	fd = open(device, O_RDWR);
258 	if (fd < 0) {
259 		fprintf(stderr, "opening %s: %s\n", device, strerror(errno));
260 		return -1;
261 	}
262 
263 	clkid = get_clockid(fd);
264 	if (CLOCK_INVALID == clkid) {
265 		fprintf(stderr, "failed to read clock id\n");
266 		return -1;
267 	}
268 
269 	if (capabilities) {
270 		if (ioctl(fd, PTP_CLOCK_GETCAPS, &caps)) {
271 			perror("PTP_CLOCK_GETCAPS");
272 		} else {
273 			printf("capabilities:\n"
274 			       "  %d maximum frequency adjustment (ppb)\n"
275 			       "  %d programmable alarms\n"
276 			       "  %d external time stamp channels\n"
277 			       "  %d programmable periodic signals\n"
278 			       "  %d pulse per second\n"
279 			       "  %d programmable pins\n"
280 			       "  %d cross timestamping\n",
281 			       caps.max_adj,
282 			       caps.n_alarm,
283 			       caps.n_ext_ts,
284 			       caps.n_per_out,
285 			       caps.pps,
286 			       caps.n_pins,
287 			       caps.cross_timestamping);
288 		}
289 	}
290 
291 	if (0x7fffffff != adjfreq) {
292 		memset(&tx, 0, sizeof(tx));
293 		tx.modes = ADJ_FREQUENCY;
294 		tx.freq = ppb_to_scaled_ppm(adjfreq);
295 		if (clock_adjtime(clkid, &tx)) {
296 			perror("clock_adjtime");
297 		} else {
298 			puts("frequency adjustment okay");
299 		}
300 	}
301 
302 	if (adjtime) {
303 		memset(&tx, 0, sizeof(tx));
304 		tx.modes = ADJ_SETOFFSET;
305 		tx.time.tv_sec = adjtime;
306 		tx.time.tv_usec = 0;
307 		if (clock_adjtime(clkid, &tx) < 0) {
308 			perror("clock_adjtime");
309 		} else {
310 			puts("time shift okay");
311 		}
312 	}
313 
314 	if (gettime) {
315 		if (clock_gettime(clkid, &ts)) {
316 			perror("clock_gettime");
317 		} else {
318 			printf("clock time: %ld.%09ld or %s",
319 			       ts.tv_sec, ts.tv_nsec, ctime(&ts.tv_sec));
320 		}
321 	}
322 
323 	if (settime == 1) {
324 		clock_gettime(CLOCK_REALTIME, &ts);
325 		if (clock_settime(clkid, &ts)) {
326 			perror("clock_settime");
327 		} else {
328 			puts("set time okay");
329 		}
330 	}
331 
332 	if (settime == 2) {
333 		clock_gettime(clkid, &ts);
334 		if (clock_settime(CLOCK_REALTIME, &ts)) {
335 			perror("clock_settime");
336 		} else {
337 			puts("set time okay");
338 		}
339 	}
340 
341 	if (settime == 3) {
342 		ts.tv_sec = seconds;
343 		ts.tv_nsec = 0;
344 		if (clock_settime(clkid, &ts)) {
345 			perror("clock_settime");
346 		} else {
347 			puts("set time okay");
348 		}
349 	}
350 
351 	if (extts) {
352 		memset(&extts_request, 0, sizeof(extts_request));
353 		extts_request.index = index;
354 		extts_request.flags = PTP_ENABLE_FEATURE;
355 		if (ioctl(fd, PTP_EXTTS_REQUEST, &extts_request)) {
356 			perror("PTP_EXTTS_REQUEST");
357 			extts = 0;
358 		} else {
359 			puts("external time stamp request okay");
360 		}
361 		for (; extts; extts--) {
362 			cnt = read(fd, &event, sizeof(event));
363 			if (cnt != sizeof(event)) {
364 				perror("read");
365 				break;
366 			}
367 			printf("event index %u at %lld.%09u\n", event.index,
368 			       event.t.sec, event.t.nsec);
369 			fflush(stdout);
370 		}
371 		/* Disable the feature again. */
372 		extts_request.flags = 0;
373 		if (ioctl(fd, PTP_EXTTS_REQUEST, &extts_request)) {
374 			perror("PTP_EXTTS_REQUEST");
375 		}
376 	}
377 
378 	if (list_pins) {
379 		int n_pins = 0;
380 		if (ioctl(fd, PTP_CLOCK_GETCAPS, &caps)) {
381 			perror("PTP_CLOCK_GETCAPS");
382 		} else {
383 			n_pins = caps.n_pins;
384 		}
385 		for (i = 0; i < n_pins; i++) {
386 			desc.index = i;
387 			if (ioctl(fd, PTP_PIN_GETFUNC, &desc)) {
388 				perror("PTP_PIN_GETFUNC");
389 				break;
390 			}
391 			printf("name %s index %u func %u chan %u\n",
392 			       desc.name, desc.index, desc.func, desc.chan);
393 		}
394 	}
395 
396 	if (oneshot) {
397 		install_handler(SIGALRM, handle_alarm);
398 		/* Create a timer. */
399 		sigevent.sigev_notify = SIGEV_SIGNAL;
400 		sigevent.sigev_signo = SIGALRM;
401 		if (timer_create(clkid, &sigevent, &timerid)) {
402 			perror("timer_create");
403 			return -1;
404 		}
405 		/* Start the timer. */
406 		memset(&timeout, 0, sizeof(timeout));
407 		timeout.it_value.tv_sec = oneshot;
408 		if (timer_settime(timerid, 0, &timeout, NULL)) {
409 			perror("timer_settime");
410 			return -1;
411 		}
412 		pause();
413 		timer_delete(timerid);
414 	}
415 
416 	if (periodic) {
417 		install_handler(SIGALRM, handle_alarm);
418 		/* Create a timer. */
419 		sigevent.sigev_notify = SIGEV_SIGNAL;
420 		sigevent.sigev_signo = SIGALRM;
421 		if (timer_create(clkid, &sigevent, &timerid)) {
422 			perror("timer_create");
423 			return -1;
424 		}
425 		/* Start the timer. */
426 		memset(&timeout, 0, sizeof(timeout));
427 		timeout.it_interval.tv_sec = periodic;
428 		timeout.it_value.tv_sec = periodic;
429 		if (timer_settime(timerid, 0, &timeout, NULL)) {
430 			perror("timer_settime");
431 			return -1;
432 		}
433 		while (1) {
434 			pause();
435 		}
436 		timer_delete(timerid);
437 	}
438 
439 	if (perout >= 0) {
440 		if (clock_gettime(clkid, &ts)) {
441 			perror("clock_gettime");
442 			return -1;
443 		}
444 		memset(&perout_request, 0, sizeof(perout_request));
445 		perout_request.index = index;
446 		perout_request.start.sec = ts.tv_sec + 2;
447 		perout_request.start.nsec = 0;
448 		perout_request.period.sec = 0;
449 		perout_request.period.nsec = perout;
450 		if (ioctl(fd, PTP_PEROUT_REQUEST, &perout_request)) {
451 			perror("PTP_PEROUT_REQUEST");
452 		} else {
453 			puts("periodic output request okay");
454 		}
455 	}
456 
457 	if (pin_index >= 0) {
458 		memset(&desc, 0, sizeof(desc));
459 		desc.index = pin_index;
460 		desc.func = pin_func;
461 		desc.chan = index;
462 		if (ioctl(fd, PTP_PIN_SETFUNC, &desc)) {
463 			perror("PTP_PIN_SETFUNC");
464 		} else {
465 			puts("set pin function okay");
466 		}
467 	}
468 
469 	if (pps != -1) {
470 		int enable = pps ? 1 : 0;
471 		if (ioctl(fd, PTP_ENABLE_PPS, enable)) {
472 			perror("PTP_ENABLE_PPS");
473 		} else {
474 			puts("pps for system time request okay");
475 		}
476 	}
477 
478 	if (pct_offset) {
479 		if (n_samples <= 0 || n_samples > 25) {
480 			puts("n_samples should be between 1 and 25");
481 			usage(progname);
482 			return -1;
483 		}
484 
485 		sysoff = calloc(1, sizeof(*sysoff));
486 		if (!sysoff) {
487 			perror("calloc");
488 			return -1;
489 		}
490 		sysoff->n_samples = n_samples;
491 
492 		if (ioctl(fd, PTP_SYS_OFFSET, sysoff))
493 			perror("PTP_SYS_OFFSET");
494 		else
495 			puts("system and phc clock time offset request okay");
496 
497 		pct = &sysoff->ts[0];
498 		for (i = 0; i < sysoff->n_samples; i++) {
499 			t1 = pctns(pct+2*i);
500 			tp = pctns(pct+2*i+1);
501 			t2 = pctns(pct+2*i+2);
502 			interval = t2 - t1;
503 			offset = (t2 + t1) / 2 - tp;
504 
505 			printf("system time: %lld.%u\n",
506 				(pct+2*i)->sec, (pct+2*i)->nsec);
507 			printf("phc    time: %lld.%u\n",
508 				(pct+2*i+1)->sec, (pct+2*i+1)->nsec);
509 			printf("system time: %lld.%u\n",
510 				(pct+2*i+2)->sec, (pct+2*i+2)->nsec);
511 			printf("system/phc clock time offset is %" PRId64 " ns\n"
512 			       "system     clock time delay  is %" PRId64 " ns\n",
513 				offset, interval);
514 		}
515 
516 		free(sysoff);
517 	}
518 
519 	close(fd);
520 	return 0;
521 }
522