/*
 * sys_wait.c - wait termination or blocking of a child process.
 * 
 * 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 <hal_kernel_types.h>
#include <hal_uspace.h>
#include <hal_irqmask.h>
#include <core.h>
#include <thread.h>
#include <process.h>
#include <vmm.h>
#include <printk.h>

#include <syscalls.h>

/////////////////////////////////
int sys_wait( uint32_t * status )
{
	error_t     error;
    vseg_t    * vseg;
    xptr_t      iter_xp;
    xptr_t      child_xp;
    process_t * child_ptr;
    cxy_t       child_cxy;
    pid_t       child_pid;
    uint32_t    child_state;
    thread_t  * child_thread;
    reg_t       save_sr;

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

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

    // check status in user space
    error = vmm_get_vseg( process, (intptr_t)status , &vseg );

	if( error )
	{

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

    // get calling process owner cluster
    cxy_t   owner_cxy = CXY_FROM_PID( pid );

    // get calling thread trdid
    trdid_t trdid = this->trdid;

    // this function must be executed by the process main thread
    if( (owner_cxy != local_cxy) || (LTID_FROM_TRDID(trdid) != 0) )
    {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : calling thread %x is not thread 0 in owner cluster %x\n",
__FUNCTION__ , trdid , owner_cxy );
#endif
        this->errno = EINVAL;
		return -1;
	}

    // get extended pointer on children list root and lock
    xptr_t children_root_xp = XPTR( owner_cxy , &process->children_root );
    xptr_t children_lock_xp = XPTR( owner_cxy , &process->children_lock );

    // exit this blocking loop only when a child processes change state
    while( 1 )
    {
        // enable IRQS
        hal_enable_irq( &save_sr );
 
        // get lock protecting children list
        remote_spinlock_lock( children_lock_xp );

        // scan the list of child process
        XLIST_FOREACH( children_root_xp , iter_xp )
        {
            // get child process owner cluster and local pointer 
            child_xp  = XLIST_ELEMENT( iter_xp , process_t , children_list );
            child_ptr = GET_PTR( child_xp );
            child_cxy = GET_CXY( child_xp );

            // get PID, term_state, and main thread from child process
            child_pid    = hal_remote_lw (XPTR( child_cxy , &child_ptr->pid ));
            child_state  = hal_remote_lw ( XPTR(child_cxy , &child_ptr->term_state ) );
            child_thread = hal_remote_lpt(XPTR( child_cxy , &child_ptr->th_tbl[0] ));

#if (DEBUG_SYS_WAIT &1)
cycle = hal_get_cycles();
if( DEBUG_SYS_WAIT < cycle )
printk("\n[DBG] %s : thread %x in process %x check child %x / state %x\n",
__FUNCTION__, this, process->pid, child_pid, child_state );
#endif
            // test if this child process is terminated,
            // but termination not yet reported to parent process
            if( ((child_state & PROCESS_TERM_EXIT)  || 
                 (child_state & PROCESS_TERM_KILL)  ||
                 (child_state & PROCESS_TERM_STOP)) &&
                 ((child_state & PROCESS_TERM_WAIT) == 0) )
            {
                // set the PROCESS_FLAG_WAIT in child process descriptor
                hal_remote_atomic_or( XPTR( child_cxy , &child_ptr->term_state ),
                                      PROCESS_TERM_WAIT );

                // set the THREAD_FLAG_REQ_DELETE in main thread if kill or exit
                if((child_state & PROCESS_TERM_EXIT) || (child_state & PROCESS_TERM_KILL))
                hal_remote_atomic_or( XPTR( child_cxy , &child_thread->flags ) ,
                                            THREAD_FLAG_REQ_DELETE );

                // release lock protecting children list
                remote_spinlock_unlock( children_lock_xp );

#if DEBUG_SYS_WAIT 
cycle = hal_get_cycles();
if( DEBUG_SYS_WAIT < cycle )
{
    if     ( child_state & PROCESS_TERM_EXIT )
        printk("\n[DBG] %s : thread %x in process %x exit / child %x exit / cycle %d\n",
        __FUNCTION__, this, process->pid, child_pid, (uint32_t)cycle );
    if( child_state & PROCESS_TERM_KILL )
        printk("\n[DBG] %s : thread %x in process %x exit / child %x killed / cycle %d\n",
        __FUNCTION__, this, process->pid, child_pid, (uint32_t)cycle );
    if( child_state & PROCESS_TERM_STOP )
        printk("\n[DBG] %s : thread %x in process %x exit / child %x stopped / cycle %d\n",
        __FUNCTION__, this, process->pid, child_pid, (uint32_t)cycle );
}
#endif
                 // return child termination state  to parent process 
                 hal_copy_to_uspace( status , &child_state , sizeof(int) );
                 return child_pid;
            }
        }  // end loop on children
        
        // block on WAIT condition
        thread_block( XPTR( local_cxy , this ) , THREAD_BLOCKED_WAIT );

        // release lock protecting children list 
        remote_spinlock_unlock( children_lock_xp );

#if (DEBUG_SYS_WAIT & 1)
cycle = hal_get_cycles();
if( DEBUG_SYS_WAIT < cycle )
printk("\n[DBG] %s : thread %x in process %x block & deschedule / cycle %d\n",
__FUNCTION__, this, process->pid, (uint32_t)cycle );
#endif

        // deschedule
        sched_yield( "parent process wait children processes termination" );

#if (DEBUG_SYS_WAIT & 1) 
cycle = hal_get_cycles();
if( DEBUG_SYS_WAIT < cycle )
printk("\n[DBG] %s : thread %x in process %x unblock & resume / cycle %d\n",
__FUNCTION__, this, process->pid, (uint32_t)cycle );
#endif

    }  // end while

    // never executed
	return -1; 

}  // end sys_wait()
