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.cache 18 19import chipsalliance.rocketchip.config.Parameters 20import chisel3._ 21import chisel3.experimental.ExtModule 22import chisel3.util._ 23import xiangshan._ 24import utils._ 25import utility._ 26import freechips.rocketchip.diplomacy.{IdRange, LazyModule, LazyModuleImp, TransferSizes} 27import freechips.rocketchip.tilelink._ 28import freechips.rocketchip.util.{BundleFieldBase, UIntToOH1} 29import device.RAMHelper 30import coupledL2.{AliasField, AliasKey, DirtyField, PrefetchField} 31import utility.ReqSourceField 32import utility.FastArbiter 33import mem.AddPipelineReg 34import xiangshan.cache.wpu._ 35 36import scala.math.max 37 38// DCache specific parameters 39case class DCacheParameters 40( 41 nSets: Int = 256, 42 nWays: Int = 8, 43 rowBits: Int = 64, 44 tagECC: Option[String] = None, 45 dataECC: Option[String] = None, 46 replacer: Option[String] = Some("setplru"), 47 updateReplaceOn2ndmiss: Boolean = true, 48 nMissEntries: Int = 1, 49 nProbeEntries: Int = 1, 50 nReleaseEntries: Int = 1, 51 nMMIOEntries: Int = 1, 52 nMMIOs: Int = 1, 53 blockBytes: Int = 64, 54 alwaysReleaseData: Boolean = false 55) extends L1CacheParameters { 56 // if sets * blockBytes > 4KB(page size), 57 // cache alias will happen, 58 // we need to avoid this by recoding additional bits in L2 cache 59 val setBytes = nSets * blockBytes 60 val aliasBitsOpt = if(setBytes > pageSize) Some(log2Ceil(setBytes / pageSize)) else None 61 val reqFields: Seq[BundleFieldBase] = Seq( 62 PrefetchField(), 63 ReqSourceField() 64 ) ++ aliasBitsOpt.map(AliasField) 65 val echoFields: Seq[BundleFieldBase] = Nil 66 67 def tagCode: Code = Code.fromString(tagECC) 68 69 def dataCode: Code = Code.fromString(dataECC) 70} 71 72// Physical Address 73// -------------------------------------- 74// | Physical Tag | PIndex | Offset | 75// -------------------------------------- 76// | 77// DCacheTagOffset 78// 79// Virtual Address 80// -------------------------------------- 81// | Above index | Set | Bank | Offset | 82// -------------------------------------- 83// | | | | 84// | | | 0 85// | | DCacheBankOffset 86// | DCacheSetOffset 87// DCacheAboveIndexOffset 88 89// Default DCache size = 64 sets * 8 ways * 8 banks * 8 Byte = 32K Byte 90 91trait HasDCacheParameters extends HasL1CacheParameters { 92 val cacheParams = dcacheParameters 93 val cfg = cacheParams 94 95 def encWordBits = cacheParams.dataCode.width(wordBits) 96 97 def encRowBits = encWordBits * rowWords // for DuplicatedDataArray only 98 def eccBits = encWordBits - wordBits 99 100 def encTagBits = cacheParams.tagCode.width(tagBits) 101 def eccTagBits = encTagBits - tagBits 102 103 def blockProbeAfterGrantCycles = 8 // give the processor some time to issue a request after a grant 104 105 def nSourceType = 10 106 def sourceTypeWidth = log2Up(nSourceType) 107 // non-prefetch source < 3 108 def LOAD_SOURCE = 0 109 def STORE_SOURCE = 1 110 def AMO_SOURCE = 2 111 // prefetch source >= 3 112 def DCACHE_PREFETCH_SOURCE = 3 113 def SOFT_PREFETCH = 4 114 def HW_PREFETCH_AGT = 5 115 def HW_PREFETCH_PHT_CUR = 6 116 def HW_PREFETCH_PHT_INC = 7 117 def HW_PREFETCH_PHT_DEC = 8 118 def HW_PREFETCH_BOP = 9 119 def HW_PREFETCH_STRIDE = 10 120 121 // each source use a id to distinguish its multiple reqs 122 def reqIdWidth = log2Up(nEntries) max log2Up(StoreBufferSize) 123 124 require(isPow2(cfg.nMissEntries)) // TODO 125 // require(isPow2(cfg.nReleaseEntries)) 126 require(cfg.nMissEntries < cfg.nReleaseEntries) 127 val nEntries = cfg.nMissEntries + cfg.nReleaseEntries 128 val releaseIdBase = cfg.nMissEntries 129 130 // banked dcache support 131 val DCacheSetDiv = 1 132 val DCacheSets = cacheParams.nSets 133 val DCacheWays = cacheParams.nWays 134 val DCacheBanks = 8 // hardcoded 135 val DCacheDupNum = 16 136 val DCacheSRAMRowBits = cacheParams.rowBits // hardcoded 137 val DCacheWordBits = 64 // hardcoded 138 val DCacheWordBytes = DCacheWordBits / 8 139 val DCacheVWordBytes = VLEN / 8 140 require(DCacheSRAMRowBits == 64) 141 142 val DCacheSetDivBits = log2Ceil(DCacheSetDiv) 143 val DCacheSetBits = log2Ceil(DCacheSets) 144 val DCacheSizeBits = DCacheSRAMRowBits * DCacheBanks * DCacheWays * DCacheSets 145 val DCacheSizeBytes = DCacheSizeBits / 8 146 val DCacheSizeWords = DCacheSizeBits / 64 // TODO 147 148 val DCacheSameVPAddrLength = 12 149 150 val DCacheSRAMRowBytes = DCacheSRAMRowBits / 8 151 val DCacheWordOffset = log2Up(DCacheWordBytes) 152 val DCacheVWordOffset = log2Up(DCacheVWordBytes) 153 154 val DCacheBankOffset = log2Up(DCacheSRAMRowBytes) 155 val DCacheSetOffset = DCacheBankOffset + log2Up(DCacheBanks) 156 val DCacheAboveIndexOffset = DCacheSetOffset + log2Up(DCacheSets) 157 val DCacheTagOffset = DCacheAboveIndexOffset min DCacheSameVPAddrLength 158 val DCacheLineOffset = DCacheSetOffset 159 160 // uncache 161 val uncacheIdxBits = log2Up(StoreQueueSize + 1) max log2Up(VirtualLoadQueueSize + 1) 162 // hardware prefetch parameters 163 // high confidence hardware prefetch port 164 val HighConfHWPFLoadPort = LoadPipelineWidth - 1 // use the last load port by default 165 val IgnorePrefetchConfidence = false 166 167 // parameters about duplicating regs to solve fanout 168 // In Main Pipe: 169 // tag_write.ready -> data_write.valid * 8 banks 170 // tag_write.ready -> meta_write.valid 171 // tag_write.ready -> tag_write.valid 172 // tag_write.ready -> err_write.valid 173 // tag_write.ready -> wb.valid 174 val nDupTagWriteReady = DCacheBanks + 4 175 // In Main Pipe: 176 // data_write.ready -> data_write.valid * 8 banks 177 // data_write.ready -> meta_write.valid 178 // data_write.ready -> tag_write.valid 179 // data_write.ready -> err_write.valid 180 // data_write.ready -> wb.valid 181 val nDupDataWriteReady = DCacheBanks + 4 182 val nDupWbReady = DCacheBanks + 4 183 val nDupStatus = nDupTagWriteReady + nDupDataWriteReady 184 val dataWritePort = 0 185 val metaWritePort = DCacheBanks 186 val tagWritePort = metaWritePort + 1 187 val errWritePort = tagWritePort + 1 188 val wbPort = errWritePort + 1 189 190 def set_to_dcache_div(set: UInt) = { 191 require(set.getWidth >= DCacheSetBits) 192 if (DCacheSetDivBits == 0) 0.U else set(DCacheSetDivBits-1, 0) 193 } 194 195 def set_to_dcache_div_set(set: UInt) = { 196 require(set.getWidth >= DCacheSetBits) 197 set(DCacheSetBits - 1, DCacheSetDivBits) 198 } 199 200 def addr_to_dcache_bank(addr: UInt) = { 201 require(addr.getWidth >= DCacheSetOffset) 202 addr(DCacheSetOffset-1, DCacheBankOffset) 203 } 204 205 def addr_to_dcache_div(addr: UInt) = { 206 require(addr.getWidth >= DCacheAboveIndexOffset) 207 if(DCacheSetDivBits == 0) 0.U else addr(DCacheSetOffset + DCacheSetDivBits - 1, DCacheSetOffset) 208 } 209 210 def addr_to_dcache_div_set(addr: UInt) = { 211 require(addr.getWidth >= DCacheAboveIndexOffset) 212 addr(DCacheAboveIndexOffset - 1, DCacheSetOffset + DCacheSetDivBits) 213 } 214 215 def addr_to_dcache_set(addr: UInt) = { 216 require(addr.getWidth >= DCacheAboveIndexOffset) 217 addr(DCacheAboveIndexOffset-1, DCacheSetOffset) 218 } 219 220 def get_data_of_bank(bank: Int, data: UInt) = { 221 require(data.getWidth >= (bank+1)*DCacheSRAMRowBits) 222 data(DCacheSRAMRowBits * (bank + 1) - 1, DCacheSRAMRowBits * bank) 223 } 224 225 def get_mask_of_bank(bank: Int, data: UInt) = { 226 require(data.getWidth >= (bank+1)*DCacheSRAMRowBytes) 227 data(DCacheSRAMRowBytes * (bank + 1) - 1, DCacheSRAMRowBytes * bank) 228 } 229 230 def get_direct_map_way(addr:UInt): UInt = { 231 addr(DCacheAboveIndexOffset + log2Up(DCacheWays) - 1, DCacheAboveIndexOffset) 232 } 233 234 def arbiter[T <: Bundle]( 235 in: Seq[DecoupledIO[T]], 236 out: DecoupledIO[T], 237 name: Option[String] = None): Unit = { 238 val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size)) 239 if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") } 240 for ((a, req) <- arb.io.in.zip(in)) { 241 a <> req 242 } 243 out <> arb.io.out 244 } 245 246 def arbiter_with_pipereg[T <: Bundle]( 247 in: Seq[DecoupledIO[T]], 248 out: DecoupledIO[T], 249 name: Option[String] = None): Unit = { 250 val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size)) 251 if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") } 252 for ((a, req) <- arb.io.in.zip(in)) { 253 a <> req 254 } 255 AddPipelineReg(arb.io.out, out, false.B) 256 } 257 258 def arbiter_with_pipereg_N_dup[T <: Bundle]( 259 in: Seq[DecoupledIO[T]], 260 out: DecoupledIO[T], 261 dups: Seq[DecoupledIO[T]], 262 name: Option[String] = None): Unit = { 263 val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size)) 264 if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") } 265 for ((a, req) <- arb.io.in.zip(in)) { 266 a <> req 267 } 268 for (dup <- dups) { 269 AddPipelineReg(arb.io.out, dup, false.B) 270 } 271 AddPipelineReg(arb.io.out, out, false.B) 272 } 273 274 def rrArbiter[T <: Bundle]( 275 in: Seq[DecoupledIO[T]], 276 out: DecoupledIO[T], 277 name: Option[String] = None): Unit = { 278 val arb = Module(new RRArbiter[T](chiselTypeOf(out.bits), in.size)) 279 if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") } 280 for ((a, req) <- arb.io.in.zip(in)) { 281 a <> req 282 } 283 out <> arb.io.out 284 } 285 286 def fastArbiter[T <: Bundle]( 287 in: Seq[DecoupledIO[T]], 288 out: DecoupledIO[T], 289 name: Option[String] = None): Unit = { 290 val arb = Module(new FastArbiter[T](chiselTypeOf(out.bits), in.size)) 291 if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") } 292 for ((a, req) <- arb.io.in.zip(in)) { 293 a <> req 294 } 295 out <> arb.io.out 296 } 297 298 val numReplaceRespPorts = 2 299 300 require(isPow2(nSets), s"nSets($nSets) must be pow2") 301 require(isPow2(nWays), s"nWays($nWays) must be pow2") 302 require(full_divide(rowBits, wordBits), s"rowBits($rowBits) must be multiple of wordBits($wordBits)") 303 require(full_divide(beatBits, rowBits), s"beatBits($beatBits) must be multiple of rowBits($rowBits)") 304} 305 306abstract class DCacheModule(implicit p: Parameters) extends L1CacheModule 307 with HasDCacheParameters 308 309abstract class DCacheBundle(implicit p: Parameters) extends L1CacheBundle 310 with HasDCacheParameters 311 312class ReplacementAccessBundle(implicit p: Parameters) extends DCacheBundle { 313 val set = UInt(log2Up(nSets).W) 314 val way = UInt(log2Up(nWays).W) 315} 316 317class ReplacementWayReqIO(implicit p: Parameters) extends DCacheBundle { 318 val set = ValidIO(UInt(log2Up(nSets).W)) 319 val dmWay = Output(UInt(log2Up(nWays).W)) 320 val way = Input(UInt(log2Up(nWays).W)) 321} 322 323class DCacheExtraMeta(implicit p: Parameters) extends DCacheBundle 324{ 325 val error = Bool() // cache line has been marked as corrupted by l2 / ecc error detected when store 326 val prefetch = Bool() // cache line is first required by prefetch 327 val access = Bool() // cache line has been accessed by load / store 328 329 // val debug_access_timestamp = UInt(64.W) // last time a load / store / refill access that cacheline 330} 331 332// memory request in word granularity(load, mmio, lr/sc, atomics) 333class DCacheWordReq(implicit p: Parameters) extends DCacheBundle 334{ 335 val cmd = UInt(M_SZ.W) 336 val vaddr = UInt(VAddrBits.W) 337 val data = UInt(VLEN.W) 338 val mask = UInt((VLEN/8).W) 339 val id = UInt(reqIdWidth.W) 340 val instrtype = UInt(sourceTypeWidth.W) 341 val isFirstIssue = Bool() 342 val replayCarry = new ReplayCarry(nWays) 343 344 val debug_robIdx = UInt(log2Ceil(RobSize).W) 345 def dump() = { 346 XSDebug("DCacheWordReq: cmd: %x vaddr: %x data: %x mask: %x id: %d\n", 347 cmd, vaddr, data, mask, id) 348 } 349} 350 351// memory request in word granularity(store) 352class DCacheLineReq(implicit p: Parameters) extends DCacheBundle 353{ 354 val cmd = UInt(M_SZ.W) 355 val vaddr = UInt(VAddrBits.W) 356 val addr = UInt(PAddrBits.W) 357 val data = UInt((cfg.blockBytes * 8).W) 358 val mask = UInt(cfg.blockBytes.W) 359 val id = UInt(reqIdWidth.W) 360 def dump() = { 361 XSDebug("DCacheLineReq: cmd: %x addr: %x data: %x mask: %x id: %d\n", 362 cmd, addr, data, mask, id) 363 } 364 def idx: UInt = get_idx(vaddr) 365} 366 367class DCacheWordReqWithVaddr(implicit p: Parameters) extends DCacheWordReq { 368 val addr = UInt(PAddrBits.W) 369 val wline = Bool() 370} 371 372class BaseDCacheWordResp(implicit p: Parameters) extends DCacheBundle 373{ 374 // read in s2 375 val data = UInt(VLEN.W) 376 // select in s3 377 val data_delayed = UInt(VLEN.W) 378 val id = UInt(reqIdWidth.W) 379 // cache req missed, send it to miss queue 380 val miss = Bool() 381 // cache miss, and failed to enter the missqueue, replay from RS is needed 382 val replay = Bool() 383 val replayCarry = new ReplayCarry(nWays) 384 // data has been corrupted 385 val tag_error = Bool() // tag error 386 val mshr_id = UInt(log2Up(cfg.nMissEntries).W) 387 388 val debug_robIdx = UInt(log2Ceil(RobSize).W) 389 def dump() = { 390 XSDebug("DCacheWordResp: data: %x id: %d miss: %b replay: %b\n", 391 data, id, miss, replay) 392 } 393} 394 395class DCacheWordResp(implicit p: Parameters) extends BaseDCacheWordResp 396{ 397 val meta_prefetch = Bool() 398 val meta_access = Bool() 399 // s2 400 val handled = Bool() 401 // s3: 1 cycle after data resp 402 val error_delayed = Bool() // all kinds of errors, include tag error 403 val replacementUpdated = Bool() 404} 405 406class BankedDCacheWordResp(implicit p: Parameters) extends DCacheWordResp 407{ 408 val bank_data = Vec(DCacheBanks, Bits(DCacheSRAMRowBits.W)) 409 val bank_oh = UInt(DCacheBanks.W) 410} 411 412class DCacheWordRespWithError(implicit p: Parameters) extends BaseDCacheWordResp 413{ 414 val error = Bool() // all kinds of errors, include tag error 415} 416 417class DCacheLineResp(implicit p: Parameters) extends DCacheBundle 418{ 419 val data = UInt((cfg.blockBytes * 8).W) 420 // cache req missed, send it to miss queue 421 val miss = Bool() 422 // cache req nacked, replay it later 423 val replay = Bool() 424 val id = UInt(reqIdWidth.W) 425 def dump() = { 426 XSDebug("DCacheLineResp: data: %x id: %d miss: %b replay: %b\n", 427 data, id, miss, replay) 428 } 429} 430 431class Refill(implicit p: Parameters) extends DCacheBundle 432{ 433 val addr = UInt(PAddrBits.W) 434 val data = UInt(l1BusDataWidth.W) 435 val error = Bool() // refilled data has been corrupted 436 // for debug usage 437 val data_raw = UInt((cfg.blockBytes * 8).W) 438 val hasdata = Bool() 439 val refill_done = Bool() 440 def dump() = { 441 XSDebug("Refill: addr: %x data: %x\n", addr, data) 442 } 443 val id = UInt(log2Up(cfg.nMissEntries).W) 444} 445 446class Release(implicit p: Parameters) extends DCacheBundle 447{ 448 val paddr = UInt(PAddrBits.W) 449 def dump() = { 450 XSDebug("Release: paddr: %x\n", paddr(PAddrBits-1, DCacheTagOffset)) 451 } 452} 453 454class DCacheWordIO(implicit p: Parameters) extends DCacheBundle 455{ 456 val req = DecoupledIO(new DCacheWordReq) 457 val resp = Flipped(DecoupledIO(new DCacheWordResp)) 458} 459 460 461class UncacheWordReq(implicit p: Parameters) extends DCacheBundle 462{ 463 val cmd = UInt(M_SZ.W) 464 val addr = UInt(PAddrBits.W) 465 val data = UInt(XLEN.W) 466 val mask = UInt((XLEN/8).W) 467 val id = UInt(uncacheIdxBits.W) 468 val instrtype = UInt(sourceTypeWidth.W) 469 val atomic = Bool() 470 val isFirstIssue = Bool() 471 val replayCarry = new ReplayCarry(nWays) 472 473 def dump() = { 474 XSDebug("UncacheWordReq: cmd: %x addr: %x data: %x mask: %x id: %d\n", 475 cmd, addr, data, mask, id) 476 } 477} 478 479class UncacheWordResp(implicit p: Parameters) extends DCacheBundle 480{ 481 val data = UInt(XLEN.W) 482 val data_delayed = UInt(XLEN.W) 483 val id = UInt(uncacheIdxBits.W) 484 val miss = Bool() 485 val replay = Bool() 486 val tag_error = Bool() 487 val error = Bool() 488 val replayCarry = new ReplayCarry(nWays) 489 val mshr_id = UInt(log2Up(cfg.nMissEntries).W) // FIXME: why uncacheWordResp is not merged to baseDcacheResp 490 491 val debug_robIdx = UInt(log2Ceil(RobSize).W) 492 def dump() = { 493 XSDebug("UncacheWordResp: data: %x id: %d miss: %b replay: %b, tag_error: %b, error: %b\n", 494 data, id, miss, replay, tag_error, error) 495 } 496} 497 498class UncacheWordIO(implicit p: Parameters) extends DCacheBundle 499{ 500 val req = DecoupledIO(new UncacheWordReq) 501 val resp = Flipped(DecoupledIO(new UncacheWordResp)) 502} 503 504class AtomicsResp(implicit p: Parameters) extends DCacheBundle { 505 val data = UInt(DataBits.W) 506 val miss = Bool() 507 val miss_id = UInt(log2Up(cfg.nMissEntries).W) 508 val replay = Bool() 509 val error = Bool() 510 511 val ack_miss_queue = Bool() 512 513 val id = UInt(reqIdWidth.W) 514} 515 516class AtomicWordIO(implicit p: Parameters) extends DCacheBundle 517{ 518 val req = DecoupledIO(new MainPipeReq) 519 val resp = Flipped(ValidIO(new AtomicsResp)) 520 val block_lr = Input(Bool()) 521} 522 523// used by load unit 524class DCacheLoadIO(implicit p: Parameters) extends DCacheWordIO 525{ 526 // kill previous cycle's req 527 val s1_kill = Output(Bool()) 528 val s2_kill = Output(Bool()) 529 val s0_pc = Output(UInt(VAddrBits.W)) 530 val s1_pc = Output(UInt(VAddrBits.W)) 531 val s2_pc = Output(UInt(VAddrBits.W)) 532 // cycle 0: load has updated replacement before 533 val replacementUpdated = Output(Bool()) 534 // cycle 0: virtual address: req.addr 535 // cycle 1: physical address: s1_paddr 536 val s1_paddr_dup_lsu = Output(UInt(PAddrBits.W)) // lsu side paddr 537 val s1_paddr_dup_dcache = Output(UInt(PAddrBits.W)) // dcache side paddr 538 val s1_disable_fast_wakeup = Input(Bool()) 539 // cycle 2: hit signal 540 val s2_hit = Input(Bool()) // hit signal for lsu, 541 val s2_first_hit = Input(Bool()) 542 val s2_bank_conflict = Input(Bool()) 543 val s2_wpu_pred_fail = Input(Bool()) 544 val s2_mq_nack = Input(Bool()) 545 546 // debug 547 val debug_s1_hit_way = Input(UInt(nWays.W)) 548 val debug_s2_pred_way_num = Input(UInt(XLEN.W)) 549 val debug_s2_dm_way_num = Input(UInt(XLEN.W)) 550 val debug_s2_real_way_num = Input(UInt(XLEN.W)) 551} 552 553class DCacheLineIO(implicit p: Parameters) extends DCacheBundle 554{ 555 val req = DecoupledIO(new DCacheLineReq) 556 val resp = Flipped(DecoupledIO(new DCacheLineResp)) 557} 558 559class DCacheToSbufferIO(implicit p: Parameters) extends DCacheBundle { 560 // sbuffer will directly send request to dcache main pipe 561 val req = Flipped(Decoupled(new DCacheLineReq)) 562 563 val main_pipe_hit_resp = ValidIO(new DCacheLineResp) 564 val refill_hit_resp = ValidIO(new DCacheLineResp) 565 566 val replay_resp = ValidIO(new DCacheLineResp) 567 568 def hit_resps: Seq[ValidIO[DCacheLineResp]] = Seq(main_pipe_hit_resp, refill_hit_resp) 569} 570 571// forward tilelink channel D's data to ldu 572class DcacheToLduForwardIO(implicit p: Parameters) extends DCacheBundle { 573 val valid = Bool() 574 val data = UInt(l1BusDataWidth.W) 575 val mshrid = UInt(log2Up(cfg.nMissEntries).W) 576 val last = Bool() 577 578 def apply(req_valid : Bool, req_data : UInt, req_mshrid : UInt, req_last : Bool) = { 579 valid := req_valid 580 data := req_data 581 mshrid := req_mshrid 582 last := req_last 583 } 584 585 def dontCare() = { 586 valid := false.B 587 data := DontCare 588 mshrid := DontCare 589 last := DontCare 590 } 591 592 def forward(req_valid : Bool, req_mshr_id : UInt, req_paddr : UInt) = { 593 val all_match = req_valid && valid && 594 req_mshr_id === mshrid && 595 req_paddr(log2Up(refillBytes)) === last 596 597 val forward_D = RegInit(false.B) 598 val forwardData = RegInit(VecInit(List.fill(VLEN/8)(0.U(8.W)))) 599 600 val block_idx = req_paddr(log2Up(refillBytes) - 1, 3) 601 val block_data = Wire(Vec(l1BusDataWidth / 64, UInt(64.W))) 602 (0 until l1BusDataWidth / 64).map(i => { 603 block_data(i) := data(64 * i + 63, 64 * i) 604 }) 605 val selected_data = Wire(UInt(128.W)) 606 selected_data := Mux(req_paddr(3), Fill(2, block_data(block_idx)), Cat(block_data(block_idx + 1.U), block_data(block_idx))) 607 608 forward_D := all_match 609 for (i <- 0 until VLEN/8) { 610 forwardData(i) := selected_data(8 * i + 7, 8 * i) 611 } 612 613 (forward_D, forwardData) 614 } 615} 616 617class MissEntryForwardIO(implicit p: Parameters) extends DCacheBundle { 618 val inflight = Bool() 619 val paddr = UInt(PAddrBits.W) 620 val raw_data = Vec(blockBytes/beatBytes, UInt(beatBits.W)) 621 val firstbeat_valid = Bool() 622 val lastbeat_valid = Bool() 623 624 def apply(mshr_valid : Bool, mshr_paddr : UInt, mshr_rawdata : Vec[UInt], mshr_first_valid : Bool, mshr_last_valid : Bool) = { 625 inflight := mshr_valid 626 paddr := mshr_paddr 627 raw_data := mshr_rawdata 628 firstbeat_valid := mshr_first_valid 629 lastbeat_valid := mshr_last_valid 630 } 631 632 // check if we can forward from mshr or D channel 633 def check(req_valid : Bool, req_paddr : UInt) = { 634 RegNext(req_valid && inflight && req_paddr(PAddrBits - 1, blockOffBits) === paddr(PAddrBits - 1, blockOffBits)) 635 } 636 637 def forward(req_valid : Bool, req_paddr : UInt) = { 638 val all_match = (req_paddr(log2Up(refillBytes)) === 0.U && firstbeat_valid) || 639 (req_paddr(log2Up(refillBytes)) === 1.U && lastbeat_valid) 640 641 val forward_mshr = RegInit(false.B) 642 val forwardData = RegInit(VecInit(List.fill(VLEN/8)(0.U(8.W)))) 643 644 val beat_data = raw_data(req_paddr(log2Up(refillBytes))) 645 val block_idx = req_paddr(log2Up(refillBytes) - 1, 3) 646 val block_data = Wire(Vec(l1BusDataWidth / 64, UInt(64.W))) 647 (0 until l1BusDataWidth / 64).map(i => { 648 block_data(i) := beat_data(64 * i + 63, 64 * i) 649 }) 650 val selected_data = Wire(UInt(128.W)) 651 selected_data := Mux(req_paddr(3), Fill(2, block_data(block_idx)), Cat(block_data(block_idx + 1.U), block_data(block_idx))) 652 653 forward_mshr := all_match 654 for (i <- 0 until VLEN/8) { 655 forwardData(i) := selected_data(8 * i + 7, 8 * i) 656 } 657 658 (forward_mshr, forwardData) 659 } 660} 661 662// forward mshr's data to ldu 663class LduToMissqueueForwardIO(implicit p: Parameters) extends DCacheBundle { 664 // req 665 val valid = Input(Bool()) 666 val mshrid = Input(UInt(log2Up(cfg.nMissEntries).W)) 667 val paddr = Input(UInt(PAddrBits.W)) 668 // resp 669 val forward_mshr = Output(Bool()) 670 val forwardData = Output(Vec(VLEN/8, UInt(8.W))) 671 val forward_result_valid = Output(Bool()) 672 673 def connect(sink: LduToMissqueueForwardIO) = { 674 sink.valid := valid 675 sink.mshrid := mshrid 676 sink.paddr := paddr 677 forward_mshr := sink.forward_mshr 678 forwardData := sink.forwardData 679 forward_result_valid := sink.forward_result_valid 680 } 681 682 def forward() = { 683 (forward_result_valid, forward_mshr, forwardData) 684 } 685} 686 687class DCacheToLsuIO(implicit p: Parameters) extends DCacheBundle { 688 val load = Vec(LoadPipelineWidth, Flipped(new DCacheLoadIO)) // for speculative load 689 val lsq = ValidIO(new Refill) // refill to load queue, wake up load misses 690 val store = new DCacheToSbufferIO // for sbuffer 691 val atomics = Flipped(new AtomicWordIO) // atomics reqs 692 val release = ValidIO(new Release) // cacheline release hint for ld-ld violation check 693 val forward_D = Output(Vec(LoadPipelineWidth, new DcacheToLduForwardIO)) 694 val forward_mshr = Vec(LoadPipelineWidth, new LduToMissqueueForwardIO) 695} 696 697class DCacheIO(implicit p: Parameters) extends DCacheBundle { 698 val hartId = Input(UInt(8.W)) 699 val l2_pf_store_only = Input(Bool()) 700 val lsu = new DCacheToLsuIO 701 val csr = new L1CacheToCsrIO 702 val error = new L1CacheErrorInfo 703 val mshrFull = Output(Bool()) 704 val force_write = Input(Bool()) 705} 706 707 708class DCache()(implicit p: Parameters) extends LazyModule with HasDCacheParameters { 709 710 val clientParameters = TLMasterPortParameters.v1( 711 Seq(TLMasterParameters.v1( 712 name = "dcache", 713 sourceId = IdRange(0, nEntries + 1), 714 supportsProbe = TransferSizes(cfg.blockBytes) 715 )), 716 requestFields = cacheParams.reqFields, 717 echoFields = cacheParams.echoFields 718 ) 719 720 val clientNode = TLClientNode(Seq(clientParameters)) 721 722 lazy val module = new DCacheImp(this) 723} 724 725 726class DCacheImp(outer: DCache) extends LazyModuleImp(outer) with HasDCacheParameters with HasPerfEvents { 727 728 val io = IO(new DCacheIO) 729 730 val (bus, edge) = outer.clientNode.out.head 731 require(bus.d.bits.data.getWidth == l1BusDataWidth, "DCache: tilelink width does not match") 732 733 println("DCache:") 734 println(" DCacheSets: " + DCacheSets) 735 println(" DCacheSetDiv: " + DCacheSetDiv) 736 println(" DCacheWays: " + DCacheWays) 737 println(" DCacheBanks: " + DCacheBanks) 738 println(" DCacheSRAMRowBits: " + DCacheSRAMRowBits) 739 println(" DCacheWordOffset: " + DCacheWordOffset) 740 println(" DCacheBankOffset: " + DCacheBankOffset) 741 println(" DCacheSetOffset: " + DCacheSetOffset) 742 println(" DCacheTagOffset: " + DCacheTagOffset) 743 println(" DCacheAboveIndexOffset: " + DCacheAboveIndexOffset) 744 println(" WPUEnable: " + dwpuParam.enWPU) 745 println(" WPUEnableCfPred: " + dwpuParam.enCfPred) 746 println(" WPUAlgorithm: " + dwpuParam.algoName) 747 748 //---------------------------------------- 749 // core data structures 750 val bankedDataArray = if(dwpuParam.enWPU) Module(new SramedDataArray) else Module(new BankedDataArray) 751 val metaArray = Module(new L1CohMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = 2)) 752 val errorArray = Module(new L1FlagMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = 2)) 753 val prefetchArray = Module(new L1FlagMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = 2)) // prefetch flag array 754 val accessArray = Module(new L1FlagMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = LoadPipelineWidth + 2)) 755 val tagArray = Module(new DuplicatedTagArray(readPorts = LoadPipelineWidth + 1)) 756 bankedDataArray.dump() 757 758 //---------------------------------------- 759 // core modules 760 val ldu = Seq.tabulate(LoadPipelineWidth)({ i => Module(new LoadPipe(i))}) 761 // val atomicsReplayUnit = Module(new AtomicsReplayEntry) 762 val mainPipe = Module(new MainPipe) 763 val refillPipe = Module(new RefillPipe) 764 val missQueue = Module(new MissQueue(edge)) 765 val probeQueue = Module(new ProbeQueue(edge)) 766 val wb = Module(new WritebackQueue(edge)) 767 768 missQueue.io.hartId := io.hartId 769 missQueue.io.l2_pf_store_only := RegNext(io.l2_pf_store_only, false.B) 770 771 val errors = ldu.map(_.io.error) ++ // load error 772 Seq(mainPipe.io.error) // store / misc error 773 io.error <> RegNext(Mux1H(errors.map(e => RegNext(e.valid) -> RegNext(e)))) 774 775 //---------------------------------------- 776 // meta array 777 778 // read / write coh meta 779 val meta_read_ports = ldu.map(_.io.meta_read) ++ 780 Seq(mainPipe.io.meta_read) 781 val meta_resp_ports = ldu.map(_.io.meta_resp) ++ 782 Seq(mainPipe.io.meta_resp) 783 val meta_write_ports = Seq( 784 mainPipe.io.meta_write, 785 refillPipe.io.meta_write 786 ) 787 meta_read_ports.zip(metaArray.io.read).foreach { case (p, r) => r <> p } 788 meta_resp_ports.zip(metaArray.io.resp).foreach { case (p, r) => p := r } 789 meta_write_ports.zip(metaArray.io.write).foreach { case (p, w) => w <> p } 790 791 // read extra meta 792 meta_read_ports.zip(errorArray.io.read).foreach { case (p, r) => r <> p } 793 meta_read_ports.zip(prefetchArray.io.read).foreach { case (p, r) => r <> p } 794 meta_read_ports.zip(accessArray.io.read).foreach { case (p, r) => r <> p } 795 val extra_meta_resp_ports = ldu.map(_.io.extra_meta_resp) ++ 796 Seq(mainPipe.io.extra_meta_resp) 797 extra_meta_resp_ports.zip(errorArray.io.resp).foreach { case (p, r) => { 798 (0 until nWays).map(i => { p(i).error := r(i) }) 799 }} 800 extra_meta_resp_ports.zip(prefetchArray.io.resp).foreach { case (p, r) => { 801 (0 until nWays).map(i => { p(i).prefetch := r(i) }) 802 }} 803 extra_meta_resp_ports.zip(accessArray.io.resp).foreach { case (p, r) => { 804 (0 until nWays).map(i => { p(i).access := r(i) }) 805 }} 806 807 // write extra meta 808 val error_flag_write_ports = Seq( 809 mainPipe.io.error_flag_write, // error flag generated by corrupted store 810 refillPipe.io.error_flag_write // corrupted signal from l2 811 ) 812 error_flag_write_ports.zip(errorArray.io.write).foreach { case (p, w) => w <> p } 813 814 val prefetch_flag_write_ports = Seq( 815 mainPipe.io.prefetch_flag_write, // set prefetch_flag to false if coh is set to Nothing 816 refillPipe.io.prefetch_flag_write // refill required by prefetch will set prefetch_flag 817 ) 818 prefetch_flag_write_ports.zip(prefetchArray.io.write).foreach { case (p, w) => w <> p } 819 820 val access_flag_write_ports = ldu.map(_.io.access_flag_write) ++ Seq( 821 mainPipe.io.access_flag_write, 822 refillPipe.io.access_flag_write 823 ) 824 access_flag_write_ports.zip(accessArray.io.write).foreach { case (p, w) => w <> p } 825 826 //---------------------------------------- 827 // tag array 828 require(tagArray.io.read.size == (ldu.size + 1)) 829 val tag_write_intend = missQueue.io.refill_pipe_req.valid || mainPipe.io.tag_write_intend 830 assert(!RegNext(!tag_write_intend && tagArray.io.write.valid)) 831 ldu.zipWithIndex.foreach { 832 case (ld, i) => 833 tagArray.io.read(i) <> ld.io.tag_read 834 ld.io.tag_resp := tagArray.io.resp(i) 835 ld.io.tag_read.ready := !tag_write_intend 836 } 837 tagArray.io.read.last <> mainPipe.io.tag_read 838 mainPipe.io.tag_resp := tagArray.io.resp.last 839 840 val fake_tag_read_conflict_this_cycle = PopCount(ldu.map(ld=> ld.io.tag_read.valid)) 841 XSPerfAccumulate("fake_tag_read_conflict", fake_tag_read_conflict_this_cycle) 842 843 val tag_write_arb = Module(new Arbiter(new TagWriteReq, 2)) 844 tag_write_arb.io.in(0) <> refillPipe.io.tag_write 845 tag_write_arb.io.in(1) <> mainPipe.io.tag_write 846 tagArray.io.write <> tag_write_arb.io.out 847 848 ldu.map(m => { 849 m.io.vtag_update.valid := tagArray.io.write.valid 850 m.io.vtag_update.bits := tagArray.io.write.bits 851 }) 852 853 //---------------------------------------- 854 // data array 855 mainPipe.io.data_read.zip(ldu).map(x => x._1 := x._2.io.lsu.req.valid) 856 857 val dataWriteArb = Module(new Arbiter(new L1BankedDataWriteReq, 2)) 858 dataWriteArb.io.in(0) <> refillPipe.io.data_write 859 dataWriteArb.io.in(1) <> mainPipe.io.data_write 860 861 bankedDataArray.io.write <> dataWriteArb.io.out 862 863 for (bank <- 0 until DCacheBanks) { 864 val dataWriteArb_dup = Module(new Arbiter(new L1BankedDataWriteReqCtrl, 2)) 865 dataWriteArb_dup.io.in(0).valid := refillPipe.io.data_write_dup(bank).valid 866 dataWriteArb_dup.io.in(0).bits := refillPipe.io.data_write_dup(bank).bits 867 dataWriteArb_dup.io.in(1).valid := mainPipe.io.data_write_dup(bank).valid 868 dataWriteArb_dup.io.in(1).bits := mainPipe.io.data_write_dup(bank).bits 869 870 bankedDataArray.io.write_dup(bank) <> dataWriteArb_dup.io.out 871 } 872 873 bankedDataArray.io.readline <> mainPipe.io.data_readline 874 bankedDataArray.io.readline_intend := mainPipe.io.data_read_intend 875 mainPipe.io.readline_error_delayed := bankedDataArray.io.readline_error_delayed 876 mainPipe.io.data_resp := bankedDataArray.io.readline_resp 877 878 (0 until LoadPipelineWidth).map(i => { 879 bankedDataArray.io.read(i) <> ldu(i).io.banked_data_read 880 bankedDataArray.io.is128Req(i) <> ldu(i).io.is128Req 881 bankedDataArray.io.read_error_delayed(i) <> ldu(i).io.read_error_delayed 882 883 ldu(i).io.banked_data_resp := bankedDataArray.io.read_resp_delayed(i) 884 885 ldu(i).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(i) 886 }) 887 888 (0 until LoadPipelineWidth).map(i => { 889 val (_, _, done, _) = edge.count(bus.d) 890 when(bus.d.bits.opcode === TLMessages.GrantData) { 891 io.lsu.forward_D(i).apply(bus.d.valid, bus.d.bits.data, bus.d.bits.source, done) 892 }.otherwise { 893 io.lsu.forward_D(i).dontCare() 894 } 895 }) 896 mainPipe.io.force_write <> io.force_write 897 898 /** dwpu */ 899 val dwpu = Module(new DCacheWpuWrapper(LoadPipelineWidth)) 900 for(i <- 0 until LoadPipelineWidth){ 901 dwpu.io.req(i) <> ldu(i).io.dwpu.req(0) 902 dwpu.io.resp(i) <> ldu(i).io.dwpu.resp(0) 903 dwpu.io.lookup_upd(i) <> ldu(i).io.dwpu.lookup_upd(0) 904 dwpu.io.cfpred(i) <> ldu(i).io.dwpu.cfpred(0) 905 } 906 dwpu.io.tagwrite_upd.valid := tagArray.io.write.valid 907 dwpu.io.tagwrite_upd.bits.vaddr := tagArray.io.write.bits.vaddr 908 dwpu.io.tagwrite_upd.bits.s1_real_way_en := tagArray.io.write.bits.way_en 909 910 //---------------------------------------- 911 // load pipe 912 // the s1 kill signal 913 // only lsu uses this, replay never kills 914 for (w <- 0 until LoadPipelineWidth) { 915 ldu(w).io.lsu <> io.lsu.load(w) 916 917 // TODO:when have load128Req 918 ldu(w).io.load128Req := false.B 919 920 // replay and nack not needed anymore 921 // TODO: remove replay and nack 922 ldu(w).io.nack := false.B 923 924 ldu(w).io.disable_ld_fast_wakeup := 925 bankedDataArray.io.disable_ld_fast_wakeup(w) // load pipe fast wake up should be disabled when bank conflict 926 } 927 928 /** LoadMissDB: record load miss state */ 929 val isWriteLoadMissTable = WireInit(Constantin.createRecord("isWriteLoadMissTable" + p(XSCoreParamsKey).HartId.toString)) 930 val isFirstHitWrite = WireInit(Constantin.createRecord("isFirstHitWrite" + p(XSCoreParamsKey).HartId.toString)) 931 val tableName = "LoadMissDB" + p(XSCoreParamsKey).HartId.toString 932 val siteName = "DcacheWrapper" + p(XSCoreParamsKey).HartId.toString 933 val loadMissTable = ChiselDB.createTable(tableName, new LoadMissEntry) 934 for( i <- 0 until LoadPipelineWidth){ 935 val loadMissEntry = Wire(new LoadMissEntry) 936 val loadMissWriteEn = 937 (!ldu(i).io.lsu.resp.bits.replay && ldu(i).io.miss_req.fire) || 938 (ldu(i).io.lsu.s2_first_hit && ldu(i).io.lsu.resp.valid && isFirstHitWrite.orR) 939 loadMissEntry.timeCnt := GTimer() 940 loadMissEntry.robIdx := ldu(i).io.lsu.resp.bits.debug_robIdx 941 loadMissEntry.paddr := ldu(i).io.miss_req.bits.addr 942 loadMissEntry.vaddr := ldu(i).io.miss_req.bits.vaddr 943 loadMissEntry.missState := OHToUInt(Cat(Seq( 944 ldu(i).io.miss_req.fire & ldu(i).io.miss_resp.merged, 945 ldu(i).io.miss_req.fire & !ldu(i).io.miss_resp.merged, 946 ldu(i).io.lsu.s2_first_hit && ldu(i).io.lsu.resp.valid 947 ))) 948 loadMissTable.log( 949 data = loadMissEntry, 950 en = isWriteLoadMissTable.orR && loadMissWriteEn, 951 site = siteName, 952 clock = clock, 953 reset = reset 954 ) 955 } 956 957 val isWriteLoadAccessTable = WireInit(Constantin.createRecord("isWriteLoadAccessTable" + p(XSCoreParamsKey).HartId.toString)) 958 val loadAccessTable = ChiselDB.createTable("LoadAccessDB" + p(XSCoreParamsKey).HartId.toString, new LoadAccessEntry) 959 for (i <- 0 until LoadPipelineWidth) { 960 val loadAccessEntry = Wire(new LoadAccessEntry) 961 loadAccessEntry.timeCnt := GTimer() 962 loadAccessEntry.robIdx := ldu(i).io.lsu.resp.bits.debug_robIdx 963 loadAccessEntry.paddr := ldu(i).io.miss_req.bits.addr 964 loadAccessEntry.vaddr := ldu(i).io.miss_req.bits.vaddr 965 loadAccessEntry.missState := OHToUInt(Cat(Seq( 966 ldu(i).io.miss_req.fire & ldu(i).io.miss_resp.merged, 967 ldu(i).io.miss_req.fire & !ldu(i).io.miss_resp.merged, 968 ldu(i).io.lsu.s2_first_hit && ldu(i).io.lsu.resp.valid 969 ))) 970 loadAccessEntry.pred_way_num := ldu(i).io.lsu.debug_s2_pred_way_num 971 loadAccessEntry.real_way_num := ldu(i).io.lsu.debug_s2_real_way_num 972 loadAccessEntry.dm_way_num := ldu(i).io.lsu.debug_s2_dm_way_num 973 loadAccessTable.log( 974 data = loadAccessEntry, 975 en = isWriteLoadAccessTable.orR && ldu(i).io.lsu.resp.valid, 976 site = siteName + "_loadpipe" + i.toString, 977 clock = clock, 978 reset = reset 979 ) 980 } 981 982 //---------------------------------------- 983 // atomics 984 // atomics not finished yet 985 // io.lsu.atomics <> atomicsReplayUnit.io.lsu 986 io.lsu.atomics.resp := RegNext(mainPipe.io.atomic_resp) 987 io.lsu.atomics.block_lr := mainPipe.io.block_lr 988 // atomicsReplayUnit.io.pipe_resp := RegNext(mainPipe.io.atomic_resp) 989 // atomicsReplayUnit.io.block_lr <> mainPipe.io.block_lr 990 991 //---------------------------------------- 992 // miss queue 993 val MissReqPortCount = LoadPipelineWidth + 1 994 val MainPipeMissReqPort = 0 995 996 // Request 997 val missReqArb = Module(new ArbiterFilterByCacheLineAddr(new MissReq, MissReqPortCount, blockOffBits, PAddrBits)) 998 999 missReqArb.io.in(MainPipeMissReqPort) <> mainPipe.io.miss_req 1000 for (w <- 0 until LoadPipelineWidth) { missReqArb.io.in(w + 1) <> ldu(w).io.miss_req } 1001 1002 for (w <- 0 until LoadPipelineWidth) { ldu(w).io.miss_resp := missQueue.io.resp } 1003 mainPipe.io.miss_resp := missQueue.io.resp 1004 1005 wb.io.miss_req.valid := missReqArb.io.out.valid 1006 wb.io.miss_req.bits := missReqArb.io.out.bits.addr 1007 1008 // block_decoupled(missReqArb.io.out, missQueue.io.req, wb.io.block_miss_req) 1009 missReqArb.io.out <> missQueue.io.req 1010 when(wb.io.block_miss_req) { 1011 missQueue.io.req.bits.cancel := true.B 1012 missReqArb.io.out.ready := false.B 1013 } 1014 1015 XSPerfAccumulate("miss_queue_fire", PopCount(VecInit(missReqArb.io.in.map(_.fire))) >= 1.U) 1016 XSPerfAccumulate("miss_queue_muti_fire", PopCount(VecInit(missReqArb.io.in.map(_.fire))) > 1.U) 1017 1018 XSPerfAccumulate("miss_queue_has_enq_req", PopCount(VecInit(missReqArb.io.in.map(_.valid))) >= 1.U) 1019 XSPerfAccumulate("miss_queue_has_muti_enq_req", PopCount(VecInit(missReqArb.io.in.map(_.valid))) > 1.U) 1020 XSPerfAccumulate("miss_queue_has_muti_enq_but_not_fire", PopCount(VecInit(missReqArb.io.in.map(_.valid))) > 1.U && PopCount(VecInit(missReqArb.io.in.map(_.fire))) === 0.U) 1021 1022 // forward missqueue 1023 (0 until LoadPipelineWidth).map(i => io.lsu.forward_mshr(i).connect(missQueue.io.forward(i))) 1024 1025 // refill to load queue 1026 io.lsu.lsq <> missQueue.io.refill_to_ldq 1027 1028 // tilelink stuff 1029 bus.a <> missQueue.io.mem_acquire 1030 bus.e <> missQueue.io.mem_finish 1031 missQueue.io.probe_addr := bus.b.bits.address 1032 1033 missQueue.io.main_pipe_resp := RegNext(mainPipe.io.atomic_resp) 1034 1035 //---------------------------------------- 1036 // probe 1037 // probeQueue.io.mem_probe <> bus.b 1038 block_decoupled(bus.b, probeQueue.io.mem_probe, missQueue.io.probe_block) 1039 probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block 1040 probeQueue.io.update_resv_set <> mainPipe.io.update_resv_set 1041 1042 //---------------------------------------- 1043 // mainPipe 1044 // when a req enters main pipe, if it is set-conflict with replace pipe or refill pipe, 1045 // block the req in main pipe 1046 block_decoupled(probeQueue.io.pipe_req, mainPipe.io.probe_req, missQueue.io.refill_pipe_req.valid) 1047 block_decoupled(io.lsu.store.req, mainPipe.io.store_req, refillPipe.io.req.valid) 1048 1049 io.lsu.store.replay_resp := RegNext(mainPipe.io.store_replay_resp) 1050 io.lsu.store.main_pipe_hit_resp := mainPipe.io.store_hit_resp 1051 1052 arbiter_with_pipereg( 1053 in = Seq(missQueue.io.main_pipe_req, io.lsu.atomics.req), 1054 out = mainPipe.io.atomic_req, 1055 name = Some("main_pipe_atomic_req") 1056 ) 1057 1058 mainPipe.io.invalid_resv_set := RegNext(wb.io.req.fire && wb.io.req.bits.addr === mainPipe.io.lrsc_locked_block.bits) 1059 1060 //---------------------------------------- 1061 // replace (main pipe) 1062 val mpStatus = mainPipe.io.status 1063 mainPipe.io.replace_req <> missQueue.io.replace_pipe_req 1064 missQueue.io.replace_pipe_resp := mainPipe.io.replace_resp 1065 1066 //---------------------------------------- 1067 // refill pipe 1068 val refillShouldBeBlocked = (mpStatus.s1.valid && mpStatus.s1.bits.set === missQueue.io.refill_pipe_req.bits.idx) || 1069 Cat(Seq(mpStatus.s2, mpStatus.s3).map(s => 1070 s.valid && 1071 s.bits.set === missQueue.io.refill_pipe_req.bits.idx && 1072 s.bits.way_en === missQueue.io.refill_pipe_req.bits.way_en 1073 )).orR 1074 block_decoupled(missQueue.io.refill_pipe_req, refillPipe.io.req, refillShouldBeBlocked) 1075 1076 val mpStatus_dup = mainPipe.io.status_dup 1077 val mq_refill_dup = missQueue.io.refill_pipe_req_dup 1078 val refillShouldBeBlocked_dup = VecInit((0 until nDupStatus).map { case i => 1079 mpStatus_dup(i).s1.valid && mpStatus_dup(i).s1.bits.set === mq_refill_dup(i).bits.idx || 1080 Cat(Seq(mpStatus_dup(i).s2, mpStatus_dup(i).s3).map(s => 1081 s.valid && 1082 s.bits.set === mq_refill_dup(i).bits.idx && 1083 s.bits.way_en === mq_refill_dup(i).bits.way_en 1084 )).orR 1085 }) 1086 dontTouch(refillShouldBeBlocked_dup) 1087 1088 refillPipe.io.req_dup_for_data_w.zipWithIndex.foreach { case (r, i) => 1089 r.bits := (mq_refill_dup.drop(dataWritePort).take(DCacheBanks))(i).bits 1090 } 1091 refillPipe.io.req_dup_for_meta_w.bits := mq_refill_dup(metaWritePort).bits 1092 refillPipe.io.req_dup_for_tag_w.bits := mq_refill_dup(tagWritePort).bits 1093 refillPipe.io.req_dup_for_err_w.bits := mq_refill_dup(errWritePort).bits 1094 refillPipe.io.req_dup_for_data_w.zipWithIndex.foreach { case (r, i) => 1095 r.valid := (mq_refill_dup.drop(dataWritePort).take(DCacheBanks))(i).valid && 1096 !(refillShouldBeBlocked_dup.drop(dataWritePort).take(DCacheBanks))(i) 1097 } 1098 refillPipe.io.req_dup_for_meta_w.valid := mq_refill_dup(metaWritePort).valid && !refillShouldBeBlocked_dup(metaWritePort) 1099 refillPipe.io.req_dup_for_tag_w.valid := mq_refill_dup(tagWritePort).valid && !refillShouldBeBlocked_dup(tagWritePort) 1100 refillPipe.io.req_dup_for_err_w.valid := mq_refill_dup(errWritePort).valid && !refillShouldBeBlocked_dup(errWritePort) 1101 1102 val refillPipe_io_req_valid_dup = VecInit(mq_refill_dup.zip(refillShouldBeBlocked_dup).map( 1103 x => x._1.valid && !x._2 1104 )) 1105 val refillPipe_io_data_write_valid_dup = VecInit(refillPipe_io_req_valid_dup.slice(0, nDupDataWriteReady)) 1106 val refillPipe_io_tag_write_valid_dup = VecInit(refillPipe_io_req_valid_dup.slice(nDupDataWriteReady, nDupStatus)) 1107 dontTouch(refillPipe_io_req_valid_dup) 1108 dontTouch(refillPipe_io_data_write_valid_dup) 1109 dontTouch(refillPipe_io_tag_write_valid_dup) 1110 mainPipe.io.data_write_ready_dup := VecInit(refillPipe_io_data_write_valid_dup.map(v => !v)) 1111 mainPipe.io.tag_write_ready_dup := VecInit(refillPipe_io_tag_write_valid_dup.map(v => !v)) 1112 mainPipe.io.wb_ready_dup := wb.io.req_ready_dup 1113 1114 mq_refill_dup.zip(refillShouldBeBlocked_dup).foreach { case (r, block) => 1115 r.ready := refillPipe.io.req.ready && !block 1116 } 1117 1118 missQueue.io.refill_pipe_resp := refillPipe.io.resp 1119 io.lsu.store.refill_hit_resp := RegNext(refillPipe.io.store_resp) 1120 1121 //---------------------------------------- 1122 // wb 1123 // add a queue between MainPipe and WritebackUnit to reduce MainPipe stalls due to WritebackUnit busy 1124 1125 wb.io.req <> mainPipe.io.wb 1126 bus.c <> wb.io.mem_release 1127 wb.io.release_wakeup := refillPipe.io.release_wakeup 1128 wb.io.release_update := mainPipe.io.release_update 1129 wb.io.probe_ttob_check_req <> mainPipe.io.probe_ttob_check_req 1130 wb.io.probe_ttob_check_resp <> mainPipe.io.probe_ttob_check_resp 1131 1132 io.lsu.release.valid := RegNext(wb.io.req.fire()) 1133 io.lsu.release.bits.paddr := RegNext(wb.io.req.bits.addr) 1134 // Note: RegNext() is required by: 1135 // * load queue released flag update logic 1136 // * load / load violation check logic 1137 // * and timing requirements 1138 // CHANGE IT WITH CARE 1139 1140 // connect bus d 1141 missQueue.io.mem_grant.valid := false.B 1142 missQueue.io.mem_grant.bits := DontCare 1143 1144 wb.io.mem_grant.valid := false.B 1145 wb.io.mem_grant.bits := DontCare 1146 1147 // in L1DCache, we ony expect Grant[Data] and ReleaseAck 1148 bus.d.ready := false.B 1149 when (bus.d.bits.opcode === TLMessages.Grant || bus.d.bits.opcode === TLMessages.GrantData) { 1150 missQueue.io.mem_grant <> bus.d 1151 } .elsewhen (bus.d.bits.opcode === TLMessages.ReleaseAck) { 1152 wb.io.mem_grant <> bus.d 1153 } .otherwise { 1154 assert (!bus.d.fire()) 1155 } 1156 1157 //---------------------------------------- 1158 // replacement algorithm 1159 val replacer = ReplacementPolicy.fromString(cacheParams.replacer, nWays, nSets) 1160 val replWayReqs = ldu.map(_.io.replace_way) ++ Seq(mainPipe.io.replace_way) 1161 1162 val victimList = VictimList(nSets) 1163 if (dwpuParam.enCfPred) { 1164 when(missQueue.io.replace_pipe_req.valid) { 1165 victimList.replace(get_idx(missQueue.io.replace_pipe_req.bits.vaddr)) 1166 } 1167 replWayReqs.foreach { 1168 case req => 1169 req.way := DontCare 1170 when(req.set.valid) { 1171 when(victimList.whether_sa(req.set.bits)) { 1172 req.way := replacer.way(req.set.bits) 1173 }.otherwise { 1174 req.way := req.dmWay 1175 } 1176 } 1177 } 1178 } else { 1179 replWayReqs.foreach { 1180 case req => 1181 req.way := DontCare 1182 when(req.set.valid) { 1183 req.way := replacer.way(req.set.bits) 1184 } 1185 } 1186 } 1187 1188 val replAccessReqs = ldu.map(_.io.replace_access) ++ Seq( 1189 mainPipe.io.replace_access 1190 ) 1191 val touchWays = Seq.fill(replAccessReqs.size)(Wire(ValidIO(UInt(log2Up(nWays).W)))) 1192 touchWays.zip(replAccessReqs).foreach { 1193 case (w, req) => 1194 w.valid := req.valid 1195 w.bits := req.bits.way 1196 } 1197 val touchSets = replAccessReqs.map(_.bits.set) 1198 replacer.access(touchSets, touchWays) 1199 1200 //---------------------------------------- 1201 // assertions 1202 // dcache should only deal with DRAM addresses 1203 when (bus.a.fire()) { 1204 assert(bus.a.bits.address >= 0x80000000L.U) 1205 } 1206 when (bus.b.fire()) { 1207 assert(bus.b.bits.address >= 0x80000000L.U) 1208 } 1209 when (bus.c.fire()) { 1210 assert(bus.c.bits.address >= 0x80000000L.U) 1211 } 1212 1213 //---------------------------------------- 1214 // utility functions 1215 def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = { 1216 sink.valid := source.valid && !block_signal 1217 source.ready := sink.ready && !block_signal 1218 sink.bits := source.bits 1219 } 1220 1221 //---------------------------------------- 1222 // Customized csr cache op support 1223 val cacheOpDecoder = Module(new CSRCacheOpDecoder("dcache", CacheInstrucion.COP_ID_DCACHE)) 1224 cacheOpDecoder.io.csr <> io.csr 1225 bankedDataArray.io.cacheOp.req := cacheOpDecoder.io.cache.req 1226 // dup cacheOp_req_valid 1227 bankedDataArray.io.cacheOp_req_dup.zipWithIndex.map{ case(dup, i) => dup := cacheOpDecoder.io.cache_req_dup(i) } 1228 // dup cacheOp_req_bits_opCode 1229 bankedDataArray.io.cacheOp_req_bits_opCode_dup.zipWithIndex.map{ case (dup, i) => dup := cacheOpDecoder.io.cacheOp_req_bits_opCode_dup(i) } 1230 1231 tagArray.io.cacheOp.req := cacheOpDecoder.io.cache.req 1232 // dup cacheOp_req_valid 1233 tagArray.io.cacheOp_req_dup.zipWithIndex.map{ case(dup, i) => dup := cacheOpDecoder.io.cache_req_dup(i) } 1234 // dup cacheOp_req_bits_opCode 1235 tagArray.io.cacheOp_req_bits_opCode_dup.zipWithIndex.map{ case (dup, i) => dup := cacheOpDecoder.io.cacheOp_req_bits_opCode_dup(i) } 1236 1237 cacheOpDecoder.io.cache.resp.valid := bankedDataArray.io.cacheOp.resp.valid || 1238 tagArray.io.cacheOp.resp.valid 1239 cacheOpDecoder.io.cache.resp.bits := Mux1H(List( 1240 bankedDataArray.io.cacheOp.resp.valid -> bankedDataArray.io.cacheOp.resp.bits, 1241 tagArray.io.cacheOp.resp.valid -> tagArray.io.cacheOp.resp.bits, 1242 )) 1243 cacheOpDecoder.io.error := io.error 1244 assert(!((bankedDataArray.io.cacheOp.resp.valid +& tagArray.io.cacheOp.resp.valid) > 1.U)) 1245 1246 //---------------------------------------- 1247 // performance counters 1248 val num_loads = PopCount(ldu.map(e => e.io.lsu.req.fire())) 1249 XSPerfAccumulate("num_loads", num_loads) 1250 1251 io.mshrFull := missQueue.io.full 1252 1253 // performance counter 1254 val ld_access = Wire(Vec(LoadPipelineWidth, missQueue.io.debug_early_replace.last.cloneType)) 1255 val st_access = Wire(ld_access.last.cloneType) 1256 ld_access.zip(ldu).foreach { 1257 case (a, u) => 1258 a.valid := RegNext(u.io.lsu.req.fire()) && !u.io.lsu.s1_kill 1259 a.bits.idx := RegNext(get_idx(u.io.lsu.req.bits.vaddr)) 1260 a.bits.tag := get_tag(u.io.lsu.s1_paddr_dup_dcache) 1261 } 1262 st_access.valid := RegNext(mainPipe.io.store_req.fire()) 1263 st_access.bits.idx := RegNext(get_idx(mainPipe.io.store_req.bits.vaddr)) 1264 st_access.bits.tag := RegNext(get_tag(mainPipe.io.store_req.bits.addr)) 1265 val access_info = ld_access.toSeq ++ Seq(st_access) 1266 val early_replace = RegNext(missQueue.io.debug_early_replace) 1267 val access_early_replace = access_info.map { 1268 case acc => 1269 Cat(early_replace.map { 1270 case r => 1271 acc.valid && r.valid && 1272 acc.bits.tag === r.bits.tag && 1273 acc.bits.idx === r.bits.idx 1274 }) 1275 } 1276 XSPerfAccumulate("access_early_replace", PopCount(Cat(access_early_replace))) 1277 1278 val perfEvents = (Seq(wb, mainPipe, missQueue, probeQueue) ++ ldu).flatMap(_.getPerfEvents) 1279 generatePerfEvent() 1280} 1281 1282class AMOHelper() extends ExtModule { 1283 val clock = IO(Input(Clock())) 1284 val enable = IO(Input(Bool())) 1285 val cmd = IO(Input(UInt(5.W))) 1286 val addr = IO(Input(UInt(64.W))) 1287 val wdata = IO(Input(UInt(64.W))) 1288 val mask = IO(Input(UInt(8.W))) 1289 val rdata = IO(Output(UInt(64.W))) 1290} 1291 1292class DCacheWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter { 1293 1294 val useDcache = coreParams.dcacheParametersOpt.nonEmpty 1295 val clientNode = if (useDcache) TLIdentityNode() else null 1296 val dcache = if (useDcache) LazyModule(new DCache()) else null 1297 if (useDcache) { 1298 clientNode := dcache.clientNode 1299 } 1300 1301 lazy val module = new LazyModuleImp(this) with HasPerfEvents { 1302 val io = IO(new DCacheIO) 1303 val perfEvents = if (!useDcache) { 1304 // a fake dcache which uses dpi-c to access memory, only for debug usage! 1305 val fake_dcache = Module(new FakeDCache()) 1306 io <> fake_dcache.io 1307 Seq() 1308 } 1309 else { 1310 io <> dcache.module.io 1311 dcache.module.getPerfEvents 1312 } 1313 generatePerfEvent() 1314 } 1315} 1316