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