1/*-
2 * Copyright (c) 2015-2017 Ruslan Bukin <br@bsdpad.com>
3 * All rights reserved.
4 *
5 * Portions of this software were developed by SRI International and the
6 * University of Cambridge Computer Laboratory under DARPA/AFRL contract
7 * FA8750-10-C-0237 ("CTSRD"), as part of the DARPA CRASH research programme.
8 *
9 * Portions of this software were developed by the University of Cambridge
10 * Computer Laboratory as part of the CTSRD Project, with support from the
11 * UK Higher Education Innovation Fund (HEIF).
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 *    notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 *    notice, this list of conditions and the following disclaimer in the
20 *    documentation and/or other materials provided with the distribution.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35/*
36 * RISC-V Timer
37 */
38
39#include "opt_platform.h"
40
41#include <sys/cdefs.h>
42__FBSDID("$FreeBSD$");
43
44#include <sys/param.h>
45#include <sys/systm.h>
46#include <sys/bus.h>
47#include <sys/kernel.h>
48#include <sys/module.h>
49#include <sys/malloc.h>
50#include <sys/rman.h>
51#include <sys/timeet.h>
52#include <sys/timetc.h>
53#include <sys/watchdog.h>
54
55#include <sys/proc.h>
56
57#include <machine/bus.h>
58#include <machine/cpu.h>
59#include <machine/intr.h>
60#include <machine/asm.h>
61#include <machine/trap.h>
62#include <machine/sbi.h>
63
64#include <dev/fdt/fdt_common.h>
65#include <dev/ofw/ofw_bus.h>
66#include <dev/ofw/ofw_bus_subr.h>
67#include <dev/ofw/openfirm.h>
68
69#define	TIMER_COUNTS		0x00
70#define	TIMER_MTIMECMP(cpu)	(cpu * 8)
71
72struct riscv_timer_softc {
73	void			*ih;
74	uint32_t		clkfreq;
75	struct eventtimer	et;
76};
77
78static struct riscv_timer_softc *riscv_timer_sc = NULL;
79
80static timecounter_get_t riscv_timer_get_timecount;
81
82static struct timecounter riscv_timer_timecount = {
83	.tc_name           = "RISC-V Timecounter",
84	.tc_get_timecount  = riscv_timer_get_timecount,
85	.tc_poll_pps       = NULL,
86	.tc_counter_mask   = ~0u,
87	.tc_frequency      = 0,
88	.tc_quality        = 1000,
89};
90
91static inline uint64_t
92get_cycles(void)
93{
94	uint64_t cycles;
95
96	__asm __volatile("rdtime %0" : "=r" (cycles));
97
98	return (cycles);
99}
100
101static long
102get_counts(struct riscv_timer_softc *sc)
103{
104	uint64_t counts;
105
106	counts = get_cycles();
107
108	return (counts);
109}
110
111static unsigned
112riscv_timer_get_timecount(struct timecounter *tc)
113{
114	struct riscv_timer_softc *sc;
115
116	sc = tc->tc_priv;
117
118	return (get_counts(sc));
119}
120
121static int
122riscv_timer_start(struct eventtimer *et, sbintime_t first, sbintime_t period)
123{
124	uint64_t counts;
125
126	if (first != 0) {
127		counts = ((uint32_t)et->et_frequency * first) >> 32;
128		sbi_set_timer(get_cycles() + counts);
129		csr_set(sie, SIE_STIE);
130
131		return (0);
132	}
133
134	return (EINVAL);
135
136}
137
138static int
139riscv_timer_stop(struct eventtimer *et)
140{
141
142	/* TODO */
143
144	return (0);
145}
146
147static int
148riscv_timer_intr(void *arg)
149{
150	struct riscv_timer_softc *sc;
151
152	sc = (struct riscv_timer_softc *)arg;
153
154	csr_clear(sip, SIP_STIP);
155
156	if (sc->et.et_active)
157		sc->et.et_event_cb(&sc->et, sc->et.et_arg);
158
159	return (FILTER_HANDLED);
160}
161
162static int
163riscv_timer_get_timebase(device_t dev, uint32_t *freq)
164{
165	phandle_t node;
166	int len;
167
168	node = OF_finddevice("/cpus");
169	if (node == -1) {
170		if (bootverbose)
171			device_printf(dev, "Can't find cpus node.\n");
172		return (ENXIO);
173	}
174
175	len = OF_getproplen(node, "timebase-frequency");
176	if (len != 4) {
177		if (bootverbose)
178			device_printf(dev,
179			    "Can't find timebase-frequency property.\n");
180		return (ENXIO);
181	}
182
183	OF_getencprop(node, "timebase-frequency", freq, len);
184
185	return (0);
186}
187
188static int
189riscv_timer_probe(device_t dev)
190{
191
192	device_set_desc(dev, "RISC-V Timer");
193
194	return (BUS_PROBE_DEFAULT);
195}
196
197static int
198riscv_timer_attach(device_t dev)
199{
200	struct riscv_timer_softc *sc;
201	int error;
202
203	sc = device_get_softc(dev);
204	if (riscv_timer_sc)
205		return (ENXIO);
206
207	if (device_get_unit(dev) != 0)
208		return (ENXIO);
209
210	if (riscv_timer_get_timebase(dev, &sc->clkfreq) != 0) {
211		device_printf(dev, "No clock frequency specified\n");
212		return (ENXIO);
213	}
214
215	riscv_timer_sc = sc;
216
217	/* Setup IRQs handler */
218	error = riscv_setup_intr(device_get_nameunit(dev), riscv_timer_intr,
219	    NULL, sc, IRQ_TIMER_SUPERVISOR, INTR_TYPE_CLK, &sc->ih);
220	if (error) {
221		device_printf(dev, "Unable to alloc int resource.\n");
222		return (ENXIO);
223	}
224
225	riscv_timer_timecount.tc_frequency = sc->clkfreq;
226	riscv_timer_timecount.tc_priv = sc;
227	tc_init(&riscv_timer_timecount);
228
229	sc->et.et_name = "RISC-V Eventtimer";
230	sc->et.et_flags = ET_FLAGS_ONESHOT | ET_FLAGS_PERCPU;
231	sc->et.et_quality = 1000;
232
233	sc->et.et_frequency = sc->clkfreq;
234	sc->et.et_min_period = (0x00000002LLU << 32) / sc->et.et_frequency;
235	sc->et.et_max_period = (0xfffffffeLLU << 32) / sc->et.et_frequency;
236	sc->et.et_start = riscv_timer_start;
237	sc->et.et_stop = riscv_timer_stop;
238	sc->et.et_priv = sc;
239	et_register(&sc->et);
240
241	return (0);
242}
243
244static device_method_t riscv_timer_methods[] = {
245	DEVMETHOD(device_probe,		riscv_timer_probe),
246	DEVMETHOD(device_attach,	riscv_timer_attach),
247	{ 0, 0 }
248};
249
250static driver_t riscv_timer_driver = {
251	"timer",
252	riscv_timer_methods,
253	sizeof(struct riscv_timer_softc),
254};
255
256static devclass_t riscv_timer_devclass;
257
258EARLY_DRIVER_MODULE(timer, nexus, riscv_timer_driver, riscv_timer_devclass,
259    0, 0, BUS_PASS_TIMER + BUS_PASS_ORDER_MIDDLE);
260
261void
262DELAY(int usec)
263{
264	int64_t counts, counts_per_usec;
265	uint64_t first, last;
266
267	/*
268	 * Check the timers are setup, if not just
269	 * use a for loop for the meantime
270	 */
271	if (riscv_timer_sc == NULL) {
272		for (; usec > 0; usec--)
273			for (counts = 200; counts > 0; counts--)
274				/*
275				 * Prevent the compiler from optimizing
276				 * out the loop
277				 */
278				cpufunc_nullop();
279		return;
280	}
281	TSENTER();
282
283	/* Get the number of times to count */
284	counts_per_usec = ((riscv_timer_timecount.tc_frequency / 1000000) + 1);
285
286	/*
287	 * Clamp the timeout at a maximum value (about 32 seconds with
288	 * a 66MHz clock). *Nobody* should be delay()ing for anywhere
289	 * near that length of time and if they are, they should be hung
290	 * out to dry.
291	 */
292	if (usec >= (0x80000000U / counts_per_usec))
293		counts = (0x80000000U / counts_per_usec) - 1;
294	else
295		counts = usec * counts_per_usec;
296
297	first = get_counts(riscv_timer_sc);
298
299	while (counts > 0) {
300		last = get_counts(riscv_timer_sc);
301		counts -= (int64_t)(last - first);
302		first = last;
303	}
304	TSEXIT();
305}
306