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