xref: /XiangShan/src/main/scala/top/Top.scala (revision c33deca9ac63869fa9a28ad5641cd23f024d5af6)
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._
338b037849SYinan Xuimport system._
34d4aca96cSlqreimport device._
358b037849SYinan Xuimport chisel3.stage.ChiselGeneratorAnnotation
368891a219SYinan Xuimport org.chipsalliance.cde.config._
378b037849SYinan Xuimport freechips.rocketchip.diplomacy._
384daa5bf3SYangyu Chenimport freechips.rocketchip.tile._
398b037849SYinan Xuimport freechips.rocketchip.tilelink._
408bc90631SZehao Liuimport freechips.rocketchip.interrupts._
414b40434cSzhanglinjuanimport freechips.rocketchip.amba.axi4._
42d4aca96cSlqreimport freechips.rocketchip.jtag.JTAGIO
43a5b77de4STang Haojinimport chisel3.experimental.{annotate, ChiselAnnotation}
44a5b77de4STang Haojinimport sifive.enterprise.firrtl.NestedPrefixModulesAnnotation
455c060727Ssumailyycimport scala.collection.mutable.{Map}
46d4aca96cSlqre
47afcc4f2aSJiawei Linabstract class BaseXSSoc()(implicit p: Parameters) extends LazyModule
48afcc4f2aSJiawei Lin  with BindingScope
49afcc4f2aSJiawei Lin{
504b40434cSzhanglinjuan  // val misc = LazyModule(new SoCMisc())
51afcc4f2aSJiawei Lin  lazy val dts = DTS(bindingTree)
524f0a2459Swakafa  lazy val json = JSON(bindingTree)
538b037849SYinan Xu}
548b037849SYinan Xu
5573be64b3SJiawei Linclass XSTop()(implicit p: Parameters) extends BaseXSSoc() with HasSoCParameter
568b037849SYinan Xu{
574b40434cSzhanglinjuan  val nocMisc = if (enableCHI) Some(LazyModule(new MemMisc())) else None
584b40434cSzhanglinjuan  val socMisc = if (!enableCHI) Some(LazyModule(new SoCMisc())) else None
594b40434cSzhanglinjuan  val misc: MemMisc = if (enableCHI) nocMisc.get else socMisc.get
604b40434cSzhanglinjuan
61afcc4f2aSJiawei Lin  ResourceBinding {
62afcc4f2aSJiawei Lin    val width = ResourceInt(2)
63ce34d21eSJiuyue Ma    val model = "xiangshan," + os.read(os.resource / "publishVersion")
64ce34d21eSJiuyue Ma    val compatible = "freechips,rocketchip-unknown"
65afcc4f2aSJiawei Lin    Resource(ResourceAnchors.root, "model").bind(ResourceString(model))
66ce34d21eSJiuyue Ma    Resource(ResourceAnchors.root, "compat").bind(ResourceString(compatible + "-dev"))
67ce34d21eSJiuyue Ma    Resource(ResourceAnchors.soc, "compat").bind(ResourceString(compatible + "-soc"))
68afcc4f2aSJiawei Lin    Resource(ResourceAnchors.root, "width").bind(width)
69afcc4f2aSJiawei Lin    Resource(ResourceAnchors.soc, "width").bind(width)
70afcc4f2aSJiawei Lin    Resource(ResourceAnchors.cpus, "width").bind(ResourceInt(1))
71afcc4f2aSJiawei Lin    def bindManagers(xbar: TLNexusNode) = {
72afcc4f2aSJiawei Lin      ManagerUnification(xbar.edges.in.head.manager.managers).foreach{ manager =>
73afcc4f2aSJiawei Lin        manager.resources.foreach(r => r.bind(manager.toResource))
74afcc4f2aSJiawei Lin      }
75afcc4f2aSJiawei Lin    }
7678a8cd25Szhanglinjuan    if (!enableCHI) {
771bf9a05aSzhanglinjuan      bindManagers(misc.l3_xbar.get.asInstanceOf[TLNexusNode])
7878a8cd25Szhanglinjuan      bindManagers(misc.peripheralXbar.get.asInstanceOf[TLNexusNode])
7978a8cd25Szhanglinjuan    }
80afcc4f2aSJiawei Lin  }
818b037849SYinan Xu
822225d46eSJiawei Lin  println(s"FPGASoC cores: $NumCores banks: $L3NBanks block size: $L3BlockSize bus size: $L3OuterBusWidth")
838b037849SYinan Xu
8434ab1ae9SJiawei Lin  val core_with_l2 = tiles.map(coreParams =>
85bb2f3f51STang Haojin    LazyModule(new XSTile()(p.alter((site, here, up) => {
862225d46eSJiawei Lin      case XSCoreParamsKey => coreParams
87bb2f3f51STang Haojin      case PerfCounterOptionsKey => up(PerfCounterOptionsKey).copy(perfDBHartID = coreParams.HartId)
882225d46eSJiawei Lin    })))
892225d46eSJiawei Lin  )
908b037849SYinan Xu
9134ab1ae9SJiawei Lin  val l3cacheOpt = soc.L3CacheParamsOpt.map(l3param =>
9234ab1ae9SJiawei Lin    LazyModule(new HuanCun()(new Config((_, _, _) => {
9334f38695STang Haojin      case HCCacheParamsKey => l3param.copy(
9434f38695STang Haojin        hartIds = tiles.map(_.HartId),
9534f38695STang Haojin        FPGAPlatform = debugOpts.FPGAPlatform
9634f38695STang Haojin      )
974daa5bf3SYangyu Chen      case MaxHartIdBits => p(MaxHartIdBits)
98bb2f3f51STang Haojin      case LogUtilsOptionsKey => p(LogUtilsOptionsKey)
99bb2f3f51STang Haojin      case PerfCounterOptionsKey => p(PerfCounterOptionsKey)
10034ab1ae9SJiawei Lin    })))
10134ab1ae9SJiawei Lin  )
10234ab1ae9SJiawei Lin
1035c060727Ssumailyyc  val chi_llcBridge_opt = Option.when(enableCHI)(
1045c060727Ssumailyyc    LazyModule(new OpenNCB()(p.alter((site, here, up) => {
1055c060727Ssumailyyc      case NCBParametersKey => new NCBParameters(
106af532009Ssumailyyc        outstandingDepth    = 64,
1075c060727Ssumailyyc        axiMasterOrder      = EnumAXIMasterOrder.WriteAddress,
1085c060727Ssumailyyc        readCompDMT         = false,
1095c060727Ssumailyyc        writeCancelable     = false,
1105c060727Ssumailyyc        writeNoError        = true,
1115c060727Ssumailyyc        axiBurstAlwaysIncr  = true
1125c060727Ssumailyyc      )
1135c060727Ssumailyyc    })))
1145c060727Ssumailyyc  )
1155c060727Ssumailyyc
1165c060727Ssumailyyc  val chi_mmioBridge_opt = Seq.fill(NumCores)(Option.when(enableCHI)(
1175c060727Ssumailyyc    LazyModule(new OpenNCB()(p.alter((site, here, up) => {
1185c060727Ssumailyyc      case NCBParametersKey => new NCBParameters(
119af532009Ssumailyyc        outstandingDepth            = 32,
1205c060727Ssumailyyc        axiMasterOrder              = EnumAXIMasterOrder.None,
1215c060727Ssumailyyc        readCompDMT                 = false,
1225c060727Ssumailyyc        writeCancelable             = false,
1235c060727Ssumailyyc        writeNoError                = true,
1245c060727Ssumailyyc        asEndpoint                  = false,
1255c060727Ssumailyyc        acceptOrderEndpoint         = true,
1265c060727Ssumailyyc        acceptMemAttrDevice         = true,
1275c060727Ssumailyyc        readReceiptAfterAcception   = true,
1285c060727Ssumailyyc        axiBurstAlwaysIncr          = true
1295c060727Ssumailyyc      )
1305c060727Ssumailyyc    })))
1315c060727Ssumailyyc  ))
13278a8cd25Szhanglinjuan
13378a8cd25Szhanglinjuan  // receive all prefetch req from cores
1340d32f713Shappy-lx  val memblock_pf_recv_nodes: Seq[Option[BundleBridgeSink[PrefetchRecv]]] = core_with_l2.map(_.core_l3_pf_port).map{
1350d32f713Shappy-lx    x => x.map(_ => BundleBridgeSink(Some(() => new PrefetchRecv)))
1360d32f713Shappy-lx  }
1370d32f713Shappy-lx
1380d32f713Shappy-lx  val l3_pf_sender_opt = soc.L3CacheParamsOpt.getOrElse(HCCacheParameters()).prefetch match {
1390d32f713Shappy-lx    case Some(pf) => Some(BundleBridgeSource(() => new PrefetchRecv))
1400d32f713Shappy-lx    case None => None
1410d32f713Shappy-lx  }
1428bc90631SZehao Liu  val nmiIntNode = IntSourceNode(IntSourcePortSimple(1, NumCores, (new NonmaskableInterruptIO).elements.size))
1438bc90631SZehao Liu  val nmi = InModuleBody(nmiIntNode.makeIOs())
1440d32f713Shappy-lx
1458b037849SYinan Xu  for (i <- 0 until NumCores) {
1464e12f40bSzhanglinjuan    core_with_l2(i).clint_int_node := misc.clint.intnode
1474e12f40bSzhanglinjuan    core_with_l2(i).plic_int_node :*= misc.plic.intnode
1484e12f40bSzhanglinjuan    core_with_l2(i).debug_int_node := misc.debugModule.debug.dmOuter.dmOuter.intnode
1498bc90631SZehao Liu    core_with_l2(i).nmi_int_node := nmiIntNode
150cac098b4SJiawei Lin    misc.plic.intnode := IntBuffer() := core_with_l2(i).beu_int_source
1514b40434cSzhanglinjuan    if (!enableCHI) {
15278a8cd25Szhanglinjuan      misc.peripheral_ports.get(i) := core_with_l2(i).tl_uncache
1534b40434cSzhanglinjuan    }
15478a8cd25Szhanglinjuan    core_with_l2(i).memory_port.foreach(port => (misc.core_to_l3_ports.get)(i) :=* port)
1550d32f713Shappy-lx    memblock_pf_recv_nodes(i).map(recv => {
1560d32f713Shappy-lx      println(s"Connecting Core_${i}'s L1 pf source to L3!")
1570d32f713Shappy-lx      recv := core_with_l2(i).core_l3_pf_port.get
1580d32f713Shappy-lx    })
1598b037849SYinan Xu  }
1608b037849SYinan Xu
16178a8cd25Szhanglinjuan  l3cacheOpt.map(_.ctlnode.map(_ := misc.peripheralXbar.get))
16238005240SJiawei Lin  l3cacheOpt.map(_.intnode.map(int => {
16338005240SJiawei Lin    misc.plic.intnode := IntBuffer() := int
16438005240SJiawei Lin  }))
16534ab1ae9SJiawei Lin
16634ab1ae9SJiawei Lin  val core_rst_nodes = if(l3cacheOpt.nonEmpty && l3cacheOpt.get.rst_nodes.nonEmpty){
16734ab1ae9SJiawei Lin    l3cacheOpt.get.rst_nodes.get
16834ab1ae9SJiawei Lin  } else {
1698a167be7SHaojin Tang    core_with_l2.map(_ => BundleBridgeSource(() => Reset()))
17034ab1ae9SJiawei Lin  }
17134ab1ae9SJiawei Lin
17234ab1ae9SJiawei Lin  core_rst_nodes.zip(core_with_l2.map(_.core_reset_sink)).foreach({
17334ab1ae9SJiawei Lin    case (source, sink) =>  sink := source
17434ab1ae9SJiawei Lin  })
175a1ea7f76SJiawei Lin
1764f94c0c6SJiawei Lin  l3cacheOpt match {
1774f94c0c6SJiawei Lin    case Some(l3) =>
1781bf9a05aSzhanglinjuan      misc.l3_out :*= l3.node :*= misc.l3_banked_xbar.get
1790d32f713Shappy-lx      l3.pf_recv_node.map(recv => {
1800d32f713Shappy-lx        println("Connecting L1 prefetcher to L3!")
1810d32f713Shappy-lx        recv := l3_pf_sender_opt.get
1820d32f713Shappy-lx      })
1839672f0b7Swakafa      l3.tpmeta_recv_node.foreach(recv => {
1849672f0b7Swakafa        for ((core, i) <- core_with_l2.zipWithIndex) {
1859672f0b7Swakafa          println(s"Connecting core_$i\'s L2 TPmeta request to L3!")
1869672f0b7Swakafa          recv := core.core_l3_tpmeta_source_port.get
1879672f0b7Swakafa        }
1889672f0b7Swakafa      })
1899672f0b7Swakafa      l3.tpmeta_send_node.foreach(send => {
1909672f0b7Swakafa        val broadcast = LazyModule(new ValidIOBroadcast[TPmetaResp]())
1919672f0b7Swakafa        broadcast.node := send
1929672f0b7Swakafa        for ((core, i) <- core_with_l2.zipWithIndex) {
1939672f0b7Swakafa          println(s"Connecting core_$i\'s L2 TPmeta response to L3!")
1949672f0b7Swakafa          core.core_l3_tpmeta_sink_port.get := broadcast.node
1959672f0b7Swakafa        }
1969672f0b7Swakafa      })
19773be64b3SJiawei Lin    case None =>
1989d5a2027SYinan Xu  }
1998b037849SYinan Xu
2005c060727Ssumailyyc  chi_llcBridge_opt match {
2015c060727Ssumailyyc    case Some(ncb) =>
2025c060727Ssumailyyc      misc.soc_xbar.get := ncb.axi4node
20378a8cd25Szhanglinjuan    case None =>
20478a8cd25Szhanglinjuan  }
20578a8cd25Szhanglinjuan
2065c060727Ssumailyyc  chi_mmioBridge_opt.foreach { e =>
2075c060727Ssumailyyc    e match {
2085c060727Ssumailyyc      case Some(ncb) =>
2095c060727Ssumailyyc        misc.soc_xbar.get := ncb.axi4node
2105c060727Ssumailyyc      case None =>
2115c060727Ssumailyyc    }
2125c060727Ssumailyyc  }
2135c060727Ssumailyyc
214935edac4STang Haojin  class XSTopImp(wrapper: LazyModule) extends LazyRawModuleImp(wrapper) {
215a5b77de4STang Haojin    soc.XSTopPrefix.foreach { prefix =>
216a5b77de4STang Haojin      val mod = this.toNamed
217a5b77de4STang Haojin      annotate(new ChiselAnnotation {
218a5b77de4STang Haojin        def toFirrtl = NestedPrefixModulesAnnotation(mod, prefix, true)
219a5b77de4STang Haojin      })
220a5b77de4STang Haojin    }
221a5b77de4STang Haojin
222876196b7SMaxpicca-Li    FileRegisters.add("dts", dts)
223876196b7SMaxpicca-Li    FileRegisters.add("graphml", graphML)
224876196b7SMaxpicca-Li    FileRegisters.add("json", json)
225876196b7SMaxpicca-Li    FileRegisters.add("plusArgs", freechips.rocketchip.util.PlusArgArtefacts.serialize_cHeader())
2264f0a2459Swakafa
2272993c5ecSHaojin Tang    val dma = socMisc.map(m => IO(Flipped(new VerilogAXI4Record(m.dma.elts.head.params))))
2281bf9a05aSzhanglinjuan    val peripheral = IO(new VerilogAXI4Record(misc.peripheral.elts.head.params))
2292993c5ecSHaojin Tang    val memory = IO(new VerilogAXI4Record(misc.memory.elts.head.params))
23073be64b3SJiawei Lin
2314b40434cSzhanglinjuan    socMisc match {
2324b40434cSzhanglinjuan      case Some(m) =>
2332993c5ecSHaojin Tang        m.dma.elements.head._2 <> dma.get.viewAs[AXI4Bundle]
2344b40434cSzhanglinjuan        dontTouch(dma.get)
2354b40434cSzhanglinjuan      case None =>
2364b40434cSzhanglinjuan    }
2374b40434cSzhanglinjuan
2382993c5ecSHaojin Tang    memory.viewAs[AXI4Bundle] <> misc.memory.elements.head._2
23978a8cd25Szhanglinjuan    peripheral.viewAs[AXI4Bundle] <> misc.peripheral.elements.head._2
24073be64b3SJiawei Lin
2418b037849SYinan Xu    val io = IO(new Bundle {
24220957846SZihao Yu      val clock = Input(Clock())
24367ba96b4SYinan Xu      val reset = Input(AsyncReset())
24434ab1ae9SJiawei Lin      val sram_config = Input(UInt(16.W))
2458b037849SYinan Xu      val extIntrs = Input(UInt(NrExtIntr.W))
24634ab1ae9SJiawei Lin      val pll0_lock = Input(Bool())
24734ab1ae9SJiawei Lin      val pll0_ctrl = Output(Vec(6, UInt(32.W)))
248d4aca96cSlqre      val systemjtag = new Bundle {
249d4aca96cSlqre        val jtag = Flipped(new JTAGIO(hasTRSTn = false))
25067ba96b4SYinan Xu        val reset = Input(AsyncReset()) // No reset allowed on top
251d4aca96cSlqre        val mfr_id = Input(UInt(11.W))
252d4aca96cSlqre        val part_number = Input(UInt(16.W))
253d4aca96cSlqre        val version = Input(UInt(4.W))
254d4aca96cSlqre      }
25577bc15a2SYinan Xu      val debug_reset = Output(Bool())
2569e56439dSHazard      val rtc_clock = Input(Bool())
25798c71602SJiawei Lin      val cacheable_check = new TLPMAIO()
258b6900d94SYinan Xu      val riscv_halt = Output(Vec(NumCores, Bool()))
25985a8d7caSZehao Liu      val riscv_critical_error = Output(Vec(NumCores, Bool()))
2600700cab2STang Haojin      val riscv_rst_vec = Input(Vec(NumCores, UInt(soc.PAddrBits.W)))
261725e8ddcSchengguanghui      val traceCoreInterface = Vec(NumCores, new Bundle {
262725e8ddcSchengguanghui        val fromEncoder = Input(new Bundle {
263725e8ddcSchengguanghui          val enable = Bool()
264725e8ddcSchengguanghui          val stall  = Bool()
265725e8ddcSchengguanghui        })
266725e8ddcSchengguanghui        val toEncoder   = Output(new Bundle {
267725e8ddcSchengguanghui          val cause     = UInt(TraceCauseWidth.W)
268725e8ddcSchengguanghui          val tval      = UInt(TraceTvalWidth.W)
269725e8ddcSchengguanghui          val priv      = UInt(TracePrivWidth.W)
270725e8ddcSchengguanghui          val iaddr     = UInt((TraceTraceGroupNum * TraceIaddrWidth).W)
271725e8ddcSchengguanghui          val itype     = UInt((TraceTraceGroupNum * TraceItypeWidth).W)
272725e8ddcSchengguanghui          val iretire   = UInt((TraceTraceGroupNum * TraceIretireWidthCompressed).W)
273725e8ddcSchengguanghui          val ilastsize = UInt((TraceTraceGroupNum * TraceIlastsizeWidth).W)
274725e8ddcSchengguanghui        })
275725e8ddcSchengguanghui      })
2768b037849SYinan Xu    })
27767ba96b4SYinan Xu
27820957846SZihao Yu    val reset_sync = withClockAndReset(io.clock, io.reset) { ResetGen() }
27967ba96b4SYinan Xu    val jtag_reset_sync = withClockAndReset(io.systemjtag.jtag.TCK, io.systemjtag.reset) { ResetGen() }
2805c060727Ssumailyyc    val chi_openllc_opt = Option.when(enableCHI)(
28120957846SZihao Yu      withClockAndReset(io.clock, io.reset) {
2825c060727Ssumailyyc        Module(new OpenLLC()(p.alter((site, here, up) => {
283186eb48dSsumailyyc          case OpenLLCParamKey => soc.OpenLLCParamsOpt.get.copy(
284186eb48dSsumailyyc            hartIds = tiles.map(_.HartId),
285186eb48dSsumailyyc            FPGAPlatform = debugOpts.FPGAPlatform
286186eb48dSsumailyyc          )
2875c060727Ssumailyyc        })))
2885c060727Ssumailyyc      }
2895c060727Ssumailyyc    )
29067ba96b4SYinan Xu
29177bc15a2SYinan Xu    // override LazyRawModuleImp's clock and reset
29220957846SZihao Yu    childClock := io.clock
29367ba96b4SYinan Xu    childReset := reset_sync
29477bc15a2SYinan Xu
29577bc15a2SYinan Xu    // output
29677bc15a2SYinan Xu    io.debug_reset := misc.module.debug_module_io.debugIO.ndreset
29777bc15a2SYinan Xu
29877bc15a2SYinan Xu    // input
29908bf93ffSrvcoresjw    dontTouch(io)
30008bf93ffSrvcoresjw    dontTouch(memory)
30173be64b3SJiawei Lin    misc.module.ext_intrs := io.extIntrs
3029e56439dSHazard    misc.module.rtc_clock := io.rtc_clock
30334ab1ae9SJiawei Lin    misc.module.pll0_lock := io.pll0_lock
30498c71602SJiawei Lin    misc.module.cacheable_check <> io.cacheable_check
30534ab1ae9SJiawei Lin
30634ab1ae9SJiawei Lin    io.pll0_ctrl <> misc.module.pll0_ctrl
307c0bc1ee4SYinan Xu
308e156f460SHaojin Tang    val msiInfo = WireInit(0.U.asTypeOf(ValidIO(new MsiInfoBundle)))
309e156f460SHaojin Tang
310007f6122SXuan Hu
31177bc15a2SYinan Xu    for ((core, i) <- core_with_l2.zipWithIndex) {
31277bc15a2SYinan Xu      core.module.io.hartId := i.U
313e156f460SHaojin Tang      core.module.io.msiInfo := msiInfo
3143bf5eac7SXuan Hu      core.module.io.clintTime := misc.module.clintTime
315b6900d94SYinan Xu      io.riscv_halt(i) := core.module.io.cpu_halt
31685a8d7caSZehao Liu      io.riscv_critical_error(i) := core.module.io.cpu_crtical_error
3173ad9f3ddSchengguanghui      // trace Interface
3183ad9f3ddSchengguanghui      val traceInterface = core.module.io.traceCoreInterface
3193ad9f3ddSchengguanghui      traceInterface.fromEncoder := io.traceCoreInterface(i).fromEncoder
3203ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.priv := traceInterface.toEncoder.priv
3213ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.cause := traceInterface.toEncoder.trap.cause
3223ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.tval := traceInterface.toEncoder.trap.tval
3233ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.iaddr := VecInit(traceInterface.toEncoder.groups.map(_.bits.iaddr)).asUInt
3243ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.itype := VecInit(traceInterface.toEncoder.groups.map(_.bits.itype)).asUInt
3253ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.iretire := VecInit(traceInterface.toEncoder.groups.map(_.bits.iretire)).asUInt
3263ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.ilastsize := VecInit(traceInterface.toEncoder.groups.map(_.bits.ilastsize)).asUInt
3273ad9f3ddSchengguanghui
328c4b44470SGuokai Chen      core.module.io.reset_vector := io.riscv_rst_vec(i)
3295c060727Ssumailyyc    }
3305c060727Ssumailyyc
33120957846SZihao Yu    withClockAndReset(io.clock, io.reset) {
3325c060727Ssumailyyc      Option.when(enableCHI)(true.B).foreach { _ =>
3335c060727Ssumailyyc        for ((core, i) <- core_with_l2.zipWithIndex) {
3345c060727Ssumailyyc          val mmioLogger = CHILogger(s"L2[${i}]_MMIO", true)
3355c060727Ssumailyyc          val llcLogger = CHILogger(s"L2[${i}]_LLC", true)
3365c060727Ssumailyyc          dontTouch(core.module.io.chi.get)
3375c060727Ssumailyyc          bind(
3385c060727Ssumailyyc            route(
3395c060727Ssumailyyc              core.module.io.chi.get, Map((AddressSet(0x0L, 0x00007fffffffL), NumCores + i)) ++ AddressSet(0x0L,
3405c060727Ssumailyyc              0xffffffffffffL).subtract(AddressSet(0x0L, 0x00007fffffffL)).map(addr => (addr, NumCores * 2)).toMap
3415c060727Ssumailyyc            ),
3425c060727Ssumailyyc            Map((NumCores + i) -> mmioLogger.io.up, (NumCores * 2) -> llcLogger.io.up)
3435c060727Ssumailyyc          )
3445c060727Ssumailyyc          chi_mmioBridge_opt(i).get.module.io.chi.connect(mmioLogger.io.down)
3455c060727Ssumailyyc          chi_openllc_opt.get.io.rn(i) <> llcLogger.io.down
3465c060727Ssumailyyc        }
3475c060727Ssumailyyc        val memLogger = CHILogger(s"LLC_MEM", true)
3485c060727Ssumailyyc        chi_openllc_opt.get.io.sn.connect(memLogger.io.up)
3495c060727Ssumailyyc        chi_llcBridge_opt.get.module.io.chi.connect(memLogger.io.down)
3505c060727Ssumailyyc        chi_openllc_opt.get.io.nodeID := (NumCores * 2).U
351186eb48dSsumailyyc        chi_openllc_opt.foreach { l3 =>
352186eb48dSsumailyyc          l3.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr)
353186eb48dSsumailyyc        }
354186eb48dSsumailyyc        core_with_l2.zip(chi_openllc_opt.get.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) =>
355186eb48dSsumailyyc          tile.module.io.debugTopDown.l3MissMatch := l3Match
356186eb48dSsumailyyc        }
357e836c770SZhaoyang You        core_with_l2.zip(chi_openllc_opt).foreach { case (tile, l3) =>
358e836c770SZhaoyang You          tile.module.io.l3Miss := l3.io.l3Miss
359e836c770SZhaoyang You        }
36078a8cd25Szhanglinjuan      }
3618b037849SYinan Xu    }
3628b037849SYinan Xu
36334ab1ae9SJiawei Lin    if(l3cacheOpt.isEmpty || l3cacheOpt.get.rst_nodes.isEmpty){
36434ab1ae9SJiawei Lin      // tie off core soft reset
36534ab1ae9SJiawei Lin      for(node <- core_rst_nodes){
366935edac4STang Haojin        node.out.head._1 := false.B.asAsyncReset
36734ab1ae9SJiawei Lin      }
36834ab1ae9SJiawei Lin    }
36934ab1ae9SJiawei Lin
37060ebee38STang Haojin    l3cacheOpt match {
37160ebee38STang Haojin      case Some(l3) =>
3720d32f713Shappy-lx        l3.pf_recv_node match {
3730d32f713Shappy-lx          case Some(recv) =>
3740d32f713Shappy-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
3750d32f713Shappy-lx            for (i <- 0 until NumCores) {
3760d32f713Shappy-lx              when(memblock_pf_recv_nodes(i).get.in.head._1.addr_valid) {
3770d32f713Shappy-lx                l3_pf_sender_opt.get.out.head._1.addr := memblock_pf_recv_nodes(i).get.in.head._1.addr
3780d32f713Shappy-lx                l3_pf_sender_opt.get.out.head._1.l2_pf_en := memblock_pf_recv_nodes(i).get.in.head._1.l2_pf_en
3790d32f713Shappy-lx              }
3800d32f713Shappy-lx            }
38160ebee38STang Haojin          case None =>
3820d32f713Shappy-lx        }
38360ebee38STang Haojin        l3.module.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr)
38460ebee38STang Haojin        core_with_l2.zip(l3.module.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) => tile.module.io.debugTopDown.l3MissMatch := l3Match }
385e836c770SZhaoyang You        core_with_l2.foreach(_.module.io.l3Miss := l3.module.io.l3Miss)
386186eb48dSsumailyyc      case None =>
387186eb48dSsumailyyc    }
388186eb48dSsumailyyc
389186eb48dSsumailyyc    (chi_openllc_opt, l3cacheOpt) match {
390e836c770SZhaoyang You      case (None, None) =>
391e836c770SZhaoyang You        core_with_l2.foreach(_.module.io.debugTopDown.l3MissMatch := false.B)
392e836c770SZhaoyang You        core_with_l2.foreach(_.module.io.l3Miss := false.B)
393186eb48dSsumailyyc      case _ =>
39460ebee38STang Haojin    }
3950d32f713Shappy-lx
396c51f1a7bSsumailyyc    core_with_l2.zipWithIndex.foreach { case (tile, i) =>
3974b40434cSzhanglinjuan      tile.module.io.nodeID.foreach { case nodeID =>
398c51f1a7bSsumailyyc        nodeID := i.U
3994b40434cSzhanglinjuan        dontTouch(nodeID)
4004b40434cSzhanglinjuan      }
4014b40434cSzhanglinjuan    }
4024b40434cSzhanglinjuan
4033a3744e4Schengguanghui    misc.module.debug_module_io.resetCtrl.hartIsInReset := core_with_l2.map(_.module.io.hartIsInReset)
40473be64b3SJiawei Lin    misc.module.debug_module_io.clock := io.clock
40567ba96b4SYinan Xu    misc.module.debug_module_io.reset := reset_sync
406d4aca96cSlqre
40767ba96b4SYinan Xu    misc.module.debug_module_io.debugIO.reset := misc.module.reset
40820957846SZihao Yu    misc.module.debug_module_io.debugIO.clock := io.clock
40977bc15a2SYinan Xu    // TODO: delay 3 cycles?
41077bc15a2SYinan Xu    misc.module.debug_module_io.debugIO.dmactiveAck := misc.module.debug_module_io.debugIO.dmactive
411d4aca96cSlqre    // jtag connector
41273be64b3SJiawei Lin    misc.module.debug_module_io.debugIO.systemjtag.foreach { x =>
413d4aca96cSlqre      x.jtag        <> io.systemjtag.jtag
41467ba96b4SYinan Xu      x.reset       := jtag_reset_sync
415d4aca96cSlqre      x.mfr_id      := io.systemjtag.mfr_id
416d4aca96cSlqre      x.part_number := io.systemjtag.part_number
417d4aca96cSlqre      x.version     := io.systemjtag.version
418d4aca96cSlqre    }
41977bc15a2SYinan Xu
42020957846SZihao Yu    withClockAndReset(io.clock, reset_sync) {
42177bc15a2SYinan Xu      // Modules are reset one by one
42225cb35b6SJiawei Lin      // reset ----> SYNC --> {SoCMisc, L3 Cache, Cores}
4233a3744e4Schengguanghui      val resetChain = Seq(Seq(misc.module) ++ l3cacheOpt.map(_.module))
4249eee369fSKamimiao      ResetGen(resetChain, reset_sync, !debugOpts.ResetGen)
4253a3744e4Schengguanghui      // Ensure that cores could be reset when DM disable `hartReset` or l3cacheOpt.isEmpty.
4263a3744e4Schengguanghui      val dmResetReqVec = misc.module.debug_module_io.resetCtrl.hartResetReq.getOrElse(0.U.asTypeOf(Vec(core_with_l2.map(_.module).length, Bool())))
4273a3744e4Schengguanghui      val syncResetCores = if(l3cacheOpt.nonEmpty) l3cacheOpt.map(_.module).get.reset.asBool else misc.module.reset.asBool
4283a3744e4Schengguanghui      (core_with_l2.map(_.module)).zip(dmResetReqVec).map { case(core, dmResetReq) =>
4293a3744e4Schengguanghui        ResetGen(Seq(Seq(core)), (syncResetCores || dmResetReq).asAsyncReset, !debugOpts.ResetGen)
4303a3744e4Schengguanghui      }
4318b037849SYinan Xu    }
43277bc15a2SYinan Xu
4338b037849SYinan Xu  }
434935edac4STang Haojin
435935edac4STang Haojin  lazy val module = new XSTopImp(this)
4369d5a2027SYinan Xu}
4378b037849SYinan Xu
438935edac4STang Haojinobject TopMain extends App {
43951e45dbbSTang Haojin  val (config, firrtlOpts, firtoolOpts) = ArgParser.parse(args)
44093610df3SMaxpicca-Li
44193610df3SMaxpicca-Li  // tools: init to close dpi-c when in fpga
44293610df3SMaxpicca-Li  val envInFPGA = config(DebugOptionsKey).FPGAPlatform
443cacfe229STang Haojin  val enableDifftest = config(DebugOptionsKey).EnableDifftest || config(DebugOptionsKey).AlwaysBasicDiff
44462129679Swakafa  val enableChiselDB = config(DebugOptionsKey).EnableChiselDB
445047e34f9SMaxpicca-Li  val enableConstantin = config(DebugOptionsKey).EnableConstantin
446047e34f9SMaxpicca-Li  Constantin.init(enableConstantin && !envInFPGA)
44762129679Swakafa  ChiselDB.init(enableChiselDB && !envInFPGA)
44893610df3SMaxpicca-Li
449*c33deca9Sklin02  if (config(SoCParamsKey).UseXSNoCDiffTop) {
450*c33deca9Sklin02    Generator.execute(firrtlOpts, DisableMonitors(p => new XSNoCDiffTop()(p))(config), firtoolOpts)
451*c33deca9Sklin02  } else {
452720dd621STang Haojin    val soc = if (config(SoCParamsKey).UseXSNoCTop)
453720dd621STang Haojin      DisableMonitors(p => LazyModule(new XSNoCTop()(p)))(config)
454720dd621STang Haojin    else
455720dd621STang Haojin      DisableMonitors(p => LazyModule(new XSTop()(p)))(config)
456720dd621STang Haojin
45751e45dbbSTang Haojin    Generator.execute(firrtlOpts, soc.module, firtoolOpts)
4582316cea8SJiuyue Ma
4592316cea8SJiuyue Ma    // generate difftest bundles (w/o DifftestTopIO)
4602316cea8SJiuyue Ma    if (enableDifftest) {
4612316cea8SJiuyue Ma      DifftestModule.finish("XiangShan", false)
4622316cea8SJiuyue Ma    }
463*c33deca9Sklin02  }
4642316cea8SJiuyue Ma
465876196b7SMaxpicca-Li  FileRegisters.write(fileDir = "./build", filePrefix = "XSTop.")
4668b037849SYinan Xu}
467