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