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