/*
 * sys_wait.c - wait termination or blocking of a child process.
 * 
 * Author    Alain Greiner (2016,2017)
 *  
 * 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_types.h>
#include <hal_uspace.h>
#include <core.h>
#include <thread.h>
#include <process.h>
#include <vmm.h>
#include <printk.h>

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

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

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

    // check status in user space
    error = vmm_v2p_translate( false , status , &paddr );

	if( error )
	{
        printk("\n[ERROR] in %s : status buffer unmapped for thread %x in process %x\n",
        __FUNCTION__ , this->trdid , process->pid );
        this->errno = EFAULT;
		return -1;
	}

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

    // This function must be executed in owner cluster
    assert( (owner_cxy == local_cxy) , __FUNCTION__ , 
    "calling thread must execute in owner cluster" );

    // This function must be executed by the main thread
    assert( (process->th_tbl[0] == this) , __FUNCTION__ ,
    "this function must be executed by the main thread" );
   
    // 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 )
    {
        // get lock protecting children list
        remote_spinlock_lock( children_lock_xp );

        // scan the list of owner 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 term_state from child owner process
            child_state = (int)hal_remote_lw ( XPTR(child_cxy,&child_ptr->term_state));

            // test if child process is terminated,
            // but termination not yet reported to parent process
            if( ((child_state & PROCESS_FLAG_EXIT)   || 
                 (child_state & PROCESS_FLAG_KILL)   ||
                 (child_state & PROCESS_FLAG_BLOCK)) &&
                 ((child_state & PROCESS_FLAG_WAIT) == 0) )
            {
                // get pointer on main thread and PID from child owner process
                child_pid    = (pid_t)     hal_remote_lw ( XPTR(child_cxy,&child_ptr->pid));
                child_thread = (thread_t *)hal_remote_lpt( XPTR(child_cxy,&child_ptr->th_tbl[0]));

                // set the PROCESS_FLAG_WAIT in owner child descriptor
                hal_remote_atomic_or( XPTR( child_cxy , &child_ptr->term_state ),
                                      PROCESS_FLAG_WAIT );

                // set the THREAD_FLAG_REQ_DELETE in child main thread
                hal_remote_atomic_or( XPTR( child_cxy , &child_thread->flags ) ,
                                            THREAD_FLAG_REQ_DELETE );

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

                 // return relevant info to calling parent process 
                 hal_copy_to_uspace( status , &child_state , sizeof(int) );
                 return child_pid;
            }
        }
        
        // release lock
        remote_spinlock_unlock( children_lock_xp );

        // deschedule without blocking
        sched_yield( "parent wait children termination" );
    }

    // never executed
	return -1; 

}  // end sys_wait()
