xref: /linux/tools/spi/spidev_test.c (revision 113f36f2dce3a5a1aacbfa700c44080ec37ee3a0)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * SPI testing utility (using spidev driver)
4  *
5  * Copyright (c) 2007  MontaVista Software, Inc.
6  * Copyright (c) 2007  Anton Vorontsov <avorontsov@ru.mvista.com>
7  *
8  * Cross-compile with cross-gcc -I/path/to/cross-kernel/include
9  */
10 
11 #include <stdint.h>
12 #include <unistd.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <errno.h>
17 #include <getopt.h>
18 #include <fcntl.h>
19 #include <time.h>
20 #include <sys/ioctl.h>
21 #include <linux/ioctl.h>
22 #include <sys/stat.h>
23 #include <linux/types.h>
24 #include <linux/spi/spidev.h>
25 
26 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
27 
28 static void pabort(const char *s)
29 {
30 	if (errno != 0)
31 		perror(s);
32 	else
33 		printf("%s\n", s);
34 
35 	abort();
36 }
37 
38 static const char *device = "/dev/spidev1.1";
39 static uint32_t mode;
40 static uint8_t bits = 8;
41 static char *input_file;
42 static char *output_file;
43 static uint32_t speed = 500000;
44 static uint16_t delay;
45 static int verbose;
46 static int transfer_size;
47 static int iterations;
48 static int interval = 5; /* interval in seconds for showing transfer rate */
49 
50 static uint8_t default_tx[] = {
51 	0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
52 	0x40, 0x00, 0x00, 0x00, 0x00, 0x95,
53 	0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
54 	0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
55 	0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
56 	0xF0, 0x0D,
57 };
58 
59 static uint8_t default_rx[ARRAY_SIZE(default_tx)] = {0, };
60 static char *input_tx;
61 
62 static void hex_dump(const void *src, size_t length, size_t line_size,
63 		     char *prefix)
64 {
65 	int i = 0;
66 	const unsigned char *address = src;
67 	const unsigned char *line = address;
68 	unsigned char c;
69 
70 	printf("%s | ", prefix);
71 	while (length-- > 0) {
72 		printf("%02X ", *address++);
73 		if (!(++i % line_size) || (length == 0 && i % line_size)) {
74 			if (length == 0) {
75 				while (i++ % line_size)
76 					printf("__ ");
77 			}
78 			printf(" |");
79 			while (line < address) {
80 				c = *line++;
81 				printf("%c", (c < 32 || c > 126) ? '.' : c);
82 			}
83 			printf("|\n");
84 			if (length > 0)
85 				printf("%s | ", prefix);
86 		}
87 	}
88 }
89 
90 /*
91  *  Unescape - process hexadecimal escape character
92  *      converts shell input "\x23" -> 0x23
93  */
94 static int unescape(char *_dst, char *_src, size_t len)
95 {
96 	int ret = 0;
97 	int match;
98 	char *src = _src;
99 	char *dst = _dst;
100 	unsigned int ch;
101 
102 	while (*src) {
103 		if (*src == '\\' && *(src+1) == 'x') {
104 			match = sscanf(src + 2, "%2x", &ch);
105 			if (!match)
106 				pabort("malformed input string");
107 
108 			src += 4;
109 			*dst++ = (unsigned char)ch;
110 		} else {
111 			*dst++ = *src++;
112 		}
113 		ret++;
114 	}
115 	return ret;
116 }
117 
118 static void transfer(int fd, uint8_t const *tx, uint8_t const *rx, size_t len)
119 {
120 	int ret;
121 	int out_fd;
122 	struct spi_ioc_transfer tr = {
123 		.tx_buf = (unsigned long)tx,
124 		.rx_buf = (unsigned long)rx,
125 		.len = len,
126 		.delay_usecs = delay,
127 		.speed_hz = speed,
128 		.bits_per_word = bits,
129 	};
130 
131 	if (mode & SPI_TX_OCTAL)
132 		tr.tx_nbits = 8;
133 	else if (mode & SPI_TX_QUAD)
134 		tr.tx_nbits = 4;
135 	else if (mode & SPI_TX_DUAL)
136 		tr.tx_nbits = 2;
137 	if (mode & SPI_RX_OCTAL)
138 		tr.rx_nbits = 8;
139 	else if (mode & SPI_RX_QUAD)
140 		tr.rx_nbits = 4;
141 	else if (mode & SPI_RX_DUAL)
142 		tr.rx_nbits = 2;
143 	if (!(mode & SPI_LOOP)) {
144 		if (mode & (SPI_TX_OCTAL | SPI_TX_QUAD | SPI_TX_DUAL))
145 			tr.rx_buf = 0;
146 		else if (mode & (SPI_RX_OCTAL | SPI_RX_QUAD | SPI_RX_DUAL))
147 			tr.tx_buf = 0;
148 	}
149 
150 	ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
151 	if (ret < 1)
152 		pabort("can't send spi message");
153 
154 	if (verbose)
155 		hex_dump(tx, len, 32, "TX");
156 
157 	if (output_file) {
158 		out_fd = open(output_file, O_WRONLY | O_CREAT | O_TRUNC, 0666);
159 		if (out_fd < 0)
160 			pabort("could not open output file");
161 
162 		ret = write(out_fd, rx, len);
163 		if (ret != len)
164 			pabort("not all bytes written to output file");
165 
166 		close(out_fd);
167 	}
168 
169 	if (verbose)
170 		hex_dump(rx, len, 32, "RX");
171 }
172 
173 static void print_usage(const char *prog)
174 {
175 	printf("Usage: %s [-2348CDHILNORSbdilopsv]\n", prog);
176 	puts("general device settings:\n"
177 		 "  -D --device         device to use (default /dev/spidev1.1)\n"
178 		 "  -s --speed          max speed (Hz)\n"
179 		 "  -d --delay          delay (usec)\n"
180 		 "  -l --loop           loopback\n"
181 		 "spi mode:\n"
182 		 "  -H --cpha           clock phase\n"
183 		 "  -O --cpol           clock polarity\n"
184 		 "number of wires for transmission:\n"
185 		 "  -2 --dual           dual transfer\n"
186 		 "  -4 --quad           quad transfer\n"
187 		 "  -8 --octal          octal transfer\n"
188 		 "  -3 --3wire          SI/SO signals shared\n"
189 		 "data:\n"
190 		 "  -i --input          input data from a file (e.g. \"test.bin\")\n"
191 		 "  -o --output         output data to a file (e.g. \"results.bin\")\n"
192 		 "  -p                  Send data (e.g. \"1234\\xde\\xad\")\n"
193 		 "  -S --size           transfer size\n"
194 		 "  -I --iter           iterations\n"
195 		 "additional parameters:\n"
196 		 "  -b --bpw            bits per word\n"
197 		 "  -L --lsb            least significant bit first\n"
198 		 "  -C --cs-high        chip select active high\n"
199 		 "  -N --no-cs          no chip select\n"
200 		 "  -R --ready          slave pulls low to pause\n"
201 		 "misc:\n"
202 		 "  -v --verbose        Verbose (show tx buffer)\n");
203 	exit(1);
204 }
205 
206 static void parse_opts(int argc, char *argv[])
207 {
208 	while (1) {
209 		static const struct option lopts[] = {
210 			{ "device",        1, 0, 'D' },
211 			{ "speed",         1, 0, 's' },
212 			{ "delay",         1, 0, 'd' },
213 			{ "loop",          0, 0, 'l' },
214 			{ "cpha",          0, 0, 'H' },
215 			{ "cpol",          0, 0, 'O' },
216 			{ "dual",          0, 0, '2' },
217 			{ "quad",          0, 0, '4' },
218 			{ "octal",         0, 0, '8' },
219 			{ "3wire",         0, 0, '3' },
220 			{ "input",         1, 0, 'i' },
221 			{ "output",        1, 0, 'o' },
222 			{ "size",          1, 0, 'S' },
223 			{ "iter",          1, 0, 'I' },
224 			{ "bpw",           1, 0, 'b' },
225 			{ "lsb",           0, 0, 'L' },
226 			{ "cs-high",       0, 0, 'C' },
227 			{ "no-cs",         0, 0, 'N' },
228 			{ "ready",         0, 0, 'R' },
229 			{ "verbose",       0, 0, 'v' },
230 			{ NULL, 0, 0, 0 },
231 		};
232 		int c;
233 
234 		c = getopt_long(argc, argv, "D:s:d:b:i:o:lHOLC3NR248p:vS:I:",
235 				lopts, NULL);
236 
237 		if (c == -1)
238 			break;
239 
240 		switch (c) {
241 		case 'D':
242 			device = optarg;
243 			break;
244 		case 's':
245 			speed = atoi(optarg);
246 			break;
247 		case 'd':
248 			delay = atoi(optarg);
249 			break;
250 		case 'b':
251 			bits = atoi(optarg);
252 			break;
253 		case 'i':
254 			input_file = optarg;
255 			break;
256 		case 'o':
257 			output_file = optarg;
258 			break;
259 		case 'l':
260 			mode |= SPI_LOOP;
261 			break;
262 		case 'H':
263 			mode |= SPI_CPHA;
264 			break;
265 		case 'O':
266 			mode |= SPI_CPOL;
267 			break;
268 		case 'L':
269 			mode |= SPI_LSB_FIRST;
270 			break;
271 		case 'C':
272 			mode |= SPI_CS_HIGH;
273 			break;
274 		case '3':
275 			mode |= SPI_3WIRE;
276 			break;
277 		case 'N':
278 			mode |= SPI_NO_CS;
279 			break;
280 		case 'v':
281 			verbose = 1;
282 			break;
283 		case 'R':
284 			mode |= SPI_READY;
285 			break;
286 		case 'p':
287 			input_tx = optarg;
288 			break;
289 		case '2':
290 			mode |= SPI_TX_DUAL;
291 			break;
292 		case '4':
293 			mode |= SPI_TX_QUAD;
294 			break;
295 		case '8':
296 			mode |= SPI_TX_OCTAL;
297 			break;
298 		case 'S':
299 			transfer_size = atoi(optarg);
300 			break;
301 		case 'I':
302 			iterations = atoi(optarg);
303 			break;
304 		default:
305 			print_usage(argv[0]);
306 		}
307 	}
308 	if (mode & SPI_LOOP) {
309 		if (mode & SPI_TX_DUAL)
310 			mode |= SPI_RX_DUAL;
311 		if (mode & SPI_TX_QUAD)
312 			mode |= SPI_RX_QUAD;
313 		if (mode & SPI_TX_OCTAL)
314 			mode |= SPI_RX_OCTAL;
315 	}
316 }
317 
318 static void transfer_escaped_string(int fd, char *str)
319 {
320 	size_t size = strlen(str);
321 	uint8_t *tx;
322 	uint8_t *rx;
323 
324 	tx = malloc(size);
325 	if (!tx)
326 		pabort("can't allocate tx buffer");
327 
328 	rx = malloc(size);
329 	if (!rx)
330 		pabort("can't allocate rx buffer");
331 
332 	size = unescape((char *)tx, str, size);
333 	transfer(fd, tx, rx, size);
334 	free(rx);
335 	free(tx);
336 }
337 
338 static void transfer_file(int fd, char *filename)
339 {
340 	ssize_t bytes;
341 	struct stat sb;
342 	int tx_fd;
343 	uint8_t *tx;
344 	uint8_t *rx;
345 
346 	if (stat(filename, &sb) == -1)
347 		pabort("can't stat input file");
348 
349 	tx_fd = open(filename, O_RDONLY);
350 	if (tx_fd < 0)
351 		pabort("can't open input file");
352 
353 	tx = malloc(sb.st_size);
354 	if (!tx)
355 		pabort("can't allocate tx buffer");
356 
357 	rx = malloc(sb.st_size);
358 	if (!rx)
359 		pabort("can't allocate rx buffer");
360 
361 	bytes = read(tx_fd, tx, sb.st_size);
362 	if (bytes != sb.st_size)
363 		pabort("failed to read input file");
364 
365 	transfer(fd, tx, rx, sb.st_size);
366 	free(rx);
367 	free(tx);
368 	close(tx_fd);
369 }
370 
371 static uint64_t _read_count;
372 static uint64_t _write_count;
373 
374 static void show_transfer_rate(void)
375 {
376 	static uint64_t prev_read_count, prev_write_count;
377 	double rx_rate, tx_rate;
378 
379 	rx_rate = ((_read_count - prev_read_count) * 8) / (interval*1000.0);
380 	tx_rate = ((_write_count - prev_write_count) * 8) / (interval*1000.0);
381 
382 	printf("rate: tx %.1fkbps, rx %.1fkbps\n", rx_rate, tx_rate);
383 
384 	prev_read_count = _read_count;
385 	prev_write_count = _write_count;
386 }
387 
388 static void transfer_buf(int fd, int len)
389 {
390 	uint8_t *tx;
391 	uint8_t *rx;
392 	int i;
393 
394 	tx = malloc(len);
395 	if (!tx)
396 		pabort("can't allocate tx buffer");
397 	for (i = 0; i < len; i++)
398 		tx[i] = random();
399 
400 	rx = malloc(len);
401 	if (!rx)
402 		pabort("can't allocate rx buffer");
403 
404 	transfer(fd, tx, rx, len);
405 
406 	_write_count += len;
407 	_read_count += len;
408 
409 	if (mode & SPI_LOOP) {
410 		if (memcmp(tx, rx, len)) {
411 			fprintf(stderr, "transfer error !\n");
412 			hex_dump(tx, len, 32, "TX");
413 			hex_dump(rx, len, 32, "RX");
414 			exit(1);
415 		}
416 	}
417 
418 	free(rx);
419 	free(tx);
420 }
421 
422 int main(int argc, char *argv[])
423 {
424 	int ret = 0;
425 	int fd;
426 	uint32_t request;
427 
428 	parse_opts(argc, argv);
429 
430 	if (input_tx && input_file)
431 		pabort("only one of -p and --input may be selected");
432 
433 	fd = open(device, O_RDWR);
434 	if (fd < 0)
435 		pabort("can't open device");
436 
437 	/*
438 	 * spi mode
439 	 */
440 	/* WR is make a request to assign 'mode' */
441 	request = mode;
442 	ret = ioctl(fd, SPI_IOC_WR_MODE32, &mode);
443 	if (ret == -1)
444 		pabort("can't set spi mode");
445 
446 	/* RD is read what mode the device actually is in */
447 	ret = ioctl(fd, SPI_IOC_RD_MODE32, &mode);
448 	if (ret == -1)
449 		pabort("can't get spi mode");
450 	/* Drivers can reject some mode bits without returning an error.
451 	 * Read the current value to identify what mode it is in, and if it
452 	 * differs from the requested mode, warn the user.
453 	 */
454 	if (request != mode)
455 		printf("WARNING device does not support requested mode 0x%x\n",
456 			request);
457 
458 	/*
459 	 * bits per word
460 	 */
461 	ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
462 	if (ret == -1)
463 		pabort("can't set bits per word");
464 
465 	ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
466 	if (ret == -1)
467 		pabort("can't get bits per word");
468 
469 	/*
470 	 * max speed hz
471 	 */
472 	ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
473 	if (ret == -1)
474 		pabort("can't set max speed hz");
475 
476 	ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
477 	if (ret == -1)
478 		pabort("can't get max speed hz");
479 
480 	printf("spi mode: 0x%x\n", mode);
481 	printf("bits per word: %u\n", bits);
482 	printf("max speed: %u Hz (%u kHz)\n", speed, speed/1000);
483 
484 	if (input_tx)
485 		transfer_escaped_string(fd, input_tx);
486 	else if (input_file)
487 		transfer_file(fd, input_file);
488 	else if (transfer_size) {
489 		struct timespec last_stat;
490 
491 		clock_gettime(CLOCK_MONOTONIC, &last_stat);
492 
493 		while (iterations-- > 0) {
494 			struct timespec current;
495 
496 			transfer_buf(fd, transfer_size);
497 
498 			clock_gettime(CLOCK_MONOTONIC, &current);
499 			if (current.tv_sec - last_stat.tv_sec > interval) {
500 				show_transfer_rate();
501 				last_stat = current;
502 			}
503 		}
504 		printf("total: tx %.1fKB, rx %.1fKB\n",
505 		       _write_count/1024.0, _read_count/1024.0);
506 	} else
507 		transfer(fd, default_tx, default_rx, sizeof(default_tx));
508 
509 	close(fd);
510 
511 	return ret;
512 }
513