xref: /XiangShan/src/main/scala/top/Top.scala (revision 881e32f5b63c435bafbaf5dc1d792ffcc9ea103e)
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        outstandingDepth    = 64,
107        axiMasterOrder      = EnumAXIMasterOrder.WriteAddress,
108        readCompDMT         = false,
109        writeCancelable     = false,
110        writeNoError        = true,
111        axiBurstAlwaysIncr  = true,
112        chiDataCheck        = EnumCHIDataCheck.OddParity
113      )
114    })))
115  )
116
117  val chi_mmioBridge_opt = Seq.fill(NumCores)(Option.when(enableCHI)(
118    LazyModule(new OpenNCB()(p.alter((site, here, up) => {
119      case NCBParametersKey => new NCBParameters(
120        outstandingDepth            = 32,
121        axiMasterOrder              = EnumAXIMasterOrder.None,
122        readCompDMT                 = false,
123        writeCancelable             = false,
124        writeNoError                = true,
125        asEndpoint                  = false,
126        acceptOrderEndpoint         = true,
127        acceptMemAttrDevice         = true,
128        readReceiptAfterAcception   = true,
129        axiBurstAlwaysIncr          = true,
130        chiDataCheck                = EnumCHIDataCheck.OddParity
131      )
132    })))
133  ))
134
135  // receive all prefetch req from cores
136  val memblock_pf_recv_nodes: Seq[Option[BundleBridgeSink[PrefetchRecv]]] = core_with_l2.map(_.core_l3_pf_port).map{
137    x => x.map(_ => BundleBridgeSink(Some(() => new PrefetchRecv)))
138  }
139
140  val l3_pf_sender_opt = soc.L3CacheParamsOpt.getOrElse(HCCacheParameters()).prefetch match {
141    case Some(pf) => Some(BundleBridgeSource(() => new PrefetchRecv))
142    case None => None
143  }
144  val nmiIntNode = IntSourceNode(IntSourcePortSimple(1, NumCores, (new NonmaskableInterruptIO).elements.size))
145  val nmi = InModuleBody(nmiIntNode.makeIOs())
146
147  for (i <- 0 until NumCores) {
148    core_with_l2(i).clint_int_node := misc.clint.intnode
149    core_with_l2(i).plic_int_node :*= misc.plic.intnode
150    core_with_l2(i).debug_int_node := misc.debugModule.debug.dmOuter.dmOuter.intnode
151    core_with_l2(i).nmi_int_node := nmiIntNode
152    misc.plic.intnode := IntBuffer() := core_with_l2(i).beu_int_source
153    if (!enableCHI) {
154      misc.peripheral_ports.get(i) := core_with_l2(i).tl_uncache
155    }
156    core_with_l2(i).memory_port.foreach(port => (misc.core_to_l3_ports.get)(i) :=* port)
157    memblock_pf_recv_nodes(i).map(recv => {
158      println(s"Connecting Core_${i}'s L1 pf source to L3!")
159      recv := core_with_l2(i).core_l3_pf_port.get
160    })
161  }
162
163  l3cacheOpt.map(_.ctlnode.map(_ := misc.peripheralXbar.get))
164  l3cacheOpt.map(_.intnode.map(int => {
165    misc.plic.intnode := IntBuffer() := int
166  }))
167
168  val core_rst_nodes = if(l3cacheOpt.nonEmpty && l3cacheOpt.get.rst_nodes.nonEmpty){
169    l3cacheOpt.get.rst_nodes.get
170  } else {
171    core_with_l2.map(_ => BundleBridgeSource(() => Reset()))
172  }
173
174  core_rst_nodes.zip(core_with_l2.map(_.core_reset_sink)).foreach({
175    case (source, sink) =>  sink := source
176  })
177
178  l3cacheOpt match {
179    case Some(l3) =>
180      misc.l3_out :*= l3.node :*= misc.l3_banked_xbar.get
181      l3.pf_recv_node.map(recv => {
182        println("Connecting L1 prefetcher to L3!")
183        recv := l3_pf_sender_opt.get
184      })
185      l3.tpmeta_recv_node.foreach(recv => {
186        for ((core, i) <- core_with_l2.zipWithIndex) {
187          println(s"Connecting core_$i\'s L2 TPmeta request to L3!")
188          recv := core.core_l3_tpmeta_source_port.get
189        }
190      })
191      l3.tpmeta_send_node.foreach(send => {
192        val broadcast = LazyModule(new ValidIOBroadcast[TPmetaResp]())
193        broadcast.node := send
194        for ((core, i) <- core_with_l2.zipWithIndex) {
195          println(s"Connecting core_$i\'s L2 TPmeta response to L3!")
196          core.core_l3_tpmeta_sink_port.get := broadcast.node
197        }
198      })
199    case None =>
200  }
201
202  chi_llcBridge_opt match {
203    case Some(ncb) =>
204      misc.soc_xbar.get := ncb.axi4node
205    case None =>
206  }
207
208  chi_mmioBridge_opt.foreach { e =>
209    e match {
210      case Some(ncb) =>
211        misc.soc_xbar.get := ncb.axi4node
212      case None =>
213    }
214  }
215
216  class XSTopImp(wrapper: LazyModule) extends LazyRawModuleImp(wrapper) {
217    soc.XSTopPrefix.foreach { prefix =>
218      val mod = this.toNamed
219      annotate(new ChiselAnnotation {
220        def toFirrtl = NestedPrefixModulesAnnotation(mod, prefix, true)
221      })
222    }
223
224    FileRegisters.add("dts", dts)
225    FileRegisters.add("graphml", graphML)
226    FileRegisters.add("json", json)
227    FileRegisters.add("plusArgs", freechips.rocketchip.util.PlusArgArtefacts.serialize_cHeader())
228
229    val dma = socMisc.map(m => IO(Flipped(new VerilogAXI4Record(m.dma.elts.head.params))))
230    val peripheral = IO(new VerilogAXI4Record(misc.peripheral.elts.head.params))
231    val memory = IO(new VerilogAXI4Record(misc.memory.elts.head.params))
232
233    socMisc match {
234      case Some(m) =>
235        m.dma.elements.head._2 <> dma.get.viewAs[AXI4Bundle]
236        dontTouch(dma.get)
237      case None =>
238    }
239
240    memory.viewAs[AXI4Bundle] <> misc.memory.elements.head._2
241    peripheral.viewAs[AXI4Bundle] <> misc.peripheral.elements.head._2
242
243    val io = IO(new Bundle {
244      val clock = Input(Clock())
245      val reset = Input(AsyncReset())
246      val sram_config = Input(UInt(16.W))
247      val extIntrs = Input(UInt(NrExtIntr.W))
248      val pll0_lock = Input(Bool())
249      val pll0_ctrl = Output(Vec(6, UInt(32.W)))
250      val systemjtag = new Bundle {
251        val jtag = Flipped(new JTAGIO(hasTRSTn = false))
252        val reset = Input(AsyncReset()) // No reset allowed on top
253        val mfr_id = Input(UInt(11.W))
254        val part_number = Input(UInt(16.W))
255        val version = Input(UInt(4.W))
256      }
257      val debug_reset = Output(Bool())
258      val rtc_clock = Input(Bool())
259      val cacheable_check = new TLPMAIO()
260      val riscv_halt = Output(Vec(NumCores, Bool()))
261      val riscv_critical_error = Output(Vec(NumCores, Bool()))
262      val riscv_rst_vec = Input(Vec(NumCores, UInt(soc.PAddrBits.W)))
263      val traceCoreInterface = Vec(NumCores, new Bundle {
264        val fromEncoder = Input(new Bundle {
265          val enable = Bool()
266          val stall  = Bool()
267        })
268        val toEncoder   = Output(new Bundle {
269          val cause     = UInt(TraceCauseWidth.W)
270          val tval      = UInt(TraceTvalWidth.W)
271          val priv      = UInt(TracePrivWidth.W)
272          val iaddr     = UInt((TraceTraceGroupNum * TraceIaddrWidth).W)
273          val itype     = UInt((TraceTraceGroupNum * TraceItypeWidth).W)
274          val iretire   = UInt((TraceTraceGroupNum * TraceIretireWidthCompressed).W)
275          val ilastsize = UInt((TraceTraceGroupNum * TraceIlastsizeWidth).W)
276        })
277      })
278    })
279
280    val reset_sync = withClockAndReset(io.clock, io.reset) { ResetGen() }
281    val jtag_reset_sync = withClockAndReset(io.systemjtag.jtag.TCK, io.systemjtag.reset) { ResetGen() }
282    val chi_openllc_opt = Option.when(enableCHI)(
283      withClockAndReset(io.clock, io.reset) {
284        Module(new OpenLLC()(p.alter((site, here, up) => {
285          case OpenLLCParamKey => soc.OpenLLCParamsOpt.get.copy(
286            hartIds = tiles.map(_.HartId),
287            FPGAPlatform = debugOpts.FPGAPlatform
288          )
289        })))
290      }
291    )
292
293    // override LazyRawModuleImp's clock and reset
294    childClock := io.clock
295    childReset := reset_sync
296
297    // output
298    io.debug_reset := misc.module.debug_module_io.debugIO.ndreset
299
300    // input
301    dontTouch(io)
302    dontTouch(memory)
303    misc.module.ext_intrs := io.extIntrs
304    misc.module.rtc_clock := io.rtc_clock
305    misc.module.pll0_lock := io.pll0_lock
306    misc.module.cacheable_check <> io.cacheable_check
307
308    io.pll0_ctrl <> misc.module.pll0_ctrl
309
310    val msiInfo = WireInit(0.U.asTypeOf(ValidIO(new MsiInfoBundle)))
311
312
313    for ((core, i) <- core_with_l2.zipWithIndex) {
314      core.module.io.hartId := i.U
315      core.module.io.msiInfo := msiInfo
316      core.module.io.clintTime := misc.module.clintTime
317      io.riscv_halt(i) := core.module.io.cpu_halt
318      io.riscv_critical_error(i) := core.module.io.cpu_crtical_error
319      // trace Interface
320      val traceInterface = core.module.io.traceCoreInterface
321      traceInterface.fromEncoder := io.traceCoreInterface(i).fromEncoder
322      io.traceCoreInterface(i).toEncoder.priv := traceInterface.toEncoder.priv
323      io.traceCoreInterface(i).toEncoder.cause := traceInterface.toEncoder.trap.cause
324      io.traceCoreInterface(i).toEncoder.tval := traceInterface.toEncoder.trap.tval
325      io.traceCoreInterface(i).toEncoder.iaddr := VecInit(traceInterface.toEncoder.groups.map(_.bits.iaddr)).asUInt
326      io.traceCoreInterface(i).toEncoder.itype := VecInit(traceInterface.toEncoder.groups.map(_.bits.itype)).asUInt
327      io.traceCoreInterface(i).toEncoder.iretire := VecInit(traceInterface.toEncoder.groups.map(_.bits.iretire)).asUInt
328      io.traceCoreInterface(i).toEncoder.ilastsize := VecInit(traceInterface.toEncoder.groups.map(_.bits.ilastsize)).asUInt
329
330      core.module.io.reset_vector := io.riscv_rst_vec(i)
331    }
332
333    withClockAndReset(io.clock, io.reset) {
334      Option.when(enableCHI)(true.B).foreach { _ =>
335        for ((core, i) <- core_with_l2.zipWithIndex) {
336          val mmioLogger = CHILogger(s"L2[${i}]_MMIO", true)
337          val llcLogger = CHILogger(s"L2[${i}]_LLC", true)
338          dontTouch(core.module.io.chi.get)
339          bind(
340            route(
341              core.module.io.chi.get, Map((AddressSet(0x0L, 0x00007fffffffL), NumCores + i)) ++ AddressSet(0x0L,
342              0xffffffffffffL).subtract(AddressSet(0x0L, 0x00007fffffffL)).map(addr => (addr, NumCores * 2)).toMap
343            ),
344            Map((NumCores + i) -> mmioLogger.io.up, (NumCores * 2) -> llcLogger.io.up)
345          )
346          chi_mmioBridge_opt(i).get.module.io.chi.connect(mmioLogger.io.down)
347          chi_openllc_opt.get.io.rn(i) <> llcLogger.io.down
348          require(core.module.io.chi.get.getWidth == llcLogger.io.up.getWidth)
349          require(llcLogger.io.down.getWidth == chi_openllc_opt.get.io.rn(i).getWidth)
350        }
351        val memLogger = CHILogger(s"LLC_MEM", true)
352        chi_openllc_opt.get.io.sn.connect(memLogger.io.up)
353        chi_llcBridge_opt.get.module.io.chi.connect(memLogger.io.down)
354        chi_openllc_opt.get.io.nodeID := (NumCores * 2).U
355        chi_openllc_opt.foreach { l3 =>
356          l3.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr)
357        }
358        core_with_l2.zip(chi_openllc_opt.get.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) =>
359          tile.module.io.debugTopDown.l3MissMatch := l3Match
360        }
361        core_with_l2.zip(chi_openllc_opt).foreach { case (tile, l3) =>
362          tile.module.io.l3Miss := l3.io.l3Miss
363        }
364      }
365    }
366
367    if(l3cacheOpt.isEmpty || l3cacheOpt.get.rst_nodes.isEmpty){
368      // tie off core soft reset
369      for(node <- core_rst_nodes){
370        node.out.head._1 := false.B.asAsyncReset
371      }
372    }
373
374    l3cacheOpt match {
375      case Some(l3) =>
376        l3.pf_recv_node match {
377          case Some(recv) =>
378            l3_pf_sender_opt.get.out.head._1.addr_valid := VecInit(memblock_pf_recv_nodes.map(_.get.in.head._1.addr_valid)).asUInt.orR
379            for (i <- 0 until NumCores) {
380              when(memblock_pf_recv_nodes(i).get.in.head._1.addr_valid) {
381                l3_pf_sender_opt.get.out.head._1.addr := memblock_pf_recv_nodes(i).get.in.head._1.addr
382                l3_pf_sender_opt.get.out.head._1.l2_pf_en := memblock_pf_recv_nodes(i).get.in.head._1.l2_pf_en
383              }
384            }
385          case None =>
386        }
387        l3.module.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr)
388        core_with_l2.zip(l3.module.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) => tile.module.io.debugTopDown.l3MissMatch := l3Match }
389        core_with_l2.foreach(_.module.io.l3Miss := l3.module.io.l3Miss)
390      case None =>
391    }
392
393    (chi_openllc_opt, l3cacheOpt) match {
394      case (None, None) =>
395        core_with_l2.foreach(_.module.io.debugTopDown.l3MissMatch := false.B)
396        core_with_l2.foreach(_.module.io.l3Miss := false.B)
397      case _ =>
398    }
399
400    core_with_l2.zipWithIndex.foreach { case (tile, i) =>
401      tile.module.io.nodeID.foreach { case nodeID =>
402        nodeID := i.U
403        dontTouch(nodeID)
404      }
405    }
406
407    misc.module.debug_module_io.resetCtrl.hartIsInReset := core_with_l2.map(_.module.io.hartIsInReset)
408    misc.module.debug_module_io.clock := io.clock
409    misc.module.debug_module_io.reset := reset_sync
410
411    misc.module.debug_module_io.debugIO.reset := misc.module.reset
412    misc.module.debug_module_io.debugIO.clock := io.clock
413    // TODO: delay 3 cycles?
414    misc.module.debug_module_io.debugIO.dmactiveAck := misc.module.debug_module_io.debugIO.dmactive
415    // jtag connector
416    misc.module.debug_module_io.debugIO.systemjtag.foreach { x =>
417      x.jtag        <> io.systemjtag.jtag
418      x.reset       := jtag_reset_sync
419      x.mfr_id      := io.systemjtag.mfr_id
420      x.part_number := io.systemjtag.part_number
421      x.version     := io.systemjtag.version
422    }
423
424    withClockAndReset(io.clock, reset_sync) {
425      // Modules are reset one by one
426      // reset ----> SYNC --> {SoCMisc, L3 Cache, Cores}
427      val resetChain = Seq(Seq(misc.module) ++ l3cacheOpt.map(_.module))
428      ResetGen(resetChain, reset_sync, !debugOpts.ResetGen)
429      // Ensure that cores could be reset when DM disable `hartReset` or l3cacheOpt.isEmpty.
430      val dmResetReqVec = misc.module.debug_module_io.resetCtrl.hartResetReq.getOrElse(0.U.asTypeOf(Vec(core_with_l2.map(_.module).length, Bool())))
431      val syncResetCores = if(l3cacheOpt.nonEmpty) l3cacheOpt.map(_.module).get.reset.asBool else misc.module.reset.asBool
432      (core_with_l2.map(_.module)).zip(dmResetReqVec).map { case(core, dmResetReq) =>
433        ResetGen(Seq(Seq(core)), (syncResetCores || dmResetReq).asAsyncReset, !debugOpts.ResetGen)
434      }
435    }
436
437  }
438
439  lazy val module = new XSTopImp(this)
440}
441
442object TopMain extends App {
443  val (config, firrtlOpts, firtoolOpts) = ArgParser.parse(args)
444
445  // tools: init to close dpi-c when in fpga
446  val envInFPGA = config(DebugOptionsKey).FPGAPlatform
447  val enableDifftest = config(DebugOptionsKey).EnableDifftest || config(DebugOptionsKey).AlwaysBasicDiff
448  val enableChiselDB = config(DebugOptionsKey).EnableChiselDB
449  val enableConstantin = config(DebugOptionsKey).EnableConstantin
450  Constantin.init(enableConstantin && !envInFPGA)
451  ChiselDB.init(enableChiselDB && !envInFPGA)
452
453  if (config(SoCParamsKey).UseXSNoCDiffTop) {
454    Generator.execute(firrtlOpts, DisableMonitors(p => new XSNoCDiffTop()(p))(config), firtoolOpts)
455  } else {
456    val soc = if (config(SoCParamsKey).UseXSNoCTop)
457      DisableMonitors(p => LazyModule(new XSNoCTop()(p)))(config)
458    else
459      DisableMonitors(p => LazyModule(new XSTop()(p)))(config)
460
461    Generator.execute(firrtlOpts, soc.module, firtoolOpts)
462
463    // generate difftest bundles (w/o DifftestTopIO)
464    if (enableDifftest) {
465      DifftestModule.finish("XiangShan", false)
466    }
467  }
468
469  FileRegisters.write(fileDir = "./build", filePrefix = "XSTop.")
470}
471