xref: /XiangShan/src/main/scala/xiangshan/mem/pipeline/AtomicsUnit.scala (revision d0de7e4a4bcd4633260dda99dfedc2a5e543b8b4)
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(storeAccessFault) || exceptionVec(loadAccessFault)
193    val exception_pa = pmp.st || pmp.ld
194    when (exception_va || exception_pa) {
195      state := s_finish
196      out_valid := true.B
197      atom_override_xtval := true.B
198    }.otherwise {
199      // if sbuffer has been flushed, go to query dcache, otherwise wait for sbuffer.
200      state := Mux(sbuffer_empty, s_cache_req, s_wait_flush_sbuffer_resp);
201    }
202    // update storeAccessFault bit
203    exceptionVec(loadAccessFault) := exceptionVec(loadAccessFault) || pmp.ld && isLr
204    exceptionVec(storeAccessFault) := exceptionVec(storeAccessFault) || pmp.st || pmp.ld && !isLr
205  }
206
207  when (state === s_wait_flush_sbuffer_resp) {
208    when (sbuffer_empty) {
209      state := s_cache_req
210    }
211  }
212
213  when (state === s_cache_req) {
214    val pipe_req = io.dcache.req.bits
215    pipe_req := DontCare
216
217    pipe_req.cmd := LookupTree(in.uop.ctrl.fuOpType, List(
218      LSUOpType.lr_w      -> M_XLR,
219      LSUOpType.sc_w      -> M_XSC,
220      LSUOpType.amoswap_w -> M_XA_SWAP,
221      LSUOpType.amoadd_w  -> M_XA_ADD,
222      LSUOpType.amoxor_w  -> M_XA_XOR,
223      LSUOpType.amoand_w  -> M_XA_AND,
224      LSUOpType.amoor_w   -> M_XA_OR,
225      LSUOpType.amomin_w  -> M_XA_MIN,
226      LSUOpType.amomax_w  -> M_XA_MAX,
227      LSUOpType.amominu_w -> M_XA_MINU,
228      LSUOpType.amomaxu_w -> M_XA_MAXU,
229
230      LSUOpType.lr_d      -> M_XLR,
231      LSUOpType.sc_d      -> M_XSC,
232      LSUOpType.amoswap_d -> M_XA_SWAP,
233      LSUOpType.amoadd_d  -> M_XA_ADD,
234      LSUOpType.amoxor_d  -> M_XA_XOR,
235      LSUOpType.amoand_d  -> M_XA_AND,
236      LSUOpType.amoor_d   -> M_XA_OR,
237      LSUOpType.amomin_d  -> M_XA_MIN,
238      LSUOpType.amomax_d  -> M_XA_MAX,
239      LSUOpType.amominu_d -> M_XA_MINU,
240      LSUOpType.amomaxu_d -> M_XA_MAXU
241    ))
242    pipe_req.miss := false.B
243    pipe_req.probe := false.B
244    pipe_req.probe_need_data := false.B
245    pipe_req.source := AMO_SOURCE.U
246    pipe_req.addr   := get_block_addr(paddr)
247    pipe_req.vaddr  := get_block_addr(in.src(0)) // vaddr
248    pipe_req.word_idx  := get_word(paddr)
249    pipe_req.amo_data  := genWdata(in.src(1), in.uop.ctrl.fuOpType(1,0))
250    pipe_req.amo_mask  := genWmask(paddr, in.uop.ctrl.fuOpType(1,0))
251
252    io.dcache.req.valid := Mux(
253      io.dcache.req.bits.cmd === M_XLR,
254      !io.dcache.block_lr, // block lr to survive in lr storm
255      data_valid // wait until src(1) is ready
256    )
257
258    when(io.dcache.req.fire){
259      state := s_cache_resp
260      paddr_reg := paddr
261      data_reg := io.dcache.req.bits.amo_data
262      mask_reg := io.dcache.req.bits.amo_mask
263      fuop_reg := in.uop.ctrl.fuOpType
264    }
265  }
266
267  val dcache_resp_data  = Reg(UInt())
268  val dcache_resp_id    = Reg(UInt())
269  val dcache_resp_error = Reg(Bool())
270
271  when (state === s_cache_resp) {
272    // when not miss
273    // everything is OK, simply send response back to sbuffer
274    // when miss and not replay
275    // wait for missQueue to handling miss and replaying our request
276    // when miss and replay
277    // req missed and fail to enter missQueue, manually replay it later
278    // TODO: add assertions:
279    // 1. add a replay delay counter?
280    // 2. when req gets into MissQueue, it should not miss any more
281    when(io.dcache.resp.fire) {
282      when(io.dcache.resp.bits.miss) {
283        when(io.dcache.resp.bits.replay) {
284          state := s_cache_req
285        }
286      } .otherwise {
287        dcache_resp_data := io.dcache.resp.bits.data
288        dcache_resp_id := io.dcache.resp.bits.id
289        dcache_resp_error := io.dcache.resp.bits.error
290        state := s_cache_resp_latch
291      }
292    }
293  }
294
295  when (state === s_cache_resp_latch) {
296    is_lrsc_valid :=  dcache_resp_id
297    val rdataSel = LookupTree(paddr(2, 0), List(
298      "b000".U -> dcache_resp_data(63, 0),
299      "b001".U -> dcache_resp_data(63, 8),
300      "b010".U -> dcache_resp_data(63, 16),
301      "b011".U -> dcache_resp_data(63, 24),
302      "b100".U -> dcache_resp_data(63, 32),
303      "b101".U -> dcache_resp_data(63, 40),
304      "b110".U -> dcache_resp_data(63, 48),
305      "b111".U -> dcache_resp_data(63, 56)
306    ))
307
308    resp_data_wire := LookupTree(in.uop.ctrl.fuOpType, List(
309      LSUOpType.lr_w      -> SignExt(rdataSel(31, 0), XLEN),
310      LSUOpType.sc_w      -> dcache_resp_data,
311      LSUOpType.amoswap_w -> SignExt(rdataSel(31, 0), XLEN),
312      LSUOpType.amoadd_w  -> SignExt(rdataSel(31, 0), XLEN),
313      LSUOpType.amoxor_w  -> SignExt(rdataSel(31, 0), XLEN),
314      LSUOpType.amoand_w  -> SignExt(rdataSel(31, 0), XLEN),
315      LSUOpType.amoor_w   -> SignExt(rdataSel(31, 0), XLEN),
316      LSUOpType.amomin_w  -> SignExt(rdataSel(31, 0), XLEN),
317      LSUOpType.amomax_w  -> SignExt(rdataSel(31, 0), XLEN),
318      LSUOpType.amominu_w -> SignExt(rdataSel(31, 0), XLEN),
319      LSUOpType.amomaxu_w -> SignExt(rdataSel(31, 0), XLEN),
320
321      LSUOpType.lr_d      -> SignExt(rdataSel(63, 0), XLEN),
322      LSUOpType.sc_d      -> dcache_resp_data,
323      LSUOpType.amoswap_d -> SignExt(rdataSel(63, 0), XLEN),
324      LSUOpType.amoadd_d  -> SignExt(rdataSel(63, 0), XLEN),
325      LSUOpType.amoxor_d  -> SignExt(rdataSel(63, 0), XLEN),
326      LSUOpType.amoand_d  -> SignExt(rdataSel(63, 0), XLEN),
327      LSUOpType.amoor_d   -> SignExt(rdataSel(63, 0), XLEN),
328      LSUOpType.amomin_d  -> SignExt(rdataSel(63, 0), XLEN),
329      LSUOpType.amomax_d  -> SignExt(rdataSel(63, 0), XLEN),
330      LSUOpType.amominu_d -> SignExt(rdataSel(63, 0), XLEN),
331      LSUOpType.amomaxu_d -> SignExt(rdataSel(63, 0), XLEN)
332    ))
333
334    when (dcache_resp_error && io.csrCtrl.cache_error_enable) {
335      exceptionVec(loadAccessFault)  := isLr
336      exceptionVec(storeAccessFault) := !isLr
337      assert(!exceptionVec(loadAccessFault))
338      assert(!exceptionVec(storeAccessFault))
339    }
340
341    resp_data := resp_data_wire
342    state := s_finish
343    out_valid := true.B
344  }
345
346  io.out.valid := out_valid
347  XSError((state === s_finish) =/= out_valid, "out_valid reg error\n")
348  io.out.bits := DontCare
349  io.out.bits.uop := in.uop
350  io.out.bits.uop.cf.exceptionVec := exceptionVec
351  io.out.bits.data := resp_data
352  io.out.bits.redirectValid := false.B
353  io.out.bits.debug.isMMIO := is_mmio
354  io.out.bits.debug.paddr := paddr
355  when (io.out.fire) {
356    XSDebug("atomics writeback: pc %x data %x\n", io.out.bits.uop.cf.pc, io.dcache.resp.bits.data)
357    state := s_invalid
358    out_valid := false.B
359  }
360
361  when (state === s_finish) {
362    data_valid := false.B
363  }
364
365  when (io.redirect.valid) {
366    atom_override_xtval := false.B
367  }
368
369  /*
370  // atomic trigger
371  val csrCtrl = io.csrCtrl
372  val tdata = Reg(Vec(6, new MatchTriggerIO))
373  val tEnable = RegInit(VecInit(Seq.fill(6)(false.B)))
374  val en = csrCtrl.trigger_enable
375  tEnable := VecInit(en(2), en (3), en(7), en(4), en(5), en(9))
376  when(csrCtrl.mem_trigger.t.valid) {
377    tdata(csrCtrl.mem_trigger.t.bits.addr) := csrCtrl.mem_trigger.t.bits.tdata
378  }
379  val lTriggerMapping = Map(0 -> 2, 1 -> 3, 2 -> 5)
380  val sTriggerMapping = Map(0 -> 0, 1 -> 1, 2 -> 4)
381
382  val backendTriggerHitReg = Reg(Vec(6, Bool()))
383  backendTriggerHitReg := VecInit(Seq.fill(6)(false.B))
384
385  when(state === s_cache_req){
386    // store trigger
387    val store_hit = Wire(Vec(3, Bool()))
388    for (j <- 0 until 3) {
389        store_hit(j) := !tdata(sTriggerMapping(j)).select && TriggerCmp(
390          vaddr,
391          tdata(sTriggerMapping(j)).tdata2,
392          tdata(sTriggerMapping(j)).matchType,
393          tEnable(sTriggerMapping(j))
394        )
395       backendTriggerHitReg(sTriggerMapping(j)) := store_hit(j)
396     }
397
398    when(tdata(0).chain) {
399      backendTriggerHitReg(0) := store_hit(0) && store_hit(1)
400      backendTriggerHitReg(1) := store_hit(0) && store_hit(1)
401    }
402
403    when(!in.uop.cf.trigger.backendEn(0)) {
404      backendTriggerHitReg(4) := false.B
405    }
406
407    // load trigger
408    val load_hit = Wire(Vec(3, Bool()))
409    for (j <- 0 until 3) {
410
411      val addrHit = TriggerCmp(
412        vaddr,
413        tdata(lTriggerMapping(j)).tdata2,
414        tdata(lTriggerMapping(j)).matchType,
415        tEnable(lTriggerMapping(j))
416      )
417      load_hit(j) := addrHit && !tdata(lTriggerMapping(j)).select
418      backendTriggerHitReg(lTriggerMapping(j)) := load_hit(j)
419    }
420    when(tdata(2).chain) {
421      backendTriggerHitReg(2) := load_hit(0) && load_hit(1)
422      backendTriggerHitReg(3) := load_hit(0) && load_hit(1)
423    }
424    when(!in.uop.cf.trigger.backendEn(1)) {
425      backendTriggerHitReg(5) := false.B
426    }
427  }
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.cf.trigger.backendHit := VecInit(Seq.fill(6)(false.B))
433  when(isLr){
434    // enable load trigger
435    io.out.bits.uop.cf.trigger.backendHit(2) := backendTriggerHitReg(2)
436    io.out.bits.uop.cf.trigger.backendHit(3) := backendTriggerHitReg(3)
437    io.out.bits.uop.cf.trigger.backendHit(5) := backendTriggerHitReg(5)
438  }.otherwise{
439    // enable store trigger
440    io.out.bits.uop.cf.trigger.backendHit(0) := backendTriggerHitReg(0)
441    io.out.bits.uop.cf.trigger.backendHit(1) := backendTriggerHitReg(1)
442    io.out.bits.uop.cf.trigger.backendHit(4) := backendTriggerHitReg(4)
443  }
444
445  */
446
447  if (env.EnableDifftest) {
448    val difftest = DifftestModule(new DiffAtomicEvent)
449    difftest.coreid := io.hartId
450    difftest.valid  := state === s_cache_resp_latch
451    difftest.addr   := paddr_reg
452    difftest.data   := data_reg
453    difftest.mask   := mask_reg
454    difftest.fuop   := fuop_reg
455    difftest.out    := resp_data_wire
456  }
457
458  if (env.EnableDifftest || env.AlwaysBasicDiff) {
459    val uop = io.out.bits.uop
460    val difftest = DifftestModule(new DiffLrScEvent)
461    difftest.coreid := io.hartId
462    difftest.valid := io.out.fire &&
463      (uop.ctrl.fuOpType === LSUOpType.sc_d || uop.ctrl.fuOpType === LSUOpType.sc_w)
464    difftest.success := is_lrsc_valid
465  }
466}
467