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