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