/*=============================================================================
//
//      hal_diag.c
//
//      HAL diagnostic output code
//
//=============================================================================
// ####ECOSGPLCOPYRIGHTBEGIN####                                            
// -------------------------------------------                              
// This file is part of eCos, the Embedded Configurable Operating System.   
// Copyright (C) 1998, 1999, 2000, 2001, 2002, 2004, 2008 Free Software Foundation, Inc.
// Copyright (C) 2004, 2008, 2009 eCosCentric Limited                             
//
// eCos is free software; you can redistribute it and/or modify it under    
// the terms of the GNU General Public License as published by the Free     
// Software Foundation; either version 2 or (at your option) any later      
// version.                                                                 
//
// eCos is distributed in the hope that it will be useful, but WITHOUT      
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or    
// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License    
// for more details.                                                        
//
// You should have received a copy of the GNU General Public License        
// along with eCos; if not, write to the Free Software Foundation, Inc.,    
// 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.            
//
// As a special exception, if other files instantiate templates or use      
// macros or inline functions from this file, or you compile this file      
// and link it with other works to produce a work based on this file,       
// this file does not by itself cause the resulting work to be covered by   
// the GNU General Public License. However the source code for this file    
// must still be made available in accordance with section (3) of the GNU   
// General Public License v2.                                               
//
// This exception does not invalidate any other reasons why a work based    
// on this file might be covered by the GNU General Public License.         
// -------------------------------------------                              
// ####ECOSGPLCOPYRIGHTEND####                                              
//=============================================================================
//#####DESCRIPTIONBEGIN####
//
// Author(s):   nickg, based on lpc2xxx code by jlarmour
// Contributors:jskov, gthomas
// Date:        2009-11-20
// Purpose:     HAL diagnostic output
// Description: Implementations of HAL diagnostic output support.
//
//####DESCRIPTIONEND####
//
//===========================================================================*/

#include <pkgconf/hal.h>
#include CYGBLD_HAL_PLATFORM_H

#include <cyg/infra/cyg_type.h>         // base types
#include <cyg/infra/cyg_trac.h>         // tracing

#include <cyg/hal/hal_arch.h>           // SAVE/RESTORE GP macros
#include <cyg/hal/hal_io.h>             // IO macros
#include <cyg/hal/hal_if.h>             // interface API
#include <cyg/hal/hal_intr.h>           // HAL_ENABLE/MASK/UNMASK_INTERRUPTS
#include <cyg/hal/hal_misc.h>           // Helper functions
#include <cyg/hal/drv_api.h>            // CYG_ISR_HANDLED

#include <cyg/hal/var_io.h>             // UART registers

#define NUMOF(t) (sizeof(t)/sizeof(t[0]))

//-----------------------------------------------------------------------------

typedef struct {
    cyg_uint32          uart;
    CYG_ADDRESS         base;
    cyg_int32           msec_timeout;
    int                 isr_vector;
    cyg_uint32          rxpin;
    cyg_uint32          txpin;
    cyg_uint32          clock;
    char                modem_control;
    
    cyg_uint32          baud_rate;
} channel_data_t;

//-----------------------------------------------------------------------------

static channel_data_t lpc1xxx_ser_channels[] = {
#if CYGINT_HAL_LPC1XXX_UART0>0
    { 0, CYGHWR_HAL_LPC1XXX_UART0, 1000, CYGNUM_HAL_INTERRUPT_UART0,
      CYGHWR_HAL_LPC1XXX_UART0_RX, CYGHWR_HAL_LPC1XXX_UART0_TX, CYGHWR_HAL_LPC1XXX_UART0_CLOCK, 0},
#endif
#if CYGINT_HAL_LPC1XXX_UART1>0    
    { 1, CYGHWR_HAL_LPC1XXX_UART1, 1000, CYGNUM_HAL_INTERRUPT_UART1,
      CYGHWR_HAL_LPC1XXX_UART1_RX, CYGHWR_HAL_LPC1XXX_UART1_TX, CYGHWR_HAL_LPC1XXX_UART1_CLOCK, 1},
#endif
#if CYGINT_HAL_LPC1XXX_UART2>0
    { 0, CYGHWR_HAL_LPC1XXX_UART2, 1000, CYGNUM_HAL_INTERRUPT_UART2,
      CYGHWR_HAL_LPC1XXX_UART2_RX, CYGHWR_HAL_LPC1XXX_UART2_TX, CYGHWR_HAL_LPC1XXX_UART2_CLOCK, 0},
#endif
#if CYGINT_HAL_LPC1XXX_UART3>0
    { 0, CYGHWR_HAL_LPC1XXX_UART3, 1000, CYGNUM_HAL_INTERRUPT_UART3,
      CYGHWR_HAL_LPC1XXX_UART3_RX, CYGHWR_HAL_LPC1XXX_UART3_TX, CYGHWR_HAL_LPC1XXX_UART3_CLOCK, 0},
#endif
};

//-----------------------------------------------------------------------------
// UART configuration helpers.
//
// These are called both from the HAL IO code and from the serial
// driver to configure the UART and set the baud rate. In each case
// the UART is identified by its base address, since we don't know
// which UARTs are configured, and we search the table for a match.

cyg_uint16
cyg_hal_lpc1xxx_uart_divisor( cyg_uint32 base, cyg_uint32 baud )
{
    int pclkdiv = 1;
    int i;

    for( i = 0; i < NUMOF(lpc1xxx_ser_channels); i++ )
    {
        channel_data_t *chan = &lpc1xxx_ser_channels[i];
       
        if( chan->base == base )
        {
            // Extract the peripheral clock divider from the clock config.
            pclkdiv = hal_lpc1xxx_pclock_divider[CYGHWR_HAL_LPC1XXX_CLOCK_DIV( chan->clock )];
        }
    }

    CYG_ASSERT( i < NUMOF(lpc1xxx_ser_channels), "Unrecognized UART base address" );
    
    return (hal_lpc1xxx_cclk / pclkdiv) / (16 * baud);
}

void
cyg_hal_lpc1xxx_uart_config( cyg_uint32 base )
{
    int i;

    for( i = 0; i < NUMOF(lpc1xxx_ser_channels); i++ )
    {
        channel_data_t *chan = &lpc1xxx_ser_channels[i];
        
        if( chan->base == base )
        {
            CYGHWR_HAL_LPC1XXX_CLOCK_ENABLE( chan->clock );
            CYGHWR_HAL_LPC1XXX_GPIO_SET( chan->txpin );
            CYGHWR_HAL_LPC1XXX_GPIO_SET( chan->rxpin );
        }
    }

    CYG_ASSERT( i < NUMOF(lpc1xxx_ser_channels), "Unrecognized UART base address" );
}

//-----------------------------------------------------------------------------

static void
update_baud_rate( channel_data_t *chan )
{
    cyg_uint8 lcr;
    CYG_ADDRESS base = chan->base;
    cyg_uint16 divisor_latch;

    // Line Control Register
    // 8 data, 1 stop, no parity, DLAB enable
    lcr = CYGHWR_HAL_LPC1XXX_UART_LCR_WORD_LENGTH_8 |
          CYGHWR_HAL_LPC1XXX_UART_LCR_STOP_1        |
          CYGHWR_HAL_LPC1XXX_UART_LCR_DLAB;

    HAL_WRITE_UINT8( base+CYGHWR_HAL_LPC1XXX_UART_LCR, lcr );

    // Initialise baud rate - baud rate clock is pclk divided by this
    // divisor latch, and end up as 16 * baud rate
    divisor_latch = cyg_hal_lpc1xxx_uart_divisor( chan->base, chan->baud_rate );
    HAL_WRITE_UINT8( base+CYGHWR_HAL_LPC1XXX_UART_DLL, divisor_latch & 0xff );
    HAL_WRITE_UINT8( base+CYGHWR_HAL_LPC1XXX_UART_DLM, (divisor_latch >>8) & 0xff );
    // Done with baud rate, disable DLAB
    lcr &= ~CYGHWR_HAL_LPC1XXX_UART_LCR_DLAB;
    HAL_WRITE_UINT8( base+CYGHWR_HAL_LPC1XXX_UART_LCR, lcr );
}

//-----------------------------------------------------------------------------

static void
cyg_hal_plf_serial_init_channel(void* __ch_data)
{
    channel_data_t *chan = (channel_data_t*)__ch_data;
    CYG_ADDRESS base = chan->base;
    cyg_uint8 dummy;

    // Ensure power is on to device and GPIO lines are configured

    cyg_hal_lpc1xxx_uart_config( chan->base );
    
    chan->baud_rate = CYGNUM_HAL_VIRTUAL_VECTOR_CONSOLE_CHANNEL_BAUD;
    update_baud_rate( chan );
    
    // disable interrupts on device
    HAL_WRITE_UINT8( base+CYGHWR_HAL_LPC1XXX_UART_IER, 0 );
    // Read IIR to clear it
    HAL_READ_UINT8( base+CYGHWR_HAL_LPC1XXX_UART_IIR, dummy ); 
    // Read LSR to clear (most of) it
    HAL_READ_UINT8( base+CYGHWR_HAL_LPC1XXX_UART_LSR, dummy ); 
    // Initialise MCR and MSR if applicable
    if (chan->modem_control)
    {
        // enable DTR+RTS signals
        HAL_WRITE_UINT8( base+CYGHWR_HAL_LPC1XXX_UART_MCR,
                         CYGHWR_HAL_LPC1XXX_UART_MCR_DTR|CYGHWR_HAL_LPC1XXX_UART_MCR_RTS);
        // clear MSR by reading
        HAL_READ_UINT8( base+CYGHWR_HAL_LPC1XXX_UART_MSR, dummy );
    }

    // Initialise FIFOs
    HAL_WRITE_UINT8( base+CYGHWR_HAL_LPC1XXX_UART_FCR,
                     CYGHWR_HAL_LPC1XXX_UART_FCR_FIFO_ENA      |
                     CYGHWR_HAL_LPC1XXX_UART_FCR_RX_FIFO_RESET |
                     CYGHWR_HAL_LPC1XXX_UART_FCR_TX_FIFO_RESET |
                     CYGHWR_HAL_LPC1XXX_UART_FCR_RX_TRIGGER_0 );

}

//-----------------------------------------------------------------------------

void
cyg_hal_plf_serial_putc(void *__ch_data, char c)
{
    CYG_ADDRESS base = ((channel_data_t*)__ch_data)->base;
    cyg_uint8 status;

    do {
        HAL_READ_UINT8( base + CYGHWR_HAL_LPC1XXX_UART_LSR, status );
    } while ((status & CYGHWR_HAL_LPC1XXX_UART_LSR_THRE) == 0);

    HAL_WRITE_UINT8( base + CYGHWR_HAL_LPC1XXX_UART_THR, c );
}

//-----------------------------------------------------------------------------

static cyg_bool
cyg_hal_plf_serial_getc_nonblock(void* __ch_data, cyg_uint8* ch)
{
    channel_data_t* chan = (channel_data_t*)__ch_data;
    CYG_ADDRESS base = chan->base;
    cyg_uint8 stat;

    HAL_READ_UINT8( base + CYGHWR_HAL_LPC1XXX_UART_LSR, stat );
    if ((stat & CYGHWR_HAL_LPC1XXX_UART_LSR_RDR) == 0)
        return false;

    HAL_READ_UINT8( base + CYGHWR_HAL_LPC1XXX_UART_RBR, *ch);

    return true;
}

//=============================================================================
// Virtual vector HAL diagnostics


#if defined(CYGSEM_HAL_VIRTUAL_VECTOR_DIAG) || defined(CYGSEM_HAL_VIRTUAL_VECTOR_CLAIM_COMMS)
cyg_uint8
cyg_hal_plf_serial_getc(void* __ch_data)
{
    cyg_uint8 ch;

    while(!cyg_hal_plf_serial_getc_nonblock(__ch_data, &ch));

    return ch;
}

static void
cyg_hal_plf_serial_write(void* __ch_data, const cyg_uint8* __buf, 
                         cyg_uint32 __len)
{
    while(__len-- > 0)
        cyg_hal_plf_serial_putc(__ch_data, *__buf++);
}

static void
cyg_hal_plf_serial_read(void* __ch_data, cyg_uint8* __buf, cyg_uint32 __len)
{
    while(__len-- > 0)
        *__buf++ = cyg_hal_plf_serial_getc(__ch_data);

}

cyg_bool
cyg_hal_plf_serial_getc_timeout(void* __ch_data, cyg_uint8* ch)
{
    int delay_count;
    channel_data_t* chan = (channel_data_t*)__ch_data;
    cyg_bool res;

    delay_count = chan->msec_timeout * 10; // delay in .1 ms steps

    for(;;) {
        res = cyg_hal_plf_serial_getc_nonblock(__ch_data, ch);
        if (res || 0 == delay_count--)
            break;
        
        CYGACC_CALL_IF_DELAY_US(100);
    }

    return res;
}

static int
cyg_hal_plf_serial_control(void *__ch_data, __comm_control_cmd_t __func, ...)
{
    static int irq_state = 0;
    channel_data_t* chan = (channel_data_t*)__ch_data;
    CYG_ADDRESS base = ((channel_data_t*)__ch_data)->base;
    int ret = 0;
    cyg_uint8 dummy;
    va_list ap;

    va_start(ap, __func);

    switch (__func) {
    case __COMMCTL_IRQ_ENABLE:
        irq_state = 1;
        // Read IIR to clear it
        HAL_READ_UINT8( base + CYGHWR_HAL_LPC1XXX_UART_IIR, dummy ); 

        HAL_INTERRUPT_ACKNOWLEDGE( chan->isr_vector );
        HAL_INTERRUPT_UNMASK( chan->isr_vector );
        HAL_WRITE_UINT8( base + CYGHWR_HAL_LPC1XXX_UART_IER, CYGHWR_HAL_LPC1XXX_UART_IER_RXDATA_INT );
        break;
    case __COMMCTL_IRQ_DISABLE:
        ret = irq_state;
        irq_state = 0;
        HAL_INTERRUPT_MASK( chan->isr_vector );
        HAL_WRITE_UINT8( base + CYGHWR_HAL_LPC1XXX_UART_IER, 0 );
        break;
    case __COMMCTL_DBG_ISR_VECTOR:
        ret = chan->isr_vector;
        break;
    case __COMMCTL_SET_TIMEOUT:
    {
        va_list ap;

        va_start(ap, __func);

        ret = chan->msec_timeout;
        chan->msec_timeout = va_arg(ap, cyg_uint32);

        va_end(ap);
    }        
    case __COMMCTL_GETBAUD:
        ret = chan->baud_rate;
        break;
    case __COMMCTL_SETBAUD:
        chan->baud_rate = va_arg(ap, cyg_int32);
        // Should we verify this value here?
        update_baud_rate(chan);
        ret = 0;
        break;
    default:
        break;
    }
    va_end(ap);
    return ret;
}

static int
cyg_hal_plf_serial_isr(void *__ch_data, int* __ctrlc, 
                       CYG_ADDRWORD __vector, CYG_ADDRWORD __data)
{
    int res = 0;
    channel_data_t* chan = (channel_data_t*)__ch_data;
    cyg_uint8 ch;
    cyg_uint8 stat;

    // Read IIR to clear it
    HAL_READ_UINT8( chan->base + CYGHWR_HAL_LPC1XXX_UART_IIR, stat ); 

    // Debug only stuff: we take the risk of this causing corruption since these events shouldn't happen
    if ((stat & CYGHWR_HAL_LPC1XXX_UART_IIR_IIR0) == 0)
    {
        CYG_TRACE1( true, "Got serial int, but none pending? iir=%08x", stat );
    }
    if ( (stat & 0xf) == CYGHWR_HAL_LPC1XXX_UART_IIR_IIR2)
    {
        // If any rxdata available interrupt is claimed to be set by this serial port,
        // we claim to handle it.
        //
        // The reason is that if you are debugging with GDB a program which runs with
        // ints enabled, then after GDB finishes and global ints are re-enabled
        // for the program, you will immediately get a serial int, reflecting
        // the serial traffic that happened earlier for GDB. But there will be
        // no actual data - it's just the interrupt flag having been set earlier. So
        // we want to claim it was handled, otherwise it's marked as a spurious int,
        // leading to a possible assert.
        res = CYG_ISR_HANDLED;
    }
    else
    {
        CYG_TRACE1( true, "Got serial int, but not RDA. iir=%08x", stat );
    }

    *__ctrlc = 0;
    HAL_READ_UINT8( chan->base + CYGHWR_HAL_LPC1XXX_UART_LSR, stat);
    if ( (stat & CYGHWR_HAL_LPC1XXX_UART_LSR_RDR) != 0 ) {

        HAL_READ_UINT8( chan->base + CYGHWR_HAL_LPC1XXX_UART_RBR, ch);
        if( cyg_hal_is_break( &ch , 1 ) )
            *__ctrlc = 1;

    }
    HAL_INTERRUPT_ACKNOWLEDGE(chan->isr_vector);

    return res;
}

static void
cyg_hal_plf_serial_init(void)
{
    hal_virtual_comm_table_t* comm;
    int cur;
    int i;
    
    cur = CYGACC_CALL_IF_SET_CONSOLE_COMM(CYGNUM_CALL_IF_SET_COMM_ID_QUERY_CURRENT);

    for( i = 0; i < CYGNUM_HAL_VIRTUAL_VECTOR_COMM_CHANNELS ; i++ )
    {
        cyg_hal_plf_serial_init_channel(&lpc1xxx_ser_channels[i]);

        CYGACC_CALL_IF_SET_CONSOLE_COMM(i);
        comm = CYGACC_CALL_IF_CONSOLE_PROCS();
        CYGACC_COMM_IF_CH_DATA_SET(*comm, &lpc1xxx_ser_channels[i]);
        CYGACC_COMM_IF_WRITE_SET(*comm, cyg_hal_plf_serial_write);
        CYGACC_COMM_IF_READ_SET(*comm, cyg_hal_plf_serial_read);
        CYGACC_COMM_IF_PUTC_SET(*comm, cyg_hal_plf_serial_putc);
        CYGACC_COMM_IF_GETC_SET(*comm, cyg_hal_plf_serial_getc);
        CYGACC_COMM_IF_CONTROL_SET(*comm, cyg_hal_plf_serial_control);
        CYGACC_COMM_IF_DBG_ISR_SET(*comm, cyg_hal_plf_serial_isr);
        CYGACC_COMM_IF_GETC_TIMEOUT_SET(*comm, cyg_hal_plf_serial_getc_timeout);
    }
    
    // Restore original console
    CYGACC_CALL_IF_SET_CONSOLE_COMM(cur);

    // set debug channel baud rate if different
#if (CYGNUM_HAL_VIRTUAL_VECTOR_CONSOLE_CHANNEL_BAUD != CYGNUM_HAL_VIRTUAL_VECTOR_DEBUG_CHANNEL_BAUD)
    lpc1xxx_ser_channels[CYGNUM_HAL_VIRTUAL_VECTOR_DEBUG_CHANNEL]->baud_rate = 
        CYGNUM_HAL_VIRTUAL_VECTOR_DEBUG_CHANNEL_BAUD;
    update_baud_rate( &lpc1xxx_ser_channels[CYGNUM_HAL_VIRTUAL_VECTOR_DEBUG_CHANNEL] );
#endif

}

void
cyg_hal_plf_comms_init(void)
{
    static int initialized = 0;

    if (initialized)
        return;

    initialized = 1;

    cyg_hal_plf_serial_init();
}

//=============================================================================

#endif // if defined(CYGSEM_HAL_VIRTUAL_VECTOR_DIAG) || defined(CYGSEM_HAL_VIRTUAL_VECTOR_CLAIM_COMMS)

//=============================================================================
// Non-Virtual vector HAL diagnostics


#ifndef CYGSEM_HAL_VIRTUAL_VECTOR_DIAG

#ifdef CYGNUM_HAL_VIRTUAL_VECTOR_CONSOLE_CHANNEL
# define CHAN CYGNUM_HAL_VIRTUAL_VECTOR_CONSOLE_CHANNEL
#else
# define CHAN 0
#endif

__externC void
hal_lpc1xxx_diag_init(void)
{
    if (CHAN <= NUMOF(lpc1xxx_ser_channels)) // this check should compile out
    {
        cyg_hal_plf_serial_init_channel(&lpc1xxx_ser_channels[CHAN]);
    }
}

__externC void
hal_lpc1xxx_diag_write_char(char c)
{
    if (CHAN <= NUMOF(lpc1xxx_ser_channels)) // this check should compile out
    {
        cyg_hal_plf_serial_putc(&lpc1xxx_ser_channels[CHAN], c);
    }
}

__externC void
hal_lpc1xxx_diag_read_char(char *c)
{
    if (CHAN <= NUMOF(lpc1xxx_ser_channels)) // this check should compile out
    {
        while (!cyg_hal_plf_serial_getc_nonblock(&lpc1xxx_ser_channels[CHAN], (cyg_uint8*)c))
            CYG_EMPTY_STATEMENT;
    }
}

#endif

//-----------------------------------------------------------------------------
// End of hal_diag.c
