/*
 * soclib_tty.c - soclib tty driver implementation.
 *
 * Author  Alain Greiner (2016)
 *
 * Copyright (c)  UPMC Sorbonne Universites
 *
 * This file is part of ALMOS-MKH..
 *
 * ALMOS-MKH. 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; version 2.0 of the License.
 *
 * ALMOS-MKH. 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 ALMOS-MKH.; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <dev_txt.h>
#include <chdev.h>
#include <soclib_tty.h>
#include <remote_spinlock.h>
#include <thread.h>
#include <printk.h>
#include <hal_special.h>

#if CONFIG_READ_DEBUG
extern uint32_t  enter_tty_cmd;
extern uint32_t  exit_tty_cmd;

extern uint32_t  enter_tty_isr;
extern uint32_t  exit_tty_isr;
#endif

///////////////////////////////////////
void soclib_tty_init( chdev_t * chdev )
{
    xptr_t reg_xp;

    chdev->cmd = &soclib_tty_cmd;
    chdev->isr = &soclib_tty_isr;
    chdev->aux = &soclib_tty_aux;

    // get TTY channel and extended pointer on TTY peripheral base address
    xptr_t   tty_xp  = chdev->base;
    uint32_t channel = chdev->channel;

    // get SOCLIB_TTY device cluster and local pointer
    cxy_t      tty_cxy = GET_CXY( tty_xp );
    uint32_t * tty_ptr = (uint32_t *)GET_PTR( tty_xp );

    // reset TTY_RX_IRQ_ENABLE 
    reg_xp = XPTR( tty_cxy , tty_ptr + (channel * TTY_SPAN) + TTY_RX_IRQ_ENABLE );
    hal_remote_sw( reg_xp , 0 );

    // reset TTY_TX_IRQ_ENABLE
    reg_xp = XPTR( tty_cxy , tty_ptr + (channel * TTY_SPAN) + TTY_TX_IRQ_ENABLE );
    hal_remote_sw( reg_xp , 0 );
}

//////////////////////////////////////////////////////////////
void __attribute__ ((noinline)) soclib_tty_cmd( xptr_t th_xp )
{

#if CONFIG_READ_DEBUG
enter_tty_cmd = hal_time_stamp();
#endif

txt_dmsg("\n[DBG] %s : core[%x,%d] / DEV thread enter / cycle %d\n", 
__FUNCTION__ , local_cxy , CURRENT_THREAD->core->lid , hal_time_stamp() );

    // get client thread cluster and local pointer
    cxy_t      th_cxy = GET_CXY( th_xp );
    thread_t * th_ptr = (thread_t *)GET_PTR( th_xp );

    // get command type and extended pointer on TXT device
    uint32_t type   =         hal_remote_lw ( XPTR( th_cxy , &th_ptr->txt_cmd.type ) );
    xptr_t   dev_xp = (xptr_t)hal_remote_lwd( XPTR( th_cxy , &th_ptr->txt_cmd.dev_xp ) );

    assert( (type == TXT_READ) || (type == TXT_WRITE) , __FUNCTION__, "illegal command type");

    // get TXT device cluster and local pointer
    cxy_t     dev_cxy = GET_CXY( dev_xp );
    chdev_t * dev_ptr = (chdev_t *)GET_PTR( dev_xp );

    // get extended pointer on SOCLIB_TTY base segment
    xptr_t tty_xp = (xptr_t)hal_remote_lwd( XPTR( dev_cxy , &dev_ptr->base ) );

    // get SOCLIB_TTY base segment cluster and local pointer
    cxy_t      tty_cxy = GET_CXY( tty_xp );
    uint32_t * tty_ptr = (uint32_t *)GET_PTR( tty_xp );

    // get TTY channel index and channel base address
    uint32_t   channel = hal_remote_lw( XPTR( dev_cxy , &dev_ptr->channel ) );
    uint32_t * base    = tty_ptr + TTY_SPAN * channel;

    // compute extended pointer on relevant TTY register
    xptr_t reg_xp; 
    if( type == TXT_READ )  reg_xp = XPTR( tty_cxy , base + TTY_RX_IRQ_ENABLE );
    else                    reg_xp = XPTR( tty_cxy , base + TTY_TX_IRQ_ENABLE );

    // enable relevant IRQ : data transfer will be done by the TTY_RX ISR)
    hal_remote_sw( reg_xp , 1 );

txt_dmsg("\n[DBG] %s : core[%x,%d] DEV thread deschedule / cycle %d\n",
__FUNCTION__ , local_cxy , CURRENT_THREAD->core->lid , hal_time_stamp() );

    // Block and deschedule server thread
    thread_block( CURRENT_THREAD , THREAD_BLOCKED_DEV_ISR );
    sched_yield("blocked on ISR");

txt_dmsg("\n[DBG] %s : core[%x,%d] / DEV thread resume / cycle %d\n",
__FUNCTION__ , local_cxy , CURRENT_THREAD->core->lid , hal_time_stamp() );

#if CONFIG_READ_DEBUG
exit_tty_cmd = hal_time_stamp();
#endif

}  // end soclib_tty_cmd()

/////////////////////////////////////////////////////////////
void __attribute__ ((noinline)) soclib_tty_aux( void * args )
{
    uint32_t   status;
    bool_t     empty;
    uint32_t   i;

    xptr_t     dev_xp = ((txt_aux_t *)args)->dev_xp;
    char     * buffer = ((txt_aux_t *)args)->buffer;
    uint32_t   count  = ((txt_aux_t *)args)->count;
    
    // get TXT0 chdev cluster and local pointer
    cxy_t     dev_cxy = GET_CXY( dev_xp );
    chdev_t * dev_ptr = (chdev_t *)GET_PTR( dev_xp );

    // get extended pointer on TTY channel base address
    xptr_t tty_xp = (xptr_t)hal_remote_lwd( XPTR( dev_cxy , &dev_ptr->base ) );

    // get TTY channel segment cluster and local pointer
    cxy_t      tty_cxy = GET_CXY( tty_xp );
    uint32_t * tty_ptr = (uint32_t *)GET_PTR( tty_xp );

    // get extended pointers on TTY_WRITE & TTY_STATUS registers
    xptr_t write_xp  = XPTR( tty_cxy , tty_ptr + TTY_WRITE );
    xptr_t status_xp = XPTR( tty_cxy , tty_ptr + TTY_STATUS );

    // loop on characters (busy waiting strategy)
    for( i = 0 ; i < count ; i++ )
    {
        do
        {
            // get TTY_STATUS
            status = hal_remote_lw( status_xp );
            empty  = ( (status & TTY_STATUS_TX_FULL) == 0 );

            // transfer one byte if TX buffer empty
            if ( empty )  hal_remote_sb( write_xp , buffer[i] );
        }
        while ( empty == false );
    }
}  // end soclib_tty_aux()


/////////////////////////////////////////////////////////////////
void __attribute__ ((noinline)) soclib_tty_isr( chdev_t * chdev )
{
    uint32_t   type;         // command type
    uint32_t   count;        // number of bytes in buffer
    xptr_t     buf_xp;       // extended pointer on buffer
    xptr_t     status_xp;    // extended pointer on TTY_STATUS register
    xptr_t     write_xp;     // extended pointer on TTY_WRITE register
    xptr_t     read_xp;      // extended pointer on TTY_READ register
    uint32_t   status;       // TTY terminal status
    char       byte;         // read byte
    uint32_t   i;

#if CONFIG_READ_DEBUG
enter_tty_isr = hal_time_stamp();
#endif

    // get extended pointer on client thread
    xptr_t root      = XPTR( local_cxy , &chdev->wait_root );
    xptr_t client_xp = XLIST_FIRST_ELEMENT( root , thread_t , wait_list );

    // get client thread cluster and local pointer
    cxy_t      client_cxy = GET_CXY( client_xp );
    thread_t * client_ptr = (thread_t *)GET_PTR( client_xp );

    // get command arguments
    type    = hal_remote_lw ( XPTR( client_cxy , &client_ptr->txt_cmd.type   ) );
    count   = hal_remote_lw ( XPTR( client_cxy , &client_ptr->txt_cmd.count  ) );
    buf_xp  = hal_remote_lwd( XPTR( client_cxy , &client_ptr->txt_cmd.buf_xp ) );

txt_dmsg("\n[DBG] %s : core[%x,%d] enter / cycle %d\n", 
__FUNCTION__ , local_cxy, CURRENT_THREAD->core->lid , hal_time_stamp() );

    // get SOCLIB_TTY peripheral cluster and local pointer
    cxy_t      tty_cxy = GET_CXY( chdev->base );
    uint32_t * tty_ptr = (uint32_t *)GET_PTR( chdev->base );

    // get channel base address
    uint32_t * base = tty_ptr + TTY_SPAN * chdev->channel;

    // get extended pointer on TTY registers
    status_xp = XPTR( tty_cxy , base + TTY_STATUS );
    write_xp  = XPTR( tty_cxy , base + TTY_WRITE );
    read_xp   = XPTR( tty_cxy , base + TTY_READ );

    if( type == TXT_READ )              // read one single character
    {
        // get TTY_STATUS
        status = hal_remote_lw( status_xp );

        if( status & TTY_STATUS_RX_FULL )   // TTY_RX full => move one byte
        {
            // get a byte from TTY_READ, and acknowledge RX_IRQ
            byte = (char)hal_remote_lb( read_xp );

            // write it to command buffer
            hal_remote_sb( buf_xp , byte );
        }
        else                               // buffer empty => exit ISR for retry
        {
            return;
        }

        // disable RX_IRQ 
        xptr_t reg_xp = XPTR( tty_cxy , base + TTY_RX_IRQ_ENABLE );
        hal_remote_sw( reg_xp , 0 );
    }
    else if( type == TXT_WRITE )         // write all characters in string
    {
        // loop on characters
        for( i = 0 ; i < count ; i++ )
        {
            // get TTY_STATUS
            status = hal_remote_lw( status_xp );

            if( (status & TTY_STATUS_TX_FULL) == 0 ) // TTY_TX empty => move one byte
            {
                // get one byte from command buffer
                byte = (char)hal_remote_lb( buf_xp + i );

                // write byte to TTY_WRITE, and acknowledge TX_IRQ
                hal_remote_sb( write_xp , byte );
            }
            else         // TTY_TX full => update command arguments and exit ISR for retry
            {
                hal_remote_sw ( XPTR( client_cxy , &client_ptr->txt_cmd.count ), count-i );
                hal_remote_swd( XPTR( client_cxy , &client_ptr->txt_cmd.buf_xp ), buf_xp+i );
                return;
            }
        }

        // disable TX_IRQ 
        xptr_t reg_xp = XPTR( tty_cxy , base + TTY_TX_IRQ_ENABLE );
        hal_remote_sw( reg_xp , 0 );
    }

    // The I/O operation completed when we reach this point

    // set I/O operation status in command
    hal_remote_sw( XPTR( client_cxy , &client_ptr->txt_cmd.error ) , 0 );

    // unblock server thread
    thread_unblock( XPTR( local_cxy , chdev->server ) , THREAD_BLOCKED_DEV_ISR );

    // unblock client thread
    thread_unblock( client_xp , THREAD_BLOCKED_IO );

    hal_fence();

txt_dmsg("\n[DBG] %s : core[%x,%d] exit / cycle %d\n", 
__FUNCTION__ , local_cxy , CURRENT_THREAD->core->lid , hal_time_stamp() );

#if CONFIG_READ_DEBUG
exit_tty_isr = hal_time_stamp();
#endif

}  // end soclib_tty_isr()

