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