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