/*
 * process.h - process related functions definition.
 *
 * Authors  Ghassan Almaless (2008,2009,2010,2011,2012)
 *          Mohamed Lamine Karaoui (2015)
 *          Alain Greiner (2016,2017,2018,2019,2020)
 *
 * 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
 */

#ifndef _PROCESS_H_
#define _PROCESS_H_

#include <kernel_config.h>
#include <errno.h>
#include <hal_kernel_types.h>
#include <list.h>
#include <xlist.h>
#include <bits.h>
#include <busylock.h>
#include <rwlock.h>
#include <queuelock.h>
#include <remote_queuelock.h>
#include <remote_rwlock.h>
#include <hal_atomic.h>
#include <vmm.h>
#include <cluster.h>
#include <vfs.h>

/****  Forward declarations  ****/

struct thread_s;

/*********************************************************************************************
 * These macros are used to compose or decompose global process identifier (PID)
 * to or from cluster identifier / local process index (CXY , LPID)
 ********************************************************************************************/

#define LPID_FROM_PID( pid )       (lpid_t)(pid & 0x0000FFFF)
#define CXY_FROM_PID( pid )        (cxy_t)(pid >> 16)
#define PID( cxy , lpid )          (pid_t)((cxy << 16) | lpid )

/*********************************************************************************************
 * This enum defines the actions that can be executed by the process_sigaction() function.
 ********************************************************************************************/

typedef enum 
{
    BLOCK_ALL_THREADS    = 0x11,
    UNBLOCK_ALL_THREADS  = 0x22,
    DELETE_ALL_THREADS   = 0x33, 
} 
process_sigactions_t;

/*********************************************************************************************
 * This structure defines an array of extended pointers on the open file descriptors
 * for a given process. The file descriptors are always stored in the same cluster 
 * as the object associated to the file descriptor (inode, socket, pipe, etc). 
 * A free entry in this array contains XPTR_NULL.
 * The array size is defined by the CONFIG_PROCESS_FILE_MAX_NR parameter.
 *
 * NOTE: - Only the fd_array[] in the owner cluster process contains the complete list
 *         of open files, and is protected by the lock against concurrent access.
 *       - the fd_array[] in a process copy is only used to speed the fdid -> xptr
 *         translation, but the "lock" and "max" fields are not significant in these copies.
 *       - The modifications made by the process_fd_register() function are only done
 *         in the owner cluster.
 *       - The modifications made by the process_fd_remove() function are done in the
 *         owner cluster, and in all process_copies.
 *       - In case of miss on a local fd_array, the process_fd_get_xptr() access the
 *         owner cluster fd_array, and update the fd_array local copy.
 ********************************************************************************************/

typedef struct fd_array_s
{
	remote_queuelock_t lock;                              /*! lock protecting fd_array      */
    uint32_t           max;                               /*! max non-free slot index       */
	xptr_t             array[CONFIG_PROCESS_FILE_MAX_NR]; /*! open file descriptors         */
}
fd_array_t;

/*********************************************************************************************
 * This structure defines the information required by the process_make_exec() function
 * to create a new reference process descriptor, and the associated main thread.
 * All fields in this structure are filled by the sys_exec() function.
 *
 * It contains three parts:
 * - the "path" field is a string defining the pathname of the .elf file.
 * - the "args_pointers" & "args_nr" fields define the arguments (one arg == one string).
 * - the "envs_pointers" & "envs_nr" fields define the env variables (one env == one string).
 *
 * For both the arguments and the environment variables, the array of pointers and the
 * strings themselve are stored in the same kernel buffer. These kernel buffers contain
 * an integer number of contiguous pages, defined by the CONFIG_VMM_ARGS_SIZE and 
 * CONFIG_VMM_ENVS_SIZE parameters respectively.
 * Each kernel (args / envs) buffer contains :
 * - in the first bytes, a fixed size kernel array of pointers on the strings.
 * - in the following bytes, the strings themselves.
 * The size of these arrays of pointers is defined by the CONFIG_PROCESS_ARGS_MAX_NR and
 * CONFIG_PROCESS_ENVS_MAX_NR parameters respectively.
 *
 * WARNING (1) The "args_pointers[i]" & "envs_pointers[i] stored in the dynamically
 *             allocated kernel buffers are local pointers. They must be extended by the
 *             local cluster identifier to compute a valid PPN.
 * WARNING (2) The "args" & "envs" kernel buffers will be mapped to the "args" and "envs"
 *             user vsegs, to be accessed by the new user process. 
 *             The process_make_exec() function must therefore replace the kernel pointers
 *             set by sys_exec(), by user pointers in the new process user space.
 ********************************************************************************************/

typedef struct exec_info_s
{
    char           path[CONFIG_VFS_MAX_PATH_LENGTH];  /*! .elf file path in kernel space    */

    char        ** args_pointers;  /*! pointer on array of pointers on strings              */
    uint32_t       args_nr;        /*! actual number of arguments                           */

    char        ** envs_pointers;  /*! pointer on array of pointers on strings              */
    uint32_t       envs_nr;        /*! actual number of environment variables               */
    char         * envs_buf_free;  /*! local pointer on first free slot in strings buffer   */
}
exec_info_t;

/*********************************************************************************************
 * This structure defines a process descriptor.
 * A process is identified by a unique PID (process identifier):
 * - The PID 16 LSB bits contain the LPID (Local Process Index)
 * - The PID 16 MSB bits contain the owner cluster CXY.
 * In each cluster, the process manager allocates  the LPID values for the process that
 * are owned by this cluster.
 * The process descriptor is replicated in all clusters containing at least one thread 
 * of the PID process, with the following rules :
 * 1) The <pid>, <ppid>, <ref_xp>, <owner_xp>, <vfs_root_xp>, <vfs_bin_xp>  fields are 
 *    defined in all process descriptor copies.
 * 2) The <vfs_cwd_xp> and associated <cwd_lock>, that can be dynamically modified,
 *    are only defined in the reference process descriptor.
 * 2) The <vmm>, containing the VSL (list of registered vsegs), and the GPT (generic
 *    page table), are only complete in the reference process cluster, other copies 
 *    are actually use as read-only caches.
 * 3) the <fd_array>, containing extended pointers on the open file descriptors, is only
 *    complete in the owner process cluster, other copies are read-only caches.
 * 4) The <sem_root>, <mutex_root>, <barrier_root>, <condvar_root>, and the associated
 *    <sync_lock>, dynamically allocated, are only defined in the reference cluster.
 * 5) The <children_root>, <children_nr>, <children_list>, and <txt_list> fields are only
 *    defined in the reference cluster, and are undefined in other clusters.
 * 6) The <local_list>, <copies_list>, <th_tbl>, <th_nr>, <u_th_lock> or <k_th_lock> fields
 *    are specific in each cluster, and are defined in all process descriptors copies.
 * 7) The termination <flags> and <exit_status> are only defined in the reference cluster.
 *    (The term_state format is defined in the shared_syscalls.h file ).
 ********************************************************************************************/

typedef struct process_s
{
    vmm_t              vmm;              /*! embedded virtual memory manager                 */

    fd_array_t         fd_array;         /*! embedded open file descriptors array            */

    exec_info_t        exec_info;        /*! embedded structure for args & envs              */

    xptr_t             vfs_root_xp;      /*! extended pointer on VFS root inode              */
    xptr_t             vfs_bin_xp;       /*! extended pointer on .elf file descriptor        */
    pid_t              pid;              /*! process identifier                              */
    xptr_t             ref_xp;           /*! extended pointer on reference process           */
    xptr_t             owner_xp;         /*! extended pointer on owner process               */
    xptr_t             parent_xp;        /*! extended pointer on parent process              */

    xptr_t             cwd_xp;           /*! extended pointer on current working dir inode   */
    remote_busylock_t  cwd_lock;         /*! lock protecting working directory changes       */

    xlist_entry_t      children_root;    /*! root of the children process xlist              */
    remote_queuelock_t children_lock;    /*! lock protecting children process xlist          */
    uint32_t           children_nr;      /*! number of children processes                    */

    xlist_entry_t      children_list;    /*! member of list of children of same parent       */
    xlist_entry_t      local_list;       /*! member of list of process in same cluster       */
    xlist_entry_t      copies_list;      /*! member of list of copies of same process        */
    xlist_entry_t      txt_list;         /*! member of list of processes sharing same TXT    */

    struct thread_s  * th_tbl[CONFIG_THREADS_MAX_PER_CLUSTER];       /*! local threads       */

    uint32_t           th_nr;            /*! number of threads in this cluster               */
    rwlock_t           th_lock;          /*! lock protecting th_tbl[]  i                     */ 

    xlist_entry_t      sem_root;         /*! root of the user defined semaphore list         */
    xlist_entry_t      mutex_root;       /*! root of the user defined mutex list             */
    xlist_entry_t      barrier_root;     /*! root of the user defined barrier list           */
    xlist_entry_t      condvar_root;     /*! root of the user defined condvar list           */
    remote_queuelock_t sync_lock;        /*! lock protecting user defined synchro lists      */

    xlist_entry_t      dir_root;         /*! root of the user defined DIR list               */
    remote_queuelock_t dir_lock;         /*! lock protexting user defined DIR list           */

    uint32_t           term_state;       /*! termination status (flags & exit status)        */
}
process_t;

/***************   Process Descriptor Operations    *****************************************/

/*********************************************************************************************
 * This function allocates memory in local cluster for a process descriptor.
 *********************************************************************************************
 * @ returns pointer on process descriptor if success / return NULL if failure
 ********************************************************************************************/
process_t * process_alloc( void );

/*********************************************************************************************
 * This function releases memory in local cluster for a process descriptor.
 *********************************************************************************************
 * @ process      : pointer on process descriptor to release.
 ********************************************************************************************/
void process_free( process_t * process );

/*********************************************************************************************
 * This function initialize, in each cluster, the kernel "process_zero", that contains
 * all kernel threads in a given cluster. It is called by the kernel_init() function.
 * The process_zero descriptor is allocated as a global variable in file kernel_init.c 
 * Both the PID and PPID fields are set to zero, the ref_xp is the local process_zero,
 * and the parent process is set to XPTR_NULL. The th_tbl[] is initialized as empty.
 * The process GPT is initialised as required by the target architecture.
 * The "kcode" and "kdata" segments are registered in the process VSL.
 * This function does not return an error code: in case of failure, it print a PANIC message
 * on kernel terminal TXT0, and the core goes to sleep mode.
 *********************************************************************************************
 * @ process  : [in] pointer on process descriptor to initialize.
 * @ info     : pointer on local boot_info_t (for kernel segments base and size). 
 ********************************************************************************************/
void process_zero_create( process_t   * process,
                          boot_info_t * info );

/*********************************************************************************************
 * This function allocates memory and initializes the "process_init" descriptor and the
 * associated "thread_init" descriptor. It is called once at the end of the kernel_init() 
 * procedure. Its local process identifier is 1, and parent process is the kernel process.
 * The "process_init" is the first user process, and all other user processes will be forked
 * from this process. The code executed by "process_init" is stored in a .elf file, whose
 * pathname is defined by the CONFIG_PROCESS_INIT_PATH configuration variable. 
 * This function does not return an error code: in case of failure, it print a PANIC message
 * on kernel terminal TXT0, and the core goes to sleep mode.
 ********************************************************************************************/
void process_init_create( void );

/*********************************************************************************************
 * This function initializes a reference user process descriptor from another process
 * descriptor, defined by the <parent_xp> argument. The <process> and <pid> arguments 
 * are previously allocated by the caller. This function can be called by two functions:
 * -  process_init_create() : process is the INIT process, and parent is process-zero.
 * -  process_make_fork()   : the parent process descriptor is generally remote.
 * The following fields are initialised :
 * - It set the pid / ppid / ref_xp / parent_xp / state fields.
 * - It creates an empty GPT and an empty VSL.
 * - It initializes the locks protecting the GPT and the VSL.
 * - It registers the "kernel" vsegs in VSL, using the hal_vmm_kernel_update() function.
 * - It registers the "args" and "envs" vsegs in VSL, using the vmm_user_init() function.
 * - The "code and "data" must be registered later, using the elf_load_process() function.
 * - It initializes the FDT, defining the three pseudo files STDIN / STDOUT / STDERR.
 *   . if INIT process     => link to kernel TXT[0].
 *   . if KSH[i] process   => allocate a free TXT[i].
 *   . if USER process     => link to parent process TXT[i].
 * - It set the root_xp, bin_xp, cwd_xp fields.
 * - It reset the children list as empty, but does NOT register it in parent children list.
 * - It reset the TH_TBL list of threads as empty.
 * - It reset the semaphore / mutex / barrier / condvar lists as empty.
 * - It registers the process in the local_list, rooted in the local cluster manager.
 * - It registers the process in the copies_list, rooted in the owner cluster manager.
 * - It registers the process extended pointer in the local pref_tbl[] array.
 *********************************************************************************************
 * @ process      : [in] pointer on local process descriptor to initialize.
 * @ pid          : [in] process identifier.
 * @ parent_xp    : [in] extended pointer on parent process descriptor.
 * @ return 0 if success / return -1 if failure
 ********************************************************************************************/
error_t process_reference_init( process_t * process,
                                pid_t       pid,
                                xptr_t      parent_xp );

/*********************************************************************************************
 * This function initializes a copy process descriptor, in the local cluster,
 * from information defined in the reference remote process descriptor.
 * As the VSL and the GPT of a process copy are handled as local caches, the GPT copy is 
 * created empty, and the VSL copy contains only the "kernel", "args", and "envs" vsegs. 
 *********************************************************************************************
 * @ process              : [in] local pointer on process descriptor to initialize.
 * @ reference_process_xp : [in] extended pointer on reference process descriptor.
 * @ return 0 if success / return -1 if failure
 ********************************************************************************************/
error_t process_copy_init( process_t * local_process,
                           xptr_t      reference_process_xp );

/*********************************************************************************************
 * This function releases all memory allocated for a process descriptor in the local cluster,
 * including memory allocated for embedded sub-structures (fd_array, vmm, etc).
 * The local th_tbl[] array must be empty.
 *********************************************************************************************
 * @ process     : [in] pointer on the process descriptor.
 ********************************************************************************************/
void process_destroy( process_t * process );

/*********************************************************************************************
 * This debug function diplays on the kernel terminal TXT0 detailed informations on a 
 * process descriptor identified by the <process_xp> argument.
 * It can be called by a thread running in any cluster.
 * WARNING: this function uses the nolock_printk() function, and the  TXT0 lock MUST be
 * taken by the caller function. 
 *********************************************************************************************
 * @ process_xp    : [in] extended pointer on process descriptor.
 ********************************************************************************************/
void process_display( xptr_t process_xp );

/*********************************************************************************************
 * This function returns a printable string defining the sigaction type.
 *********************************************************************************************
 * @ sigaction_type   : BLOCK_ALL_THREADS / UNBLOCK_ALL_THREADS / DELETE_ALL_THREADS
 * @ return a string pointer.
 ********************************************************************************************/
const char * process_action_str( process_sigactions_t sigaction_type );

/*********************************************************************************************
 * This function allows a client thread running in any cluster to block, unblock or delete 
 * all threads of a process identified by the <pid> argument, depending on the 
 * <action_type> argument.
 *
 * It uses the multicast, non blocking rpc_process_sigaction_client() function to send
 * parallel requests to all remote clusters containing process copies. 
 * Then it blocks and deschedule to wait completion of these parallel requests.
 *
 * It is used by the sys_kill() & sys_exit() functions to handle the "kill" & "exit" syscalls.
 * It is also used by the process_make_exec() function to handle the "exec" syscall.
 * It is also called by the TXT device ISR to execute the ctrl C & ctrl Z commands.
 *
 * WARNING (1) the DELETE action is NOT executed on the target process main thread
 * (thread 0 in process owner cluster), and not executed on the client thread itself.
 *
 * WARNING (2) the BLOCK action is executed on all target process threads, and this function
 * returns only when all threads BUT the client thread are actually blocked and not running.
 * When the client thread is also a target thread, it is blocked but not descheduled. 
 * 
 * WARNING (3) the UNBLOCK action is executed on all target process threads, as the
 * client thread cannot be a target thread.
 *
 * Implementation note:
 * This function allocates a - shared - RPC descriptor in client thread stack, 
 * and initializes it. This RPC descriptor can be shared because all parallel,
 * non-blocking, RPC server threads use the same input arguments, including the
 * RPC responses counter field.
 *********************************************************************************************
 * @ pid         : target process identifier.
 * @ action_type : BLOCK_ALL_THREADS / UNBLOCK_ALL_THREADS / DELETE_ALL_THREADS
 ********************************************************************************************/
void process_sigaction( pid_t       pid,
                        uint32_t    action_type );

/*********************************************************************************************
 * This function marks for delete all threads for a given <process> in the local cluster.
 * It scan the list of local thread, and sets the THREAD_FLAG_REQ_DELETE bit for all
 * threads, BUT the main thread (thread 0 in owner cluster), and the client thread
 * identified by the <client_xp> argument. 
 * The actual delete will be done by the scheduler at the next scheduling point.
 *********************************************************************************************
 * @ process     : pointer on the process descriptor.
 * @ client_xp   : extended pointer on the client thread that should not be marked.
 ********************************************************************************************/
void process_delete_threads( process_t * process,
                             xptr_t      client_xp );

/*********************************************************************************************
 * This function blocks all threads for a given <process> in the local cluster. 
 * It scan the list of local thread, and sets the THREAD_BLOCKED_GLOBAL bit for all threads.
 * It request the relevant schedulers to acknowledge the blocking, using IPI if required, 
 * when the target thread is running on another core than the calling thread.
 * It returns only when all threads in cluster, including the caller are actually blocked.
 * The threads are not detached from the scheduler, and not detached from the local process.
 *********************************************************************************************
 * @ process     : pointer on the target process descriptor.
 ********************************************************************************************/
void process_block_threads( process_t * process );

/*********************************************************************************************
 * This function unblocks all threads of a given user process in a given cluster.
 *********************************************************************************************
 * @ process     : pointer on the process descriptor.
 ********************************************************************************************/
void process_unblock_threads( process_t * process );

/*********************************************************************************************
 * This function returns a pointer on the local copy of a process identified by its PID.
 * If this local copy does not exist yet, it is dynamically created, from the reference
 * process descriptor, registered in the global copies_list, and registered in the local_list.
 * This function is used by the thread_user_create() function.
 *********************************************************************************************
 * @ pid     : searched process identifier.
 * @ returns pointer on the local process descriptor if success / returns NULL if failure.
 ********************************************************************************************/
process_t * process_get_local_copy( pid_t pid );

/*********************************************************************************************
 * This function returns the parent process identifier for a remote process descriptor
 * identified by an extended pointer.
 *********************************************************************************************
 * @ process_xp   : extended pointer on remote process descriptor.
 * @ returns parent process dentifier.
 ********************************************************************************************/
pid_t process_get_ppid( xptr_t process_xp );

/*********************************************************************************************
 * This function implements the "execve" system call, and is called by sys_exec() function.
 * It must be called by the main thread of the calling "old" process.
 * The <exec_info> structure in process descriptor contains all informations required
 * to update both the calling process descriptor and the calling thread descriptor.
 * The "new" process keep the "old" process PID and PPID, all open files, and env variables,
 * the vfs_root and vfs_cwd, but build a brand new memory image (new VMM from the .elf file).
 * It is executed in the local cluster, that becomes both the "owner" and the "reference"
 * cluster for the "new" process.
 *********************************************************************************************
 * Implementation note:
 * It executes the following sequence:
 * 1) it creates a file descriptor for the .elf file (pathname in exec_info).
 * 2) it deletes all other threads than the main thread, in all clusters.
 * 3) it reset the existing VMM (remove all user vsegs).
 * 4) it build the "args" user vseg from process exec_info, and registers in the VMM. 
 * 5) TODO it build the "envs" user vseg from process exec_info, and registers in the VMM.
 * 6) it get the "code" and "data" user vsegs from the .elf file, and registers in the VMM.
 * 7) it allocates an user "stack" vseg, and registers in the VMM
 * 8) it calls thread_user_exec() to complete thread initialisation and jumps to user code.
 *********************************************************************************************
 * @ return 0 if success / return non-zero if error.
 ********************************************************************************************/
error_t process_make_exec( void );

/*********************************************************************************************
 * This function implements the "fork" system call, and is called by the sys_fork() function,
 * likely through the RPC_PROCESS_MAKE_FORK. 
 * It allocates memory and initializes a new child process descriptor, and the associated
 * child thread descriptor in local cluster. It involves up to three different clusters:
 * - the child (local) cluster can be any cluster selected by the sys_fork function.
 * - the parent cluster must be the reference cluster for the parent process.
 * - the client cluster containing the thread requesting the fork can be any cluster.
 * The new child process descriptor is initialised from informations found in the parent
 * reference process descriptor, containing the complete process description.
 * The new child thread descriptor is initialised from informations found in the parent
 * thread descriptor.
 *********************************************************************************************
 * @ parent_process_xp  : extended pointer on the reference parent process.
 * @ parent_thread_xp   : extended pointer on the parent thread requesting the fork.
 * @ child_pid          : [out] child process identifier.
 * @ child_thread_ptr   : [out] local pointer on child thread in target cluster.
 * @ return 0 if success / return non-zero if error.
 ********************************************************************************************/
error_t process_make_fork(  xptr_t             parent_process_xp,
                            xptr_t             parent_thread_xp,
                            pid_t            * child_pid, 
                            struct thread_s ** child_thread_ptr );


/********************     fd_array  operations       ****************************************/


/*********************************************************************************************
 * This function returns a printable string for a file descriptor type.
 * These file types are defined in the <vfs.h> file.
 *********************************************************************************************
 * @ type     : [in] file type.
 ********************************************************************************************/
char * process_fd_type_str( uint32_t type );

/*********************************************************************************************
 * This function initializes all entries of the local fd_array as empty.
 *********************************************************************************************
 * @ process  : [in] pointer on the local process descriptor.
 ********************************************************************************************/
void process_fd_init( process_t * process );

/*********************************************************************************************
 * This function allocates a free slot in the owner cluster process fd_array identified
 * by the <process_xp> argument, register the <file_xp> argument in the allocated slot,
 * and return the slot index in the <fdid> buffer.
 * It can be called by any thread in any cluster.
 * It takes the lock protecting the fd_array against concurrent slot allocations.
 * Note: we must use the owner process descriptor, because only this fd_array contains
 * all files open by a given process.
 *********************************************************************************************
 * @ process_xp : [in]  extended pointer on owner process.
 * @ file_xp    : [in]  extended pointer on the file descriptor to be registered.
 * @ fdid       : [out] buffer for allocated fd_array slot index.
 * @ return 0 if success / return -1 if array full.
 ********************************************************************************************/
error_t process_fd_register( xptr_t      process_xp,
                             xptr_t      file_xp,
                             uint32_t  * fdid );

/*********************************************************************************************
 * This function uses as many remote accesses as required, to reset one fd_array[] entry,
 * identified by the <fdid> argument, in all clusters containing a copy of the 
 * process descriptor, identified by the <process_xp> argument. 
 * It can be called by any thread in any cluster.
 * It takes the lock protecting the list of copies.
 * Note: we must use the owner process descriptor, because only this owner cluster contains
 * the complete list of process copies.
 *********************************************************************************************
 * @ process_xp  : [in] extended pointer on the owner process descriptor.
 * @ fdid        : [in] file descriptor index in the fd_array.
 ********************************************************************************************/
void process_fd_remove( xptr_t     process_xp,
                        uint32_t   fdid );

/*********************************************************************************************
 * This function scan the fd_array to close all files (or sockets) registered in the process
 * fd_array identified by the <process_xp> argument. It call the sys_close() function for 
 * each registered entry, to release all allocated memory, and reset this entry in all
 * process descriptors copies.
 * It takes the lock protecting the fd_array against concurrent accesses.
 * Note: we must use the owner process descriptor, because only this owner cluster contains
 * the complete list of process copies.
 *********************************************************************************************
 * @ process_xp  : [in] extended pointer on the owner process descriptor.
 ********************************************************************************************/
void process_fd_clean_all( xptr_t process_xp );

/*********************************************************************************************
 * This function returns an extended pointer on a file descriptor identified by its <fdid>
 * index in fd_array of the local process, identified by the <process> argument.
 * It can be called by any thread running in any cluster.
 * It accesses first the local process descriptor. In case of local miss, it takes
 * the lock protecting the reference fd_array, and access the reference process descriptor.
 * It updates the local fd_array when the file descriptor exists in owner cluster. 
 * It release the lock protecting the reference fd_array.
 *********************************************************************************************
 * @ process  : local pointer on local process descriptor.
 * @ fdid     : file descriptor index in the fd_array.
 * @ return extended pointer on file descriptor if success / return XPTR_NULL if not found.
 ********************************************************************************************/
xptr_t process_fd_get_xptr_from_local( process_t * process,
                                       uint32_t    fdid );

/*********************************************************************************************
 * This function returns an extended pointer on a file descriptor identified by its <fdid>
 * index in the fd_array of the owner process, identified by the <process_xp> argument,
 * accessing directly the fd_array in owner cluster. It can be called by any thread running
 * in any cluster, but the local fd_array copy is not updated.
 *********************************************************************************************
 * @ process_xp  : extended pointer on the owner process descriptor.
 * @ fdid        : file descriptor index in the fd_array.
 * @ return extended pointer on file descriptor if success / return XPTR_NULL if not found.
 ********************************************************************************************/
xptr_t process_fd_get_xptr_from_owner( xptr_t      process_xp,
                                       uint32_t    fdid );

/*********************************************************************************************
 * This function scans all entries in a fd_array, identified by the <src_xp> argument, that
 * must be the process descriptor in owner cluster. For each non-zero entry, it allocates a
 * new file descriptor in the cluster containing the involved inode, and registers it in the
 * fd_array identified by the <dst_xp> argument, that must also be the process descriptor in
 * owner cluster. The calling thread itself can be running in any cluster.
 * It takes the lock protecting the <src_xp> fd_array against concurrent accesses.
 *********************************************************************************************
 * @ dst_xp   : extended pointer on the source process descriptor (in owner cluster).
 * @ src_xp   : extended pointer on the destination process descriptor (in owner cluster).
 * @ return 0 if success / return -1 if failure
 ********************************************************************************************/
error_t process_fd_replicate( xptr_t dst_xp,
                              xptr_t src_xp );

/*********************************************************************************************
 * This function checks the current number of open files for a given process.
 * It can be called by any thread in any cluster, because it uses portable remote access
 * primitives to access the reference process descriptor.
 * It does not take the lock protecting the reference fd_array.
 *********************************************************************************************
 * @ returns true if file descriptor array full.
 ********************************************************************************************/
bool_t process_fd_array_full( void );

/*********************************************************************************************
 * This debug function diplays on the kernel terminal TXT0 detailed informations on the
 * set of file descriptors registered in the fd_array of a process descriptor identified
 * by the <process_xp> argument. 
 *********************************************************************************************
 * @ process_xp    : [in] extended pointer on process descriptor.
 ********************************************************************************************/
void process_fd_display( xptr_t process_xp );

/*********************************************************************************************
 * This utility function builds in the buffer defined by the <buffer> and <size> arguments
 * a printable string describing the current state of a process descriptor identified 
 * by the <process_xp> argument, or a WARNING message if the buffer size is too small.
 *********************************************************************************************
 * @ process_xp  : extended pointer on target process descriptor.
 * @ buffer      : kernel buffer for string.
 * @ size        : buffer size in bytes.
 * @ return always the string length (not including NUL), that can be a warning message.
 ********************************************************************************************/
uint32_t process_build_string( xptr_t   process_xp,
                               char   * buffer,
                               uint32_t size );

/********************   Thread Related Operations   *****************************************/

/*********************************************************************************************
 * This function atomically registers a new thread identified by the <thread> argument 
 * in the th_tbl[] array of the local process descriptor identified by the <process>
 * argument. It checks that there is an available slot in the local th_tbl[] array,
 * and allocates a new LTID using the relevant lock depending on the kernel/user type,
 * and returns the global thread identifier in the <trdid> buffer.
 *********************************************************************************************
 * @ process  : [in]  pointer on the local process descriptor.
 * @ thread   : [in]  pointer on new thread to be registered.
 * @ trdid    : [out] buffer for allocated trdid.
 * @ returns 0 if success / returns non zero if no slot available.
 ********************************************************************************************/
error_t process_register_thread( process_t       * process,
                                 struct thread_s * thread,
                                 trdid_t         * trdid );

/*********************************************************************************************
 * This function atomically removes a thread identified by the <thread> argument from 
 * the local process descriptor th_tbl[] array, and returns the number of thread currently
 * registered in th_tbl[] array before this remove.
 *********************************************************************************************
 * @ thread   : pointer on thread to be removed.
 * @ returns number of threads registered in th_tbl before thread remove.
 ********************************************************************************************/
uint32_t process_remove_thread( struct thread_s * thread );


/***************   Terminals related operations  ********************************************/

/*********************************************************************************************
 * This function scan the set of user TXT terminals to find a free terminal
 * (the list of attached processes is empty for a free TXT terminal).
 * It is called only by the process_reference_init() function when creating a KSH process.
 * It makes a kernel panic if no free TXT terminal is found.
 * The allocated TXT terminal is only released when the KSH process is deleted.
 *********************************************************************************************
 * @ return TXT terminal index if succes / kernel panic if no terminal found.
 ********************************************************************************************/
uint32_t process_txt_alloc( void );

/*********************************************************************************************
 * This function attach a process, identified by the <process_xp> argument to a TXT terminal,
 * identified by the <txt_id> channel index argument.
 * The process descriptor identified by the <process_xp> argument must be in the owner
 * cluster. It insert the process descriptor in the xlist rooted in the TXT_RX device.
 * It is called by the process_reference_init() function.
 *********************************************************************************************
 * @ process_xp : extended pointer on process descriptor in owner cluster.
 * @ txt_id     : TXT channel index.
 ********************************************************************************************/
void process_txt_attach( xptr_t    process_xp,
                         uint32_t  txt_id );

/*********************************************************************************************
 * This function detach a process, identified by the <process_xp> argument,
 * from the list of process attached to a given TXT terminal. It transfer the TXT ownership
 * to another process, if the detached process is the TXT owner.
 * The process descriptor identified by the <process_xp> argument must be in the owner
 * cluster, but the calling thread can be running in any cluster. 
 *********************************************************************************************
 * @ process_xp  : extended pointer on process descriptor in owner cluster.
 ********************************************************************************************/
void process_txt_detach( xptr_t  process_xp );                     

/*********************************************************************************************
 * This function returns the TXT terminal index allocated to a process identified by the
 * <process_xp> argument. The process descriptor identified by the <process_xp> argument 
 * must be in the owner cluster, but the calling thread can be running in any cluster. 
 *********************************************************************************************
 * @ process_xp  : extended pointer on process descriptor in owner cluster.
 ********************************************************************************************/
uint32_t process_txt_get_index( xptr_t process_xp );

/*********************************************************************************************
 * This function gives a process identified by the <process_xp> argument the 
 * ownership of its attached TXT_RX terminal (i.e. put the process in foreground).
 * It can be called by a thread running in any cluster, but the target process descriptor
 * must be in the owner cluster.
 *********************************************************************************************
 * @ owner_xp  : extended pointer on process descriptor in owner cluster.
 ********************************************************************************************/
void process_txt_set_ownership( xptr_t process_xp );

/*********************************************************************************************
 * When the target process identified by the <owner_xp> argument has the exclusive ownership
 * of the TXT_RX terminal, this function transfer this ownership to another process attached
 * to the same terminal. The target process descriptor must be the process owner.
 * This function does nothing if the target process is not the TXT owner.
 * - If the current owner is not the KSH process, the new owner is the KSH process.
 * - If the current owner is the KSH process, the new owner is another attached process.
 * - If there is no other attached process, the TXT has no more defined owner. 
 *********************************************************************************************
 * @ process_xp  : extended pointer on process descriptor in owner cluster.
 ********************************************************************************************/
void process_txt_transfer_ownership( xptr_t process_xp );

/*********************************************************************************************
 * This function returns true if the  process identified by the <process_xp> argument
 * is the TXT owner. It can be called by a thread running in any cluster, but the
 * process_xp must be the owner cluster process descriptor. 
 *********************************************************************************************
 * @ returns true if target process is TXT owner.
 ********************************************************************************************/
bool_t process_txt_is_owner( xptr_t process_xp );

/*********************************************************************************************
 * This function returns an extended pointer on the current TXT owner process, 
 * for the TXT terminal identified by the <channel> index. 
 *********************************************************************************************
 * @ channel : TXT channel.
 * @ return extended pointer on TXT owner process.
 ********************************************************************************************/
xptr_t process_txt_get_owner( uint32_t channel );

/*********************************************************************************************
 * This debug function diplays on the kernel terminal the list of processes attached
 * to a given terminal identified by the <txt_id> argument.
 *********************************************************************************************
 * @ txt_id  : TXT terminal channel.
 ********************************************************************************************/
void process_txt_display( uint32_t txt_id );


#endif	/* _PROCESS_H_ */
