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