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