/*
 * sys_kill.c - Kernel function implementing the "kill" 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_irqmask.h>
#include <errno.h>
#include <thread.h>
#include <printk.h>
#include <process.h>
#include <shared_syscalls.h>
#include <cluster.h>
#include <rpc.h>

#include <syscalls.h>


#if DEBUG_SYS_KILL
////////////////////////////////////////////
static char* sig_type_str( uint32_t sig_id )
{
    switch( sig_id )
    {
        case SIGKILL: return "SIGKILL";
        case SIGSTOP: return "SIGSTOP";
        case SIGCONT: return "SIGCONT";
        default:      return "undefined";
    }
}
#endif


///////////////////////////
int sys_kill( pid_t    pid,
              uint32_t sig_id )
{
    xptr_t      owner_xp;          // extended pointer on process in owner cluster
    cxy_t       owner_cxy;         // process owner cluster
    process_t * owner_ptr;         // local pointer on process in owner cluster
    xptr_t      parent_xp;         // extended pointer on parent process
    cxy_t       parent_cxy;        // parent process cluster
    process_t * parent_ptr;        // local pointer on parent process
    thread_t  * parent_main_ptr;   // local pointer on parent main thread
    xptr_t      parent_main_xp;    // extended pointer on parent main thread

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

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

#if DEBUG_SYS_KILL
tm_start = hal_get_cycles();
if( DEBUG_SYS_KILL < tm_start )
printk("\n[DBG] %s : thread[%x,%x] enter / process %x / %s / cycle %d\n",
__FUNCTION__, this->process->pid, this->trdid, pid,
sig_type_str(sig_id), (uint32_t)tm_start );
#endif

    // get pointers on process descriptor in owner cluster
    owner_xp  = cluster_get_owner_process_from_pid( pid );
    owner_cxy = GET_CXY( owner_xp );
    owner_ptr = GET_PTR( owner_xp );
    
#if (DEBUG_SYS_KILL & 1)
if( DEBUG_SYS_KILL < tm_start )
printk("\n[DBG] %s : thread[%x,%x] get owner process %x in cluster %x\n",
__FUNCTION__ , this->process->pid, this->trdid, owner_ptr, owner_cxy );
#endif

    // check process found
    if( owner_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;
    }

    // get parent process descriptor pointers
    parent_xp  = (xptr_t)hal_remote_l64( XPTR( owner_cxy , &owner_ptr->parent_xp ) );
    parent_cxy = GET_CXY( parent_xp );
    parent_ptr = GET_PTR( parent_xp );

#if (DEBUG_SYS_KILL & 1)
if( DEBUG_SYS_KILL < tm_start )
printk("\n[DBG] %s : thread[%x,%x] get parent process %x in cluster %x\n",
__FUNCTION__ , this->process->pid, this->trdid, parent_ptr, parent_cxy );
#endif

    // get pointers on the parent process main thread
    parent_main_ptr = hal_remote_lpt( XPTR( parent_cxy , &parent_ptr->th_tbl[0] ) ); 
    parent_main_xp  = XPTR( parent_cxy , parent_main_ptr );

    // analyse signal type / supported values are : 0, SIGSTOP, SIGCONT, SIGKILL
    switch( sig_id )
    {
        case 0 :          // does nothing
        {
            break;
        }
        case SIGSTOP:     // block all target process threads
        {
            // block all threads in all clusters
            process_sigaction( pid , BLOCK_ALL_THREADS );

            // atomically update owner process termination state
            hal_remote_atomic_or( XPTR( owner_cxy , &owner_ptr->term_state ) ,
                                  PROCESS_TERM_STOP );

            // unblock the parent process main thread
            thread_unblock( parent_main_xp , THREAD_BLOCKED_WAIT );

            break;
        }
        case SIGCONT:     // unblock all target process threads
        {
            // unblock all threads in all clusters
            process_sigaction( pid , UNBLOCK_ALL_THREADS );

            // atomically update owner process termination state
            hal_remote_atomic_and( XPTR( owner_cxy , &owner_ptr->term_state ) ,
                                   ~PROCESS_TERM_STOP );

            // unblock the parent process main thread 
            thread_unblock( parent_main_xp , THREAD_BLOCKED_WAIT );

            break;
        }
        case SIGKILL:
        {
            // a process cannot kill itself
            if( (pid == process->pid) ) 
            {

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

            // processe INIT cannot be killed
            if( pid == 1 )
            {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : process_init cannot be killed\n", __FUNCTION__ );
#endif
		        this->errno = EINVAL;
                return -1;
            }

            // remove process from TXT list
            process_txt_detach( owner_xp );

            // mark for delete all threads in all clusters, but the main 
            process_sigaction( pid , DELETE_ALL_THREADS );

            // block main thread
            xptr_t main_xp = XPTR( owner_cxy , &owner_ptr->th_tbl[0] );
            thread_block( main_xp , THREAD_BLOCKED_GLOBAL );

            // atomically update owner process descriptor term_state to ask
            // the parent process sys_wait() function to delete this main thread
            hal_remote_atomic_or( XPTR( owner_cxy , &owner_ptr->term_state ) ,
                                  PROCESS_TERM_KILL );

            // unblock the parent process main thread 
            thread_unblock( parent_main_xp , THREAD_BLOCKED_WAIT );

            break;
        }
        default:
        {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : illegal signal %d / process %x\n", __FUNCTION__, sig_id, pid );
#endif
    	    this->errno = EINVAL;
            return -1;
        }
    }
    
    hal_fence();

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

#if DEBUG_SYS_KILL
if( DEBUG_SYS_KILL < tm_end )
printk("\n[DBG] %s : thread[%x,%x] exit / process %x / %s / cost = %d / cycle %d\n",
__FUNCTION__ , this->process->pid, this->trdid, pid,
sig_type_str(sig_id), (uint32_t)(tm_end - tm_start), (uint32_t)tm_end );
#endif

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

	return 0;

}  // end sys_kill()

