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