xref: /XiangShan/src/main/scala/xiangshan/mem/sbuffer/Sbuffer.scala (revision 45a77344216eaac365db01a604b06a401484aab2)
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 chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import xiangshan._
23import utils._
24import utility._
25import xiangshan.cache._
26import difftest._
27import freechips.rocketchip.util._
28
29class SbufferFlushBundle extends Bundle {
30  val valid = Output(Bool())
31  val empty = Input(Bool())
32}
33
34trait HasSbufferConst extends HasXSParameter {
35  val EvictCycles = 1 << 20
36  val SbufferReplayDelayCycles = 16
37  require(isPow2(EvictCycles))
38  val EvictCountBits = log2Up(EvictCycles+1)
39  val MissqReplayCountBits = log2Up(SbufferReplayDelayCycles) + 1
40
41  // dcache write hit resp has 2 sources
42  // refill pipe resp and main pipe resp
43  val NumDcacheWriteResp = 2 // hardcoded
44
45  val SbufferIndexWidth: Int = log2Up(StoreBufferSize)
46  // paddr = ptag + offset
47  val CacheLineBytes: Int = CacheLineSize / 8
48  val CacheLineWords: Int = CacheLineBytes / DataBytes
49  val OffsetWidth: Int = log2Up(CacheLineBytes)
50  val WordsWidth: Int = log2Up(CacheLineWords)
51  val PTagWidth: Int = PAddrBits - OffsetWidth
52  val VTagWidth: Int = VAddrBits - OffsetWidth
53  val WordOffsetWidth: Int = PAddrBits - WordsWidth
54}
55
56class SbufferEntryState (implicit p: Parameters) extends SbufferBundle {
57  val state_valid    = Bool() // this entry is active
58  val state_inflight = Bool() // sbuffer is trying to write this entry to dcache
59  val w_timeout = Bool() // with timeout resp, waiting for resend store pipeline req timeout
60  val w_sameblock_inflight = Bool() // same cache block dcache req is inflight
61
62  def isInvalid(): Bool = !state_valid
63  def isValid(): Bool = state_valid
64  def isActive(): Bool = state_valid && !state_inflight
65  def isInflight(): Bool = state_inflight
66  def isDcacheReqCandidate(): Bool = state_valid && !state_inflight && !w_sameblock_inflight
67}
68
69class SbufferBundle(implicit p: Parameters) extends XSBundle with HasSbufferConst
70
71class DataWriteReq(implicit p: Parameters) extends SbufferBundle {
72  // univerisal writemask
73  val wvec = UInt(StoreBufferSize.W)
74  // 2 cycle update
75  val mask = UInt((DataBits/8).W)
76  val data = UInt(DataBits.W)
77  val wordOffset = UInt(WordOffsetWidth.W)
78  val wline = Bool() // write full cacheline
79}
80
81class MaskFlushReq(implicit p: Parameters) extends SbufferBundle {
82  // univerisal writemask
83  val wvec = UInt(StoreBufferSize.W)
84}
85
86class SbufferData(implicit p: Parameters) extends XSModule with HasSbufferConst {
87  val io = IO(new Bundle(){
88    // update data and mask when alloc or merge
89    val writeReq = Vec(EnsbufferWidth, Flipped(ValidIO(new DataWriteReq)))
90    // clean mask when deq
91    val maskFlushReq = Vec(NumDcacheWriteResp, Flipped(ValidIO(new MaskFlushReq)))
92    val dataOut = Output(Vec(StoreBufferSize, Vec(CacheLineWords, Vec(DataBytes, UInt(8.W)))))
93    val maskOut = Output(Vec(StoreBufferSize, Vec(CacheLineWords, Vec(DataBytes, Bool()))))
94  })
95
96  val data = Reg(Vec(StoreBufferSize, Vec(CacheLineWords, Vec(DataBytes, UInt(8.W)))))
97  // val mask = Reg(Vec(StoreBufferSize, Vec(CacheLineWords, Vec(DataBytes, Bool()))))
98  val mask = RegInit(
99    VecInit(Seq.fill(StoreBufferSize)(
100      VecInit(Seq.fill(CacheLineWords)(
101        VecInit(Seq.fill(DataBytes)(false.B))
102      ))
103    ))
104  )
105
106  // 2 cycle line mask clean
107  for(line <- 0 until StoreBufferSize){
108    val line_mask_clean_flag = RegNext(
109      io.maskFlushReq.map(a => a.valid && a.bits.wvec(line)).reduce(_ || _)
110    )
111    line_mask_clean_flag.suggestName("line_mask_clean_flag_"+line)
112    when(line_mask_clean_flag){
113      for(word <- 0 until CacheLineWords){
114        for(byte <- 0 until DataBytes){
115          mask(line)(word)(byte) := false.B
116        }
117      }
118    }
119  }
120
121  // 2 cycle data / mask update
122  for(i <- 0 until EnsbufferWidth) {
123    val req = io.writeReq(i)
124    for(line <- 0 until StoreBufferSize){
125      val sbuffer_in_s1_line_wen = req.valid && req.bits.wvec(line)
126      val sbuffer_in_s2_line_wen = RegNext(sbuffer_in_s1_line_wen)
127      val line_write_buffer_data = RegEnable(req.bits.data, sbuffer_in_s1_line_wen)
128      val line_write_buffer_wline = RegEnable(req.bits.wline, sbuffer_in_s1_line_wen)
129      val line_write_buffer_mask = RegEnable(req.bits.mask, sbuffer_in_s1_line_wen)
130      val line_write_buffer_offset = RegEnable(req.bits.wordOffset(WordsWidth-1, 0), sbuffer_in_s1_line_wen)
131      sbuffer_in_s1_line_wen.suggestName("sbuffer_in_s1_line_wen_"+line)
132      sbuffer_in_s2_line_wen.suggestName("sbuffer_in_s2_line_wen_"+line)
133      line_write_buffer_data.suggestName("line_write_buffer_data_"+line)
134      line_write_buffer_wline.suggestName("line_write_buffer_wline_"+line)
135      line_write_buffer_mask.suggestName("line_write_buffer_mask_"+line)
136      line_write_buffer_offset.suggestName("line_write_buffer_offset_"+line)
137      for(word <- 0 until CacheLineWords){
138        for(byte <- 0 until DataBytes){
139          val write_byte = sbuffer_in_s2_line_wen && (
140            line_write_buffer_mask(byte) && (line_write_buffer_offset === word.U) ||
141            line_write_buffer_wline
142          )
143          when(write_byte){
144            data(line)(word)(byte) := line_write_buffer_data(byte*8+7, byte*8)
145            mask(line)(word)(byte) := true.B
146          }
147        }
148      }
149    }
150  }
151
152  // 1 cycle line mask clean
153  // for(i <- 0 until EnsbufferWidth) {
154  //   val req = io.writeReq(i)
155  //   when(req.valid){
156  //     for(line <- 0 until StoreBufferSize){
157  //       when(
158  //         req.bits.wvec(line) &&
159  //         req.bits.cleanMask
160  //       ){
161  //         for(word <- 0 until CacheLineWords){
162  //           for(byte <- 0 until DataBytes){
163  //             mask(line)(word)(byte) := false.B
164  //             val debug_last_cycle_write_byte = RegNext(req.valid && req.bits.wvec(line) && (
165  //               req.bits.mask(byte) && (req.bits.wordOffset(WordsWidth-1, 0) === word.U) ||
166  //               req.bits.wline
167  //             ))
168  //             assert(!debug_last_cycle_write_byte)
169  //           }
170  //         }
171  //       }
172  //     }
173  //   }
174  // }
175
176  io.dataOut := data
177  io.maskOut := mask
178}
179
180class Sbuffer(implicit p: Parameters) extends DCacheModule with HasSbufferConst with HasPerfEvents {
181  val io = IO(new Bundle() {
182    val hartId = Input(UInt(8.W))
183    val in = Vec(EnsbufferWidth, Flipped(Decoupled(new DCacheWordReqWithVaddr)))  //Todo: store logic only support Width == 2 now
184    val dcache = Flipped(new DCacheToSbufferIO)
185    val forward = Vec(LoadPipelineWidth, Flipped(new LoadForwardQueryIO))
186    val sqempty = Input(Bool())
187    val flush = Flipped(new SbufferFlushBundle)
188    val csrCtrl = Flipped(new CustomCSRCtrlIO)
189  })
190
191  val dataModule = Module(new SbufferData)
192  dataModule.io.writeReq <> DontCare
193  val writeReq = dataModule.io.writeReq
194
195  val ptag = Reg(Vec(StoreBufferSize, UInt(PTagWidth.W)))
196  val vtag = Reg(Vec(StoreBufferSize, UInt(VTagWidth.W)))
197  val debug_mask = Reg(Vec(StoreBufferSize, Vec(CacheLineWords, Vec(DataBytes, Bool()))))
198  val waitInflightMask = Reg(Vec(StoreBufferSize, UInt(StoreBufferSize.W)))
199  val data = dataModule.io.dataOut
200  val mask = dataModule.io.maskOut
201  val stateVec = RegInit(VecInit(Seq.fill(StoreBufferSize)(0.U.asTypeOf(new SbufferEntryState))))
202  val cohCount = RegInit(VecInit(Seq.fill(StoreBufferSize)(0.U(EvictCountBits.W))))
203  val missqReplayCount = RegInit(VecInit(Seq.fill(StoreBufferSize)(0.U(MissqReplayCountBits.W))))
204
205  val sbuffer_out_s0_fire = Wire(Bool())
206
207  /*
208       idle --[flush]   --> drain   --[buf empty]--> idle
209            --[buf full]--> replace --[dcache resp]--> idle
210  */
211  // x_drain_all: drain store queue and sbuffer
212  // x_drain_sbuffer: drain sbuffer only, block store queue to sbuffer write
213  val x_idle :: x_replace :: x_drain_all :: x_drain_sbuffer :: Nil = Enum(4)
214  def needDrain(state: UInt): Bool =
215    state(1)
216  val sbuffer_state = RegInit(x_idle)
217
218  // ---------------------- Store Enq Sbuffer ---------------------
219
220  def getPTag(pa: UInt): UInt =
221    pa(PAddrBits - 1, PAddrBits - PTagWidth)
222
223  def getVTag(va: UInt): UInt =
224    va(VAddrBits - 1, VAddrBits - VTagWidth)
225
226  def getWord(pa: UInt): UInt =
227    pa(PAddrBits-1, 3)
228
229  def getWordOffset(pa: UInt): UInt =
230    pa(OffsetWidth-1, 3)
231
232  def getAddr(ptag: UInt): UInt =
233    Cat(ptag, 0.U((PAddrBits - PTagWidth).W))
234
235  def getByteOffset(offect: UInt): UInt =
236    Cat(offect(OffsetWidth - 1, 3), 0.U(3.W))
237
238  def isOneOf(key: UInt, seq: Seq[UInt]): Bool =
239    if(seq.isEmpty) false.B else Cat(seq.map(_===key)).orR()
240
241  def widthMap[T <: Data](f: Int => T) = (0 until StoreBufferSize) map f
242
243  // sbuffer entry count
244
245  val plru = new PseudoLRU(StoreBufferSize)
246  val accessIdx = Wire(Vec(EnsbufferWidth + 1, Valid(UInt(SbufferIndexWidth.W))))
247
248  val candidateVec = VecInit(stateVec.map(s => s.isDcacheReqCandidate()))
249  val candidateIdx = PriorityEncoder(candidateVec)
250
251  val replaceAlgoIdx = plru.way
252  val replaceAlgoNotDcacheCandidate = !stateVec(replaceAlgoIdx).isDcacheReqCandidate()
253
254  val replaceIdx = Mux(replaceAlgoNotDcacheCandidate, candidateIdx, replaceAlgoIdx)
255  plru.access(accessIdx)
256
257  //-------------------------cohCount-----------------------------
258  // insert and merge: cohCount=0
259  // every cycle cohCount+=1
260  // if cohCount(EvictCountBits-1)==1, evict
261  val cohTimeOutMask = VecInit(widthMap(i => cohCount(i)(EvictCountBits - 1) && stateVec(i).isActive()))
262  val (cohTimeOutIdx, cohHasTimeOut) = PriorityEncoderWithFlag(cohTimeOutMask)
263  val cohTimeOutOH = PriorityEncoderOH(cohTimeOutMask)
264  val missqReplayTimeOutMask = VecInit(widthMap(i => missqReplayCount(i)(MissqReplayCountBits - 1) && stateVec(i).w_timeout))
265  val (missqReplayTimeOutIdxGen, missqReplayHasTimeOutGen) = PriorityEncoderWithFlag(missqReplayTimeOutMask)
266  val missqReplayHasTimeOut = RegNext(missqReplayHasTimeOutGen) && !RegNext(sbuffer_out_s0_fire)
267  val missqReplayTimeOutIdx = RegEnable(missqReplayTimeOutIdxGen, missqReplayHasTimeOutGen)
268
269  //-------------------------sbuffer enqueue-----------------------------
270
271  // Now sbuffer enq logic is divided into 3 stages:
272
273  // sbuffer_in_s0:
274  // * read data and meta from store queue
275  // * store them in 2 entry fifo queue
276
277  // sbuffer_in_s1:
278  // * read data and meta from fifo queue
279  // * update sbuffer meta (vtag, ptag, flag)
280  // * prevert that line from being sent to dcache (add a block condition)
281  // * prepare cacheline level write enable signal, RegNext() data and mask
282
283  // sbuffer_in_s2:
284  // * use cacheline level buffer to update sbuffer data and mask
285  // * remove dcache write block (if there is)
286
287  val activeMask = VecInit(stateVec.map(s => s.isActive()))
288  val validMask  = VecInit(stateVec.map(s => s.isValid()))
289  val drainIdx = PriorityEncoder(activeMask)
290
291  val inflightMask = VecInit(stateVec.map(s => s.isInflight()))
292
293  val inptags = io.in.map(in => getPTag(in.bits.addr))
294  val invtags = io.in.map(in => getVTag(in.bits.vaddr))
295  val sameTag = inptags(0) === inptags(1)
296  val firstWord = getWord(io.in(0).bits.addr)
297  val secondWord = getWord(io.in(1).bits.addr)
298
299  // merge condition
300  val mergeMask = Wire(Vec(EnsbufferWidth, Vec(StoreBufferSize, Bool())))
301  val mergeIdx = mergeMask.map(PriorityEncoder(_)) // avoid using mergeIdx for better timing
302  val canMerge = mergeMask.map(ParallelOR(_))
303  val mergeVec = mergeMask.map(_.asUInt)
304
305  for(i <- 0 until EnsbufferWidth){
306    mergeMask(i) := widthMap(j =>
307      inptags(i) === ptag(j) && activeMask(j)
308    )
309    assert(!(PopCount(mergeMask(i).asUInt) > 1.U && io.in(i).fire()))
310  }
311
312  // insert condition
313  // firstInsert: the first invalid entry
314  // if first entry canMerge or second entry has the same ptag with the first entry,
315  // secondInsert equal the first invalid entry, otherwise, the second invalid entry
316  val invalidMask = VecInit(stateVec.map(s => s.isInvalid()))
317  val evenInvalidMask = GetEvenBits(invalidMask.asUInt)
318  val oddInvalidMask = GetOddBits(invalidMask.asUInt)
319
320  def getFirstOneOH(input: UInt): UInt = {
321    assert(input.getWidth > 1)
322    val output = WireInit(VecInit(input.asBools))
323    (1 until input.getWidth).map(i => {
324      output(i) := !input(i - 1, 0).orR && input(i)
325    })
326    output.asUInt
327  }
328
329  val evenRawInsertVec = getFirstOneOH(evenInvalidMask)
330  val oddRawInsertVec = getFirstOneOH(oddInvalidMask)
331  val (evenRawInsertIdx, evenCanInsert) = PriorityEncoderWithFlag(evenInvalidMask)
332  val (oddRawInsertIdx, oddCanInsert) = PriorityEncoderWithFlag(oddInvalidMask)
333  val evenInsertIdx = Cat(evenRawInsertIdx, 0.U(1.W)) // slow to generate, for debug only
334  val oddInsertIdx = Cat(oddRawInsertIdx, 1.U(1.W)) // slow to generate, for debug only
335  val evenInsertVec = GetEvenBits.reverse(evenRawInsertVec)
336  val oddInsertVec = GetOddBits.reverse(oddRawInsertVec)
337
338  val enbufferSelReg = RegInit(false.B)
339  when(io.in(0).valid) {
340    enbufferSelReg := ~enbufferSelReg
341  }
342
343  val firstInsertIdx = Mux(enbufferSelReg, evenInsertIdx, oddInsertIdx) // slow to generate, for debug only
344  val secondInsertIdx = Mux(sameTag,
345    firstInsertIdx,
346    Mux(~enbufferSelReg, evenInsertIdx, oddInsertIdx)
347  ) // slow to generate, for debug only
348  val firstInsertVec = Mux(enbufferSelReg, evenInsertVec, oddInsertVec)
349  val secondInsertVec = Mux(sameTag,
350    firstInsertVec,
351    Mux(~enbufferSelReg, evenInsertVec, oddInsertVec)
352  ) // slow to generate, for debug only
353  val firstCanInsert = sbuffer_state =/= x_drain_sbuffer && Mux(enbufferSelReg, evenCanInsert, oddCanInsert)
354  val secondCanInsert = sbuffer_state =/= x_drain_sbuffer && Mux(sameTag,
355    firstCanInsert,
356    Mux(~enbufferSelReg, evenCanInsert, oddCanInsert)
357  ) && (EnsbufferWidth >= 1).B
358  val forward_need_uarch_drain = WireInit(false.B)
359  val merge_need_uarch_drain = WireInit(false.B)
360  val do_uarch_drain = RegNext(forward_need_uarch_drain) || RegNext(RegNext(merge_need_uarch_drain))
361  XSPerfAccumulate("do_uarch_drain", do_uarch_drain)
362
363  io.in(0).ready := firstCanInsert
364  io.in(1).ready := secondCanInsert && io.in(0).ready
365
366  def wordReqToBufLine( // allocate a new line in sbuffer
367    req: DCacheWordReq,
368    reqptag: UInt,
369    reqvtag: UInt,
370    insertIdx: UInt,
371    insertVec: UInt,
372    wordOffset: UInt
373  ): Unit = {
374    assert(UIntToOH(insertIdx) === insertVec)
375    val sameBlockInflightMask = genSameBlockInflightMask(reqptag)
376    (0 until StoreBufferSize).map(entryIdx => {
377      when(insertVec(entryIdx)){
378        stateVec(entryIdx).state_valid := true.B
379        stateVec(entryIdx).w_sameblock_inflight := sameBlockInflightMask.orR // set w_sameblock_inflight when a line is first allocated
380        when(sameBlockInflightMask.orR){
381          waitInflightMask(entryIdx) := sameBlockInflightMask
382        }
383        cohCount(entryIdx) := 0.U
384        // missqReplayCount(insertIdx) := 0.U
385        ptag(entryIdx) := reqptag
386        vtag(entryIdx) := reqvtag // update vtag iff a new sbuffer line is allocated
387      }
388    })
389  }
390
391  def mergeWordReq( // merge write req into an existing line
392    req: DCacheWordReq,
393    reqptag: UInt,
394    reqvtag: UInt,
395    mergeIdx: UInt,
396    mergeVec: UInt,
397    wordOffset: UInt
398  ): Unit = {
399    assert(UIntToOH(mergeIdx) === mergeVec)
400    (0 until StoreBufferSize).map(entryIdx => {
401      when(mergeVec(entryIdx)) {
402        cohCount(entryIdx) := 0.U
403        // missqReplayCount(entryIdx) := 0.U
404        // check if vtag is the same, if not, trigger sbuffer flush
405        when(reqvtag =/= vtag(entryIdx)) {
406          XSDebug("reqvtag =/= sbufvtag req(vtag %x ptag %x) sbuffer(vtag %x ptag %x)\n",
407            reqvtag << OffsetWidth,
408            reqptag << OffsetWidth,
409            vtag(entryIdx) << OffsetWidth,
410            ptag(entryIdx) << OffsetWidth
411          )
412          merge_need_uarch_drain := true.B
413        }
414      }
415    })
416  }
417
418  for(((in, wordOffset), i) <- io.in.zip(Seq(firstWord, secondWord)).zipWithIndex){
419    writeReq(i).valid := in.fire()
420    writeReq(i).bits.wordOffset := wordOffset
421    writeReq(i).bits.mask := in.bits.mask
422    writeReq(i).bits.data := in.bits.data
423    writeReq(i).bits.wline := in.bits.wline
424    val debug_insertIdx = if(i == 0) firstInsertIdx else secondInsertIdx
425    val insertVec = if(i == 0) firstInsertVec else secondInsertVec
426    assert(!((PopCount(insertVec) > 1.U) && in.fire()))
427    val insertIdx = OHToUInt(insertVec)
428    accessIdx(i).valid := RegNext(in.fire())
429    accessIdx(i).bits := RegNext(Mux(canMerge(i), mergeIdx(i), insertIdx))
430    when(in.fire()){
431      when(canMerge(i)){
432        writeReq(i).bits.wvec := mergeVec(i)
433        mergeWordReq(in.bits, inptags(i), invtags(i), mergeIdx(i), mergeVec(i), wordOffset)
434        XSDebug(p"merge req $i to line [${mergeIdx(i)}]\n")
435      }.otherwise({
436        writeReq(i).bits.wvec := insertVec
437        wordReqToBufLine(in.bits, inptags(i), invtags(i), insertIdx, insertVec, wordOffset)
438        XSDebug(p"insert req $i to line[$insertIdx]\n")
439        assert(debug_insertIdx === insertIdx)
440      })
441    }
442  }
443
444
445  for(i <- 0 until StoreBufferSize){
446    XSDebug(stateVec(i).isValid(),
447      p"[$i] timeout:${cohCount(i)(EvictCountBits-1)} state:${stateVec(i)}\n"
448    )
449  }
450
451  for((req, i) <- io.in.zipWithIndex){
452    XSDebug(req.fire(),
453      p"accept req [$i]: " +
454        p"addr:${Hexadecimal(req.bits.addr)} " +
455        p"mask:${Binary(req.bits.mask)} " +
456        p"data:${Hexadecimal(req.bits.data)}\n"
457    )
458    XSDebug(req.valid && !req.ready,
459      p"req [$i] blocked by sbuffer\n"
460    )
461  }
462
463  // ---------------------- Send Dcache Req ---------------------
464
465  val sbuffer_empty = Cat(invalidMask).andR()
466  val sq_empty = !Cat(io.in.map(_.valid)).orR()
467  val empty = sbuffer_empty && sq_empty
468  val threshold = RegNext(io.csrCtrl.sbuffer_threshold +& 1.U)
469  val ActiveCount = PopCount(activeMask)
470  val ValidCount = PopCount(validMask)
471  val do_eviction = RegNext(ActiveCount >= threshold || ActiveCount === (StoreBufferSize-1).U || ValidCount === (StoreBufferSize).U, init = false.B)
472  require((StoreBufferThreshold + 1) <= StoreBufferSize)
473
474  XSDebug(p"ActiveCount[$ActiveCount]\n")
475
476  io.flush.empty := RegNext(empty && io.sqempty)
477  // lru.io.flush := sbuffer_state === x_drain_all && empty
478  switch(sbuffer_state){
479    is(x_idle){
480      when(io.flush.valid){
481        sbuffer_state := x_drain_all
482      }.elsewhen(do_uarch_drain){
483        sbuffer_state := x_drain_sbuffer
484      }.elsewhen(do_eviction){
485        sbuffer_state := x_replace
486      }
487    }
488    is(x_drain_all){
489      when(empty){
490        sbuffer_state := x_idle
491      }
492    }
493    is(x_drain_sbuffer){
494      when(io.flush.valid){
495        sbuffer_state := x_drain_all
496      }.elsewhen(sbuffer_empty){
497        sbuffer_state := x_idle
498      }
499    }
500    is(x_replace){
501      when(io.flush.valid){
502        sbuffer_state := x_drain_all
503      }.elsewhen(do_uarch_drain){
504        sbuffer_state := x_drain_sbuffer
505      }.elsewhen(!do_eviction){
506        sbuffer_state := x_idle
507      }
508    }
509  }
510  XSDebug(p"sbuffer state:${sbuffer_state} do eviction:${do_eviction} empty:${empty}\n")
511
512  def noSameBlockInflight(idx: UInt): Bool = {
513    // stateVec(idx) itself must not be s_inflight
514    !Cat(widthMap(i => inflightMask(i) && ptag(idx) === ptag(i))).orR()
515  }
516
517  def genSameBlockInflightMask(ptag_in: UInt): UInt = {
518    val mask = VecInit(widthMap(i => inflightMask(i) && ptag_in === ptag(i))).asUInt // quite slow, use it with care
519    assert(!(PopCount(mask) > 1.U))
520    mask
521  }
522
523  def haveSameBlockInflight(ptag_in: UInt): Bool = {
524    genSameBlockInflightMask(ptag_in).orR
525  }
526
527  // ---------------------------------------------------------------------------
528  // sbuffer to dcache pipeline
529  // ---------------------------------------------------------------------------
530
531  // Now sbuffer deq logic is divided into 2 stages:
532
533  // sbuffer_out_s0:
534  // * read data and meta from sbuffer
535  // * RegNext() them
536  // * set line state to inflight
537
538  // sbuffer_out_s1:
539  // * send write req to dcache
540
541  // sbuffer_out_extra:
542  // * receive write result from dcache
543  // * update line state
544
545  val sbuffer_out_s1_ready = Wire(Bool())
546
547  // ---------------------------------------------------------------------------
548  // sbuffer_out_s0
549  // ---------------------------------------------------------------------------
550
551  val need_drain = needDrain(sbuffer_state)
552  val need_replace = do_eviction || (sbuffer_state === x_replace)
553  val sbuffer_out_s0_evictionIdx = Mux(missqReplayHasTimeOut,
554    missqReplayTimeOutIdx,
555    Mux(need_drain,
556      drainIdx,
557      Mux(cohHasTimeOut, cohTimeOutIdx, replaceIdx)
558    )
559  )
560
561  // If there is a inflight dcache req which has same ptag with sbuffer_out_s0_evictionIdx's ptag,
562  // current eviction should be blocked.
563  val sbuffer_out_s0_valid = missqReplayHasTimeOut ||
564    stateVec(sbuffer_out_s0_evictionIdx).isDcacheReqCandidate() &&
565    (need_drain || cohHasTimeOut || need_replace)
566  assert(!(
567    stateVec(sbuffer_out_s0_evictionIdx).isDcacheReqCandidate &&
568    !noSameBlockInflight(sbuffer_out_s0_evictionIdx)
569  ))
570  val sbuffer_out_s0_cango = sbuffer_out_s1_ready
571  sbuffer_out_s0_fire := sbuffer_out_s0_valid && sbuffer_out_s0_cango
572
573  // ---------------------------------------------------------------------------
574  // sbuffer_out_s1
575  // ---------------------------------------------------------------------------
576
577  // TODO: use EnsbufferWidth
578  val shouldWaitWriteFinish = RegNext(VecInit((0 until EnsbufferWidth).map{i =>
579    (writeReq(i).bits.wvec.asUInt & UIntToOH(sbuffer_out_s0_evictionIdx).asUInt).orR &&
580    writeReq(i).valid
581  }).asUInt.orR)
582  // block dcache write if read / write hazard
583  val blockDcacheWrite = shouldWaitWriteFinish
584
585  val sbuffer_out_s1_valid = RegInit(false.B)
586  sbuffer_out_s1_ready := io.dcache.req.ready && !blockDcacheWrite || !sbuffer_out_s1_valid
587  val sbuffer_out_s1_fire = io.dcache.req.fire()
588
589  // when sbuffer_out_s1_fire, send dcache req stored in pipeline reg to dcache
590  when(sbuffer_out_s1_fire){
591    sbuffer_out_s1_valid := false.B
592  }
593  // when sbuffer_out_s0_fire, read dcache req data and store them in a pipeline reg
594  when(sbuffer_out_s0_cango){
595    sbuffer_out_s1_valid := sbuffer_out_s0_valid
596  }
597  when(sbuffer_out_s0_fire){
598    stateVec(sbuffer_out_s0_evictionIdx).state_inflight := true.B
599    stateVec(sbuffer_out_s0_evictionIdx).w_timeout := false.B
600    // stateVec(sbuffer_out_s0_evictionIdx).s_pipe_req := true.B
601    XSDebug(p"$sbuffer_out_s0_evictionIdx will be sent to Dcache\n")
602  }
603
604  XSDebug(p"need drain:$need_drain cohHasTimeOut: $cohHasTimeOut need replace:$need_replace\n")
605  XSDebug(p"drainIdx:$drainIdx tIdx:$cohTimeOutIdx replIdx:$replaceIdx " +
606    p"blocked:${!noSameBlockInflight(sbuffer_out_s0_evictionIdx)} v:${activeMask(sbuffer_out_s0_evictionIdx)}\n")
607  XSDebug(p"sbuffer_out_s0_valid:$sbuffer_out_s0_valid evictIdx:$sbuffer_out_s0_evictionIdx dcache ready:${io.dcache.req.ready}\n")
608  // Note: if other dcache req in the same block are inflight,
609  // the lru update may not accurate
610  accessIdx(EnsbufferWidth).valid := invalidMask(replaceIdx) || (
611    need_replace && !need_drain && !cohHasTimeOut && !missqReplayHasTimeOut && sbuffer_out_s0_cango && activeMask(replaceIdx))
612  accessIdx(EnsbufferWidth).bits := replaceIdx
613  val sbuffer_out_s1_evictionIdx = RegEnable(sbuffer_out_s0_evictionIdx, enable = sbuffer_out_s0_fire)
614  val sbuffer_out_s1_evictionPTag = RegEnable(ptag(sbuffer_out_s0_evictionIdx), enable = sbuffer_out_s0_fire)
615  val sbuffer_out_s1_evictionVTag = RegEnable(vtag(sbuffer_out_s0_evictionIdx), enable = sbuffer_out_s0_fire)
616
617  io.dcache.req.valid := sbuffer_out_s1_valid && !blockDcacheWrite
618  io.dcache.req.bits := DontCare
619  io.dcache.req.bits.cmd   := MemoryOpConstants.M_XWR
620  io.dcache.req.bits.addr  := getAddr(sbuffer_out_s1_evictionPTag)
621  io.dcache.req.bits.vaddr := getAddr(sbuffer_out_s1_evictionVTag)
622  io.dcache.req.bits.data  := data(sbuffer_out_s1_evictionIdx).asUInt
623  io.dcache.req.bits.mask  := mask(sbuffer_out_s1_evictionIdx).asUInt
624  io.dcache.req.bits.id := sbuffer_out_s1_evictionIdx
625
626  when (sbuffer_out_s1_fire) {
627    assert(!(io.dcache.req.bits.vaddr === 0.U))
628    assert(!(io.dcache.req.bits.addr === 0.U))
629  }
630
631  XSDebug(sbuffer_out_s1_fire,
632    p"send buf [$sbuffer_out_s1_evictionIdx] to Dcache, req fire\n"
633  )
634
635  // update sbuffer status according to dcache resp source
636
637  def id_to_sbuffer_id(id: UInt): UInt = {
638    require(id.getWidth >= log2Up(StoreBufferSize))
639    id(log2Up(StoreBufferSize)-1, 0)
640  }
641
642  // hit resp
643  io.dcache.hit_resps.map(resp => {
644    val dcache_resp_id = resp.bits.id
645    when (resp.fire()) {
646      stateVec(dcache_resp_id).state_inflight := false.B
647      stateVec(dcache_resp_id).state_valid := false.B
648      assert(!resp.bits.replay)
649      assert(!resp.bits.miss) // not need to resp if miss, to be opted
650      assert(stateVec(dcache_resp_id).state_inflight === true.B)
651    }
652
653    // Update w_sameblock_inflight flag is delayed for 1 cycle
654    //
655    // When a new req allocate a new line in sbuffer, sameblock_inflight check will ignore
656    // current dcache.hit_resps. Then, in the next cycle, we have plenty of time to check
657    // if the same block is still inflight
658    (0 until StoreBufferSize).map(i => {
659      when(
660        stateVec(i).w_sameblock_inflight &&
661        stateVec(i).state_valid &&
662        RegNext(resp.fire()) &&
663        waitInflightMask(i) === UIntToOH(RegNext(id_to_sbuffer_id(dcache_resp_id)))
664      ){
665        stateVec(i).w_sameblock_inflight := false.B
666      }
667    })
668  })
669
670  io.dcache.hit_resps.zip(dataModule.io.maskFlushReq).map{case (resp, maskFlush) => {
671    maskFlush.valid := resp.fire()
672    maskFlush.bits.wvec := UIntToOH(resp.bits.id)
673  }}
674
675  // replay resp
676  val replay_resp_id = io.dcache.replay_resp.bits.id
677  when (io.dcache.replay_resp.fire()) {
678    missqReplayCount(replay_resp_id) := 0.U
679    stateVec(replay_resp_id).w_timeout := true.B
680    // waiting for timeout
681    assert(io.dcache.replay_resp.bits.replay)
682    assert(stateVec(replay_resp_id).state_inflight === true.B)
683  }
684
685  // TODO: reuse cohCount
686  (0 until StoreBufferSize).map(i => {
687    when(stateVec(i).w_timeout && stateVec(i).state_inflight && !missqReplayCount(i)(MissqReplayCountBits-1)) {
688      missqReplayCount(i) := missqReplayCount(i) + 1.U
689    }
690    when(activeMask(i) && !cohTimeOutMask(i)){
691      cohCount(i) := cohCount(i)+1.U
692    }
693  })
694
695  if (env.EnableDifftest) {
696    // hit resp
697    io.dcache.hit_resps.zipWithIndex.map{case (resp, index) => {
698      val difftest = Module(new DifftestSbufferEvent)
699      val dcache_resp_id = resp.bits.id
700      difftest.io.clock := clock
701      difftest.io.coreid := io.hartId
702      difftest.io.index := index.U
703      difftest.io.sbufferResp := RegNext(resp.fire())
704      difftest.io.sbufferAddr := RegNext(getAddr(ptag(dcache_resp_id)))
705      difftest.io.sbufferData := RegNext(data(dcache_resp_id).asTypeOf(Vec(CacheLineBytes, UInt(8.W))))
706      difftest.io.sbufferMask := RegNext(mask(dcache_resp_id).asUInt)
707    }}
708  }
709
710  // ---------------------- Load Data Forward ---------------------
711  val mismatch = Wire(Vec(LoadPipelineWidth, Bool()))
712  XSPerfAccumulate("vaddr_match_failed", mismatch(0) || mismatch(1))
713  for ((forward, i) <- io.forward.zipWithIndex) {
714    val vtag_matches = VecInit(widthMap(w => vtag(w) === getVTag(forward.vaddr)))
715    // ptag_matches uses paddr from dtlb, which is far from sbuffer
716    val ptag_matches = VecInit(widthMap(w => RegEnable(ptag(w), forward.valid) === RegEnable(getPTag(forward.paddr), forward.valid)))
717    val tag_matches = vtag_matches
718    val tag_mismatch = RegNext(forward.valid) && VecInit(widthMap(w =>
719      RegNext(vtag_matches(w)) =/= ptag_matches(w) && RegNext((activeMask(w) || inflightMask(w)))
720    )).asUInt.orR
721    mismatch(i) := tag_mismatch
722    when (tag_mismatch) {
723      XSDebug("forward tag mismatch: pmatch %x vmatch %x vaddr %x paddr %x\n",
724        RegNext(ptag_matches.asUInt),
725        RegNext(vtag_matches.asUInt),
726        RegNext(forward.vaddr),
727        RegNext(forward.paddr)
728      )
729      forward_need_uarch_drain := true.B
730    }
731    val valid_tag_matches = widthMap(w => tag_matches(w) && activeMask(w))
732    val inflight_tag_matches = widthMap(w => tag_matches(w) && inflightMask(w))
733    val line_offset_mask = UIntToOH(getWordOffset(forward.paddr))
734
735    val valid_tag_match_reg = valid_tag_matches.map(RegNext(_))
736    val inflight_tag_match_reg = inflight_tag_matches.map(RegNext(_))
737    val line_offset_reg = RegNext(line_offset_mask)
738    val forward_mask_candidate_reg = RegEnable(
739      VecInit(mask.map(entry => entry(getWordOffset(forward.paddr)))),
740      forward.valid
741    )
742    val forward_data_candidate_reg = RegEnable(
743      VecInit(data.map(entry => entry(getWordOffset(forward.paddr)))),
744      forward.valid
745    )
746
747    val selectedValidMask = Mux1H(valid_tag_match_reg, forward_mask_candidate_reg)
748    val selectedValidData = Mux1H(valid_tag_match_reg, forward_data_candidate_reg)
749    selectedValidMask.suggestName("selectedValidMask_"+i)
750    selectedValidData.suggestName("selectedValidData_"+i)
751
752    val selectedInflightMask = Mux1H(inflight_tag_match_reg, forward_mask_candidate_reg)
753    val selectedInflightData = Mux1H(inflight_tag_match_reg, forward_data_candidate_reg)
754    selectedInflightMask.suggestName("selectedInflightMask_"+i)
755    selectedInflightData.suggestName("selectedInflightData_"+i)
756
757    // currently not being used
758    val selectedInflightMaskFast = Mux1H(line_offset_mask, Mux1H(inflight_tag_matches, mask).asTypeOf(Vec(CacheLineWords, Vec(DataBytes, Bool()))))
759    val selectedValidMaskFast = Mux1H(line_offset_mask, Mux1H(valid_tag_matches, mask).asTypeOf(Vec(CacheLineWords, Vec(DataBytes, Bool()))))
760
761    forward.dataInvalid := false.B // data in store line merge buffer is always ready
762    forward.matchInvalid := tag_mismatch // paddr / vaddr cam result does not match
763    for (j <- 0 until DataBytes) {
764      forward.forwardMask(j) := false.B
765      forward.forwardData(j) := DontCare
766
767      // valid entries have higher priority than inflight entries
768      when(selectedInflightMask(j)) {
769        forward.forwardMask(j) := true.B
770        forward.forwardData(j) := selectedInflightData(j)
771      }
772      when(selectedValidMask(j)) {
773        forward.forwardMask(j) := true.B
774        forward.forwardData(j) := selectedValidData(j)
775      }
776
777      forward.forwardMaskFast(j) := selectedInflightMaskFast(j) || selectedValidMaskFast(j)
778    }
779    forward.addrInvalid := DontCare
780  }
781
782  for (i <- 0 until StoreBufferSize) {
783    XSDebug("sbf entry " + i + " : ptag %x vtag %x valid %x active %x inflight %x w_timeout %x\n",
784      ptag(i) << OffsetWidth,
785      vtag(i) << OffsetWidth,
786      stateVec(i).isValid(),
787      activeMask(i),
788      inflightMask(i),
789      stateVec(i).w_timeout
790    )
791  }
792
793  val perf_valid_entry_count = RegNext(PopCount(VecInit(stateVec.map(s => !s.isInvalid())).asUInt))
794  XSPerfHistogram("util", perf_valid_entry_count, true.B, 0, StoreBufferSize, 1)
795  XSPerfAccumulate("sbuffer_req_valid", PopCount(VecInit(io.in.map(_.valid)).asUInt))
796  XSPerfAccumulate("sbuffer_req_fire", PopCount(VecInit(io.in.map(_.fire())).asUInt))
797  XSPerfAccumulate("sbuffer_merge", PopCount(VecInit(io.in.zipWithIndex.map({case (in, i) => in.fire() && canMerge(i)})).asUInt))
798  XSPerfAccumulate("sbuffer_newline", PopCount(VecInit(io.in.zipWithIndex.map({case (in, i) => in.fire() && !canMerge(i)})).asUInt))
799  XSPerfAccumulate("dcache_req_valid", io.dcache.req.valid)
800  XSPerfAccumulate("dcache_req_fire", io.dcache.req.fire())
801  XSPerfAccumulate("sbuffer_idle", sbuffer_state === x_idle)
802  XSPerfAccumulate("sbuffer_flush", sbuffer_state === x_drain_sbuffer)
803  XSPerfAccumulate("sbuffer_replace", sbuffer_state === x_replace)
804  XSPerfAccumulate("evenCanInsert", evenCanInsert)
805  XSPerfAccumulate("oddCanInsert", oddCanInsert)
806  XSPerfAccumulate("mainpipe_resp_valid", io.dcache.main_pipe_hit_resp.fire())
807  XSPerfAccumulate("refill_resp_valid", io.dcache.refill_hit_resp.fire())
808  XSPerfAccumulate("replay_resp_valid", io.dcache.replay_resp.fire())
809  XSPerfAccumulate("coh_timeout", cohHasTimeOut)
810
811  // val (store_latency_sample, store_latency) = TransactionLatencyCounter(io.lsu.req.fire(), io.lsu.resp.fire())
812  // XSPerfHistogram("store_latency", store_latency, store_latency_sample, 0, 100, 10)
813  // XSPerfAccumulate("store_req", io.lsu.req.fire())
814
815  val perfEvents = Seq(
816    ("sbuffer_req_valid ", PopCount(VecInit(io.in.map(_.valid)).asUInt)                                                                ),
817    ("sbuffer_req_fire  ", PopCount(VecInit(io.in.map(_.fire())).asUInt)                                                               ),
818    ("sbuffer_merge     ", PopCount(VecInit(io.in.zipWithIndex.map({case (in, i) => in.fire() && canMerge(i)})).asUInt)                ),
819    ("sbuffer_newline   ", PopCount(VecInit(io.in.zipWithIndex.map({case (in, i) => in.fire() && !canMerge(i)})).asUInt)               ),
820    ("dcache_req_valid  ", io.dcache.req.valid                                                                                         ),
821    ("dcache_req_fire   ", io.dcache.req.fire()                                                                                        ),
822    ("sbuffer_idle      ", sbuffer_state === x_idle                                                                                    ),
823    ("sbuffer_flush     ", sbuffer_state === x_drain_sbuffer                                                                           ),
824    ("sbuffer_replace   ", sbuffer_state === x_replace                                                                                 ),
825    ("mpipe_resp_valid  ", io.dcache.main_pipe_hit_resp.fire()                                                                         ),
826    ("refill_resp_valid ", io.dcache.refill_hit_resp.fire()                                                                            ),
827    ("replay_resp_valid ", io.dcache.replay_resp.fire()                                                                                ),
828    ("coh_timeout       ", cohHasTimeOut                                                                                               ),
829    ("sbuffer_1_4_valid ", (perf_valid_entry_count < (StoreBufferSize.U/4.U))                                                          ),
830    ("sbuffer_2_4_valid ", (perf_valid_entry_count > (StoreBufferSize.U/4.U)) & (perf_valid_entry_count <= (StoreBufferSize.U/2.U))    ),
831    ("sbuffer_3_4_valid ", (perf_valid_entry_count > (StoreBufferSize.U/2.U)) & (perf_valid_entry_count <= (StoreBufferSize.U*3.U/4.U))),
832    ("sbuffer_full_valid", (perf_valid_entry_count > (StoreBufferSize.U*3.U/4.U)))
833  )
834  generatePerfEvent()
835
836}
837