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