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