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