1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * MediaTek timer driver
4 *
5 * Copyright (C) 2018 MediaTek Inc.
6 * Author: Ryder Lee <ryder.lee@mediatek.com>
7 */
8
9 #include <clk.h>
10 #include <common.h>
11 #include <dm.h>
12 #include <timer.h>
13 #include <asm/io.h>
14 #include <linux/bitops.h>
15
16 #define MTK_GPT4_CTRL 0x40
17 #define MTK_GPT4_CLK 0x44
18 #define MTK_GPT4_CNT 0x48
19
20 #define GPT4_ENABLE BIT(0)
21 #define GPT4_CLEAR BIT(1)
22 #define GPT4_FREERUN GENMASK(5, 4)
23 #define GPT4_CLK_SYS 0x0
24 #define GPT4_CLK_DIV1 0x0
25
26 struct mtk_timer_priv {
27 void __iomem *base;
28 };
29
mtk_timer_get_count(struct udevice * dev)30 static u64 mtk_timer_get_count(struct udevice *dev)
31 {
32 struct mtk_timer_priv *priv = dev_get_priv(dev);
33 u32 val = readl(priv->base + MTK_GPT4_CNT);
34
35 return timer_conv_64(val);
36 }
37
mtk_timer_probe(struct udevice * dev)38 static int mtk_timer_probe(struct udevice *dev)
39 {
40 struct timer_dev_priv *uc_priv = dev_get_uclass_priv(dev);
41 struct mtk_timer_priv *priv = dev_get_priv(dev);
42 struct clk clk, parent;
43 int ret;
44
45 priv->base = dev_read_addr_ptr(dev);
46 if (!priv->base)
47 return -ENOENT;
48
49 ret = clk_get_by_index(dev, 0, &clk);
50 if (ret)
51 return ret;
52
53 ret = clk_get_by_index(dev, 1, &parent);
54 if (!ret) {
55 ret = clk_set_parent(&clk, &parent);
56 if (ret)
57 return ret;
58 }
59
60 uc_priv->clock_rate = clk_get_rate(&clk);
61 if (!uc_priv->clock_rate)
62 return -EINVAL;
63
64 /*
65 * Initialize the timer:
66 * 1. set clock source to system clock with clock divider setting to 1
67 * 2. set timer mode to free running
68 * 3. reset timer counter to 0 then enable the timer
69 */
70 writel(GPT4_CLK_SYS | GPT4_CLK_DIV1, priv->base + MTK_GPT4_CLK);
71 writel(GPT4_FREERUN | GPT4_CLEAR | GPT4_ENABLE,
72 priv->base + MTK_GPT4_CTRL);
73
74 return 0;
75 }
76
77 static const struct timer_ops mtk_timer_ops = {
78 .get_count = mtk_timer_get_count,
79 };
80
81 static const struct udevice_id mtk_timer_ids[] = {
82 { .compatible = "mediatek,timer" },
83 { .compatible = "mediatek,mt6577-timer" },
84 { }
85 };
86
87 U_BOOT_DRIVER(mtk_timer) = {
88 .name = "mtk_timer",
89 .id = UCLASS_TIMER,
90 .of_match = mtk_timer_ids,
91 .priv_auto = sizeof(struct mtk_timer_priv),
92 .probe = mtk_timer_probe,
93 .ops = &mtk_timer_ops,
94 .flags = DM_FLAG_PRE_RELOC,
95 };
96