#include <systemc>
#include <sys/time.h>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cstdarg>
#include <stdint.h>
#include <fstream>

#include "mapping_table.h"
#include "mips32.h"
#include "vci_simhelper.h"
#include "vci_simple_ram.h"
#include "vci_multi_tty.h"
#include "vci_xicu.h"
#include "vci_simple_ring_fast.h"
#include "vci_mem_cache_v4.h"
#include "vci_cc_xcache_wrapper_v4.h"
#include "alloc_elems.h"

#include "iss/gdbserver.h"

#include "segmentation.h"

//===========================================
// Define before include
//===========================================

// Parameters
// * Platforms
#  define PARAM_VCI                         4,8,32,1,1,1,8,4,4,1

#  define USE_OLD_XCACHE                    0
#  define USE_VGMN                          1
#  define NB_PROC_MIN                       1
#  define NB_PROC_MAX                       15
//                                          fifo_depth
#  define PARAM_RING_P                      2
#  define PARAM_RING_C                      2
#  define PARAM_RING_X                      2
//                                          pti    , hwi    , wti, irq
#  define PARAM_XICU                        nb_proc*nb_cpu_by_cache, nb_proc*nb_cpu_by_cache, 0  , nb_proc*nb_cpu_by_cache
//#define PARAM_XICU                        nb_proc, nb_proc, 0  , nb_proc

// * Debug
#  define DEBUG_TOP                         0
#  define SOCVIEW                           0
#  define STOP_SIMULATION_NB_FRZ_CYCLES     100000
                                            
// * Simulation                             
#  define CONFIG_DEFAULT                    "configuration/default.cfg"
#  define NCYCLES_DEFAULT                   0
#  define SOFT_DEFAULT                      "soft/bin.soft"
//===========================================

void usage (char * funcname)
{
  std::cout << funcname << " [option] " << std::endl;
  std::cout << " * -NCYCLES int : number of simulated cycle, if 0 then no stop condition." << std::endl;
  std::cout << "                  default : " << NCYCLES_DEFAULT << " cycle(s)" << std::endl;
  std::cout << " * -CFG string  : configuration file" << std::endl;
  std::cout << "                    - nb_proc," << std::endl;
  std::cout << "                    - nb_cpu_by_cache, nb_dcache," << std::endl;
  std::cout << "                    - iways, isets, iwords," << std::endl;
  std::cout << "                    - dways, dsets, dwords," << std::endl;
  std::cout << "                    - wnwords, wnlines, " << std::endl;
  std::cout << "                    - memc_nways, memc_nsets, memc_words, memc_heap_size." << std::endl;
  std::cout << "                  default : \"" << CONFIG_DEFAULT << "\"" << std::endl;
  std::cout << " * -SOFT string : software executed by this platform." << std::endl;
  std::cout << "                  default : \"" << SOFT_DEFAULT << "\"" << std::endl;

  exit(1);
}

int _main(int argc, char *argv[])
{
	int    ncycles = NCYCLES_DEFAULT;
	char * config  = CONFIG_DEFAULT;
        char * soft    = SOFT_DEFAULT;

        if (argc > 1)
          {
            for( int n=1 ; n<argc ; n=n+2 )
              {
                if( (strcmp(argv[n],"-NCYCLES") == 0) && (n+1<argc) )
                  {
                    ncycles = atoi(argv[n+1]);
                  }
                else if( (strcmp(argv[n],"-CFG") == 0) && (n+1<argc) )
                  {
                    // strcpy(config, argv[n+1]);
                    config = argv[n+1];
                  }
                else if( (strcmp(argv[n],"-SOFT") == 0) && (n+1<argc) )
                  {
                    // strcpy(soft, argv[n+1]);
                    soft = argv[n+1];
                  }
                else
                  {
                    usage(argv[0]);
                  }
              }
          }

        if (ncycles == 0)
          ncycles = -1;

        uint32_t nb_proc;
        uint32_t nb_cpu_by_cache;
        uint32_t nb_dcache;
        uint32_t iways, isets, iwords;
        uint32_t dways, dsets, dwords;
        uint32_t wnwords, wnlines;
        uint32_t memc_nways, memc_nsets, memc_words, memc_heap_size;

        std::ifstream inFile;
        const char * filename = config;

        inFile.open(filename);
        
        if (!inFile) 
          {
            std::cout << "Can't open file : \"" << filename << "\"." << std::endl;
            usage(argv[0]);
          }

        std::string str;
        if (not (inFile >> str)){std::cout << "Invalid parameters number in configuration file." << std::endl; usage(argv[0]);}
        nb_proc         =std::atoi(str.c_str());
        if (not (inFile >> str)){std::cout << "Invalid parameters number in configuration file." << std::endl; usage(argv[0]);}
        nb_cpu_by_cache =std::atoi(str.c_str());
        if (not (inFile >> str)){std::cout << "Invalid parameters number in configuration file." << std::endl; usage(argv[0]);}
        nb_dcache       =std::atoi(str.c_str());
        if (not (inFile >> str)){std::cout << "Invalid parameters number in configuration file." << std::endl; usage(argv[0]);}
        iways           =std::atoi(str.c_str());
        if (not (inFile >> str)){std::cout << "Invalid parameters number in configuration file." << std::endl; usage(argv[0]);}
        isets           =std::atoi(str.c_str());
        if (not (inFile >> str)){std::cout << "Invalid parameters number in configuration file." << std::endl; usage(argv[0]);}
        iwords          =std::atoi(str.c_str());
        if (not (inFile >> str)){std::cout << "Invalid parameters number in configuration file." << std::endl; usage(argv[0]);}
        dways           =std::atoi(str.c_str());
        if (not (inFile >> str)){std::cout << "Invalid parameters number in configuration file." << std::endl; usage(argv[0]);}
        dsets           =std::atoi(str.c_str());
        if (not (inFile >> str)){std::cout << "Invalid parameters number in configuration file." << std::endl; usage(argv[0]);}
        dwords          =std::atoi(str.c_str());
        if (not (inFile >> str)){std::cout << "Invalid parameters number in configuration file." << std::endl; usage(argv[0]);}
        wnwords         =std::atoi(str.c_str());
        if (not (inFile >> str)){std::cout << "Invalid parameters number in configuration file." << std::endl; usage(argv[0]);}
        wnlines         =std::atoi(str.c_str());
        if (not (inFile >> str)){std::cout << "Invalid parameters number in configuration file." << std::endl; usage(argv[0]);}
        memc_nways      =std::atoi(str.c_str());
        if (not (inFile >> str)){std::cout << "Invalid parameters number in configuration file." << std::endl; usage(argv[0]);}
        memc_nsets      =std::atoi(str.c_str());
        if (not (inFile >> str)){std::cout << "Invalid parameters number in configuration file." << std::endl; usage(argv[0]);}
        memc_words      =std::atoi(str.c_str());
        if (not (inFile >> str)){std::cout << "Invalid parameters number in configuration file." << std::endl; usage(argv[0]);}
        memc_heap_size  =std::atoi(str.c_str());

        if (((nb_proc*nb_cpu_by_cache)<NB_PROC_MIN) or
            ((nb_proc*nb_cpu_by_cache)>NB_PROC_MAX))
          {
            std::cout << "Parameters nb_proc is out of bound." << std::endl;
            usage(argv[0]);
          }

        std::cout << "  * Parameters : " << std::endl;
        std::cout << "    * nb_proc          : " << nb_proc          << std::endl;
        std::cout << "    * nb_cpu_by_cache  : " << nb_cpu_by_cache  << std::endl;
        std::cout << "    * nb_dcache        : " << nb_dcache        << std::endl;
        std::cout << "    * iways            : " << iways            << std::endl;
        std::cout << "    * isets            : " << isets            << std::endl;
        std::cout << "    * iwords           : " << iwords           << std::endl;
        std::cout << "    * dways            : " << dways            << std::endl;
        std::cout << "    * dsets            : " << dsets            << std::endl;
        std::cout << "    * dwords           : " << dwords           << std::endl;
        std::cout << "    * wnwords          : " << wnwords          << std::endl;
        std::cout << "    * wnlines          : " << wnlines          << std::endl;
        std::cout << "    * memc_nways       : " << memc_nways       << std::endl;
        std::cout << "    * memc_nsets       : " << memc_nsets       << std::endl;
        std::cout << "    * memc_words       : " << memc_words       << std::endl;
        std::cout << "    * memc_heap_size   : " << memc_heap_size   << std::endl;
        std::cout << "  * Simulation : " << std::endl;
        std::cout << "    * ncycles          : " << ncycles          << std::endl;
        std::cout << "    * soft             : " << soft             << std::endl;

	using namespace sc_core;
	// Avoid repeating these everywhere
	using soclib::common::IntTab;
	using soclib::common::Segment;

	// Define VCI parameters
	typedef soclib::caba::VciParams<PARAM_VCI> vci_param;
	typedef soclib::common::GdbServer<soclib::common::Mips32ElIss> proc_iss;
	// Mapping table

	soclib::common::MappingTable maptabp(32, IntTab(8), IntTab(8), 0x00300000); // size, level_addr_bits, level_id_bits, cacheability_mask

	maptabp.add(Segment("reset"    , RESET_BASE    , RESET_SIZE    , IntTab(2), true));
	maptabp.add(Segment("excep"    , EXCEP_BASE    , EXCEP_SIZE    , IntTab(2), true));

	maptabp.add(Segment("tty"      , TTY_BASE      , TTY_SIZE      , IntTab(1), false));
	maptabp.add(Segment("text"     , TEXT_BASE     , TEXT_SIZE     , IntTab(2), true));
	maptabp.add(Segment("mc_r"     , MC_R_BASE     , MC_R_SIZE     , IntTab(2), false, true, IntTab(0)));
	maptabp.add(Segment("mc_m"     , MC_M_BASE     , MC_M_SIZE     , IntTab(2), true));
      //maptabp.add(Segment("mc_u"     , MC_U_BASE     , MC_U_SIZE     , IntTab(2), false));
      //maptabp.add(Segment("ptba"     , PTD_ADDR      , TAB_SIZE      , IntTab(2), true));
	maptabp.add(Segment("xicu"     , XICU_BASE     , XICU_SIZE     , IntTab(3), false));
	maptabp.add(Segment("simhelper", SIMHELPER_BASE, SIMHELPER_SIZE, IntTab(4), false));
 
	std::cout << maptabp << std::endl;

        soclib::common::MappingTable maptabc(32, IntTab(8), IntTab(8), 0x00300000);
        // for (uint32_t i=0; i<nb_proc; ++i)
        //   for (uint32_t j=0; j<nb_cpu_by_cache; ++j)
        //   {
        //     std::ostringstream str;
        //     str << "c_proc_" << i << "_" << j;
        //     maptabc.add(Segment(str.str().c_str(), C_PROC_BASE+(i*nb_cpu_by_cache+j)*C_PROC_SPAN, C_PROC_SIZE , IntTab(i), false, true, IntTab(i)));
        //   }
        for (uint32_t i=0; i<nb_proc; ++i)
        {
          std::ostringstream str;
          str << "c_proc_" << i;
          maptabc.add(Segment(str.str().c_str(), C_PROC_BASE+i*C_PROC_SPAN, C_PROC_SIZE , IntTab(i), false, true, IntTab(i)));
        }
	maptabc.add(Segment("mc_r"    , MC_R_BASE  , MC_R_SIZE   , IntTab(nb_proc), false, false));
	maptabc.add(Segment("mc_m"    , MC_M_BASE  , MC_M_SIZE   , IntTab(nb_proc), false, false));
	// maptabc.add(Segment("mc_u"    , MC_U_BASE  , MC_U_SIZE   , IntTab(nb_proc), false, false));
	maptabc.add(Segment("reset"   , RESET_BASE , RESET_SIZE  , IntTab(nb_proc), false, false));
	maptabc.add(Segment("excep"   , EXCEP_BASE , EXCEP_SIZE  , IntTab(nb_proc), false, false));
	maptabc.add(Segment("text"    , TEXT_BASE  , TEXT_SIZE   , IntTab(nb_proc), false, false));
      //maptabc.add(Segment("ptba"    , PTD_ADDR   , TAB_SIZE    , IntTab(nb_proc), false, false));

	std::cout << maptabc << std::endl;
	
	soclib::common::MappingTable maptabx(32, IntTab(8), IntTab(8), 0x00300000);
	maptabx.add(Segment("xram" , MC_M_BASE , MC_M_SIZE , IntTab(0), false));
	// maptabx.add(Segment("uram" , MC_U_BASE , MC_U_SIZE , IntTab(0), false));
	maptabx.add(Segment("reset", RESET_BASE, RESET_SIZE, IntTab(0), false));
	maptabx.add(Segment("excep", EXCEP_BASE, EXCEP_SIZE, IntTab(0), false));
	maptabx.add(Segment("text" , TEXT_BASE , TEXT_SIZE , IntTab(0), false));
	// maptabx.add(Segment("ptba" , PTD_ADDR  , TAB_SIZE  , IntTab(0), false));
	
	std::cout << maptabx << std::endl;

	// Signals
	sc_clock	signal_clk("clk");
	sc_signal<bool> signal_resetn("resetn");
   
	sc_signal<bool> *** signal_proc_it = soclib::common::alloc_elems<sc_signal<bool> >("proc_it", nb_proc, nb_cpu_by_cache, 6);

	soclib::caba::VciSignals<vci_param> * signal_vci_ini_rw_proc = soclib::common::alloc_elems<soclib::caba::VciSignals<vci_param> >("vci_ini_rw_proc", nb_proc);
	soclib::caba::VciSignals<vci_param> * signal_vci_ini_c_proc  = soclib::common::alloc_elems<soclib::caba::VciSignals<vci_param> >("vci_ini_c_proc" , nb_proc);
	soclib::caba::VciSignals<vci_param> * signal_vci_tgt_proc    = soclib::common::alloc_elems<soclib::caba::VciSignals<vci_param> >("vci_tgt_proc"   , nb_proc);

	soclib::caba::VciSignals<vci_param> signal_vci_tgt_tty("vci_tgt_tty");

	soclib::caba::VciSignals<vci_param> signal_vci_tgt_simhelper("signal_vci_tgt_simhelper");

	soclib::caba::VciSignals<vci_param> signal_vci_tgt_rom("vci_tgt_rom");

	soclib::caba::VciSignals<vci_param> signal_vci_tgt_xram("vci_tgt_xram");

	soclib::caba::VciSignals<vci_param> signal_vci_tgt_xicu("vci_tgt_xicu");

	soclib::caba::VciSignals<vci_param> signal_vci_ixr_memc("vci_ixr_memc");
	soclib::caba::VciSignals<vci_param> signal_vci_ini_memc("vci_ini_memc");
	soclib::caba::VciSignals<vci_param> signal_vci_tgt_memc("vci_tgt_memc");
	soclib::caba::VciSignals<vci_param> signal_vci_tgt_cleanup_memc("vci_tgt_cleanup_memc");

	sc_signal<bool> ** signal_tty_irq = soclib::common::alloc_elems<sc_signal<bool> >("signal_tty_irq", nb_proc, nb_cpu_by_cache);

	soclib::common::Loader loader(soft);

        soclib::common::GdbServer<soclib::common::Mips32ElIss>::set_loader(loader);

	soclib::caba::VciCcXCacheWrapperV4<vci_param, proc_iss > * proc [nb_proc];
        for (uint32_t i=0; i<nb_proc; ++i)
          {
            uint32_t num_cpu = i*nb_cpu_by_cache;

            std::ostringstream str;
            str << "proc_" << num_cpu;

            proc[i] = new soclib::caba::VciCcXCacheWrapperV4<vci_param, proc_iss > (str.str().c_str(), num_cpu, maptabp, maptabc, IntTab(i),IntTab(i),IntTab(i)
#if USE_OLD_XCACHE
                                                                                    ,iways, isets, iwords
                                                                                    ,dways, dsets, dwords
#else
                                                                                    ,nb_cpu_by_cache   
                                                                                    ,nb_dcache
                                                                                    ,iways*nb_cpu_by_cache, isets, iwords
                                                                                    ,dways*nb_cpu_by_cache, dsets, dwords
                                                                                    ,wnwords, wnlines*nb_cpu_by_cache
#endif
                                                                                    );

#if not USE_OLD_XCACHE
            proc[i]->stop_simulation(STOP_SIMULATION_NB_FRZ_CYCLES);
#endif
          }

	soclib::caba::VciSimpleRam<vci_param> 
	rom ("rom", IntTab(0), maptabp, loader);

	soclib::caba::VciSimpleRam<vci_param> 
	xram("xram", IntTab(0), maptabx, loader);

        //                                  x_init    c_init          p_tgt     c_tgt
	soclib::caba::VciMemCacheV4<vci_param> 
        memc("memc",maptabp,maptabc,maptabx,IntTab(0),IntTab(nb_proc),IntTab(2),IntTab(nb_proc), memc_nways, memc_nsets, memc_words, memc_heap_size);

        std::vector<std::string> tty_name;
        for (uint32_t i=0; i<nb_proc*nb_cpu_by_cache; ++i)
          {
            std::ostringstream str;
            str << "tty_" << i;

            tty_name.push_back(str.str());
          }
	
	soclib::caba::VciMultiTty<vci_param> 
	tty("tty",IntTab(1),maptabp,tty_name);

        soclib::caba::VciXicu<vci_param> 
        xicu("xicu", maptabp, IntTab(3), PARAM_XICU);

	// soclib::caba::VciTimer<vci_param> 
        // timer("timer", IntTab(3), maptabp, nb_proc);

	soclib::caba::VciSimhelper<vci_param> 
        simhelper("simhelper", IntTab(4), maptabp);

        //                  initiatior | target 
        // interconnect_p : proc       | rom, tty, memc, xicu, simhelper
        // interconnect_c : proc, memc | proc, memc
        // interconnect_x : memc       | xram

	soclib::caba::VciSimpleRingFast<vci_param,40,33> 
	interconnect_p("interconnect_p",maptabp, IntTab(), PARAM_RING_P,nb_proc  , 5        );

	soclib::caba::VciSimpleRingFast<vci_param,40,33>
	interconnect_c("interconnect_c",maptabc, IntTab(), PARAM_RING_C,nb_proc+1, nb_proc+1);

	soclib::caba::VciSimpleRingFast<vci_param,40,33>
	interconnect_x("interconnect_x",maptabx, IntTab(), PARAM_RING_X,1        , 1        );

	// Net-List
        for (uint32_t i=0; i<nb_proc; ++i)
          {
            proc[i]->p_clk(signal_clk);  
            proc[i]->p_resetn(signal_resetn);
            for (uint32_t j=0; j<nb_cpu_by_cache; ++j)
              {
                proc[i]->p_irq[j][0](signal_proc_it[i][j][0]);
                proc[i]->p_irq[j][1](signal_proc_it[i][j][1]);
                proc[i]->p_irq[j][2](signal_proc_it[i][j][2]);
                proc[i]->p_irq[j][3](signal_proc_it[i][j][3]);
                proc[i]->p_irq[j][4](signal_proc_it[i][j][4]);
                proc[i]->p_irq[j][5](signal_proc_it[i][j][5]);
              }
            proc[i]->p_vci_ini_rw(signal_vci_ini_rw_proc[i]);
            proc[i]->p_vci_ini_c(signal_vci_ini_c_proc[i]);
            proc[i]->p_vci_tgt(signal_vci_tgt_proc[i]);
          }

	rom.p_clk(signal_clk);
	rom.p_resetn(signal_resetn);
	rom.p_vci(signal_vci_tgt_rom);

	tty.p_clk(signal_clk);
	tty.p_resetn(signal_resetn);
	tty.p_vci(signal_vci_tgt_tty);
        for (uint32_t i=0; i<nb_proc; ++i)
          for (uint32_t j=0; j<nb_cpu_by_cache; ++j)
            tty.p_irq[i*nb_cpu_by_cache+j](signal_tty_irq[i][j]); 

        xicu.p_clk(signal_clk);
        xicu.p_resetn(signal_resetn);
        xicu.p_vci(signal_vci_tgt_xicu);
        for (uint32_t i=0; i<nb_proc; ++i)
          for (uint32_t j=0; j<nb_cpu_by_cache; ++j)
          {
            xicu.p_hwi[i*nb_cpu_by_cache+j](signal_tty_irq[i][j]);
            xicu.p_irq[i*nb_cpu_by_cache+j](signal_proc_it[i][j][0]);
          }

        simhelper.p_clk(signal_clk);
        simhelper.p_resetn(signal_resetn);
        simhelper.p_vci(signal_vci_tgt_simhelper);

	memc.p_clk(signal_clk);
	memc.p_resetn(signal_resetn);
	memc.p_vci_tgt(signal_vci_tgt_memc);
	memc.p_vci_tgt_cleanup(signal_vci_tgt_cleanup_memc);
	memc.p_vci_ini(signal_vci_ini_memc);
	memc.p_vci_ixr(signal_vci_ixr_memc);

	xram.p_clk(signal_clk);
	xram.p_resetn(signal_resetn);
	xram.p_vci(signal_vci_tgt_xram);
        
	interconnect_p.p_clk(signal_clk);
	interconnect_p.p_resetn(signal_resetn);

        for (uint32_t i=0; i<nb_proc; ++i)
        interconnect_p.p_to_initiator[i](signal_vci_ini_rw_proc[i]);

	interconnect_p.p_to_target[0](signal_vci_tgt_rom);
	interconnect_p.p_to_target[1](signal_vci_tgt_tty);
	interconnect_p.p_to_target[2](signal_vci_tgt_memc);
	interconnect_p.p_to_target[3](signal_vci_tgt_xicu);
	interconnect_p.p_to_target[4](signal_vci_tgt_simhelper);

	interconnect_c.p_clk(signal_clk);
	interconnect_c.p_resetn(signal_resetn);

        for (uint32_t i=0; i<nb_proc; ++i)
	interconnect_c.p_to_initiator[i](signal_vci_ini_c_proc[i]);
	interconnect_c.p_to_initiator[nb_proc](signal_vci_ini_memc);

        for (uint32_t i=0; i<nb_proc; ++i)
	interconnect_c.p_to_target[i](signal_vci_tgt_proc[i]);
	interconnect_c.p_to_target[nb_proc](signal_vci_tgt_cleanup_memc);

	interconnect_x.p_clk(signal_clk);
	interconnect_x.p_resetn(signal_resetn);

	interconnect_x.p_to_initiator[0](signal_vci_ixr_memc);

	interconnect_x.p_to_target[0](signal_vci_tgt_xram);

	sc_start(sc_core::sc_time(0, SC_NS));
	signal_resetn = false;
	sc_start(sc_core::sc_time(1, SC_NS));
	signal_resetn = true;

#if SOCVIEW
	debug();
#elif DEBUG_TOP

        uint32_t num_cycle=0;
        while(1)
          {
            std::cout << std::endl
                      << std::dec << "===== [ cycle " << num_cycle << " ]======" << std::endl
                      << std::endl;
            
            sc_start(sc_core::sc_time(1, SC_NS));
            
            // for (uint32_t i=0; i<nb_proc; ++i)
            //   proc[i]->print_trace(1);
            num_cycle ++;
          }
#else
        if (ncycles==-1)
          sc_start();
        else
          sc_start(sc_core::sc_time(ncycles, SC_NS));

        // std::cout << "Hit ENTER to end simulation" << std::endl;
        // char buf[1];
	// std::cin.getline(buf,1);
#endif
        for (uint32_t i=0; i<nb_proc; ++i)
          proc[i]->print_cpi();
        for (uint32_t i=0; i<nb_proc; ++i)
          proc[i]->print_stats();

        soclib::common::dealloc_elems<sc_signal<bool>                     >(signal_tty_irq         , nb_proc, nb_cpu_by_cache);
	soclib::common::dealloc_elems<soclib::caba::VciSignals<vci_param> >(signal_vci_tgt_proc    , nb_proc);
	soclib::common::dealloc_elems<soclib::caba::VciSignals<vci_param> >(signal_vci_ini_c_proc  , nb_proc);
	soclib::common::dealloc_elems<soclib::caba::VciSignals<vci_param> >(signal_vci_ini_rw_proc , nb_proc);
	soclib::common::dealloc_elems<sc_signal<bool>                     >(signal_proc_it         , nb_proc, nb_cpu_by_cache, 6);

        for (uint32_t i=0; i<nb_proc; ++i)
          delete proc[i];

	return EXIT_SUCCESS;
}

int sc_main (int argc, char *argv[])
{
  try {
    return _main(argc, argv);
  } catch (std::exception &e) {
    std::cout << e.what() << std::endl;
  } catch (...) {
    std::cout << "Unknown exception occured" << std::endl;
    throw;
  }
  return 1;
}
