/*
 * 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 <hal_irqmask.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;
    reg_t       save_sr;

    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 )
	{

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

    // get process owner cluster and calling thread trdid
    cxy_t   owner_cxy = CXY_FROM_PID( pid );
    trdid_t trdid     = this->trdid;

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

#if CONFIG_DEBUG_SYSCALL_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 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_TERM_EXIT)  || 
                 (child_state & PROCESS_TERM_KILL)  ||
                 (child_state & PROCESS_TERM_STOP)) &&
                 ((child_state & PROCESS_TERM_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_TERM_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 );

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

#if CONFIG_DEBUG_SYS_WAIT 
tm_end = hal_get_cycles();
if( CONFIG_DEBUG_SYS_WAIT < tm_end )
printk("\n[DBG] %s : thread %x exit / parent %x / child %x / cycle %d\n",
__FUNCTION__, this, process->pid, child_pid, (uint32_t)tm_end );
#endif
                 // return child termination state  to parent process 
                 hal_copy_to_uspace( status , &child_state , sizeof(int) );
                 return child_pid;
            }
        }  // end loop on children
        
        // release lock protecting children list 
        remote_spinlock_unlock( children_lock_xp );

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

    }  // end while

    // never executed
	return -1; 

}  // end sys_wait()
