/*
 * sys_mmap.c - map files, memory or devices into process virtual address space
 * 
 * Authors       Alain Greiner (2016,2017,2018,2019,2020)
 *
 * 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 <hal_kernel_types.h>
#include <hal_uspace.h>
#include <hal_vmm.h>
#include <hal_irqmask.h>
#include <errno.h>
#include <thread.h>
#include <printk.h>
#include <mapper.h>
#include <vfs.h>
#include <process.h>
#include <vmm.h>

#include <syscalls.h>
#include <shared_syscalls.h>

//////////////////////////////////
int sys_mmap( mmap_attr_t * attr )
{
    vseg_t      * vseg;
    cxy_t         vseg_cxy;     // target cluster for the vseg
    vseg_type_t   vseg_type;    // vseg type
    mmap_attr_t   k_attr;       // attributes copy in kernel space
    xptr_t        mapper_xp;
    reg_t         save_sr;      // required to enable IRQs

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

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

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

    // check user buffer (containing attributes) is mapped 
    if( vmm_get_vseg( process , (intptr_t)attr , &vseg ) )
    {

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

    // copy attributes from user space to kernel space
    hal_copy_from_uspace( XPTR( local_cxy , &k_attr ),
                          attr,
                          sizeof(mmap_attr_t) );

    // get addr, fdid, offset, and length attributes
    uint32_t  fdid   = k_attr.fdid;
    uint32_t  offset = k_attr.offset;
    uint32_t  length = k_attr.length;

    // get flags
    bool_t     map_fixed   = ( (k_attr.flags & MAP_FIXED)   != 0 );
    bool_t     map_anon    = ( (k_attr.flags & MAP_ANON)    != 0 );
    bool_t     map_remote  = ( (k_attr.flags & MAP_REMOTE)  != 0 );
    bool_t     map_shared  = ( (k_attr.flags & MAP_SHARED)  != 0 );
    bool_t     map_private = ( (k_attr.flags & MAP_PRIVATE) != 0 );

    // MAP_FIXED not supported
    if( map_fixed )
    {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : thread[%x,%x] / MAP_FIXED not supported\n",
__FUNCTION__ , process->pid, this->trdid );
#endif
        this->errno = EINVAL;
        return -1;
    }

    if( map_shared == map_private )
    {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : thread[%x,%x] / MAP_SHARED == MAP_PRIVATE\n",
__FUNCTION__ , process->pid, this->trdid );
#endif
        this->errno = EINVAL;
        return -1;
    }

// FIXME handle Copy_On_Write for MAP_PRIVATE...

    // test mmap type : can be FILE / ANON / REMOTE
    // to define vseg_type & vseg_cxy

    /////////////////////////////////////////////////////////// MAP_FILE
    if( (map_anon == false) && (map_remote == false) )   
    {

#if (DEBUG_SYS_MMAP & 1)
if ( DEBUG_SYS_MMAP < tm_start )
printk("\n[%s] thread[%x,%x] type file : fdid %d / offset %x / %x bytes\n",
__FUNCTION__, process->pid, this->trdid, fdid, offset, length );
#endif

// FIXME: handle concurent delete of file by another thread 

		if( fdid >= CONFIG_PROCESS_FILE_MAX_NR ) 
		{

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

        // get extended pointer on file descriptor
        xptr_t file_xp = process_fd_get_xptr_from_local( process , fdid );

        if( file_xp == XPTR_NULL )
        {

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

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

#if (DEBUG_SYS_MMAP & 1)
if ( DEBUG_SYS_MMAP < tm_start )
printk("\n[%s] thread[%x,%x] get file pointer %x in cluster %x\n",
__FUNCTION__, process->pid, this->trdid, file_ptr, file_cxy );
#endif

        // get mapper pointer 
        mapper_t    * mapper_ptr = hal_remote_lpt(XPTR(file_cxy , &file_ptr->mapper));

#if (DEBUG_SYS_MMAP & 1)
if ( DEBUG_SYS_MMAP < tm_start )
printk("\n[%s] thread[%x,%x] get file mapper %x\n",
__FUNCTION__, process->pid, this->trdid, mapper_ptr );
#endif

/* TODO
        // chek access rigths
        uint32_t   file_attr  = hal_remote_l32(XPTR(file_cxy , &file_ptr->attr  ));
        bool_t     prot_read  = ( (k_attr.prot & PROT_READ )   != 0 );
        bool_t     prot_write = ( (k_attr.prot & PROT_WRITE)   != 0 );

        // check access rights
		if( (prot_read  && !(file_attr & FD_ATTR_READ_ENABLE)) ||
		    (prot_write && !(file_attr & FD_ATTR_WRITE_ENABLE)) )
		{

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s: prot = %x / file_attr = %x / thread %x , process %x\n", 
__FUNCTION__ , k_attr.prot , file_attr , this->trdid , process->pid );
#endif
			this->errno = EACCES;
			return -1;
		}
*/

		// increment file refcount
		vfs_file_count_up( file_xp );

        mapper_xp = XPTR( file_cxy , mapper_ptr );
        vseg_type = VSEG_TYPE_FILE;
        vseg_cxy  = file_cxy;
    }
    ///////////////////////////////////////////////////////// MAP_ANON
    else if ( map_anon )                                 
    {
        mapper_xp = XPTR_NULL;
        vseg_type = VSEG_TYPE_ANON;
        vseg_cxy  = local_cxy;

#if (DEBUG_SYS_MMAP & 1)
if ( DEBUG_SYS_MMAP < tm_start )
printk("\n[%s] thread[%x,%x] type anon / %x bytes / cluster %x\n",
__FUNCTION__, process->pid, this->trdid, length, vseg_cxy );
#endif

    } 
    /////////////////////////////////////////////////////// MAP_REMOTE
    else                                                 
    {
        mapper_xp = XPTR_NULL;
        vseg_type = VSEG_TYPE_REMOTE;
        vseg_cxy  = k_attr.fdid;

#if (DEBUG_SYS_MMAP & 1)
if ( DEBUG_SYS_MMAP < tm_start )
printk("\n[%s] thread[%x,%x] type remote / %x bytes / target cluster %x\n",
__FUNCTION__, process->pid, this->trdid, length, vseg_cxy );
#endif
 
        if( cluster_is_active( vseg_cxy ) == false )
        {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : thread[%x,%x] / illegal cxy %x for REMOTE\n",
__FUNCTION__, this->trdid , process->pid, vseg_cxy );
#endif
            this->errno = EINVAL;
            return -1;
        }
    }

    // enable IRQs
    hal_enable_irq( &save_sr );

    // get reference process cluster and local pointer
    xptr_t      ref_xp  = process->ref_xp;
    cxy_t       ref_cxy = GET_CXY( ref_xp );
    process_t * ref_ptr = GET_PTR( ref_xp );

    // register vseg in reference VSL
    if( local_cxy == ref_cxy )
    {
        vseg = vmm_create_vseg( process,
                                vseg_type,
                                0,               // vseg base (unused for mmap)
                                length,          // vseg size
                                offset,          // file offset
                                0,               // file_size (unused for mmap)
                                mapper_xp,
                                vseg_cxy );
    }
    else
    {
        rpc_vmm_create_vseg_client( ref_cxy,
                                    ref_ptr,
                                    vseg_type,
                                    0,            // vseg base (unused for mmap)
                                    length,       // vseg size
                                    offset,       // file offset
                                    0,            // file size (unused for mmap)
                                    mapper_xp,
                                    vseg_cxy,
                                    &vseg ); 
    }
    
    // restore IRQs
    hal_restore_irq( save_sr );

    if( vseg == NULL )
    {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : thread[%x,%x] / cannot create vseg\n",
__FUNCTION__, process->pid, this->trdid );
#endif
        this->errno = ENOMEM;
        return -1;
    }

    // copy vseg base address to user space mmap_attr_t
    hal_copy_to_uspace( &attr->addr,
                        XPTR( ref_cxy , &vseg->min ),
                        sizeof(intptr_t) );
    hal_fence();

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

#if CONFIG_INSTRUMENTATION_SYSCALLS
hal_atomic_add( &syscalls_cumul_cost[SYS_MMAP] , tm_end - tm_start );
hal_atomic_add( &syscalls_occurences[SYS_MMAP] , 1 );
#endif

#if DEBUG_SYS_MMAP
if ( DEBUG_SYS_MMAP < tm_end )
printk("\n[%s] thread[%x,%x] exit / %s / cxy %x / base %x / size %x / cycle %d\n",
__FUNCTION__, process->pid, this->trdid,
vseg_type_str(vseg->type), vseg->cxy, vseg->min, length, (uint32_t)tm_end );
#endif

        return 0;

}  // end sys_mmap()

