xref: /XiangShan/src/main/scala/device/AXI4Timer.scala (revision c6d439803a044ea209139672b25e35fe8d7f4aa0)
1/***************************************************************************************
2* Copyright (c) 2020-2021 Institute of Computing Technology, Chinese Academy of Sciences
3*
4* XiangShan is licensed under Mulan PSL v2.
5* You can use this software according to the terms and conditions of the Mulan PSL v2.
6* You may obtain a copy of Mulan PSL v2 at:
7*          http://license.coscl.org.cn/MulanPSL2
8*
9* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
10* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
11* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
12*
13* See the Mulan PSL v2 for more details.
14***************************************************************************************/
15
16package device
17
18import chisel3._
19import chipsalliance.rocketchip.config.Parameters
20import freechips.rocketchip.diplomacy.AddressSet
21import utils._
22
23class TimerIO extends Bundle {
24  val mtip = Output(Bool())
25}
26
27class AXI4Timer
28(
29  sim: Boolean = false,
30  address: Seq[AddressSet]
31)(implicit p: Parameters)
32  extends AXI4SlaveModule(address, executable = false, _extra = new TimerIO)
33{
34  override lazy val module = new AXI4SlaveModuleImp[TimerIO](this){
35    val mtime = RegInit(0.U(64.W))  // unit: us
36    val mtimecmp = RegInit(0.U(64.W))
37
38    val clk = (if (!sim) 40 /* 40MHz / 1000000 */ else 10000)
39    val freq = RegInit(clk.U(16.W))
40    val inc = RegInit(1000.U(16.W))
41
42    val cnt = RegInit(0.U(16.W))
43    val nextCnt = cnt + 1.U
44    cnt := Mux(nextCnt < freq, nextCnt, 0.U)
45    val tick = (nextCnt === freq)
46    when (tick) { mtime := mtime + inc }
47
48    val mapping = Map(
49      RegMap(0x4000, mtimecmp),
50      RegMap(0x8000, freq),
51      RegMap(0x8008, inc),
52      RegMap(0xbff8, mtime)
53    )
54    def getOffset(addr: UInt) = addr(15,0)
55
56    RegMap.generate(mapping, getOffset(raddr), in.r.bits.data,
57      getOffset(waddr), in.w.fire(), in.w.bits.data, MaskExpand(in.w.bits.strb))
58
59    io.extra.get.mtip := RegNext(mtime >= mtimecmp)
60  }
61}
62