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 /* clock_adjtime is not available in GLIBC < 2.14 */
39 #if !__GLIBC_PREREQ(2, 14)
40 #include <sys/syscall.h>
41 static int clock_adjtime(clockid_t id, struct timex *tx)
42 {
43 	return syscall(__NR_clock_adjtime, id, tx);
44 }
45 #endif
46 
47 static clockid_t get_clockid(int fd)
48 {
49 #define CLOCKFD 3
50 	return (((unsigned int) ~fd) << 3) | CLOCKFD;
51 }
52 
53 static long ppb_to_scaled_ppm(int ppb)
54 {
55 	/*
56 	 * The 'freq' field in the 'struct timex' is in parts per
57 	 * million, but with a 16 bit binary fractional field.
58 	 * Instead of calculating either one of
59 	 *
60 	 *    scaled_ppm = (ppb / 1000) << 16  [1]
61 	 *    scaled_ppm = (ppb << 16) / 1000  [2]
62 	 *
63 	 * we simply use double precision math, in order to avoid the
64 	 * truncation in [1] and the possible overflow in [2].
65 	 */
66 	return (long) (ppb * 65.536);
67 }
68 
69 static int64_t pctns(struct ptp_clock_time *t)
70 {
71 	return t->sec * 1000000000LL + t->nsec;
72 }
73 
74 static void usage(char *progname)
75 {
76 	fprintf(stderr,
77 		"usage: %s [options]\n"
78 		" -c         query the ptp clock's capabilities\n"
79 		" -d name    device to open\n"
80 		" -e val     read 'val' external time stamp events\n"
81 		" -f val     adjust the ptp clock frequency by 'val' ppb\n"
82 		" -g         get the ptp clock time\n"
83 		" -h         prints this message\n"
84 		" -i val     index for event/trigger\n"
85 		" -k val     measure the time offset between system and phc clock\n"
86 		"            for 'val' times (Maximum 25)\n"
87 		" -l         list the current pin configuration\n"
88 		" -L pin,val configure pin index 'pin' with function 'val'\n"
89 		"            the channel index is taken from the '-i' option\n"
90 		"            'val' specifies the auxiliary function:\n"
91 		"            0 - none\n"
92 		"            1 - external time stamp\n"
93 		"            2 - periodic output\n"
94 		" -p val     enable output with a period of 'val' nanoseconds\n"
95 		" -P val     enable or disable (val=1|0) the system clock PPS\n"
96 		" -s         set the ptp clock time from the system time\n"
97 		" -S         set the system time from the ptp clock time\n"
98 		" -t val     shift the ptp clock time by 'val' seconds\n"
99 		" -T val     set the ptp clock time to 'val' seconds\n",
100 		progname);
101 }
102 
103 int main(int argc, char *argv[])
104 {
105 	struct ptp_clock_caps caps;
106 	struct ptp_extts_event event;
107 	struct ptp_extts_request extts_request;
108 	struct ptp_perout_request perout_request;
109 	struct ptp_pin_desc desc;
110 	struct timespec ts;
111 	struct timex tx;
112 	struct ptp_clock_time *pct;
113 	struct ptp_sys_offset *sysoff;
114 
115 	char *progname;
116 	unsigned int i;
117 	int c, cnt, fd;
118 
119 	char *device = DEVICE;
120 	clockid_t clkid;
121 	int adjfreq = 0x7fffffff;
122 	int adjtime = 0;
123 	int capabilities = 0;
124 	int extts = 0;
125 	int gettime = 0;
126 	int index = 0;
127 	int list_pins = 0;
128 	int pct_offset = 0;
129 	int n_samples = 0;
130 	int perout = -1;
131 	int pin_index = -1, pin_func;
132 	int pps = -1;
133 	int seconds = 0;
134 	int settime = 0;
135 
136 	int64_t t1, t2, tp;
137 	int64_t interval, offset;
138 
139 	progname = strrchr(argv[0], '/');
140 	progname = progname ? 1+progname : argv[0];
141 	while (EOF != (c = getopt(argc, argv, "cd:e:f:ghi:k:lL:p:P:sSt:T:v"))) {
142 		switch (c) {
143 		case 'c':
144 			capabilities = 1;
145 			break;
146 		case 'd':
147 			device = optarg;
148 			break;
149 		case 'e':
150 			extts = atoi(optarg);
151 			break;
152 		case 'f':
153 			adjfreq = atoi(optarg);
154 			break;
155 		case 'g':
156 			gettime = 1;
157 			break;
158 		case 'i':
159 			index = atoi(optarg);
160 			break;
161 		case 'k':
162 			pct_offset = 1;
163 			n_samples = atoi(optarg);
164 			break;
165 		case 'l':
166 			list_pins = 1;
167 			break;
168 		case 'L':
169 			cnt = sscanf(optarg, "%d,%d", &pin_index, &pin_func);
170 			if (cnt != 2) {
171 				usage(progname);
172 				return -1;
173 			}
174 			break;
175 		case 'p':
176 			perout = atoi(optarg);
177 			break;
178 		case 'P':
179 			pps = atoi(optarg);
180 			break;
181 		case 's':
182 			settime = 1;
183 			break;
184 		case 'S':
185 			settime = 2;
186 			break;
187 		case 't':
188 			adjtime = atoi(optarg);
189 			break;
190 		case 'T':
191 			settime = 3;
192 			seconds = atoi(optarg);
193 			break;
194 		case 'h':
195 			usage(progname);
196 			return 0;
197 		case '?':
198 		default:
199 			usage(progname);
200 			return -1;
201 		}
202 	}
203 
204 	fd = open(device, O_RDWR);
205 	if (fd < 0) {
206 		fprintf(stderr, "opening %s: %s\n", device, strerror(errno));
207 		return -1;
208 	}
209 
210 	clkid = get_clockid(fd);
211 	if (CLOCK_INVALID == clkid) {
212 		fprintf(stderr, "failed to read clock id\n");
213 		return -1;
214 	}
215 
216 	if (capabilities) {
217 		if (ioctl(fd, PTP_CLOCK_GETCAPS, &caps)) {
218 			perror("PTP_CLOCK_GETCAPS");
219 		} else {
220 			printf("capabilities:\n"
221 			       "  %d maximum frequency adjustment (ppb)\n"
222 			       "  %d programmable alarms\n"
223 			       "  %d external time stamp channels\n"
224 			       "  %d programmable periodic signals\n"
225 			       "  %d pulse per second\n"
226 			       "  %d programmable pins\n"
227 			       "  %d cross timestamping\n",
228 			       caps.max_adj,
229 			       caps.n_alarm,
230 			       caps.n_ext_ts,
231 			       caps.n_per_out,
232 			       caps.pps,
233 			       caps.n_pins,
234 			       caps.cross_timestamping);
235 		}
236 	}
237 
238 	if (0x7fffffff != adjfreq) {
239 		memset(&tx, 0, sizeof(tx));
240 		tx.modes = ADJ_FREQUENCY;
241 		tx.freq = ppb_to_scaled_ppm(adjfreq);
242 		if (clock_adjtime(clkid, &tx)) {
243 			perror("clock_adjtime");
244 		} else {
245 			puts("frequency adjustment okay");
246 		}
247 	}
248 
249 	if (adjtime) {
250 		memset(&tx, 0, sizeof(tx));
251 		tx.modes = ADJ_SETOFFSET;
252 		tx.time.tv_sec = adjtime;
253 		tx.time.tv_usec = 0;
254 		if (clock_adjtime(clkid, &tx) < 0) {
255 			perror("clock_adjtime");
256 		} else {
257 			puts("time shift okay");
258 		}
259 	}
260 
261 	if (gettime) {
262 		if (clock_gettime(clkid, &ts)) {
263 			perror("clock_gettime");
264 		} else {
265 			printf("clock time: %ld.%09ld or %s",
266 			       ts.tv_sec, ts.tv_nsec, ctime(&ts.tv_sec));
267 		}
268 	}
269 
270 	if (settime == 1) {
271 		clock_gettime(CLOCK_REALTIME, &ts);
272 		if (clock_settime(clkid, &ts)) {
273 			perror("clock_settime");
274 		} else {
275 			puts("set time okay");
276 		}
277 	}
278 
279 	if (settime == 2) {
280 		clock_gettime(clkid, &ts);
281 		if (clock_settime(CLOCK_REALTIME, &ts)) {
282 			perror("clock_settime");
283 		} else {
284 			puts("set time okay");
285 		}
286 	}
287 
288 	if (settime == 3) {
289 		ts.tv_sec = seconds;
290 		ts.tv_nsec = 0;
291 		if (clock_settime(clkid, &ts)) {
292 			perror("clock_settime");
293 		} else {
294 			puts("set time okay");
295 		}
296 	}
297 
298 	if (extts) {
299 		memset(&extts_request, 0, sizeof(extts_request));
300 		extts_request.index = index;
301 		extts_request.flags = PTP_ENABLE_FEATURE;
302 		if (ioctl(fd, PTP_EXTTS_REQUEST, &extts_request)) {
303 			perror("PTP_EXTTS_REQUEST");
304 			extts = 0;
305 		} else {
306 			puts("external time stamp request okay");
307 		}
308 		for (; extts; extts--) {
309 			cnt = read(fd, &event, sizeof(event));
310 			if (cnt != sizeof(event)) {
311 				perror("read");
312 				break;
313 			}
314 			printf("event index %u at %lld.%09u\n", event.index,
315 			       event.t.sec, event.t.nsec);
316 			fflush(stdout);
317 		}
318 		/* Disable the feature again. */
319 		extts_request.flags = 0;
320 		if (ioctl(fd, PTP_EXTTS_REQUEST, &extts_request)) {
321 			perror("PTP_EXTTS_REQUEST");
322 		}
323 	}
324 
325 	if (list_pins) {
326 		int n_pins = 0;
327 		if (ioctl(fd, PTP_CLOCK_GETCAPS, &caps)) {
328 			perror("PTP_CLOCK_GETCAPS");
329 		} else {
330 			n_pins = caps.n_pins;
331 		}
332 		for (i = 0; i < n_pins; i++) {
333 			desc.index = i;
334 			if (ioctl(fd, PTP_PIN_GETFUNC, &desc)) {
335 				perror("PTP_PIN_GETFUNC");
336 				break;
337 			}
338 			printf("name %s index %u func %u chan %u\n",
339 			       desc.name, desc.index, desc.func, desc.chan);
340 		}
341 	}
342 
343 	if (perout >= 0) {
344 		if (clock_gettime(clkid, &ts)) {
345 			perror("clock_gettime");
346 			return -1;
347 		}
348 		memset(&perout_request, 0, sizeof(perout_request));
349 		perout_request.index = index;
350 		perout_request.start.sec = ts.tv_sec + 2;
351 		perout_request.start.nsec = 0;
352 		perout_request.period.sec = 0;
353 		perout_request.period.nsec = perout;
354 		if (ioctl(fd, PTP_PEROUT_REQUEST, &perout_request)) {
355 			perror("PTP_PEROUT_REQUEST");
356 		} else {
357 			puts("periodic output request okay");
358 		}
359 	}
360 
361 	if (pin_index >= 0) {
362 		memset(&desc, 0, sizeof(desc));
363 		desc.index = pin_index;
364 		desc.func = pin_func;
365 		desc.chan = index;
366 		if (ioctl(fd, PTP_PIN_SETFUNC, &desc)) {
367 			perror("PTP_PIN_SETFUNC");
368 		} else {
369 			puts("set pin function okay");
370 		}
371 	}
372 
373 	if (pps != -1) {
374 		int enable = pps ? 1 : 0;
375 		if (ioctl(fd, PTP_ENABLE_PPS, enable)) {
376 			perror("PTP_ENABLE_PPS");
377 		} else {
378 			puts("pps for system time request okay");
379 		}
380 	}
381 
382 	if (pct_offset) {
383 		if (n_samples <= 0 || n_samples > 25) {
384 			puts("n_samples should be between 1 and 25");
385 			usage(progname);
386 			return -1;
387 		}
388 
389 		sysoff = calloc(1, sizeof(*sysoff));
390 		if (!sysoff) {
391 			perror("calloc");
392 			return -1;
393 		}
394 		sysoff->n_samples = n_samples;
395 
396 		if (ioctl(fd, PTP_SYS_OFFSET, sysoff))
397 			perror("PTP_SYS_OFFSET");
398 		else
399 			puts("system and phc clock time offset request okay");
400 
401 		pct = &sysoff->ts[0];
402 		for (i = 0; i < sysoff->n_samples; i++) {
403 			t1 = pctns(pct+2*i);
404 			tp = pctns(pct+2*i+1);
405 			t2 = pctns(pct+2*i+2);
406 			interval = t2 - t1;
407 			offset = (t2 + t1) / 2 - tp;
408 
409 			printf("system time: %lld.%u\n",
410 				(pct+2*i)->sec, (pct+2*i)->nsec);
411 			printf("phc    time: %lld.%u\n",
412 				(pct+2*i+1)->sec, (pct+2*i+1)->nsec);
413 			printf("system time: %lld.%u\n",
414 				(pct+2*i+2)->sec, (pct+2*i+2)->nsec);
415 			printf("system/phc clock time offset is %" PRId64 " ns\n"
416 			       "system     clock time delay  is %" PRId64 " ns\n",
417 				offset, interval);
418 		}
419 
420 		free(sysoff);
421 	}
422 
423 	close(fd);
424 	return 0;
425 }
426