xref: /linux/tools/testing/selftests/ptp/testptp.c (revision 7f71507851fc7764b36a3221839607d3a45c2025)
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 #define NSEC_PER_SEC 1000000000LL
39 
40 /* clock_adjtime is not available in GLIBC < 2.14 */
41 #if !__GLIBC_PREREQ(2, 14)
42 #include <sys/syscall.h>
43 static int clock_adjtime(clockid_t id, struct timex *tx)
44 {
45 	return syscall(__NR_clock_adjtime, id, tx);
46 }
47 #endif
48 
49 static void show_flag_test(int rq_index, unsigned int flags, int err)
50 {
51 	printf("PTP_EXTTS_REQUEST%c flags 0x%08x : (%d) %s\n",
52 	       rq_index ? '1' + rq_index : ' ',
53 	       flags, err, strerror(errno));
54 	/* sigh, uClibc ... */
55 	errno = 0;
56 }
57 
58 static void do_flag_test(int fd, unsigned int index)
59 {
60 	struct ptp_extts_request extts_request;
61 	unsigned long request[2] = {
62 		PTP_EXTTS_REQUEST,
63 		PTP_EXTTS_REQUEST2,
64 	};
65 	unsigned int enable_flags[5] = {
66 		PTP_ENABLE_FEATURE,
67 		PTP_ENABLE_FEATURE | PTP_RISING_EDGE,
68 		PTP_ENABLE_FEATURE | PTP_FALLING_EDGE,
69 		PTP_ENABLE_FEATURE | PTP_RISING_EDGE | PTP_FALLING_EDGE,
70 		PTP_ENABLE_FEATURE | (PTP_EXTTS_VALID_FLAGS + 1),
71 	};
72 	int err, i, j;
73 
74 	memset(&extts_request, 0, sizeof(extts_request));
75 	extts_request.index = index;
76 
77 	for (i = 0; i < 2; i++) {
78 		for (j = 0; j < 5; j++) {
79 			extts_request.flags = enable_flags[j];
80 			err = ioctl(fd, request[i], &extts_request);
81 			show_flag_test(i, extts_request.flags, err);
82 
83 			extts_request.flags = 0;
84 			err = ioctl(fd, request[i], &extts_request);
85 		}
86 	}
87 }
88 
89 static clockid_t get_clockid(int fd)
90 {
91 #define CLOCKFD 3
92 	return (((unsigned int) ~fd) << 3) | CLOCKFD;
93 }
94 
95 static long ppb_to_scaled_ppm(int ppb)
96 {
97 	/*
98 	 * The 'freq' field in the 'struct timex' is in parts per
99 	 * million, but with a 16 bit binary fractional field.
100 	 * Instead of calculating either one of
101 	 *
102 	 *    scaled_ppm = (ppb / 1000) << 16  [1]
103 	 *    scaled_ppm = (ppb << 16) / 1000  [2]
104 	 *
105 	 * we simply use double precision math, in order to avoid the
106 	 * truncation in [1] and the possible overflow in [2].
107 	 */
108 	return (long) (ppb * 65.536);
109 }
110 
111 static int64_t pctns(struct ptp_clock_time *t)
112 {
113 	return t->sec * NSEC_PER_SEC + t->nsec;
114 }
115 
116 static void usage(char *progname)
117 {
118 	fprintf(stderr,
119 		"usage: %s [options]\n"
120 		" -c         query the ptp clock's capabilities\n"
121 		" -d name    device to open\n"
122 		" -e val     read 'val' external time stamp events\n"
123 		" -f val     adjust the ptp clock frequency by 'val' ppb\n"
124 		" -F chan    Enable single channel mask and keep device open for debugfs verification.\n"
125 		" -g         get the ptp clock time\n"
126 		" -h         prints this message\n"
127 		" -i val     index for event/trigger\n"
128 		" -k val     measure the time offset between system and phc clock\n"
129 		"            for 'val' times (Maximum 25)\n"
130 		" -l         list the current pin configuration\n"
131 		" -L pin,val configure pin index 'pin' with function 'val'\n"
132 		"            the channel index is taken from the '-i' option\n"
133 		"            'val' specifies the auxiliary function:\n"
134 		"            0 - none\n"
135 		"            1 - external time stamp\n"
136 		"            2 - periodic output\n"
137 		" -n val     shift the ptp clock time by 'val' nanoseconds\n"
138 		" -o val     phase offset (in nanoseconds) to be provided to the PHC servo\n"
139 		" -p val     enable output with a period of 'val' nanoseconds\n"
140 		" -H val     set output phase to 'val' nanoseconds (requires -p)\n"
141 		" -w val     set output pulse width to 'val' nanoseconds (requires -p)\n"
142 		" -P val     enable or disable (val=1|0) the system clock PPS\n"
143 		" -s         set the ptp clock time from the system time\n"
144 		" -S         set the system time from the ptp clock time\n"
145 		" -t val     shift the ptp clock time by 'val' seconds\n"
146 		" -T val     set the ptp clock time to 'val' seconds\n"
147 		" -x val     get an extended ptp clock time with the desired number of samples (up to %d)\n"
148 		" -X         get a ptp clock cross timestamp\n"
149 		" -y val     pre/post tstamp timebase to use {realtime|monotonic|monotonic-raw}\n"
150 		" -z         test combinations of rising/falling external time stamp flags\n",
151 		progname, PTP_MAX_SAMPLES);
152 }
153 
154 int main(int argc, char *argv[])
155 {
156 	struct ptp_clock_caps caps;
157 	struct ptp_extts_event event;
158 	struct ptp_extts_request extts_request;
159 	struct ptp_perout_request perout_request;
160 	struct ptp_pin_desc desc;
161 	struct timespec ts;
162 	struct timex tx;
163 	struct ptp_clock_time *pct;
164 	struct ptp_sys_offset *sysoff;
165 	struct ptp_sys_offset_extended *soe;
166 	struct ptp_sys_offset_precise *xts;
167 
168 	char *progname;
169 	unsigned int i;
170 	int c, cnt, fd;
171 
172 	char *device = DEVICE;
173 	clockid_t clkid;
174 	int adjfreq = 0x7fffffff;
175 	int adjtime = 0;
176 	int adjns = 0;
177 	int adjphase = 0;
178 	int capabilities = 0;
179 	int extts = 0;
180 	int flagtest = 0;
181 	int gettime = 0;
182 	int index = 0;
183 	int list_pins = 0;
184 	int pct_offset = 0;
185 	int getextended = 0;
186 	int getcross = 0;
187 	int n_samples = 0;
188 	int pin_index = -1, pin_func;
189 	int pps = -1;
190 	int seconds = 0;
191 	int settime = 0;
192 	int channel = -1;
193 	clockid_t ext_clockid = CLOCK_REALTIME;
194 
195 	int64_t t1, t2, tp;
196 	int64_t interval, offset;
197 	int64_t perout_phase = -1;
198 	int64_t pulsewidth = -1;
199 	int64_t perout = -1;
200 
201 	progname = strrchr(argv[0], '/');
202 	progname = progname ? 1+progname : argv[0];
203 	while (EOF != (c = getopt(argc, argv, "cd:e:f:F:ghH:i:k:lL:n:o:p:P:sSt:T:w:x:Xy:z"))) {
204 		switch (c) {
205 		case 'c':
206 			capabilities = 1;
207 			break;
208 		case 'd':
209 			device = optarg;
210 			break;
211 		case 'e':
212 			extts = atoi(optarg);
213 			break;
214 		case 'f':
215 			adjfreq = atoi(optarg);
216 			break;
217 		case 'F':
218 			channel = atoi(optarg);
219 			break;
220 		case 'g':
221 			gettime = 1;
222 			break;
223 		case 'H':
224 			perout_phase = atoll(optarg);
225 			break;
226 		case 'i':
227 			index = atoi(optarg);
228 			break;
229 		case 'k':
230 			pct_offset = 1;
231 			n_samples = atoi(optarg);
232 			break;
233 		case 'l':
234 			list_pins = 1;
235 			break;
236 		case 'L':
237 			cnt = sscanf(optarg, "%d,%d", &pin_index, &pin_func);
238 			if (cnt != 2) {
239 				usage(progname);
240 				return -1;
241 			}
242 			break;
243 		case 'n':
244 			adjns = atoi(optarg);
245 			break;
246 		case 'o':
247 			adjphase = atoi(optarg);
248 			break;
249 		case 'p':
250 			perout = atoll(optarg);
251 			break;
252 		case 'P':
253 			pps = atoi(optarg);
254 			break;
255 		case 's':
256 			settime = 1;
257 			break;
258 		case 'S':
259 			settime = 2;
260 			break;
261 		case 't':
262 			adjtime = atoi(optarg);
263 			break;
264 		case 'T':
265 			settime = 3;
266 			seconds = atoi(optarg);
267 			break;
268 		case 'w':
269 			pulsewidth = atoi(optarg);
270 			break;
271 		case 'x':
272 			getextended = atoi(optarg);
273 			if (getextended < 1 || getextended > PTP_MAX_SAMPLES) {
274 				fprintf(stderr,
275 					"number of extended timestamp samples must be between 1 and %d; was asked for %d\n",
276 					PTP_MAX_SAMPLES, getextended);
277 				return -1;
278 			}
279 			break;
280 		case 'X':
281 			getcross = 1;
282 			break;
283 		case 'y':
284 			if (!strcasecmp(optarg, "realtime"))
285 				ext_clockid = CLOCK_REALTIME;
286 			else if (!strcasecmp(optarg, "monotonic"))
287 				ext_clockid = CLOCK_MONOTONIC;
288 			else if (!strcasecmp(optarg, "monotonic-raw"))
289 				ext_clockid = CLOCK_MONOTONIC_RAW;
290 			else {
291 				fprintf(stderr,
292 					"type needs to be realtime, monotonic or monotonic-raw; was given %s\n",
293 					optarg);
294 				return -1;
295 			}
296 			break;
297 
298 		case 'z':
299 			flagtest = 1;
300 			break;
301 		case 'h':
302 			usage(progname);
303 			return 0;
304 		case '?':
305 		default:
306 			usage(progname);
307 			return -1;
308 		}
309 	}
310 
311 	fd = open(device, O_RDWR);
312 	if (fd < 0) {
313 		fprintf(stderr, "opening %s: %s\n", device, strerror(errno));
314 		return -1;
315 	}
316 
317 	clkid = get_clockid(fd);
318 	if (CLOCK_INVALID == clkid) {
319 		fprintf(stderr, "failed to read clock id\n");
320 		return -1;
321 	}
322 
323 	if (capabilities) {
324 		if (ioctl(fd, PTP_CLOCK_GETCAPS, &caps)) {
325 			perror("PTP_CLOCK_GETCAPS");
326 		} else {
327 			printf("capabilities:\n"
328 			       "  %d maximum frequency adjustment (ppb)\n"
329 			       "  %d programmable alarms\n"
330 			       "  %d external time stamp channels\n"
331 			       "  %d programmable periodic signals\n"
332 			       "  %d pulse per second\n"
333 			       "  %d programmable pins\n"
334 			       "  %d cross timestamping\n"
335 			       "  %d adjust_phase\n"
336 			       "  %d maximum phase adjustment (ns)\n",
337 			       caps.max_adj,
338 			       caps.n_alarm,
339 			       caps.n_ext_ts,
340 			       caps.n_per_out,
341 			       caps.pps,
342 			       caps.n_pins,
343 			       caps.cross_timestamping,
344 			       caps.adjust_phase,
345 			       caps.max_phase_adj);
346 		}
347 	}
348 
349 	if (0x7fffffff != adjfreq) {
350 		memset(&tx, 0, sizeof(tx));
351 		tx.modes = ADJ_FREQUENCY;
352 		tx.freq = ppb_to_scaled_ppm(adjfreq);
353 		if (clock_adjtime(clkid, &tx)) {
354 			perror("clock_adjtime");
355 		} else {
356 			puts("frequency adjustment okay");
357 		}
358 	}
359 
360 	if (adjtime || adjns) {
361 		memset(&tx, 0, sizeof(tx));
362 		tx.modes = ADJ_SETOFFSET | ADJ_NANO;
363 		tx.time.tv_sec = adjtime;
364 		tx.time.tv_usec = adjns;
365 		while (tx.time.tv_usec < 0) {
366 			tx.time.tv_sec  -= 1;
367 			tx.time.tv_usec += NSEC_PER_SEC;
368 		}
369 
370 		if (clock_adjtime(clkid, &tx) < 0) {
371 			perror("clock_adjtime");
372 		} else {
373 			puts("time shift okay");
374 		}
375 	}
376 
377 	if (adjphase) {
378 		memset(&tx, 0, sizeof(tx));
379 		tx.modes = ADJ_OFFSET | ADJ_NANO;
380 		tx.offset = adjphase;
381 
382 		if (clock_adjtime(clkid, &tx) < 0) {
383 			perror("clock_adjtime");
384 		} else {
385 			puts("phase adjustment okay");
386 		}
387 	}
388 
389 	if (gettime) {
390 		if (clock_gettime(clkid, &ts)) {
391 			perror("clock_gettime");
392 		} else {
393 			printf("clock time: %ld.%09ld or %s",
394 			       ts.tv_sec, ts.tv_nsec, ctime(&ts.tv_sec));
395 		}
396 	}
397 
398 	if (settime == 1) {
399 		clock_gettime(CLOCK_REALTIME, &ts);
400 		if (clock_settime(clkid, &ts)) {
401 			perror("clock_settime");
402 		} else {
403 			puts("set time okay");
404 		}
405 	}
406 
407 	if (settime == 2) {
408 		clock_gettime(clkid, &ts);
409 		if (clock_settime(CLOCK_REALTIME, &ts)) {
410 			perror("clock_settime");
411 		} else {
412 			puts("set time okay");
413 		}
414 	}
415 
416 	if (settime == 3) {
417 		ts.tv_sec = seconds;
418 		ts.tv_nsec = 0;
419 		if (clock_settime(clkid, &ts)) {
420 			perror("clock_settime");
421 		} else {
422 			puts("set time okay");
423 		}
424 	}
425 
426 	if (pin_index >= 0) {
427 		memset(&desc, 0, sizeof(desc));
428 		desc.index = pin_index;
429 		desc.func = pin_func;
430 		desc.chan = index;
431 		if (ioctl(fd, PTP_PIN_SETFUNC, &desc)) {
432 			perror("PTP_PIN_SETFUNC");
433 		} else {
434 			puts("set pin function okay");
435 		}
436 	}
437 
438 	if (extts) {
439 		memset(&extts_request, 0, sizeof(extts_request));
440 		extts_request.index = index;
441 		extts_request.flags = PTP_ENABLE_FEATURE;
442 		if (ioctl(fd, PTP_EXTTS_REQUEST, &extts_request)) {
443 			perror("PTP_EXTTS_REQUEST");
444 			extts = 0;
445 		} else {
446 			puts("external time stamp request okay");
447 		}
448 		for (; extts; extts--) {
449 			cnt = read(fd, &event, sizeof(event));
450 			if (cnt != sizeof(event)) {
451 				perror("read");
452 				break;
453 			}
454 			printf("event index %u at %lld.%09u\n", event.index,
455 			       event.t.sec, event.t.nsec);
456 			fflush(stdout);
457 		}
458 		/* Disable the feature again. */
459 		extts_request.flags = 0;
460 		if (ioctl(fd, PTP_EXTTS_REQUEST, &extts_request)) {
461 			perror("PTP_EXTTS_REQUEST");
462 		}
463 	}
464 
465 	if (flagtest) {
466 		do_flag_test(fd, index);
467 	}
468 
469 	if (list_pins) {
470 		int n_pins = 0;
471 		if (ioctl(fd, PTP_CLOCK_GETCAPS, &caps)) {
472 			perror("PTP_CLOCK_GETCAPS");
473 		} else {
474 			n_pins = caps.n_pins;
475 		}
476 		for (i = 0; i < n_pins; i++) {
477 			desc.index = i;
478 			if (ioctl(fd, PTP_PIN_GETFUNC, &desc)) {
479 				perror("PTP_PIN_GETFUNC");
480 				break;
481 			}
482 			printf("name %s index %u func %u chan %u\n",
483 			       desc.name, desc.index, desc.func, desc.chan);
484 		}
485 	}
486 
487 	if (pulsewidth >= 0 && perout < 0) {
488 		puts("-w can only be specified together with -p");
489 		return -1;
490 	}
491 
492 	if (perout_phase >= 0 && perout < 0) {
493 		puts("-H can only be specified together with -p");
494 		return -1;
495 	}
496 
497 	if (perout >= 0) {
498 		if (clock_gettime(clkid, &ts)) {
499 			perror("clock_gettime");
500 			return -1;
501 		}
502 		memset(&perout_request, 0, sizeof(perout_request));
503 		perout_request.index = index;
504 		perout_request.period.sec = perout / NSEC_PER_SEC;
505 		perout_request.period.nsec = perout % NSEC_PER_SEC;
506 		perout_request.flags = 0;
507 		if (pulsewidth >= 0) {
508 			perout_request.flags |= PTP_PEROUT_DUTY_CYCLE;
509 			perout_request.on.sec = pulsewidth / NSEC_PER_SEC;
510 			perout_request.on.nsec = pulsewidth % NSEC_PER_SEC;
511 		}
512 		if (perout_phase >= 0) {
513 			perout_request.flags |= PTP_PEROUT_PHASE;
514 			perout_request.phase.sec = perout_phase / NSEC_PER_SEC;
515 			perout_request.phase.nsec = perout_phase % NSEC_PER_SEC;
516 		} else {
517 			perout_request.start.sec = ts.tv_sec + 2;
518 			perout_request.start.nsec = 0;
519 		}
520 
521 		if (ioctl(fd, PTP_PEROUT_REQUEST2, &perout_request)) {
522 			perror("PTP_PEROUT_REQUEST");
523 		} else {
524 			puts("periodic output request okay");
525 		}
526 	}
527 
528 	if (pps != -1) {
529 		int enable = pps ? 1 : 0;
530 		if (ioctl(fd, PTP_ENABLE_PPS, enable)) {
531 			perror("PTP_ENABLE_PPS");
532 		} else {
533 			puts("pps for system time request okay");
534 		}
535 	}
536 
537 	if (pct_offset) {
538 		if (n_samples <= 0 || n_samples > 25) {
539 			puts("n_samples should be between 1 and 25");
540 			usage(progname);
541 			return -1;
542 		}
543 
544 		sysoff = calloc(1, sizeof(*sysoff));
545 		if (!sysoff) {
546 			perror("calloc");
547 			return -1;
548 		}
549 		sysoff->n_samples = n_samples;
550 
551 		if (ioctl(fd, PTP_SYS_OFFSET, sysoff))
552 			perror("PTP_SYS_OFFSET");
553 		else
554 			puts("system and phc clock time offset request okay");
555 
556 		pct = &sysoff->ts[0];
557 		for (i = 0; i < sysoff->n_samples; i++) {
558 			t1 = pctns(pct+2*i);
559 			tp = pctns(pct+2*i+1);
560 			t2 = pctns(pct+2*i+2);
561 			interval = t2 - t1;
562 			offset = (t2 + t1) / 2 - tp;
563 
564 			printf("system time: %lld.%09u\n",
565 				(pct+2*i)->sec, (pct+2*i)->nsec);
566 			printf("phc    time: %lld.%09u\n",
567 				(pct+2*i+1)->sec, (pct+2*i+1)->nsec);
568 			printf("system time: %lld.%09u\n",
569 				(pct+2*i+2)->sec, (pct+2*i+2)->nsec);
570 			printf("system/phc clock time offset is %" PRId64 " ns\n"
571 			       "system     clock time delay  is %" PRId64 " ns\n",
572 				offset, interval);
573 		}
574 
575 		free(sysoff);
576 	}
577 
578 	if (getextended) {
579 		soe = calloc(1, sizeof(*soe));
580 		if (!soe) {
581 			perror("calloc");
582 			return -1;
583 		}
584 
585 		soe->n_samples = getextended;
586 		soe->clockid = ext_clockid;
587 
588 		if (ioctl(fd, PTP_SYS_OFFSET_EXTENDED, soe)) {
589 			perror("PTP_SYS_OFFSET_EXTENDED");
590 		} else {
591 			printf("extended timestamp request returned %d samples\n",
592 			       getextended);
593 
594 			for (i = 0; i < getextended; i++) {
595 				switch (ext_clockid) {
596 				case CLOCK_REALTIME:
597 					printf("sample #%2d: real time before: %lld.%09u\n",
598 					       i, soe->ts[i][0].sec,
599 					       soe->ts[i][0].nsec);
600 					break;
601 				case CLOCK_MONOTONIC:
602 					printf("sample #%2d: monotonic time before: %lld.%09u\n",
603 					       i, soe->ts[i][0].sec,
604 					       soe->ts[i][0].nsec);
605 					break;
606 				case CLOCK_MONOTONIC_RAW:
607 					printf("sample #%2d: monotonic-raw time before: %lld.%09u\n",
608 					       i, soe->ts[i][0].sec,
609 					       soe->ts[i][0].nsec);
610 					break;
611 				default:
612 					break;
613 				}
614 				printf("            phc time: %lld.%09u\n",
615 				       soe->ts[i][1].sec, soe->ts[i][1].nsec);
616 				switch (ext_clockid) {
617 				case CLOCK_REALTIME:
618 					printf("            real time after: %lld.%09u\n",
619 					       soe->ts[i][2].sec,
620 					       soe->ts[i][2].nsec);
621 					break;
622 				case CLOCK_MONOTONIC:
623 					printf("            monotonic time after: %lld.%09u\n",
624 					       soe->ts[i][2].sec,
625 					       soe->ts[i][2].nsec);
626 					break;
627 				case CLOCK_MONOTONIC_RAW:
628 					printf("            monotonic-raw time after: %lld.%09u\n",
629 					       soe->ts[i][2].sec,
630 					       soe->ts[i][2].nsec);
631 					break;
632 				default:
633 					break;
634 				}
635 			}
636 		}
637 
638 		free(soe);
639 	}
640 
641 	if (getcross) {
642 		xts = calloc(1, sizeof(*xts));
643 		if (!xts) {
644 			perror("calloc");
645 			return -1;
646 		}
647 
648 		if (ioctl(fd, PTP_SYS_OFFSET_PRECISE, xts)) {
649 			perror("PTP_SYS_OFFSET_PRECISE");
650 		} else {
651 			puts("system and phc crosstimestamping request okay");
652 
653 			printf("device time: %lld.%09u\n",
654 			       xts->device.sec, xts->device.nsec);
655 			printf("system time: %lld.%09u\n",
656 			       xts->sys_realtime.sec, xts->sys_realtime.nsec);
657 			printf("monoraw time: %lld.%09u\n",
658 			       xts->sys_monoraw.sec, xts->sys_monoraw.nsec);
659 		}
660 
661 		free(xts);
662 	}
663 
664 	if (channel >= 0) {
665 		if (ioctl(fd, PTP_MASK_CLEAR_ALL)) {
666 			perror("PTP_MASK_CLEAR_ALL");
667 		} else if (ioctl(fd, PTP_MASK_EN_SINGLE, (unsigned int *)&channel)) {
668 			perror("PTP_MASK_EN_SINGLE");
669 		} else {
670 			printf("Channel %d exclusively enabled. Check on debugfs.\n", channel);
671 			printf("Press any key to continue\n.");
672 			getchar();
673 		}
674 	}
675 
676 	close(fd);
677 	return 0;
678 }
679