dtlb.scala 13.5 KB
Newer Older
Y
Yinan Xu 已提交
1
package xiangshan.cache
2 3 4 5

import chisel3._
import chisel3.util._
import xiangshan._
6
import utils._
7 8 9 10 11
import chisel3.util.experimental.BoringUtils
import xiangshan.backend.decode.XSTrap
import xiangshan.mem._
import xiangshan.mem.pipeline._
import bus.simplebus._
Z
ZhangZifei 已提交
12
import xiangshan.backend.fu.HasCSRConst
13

14
trait HasTlbConst extends HasXSParameter {
Z
ZhangZifei 已提交
15 16 17
  val Level = 3

  val offLen  = 12
Z
ZhangZifei 已提交
18 19 20
  val ppnLen  = PAddrBits - offLen
  val vpnnLen = 9
  val vpnLen  = VAddrBits - offLen
Z
ZhangZifei 已提交
21 22
  val flagLen = 8
  val pteResLen = XLEN - ppnLen - 2 - flagLen
Z
ZhangZifei 已提交
23
  val asidLen = 16
Z
ZhangZifei 已提交
24 25 26 27 28

  def vaBundle = new Bundle {
    val vpn  = UInt(vpnLen.W)
    val off  = UInt(offLen.W)
  }
Z
ZhangZifei 已提交
29
  def pteBundle = new Bundle {
Z
ZhangZifei 已提交
30 31 32
    val reserved  = UInt(pteResLen.W)
    val ppn  = UInt(ppnLen.W)
    val rsw  = UInt(2.W)
Z
ZhangZifei 已提交
33
    val perm = new Bundle {
Z
ZhangZifei 已提交
34 35 36 37 38 39 40 41
      val d    = Bool()
      val a    = Bool()
      val g    = Bool()
      val u    = Bool()
      val x    = Bool()
      val w    = Bool()
      val r    = Bool()
      val v    = Bool()
Z
ZhangZifei 已提交
42 43 44 45
    }
  }
}

Z
ZhangZifei 已提交
46 47
abstract class TlbBundle extends XSBundle with HasTlbConst
abstract class TlbModule extends XSModule with HasTlbConst
Z
ZhangZifei 已提交
48 49 50 51 52 53 54 55 56 57

class PermBundle(val hasV: Boolean = true) extends TlbBundle {
  val d = Bool()
  val a = Bool()
  val g = Bool()
  val u = Bool()
  val x = Bool()
  val w = Bool()
  val r = Bool()
  if (hasV) { val v = Bool() }
Z
ZhangZifei 已提交
58 59 60 61 62

  override def toPrintable: Printable = {
    p"d:${d} a:${a} g:${g} u:${u} x:${x} w:${w} r:${r}"// + 
    //(if(hasV) (p"v:${v}") else p"")
  }
Z
ZhangZifei 已提交
63 64
}

65
class TlbEntry extends TlbBundle {
Z
ZhangZifei 已提交
66 67 68 69 70 71 72
  val vpn = UInt(vpnLen.W) // tag is vpn
  val ppn = UInt(ppnLen.W)
  val level = UInt(log2Up(Level).W) // 0 for 4KB, 1 for 2MB, 2 for 1GB
  // val asid = UInt(asidLen.W), asid maybe expensive to support, but useless
  // val v = Bool() // v&g is special, may need sperate storage?
  val perm = new PermBundle(hasV = false)

73
  def vpnHit(vpn: UInt):Bool = {
Z
ZhangZifei 已提交
74
    val fullMask = VecInit((Seq.fill(vpnLen)(true.B))).asUInt
75
    val maskLevel = VecInit((Level-1 to 0 by -1).map{i => // NOTE: level 2 for 4KB, 1 for 2MB, 0 for 1GB
Z
ZhangZifei 已提交
76 77 78 79 80 81 82 83 84
      VecInit(Seq.fill(vpnLen-i*vpnnLen)(true.B) ++ Seq.fill(i*vpnnLen)(false.B)).asUInt})
    val mask = maskLevel(level)
    (mask&this.vpn) === (mask&vpn)
  }

  // def asidHit(asid: UInt) = {
  //   this.asid === asid
  // }

85
  def hit(vpn: UInt/*, asid: UInt*/):Bool = {
Z
ZhangZifei 已提交
86 87 88
    vpnHit(vpn)// && asidHit(asid)
  }

89
  def genTlbEntry(pte: UInt, level: UInt, vpn: UInt/*, asid: UInt*/) = {
90
    val e = Wire(new TlbEntry)
Z
ZhangZifei 已提交
91 92 93 94 95 96 97
    e.ppn := pte.asTypeOf(pteBundle).ppn
    e.level := level
    e.vpn := vpn
    e.perm := pte.asTypeOf(pteBundle).perm
    // e.asid := asid
    e
  }
Z
ZhangZifei 已提交
98 99 100 101

  override def toPrintable: Printable = {
    p"vpn:0x${Hexadecimal(vpn)} ppn:0x${Hexadecimal(ppn)} level:${level} perm:${perm}"
  }
Z
ZhangZifei 已提交
102 103
}

104 105 106 107 108 109
object TlbCmd {
  def read  = "b00".U
  def write = "b01".U
  def exec  = "b10".U

  def apply() = UInt(2.W)
Z
ZhangZifei 已提交
110 111 112
  def isRead(a: UInt) = a===read
  def isWrite(a: UInt) = a===write
  def isExec(a: UInt) = a===exec
113 114
}

115
class TlbReq extends TlbBundle {
116
  val vaddr = UInt(VAddrBits.W)
Z
ZhangZifei 已提交
117
  val idx = UInt(RoqIdxWidth.W)
118
  val cmd = TlbCmd()
119 120 121 122 123
  val debug = new Bundle {
    val pc = UInt(XLEN.W)
    val roqIdx = UInt(RoqIdxWidth.W)
    val lsroqIdx = UInt(LsroqIdxWidth.W)
  }
Z
ZhangZifei 已提交
124 125

  override def toPrintable: Printable = {
126
    p"vaddr:0x${Hexadecimal(vaddr)} idx:${idx} cmd:${cmd} pc:0x${Hexadecimal(debug.pc)} roqIdx:${debug.roqIdx} lsroqIdx:${debug.lsroqIdx}"
Z
ZhangZifei 已提交
127
  }
128 129
}

130
class TlbResp extends TlbBundle {
131 132
  val paddr = UInt(PAddrBits.W)
  val miss = Bool()
Z
ZhangZifei 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
  val excp = new Bundle {
    val pf = new Bundle {
      val ld = Bool()
      val st = Bool()
      val instr = Bool()
    }
    // val ma = new Bundle { // may handle in other module
    //   val ld = Bool()
    //   val st = Bool()
    //   val instr = Bool()
    // }
    // val af = new Bundle {
    //   val ld = Bool()
    //   val st = Bool()
    //   val instr = Bool()
    // }
  }
Z
ZhangZifei 已提交
150 151 152
  override def toPrintable: Printable = {
    p"paddr:0x${Hexadecimal(paddr)} miss:${miss} excp.pf: ld:${excp.pf.ld} st:${excp.pf.st} instr:${excp.pf.instr}"
  }
153 154
}

155 156 157
class TlbRequestIO() extends TlbBundle {
  val req = Valid(new TlbReq)
  val resp = Flipped(Valid(new TlbResp))
158

159
  // override def cloneType: this.type = (new TlbRequestIO(Width)).asInstanceOf[this.type]
Z
ZhangZifei 已提交
160 161 162
}

class TlbPtwIO extends TlbBundle {
Z
ZhangZifei 已提交
163 164
  val req = DecoupledIO(new PtwReq)
  val resp = Flipped(DecoupledIO(new PtwResp))
Z
ZhangZifei 已提交
165 166
}

167
class TlbIO(Width: Int) extends TlbBundle {
168
  val requestor = Vec(Width, Flipped(new TlbRequestIO))
169
  val ptw = new TlbPtwIO
170 171

  override def cloneType: this.type = (new TlbIO(Width)).asInstanceOf[this.type]
172 173
}

174 175 176
class FakeTlb(Width: Int = 1) extends TlbModule {
  val io = IO(new TlbIO(Width))
  // Tlb has 4 ports: 2 for load, 2 for store
Z
ZhangZifei 已提交
177
  io <> DontCare
178
  // fake Tlb
179
  (0 until LoadPipelineWidth + StorePipelineWidth).map(i => {
180 181 182
    io.requestor(i).resp.valid := io.requestor(i).req.valid
    io.requestor(i).resp.bits.paddr := io.requestor(i).req.bits.vaddr
    io.requestor(i).resp.bits.miss := false.B
183
  })
Z
ZhangZifei 已提交
184 185
}

Z
ZhangZifei 已提交
186
class TLB(Width: Int, isDtlb: Boolean) extends TlbModule with HasCSRConst{
187
  val io = IO(new TlbIO(Width))
Z
ZhangZifei 已提交
188

189 190
  val req    = io.requestor.map(_.req)
  val resp   = io.requestor.map(_.resp)
191
  val ptw    = io.ptw
192

193 194 195 196
  val sfence = WireInit(0.U.asTypeOf(new SfenceBundle))
  val csr    = WireInit(0.U.asTypeOf(new TlbCsrBundle))
  val satp   = csr.satp
  val priv   = csr.priv
Z
ZhangZifei 已提交
197 198
  val ifecth = if (isDtlb) false.B else true.B
  val mode   = if (isDtlb) priv.dmode else priv.imode
199
  val vmEnable = satp.mode === 8.U // && (mode < ModeM) // FIXME: fix me when boot xv6/linux...
200 201 202
  BoringUtils.addSink(sfence, "SfenceBundle")
  BoringUtils.addSink(csr, "TLBCSRIO")

203
  val reqAddr = req.map(_.bits.vaddr.asTypeOf(vaBundle))
204 205
  val cmd     = req.map(_.bits.cmd)
  val valid   = req.map(_.valid)
Z
ZhangZifei 已提交
206

207 208 209
  def widthMapSeq[T <: Seq[Data]](f: Int => T) = (0 until Width).map(f)
  def widthMap[T <: Data](f: Int => T) = (0 until Width).map(f)

210
  val v = RegInit(0.U(TlbEntrySize.W))
211
  val pf = RegInit(0.U(TlbEntrySize.W)) // TODO: when ptw resp a pf(now only page not found), store here
212
  val entry = Reg(Vec(TlbEntrySize, new TlbEntry))
Z
ZhangZifei 已提交
213

214 215 216 217 218 219 220
  val entryHitVec = widthMapSeq{i => VecInit(entry.map(_.hit(reqAddr(i).vpn/*, satp.asid*/))) }
  val hitVec  = widthMapSeq{ i => (v.asBools zip entryHitVec(i)).map{ case (a,b) => a&b } }
  val pfHitVec   = widthMapSeq{ i => (pf.asBools zip entryHitVec(i)).map{ case (a,b) => a&b } }
  val pfArray = widthMap{ i => ParallelOR(pfHitVec(i)).asBool && valid(i) && vmEnable }
  val hit     = widthMap{ i => ParallelOR(hitVec(i)).asBool && valid(i) && vmEnable && ~pfArray(i) }
  val miss    = widthMap{ i => !hit(i) && valid(i) && vmEnable && ~pfArray(i) }
  val hitppn  = widthMap{ i => ParallelMux(hitVec(i) zip entry.map(_.ppn)) }
221
  val hitPerm = widthMap{ i => ParallelMux(hitVec(i) zip entry.map(_.perm)) }
Z
ZhangZifei 已提交
222
  val multiHit = {
223
    val hitSum = widthMap{ i => PopCount(hitVec(i)) }
224 225
    val pfHitSum = widthMap{ i => PopCount(pfHitVec(i)) }
    ParallelOR(widthMap{ i => !(hitSum(i)===0.U || hitSum(i)===1.U) || !(pfHitSum(i)===0.U || pfHitSum(i)===1.U)})
Z
ZhangZifei 已提交
226 227
  }

Z
ZhangZifei 已提交
228
  // resp  // TODO: A/D has not being concerned
229
  for(i <- 0 until Width) {
230
    // req(i).ready := resp(i).ready // true.B // ValidIO
231 232
    resp(i).valid := valid(i) // TODO: check it's func in outer module
    resp(i).bits.paddr := Mux(vmEnable, Cat(hitppn(i), reqAddr(i).off), SignExt(req(i).bits.vaddr, PAddrBits))
Z
ZhangZifei 已提交
233 234 235 236
    resp(i).bits.miss := miss(i)

    val perm = hitPerm(i) // NOTE: given the excp, the out module choose one to use?
    val modeCheck = !(mode === ModeU && !perm.u || mode === ModeS && perm.u && (!priv.sum || ifecth))
237 238 239
    resp(i).bits.excp.pf.ld    := (pfArray(i) && TlbCmd.isRead(cmd(i)) && true.B /*!isAMO*/) || hit(i) && !(modeCheck && (perm.r || priv.mxr && perm.x)) && (TlbCmd.isRead(cmd(i)) && true.B/*!isAMO*/) // TODO: handle isAMO
    resp(i).bits.excp.pf.st    := (pfArray(i) && TlbCmd.isWrite(cmd(i)) || false.B /*isAMO*/ ) || hit(i) && !(modeCheck && perm.w) && (TlbCmd.isWrite(cmd(i)) || false.B/*TODO isAMO. */)
    resp(i).bits.excp.pf.instr := (pfArray(i) && TlbCmd.isExec(cmd(i))) || hit(i) && !(modeCheck && perm.x) && TlbCmd.isExec(cmd(i))
Z
ZhangZifei 已提交
240 241 242
  }

  // ptw
Z
ZhangZifei 已提交
243 244
  val state_idle :: state_wait :: Nil = Enum(2)
  val state = RegInit(state_idle)
Z
ZhangZifei 已提交
245

246
  ptw <> DontCare // TODO: need check it
247
  ptw.req.valid := ParallelOR(miss).asBool && state===state_idle
248
  ptw.resp.ready := state===state_wait
249 250 251 252 253 254 255 256 257 258 259
  class comBundle extends TlbBundle with HasRoqIdx{
    val valid = Bool()
    val bits = new PtwReq

    def isPrior(that: comBundle): Bool = {
      (this.valid && !that.valid) || (this.valid && that.valid && (that isAfter this))
    }
  }
  object Compare {
    def apply[T<:Data](xs: Seq[comBundle]): comBundle = {
      ParallelOperation(xs, (a: comBundle, b: comBundle) => Mux(a isPrior b, a, b))
260 261 262
    }
  }

263 264 265 266 267 268 269 270 271 272
  // val ptwReqSeq = Wire(Seq.fill(Width)(new comBundle()))
  val ptwReqSeq = Seq.fill(Width)(Wire(new comBundle()))
  for (i <- 0 until Width) {
    ptwReqSeq(i).valid := valid(i) && miss(i)
    ptwReqSeq(i).roqIdx := req(i).bits.idx
    ptwReqSeq(i).bits.vpn := reqAddr(i).vpn
    ptwReqSeq(i).bits.idx := req(i).bits.idx
  }
  ptw.req.bits := Compare(ptwReqSeq).bits

Z
ZhangZifei 已提交
273
  switch (state) {
Z
ZhangZifei 已提交
274
    is (state_idle) {
275 276
      when (ParallelOR(miss).asBool) {
        state := state_wait
Z
ZhangZifei 已提交
277
      }
278
      assert(!ptw.resp.valid)
Z
ZhangZifei 已提交
279
    }
280

Z
ZhangZifei 已提交
281
    is (state_wait) {
282
      when (ptw.resp.fire()) {
Z
ZhangZifei 已提交
283
        state := state_idle
Z
ZhangZifei 已提交
284 285 286 287
      }
    }
  }

288 289 290 291 292 293 294
  // reset pf when pf hit
  val pfHitReset = WireInit(0.U(TlbEntrySize.W))
  when (ParallelOR(pfArray).asBool /* or ParallelOR(valid)*/) {
    val pfHitAndValid = widthMap{i => Mux(valid(i), VecInit(pfHitVec(i)).asUInt, 0.U) }
    pfHitReset := ParallelOR(pfHitAndValid)
  }

Z
ZhangZifei 已提交
295
  // refill
Z
ZhangZifei 已提交
296
  val refill = ptw.resp.fire() && !ptw.resp.bits.pf
297 298
  val randIdx = LFSR64()(log2Up(TlbEntrySize)-1,0)
  val priorIdx = PriorityEncoder(~v)
299
  val antiPriorIdx = PriorityEncoder(Reverse(~(v|pf))) // or just (TlbEntrySize-1).U
300
  val refillIdx = Mux(ParallelAND(v.asBools), Mux(ptw.resp.bits.pf, antiPriorIdx, priorIdx), randIdx)
301
  val pfRefill = WireInit(0.U(TlbEntrySize.W))
Z
ZhangZifei 已提交
302
  when (refill) {
303
    v := Mux(ptw.resp.bits.pf, v & ~UIntToOH(refillIdx), v | UIntToOH(refillIdx))
304
    pfRefill := Mux(ptw.resp.bits.pf, UIntToOH(refillIdx), 0.U)
Z
ZhangZifei 已提交
305
    entry(refillIdx) := ptw.resp.bits.entry
306
    XSDebug(p"Refill: idx:${refillIdx} entry:${ptw.resp.bits.entry}\n")
Z
ZhangZifei 已提交
307
  }
Z
ZhangZifei 已提交
308

309 310 311 312 313 314 315 316 317 318
  // pf update
  when (refill || ParallelOR(pfArray).asBool /* or ParallelOR(valid)*/) {
    pf := (pf & ~pfHitReset) | pfRefill
  }

  // sfence (flush)
  when (sfence.valid) {
    when (sfence.bits.rs1) { // virtual address *.rs1 <- (rs1===0.U)
      when (sfence.bits.rs2) { // asid, but i do not want to support asid, *.rs2 <- (rs2===0.U)
        v := 0.U // all should be flush
319
        pf := 0.U
320 321
      }.otherwise { // all pte but only spec asid
        v := v & ~VecInit(entry.map(e => /*e.asid === sfence.bits.asid && */!e.perm.g)).asUInt
322
        pf := pf & ~VecInit(entry.map(e => /*e.asid === sfence.bits.asid && */!e.perm.g)).asUInt
323 324 325
      }
    }.otherwise { // virtual rs1=/=0.U
      when (sfence.bits.rs2) { // asid
326
        v := v & ~VecInit(entry.map(_.vpn === sfence.bits.addr.asTypeOf(vaBundle).vpn)).asUInt
327
        pf := pf & ~VecInit(entry.map(_.vpn === sfence.bits.addr.asTypeOf(vaBundle).vpn)).asUInt
328
      }.otherwise { // particular va and asid
329
        v := v & ~VecInit(entry.map(e => e.vpn === sfence.bits.addr.asTypeOf(vaBundle).vpn && (/*e.asid === sfence.bits.asid && */!e.perm.g))).asUInt
330
        pf := pf & ~VecInit(entry.map(e => e.vpn === sfence.bits.addr.asTypeOf(vaBundle).vpn && (/*e.asid === sfence.bits.asid && */!e.perm.g))).asUInt
331 332 333 334 335
      }
    }
  }

  // Log
Z
ZhangZifei 已提交
336 337
  for(i <- 0 until Width) {
    XSDebug(req(i).valid, p"req(${i.U}): ${req(i).bits}\n")
338
    XSDebug(resp(i).valid, p"resp(${i.U}): ${resp(i).bits}\n")
Z
ZhangZifei 已提交
339 340 341
  }

  XSDebug(sfence.valid, p"Sfence: ${sfence}\n")
342
  XSDebug(ParallelOR(valid)|| ptw.resp.valid, p"CSR: ${csr}\n")
343
  XSDebug(ParallelOR(valid) || ptw.resp.valid, p"vmEnable:${vmEnable} hit:${Binary(VecInit(hit).asUInt)} miss:${Binary(VecInit(miss).asUInt)} v:${Hexadecimal(v)} pf:${Hexadecimal(pf)} state:${state}\n")
Z
ZhangZifei 已提交
344
  XSDebug(ptw.req.fire(), p"PTW req:${ptw.req.bits}\n")
345 346 347 348 349 350 351 352 353 354 355 356 357
  XSDebug(ptw.resp.valid, p"PTW resp:${ptw.resp.bits} (v:${ptw.resp.valid}r:${ptw.resp.ready}) \n")

  // assert check, can be remove when tlb can work
  for(i <- 0 until Width) {
    assert((hit(i)&pfArray(i))===false.B, "hit(%d):%d pfArray(%d):%d v:0x%x pf:0x%x", i.U, hit(i), i.U, pfArray(i), v, pf)
  }
  for(i <- 0 until Width) {
    XSDebug(multiHit, p"vpn:0x${Hexadecimal(reqAddr(i).vpn)} hitVec:0x${Hexadecimal(VecInit(hitVec(i)).asUInt)} pfHitVec:0x${Hexadecimal(VecInit(pfHitVec(i)).asUInt)}\n")
  }
  for(i <- 0 until TlbEntrySize) {
    XSDebug(multiHit, p"entry(${i.U}): v:${v(i)} ${entry(i)}\n")
  }
  assert(!multiHit) // add multiHit here, later it should be removed (maybe), turn to miss and flush
358 359 360 361 362 363 364

  for (i <- 0 until Width) {
    XSDebug(resp(i).valid && !resp(i).bits.miss && !(req(i).bits.vaddr===resp(i).bits.paddr), p"vaddr:0x${Hexadecimal(req(i).bits.vaddr)} paddr:0x${Hexadecimal(resp(i).bits.paddr)} hitVec:0x${Hexadecimal(VecInit(hitVec(i)).asUInt)}}\n")
    when (resp(i).valid && !resp(i).bits.miss && !(req(i).bits.vaddr===resp(i).bits.paddr)) {
      for (j <- 0 until TlbEntrySize) {
        XSDebug(true.B, p"TLBEntry(${j.U}): v:${v(j)} ${entry(j)}\n")
      }
365 366 367 368
    } // FIXME: remove me when tlb may be ok
    when(resp(i).valid && !resp(i).bits.miss) {
      assert(req(i).bits.vaddr===resp(i).bits.paddr, "vaddr:0x%x paddr:0x%x hitVec:%x ", req(i).bits.vaddr, resp(i).bits.paddr, VecInit(hitVec(i)).asUInt)
    } // FIXME: remove me when tlb may be ok
369
  }
370 371
  
  assert((v&pf)===0.U, "v and pf can't be true at same time: v:0x%x pf:0x%x", v, pf)
372
}