#!/usr/bin/env python

import sys

##########################################################################################
#  File   : arch_classes.py
#  Date   : 2016
#  Author : Alain Greiner
#  Copyright (c)  UPMC Sorbonne Universites
#########################################################################################
#  This file contains the python classes required to define a generic hardware 
#  architecture for the ALMOS-MK operating system.
#  It handle 4 types of objects: clusters, cores, devices and irqs.
#  - The number of cluster is variable (can be one). 
#  - The cluster topology can be a 2D mesh or a simple 1D array.
#  - The number of cores per cluster is variable (can be zero). 
#  - The number of addressable devices per cluster is variable.
#  - The size of the physical memory bank per cluster is variable.
#  An adressable device can be a physical memory bank or a peripheral.
#  Each cluster cover a fixed size segment in physical address space, 
# that is defined by (PADDR_WIDTH - X_WIDTH - Y_WIDTH)
#########################################################################################
# Implementation Note:
# The objects used to describe an architecture are distributed in the python structure:
# For example the set of cores and the set of devices are split in several subsets 
# (one subset of cores and one subset of devices per cluster). 
# In the generated C binary data structure, all objects of same type
# are stored in a linear array (one single array for all cores for example).
# For all objects, we compute and store in the python object  a "global index"
# corresponding to the index in this global array, and this index can be used as
# a pseudo-pointer to identify a specific object of a given type.
#########################################################################################

#########################################################################################
#  Define global parameters 
#########################################################################################

ARCHINFO_SIGNATURE = 0xBABE2016    # magic number indicating a valid C BLOB
PAGE_SIZE          = 0x1000        # to check peripherals alignment

#########################################################################################
# These arrays define the supported types of peripherals.
# They must be kept consistent with values defined in file arch_info.h 
#########################################################################################

DEVICE_TYPES_STR = [
    'RAM_SCL',         # 0.0
    'ROM_SCL',         # 1.0
    'FBF_SCL',         # 2.0
    'IOB_TSR',         # 3.0
    'IOC_BDV',         # 4.0
    'IOC_HBA',         # 4.1
    'IOC_SDC',         # 4.2
    'IOC_SPI',         # 4.3
    'IOC_RDK',         # 4.4
    'MMC_TSR',         # 5.0
    'DMA_SCL',         # 6.0
    'NIC_CBF',         # 7.0
    'TIM_SCL',         # 8.0
    'TXT_TTY',         # 9.0
    'TXT_MTY',         # 9.1
    'ICU_XCU',         # A.0
    'PIC_TSR',         # B.0
    ]
   
DEVICE_TYPES_INT = [
    0x00000000,        # 0.0
    0x00010000,        # 1.0
    0x00020000,        # 1.0
    0x00030000,        # 3.0
    0x00040000,        # 4.0
    0x00040001,        # 4.1
    0x00040002,        # 4.2
    0x00040003,        # 4.3
    0x00040004,        # 4.4
    0x00050000,        # 5.0
    0x00060000,        # 6.0
    0x00070000,        # 7.0
    0x00080000,        # 8.0
    0x00090000,        # 9.0
    0x00090001,        # 9.1
    0x000A0000,        # A.0
    0x000B0000,        # B.0
    ]

 #########################################################################################
class Archinfo( object ):          
#########################################################################################
    def __init__( self,
                  name,              # architecture instance name 
                  x_size,            # number of clusters in a row
                  y_size,            # number of clusters in a column
                  cores_max,         # max number of cores per cluster
                  devices_max,       # max number of devices per cluster
                  paddr_width,       # number of bits in physical address
                  x_width,           # number of bits for x coordinate
                  y_width,           # number of bits for y coordinate
                  irqs_per_core,     # number or IRQs from ICU to one core 
                  io_cxy,            # IO cluster identifier
                  boot_cxy,          # boot cluster identifier
                  cache_line,        # number of bytes in cache line
                  reset_address,     # Preloader physical base address
                  p_width ):         # TSAR specific : number of bits to code core lid

        assert ( x_size <= (1<<x_width) )
        assert ( y_size <= (1<<y_width) )

        self.signature      = ARCHINFO_SIGNATURE
        self.name           = name
        self.x_size         = x_size
        self.y_size         = y_size
        self.cores_max      = cores_max
        self.devices_max    = devices_max
        self.paddr_width    = paddr_width
        self.x_width        = x_width
        self.y_width        = y_width
        self.irqs_per_core  = irqs_per_core
        self.io_cxy         = io_cxy
        self.boot_cxy       = boot_cxy
        self.cache_line     = cache_line
        self.reset_address  = reset_address
        self.p_width        = p_width

        self.total_cores    = 0
        self.total_devices  = 0
        self.total_irqs     = 0

        self.clusters       = []

        for x in xrange( self.x_size ):
            for y in xrange( self.y_size ):

                # call cluster constructor
                cxy = (x<<y_width) + y 
                cluster = Cluster( cxy )

                # update cluster global index
                cluster.index = (x * self.y_size) + y

                # register cluster in Archinfo
                self.clusters.append( cluster )

        return

    ##########################   add a device in a cluster
    def addDevice( self,
                   ptype,              # device type
                   base,               # associated pseg base address
                   size,               # associated pseg length (bytes)
                   channels = 1,       # number of channels
                   arg0     = 0,       # optional argument (semantic depends on ptype)
                   arg1     = 0,       # optional argument (semantic depends on ptype)
                   arg2     = 0,       # optional argument (semantic depends on ptype)
                   arg3     = 0 ):     # optional argument (semantic depends on ptype)

        # computes cluster identifier and global index from the base address
        cxy = base >> (self.paddr_width - self.x_width - self.y_width)
        x          = cxy >> (self.y_width);
        y          = cxy & ((1 << self.y_width) - 1)
        cluster_id = (x * self.y_size) + y

        assert (x < self.x_size) and (y < self.y_size)
        assert (base & (PAGE_SIZE-1) == 0)
        assert (ptype in DEVICE_TYPES_STR)

        # call device constructor
        device = Device( base, size, ptype, channels, arg0, arg1, arg2, arg3 )

        # register device in cluster
        self.clusters[cluster_id].devices.append( device )

        # update device global index
        device.index = self.total_devices
        self.total_devices += 1

        return device

    ################################   add an input IRQ in a device
    def addIrq( self,
                dstdev,                # destination device (PIC or ICU)
                port,                  # input IRQ port index
                srcdev,                # source device
                channel = 0,           # source device channel
                is_rx = False ):       # I/O operation direction

        assert (dstdev.ptype == 'ICU_XCU') or (dstdev.ptype == 'PIC_TSR')
        assert (port < dstdev.arg0)

        # call Irq constructor
        irq = Irq( port , srcdev, channel , is_rx )

        # register IRQ in destination device
        dstdev.irqs.append( irq )

        # update IRQ global index
        irq.index = self.total_irqs
        self.total_irqs += 1

        # pointer from the source to the interrupt controller device
        if (srcdev.irq_ctrl == None): srcdev.irq_ctrl = dstdev

        if (srcdev.irq_ctrl != dstdev):
            print '[genarch error] in addIrq():'
            print '    two different interrupt controller for the same device'
            sys.exit(1)

        return irq

    ##########################    add a core in a cluster
    def addCore( self,
                 gid,                  # global hardware identifier
                 cxy,                  # cluster identifier
                 lid ):                # local index in cluster

        assert ((cxy >> self.y_width) < self.x_size)
        assert ((cxy & ((1<<self.y_width)-1)) < self.y_size)
        assert (lid < self.cores_max)
 
        # call Core contructor
        core = Core( gid, cxy, lid )

        # compute cluster global index from cluster identifier
        x          = cxy>>self.y_width
        y          = cxy & ((1<<self.y_width)-1)
        cluster_id = (x * self.y_size) + y

        # register core in cluster
        self.clusters[cluster_id].cores.append( core )

        # update core global index
        core.index = self.total_cores
        self.total_cores += 1

        return core

    #################################
    def str2bytes( self, nbytes, s ):    # string => nbytes_packed byte array

        byte_stream = bytearray()
        length = len( s )
        if length < (nbytes - 1):
            for b in s:
                byte_stream.append( b )
            for x in xrange(nbytes-length):
                byte_stream.append( '\0' )
        else:
            print '[genarch error] in str2bytes()'
            print '    string %s too long' % s
            sys.exit(1)

        return byte_stream

    ###################################
    def int2bytes( self, nbytes, val ):    # integer => nbytes litle endian byte array

        byte_stream = bytearray()
        for n in xrange( nbytes ):
            byte_stream.append( (val >> (n<<3)) & 0xFF )

        return byte_stream

    ################
    def xml( self ):    # compute string for xml file generation

        s = '<?xml version="1.0"?>\n\n'
        s += '<arch_info signature    = "0x%x"\n' % (self.signature)
        s += '           name         = "%s"\n'   % (self.name)
        s += '           x_size       = "%d"\n'   % (self.x_size)
        s += '           y_size       = "%d"\n'   % (self.y_size)
        s += '           cores        = "%d"\n'   % (self.cores_max)
        s += '           io_cxy       = "%d" >\n' % (self.io_cxy)
        s += '\n'

        s += '    <clusterset>\n'
        for x in xrange ( self.x_size ):
            for y in xrange ( self.y_size ):
                cluster_id = (x * self.y_size) + y
                s += self.clusters[cluster_id].xml()
        s += '    </clusterset>\n'
        s += '\n'

        s += '</arch_info>\n'
        return s

    ##########################
    def cbin( self, verbose ):     # C binary structure for "archinfo.bin" file generation 

        byte_stream = bytearray()

        # header
        byte_stream += self.int2bytes(4,  self.signature)
        byte_stream += self.int2bytes(4,  self.x_size)
        byte_stream += self.int2bytes(4,  self.y_size)
        byte_stream += self.int2bytes(4,  self.paddr_width)
        byte_stream += self.int2bytes(4,  self.x_width)
        byte_stream += self.int2bytes(4,  self.y_width)
        byte_stream += self.int2bytes(4,  self.cores_max)
        byte_stream += self.int2bytes(4,  self.devices_max)

        byte_stream += self.int2bytes(4,  self.total_cores)
        byte_stream += self.int2bytes(4,  self.total_devices)
        byte_stream += self.int2bytes(4,  self.total_irqs)
        byte_stream += self.int2bytes(4,  self.io_cxy)
        byte_stream += self.int2bytes(4,  self.boot_cxy)
        byte_stream += self.int2bytes(4,  self.irqs_per_core)
        byte_stream += self.int2bytes(4,  self.cache_line)
        byte_stream += self.int2bytes(4,  0)

        byte_stream += self.str2bytes(64, self.name)

        if ( verbose ):
            print '\n'
            print 'name          = %s' % self.name
            print 'signature     = %x' % self.signature
            print 'x_size        = %d' % self.x_size
            print 'y_size        = %d' % self.y_size
            print 'total_cores   = %d' % self.total_cores
            print 'total_devices = %d' % self.total_devices
            print 'total_irqs    = %d' % self.total_irqs
            print '\n'

        # cores array
        index = 0
        for cluster in self.clusters:
            for core in cluster.cores:
                byte_stream += core.cbin( self, verbose, index )
                index += 1

        if ( verbose ): print '\n'

        # clusters array
        index = 0
        for cluster in self.clusters:
            byte_stream += cluster.cbin( self, verbose, index )
            index += 1

        if ( verbose ): print '\n'

        # devices array
        index = 0
        for cluster in self.clusters:
            for device in cluster.devices:
                byte_stream += device.cbin( self, verbose, index )
                index += 1

        if ( verbose ): print '\n'

        # irqs array
        index = 0
        for cluster in self.clusters:
            for device in cluster.devices:
                for irq in device.irqs:
                    byte_stream += irq.cbin( self, verbose, index )
                    index += 1

        if ( verbose ): print '\n'

        return byte_stream
    # end of cbin()


    ######################################################################
    def hard_config( self ):     # compute string for hard_config.h file 
                                 # required by
                                 # - top.cpp compilation
                                 # - almos-mk bootloader compilation
                                 # - tsar_preloader compilation

        # for each device type, define default values
        # for pbase address, size, number of components, and channels
        nb_ram       = 0
        ram_channels = 0
        ram_base     = 0xFFFFFFFFFFFFFFFF
        ram_size     = 0

        nb_rom       = 0
        rom_channels = 0
        rom_base     = 0xFFFFFFFFFFFFFFFF
        rom_size     = 0

        nb_fbf       = 0
        fbf_channels = 0
        fbf_base     = 0xFFFFFFFFFFFFFFFF
        fbf_size     = 0
        fbf_arg0     = 0
        fbf_arg1     = 0

        nb_iob       = 0
        iob_channels = 0
        iob_base     = 0xFFFFFFFFFFFFFFFF
        iob_size     = 0

        nb_ioc       = 0
        ioc_channels = 0
        ioc_base     = 0xFFFFFFFFFFFFFFFF
        ioc_size     = 0
        use_ioc_bdv  = False
        use_ioc_sdc  = False
        use_ioc_hba  = False
        use_ioc_spi  = False
        use_ioc_rdk  = False

        nb_mmc       = 0
        mmc_channels = 0
        mmc_base     = 0xFFFFFFFFFFFFFFFF
        mmc_size     = 0

        nb_dma       = 0
        dma_channels = 0
        dma_base     = 0xFFFFFFFFFFFFFFFF
        dma_size     = 0

        nb_nic       = 0
        nic_channels = 0
        nic_base     = 0xFFFFFFFFFFFFFFFF
        nic_size     = 0

        nb_sim       = 0
        sim_channels = 0
        sim_base     = 0xFFFFFFFFFFFFFFFF
        sim_size     = 0

        nb_tim       = 0
        tim_channels = 0
        tim_base     = 0xFFFFFFFFFFFFFFFF
        tim_size     = 0

        nb_txt       = 0
        txt_channels = 0
        txt_base     = 0xFFFFFFFFFFFFFFFF
        txt_size     = 0

        nb_icu       = 0
        icu_channels = 0
        icu_base     = 0xFFFFFFFFFFFFFFFF
        icu_size     = 0
        icu_arg0     = 0

        nb_pic       = 0
        pic_channels = 0
        pic_base     = 0xFFFFFFFFFFFFFFFF
        pic_size     = 0

        nb_rom        = 0
        rom_channels  = 0
        rom_base      = 0xFFFFFFFFFFFFFFFF
        rom_size      = 0

        # get devices attributes
        for cluster in self.clusters:
            for device in cluster.devices:

                if ( device.ptype == 'RAM_SCL' ):
                    ram_base     = device.base
                    ram_size     = device.size
                    ram_channels = device.channels
                    nb_ram +=1
                
                elif ( device.ptype == 'ROM_SCL' ):
                    rom_base     = device.base
                    rom_size     = device.size
                    rom_channels = device.channels
                    nb_rom +=1

                elif ( device.ptype == 'FBF_SCL' ):
                    fbf_base     = device.base
                    fbf_size     = device.size
                    fbf_channels = device.channels
                    fbf_arg0     = device.arg0
                    fbf_arg1     = device.arg1
                    nb_fbf +=1

                elif ( device.ptype == 'IOB_TSR' ):
                    iob_base     = device.base
                    iob_size     = device.size
                    iob_channels = device.channels
                    nb_iob +=1

                elif ( device.ptype == 'IOC_BDV' ):
                    ioc_base     = device.base
                    ioc_size     = device.size
                    ioc_channels = device.channels
                    use_ioc_bdv  = True
                    nb_ioc += 1
                elif ( device.ptype == 'IOC_HBA' ):
                    ioc_base     = device.base
                    ioc_size     = device.size
                    ioc_channels = device.channels
                    use_ioc_hba  = True
                    nb_ioc += 1
                elif ( device.ptype == 'IOC_SDC' ):
                    ioc_base     = device.base
                    ioc_size     = device.size
                    ioc_channels = device.channels
                    use_ioc_sdc  = True
                    nb_ioc += 1
                elif ( device.ptype == 'IOC_SPI' ):
                    ioc_base     = device.base
                    ioc_size     = device.size
                    ioc_channels = device.channels
                    use_ioc_spi  = True
                    nb_ioc += 1
                elif ( device.ptype == 'IOC_RDK' ):
                    ioc_base     = device.base
                    ioc_size     = device.size
                    ioc_channels = device.channels
                    use_ioc_rdk  = True
                    nb_ioc += 1

                elif ( device.ptype == 'MMC_TSR' ):
                    mmc_base     = device.base
                    mmc_size     = device.size
                    mmc_channels = device.channels
                    nb_mmc +=1

                elif ( device.ptype == 'DMA_SCL' ):
                    dma_base     = device.base
                    dma_size     = device.size
                    dma_channels = device.channels
                    nb_dma +=1

                elif ( device.ptype == 'NIC_CBF' ):
                    nic_base     = device.base
                    nic_size     = device.size
                    nic_channels = device.channels
                    nb_nic +=1

                elif ( device.ptype == 'TIM_SCL' ):
                    tim_base     = device.pseg.base
                    tim_size     = device.pseg.size
                    tim_channels = device.channels
                    nb_tim +=1

                elif ( device.ptype == 'TXT_TTY' ):
                    txt_base     = device.base
                    txt_size     = device.size
                    txt_channels = device.channels
                    nb_txt +=1

                elif ( device.ptype == 'ICU_XCU' ):
                    icu_base     = device.base
                    icu_size     = device.size
                    icu_channels = device.channels
                    icu_arg0     = device.arg0
                    icu_arg1     = device.arg1
                    icu_arg2     = device.arg2
                    icu_arg3     = device.arg3
                    nb_icu +=1

                elif ( device.ptype == 'PIC_TSR' ):
                    pic_base     = device.base
                    pic_size     = device.size
                    pic_channels = device.channels
                    nb_pic +=1

        # one and only one IOC controller
        assert ( nb_ioc == 1 )

        # compute rdk_base and rdk_size
        if( use_ioc_rdk ):
            rdk_base = ioc_base
            rdk_size = ioc_size
        else:
            rdk_base = 0
            rdk_size = 0

        # Compute total number of cores, devices and irqs
        nb_total_cores   = self.total_cores
        nb_total_devices = self.total_devices
        nb_total_irqs    = self.total_irqs

        # boot core has (cxy == boot_cxy) and (lid == 0)
        for cluster in self.clusters:
            if( cluster.cxy == self.boot_cxy ): boot_core_gid = cluster.cores[0].gid

        # compute mask to get local physical address (cluster independant)
        local_paddr_width   = self.paddr_width - self.x_width - self.y_width
        local_physical_mask = (1<<local_paddr_width)-1

        # build string
        s =  '/* Generated by genarch for %s */\n'  % self.name
        s += '\n'
        s += '#ifndef HARD_CONFIG_H\n'
        s += '#define HARD_CONFIG_H\n'
        s += '\n'

        s += '/* General platform parameters */\n'
        s += '\n'
        s += '#define X_SIZE                 %d\n'    % self.x_size
        s += '#define Y_SIZE                 %d\n'    % self.y_size
        s += '#define PADDR_WIDTH            %d\n'    % self.paddr_width
        s += '#define X_WIDTH                %d\n'    % self.x_width
        s += '#define Y_WIDTH                %d\n'    % self.y_width
        s += '#define P_WIDTH                %d\n'    % self.p_width  
        s += '#define X_IO                   %d\n'    % (self.io_cxy >> self.y_width)
        s += '#define Y_IO                   %d\n'    % (self.io_cxy & ((1<<self.y_width)-1))
        s += '#define NB_PROCS_MAX           %d\n'    % self.cores_max
        s += '#define NB_DEVICES_MAX         %d\n'    % self.devices_max
        s += '#define IRQ_PER_PROCESSOR      %d\n'    % self.irqs_per_core
        s += '#define RESET_ADDRESS          0x%x\n'  % self.reset_address
        s += '#define NB_TOTAL_PROCS         %d\n'    % nb_total_cores
        s += '#define BOOT_CORE_GID          %d\n'    % boot_core_gid
        s += '#define BOOT_CORE_CXY          %d\n'    % self.boot_cxy
        s += '#define CACHE_LINE_SIZE        %d\n'    % self.cache_line
        s += '\n'

        s += '/* Peripherals */\n'
        s += '\n'
        s += '#define NB_TXT_CHANNELS        %d\n'    % txt_channels
        s += '#define NB_IOC_CHANNELS        %d\n'    % ioc_channels
        s += '#define NB_NIC_CHANNELS        %d\n'    % nic_channels
        s += '#define NB_TIM_CHANNELS        %d\n'    % tim_channels
        s += '\n'
        s += '#define USE_ICU                %d\n'    % ( nb_icu != 0 )
        s += '#define USE_IOB                %d\n'    % ( nb_iob != 0 )
        s += '#define USE_PIC                %d\n'    % ( nb_pic != 0 )
        s += '#define USE_FBF                %d\n'    % ( nb_fbf != 0 )
        s += '#define USE_NIC                %d\n'    % ( nb_nic != 0 )
        s += '#define USE_DMA                %d\n'    % ( nb_dma != 0 )
        s += '\n'
        s += '#define USE_IOC_BDV            %d\n'    % use_ioc_bdv
        s += '#define USE_IOC_SDC            %d\n'    % use_ioc_sdc
        s += '#define USE_IOC_HBA            %d\n'    % use_ioc_hba
        s += '#define USE_IOC_SPI            %d\n'    % use_ioc_spi
        s += '#define USE_IOC_RDK            %d\n'    % use_ioc_rdk
        s += '\n'
        s += '#define FBUF_X_SIZE            %d\n'    % fbf_arg0
        s += '#define FBUF_Y_SIZE            %d\n'    % fbf_arg1
        s += '\n'
        s += '#define ICU_NB_HWI             %d\n'    % icu_arg0
        s += '#define ICU_NB_PTI             %d\n'    % icu_arg1
        s += '#define ICU_NB_WTI             %d\n'    % icu_arg2
        s += '#define ICU_NB_OUT             %d\n'    % icu_arg3
        s += '\n'

        s += '/* local physical base address and size for devices */\n'
        s += '\n'
        s += '#define SEG_RAM_BASE           0x%x\n'  % (ram_base & local_physical_mask)
        s += '#define SEG_RAM_SIZE           0x%x\n'  % ram_size
        s += '\n'
        s += '#define SEG_FBF_BASE           0x%x\n'  % (fbf_base & local_physical_mask)
        s += '#define SEG_FBF_SIZE           0x%x\n'  % fbf_size
        s += '\n'
        s += '#define SEG_IOB_BASE           0x%x\n'  % (iob_base & local_physical_mask)
        s += '#define SEG_IOB_SIZE           0x%x\n'  % iob_size
        s += '\n'
        s += '#define SEG_IOC_BASE           0x%x\n'  % (ioc_base & local_physical_mask)
        s += '#define SEG_IOC_SIZE           0x%x\n'  % ioc_size
        s += '\n'
        s += '#define SEG_MMC_BASE           0x%x\n'  % (mmc_base & local_physical_mask)
        s += '#define SEG_MMC_SIZE           0x%x\n'  % mmc_size
        s += '\n'
        s += '#define SEG_DMA_BASE           0x%x\n'  % (dma_base & local_physical_mask)
        s += '#define SEG_DMA_SIZE           0x%x\n'  % dma_size
        s += '\n'
        s += '#define SEG_ROM_BASE           0x%x\n'  % (rom_base & local_physical_mask)
        s += '#define SEG_ROM_SIZE           0x%x\n'  % rom_size
        s += '\n'
        s += '#define SEG_SIM_BASE           0x%x\n'  % (sim_base & local_physical_mask)
        s += '#define SEG_SIM_SIZE           0x%x\n'  % sim_size
        s += '\n'
        s += '#define SEG_NIC_BASE           0x%x\n'  % (nic_base & local_physical_mask)
        s += '#define SEG_NIC_SIZE           0x%x\n'  % nic_size
        s += '\n'
        s += '#define SEG_PIC_BASE           0x%x\n'  % (pic_base & local_physical_mask)
        s += '#define SEG_PIC_SIZE           0x%x\n'  % pic_size
        s += '\n'
        s += '#define SEG_TIM_BASE           0x%x\n'  % (tim_base & local_physical_mask)
        s += '#define SEG_TIM_SIZE           0x%x\n'  % tim_size
        s += '\n'
        s += '#define SEG_TXT_BASE           0x%x\n'  % (txt_base & local_physical_mask)
        s += '#define SEG_TXT_SIZE           0x%x\n'  % txt_size
        s += '\n'
        s += '#define SEG_ICU_BASE           0x%x\n'  % (icu_base & local_physical_mask)
        s += '#define SEG_ICU_SIZE           0x%x\n'  % icu_size
        s += '\n'
        s += '#define SEG_RDK_BASE           0x%x\n'  % (rdk_base & local_physical_mask)
        s += '#define SEG_RDK_SIZE           0x%x\n'  % rdk_size
        s += '\n'
        s += '#endif\n'

        return s

    # end of hard_config()





###################################################################################
class Cluster ( object ):
###################################################################################
    def __init__( self,
                  cxy ):

        self.index       = 0           # global index (set by Archinfo constructor)
        self.cxy         = cxy         # cluster identifier
        self.cores       = []          # local cores (filled by addCore)
        self.devices     = []          # local devices(filled by addDevice)

        return

    ################
    def xml( self ):  # xml for a cluster

        s = '        <cluster cxy = "%x" >\n' % (self.cxy)
        for core   in self.cores:   s += core.xml()
        for device in self.devices: s += device.xml()
        s += '        </cluster>\n'

        return s

    #############################################
    def cbin( self, mapping, verbose, expected ):  # C binary structure for Cluster

        if ( verbose ):
            print '*** cbin for cluster[%d] / identifier = %x' \
                   % (self.index , self.cxy)

        # check index
        if (self.index != expected):
            print '[genarch error] in Cluster.cbin()'
            print '    cluster global index = %d / expected = %d' \
                       % (self.index,expected)
            sys.exit(1)

        # compute global index for first core in cluster
        if ( len(self.cores) > 0 ):
            core_id = self.cores[0].index
        else:
            core_id = 0

        # compute global index for first device in cluster
        if ( len(self.devices) > 0 ):
            device_id = self.devices[0].index
        else:
            device_id = 0

        byte_stream = bytearray()
        byte_stream += mapping.int2bytes(4,self.cxy)          # cxy 
        byte_stream += mapping.int2bytes(4,len(self.cores))   # cores in cluster
        byte_stream += mapping.int2bytes(4,core_id )          # first core global index
        byte_stream += mapping.int2bytes(4,len(self.devices)) # devices in cluster
        byte_stream += mapping.int2bytes(4, device_id )       # first device global index

        if ( verbose ):
            print 'nb_cores   = %d' %  len( self.cores )
            print 'core_id    = %d' %  core_id
            print 'nb_devices = %d' %  len( self.devices )
            print 'device_id  = %d' %  device_id

        return byte_stream




##################################################################################
class Core ( object ):          
##################################################################################
    def __init__( self,
                  gid,
                  cxy,
                  lid ):

        self.index    = 0          # global index / set by addProc()
        self.gid      = gid        # hardware identifier
        self.cxy      = cxy        # cluster identifier
        self.lid      = lid        # local index in cluster

        return

    ###################################
    def xml( self ):   # xml for a core
        return '            <core gid="%x" lid="%d" />\n' % (self.gid, self.lid)

    ####################################################################
    def cbin( self, mapping, verbose, expected ):    # C binary for Proc

        if ( verbose ):
            print '*** cbin for core [%d] in cluster %x' \
                  % (self.lid, self.cxy)

        # check index
        if (self.index != expected):
            print '[genarch error] in Core.cbin()'
            print '    core global index = %d / expected = %d' \
                       % (self.index,expected)
            sys.exit(1)

        byte_stream = bytearray()
        byte_stream += mapping.int2bytes( 4 , self.gid )      # hardware identifier
        byte_stream += mapping.int2bytes( 2 , self.cxy )      # cluster identifier
        byte_stream += mapping.int2bytes( 2 , self.lid )      # local index

        return byte_stream




##################################################################################
class Device ( object ):
##################################################################################
    def __init__( self,
                  base,
                  size,
                  ptype,
                  channels = 1,
                  arg0     = 0,
                  arg1     = 0,
                  arg2     = 0,
                  arg3     = 0 ):

        self.index    = 0             # global device index ( set by addDevice() )
        self.base     = base          # associated segment base
        self.size     = size          # associated segment size (bytes)
        self.ptype    = ptype         # device type
        self.channels = channels      # number of channels
        self.arg0     = arg0          # optional (semantic depends on ptype)
        self.arg1     = arg1          # optional (semantic depends on ptype)
        self.arg2     = arg2          # optional (semantic depends on ptype)
        self.arg3     = arg3          # optional (semantic depends on ptype)
        self.irqs     = []            # set of input IRQs (for PIC and ICU only)
        self.irq_ctrl = None          # interrupt controller for this device
        return

    ######################################
    def xml( self ):    # xml for a device

        s =  '            <device type="%s"' % self.ptype
        s += ' base="%x"'                    % self.base
        s += ' size="%x"'                    % self.size
        s += ' channels="%d"'                % self.channels
        s += ' arg0="%d"'                    % self.arg0
        s += ' arg1="%d"'                    % self.arg1
        s += ' arg2="%d"'                    % self.arg2
        s += ' arg3="%d"'                    % self.arg3
        if ( (self.ptype == 'PIC_TSR') or (self.ptype == 'ICU_XCU') ):
            s += ' >\n'
            for irq in self.irqs: s += irq.xml()
            s += '            </device>\n'
        else:
            s += ' />\n'
        return s

    ######################################################################
    def cbin( self, mapping, verbose, expected ):    # C binary for Periph

        if ( verbose ):
            print '*** cbin for device[%d] / type = %s / base = %x' \
                  % (self.index , self.ptype , self.base)

        # check index
        if (self.index != expected):
            print '[genarch error] in Periph.cbin()'
            print '    device global index = %d / expected = %d' \
                       % (self.index,expected)
            sys.exit(1)

        # compute first irq global index
        if ( len(self.irqs) > 0 ):
            irq_id = self.irqs[0].index
        else:
            irq_id = 0

        # compute device type numerical value
        ptype_id = 0xFFFFFFFF
        for x in xrange( len(DEVICE_TYPES_STR) ):
            if ( self.ptype == DEVICE_TYPES_STR[x] ):  ptype_id = DEVICE_TYPES_INT[x]

        if ( ptype_id == 0xFFFFFFFF ):
            print '[genarch error] in Device.cbin()'
            print '    undefined device type %s' % self.ptype
            sys.exit(1)

        byte_stream = bytearray()
        byte_stream += mapping.int2bytes(8,self.base)      # segment base address
        byte_stream += mapping.int2bytes(8,self.size)      # segment size
        byte_stream += mapping.int2bytes(4,ptype_id)       # device type
        byte_stream += mapping.int2bytes(4,self.channels)  # number of channels
        byte_stream += mapping.int2bytes(4,self.arg0)      # optionnal arg0
        byte_stream += mapping.int2bytes(4,self.arg1)      # optionnal arg1
        byte_stream += mapping.int2bytes(4,self.arg2)      # optionnal arg2
        byte_stream += mapping.int2bytes(4,self.arg3)      # optionnal arg3
        byte_stream += mapping.int2bytes(4,len(self.irqs)) # number of input irqs
        byte_stream += mapping.int2bytes(4 ,irq_id)        # first irq global index

        if ( verbose ):
            print 'base       = %x' %  self.base
            print 'size       = %x' %  self.size
            print 'nb_irqs    = %d' %  len( self.irqs )
            print 'irq_id     = %d' %  irq_id

        return byte_stream

##################################################################################
class Irq ( object ): 
##################################################################################
    def __init__( self,
                  port,
                  dev,
                  channel,
                  is_rx ): 

        assert port < 32

        self.index   = 0              # global index ( set by addIrq() )
        self.port    = port           # input IRQ port index
        self.dev     = dev            # source device
        self.channel = channel        # source device channel
        self.is_rx   = is_rx          # source device direction

        return

    ################################
    def xml( self ):   # xml for Irq 
        s = '                <irq port="%d" devtype="%s" channel="%d" is_rx="%d" />\n' \
                             % ( self.port, self.dev.ptype, self.channel, self.is_rx )
        return s

    ####################################################################
    def cbin( self, mapping, verbose, expected ):     # C binary for Irq

        if ( verbose ):
            print '*** cbin for irq[%d] / src_dev = %s' \
                   % (self.port , self.dev.ptype)

        # check index
        if (self.index != expected):
            print '[genarch error] in Irq.cbin()'
            print '    irq global index = %d / expected = %d' \
                       % (self.index , expected)
            sys.exit(1)

        # compute source device type numerical value
        dev_id = 0xFFFFFFFF
        for x in xrange( len(DEVICE_TYPES_STR) ):
            if ( self.dev.ptype == DEVICE_TYPES_STR[x] ): dev_id = DEVICE_TYPES_INT[x]

        if ( dev_id == 0xFFFFFFFF ):
            print '[genarch error] in Irq.cbin()'
            print '    undefined device type %s' % self.dev.ptype
            sys.exit(1)

        byte_stream = bytearray()
        byte_stream += mapping.int2bytes( 4,  dev_id )
        byte_stream += mapping.int2bytes( 1,  self.channel )
        byte_stream += mapping.int2bytes( 1,  self.is_rx )
        byte_stream += mapping.int2bytes( 1,  self.port )
        byte_stream += mapping.int2bytes( 1,  0 )

        if ( verbose ):
            print 'dev_id     = %d' %  dev_id
            print 'channel    = %d' %  self.channel
            print 'is_rx      = %d' %  self.is_rx   
            print 'port       = %s' %  self.port

        return byte_stream

# Local Variables:
# tab-width: 4;
# c-basic-offset: 4;
# c-file-offsets:((innamespace . 0)(inline-open . 0));
# indent-tabs-mode: nil;
# End:
#
# vim: filetype=python:expandtab:shiftwidth=4:tabstop=4:softtabstop=4

