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 val data_dup_0 = UInt(DataBits.W) 330} 331 332class DCacheWordRespWithError(implicit p: Parameters) extends BaseDCacheWordResp 333{ 334 val error = Bool() // all kinds of errors, include tag error 335} 336 337class DCacheLineResp(implicit p: Parameters) extends DCacheBundle 338{ 339 val data = UInt((cfg.blockBytes * 8).W) 340 // cache req missed, send it to miss queue 341 val miss = Bool() 342 // cache req nacked, replay it later 343 val replay = Bool() 344 val id = UInt(reqIdWidth.W) 345 def dump() = { 346 XSDebug("DCacheLineResp: data: %x id: %d miss: %b replay: %b\n", 347 data, id, miss, replay) 348 } 349} 350 351class Refill(implicit p: Parameters) extends DCacheBundle 352{ 353 val addr = UInt(PAddrBits.W) 354 val data = UInt(l1BusDataWidth.W) 355 val error = Bool() // refilled data has been corrupted 356 // for debug usage 357 val data_raw = UInt((cfg.blockBytes * 8).W) 358 val hasdata = Bool() 359 val refill_done = Bool() 360 def dump() = { 361 XSDebug("Refill: addr: %x data: %x\n", addr, data) 362 } 363} 364 365class Release(implicit p: Parameters) extends DCacheBundle 366{ 367 val paddr = UInt(PAddrBits.W) 368 def dump() = { 369 XSDebug("Release: paddr: %x\n", paddr(PAddrBits-1, DCacheTagOffset)) 370 } 371} 372 373class DCacheWordIO(implicit p: Parameters) extends DCacheBundle 374{ 375 val req = DecoupledIO(new DCacheWordReq) 376 val resp = Flipped(DecoupledIO(new DCacheWordResp)) 377} 378 379class UncacheWordIO(implicit p: Parameters) extends DCacheBundle 380{ 381 val req = DecoupledIO(new DCacheWordReq) 382 val resp = Flipped(DecoupledIO(new DCacheWordRespWithError)) 383} 384 385class AtomicsResp(implicit p: Parameters) extends DCacheBundle { 386 val data = UInt(DataBits.W) 387 val miss = Bool() 388 val miss_id = UInt(log2Up(cfg.nMissEntries).W) 389 val replay = Bool() 390 val error = Bool() 391 392 val ack_miss_queue = Bool() 393 394 val id = UInt(reqIdWidth.W) 395} 396 397class AtomicWordIO(implicit p: Parameters) extends DCacheBundle 398{ 399 val req = DecoupledIO(new MainPipeReq) 400 val resp = Flipped(ValidIO(new AtomicsResp)) 401 val block_lr = Input(Bool()) 402} 403 404// used by load unit 405class DCacheLoadIO(implicit p: Parameters) extends DCacheWordIO 406{ 407 // kill previous cycle's req 408 val s1_kill = Output(Bool()) 409 val s2_kill = Output(Bool()) 410 // cycle 0: virtual address: req.addr 411 // cycle 1: physical address: s1_paddr 412 val s1_paddr_dup_lsu = Output(UInt(PAddrBits.W)) // lsu side paddr 413 val s1_paddr_dup_dcache = Output(UInt(PAddrBits.W)) // dcache side paddr 414 val s1_disable_fast_wakeup = Input(Bool()) 415 val s1_bank_conflict = Input(Bool()) 416 // cycle 2: hit signal 417 val s2_hit = Input(Bool()) // hit signal for lsu, 418 419 // debug 420 val debug_s1_hit_way = Input(UInt(nWays.W)) 421} 422 423class DCacheLineIO(implicit p: Parameters) extends DCacheBundle 424{ 425 val req = DecoupledIO(new DCacheLineReq) 426 val resp = Flipped(DecoupledIO(new DCacheLineResp)) 427} 428 429class DCacheToSbufferIO(implicit p: Parameters) extends DCacheBundle { 430 // sbuffer will directly send request to dcache main pipe 431 val req = Flipped(Decoupled(new DCacheLineReq)) 432 433 val main_pipe_hit_resp = ValidIO(new DCacheLineResp) 434 val refill_hit_resp = ValidIO(new DCacheLineResp) 435 436 val replay_resp = ValidIO(new DCacheLineResp) 437 438 def hit_resps: Seq[ValidIO[DCacheLineResp]] = Seq(main_pipe_hit_resp, refill_hit_resp) 439} 440 441class DCacheToLsuIO(implicit p: Parameters) extends DCacheBundle { 442 val load = Vec(LoadPipelineWidth, Flipped(new DCacheLoadIO)) // for speculative load 443 val lsq = ValidIO(new Refill) // refill to load queue, wake up load misses 444 val store = new DCacheToSbufferIO // for sbuffer 445 val atomics = Flipped(new AtomicWordIO) // atomics reqs 446 val release = ValidIO(new Release) // cacheline release hint for ld-ld violation check 447} 448 449class DCacheIO(implicit p: Parameters) extends DCacheBundle { 450 val hartId = Input(UInt(8.W)) 451 val lsu = new DCacheToLsuIO 452 val csr = new L1CacheToCsrIO 453 val error = new L1CacheErrorInfo 454 val mshrFull = Output(Bool()) 455} 456 457 458class DCache()(implicit p: Parameters) extends LazyModule with HasDCacheParameters { 459 460 val clientParameters = TLMasterPortParameters.v1( 461 Seq(TLMasterParameters.v1( 462 name = "dcache", 463 sourceId = IdRange(0, nEntries + 1), 464 supportsProbe = TransferSizes(cfg.blockBytes) 465 )), 466 requestFields = cacheParams.reqFields, 467 echoFields = cacheParams.echoFields 468 ) 469 470 val clientNode = TLClientNode(Seq(clientParameters)) 471 472 lazy val module = new DCacheImp(this) 473} 474 475 476class DCacheImp(outer: DCache) extends LazyModuleImp(outer) with HasDCacheParameters with HasPerfEvents { 477 478 val io = IO(new DCacheIO) 479 480 val (bus, edge) = outer.clientNode.out.head 481 require(bus.d.bits.data.getWidth == l1BusDataWidth, "DCache: tilelink width does not match") 482 483 println("DCache:") 484 println(" DCacheSets: " + DCacheSets) 485 println(" DCacheWays: " + DCacheWays) 486 println(" DCacheBanks: " + DCacheBanks) 487 println(" DCacheSRAMRowBits: " + DCacheSRAMRowBits) 488 println(" DCacheWordOffset: " + DCacheWordOffset) 489 println(" DCacheBankOffset: " + DCacheBankOffset) 490 println(" DCacheSetOffset: " + DCacheSetOffset) 491 println(" DCacheTagOffset: " + DCacheTagOffset) 492 println(" DCacheAboveIndexOffset: " + DCacheAboveIndexOffset) 493 494 //---------------------------------------- 495 // core data structures 496 val bankedDataArray = Module(new BankedDataArray) 497 val metaArray = Module(new AsynchronousMetaArray(readPorts = LoadPipelineWidth + 1, writePorts = 2)) 498 val errorArray = Module(new ErrorArray(readPorts = LoadPipelineWidth + 1, writePorts = 2)) // TODO: add it to meta array 499 val tagArray = Module(new DuplicatedTagArray(readPorts = LoadPipelineWidth + 1)) 500 bankedDataArray.dump() 501 502 //---------------------------------------- 503 // core modules 504 val ldu = Seq.tabulate(LoadPipelineWidth)({ i => Module(new LoadPipe(i))}) 505 // val atomicsReplayUnit = Module(new AtomicsReplayEntry) 506 val mainPipe = Module(new MainPipe) 507 val refillPipe = Module(new RefillPipe) 508 val missQueue = Module(new MissQueue(edge)) 509 val probeQueue = Module(new ProbeQueue(edge)) 510 val wb = Module(new WritebackQueue(edge)) 511 512 missQueue.io.hartId := io.hartId 513 514 val errors = ldu.map(_.io.error) ++ // load error 515 Seq(mainPipe.io.error) // store / misc error 516 io.error <> RegNext(Mux1H(errors.map(e => RegNext(e.valid) -> RegNext(e)))) 517 518 //---------------------------------------- 519 // meta array 520 val meta_read_ports = ldu.map(_.io.meta_read) ++ 521 Seq(mainPipe.io.meta_read) 522 val meta_resp_ports = ldu.map(_.io.meta_resp) ++ 523 Seq(mainPipe.io.meta_resp) 524 val meta_write_ports = Seq( 525 mainPipe.io.meta_write, 526 refillPipe.io.meta_write 527 ) 528 meta_read_ports.zip(metaArray.io.read).foreach { case (p, r) => r <> p } 529 meta_resp_ports.zip(metaArray.io.resp).foreach { case (p, r) => p := r } 530 meta_write_ports.zip(metaArray.io.write).foreach { case (p, w) => w <> p } 531 532 val error_flag_resp_ports = ldu.map(_.io.error_flag_resp) ++ 533 Seq(mainPipe.io.error_flag_resp) 534 val error_flag_write_ports = Seq( 535 mainPipe.io.error_flag_write, 536 refillPipe.io.error_flag_write 537 ) 538 meta_read_ports.zip(errorArray.io.read).foreach { case (p, r) => r <> p } 539 error_flag_resp_ports.zip(errorArray.io.resp).foreach { case (p, r) => p := r } 540 error_flag_write_ports.zip(errorArray.io.write).foreach { case (p, w) => w <> p } 541 542 //---------------------------------------- 543 // tag array 544 require(tagArray.io.read.size == (ldu.size + 1)) 545 val tag_write_intend = missQueue.io.refill_pipe_req.valid || mainPipe.io.tag_write_intend 546 assert(!RegNext(!tag_write_intend && tagArray.io.write.valid)) 547 ldu.zipWithIndex.foreach { 548 case (ld, i) => 549 tagArray.io.read(i) <> ld.io.tag_read 550 ld.io.tag_resp := tagArray.io.resp(i) 551 ld.io.tag_read.ready := !tag_write_intend 552 } 553 tagArray.io.read.last <> mainPipe.io.tag_read 554 mainPipe.io.tag_resp := tagArray.io.resp.last 555 556 val fake_tag_read_conflict_this_cycle = PopCount(ldu.map(ld=> ld.io.tag_read.valid)) 557 XSPerfAccumulate("fake_tag_read_conflict", fake_tag_read_conflict_this_cycle) 558 559 val tag_write_arb = Module(new Arbiter(new TagWriteReq, 2)) 560 tag_write_arb.io.in(0) <> refillPipe.io.tag_write 561 tag_write_arb.io.in(1) <> mainPipe.io.tag_write 562 tagArray.io.write <> tag_write_arb.io.out 563 564 //---------------------------------------- 565 // data array 566 567 val dataWriteArb = Module(new Arbiter(new L1BankedDataWriteReq, 2)) 568 dataWriteArb.io.in(0) <> refillPipe.io.data_write 569 dataWriteArb.io.in(1) <> mainPipe.io.data_write 570 571 bankedDataArray.io.write <> dataWriteArb.io.out 572 573 for (bank <- 0 until DCacheBanks) { 574 val dataWriteArb_dup = Module(new Arbiter(new L1BankedDataWriteReqCtrl, 2)) 575 dataWriteArb_dup.io.in(0).valid := refillPipe.io.data_write_dup(bank).valid 576 dataWriteArb_dup.io.in(0).bits := refillPipe.io.data_write_dup(bank).bits 577 dataWriteArb_dup.io.in(1).valid := mainPipe.io.data_write_dup(bank).valid 578 dataWriteArb_dup.io.in(1).bits := mainPipe.io.data_write_dup(bank).bits 579 580 bankedDataArray.io.write_dup(bank) <> dataWriteArb_dup.io.out 581 } 582 583 bankedDataArray.io.readline <> mainPipe.io.data_read 584 bankedDataArray.io.readline_intend := mainPipe.io.data_read_intend 585 mainPipe.io.readline_error_delayed := bankedDataArray.io.readline_error_delayed 586 mainPipe.io.data_resp := bankedDataArray.io.resp 587 588 (0 until LoadPipelineWidth).map(i => { 589 bankedDataArray.io.read(i) <> ldu(i).io.banked_data_read 590 bankedDataArray.io.read_error_delayed(i) <> ldu(i).io.read_error_delayed 591 592 ldu(i).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(i) 593 ldu(i).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(i) 594 }) 595 596 (0 until (LoadPipelineWidth / 2)).map(i => { 597 ldu(i).io.banked_data_resp := bankedDataArray.io.resp 598 }) 599 600 ((LoadPipelineWidth / 2) until LoadPipelineWidth).map(i => { 601 ldu(i).io.banked_data_resp := bankedDataArray.io.resp_dup_0 602 }) 603 604 //---------------------------------------- 605 // load pipe 606 // the s1 kill signal 607 // only lsu uses this, replay never kills 608 for (w <- 0 until LoadPipelineWidth) { 609 ldu(w).io.lsu <> io.lsu.load(w) 610 611 // replay and nack not needed anymore 612 // TODO: remove replay and nack 613 ldu(w).io.nack := false.B 614 615 ldu(w).io.disable_ld_fast_wakeup := 616 bankedDataArray.io.disable_ld_fast_wakeup(w) // load pipe fast wake up should be disabled when bank conflict 617 } 618 619 //---------------------------------------- 620 // atomics 621 // atomics not finished yet 622 // io.lsu.atomics <> atomicsReplayUnit.io.lsu 623 io.lsu.atomics.resp := RegNext(mainPipe.io.atomic_resp) 624 io.lsu.atomics.block_lr := mainPipe.io.block_lr 625 // atomicsReplayUnit.io.pipe_resp := RegNext(mainPipe.io.atomic_resp) 626 // atomicsReplayUnit.io.block_lr <> mainPipe.io.block_lr 627 628 //---------------------------------------- 629 // miss queue 630 val MissReqPortCount = LoadPipelineWidth + 1 631 val MainPipeMissReqPort = 0 632 633 // Request 634 val missReqArb = Module(new Arbiter(new MissReq, MissReqPortCount)) 635 636 missReqArb.io.in(MainPipeMissReqPort) <> mainPipe.io.miss_req 637 for (w <- 0 until LoadPipelineWidth) { missReqArb.io.in(w + 1) <> ldu(w).io.miss_req } 638 639 wb.io.miss_req.valid := missReqArb.io.out.valid 640 wb.io.miss_req.bits := missReqArb.io.out.bits.addr 641 642 // block_decoupled(missReqArb.io.out, missQueue.io.req, wb.io.block_miss_req) 643 missReqArb.io.out <> missQueue.io.req 644 when(wb.io.block_miss_req) { 645 missQueue.io.req.bits.cancel := true.B 646 missReqArb.io.out.ready := false.B 647 } 648 649 // refill to load queue 650 io.lsu.lsq <> missQueue.io.refill_to_ldq 651 652 // tilelink stuff 653 bus.a <> missQueue.io.mem_acquire 654 bus.e <> missQueue.io.mem_finish 655 missQueue.io.probe_addr := bus.b.bits.address 656 657 missQueue.io.main_pipe_resp := RegNext(mainPipe.io.atomic_resp) 658 659 //---------------------------------------- 660 // probe 661 // probeQueue.io.mem_probe <> bus.b 662 block_decoupled(bus.b, probeQueue.io.mem_probe, missQueue.io.probe_block) 663 probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block 664 probeQueue.io.update_resv_set <> mainPipe.io.update_resv_set 665 666 //---------------------------------------- 667 // mainPipe 668 // when a req enters main pipe, if it is set-conflict with replace pipe or refill pipe, 669 // block the req in main pipe 670 block_decoupled(probeQueue.io.pipe_req, mainPipe.io.probe_req, missQueue.io.refill_pipe_req.valid) 671 block_decoupled(io.lsu.store.req, mainPipe.io.store_req, refillPipe.io.req.valid) 672 673 io.lsu.store.replay_resp := RegNext(mainPipe.io.store_replay_resp) 674 io.lsu.store.main_pipe_hit_resp := mainPipe.io.store_hit_resp 675 676 arbiter_with_pipereg( 677 in = Seq(missQueue.io.main_pipe_req, io.lsu.atomics.req), 678 out = mainPipe.io.atomic_req, 679 name = Some("main_pipe_atomic_req") 680 ) 681 682 mainPipe.io.invalid_resv_set := RegNext(wb.io.req.fire && wb.io.req.bits.addr === mainPipe.io.lrsc_locked_block.bits) 683 684 //---------------------------------------- 685 // replace (main pipe) 686 val mpStatus = mainPipe.io.status 687 mainPipe.io.replace_req <> missQueue.io.replace_pipe_req 688 missQueue.io.replace_pipe_resp := mainPipe.io.replace_resp 689 690 //---------------------------------------- 691 // refill pipe 692 val refillShouldBeBlocked = (mpStatus.s1.valid && mpStatus.s1.bits.set === missQueue.io.refill_pipe_req.bits.idx) || 693 Cat(Seq(mpStatus.s2, mpStatus.s3).map(s => 694 s.valid && 695 s.bits.set === missQueue.io.refill_pipe_req.bits.idx && 696 s.bits.way_en === missQueue.io.refill_pipe_req.bits.way_en 697 )).orR 698 block_decoupled(missQueue.io.refill_pipe_req, refillPipe.io.req, refillShouldBeBlocked) 699 700 val mpStatus_dup = mainPipe.io.status_dup 701 val mq_refill_dup = missQueue.io.refill_pipe_req_dup 702 val refillShouldBeBlocked_dup = VecInit((0 until nDupStatus).map { case i => 703 mpStatus_dup(i).s1.valid && mpStatus_dup(i).s1.bits.set === mq_refill_dup(i).bits.idx || 704 Cat(Seq(mpStatus_dup(i).s2, mpStatus_dup(i).s3).map(s => 705 s.valid && 706 s.bits.set === mq_refill_dup(i).bits.idx && 707 s.bits.way_en === mq_refill_dup(i).bits.way_en 708 )).orR 709 }) 710 dontTouch(refillShouldBeBlocked_dup) 711 712 refillPipe.io.req_dup_for_data_w.zipWithIndex.foreach { case (r, i) => 713 r.bits := (mq_refill_dup.drop(dataWritePort).take(DCacheBanks))(i).bits 714 } 715 refillPipe.io.req_dup_for_meta_w.bits := mq_refill_dup(metaWritePort).bits 716 refillPipe.io.req_dup_for_tag_w.bits := mq_refill_dup(tagWritePort).bits 717 refillPipe.io.req_dup_for_err_w.bits := mq_refill_dup(errWritePort).bits 718 refillPipe.io.req_dup_for_data_w.zipWithIndex.foreach { case (r, i) => 719 r.valid := (mq_refill_dup.drop(dataWritePort).take(DCacheBanks))(i).valid && 720 !(refillShouldBeBlocked_dup.drop(dataWritePort).take(DCacheBanks))(i) 721 } 722 refillPipe.io.req_dup_for_meta_w.valid := mq_refill_dup(metaWritePort).valid && !refillShouldBeBlocked_dup(metaWritePort) 723 refillPipe.io.req_dup_for_tag_w.valid := mq_refill_dup(tagWritePort).valid && !refillShouldBeBlocked_dup(tagWritePort) 724 refillPipe.io.req_dup_for_err_w.valid := mq_refill_dup(errWritePort).valid && !refillShouldBeBlocked_dup(errWritePort) 725 726 val refillPipe_io_req_valid_dup = VecInit(mq_refill_dup.zip(refillShouldBeBlocked_dup).map( 727 x => x._1.valid && !x._2 728 )) 729 val refillPipe_io_data_write_valid_dup = VecInit(refillPipe_io_req_valid_dup.slice(0, nDupDataWriteReady)) 730 val refillPipe_io_tag_write_valid_dup = VecInit(refillPipe_io_req_valid_dup.slice(nDupDataWriteReady, nDupStatus)) 731 dontTouch(refillPipe_io_req_valid_dup) 732 dontTouch(refillPipe_io_data_write_valid_dup) 733 dontTouch(refillPipe_io_tag_write_valid_dup) 734 mainPipe.io.data_write_ready_dup := VecInit(refillPipe_io_data_write_valid_dup.map(v => !v)) 735 mainPipe.io.tag_write_ready_dup := VecInit(refillPipe_io_tag_write_valid_dup.map(v => !v)) 736 mainPipe.io.wb_ready_dup := wb.io.req_ready_dup 737 738 mq_refill_dup.zip(refillShouldBeBlocked_dup).foreach { case (r, block) => 739 r.ready := refillPipe.io.req.ready && !block 740 } 741 742 missQueue.io.refill_pipe_resp := refillPipe.io.resp 743 io.lsu.store.refill_hit_resp := RegNext(refillPipe.io.store_resp) 744 745 //---------------------------------------- 746 // wb 747 // add a queue between MainPipe and WritebackUnit to reduce MainPipe stalls due to WritebackUnit busy 748 749 wb.io.req <> mainPipe.io.wb 750 bus.c <> wb.io.mem_release 751 wb.io.release_wakeup := refillPipe.io.release_wakeup 752 wb.io.release_update := mainPipe.io.release_update 753 754 io.lsu.release.valid := RegNext(wb.io.req.fire()) 755 io.lsu.release.bits.paddr := RegNext(wb.io.req.bits.addr) 756 // Note: RegNext() is required by: 757 // * load queue released flag update logic 758 // * load / load violation check logic 759 // * and timing requirements 760 // CHANGE IT WITH CARE 761 762 // connect bus d 763 missQueue.io.mem_grant.valid := false.B 764 missQueue.io.mem_grant.bits := DontCare 765 766 wb.io.mem_grant.valid := false.B 767 wb.io.mem_grant.bits := DontCare 768 769 // in L1DCache, we ony expect Grant[Data] and ReleaseAck 770 bus.d.ready := false.B 771 when (bus.d.bits.opcode === TLMessages.Grant || bus.d.bits.opcode === TLMessages.GrantData) { 772 missQueue.io.mem_grant <> bus.d 773 } .elsewhen (bus.d.bits.opcode === TLMessages.ReleaseAck) { 774 wb.io.mem_grant <> bus.d 775 } .otherwise { 776 assert (!bus.d.fire()) 777 } 778 779 //---------------------------------------- 780 // replacement algorithm 781 val replacer = ReplacementPolicy.fromString(cacheParams.replacer, nWays, nSets) 782 783 val replWayReqs = ldu.map(_.io.replace_way) ++ Seq(mainPipe.io.replace_way) 784 replWayReqs.foreach{ 785 case req => 786 req.way := DontCare 787 when (req.set.valid) { req.way := replacer.way(req.set.bits) } 788 } 789 790 val replAccessReqs = ldu.map(_.io.replace_access) ++ Seq( 791 mainPipe.io.replace_access 792 ) 793 val touchWays = Seq.fill(replAccessReqs.size)(Wire(ValidIO(UInt(log2Up(nWays).W)))) 794 touchWays.zip(replAccessReqs).foreach { 795 case (w, req) => 796 w.valid := req.valid 797 w.bits := req.bits.way 798 } 799 val touchSets = replAccessReqs.map(_.bits.set) 800 replacer.access(touchSets, touchWays) 801 802 //---------------------------------------- 803 // assertions 804 // dcache should only deal with DRAM addresses 805 when (bus.a.fire()) { 806 assert(bus.a.bits.address >= 0x80000000L.U) 807 } 808 when (bus.b.fire()) { 809 assert(bus.b.bits.address >= 0x80000000L.U) 810 } 811 when (bus.c.fire()) { 812 assert(bus.c.bits.address >= 0x80000000L.U) 813 } 814 815 //---------------------------------------- 816 // utility functions 817 def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = { 818 sink.valid := source.valid && !block_signal 819 source.ready := sink.ready && !block_signal 820 sink.bits := source.bits 821 } 822 823 //---------------------------------------- 824 // Customized csr cache op support 825 val cacheOpDecoder = Module(new CSRCacheOpDecoder("dcache", CacheInstrucion.COP_ID_DCACHE)) 826 cacheOpDecoder.io.csr <> io.csr 827 bankedDataArray.io.cacheOp.req := cacheOpDecoder.io.cache.req 828 // dup cacheOp_req_valid 829 bankedDataArray.io.cacheOp_req_dup.zipWithIndex.map{ case(dup, i) => dup := cacheOpDecoder.io.cache_req_dup(i) } 830 // dup cacheOp_req_bits_opCode 831 bankedDataArray.io.cacheOp_req_bits_opCode_dup.zipWithIndex.map{ case (dup, i) => dup := cacheOpDecoder.io.cacheOp_req_bits_opCode_dup(i) } 832 833 tagArray.io.cacheOp.req := cacheOpDecoder.io.cache.req 834 // dup cacheOp_req_valid 835 tagArray.io.cacheOp_req_dup.zipWithIndex.map{ case(dup, i) => dup := cacheOpDecoder.io.cache_req_dup(i) } 836 // dup cacheOp_req_bits_opCode 837 tagArray.io.cacheOp_req_bits_opCode_dup.zipWithIndex.map{ case (dup, i) => dup := cacheOpDecoder.io.cacheOp_req_bits_opCode_dup(i) } 838 839 cacheOpDecoder.io.cache.resp.valid := bankedDataArray.io.cacheOp.resp.valid || 840 tagArray.io.cacheOp.resp.valid 841 cacheOpDecoder.io.cache.resp.bits := Mux1H(List( 842 bankedDataArray.io.cacheOp.resp.valid -> bankedDataArray.io.cacheOp.resp.bits, 843 tagArray.io.cacheOp.resp.valid -> tagArray.io.cacheOp.resp.bits, 844 )) 845 cacheOpDecoder.io.error := io.error 846 assert(!((bankedDataArray.io.cacheOp.resp.valid +& tagArray.io.cacheOp.resp.valid) > 1.U)) 847 848 //---------------------------------------- 849 // performance counters 850 val num_loads = PopCount(ldu.map(e => e.io.lsu.req.fire())) 851 XSPerfAccumulate("num_loads", num_loads) 852 853 io.mshrFull := missQueue.io.full 854 855 // performance counter 856 val ld_access = Wire(Vec(LoadPipelineWidth, missQueue.io.debug_early_replace.last.cloneType)) 857 val st_access = Wire(ld_access.last.cloneType) 858 ld_access.zip(ldu).foreach { 859 case (a, u) => 860 a.valid := RegNext(u.io.lsu.req.fire()) && !u.io.lsu.s1_kill 861 a.bits.idx := RegNext(get_idx(u.io.lsu.req.bits.addr)) 862 a.bits.tag := get_tag(u.io.lsu.s1_paddr_dup_dcache) 863 } 864 st_access.valid := RegNext(mainPipe.io.store_req.fire()) 865 st_access.bits.idx := RegNext(get_idx(mainPipe.io.store_req.bits.vaddr)) 866 st_access.bits.tag := RegNext(get_tag(mainPipe.io.store_req.bits.addr)) 867 val access_info = ld_access.toSeq ++ Seq(st_access) 868 val early_replace = RegNext(missQueue.io.debug_early_replace) 869 val access_early_replace = access_info.map { 870 case acc => 871 Cat(early_replace.map { 872 case r => 873 acc.valid && r.valid && 874 acc.bits.tag === r.bits.tag && 875 acc.bits.idx === r.bits.idx 876 }) 877 } 878 XSPerfAccumulate("access_early_replace", PopCount(Cat(access_early_replace))) 879 880 val perfEvents = (Seq(wb, mainPipe, missQueue, probeQueue) ++ ldu).flatMap(_.getPerfEvents) 881 generatePerfEvent() 882} 883 884class AMOHelper() extends ExtModule { 885 val clock = IO(Input(Clock())) 886 val enable = IO(Input(Bool())) 887 val cmd = IO(Input(UInt(5.W))) 888 val addr = IO(Input(UInt(64.W))) 889 val wdata = IO(Input(UInt(64.W))) 890 val mask = IO(Input(UInt(8.W))) 891 val rdata = IO(Output(UInt(64.W))) 892} 893 894class DCacheWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter { 895 896 val useDcache = coreParams.dcacheParametersOpt.nonEmpty 897 val clientNode = if (useDcache) TLIdentityNode() else null 898 val dcache = if (useDcache) LazyModule(new DCache()) else null 899 if (useDcache) { 900 clientNode := dcache.clientNode 901 } 902 903 lazy val module = new LazyModuleImp(this) with HasPerfEvents { 904 val io = IO(new DCacheIO) 905 val perfEvents = if (!useDcache) { 906 // a fake dcache which uses dpi-c to access memory, only for debug usage! 907 val fake_dcache = Module(new FakeDCache()) 908 io <> fake_dcache.io 909 Seq() 910 } 911 else { 912 io <> dcache.module.io 913 dcache.module.getPerfEvents 914 } 915 generatePerfEvent() 916 } 917} 918