/*
 * sys_thread_create.c - creates a new user thread
 *
 * 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_uspace.h>
#include <printk.h>
#include <errno.h>
#include <core.h>
#include <cluster.h>
#include <list.h>
#include <xlist.h>
#include <thread.h>
#include <scheduler.h>
#include <kmem.h>
#include <process.h>
#include <spinlock.h>
#include <dqdt.h>
#include <rpc.h>


///////////////////////////////////////////////////
int sys_thread_create ( pthread_t      * trdid_ptr,
                        pthread_attr_t * user_attr,
                        void           * start_func,
                        void           * start_arg )
{
	pthread_attr_t   kern_attr;        // copy of pthread attributes in kernel space
	thread_t       * parent;           // pointer on thread executing the pthread_create
	xptr_t           parent_xp;        // extended pointer on created thread
	thread_t       * child_ptr;        // pointer on created child thread
	xptr_t           child_xp;         // extended pointer on created thread
	trdid_t          trdid;            // created thread identifier
	process_t      * process;          // pointer on local process descriptor
	vseg_t         * vseg;             // required for user space checking
    cxy_t            target_cxy;       // target cluster identifier
	error_t          error;

	// get parent thead pointer, extended pointer, and process 
	parent     = CURRENT_THREAD;
	parent_xp  = XPTR( local_cxy , parent );
	process    = parent->process;

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

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

    if ( error )
    {

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

	// check user_attr buffer in user space & copy to kernel space
    if( user_attr != NULL )
    {
	    error = vmm_get_vseg( process , (intptr_t)user_attr , &vseg );

	    if( error )
	    {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : user_attr buffer unmapped %x / thread %x / process %x\n",
__FUNCTION__ , (intptr_t)user_attr , parent->trdid , process->pid );
vmm_display( process , false );
#endif
		    parent->errno = EINVAL;
		    return -1;
	    }
        
	    hal_copy_from_uspace( &kern_attr , user_attr , sizeof(pthread_attr_t) );
    }

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

    if( error )
    {

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

	// check start_arg buffer in user space
	if( start_arg != NULL )
    {
        error = vmm_get_vseg( process , (intptr_t)start_arg , &vseg );

   	    if( error )
	    {

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

    // define attributes and target_cxy
    if( user_attr != NULL )                      // user defined attributes
    {
	    // check / get target_cxy
	    if( kern_attr.attributes & PT_ATTR_CLUSTER_DEFINED )
	    {
		    if( cluster_is_undefined( kern_attr.cxy ) )
		    {

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : illegal target cluster = %x / thread %x / process %x\n",
__FUNCTION__ , kern_attr.cxy, parent->trdid, process->pid );
#endif
			    parent->errno = EINVAL;
			    return -1;
            }
            target_cxy = kern_attr.cxy;
		}
        else
        {
            target_cxy = dqdt_get_cluster_for_process();
        }
	}
	else                                        // set default attributes
	{
        kern_attr.attributes = PT_ATTR_DETACH | PT_ATTR_CLUSTER_DEFINED;
        target_cxy           = dqdt_get_cluster_for_process();
	}

	// create the thread, using a RPC if required
	// this returns "error", "child_ptr", and "child_xp"

	if( target_cxy == local_cxy )                         // target cluster is local
	{
		// create thread in local cluster
		error = thread_user_create( process->pid,
		                            start_func,
		                            start_arg,
		                            &kern_attr,
		                            &child_ptr );

		child_xp = XPTR( local_cxy , child_ptr );
	}
	else                                                 // target cluster is remote
	{
		rpc_thread_user_create_client( target_cxy,
		                               process->pid,
		                               start_func,
		                               start_arg,
		                               &kern_attr,
		                               &child_xp,
		                               &error );

		child_ptr = (thread_t *)GET_PTR( child_xp );
	}

	// check successful thread creation
	if( error )
	{

#if DEBUG_SYSCALLS_ERROR
printk("\n[ERROR] in %s : cannot create new thread / thread %x / process %x\n",
__FUNCTION__ , parent->trdid, process->pid );
#endif
		parent->errno = ENOMEM;
		return -1;
	}

	// returns trdid to user space
	trdid = hal_remote_lw( XPTR( target_cxy , &child_ptr->trdid ) );
	hal_copy_to_uspace( trdid_ptr , &trdid , sizeof(pthread_t) );

    // activate new thread
	thread_unblock( child_xp , THREAD_BLOCKED_GLOBAL );

    hal_fence();

#if DEBUG_SYS_THREAD_CREATE
tm_end = hal_get_cycles();
if( DEBUG_SYS_THREAD_CREATE < tm_end )
printk("\n[DBG] %s : thread %x (cxy %x) created thread %x (cxy %x) / process %x / cycle %d\n",
__FUNCTION__, parent, local_cxy, child_ptr, target_cxy, process->pid, (uint32_t)tm_end );
#endif

	return 0;

}  // end sys_thread_create()

