xref: /XiangShan/src/main/scala/xiangshan/cache/mmu/PageTableWalker.scala (revision b03c55a5df5dc8793cb44b42dd60141566e57e78)
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._
28import xiangshan.backend.fu.{PMPReqBundle, PMPRespBundle}
29
30/** Page Table Walk is divided into two parts
31  * One,   PTW: page walk for pde, except for leaf entries, one by one
32  * Two, LLPTW: page walk for pte, only the leaf entries(4KB), in parallel
33  */
34
35
36/** PTW : page table walker
37  * a finite state machine
38  * only take 1GB and 2MB page walks
39  * or in other words, except the last level(leaf)
40  **/
41class PTWIO()(implicit p: Parameters) extends MMUIOBaseBundle with HasPtwConst {
42  val req = Flipped(DecoupledIO(new Bundle {
43    val req_info = new L2TlbInnerBundle()
44    val l1Hit = Bool()
45    val ppn = UInt(gvpnLen.W)
46    val stage1Hit = Bool()
47    val stage1 = new PtwMergeResp
48  }))
49  val resp = DecoupledIO(new Bundle {
50    val source = UInt(bSourceWidth.W)
51    val s2xlate = UInt(2.W)
52    val resp = new PtwMergeResp
53    val h_resp = new HptwResp
54  })
55
56  val llptw = DecoupledIO(new LLPTWInBundle())
57  // NOTE: llptw change from "connect to llptw" to "connect to page cache"
58  // to avoid corner case that caused duplicate entries
59
60  val hptw = new Bundle {
61    val req = DecoupledIO(new Bundle {
62      val source = UInt(bSourceWidth.W)
63      val id = UInt(log2Up(l2tlbParams.llptwsize).W)
64      val gvpn = UInt(vpnLen.W)
65    })
66    val resp = Flipped(Valid(new Bundle {
67      val h_resp = Output(new HptwResp)
68    }))
69  }
70  val mem = new Bundle {
71    val req = DecoupledIO(new L2TlbMemReqBundle())
72    val resp = Flipped(ValidIO(UInt(XLEN.W)))
73    val mask = Input(Bool())
74  }
75  val pmp = new Bundle {
76    val req = ValidIO(new PMPReqBundle())
77    val resp = Flipped(new PMPRespBundle())
78  }
79
80  val refill = Output(new Bundle {
81    val req_info = new L2TlbInnerBundle()
82    val level = UInt(log2Up(Level).W)
83  })
84}
85
86class PTW()(implicit p: Parameters) extends XSModule with HasPtwConst with HasPerfEvents {
87  val io = IO(new PTWIO)
88  val sfence = io.sfence
89  val mem = io.mem
90  val req_s2xlate = Reg(UInt(2.W))
91  val enableS2xlate = req_s2xlate =/= noS2xlate
92  val onlyS1xlate = req_s2xlate === onlyStage1
93  val onlyS2xlate = req_s2xlate === onlyStage2
94
95  val satp = Mux(enableS2xlate, io.csr.vsatp, io.csr.satp)
96  val hgatp = io.csr.hgatp
97  val flush = io.sfence.valid || io.csr.satp.changed || io.csr.vsatp.changed || io.csr.hgatp.changed
98  val s2xlate = enableS2xlate && !onlyS1xlate
99  val level = RegInit(0.U(log2Up(Level).W))
100  val af_level = RegInit(0.U(log2Up(Level).W)) // access fault return this level
101  val ppn = Reg(UInt(gvpnLen.W))
102  val vpn = Reg(UInt(vpnLen.W)) // vpn or gvpn(onlyS2xlate)
103  val levelNext = level + 1.U
104  val l1Hit = Reg(Bool())
105  val pte = mem.resp.bits.asTypeOf(new PteBundle().cloneType)
106
107  // s/w register
108  val s_pmp_check = RegInit(true.B)
109  val s_mem_req = RegInit(true.B)
110  val s_llptw_req = RegInit(true.B)
111  val w_mem_resp = RegInit(true.B)
112  val s_hptw_req = RegInit(true.B)
113  val w_hptw_resp = RegInit(true.B)
114  val s_last_hptw_req = RegInit(true.B)
115  val w_last_hptw_resp = RegInit(true.B)
116  // for updating "level"
117  val mem_addr_update = RegInit(false.B)
118
119  val idle = RegInit(true.B)
120  val finish = WireInit(false.B)
121  val sent_to_pmp = idle === false.B && (s_pmp_check === false.B || mem_addr_update) && !finish
122
123  val pageFault = pte.isPf(level)
124  val accessFault = RegEnable(io.pmp.resp.ld || io.pmp.resp.mmio, sent_to_pmp)
125
126  val hptw_pageFault = RegInit(false.B)
127  val hptw_accessFault = RegInit(false.B)
128  val last_s2xlate = RegInit(false.B)
129  val stage1Hit = RegEnable(io.req.bits.stage1Hit, io.req.fire)
130  val stage1 = RegEnable(io.req.bits.stage1, io.req.fire)
131  val hptw_resp_stage2 = Reg(Bool())
132
133  val ppn_af = Mux(s2xlate, pte.isStage1Af(), pte.isAf()) // In two-stage address translation, stage 1 ppn is a vpn for host, so don't need to check ppn_high
134  val find_pte = pte.isLeaf() || ppn_af || pageFault || hptw_pageFault || hptw_accessFault
135  val to_find_pte = level === 1.U && find_pte === false.B
136  val source = RegEnable(io.req.bits.req_info.source, io.req.fire)
137
138  val l1addr = MakeAddr(satp.ppn, getVpnn(vpn, 2))
139  val l2addr = MakeAddr(Mux(l1Hit, ppn, pte.getPPN()), getVpnn(vpn, 1))
140  val mem_addr = Mux(af_level === 0.U, l1addr, l2addr)
141
142  val hptw_resp = RegEnable(io.hptw.resp.bits.h_resp, io.hptw.resp.fire)
143  val gpaddr = MuxCase(mem_addr, Seq(
144    stage1Hit -> Cat(stage1.genPPN(), 0.U(offLen.W)),
145    onlyS2xlate -> Cat(vpn, 0.U(offLen.W)),
146    !s_last_hptw_req -> Cat(MuxLookup(level, pte.getPPN())(Seq(
147      0.U -> Cat(pte.getPPN()(gvpnLen - 1, vpnnLen * 2), vpn(vpnnLen * 2 - 1, 0)),
148      1.U -> Cat(pte.getPPN()(gvpnLen - 1, vpnnLen), vpn(vpnnLen - 1, 0)
149    ))),
150    0.U(offLen.W))
151  ))
152  val hpaddr = Cat(hptw_resp.genPPNS2(get_pn(gpaddr)), get_off(gpaddr))
153
154  io.req.ready := idle
155  val ptw_resp = Wire(new PtwMergeResp)
156  ptw_resp.apply(pageFault && !accessFault && !ppn_af, accessFault || ppn_af, Mux(accessFault, af_level,level), pte, vpn, satp.asid, hgatp.asid, vpn(sectortlbwidth - 1, 0), not_super = false)
157
158  val normal_resp = idle === false.B && mem_addr_update && !last_s2xlate && ((w_mem_resp && find_pte) || (s_pmp_check && accessFault) || onlyS2xlate)
159  val stageHit_resp = idle === false.B && hptw_resp_stage2
160  io.resp.valid := Mux(stage1Hit, stageHit_resp, normal_resp)
161  io.resp.bits.source := source
162  io.resp.bits.resp := Mux(stage1Hit, stage1, ptw_resp)
163  io.resp.bits.h_resp := hptw_resp
164  io.resp.bits.s2xlate := req_s2xlate
165
166  io.llptw.valid := s_llptw_req === false.B && to_find_pte && !accessFault
167  io.llptw.bits.req_info.source := source
168  io.llptw.bits.req_info.vpn := vpn
169  io.llptw.bits.req_info.s2xlate := req_s2xlate
170  io.llptw.bits.ppn := DontCare
171
172  io.pmp.req.valid := DontCare // samecycle, do not use valid
173  io.pmp.req.bits.addr := Mux(s2xlate, hpaddr, mem_addr)
174  io.pmp.req.bits.size := 3.U // TODO: fix it
175  io.pmp.req.bits.cmd := TlbCmd.read
176
177  mem.req.valid := s_mem_req === false.B && !mem.mask && !accessFault && s_pmp_check
178  mem.req.bits.addr := Mux(s2xlate, hpaddr, mem_addr)
179  mem.req.bits.id := FsmReqID.U(bMemID.W)
180  mem.req.bits.hptw_bypassed := false.B
181
182  io.refill.req_info.s2xlate := Mux(enableS2xlate, onlyStage1, req_s2xlate) // ptw refill the pte of stage 1 when s2xlate is enabled
183  io.refill.req_info.vpn := vpn
184  io.refill.level := level
185  io.refill.req_info.source := source
186
187  io.hptw.req.valid := !s_hptw_req || !s_last_hptw_req
188  io.hptw.req.bits.id := FsmReqID.U(bMemID.W)
189  io.hptw.req.bits.gvpn := get_pn(gpaddr)
190  io.hptw.req.bits.source := source
191
192  when (io.req.fire && io.req.bits.stage1Hit){
193    idle := false.B
194    req_s2xlate := io.req.bits.req_info.s2xlate
195    s_hptw_req := false.B
196    hptw_resp_stage2 := false.B
197    last_s2xlate := false.B
198  }
199
200  when (io.hptw.resp.fire && w_hptw_resp === false.B && stage1Hit){
201    w_hptw_resp := true.B
202    hptw_resp_stage2 := true.B
203  }
204
205  when (io.resp.fire && stage1Hit){
206    idle := true.B
207  }
208
209  when (io.req.fire && !io.req.bits.stage1Hit){
210    val req = io.req.bits
211    level := Mux(req.l1Hit, 1.U, 0.U)
212    af_level := Mux(req.l1Hit, 1.U, 0.U)
213    ppn := Mux(req.l1Hit, io.req.bits.ppn, satp.ppn)
214    vpn := io.req.bits.req_info.vpn
215    l1Hit := req.l1Hit
216    accessFault := false.B
217    idle := false.B
218    hptw_pageFault := false.B
219    req_s2xlate := io.req.bits.req_info.s2xlate
220    when(io.req.bits.req_info.s2xlate =/= noS2xlate && io.req.bits.req_info.s2xlate =/= onlyStage1){
221      last_s2xlate := true.B
222      s_hptw_req := false.B
223    }.otherwise {
224      last_s2xlate := false.B
225      s_pmp_check := false.B
226    }
227  }
228
229  when(io.hptw.req.fire && s_hptw_req === false.B){
230    s_hptw_req := true.B
231    w_hptw_resp := false.B
232  }
233
234  when(io.hptw.resp.fire && w_hptw_resp === false.B && !stage1Hit) {
235    hptw_pageFault := io.hptw.resp.bits.h_resp.gpf
236    hptw_accessFault := io.hptw.resp.bits.h_resp.gaf
237    w_hptw_resp := true.B
238    when(onlyS2xlate){
239      mem_addr_update := true.B
240      last_s2xlate := false.B
241    }.otherwise {
242      s_pmp_check := false.B
243    }
244  }
245
246  when(io.hptw.req.fire && s_last_hptw_req === false.B) {
247    w_last_hptw_resp := false.B
248    s_last_hptw_req := true.B
249  }
250
251  when(io.hptw.resp.fire && w_last_hptw_resp === false.B){
252    hptw_pageFault := io.hptw.resp.bits.h_resp.gpf
253    hptw_accessFault := io.hptw.resp.bits.h_resp.gaf
254    w_last_hptw_resp := true.B
255    mem_addr_update := true.B
256    last_s2xlate := false.B
257  }
258
259  when(sent_to_pmp && mem_addr_update === false.B){
260    s_mem_req := false.B
261    s_pmp_check := true.B
262  }
263
264  when(accessFault && idle === false.B){
265    s_pmp_check := true.B
266    s_mem_req := true.B
267    w_mem_resp := true.B
268    s_llptw_req := true.B
269    s_hptw_req := true.B
270    w_hptw_resp := true.B
271    s_last_hptw_req := true.B
272    w_last_hptw_resp := true.B
273    mem_addr_update := true.B
274    last_s2xlate := false.B
275  }
276
277  when (mem.req.fire){
278    s_mem_req := true.B
279    w_mem_resp := false.B
280  }
281
282  when(mem.resp.fire && w_mem_resp === false.B){
283    w_mem_resp := true.B
284    af_level := af_level + 1.U
285    s_llptw_req := false.B
286    mem_addr_update := true.B
287  }
288
289  when(mem_addr_update){
290    when(level === 0.U && !onlyS2xlate && !(find_pte || accessFault)){
291      level := levelNext
292      when(s2xlate){
293        s_hptw_req := false.B
294      }.otherwise{
295        s_mem_req := false.B
296      }
297      s_llptw_req := true.B
298      mem_addr_update := false.B
299    }.elsewhen(io.llptw.valid){
300      when(io.llptw.fire) {
301        idle := true.B
302        s_llptw_req := true.B
303        mem_addr_update := false.B
304        last_s2xlate := false.B
305      }
306      finish := true.B
307    }.elsewhen(s2xlate && last_s2xlate === true.B) {
308      when(accessFault || pageFault || ppn_af){
309        last_s2xlate := false.B
310      }.otherwise{
311        s_last_hptw_req := false.B
312        mem_addr_update := false.B
313      }
314    }.elsewhen(io.resp.valid){
315      when(io.resp.fire) {
316        idle := true.B
317        s_llptw_req := true.B
318        mem_addr_update := false.B
319        accessFault := false.B
320      }
321      finish := true.B
322    }
323  }
324
325
326  when (flush) {
327    idle := true.B
328    s_pmp_check := true.B
329    s_mem_req := true.B
330    s_llptw_req := true.B
331    w_mem_resp := true.B
332    accessFault := false.B
333    mem_addr_update := false.B
334    s_hptw_req := true.B
335    w_hptw_resp := true.B
336    s_last_hptw_req := true.B
337    w_last_hptw_resp := true.B
338  }
339
340
341  XSDebug(p"[ptw] level:${level} notFound:${pageFault}\n")
342
343  // perf
344  XSPerfAccumulate("fsm_count", io.req.fire)
345  for (i <- 0 until PtwWidth) {
346    XSPerfAccumulate(s"fsm_count_source${i}", io.req.fire && io.req.bits.req_info.source === i.U)
347  }
348  XSPerfAccumulate("fsm_busy", !idle)
349  XSPerfAccumulate("fsm_idle", idle)
350  XSPerfAccumulate("resp_blocked", io.resp.valid && !io.resp.ready)
351  XSPerfAccumulate("ptw_ppn_af", io.resp.fire && ppn_af)
352  XSPerfAccumulate("mem_count", mem.req.fire)
353  XSPerfAccumulate("mem_cycle", BoolStopWatch(mem.req.fire, mem.resp.fire, true))
354  XSPerfAccumulate("mem_blocked", mem.req.valid && !mem.req.ready)
355
356  TimeOutAssert(!idle, timeOutThreshold, "page table walker time out")
357
358  val perfEvents = Seq(
359    ("fsm_count         ", io.req.fire                                     ),
360    ("fsm_busy          ", !idle                                             ),
361    ("fsm_idle          ", idle                                              ),
362    ("resp_blocked      ", io.resp.valid && !io.resp.ready                   ),
363    ("mem_count         ", mem.req.fire                                    ),
364    ("mem_cycle         ", BoolStopWatch(mem.req.fire, mem.resp.fire, true)),
365    ("mem_blocked       ", mem.req.valid && !mem.req.ready                   ),
366  )
367  generatePerfEvent()
368}
369
370/*========================= LLPTW ==============================*/
371
372/** LLPTW : Last Level Page Table Walker
373  * the page walker that only takes 4KB(last level) page walk.
374  **/
375
376class LLPTWInBundle(implicit p: Parameters) extends XSBundle with HasPtwConst {
377  val req_info = Output(new L2TlbInnerBundle())
378  val ppn = Output(UInt(gvpnLen.W))
379}
380
381class LLPTWIO(implicit p: Parameters) extends MMUIOBaseBundle with HasPtwConst {
382  val in = Flipped(DecoupledIO(new LLPTWInBundle()))
383  val out = DecoupledIO(new Bundle {
384    val req_info = Output(new L2TlbInnerBundle())
385    val id = Output(UInt(bMemID.W))
386    val h_resp = Output(new HptwResp)
387    val first_s2xlate_fault = Output(Bool()) // Whether the first stage 2 translation occurs pf/af
388    val af = Output(Bool())
389  })
390  val mem = new Bundle {
391    val req = DecoupledIO(new L2TlbMemReqBundle())
392    val resp = Flipped(Valid(new Bundle {
393      val id = Output(UInt(log2Up(l2tlbParams.llptwsize).W))
394      val value = Output(UInt(blockBits.W))
395    }))
396    val enq_ptr = Output(UInt(log2Ceil(l2tlbParams.llptwsize).W))
397    val buffer_it = Output(Vec(l2tlbParams.llptwsize, Bool()))
398    val refill = Output(new L2TlbInnerBundle())
399    val req_mask = Input(Vec(l2tlbParams.llptwsize, Bool()))
400  }
401  val cache = DecoupledIO(new L2TlbInnerBundle())
402  val pmp = new Bundle {
403    val req = Valid(new PMPReqBundle())
404    val resp = Flipped(new PMPRespBundle())
405  }
406  val hptw = new Bundle {
407    val req = DecoupledIO(new Bundle{
408      val source = UInt(bSourceWidth.W)
409      val id = UInt(log2Up(l2tlbParams.llptwsize).W)
410      val gvpn = UInt(vpnLen.W)
411    })
412    val resp = Flipped(Valid(new Bundle {
413      val id = Output(UInt(log2Up(l2tlbParams.llptwsize).W))
414      val h_resp = Output(new HptwResp)
415    }))
416  }
417}
418
419class LLPTWEntry(implicit p: Parameters) extends XSBundle with HasPtwConst {
420  val req_info = new L2TlbInnerBundle()
421  val ppn = UInt(gvpnLen.W)
422  val wait_id = UInt(log2Up(l2tlbParams.llptwsize).W)
423  val af = Bool()
424  val hptw_resp = new HptwResp()
425  val first_s2xlate_fault = Output(Bool())
426}
427
428
429class LLPTW(implicit p: Parameters) extends XSModule with HasPtwConst with HasPerfEvents {
430  val io = IO(new LLPTWIO())
431  val enableS2xlate = io.in.bits.req_info.s2xlate =/= noS2xlate
432  val satp = Mux(enableS2xlate, io.csr.vsatp, io.csr.satp)
433
434  val flush = io.sfence.valid || io.csr.satp.changed || io.csr.vsatp.changed || io.csr.hgatp.changed
435  val entries = Reg(Vec(l2tlbParams.llptwsize, new LLPTWEntry()))
436  val state_idle :: state_hptw_req :: state_hptw_resp :: state_addr_check :: state_mem_req :: state_mem_waiting :: state_mem_out :: state_last_hptw_req :: state_last_hptw_resp :: state_cache :: Nil = Enum(10)
437  val state = RegInit(VecInit(Seq.fill(l2tlbParams.llptwsize)(state_idle)))
438
439  val is_emptys = state.map(_ === state_idle)
440  val is_mems = state.map(_ === state_mem_req)
441  val is_waiting = state.map(_ === state_mem_waiting)
442  val is_having = state.map(_ === state_mem_out)
443  val is_cache = state.map(_ === state_cache)
444  val is_hptw_req = state.map(_ === state_hptw_req)
445  val is_last_hptw_req = state.map(_ === state_last_hptw_req)
446  val is_hptw_resp = state.map(_ === state_hptw_resp)
447  val is_last_hptw_resp = state.map(_ === state_last_hptw_resp)
448
449  val full = !ParallelOR(is_emptys).asBool
450  val enq_ptr = ParallelPriorityEncoder(is_emptys)
451
452  val mem_ptr = ParallelPriorityEncoder(is_having) // TODO: optimize timing, bad: entries -> ptr -> entry
453  val mem_arb = Module(new RRArbiter(new LLPTWEntry(), l2tlbParams.llptwsize))
454  for (i <- 0 until l2tlbParams.llptwsize) {
455    mem_arb.io.in(i).bits := entries(i)
456    mem_arb.io.in(i).valid := is_mems(i) && !io.mem.req_mask(i)
457  }
458
459  // process hptw requests in serial
460  val hyper_arb1 = Module(new RRArbiter(new LLPTWEntry(), l2tlbParams.llptwsize))
461  for (i <- 0 until l2tlbParams.llptwsize) {
462    hyper_arb1.io.in(i).bits := entries(i)
463    hyper_arb1.io.in(i).valid := is_hptw_req(i) && !(Cat(is_hptw_resp).orR) && !(Cat(is_last_hptw_resp).orR)
464  }
465  val hyper_arb2 = Module(new RRArbiter(new LLPTWEntry(), l2tlbParams.llptwsize))
466  for(i <- 0 until l2tlbParams.llptwsize) {
467    hyper_arb2.io.in(i).bits := entries(i)
468    hyper_arb2.io.in(i).valid := is_last_hptw_req(i) && !(Cat(is_hptw_resp).orR) && !(Cat(is_last_hptw_resp).orR)
469  }
470
471  val cache_ptr = ParallelMux(is_cache, (0 until l2tlbParams.llptwsize).map(_.U(log2Up(l2tlbParams.llptwsize).W)))
472
473  // duplicate req
474  // to_wait: wait for the last to access mem, set to mem_resp
475  // to_cache: the last is back just right now, set to mem_cache
476  val dup_vec = state.indices.map(i =>
477    dup(io.in.bits.req_info.vpn, entries(i).req_info.vpn) && io.in.bits.req_info.s2xlate === entries(i).req_info.s2xlate
478  )
479  val dup_req_fire = mem_arb.io.out.fire && dup(io.in.bits.req_info.vpn, mem_arb.io.out.bits.req_info.vpn) && io.in.bits.req_info.s2xlate === mem_arb.io.out.bits.req_info.s2xlate // dup with the req fire entry
480  val dup_vec_wait = dup_vec.zip(is_waiting).map{case (d, w) => d && w} // dup with "mem_waiting" entries, sending mem req already
481  val dup_vec_having = dup_vec.zipWithIndex.map{case (d, i) => d && is_having(i)} // dup with the "mem_out" entry recv the data just now
482  val dup_vec_last_hptw = dup_vec.zipWithIndex.map{case (d, i) => d && (is_last_hptw_req(i) || is_last_hptw_resp(i))}
483  val wait_id = Mux(dup_req_fire, mem_arb.io.chosen, ParallelMux(dup_vec_wait zip entries.map(_.wait_id)))
484  val dup_wait_resp = io.mem.resp.fire && VecInit(dup_vec_wait)(io.mem.resp.bits.id) // dup with the entry that data coming next cycle
485  val to_wait = Cat(dup_vec_wait).orR || dup_req_fire
486  val to_mem_out = dup_wait_resp && ((entries(io.mem.resp.bits.id).req_info.s2xlate === noS2xlate) || (entries(io.mem.resp.bits.id).req_info.s2xlate === onlyStage1))
487  val to_cache = Cat(dup_vec_having).orR || Cat(dup_vec_last_hptw).orR
488  val to_hptw_req = io.in.bits.req_info.s2xlate === allStage
489  val to_last_hptw_req = dup_wait_resp && entries(io.mem.resp.bits.id).req_info.s2xlate === allStage
490  val last_hptw_req_id = io.mem.resp.bits.id
491  val req_paddr = MakeAddr(io.in.bits.ppn(ppnLen-1, 0), getVpnn(io.in.bits.req_info.vpn, 0))
492  val req_hpaddr = MakeAddr(entries(last_hptw_req_id).hptw_resp.genPPNS2(get_pn(req_paddr)), getVpnn(io.in.bits.req_info.vpn, 0))
493  val index =  Mux(entries(last_hptw_req_id).req_info.s2xlate === allStage, req_hpaddr, req_paddr)(log2Up(l2tlbParams.blockBytes)-1, log2Up(XLEN/8))
494  val last_hptw_req_ppn = io.mem.resp.bits.value.asTypeOf(Vec(blockBits / XLEN, new PteBundle()))(index).getPPN()
495  XSError(RegNext(dup_req_fire && Cat(dup_vec_wait).orR, init = false.B), "mem req but some entries already waiting, should not happed")
496
497  XSError(io.in.fire && ((to_mem_out && to_cache) || (to_wait && to_cache)), "llptw enq, to cache conflict with to mem")
498  val mem_resp_hit = RegInit(VecInit(Seq.fill(l2tlbParams.llptwsize)(false.B)))
499  val enq_state_normal = MuxCase(state_addr_check, Seq(
500    to_mem_out -> state_mem_out, // same to the blew, but the mem resp now
501    to_last_hptw_req -> state_last_hptw_req,
502    to_wait -> state_mem_waiting,
503    to_cache -> state_cache,
504    to_hptw_req -> state_hptw_req
505  ))
506  val enq_state = Mux(from_pre(io.in.bits.req_info.source) && enq_state_normal =/= state_addr_check, state_idle, enq_state_normal)
507  when (io.in.fire) {
508    // if prefetch req does not need mem access, just give it up.
509    // so there will be at most 1 + FilterSize entries that needs re-access page cache
510    // so 2 + FilterSize is enough to avoid dead-lock
511    state(enq_ptr) := enq_state
512    entries(enq_ptr).req_info := io.in.bits.req_info
513    entries(enq_ptr).ppn := Mux(to_last_hptw_req, last_hptw_req_ppn, io.in.bits.ppn)
514    entries(enq_ptr).wait_id := Mux(to_wait, wait_id, enq_ptr)
515    entries(enq_ptr).af := false.B
516    entries(enq_ptr).hptw_resp := Mux(to_last_hptw_req, entries(last_hptw_req_id).hptw_resp, Mux(to_wait, entries(wait_id).hptw_resp, entries(enq_ptr).hptw_resp))
517    entries(enq_ptr).first_s2xlate_fault := false.B
518    mem_resp_hit(enq_ptr) := to_mem_out || to_last_hptw_req
519  }
520
521  val enq_ptr_reg = RegNext(enq_ptr)
522  val need_addr_check = GatedValidRegNext(enq_state === state_addr_check && io.in.fire && !flush)
523
524  val hasHptwResp = ParallelOR(state.map(_ === state_hptw_resp)).asBool
525  val hptw_resp_ptr_reg = RegNext(io.hptw.resp.bits.id)
526  val hptw_need_addr_check = RegNext(hasHptwResp && io.hptw.resp.fire && !flush) && state(hptw_resp_ptr_reg) === state_addr_check
527
528  val ptes = io.mem.resp.bits.value.asTypeOf(Vec(blockBits / XLEN, new PteBundle()))
529  val gpaddr = MakeGPAddr(entries(hptw_resp_ptr_reg).ppn, getVpnn(entries(hptw_resp_ptr_reg).req_info.vpn, 0))
530  val hptw_resp = entries(hptw_resp_ptr_reg).hptw_resp
531  val hpaddr = Cat(hptw_resp.genPPNS2(get_pn(gpaddr)), get_off(gpaddr))
532  val addr = RegEnable(MakeAddr(io.in.bits.ppn(ppnLen - 1, 0), getVpnn(io.in.bits.req_info.vpn, 0)), io.in.fire)
533  io.pmp.req.valid := need_addr_check || hptw_need_addr_check
534  io.pmp.req.bits.addr := Mux(hptw_need_addr_check, hpaddr, addr)
535  io.pmp.req.bits.cmd := TlbCmd.read
536  io.pmp.req.bits.size := 3.U // TODO: fix it
537  val pmp_resp_valid = io.pmp.req.valid // same cycle
538  when (pmp_resp_valid) {
539    // NOTE: when pmp resp but state is not addr check, then the entry is dup with other entry, the state was changed before
540    //       when dup with the req-ing entry, set to mem_waiting (above codes), and the ld must be false, so dontcare
541    val ptr = Mux(hptw_need_addr_check, hptw_resp_ptr_reg, enq_ptr_reg);
542    val accessFault = io.pmp.resp.ld || io.pmp.resp.mmio
543    entries(ptr).af := accessFault
544    state(ptr) := Mux(accessFault, state_mem_out, state_mem_req)
545  }
546
547  when (mem_arb.io.out.fire) {
548    for (i <- state.indices) {
549      when (state(i) =/= state_idle && state(i) =/= state_mem_out && state(i) =/= state_last_hptw_req && state(i) =/= state_last_hptw_resp
550      && entries(i).req_info.s2xlate === mem_arb.io.out.bits.req_info.s2xlate
551      && dup(entries(i).req_info.vpn, mem_arb.io.out.bits.req_info.vpn)) {
552        // NOTE: "dup enq set state to mem_wait" -> "sending req set other dup entries to mem_wait"
553        state(i) := state_mem_waiting
554        entries(i).hptw_resp := entries(mem_arb.io.chosen).hptw_resp
555        entries(i).wait_id := mem_arb.io.chosen
556      }
557    }
558  }
559  when (io.mem.resp.fire) {
560    state.indices.map{i =>
561      when (state(i) === state_mem_waiting && io.mem.resp.bits.id === entries(i).wait_id) {
562        state(i) := Mux(entries(i).req_info.s2xlate === allStage, state_last_hptw_req, state_mem_out)
563        mem_resp_hit(i) := true.B
564        val req_paddr = MakeAddr(entries(i).ppn, getVpnn(entries(i).req_info.vpn, 0))
565        val req_hpaddr = MakeAddr(entries(i).hptw_resp.genPPNS2(get_pn(req_paddr)), getVpnn(entries(i).req_info.vpn, 0))
566        val index =  Mux(entries(i).req_info.s2xlate === allStage, req_hpaddr, req_paddr)(log2Up(l2tlbParams.blockBytes)-1, log2Up(XLEN/8))
567        entries(i).ppn := ptes(index).getPPN() // for last stage 2 translation
568      }
569    }
570  }
571
572  when (hyper_arb1.io.out.fire) {
573    for (i <- state.indices) {
574      when (state(i) === state_hptw_req && entries(i).ppn === hyper_arb1.io.out.bits.ppn && entries(i).req_info.s2xlate === allStage && hyper_arb1.io.chosen === i.U) {
575        state(i) := state_hptw_resp
576        entries(i).wait_id := hyper_arb1.io.chosen
577      }
578    }
579  }
580
581  when (hyper_arb2.io.out.fire) {
582    for (i <- state.indices) {
583      when (state(i) === state_last_hptw_req && entries(i).ppn === hyper_arb2.io.out.bits.ppn && entries(i).req_info.s2xlate === allStage && hyper_arb2.io.chosen === i.U) {
584        state(i) := state_last_hptw_resp
585        entries(i).wait_id := hyper_arb2.io.chosen
586      }
587    }
588  }
589
590  when (io.hptw.resp.fire) {
591    for (i <- state.indices) {
592      when (state(i) === state_hptw_resp && io.hptw.resp.bits.id === entries(i).wait_id && io.hptw.resp.bits.h_resp.entry.tag === entries(i).ppn) {
593        when (io.hptw.resp.bits.h_resp.gaf || io.hptw.resp.bits.h_resp.gpf) {
594          state(i) := state_mem_out
595          entries(i).hptw_resp := io.hptw.resp.bits.h_resp
596          entries(i).first_s2xlate_fault := io.hptw.resp.bits.h_resp.gaf || io.hptw.resp.bits.h_resp.gpf
597        }.otherwise{ // change the entry that is waiting hptw resp
598          val need_to_waiting_vec = state.indices.map(i => state(i) === state_mem_waiting && dup(entries(i).req_info.vpn, entries(io.hptw.resp.bits.id).req_info.vpn))
599          val waiting_index = ParallelMux(need_to_waiting_vec zip entries.map(_.wait_id))
600          state(i) := Mux(Cat(need_to_waiting_vec).orR, state_mem_waiting, state_addr_check)
601          entries(i).hptw_resp := io.hptw.resp.bits.h_resp
602          entries(i).wait_id := Mux(Cat(need_to_waiting_vec).orR, waiting_index, entries(i).wait_id)
603          //To do: change the entry that is having the same hptw req
604        }
605      }
606      when (state(i) === state_last_hptw_resp && io.hptw.resp.bits.id === entries(i).wait_id && io.hptw.resp.bits.h_resp.entry.tag === entries(i).ppn) {
607        state(i) := state_mem_out
608        entries(i).hptw_resp := io.hptw.resp.bits.h_resp
609        //To do: change the entry that is having the same hptw req
610      }
611    }
612  }
613  when (io.out.fire) {
614    assert(state(mem_ptr) === state_mem_out)
615    state(mem_ptr) := state_idle
616  }
617  mem_resp_hit.map(a => when (a) { a := false.B } )
618
619  when (io.cache.fire) {
620    state(cache_ptr) := state_idle
621  }
622  XSError(io.out.fire && io.cache.fire && (mem_ptr === cache_ptr), "mem resp and cache fire at the same time at same entry")
623
624  when (flush) {
625    state.map(_ := state_idle)
626  }
627
628  io.in.ready := !full
629
630  io.out.valid := ParallelOR(is_having).asBool
631  io.out.bits.req_info := entries(mem_ptr).req_info
632  io.out.bits.id := mem_ptr
633  io.out.bits.af := entries(mem_ptr).af
634  io.out.bits.h_resp := entries(mem_ptr).hptw_resp
635  io.out.bits.first_s2xlate_fault := entries(mem_ptr).first_s2xlate_fault
636
637  val hptw_req_arb = Module(new Arbiter(new Bundle{
638      val source = UInt(bSourceWidth.W)
639      val id = UInt(log2Up(l2tlbParams.llptwsize).W)
640      val ppn = UInt(gvpnLen.W)
641    } , 2))
642  // first stage 2 translation
643  hptw_req_arb.io.in(0).valid := hyper_arb1.io.out.valid
644  hptw_req_arb.io.in(0).bits.source := hyper_arb1.io.out.bits.req_info.source
645  hptw_req_arb.io.in(0).bits.ppn := hyper_arb1.io.out.bits.ppn
646  hptw_req_arb.io.in(0).bits.id := hyper_arb1.io.chosen
647  hyper_arb1.io.out.ready := hptw_req_arb.io.in(0).ready
648  // last stage 2 translation
649  hptw_req_arb.io.in(1).valid := hyper_arb2.io.out.valid
650  hptw_req_arb.io.in(1).bits.source := hyper_arb2.io.out.bits.req_info.source
651  hptw_req_arb.io.in(1).bits.ppn := hyper_arb2.io.out.bits.ppn
652  hptw_req_arb.io.in(1).bits.id := hyper_arb2.io.chosen
653  hyper_arb2.io.out.ready := hptw_req_arb.io.in(1).ready
654  hptw_req_arb.io.out.ready := io.hptw.req.ready
655  io.hptw.req.valid := hptw_req_arb.io.out.fire && !flush
656  io.hptw.req.bits.gvpn := hptw_req_arb.io.out.bits.ppn
657  io.hptw.req.bits.id := hptw_req_arb.io.out.bits.id
658  io.hptw.req.bits.source := hptw_req_arb.io.out.bits.source
659
660  io.mem.req.valid := mem_arb.io.out.valid && !flush
661  val mem_paddr = MakeAddr(mem_arb.io.out.bits.ppn, getVpnn(mem_arb.io.out.bits.req_info.vpn, 0))
662  val mem_hpaddr = MakeAddr(mem_arb.io.out.bits.hptw_resp.genPPNS2(get_pn(mem_paddr)), getVpnn(mem_arb.io.out.bits.req_info.vpn, 0))
663  io.mem.req.bits.addr := Mux(mem_arb.io.out.bits.req_info.s2xlate === allStage, mem_hpaddr, mem_paddr)
664  io.mem.req.bits.id := mem_arb.io.chosen
665  io.mem.req.bits.hptw_bypassed := false.B
666  mem_arb.io.out.ready := io.mem.req.ready
667  val mem_refill_id = RegNext(io.mem.resp.bits.id(log2Up(l2tlbParams.llptwsize)-1, 0))
668  io.mem.refill := entries(mem_refill_id).req_info
669  io.mem.refill.s2xlate := Mux(entries(mem_refill_id).req_info.s2xlate === noS2xlate, noS2xlate, onlyStage1) // llptw refill the pte of stage 1
670  io.mem.buffer_it := mem_resp_hit
671  io.mem.enq_ptr := enq_ptr
672
673  io.cache.valid := Cat(is_cache).orR
674  io.cache.bits := ParallelMux(is_cache, entries.map(_.req_info))
675
676  XSPerfAccumulate("llptw_in_count", io.in.fire)
677  XSPerfAccumulate("llptw_in_block", io.in.valid && !io.in.ready)
678  for (i <- 0 until 7) {
679    XSPerfAccumulate(s"enq_state${i}", io.in.fire && enq_state === i.U)
680  }
681  for (i <- 0 until (l2tlbParams.llptwsize + 1)) {
682    XSPerfAccumulate(s"util${i}", PopCount(is_emptys.map(!_)) === i.U)
683    XSPerfAccumulate(s"mem_util${i}", PopCount(is_mems) === i.U)
684    XSPerfAccumulate(s"waiting_util${i}", PopCount(is_waiting) === i.U)
685  }
686  XSPerfAccumulate("mem_count", io.mem.req.fire)
687  XSPerfAccumulate("mem_cycle", PopCount(is_waiting) =/= 0.U)
688  XSPerfAccumulate("blocked_in", io.in.valid && !io.in.ready)
689
690  for (i <- 0 until l2tlbParams.llptwsize) {
691    TimeOutAssert(state(i) =/= state_idle, timeOutThreshold, s"missqueue time out no out ${i}")
692  }
693
694  val perfEvents = Seq(
695    ("tlbllptw_incount           ", io.in.fire               ),
696    ("tlbllptw_inblock           ", io.in.valid && !io.in.ready),
697    ("tlbllptw_memcount          ", io.mem.req.fire          ),
698    ("tlbllptw_memcycle          ", PopCount(is_waiting)       ),
699  )
700  generatePerfEvent()
701}
702
703/*========================= HPTW ==============================*/
704
705/** HPTW : Hypervisor Page Table Walker
706  * the page walker take the virtual machine's page walk.
707  * guest physical address translation, guest physical address -> host physical address
708  **/
709class HPTWIO()(implicit p: Parameters) extends MMUIOBaseBundle with HasPtwConst {
710  val req = Flipped(DecoupledIO(new Bundle {
711    val source = UInt(bSourceWidth.W)
712    val id = UInt(log2Up(l2tlbParams.llptwsize).W)
713    val gvpn = UInt(vpnLen.W)
714    val ppn = UInt(ppnLen.W)
715    val l1Hit = Bool()
716    val l2Hit = Bool()
717    val bypassed = Bool() // if bypass, don't refill
718  }))
719  val resp = DecoupledIO(new Bundle {
720    val source = UInt(bSourceWidth.W)
721    val resp = Output(new HptwResp())
722    val id = Output(UInt(bMemID.W))
723  })
724
725  val mem = new Bundle {
726    val req = DecoupledIO(new L2TlbMemReqBundle())
727    val resp = Flipped(ValidIO(UInt(XLEN.W)))
728    val mask = Input(Bool())
729  }
730  val refill = Output(new Bundle {
731    val req_info = new L2TlbInnerBundle()
732    val level = UInt(log2Up(Level).W)
733  })
734  val pmp = new Bundle {
735    val req = ValidIO(new PMPReqBundle())
736    val resp = Flipped(new PMPRespBundle())
737  }
738}
739
740class HPTW()(implicit p: Parameters) extends XSModule with HasPtwConst {
741  val io = IO(new HPTWIO)
742  val hgatp = io.csr.hgatp
743  val sfence = io.sfence
744  val flush = sfence.valid || hgatp.changed || io.csr.satp.changed || io.csr.vsatp.changed
745
746  val level = RegInit(0.U(log2Up(Level).W))
747  val gpaddr = Reg(UInt(GPAddrBits.W))
748  val req_ppn = Reg(UInt(ppnLen.W))
749  val vpn = gpaddr(GPAddrBits-1, offLen)
750  val levelNext = level + 1.U
751  val l1Hit = Reg(Bool())
752  val l2Hit = Reg(Bool())
753  val bypassed = Reg(Bool())
754  val pg_base = MakeGPAddr(hgatp.ppn, getGVpnn(vpn, 2.U)) // for l0
755//  val pte = io.mem.resp.bits.MergeRespToPte()
756  val pte = io.mem.resp.bits.asTypeOf(new PteBundle().cloneType)
757  val ppn_l1 = Mux(l1Hit, req_ppn, pte.ppn)
758  val ppn_l2 = Mux(l2Hit, req_ppn, pte.ppn)
759  val ppn = Mux(level === 1.U, ppn_l1, ppn_l2) //for l1 and l2
760  val p_pte = MakeAddr(ppn, getVpnn(vpn, 2.U - level))
761  val mem_addr = Mux(level === 0.U, pg_base, p_pte)
762
763  //s/w register
764  val s_pmp_check = RegInit(true.B)
765  val s_mem_req = RegInit(true.B)
766  val w_mem_resp = RegInit(true.B)
767  val idle = RegInit(true.B)
768  val mem_addr_update = RegInit(false.B)
769  val finish = WireInit(false.B)
770
771  val sent_to_pmp = !idle && (!s_pmp_check || mem_addr_update) && !finish
772  val pageFault = pte.isPf(level) || (!pte.isLeaf() && level >= 2.U)
773  val accessFault = RegEnable(io.pmp.resp.ld || io.pmp.resp.mmio, sent_to_pmp)
774
775  val ppn_af = pte.isAf()
776  val find_pte = pte.isLeaf() || ppn_af || pageFault
777
778  val resp_valid = !idle && mem_addr_update && ((w_mem_resp && find_pte) || (s_pmp_check && accessFault))
779  val id = Reg(UInt(log2Up(l2tlbParams.llptwsize).W))
780  val source = RegEnable(io.req.bits.source, io.req.fire)
781
782  io.req.ready := idle
783  val resp = Wire(new HptwResp())
784  resp.apply(pageFault && !accessFault && !ppn_af, accessFault || ppn_af, level, pte, vpn, hgatp.asid)
785  io.resp.valid := resp_valid
786  io.resp.bits.id := id
787  io.resp.bits.resp := resp
788  io.resp.bits.source := source
789
790  io.pmp.req.valid := DontCare
791  io.pmp.req.bits.addr := mem_addr
792  io.pmp.req.bits.size := 3.U
793  io.pmp.req.bits.cmd := TlbCmd.read
794
795  io.mem.req.valid := !s_mem_req && !io.mem.mask && !accessFault && s_pmp_check
796  io.mem.req.bits.addr := mem_addr
797  io.mem.req.bits.id := HptwReqId.U(bMemID.W)
798  io.mem.req.bits.hptw_bypassed := bypassed
799
800  io.refill.req_info.vpn := vpn
801  io.refill.level := level
802  io.refill.req_info.source := source
803  io.refill.req_info.s2xlate := onlyStage2
804  when (idle){
805    when(io.req.fire){
806      bypassed := io.req.bits.bypassed
807      level := Mux(io.req.bits.l2Hit, 2.U, Mux(io.req.bits.l1Hit, 1.U, 0.U))
808      idle := false.B
809      gpaddr := Cat(io.req.bits.gvpn, 0.U(offLen.W))
810      accessFault := false.B
811      s_pmp_check := false.B
812      id := io.req.bits.id
813      req_ppn := io.req.bits.ppn
814      l1Hit := io.req.bits.l1Hit
815      l2Hit := io.req.bits.l2Hit
816    }
817  }
818
819  when(sent_to_pmp && !mem_addr_update){
820    s_mem_req := false.B
821    s_pmp_check := true.B
822  }
823
824  when(accessFault && !idle){
825    s_pmp_check := true.B
826    s_mem_req := true.B
827    w_mem_resp := true.B
828    mem_addr_update := true.B
829  }
830
831  when(io.mem.req.fire){
832    s_mem_req := true.B
833    w_mem_resp := false.B
834  }
835
836  when(io.mem.resp.fire && !w_mem_resp){
837    w_mem_resp := true.B
838    mem_addr_update := true.B
839  }
840
841  when(mem_addr_update){
842    when(!(find_pte || accessFault)){
843      level := levelNext
844      s_mem_req := false.B
845      mem_addr_update := false.B
846    }.elsewhen(resp_valid){
847      when(io.resp.fire){
848        idle := true.B
849        mem_addr_update := false.B
850        accessFault := false.B
851      }
852      finish := true.B
853    }
854  }
855   when (flush) {
856    idle := true.B
857    s_pmp_check := true.B
858    s_mem_req := true.B
859    w_mem_resp := true.B
860    accessFault := false.B
861    mem_addr_update := false.B
862  }
863}
864