Newer
Older
uwuboot / source / arm9 / spiflash.c
@profi200 profi200 on 5 Feb 2017 1 KB Moved reg defines back from io.h.
#include "mem_map.h"
#include "types.h"
#include "arm9/spiflash.h"


#define SPI_REGS_BUS2_BASE  (IO_MEM_ARM9_ARM11 + 0x60000)
#define REG_SPI_BUS2_CNT    *((vu16*)(SPI_REGS_BUS2_BASE + 0x00))
#define REG_SPI_BUS2_DATA   *((vu8* )(SPI_REGS_BUS2_BASE + 0x02))



static void spi_busy_wait()
{
    while(REG_SPI_BUS2_CNT & 0x80);
}

static void spi_put_byte(u8 data)
{
    REG_SPI_BUS2_DATA = data;
    spi_busy_wait();
}

static u8 spi_receive_byte()
{
    // clock out a dummy byte
    REG_SPI_BUS2_DATA = 0x00;
    spi_busy_wait();
    return REG_SPI_BUS2_DATA;
}

// select spiflash if select=true, deselect otherwise 
static void spiflash_select(bool select)
{
    // select device 1, enable SPI bus
    REG_SPI_BUS2_CNT = 0x8100 | (select << 11);
}

bool spiflash_get_status()
{
    u8 resp;

    spi_busy_wait();
    spiflash_select(1);
    spi_put_byte(SPIFLASH_CMD_RDSR);
    spiflash_select(0);
    resp = spi_receive_byte();

    if(resp & 1) return false;
    return true;
}

void spiflash_read(u32 offset, u32 size, u8 *buf)
{
	spi_busy_wait();
	spiflash_select(1);
	spi_put_byte(SPIFLASH_CMD_READ);
	
	// write addr (24-bit, msb first)	
	for(int i=0; i<3; i++)
	{
		offset <<= 8;
		spi_put_byte((offset >> 24) & 0xFF);
	}
	
	// read bytes
	for(u32 i=0; i<size; i++)
		buf[i] = spi_receive_byte();
	
	// end of read
	spiflash_select(0);
	spi_receive_byte();
}