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 utils._ 23import xiangshan._ 24import xiangshan.cache._ 25import xiangshan.cache.{DCacheLineIO, DCacheWordIO, MemoryOpConstants} 26import xiangshan.cache.mmu.TlbRequestIO 27import xiangshan.mem._ 28import xiangshan.backend.rob.RobLsqIO 29import xiangshan.backend.fu.HasExceptionNO 30import xiangshan.frontend.FtqPtr 31import xiangshan.backend.fu.fpu.FPU 32 33 34class LqPtr(implicit p: Parameters) extends CircularQueuePtr[LqPtr]( 35 p => p(XSCoreParamsKey).LoadQueueSize 36){ 37 override def cloneType = (new LqPtr).asInstanceOf[this.type] 38} 39 40object LqPtr { 41 def apply(f: Bool, v: UInt)(implicit p: Parameters): LqPtr = { 42 val ptr = Wire(new LqPtr) 43 ptr.flag := f 44 ptr.value := v 45 ptr 46 } 47} 48 49trait HasLoadHelper { this: XSModule => 50 def rdataHelper(uop: MicroOp, rdata: UInt): UInt = { 51 val fpWen = uop.ctrl.fpWen 52 LookupTree(uop.ctrl.fuOpType, List( 53 LSUOpType.lb -> SignExt(rdata(7, 0) , XLEN), 54 LSUOpType.lh -> SignExt(rdata(15, 0), XLEN), 55 /* 56 riscv-spec-20191213: 12.2 NaN Boxing of Narrower Values 57 Any operation that writes a narrower result to an f register must write 58 all 1s to the uppermost FLEN−n bits to yield a legal NaN-boxed value. 59 */ 60 LSUOpType.lw -> Mux(fpWen, FPU.box(rdata, FPU.S), SignExt(rdata(31, 0), XLEN)), 61 LSUOpType.ld -> Mux(fpWen, FPU.box(rdata, FPU.D), SignExt(rdata(63, 0), XLEN)), 62 LSUOpType.lbu -> ZeroExt(rdata(7, 0) , XLEN), 63 LSUOpType.lhu -> ZeroExt(rdata(15, 0), XLEN), 64 LSUOpType.lwu -> ZeroExt(rdata(31, 0), XLEN), 65 )) 66 } 67} 68 69class LqEnqIO(implicit p: Parameters) extends XSBundle { 70 val canAccept = Output(Bool()) 71 val sqCanAccept = Input(Bool()) 72 val needAlloc = Vec(exuParameters.LsExuCnt, Input(Bool())) 73 val req = Vec(exuParameters.LsExuCnt, Flipped(ValidIO(new MicroOp))) 74 val resp = Vec(exuParameters.LsExuCnt, Output(new LqPtr)) 75} 76 77// Load Queue 78class LoadQueue(implicit p: Parameters) extends XSModule 79 with HasDCacheParameters 80 with HasCircularQueuePtrHelper 81 with HasLoadHelper 82 with HasExceptionNO 83{ 84 val io = IO(new Bundle() { 85 val enq = new LqEnqIO 86 val brqRedirect = Flipped(ValidIO(new Redirect)) 87 val loadIn = Vec(LoadPipelineWidth, Flipped(Valid(new LsPipelineBundle))) 88 val storeIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle))) 89 val loadDataForwarded = Vec(LoadPipelineWidth, Input(Bool())) 90 val needReplayFromRS = Vec(LoadPipelineWidth, Input(Bool())) 91 val ldout = Vec(2, DecoupledIO(new ExuOutput)) // writeback int load 92 val load_s1 = Vec(LoadPipelineWidth, Flipped(new PipeLoadForwardQueryIO)) // TODO: to be renamed 93 val loadViolationQuery = Vec(LoadPipelineWidth, Flipped(new LoadViolationQueryIO)) 94 val rob = Flipped(new RobLsqIO) 95 val rollback = Output(Valid(new Redirect)) // replay now starts from load instead of store 96 val dcache = Flipped(ValidIO(new Refill)) // TODO: to be renamed 97 val release = Flipped(ValidIO(new Release)) 98 val uncache = new DCacheWordIO 99 val exceptionAddr = new ExceptionAddrIO 100 val lqFull = Output(Bool()) 101 }) 102 103 println("LoadQueue: size:" + LoadQueueSize) 104 105 val uop = Reg(Vec(LoadQueueSize, new MicroOp)) 106 // val data = Reg(Vec(LoadQueueSize, new LsRobEntry)) 107 val dataModule = Module(new LoadQueueData(LoadQueueSize, wbNumRead = LoadPipelineWidth, wbNumWrite = LoadPipelineWidth)) 108 dataModule.io := DontCare 109 val vaddrModule = Module(new SyncDataModuleTemplate(UInt(VAddrBits.W), LoadQueueSize, numRead = 1, numWrite = LoadPipelineWidth)) 110 vaddrModule.io := DontCare 111 val allocated = RegInit(VecInit(List.fill(LoadQueueSize)(false.B))) // lq entry has been allocated 112 val datavalid = RegInit(VecInit(List.fill(LoadQueueSize)(false.B))) // data is valid 113 val writebacked = RegInit(VecInit(List.fill(LoadQueueSize)(false.B))) // inst has been writebacked to CDB 114 val released = RegInit(VecInit(List.fill(LoadQueueSize)(false.B))) // load data has been released by dcache 115 val miss = Reg(Vec(LoadQueueSize, Bool())) // load inst missed, waiting for miss queue to accept miss request 116 // val listening = Reg(Vec(LoadQueueSize, Bool())) // waiting for refill result 117 val pending = Reg(Vec(LoadQueueSize, Bool())) // mmio pending: inst is an mmio inst, it will not be executed until it reachs the end of rob 118 val refilling = WireInit(VecInit(List.fill(LoadQueueSize)(false.B))) // inst has been writebacked to CDB 119 120 val debug_mmio = Reg(Vec(LoadQueueSize, Bool())) // mmio: inst is an mmio inst 121 val debug_paddr = Reg(Vec(LoadQueueSize, UInt(PAddrBits.W))) // mmio: inst is an mmio inst 122 123 val enqPtrExt = RegInit(VecInit((0 until io.enq.req.length).map(_.U.asTypeOf(new LqPtr)))) 124 val deqPtrExt = RegInit(0.U.asTypeOf(new LqPtr)) 125 val deqPtrExtNext = Wire(new LqPtr) 126 val allowEnqueue = RegInit(true.B) 127 128 val enqPtr = enqPtrExt(0).value 129 val deqPtr = deqPtrExt.value 130 131 val deqMask = UIntToMask(deqPtr, LoadQueueSize) 132 val enqMask = UIntToMask(enqPtr, LoadQueueSize) 133 134 val commitCount = RegNext(io.rob.lcommit) 135 136 /** 137 * Enqueue at dispatch 138 * 139 * Currently, LoadQueue only allows enqueue when #emptyEntries > EnqWidth 140 */ 141 io.enq.canAccept := allowEnqueue 142 143 for (i <- 0 until io.enq.req.length) { 144 val offset = if (i == 0) 0.U else PopCount(io.enq.needAlloc.take(i)) 145 val lqIdx = enqPtrExt(offset) 146 val index = lqIdx.value 147 when (io.enq.req(i).valid && io.enq.canAccept && io.enq.sqCanAccept && !io.brqRedirect.valid) { 148 uop(index) := io.enq.req(i).bits 149 allocated(index) := true.B 150 datavalid(index) := false.B 151 writebacked(index) := false.B 152 released(index) := false.B 153 miss(index) := false.B 154 // listening(index) := false.B 155 pending(index) := false.B 156 } 157 io.enq.resp(i) := lqIdx 158 } 159 XSDebug(p"(ready, valid): ${io.enq.canAccept}, ${Binary(Cat(io.enq.req.map(_.valid)))}\n") 160 161 /** 162 * Writeback load from load units 163 * 164 * Most load instructions writeback to regfile at the same time. 165 * However, 166 * (1) For an mmio instruction with exceptions, it writes back to ROB immediately. 167 * (2) For an mmio instruction without exceptions, it does not write back. 168 * The mmio instruction will be sent to lower level when it reaches ROB's head. 169 * After uncache response, it will write back through arbiter with loadUnit. 170 * (3) For cache misses, it is marked miss and sent to dcache later. 171 * After cache refills, it will write back through arbiter with loadUnit. 172 */ 173 for (i <- 0 until LoadPipelineWidth) { 174 dataModule.io.wb.wen(i) := false.B 175 val loadWbIndex = io.loadIn(i).bits.uop.lqIdx.value 176 when(io.loadIn(i).fire()) { 177 when(io.loadIn(i).bits.miss) { 178 XSInfo(io.loadIn(i).valid, "load miss write to lq idx %d pc 0x%x vaddr %x paddr %x data %x mask %x forwardData %x forwardMask: %x mmio %x\n", 179 io.loadIn(i).bits.uop.lqIdx.asUInt, 180 io.loadIn(i).bits.uop.cf.pc, 181 io.loadIn(i).bits.vaddr, 182 io.loadIn(i).bits.paddr, 183 io.loadIn(i).bits.data, 184 io.loadIn(i).bits.mask, 185 io.loadIn(i).bits.forwardData.asUInt, 186 io.loadIn(i).bits.forwardMask.asUInt, 187 io.loadIn(i).bits.mmio 188 ) 189 }.otherwise { 190 XSInfo(io.loadIn(i).valid, "load hit write to cbd lqidx %d pc 0x%x vaddr %x paddr %x data %x mask %x forwardData %x forwardMask: %x mmio %x\n", 191 io.loadIn(i).bits.uop.lqIdx.asUInt, 192 io.loadIn(i).bits.uop.cf.pc, 193 io.loadIn(i).bits.vaddr, 194 io.loadIn(i).bits.paddr, 195 io.loadIn(i).bits.data, 196 io.loadIn(i).bits.mask, 197 io.loadIn(i).bits.forwardData.asUInt, 198 io.loadIn(i).bits.forwardMask.asUInt, 199 io.loadIn(i).bits.mmio 200 )} 201 datavalid(loadWbIndex) := (!io.loadIn(i).bits.miss || io.loadDataForwarded(i)) && 202 !io.loadIn(i).bits.mmio && // mmio data is not valid until we finished uncache access 203 !io.needReplayFromRS(i) // do not writeback if that inst will be resend from rs 204 writebacked(loadWbIndex) := !io.loadIn(i).bits.miss && !io.loadIn(i).bits.mmio 205 206 val loadWbData = Wire(new LQDataEntry) 207 loadWbData.paddr := io.loadIn(i).bits.paddr 208 loadWbData.mask := io.loadIn(i).bits.mask 209 loadWbData.data := io.loadIn(i).bits.forwardData.asUInt // fwd data 210 loadWbData.fwdMask := io.loadIn(i).bits.forwardMask 211 dataModule.io.wbWrite(i, loadWbIndex, loadWbData) 212 dataModule.io.wb.wen(i) := true.B 213 214 215 debug_mmio(loadWbIndex) := io.loadIn(i).bits.mmio 216 debug_paddr(loadWbIndex) := io.loadIn(i).bits.paddr 217 218 val dcacheMissed = io.loadIn(i).bits.miss && !io.loadIn(i).bits.mmio 219 miss(loadWbIndex) := dcacheMissed && !io.loadDataForwarded(i) && !io.needReplayFromRS(i) 220 pending(loadWbIndex) := io.loadIn(i).bits.mmio 221 uop(loadWbIndex).debugInfo := io.loadIn(i).bits.uop.debugInfo 222 // update replayInst (replay from fetch) bit, 223 // for replayInst may be set to true in load pipeline 224 uop(loadWbIndex).ctrl.replayInst := io.loadIn(i).bits.uop.ctrl.replayInst 225 } 226 // vaddrModule write is delayed, as vaddrModule will not be read right after write 227 vaddrModule.io.waddr(i) := RegNext(loadWbIndex) 228 vaddrModule.io.wdata(i) := RegNext(io.loadIn(i).bits.vaddr) 229 vaddrModule.io.wen(i) := RegNext(io.loadIn(i).fire()) 230 } 231 232 when(io.dcache.valid) { 233 XSDebug("miss resp: paddr:0x%x data %x\n", io.dcache.bits.addr, io.dcache.bits.data) 234 } 235 236 // Refill 64 bit in a cycle 237 // Refill data comes back from io.dcache.resp 238 dataModule.io.refill.valid := io.dcache.valid 239 dataModule.io.refill.paddr := io.dcache.bits.addr 240 dataModule.io.refill.data := io.dcache.bits.data 241 242 (0 until LoadQueueSize).map(i => { 243 dataModule.io.refill.refillMask(i) := allocated(i) && miss(i) 244 when(dataModule.io.refill.valid && dataModule.io.refill.refillMask(i) && dataModule.io.refill.matchMask(i)) { 245 datavalid(i) := true.B 246 miss(i) := false.B 247 refilling(i) := true.B 248 } 249 }) 250 251 // Writeback up to 2 missed load insts to CDB 252 // 253 // Pick 2 missed load (data refilled), write them back to cdb 254 // 2 refilled load will be selected from even/odd entry, separately 255 256 // Stage 0 257 // Generate writeback indexes 258 259 def getEvenBits(input: UInt): UInt = { 260 VecInit((0 until LoadQueueSize/2).map(i => {input(2*i)})).asUInt 261 } 262 def getOddBits(input: UInt): UInt = { 263 VecInit((0 until LoadQueueSize/2).map(i => {input(2*i+1)})).asUInt 264 } 265 266 val loadWbSel = Wire(Vec(LoadPipelineWidth, UInt(log2Up(LoadQueueSize).W))) // index selected last cycle 267 val loadWbSelV = Wire(Vec(LoadPipelineWidth, Bool())) // index selected in last cycle is valid 268 269 val loadWbSelVec = VecInit((0 until LoadQueueSize).map(i => { 270 allocated(i) && !writebacked(i) && (datavalid(i) || refilling(i)) 271 })).asUInt() // use uint instead vec to reduce verilog lines 272 val evenDeqMask = getEvenBits(deqMask) 273 val oddDeqMask = getOddBits(deqMask) 274 // generate lastCycleSelect mask 275 val evenSelectMask = Mux(io.ldout(0).fire(), getEvenBits(UIntToOH(loadWbSel(0))), 0.U) 276 val oddSelectMask = Mux(io.ldout(1).fire(), getOddBits(UIntToOH(loadWbSel(1))), 0.U) 277 // generate real select vec 278 val loadEvenSelVec = getEvenBits(loadWbSelVec) & ~evenSelectMask 279 val loadOddSelVec = getOddBits(loadWbSelVec) & ~oddSelectMask 280 281 def toVec(a: UInt): Vec[Bool] = { 282 VecInit(a.asBools) 283 } 284 285 val loadWbSelGen = Wire(Vec(LoadPipelineWidth, UInt(log2Up(LoadQueueSize).W))) 286 val loadWbSelVGen = Wire(Vec(LoadPipelineWidth, Bool())) 287 loadWbSelGen(0) := Cat(getFirstOne(toVec(loadEvenSelVec), evenDeqMask), 0.U(1.W)) 288 loadWbSelVGen(0):= loadEvenSelVec.asUInt.orR 289 loadWbSelGen(1) := Cat(getFirstOne(toVec(loadOddSelVec), oddDeqMask), 1.U(1.W)) 290 loadWbSelVGen(1) := loadOddSelVec.asUInt.orR 291 292 (0 until LoadPipelineWidth).map(i => { 293 loadWbSel(i) := RegNext(loadWbSelGen(i)) 294 loadWbSelV(i) := RegNext(loadWbSelVGen(i), init = false.B) 295 when(io.ldout(i).fire()){ 296 // Mark them as writebacked, so they will not be selected in the next cycle 297 writebacked(loadWbSel(i)) := true.B 298 } 299 }) 300 301 // Stage 1 302 // Use indexes generated in cycle 0 to read data 303 // writeback data to cdb 304 (0 until LoadPipelineWidth).map(i => { 305 // data select 306 dataModule.io.wb.raddr(i) := loadWbSelGen(i) 307 val rdata = dataModule.io.wb.rdata(i).data 308 val seluop = uop(loadWbSel(i)) 309 val func = seluop.ctrl.fuOpType 310 val raddr = dataModule.io.wb.rdata(i).paddr 311 val rdataSel = LookupTree(raddr(2, 0), List( 312 "b000".U -> rdata(63, 0), 313 "b001".U -> rdata(63, 8), 314 "b010".U -> rdata(63, 16), 315 "b011".U -> rdata(63, 24), 316 "b100".U -> rdata(63, 32), 317 "b101".U -> rdata(63, 40), 318 "b110".U -> rdata(63, 48), 319 "b111".U -> rdata(63, 56) 320 )) 321 val rdataPartialLoad = rdataHelper(seluop, rdataSel) 322 323 // writeback missed int/fp load 324 // 325 // Int load writeback will finish (if not blocked) in one cycle 326 io.ldout(i).bits.uop := seluop 327 io.ldout(i).bits.uop.lqIdx := loadWbSel(i).asTypeOf(new LqPtr) 328 io.ldout(i).bits.data := rdataPartialLoad 329 io.ldout(i).bits.redirectValid := false.B 330 io.ldout(i).bits.redirect := DontCare 331 io.ldout(i).bits.debug.isMMIO := debug_mmio(loadWbSel(i)) 332 io.ldout(i).bits.debug.isPerfCnt := false.B 333 io.ldout(i).bits.debug.paddr := debug_paddr(loadWbSel(i)) 334 io.ldout(i).bits.fflags := DontCare 335 io.ldout(i).valid := loadWbSelV(i) 336 337 when(io.ldout(i).fire()) { 338 XSInfo("int load miss write to cbd robidx %d lqidx %d pc 0x%x mmio %x\n", 339 io.ldout(i).bits.uop.robIdx.asUInt, 340 io.ldout(i).bits.uop.lqIdx.asUInt, 341 io.ldout(i).bits.uop.cf.pc, 342 debug_mmio(loadWbSel(i)) 343 ) 344 } 345 346 }) 347 348 /** 349 * Load commits 350 * 351 * When load commited, mark it as !allocated and move deqPtrExt forward. 352 */ 353 (0 until CommitWidth).map(i => { 354 when(commitCount > i.U){ 355 allocated((deqPtrExt+i.U).value) := false.B 356 } 357 }) 358 359 def getFirstOne(mask: Vec[Bool], startMask: UInt) = { 360 val length = mask.length 361 val highBits = (0 until length).map(i => mask(i) & ~startMask(i)) 362 val highBitsUint = Cat(highBits.reverse) 363 PriorityEncoder(Mux(highBitsUint.orR(), highBitsUint, mask.asUInt)) 364 } 365 366 def getOldestInTwo(valid: Seq[Bool], uop: Seq[MicroOp]) = { 367 assert(valid.length == uop.length) 368 assert(valid.length == 2) 369 Mux(valid(0) && valid(1), 370 Mux(isAfter(uop(0).robIdx, uop(1).robIdx), uop(1), uop(0)), 371 Mux(valid(0) && !valid(1), uop(0), uop(1))) 372 } 373 374 def getAfterMask(valid: Seq[Bool], uop: Seq[MicroOp]) = { 375 assert(valid.length == uop.length) 376 val length = valid.length 377 (0 until length).map(i => { 378 (0 until length).map(j => { 379 Mux(valid(i) && valid(j), 380 isAfter(uop(i).robIdx, uop(j).robIdx), 381 Mux(!valid(i), true.B, false.B)) 382 }) 383 }) 384 } 385 386 /** 387 * Store-Load Memory violation detection 388 * 389 * When store writes back, it searches LoadQueue for younger load instructions 390 * with the same load physical address. They loaded wrong data and need re-execution. 391 * 392 * Cycle 0: Store Writeback 393 * Generate match vector for store address with rangeMask(stPtr, enqPtr). 394 * Besides, load instructions in LoadUnit_S1 and S2 are also checked. 395 * Cycle 1: Redirect Generation 396 * There're three possible types of violations, up to 6 possible redirect requests. 397 * Choose the oldest load (part 1). (4 + 2) -> (1 + 2) 398 * Cycle 2: Redirect Fire 399 * Choose the oldest load (part 2). (3 -> 1) 400 * Prepare redirect request according to the detected violation. 401 * Fire redirect request (if valid) 402 */ 403 404 // stage 0: lq l1 wb l1 wb lq 405 // | | | | | | (paddr match) 406 // stage 1: lq l1 wb l1 wb lq 407 // | | | | | | 408 // | |------------| | 409 // | | | 410 // stage 2: lq l1wb lq 411 // | | | 412 // -------------------- 413 // | 414 // rollback req 415 io.load_s1 := DontCare 416 def detectRollback(i: Int) = { 417 val startIndex = io.storeIn(i).bits.uop.lqIdx.value 418 val lqIdxMask = UIntToMask(startIndex, LoadQueueSize) 419 val xorMask = lqIdxMask ^ enqMask 420 val sameFlag = io.storeIn(i).bits.uop.lqIdx.flag === enqPtrExt(0).flag 421 val toEnqPtrMask = Mux(sameFlag, xorMask, ~xorMask) 422 423 // check if load already in lq needs to be rolledback 424 dataModule.io.violation(i).paddr := io.storeIn(i).bits.paddr 425 dataModule.io.violation(i).mask := io.storeIn(i).bits.mask 426 val addrMaskMatch = RegNext(dataModule.io.violation(i).violationMask) 427 val entryNeedCheck = RegNext(VecInit((0 until LoadQueueSize).map(j => { 428 allocated(j) && toEnqPtrMask(j) && (datavalid(j) || miss(j)) 429 }))) 430 val lqViolationVec = VecInit((0 until LoadQueueSize).map(j => { 431 addrMaskMatch(j) && entryNeedCheck(j) 432 })) 433 val lqViolation = lqViolationVec.asUInt().orR() 434 val lqViolationIndex = getFirstOne(lqViolationVec, RegNext(lqIdxMask)) 435 val lqViolationUop = uop(lqViolationIndex) 436 // lqViolationUop.lqIdx.flag := deqMask(lqViolationIndex) ^ deqPtrExt.flag 437 // lqViolationUop.lqIdx.value := lqViolationIndex 438 XSDebug(lqViolation, p"${Binary(Cat(lqViolationVec))}, $startIndex, $lqViolationIndex\n") 439 440 // when l/s writeback to rob together, check if rollback is needed 441 val wbViolationVec = RegNext(VecInit((0 until LoadPipelineWidth).map(j => { 442 io.loadIn(j).valid && 443 isAfter(io.loadIn(j).bits.uop.robIdx, io.storeIn(i).bits.uop.robIdx) && 444 io.storeIn(i).bits.paddr(PAddrBits - 1, 3) === io.loadIn(j).bits.paddr(PAddrBits - 1, 3) && 445 (io.storeIn(i).bits.mask & io.loadIn(j).bits.mask).orR 446 }))) 447 val wbViolation = wbViolationVec.asUInt().orR() 448 val wbViolationUop = getOldestInTwo(wbViolationVec, RegNext(VecInit(io.loadIn.map(_.bits.uop)))) 449 XSDebug(wbViolation, p"${Binary(Cat(wbViolationVec))}, $wbViolationUop\n") 450 451 // check if rollback is needed for load in l1 452 val l1ViolationVec = RegNext(VecInit((0 until LoadPipelineWidth).map(j => { 453 io.load_s1(j).valid && // L1 valid 454 isAfter(io.load_s1(j).uop.robIdx, io.storeIn(i).bits.uop.robIdx) && 455 io.storeIn(i).bits.paddr(PAddrBits - 1, 3) === io.load_s1(j).paddr(PAddrBits - 1, 3) && 456 (io.storeIn(i).bits.mask & io.load_s1(j).mask).orR 457 }))) 458 val l1Violation = l1ViolationVec.asUInt().orR() 459 val l1ViolationUop = getOldestInTwo(l1ViolationVec, RegNext(VecInit(io.load_s1.map(_.uop)))) 460 XSDebug(l1Violation, p"${Binary(Cat(l1ViolationVec))}, $l1ViolationUop\n") 461 462 XSDebug( 463 l1Violation, 464 "need rollback (l1 load) pc %x robidx %d target %x\n", 465 io.storeIn(i).bits.uop.cf.pc, io.storeIn(i).bits.uop.robIdx.asUInt, l1ViolationUop.robIdx.asUInt 466 ) 467 XSDebug( 468 lqViolation, 469 "need rollback (ld wb before store) pc %x robidx %d target %x\n", 470 io.storeIn(i).bits.uop.cf.pc, io.storeIn(i).bits.uop.robIdx.asUInt, lqViolationUop.robIdx.asUInt 471 ) 472 XSDebug( 473 wbViolation, 474 "need rollback (ld/st wb together) pc %x robidx %d target %x\n", 475 io.storeIn(i).bits.uop.cf.pc, io.storeIn(i).bits.uop.robIdx.asUInt, wbViolationUop.robIdx.asUInt 476 ) 477 478 ((lqViolation, lqViolationUop), (wbViolation, wbViolationUop), (l1Violation, l1ViolationUop)) 479 } 480 481 def rollbackSel(a: Valid[MicroOpRbExt], b: Valid[MicroOpRbExt]): ValidIO[MicroOpRbExt] = { 482 Mux( 483 a.valid, 484 Mux( 485 b.valid, 486 Mux(isAfter(a.bits.uop.robIdx, b.bits.uop.robIdx), b, a), // a,b both valid, sel oldest 487 a // sel a 488 ), 489 b // sel b 490 ) 491 } 492 val lastCycleRedirect = RegNext(io.brqRedirect) 493 val lastlastCycleRedirect = RegNext(lastCycleRedirect) 494 495 // S2: select rollback (part1) and generate rollback request 496 // rollback check 497 // Wb/L1 rollback seq check is done in s2 498 val rollbackWb = Wire(Vec(StorePipelineWidth, Valid(new MicroOpRbExt))) 499 val rollbackL1 = Wire(Vec(StorePipelineWidth, Valid(new MicroOpRbExt))) 500 val rollbackL1Wb = Wire(Vec(StorePipelineWidth*2, Valid(new MicroOpRbExt))) 501 // Lq rollback seq check is done in s3 (next stage), as getting rollbackLq MicroOp is slow 502 val rollbackLq = Wire(Vec(StorePipelineWidth, Valid(new MicroOpRbExt))) 503 // store ftq index for store set update 504 val stFtqIdxS2 = Wire(Vec(StorePipelineWidth, new FtqPtr)) 505 val stFtqOffsetS2 = Wire(Vec(StorePipelineWidth, UInt(log2Up(PredictWidth).W))) 506 for (i <- 0 until StorePipelineWidth) { 507 val detectedRollback = detectRollback(i) 508 rollbackLq(i).valid := detectedRollback._1._1 && RegNext(io.storeIn(i).valid) 509 rollbackLq(i).bits.uop := detectedRollback._1._2 510 rollbackLq(i).bits.flag := i.U 511 rollbackWb(i).valid := detectedRollback._2._1 && RegNext(io.storeIn(i).valid) 512 rollbackWb(i).bits.uop := detectedRollback._2._2 513 rollbackWb(i).bits.flag := i.U 514 rollbackL1(i).valid := detectedRollback._3._1 && RegNext(io.storeIn(i).valid) 515 rollbackL1(i).bits.uop := detectedRollback._3._2 516 rollbackL1(i).bits.flag := i.U 517 rollbackL1Wb(2*i) := rollbackL1(i) 518 rollbackL1Wb(2*i+1) := rollbackWb(i) 519 stFtqIdxS2(i) := RegNext(io.storeIn(i).bits.uop.cf.ftqPtr) 520 stFtqOffsetS2(i) := RegNext(io.storeIn(i).bits.uop.cf.ftqOffset) 521 } 522 523 val rollbackL1WbSelected = ParallelOperation(rollbackL1Wb, rollbackSel) 524 val rollbackL1WbVReg = RegNext(rollbackL1WbSelected.valid) 525 val rollbackL1WbReg = RegEnable(rollbackL1WbSelected.bits, rollbackL1WbSelected.valid) 526 val rollbackLq0VReg = RegNext(rollbackLq(0).valid) 527 val rollbackLq0Reg = RegEnable(rollbackLq(0).bits, rollbackLq(0).valid) 528 val rollbackLq1VReg = RegNext(rollbackLq(1).valid) 529 val rollbackLq1Reg = RegEnable(rollbackLq(1).bits, rollbackLq(1).valid) 530 531 // S3: select rollback (part2), generate rollback request, then fire rollback request 532 // Note that we use robIdx - 1.U to flush the load instruction itself. 533 // Thus, here if last cycle's robIdx equals to this cycle's robIdx, it still triggers the redirect. 534 535 // FIXME: this is ugly 536 val rollbackValidVec = Seq(rollbackL1WbVReg, rollbackLq0VReg, rollbackLq1VReg) 537 val rollbackUopExtVec = Seq(rollbackL1WbReg, rollbackLq0Reg, rollbackLq1Reg) 538 539 // select uop in parallel 540 val mask = getAfterMask(rollbackValidVec, rollbackUopExtVec.map(i => i.uop)) 541 val oneAfterZero = mask(1)(0) 542 val rollbackUopExt = Mux(oneAfterZero && mask(2)(0), 543 rollbackUopExtVec(0), 544 Mux(!oneAfterZero && mask(2)(1), rollbackUopExtVec(1), rollbackUopExtVec(2))) 545 val stFtqIdxS3 = RegNext(stFtqIdxS2) 546 val stFtqOffsetS3 = RegNext(stFtqOffsetS2) 547 val rollbackUop = rollbackUopExt.uop 548 val rollbackStFtqIdx = stFtqIdxS3(rollbackUopExt.flag) 549 val rollbackStFtqOffset = stFtqOffsetS3(rollbackUopExt.flag) 550 551 // check if rollback request is still valid in parallel 552 val rollbackValidVecChecked = Wire(Vec(3, Bool())) 553 for(((v, uop), idx) <- rollbackValidVec.zip(rollbackUopExtVec.map(i => i.uop)).zipWithIndex) { 554 rollbackValidVecChecked(idx) := v && 555 (!lastCycleRedirect.valid || isBefore(uop.robIdx, lastCycleRedirect.bits.robIdx)) && 556 (!lastlastCycleRedirect.valid || isBefore(uop.robIdx, lastlastCycleRedirect.bits.robIdx)) 557 } 558 559 io.rollback.bits.robIdx := rollbackUop.robIdx 560 io.rollback.bits.ftqIdx := rollbackUop.cf.ftqPtr 561 io.rollback.bits.stFtqIdx := rollbackStFtqIdx 562 io.rollback.bits.ftqOffset := rollbackUop.cf.ftqOffset 563 io.rollback.bits.stFtqOffset := rollbackStFtqOffset 564 io.rollback.bits.level := RedirectLevel.flush 565 io.rollback.bits.interrupt := DontCare 566 io.rollback.bits.cfiUpdate := DontCare 567 io.rollback.bits.cfiUpdate.target := rollbackUop.cf.pc 568 io.rollback.bits.debug_runahead_checkpoint_id := rollbackUop.debugInfo.runahead_checkpoint_id 569 // io.rollback.bits.pc := DontCare 570 571 io.rollback.valid := rollbackValidVecChecked.asUInt.orR 572 573 when(io.rollback.valid) { 574 // XSDebug("Mem rollback: pc %x robidx %d\n", io.rollback.bits.cfi, io.rollback.bits.robIdx.asUInt) 575 } 576 577 /** 578 * Load-Load Memory violation detection 579 * 580 * When load arrives load_s1, it searches LoadQueue for younger load instructions 581 * with the same load physical address. If younger load has been released (or observed), 582 * the younger load needs to be re-execed. 583 * 584 * For now, if re-exec it found to be needed in load_s1, we mark the older load as replayInst, 585 * the two loads will be replayed if the older load becomes the head of rob. 586 * 587 * When dcache releases a line, mark all writebacked entrys in load queue with 588 * the same line paddr as released. 589 */ 590 591 // Load-Load Memory violation query 592 val deqRightMask = UIntToMask.rightmask(deqPtr, LoadQueueSize) 593 (0 until LoadPipelineWidth).map(i => { 594 dataModule.io.release_violation(i).paddr := io.loadViolationQuery(i).req.bits.paddr 595 io.loadViolationQuery(i).req.ready := true.B 596 io.loadViolationQuery(i).resp.valid := RegNext(io.loadViolationQuery(i).req.fire()) 597 // Generate real violation mask 598 // Note that we use UIntToMask.rightmask here 599 val startIndex = io.loadViolationQuery(i).req.bits.uop.lqIdx.value 600 val lqIdxMask = UIntToMask.rightmask(startIndex, LoadQueueSize) 601 val xorMask = lqIdxMask ^ deqRightMask 602 val sameFlag = io.loadViolationQuery(i).req.bits.uop.lqIdx.flag === deqPtrExt.flag 603 val toDeqPtrMask = Mux(sameFlag, xorMask, ~xorMask) 604 val ldld_violation_mask = WireInit(VecInit((0 until LoadQueueSize).map(j => { 605 dataModule.io.release_violation(i).match_mask(j) && // addr match 606 toDeqPtrMask(j) && // the load is younger than current load 607 allocated(j) && // entry is valid 608 released(j) && // cacheline is released 609 (datavalid(j) || miss(j)) // paddr is valid 610 }))) 611 dontTouch(ldld_violation_mask) 612 ldld_violation_mask.suggestName("ldldViolationMask_" + i) 613 io.loadViolationQuery(i).resp.bits.have_violation := RegNext(ldld_violation_mask.asUInt.orR) 614 }) 615 616 // "released" flag update 617 // 618 // When io.release.valid, it uses the last ld-ld paddr cam port to 619 // update release flag in 1 cycle 620 when(io.release.valid){ 621 // Take over ld-ld paddr cam port 622 dataModule.io.release_violation.takeRight(1)(0).paddr := io.release.bits.paddr 623 io.loadViolationQuery.takeRight(1)(0).req.ready := false.B 624 // If a load needs that cam port, replay it from rs 625 (0 until LoadQueueSize).map(i => { 626 when(dataModule.io.release_violation.takeRight(1)(0).match_mask(i) && allocated(i) && writebacked(i)){ 627 // Note: if a load has missed in dcache and is waiting for refill in load queue, 628 // its released flag still needs to be set as true if addr matches. 629 released(i) := true.B 630 } 631 }) 632 } 633 634 /** 635 * Memory mapped IO / other uncached operations 636 * 637 * States: 638 * (1) writeback from store units: mark as pending 639 * (2) when they reach ROB's head, they can be sent to uncache channel 640 * (3) response from uncache channel: mark as datavalid 641 * (4) writeback to ROB (and other units): mark as writebacked 642 * (5) ROB commits the instruction: same as normal instructions 643 */ 644 //(2) when they reach ROB's head, they can be sent to uncache channel 645 val lqTailMmioPending = WireInit(pending(deqPtr)) 646 val lqTailAllocated = WireInit(allocated(deqPtr)) 647 val s_idle :: s_req :: s_resp :: s_wait :: Nil = Enum(4) 648 val uncacheState = RegInit(s_idle) 649 switch(uncacheState) { 650 is(s_idle) { 651 when(io.rob.pendingld && lqTailMmioPending && lqTailAllocated) { 652 uncacheState := s_req 653 } 654 } 655 is(s_req) { 656 when(io.uncache.req.fire()) { 657 uncacheState := s_resp 658 } 659 } 660 is(s_resp) { 661 when(io.uncache.resp.fire()) { 662 uncacheState := s_wait 663 } 664 } 665 is(s_wait) { 666 when(io.rob.commit) { 667 uncacheState := s_idle // ready for next mmio 668 } 669 } 670 } 671 io.uncache.req.valid := uncacheState === s_req 672 673 dataModule.io.uncache.raddr := deqPtrExtNext.value 674 675 io.uncache.req.bits.cmd := MemoryOpConstants.M_XRD 676 io.uncache.req.bits.addr := dataModule.io.uncache.rdata.paddr 677 io.uncache.req.bits.data := dataModule.io.uncache.rdata.data 678 io.uncache.req.bits.mask := dataModule.io.uncache.rdata.mask 679 680 io.uncache.req.bits.id := DontCare 681 io.uncache.req.bits.instrtype := DontCare 682 683 io.uncache.resp.ready := true.B 684 685 when (io.uncache.req.fire()) { 686 pending(deqPtr) := false.B 687 688 XSDebug("uncache req: pc %x addr %x data %x op %x mask %x\n", 689 uop(deqPtr).cf.pc, 690 io.uncache.req.bits.addr, 691 io.uncache.req.bits.data, 692 io.uncache.req.bits.cmd, 693 io.uncache.req.bits.mask 694 ) 695 } 696 697 // (3) response from uncache channel: mark as datavalid 698 dataModule.io.uncache.wen := false.B 699 when(io.uncache.resp.fire()){ 700 datavalid(deqPtr) := true.B 701 dataModule.io.uncacheWrite(deqPtr, io.uncache.resp.bits.data(XLEN-1, 0)) 702 dataModule.io.uncache.wen := true.B 703 704 XSDebug("uncache resp: data %x\n", io.dcache.bits.data) 705 } 706 707 // Read vaddr for mem exception 708 // no inst will be commited 1 cycle before tval update 709 vaddrModule.io.raddr(0) := (deqPtrExt + commitCount).value 710 io.exceptionAddr.vaddr := vaddrModule.io.rdata(0) 711 712 // misprediction recovery / exception redirect 713 // invalidate lq term using robIdx 714 val needCancel = Wire(Vec(LoadQueueSize, Bool())) 715 for (i <- 0 until LoadQueueSize) { 716 needCancel(i) := uop(i).robIdx.needFlush(io.brqRedirect) && allocated(i) 717 when (needCancel(i)) { 718 allocated(i) := false.B 719 } 720 } 721 722 /** 723 * update pointers 724 */ 725 val lastCycleCancelCount = PopCount(RegNext(needCancel)) 726 // when io.brqRedirect.valid, we don't allow eneuque even though it may fire. 727 val enqNumber = Mux(io.enq.canAccept && io.enq.sqCanAccept && !io.brqRedirect.valid, PopCount(io.enq.req.map(_.valid)), 0.U) 728 when (lastCycleRedirect.valid) { 729 // we recover the pointers in the next cycle after redirect 730 enqPtrExt := VecInit(enqPtrExt.map(_ - lastCycleCancelCount)) 731 }.otherwise { 732 enqPtrExt := VecInit(enqPtrExt.map(_ + enqNumber)) 733 } 734 735 deqPtrExtNext := deqPtrExt + commitCount 736 deqPtrExt := deqPtrExtNext 737 738 val validCount = distanceBetween(enqPtrExt(0), deqPtrExt) 739 740 allowEnqueue := validCount + enqNumber <= (LoadQueueSize - io.enq.req.length).U 741 742 /** 743 * misc 744 */ 745 io.rob.storeDataRobWb := DontCare // will be overwriten by store queue's result 746 747 // perf counter 748 QueuePerf(LoadQueueSize, validCount, !allowEnqueue) 749 io.lqFull := !allowEnqueue 750 XSPerfAccumulate("rollback", io.rollback.valid) // rollback redirect generated 751 XSPerfAccumulate("mmioCycle", uncacheState =/= s_idle) // lq is busy dealing with uncache req 752 XSPerfAccumulate("mmioCnt", io.uncache.req.fire()) 753 XSPerfAccumulate("refill", io.dcache.valid) 754 XSPerfAccumulate("writeback_success", PopCount(VecInit(io.ldout.map(i => i.fire())))) 755 XSPerfAccumulate("writeback_blocked", PopCount(VecInit(io.ldout.map(i => i.valid && !i.ready)))) 756 XSPerfAccumulate("utilization_miss", PopCount((0 until LoadQueueSize).map(i => allocated(i) && miss(i)))) 757 758 val perfinfo = IO(new Bundle(){ 759 val perfEvents = Output(new PerfEventsBundle(10)) 760 }) 761 val perfEvents = Seq( 762 ("rollback ", io.rollback.valid ), 763 ("mmioCycle ", uncacheState =/= s_idle ), 764 ("mmio_Cnt ", io.uncache.req.fire() ), 765 ("refill ", io.dcache.valid ), 766 ("writeback_success ", PopCount(VecInit(io.ldout.map(i => i.fire()))) ), 767 ("writeback_blocked ", PopCount(VecInit(io.ldout.map(i => i.valid && !i.ready))) ), 768 ("ltq_1/4_valid ", (validCount < (LoadQueueSize.U/4.U)) ), 769 ("ltq_2/4_valid ", (validCount > (LoadQueueSize.U/4.U)) & (validCount <= (LoadQueueSize.U/2.U)) ), 770 ("ltq_3/4_valid ", (validCount > (LoadQueueSize.U/2.U)) & (validCount <= (LoadQueueSize.U*3.U/4.U))), 771 ("ltq_4/4_valid ", (validCount > (LoadQueueSize.U*3.U/4.U)) ), 772 ) 773 774 for (((perf_out,(perf_name,perf)),i) <- perfinfo.perfEvents.perf_events.zip(perfEvents).zipWithIndex) { 775 perf_out.incr_step := RegNext(perf) 776 } 777 // debug info 778 XSDebug("enqPtrExt %d:%d deqPtrExt %d:%d\n", enqPtrExt(0).flag, enqPtr, deqPtrExt.flag, deqPtr) 779 780 def PrintFlag(flag: Bool, name: String): Unit = { 781 when(flag) { 782 XSDebug(false, true.B, name) 783 }.otherwise { 784 XSDebug(false, true.B, " ") 785 } 786 } 787 788 for (i <- 0 until LoadQueueSize) { 789 XSDebug(i + " pc %x pa %x ", uop(i).cf.pc, debug_paddr(i)) 790 PrintFlag(allocated(i), "a") 791 PrintFlag(allocated(i) && datavalid(i), "v") 792 PrintFlag(allocated(i) && writebacked(i), "w") 793 PrintFlag(allocated(i) && miss(i), "m") 794 PrintFlag(allocated(i) && pending(i), "p") 795 XSDebug(false, true.B, "\n") 796 } 797 798} 799