/*
 * dev_txt.c - TXT (Text Terminal) generic device API implementation.
 *
 * Author  Alain Greiner    (2016)
 *
 * 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 <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

////////////////////////////////////////
char * dev_txt_type_str( uint32_t type )
{
    if     ( type == TXT_SYNC_WRITE ) return "TXT_SYNC_WRITE";
    else if( type == TXT_READ       ) return "TXT_READ";
    else if( type == TXT_WRITE      ) return "TXT_WRITE";
    else                              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( (pic_xp != XPTR_NULL) || (channel == 0) , __FUNCTION__ , 
            "PIC not initialised before TXT" );

    // set chdev name
    if( is_rx ) snprintf( txt->name , 16 , "txt%d_rx" , channel );
    else        snprintf( 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_spinlock_init( XPTR( local_cxy , &txt->ext.txt.lock ) );
    
    // call driver init function
    hal_drivers_txt_init(txt, impl);

    // no server thread and no IRQ routing for TXT0 
    // 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();

        // 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_sequencial_server,
                                      txt,
                                      lid );

        assert( (error == 0) , __FUNCTION__ , "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 );
    }
}

//////////////////////////////////////////////////////////////////////////////////
// This static function is called by dev_txt_read(), dev_txt_write() functions.
////////////////////////////////////i/////////////////////////////////////////////
static error_t dev_txt_access( uint32_t   type,
                               uint32_t   channel,
                               char     * buffer,
                               uint32_t   count )
{
    xptr_t     dev_xp;
    thread_t * this = CURRENT_THREAD;

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

    // get extended pointer on remote TXT chdev descriptor
    if( type == TXT_WRITE )  dev_xp = chdev_dir.txt_tx[channel];
    else                     dev_xp = chdev_dir.txt_rx[channel];

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

    // register command in calling thread descriptor
    this->txt_cmd.dev_xp  = dev_xp;
    this->txt_cmd.type    = type;
    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 );

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

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

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

#if DEBUG_DEV_TXT_TX
uint32_t cycle = (uint32_t)hal_get_cycles();
if( DEBUG_DEV_TXT_TX < cycle )
printk("\n[DBG] %s : thread %x enters / cycle %d\n", __FUNCTION__, CURRENT_THREAD, cycle );
#endif

    return dev_txt_access( TXT_WRITE , channel , buffer , count );

#if DEBUG_DEV_TXT_TX
cycle = (uint32_t)hal_get_cycles();
if( DEBUG_DEV_TXT_TX < cycle )
printk("\n[DBG] %s : thread %x exit / cycle %d\n", __FUNCTION__, CURRENT_THREAD, cycle );
#endif

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

}

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

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

#if DEBUG_DEV_TXT_RX
uint32_t cycle = (uint32_t)hal_get_cycles();
if( DEBUG_DEV_TXT_RX < cycle )
printk("\n[DBG] %s : thread %x enters / cycle %d\n", __FUNCTION__, CURRENT_THREAD, cycle );
#endif

    return dev_txt_access( TXT_READ , channel , buffer , 1 );

#if DEBUG_DEV_TXT_RX
cycle = (uint32_t)hal_get_cycles();
if( DEBUG_DEV_TXT_RX < cycle )
printk("\n[DBG] %s : thread %x exit / cycle %d\n", __FUNCTION__, CURRENT_THREAD, cycle );
#endif

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

}

//////////////////////////////////////////////
error_t dev_txt_sync_write( char     * buffer,
                            uint32_t   count )
{
    // get extended pointer on TXT[0] chdev
    xptr_t  dev_xp = chdev_dir.txt_tx[0];

    assert( (dev_xp != XPTR_NULL) , __FUNCTION__ ,
    "undefined TXT0 chdev descriptor" );

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

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

    // call driver function
    aux( &args );

    return 0;
}

