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 28import system.L1CacheErrorInfo 29import device.RAMHelper 30import huancun.{AliasField, AliasKey, PreferCacheField, PrefetchField, DirtyField} 31 32// DCache specific parameters 33case class DCacheParameters 34( 35 nSets: Int = 256, 36 nWays: Int = 8, 37 rowBits: Int = 128, 38 tagECC: Option[String] = None, 39 dataECC: Option[String] = None, 40 replacer: Option[String] = Some("random"), 41 nMissEntries: Int = 1, 42 nProbeEntries: Int = 1, 43 nReleaseEntries: Int = 1, 44 nStoreReplayEntries: Int = 1, 45 nMMIOEntries: Int = 1, 46 nMMIOs: Int = 1, 47 blockBytes: Int = 64, 48 alwaysReleaseData: Boolean = true 49) extends L1CacheParameters { 50 // if sets * blockBytes > 4KB(page size), 51 // cache alias will happen, 52 // we need to avoid this by recoding additional bits in L2 cache 53 val setBytes = nSets * blockBytes 54 val aliasBitsOpt = if(setBytes > pageSize) Some(log2Ceil(setBytes / pageSize)) else None 55 val reqFields: Seq[BundleFieldBase] = Seq( 56 PrefetchField(), 57 PreferCacheField() 58 ) ++ aliasBitsOpt.map(AliasField) 59 val echoFields: Seq[BundleFieldBase] = Seq(DirtyField()) 60 61 def tagCode: Code = Code.fromString(tagECC) 62 63 def dataCode: Code = Code.fromString(dataECC) 64} 65 66// Physical Address 67// -------------------------------------- 68// | Physical Tag | PIndex | Offset | 69// -------------------------------------- 70// | 71// DCacheTagOffset 72// 73// Virtual Address 74// -------------------------------------- 75// | Above index | Set | Bank | Offset | 76// -------------------------------------- 77// | | | | 78// | | | DCacheWordOffset 79// | | DCacheBankOffset 80// | DCacheSetOffset 81// DCacheAboveIndexOffset 82 83// Default DCache size = 64 sets * 8 ways * 8 banks * 8 Byte = 32K Byte 84 85trait HasDCacheParameters extends HasL1CacheParameters { 86 val cacheParams = dcacheParameters 87 val cfg = cacheParams 88 89 def encWordBits = cacheParams.dataCode.width(wordBits) 90 91 def encRowBits = encWordBits * rowWords // for DuplicatedDataArray only 92 def eccBits = encWordBits - wordBits 93 94 def lrscCycles = LRSCCycles // ISA requires 16-insn LRSC sequences to succeed 95 def lrscBackoff = 3 // disallow LRSC reacquisition briefly 96 def blockProbeAfterGrantCycles = 8 // give the processor some time to issue a request after a grant 97 98 def nSourceType = 3 99 def sourceTypeWidth = log2Up(nSourceType) 100 def LOAD_SOURCE = 0 101 def STORE_SOURCE = 1 102 def AMO_SOURCE = 2 103 def SOFT_PREFETCH = 3 104 105 // each source use a id to distinguish its multiple reqs 106 def reqIdWidth = 64 107 108 // banked dcache support 109 val DCacheSets = cacheParams.nSets 110 val DCacheWays = cacheParams.nWays 111 val DCacheBanks = 8 112 val DCacheSRAMRowBits = 64 // hardcoded 113 114 val DCacheLineBits = DCacheSRAMRowBits * DCacheBanks * DCacheWays * DCacheSets 115 val DCacheLineBytes = DCacheLineBits / 8 116 val DCacheLineWords = DCacheLineBits / 64 // TODO 117 118 val DCacheSameVPAddrLength = 12 119 120 val DCacheSRAMRowBytes = DCacheSRAMRowBits / 8 121 val DCacheWordOffset = 0 122 val DCacheBankOffset = DCacheWordOffset + log2Up(DCacheSRAMRowBytes) 123 val DCacheSetOffset = DCacheBankOffset + log2Up(DCacheBanks) 124 val DCacheAboveIndexOffset = DCacheSetOffset + log2Up(DCacheSets) 125 val DCacheTagOffset = DCacheAboveIndexOffset min DCacheSameVPAddrLength 126 val DCacheIndexOffset = DCacheBankOffset 127 128 def addr_to_dcache_bank(addr: UInt) = { 129 require(addr.getWidth >= DCacheSetOffset) 130 addr(DCacheSetOffset-1, DCacheBankOffset) 131 } 132 133 def addr_to_dcache_set(addr: UInt) = { 134 require(addr.getWidth >= DCacheAboveIndexOffset) 135 addr(DCacheAboveIndexOffset-1, DCacheSetOffset) 136 } 137 138 def get_data_of_bank(bank: Int, data: UInt) = { 139 require(data.getWidth >= (bank+1)*DCacheSRAMRowBits) 140 data(DCacheSRAMRowBits * (bank + 1) - 1, DCacheSRAMRowBits * bank) 141 } 142 143 def get_mask_of_bank(bank: Int, data: UInt) = { 144 require(data.getWidth >= (bank+1)*DCacheSRAMRowBytes) 145 data(DCacheSRAMRowBytes * (bank + 1) - 1, DCacheSRAMRowBytes * bank) 146 } 147 148 require(isPow2(nSets), s"nSets($nSets) must be pow2") 149 require(isPow2(nWays), s"nWays($nWays) must be pow2") 150 require(full_divide(rowBits, wordBits), s"rowBits($rowBits) must be multiple of wordBits($wordBits)") 151 require(full_divide(beatBits, rowBits), s"beatBits($beatBits) must be multiple of rowBits($rowBits)") 152} 153 154abstract class DCacheModule(implicit p: Parameters) extends L1CacheModule 155 with HasDCacheParameters 156 157abstract class DCacheBundle(implicit p: Parameters) extends L1CacheBundle 158 with HasDCacheParameters 159 160class ReplacementAccessBundle(implicit p: Parameters) extends DCacheBundle { 161 val set = UInt(log2Up(nSets).W) 162 val way = UInt(log2Up(nWays).W) 163} 164 165// memory request in word granularity(load, mmio, lr/sc, atomics) 166class DCacheWordReq(implicit p: Parameters) extends DCacheBundle 167{ 168 val cmd = UInt(M_SZ.W) 169 val addr = UInt(PAddrBits.W) 170 val data = UInt(DataBits.W) 171 val mask = UInt((DataBits/8).W) 172 val id = UInt(reqIdWidth.W) 173 val instrtype = UInt(sourceTypeWidth.W) 174 def dump() = { 175 XSDebug("DCacheWordReq: cmd: %x addr: %x data: %x mask: %x id: %d\n", 176 cmd, addr, data, mask, id) 177 } 178} 179 180// memory request in word granularity(store) 181class DCacheLineReq(implicit p: Parameters) extends DCacheBundle 182{ 183 val cmd = UInt(M_SZ.W) 184 val vaddr = UInt(VAddrBits.W) 185 val addr = UInt(PAddrBits.W) 186 val data = UInt((cfg.blockBytes * 8).W) 187 val mask = UInt(cfg.blockBytes.W) 188 val id = UInt(reqIdWidth.W) 189 def dump() = { 190 XSDebug("DCacheLineReq: cmd: %x addr: %x data: %x mask: %x id: %d\n", 191 cmd, addr, data, mask, id) 192 } 193} 194 195class DCacheWordReqWithVaddr(implicit p: Parameters) extends DCacheWordReq { 196 val vaddr = UInt(VAddrBits.W) 197} 198 199class DCacheWordResp(implicit p: Parameters) extends DCacheBundle 200{ 201 val data = UInt(DataBits.W) 202 // cache req missed, send it to miss queue 203 val miss = Bool() 204 // cache req nacked, replay it later 205 val miss_enter = Bool() 206 // cache miss, and enter the missqueue successfully. just for softprefetch 207 val replay = Bool() 208 val id = UInt(reqIdWidth.W) 209 def dump() = { 210 XSDebug("DCacheWordResp: data: %x id: %d miss: %b replay: %b\n", 211 data, id, miss, replay) 212 } 213} 214 215class DCacheLineResp(implicit p: Parameters) extends DCacheBundle 216{ 217 val data = UInt((cfg.blockBytes * 8).W) 218 // cache req missed, send it to miss queue 219 val miss = Bool() 220 // cache req nacked, replay it later 221 val replay = Bool() 222 val id = UInt(reqIdWidth.W) 223 def dump() = { 224 XSDebug("DCacheLineResp: data: %x id: %d miss: %b replay: %b\n", 225 data, id, miss, replay) 226 } 227} 228 229class Refill(implicit p: Parameters) extends DCacheBundle 230{ 231 val addr = UInt(PAddrBits.W) 232 val data = UInt(l1BusDataWidth.W) 233 // for debug usage 234 val data_raw = UInt((cfg.blockBytes * 8).W) 235 val hasdata = Bool() 236 val refill_done = Bool() 237 def dump() = { 238 XSDebug("Refill: addr: %x data: %x\n", addr, data) 239 } 240} 241 242class DCacheWordIO(implicit p: Parameters) extends DCacheBundle 243{ 244 val req = DecoupledIO(new DCacheWordReq) 245 val resp = Flipped(DecoupledIO(new DCacheWordResp)) 246} 247 248class DCacheWordIOWithVaddr(implicit p: Parameters) extends DCacheBundle 249{ 250 val req = DecoupledIO(new DCacheWordReqWithVaddr) 251 val resp = Flipped(DecoupledIO(new DCacheWordResp)) 252} 253 254// used by load unit 255class DCacheLoadIO(implicit p: Parameters) extends DCacheWordIO 256{ 257 // kill previous cycle's req 258 val s1_kill = Output(Bool()) 259 // cycle 0: virtual address: req.addr 260 // cycle 1: physical address: s1_paddr 261 val s1_paddr = Output(UInt(PAddrBits.W)) 262 val s1_hit_way = Input(UInt(nWays.W)) 263 val s1_disable_fast_wakeup = Input(Bool()) 264 val s1_bank_conflict = Input(Bool()) 265} 266 267class DCacheLineIO(implicit p: Parameters) extends DCacheBundle 268{ 269 val req = DecoupledIO(new DCacheLineReq) 270 val resp = Flipped(DecoupledIO(new DCacheLineResp)) 271} 272 273class DCacheToLsuIO(implicit p: Parameters) extends DCacheBundle { 274 val load = Vec(LoadPipelineWidth, Flipped(new DCacheLoadIO)) // for speculative load 275 val lsq = ValidIO(new Refill) // refill to load queue, wake up load misses 276 val store = Flipped(new DCacheLineIO) // for sbuffer 277 val atomics = Flipped(new DCacheWordIOWithVaddr) // atomics reqs 278} 279 280class DCacheIO(implicit p: Parameters) extends DCacheBundle { 281 val lsu = new DCacheToLsuIO 282 val error = new L1CacheErrorInfo 283 val mshrFull = Output(Bool()) 284} 285 286 287class DCache()(implicit p: Parameters) extends LazyModule with HasDCacheParameters { 288 289 val clientParameters = TLMasterPortParameters.v1( 290 Seq(TLMasterParameters.v1( 291 name = "dcache", 292 sourceId = IdRange(0, cfg.nMissEntries+1), 293 supportsProbe = TransferSizes(cfg.blockBytes) 294 )), 295 requestFields = cacheParams.reqFields, 296 echoFields = cacheParams.echoFields 297 ) 298 299 val clientNode = TLClientNode(Seq(clientParameters)) 300 301 lazy val module = new DCacheImp(this) 302} 303 304 305class DCacheImp(outer: DCache) extends LazyModuleImp(outer) with HasDCacheParameters { 306 307 val io = IO(new DCacheIO) 308 309 val (bus, edge) = outer.clientNode.out.head 310 require(bus.d.bits.data.getWidth == l1BusDataWidth, "DCache: tilelink width does not match") 311 312 println("DCache:") 313 println(" DCacheSets: " + DCacheSets) 314 println(" DCacheWays: " + DCacheWays) 315 println(" DCacheBanks: " + DCacheBanks) 316 println(" DCacheSRAMRowBits: " + DCacheSRAMRowBits) 317 println(" DCacheWordOffset: " + DCacheWordOffset) 318 println(" DCacheBankOffset: " + DCacheBankOffset) 319 println(" DCacheSetOffset: " + DCacheSetOffset) 320 println(" DCacheTagOffset: " + DCacheTagOffset) 321 println(" DCacheAboveIndexOffset: " + DCacheAboveIndexOffset) 322 323 //---------------------------------------- 324 // core data structures 325 val bankedDataArray = Module(new BankedDataArray) 326 val metaArray = Module(new DuplicatedMetaArray(numReadPorts = 3)) 327 bankedDataArray.dump() 328 329 val errors = bankedDataArray.io.errors ++ metaArray.io.errors 330 io.error <> RegNext(Mux1H(errors.map(e => e.ecc_error.valid -> e))) 331 // assert(!io.error.ecc_error.valid) 332 333 //---------------------------------------- 334 // core modules 335 val ldu = Seq.tabulate(LoadPipelineWidth)({ i => Module(new LoadPipe(i))}) 336 val storeReplayUnit = Module(new StoreReplayQueue) 337 val atomicsReplayUnit = Module(new AtomicsReplayEntry) 338 339 val mainPipe = Module(new MainPipe) 340 val missQueue = Module(new MissQueue(edge)) 341 val probeQueue = Module(new ProbeQueue(edge)) 342 val wb = Module(new WritebackQueue(edge)) 343 344 345 //---------------------------------------- 346 // meta array 347 val MetaWritePortCount = 1 348 val MainPipeMetaWritePort = 0 349 metaArray.io.write <> mainPipe.io.meta_write 350 351 // MainPipe contend MetaRead with Load 0 352 // give priority to MainPipe 353 val MetaReadPortCount = 2 354 val MainPipeMetaReadPort = 0 355 val LoadPipeMetaReadPort = 1 356 357 metaArray.io.read(LoadPipelineWidth) <> mainPipe.io.meta_read 358 mainPipe.io.meta_resp <> metaArray.io.resp(LoadPipelineWidth) 359 360 for (w <- 0 until LoadPipelineWidth) { 361 metaArray.io.read(w) <> ldu(w).io.meta_read 362 ldu(w).io.meta_resp <> metaArray.io.resp(w) 363 } 364 365 //---------------------------------------- 366 // data array 367 368 bankedDataArray.io.write <> mainPipe.io.banked_data_write 369 bankedDataArray.io.read(0) <> ldu(0).io.banked_data_read 370 bankedDataArray.io.read(1) <> ldu(1).io.banked_data_read 371 bankedDataArray.io.readline <> mainPipe.io.banked_data_read 372 373 ldu(0).io.banked_data_resp := bankedDataArray.io.resp 374 ldu(1).io.banked_data_resp := bankedDataArray.io.resp 375 mainPipe.io.banked_data_resp := bankedDataArray.io.resp 376 377 ldu(0).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(0) 378 ldu(1).io.bank_conflict_fast := bankedDataArray.io.bank_conflict_fast(1) 379 ldu(0).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(0) 380 ldu(1).io.bank_conflict_slow := bankedDataArray.io.bank_conflict_slow(1) 381 382 //---------------------------------------- 383 // load pipe 384 // the s1 kill signal 385 // only lsu uses this, replay never kills 386 for (w <- 0 until LoadPipelineWidth) { 387 ldu(w).io.lsu <> io.lsu.load(w) 388 389 // replay and nack not needed anymore 390 // TODO: remove replay and nack 391 ldu(w).io.nack := false.B 392 393 ldu(w).io.disable_ld_fast_wakeup := 394 mainPipe.io.disable_ld_fast_wakeup(w) || 395 bankedDataArray.io.bank_conflict_fast(w) // load pipe fast wake up should be disabled when bank conflict 396 } 397 398 //---------------------------------------- 399 // store pipe and store miss queue 400 storeReplayUnit.io.lsu <> io.lsu.store 401 402 //---------------------------------------- 403 // atomics 404 // atomics not finished yet 405 io.lsu.atomics <> atomicsReplayUnit.io.lsu 406 407 //---------------------------------------- 408 // miss queue 409 val MissReqPortCount = LoadPipelineWidth + 1 410 val MainPipeMissReqPort = 0 411 412 // Request 413 val missReqArb = Module(new RRArbiter(new MissReq, MissReqPortCount)) 414 415 missReqArb.io.in(MainPipeMissReqPort) <> mainPipe.io.miss_req 416 for (w <- 0 until LoadPipelineWidth) { missReqArb.io.in(w + 1) <> ldu(w).io.miss_req } 417 418 wb.io.miss_req.valid := missReqArb.io.out.valid 419 wb.io.miss_req.bits := missReqArb.io.out.bits.addr 420 421 block_decoupled(missReqArb.io.out, missQueue.io.req, wb.io.block_miss_req) 422 423 // refill to load queue 424 io.lsu.lsq <> missQueue.io.refill 425 426 // tilelink stuff 427 bus.a <> missQueue.io.mem_acquire 428 bus.e <> missQueue.io.mem_finish 429 missQueue.io.probe_req := bus.b.bits.address 430 431 //---------------------------------------- 432 // probe 433 // probeQueue.io.mem_probe <> bus.b 434 block_decoupled(bus.b, probeQueue.io.mem_probe, missQueue.io.probe_block) 435 436 //---------------------------------------- 437 // mainPipe 438 val MainPipeReqPortCount = 4 439 val MissMainPipeReqPort = 0 440 val StoreMainPipeReqPort = 1 441 val AtomicsMainPipeReqPort = 2 442 val ProbeMainPipeReqPort = 3 443 444 val mainPipeReqArb = Module(new RRArbiter(new MainPipeReq, MainPipeReqPortCount)) 445 mainPipeReqArb.io.in(MissMainPipeReqPort) <> missQueue.io.pipe_req 446 mainPipeReqArb.io.in(StoreMainPipeReqPort) <> storeReplayUnit.io.pipe_req 447 mainPipeReqArb.io.in(AtomicsMainPipeReqPort) <> atomicsReplayUnit.io.pipe_req 448 mainPipeReqArb.io.in(ProbeMainPipeReqPort) <> probeQueue.io.pipe_req 449 450 // add a stage to break the Arbiter bits.addr to ready path 451 val mainPipeReq_valid = RegInit(false.B) 452 val mainPipeReq_fire = mainPipeReq_valid && mainPipe.io.req.ready 453 val mainPipeReq_req = RegEnable(mainPipeReqArb.io.out.bits, mainPipeReqArb.io.out.fire()) 454 455 mainPipeReqArb.io.out.ready := mainPipeReq_fire || !mainPipeReq_valid 456 mainPipe.io.req.valid := mainPipeReq_valid 457 mainPipe.io.req.bits := mainPipeReq_req 458 459 when (mainPipeReqArb.io.out.fire()) { mainPipeReq_valid := true.B } 460 when (!mainPipeReqArb.io.out.fire() && mainPipeReq_fire) { mainPipeReq_valid := false.B } 461 462 missQueue.io.pipe_resp <> mainPipe.io.miss_resp 463 storeReplayUnit.io.pipe_resp <> mainPipe.io.store_resp 464 atomicsReplayUnit.io.pipe_resp <> mainPipe.io.amo_resp 465 466 probeQueue.io.lrsc_locked_block <> mainPipe.io.lrsc_locked_block 467 468 for(i <- 0 until LoadPipelineWidth) { 469 mainPipe.io.replace_access(i) <> ldu(i).io.replace_access 470 } 471 472 //---------------------------------------- 473 // wb 474 // add a queue between MainPipe and WritebackUnit to reduce MainPipe stalls due to WritebackUnit busy 475 wb.io.req <> mainPipe.io.wb_req 476 bus.c <> wb.io.mem_release 477 478 // connect bus d 479 missQueue.io.mem_grant.valid := false.B 480 missQueue.io.mem_grant.bits := DontCare 481 482 wb.io.mem_grant.valid := false.B 483 wb.io.mem_grant.bits := DontCare 484 485 // in L1DCache, we ony expect Grant[Data] and ReleaseAck 486 bus.d.ready := false.B 487 when (bus.d.bits.opcode === TLMessages.Grant || bus.d.bits.opcode === TLMessages.GrantData) { 488 missQueue.io.mem_grant <> bus.d 489 } .elsewhen (bus.d.bits.opcode === TLMessages.ReleaseAck) { 490 wb.io.mem_grant <> bus.d 491 } .otherwise { 492 assert (!bus.d.fire()) 493 } 494 495 //---------------------------------------- 496 // assertions 497 // dcache should only deal with DRAM addresses 498 when (bus.a.fire()) { 499 assert(bus.a.bits.address >= 0x80000000L.U) 500 } 501 when (bus.b.fire()) { 502 assert(bus.b.bits.address >= 0x80000000L.U) 503 } 504 when (bus.c.fire()) { 505 assert(bus.c.bits.address >= 0x80000000L.U) 506 } 507 508 //---------------------------------------- 509 // utility functions 510 def block_decoupled[T <: Data](source: DecoupledIO[T], sink: DecoupledIO[T], block_signal: Bool) = { 511 sink.valid := source.valid && !block_signal 512 source.ready := sink.ready && !block_signal 513 sink.bits := source.bits 514 } 515 516 //---------------------------------------- 517 // performance counters 518 val num_loads = PopCount(ldu.map(e => e.io.lsu.req.fire())) 519 XSPerfAccumulate("num_loads", num_loads) 520 521 io.mshrFull := missQueue.io.full 522} 523 524class AMOHelper() extends ExtModule { 525 val clock = IO(Input(Clock())) 526 val enable = IO(Input(Bool())) 527 val cmd = IO(Input(UInt(5.W))) 528 val addr = IO(Input(UInt(64.W))) 529 val wdata = IO(Input(UInt(64.W))) 530 val mask = IO(Input(UInt(8.W))) 531 val rdata = IO(Output(UInt(64.W))) 532} 533 534 535class DCacheWrapper()(implicit p: Parameters) extends LazyModule with HasXSParameter { 536 537 val useDcache = coreParams.dcacheParametersOpt.nonEmpty 538 val clientNode = if (useDcache) TLIdentityNode() else null 539 val dcache = if (useDcache) LazyModule(new DCache()) else null 540 if (useDcache) { 541 clientNode := dcache.clientNode 542 } 543 544 lazy val module = new LazyModuleImp(this) { 545 val io = IO(new DCacheIO) 546 if (!useDcache) { 547 // a fake dcache which uses dpi-c to access memory, only for debug usage! 548 val fake_dcache = Module(new FakeDCache()) 549 io <> fake_dcache.io 550 } 551 else { 552 io <> dcache.module.io 553 } 554 } 555} 556