xref: /XiangShan/src/main/scala/top/XSNoCTop.scala (revision a74491fc58c5cd01127b775542f99dfb2da0e736)
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 utility.sram.SramMbistBundle
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
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  // asynchronous bridge sink node
94  val tlAsyncSinkOpt = Option.when(SeperateTLBus && EnableSeperateTLAsync)(
95    LazyModule(new TLAsyncCrossingSink(SeperateTLAsyncBridge.get))
96  )
97  tlAsyncSinkOpt.foreach(_.node := core_with_l2.tlAsyncSourceOpt.get.node)
98  // synchronous sink node
99  val tlSyncSinkOpt = Option.when(SeperateTLBus && !EnableSeperateTLAsync)(TLTempNode())
100  tlSyncSinkOpt.foreach(_ := core_with_l2.tlSyncSourceOpt.get)
101
102  // The Manager Node is only used to make IO
103  val tl = Option.when(SeperateTLBus)(TLManagerNode(Seq(
104    TLSlavePortParameters.v1(
105      managers = SeperateTLBusRanges map { address =>
106        TLSlaveParameters.v1(
107          address = Seq(address),
108          regionType = RegionType.UNCACHED,
109          executable = true,
110          supportsGet = TransferSizes(1, p(SoCParamsKey).L3BlockSize),
111          supportsPutPartial = TransferSizes(1, p(SoCParamsKey).L3BlockSize),
112          supportsPutFull = TransferSizes(1, p(SoCParamsKey).L3BlockSize),
113          fifoId = Some(0)
114        )
115
116      },
117      beatBytes = 8
118    )
119  )))
120  val tlXbar = Option.when(SeperateTLBus)(TLXbar())
121  tlAsyncSinkOpt.foreach(sink => tlXbar.get := sink.node)
122  tlSyncSinkOpt.foreach(sink => tlXbar.get := sink)
123  tl.foreach(_ := tlXbar.get)
124  // seperate TL io
125  val io_tl = tl.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    private val hasSramCtl = tiles.head.hasSramCtl
151    val io = IO(new Bundle {
152      val hartId = Input(UInt(p(MaxHartIdBits).W))
153      val riscv_halt = Output(Bool())
154      val riscv_critical_error = Output(Bool())
155      val hartResetReq = Input(Bool())
156      val hartIsInReset = Output(Bool())
157      val riscv_rst_vec = Input(UInt(soc.PAddrBits.W))
158      val chi = new PortIO
159      val nodeID = Input(UInt(soc.NodeIDWidthList(issue).W))
160      val clintTime = Input(ValidIO(UInt(64.W)))
161      val traceCoreInterface = new Bundle {
162        val fromEncoder = Input(new Bundle {
163          val enable = Bool()
164          val stall  = Bool()
165        })
166        val toEncoder   = Output(new Bundle {
167          val cause     = UInt(TraceCauseWidth.W)
168          val tval      = UInt(TraceTvalWidth.W)
169          val priv      = UInt(TracePrivWidth.W)
170          val iaddr     = UInt((TraceTraceGroupNum * TraceIaddrWidth).W)
171          val itype     = UInt((TraceTraceGroupNum * TraceItypeWidth).W)
172          val iretire   = UInt((TraceTraceGroupNum * TraceIretireWidthCompressed).W)
173          val ilastsize = UInt((TraceTraceGroupNum * TraceIlastsizeWidth).W)
174        })
175      }
176      val dft = Option.when(hasMbist)(Input(new SramMbistBundle))
177      val dft_reset = Option.when(hasMbist)(Input(new DFTResetSignals()))
178      val sramCtl = Option.when(hasSramCtl)(Input(UInt(64.W)))
179      val lp = Option.when(EnablePowerDown) (new LowPowerIO)
180    })
181    // imsic axi4lite io
182    val imsic_axi4lite = wrapper.u_imsic_bus_top.module.axi4lite.map(x => IO(chiselTypeOf(x)))
183    // imsic tl io
184    val imsic_m_tl = wrapper.u_imsic_bus_top.tl_m.map(x => IO(chiselTypeOf(x.getWrappedValue)))
185    val imsic_s_tl = wrapper.u_imsic_bus_top.tl_s.map(x => IO(chiselTypeOf(x.getWrappedValue)))
186
187    val noc_reset_sync = EnableCHIAsyncBridge.map(_ => withClockAndReset(noc_clock, noc_reset) { ResetGen(2, io.dft_reset) })
188    val soc_reset_sync = withClockAndReset(soc_clock, soc_reset) { ResetGen(2, io.dft_reset) }
189    wrapper.core_with_l2.module.io.sramTest.mbist.zip(io.dft).foreach { case (a, b) => a := b }
190    wrapper.core_with_l2.module.io.sramTest.mbistReset.zip(io.dft_reset).foreach { case (a, b) => a := b }
191    wrapper.core_with_l2.module.io.sramTest.sramCtl.zip(io.sramCtl).foreach { case (a, b) => a := b }
192    // device clock and reset
193    wrapper.u_imsic_bus_top.module.clock := soc_clock
194    wrapper.u_imsic_bus_top.module.reset := soc_reset_sync
195
196    // imsic axi4lite io connection
197    wrapper.u_imsic_bus_top.module.axi4lite.foreach(_ <> imsic_axi4lite.get)
198
199    // imsic tl io connection
200    wrapper.u_imsic_bus_top.tl_m.foreach(_ <> imsic_m_tl.get)
201    wrapper.u_imsic_bus_top.tl_s.foreach(_ <> imsic_s_tl.get)
202
203    // input
204    dontTouch(io)
205
206    /*
207     SoC control the sequence of power on/off with isolation/reset/clock
208     */
209    val soc_rst_n = io.lp.map(_.i_cpu_sw_rst_n).getOrElse(true.B)
210    val soc_iso_en = io.lp.map(_.i_cpu_iso_en).getOrElse(false.B)
211
212    /* Core+L2 reset when:
213     1. normal reset from SoC
214     2. SoC initialize reset during Power on/off flow
215     */
216    val cpuReset = reset.asBool || !soc_rst_n
217
218    //Interrupt sources collect
219    val msip  = clint.head(0)
220    val mtip  = clint.head(1)
221    val meip  = plic.head(0)
222    val seip  = plic.last(0)
223    val nmi_31 = nmi.head(0)
224    val nmi_43 = nmi.head(1)
225    val msi_info_vld = core_with_l2.module.io.msiInfo.valid
226    val intSrc = Cat(msip, mtip, meip, seip, nmi_31, nmi_43, msi_info_vld)
227
228    /*
229     * CPU Low Power State:
230     * 1. core+L2 Low power state transactions is triggered by l2 flush request from core CSR
231     * 2. wait L2 flush done
232     * 3. wait Core to wfi -> send out < io.o_cpu_no_op >
233     */
234    val sIDLE :: sL2FLUSH :: sWAITWFI :: sEXITCO :: sPOFFREQ :: Nil = Enum(5)
235    val lpState = withClockAndReset(clock, cpuReset.asAsyncReset) {RegInit(sIDLE)}
236    val l2_flush_en = core_with_l2.module.io.l2_flush_en.getOrElse(false.B)
237    val l2_flush_done = core_with_l2.module.io.l2_flush_done.getOrElse(false.B)
238    val isWFI = core_with_l2.module.io.cpu_halt
239    val exitco = !io.chi.syscoreq & !io.chi.syscoack
240    lpState := lpStateNext(lpState, l2_flush_en, l2_flush_done, isWFI, exitco)
241    io.lp.foreach { lp => lp.o_cpu_no_op := lpState === sPOFFREQ } // inform SoC core+l2 want to power off
242
243    /*WFI clock Gating state
244     1. works only when lpState is IDLE means Core+L2 works in normal state
245     2. when Core is in wfi state, core+l2 clock is gated
246     3. only reset/interrupt/snoop could recover core+l2 clock
247    */
248    val sNORMAL :: sGCLOCK :: sAWAKE :: Nil = Enum(3)
249    val wfiState = withClockAndReset(clock, cpuReset.asAsyncReset) {RegInit(sNORMAL)}
250    val isNormal = lpState === sIDLE
251    val wfiGateClock = withClockAndReset(clock, cpuReset.asAsyncReset) {RegInit(false.B)}
252    wfiState := WfiStateNext(wfiState, isWFI, isNormal, io.chi.rx.snp.flitpend, intSrc)
253
254    if (WFIClockGate) {
255      wfiGateClock := (wfiState === sGCLOCK)
256    }else {
257      wfiGateClock := false.B
258    }
259
260
261
262    /* during power down sequence, SoC reset will gate clock */
263    val pwrdownGateClock = withClockAndReset(clock, cpuReset.asAsyncReset) {RegInit(false.B)}
264    pwrdownGateClock := !soc_rst_n && lpState === sPOFFREQ
265    /*
266     physical power off handshake:
267     i_cpu_pwrdown_req_n
268     o_cpu_pwrdown_ack_n means all power is safely on
269     */
270    val soc_pwrdown_n = io.lp.map(_.i_cpu_pwrdown_req_n).getOrElse(true.B)
271    io.lp.foreach { lp => lp.o_cpu_pwrdown_ack_n := core_with_l2.module.io.pwrdown_ack_n.getOrElse(true.B) }
272
273
274    /* Core+L2 hardware initial clock gating as:
275     1. Gate clock when SoC reset CPU with < io.i_cpu_sw_rst_n > valid
276     2. Gate clock when SoC is enable clock (Core+L2 in normal state) and core is in wfi state
277     3. Disable clock gate at the cycle of Flitpend valid in rx.snp channel
278     */
279    val cpuClockEn = !wfiGateClock && !pwrdownGateClock | io.chi.rx.snp.flitpend
280
281    dontTouch(wfiGateClock)
282    dontTouch(pwrdownGateClock)
283    dontTouch(cpuClockEn)
284
285    core_with_l2.module.clock := ClockGate(false.B, cpuClockEn, clock)
286    core_with_l2.module.reset := cpuReset.asAsyncReset
287    core_with_l2.module.noc_reset.foreach(_ := noc_reset.get)
288    core_with_l2.module.soc_reset := soc_reset
289    core_with_l2.module.io.hartId := io.hartId
290    core_with_l2.module.io.nodeID.get := io.nodeID
291    io.riscv_halt := core_with_l2.module.io.cpu_halt
292    io.riscv_critical_error := core_with_l2.module.io.cpu_crtical_error
293    core_with_l2.module.io.hartResetReq := io.hartResetReq
294    io.hartIsInReset := core_with_l2.module.io.hartIsInReset
295    core_with_l2.module.io.reset_vector := io.riscv_rst_vec
296    core_with_l2.module.io.iso_en.foreach { _ := false.B }
297    core_with_l2.module.io.pwrdown_req_n.foreach { _ := true.B }
298    // trace Interface
299    val traceInterface = core_with_l2.module.io.traceCoreInterface
300    traceInterface.fromEncoder := io.traceCoreInterface.fromEncoder
301    io.traceCoreInterface.toEncoder.priv := traceInterface.toEncoder.priv
302    io.traceCoreInterface.toEncoder.cause := traceInterface.toEncoder.trap.cause
303    io.traceCoreInterface.toEncoder.tval := traceInterface.toEncoder.trap.tval
304    io.traceCoreInterface.toEncoder.iaddr := VecInit(traceInterface.toEncoder.groups.map(_.bits.iaddr)).asUInt
305    io.traceCoreInterface.toEncoder.itype := VecInit(traceInterface.toEncoder.groups.map(_.bits.itype)).asUInt
306    io.traceCoreInterface.toEncoder.iretire := VecInit(traceInterface.toEncoder.groups.map(_.bits.iretire)).asUInt
307    io.traceCoreInterface.toEncoder.ilastsize := VecInit(traceInterface.toEncoder.groups.map(_.bits.ilastsize)).asUInt
308
309    EnableClintAsyncBridge match {
310      case Some(param) =>
311        withClockAndReset(soc_clock, soc_reset_sync) {
312          val source = Module(new AsyncQueueSource(UInt(64.W), param))
313          source.io.enq.valid := io.clintTime.valid
314          source.io.enq.bits := io.clintTime.bits
315          core_with_l2.module.io.clintTime <> source.io.async
316        }
317      case None =>
318        core_with_l2.module.io.clintTime <> io.clintTime
319    }
320
321    EnableCHIAsyncBridge match {
322      case Some(param) =>
323        withClockAndReset(noc_clock.get, noc_reset_sync.get) {
324          val sink = Module(new CHIAsyncBridgeSink(param))
325          sink.io.async <> core_with_l2.module.io.chi
326          io.chi <> sink.io.deq
327        }
328      case None =>
329        io.chi <> core_with_l2.module.io.chi
330    }
331
332    // Seperate DebugModule TL Async Queue Sink
333    if (SeperateTLBus && EnableSeperateTLAsync) {
334      tlAsyncSinkOpt.get.module.clock := soc_clock
335      tlAsyncSinkOpt.get.module.reset := soc_reset_sync
336    }
337
338    core_with_l2.module.io.msiInfo.valid := wrapper.u_imsic_bus_top.module.o_msi_info_vld
339    core_with_l2.module.io.msiInfo.bits.info := wrapper.u_imsic_bus_top.module.o_msi_info
340    // tie off core soft reset
341    core_rst_node.out.head._1 := false.B.asAsyncReset
342
343    core_with_l2.module.io.debugTopDown.l3MissMatch := false.B
344    core_with_l2.module.io.l3Miss := false.B
345  }
346
347  lazy val module = new XSNoCTopImp(this)
348}
349
350class XSNoCDiffTop(implicit p: Parameters) extends Module {
351  override val desiredName: String = "XSDiffTop"
352  val l_soc = LazyModule(new XSNoCTop())
353  val soc = Module(l_soc.module)
354
355  // Expose XSTop IOs outside, i.e. io
356  def exposeIO(data: Data, name: String): Unit = {
357    val dummy = IO(chiselTypeOf(data)).suggestName(name)
358    dummy <> data
359  }
360  def exposeOptionIO(data: Option[Data], name: String): Unit = {
361    if (data.isDefined) {
362      val dummy = IO(chiselTypeOf(data.get)).suggestName(name)
363      dummy <> data.get
364    }
365  }
366  exposeIO(l_soc.clint, "clint")
367  exposeIO(l_soc.debug, "debug")
368  exposeIO(l_soc.plic, "plic")
369  exposeIO(l_soc.beu, "beu")
370  exposeIO(l_soc.nmi, "nmi")
371  soc.clock := clock
372  soc.reset := reset.asAsyncReset
373  exposeIO(soc.soc_clock, "soc_clock")
374  exposeIO(soc.soc_reset, "soc_reset")
375  exposeIO(soc.io, "io")
376  exposeOptionIO(soc.noc_clock, "noc_clock")
377  exposeOptionIO(soc.noc_reset, "noc_reset")
378  exposeOptionIO(soc.imsic_axi4lite, "imsic_axi4lite")
379
380  // TODO:
381  // XSDiffTop is only part of DUT, we can not instantiate difftest here.
382  // Temporarily we collect Performance counters for each DiffTop, need control signals passed from Difftest
383  val timer = IO(Input(UInt(64.W)))
384  val logEnable = IO(Input(Bool()))
385  val clean = IO(Input(Bool()))
386  val dump = IO(Input(Bool()))
387  XSLog.collect(timer, logEnable, clean, dump)
388  DifftestWiring.createAndConnectExtraIOs()
389  Profile.generateJson("XiangShan")
390  XSNoCDiffTopChecker()
391}
392
393// TODO:
394// Currently we use two-step XiangShan-Difftest, generating XS(with Diff Interface only) and Difftest seperately
395// To avoid potential interface problem between XS and Diff, we add Checker and CI(dual-core)
396// We will try one-step XS-Diff later
397object XSNoCDiffTopChecker {
398  def apply(): Unit = {
399    val verilog =
400      """
401        |`define CONFIG_XSCORE_NR 2
402        |`include "gateway_interface.svh"
403        |module XSDiffTopChecker(
404        | input                                 cpu_clk,
405        | input                                 cpu_rstn,
406        | input                                 sys_clk,
407        | input                                 sys_rstn
408        |);
409        |wire [63:0] timer;
410        |wire logEnable;
411        |wire clean;
412        |wire dump;
413        |// FIXME: use siganls from Difftest rather than default value
414        |assign timer = 64'b0;
415        |assign logEnable = 1'b0;
416        |assign clean = 1'b0;
417        |assign dump = 1'b0;
418        |gateway_if gateway_if_i();
419        |core_if core_if_o[`CONFIG_XSCORE_NR]();
420        |generate
421        |    genvar i;
422        |    for (i = 0; i < `CONFIG_XSCORE_NR; i = i+1)
423        |    begin: u_CPU_TOP
424        |    // FIXME: add missing ports
425        |    XSDiffTop u_XSTop (
426        |        .clock                   (cpu_clk),
427        |        .noc_clock               (sys_clk),
428        |        .soc_clock               (sys_clk),
429        |        .io_hartId               (6'h0 + i),
430        |        .timer                   (timer),
431        |        .logEnable               (logEnable),
432        |        .clean                   (clean),
433        |        .dump                    (dump),
434        |        .gateway_out             (core_if_o[i])
435        |    );
436        |    end
437        |endgenerate
438        |    CoreToGateway u_CoreToGateway(
439        |    .gateway_out (gateway_if_i.out),
440        |    .core_in (core_if_o)
441        |    );
442        |    GatewayEndpoint u_GatewayEndpoint(
443        |    .clock (sys_clk),
444        |    .reset (sys_rstn),
445        |    .gateway_in (gateway_if_i.in),
446        |    .step ()
447        |    );
448        |
449        |endmodule
450      """.stripMargin
451    FileRegisters.writeOutputFile("./build", "XSDiffTopChecker.sv", verilog)
452  }
453}
454