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