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