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