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