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