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