xref: /aosp_15_r20/external/coreboot/src/drivers/spi/bitbang.c (revision b9411a12aaaa7e1e6a6fb7c5e057f44ee179a49c)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 
3 #include <console/console.h>
4 #include <delay.h>
5 #include <spi_bitbang.h>
6 #include <types.h>
7 
8 /* Set to 1 to dump all SPI transfers to the UART. */
9 #define TRACE		0
10 /*
11  * In theory, this should work fine with 0 delay since the bus is fully clocked
12  * by the master and the slave just needs to follow clock transitions whenever
13  * they happen. We're not going to be "too fast" by bit-banging anyway. However,
14  * if something doesn't work right, try increasing this value to slow it down.
15  */
16 #define HALF_CLOCK_US	0
17 
spi_bitbang_claim_bus(const struct spi_bitbang_ops * ops)18 int spi_bitbang_claim_bus(const struct spi_bitbang_ops *ops)
19 {
20 	ops->set_cs(ops, 0);
21 	return 0;
22 }
23 
spi_bitbang_release_bus(const struct spi_bitbang_ops * ops)24 void spi_bitbang_release_bus(const struct spi_bitbang_ops *ops)
25 {
26 	ops->set_cs(ops, 1);
27 }
28 
29 /* Implements a CPOL=0, CPH=0, MSB first 8-bit controller. */
spi_bitbang_xfer(const struct spi_bitbang_ops * ops,const void * dout,size_t bytes_out,void * din,size_t bytes_in)30 int spi_bitbang_xfer(const struct spi_bitbang_ops *ops, const void *dout,
31 		     size_t bytes_out, void *din, size_t bytes_in)
32 {
33 	if (TRACE) {
34 		if (bytes_in && bytes_out)
35 			printk(BIOS_SPEW, "!");
36 		else if (bytes_in)
37 			printk(BIOS_SPEW, "<");
38 		else if (bytes_out)
39 			printk(BIOS_SPEW, ">");
40 	}
41 
42 	while (bytes_out || bytes_in) {
43 		int i;
44 		uint8_t in_byte = 0, out_byte = 0;
45 		if (bytes_out) {
46 			out_byte = *(const uint8_t *)dout++;
47 			bytes_out--;
48 			if (TRACE)
49 				printk(BIOS_SPEW, "%02x", out_byte);
50 		}
51 		for (i = 7; i >= 0; i--) {
52 			ops->set_mosi(ops, !!(out_byte & (1 << i)));
53 			if (HALF_CLOCK_US)
54 				udelay(HALF_CLOCK_US);
55 			ops->set_clk(ops, 1);
56 			in_byte |= !!ops->get_miso(ops) << i;
57 			if (HALF_CLOCK_US)
58 				udelay(HALF_CLOCK_US);
59 			ops->set_clk(ops, 0);
60 		}
61 		if (bytes_in) {
62 			*(uint8_t *)din++ = in_byte;
63 			bytes_in--;
64 			if (TRACE)
65 				printk(BIOS_SPEW, "%02x", in_byte);
66 		}
67 	}
68 
69 	if (TRACE)
70 		printk(BIOS_SPEW, "\n");
71 	return 0;
72 }
73