1 /*
2  *  linux/drivers/spi/spi-loopback-test.c
3  *
4  *  (c) Martin Sperl <[email protected]>
5  *
6  *  Loopback test driver to test several typical spi_message conditions
7  *  that a spi_master driver may encounter
8  *  this can also get used for regression testing
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 2 of the License, or
13  *  (at your option) any later version.
14  *
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  */
20 
21 #include <linux/delay.h>
22 #include <linux/kernel.h>
23 #include <linux/ktime.h>
24 #include <linux/list.h>
25 #include <linux/list_sort.h>
26 #include <linux/module.h>
27 #include <linux/of_device.h>
28 #include <linux/printk.h>
29 #include <linux/spi/spi.h>
30 
31 #include "spi-test.h"
32 
33 /* flag to only simulate transfers */
34 int simulate_only;
35 module_param(simulate_only, int, 0);
36 MODULE_PARM_DESC(simulate_only, "if not 0 do not execute the spi message");
37 
38 /* dump spi messages */
39 int dump_messages;
40 module_param(dump_messages, int, 0);
41 MODULE_PARM_DESC(dump_messages,
42 		 "=1 dump the basic spi_message_structure, " \
43 		 "=2 dump the spi_message_structure including data, " \
44 		 "=3 dump the spi_message structure before and after execution");
45 /* the device is jumpered for loopback - enabling some rx_buf tests */
46 int loopback;
47 module_param(loopback, int, 0);
48 MODULE_PARM_DESC(loopback,
49 		 "if set enable loopback mode, where the rx_buf "	\
50 		 "is checked to match tx_buf after the spi_message "	\
51 		 "is executed");
52 
53 /* run only a specific test */
54 int run_only_test = -1;
55 module_param(run_only_test, int, 0);
56 MODULE_PARM_DESC(run_only_test,
57 		 "only run the test with this number (0-based !)");
58 
59 /* the actual tests to execute */
60 static struct spi_test spi_tests[] = {
61 	{
62 		.description	= "tx/rx-transfer - start of page",
63 		.fill_option	= FILL_COUNT_8,
64 		.iterate_len    = { ITERATE_MAX_LEN },
65 		.iterate_tx_align = ITERATE_ALIGN,
66 		.iterate_rx_align = ITERATE_ALIGN,
67 		.transfer_count = 1,
68 		.transfers		= {
69 			{
70 				.tx_buf = TX(0),
71 				.rx_buf = RX(0),
72 			},
73 		},
74 	},
75 	{
76 		.description	= "tx/rx-transfer - crossing PAGE_SIZE",
77 		.fill_option	= FILL_COUNT_8,
78 		.iterate_len    = { ITERATE_MAX_LEN },
79 		.iterate_tx_align = ITERATE_ALIGN,
80 		.iterate_rx_align = ITERATE_ALIGN,
81 		.transfer_count = 1,
82 		.transfers		= {
83 			{
84 				.tx_buf = TX(PAGE_SIZE - 4),
85 				.rx_buf = RX(PAGE_SIZE - 4),
86 			},
87 		},
88 	},
89 	{
90 		.description	= "tx-transfer - only",
91 		.fill_option	= FILL_COUNT_8,
92 		.iterate_len    = { ITERATE_MAX_LEN },
93 		.iterate_tx_align = ITERATE_ALIGN,
94 		.transfer_count = 1,
95 		.transfers		= {
96 			{
97 				.tx_buf = TX(0),
98 			},
99 		},
100 	},
101 	{
102 		.description	= "rx-transfer - only",
103 		.fill_option	= FILL_COUNT_8,
104 		.iterate_len    = { ITERATE_MAX_LEN },
105 		.iterate_rx_align = ITERATE_ALIGN,
106 		.transfer_count = 1,
107 		.transfers		= {
108 			{
109 				.rx_buf = RX(0),
110 			},
111 		},
112 	},
113 	{
114 		.description	= "two tx-transfers - alter both",
115 		.fill_option	= FILL_COUNT_8,
116 		.iterate_len    = { ITERATE_LEN },
117 		.iterate_tx_align = ITERATE_ALIGN,
118 		.iterate_transfer_mask = BIT(0) | BIT(1),
119 		.transfer_count = 2,
120 		.transfers		= {
121 			{
122 				.tx_buf = TX(0),
123 			},
124 			{
125 				/* this is why we cant use ITERATE_MAX_LEN */
126 				.tx_buf = TX(SPI_TEST_MAX_SIZE_HALF),
127 			},
128 		},
129 	},
130 	{
131 		.description	= "two tx-transfers - alter first",
132 		.fill_option	= FILL_COUNT_8,
133 		.iterate_len    = { ITERATE_MAX_LEN },
134 		.iterate_tx_align = ITERATE_ALIGN,
135 		.iterate_transfer_mask = BIT(0),
136 		.transfer_count = 2,
137 		.transfers		= {
138 			{
139 				.tx_buf = TX(64),
140 			},
141 			{
142 				.len = 1,
143 				.tx_buf = TX(0),
144 			},
145 		},
146 	},
147 	{
148 		.description	= "two tx-transfers - alter second",
149 		.fill_option	= FILL_COUNT_8,
150 		.iterate_len    = { ITERATE_MAX_LEN },
151 		.iterate_tx_align = ITERATE_ALIGN,
152 		.iterate_transfer_mask = BIT(1),
153 		.transfer_count = 2,
154 		.transfers		= {
155 			{
156 				.len = 16,
157 				.tx_buf = TX(0),
158 			},
159 			{
160 				.tx_buf = TX(64),
161 			},
162 		},
163 	},
164 	{
165 		.description	= "two transfers tx then rx - alter both",
166 		.fill_option	= FILL_COUNT_8,
167 		.iterate_len    = { ITERATE_MAX_LEN },
168 		.iterate_tx_align = ITERATE_ALIGN,
169 		.iterate_transfer_mask = BIT(0) | BIT(1),
170 		.transfer_count = 2,
171 		.transfers		= {
172 			{
173 				.tx_buf = TX(0),
174 			},
175 			{
176 				.rx_buf = RX(0),
177 			},
178 		},
179 	},
180 	{
181 		.description	= "two transfers tx then rx - alter tx",
182 		.fill_option	= FILL_COUNT_8,
183 		.iterate_len    = { ITERATE_MAX_LEN },
184 		.iterate_tx_align = ITERATE_ALIGN,
185 		.iterate_transfer_mask = BIT(0),
186 		.transfer_count = 2,
187 		.transfers		= {
188 			{
189 				.tx_buf = TX(0),
190 			},
191 			{
192 				.len = 1,
193 				.rx_buf = RX(0),
194 			},
195 		},
196 	},
197 	{
198 		.description	= "two transfers tx then rx - alter rx",
199 		.fill_option	= FILL_COUNT_8,
200 		.iterate_len    = { ITERATE_MAX_LEN },
201 		.iterate_tx_align = ITERATE_ALIGN,
202 		.iterate_transfer_mask = BIT(1),
203 		.transfer_count = 2,
204 		.transfers		= {
205 			{
206 				.len = 1,
207 				.tx_buf = TX(0),
208 			},
209 			{
210 				.rx_buf = RX(0),
211 			},
212 		},
213 	},
214 	{
215 		.description	= "two tx+rx transfers - alter both",
216 		.fill_option	= FILL_COUNT_8,
217 		.iterate_len    = { ITERATE_LEN },
218 		.iterate_tx_align = ITERATE_ALIGN,
219 		.iterate_transfer_mask = BIT(0) | BIT(1),
220 		.transfer_count = 2,
221 		.transfers		= {
222 			{
223 				.tx_buf = TX(0),
224 				.rx_buf = RX(0),
225 			},
226 			{
227 				/* making sure we align without overwrite
228 				 * the reason we can not use ITERATE_MAX_LEN
229 				 */
230 				.tx_buf = TX(SPI_TEST_MAX_SIZE_HALF),
231 				.rx_buf = RX(SPI_TEST_MAX_SIZE_HALF),
232 			},
233 		},
234 	},
235 	{
236 		.description	= "two tx+rx transfers - alter first",
237 		.fill_option	= FILL_COUNT_8,
238 		.iterate_len    = { ITERATE_MAX_LEN },
239 		.iterate_tx_align = ITERATE_ALIGN,
240 		.iterate_transfer_mask = BIT(0),
241 		.transfer_count = 2,
242 		.transfers		= {
243 			{
244 				/* making sure we align without overwrite */
245 				.tx_buf = TX(1024),
246 				.rx_buf = RX(1024),
247 			},
248 			{
249 				.len = 1,
250 				/* making sure we align without overwrite */
251 				.tx_buf = TX(0),
252 				.rx_buf = RX(0),
253 			},
254 		},
255 	},
256 	{
257 		.description	= "two tx+rx transfers - alter second",
258 		.fill_option	= FILL_COUNT_8,
259 		.iterate_len    = { ITERATE_MAX_LEN },
260 		.iterate_tx_align = ITERATE_ALIGN,
261 		.iterate_transfer_mask = BIT(1),
262 		.transfer_count = 2,
263 		.transfers		= {
264 			{
265 				.len = 1,
266 				.tx_buf = TX(0),
267 				.rx_buf = RX(0),
268 			},
269 			{
270 				/* making sure we align without overwrite */
271 				.tx_buf = TX(1024),
272 				.rx_buf = RX(1024),
273 			},
274 		},
275 	},
276 
277 	{ /* end of tests sequence */ }
278 };
279 
280 static int spi_loopback_test_probe(struct spi_device *spi)
281 {
282 	int ret;
283 
284 	dev_info(&spi->dev, "Executing spi-loopback-tests\n");
285 
286 	ret = spi_test_run_tests(spi, spi_tests);
287 
288 	dev_info(&spi->dev, "Finished spi-loopback-tests with return: %i\n",
289 		 ret);
290 
291 	return ret;
292 }
293 
294 /* non const match table to permit to change via a module parameter */
295 static struct of_device_id spi_loopback_test_of_match[] = {
296 	{ .compatible	= "linux,spi-loopback-test", },
297 	{ }
298 };
299 
300 /* allow to override the compatible string via a module_parameter */
301 module_param_string(compatible, spi_loopback_test_of_match[0].compatible,
302 		    sizeof(spi_loopback_test_of_match[0].compatible),
303 		    0000);
304 
305 MODULE_DEVICE_TABLE(of, spi_loopback_test_of_match);
306 
307 static struct spi_driver spi_loopback_test_driver = {
308 	.driver = {
309 		.name = "spi-loopback-test",
310 		.owner = THIS_MODULE,
311 		.of_match_table = spi_loopback_test_of_match,
312 	},
313 	.probe = spi_loopback_test_probe,
314 };
315 
316 module_spi_driver(spi_loopback_test_driver);
317 
318 MODULE_AUTHOR("Martin Sperl <[email protected]>");
319 MODULE_DESCRIPTION("test spi_driver to check core functionality");
320 MODULE_LICENSE("GPL");
321 
322 /*-------------------------------------------------------------------------*/
323 
324 /* spi_test implementation */
325 
326 #define RANGE_CHECK(ptr, plen, start, slen) \
327 	((ptr >= start) && (ptr + plen <= start + slen))
328 
329 /* we allocate one page more, to allow for offsets */
330 #define SPI_TEST_MAX_SIZE_PLUS (SPI_TEST_MAX_SIZE + PAGE_SIZE)
331 
332 static void spi_test_print_hex_dump(char *pre, const void *ptr, size_t len)
333 {
334 	/* limit the hex_dump */
335 	if (len < 1024) {
336 		print_hex_dump(KERN_INFO, pre,
337 			       DUMP_PREFIX_OFFSET, 16, 1,
338 			       ptr, len, 0);
339 		return;
340 	}
341 	/* print head */
342 	print_hex_dump(KERN_INFO, pre,
343 		       DUMP_PREFIX_OFFSET, 16, 1,
344 		       ptr, 512, 0);
345 	/* print tail */
346 	pr_info("%s truncated - continuing at offset %04zx\n",
347 		pre, len - 512);
348 	print_hex_dump(KERN_INFO, pre,
349 		       DUMP_PREFIX_OFFSET, 16, 1,
350 		       ptr + (len - 512), 512, 0);
351 }
352 
353 static void spi_test_dump_message(struct spi_device *spi,
354 				  struct spi_message *msg,
355 				  bool dump_data)
356 {
357 	struct spi_transfer *xfer;
358 	int i;
359 	u8 b;
360 
361 	dev_info(&spi->dev, "  spi_msg@%pK\n", msg);
362 	if (msg->status)
363 		dev_info(&spi->dev, "    status:        %i\n",
364 			 msg->status);
365 	dev_info(&spi->dev, "    frame_length:  %i\n",
366 		 msg->frame_length);
367 	dev_info(&spi->dev, "    actual_length: %i\n",
368 		 msg->actual_length);
369 
370 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
371 		dev_info(&spi->dev, "    spi_transfer@%pK\n", xfer);
372 		dev_info(&spi->dev, "      len:    %i\n", xfer->len);
373 		dev_info(&spi->dev, "      tx_buf: %pK\n", xfer->tx_buf);
374 		if (dump_data && xfer->tx_buf)
375 			spi_test_print_hex_dump("          TX: ",
376 						xfer->tx_buf,
377 						xfer->len);
378 
379 		dev_info(&spi->dev, "      rx_buf: %pK\n", xfer->rx_buf);
380 		if (dump_data && xfer->rx_buf)
381 			spi_test_print_hex_dump("          RX: ",
382 						xfer->rx_buf,
383 						xfer->len);
384 		/* check for unwritten test pattern on rx_buf */
385 		if (xfer->rx_buf) {
386 			for (i = 0 ; i < xfer->len ; i++) {
387 				b = ((u8 *)xfer->rx_buf)[xfer->len - 1 - i];
388 				if (b != SPI_TEST_PATTERN_UNWRITTEN)
389 					break;
390 			}
391 			if (i)
392 				dev_info(&spi->dev,
393 					 "      rx_buf filled with %02x starts at offset: %i\n",
394 					 SPI_TEST_PATTERN_UNWRITTEN,
395 					 xfer->len - i);
396 		}
397 	}
398 }
399 
400 struct rx_ranges {
401 	struct list_head list;
402 	u8 *start;
403 	u8 *end;
404 };
405 
406 static int rx_ranges_cmp(void *priv, struct list_head *a, struct list_head *b)
407 {
408 	struct rx_ranges *rx_a = list_entry(a, struct rx_ranges, list);
409 	struct rx_ranges *rx_b = list_entry(b, struct rx_ranges, list);
410 
411 	if (rx_a->start > rx_b->start)
412 		return 1;
413 	if (rx_a->start < rx_b->start)
414 		return -1;
415 	return 0;
416 }
417 
418 static int spi_check_rx_ranges(struct spi_device *spi,
419 			       struct spi_message *msg,
420 			       void *rx)
421 {
422 	struct spi_transfer *xfer;
423 	struct rx_ranges ranges[SPI_TEST_MAX_TRANSFERS], *r;
424 	int i = 0;
425 	LIST_HEAD(ranges_list);
426 	u8 *addr;
427 	int ret = 0;
428 
429 	/* loop over all transfers to fill in the rx_ranges */
430 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
431 		/* if there is no rx, then no check is needed */
432 		if (!xfer->rx_buf)
433 			continue;
434 		/* fill in the rx_range */
435 		if (RANGE_CHECK(xfer->rx_buf, xfer->len,
436 				rx, SPI_TEST_MAX_SIZE_PLUS)) {
437 			ranges[i].start = xfer->rx_buf;
438 			ranges[i].end = xfer->rx_buf + xfer->len;
439 			list_add(&ranges[i].list, &ranges_list);
440 			i++;
441 		}
442 	}
443 
444 	/* if no ranges, then we can return and avoid the checks...*/
445 	if (!i)
446 		return 0;
447 
448 	/* sort the list */
449 	list_sort(NULL, &ranges_list, rx_ranges_cmp);
450 
451 	/* and iterate over all the rx addresses */
452 	for (addr = rx; addr < (u8 *)rx + SPI_TEST_MAX_SIZE_PLUS; addr++) {
453 		/* if we are the DO not write pattern,
454 		 * then continue with the loop...
455 		 */
456 		if (*addr == SPI_TEST_PATTERN_DO_NOT_WRITE)
457 			continue;
458 
459 		/* check if we are inside a range */
460 		list_for_each_entry(r, &ranges_list, list) {
461 			/* if so then set to end... */
462 			if ((addr >= r->start) && (addr < r->end))
463 				addr = r->end;
464 		}
465 		/* second test after a (hopefull) translation */
466 		if (*addr == SPI_TEST_PATTERN_DO_NOT_WRITE)
467 			continue;
468 
469 		/* if still not found then something has modified too much */
470 		/* we could list the "closest" transfer here... */
471 		dev_err(&spi->dev,
472 			"loopback strangeness - rx changed outside of allowed range at: %pK\n",
473 			addr);
474 		/* do not return, only set ret,
475 		 * so that we list all addresses
476 		 */
477 		ret = -ERANGE;
478 	}
479 
480 	return ret;
481 }
482 
483 static int spi_test_check_elapsed_time(struct spi_device *spi,
484 				       struct spi_test *test)
485 {
486 	int i;
487 	unsigned long long estimated_time = 0;
488 	unsigned long long delay_usecs = 0;
489 
490 	for (i = 0; i < test->transfer_count; i++) {
491 		struct spi_transfer *xfer = test->transfers + i;
492 		unsigned long long nbits = BITS_PER_BYTE * xfer->len;
493 
494 		delay_usecs += xfer->delay_usecs;
495 		if (!xfer->speed_hz)
496 			continue;
497 		estimated_time += div_u64(nbits * NSEC_PER_SEC, xfer->speed_hz);
498 	}
499 
500 	estimated_time += delay_usecs * NSEC_PER_USEC;
501 	if (test->elapsed_time < estimated_time) {
502 		dev_err(&spi->dev,
503 			"elapsed time %lld ns is shorter than minimam estimated time %lld ns\n",
504 			test->elapsed_time, estimated_time);
505 
506 		return -EINVAL;
507 	}
508 
509 	return 0;
510 }
511 
512 static int spi_test_check_loopback_result(struct spi_device *spi,
513 					  struct spi_message *msg,
514 					  void *tx, void *rx)
515 {
516 	struct spi_transfer *xfer;
517 	u8 rxb, txb;
518 	size_t i;
519 	int ret;
520 
521 	/* checks rx_buffer pattern are valid with loopback or without */
522 	ret = spi_check_rx_ranges(spi, msg, rx);
523 	if (ret)
524 		return ret;
525 
526 	/* if we run without loopback, then return now */
527 	if (!loopback)
528 		return 0;
529 
530 	/* if applicable to transfer check that rx_buf is equal to tx_buf */
531 	list_for_each_entry(xfer, &msg->transfers, transfer_list) {
532 		/* if there is no rx, then no check is needed */
533 		if (!xfer->len || !xfer->rx_buf)
534 			continue;
535 		/* so depending on tx_buf we need to handle things */
536 		if (xfer->tx_buf) {
537 			for (i = 0; i < xfer->len; i++) {
538 				txb = ((u8 *)xfer->tx_buf)[i];
539 				rxb = ((u8 *)xfer->rx_buf)[i];
540 				if (txb != rxb)
541 					goto mismatch_error;
542 			}
543 		} else {
544 			/* first byte received */
545 			txb = ((u8 *)xfer->rx_buf)[0];
546 			/* first byte may be 0 or xff */
547 			if (!((txb == 0) || (txb == 0xff))) {
548 				dev_err(&spi->dev,
549 					"loopback strangeness - we expect 0x00 or 0xff, but not 0x%02x\n",
550 					txb);
551 				return -EINVAL;
552 			}
553 			/* check that all bytes are identical */
554 			for (i = 1; i < xfer->len; i++) {
555 				rxb = ((u8 *)xfer->rx_buf)[i];
556 				if (rxb != txb)
557 					goto mismatch_error;
558 			}
559 		}
560 	}
561 
562 	return 0;
563 
564 mismatch_error:
565 	dev_err(&spi->dev,
566 		"loopback strangeness - transfer mismatch on byte %04zx - expected 0x%02x, but got 0x%02x\n",
567 		i, txb, rxb);
568 
569 	return -EINVAL;
570 }
571 
572 static int spi_test_translate(struct spi_device *spi,
573 			      void **ptr, size_t len,
574 			      void *tx, void *rx)
575 {
576 	size_t off;
577 
578 	/* return on null */
579 	if (!*ptr)
580 		return 0;
581 
582 	/* in the MAX_SIZE_HALF case modify the pointer */
583 	if (((size_t)*ptr) & SPI_TEST_MAX_SIZE_HALF)
584 		/* move the pointer to the correct range */
585 		*ptr += (SPI_TEST_MAX_SIZE_PLUS / 2) -
586 			SPI_TEST_MAX_SIZE_HALF;
587 
588 	/* RX range
589 	 * - we check against MAX_SIZE_PLUS to allow for automated alignment
590 	 */
591 	if (RANGE_CHECK(*ptr, len,  RX(0), SPI_TEST_MAX_SIZE_PLUS)) {
592 		off = *ptr - RX(0);
593 		*ptr = rx + off;
594 
595 		return 0;
596 	}
597 
598 	/* TX range */
599 	if (RANGE_CHECK(*ptr, len,  TX(0), SPI_TEST_MAX_SIZE_PLUS)) {
600 		off = *ptr - TX(0);
601 		*ptr = tx + off;
602 
603 		return 0;
604 	}
605 
606 	dev_err(&spi->dev,
607 		"PointerRange [%pK:%pK[ not in range [%pK:%pK[ or [%pK:%pK[\n",
608 		*ptr, *ptr + len,
609 		RX(0), RX(SPI_TEST_MAX_SIZE),
610 		TX(0), TX(SPI_TEST_MAX_SIZE));
611 
612 	return -EINVAL;
613 }
614 
615 static int spi_test_fill_pattern(struct spi_device *spi,
616 				 struct spi_test *test)
617 {
618 	struct spi_transfer *xfers = test->transfers;
619 	u8 *tx_buf;
620 	size_t count = 0;
621 	int i, j;
622 
623 #ifdef __BIG_ENDIAN
624 #define GET_VALUE_BYTE(value, index, bytes) \
625 	(value >> (8 * (bytes - 1 - count % bytes)))
626 #else
627 #define GET_VALUE_BYTE(value, index, bytes) \
628 	(value >> (8 * (count % bytes)))
629 #endif
630 
631 	/* fill all transfers with the pattern requested */
632 	for (i = 0; i < test->transfer_count; i++) {
633 		/* fill rx_buf with SPI_TEST_PATTERN_UNWRITTEN */
634 		if (xfers[i].rx_buf)
635 			memset(xfers[i].rx_buf, SPI_TEST_PATTERN_UNWRITTEN,
636 			       xfers[i].len);
637 		/* if tx_buf is NULL then skip */
638 		tx_buf = (u8 *)xfers[i].tx_buf;
639 		if (!tx_buf)
640 			continue;
641 		/* modify all the transfers */
642 		for (j = 0; j < xfers[i].len; j++, tx_buf++, count++) {
643 			/* fill tx */
644 			switch (test->fill_option) {
645 			case FILL_MEMSET_8:
646 				*tx_buf = test->fill_pattern;
647 				break;
648 			case FILL_MEMSET_16:
649 				*tx_buf = GET_VALUE_BYTE(test->fill_pattern,
650 							 count, 2);
651 				break;
652 			case FILL_MEMSET_24:
653 				*tx_buf = GET_VALUE_BYTE(test->fill_pattern,
654 							 count, 3);
655 				break;
656 			case FILL_MEMSET_32:
657 				*tx_buf = GET_VALUE_BYTE(test->fill_pattern,
658 							 count, 4);
659 				break;
660 			case FILL_COUNT_8:
661 				*tx_buf = count;
662 				break;
663 			case FILL_COUNT_16:
664 				*tx_buf = GET_VALUE_BYTE(count, count, 2);
665 				break;
666 			case FILL_COUNT_24:
667 				*tx_buf = GET_VALUE_BYTE(count, count, 3);
668 				break;
669 			case FILL_COUNT_32:
670 				*tx_buf = GET_VALUE_BYTE(count, count, 4);
671 				break;
672 			case FILL_TRANSFER_BYTE_8:
673 				*tx_buf = j;
674 				break;
675 			case FILL_TRANSFER_BYTE_16:
676 				*tx_buf = GET_VALUE_BYTE(j, j, 2);
677 				break;
678 			case FILL_TRANSFER_BYTE_24:
679 				*tx_buf = GET_VALUE_BYTE(j, j, 3);
680 				break;
681 			case FILL_TRANSFER_BYTE_32:
682 				*tx_buf = GET_VALUE_BYTE(j, j, 4);
683 				break;
684 			case FILL_TRANSFER_NUM:
685 				*tx_buf = i;
686 				break;
687 			default:
688 				dev_err(&spi->dev,
689 					"unsupported fill_option: %i\n",
690 					test->fill_option);
691 				return -EINVAL;
692 			}
693 		}
694 	}
695 
696 	return 0;
697 }
698 
699 static int _spi_test_run_iter(struct spi_device *spi,
700 			      struct spi_test *test,
701 			      void *tx, void *rx)
702 {
703 	struct spi_message *msg = &test->msg;
704 	struct spi_transfer *x;
705 	int i, ret;
706 
707 	/* initialize message - zero-filled via static initialization */
708 	spi_message_init_no_memset(msg);
709 
710 	/* fill rx with the DO_NOT_WRITE pattern */
711 	memset(rx, SPI_TEST_PATTERN_DO_NOT_WRITE, SPI_TEST_MAX_SIZE_PLUS);
712 
713 	/* add the individual transfers */
714 	for (i = 0; i < test->transfer_count; i++) {
715 		x = &test->transfers[i];
716 
717 		/* patch the values of tx_buf */
718 		ret = spi_test_translate(spi, (void **)&x->tx_buf, x->len,
719 					 (void *)tx, rx);
720 		if (ret)
721 			return ret;
722 
723 		/* patch the values of rx_buf */
724 		ret = spi_test_translate(spi, &x->rx_buf, x->len,
725 					 (void *)tx, rx);
726 		if (ret)
727 			return ret;
728 
729 		/* and add it to the list */
730 		spi_message_add_tail(x, msg);
731 	}
732 
733 	/* fill in the transfer buffers with pattern */
734 	ret = spi_test_fill_pattern(spi, test);
735 	if (ret)
736 		return ret;
737 
738 	/* and execute */
739 	if (test->execute_msg)
740 		ret = test->execute_msg(spi, test, tx, rx);
741 	else
742 		ret = spi_test_execute_msg(spi, test, tx, rx);
743 
744 	/* handle result */
745 	if (ret == test->expected_return)
746 		return 0;
747 
748 	dev_err(&spi->dev,
749 		"test failed - test returned %i, but we expect %i\n",
750 		ret, test->expected_return);
751 
752 	if (ret)
753 		return ret;
754 
755 	/* if it is 0, as we expected something else,
756 	 * then return something special
757 	 */
758 	return -EFAULT;
759 }
760 
761 static int spi_test_run_iter(struct spi_device *spi,
762 			     const struct spi_test *testtemplate,
763 			     void *tx, void *rx,
764 			     size_t len,
765 			     size_t tx_off,
766 			     size_t rx_off
767 	)
768 {
769 	struct spi_test test;
770 	int i, tx_count, rx_count;
771 
772 	/* copy the test template to test */
773 	memcpy(&test, testtemplate, sizeof(test));
774 
775 	/* if iterate_transfer_mask is not set,
776 	 * then set it to first transfer only
777 	 */
778 	if (!(test.iterate_transfer_mask & (BIT(test.transfer_count) - 1)))
779 		test.iterate_transfer_mask = 1;
780 
781 	/* count number of transfers with tx/rx_buf != NULL */
782 	rx_count = tx_count = 0;
783 	for (i = 0; i < test.transfer_count; i++) {
784 		if (test.transfers[i].tx_buf)
785 			tx_count++;
786 		if (test.transfers[i].rx_buf)
787 			rx_count++;
788 	}
789 
790 	/* in some iteration cases warn and exit early,
791 	 * as there is nothing to do, that has not been tested already...
792 	 */
793 	if (tx_off && (!tx_count)) {
794 		dev_warn_once(&spi->dev,
795 			      "%s: iterate_tx_off configured with tx_buf==NULL - ignoring\n",
796 			      test.description);
797 		return 0;
798 	}
799 	if (rx_off && (!rx_count)) {
800 		dev_warn_once(&spi->dev,
801 			      "%s: iterate_rx_off configured with rx_buf==NULL - ignoring\n",
802 			      test.description);
803 		return 0;
804 	}
805 
806 	/* write out info */
807 	if (!(len || tx_off || rx_off)) {
808 		dev_info(&spi->dev, "Running test %s\n", test.description);
809 	} else {
810 		dev_info(&spi->dev,
811 			 "  with iteration values: len = %zu, tx_off = %zu, rx_off = %zu\n",
812 			 len, tx_off, rx_off);
813 	}
814 
815 	/* update in the values from iteration values */
816 	for (i = 0; i < test.transfer_count; i++) {
817 		/* only when bit in transfer mask is set */
818 		if (!(test.iterate_transfer_mask & BIT(i)))
819 			continue;
820 		test.transfers[i].len = len;
821 		if (test.transfers[i].tx_buf)
822 			test.transfers[i].tx_buf += tx_off;
823 		if (test.transfers[i].tx_buf)
824 			test.transfers[i].rx_buf += rx_off;
825 	}
826 
827 	/* and execute */
828 	return _spi_test_run_iter(spi, &test, tx, rx);
829 }
830 
831 /**
832  * spi_test_execute_msg - default implementation to run a test
833  *
834  * spi: @spi_device on which to run the @spi_message
835  * test: the test to execute, which already contains @msg
836  * tx:   the tx buffer allocated for the test sequence
837  * rx:   the rx buffer allocated for the test sequence
838  *
839  * Returns: error code of spi_sync as well as basic error checking
840  */
841 int spi_test_execute_msg(struct spi_device *spi, struct spi_test *test,
842 			 void *tx, void *rx)
843 {
844 	struct spi_message *msg = &test->msg;
845 	int ret = 0;
846 	int i;
847 
848 	/* only if we do not simulate */
849 	if (!simulate_only) {
850 		ktime_t start;
851 
852 		/* dump the complete message before and after the transfer */
853 		if (dump_messages == 3)
854 			spi_test_dump_message(spi, msg, true);
855 
856 		start = ktime_get();
857 		/* run spi message */
858 		ret = spi_sync(spi, msg);
859 		test->elapsed_time = ktime_to_ns(ktime_sub(ktime_get(), start));
860 		if (ret == -ETIMEDOUT) {
861 			dev_info(&spi->dev,
862 				 "spi-message timed out - reruning...\n");
863 			/* rerun after a few explicit schedules */
864 			for (i = 0; i < 16; i++)
865 				schedule();
866 			ret = spi_sync(spi, msg);
867 		}
868 		if (ret) {
869 			dev_err(&spi->dev,
870 				"Failed to execute spi_message: %i\n",
871 				ret);
872 			goto exit;
873 		}
874 
875 		/* do some extra error checks */
876 		if (msg->frame_length != msg->actual_length) {
877 			dev_err(&spi->dev,
878 				"actual length differs from expected\n");
879 			ret = -EIO;
880 			goto exit;
881 		}
882 
883 		/* run rx-buffer tests */
884 		ret = spi_test_check_loopback_result(spi, msg, tx, rx);
885 		if (ret)
886 			goto exit;
887 
888 		ret = spi_test_check_elapsed_time(spi, test);
889 	}
890 
891 	/* if requested or on error dump message (including data) */
892 exit:
893 	if (dump_messages || ret)
894 		spi_test_dump_message(spi, msg,
895 				      (dump_messages >= 2) || (ret));
896 
897 	return ret;
898 }
899 EXPORT_SYMBOL_GPL(spi_test_execute_msg);
900 
901 /**
902  * spi_test_run_test - run an individual spi_test
903  *                     including all the relevant iterations on:
904  *                     length and buffer alignment
905  *
906  * spi:  the spi_device to send the messages to
907  * test: the test which we need to execute
908  * tx:   the tx buffer allocated for the test sequence
909  * rx:   the rx buffer allocated for the test sequence
910  *
911  * Returns: status code of spi_sync or other failures
912  */
913 
914 int spi_test_run_test(struct spi_device *spi, const struct spi_test *test,
915 		      void *tx, void *rx)
916 {
917 	int idx_len;
918 	size_t len;
919 	size_t tx_align, rx_align;
920 	int ret;
921 
922 	/* test for transfer limits */
923 	if (test->transfer_count >= SPI_TEST_MAX_TRANSFERS) {
924 		dev_err(&spi->dev,
925 			"%s: Exceeded max number of transfers with %i\n",
926 			test->description, test->transfer_count);
927 		return -E2BIG;
928 	}
929 
930 	/* setting up some values in spi_message
931 	 * based on some settings in spi_master
932 	 * some of this can also get done in the run() method
933 	 */
934 
935 	/* iterate over all the iterable values using macros
936 	 * (to make it a bit more readable...
937 	 */
938 #define FOR_EACH_ALIGNMENT(var)						\
939 	for (var = 0;							\
940 	    var < (test->iterate_##var ?				\
941 			(spi->master->dma_alignment ?			\
942 			 spi->master->dma_alignment :			\
943 			 test->iterate_##var) :				\
944 			1);						\
945 	    var++)
946 
947 	for (idx_len = 0; idx_len < SPI_TEST_MAX_ITERATE &&
948 	     (len = test->iterate_len[idx_len]) != -1; idx_len++) {
949 		FOR_EACH_ALIGNMENT(tx_align) {
950 			FOR_EACH_ALIGNMENT(rx_align) {
951 				/* and run the iteration */
952 				ret = spi_test_run_iter(spi, test,
953 							tx, rx,
954 							len,
955 							tx_align,
956 							rx_align);
957 				if (ret)
958 					return ret;
959 			}
960 		}
961 	}
962 
963 	return 0;
964 }
965 EXPORT_SYMBOL_GPL(spi_test_run_test);
966 
967 /**
968  * spi_test_run_tests - run an array of spi_messages tests
969  * @spi: the spi device on which to run the tests
970  * @tests: NULL-terminated array of @spi_test
971  *
972  * Returns: status errors as per @spi_test_run_test()
973  */
974 
975 int spi_test_run_tests(struct spi_device *spi,
976 		       struct spi_test *tests)
977 {
978 	char *rx = NULL, *tx = NULL;
979 	int ret = 0, count = 0;
980 	struct spi_test *test;
981 
982 	/* allocate rx/tx buffers of 128kB size without devm
983 	 * in the hope that is on a page boundary
984 	 */
985 	rx = kzalloc(SPI_TEST_MAX_SIZE_PLUS, GFP_KERNEL);
986 	if (!rx) {
987 		ret = -ENOMEM;
988 		goto out;
989 	}
990 
991 	tx = kzalloc(SPI_TEST_MAX_SIZE_PLUS, GFP_KERNEL);
992 	if (!tx) {
993 		ret = -ENOMEM;
994 		goto out;
995 	}
996 
997 	/* now run the individual tests in the table */
998 	for (test = tests, count = 0; test->description[0];
999 	     test++, count++) {
1000 		/* only run test if requested */
1001 		if ((run_only_test > -1) && (count != run_only_test))
1002 			continue;
1003 		/* run custom implementation */
1004 		if (test->run_test)
1005 			ret = test->run_test(spi, test, tx, rx);
1006 		else
1007 			ret = spi_test_run_test(spi, test, tx, rx);
1008 		if (ret)
1009 			goto out;
1010 		/* add some delays so that we can easily
1011 		 * detect the individual tests when using a logic analyzer
1012 		 * we also add scheduling to avoid potential spi_timeouts...
1013 		 */
1014 		mdelay(100);
1015 		schedule();
1016 	}
1017 
1018 out:
1019 	kfree(rx);
1020 	kfree(tx);
1021 	return ret;
1022 }
1023 EXPORT_SYMBOL_GPL(spi_test_run_tests);
1024