/*
 * sys_sem.c - Acces a POSIX unamed semaphore.
 * 
 * Authors     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 <hal_kernel_types.h>
#include <hal_uspace.h>
#include <shared_semaphore.h>
#include <errno.h>
#include <thread.h>
#include <printk.h>
#include <vmm.h>
#include <remote_sem.h>
#include <syscalls.h>

#if DEBUG_SYS_SEM
//////////////////////////////////////////////////
static char * sys_sem_op_str( uint32_t operation )
{
  	if     ( operation == SEM_INIT     ) return "INIT";
  	else if( operation == SEM_WAIT     ) return "WAIT";
  	else if( operation == SEM_POST     ) return "POST";
  	else if( operation == SEM_GETVALUE ) return "GETVALUE";
  	else if( operation == SEM_DESTROY  ) return "DESTROY";
  	else                                 return "undefined";
}
#endif

//////////////////////////////////
int sys_sem( void         * vaddr,            // semaphore virtual  address 
             uint32_t       operation,        // requested operation type
             uint32_t       init_value,       // initial value
             uint32_t     * current_value )   // pointer on current value buffer
{
	vseg_t         * vseg;
    error_t          error;
    uint32_t         current;     // semaphore current value
    xptr_t           sem_xp;      // extended pointer on semaphore 

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

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

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

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : unmapped semaphore pointer %x / thread %x in process %x / cycle %d\n",
__FUNCTION__ , (intptr_t)vaddr, this->trdid, process->pid, (uint32_t)hal_get_cycles() );
vmm_display( process , false );
#endif
        this->errno = EINVAL;
        return -1;
    }

    // execute requested operation
	switch( operation )
	{
        //////////////
	    case SEM_INIT:
        {
            // call relevant kernel function to initialize semaphore
            error = remote_sem_create( (intptr_t)vaddr , 
                                       init_value,
                                       XPTR( local_cxy , &sem_xp ) );

            if ( error )
            {

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

            break;
        }
        //////////////////
        case SEM_GETVALUE:
        {
            // check current_value buffer in user vspace
	        error = vmm_get_vseg( process , (intptr_t)current_value , &vseg );
            if( error )
            {

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

            // get extended pointer on remote semaphore
            sem_xp = remote_sem_from_vaddr( (intptr_t)vaddr );

            // check semaphore registered
            if( sem_xp == XPTR_NULL )
            {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s GETVALUE: semaphore %x not found / thread %x in process %x / cycle %d\n",
__FUNCTION__ , (intptr_t)vaddr, this->trdid, process->pid, (uint32_t)hal_get_cycles() );
#endif
                this->errno = EINVAL;
                return -1;
            }

            // call relevant kernel function to get semaphore current value
		    remote_sem_get_value( sem_xp , &current );
 
            // return value to user
            hal_copy_to_uspace( current_value , &current , sizeof(uint32_t) );

            break;
        }
        //////////////
	    case SEM_WAIT:
        {  
            // get extended pointer on remote semaphore
            sem_xp = remote_sem_from_vaddr( (intptr_t)vaddr );

            // check semaphore registered
            if( sem_xp == XPTR_NULL )
            {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s WAIT: semaphore %x not found / thread %x in process %x / cycle %d\n",
__FUNCTION__ , (intptr_t)vaddr, this->trdid, process->pid, (uint32_t)hal_get_cycles() );
vmm_display( process , true );
#endif
                this->errno = EINVAL;
                return -1;
            }

            // call relevant kernel function to wait semaphore available
            remote_sem_wait( sem_xp );
            
            break;
        }
        //////////////
	    case SEM_POST:
        {
            // get extended pointer on remote semaphore
            sem_xp = remote_sem_from_vaddr( (intptr_t)vaddr );

            // check semaphore registered
            if( sem_xp == XPTR_NULL )
            {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s POST: semaphore %x not found / thread %x in process %x / cycle %d\n",
__FUNCTION__ , (intptr_t)vaddr, this->trdid, process->pid, (uint32_t)hal_get_cycles() );
#endif
                this->errno = EINVAL;
                return -1;
            }

            // call relevant kernel function to release semaphore 
            remote_sem_post( sem_xp );

			break;
        }
        /////////////////
	    case SEM_DESTROY:
        {
            // get extended pointer on remote semaphore
            sem_xp = remote_sem_from_vaddr( (intptr_t)vaddr );

            // check semaphore registered
            if( sem_xp == XPTR_NULL )
            {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s DESTROY: semaphore %x not found / thread %x in process %x / cycle %d\n",
__FUNCTION__ , (intptr_t)vaddr, this->trdid, process->pid, (uint32_t)hal_get_cycles() );
#endif
                this->errno = EINVAL;
                return -1;
            }

            // destroy semaphore
            remote_sem_destroy( sem_xp );

            break;
	    }	
        ///////
	    default:  // undefined operation                       
        {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : undefined operation type %d / thread %x in process %x / cycle %d\n",
__FUNCTION__ , operation, this->trdid, process->pid, (uint32_t)hal_get_cycles() );
#endif
            this->errno = EINVAL;
            return -1;
        }
	}

    hal_fence();

#if DEBUG_SYS_SEM
tm_end = hal_get_cycles();
if( DEBUG_SYS_SEM < tm_end )
{
    cxy_t          sem_cxy = GET_CXY( sem_xp );
    remote_sem_t * sem_ptr = GET_PTR( sem_xp );
    uint32_t       value   = hal_remote_lw( XPTR( sem_cxy , &sem_ptr->count ) ); 
    printk("\n[DBG] %s : thread %x in process %x exit for %s / value %d / cost = %d / cycle %d\n",
    __FUNCTION__, this->trdid, process->pid, sys_sem_op_str( operation ), value, 
    (uint32_t)(tm_end - tm_start), (uint32_t)tm_end );
}
#endif

    return 0;

}  // end sys_sem()
