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