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

// #include <hard_config.h>
#include <soclib_sdc.h>
//#include <tty0.h>
//#include <utils.h>
#include <hal_kernel_types.h>
#include <chdev.h>
#include <dev_ioc.h>
#include <thread.h>
#include <printk.h>

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

extern   chdev_directory_t    chdev_dir;  // allocated in the kernel_init.c file.

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

__attribute__((section(".kdata")))
static struct sdcard_dev global_sdcard;

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

///////////////////////////////////////////////////////////////////////////////
// This function enables SD Card select signal
///////////////////////////////////////////////////////////////////////////////
static void _sdc_enable(sdcard_dev_t *sdcard)
{
    spi_ss_assert( __FUNCTION__,sdcard->spi, sdcard->slave_id);
}

///////////////////////////////////////////////////////////////////////////////
// This function disables SD Card select signal
///////////////////////////////////////////////////////////////////////////////
static void _sdc_disable(sdcard_dev_t *sdcard)
{
    spi_ss_deassert( __FUNCTION__,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(sdcard_dev_t *sdcard, 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(sdcard_dev_t *sdcard, 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(sdcard_dev_t *sdcard)
{
    _sdc_gen_tick(sdcard, 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(sdcard_dev_t *sdcard)
{
    unsigned char sdcard_rsp;
    register int  iter;

    iter       = 0;
    sdcard_rsp = _sdc_receive_char(sdcard);
    while (
            (iter < SDCARD_COMMAND_TIMEOUT) &&
            !SDCARD_CHECK_R1_VALID(sdcard_rsp)
          )
    {
        sdcard_rsp = _sdc_receive_char(sdcard);
        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(sdcard_dev_t *sdcard)
{
	while (_sdc_receive_char(sdcard) != 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 ( sdcard_dev_t *sdcard,
                               int      index,
                               int      app  ,
                               void *   args ,
                               unsigned crc7 )
{
    unsigned char sdcard_rsp;
    unsigned char * _args;

    _sdc_gen_tick(sdcard, 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(sdcard);
        if (SDCARD_CHECK_R1_ERROR(sdcard_rsp))
        {
            return sdcard_rsp;        
        }
    }

    _args = (unsigned char *) args;

    _sdc_gen_tick(sdcard, 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(sdcard);
}

///////////////////////////////////////////////////////////////////////////////
// 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( sdcard_dev_t *sdcard, xptr_t base, unsigned int channel )
{
	unsigned char args[4];
	unsigned char sdcard_rsp;
	unsigned int  iter, ersp;

	sdcard->spi      = base;
	sdcard->slave_id = channel;

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

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

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

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

	_sdc_disable(sdcard);

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

	// send CMD41, enabling the card
	_sdc_enable(sdcard);
	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(sdcard, 41, SDCARD_ACMD, args, 0x00);
		if( sdcard_rsp == 0x01 )
		{
			continue;
		}

		break;
	}

	_sdc_disable(sdcard);
	if (sdcard_rsp)
    {
		printk("[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(sdcard);
		args[0] = sdcard->sdhc ? 0x40: 0;
		args[1] = 0;
		args[2] = 0;
		args[3] = 0;
        sdcard_rsp = _sdc_send_command(sdcard, 58, SDCARD_CMD, args, 0x00);
		if (sdcard_rsp)
        {
			printk("[SDC ERROR] CMD58 failed\n");
			return sdcard_rsp;
		}
		ersp = _sdc_receive_char(sdcard);
		ersp = (ersp << 8) | _sdc_receive_char(sdcard);
		ersp = (ersp << 8) | _sdc_receive_char(sdcard);
		ersp = (ersp << 8) | _sdc_receive_char(sdcard);
		if (ersp & 0x40000000)
        {
			printk(" SDHC ");
		} 
        else
        {
			sdcard->sdhc = 0;
		}
		_sdc_disable(sdcard);
	}
	printk("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(sdcard_dev_t *sdcard, 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);

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

    _sdc_disable(sdcard);

    sdcard->block_length = len;

	return 0;
}

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

////////////////////////
void soclib_sdc_init( chdev_t* chdev )
{
    // initializing the SPI controller
    _spi_init (
        chdev->base   ,
        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)
    {
        printk("[SDC WARNING] Trying to initialize SD card...\n");

        sdcard_rsp = _sdc_open(&global_sdcard, chdev->base, 0 );  // only channel 0
        if (sdcard_rsp == 0)
        {
            printk("OK\n");
            break;
        }

        printk("KO\n");

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

        if (++iter >= SDCARD_RESET_ITER_MAX)
        {
            assert( __FUNCTION__, false, __FUNCTION__, "\n[SDC ERROR] During SD card reset / card response = %x \n", sdcard_rsp);
        }
    }

    // set the block length of the SD Card
    sdcard_rsp = _sdc_set_block_size(&global_sdcard, 512);
    if (sdcard_rsp)
    {
        assert( __FUNCTION__, false, __FUNCTION__, "[SDC ERROR] During SD card block size initialization\n");
    }

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

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

    /* Initialize the chdev */
    // get extended pointer on SOCLIB_BDV peripheral base address
	xptr_t  sdc_xp = chdev->base;

    // set driver specific fields
    chdev->cmd = &soclib_sdc_cmd;
    chdev->isr = &soclib_sdc_isr;

} // end soclib_sdc_init()

/////////////////////////////////////////////////////
void __attribute__ ((noinline)) soclib_sdc_cmd( xptr_t th_xp )
{
    cxy_t      th_cxy = GET_CXY( th_xp );
    thread_t * th_ptr = GET_PTR( th_xp );

    // get command arguments and extended pointer on IOC device
    uint32_t        cmd_type =         hal_remote_lw ( XPTR( th_cxy , &th_ptr->ioc_cmd.type   ) );
    unsigned int    lba      =         hal_remote_lw ( XPTR( th_cxy , &th_ptr->ioc_cmd.lba ) );
    xptr_t          buf_xp   = (xptr_t)hal_remote_lwd( XPTR( th_cxy , &th_ptr->ioc_cmd.buf_xp ) );
    unsigned int    count    =         hal_remote_lw ( XPTR( th_cxy , &th_ptr->ioc_cmd.count  ) );

    unsigned char args[4];
    unsigned char sdcard_rsp;
    unsigned int i;
    unsigned int curr = lba;
    unsigned int last = lba + count;

    if ( cmd_type == IOC_SYNC_READ )  // read access
    {
        for ( ; curr < last ; curr++ )
        {
            _sdc_lseek(&global_sdcard, curr);

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

            _sdc_enable(&global_sdcard);

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

            _sdc_wait_data_block(&global_sdcard);

            if (spi_get_data(global_sdcard.spi, buf_xp, 512 ))
            {
                _sdc_disable(&global_sdcard);
                return 1;
            }

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

            _sdc_disable(&global_sdcard);

            buf_xp += 512;
        }
    }
    else            // write access
    {
        assert( __FUNCTION__, false, __FUNCTION__, "[SDC ERROR] function _sdc_write() not iplemented yet\n");
    }
}  // _end sdc_access()

///////////////////////////////////////////////////////////////////////////////
// This ISR handles the IRQ generated by a SDC controler
///////////////////////////////////////////////////////////////////////////////
void __attribute__ ((noinline)) soclib_sdc_isr( chdev_t * chdev )
{
    assert( __FUNCTION__, false, __FUNCTION__, "\n[GIET ERROR] _sdc_isr() not implemented\n");
}

// 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
