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