xref: /XiangShan/src/main/scala/top/Top.scala (revision a38d1eab87777ed93b417106a7dfd58a062cee18)
1/***************************************************************************************
2* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC)
3* Copyright (c) 2020-2024 Institute of Computing Technology, Chinese Academy of Sciences
4* Copyright (c) 2020-2021 Peng Cheng Laboratory
5*
6* XiangShan is licensed under Mulan PSL v2.
7* You can use this software according to the terms and conditions of the Mulan PSL v2.
8* You may obtain a copy of Mulan PSL v2 at:
9*          http://license.coscl.org.cn/MulanPSL2
10*
11* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
12* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
13* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
14*
15* See the Mulan PSL v2 for more details.
16***************************************************************************************/
17
18package top
19
20import chisel3._
21import chisel3.util._
22import chisel3.experimental.dataview._
23import difftest.DifftestModule
24import xiangshan._
25import utils._
26import huancun.{HCCacheParameters, HCCacheParamsKey, HuanCun, PrefetchRecv, TPmetaResp}
27import coupledL2.EnableCHI
28import coupledL2.tl2chi.CHILogger
29import openLLC.{OpenLLC, OpenLLCParamKey, OpenNCB}
30import openLLC.TargetBinder._
31import cc.xiangshan.openncb._
32import utility._
33import system._
34import device._
35import chisel3.stage.ChiselGeneratorAnnotation
36import org.chipsalliance.cde.config._
37import freechips.rocketchip.diplomacy._
38import freechips.rocketchip.tile._
39import freechips.rocketchip.tilelink._
40import freechips.rocketchip.interrupts._
41import freechips.rocketchip.amba.axi4._
42import freechips.rocketchip.jtag.JTAGIO
43import chisel3.experimental.{annotate, ChiselAnnotation}
44import sifive.enterprise.firrtl.NestedPrefixModulesAnnotation
45import scala.collection.mutable.{Map}
46
47abstract class BaseXSSoc()(implicit p: Parameters) extends LazyModule
48  with BindingScope
49{
50  // val misc = LazyModule(new SoCMisc())
51  lazy val dts = DTS(bindingTree)
52  lazy val json = JSON(bindingTree)
53}
54
55class XSTop()(implicit p: Parameters) extends BaseXSSoc() with HasSoCParameter
56{
57  val nocMisc = if (enableCHI) Some(LazyModule(new MemMisc())) else None
58  val socMisc = if (!enableCHI) Some(LazyModule(new SoCMisc())) else None
59  val misc: MemMisc = if (enableCHI) nocMisc.get else socMisc.get
60
61  ResourceBinding {
62    val width = ResourceInt(2)
63    val model = "xiangshan," + os.read(os.resource / "publishVersion")
64    val compatible = "freechips,rocketchip-unknown"
65    Resource(ResourceAnchors.root, "model").bind(ResourceString(model))
66    Resource(ResourceAnchors.root, "compat").bind(ResourceString(compatible + "-dev"))
67    Resource(ResourceAnchors.soc, "compat").bind(ResourceString(compatible + "-soc"))
68    Resource(ResourceAnchors.root, "width").bind(width)
69    Resource(ResourceAnchors.soc, "width").bind(width)
70    Resource(ResourceAnchors.cpus, "width").bind(ResourceInt(1))
71    def bindManagers(xbar: TLNexusNode) = {
72      ManagerUnification(xbar.edges.in.head.manager.managers).foreach{ manager =>
73        manager.resources.foreach(r => r.bind(manager.toResource))
74      }
75    }
76    if (!enableCHI) {
77      bindManagers(misc.l3_xbar.get.asInstanceOf[TLNexusNode])
78      bindManagers(misc.peripheralXbar.get.asInstanceOf[TLNexusNode])
79    }
80  }
81
82  println(s"FPGASoC cores: $NumCores banks: $L3NBanks block size: $L3BlockSize bus size: $L3OuterBusWidth")
83
84  val core_with_l2 = tiles.map(coreParams =>
85    LazyModule(new XSTile()(p.alter((site, here, up) => {
86      case XSCoreParamsKey => coreParams
87      case PerfCounterOptionsKey => up(PerfCounterOptionsKey).copy(perfDBHartID = coreParams.HartId)
88    })))
89  )
90
91  val l3cacheOpt = soc.L3CacheParamsOpt.map(l3param =>
92    LazyModule(new HuanCun()(new Config((_, _, _) => {
93      case HCCacheParamsKey => l3param.copy(
94        hartIds = tiles.map(_.HartId),
95        FPGAPlatform = debugOpts.FPGAPlatform
96      )
97      case MaxHartIdBits => p(MaxHartIdBits)
98      case LogUtilsOptionsKey => p(LogUtilsOptionsKey)
99      case PerfCounterOptionsKey => p(PerfCounterOptionsKey)
100    })))
101  )
102
103  val chi_llcBridge_opt = Option.when(enableCHI)(
104    LazyModule(new OpenNCB()(p.alter((site, here, up) => {
105      case NCBParametersKey => new NCBParameters(
106        axiMasterOrder      = EnumAXIMasterOrder.WriteAddress,
107        readCompDMT         = false,
108        writeCancelable     = false,
109        writeNoError        = true,
110        axiBurstAlwaysIncr  = true
111      )
112    })))
113  )
114
115  val chi_mmioBridge_opt = Seq.fill(NumCores)(Option.when(enableCHI)(
116    LazyModule(new OpenNCB()(p.alter((site, here, up) => {
117      case NCBParametersKey => new NCBParameters(
118        axiMasterOrder              = EnumAXIMasterOrder.None,
119        readCompDMT                 = false,
120        writeCancelable             = false,
121        writeNoError                = true,
122        asEndpoint                  = false,
123        acceptOrderEndpoint         = true,
124        acceptMemAttrDevice         = true,
125        readReceiptAfterAcception   = true,
126        axiBurstAlwaysIncr          = true
127      )
128    })))
129  ))
130
131  // receive all prefetch req from cores
132  val memblock_pf_recv_nodes: Seq[Option[BundleBridgeSink[PrefetchRecv]]] = core_with_l2.map(_.core_l3_pf_port).map{
133    x => x.map(_ => BundleBridgeSink(Some(() => new PrefetchRecv)))
134  }
135
136  val l3_pf_sender_opt = soc.L3CacheParamsOpt.getOrElse(HCCacheParameters()).prefetch match {
137    case Some(pf) => Some(BundleBridgeSource(() => new PrefetchRecv))
138    case None => None
139  }
140  val nmiIntNode = IntSourceNode(IntSourcePortSimple(1, NumCores, (new NonmaskableInterruptIO).elements.size))
141  val nmi = InModuleBody(nmiIntNode.makeIOs())
142
143  for (i <- 0 until NumCores) {
144    core_with_l2(i).clint_int_node := misc.clint.intnode
145    core_with_l2(i).plic_int_node :*= misc.plic.intnode
146    core_with_l2(i).debug_int_node := misc.debugModule.debug.dmOuter.dmOuter.intnode
147    core_with_l2(i).nmi_int_node := nmiIntNode
148    misc.plic.intnode := IntBuffer() := core_with_l2(i).beu_int_source
149    if (!enableCHI) {
150      misc.peripheral_ports.get(i) := core_with_l2(i).tl_uncache
151    }
152    core_with_l2(i).memory_port.foreach(port => (misc.core_to_l3_ports.get)(i) :=* port)
153    memblock_pf_recv_nodes(i).map(recv => {
154      println(s"Connecting Core_${i}'s L1 pf source to L3!")
155      recv := core_with_l2(i).core_l3_pf_port.get
156    })
157  }
158
159  l3cacheOpt.map(_.ctlnode.map(_ := misc.peripheralXbar.get))
160  l3cacheOpt.map(_.intnode.map(int => {
161    misc.plic.intnode := IntBuffer() := int
162  }))
163
164  val core_rst_nodes = if(l3cacheOpt.nonEmpty && l3cacheOpt.get.rst_nodes.nonEmpty){
165    l3cacheOpt.get.rst_nodes.get
166  } else {
167    core_with_l2.map(_ => BundleBridgeSource(() => Reset()))
168  }
169
170  core_rst_nodes.zip(core_with_l2.map(_.core_reset_sink)).foreach({
171    case (source, sink) =>  sink := source
172  })
173
174  l3cacheOpt match {
175    case Some(l3) =>
176      misc.l3_out :*= l3.node :*= misc.l3_banked_xbar.get
177      l3.pf_recv_node.map(recv => {
178        println("Connecting L1 prefetcher to L3!")
179        recv := l3_pf_sender_opt.get
180      })
181      l3.tpmeta_recv_node.foreach(recv => {
182        for ((core, i) <- core_with_l2.zipWithIndex) {
183          println(s"Connecting core_$i\'s L2 TPmeta request to L3!")
184          recv := core.core_l3_tpmeta_source_port.get
185        }
186      })
187      l3.tpmeta_send_node.foreach(send => {
188        val broadcast = LazyModule(new ValidIOBroadcast[TPmetaResp]())
189        broadcast.node := send
190        for ((core, i) <- core_with_l2.zipWithIndex) {
191          println(s"Connecting core_$i\'s L2 TPmeta response to L3!")
192          core.core_l3_tpmeta_sink_port.get := broadcast.node
193        }
194      })
195    case None =>
196  }
197
198  chi_llcBridge_opt match {
199    case Some(ncb) =>
200      misc.soc_xbar.get := ncb.axi4node
201    case None =>
202  }
203
204  chi_mmioBridge_opt.foreach { e =>
205    e match {
206      case Some(ncb) =>
207        misc.soc_xbar.get := ncb.axi4node
208      case None =>
209    }
210  }
211
212  class XSTopImp(wrapper: LazyModule) extends LazyRawModuleImp(wrapper) {
213    soc.XSTopPrefix.foreach { prefix =>
214      val mod = this.toNamed
215      annotate(new ChiselAnnotation {
216        def toFirrtl = NestedPrefixModulesAnnotation(mod, prefix, true)
217      })
218    }
219
220    FileRegisters.add("dts", dts)
221    FileRegisters.add("graphml", graphML)
222    FileRegisters.add("json", json)
223    FileRegisters.add("plusArgs", freechips.rocketchip.util.PlusArgArtefacts.serialize_cHeader())
224
225    val dma = socMisc.map(m => IO(Flipped(new VerilogAXI4Record(m.dma.elts.head.params))))
226    val peripheral = IO(new VerilogAXI4Record(misc.peripheral.elts.head.params))
227    val memory = IO(new VerilogAXI4Record(misc.memory.elts.head.params))
228
229    socMisc match {
230      case Some(m) =>
231        m.dma.elements.head._2 <> dma.get.viewAs[AXI4Bundle]
232        dontTouch(dma.get)
233      case None =>
234    }
235
236    memory.viewAs[AXI4Bundle] <> misc.memory.elements.head._2
237    peripheral.viewAs[AXI4Bundle] <> misc.peripheral.elements.head._2
238
239    val io = IO(new Bundle {
240      val clock = Input(Bool())
241      val reset = Input(AsyncReset())
242      val sram_config = Input(UInt(16.W))
243      val extIntrs = Input(UInt(NrExtIntr.W))
244      val pll0_lock = Input(Bool())
245      val pll0_ctrl = Output(Vec(6, UInt(32.W)))
246      val systemjtag = new Bundle {
247        val jtag = Flipped(new JTAGIO(hasTRSTn = false))
248        val reset = Input(AsyncReset()) // No reset allowed on top
249        val mfr_id = Input(UInt(11.W))
250        val part_number = Input(UInt(16.W))
251        val version = Input(UInt(4.W))
252      }
253      val debug_reset = Output(Bool())
254      val rtc_clock = Input(Bool())
255      val cacheable_check = new TLPMAIO()
256      val riscv_halt = Output(Vec(NumCores, Bool()))
257      val riscv_rst_vec = Input(Vec(NumCores, UInt(soc.PAddrBits.W)))
258    })
259
260    val reset_sync = withClockAndReset(io.clock.asClock, io.reset) { ResetGen() }
261    val jtag_reset_sync = withClockAndReset(io.systemjtag.jtag.TCK, io.systemjtag.reset) { ResetGen() }
262    val chi_openllc_opt = Option.when(enableCHI)(
263      withClockAndReset(io.clock.asClock, io.reset) {
264        Module(new OpenLLC()(p.alter((site, here, up) => {
265          case OpenLLCParamKey => soc.OpenLLCParamsOpt.get
266        })))
267      }
268    )
269
270    // override LazyRawModuleImp's clock and reset
271    childClock := io.clock.asClock
272    childReset := reset_sync
273
274    // output
275    io.debug_reset := misc.module.debug_module_io.debugIO.ndreset
276
277    // input
278    dontTouch(io)
279    dontTouch(memory)
280    misc.module.ext_intrs := io.extIntrs
281    misc.module.rtc_clock := io.rtc_clock
282    misc.module.pll0_lock := io.pll0_lock
283    misc.module.cacheable_check <> io.cacheable_check
284
285    io.pll0_ctrl <> misc.module.pll0_ctrl
286
287    val msiInfo = WireInit(0.U.asTypeOf(ValidIO(new MsiInfoBundle)))
288
289
290    for ((core, i) <- core_with_l2.zipWithIndex) {
291      core.module.io.hartId := i.U
292      core.module.io.msiInfo := msiInfo
293      core.module.io.clintTime := misc.module.clintTime
294      io.riscv_halt(i) := core.module.io.cpu_halt
295      core.module.io.reset_vector := io.riscv_rst_vec(i)
296    }
297
298    withClockAndReset(io.clock.asClock, io.reset) {
299      Option.when(enableCHI)(true.B).foreach { _ =>
300        for ((core, i) <- core_with_l2.zipWithIndex) {
301          val mmioLogger = CHILogger(s"L2[${i}]_MMIO", true)
302          val llcLogger = CHILogger(s"L2[${i}]_LLC", true)
303          dontTouch(core.module.io.chi.get)
304          bind(
305            route(
306              core.module.io.chi.get, Map((AddressSet(0x0L, 0x00007fffffffL), NumCores + i)) ++ AddressSet(0x0L,
307              0xffffffffffffL).subtract(AddressSet(0x0L, 0x00007fffffffL)).map(addr => (addr, NumCores * 2)).toMap
308            ),
309            Map((NumCores + i) -> mmioLogger.io.up, (NumCores * 2) -> llcLogger.io.up)
310          )
311          chi_mmioBridge_opt(i).get.module.io.chi.connect(mmioLogger.io.down)
312          chi_openllc_opt.get.io.rn(i) <> llcLogger.io.down
313        }
314        val memLogger = CHILogger(s"LLC_MEM", true)
315        chi_openllc_opt.get.io.sn.connect(memLogger.io.up)
316        chi_llcBridge_opt.get.module.io.chi.connect(memLogger.io.down)
317        chi_openllc_opt.get.io.nodeID := (NumCores * 2).U
318      }
319    }
320
321    if(l3cacheOpt.isEmpty || l3cacheOpt.get.rst_nodes.isEmpty){
322      // tie off core soft reset
323      for(node <- core_rst_nodes){
324        node.out.head._1 := false.B.asAsyncReset
325      }
326    }
327
328    l3cacheOpt match {
329      case Some(l3) =>
330        l3.pf_recv_node match {
331          case Some(recv) =>
332            l3_pf_sender_opt.get.out.head._1.addr_valid := VecInit(memblock_pf_recv_nodes.map(_.get.in.head._1.addr_valid)).asUInt.orR
333            for (i <- 0 until NumCores) {
334              when(memblock_pf_recv_nodes(i).get.in.head._1.addr_valid) {
335                l3_pf_sender_opt.get.out.head._1.addr := memblock_pf_recv_nodes(i).get.in.head._1.addr
336                l3_pf_sender_opt.get.out.head._1.l2_pf_en := memblock_pf_recv_nodes(i).get.in.head._1.l2_pf_en
337              }
338            }
339          case None =>
340        }
341        l3.module.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr)
342        core_with_l2.zip(l3.module.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) => tile.module.io.debugTopDown.l3MissMatch := l3Match }
343      case None => core_with_l2.foreach(_.module.io.debugTopDown.l3MissMatch := false.B)
344    }
345
346    core_with_l2.foreach { case tile =>
347      tile.module.io.nodeID.foreach { case nodeID =>
348        nodeID := DontCare
349        dontTouch(nodeID)
350      }
351    }
352
353    misc.module.debug_module_io.resetCtrl.hartIsInReset := core_with_l2.map(_.module.reset.asBool)
354    misc.module.debug_module_io.clock := io.clock
355    misc.module.debug_module_io.reset := reset_sync
356
357    misc.module.debug_module_io.debugIO.reset := misc.module.reset
358    misc.module.debug_module_io.debugIO.clock := io.clock.asClock
359    // TODO: delay 3 cycles?
360    misc.module.debug_module_io.debugIO.dmactiveAck := misc.module.debug_module_io.debugIO.dmactive
361    // jtag connector
362    misc.module.debug_module_io.debugIO.systemjtag.foreach { x =>
363      x.jtag        <> io.systemjtag.jtag
364      x.reset       := jtag_reset_sync
365      x.mfr_id      := io.systemjtag.mfr_id
366      x.part_number := io.systemjtag.part_number
367      x.version     := io.systemjtag.version
368    }
369
370    withClockAndReset(io.clock.asClock, reset_sync) {
371      // Modules are reset one by one
372      // reset ----> SYNC --> {SoCMisc, L3 Cache, Cores}
373      val resetChain = Seq(Seq(misc.module) ++ l3cacheOpt.map(_.module) ++ core_with_l2.map(_.module))
374      ResetGen(resetChain, reset_sync, !debugOpts.ResetGen)
375    }
376
377  }
378
379  lazy val module = new XSTopImp(this)
380}
381
382object TopMain extends App {
383  val (config, firrtlOpts, firtoolOpts) = ArgParser.parse(args)
384
385  // tools: init to close dpi-c when in fpga
386  val envInFPGA = config(DebugOptionsKey).FPGAPlatform
387  val enableDifftest = config(DebugOptionsKey).EnableDifftest || config(DebugOptionsKey).AlwaysBasicDiff
388  val enableChiselDB = config(DebugOptionsKey).EnableChiselDB
389  val enableConstantin = config(DebugOptionsKey).EnableConstantin
390  Constantin.init(enableConstantin && !envInFPGA)
391  ChiselDB.init(enableChiselDB && !envInFPGA)
392
393  val soc = if (config(SoCParamsKey).UseXSNoCTop)
394    DisableMonitors(p => LazyModule(new XSNoCTop()(p)))(config)
395  else
396    DisableMonitors(p => LazyModule(new XSTop()(p)))(config)
397
398  Generator.execute(firrtlOpts, soc.module, firtoolOpts)
399
400  // generate difftest bundles (w/o DifftestTopIO)
401  if (enableDifftest) {
402    DifftestModule.finish("XiangShan", false)
403  }
404
405  FileRegisters.write(fileDir = "./build", filePrefix = "XSTop.")
406}
407