1package xiangshan.mem 2 3import chisel3._ 4import chisel3.util._ 5import utils._ 6import xiangshan._ 7import xiangshan.cache._ 8import xiangshan.cache.{DCacheWordIO, DCacheLineIO, TlbRequestIO, MemoryOpConstants} 9import xiangshan.backend.LSUOpType 10import xiangshan.backend.roq.RoqLsqIO 11 12 13class SqPtr extends CircularQueuePtr(SqPtr.StoreQueueSize) { } 14 15object SqPtr extends HasXSParameter { 16 def apply(f: Bool, v: UInt): SqPtr = { 17 val ptr = Wire(new SqPtr) 18 ptr.flag := f 19 ptr.value := v 20 ptr 21 } 22} 23 24class SqEnqIO extends XSBundle { 25 val canAccept = Output(Bool()) 26 val lqCanAccept = Input(Bool()) 27 val needAlloc = Vec(RenameWidth, Input(Bool())) 28 val req = Vec(RenameWidth, Flipped(ValidIO(new MicroOp))) 29 val resp = Vec(RenameWidth, Output(new SqPtr)) 30} 31 32// Store Queue 33class StoreQueue extends XSModule with HasDCacheParameters with HasCircularQueuePtrHelper { 34 val io = IO(new Bundle() { 35 val enq = new SqEnqIO 36 val brqRedirect = Flipped(ValidIO(new Redirect)) 37 val flush = Input(Bool()) 38 val storeIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle))) 39 val sbuffer = Vec(StorePipelineWidth, Decoupled(new DCacheWordReq)) 40 val mmioStout = DecoupledIO(new ExuOutput) // writeback uncached store 41 val forward = Vec(LoadPipelineWidth, Flipped(new MaskedLoadForwardQueryIO)) 42 val roq = Flipped(new RoqLsqIO) 43 val uncache = new DCacheWordIO 44 // val refill = Flipped(Valid(new DCacheLineReq )) 45 val exceptionAddr = new ExceptionAddrIO 46 val sqempty = Output(Bool()) 47 val issuePtrExt = Output(new SqPtr) 48 val storeIssue = Vec(StorePipelineWidth, Flipped(Valid(new ExuInput))) 49 }) 50 51 val difftestIO = IO(new Bundle() { 52 val storeCommit = Output(UInt(2.W)) 53 val storeAddr = Output(Vec(2, UInt(64.W))) 54 val storeData = Output(Vec(2, UInt(64.W))) 55 val storeMask = Output(Vec(2, UInt(8.W))) 56 }) 57 difftestIO <> DontCare 58 59 // data modules 60 val uop = Reg(Vec(StoreQueueSize, new MicroOp)) 61 // val data = Reg(Vec(StoreQueueSize, new LsqEntry)) 62 val dataModule = Module(new StoreQueueData(StoreQueueSize, numRead = StorePipelineWidth, numWrite = StorePipelineWidth, numForward = StorePipelineWidth)) 63 dataModule.io := DontCare 64 val paddrModule = Module(new SQPaddrModule(StoreQueueSize, numRead = StorePipelineWidth, numWrite = StorePipelineWidth, numForward = StorePipelineWidth)) 65 paddrModule.io := DontCare 66 val vaddrModule = Module(new SyncDataModuleTemplate(UInt(VAddrBits.W), StoreQueueSize, numRead = 1, numWrite = StorePipelineWidth)) 67 vaddrModule.io := DontCare 68 69 // state & misc 70 val allocated = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // sq entry has been allocated 71 val datavalid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // non-mmio data is valid 72 val writebacked = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // inst has been writebacked to CDB 73 val issued = Reg(Vec(StoreQueueSize, Bool())) // inst has been issued by rs 74 val commited = Reg(Vec(StoreQueueSize, Bool())) // inst has been commited by roq 75 val pending = Reg(Vec(StoreQueueSize, Bool())) // mmio pending: inst is an mmio inst, it will not be executed until it reachs the end of roq 76 val mmio = Reg(Vec(StoreQueueSize, Bool())) // mmio: inst is an mmio inst 77 78 // ptr 79 require(StoreQueueSize > RenameWidth) 80 val enqPtrExt = RegInit(VecInit((0 until RenameWidth).map(_.U.asTypeOf(new SqPtr)))) 81 val deqPtrExt = RegInit(VecInit((0 until StorePipelineWidth).map(_.U.asTypeOf(new SqPtr)))) 82 val cmtPtrExt = RegInit(VecInit((0 until CommitWidth).map(_.U.asTypeOf(new SqPtr)))) 83 val issuePtrExt = RegInit(0.U.asTypeOf(new SqPtr)) 84 val validCounter = RegInit(0.U(log2Ceil(LoadQueueSize + 1).W)) 85 val allowEnqueue = RegInit(true.B) 86 87 val enqPtr = enqPtrExt(0).value 88 val deqPtr = deqPtrExt(0).value 89 val cmtPtr = cmtPtrExt(0).value 90 91 val deqMask = UIntToMask(deqPtr, StoreQueueSize) 92 val enqMask = UIntToMask(enqPtr, StoreQueueSize) 93 94 val commitCount = RegNext(io.roq.scommit) 95 96 // Read dataModule 97 // deqPtrExtNext and deqPtrExtNext+1 entry will be read from dataModule 98 // if !sbuffer.fire(), read the same ptr 99 // if sbuffer.fire(), read next 100 val deqPtrExtNext = WireInit(Mux(io.sbuffer(1).fire(), 101 VecInit(deqPtrExt.map(_ + 2.U)), 102 Mux(io.sbuffer(0).fire() || io.mmioStout.fire(), 103 VecInit(deqPtrExt.map(_ + 1.U)), 104 deqPtrExt 105 ) 106 )) 107 for (i <- 0 until StorePipelineWidth) { 108 dataModule.io.raddr(i) := deqPtrExtNext(i).value 109 paddrModule.io.raddr(i) := deqPtrExtNext(i).value 110 } 111 112 // no inst will be commited 1 cycle before tval update 113 vaddrModule.io.raddr(0) := (cmtPtrExt(0) + commitCount).value 114 115 /** 116 * Enqueue at dispatch 117 * 118 * Currently, StoreQueue only allows enqueue when #emptyEntries > RenameWidth(EnqWidth) 119 */ 120 io.enq.canAccept := allowEnqueue 121 for (i <- 0 until RenameWidth) { 122 val offset = if (i == 0) 0.U else PopCount(io.enq.needAlloc.take(i)) 123 val sqIdx = enqPtrExt(offset) 124 val index = sqIdx.value 125 when (io.enq.req(i).valid && io.enq.canAccept && io.enq.lqCanAccept && !(io.brqRedirect.valid || io.flush)) { 126 uop(index) := io.enq.req(i).bits 127 allocated(index) := true.B 128 datavalid(index) := false.B 129 writebacked(index) := false.B 130 issued(index) := false.B 131 commited(index) := false.B 132 pending(index) := false.B 133 } 134 io.enq.resp(i) := sqIdx 135 } 136 XSDebug(p"(ready, valid): ${io.enq.canAccept}, ${Binary(Cat(io.enq.req.map(_.valid)))}\n") 137 138 /** 139 * Update issuePtr when issue from rs 140 */ 141 142 // update state bit issued 143 for (i <- 0 until StorePipelineWidth) { 144 when (io.storeIssue(i).valid) { 145 issued(io.storeIssue(i).bits.uop.sqIdx.value) := true.B 146 } 147 } 148 149 // update issuePtr 150 val IssuePtrMoveStride = 4 151 require(IssuePtrMoveStride >= 2) 152 153 val issueLookup = Wire(Vec(IssuePtrMoveStride, Bool())) 154 for (i <- 0 until IssuePtrMoveStride) { 155 val lookUpPtr = issuePtrExt.value + i.U 156 if(i == 0){ 157 issueLookup(i) := allocated(lookUpPtr) && issued(lookUpPtr) 158 }else{ 159 issueLookup(i) := allocated(lookUpPtr) && issued(lookUpPtr) && issueLookup(i-1) 160 } 161 162 when(issueLookup(i)){ 163 issuePtrExt := issuePtrExt + (i+1).U 164 } 165 } 166 167 when(io.brqRedirect.valid || io.flush){ 168 issuePtrExt := Mux( 169 isAfter(cmtPtrExt(0), deqPtrExt(0)), 170 cmtPtrExt(0), 171 deqPtrExtNext(0) // for mmio insts, deqPtr may be ahead of cmtPtr 172 ) 173 } 174 // send issuePtrExt to rs 175 // io.issuePtrExt := cmtPtrExt(0) 176 io.issuePtrExt := issuePtrExt 177 178 /** 179 * Writeback store from store units 180 * 181 * Most store instructions writeback to regfile in the previous cycle. 182 * However, 183 * (1) For an mmio instruction with exceptions, we need to mark it as datavalid 184 * (in this way it will trigger an exception when it reaches ROB's head) 185 * instead of pending to avoid sending them to lower level. 186 * (2) For an mmio instruction without exceptions, we mark it as pending. 187 * When the instruction reaches ROB's head, StoreQueue sends it to uncache channel. 188 * Upon receiving the response, StoreQueue writes back the instruction 189 * through arbiter with store units. It will later commit as normal. 190 */ 191 for (i <- 0 until StorePipelineWidth) { 192 dataModule.io.wen(i) := false.B 193 paddrModule.io.wen(i) := false.B 194 val stWbIndex = io.storeIn(i).bits.uop.sqIdx.value 195 when (io.storeIn(i).fire()) { 196 datavalid(stWbIndex) := !io.storeIn(i).bits.mmio 197 writebacked(stWbIndex) := !io.storeIn(i).bits.mmio 198 pending(stWbIndex) := io.storeIn(i).bits.mmio 199 200 val storeWbData = Wire(new SQDataEntry) 201 storeWbData := DontCare 202 storeWbData.mask := io.storeIn(i).bits.mask 203 storeWbData.data := io.storeIn(i).bits.data 204 205 dataModule.io.waddr(i) := stWbIndex 206 dataModule.io.wdata(i) := storeWbData 207 dataModule.io.wen(i) := true.B 208 209 paddrModule.io.waddr(i) := stWbIndex 210 paddrModule.io.wdata(i) := io.storeIn(i).bits.paddr 211 paddrModule.io.wen(i) := true.B 212 213 214 mmio(stWbIndex) := io.storeIn(i).bits.mmio 215 216 XSInfo("store write to sq idx %d pc 0x%x vaddr %x paddr %x data %x mmio %x\n", 217 io.storeIn(i).bits.uop.sqIdx.value, 218 io.storeIn(i).bits.uop.cf.pc, 219 io.storeIn(i).bits.vaddr, 220 io.storeIn(i).bits.paddr, 221 io.storeIn(i).bits.data, 222 io.storeIn(i).bits.mmio 223 ) 224 } 225 // vaddrModule write is delayed, as vaddrModule will not be read right after write 226 vaddrModule.io.waddr(i) := RegNext(stWbIndex) 227 vaddrModule.io.wdata(i) := RegNext(io.storeIn(i).bits.vaddr) 228 vaddrModule.io.wen(i) := RegNext(io.storeIn(i).fire()) 229 } 230 231 /** 232 * load forward query 233 * 234 * Check store queue for instructions that is older than the load. 235 * The response will be valid at the next cycle after req. 236 */ 237 // check over all lq entries and forward data from the first matched store 238 for (i <- 0 until LoadPipelineWidth) { 239 io.forward(i).forwardMask := 0.U(8.W).asBools 240 io.forward(i).forwardData := DontCare 241 242 // Compare deqPtr (deqPtr) and forward.sqIdx, we have two cases: 243 // (1) if they have the same flag, we need to check range(tail, sqIdx) 244 // (2) if they have different flags, we need to check range(tail, LoadQueueSize) and range(0, sqIdx) 245 // Forward1: Mux(same_flag, range(tail, sqIdx), range(tail, LoadQueueSize)) 246 // Forward2: Mux(same_flag, 0.U, range(0, sqIdx) ) 247 // i.e. forward1 is the target entries with the same flag bits and forward2 otherwise 248 val differentFlag = deqPtrExt(0).flag =/= io.forward(i).sqIdx.flag 249 val forwardMask = io.forward(i).sqIdxMask 250 val storeWritebackedVec = WireInit(VecInit(Seq.fill(StoreQueueSize)(false.B))) 251 for (j <- 0 until StoreQueueSize) { 252 storeWritebackedVec(j) := datavalid(j) && allocated(j) // all datavalid terms need to be checked 253 } 254 val needForward1 = Mux(differentFlag, ~deqMask, deqMask ^ forwardMask) & storeWritebackedVec.asUInt 255 val needForward2 = Mux(differentFlag, forwardMask, 0.U(StoreQueueSize.W)) & storeWritebackedVec.asUInt 256 257 XSDebug(p"$i f1 ${Binary(needForward1)} f2 ${Binary(needForward2)} " + 258 p"sqIdx ${io.forward(i).sqIdx} pa ${Hexadecimal(io.forward(i).paddr)}\n" 259 ) 260 261 // do real fwd query 262 dataModule.io.needForward(i)(0) := needForward1 & paddrModule.io.forwardMmask(i).asUInt 263 dataModule.io.needForward(i)(1) := needForward2 & paddrModule.io.forwardMmask(i).asUInt 264 265 paddrModule.io.forwardMdata(i) := io.forward(i).paddr 266 267 io.forward(i).forwardMask := dataModule.io.forwardMask(i) 268 io.forward(i).forwardData := dataModule.io.forwardData(i) 269 } 270 271 /** 272 * Memory mapped IO / other uncached operations 273 * 274 * States: 275 * (1) writeback from store units: mark as pending 276 * (2) when they reach ROB's head, they can be sent to uncache channel 277 * (3) response from uncache channel: mark as datavalid 278 * (4) writeback to ROB (and other units): mark as writebacked 279 * (5) ROB commits the instruction: same as normal instructions 280 */ 281 //(2) when they reach ROB's head, they can be sent to uncache channel 282 val s_idle :: s_req :: s_resp :: s_wb :: s_wait :: Nil = Enum(5) 283 val uncacheState = RegInit(s_idle) 284 switch(uncacheState) { 285 is(s_idle) { 286 when(io.roq.pendingst && pending(deqPtr) && allocated(deqPtr)) { 287 uncacheState := s_req 288 } 289 } 290 is(s_req) { 291 when(io.uncache.req.fire()) { 292 uncacheState := s_resp 293 } 294 } 295 is(s_resp) { 296 when(io.uncache.resp.fire()) { 297 uncacheState := s_wb 298 } 299 } 300 is(s_wb) { 301 when (io.mmioStout.fire()) { 302 uncacheState := s_wait 303 } 304 } 305 is(s_wait) { 306 when(io.roq.commit) { 307 uncacheState := s_idle // ready for next mmio 308 } 309 } 310 } 311 io.uncache.req.valid := uncacheState === s_req 312 313 io.uncache.req.bits.cmd := MemoryOpConstants.M_XWR 314 io.uncache.req.bits.addr := paddrModule.io.rdata(0) // data(deqPtr) -> rdata(0) 315 io.uncache.req.bits.data := dataModule.io.rdata(0).data 316 io.uncache.req.bits.mask := dataModule.io.rdata(0).mask 317 318 io.uncache.req.bits.id := DontCare 319 320 when(io.uncache.req.fire()){ 321 pending(deqPtr) := false.B 322 323 XSDebug( 324 p"uncache req: pc ${Hexadecimal(uop(deqPtr).cf.pc)} " + 325 p"addr ${Hexadecimal(io.uncache.req.bits.addr)} " + 326 p"data ${Hexadecimal(io.uncache.req.bits.data)} " + 327 p"op ${Hexadecimal(io.uncache.req.bits.cmd)} " + 328 p"mask ${Hexadecimal(io.uncache.req.bits.mask)}\n" 329 ) 330 } 331 332 // (3) response from uncache channel: mark as datavalid 333 io.uncache.resp.ready := true.B 334 when (io.uncache.resp.fire()) { 335 datavalid(deqPtr) := true.B 336 } 337 338 // (4) writeback to ROB (and other units): mark as writebacked 339 io.mmioStout.valid := uncacheState === s_wb // allocated(deqPtr) && datavalid(deqPtr) && !writebacked(deqPtr) 340 io.mmioStout.bits.uop := uop(deqPtr) 341 io.mmioStout.bits.uop.sqIdx := deqPtrExt(0) 342 io.mmioStout.bits.data := dataModule.io.rdata(0).data // dataModule.io.rdata.read(deqPtr) 343 io.mmioStout.bits.redirectValid := false.B 344 io.mmioStout.bits.redirect := DontCare 345 io.mmioStout.bits.debug.isMMIO := true.B 346 io.mmioStout.bits.debug.paddr := DontCare 347 io.mmioStout.bits.debug.isPerfCnt := false.B 348 io.mmioStout.bits.fflags := DontCare 349 when (io.mmioStout.fire()) { 350 writebacked(deqPtr) := true.B 351 allocated(deqPtr) := false.B 352 } 353 354 /** 355 * ROB commits store instructions (mark them as commited) 356 * 357 * (1) When store commits, mark it as commited. 358 * (2) They will not be cancelled and can be sent to lower level. 359 */ 360 for (i <- 0 until CommitWidth) { 361 when (commitCount > i.U) { 362 commited(cmtPtrExt(i).value) := true.B 363 } 364 } 365 cmtPtrExt := cmtPtrExt.map(_ + commitCount) 366 367 // Commited stores will not be cancelled and can be sent to lower level. 368 // remove retired insts from sq, add retired store to sbuffer 369 for (i <- 0 until StorePipelineWidth) { 370 // We use RegNext to prepare data for sbuffer 371 val ptr = deqPtrExt(i).value 372 // if !sbuffer.fire(), read the same ptr 373 // if sbuffer.fire(), read next 374 io.sbuffer(i).valid := allocated(ptr) && commited(ptr) && !mmio(ptr) 375 io.sbuffer(i).bits.cmd := MemoryOpConstants.M_XWR 376 io.sbuffer(i).bits.addr := paddrModule.io.rdata(i) 377 io.sbuffer(i).bits.data := dataModule.io.rdata(i).data 378 io.sbuffer(i).bits.mask := dataModule.io.rdata(i).mask 379 io.sbuffer(i).bits.id := DontCare 380 381 when (io.sbuffer(i).fire()) { 382 allocated(ptr) := false.B 383 XSDebug("sbuffer "+i+" fire: ptr %d\n", ptr) 384 } 385 } 386 when (io.sbuffer(1).fire()) { 387 assert(io.sbuffer(0).fire()) 388 } 389 390 val storeCommit = PopCount(io.sbuffer.map(_.fire())) 391 val waddr = VecInit(io.sbuffer.map(req => SignExt(req.bits.addr, 64))) 392 val wdata = VecInit(io.sbuffer.map(req => req.bits.data & MaskExpand(req.bits.mask))) 393 val wmask = VecInit(io.sbuffer.map(_.bits.mask)) 394 395 if (!env.FPGAPlatform) { 396 difftestIO.storeCommit := RegNext(storeCommit) 397 difftestIO.storeAddr := RegNext(waddr) 398 difftestIO.storeData := RegNext(wdata) 399 difftestIO.storeMask := RegNext(wmask) 400 } 401 402 // Read vaddr for mem exception 403 io.exceptionAddr.vaddr := vaddrModule.io.rdata(0) 404 405 // misprediction recovery / exception redirect 406 // invalidate sq term using robIdx 407 val needCancel = Wire(Vec(StoreQueueSize, Bool())) 408 for (i <- 0 until StoreQueueSize) { 409 needCancel(i) := uop(i).roqIdx.needFlush(io.brqRedirect, io.flush) && allocated(i) && !commited(i) 410 when (needCancel(i)) { 411 allocated(i) := false.B 412 } 413 } 414 415 /** 416 * update pointers 417 */ 418 val lastCycleRedirect = RegNext(io.brqRedirect.valid) 419 val lastCycleFlush = RegNext(io.flush) 420 val lastCycleCancelCount = PopCount(RegNext(needCancel)) 421 // when io.brqRedirect.valid, we don't allow eneuque even though it may fire. 422 val enqNumber = Mux(io.enq.canAccept && io.enq.lqCanAccept && !(io.brqRedirect.valid || io.flush), PopCount(io.enq.req.map(_.valid)), 0.U) 423 when (lastCycleRedirect || lastCycleFlush) { 424 // we recover the pointers in the next cycle after redirect 425 enqPtrExt := VecInit(enqPtrExt.map(_ - lastCycleCancelCount)) 426 }.otherwise { 427 enqPtrExt := VecInit(enqPtrExt.map(_ + enqNumber)) 428 } 429 430 deqPtrExt := deqPtrExtNext 431 432 val dequeueCount = Mux(io.sbuffer(1).fire(), 2.U, Mux(io.sbuffer(0).fire() || io.mmioStout.fire(), 1.U, 0.U)) 433 val validCount = distanceBetween(enqPtrExt(0), deqPtrExt(0)) 434 435 allowEnqueue := validCount + enqNumber <= (StoreQueueSize - RenameWidth).U 436 437 // io.sqempty will be used by sbuffer 438 // We delay it for 1 cycle for better timing 439 // When sbuffer need to check if it is empty, the pipeline is blocked, which means delay io.sqempty 440 // for 1 cycle will also promise that sq is empty in that cycle 441 io.sqempty := RegNext(enqPtrExt(0).value === deqPtrExt(0).value && enqPtrExt(0).flag === deqPtrExt(0).flag) 442 443 // perf counter 444 XSPerf("utilization", validCount) 445 XSPerf("full", !allowEnqueue) 446 XSPerf("mmioCycle", uncacheState =/= s_idle) // lq is busy dealing with uncache req 447 XSPerf("mmioCnt", io.uncache.req.fire()) 448 XSPerf("writeback", io.mmioStout.fire()) 449 XSPerf("wbBlocked", io.mmioStout.valid && !io.mmioStout.ready) 450 XSPerf("validEntryCnt", distanceBetween(enqPtrExt(0), deqPtrExt(0))) 451 XSPerf("cmtEntryCnt", distanceBetween(cmtPtrExt(0), deqPtrExt(0))) 452 XSPerf("nCmtEntryCnt", distanceBetween(enqPtrExt(0), cmtPtrExt(0))) 453 454 // debug info 455 XSDebug("enqPtrExt %d:%d deqPtrExt %d:%d\n", enqPtrExt(0).flag, enqPtr, deqPtrExt(0).flag, deqPtr) 456 457 def PrintFlag(flag: Bool, name: String): Unit = { 458 when(flag) { 459 XSDebug(false, true.B, name) 460 }.otherwise { 461 XSDebug(false, true.B, " ") 462 } 463 } 464 465 for (i <- 0 until StoreQueueSize) { 466 if (i % 4 == 0) XSDebug("") 467 XSDebug(false, true.B, "%x ", uop(i).cf.pc) 468 PrintFlag(allocated(i), "a") 469 PrintFlag(allocated(i) && datavalid(i), "v") 470 PrintFlag(allocated(i) && writebacked(i), "w") 471 PrintFlag(allocated(i) && commited(i), "c") 472 PrintFlag(allocated(i) && pending(i), "p") 473 XSDebug(false, true.B, " ") 474 if (i % 4 == 3 || i == StoreQueueSize - 1) XSDebug(false, true.B, "\n") 475 } 476 477} 478