xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/Repeater.scala (revision e4d4d30585412eb8ac83b5c75599a348356342a2)
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.cache.mmu
18
19import org.chipsalliance.cde.config.Parameters
20import chisel3._
21import chisel3.util._
22import xiangshan._
23import xiangshan.cache.{HasDCacheParameters, MemoryOpConstants}
24import utils._
25import utility._
26import freechips.rocketchip.diplomacy.{LazyModule, LazyModuleImp}
27import freechips.rocketchip.tilelink._
28
29class PTWReapterIO(Width: Int)(implicit p: Parameters) extends MMUIOBaseBundle {
30  val tlb = Flipped(new TlbPtwIO(Width))
31  val ptw = new TlbPtwIO
32
33  def apply(tlb: TlbPtwIO, ptw: TlbPtwIO, sfence: SfenceBundle, csr: TlbCsrBundle): Unit = {
34    this.tlb <> tlb
35    this.ptw <> ptw
36    this.sfence <> sfence
37    this.csr <> csr
38  }
39
40  def apply(tlb: TlbPtwIO, sfence: SfenceBundle, csr: TlbCsrBundle): Unit = {
41    this.tlb <> tlb
42    this.sfence <> sfence
43    this.csr <> csr
44  }
45
46}
47
48class PTWRepeater(Width: Int = 1, FenceDelay: Int)(implicit p: Parameters) extends XSModule with HasPtwConst {
49  val io = IO(new PTWReapterIO(Width))
50
51  val req_in = if (Width == 1) {
52    io.tlb.req(0)
53  } else {
54    val arb = Module(new RRArbiter(io.tlb.req(0).bits.cloneType, Width))
55    arb.io.in <> io.tlb.req
56    arb.io.out
57  }
58  val (tlb, ptw, flush) = (io.tlb, io.ptw, DelayN(io.sfence.valid || io.csr.satp.changed, FenceDelay))
59  val req = RegEnable(req_in.bits, req_in.fire)
60  val resp = RegEnable(ptw.resp.bits, ptw.resp.fire)
61  val haveOne = BoolStopWatch(req_in.fire, tlb.resp.fire || flush)
62  val sent = BoolStopWatch(ptw.req(0).fire, req_in.fire || flush)
63  val recv = BoolStopWatch(ptw.resp.fire && haveOne, req_in.fire || flush)
64
65  req_in.ready := !haveOne
66  ptw.req(0).valid := haveOne && !sent
67  ptw.req(0).bits := req
68
69  tlb.resp.bits := resp
70  tlb.resp.valid := haveOne && recv
71  ptw.resp.ready := !recv
72
73  XSPerfAccumulate("req_count", ptw.req(0).fire)
74  XSPerfAccumulate("tlb_req_cycle", BoolStopWatch(req_in.fire, tlb.resp.fire || flush))
75  XSPerfAccumulate("ptw_req_cycle", BoolStopWatch(ptw.req(0).fire, ptw.resp.fire || flush))
76
77  XSDebug(haveOne, p"haveOne:${haveOne} sent:${sent} recv:${recv} sfence:${flush} req:${req} resp:${resp}")
78  XSDebug(req_in.valid || io.tlb.resp.valid, p"tlb: ${tlb}\n")
79  XSDebug(io.ptw.req(0).valid || io.ptw.resp.valid, p"ptw: ${ptw}\n")
80  assert(!RegNext(recv && io.ptw.resp.valid, init = false.B), "re-receive ptw.resp")
81  XSError(io.ptw.req(0).valid && io.ptw.resp.valid && !flush, "ptw repeater recv resp when sending")
82  XSError(io.ptw.resp.valid && (req.vpn =/= io.ptw.resp.bits.entry.tag), "ptw repeater recv resp with wrong tag")
83  XSError(io.ptw.resp.valid && !io.ptw.resp.ready, "ptw repeater's ptw resp back, but not ready")
84  TimeOutAssert(sent && !recv, timeOutThreshold, "Repeater doesn't recv resp in time")
85}
86
87/* dtlb
88 *
89 */
90
91class PTWRepeaterNB(Width: Int = 1, passReady: Boolean = false, FenceDelay: Int)(implicit p: Parameters) extends XSModule with HasPtwConst {
92  val io = IO(new PTWReapterIO(Width))
93
94  val req_in = if (Width == 1) {
95    io.tlb.req(0)
96  } else {
97    val arb = Module(new RRArbiter(io.tlb.req(0).bits.cloneType, Width))
98    arb.io.in <> io.tlb.req
99    arb.io.out
100  }
101  val (tlb, ptw, flush) = (io.tlb, io.ptw, DelayN(io.sfence.valid || io.csr.satp.changed, FenceDelay))
102  /* sent: tlb -> repeater -> ptw
103   * recv: ptw -> repeater -> tlb
104   * different from PTWRepeater
105   */
106
107  // tlb -> repeater -> ptw
108  val req = RegEnable(req_in.bits, req_in.fire)
109  val sent = BoolStopWatch(req_in.fire, ptw.req(0).fire || flush)
110  req_in.ready := !sent || { if (passReady) ptw.req(0).ready else false.B }
111  ptw.req(0).valid := sent
112  ptw.req(0).bits := req
113
114  // ptw -> repeater -> tlb
115  val resp = RegEnable(ptw.resp.bits, ptw.resp.fire)
116  val recv = BoolStopWatch(ptw.resp.fire, tlb.resp.fire || flush)
117  ptw.resp.ready := !recv || { if (passReady) tlb.resp.ready else false.B }
118  tlb.resp.valid := recv
119  tlb.resp.bits := resp
120
121  XSPerfAccumulate("req", req_in.fire)
122  XSPerfAccumulate("resp", tlb.resp.fire)
123  if (!passReady) {
124    XSPerfAccumulate("req_blank", req_in.valid && sent && ptw.req(0).ready)
125    XSPerfAccumulate("resp_blank", ptw.resp.valid && recv && tlb.resp.ready)
126    XSPerfAccumulate("req_blank_ignore_ready", req_in.valid && sent)
127    XSPerfAccumulate("resp_blank_ignore_ready", ptw.resp.valid && recv)
128  }
129  XSDebug(req_in.valid || io.tlb.resp.valid, p"tlb: ${tlb}\n")
130  XSDebug(io.ptw.req(0).valid || io.ptw.resp.valid, p"ptw: ${ptw}\n")
131}
132
133class PTWFilterIO(Width: Int, hasHint: Boolean = false)(implicit p: Parameters) extends MMUIOBaseBundle {
134  val tlb = Flipped(new VectorTlbPtwIO(Width))
135  val ptw = new TlbPtwIO()
136  val hint = if (hasHint) Some(new TlbHintIO) else None
137  val rob_head_miss_in_tlb = Output(Bool())
138  val debugTopDown = new Bundle {
139    val robHeadVaddr = Flipped(Valid(UInt(VAddrBits.W)))
140  }
141
142  def apply(tlb: VectorTlbPtwIO, ptw: TlbPtwIO, sfence: SfenceBundle, csr: TlbCsrBundle): Unit = {
143    this.tlb <> tlb
144    this.ptw <> ptw
145    this.sfence <> sfence
146    this.csr <> csr
147  }
148
149  def apply(tlb: VectorTlbPtwIO, sfence: SfenceBundle, csr: TlbCsrBundle): Unit = {
150    this.tlb <> tlb
151    this.sfence <> sfence
152    this.csr <> csr
153  }
154
155}
156
157class PTWFilterEntryIO(Width: Int, hasHint: Boolean = false)(implicit p: Parameters) extends PTWFilterIO(Width, hasHint){
158  val flush = Input(Bool())
159  val refill = Output(Bool())
160  val memidx = Output(new MemBlockidxBundle)
161}
162
163class PTWFilterEntry(Width: Int, Size: Int, hasHint: Boolean = false)(implicit p: Parameters) extends XSModule with HasPtwConst {
164  private val LdExuCnt = backendParams.LdExuCnt
165
166  val io = IO(new PTWFilterEntryIO(Width, hasHint))
167  require(isPow2(Size), s"Filter Size ($Size) must be a power of 2")
168
169  def firstValidIndex(v: Seq[Bool], valid: Bool): UInt = {
170    val index = WireInit(0.U(log2Up(Size).W))
171    for (i <- 0 until v.size) {
172      when (v(i) === valid) {
173        index := i.U
174      }
175    }
176    index
177  }
178
179  val v = RegInit(VecInit(Seq.fill(Size)(false.B)))
180  val sent = RegInit(VecInit(Seq.fill(Size)(false.B)))
181  val vpn = Reg(Vec(Size, UInt(vpnLen.W)))
182  val memidx = Reg(Vec(Size, new MemBlockidxBundle))
183
184  val enqvalid = WireInit(VecInit(Seq.fill(Width)(false.B)))
185  val canenq = WireInit(VecInit(Seq.fill(Width)(false.B)))
186  val enqidx = WireInit(VecInit(Seq.fill(Width)(0.U(log2Up(Size).W))))
187
188  //val selectCount = RegInit(0.U(log2Up(Width).W))
189
190  val entryIsMatchVec = WireInit(VecInit(Seq.fill(Width)(false.B)))
191  val entryMatchIndexVec = WireInit(VecInit(Seq.fill(Width)(0.U(log2Up(Size).W))))
192  val ptwResp_EntryMatchVec = vpn.zip(v).map{ case (pi, vi) => vi && io.ptw.resp.bits.hit(pi, io.csr.satp.asid, true, true)}
193  val ptwResp_EntryMatchFirst = firstValidIndex(ptwResp_EntryMatchVec, true.B)
194  val ptwResp_ReqMatchVec = io.tlb.req.map(a => io.ptw.resp.valid && io.ptw.resp.bits.hit(a.bits.vpn, 0.U, allType = true, true))
195
196  io.refill := Cat(ptwResp_EntryMatchVec).orR && io.ptw.resp.fire
197  io.ptw.resp.ready := true.B
198  // DontCare
199  io.tlb.req.map(_.ready := true.B)
200  io.tlb.resp.valid := false.B
201  io.tlb.resp.bits.data := 0.U.asTypeOf(new PtwSectorRespwithMemIdx)
202  io.tlb.resp.bits.vector := 0.U.asTypeOf(Vec(Width, Bool()))
203  io.memidx := 0.U.asTypeOf(new MemBlockidxBundle)
204
205  // ugly code, should be optimized later
206  require(Width <= 4, s"DTLB Filter Width ($Width) must equal or less than 4")
207  if (Width == 1) {
208    require(Size == 8, s"prefetch filter Size ($Size) should be 8")
209    canenq(0) := !(Cat(v).andR)
210    enqidx(0) := firstValidIndex(v, false.B)
211  } else if (Width == 2) {
212    require(Size == 8, s"store filter Size ($Size) should be 8")
213    canenq(0) := !(Cat(v.take(Size/2)).andR)
214    enqidx(0) := firstValidIndex(v.take(Size/2), false.B)
215    canenq(1) := !(Cat(v.drop(Size/2)).andR)
216    enqidx(1) := firstValidIndex(v.drop(Size/2), false.B) + (Size/2).U
217  } else if (Width == 3) {
218    require(Size == 16, s"load filter Size ($Size) should be 16")
219    canenq(0) := !(Cat(v.take(8)).andR)
220    enqidx(0) := firstValidIndex(v.take(8), false.B)
221    canenq(1) := !(Cat(v.drop(8).take(4)).andR)
222    enqidx(1) := firstValidIndex(v.drop(8).take(4), false.B) + 8.U
223    // four entries for prefetch
224    canenq(2) := !(Cat(v.drop(12)).andR)
225    enqidx(2) := firstValidIndex(v.drop(12), false.B) + 12.U
226  } else if (Width == 4) {
227    require(Size == 16, s"load filter Size ($Size) should be 16")
228    for (i <- 0 until Width) {
229      canenq(i) := !(Cat(VecInit(v.slice(i * 4, (i + 1) * 4))).andR)
230      enqidx(i) := firstValidIndex(v.slice(i * 4, (i + 1) * 4), false.B) + (i * 4).U
231    }
232  }
233
234  for (i <- 0 until Width) {
235    enqvalid(i) := io.tlb.req(i).valid && !ptwResp_ReqMatchVec(i) && !entryIsMatchVec(i) && canenq(i)
236    when (!enqvalid(i)) {
237      enqidx(i) := entryMatchIndexVec(i)
238    }
239
240    val entryIsMatch = vpn.zip(v).map{ case (pi, vi) => vi && pi === io.tlb.req(i).bits.vpn}
241    entryIsMatchVec(i) := Cat(entryIsMatch).orR
242    entryMatchIndexVec(i) := firstValidIndex(entryIsMatch, true.B)
243
244    if (i > 0) {
245      for (j <- 0 until i) {
246        val newIsMatch = io.tlb.req(i).bits.vpn === io.tlb.req(j).bits.vpn
247        when (newIsMatch && io.tlb.req(j).valid) {
248          enqidx(i) := enqidx(j)
249          canenq(i) := canenq(j)
250          enqvalid(i) := false.B
251        }
252      }
253    }
254
255    when (enqvalid(i)) {
256      v(enqidx(i)) := true.B
257      sent(enqidx(i)) := false.B
258      vpn(enqidx(i)) := io.tlb.req(i).bits.vpn
259      memidx(enqidx(i)) := io.tlb.req(i).bits.memidx
260    }
261  }
262
263  val issuevec = v.zip(sent).map{ case (v, s) => v && !s}
264  val issueindex = firstValidIndex(issuevec, true.B)
265  val canissue = Cat(issuevec).orR
266  for (i <- 0 until Size) {
267    io.ptw.req(0).valid := canissue
268    io.ptw.req(0).bits.vpn := vpn(issueindex)
269  }
270  when (io.ptw.req(0).fire) {
271    sent(issueindex) := true.B
272  }
273
274  when (io.ptw.resp.fire) {
275    v.zip(ptwResp_EntryMatchVec).map{ case (vi, mi) => when (mi) { vi := false.B }}
276    io.memidx := memidx(ptwResp_EntryMatchFirst)
277  }
278
279  when (io.flush) {
280    v.map(_ := false.B)
281  }
282
283  if (hasHint) {
284    val hintIO = io.hint.getOrElse(new TlbHintIO)
285    for (i <- 0 until LdExuCnt) {
286      hintIO.req(i).id := enqidx(i)
287      hintIO.req(i).full := !canenq(i) || ptwResp_ReqMatchVec(i)
288    }
289    hintIO.resp.valid := io.refill
290    hintIO.resp.bits.id := ptwResp_EntryMatchFirst
291    hintIO.resp.bits.replay_all := PopCount(ptwResp_EntryMatchVec) > 1.U
292  }
293
294  io.rob_head_miss_in_tlb := VecInit(v.zip(vpn).map{case (vi, vpni) => {
295    vi && io.debugTopDown.robHeadVaddr.valid && vpni === get_pn(io.debugTopDown.robHeadVaddr.bits)
296  }}).asUInt.orR
297
298
299  // Perf Counter
300  val counter = PopCount(v)
301  val inflight_counter = RegInit(0.U(log2Up(Size).W))
302  val inflight_full = inflight_counter === Size.U
303  when (io.ptw.req(0).fire =/= io.ptw.resp.fire) {
304    inflight_counter := Mux(io.ptw.req(0).fire, inflight_counter + 1.U, inflight_counter - 1.U)
305  }
306
307  assert(inflight_counter <= Size.U, "inflight should be no more than Size")
308  when (counter === 0.U) {
309    assert(!io.ptw.req(0).fire, "when counter is 0, should not req")
310  }
311
312  when (io.flush) {
313    inflight_counter := 0.U
314  }
315
316  XSPerfAccumulate("tlb_req_count", PopCount(Cat(io.tlb.req.map(_.valid))))
317  XSPerfAccumulate("tlb_req_count_filtered", PopCount(enqvalid))
318  XSPerfAccumulate("ptw_req_count", io.ptw.req(0).fire)
319  XSPerfAccumulate("ptw_req_cycle", inflight_counter)
320  XSPerfAccumulate("tlb_resp_count", io.tlb.resp.fire)
321  XSPerfAccumulate("ptw_resp_count", io.ptw.resp.fire)
322  XSPerfAccumulate("inflight_cycle", Cat(sent).orR)
323
324  for (i <- 0 until Size + 1) {
325    XSPerfAccumulate(s"counter${i}", counter === i.U)
326  }
327
328  for (i <- 0 until Size) {
329    TimeOutAssert(v(i), timeOutThreshold, s"Filter ${i} doesn't recv resp in time")
330  }
331
332}
333
334class PTWNewFilter(Width: Int, Size: Int, FenceDelay: Int)(implicit p: Parameters) extends XSModule with HasPtwConst {
335  require(Size >= Width)
336
337  private val LduCnt = backendParams.LduCnt
338  private val HyuCnt = backendParams.HyuCnt
339  private val StaCnt = backendParams.StaCnt
340  // all load execute units, including ldu and hyu
341  private val LdExuCnt = backendParams.LdExuCnt
342  // all store address execute units, including sta and hyu
343  private val StaExuCnt = backendParams.StaExuCnt
344
345  val io = IO(new PTWFilterIO(Width, hasHint = true))
346
347  val load_filter = VecInit(Seq.fill(1) {
348    val load_entry = Module(new PTWFilterEntry(Width = LdExuCnt + 1, Size = loadfiltersize, hasHint = true))
349    load_entry.io
350  })
351
352  val store_filter = VecInit(Seq.fill(1) {
353    val store_entry = Module(new PTWFilterEntry(Width = StaCnt, Size = storefiltersize))
354    store_entry.io
355  })
356
357  val prefetch_filter = VecInit(Seq.fill(1) {
358    val prefetch_entry = Module(new PTWFilterEntry(Width = 1, Size = prefetchfiltersize))
359    prefetch_entry.io
360  })
361
362  val filter = load_filter ++ store_filter ++ prefetch_filter
363
364  load_filter.map(_.tlb.req := io.tlb.req.take(LdExuCnt + 1))
365  store_filter.map(_.tlb.req := io.tlb.req.drop(LdExuCnt + 1).take(StaCnt))
366  prefetch_filter.map(_.tlb.req := io.tlb.req.drop(LdExuCnt + 1 + StaCnt))
367
368  val flush = DelayN(io.sfence.valid || io.csr.satp.changed, FenceDelay)
369  val ptwResp = RegEnable(io.ptw.resp.bits, io.ptw.resp.fire)
370  val ptwResp_valid = Cat(filter.map(_.refill)).orR
371  filter.map(_.tlb.resp.ready := true.B)
372  filter.map(_.ptw.resp.valid := RegNext(io.ptw.resp.fire, init = false.B))
373  filter.map(_.ptw.resp.bits := ptwResp)
374  filter.map(_.flush := flush)
375  filter.map(_.sfence := io.sfence)
376  filter.map(_.csr := io.csr)
377  filter.map(_.debugTopDown.robHeadVaddr := io.debugTopDown.robHeadVaddr)
378
379  io.tlb.req.map(_.ready := true.B)
380  io.tlb.resp.valid := ptwResp_valid
381  io.tlb.resp.bits.data.entry := ptwResp.entry
382  io.tlb.resp.bits.data.addr_low := ptwResp.addr_low
383  io.tlb.resp.bits.data.ppn_low := ptwResp.ppn_low
384  io.tlb.resp.bits.data.valididx := ptwResp.valididx
385  io.tlb.resp.bits.data.pteidx := ptwResp.pteidx
386  io.tlb.resp.bits.data.pf := ptwResp.pf
387  io.tlb.resp.bits.data.af := ptwResp.af
388  io.tlb.resp.bits.data.memidx := 0.U.asTypeOf(new MemBlockidxBundle)
389  // vector used to represent different requestors of DTLB
390  // (e.g. the store DTLB has StuCnt requestors)
391  // However, it is only necessary to distinguish between different DTLB now
392  for (i <- 0 until Width) {
393    io.tlb.resp.bits.vector(i) := false.B
394  }
395  io.tlb.resp.bits.vector(0) := load_filter(0).refill
396  io.tlb.resp.bits.vector(LdExuCnt + 1) := store_filter(0).refill
397  io.tlb.resp.bits.vector(LdExuCnt + 1 + StaCnt) := prefetch_filter(0).refill
398
399  val hintIO = io.hint.getOrElse(new TlbHintIO)
400  val load_hintIO = load_filter(0).hint.getOrElse(new TlbHintIO)
401  for (i <- 0 until LdExuCnt) {
402    hintIO.req(i) := RegNext(load_hintIO.req(i))
403  }
404  hintIO.resp := RegNext(load_hintIO.resp)
405
406  when (load_filter(0).refill) {
407    io.tlb.resp.bits.vector(0) := true.B
408    io.tlb.resp.bits.data.memidx := load_filter(0).memidx
409  }
410  when (store_filter(0).refill) {
411    io.tlb.resp.bits.vector(LdExuCnt + 1) := true.B
412    io.tlb.resp.bits.data.memidx := store_filter(0).memidx
413  }
414  when (prefetch_filter(0).refill) {
415    io.tlb.resp.bits.vector(LdExuCnt + 1 + StaCnt) := true.B
416    io.tlb.resp.bits.data.memidx := 0.U.asTypeOf(new MemBlockidxBundle)
417  }
418
419  val ptw_arb = Module(new RRArbiterInit(new PtwReq, 3))
420  for (i <- 0 until 3) {
421    ptw_arb.io.in(i).valid := filter(i).ptw.req(0).valid
422    ptw_arb.io.in(i).bits.vpn := filter(i).ptw.req(0).bits.vpn
423    filter(i).ptw.req(0).ready := ptw_arb.io.in(i).ready
424  }
425  ptw_arb.io.out.ready := io.ptw.req(0).ready
426  io.ptw.req(0).valid := ptw_arb.io.out.valid
427  io.ptw.req(0).bits.vpn := ptw_arb.io.out.bits.vpn
428  io.ptw.resp.ready := true.B
429
430  io.rob_head_miss_in_tlb := Cat(filter.map(_.rob_head_miss_in_tlb)).orR
431}
432
433class PTWFilter(Width: Int, Size: Int, FenceDelay: Int)(implicit p: Parameters) extends XSModule with HasPtwConst {
434  require(Size >= Width)
435
436  val io = IO(new PTWFilterIO(Width))
437
438  val v = RegInit(VecInit(Seq.fill(Size)(false.B)))
439  val ports = Reg(Vec(Size, Vec(Width, Bool()))) // record which port(s) the entry come from, may not able to cover all the ports
440  val vpn = Reg(Vec(Size, UInt(vpnLen.W)))
441  val memidx = Reg(Vec(Size, new MemBlockidxBundle))
442  val enqPtr = RegInit(0.U(log2Up(Size).W)) // Enq
443  val issPtr = RegInit(0.U(log2Up(Size).W)) // Iss to Ptw
444  val deqPtr = RegInit(0.U(log2Up(Size).W)) // Deq
445  val mayFullDeq = RegInit(false.B)
446  val mayFullIss = RegInit(false.B)
447  val counter = RegInit(0.U(log2Up(Size+1).W))
448
449  val flush = DelayN(io.sfence.valid || io.csr.satp.changed, FenceDelay)
450  val tlb_req = WireInit(io.tlb.req) // NOTE: tlb_req is not io.tlb.req, see below codes, just use cloneType
451  tlb_req.suggestName("tlb_req")
452
453  val inflight_counter = RegInit(0.U(log2Up(Size + 1).W))
454  val inflight_full = inflight_counter === Size.U
455  when (io.ptw.req(0).fire =/= io.ptw.resp.fire) {
456    inflight_counter := Mux(io.ptw.req(0).fire, inflight_counter + 1.U, inflight_counter - 1.U)
457  }
458
459  val canEnqueue = Wire(Bool()) // NOTE: actually enqueue
460  val ptwResp = RegEnable(io.ptw.resp.bits, io.ptw.resp.fire)
461  val ptwResp_OldMatchVec = vpn.zip(v).map{ case (pi, vi) =>
462    vi && io.ptw.resp.bits.hit(pi, io.csr.satp.asid, true, true)}
463  val ptwResp_valid = RegNext(io.ptw.resp.fire && Cat(ptwResp_OldMatchVec).orR, init = false.B)
464  // May send repeated requests to L2 tlb with same vpn(26, 3) when sector tlb
465  val oldMatchVec_early = io.tlb.req.map(a => vpn.zip(v).map{ case (pi, vi) => vi && pi === a.bits.vpn})
466  val lastReqMatchVec_early = io.tlb.req.map(a => tlb_req.map{ b => b.valid && b.bits.vpn === a.bits.vpn && canEnqueue})
467  val newMatchVec_early = io.tlb.req.map(a => io.tlb.req.map(b => a.bits.vpn === b.bits.vpn))
468
469  (0 until Width) foreach { i =>
470    tlb_req(i).valid := RegNext(io.tlb.req(i).valid &&
471      !(ptwResp_valid && ptwResp.hit(io.tlb.req(i).bits.vpn, 0.U, true, true)) &&
472      !Cat(lastReqMatchVec_early(i)).orR,
473      init = false.B)
474    tlb_req(i).bits := RegEnable(io.tlb.req(i).bits, io.tlb.req(i).valid)
475  }
476
477  val oldMatchVec = oldMatchVec_early.map(a => RegNext(Cat(a).orR))
478  val newMatchVec = (0 until Width).map(i => (0 until Width).map(j =>
479    RegNext(newMatchVec_early(i)(j)) && tlb_req(j).valid
480  ))
481  val ptwResp_newMatchVec = tlb_req.map(a =>
482    ptwResp_valid && ptwResp.hit(a.bits.vpn, 0.U, allType = true, true))
483
484  val oldMatchVec2 = (0 until Width).map(i => oldMatchVec_early(i).map(RegNext(_)).map(_ & tlb_req(i).valid))
485  val update_ports = v.indices.map(i => oldMatchVec2.map(j => j(i)))
486  val ports_init = (0 until Width).map(i => (1 << i).U(Width.W))
487  val filter_ports = (0 until Width).map(i => ParallelMux(newMatchVec(i).zip(ports_init).drop(i)))
488  val resp_vector = RegEnable(ParallelMux(ptwResp_OldMatchVec zip ports), io.ptw.resp.fire)
489
490  def canMerge(index: Int) : Bool = {
491    ptwResp_newMatchVec(index) || oldMatchVec(index) ||
492    Cat(newMatchVec(index).take(index)).orR
493  }
494
495  def filter_req() = {
496    val reqs =  tlb_req.indices.map{ i =>
497      val req = Wire(ValidIO(new PtwReqwithMemIdx()))
498      val merge = canMerge(i)
499      req.bits := tlb_req(i).bits
500      req.valid := !merge && tlb_req(i).valid
501      req
502    }
503    reqs
504  }
505
506  val reqs = filter_req()
507  val req_ports = filter_ports
508  val isFull = enqPtr === deqPtr && mayFullDeq
509  val isEmptyDeq = enqPtr === deqPtr && !mayFullDeq
510  val isEmptyIss = enqPtr === issPtr && !mayFullIss
511  val accumEnqNum = (0 until Width).map(i => PopCount(reqs.take(i).map(_.valid)))
512  val enqPtrVecInit = VecInit((0 until Width).map(i => enqPtr + i.U))
513  val enqPtrVec = VecInit((0 until Width).map(i => enqPtrVecInit(accumEnqNum(i))))
514  val enqNum = PopCount(reqs.map(_.valid))
515  canEnqueue := counter +& enqNum <= Size.U
516
517  // the req may recv false ready, but actually received. Filter and TLB will handle it.
518  val enqNum_fake = PopCount(io.tlb.req.map(_.valid))
519  val canEnqueue_fake = counter +& enqNum_fake <= Size.U
520  io.tlb.req.map(_.ready := canEnqueue_fake) // NOTE: just drop un-fire reqs
521
522  // tlb req flushed by ptw resp: last ptw resp && current ptw resp
523  // the flushed tlb req will fakely enq, with a false valid
524  val tlb_req_flushed = reqs.map(a => io.ptw.resp.valid && io.ptw.resp.bits.hit(a.bits.vpn, 0.U, true, true))
525
526  io.tlb.resp.valid := ptwResp_valid
527  io.tlb.resp.bits.data.entry := ptwResp.entry
528  io.tlb.resp.bits.data.addr_low := ptwResp.addr_low
529  io.tlb.resp.bits.data.ppn_low := ptwResp.ppn_low
530  io.tlb.resp.bits.data.valididx := ptwResp.valididx
531  io.tlb.resp.bits.data.pteidx := ptwResp.pteidx
532  io.tlb.resp.bits.data.pf := ptwResp.pf
533  io.tlb.resp.bits.data.af := ptwResp.af
534  io.tlb.resp.bits.data.memidx := memidx(OHToUInt(ptwResp_OldMatchVec))
535  io.tlb.resp.bits.vector := resp_vector
536
537  val issue_valid = v(issPtr) && !isEmptyIss && !inflight_full
538  val issue_filtered = ptwResp_valid && ptwResp.hit(io.ptw.req(0).bits.vpn, io.csr.satp.asid, allType=true, ignoreAsid=true)
539  val issue_fire_fake = issue_valid && (io.ptw.req(0).ready || (issue_filtered && false.B /*timing-opt*/))
540  io.ptw.req(0).valid := issue_valid && !issue_filtered
541  io.ptw.req(0).bits.vpn := vpn(issPtr)
542  io.ptw.resp.ready := true.B
543
544  reqs.zipWithIndex.map{
545    case (req, i) =>
546      when (req.valid && canEnqueue) {
547        v(enqPtrVec(i)) := !tlb_req_flushed(i)
548        vpn(enqPtrVec(i)) := req.bits.vpn
549        memidx(enqPtrVec(i)) := req.bits.memidx
550        ports(enqPtrVec(i)) := req_ports(i).asBools
551      }
552  }
553  for (i <- ports.indices) {
554    when (v(i)) {
555      ports(i) := ports(i).zip(update_ports(i)).map(a => a._1 || a._2)
556    }
557  }
558
559  val do_enq = canEnqueue && Cat(reqs.map(_.valid)).orR
560  val do_deq = (!v(deqPtr) && !isEmptyDeq)
561  val do_iss = issue_fire_fake || (!v(issPtr) && !isEmptyIss)
562  when (do_enq) {
563    enqPtr := enqPtr + enqNum
564  }
565  when (do_deq) {
566    deqPtr := deqPtr + 1.U
567  }
568  when (do_iss) {
569    issPtr := issPtr + 1.U
570  }
571  when (issue_fire_fake && issue_filtered) { // issued but is filtered
572    v(issPtr) := false.B
573  }
574  when (do_enq =/= do_deq) {
575    mayFullDeq := do_enq
576  }
577  when (do_enq =/= do_iss) {
578    mayFullIss := do_enq
579  }
580
581  when (io.ptw.resp.fire) {
582    v.zip(ptwResp_OldMatchVec).map{ case (vi, mi) => when (mi) { vi := false.B }}
583  }
584
585  counter := counter - do_deq + Mux(do_enq, enqNum, 0.U)
586  assert(counter <= Size.U, "counter should be no more than Size")
587  assert(inflight_counter <= Size.U, "inflight should be no more than Size")
588  when (counter === 0.U) {
589    assert(!io.ptw.req(0).fire, "when counter is 0, should not req")
590    assert(isEmptyDeq && isEmptyIss, "when counter is 0, should be empty")
591  }
592  when (counter === Size.U) {
593    assert(mayFullDeq, "when counter is Size, should be full")
594  }
595
596  when (flush) {
597    v.map(_ := false.B)
598    deqPtr := 0.U
599    enqPtr := 0.U
600    issPtr := 0.U
601    ptwResp_valid := false.B
602    mayFullDeq := false.B
603    mayFullIss := false.B
604    counter := 0.U
605    inflight_counter := 0.U
606  }
607
608  val robHeadVaddr = io.debugTopDown.robHeadVaddr
609  io.rob_head_miss_in_tlb := VecInit(v.zip(vpn).map{case (vi, vpni) => {
610    vi && robHeadVaddr.valid && vpni === get_pn(robHeadVaddr.bits)
611  }}).asUInt.orR
612
613  // perf
614  XSPerfAccumulate("tlb_req_count", PopCount(Cat(io.tlb.req.map(_.valid))))
615  XSPerfAccumulate("tlb_req_count_filtered", Mux(do_enq, accumEnqNum(Width - 1), 0.U))
616  XSPerfAccumulate("ptw_req_count", io.ptw.req(0).fire)
617  XSPerfAccumulate("ptw_req_cycle", inflight_counter)
618  XSPerfAccumulate("tlb_resp_count", io.tlb.resp.fire)
619  XSPerfAccumulate("ptw_resp_count", io.ptw.resp.fire)
620  XSPerfAccumulate("inflight_cycle", !isEmptyDeq)
621  for (i <- 0 until Size + 1) {
622    XSPerfAccumulate(s"counter${i}", counter === i.U)
623  }
624
625  for (i <- 0 until Size) {
626    TimeOutAssert(v(i), timeOutThreshold, s"Filter ${i} doesn't recv resp in time")
627  }
628}
629
630object PTWRepeater {
631  def apply(fenceDelay: Int,
632    tlb: TlbPtwIO,
633    sfence: SfenceBundle,
634    csr: TlbCsrBundle
635  )(implicit p: Parameters) = {
636    val width = tlb.req.size
637    val repeater = Module(new PTWRepeater(width, fenceDelay))
638    repeater.io.apply(tlb, sfence, csr)
639    repeater
640  }
641
642  def apply(fenceDelay: Int,
643    tlb: TlbPtwIO,
644    ptw: TlbPtwIO,
645    sfence: SfenceBundle,
646    csr: TlbCsrBundle
647  )(implicit p: Parameters) = {
648    val width = tlb.req.size
649    val repeater = Module(new PTWRepeater(width, fenceDelay))
650    repeater.io.apply(tlb, ptw, sfence, csr)
651    repeater
652  }
653}
654
655object PTWRepeaterNB {
656  def apply(passReady: Boolean, fenceDelay: Int,
657    tlb: TlbPtwIO,
658    sfence: SfenceBundle,
659    csr: TlbCsrBundle
660  )(implicit p: Parameters) = {
661    val width = tlb.req.size
662    val repeater = Module(new PTWRepeaterNB(width, passReady,fenceDelay))
663    repeater.io.apply(tlb, sfence, csr)
664    repeater
665  }
666
667  def apply(passReady: Boolean, fenceDelay: Int,
668    tlb: TlbPtwIO,
669    ptw: TlbPtwIO,
670    sfence: SfenceBundle,
671    csr: TlbCsrBundle
672  )(implicit p: Parameters) = {
673    val width = tlb.req.size
674    val repeater = Module(new PTWRepeaterNB(width, passReady, fenceDelay))
675    repeater.io.apply(tlb, ptw, sfence, csr)
676    repeater
677  }
678}
679
680object PTWFilter {
681  def apply(fenceDelay: Int,
682    tlb: VectorTlbPtwIO,
683    ptw: TlbPtwIO,
684    sfence: SfenceBundle,
685    csr: TlbCsrBundle,
686    size: Int
687  )(implicit p: Parameters) = {
688    val width = tlb.req.size
689    val filter = Module(new PTWFilter(width, size, fenceDelay))
690    filter.io.apply(tlb, ptw, sfence, csr)
691    filter
692  }
693
694  def apply(fenceDelay: Int,
695    tlb: VectorTlbPtwIO,
696    sfence: SfenceBundle,
697    csr: TlbCsrBundle,
698    size: Int
699  )(implicit p: Parameters) = {
700    val width = tlb.req.size
701    val filter = Module(new PTWFilter(width, size, fenceDelay))
702    filter.io.apply(tlb, sfence, csr)
703    filter
704  }
705}
706
707object PTWNewFilter {
708  def apply(fenceDelay: Int,
709            tlb: VectorTlbPtwIO,
710            ptw: TlbPtwIO,
711            sfence: SfenceBundle,
712            csr: TlbCsrBundle,
713            size: Int
714           )(implicit p: Parameters) = {
715    val width = tlb.req.size
716    val filter = Module(new PTWNewFilter(width, size, fenceDelay))
717    filter.io.apply(tlb, ptw, sfence, csr)
718    filter
719  }
720
721  def apply(fenceDelay: Int,
722            tlb: VectorTlbPtwIO,
723            sfence: SfenceBundle,
724            csr: TlbCsrBundle,
725            size: Int
726           )(implicit p: Parameters) = {
727    val width = tlb.req.size
728    val filter = Module(new PTWNewFilter(width, size, fenceDelay))
729    filter.io.apply(tlb, sfence, csr)
730    filter
731  }
732}
733