xref: /XiangShan/src/main/scala/top/Top.scala (revision e0d20e1b5f74a18febc6cf9ea4235f8ae9aa3223)
1c6d43980SLemover/***************************************************************************************
22993c5ecSHaojin Tang* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC)
32993c5ecSHaojin Tang* Copyright (c) 2020-2024 Institute of Computing Technology, Chinese Academy of Sciences
4f320e0f0SYinan Xu* Copyright (c) 2020-2021 Peng Cheng Laboratory
5c6d43980SLemover*
6c6d43980SLemover* XiangShan is licensed under Mulan PSL v2.
7c6d43980SLemover* You can use this software according to the terms and conditions of the Mulan PSL v2.
8c6d43980SLemover* You may obtain a copy of Mulan PSL v2 at:
9c6d43980SLemover*          http://license.coscl.org.cn/MulanPSL2
10c6d43980SLemover*
11c6d43980SLemover* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
12c6d43980SLemover* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
13c6d43980SLemover* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
14c6d43980SLemover*
15c6d43980SLemover* See the Mulan PSL v2 for more details.
16c6d43980SLemover***************************************************************************************/
17c6d43980SLemover
188b037849SYinan Xupackage top
198b037849SYinan Xu
208b037849SYinan Xuimport chisel3._
218b037849SYinan Xuimport chisel3.util._
222993c5ecSHaojin Tangimport chisel3.experimental.dataview._
232316cea8SJiuyue Maimport difftest.DifftestModule
248b037849SYinan Xuimport xiangshan._
2594c92d92SYinan Xuimport utils._
269672f0b7Swakafaimport huancun.{HCCacheParameters, HCCacheParamsKey, HuanCun, PrefetchRecv, TPmetaResp}
274b40434cSzhanglinjuanimport coupledL2.EnableCHI
285c060727Ssumailyycimport coupledL2.tl2chi.CHILogger
295c060727Ssumailyycimport openLLC.{OpenLLC, OpenLLCParamKey, OpenNCB}
305c060727Ssumailyycimport openLLC.TargetBinder._
315c060727Ssumailyycimport cc.xiangshan.openncb._
323c02ee8fSwakafaimport utility._
33*e0d20e1bSTang Haojinimport utility.sram.SramBroadcastBundle
348b037849SYinan Xuimport system._
35d4aca96cSlqreimport device._
368b037849SYinan Xuimport chisel3.stage.ChiselGeneratorAnnotation
378891a219SYinan Xuimport org.chipsalliance.cde.config._
388b037849SYinan Xuimport freechips.rocketchip.diplomacy._
394daa5bf3SYangyu Chenimport freechips.rocketchip.tile._
408b037849SYinan Xuimport freechips.rocketchip.tilelink._
418bc90631SZehao Liuimport freechips.rocketchip.interrupts._
424b40434cSzhanglinjuanimport freechips.rocketchip.amba.axi4._
43d4aca96cSlqreimport freechips.rocketchip.jtag.JTAGIO
44a5b77de4STang Haojinimport chisel3.experimental.{annotate, ChiselAnnotation}
45a5b77de4STang Haojinimport sifive.enterprise.firrtl.NestedPrefixModulesAnnotation
465c060727Ssumailyycimport scala.collection.mutable.{Map}
47d4aca96cSlqre
48afcc4f2aSJiawei Linabstract class BaseXSSoc()(implicit p: Parameters) extends LazyModule
49afcc4f2aSJiawei Lin  with BindingScope
50afcc4f2aSJiawei Lin{
514b40434cSzhanglinjuan  // val misc = LazyModule(new SoCMisc())
52afcc4f2aSJiawei Lin  lazy val dts = DTS(bindingTree)
534f0a2459Swakafa  lazy val json = JSON(bindingTree)
548b037849SYinan Xu}
558b037849SYinan Xu
5673be64b3SJiawei Linclass XSTop()(implicit p: Parameters) extends BaseXSSoc() with HasSoCParameter
578b037849SYinan Xu{
584b40434cSzhanglinjuan  val nocMisc = if (enableCHI) Some(LazyModule(new MemMisc())) else None
594b40434cSzhanglinjuan  val socMisc = if (!enableCHI) Some(LazyModule(new SoCMisc())) else None
604b40434cSzhanglinjuan  val misc: MemMisc = if (enableCHI) nocMisc.get else socMisc.get
614b40434cSzhanglinjuan
62afcc4f2aSJiawei Lin  ResourceBinding {
63afcc4f2aSJiawei Lin    val width = ResourceInt(2)
64ce34d21eSJiuyue Ma    val model = "xiangshan," + os.read(os.resource / "publishVersion")
65ce34d21eSJiuyue Ma    val compatible = "freechips,rocketchip-unknown"
66afcc4f2aSJiawei Lin    Resource(ResourceAnchors.root, "model").bind(ResourceString(model))
67ce34d21eSJiuyue Ma    Resource(ResourceAnchors.root, "compat").bind(ResourceString(compatible + "-dev"))
68ce34d21eSJiuyue Ma    Resource(ResourceAnchors.soc, "compat").bind(ResourceString(compatible + "-soc"))
69afcc4f2aSJiawei Lin    Resource(ResourceAnchors.root, "width").bind(width)
70afcc4f2aSJiawei Lin    Resource(ResourceAnchors.soc, "width").bind(width)
71afcc4f2aSJiawei Lin    Resource(ResourceAnchors.cpus, "width").bind(ResourceInt(1))
72afcc4f2aSJiawei Lin    def bindManagers(xbar: TLNexusNode) = {
73afcc4f2aSJiawei Lin      ManagerUnification(xbar.edges.in.head.manager.managers).foreach{ manager =>
74afcc4f2aSJiawei Lin        manager.resources.foreach(r => r.bind(manager.toResource))
75afcc4f2aSJiawei Lin      }
76afcc4f2aSJiawei Lin    }
7778a8cd25Szhanglinjuan    if (!enableCHI) {
781bf9a05aSzhanglinjuan      bindManagers(misc.l3_xbar.get.asInstanceOf[TLNexusNode])
7978a8cd25Szhanglinjuan      bindManagers(misc.peripheralXbar.get.asInstanceOf[TLNexusNode])
8078a8cd25Szhanglinjuan    }
81afcc4f2aSJiawei Lin  }
828b037849SYinan Xu
832225d46eSJiawei Lin  println(s"FPGASoC cores: $NumCores banks: $L3NBanks block size: $L3BlockSize bus size: $L3OuterBusWidth")
848b037849SYinan Xu
8534ab1ae9SJiawei Lin  val core_with_l2 = tiles.map(coreParams =>
86bb2f3f51STang Haojin    LazyModule(new XSTile()(p.alter((site, here, up) => {
872225d46eSJiawei Lin      case XSCoreParamsKey => coreParams
88bb2f3f51STang Haojin      case PerfCounterOptionsKey => up(PerfCounterOptionsKey).copy(perfDBHartID = coreParams.HartId)
892225d46eSJiawei Lin    })))
902225d46eSJiawei Lin  )
918b037849SYinan Xu
9234ab1ae9SJiawei Lin  val l3cacheOpt = soc.L3CacheParamsOpt.map(l3param =>
9334ab1ae9SJiawei Lin    LazyModule(new HuanCun()(new Config((_, _, _) => {
9434f38695STang Haojin      case HCCacheParamsKey => l3param.copy(
9534f38695STang Haojin        hartIds = tiles.map(_.HartId),
9634f38695STang Haojin        FPGAPlatform = debugOpts.FPGAPlatform
9734f38695STang Haojin      )
984daa5bf3SYangyu Chen      case MaxHartIdBits => p(MaxHartIdBits)
99bb2f3f51STang Haojin      case LogUtilsOptionsKey => p(LogUtilsOptionsKey)
100bb2f3f51STang Haojin      case PerfCounterOptionsKey => p(PerfCounterOptionsKey)
10134ab1ae9SJiawei Lin    })))
10234ab1ae9SJiawei Lin  )
10334ab1ae9SJiawei Lin
1045c060727Ssumailyyc  val chi_llcBridge_opt = Option.when(enableCHI)(
1055c060727Ssumailyyc    LazyModule(new OpenNCB()(p.alter((site, here, up) => {
1065c060727Ssumailyyc      case NCBParametersKey => new NCBParameters(
107af532009Ssumailyyc        outstandingDepth    = 64,
1085c060727Ssumailyyc        axiMasterOrder      = EnumAXIMasterOrder.WriteAddress,
1095c060727Ssumailyyc        readCompDMT         = false,
1105c060727Ssumailyyc        writeCancelable     = false,
1115c060727Ssumailyyc        writeNoError        = true,
112881e32f5SZifei Zhang        axiBurstAlwaysIncr  = true,
113881e32f5SZifei Zhang        chiDataCheck        = EnumCHIDataCheck.OddParity
1145c060727Ssumailyyc      )
1155c060727Ssumailyyc    })))
1165c060727Ssumailyyc  )
1175c060727Ssumailyyc
1185c060727Ssumailyyc  val chi_mmioBridge_opt = Seq.fill(NumCores)(Option.when(enableCHI)(
1195c060727Ssumailyyc    LazyModule(new OpenNCB()(p.alter((site, here, up) => {
1205c060727Ssumailyyc      case NCBParametersKey => new NCBParameters(
121af532009Ssumailyyc        outstandingDepth            = 32,
1225c060727Ssumailyyc        axiMasterOrder              = EnumAXIMasterOrder.None,
1235c060727Ssumailyyc        readCompDMT                 = false,
1245c060727Ssumailyyc        writeCancelable             = false,
1255c060727Ssumailyyc        writeNoError                = true,
1265c060727Ssumailyyc        asEndpoint                  = false,
1275c060727Ssumailyyc        acceptOrderEndpoint         = true,
1285c060727Ssumailyyc        acceptMemAttrDevice         = true,
1295c060727Ssumailyyc        readReceiptAfterAcception   = true,
130881e32f5SZifei Zhang        axiBurstAlwaysIncr          = true,
131881e32f5SZifei Zhang        chiDataCheck                = EnumCHIDataCheck.OddParity
1325c060727Ssumailyyc      )
1335c060727Ssumailyyc    })))
1345c060727Ssumailyyc  ))
13578a8cd25Szhanglinjuan
13678a8cd25Szhanglinjuan  // receive all prefetch req from cores
1370d32f713Shappy-lx  val memblock_pf_recv_nodes: Seq[Option[BundleBridgeSink[PrefetchRecv]]] = core_with_l2.map(_.core_l3_pf_port).map{
1380d32f713Shappy-lx    x => x.map(_ => BundleBridgeSink(Some(() => new PrefetchRecv)))
1390d32f713Shappy-lx  }
1400d32f713Shappy-lx
1410d32f713Shappy-lx  val l3_pf_sender_opt = soc.L3CacheParamsOpt.getOrElse(HCCacheParameters()).prefetch match {
1420d32f713Shappy-lx    case Some(pf) => Some(BundleBridgeSource(() => new PrefetchRecv))
1430d32f713Shappy-lx    case None => None
1440d32f713Shappy-lx  }
1458bc90631SZehao Liu  val nmiIntNode = IntSourceNode(IntSourcePortSimple(1, NumCores, (new NonmaskableInterruptIO).elements.size))
1468bc90631SZehao Liu  val nmi = InModuleBody(nmiIntNode.makeIOs())
1470d32f713Shappy-lx
1488b037849SYinan Xu  for (i <- 0 until NumCores) {
1494e12f40bSzhanglinjuan    core_with_l2(i).clint_int_node := misc.clint.intnode
1504e12f40bSzhanglinjuan    core_with_l2(i).plic_int_node :*= misc.plic.intnode
1514e12f40bSzhanglinjuan    core_with_l2(i).debug_int_node := misc.debugModule.debug.dmOuter.dmOuter.intnode
1528bc90631SZehao Liu    core_with_l2(i).nmi_int_node := nmiIntNode
153cac098b4SJiawei Lin    misc.plic.intnode := IntBuffer() := core_with_l2(i).beu_int_source
1544b40434cSzhanglinjuan    if (!enableCHI) {
15578a8cd25Szhanglinjuan      misc.peripheral_ports.get(i) := core_with_l2(i).tl_uncache
1564b40434cSzhanglinjuan    }
15778a8cd25Szhanglinjuan    core_with_l2(i).memory_port.foreach(port => (misc.core_to_l3_ports.get)(i) :=* port)
1580d32f713Shappy-lx    memblock_pf_recv_nodes(i).map(recv => {
1590d32f713Shappy-lx      println(s"Connecting Core_${i}'s L1 pf source to L3!")
1600d32f713Shappy-lx      recv := core_with_l2(i).core_l3_pf_port.get
1610d32f713Shappy-lx    })
1624a699e27Szhanglinjuan    misc.debugModuleXbarOpt.foreach(_ := core_with_l2(i).sep_dm_opt.get)
1638b037849SYinan Xu  }
1648b037849SYinan Xu
16578a8cd25Szhanglinjuan  l3cacheOpt.map(_.ctlnode.map(_ := misc.peripheralXbar.get))
16638005240SJiawei Lin  l3cacheOpt.map(_.intnode.map(int => {
16738005240SJiawei Lin    misc.plic.intnode := IntBuffer() := int
16838005240SJiawei Lin  }))
16934ab1ae9SJiawei Lin
17034ab1ae9SJiawei Lin  val core_rst_nodes = if(l3cacheOpt.nonEmpty && l3cacheOpt.get.rst_nodes.nonEmpty){
17134ab1ae9SJiawei Lin    l3cacheOpt.get.rst_nodes.get
17234ab1ae9SJiawei Lin  } else {
1738a167be7SHaojin Tang    core_with_l2.map(_ => BundleBridgeSource(() => Reset()))
17434ab1ae9SJiawei Lin  }
17534ab1ae9SJiawei Lin
17634ab1ae9SJiawei Lin  core_rst_nodes.zip(core_with_l2.map(_.core_reset_sink)).foreach({
17734ab1ae9SJiawei Lin    case (source, sink) =>  sink := source
17834ab1ae9SJiawei Lin  })
179a1ea7f76SJiawei Lin
1804f94c0c6SJiawei Lin  l3cacheOpt match {
1814f94c0c6SJiawei Lin    case Some(l3) =>
1821bf9a05aSzhanglinjuan      misc.l3_out :*= l3.node :*= misc.l3_banked_xbar.get
1830d32f713Shappy-lx      l3.pf_recv_node.map(recv => {
1840d32f713Shappy-lx        println("Connecting L1 prefetcher to L3!")
1850d32f713Shappy-lx        recv := l3_pf_sender_opt.get
1860d32f713Shappy-lx      })
1879672f0b7Swakafa      l3.tpmeta_recv_node.foreach(recv => {
1889672f0b7Swakafa        for ((core, i) <- core_with_l2.zipWithIndex) {
1899672f0b7Swakafa          println(s"Connecting core_$i\'s L2 TPmeta request to L3!")
1909672f0b7Swakafa          recv := core.core_l3_tpmeta_source_port.get
1919672f0b7Swakafa        }
1929672f0b7Swakafa      })
1939672f0b7Swakafa      l3.tpmeta_send_node.foreach(send => {
1949672f0b7Swakafa        val broadcast = LazyModule(new ValidIOBroadcast[TPmetaResp]())
1959672f0b7Swakafa        broadcast.node := send
1969672f0b7Swakafa        for ((core, i) <- core_with_l2.zipWithIndex) {
1979672f0b7Swakafa          println(s"Connecting core_$i\'s L2 TPmeta response to L3!")
1989672f0b7Swakafa          core.core_l3_tpmeta_sink_port.get := broadcast.node
1999672f0b7Swakafa        }
2009672f0b7Swakafa      })
20173be64b3SJiawei Lin    case None =>
2029d5a2027SYinan Xu  }
2038b037849SYinan Xu
2045c060727Ssumailyyc  chi_llcBridge_opt match {
2055c060727Ssumailyyc    case Some(ncb) =>
2065c060727Ssumailyyc      misc.soc_xbar.get := ncb.axi4node
20778a8cd25Szhanglinjuan    case None =>
20878a8cd25Szhanglinjuan  }
20978a8cd25Szhanglinjuan
2105c060727Ssumailyyc  chi_mmioBridge_opt.foreach { e =>
2115c060727Ssumailyyc    e match {
2125c060727Ssumailyyc      case Some(ncb) =>
2135c060727Ssumailyyc        misc.soc_xbar.get := ncb.axi4node
2145c060727Ssumailyyc      case None =>
2155c060727Ssumailyyc    }
2165c060727Ssumailyyc  }
2175c060727Ssumailyyc
218935edac4STang Haojin  class XSTopImp(wrapper: LazyModule) extends LazyRawModuleImp(wrapper) {
219a5b77de4STang Haojin    soc.XSTopPrefix.foreach { prefix =>
220a5b77de4STang Haojin      val mod = this.toNamed
221a5b77de4STang Haojin      annotate(new ChiselAnnotation {
222a5b77de4STang Haojin        def toFirrtl = NestedPrefixModulesAnnotation(mod, prefix, true)
223a5b77de4STang Haojin      })
224a5b77de4STang Haojin    }
225a5b77de4STang Haojin
226876196b7SMaxpicca-Li    FileRegisters.add("dts", dts)
227876196b7SMaxpicca-Li    FileRegisters.add("graphml", graphML)
228876196b7SMaxpicca-Li    FileRegisters.add("json", json)
229876196b7SMaxpicca-Li    FileRegisters.add("plusArgs", freechips.rocketchip.util.PlusArgArtefacts.serialize_cHeader())
2304f0a2459Swakafa
2312993c5ecSHaojin Tang    val dma = socMisc.map(m => IO(Flipped(new VerilogAXI4Record(m.dma.elts.head.params))))
2321bf9a05aSzhanglinjuan    val peripheral = IO(new VerilogAXI4Record(misc.peripheral.elts.head.params))
2332993c5ecSHaojin Tang    val memory = IO(new VerilogAXI4Record(misc.memory.elts.head.params))
23473be64b3SJiawei Lin
2354b40434cSzhanglinjuan    socMisc match {
2364b40434cSzhanglinjuan      case Some(m) =>
2372993c5ecSHaojin Tang        m.dma.elements.head._2 <> dma.get.viewAs[AXI4Bundle]
2384b40434cSzhanglinjuan        dontTouch(dma.get)
2394b40434cSzhanglinjuan      case None =>
2404b40434cSzhanglinjuan    }
2414b40434cSzhanglinjuan
2422993c5ecSHaojin Tang    memory.viewAs[AXI4Bundle] <> misc.memory.elements.head._2
24378a8cd25Szhanglinjuan    peripheral.viewAs[AXI4Bundle] <> misc.peripheral.elements.head._2
24473be64b3SJiawei Lin
2458b037849SYinan Xu    val io = IO(new Bundle {
24620957846SZihao Yu      val clock = Input(Clock())
24767ba96b4SYinan Xu      val reset = Input(AsyncReset())
24834ab1ae9SJiawei Lin      val sram_config = Input(UInt(16.W))
2498b037849SYinan Xu      val extIntrs = Input(UInt(NrExtIntr.W))
25034ab1ae9SJiawei Lin      val pll0_lock = Input(Bool())
25134ab1ae9SJiawei Lin      val pll0_ctrl = Output(Vec(6, UInt(32.W)))
252d4aca96cSlqre      val systemjtag = new Bundle {
253d4aca96cSlqre        val jtag = Flipped(new JTAGIO(hasTRSTn = false))
25467ba96b4SYinan Xu        val reset = Input(AsyncReset()) // No reset allowed on top
255d4aca96cSlqre        val mfr_id = Input(UInt(11.W))
256d4aca96cSlqre        val part_number = Input(UInt(16.W))
257d4aca96cSlqre        val version = Input(UInt(4.W))
258d4aca96cSlqre      }
25977bc15a2SYinan Xu      val debug_reset = Output(Bool())
2609e56439dSHazard      val rtc_clock = Input(Bool())
26198c71602SJiawei Lin      val cacheable_check = new TLPMAIO()
262b6900d94SYinan Xu      val riscv_halt = Output(Vec(NumCores, Bool()))
26385a8d7caSZehao Liu      val riscv_critical_error = Output(Vec(NumCores, Bool()))
2640700cab2STang Haojin      val riscv_rst_vec = Input(Vec(NumCores, UInt(soc.PAddrBits.W)))
265725e8ddcSchengguanghui      val traceCoreInterface = Vec(NumCores, new Bundle {
266725e8ddcSchengguanghui        val fromEncoder = Input(new Bundle {
267725e8ddcSchengguanghui          val enable = Bool()
268725e8ddcSchengguanghui          val stall  = Bool()
269725e8ddcSchengguanghui        })
270725e8ddcSchengguanghui        val toEncoder   = Output(new Bundle {
271725e8ddcSchengguanghui          val cause     = UInt(TraceCauseWidth.W)
272725e8ddcSchengguanghui          val tval      = UInt(TraceTvalWidth.W)
273725e8ddcSchengguanghui          val priv      = UInt(TracePrivWidth.W)
274725e8ddcSchengguanghui          val iaddr     = UInt((TraceTraceGroupNum * TraceIaddrWidth).W)
275725e8ddcSchengguanghui          val itype     = UInt((TraceTraceGroupNum * TraceItypeWidth).W)
276725e8ddcSchengguanghui          val iretire   = UInt((TraceTraceGroupNum * TraceIretireWidthCompressed).W)
277725e8ddcSchengguanghui          val ilastsize = UInt((TraceTraceGroupNum * TraceIlastsizeWidth).W)
278725e8ddcSchengguanghui        })
279725e8ddcSchengguanghui      })
2808b037849SYinan Xu    })
28167ba96b4SYinan Xu
28220957846SZihao Yu    val reset_sync = withClockAndReset(io.clock, io.reset) { ResetGen() }
28367ba96b4SYinan Xu    val jtag_reset_sync = withClockAndReset(io.systemjtag.jtag.TCK, io.systemjtag.reset) { ResetGen() }
2845c060727Ssumailyyc    val chi_openllc_opt = Option.when(enableCHI)(
28520957846SZihao Yu      withClockAndReset(io.clock, io.reset) {
2865c060727Ssumailyyc        Module(new OpenLLC()(p.alter((site, here, up) => {
287186eb48dSsumailyyc          case OpenLLCParamKey => soc.OpenLLCParamsOpt.get.copy(
288186eb48dSsumailyyc            hartIds = tiles.map(_.HartId),
289186eb48dSsumailyyc            FPGAPlatform = debugOpts.FPGAPlatform
290186eb48dSsumailyyc          )
2915c060727Ssumailyyc        })))
2925c060727Ssumailyyc      }
2935c060727Ssumailyyc    )
29467ba96b4SYinan Xu
29577bc15a2SYinan Xu    // override LazyRawModuleImp's clock and reset
29620957846SZihao Yu    childClock := io.clock
29767ba96b4SYinan Xu    childReset := reset_sync
29877bc15a2SYinan Xu
29977bc15a2SYinan Xu    // output
30077bc15a2SYinan Xu    io.debug_reset := misc.module.debug_module_io.debugIO.ndreset
30177bc15a2SYinan Xu
30277bc15a2SYinan Xu    // input
30308bf93ffSrvcoresjw    dontTouch(io)
30408bf93ffSrvcoresjw    dontTouch(memory)
30573be64b3SJiawei Lin    misc.module.ext_intrs := io.extIntrs
3069e56439dSHazard    misc.module.rtc_clock := io.rtc_clock
30734ab1ae9SJiawei Lin    misc.module.pll0_lock := io.pll0_lock
30898c71602SJiawei Lin    misc.module.cacheable_check <> io.cacheable_check
30934ab1ae9SJiawei Lin
31034ab1ae9SJiawei Lin    io.pll0_ctrl <> misc.module.pll0_ctrl
311c0bc1ee4SYinan Xu
312e156f460SHaojin Tang    val msiInfo = WireInit(0.U.asTypeOf(ValidIO(new MsiInfoBundle)))
313e156f460SHaojin Tang
314007f6122SXuan Hu
31577bc15a2SYinan Xu    for ((core, i) <- core_with_l2.zipWithIndex) {
31677bc15a2SYinan Xu      core.module.io.hartId := i.U
317e156f460SHaojin Tang      core.module.io.msiInfo := msiInfo
3183bf5eac7SXuan Hu      core.module.io.clintTime := misc.module.clintTime
319b6900d94SYinan Xu      io.riscv_halt(i) := core.module.io.cpu_halt
32085a8d7caSZehao Liu      io.riscv_critical_error(i) := core.module.io.cpu_crtical_error
3213ad9f3ddSchengguanghui      // trace Interface
3223ad9f3ddSchengguanghui      val traceInterface = core.module.io.traceCoreInterface
3233ad9f3ddSchengguanghui      traceInterface.fromEncoder := io.traceCoreInterface(i).fromEncoder
3243ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.priv := traceInterface.toEncoder.priv
3253ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.cause := traceInterface.toEncoder.trap.cause
3263ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.tval := traceInterface.toEncoder.trap.tval
3273ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.iaddr := VecInit(traceInterface.toEncoder.groups.map(_.bits.iaddr)).asUInt
3283ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.itype := VecInit(traceInterface.toEncoder.groups.map(_.bits.itype)).asUInt
3293ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.iretire := VecInit(traceInterface.toEncoder.groups.map(_.bits.iretire)).asUInt
3303ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.ilastsize := VecInit(traceInterface.toEncoder.groups.map(_.bits.ilastsize)).asUInt
3313ad9f3ddSchengguanghui
332*e0d20e1bSTang Haojin      core.module.io.dft.foreach(dontTouch(_) := 0.U.asTypeOf(new SramBroadcastBundle))
333*e0d20e1bSTang Haojin      core.module.io.dft_reset.foreach(dontTouch(_) := 0.U.asTypeOf(new DFTResetSignals))
334c4b44470SGuokai Chen      core.module.io.reset_vector := io.riscv_rst_vec(i)
3355c060727Ssumailyyc    }
3365c060727Ssumailyyc
33720957846SZihao Yu    withClockAndReset(io.clock, io.reset) {
3385c060727Ssumailyyc      Option.when(enableCHI)(true.B).foreach { _ =>
3395c060727Ssumailyyc        for ((core, i) <- core_with_l2.zipWithIndex) {
3405c060727Ssumailyyc          val mmioLogger = CHILogger(s"L2[${i}]_MMIO", true)
3415c060727Ssumailyyc          val llcLogger = CHILogger(s"L2[${i}]_LLC", true)
3425c060727Ssumailyyc          dontTouch(core.module.io.chi.get)
3435c060727Ssumailyyc          bind(
3445c060727Ssumailyyc            route(
3455c060727Ssumailyyc              core.module.io.chi.get, Map((AddressSet(0x0L, 0x00007fffffffL), NumCores + i)) ++ AddressSet(0x0L,
3465c060727Ssumailyyc              0xffffffffffffL).subtract(AddressSet(0x0L, 0x00007fffffffL)).map(addr => (addr, NumCores * 2)).toMap
3475c060727Ssumailyyc            ),
3485c060727Ssumailyyc            Map((NumCores + i) -> mmioLogger.io.up, (NumCores * 2) -> llcLogger.io.up)
3495c060727Ssumailyyc          )
3505c060727Ssumailyyc          chi_mmioBridge_opt(i).get.module.io.chi.connect(mmioLogger.io.down)
3515c060727Ssumailyyc          chi_openllc_opt.get.io.rn(i) <> llcLogger.io.down
352881e32f5SZifei Zhang          require(core.module.io.chi.get.getWidth == llcLogger.io.up.getWidth)
353881e32f5SZifei Zhang          require(llcLogger.io.down.getWidth == chi_openllc_opt.get.io.rn(i).getWidth)
3545c060727Ssumailyyc        }
3555c060727Ssumailyyc        val memLogger = CHILogger(s"LLC_MEM", true)
3565c060727Ssumailyyc        chi_openllc_opt.get.io.sn.connect(memLogger.io.up)
3575c060727Ssumailyyc        chi_llcBridge_opt.get.module.io.chi.connect(memLogger.io.down)
3585c060727Ssumailyyc        chi_openllc_opt.get.io.nodeID := (NumCores * 2).U
359186eb48dSsumailyyc        chi_openllc_opt.foreach { l3 =>
360186eb48dSsumailyyc          l3.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr)
361186eb48dSsumailyyc        }
362186eb48dSsumailyyc        core_with_l2.zip(chi_openllc_opt.get.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) =>
363186eb48dSsumailyyc          tile.module.io.debugTopDown.l3MissMatch := l3Match
364186eb48dSsumailyyc        }
365e836c770SZhaoyang You        core_with_l2.zip(chi_openllc_opt).foreach { case (tile, l3) =>
366e836c770SZhaoyang You          tile.module.io.l3Miss := l3.io.l3Miss
367e836c770SZhaoyang You        }
36878a8cd25Szhanglinjuan      }
3698b037849SYinan Xu    }
3708b037849SYinan Xu
37134ab1ae9SJiawei Lin    if(l3cacheOpt.isEmpty || l3cacheOpt.get.rst_nodes.isEmpty){
37234ab1ae9SJiawei Lin      // tie off core soft reset
37334ab1ae9SJiawei Lin      for(node <- core_rst_nodes){
374935edac4STang Haojin        node.out.head._1 := false.B.asAsyncReset
37534ab1ae9SJiawei Lin      }
37634ab1ae9SJiawei Lin    }
37734ab1ae9SJiawei Lin
37860ebee38STang Haojin    l3cacheOpt match {
37960ebee38STang Haojin      case Some(l3) =>
3800d32f713Shappy-lx        l3.pf_recv_node match {
3810d32f713Shappy-lx          case Some(recv) =>
3820d32f713Shappy-lx            l3_pf_sender_opt.get.out.head._1.addr_valid := VecInit(memblock_pf_recv_nodes.map(_.get.in.head._1.addr_valid)).asUInt.orR
3830d32f713Shappy-lx            for (i <- 0 until NumCores) {
3840d32f713Shappy-lx              when(memblock_pf_recv_nodes(i).get.in.head._1.addr_valid) {
3850d32f713Shappy-lx                l3_pf_sender_opt.get.out.head._1.addr := memblock_pf_recv_nodes(i).get.in.head._1.addr
3860d32f713Shappy-lx                l3_pf_sender_opt.get.out.head._1.l2_pf_en := memblock_pf_recv_nodes(i).get.in.head._1.l2_pf_en
3870d32f713Shappy-lx              }
3880d32f713Shappy-lx            }
38960ebee38STang Haojin          case None =>
3900d32f713Shappy-lx        }
39160ebee38STang Haojin        l3.module.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr)
39260ebee38STang Haojin        core_with_l2.zip(l3.module.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) => tile.module.io.debugTopDown.l3MissMatch := l3Match }
393e836c770SZhaoyang You        core_with_l2.foreach(_.module.io.l3Miss := l3.module.io.l3Miss)
394186eb48dSsumailyyc      case None =>
395186eb48dSsumailyyc    }
396186eb48dSsumailyyc
397186eb48dSsumailyyc    (chi_openllc_opt, l3cacheOpt) match {
398e836c770SZhaoyang You      case (None, None) =>
399e836c770SZhaoyang You        core_with_l2.foreach(_.module.io.debugTopDown.l3MissMatch := false.B)
400e836c770SZhaoyang You        core_with_l2.foreach(_.module.io.l3Miss := false.B)
401186eb48dSsumailyyc      case _ =>
40260ebee38STang Haojin    }
4030d32f713Shappy-lx
404c51f1a7bSsumailyyc    core_with_l2.zipWithIndex.foreach { case (tile, i) =>
4054b40434cSzhanglinjuan      tile.module.io.nodeID.foreach { case nodeID =>
406c51f1a7bSsumailyyc        nodeID := i.U
4074b40434cSzhanglinjuan        dontTouch(nodeID)
4084b40434cSzhanglinjuan      }
4094b40434cSzhanglinjuan    }
4104b40434cSzhanglinjuan
4113a3744e4Schengguanghui    misc.module.debug_module_io.resetCtrl.hartIsInReset := core_with_l2.map(_.module.io.hartIsInReset)
41273be64b3SJiawei Lin    misc.module.debug_module_io.clock := io.clock
41367ba96b4SYinan Xu    misc.module.debug_module_io.reset := reset_sync
414d4aca96cSlqre
41567ba96b4SYinan Xu    misc.module.debug_module_io.debugIO.reset := misc.module.reset
41620957846SZihao Yu    misc.module.debug_module_io.debugIO.clock := io.clock
41777bc15a2SYinan Xu    // TODO: delay 3 cycles?
41877bc15a2SYinan Xu    misc.module.debug_module_io.debugIO.dmactiveAck := misc.module.debug_module_io.debugIO.dmactive
419d4aca96cSlqre    // jtag connector
42073be64b3SJiawei Lin    misc.module.debug_module_io.debugIO.systemjtag.foreach { x =>
421d4aca96cSlqre      x.jtag        <> io.systemjtag.jtag
42267ba96b4SYinan Xu      x.reset       := jtag_reset_sync
423d4aca96cSlqre      x.mfr_id      := io.systemjtag.mfr_id
424d4aca96cSlqre      x.part_number := io.systemjtag.part_number
425d4aca96cSlqre      x.version     := io.systemjtag.version
426d4aca96cSlqre    }
42777bc15a2SYinan Xu
42820957846SZihao Yu    withClockAndReset(io.clock, reset_sync) {
42977bc15a2SYinan Xu      // Modules are reset one by one
43025cb35b6SJiawei Lin      // reset ----> SYNC --> {SoCMisc, L3 Cache, Cores}
4313a3744e4Schengguanghui      val resetChain = Seq(Seq(misc.module) ++ l3cacheOpt.map(_.module))
4329eee369fSKamimiao      ResetGen(resetChain, reset_sync, !debugOpts.ResetGen)
4333a3744e4Schengguanghui      // Ensure that cores could be reset when DM disable `hartReset` or l3cacheOpt.isEmpty.
4343a3744e4Schengguanghui      val dmResetReqVec = misc.module.debug_module_io.resetCtrl.hartResetReq.getOrElse(0.U.asTypeOf(Vec(core_with_l2.map(_.module).length, Bool())))
4353a3744e4Schengguanghui      val syncResetCores = if(l3cacheOpt.nonEmpty) l3cacheOpt.map(_.module).get.reset.asBool else misc.module.reset.asBool
4363a3744e4Schengguanghui      (core_with_l2.map(_.module)).zip(dmResetReqVec).map { case(core, dmResetReq) =>
4373a3744e4Schengguanghui        ResetGen(Seq(Seq(core)), (syncResetCores || dmResetReq).asAsyncReset, !debugOpts.ResetGen)
4383a3744e4Schengguanghui      }
4398b037849SYinan Xu    }
44077bc15a2SYinan Xu
4418b037849SYinan Xu  }
442935edac4STang Haojin
443935edac4STang Haojin  lazy val module = new XSTopImp(this)
4449d5a2027SYinan Xu}
4458b037849SYinan Xu
446935edac4STang Haojinobject TopMain extends App {
44751e45dbbSTang Haojin  val (config, firrtlOpts, firtoolOpts) = ArgParser.parse(args)
44893610df3SMaxpicca-Li
44993610df3SMaxpicca-Li  // tools: init to close dpi-c when in fpga
45093610df3SMaxpicca-Li  val envInFPGA = config(DebugOptionsKey).FPGAPlatform
451cacfe229STang Haojin  val enableDifftest = config(DebugOptionsKey).EnableDifftest || config(DebugOptionsKey).AlwaysBasicDiff
45262129679Swakafa  val enableChiselDB = config(DebugOptionsKey).EnableChiselDB
453047e34f9SMaxpicca-Li  val enableConstantin = config(DebugOptionsKey).EnableConstantin
454047e34f9SMaxpicca-Li  Constantin.init(enableConstantin && !envInFPGA)
45562129679Swakafa  ChiselDB.init(enableChiselDB && !envInFPGA)
45693610df3SMaxpicca-Li
457c33deca9Sklin02  if (config(SoCParamsKey).UseXSNoCDiffTop) {
458c33deca9Sklin02    Generator.execute(firrtlOpts, DisableMonitors(p => new XSNoCDiffTop()(p))(config), firtoolOpts)
459c33deca9Sklin02  } else {
460720dd621STang Haojin    val soc = if (config(SoCParamsKey).UseXSNoCTop)
461720dd621STang Haojin      DisableMonitors(p => LazyModule(new XSNoCTop()(p)))(config)
462720dd621STang Haojin    else
463720dd621STang Haojin      DisableMonitors(p => LazyModule(new XSTop()(p)))(config)
464720dd621STang Haojin
46551e45dbbSTang Haojin    Generator.execute(firrtlOpts, soc.module, firtoolOpts)
4662316cea8SJiuyue Ma
4672316cea8SJiuyue Ma    // generate difftest bundles (w/o DifftestTopIO)
4682316cea8SJiuyue Ma    if (enableDifftest) {
4692316cea8SJiuyue Ma      DifftestModule.finish("XiangShan", false)
4702316cea8SJiuyue Ma    }
471c33deca9Sklin02  }
4722316cea8SJiuyue Ma
473876196b7SMaxpicca-Li  FileRegisters.write(fileDir = "./build", filePrefix = "XSTop.")
4748b037849SYinan Xu}
475