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>
clock_adjtime(clockid_t id,struct timex * tx)43 static int clock_adjtime(clockid_t id, struct timex *tx)
44 {
45 	return syscall(__NR_clock_adjtime, id, tx);
46 }
47 #endif
48 
show_flag_test(int rq_index,unsigned int flags,int err)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 
do_flag_test(int fd,unsigned int index)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 
get_clockid(int fd)89 static clockid_t get_clockid(int fd)
90 {
91 #define CLOCKFD 3
92 	return (((unsigned int) ~fd) << 3) | CLOCKFD;
93 }
94 
ppb_to_scaled_ppm(int ppb)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 
pctns(struct ptp_clock_time * t)111 static int64_t pctns(struct ptp_clock_time *t)
112 {
113 	return t->sec * NSEC_PER_SEC + t->nsec;
114 }
115 
usage(char * progname)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 		" -n val     shift the ptp clock time by 'val' nanoseconds\n"
137 		" -o val     phase offset (in nanoseconds) to be provided to the PHC servo\n"
138 		" -p val     enable output with a period of 'val' nanoseconds\n"
139 		" -H val     set output phase to 'val' nanoseconds (requires -p)\n"
140 		" -w val     set output pulse width to 'val' nanoseconds (requires -p)\n"
141 		" -P val     enable or disable (val=1|0) the system clock PPS\n"
142 		" -s         set the ptp clock time from the system time\n"
143 		" -S         set the system time from the ptp clock time\n"
144 		" -t val     shift the ptp clock time by 'val' seconds\n"
145 		" -T val     set the ptp clock time to 'val' seconds\n"
146 		" -x val     get an extended ptp clock time with the desired number of samples (up to %d)\n"
147 		" -X         get a ptp clock cross timestamp\n"
148 		" -z         test combinations of rising/falling external time stamp flags\n",
149 		progname, PTP_MAX_SAMPLES);
150 }
151 
main(int argc,char * argv[])152 int main(int argc, char *argv[])
153 {
154 	struct ptp_clock_caps caps;
155 	struct ptp_extts_event event;
156 	struct ptp_extts_request extts_request;
157 	struct ptp_perout_request perout_request;
158 	struct ptp_pin_desc desc;
159 	struct timespec ts;
160 	struct timex tx;
161 	struct ptp_clock_time *pct;
162 	struct ptp_sys_offset *sysoff;
163 	struct ptp_sys_offset_extended *soe;
164 	struct ptp_sys_offset_precise *xts;
165 
166 	char *progname;
167 	unsigned int i;
168 	int c, cnt, fd;
169 
170 	char *device = DEVICE;
171 	clockid_t clkid;
172 	int adjfreq = 0x7fffffff;
173 	int adjtime = 0;
174 	int adjns = 0;
175 	int adjphase = 0;
176 	int capabilities = 0;
177 	int extts = 0;
178 	int flagtest = 0;
179 	int gettime = 0;
180 	int index = 0;
181 	int list_pins = 0;
182 	int pct_offset = 0;
183 	int getextended = 0;
184 	int getcross = 0;
185 	int n_samples = 0;
186 	int pin_index = -1, pin_func;
187 	int pps = -1;
188 	int seconds = 0;
189 	int settime = 0;
190 
191 	int64_t t1, t2, tp;
192 	int64_t interval, offset;
193 	int64_t perout_phase = -1;
194 	int64_t pulsewidth = -1;
195 	int64_t perout = -1;
196 
197 	progname = strrchr(argv[0], '/');
198 	progname = progname ? 1+progname : argv[0];
199 	while (EOF != (c = getopt(argc, argv, "cd:e:f:ghH:i:k:lL:n:o:p:P:sSt:T:w:x:Xz"))) {
200 		switch (c) {
201 		case 'c':
202 			capabilities = 1;
203 			break;
204 		case 'd':
205 			device = optarg;
206 			break;
207 		case 'e':
208 			extts = atoi(optarg);
209 			break;
210 		case 'f':
211 			adjfreq = atoi(optarg);
212 			break;
213 		case 'g':
214 			gettime = 1;
215 			break;
216 		case 'H':
217 			perout_phase = atoll(optarg);
218 			break;
219 		case 'i':
220 			index = atoi(optarg);
221 			break;
222 		case 'k':
223 			pct_offset = 1;
224 			n_samples = atoi(optarg);
225 			break;
226 		case 'l':
227 			list_pins = 1;
228 			break;
229 		case 'L':
230 			cnt = sscanf(optarg, "%d,%d", &pin_index, &pin_func);
231 			if (cnt != 2) {
232 				usage(progname);
233 				return -1;
234 			}
235 			break;
236 		case 'n':
237 			adjns = atoi(optarg);
238 			break;
239 		case 'o':
240 			adjphase = atoi(optarg);
241 			break;
242 		case 'p':
243 			perout = atoll(optarg);
244 			break;
245 		case 'P':
246 			pps = atoi(optarg);
247 			break;
248 		case 's':
249 			settime = 1;
250 			break;
251 		case 'S':
252 			settime = 2;
253 			break;
254 		case 't':
255 			adjtime = atoi(optarg);
256 			break;
257 		case 'T':
258 			settime = 3;
259 			seconds = atoi(optarg);
260 			break;
261 		case 'w':
262 			pulsewidth = atoi(optarg);
263 			break;
264 		case 'x':
265 			getextended = atoi(optarg);
266 			if (getextended < 1 || getextended > PTP_MAX_SAMPLES) {
267 				fprintf(stderr,
268 					"number of extended timestamp samples must be between 1 and %d; was asked for %d\n",
269 					PTP_MAX_SAMPLES, getextended);
270 				return -1;
271 			}
272 			break;
273 		case 'X':
274 			getcross = 1;
275 			break;
276 		case 'z':
277 			flagtest = 1;
278 			break;
279 		case 'h':
280 			usage(progname);
281 			return 0;
282 		case '?':
283 		default:
284 			usage(progname);
285 			return -1;
286 		}
287 	}
288 
289 	fd = open(device, O_RDWR);
290 	if (fd < 0) {
291 		fprintf(stderr, "opening %s: %s\n", device, strerror(errno));
292 		return -1;
293 	}
294 
295 	clkid = get_clockid(fd);
296 	if (CLOCK_INVALID == clkid) {
297 		fprintf(stderr, "failed to read clock id\n");
298 		return -1;
299 	}
300 
301 	if (capabilities) {
302 		if (ioctl(fd, PTP_CLOCK_GETCAPS, &caps)) {
303 			perror("PTP_CLOCK_GETCAPS");
304 		} else {
305 			printf("capabilities:\n"
306 			       "  %d maximum frequency adjustment (ppb)\n"
307 			       "  %d programmable alarms\n"
308 			       "  %d external time stamp channels\n"
309 			       "  %d programmable periodic signals\n"
310 			       "  %d pulse per second\n"
311 			       "  %d programmable pins\n"
312 			       "  %d cross timestamping\n"
313 			       "  %d adjust_phase\n"
314 			       "  %d maximum phase adjustment (ns)\n",
315 			       caps.max_adj,
316 			       caps.n_alarm,
317 			       caps.n_ext_ts,
318 			       caps.n_per_out,
319 			       caps.pps,
320 			       caps.n_pins,
321 			       caps.cross_timestamping,
322 			       caps.adjust_phase,
323 			       caps.max_phase_adj);
324 		}
325 	}
326 
327 	if (0x7fffffff != adjfreq) {
328 		memset(&tx, 0, sizeof(tx));
329 		tx.modes = ADJ_FREQUENCY;
330 		tx.freq = ppb_to_scaled_ppm(adjfreq);
331 		if (clock_adjtime(clkid, &tx)) {
332 			perror("clock_adjtime");
333 		} else {
334 			puts("frequency adjustment okay");
335 		}
336 	}
337 
338 	if (adjtime || adjns) {
339 		memset(&tx, 0, sizeof(tx));
340 		tx.modes = ADJ_SETOFFSET | ADJ_NANO;
341 		tx.time.tv_sec = adjtime;
342 		tx.time.tv_usec = adjns;
343 		while (tx.time.tv_usec < 0) {
344 			tx.time.tv_sec  -= 1;
345 			tx.time.tv_usec += NSEC_PER_SEC;
346 		}
347 
348 		if (clock_adjtime(clkid, &tx) < 0) {
349 			perror("clock_adjtime");
350 		} else {
351 			puts("time shift okay");
352 		}
353 	}
354 
355 	if (adjphase) {
356 		memset(&tx, 0, sizeof(tx));
357 		tx.modes = ADJ_OFFSET | ADJ_NANO;
358 		tx.offset = adjphase;
359 
360 		if (clock_adjtime(clkid, &tx) < 0) {
361 			perror("clock_adjtime");
362 		} else {
363 			puts("phase adjustment okay");
364 		}
365 	}
366 
367 	if (gettime) {
368 		if (clock_gettime(clkid, &ts)) {
369 			perror("clock_gettime");
370 		} else {
371 			printf("clock time: %ld.%09ld or %s",
372 			       ts.tv_sec, ts.tv_nsec, ctime(&ts.tv_sec));
373 		}
374 	}
375 
376 	if (settime == 1) {
377 		clock_gettime(CLOCK_REALTIME, &ts);
378 		if (clock_settime(clkid, &ts)) {
379 			perror("clock_settime");
380 		} else {
381 			puts("set time okay");
382 		}
383 	}
384 
385 	if (settime == 2) {
386 		clock_gettime(clkid, &ts);
387 		if (clock_settime(CLOCK_REALTIME, &ts)) {
388 			perror("clock_settime");
389 		} else {
390 			puts("set time okay");
391 		}
392 	}
393 
394 	if (settime == 3) {
395 		ts.tv_sec = seconds;
396 		ts.tv_nsec = 0;
397 		if (clock_settime(clkid, &ts)) {
398 			perror("clock_settime");
399 		} else {
400 			puts("set time okay");
401 		}
402 	}
403 
404 	if (pin_index >= 0) {
405 		memset(&desc, 0, sizeof(desc));
406 		desc.index = pin_index;
407 		desc.func = pin_func;
408 		desc.chan = index;
409 		if (ioctl(fd, PTP_PIN_SETFUNC, &desc)) {
410 			perror("PTP_PIN_SETFUNC");
411 		} else {
412 			puts("set pin function okay");
413 		}
414 	}
415 
416 	if (extts) {
417 		memset(&extts_request, 0, sizeof(extts_request));
418 		extts_request.index = index;
419 		extts_request.flags = PTP_ENABLE_FEATURE;
420 		if (ioctl(fd, PTP_EXTTS_REQUEST, &extts_request)) {
421 			perror("PTP_EXTTS_REQUEST");
422 			extts = 0;
423 		} else {
424 			puts("external time stamp request okay");
425 		}
426 		for (; extts; extts--) {
427 			cnt = read(fd, &event, sizeof(event));
428 			if (cnt != sizeof(event)) {
429 				perror("read");
430 				break;
431 			}
432 			printf("event index %u at %lld.%09u\n", event.index,
433 			       event.t.sec, event.t.nsec);
434 			fflush(stdout);
435 		}
436 		/* Disable the feature again. */
437 		extts_request.flags = 0;
438 		if (ioctl(fd, PTP_EXTTS_REQUEST, &extts_request)) {
439 			perror("PTP_EXTTS_REQUEST");
440 		}
441 	}
442 
443 	if (flagtest) {
444 		do_flag_test(fd, index);
445 	}
446 
447 	if (list_pins) {
448 		int n_pins = 0;
449 		if (ioctl(fd, PTP_CLOCK_GETCAPS, &caps)) {
450 			perror("PTP_CLOCK_GETCAPS");
451 		} else {
452 			n_pins = caps.n_pins;
453 		}
454 		for (i = 0; i < n_pins; i++) {
455 			desc.index = i;
456 			if (ioctl(fd, PTP_PIN_GETFUNC, &desc)) {
457 				perror("PTP_PIN_GETFUNC");
458 				break;
459 			}
460 			printf("name %s index %u func %u chan %u\n",
461 			       desc.name, desc.index, desc.func, desc.chan);
462 		}
463 	}
464 
465 	if (pulsewidth >= 0 && perout < 0) {
466 		puts("-w can only be specified together with -p");
467 		return -1;
468 	}
469 
470 	if (perout_phase >= 0 && perout < 0) {
471 		puts("-H can only be specified together with -p");
472 		return -1;
473 	}
474 
475 	if (perout >= 0) {
476 		if (clock_gettime(clkid, &ts)) {
477 			perror("clock_gettime");
478 			return -1;
479 		}
480 		memset(&perout_request, 0, sizeof(perout_request));
481 		perout_request.index = index;
482 		perout_request.period.sec = perout / NSEC_PER_SEC;
483 		perout_request.period.nsec = perout % NSEC_PER_SEC;
484 		perout_request.flags = 0;
485 		if (pulsewidth >= 0) {
486 			perout_request.flags |= PTP_PEROUT_DUTY_CYCLE;
487 			perout_request.on.sec = pulsewidth / NSEC_PER_SEC;
488 			perout_request.on.nsec = pulsewidth % NSEC_PER_SEC;
489 		}
490 		if (perout_phase >= 0) {
491 			perout_request.flags |= PTP_PEROUT_PHASE;
492 			perout_request.phase.sec = perout_phase / NSEC_PER_SEC;
493 			perout_request.phase.nsec = perout_phase % NSEC_PER_SEC;
494 		} else {
495 			perout_request.start.sec = ts.tv_sec + 2;
496 			perout_request.start.nsec = 0;
497 		}
498 
499 		if (ioctl(fd, PTP_PEROUT_REQUEST2, &perout_request)) {
500 			perror("PTP_PEROUT_REQUEST");
501 		} else {
502 			puts("periodic output request okay");
503 		}
504 	}
505 
506 	if (pps != -1) {
507 		int enable = pps ? 1 : 0;
508 		if (ioctl(fd, PTP_ENABLE_PPS, enable)) {
509 			perror("PTP_ENABLE_PPS");
510 		} else {
511 			puts("pps for system time request okay");
512 		}
513 	}
514 
515 	if (pct_offset) {
516 		if (n_samples <= 0 || n_samples > 25) {
517 			puts("n_samples should be between 1 and 25");
518 			usage(progname);
519 			return -1;
520 		}
521 
522 		sysoff = calloc(1, sizeof(*sysoff));
523 		if (!sysoff) {
524 			perror("calloc");
525 			return -1;
526 		}
527 		sysoff->n_samples = n_samples;
528 
529 		if (ioctl(fd, PTP_SYS_OFFSET, sysoff))
530 			perror("PTP_SYS_OFFSET");
531 		else
532 			puts("system and phc clock time offset request okay");
533 
534 		pct = &sysoff->ts[0];
535 		for (i = 0; i < sysoff->n_samples; i++) {
536 			t1 = pctns(pct+2*i);
537 			tp = pctns(pct+2*i+1);
538 			t2 = pctns(pct+2*i+2);
539 			interval = t2 - t1;
540 			offset = (t2 + t1) / 2 - tp;
541 
542 			printf("system time: %lld.%09u\n",
543 				(pct+2*i)->sec, (pct+2*i)->nsec);
544 			printf("phc    time: %lld.%09u\n",
545 				(pct+2*i+1)->sec, (pct+2*i+1)->nsec);
546 			printf("system time: %lld.%09u\n",
547 				(pct+2*i+2)->sec, (pct+2*i+2)->nsec);
548 			printf("system/phc clock time offset is %" PRId64 " ns\n"
549 			       "system     clock time delay  is %" PRId64 " ns\n",
550 				offset, interval);
551 		}
552 
553 		free(sysoff);
554 	}
555 
556 	if (getextended) {
557 		soe = calloc(1, sizeof(*soe));
558 		if (!soe) {
559 			perror("calloc");
560 			return -1;
561 		}
562 
563 		soe->n_samples = getextended;
564 
565 		if (ioctl(fd, PTP_SYS_OFFSET_EXTENDED, soe)) {
566 			perror("PTP_SYS_OFFSET_EXTENDED");
567 		} else {
568 			printf("extended timestamp request returned %d samples\n",
569 			       getextended);
570 
571 			for (i = 0; i < getextended; i++) {
572 				printf("sample #%2d: system time before: %lld.%09u\n",
573 				       i, soe->ts[i][0].sec, soe->ts[i][0].nsec);
574 				printf("            phc time: %lld.%09u\n",
575 				       soe->ts[i][1].sec, soe->ts[i][1].nsec);
576 				printf("            system time after: %lld.%09u\n",
577 				       soe->ts[i][2].sec, soe->ts[i][2].nsec);
578 			}
579 		}
580 
581 		free(soe);
582 	}
583 
584 	if (getcross) {
585 		xts = calloc(1, sizeof(*xts));
586 		if (!xts) {
587 			perror("calloc");
588 			return -1;
589 		}
590 
591 		if (ioctl(fd, PTP_SYS_OFFSET_PRECISE, xts)) {
592 			perror("PTP_SYS_OFFSET_PRECISE");
593 		} else {
594 			puts("system and phc crosstimestamping request okay");
595 
596 			printf("device time: %lld.%09u\n",
597 			       xts->device.sec, xts->device.nsec);
598 			printf("system time: %lld.%09u\n",
599 			       xts->sys_realtime.sec, xts->sys_realtime.nsec);
600 			printf("monoraw time: %lld.%09u\n",
601 			       xts->sys_monoraw.sec, xts->sys_monoraw.nsec);
602 		}
603 
604 		free(xts);
605 	}
606 
607 	close(fd);
608 	return 0;
609 }
610