/*
 * sys_write.c - Kernel function implementing the "write" system call.
 * 
 * Author        Alain Greiner (2016,2017,2018,2019)
 *
 * 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_kernel_types.h>
#include <hal_vmm.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>


extern uint32_t enter_sys_write;
extern uint32_t enter_devfs_write;
extern uint32_t enter_txt_write;
extern uint32_t enter_chdev_cmd_write;
extern uint32_t enter_chdev_server_write;
extern uint32_t enter_tty_cmd_write;
extern uint32_t enter_tty_isr_write;
extern uint32_t exit_tty_isr_write;
extern uint32_t exit_tty_cmd_write;
extern uint32_t exit_chdev_server_write;
extern uint32_t exit_chdev_cmd_write;
extern uint32_t exit_txt_write;
extern uint32_t exit_devfs_write;
extern uint32_t exit_sys_write;

//////////////////////////////////
int sys_write( uint32_t   file_id,
               void     * vaddr,
               uint32_t   count )
{
    error_t       error;
    vseg_t      * vseg;            // required for user space checking
	xptr_t        file_xp;         // remote file extended pointer
    vfs_file_t  * file_ptr;        // remote file local pointer
    cxy_t         file_cxy;        // remote file cluster identifier
    uint32_t      file_type;       // file type
    uint32_t      file_offset;     // current file offset
    uint32_t      file_attr;       // file_attribute
    vfs_inode_t * inode_ptr;       // local pointer on associated inode
    uint32_t      nbytes;          // number of bytes actually written
    reg_t         save_sr;         // required to enable IRQs during syscall

	thread_t    * this = CURRENT_THREAD;
	process_t   * process = this->process;

#if (DEBUG_SYS_WRITE || CONFIG_INSTRUMENTATION_SYSCALLS)
uint64_t     tm_start = hal_get_cycles();
#endif

#if DEBUG_SYS_WRITE
if( DEBUG_SYS_WRITE < tm_start )
printk("\n[%s] thread[%x,%x] enter / vaddr %x / %d bytes / cycle %d\n",
__FUNCTION__, process->pid, this->trdid, vaddr, count, (uint32_t)tm_start );
#endif
 
#if (DEBUG_SYS_WRITE & 1)
enter_sys_write = (uint32_t)tm_start;
#endif

    // check file_id argument
	if( file_id >= CONFIG_PROCESS_FILE_MAX_NR )
	{

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : thread[%x,%x] illegal file descriptor index %d\n",
__FUNCTION__, process->pid, this->trdid, file_id );
#endif
        this->errno = EBADFD;
		return -1;
	}

    // check user buffer in user space
    error = vmm_get_vseg( process , (intptr_t)vaddr , &vseg );

    if ( error )
    {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : thread[%x,%x] user buffer unmapped %x\n",
__FUNCTION__ , process->pid, this->trdid, (intptr_t)vaddr );
hal_vmm_display( process , false );
#endif
		this->errno = EINVAL;
		return -1;
    }

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

    if( file_xp == XPTR_NULL )
    {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : thread[%x,%x] undefined file descriptor = %d\n",
__FUNCTION__, process->pid, this->trdid, file_id );
#endif
		this->errno = EBADFD;
		return -1;
    }

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

    // get file type, offset, aatributes, and associated inode
    file_type   = hal_remote_l32( XPTR( file_cxy , &file_ptr->type ) );
    file_offset = hal_remote_l32( XPTR( file_cxy , &file_ptr->offset ) );
    inode_ptr   = hal_remote_lpt( XPTR( file_cxy , &file_ptr->inode ) );
    file_attr   = hal_remote_l32( XPTR( file_cxy , &file_ptr->attr ) );

    // enable IRQs
    hal_enable_irq( &save_sr );

    // action depend on file type
    if( file_type == INODE_TYPE_FILE )  // write to a file mapper 
    {
        // check file writable
        if( (file_attr & FD_ATTR_WRITE_ENABLE) == 0 )
	    {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : thread[%x,%x] file %d not writable\n",
__FUNCTION__ , process->pid, this->trdid, file_id );
#endif
            hal_restore_irq( save_sr );
		    this->errno = EBADFD;
		    return -1;
	    }

        // move count bytes to mapper
        nbytes = vfs_user_move( false,               // from buffer to mapper
                                file_xp,
                                vaddr, 
                                count );
        if ( nbytes != count )
        {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : thread[%x,%x] cannot write %d bytes into file %d\n",
__FUNCTION__ , process->pid, this->trdid, count, file_id );
#endif
            hal_restore_irq( save_sr );
            this->errno = EIO;
            return -1;

        }

        // update file size in inode descriptor
        // only if (file_offset + count) > current_size
        // note: the parent directory entry in mapper will
        // be updated by the close syscall      
        xptr_t inode_xp = XPTR( file_cxy , inode_ptr );
        vfs_inode_update_size( inode_xp , file_offset + count );
    }
    else if( file_type == INODE_TYPE_DEV )  // write to TXT device
    {
        // move count bytes to device
        nbytes = devfs_user_move( false,             // from buffer to device
                                  file_xp,
                                  vaddr,
                                  count );
        if( nbytes != count )
        {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : thread[%x,‰x] cannot write data to file %d\n",
__FUNCTION__ , process->pid, this->trdid, file_id );
#endif
            hal_restore_irq( save_sr );
            this->errno = EIO;
            return -1;
        }
    }
    else  // not FILE and not DEV
    {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : thread[%x,%x] / illegal inode type %\n",
__FUNCTION__, vfs_inode_type_str( file_type ) );
#endif
        hal_restore_irq( save_sr );
		this->errno = EBADFD;
		return -1;
    }

    // restore IRQs
    hal_restore_irq( save_sr );

    hal_fence();

#if (DEBUG_SYS_WRITE || CONFIG_INSTRUMENTATION_SYSCALLS)
uint64_t     tm_end = hal_get_cycles();
#endif

#if DEBUG_SYS_WRITE
if( DEBUG_SYS_WRITE < tm_end )
printk("\n[%s] thread[%x,%x] exit / cycle %d\n",
__FUNCTION__, process->pid, this->trdid, (uint32_t)tm_end );
#endif
 
#if CONFIG_INSTRUMENTATION_SYSCALLS
hal_atomic_add( &syscalls_cumul_cost[SYS_WRITE] , tm_end - tm_start );
hal_atomic_add( &syscalls_occurences[SYS_WRITE] , 1 );
#endif

#if (DEBUG_SYS_WRITE & 1) 
exit_sys_write = (uint32_t)tm_end;

printk("\n***** timing to write a string *****\n"
" - enter_sys_write          = %d / delta %d\n"
" - enter_devfs_write        = %d / delta %d\n"
" - enter_txt_write          = %d / delta %d\n"
" - enter_chdev_cmd_write    = %d / delta %d\n"
" - enter_chdev_server_write = %d / delta %d\n"
" - enter_tty_cmd_write      = %d / delta %d\n"
" - enter_tty_isr_write      = %d / delta %d\n"
" - exit_tty_isr_write       = %d / delta %d\n"
" - exit_tty_cmd_write       = %d / delta %d\n"
" - exit_chdev_server_write  = %d / delta %d\n"
" - exit_chdev_cmd_write     = %d / delta %d\n"
" - exit_txt_write           = %d / delta %d\n"
" - exit_devfs_write         = %d / delta %d\n"
" - exit_sys_write           = %d / delta %d\n",
enter_sys_write          , 0 ,
enter_devfs_write        , enter_devfs_write        - enter_sys_write          ,
enter_txt_write          , enter_txt_write          - enter_devfs_write        ,
enter_chdev_cmd_write    , enter_chdev_cmd_write    - enter_txt_write          ,
enter_chdev_server_write , enter_chdev_server_write - enter_chdev_cmd_write    ,
enter_tty_cmd_write      , enter_tty_cmd_write      - enter_chdev_server_write ,
enter_tty_isr_write      , enter_tty_isr_write      - enter_tty_cmd_write      ,
exit_tty_isr_write       , exit_tty_isr_write       - enter_tty_isr_write      ,
exit_tty_cmd_write       , exit_tty_cmd_write       - exit_tty_isr_write       ,
exit_chdev_server_write  , exit_chdev_server_write  - exit_tty_cmd_write       ,
exit_chdev_cmd_write     , exit_chdev_cmd_write     - exit_chdev_server_write  ,
exit_txt_write           , exit_txt_write           - exit_chdev_cmd_write     ,
exit_devfs_write         , exit_devfs_write         - exit_txt_write           ,
exit_sys_write           , exit_sys_write           - exit_devfs_write         );
#endif
 
	return nbytes;

}  // end sys_write()
