xref: /XiangShan/src/main/scala/xiangshan/L2Top.scala (revision c41f725a91c55e75c95c55b4bb0d2649f43e4c83)
1/***************************************************************************************
2  * Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3  * Copyright (c) 2020-2021 Peng Cheng Laboratory
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 xiangshan
18
19import chisel3._
20import chisel3.util._
21import org.chipsalliance.cde.config._
22import chisel3.util.{Valid, ValidIO}
23import freechips.rocketchip.diplomacy._
24import freechips.rocketchip.interrupts._
25import freechips.rocketchip.tile.{BusErrorUnit, BusErrorUnitParams, BusErrors, MaxHartIdBits}
26import freechips.rocketchip.tilelink._
27import device.MsiInfoBundle
28import coupledL2.{EnableCHI, L2ParamKey, PrefetchCtrlFromCore}
29import coupledL2.tl2tl.TL2TLCoupledL2
30import coupledL2.tl2chi.{CHIIssue, PortIO, TL2CHICoupledL2}
31import huancun.BankBitsKey
32import system.HasSoCParameter
33import top.BusPerfMonitor
34import utility._
35import xiangshan.cache.mmu.TlbRequestIO
36import xiangshan.backend.fu.PMPRespBundle
37import xiangshan.backend.trace.{Itype, TraceCoreInterface}
38
39class L1BusErrorUnitInfo(implicit val p: Parameters) extends Bundle with HasSoCParameter {
40  val ecc_error = Valid(UInt(soc.PAddrBits.W))
41}
42
43class XSL1BusErrors()(implicit val p: Parameters) extends BusErrors {
44  val icache = new L1BusErrorUnitInfo
45  val dcache = new L1BusErrorUnitInfo
46  val l2 = new L1BusErrorUnitInfo
47
48  override def toErrorList: List[Option[(ValidIO[UInt], String, String)]] =
49    List(
50      Some(icache.ecc_error, "I_ECC", "Icache ecc error"),
51      Some(dcache.ecc_error, "D_ECC", "Dcache ecc error"),
52      Some(l2.ecc_error, "L2_ECC", "L2Cache ecc error")
53    )
54}
55
56/**
57  *   L2Top contains everything between Core and XSTile-IO
58  */
59class L2TopInlined()(implicit p: Parameters) extends LazyModule
60  with HasXSParameter
61  with HasSoCParameter
62{
63  override def shouldBeInlined: Boolean = true
64
65  def chainBuffer(depth: Int, n: String): (Seq[LazyModule], TLNode) = {
66    val buffers = Seq.fill(depth){ LazyModule(new TLBuffer()) }
67    buffers.zipWithIndex.foreach{ case (b, i) => {
68      b.suggestName(s"${n}_${i}")
69    }}
70    val node = buffers.map(_.node.asInstanceOf[TLNode]).reduce(_ :*=* _)
71    (buffers, node)
72  }
73  val enableL2 = coreParams.L2CacheParamsOpt.isDefined
74  // =========== Components ============
75  val l1_xbar = TLXbar()
76  val mmio_xbar = TLXbar()
77  val mmio_port = TLIdentityNode() // to L3
78  val memory_port = if (enableCHI && enableL2) None else Some(TLIdentityNode())
79  val beu = LazyModule(new BusErrorUnit(
80    new XSL1BusErrors(),
81    BusErrorUnitParams(soc.BEURange.base, soc.BEURange.mask.toInt + 1)
82  ))
83
84  val i_mmio_port = TLTempNode()
85  val icachectrl_port_opt = if(icacheParameters.cacheCtrlAddressOpt.nonEmpty) Option(TLTempNode()) else None
86  val d_mmio_port = TLTempNode()
87
88  val misc_l2_pmu = BusPerfMonitor(name = "Misc_L2", enable = !debugOpts.FPGAPlatform) // l1D & l1I & PTW
89  val l2_l3_pmu = BusPerfMonitor(name = "L2_L3", enable = !debugOpts.FPGAPlatform && !enableCHI, stat_latency = true)
90  val xbar_l2_buffer = TLBuffer()
91
92  val enbale_tllog = !debugOpts.FPGAPlatform && debugOpts.AlwaysBasicDB
93  val l1d_logger = TLLogger(s"L2_L1D_${coreParams.HartId}", enbale_tllog)
94  val l1i_logger = TLLogger(s"L2_L1I_${coreParams.HartId}", enbale_tllog)
95  val ptw_logger = TLLogger(s"L2_PTW_${coreParams.HartId}", enbale_tllog)
96  val ptw_to_l2_buffer = LazyModule(new TLBuffer)
97  val i_mmio_buffer = LazyModule(new TLBuffer)
98
99  val clint_int_node = IntIdentityNode()
100  val debug_int_node = IntIdentityNode()
101  val plic_int_node = IntIdentityNode()
102  val nmi_int_node = IntIdentityNode()
103
104  println(s"enableCHI: ${enableCHI}")
105  val l2cache = if (enableL2) {
106    val config = new Config((_, _, _) => {
107      case L2ParamKey => coreParams.L2CacheParamsOpt.get.copy(
108        hartId = p(XSCoreParamsKey).HartId,
109        FPGAPlatform = debugOpts.FPGAPlatform
110      )
111      case EnableCHI => p(EnableCHI)
112      case CHIIssue => p(CHIIssue)
113      case BankBitsKey => log2Ceil(coreParams.L2NBanks)
114      case MaxHartIdBits => p(MaxHartIdBits)
115      case LogUtilsOptionsKey => p(LogUtilsOptionsKey)
116      case PerfCounterOptionsKey => p(PerfCounterOptionsKey)
117    })
118    if (enableCHI) Some(LazyModule(new TL2CHICoupledL2()(new Config(config))))
119    else Some(LazyModule(new TL2TLCoupledL2()(new Config(config))))
120  } else None
121  val l2_binder = coreParams.L2CacheParamsOpt.map(_ => BankBinder(coreParams.L2NBanks, 64))
122
123  // =========== Connection ============
124  // l2 to l2_binder, then to memory_port
125  l2cache match {
126    case Some(l2) =>
127      l2_binder.get :*= l2.node :*= xbar_l2_buffer :*= l1_xbar :=* misc_l2_pmu
128      l2 match {
129        case l2: TL2TLCoupledL2 =>
130          memory_port.get := l2_l3_pmu := TLClientsMerger() := TLXbar() :=* l2_binder.get
131        case l2: TL2CHICoupledL2 =>
132          l2.managerNode := TLXbar() :=* l2_binder.get
133          l2.mmioNode := mmio_port
134      }
135    case None =>
136      memory_port.get := l1_xbar
137  }
138
139  mmio_xbar := TLBuffer.chainNode(2) := i_mmio_port
140  mmio_xbar := TLBuffer.chainNode(2) := d_mmio_port
141  beu.node := TLBuffer.chainNode(1) := mmio_xbar
142  if (icacheParameters.cacheCtrlAddressOpt.nonEmpty) {
143    icachectrl_port_opt.get := TLBuffer.chainNode(1) := mmio_xbar
144  }
145
146  // filter out in-core addresses before sent to mmio_port
147  // Option[AddressSet] ++ Option[AddressSet] => List[AddressSet]
148  private def mmioFilters: Seq[AddressSet] =
149    (icacheParameters.cacheCtrlAddressOpt ++ dcacheParameters.cacheCtrlAddressOpt).toSeq
150  mmio_port :=
151    TLFilter(TLFilter.mSubtract(mmioFilters)) :=
152    TLBuffer() :=
153    mmio_xbar
154
155  class Imp(wrapper: LazyModule) extends LazyModuleImp(wrapper) {
156    val io = IO(new Bundle {
157      val beu_errors = Input(chiselTypeOf(beu.module.io.errors))
158      val reset_vector = new Bundle {
159        val fromTile = Input(UInt(PAddrBits.W))
160        val toCore = Output(UInt(PAddrBits.W))
161      }
162      val hartId = new Bundle() {
163        val fromTile = Input(UInt(64.W))
164        val toCore = Output(UInt(64.W))
165      }
166      val msiInfo = new Bundle() {
167        val fromTile = Input(ValidIO(new MsiInfoBundle))
168        val toCore = Output(ValidIO(new MsiInfoBundle))
169      }
170      val cpu_halt = new Bundle() {
171        val fromCore = Input(Bool())
172        val toTile = Output(Bool())
173      }
174      val cpu_poff = new Bundle() {
175        val fromCore = Input(Bool())
176        val toTile = Output(Bool())
177      }
178      val cpu_critical_error = new Bundle() {
179        val fromCore = Input(Bool())
180        val toTile = Output(Bool())
181      }
182      val hartIsInReset = new Bundle() {
183        val resetInFrontend = Input(Bool())
184        val toTile = Output(Bool())
185      }
186      val traceCoreInterface = new Bundle{
187        val fromCore = Flipped(new TraceCoreInterface)
188        val toTile   = new TraceCoreInterface
189      }
190      val debugTopDown = new Bundle() {
191        val robTrueCommit = Input(UInt(64.W))
192        val robHeadPaddr = Flipped(Valid(UInt(36.W)))
193        val l2MissMatch = Output(Bool())
194      }
195      val l2Miss = Output(Bool())
196      val l3Miss = new Bundle {
197        val fromTile = Input(Bool())
198        val toCore = Output(Bool())
199      }
200      val clintTime = new Bundle {
201        val fromTile = Input(ValidIO(UInt(64.W)))
202        val toCore = Output(ValidIO(UInt(64.W)))
203      }
204      val chi = if (enableCHI) Some(new PortIO) else None
205      val nodeID = if (enableCHI) Some(Input(UInt(NodeIDWidth.W))) else None
206      val pfCtrlFromCore = Input(new PrefetchCtrlFromCore)
207      val l2_tlb_req = new TlbRequestIO(nRespDups = 2)
208      val l2_pmp_resp = Flipped(new PMPRespBundle)
209      val l2_hint = ValidIO(new L2ToL1Hint())
210      val perfEvents = Output(Vec(numPCntHc * coreParams.L2NBanks + 1, new PerfEvent))
211      val l2_flush_en = Input(Bool())
212      val l2_flush_done = Output(Bool())
213      // val reset_core = IO(Output(Reset()))
214    })
215
216    val resetDelayN = Module(new DelayN(UInt(PAddrBits.W), 5))
217
218    beu.module.io.errors.icache := io.beu_errors.icache
219    beu.module.io.errors.dcache := io.beu_errors.dcache
220    resetDelayN.io.in := io.reset_vector.fromTile
221    io.reset_vector.toCore := resetDelayN.io.out
222    io.hartId.toCore := io.hartId.fromTile
223    io.msiInfo.toCore := io.msiInfo.fromTile
224    io.cpu_halt.toTile := io.cpu_halt.fromCore
225    io.cpu_poff.toTile := io.cpu_poff.fromCore
226    io.cpu_critical_error.toTile := io.cpu_critical_error.fromCore
227    io.l2_flush_done := true.B //TODO connect CoupleedL2
228    io.l3Miss.toCore := io.l3Miss.fromTile
229    io.clintTime.toCore := io.clintTime.fromTile
230    // trace interface
231    val traceToTile = io.traceCoreInterface.toTile
232    val traceFromCore = io.traceCoreInterface.fromCore
233    traceFromCore.fromEncoder := RegNext(traceToTile.fromEncoder)
234    traceToTile.toEncoder.trap := RegEnable(
235      traceFromCore.toEncoder.trap,
236      traceFromCore.toEncoder.groups(0).valid && Itype.isTrap(traceFromCore.toEncoder.groups(0).bits.itype)
237    )
238    traceToTile.toEncoder.priv := RegEnable(
239      traceFromCore.toEncoder.priv,
240      traceFromCore.toEncoder.groups(0).valid
241    )
242    (0 until TraceGroupNum).foreach{ i =>
243      traceToTile.toEncoder.groups(i).valid := RegNext(traceFromCore.toEncoder.groups(i).valid)
244      traceToTile.toEncoder.groups(i).bits.iretire := RegNext(traceFromCore.toEncoder.groups(i).bits.iretire)
245      traceToTile.toEncoder.groups(i).bits.itype := RegNext(traceFromCore.toEncoder.groups(i).bits.itype)
246      traceToTile.toEncoder.groups(i).bits.ilastsize := RegEnable(
247        traceFromCore.toEncoder.groups(i).bits.ilastsize,
248        traceFromCore.toEncoder.groups(i).valid
249      )
250      traceToTile.toEncoder.groups(i).bits.iaddr := RegEnable(
251        traceFromCore.toEncoder.groups(i).bits.iaddr,
252        traceFromCore.toEncoder.groups(i).valid
253      )
254    }
255
256    dontTouch(io.hartId)
257    dontTouch(io.cpu_halt)
258    dontTouch(io.cpu_critical_error)
259    if (!io.chi.isEmpty) { dontTouch(io.chi.get) }
260
261    val hartIsInReset = RegInit(true.B)
262    hartIsInReset := io.hartIsInReset.resetInFrontend || reset.asBool
263    io.hartIsInReset.toTile := hartIsInReset
264
265    if (l2cache.isDefined) {
266      val l2 = l2cache.get.module
267
268      l2.io.pfCtrlFromCore := io.pfCtrlFromCore
269      io.l2_hint := l2.io.l2_hint
270      l2.io.debugTopDown.robHeadPaddr := DontCare
271      l2.io.hartId := io.hartId.fromTile
272      l2.io.debugTopDown.robHeadPaddr := io.debugTopDown.robHeadPaddr
273      l2.io.debugTopDown.robTrueCommit := io.debugTopDown.robTrueCommit
274      io.debugTopDown.l2MissMatch := l2.io.debugTopDown.l2MissMatch
275      io.l2Miss := l2.io.l2Miss
276
277      /* l2 tlb */
278      io.l2_tlb_req.req.bits := DontCare
279      io.l2_tlb_req.req.valid := l2.io.l2_tlb_req.req.valid
280      io.l2_tlb_req.resp.ready := l2.io.l2_tlb_req.resp.ready
281      io.l2_tlb_req.req.bits.vaddr := l2.io.l2_tlb_req.req.bits.vaddr
282      io.l2_tlb_req.req.bits.cmd := l2.io.l2_tlb_req.req.bits.cmd
283      io.l2_tlb_req.req.bits.size := l2.io.l2_tlb_req.req.bits.size
284      io.l2_tlb_req.req.bits.kill := l2.io.l2_tlb_req.req.bits.kill
285      io.l2_tlb_req.req.bits.no_translate := l2.io.l2_tlb_req.req.bits.no_translate
286      io.l2_tlb_req.req_kill := l2.io.l2_tlb_req.req_kill
287      io.perfEvents := l2.io_perf
288
289      val allPerfEvents = l2.getPerfEvents
290      if (printEventCoding) {
291        for (((name, inc), i) <- allPerfEvents.zipWithIndex) {
292          println("L2 Cache perfEvents Set", name, inc, i)
293        }
294      }
295
296      l2.io.l2_tlb_req.resp.valid := io.l2_tlb_req.resp.valid
297      l2.io.l2_tlb_req.req.ready := io.l2_tlb_req.req.ready
298      l2.io.l2_tlb_req.resp.bits.paddr.head := io.l2_tlb_req.resp.bits.paddr.head
299      l2.io.l2_tlb_req.resp.bits.pbmt := io.l2_tlb_req.resp.bits.pbmt.head
300      l2.io.l2_tlb_req.resp.bits.miss := io.l2_tlb_req.resp.bits.miss
301      l2.io.l2_tlb_req.resp.bits.excp.head.gpf := io.l2_tlb_req.resp.bits.excp.head.gpf
302      l2.io.l2_tlb_req.resp.bits.excp.head.pf := io.l2_tlb_req.resp.bits.excp.head.pf
303      l2.io.l2_tlb_req.resp.bits.excp.head.af := io.l2_tlb_req.resp.bits.excp.head.af
304      l2.io.l2_tlb_req.pmp_resp.ld := io.l2_pmp_resp.ld
305      l2.io.l2_tlb_req.pmp_resp.st := io.l2_pmp_resp.st
306      l2.io.l2_tlb_req.pmp_resp.instr := io.l2_pmp_resp.instr
307      l2.io.l2_tlb_req.pmp_resp.mmio := io.l2_pmp_resp.mmio
308      l2.io.l2_tlb_req.pmp_resp.atomic := io.l2_pmp_resp.atomic
309      l2cache.get match {
310        case l2cache: TL2CHICoupledL2 =>
311          val l2 = l2cache.module
312          l2.io_nodeID := io.nodeID.get
313          io.chi.get <> l2.io_chi
314        case l2cache: TL2TLCoupledL2 =>
315      }
316
317      beu.module.io.errors.l2.ecc_error.valid := l2.io.error.valid
318      beu.module.io.errors.l2.ecc_error.bits := l2.io.error.address
319    } else {
320      io.l2_hint := 0.U.asTypeOf(io.l2_hint)
321      io.debugTopDown <> DontCare
322      io.l2Miss := false.B
323
324      io.l2_tlb_req.req.valid := false.B
325      io.l2_tlb_req.req.bits := DontCare
326      io.l2_tlb_req.req_kill := DontCare
327      io.l2_tlb_req.resp.ready := true.B
328      io.perfEvents := DontCare
329
330      beu.module.io.errors.l2 := 0.U.asTypeOf(beu.module.io.errors.l2)
331    }
332  }
333
334  lazy val module = new Imp(this)
335}
336
337class L2Top()(implicit p: Parameters) extends LazyModule
338  with HasXSParameter
339  with HasSoCParameter {
340
341  override def shouldBeInlined: Boolean = false
342
343  val inner = LazyModule(new L2TopInlined())
344
345  class Imp(wrapper: LazyModule) extends LazyModuleImp(wrapper) {
346    val io = IO(inner.module.io.cloneType)
347    val reset_core = IO(Output(Reset()))
348    io <> inner.module.io
349
350    if (debugOpts.ResetGen) {
351      ResetGen(ResetGenNode(Seq(
352        CellNode(reset_core),
353        ModuleNode(inner.module)
354      )), reset, sim = false)
355    } else {
356      reset_core := DontCare
357    }
358  }
359
360  lazy val module = new Imp(this)
361}
362