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