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