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 ) 113 }))) 114 ) 115 116 val chi_mmioBridge_opt = Seq.fill(NumCores)(Option.when(enableCHI)( 117 LazyModule(new OpenNCB()(p.alter((site, here, up) => { 118 case NCBParametersKey => new NCBParameters( 119 outstandingDepth = 32, 120 axiMasterOrder = EnumAXIMasterOrder.None, 121 readCompDMT = false, 122 writeCancelable = false, 123 writeNoError = true, 124 asEndpoint = false, 125 acceptOrderEndpoint = true, 126 acceptMemAttrDevice = true, 127 readReceiptAfterAcception = true, 128 axiBurstAlwaysIncr = true 129 ) 130 }))) 131 )) 132 133 // receive all prefetch req from cores 134 val memblock_pf_recv_nodes: Seq[Option[BundleBridgeSink[PrefetchRecv]]] = core_with_l2.map(_.core_l3_pf_port).map{ 135 x => x.map(_ => BundleBridgeSink(Some(() => new PrefetchRecv))) 136 } 137 138 val l3_pf_sender_opt = soc.L3CacheParamsOpt.getOrElse(HCCacheParameters()).prefetch match { 139 case Some(pf) => Some(BundleBridgeSource(() => new PrefetchRecv)) 140 case None => None 141 } 142 val nmiIntNode = IntSourceNode(IntSourcePortSimple(1, NumCores, (new NonmaskableInterruptIO).elements.size)) 143 val nmi = InModuleBody(nmiIntNode.makeIOs()) 144 145 for (i <- 0 until NumCores) { 146 core_with_l2(i).clint_int_node := misc.clint.intnode 147 core_with_l2(i).plic_int_node :*= misc.plic.intnode 148 core_with_l2(i).debug_int_node := misc.debugModule.debug.dmOuter.dmOuter.intnode 149 core_with_l2(i).nmi_int_node := nmiIntNode 150 misc.plic.intnode := IntBuffer() := core_with_l2(i).beu_int_source 151 if (!enableCHI) { 152 misc.peripheral_ports.get(i) := core_with_l2(i).tl_uncache 153 } 154 core_with_l2(i).memory_port.foreach(port => (misc.core_to_l3_ports.get)(i) :=* port) 155 memblock_pf_recv_nodes(i).map(recv => { 156 println(s"Connecting Core_${i}'s L1 pf source to L3!") 157 recv := core_with_l2(i).core_l3_pf_port.get 158 }) 159 } 160 161 l3cacheOpt.map(_.ctlnode.map(_ := misc.peripheralXbar.get)) 162 l3cacheOpt.map(_.intnode.map(int => { 163 misc.plic.intnode := IntBuffer() := int 164 })) 165 166 val core_rst_nodes = if(l3cacheOpt.nonEmpty && l3cacheOpt.get.rst_nodes.nonEmpty){ 167 l3cacheOpt.get.rst_nodes.get 168 } else { 169 core_with_l2.map(_ => BundleBridgeSource(() => Reset())) 170 } 171 172 core_rst_nodes.zip(core_with_l2.map(_.core_reset_sink)).foreach({ 173 case (source, sink) => sink := source 174 }) 175 176 l3cacheOpt match { 177 case Some(l3) => 178 misc.l3_out :*= l3.node :*= misc.l3_banked_xbar.get 179 l3.pf_recv_node.map(recv => { 180 println("Connecting L1 prefetcher to L3!") 181 recv := l3_pf_sender_opt.get 182 }) 183 l3.tpmeta_recv_node.foreach(recv => { 184 for ((core, i) <- core_with_l2.zipWithIndex) { 185 println(s"Connecting core_$i\'s L2 TPmeta request to L3!") 186 recv := core.core_l3_tpmeta_source_port.get 187 } 188 }) 189 l3.tpmeta_send_node.foreach(send => { 190 val broadcast = LazyModule(new ValidIOBroadcast[TPmetaResp]()) 191 broadcast.node := send 192 for ((core, i) <- core_with_l2.zipWithIndex) { 193 println(s"Connecting core_$i\'s L2 TPmeta response to L3!") 194 core.core_l3_tpmeta_sink_port.get := broadcast.node 195 } 196 }) 197 case None => 198 } 199 200 chi_llcBridge_opt match { 201 case Some(ncb) => 202 misc.soc_xbar.get := ncb.axi4node 203 case None => 204 } 205 206 chi_mmioBridge_opt.foreach { e => 207 e match { 208 case Some(ncb) => 209 misc.soc_xbar.get := ncb.axi4node 210 case None => 211 } 212 } 213 214 class XSTopImp(wrapper: LazyModule) extends LazyRawModuleImp(wrapper) { 215 soc.XSTopPrefix.foreach { prefix => 216 val mod = this.toNamed 217 annotate(new ChiselAnnotation { 218 def toFirrtl = NestedPrefixModulesAnnotation(mod, prefix, true) 219 }) 220 } 221 222 FileRegisters.add("dts", dts) 223 FileRegisters.add("graphml", graphML) 224 FileRegisters.add("json", json) 225 FileRegisters.add("plusArgs", freechips.rocketchip.util.PlusArgArtefacts.serialize_cHeader()) 226 227 val dma = socMisc.map(m => IO(Flipped(new VerilogAXI4Record(m.dma.elts.head.params)))) 228 val peripheral = IO(new VerilogAXI4Record(misc.peripheral.elts.head.params)) 229 val memory = IO(new VerilogAXI4Record(misc.memory.elts.head.params)) 230 231 socMisc match { 232 case Some(m) => 233 m.dma.elements.head._2 <> dma.get.viewAs[AXI4Bundle] 234 dontTouch(dma.get) 235 case None => 236 } 237 238 memory.viewAs[AXI4Bundle] <> misc.memory.elements.head._2 239 peripheral.viewAs[AXI4Bundle] <> misc.peripheral.elements.head._2 240 241 val io = IO(new Bundle { 242 val clock = Input(Bool()) 243 val reset = Input(AsyncReset()) 244 val sram_config = Input(UInt(16.W)) 245 val extIntrs = Input(UInt(NrExtIntr.W)) 246 val pll0_lock = Input(Bool()) 247 val pll0_ctrl = Output(Vec(6, UInt(32.W))) 248 val systemjtag = new Bundle { 249 val jtag = Flipped(new JTAGIO(hasTRSTn = false)) 250 val reset = Input(AsyncReset()) // No reset allowed on top 251 val mfr_id = Input(UInt(11.W)) 252 val part_number = Input(UInt(16.W)) 253 val version = Input(UInt(4.W)) 254 } 255 val debug_reset = Output(Bool()) 256 val rtc_clock = Input(Bool()) 257 val cacheable_check = new TLPMAIO() 258 val riscv_halt = Output(Vec(NumCores, Bool())) 259 val riscv_critical_error = Output(Vec(NumCores, Bool())) 260 val riscv_rst_vec = Input(Vec(NumCores, UInt(soc.PAddrBits.W))) 261 }) 262 263 val reset_sync = withClockAndReset(io.clock.asClock, io.reset) { ResetGen() } 264 val jtag_reset_sync = withClockAndReset(io.systemjtag.jtag.TCK, io.systemjtag.reset) { ResetGen() } 265 val chi_openllc_opt = Option.when(enableCHI)( 266 withClockAndReset(io.clock.asClock, io.reset) { 267 Module(new OpenLLC()(p.alter((site, here, up) => { 268 case OpenLLCParamKey => soc.OpenLLCParamsOpt.get 269 }))) 270 } 271 ) 272 273 // override LazyRawModuleImp's clock and reset 274 childClock := io.clock.asClock 275 childReset := reset_sync 276 277 // output 278 io.debug_reset := misc.module.debug_module_io.debugIO.ndreset 279 280 // input 281 dontTouch(io) 282 dontTouch(memory) 283 misc.module.ext_intrs := io.extIntrs 284 misc.module.rtc_clock := io.rtc_clock 285 misc.module.pll0_lock := io.pll0_lock 286 misc.module.cacheable_check <> io.cacheable_check 287 288 io.pll0_ctrl <> misc.module.pll0_ctrl 289 290 val msiInfo = WireInit(0.U.asTypeOf(ValidIO(new MsiInfoBundle))) 291 292 293 for ((core, i) <- core_with_l2.zipWithIndex) { 294 core.module.io.hartId := i.U 295 core.module.io.msiInfo := msiInfo 296 core.module.io.clintTime := misc.module.clintTime 297 io.riscv_halt(i) := core.module.io.cpu_halt 298 io.riscv_critical_error(i) := core.module.io.cpu_crtical_error 299 core.module.io.reset_vector := io.riscv_rst_vec(i) 300 } 301 302 withClockAndReset(io.clock.asClock, io.reset) { 303 Option.when(enableCHI)(true.B).foreach { _ => 304 for ((core, i) <- core_with_l2.zipWithIndex) { 305 val mmioLogger = CHILogger(s"L2[${i}]_MMIO", true) 306 val llcLogger = CHILogger(s"L2[${i}]_LLC", true) 307 dontTouch(core.module.io.chi.get) 308 bind( 309 route( 310 core.module.io.chi.get, Map((AddressSet(0x0L, 0x00007fffffffL), NumCores + i)) ++ AddressSet(0x0L, 311 0xffffffffffffL).subtract(AddressSet(0x0L, 0x00007fffffffL)).map(addr => (addr, NumCores * 2)).toMap 312 ), 313 Map((NumCores + i) -> mmioLogger.io.up, (NumCores * 2) -> llcLogger.io.up) 314 ) 315 chi_mmioBridge_opt(i).get.module.io.chi.connect(mmioLogger.io.down) 316 chi_openllc_opt.get.io.rn(i) <> llcLogger.io.down 317 } 318 val memLogger = CHILogger(s"LLC_MEM", true) 319 chi_openllc_opt.get.io.sn.connect(memLogger.io.up) 320 chi_llcBridge_opt.get.module.io.chi.connect(memLogger.io.down) 321 chi_openllc_opt.get.io.nodeID := (NumCores * 2).U 322 } 323 } 324 325 if(l3cacheOpt.isEmpty || l3cacheOpt.get.rst_nodes.isEmpty){ 326 // tie off core soft reset 327 for(node <- core_rst_nodes){ 328 node.out.head._1 := false.B.asAsyncReset 329 } 330 } 331 332 l3cacheOpt match { 333 case Some(l3) => 334 l3.pf_recv_node match { 335 case Some(recv) => 336 l3_pf_sender_opt.get.out.head._1.addr_valid := VecInit(memblock_pf_recv_nodes.map(_.get.in.head._1.addr_valid)).asUInt.orR 337 for (i <- 0 until NumCores) { 338 when(memblock_pf_recv_nodes(i).get.in.head._1.addr_valid) { 339 l3_pf_sender_opt.get.out.head._1.addr := memblock_pf_recv_nodes(i).get.in.head._1.addr 340 l3_pf_sender_opt.get.out.head._1.l2_pf_en := memblock_pf_recv_nodes(i).get.in.head._1.l2_pf_en 341 } 342 } 343 case None => 344 } 345 l3.module.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr) 346 core_with_l2.zip(l3.module.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) => tile.module.io.debugTopDown.l3MissMatch := l3Match } 347 case None => core_with_l2.foreach(_.module.io.debugTopDown.l3MissMatch := false.B) 348 } 349 350 core_with_l2.foreach { case tile => 351 tile.module.io.nodeID.foreach { case nodeID => 352 nodeID := DontCare 353 dontTouch(nodeID) 354 } 355 } 356 357 misc.module.debug_module_io.resetCtrl.hartIsInReset := core_with_l2.map(_.module.reset.asBool) 358 misc.module.debug_module_io.clock := io.clock 359 misc.module.debug_module_io.reset := reset_sync 360 361 misc.module.debug_module_io.debugIO.reset := misc.module.reset 362 misc.module.debug_module_io.debugIO.clock := io.clock.asClock 363 // TODO: delay 3 cycles? 364 misc.module.debug_module_io.debugIO.dmactiveAck := misc.module.debug_module_io.debugIO.dmactive 365 // jtag connector 366 misc.module.debug_module_io.debugIO.systemjtag.foreach { x => 367 x.jtag <> io.systemjtag.jtag 368 x.reset := jtag_reset_sync 369 x.mfr_id := io.systemjtag.mfr_id 370 x.part_number := io.systemjtag.part_number 371 x.version := io.systemjtag.version 372 } 373 374 withClockAndReset(io.clock.asClock, reset_sync) { 375 // Modules are reset one by one 376 // reset ----> SYNC --> {SoCMisc, L3 Cache, Cores} 377 val resetChain = Seq(Seq(misc.module) ++ l3cacheOpt.map(_.module) ++ core_with_l2.map(_.module)) 378 ResetGen(resetChain, reset_sync, !debugOpts.ResetGen) 379 } 380 381 } 382 383 lazy val module = new XSTopImp(this) 384} 385 386object TopMain extends App { 387 val (config, firrtlOpts, firtoolOpts) = ArgParser.parse(args) 388 389 // tools: init to close dpi-c when in fpga 390 val envInFPGA = config(DebugOptionsKey).FPGAPlatform 391 val enableDifftest = config(DebugOptionsKey).EnableDifftest || config(DebugOptionsKey).AlwaysBasicDiff 392 val enableChiselDB = config(DebugOptionsKey).EnableChiselDB 393 val enableConstantin = config(DebugOptionsKey).EnableConstantin 394 Constantin.init(enableConstantin && !envInFPGA) 395 ChiselDB.init(enableChiselDB && !envInFPGA) 396 397 val soc = if (config(SoCParamsKey).UseXSNoCTop) 398 DisableMonitors(p => LazyModule(new XSNoCTop()(p)))(config) 399 else 400 DisableMonitors(p => LazyModule(new XSTop()(p)))(config) 401 402 Generator.execute(firrtlOpts, soc.module, firtoolOpts) 403 404 // generate difftest bundles (w/o DifftestTopIO) 405 if (enableDifftest) { 406 DifftestModule.finish("XiangShan", false) 407 } 408 409 FileRegisters.write(fileDir = "./build", filePrefix = "XSTop.") 410} 411