/*
 * chdev.h - channel device (chdev) descriptor definition.
 * 
 * Authors  Alain Greiner    (2016)
 *
 * 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_spinlock.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 the NIC and TXT devices).
 * Each chdev contains a waiting queue, registering the "client threads" requests,
 * 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 the functionality and the 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 descriptor.
 * For multi-channels device, there is one chdev descriptor per channel.
 * This structure is NOT replicated, and can be located in any cluster.
 * One kernel thread, in charge of handling the commands registered in the waiting queue
 * of client threads is associated to each chdev descriptor (not for ICU, PIC, IOB).
 * For each device type ***, the specific extension is defined in the "dev_***.h" file.
 *****************************************************************************************/

typedef struct chdev_s
{
	uint32_t             func;        /*! peripheral functionnal type                    */
	uint32_t             impl;        /*! peripheral inplementation subtype              */
    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              */

	remote_spinlock_t    wait_lock;	  /*! lock protecting exclusive access to queue      */
    xlist_entry_t        wait_root;   /*! root of waiting threads queue                  */

    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 function registers the calling thread in the waiting queue of a remote 
 * chdev descriptor, activates (i.e. unblock) the server thread associated to chdev,
 * and blocks itself on the THREAD_BLOCKED_IO condition.
 ******************************************************************************************
 * @ chdev_xp  : extended pointer on remote chdev descriptor.
 *****************************************************************************************/
void chdev_register_command( xptr_t chdev_xp );

/******************************************************************************************
 * This function is executed by the server thread associated to a chdev descriptor.
 * It executes an infinite loop to handle sequencially all commands registered by the
 * client threads in the device waiting queue, until the queue is empty.
 * The driver CMD function being blocking, these functions 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_IO_ISR condition, and reactivated by the ISR.
 * When the waiting queue is empty, the server thread blocks on the THREAD_BLOCKED_IO_CMD
 * condition and deschedule. It is re-activated by a client thread registering a command.
 ******************************************************************************************
 * @ chdev   : local pointer on device descriptor.
 *****************************************************************************************/
void chdev_sequencial_server( 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();

/******************************************************************************************
 * 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_ */
