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 = 64, 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 = log2Up(nEntries) max log2Up(StoreBufferSize) 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 // hardcoded 121 val DCacheSRAMRowBits = cacheParams.rowBits // hardcoded 122 val DCacheWordBits = 64 // hardcoded 123 val DCacheWordBytes = DCacheWordBits / 8 124 require(DCacheSRAMRowBits == 64) 125 126 val DCacheSizeBits = DCacheSRAMRowBits * DCacheBanks * DCacheWays * DCacheSets 127 val DCacheSizeBytes = DCacheSizeBits / 8 128 val DCacheSizeWords = DCacheSizeBits / 64 // TODO 129 130 val DCacheSameVPAddrLength = 12 131 132 val DCacheSRAMRowBytes = DCacheSRAMRowBits / 8 133 val DCacheWordOffset = log2Up(DCacheWordBytes) 134 135 val DCacheBankOffset = log2Up(DCacheSRAMRowBytes) 136 val DCacheSetOffset = DCacheBankOffset + log2Up(DCacheBanks) 137 val DCacheAboveIndexOffset = DCacheSetOffset + log2Up(DCacheSets) 138 val DCacheTagOffset = DCacheAboveIndexOffset min DCacheSameVPAddrLength 139 val DCacheLineOffset = DCacheSetOffset 140 141 // parameters about duplicating regs to solve fanout 142 // In Main Pipe: 143 // tag_write.ready -> data_write.valid * 8 banks 144 // tag_write.ready -> meta_write.valid 145 // tag_write.ready -> tag_write.valid 146 // tag_write.ready -> err_write.valid 147 // tag_write.ready -> wb.valid 148 val nDupTagWriteReady = DCacheBanks + 4 149 // In Main Pipe: 150 // data_write.ready -> data_write.valid * 8 banks 151 // data_write.ready -> meta_write.valid 152 // data_write.ready -> tag_write.valid 153 // data_write.ready -> err_write.valid 154 // data_write.ready -> wb.valid 155 val nDupDataWriteReady = DCacheBanks + 4 156 val nDupWbReady = DCacheBanks + 4 157 val nDupStatus = nDupTagWriteReady + nDupDataWriteReady 158 val dataWritePort = 0 159 val metaWritePort = DCacheBanks 160 val tagWritePort = metaWritePort + 1 161 val errWritePort = tagWritePort + 1 162 val wbPort = errWritePort + 1 163 164 def addr_to_dcache_bank(addr: UInt) = { 165 require(addr.getWidth >= DCacheSetOffset) 166 addr(DCacheSetOffset-1, DCacheBankOffset) 167 } 168 169 def addr_to_dcache_set(addr: UInt) = { 170 require(addr.getWidth >= DCacheAboveIndexOffset) 171 addr(DCacheAboveIndexOffset-1, DCacheSetOffset) 172 } 173 174 def get_data_of_bank(bank: Int, data: UInt) = { 175 require(data.getWidth >= (bank+1)*DCacheSRAMRowBits) 176 data(DCacheSRAMRowBits * (bank + 1) - 1, DCacheSRAMRowBits * bank) 177 } 178 179 def get_mask_of_bank(bank: Int, data: UInt) = { 180 require(data.getWidth >= (bank+1)*DCacheSRAMRowBytes) 181 data(DCacheSRAMRowBytes * (bank + 1) - 1, DCacheSRAMRowBytes * bank) 182 } 183 184 def arbiter[T <: Bundle]( 185 in: Seq[DecoupledIO[T]], 186 out: DecoupledIO[T], 187 name: Option[String] = None): Unit = { 188 val arb = Module(new Arbiter[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 def arbiter_with_pipereg[T <: Bundle]( 197 in: Seq[DecoupledIO[T]], 198 out: DecoupledIO[T], 199 name: Option[String] = None): Unit = { 200 val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size)) 201 if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") } 202 for ((a, req) <- arb.io.in.zip(in)) { 203 a <> req 204 } 205 AddPipelineReg(arb.io.out, out, false.B) 206 } 207 208 def arbiter_with_pipereg_N_dup[T <: Bundle]( 209 in: Seq[DecoupledIO[T]], 210 out: DecoupledIO[T], 211 dups: Seq[DecoupledIO[T]], 212 name: Option[String] = None): Unit = { 213 val arb = Module(new Arbiter[T](chiselTypeOf(out.bits), in.size)) 214 if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") } 215 for ((a, req) <- arb.io.in.zip(in)) { 216 a <> req 217 } 218 for (dup <- dups) { 219 AddPipelineReg(arb.io.out, dup, false.B) 220 } 221 AddPipelineReg(arb.io.out, out, false.B) 222 } 223 224 def rrArbiter[T <: Bundle]( 225 in: Seq[DecoupledIO[T]], 226 out: DecoupledIO[T], 227 name: Option[String] = None): Unit = { 228 val arb = Module(new RRArbiter[T](chiselTypeOf(out.bits), in.size)) 229 if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") } 230 for ((a, req) <- arb.io.in.zip(in)) { 231 a <> req 232 } 233 out <> arb.io.out 234 } 235 236 def fastArbiter[T <: Bundle]( 237 in: Seq[DecoupledIO[T]], 238 out: DecoupledIO[T], 239 name: Option[String] = None): Unit = { 240 val arb = Module(new FastArbiter[T](chiselTypeOf(out.bits), in.size)) 241 if (name.nonEmpty) { arb.suggestName(s"${name.get}_arb") } 242 for ((a, req) <- arb.io.in.zip(in)) { 243 a <> req 244 } 245 out <> arb.io.out 246 } 247 248 val numReplaceRespPorts = 2 249 250 require(isPow2(nSets), s"nSets($nSets) must be pow2") 251 require(isPow2(nWays), s"nWays($nWays) must be pow2") 252 require(full_divide(rowBits, wordBits), s"rowBits($rowBits) must be multiple of wordBits($wordBits)") 253 require(full_divide(beatBits, rowBits), s"beatBits($beatBits) must be multiple of rowBits($rowBits)") 254} 255 256abstract class DCacheModule(implicit p: Parameters) extends L1CacheModule 257 with HasDCacheParameters 258 259abstract class DCacheBundle(implicit p: Parameters) extends L1CacheBundle 260 with HasDCacheParameters 261 262class ReplacementAccessBundle(implicit p: Parameters) extends DCacheBundle { 263 val set = UInt(log2Up(nSets).W) 264 val way = UInt(log2Up(nWays).W) 265} 266 267class ReplacementWayReqIO(implicit p: Parameters) extends DCacheBundle { 268 val set = ValidIO(UInt(log2Up(nSets).W)) 269 val way = Input(UInt(log2Up(nWays).W)) 270} 271 272// memory request in word granularity(load, mmio, lr/sc, atomics) 273class DCacheWordReq(implicit p: Parameters) extends DCacheBundle 274{ 275 val cmd = UInt(M_SZ.W) 276 val addr = UInt(PAddrBits.W) 277 val data = UInt(DataBits.W) 278 val mask = UInt((DataBits/8).W) 279 val id = UInt(reqIdWidth.W) 280 val instrtype = UInt(sourceTypeWidth.W) 281 def dump() = { 282 XSDebug("DCacheWordReq: cmd: %x addr: %x data: %x mask: %x id: %d\n", 283 cmd, addr, data, mask, id) 284 } 285} 286 287// memory request in word granularity(store) 288class DCacheLineReq(implicit p: Parameters) extends DCacheBundle 289{ 290 val cmd = UInt(M_SZ.W) 291 val vaddr = UInt(VAddrBits.W) 292 val addr = UInt(PAddrBits.W) 293 val data = UInt((cfg.blockBytes * 8).W) 294 val mask = UInt(cfg.blockBytes.W) 295 val id = UInt(reqIdWidth.W) 296 def dump() = { 297 XSDebug("DCacheLineReq: cmd: %x addr: %x data: %x mask: %x id: %d\n", 298 cmd, addr, data, mask, id) 299 } 300 def idx: UInt = get_idx(vaddr) 301} 302 303class DCacheWordReqWithVaddr(implicit p: Parameters) extends DCacheWordReq { 304 val vaddr = UInt(VAddrBits.W) 305 val wline = Bool() 306} 307 308class BaseDCacheWordResp(implicit p: Parameters) extends DCacheBundle 309{ 310 val data = UInt(DataBits.W) 311 val id = UInt(reqIdWidth.W) 312 313 // cache req missed, send it to miss queue 314 val miss = Bool() 315 // cache miss, and failed to enter the missqueue, replay from RS is needed 316 val replay = Bool() 317 // data has been corrupted 318 val tag_error = Bool() // tag error 319 def dump() = { 320 XSDebug("DCacheWordResp: data: %x id: %d miss: %b replay: %b\n", 321 data, id, miss, replay) 322 } 323} 324 325class DCacheWordResp(implicit p: Parameters) extends BaseDCacheWordResp 326{ 327 // 1 cycle after data resp 328 val error_delayed = Bool() // all kinds of errors, include tag error 329} 330 331class BankedDCacheWordResp(implicit p: Parameters) extends DCacheWordResp 332{ 333 val bank_data = Vec(DCacheBanks, Bits(DCacheSRAMRowBits.W)) 334 val bank_oh = UInt(DCacheBanks.W) 335} 336 337class DCacheWordRespWithError(implicit p: Parameters) extends BaseDCacheWordResp 338{ 339 val error = Bool() // all kinds of errors, include tag error 340} 341 342class DCacheLineResp(implicit p: Parameters) extends DCacheBundle 343{ 344 val data = UInt((cfg.blockBytes * 8).W) 345 // cache req missed, send it to miss queue 346 val miss = Bool() 347 // cache req nacked, replay it later 348 val replay = Bool() 349 val id = UInt(reqIdWidth.W) 350 def dump() = { 351 XSDebug("DCacheLineResp: data: %x id: %d miss: %b replay: %b\n", 352 data, id, miss, replay) 353 } 354} 355 356class Refill(implicit p: Parameters) extends DCacheBundle 357{ 358 val addr = UInt(PAddrBits.W) 359 val data = UInt(l1BusDataWidth.W) 360 val error = Bool() // refilled data has been corrupted 361 // for debug usage 362 val data_raw = UInt((cfg.blockBytes * 8).W) 363 val hasdata = Bool() 364 val refill_done = Bool() 365 def dump() = { 366 XSDebug("Refill: addr: %x data: %x\n", addr, data) 367 } 368} 369 370class Release(implicit p: Parameters) extends DCacheBundle 371{ 372 val paddr = UInt(PAddrBits.W) 373 def dump() = { 374 XSDebug("Release: paddr: %x\n", paddr(PAddrBits-1, DCacheTagOffset)) 375 } 376} 377 378class DCacheWordIO(implicit p: Parameters) extends DCacheBundle 379{ 380 val req = DecoupledIO(new DCacheWordReq) 381 val resp = Flipped(DecoupledIO(new BankedDCacheWordResp)) 382} 383 384class UncacheWordIO(implicit p: Parameters) extends DCacheBundle 385{ 386 val req = DecoupledIO(new DCacheWordReq) 387 val resp = Flipped(DecoupledIO(new DCacheWordRespWithError)) 388} 389 390class AtomicsResp(implicit p: Parameters) extends DCacheBundle { 391 val data = UInt(DataBits.W) 392 val miss = Bool() 393 val miss_id = UInt(log2Up(cfg.nMissEntries).W) 394 val replay = Bool() 395 val error = Bool() 396 397 val ack_miss_queue = Bool() 398 399 val id = UInt(reqIdWidth.W) 400} 401 402class AtomicWordIO(implicit p: Parameters) extends DCacheBundle 403{ 404 val req = DecoupledIO(new MainPipeReq) 405 val resp = Flipped(ValidIO(new AtomicsResp)) 406 val block_lr = Input(Bool()) 407} 408 409// used by load unit 410class DCacheLoadIO(implicit p: Parameters) extends DCacheWordIO 411{ 412 // kill previous cycle's req 413 val s1_kill = Output(Bool()) 414 val s2_kill = Output(Bool()) 415 // cycle 0: virtual address: req.addr 416 // cycle 1: physical address: s1_paddr 417 val s1_paddr_dup_lsu = Output(UInt(PAddrBits.W)) // lsu side paddr 418 val s1_paddr_dup_dcache = Output(UInt(PAddrBits.W)) // dcache side paddr 419 val s1_disable_fast_wakeup = Input(Bool()) 420 val s1_bank_conflict = Input(Bool()) 421 // cycle 2: hit signal 422 val s2_hit = Input(Bool()) // hit signal for lsu, 423 424 // debug 425 val debug_s1_hit_way = Input(UInt(nWays.W)) 426} 427 428class DCacheLineIO(implicit p: Parameters) extends DCacheBundle 429{ 430 val req = DecoupledIO(new DCacheLineReq) 431 val resp = Flipped(DecoupledIO(new DCacheLineResp)) 432} 433 434class DCacheToSbufferIO(implicit p: Parameters) extends DCacheBundle { 435 // sbuffer will directly send request to dcache main pipe 436 val req = Flipped(Decoupled(new DCacheLineReq)) 437 438 val main_pipe_hit_resp = ValidIO(new DCacheLineResp) 439 val refill_hit_resp = ValidIO(new DCacheLineResp) 440 441 val replay_resp = ValidIO(new DCacheLineResp) 442 443 def hit_resps: Seq[ValidIO[DCacheLineResp]] = Seq(main_pipe_hit_resp, refill_hit_resp) 444} 445 446class DCacheToLsuIO(implicit p: Parameters) extends DCacheBundle { 447 val load = Vec(LoadPipelineWidth, Flipped(new DCacheLoadIO)) // for speculative load 448 val lsq = ValidIO(new Refill) // refill to load queue, wake up load misses 449 val store = new DCacheToSbufferIO // for sbuffer 450 val atomics = Flipped(new AtomicWordIO) // atomics reqs 451 val release = ValidIO(new Release) // cacheline release hint for ld-ld violation check 452} 453 454class DCacheIO(implicit p: Parameters) extends DCacheBundle { 455 val hartId = Input(UInt(8.W)) 456 val lsu = new DCacheToLsuIO 457 val csr = new L1CacheToCsrIO 458 val error = new L1CacheErrorInfo 459 val mshrFull = Output(Bool()) 460} 461 462 463class DCache()(implicit p: Parameters) extends LazyModule with HasDCacheParameters { 464 465 val clientParameters = TLMasterPortParameters.v1( 466 Seq(TLMasterParameters.v1( 467 name = "dcache", 468 sourceId = IdRange(0, nEntries + 1), 469 supportsProbe = TransferSizes(cfg.blockBytes) 470 )), 471 requestFields = cacheParams.reqFields, 472 echoFields = cacheParams.echoFields 473 ) 474 475 val clientNode = TLClientNode(Seq(clientParameters)) 476 477 lazy val module = new DCacheImp(this) 478} 479 480 481class DCacheImp(outer: DCache) extends LazyModuleImp(outer) with HasDCacheParameters with HasPerfEvents { 482 483 val io = IO(new DCacheIO) 484 485 val (bus, edge) = outer.clientNode.out.head 486 require(bus.d.bits.data.getWidth == l1BusDataWidth, "DCache: tilelink width does not match") 487 488 println("DCache:") 489 println(" DCacheSets: " + DCacheSets) 490 println(" DCacheWays: " + DCacheWays) 491 println(" DCacheBanks: " + DCacheBanks) 492 println(" DCacheSRAMRowBits: " + DCacheSRAMRowBits) 493 println(" DCacheWordOffset: " + DCacheWordOffset) 494 println(" DCacheBankOffset: " + DCacheBankOffset) 495 println(" DCacheSetOffset: " + DCacheSetOffset) 496 println(" DCacheTagOffset: " + DCacheTagOffset) 497 println(" DCacheAboveIndexOffset: " + DCacheAboveIndexOffset) 498 499 //---------------------------------------- 500 // core data structures 501 val bankedDataArray = Module(new BankedDataArray) 502 val metaArray = Module(new AsynchronousMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = 2)) 503 val errorArray = Module(new ErrorArray(readPorts = LoadPipelineWidth + 1, writePorts = 2)) // TODO: add it to meta array 504 val tagArray = Module(new DuplicatedTagArray(readPorts = LoadPipelineWidth + 1)) 505 bankedDataArray.dump() 506 507 //---------------------------------------- 508 // core modules 509 val ldu = Seq.tabulate(LoadPipelineWidth)({ i => Module(new LoadPipe(i))}) 510 // val atomicsReplayUnit = Module(new AtomicsReplayEntry) 511 val mainPipe = Module(new MainPipe) 512 val refillPipe = Module(new RefillPipe) 513 val missQueue = Module(new MissQueue(edge)) 514 val probeQueue = Module(new ProbeQueue(edge)) 515 val wb = Module(new WritebackQueue(edge)) 516 517 missQueue.io.hartId := io.hartId 518 519 val errors = ldu.map(_.io.error) ++ // load error 520 Seq(mainPipe.io.error) // store / misc error 521 io.error <> RegNext(Mux1H(errors.map(e => RegNext(e.valid) -> RegNext(e)))) 522 523 //---------------------------------------- 524 // meta array 525 val meta_read_ports = ldu.map(_.io.meta_read) ++ 526 Seq(mainPipe.io.meta_read) 527 val meta_resp_ports = ldu.map(_.io.meta_resp) ++ 528 Seq(mainPipe.io.meta_resp) 529 val meta_write_ports = Seq( 530 mainPipe.io.meta_write, 531 refillPipe.io.meta_write 532 ) 533 meta_read_ports.zip(metaArray.io.read).foreach { case (p, r) => r <> p } 534 meta_resp_ports.zip(metaArray.io.resp).foreach { case (p, r) => p := r } 535 meta_write_ports.zip(metaArray.io.write).foreach { case (p, w) => w <> p } 536 537 val error_flag_resp_ports = ldu.map(_.io.error_flag_resp) ++ 538 Seq(mainPipe.io.error_flag_resp) 539 val error_flag_write_ports = Seq( 540 mainPipe.io.error_flag_write, 541 refillPipe.io.error_flag_write 542 ) 543 meta_read_ports.zip(errorArray.io.read).foreach { case (p, r) => r <> p } 544 error_flag_resp_ports.zip(errorArray.io.resp).foreach { case (p, r) => p := r } 545 error_flag_write_ports.zip(errorArray.io.write).foreach { case (p, w) => w <> p } 546 547 //---------------------------------------- 548 // tag array 549 require(tagArray.io.read.size == (ldu.size + 1)) 550 val tag_write_intend = missQueue.io.refill_pipe_req.valid || mainPipe.io.tag_write_intend 551 assert(!RegNext(!tag_write_intend && tagArray.io.write.valid)) 552 ldu.zipWithIndex.foreach { 553 case (ld, i) => 554 tagArray.io.read(i) <> ld.io.tag_read 555 ld.io.tag_resp := tagArray.io.resp(i) 556 ld.io.tag_read.ready := !tag_write_intend 557 } 558 tagArray.io.read.last <> mainPipe.io.tag_read 559 mainPipe.io.tag_resp := tagArray.io.resp.last 560 561 val fake_tag_read_conflict_this_cycle = PopCount(ldu.map(ld=> ld.io.tag_read.valid)) 562 XSPerfAccumulate("fake_tag_read_conflict", fake_tag_read_conflict_this_cycle) 563 564 val tag_write_arb = Module(new Arbiter(new TagWriteReq, 2)) 565 tag_write_arb.io.in(0) <> refillPipe.io.tag_write 566 tag_write_arb.io.in(1) <> mainPipe.io.tag_write 567 tagArray.io.write <> tag_write_arb.io.out 568 569 //---------------------------------------- 570 // data array 571 572 val dataWriteArb = Module(new Arbiter(new L1BankedDataWriteReq, 2)) 573 dataWriteArb.io.in(0) <> refillPipe.io.data_write 574 dataWriteArb.io.in(1) <> mainPipe.io.data_write 575 576 bankedDataArray.io.write <> dataWriteArb.io.out 577 578 for (bank <- 0 until DCacheBanks) { 579 val dataWriteArb_dup = Module(new Arbiter(new L1BankedDataWriteReqCtrl, 2)) 580 dataWriteArb_dup.io.in(0).valid := refillPipe.io.data_write_dup(bank).valid 581 dataWriteArb_dup.io.in(0).bits := refillPipe.io.data_write_dup(bank).bits 582 dataWriteArb_dup.io.in(1).valid := mainPipe.io.data_write_dup(bank).valid 583 dataWriteArb_dup.io.in(1).bits := mainPipe.io.data_write_dup(bank).bits 584 585 bankedDataArray.io.write_dup(bank) <> dataWriteArb_dup.io.out 586 } 587 588 bankedDataArray.io.readline <> mainPipe.io.data_read 589 bankedDataArray.io.readline_intend := mainPipe.io.data_read_intend 590 mainPipe.io.readline_error_delayed := bankedDataArray.io.readline_error_delayed 591 mainPipe.io.data_resp := bankedDataArray.io.resp 592 593 (0 until LoadPipelineWidth).map(i => { 594 bankedDataArray.io.read(i) <> ldu(i).io.banked_data_read 595 bankedDataArray.io.read_error_delayed(i) <> ldu(i).io.read_error_delayed 596 597 ldu(i).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(i) 598 ldu(i).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(i) 599 }) 600 601 (0 until LoadPipelineWidth).map(i => { 602 ldu(i).io.banked_data_resp := bankedDataArray.io.resp 603 }) 604 605 //---------------------------------------- 606 // load pipe 607 // the s1 kill signal 608 // only lsu uses this, replay never kills 609 for (w <- 0 until LoadPipelineWidth) { 610 ldu(w).io.lsu <> io.lsu.load(w) 611 612 // replay and nack not needed anymore 613 // TODO: remove replay and nack 614 ldu(w).io.nack := false.B 615 616 ldu(w).io.disable_ld_fast_wakeup := 617 bankedDataArray.io.disable_ld_fast_wakeup(w) // load pipe fast wake up should be disabled when bank conflict 618 } 619 620 //---------------------------------------- 621 // atomics 622 // atomics not finished yet 623 // io.lsu.atomics <> atomicsReplayUnit.io.lsu 624 io.lsu.atomics.resp := RegNext(mainPipe.io.atomic_resp) 625 io.lsu.atomics.block_lr := mainPipe.io.block_lr 626 // atomicsReplayUnit.io.pipe_resp := RegNext(mainPipe.io.atomic_resp) 627 // atomicsReplayUnit.io.block_lr <> mainPipe.io.block_lr 628 629 //---------------------------------------- 630 // miss queue 631 val MissReqPortCount = LoadPipelineWidth + 1 632 val MainPipeMissReqPort = 0 633 634 // Request 635 val missReqArb = Module(new Arbiter(new MissReq, MissReqPortCount)) 636 637 missReqArb.io.in(MainPipeMissReqPort) <> mainPipe.io.miss_req 638 for (w <- 0 until LoadPipelineWidth) { missReqArb.io.in(w + 1) <> ldu(w).io.miss_req } 639 640 wb.io.miss_req.valid := missReqArb.io.out.valid 641 wb.io.miss_req.bits := missReqArb.io.out.bits.addr 642 643 // block_decoupled(missReqArb.io.out, missQueue.io.req, wb.io.block_miss_req) 644 missReqArb.io.out <> missQueue.io.req 645 when(wb.io.block_miss_req) { 646 missQueue.io.req.bits.cancel := true.B 647 missReqArb.io.out.ready := false.B 648 } 649 650 // refill to load queue 651 io.lsu.lsq <> missQueue.io.refill_to_ldq 652 653 // tilelink stuff 654 bus.a <> missQueue.io.mem_acquire 655 bus.e <> missQueue.io.mem_finish 656 missQueue.io.probe_addr := bus.b.bits.address 657 658 missQueue.io.main_pipe_resp := RegNext(mainPipe.io.atomic_resp) 659 660 //---------------------------------------- 661 // probe 662 // probeQueue.io.mem_probe <> bus.b 663 block_decoupled(bus.b, probeQueue.io.mem_probe, missQueue.io.probe_block) 664 probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block 665 probeQueue.io.update_resv_set <> mainPipe.io.update_resv_set 666 667 //---------------------------------------- 668 // mainPipe 669 // when a req enters main pipe, if it is set-conflict with replace pipe or refill pipe, 670 // block the req in main pipe 671 block_decoupled(probeQueue.io.pipe_req, mainPipe.io.probe_req, missQueue.io.refill_pipe_req.valid) 672 block_decoupled(io.lsu.store.req, mainPipe.io.store_req, refillPipe.io.req.valid) 673 674 io.lsu.store.replay_resp := RegNext(mainPipe.io.store_replay_resp) 675 io.lsu.store.main_pipe_hit_resp := mainPipe.io.store_hit_resp 676 677 arbiter_with_pipereg( 678 in = Seq(missQueue.io.main_pipe_req, io.lsu.atomics.req), 679 out = mainPipe.io.atomic_req, 680 name = Some("main_pipe_atomic_req") 681 ) 682 683 mainPipe.io.invalid_resv_set := RegNext(wb.io.req.fire && wb.io.req.bits.addr === mainPipe.io.lrsc_locked_block.bits) 684 685 //---------------------------------------- 686 // replace (main pipe) 687 val mpStatus = mainPipe.io.status 688 mainPipe.io.replace_req <> missQueue.io.replace_pipe_req 689 missQueue.io.replace_pipe_resp := mainPipe.io.replace_resp 690 691 //---------------------------------------- 692 // refill pipe 693 val refillShouldBeBlocked = (mpStatus.s1.valid && mpStatus.s1.bits.set === missQueue.io.refill_pipe_req.bits.idx) || 694 Cat(Seq(mpStatus.s2, mpStatus.s3).map(s => 695 s.valid && 696 s.bits.set === missQueue.io.refill_pipe_req.bits.idx && 697 s.bits.way_en === missQueue.io.refill_pipe_req.bits.way_en 698 )).orR 699 block_decoupled(missQueue.io.refill_pipe_req, refillPipe.io.req, refillShouldBeBlocked) 700 701 val mpStatus_dup = mainPipe.io.status_dup 702 val mq_refill_dup = missQueue.io.refill_pipe_req_dup 703 val refillShouldBeBlocked_dup = VecInit((0 until nDupStatus).map { case i => 704 mpStatus_dup(i).s1.valid && mpStatus_dup(i).s1.bits.set === mq_refill_dup(i).bits.idx || 705 Cat(Seq(mpStatus_dup(i).s2, mpStatus_dup(i).s3).map(s => 706 s.valid && 707 s.bits.set === mq_refill_dup(i).bits.idx && 708 s.bits.way_en === mq_refill_dup(i).bits.way_en 709 )).orR 710 }) 711 dontTouch(refillShouldBeBlocked_dup) 712 713 refillPipe.io.req_dup_for_data_w.zipWithIndex.foreach { case (r, i) => 714 r.bits := (mq_refill_dup.drop(dataWritePort).take(DCacheBanks))(i).bits 715 } 716 refillPipe.io.req_dup_for_meta_w.bits := mq_refill_dup(metaWritePort).bits 717 refillPipe.io.req_dup_for_tag_w.bits := mq_refill_dup(tagWritePort).bits 718 refillPipe.io.req_dup_for_err_w.bits := mq_refill_dup(errWritePort).bits 719 refillPipe.io.req_dup_for_data_w.zipWithIndex.foreach { case (r, i) => 720 r.valid := (mq_refill_dup.drop(dataWritePort).take(DCacheBanks))(i).valid && 721 !(refillShouldBeBlocked_dup.drop(dataWritePort).take(DCacheBanks))(i) 722 } 723 refillPipe.io.req_dup_for_meta_w.valid := mq_refill_dup(metaWritePort).valid && !refillShouldBeBlocked_dup(metaWritePort) 724 refillPipe.io.req_dup_for_tag_w.valid := mq_refill_dup(tagWritePort).valid && !refillShouldBeBlocked_dup(tagWritePort) 725 refillPipe.io.req_dup_for_err_w.valid := mq_refill_dup(errWritePort).valid && !refillShouldBeBlocked_dup(errWritePort) 726 727 val refillPipe_io_req_valid_dup = VecInit(mq_refill_dup.zip(refillShouldBeBlocked_dup).map( 728 x => x._1.valid && !x._2 729 )) 730 val refillPipe_io_data_write_valid_dup = VecInit(refillPipe_io_req_valid_dup.slice(0, nDupDataWriteReady)) 731 val refillPipe_io_tag_write_valid_dup = VecInit(refillPipe_io_req_valid_dup.slice(nDupDataWriteReady, nDupStatus)) 732 dontTouch(refillPipe_io_req_valid_dup) 733 dontTouch(refillPipe_io_data_write_valid_dup) 734 dontTouch(refillPipe_io_tag_write_valid_dup) 735 mainPipe.io.data_write_ready_dup := VecInit(refillPipe_io_data_write_valid_dup.map(v => !v)) 736 mainPipe.io.tag_write_ready_dup := VecInit(refillPipe_io_tag_write_valid_dup.map(v => !v)) 737 mainPipe.io.wb_ready_dup := wb.io.req_ready_dup 738 739 mq_refill_dup.zip(refillShouldBeBlocked_dup).foreach { case (r, block) => 740 r.ready := refillPipe.io.req.ready && !block 741 } 742 743 missQueue.io.refill_pipe_resp := refillPipe.io.resp 744 io.lsu.store.refill_hit_resp := RegNext(refillPipe.io.store_resp) 745 746 //---------------------------------------- 747 // wb 748 // add a queue between MainPipe and WritebackUnit to reduce MainPipe stalls due to WritebackUnit busy 749 750 wb.io.req <> mainPipe.io.wb 751 bus.c <> wb.io.mem_release 752 wb.io.release_wakeup := refillPipe.io.release_wakeup 753 wb.io.release_update := mainPipe.io.release_update 754 wb.io.probe_ttob_check_req <> mainPipe.io.probe_ttob_check_req 755 wb.io.probe_ttob_check_resp <> mainPipe.io.probe_ttob_check_resp 756 757 io.lsu.release.valid := RegNext(wb.io.req.fire()) 758 io.lsu.release.bits.paddr := RegNext(wb.io.req.bits.addr) 759 // Note: RegNext() is required by: 760 // * load queue released flag update logic 761 // * load / load violation check logic 762 // * and timing requirements 763 // CHANGE IT WITH CARE 764 765 // connect bus d 766 missQueue.io.mem_grant.valid := false.B 767 missQueue.io.mem_grant.bits := DontCare 768 769 wb.io.mem_grant.valid := false.B 770 wb.io.mem_grant.bits := DontCare 771 772 // in L1DCache, we ony expect Grant[Data] and ReleaseAck 773 bus.d.ready := false.B 774 when (bus.d.bits.opcode === TLMessages.Grant || bus.d.bits.opcode === TLMessages.GrantData) { 775 missQueue.io.mem_grant <> bus.d 776 } .elsewhen (bus.d.bits.opcode === TLMessages.ReleaseAck) { 777 wb.io.mem_grant <> bus.d 778 } .otherwise { 779 assert (!bus.d.fire()) 780 } 781 782 //---------------------------------------- 783 // replacement algorithm 784 val replacer = ReplacementPolicy.fromString(cacheParams.replacer, nWays, nSets) 785 786 val replWayReqs = ldu.map(_.io.replace_way) ++ Seq(mainPipe.io.replace_way) 787 replWayReqs.foreach{ 788 case req => 789 req.way := DontCare 790 when (req.set.valid) { req.way := replacer.way(req.set.bits) } 791 } 792 793 val replAccessReqs = ldu.map(_.io.replace_access) ++ Seq( 794 mainPipe.io.replace_access 795 ) 796 val touchWays = Seq.fill(replAccessReqs.size)(Wire(ValidIO(UInt(log2Up(nWays).W)))) 797 touchWays.zip(replAccessReqs).foreach { 798 case (w, req) => 799 w.valid := req.valid 800 w.bits := req.bits.way 801 } 802 val touchSets = replAccessReqs.map(_.bits.set) 803 replacer.access(touchSets, touchWays) 804 805 //---------------------------------------- 806 // assertions 807 // dcache should only deal with DRAM addresses 808 when (bus.a.fire()) { 809 assert(bus.a.bits.address >= 0x80000000L.U) 810 } 811 when (bus.b.fire()) { 812 assert(bus.b.bits.address >= 0x80000000L.U) 813 } 814 when (bus.c.fire()) { 815 assert(bus.c.bits.address >= 0x80000000L.U) 816 } 817 818 //---------------------------------------- 819 // utility functions 820 def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = { 821 sink.valid := source.valid && !block_signal 822 source.ready := sink.ready && !block_signal 823 sink.bits := source.bits 824 } 825 826 //---------------------------------------- 827 // Customized csr cache op support 828 val cacheOpDecoder = Module(new CSRCacheOpDecoder("dcache", CacheInstrucion.COP_ID_DCACHE)) 829 cacheOpDecoder.io.csr <> io.csr 830 bankedDataArray.io.cacheOp.req := cacheOpDecoder.io.cache.req 831 // dup cacheOp_req_valid 832 bankedDataArray.io.cacheOp_req_dup.zipWithIndex.map{ case(dup, i) => dup := cacheOpDecoder.io.cache_req_dup(i) } 833 // dup cacheOp_req_bits_opCode 834 bankedDataArray.io.cacheOp_req_bits_opCode_dup.zipWithIndex.map{ case (dup, i) => dup := cacheOpDecoder.io.cacheOp_req_bits_opCode_dup(i) } 835 836 tagArray.io.cacheOp.req := cacheOpDecoder.io.cache.req 837 // dup cacheOp_req_valid 838 tagArray.io.cacheOp_req_dup.zipWithIndex.map{ case(dup, i) => dup := cacheOpDecoder.io.cache_req_dup(i) } 839 // dup cacheOp_req_bits_opCode 840 tagArray.io.cacheOp_req_bits_opCode_dup.zipWithIndex.map{ case (dup, i) => dup := cacheOpDecoder.io.cacheOp_req_bits_opCode_dup(i) } 841 842 cacheOpDecoder.io.cache.resp.valid := bankedDataArray.io.cacheOp.resp.valid || 843 tagArray.io.cacheOp.resp.valid 844 cacheOpDecoder.io.cache.resp.bits := Mux1H(List( 845 bankedDataArray.io.cacheOp.resp.valid -> bankedDataArray.io.cacheOp.resp.bits, 846 tagArray.io.cacheOp.resp.valid -> tagArray.io.cacheOp.resp.bits, 847 )) 848 cacheOpDecoder.io.error := io.error 849 assert(!((bankedDataArray.io.cacheOp.resp.valid +& tagArray.io.cacheOp.resp.valid) > 1.U)) 850 851 //---------------------------------------- 852 // performance counters 853 val num_loads = PopCount(ldu.map(e => e.io.lsu.req.fire())) 854 XSPerfAccumulate("num_loads", num_loads) 855 856 io.mshrFull := missQueue.io.full 857 858 // performance counter 859 val ld_access = Wire(Vec(LoadPipelineWidth, missQueue.io.debug_early_replace.last.cloneType)) 860 val st_access = Wire(ld_access.last.cloneType) 861 ld_access.zip(ldu).foreach { 862 case (a, u) => 863 a.valid := RegNext(u.io.lsu.req.fire()) && !u.io.lsu.s1_kill 864 a.bits.idx := RegNext(get_idx(u.io.lsu.req.bits.addr)) 865 a.bits.tag := get_tag(u.io.lsu.s1_paddr_dup_dcache) 866 } 867 st_access.valid := RegNext(mainPipe.io.store_req.fire()) 868 st_access.bits.idx := RegNext(get_idx(mainPipe.io.store_req.bits.vaddr)) 869 st_access.bits.tag := RegNext(get_tag(mainPipe.io.store_req.bits.addr)) 870 val access_info = ld_access.toSeq ++ Seq(st_access) 871 val early_replace = RegNext(missQueue.io.debug_early_replace) 872 val access_early_replace = access_info.map { 873 case acc => 874 Cat(early_replace.map { 875 case r => 876 acc.valid && r.valid && 877 acc.bits.tag === r.bits.tag && 878 acc.bits.idx === r.bits.idx 879 }) 880 } 881 XSPerfAccumulate("access_early_replace", PopCount(Cat(access_early_replace))) 882 883 val perfEvents = (Seq(wb, mainPipe, missQueue, probeQueue) ++ ldu).flatMap(_.getPerfEvents) 884 generatePerfEvent() 885} 886 887class AMOHelper() extends ExtModule { 888 val clock = IO(Input(Clock())) 889 val enable = IO(Input(Bool())) 890 val cmd = IO(Input(UInt(5.W))) 891 val addr = IO(Input(UInt(64.W))) 892 val wdata = IO(Input(UInt(64.W))) 893 val mask = IO(Input(UInt(8.W))) 894 val rdata = IO(Output(UInt(64.W))) 895} 896 897class DCacheWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter { 898 899 val useDcache = coreParams.dcacheParametersOpt.nonEmpty 900 val clientNode = if (useDcache) TLIdentityNode() else null 901 val dcache = if (useDcache) LazyModule(new DCache()) else null 902 if (useDcache) { 903 clientNode := dcache.clientNode 904 } 905 906 lazy val module = new LazyModuleImp(this) with HasPerfEvents { 907 val io = IO(new DCacheIO) 908 val perfEvents = if (!useDcache) { 909 // a fake dcache which uses dpi-c to access memory, only for debug usage! 910 val fake_dcache = Module(new FakeDCache()) 911 io <> fake_dcache.io 912 Seq() 913 } 914 else { 915 io <> dcache.module.io 916 dcache.module.getPerfEvents 917 } 918 generatePerfEvent() 919 } 920} 921