1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * Copyright (C) 2017-2022 Weidm��ller Interface GmbH & Co. KG
4 * Stefan Herbrechtsmeier <stefan.herbrechtsmeier@weidmueller.com>
5 *
6 * Copyright (C) 2012 Michal Simek <monstr@monstr.eu>
7 * Copyright (C) 2011-2017 Xilinx, Inc. All rights reserved.
8 *
9 * (C) Copyright 2008
10 * Guennadi Liakhovetki, DENX Software Engineering, <lg@denx.de>
11 *
12 * (C) Copyright 2004
13 * Philippe Robin, ARM Ltd. <philippe.robin@arm.com>
14 *
15 * (C) Copyright 2002-2004
16 * Gary Jennejohn, DENX Software Engineering, <gj@denx.de>
17 *
18 * (C) Copyright 2003
19 * Texas Instruments <www.ti.com>
20 *
21 * (C) Copyright 2002
22 * Sysgo Real-Time Solutions, GmbH <www.elinos.com>
23 * Marius Groeger <mgroeger@sysgo.de>
24 *
25 * (C) Copyright 2002
26 * Sysgo Real-Time Solutions, GmbH <www.elinos.com>
27 * Alex Zuepke <azu@sysgo.de>
28 */
29
30#include <dm.h>
31#include <fdtdec.h>
32#include <timer.h>
33#include <linux/bitops.h>
34
35#include <asm/io.h>
36
37#define SCUTIMER_CONTROL_PRESCALER_MASK		0x0000FF00 /* Prescaler */
38#define SCUTIMER_CONTROL_AUTO_RELOAD_MASK	0x00000002 /* Auto-reload */
39#define SCUTIMER_CONTROL_ENABLE_MASK		0x00000001 /* Timer enable */
40
41#define TIMER_LOAD_VAL 0xFFFFFFFF
42
43struct arm_twd_timer_regs {
44	u32 load; /* Timer Load Register */
45	u32 counter; /* Timer Counter Register */
46	u32 control; /* Timer Control Register */
47};
48
49struct arm_twd_timer_priv {
50	struct arm_twd_timer_regs *base;
51};
52
53static u64 arm_twd_timer_get_count(struct udevice *dev)
54{
55	struct arm_twd_timer_priv *priv = dev_get_priv(dev);
56	struct arm_twd_timer_regs *regs = priv->base;
57	u32 count = TIMER_LOAD_VAL - readl(&regs->counter);
58
59	return timer_conv_64(count);
60}
61
62static int arm_twd_timer_probe(struct udevice *dev)
63{
64	struct arm_twd_timer_priv *priv = dev_get_priv(dev);
65	struct arm_twd_timer_regs *regs;
66	fdt_addr_t addr;
67
68	addr = dev_read_addr(dev);
69	if (addr == FDT_ADDR_T_NONE)
70		return -EINVAL;
71
72	priv->base = (struct arm_twd_timer_regs *)addr;
73
74	regs = priv->base;
75
76	/* Load the timer counter register */
77	writel(0xFFFFFFFF, &regs->load);
78
79	/*
80	 * Start the A9Timer device
81	 * Enable Auto reload mode, Clear prescaler control bits
82	 * Set prescaler value, Enable the decrementer
83	 */
84	clrsetbits_le32(&regs->control, SCUTIMER_CONTROL_PRESCALER_MASK,
85			SCUTIMER_CONTROL_AUTO_RELOAD_MASK |
86			SCUTIMER_CONTROL_ENABLE_MASK);
87
88	return 0;
89}
90
91static const struct timer_ops arm_twd_timer_ops = {
92	.get_count = arm_twd_timer_get_count,
93};
94
95static const struct udevice_id arm_twd_timer_ids[] = {
96	{ .compatible = "arm,cortex-a9-twd-timer" },
97	{}
98};
99
100U_BOOT_DRIVER(arm_twd_timer) = {
101	.name = "arm_twd_timer",
102	.id = UCLASS_TIMER,
103	.of_match = arm_twd_timer_ids,
104	.priv_auto	= sizeof(struct arm_twd_timer_priv),
105	.probe = arm_twd_timer_probe,
106	.ops = &arm_twd_timer_ops,
107};
108