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