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