xref: /XiangShan/src/main/scala/top/Top.scala (revision 1bc48dd1fa0af361fd194c65bad3b86349ec2903)
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 openLLC.DummyLLC
29import utility._
30import system._
31import device._
32import chisel3.stage.ChiselGeneratorAnnotation
33import org.chipsalliance.cde.config._
34import freechips.rocketchip.diplomacy._
35import freechips.rocketchip.tile._
36import freechips.rocketchip.tilelink._
37import freechips.rocketchip.interrupts._
38import freechips.rocketchip.amba.axi4._
39import freechips.rocketchip.jtag.JTAGIO
40import chisel3.experimental.{annotate, ChiselAnnotation}
41import sifive.enterprise.firrtl.NestedPrefixModulesAnnotation
42
43abstract class BaseXSSoc()(implicit p: Parameters) extends LazyModule
44  with BindingScope
45{
46  // val misc = LazyModule(new SoCMisc())
47  lazy val dts = DTS(bindingTree)
48  lazy val json = JSON(bindingTree)
49}
50
51class XSTop()(implicit p: Parameters) extends BaseXSSoc() with HasSoCParameter
52{
53  val nocMisc = if (enableCHI) Some(LazyModule(new MemMisc())) else None
54  val socMisc = if (!enableCHI) Some(LazyModule(new SoCMisc())) else None
55  val misc: MemMisc = if (enableCHI) nocMisc.get else socMisc.get
56
57  ResourceBinding {
58    val width = ResourceInt(2)
59    val model = "xiangshan," + os.read(os.resource / "publishVersion")
60    val compatible = "freechips,rocketchip-unknown"
61    Resource(ResourceAnchors.root, "model").bind(ResourceString(model))
62    Resource(ResourceAnchors.root, "compat").bind(ResourceString(compatible + "-dev"))
63    Resource(ResourceAnchors.soc, "compat").bind(ResourceString(compatible + "-soc"))
64    Resource(ResourceAnchors.root, "width").bind(width)
65    Resource(ResourceAnchors.soc, "width").bind(width)
66    Resource(ResourceAnchors.cpus, "width").bind(ResourceInt(1))
67    def bindManagers(xbar: TLNexusNode) = {
68      ManagerUnification(xbar.edges.in.head.manager.managers).foreach{ manager =>
69        manager.resources.foreach(r => r.bind(manager.toResource))
70      }
71    }
72    if (!enableCHI) {
73      bindManagers(misc.l3_xbar.get.asInstanceOf[TLNexusNode])
74      bindManagers(misc.peripheralXbar.get.asInstanceOf[TLNexusNode])
75    }
76  }
77
78  println(s"FPGASoC cores: $NumCores banks: $L3NBanks block size: $L3BlockSize bus size: $L3OuterBusWidth")
79
80  val core_with_l2 = tiles.map(coreParams =>
81    LazyModule(new XSTile()(p.alter((site, here, up) => {
82      case XSCoreParamsKey => coreParams
83      case PerfCounterOptionsKey => up(PerfCounterOptionsKey).copy(perfDBHartID = coreParams.HartId)
84    })))
85  )
86
87  val l3cacheOpt = soc.L3CacheParamsOpt.map(l3param =>
88    LazyModule(new HuanCun()(new Config((_, _, _) => {
89      case HCCacheParamsKey => l3param.copy(
90        hartIds = tiles.map(_.HartId),
91        FPGAPlatform = debugOpts.FPGAPlatform
92      )
93      case MaxHartIdBits => p(MaxHartIdBits)
94      case LogUtilsOptionsKey => p(LogUtilsOptionsKey)
95      case PerfCounterOptionsKey => p(PerfCounterOptionsKey)
96    })))
97  )
98
99  val chi_dummyllc_opt = Option.when(enableCHI)(LazyModule(new DummyLLC(numRNs = NumCores)(p)))
100
101  // receive all prefetch req from cores
102  val memblock_pf_recv_nodes: Seq[Option[BundleBridgeSink[PrefetchRecv]]] = core_with_l2.map(_.core_l3_pf_port).map{
103    x => x.map(_ => BundleBridgeSink(Some(() => new PrefetchRecv)))
104  }
105
106  val l3_pf_sender_opt = soc.L3CacheParamsOpt.getOrElse(HCCacheParameters()).prefetch match {
107    case Some(pf) => Some(BundleBridgeSource(() => new PrefetchRecv))
108    case None => None
109  }
110  val nmiIntNode = IntSourceNode(IntSourcePortSimple(1, NumCores, (new NonmaskableInterruptIO).elements.size))
111  val nmi = InModuleBody(nmiIntNode.makeIOs())
112
113  for (i <- 0 until NumCores) {
114    core_with_l2(i).clint_int_node := misc.clint.intnode
115    core_with_l2(i).plic_int_node :*= misc.plic.intnode
116    core_with_l2(i).debug_int_node := misc.debugModule.debug.dmOuter.dmOuter.intnode
117    core_with_l2(i).nmi_int_node := nmiIntNode
118    misc.plic.intnode := IntBuffer() := core_with_l2(i).beu_int_source
119    if (!enableCHI) {
120      misc.peripheral_ports.get(i) := core_with_l2(i).tl_uncache
121    }
122    core_with_l2(i).memory_port.foreach(port => (misc.core_to_l3_ports.get)(i) :=* port)
123    memblock_pf_recv_nodes(i).map(recv => {
124      println(s"Connecting Core_${i}'s L1 pf source to L3!")
125      recv := core_with_l2(i).core_l3_pf_port.get
126    })
127  }
128
129  l3cacheOpt.map(_.ctlnode.map(_ := misc.peripheralXbar.get))
130  l3cacheOpt.map(_.intnode.map(int => {
131    misc.plic.intnode := IntBuffer() := int
132  }))
133
134  val core_rst_nodes = if(l3cacheOpt.nonEmpty && l3cacheOpt.get.rst_nodes.nonEmpty){
135    l3cacheOpt.get.rst_nodes.get
136  } else {
137    core_with_l2.map(_ => BundleBridgeSource(() => Reset()))
138  }
139
140  core_rst_nodes.zip(core_with_l2.map(_.core_reset_sink)).foreach({
141    case (source, sink) =>  sink := source
142  })
143
144  l3cacheOpt match {
145    case Some(l3) =>
146      misc.l3_out :*= l3.node :*= misc.l3_banked_xbar.get
147      l3.pf_recv_node.map(recv => {
148        println("Connecting L1 prefetcher to L3!")
149        recv := l3_pf_sender_opt.get
150      })
151      l3.tpmeta_recv_node.foreach(recv => {
152        for ((core, i) <- core_with_l2.zipWithIndex) {
153          println(s"Connecting core_$i\'s L2 TPmeta request to L3!")
154          recv := core.core_l3_tpmeta_source_port.get
155        }
156      })
157      l3.tpmeta_send_node.foreach(send => {
158        val broadcast = LazyModule(new ValidIOBroadcast[TPmetaResp]())
159        broadcast.node := send
160        for ((core, i) <- core_with_l2.zipWithIndex) {
161          println(s"Connecting core_$i\'s L2 TPmeta response to L3!")
162          core.core_l3_tpmeta_sink_port.get := broadcast.node
163        }
164      })
165    case None =>
166  }
167
168  chi_dummyllc_opt match {
169    case Some(llc) =>
170      misc.soc_xbar.get := llc.axi4node
171    case None =>
172  }
173
174  class XSTopImp(wrapper: LazyModule) extends LazyRawModuleImp(wrapper) {
175    soc.XSTopPrefix.foreach { prefix =>
176      val mod = this.toNamed
177      annotate(new ChiselAnnotation {
178        def toFirrtl = NestedPrefixModulesAnnotation(mod, prefix, true)
179      })
180    }
181
182    FileRegisters.add("dts", dts)
183    FileRegisters.add("graphml", graphML)
184    FileRegisters.add("json", json)
185    FileRegisters.add("plusArgs", freechips.rocketchip.util.PlusArgArtefacts.serialize_cHeader())
186
187    val dma = socMisc.map(m => IO(Flipped(new VerilogAXI4Record(m.dma.elts.head.params))))
188    val peripheral = IO(new VerilogAXI4Record(misc.peripheral.elts.head.params))
189    val memory = IO(new VerilogAXI4Record(misc.memory.elts.head.params))
190
191    socMisc match {
192      case Some(m) =>
193        m.dma.elements.head._2 <> dma.get.viewAs[AXI4Bundle]
194        dontTouch(dma.get)
195      case None =>
196    }
197
198    memory.viewAs[AXI4Bundle] <> misc.memory.elements.head._2
199    peripheral.viewAs[AXI4Bundle] <> misc.peripheral.elements.head._2
200
201    val io = IO(new Bundle {
202      val clock = Input(Bool())
203      val reset = Input(AsyncReset())
204      val sram_config = Input(UInt(16.W))
205      val extIntrs = Input(UInt(NrExtIntr.W))
206      val pll0_lock = Input(Bool())
207      val pll0_ctrl = Output(Vec(6, UInt(32.W)))
208      val systemjtag = new Bundle {
209        val jtag = Flipped(new JTAGIO(hasTRSTn = false))
210        val reset = Input(AsyncReset()) // No reset allowed on top
211        val mfr_id = Input(UInt(11.W))
212        val part_number = Input(UInt(16.W))
213        val version = Input(UInt(4.W))
214      }
215      val debug_reset = Output(Bool())
216      val rtc_clock = Input(Bool())
217      val cacheable_check = new TLPMAIO()
218      val riscv_halt = Output(Vec(NumCores, Bool()))
219      val riscv_rst_vec = Input(Vec(NumCores, UInt(soc.PAddrBits.W)))
220    })
221
222    val reset_sync = withClockAndReset(io.clock.asClock, io.reset) { ResetGen() }
223    val jtag_reset_sync = withClockAndReset(io.systemjtag.jtag.TCK, io.systemjtag.reset) { ResetGen() }
224
225    // override LazyRawModuleImp's clock and reset
226    childClock := io.clock.asClock
227    childReset := reset_sync
228
229    // output
230    io.debug_reset := misc.module.debug_module_io.debugIO.ndreset
231
232    // input
233    dontTouch(io)
234    dontTouch(memory)
235    misc.module.ext_intrs := io.extIntrs
236    misc.module.rtc_clock := io.rtc_clock
237    misc.module.pll0_lock := io.pll0_lock
238    misc.module.cacheable_check <> io.cacheable_check
239
240    io.pll0_ctrl <> misc.module.pll0_ctrl
241
242    val msiInfo = WireInit(0.U.asTypeOf(ValidIO(new MsiInfoBundle)))
243
244
245    for ((core, i) <- core_with_l2.zipWithIndex) {
246      core.module.io.hartId := i.U
247      core.module.io.msiInfo := msiInfo
248      core.module.io.clintTime := misc.module.clintTime
249      io.riscv_halt(i) := core.module.io.cpu_halt
250      core.module.io.reset_vector := io.riscv_rst_vec(i)
251      chi_dummyllc_opt.foreach { case llc =>
252        llc.module.io.rn(i) <> core.module.io.chi.get
253        core.module.io.nodeID.get := i.U // TODO
254      }
255    }
256
257    if(l3cacheOpt.isEmpty || l3cacheOpt.get.rst_nodes.isEmpty){
258      // tie off core soft reset
259      for(node <- core_rst_nodes){
260        node.out.head._1 := false.B.asAsyncReset
261      }
262    }
263
264    l3cacheOpt match {
265      case Some(l3) =>
266        l3.pf_recv_node match {
267          case Some(recv) =>
268            l3_pf_sender_opt.get.out.head._1.addr_valid := VecInit(memblock_pf_recv_nodes.map(_.get.in.head._1.addr_valid)).asUInt.orR
269            for (i <- 0 until NumCores) {
270              when(memblock_pf_recv_nodes(i).get.in.head._1.addr_valid) {
271                l3_pf_sender_opt.get.out.head._1.addr := memblock_pf_recv_nodes(i).get.in.head._1.addr
272                l3_pf_sender_opt.get.out.head._1.l2_pf_en := memblock_pf_recv_nodes(i).get.in.head._1.l2_pf_en
273              }
274            }
275          case None =>
276        }
277        l3.module.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr)
278        core_with_l2.zip(l3.module.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) => tile.module.io.debugTopDown.l3MissMatch := l3Match }
279      case None => core_with_l2.foreach(_.module.io.debugTopDown.l3MissMatch := false.B)
280    }
281
282    core_with_l2.foreach { case tile =>
283      tile.module.io.nodeID.foreach { case nodeID =>
284        nodeID := DontCare
285        dontTouch(nodeID)
286      }
287    }
288
289    misc.module.debug_module_io.resetCtrl.hartIsInReset := core_with_l2.map(_.module.reset.asBool)
290    misc.module.debug_module_io.clock := io.clock
291    misc.module.debug_module_io.reset := reset_sync
292
293    misc.module.debug_module_io.debugIO.reset := misc.module.reset
294    misc.module.debug_module_io.debugIO.clock := io.clock.asClock
295    // TODO: delay 3 cycles?
296    misc.module.debug_module_io.debugIO.dmactiveAck := misc.module.debug_module_io.debugIO.dmactive
297    // jtag connector
298    misc.module.debug_module_io.debugIO.systemjtag.foreach { x =>
299      x.jtag        <> io.systemjtag.jtag
300      x.reset       := jtag_reset_sync
301      x.mfr_id      := io.systemjtag.mfr_id
302      x.part_number := io.systemjtag.part_number
303      x.version     := io.systemjtag.version
304    }
305
306    withClockAndReset(io.clock.asClock, reset_sync) {
307      // Modules are reset one by one
308      // reset ----> SYNC --> {SoCMisc, L3 Cache, Cores}
309      val resetChain = Seq(Seq(misc.module) ++ l3cacheOpt.map(_.module) ++ core_with_l2.map(_.module))
310      ResetGen(resetChain, reset_sync, !debugOpts.ResetGen)
311    }
312
313  }
314
315  lazy val module = new XSTopImp(this)
316}
317
318object TopMain extends App {
319  val (config, firrtlOpts, firtoolOpts) = ArgParser.parse(args)
320
321  // tools: init to close dpi-c when in fpga
322  val envInFPGA = config(DebugOptionsKey).FPGAPlatform
323  val enableDifftest = config(DebugOptionsKey).EnableDifftest || config(DebugOptionsKey).AlwaysBasicDiff
324  val enableChiselDB = config(DebugOptionsKey).EnableChiselDB
325  val enableConstantin = config(DebugOptionsKey).EnableConstantin
326  Constantin.init(enableConstantin && !envInFPGA)
327  ChiselDB.init(enableChiselDB && !envInFPGA)
328
329  val soc = if (config(SoCParamsKey).UseXSNoCTop)
330    DisableMonitors(p => LazyModule(new XSNoCTop()(p)))(config)
331  else
332    DisableMonitors(p => LazyModule(new XSTop()(p)))(config)
333
334  Generator.execute(firrtlOpts, soc.module, firtoolOpts)
335
336  // generate difftest bundles (w/o DifftestTopIO)
337  if (enableDifftest) {
338    DifftestModule.finish("XiangShan", false)
339  }
340
341  FileRegisters.write(fileDir = "./build", filePrefix = "XSTop.")
342}
343