xref: /XiangShan/src/main/scala/xiangshan/mem/MemBlock.scala (revision c590fb326b3540db0e5d81d49ff03b6158012466)
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.mem
18
19import org.chipsalliance.cde.config.Parameters
20import chisel3._
21import chisel3.util._
22import freechips.rocketchip.diplomacy._
23import freechips.rocketchip.diplomacy.{BundleBridgeSource, LazyModule, LazyModuleImp}
24import freechips.rocketchip.interrupts.{IntSinkNode, IntSinkPortSimple}
25import freechips.rocketchip.tile.HasFPUParameters
26import freechips.rocketchip.tilelink._
27import device.MsiInfoBundle
28import utils._
29import utility._
30import system.SoCParamsKey
31import xiangshan._
32import xiangshan.ExceptionNO._
33import xiangshan.frontend.HasInstrMMIOConst
34import xiangshan.backend.Bundles.{DynInst, MemExuInput, MemExuOutput}
35import xiangshan.backend.ctrlblock.{DebugLSIO, LsTopdownInfo}
36import xiangshan.backend.exu.MemExeUnit
37import xiangshan.backend.fu._
38import xiangshan.backend.fu.FuType._
39import xiangshan.backend.fu.util.{HasCSRConst, SdtrigExt}
40import xiangshan.backend.{BackendToTopBundle, TopToBackendBundle}
41import xiangshan.backend.rob.{RobDebugRollingIO, RobPtr, RobLsqIO}
42import xiangshan.backend.datapath.NewPipelineConnect
43import xiangshan.backend.fu.NewCSR.{CsrTriggerBundle, TriggerUtil}
44import xiangshan.backend.trace.{Itype, TraceCoreInterface}
45import xiangshan.backend.Bundles._
46import xiangshan.mem._
47import xiangshan.mem.mdp._
48import xiangshan.mem.prefetch.{BasePrefecher, L1Prefetcher, SMSParams, SMSPrefetcher}
49import xiangshan.cache._
50import xiangshan.cache.mmu._
51import coupledL2.{PrefetchRecv}
52
53trait HasMemBlockParameters extends HasXSParameter {
54  // number of memory units
55  val LduCnt  = backendParams.LduCnt
56  val StaCnt  = backendParams.StaCnt
57  val StdCnt  = backendParams.StdCnt
58  val HyuCnt  = backendParams.HyuCnt
59  val VlduCnt = backendParams.VlduCnt
60  val VstuCnt = backendParams.VstuCnt
61
62  val LdExuCnt  = LduCnt + HyuCnt
63  val StAddrCnt = StaCnt + HyuCnt
64  val StDataCnt = StdCnt
65  val MemExuCnt = LduCnt + HyuCnt + StaCnt + StdCnt
66  val MemAddrExtCnt = LdExuCnt + StaCnt
67  val MemVExuCnt = VlduCnt + VstuCnt
68
69  val AtomicWBPort   = 0
70  val MisalignWBPort = 1
71  val UncacheWBPort  = 2
72  val NCWBPorts = Seq(1, 2)
73}
74
75abstract class MemBlockBundle(implicit val p: Parameters) extends Bundle with HasMemBlockParameters
76
77class Std(cfg: FuConfig)(implicit p: Parameters) extends FuncUnit(cfg) {
78  io.in.ready := io.out.ready
79  io.out.valid := io.in.valid
80  io.out.bits := 0.U.asTypeOf(io.out.bits)
81  io.out.bits.res.data := io.in.bits.data.src(0)
82  io.out.bits.ctrl.robIdx := io.in.bits.ctrl.robIdx
83}
84
85class ooo_to_mem(implicit p: Parameters) extends MemBlockBundle {
86  val backendToTopBypass = Flipped(new BackendToTopBundle)
87
88  val loadFastMatch = Vec(LdExuCnt, Input(UInt(LdExuCnt.W)))
89  val loadFastFuOpType = Vec(LdExuCnt, Input(FuOpType()))
90  val loadFastImm = Vec(LdExuCnt, Input(UInt(12.W)))
91  val sfence = Input(new SfenceBundle)
92  val tlbCsr = Input(new TlbCsrBundle)
93  val lsqio = new Bundle {
94    val lcommit = Input(UInt(log2Up(CommitWidth + 1).W))
95    val scommit = Input(UInt(log2Up(CommitWidth + 1).W))
96    val pendingMMIOld = Input(Bool())
97    val pendingld = Input(Bool())
98    val pendingst = Input(Bool())
99    val pendingVst = Input(Bool())
100    val commit = Input(Bool())
101    val pendingPtr = Input(new RobPtr)
102    val pendingPtrNext = Input(new RobPtr)
103  }
104
105  val isStoreException = Input(Bool())
106  val isVlsException = Input(Bool())
107  val csrCtrl = Flipped(new CustomCSRCtrlIO)
108  val enqLsq = new LsqEnqIO
109  val flushSb = Input(Bool())
110
111  val storePc = Vec(StaCnt, Input(UInt(VAddrBits.W))) // for hw prefetch
112  val hybridPc = Vec(HyuCnt, Input(UInt(VAddrBits.W))) // for hw prefetch
113
114  val issueLda = MixedVec(Seq.fill(LduCnt)(Flipped(DecoupledIO(new MemExuInput))))
115  val issueSta = MixedVec(Seq.fill(StaCnt)(Flipped(DecoupledIO(new MemExuInput))))
116  val issueStd = MixedVec(Seq.fill(StdCnt)(Flipped(DecoupledIO(new MemExuInput))))
117  val issueHya = MixedVec(Seq.fill(HyuCnt)(Flipped(DecoupledIO(new MemExuInput))))
118  val issueVldu = MixedVec(Seq.fill(VlduCnt)(Flipped(DecoupledIO(new MemExuInput(isVector=true)))))
119
120  def issueUops = issueLda ++ issueSta ++ issueStd ++ issueHya ++ issueVldu
121}
122
123class mem_to_ooo(implicit p: Parameters) extends MemBlockBundle {
124  val topToBackendBypass = new TopToBackendBundle
125
126  val otherFastWakeup = Vec(LdExuCnt, ValidIO(new DynInst))
127  val lqCancelCnt = Output(UInt(log2Up(VirtualLoadQueueSize + 1).W))
128  val sqCancelCnt = Output(UInt(log2Up(StoreQueueSize + 1).W))
129  val sqDeq = Output(UInt(log2Ceil(EnsbufferWidth + 1).W))
130  val lqDeq = Output(UInt(log2Up(CommitWidth + 1).W))
131  // used by VLSU issue queue, the vector store would wait all store before it, and the vector load would wait all load
132  val sqDeqPtr = Output(new SqPtr)
133  val lqDeqPtr = Output(new LqPtr)
134  val stIn = Vec(StAddrCnt, ValidIO(new MemExuInput))
135  val stIssuePtr = Output(new SqPtr())
136
137  val memoryViolation = ValidIO(new Redirect)
138  val sbIsEmpty = Output(Bool())
139
140  val lsTopdownInfo = Vec(LdExuCnt, Output(new LsTopdownInfo))
141
142  val lsqio = new Bundle {
143    val vaddr = Output(UInt(XLEN.W))
144    val vstart = Output(UInt((log2Up(VLEN) + 1).W))
145    val vl = Output(UInt((log2Up(VLEN) + 1).W))
146    val gpaddr = Output(UInt(XLEN.W))
147    val isForVSnonLeafPTE = Output(Bool())
148    val mmio = Output(Vec(LoadPipelineWidth, Bool()))
149    val uop = Output(Vec(LoadPipelineWidth, new DynInst))
150    val lqCanAccept = Output(Bool())
151    val sqCanAccept = Output(Bool())
152  }
153
154  val storeDebugInfo = Vec(EnsbufferWidth, new Bundle {
155    val robidx = Output(new RobPtr)
156    val pc     = Input(UInt(VAddrBits.W))
157  })
158
159  val writebackLda = Vec(LduCnt, DecoupledIO(new MemExuOutput))
160  val writebackSta = Vec(StaCnt, DecoupledIO(new MemExuOutput))
161  val writebackStd = Vec(StdCnt, DecoupledIO(new MemExuOutput))
162  val writebackHyuLda = Vec(HyuCnt, DecoupledIO(new MemExuOutput))
163  val writebackHyuSta = Vec(HyuCnt, DecoupledIO(new MemExuOutput))
164  val writebackVldu = Vec(VlduCnt, DecoupledIO(new MemExuOutput(isVector = true)))
165  def writeBack: Seq[DecoupledIO[MemExuOutput]] = {
166    writebackSta ++
167      writebackHyuLda ++ writebackHyuSta ++
168      writebackLda ++
169      writebackVldu ++
170      writebackStd
171  }
172
173  val ldaIqFeedback = Vec(LduCnt, new MemRSFeedbackIO)
174  val staIqFeedback = Vec(StaCnt, new MemRSFeedbackIO)
175  val hyuIqFeedback = Vec(HyuCnt, new MemRSFeedbackIO)
176  val vstuIqFeedback= Vec(VstuCnt, new MemRSFeedbackIO(isVector = true))
177  val vlduIqFeedback= Vec(VlduCnt, new MemRSFeedbackIO(isVector = true))
178  val ldCancel = Vec(backendParams.LdExuCnt, new LoadCancelIO)
179  val wakeup = Vec(backendParams.LdExuCnt, Valid(new DynInst))
180
181  val s3_delayed_load_error = Vec(LdExuCnt, Output(Bool()))
182}
183
184class MemCoreTopDownIO extends Bundle {
185  val robHeadMissInDCache = Output(Bool())
186  val robHeadTlbReplay = Output(Bool())
187  val robHeadTlbMiss = Output(Bool())
188  val robHeadLoadVio = Output(Bool())
189  val robHeadLoadMSHR = Output(Bool())
190}
191
192class fetch_to_mem(implicit p: Parameters) extends XSBundle{
193  val itlb = Flipped(new TlbPtwIO())
194}
195
196// triple buffer applied in i-mmio path (two at MemBlock, one at L2Top)
197class InstrUncacheBuffer()(implicit p: Parameters) extends LazyModule with HasInstrMMIOConst {
198  val node = new TLBufferNode(BufferParams.default, BufferParams.default, BufferParams.default, BufferParams.default, BufferParams.default)
199  lazy val module = new InstrUncacheBufferImpl
200
201  class InstrUncacheBufferImpl extends LazyModuleImp(this) {
202    (node.in zip node.out) foreach { case ((in, edgeIn), (out, edgeOut)) =>
203      out.a <> BufferParams.default(BufferParams.default(in.a))
204      in.d <> BufferParams.default(BufferParams.default(out.d))
205
206      // only a.valid, a.ready, a.address can change
207      // hoping that the rest would be optimized to keep MemBlock port unchanged after adding buffer
208      out.a.bits.data := 0.U
209      out.a.bits.mask := Fill(mmioBusBytes, 1.U(1.W))
210      out.a.bits.opcode := 4.U // Get
211      out.a.bits.size := log2Ceil(mmioBusBytes).U
212      out.a.bits.source := 0.U
213    }
214  }
215}
216
217// triple buffer applied in L1I$-L2 path (two at MemBlock, one at L2Top)
218class ICacheBuffer()(implicit p: Parameters) extends LazyModule {
219  val node = new TLBufferNode(BufferParams.default, BufferParams.default, BufferParams.default, BufferParams.default, BufferParams.default)
220  lazy val module = new ICacheBufferImpl
221
222  class ICacheBufferImpl extends LazyModuleImp(this) {
223    (node.in zip node.out) foreach { case ((in, edgeIn), (out, edgeOut)) =>
224      out.a <> BufferParams.default(BufferParams.default(in.a))
225      in.d <> BufferParams.default(BufferParams.default(out.d))
226    }
227  }
228}
229
230class ICacheCtrlBuffer()(implicit p: Parameters) extends LazyModule {
231  val node = new TLBufferNode(BufferParams.default, BufferParams.default, BufferParams.default, BufferParams.default, BufferParams.default)
232  lazy val module = new ICacheCtrlBufferImpl
233
234  class ICacheCtrlBufferImpl extends LazyModuleImp(this) {
235    (node.in zip node.out) foreach { case ((in, edgeIn), (out, edgeOut)) =>
236      out.a <> BufferParams.default(BufferParams.default(in.a))
237      in.d <> BufferParams.default(BufferParams.default(out.d))
238    }
239  }
240}
241
242// Frontend bus goes through MemBlock
243class FrontendBridge()(implicit p: Parameters) extends LazyModule {
244  val icache_node = LazyModule(new ICacheBuffer()).suggestName("icache").node// to keep IO port name
245  val icachectrl_node = LazyModule(new ICacheCtrlBuffer()).suggestName("icachectrl").node
246  val instr_uncache_node = LazyModule(new InstrUncacheBuffer()).suggestName("instr_uncache").node
247  lazy val module = new LazyModuleImp(this) {
248  }
249}
250
251class MemBlockInlined()(implicit p: Parameters) extends LazyModule
252  with HasXSParameter {
253  override def shouldBeInlined: Boolean = true
254
255  val dcache = LazyModule(new DCacheWrapper())
256  val uncache = LazyModule(new Uncache())
257  val uncache_port = TLTempNode()
258  val uncache_xbar = TLXbar()
259  val ptw = LazyModule(new L2TLBWrapper())
260  val ptw_to_l2_buffer = if (!coreParams.softPTW) LazyModule(new TLBuffer) else null
261  val l1d_to_l2_buffer = if (coreParams.dcacheParametersOpt.nonEmpty) LazyModule(new TLBuffer) else null
262  val dcache_port = TLNameNode("dcache_client") // to keep dcache-L2 port name
263  val l2_pf_sender_opt = coreParams.prefetcher.map(_ =>
264    BundleBridgeSource(() => new PrefetchRecv)
265  )
266  val l3_pf_sender_opt = if (p(SoCParamsKey).L3CacheParamsOpt.nonEmpty) coreParams.prefetcher.map(_ =>
267    BundleBridgeSource(() => new huancun.PrefetchRecv)
268  ) else None
269  val frontendBridge = LazyModule(new FrontendBridge)
270  // interrupt sinks
271  val clint_int_sink = IntSinkNode(IntSinkPortSimple(1, 2))
272  val debug_int_sink = IntSinkNode(IntSinkPortSimple(1, 1))
273  val plic_int_sink = IntSinkNode(IntSinkPortSimple(2, 1))
274  val nmi_int_sink = IntSinkNode(IntSinkPortSimple(1, (new NonmaskableInterruptIO).elements.size))
275
276  if (!coreParams.softPTW) {
277    ptw_to_l2_buffer.node := ptw.node
278  }
279  uncache_xbar := TLBuffer() := uncache.clientNode
280  if (dcache.uncacheNode.isDefined) {
281    dcache.uncacheNode.get := TLBuffer.chainNode(2) := uncache_xbar
282  }
283  uncache_port := TLBuffer.chainNode(2) := uncache_xbar
284
285  lazy val module = new MemBlockInlinedImp(this)
286}
287
288class MemBlockInlinedImp(outer: MemBlockInlined) extends LazyModuleImp(outer)
289  with HasXSParameter
290  with HasFPUParameters
291  with HasPerfEvents
292  with HasL1PrefetchSourceParameter
293  with HasCircularQueuePtrHelper
294  with HasMemBlockParameters
295  with HasTlbConst
296  with HasCSRConst
297  with SdtrigExt
298{
299  val io = IO(new Bundle {
300    val hartId = Input(UInt(hartIdLen.W))
301    val redirect = Flipped(ValidIO(new Redirect))
302
303    val ooo_to_mem = new ooo_to_mem
304    val mem_to_ooo = new mem_to_ooo
305    val fetch_to_mem = new fetch_to_mem
306
307    val ifetchPrefetch = Vec(LduCnt, ValidIO(new SoftIfetchPrefetchBundle))
308
309    // misc
310    val error = ValidIO(new L1CacheErrorInfo)
311    val memInfo = new Bundle {
312      val sqFull = Output(Bool())
313      val lqFull = Output(Bool())
314      val dcacheMSHRFull = Output(Bool())
315    }
316    val debug_ls = new DebugLSIO
317    val l2_hint = Input(Valid(new L2ToL1Hint()))
318    val l2PfqBusy = Input(Bool())
319    val l2_tlb_req = Flipped(new TlbRequestIO(nRespDups = 2))
320    val l2_pmp_resp = new PMPRespBundle
321    val l2_flush_done = Input(Bool())
322
323    val debugTopDown = new Bundle {
324      val robHeadVaddr = Flipped(Valid(UInt(VAddrBits.W)))
325      val toCore = new MemCoreTopDownIO
326    }
327    val debugRolling = Flipped(new RobDebugRollingIO)
328
329    // All the signals from/to frontend/backend to/from bus will go through MemBlock
330    val fromTopToBackend = Input(new Bundle {
331      val msiInfo   = ValidIO(new MsiInfoBundle)
332      val clintTime = ValidIO(UInt(64.W))
333    })
334    val inner_hartId = Output(UInt(hartIdLen.W))
335    val inner_reset_vector = Output(UInt(PAddrBits.W))
336    val outer_reset_vector = Input(UInt(PAddrBits.W))
337    val outer_cpu_halt = Output(Bool())
338    val outer_l2_flush_en = Output(Bool())
339    val outer_power_down_en = Output(Bool())
340    val outer_cpu_critical_error = Output(Bool())
341    val inner_beu_errors_icache = Input(new L1BusErrorUnitInfo)
342    val outer_beu_errors_icache = Output(new L1BusErrorUnitInfo)
343    val inner_hc_perfEvents = Output(Vec(numPCntHc * coreParams.L2NBanks + 1, new PerfEvent))
344    val outer_hc_perfEvents = Input(Vec(numPCntHc * coreParams.L2NBanks + 1, new PerfEvent))
345
346    // reset signals of frontend & backend are generated in memblock
347    val reset_backend = Output(Reset())
348    // Reset singal from frontend.
349    val resetInFrontendBypass = new Bundle{
350      val fromFrontend = Input(Bool())
351      val toL2Top      = Output(Bool())
352    }
353    val traceCoreInterfaceBypass = new Bundle{
354      val fromBackend = Flipped(new TraceCoreInterface(hasOffset = true))
355      val toL2Top     = new TraceCoreInterface
356    }
357
358    val topDownInfo = new Bundle {
359      val fromL2Top = Input(new TopDownFromL2Top)
360      val toBackend = Flipped(new TopDownInfo)
361    }
362  })
363
364  dontTouch(io.inner_hartId)
365  dontTouch(io.inner_reset_vector)
366  dontTouch(io.outer_reset_vector)
367  dontTouch(io.outer_cpu_halt)
368  dontTouch(io.outer_l2_flush_en)
369  dontTouch(io.outer_power_down_en)
370  dontTouch(io.outer_cpu_critical_error)
371  dontTouch(io.inner_beu_errors_icache)
372  dontTouch(io.outer_beu_errors_icache)
373  dontTouch(io.inner_hc_perfEvents)
374  dontTouch(io.outer_hc_perfEvents)
375
376  val redirect = RegNextWithEnable(io.redirect)
377
378  private val dcache = outer.dcache.module
379  val uncache = outer.uncache.module
380
381  //val delayedDcacheRefill = RegNext(dcache.io.lsu.lsq)
382
383  val csrCtrl = DelayN(io.ooo_to_mem.csrCtrl, 2)
384  dcache.io.l2_pf_store_only := RegNext(io.ooo_to_mem.csrCtrl.pf_ctrl.l2_pf_store_only, false.B)
385  io.error <> DelayNWithValid(dcache.io.error, 2)
386  when(!csrCtrl.cache_error_enable){
387    io.error.bits.report_to_beu := false.B
388    io.error.valid := false.B
389  }
390
391  val loadUnits = Seq.fill(LduCnt)(Module(new LoadUnit))
392  val storeUnits = Seq.fill(StaCnt)(Module(new StoreUnit))
393  val stdExeUnits = Seq.fill(StdCnt)(Module(new MemExeUnit(backendParams.memSchdParams.get.issueBlockParams.find(_.StdCnt != 0).get.exuBlockParams.head)))
394  val hybridUnits = Seq.fill(HyuCnt)(Module(new HybridUnit)) // Todo: replace it with HybridUnit
395  val stData = stdExeUnits.map(_.io.out)
396  val exeUnits = loadUnits ++ storeUnits
397
398  // The number of vector load/store units is decoupled with the number of load/store units
399  val vlSplit = Seq.fill(VlduCnt)(Module(new VLSplitImp))
400  val vsSplit = Seq.fill(VstuCnt)(Module(new VSSplitImp))
401  val vlMergeBuffer = Module(new VLMergeBufferImp)
402  val vsMergeBuffer = Seq.fill(VstuCnt)(Module(new VSMergeBufferImp))
403  val vSegmentUnit  = Module(new VSegmentUnit)
404  val vfofBuffer    = Module(new VfofBuffer)
405
406  // misalign Buffer
407  val loadMisalignBuffer = Module(new LoadMisalignBuffer)
408  val storeMisalignBuffer = Module(new StoreMisalignBuffer)
409
410  val l1_pf_req = Wire(Decoupled(new L1PrefetchReq()))
411  dcache.io.sms_agt_evict_req.ready := false.B
412  val prefetcherOpt: Option[BasePrefecher] = coreParams.prefetcher.map {
413    case _: SMSParams =>
414      val sms = Module(new SMSPrefetcher())
415      sms.io_agt_en := GatedRegNextN(io.ooo_to_mem.csrCtrl.pf_ctrl.l1D_pf_enable_agt, 2, Some(false.B))
416      sms.io_pht_en := GatedRegNextN(io.ooo_to_mem.csrCtrl.pf_ctrl.l1D_pf_enable_pht, 2, Some(false.B))
417      sms.io_act_threshold := GatedRegNextN(io.ooo_to_mem.csrCtrl.pf_ctrl.l1D_pf_active_threshold, 2, Some(12.U))
418      sms.io_act_stride := GatedRegNextN(io.ooo_to_mem.csrCtrl.pf_ctrl.l1D_pf_active_stride, 2, Some(30.U))
419      sms.io_stride_en := false.B
420      sms.io_dcache_evict <> dcache.io.sms_agt_evict_req
421      sms
422  }
423  prefetcherOpt.foreach{ pf => pf.io.l1_req.ready := false.B }
424  val hartId = p(XSCoreParamsKey).HartId
425  val l1PrefetcherOpt: Option[BasePrefecher] = coreParams.prefetcher.map {
426    case _ =>
427      val l1Prefetcher = Module(new L1Prefetcher())
428      l1Prefetcher.io.enable := Constantin.createRecord(s"enableL1StreamPrefetcher$hartId", initValue = true)
429      l1Prefetcher.pf_ctrl <> dcache.io.pf_ctrl
430      l1Prefetcher.l2PfqBusy := io.l2PfqBusy
431
432      // stride will train on miss or prefetch hit
433      for (i <- 0 until LduCnt) {
434        val source = loadUnits(i).io.prefetch_train_l1
435        l1Prefetcher.stride_train(i).valid := source.valid && source.bits.isFirstIssue && (
436          source.bits.miss || isFromStride(source.bits.meta_prefetch)
437        )
438        l1Prefetcher.stride_train(i).bits := source.bits
439        val loadPc = RegNext(io.ooo_to_mem.issueLda(i).bits.uop.pc) // for s1
440        l1Prefetcher.stride_train(i).bits.uop.pc := Mux(
441          loadUnits(i).io.s2_ptr_chasing,
442          RegEnable(loadPc, loadUnits(i).io.s2_prefetch_spec),
443          RegEnable(RegEnable(loadPc, loadUnits(i).io.s1_prefetch_spec), loadUnits(i).io.s2_prefetch_spec)
444        )
445      }
446      for (i <- 0 until HyuCnt) {
447        val source = hybridUnits(i).io.prefetch_train_l1
448        l1Prefetcher.stride_train.drop(LduCnt)(i).valid := source.valid && source.bits.isFirstIssue && (
449          source.bits.miss || isFromStride(source.bits.meta_prefetch)
450        )
451        l1Prefetcher.stride_train.drop(LduCnt)(i).bits := source.bits
452        l1Prefetcher.stride_train.drop(LduCnt)(i).bits.uop.pc := Mux(
453          hybridUnits(i).io.ldu_io.s2_ptr_chasing,
454          RegNext(io.ooo_to_mem.hybridPc(i)),
455          RegNext(RegNext(io.ooo_to_mem.hybridPc(i)))
456        )
457      }
458      l1Prefetcher
459  }
460  // load prefetch to l1 Dcache
461  l1PrefetcherOpt match {
462    case Some(pf) => l1_pf_req <> Pipeline(in = pf.io.l1_req, depth = 1, pipe = false, name = Some("pf_queue_to_ldu_reg"))
463    case None =>
464      l1_pf_req.valid := false.B
465      l1_pf_req.bits := DontCare
466  }
467  val pf_train_on_hit = RegNextN(io.ooo_to_mem.csrCtrl.pf_ctrl.l1D_pf_train_on_hit, 2, Some(true.B))
468
469  loadUnits.zipWithIndex.map(x => x._1.suggestName("LoadUnit_"+x._2))
470  storeUnits.zipWithIndex.map(x => x._1.suggestName("StoreUnit_"+x._2))
471  hybridUnits.zipWithIndex.map(x => x._1.suggestName("HybridUnit_"+x._2))
472  val atomicsUnit = Module(new AtomicsUnit)
473
474
475  val ldaExeWbReqs = Wire(Vec(LduCnt, Decoupled(new MemExuOutput)))
476  // atomicsUnit will overwrite the source from ldu if it is about to writeback
477  val atomicWritebackOverride = Mux(
478    atomicsUnit.io.out.valid,
479    atomicsUnit.io.out.bits,
480    loadUnits(AtomicWBPort).io.ldout.bits
481  )
482  ldaExeWbReqs(AtomicWBPort).valid := atomicsUnit.io.out.valid || loadUnits(AtomicWBPort).io.ldout.valid
483  ldaExeWbReqs(AtomicWBPort).bits  := atomicWritebackOverride
484  atomicsUnit.io.out.ready := ldaExeWbReqs(AtomicWBPort).ready
485  loadUnits(AtomicWBPort).io.ldout.ready := ldaExeWbReqs(AtomicWBPort).ready
486
487  val st_data_atomics = Seq.tabulate(StdCnt)(i =>
488    stData(i).valid && FuType.storeIsAMO(stData(i).bits.uop.fuType)
489  )
490
491  // misalignBuffer will overwrite the source from ldu if it is about to writeback
492  val misalignWritebackOverride = Mux(
493    loadUnits(MisalignWBPort).io.ldout.valid,
494    loadUnits(MisalignWBPort).io.ldout.bits,
495    loadMisalignBuffer.io.writeBack.bits
496  )
497  ldaExeWbReqs(MisalignWBPort).valid    := loadMisalignBuffer.io.writeBack.valid || loadUnits(MisalignWBPort).io.ldout.valid
498  ldaExeWbReqs(MisalignWBPort).bits     := misalignWritebackOverride
499  loadMisalignBuffer.io.writeBack.ready := ldaExeWbReqs(MisalignWBPort).ready && !loadUnits(MisalignWBPort).io.ldout.valid
500  loadMisalignBuffer.io.loadOutValid    := loadUnits(MisalignWBPort).io.ldout.valid
501  loadMisalignBuffer.io.loadVecOutValid := loadUnits(MisalignWBPort).io.vecldout.valid
502  loadUnits(MisalignWBPort).io.ldout.ready := ldaExeWbReqs(MisalignWBPort).ready
503  ldaExeWbReqs(MisalignWBPort).bits.isFromLoadUnit := loadUnits(MisalignWBPort).io.ldout.bits.isFromLoadUnit || loadMisalignBuffer.io.writeBack.valid
504
505  // loadUnit will overwrite the source from uncache if it is about to writeback
506  ldaExeWbReqs(UncacheWBPort) <> loadUnits(UncacheWBPort).io.ldout
507  io.mem_to_ooo.writebackLda <> ldaExeWbReqs
508  io.mem_to_ooo.writebackSta <> storeUnits.map(_.io.stout)
509  io.mem_to_ooo.writebackStd.zip(stdExeUnits).foreach {x =>
510    x._1.bits  := x._2.io.out.bits
511    // AMOs do not need to write back std now.
512    x._1.valid := x._2.io.out.fire && !FuType.storeIsAMO(x._2.io.out.bits.uop.fuType)
513  }
514  io.mem_to_ooo.writebackHyuLda <> hybridUnits.map(_.io.ldout)
515  io.mem_to_ooo.writebackHyuSta <> hybridUnits.map(_.io.stout)
516  io.mem_to_ooo.otherFastWakeup := DontCare
517  io.mem_to_ooo.otherFastWakeup.drop(HyuCnt).take(LduCnt).zip(loadUnits.map(_.io.fast_uop)).foreach{case(a,b)=> a := b}
518  io.mem_to_ooo.otherFastWakeup.take(HyuCnt).zip(hybridUnits.map(_.io.ldu_io.fast_uop)).foreach{case(a,b)=> a:=b}
519  val stOut = io.mem_to_ooo.writebackSta ++ io.mem_to_ooo.writebackHyuSta
520
521  // prefetch to l1 req
522  // Stream's confidence is always 1
523  // (LduCnt + HyuCnt) l1_pf_reqs ?
524  loadUnits.foreach(load_unit => {
525    load_unit.io.prefetch_req.valid <> l1_pf_req.valid
526    load_unit.io.prefetch_req.bits <> l1_pf_req.bits
527  })
528
529  hybridUnits.foreach(hybrid_unit => {
530    hybrid_unit.io.ldu_io.prefetch_req.valid <> l1_pf_req.valid
531    hybrid_unit.io.ldu_io.prefetch_req.bits <> l1_pf_req.bits
532  })
533
534  // NOTE: loadUnits(0) has higher bank conflict and miss queue arb priority than loadUnits(1) and loadUnits(2)
535  // when loadUnits(1)/loadUnits(2) stage 0 is busy, hw prefetch will never use that pipeline
536  val LowConfPorts = if (LduCnt == 2) Seq(1) else if (LduCnt == 3) Seq(1, 2) else Seq(0)
537  LowConfPorts.map{case i => loadUnits(i).io.prefetch_req.bits.confidence := 0.U}
538  hybridUnits.foreach(hybrid_unit => { hybrid_unit.io.ldu_io.prefetch_req.bits.confidence := 0.U })
539
540  val canAcceptHighConfPrefetch = loadUnits.map(_.io.canAcceptHighConfPrefetch) ++
541                                  hybridUnits.map(_.io.canAcceptLowConfPrefetch)
542  val canAcceptLowConfPrefetch = loadUnits.map(_.io.canAcceptLowConfPrefetch) ++
543                                 hybridUnits.map(_.io.canAcceptLowConfPrefetch)
544  l1_pf_req.ready := (0 until LduCnt + HyuCnt).map{
545    case i => {
546      if (LowConfPorts.contains(i)) {
547        loadUnits(i).io.canAcceptLowConfPrefetch
548      } else {
549        Mux(l1_pf_req.bits.confidence === 1.U, canAcceptHighConfPrefetch(i), canAcceptLowConfPrefetch(i))
550      }
551    }
552  }.reduce(_ || _)
553
554  // l1 pf fuzzer interface
555  val DebugEnableL1PFFuzzer = false
556  if (DebugEnableL1PFFuzzer) {
557    // l1 pf req fuzzer
558    val fuzzer = Module(new L1PrefetchFuzzer())
559    fuzzer.io.vaddr := DontCare
560    fuzzer.io.paddr := DontCare
561
562    // override load_unit prefetch_req
563    loadUnits.foreach(load_unit => {
564      load_unit.io.prefetch_req.valid <> fuzzer.io.req.valid
565      load_unit.io.prefetch_req.bits <> fuzzer.io.req.bits
566    })
567
568    // override hybrid_unit prefetch_req
569    hybridUnits.foreach(hybrid_unit => {
570      hybrid_unit.io.ldu_io.prefetch_req.valid <> fuzzer.io.req.valid
571      hybrid_unit.io.ldu_io.prefetch_req.bits <> fuzzer.io.req.bits
572    })
573
574    fuzzer.io.req.ready := l1_pf_req.ready
575  }
576
577  // TODO: fast load wakeup
578  val lsq     = Module(new LsqWrapper)
579  val sbuffer = Module(new Sbuffer)
580  // if you wants to stress test dcache store, use FakeSbuffer
581  // val sbuffer = Module(new FakeSbuffer) // out of date now
582  io.mem_to_ooo.stIssuePtr := lsq.io.issuePtrExt
583
584  dcache.io.hartId := io.hartId
585  lsq.io.hartId := io.hartId
586  sbuffer.io.hartId := io.hartId
587  atomicsUnit.io.hartId := io.hartId
588
589  dcache.io.lqEmpty := lsq.io.lqEmpty
590
591  // load/store prefetch to l2 cache
592  prefetcherOpt.foreach(sms_pf => {
593    l1PrefetcherOpt.foreach(l1_pf => {
594      val sms_pf_to_l2 = DelayNWithValid(sms_pf.io.l2_req, 2)
595      val l1_pf_to_l2 = DelayNWithValid(l1_pf.io.l2_req, 2)
596
597      outer.l2_pf_sender_opt.get.out.head._1.addr_valid := sms_pf_to_l2.valid || l1_pf_to_l2.valid
598      outer.l2_pf_sender_opt.get.out.head._1.addr := Mux(l1_pf_to_l2.valid, l1_pf_to_l2.bits.addr, sms_pf_to_l2.bits.addr)
599      outer.l2_pf_sender_opt.get.out.head._1.pf_source := Mux(l1_pf_to_l2.valid, l1_pf_to_l2.bits.source, sms_pf_to_l2.bits.source)
600      outer.l2_pf_sender_opt.get.out.head._1.l2_pf_en := RegNextN(io.ooo_to_mem.csrCtrl.pf_ctrl.l2_pf_enable, 2, Some(true.B))
601
602      sms_pf.io.enable := RegNextN(io.ooo_to_mem.csrCtrl.pf_ctrl.l1D_pf_enable, 2, Some(false.B))
603
604      val l2_trace = Wire(new LoadPfDbBundle)
605      l2_trace.paddr := outer.l2_pf_sender_opt.get.out.head._1.addr
606      val table = ChiselDB.createTable(s"L2PrefetchTrace$hartId", new LoadPfDbBundle, basicDB = false)
607      table.log(l2_trace, l1_pf_to_l2.valid, "StreamPrefetchTrace", clock, reset)
608      table.log(l2_trace, !l1_pf_to_l2.valid && sms_pf_to_l2.valid, "L2PrefetchTrace", clock, reset)
609
610      val l1_pf_to_l3 = ValidIODelay(l1_pf.io.l3_req, 4)
611      outer.l3_pf_sender_opt.foreach(_.out.head._1.addr_valid := l1_pf_to_l3.valid)
612      outer.l3_pf_sender_opt.foreach(_.out.head._1.addr := l1_pf_to_l3.bits)
613      outer.l3_pf_sender_opt.foreach(_.out.head._1.l2_pf_en := RegNextN(io.ooo_to_mem.csrCtrl.pf_ctrl.l2_pf_enable, 4, Some(true.B)))
614
615      val l3_trace = Wire(new LoadPfDbBundle)
616      l3_trace.paddr := outer.l3_pf_sender_opt.map(_.out.head._1.addr).getOrElse(0.U)
617      val l3_table = ChiselDB.createTable(s"L3PrefetchTrace$hartId", new LoadPfDbBundle, basicDB = false)
618      l3_table.log(l3_trace, l1_pf_to_l3.valid, "StreamPrefetchTrace", clock, reset)
619
620      XSPerfAccumulate("prefetch_fire_l2", outer.l2_pf_sender_opt.get.out.head._1.addr_valid)
621      XSPerfAccumulate("prefetch_fire_l3", outer.l3_pf_sender_opt.map(_.out.head._1.addr_valid).getOrElse(false.B))
622      XSPerfAccumulate("l1pf_fire_l2", l1_pf_to_l2.valid)
623      XSPerfAccumulate("sms_fire_l2", !l1_pf_to_l2.valid && sms_pf_to_l2.valid)
624      XSPerfAccumulate("sms_block_by_l1pf", l1_pf_to_l2.valid && sms_pf_to_l2.valid)
625    })
626  })
627
628  // ptw
629  val sfence = RegNext(RegNext(io.ooo_to_mem.sfence))
630  val tlbcsr = RegNext(RegNext(io.ooo_to_mem.tlbCsr))
631  private val ptw = outer.ptw.module
632  private val ptw_to_l2_buffer = outer.ptw_to_l2_buffer.module
633  private val l1d_to_l2_buffer = outer.l1d_to_l2_buffer.module
634  ptw.io.hartId := io.hartId
635  ptw.io.sfence <> sfence
636  ptw.io.csr.tlb <> tlbcsr
637  ptw.io.csr.distribute_csr <> csrCtrl.distribute_csr
638
639  val perfEventsPTW = if (!coreParams.softPTW) {
640    ptw.getPerfEvents
641  } else {
642    Seq()
643  }
644
645  // dtlb
646  val dtlb_ld_tlb_ld = Module(new TLBNonBlock(LduCnt + HyuCnt + 1, 2, ldtlbParams))
647  val dtlb_st_tlb_st = Module(new TLBNonBlock(StaCnt, 1, sttlbParams))
648  val dtlb_prefetch_tlb_prefetch = Module(new TLBNonBlock(2, 2, pftlbParams))
649  val dtlb_ld = Seq(dtlb_ld_tlb_ld.io)
650  val dtlb_st = Seq(dtlb_st_tlb_st.io)
651  val dtlb_prefetch = Seq(dtlb_prefetch_tlb_prefetch.io)
652  /* tlb vec && constant variable */
653  val dtlb = dtlb_ld ++ dtlb_st ++ dtlb_prefetch
654  val (dtlb_ld_idx, dtlb_st_idx, dtlb_pf_idx) = (0, 1, 2)
655  val TlbSubSizeVec = Seq(LduCnt + HyuCnt + 1, StaCnt, 2) // (load + hyu + stream pf, store, sms+l2bop)
656  val DTlbSize = TlbSubSizeVec.sum
657  val TlbStartVec = TlbSubSizeVec.scanLeft(0)(_ + _).dropRight(1)
658  val TlbEndVec = TlbSubSizeVec.scanLeft(0)(_ + _).drop(1)
659
660  val ptwio = Wire(new VectorTlbPtwIO(DTlbSize))
661  val dtlb_reqs = dtlb.map(_.requestor).flatten
662  val dtlb_pmps = dtlb.map(_.pmp).flatten
663  dtlb.map(_.hartId := io.hartId)
664  dtlb.map(_.sfence := sfence)
665  dtlb.map(_.csr := tlbcsr)
666  dtlb.map(_.flushPipe.map(a => a := false.B)) // non-block doesn't need
667  dtlb.map(_.redirect := redirect)
668  if (refillBothTlb) {
669    require(ldtlbParams.outReplace == sttlbParams.outReplace)
670    require(ldtlbParams.outReplace == hytlbParams.outReplace)
671    require(ldtlbParams.outReplace == pftlbParams.outReplace)
672    require(ldtlbParams.outReplace)
673
674    val replace = Module(new TlbReplace(DTlbSize, ldtlbParams))
675    replace.io.apply_sep(dtlb_ld.map(_.replace) ++ dtlb_st.map(_.replace) ++ dtlb_prefetch.map(_.replace), ptwio.resp.bits.data.s1.entry.tag)
676  } else {
677    // TODO: there will be bugs in TlbReplace when outReplace enable, since the order of Hyu is not right.
678    if (ldtlbParams.outReplace) {
679      val replace_ld = Module(new TlbReplace(LduCnt + 1, ldtlbParams))
680      replace_ld.io.apply_sep(dtlb_ld.map(_.replace), ptwio.resp.bits.data.s1.entry.tag)
681    }
682    if (hytlbParams.outReplace) {
683      val replace_hy = Module(new TlbReplace(HyuCnt, hytlbParams))
684      replace_hy.io.apply_sep(dtlb_ld.map(_.replace), ptwio.resp.bits.data.s1.entry.tag)
685    }
686    if (sttlbParams.outReplace) {
687      val replace_st = Module(new TlbReplace(StaCnt, sttlbParams))
688      replace_st.io.apply_sep(dtlb_st.map(_.replace), ptwio.resp.bits.data.s1.entry.tag)
689    }
690    if (pftlbParams.outReplace) {
691      val replace_pf = Module(new TlbReplace(2, pftlbParams))
692      replace_pf.io.apply_sep(dtlb_prefetch.map(_.replace), ptwio.resp.bits.data.s1.entry.tag)
693    }
694  }
695
696  val ptw_resp_next = RegEnable(ptwio.resp.bits, ptwio.resp.valid)
697  val ptw_resp_v = RegNext(ptwio.resp.valid && !(sfence.valid && tlbcsr.satp.changed && tlbcsr.vsatp.changed && tlbcsr.hgatp.changed), init = false.B)
698  ptwio.resp.ready := true.B
699
700  val tlbreplay = WireInit(VecInit(Seq.fill(LdExuCnt)(false.B)))
701  val tlbreplay_reg = GatedValidRegNext(tlbreplay)
702  val dtlb_ld0_tlbreplay_reg = GatedValidRegNext(dtlb_ld(0).tlbreplay)
703
704  if (backendParams.debugEn){ dontTouch(tlbreplay) }
705
706  for (i <- 0 until LdExuCnt) {
707    tlbreplay(i) := dtlb_ld(0).ptw.req(i).valid && ptw_resp_next.vector(0) && ptw_resp_v &&
708      ptw_resp_next.data.hit(dtlb_ld(0).ptw.req(i).bits.vpn, tlbcsr.satp.asid, tlbcsr.vsatp.asid, tlbcsr.hgatp.vmid, allType = true, ignoreAsid = true)
709  }
710
711  dtlb.flatMap(a => a.ptw.req)
712    .zipWithIndex
713    .foreach{ case (tlb, i) =>
714      tlb.ready := ptwio.req(i).ready
715      ptwio.req(i).bits := tlb.bits
716    val vector_hit = if (refillBothTlb) Cat(ptw_resp_next.vector).orR
717      else if (i < TlbEndVec(dtlb_ld_idx)) Cat(ptw_resp_next.vector.slice(TlbStartVec(dtlb_ld_idx), TlbEndVec(dtlb_ld_idx))).orR
718      else if (i < TlbEndVec(dtlb_st_idx)) Cat(ptw_resp_next.vector.slice(TlbStartVec(dtlb_st_idx), TlbEndVec(dtlb_st_idx))).orR
719      else                                 Cat(ptw_resp_next.vector.slice(TlbStartVec(dtlb_pf_idx), TlbEndVec(dtlb_pf_idx))).orR
720    ptwio.req(i).valid := tlb.valid && !(ptw_resp_v && vector_hit && ptw_resp_next.data.hit(tlb.bits.vpn, tlbcsr.satp.asid, tlbcsr.vsatp.asid, tlbcsr.hgatp.vmid, allType = true, ignoreAsid = true))
721  }
722  dtlb.foreach(_.ptw.resp.bits := ptw_resp_next.data)
723  if (refillBothTlb) {
724    dtlb.foreach(_.ptw.resp.valid := ptw_resp_v && Cat(ptw_resp_next.vector).orR)
725  } else {
726    dtlb_ld.foreach(_.ptw.resp.valid := ptw_resp_v && Cat(ptw_resp_next.vector.slice(TlbStartVec(dtlb_ld_idx), TlbEndVec(dtlb_ld_idx))).orR)
727    dtlb_st.foreach(_.ptw.resp.valid := ptw_resp_v && Cat(ptw_resp_next.vector.slice(TlbStartVec(dtlb_st_idx), TlbEndVec(dtlb_st_idx))).orR)
728    dtlb_prefetch.foreach(_.ptw.resp.valid := ptw_resp_v && Cat(ptw_resp_next.vector.slice(TlbStartVec(dtlb_pf_idx), TlbEndVec(dtlb_pf_idx))).orR)
729  }
730  dtlb_ld.foreach(_.ptw.resp.bits.getGpa := Cat(ptw_resp_next.getGpa.take(LduCnt + HyuCnt + 1)).orR)
731  dtlb_st.foreach(_.ptw.resp.bits.getGpa := Cat(ptw_resp_next.getGpa.slice(LduCnt + HyuCnt + 1, LduCnt + HyuCnt + 1 + StaCnt)).orR)
732  dtlb_prefetch.foreach(_.ptw.resp.bits.getGpa := Cat(ptw_resp_next.getGpa.drop(LduCnt + HyuCnt + 1 + StaCnt)).orR)
733
734  val dtlbRepeater  = PTWNewFilter(ldtlbParams.fenceDelay, ptwio, ptw.io.tlb(1), sfence, tlbcsr, l2tlbParams.dfilterSize)
735  val itlbRepeater3 = PTWRepeaterNB(passReady = false, itlbParams.fenceDelay, io.fetch_to_mem.itlb, ptw.io.tlb(0), sfence, tlbcsr)
736
737  lsq.io.debugTopDown.robHeadMissInDTlb := dtlbRepeater.io.rob_head_miss_in_tlb
738
739  // pmp
740  val pmp = Module(new PMP())
741  pmp.io.distribute_csr <> csrCtrl.distribute_csr
742
743  val pmp_checkers = Seq.fill(DTlbSize)(Module(new PMPChecker(4, leaveHitMux = true)))
744  val pmp_check = pmp_checkers.map(_.io)
745  for ((p,d) <- pmp_check zip dtlb_pmps) {
746    p.apply(tlbcsr.priv.dmode, pmp.io.pmp, pmp.io.pma, d)
747    require(p.req.bits.size.getWidth == d.bits.size.getWidth)
748  }
749
750  for (i <- 0 until LduCnt) {
751    io.debug_ls.debugLsInfo(i) := loadUnits(i).io.debug_ls
752  }
753  for (i <- 0 until HyuCnt) {
754    io.debug_ls.debugLsInfo.drop(LduCnt)(i) := hybridUnits(i).io.ldu_io.debug_ls
755  }
756  for (i <- 0 until StaCnt) {
757    io.debug_ls.debugLsInfo.drop(LduCnt + HyuCnt)(i) := storeUnits(i).io.debug_ls
758  }
759  for (i <- 0 until HyuCnt) {
760    io.debug_ls.debugLsInfo.drop(LduCnt + HyuCnt + StaCnt)(i) := hybridUnits(i).io.stu_io.debug_ls
761  }
762
763  io.mem_to_ooo.lsTopdownInfo := loadUnits.map(_.io.lsTopdownInfo) ++ hybridUnits.map(_.io.ldu_io.lsTopdownInfo)
764
765  // trigger
766  val tdata = RegInit(VecInit(Seq.fill(TriggerNum)(0.U.asTypeOf(new MatchTriggerIO))))
767  val tEnable = RegInit(VecInit(Seq.fill(TriggerNum)(false.B)))
768  tEnable := csrCtrl.mem_trigger.tEnableVec
769  when(csrCtrl.mem_trigger.tUpdate.valid) {
770    tdata(csrCtrl.mem_trigger.tUpdate.bits.addr) := csrCtrl.mem_trigger.tUpdate.bits.tdata
771  }
772  val triggerCanRaiseBpExp = csrCtrl.mem_trigger.triggerCanRaiseBpExp
773  val debugMode = csrCtrl.mem_trigger.debugMode
774
775  val backendTriggerTimingVec = VecInit(tdata.map(_.timing))
776  val backendTriggerChainVec = VecInit(tdata.map(_.chain))
777
778  XSDebug(tEnable.asUInt.orR, "Debug Mode: At least one store trigger is enabled\n")
779  for (j <- 0 until TriggerNum)
780    PrintTriggerInfo(tEnable(j), tdata(j))
781
782  // The segment instruction is executed atomically.
783  // After the segment instruction directive starts executing, no other instructions should be executed.
784  val vSegmentFlag = RegInit(false.B)
785
786  when(GatedValidRegNext(vSegmentUnit.io.in.fire)) {
787    vSegmentFlag := true.B
788  }.elsewhen(GatedValidRegNext(vSegmentUnit.io.uopwriteback.valid)) {
789    vSegmentFlag := false.B
790  }
791
792  // LoadUnit
793  val correctMissTrain = Constantin.createRecord(s"CorrectMissTrain$hartId", initValue = false)
794
795  for (i <- 0 until LduCnt) {
796    loadUnits(i).io.redirect <> redirect
797
798    // get input form dispatch
799    loadUnits(i).io.ldin <> io.ooo_to_mem.issueLda(i)
800    loadUnits(i).io.feedback_slow <> io.mem_to_ooo.ldaIqFeedback(i).feedbackSlow
801    io.mem_to_ooo.ldaIqFeedback(i).feedbackFast := DontCare
802    loadUnits(i).io.correctMissTrain := correctMissTrain
803    io.mem_to_ooo.ldCancel.drop(HyuCnt)(i) := loadUnits(i).io.ldCancel
804    io.mem_to_ooo.wakeup.drop(HyuCnt)(i) := loadUnits(i).io.wakeup
805
806    // vector
807    if (i < VlduCnt) {
808      loadUnits(i).io.vecldout.ready := false.B
809    } else {
810      loadUnits(i).io.vecldin.valid := false.B
811      loadUnits(i).io.vecldin.bits := DontCare
812      loadUnits(i).io.vecldout.ready := false.B
813    }
814
815    // fast replay
816    loadUnits(i).io.fast_rep_in <> loadUnits(i).io.fast_rep_out
817
818    // SoftPrefetch to frontend (prefetch.i)
819    loadUnits(i).io.ifetchPrefetch <> io.ifetchPrefetch(i)
820
821    // dcache access
822    loadUnits(i).io.dcache <> dcache.io.lsu.load(i)
823    if(i == 0){
824      vSegmentUnit.io.rdcache := DontCare
825      dcache.io.lsu.load(i).req.valid := loadUnits(i).io.dcache.req.valid || vSegmentUnit.io.rdcache.req.valid
826      dcache.io.lsu.load(i).req.bits  := Mux1H(Seq(
827        vSegmentUnit.io.rdcache.req.valid -> vSegmentUnit.io.rdcache.req.bits,
828        loadUnits(i).io.dcache.req.valid -> loadUnits(i).io.dcache.req.bits
829      ))
830      vSegmentUnit.io.rdcache.req.ready := dcache.io.lsu.load(i).req.ready
831    }
832
833    // Dcache requests must also be preempted by the segment.
834    when(vSegmentFlag){
835      loadUnits(i).io.dcache.req.ready             := false.B // Dcache is preempted.
836
837      dcache.io.lsu.load(0).pf_source              := vSegmentUnit.io.rdcache.pf_source
838      dcache.io.lsu.load(0).s1_paddr_dup_lsu       := vSegmentUnit.io.rdcache.s1_paddr_dup_lsu
839      dcache.io.lsu.load(0).s1_paddr_dup_dcache    := vSegmentUnit.io.rdcache.s1_paddr_dup_dcache
840      dcache.io.lsu.load(0).s1_kill                := vSegmentUnit.io.rdcache.s1_kill
841      dcache.io.lsu.load(0).s2_kill                := vSegmentUnit.io.rdcache.s2_kill
842      dcache.io.lsu.load(0).s0_pc                  := vSegmentUnit.io.rdcache.s0_pc
843      dcache.io.lsu.load(0).s1_pc                  := vSegmentUnit.io.rdcache.s1_pc
844      dcache.io.lsu.load(0).s2_pc                  := vSegmentUnit.io.rdcache.s2_pc
845      dcache.io.lsu.load(0).is128Req               := vSegmentUnit.io.rdcache.is128Req
846    }.otherwise {
847      loadUnits(i).io.dcache.req.ready             := dcache.io.lsu.load(i).req.ready
848
849      dcache.io.lsu.load(0).pf_source              := loadUnits(0).io.dcache.pf_source
850      dcache.io.lsu.load(0).s1_paddr_dup_lsu       := loadUnits(0).io.dcache.s1_paddr_dup_lsu
851      dcache.io.lsu.load(0).s1_paddr_dup_dcache    := loadUnits(0).io.dcache.s1_paddr_dup_dcache
852      dcache.io.lsu.load(0).s1_kill                := loadUnits(0).io.dcache.s1_kill
853      dcache.io.lsu.load(0).s2_kill                := loadUnits(0).io.dcache.s2_kill
854      dcache.io.lsu.load(0).s0_pc                  := loadUnits(0).io.dcache.s0_pc
855      dcache.io.lsu.load(0).s1_pc                  := loadUnits(0).io.dcache.s1_pc
856      dcache.io.lsu.load(0).s2_pc                  := loadUnits(0).io.dcache.s2_pc
857      dcache.io.lsu.load(0).is128Req               := loadUnits(0).io.dcache.is128Req
858    }
859
860    // forward
861    loadUnits(i).io.lsq.forward <> lsq.io.forward(i)
862    loadUnits(i).io.sbuffer <> sbuffer.io.forward(i)
863    loadUnits(i).io.ubuffer <> uncache.io.forward(i)
864    loadUnits(i).io.tl_d_channel := dcache.io.lsu.forward_D(i)
865    loadUnits(i).io.forward_mshr <> dcache.io.lsu.forward_mshr(i)
866    // ld-ld violation check
867    loadUnits(i).io.lsq.ldld_nuke_query <> lsq.io.ldu.ldld_nuke_query(i)
868    loadUnits(i).io.lsq.stld_nuke_query <> lsq.io.ldu.stld_nuke_query(i)
869    loadUnits(i).io.csrCtrl       <> csrCtrl
870    // dcache refill req
871  // loadUnits(i).io.refill           <> delayedDcacheRefill
872    // dtlb
873    loadUnits(i).io.tlb <> dtlb_reqs.take(LduCnt)(i)
874    if(i == 0 ){ // port 0 assign to vsegmentUnit
875      val vsegmentDtlbReqValid = vSegmentUnit.io.dtlb.req.valid // segment tlb resquest need to delay 1 cycle
876      dtlb_reqs.take(LduCnt)(i).req.valid := loadUnits(i).io.tlb.req.valid || RegNext(vsegmentDtlbReqValid)
877      vSegmentUnit.io.dtlb.req.ready      := dtlb_reqs.take(LduCnt)(i).req.ready
878      dtlb_reqs.take(LduCnt)(i).req.bits  := ParallelPriorityMux(Seq(
879        RegNext(vsegmentDtlbReqValid)     -> RegEnable(vSegmentUnit.io.dtlb.req.bits, vsegmentDtlbReqValid),
880        loadUnits(i).io.tlb.req.valid     -> loadUnits(i).io.tlb.req.bits
881      ))
882    }
883    // pmp
884    loadUnits(i).io.pmp <> pmp_check(i).resp
885    // st-ld violation query
886    val stld_nuke_query = storeUnits.map(_.io.stld_nuke_query) ++ hybridUnits.map(_.io.stu_io.stld_nuke_query)
887    for (s <- 0 until StorePipelineWidth) {
888      loadUnits(i).io.stld_nuke_query(s) := stld_nuke_query(s)
889    }
890    loadUnits(i).io.lq_rep_full <> lsq.io.lq_rep_full
891    // load prefetch train
892    prefetcherOpt.foreach(pf => {
893      // sms will train on all miss load sources
894      val source = loadUnits(i).io.prefetch_train
895      pf.io.ld_in(i).valid := Mux(pf_train_on_hit,
896        source.valid,
897        source.valid && source.bits.isFirstIssue && source.bits.miss
898      )
899      pf.io.ld_in(i).bits := source.bits
900      val loadPc = RegNext(io.ooo_to_mem.issueLda(i).bits.uop.pc) // for s1
901      pf.io.ld_in(i).bits.uop.pc := Mux(
902        loadUnits(i).io.s2_ptr_chasing,
903        RegEnable(loadPc, loadUnits(i).io.s2_prefetch_spec),
904        RegEnable(RegEnable(loadPc, loadUnits(i).io.s1_prefetch_spec), loadUnits(i).io.s2_prefetch_spec)
905      )
906    })
907    l1PrefetcherOpt.foreach(pf => {
908      // stream will train on all load sources
909      val source = loadUnits(i).io.prefetch_train_l1
910      pf.io.ld_in(i).valid := source.valid && source.bits.isFirstIssue
911      pf.io.ld_in(i).bits := source.bits
912    })
913
914    // load to load fast forward: load(i) prefers data(i)
915    val l2l_fwd_out = loadUnits.map(_.io.l2l_fwd_out) ++ hybridUnits.map(_.io.ldu_io.l2l_fwd_out)
916    val fastPriority = (i until LduCnt + HyuCnt) ++ (0 until i)
917    val fastValidVec = fastPriority.map(j => l2l_fwd_out(j).valid)
918    val fastDataVec = fastPriority.map(j => l2l_fwd_out(j).data)
919    val fastErrorVec = fastPriority.map(j => l2l_fwd_out(j).dly_ld_err)
920    val fastMatchVec = fastPriority.map(j => io.ooo_to_mem.loadFastMatch(i)(j))
921    loadUnits(i).io.l2l_fwd_in.valid := VecInit(fastValidVec).asUInt.orR
922    loadUnits(i).io.l2l_fwd_in.data := ParallelPriorityMux(fastValidVec, fastDataVec)
923    loadUnits(i).io.l2l_fwd_in.dly_ld_err := ParallelPriorityMux(fastValidVec, fastErrorVec)
924    val fastMatch = ParallelPriorityMux(fastValidVec, fastMatchVec)
925    loadUnits(i).io.ld_fast_match := fastMatch
926    loadUnits(i).io.ld_fast_imm := io.ooo_to_mem.loadFastImm(i)
927    loadUnits(i).io.ld_fast_fuOpType := io.ooo_to_mem.loadFastFuOpType(i)
928    loadUnits(i).io.replay <> lsq.io.replay(i)
929
930    val l2_hint = RegNext(io.l2_hint)
931
932    // L2 Hint for DCache
933    dcache.io.l2_hint <> l2_hint
934
935    loadUnits(i).io.l2_hint <> l2_hint
936    loadUnits(i).io.tlb_hint.id := dtlbRepeater.io.hint.get.req(i).id
937    loadUnits(i).io.tlb_hint.full := dtlbRepeater.io.hint.get.req(i).full ||
938      tlbreplay_reg(i) || dtlb_ld0_tlbreplay_reg(i)
939
940    // passdown to lsq (load s2)
941    lsq.io.ldu.ldin(i) <> loadUnits(i).io.lsq.ldin
942    if (i == UncacheWBPort) {
943      lsq.io.ldout(i) <> loadUnits(i).io.lsq.uncache
944    } else {
945      lsq.io.ldout(i).ready := true.B
946      loadUnits(i).io.lsq.uncache.valid := false.B
947      loadUnits(i).io.lsq.uncache.bits := DontCare
948    }
949    lsq.io.ld_raw_data(i) <> loadUnits(i).io.lsq.ld_raw_data
950    lsq.io.ncOut(i) <> loadUnits(i).io.lsq.nc_ldin
951    lsq.io.l2_hint.valid := l2_hint.valid
952    lsq.io.l2_hint.bits.sourceId := l2_hint.bits.sourceId
953    lsq.io.l2_hint.bits.isKeyword := l2_hint.bits.isKeyword
954
955    lsq.io.tlb_hint <> dtlbRepeater.io.hint.get
956
957    // connect misalignBuffer
958    loadMisalignBuffer.io.req(i) <> loadUnits(i).io.misalign_buf
959
960    if (i == MisalignWBPort) {
961      loadUnits(i).io.misalign_ldin  <> loadMisalignBuffer.io.splitLoadReq
962      loadUnits(i).io.misalign_ldout <> loadMisalignBuffer.io.splitLoadResp
963    } else {
964      loadUnits(i).io.misalign_ldin.valid := false.B
965      loadUnits(i).io.misalign_ldin.bits := DontCare
966    }
967
968    // alter writeback exception info
969    io.mem_to_ooo.s3_delayed_load_error(i) := loadUnits(i).io.s3_dly_ld_err
970
971    // update mem dependency predictor
972    // io.memPredUpdate(i) := DontCare
973
974    // --------------------------------
975    // Load Triggers
976    // --------------------------------
977    loadUnits(i).io.fromCsrTrigger.tdataVec := tdata
978    loadUnits(i).io.fromCsrTrigger.tEnableVec := tEnable
979    loadUnits(i).io.fromCsrTrigger.triggerCanRaiseBpExp := triggerCanRaiseBpExp
980    loadUnits(i).io.fromCsrTrigger.debugMode := debugMode
981  }
982
983  for (i <- 0 until HyuCnt) {
984    hybridUnits(i).io.redirect <> redirect
985
986    // get input from dispatch
987    hybridUnits(i).io.lsin <> io.ooo_to_mem.issueHya(i)
988    hybridUnits(i).io.feedback_slow <> io.mem_to_ooo.hyuIqFeedback(i).feedbackSlow
989    hybridUnits(i).io.feedback_fast <> io.mem_to_ooo.hyuIqFeedback(i).feedbackFast
990    hybridUnits(i).io.correctMissTrain := correctMissTrain
991    io.mem_to_ooo.ldCancel.take(HyuCnt)(i) := hybridUnits(i).io.ldu_io.ldCancel
992    io.mem_to_ooo.wakeup.take(HyuCnt)(i) := hybridUnits(i).io.ldu_io.wakeup
993
994    // ------------------------------------
995    //  Load Port
996    // ------------------------------------
997    // fast replay
998    hybridUnits(i).io.ldu_io.fast_rep_in <> hybridUnits(i).io.ldu_io.fast_rep_out
999
1000    // get input from dispatch
1001    hybridUnits(i).io.ldu_io.dcache <> dcache.io.lsu.load(LduCnt + i)
1002    hybridUnits(i).io.stu_io.dcache <> dcache.io.lsu.sta(StaCnt + i)
1003
1004    // dcache access
1005    hybridUnits(i).io.ldu_io.lsq.forward <> lsq.io.forward(LduCnt + i)
1006    // forward
1007    hybridUnits(i).io.ldu_io.sbuffer <> sbuffer.io.forward(LduCnt + i)
1008    hybridUnits(i).io.ldu_io.ubuffer <> uncache.io.forward(LduCnt + i)
1009    // hybridUnits(i).io.ldu_io.vec_forward <> vsFlowQueue.io.forward(LduCnt + i)
1010    hybridUnits(i).io.ldu_io.vec_forward := DontCare
1011    hybridUnits(i).io.ldu_io.tl_d_channel := dcache.io.lsu.forward_D(LduCnt + i)
1012    hybridUnits(i).io.ldu_io.forward_mshr <> dcache.io.lsu.forward_mshr(LduCnt + i)
1013    // ld-ld violation check
1014    hybridUnits(i).io.ldu_io.lsq.ldld_nuke_query <> lsq.io.ldu.ldld_nuke_query(LduCnt + i)
1015    hybridUnits(i).io.ldu_io.lsq.stld_nuke_query <> lsq.io.ldu.stld_nuke_query(LduCnt + i)
1016    hybridUnits(i).io.csrCtrl <> csrCtrl
1017    // dcache refill req
1018    hybridUnits(i).io.ldu_io.tlb_hint.id := dtlbRepeater.io.hint.get.req(LduCnt + i).id
1019    hybridUnits(i).io.ldu_io.tlb_hint.full := dtlbRepeater.io.hint.get.req(LduCnt + i).full ||
1020      tlbreplay_reg(LduCnt + i) || dtlb_ld0_tlbreplay_reg(LduCnt + i)
1021
1022    // dtlb
1023    hybridUnits(i).io.tlb <> dtlb_ld.head.requestor(LduCnt + i)
1024    // pmp
1025    hybridUnits(i).io.pmp <> pmp_check.drop(LduCnt)(i).resp
1026    // st-ld violation query
1027    val stld_nuke_query = VecInit(storeUnits.map(_.io.stld_nuke_query) ++ hybridUnits.map(_.io.stu_io.stld_nuke_query))
1028    hybridUnits(i).io.ldu_io.stld_nuke_query := stld_nuke_query
1029    hybridUnits(i).io.ldu_io.lq_rep_full <> lsq.io.lq_rep_full
1030    // load prefetch train
1031    prefetcherOpt.foreach(pf => {
1032      val source = hybridUnits(i).io.prefetch_train
1033      pf.io.ld_in(LduCnt + i).valid := Mux(pf_train_on_hit,
1034        source.valid,
1035        source.valid && source.bits.isFirstIssue && source.bits.miss
1036      )
1037      pf.io.ld_in(LduCnt + i).bits := source.bits
1038      pf.io.ld_in(LduCnt + i).bits.uop.pc := Mux(hybridUnits(i).io.ldu_io.s2_ptr_chasing, io.ooo_to_mem.hybridPc(i), RegNext(io.ooo_to_mem.hybridPc(i)))
1039    })
1040    l1PrefetcherOpt.foreach(pf => {
1041      // stream will train on all load sources
1042      val source = hybridUnits(i).io.prefetch_train_l1
1043      pf.io.ld_in(LduCnt + i).valid := source.valid && source.bits.isFirstIssue &&
1044                                       FuType.isLoad(source.bits.uop.fuType)
1045      pf.io.ld_in(LduCnt + i).bits := source.bits
1046      pf.io.st_in(StaCnt + i).valid := false.B
1047      pf.io.st_in(StaCnt + i).bits := DontCare
1048    })
1049    prefetcherOpt.foreach(pf => {
1050      val source = hybridUnits(i).io.prefetch_train
1051      pf.io.st_in(StaCnt + i).valid := Mux(pf_train_on_hit,
1052        source.valid,
1053        source.valid && source.bits.isFirstIssue && source.bits.miss
1054      ) && FuType.isStore(source.bits.uop.fuType)
1055      pf.io.st_in(StaCnt + i).bits := source.bits
1056      pf.io.st_in(StaCnt + i).bits.uop.pc := RegNext(io.ooo_to_mem.hybridPc(i))
1057    })
1058
1059    // load to load fast forward: load(i) prefers data(i)
1060    val l2l_fwd_out = loadUnits.map(_.io.l2l_fwd_out) ++ hybridUnits.map(_.io.ldu_io.l2l_fwd_out)
1061    val fastPriority = (LduCnt + i until LduCnt + HyuCnt) ++ (0 until LduCnt + i)
1062    val fastValidVec = fastPriority.map(j => l2l_fwd_out(j).valid)
1063    val fastDataVec = fastPriority.map(j => l2l_fwd_out(j).data)
1064    val fastErrorVec = fastPriority.map(j => l2l_fwd_out(j).dly_ld_err)
1065    val fastMatchVec = fastPriority.map(j => io.ooo_to_mem.loadFastMatch(LduCnt + i)(j))
1066    hybridUnits(i).io.ldu_io.l2l_fwd_in.valid := VecInit(fastValidVec).asUInt.orR
1067    hybridUnits(i).io.ldu_io.l2l_fwd_in.data := ParallelPriorityMux(fastValidVec, fastDataVec)
1068    hybridUnits(i).io.ldu_io.l2l_fwd_in.dly_ld_err := ParallelPriorityMux(fastValidVec, fastErrorVec)
1069    val fastMatch = ParallelPriorityMux(fastValidVec, fastMatchVec)
1070    hybridUnits(i).io.ldu_io.ld_fast_match := fastMatch
1071    hybridUnits(i).io.ldu_io.ld_fast_imm := io.ooo_to_mem.loadFastImm(LduCnt + i)
1072    hybridUnits(i).io.ldu_io.ld_fast_fuOpType := io.ooo_to_mem.loadFastFuOpType(LduCnt + i)
1073    hybridUnits(i).io.ldu_io.replay <> lsq.io.replay(LduCnt + i)
1074    hybridUnits(i).io.ldu_io.l2_hint <> io.l2_hint
1075
1076    // uncache
1077    lsq.io.ldout.drop(LduCnt)(i) <> hybridUnits(i).io.ldu_io.lsq.uncache
1078    lsq.io.ld_raw_data.drop(LduCnt)(i) <> hybridUnits(i).io.ldu_io.lsq.ld_raw_data
1079
1080
1081    // passdown to lsq (load s2)
1082    hybridUnits(i).io.ldu_io.lsq.nc_ldin.valid := false.B
1083    hybridUnits(i).io.ldu_io.lsq.nc_ldin.bits := DontCare
1084    lsq.io.ldu.ldin(LduCnt + i) <> hybridUnits(i).io.ldu_io.lsq.ldin
1085    // Lsq to sta unit
1086    lsq.io.sta.storeMaskIn(StaCnt + i) <> hybridUnits(i).io.stu_io.st_mask_out
1087
1088    // Lsq to std unit's rs
1089    lsq.io.std.storeDataIn(StaCnt + i) := stData(StaCnt + i)
1090    lsq.io.std.storeDataIn(StaCnt + i).valid := stData(StaCnt + i).valid && !st_data_atomics(StaCnt + i)
1091    // prefetch
1092    hybridUnits(i).io.stu_io.prefetch_req <> sbuffer.io.store_prefetch(StaCnt + i)
1093
1094    io.mem_to_ooo.s3_delayed_load_error(LduCnt + i) := hybridUnits(i).io.ldu_io.s3_dly_ld_err
1095
1096    // ------------------------------------
1097    //  Store Port
1098    // ------------------------------------
1099    hybridUnits(i).io.stu_io.lsq <> lsq.io.sta.storeAddrIn.takeRight(HyuCnt)(i)
1100    hybridUnits(i).io.stu_io.lsq_replenish <> lsq.io.sta.storeAddrInRe.takeRight(HyuCnt)(i)
1101
1102    lsq.io.sta.storeMaskIn.takeRight(HyuCnt)(i) <> hybridUnits(i).io.stu_io.st_mask_out
1103    io.mem_to_ooo.stIn.takeRight(HyuCnt)(i).valid := hybridUnits(i).io.stu_io.issue.valid
1104    io.mem_to_ooo.stIn.takeRight(HyuCnt)(i).bits := hybridUnits(i).io.stu_io.issue.bits
1105
1106    // ------------------------------------
1107    //  Vector Store Port
1108    // ------------------------------------
1109    hybridUnits(i).io.vec_stu_io.isFirstIssue := true.B
1110
1111    // -------------------------
1112    // Store Triggers
1113    // -------------------------
1114    hybridUnits(i).io.fromCsrTrigger.tdataVec := tdata
1115    hybridUnits(i).io.fromCsrTrigger.tEnableVec := tEnable
1116    hybridUnits(i).io.fromCsrTrigger.triggerCanRaiseBpExp := triggerCanRaiseBpExp
1117    hybridUnits(i).io.fromCsrTrigger.debugMode := debugMode
1118  }
1119
1120  // misalignBuffer
1121  loadMisalignBuffer.io.redirect                <> redirect
1122  loadMisalignBuffer.io.rob.lcommit             := io.ooo_to_mem.lsqio.lcommit
1123  loadMisalignBuffer.io.rob.scommit             := io.ooo_to_mem.lsqio.scommit
1124  loadMisalignBuffer.io.rob.pendingMMIOld       := io.ooo_to_mem.lsqio.pendingMMIOld
1125  loadMisalignBuffer.io.rob.pendingld           := io.ooo_to_mem.lsqio.pendingld
1126  loadMisalignBuffer.io.rob.pendingst           := io.ooo_to_mem.lsqio.pendingst
1127  loadMisalignBuffer.io.rob.pendingVst          := io.ooo_to_mem.lsqio.pendingVst
1128  loadMisalignBuffer.io.rob.commit              := io.ooo_to_mem.lsqio.commit
1129  loadMisalignBuffer.io.rob.pendingPtr          := io.ooo_to_mem.lsqio.pendingPtr
1130  loadMisalignBuffer.io.rob.pendingPtrNext      := io.ooo_to_mem.lsqio.pendingPtrNext
1131
1132  lsq.io.loadMisalignFull                       := loadMisalignBuffer.io.loadMisalignFull
1133
1134  storeMisalignBuffer.io.redirect               <> redirect
1135  storeMisalignBuffer.io.rob.lcommit            := io.ooo_to_mem.lsqio.lcommit
1136  storeMisalignBuffer.io.rob.scommit            := io.ooo_to_mem.lsqio.scommit
1137  storeMisalignBuffer.io.rob.pendingMMIOld      := io.ooo_to_mem.lsqio.pendingMMIOld
1138  storeMisalignBuffer.io.rob.pendingld          := io.ooo_to_mem.lsqio.pendingld
1139  storeMisalignBuffer.io.rob.pendingst          := io.ooo_to_mem.lsqio.pendingst
1140  storeMisalignBuffer.io.rob.pendingVst         := io.ooo_to_mem.lsqio.pendingVst
1141  storeMisalignBuffer.io.rob.commit             := io.ooo_to_mem.lsqio.commit
1142  storeMisalignBuffer.io.rob.pendingPtr         := io.ooo_to_mem.lsqio.pendingPtr
1143  storeMisalignBuffer.io.rob.pendingPtrNext     := io.ooo_to_mem.lsqio.pendingPtrNext
1144
1145  lsq.io.maControl                              <> storeMisalignBuffer.io.sqControl
1146
1147  lsq.io.cmoOpReq <> dcache.io.cmoOpReq
1148  lsq.io.cmoOpResp <> dcache.io.cmoOpResp
1149
1150  // Prefetcher
1151  val StreamDTLBPortIndex = TlbStartVec(dtlb_ld_idx) + LduCnt + HyuCnt
1152  val PrefetcherDTLBPortIndex = TlbStartVec(dtlb_pf_idx)
1153  val L2toL1DLBPortIndex = TlbStartVec(dtlb_pf_idx) + 1
1154  prefetcherOpt match {
1155  case Some(pf) =>
1156    dtlb_reqs(PrefetcherDTLBPortIndex) <> pf.io.tlb_req
1157    pf.io.pmp_resp := pmp_check(PrefetcherDTLBPortIndex).resp
1158  case None =>
1159    dtlb_reqs(PrefetcherDTLBPortIndex) := DontCare
1160    dtlb_reqs(PrefetcherDTLBPortIndex).req.valid := false.B
1161    dtlb_reqs(PrefetcherDTLBPortIndex).resp.ready := true.B
1162  }
1163  l1PrefetcherOpt match {
1164    case Some(pf) =>
1165      dtlb_reqs(StreamDTLBPortIndex) <> pf.io.tlb_req
1166      pf.io.pmp_resp := pmp_check(StreamDTLBPortIndex).resp
1167    case None =>
1168        dtlb_reqs(StreamDTLBPortIndex) := DontCare
1169        dtlb_reqs(StreamDTLBPortIndex).req.valid := false.B
1170        dtlb_reqs(StreamDTLBPortIndex).resp.ready := true.B
1171  }
1172  dtlb_reqs(L2toL1DLBPortIndex) <> io.l2_tlb_req
1173  dtlb_reqs(L2toL1DLBPortIndex).resp.ready := true.B
1174  io.l2_pmp_resp := pmp_check(L2toL1DLBPortIndex).resp
1175
1176  // StoreUnit
1177  for (i <- 0 until StdCnt) {
1178    stdExeUnits(i).io.flush <> redirect
1179    stdExeUnits(i).io.in.valid := io.ooo_to_mem.issueStd(i).valid
1180    io.ooo_to_mem.issueStd(i).ready := stdExeUnits(i).io.in.ready
1181    stdExeUnits(i).io.in.bits := io.ooo_to_mem.issueStd(i).bits
1182  }
1183
1184  for (i <- 0 until StaCnt) {
1185    val stu = storeUnits(i)
1186
1187    stu.io.redirect      <> redirect
1188    stu.io.csrCtrl       <> csrCtrl
1189    stu.io.dcache        <> dcache.io.lsu.sta(i)
1190    stu.io.feedback_slow <> io.mem_to_ooo.staIqFeedback(i).feedbackSlow
1191    stu.io.stin         <> io.ooo_to_mem.issueSta(i)
1192    stu.io.lsq          <> lsq.io.sta.storeAddrIn(i)
1193    stu.io.lsq_replenish <> lsq.io.sta.storeAddrInRe(i)
1194    // dtlb
1195    stu.io.tlb          <> dtlb_st.head.requestor(i)
1196    stu.io.pmp          <> pmp_check(LduCnt + HyuCnt + 1 + i).resp
1197
1198    // -------------------------
1199    // Store Triggers
1200    // -------------------------
1201    stu.io.fromCsrTrigger.tdataVec := tdata
1202    stu.io.fromCsrTrigger.tEnableVec := tEnable
1203    stu.io.fromCsrTrigger.triggerCanRaiseBpExp := triggerCanRaiseBpExp
1204    stu.io.fromCsrTrigger.debugMode := debugMode
1205
1206    // prefetch
1207    stu.io.prefetch_req <> sbuffer.io.store_prefetch(i)
1208
1209    // store unit does not need fast feedback
1210    io.mem_to_ooo.staIqFeedback(i).feedbackFast := DontCare
1211
1212    // Lsq to sta unit
1213    lsq.io.sta.storeMaskIn(i) <> stu.io.st_mask_out
1214
1215    // connect misalignBuffer
1216    storeMisalignBuffer.io.req(i) <> stu.io.misalign_buf
1217
1218    if (i == 0) {
1219      stu.io.misalign_stin  <> storeMisalignBuffer.io.splitStoreReq
1220      stu.io.misalign_stout <> storeMisalignBuffer.io.splitStoreResp
1221    } else {
1222      stu.io.misalign_stin.valid := false.B
1223      stu.io.misalign_stin.bits := DontCare
1224    }
1225
1226    // Lsq to std unit's rs
1227    if (i < VstuCnt){
1228      when (vsSplit(i).io.vstd.get.valid) {
1229        lsq.io.std.storeDataIn(i).valid := true.B
1230        lsq.io.std.storeDataIn(i).bits := vsSplit(i).io.vstd.get.bits
1231        stData(i).ready := false.B
1232      }.otherwise {
1233        lsq.io.std.storeDataIn(i).valid := stData(i).valid && !st_data_atomics(i)
1234        lsq.io.std.storeDataIn(i).bits.uop := stData(i).bits.uop
1235        lsq.io.std.storeDataIn(i).bits.data := stData(i).bits.data
1236        lsq.io.std.storeDataIn(i).bits.mask.map(_ := 0.U)
1237        lsq.io.std.storeDataIn(i).bits.vdIdx.map(_ := 0.U)
1238        lsq.io.std.storeDataIn(i).bits.vdIdxInField.map(_ := 0.U)
1239        stData(i).ready := true.B
1240      }
1241    } else {
1242        lsq.io.std.storeDataIn(i).valid := stData(i).valid && !st_data_atomics(i)
1243        lsq.io.std.storeDataIn(i).bits.uop := stData(i).bits.uop
1244        lsq.io.std.storeDataIn(i).bits.data := stData(i).bits.data
1245        lsq.io.std.storeDataIn(i).bits.mask.map(_ := 0.U)
1246        lsq.io.std.storeDataIn(i).bits.vdIdx.map(_ := 0.U)
1247        lsq.io.std.storeDataIn(i).bits.vdIdxInField.map(_ := 0.U)
1248        stData(i).ready := true.B
1249    }
1250    lsq.io.std.storeDataIn.map(_.bits.debug := 0.U.asTypeOf(new DebugBundle))
1251    lsq.io.std.storeDataIn.foreach(_.bits.isFromLoadUnit := DontCare)
1252
1253
1254    // store prefetch train
1255    l1PrefetcherOpt.foreach(pf => {
1256      // stream will train on all load sources
1257      pf.io.st_in(i).valid := false.B
1258      pf.io.st_in(i).bits := DontCare
1259    })
1260
1261    prefetcherOpt.foreach(pf => {
1262      pf.io.st_in(i).valid := Mux(pf_train_on_hit,
1263        stu.io.prefetch_train.valid,
1264        stu.io.prefetch_train.valid && stu.io.prefetch_train.bits.isFirstIssue && (
1265          stu.io.prefetch_train.bits.miss
1266          )
1267      )
1268      pf.io.st_in(i).bits := stu.io.prefetch_train.bits
1269      pf.io.st_in(i).bits.uop.pc := RegEnable(RegEnable(io.ooo_to_mem.storePc(i), stu.io.s1_prefetch_spec), stu.io.s2_prefetch_spec)
1270    })
1271
1272    // 1. sync issue info to store set LFST
1273    // 2. when store issue, broadcast issued sqPtr to wake up the following insts
1274    // io.stIn(i).valid := io.issue(exuParameters.LduCnt + i).valid
1275    // io.stIn(i).bits := io.issue(exuParameters.LduCnt + i).bits
1276    io.mem_to_ooo.stIn(i).valid := stu.io.issue.valid
1277    io.mem_to_ooo.stIn(i).bits := stu.io.issue.bits
1278
1279    stu.io.stout.ready := true.B
1280
1281    // vector
1282    if (i < VstuCnt) {
1283      stu.io.vecstin <> vsSplit(i).io.out
1284      // vsFlowQueue.io.pipeFeedback(i) <> stu.io.vec_feedback_slow // need connect
1285    } else {
1286      stu.io.vecstin.valid := false.B
1287      stu.io.vecstin.bits := DontCare
1288      stu.io.vecstout.ready := false.B
1289    }
1290    stu.io.vec_isFirstIssue := true.B // TODO
1291  }
1292
1293  // mmio store writeback will use store writeback port 0
1294  val mmioStout = WireInit(0.U.asTypeOf(lsq.io.mmioStout))
1295  NewPipelineConnect(
1296    lsq.io.mmioStout, mmioStout, mmioStout.fire,
1297    false.B,
1298    Option("mmioStOutConnect")
1299  )
1300  mmioStout.ready := false.B
1301  when (mmioStout.valid && !storeUnits(0).io.stout.valid) {
1302    stOut(0).valid := true.B
1303    stOut(0).bits  := mmioStout.bits
1304    mmioStout.ready := true.B
1305  }
1306
1307  // vec mmio writeback
1308  lsq.io.vecmmioStout.ready := false.B
1309
1310  // miss align buffer will overwrite stOut(0)
1311  val storeMisalignCanWriteBack = !mmioStout.valid && !storeUnits(0).io.stout.valid && !storeUnits(0).io.vecstout.valid
1312  storeMisalignBuffer.io.writeBack.ready := storeMisalignCanWriteBack
1313  storeMisalignBuffer.io.storeOutValid := storeUnits(0).io.stout.valid
1314  storeMisalignBuffer.io.storeVecOutValid := storeUnits(0).io.vecstout.valid
1315  when (storeMisalignBuffer.io.writeBack.valid && storeMisalignCanWriteBack) {
1316    stOut(0).valid := true.B
1317    stOut(0).bits  := storeMisalignBuffer.io.writeBack.bits
1318  }
1319
1320  // Uncache
1321  uncache.io.enableOutstanding := io.ooo_to_mem.csrCtrl.uncache_write_outstanding_enable
1322  uncache.io.hartId := io.hartId
1323  lsq.io.uncacheOutstanding := io.ooo_to_mem.csrCtrl.uncache_write_outstanding_enable
1324
1325  // Lsq
1326  io.mem_to_ooo.lsqio.mmio       := lsq.io.rob.mmio
1327  io.mem_to_ooo.lsqio.uop        := lsq.io.rob.uop
1328  lsq.io.rob.lcommit             := io.ooo_to_mem.lsqio.lcommit
1329  lsq.io.rob.scommit             := io.ooo_to_mem.lsqio.scommit
1330  lsq.io.rob.pendingMMIOld       := io.ooo_to_mem.lsqio.pendingMMIOld
1331  lsq.io.rob.pendingld           := io.ooo_to_mem.lsqio.pendingld
1332  lsq.io.rob.pendingst           := io.ooo_to_mem.lsqio.pendingst
1333  lsq.io.rob.pendingVst          := io.ooo_to_mem.lsqio.pendingVst
1334  lsq.io.rob.commit              := io.ooo_to_mem.lsqio.commit
1335  lsq.io.rob.pendingPtr          := io.ooo_to_mem.lsqio.pendingPtr
1336  lsq.io.rob.pendingPtrNext      := io.ooo_to_mem.lsqio.pendingPtrNext
1337
1338  //  lsq.io.rob            <> io.lsqio.rob
1339  lsq.io.enq            <> io.ooo_to_mem.enqLsq
1340  lsq.io.brqRedirect    <> redirect
1341
1342  //  violation rollback
1343  def selectOldestRedirect(xs: Seq[Valid[Redirect]]): Vec[Bool] = {
1344    val compareVec = (0 until xs.length).map(i => (0 until i).map(j => isAfter(xs(j).bits.robIdx, xs(i).bits.robIdx)))
1345    val resultOnehot = VecInit((0 until xs.length).map(i => Cat((0 until xs.length).map(j =>
1346      (if (j < i) !xs(j).valid || compareVec(i)(j)
1347      else if (j == i) xs(i).valid
1348      else !xs(j).valid || !compareVec(j)(i))
1349    )).andR))
1350    resultOnehot
1351  }
1352  val allRedirect = loadUnits.map(_.io.rollback) ++ hybridUnits.map(_.io.ldu_io.rollback) ++ lsq.io.nack_rollback ++ lsq.io.nuke_rollback
1353  val oldestOneHot = selectOldestRedirect(allRedirect)
1354  val oldestRedirect = WireDefault(Mux1H(oldestOneHot, allRedirect))
1355  // memory replay would not cause IAF/IPF/IGPF
1356  oldestRedirect.bits.cfiUpdate.backendIAF := false.B
1357  oldestRedirect.bits.cfiUpdate.backendIPF := false.B
1358  oldestRedirect.bits.cfiUpdate.backendIGPF := false.B
1359  io.mem_to_ooo.memoryViolation := oldestRedirect
1360  io.mem_to_ooo.lsqio.lqCanAccept  := lsq.io.lqCanAccept
1361  io.mem_to_ooo.lsqio.sqCanAccept  := lsq.io.sqCanAccept
1362
1363  // lsq.io.uncache        <> uncache.io.lsq
1364  val s_idle :: s_scalar_uncache :: s_vector_uncache :: Nil = Enum(3)
1365  val uncacheState = RegInit(s_idle)
1366  val uncacheReq = Wire(Decoupled(new UncacheWordReq))
1367  val uncacheIdResp = uncache.io.lsq.idResp
1368  val uncacheResp = Wire(Decoupled(new UncacheWordResp))
1369
1370  uncacheReq.bits := DontCare
1371  uncacheReq.valid := false.B
1372  uncacheReq.ready := false.B
1373  uncacheResp.bits := DontCare
1374  uncacheResp.valid := false.B
1375  uncacheResp.ready := false.B
1376  lsq.io.uncache.req.ready := false.B
1377  lsq.io.uncache.idResp.valid := false.B
1378  lsq.io.uncache.idResp.bits := DontCare
1379  lsq.io.uncache.resp.valid := false.B
1380  lsq.io.uncache.resp.bits := DontCare
1381
1382  switch (uncacheState) {
1383    is (s_idle) {
1384      when (uncacheReq.fire) {
1385        when (lsq.io.uncache.req.valid) {
1386          when (!lsq.io.uncache.req.bits.nc || !io.ooo_to_mem.csrCtrl.uncache_write_outstanding_enable) {
1387            uncacheState := s_scalar_uncache
1388          }
1389        }.otherwise {
1390          // val isStore = vsFlowQueue.io.uncache.req.bits.cmd === MemoryOpConstants.M_XWR
1391          when (!io.ooo_to_mem.csrCtrl.uncache_write_outstanding_enable) {
1392            uncacheState := s_vector_uncache
1393          }
1394        }
1395      }
1396    }
1397
1398    is (s_scalar_uncache) {
1399      when (uncacheResp.fire) {
1400        uncacheState := s_idle
1401      }
1402    }
1403
1404    is (s_vector_uncache) {
1405      when (uncacheResp.fire) {
1406        uncacheState := s_idle
1407      }
1408    }
1409  }
1410
1411  when (lsq.io.uncache.req.valid) {
1412    uncacheReq <> lsq.io.uncache.req
1413  }
1414  when (io.ooo_to_mem.csrCtrl.uncache_write_outstanding_enable) {
1415    lsq.io.uncache.resp <> uncacheResp
1416    lsq.io.uncache.idResp <> uncacheIdResp
1417  }.otherwise {
1418    when (uncacheState === s_scalar_uncache) {
1419      lsq.io.uncache.resp <> uncacheResp
1420      lsq.io.uncache.idResp <> uncacheIdResp
1421    }
1422  }
1423  // delay dcache refill for 1 cycle for better timing
1424  AddPipelineReg(uncacheReq, uncache.io.lsq.req, false.B)
1425  AddPipelineReg(uncache.io.lsq.resp, uncacheResp, false.B)
1426
1427  //lsq.io.refill         := delayedDcacheRefill
1428  lsq.io.release        := dcache.io.lsu.release
1429  lsq.io.lqCancelCnt <> io.mem_to_ooo.lqCancelCnt
1430  lsq.io.sqCancelCnt <> io.mem_to_ooo.sqCancelCnt
1431  lsq.io.lqDeq <> io.mem_to_ooo.lqDeq
1432  lsq.io.sqDeq <> io.mem_to_ooo.sqDeq
1433  // Todo: assign these
1434  io.mem_to_ooo.sqDeqPtr := lsq.io.sqDeqPtr
1435  io.mem_to_ooo.lqDeqPtr := lsq.io.lqDeqPtr
1436  lsq.io.tl_d_channel <> dcache.io.lsu.tl_d_channel
1437
1438  // LSQ to store buffer
1439  lsq.io.sbuffer        <> sbuffer.io.in
1440  sbuffer.io.in(0).valid := lsq.io.sbuffer(0).valid || vSegmentUnit.io.sbuffer.valid
1441  sbuffer.io.in(0).bits  := Mux1H(Seq(
1442    vSegmentUnit.io.sbuffer.valid -> vSegmentUnit.io.sbuffer.bits,
1443    lsq.io.sbuffer(0).valid       -> lsq.io.sbuffer(0).bits
1444  ))
1445  vSegmentUnit.io.sbuffer.ready := sbuffer.io.in(0).ready
1446  lsq.io.sqEmpty        <> sbuffer.io.sqempty
1447  dcache.io.force_write := lsq.io.force_write
1448
1449  // Initialize when unenabled difftest.
1450  sbuffer.io.vecDifftestInfo      := DontCare
1451  lsq.io.sbufferVecDifftestInfo   := DontCare
1452  vSegmentUnit.io.vecDifftestInfo := DontCare
1453  if (env.EnableDifftest) {
1454    sbuffer.io.vecDifftestInfo .zipWithIndex.map{ case (sbufferPort, index) =>
1455      if (index == 0) {
1456        val vSegmentDifftestValid = vSegmentUnit.io.vecDifftestInfo.valid
1457        sbufferPort.valid := Mux(vSegmentDifftestValid, vSegmentUnit.io.vecDifftestInfo.valid, lsq.io.sbufferVecDifftestInfo(0).valid)
1458        sbufferPort.bits  := Mux(vSegmentDifftestValid, vSegmentUnit.io.vecDifftestInfo.bits, lsq.io.sbufferVecDifftestInfo(0).bits)
1459
1460        vSegmentUnit.io.vecDifftestInfo.ready  := sbufferPort.ready
1461        lsq.io.sbufferVecDifftestInfo(0).ready := sbufferPort.ready
1462      } else {
1463         sbufferPort <> lsq.io.sbufferVecDifftestInfo(index)
1464      }
1465    }
1466  }
1467
1468  // lsq.io.vecStoreRetire <> vsFlowQueue.io.sqRelease
1469  // lsq.io.vecWriteback.valid := vlWrapper.io.uopWriteback.fire &&
1470  //   vlWrapper.io.uopWriteback.bits.uop.vpu.lastUop
1471  // lsq.io.vecWriteback.bits := vlWrapper.io.uopWriteback.bits
1472
1473  // vector
1474  val vLoadCanAccept  = (0 until VlduCnt).map(i =>
1475    vlSplit(i).io.in.ready && VlduType.isVecLd(io.ooo_to_mem.issueVldu(i).bits.uop.fuOpType)
1476  )
1477  val vStoreCanAccept = (0 until VstuCnt).map(i =>
1478    vsSplit(i).io.in.ready && VstuType.isVecSt(io.ooo_to_mem.issueVldu(i).bits.uop.fuOpType)
1479  )
1480  val isSegment     = io.ooo_to_mem.issueVldu.head.valid && isVsegls(io.ooo_to_mem.issueVldu.head.bits.uop.fuType)
1481  val isFixVlUop    = io.ooo_to_mem.issueVldu.map{x =>
1482    x.bits.uop.vpu.isVleff && x.bits.uop.vpu.lastUop && x.valid
1483  }
1484
1485  // init port
1486  /**
1487   * TODO: splited vsMergebuffer maybe remove, if one RS can accept two feedback, or don't need RS replay uop
1488   * for now:
1489   *  RS0 -> VsSplit0 -> stu0 -> vsMergebuffer0 -> feedback -> RS0
1490   *  RS1 -> VsSplit1 -> stu1 -> vsMergebuffer1 -> feedback -> RS1
1491   *
1492   * vector load don't need feedback
1493   *
1494   *  RS0 -> VlSplit0  -> ldu0 -> |
1495   *  RS1 -> VlSplit1  -> ldu1 -> |  -> vlMergebuffer
1496   *        replayIO   -> ldu3 -> |
1497   * */
1498  (0 until VstuCnt).foreach{i =>
1499    vsMergeBuffer(i).io.fromPipeline := DontCare
1500    vsMergeBuffer(i).io.fromSplit := DontCare
1501
1502    vsMergeBuffer(i).io.fromMisalignBuffer.get.flush := storeMisalignBuffer.io.toVecStoreMergeBuffer(i).flush
1503    vsMergeBuffer(i).io.fromMisalignBuffer.get.mbIndex := storeMisalignBuffer.io.toVecStoreMergeBuffer(i).mbIndex
1504  }
1505
1506  (0 until VstuCnt).foreach{i =>
1507    vsSplit(i).io.redirect <> redirect
1508    vsSplit(i).io.in <> io.ooo_to_mem.issueVldu(i)
1509    vsSplit(i).io.in.valid := io.ooo_to_mem.issueVldu(i).valid &&
1510                              vStoreCanAccept(i) && !isSegment
1511    vsSplit(i).io.toMergeBuffer <> vsMergeBuffer(i).io.fromSplit.head
1512    NewPipelineConnect(
1513      vsSplit(i).io.out, storeUnits(i).io.vecstin, storeUnits(i).io.vecstin.fire,
1514      Mux(vsSplit(i).io.out.fire, vsSplit(i).io.out.bits.uop.robIdx.needFlush(io.redirect), storeUnits(i).io.vecstin.bits.uop.robIdx.needFlush(io.redirect)),
1515      Option("VsSplitConnectStu")
1516    )
1517    vsSplit(i).io.vstd.get := DontCare // Todo: Discuss how to pass vector store data
1518
1519    vsSplit(i).io.vstdMisalign.get.storeMisalignBufferEmpty := !storeMisalignBuffer.io.full
1520    vsSplit(i).io.vstdMisalign.get.storePipeEmpty := !storeUnits(i).io.s0_s1_valid
1521
1522  }
1523  (0 until VlduCnt).foreach{i =>
1524    vlSplit(i).io.redirect <> redirect
1525    vlSplit(i).io.in <> io.ooo_to_mem.issueVldu(i)
1526    vlSplit(i).io.in.valid := io.ooo_to_mem.issueVldu(i).valid &&
1527                              vLoadCanAccept(i) && !isSegment && !isFixVlUop(i)
1528    vlSplit(i).io.toMergeBuffer <> vlMergeBuffer.io.fromSplit(i)
1529    vlSplit(i).io.threshold.get.valid := vlMergeBuffer.io.toSplit.get.threshold
1530    vlSplit(i).io.threshold.get.bits  := lsq.io.lqDeqPtr
1531    NewPipelineConnect(
1532      vlSplit(i).io.out, loadUnits(i).io.vecldin, loadUnits(i).io.vecldin.fire,
1533      Mux(vlSplit(i).io.out.fire, vlSplit(i).io.out.bits.uop.robIdx.needFlush(io.redirect), loadUnits(i).io.vecldin.bits.uop.robIdx.needFlush(io.redirect)),
1534      Option("VlSplitConnectLdu")
1535    )
1536
1537    //Subsequent instrction will be blocked
1538    vfofBuffer.io.in(i).valid := io.ooo_to_mem.issueVldu(i).valid
1539    vfofBuffer.io.in(i).bits  := io.ooo_to_mem.issueVldu(i).bits
1540  }
1541  (0 until LduCnt).foreach{i=>
1542    loadUnits(i).io.vecldout.ready         := vlMergeBuffer.io.fromPipeline(i).ready
1543    loadMisalignBuffer.io.vecWriteBack.ready := true.B
1544
1545    if (i == MisalignWBPort) {
1546      when(loadUnits(i).io.vecldout.valid) {
1547        vlMergeBuffer.io.fromPipeline(i).valid := loadUnits(i).io.vecldout.valid
1548        vlMergeBuffer.io.fromPipeline(i).bits  := loadUnits(i).io.vecldout.bits
1549      } .otherwise {
1550        vlMergeBuffer.io.fromPipeline(i).valid   := loadMisalignBuffer.io.vecWriteBack.valid
1551        vlMergeBuffer.io.fromPipeline(i).bits    := loadMisalignBuffer.io.vecWriteBack.bits
1552      }
1553    } else {
1554      vlMergeBuffer.io.fromPipeline(i).valid := loadUnits(i).io.vecldout.valid
1555      vlMergeBuffer.io.fromPipeline(i).bits  := loadUnits(i).io.vecldout.bits
1556    }
1557  }
1558
1559  (0 until StaCnt).foreach{i=>
1560    if(i < VstuCnt){
1561      storeUnits(i).io.vecstout.ready := true.B
1562      storeMisalignBuffer.io.vecWriteBack(i).ready := vsMergeBuffer(i).io.fromPipeline.head.ready
1563
1564      when(storeUnits(i).io.vecstout.valid) {
1565        vsMergeBuffer(i).io.fromPipeline.head.valid := storeUnits(i).io.vecstout.valid
1566        vsMergeBuffer(i).io.fromPipeline.head.bits  := storeUnits(i).io.vecstout.bits
1567      } .otherwise {
1568        vsMergeBuffer(i).io.fromPipeline.head.valid   := storeMisalignBuffer.io.vecWriteBack(i).valid
1569        vsMergeBuffer(i).io.fromPipeline.head.bits    := storeMisalignBuffer.io.vecWriteBack(i).bits
1570      }
1571    }
1572  }
1573
1574  (0 until VlduCnt).foreach{i=>
1575    io.ooo_to_mem.issueVldu(i).ready := vLoadCanAccept(i) || vStoreCanAccept(i)
1576  }
1577
1578  vlMergeBuffer.io.redirect <> redirect
1579  vsMergeBuffer.map(_.io.redirect <> redirect)
1580  (0 until VlduCnt).foreach{i=>
1581    vlMergeBuffer.io.toLsq(i) <> lsq.io.ldvecFeedback(i)
1582  }
1583  (0 until VstuCnt).foreach{i=>
1584    vsMergeBuffer(i).io.toLsq.head <> lsq.io.stvecFeedback(i)
1585  }
1586
1587  (0 until VlduCnt).foreach{i=>
1588    // send to RS
1589    vlMergeBuffer.io.feedback(i) <> io.mem_to_ooo.vlduIqFeedback(i).feedbackSlow
1590    io.mem_to_ooo.vlduIqFeedback(i).feedbackFast := DontCare
1591  }
1592  (0 until VstuCnt).foreach{i =>
1593    // send to RS
1594    if (i == 0){
1595      io.mem_to_ooo.vstuIqFeedback(i).feedbackSlow.valid := vsMergeBuffer(i).io.feedback.head.valid || vSegmentUnit.io.feedback.valid
1596      io.mem_to_ooo.vstuIqFeedback(i).feedbackSlow.bits := Mux1H(Seq(
1597        vSegmentUnit.io.feedback.valid -> vSegmentUnit.io.feedback.bits,
1598        vsMergeBuffer(i).io.feedback.head.valid ->  vsMergeBuffer(i).io.feedback.head.bits
1599      ))
1600      io.mem_to_ooo.vstuIqFeedback(i).feedbackFast := DontCare
1601    } else {
1602      vsMergeBuffer(i).io.feedback.head <> io.mem_to_ooo.vstuIqFeedback(i).feedbackSlow
1603      io.mem_to_ooo.vstuIqFeedback(i).feedbackFast := DontCare
1604    }
1605  }
1606
1607  (0 until VlduCnt).foreach{i=>
1608    if (i == 0){ // for segmentUnit, segmentUnit use port0 writeback
1609      io.mem_to_ooo.writebackVldu(i).valid := vlMergeBuffer.io.uopWriteback(i).valid || vsMergeBuffer(i).io.uopWriteback.head.valid || vSegmentUnit.io.uopwriteback.valid
1610      io.mem_to_ooo.writebackVldu(i).bits := PriorityMux(Seq(
1611        vSegmentUnit.io.uopwriteback.valid          -> vSegmentUnit.io.uopwriteback.bits,
1612        vlMergeBuffer.io.uopWriteback(i).valid      -> vlMergeBuffer.io.uopWriteback(i).bits,
1613        vsMergeBuffer(i).io.uopWriteback.head.valid -> vsMergeBuffer(i).io.uopWriteback.head.bits,
1614      ))
1615      vlMergeBuffer.io.uopWriteback(i).ready := io.mem_to_ooo.writebackVldu(i).ready && !vSegmentUnit.io.uopwriteback.valid
1616      vsMergeBuffer(i).io.uopWriteback.head.ready := io.mem_to_ooo.writebackVldu(i).ready && !vlMergeBuffer.io.uopWriteback(i).valid && !vSegmentUnit.io.uopwriteback.valid
1617      vSegmentUnit.io.uopwriteback.ready := io.mem_to_ooo.writebackVldu(i).ready
1618    } else if (i == 1) {
1619      io.mem_to_ooo.writebackVldu(i).valid := vlMergeBuffer.io.uopWriteback(i).valid || vsMergeBuffer(i).io.uopWriteback.head.valid || vfofBuffer.io.uopWriteback.valid
1620      io.mem_to_ooo.writebackVldu(i).bits := PriorityMux(Seq(
1621        vfofBuffer.io.uopWriteback.valid            -> vfofBuffer.io.uopWriteback.bits,
1622        vlMergeBuffer.io.uopWriteback(i).valid      -> vlMergeBuffer.io.uopWriteback(i).bits,
1623        vsMergeBuffer(i).io.uopWriteback.head.valid -> vsMergeBuffer(i).io.uopWriteback.head.bits,
1624      ))
1625      vlMergeBuffer.io.uopWriteback(i).ready := io.mem_to_ooo.writebackVldu(i).ready && !vfofBuffer.io.uopWriteback.valid
1626      vsMergeBuffer(i).io.uopWriteback.head.ready := io.mem_to_ooo.writebackVldu(i).ready && !vlMergeBuffer.io.uopWriteback(i).valid && !vfofBuffer.io.uopWriteback.valid
1627      vfofBuffer.io.uopWriteback.ready := io.mem_to_ooo.writebackVldu(i).ready
1628    } else {
1629      io.mem_to_ooo.writebackVldu(i).valid := vlMergeBuffer.io.uopWriteback(i).valid || vsMergeBuffer(i).io.uopWriteback.head.valid
1630      io.mem_to_ooo.writebackVldu(i).bits := PriorityMux(Seq(
1631        vlMergeBuffer.io.uopWriteback(i).valid -> vlMergeBuffer.io.uopWriteback(i).bits,
1632        vsMergeBuffer(i).io.uopWriteback.head.valid -> vsMergeBuffer(i).io.uopWriteback.head.bits,
1633      ))
1634      vlMergeBuffer.io.uopWriteback(i).ready := io.mem_to_ooo.writebackVldu(i).ready
1635      vsMergeBuffer(i).io.uopWriteback.head.ready := io.mem_to_ooo.writebackVldu(i).ready && !vlMergeBuffer.io.uopWriteback(i).valid
1636    }
1637
1638    vfofBuffer.io.mergeUopWriteback(i).valid := vlMergeBuffer.io.uopWriteback(i).valid
1639    vfofBuffer.io.mergeUopWriteback(i).bits  := vlMergeBuffer.io.uopWriteback(i).bits
1640  }
1641
1642
1643  vfofBuffer.io.redirect <> redirect
1644
1645  // Sbuffer
1646  sbuffer.io.csrCtrl    <> csrCtrl
1647  sbuffer.io.dcache     <> dcache.io.lsu.store
1648  sbuffer.io.memSetPattenDetected := dcache.io.memSetPattenDetected
1649  sbuffer.io.force_write <> lsq.io.force_write
1650  // flush sbuffer
1651  val cmoFlush = lsq.io.flushSbuffer.valid
1652  val fenceFlush = io.ooo_to_mem.flushSb
1653  val atomicsFlush = atomicsUnit.io.flush_sbuffer.valid || vSegmentUnit.io.flush_sbuffer.valid
1654  val stIsEmpty = sbuffer.io.flush.empty && uncache.io.flush.empty
1655  io.mem_to_ooo.sbIsEmpty := RegNext(stIsEmpty)
1656
1657  // if both of them tries to flush sbuffer at the same time
1658  // something must have gone wrong
1659  assert(!(fenceFlush && atomicsFlush && cmoFlush))
1660  sbuffer.io.flush.valid := RegNext(fenceFlush || atomicsFlush || cmoFlush)
1661  uncache.io.flush.valid := sbuffer.io.flush.valid
1662
1663  // AtomicsUnit: AtomicsUnit will override other control signials,
1664  // as atomics insts (LR/SC/AMO) will block the pipeline
1665  val s_normal +: s_atomics = Enum(StaCnt + HyuCnt + 1)
1666  val state = RegInit(s_normal)
1667
1668  val st_atomics = Seq.tabulate(StaCnt)(i =>
1669    io.ooo_to_mem.issueSta(i).valid && FuType.storeIsAMO((io.ooo_to_mem.issueSta(i).bits.uop.fuType))
1670  ) ++ Seq.tabulate(HyuCnt)(i =>
1671    io.ooo_to_mem.issueHya(i).valid && FuType.storeIsAMO((io.ooo_to_mem.issueHya(i).bits.uop.fuType))
1672  )
1673
1674  for (i <- 0 until StaCnt) when(st_atomics(i)) {
1675    io.ooo_to_mem.issueSta(i).ready := atomicsUnit.io.in.ready
1676    storeUnits(i).io.stin.valid := false.B
1677
1678    state := s_atomics(i)
1679  }
1680  for (i <- 0 until HyuCnt) when(st_atomics(StaCnt + i)) {
1681    io.ooo_to_mem.issueHya(i).ready := atomicsUnit.io.in.ready
1682    hybridUnits(i).io.lsin.valid := false.B
1683
1684    state := s_atomics(StaCnt + i)
1685    assert(!st_atomics.zipWithIndex.filterNot(_._2 == StaCnt + i).unzip._1.reduce(_ || _))
1686  }
1687  when (atomicsUnit.io.out.valid) {
1688    state := s_normal
1689  }
1690
1691  atomicsUnit.io.in.valid := st_atomics.reduce(_ || _)
1692  atomicsUnit.io.in.bits  := Mux1H(Seq.tabulate(StaCnt)(i =>
1693    st_atomics(i) -> io.ooo_to_mem.issueSta(i).bits) ++
1694    Seq.tabulate(HyuCnt)(i => st_atomics(StaCnt+i) -> io.ooo_to_mem.issueHya(i).bits))
1695  atomicsUnit.io.storeDataIn.zipWithIndex.foreach { case (stdin, i) =>
1696    stdin.valid := st_data_atomics(i)
1697    stdin.bits := stData(i).bits
1698  }
1699  atomicsUnit.io.redirect <> redirect
1700
1701  // TODO: complete amo's pmp support
1702  val amoTlb = dtlb_ld(0).requestor(0)
1703  atomicsUnit.io.dtlb.resp.valid := false.B
1704  atomicsUnit.io.dtlb.resp.bits  := DontCare
1705  atomicsUnit.io.dtlb.req.ready  := amoTlb.req.ready
1706  atomicsUnit.io.pmpResp := pmp_check(0).resp
1707
1708  atomicsUnit.io.dcache <> dcache.io.lsu.atomics
1709  atomicsUnit.io.flush_sbuffer.empty := stIsEmpty
1710
1711  atomicsUnit.io.csrCtrl := csrCtrl
1712
1713  // for atomicsUnit, it uses loadUnit(0)'s TLB port
1714
1715  when (state =/= s_normal) {
1716    // use store wb port instead of load
1717    loadUnits(0).io.ldout.ready := false.B
1718    // use load_0's TLB
1719    atomicsUnit.io.dtlb <> amoTlb
1720
1721    // hw prefetch should be disabled while executing atomic insts
1722    loadUnits.map(i => i.io.prefetch_req.valid := false.B)
1723
1724    // make sure there's no in-flight uops in load unit
1725    assert(!loadUnits(0).io.ldout.valid)
1726  }
1727
1728  lsq.io.flushSbuffer.empty := sbuffer.io.sbempty
1729
1730  for (i <- 0 until StaCnt) {
1731    when (state === s_atomics(i)) {
1732      io.mem_to_ooo.staIqFeedback(i).feedbackSlow := atomicsUnit.io.feedbackSlow
1733      assert(!storeUnits(i).io.feedback_slow.valid)
1734    }
1735  }
1736  for (i <- 0 until HyuCnt) {
1737    when (state === s_atomics(StaCnt + i)) {
1738      io.mem_to_ooo.hyuIqFeedback(i).feedbackSlow := atomicsUnit.io.feedbackSlow
1739      assert(!hybridUnits(i).io.feedback_slow.valid)
1740    }
1741  }
1742
1743  lsq.io.exceptionAddr.isStore := io.ooo_to_mem.isStoreException
1744  // Exception address is used several cycles after flush.
1745  // We delay it by 10 cycles to ensure its flush safety.
1746  val atomicsException = RegInit(false.B)
1747  when (DelayN(redirect.valid, 10) && atomicsException) {
1748    atomicsException := false.B
1749  }.elsewhen (atomicsUnit.io.exceptionInfo.valid) {
1750    atomicsException := true.B
1751  }
1752
1753  val misalignBufExceptionOverwrite = loadMisalignBuffer.io.overwriteExpBuf.valid || storeMisalignBuffer.io.overwriteExpBuf.valid
1754  val misalignBufExceptionVaddr = Mux(loadMisalignBuffer.io.overwriteExpBuf.valid,
1755    loadMisalignBuffer.io.overwriteExpBuf.vaddr,
1756    storeMisalignBuffer.io.overwriteExpBuf.vaddr
1757  )
1758  val misalignBufExceptionIsHyper = Mux(loadMisalignBuffer.io.overwriteExpBuf.valid,
1759    loadMisalignBuffer.io.overwriteExpBuf.isHyper,
1760    storeMisalignBuffer.io.overwriteExpBuf.isHyper
1761  )
1762  val misalignBufExceptionGpaddr = Mux(loadMisalignBuffer.io.overwriteExpBuf.valid,
1763    loadMisalignBuffer.io.overwriteExpBuf.gpaddr,
1764    storeMisalignBuffer.io.overwriteExpBuf.gpaddr
1765  )
1766  val misalignBufExceptionIsForVSnonLeafPTE = Mux(loadMisalignBuffer.io.overwriteExpBuf.valid,
1767    loadMisalignBuffer.io.overwriteExpBuf.isForVSnonLeafPTE,
1768    storeMisalignBuffer.io.overwriteExpBuf.isForVSnonLeafPTE
1769  )
1770
1771  val vSegmentException = RegInit(false.B)
1772  when (DelayN(redirect.valid, 10) && vSegmentException) {
1773    vSegmentException := false.B
1774  }.elsewhen (vSegmentUnit.io.exceptionInfo.valid) {
1775    vSegmentException := true.B
1776  }
1777  val atomicsExceptionAddress = RegEnable(atomicsUnit.io.exceptionInfo.bits.vaddr, atomicsUnit.io.exceptionInfo.valid)
1778  val vSegmentExceptionVstart = RegEnable(vSegmentUnit.io.exceptionInfo.bits.vstart, vSegmentUnit.io.exceptionInfo.valid)
1779  val vSegmentExceptionVl     = RegEnable(vSegmentUnit.io.exceptionInfo.bits.vl, vSegmentUnit.io.exceptionInfo.valid)
1780  val vSegmentExceptionAddress = RegEnable(vSegmentUnit.io.exceptionInfo.bits.vaddr, vSegmentUnit.io.exceptionInfo.valid)
1781  val atomicsExceptionGPAddress = RegEnable(atomicsUnit.io.exceptionInfo.bits.gpaddr, atomicsUnit.io.exceptionInfo.valid)
1782  val vSegmentExceptionGPAddress = RegEnable(vSegmentUnit.io.exceptionInfo.bits.gpaddr, vSegmentUnit.io.exceptionInfo.valid)
1783  val atomicsExceptionIsForVSnonLeafPTE = RegEnable(atomicsUnit.io.exceptionInfo.bits.isForVSnonLeafPTE, atomicsUnit.io.exceptionInfo.valid)
1784  val vSegmentExceptionIsForVSnonLeafPTE = RegEnable(vSegmentUnit.io.exceptionInfo.bits.isForVSnonLeafPTE, vSegmentUnit.io.exceptionInfo.valid)
1785
1786  val exceptionVaddr = Mux(
1787    atomicsException,
1788    atomicsExceptionAddress,
1789    Mux(misalignBufExceptionOverwrite,
1790      misalignBufExceptionVaddr,
1791      Mux(vSegmentException,
1792        vSegmentExceptionAddress,
1793        lsq.io.exceptionAddr.vaddr
1794      )
1795    )
1796  )
1797  // whether vaddr need ext or is hyper inst:
1798  // VaNeedExt: atomicsException -> false; misalignBufExceptionOverwrite -> true; vSegmentException -> false
1799  // IsHyper: atomicsException -> false; vSegmentException -> false
1800  val exceptionVaNeedExt = !atomicsException &&
1801    (misalignBufExceptionOverwrite ||
1802      (!vSegmentException && lsq.io.exceptionAddr.vaNeedExt))
1803  val exceptionIsHyper = !atomicsException &&
1804    (misalignBufExceptionOverwrite && misalignBufExceptionIsHyper ||
1805      (!vSegmentException && lsq.io.exceptionAddr.isHyper && !misalignBufExceptionOverwrite))
1806
1807  def GenExceptionVa(mode: UInt, isVirt: Bool, vaNeedExt: Bool,
1808                     satp: TlbSatpBundle, vsatp: TlbSatpBundle, hgatp: TlbHgatpBundle,
1809                     vaddr: UInt) = {
1810    require(VAddrBits >= 50)
1811
1812    val Sv39 = satp.mode === 8.U
1813    val Sv48 = satp.mode === 9.U
1814    val Sv39x4 = vsatp.mode === 8.U || hgatp.mode === 8.U
1815    val Sv48x4 = vsatp.mode === 9.U || hgatp.mode === 9.U
1816    val vmEnable = !isVirt && (Sv39 || Sv48) && (mode < ModeM)
1817    val s2xlateEnable = isVirt && (Sv39x4 || Sv48x4) && (mode < ModeM)
1818
1819    val s2xlate = MuxCase(noS2xlate, Seq(
1820      !isVirt                                    -> noS2xlate,
1821      (vsatp.mode =/= 0.U && hgatp.mode =/= 0.U) -> allStage,
1822      (vsatp.mode === 0.U)                       -> onlyStage2,
1823      (hgatp.mode === 0.U)                       -> onlyStage1
1824    ))
1825    val onlyS2 = s2xlate === onlyStage2
1826
1827    val bareAddr   = ZeroExt(vaddr(PAddrBits - 1, 0), XLEN)
1828    val sv39Addr   = SignExt(vaddr.take(39), XLEN)
1829    val sv39x4Addr = ZeroExt(vaddr.take(39 + 2), XLEN)
1830    val sv48Addr   = SignExt(vaddr.take(48), XLEN)
1831    val sv48x4Addr = ZeroExt(vaddr.take(48 + 2), XLEN)
1832
1833    val ExceptionVa = Wire(UInt(XLEN.W))
1834    when (vaNeedExt) {
1835      ExceptionVa := Mux1H(Seq(
1836        (!(vmEnable || s2xlateEnable)) -> bareAddr,
1837        (!onlyS2 && (Sv39 || Sv39x4))  -> sv39Addr,
1838        (!onlyS2 && (Sv48 || Sv48x4))  -> sv48Addr,
1839        ( onlyS2 && (Sv39 || Sv39x4))  -> sv39x4Addr,
1840        ( onlyS2 && (Sv48 || Sv48x4))  -> sv48x4Addr,
1841      ))
1842    } .otherwise {
1843      ExceptionVa := vaddr
1844    }
1845
1846    ExceptionVa
1847  }
1848
1849  io.mem_to_ooo.lsqio.vaddr := RegNext(
1850    GenExceptionVa(tlbcsr.priv.dmode, tlbcsr.priv.virt || exceptionIsHyper, exceptionVaNeedExt,
1851    tlbcsr.satp, tlbcsr.vsatp, tlbcsr.hgatp, exceptionVaddr)
1852  )
1853
1854  // vsegment instruction is executed atomic, which mean atomicsException and vSegmentException should not raise at the same time.
1855  XSError(atomicsException && vSegmentException, "atomicsException and vSegmentException raise at the same time!")
1856  io.mem_to_ooo.lsqio.vstart := RegNext(Mux(vSegmentException,
1857                                            vSegmentExceptionVstart,
1858                                            lsq.io.exceptionAddr.vstart)
1859  )
1860  io.mem_to_ooo.lsqio.vl     := RegNext(Mux(vSegmentException,
1861                                            vSegmentExceptionVl,
1862                                            lsq.io.exceptionAddr.vl)
1863  )
1864
1865  XSError(atomicsException && atomicsUnit.io.in.valid, "new instruction before exception triggers\n")
1866  io.mem_to_ooo.lsqio.gpaddr := RegNext(Mux(
1867    atomicsException,
1868    atomicsExceptionGPAddress,
1869    Mux(misalignBufExceptionOverwrite,
1870      misalignBufExceptionGpaddr,
1871      Mux(vSegmentException,
1872        vSegmentExceptionGPAddress,
1873        lsq.io.exceptionAddr.gpaddr
1874      )
1875    )
1876  ))
1877  io.mem_to_ooo.lsqio.isForVSnonLeafPTE := RegNext(Mux(
1878    atomicsException,
1879    atomicsExceptionIsForVSnonLeafPTE,
1880    Mux(misalignBufExceptionOverwrite,
1881      misalignBufExceptionIsForVSnonLeafPTE,
1882      Mux(vSegmentException,
1883        vSegmentExceptionIsForVSnonLeafPTE,
1884        lsq.io.exceptionAddr.isForVSnonLeafPTE
1885      )
1886    )
1887  ))
1888  io.mem_to_ooo.topToBackendBypass match { case x =>
1889    x.hartId            := io.hartId
1890    x.l2FlushDone       := RegNext(io.l2_flush_done)
1891    x.externalInterrupt.msip  := outer.clint_int_sink.in.head._1(0)
1892    x.externalInterrupt.mtip  := outer.clint_int_sink.in.head._1(1)
1893    x.externalInterrupt.meip  := outer.plic_int_sink.in.head._1(0)
1894    x.externalInterrupt.seip  := outer.plic_int_sink.in.last._1(0)
1895    x.externalInterrupt.debug := outer.debug_int_sink.in.head._1(0)
1896    x.externalInterrupt.nmi.nmi_31 := outer.nmi_int_sink.in.head._1(0)
1897    x.externalInterrupt.nmi.nmi_43 := outer.nmi_int_sink.in.head._1(1)
1898    x.msiInfo           := DelayNWithValid(io.fromTopToBackend.msiInfo, 1)
1899    x.clintTime         := DelayNWithValid(io.fromTopToBackend.clintTime, 1)
1900  }
1901
1902  io.memInfo.sqFull := RegNext(lsq.io.sqFull)
1903  io.memInfo.lqFull := RegNext(lsq.io.lqFull)
1904  io.memInfo.dcacheMSHRFull := RegNext(dcache.io.mshrFull)
1905
1906  io.inner_hartId := io.hartId
1907  io.inner_reset_vector := RegNext(io.outer_reset_vector)
1908  io.outer_cpu_halt := io.ooo_to_mem.backendToTopBypass.cpuHalted
1909  io.outer_l2_flush_en := io.ooo_to_mem.csrCtrl.flush_l2_enable
1910  io.outer_power_down_en := io.ooo_to_mem.csrCtrl.power_down_enable
1911  io.outer_cpu_critical_error := io.ooo_to_mem.backendToTopBypass.cpuCriticalError
1912  io.outer_beu_errors_icache := RegNext(io.inner_beu_errors_icache)
1913  io.inner_hc_perfEvents <> RegNext(io.outer_hc_perfEvents)
1914
1915  // vector segmentUnit
1916  vSegmentUnit.io.in.bits <> io.ooo_to_mem.issueVldu.head.bits
1917  vSegmentUnit.io.in.valid := isSegment && io.ooo_to_mem.issueVldu.head.valid// is segment instruction
1918  vSegmentUnit.io.dtlb.resp.bits <> dtlb_reqs.take(LduCnt).head.resp.bits
1919  vSegmentUnit.io.dtlb.resp.valid <> dtlb_reqs.take(LduCnt).head.resp.valid
1920  vSegmentUnit.io.pmpResp <> pmp_check.head.resp
1921  vSegmentUnit.io.flush_sbuffer.empty := stIsEmpty
1922  vSegmentUnit.io.redirect <> redirect
1923  vSegmentUnit.io.rdcache.resp.bits := dcache.io.lsu.load(0).resp.bits
1924  vSegmentUnit.io.rdcache.resp.valid := dcache.io.lsu.load(0).resp.valid
1925  vSegmentUnit.io.rdcache.s2_bank_conflict := dcache.io.lsu.load(0).s2_bank_conflict
1926  // -------------------------
1927  // Vector Segment Triggers
1928  // -------------------------
1929  vSegmentUnit.io.fromCsrTrigger.tdataVec := tdata
1930  vSegmentUnit.io.fromCsrTrigger.tEnableVec := tEnable
1931  vSegmentUnit.io.fromCsrTrigger.triggerCanRaiseBpExp := triggerCanRaiseBpExp
1932  vSegmentUnit.io.fromCsrTrigger.debugMode := debugMode
1933
1934  // reset tree of MemBlock
1935  if (p(DebugOptionsKey).ResetGen) {
1936    val leftResetTree = ResetGenNode(
1937      Seq(
1938        ModuleNode(ptw),
1939        ModuleNode(ptw_to_l2_buffer),
1940        ModuleNode(lsq),
1941        ModuleNode(dtlb_st_tlb_st),
1942        ModuleNode(dtlb_prefetch_tlb_prefetch),
1943        ModuleNode(pmp)
1944      )
1945      ++ pmp_checkers.map(ModuleNode(_))
1946      ++ (if (prefetcherOpt.isDefined) Seq(ModuleNode(prefetcherOpt.get)) else Nil)
1947      ++ (if (l1PrefetcherOpt.isDefined) Seq(ModuleNode(l1PrefetcherOpt.get)) else Nil)
1948    )
1949    val rightResetTree = ResetGenNode(
1950      Seq(
1951        ModuleNode(sbuffer),
1952        ModuleNode(dtlb_ld_tlb_ld),
1953        ModuleNode(dcache),
1954        ModuleNode(l1d_to_l2_buffer),
1955        CellNode(io.reset_backend)
1956      )
1957    )
1958    ResetGen(leftResetTree, reset, sim = false)
1959    ResetGen(rightResetTree, reset, sim = false)
1960  } else {
1961    io.reset_backend := DontCare
1962  }
1963  io.resetInFrontendBypass.toL2Top := io.resetInFrontendBypass.fromFrontend
1964  // trace interface
1965  val traceToL2Top = io.traceCoreInterfaceBypass.toL2Top
1966  val traceFromBackend = io.traceCoreInterfaceBypass.fromBackend
1967  traceFromBackend.fromEncoder := RegNext(traceToL2Top.fromEncoder)
1968  traceToL2Top.toEncoder.trap  := RegEnable(
1969    traceFromBackend.toEncoder.trap,
1970    traceFromBackend.toEncoder.groups(0).valid && Itype.isTrap(traceFromBackend.toEncoder.groups(0).bits.itype)
1971  )
1972  traceToL2Top.toEncoder.priv := RegEnable(
1973    traceFromBackend.toEncoder.priv,
1974    traceFromBackend.toEncoder.groups(0).valid
1975  )
1976  (0 until TraceGroupNum).foreach { i =>
1977    traceToL2Top.toEncoder.groups(i).valid := RegNext(traceFromBackend.toEncoder.groups(i).valid)
1978    traceToL2Top.toEncoder.groups(i).bits.iretire := RegNext(traceFromBackend.toEncoder.groups(i).bits.iretire)
1979    traceToL2Top.toEncoder.groups(i).bits.itype := RegNext(traceFromBackend.toEncoder.groups(i).bits.itype)
1980    traceToL2Top.toEncoder.groups(i).bits.ilastsize := RegEnable(
1981      traceFromBackend.toEncoder.groups(i).bits.ilastsize,
1982      traceFromBackend.toEncoder.groups(i).valid
1983    )
1984    traceToL2Top.toEncoder.groups(i).bits.iaddr := RegEnable(
1985      traceFromBackend.toEncoder.groups(i).bits.iaddr,
1986      traceFromBackend.toEncoder.groups(i).valid
1987    ) + (RegEnable(
1988      traceFromBackend.toEncoder.groups(i).bits.ftqOffset.getOrElse(0.U),
1989      traceFromBackend.toEncoder.groups(i).valid
1990    ) << instOffsetBits)
1991  }
1992
1993
1994  io.mem_to_ooo.storeDebugInfo := DontCare
1995  // store event difftest information
1996  if (env.EnableDifftest) {
1997    (0 until EnsbufferWidth).foreach{i =>
1998        io.mem_to_ooo.storeDebugInfo(i).robidx := sbuffer.io.vecDifftestInfo(i).bits.robIdx
1999        sbuffer.io.vecDifftestInfo(i).bits.pc := io.mem_to_ooo.storeDebugInfo(i).pc
2000    }
2001  }
2002
2003  // top-down info
2004  dcache.io.debugTopDown.robHeadVaddr := io.debugTopDown.robHeadVaddr
2005  dtlbRepeater.io.debugTopDown.robHeadVaddr := io.debugTopDown.robHeadVaddr
2006  lsq.io.debugTopDown.robHeadVaddr := io.debugTopDown.robHeadVaddr
2007  io.debugTopDown.toCore.robHeadMissInDCache := dcache.io.debugTopDown.robHeadMissInDCache
2008  io.debugTopDown.toCore.robHeadTlbReplay := lsq.io.debugTopDown.robHeadTlbReplay
2009  io.debugTopDown.toCore.robHeadTlbMiss := lsq.io.debugTopDown.robHeadTlbMiss
2010  io.debugTopDown.toCore.robHeadLoadVio := lsq.io.debugTopDown.robHeadLoadVio
2011  io.debugTopDown.toCore.robHeadLoadMSHR := lsq.io.debugTopDown.robHeadLoadMSHR
2012  dcache.io.debugTopDown.robHeadOtherReplay := lsq.io.debugTopDown.robHeadOtherReplay
2013  dcache.io.debugRolling := io.debugRolling
2014
2015  lsq.io.noUopsIssued := io.topDownInfo.toBackend.noUopsIssued
2016  io.topDownInfo.toBackend.lqEmpty := lsq.io.lqEmpty
2017  io.topDownInfo.toBackend.sqEmpty := lsq.io.sqEmpty
2018  io.topDownInfo.toBackend.l1Miss := dcache.io.l1Miss
2019  io.topDownInfo.toBackend.l2TopMiss.l2Miss := RegNext(io.topDownInfo.fromL2Top.l2Miss)
2020  io.topDownInfo.toBackend.l2TopMiss.l3Miss := RegNext(io.topDownInfo.fromL2Top.l3Miss)
2021
2022  val hyLdDeqCount = PopCount(io.ooo_to_mem.issueHya.map(x => x.valid && FuType.isLoad(x.bits.uop.fuType)))
2023  val hyStDeqCount = PopCount(io.ooo_to_mem.issueHya.map(x => x.valid && FuType.isStore(x.bits.uop.fuType)))
2024  val ldDeqCount = PopCount(io.ooo_to_mem.issueLda.map(_.valid)) +& hyLdDeqCount
2025  val stDeqCount = PopCount(io.ooo_to_mem.issueSta.take(StaCnt).map(_.valid)) +& hyStDeqCount
2026  val iqDeqCount = ldDeqCount +& stDeqCount
2027  XSPerfAccumulate("load_iq_deq_count", ldDeqCount)
2028  XSPerfHistogram("load_iq_deq_count", ldDeqCount, true.B, 0, LdExuCnt + 1)
2029  XSPerfAccumulate("store_iq_deq_count", stDeqCount)
2030  XSPerfHistogram("store_iq_deq_count", stDeqCount, true.B, 0, StAddrCnt + 1)
2031  XSPerfAccumulate("ls_iq_deq_count", iqDeqCount)
2032
2033  val pfevent = Module(new PFEvent)
2034  pfevent.io.distribute_csr := csrCtrl.distribute_csr
2035  val csrevents = pfevent.io.hpmevent.slice(16,24)
2036
2037  val perfFromUnits = (loadUnits ++ Seq(sbuffer, lsq, dcache)).flatMap(_.getPerfEvents)
2038  val perfFromPTW = perfEventsPTW.map(x => ("PTW_" + x._1, x._2))
2039  val perfBlock     = Seq(("ldDeqCount", ldDeqCount),
2040                          ("stDeqCount", stDeqCount))
2041  // let index = 0 be no event
2042  val allPerfEvents = Seq(("noEvent", 0.U)) ++ perfFromUnits ++ perfFromPTW ++ perfBlock
2043
2044  if (printEventCoding) {
2045    for (((name, inc), i) <- allPerfEvents.zipWithIndex) {
2046      println("MemBlock perfEvents Set", name, inc, i)
2047    }
2048  }
2049
2050  val allPerfInc = allPerfEvents.map(_._2.asTypeOf(new PerfEvent))
2051  val perfEvents = HPerfMonitor(csrevents, allPerfInc).getPerfEvents
2052  generatePerfEvent()
2053}
2054
2055class MemBlock()(implicit p: Parameters) extends LazyModule
2056  with HasXSParameter {
2057  override def shouldBeInlined: Boolean = false
2058
2059  val inner = LazyModule(new MemBlockInlined())
2060
2061  lazy val module = new MemBlockImp(this)
2062}
2063
2064class MemBlockImp(wrapper: MemBlock) extends LazyModuleImp(wrapper) {
2065  val io = IO(wrapper.inner.module.io.cloneType)
2066  val io_perf = IO(wrapper.inner.module.io_perf.cloneType)
2067  io <> wrapper.inner.module.io
2068  io_perf <> wrapper.inner.module.io_perf
2069
2070  if (p(DebugOptionsKey).ResetGen) {
2071    ResetGen(ResetGenNode(Seq(ModuleNode(wrapper.inner.module))), reset, sim = false)
2072  }
2073}
2074