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 val traceCoreInterface = Vec(NumCores, new Bundle { 262 val fromEncoder = Input(new Bundle { 263 val enable = Bool() 264 val stall = Bool() 265 }) 266 val toEncoder = Output(new Bundle { 267 val cause = UInt(TraceCauseWidth.W) 268 val tval = UInt(TraceTvalWidth.W) 269 val priv = UInt(TracePrivWidth.W) 270 val iaddr = UInt((TraceTraceGroupNum * TraceIaddrWidth).W) 271 val itype = UInt((TraceTraceGroupNum * TraceItypeWidth).W) 272 val iretire = UInt((TraceTraceGroupNum * TraceIretireWidthCompressed).W) 273 val ilastsize = UInt((TraceTraceGroupNum * TraceIlastsizeWidth).W) 274 }) 275 }) 276 }) 277 278 val reset_sync = withClockAndReset(io.clock.asClock, io.reset) { ResetGen() } 279 val jtag_reset_sync = withClockAndReset(io.systemjtag.jtag.TCK, io.systemjtag.reset) { ResetGen() } 280 val chi_openllc_opt = Option.when(enableCHI)( 281 withClockAndReset(io.clock.asClock, io.reset) { 282 Module(new OpenLLC()(p.alter((site, here, up) => { 283 case OpenLLCParamKey => soc.OpenLLCParamsOpt.get.copy( 284 hartIds = tiles.map(_.HartId), 285 FPGAPlatform = debugOpts.FPGAPlatform 286 ) 287 }))) 288 } 289 ) 290 291 // override LazyRawModuleImp's clock and reset 292 childClock := io.clock.asClock 293 childReset := reset_sync 294 295 // output 296 io.debug_reset := misc.module.debug_module_io.debugIO.ndreset 297 298 // input 299 dontTouch(io) 300 dontTouch(memory) 301 misc.module.ext_intrs := io.extIntrs 302 misc.module.rtc_clock := io.rtc_clock 303 misc.module.pll0_lock := io.pll0_lock 304 misc.module.cacheable_check <> io.cacheable_check 305 306 io.pll0_ctrl <> misc.module.pll0_ctrl 307 308 val msiInfo = WireInit(0.U.asTypeOf(ValidIO(new MsiInfoBundle))) 309 310 311 for ((core, i) <- core_with_l2.zipWithIndex) { 312 core.module.io.hartId := i.U 313 core.module.io.msiInfo := msiInfo 314 core.module.io.clintTime := misc.module.clintTime 315 io.riscv_halt(i) := core.module.io.cpu_halt 316 io.riscv_critical_error(i) := core.module.io.cpu_crtical_error 317 // trace Interface 318 val traceInterface = core.module.io.traceCoreInterface 319 traceInterface.fromEncoder := io.traceCoreInterface(i).fromEncoder 320 io.traceCoreInterface(i).toEncoder.priv := traceInterface.toEncoder.priv 321 io.traceCoreInterface(i).toEncoder.cause := traceInterface.toEncoder.trap.cause 322 io.traceCoreInterface(i).toEncoder.tval := traceInterface.toEncoder.trap.tval 323 io.traceCoreInterface(i).toEncoder.iaddr := VecInit(traceInterface.toEncoder.groups.map(_.bits.iaddr)).asUInt 324 io.traceCoreInterface(i).toEncoder.itype := VecInit(traceInterface.toEncoder.groups.map(_.bits.itype)).asUInt 325 io.traceCoreInterface(i).toEncoder.iretire := VecInit(traceInterface.toEncoder.groups.map(_.bits.iretire)).asUInt 326 io.traceCoreInterface(i).toEncoder.ilastsize := VecInit(traceInterface.toEncoder.groups.map(_.bits.ilastsize)).asUInt 327 328 core.module.io.reset_vector := io.riscv_rst_vec(i) 329 } 330 331 withClockAndReset(io.clock.asClock, io.reset) { 332 Option.when(enableCHI)(true.B).foreach { _ => 333 for ((core, i) <- core_with_l2.zipWithIndex) { 334 val mmioLogger = CHILogger(s"L2[${i}]_MMIO", true) 335 val llcLogger = CHILogger(s"L2[${i}]_LLC", true) 336 dontTouch(core.module.io.chi.get) 337 bind( 338 route( 339 core.module.io.chi.get, Map((AddressSet(0x0L, 0x00007fffffffL), NumCores + i)) ++ AddressSet(0x0L, 340 0xffffffffffffL).subtract(AddressSet(0x0L, 0x00007fffffffL)).map(addr => (addr, NumCores * 2)).toMap 341 ), 342 Map((NumCores + i) -> mmioLogger.io.up, (NumCores * 2) -> llcLogger.io.up) 343 ) 344 chi_mmioBridge_opt(i).get.module.io.chi.connect(mmioLogger.io.down) 345 chi_openllc_opt.get.io.rn(i) <> llcLogger.io.down 346 } 347 val memLogger = CHILogger(s"LLC_MEM", true) 348 chi_openllc_opt.get.io.sn.connect(memLogger.io.up) 349 chi_llcBridge_opt.get.module.io.chi.connect(memLogger.io.down) 350 chi_openllc_opt.get.io.nodeID := (NumCores * 2).U 351 chi_openllc_opt.foreach { l3 => 352 l3.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr) 353 } 354 core_with_l2.zip(chi_openllc_opt.get.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) => 355 tile.module.io.debugTopDown.l3MissMatch := l3Match 356 } 357 } 358 } 359 360 if(l3cacheOpt.isEmpty || l3cacheOpt.get.rst_nodes.isEmpty){ 361 // tie off core soft reset 362 for(node <- core_rst_nodes){ 363 node.out.head._1 := false.B.asAsyncReset 364 } 365 } 366 367 l3cacheOpt match { 368 case Some(l3) => 369 l3.pf_recv_node match { 370 case Some(recv) => 371 l3_pf_sender_opt.get.out.head._1.addr_valid := VecInit(memblock_pf_recv_nodes.map(_.get.in.head._1.addr_valid)).asUInt.orR 372 for (i <- 0 until NumCores) { 373 when(memblock_pf_recv_nodes(i).get.in.head._1.addr_valid) { 374 l3_pf_sender_opt.get.out.head._1.addr := memblock_pf_recv_nodes(i).get.in.head._1.addr 375 l3_pf_sender_opt.get.out.head._1.l2_pf_en := memblock_pf_recv_nodes(i).get.in.head._1.l2_pf_en 376 } 377 } 378 case None => 379 } 380 l3.module.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr) 381 core_with_l2.zip(l3.module.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) => tile.module.io.debugTopDown.l3MissMatch := l3Match } 382 case None => 383 } 384 385 (chi_openllc_opt, l3cacheOpt) match { 386 case (None, None) => core_with_l2.foreach(_.module.io.debugTopDown.l3MissMatch := false.B) 387 case _ => 388 } 389 390 core_with_l2.foreach { case tile => 391 tile.module.io.nodeID.foreach { case nodeID => 392 nodeID := DontCare 393 dontTouch(nodeID) 394 } 395 } 396 397 misc.module.debug_module_io.resetCtrl.hartIsInReset := core_with_l2.map(_.module.io.hartIsInReset) 398 misc.module.debug_module_io.clock := io.clock 399 misc.module.debug_module_io.reset := reset_sync 400 401 misc.module.debug_module_io.debugIO.reset := misc.module.reset 402 misc.module.debug_module_io.debugIO.clock := io.clock.asClock 403 // TODO: delay 3 cycles? 404 misc.module.debug_module_io.debugIO.dmactiveAck := misc.module.debug_module_io.debugIO.dmactive 405 // jtag connector 406 misc.module.debug_module_io.debugIO.systemjtag.foreach { x => 407 x.jtag <> io.systemjtag.jtag 408 x.reset := jtag_reset_sync 409 x.mfr_id := io.systemjtag.mfr_id 410 x.part_number := io.systemjtag.part_number 411 x.version := io.systemjtag.version 412 } 413 414 withClockAndReset(io.clock.asClock, reset_sync) { 415 // Modules are reset one by one 416 // reset ----> SYNC --> {SoCMisc, L3 Cache, Cores} 417 val resetChain = Seq(Seq(misc.module) ++ l3cacheOpt.map(_.module)) 418 ResetGen(resetChain, reset_sync, !debugOpts.ResetGen) 419 // Ensure that cores could be reset when DM disable `hartReset` or l3cacheOpt.isEmpty. 420 val dmResetReqVec = misc.module.debug_module_io.resetCtrl.hartResetReq.getOrElse(0.U.asTypeOf(Vec(core_with_l2.map(_.module).length, Bool()))) 421 val syncResetCores = if(l3cacheOpt.nonEmpty) l3cacheOpt.map(_.module).get.reset.asBool else misc.module.reset.asBool 422 (core_with_l2.map(_.module)).zip(dmResetReqVec).map { case(core, dmResetReq) => 423 ResetGen(Seq(Seq(core)), (syncResetCores || dmResetReq).asAsyncReset, !debugOpts.ResetGen) 424 } 425 } 426 427 } 428 429 lazy val module = new XSTopImp(this) 430} 431 432object TopMain extends App { 433 val (config, firrtlOpts, firtoolOpts) = ArgParser.parse(args) 434 435 // tools: init to close dpi-c when in fpga 436 val envInFPGA = config(DebugOptionsKey).FPGAPlatform 437 val enableDifftest = config(DebugOptionsKey).EnableDifftest || config(DebugOptionsKey).AlwaysBasicDiff 438 val enableChiselDB = config(DebugOptionsKey).EnableChiselDB 439 val enableConstantin = config(DebugOptionsKey).EnableConstantin 440 Constantin.init(enableConstantin && !envInFPGA) 441 ChiselDB.init(enableChiselDB && !envInFPGA) 442 443 val soc = if (config(SoCParamsKey).UseXSNoCTop) 444 DisableMonitors(p => LazyModule(new XSNoCTop()(p)))(config) 445 else 446 DisableMonitors(p => LazyModule(new XSTop()(p)))(config) 447 448 Generator.execute(firrtlOpts, soc.module, firtoolOpts) 449 450 // generate difftest bundles (w/o DifftestTopIO) 451 if (enableDifftest) { 452 DifftestModule.finish("XiangShan", false) 453 } 454 455 FileRegisters.write(fileDir = "./build", filePrefix = "XSTop.") 456} 457