00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 FILE_LICENCE ( GPL2_OR_LATER );
00020
00021 #include <stddef.h>
00022 #include <errno.h>
00023 #include <unistd.h>
00024 #include <gpxe/spi.h>
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045 static inline unsigned int spi_command ( unsigned int command,
00046 unsigned int address,
00047 int munge_address ) {
00048 return ( command | ( ( ( address >> 8 ) & munge_address ) << 3 ) );
00049 }
00050
00051
00052
00053
00054
00055
00056
00057 static int spi_wait ( struct spi_device *device ) {
00058 struct spi_bus *bus = device->bus;
00059 uint8_t status;
00060 int i;
00061 int rc;
00062
00063 for ( i = 0 ; i < 50 ; i++ ) {
00064 udelay ( 20 );
00065 if ( ( rc = bus->rw ( bus, device, SPI_RDSR, -1, NULL,
00066 &status, sizeof ( status ) ) ) != 0 )
00067 return rc;
00068 if ( ! ( status & SPI_STATUS_NRDY ) )
00069 return 0;
00070 }
00071 DBG ( "SPI %p timed out\n", device );
00072 return -ETIMEDOUT;
00073 }
00074
00075
00076
00077
00078
00079
00080
00081
00082
00083
00084 int spi_read ( struct nvs_device *nvs, unsigned int address,
00085 void *data, size_t len ) {
00086 struct spi_device *device = nvs_to_spi ( nvs );
00087 struct spi_bus *bus = device->bus;
00088 unsigned int command = spi_command ( SPI_READ, address,
00089 device->munge_address );
00090 int rc;
00091
00092 DBG ( "SPI %p reading %zd bytes from %#04x\n", device, len, address );
00093 if ( ( rc = bus->rw ( bus, device, command, address,
00094 NULL, data, len ) ) != 0 ) {
00095 DBG ( "SPI %p failed to read data from device\n", device );
00096 return rc;
00097 }
00098
00099 return 0;
00100 }
00101
00102
00103
00104
00105
00106
00107
00108
00109
00110
00111 int spi_write ( struct nvs_device *nvs, unsigned int address,
00112 const void *data, size_t len ) {
00113 struct spi_device *device = nvs_to_spi ( nvs );
00114 struct spi_bus *bus = device->bus;
00115 unsigned int command = spi_command ( SPI_WRITE, address,
00116 device->munge_address );
00117 int rc;
00118
00119 DBG ( "SPI %p writing %zd bytes to %#04x\n", device, len, address );
00120
00121 if ( ( rc = bus->rw ( bus, device, SPI_WREN, -1,
00122 NULL, NULL, 0 ) ) != 0 ) {
00123 DBG ( "SPI %p failed to write-enable device\n", device );
00124 return rc;
00125 }
00126
00127 if ( ( rc = bus->rw ( bus, device, command, address,
00128 data, NULL, len ) ) != 0 ) {
00129 DBG ( "SPI %p failed to write data to device\n", device );
00130 return rc;
00131 }
00132
00133 if ( ( rc = spi_wait ( device ) ) != 0 ) {
00134 DBG ( "SPI %p failed to complete write operation\n", device );
00135 return rc;
00136 }
00137
00138 return 0;
00139 }
00140