1 // SPDX-License-Identifier: GPL-2.0+
4 * Gerald Van Baren, Custom IDEAS, vanbaren@cideas.com.
6 * Influenced by code from:
7 * Wolfgang Denk, DENX Software Engineering, wd@denx.de.
15 /*-----------------------------------------------------------------------
20 #define PRINTD(fmt,args...) printf (fmt ,##args)
22 #define PRINTD(fmt,args...)
25 struct soft_spi_slave {
26 struct spi_slave slave;
30 static inline struct soft_spi_slave *to_soft_spi(struct spi_slave *slave)
32 return container_of(slave, struct soft_spi_slave, slave);
35 /*=====================================================================*/
36 /* Public Functions */
37 /*=====================================================================*/
39 struct spi_slave *spi_setup_slave(unsigned int bus, unsigned int cs,
40 unsigned int max_hz, unsigned int mode)
42 struct soft_spi_slave *ss;
44 if (!spi_cs_is_valid(bus, cs))
47 ss = spi_alloc_slave(struct soft_spi_slave, bus, cs);
53 /* TODO: Use max_hz to limit the SCK rate */
58 void spi_free_slave(struct spi_slave *slave)
60 struct soft_spi_slave *ss = to_soft_spi(slave);
65 int spi_claim_bus(struct spi_slave *slave)
67 #ifdef CONFIG_SYS_IMMR
68 volatile immap_t *immr = (immap_t *)CONFIG_SYS_IMMR;
70 struct soft_spi_slave *ss = to_soft_spi(slave);
73 * Make sure the SPI clock is in idle state as defined for
76 if (ss->mode & SPI_CPOL)
84 void spi_release_bus(struct spi_slave *slave)
89 /*-----------------------------------------------------------------------
92 * This writes "bitlen" bits out the SPI MOSI port and simultaneously clocks
93 * "bitlen" bits in the SPI MISO port. That's just the way SPI works.
95 * The source of the outgoing bits is the "dout" parameter and the
96 * destination of the input bits is the "din" parameter. Note that "dout"
97 * and "din" can point to the same memory location, in which case the
98 * input data overwrites the output data (since both are buffered by
99 * temporary variables, this is OK).
101 int spi_xfer(struct spi_slave *slave, unsigned int bitlen,
102 const void *dout, void *din, unsigned long flags)
104 #ifdef CONFIG_SYS_IMMR
105 volatile immap_t *immr = (immap_t *)CONFIG_SYS_IMMR;
107 struct soft_spi_slave *ss = to_soft_spi(slave);
110 const u8 *txd = dout;
112 int cpol = ss->mode & SPI_CPOL;
113 int cpha = ss->mode & SPI_CPHA;
116 PRINTD("spi_xfer: slave %u:%u dout %08X din %08X bitlen %u\n",
117 slave->bus, slave->cs, *(uint *)txd, *(uint *)rxd, bitlen);
119 if (flags & SPI_XFER_BEGIN)
120 spi_cs_activate(slave);
122 for(j = 0; j < bitlen; j++) {
124 * Check if it is time to work on a new byte.
140 SPI_SDA(tmpdout & 0x80);
154 * If the number of bits isn't a multiple of 8, shift the last
155 * bits over to left-justify them. Then store the last byte
159 if ((bitlen % 8) != 0)
160 tmpdin <<= 8 - (bitlen % 8);
164 if (flags & SPI_XFER_END)
165 spi_cs_deactivate(slave);