xref: /XiangShan/src/main/scala/top/XSNoCTop.scala (revision 15b6534b3b50053d14dfe0f37a9742568566da6d)
1/***************************************************************************************
2* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC)
3* Copyright (c) 2024 Institute of Computing Technology, Chinese Academy of Sciences
4*
5* XiangShan is licensed under Mulan PSL v2.
6* You can use this software according to the terms and conditions of the Mulan PSL v2.
7* You may obtain a copy of Mulan PSL v2 at:
8*          http://license.coscl.org.cn/MulanPSL2
9*
10* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
11* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
12* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
13*
14* See the Mulan PSL v2 for more details.
15***************************************************************************************/
16
17package top
18
19import chisel3._
20import chisel3.util._
21import chisel3.experimental.dataview._
22import xiangshan._
23import utils._
24import utility._
25import system._
26import device._
27import org.chipsalliance.cde.config._
28import freechips.rocketchip.amba.axi4._
29import freechips.rocketchip.devices.debug.DebugModuleKey
30import freechips.rocketchip.diplomacy._
31import freechips.rocketchip.interrupts._
32import freechips.rocketchip.tilelink._
33import coupledL2.tl2chi.{CHIAsyncBridgeSink, PortIO}
34import freechips.rocketchip.tile.MaxHartIdBits
35import freechips.rocketchip.util.{AsyncQueueParams, AsyncQueueSource}
36import chisel3.experimental.{ChiselAnnotation, annotate}
37import sifive.enterprise.firrtl.NestedPrefixModulesAnnotation
38import utility.sram.SramBroadcastBundle
39
40import difftest.common.DifftestWiring
41import difftest.util.Profile
42
43class XSNoCTop()(implicit p: Parameters) extends BaseXSSoc with HasSoCParameter
44{
45  override lazy val desiredName: String = "XSTop"
46
47  ResourceBinding {
48    val width = ResourceInt(2)
49    val model = "freechips,rocketchip-unknown"
50    Resource(ResourceAnchors.root, "model").bind(ResourceString(model))
51    Resource(ResourceAnchors.root, "compat").bind(ResourceString(model + "-dev"))
52    Resource(ResourceAnchors.soc, "compat").bind(ResourceString(model + "-soc"))
53    Resource(ResourceAnchors.root, "width").bind(width)
54    Resource(ResourceAnchors.soc, "width").bind(width)
55    Resource(ResourceAnchors.cpus, "width").bind(ResourceInt(1))
56    def bindManagers(xbar: TLNexusNode) = {
57      ManagerUnification(xbar.edges.in.head.manager.managers).foreach{ manager =>
58        manager.resources.foreach(r => r.bind(manager.toResource))
59      }
60    }
61  }
62
63  require(enableCHI)
64
65  // xstile
66  val core_with_l2 = LazyModule(new XSTileWrap()(p.alter((site, here, up) => {
67    case XSCoreParamsKey => tiles.head
68    case PerfCounterOptionsKey => up(PerfCounterOptionsKey).copy(perfDBHartID = tiles.head.HartId)
69  })))
70
71  // imsic bus top
72  val u_imsic_bus_top = LazyModule(new imsic_bus_top)
73
74  // interrupts
75  val clintIntNode = IntSourceNode(IntSourcePortSimple(1, 1, 2))
76  val debugIntNode = IntSourceNode(IntSourcePortSimple(1, 1, 1))
77  val plicIntNode = IntSourceNode(IntSourcePortSimple(1, 2, 1))
78  val nmiIntNode = IntSourceNode(IntSourcePortSimple(1, 1, (new NonmaskableInterruptIO).elements.size))
79  val beuIntNode = IntSinkNode(IntSinkPortSimple(1, 1))
80  core_with_l2.clintIntNode := clintIntNode
81  core_with_l2.debugIntNode := debugIntNode
82  core_with_l2.plicIntNode :*= plicIntNode
83  core_with_l2.nmiIntNode := nmiIntNode
84  beuIntNode := core_with_l2.beuIntNode
85  val clint = InModuleBody(clintIntNode.makeIOs())
86  val debug = InModuleBody(debugIntNode.makeIOs())
87  val plic = InModuleBody(plicIntNode.makeIOs())
88  val nmi = InModuleBody(nmiIntNode.makeIOs())
89  val beu = InModuleBody(beuIntNode.makeIOs())
90
91  // seperate DebugModule bus
92  val EnableDMAsync = EnableDMAsyncBridge.isDefined
93  // asynchronous bridge sink node
94  val dmAsyncSinkOpt = Option.when(SeperateDMBus && EnableDMAsync)(
95    LazyModule(new TLAsyncCrossingSink(EnableDMAsyncBridge.get))
96  )
97  dmAsyncSinkOpt.foreach(_.node := core_with_l2.dmAsyncSourceOpt.get.node)
98  // synchronous sink node
99  val dmSyncSinkOpt = Option.when(SeperateDMBus && !EnableDMAsync)(TLTempNode())
100  dmSyncSinkOpt.foreach(_ := core_with_l2.dmSyncSourceOpt.get)
101
102  // The Manager Node is only used to make IO. Standalone DM should be used for XSNoCTopConfig
103  val dm = Option.when(SeperateDMBus)(TLManagerNode(Seq(
104    TLSlavePortParameters.v1(
105      managers = Seq(
106        TLSlaveParameters.v1(
107          address = Seq(p(DebugModuleKey).get.address),
108          regionType = RegionType.UNCACHED,
109          supportsGet = TransferSizes(1, p(SoCParamsKey).L3BlockSize),
110          supportsPutPartial = TransferSizes(1, p(SoCParamsKey).L3BlockSize),
111          supportsPutFull = TransferSizes(1, p(SoCParamsKey).L3BlockSize),
112          fifoId = Some(0)
113        )
114      ),
115      beatBytes = 8
116    )
117  )))
118  val dmXbar = Option.when(SeperateDMBus)(TLXbar())
119  dmAsyncSinkOpt.foreach(sink => dmXbar.get := sink.node)
120  dmSyncSinkOpt.foreach(sink => dmXbar.get := sink)
121  dm.foreach(_ := dmXbar.get)
122  // seperate debug module io
123  val io_dm = dm.map(x => InModuleBody(x.makeIOs()))
124
125  // reset nodes
126  val core_rst_node = BundleBridgeSource(() => Reset())
127  core_with_l2.tile.core_reset_sink := core_rst_node
128
129  class XSNoCTopImp(wrapper: XSNoCTop) extends LazyRawModuleImp(wrapper) {
130    soc.XSTopPrefix.foreach { prefix =>
131      val mod = this.toNamed
132      annotate(new ChiselAnnotation {
133        def toFirrtl = NestedPrefixModulesAnnotation(mod, prefix, true)
134      })
135    }
136    FileRegisters.add("dts", dts)
137    FileRegisters.add("graphml", graphML)
138    FileRegisters.add("json", json)
139    FileRegisters.add("plusArgs", freechips.rocketchip.util.PlusArgArtefacts.serialize_cHeader())
140
141    val clock = IO(Input(Clock()))
142    val reset = IO(Input(AsyncReset()))
143    val noc_clock = EnableCHIAsyncBridge.map(_ => IO(Input(Clock())))
144    val noc_reset = EnableCHIAsyncBridge.map(_ => IO(Input(AsyncReset())))
145    val soc_clock = IO(Input(Clock()))
146    val soc_reset = IO(Input(AsyncReset()))
147    private val hasMbist = tiles.head.hasMbist
148    val io = IO(new Bundle {
149      val hartId = Input(UInt(p(MaxHartIdBits).W))
150      val riscv_halt = Output(Bool())
151      val riscv_critical_error = Output(Bool())
152      val hartResetReq = Input(Bool())
153      val hartIsInReset = Output(Bool())
154      val riscv_rst_vec = Input(UInt(soc.PAddrBits.W))
155      val chi = new PortIO
156      val nodeID = Input(UInt(soc.NodeIDWidthList(issue).W))
157      val clintTime = Input(ValidIO(UInt(64.W)))
158      val traceCoreInterface = new Bundle {
159        val fromEncoder = Input(new Bundle {
160          val enable = Bool()
161          val stall  = Bool()
162        })
163        val toEncoder   = Output(new Bundle {
164          val cause     = UInt(TraceCauseWidth.W)
165          val tval      = UInt(TraceTvalWidth.W)
166          val priv      = UInt(TracePrivWidth.W)
167          val iaddr     = UInt((TraceTraceGroupNum * TraceIaddrWidth).W)
168          val itype     = UInt((TraceTraceGroupNum * TraceItypeWidth).W)
169          val iretire   = UInt((TraceTraceGroupNum * TraceIretireWidthCompressed).W)
170          val ilastsize = UInt((TraceTraceGroupNum * TraceIlastsizeWidth).W)
171        })
172      }
173      val dft = if(hasMbist) Some(Input(new SramBroadcastBundle)) else None
174      val dft_reset = if(hasMbist) Some(Input(new DFTResetSignals())) else None
175    })
176    // imsic axi4 io
177    val imsic_axi4 = wrapper.u_imsic_bus_top.axi4.map(x => IO(Flipped(new VerilogAXI4Record(x.elts.head.params.copy(addrBits = 32)))))
178    // imsic tl io
179    val imsic_m_tl = wrapper.u_imsic_bus_top.tl_m.map(x => IO(chiselTypeOf(x.getWrappedValue)))
180    val imsic_s_tl = wrapper.u_imsic_bus_top.tl_s.map(x => IO(chiselTypeOf(x.getWrappedValue)))
181    // imsic bare io
182    val imsic = wrapper.u_imsic_bus_top.module.msi.map(x => IO(chiselTypeOf(x)))
183
184    val noc_reset_sync = EnableCHIAsyncBridge.map(_ => withClockAndReset(noc_clock, noc_reset) { ResetGen(2, io.dft_reset) })
185    val soc_reset_sync = withClockAndReset(soc_clock, soc_reset) { ResetGen(2, io.dft_reset) }
186    wrapper.core_with_l2.module.io.dft.zip(io.dft).foreach({case(a, b) => a := b})
187    wrapper.core_with_l2.module.io.dft_reset.zip(io.dft_reset).foreach({case(a, b) => a := b})
188    // device clock and reset
189    wrapper.u_imsic_bus_top.module.clock := soc_clock
190    wrapper.u_imsic_bus_top.module.reset := soc_reset_sync
191
192    // imsic axi4 io connection
193    imsic_axi4.foreach(_.viewAs[AXI4Bundle] <> wrapper.u_imsic_bus_top.axi4.get.elements.head._2)
194    // imsic tl io connection
195    wrapper.u_imsic_bus_top.tl_m.foreach(_ <> imsic_m_tl.get)
196    wrapper.u_imsic_bus_top.tl_s.foreach(_ <> imsic_s_tl.get)
197    // imsic bare io connection
198    wrapper.u_imsic_bus_top.module.msi.foreach(_ <> imsic.get)
199
200    // input
201    dontTouch(io)
202
203    core_with_l2.module.clock := clock
204    core_with_l2.module.reset := reset
205    core_with_l2.module.noc_reset.foreach(_ := noc_reset.get)
206    core_with_l2.module.soc_reset := soc_reset
207    core_with_l2.module.io.hartId := io.hartId
208    core_with_l2.module.io.nodeID.get := io.nodeID
209    io.riscv_halt := core_with_l2.module.io.cpu_halt
210    io.riscv_critical_error := core_with_l2.module.io.cpu_crtical_error
211    core_with_l2.module.io.hartResetReq := io.hartResetReq
212    io.hartIsInReset := core_with_l2.module.io.hartIsInReset
213    core_with_l2.module.io.reset_vector := io.riscv_rst_vec
214    // trace Interface
215    val traceInterface = core_with_l2.module.io.traceCoreInterface
216    traceInterface.fromEncoder := io.traceCoreInterface.fromEncoder
217    io.traceCoreInterface.toEncoder.priv := traceInterface.toEncoder.priv
218    io.traceCoreInterface.toEncoder.cause := traceInterface.toEncoder.trap.cause
219    io.traceCoreInterface.toEncoder.tval := traceInterface.toEncoder.trap.tval
220    io.traceCoreInterface.toEncoder.iaddr := VecInit(traceInterface.toEncoder.groups.map(_.bits.iaddr)).asUInt
221    io.traceCoreInterface.toEncoder.itype := VecInit(traceInterface.toEncoder.groups.map(_.bits.itype)).asUInt
222    io.traceCoreInterface.toEncoder.iretire := VecInit(traceInterface.toEncoder.groups.map(_.bits.iretire)).asUInt
223    io.traceCoreInterface.toEncoder.ilastsize := VecInit(traceInterface.toEncoder.groups.map(_.bits.ilastsize)).asUInt
224
225    EnableClintAsyncBridge match {
226      case Some(param) =>
227        withClockAndReset(soc_clock, soc_reset_sync) {
228          val source = Module(new AsyncQueueSource(UInt(64.W), param))
229          source.io.enq.valid := io.clintTime.valid
230          source.io.enq.bits := io.clintTime.bits
231          core_with_l2.module.io.clintTime <> source.io.async
232        }
233      case None =>
234        core_with_l2.module.io.clintTime <> io.clintTime
235    }
236
237    EnableCHIAsyncBridge match {
238      case Some(param) =>
239        withClockAndReset(noc_clock.get, noc_reset_sync.get) {
240          val sink = Module(new CHIAsyncBridgeSink(param))
241          sink.io.async <> core_with_l2.module.io.chi
242          io.chi <> sink.io.deq
243        }
244      case None =>
245        io.chi <> core_with_l2.module.io.chi
246    }
247
248    // Seperate DebugModule TL Async Queue Sink
249    if (SeperateDMBus && EnableDMAsync) {
250      dmAsyncSinkOpt.get.module.clock := soc_clock
251      dmAsyncSinkOpt.get.module.reset := soc_reset_sync
252    }
253
254    core_with_l2.module.io.msiInfo.valid := wrapper.u_imsic_bus_top.module.msiio.vld_req
255    core_with_l2.module.io.msiInfo.bits := wrapper.u_imsic_bus_top.module.msiio.data
256    wrapper.u_imsic_bus_top.module.msiio.vld_ack := core_with_l2.module.io.msiAck
257    // tie off core soft reset
258    core_rst_node.out.head._1 := false.B.asAsyncReset
259
260    core_with_l2.module.io.debugTopDown.l3MissMatch := false.B
261    core_with_l2.module.io.l3Miss := false.B
262  }
263
264  lazy val module = new XSNoCTopImp(this)
265}
266
267class XSNoCDiffTop(implicit p: Parameters) extends Module {
268  override val desiredName: String = "XSDiffTop"
269  val l_soc = LazyModule(new XSNoCTop())
270  val soc = Module(l_soc.module)
271
272  // Expose XSTop IOs outside, i.e. io
273  def exposeIO(data: Data, name: String): Unit = {
274    val dummy = IO(chiselTypeOf(data)).suggestName(name)
275    dummy <> data
276  }
277  def exposeOptionIO(data: Option[Data], name: String): Unit = {
278    if (data.isDefined) {
279      val dummy = IO(chiselTypeOf(data.get)).suggestName(name)
280      dummy <> data.get
281    }
282  }
283  exposeIO(l_soc.clint, "clint")
284  exposeIO(l_soc.debug, "debug")
285  exposeIO(l_soc.plic, "plic")
286  exposeIO(l_soc.beu, "beu")
287  exposeIO(l_soc.nmi, "nmi")
288  soc.clock := clock
289  soc.reset := reset.asAsyncReset
290  exposeIO(soc.soc_clock, "soc_clock")
291  exposeIO(soc.soc_reset, "soc_reset")
292  exposeIO(soc.io, "io")
293  exposeOptionIO(soc.noc_clock, "noc_clock")
294  exposeOptionIO(soc.noc_reset, "noc_reset")
295  exposeOptionIO(soc.imsic_axi4, "imsic_axi4")
296  exposeOptionIO(soc.imsic_m_tl, "imsic_m_tl")
297  exposeOptionIO(soc.imsic_s_tl, "imsic_s_tl")
298  exposeOptionIO(soc.imsic, "imsic")
299
300  // TODO:
301  // XSDiffTop is only part of DUT, we can not instantiate difftest here.
302  // Temporarily we collect Performance counters for each DiffTop, need control signals passed from Difftest
303  val timer = IO(Input(UInt(64.W)))
304  val logEnable = IO(Input(Bool()))
305  val clean = IO(Input(Bool()))
306  val dump = IO(Input(Bool()))
307  XSLog.collect(timer, logEnable, clean, dump)
308  DifftestWiring.createAndConnectExtraIOs()
309  Profile.generateJson("XiangShan")
310  XSNoCDiffTopChecker()
311}
312
313// TODO:
314// Currently we use two-step XiangShan-Difftest, generating XS(with Diff Interface only) and Difftest seperately
315// To avoid potential interface problem between XS and Diff, we add Checker and CI(dual-core)
316// We will try one-step XS-Diff later
317object XSNoCDiffTopChecker {
318  def apply(): Unit = {
319    val verilog =
320      """
321        |`define CONFIG_XSCORE_NR 2
322        |`include "gateway_interface.svh"
323        |module XSDiffTopChecker(
324        | input                                 cpu_clk,
325        | input                                 cpu_rstn,
326        | input                                 sys_clk,
327        | input                                 sys_rstn
328        |);
329        |wire [63:0] timer;
330        |wire logEnable;
331        |wire clean;
332        |wire dump;
333        |// FIXME: use siganls from Difftest rather than default value
334        |assign timer = 64'b0;
335        |assign logEnable = 1'b0;
336        |assign clean = 1'b0;
337        |assign dump = 1'b0;
338        |gateway_if gateway_if_i();
339        |core_if core_if_o[`CONFIG_XSCORE_NR]();
340        |generate
341        |    genvar i;
342        |    for (i = 0; i < `CONFIG_XSCORE_NR; i = i+1)
343        |    begin: u_CPU_TOP
344        |    // FIXME: add missing ports
345        |    XSDiffTop u_XSTop (
346        |        .clock                   (cpu_clk),
347        |        .noc_clock               (sys_clk),
348        |        .soc_clock               (sys_clk),
349        |        .io_hartId               (6'h0 + i),
350        |        .timer                   (timer),
351        |        .logEnable               (logEnable),
352        |        .clean                   (clean),
353        |        .dump                    (dump),
354        |        .gateway_out             (core_if_o[i])
355        |    );
356        |    end
357        |endgenerate
358        |    CoreToGateway u_CoreToGateway(
359        |    .gateway_out (gateway_if_i.out),
360        |    .core_in (core_if_o)
361        |    );
362        |    GatewayEndpoint u_GatewayEndpoint(
363        |    .clock (sys_clk),
364        |    .reset (sys_rstn),
365        |    .gateway_in (gateway_if_i.in),
366        |    .step ()
367        |    );
368        |
369        |endmodule
370      """.stripMargin
371    FileRegisters.writeOutputFile("./build", "XSDiffTopChecker.sv", verilog)
372  }
373}
374