/*
 * pthread.h - User level <pthread> library definition.
 * 
 * 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
 */

#ifndef _PTHREAD_H_
#define _PTHREAD_H_

//////////////////////////////////////////////////////////////////////////////////////////////
//             POSIX thread related functions
// 
//  This include the thread creation/destruction, as well as the synchronisations:
//  barriers, mutexes, and condition variables.
//////////////////////////////////////////////////////////////////////////////////////////////

#include <shared_pthread.h>

/********************************************************************************************* 
 * This function creates a new user thread. The <user_attr> argument is a pointer
 * on a structure containing the thread attributes, defined in thread.h file.
 *********************************************************************************************
 * @ trdid       : [out] buffer for created thread identifier in process.
 * @ user_attr   : [in]  pointer on thread attributes structure.
 * @ start_func  : [in]  pointer on start function.
 * @ start_args  : [in]  pointer on start function arguments.
 * @ return 0 if success / return -1 if failure.
 ********************************************************************************************/
int pthread_create( pthread_t            * trdid,
                    const pthread_attr_t * attr,
                    void                 * start_func,
                    void                 * start_args );

/********************************************************************************************* 
 * This blocking function causes the calling thread to wait for the termination of a target
 * thread identified by the <trdid> argument. The <exit_value> defines the buffer to store
 * the pointer returned by the terminating thread.
 *********************************************************************************************
 * @ trdid       : target thread identifier in process.
 * @ start_args  : [in]  pointer on start function arguments.
 * @ return 0 if success / return -1 if failure.
 ********************************************************************************************/
int pthread_join( pthread_t    trdid,
                  void      ** exit_value );

/********************************************************************************************* 
 * This function is used to indicate that storage for the target thread, identified by the
 * <trdid> argument can be reclaimed when the thread terminates.
 * If target thread has not terminated, pthread_detach() will not cause it to terminate.
 *********************************************************************************************
 * @ trdid       : target thread identifier in process.
 * @ return 0 if success / return -1 if failure.
 ********************************************************************************************/
int pthread_detach( pthread_t   trdid );

/********************************************************************************************* 
 * This function terminates the execution of the calling thread, and makes the exit_value 
 * pointer available to any successful pthread_join() with the terminating thread.
 *********************************************************************************************
 * @ exit_vallue  : [in] pointer to be returned to parent thread if thread is attached.
 * @ return 0 if success / return -1 if failure.
 ********************************************************************************************/
int pthread_exit( void * exit_value );

/********************************************************************************************* 
 * This function calls the scheduler for the core running the calling thread.
 * WARNING: It is not defined by POSIX.
 *********************************************************************************************
 * @ return always 0.
 ********************************************************************************************/
int pthread_yield( void );


//////////////////////////////////////////////////////////////////////////////////////////////
//                 POSIX barrier related functions
//
// These functions are implemented in user space. Only the pthread_barrier_init() function
// uses system calls to build the distributed quad-tree infrastructure.
//////////////////////////////////////////////////////////////////////////////////////////////

/********************************************************************************************* 
 * These structures defines a hierarchical, POSIX compliant, barrier.
 * - If the barrier attribute in the pthread_barrier_init() is NULL, it is implemented
 *   as a simple, sense reversing barrier, localised in the calling thread cluster.
 * - If the barrier attribute is defined, it is implemented as a hierarchical, physically
 *   distributed quad-tree, covering all clusters specified, with the following constraints:
 *   . The involved clusters form a mesh [x_size * y_size]
 *   . The lower left involved cluster is cluster(0,0)  
 *   . The number of threads per cluster is the same in all clusters.
 *
 * Implementation note:
 * - The quad three is implemented as a three dimensions array of node[x][y][l]
 *   . [x][y] are the cluster coordinates / max values are (QDT_XMAX-1), (QDT_YMAX-1)
 *   . [l] is the node level / 0 for terminal nodes / (QDT_LMAX-1) for the root node
 ********************************************************************************************/

#define  QDT_XMAX    16                /*! max number of clusters in a row                  */
#define  QDT_YMAX    16                /*! max number of clusters in a column               */
#define  QDT_LMAX    5                 /*! max depth of the quad tree                       */
#define  QDT_YWIDTH  4                 /*! Y field in cxy, for cxy <=> (x,y) translation    */
#define  QDT_YMASK   0xF               /*! Y field in cxy, for cxy <=> (x,y) translation    */

typedef struct sqt_node_s
{
    volatile unsigned int sense;       /*! barrier state (toggle)                           */
    volatile unsigned int count;       /*! number of not arrived tasks                      */
    unsigned int          arity;       /*! number of locally expected tasks                 */
    unsigned int          level;       /*! hierarchical level (0 is bottom)                 */
    struct sqt_node_s   * parent;      /*! pointer on parent node (NULL for root)           */
    struct sqt_node_s   * child[4];    /*! pointer on children node (NULL for bottom)       */
}
sqt_node_t;

typedef struct pthread_barrier_s
{
    sqt_node_t          * node[QDT_XMAX][QDT_YMAX][QDT_LMAX];
}
pthread_barrier_t;

typedef struct pthread_barrierattr_s
{
    unsigned int          x_size;      /*! number of clusters in a row (0 to x_size-1)      */
    unsigned int          y_size;      /*! number of clusters in a column (0 to y_size-1)   */
    unsigned int          nthreads;    /*! number of expected threads in a cluster          */
}
pthread_barrierattr_t;

/********************************************************************************************* 
 * This function allocates resources required to use the barrier referenced by the <barrier>
 * argument, and initializes the barrier from attributes referenced by the <attr> argument.
 * If <attr> is NULL, the default barrier attributes shall be used. 
 * The results are undefined if pthread_barrier_init() is called when any thread is blocked 
 * on the barrier, or is used without first being initialized, or if pthread_barrier_init()
 * is called specifying an already initialized barrier.
 *********************************************************************************************
 * @ barrier     : [in]  pointer on barrier in user space.
 * @ attr        : [in]  pointer on attributes structure.
 * @ count       : [in]  number of expected threads.
 * @ return 0 if success / return EINVAL if illegal attributes.
 ********************************************************************************************/
int pthread_barrier_init( pthread_barrier_t           * barrier,
                          const pthread_barrierattr_t * attr,
                          unsigned int                  count ); 

/********************************************************************************************* 
 * This function synchronizes participating threads at the barrier referenced by <barrier>.
 * The calling is blocked until the required number of threads have called the function
 * pthread_barrier_wait() specifying the barrier.
 * When the required number of threads have called pthread_barrier_wait(), the constant
 * PTHREAD_BARRIER_SERIAL_THREAD is returned to one unspecified thread and zero is returned
 * to each of the remaining threads. 
 *********************************************************************************************
 * @ barrier     : [in]  pointer on barrier in user space.
 * @ return 0 if success / return EINVAL if the barrier was not properly initialized.
 ********************************************************************************************/
int pthread_barrier_wait( pthread_barrier_t * barrier );

/********************************************************************************************* 
 * This function destroy the barrier referenced by <barrier> and release all resources used
 * by the barrier. The effect of subsequent use of the barrier is undefined until the barrier
 * is reinitialized by another call to pthread_barrier_init().
 * An implementation may use this function to set barrier to an invalid value. 
 * The results are undefined if pthread_barrier_destroy() is called when a thread is blocked
 * on the barrier, or if this function is called with an uninitialized barrier.
 *********************************************************************************************
 * @ barrier     : [in]  pointer on barrier in user space.
 ********************************************************************************************/
int pthread_barrier_destroy( pthread_barrier_t * barrier );
   

//////////////////////////////////////////////////////////////////////////////////////////////
//                      POSIX mutex related functions
//////////////////////////////////////////////////////////////////////////////////////////////

/********************************************************************************************* 
 * This function initialise the mutex identified by the <mutex> argument.
 * The <attr> argument is not supported yet, and must be NULL.
 *********************************************************************************************
 * @ mutex     : pointer on mutex in user space.
 * @ attr      : pointer on attributes structure / must be NULL.
 * @ return 0 if success / return -1 if failure.
 ********************************************************************************************/
int pthread_mutex_init( pthread_mutex_t           * mutex,
                        const pthread_mutexattr_t * attr );

/********************************************************************************************* 
 * This function destroy the mutex identified by the <mutex> argument.
 *********************************************************************************************
 * @ mutex     : pointer on mutex in user space.
 * @ return 0 if success / return -1 if failure.
 ********************************************************************************************/
int pthread_mutex_destroy( pthread_mutex_t * mutex );

/********************************************************************************************* 
 * This bloking function locks the mutex identified by the <mutex> argument,
 * and blocks until it becomes available.
 *********************************************************************************************
 * @ mutex     : pointer on mutex in user space.
 * @ return 0 if success / return -1 if failure.
 ********************************************************************************************/
int pthread_mutex_lock( pthread_mutex_t * mutex );

/********************************************************************************************* 
 * This function unlocks the mutex identified by the <mutex> argument.
 *********************************************************************************************
 * @ mutex     : pointer on mutex in user space.
 * @ return 0 if success / return -1 if failure.
 ********************************************************************************************/
int pthread_mutex_unlock( pthread_mutex_t * mutex );

/********************************************************************************************* 
 * This function tries to lock the mutex identified by the <mutex> argument,
 * but don't block if the mutex is locked by another thread, including the current thread.
 *********************************************************************************************
 * @ mutex     : pointer on mutex in user space.
 * @ return 0 if success / return -1 if mutex already taken.
 ********************************************************************************************/
int pthread_mutex_trylock( pthread_mutex_t * mutex );


//////////////////////////////////////////////////////////////////////////////////////////////
//                      POSIX condvar related functions
//////////////////////////////////////////////////////////////////////////////////////////////

/********************************************************************************************* 
 * This function initializes a condition variable identified by the <cond> argument.
 * WARNING: the <attr> argument is not supported and must be NULL.
 *********************************************************************************************
 * @ cond   : [in] pointer on condition in user space.
 * @ attr   : [in] pointer on condition attribute (must be NULL).
 * @ return 0 if success / return -1 if failure.
 ********************************************************************************************/
int pthread_cond_init( pthread_cond_t     * cond,
                       pthread_condattr_t * attr );

/********************************************************************************************* 
 * This function atomically unlocks the <mutex> and blocks the calling thread on the 
 * condition specified by the <cond> argument.  The thread unblocks only after another
 * thread calls the pthread_cond_signal() or pthread_cond_broadcast() functions with the
 * same condition variable.  The mutex must be locked before calling this function,
 * otherwise the behavior is undefined. Before the pthread_cond_wait() function returns
 * to the calling function, it re-acquires the <mutex>.
 *********************************************************************************************
 * @ cond      : pointer on condition in user space.
 * @ mutex     : pointer on mutex in user space.
 * @ return 0 if success / return -1 if failure.
 ********************************************************************************************/
int pthread_cond_wait( pthread_cond_t  * cond,
                       pthread_mutex_t * mutex );

/********************************************************************************************* 
 * This function unblocks one thread blocked on condition specified by the <cond> argument. 
 *********************************************************************************************
 * @ cond      : pointer on condition in user space.
 * @ return 0 if success / return -1 if failure.
 ********************************************************************************************/
int pthread_cond_signal( pthread_cond_t * cond );

/********************************************************************************************* 
 * This function unblocks all threads blocked on condition specified by the <cond> argument. 
 *********************************************************************************************
 * @ cond      : pointer on condition in user space.
 * @ return 0 if success / return -1 if failure.
 ********************************************************************************************/
int pthread_cond_broadcast( pthread_cond_t * cond );

/********************************************************************************************* 
 * This function delete the condition variable specified by the <cond> argument. 
 *********************************************************************************************
 * @ cond      : pointer on condition in user space.
 * @ return 0 if success / return -1 if failure.
 ********************************************************************************************/
int pthread_cond_destroy( pthread_cond_t * cond );



#endif  // _PTHREAD_H_
