xref: /XiangShan/src/main/scala/xiangshan/mem/pipeline/AtomicsUnit.scala (revision bb76fc1b2ecc820357f700a1b7fab9af4780756f)
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.mem
18
19import org.chipsalliance.cde.config.Parameters
20import chisel3._
21import chisel3.util._
22import utils._
23import utility._
24import xiangshan._
25import xiangshan.cache.{AtomicWordIO, HasDCacheParameters, MemoryOpConstants}
26import xiangshan.cache.mmu.{TlbCmd, TlbRequestIO}
27import difftest._
28import xiangshan.ExceptionNO._
29import xiangshan.backend.fu.PMPRespBundle
30import xiangshan.backend.fu.FuType
31import xiangshan.backend.Bundles.{MemExuInput, MemExuOutput}
32import xiangshan.backend.fu.NewCSR.TriggerUtil
33import xiangshan.backend.fu.util.SdtrigExt
34import xiangshan.cache.mmu.Pbmt
35
36class AtomicsUnit(implicit p: Parameters) extends XSModule
37  with MemoryOpConstants
38  with HasDCacheParameters
39  with SdtrigExt{
40  val io = IO(new Bundle() {
41    val hartId        = Input(UInt(hartIdLen.W))
42    val in            = Flipped(Decoupled(new MemExuInput))
43    val storeDataIn   = Flipped(Valid(new MemExuOutput)) // src2 from rs
44    val out           = Decoupled(new MemExuOutput)
45    val dcache        = new AtomicWordIO
46    val dtlb          = new TlbRequestIO(2)
47    val pmpResp       = Flipped(new PMPRespBundle())
48    val flush_sbuffer = new SbufferFlushBundle
49    val feedbackSlow  = ValidIO(new RSFeedback)
50    val redirect      = Flipped(ValidIO(new Redirect))
51    val exceptionInfo = ValidIO(new Bundle {
52      val vaddr = UInt(XLEN.W)
53      val gpaddr = UInt(XLEN.W)
54      val isForVSnonLeafPTE = Bool()
55    })
56    val csrCtrl       = Flipped(new CustomCSRCtrlIO)
57  })
58
59  //-------------------------------------------------------
60  // Atomics Memory Accsess FSM
61  //-------------------------------------------------------
62  val s_invalid :: s_tlb_and_flush_sbuffer_req :: s_pm :: s_wait_flush_sbuffer_resp :: s_cache_req :: s_cache_resp :: s_cache_resp_latch :: s_finish :: Nil = Enum(8)
63  val state = RegInit(s_invalid)
64  val out_valid = RegInit(false.B)
65  val data_valid = RegInit(false.B)
66  val in = Reg(new MemExuInput())
67  val exceptionVec = RegInit(0.U.asTypeOf(ExceptionVec()))
68  val trigger = RegInit(TriggerAction.None)
69  val atom_override_xtval = RegInit(false.B)
70  val have_sent_first_tlb_req = RegInit(false.B)
71  // paddr after translation
72  val paddr = Reg(UInt())
73  val gpaddr = Reg(UInt())
74  val vaddr = in.src(0)
75  val is_mmio = Reg(Bool())
76  val is_nc = RegInit(false.B)
77  val isForVSnonLeafPTE = Reg(Bool())
78
79  // dcache response data
80  val resp_data = Reg(UInt())
81  val resp_data_wire = WireInit(0.U)
82  val is_lrsc_valid = Reg(Bool())
83  // sbuffer is empty or not
84  val sbuffer_empty = io.flush_sbuffer.empty
85
86
87  // Difftest signals
88  val paddr_reg = Reg(UInt(64.W))
89  val data_reg = Reg(UInt(64.W))
90  val mask_reg = Reg(UInt(8.W))
91  val fuop_reg = Reg(UInt(8.W))
92
93  io.exceptionInfo.valid := atom_override_xtval
94  io.exceptionInfo.bits.vaddr := in.src(0)
95  io.exceptionInfo.bits.gpaddr := gpaddr
96  io.exceptionInfo.bits.isForVSnonLeafPTE := isForVSnonLeafPTE
97
98  // assign default value to output signals
99  io.in.ready          := false.B
100
101  io.dcache.req.valid  := false.B
102  io.dcache.req.bits   := DontCare
103
104  io.dtlb.req.valid    := false.B
105  io.dtlb.req.bits     := DontCare
106  io.dtlb.req_kill     := false.B
107  io.dtlb.resp.ready   := true.B
108
109  io.flush_sbuffer.valid := false.B
110
111  when (state === s_invalid) {
112    io.in.ready := true.B
113    when (io.in.fire) {
114      in := io.in.bits
115      in.src(1) := in.src(1) // leave src2 unchanged
116      state := s_tlb_and_flush_sbuffer_req
117      have_sent_first_tlb_req := false.B
118    }
119  }
120
121  when (io.storeDataIn.fire) {
122    in.src(1) := io.storeDataIn.bits.data
123    data_valid := true.B
124  }
125
126  // TODO: remove this for AMOCAS
127  assert(!(io.storeDataIn.fire && data_valid), "atomic unit re-receive data")
128
129  // Send TLB feedback to store issue queue
130  // we send feedback right after we receives request
131  // also, we always treat amo as tlb hit
132  // since we will continue polling tlb all by ourself
133  io.feedbackSlow.valid       := GatedValidRegNext(GatedValidRegNext(io.in.valid))
134  io.feedbackSlow.bits.hit    := true.B
135  io.feedbackSlow.bits.robIdx  := RegEnable(io.in.bits.uop.robIdx, io.in.valid)
136  io.feedbackSlow.bits.sqIdx   := RegEnable(io.in.bits.uop.sqIdx, io.in.valid)
137  io.feedbackSlow.bits.lqIdx   := RegEnable(io.in.bits.uop.lqIdx, io.in.valid)
138  io.feedbackSlow.bits.flushState := DontCare
139  io.feedbackSlow.bits.sourceType := DontCare
140  io.feedbackSlow.bits.dataInvalidSqIdx := DontCare
141
142  // atomic trigger
143  val csrCtrl = io.csrCtrl
144  val tdata = Reg(Vec(TriggerNum, new MatchTriggerIO))
145  val tEnableVec = RegInit(VecInit(Seq.fill(TriggerNum)(false.B)))
146  tEnableVec := csrCtrl.mem_trigger.tEnableVec
147  when (csrCtrl.mem_trigger.tUpdate.valid) {
148    tdata(csrCtrl.mem_trigger.tUpdate.bits.addr) := csrCtrl.mem_trigger.tUpdate.bits.tdata
149  }
150
151  val debugMode = csrCtrl.mem_trigger.debugMode
152  val triggerCanRaiseBpExp = csrCtrl.mem_trigger.triggerCanRaiseBpExp
153  val backendTriggerTimingVec = VecInit(tdata.map(_.timing))
154  val backendTriggerChainVec = VecInit(tdata.map(_.chain))
155  val backendTriggerHitVec = WireInit(VecInit(Seq.fill(TriggerNum)(false.B)))
156  val backendTriggerCanFireVec = RegInit(VecInit(Seq.fill(TriggerNum)(false.B)))
157
158  assert(state === s_invalid || in.uop.fuOpType(1,0) === "b10".U || in.uop.fuOpType(1,0) === "b11".U,
159    "Only word or doubleword is supported")
160  val isLr = in.uop.fuOpType === LSUOpType.lr_w || in.uop.fuOpType === LSUOpType.lr_d
161  val isSc = in.uop.fuOpType === LSUOpType.sc_w || in.uop.fuOpType === LSUOpType.sc_d
162  val isNotLr = !isLr
163  val isNotSc = !isSc
164
165  // store trigger
166  val store_hit = Wire(Vec(TriggerNum, Bool()))
167  for (j <- 0 until TriggerNum) {
168    store_hit(j) := !tdata(j).select && !debugMode && isNotLr && TriggerCmp(
169      vaddr,
170      tdata(j).tdata2,
171      tdata(j).matchType,
172      tEnableVec(j) && tdata(j).store
173    )
174  }
175  // load trigger
176  val load_hit = Wire(Vec(TriggerNum, Bool()))
177  for (j <- 0 until TriggerNum) {
178    load_hit(j) := !tdata(j).select && !debugMode && isNotSc && TriggerCmp(
179      vaddr,
180      tdata(j).tdata2,
181      tdata(j).matchType,
182      tEnableVec(j) && tdata(j).load
183    )
184  }
185  backendTriggerHitVec := store_hit.zip(load_hit).map { case (sh, lh) => sh || lh }
186  // triggerCanFireVec will update at T+1
187  TriggerCheckCanFire(TriggerNum, backendTriggerCanFireVec, backendTriggerHitVec, backendTriggerTimingVec, backendTriggerChainVec)
188
189  val actionVec = VecInit(tdata.map(_.action))
190  val triggerAction = Wire(TriggerAction())
191  TriggerUtil.triggerActionGen(triggerAction, backendTriggerCanFireVec, actionVec, triggerCanRaiseBpExp)
192  val triggerDebugMode = TriggerAction.isDmode(triggerAction)
193  val triggerBreakpoint = TriggerAction.isExp(triggerAction)
194
195  // tlb translation, manipulating signals && deal with exception
196  // at the same time, flush sbuffer
197  when (state === s_tlb_and_flush_sbuffer_req) {
198    // send req to dtlb
199    // keep firing until tlb hit
200    io.dtlb.req.valid       := true.B
201    io.dtlb.req.bits.vaddr  := in.src(0)
202    io.dtlb.req.bits.fullva := in.src(0)
203    io.dtlb.req.bits.checkfullva := true.B
204    io.dtlb.resp.ready      := true.B
205    io.dtlb.req.bits.cmd    := Mux(isLr, TlbCmd.atom_read, TlbCmd.atom_write)
206    io.dtlb.req.bits.debug.pc := in.uop.pc
207    io.dtlb.req.bits.debug.robIdx := in.uop.robIdx
208    io.dtlb.req.bits.debug.isFirstIssue := false.B
209    io.out.bits.uop.debugInfo.tlbFirstReqTime := GTimer() // FIXME lyq: it will be always assigned
210
211    // send req to sbuffer to flush it if it is not empty
212    io.flush_sbuffer.valid := !sbuffer_empty
213
214    // do not accept tlb resp in the first cycle
215    // this limition is for hw prefetcher
216    // when !have_sent_first_tlb_req, tlb resp may come from hw prefetch
217    have_sent_first_tlb_req := true.B
218
219    when (io.dtlb.resp.fire && have_sent_first_tlb_req){
220      paddr   := io.dtlb.resp.bits.paddr(0)
221      gpaddr  := io.dtlb.resp.bits.gpaddr(0)
222      isForVSnonLeafPTE := io.dtlb.resp.bits.isForVSnonLeafPTE
223      // exception handling
224      val addrAligned = LookupTree(in.uop.fuOpType(1,0), List(
225        "b10".U   -> (in.src(0)(1,0) === 0.U), //w
226        "b11".U   -> (in.src(0)(2,0) === 0.U)  //d
227      ))
228      exceptionVec(loadAddrMisaligned)  := !addrAligned && isLr
229      exceptionVec(storeAddrMisaligned) := !addrAligned && !isLr
230      exceptionVec(storePageFault)      := io.dtlb.resp.bits.excp(0).pf.st
231      exceptionVec(loadPageFault)       := io.dtlb.resp.bits.excp(0).pf.ld
232      exceptionVec(storeAccessFault)    := io.dtlb.resp.bits.excp(0).af.st
233      exceptionVec(loadAccessFault)     := io.dtlb.resp.bits.excp(0).af.ld
234      exceptionVec(storeGuestPageFault) := io.dtlb.resp.bits.excp(0).gpf.st
235      exceptionVec(loadGuestPageFault)  := io.dtlb.resp.bits.excp(0).gpf.ld
236
237      exceptionVec(breakPoint) := triggerBreakpoint
238      trigger                  := triggerAction
239
240      when (!io.dtlb.resp.bits.miss) {
241        is_nc := Pbmt.isNC(io.dtlb.resp.bits.pbmt(0))
242        io.out.bits.uop.debugInfo.tlbRespTime := GTimer()
243        when (!addrAligned || triggerDebugMode || triggerBreakpoint) {
244          // NOTE: when addrAligned or trigger fire, do not need to wait tlb actually
245          // check for miss aligned exceptions, tlb exception are checked next cycle for timing
246          // if there are exceptions, no need to execute it
247          state := s_finish
248          out_valid := true.B
249          atom_override_xtval := true.B
250        } .otherwise {
251          state := s_pm
252        }
253      }
254    }
255  }
256
257  val pbmtReg = RegEnable(io.dtlb.resp.bits.pbmt(0), io.dtlb.resp.fire && !io.dtlb.resp.bits.miss)
258  when (state === s_pm) {
259    val pmp = WireInit(io.pmpResp)
260    is_mmio := Pbmt.isIO(pbmtReg) || (Pbmt.isPMA(pbmtReg) && pmp.mmio)
261
262    // NOTE: only handle load/store exception here, if other exception happens, don't send here
263    val exception_va = exceptionVec(storePageFault) || exceptionVec(loadPageFault) ||
264      exceptionVec(storeGuestPageFault) || exceptionVec(loadGuestPageFault) ||
265      exceptionVec(storeAccessFault) || exceptionVec(loadAccessFault)
266    val exception_pa = pmp.st || pmp.ld || pmp.mmio
267    when (exception_va || exception_pa) {
268      state := s_finish
269      out_valid := true.B
270      atom_override_xtval := true.B
271    }.otherwise {
272      // if sbuffer has been flushed, go to query dcache, otherwise wait for sbuffer.
273      state := Mux(sbuffer_empty, s_cache_req, s_wait_flush_sbuffer_resp);
274    }
275    // update storeAccessFault bit
276    exceptionVec(loadAccessFault) := exceptionVec(loadAccessFault) || (pmp.ld || pmp.mmio) && isLr
277    exceptionVec(storeAccessFault) := exceptionVec(storeAccessFault) || pmp.st || (pmp.ld || pmp.mmio) && !isLr
278  }
279
280  when (state === s_wait_flush_sbuffer_resp) {
281    when (sbuffer_empty) {
282      state := s_cache_req
283    }
284  }
285
286  when (state === s_cache_req) {
287    val pipe_req = io.dcache.req.bits
288    pipe_req := DontCare
289
290    pipe_req.cmd := LookupTree(in.uop.fuOpType, List(
291      LSUOpType.lr_w      -> M_XLR,
292      LSUOpType.sc_w      -> M_XSC,
293      LSUOpType.amoswap_w -> M_XA_SWAP,
294      LSUOpType.amoadd_w  -> M_XA_ADD,
295      LSUOpType.amoxor_w  -> M_XA_XOR,
296      LSUOpType.amoand_w  -> M_XA_AND,
297      LSUOpType.amoor_w   -> M_XA_OR,
298      LSUOpType.amomin_w  -> M_XA_MIN,
299      LSUOpType.amomax_w  -> M_XA_MAX,
300      LSUOpType.amominu_w -> M_XA_MINU,
301      LSUOpType.amomaxu_w -> M_XA_MAXU,
302
303      LSUOpType.lr_d      -> M_XLR,
304      LSUOpType.sc_d      -> M_XSC,
305      LSUOpType.amoswap_d -> M_XA_SWAP,
306      LSUOpType.amoadd_d  -> M_XA_ADD,
307      LSUOpType.amoxor_d  -> M_XA_XOR,
308      LSUOpType.amoand_d  -> M_XA_AND,
309      LSUOpType.amoor_d   -> M_XA_OR,
310      LSUOpType.amomin_d  -> M_XA_MIN,
311      LSUOpType.amomax_d  -> M_XA_MAX,
312      LSUOpType.amominu_d -> M_XA_MINU,
313      LSUOpType.amomaxu_d -> M_XA_MAXU
314    ))
315    pipe_req.miss := false.B
316    pipe_req.probe := false.B
317    pipe_req.probe_need_data := false.B
318    pipe_req.source := AMO_SOURCE.U
319    pipe_req.addr   := get_block_addr(paddr)
320    pipe_req.vaddr  := get_block_addr(in.src(0)) // vaddr
321    pipe_req.word_idx  := get_word(paddr)
322    pipe_req.amo_data  := genWdata(in.src(1), in.uop.fuOpType(1,0))
323    pipe_req.amo_mask  := genWmask(paddr, in.uop.fuOpType(1,0))
324
325    io.dcache.req.valid := Mux(
326      io.dcache.req.bits.cmd === M_XLR,
327      !io.dcache.block_lr, // block lr to survive in lr storm
328      data_valid // wait until src(1) is ready
329    )
330
331    when(io.dcache.req.fire){
332      state := s_cache_resp
333      paddr_reg := paddr
334      data_reg := io.dcache.req.bits.amo_data
335      mask_reg := io.dcache.req.bits.amo_mask
336      fuop_reg := in.uop.fuOpType
337    }
338  }
339
340  val dcache_resp_data  = Reg(UInt())
341  val dcache_resp_id    = Reg(UInt())
342  val dcache_resp_error = Reg(Bool())
343
344  when (state === s_cache_resp) {
345    // when not miss
346    // everything is OK, simply send response back to sbuffer
347    // when miss and not replay
348    // wait for missQueue to handling miss and replaying our request
349    // when miss and replay
350    // req missed and fail to enter missQueue, manually replay it later
351    // TODO: add assertions:
352    // 1. add a replay delay counter?
353    // 2. when req gets into MissQueue, it should not miss any more
354    when(io.dcache.resp.fire) {
355      when(io.dcache.resp.bits.miss) {
356        when(io.dcache.resp.bits.replay) {
357          state := s_cache_req
358        }
359      } .otherwise {
360        dcache_resp_data := io.dcache.resp.bits.data
361        dcache_resp_id := io.dcache.resp.bits.id
362        dcache_resp_error := io.dcache.resp.bits.error
363        state := s_cache_resp_latch
364      }
365    }
366  }
367
368  when (state === s_cache_resp_latch) {
369    is_lrsc_valid :=  dcache_resp_id
370    val rdataSel = LookupTree(paddr(2, 0), List(
371      "b000".U -> dcache_resp_data(63, 0),
372      "b100".U -> dcache_resp_data(63, 32)
373    ))
374
375    resp_data_wire := Mux(
376      isSc,
377      dcache_resp_data,
378      LookupTree(in.uop.fuOpType(1,0), List(
379        "b10".U -> SignExt(rdataSel(31, 0), XLEN), // w
380        "b11".U -> SignExt(rdataSel(63, 0), XLEN)  // d
381      ))
382    )
383
384    when (dcache_resp_error && io.csrCtrl.cache_error_enable) {
385      exceptionVec(loadAccessFault)  := isLr
386      exceptionVec(storeAccessFault) := !isLr
387      assert(!exceptionVec(loadAccessFault))
388      assert(!exceptionVec(storeAccessFault))
389    }
390
391    resp_data := resp_data_wire
392    state := s_finish
393    out_valid := true.B
394  }
395
396  io.out.valid := out_valid
397  XSError((state === s_finish) =/= out_valid, "out_valid reg error\n")
398  io.out.bits := DontCare
399  io.out.bits.uop := in.uop
400  io.out.bits.uop.exceptionVec := exceptionVec
401  io.out.bits.uop.trigger := trigger
402  io.out.bits.uop.fuType := FuType.mou.U
403  io.out.bits.data := resp_data
404  io.out.bits.debug.isMMIO := is_mmio
405  io.out.bits.debug.isNC := is_nc
406  io.out.bits.debug.paddr := paddr
407  when (io.out.fire) {
408    XSDebug("atomics writeback: pc %x data %x\n", io.out.bits.uop.pc, io.dcache.resp.bits.data)
409    state := s_invalid
410    out_valid := false.B
411  }
412
413  when (state === s_finish) {
414    data_valid := false.B
415  }
416
417  when (io.redirect.valid) {
418    atom_override_xtval := false.B
419  }
420
421  if (env.EnableDifftest) {
422    val difftest = DifftestModule(new DiffAtomicEvent)
423    difftest.coreid := io.hartId
424    difftest.valid  := state === s_cache_resp_latch
425    difftest.addr   := paddr_reg
426    difftest.data   := data_reg
427    difftest.mask   := mask_reg
428    difftest.fuop   := fuop_reg
429    difftest.out    := resp_data_wire
430  }
431
432  if (env.EnableDifftest || env.AlwaysBasicDiff) {
433    val uop = io.out.bits.uop
434    val difftest = DifftestModule(new DiffLrScEvent)
435    difftest.coreid := io.hartId
436    difftest.valid := io.out.fire &&
437      (uop.fuOpType === LSUOpType.sc_d || uop.fuOpType === LSUOpType.sc_w)
438    difftest.success := is_lrsc_valid
439  }
440}
441