///////////////////////////////////////////////////////////////////////////////////
// File     : sdc_driver.c
// Date     : 31/08/2012
// Author   : cesar fuguet
// Copyright (c) UPMC-LIP6
///////////////////////////////////////////////////////////////////////////////////

#include <boot_spi_driver.h>
#include <hal_kernel_types.h>
#include <hard_config.h>
#include <boot_utils.h>

#define SYSCLK_FREQ           (RESET_SYSTEM_CLK * 1000)
#define SDCARD_RESET_ITER_MAX 4

///////////////////////////////////////////////////////////////////////////////
//   Global variables
///////////////////////////////////////////////////////////////////////////////

__attribute__((section(".kdata")))
static struct boot_sdcard_dev sdcard;

__attribute__((section(".kdata")))
static struct boot_spi_dev*   spi;

///////////////////////////////////////////////////////////////////////////////
// This function enables SD Card select signal
///////////////////////////////////////////////////////////////////////////////
static void _sdc_enable()
{
    spi_ss_assert(sdcard.spi, sdcard.slave_id);
}

///////////////////////////////////////////////////////////////////////////////
// This function disables SD Card select signal
///////////////////////////////////////////////////////////////////////////////
static void _sdc_disable()
{
    spi_ss_deassert(sdcard.spi, sdcard.slave_id);
}

///////////////////////////////////////////////////////////////////////////////
// This function writes on the SPI tx register to generate SD card clock ticks
// - tick_count: number of ticks to generate (1 tick -> 8 clocks) 
///////////////////////////////////////////////////////////////////////////////
static void _sdc_gen_tick(unsigned int tick_count)
{
    register int i = 0;
    while(i++ < tick_count) spi_put_tx(sdcard.spi, 0xFF, 0);
}

///////////////////////////////////////////////////////////////////////////////
// This function changes the SD card access pointer position in terms of
// blocks
// - lba: number of logical block to move the pointer
///////////////////////////////////////////////////////////////////////////////
void _sdc_lseek(unsigned int lba)
{
    sdcard.access_pointer = sdcard.block_length * lba;
}

///////////////////////////////////////////////////////////////////////////////
// This function gets a byte from the SD card
///////////////////////////////////////////////////////////////////////////////
static unsigned char _sdc_receive_char()
{
    _sdc_gen_tick(1);

    return spi_get_rx(sdcard.spi, 0);
}

///////////////////////////////////////////////////////////////////////////////
// This function returns when a valid response from the SD card is received or
// a timeout has been triggered
// Returns the SD card response value
///////////////////////////////////////////////////////////////////////////////
static unsigned char _sdc_wait_response()
{
    unsigned char sdcard_rsp;
    register int  iter;

    iter       = 0;
    sdcard_rsp = _sdc_receive_char();
    while (
            (iter < SDCARD_COMMAND_TIMEOUT) &&
            !SDCARD_CHECK_R1_VALID(sdcard_rsp)
          )
    {
        sdcard_rsp = _sdc_receive_char();
        iter++;
    }

    return sdcard_rsp;
}

///////////////////////////////////////////////////////////////////////////////
// This function returns when a data block from the SD card is received (data
// block start marker received).
// It must be called after a read command
///////////////////////////////////////////////////////////////////////////////
static void _sdc_wait_data_block()
{
	while (_sdc_receive_char() != 0xFE);
}

///////////////////////////////////////////////////////////////////////////////
// This function sends a command to the SD card
// - index: CMD index
// - app: type of command
// - args: CMD arguments vector
// - crc7: CRC (7 bits) to send
///////////////////////////////////////////////////////////////////////////////
static int _sdc_send_command ( int      index,
                               int      app  ,
                               void *   args ,
                               unsigned crc7 )
{
    unsigned char sdcard_rsp;
    unsigned char * _args;

    _sdc_gen_tick(5);  

    if (app == SDCARD_ACMD)
    {
        spi_put_tx(sdcard.spi, 0x40 | 55         , 0 );// CMD and START bit
        spi_put_tx(sdcard.spi, 0x00              , 0 );// Argument[0]
        spi_put_tx(sdcard.spi, 0x00              , 0 );// Argument[1]
        spi_put_tx(sdcard.spi, 0x00              , 0 );// Argument[2]
        spi_put_tx(sdcard.spi, 0x00              , 0 );// Argument[3]
        spi_put_tx(sdcard.spi, 0x01 | (crc7 << 1), 0 );// END bit

        sdcard_rsp = _sdc_wait_response();
        if (SDCARD_CHECK_R1_ERROR(sdcard_rsp))
        {
            return sdcard_rsp;        
        }
    }

    _args = (unsigned char *) args;

    _sdc_gen_tick(1);  

    spi_put_tx(sdcard.spi, 0x40 | index      , 0 );
    spi_put_tx(sdcard.spi, _args[0]          , 0 );
    spi_put_tx(sdcard.spi, _args[1]          , 0 );
    spi_put_tx(sdcard.spi, _args[2]          , 0 );
    spi_put_tx(sdcard.spi, _args[3]          , 0 );
    spi_put_tx(sdcard.spi, 0x01 | (crc7 << 1), 0 );

    return _sdc_wait_response();
}

///////////////////////////////////////////////////////////////////////////////
// This function initializes the SD card (reset procedure)
// - channel: channel index (only channel 0 is supported)
// Returns 0 if success, other value if failure
///////////////////////////////////////////////////////////////////////////////
static int _sdc_open( unsigned int channel )
{
	unsigned char args[4];
	unsigned char sdcard_rsp;
	unsigned int  iter, ersp;

	sdcard.spi      = spi;
	sdcard.slave_id = channel;

	// supply SD card ramp up time (min 74 cycles)
	_sdc_gen_tick(10);

	// Assert slave select signal
	// Send CMD0 (Reset Command)
	// Deassert slave select signal
	_sdc_enable();

	args[0] = 0;
	args[1] = 0;
	args[2] = 0;
	args[3] = 0;
	sdcard_rsp = _sdc_send_command(0, SDCARD_CMD, args, 0x4A);

	if ( sdcard_rsp != 0x01 )
	{
		boot_puts("[BOOT SDC ERROR] card CMD0 failed\n");
		return sdcard_rsp;
	}

	_sdc_disable();

	// send CMD8. If card is pre-v2, It will reply with illegal command.
	// Otherwise we announce sdhc support.
	_sdc_enable();
	args[0] = 0;
	args[1] = 0;
	args[2] = 0x01;
	args[3] = 0x01;
	sdcard_rsp = _sdc_send_command(8, SDCARD_CMD, args, 0x63);
	if (!SDCARD_CHECK_R1_VALID(sdcard_rsp))
    {
		boot_puts("[BOOT SDC ERROR] card CMD8 failed\n");
		return sdcard_rsp;
	}
	if (!SDCARD_CHECK_R1_ERROR(sdcard_rsp))
    {
		// no error, command accepted. get whole reply
		ersp = _sdc_receive_char();
		ersp = (ersp << 8) | _sdc_receive_char();
		ersp = (ersp << 8) | _sdc_receive_char();
		ersp = (ersp << 8) | _sdc_receive_char();
		if ((ersp & 0xffff) != 0x0101) 
        {
			// voltage mismatch
			boot_puts("[BOOT SDC ERROR] card CMD8 mismatch\n");
			return sdcard_rsp;
		}
		boot_puts("[BOOT SDC WARNING] v2 or later ");
		sdcard.sdhc = 1;
	}
    else if ((sdcard_rsp & SDCARD_R1_ILLEGAL_CMD) == 0)
    {
		// other error
		boot_puts("[BOOT SDC ERROR] card CMD8 error\n");
		return sdcard_rsp;
	}
    else
    {
		sdcard.sdhc = 0;
	}
	_sdc_disable();

	// send CMD41, enabling the card
	_sdc_enable();
	args[0] = sdcard.sdhc ? 0x40: 0;
	args[1] = 0;
	args[2] = 0;
	args[3] = 0;

	iter = 0;
	while( iter++ < SDCARD_COMMAND_TIMEOUT )
	{
		sdcard_rsp = _sdc_send_command(41, SDCARD_ACMD, args, 0x00);
		if( sdcard_rsp == 0x01 )
		{
			continue;
		}

		break;
	}

	_sdc_disable();
	if (sdcard_rsp)
    {
		boot_puts("[BOOT SDC ERROR] ACMD41 failed\n");
		return sdcard_rsp;
	}
	if (sdcard.sdhc != 0)
    {
		// get the card capacity to see if it's really HC
		_sdc_enable();
		args[0] = sdcard.sdhc ? 0x40: 0;
		args[1] = 0;
		args[2] = 0;
		args[3] = 0;
        sdcard_rsp = _sdc_send_command(58, SDCARD_CMD, args, 0x00);
		if (sdcard_rsp)
        {
			boot_puts("[BOOT SDC ERROR] CMD58 failed\n");
			return sdcard_rsp;
		}
		ersp = _sdc_receive_char();
		ersp = (ersp << 8) | _sdc_receive_char();
		ersp = (ersp << 8) | _sdc_receive_char();
		ersp = (ersp << 8) | _sdc_receive_char();
		if (ersp & 0x40000000)
        {
			boot_puts(" SDHC ");
		} 
        else
        {
			sdcard.sdhc = 0;
		}
		_sdc_disable();
	}
	boot_puts("card detected\n");
	return 0;
}

///////////////////////////////////////////////////////////////////////////////
// This function sets the block size in the SD card.
// - len: block size in bytes (only 512 bytes supported)
// Returns 0 if success, other value if failure
///////////////////////////////////////////////////////////////////////////////
static unsigned int _sdc_set_block_size(unsigned int len)
{
    unsigned char args[4];
    unsigned char sdcard_rsp;
    register int i;

    // For now, supported block size is 512 bytes
    if (len != 512) return 1;

    // When using high capacity SDCARD, the block_length is not a number of bytes
    // but a number of blocks (transfer unit)
    if (sdcard.sdhc)
    {
        sdcard.block_length = len / 512;
        return 0;
    }

    for (i = 0; i < 4; i++)
    {
        args[i] = (len >> (32 - (i+1)*8)) & 0xFF;
    }

    _sdc_enable();

    sdcard_rsp = _sdc_send_command(16, SDCARD_CMD, args, 0x00);
    if ( SDCARD_CHECK_R1_ERROR(sdcard_rsp) )
    {
        _sdc_disable();
        return sdcard_rsp;
    }

    _sdc_disable();

    sdcard.block_length = len;

	return 0;
}

/////////////////////////////////////////////////////////////////////////////////
//           Extern functions
/////////////////////////////////////////////////////////////////////////////////

////////////////////////
int boot_spi_init()
{
    spi = (struct boot_spi_dev*)SEG_IOC_BASE;

    // initializing the SPI controller
    _spi_init (
        spi           ,
        200000        , /**< SPI_clk: 200 Khz */
        SYSCLK_FREQ   , /**< Sys_clk          */
        8             , /**< Charlen: 8       */
        SPI_TX_NEGEDGE,
        SPI_RX_POSEDGE
    );

    // initializing the SD Card
    unsigned int iter = 0;
    unsigned char sdcard_rsp;
    unsigned int i;

    while(1)
    {
        boot_puts("[BOOT SDC WARNING] Trying to initialize SD card...\n");

        sdcard_rsp = _sdc_open( 0 );  // only channel 0
        if (sdcard_rsp == 0)
        {
            boot_puts("OK\n");
            break;
        }

        boot_puts("KO\n");

        for (i = 0; i < 1000; i++);

        if (++iter >= SDCARD_RESET_ITER_MAX)
        {
            boot_puts("\n[BOOT SDC ERROR] During SD card reset");
            return -1;
        }
    }

    // set the block length of the SD Card
    sdcard_rsp = _sdc_set_block_size(512);
    if (sdcard_rsp)
    {
        boot_puts("[BOOT SDC ERROR] During SD card block size initialization\n");
        return -1;
    }

    // incrementing SDCARD clock frequency for normal function
    _spi_init (
        spi         ,
        10000000    , // SPI_clk 10 Mhz
        SYSCLK_FREQ , // Sys_clk
        -1          , // Charlen: 8
        -1          ,
        -1
    );

    boot_puts("[BOOT SDC WARNING] Finish SD card initialization\n\r");

    return 0;
} // end _sdc_init()


/////////////////////////////////////////////////////
int boot_spi_access( unsigned int       lba,
                 unsigned long long buf_paddr,
                 unsigned int       count )
{
    unsigned char args[4];
    unsigned char sdcard_rsp;
    unsigned int i;
    unsigned int curr = lba;
    unsigned int last = lba + count;

    for ( ; curr < last ; curr++ )
    {
        _sdc_lseek(curr);

        for (i = 0; i < 4; i++)
        {
            args[i] = (sdcard.access_pointer >> (32 - (i+1)*8)) & 0xFF;
        }

        _sdc_enable();

        sdcard_rsp = _sdc_send_command(17, SDCARD_CMD, args, 0x00);
        if ( SDCARD_CHECK_R1_ERROR(sdcard_rsp) )
        {
            _sdc_disable();
            return sdcard_rsp;
        }

        _sdc_wait_data_block();

        if (spi_get_data(sdcard.spi, buf_paddr, 512 ))
        {
            _sdc_disable();
            return 1;
        }

        // Get the CRC16 (comes at the end of the data block)
        _sdc_receive_char(); // first byte
        _sdc_receive_char(); // second byte

        _sdc_disable();

        buf_paddr += 512;
    }
    return 0;
}  // _end sdc_access()

// Local Variables:
// tab-width: 4
// c-basic-offset: 4
// c-file-offsets:((innamespace . 0)(inline-open . 0))
// indent-tabs-mode: nil
// End:
// vim: filetype=c:expandtab:shiftwidth=4:tabstop=4:softtabstop=4
