xref: /XiangShan/src/main/scala/top/Top.scala (revision d29457077dba131b5b0f793bbf7a71463640ac2a)
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 top
18
19import chisel3._
20import chisel3.util._
21import xiangshan._
22import utils._
23import huancun.{HCCacheParameters, HCCacheParamsKey, HuanCun, PrefetchRecv, TPmetaResp}
24import utility._
25import system._
26import device._
27import chisel3.stage.ChiselGeneratorAnnotation
28import org.chipsalliance.cde.config._
29import freechips.rocketchip.diplomacy._
30import freechips.rocketchip.tilelink._
31import freechips.rocketchip.jtag.JTAGIO
32
33abstract class BaseXSSoc()(implicit p: Parameters) extends LazyModule
34  with BindingScope
35{
36  val misc = LazyModule(new SoCMisc())
37  lazy val dts = DTS(bindingTree)
38  lazy val json = JSON(bindingTree)
39}
40
41class XSTop()(implicit p: Parameters) extends BaseXSSoc() with HasSoCParameter
42{
43  ResourceBinding {
44    val width = ResourceInt(2)
45    val model = "freechips,rocketchip-unknown"
46    Resource(ResourceAnchors.root, "model").bind(ResourceString(model))
47    Resource(ResourceAnchors.root, "compat").bind(ResourceString(model + "-dev"))
48    Resource(ResourceAnchors.soc, "compat").bind(ResourceString(model + "-soc"))
49    Resource(ResourceAnchors.root, "width").bind(width)
50    Resource(ResourceAnchors.soc, "width").bind(width)
51    Resource(ResourceAnchors.cpus, "width").bind(ResourceInt(1))
52    def bindManagers(xbar: TLNexusNode) = {
53      ManagerUnification(xbar.edges.in.head.manager.managers).foreach{ manager =>
54        manager.resources.foreach(r => r.bind(manager.toResource))
55      }
56    }
57    bindManagers(misc.l3_xbar.asInstanceOf[TLNexusNode])
58    bindManagers(misc.peripheralXbar.asInstanceOf[TLNexusNode])
59  }
60
61  println(s"FPGASoC cores: $NumCores banks: $L3NBanks block size: $L3BlockSize bus size: $L3OuterBusWidth")
62
63  val core_with_l2 = tiles.map(coreParams =>
64    LazyModule(new XSTile()(p.alterPartial({
65      case XSCoreParamsKey => coreParams
66    })))
67  )
68
69  val l3cacheOpt = soc.L3CacheParamsOpt.map(l3param =>
70    LazyModule(new HuanCun()(new Config((_, _, _) => {
71      case HCCacheParamsKey => l3param.copy(
72        hartIds = tiles.map(_.HartId),
73        FPGAPlatform = debugOpts.FPGAPlatform
74      )
75    })))
76  )
77
78  // recieve all prefetch req from cores
79  val memblock_pf_recv_nodes: Seq[Option[BundleBridgeSink[PrefetchRecv]]] = core_with_l2.map(_.core_l3_pf_port).map{
80    x => x.map(_ => BundleBridgeSink(Some(() => new PrefetchRecv)))
81  }
82
83  val l3_pf_sender_opt = soc.L3CacheParamsOpt.getOrElse(HCCacheParameters()).prefetch match {
84    case Some(pf) => Some(BundleBridgeSource(() => new PrefetchRecv))
85    case None => None
86  }
87
88  for (i <- 0 until NumCores) {
89    core_with_l2(i).clint_int_node := misc.clint.intnode
90    core_with_l2(i).plic_int_node :*= misc.plic.intnode
91    core_with_l2(i).debug_int_node := misc.debugModule.debug.dmOuter.dmOuter.intnode
92    misc.plic.intnode := IntBuffer() := core_with_l2(i).beu_int_source
93    misc.peripheral_ports(i) := core_with_l2(i).uncache
94    misc.core_to_l3_ports(i) :=* core_with_l2(i).memory_port
95    memblock_pf_recv_nodes(i).map(recv => {
96      println(s"Connecting Core_${i}'s L1 pf source to L3!")
97      recv := core_with_l2(i).core_l3_pf_port.get
98    })
99  }
100
101  l3cacheOpt.map(_.ctlnode.map(_ := misc.peripheralXbar))
102  l3cacheOpt.map(_.intnode.map(int => {
103    misc.plic.intnode := IntBuffer() := int
104  }))
105
106  val core_rst_nodes = if(l3cacheOpt.nonEmpty && l3cacheOpt.get.rst_nodes.nonEmpty){
107    l3cacheOpt.get.rst_nodes.get
108  } else {
109    core_with_l2.map(_ => BundleBridgeSource(() => Reset()))
110  }
111
112  core_rst_nodes.zip(core_with_l2.map(_.core_reset_sink)).foreach({
113    case (source, sink) =>  sink := source
114  })
115
116  l3cacheOpt match {
117    case Some(l3) =>
118      misc.l3_out :*= l3.node :*= misc.l3_banked_xbar
119      l3.pf_recv_node.map(recv => {
120        println("Connecting L1 prefetcher to L3!")
121        recv := l3_pf_sender_opt.get
122      })
123      l3.tpmeta_recv_node.foreach(recv => {
124        for ((core, i) <- core_with_l2.zipWithIndex) {
125          println(s"Connecting core_$i\'s L2 TPmeta request to L3!")
126          recv := core.core_l3_tpmeta_source_port.get
127        }
128      })
129      l3.tpmeta_send_node.foreach(send => {
130        val broadcast = LazyModule(new ValidIOBroadcast[TPmetaResp]())
131        broadcast.node := send
132        for ((core, i) <- core_with_l2.zipWithIndex) {
133          println(s"Connecting core_$i\'s L2 TPmeta response to L3!")
134          core.core_l3_tpmeta_sink_port.get := broadcast.node
135        }
136      })
137    case None =>
138  }
139
140  class XSTopImp(wrapper: LazyModule) extends LazyRawModuleImp(wrapper) {
141    FileRegisters.add("dts", dts)
142    FileRegisters.add("graphml", graphML)
143    FileRegisters.add("json", json)
144    FileRegisters.add("plusArgs", freechips.rocketchip.util.PlusArgArtefacts.serialize_cHeader())
145
146    val dma = IO(Flipped(misc.dma.cloneType))
147    val peripheral = IO(misc.peripheral.cloneType)
148    val memory = IO(misc.memory.cloneType)
149
150    misc.dma <> dma
151    peripheral <> misc.peripheral
152    memory <> misc.memory
153
154    val io = IO(new Bundle {
155      val clock = Input(Bool())
156      val reset = Input(AsyncReset())
157      val sram_config = Input(UInt(16.W))
158      val extIntrs = Input(UInt(NrExtIntr.W))
159      val pll0_lock = Input(Bool())
160      val pll0_ctrl = Output(Vec(6, UInt(32.W)))
161      val systemjtag = new Bundle {
162        val jtag = Flipped(new JTAGIO(hasTRSTn = false))
163        val reset = Input(AsyncReset()) // No reset allowed on top
164        val mfr_id = Input(UInt(11.W))
165        val part_number = Input(UInt(16.W))
166        val version = Input(UInt(4.W))
167      }
168      val debug_reset = Output(Bool())
169      val rtc_clock = Input(Bool())
170      val cacheable_check = new TLPMAIO()
171      val riscv_halt = Output(Vec(NumCores, Bool()))
172      val riscv_rst_vec = Input(Vec(NumCores, UInt(38.W)))
173    })
174
175    val reset_sync = withClockAndReset(io.clock.asClock, io.reset) { ResetGen() }
176    val jtag_reset_sync = withClockAndReset(io.systemjtag.jtag.TCK, io.systemjtag.reset) { ResetGen() }
177
178    // override LazyRawModuleImp's clock and reset
179    childClock := io.clock.asClock
180    childReset := reset_sync
181
182    // output
183    io.debug_reset := misc.module.debug_module_io.debugIO.ndreset
184
185    // input
186    dontTouch(dma)
187    dontTouch(io)
188    dontTouch(peripheral)
189    dontTouch(memory)
190    misc.module.ext_intrs := io.extIntrs
191    misc.module.rtc_clock := io.rtc_clock
192    misc.module.pll0_lock := io.pll0_lock
193    misc.module.cacheable_check <> io.cacheable_check
194
195    io.pll0_ctrl <> misc.module.pll0_ctrl
196
197    for ((core, i) <- core_with_l2.zipWithIndex) {
198      core.module.io.hartId := i.U
199      io.riscv_halt(i) := core.module.io.cpu_halt
200      core.module.io.reset_vector := io.riscv_rst_vec(i)
201    }
202
203    if(l3cacheOpt.isEmpty || l3cacheOpt.get.rst_nodes.isEmpty){
204      // tie off core soft reset
205      for(node <- core_rst_nodes){
206        node.out.head._1 := false.B.asAsyncReset
207      }
208    }
209
210    l3cacheOpt match {
211      case Some(l3) =>
212        l3.pf_recv_node match {
213          case Some(recv) =>
214            l3_pf_sender_opt.get.out.head._1.addr_valid := VecInit(memblock_pf_recv_nodes.map(_.get.in.head._1.addr_valid)).asUInt.orR
215            for (i <- 0 until NumCores) {
216              when(memblock_pf_recv_nodes(i).get.in.head._1.addr_valid) {
217                l3_pf_sender_opt.get.out.head._1.addr := memblock_pf_recv_nodes(i).get.in.head._1.addr
218                l3_pf_sender_opt.get.out.head._1.l2_pf_en := memblock_pf_recv_nodes(i).get.in.head._1.l2_pf_en
219              }
220            }
221          case None =>
222        }
223        l3.module.io.debugTopDown.robHeadPaddr := core_with_l2.map(_.module.io.debugTopDown.robHeadPaddr)
224        core_with_l2.zip(l3.module.io.debugTopDown.addrMatch).foreach { case (tile, l3Match) => tile.module.io.debugTopDown.l3MissMatch := l3Match }
225      case None => core_with_l2.foreach(_.module.io.debugTopDown.l3MissMatch := false.B)
226    }
227
228    misc.module.debug_module_io.resetCtrl.hartIsInReset := core_with_l2.map(_.module.reset.asBool)
229    misc.module.debug_module_io.clock := io.clock
230    misc.module.debug_module_io.reset := reset_sync
231
232    misc.module.debug_module_io.debugIO.reset := misc.module.reset
233    misc.module.debug_module_io.debugIO.clock := io.clock.asClock
234    // TODO: delay 3 cycles?
235    misc.module.debug_module_io.debugIO.dmactiveAck := misc.module.debug_module_io.debugIO.dmactive
236    // jtag connector
237    misc.module.debug_module_io.debugIO.systemjtag.foreach { x =>
238      x.jtag        <> io.systemjtag.jtag
239      x.reset       := jtag_reset_sync
240      x.mfr_id      := io.systemjtag.mfr_id
241      x.part_number := io.systemjtag.part_number
242      x.version     := io.systemjtag.version
243    }
244
245    withClockAndReset(io.clock.asClock, reset_sync) {
246      // Modules are reset one by one
247      // reset ----> SYNC --> {SoCMisc, L3 Cache, Cores}
248      val resetChain = Seq(Seq(misc.module) ++ l3cacheOpt.map(_.module) ++ core_with_l2.map(_.module))
249      ResetGen(resetChain, reset_sync, !debugOpts.FPGAPlatform)
250    }
251
252  }
253
254  lazy val module = new XSTopImp(this)
255}
256
257object TopMain extends App {
258  val (config, firrtlOpts, firtoolOpts) = ArgParser.parse(args)
259
260  // tools: init to close dpi-c when in fpga
261  val envInFPGA = config(DebugOptionsKey).FPGAPlatform
262  val enableChiselDB = config(DebugOptionsKey).EnableChiselDB
263  val enableConstantin = config(DebugOptionsKey).EnableConstantin
264  Constantin.init(enableConstantin && !envInFPGA)
265  ChiselDB.init(enableChiselDB && !envInFPGA)
266
267  val soc = DisableMonitors(p => LazyModule(new XSTop()(p)))(config)
268  Generator.execute(firrtlOpts, soc.module, firtoolOpts)
269  FileRegisters.write(fileDir = "./build", filePrefix = "XSTop.")
270}
271