/*
 * sys_fg.c - Kernel function implementing the "is_fg" system call.
 * 
 * Author    Alain Greiner (2016,2017,2018)
 *
 * 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_uspace.h>
#include <hal_special.h>
#include <errno.h>
#include <thread.h>
#include <printk.h>
#include <process.h>
#include <vseg.h>
#include <shared_syscalls.h>
#include <cluster.h>

//////////////////////////////
int sys_is_fg( pid_t      pid,
               uint32_t * is_fg )
{
    xptr_t      process_xp;       // extended pointer on process descriptor in owner cluster
    uint32_t    is_txt_owner;     // kernel buffer for is_fg
    vseg_t    * vseg;             // for buffer mapping check
    error_t     error;

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

#if DEBUG_SYS_IS_FG
uint64_t    tm_start;
uint64_t    tm_end;
tm_start = hal_get_cycles();
if( DEBUG_SYS_FG < tm_start )
printk("\n[DBG] %s : thread %x in process %x enter for pid %x / cycle %d\n",
__FUNCTION__ , this->trdid , process->pid, pid, (uint32_t)tm_start );
#endif

    // check buffer in user vspace
	error = vmm_get_vseg( process , (intptr_t)is_fg , &vseg );
    if( error )
    {

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

    // check target process existence
    process_xp = cluster_get_owner_process_from_pid( pid );

    if( process_xp == XPTR_NULL )
    {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : process %x not found\n", __FUNCTION__ , pid );
#endif
        this->errno = EINVAL;
        return -1;
    }
    
    // call relevant kernel function
    is_txt_owner = process_txt_is_owner( process_xp );

    // copy to user space
    hal_copy_to_uspace( is_fg , &is_txt_owner , sizeof(uint32_t) );

    hal_fence();

#if DEBUG_SYS_IS_FG
tm_end = hal_get_cycles();
if( DEBUG_SYS_FG < tm_end )
printk("\n[DBG] %s : thread %x in process %x exit / is_txt_owner %d / cycle %d\n",
__FUNCTION__, this->trdid, process->pid, is_txt_owner, (uint32_t)tm_end );
#endif

	return 0;

}  // end sys_is_fg()

