/*
 * chdev.h - channel device (chdev) descriptor and API definition.
 * 
 * Authors  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 _CHDEV_H_
#define _CHDEV_H_

#include <kernel_config.h>
#include <hal_kernel_types.h>
#include <xlist.h>
#include <remote_busylock.h>
#include <dev_iob.h>
#include <dev_ioc.h>
#include <dev_nic.h>
#include <dev_pic.h>
#include <dev_fbf.h>
#include <dev_txt.h>

/****************************************************************************************
 *       Channel Device descriptor definition
 *
 * This file defines the kernel representation of a generic (i.e. implementation
 * independant) Channel Device descriptor (in brief "chdev").
 * ALMOS-MKH supports multi-channels peripherals, and defines one separated chdev 
 * descriptor for each channel (and for each RX/TX direction for NIC and TXT devices).
 * Each chdev contains a trans-clusters waiting queue, registering the "client threads",
 * and an associated "server thread", handling these requests.
 * These descriptors are physically distributed on all clusters to minimize contention.
 * Therefore a given I/O operation involve generally three clusters:
 * - the client cluster, containing the client thread,
 * - the server cluster, containing the chdev and the server thread,
 * - the I/O cluster, containing the physical device.
 ***************************************************************************************/

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

struct  chdev_s;
struct  thread_s;
struct  boot_info_s;

/****************************************************************************************
 * These macros extract functionality and  implementation from the peripheral type.
 ***************************************************************************************/
 
#define FUNC_FROM_TYPE( type )    ((uint32_t)(type>>16))
#define IMPL_FROM_TYPE( type )    ((uint32_t)(type & 0x0000FFFF))

/****************************************************************************************
 * This define the generic prototypes for the three functions that must be defined
 * by the drivers implementing a generic device:
 * - "cmd"     : start a blocking I/O operation.
 * - "isr"     : complete an I/O operation.
 * - "aux"     : not for all drivers (implement special functions)
 * The "cmd", "isr", and "aux" driver functions are registered in the generic chdev
 * descriptor at kernel init, and are called to start and complete an I/O operation.  
***************************************************************************************/

typedef void (dev_ini_t) ( xptr_t dev );      
typedef void (dev_cmd_t) ( xptr_t thread );  
typedef void (dev_isr_t) ( struct chdev_s * dev );  
typedef void (dev_aux_t) ( void * args );  

/****************************************************************************************
 * This enum defines the supported generic device types.
 * These types are functionnal types: all (architecture specific) implementations 
 * provide the same set of operations and the same driver API.
 * This enum must be consistent with the enum in files arch_info.h, and arch_class.py.
 *
 * WARNING : The ICU device exist in boot_info to specify the base address of the 
 *           distributed LAPIC controler, but it does not exist as a chdev in the kernel,
 *           as it is hidden in the driver associated to the PIC device.
 ***************************************************************************************/
 
enum dev_func_type 
{
	DEV_FUNC_RAM   =  0,
	DEV_FUNC_ROM   =  1,
	DEV_FUNC_FBF   =  2,
    DEV_FUNC_IOB   =  3,
    DEV_FUNC_IOC   =  4,
	DEV_FUNC_MMC   =  5,
	DEV_FUNC_DMA   =  6,
	DEV_FUNC_NIC   =  7,
	DEV_FUNC_TIM   =  8,
	DEV_FUNC_TXT   =  9,
    DEV_FUNC_ICU   = 10,    
    DEV_FUNC_PIC   = 11,

    DEV_FUNC_NR    = 12,
};

/******************************************************************************************
 * This structure defines a chdev (channel device) descriptor.
 * This structure is NOT replicated, and can be located in any cluster.
 * One server thread is in charge of handling the commands registered in the queue
 * of clients associated to each chdev descriptor.
 *
 * For each device type ***, the specific extension is defined in the "dev_***.h" file.
 *
 * NOTE . For most chdevs, the busylock is used to protect the waiting queue changes,
 *        when a client registers in this queue, or is removed after service.
 *      . This busylock is also used to protect direct access to the shared
 *        kernel TXT0 terminal, that does not use the waiting queue.
 *      . For mostd chdevs, the client waiting queue is an xlist of threads, but it is
 *        a list of sockets for the NIC chdevs. It is unused for ICU, PIC, and IOB.
 *****************************************************************************************/

typedef struct chdev_s
{
	uint32_t             func;        /*! peripheral functionnal type                    */
	uint32_t             impl;        /*! peripheral implementation type                 */
    uint32_t             channel;     /*! channel index                                  */
    bool_t               is_rx;       /*! relevant for NIC and TXT peripherals           */
	xptr_t               base;        /*! extended pointer on channel device segment     */
    char                 name[16];    /*! name (required by DEVFS)                       */

    dev_cmd_t          * cmd;         /*! local pointer on driver CMD function           */
    dev_isr_t          * isr;         /*! local pointer on driver ISR function           */
    dev_aux_t          * aux;         /*! local pointer on driver AUX function           */

    struct thread_s    * server;      /*! local pointer on associated server thread      */

    uint32_t             irq_type;    /*! associated IRQ type in local ICU               */
    uint32_t             irq_id;      /*! associated IRQ index in local ICU              */

	xlist_entry_t        wait_root;   /*! root of clients waiting queue                  */
    remote_busylock_t    wait_lock;   /*! lock protecting waiting queue                  */
    uint32_t             wait_nr;     /*! number of registered clients (NIC only)        */

    union
    {
        iob_extend_t     iob;         /*! IOB specific extension                         */
        ioc_extend_t     ioc;         /*! IOC specific extension                         */
        nic_extend_t     nic;         /*! NIC specific extension                         */
        pic_extend_t     pic;         /*! PIC specific extension                         */
        fbf_extend_t     fbf;         /*! FBF specific extension                         */
        txt_extend_t     txt;         /*! TXT specific extension                         */
    } 
    ext;
}
chdev_t;

/******************************************************************************************
 * This structure defines the channel_devices descriptors directory.
 * Each entry in this structure contains an extended pointer on a chdev descriptor.
 * There is one entry per channel OR per cluster, depending on peripheral type.
 * This structure is replicated in each cluster, and is initialised during kernel init.
 * It is used for fast access to a device descriptor, from type and channel for an
 * external peripheral, or from type and cluster for an internal peripheral.
 * - a "shared" chdev can be accessed by any thread running in any cluster.
 * - a "private" chdev can only be accessed by a thread running in local cluster.
 *****************************************************************************************/

typedef struct chdev_directory_s
{
    xptr_t   iob;                                // external / single channel / shared
    xptr_t   pic;                                // external / single channel / shared

    xptr_t   ioc[CONFIG_MAX_IOC_CHANNELS];       // external / multi-channels / shared
    xptr_t   fbf[CONFIG_MAX_FBF_CHANNELS];       // external / multi-channels / shared
    xptr_t   txt_rx[CONFIG_MAX_TXT_CHANNELS];    // external / multi-channels / shared
    xptr_t   txt_tx[CONFIG_MAX_TXT_CHANNELS];    // external / multi-channels / shared
    xptr_t   nic_rx[CONFIG_MAX_NIC_CHANNELS];    // external / multi-channels / shared
    xptr_t   nic_tx[CONFIG_MAX_NIC_CHANNELS];    // external / multi-channels / shared

    xptr_t   mmc[CONFIG_MAX_CLUSTERS];           // internal / single channel / shared

    xptr_t   dma[CONFIG_MAX_DMA_CHANNELS];       // internal / multi-channels / private
}
chdev_directory_t;

/****************************************************************************************
 * This function display relevant values for a chdev descriptor.
 ****************************************************************************************
 * @ chdev   : pointer on chdev.
 ***************************************************************************************/
void chdev_print( chdev_t * chdev );

/****************************************************************************************
 * This function returns a printable string for a device functionnal types.
 ****************************************************************************************
 * @ func_type  : functionnal type.
 * @ return pointer on string.
 ***************************************************************************************/
char * chdev_func_str( uint32_t func_type );

/****************************************************************************************
 * This  function allocates memory and initializes a chdev descriptor in local cluster,
 * from arguments values.  It should be called by a local thread. 
 * The device specific fields are initialised later.
 ****************************************************************************************
 * @ func      : functionnal type.
 * @ impl      : implementation type.
 * @ channel   : channel index / for multi-channels peripherals.
 * @ is_rx     : for NIC peripheral / NIC RX if true / NIC TX if false.
 * @ base      : extended pointer on peripheral segment base.
 * @ return a local pointer on created chdev / return NULL if failure.
 ***************************************************************************************/
chdev_t * chdev_create( uint32_t    func,
                        uint32_t    impl,
                        uint32_t    channel,
                        bool_t      is_rx,
                        xptr_t      base );

/****************************************************************************************
 * This generid function is executed by an user thread requesting an IOC or TXT chdev
 * service. It registers the calling thread in the waiting queue of a the remote
 * chdev descriptor identified by the <chdev_xp> argument.
 * It activates (i.e. unblocks) the server thread associated to chdev, blocks itself,
 * and deschedule.  It is supposed to be re-activated by the server thread. 
 * It can be called by a thread running in any cluster.
 * It cannot be used for a NIC or FBF chdev, because it is only convenient for one shot
 * I/O operations, as the server thread removes the client thread from the waiting
 * queue when it starts to execute the command.
 ****************************************************************************************
 * Implementation Note:
 * The following actions are executed in a critical section, thanks to the
 * busylock_acquire / busylock_release mechanism :
 * 1) it takes the lock protecting the waiting queue.
 * 2) it registers client thread in the server queue. 
 * 3) it unblocks the server thread from the THREAD_BLOCKED_CLIENT condition.
 * 4) it blocks the client thread on the THREAD_BLOCKED_IO condition.
 * 5) it send an IPI to the core running the server thread to force scheduling.
 * 6) it releases the lock protecting waiting queue.
 * 7) it deschedules.
 ****************************************************************************************
 * @ chdev_xp  : extended pointer on remote chdev descriptor.
 ***************************************************************************************/
void chdev_register_command( xptr_t chdev_xp );

/****************************************************************************************
 * This generic function is executed by the server thread associated to an IOC or TXT
 * chdev identified by the <chdev> argument, to execute all commands registered in the
 * waiting queue attached to this chev. 
 * When the clients queue is empty, the server thread blocks on the THREAD_BLOCKED_CLIENT
 * condition and deschedules. It is supposed to be re-activated by a client thread 
 * registering a new command.
 * It cannot be used for a NIC or FBF chdev, because it is only convenient for one shot
 * I/O operations, as the server thread removes the client thread from the waiting
 * queue when it starts to execute the command.
 ****************************************************************************************
 * Implementation Note:
 * All driver CMD functions are supposed to be blocking, and return only when the command
 * is completed. These functions can use either a busy waiting policy, or a descheduling
 * policy, blocking on the THREAD_BLOCKED_ISR condition. In the descheduling scenario,
 * the server thread is supposed to be reactivated by the ISR attached to the hardware
 * interrupts signaling command completion.
 ****************************************************************************************
 * @ chdev   : local pointer on device descriptor.
 ***************************************************************************************/
void chdev_server_func( chdev_t * chdev );

/****************************************************************************************
 * This function returns an extended pointer on the chdev associated to a pseudo file
 * descriptor (type INODE_TYPE_DEV) identified by the <file_xp> argument.
 * It can be called by a thread running in any cluster.
 * It enters kernel panic if the inode has not the expected type.
 ****************************************************************************************
 * @ file_xp   : extended pointer on the pseudo file descriptor.
 * @ return an extended pointer on chdev.
 ***************************************************************************************/
xptr_t chdev_from_file( xptr_t file_xp );

/****************************************************************************************
 * This function displays the local copy of the external chdevs directory.
 * (global variable replicated in all clusters)
 ***************************************************************************************/
void chdev_dir_display( void );

/****************************************************************************************
 * This function displays the list of threads registered in the queue associated
 * to the chdev identified by the <chdev_xp>. 
 ****************************************************************************************
 * # root_xp  : extended pointer
 ***************************************************************************************/
void chdev_queue_display( xptr_t chdev_xp );

#endif	/* _CHDEV_H_ */
