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