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