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 chisel3._ 20import chisel3.util._ 21import chipsalliance.rocketchip.config._ 22import xiangshan._ 23import xiangshan.backend.rob.RobPtr 24import xiangshan.cache._ 25import xiangshan.frontend.FtqPtr 26import xiangshan.mem.mdp._ 27import utils._ 28import utility._ 29import xiangshan.backend.Bundles.DynInst 30 31class LoadQueueRAW(implicit p: Parameters) extends XSModule 32 with HasDCacheParameters 33 with HasCircularQueuePtrHelper 34 with HasLoadHelper 35 with HasPerfEvents 36{ 37 val io = IO(new Bundle() { 38 // control 39 val redirect = Flipped(ValidIO(new Redirect)) 40 41 // violation query 42 val query = Vec(LoadPipelineWidth, Flipped(new LoadNukeQueryIO)) 43 44 // from store unit s1 45 val storeIn = Vec(StorePipelineWidth, Flipped(Valid(new LsPipelineBundle))) 46 47 // global rollback flush 48 val rollback = Output(Valid(new Redirect)) 49 50 // to LoadQueueReplay 51 val stAddrReadySqPtr = Input(new SqPtr) 52 val stIssuePtr = Input(new SqPtr) 53 val lqFull = Output(Bool()) 54 }) 55 56 println("LoadQueueRAW: size " + LoadQueueRAWSize) 57 // LoadQueueRAW field 58 // +-------+--------+-------+-------+-----------+ 59 // | Valid | uop |PAddr | Mask | Datavalid | 60 // +-------+--------+-------+-------+-----------+ 61 // 62 // Field descriptions: 63 // Allocated : entry has been allocated already 64 // MicroOp : inst's microOp 65 // PAddr : physical address. 66 // Mask : data mask 67 // Datavalid : data valid 68 // 69 val allocated = RegInit(VecInit(List.fill(LoadQueueRAWSize)(false.B))) // The control signals need to explicitly indicate the initial value 70 val uop = Reg(Vec(LoadQueueRAWSize, new DynInst)) 71 val paddrModule = Module(new LqPAddrModule( 72 gen = UInt(PAddrBits.W), 73 numEntries = LoadQueueRAWSize, 74 numRead = LoadPipelineWidth, 75 numWrite = LoadPipelineWidth, 76 numWBank = LoadQueueNWriteBanks, 77 numWDelay = 2, 78 numCamPort = StorePipelineWidth 79 )) 80 paddrModule.io := DontCare 81 val maskModule = Module(new LqMaskModule( 82 gen = UInt((VLEN/8).W), 83 numEntries = LoadQueueRAWSize, 84 numRead = LoadPipelineWidth, 85 numWrite = LoadPipelineWidth, 86 numWBank = LoadQueueNWriteBanks, 87 numWDelay = 2, 88 numCamPort = StorePipelineWidth 89 )) 90 maskModule.io := DontCare 91 val datavalid = RegInit(VecInit(List.fill(LoadQueueRAWSize)(false.B))) 92 93 // freeliset: store valid entries index. 94 // +---+---+--------------+-----+-----+ 95 // | 0 | 1 | ...... | n-2 | n-1 | 96 // +---+---+--------------+-----+-----+ 97 val freeList = Module(new FreeList( 98 size = LoadQueueRAWSize, 99 allocWidth = LoadPipelineWidth, 100 freeWidth = 4, 101 moduleName = "LoadQueueRAW freelist" 102 )) 103 freeList.io := DontCare 104 105 // LoadQueueRAW enqueue 106 val canEnqueue = io.query.map(_.req.valid) 107 val cancelEnqueue = io.query.map(_.req.bits.uop.robIdx.needFlush(io.redirect)) 108 val allAddrCheck = io.stIssuePtr === io.stAddrReadySqPtr 109 val hasAddrInvalidStore = io.query.map(_.req.bits.uop.sqIdx).map(sqIdx => { 110 Mux(!allAddrCheck, isBefore(io.stAddrReadySqPtr, sqIdx), false.B) 111 }) 112 val needEnqueue = canEnqueue.zip(hasAddrInvalidStore).zip(cancelEnqueue).map { case ((v, r), c) => v && r && !c } 113 val bypassPAddr = Reg(Vec(LoadPipelineWidth, UInt(PAddrBits.W))) 114 val bypassMask = Reg(Vec(LoadPipelineWidth, UInt((VLEN/8).W))) 115 116 // Allocate logic 117 val enqValidVec = Wire(Vec(LoadPipelineWidth, Bool())) 118 val enqIndexVec = Wire(Vec(LoadPipelineWidth, UInt())) 119 120 // Enqueue 121 for ((enq, w) <- io.query.map(_.req).zipWithIndex) { 122 paddrModule.io.wen(w) := false.B 123 maskModule.io.wen(w) := false.B 124 freeList.io.doAllocate(w) := false.B 125 126 freeList.io.allocateReq(w) := needEnqueue(w) 127 128 // Allocate ready 129 enqValidVec(w) := freeList.io.canAllocate(w) 130 enqIndexVec(w) := freeList.io.allocateSlot(w) 131 enq.ready := Mux(needEnqueue(w), enqValidVec(w), true.B) 132 133 val enqIndex = enqIndexVec(w) 134 when (needEnqueue(w) && enq.ready) { 135 val debug_robIdx = enq.bits.uop.robIdx.asUInt 136 XSError(allocated(enqIndex), p"LoadQueueRAW: You can not write an valid entry! check: ldu $w, robIdx $debug_robIdx") 137 138 freeList.io.doAllocate(w) := true.B 139 140 // Allocate new entry 141 allocated(enqIndex) := true.B 142 143 // Write paddr 144 paddrModule.io.wen(w) := true.B 145 paddrModule.io.waddr(w) := enqIndex 146 paddrModule.io.wdata(w) := enq.bits.paddr 147 bypassPAddr(w) := enq.bits.paddr 148 149 // Write mask 150 maskModule.io.wen(w) := true.B 151 maskModule.io.waddr(w) := enqIndex 152 maskModule.io.wdata(w) := enq.bits.mask 153 bypassMask(w) := enq.bits.mask 154 155 // Fill info 156 uop(enqIndex) := enq.bits.uop 157 datavalid(enqIndex) := enq.bits.data_valid 158 } 159 } 160 161 for ((query, w) <- io.query.map(_.resp).zipWithIndex) { 162 query.valid := RegNext(io.query(w).req.valid) 163 query.bits.rep_frm_fetch := RegNext(false.B) 164 } 165 166 // LoadQueueRAW deallocate 167 val freeMaskVec = Wire(Vec(LoadQueueRAWSize, Bool())) 168 169 // init 170 freeMaskVec.map(e => e := false.B) 171 172 // when the stores that "older than" current load address were ready. 173 // current load will be released. 174 for (i <- 0 until LoadQueueRAWSize) { 175 val deqNotBlock = Mux(!allAddrCheck, !isBefore(io.stAddrReadySqPtr, uop(i).sqIdx), true.B) 176 val needCancel = uop(i).robIdx.needFlush(io.redirect) 177 178 when (allocated(i) && (deqNotBlock || needCancel)) { 179 allocated(i) := false.B 180 freeMaskVec(i) := true.B 181 } 182 } 183 184 // if need replay deallocate entry 185 val lastCanAccept = RegNext(VecInit(needEnqueue.zip(enqValidVec).map(x => x._1 && x._2))) 186 val lastAllocIndex = RegNext(enqIndexVec) 187 188 for ((revoke, w) <- io.query.map(_.revoke).zipWithIndex) { 189 val revokeValid = revoke && lastCanAccept(w) 190 val revokeIndex = lastAllocIndex(w) 191 192 when (allocated(revokeIndex) && revokeValid) { 193 allocated(revokeIndex) := false.B 194 freeMaskVec(revokeIndex) := true.B 195 } 196 } 197 freeList.io.free := freeMaskVec.asUInt 198 199 io.lqFull := freeList.io.empty 200 201 /** 202 * Store-Load Memory violation detection 203 * Scheme 1(Current scheme): flush the pipeline then re-fetch from the load instruction (like old load queue). 204 * Scheme 2 : re-fetch instructions from the first instruction after the store instruction. 205 * 206 * When store writes back, it searches LoadQueue for younger load instructions 207 * with the same load physical address. They loaded wrong data and need re-execution. 208 * 209 * Cycle 0: Store Writeback 210 * Generate match vector for store address with rangeMask(stPtr, enqPtr). 211 * Cycle 1: Select oldest load from select group. 212 * Cycle x: Redirect Fire 213 * Choose the oldest load from LoadPipelineWidth oldest loads. 214 * Prepare redirect request according to the detected violation. 215 * Fire redirect request (if valid) 216 */ 217 // SelectGroup 0 SelectGroup 1 SelectGroup y 218 // stage 0: lq lq lq ...... lq lq lq ....... lq lq lq 219 // | | | | | | | | | 220 // stage 1: lq lq lq ...... lq lq lq ....... lq lq lq 221 // \ | / ...... \ | / ....... \ | / 222 // stage 2: lq lq lq 223 // \ | / ....... \ | / ........ \ | / 224 // stage 3: lq lq lq 225 // ... 226 // ... 227 // | 228 // stage x: lq 229 // | 230 // rollback req 231 232 // select logic 233 val SelectGroupSize = RollbackGroupSize 234 val lgSelectGroupSize = log2Ceil(SelectGroupSize) 235 val TotalSelectCycles = scala.math.ceil(log2Ceil(LoadQueueRAWSize).toFloat / lgSelectGroupSize).toInt + 1 236 237 def selectPartialOldest[T <: XSBundleWithMicroOp](valid: Seq[Bool], bits: Seq[T]): (Seq[Bool], Seq[T]) = { 238 assert(valid.length == bits.length) 239 if (valid.length == 0 || valid.length == 1) { 240 (valid, bits) 241 } else if (valid.length == 2) { 242 val res = Seq.fill(2)(Wire(ValidIO(chiselTypeOf(bits(0))))) 243 for (i <- res.indices) { 244 res(i).valid := valid(i) 245 res(i).bits := bits(i) 246 } 247 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))) 248 (Seq(oldest.valid), Seq(oldest.bits)) 249 } else { 250 val left = selectPartialOldest(valid.take(valid.length / 2), bits.take(bits.length / 2)) 251 val right = selectPartialOldest(valid.takeRight(valid.length - (valid.length / 2)), bits.takeRight(bits.length - (bits.length / 2))) 252 selectPartialOldest(left._1 ++ right._1, left._2 ++ right._2) 253 } 254 } 255 256 def selectOldest[T <: XSBundleWithMicroOp](valid: Seq[Bool], bits: Seq[T]): (Seq[Bool], Seq[T]) = { 257 assert(valid.length == bits.length) 258 val numSelectGroups = scala.math.ceil(valid.length.toFloat / SelectGroupSize).toInt 259 260 // group info 261 val selectValidGroups = 262 if (valid.length <= SelectGroupSize) { 263 Seq(valid) 264 } else { 265 (0 until numSelectGroups).map(g => { 266 if (valid.length < (g + 1) * SelectGroupSize) { 267 valid.takeRight(valid.length - g * SelectGroupSize) 268 } else { 269 (0 until SelectGroupSize).map(j => valid(g * SelectGroupSize + j)) 270 } 271 }) 272 } 273 val selectBitsGroups = 274 if (bits.length <= SelectGroupSize) { 275 Seq(bits) 276 } else { 277 (0 until numSelectGroups).map(g => { 278 if (bits.length < (g + 1) * SelectGroupSize) { 279 bits.takeRight(bits.length - g * SelectGroupSize) 280 } else { 281 (0 until SelectGroupSize).map(j => bits(g * SelectGroupSize + j)) 282 } 283 }) 284 } 285 286 // select logic 287 if (valid.length <= SelectGroupSize) { 288 val (selValid, selBits) = selectPartialOldest(valid, bits) 289 (Seq(RegNext(selValid(0) && !selBits(0).uop.robIdx.needFlush(io.redirect))), Seq(RegNext(selBits(0)))) 290 } else { 291 val select = (0 until numSelectGroups).map(g => { 292 val (selValid, selBits) = selectPartialOldest(selectValidGroups(g), selectBitsGroups(g)) 293 (RegNext(selValid(0) && !selBits(0).uop.robIdx.needFlush(io.redirect)), RegNext(selBits(0))) 294 }) 295 selectOldest(select.map(_._1), select.map(_._2)) 296 } 297 } 298 299 def detectRollback(i: Int) = { 300 paddrModule.io.violationMdata(i) := io.storeIn(i).bits.paddr 301 maskModule.io.violationMdata(i) := io.storeIn(i).bits.mask 302 303 val bypassPaddrMask = RegNext(VecInit((0 until LoadPipelineWidth).map(j => bypassPAddr(j)(PAddrBits-1, DCacheVWordOffset) === io.storeIn(i).bits.paddr(PAddrBits-1, DCacheVWordOffset)))) 304 val bypassMMask = RegNext(VecInit((0 until LoadPipelineWidth).map(j => (bypassMask(j) & io.storeIn(i).bits.mask).orR))) 305 val bypassMaskUInt = (0 until LoadPipelineWidth).map(j => 306 Fill(LoadQueueRAWSize, RegNext(RegNext(io.query(j).req.fire))) & Mux(bypassPaddrMask(j) && bypassMMask(j), UIntToOH(RegNext(RegNext(enqIndexVec(j)))), 0.U(LoadQueueRAWSize)) 307 ).reduce(_|_) 308 309 val addrMaskMatch = RegNext(paddrModule.io.violationMmask(i).asUInt & maskModule.io.violationMmask(i).asUInt) | bypassMaskUInt 310 val entryNeedCheck = RegNext(VecInit((0 until LoadQueueRAWSize).map(j => { 311 allocated(j) && isAfter(uop(j).robIdx, io.storeIn(i).bits.uop.robIdx) && datavalid(j) && !uop(j).robIdx.needFlush(io.redirect) 312 }))) 313 val lqViolationSelVec = VecInit((0 until LoadQueueRAWSize).map(j => { 314 addrMaskMatch(j) && entryNeedCheck(j) 315 })) 316 317 val lqViolationSelUopExts = uop.map(uop => { 318 val wrapper = Wire(new XSBundleWithMicroOp) 319 wrapper.uop := uop 320 wrapper 321 }) 322 323 // select logic 324 val lqSelect = selectOldest(lqViolationSelVec, lqViolationSelUopExts) 325 326 // select one inst 327 val lqViolation = lqSelect._1(0) 328 val lqViolationUop = lqSelect._2(0).uop 329 330 XSDebug( 331 lqViolation, 332 "need rollback (ld wb before store) pc %x robidx %d target %x\n", 333 io.storeIn(i).bits.uop.pc, io.storeIn(i).bits.uop.robIdx.asUInt, lqViolationUop.robIdx.asUInt 334 ) 335 336 (lqViolation, lqViolationUop) 337 } 338 339 // select rollback (part1) and generate rollback request 340 // rollback check 341 // Lq rollback seq check is done in s3 (next stage), as getting rollbackLq MicroOp is slow 342 val rollbackLqWb = Wire(Vec(StorePipelineWidth, Valid(new MicroOpRbExt))) 343 val stFtqIdx = Wire(Vec(StorePipelineWidth, new FtqPtr)) 344 val stFtqOffset = Wire(Vec(StorePipelineWidth, UInt(log2Up(PredictWidth).W))) 345 for (w <- 0 until StorePipelineWidth) { 346 val detectedRollback = detectRollback(w) 347 rollbackLqWb(w).valid := detectedRollback._1 && DelayN(io.storeIn(w).valid && !io.storeIn(w).bits.miss, TotalSelectCycles) 348 rollbackLqWb(w).bits.uop := detectedRollback._2 349 rollbackLqWb(w).bits.flag := w.U 350 stFtqIdx(w) := DelayN(io.storeIn(w).bits.uop.ftqPtr, TotalSelectCycles) 351 stFtqOffset(w) := DelayN(io.storeIn(w).bits.uop.ftqOffset, TotalSelectCycles) 352 } 353 354 val rollbackLqWbValid = rollbackLqWb.map(x => x.valid && !x.bits.uop.robIdx.needFlush(io.redirect)) 355 val rollbackLqWbBits = rollbackLqWb.map(x => x.bits) 356 357 // select rollback (part2), generate rollback request, then fire rollback request 358 // Note that we use robIdx - 1.U to flush the load instruction itself. 359 // Thus, here if last cycle's robIdx equals to this cycle's robIdx, it still triggers the redirect. 360 361 // select uop in parallel 362 val lqs = selectPartialOldest(rollbackLqWbValid, rollbackLqWbBits) 363 val rollbackUopExt = lqs._2(0) 364 val rollbackUop = rollbackUopExt.uop 365 val rollbackStFtqIdx = stFtqIdx(rollbackUopExt.flag) 366 val rollbackStFtqOffset = stFtqOffset(rollbackUopExt.flag) 367 368 // check if rollback request is still valid in parallel 369 io.rollback.bits := DontCare 370 io.rollback.bits.robIdx := rollbackUop.robIdx 371 io.rollback.bits.ftqIdx := rollbackUop.ftqPtr 372 io.rollback.bits.stFtqIdx := rollbackStFtqIdx 373 io.rollback.bits.ftqOffset := rollbackUop.ftqOffset 374 io.rollback.bits.stFtqOffset := rollbackStFtqOffset 375 io.rollback.bits.level := RedirectLevel.flush 376 io.rollback.bits.interrupt := DontCare 377 io.rollback.bits.cfiUpdate := DontCare 378 io.rollback.bits.cfiUpdate.target := rollbackUop.pc 379 io.rollback.bits.debug_runahead_checkpoint_id := rollbackUop.debugInfo.runahead_checkpoint_id 380 // io.rollback.bits.pc := DontCare 381 382 io.rollback.valid := VecInit(rollbackLqWbValid).asUInt.orR 383 384 // perf cnt 385 val canEnqCount = PopCount(io.query.map(_.req.fire)) 386 val validCount = freeList.io.validCount 387 val allowEnqueue = validCount <= (LoadQueueRAWSize - LoadPipelineWidth).U 388 389 QueuePerf(LoadQueueRAWSize, validCount, !allowEnqueue) 390 XSPerfAccumulate("enqs", canEnqCount) 391 XSPerfAccumulate("stld_rollback", io.rollback.valid) 392 val perfEvents: Seq[(String, UInt)] = Seq( 393 ("enq ", canEnqCount), 394 ("stld_rollback", io.rollback.valid), 395 ) 396 generatePerfEvent() 397 // end 398}