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