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 /*-----------------------------------------------------------------------
46 struct spi_slave *spi_setup_slave(unsigned int bus, unsigned int cs,
47 unsigned int max_hz, unsigned int mode)
49 struct soft_spi_slave *ss;
51 if (!spi_cs_is_valid(bus, cs))
54 ss = spi_alloc_slave(struct soft_spi_slave, bus, cs);
60 /* TODO: Use max_hz to limit the SCK rate */
65 void spi_free_slave(struct spi_slave *slave)
67 struct soft_spi_slave *ss = to_soft_spi(slave);
72 int spi_claim_bus(struct spi_slave *slave)
74 #ifdef CONFIG_SYS_IMMR
75 volatile immap_t *immr = (immap_t *)CONFIG_SYS_IMMR;
77 struct soft_spi_slave *ss = to_soft_spi(slave);
80 * Make sure the SPI clock is in idle state as defined for
83 if (ss->mode & SPI_CPOL)
91 void spi_release_bus(struct spi_slave *slave)
96 /*-----------------------------------------------------------------------
99 * This writes "bitlen" bits out the SPI MOSI port and simultaneously clocks
100 * "bitlen" bits in the SPI MISO port. That's just the way SPI works.
102 * The source of the outgoing bits is the "dout" parameter and the
103 * destination of the input bits is the "din" parameter. Note that "dout"
104 * and "din" can point to the same memory location, in which case the
105 * input data overwrites the output data (since both are buffered by
106 * temporary variables, this is OK).
108 int spi_xfer(struct spi_slave *slave, unsigned int bitlen,
109 const void *dout, void *din, unsigned long flags)
111 #ifdef CONFIG_SYS_IMMR
112 volatile immap_t *immr = (immap_t *)CONFIG_SYS_IMMR;
114 struct soft_spi_slave *ss = to_soft_spi(slave);
117 const u8 *txd = dout;
119 int cpol = ss->mode & SPI_CPOL;
120 int cpha = ss->mode & SPI_CPHA;
123 PRINTD("spi_xfer: slave %u:%u dout %08X din %08X bitlen %u\n",
124 slave->bus, slave->cs, *(uint *)txd, *(uint *)rxd, bitlen);
126 if (flags & SPI_XFER_BEGIN)
127 spi_cs_activate(slave);
129 for(j = 0; j < bitlen; j++) {
131 * Check if it is time to work on a new byte.
147 SPI_SDA(tmpdout & 0x80);
161 * If the number of bits isn't a multiple of 8, shift the last
162 * bits over to left-justify them. Then store the last byte
166 if ((bitlen % 8) != 0)
167 tmpdin <<= 8 - (bitlen % 8);
171 if (flags & SPI_XFER_END)
172 spi_cs_deactivate(slave);