1/*************************************************************************************** 2* Copyright (c) 2024 Beijing Institute of Open Source Chip (BOSC) 3* Copyright (c) 2020-2024 Institute of Computing Technology, Chinese Academy of Sciences 4* Copyright (c) 2020-2021 Peng Cheng Laboratory 5* 6* XiangShan is licensed under Mulan PSL v2. 7* You can use this software according to the terms and conditions of the Mulan PSL v2. 8* You may obtain a copy of Mulan PSL v2 at: 9* http://license.coscl.org.cn/MulanPSL2 10* 11* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, 12* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, 13* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. 14* 15* See the Mulan PSL v2 for more details. 16***************************************************************************************/ 17 18package top 19 20import chisel3._ 21import chisel3.util._ 22import chisel3.experimental.dataview._ 23import difftest.DifftestModule 24import xiangshan._ 25import utils._ 26import huancun.{HCCacheParameters, HCCacheParamsKey, HuanCun, PrefetchRecv, TPmetaResp} 27import coupledL2.EnableCHI 28import coupledL2.tl2chi.CHILogger 29import openLLC.{OpenLLC, OpenLLCParamKey, OpenNCB} 30import openLLC.TargetBinder._ 31import cc.xiangshan.openncb._ 32import utility._ 33import utility.sram.SramBroadcastBundle 34import system._ 35import device._ 36import chisel3.stage.ChiselGeneratorAnnotation 37import org.chipsalliance.cde.config._ 38import freechips.rocketchip.diplomacy._ 39import freechips.rocketchip.tile._ 40import freechips.rocketchip.tilelink._ 41import freechips.rocketchip.interrupts._ 42import freechips.rocketchip.amba.axi4._ 43import freechips.rocketchip.jtag.JTAGIO 44import chisel3.experimental.{annotate, ChiselAnnotation} 45import sifive.enterprise.firrtl.NestedPrefixModulesAnnotation 46import scala.collection.mutable.{Map} 47 48abstract class BaseXSSoc()(implicit p: Parameters) extends LazyModule 49 with BindingScope 50{ 51 // val misc = LazyModule(new SoCMisc()) 52 lazy val dts = DTS(bindingTree) 53 lazy val json = JSON(bindingTree) 54} 55 56class XSTop()(implicit p: Parameters) extends BaseXSSoc() with HasSoCParameter 57{ 58 val nocMisc = if (enableCHI) Some(LazyModule(new MemMisc())) else None 59 val socMisc = if (!enableCHI) Some(LazyModule(new SoCMisc())) else None 60 val misc: MemMisc = if (enableCHI) nocMisc.get else socMisc.get 61 62 ResourceBinding { 63 val width = ResourceInt(2) 64 val model = "xiangshan," + os.read(os.resource / "publishVersion") 65 val compatible = "freechips,rocketchip-unknown" 66 Resource(ResourceAnchors.root, "model").bind(ResourceString(model)) 67 Resource(ResourceAnchors.root, "compat").bind(ResourceString(compatible + "-dev")) 68 Resource(ResourceAnchors.soc, "compat").bind(ResourceString(compatible + "-soc")) 69 Resource(ResourceAnchors.root, "width").bind(width) 70 Resource(ResourceAnchors.soc, "width").bind(width) 71 Resource(ResourceAnchors.cpus, "width").bind(ResourceInt(1)) 72 def bindManagers(xbar: TLNexusNode) = { 73 ManagerUnification(xbar.edges.in.head.manager.managers).foreach{ manager => 74 manager.resources.foreach(r => r.bind(manager.toResource)) 75 } 76 } 77 if (!enableCHI) { 78 bindManagers(misc.l3_xbar.get.asInstanceOf[TLNexusNode]) 79 bindManagers(misc.peripheralXbar.get.asInstanceOf[TLNexusNode]) 80 } 81 } 82 83 println(s"FPGASoC cores: $NumCores banks: $L3NBanks block size: $L3BlockSize bus size: $L3OuterBusWidth") 84 85 val core_with_l2 = tiles.map(coreParams => 86 LazyModule(new XSTile()(p.alter((site, here, up) => { 87 case XSCoreParamsKey => coreParams 88 case PerfCounterOptionsKey => up(PerfCounterOptionsKey).copy(perfDBHartID = coreParams.HartId) 89 }))) 90 ) 91 92 val l3cacheOpt = soc.L3CacheParamsOpt.map(l3param => 93 LazyModule(new HuanCun()(new Config((_, _, _) => { 94 case HCCacheParamsKey => l3param.copy( 95 hartIds = tiles.map(_.HartId), 96 FPGAPlatform = debugOpts.FPGAPlatform 97 ) 98 case MaxHartIdBits => p(MaxHartIdBits) 99 case LogUtilsOptionsKey => p(LogUtilsOptionsKey) 100 case PerfCounterOptionsKey => p(PerfCounterOptionsKey) 101 }))) 102 ) 103 104 val chi_llcBridge_opt = Option.when(enableCHI)( 105 LazyModule(new OpenNCB()(p.alter((site, here, up) => { 106 case NCBParametersKey => new NCBParameters( 107 outstandingDepth = 64, 108 axiMasterOrder = EnumAXIMasterOrder.WriteAddress, 109 readCompDMT = false, 110 writeCancelable = false, 111 writeNoError = true, 112 axiBurstAlwaysIncr = true, 113 chiDataCheck = EnumCHIDataCheck.OddParity 114 ) 115 }))) 116 ) 117 118 val chi_mmioBridge_opt = Seq.fill(NumCores)(Option.when(enableCHI)( 119 LazyModule(new OpenNCB()(p.alter((site, here, up) => { 120 case NCBParametersKey => new NCBParameters( 121 outstandingDepth = 32, 122 axiMasterOrder = EnumAXIMasterOrder.None, 123 readCompDMT = false, 124 writeCancelable = false, 125 writeNoError = true, 126 asEndpoint = false, 127 acceptOrderEndpoint = true, 128 acceptMemAttrDevice = true, 129 readReceiptAfterAcception = true, 130 axiBurstAlwaysIncr = true, 131 chiDataCheck = EnumCHIDataCheck.OddParity 132 ) 133 }))) 134 )) 135 136 // receive all prefetch req from cores 137 val memblock_pf_recv_nodes: Seq[Option[BundleBridgeSink[PrefetchRecv]]] = core_with_l2.map(_.core_l3_pf_port).map{ 138 x => x.map(_ => BundleBridgeSink(Some(() => new PrefetchRecv))) 139 } 140 141 val l3_pf_sender_opt = soc.L3CacheParamsOpt.getOrElse(HCCacheParameters()).prefetch match { 142 case Some(pf) => Some(BundleBridgeSource(() => new PrefetchRecv)) 143 case None => None 144 } 145 val nmiIntNode = IntSourceNode(IntSourcePortSimple(1, NumCores, (new NonmaskableInterruptIO).elements.size)) 146 val nmi = InModuleBody(nmiIntNode.makeIOs()) 147 148 for (i <- 0 until NumCores) { 149 core_with_l2(i).clint_int_node := misc.clint.intnode 150 core_with_l2(i).plic_int_node :*= misc.plic.intnode 151 core_with_l2(i).debug_int_node := misc.debugModule.debug.dmOuter.dmOuter.intnode 152 core_with_l2(i).nmi_int_node := nmiIntNode 153 misc.plic.intnode := IntBuffer() := core_with_l2(i).beu_int_source 154 if (!enableCHI) { 155 misc.peripheral_ports.get(i) := core_with_l2(i).tl_uncache 156 } 157 core_with_l2(i).memory_port.foreach(port => (misc.core_to_l3_ports.get)(i) :=* port) 158 memblock_pf_recv_nodes(i).map(recv => { 159 println(s"Connecting Core_${i}'s L1 pf source to L3!") 160 recv := core_with_l2(i).core_l3_pf_port.get 161 }) 162 misc.debugModuleXbarOpt.foreach(_ := core_with_l2(i).sep_dm_opt.get) 163 } 164 165 l3cacheOpt.map(_.ctlnode.map(_ := misc.peripheralXbar.get)) 166 l3cacheOpt.map(_.intnode.map(int => { 167 misc.plic.intnode := IntBuffer() := int 168 })) 169 170 val core_rst_nodes = if(l3cacheOpt.nonEmpty && l3cacheOpt.get.rst_nodes.nonEmpty){ 171 l3cacheOpt.get.rst_nodes.get 172 } else { 173 core_with_l2.map(_ => BundleBridgeSource(() => Reset())) 174 } 175 176 core_rst_nodes.zip(core_with_l2.map(_.core_reset_sink)).foreach({ 177 case (source, sink) => sink := source 178 }) 179 180 l3cacheOpt match { 181 case Some(l3) => 182 misc.l3_out :*= l3.node :*= misc.l3_banked_xbar.get 183 l3.pf_recv_node.map(recv => { 184 println("Connecting L1 prefetcher to L3!") 185 recv := l3_pf_sender_opt.get 186 }) 187 l3.tpmeta_recv_node.foreach(recv => { 188 for ((core, i) <- core_with_l2.zipWithIndex) { 189 println(s"Connecting core_$i\'s L2 TPmeta request to L3!") 190 recv := core.core_l3_tpmeta_source_port.get 191 } 192 }) 193 l3.tpmeta_send_node.foreach(send => { 194 val broadcast = LazyModule(new ValidIOBroadcast[TPmetaResp]()) 195 broadcast.node := send 196 for ((core, i) <- core_with_l2.zipWithIndex) { 197 println(s"Connecting core_$i\'s L2 TPmeta response to L3!") 198 core.core_l3_tpmeta_sink_port.get := broadcast.node 199 } 200 }) 201 case None => 202 } 203 204 chi_llcBridge_opt match { 205 case Some(ncb) => 206 misc.soc_xbar.get := ncb.axi4node 207 case None => 208 } 209 210 chi_mmioBridge_opt.foreach { e => 211 e match { 212 case Some(ncb) => 213 misc.soc_xbar.get := ncb.axi4node 214 case None => 215 } 216 } 217 218 class XSTopImp(wrapper: LazyModule) extends LazyRawModuleImp(wrapper) { 219 soc.XSTopPrefix.foreach { prefix => 220 val mod = this.toNamed 221 annotate(new ChiselAnnotation { 222 def toFirrtl = NestedPrefixModulesAnnotation(mod, prefix, true) 223 }) 224 } 225 226 FileRegisters.add("dts", dts) 227 FileRegisters.add("graphml", graphML) 228 FileRegisters.add("json", json) 229 FileRegisters.add("plusArgs", freechips.rocketchip.util.PlusArgArtefacts.serialize_cHeader()) 230 231 val dma = socMisc.map(m => IO(Flipped(new VerilogAXI4Record(m.dma.elts.head.params)))) 232 val peripheral = IO(new VerilogAXI4Record(misc.peripheral.elts.head.params)) 233 val memory = IO(new VerilogAXI4Record(misc.memory.elts.head.params)) 234 235 socMisc match { 236 case Some(m) => 237 m.dma.elements.head._2 <> dma.get.viewAs[AXI4Bundle] 238 dontTouch(dma.get) 239 case None => 240 } 241 242 memory.viewAs[AXI4Bundle] <> misc.memory.elements.head._2 243 peripheral.viewAs[AXI4Bundle] <> misc.peripheral.elements.head._2 244 245 val io = IO(new Bundle { 246 val clock = Input(Clock()) 247 val reset = Input(AsyncReset()) 248 val sram_config = Input(UInt(16.W)) 249 val extIntrs = Input(UInt(NrExtIntr.W)) 250 val pll0_lock = Input(Bool()) 251 val pll0_ctrl = Output(Vec(6, UInt(32.W))) 252 val systemjtag = new Bundle { 253 val jtag = Flipped(new JTAGIO(hasTRSTn = false)) 254 val reset = Input(AsyncReset()) // No reset allowed on top 255 val mfr_id = Input(UInt(11.W)) 256 val part_number = Input(UInt(16.W)) 257 val version = Input(UInt(4.W)) 258 } 259 val debug_reset = Output(Bool()) 260 val rtc_clock = Input(Bool()) 261 val cacheable_check = new TLPMAIO() 262 val riscv_halt = Output(Vec(NumCores, Bool())) 263 val riscv_critical_error = Output(Vec(NumCores, Bool())) 264 val riscv_rst_vec = Input(Vec(NumCores, UInt(soc.PAddrBits.W))) 265 val traceCoreInterface = Vec(NumCores, new Bundle { 266 val fromEncoder = Input(new Bundle { 267 val enable = Bool() 268 val stall = Bool() 269 }) 270 val toEncoder = Output(new Bundle { 271 val cause = UInt(TraceCauseWidth.W) 272 val tval = UInt(TraceTvalWidth.W) 273 val priv = UInt(TracePrivWidth.W) 274 val iaddr = UInt((TraceTraceGroupNum * TraceIaddrWidth).W) 275 val itype = UInt((TraceTraceGroupNum * TraceItypeWidth).W) 276 val iretire = UInt((TraceTraceGroupNum * TraceIretireWidthCompressed).W) 277 val ilastsize = UInt((TraceTraceGroupNum * TraceIlastsizeWidth).W) 278 }) 279 }) 280 }) 281 282 val reset_sync = withClockAndReset(io.clock, io.reset) { ResetGen() } 283 val jtag_reset_sync = withClockAndReset(io.systemjtag.jtag.TCK, io.systemjtag.reset) { ResetGen() } 284 val chi_openllc_opt = Option.when(enableCHI)( 285 withClockAndReset(io.clock, io.reset) { 286 Module(new OpenLLC()(p.alter((site, here, up) => { 287 case OpenLLCParamKey => soc.OpenLLCParamsOpt.get.copy( 288 hartIds = tiles.map(_.HartId), 289 FPGAPlatform = debugOpts.FPGAPlatform 290 ) 291 }))) 292 } 293 ) 294 295 // override LazyRawModuleImp's clock and reset 296 childClock := io.clock 297 childReset := reset_sync 298 299 // output 300 io.debug_reset := misc.module.debug_module_io.debugIO.ndreset 301 302 // input 303 dontTouch(io) 304 dontTouch(memory) 305 misc.module.ext_intrs := io.extIntrs 306 misc.module.rtc_clock := io.rtc_clock 307 misc.module.pll0_lock := io.pll0_lock 308 misc.module.cacheable_check <> io.cacheable_check 309 310 io.pll0_ctrl <> misc.module.pll0_ctrl 311 312 val msiInfo = WireInit(0.U.asTypeOf(ValidIO(new MsiInfoBundle))) 313 314 315 for ((core, i) <- core_with_l2.zipWithIndex) { 316 core.module.io.hartId := i.U 317 core.module.io.msiInfo := msiInfo 318 core.module.io.clintTime := misc.module.clintTime 319 io.riscv_halt(i) := core.module.io.cpu_halt 320 io.riscv_critical_error(i) := core.module.io.cpu_crtical_error 321 // trace Interface 322 val traceInterface = core.module.io.traceCoreInterface 323 traceInterface.fromEncoder := io.traceCoreInterface(i).fromEncoder 324 io.traceCoreInterface(i).toEncoder.priv := traceInterface.toEncoder.priv 325 io.traceCoreInterface(i).toEncoder.cause := traceInterface.toEncoder.trap.cause 326 io.traceCoreInterface(i).toEncoder.tval := traceInterface.toEncoder.trap.tval 327 io.traceCoreInterface(i).toEncoder.iaddr := VecInit(traceInterface.toEncoder.groups.map(_.bits.iaddr)).asUInt 328 io.traceCoreInterface(i).toEncoder.itype := VecInit(traceInterface.toEncoder.groups.map(_.bits.itype)).asUInt 329 io.traceCoreInterface(i).toEncoder.iretire := VecInit(traceInterface.toEncoder.groups.map(_.bits.iretire)).asUInt 330 io.traceCoreInterface(i).toEncoder.ilastsize := VecInit(traceInterface.toEncoder.groups.map(_.bits.ilastsize)).asUInt 331 332 core.module.io.dft.foreach(dontTouch(_) := 0.U.asTypeOf(new SramBroadcastBundle)) 333 core.module.io.dft_reset.foreach(dontTouch(_) := 0.U.asTypeOf(new DFTResetSignals)) 334 core.module.io.reset_vector := io.riscv_rst_vec(i) 335 } 336 337 withClockAndReset(io.clock, io.reset) { 338 Option.when(enableCHI)(true.B).foreach { _ => 339 for ((core, i) <- core_with_l2.zipWithIndex) { 340 val mmioLogger = CHILogger(s"L2[${i}]_MMIO", true) 341 val llcLogger = CHILogger(s"L2[${i}]_LLC", true) 342 dontTouch(core.module.io.chi.get) 343 bind( 344 route( 345 core.module.io.chi.get, Map((AddressSet(0x0L, 0x00007fffffffL), NumCores + i)) ++ AddressSet(0x0L, 346 0xffffffffffffL).subtract(AddressSet(0x0L, 0x00007fffffffL)).map(addr => (addr, NumCores * 2)).toMap 347 ), 348 Map((NumCores + i) -> mmioLogger.io.up, (NumCores * 2) -> llcLogger.io.up) 349 ) 350 chi_mmioBridge_opt(i).get.module.io.chi.connect(mmioLogger.io.down) 351 chi_openllc_opt.get.io.rn(i) <> llcLogger.io.down 352 require(core.module.io.chi.get.getWidth == llcLogger.io.up.getWidth) 353 require(llcLogger.io.down.getWidth == chi_openllc_opt.get.io.rn(i).getWidth) 354 } 355 val memLogger = CHILogger(s"LLC_MEM", true) 356 chi_openllc_opt.get.io.sn.connect(memLogger.io.up) 357 chi_llcBridge_opt.get.module.io.chi.connect(memLogger.io.down) 358 chi_openllc_opt.get.io.nodeID := (NumCores * 2).U 359 chi_openllc_opt.foreach { l3 => 360 l3.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr) 361 } 362 core_with_l2.zip(chi_openllc_opt.get.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) => 363 tile.module.io.debugTopDown.l3MissMatch := l3Match 364 } 365 core_with_l2.zip(chi_openllc_opt).foreach { case (tile, l3) => 366 tile.module.io.l3Miss := l3.io.l3Miss 367 } 368 } 369 } 370 371 if(l3cacheOpt.isEmpty || l3cacheOpt.get.rst_nodes.isEmpty){ 372 // tie off core soft reset 373 for(node <- core_rst_nodes){ 374 node.out.head._1 := false.B.asAsyncReset 375 } 376 } 377 378 l3cacheOpt match { 379 case Some(l3) => 380 l3.pf_recv_node match { 381 case Some(recv) => 382 l3_pf_sender_opt.get.out.head._1.addr_valid := VecInit(memblock_pf_recv_nodes.map(_.get.in.head._1.addr_valid)).asUInt.orR 383 for (i <- 0 until NumCores) { 384 when(memblock_pf_recv_nodes(i).get.in.head._1.addr_valid) { 385 l3_pf_sender_opt.get.out.head._1.addr := memblock_pf_recv_nodes(i).get.in.head._1.addr 386 l3_pf_sender_opt.get.out.head._1.l2_pf_en := memblock_pf_recv_nodes(i).get.in.head._1.l2_pf_en 387 } 388 } 389 case None => 390 } 391 l3.module.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr) 392 core_with_l2.zip(l3.module.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) => tile.module.io.debugTopDown.l3MissMatch := l3Match } 393 core_with_l2.foreach(_.module.io.l3Miss := l3.module.io.l3Miss) 394 case None => 395 } 396 397 (chi_openllc_opt, l3cacheOpt) match { 398 case (None, None) => 399 core_with_l2.foreach(_.module.io.debugTopDown.l3MissMatch := false.B) 400 core_with_l2.foreach(_.module.io.l3Miss := false.B) 401 case _ => 402 } 403 404 core_with_l2.zipWithIndex.foreach { case (tile, i) => 405 tile.module.io.nodeID.foreach { case nodeID => 406 nodeID := i.U 407 dontTouch(nodeID) 408 } 409 } 410 411 misc.module.debug_module_io.resetCtrl.hartIsInReset := core_with_l2.map(_.module.io.hartIsInReset) 412 misc.module.debug_module_io.clock := io.clock 413 misc.module.debug_module_io.reset := reset_sync 414 415 misc.module.debug_module_io.debugIO.reset := misc.module.reset 416 misc.module.debug_module_io.debugIO.clock := io.clock 417 // TODO: delay 3 cycles? 418 misc.module.debug_module_io.debugIO.dmactiveAck := misc.module.debug_module_io.debugIO.dmactive 419 // jtag connector 420 misc.module.debug_module_io.debugIO.systemjtag.foreach { x => 421 x.jtag <> io.systemjtag.jtag 422 x.reset := jtag_reset_sync 423 x.mfr_id := io.systemjtag.mfr_id 424 x.part_number := io.systemjtag.part_number 425 x.version := io.systemjtag.version 426 } 427 428 withClockAndReset(io.clock, reset_sync) { 429 // Modules are reset one by one 430 // reset ----> SYNC --> {SoCMisc, L3 Cache, Cores} 431 val resetChain = Seq(Seq(misc.module) ++ l3cacheOpt.map(_.module)) 432 ResetGen(resetChain, reset_sync, !debugOpts.ResetGen) 433 // Ensure that cores could be reset when DM disable `hartReset` or l3cacheOpt.isEmpty. 434 val dmResetReqVec = misc.module.debug_module_io.resetCtrl.hartResetReq.getOrElse(0.U.asTypeOf(Vec(core_with_l2.map(_.module).length, Bool()))) 435 val syncResetCores = if(l3cacheOpt.nonEmpty) l3cacheOpt.map(_.module).get.reset.asBool else misc.module.reset.asBool 436 (core_with_l2.map(_.module)).zip(dmResetReqVec).map { case(core, dmResetReq) => 437 ResetGen(Seq(Seq(core)), (syncResetCores || dmResetReq).asAsyncReset, !debugOpts.ResetGen) 438 } 439 } 440 441 } 442 443 lazy val module = new XSTopImp(this) 444} 445 446object TopMain extends App { 447 val (config, firrtlOpts, firtoolOpts) = ArgParser.parse(args) 448 449 // tools: init to close dpi-c when in fpga 450 val envInFPGA = config(DebugOptionsKey).FPGAPlatform 451 val enableDifftest = config(DebugOptionsKey).EnableDifftest || config(DebugOptionsKey).AlwaysBasicDiff 452 val enableChiselDB = config(DebugOptionsKey).EnableChiselDB 453 val enableConstantin = config(DebugOptionsKey).EnableConstantin 454 Constantin.init(enableConstantin && !envInFPGA) 455 ChiselDB.init(enableChiselDB && !envInFPGA) 456 457 if (config(SoCParamsKey).UseXSNoCDiffTop) { 458 Generator.execute(firrtlOpts, DisableMonitors(p => new XSNoCDiffTop()(p))(config), firtoolOpts) 459 } else { 460 val soc = if (config(SoCParamsKey).UseXSNoCTop) 461 DisableMonitors(p => LazyModule(new XSNoCTop()(p)))(config) 462 else 463 DisableMonitors(p => LazyModule(new XSTop()(p)))(config) 464 465 Generator.execute(firrtlOpts, soc.module, firtoolOpts) 466 467 // generate difftest bundles (w/o DifftestTopIO) 468 if (enableDifftest) { 469 DifftestModule.finish("XiangShan", false) 470 } 471 } 472 473 FileRegisters.write(fileDir = "./build", filePrefix = "XSTop.") 474} 475