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.RoqPtr 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 = Input(Valid(new Redirect)) 37 val storeIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle))) 38 val sbuffer = Vec(StorePipelineWidth, Decoupled(new DCacheWordReq)) 39 val mmioStout = DecoupledIO(new ExuOutput) // writeback uncached store 40 val forward = Vec(LoadPipelineWidth, Flipped(new LoadForwardQueryIO)) 41 val commits = Flipped(new RoqCommitIO) 42 val uncache = new DCacheWordIO 43 val roqDeqPtr = Input(new RoqPtr) 44 // val refill = Flipped(Valid(new DCacheLineReq )) 45 val exceptionAddr = new ExceptionAddrIO 46 }) 47 48 // data modules 49 val uop = Reg(Vec(StoreQueueSize, new MicroOp)) 50 // val data = Reg(Vec(StoreQueueSize, new LsqEntry)) 51 val dataModule = Module(new StoreQueueData(StoreQueueSize, numRead = StorePipelineWidth, numWrite = StorePipelineWidth, numForward = StorePipelineWidth)) 52 dataModule.io := DontCare 53 val vaddrModule = Module(new AsyncDataModuleTemplate(UInt(VAddrBits.W), StoreQueueSize, numRead = 1, numWrite = StorePipelineWidth)) 54 vaddrModule.io := DontCare 55 val exceptionModule = Module(new AsyncDataModuleTemplate(UInt(16.W), StoreQueueSize, numRead = StorePipelineWidth, numWrite = StorePipelineWidth)) 56 exceptionModule.io := DontCare 57 58 // state & misc 59 val allocated = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // sq entry has been allocated 60 val datavalid = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // non-mmio data is valid 61 val writebacked = RegInit(VecInit(List.fill(StoreQueueSize)(false.B))) // inst has been writebacked to CDB 62 val commited = Reg(Vec(StoreQueueSize, Bool())) // inst has been commited by roq 63 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 64 val mmio = Reg(Vec(StoreQueueSize, Bool())) // mmio: inst is an mmio inst 65 66 // ptr 67 require(StoreQueueSize > RenameWidth) 68 val enqPtrExt = RegInit(VecInit((0 until RenameWidth).map(_.U.asTypeOf(new SqPtr)))) 69 val deqPtrExt = RegInit(VecInit((0 until StorePipelineWidth).map(_.U.asTypeOf(new SqPtr)))) 70 val validCounter = RegInit(0.U(log2Ceil(LoadQueueSize + 1).W)) 71 val allowEnqueue = RegInit(true.B) 72 73 val enqPtr = enqPtrExt(0).value 74 val deqPtr = deqPtrExt(0).value 75 76 val tailMask = UIntToMask(deqPtr, StoreQueueSize) 77 val headMask = UIntToMask(enqPtr, StoreQueueSize) 78 79 // Read dataModule 80 // deqPtr and deqPtr+1 entry will be read from dataModule 81 val dataModuleRead = dataModule.io.rdata 82 for (i <- 0 until StorePipelineWidth) { 83 dataModule.io.raddr(i) := deqPtrExt(i).value 84 } 85 vaddrModule.io.raddr(0) := io.exceptionAddr.lsIdx.sqIdx.value 86 exceptionModule.io.raddr(0) := deqPtr // read exception 87 88 /** 89 * Enqueue at dispatch 90 * 91 * Currently, StoreQueue only allows enqueue when #emptyEntries > RenameWidth(EnqWidth) 92 */ 93 io.enq.canAccept := allowEnqueue 94 for (i <- 0 until RenameWidth) { 95 val offset = if (i == 0) 0.U else PopCount(io.enq.needAlloc.take(i)) 96 val sqIdx = enqPtrExt(offset) 97 val index = sqIdx.value 98 when (io.enq.req(i).valid && io.enq.canAccept && io.enq.lqCanAccept && !io.brqRedirect.valid) { 99 uop(index) := io.enq.req(i).bits 100 allocated(index) := true.B 101 datavalid(index) := false.B 102 writebacked(index) := false.B 103 commited(index) := false.B 104 pending(index) := false.B 105 } 106 io.enq.resp(i) := sqIdx 107 } 108 XSDebug(p"(ready, valid): ${io.enq.canAccept}, ${Binary(Cat(io.enq.req.map(_.valid)))}\n") 109 110 /** 111 * Writeback store from store units 112 * 113 * Most store instructions writeback to regfile in the previous cycle. 114 * However, 115 * (1) For an mmio instruction with exceptions, we need to mark it as datavalid 116 * (in this way it will trigger an exception when it reaches ROB's head) 117 * instead of pending to avoid sending them to lower level. 118 * (2) For an mmio instruction without exceptions, we mark it as pending. 119 * When the instruction reaches ROB's head, StoreQueue sends it to uncache channel. 120 * Upon receiving the response, StoreQueue writes back the instruction 121 * through arbiter with store units. It will later commit as normal. 122 */ 123 for (i <- 0 until StorePipelineWidth) { 124 dataModule.io.wen(i) := false.B 125 vaddrModule.io.wen(i) := false.B 126 exceptionModule.io.wen(i) := false.B 127 when(io.storeIn(i).fire()) { 128 val stWbIndex = io.storeIn(i).bits.uop.sqIdx.value 129 val hasException = io.storeIn(i).bits.uop.cf.exceptionVec.asUInt.orR 130 val hasWritebacked = !io.storeIn(i).bits.mmio || hasException 131 datavalid(stWbIndex) := hasWritebacked 132 writebacked(stWbIndex) := hasWritebacked 133 pending(stWbIndex) := !hasWritebacked // valid mmio require 134 135 val storeWbData = Wire(new SQDataEntry) 136 storeWbData := DontCare 137 storeWbData.paddr := io.storeIn(i).bits.paddr 138 storeWbData.mask := io.storeIn(i).bits.mask 139 storeWbData.data := io.storeIn(i).bits.data 140 dataModule.io.waddr(i) := stWbIndex 141 dataModule.io.wdata(i) := storeWbData 142 dataModule.io.wen(i) := true.B 143 144 vaddrModule.io.waddr(i) := stWbIndex 145 vaddrModule.io.wdata(i) := io.storeIn(i).bits.vaddr 146 vaddrModule.io.wen(i) := true.B 147 148 exceptionModule.io.waddr(i) := stWbIndex 149 exceptionModule.io.wdata(i) := io.storeIn(i).bits.uop.cf.exceptionVec.asUInt 150 exceptionModule.io.wen(i) := true.B 151 152 mmio(stWbIndex) := io.storeIn(i).bits.mmio 153 154 XSInfo("store write to sq idx %d pc 0x%x vaddr %x paddr %x data %x mmio %x roll %x exc %x\n", 155 io.storeIn(i).bits.uop.sqIdx.value, 156 io.storeIn(i).bits.uop.cf.pc, 157 io.storeIn(i).bits.vaddr, 158 io.storeIn(i).bits.paddr, 159 io.storeIn(i).bits.data, 160 io.storeIn(i).bits.mmio, 161 io.storeIn(i).bits.rollback, 162 io.storeIn(i).bits.uop.cf.exceptionVec.asUInt 163 ) 164 } 165 } 166 167 /** 168 * load forward query 169 * 170 * Check store queue for instructions that is older than the load. 171 * The response will be valid at the next cycle after req. 172 */ 173 // check over all lq entries and forward data from the first matched store 174 for (i <- 0 until LoadPipelineWidth) { 175 io.forward(i).forwardMask := 0.U(8.W).asBools 176 io.forward(i).forwardData := DontCare 177 178 // Compare deqPtr (deqPtr) and forward.sqIdx, we have two cases: 179 // (1) if they have the same flag, we need to check range(tail, sqIdx) 180 // (2) if they have different flags, we need to check range(tail, LoadQueueSize) and range(0, sqIdx) 181 // Forward1: Mux(same_flag, range(tail, sqIdx), range(tail, LoadQueueSize)) 182 // Forward2: Mux(same_flag, 0.U, range(0, sqIdx) ) 183 // i.e. forward1 is the target entries with the same flag bits and forward2 otherwise 184 val differentFlag = deqPtrExt(0).flag =/= io.forward(i).sqIdx.flag 185 val forwardMask = UIntToMask(io.forward(i).sqIdx.value, StoreQueueSize) 186 val storeWritebackedVec = WireInit(VecInit(Seq.fill(StoreQueueSize)(false.B))) 187 for (j <- 0 until StoreQueueSize) { 188 storeWritebackedVec(j) := datavalid(j) && allocated(j) // all datavalid terms need to be checked 189 } 190 val needForward1 = Mux(differentFlag, ~tailMask, tailMask ^ forwardMask) & storeWritebackedVec.asUInt 191 val needForward2 = Mux(differentFlag, forwardMask, 0.U(StoreQueueSize.W)) & storeWritebackedVec.asUInt 192 193 XSDebug(p"$i f1 ${Binary(needForward1)} f2 ${Binary(needForward2)} " + 194 p"sqIdx ${io.forward(i).sqIdx} pa ${Hexadecimal(io.forward(i).paddr)}\n" 195 ) 196 197 // do real fwd query 198 dataModule.io.forwardQuery( 199 numForward = i, 200 paddr = io.forward(i).paddr, 201 needForward1 = needForward1, 202 needForward2 = needForward2 203 ) 204 205 io.forward(i).forwardMask := dataModule.io.forward(i).forwardMask 206 io.forward(i).forwardData := dataModule.io.forward(i).forwardData 207 } 208 209 /** 210 * Memory mapped IO / other uncached operations 211 * 212 * States: 213 * (1) writeback from store units: mark as pending 214 * (2) when they reach ROB's head, they can be sent to uncache channel 215 * (3) response from uncache channel: mark as datavalid 216 * (4) writeback to ROB (and other units): mark as writebacked 217 * (5) ROB commits the instruction: same as normal instructions 218 */ 219 //(2) when they reach ROB's head, they can be sent to uncache channel 220 io.uncache.req.valid := pending(deqPtr) && allocated(deqPtr) && 221 io.commits.info(0).commitType === CommitType.STORE && 222 io.roqDeqPtr === uop(deqPtr).roqIdx && 223 !io.commits.isWalk 224 225 io.uncache.req.bits.cmd := MemoryOpConstants.M_XWR 226 io.uncache.req.bits.addr := dataModule.io.rdata(0).paddr // data(deqPtr) -> rdata(0) 227 io.uncache.req.bits.data := dataModule.io.rdata(0).data 228 io.uncache.req.bits.mask := dataModule.io.rdata(0).mask 229 230 io.uncache.req.bits.meta.id := DontCare 231 io.uncache.req.bits.meta.vaddr := DontCare 232 io.uncache.req.bits.meta.paddr := dataModule.io.rdata(0).paddr 233 io.uncache.req.bits.meta.uop := uop(deqPtr) 234 io.uncache.req.bits.meta.mmio := true.B 235 io.uncache.req.bits.meta.tlb_miss := false.B 236 io.uncache.req.bits.meta.mask := dataModule.io.rdata(0).mask 237 io.uncache.req.bits.meta.replay := false.B 238 239 when(io.uncache.req.fire()){ 240 pending(deqPtr) := false.B 241 242 XSDebug( 243 p"uncache req: pc ${Hexadecimal(uop(deqPtr).cf.pc)} " + 244 p"addr ${Hexadecimal(io.uncache.req.bits.addr)} " + 245 p"data ${Hexadecimal(io.uncache.req.bits.data)} " + 246 p"op ${Hexadecimal(io.uncache.req.bits.cmd)} " + 247 p"mask ${Hexadecimal(io.uncache.req.bits.mask)}\n" 248 ) 249 } 250 251 // (3) response from uncache channel: mark as datavalid 252 io.uncache.resp.ready := true.B 253 when (io.uncache.resp.fire()) { 254 datavalid(deqPtr) := true.B 255 } 256 257 // (4) writeback to ROB (and other units): mark as writebacked 258 io.mmioStout.valid := allocated(deqPtr) && datavalid(deqPtr) && !writebacked(deqPtr) 259 io.mmioStout.bits.uop := uop(deqPtr) 260 io.mmioStout.bits.uop.sqIdx := deqPtrExt(0) 261 io.mmioStout.bits.uop.cf.exceptionVec := exceptionModule.io.rdata(0).asBools 262 io.mmioStout.bits.data := dataModuleRead(0).data // dataModuleRead.read(deqPtr) 263 io.mmioStout.bits.redirectValid := false.B 264 io.mmioStout.bits.redirect := DontCare 265 io.mmioStout.bits.brUpdate := DontCare 266 io.mmioStout.bits.debug.isMMIO := true.B 267 io.mmioStout.bits.debug.isPerfCnt := false.B 268 io.mmioStout.bits.fflags := DontCare 269 when (io.mmioStout.fire()) { 270 writebacked(deqPtr) := true.B 271 allocated(deqPtr) := false.B 272 } 273 274 /** 275 * ROB commits store instructions (mark them as commited) 276 * 277 * (1) When store commits, mark it as commited. 278 * (2) They will not be cancelled and can be sent to lower level. 279 */ 280 for (i <- 0 until CommitWidth) { 281 val storeCommit = !io.commits.isWalk && io.commits.valid(i) && io.commits.info(i).commitType === CommitType.STORE 282 when (storeCommit) { 283 commited(io.commits.info(i).sqIdx.value) := true.B 284 XSDebug("store commit %d: idx %d\n", i.U, io.commits.info(i).sqIdx.value) 285 } 286 } 287 288 // Commited stores will not be cancelled and can be sent to lower level. 289 // remove retired insts from sq, add retired store to sbuffer 290 for (i <- 0 until StorePipelineWidth) { 291 val ptr = deqPtrExt(i).value 292 val ismmio = mmio(ptr) 293 io.sbuffer(i).valid := allocated(ptr) && commited(ptr) && !ismmio 294 io.sbuffer(i).bits.cmd := MemoryOpConstants.M_XWR 295 io.sbuffer(i).bits.addr := dataModuleRead(i).paddr 296 io.sbuffer(i).bits.data := dataModuleRead(i).data 297 io.sbuffer(i).bits.mask := dataModuleRead(i).mask 298 io.sbuffer(i).bits.meta := DontCare 299 io.sbuffer(i).bits.meta.tlb_miss := false.B 300 io.sbuffer(i).bits.meta.uop := DontCare 301 io.sbuffer(i).bits.meta.mmio := false.B 302 io.sbuffer(i).bits.meta.mask := dataModuleRead(i).mask 303 304 when (io.sbuffer(i).fire()) { 305 allocated(ptr) := false.B 306 XSDebug("sbuffer "+i+" fire: ptr %d\n", ptr) 307 } 308 } 309 when (io.sbuffer(1).fire()) { 310 assert(io.sbuffer(0).fire()) 311 } 312 313 if (!env.FPGAPlatform) { 314 val storeCommit = PopCount(io.sbuffer.map(_.fire())) 315 val waddr = VecInit(io.sbuffer.map(req => SignExt(req.bits.addr, 64))) 316 val wdata = VecInit(io.sbuffer.map(req => req.bits.data & MaskExpand(req.bits.mask))) 317 val wmask = VecInit(io.sbuffer.map(_.bits.mask)) 318 319 ExcitingUtils.addSource(RegNext(storeCommit), "difftestStoreCommit", ExcitingUtils.Debug) 320 ExcitingUtils.addSource(RegNext(waddr), "difftestStoreAddr", ExcitingUtils.Debug) 321 ExcitingUtils.addSource(RegNext(wdata), "difftestStoreData", ExcitingUtils.Debug) 322 ExcitingUtils.addSource(RegNext(wmask), "difftestStoreMask", ExcitingUtils.Debug) 323 } 324 325 // Read vaddr for mem exception 326 io.exceptionAddr.vaddr := vaddrModule.io.rdata(0) 327 328 // misprediction recovery / exception redirect 329 // invalidate sq term using robIdx 330 val needCancel = Wire(Vec(StoreQueueSize, Bool())) 331 for (i <- 0 until StoreQueueSize) { 332 needCancel(i) := uop(i).roqIdx.needFlush(io.brqRedirect) && allocated(i) && !commited(i) 333 when (needCancel(i)) { 334 allocated(i) := false.B 335 } 336 } 337 338 /** 339 * update pointers 340 */ 341 val lastCycleRedirect = RegNext(io.brqRedirect.valid) 342 val lastCycleCancelCount = PopCount(RegNext(needCancel)) 343 // when io.brqRedirect.valid, we don't allow eneuque even though it may fire. 344 val enqNumber = Mux(io.enq.canAccept && io.enq.lqCanAccept && !io.brqRedirect.valid, PopCount(io.enq.req.map(_.valid)), 0.U) 345 when (lastCycleRedirect) { 346 // we recover the pointers in the next cycle after redirect 347 enqPtrExt := VecInit(enqPtrExt.map(_ - lastCycleCancelCount)) 348 }.otherwise { 349 enqPtrExt := VecInit(enqPtrExt.map(_ + enqNumber)) 350 } 351 352 deqPtrExt := Mux(io.sbuffer(1).fire(), 353 VecInit(deqPtrExt.map(_ + 2.U)), 354 Mux(io.sbuffer(0).fire() || io.mmioStout.fire(), 355 VecInit(deqPtrExt.map(_ + 1.U)), 356 deqPtrExt 357 ) 358 ) 359 360 val lastLastCycleRedirect = RegNext(lastCycleRedirect) 361 val dequeueCount = Mux(io.sbuffer(1).fire(), 2.U, Mux(io.sbuffer(0).fire() || io.mmioStout.fire(), 1.U, 0.U)) 362 val trueValidCounter = distanceBetween(enqPtrExt(0), deqPtrExt(0)) 363 validCounter := Mux(lastLastCycleRedirect, 364 trueValidCounter - dequeueCount, 365 validCounter + enqNumber - dequeueCount 366 ) 367 368 allowEnqueue := Mux(io.brqRedirect.valid, 369 false.B, 370 Mux(lastLastCycleRedirect, 371 trueValidCounter <= (StoreQueueSize - RenameWidth).U, 372 validCounter + enqNumber <= (StoreQueueSize - RenameWidth).U 373 ) 374 ) 375 376 // debug info 377 XSDebug("enqPtrExt %d:%d deqPtrExt %d:%d\n", enqPtrExt(0).flag, enqPtr, deqPtrExt(0).flag, deqPtr) 378 379 def PrintFlag(flag: Bool, name: String): Unit = { 380 when(flag) { 381 XSDebug(false, true.B, name) 382 }.otherwise { 383 XSDebug(false, true.B, " ") 384 } 385 } 386 387 for (i <- 0 until StoreQueueSize) { 388 if (i % 4 == 0) XSDebug("") 389 XSDebug(false, true.B, "%x [%x] ", uop(i).cf.pc, dataModule.io.debug(i).paddr) 390 PrintFlag(allocated(i), "a") 391 PrintFlag(allocated(i) && datavalid(i), "v") 392 PrintFlag(allocated(i) && writebacked(i), "w") 393 PrintFlag(allocated(i) && commited(i), "c") 394 PrintFlag(allocated(i) && pending(i), "p") 395 XSDebug(false, true.B, " ") 396 if (i % 4 == 3 || i == StoreQueueSize - 1) XSDebug(false, true.B, "\n") 397 } 398 399} 400