/*
 * vmm.h - virtual memory management related operations
 *
 * Authors   Ghassan Almaless (2008,2009,2010,2011, 2012)
 *           Mohamed Lamine Karaoui (2015)
 *           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
 */

#ifndef _VMM_H_
#define _VMM_H_

#include <hal_kernel_types.h>
#include <bits.h>
#include <list.h>
#include <queuelock.h>
#include <hal_gpt.h>
#include <vseg.h>
#include <page.h>

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

struct process_s;

/*********************************************************************************************
 * This structure defines the STACK allocator used by the VMM to dynamically handle
 * a STACK vseg requested or released by an user process.
 * This allocator handles a fixed size array of fixed size slots in the STACK zone.
 * The stack size and the number of slots are defined by the CONFIG_VMM_STACK_SIZE, and
 * CONFIG_VMM_STACK_BASE parameters.
 * Each slot can contain one user stack vseg. The first page in the slot is not allocated
 * to detect stack overflow.
 * The slot index can be computed form the slot base address, and reversely.
 * All allocation / release operations are registered in the stack_bitmap, that completely
 * define the STACK zone state.
 ********************************************************************************************/

typedef struct stack_mgr_s
{
    busylock_t     lock;               /*! lock protecting STACK allocator                  */
    vpn_t          vpn_base;           /*! first page of STACK zone                         */
    bitmap_t       bitmap;             /*! bit bector of allocated stacks                   */
}
stack_mgr_t;

/*********************************************************************************************
 * This structure defines the MMAP allocator used by the VMM to dynamically handle  
 * MMAP vsegs requested or released by an user process.
 * This allocator should be only used in the reference cluster.
 * - allocation policy : all allocated vsegs occupy an integer number of pages that is
 *   power of 2, and are aligned on a page boundary. The requested number of pages is
 *   rounded if required. The first_free_vpn variable defines completely the MMAP zone state.
 *   It is never decremented, as the released vsegs are simply registered in a zombi_list.
 *   The relevant zombi_list is checked first for each allocation request.
 * - release policy : a released MMAP vseg is registered in an array of zombi_lists.
 *   This array is indexed by ln(number of pages), and each entry contains the root of
 *   a local list of zombi vsegs that have the same size. The physical memory allocated
 *   for a zombi vseg descriptor is not released, to use the "list" field.
 *   This physical memory allocated for MMAP vseg descriptors is actually released
 *   when the VMM is destroyed.
 ********************************************************************************************/

typedef struct mmap_mgr_s
{
    busylock_t     lock;               /*! lock protecting MMAP allocator                   */
    vpn_t          vpn_base;           /*! first page of MMAP zone                          */
    vpn_t          vpn_size;           /*! number of pages in MMAP zone                     */
    vpn_t          first_free_vpn;     /*! first free page in MMAP zone                     */
    list_entry_t   zombi_list[32];     /*! array of roots of released vsegs lists           */
}
mmap_mgr_t;

/*********************************************************************************************
 * This structure defines the Virtual Memory Manager for a given process in a given cluster.
 * This local VMM implements four main services:
 * 1) It contains the local copy of vseg list (VSL), only complete in referrence.
 * 2) It contains the local copy of the generic page table (GPT), only complete in reference.
 * 3) The stack manager dynamically allocates virtual memory space for the STACK vsegs.
 * 4) The mmap manager dynamically allocates virtual memory for the (FILE/ANON/REMOTE) vsegs.
 ******************************************************a**************************************
 * Implementation notes:
 * 1. In most clusters, the VSL and GPT are only partial copies of the reference VSL and GPT
 *    structures, stored in the reference cluster.
 * 2. The VSL contains only local vsegs, but it is implemented as an xlist, and protected by
 *    a remote_rwlock, because it can be accessed by a thread running in a remote cluster.
 *    An exemple is the vmm_fork_copy() function.
 * 3. The GPT in the reference cluster can be directly accessed by remote threads to handle
 *    false page-fault (page is mapped in the reference GPT, but the PTE copy is missing
 *    in the local GPT). It is also protected by a remote_rwlock. 
 ********************************************************************************************/

typedef struct vmm_s
{
	remote_rwlock_t  vsegs_lock;         /*! lock protecting the local VSL                  */
	xlist_entry_t    vsegs_root;         /*! Virtual Segment List (complete in reference)   */
	uint32_t         vsegs_nr;           /*! total number of local vsegs                    */

    remote_rwlock_t  gpt_lock;           /*! lock protecting the local GPT                  */
    gpt_t            gpt;                /*! Generic Page Table (complete in reference)     */

    stack_mgr_t      stack_mgr;          /*! embedded STACK vsegs allocator                 */
    mmap_mgr_t       mmap_mgr;           /*! embedded MMAP vsegs allocator                  */

	uint32_t         pgfault_nr;         /*! page fault counter (instrumentation)           */

    vpn_t            kent_vpn_base;      /*! kentry vseg first page                         */
    vpn_t            args_vpn_base;      /*! args vseg first page                           */
    vpn_t            envs_vpn_base;      /*! envs zone first page                           */
    vpn_t            heap_vpn_base;      /*! envs zone first page                           */
	vpn_t            code_vpn_base;      /*! code zone first page                           */
	vpn_t            data_vpn_base;      /*! data zone first page                           */

	intptr_t         entry_point;        /*! main thread entry point                        */
}
vmm_t;

/*********************************************************************************************
 * This function initialises the virtual memory manager attached to an user process.
 * - It initializes the STACK and MMAP allocators.
 * - It registers the "kentry", "args", "envs" vsegs in the VSL.
 * - It initializes the generic page table, calling the HAL specific hal_gpt_init() function.
 * - For TSAR it map all pages for the "kentry" vseg, that must be identity mapping.
 * Note:
 * - The "code" and "data" vsegs are registered by the elf_load_process() function.
 * - The "stack" vsegs are dynamically created by the thread_user_create() function.
 * - The "file", "anon", "remote" vsegs are dynamically created by the mmap() syscall.
 *********************************************************************************************
 * @ process   : pointer on process descriptor
 * @ return 0 if success / return -1 if failure.
 ********************************************************************************************/
error_t vmm_init( struct process_s * process );

/*********************************************************************************************
 * This function displays on TXY0 the list or registered vsegs for a given <process>.
 * It must be executed by a thread running in reference cluster.
 * If the <mapping> argument is true, it displays for each vseg all mapped PTEs in GPT.
 *********************************************************************************************
 * @ process   : pointer on process descriptor.
 * @ mapping   : detailed mapping if true.
 ********************************************************************************************/
void vmm_display( struct process_s * process,
                  bool_t             mapping );

/*******************************************************************************************
 * This function adds a vseg descriptor in the VSL of a given VMM,
 * and updates the vmm field in the vseg descriptor.
 * It takes the lock protecting VSL.
 *******************************************************************************************
 * @ vmm       : pointer on the VMM
 * @ vseg      : pointer on the vseg descriptor
 ******************************************************************************************/
void vmm_vseg_attach( struct vmm_s  * vmm,
                      vseg_t        * vseg );

/*******************************************************************************************
 * This function removes a vseg descriptor from the set of vsegs controlled by a given VMM,
 * and updates the vmm field in the vseg descriptor. No memory is released.
 * It takes the lock protecting VSL.
 *******************************************************************************************
 * @ vmm       : pointer on the VMM
 * @ vseg      : pointer on the vseg descriptor
 ******************************************************************************************/
void vmm_vseg_detach( struct vmm_s  * vmm,
                      vseg_t        * vseg );

/*********************************************************************************************
 * This function is called by the process_make_fork() function. It partially copies
 * the content of a remote parent process VMM to the local child process VMM:
 * - all DATA, MMAP, REMOTE vsegs registered in the parent VSL are registered in the child
 *   VSL, and all valid GPT entries in parent GPT are copied to the child GPT. 
 *   The WRITABLE flag is reset and the COW flag is set in child GPT.
 * - all CODE vsegs registered in the parent VSL are registered in the child VSL, but the
 *   GPT entries are not copied in the chilf GPT, that will be dynamically updated from
 *   the .elf file when a page fault is reported.
 * - all FILE vsegs registered in the parent VSL are registered in the child VSL, and all
 *   valid GPT entries in parent GPT are copied to the child GPT. The COW flag is not set.
 * - no STACK vseg is copied from  parent VMM to child VMM, because the child STACK vseg
 *   must be copied later from the cluster containing the user thread requesting the fork().
 *********************************************************************************************
 * @ child_process     : local pointer on local child process descriptor.
 * @ parent_process_xp : extended pointer on remote parent process descriptor.
 * @ return 0 if success / return -1 if failure.
 ********************************************************************************************/
error_t vmm_fork_copy( struct process_s * child_process,
                       xptr_t             parent_process_xp );

/*********************************************************************************************
 * This function is called by the process_make_fork() function executing the fork syscall.
 * It set the COW flag, and reset the WRITABLE flag of all GPT entries of the DATA, MMAP,
 * and REMOTE vsegs of a process identified by the <process> argument.
 * It must be called by a thread running in the reference cluster, that contains the complete
 * VSL and GPT (use the rpc_vmm_set_cow_client() when the calling thread client is remote). 
 * It updates all copies of the process in all clusters, to maintain coherence in GPT copies,
 * using the list of copies stored in the owner process, and using remote_write accesses to
 * update the remote GPTs. It atomically increment the pending_fork counter, in all involved
 * physical page descriptors. It cannot fail, as only mapped entries in GPTs are updated.
 *********************************************************************************************
 * @ process   : local pointer on local reference process descriptor.
 ********************************************************************************************/
void vmm_set_cow( struct process_s * process );

/*********************************************************************************************
 * This global function modifies a GPT entry identified by the <process> and <vpn> 
 * arguments in all clusters containing a process copy.
 * It must be called by a thread running in the reference cluster.
 * It updates all copies of the process in all clusters, to maintain coherence in GPT copies,
 * using the list of copies stored in the owner process, and using remote_write accesses to
 * update the remote GPTs. It cannot fail, as only mapped entries in GPT copies are updated.
 *********************************************************************************************
 * @ process   : local pointer on local process descriptor.
 * @ vpn       : PTE index.
 * @ attr      : PTE / attributes.
 * @ ppn       : PTE / physical page index.
 ********************************************************************************************/
void vmm_global_update_pte( struct process_s * process,
                            vpn_t              vpn,
                            uint32_t           attr,
                            ppn_t              ppn );

/*********************************************************************************************
 * This function unmaps from the local GPT all mapped PTEs of a vseg identified by the
 * <process> and <vseg> arguments. It can be used for any type of vseg.
 * If this function is executed in the reference cluster, it handles for each referenced 
 * physical pages the pending forks counter :
 * - if counter is non-zero, it decrements it.
 * - if counter is zero, it releases the physical page to local kmem allocator.
 *********************************************************************************************
 * @ process  : pointer on process descriptor.
 * @ vseg     : pointer on the vseg to be unmapped.
 ********************************************************************************************/
void vmm_unmap_vseg( struct process_s * process,
                     vseg_t           * vseg );

/*********************************************************************************************
 * This function deletes, in the local cluster, all vsegs registered in the VSL
 * of the process identified by the <process> argument. For each vseg:
 * - it unmaps all vseg PTEs from the GPT (release the physical pages when required). 
 * - it removes the vseg from the local VSL.
 * - it releases the memory allocated to the local vseg descriptors.
 * Finally, it releases the memory allocated to the GPT itself.
 *********************************************************************************************
 * @ process   : pointer on process descriptor.
 ********************************************************************************************/
void vmm_destroy( struct process_s * process );

/*********************************************************************************************
 * This function scans the list of vsegs registered in the VMM of a given process descriptor
 * to check if a given virtual region (defined by a base and size) overlap an existing vseg.
 *********************************************************************************************
 * @ process  : pointer on process descriptor.
 * @ base     : region virtual base address.
 * @ size     : region size (bytes).
 * @ returns NULL if no conflict / return conflicting vseg pointer if conflict.
 ********************************************************************************************/
vseg_t * vmm_check_conflict( struct process_s * process,
                             vpn_t              base,
                             vpn_t              size );

/*********************************************************************************************
 * This function allocates memory for a vseg descriptor, initialises it, and register it
 * in the VMM of the local process descriptor, that should be the reference process.
 * For the 'stack", "file", "anon", & "remote" types, it does not use the <base> argument,
 * but uses the STACK and MMAP virtual memory allocators.
 * It checks collision with all pre-existing vsegs.
 * To comply with the "on-demand" paging policy, this function does NOT modify the page table,
 * and does not allocate physical memory for vseg data.
 * It should be called by a local thread (could be a RPC thread if the client thread is not
 * running in the regerence cluster).
 *********************************************************************************************
 * @ process     : pointer on local processor descriptor.
 * @ type        : vseg type.
 * @ base        : vseg base address (not used for dynamically allocated vsegs).
 * @ size        : vseg size (bytes).
 * @ file_offset : offset in file for CODE, DATA, FILE types. 
 * @ file_size   : can be smaller than "size" for DATA type.
 * @ mapper_xp   : extended pointer on mapper for CODE, DATA, FILE types.
 * @ cxy         : physical mapping cluster (for non distributed vsegs).
 * @ returns pointer on vseg if success / returns NULL if no memory, or conflict.
 ********************************************************************************************/
vseg_t * vmm_create_vseg( struct process_s * process,
                          vseg_type_t        type,
                          intptr_t           base,
	                      uint32_t           size,
                          uint32_t           file_offset,
                          uint32_t           file_size,
                          xptr_t             mapper_xp,
                          cxy_t              cxy );

/*********************************************************************************************
 * This function removes a vseg identified by it's pointer from the VMM of the calling process.
 * - If the vseg has not the STACK or MMAP type, it is removed from the vsegs list,
 *   and the physical memory allocated to vseg descriptor is released to KMEM.
 * - If the vseg has the STACK type, it is removed from the vsegs list, the physical memory
 *   allocated to vseg descriptor is released to KMEM, and the stack slot is returned to the
 *   VMM STACK allocator.
 * - If the vseg has the MMAP type, it is removed from the vsegs list and is registered
 *   in the zombi_list of the VMM MMAP allocator for future reuse. The physical memory
 *   allocated to vseg descriptor is NOT released to KMEM.
 *********************************************************************************************
 * @ vseg      : pointer on vseg to be removed.
 ********************************************************************************************/
void vmm_remove_vseg( vseg_t * vseg );

/*********************************************************************************************
 * This function removes a given region (defined by a base address and a size) from
 * the VMM of a given process descriptor. This can modify the number of vsegs:
 * (a) if the region is not entirely mapped in an existing vseg, it's an error.
 * (b) if the region has same base and size as an existing vseg, the vseg is removed.
 * (c) if the removed region cut the vseg in two parts, it is modified.
 * (d) if the removed region cut the vseg in three parts, it is modified, and a new
 *     vseg is created with same type.
 * FIXME [AG] this function must be called by a thread running in the reference cluster,
 * and the VMM must be updated in all process descriptors copies. 
 *********************************************************************************************
 * @ process   : pointer on process descriptor
 * @ base      : vseg base address
 * @ size      : vseg size (bytes)
 ********************************************************************************************/
error_t vmm_resize_vseg( struct process_s * process,
                         intptr_t           base,
                         intptr_t           size );

/*********************************************************************************************
 * This function checks that a given virtual address is contained in a registered vseg.
 * It can be called by any thread running in any cluster:
 * - if the vseg is registered in the local process VMM, it returns the local vseg pointer.
 * - if the vseg is missing in local VMM, it uses a RPC to get it from the reference cluster,
 *   register it in local VMM and returns the local vseg pointer, if success.
 * - it returns an user error if the vseg is missing in the reference VMM, or if there is 
 *   not enough memory for a new vseg descriptor in cluster containing the calling thread.
 *********************************************************************************************
 * @ process   : [in] pointer on process descriptor
 * @ vaddr     : [in] virtual address
 * @ vseg      : [out] local pointer on local vseg
 * @ returns 0 if success / returns -1 if user error (out of segment).
 *********************************************************************************************/
error_t vmm_get_vseg( struct process_s  * process,
                      intptr_t            vaddr,
                      vseg_t           ** vseg );            

/*********************************************************************************************
 * This function is called by the generic exception handler in case of page-fault event,
 * detected for a given <vpn> in a given <process> in any cluster. 
 * It checks the missing VPN and returns an user error if it is not in a registered vseg.
 * For a legal VPN, there is actually 3 cases:
 * 1) if the missing VPN belongs to a private vseg (STACK or CODE segment types, non
 *    replicated in all clusters), it allocates a new physical page, computes the attributes,
 *    depending on vseg type, and updates directly the local GPT.
 * 2) if the missing VPN belongs to a public vseg, it can be a false page-fault, when the VPN
 *    is mapped in the reference GPT, but not in the local GPT. For this false page-fault,
 *    the local GPT is simply updated from the reference GPT.
 * 3) if the missing VPN is public, and unmapped in the reference GPT, it's a true page fault.
 *    The calling thread  allocates a new physical page, computes the attributes, depending
 *    on vseg type, and updates directly (without RPC) the local GPT and the reference GPT.
 *    Other GPT copies  will updated on demand.
 * In the three cases, concurrent accesses to the GPT are handled, thanks to the 
 * remote_rwlock protecting each GPT copy.
 *********************************************************************************************
 * @ process   : pointer on local process descriptor copy.
 * @ vpn       : VPN of the missing PTE.
 * @ returns EXCP_NON_FATAL / EXCP_USER_ERROR / EXCP_KERNEL_PANIC after analysis
 ********************************************************************************************/
error_t vmm_handle_page_fault( struct process_s * process,
                               vpn_t              vpn );

/*********************************************************************************************
 * This function is called by the generic exception handler in case of copy-on-write event, 
 * detected for a given <vpn> in a given <process> in any cluster.
 * It returns a kernel panic if VPN is not in a registered vseg or is not mapped.
 * For a legal mapped vseg there is two cases:
 * 1) If the missing VPN belongs to a private vseg (STACK or CODE segment types, non
 *    replicated in all clusters), it access the local GPT to get the current PPN and ATTR.
 *    It access the forks counter in the current physical page descriptor.
 *    If there is a pending fork, it allocates a new physical page from the cluster defined 
 *    by the vseg type, copies the old physical page content to the new physical page,
 *    and decrements the pending_fork counter in old physical page descriptor.
 *    Finally, it reset the COW flag and set the WRITE flag in local GPT.
 * 2) If the missing VPN is public, it access the reference GPT to get the current PPN and
 *    ATTR. It access the forks counter in the current physical page descriptor.
 *    If there is a pending fork, it allocates a new physical page from the cluster defined 
 *    by the vseg type, copies the old physical page content to the new physical page,
 *    and decrements the pending_fork counter in old physical page descriptor.
 *    Finally it calls the vmm_global_update_pte() function to reset the COW flag and set
 *    the WRITE flag in all the GPT copies, using a RPC if the reference cluster is remote.
 * In both cases, concurrent accesses to the GPT are handled, thanks to the 
 * remote_rwlock protecting each GPT copy.
 *********************************************************************************************
 * @ process   : pointer on local process descriptor copy.
 * @ vpn       : VPN of the faulting PTE.
 * @ returns EXCP_NON_FATAL / EXCP_USER_ERROR / EXCP_KERNEL_PANIC after analysis
 ********************************************************************************************/
error_t vmm_handle_cow( struct process_s * process,
                        vpn_t              vpn );

/*********************************************************************************************
 * This function is called by the vmm_get_pte() function when a page is unmapped.
 * Depending on the vseg type, defined by the <vseg> argument, it returns the PPN 
 * (Physical Page Number) associated to a missing page defined by the <vpn> argument.
 * - For the FILE type, it returns directly the physical page from the file mapper.
 * - For the CODE and DATA types, it allocates a new physical page from the cluster defined
 *   by the <vseg->cxy> field, or by the <vpn> MSB bits for a distributed vseg,
 *   and initialize this page from the .elf file mapper.
 * - For all other types, it allocates a new physical page from the cluster defined
 *   by the <vseg->cxy> field, or by the <vpn> MSB bits for a distributed vseg,
 *   but the new page is not initialized.
 *********************************************************************************************
 * @ vseg   : local pointer on vseg containing the mising page.
 * @ vpn    : Virtual Page Number identifying the missing page.
 * @ ppn    : [out] returned Physical Page Number.
 * return 0 if success / return EINVAL or ENOMEM if error.
 ********************************************************************************************/
error_t vmm_get_one_ppn( vseg_t * vseg,
                         vpn_t    vpn,
                         ppn_t  * ppn );


#endif /* _VMM_H_ */
