/*
 * dev_ioc.c - IOC (Block Device Controler) 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 <almos_config.h>
#include <hal_types.h>
#include <hal_gpt.h>
#include <soclib_bdv.h>
#include <soclib_hba.h>
//#include <soclib_sdc.h>
//#include <soclib_spi.h>
//#include <soclib_rdk.h>
#include <thread.h>
#include <printk.h>
#include <chdev.h>
#include <dev_ioc.h>

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

extern chdev_directory_t  chdev_dir;         // allocated in kernel_init.c

extern chdev_pic_input_t  chdev_pic_input;   // allocated in kernel_init.c

////////////////////////////////////
void dev_ioc_init( chdev_t * chdev )
{
    // the local ICU chdev must be initialized before the IOC chdev, because
    // the IOC chdev initialisation requires allocation of a WTI from local ICU
    xptr_t  icu_xp  = chdev_dir.icu[local_cxy];
    assert( (icu_xp != XPTR_NULL) , __FUNCTION__ , "ICU not initialised before IOC" );

    // get implementation and channel from chdev descriptor
    uint32_t  impl    = chdev->impl;
    uint32_t  channel = chdev->channel;

    // set driver specific fields in chdev descriptor and call driver init function
    if( impl == IMPL_IOC_BDV )
    {
        chdev->cmd = &soclib_bdv_cmd;
        chdev->isr = &soclib_bdv_isr;
        soclib_bdv_init( chdev );
    }
    else if( impl == IMPL_IOC_HBA )
    {
        chdev->cmd = &soclib_hba_command;
        chdev->isr = &soclib_hba_isr;
        soclib_hba_init( chdev );
    }
    else
    {
        assert( false , __FUNCTION__ , "undefined IOC device implementation" );
    }

    // get a WTI mailbox from local ICU
    uint32_t wti_id = dev_icu_wti_alloc();

    assert( (wti_id != -1) , __FUNCTION__ , "cannot allocate WTI mailbox" );

    // select a core
    lid_t lid = cluster_select_local_core();

    // enable WTI IRQ and update WTI interrupt vector
    dev_icu_enable_irq( lid , WTI_TYPE , wti_id , chdev );

    // link IOC IRQ to WTI mailbox in PIC component 
    uint32_t irq_id = chdev_pic_input.ioc[channel];
    dev_pic_bind_irq( irq_id , local_cxy , wti_id );

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

    error = thread_kernel_create( &new_thread,
                                  THREAD_DEV,
                                  &chdev_sequencial_server,
                                  chdev,
                                  lid ); 
    assert( (error == 0) , __FUNCTION__ , "cannot create server thread" );

    // set "server" field in chdev descriptor
    chdev->server = new_thread;
    
    // start server thread
    thread_unblock( XPTR( local_cxy , new_thread ) , THREAD_BLOCKED_GLOBAL );
 
}  // end dev_ioc_init()

//////////////////////////////////////////////////////////////////////////////////
// This static function is called by dev_ioc_read() & dev_ioc_write() functions.
// It builds and registers the command in the calling thread descriptor, after
// translation of buffer virtual address to physical address. 
// Then, it registers the calling thead in chdev waiting queue.
// Finally it blocks on the THREAD_BLOCKED_DEV condition and deschedule.
////////////////////////////////////i/////////////////////////////////////////////
static error_t dev_ioc_access( bool_t    to_mem,
                               char    * buffer,
                               uint32_t  lba,
                               uint32_t  count )
{
    thread_t * this = CURRENT_THREAD;              // pointer on client thread

    error_t     error;
    paddr_t     buf_paddr;

    // Get buffer physical address
    error = vmm_v2p_translate( CONFIG_KERNEL_IDENTITY , buffer , &buf_paddr );
 
    if( error )  return EINVAL;

    ioc_dmsg("\n[INFO] in %s : thread %x in process %x"
             " for lba = %x / vaddr = %x / paddr = %l / at cycle %d\n", 
             __FUNCTION__ , this->trdid , this->process->pid , 
             lba , (uint32_t)buffer , buf_paddr , hal_time_stamp() );

#if USE_IOB    // software L2/L3 cache coherence for memory buffer 

    if ( to_mem )  dev_mmc_inval( buf_paddr, count<<9 );
    else           dev_mmc_sync( buf_paddr, count<<9 );

#endif     // end software L2/L3 cache coherence

    // get extended pointer on IOC chdev descriptor
    xptr_t  dev_xp = chdev_dir.ioc[0];

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

    // register command in calling thread descriptor
    this->command.ioc.dev_xp    = dev_xp;
    this->command.ioc.to_mem    = to_mem;
    this->command.ioc.buf_xp    = XPTR( local_cxy , buffer );
    this->command.ioc.lba       = lba;
    this->command.ioc.count     = count;

    // register client thread in IOC chdev 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 , this );

    ioc_dmsg("\n[INFO] in %s : thread %x in process %x"
             " completes / error = %d / at cycle %d\n", 
             __FUNCTION__ , this->trdid , this->process->pid ,
             this->dev.ioc.error , hal_time_stamp() );

    // return I/O operation status
    return this->command.ioc.error;  

}  // end dev_ioc_access()

////////////////////////////////////////////
error_t dev_ioc_read( char         * buffer,
                      uint32_t       lba,
                      uint32_t       count )
{
    return dev_ioc_access( true , buffer , lba , count ); 
}  

////////////////////////////////////////////
error_t dev_ioc_write( char         * buffer,
                       uint32_t       lba,
                       uint32_t       count )
{
    return dev_ioc_access( false , buffer , lba , count ); 
}
