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