/*
 * sys_read.c - read bytes from a file
 * 
 * Author     Alain Greiner (2016,2017)
 *
 * 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 <kernel_config.h>
#include <hal_types.h>
#include <hal_uspace.h>
#include <hal_irqmask.h>
#include <hal_special.h>
#include <errno.h>
#include <vfs.h>
#include <vmm.h>
#include <thread.h>
#include <printk.h>
#include <process.h>

// TODO: concurrent user page(s) munmap need to be handled [AG] 

// TODO : remove these debug variables
extern uint32_t enter_sys_read;
extern uint32_t enter_devfs_move;
extern uint32_t enter_txt_read;
extern uint32_t enter_chdev_cmd;
extern uint32_t enter_chdev_server;
extern uint32_t enter_tty_cmd;
extern uint32_t enter_tty_isr;
extern uint32_t exit_tty_isr;
extern uint32_t exit_tty_cmd;
extern uint32_t exit_chdev_server;
extern uint32_t exit_chdev_cmd;
extern uint32_t exit_txt_read;
extern uint32_t exit_devfs_move;
extern uint32_t exit_sys_read;


/////////////////////////////////
int sys_read( uint32_t   file_id,
              void     * vaddr,
              uint32_t   count )
{
    error_t      error;
    paddr_t      paddr;       // required for user space checking
	xptr_t       file_xp;     // remote file extended pointer
    uint32_t     nbytes;      // number of bytes actually read
    reg_t        save_sr;     // required to enable IRQs during syscall

#if CONFIG_READ_DEBUG
uint64_t     tm_start;
uint64_t     tm_end;
tm_start = hal_get_cycles();
#endif

#if CONFIG_READ_DEBUG
enter_sys_read = (uint32_t)tm_start;
#endif

	thread_t  *  this    = CURRENT_THREAD;
	process_t *  process = this->process;
 
    // check file_id argument
	if( file_id >= CONFIG_PROCESS_FILE_MAX_NR )
	{
        printk("\n[ERROR] in %s : illegal file descriptor index = %d\n",
        __FUNCTION__ , file_id );
		this->errno = EBADFD;
		return -1;
	}

    // check user buffer in user space
    error = vmm_v2p_translate( false , vaddr , &paddr );

    if ( error )
    {
        printk("\n[ERROR] in %s : user buffer unmapped = %x\n",
        __FUNCTION__ , (intptr_t)vaddr );
		this->errno = EINVAL;
		return -1;
    }

    // enable IRQs
    hal_enable_irq( &save_sr );

    // get extended pointer on remote file descriptor
    file_xp = process_fd_get_xptr( process , file_id );

    if( file_xp == XPTR_NULL )
    {
        printk("\n[ERROR] in %s : undefined file descriptor index = %d in process %x\n",
        __FUNCTION__ , file_id , process->pid );
        this->errno = EBADFD;
        return -1;
    }

    // get file descriptor cluster and local pointer
    vfs_file_t * file_ptr = (vfs_file_t *)GET_PTR( file_xp );
    cxy_t        file_cxy = GET_CXY( file_xp );

    // check file readable
    uint32_t attr = hal_remote_lw( XPTR( file_cxy , &file_ptr->attr ) );
    if( (attr & FD_ATTR_READ_ENABLE) == 0 )
	{
        printk("\n[ERROR] in %s : file %d not readable in process %x\n",
        __FUNCTION__ , file_id , process->pid );
		this->errno = EBADFD;
		return -1;
	}
    
    // get file type
    vfs_inode_type_t type = hal_remote_lw( XPTR( file_cxy , &file_ptr->type ) );

    // action depend on file type
    if( type == INODE_TYPE_FILE )      // check file readable & read from mapper 
    {
        // check file readable
        uint32_t attr = hal_remote_lw( XPTR( file_cxy , &file_ptr->attr ) );
        if( (attr & FD_ATTR_READ_ENABLE) == 0 )
	    {
            printk("\n[ERROR] in %s : file %d not readable in process %x\n",
            __FUNCTION__ , file_id , process->pid );
		    this->errno = EBADFD;
		    return -1;
	    }

        // move count bytes from mapper
        nbytes = vfs_user_move( true,               // from mapper to buffer
                                file_xp,
                                vaddr, 
                                count );
    }
    else if( type == INODE_TYPE_DEV )  // check ownership & read from from device
    {
        // move count bytes from device
        nbytes = devfs_user_move( true,             // from device to buffer
                                  file_xp,
                                  vaddr,
                                  count );

        // check ownership
        xptr_t    chdev_xp  = chdev_from_file( file_xp );
        cxy_t     chdev_cxy = GET_CXY( chdev_xp );
        chdev_t * chdev_ptr = (chdev_t *)GET_PTR( chdev_xp );
        xptr_t    owner_xp  = hal_remote_lwd( XPTR( chdev_cxy , &chdev_ptr->ext.txt.owner_xp ) );

        if( XPTR( local_cxy , process ) != owner_xp )
        {
            printk("\n[ERROR] in %s : process %x not in foreground for TXT%d\n",
            __FUNCTION__, process->pid, hal_remote_lw( XPTR(chdev_cxy,&chdev_ptr->channel) ) );
		    this->errno = EBADFD;
		    return -1;
        }
    }
    else
    {
        nbytes = 0;
        assert( false , __FUNCTION__ , "file type %d non supported yet\n", type );
    }

    if( nbytes != count )
    {
        printk("\n[ERROR] in %s cannot read data from file %d in process %x\n",
        __FUNCTION__ , file_id , process->pid );
        this->errno = error;
        return -1;
    }

    // restore IRQs
    hal_restore_irq( save_sr );

    hal_fence();

#if CONFIG_READ_DEBUG
tm_end = hal_get_cycles();
printk("\n[DBG] %s : core[%x,%d] / thread %x in process %x / cycle %d\n"
"nbytes = %d / first byte = %c / file_id = %d / cost = %d\n",
__FUNCTION__ , local_cxy , this->core->lid , this->trdid , this->process->pid ,
(uint32_t)tm_start , nbytes , *((char *)(intptr_t)paddr) , file_id ,
(uint32_t)(tm_end - tm_start) );
#endif

#if (CONFIG_READ_DEBUG & 0x1) 
exit_sys_read = (uint32_t)tm_end;

printk("\n@@@@@@@@@@@@ timing to read character %c\n"
" - enter_sys_read     = %d / delta %d\n"
" - enter_devfs_move   = %d / delta %d\n"
" - enter_txt_read     = %d / delta %d\n"
" - enter_chdev_cmd    = %d / delta %d\n"
" - enter_chdev_server = %d / delta %d\n"
" - enter_tty_cmd      = %d / delta %d\n"
" - enter_tty_isr      = %d / delta %d\n"
" - exit_tty_isr       = %d / delta %d\n"
" - exit_tty_cmd       = %d / delta %d\n"
" - exit_chdev_server  = %d / delta %d\n"
" - exit_chdev_cmd     = %d / delta %d\n"
" - exit_txt_read      = %d / delta %d\n"
" - exit_devfs_move    = %d / delta %d\n"
" - exit_sys_read      = %d / delta %d\n",
*((char *)(intptr_t)paddr) ,
enter_sys_read     , 0 ,
enter_devfs_move   , enter_devfs_move   - enter_sys_read     ,
enter_txt_read     , enter_txt_read     - enter_devfs_move   ,
enter_chdev_cmd    , enter_chdev_cmd    - enter_txt_read     ,
enter_chdev_server , enter_chdev_server - enter_chdev_cmd    ,
enter_tty_cmd      , enter_tty_cmd      - enter_chdev_server ,
enter_tty_isr      , enter_tty_isr      - enter_tty_cmd      ,
exit_tty_isr       , exit_tty_isr       - enter_tty_isr      ,
exit_tty_cmd       , exit_tty_cmd       - exit_tty_isr       ,
exit_chdev_server  , exit_chdev_server  - exit_tty_cmd       ,
exit_chdev_cmd     , exit_chdev_cmd     - exit_chdev_server  ,
exit_txt_read      , exit_txt_read      - exit_chdev_cmd     ,
exit_devfs_move    , exit_devfs_move    - exit_txt_read      ,
exit_sys_read      , exit_sys_read      - exit_devfs_move    );
#endif
 
	return nbytes;

}  // end sys_read()
