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