3 * Albin Tonnerre, Free Electrons <albin.tonnerre@free-electrons.com>
5 * SPDX-License-Identifier: GPL-2.0+
11 #define SPI_EEPROM_WREN 0x06
12 #define SPI_EEPROM_RDSR 0x05
13 #define SPI_EEPROM_READ 0x03
14 #define SPI_EEPROM_WRITE 0x02
16 #ifndef CONFIG_DEFAULT_SPI_BUS
17 #define CONFIG_DEFAULT_SPI_BUS 0
20 #ifndef CONFIG_DEFAULT_SPI_MODE
21 #define CONFIG_DEFAULT_SPI_MODE SPI_MODE_0
24 #ifndef CONFIG_SYS_SPI_WRITE_TOUT
25 #define CONFIG_SYS_SPI_WRITE_TOUT (5 * CONFIG_SYS_HZ)
28 ssize_t spi_read(uchar *addr, int alen, uchar *buffer, int len)
30 struct spi_slave *slave;
31 u8 cmd = SPI_EEPROM_READ;
33 slave = spi_setup_slave(CONFIG_DEFAULT_SPI_BUS, 1, 1000000,
34 CONFIG_DEFAULT_SPI_MODE);
41 if (spi_xfer(slave, 8, &cmd, NULL, SPI_XFER_BEGIN))
45 * if alen == 3, addr[0] is the block number, we never use it here.
46 * All we need are the lower 16 bits.
51 /* address, and data */
52 if (spi_xfer(slave, 16, addr, NULL, 0))
54 if (spi_xfer(slave, 8 * len, NULL, buffer, SPI_XFER_END))
57 spi_release_bus(slave);
58 spi_free_slave(slave);
62 ssize_t spi_write(uchar *addr, int alen, uchar *buffer, int len)
64 struct spi_slave *slave;
68 slave = spi_setup_slave(CONFIG_DEFAULT_SPI_BUS, 1, 1000000,
69 CONFIG_DEFAULT_SPI_MODE);
75 buf[0] = SPI_EEPROM_WREN;
76 if (spi_xfer(slave, 8, buf, NULL, SPI_XFER_BEGIN | SPI_XFER_END))
79 buf[0] = SPI_EEPROM_WRITE;
81 /* As for reading, drop addr[0] if alen is 3 */
87 memcpy(buf + 1, addr, alen);
88 /* command + addr, then data */
89 if (spi_xfer(slave, 24, buf, NULL, SPI_XFER_BEGIN))
91 if (spi_xfer(slave, len * 8, buffer, NULL, SPI_XFER_END))
96 buf[0] = SPI_EEPROM_RDSR;
98 spi_xfer(slave, 16, buf, buf, SPI_XFER_BEGIN | SPI_XFER_END);
103 } while (get_timer(start) < CONFIG_SYS_SPI_WRITE_TOUT);
106 printf("*** spi_write: Timeout while writing!\n");
108 spi_release_bus(slave);
109 spi_free_slave(slave);