/*
 * dev_txt.c - TXT (Text Terminal) generic device API implementation.
 *
 * Author  Alain Greiner    (2016,2017,2018,2019)
 *
 * Copyright (c) UPMC Sorbonne Universites
 *
 * This file is part of ALMOS-MK
 *
 * 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-kernel; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <hal_kernel_types.h>
#include <hal_special.h>
#include <hal_remote.h>
#include <hal_drivers.h>
#include <thread.h>
#include <remote_busylock.h>
#include <chdev.h>
#include <rpc.h>
#include <printk.h>
#include <dev_txt.h>

/////////////////////////////////////////////////////////////////////////////////////////
// Extern global variables
/////////////////////////////////////////////////////////////////////////////////////////

extern chdev_directory_t  chdev_dir;         // allocated in kernel_init.c


#if (DEBUG_SYS_READ & 1)
extern uint32_t enter_txt_read;
extern uint32_t exit_txt_read;
#endif

#if (DEBUG_SYS_WRITE & 1)
extern uint32_t enter_txt_write;
extern uint32_t exit_txt_write;
#endif

///////////////////////////////////////////////////
const char * dev_txt_type_str( dev_txt_cmd_t type )
{
    switch (type)
    {
        case (TXT_SYNC_WRITE): return "TXT_SYNC_WRITE";
        case (TXT_READ):       return "TXT_READ";
        case (TXT_WRITE):      return "TXT_WRITE";
        default:               return "undefined";
    }
}

//////////////////////////////////
void dev_txt_init( chdev_t * txt )
{
    // For all TXT channels other than the TXT0 (kernel terminal), 
    // the PIC chdev must be initialized before the TXT chdev, because
    // the TXT chdev initialization requires the routing of an external IRQ

    xptr_t    pic_xp  = chdev_dir.pic;
    uint32_t  channel = txt->channel;
    uint32_t  impl    = txt->impl;
    bool_t    is_rx   = txt->is_rx;

assert( __FUNCTION__, ((pic_xp != XPTR_NULL) || (channel == 0)) ,
"PIC not initialised before TXT" );

    // set chdev name
    if( is_rx ) snprintk( txt->name , 16 , "txt%d_rx" , channel );
    else        snprintk( txt->name , 16 , "txt%d_tx" , channel );

    // set TXT chdev extension
    txt->ext.txt.owner_xp = XPTR_NULL;
    xlist_root_init( XPTR( local_cxy, &txt->ext.txt.root ) );
    remote_busylock_init( XPTR( local_cxy , &txt->ext.txt.lock ), LOCK_CHDEV_TXTLIST );
    
    // call driver init function
    hal_drivers_txt_init( txt );

    // no server thread and no IRQ routing for TXT0 
    // except for LETI where there MUST be IRQ routing
    // no server thread for IMPL_TXT_RS2 (multiplexed in software, not hardware)
    if( channel != 0 && impl != IMPL_TXT_RS2 )
    {
        // select a core to execute the server thread
        lid_t lid = cluster_select_local_core( local_cxy );

        // The unique IRQ from cluster 00's MTTY must be bound to a RX chdev
        // so that all IRQs are considered as RX IRQs and treated as such
        // Indeed, IRQs are raised by the MTTY only on user keystroke, so IRQs must
        // always be considered as RX IRQs.
        if ( ( impl != IMPL_TXT_MTY ) || ( channel == 1 && is_rx == 1 ) ) 
        {
        // bind IRQ to the selected core
        dev_pic_bind_irq( lid , txt );

        // enable IRQ
        dev_pic_enable_irq( lid , XPTR( local_cxy , txt ) );
        }

        // create server thread
        thread_t * new_thread;
        error_t    error;

        error = thread_kernel_create( &new_thread,
                                      THREAD_DEV,
                                      &chdev_server_func,
                                      txt,
                                      lid );

        assert( __FUNCTION__, (error == 0) , "cannot create server thread" );

        // set "server" field in chdev descriptor
        txt->server = new_thread;

        // set "chdev" field in thread descriptor
        new_thread->chdev = txt;

        // unblock server thread
        thread_unblock( XPTR( local_cxy , new_thread ) , THREAD_BLOCKED_GLOBAL );
    }
}  // end dev_txt_init()

/////////////////////////////////////////
error_t dev_txt_write( uint32_t   channel,
                       char     * buffer,
                       uint32_t   count )
{
    error_t error;

#if (DEBUG_SYS_WRITE & 1)
enter_txt_write = hal_time_stamp();
#endif

    thread_t * this = CURRENT_THREAD;

#if DEBUG_DEV_TXT_TX
uint32_t   cycle = (uint32_t)hal_get_cycles();
if( DEBUG_DEV_TXT_TX < cycle )
printk("\n[%s] thread[%x,%x] enters for <%s> / cycle %d\n",
__FUNCTION__, this->process->pid, this->trdid, buffer, cycle );
#endif

// check channel argument
assert( __FUNCTION__, (channel < CONFIG_MAX_TXT_CHANNELS) , "illegal channel index" );

    // get pointers on chdev
    xptr_t    dev_xp  = chdev_dir.txt_tx[channel];
    cxy_t     dev_cxy = GET_CXY( dev_xp );
    chdev_t * dev_ptr = GET_PTR( dev_xp );

// check dev_xp 
assert( __FUNCTION__, (dev_xp != XPTR_NULL) , "undefined TXT chdev descriptor" );

    // If we use MTTY (vci_multi_tty), we do a synchronous write on TXT[0]
    // If we use TTY  (vci_tty_tsar), we do a standard asynchronous write
    // TODO this is not very clean ... [AG]

    if( dev_ptr->impl == IMPL_TXT_MTY )  
    {
        // get driver command function
        dev_aux_t * aux = (dev_aux_t *)hal_remote_lpt( XPTR( dev_cxy , &dev_ptr->aux ) );

        // build arguments structure
        txt_sync_args_t  args;
        args.dev_xp = dev_xp;
        args.buffer = buffer;
        args.count  = count;
        args.channel = channel;

        // call directly the driver function
        aux( &args );

        error = 0;
    }
    else
    {
        // register command in calling thread descriptor
        this->txt_cmd.dev_xp  = dev_xp;
        this->txt_cmd.type    = TXT_WRITE;
        this->txt_cmd.buf_xp  = XPTR( local_cxy , buffer );
        this->txt_cmd.count   = count;

        // register client thread in waiting queue, activate server thread
        // block client thread on THREAD_BLOCKED_IO and deschedule.
        // it is re-activated by the ISR signaling IO operation completion.
        chdev_register_command( dev_xp );

        // get I/O operation status from calling thread descriptor
        error = this->txt_cmd.error;

        if( error )
        {
            printk("\n[ERROR] in %s : cannot write string %s / cycle %d\n",
            __FUNCTION__, buffer, (uint32_t)hal_get_cycles() );
        }
    }

#if DEBUG_DEV_TXT_TX
cycle = (uint32_t)hal_get_cycles();
if( DEBUG_DEV_TXT_TX < cycle )
printk("\n[%s] thread[%x,%x] exit /  cycle %d\n",
__FUNCTION__, this->process->pid, this->trdid, cycle );
#endif

#if (DEBUG_SYS_WRITE & 1)
exit_txt_write = hal_time_stamp();
#endif

    return error;

}  // end dev_txt_write()

/////////////////////////////////////////
error_t dev_txt_read( uint32_t   channel,
                      char     * buffer )
{
    error_t error;

#if (DEBUG_SYS_READ & 1)
enter_txt_read = hal_time_stamp();
#endif

    thread_t * this = CURRENT_THREAD;

#if DEBUG_DEV_TXT_RX
uint32_t   cycle = (uint32_t)hal_get_cycles();
if( DEBUG_DEV_TXT_RX < cycle )
printk("\n[%s] thread[%x,%x] enters / cycle %d\n",
__FUNCTION__, this->process->pid, this->trdid, cycle );
#endif

// check channel argument
assert( __FUNCTION__, (channel < CONFIG_MAX_TXT_CHANNELS) , "illegal channel index" );

    // get pointers on chdev
    xptr_t    dev_xp  = chdev_dir.txt_rx[channel];

// check dev_xp 
assert( __FUNCTION__, (dev_xp != XPTR_NULL) , "undefined TXT chdev descriptor" );

    // register command in calling thread descriptor
    this->txt_cmd.dev_xp  = dev_xp;
    this->txt_cmd.type    = TXT_READ;
    this->txt_cmd.buf_xp  = XPTR( local_cxy , buffer );
    this->txt_cmd.count   = 1;

    // register client thread in waiting queue, activate server thread
    // block client thread on THREAD_BLOCKED_IO and deschedule.
    // it is re-activated by the ISR signaling IO operation completion.
    chdev_register_command( dev_xp );

    // get I/O operation status from calling thread descriptor
    error = this->txt_cmd.error;

    if( error )
    {
         printk("\n[ERROR] in %s : cannot write string %s / cycle %d\n",
         __FUNCTION__, buffer, (uint32_t)hal_get_cycles() );
    }

#if DEBUG_DEV_TXT_RX
cycle = (uint32_t)hal_get_cycles();
if( DEBUG_DEV_TXT_RX < cycle )
printk("\n[%s] thread[%x,%x] get character <%c> / cycle %d\n",
__FUNCTION__, this->process->pid, this->trdid, *buffer, cycle );
#endif

#if (DEBUG_SYS_READ & 1)
exit_txt_read = hal_time_stamp();
#endif

    return error;

}  // end dev_txt_read()

////////////////////////////////////////////////
error_t dev_txt_sync_write( const char * buffer,
                            uint32_t     count )
{
    // get extended pointers on TXT[0] chdev
    xptr_t    dev_xp  = chdev_dir.txt_tx[0];
    cxy_t     dev_cxy = GET_CXY( dev_xp );
    chdev_t * dev_ptr = GET_PTR( dev_xp );

    if( dev_xp != XPTR_NULL) 
    {
        // get driver command function
        dev_aux_t * aux = (dev_aux_t *)hal_remote_lpt( XPTR( dev_cxy , &dev_ptr->aux ) );

        // build arguments structure
        txt_sync_args_t  args;
        args.dev_xp = dev_xp;
        args.buffer = buffer;
        args.count  = count;
        args.channel = 0;

        // call driver function
        aux( &args );

        return 0;
    }
    else
    {
        return -1;
    }
}   // end dev_txt_sync_write() 

