xref: /linux/tools/testing/selftests/ptp/testptp.c (revision 64b14a184e83eb62ea0615e31a409956049d40e7)
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 * 1000000000LL + 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 		" -g         get the ptp clock time\n"
125 		" -h         prints this message\n"
126 		" -i val     index for event/trigger\n"
127 		" -k val     measure the time offset between system and phc clock\n"
128 		"            for 'val' times (Maximum 25)\n"
129 		" -l         list the current pin configuration\n"
130 		" -L pin,val configure pin index 'pin' with function 'val'\n"
131 		"            the channel index is taken from the '-i' option\n"
132 		"            'val' specifies the auxiliary function:\n"
133 		"            0 - none\n"
134 		"            1 - external time stamp\n"
135 		"            2 - periodic output\n"
136 		" -p val     enable output with a period of 'val' nanoseconds\n"
137 		" -H val     set output phase to 'val' nanoseconds (requires -p)\n"
138 		" -w val     set output pulse width to 'val' nanoseconds (requires -p)\n"
139 		" -P val     enable or disable (val=1|0) the system clock PPS\n"
140 		" -s         set the ptp clock time from the system time\n"
141 		" -S         set the system time from the ptp clock time\n"
142 		" -t val     shift the ptp clock time by 'val' seconds\n"
143 		" -T val     set the ptp clock time to 'val' seconds\n"
144 		" -z         test combinations of rising/falling external time stamp flags\n",
145 		progname);
146 }
147 
148 int main(int argc, char *argv[])
149 {
150 	struct ptp_clock_caps caps;
151 	struct ptp_extts_event event;
152 	struct ptp_extts_request extts_request;
153 	struct ptp_perout_request perout_request;
154 	struct ptp_pin_desc desc;
155 	struct timespec ts;
156 	struct timex tx;
157 	struct ptp_clock_time *pct;
158 	struct ptp_sys_offset *sysoff;
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 flagtest = 0;
171 	int gettime = 0;
172 	int index = 0;
173 	int list_pins = 0;
174 	int pct_offset = 0;
175 	int n_samples = 0;
176 	int pin_index = -1, pin_func;
177 	int pps = -1;
178 	int seconds = 0;
179 	int settime = 0;
180 
181 	int64_t t1, t2, tp;
182 	int64_t interval, offset;
183 	int64_t perout_phase = -1;
184 	int64_t pulsewidth = -1;
185 	int64_t perout = -1;
186 
187 	progname = strrchr(argv[0], '/');
188 	progname = progname ? 1+progname : argv[0];
189 	while (EOF != (c = getopt(argc, argv, "cd:e:f:ghH:i:k:lL:p:P:sSt:T:w:z"))) {
190 		switch (c) {
191 		case 'c':
192 			capabilities = 1;
193 			break;
194 		case 'd':
195 			device = optarg;
196 			break;
197 		case 'e':
198 			extts = atoi(optarg);
199 			break;
200 		case 'f':
201 			adjfreq = atoi(optarg);
202 			break;
203 		case 'g':
204 			gettime = 1;
205 			break;
206 		case 'H':
207 			perout_phase = atoll(optarg);
208 			break;
209 		case 'i':
210 			index = atoi(optarg);
211 			break;
212 		case 'k':
213 			pct_offset = 1;
214 			n_samples = atoi(optarg);
215 			break;
216 		case 'l':
217 			list_pins = 1;
218 			break;
219 		case 'L':
220 			cnt = sscanf(optarg, "%d,%d", &pin_index, &pin_func);
221 			if (cnt != 2) {
222 				usage(progname);
223 				return -1;
224 			}
225 			break;
226 		case 'p':
227 			perout = atoll(optarg);
228 			break;
229 		case 'P':
230 			pps = atoi(optarg);
231 			break;
232 		case 's':
233 			settime = 1;
234 			break;
235 		case 'S':
236 			settime = 2;
237 			break;
238 		case 't':
239 			adjtime = atoi(optarg);
240 			break;
241 		case 'T':
242 			settime = 3;
243 			seconds = atoi(optarg);
244 			break;
245 		case 'w':
246 			pulsewidth = atoi(optarg);
247 			break;
248 		case 'z':
249 			flagtest = 1;
250 			break;
251 		case 'h':
252 			usage(progname);
253 			return 0;
254 		case '?':
255 		default:
256 			usage(progname);
257 			return -1;
258 		}
259 	}
260 
261 	fd = open(device, O_RDWR);
262 	if (fd < 0) {
263 		fprintf(stderr, "opening %s: %s\n", device, strerror(errno));
264 		return -1;
265 	}
266 
267 	clkid = get_clockid(fd);
268 	if (CLOCK_INVALID == clkid) {
269 		fprintf(stderr, "failed to read clock id\n");
270 		return -1;
271 	}
272 
273 	if (capabilities) {
274 		if (ioctl(fd, PTP_CLOCK_GETCAPS, &caps)) {
275 			perror("PTP_CLOCK_GETCAPS");
276 		} else {
277 			printf("capabilities:\n"
278 			       "  %d maximum frequency adjustment (ppb)\n"
279 			       "  %d programmable alarms\n"
280 			       "  %d external time stamp channels\n"
281 			       "  %d programmable periodic signals\n"
282 			       "  %d pulse per second\n"
283 			       "  %d programmable pins\n"
284 			       "  %d cross timestamping\n"
285 			       "  %d adjust_phase\n",
286 			       caps.max_adj,
287 			       caps.n_alarm,
288 			       caps.n_ext_ts,
289 			       caps.n_per_out,
290 			       caps.pps,
291 			       caps.n_pins,
292 			       caps.cross_timestamping,
293 			       caps.adjust_phase);
294 		}
295 	}
296 
297 	if (0x7fffffff != adjfreq) {
298 		memset(&tx, 0, sizeof(tx));
299 		tx.modes = ADJ_FREQUENCY;
300 		tx.freq = ppb_to_scaled_ppm(adjfreq);
301 		if (clock_adjtime(clkid, &tx)) {
302 			perror("clock_adjtime");
303 		} else {
304 			puts("frequency adjustment okay");
305 		}
306 	}
307 
308 	if (adjtime) {
309 		memset(&tx, 0, sizeof(tx));
310 		tx.modes = ADJ_SETOFFSET;
311 		tx.time.tv_sec = adjtime;
312 		tx.time.tv_usec = 0;
313 		if (clock_adjtime(clkid, &tx) < 0) {
314 			perror("clock_adjtime");
315 		} else {
316 			puts("time shift okay");
317 		}
318 	}
319 
320 	if (gettime) {
321 		if (clock_gettime(clkid, &ts)) {
322 			perror("clock_gettime");
323 		} else {
324 			printf("clock time: %ld.%09ld or %s",
325 			       ts.tv_sec, ts.tv_nsec, ctime(&ts.tv_sec));
326 		}
327 	}
328 
329 	if (settime == 1) {
330 		clock_gettime(CLOCK_REALTIME, &ts);
331 		if (clock_settime(clkid, &ts)) {
332 			perror("clock_settime");
333 		} else {
334 			puts("set time okay");
335 		}
336 	}
337 
338 	if (settime == 2) {
339 		clock_gettime(clkid, &ts);
340 		if (clock_settime(CLOCK_REALTIME, &ts)) {
341 			perror("clock_settime");
342 		} else {
343 			puts("set time okay");
344 		}
345 	}
346 
347 	if (settime == 3) {
348 		ts.tv_sec = seconds;
349 		ts.tv_nsec = 0;
350 		if (clock_settime(clkid, &ts)) {
351 			perror("clock_settime");
352 		} else {
353 			puts("set time okay");
354 		}
355 	}
356 
357 	if (pin_index >= 0) {
358 		memset(&desc, 0, sizeof(desc));
359 		desc.index = pin_index;
360 		desc.func = pin_func;
361 		desc.chan = index;
362 		if (ioctl(fd, PTP_PIN_SETFUNC, &desc)) {
363 			perror("PTP_PIN_SETFUNC");
364 		} else {
365 			puts("set pin function okay");
366 		}
367 	}
368 
369 	if (extts) {
370 		memset(&extts_request, 0, sizeof(extts_request));
371 		extts_request.index = index;
372 		extts_request.flags = PTP_ENABLE_FEATURE;
373 		if (ioctl(fd, PTP_EXTTS_REQUEST, &extts_request)) {
374 			perror("PTP_EXTTS_REQUEST");
375 			extts = 0;
376 		} else {
377 			puts("external time stamp request okay");
378 		}
379 		for (; extts; extts--) {
380 			cnt = read(fd, &event, sizeof(event));
381 			if (cnt != sizeof(event)) {
382 				perror("read");
383 				break;
384 			}
385 			printf("event index %u at %lld.%09u\n", event.index,
386 			       event.t.sec, event.t.nsec);
387 			fflush(stdout);
388 		}
389 		/* Disable the feature again. */
390 		extts_request.flags = 0;
391 		if (ioctl(fd, PTP_EXTTS_REQUEST, &extts_request)) {
392 			perror("PTP_EXTTS_REQUEST");
393 		}
394 	}
395 
396 	if (flagtest) {
397 		do_flag_test(fd, index);
398 	}
399 
400 	if (list_pins) {
401 		int n_pins = 0;
402 		if (ioctl(fd, PTP_CLOCK_GETCAPS, &caps)) {
403 			perror("PTP_CLOCK_GETCAPS");
404 		} else {
405 			n_pins = caps.n_pins;
406 		}
407 		for (i = 0; i < n_pins; i++) {
408 			desc.index = i;
409 			if (ioctl(fd, PTP_PIN_GETFUNC, &desc)) {
410 				perror("PTP_PIN_GETFUNC");
411 				break;
412 			}
413 			printf("name %s index %u func %u chan %u\n",
414 			       desc.name, desc.index, desc.func, desc.chan);
415 		}
416 	}
417 
418 	if (pulsewidth >= 0 && perout < 0) {
419 		puts("-w can only be specified together with -p");
420 		return -1;
421 	}
422 
423 	if (perout_phase >= 0 && perout < 0) {
424 		puts("-H can only be specified together with -p");
425 		return -1;
426 	}
427 
428 	if (perout >= 0) {
429 		if (clock_gettime(clkid, &ts)) {
430 			perror("clock_gettime");
431 			return -1;
432 		}
433 		memset(&perout_request, 0, sizeof(perout_request));
434 		perout_request.index = index;
435 		perout_request.period.sec = perout / NSEC_PER_SEC;
436 		perout_request.period.nsec = perout % NSEC_PER_SEC;
437 		perout_request.flags = 0;
438 		if (pulsewidth >= 0) {
439 			perout_request.flags |= PTP_PEROUT_DUTY_CYCLE;
440 			perout_request.on.sec = pulsewidth / NSEC_PER_SEC;
441 			perout_request.on.nsec = pulsewidth % NSEC_PER_SEC;
442 		}
443 		if (perout_phase >= 0) {
444 			perout_request.flags |= PTP_PEROUT_PHASE;
445 			perout_request.phase.sec = perout_phase / NSEC_PER_SEC;
446 			perout_request.phase.nsec = perout_phase % NSEC_PER_SEC;
447 		} else {
448 			perout_request.start.sec = ts.tv_sec + 2;
449 			perout_request.start.nsec = 0;
450 		}
451 
452 		if (ioctl(fd, PTP_PEROUT_REQUEST2, &perout_request)) {
453 			perror("PTP_PEROUT_REQUEST");
454 		} else {
455 			puts("periodic output request okay");
456 		}
457 	}
458 
459 	if (pps != -1) {
460 		int enable = pps ? 1 : 0;
461 		if (ioctl(fd, PTP_ENABLE_PPS, enable)) {
462 			perror("PTP_ENABLE_PPS");
463 		} else {
464 			puts("pps for system time request okay");
465 		}
466 	}
467 
468 	if (pct_offset) {
469 		if (n_samples <= 0 || n_samples > 25) {
470 			puts("n_samples should be between 1 and 25");
471 			usage(progname);
472 			return -1;
473 		}
474 
475 		sysoff = calloc(1, sizeof(*sysoff));
476 		if (!sysoff) {
477 			perror("calloc");
478 			return -1;
479 		}
480 		sysoff->n_samples = n_samples;
481 
482 		if (ioctl(fd, PTP_SYS_OFFSET, sysoff))
483 			perror("PTP_SYS_OFFSET");
484 		else
485 			puts("system and phc clock time offset request okay");
486 
487 		pct = &sysoff->ts[0];
488 		for (i = 0; i < sysoff->n_samples; i++) {
489 			t1 = pctns(pct+2*i);
490 			tp = pctns(pct+2*i+1);
491 			t2 = pctns(pct+2*i+2);
492 			interval = t2 - t1;
493 			offset = (t2 + t1) / 2 - tp;
494 
495 			printf("system time: %lld.%u\n",
496 				(pct+2*i)->sec, (pct+2*i)->nsec);
497 			printf("phc    time: %lld.%u\n",
498 				(pct+2*i+1)->sec, (pct+2*i+1)->nsec);
499 			printf("system time: %lld.%u\n",
500 				(pct+2*i+2)->sec, (pct+2*i+2)->nsec);
501 			printf("system/phc clock time offset is %" PRId64 " ns\n"
502 			       "system     clock time delay  is %" PRId64 " ns\n",
503 				offset, interval);
504 		}
505 
506 		free(sysoff);
507 	}
508 
509 	close(fd);
510 	return 0;
511 }
512