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 freechips.rocketchip.diplomacy.{IdRange, LazyModule, LazyModuleImp, TransferSizes} 26import freechips.rocketchip.tilelink._ 27import freechips.rocketchip.util.BundleFieldBase 28import device.RAMHelper 29import huancun.{AliasField, AliasKey, PreferCacheField, PrefetchField, DirtyField} 30import scala.math.max 31 32// DCache specific parameters 33case class DCacheParameters 34( 35 nSets: Int = 256, 36 nWays: Int = 8, 37 rowBits: Int = 128, 38 tagECC: Option[String] = None, 39 dataECC: Option[String] = None, 40 replacer: Option[String] = Some("setplru"), 41 nMissEntries: Int = 1, 42 nProbeEntries: Int = 1, 43 nReleaseEntries: Int = 1, 44 nMMIOEntries: Int = 1, 45 nMMIOs: Int = 1, 46 blockBytes: Int = 64, 47 alwaysReleaseData: Boolean = true 48) extends L1CacheParameters { 49 // if sets * blockBytes > 4KB(page size), 50 // cache alias will happen, 51 // we need to avoid this by recoding additional bits in L2 cache 52 val setBytes = nSets * blockBytes 53 val aliasBitsOpt = if(setBytes > pageSize) Some(log2Ceil(setBytes / pageSize)) else None 54 val reqFields: Seq[BundleFieldBase] = Seq( 55 PrefetchField(), 56 PreferCacheField() 57 ) ++ aliasBitsOpt.map(AliasField) 58 val echoFields: Seq[BundleFieldBase] = Seq(DirtyField()) 59 60 def tagCode: Code = Code.fromString(tagECC) 61 62 def dataCode: Code = Code.fromString(dataECC) 63} 64 65// Physical Address 66// -------------------------------------- 67// | Physical Tag | PIndex | Offset | 68// -------------------------------------- 69// | 70// DCacheTagOffset 71// 72// Virtual Address 73// -------------------------------------- 74// | Above index | Set | Bank | Offset | 75// -------------------------------------- 76// | | | | 77// | | | 0 78// | | DCacheBankOffset 79// | DCacheSetOffset 80// DCacheAboveIndexOffset 81 82// Default DCache size = 64 sets * 8 ways * 8 banks * 8 Byte = 32K Byte 83 84trait HasDCacheParameters extends HasL1CacheParameters { 85 val cacheParams = dcacheParameters 86 val cfg = cacheParams 87 88 def encWordBits = cacheParams.dataCode.width(wordBits) 89 90 def encRowBits = encWordBits * rowWords // for DuplicatedDataArray only 91 def eccBits = encWordBits - wordBits 92 93 def encTagBits = cacheParams.tagCode.width(tagBits) 94 def eccTagBits = encTagBits - tagBits 95 96 def lrscCycles = LRSCCycles // ISA requires 16-insn LRSC sequences to succeed 97 def lrscBackoff = 3 // disallow LRSC reacquisition briefly 98 def blockProbeAfterGrantCycles = 8 // give the processor some time to issue a request after a grant 99 100 def nSourceType = 3 101 def sourceTypeWidth = log2Up(nSourceType) 102 def LOAD_SOURCE = 0 103 def STORE_SOURCE = 1 104 def AMO_SOURCE = 2 105 def SOFT_PREFETCH = 3 106 107 // each source use a id to distinguish its multiple reqs 108 def reqIdWidth = 64 109 110 require(isPow2(cfg.nMissEntries)) // TODO 111 // require(isPow2(cfg.nReleaseEntries)) 112 require(cfg.nMissEntries < cfg.nReleaseEntries) 113 val nEntries = cfg.nMissEntries + cfg.nReleaseEntries 114 val releaseIdBase = cfg.nMissEntries 115 116 // banked dcache support 117 val DCacheSets = cacheParams.nSets 118 val DCacheWays = cacheParams.nWays 119 val DCacheBanks = 8 120 val DCacheSRAMRowBits = 64 // hardcoded 121 val DCacheWordBits = 64 // hardcoded 122 val DCacheWordBytes = DCacheWordBits / 8 123 124 val DCacheSizeBits = DCacheSRAMRowBits * DCacheBanks * DCacheWays * DCacheSets 125 val DCacheSizeBytes = DCacheSizeBits / 8 126 val DCacheSizeWords = DCacheSizeBits / 64 // TODO 127 128 val DCacheSameVPAddrLength = 12 129 130 val DCacheSRAMRowBytes = DCacheSRAMRowBits / 8 131 val DCacheWordOffset = log2Up(DCacheWordBytes) 132 133 val DCacheBankOffset = log2Up(DCacheSRAMRowBytes) 134 val DCacheSetOffset = DCacheBankOffset + log2Up(DCacheBanks) 135 val DCacheAboveIndexOffset = DCacheSetOffset + log2Up(DCacheSets) 136 val DCacheTagOffset = DCacheAboveIndexOffset min DCacheSameVPAddrLength 137 val DCacheLineOffset = DCacheSetOffset 138 val DCacheIndexOffset = DCacheBankOffset 139 140 def addr_to_dcache_bank(addr: UInt) = { 141 require(addr.getWidth >= DCacheSetOffset) 142 addr(DCacheSetOffset-1, DCacheBankOffset) 143 } 144 145 def addr_to_dcache_set(addr: UInt) = { 146 require(addr.getWidth >= DCacheAboveIndexOffset) 147 addr(DCacheAboveIndexOffset-1, DCacheSetOffset) 148 } 149 150 def get_data_of_bank(bank: Int, data: UInt) = { 151 require(data.getWidth >= (bank+1)*DCacheSRAMRowBits) 152 data(DCacheSRAMRowBits * (bank + 1) - 1, DCacheSRAMRowBits * bank) 153 } 154 155 def get_mask_of_bank(bank: Int, data: UInt) = { 156 require(data.getWidth >= (bank+1)*DCacheSRAMRowBytes) 157 data(DCacheSRAMRowBytes * (bank + 1) - 1, DCacheSRAMRowBytes * bank) 158 } 159 160 val numReplaceRespPorts = 2 161 162 require(isPow2(nSets), s"nSets($nSets) must be pow2") 163 require(isPow2(nWays), s"nWays($nWays) must be pow2") 164 require(full_divide(rowBits, wordBits), s"rowBits($rowBits) must be multiple of wordBits($wordBits)") 165 require(full_divide(beatBits, rowBits), s"beatBits($beatBits) must be multiple of rowBits($rowBits)") 166} 167 168abstract class DCacheModule(implicit p: Parameters) extends L1CacheModule 169 with HasDCacheParameters 170 171abstract class DCacheBundle(implicit p: Parameters) extends L1CacheBundle 172 with HasDCacheParameters 173 174class ReplacementAccessBundle(implicit p: Parameters) extends DCacheBundle { 175 val set = UInt(log2Up(nSets).W) 176 val way = UInt(log2Up(nWays).W) 177} 178 179class ReplacementWayReqIO(implicit p: Parameters) extends DCacheBundle { 180 val set = ValidIO(UInt(log2Up(nSets).W)) 181 val way = Input(UInt(log2Up(nWays).W)) 182} 183 184// memory request in word granularity(load, mmio, lr/sc, atomics) 185class DCacheWordReq(implicit p: Parameters) extends DCacheBundle 186{ 187 val cmd = UInt(M_SZ.W) 188 val addr = UInt(PAddrBits.W) 189 val data = UInt(DataBits.W) 190 val mask = UInt((DataBits/8).W) 191 val id = UInt(reqIdWidth.W) 192 val instrtype = UInt(sourceTypeWidth.W) 193 def dump() = { 194 XSDebug("DCacheWordReq: cmd: %x addr: %x data: %x mask: %x id: %d\n", 195 cmd, addr, data, mask, id) 196 } 197} 198 199// memory request in word granularity(store) 200class DCacheLineReq(implicit p: Parameters) extends DCacheBundle 201{ 202 val cmd = UInt(M_SZ.W) 203 val vaddr = UInt(VAddrBits.W) 204 val addr = UInt(PAddrBits.W) 205 val data = UInt((cfg.blockBytes * 8).W) 206 val mask = UInt(cfg.blockBytes.W) 207 val id = UInt(reqIdWidth.W) 208 def dump() = { 209 XSDebug("DCacheLineReq: cmd: %x addr: %x data: %x mask: %x id: %d\n", 210 cmd, addr, data, mask, id) 211 } 212 def idx: UInt = get_idx(vaddr) 213} 214 215class DCacheWordReqWithVaddr(implicit p: Parameters) extends DCacheWordReq { 216 val vaddr = UInt(VAddrBits.W) 217 val wline = Bool() 218} 219 220class DCacheWordResp(implicit p: Parameters) extends DCacheBundle 221{ 222 val data = UInt(DataBits.W) 223 // cache req missed, send it to miss queue 224 val miss = Bool() 225 // cache req nacked, replay it later 226 val miss_enter = Bool() 227 // cache miss, and enter the missqueue successfully. just for softprefetch 228 val replay = Bool() 229 val id = UInt(reqIdWidth.W) 230 def dump() = { 231 XSDebug("DCacheWordResp: data: %x id: %d miss: %b replay: %b\n", 232 data, id, miss, replay) 233 } 234} 235 236class DCacheLineResp(implicit p: Parameters) extends DCacheBundle 237{ 238 val data = UInt((cfg.blockBytes * 8).W) 239 // cache req missed, send it to miss queue 240 val miss = Bool() 241 // cache req nacked, replay it later 242 val replay = Bool() 243 val id = UInt(reqIdWidth.W) 244 def dump() = { 245 XSDebug("DCacheLineResp: data: %x id: %d miss: %b replay: %b\n", 246 data, id, miss, replay) 247 } 248} 249 250class Refill(implicit p: Parameters) extends DCacheBundle 251{ 252 val addr = UInt(PAddrBits.W) 253 val data = UInt(l1BusDataWidth.W) 254 // for debug usage 255 val data_raw = UInt((cfg.blockBytes * 8).W) 256 val hasdata = Bool() 257 val refill_done = Bool() 258 def dump() = { 259 XSDebug("Refill: addr: %x data: %x\n", addr, data) 260 } 261} 262 263class Release(implicit p: Parameters) extends DCacheBundle 264{ 265 val paddr = UInt(PAddrBits.W) 266 def dump() = { 267 XSDebug("Release: paddr: %x\n", paddr(PAddrBits-1, DCacheTagOffset)) 268 } 269} 270 271class DCacheWordIO(implicit p: Parameters) extends DCacheBundle 272{ 273 val req = DecoupledIO(new DCacheWordReq) 274 val resp = Flipped(DecoupledIO(new DCacheWordResp)) 275} 276 277class DCacheWordIOWithVaddr(implicit p: Parameters) extends DCacheBundle 278{ 279 val req = DecoupledIO(new DCacheWordReqWithVaddr) 280 val resp = Flipped(DecoupledIO(new DCacheWordResp)) 281} 282 283// used by load unit 284class DCacheLoadIO(implicit p: Parameters) extends DCacheWordIO 285{ 286 // kill previous cycle's req 287 val s1_kill = Output(Bool()) 288 val s2_kill = Output(Bool()) 289 // cycle 0: virtual address: req.addr 290 // cycle 1: physical address: s1_paddr 291 val s1_paddr = Output(UInt(PAddrBits.W)) 292 val s1_hit_way = Input(UInt(nWays.W)) 293 val s1_disable_fast_wakeup = Input(Bool()) 294 val s1_bank_conflict = Input(Bool()) 295} 296 297class DCacheLineIO(implicit p: Parameters) extends DCacheBundle 298{ 299 val req = DecoupledIO(new DCacheLineReq) 300 val resp = Flipped(DecoupledIO(new DCacheLineResp)) 301} 302 303class DCacheToSbufferIO(implicit p: Parameters) extends DCacheBundle { 304 // sbuffer will directly send request to dcache main pipe 305 val req = Flipped(Decoupled(new DCacheLineReq)) 306 307 val main_pipe_hit_resp = ValidIO(new DCacheLineResp) 308 val refill_hit_resp = ValidIO(new DCacheLineResp) 309 310 val replay_resp = ValidIO(new DCacheLineResp) 311 312 def hit_resps: Seq[ValidIO[DCacheLineResp]] = Seq(main_pipe_hit_resp, refill_hit_resp) 313} 314 315class DCacheToLsuIO(implicit p: Parameters) extends DCacheBundle { 316 val load = Vec(LoadPipelineWidth, Flipped(new DCacheLoadIO)) // for speculative load 317 val lsq = ValidIO(new Refill) // refill to load queue, wake up load misses 318 val store = new DCacheToSbufferIO // for sbuffer 319 val atomics = Flipped(new DCacheWordIOWithVaddr) // atomics reqs 320 val release = ValidIO(new Release) // cacheline release hint for ld-ld violation check 321} 322 323class DCacheIO(implicit p: Parameters) extends DCacheBundle { 324 val lsu = new DCacheToLsuIO 325 val csr = new L1CacheToCsrIO 326 val error = new L1CacheErrorInfo 327 val mshrFull = Output(Bool()) 328} 329 330 331class DCache()(implicit p: Parameters) extends LazyModule with HasDCacheParameters { 332 333 val clientParameters = TLMasterPortParameters.v1( 334 Seq(TLMasterParameters.v1( 335 name = "dcache", 336 sourceId = IdRange(0, nEntries + 1), 337 supportsProbe = TransferSizes(cfg.blockBytes) 338 )), 339 requestFields = cacheParams.reqFields, 340 echoFields = cacheParams.echoFields 341 ) 342 343 val clientNode = TLClientNode(Seq(clientParameters)) 344 345 lazy val module = new DCacheImp(this) 346} 347 348 349class DCacheImp(outer: DCache) extends LazyModuleImp(outer) with HasDCacheParameters { 350 351 val io = IO(new DCacheIO) 352 353 val (bus, edge) = outer.clientNode.out.head 354 require(bus.d.bits.data.getWidth == l1BusDataWidth, "DCache: tilelink width does not match") 355 356 println("DCache:") 357 println(" DCacheSets: " + DCacheSets) 358 println(" DCacheWays: " + DCacheWays) 359 println(" DCacheBanks: " + DCacheBanks) 360 println(" DCacheSRAMRowBits: " + DCacheSRAMRowBits) 361 println(" DCacheWordOffset: " + DCacheWordOffset) 362 println(" DCacheBankOffset: " + DCacheBankOffset) 363 println(" DCacheSetOffset: " + DCacheSetOffset) 364 println(" DCacheTagOffset: " + DCacheTagOffset) 365 println(" DCacheAboveIndexOffset: " + DCacheAboveIndexOffset) 366 367 //---------------------------------------- 368 // core data structures 369 val bankedDataArray = Module(new BankedDataArray) 370 val metaArray = Module(new AsynchronousMetaArray(readPorts = 4, writePorts = 3)) 371 val tagArray = Module(new DuplicatedTagArray(readPorts = LoadPipelineWidth + 1)) 372 bankedDataArray.dump() 373 374 val errors = bankedDataArray.io.errors ++ metaArray.io.errors 375 io.error <> RegNext(Mux1H(errors.map(e => e.ecc_error.valid -> e))) 376 // assert(!io.error.ecc_error.valid) 377 378 //---------------------------------------- 379 // core modules 380 val ldu = Seq.tabulate(LoadPipelineWidth)({ i => Module(new LoadPipe(i))}) 381 val atomicsReplayUnit = Module(new AtomicsReplayEntry) 382 val mainPipe = Module(new MainPipe) 383 val refillPipe = Module(new RefillPipe) 384 val replacePipe = Module(new ReplacePipe) 385 val missQueue = Module(new MissQueue(edge)) 386 val probeQueue = Module(new ProbeQueue(edge)) 387 val wb = Module(new WritebackQueue(edge)) 388 389 //---------------------------------------- 390 // meta array 391 val meta_read_ports = ldu.map(_.io.meta_read) ++ 392 Seq(mainPipe.io.meta_read, 393 replacePipe.io.meta_read) 394 val meta_resp_ports = ldu.map(_.io.meta_resp) ++ 395 Seq(mainPipe.io.meta_resp, 396 replacePipe.io.meta_resp) 397 val meta_write_ports = Seq( 398 mainPipe.io.meta_write, 399 refillPipe.io.meta_write, 400 replacePipe.io.meta_write 401 ) 402 meta_read_ports.zip(metaArray.io.read).foreach { case (p, r) => r <> p } 403 meta_resp_ports.zip(metaArray.io.resp).foreach { case (p, r) => p := r } 404 meta_write_ports.zip(metaArray.io.write).foreach { case (p, w) => w <> p } 405 406 //---------------------------------------- 407 // tag array 408 require(tagArray.io.read.size == (ldu.size + 1)) 409 ldu.zipWithIndex.foreach { 410 case (ld, i) => 411 tagArray.io.read(i) <> ld.io.tag_read 412 ld.io.tag_resp := tagArray.io.resp(i) 413 } 414 tagArray.io.read.last <> mainPipe.io.tag_read 415 mainPipe.io.tag_resp := tagArray.io.resp.last 416 417 val tag_write_arb = Module(new Arbiter(new TagWriteReq, 2)) 418 tag_write_arb.io.in(0) <> refillPipe.io.tag_write 419 tag_write_arb.io.in(1) <> mainPipe.io.tag_write 420 tagArray.io.write <> tag_write_arb.io.out 421 422 //---------------------------------------- 423 // data array 424 425 val dataReadLineArb = Module(new Arbiter(new L1BankedDataReadLineReq, 2)) 426 dataReadLineArb.io.in(0) <> replacePipe.io.data_read 427 dataReadLineArb.io.in(1) <> mainPipe.io.data_read 428 429 val dataWriteArb = Module(new Arbiter(new L1BankedDataWriteReq, 2)) 430 dataWriteArb.io.in(0) <> refillPipe.io.data_write 431 dataWriteArb.io.in(1) <> mainPipe.io.data_write 432 433 bankedDataArray.io.write <> dataWriteArb.io.out 434 bankedDataArray.io.read(0) <> ldu(0).io.banked_data_read 435 bankedDataArray.io.read(1) <> ldu(1).io.banked_data_read 436 bankedDataArray.io.readline <> dataReadLineArb.io.out 437 438 ldu(0).io.banked_data_resp := bankedDataArray.io.resp 439 ldu(1).io.banked_data_resp := bankedDataArray.io.resp 440 mainPipe.io.data_resp := bankedDataArray.io.resp 441 replacePipe.io.data_resp := bankedDataArray.io.resp 442 443 ldu(0).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(0) 444 ldu(1).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(1) 445 ldu(0).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(0) 446 ldu(1).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(1) 447 448 //---------------------------------------- 449 // load pipe 450 // the s1 kill signal 451 // only lsu uses this, replay never kills 452 for (w <- 0 until LoadPipelineWidth) { 453 ldu(w).io.lsu <> io.lsu.load(w) 454 455 // replay and nack not needed anymore 456 // TODO: remove replay and nack 457 ldu(w).io.nack := false.B 458 459 ldu(w).io.disable_ld_fast_wakeup := 460 bankedDataArray.io.bank_conflict_fast(w) // load pipe fast wake up should be disabled when bank conflict 461 } 462 463 //---------------------------------------- 464 // atomics 465 // atomics not finished yet 466 io.lsu.atomics <> atomicsReplayUnit.io.lsu 467 atomicsReplayUnit.io.pipe_resp := mainPipe.io.atomic_resp 468 469 //---------------------------------------- 470 // miss queue 471 val MissReqPortCount = LoadPipelineWidth + 1 472 val MainPipeMissReqPort = 0 473 474 // Request 475 val missReqArb = Module(new Arbiter(new MissReq, MissReqPortCount)) 476 477 missReqArb.io.in(MainPipeMissReqPort) <> mainPipe.io.miss 478 for (w <- 0 until LoadPipelineWidth) { missReqArb.io.in(w + 1) <> ldu(w).io.miss_req } 479 480 wb.io.miss_req.valid := missReqArb.io.out.valid 481 wb.io.miss_req.bits := missReqArb.io.out.bits.addr 482 483 block_decoupled(missReqArb.io.out, missQueue.io.req, wb.io.block_miss_req) 484 485 // refill to load queue 486 io.lsu.lsq <> missQueue.io.refill_to_ldq 487 488 // tilelink stuff 489 bus.a <> missQueue.io.mem_acquire 490 bus.e <> missQueue.io.mem_finish 491 missQueue.io.probe_addr := bus.b.bits.address 492 493 missQueue.io.main_pipe_resp := mainPipe.io.atomic_resp 494 495 //---------------------------------------- 496 // probe 497 // probeQueue.io.mem_probe <> bus.b 498 block_decoupled(bus.b, probeQueue.io.mem_probe, missQueue.io.probe_block) 499 probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block 500 probeQueue.io.update_resv_set <> mainPipe.io.update_resv_set 501 502 //---------------------------------------- 503 // mainPipe 504 // when a req enters main pipe, if it is set-conflict with replace pipe or refill pipe, 505 // block the req in main pipe 506 val refillPipeStatus, replacePipeStatusS0 = Wire(Valid(UInt(idxBits.W))) 507 refillPipeStatus.valid := refillPipe.io.req.valid 508 refillPipeStatus.bits := get_idx(refillPipe.io.req.bits.paddrWithVirtualAlias) 509 replacePipeStatusS0.valid := replacePipe.io.req.valid 510 replacePipeStatusS0.bits := get_idx(replacePipe.io.req.bits.vaddr) 511 val blockMainPipeReqs = Seq( 512 refillPipeStatus, 513 replacePipeStatusS0, 514 replacePipe.io.status.s1_set, 515 replacePipe.io.status.s2_set 516 ) 517 val storeShouldBeBlocked = Cat(blockMainPipeReqs.map(r => r.valid && r.bits === io.lsu.store.req.bits.idx)).orR 518 val probeShouldBeBlocked = Cat(blockMainPipeReqs.map(r => r.valid && r.bits === get_idx(probeQueue.io.pipe_req.bits.vaddr))).orR 519 520 block_decoupled(probeQueue.io.pipe_req, mainPipe.io.probe_req, probeShouldBeBlocked) 521 block_decoupled(io.lsu.store.req, mainPipe.io.store_req, storeShouldBeBlocked) 522 523 io.lsu.store.replay_resp := mainPipe.io.store_replay_resp 524 io.lsu.store.main_pipe_hit_resp := mainPipe.io.store_hit_resp 525 526 val mainPipeAtomicReqArb = Module(new Arbiter(new MainPipeReq, 2)) 527 mainPipeAtomicReqArb.io.in(0) <> missQueue.io.main_pipe_req 528 mainPipeAtomicReqArb.io.in(1) <> atomicsReplayUnit.io.pipe_req 529 mainPipe.io.atomic_req <> mainPipeAtomicReqArb.io.out 530 531 mainPipe.io.invalid_resv_set := wb.io.req.fire && wb.io.req.bits.addr === mainPipe.io.lrsc_locked_block.bits 532 533 //---------------------------------------- 534 // replace pipe 535 val mpStatus = mainPipe.io.status 536 val replaceSet = addr_to_dcache_set(missQueue.io.replace_pipe_req.bits.vaddr) 537 val replaceWayEn = missQueue.io.replace_pipe_req.bits.way_en 538 val replaceShouldBeBlocked = mpStatus.s1.valid || 539 Cat(Seq(mpStatus.s2, mpStatus.s3).map(s => 540 s.valid && s.bits.set === replaceSet && s.bits.way_en === replaceWayEn 541 )).orR() 542 block_decoupled(missQueue.io.replace_pipe_req, replacePipe.io.req, replaceShouldBeBlocked) 543 missQueue.io.replace_pipe_resp := replacePipe.io.resp 544 545 //---------------------------------------- 546 // refill pipe 547 val refillShouldBeBlocked = (mpStatus.s1.valid && mpStatus.s1.bits.set === missQueue.io.refill_pipe_req.bits.idx) || 548 Cat(Seq(mpStatus.s2, mpStatus.s3).map(s => 549 s.valid && 550 s.bits.set === missQueue.io.refill_pipe_req.bits.idx && 551 s.bits.way_en === missQueue.io.refill_pipe_req.bits.way_en 552 )).orR 553 block_decoupled(missQueue.io.refill_pipe_req, refillPipe.io.req, refillShouldBeBlocked) 554 io.lsu.store.refill_hit_resp := refillPipe.io.store_resp 555 556 //---------------------------------------- 557 // wb 558 // add a queue between MainPipe and WritebackUnit to reduce MainPipe stalls due to WritebackUnit busy 559 val wbArb = Module(new Arbiter(new WritebackReq, 2)) 560 wbArb.io.in.zip(Seq(mainPipe.io.wb, replacePipe.io.wb)).foreach { case (arb, pipe) => arb <> pipe } 561 wb.io.req <> wbArb.io.out 562 bus.c <> wb.io.mem_release 563 wb.io.release_wakeup := refillPipe.io.release_wakeup 564 wb.io.release_update := mainPipe.io.release_update 565 io.lsu.release.valid := bus.c.fire() 566 io.lsu.release.bits.paddr := bus.c.bits.address 567 568 // connect bus d 569 missQueue.io.mem_grant.valid := false.B 570 missQueue.io.mem_grant.bits := DontCare 571 572 wb.io.mem_grant.valid := false.B 573 wb.io.mem_grant.bits := DontCare 574 575 // in L1DCache, we ony expect Grant[Data] and ReleaseAck 576 bus.d.ready := false.B 577 when (bus.d.bits.opcode === TLMessages.Grant || bus.d.bits.opcode === TLMessages.GrantData) { 578 missQueue.io.mem_grant <> bus.d 579 } .elsewhen (bus.d.bits.opcode === TLMessages.ReleaseAck) { 580 wb.io.mem_grant <> bus.d 581 } .otherwise { 582 assert (!bus.d.fire()) 583 } 584 585 //---------------------------------------- 586 // replacement algorithm 587 val replacer = ReplacementPolicy.fromString(cacheParams.replacer, nWays, nSets) 588 589 val replWayReqs = ldu.map(_.io.replace_way) ++ Seq(mainPipe.io.replace_way) 590 replWayReqs.foreach{ 591 case req => 592 req.way := DontCare 593 when (req.set.valid) { req.way := replacer.way(req.set.bits) } 594 } 595 596 val replAccessReqs = ldu.map(_.io.replace_access) ++ Seq( 597 mainPipe.io.replace_access, 598 refillPipe.io.replace_access 599 ) 600 val touchWays = Seq.fill(replAccessReqs.size)(Wire(ValidIO(UInt(log2Up(nWays).W)))) 601 touchWays.zip(replAccessReqs).foreach { 602 case (w, req) => 603 w.valid := req.valid 604 w.bits := req.bits.way 605 } 606 val touchSets = replAccessReqs.map(_.bits.set) 607 replacer.access(touchSets, touchWays) 608 609 //---------------------------------------- 610 // assertions 611 // dcache should only deal with DRAM addresses 612 when (bus.a.fire()) { 613 assert(bus.a.bits.address >= 0x80000000L.U) 614 } 615 when (bus.b.fire()) { 616 assert(bus.b.bits.address >= 0x80000000L.U) 617 } 618 when (bus.c.fire()) { 619 assert(bus.c.bits.address >= 0x80000000L.U) 620 } 621 622 //---------------------------------------- 623 // utility functions 624 def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = { 625 sink.valid := source.valid && !block_signal 626 source.ready := sink.ready && !block_signal 627 sink.bits := source.bits 628 } 629 630 //---------------------------------------- 631 // Customized csr cache op support 632 val cacheOpDecoder = Module(new CSRCacheOpDecoder("dcache", CacheInstrucion.COP_ID_DCACHE)) 633 cacheOpDecoder.io.csr <> io.csr 634 bankedDataArray.io.cacheOp.req := cacheOpDecoder.io.cache.req 635 metaArray.io.cacheOp.req := cacheOpDecoder.io.cache.req 636 tagArray.io.cacheOp.req := cacheOpDecoder.io.cache.req 637 cacheOpDecoder.io.cache.resp.valid := bankedDataArray.io.cacheOp.resp.valid || 638 metaArray.io.cacheOp.resp.valid || 639 tagArray.io.cacheOp.resp.valid 640 cacheOpDecoder.io.cache.resp.bits := Mux1H(List( 641 bankedDataArray.io.cacheOp.resp.valid -> bankedDataArray.io.cacheOp.resp.bits, 642 metaArray.io.cacheOp.resp.valid -> metaArray.io.cacheOp.resp.bits, 643 tagArray.io.cacheOp.resp.valid -> tagArray.io.cacheOp.resp.bits, 644 )) 645 assert(!((bankedDataArray.io.cacheOp.resp.valid +& metaArray.io.cacheOp.resp.valid +& tagArray.io.cacheOp.resp.valid) > 1.U)) 646 647 //---------------------------------------- 648 // performance counters 649 val num_loads = PopCount(ldu.map(e => e.io.lsu.req.fire())) 650 XSPerfAccumulate("num_loads", num_loads) 651 652 io.mshrFull := missQueue.io.full 653 654 // performance counter 655 val ld_access = Wire(Vec(LoadPipelineWidth, missQueue.io.debug_early_replace.last.cloneType)) 656 val st_access = Wire(ld_access.last.cloneType) 657 ld_access.zip(ldu).foreach { 658 case (a, u) => 659 a.valid := RegNext(u.io.lsu.req.fire()) && !u.io.lsu.s1_kill 660 a.bits.idx := RegNext(get_idx(u.io.lsu.req.bits.addr)) 661 a.bits.tag := get_tag(u.io.lsu.s1_paddr) 662 } 663 st_access.valid := RegNext(mainPipe.io.store_req.fire()) 664 st_access.bits.idx := RegNext(get_idx(mainPipe.io.store_req.bits.vaddr)) 665 st_access.bits.tag := RegNext(get_tag(mainPipe.io.store_req.bits.addr)) 666 val access_info = ld_access.toSeq ++ Seq(st_access) 667 val early_replace = RegNext(missQueue.io.debug_early_replace) 668 val access_early_replace = access_info.map { 669 case acc => 670 Cat(early_replace.map { 671 case r => 672 acc.valid && r.valid && 673 acc.bits.tag === r.bits.tag && 674 acc.bits.idx === r.bits.idx 675 }) 676 } 677 XSPerfAccumulate("access_early_replace", PopCount(Cat(access_early_replace))) 678 679 val wb_perf = wb.perfEvents.map(_._1).zip(wb.perfinfo.perfEvents.perf_events) 680 val mainp_perf = mainPipe.perfEvents.map(_._1).zip(mainPipe.perfinfo.perfEvents.perf_events) 681 val missq_perf = missQueue.perfEvents.map(_._1).zip(missQueue.perfinfo.perfEvents.perf_events) 682 val probq_perf = probeQueue.perfEvents.map(_._1).zip(probeQueue.perfinfo.perfEvents.perf_events) 683 val ldu_0_perf = ldu(0).perfEvents.map(_._1).zip(ldu(0).perfinfo.perfEvents.perf_events) 684 val ldu_1_perf = ldu(1).perfEvents.map(_._1).zip(ldu(1).perfinfo.perfEvents.perf_events) 685 val perfEvents = wb_perf ++ mainp_perf ++ missq_perf ++ probq_perf ++ ldu_0_perf ++ ldu_1_perf 686 val perflist = wb.perfinfo.perfEvents.perf_events ++ mainPipe.perfinfo.perfEvents.perf_events ++ 687 missQueue.perfinfo.perfEvents.perf_events ++ probeQueue.perfinfo.perfEvents.perf_events ++ 688 ldu(0).perfinfo.perfEvents.perf_events ++ ldu(1).perfinfo.perfEvents.perf_events 689 val perf_length = perflist.length 690 val perfinfo = IO(new Bundle(){ 691 val perfEvents = Output(new PerfEventsBundle(perflist.length)) 692 }) 693 perfinfo.perfEvents.perf_events := perflist 694 695} 696 697class AMOHelper() extends ExtModule { 698 val clock = IO(Input(Clock())) 699 val enable = IO(Input(Bool())) 700 val cmd = IO(Input(UInt(5.W))) 701 val addr = IO(Input(UInt(64.W))) 702 val wdata = IO(Input(UInt(64.W))) 703 val mask = IO(Input(UInt(8.W))) 704 val rdata = IO(Output(UInt(64.W))) 705} 706 707class DCacheWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter { 708 709 val useDcache = coreParams.dcacheParametersOpt.nonEmpty 710 val clientNode = if (useDcache) TLIdentityNode() else null 711 val dcache = if (useDcache) LazyModule(new DCache()) else null 712 if (useDcache) { 713 clientNode := dcache.clientNode 714 } 715 716 lazy val module = new LazyModuleImp(this) { 717 val io = IO(new DCacheIO) 718 val perfinfo = IO(new Bundle(){ 719 val perfEvents = Output(new PerfEventsBundle(dcache.asInstanceOf[DCache].module.perf_length)) 720 }) 721 val perfEvents = dcache.asInstanceOf[DCache].module.perfEvents.map(_._1).zip(dcache.asInstanceOf[DCache].module.perfinfo.perfEvents.perf_events) 722 if (!useDcache) { 723 // a fake dcache which uses dpi-c to access memory, only for debug usage! 724 val fake_dcache = Module(new FakeDCache()) 725 io <> fake_dcache.io 726 } 727 else { 728 io <> dcache.module.io 729 perfinfo := dcache.asInstanceOf[DCache].module.perfinfo 730 } 731 } 732} 733