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 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(8.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 prefetcher.io.memSetPattenDetected := io.memSetPattenDetected 407 408 def wordReqToBufLine( // allocate a new line in sbuffer 409 req: DCacheWordReq, 410 reqptag: UInt, 411 reqvtag: UInt, 412 insertIdx: UInt, 413 insertVec: UInt, 414 wordOffset: UInt 415 ): Unit = { 416 assert(UIntToOH(insertIdx) === insertVec) 417 val sameBlockInflightMask = genSameBlockInflightMask(reqptag) 418 (0 until StoreBufferSize).map(entryIdx => { 419 when(insertVec(entryIdx)){ 420 stateVec(entryIdx).state_valid := true.B 421 stateVec(entryIdx).w_sameblock_inflight := sameBlockInflightMask.orR // set w_sameblock_inflight when a line is first allocated 422 when(sameBlockInflightMask.orR){ 423 waitInflightMask(entryIdx) := sameBlockInflightMask 424 } 425 cohCount(entryIdx) := 0.U 426 // missqReplayCount(insertIdx) := 0.U 427 ptag(entryIdx) := reqptag 428 vtag(entryIdx) := reqvtag // update vtag if a new sbuffer line is allocated 429 } 430 }) 431 } 432 433 def mergeWordReq( // merge write req into an existing line 434 req: DCacheWordReq, 435 reqptag: UInt, 436 reqvtag: UInt, 437 mergeIdx: UInt, 438 mergeVec: UInt, 439 wordOffset: UInt 440 ): Unit = { 441 assert(UIntToOH(mergeIdx) === mergeVec) 442 (0 until StoreBufferSize).map(entryIdx => { 443 when(mergeVec(entryIdx)) { 444 cohCount(entryIdx) := 0.U 445 // missqReplayCount(entryIdx) := 0.U 446 // check if vtag is the same, if not, trigger sbuffer flush 447 when(reqvtag =/= vtag(entryIdx)) { 448 XSDebug("reqvtag =/= sbufvtag req(vtag %x ptag %x) sbuffer(vtag %x ptag %x)\n", 449 reqvtag << OffsetWidth, 450 reqptag << OffsetWidth, 451 vtag(entryIdx) << OffsetWidth, 452 ptag(entryIdx) << OffsetWidth 453 ) 454 merge_need_uarch_drain := true.B 455 } 456 } 457 }) 458 } 459 460 for(((in, vwordOffset), i) <- io.in.zip(Seq(firstWord, secondWord)).zipWithIndex){ 461 writeReq(i).valid := in.fire() 462 writeReq(i).bits.vwordOffset := vwordOffset 463 writeReq(i).bits.mask := in.bits.mask 464 writeReq(i).bits.data := in.bits.data 465 writeReq(i).bits.wline := in.bits.wline 466 val debug_insertIdx = if(i == 0) firstInsertIdx else secondInsertIdx 467 val insertVec = if(i == 0) firstInsertVec else secondInsertVec 468 assert(!((PopCount(insertVec) > 1.U) && in.fire())) 469 val insertIdx = OHToUInt(insertVec) 470 accessIdx(i).valid := RegNext(in.fire()) 471 accessIdx(i).bits := RegNext(Mux(canMerge(i), mergeIdx(i), insertIdx)) 472 when(in.fire()){ 473 when(canMerge(i)){ 474 writeReq(i).bits.wvec := mergeVec(i) 475 mergeWordReq(in.bits, inptags(i), invtags(i), mergeIdx(i), mergeVec(i), vwordOffset) 476 XSDebug(p"merge req $i to line [${mergeIdx(i)}]\n") 477 }.otherwise({ 478 writeReq(i).bits.wvec := insertVec 479 wordReqToBufLine(in.bits, inptags(i), invtags(i), insertIdx, insertVec, vwordOffset) 480 XSDebug(p"insert req $i to line[$insertIdx]\n") 481 assert(debug_insertIdx === insertIdx) 482 }) 483 } 484 } 485 486 487 for(i <- 0 until StoreBufferSize){ 488 XSDebug(stateVec(i).isValid(), 489 p"[$i] timeout:${cohCount(i)(EvictCountBits-1)} state:${stateVec(i)}\n" 490 ) 491 } 492 493 for((req, i) <- io.in.zipWithIndex){ 494 XSDebug(req.fire(), 495 p"accept req [$i]: " + 496 p"addr:${Hexadecimal(req.bits.addr)} " + 497 p"mask:${Binary(shiftMaskToLow(req.bits.addr,req.bits.mask))} " + 498 p"data:${Hexadecimal(shiftDataToLow(req.bits.addr,req.bits.data))}\n" 499 ) 500 XSDebug(req.valid && !req.ready, 501 p"req [$i] blocked by sbuffer\n" 502 ) 503 } 504 505 // for now, when enq, trigger a prefetch (if EnableAtCommitMissTrigger) 506 require(EnsbufferWidth == StorePipelineWidth) 507 508 // ---------------------- Send Dcache Req --------------------- 509 510 val sbuffer_empty = Cat(invalidMask).andR() 511 val sq_empty = !Cat(io.in.map(_.valid)).orR() 512 val empty = sbuffer_empty && sq_empty 513 val threshold = Wire(UInt(5.W)) // RegNext(io.csrCtrl.sbuffer_threshold +& 1.U) 514 threshold := Constantin.createRecord("StoreBufferThreshold_"+p(XSCoreParamsKey).HartId.toString(), initValue = 7.U) 515 val base = Wire(UInt(5.W)) 516 base := Constantin.createRecord("StoreBufferBase_"+p(XSCoreParamsKey).HartId.toString(), initValue = 4.U) 517 val ActiveCount = PopCount(activeMask) 518 val ValidCount = PopCount(validMask) 519 val forceThreshold = Mux(io.force_write, threshold - base, threshold) 520 val do_eviction = RegNext(ActiveCount >= forceThreshold || ActiveCount === (StoreBufferSize-1).U || ValidCount === (StoreBufferSize).U, init = false.B) 521 require((StoreBufferThreshold + 1) <= StoreBufferSize) 522 523 XSDebug(p"ActiveCount[$ActiveCount]\n") 524 525 io.flush.empty := RegNext(empty && io.sqempty) 526 // lru.io.flush := sbuffer_state === x_drain_all && empty 527 switch(sbuffer_state){ 528 is(x_idle){ 529 when(io.flush.valid){ 530 sbuffer_state := x_drain_all 531 }.elsewhen(do_uarch_drain){ 532 sbuffer_state := x_drain_sbuffer 533 }.elsewhen(do_eviction){ 534 sbuffer_state := x_replace 535 } 536 } 537 is(x_drain_all){ 538 when(empty){ 539 sbuffer_state := x_idle 540 } 541 } 542 is(x_drain_sbuffer){ 543 when(io.flush.valid){ 544 sbuffer_state := x_drain_all 545 }.elsewhen(sbuffer_empty){ 546 sbuffer_state := x_idle 547 } 548 } 549 is(x_replace){ 550 when(io.flush.valid){ 551 sbuffer_state := x_drain_all 552 }.elsewhen(do_uarch_drain){ 553 sbuffer_state := x_drain_sbuffer 554 }.elsewhen(!do_eviction){ 555 sbuffer_state := x_idle 556 } 557 } 558 } 559 XSDebug(p"sbuffer state:${sbuffer_state} do eviction:${do_eviction} empty:${empty}\n") 560 561 def noSameBlockInflight(idx: UInt): Bool = { 562 // stateVec(idx) itself must not be s_inflight 563 !Cat(widthMap(i => inflightMask(i) && ptag(idx) === ptag(i))).orR() 564 } 565 566 def genSameBlockInflightMask(ptag_in: UInt): UInt = { 567 val mask = VecInit(widthMap(i => inflightMask(i) && ptag_in === ptag(i))).asUInt // quite slow, use it with care 568 assert(!(PopCount(mask) > 1.U)) 569 mask 570 } 571 572 def haveSameBlockInflight(ptag_in: UInt): Bool = { 573 genSameBlockInflightMask(ptag_in).orR 574 } 575 576 // --------------------------------------------------------------------------- 577 // sbuffer to dcache pipeline 578 // --------------------------------------------------------------------------- 579 580 // Now sbuffer deq logic is divided into 2 stages: 581 582 // sbuffer_out_s0: 583 // * read data and meta from sbuffer 584 // * RegNext() them 585 // * set line state to inflight 586 587 // sbuffer_out_s1: 588 // * send write req to dcache 589 590 // sbuffer_out_extra: 591 // * receive write result from dcache 592 // * update line state 593 594 val sbuffer_out_s1_ready = Wire(Bool()) 595 596 // --------------------------------------------------------------------------- 597 // sbuffer_out_s0 598 // --------------------------------------------------------------------------- 599 600 val need_drain = needDrain(sbuffer_state) 601 val need_replace = do_eviction || (sbuffer_state === x_replace) 602 val sbuffer_out_s0_evictionIdx = Mux(missqReplayHasTimeOut, 603 missqReplayTimeOutIdx, 604 Mux(need_drain, 605 drainIdx, 606 Mux(cohHasTimeOut, cohTimeOutIdx, replaceIdx) 607 ) 608 ) 609 610 // If there is a inflight dcache req which has same ptag with sbuffer_out_s0_evictionIdx's ptag, 611 // current eviction should be blocked. 612 val sbuffer_out_s0_valid = missqReplayHasTimeOut || 613 stateVec(sbuffer_out_s0_evictionIdx).isDcacheReqCandidate() && 614 (need_drain || cohHasTimeOut || need_replace) 615 assert(!( 616 stateVec(sbuffer_out_s0_evictionIdx).isDcacheReqCandidate && 617 !noSameBlockInflight(sbuffer_out_s0_evictionIdx) 618 )) 619 val sbuffer_out_s0_cango = sbuffer_out_s1_ready 620 sbuffer_out_s0_fire := sbuffer_out_s0_valid && sbuffer_out_s0_cango 621 622 // --------------------------------------------------------------------------- 623 // sbuffer_out_s1 624 // --------------------------------------------------------------------------- 625 626 // TODO: use EnsbufferWidth 627 val shouldWaitWriteFinish = RegNext(VecInit((0 until EnsbufferWidth).map{i => 628 (writeReq(i).bits.wvec.asUInt & UIntToOH(sbuffer_out_s0_evictionIdx).asUInt).orR && 629 writeReq(i).valid 630 }).asUInt.orR) 631 // block dcache write if read / write hazard 632 val blockDcacheWrite = shouldWaitWriteFinish 633 634 val sbuffer_out_s1_valid = RegInit(false.B) 635 sbuffer_out_s1_ready := io.dcache.req.ready && !blockDcacheWrite || !sbuffer_out_s1_valid 636 val sbuffer_out_s1_fire = io.dcache.req.fire() 637 638 // when sbuffer_out_s1_fire, send dcache req stored in pipeline reg to dcache 639 when(sbuffer_out_s1_fire){ 640 sbuffer_out_s1_valid := false.B 641 } 642 // when sbuffer_out_s0_fire, read dcache req data and store them in a pipeline reg 643 when(sbuffer_out_s0_cango){ 644 sbuffer_out_s1_valid := sbuffer_out_s0_valid 645 } 646 when(sbuffer_out_s0_fire){ 647 stateVec(sbuffer_out_s0_evictionIdx).state_inflight := true.B 648 stateVec(sbuffer_out_s0_evictionIdx).w_timeout := false.B 649 // stateVec(sbuffer_out_s0_evictionIdx).s_pipe_req := true.B 650 XSDebug(p"$sbuffer_out_s0_evictionIdx will be sent to Dcache\n") 651 } 652 653 XSDebug(p"need drain:$need_drain cohHasTimeOut: $cohHasTimeOut need replace:$need_replace\n") 654 XSDebug(p"drainIdx:$drainIdx tIdx:$cohTimeOutIdx replIdx:$replaceIdx " + 655 p"blocked:${!noSameBlockInflight(sbuffer_out_s0_evictionIdx)} v:${activeMask(sbuffer_out_s0_evictionIdx)}\n") 656 XSDebug(p"sbuffer_out_s0_valid:$sbuffer_out_s0_valid evictIdx:$sbuffer_out_s0_evictionIdx dcache ready:${io.dcache.req.ready}\n") 657 // Note: if other dcache req in the same block are inflight, 658 // the lru update may not accurate 659 accessIdx(EnsbufferWidth).valid := invalidMask(replaceIdx) || ( 660 need_replace && !need_drain && !cohHasTimeOut && !missqReplayHasTimeOut && sbuffer_out_s0_cango && activeMask(replaceIdx)) 661 accessIdx(EnsbufferWidth).bits := replaceIdx 662 val sbuffer_out_s1_evictionIdx = RegEnable(sbuffer_out_s0_evictionIdx, enable = sbuffer_out_s0_fire) 663 val sbuffer_out_s1_evictionPTag = RegEnable(ptag(sbuffer_out_s0_evictionIdx), enable = sbuffer_out_s0_fire) 664 val sbuffer_out_s1_evictionVTag = RegEnable(vtag(sbuffer_out_s0_evictionIdx), enable = sbuffer_out_s0_fire) 665 666 io.dcache.req.valid := sbuffer_out_s1_valid && !blockDcacheWrite 667 io.dcache.req.bits := DontCare 668 io.dcache.req.bits.cmd := MemoryOpConstants.M_XWR 669 io.dcache.req.bits.addr := getAddr(sbuffer_out_s1_evictionPTag) 670 io.dcache.req.bits.vaddr := getAddr(sbuffer_out_s1_evictionVTag) 671 io.dcache.req.bits.data := data(sbuffer_out_s1_evictionIdx).asUInt 672 io.dcache.req.bits.mask := mask(sbuffer_out_s1_evictionIdx).asUInt 673 io.dcache.req.bits.id := sbuffer_out_s1_evictionIdx 674 675 when (sbuffer_out_s1_fire) { 676 assert(!(io.dcache.req.bits.vaddr === 0.U)) 677 assert(!(io.dcache.req.bits.addr === 0.U)) 678 } 679 680 XSDebug(sbuffer_out_s1_fire, 681 p"send buf [$sbuffer_out_s1_evictionIdx] to Dcache, req fire\n" 682 ) 683 684 // update sbuffer status according to dcache resp source 685 686 def id_to_sbuffer_id(id: UInt): UInt = { 687 require(id.getWidth >= log2Up(StoreBufferSize)) 688 id(log2Up(StoreBufferSize)-1, 0) 689 } 690 691 // hit resp 692 io.dcache.hit_resps.map(resp => { 693 val dcache_resp_id = resp.bits.id 694 when (resp.fire()) { 695 stateVec(dcache_resp_id).state_inflight := false.B 696 stateVec(dcache_resp_id).state_valid := false.B 697 assert(!resp.bits.replay) 698 assert(!resp.bits.miss) // not need to resp if miss, to be opted 699 assert(stateVec(dcache_resp_id).state_inflight === true.B) 700 } 701 702 // Update w_sameblock_inflight flag is delayed for 1 cycle 703 // 704 // When a new req allocate a new line in sbuffer, sameblock_inflight check will ignore 705 // current dcache.hit_resps. Then, in the next cycle, we have plenty of time to check 706 // if the same block is still inflight 707 (0 until StoreBufferSize).map(i => { 708 when( 709 stateVec(i).w_sameblock_inflight && 710 stateVec(i).state_valid && 711 RegNext(resp.fire()) && 712 waitInflightMask(i) === UIntToOH(RegNext(id_to_sbuffer_id(dcache_resp_id))) 713 ){ 714 stateVec(i).w_sameblock_inflight := false.B 715 } 716 }) 717 }) 718 719 io.dcache.hit_resps.zip(dataModule.io.maskFlushReq).map{case (resp, maskFlush) => { 720 maskFlush.valid := resp.fire() 721 maskFlush.bits.wvec := UIntToOH(resp.bits.id) 722 }} 723 724 // replay resp 725 val replay_resp_id = io.dcache.replay_resp.bits.id 726 when (io.dcache.replay_resp.fire()) { 727 missqReplayCount(replay_resp_id) := 0.U 728 stateVec(replay_resp_id).w_timeout := true.B 729 // waiting for timeout 730 assert(io.dcache.replay_resp.bits.replay) 731 assert(stateVec(replay_resp_id).state_inflight === true.B) 732 } 733 734 // TODO: reuse cohCount 735 (0 until StoreBufferSize).map(i => { 736 when(stateVec(i).w_timeout && stateVec(i).state_inflight && !missqReplayCount(i)(MissqReplayCountBits-1)) { 737 missqReplayCount(i) := missqReplayCount(i) + 1.U 738 } 739 when(activeMask(i) && !cohTimeOutMask(i)){ 740 cohCount(i) := cohCount(i)+1.U 741 } 742 }) 743 744 if (env.EnableDifftest) { 745 // hit resp 746 io.dcache.hit_resps.zipWithIndex.map{case (resp, index) => { 747 val difftest = DifftestModule(new DiffSbufferEvent, delay = 1) 748 val dcache_resp_id = resp.bits.id 749 difftest.coreid := io.hartId 750 difftest.index := index.U 751 difftest.valid := resp.fire() 752 difftest.addr := getAddr(ptag(dcache_resp_id)) 753 difftest.data := data(dcache_resp_id).asTypeOf(Vec(CacheLineBytes, UInt(8.W))) 754 difftest.mask := mask(dcache_resp_id).asUInt 755 }} 756 } 757 758 // ---------------------- Load Data Forward --------------------- 759 val mismatch = Wire(Vec(LoadPipelineWidth, Bool())) 760 XSPerfAccumulate("vaddr_match_failed", mismatch(0) || mismatch(1)) 761 for ((forward, i) <- io.forward.zipWithIndex) { 762 val vtag_matches = VecInit(widthMap(w => vtag(w) === getVTag(forward.vaddr))) 763 // ptag_matches uses paddr from dtlb, which is far from sbuffer 764 val ptag_matches = VecInit(widthMap(w => RegEnable(ptag(w), forward.valid) === RegEnable(getPTag(forward.paddr), forward.valid))) 765 val tag_matches = vtag_matches 766 val tag_mismatch = RegNext(forward.valid) && VecInit(widthMap(w => 767 RegNext(vtag_matches(w)) =/= ptag_matches(w) && RegNext((activeMask(w) || inflightMask(w))) 768 )).asUInt.orR 769 mismatch(i) := tag_mismatch 770 when (tag_mismatch) { 771 XSDebug("forward tag mismatch: pmatch %x vmatch %x vaddr %x paddr %x\n", 772 RegNext(ptag_matches.asUInt), 773 RegNext(vtag_matches.asUInt), 774 RegNext(forward.vaddr), 775 RegNext(forward.paddr) 776 ) 777 forward_need_uarch_drain := true.B 778 } 779 val valid_tag_matches = widthMap(w => tag_matches(w) && activeMask(w)) 780 val inflight_tag_matches = widthMap(w => tag_matches(w) && inflightMask(w)) 781 val line_offset_mask = UIntToOH(getVWordOffset(forward.paddr)) 782 783 val valid_tag_match_reg = valid_tag_matches.map(RegNext(_)) 784 val inflight_tag_match_reg = inflight_tag_matches.map(RegNext(_)) 785 val line_offset_reg = RegNext(line_offset_mask) 786 val forward_mask_candidate_reg = RegEnable( 787 VecInit(mask.map(entry => entry(getVWordOffset(forward.paddr)))), 788 forward.valid 789 ) 790 val forward_data_candidate_reg = RegEnable( 791 VecInit(data.map(entry => entry(getVWordOffset(forward.paddr)))), 792 forward.valid 793 ) 794 795 val selectedValidMask = Mux1H(valid_tag_match_reg, forward_mask_candidate_reg) 796 val selectedValidData = Mux1H(valid_tag_match_reg, forward_data_candidate_reg) 797 selectedValidMask.suggestName("selectedValidMask_"+i) 798 selectedValidData.suggestName("selectedValidData_"+i) 799 800 val selectedInflightMask = Mux1H(inflight_tag_match_reg, forward_mask_candidate_reg) 801 val selectedInflightData = Mux1H(inflight_tag_match_reg, forward_data_candidate_reg) 802 selectedInflightMask.suggestName("selectedInflightMask_"+i) 803 selectedInflightData.suggestName("selectedInflightData_"+i) 804 805 // currently not being used 806 val selectedInflightMaskFast = Mux1H(line_offset_mask, Mux1H(inflight_tag_matches, mask).asTypeOf(Vec(CacheLineVWords, Vec(VDataBytes, Bool())))) 807 val selectedValidMaskFast = Mux1H(line_offset_mask, Mux1H(valid_tag_matches, mask).asTypeOf(Vec(CacheLineVWords, Vec(VDataBytes, Bool())))) 808 809 forward.dataInvalid := false.B // data in store line merge buffer is always ready 810 forward.matchInvalid := tag_mismatch // paddr / vaddr cam result does not match 811 for (j <- 0 until VDataBytes) { 812 forward.forwardMask(j) := false.B 813 forward.forwardData(j) := DontCare 814 815 // valid entries have higher priority than inflight entries 816 when(selectedInflightMask(j)) { 817 forward.forwardMask(j) := true.B 818 forward.forwardData(j) := selectedInflightData(j) 819 } 820 when(selectedValidMask(j)) { 821 forward.forwardMask(j) := true.B 822 forward.forwardData(j) := selectedValidData(j) 823 } 824 825 forward.forwardMaskFast(j) := selectedInflightMaskFast(j) || selectedValidMaskFast(j) 826 } 827 forward.addrInvalid := DontCare 828 } 829 830 for (i <- 0 until StoreBufferSize) { 831 XSDebug("sbf entry " + i + " : ptag %x vtag %x valid %x active %x inflight %x w_timeout %x\n", 832 ptag(i) << OffsetWidth, 833 vtag(i) << OffsetWidth, 834 stateVec(i).isValid(), 835 activeMask(i), 836 inflightMask(i), 837 stateVec(i).w_timeout 838 ) 839 } 840 841 val perf_valid_entry_count = RegNext(PopCount(VecInit(stateVec.map(s => !s.isInvalid())).asUInt)) 842 XSPerfHistogram("util", perf_valid_entry_count, true.B, 0, StoreBufferSize, 1) 843 XSPerfAccumulate("sbuffer_req_valid", PopCount(VecInit(io.in.map(_.valid)).asUInt)) 844 XSPerfAccumulate("sbuffer_req_fire", PopCount(VecInit(io.in.map(_.fire())).asUInt)) 845 XSPerfAccumulate("sbuffer_merge", PopCount(VecInit(io.in.zipWithIndex.map({case (in, i) => in.fire() && canMerge(i)})).asUInt)) 846 XSPerfAccumulate("sbuffer_newline", PopCount(VecInit(io.in.zipWithIndex.map({case (in, i) => in.fire() && !canMerge(i)})).asUInt)) 847 XSPerfAccumulate("dcache_req_valid", io.dcache.req.valid) 848 XSPerfAccumulate("dcache_req_fire", io.dcache.req.fire()) 849 XSPerfAccumulate("sbuffer_idle", sbuffer_state === x_idle) 850 XSPerfAccumulate("sbuffer_flush", sbuffer_state === x_drain_sbuffer) 851 XSPerfAccumulate("sbuffer_replace", sbuffer_state === x_replace) 852 XSPerfAccumulate("evenCanInsert", evenCanInsert) 853 XSPerfAccumulate("oddCanInsert", oddCanInsert) 854 XSPerfAccumulate("mainpipe_resp_valid", io.dcache.main_pipe_hit_resp.fire()) 855 XSPerfAccumulate("refill_resp_valid", io.dcache.refill_hit_resp.fire()) 856 XSPerfAccumulate("replay_resp_valid", io.dcache.replay_resp.fire()) 857 XSPerfAccumulate("coh_timeout", cohHasTimeOut) 858 859 // val (store_latency_sample, store_latency) = TransactionLatencyCounter(io.lsu.req.fire(), io.lsu.resp.fire()) 860 // XSPerfHistogram("store_latency", store_latency, store_latency_sample, 0, 100, 10) 861 // XSPerfAccumulate("store_req", io.lsu.req.fire()) 862 863 val perfEvents = Seq( 864 ("sbuffer_req_valid ", PopCount(VecInit(io.in.map(_.valid)).asUInt) ), 865 ("sbuffer_req_fire ", PopCount(VecInit(io.in.map(_.fire())).asUInt) ), 866 ("sbuffer_merge ", PopCount(VecInit(io.in.zipWithIndex.map({case (in, i) => in.fire() && canMerge(i)})).asUInt) ), 867 ("sbuffer_newline ", PopCount(VecInit(io.in.zipWithIndex.map({case (in, i) => in.fire() && !canMerge(i)})).asUInt) ), 868 ("dcache_req_valid ", io.dcache.req.valid ), 869 ("dcache_req_fire ", io.dcache.req.fire() ), 870 ("sbuffer_idle ", sbuffer_state === x_idle ), 871 ("sbuffer_flush ", sbuffer_state === x_drain_sbuffer ), 872 ("sbuffer_replace ", sbuffer_state === x_replace ), 873 ("mpipe_resp_valid ", io.dcache.main_pipe_hit_resp.fire() ), 874 ("refill_resp_valid ", io.dcache.refill_hit_resp.fire() ), 875 ("replay_resp_valid ", io.dcache.replay_resp.fire() ), 876 ("coh_timeout ", cohHasTimeOut ), 877 ("sbuffer_1_4_valid ", (perf_valid_entry_count < (StoreBufferSize.U/4.U)) ), 878 ("sbuffer_2_4_valid ", (perf_valid_entry_count > (StoreBufferSize.U/4.U)) & (perf_valid_entry_count <= (StoreBufferSize.U/2.U)) ), 879 ("sbuffer_3_4_valid ", (perf_valid_entry_count > (StoreBufferSize.U/2.U)) & (perf_valid_entry_count <= (StoreBufferSize.U*3.U/4.U))), 880 ("sbuffer_full_valid", (perf_valid_entry_count > (StoreBufferSize.U*3.U/4.U))) 881 ) 882 generatePerfEvent() 883 884} 885