File Index
Files and directories
Sign in
FILE

testptp.c

File preview with syntax highlighting.

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