xref: /XiangShan/src/main/scala/xiangshan/mem/sbuffer/Sbuffer.scala (revision b03c55a5df5dc8793cb44b42dd60141566e57e78)
1/***************************************************************************************
2* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC)
3* Copyright (c) 2020-2024 Institute of Computing Technology, Chinese Academy of Sciences
4* Copyright (c) 2020-2021 Peng Cheng Laboratory
5*
6* XiangShan is licensed under Mulan PSL v2.
7* You can use this software according to the terms and conditions of the Mulan PSL v2.
8* You may obtain a copy of Mulan PSL v2 at:
9*          http://license.coscl.org.cn/MulanPSL2
10*
11* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
12* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
13* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
14*
15* See the Mulan PSL v2 for more details.
16***************************************************************************************/
17
18package xiangshan.mem
19
20import org.chipsalliance.cde.config.Parameters
21import chisel3._
22import chisel3.util._
23import xiangshan._
24import utils._
25import utility._
26import xiangshan.cache._
27import xiangshan.mem._
28import xiangshan.backend.Bundles.DynInst
29import difftest._
30import freechips.rocketchip.util._
31import xiangshan.backend.fu.FuType._
32
33class SbufferFlushBundle extends Bundle {
34  val valid = Output(Bool())
35  val empty = Input(Bool())
36}
37
38trait HasSbufferConst extends HasXSParameter {
39  val EvictCycles = 1 << 20
40  val SbufferReplayDelayCycles = 16
41  require(isPow2(EvictCycles))
42  val EvictCountBits = log2Up(EvictCycles+1)
43  val MissqReplayCountBits = log2Up(SbufferReplayDelayCycles) + 1
44
45  // dcache write hit resp has 2 sources
46  // refill pipe resp and main pipe resp (fixed:only main pipe resp)
47  // val NumDcacheWriteResp = 2 // hardcoded
48  val NumDcacheWriteResp = 1 // hardcoded
49
50  val SbufferIndexWidth: Int = log2Up(StoreBufferSize)
51  // paddr = ptag + offset
52  val CacheLineBytes: Int = CacheLineSize / 8
53  val CacheLineWords: Int = CacheLineBytes / DataBytes
54  val OffsetWidth: Int = log2Up(CacheLineBytes)
55  val WordsWidth: Int = log2Up(CacheLineWords)
56  val PTagWidth: Int = PAddrBits - OffsetWidth
57  val VTagWidth: Int = VAddrBits - OffsetWidth
58  val WordOffsetWidth: Int = PAddrBits - WordsWidth
59
60  val CacheLineVWords: Int = CacheLineBytes / VDataBytes
61  val VWordsWidth: Int = log2Up(CacheLineVWords)
62  val VWordWidth: Int = log2Up(VDataBytes)
63  val VWordOffsetWidth: Int = PAddrBits - VWordWidth
64}
65
66class SbufferEntryState (implicit p: Parameters) extends SbufferBundle {
67  val state_valid    = Bool() // this entry is active
68  val state_inflight = Bool() // sbuffer is trying to write this entry to dcache
69  val w_timeout = Bool() // with timeout resp, waiting for resend store pipeline req timeout
70  val w_sameblock_inflight = Bool() // same cache block dcache req is inflight
71
72  def isInvalid(): Bool = !state_valid
73  def isValid(): Bool = state_valid
74  def isActive(): Bool = state_valid && !state_inflight
75  def isInflight(): Bool = state_inflight
76  def isDcacheReqCandidate(): Bool = state_valid && !state_inflight && !w_sameblock_inflight
77}
78
79class SbufferBundle(implicit p: Parameters) extends XSBundle with HasSbufferConst
80
81class DataWriteReq(implicit p: Parameters) extends SbufferBundle {
82  // univerisal writemask
83  val wvec = UInt(StoreBufferSize.W)
84  // 2 cycle update
85  val mask = UInt((VLEN/8).W)
86  val data = UInt(VLEN.W)
87  val vwordOffset = UInt(VWordOffsetWidth.W)
88  val wline = Bool() // write full cacheline
89}
90
91class MaskFlushReq(implicit p: Parameters) extends SbufferBundle {
92  // univerisal writemask
93  val wvec = UInt(StoreBufferSize.W)
94}
95
96class SbufferData(implicit p: Parameters) extends XSModule with HasSbufferConst {
97  val io = IO(new Bundle(){
98    // update data and mask when alloc or merge
99    val writeReq = Vec(EnsbufferWidth, Flipped(ValidIO(new DataWriteReq)))
100    // clean mask when deq
101    val maskFlushReq = Vec(NumDcacheWriteResp, Flipped(ValidIO(new MaskFlushReq)))
102    val dataOut = Output(Vec(StoreBufferSize, Vec(CacheLineVWords, Vec(VDataBytes, UInt(8.W)))))
103    val maskOut = Output(Vec(StoreBufferSize, Vec(CacheLineVWords, Vec(VDataBytes, Bool()))))
104  })
105
106  val data = Reg(Vec(StoreBufferSize, Vec(CacheLineVWords, Vec(VDataBytes, UInt(8.W)))))
107  // val mask = Reg(Vec(StoreBufferSize, Vec(CacheLineWords, Vec(DataBytes, Bool()))))
108  val mask = RegInit(
109    VecInit(Seq.fill(StoreBufferSize)(
110      VecInit(Seq.fill(CacheLineVWords)(
111        VecInit(Seq.fill(VDataBytes)(false.B))
112      ))
113    ))
114  )
115
116  // 2 cycle line mask clean
117  for(line <- 0 until StoreBufferSize){
118    val line_mask_clean_flag = GatedValidRegNext(
119      io.maskFlushReq.map(a => a.valid && a.bits.wvec(line)).reduce(_ || _)
120    )
121    line_mask_clean_flag.suggestName("line_mask_clean_flag_"+line)
122    when(line_mask_clean_flag){
123      for(word <- 0 until CacheLineVWords){
124        for(byte <- 0 until VDataBytes){
125          mask(line)(word)(byte) := false.B
126        }
127      }
128    }
129  }
130
131  // 2 cycle data / mask update
132  for(i <- 0 until EnsbufferWidth) {
133    val req = io.writeReq(i)
134    for(line <- 0 until StoreBufferSize){
135      val sbuffer_in_s1_line_wen = req.valid && req.bits.wvec(line)
136      val sbuffer_in_s2_line_wen = GatedValidRegNext(sbuffer_in_s1_line_wen)
137      val line_write_buffer_data = RegEnable(req.bits.data, sbuffer_in_s1_line_wen)
138      val line_write_buffer_wline = RegEnable(req.bits.wline, sbuffer_in_s1_line_wen)
139      val line_write_buffer_mask = RegEnable(req.bits.mask, sbuffer_in_s1_line_wen)
140      val line_write_buffer_offset = RegEnable(req.bits.vwordOffset(VWordsWidth-1, 0), sbuffer_in_s1_line_wen)
141      sbuffer_in_s1_line_wen.suggestName("sbuffer_in_s1_line_wen_"+line)
142      sbuffer_in_s2_line_wen.suggestName("sbuffer_in_s2_line_wen_"+line)
143      line_write_buffer_data.suggestName("line_write_buffer_data_"+line)
144      line_write_buffer_wline.suggestName("line_write_buffer_wline_"+line)
145      line_write_buffer_mask.suggestName("line_write_buffer_mask_"+line)
146      line_write_buffer_offset.suggestName("line_write_buffer_offset_"+line)
147      for(word <- 0 until CacheLineVWords){
148        for(byte <- 0 until VDataBytes){
149          val write_byte = sbuffer_in_s2_line_wen && (
150            line_write_buffer_mask(byte) && (line_write_buffer_offset === word.U) ||
151            line_write_buffer_wline
152          )
153          when(write_byte){
154            data(line)(word)(byte) := line_write_buffer_data(byte*8+7, byte*8)
155            mask(line)(word)(byte) := true.B
156          }
157        }
158      }
159    }
160  }
161
162  // 1 cycle line mask clean
163  // for(i <- 0 until EnsbufferWidth) {
164  //   val req = io.writeReq(i)
165  //   when(req.valid){
166  //     for(line <- 0 until StoreBufferSize){
167  //       when(
168  //         req.bits.wvec(line) &&
169  //         req.bits.cleanMask
170  //       ){
171  //         for(word <- 0 until CacheLineWords){
172  //           for(byte <- 0 until DataBytes){
173  //             mask(line)(word)(byte) := false.B
174  //             val debug_last_cycle_write_byte = RegNext(req.valid && req.bits.wvec(line) && (
175  //               req.bits.mask(byte) && (req.bits.wordOffset(WordsWidth-1, 0) === word.U) ||
176  //               req.bits.wline
177  //             ))
178  //             assert(!debug_last_cycle_write_byte)
179  //           }
180  //         }
181  //       }
182  //     }
183  //   }
184  // }
185
186  io.dataOut := data
187  io.maskOut := mask
188}
189
190class Sbuffer(implicit p: Parameters)
191  extends DCacheModule
192    with HasSbufferConst
193    with HasPerfEvents {
194  val io = IO(new Bundle() {
195    val hartId = Input(UInt(hartIdLen.W))
196    val in = Vec(EnsbufferWidth, Flipped(Decoupled(new DCacheWordReqWithVaddrAndPfFlag)))  //Todo: store logic only support Width == 2 now
197    val vecDifftestInfo = Vec(EnsbufferWidth, Flipped(Decoupled(new DynInst)))
198    val dcache = Flipped(new DCacheToSbufferIO)
199    val forward = Vec(LoadPipelineWidth, Flipped(new LoadForwardQueryIO))
200    val sqempty = Input(Bool())
201    val flush = Flipped(new SbufferFlushBundle)
202    val csrCtrl = Flipped(new CustomCSRCtrlIO)
203    val store_prefetch = Vec(StorePipelineWidth, DecoupledIO(new StorePrefetchReq)) // to dcache
204    val memSetPattenDetected = Input(Bool())
205    val force_write = Input(Bool())
206  })
207
208  val dataModule = Module(new SbufferData)
209  dataModule.io.writeReq <> DontCare
210  val prefetcher = Module(new StorePfWrapper())
211  val writeReq = dataModule.io.writeReq
212
213  val ptag = Reg(Vec(StoreBufferSize, UInt(PTagWidth.W)))
214  val vtag = Reg(Vec(StoreBufferSize, UInt(VTagWidth.W)))
215  val debug_mask = Reg(Vec(StoreBufferSize, Vec(CacheLineWords, Vec(DataBytes, Bool()))))
216  val waitInflightMask = Reg(Vec(StoreBufferSize, UInt(StoreBufferSize.W)))
217  val data = dataModule.io.dataOut
218  val mask = dataModule.io.maskOut
219  val stateVec = RegInit(VecInit(Seq.fill(StoreBufferSize)(0.U.asTypeOf(new SbufferEntryState))))
220  val cohCount = RegInit(VecInit(Seq.fill(StoreBufferSize)(0.U(EvictCountBits.W))))
221  val missqReplayCount = RegInit(VecInit(Seq.fill(StoreBufferSize)(0.U(MissqReplayCountBits.W))))
222
223  val sbuffer_out_s0_fire = Wire(Bool())
224
225  /*
226       idle --[flush]   --> drain   --[buf empty]--> idle
227            --[buf full]--> replace --[dcache resp]--> idle
228  */
229  // x_drain_all: drain store queue and sbuffer
230  // x_drain_sbuffer: drain sbuffer only, block store queue to sbuffer write
231  val x_idle :: x_replace :: x_drain_all :: x_drain_sbuffer :: Nil = Enum(4)
232  def needDrain(state: UInt): Bool =
233    state(1)
234  val sbuffer_state = RegInit(x_idle)
235
236  // ---------------------- Store Enq Sbuffer ---------------------
237
238  def getPTag(pa: UInt): UInt =
239    pa(PAddrBits - 1, PAddrBits - PTagWidth)
240
241  def getVTag(va: UInt): UInt =
242    va(VAddrBits - 1, VAddrBits - VTagWidth)
243
244  def getWord(pa: UInt): UInt =
245    pa(PAddrBits-1, 3)
246
247  def getVWord(pa: UInt): UInt =
248    pa(PAddrBits-1, 4)
249
250  def getWordOffset(pa: UInt): UInt =
251    pa(OffsetWidth-1, 3)
252
253  def getVWordOffset(pa: UInt): UInt =
254    pa(OffsetWidth-1, 4)
255
256  def getAddr(ptag: UInt): UInt =
257    Cat(ptag, 0.U((PAddrBits - PTagWidth).W))
258
259  def getByteOffset(offect: UInt): UInt =
260    Cat(offect(OffsetWidth - 1, 3), 0.U(3.W))
261
262  def isOneOf(key: UInt, seq: Seq[UInt]): Bool =
263    if(seq.isEmpty) false.B else Cat(seq.map(_===key)).orR
264
265  def widthMap[T <: Data](f: Int => T) = (0 until StoreBufferSize) map f
266
267  // sbuffer entry count
268
269  val plru = new ValidPseudoLRU(StoreBufferSize)
270  val accessIdx = Wire(Vec(EnsbufferWidth + 1, Valid(UInt(SbufferIndexWidth.W))))
271
272  val candidateVec = VecInit(stateVec.map(s => s.isDcacheReqCandidate()))
273
274  val replaceAlgoIdx = plru.way(candidateVec.reverse)._2
275  val replaceAlgoNotDcacheCandidate = !stateVec(replaceAlgoIdx).isDcacheReqCandidate()
276
277  assert(!(candidateVec.asUInt.orR && replaceAlgoNotDcacheCandidate), "we have way to select, but replace algo selects invalid way")
278
279  val replaceIdx = replaceAlgoIdx
280  plru.access(accessIdx)
281
282  //-------------------------cohCount-----------------------------
283  // insert and merge: cohCount=0
284  // every cycle cohCount+=1
285  // if cohCount(EvictCountBits-1)==1, evict
286  val cohTimeOutMask = VecInit(widthMap(i => cohCount(i)(EvictCountBits - 1) && stateVec(i).isActive()))
287  val (cohTimeOutIdx, cohHasTimeOut) = PriorityEncoderWithFlag(cohTimeOutMask)
288  val cohTimeOutOH = PriorityEncoderOH(cohTimeOutMask)
289  val missqReplayTimeOutMask = VecInit(widthMap(i => missqReplayCount(i)(MissqReplayCountBits - 1) && stateVec(i).w_timeout))
290  val (missqReplayTimeOutIdxGen, missqReplayHasTimeOutGen) = PriorityEncoderWithFlag(missqReplayTimeOutMask)
291  val missqReplayHasTimeOut = GatedValidRegNext(missqReplayHasTimeOutGen) && !GatedValidRegNext(sbuffer_out_s0_fire)
292  val missqReplayTimeOutIdx = RegEnable(missqReplayTimeOutIdxGen, missqReplayHasTimeOutGen)
293
294  //-------------------------sbuffer enqueue-----------------------------
295
296  // Now sbuffer enq logic is divided into 3 stages:
297
298  // sbuffer_in_s0:
299  // * read data and meta from store queue
300  // * store them in 2 entry fifo queue
301
302  // sbuffer_in_s1:
303  // * read data and meta from fifo queue
304  // * update sbuffer meta (vtag, ptag, flag)
305  // * prevert that line from being sent to dcache (add a block condition)
306  // * prepare cacheline level write enable signal, RegNext() data and mask
307
308  // sbuffer_in_s2:
309  // * use cacheline level buffer to update sbuffer data and mask
310  // * remove dcache write block (if there is)
311
312  val activeMask = VecInit(stateVec.map(s => s.isActive()))
313  val validMask  = VecInit(stateVec.map(s => s.isValid()))
314  val drainIdx = PriorityEncoder(activeMask)
315
316  val inflightMask = VecInit(stateVec.map(s => s.isInflight()))
317
318  val inptags = io.in.map(in => getPTag(in.bits.addr))
319  val invtags = io.in.map(in => getVTag(in.bits.vaddr))
320  val sameTag = inptags(0) === inptags(1)
321  val firstWord = getVWord(io.in(0).bits.addr)
322  val secondWord = getVWord(io.in(1).bits.addr)
323  // merge condition
324  val mergeMask = Wire(Vec(EnsbufferWidth, Vec(StoreBufferSize, Bool())))
325  val mergeIdx = mergeMask.map(PriorityEncoder(_)) // avoid using mergeIdx for better timing
326  val canMerge = mergeMask.map(ParallelOR(_))
327  val mergeVec = mergeMask.map(_.asUInt)
328
329  for(i <- 0 until EnsbufferWidth){
330    mergeMask(i) := widthMap(j =>
331      inptags(i) === ptag(j) && activeMask(j)
332    )
333    assert(!(PopCount(mergeMask(i).asUInt) > 1.U && io.in(i).fire && io.in(i).bits.vecValid))
334  }
335
336  // insert condition
337  // firstInsert: the first invalid entry
338  // if first entry canMerge or second entry has the same ptag with the first entry,
339  // secondInsert equal the first invalid entry, otherwise, the second invalid entry
340  val invalidMask = VecInit(stateVec.map(s => s.isInvalid()))
341  val evenInvalidMask = GetEvenBits(invalidMask.asUInt)
342  val oddInvalidMask = GetOddBits(invalidMask.asUInt)
343
344  def getFirstOneOH(input: UInt): UInt = {
345    assert(input.getWidth > 1)
346    val output = WireInit(VecInit(input.asBools))
347    (1 until input.getWidth).map(i => {
348      output(i) := !input(i - 1, 0).orR && input(i)
349    })
350    output.asUInt
351  }
352
353  val evenRawInsertVec = getFirstOneOH(evenInvalidMask)
354  val oddRawInsertVec = getFirstOneOH(oddInvalidMask)
355  val (evenRawInsertIdx, evenCanInsert) = PriorityEncoderWithFlag(evenInvalidMask)
356  val (oddRawInsertIdx, oddCanInsert) = PriorityEncoderWithFlag(oddInvalidMask)
357  val evenInsertIdx = Cat(evenRawInsertIdx, 0.U(1.W)) // slow to generate, for debug only
358  val oddInsertIdx = Cat(oddRawInsertIdx, 1.U(1.W)) // slow to generate, for debug only
359  val evenInsertVec = GetEvenBits.reverse(evenRawInsertVec)
360  val oddInsertVec = GetOddBits.reverse(oddRawInsertVec)
361
362  val enbufferSelReg = RegInit(false.B)
363  when(io.in(0).valid) {
364    enbufferSelReg := ~enbufferSelReg
365  }
366
367  val firstInsertIdx = Mux(enbufferSelReg, evenInsertIdx, oddInsertIdx) // slow to generate, for debug only
368  val secondInsertIdx = Mux(sameTag,
369    firstInsertIdx,
370    Mux(~enbufferSelReg, evenInsertIdx, oddInsertIdx)
371  ) // slow to generate, for debug only
372  val firstInsertVec = Mux(enbufferSelReg, evenInsertVec, oddInsertVec)
373  val secondInsertVec = Mux(sameTag,
374    firstInsertVec,
375    Mux(~enbufferSelReg, evenInsertVec, oddInsertVec)
376  ) // slow to generate, for debug only
377  val firstCanInsert = sbuffer_state =/= x_drain_sbuffer && Mux(enbufferSelReg, evenCanInsert, oddCanInsert)
378  val secondCanInsert = sbuffer_state =/= x_drain_sbuffer && Mux(sameTag,
379    firstCanInsert,
380    Mux(~enbufferSelReg, evenCanInsert, oddCanInsert)
381  ) && (EnsbufferWidth >= 1).B
382  val forward_need_uarch_drain = WireInit(false.B)
383  val merge_need_uarch_drain = WireInit(false.B)
384  val do_uarch_drain = GatedValidRegNext(forward_need_uarch_drain) || GatedValidRegNext(GatedValidRegNext(merge_need_uarch_drain))
385  XSPerfAccumulate("do_uarch_drain", do_uarch_drain)
386
387  io.in(0).ready := firstCanInsert
388  io.in(1).ready := secondCanInsert && io.in(0).ready
389
390  for (i <- 0 until EnsbufferWidth) {
391    // train
392    if (EnableStorePrefetchSPB) {
393      prefetcher.io.sbuffer_enq(i).valid := io.in(i).fire && io.in(i).bits.vecValid
394      prefetcher.io.sbuffer_enq(i).bits := DontCare
395      prefetcher.io.sbuffer_enq(i).bits.vaddr := io.in(i).bits.vaddr
396    } else {
397      prefetcher.io.sbuffer_enq(i).valid := false.B
398      prefetcher.io.sbuffer_enq(i).bits := DontCare
399    }
400
401    // prefetch req
402    if (EnableStorePrefetchAtCommit) {
403      if (EnableAtCommitMissTrigger) {
404        io.store_prefetch(i).valid := prefetcher.io.prefetch_req(i).valid || (io.in(i).fire && io.in(i).bits.vecValid && io.in(i).bits.prefetch)
405      } else {
406        io.store_prefetch(i).valid := prefetcher.io.prefetch_req(i).valid || (io.in(i).fire && io.in(i).bits.vecValid)
407      }
408      io.store_prefetch(i).bits.paddr := DontCare
409      io.store_prefetch(i).bits.vaddr := Mux(prefetcher.io.prefetch_req(i).valid, prefetcher.io.prefetch_req(i).bits.vaddr, io.in(i).bits.vaddr)
410      prefetcher.io.prefetch_req(i).ready := io.store_prefetch(i).ready
411    } else {
412      io.store_prefetch(i) <> prefetcher.io.prefetch_req(i)
413    }
414    io.store_prefetch zip prefetcher.io.prefetch_req drop 2 foreach (x => x._1 <> x._2)
415  }
416  prefetcher.io.memSetPattenDetected := io.memSetPattenDetected
417
418  def wordReqToBufLine( // allocate a new line in sbuffer
419    req: DCacheWordReq,
420    reqptag: UInt,
421    reqvtag: UInt,
422    insertIdx: UInt,
423    insertVec: UInt,
424    wordOffset: UInt
425  ): Unit = {
426    assert(UIntToOH(insertIdx) === insertVec)
427    val sameBlockInflightMask = genSameBlockInflightMask(reqptag)
428    (0 until StoreBufferSize).map(entryIdx => {
429      when(insertVec(entryIdx)){
430        stateVec(entryIdx).state_valid := true.B
431        stateVec(entryIdx).w_sameblock_inflight := sameBlockInflightMask.orR // set w_sameblock_inflight when a line is first allocated
432        when(sameBlockInflightMask.orR){
433          waitInflightMask(entryIdx) := sameBlockInflightMask
434        }
435        cohCount(entryIdx) := 0.U
436        // missqReplayCount(insertIdx) := 0.U
437        ptag(entryIdx) := reqptag
438        vtag(entryIdx) := reqvtag // update vtag if a new sbuffer line is allocated
439      }
440    })
441  }
442
443  def mergeWordReq( // merge write req into an existing line
444    req: DCacheWordReq,
445    reqptag: UInt,
446    reqvtag: UInt,
447    mergeIdx: UInt,
448    mergeVec: UInt,
449    wordOffset: UInt
450  ): Unit = {
451    assert(UIntToOH(mergeIdx) === mergeVec)
452    (0 until StoreBufferSize).map(entryIdx => {
453      when(mergeVec(entryIdx)) {
454        cohCount(entryIdx) := 0.U
455        // missqReplayCount(entryIdx) := 0.U
456        // check if vtag is the same, if not, trigger sbuffer flush
457        when(reqvtag =/= vtag(entryIdx)) {
458          XSDebug("reqvtag =/= sbufvtag req(vtag %x ptag %x) sbuffer(vtag %x ptag %x)\n",
459            reqvtag << OffsetWidth,
460            reqptag << OffsetWidth,
461            vtag(entryIdx) << OffsetWidth,
462            ptag(entryIdx) << OffsetWidth
463          )
464          merge_need_uarch_drain := true.B
465        }
466      }
467    })
468  }
469
470  for(((in, vwordOffset), i) <- io.in.zip(Seq(firstWord, secondWord)).zipWithIndex){
471    writeReq(i).valid := in.fire && in.bits.vecValid
472    writeReq(i).bits.vwordOffset := vwordOffset
473    writeReq(i).bits.mask := in.bits.mask
474    writeReq(i).bits.data := in.bits.data
475    writeReq(i).bits.wline := in.bits.wline
476    val debug_insertIdx = if(i == 0) firstInsertIdx else secondInsertIdx
477    val insertVec = if(i == 0) firstInsertVec else secondInsertVec
478    assert(!((PopCount(insertVec) > 1.U) && in.fire && in.bits.vecValid))
479    val insertIdx = OHToUInt(insertVec)
480    val accessValid = in.fire && in.bits.vecValid
481    accessIdx(i).valid := RegNext(accessValid)
482    accessIdx(i).bits := RegEnable(Mux(canMerge(i), mergeIdx(i), insertIdx), accessValid)
483    when(accessValid){
484      when(canMerge(i)){
485        writeReq(i).bits.wvec := mergeVec(i)
486        mergeWordReq(in.bits, inptags(i), invtags(i), mergeIdx(i), mergeVec(i), vwordOffset)
487        XSDebug(p"merge req $i to line [${mergeIdx(i)}]\n")
488      }.otherwise({
489        writeReq(i).bits.wvec := insertVec
490        wordReqToBufLine(in.bits, inptags(i), invtags(i), insertIdx, insertVec, vwordOffset)
491        XSDebug(p"insert req $i to line[$insertIdx]\n")
492        assert(debug_insertIdx === insertIdx)
493      })
494    }
495  }
496
497
498  for(i <- 0 until StoreBufferSize){
499    XSDebug(stateVec(i).isValid(),
500      p"[$i] timeout:${cohCount(i)(EvictCountBits-1)} state:${stateVec(i)}\n"
501    )
502  }
503
504  for((req, i) <- io.in.zipWithIndex){
505    XSDebug(req.fire && req.bits.vecValid,
506      p"accept req [$i]: " +
507        p"addr:${Hexadecimal(req.bits.addr)} " +
508        p"mask:${Binary(shiftMaskToLow(req.bits.addr,req.bits.mask))} " +
509        p"data:${Hexadecimal(shiftDataToLow(req.bits.addr,req.bits.data))}\n"
510    )
511    XSDebug(req.valid && !req.ready,
512      p"req [$i] blocked by sbuffer\n"
513    )
514  }
515
516  // for now, when enq, trigger a prefetch (if EnableAtCommitMissTrigger)
517  require(EnsbufferWidth <= StorePipelineWidth)
518
519  // ---------------------- Send Dcache Req ---------------------
520
521  val sbuffer_empty = Cat(invalidMask).andR
522  val sq_empty = !Cat(io.in.map(_.valid)).orR
523  val empty = sbuffer_empty && sq_empty
524  val threshold = Wire(UInt(5.W)) // RegNext(io.csrCtrl.sbuffer_threshold +& 1.U)
525  threshold := Constantin.createRecord(s"StoreBufferThreshold_${p(XSCoreParamsKey).HartId}", initValue = 7)
526  val base = Wire(UInt(5.W))
527  base := Constantin.createRecord(s"StoreBufferBase_${p(XSCoreParamsKey).HartId}", initValue = 4)
528  val ActiveCount = PopCount(activeMask)
529  val ValidCount = PopCount(validMask)
530  val forceThreshold = Mux(io.force_write, threshold - base, threshold)
531  val do_eviction = GatedValidRegNext(ActiveCount >= forceThreshold || ActiveCount === (StoreBufferSize-1).U || ValidCount === (StoreBufferSize).U, init = false.B)
532  require((StoreBufferThreshold + 1) <= StoreBufferSize)
533
534  XSDebug(p"ActiveCount[$ActiveCount]\n")
535
536  io.flush.empty := GatedValidRegNext(empty && io.sqempty)
537  // lru.io.flush := sbuffer_state === x_drain_all && empty
538  switch(sbuffer_state){
539    is(x_idle){
540      when(io.flush.valid){
541        sbuffer_state := x_drain_all
542      }.elsewhen(do_uarch_drain){
543        sbuffer_state := x_drain_sbuffer
544      }.elsewhen(do_eviction){
545        sbuffer_state := x_replace
546      }
547    }
548    is(x_drain_all){
549      when(empty){
550        sbuffer_state := x_idle
551      }
552    }
553    is(x_drain_sbuffer){
554      when(io.flush.valid){
555        sbuffer_state := x_drain_all
556      }.elsewhen(sbuffer_empty){
557        sbuffer_state := x_idle
558      }
559    }
560    is(x_replace){
561      when(io.flush.valid){
562        sbuffer_state := x_drain_all
563      }.elsewhen(do_uarch_drain){
564        sbuffer_state := x_drain_sbuffer
565      }.elsewhen(!do_eviction){
566        sbuffer_state := x_idle
567      }
568    }
569  }
570  XSDebug(p"sbuffer state:${sbuffer_state} do eviction:${do_eviction} empty:${empty}\n")
571
572  def noSameBlockInflight(idx: UInt): Bool = {
573    // stateVec(idx) itself must not be s_inflight
574    !Cat(widthMap(i => inflightMask(i) && ptag(idx) === ptag(i))).orR
575  }
576
577  def genSameBlockInflightMask(ptag_in: UInt): UInt = {
578    val mask = VecInit(widthMap(i => inflightMask(i) && ptag_in === ptag(i))).asUInt // quite slow, use it with care
579    assert(!(PopCount(mask) > 1.U))
580    mask
581  }
582
583  def haveSameBlockInflight(ptag_in: UInt): Bool = {
584    genSameBlockInflightMask(ptag_in).orR
585  }
586
587  // ---------------------------------------------------------------------------
588  // sbuffer to dcache pipeline
589  // ---------------------------------------------------------------------------
590
591  // Now sbuffer deq logic is divided into 2 stages:
592
593  // sbuffer_out_s0:
594  // * read data and meta from sbuffer
595  // * RegNext() them
596  // * set line state to inflight
597
598  // sbuffer_out_s1:
599  // * send write req to dcache
600
601  // sbuffer_out_extra:
602  // * receive write result from dcache
603  // * update line state
604
605  val sbuffer_out_s1_ready = Wire(Bool())
606
607  // ---------------------------------------------------------------------------
608  // sbuffer_out_s0
609  // ---------------------------------------------------------------------------
610
611  val need_drain = needDrain(sbuffer_state)
612  val need_replace = do_eviction || (sbuffer_state === x_replace)
613  val sbuffer_out_s0_evictionIdx = Mux(missqReplayHasTimeOut,
614    missqReplayTimeOutIdx,
615    Mux(need_drain,
616      drainIdx,
617      Mux(cohHasTimeOut, cohTimeOutIdx, replaceIdx)
618    )
619  )
620
621  // If there is a inflight dcache req which has same ptag with sbuffer_out_s0_evictionIdx's ptag,
622  // current eviction should be blocked.
623  val sbuffer_out_s0_valid = missqReplayHasTimeOut ||
624    stateVec(sbuffer_out_s0_evictionIdx).isDcacheReqCandidate() &&
625    (need_drain || cohHasTimeOut || need_replace)
626  assert(!(
627    stateVec(sbuffer_out_s0_evictionIdx).isDcacheReqCandidate() &&
628    !noSameBlockInflight(sbuffer_out_s0_evictionIdx)
629  ))
630  val sbuffer_out_s0_cango = sbuffer_out_s1_ready
631  sbuffer_out_s0_fire := sbuffer_out_s0_valid && sbuffer_out_s0_cango
632
633  // ---------------------------------------------------------------------------
634  // sbuffer_out_s1
635  // ---------------------------------------------------------------------------
636
637  // TODO: use EnsbufferWidth
638  val shouldWaitWriteFinish = GatedValidRegNext(VecInit((0 until EnsbufferWidth).map{i =>
639    (writeReq(i).bits.wvec.asUInt & UIntToOH(sbuffer_out_s0_evictionIdx).asUInt).orR &&
640    writeReq(i).valid
641  }).asUInt.orR)
642  // block dcache write if read / write hazard
643  val blockDcacheWrite = shouldWaitWriteFinish
644
645  val sbuffer_out_s1_valid = RegInit(false.B)
646  sbuffer_out_s1_ready := io.dcache.req.ready && !blockDcacheWrite || !sbuffer_out_s1_valid
647  val sbuffer_out_s1_fire = io.dcache.req.fire
648
649  // when sbuffer_out_s1_fire, send dcache req stored in pipeline reg to dcache
650  when(sbuffer_out_s1_fire){
651    sbuffer_out_s1_valid := false.B
652  }
653  // when sbuffer_out_s0_fire, read dcache req data and store them in a pipeline reg
654  when(sbuffer_out_s0_cango){
655    sbuffer_out_s1_valid := sbuffer_out_s0_valid
656  }
657  when(sbuffer_out_s0_fire){
658    stateVec(sbuffer_out_s0_evictionIdx).state_inflight := true.B
659    stateVec(sbuffer_out_s0_evictionIdx).w_timeout := false.B
660    // stateVec(sbuffer_out_s0_evictionIdx).s_pipe_req := true.B
661    XSDebug(p"$sbuffer_out_s0_evictionIdx will be sent to Dcache\n")
662  }
663
664  XSDebug(p"need drain:$need_drain cohHasTimeOut: $cohHasTimeOut need replace:$need_replace\n")
665  XSDebug(p"drainIdx:$drainIdx tIdx:$cohTimeOutIdx replIdx:$replaceIdx " +
666    p"blocked:${!noSameBlockInflight(sbuffer_out_s0_evictionIdx)} v:${activeMask(sbuffer_out_s0_evictionIdx)}\n")
667  XSDebug(p"sbuffer_out_s0_valid:$sbuffer_out_s0_valid evictIdx:$sbuffer_out_s0_evictionIdx dcache ready:${io.dcache.req.ready}\n")
668  // Note: if other dcache req in the same block are inflight,
669  // the lru update may not accurate
670  accessIdx(EnsbufferWidth).valid := invalidMask(replaceIdx) || (
671    need_replace && !need_drain && !cohHasTimeOut && !missqReplayHasTimeOut && sbuffer_out_s0_cango && activeMask(replaceIdx))
672  accessIdx(EnsbufferWidth).bits := replaceIdx
673  val sbuffer_out_s1_evictionIdx = RegEnable(sbuffer_out_s0_evictionIdx, sbuffer_out_s0_fire)
674  val sbuffer_out_s1_evictionPTag = RegEnable(ptag(sbuffer_out_s0_evictionIdx), sbuffer_out_s0_fire)
675  val sbuffer_out_s1_evictionVTag = RegEnable(vtag(sbuffer_out_s0_evictionIdx), sbuffer_out_s0_fire)
676
677  io.dcache.req.valid := sbuffer_out_s1_valid && !blockDcacheWrite
678  io.dcache.req.bits := DontCare
679  io.dcache.req.bits.cmd   := MemoryOpConstants.M_XWR
680  io.dcache.req.bits.addr  := getAddr(sbuffer_out_s1_evictionPTag)
681  io.dcache.req.bits.vaddr := getAddr(sbuffer_out_s1_evictionVTag)
682  io.dcache.req.bits.data  := data(sbuffer_out_s1_evictionIdx).asUInt
683  io.dcache.req.bits.mask  := mask(sbuffer_out_s1_evictionIdx).asUInt
684  io.dcache.req.bits.id := sbuffer_out_s1_evictionIdx
685
686  when (sbuffer_out_s1_fire) {
687    assert(!(io.dcache.req.bits.vaddr === 0.U))
688    assert(!(io.dcache.req.bits.addr === 0.U))
689  }
690
691  XSDebug(sbuffer_out_s1_fire,
692    p"send buf [$sbuffer_out_s1_evictionIdx] to Dcache, req fire\n"
693  )
694
695  // update sbuffer status according to dcache resp source
696
697  def id_to_sbuffer_id(id: UInt): UInt = {
698    require(id.getWidth >= log2Up(StoreBufferSize))
699    id(log2Up(StoreBufferSize)-1, 0)
700  }
701
702  // hit resp
703  io.dcache.hit_resps.map(resp => {
704    val dcache_resp_id = resp.bits.id
705    when (resp.fire) {
706      stateVec(dcache_resp_id).state_inflight := false.B
707      stateVec(dcache_resp_id).state_valid := false.B
708      assert(!resp.bits.replay)
709      assert(!resp.bits.miss) // not need to resp if miss, to be opted
710      assert(stateVec(dcache_resp_id).state_inflight === true.B)
711    }
712
713    // Update w_sameblock_inflight flag is delayed for 1 cycle
714    //
715    // When a new req allocate a new line in sbuffer, sameblock_inflight check will ignore
716    // current dcache.hit_resps. Then, in the next cycle, we have plenty of time to check
717    // if the same block is still inflight
718    (0 until StoreBufferSize).map(i => {
719      when(
720        stateVec(i).w_sameblock_inflight &&
721        stateVec(i).state_valid &&
722        GatedValidRegNext(resp.fire) &&
723        waitInflightMask(i) === UIntToOH(RegEnable(id_to_sbuffer_id(dcache_resp_id), resp.fire))
724      ){
725        stateVec(i).w_sameblock_inflight := false.B
726      }
727    })
728  })
729
730  io.dcache.hit_resps.zip(dataModule.io.maskFlushReq).map{case (resp, maskFlush) => {
731    maskFlush.valid := resp.fire
732    maskFlush.bits.wvec := UIntToOH(resp.bits.id)
733  }}
734
735  // replay resp
736  val replay_resp_id = io.dcache.replay_resp.bits.id
737  when (io.dcache.replay_resp.fire) {
738    missqReplayCount(replay_resp_id) := 0.U
739    stateVec(replay_resp_id).w_timeout := true.B
740    // waiting for timeout
741    assert(io.dcache.replay_resp.bits.replay)
742    assert(stateVec(replay_resp_id).state_inflight === true.B)
743  }
744
745  // TODO: reuse cohCount
746  (0 until StoreBufferSize).map(i => {
747    when(stateVec(i).w_timeout && stateVec(i).state_inflight && !missqReplayCount(i)(MissqReplayCountBits-1)) {
748      missqReplayCount(i) := missqReplayCount(i) + 1.U
749    }
750    when(activeMask(i) && !cohTimeOutMask(i)){
751      cohCount(i) := cohCount(i)+1.U
752    }
753  })
754
755  if (env.EnableDifftest) {
756    // hit resp
757    io.dcache.hit_resps.zipWithIndex.map{case (resp, index) => {
758      val difftest = DifftestModule(new DiffSbufferEvent, delay = 1)
759      val dcache_resp_id = resp.bits.id
760      difftest.coreid := io.hartId
761      difftest.index  := index.U
762      difftest.valid  := resp.fire
763      difftest.addr   := getAddr(ptag(dcache_resp_id))
764      difftest.data   := data(dcache_resp_id).asTypeOf(Vec(CacheLineBytes, UInt(8.W)))
765      difftest.mask   := mask(dcache_resp_id).asUInt
766    }}
767  }
768
769  // ---------------------- Load Data Forward ---------------------
770  val mismatch = Wire(Vec(LoadPipelineWidth, Bool()))
771  XSPerfAccumulate("vaddr_match_failed", mismatch(0) || mismatch(1))
772  for ((forward, i) <- io.forward.zipWithIndex) {
773    val vtag_matches = VecInit(widthMap(w => vtag(w) === getVTag(forward.vaddr)))
774    // ptag_matches uses paddr from dtlb, which is far from sbuffer
775    val ptag_matches = VecInit(widthMap(w => RegEnable(ptag(w), forward.valid) === RegEnable(getPTag(forward.paddr), forward.valid)))
776    val tag_matches = vtag_matches
777    val tag_mismatch = GatedValidRegNext(forward.valid) && VecInit(widthMap(w =>
778      GatedValidRegNext(vtag_matches(w)) =/= ptag_matches(w) && GatedValidRegNext((activeMask(w) || inflightMask(w)))
779    )).asUInt.orR
780    mismatch(i) := tag_mismatch
781    when (tag_mismatch) {
782      XSDebug("forward tag mismatch: pmatch %x vmatch %x vaddr %x paddr %x\n",
783        RegNext(ptag_matches.asUInt),
784        RegNext(vtag_matches.asUInt),
785        RegNext(forward.vaddr),
786        RegNext(forward.paddr)
787      )
788      forward_need_uarch_drain := true.B
789    }
790    val valid_tag_matches = widthMap(w => tag_matches(w) && activeMask(w))
791    val inflight_tag_matches = widthMap(w => tag_matches(w) && inflightMask(w))
792    val line_offset_mask = UIntToOH(getVWordOffset(forward.paddr))
793
794    val valid_tag_match_reg = valid_tag_matches.map(RegEnable(_, forward.valid))
795    val inflight_tag_match_reg = inflight_tag_matches.map(RegEnable(_, forward.valid))
796    val forward_mask_candidate_reg = RegEnable(
797      VecInit(mask.map(entry => entry(getVWordOffset(forward.paddr)))),
798      forward.valid
799    )
800    val forward_data_candidate_reg = RegEnable(
801      VecInit(data.map(entry => entry(getVWordOffset(forward.paddr)))),
802      forward.valid
803    )
804
805    val selectedValidMask = Mux1H(valid_tag_match_reg, forward_mask_candidate_reg)
806    val selectedValidData = Mux1H(valid_tag_match_reg, forward_data_candidate_reg)
807    selectedValidMask.suggestName("selectedValidMask_"+i)
808    selectedValidData.suggestName("selectedValidData_"+i)
809
810    val selectedInflightMask = Mux1H(inflight_tag_match_reg, forward_mask_candidate_reg)
811    val selectedInflightData = Mux1H(inflight_tag_match_reg, forward_data_candidate_reg)
812    selectedInflightMask.suggestName("selectedInflightMask_"+i)
813    selectedInflightData.suggestName("selectedInflightData_"+i)
814
815    // currently not being used
816    val selectedInflightMaskFast = Mux1H(line_offset_mask, Mux1H(inflight_tag_matches, mask).asTypeOf(Vec(CacheLineVWords, Vec(VDataBytes, Bool()))))
817    val selectedValidMaskFast = Mux1H(line_offset_mask, Mux1H(valid_tag_matches, mask).asTypeOf(Vec(CacheLineVWords, Vec(VDataBytes, Bool()))))
818
819    forward.dataInvalid := false.B // data in store line merge buffer is always ready
820    forward.matchInvalid := tag_mismatch // paddr / vaddr cam result does not match
821    for (j <- 0 until VDataBytes) {
822      forward.forwardMask(j) := false.B
823      forward.forwardData(j) := DontCare
824
825      // valid entries have higher priority than inflight entries
826      when(selectedInflightMask(j)) {
827        forward.forwardMask(j) := true.B
828        forward.forwardData(j) := selectedInflightData(j)
829      }
830      when(selectedValidMask(j)) {
831        forward.forwardMask(j) := true.B
832        forward.forwardData(j) := selectedValidData(j)
833      }
834
835      forward.forwardMaskFast(j) := selectedInflightMaskFast(j) || selectedValidMaskFast(j)
836    }
837    forward.addrInvalid := DontCare
838  }
839
840  for (i <- 0 until StoreBufferSize) {
841    XSDebug("sbf entry " + i + " : ptag %x vtag %x valid %x active %x inflight %x w_timeout %x\n",
842      ptag(i) << OffsetWidth,
843      vtag(i) << OffsetWidth,
844      stateVec(i).isValid(),
845      activeMask(i),
846      inflightMask(i),
847      stateVec(i).w_timeout
848    )
849  }
850
851  /*
852  *
853  **********************************************************
854  *      -------------                   -------------     *
855  *      | XiangShan |                   |    NEMU   |     *
856  *      -------------                   -------------     *
857  *            |                               |           *
858  *            V                               V           *
859  *          -----                           -----         *
860  *          | Q |                           | Q |         *
861  *          | U |                           | U |         *
862  *          | E |                           | E |         *
863  *          | U |                           | U |         *
864  *          | E |                           | E |         *
865  *          |   |                           |   |         *
866  *          -----                           -----         *
867  *            |                               |           *
868  *            |        --------------         |           *
869  *            |>>>>>>>>|  DIFFTEST  |<<<<<<<<<|           *
870  *                     --------------                     *
871  **********************************************************
872  */
873  // Initialize when unenabled difftest.
874  for (i <- 0 until EnsbufferWidth) {
875    io.vecDifftestInfo(i) := DontCare
876  }
877  if (env.EnableDifftest) {
878    val VecMemFLOWMaxNumber = 16
879
880    def UIntSlice(in: UInt, High: UInt, Low: UInt): UInt = {
881      val maxNum = in.getWidth
882      val result = Wire(Vec(maxNum, Bool()))
883
884      for (i <- 0 until maxNum) {
885        when (Low + i.U <= High) {
886          result(i) := in(Low + i.U)
887        }.otherwise{
888          result(i) := 0.U
889        }
890      }
891
892      result.asUInt
893    }
894
895    // To align with 'nemu', we need:
896    //  For 'unit-store' and 'whole' vector store instr, we re-split here,
897    //  and for the res, we do nothing.
898    for (i <- 0 until EnsbufferWidth) {
899      io.vecDifftestInfo(i).ready := io.in(i).ready
900
901      val uop             = io.vecDifftestInfo(i).bits
902
903      val isVse           = isVStore(uop.fuType) && LSUOpType.isUStride(uop.fuOpType)
904      val isVsm           = isVStore(uop.fuType) && VstuType.isMasked(uop.fuOpType)
905      val isVsr           = isVStore(uop.fuType) && VstuType.isWhole(uop.fuOpType)
906
907      val vpu             = uop.vpu
908      val veew            = uop.vpu.veew
909      val eew             = EewLog2(veew)
910      val EEB             = (1.U << eew).asUInt //Only when VLEN=128 effective element byte
911      val EEWBits         = (EEB << 3.U).asUInt
912      val nf              = Mux(isVsr, 0.U, vpu.nf)
913
914      val isSegment       = nf =/= 0.U && !isVsm
915      val isVSLine        = (isVse || isVsm || isVsr) && !isSegment
916
917      // The number of stores generated by a uop theroy.
918      // No other vector instructions need to be considered.
919      val flow            = Mux(
920                              isVSLine,
921                              (16.U >> eew).asUInt,
922                              0.U
923                            )
924
925      val rawData         = io.in(i).bits.data
926      val rawMask         = io.in(i).bits.mask
927      val rawAddr         = io.in(i).bits.addr
928
929      // A common difftest interface for scalar and vector instr
930      val difftestCommon = DifftestModule(new DiffStoreEvent, delay = 2)
931      when (isVSLine) {
932        val splitMask         = UIntSlice(rawMask, EEB - 1.U, 0.U)(7,0)  // Byte
933        val splitData         = UIntSlice(rawData, EEWBits - 1.U, 0.U)(63,0) // Double word
934        val storeCommit       = io.in(i).fire && splitMask.orR && io.in(i).bits.vecValid
935        val waddr             = rawAddr
936        val wmask             = splitMask
937        val wdata             = splitData & MaskExpand(splitMask)
938
939        difftestCommon.coreid := io.hartId
940        difftestCommon.index  := (i*VecMemFLOWMaxNumber).U
941        difftestCommon.valid  := storeCommit
942        difftestCommon.addr   := waddr
943        difftestCommon.data   := wdata
944        difftestCommon.mask   := wmask
945
946      }.otherwise{
947        val storeCommit       = io.in(i).fire
948        val waddr             = ZeroExt(Cat(io.in(i).bits.addr(PAddrBits - 1, 3), 0.U(3.W)), 64)
949        val sbufferMask       = shiftMaskToLow(io.in(i).bits.addr, io.in(i).bits.mask)
950        val sbufferData       = shiftDataToLow(io.in(i).bits.addr, io.in(i).bits.data)
951        val wmask             = sbufferMask
952        val wdata             = sbufferData & MaskExpand(sbufferMask)
953
954        difftestCommon.coreid := io.hartId
955        difftestCommon.index  := (i*VecMemFLOWMaxNumber).U
956        difftestCommon.valid  := storeCommit && io.in(i).bits.vecValid
957        difftestCommon.addr   := waddr
958        difftestCommon.data   := wdata
959        difftestCommon.mask   := wmask
960
961      }
962
963      // Only the interface used by the 'unit-store' and 'whole' vector store instr
964      for (index <- 1 until VecMemFLOWMaxNumber) {
965        val difftest = DifftestModule(new DiffStoreEvent, delay = 2)
966
967        // I've already done something process with 'mask' outside:
968        //  Different cases of 'vm' have been considered:
969        //    Any valid store will definitely not have all 0 masks,
970        //    and the extra part due to unaligned access must have a mask of 0
971        when (index.U < flow && isVSLine) {
972          // Make NEMU-difftest happy
973          val shiftIndex  = EEB*index.U
974          val shiftFlag   = shiftIndex(2,0).orR // Double word Flag
975          val shiftBytes  = Mux(shiftFlag, shiftIndex(2,0), 0.U)
976          val shiftBits   = shiftBytes << 3.U
977          val splitMask   = UIntSlice(rawMask, (EEB*(index+1).U - 1.U), EEB*index.U)(7,0)  // Byte
978          val splitData   = UIntSlice(rawData, (EEWBits*(index+1).U - 1.U), EEWBits*index.U)(63,0) // Double word
979          val storeCommit = io.in(i).fire && splitMask.orR  && io.in(i).bits.vecValid
980          val waddr       = Cat(rawAddr(PAddrBits - 1, 4), Cat(shiftIndex(3), 0.U(3.W)))
981          val wmask       = splitMask << shiftBytes
982          val wdata       = (splitData & MaskExpand(splitMask)) << shiftBits
983
984          difftest.coreid := io.hartId
985          difftest.index  := (i*VecMemFLOWMaxNumber+index).U
986          difftest.valid  := storeCommit
987          difftest.addr   := waddr
988          difftest.data   := wdata
989          difftest.mask   := wmask
990
991        }.otherwise{
992          difftest.coreid := 0.U
993          difftest.index  := 0.U
994          difftest.valid  := 0.U
995          difftest.addr   := 0.U
996          difftest.data   := 0.U
997          difftest.mask   := 0.U
998
999        }
1000      }
1001    }
1002  }
1003
1004  val perf_valid_entry_count = RegNext(PopCount(VecInit(stateVec.map(s => !s.isInvalid())).asUInt))
1005  XSPerfHistogram("util", perf_valid_entry_count, true.B, 0, StoreBufferSize, 1)
1006  XSPerfAccumulate("sbuffer_req_valid", PopCount(VecInit(io.in.map(_.valid)).asUInt))
1007  XSPerfAccumulate("sbuffer_req_fire", PopCount(VecInit(io.in.map(_.fire)).asUInt))
1008  XSPerfAccumulate("sbuffer_req_fire_vecinvalid", PopCount(VecInit(io.in.map(data => data.fire && !data.bits.vecValid)).asUInt))
1009  XSPerfAccumulate("sbuffer_merge", PopCount(VecInit(io.in.zipWithIndex.map({case (in, i) => in.fire && canMerge(i)})).asUInt))
1010  XSPerfAccumulate("sbuffer_newline", PopCount(VecInit(io.in.zipWithIndex.map({case (in, i) => in.fire && !canMerge(i)})).asUInt))
1011  XSPerfAccumulate("dcache_req_valid", io.dcache.req.valid)
1012  XSPerfAccumulate("dcache_req_fire", io.dcache.req.fire)
1013  XSPerfAccumulate("sbuffer_idle", sbuffer_state === x_idle)
1014  XSPerfAccumulate("sbuffer_flush", sbuffer_state === x_drain_sbuffer)
1015  XSPerfAccumulate("sbuffer_replace", sbuffer_state === x_replace)
1016  XSPerfAccumulate("evenCanInsert", evenCanInsert)
1017  XSPerfAccumulate("oddCanInsert", oddCanInsert)
1018  XSPerfAccumulate("mainpipe_resp_valid", io.dcache.main_pipe_hit_resp.fire)
1019  //XSPerfAccumulate("refill_resp_valid", io.dcache.refill_hit_resp.fire)
1020  XSPerfAccumulate("replay_resp_valid", io.dcache.replay_resp.fire)
1021  XSPerfAccumulate("coh_timeout", cohHasTimeOut)
1022
1023  // val (store_latency_sample, store_latency) = TransactionLatencyCounter(io.lsu.req.fire, io.lsu.resp.fire)
1024  // XSPerfHistogram("store_latency", store_latency, store_latency_sample, 0, 100, 10)
1025  // XSPerfAccumulate("store_req", io.lsu.req.fire)
1026
1027  val perfEvents = Seq(
1028    ("sbuffer_req_valid ", PopCount(VecInit(io.in.map(_.valid)).asUInt)                                                                ),
1029    ("sbuffer_req_fire  ", PopCount(VecInit(io.in.map(_.fire)).asUInt)                                                               ),
1030    ("sbuffer_merge     ", PopCount(VecInit(io.in.zipWithIndex.map({case (in, i) => in.fire && canMerge(i)})).asUInt)                ),
1031    ("sbuffer_newline   ", PopCount(VecInit(io.in.zipWithIndex.map({case (in, i) => in.fire && !canMerge(i)})).asUInt)               ),
1032    ("dcache_req_valid  ", io.dcache.req.valid                                                                                         ),
1033    ("dcache_req_fire   ", io.dcache.req.fire                                                                                        ),
1034    ("sbuffer_idle      ", sbuffer_state === x_idle                                                                                    ),
1035    ("sbuffer_flush     ", sbuffer_state === x_drain_sbuffer                                                                           ),
1036    ("sbuffer_replace   ", sbuffer_state === x_replace                                                                                 ),
1037    ("mpipe_resp_valid  ", io.dcache.main_pipe_hit_resp.fire                                                                         ),
1038    //("refill_resp_valid ", io.dcache.refill_hit_resp.fire                                                                            ),
1039    ("replay_resp_valid ", io.dcache.replay_resp.fire                                                                                ),
1040    ("coh_timeout       ", cohHasTimeOut                                                                                               ),
1041    ("sbuffer_1_4_valid ", (perf_valid_entry_count < (StoreBufferSize.U/4.U))                                                          ),
1042    ("sbuffer_2_4_valid ", (perf_valid_entry_count > (StoreBufferSize.U/4.U)) & (perf_valid_entry_count <= (StoreBufferSize.U/2.U))    ),
1043    ("sbuffer_3_4_valid ", (perf_valid_entry_count > (StoreBufferSize.U/2.U)) & (perf_valid_entry_count <= (StoreBufferSize.U*3.U/4.U))),
1044    ("sbuffer_full_valid", (perf_valid_entry_count > (StoreBufferSize.U*3.U/4.U)))
1045  )
1046  generatePerfEvent()
1047
1048}
1049