/*
 * sys_mutex.c - Access a POSIX mutex.
 * 
 * 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 <hal_kernel_types.h>
#include <hal_special.h>
#include <hal_vmm.h>
#include <errno.h>
#include <thread.h>
#include <printk.h>
#include <vmm.h>
#include <syscalls.h>
#include <remote_mutex.h>


#if DEBUG_SYS_MUTEX
////////////////////////////////////////////////////
static char * sys_mutex_op_str( uint32_t operation )
{
  	if     ( operation == MUTEX_INIT     ) return "INIT";
  	else if( operation == MUTEX_LOCK     ) return "LOCK";
  	else if( operation == MUTEX_UNLOCK   ) return "UNLOCK";
  	else if( operation == MUTEX_TRYLOCK  ) return "TRYLOCK";
  	else if( operation == MUTEX_DESTROY  ) return "DESTROY";
  	else                                   return "undefined";
}
#endif

/////////////////////////////////
int sys_mutex( void     * vaddr,
               uint32_t   operation,
               uint32_t   attr )
{
	error_t     error;
    vseg_t    * vseg;      // for vaddr check

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

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

#if DEBUG_SYS_MUTEX
if( DEBUG_SYS_MUTEX < tm_start )
printk("\n[%s] thread[%x,%x] enter for %s / cycle %d\n",
__FUNCTION__, this->trdid, process->pid, sys_mutex_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 : mutex unmapped %x / thread %x / process %x\n",
__FUNCTION__ , (intptr_t)vaddr , this->trdid , process->pid );
#endif
        this->errno = error;
        return -1;
    }

    // execute requested operation
	switch( operation )
	{   
        //////////////// 
	    case MUTEX_INIT:
        { 
            if( attr != 0 )
            {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : mutex attribute non supported / thread %x / process %x\n",
__FUNCTION__ , this->trdid , process->pid );
#endif
                this->errno = error;
                return -1;
            }
   
            error = remote_mutex_create( (intptr_t)vaddr );

            if( error )
            {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : cannot create mutex / thread %x / process %x\n",
__FUNCTION__ , this->trdid , process->pid );
#endif
                this->errno = error;
                return -1;
            } 
		    break;
		}
        ///////////////////
	    case MUTEX_DESTROY:
        {
            xptr_t mutex_xp = remote_mutex_from_ident( (intptr_t)vaddr );

            if( mutex_xp == XPTR_NULL )     // user error
            {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : mutex %x not registered / thread %x / process %x\n",
__FUNCTION__ , (intptr_t)vaddr , this->trdid , process->pid );
#endif
                this->errno = EINVAL;
                return -1;
            }
            else                          // success
            {
                remote_mutex_destroy( mutex_xp ); 
            }
            break;
        }
        ////////////////
	    case MUTEX_LOCK:
        {
            xptr_t mutex_xp = remote_mutex_from_ident( (intptr_t)vaddr );

            if( mutex_xp == XPTR_NULL )     // user error
            {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : mutex %x not registered / thread %x / process %x\n",
__FUNCTION__ , (intptr_t)vaddr , this->trdid , process->pid );
#endif
                this->errno = EINVAL;
                return -1;
            }
            else                          // success
            {
                remote_mutex_lock( mutex_xp ); 
            }
            break;
        }
        //////////////////
	    case MUTEX_UNLOCK:
        {
            xptr_t mutex_xp = remote_mutex_from_ident( (intptr_t)vaddr );

            if( mutex_xp == XPTR_NULL )     // user error
            {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : mutex %x not registered / thread %x / process %x\n",
__FUNCTION__ , (intptr_t)vaddr , this->trdid , process->pid );
#endif
                this->errno = EINVAL;
                return -1;
            }
            else                          // success
            {
                error = remote_mutex_unlock( mutex_xp ); 

                if( error )
                {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : mutex %x not owned in UNLOCK / thread %x / process %x\n",
__FUNCTION__ , (intptr_t)vaddr , this->trdid , process->pid );
#endif
                    this->errno = EINVAL;
                    return -1;
                }
            }
            break;
        }
        ///////////////////
	    case MUTEX_TRYLOCK:
        {
            xptr_t mutex_xp = remote_mutex_from_ident( (intptr_t)vaddr );

            if( mutex_xp == XPTR_NULL )     // user error
            {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : mutex %x not registered / thread %x / process %x\n",
__FUNCTION__ , (intptr_t)vaddr , this->trdid , process->pid );
#endif
                this->errno = EINVAL;
                return -1;
            }
            else                          // success
            {
                error = remote_mutex_trylock( mutex_xp ); 

                if( error ) // non fatal : mutex already taken
                {
                    this->errno = EBUSY;
                    return -1; 
                }
            }
            break;
        }
        ////////
        default: 
        {
            assert( __FUNCTION__, false, "illegal operation type <%x>", operation );
        }
	}

    hal_fence();

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

#if DEBUG_SYS_MUTEX
if( DEBUG_SYS_MUTEX < tm_end )
printk("\n[%s] thread[%x,%x] exit for %s / cycle %d\n",
__FUNCTION__, this->trdid, process->pid, sys_mutex_op_str( operation ), (uint32_t)tm_end );
#endif

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

	return 0;

}  // end sys_mutex()

