xref: /XiangShan/src/main/scala/xiangshan/Bundle.scala (revision 1bc48dd1fa0af361fd194c65bad3b86349ec2903)
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 xiangshan
18
19import org.chipsalliance.cde.config.Parameters
20import chisel3._
21import chisel3.util.BitPat.bitPatToUInt
22import chisel3.util._
23import chisel3.experimental.BundleLiterals._
24import utility._
25import utils._
26import xiangshan.backend.decode.{ImmUnion, XDecode}
27import xiangshan.backend.fu.FuType
28import xiangshan.backend.rob.RobPtr
29import xiangshan.frontend._
30import xiangshan.mem.{LqPtr, SqPtr}
31import xiangshan.backend.Bundles.{DynInst, UopIdx}
32import xiangshan.backend.fu.vector.Bundles.VType
33import xiangshan.frontend.{AllAheadFoldedHistoryOldestBits, AllFoldedHistories, BPUCtrl, CGHPtr, FtqPtr, FtqToCtrlIO}
34import xiangshan.frontend.{Ftq_Redirect_SRAMEntry, HasBPUParameter, IfuToBackendIO, PreDecodeInfo, RASPtr}
35import xiangshan.cache.HasDCacheParameters
36import utility._
37
38import org.chipsalliance.cde.config.Parameters
39import chisel3.util.BitPat.bitPatToUInt
40import chisel3.util.experimental.decode.EspressoMinimizer
41import xiangshan.backend.CtrlToFtqIO
42import xiangshan.backend.fu.NewCSR.{Mcontrol6, Tdata1Bundle, Tdata2Bundle}
43import xiangshan.backend.fu.PMPEntry
44import xiangshan.frontend.Ftq_Redirect_SRAMEntry
45import xiangshan.frontend.AllFoldedHistories
46import xiangshan.frontend.AllAheadFoldedHistoryOldestBits
47import xiangshan.frontend.RASPtr
48import xiangshan.backend.rob.RobBundles.RobCommitEntryBundle
49
50class ValidUndirectioned[T <: Data](gen: T) extends Bundle {
51  val valid = Bool()
52  val bits = gen.cloneType.asInstanceOf[T]
53
54}
55
56object ValidUndirectioned {
57  def apply[T <: Data](gen: T) = {
58    new ValidUndirectioned[T](gen)
59  }
60}
61
62object RSFeedbackType {
63  val lrqFull         = 0.U(4.W)
64  val tlbMiss         = 1.U(4.W)
65  val mshrFull        = 2.U(4.W)
66  val dataInvalid     = 3.U(4.W)
67  val bankConflict    = 4.U(4.W)
68  val ldVioCheckRedo  = 5.U(4.W)
69  val feedbackInvalid = 7.U(4.W)
70  val issueSuccess    = 8.U(4.W)
71  val rfArbitFail     = 9.U(4.W)
72  val fuIdle          = 10.U(4.W)
73  val fuBusy          = 11.U(4.W)
74  val fuUncertain     = 12.U(4.W)
75
76  val allTypes = 16
77  def apply() = UInt(4.W)
78
79  def isStageSuccess(feedbackType: UInt) = {
80    feedbackType === issueSuccess
81  }
82
83  def isBlocked(feedbackType: UInt) = {
84    feedbackType === rfArbitFail || feedbackType === fuBusy || feedbackType >= lrqFull && feedbackType <= feedbackInvalid
85  }
86}
87
88class PredictorAnswer(implicit p: Parameters) extends XSBundle {
89  val hit    = if (!env.FPGAPlatform) Bool() else UInt(0.W)
90  val taken  = if (!env.FPGAPlatform) Bool() else UInt(0.W)
91  val target = if (!env.FPGAPlatform) UInt(VAddrBits.W) else UInt(0.W)
92}
93
94class CfiUpdateInfo(implicit p: Parameters) extends XSBundle with HasBPUParameter {
95  // from backend
96  val pc = UInt(VAddrBits.W)
97  // frontend -> backend -> frontend
98  val pd = new PreDecodeInfo
99  val ssp = UInt(log2Up(RasSize).W)
100  val sctr = UInt(RasCtrSize.W)
101  val TOSW = new RASPtr
102  val TOSR = new RASPtr
103  val NOS = new RASPtr
104  val topAddr = UInt(VAddrBits.W)
105  // val hist = new ShiftingGlobalHistory
106  val folded_hist = new AllFoldedHistories(foldedGHistInfos)
107  val afhob = new AllAheadFoldedHistoryOldestBits(foldedGHistInfos)
108  val lastBrNumOH = UInt((numBr+1).W)
109  val ghr = UInt(UbtbGHRLength.W)
110  val histPtr = new CGHPtr
111  val specCnt = Vec(numBr, UInt(10.W))
112  // need pipeline update
113  val br_hit = Bool() // if in ftb entry
114  val jr_hit = Bool() // if in ftb entry
115  val sc_hit = Bool() // if used in ftb entry, invalid if !br_hit
116  val predTaken = Bool()
117  val target = UInt(VAddrBits.W)
118  val taken = Bool()
119  val isMisPred = Bool()
120  val shift = UInt((log2Ceil(numBr)+1).W)
121  val addIntoHist = Bool()
122  // raise exceptions from backend
123  val backendIGPF = Bool() // instruction guest page fault
124  val backendIPF = Bool() // instruction page fault
125  val backendIAF = Bool() // instruction access fault
126
127  def fromFtqRedirectSram(entry: Ftq_Redirect_SRAMEntry) = {
128    // this.hist := entry.ghist
129    this.histPtr := entry.histPtr
130    this.ssp := entry.ssp
131    this.sctr := entry.sctr
132    this.TOSW := entry.TOSW
133    this.TOSR := entry.TOSR
134    this.NOS := entry.NOS
135    this.topAddr := entry.topAddr
136    this
137  }
138
139  def hasBackendFault = backendIGPF || backendIPF || backendIAF
140}
141
142// Dequeue DecodeWidth insts from Ibuffer
143class CtrlFlow(implicit p: Parameters) extends XSBundle {
144  val instr = UInt(32.W)
145  val pc = UInt(VAddrBits.W)
146  val foldpc = UInt(MemPredPCWidth.W)
147  val exceptionVec = ExceptionVec()
148  val exceptionFromBackend = Bool()
149  val trigger = TriggerAction()
150  val pd = new PreDecodeInfo
151  val pred_taken = Bool()
152  val crossPageIPFFix = Bool()
153  val storeSetHit = Bool() // inst has been allocated an store set
154  val waitForRobIdx = new RobPtr // store set predicted previous store robIdx
155  // Load wait is needed
156  // load inst will not be executed until former store (predicted by mdp) addr calcuated
157  val loadWaitBit = Bool()
158  // If (loadWaitBit && loadWaitStrict), strict load wait is needed
159  // load inst will not be executed until ALL former store addr calcuated
160  val loadWaitStrict = Bool()
161  val ssid = UInt(SSIDWidth.W)
162  val ftqPtr = new FtqPtr
163  val ftqOffset = UInt(log2Up(PredictWidth).W)
164}
165
166
167class FPUCtrlSignals(implicit p: Parameters) extends XSBundle {
168  val isAddSub = Bool() // swap23
169  val typeTagIn = UInt(1.W)
170  val typeTagOut = UInt(1.W)
171  val fromInt = Bool()
172  val wflags = Bool()
173  val fpWen = Bool()
174  val fmaCmd = UInt(2.W)
175  val div = Bool()
176  val sqrt = Bool()
177  val fcvt = Bool()
178  val typ = UInt(2.W)
179  val fmt = UInt(2.W)
180  val ren3 = Bool() //TODO: remove SrcType.fp
181  val rm = UInt(3.W)
182}
183
184// Decode DecodeWidth insts at Decode Stage
185class CtrlSignals(implicit p: Parameters) extends XSBundle {
186  // val debug_globalID = UInt(XLEN.W)
187  val srcType = Vec(4, SrcType())
188  val lsrc = Vec(4, UInt(LogicRegsWidth.W))
189  val ldest = UInt(LogicRegsWidth.W)
190  val fuType = FuType()
191  val fuOpType = FuOpType()
192  val rfWen = Bool()
193  val fpWen = Bool()
194  val vecWen = Bool()
195  val isXSTrap = Bool()
196  val noSpecExec = Bool() // wait forward
197  val blockBackward = Bool() // block backward
198  val flushPipe = Bool() // This inst will flush all the pipe when commit, like exception but can commit
199  val uopSplitType = UopSplitType()
200  val selImm = SelImm()
201  val imm = UInt(32.W)
202  val commitType = CommitType()
203  val fpu = new FPUCtrlSignals
204  val uopIdx = UopIdx()
205  val isMove = Bool()
206  val vm = Bool()
207  val singleStep = Bool()
208  // This inst will flush all the pipe when it is the oldest inst in ROB,
209  // then replay from this inst itself
210  val replayInst = Bool()
211  val canRobCompress = Bool()
212
213  private def allSignals = srcType.take(3) ++ Seq(fuType, fuOpType, rfWen, fpWen, vecWen,
214    isXSTrap, noSpecExec, blockBackward, flushPipe, canRobCompress, uopSplitType, selImm)
215
216  def decode(inst: UInt, table: Iterable[(BitPat, List[BitPat])]): CtrlSignals = {
217    val decoder = freechips.rocketchip.rocket.DecodeLogic(inst, XDecode.decodeDefault, table, EspressoMinimizer)
218    allSignals zip decoder foreach { case (s, d) => s := d }
219    commitType := DontCare
220    this
221  }
222
223  def decode(bit: List[BitPat]): CtrlSignals = {
224    allSignals.zip(bit.map(bitPatToUInt(_))).foreach{ case (s, d) => s := d }
225    this
226  }
227
228  def isWFI: Bool = fuType === FuType.csr.U && fuOpType === CSROpType.wfi
229  def isSoftPrefetch: Bool = {
230    fuType === FuType.alu.U && fuOpType === ALUOpType.or && selImm === SelImm.IMM_I && ldest === 0.U
231  }
232  def needWriteRf: Bool = rfWen || fpWen || vecWen
233  def isHyperInst: Bool = {
234    fuType === FuType.ldu.U && LSUOpType.isHlv(fuOpType) || fuType === FuType.stu.U && LSUOpType.isHsv(fuOpType)
235  }
236}
237
238class CfCtrl(implicit p: Parameters) extends XSBundle {
239  val cf = new CtrlFlow
240  val ctrl = new CtrlSignals
241}
242
243class PerfDebugInfo(implicit p: Parameters) extends XSBundle {
244  val eliminatedMove = Bool()
245  // val fetchTime = UInt(XLEN.W)
246  val renameTime = UInt(XLEN.W)
247  val dispatchTime = UInt(XLEN.W)
248  val enqRsTime = UInt(XLEN.W)
249  val selectTime = UInt(XLEN.W)
250  val issueTime = UInt(XLEN.W)
251  val writebackTime = UInt(XLEN.W)
252  // val commitTime = UInt(XLEN.W)
253  val runahead_checkpoint_id = UInt(XLEN.W)
254  val tlbFirstReqTime = UInt(XLEN.W)
255  val tlbRespTime = UInt(XLEN.W) // when getting hit result (including delay in L2TLB hit)
256}
257
258// Separate LSQ
259class LSIdx(implicit p: Parameters) extends XSBundle {
260  val lqIdx = new LqPtr
261  val sqIdx = new SqPtr
262}
263
264// CfCtrl -> MicroOp at Rename Stage
265class MicroOp(implicit p: Parameters) extends CfCtrl {
266  val srcState = Vec(4, SrcState())
267  val psrc = Vec(4, UInt(PhyRegIdxWidth.W))
268  val pdest = UInt(PhyRegIdxWidth.W)
269  val robIdx = new RobPtr
270  val instrSize = UInt(log2Ceil(RenameWidth + 1).W)
271  val lqIdx = new LqPtr
272  val sqIdx = new SqPtr
273  val eliminatedMove = Bool()
274  val snapshot = Bool()
275  val debugInfo = new PerfDebugInfo
276  def needRfRPort(index: Int, isFp: Boolean, ignoreState: Boolean = true) : Bool = {
277    val stateReady = srcState(index) === SrcState.rdy || ignoreState.B
278    val readReg = if (isFp) {
279      ctrl.srcType(index) === SrcType.fp
280    } else {
281      ctrl.srcType(index) === SrcType.reg && ctrl.lsrc(index) =/= 0.U
282    }
283    readReg && stateReady
284  }
285  def srcIsReady: Vec[Bool] = {
286    VecInit(ctrl.srcType.zip(srcState).map{ case (t, s) => SrcType.isPcOrImm(t) || s === SrcState.rdy })
287  }
288  def clearExceptions(
289    exceptionBits: Seq[Int] = Seq(),
290    flushPipe: Boolean = false,
291    replayInst: Boolean = false
292  ): MicroOp = {
293    cf.exceptionVec.zipWithIndex.filterNot(x => exceptionBits.contains(x._2)).foreach(_._1 := false.B)
294    if (!flushPipe) { ctrl.flushPipe := false.B }
295    if (!replayInst) { ctrl.replayInst := false.B }
296    this
297  }
298}
299
300class XSBundleWithMicroOp(implicit p: Parameters) extends XSBundle {
301  val uop = new DynInst
302}
303
304class MicroOpRbExt(implicit p: Parameters) extends XSBundleWithMicroOp {
305  val flag = UInt(1.W)
306}
307
308class Redirect(implicit p: Parameters) extends XSBundle {
309  val isRVC = Bool()
310  val robIdx = new RobPtr
311  val ftqIdx = new FtqPtr
312  val ftqOffset = UInt(log2Up(PredictWidth).W)
313  val level = RedirectLevel()
314  val interrupt = Bool()
315  val cfiUpdate = new CfiUpdateInfo
316  val fullTarget = UInt(XLEN.W) // only used for tval storage in backend
317
318  val stFtqIdx = new FtqPtr // for load violation predict
319  val stFtqOffset = UInt(log2Up(PredictWidth).W)
320
321  val debug_runahead_checkpoint_id = UInt(64.W)
322  val debugIsCtrl = Bool()
323  val debugIsMemVio = Bool()
324
325  def flushItself() = RedirectLevel.flushItself(level)
326}
327
328object Redirect extends HasCircularQueuePtrHelper {
329
330  def selectOldestRedirect(xs: Seq[Valid[Redirect]]): Vec[Bool] = {
331    val compareVec = (0 until xs.length).map(i => (0 until i).map(j => isAfter(xs(j).bits.robIdx, xs(i).bits.robIdx)))
332    val resultOnehot = VecInit((0 until xs.length).map(i => Cat((0 until xs.length).map(j =>
333      (if (j < i) !xs(j).valid || compareVec(i)(j)
334      else if (j == i) xs(i).valid
335      else !xs(j).valid || !compareVec(j)(i))
336    )).andR))
337    resultOnehot
338  }
339}
340
341class ResetPregStateReq(implicit p: Parameters) extends XSBundle {
342  // NOTE: set isInt and isFp both to 'false' when invalid
343  val isInt = Bool()
344  val isFp = Bool()
345  val isVec = Bool()
346  val isV0 = Bool()
347  val isVl = Bool()
348  val preg = UInt(PhyRegIdxWidth.W)
349}
350
351class DebugBundle(implicit p: Parameters) extends XSBundle {
352  val isMMIO = Bool()
353  val isPerfCnt = Bool()
354  val paddr = UInt(PAddrBits.W)
355  val vaddr = UInt(VAddrBits.W)
356  /* add L/S inst info in EXU */
357  // val L1toL2TlbLatency = UInt(XLEN.W)
358  // val levelTlbHit = UInt(2.W)
359}
360
361class SoftIfetchPrefetchBundle(implicit p: Parameters) extends XSBundle {
362  val vaddr = UInt(VAddrBits.W)
363}
364
365class ExternalInterruptIO(implicit p: Parameters) extends XSBundle {
366  val mtip = Input(Bool())
367  val msip = Input(Bool())
368  val meip = Input(Bool())
369  val seip = Input(Bool())
370  val debug = Input(Bool())
371  val nmi = new NonmaskableInterruptIO()
372}
373
374class NonmaskableInterruptIO() extends Bundle {
375  val nmi_31 = Input(Bool())
376  val nmi_43 = Input(Bool())
377  // reserve for other nmi type
378}
379
380class CSRSpecialIO(implicit p: Parameters) extends XSBundle {
381  val exception = Flipped(ValidIO(new DynInst))
382  val isInterrupt = Input(Bool())
383  val memExceptionVAddr = Input(UInt(VAddrBits.W))
384  val trapTarget = Output(UInt(VAddrBits.W))
385  val externalInterrupt = new ExternalInterruptIO
386  val interrupt = Output(Bool())
387}
388
389class DiffCommitIO(implicit p: Parameters) extends XSBundle {
390  val isCommit = Bool()
391  val commitValid = Vec(CommitWidth * MaxUopSize, Bool())
392
393  val info = Vec(CommitWidth * MaxUopSize, new RabCommitInfo)
394}
395
396class RobCommitInfo(implicit p: Parameters) extends RobCommitEntryBundle
397
398class RobCommitIO(implicit p: Parameters) extends XSBundle {
399  val isCommit = Bool()
400  val commitValid = Vec(CommitWidth, Bool())
401
402  val isWalk = Bool()
403  // valid bits optimized for walk
404  val walkValid = Vec(CommitWidth, Bool())
405
406  val info = Vec(CommitWidth, new RobCommitInfo)
407  val robIdx = Vec(CommitWidth, new RobPtr)
408
409  def hasWalkInstr: Bool = isWalk && walkValid.asUInt.orR
410  def hasCommitInstr: Bool = isCommit && commitValid.asUInt.orR
411}
412
413class RabCommitInfo(implicit p: Parameters) extends XSBundle {
414  val ldest = UInt(LogicRegsWidth.W)
415  val pdest = UInt(PhyRegIdxWidth.W)
416  val rfWen = Bool()
417  val fpWen = Bool()
418  val vecWen = Bool()
419  val v0Wen = Bool()
420  val vlWen = Bool()
421  val isMove = Bool()
422}
423
424class RabCommitIO(implicit p: Parameters) extends XSBundle {
425  val isCommit = Bool()
426  val commitValid = Vec(RabCommitWidth, Bool())
427
428  val isWalk = Bool()
429  // valid bits optimized for walk
430  val walkValid = Vec(RabCommitWidth, Bool())
431
432  val info = Vec(RabCommitWidth, new RabCommitInfo)
433  val robIdx = OptionWrapper(!env.FPGAPlatform, Vec(RabCommitWidth, new RobPtr))
434
435  def hasWalkInstr: Bool = isWalk && walkValid.asUInt.orR
436  def hasCommitInstr: Bool = isCommit && commitValid.asUInt.orR
437}
438
439class SnapshotPort(implicit p: Parameters) extends XSBundle {
440  val snptEnq = Bool()
441  val snptDeq = Bool()
442  val useSnpt = Bool()
443  val snptSelect = UInt(log2Ceil(RenameSnapshotNum).W)
444  val flushVec = Vec(RenameSnapshotNum, Bool())
445}
446
447class RSFeedback(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
448  val robIdx = new RobPtr
449  val hit = Bool()
450  val flushState = Bool()
451  val sourceType = RSFeedbackType()
452  val dataInvalidSqIdx = new SqPtr
453  val sqIdx = new SqPtr
454  val lqIdx = new LqPtr
455}
456
457class MemRSFeedbackIO(isVector: Boolean = false)(implicit p: Parameters) extends XSBundle {
458  // Note: you need to update in implicit Parameters p before imp MemRSFeedbackIO
459  // for instance: MemRSFeedbackIO()(updateP)
460  val feedbackSlow = ValidIO(new RSFeedback(isVector)) // dcache miss queue full, dtlb miss
461  val feedbackFast = ValidIO(new RSFeedback(isVector)) // bank conflict
462}
463
464class LoadCancelIO(implicit p: Parameters) extends XSBundle {
465  val ld1Cancel = Bool()
466  val ld2Cancel = Bool()
467}
468
469class FrontendToCtrlIO(implicit p: Parameters) extends XSBundle {
470  // to backend end
471  val cfVec = Vec(DecodeWidth, DecoupledIO(new CtrlFlow))
472  val stallReason = new StallReasonIO(DecodeWidth)
473  val fromFtq = new FtqToCtrlIO
474  val fromIfu = new IfuToBackendIO
475  // from backend
476  val toFtq = Flipped(new CtrlToFtqIO)
477  val canAccept = Input(Bool())
478}
479
480class SatpStruct(implicit p: Parameters) extends XSBundle {
481  val mode = UInt(4.W)
482  val asid = UInt(16.W)
483  val ppn  = UInt(44.W)
484}
485
486class TlbSatpBundle(implicit p: Parameters) extends SatpStruct {
487  val changed = Bool()
488
489  // Todo: remove it
490  def apply(satp_value: UInt): Unit = {
491    require(satp_value.getWidth == XLEN)
492    val sa = satp_value.asTypeOf(new SatpStruct)
493    mode := sa.mode
494    asid := sa.asid
495    ppn := sa.ppn
496    changed := DataChanged(sa.asid) // when ppn is changed, software need do the flush
497  }
498}
499
500class HgatpStruct(implicit p: Parameters) extends XSBundle {
501  val mode = UInt(4.W)
502  val vmid = UInt(16.W)
503  val ppn  = UInt(44.W)
504}
505
506class TlbHgatpBundle(implicit p: Parameters) extends HgatpStruct {
507  val changed = Bool()
508
509  // Todo: remove it
510  def apply(hgatp_value: UInt): Unit = {
511    require(hgatp_value.getWidth == XLEN)
512    val sa = hgatp_value.asTypeOf(new HgatpStruct)
513    mode := sa.mode
514    vmid := sa.vmid
515    ppn := sa.ppn
516    changed := DataChanged(sa.vmid) // when ppn is changed, software need do the flush
517  }
518}
519
520class TlbCsrBundle(implicit p: Parameters) extends XSBundle {
521  val satp = new TlbSatpBundle()
522  val vsatp = new TlbSatpBundle()
523  val hgatp = new TlbHgatpBundle()
524  val priv = new Bundle {
525    val mxr = Bool()
526    val sum = Bool()
527    val vmxr = Bool()
528    val vsum = Bool()
529    val virt = Bool()
530    val spvp = UInt(1.W)
531    val imode = UInt(2.W)
532    val dmode = UInt(2.W)
533  }
534  val mPBMTE = Bool()
535  val hPBMTE = Bool()
536
537  override def toPrintable: Printable = {
538    p"Satp mode:0x${Hexadecimal(satp.mode)} asid:0x${Hexadecimal(satp.asid)} ppn:0x${Hexadecimal(satp.ppn)} " +
539      p"Priv mxr:${priv.mxr} sum:${priv.sum} imode:${priv.imode} dmode:${priv.dmode}"
540  }
541}
542
543class SfenceBundle(implicit p: Parameters) extends XSBundle {
544  val valid = Bool()
545  val bits = new Bundle {
546    val rs1 = Bool()
547    val rs2 = Bool()
548    val addr = UInt(VAddrBits.W)
549    val id = UInt((AsidLength).W) // asid or vmid
550    val flushPipe = Bool()
551    val hv = Bool()
552    val hg = Bool()
553  }
554
555  override def toPrintable: Printable = {
556    p"valid:0x${Hexadecimal(valid)} rs1:${bits.rs1} rs2:${bits.rs2} addr:${Hexadecimal(bits.addr)}, flushPipe:${bits.flushPipe}"
557  }
558}
559
560// Bundle for load violation predictor updating
561class MemPredUpdateReq(implicit p: Parameters) extends XSBundle  {
562  val valid = Bool()
563
564  // wait table update
565  val waddr = UInt(MemPredPCWidth.W)
566  val wdata = Bool() // true.B by default
567
568  // store set update
569  // by default, ldpc/stpc should be xor folded
570  val ldpc = UInt(MemPredPCWidth.W)
571  val stpc = UInt(MemPredPCWidth.W)
572}
573
574class CustomCSRCtrlIO(implicit p: Parameters) extends XSBundle {
575  // Prefetcher
576  val l1I_pf_enable = Output(Bool())
577  val l2_pf_enable = Output(Bool())
578  val l1D_pf_enable = Output(Bool())
579  val l1D_pf_train_on_hit = Output(Bool())
580  val l1D_pf_enable_agt = Output(Bool())
581  val l1D_pf_enable_pht = Output(Bool())
582  val l1D_pf_active_threshold = Output(UInt(4.W))
583  val l1D_pf_active_stride = Output(UInt(6.W))
584  val l1D_pf_enable_stride = Output(Bool())
585  val l2_pf_store_only = Output(Bool())
586  // ICache
587  val icache_parity_enable = Output(Bool())
588  // Load violation predictor
589  val lvpred_disable = Output(Bool())
590  val no_spec_load = Output(Bool())
591  val storeset_wait_store = Output(Bool())
592  val storeset_no_fast_wakeup = Output(Bool())
593  val lvpred_timeout = Output(UInt(5.W))
594  // Branch predictor
595  val bp_ctrl = Output(new BPUCtrl)
596  // Memory Block
597  val sbuffer_threshold = Output(UInt(4.W))
598  val ldld_vio_check_enable = Output(Bool())
599  val soft_prefetch_enable = Output(Bool())
600  val cache_error_enable = Output(Bool())
601  val uncache_write_outstanding_enable = Output(Bool())
602  val hd_misalign_st_enable = Output(Bool())
603  val hd_misalign_ld_enable = Output(Bool())
604  // Rename
605  val fusion_enable = Output(Bool())
606  val wfi_enable = Output(Bool())
607
608  // distribute csr write signal
609  val distribute_csr = new DistributedCSRIO()
610  // TODO: move it to a new bundle, since single step is not a custom control signal
611  val singlestep = Output(Bool())
612  val frontend_trigger = new FrontendTdataDistributeIO()
613  val mem_trigger = new MemTdataDistributeIO()
614  // Virtualization Mode
615  val virtMode = Output(Bool())
616}
617
618class DistributedCSRIO(implicit p: Parameters) extends XSBundle {
619  // CSR has been written by csr inst, copies of csr should be updated
620  val w = ValidIO(new Bundle {
621    val addr = Output(UInt(12.W))
622    val data = Output(UInt(XLEN.W))
623  })
624}
625
626class DistributedCSRUpdateReq(implicit p: Parameters) extends XSBundle {
627  // Request csr to be updated
628  //
629  // Note that this request will ONLY update CSR Module it self,
630  // copies of csr will NOT be updated, use it with care!
631  //
632  // For each cycle, no more than 1 DistributedCSRUpdateReq is valid
633  val w = ValidIO(new Bundle {
634    val addr = Output(UInt(12.W))
635    val data = Output(UInt(XLEN.W))
636  })
637  def apply(valid: Bool, addr: UInt, data: UInt, src_description: String) = {
638    when(valid){
639      w.bits.addr := addr
640      w.bits.data := data
641    }
642    println("Distributed CSR update req registered for " + src_description)
643  }
644}
645
646class AddrTransType(implicit p: Parameters) extends XSBundle {
647  val bare, sv39, sv39x4, sv48, sv48x4 = Bool()
648
649  def checkAccessFault(target: UInt): Bool = bare && target(XLEN - 1, PAddrBits).orR
650  def checkPageFault(target: UInt): Bool =
651    sv39 && target(XLEN - 1, 39) =/= VecInit.fill(XLEN - 39)(target(38)).asUInt ||
652    sv48 && target(XLEN - 1, 48) =/= VecInit.fill(XLEN - 48)(target(47)).asUInt
653  def checkGuestPageFault(target: UInt): Bool =
654    sv39x4 && target(XLEN - 1, 41).orR || sv48x4 && target(XLEN - 1, 50).orR
655}
656
657object AddrTransType {
658  def apply(bare: Boolean = false,
659            sv39: Boolean = false,
660            sv39x4: Boolean = false,
661            sv48: Boolean = false,
662            sv48x4: Boolean = false)(implicit p: Parameters): AddrTransType =
663    (new AddrTransType).Lit(_.bare -> bare.B,
664                            _.sv39 -> sv39.B,
665                            _.sv39x4 -> sv39x4.B,
666                            _.sv48 -> sv48.B,
667                            _.sv48x4 -> sv48x4.B)
668
669  def apply(bare: Bool, sv39: Bool, sv39x4: Bool, sv48: Bool, sv48x4: Bool)(implicit p: Parameters): AddrTransType = {
670    val addrTransType = Wire(new AddrTransType)
671    addrTransType.bare := bare
672    addrTransType.sv39 := sv39
673    addrTransType.sv39x4 := sv39x4
674    addrTransType.sv48 := sv48
675    addrTransType.sv48x4 := sv48x4
676    addrTransType
677  }
678}
679
680class L1CacheErrorInfo(implicit p: Parameters) extends XSBundle {
681  // L1CacheErrorInfo is also used to encode customized CACHE_ERROR CSR
682  val source = Output(new Bundle() {
683    val tag = Bool() // l1 tag array
684    val data = Bool() // l1 data array
685    val l2 = Bool()
686  })
687  val opType = Output(new Bundle() {
688    val fetch = Bool()
689    val load = Bool()
690    val store = Bool()
691    val probe = Bool()
692    val release = Bool()
693    val atom = Bool()
694  })
695  val paddr = Output(UInt(PAddrBits.W))
696
697  // report error and paddr to beu
698  // bus error unit will receive error info iff ecc_error.valid
699  val report_to_beu = Output(Bool())
700
701  def toL1BusErrorUnitInfo(valid: Bool): L1BusErrorUnitInfo = {
702    val beu_info = Wire(new L1BusErrorUnitInfo)
703    beu_info.ecc_error.valid := valid && report_to_beu
704    beu_info.ecc_error.bits := paddr
705    beu_info
706  }
707}
708
709object TriggerAction extends NamedUInt(4) {
710  // Put breakpoint Exception gererated by trigger in ExceptionVec[3].
711  def BreakpointExp = 0.U(width.W)  // raise breakpoint exception
712  def DebugMode     = 1.U(width.W)  // enter debug mode
713  def TraceOn       = 2.U(width.W)
714  def TraceOff      = 3.U(width.W)
715  def TraceNotify   = 4.U(width.W)
716  def None          = 15.U(width.W) // use triggerAction = 15.U to express that action is None;
717
718  def isExp(action: UInt)   = action === BreakpointExp
719  def isDmode(action: UInt) = action === DebugMode
720  def isNone(action: UInt)  = action === None
721}
722
723// these 3 bundles help distribute trigger control signals from CSR
724// to Frontend, Load and Store.
725class FrontendTdataDistributeIO(implicit p: Parameters) extends XSBundle {
726  val tUpdate = ValidIO(new Bundle {
727    val addr = Output(UInt(log2Up(TriggerNum).W))
728    val tdata = new MatchTriggerIO
729  })
730  val tEnableVec: Vec[Bool] = Output(Vec(TriggerNum, Bool()))
731  val debugMode = Output(Bool())
732  val triggerCanRaiseBpExp = Output(Bool())
733}
734
735class MemTdataDistributeIO(implicit p: Parameters) extends XSBundle {
736  val tUpdate = ValidIO(new Bundle {
737    val addr = Output(UInt(log2Up(TriggerNum).W))
738    val tdata = new MatchTriggerIO
739  })
740  val tEnableVec: Vec[Bool] = Output(Vec(TriggerNum, Bool()))
741  val debugMode = Output(Bool())
742  val triggerCanRaiseBpExp  = Output(Bool())
743}
744
745class MatchTriggerIO(implicit p: Parameters) extends XSBundle {
746  val matchType = Output(UInt(2.W))
747  val select    = Output(Bool())
748  val timing    = Output(Bool())
749  val action    = Output(TriggerAction())
750  val chain     = Output(Bool())
751  val execute   = Output(Bool())
752  val store     = Output(Bool())
753  val load      = Output(Bool())
754  val tdata2    = Output(UInt(64.W))
755
756  def GenTdataDistribute(tdata1: Tdata1Bundle, tdata2: Tdata2Bundle): MatchTriggerIO = {
757    val mcontrol6 = Wire(new Mcontrol6)
758    mcontrol6 := tdata1.DATA.asUInt
759    this.matchType := mcontrol6.MATCH.asUInt
760    this.select    := mcontrol6.SELECT.asBool
761    this.timing    := false.B
762    this.action    := mcontrol6.ACTION.asUInt
763    this.chain     := mcontrol6.CHAIN.asBool
764    this.execute   := mcontrol6.EXECUTE.asBool
765    this.load      := mcontrol6.LOAD.asBool
766    this.store     := mcontrol6.STORE.asBool
767    this.tdata2    := tdata2.asUInt
768    this
769  }
770}
771
772class StallReasonIO(width: Int) extends Bundle {
773  val reason = Output(Vec(width, UInt(log2Ceil(TopDownCounters.NumStallReasons.id).W)))
774  val backReason = Flipped(Valid(UInt(log2Ceil(TopDownCounters.NumStallReasons.id).W)))
775}
776
777// custom l2 - l1 interface
778class L2ToL1Hint(implicit p: Parameters) extends XSBundle with HasDCacheParameters {
779  val sourceId = UInt(log2Up(cfg.nMissEntries).W)    // tilelink sourceID -> mshr id
780  val isKeyword = Bool()                             // miss entry keyword -> L1 load queue replay
781}
782
783