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