xref: /XiangShan/src/main/scala/xiangshan/cache/dcache/mainpipe/MainPipe.scala (revision e13d224a171ca31556118081225ebfc4b6018142)
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.cache
18
19import chipsalliance.rocketchip.config.Parameters
20import chisel3._
21import chisel3.util._
22import freechips.rocketchip.tilelink.ClientStates._
23import freechips.rocketchip.tilelink.MemoryOpCategories._
24import freechips.rocketchip.tilelink.TLPermissions._
25import freechips.rocketchip.tilelink.{ClientMetadata, ClientStates, TLPermissions}
26import utils._
27import xiangshan.L1CacheErrorInfo
28
29class MainPipeReq(implicit p: Parameters) extends DCacheBundle {
30  val miss = Bool() // only amo miss will refill in main pipe
31  val miss_id = UInt(log2Up(cfg.nMissEntries).W)
32  val miss_param = UInt(TLPermissions.bdWidth.W)
33  val miss_dirty = Bool()
34
35  val probe = Bool()
36  val probe_param = UInt(TLPermissions.bdWidth.W)
37  val probe_need_data = Bool()
38
39  // request info
40  // reqs from Store, AMO use this
41  // probe does not use this
42  val source = UInt(sourceTypeWidth.W)
43  val cmd = UInt(M_SZ.W)
44  // if dcache size > 32KB, vaddr is also needed for store
45  // vaddr is used to get extra index bits
46  val vaddr  = UInt(VAddrBits.W)
47  // must be aligned to block
48  val addr   = UInt(PAddrBits.W)
49
50  // store
51  val store_data = UInt((cfg.blockBytes * 8).W)
52  val store_mask = UInt(cfg.blockBytes.W)
53
54  // which word does amo work on?
55  val word_idx = UInt(log2Up(cfg.blockBytes * 8 / DataBits).W)
56  val amo_data   = UInt(DataBits.W)
57  val amo_mask   = UInt((DataBits / 8).W)
58
59  // replace
60  val replace = Bool()
61  val replace_way_en = UInt(DCacheWays.W)
62
63  val id = UInt(reqIdWidth.W)
64
65  def isLoad: Bool = source === LOAD_SOURCE.U
66  def isStore: Bool = source === STORE_SOURCE.U
67  def isAMO: Bool = source === AMO_SOURCE.U
68
69  def convertStoreReq(store: DCacheLineReq): MainPipeReq = {
70    val req = Wire(new MainPipeReq)
71    req := DontCare
72    req.miss := false.B
73    req.miss_dirty := false.B
74    req.probe := false.B
75    req.probe_need_data := false.B
76    req.source := STORE_SOURCE.U
77    req.cmd := store.cmd
78    req.addr := store.addr
79    req.vaddr := store.vaddr
80    req.store_data := store.data
81    req.store_mask := store.mask
82    req.replace := false.B
83    req.id := store.id
84    req
85  }
86}
87
88class MainPipe(implicit p: Parameters) extends DCacheModule with HasPerfEvents {
89  val metaBits = (new Meta).getWidth
90  val encMetaBits = cacheParams.tagCode.width((new MetaAndTag).getWidth) - tagBits
91
92  val io = IO(new Bundle() {
93    // probe queue
94    val probe_req = Flipped(DecoupledIO(new MainPipeReq))
95    // store miss go to miss queue
96    val miss_req = DecoupledIO(new MissReq)
97    // store buffer
98    val store_req = Flipped(DecoupledIO(new DCacheLineReq))
99    val store_replay_resp = ValidIO(new DCacheLineResp)
100    val store_hit_resp = ValidIO(new DCacheLineResp)
101    val release_update = ValidIO(new ReleaseUpdate)
102    // atmoics
103    val atomic_req = Flipped(DecoupledIO(new MainPipeReq))
104    val atomic_resp = ValidIO(new AtomicsResp)
105    // replace
106    val replace_req = Flipped(DecoupledIO(new MainPipeReq))
107    val replace_resp = ValidIO(UInt(log2Up(cfg.nMissEntries).W))
108    // write-back queue
109    val wb = DecoupledIO(new WritebackReq)
110
111    val data_read = DecoupledIO(new L1BankedDataReadLineReq)
112    val data_resp = Input(Vec(DCacheBanks, new L1BankedDataReadResult()))
113    val data_write = DecoupledIO(new L1BankedDataWriteReq)
114
115    val meta_read = DecoupledIO(new MetaReadReq)
116    val meta_resp = Input(Vec(nWays, UInt(encMetaBits.W)))
117    val meta_write = DecoupledIO(new MetaWriteReq)
118
119    val tag_read = DecoupledIO(new TagReadReq)
120    val tag_resp = Input(Vec(nWays, UInt(tagBits.W)))
121    val tag_write = DecoupledIO(new TagWriteReq)
122
123    // update state vec in replacement algo
124    val replace_access = ValidIO(new ReplacementAccessBundle)
125    // find the way to be replaced
126    val replace_way = new ReplacementWayReqIO
127
128    val status = new Bundle() {
129      val s0_set = ValidIO(UInt(idxBits.W))
130      val s1, s2, s3 = ValidIO(new Bundle() {
131        val set = UInt(idxBits.W)
132        val way_en = UInt(nWays.W)
133      })
134    }
135
136    // lrsc locked block should block probe
137    val lrsc_locked_block = Output(Valid(UInt(PAddrBits.W)))
138    val invalid_resv_set = Input(Bool())
139    val update_resv_set = Output(Bool())
140
141    // ecc error
142    val error = Output(new L1CacheErrorInfo())
143  })
144
145  // meta array is made of regs, so meta write or read should always be ready
146  assert(RegNext(io.meta_read.ready))
147  assert(RegNext(io.meta_write.ready))
148
149  val s1_s0_set_conflict, s2_s0_set_conlict, s3_s0_set_conflict = Wire(Bool())
150  val set_conflict = s1_s0_set_conflict || s2_s0_set_conlict || s3_s0_set_conflict
151  // check sbuffer store req set_conflict in parallel with req arbiter
152  // it will speed up the generation of store_req.ready, which is in crit. path
153  val s1_s0_set_conflict_store, s2_s0_set_conlict_store, s3_s0_set_conflict_store = Wire(Bool())
154  val store_set_conflict = s1_s0_set_conflict_store || s2_s0_set_conlict_store || s3_s0_set_conflict_store
155  val s1_ready, s2_ready, s3_ready = Wire(Bool())
156
157  // convert store req to main pipe req, and select a req from store and probe
158  val store_req = Wire(DecoupledIO(new MainPipeReq))
159  store_req.bits := (new MainPipeReq).convertStoreReq(io.store_req.bits)
160  store_req.valid := io.store_req.valid
161  io.store_req.ready := store_req.ready
162
163  // s0: read meta and tag
164  val req = Wire(DecoupledIO(new MainPipeReq))
165  arbiter(
166    in = Seq(
167      io.probe_req,
168      io.replace_req,
169      store_req, // Note: store_req.ready is now manually assigned for better timing
170      io.atomic_req
171    ),
172    out = req,
173    name = Some("main_pipe_req")
174  )
175
176  val store_idx = get_idx(io.store_req.bits.vaddr)
177  // manually assign store_req.ready for better timing
178  // now store_req set conflict check is done in parallel with req arbiter
179  store_req.ready := io.meta_read.ready && io.tag_read.ready && s1_ready && !store_set_conflict &&
180    !io.probe_req.valid && !io.replace_req.valid
181  val s0_req = req.bits
182  val s0_idx = get_idx(s0_req.vaddr)
183  val s0_can_go = io.meta_read.ready && io.tag_read.ready && s1_ready && !set_conflict
184  val s0_fire = req.valid && s0_can_go
185
186  val bank_write = VecInit((0 until DCacheBanks).map(i => get_mask_of_bank(i, s0_req.store_mask).orR)).asUInt
187  val bank_full_write = VecInit((0 until DCacheBanks).map(i => get_mask_of_bank(i, s0_req.store_mask).andR)).asUInt
188  val banks_full_overwrite = bank_full_write.andR
189
190  val banked_store_rmask = bank_write & ~bank_full_write
191  val banked_full_rmask = ~0.U(DCacheBanks.W)
192  val banked_none_rmask = 0.U(DCacheBanks.W)
193
194  val store_need_data = !s0_req.probe && s0_req.isStore && banked_store_rmask.orR
195  val probe_need_data = s0_req.probe
196  val amo_need_data = !s0_req.probe && s0_req.isAMO
197  val miss_need_data = s0_req.miss
198  val replace_need_data = s0_req.replace
199
200  val banked_need_data = store_need_data || probe_need_data || amo_need_data || miss_need_data || replace_need_data
201
202  val s0_banked_rmask = Mux(store_need_data, banked_store_rmask,
203    Mux(probe_need_data || amo_need_data || miss_need_data || replace_need_data,
204      banked_full_rmask,
205      banked_none_rmask
206    ))
207
208  // generate wmask here and use it in stage 2
209  val banked_store_wmask = bank_write
210  val banked_full_wmask = ~0.U(DCacheBanks.W)
211  val banked_none_wmask = 0.U(DCacheBanks.W)
212
213  // s1: read data
214  val s1_valid = RegInit(false.B)
215  val s1_need_data = RegEnable(banked_need_data, s0_fire)
216  val s1_req = RegEnable(s0_req, s0_fire)
217  val s1_banked_rmask = RegEnable(s0_banked_rmask, s0_fire)
218  val s1_banked_store_wmask = RegEnable(banked_store_wmask, s0_fire)
219  val s1_can_go = s2_ready && (io.data_read.ready || !s1_need_data)
220  val s1_fire = s1_valid && s1_can_go
221  val s1_idx = get_idx(s1_req.vaddr)
222  when (s0_fire) {
223    s1_valid := true.B
224  }.elsewhen (s1_fire) {
225    s1_valid := false.B
226  }
227  s1_ready := !s1_valid || s1_can_go
228  s1_s0_set_conflict := s1_valid && s0_idx === s1_idx
229  s1_s0_set_conflict_store := s1_valid && store_idx === s1_idx
230
231  def getMeta(encMeta: UInt): UInt = {
232    require(encMeta.getWidth == encMetaBits)
233    encMeta(metaBits - 1, 0)
234  }
235  def getECC(encMeta: UInt): UInt = {
236    require(encMeta.getWidth == encMetaBits)
237    encMeta(encMetaBits - 1, metaBits)
238  }
239
240  val tag_resp = Wire(Vec(nWays, UInt(tagBits.W)))
241  val ecc_meta_resp = Wire(Vec(nWays, UInt(encMetaBits.W)))
242  tag_resp := Mux(RegNext(s0_fire), io.tag_resp, RegNext(tag_resp))
243  ecc_meta_resp := Mux(RegNext(s0_fire), io.meta_resp, RegNext(ecc_meta_resp))
244  val meta_resp = ecc_meta_resp.map(getMeta(_))
245  val ecc_resp = ecc_meta_resp.map(getECC(_))
246
247  def wayMap[T <: Data](f: Int => T) = VecInit((0 until nWays).map(f))
248  val s1_tag_eq_way = wayMap((w: Int) => tag_resp(w) === get_tag(s1_req.addr)).asUInt
249  val s1_tag_match_way = wayMap((w: Int) => s1_tag_eq_way(w) && Meta(meta_resp(w)).coh.isValid()).asUInt
250  val s1_tag_match = s1_tag_match_way.orR
251
252  val s1_hit_tag = Mux(s1_tag_match, Mux1H(s1_tag_match_way, wayMap(w => tag_resp(w))), get_tag(s1_req.addr))
253  val s1_hit_coh = ClientMetadata(Mux(s1_tag_match, Mux1H(s1_tag_match_way, wayMap(w => meta_resp(w))), 0.U))
254  val s1_ecc = Mux1H(s1_tag_match_way, wayMap((w: Int) => ecc_resp(w)))
255  val s1_eccMetaAndTag = Cat(s1_ecc, MetaAndTag(s1_hit_coh, get_tag(s1_req.addr)).asUInt)
256
257  // replacement policy
258  val s1_repl_way_en = WireInit(0.U(nWays.W))
259  s1_repl_way_en := Mux(RegNext(s0_fire), UIntToOH(io.replace_way.way), RegNext(s1_repl_way_en))
260  val s1_repl_tag = Mux1H(s1_repl_way_en, wayMap(w => tag_resp(w)))
261  val s1_repl_coh = Mux1H(s1_repl_way_en, wayMap(w => meta_resp(w))).asTypeOf(new ClientMetadata)
262
263  val s1_need_replacement = (s1_req.miss || s1_req.isStore && !s1_req.probe) && !s1_tag_match
264  val s1_way_en = Mux(s1_req.replace, s1_req.replace_way_en, Mux(s1_need_replacement, s1_repl_way_en, s1_tag_match_way))
265  val s1_tag = Mux(s1_req.replace, get_tag(s1_req.addr), Mux(s1_need_replacement, s1_repl_tag, s1_hit_tag))
266  val s1_coh = Mux(
267    s1_req.replace,
268    Mux1H(s1_req.replace_way_en, meta_resp.map(ClientMetadata(_))),
269    Mux(s1_need_replacement, s1_repl_coh, s1_hit_coh)
270  )
271
272  val s1_has_permission = s1_hit_coh.onAccess(s1_req.cmd)._1
273  val s1_hit = s1_tag_match && s1_has_permission
274  val s1_pregen_can_go_to_mq = !s1_req.replace && !s1_req.probe && !s1_req.miss && (s1_req.isStore || s1_req.isAMO) && !s1_hit
275
276  // s2: select data, return resp if this is a store miss
277  val s2_valid = RegInit(false.B)
278  val s2_req = RegEnable(s1_req, s1_fire)
279  val s2_tag_match = RegEnable(s1_tag_match, s1_fire)
280  val s2_hit_coh = RegEnable(s1_hit_coh, s1_fire)
281  val (s2_has_permission, _, s2_new_hit_coh) = s2_hit_coh.onAccess(s2_req.cmd)
282  val s2_repl_way_en = RegEnable(s1_repl_way_en, s1_fire)
283  val s2_repl_tag = RegEnable(s1_repl_tag, s1_fire)
284  val s2_repl_coh = RegEnable(s1_repl_coh, s1_fire)
285  val s2_need_replacement = RegEnable(s1_need_replacement, s1_fire)
286  val s2_idx = get_idx(s2_req.vaddr)
287  val s2_way_en = RegEnable(s1_way_en, s1_fire)
288  val s2_tag = RegEnable(s1_tag, s1_fire)
289  val s2_coh = RegEnable(s1_coh, s1_fire)
290  val s2_banked_store_wmask = RegEnable(s1_banked_store_wmask, s1_fire)
291
292  val s2_hit = s2_tag_match && s2_has_permission
293  val s2_amo_hit = s2_hit && !s2_req.probe && !s2_req.miss && s2_req.isAMO
294  val s2_store_hit = s2_hit && !s2_req.probe && !s2_req.miss && s2_req.isStore
295
296  s2_s0_set_conlict := s2_valid && s0_idx === s2_idx
297  s2_s0_set_conlict_store := s2_valid && store_idx === s2_idx
298
299  // For a store req, it either hits and goes to s3, or miss and enter miss queue immediately
300  val s2_can_go_to_s3 = (s2_req.replace || s2_req.probe || s2_req.miss || (s2_req.isStore || s2_req.isAMO) && s2_hit) && s3_ready
301  val s2_can_go_to_mq = RegEnable(s1_pregen_can_go_to_mq, s1_fire)
302  assert(RegNext(!(s2_valid && s2_can_go_to_s3 && s2_can_go_to_mq)))
303  val s2_can_go = s2_can_go_to_s3 || s2_can_go_to_mq
304  val s2_fire = s2_valid && s2_can_go
305  val s2_fire_to_s3 = s2_valid && s2_can_go_to_s3
306  when (s1_fire) {
307    s2_valid := true.B
308  }.elsewhen (s2_fire) {
309    s2_valid := false.B
310  }
311  s2_ready := !s2_valid || s2_can_go
312  val replay = !io.miss_req.ready
313
314  val data_resp = Wire(io.data_resp.cloneType)
315  data_resp := Mux(RegNext(s1_fire), io.data_resp, RegNext(data_resp))
316  val s2_store_data_merged = Wire(Vec(DCacheBanks, UInt(DCacheSRAMRowBits.W)))
317
318  def mergePutData(old_data: UInt, new_data: UInt, wmask: UInt): UInt = {
319    val full_wmask = FillInterleaved(8, wmask)
320    ((~full_wmask & old_data) | (full_wmask & new_data))
321  }
322
323  val s2_data = WireInit(VecInit((0 until DCacheBanks).map(i => {
324    val decoded = cacheParams.dataCode.decode(data_resp(i).asECCData())
325    // assert(!RegNext(s2_valid && s2_hit && decoded.uncorrectable))
326    // TODO: trigger ecc error
327    data_resp(i).raw_data
328  })))
329
330  for (i <- 0 until DCacheBanks) {
331    val old_data = s2_data(i)
332    val new_data = get_data_of_bank(i, s2_req.store_data)
333    // for amo hit, we should use read out SRAM data
334    // do not merge with store data
335    val wmask = Mux(s2_amo_hit, 0.U(wordBytes.W), get_mask_of_bank(i, s2_req.store_mask))
336    s2_store_data_merged(i) := mergePutData(old_data, new_data, wmask)
337  }
338
339  val s2_data_word = s2_store_data_merged(s2_req.word_idx)
340
341  // s3: write data, meta and tag
342  val s3_valid = RegInit(false.B)
343  val s3_req = RegEnable(s2_req, s2_fire_to_s3)
344  val s3_idx = get_idx(s3_req.vaddr)
345  val s3_tag = RegEnable(s2_tag, s2_fire_to_s3)
346  val s3_tag_match = RegEnable(s2_tag_match, s2_fire_to_s3)
347  val s3_coh = RegEnable(s2_coh, s2_fire_to_s3)
348  val s3_hit = RegEnable(s2_hit, s2_fire_to_s3)
349  val s3_amo_hit = RegEnable(s2_amo_hit, s2_fire_to_s3)
350  val s3_store_hit = RegEnable(s2_store_hit, s2_fire_to_s3)
351  val s3_hit_coh = RegEnable(s2_hit_coh, s2_fire_to_s3)
352  val s3_new_hit_coh = RegEnable(s2_new_hit_coh, s2_fire_to_s3)
353  val s3_way_en = RegEnable(s2_way_en, s2_fire_to_s3)
354  val s3_banked_store_wmask = RegEnable(s2_banked_store_wmask, s2_fire_to_s3)
355  val s3_store_data_merged = RegEnable(s2_store_data_merged, s2_fire_to_s3)
356  val s3_data_word = RegEnable(s2_data_word, s2_fire_to_s3)
357  val s3_data = RegEnable(s2_data, s2_fire_to_s3)
358  val (probe_has_dirty_data, probe_shrink_param, probe_new_coh) = s3_coh.onProbe(s3_req.probe_param)
359  val s3_need_replacement = RegEnable(s2_need_replacement, s2_fire_to_s3)
360
361  val miss_update_meta = s3_req.miss
362  val probe_update_meta = s3_req.probe && s3_tag_match && s3_coh =/= probe_new_coh
363  val store_update_meta = s3_req.isStore && !s3_req.probe && s3_hit_coh =/= s3_new_hit_coh
364  val amo_update_meta = s3_req.isAMO && !s3_req.probe && s3_hit_coh =/= s3_new_hit_coh
365  val amo_wait_amoalu = s3_req.isAMO && s3_req.cmd =/= M_XLR && s3_req.cmd =/= M_XSC
366  val update_meta = (miss_update_meta || probe_update_meta || store_update_meta || amo_update_meta) && !s3_req.replace
367
368  def missCohGen(cmd: UInt, param: UInt, dirty: Bool) = {
369    val c = categorize(cmd)
370    MuxLookup(Cat(c, param, dirty), Nothing, Seq(
371      //(effect param) -> (next)
372      Cat(rd, toB, false.B)  -> Branch,
373      Cat(rd, toB, true.B)   -> Branch,
374      Cat(rd, toT, false.B)  -> Trunk,
375      Cat(rd, toT, true.B)   -> Dirty,
376      Cat(wi, toT, false.B)  -> Trunk,
377      Cat(wi, toT, true.B)   -> Dirty,
378      Cat(wr, toT, false.B)  -> Dirty,
379      Cat(wr, toT, true.B)   -> Dirty))
380  }
381  val miss_new_coh = ClientMetadata(missCohGen(s3_req.cmd, s3_req.miss_param, s3_req.miss_dirty))
382
383  val new_coh = Mux(
384    miss_update_meta,
385    miss_new_coh,
386    Mux(
387      probe_update_meta,
388      probe_new_coh,
389      Mux(
390        store_update_meta || amo_update_meta,
391        s3_new_hit_coh,
392        ClientMetadata.onReset
393      )
394    )
395  )
396
397  // LR, SC and AMO
398  val debug_sc_fail_addr = RegInit(0.U)
399  val debug_sc_fail_cnt  = RegInit(0.U(8.W))
400
401  val lrsc_count = RegInit(0.U(log2Ceil(lrscCycles).W))
402  val lrsc_valid = lrsc_count > lrscBackoff.U
403  val lrsc_addr  = Reg(UInt())
404  val s3_lr = !s3_req.probe && s3_req.isAMO && s3_req.cmd === M_XLR
405  val s3_sc = !s3_req.probe && s3_req.isAMO && s3_req.cmd === M_XSC
406  val s3_lrsc_addr_match = lrsc_valid && lrsc_addr === get_block_addr(s3_req.addr)
407  val s3_sc_fail = s3_sc && !s3_lrsc_addr_match
408  val s3_sc_resp = Mux(s3_sc_fail, 1.U, 0.U)
409
410  val s3_can_do_amo = (s3_req.miss && !s3_req.probe && s3_req.source === AMO_SOURCE.U) || s3_amo_hit
411  val s3_can_do_amo_write = s3_can_do_amo && isWrite(s3_req.cmd) && !s3_sc_fail
412
413  when (s3_valid && (s3_lr || s3_sc)) {
414    when (s3_can_do_amo && s3_lr) {
415      lrsc_count := (lrscCycles - 1).U
416      lrsc_addr := get_block_addr(s3_req.addr)
417    } .otherwise {
418      lrsc_count := 0.U
419    }
420  } .elsewhen (lrsc_count > 0.U) {
421    lrsc_count := lrsc_count - 1.U
422  }
423
424  io.lrsc_locked_block.valid := lrsc_valid
425  io.lrsc_locked_block.bits  := lrsc_addr
426
427  // When we update update_resv_set, block all probe req in the next cycle
428  // It should give Probe reservation set addr compare an independent cycle,
429  // which will lead to better timing
430  io.update_resv_set := s3_valid && s3_lr && s3_can_do_amo
431
432  // when we release this block,
433  // we invalidate this reservation set
434  when (io.invalid_resv_set) {
435    lrsc_count := 0.U
436  }
437
438  when (s3_valid) {
439    when (s3_req.addr === debug_sc_fail_addr) {
440      when (s3_sc_fail) {
441        debug_sc_fail_cnt := debug_sc_fail_cnt + 1.U
442      } .elsewhen (s3_sc) {
443        debug_sc_fail_cnt := 0.U
444      }
445    } .otherwise {
446      when (s3_sc_fail) {
447        debug_sc_fail_addr := s3_req.addr
448        debug_sc_fail_cnt  := 1.U
449      }
450    }
451  }
452  assert(debug_sc_fail_cnt < 100.U, "L1DCache failed too many SCs in a row")
453
454
455  val banked_amo_wmask = UIntToOH(s3_req.word_idx)
456//  val banked_wmask = s3_banked_store_wmask
457  val banked_wmask = Mux(
458    s3_req.miss,
459    banked_full_wmask,
460    Mux(
461      s3_store_hit,
462      s3_banked_store_wmask,
463      Mux(
464        s3_can_do_amo_write,
465        banked_amo_wmask,
466        banked_none_wmask
467      )
468    )
469  )
470  val update_data = banked_wmask.asUInt.orR
471
472  // generate write data
473  // AMO hits
474  val s3_s_amoalu = RegInit(false.B)
475  val do_amoalu = amo_wait_amoalu && s3_valid && !s3_s_amoalu
476  val amoalu   = Module(new AMOALU(wordBits))
477  amoalu.io.mask := s3_req.amo_mask
478  amoalu.io.cmd  := s3_req.cmd
479  amoalu.io.lhs  := s3_data_word
480  amoalu.io.rhs  := s3_req.amo_data
481
482  // merge amo write data
483//  val amo_bitmask = FillInterleaved(8, s3_req.amo_mask)
484  val s3_amo_data_merged = Wire(Vec(DCacheBanks, UInt(DCacheSRAMRowBits.W)))
485  val s3_sc_data_merged = Wire(Vec(DCacheBanks, UInt(DCacheSRAMRowBits.W)))
486  for (i <- 0 until DCacheBanks) {
487    val old_data = s3_store_data_merged(i)
488    val new_data = amoalu.io.out
489    val wmask = Mux(
490      s3_req.word_idx === i.U,
491      ~0.U(wordBytes.W),
492      0.U(wordBytes.W)
493    )
494    s3_amo_data_merged(i) := mergePutData(old_data, new_data, wmask)
495//    s3_sc_data_merged(i) := amo_bitmask & s3_req.amo_data | ~amo_bitmask & old_data
496    s3_sc_data_merged(i) := mergePutData(old_data, s3_req.amo_data,
497      Mux(s3_req.word_idx === i.U && !s3_sc_fail, s3_req.amo_mask, 0.U(wordBytes.W))
498    )
499  }
500  val s3_amo_data_merged_reg = RegEnable(s3_amo_data_merged, do_amoalu)
501  when(do_amoalu){
502    s3_s_amoalu := true.B
503  }
504
505  val miss_wb = s3_req.miss && s3_need_replacement && s3_coh.state =/= ClientStates.Nothing
506  val probe_wb = s3_req.probe
507  val replace_wb = s3_req.replace
508  val need_wb = miss_wb || probe_wb || replace_wb
509
510  val (_, miss_shrink_param, _) = s3_coh.onCacheControl(M_FLUSH)
511  val writeback_param = Mux(probe_wb, probe_shrink_param, miss_shrink_param)
512  val writeback_data = if (dcacheParameters.alwaysReleaseData) {
513    s3_tag_match && s3_req.probe && s3_req.probe_need_data ||
514      s3_coh === ClientStates.Dirty || (miss_wb || replace_wb) && s3_coh.state =/= ClientStates.Nothing
515  } else {
516    s3_tag_match && s3_req.probe && s3_req.probe_need_data || s3_coh === ClientStates.Dirty
517  }
518
519  val s3_probe_can_go = s3_req.probe && io.wb.ready && (io.meta_write.ready || !probe_update_meta)
520  val s3_store_can_go = s3_req.isStore && !s3_req.probe && (io.meta_write.ready || !store_update_meta) && (io.data_write.ready || !update_data)
521  val s3_amo_can_go = s3_amo_hit && (io.meta_write.ready || !amo_update_meta) && (io.data_write.ready || !update_data) && (s3_s_amoalu || !amo_wait_amoalu)
522  val s3_miss_can_go = s3_req.miss &&
523    (io.meta_write.ready || !amo_update_meta) &&
524    (io.data_write.ready || !update_data) &&
525    (s3_s_amoalu || !amo_wait_amoalu) &&
526    io.tag_write.ready &&
527    io.wb.ready
528  val s3_replace_nothing = s3_req.replace && s3_coh.state === ClientStates.Nothing
529  val s3_replace_can_go = s3_req.replace && (s3_replace_nothing || io.wb.ready)
530  val s3_can_go = s3_probe_can_go || s3_store_can_go || s3_amo_can_go || s3_miss_can_go || s3_replace_can_go
531  val s3_fire = s3_valid && s3_can_go
532  when (s2_fire_to_s3) {
533    s3_valid := true.B
534  }.elsewhen (s3_fire) {
535    s3_valid := false.B
536  }
537  s3_ready := !s3_valid || s3_can_go
538  s3_s0_set_conflict := s3_valid && s3_idx === s0_idx
539  s3_s0_set_conflict_store := s3_valid && s3_idx === store_idx
540  assert(RegNext(!s3_valid || !(s3_req.isStore && !s3_req.probe) || s3_hit)) // miss store should never come to s3
541
542  when(s3_fire) {
543    s3_s_amoalu := false.B
544  }
545
546  req.ready := s0_can_go
547
548  io.meta_read.valid := req.valid && s1_ready && !set_conflict
549  io.meta_read.bits.idx := get_idx(s0_req.vaddr)
550  io.meta_read.bits.way_en := Mux(s0_req.replace, s0_req.replace_way_en, ~0.U(nWays.W))
551
552  io.tag_read.valid := req.valid && s1_ready && !set_conflict && !s0_req.replace
553  io.tag_read.bits.idx := get_idx(s0_req.vaddr)
554  io.tag_read.bits.way_en := ~0.U(nWays.W)
555
556  io.data_read.valid := s1_valid && s1_need_data && s2_ready
557  io.data_read.bits.rmask := s1_banked_rmask
558  io.data_read.bits.way_en := s1_way_en
559  io.data_read.bits.addr := s1_req.vaddr
560
561  io.miss_req.valid := s2_valid && s2_can_go_to_mq
562  val miss_req = io.miss_req.bits
563  miss_req := DontCare
564  miss_req.source := s2_req.source
565  miss_req.cmd := s2_req.cmd
566  miss_req.addr := s2_req.addr
567  miss_req.vaddr := s2_req.vaddr
568  miss_req.way_en := s2_way_en
569  miss_req.store_data := s2_req.store_data
570  miss_req.store_mask := s2_req.store_mask
571  miss_req.word_idx := s2_req.word_idx
572  miss_req.amo_data := s2_req.amo_data
573  miss_req.amo_mask := s2_req.amo_mask
574  miss_req.req_coh := s2_hit_coh
575  miss_req.replace_coh := s2_repl_coh
576  miss_req.replace_tag := s2_repl_tag
577  miss_req.id := s2_req.id
578  miss_req.cancel := false.B
579
580  io.store_replay_resp.valid := s2_valid && s2_can_go_to_mq && replay && s2_req.isStore
581  io.store_replay_resp.bits.data := DontCare
582  io.store_replay_resp.bits.miss := true.B
583  io.store_replay_resp.bits.replay := true.B
584  io.store_replay_resp.bits.id := s2_req.id
585
586  io.store_hit_resp.valid := s3_valid && s3_store_can_go
587  io.store_hit_resp.bits.data := DontCare
588  io.store_hit_resp.bits.miss := false.B
589  io.store_hit_resp.bits.replay := false.B
590  io.store_hit_resp.bits.id := s3_req.id
591
592  io.release_update.valid := s3_valid && (s3_store_can_go || s3_amo_can_go) && s3_hit && update_data
593  io.release_update.bits.addr := s3_req.addr
594  io.release_update.bits.mask := Mux(s3_store_hit, s3_banked_store_wmask, banked_amo_wmask)
595  io.release_update.bits.data := Mux(
596    amo_wait_amoalu,
597    s3_amo_data_merged_reg,
598    Mux(
599      s3_sc,
600      s3_sc_data_merged,
601      s3_store_data_merged
602    )
603  ).asUInt
604
605  val atomic_hit_resp = Wire(new AtomicsResp)
606  atomic_hit_resp.data := Mux(s3_sc, s3_sc_resp, s3_data_word)
607  atomic_hit_resp.miss := false.B
608  atomic_hit_resp.miss_id := s3_req.miss_id
609  atomic_hit_resp.replay := false.B
610  atomic_hit_resp.ack_miss_queue := s3_req.miss
611  atomic_hit_resp.id := lrsc_valid
612  val atomic_replay_resp = Wire(new AtomicsResp)
613  atomic_replay_resp.data := DontCare
614  atomic_replay_resp.miss := true.B
615  atomic_replay_resp.miss_id := DontCare
616  atomic_replay_resp.replay := true.B
617  atomic_replay_resp.ack_miss_queue := false.B
618  atomic_replay_resp.id := DontCare
619  val atomic_replay_resp_valid = s2_valid && s2_can_go_to_mq && replay && s2_req.isAMO
620  val atomic_hit_resp_valid = s3_valid && (s3_amo_can_go || s3_miss_can_go && s3_req.isAMO)
621  io.atomic_resp.valid := atomic_replay_resp_valid || atomic_hit_resp_valid
622  io.atomic_resp.bits := Mux(atomic_replay_resp_valid, atomic_replay_resp, atomic_hit_resp)
623
624  io.replace_resp.valid := s3_fire && s3_req.replace
625  io.replace_resp.bits := s3_req.miss_id
626
627  io.meta_write.valid := s3_fire && update_meta
628  io.meta_write.bits.idx := s3_idx
629  io.meta_write.bits.way_en := s3_way_en
630  io.meta_write.bits.tag := get_tag(s3_req.addr)
631  io.meta_write.bits.meta.coh := new_coh
632
633  io.tag_write.valid := s3_fire && s3_req.miss
634  io.tag_write.bits.idx := s3_idx
635  io.tag_write.bits.way_en := s3_way_en
636  io.tag_write.bits.tag := get_tag(s3_req.addr)
637
638  io.data_write.valid := s3_fire && update_data
639  io.data_write.bits.way_en := s3_way_en
640  io.data_write.bits.addr := s3_req.vaddr
641  io.data_write.bits.wmask := banked_wmask
642  io.data_write.bits.data := Mux(
643    amo_wait_amoalu,
644    s3_amo_data_merged_reg,
645    Mux(
646      s3_sc,
647      s3_sc_data_merged,
648      s3_store_data_merged
649    )
650  )
651  assert(RegNext(!io.meta_write.valid || !s3_req.replace))
652  assert(RegNext(!io.tag_write.valid || !s3_req.replace))
653  assert(RegNext(!io.data_write.valid || !s3_req.replace))
654
655  io.wb.valid := s3_valid && (
656    // replace
657    s3_req.replace && !s3_replace_nothing ||
658    // probe can go to wbq
659    s3_req.probe && (io.meta_write.ready || !probe_update_meta) ||
660      // amo miss can go to wbq
661      s3_req.miss &&
662        (io.meta_write.ready || !amo_update_meta) &&
663        (io.data_write.ready || !update_data) &&
664        (s3_s_amoalu || !amo_wait_amoalu) &&
665        io.tag_write.ready
666    ) && need_wb
667  io.wb.bits.addr := get_block_addr(Cat(s3_tag, get_untag(s3_req.vaddr)))
668  io.wb.bits.param := writeback_param
669  io.wb.bits.voluntary := s3_req.miss || s3_req.replace
670  io.wb.bits.hasData := writeback_data
671  io.wb.bits.dirty := s3_coh === ClientStates.Dirty
672  io.wb.bits.data := s3_data.asUInt()
673  io.wb.bits.delay_release := s3_req.replace
674  io.wb.bits.miss_id := s3_req.miss_id
675
676  io.replace_access.valid := RegNext(s1_fire && (s1_req.isAMO || s1_req.isStore) && !s1_req.probe && s1_tag_match)
677  io.replace_access.bits.set := s2_idx
678  io.replace_access.bits.way := RegNext(OHToUInt(s1_way_en))
679
680  io.replace_way.set.valid := RegNext(s0_fire)
681  io.replace_way.set.bits := s1_idx
682
683  // TODO: consider block policy of a finer granularity
684  io.status.s0_set.valid := req.valid
685  io.status.s0_set.bits := get_idx(s0_req.vaddr)
686  io.status.s1.valid := s1_valid
687  io.status.s1.bits.set := s1_idx
688  io.status.s1.bits.way_en := s1_way_en
689  io.status.s2.valid := s2_valid && !s2_req.replace
690  io.status.s2.bits.set := s2_idx
691  io.status.s2.bits.way_en := s2_way_en
692  io.status.s3.valid := s3_valid && !s3_req.replace
693  io.status.s3.bits.set := s3_idx
694  io.status.s3.bits.way_en := s3_way_en
695
696  io.error.ecc_error.valid := RegNext(s1_fire && s1_hit && !s1_req.replace) &&
697    RegNext(dcacheParameters.dataCode.decode(s1_eccMetaAndTag).error)
698  io.error.ecc_error.bits := true.B
699  io.error.paddr.valid := io.error.ecc_error.valid
700  io.error.paddr.bits := s2_req.addr
701
702  val perfEvents = Seq(
703    ("dcache_mp_req          ", s0_fire                                                      ),
704    ("dcache_mp_total_penalty", PopCount(VecInit(Seq(s0_fire, s1_valid, s2_valid, s3_valid))))
705  )
706  generatePerfEvent()
707}
708