xref: /XiangShan/src/main/scala/top/Top.scala (revision 30f35717e23156cb95b30a36db530384545b48a4)
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._
26602aa9f1Scz4eimport utility._
27*30f35717Scz4eimport utility.sram.SramBroadcastBundle
289672f0b7Swakafaimport huancun.{HCCacheParameters, HCCacheParamsKey, HuanCun, PrefetchRecv, TPmetaResp}
294b40434cSzhanglinjuanimport coupledL2.EnableCHI
305c060727Ssumailyycimport coupledL2.tl2chi.CHILogger
315c060727Ssumailyycimport openLLC.{OpenLLC, OpenLLCParamKey, OpenNCB}
325c060727Ssumailyycimport openLLC.TargetBinder._
335c060727Ssumailyycimport cc.xiangshan.openncb._
348b037849SYinan Xuimport system._
35d4aca96cSlqreimport device._
368b037849SYinan Xuimport chisel3.stage.ChiselGeneratorAnnotation
378891a219SYinan Xuimport org.chipsalliance.cde.config._
3816ae9ddcSTang Haojinimport freechips.rocketchip.devices.debug.DebugModuleKey
398b037849SYinan Xuimport freechips.rocketchip.diplomacy._
404daa5bf3SYangyu Chenimport freechips.rocketchip.tile._
418b037849SYinan Xuimport freechips.rocketchip.tilelink._
428bc90631SZehao Liuimport freechips.rocketchip.interrupts._
434b40434cSzhanglinjuanimport freechips.rocketchip.amba.axi4._
44d4aca96cSlqreimport freechips.rocketchip.jtag.JTAGIO
45a5b77de4STang Haojinimport chisel3.experimental.{annotate, ChiselAnnotation}
46a5b77de4STang Haojinimport sifive.enterprise.firrtl.NestedPrefixModulesAnnotation
475c060727Ssumailyycimport scala.collection.mutable.{Map}
48d4aca96cSlqre
49ba0bece8SKamimiaoimport difftest.common.DifftestWiring
50ba0bece8SKamimiaoimport difftest.util.Profile
51ba0bece8SKamimiao
52afcc4f2aSJiawei Linabstract class BaseXSSoc()(implicit p: Parameters) extends LazyModule
53afcc4f2aSJiawei Lin  with BindingScope
54afcc4f2aSJiawei Lin{
554b40434cSzhanglinjuan  // val misc = LazyModule(new SoCMisc())
56afcc4f2aSJiawei Lin  lazy val dts = DTS(bindingTree)
574f0a2459Swakafa  lazy val json = JSON(bindingTree)
588b037849SYinan Xu}
598b037849SYinan Xu
6073be64b3SJiawei Linclass XSTop()(implicit p: Parameters) extends BaseXSSoc() with HasSoCParameter
618b037849SYinan Xu{
624b40434cSzhanglinjuan  val nocMisc = if (enableCHI) Some(LazyModule(new MemMisc())) else None
634b40434cSzhanglinjuan  val socMisc = if (!enableCHI) Some(LazyModule(new SoCMisc())) else None
644b40434cSzhanglinjuan  val misc: MemMisc = if (enableCHI) nocMisc.get else socMisc.get
654b40434cSzhanglinjuan
66afcc4f2aSJiawei Lin  ResourceBinding {
67afcc4f2aSJiawei Lin    val width = ResourceInt(2)
68ce34d21eSJiuyue Ma    val model = "xiangshan," + os.read(os.resource / "publishVersion")
69ce34d21eSJiuyue Ma    val compatible = "freechips,rocketchip-unknown"
70afcc4f2aSJiawei Lin    Resource(ResourceAnchors.root, "model").bind(ResourceString(model))
71ce34d21eSJiuyue Ma    Resource(ResourceAnchors.root, "compat").bind(ResourceString(compatible + "-dev"))
72ce34d21eSJiuyue Ma    Resource(ResourceAnchors.soc, "compat").bind(ResourceString(compatible + "-soc"))
73afcc4f2aSJiawei Lin    Resource(ResourceAnchors.root, "width").bind(width)
74afcc4f2aSJiawei Lin    Resource(ResourceAnchors.soc, "width").bind(width)
75afcc4f2aSJiawei Lin    Resource(ResourceAnchors.cpus, "width").bind(ResourceInt(1))
76afcc4f2aSJiawei Lin    def bindManagers(xbar: TLNexusNode) = {
77afcc4f2aSJiawei Lin      ManagerUnification(xbar.edges.in.head.manager.managers).foreach{ manager =>
78afcc4f2aSJiawei Lin        manager.resources.foreach(r => r.bind(manager.toResource))
79afcc4f2aSJiawei Lin      }
80afcc4f2aSJiawei Lin    }
8178a8cd25Szhanglinjuan    if (!enableCHI) {
821bf9a05aSzhanglinjuan      bindManagers(misc.l3_xbar.get.asInstanceOf[TLNexusNode])
8378a8cd25Szhanglinjuan      bindManagers(misc.peripheralXbar.get.asInstanceOf[TLNexusNode])
8478a8cd25Szhanglinjuan    }
85afcc4f2aSJiawei Lin  }
868b037849SYinan Xu
872225d46eSJiawei Lin  println(s"FPGASoC cores: $NumCores banks: $L3NBanks block size: $L3BlockSize bus size: $L3OuterBusWidth")
888b037849SYinan Xu
8934ab1ae9SJiawei Lin  val core_with_l2 = tiles.map(coreParams =>
90bb2f3f51STang Haojin    LazyModule(new XSTile()(p.alter((site, here, up) => {
912225d46eSJiawei Lin      case XSCoreParamsKey => coreParams
92bb2f3f51STang Haojin      case PerfCounterOptionsKey => up(PerfCounterOptionsKey).copy(perfDBHartID = coreParams.HartId)
932225d46eSJiawei Lin    })))
942225d46eSJiawei Lin  )
958b037849SYinan Xu
9634ab1ae9SJiawei Lin  val l3cacheOpt = soc.L3CacheParamsOpt.map(l3param =>
9734ab1ae9SJiawei Lin    LazyModule(new HuanCun()(new Config((_, _, _) => {
9834f38695STang Haojin      case HCCacheParamsKey => l3param.copy(
9934f38695STang Haojin        hartIds = tiles.map(_.HartId),
10034f38695STang Haojin        FPGAPlatform = debugOpts.FPGAPlatform
10134f38695STang Haojin      )
1024daa5bf3SYangyu Chen      case MaxHartIdBits => p(MaxHartIdBits)
103bb2f3f51STang Haojin      case LogUtilsOptionsKey => p(LogUtilsOptionsKey)
104bb2f3f51STang Haojin      case PerfCounterOptionsKey => p(PerfCounterOptionsKey)
10534ab1ae9SJiawei Lin    })))
10634ab1ae9SJiawei Lin  )
10734ab1ae9SJiawei Lin
1085c060727Ssumailyyc  val chi_llcBridge_opt = Option.when(enableCHI)(
1095c060727Ssumailyyc    LazyModule(new OpenNCB()(p.alter((site, here, up) => {
1105c060727Ssumailyyc      case NCBParametersKey => new NCBParameters(
111af532009Ssumailyyc        outstandingDepth    = 64,
1125c060727Ssumailyyc        axiMasterOrder      = EnumAXIMasterOrder.WriteAddress,
1135c060727Ssumailyyc        readCompDMT         = false,
1145c060727Ssumailyyc        writeCancelable     = false,
1155c060727Ssumailyyc        writeNoError        = true,
116881e32f5SZifei Zhang        axiBurstAlwaysIncr  = true,
117881e32f5SZifei Zhang        chiDataCheck        = EnumCHIDataCheck.OddParity
1185c060727Ssumailyyc      )
1195c060727Ssumailyyc    })))
1205c060727Ssumailyyc  )
1215c060727Ssumailyyc
1225c060727Ssumailyyc  val chi_mmioBridge_opt = Seq.fill(NumCores)(Option.when(enableCHI)(
1235c060727Ssumailyyc    LazyModule(new OpenNCB()(p.alter((site, here, up) => {
1245c060727Ssumailyyc      case NCBParametersKey => new NCBParameters(
125af532009Ssumailyyc        outstandingDepth            = 32,
1265c060727Ssumailyyc        axiMasterOrder              = EnumAXIMasterOrder.None,
1275c060727Ssumailyyc        readCompDMT                 = false,
1285c060727Ssumailyyc        writeCancelable             = false,
1295c060727Ssumailyyc        writeNoError                = true,
1305c060727Ssumailyyc        asEndpoint                  = false,
1315c060727Ssumailyyc        acceptOrderEndpoint         = true,
1325c060727Ssumailyyc        acceptMemAttrDevice         = true,
1335c060727Ssumailyyc        readReceiptAfterAcception   = true,
134881e32f5SZifei Zhang        axiBurstAlwaysIncr          = true,
135881e32f5SZifei Zhang        chiDataCheck                = EnumCHIDataCheck.OddParity
1365c060727Ssumailyyc      )
1375c060727Ssumailyyc    })))
1385c060727Ssumailyyc  ))
13978a8cd25Szhanglinjuan
14078a8cd25Szhanglinjuan  // receive all prefetch req from cores
1410d32f713Shappy-lx  val memblock_pf_recv_nodes: Seq[Option[BundleBridgeSink[PrefetchRecv]]] = core_with_l2.map(_.core_l3_pf_port).map{
1420d32f713Shappy-lx    x => x.map(_ => BundleBridgeSink(Some(() => new PrefetchRecv)))
1430d32f713Shappy-lx  }
1440d32f713Shappy-lx
1450d32f713Shappy-lx  val l3_pf_sender_opt = soc.L3CacheParamsOpt.getOrElse(HCCacheParameters()).prefetch match {
1460d32f713Shappy-lx    case Some(pf) => Some(BundleBridgeSource(() => new PrefetchRecv))
1470d32f713Shappy-lx    case None => None
1480d32f713Shappy-lx  }
1498bc90631SZehao Liu  val nmiIntNode = IntSourceNode(IntSourcePortSimple(1, NumCores, (new NonmaskableInterruptIO).elements.size))
1508bc90631SZehao Liu  val nmi = InModuleBody(nmiIntNode.makeIOs())
1510d32f713Shappy-lx
1528b037849SYinan Xu  for (i <- 0 until NumCores) {
1534e12f40bSzhanglinjuan    core_with_l2(i).clint_int_node := misc.clint.intnode
1544e12f40bSzhanglinjuan    core_with_l2(i).plic_int_node :*= misc.plic.intnode
1554e12f40bSzhanglinjuan    core_with_l2(i).debug_int_node := misc.debugModule.debug.dmOuter.dmOuter.intnode
1568bc90631SZehao Liu    core_with_l2(i).nmi_int_node := nmiIntNode
157cac098b4SJiawei Lin    misc.plic.intnode := IntBuffer() := core_with_l2(i).beu_int_source
1584b40434cSzhanglinjuan    if (!enableCHI) {
15978a8cd25Szhanglinjuan      misc.peripheral_ports.get(i) := core_with_l2(i).tl_uncache
1604b40434cSzhanglinjuan    }
16178a8cd25Szhanglinjuan    core_with_l2(i).memory_port.foreach(port => (misc.core_to_l3_ports.get)(i) :=* port)
1620d32f713Shappy-lx    memblock_pf_recv_nodes(i).map(recv => {
1630d32f713Shappy-lx      println(s"Connecting Core_${i}'s L1 pf source to L3!")
1640d32f713Shappy-lx      recv := core_with_l2(i).core_l3_pf_port.get
1650d32f713Shappy-lx    })
16616ae9ddcSTang Haojin    misc.debugModuleXbarOpt.foreach { debugModuleXbar =>
16716ae9ddcSTang Haojin      // SeperateTlBus can only be connected to DebugModule now in non-XSNoCTop environment
16816ae9ddcSTang Haojin      println(s"SeparateDM: ${SeperateDM}")
16916ae9ddcSTang Haojin      println(s"misc.debugModuleXbarOpt: ${misc.debugModuleXbarOpt}")
17016ae9ddcSTang Haojin      require(core_with_l2(i).sep_tl_opt.isDefined)
17116ae9ddcSTang Haojin      require(SeperateTLBusRanges.size == 1)
17216ae9ddcSTang Haojin      require(SeperateTLBusRanges.head == p(DebugModuleKey).get.address)
17316ae9ddcSTang Haojin      debugModuleXbar := core_with_l2(i).sep_tl_opt.get
17416ae9ddcSTang Haojin    }
1758b037849SYinan Xu  }
1768b037849SYinan Xu
17778a8cd25Szhanglinjuan  l3cacheOpt.map(_.ctlnode.map(_ := misc.peripheralXbar.get))
17838005240SJiawei Lin  l3cacheOpt.map(_.intnode.map(int => {
17938005240SJiawei Lin    misc.plic.intnode := IntBuffer() := int
18038005240SJiawei Lin  }))
18134ab1ae9SJiawei Lin
18234ab1ae9SJiawei Lin  val core_rst_nodes = if(l3cacheOpt.nonEmpty && l3cacheOpt.get.rst_nodes.nonEmpty){
18334ab1ae9SJiawei Lin    l3cacheOpt.get.rst_nodes.get
18434ab1ae9SJiawei Lin  } else {
1858a167be7SHaojin Tang    core_with_l2.map(_ => BundleBridgeSource(() => Reset()))
18634ab1ae9SJiawei Lin  }
18734ab1ae9SJiawei Lin
18834ab1ae9SJiawei Lin  core_rst_nodes.zip(core_with_l2.map(_.core_reset_sink)).foreach({
18934ab1ae9SJiawei Lin    case (source, sink) =>  sink := source
19034ab1ae9SJiawei Lin  })
191a1ea7f76SJiawei Lin
1924f94c0c6SJiawei Lin  l3cacheOpt match {
1934f94c0c6SJiawei Lin    case Some(l3) =>
1941bf9a05aSzhanglinjuan      misc.l3_out :*= l3.node :*= misc.l3_banked_xbar.get
1950d32f713Shappy-lx      l3.pf_recv_node.map(recv => {
1960d32f713Shappy-lx        println("Connecting L1 prefetcher to L3!")
1970d32f713Shappy-lx        recv := l3_pf_sender_opt.get
1980d32f713Shappy-lx      })
1999672f0b7Swakafa      l3.tpmeta_recv_node.foreach(recv => {
2009672f0b7Swakafa        for ((core, i) <- core_with_l2.zipWithIndex) {
2019672f0b7Swakafa          println(s"Connecting core_$i\'s L2 TPmeta request to L3!")
2029672f0b7Swakafa          recv := core.core_l3_tpmeta_source_port.get
2039672f0b7Swakafa        }
2049672f0b7Swakafa      })
2059672f0b7Swakafa      l3.tpmeta_send_node.foreach(send => {
2069672f0b7Swakafa        val broadcast = LazyModule(new ValidIOBroadcast[TPmetaResp]())
2079672f0b7Swakafa        broadcast.node := send
2089672f0b7Swakafa        for ((core, i) <- core_with_l2.zipWithIndex) {
2099672f0b7Swakafa          println(s"Connecting core_$i\'s L2 TPmeta response to L3!")
2109672f0b7Swakafa          core.core_l3_tpmeta_sink_port.get := broadcast.node
2119672f0b7Swakafa        }
2129672f0b7Swakafa      })
21373be64b3SJiawei Lin    case None =>
2149d5a2027SYinan Xu  }
2158b037849SYinan Xu
2165c060727Ssumailyyc  chi_llcBridge_opt match {
2175c060727Ssumailyyc    case Some(ncb) =>
2185c060727Ssumailyyc      misc.soc_xbar.get := ncb.axi4node
21978a8cd25Szhanglinjuan    case None =>
22078a8cd25Szhanglinjuan  }
22178a8cd25Szhanglinjuan
2225c060727Ssumailyyc  chi_mmioBridge_opt.foreach { e =>
2235c060727Ssumailyyc    e match {
2245c060727Ssumailyyc      case Some(ncb) =>
2255c060727Ssumailyyc        misc.soc_xbar.get := ncb.axi4node
2265c060727Ssumailyyc      case None =>
2275c060727Ssumailyyc    }
2285c060727Ssumailyyc  }
2295c060727Ssumailyyc
230935edac4STang Haojin  class XSTopImp(wrapper: LazyModule) extends LazyRawModuleImp(wrapper) {
231a5b77de4STang Haojin    soc.XSTopPrefix.foreach { prefix =>
232a5b77de4STang Haojin      val mod = this.toNamed
233a5b77de4STang Haojin      annotate(new ChiselAnnotation {
234a5b77de4STang Haojin        def toFirrtl = NestedPrefixModulesAnnotation(mod, prefix, true)
235a5b77de4STang Haojin      })
236a5b77de4STang Haojin    }
237a5b77de4STang Haojin
238876196b7SMaxpicca-Li    FileRegisters.add("dts", dts)
239876196b7SMaxpicca-Li    FileRegisters.add("graphml", graphML)
240876196b7SMaxpicca-Li    FileRegisters.add("json", json)
241876196b7SMaxpicca-Li    FileRegisters.add("plusArgs", freechips.rocketchip.util.PlusArgArtefacts.serialize_cHeader())
2424f0a2459Swakafa
2432993c5ecSHaojin Tang    val dma = socMisc.map(m => IO(Flipped(new VerilogAXI4Record(m.dma.elts.head.params))))
2441bf9a05aSzhanglinjuan    val peripheral = IO(new VerilogAXI4Record(misc.peripheral.elts.head.params))
2452993c5ecSHaojin Tang    val memory = IO(new VerilogAXI4Record(misc.memory.elts.head.params))
24673be64b3SJiawei Lin
2474b40434cSzhanglinjuan    socMisc match {
2484b40434cSzhanglinjuan      case Some(m) =>
2492993c5ecSHaojin Tang        m.dma.elements.head._2 <> dma.get.viewAs[AXI4Bundle]
2504b40434cSzhanglinjuan        dontTouch(dma.get)
2514b40434cSzhanglinjuan      case None =>
2524b40434cSzhanglinjuan    }
2534b40434cSzhanglinjuan
2542993c5ecSHaojin Tang    memory.viewAs[AXI4Bundle] <> misc.memory.elements.head._2
25578a8cd25Szhanglinjuan    peripheral.viewAs[AXI4Bundle] <> misc.peripheral.elements.head._2
25673be64b3SJiawei Lin
2578b037849SYinan Xu    val io = IO(new Bundle {
25820957846SZihao Yu      val clock = Input(Clock())
25967ba96b4SYinan Xu      val reset = Input(AsyncReset())
26034ab1ae9SJiawei Lin      val sram_config = Input(UInt(16.W))
2618b037849SYinan Xu      val extIntrs = Input(UInt(NrExtIntr.W))
26234ab1ae9SJiawei Lin      val pll0_lock = Input(Bool())
26334ab1ae9SJiawei Lin      val pll0_ctrl = Output(Vec(6, UInt(32.W)))
264d4aca96cSlqre      val systemjtag = new Bundle {
265d4aca96cSlqre        val jtag = Flipped(new JTAGIO(hasTRSTn = false))
26667ba96b4SYinan Xu        val reset = Input(AsyncReset()) // No reset allowed on top
267d4aca96cSlqre        val mfr_id = Input(UInt(11.W))
268d4aca96cSlqre        val part_number = Input(UInt(16.W))
269d4aca96cSlqre        val version = Input(UInt(4.W))
270d4aca96cSlqre      }
27177bc15a2SYinan Xu      val debug_reset = Output(Bool())
2729e56439dSHazard      val rtc_clock = Input(Bool())
27398c71602SJiawei Lin      val cacheable_check = new TLPMAIO()
274b6900d94SYinan Xu      val riscv_halt = Output(Vec(NumCores, Bool()))
27585a8d7caSZehao Liu      val riscv_critical_error = Output(Vec(NumCores, Bool()))
2760700cab2STang Haojin      val riscv_rst_vec = Input(Vec(NumCores, UInt(soc.PAddrBits.W)))
277725e8ddcSchengguanghui      val traceCoreInterface = Vec(NumCores, new Bundle {
278725e8ddcSchengguanghui        val fromEncoder = Input(new Bundle {
279725e8ddcSchengguanghui          val enable = Bool()
280725e8ddcSchengguanghui          val stall  = Bool()
281725e8ddcSchengguanghui        })
282725e8ddcSchengguanghui        val toEncoder   = Output(new Bundle {
283725e8ddcSchengguanghui          val cause     = UInt(TraceCauseWidth.W)
284725e8ddcSchengguanghui          val tval      = UInt(TraceTvalWidth.W)
285725e8ddcSchengguanghui          val priv      = UInt(TracePrivWidth.W)
286725e8ddcSchengguanghui          val iaddr     = UInt((TraceTraceGroupNum * TraceIaddrWidth).W)
287725e8ddcSchengguanghui          val itype     = UInt((TraceTraceGroupNum * TraceItypeWidth).W)
288725e8ddcSchengguanghui          val iretire   = UInt((TraceTraceGroupNum * TraceIretireWidthCompressed).W)
289725e8ddcSchengguanghui          val ilastsize = UInt((TraceTraceGroupNum * TraceIlastsizeWidth).W)
290725e8ddcSchengguanghui        })
291725e8ddcSchengguanghui      })
2928b037849SYinan Xu    })
29367ba96b4SYinan Xu
29420957846SZihao Yu    val reset_sync = withClockAndReset(io.clock, io.reset) { ResetGen() }
29567ba96b4SYinan Xu    val jtag_reset_sync = withClockAndReset(io.systemjtag.jtag.TCK, io.systemjtag.reset) { ResetGen() }
2965c060727Ssumailyyc    val chi_openllc_opt = Option.when(enableCHI)(
29720957846SZihao Yu      withClockAndReset(io.clock, io.reset) {
2985c060727Ssumailyyc        Module(new OpenLLC()(p.alter((site, here, up) => {
299186eb48dSsumailyyc          case OpenLLCParamKey => soc.OpenLLCParamsOpt.get.copy(
300186eb48dSsumailyyc            hartIds = tiles.map(_.HartId),
301186eb48dSsumailyyc            FPGAPlatform = debugOpts.FPGAPlatform
302186eb48dSsumailyyc          )
3035c060727Ssumailyyc        })))
3045c060727Ssumailyyc      }
3055c060727Ssumailyyc    )
30667ba96b4SYinan Xu
30777bc15a2SYinan Xu    // override LazyRawModuleImp's clock and reset
30820957846SZihao Yu    childClock := io.clock
30967ba96b4SYinan Xu    childReset := reset_sync
31077bc15a2SYinan Xu
31177bc15a2SYinan Xu    // output
31277bc15a2SYinan Xu    io.debug_reset := misc.module.debug_module_io.debugIO.ndreset
31377bc15a2SYinan Xu
31477bc15a2SYinan Xu    // input
31508bf93ffSrvcoresjw    dontTouch(io)
31608bf93ffSrvcoresjw    dontTouch(memory)
31773be64b3SJiawei Lin    misc.module.ext_intrs := io.extIntrs
3189e56439dSHazard    misc.module.rtc_clock := io.rtc_clock
31934ab1ae9SJiawei Lin    misc.module.pll0_lock := io.pll0_lock
32098c71602SJiawei Lin    misc.module.cacheable_check <> io.cacheable_check
32134ab1ae9SJiawei Lin
32234ab1ae9SJiawei Lin    io.pll0_ctrl <> misc.module.pll0_ctrl
323c0bc1ee4SYinan Xu
3248cfc24b2STang Haojin    val msiInfo = WireInit(0.U.asTypeOf(ValidIO(UInt(soc.IMSICParams.MSI_INFO_WIDTH.W))))
325e156f460SHaojin Tang
326007f6122SXuan Hu
32777bc15a2SYinan Xu    for ((core, i) <- core_with_l2.zipWithIndex) {
32877bc15a2SYinan Xu      core.module.io.hartId := i.U
329e156f460SHaojin Tang      core.module.io.msiInfo := msiInfo
3303bf5eac7SXuan Hu      core.module.io.clintTime := misc.module.clintTime
331b6900d94SYinan Xu      io.riscv_halt(i) := core.module.io.cpu_halt
33285a8d7caSZehao Liu      io.riscv_critical_error(i) := core.module.io.cpu_crtical_error
3333ad9f3ddSchengguanghui      // trace Interface
3343ad9f3ddSchengguanghui      val traceInterface = core.module.io.traceCoreInterface
3353ad9f3ddSchengguanghui      traceInterface.fromEncoder := io.traceCoreInterface(i).fromEncoder
3363ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.priv := traceInterface.toEncoder.priv
3373ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.cause := traceInterface.toEncoder.trap.cause
3383ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.tval := traceInterface.toEncoder.trap.tval
3393ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.iaddr := VecInit(traceInterface.toEncoder.groups.map(_.bits.iaddr)).asUInt
3403ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.itype := VecInit(traceInterface.toEncoder.groups.map(_.bits.itype)).asUInt
3413ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.iretire := VecInit(traceInterface.toEncoder.groups.map(_.bits.iretire)).asUInt
3423ad9f3ddSchengguanghui      io.traceCoreInterface(i).toEncoder.ilastsize := VecInit(traceInterface.toEncoder.groups.map(_.bits.ilastsize)).asUInt
3433ad9f3ddSchengguanghui
344*30f35717Scz4e      core.module.io.dft.foreach(dontTouch(_) := DontCare)
345*30f35717Scz4e      core.module.io.dft_reset.foreach(dontTouch(_) := DontCare)
346c4b44470SGuokai Chen      core.module.io.reset_vector := io.riscv_rst_vec(i)
3475c060727Ssumailyyc    }
3485c060727Ssumailyyc
34920957846SZihao Yu    withClockAndReset(io.clock, io.reset) {
3505c060727Ssumailyyc      Option.when(enableCHI)(true.B).foreach { _ =>
3515c060727Ssumailyyc        for ((core, i) <- core_with_l2.zipWithIndex) {
3525c060727Ssumailyyc          val mmioLogger = CHILogger(s"L2[${i}]_MMIO", true)
3535c060727Ssumailyyc          val llcLogger = CHILogger(s"L2[${i}]_LLC", true)
3545c060727Ssumailyyc          dontTouch(core.module.io.chi.get)
3555c060727Ssumailyyc          bind(
3565c060727Ssumailyyc            route(
3575c060727Ssumailyyc              core.module.io.chi.get, Map((AddressSet(0x0L, 0x00007fffffffL), NumCores + i)) ++ AddressSet(0x0L,
3585c060727Ssumailyyc              0xffffffffffffL).subtract(AddressSet(0x0L, 0x00007fffffffL)).map(addr => (addr, NumCores * 2)).toMap
3595c060727Ssumailyyc            ),
3605c060727Ssumailyyc            Map((NumCores + i) -> mmioLogger.io.up, (NumCores * 2) -> llcLogger.io.up)
3615c060727Ssumailyyc          )
3625c060727Ssumailyyc          chi_mmioBridge_opt(i).get.module.io.chi.connect(mmioLogger.io.down)
3635c060727Ssumailyyc          chi_openllc_opt.get.io.rn(i) <> llcLogger.io.down
364881e32f5SZifei Zhang          require(core.module.io.chi.get.getWidth == llcLogger.io.up.getWidth)
365881e32f5SZifei Zhang          require(llcLogger.io.down.getWidth == chi_openllc_opt.get.io.rn(i).getWidth)
3665c060727Ssumailyyc        }
3675c060727Ssumailyyc        val memLogger = CHILogger(s"LLC_MEM", true)
3685c060727Ssumailyyc        chi_openllc_opt.get.io.sn.connect(memLogger.io.up)
3695c060727Ssumailyyc        chi_llcBridge_opt.get.module.io.chi.connect(memLogger.io.down)
3705c060727Ssumailyyc        chi_openllc_opt.get.io.nodeID := (NumCores * 2).U
371186eb48dSsumailyyc        chi_openllc_opt.foreach { l3 =>
372186eb48dSsumailyyc          l3.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr)
373186eb48dSsumailyyc        }
374186eb48dSsumailyyc        core_with_l2.zip(chi_openllc_opt.get.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) =>
375186eb48dSsumailyyc          tile.module.io.debugTopDown.l3MissMatch := l3Match
376186eb48dSsumailyyc        }
377aa340261SAnzo        core_with_l2.map(_.module.io.l3Miss := (if (chi_openllc_opt.nonEmpty) chi_openllc_opt.get.io.l3Miss else false.B))
37878a8cd25Szhanglinjuan      }
3798b037849SYinan Xu    }
3808b037849SYinan Xu
38134ab1ae9SJiawei Lin    if(l3cacheOpt.isEmpty || l3cacheOpt.get.rst_nodes.isEmpty){
38234ab1ae9SJiawei Lin      // tie off core soft reset
38334ab1ae9SJiawei Lin      for(node <- core_rst_nodes){
384935edac4STang Haojin        node.out.head._1 := false.B.asAsyncReset
38534ab1ae9SJiawei Lin      }
38634ab1ae9SJiawei Lin    }
38734ab1ae9SJiawei Lin
38860ebee38STang Haojin    l3cacheOpt match {
38960ebee38STang Haojin      case Some(l3) =>
3900d32f713Shappy-lx        l3.pf_recv_node match {
3910d32f713Shappy-lx          case Some(recv) =>
3920d32f713Shappy-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
3930d32f713Shappy-lx            for (i <- 0 until NumCores) {
3940d32f713Shappy-lx              when(memblock_pf_recv_nodes(i).get.in.head._1.addr_valid) {
3950d32f713Shappy-lx                l3_pf_sender_opt.get.out.head._1.addr := memblock_pf_recv_nodes(i).get.in.head._1.addr
3960d32f713Shappy-lx                l3_pf_sender_opt.get.out.head._1.l2_pf_en := memblock_pf_recv_nodes(i).get.in.head._1.l2_pf_en
3970d32f713Shappy-lx              }
3980d32f713Shappy-lx            }
39960ebee38STang Haojin          case None =>
4000d32f713Shappy-lx        }
40160ebee38STang Haojin        l3.module.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr)
40260ebee38STang Haojin        core_with_l2.zip(l3.module.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) => tile.module.io.debugTopDown.l3MissMatch := l3Match }
403e836c770SZhaoyang You        core_with_l2.foreach(_.module.io.l3Miss := l3.module.io.l3Miss)
404186eb48dSsumailyyc      case None =>
405186eb48dSsumailyyc    }
406186eb48dSsumailyyc
407186eb48dSsumailyyc    (chi_openllc_opt, l3cacheOpt) match {
408e836c770SZhaoyang You      case (None, None) =>
409e836c770SZhaoyang You        core_with_l2.foreach(_.module.io.debugTopDown.l3MissMatch := false.B)
410e836c770SZhaoyang You        core_with_l2.foreach(_.module.io.l3Miss := false.B)
411186eb48dSsumailyyc      case _ =>
41260ebee38STang Haojin    }
4130d32f713Shappy-lx
414c51f1a7bSsumailyyc    core_with_l2.zipWithIndex.foreach { case (tile, i) =>
4154b40434cSzhanglinjuan      tile.module.io.nodeID.foreach { case nodeID =>
416c51f1a7bSsumailyyc        nodeID := i.U
4174b40434cSzhanglinjuan        dontTouch(nodeID)
4184b40434cSzhanglinjuan      }
4194b40434cSzhanglinjuan    }
4204b40434cSzhanglinjuan
4213a3744e4Schengguanghui    misc.module.debug_module_io.resetCtrl.hartIsInReset := core_with_l2.map(_.module.io.hartIsInReset)
42273be64b3SJiawei Lin    misc.module.debug_module_io.clock := io.clock
42367ba96b4SYinan Xu    misc.module.debug_module_io.reset := reset_sync
424d4aca96cSlqre
42567ba96b4SYinan Xu    misc.module.debug_module_io.debugIO.reset := misc.module.reset
42620957846SZihao Yu    misc.module.debug_module_io.debugIO.clock := io.clock
42777bc15a2SYinan Xu    // TODO: delay 3 cycles?
42877bc15a2SYinan Xu    misc.module.debug_module_io.debugIO.dmactiveAck := misc.module.debug_module_io.debugIO.dmactive
429d4aca96cSlqre    // jtag connector
43073be64b3SJiawei Lin    misc.module.debug_module_io.debugIO.systemjtag.foreach { x =>
431d4aca96cSlqre      x.jtag        <> io.systemjtag.jtag
43267ba96b4SYinan Xu      x.reset       := jtag_reset_sync
433d4aca96cSlqre      x.mfr_id      := io.systemjtag.mfr_id
434d4aca96cSlqre      x.part_number := io.systemjtag.part_number
435d4aca96cSlqre      x.version     := io.systemjtag.version
436d4aca96cSlqre    }
43777bc15a2SYinan Xu
43820957846SZihao Yu    withClockAndReset(io.clock, reset_sync) {
43977bc15a2SYinan Xu      // Modules are reset one by one
44025cb35b6SJiawei Lin      // reset ----> SYNC --> {SoCMisc, L3 Cache, Cores}
4413a3744e4Schengguanghui      val resetChain = Seq(Seq(misc.module) ++ l3cacheOpt.map(_.module))
4429eee369fSKamimiao      ResetGen(resetChain, reset_sync, !debugOpts.ResetGen)
4433a3744e4Schengguanghui      // Ensure that cores could be reset when DM disable `hartReset` or l3cacheOpt.isEmpty.
4443a3744e4Schengguanghui      val dmResetReqVec = misc.module.debug_module_io.resetCtrl.hartResetReq.getOrElse(0.U.asTypeOf(Vec(core_with_l2.map(_.module).length, Bool())))
4453a3744e4Schengguanghui      val syncResetCores = if(l3cacheOpt.nonEmpty) l3cacheOpt.map(_.module).get.reset.asBool else misc.module.reset.asBool
4463a3744e4Schengguanghui      (core_with_l2.map(_.module)).zip(dmResetReqVec).map { case(core, dmResetReq) =>
4473a3744e4Schengguanghui        ResetGen(Seq(Seq(core)), (syncResetCores || dmResetReq).asAsyncReset, !debugOpts.ResetGen)
4483a3744e4Schengguanghui      }
4498b037849SYinan Xu    }
45077bc15a2SYinan Xu
4518b037849SYinan Xu  }
452935edac4STang Haojin
453935edac4STang Haojin  lazy val module = new XSTopImp(this)
4549d5a2027SYinan Xu}
4558b037849SYinan Xu
456ba0bece8SKamimiaoclass XSTileDiffTop(implicit p: Parameters) extends Module {
457ba0bece8SKamimiao  override val desiredName: String = "XSDiffTop"
458ba0bece8SKamimiao  val l_soc = LazyModule(new XSTop())
459ba0bece8SKamimiao  val soc = Module(l_soc.module)
460ba0bece8SKamimiao
461ba0bece8SKamimiao  // Expose XSTop IOs outside, i.e. io
462ba0bece8SKamimiao  def exposeIO(data: Data, name: String): Unit = {
463ba0bece8SKamimiao    val dummy = IO(chiselTypeOf(data)).suggestName(name)
464ba0bece8SKamimiao    dummy <> data
465ba0bece8SKamimiao  }
466ba0bece8SKamimiao  def exposeOptionIO(data: Option[Data], name: String): Unit = {
467ba0bece8SKamimiao    if (data.isDefined) {
468ba0bece8SKamimiao      val dummy = IO(chiselTypeOf(data.get)).suggestName(name)
469ba0bece8SKamimiao      dummy <> data.get
470ba0bece8SKamimiao    }
471ba0bece8SKamimiao  }
472ba0bece8SKamimiao  exposeIO(l_soc.nmi,"nmi")
473ba0bece8SKamimiao  exposeIO(soc.memory, "memory")
474ba0bece8SKamimiao  exposeIO(soc.peripheral,"peripheral")
475ba0bece8SKamimiao  exposeIO(soc.io,"io")
476ba0bece8SKamimiao  exposeOptionIO(soc.dma, "dma")
477ba0bece8SKamimiao
478ba0bece8SKamimiao  DifftestWiring.createAndConnectExtraIOs()
479ba0bece8SKamimiao  Profile.generateJson("XiangShan")
480ba0bece8SKamimiao}
481ba0bece8SKamimiao
482935edac4STang Haojinobject TopMain extends App {
48351e45dbbSTang Haojin  val (config, firrtlOpts, firtoolOpts) = ArgParser.parse(args)
48493610df3SMaxpicca-Li
48593610df3SMaxpicca-Li  // tools: init to close dpi-c when in fpga
48693610df3SMaxpicca-Li  val envInFPGA = config(DebugOptionsKey).FPGAPlatform
487cacfe229STang Haojin  val enableDifftest = config(DebugOptionsKey).EnableDifftest || config(DebugOptionsKey).AlwaysBasicDiff
48862129679Swakafa  val enableChiselDB = config(DebugOptionsKey).EnableChiselDB
489047e34f9SMaxpicca-Li  val enableConstantin = config(DebugOptionsKey).EnableConstantin
490047e34f9SMaxpicca-Li  Constantin.init(enableConstantin && !envInFPGA)
49162129679Swakafa  ChiselDB.init(enableChiselDB && !envInFPGA)
49293610df3SMaxpicca-Li
493c33deca9Sklin02  if (config(SoCParamsKey).UseXSNoCDiffTop) {
494c33deca9Sklin02    Generator.execute(firrtlOpts, DisableMonitors(p => new XSNoCDiffTop()(p))(config), firtoolOpts)
495ba0bece8SKamimiao  } else if (config(SoCParamsKey).UseXSTileDiffTop) {
496ba0bece8SKamimiao    Generator.execute(firrtlOpts, DisableMonitors(p => new XSTileDiffTop()(p))(config), firtoolOpts)
497c33deca9Sklin02  } else {
498720dd621STang Haojin    val soc = if (config(SoCParamsKey).UseXSNoCTop)
499720dd621STang Haojin      DisableMonitors(p => LazyModule(new XSNoCTop()(p)))(config)
500720dd621STang Haojin    else
501720dd621STang Haojin      DisableMonitors(p => LazyModule(new XSTop()(p)))(config)
502720dd621STang Haojin
50351e45dbbSTang Haojin    Generator.execute(firrtlOpts, soc.module, firtoolOpts)
5042316cea8SJiuyue Ma
5052316cea8SJiuyue Ma    // generate difftest bundles (w/o DifftestTopIO)
5062316cea8SJiuyue Ma    if (enableDifftest) {
5072316cea8SJiuyue Ma      DifftestModule.finish("XiangShan", false)
5082316cea8SJiuyue Ma    }
509c33deca9Sklin02  }
5102316cea8SJiuyue Ma
511876196b7SMaxpicca-Li  FileRegisters.write(fileDir = "./build", filePrefix = "XSTop.")
5128b037849SYinan Xu}
513