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