1/*-
2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3 *
4 * Copyright (c) 2012, 2013 The FreeBSD Foundation
5 * All rights reserved.
6 *
7 * This software was developed by Oleksandr Rybalko under sponsorship
8 * from the FreeBSD Foundation.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1.	Redistributions of source code must retain the above copyright
14 *	notice, this list of conditions and the following disclaimer.
15 * 2.	Redistributions in binary form must reproduce the above copyright
16 *	notice, this list of conditions and the following disclaimer in the
17 *	documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32#include <sys/cdefs.h>
33__FBSDID("$FreeBSD$");
34
35#include <sys/param.h>
36#include <sys/systm.h>
37#include <sys/bus.h>
38#include <sys/kernel.h>
39#include <sys/module.h>
40#include <sys/rman.h>
41#include <sys/timeet.h>
42#include <sys/timetc.h>
43#include <machine/bus.h>
44#include <machine/intr.h>
45#include <machine/machdep.h> /* For arm_set_delay */
46
47#include <dev/ofw/openfirm.h>
48#include <dev/ofw/ofw_bus.h>
49#include <dev/ofw/ofw_bus_subr.h>
50
51#include <arm/freescale/imx/imx_ccmvar.h>
52#include <arm/freescale/imx/imx_gptreg.h>
53
54#define	WRITE4(_sc, _r, _v)						\
55	    bus_space_write_4((_sc)->sc_iot, (_sc)->sc_ioh, (_r), (_v))
56#define	READ4(_sc, _r)							\
57	    bus_space_read_4((_sc)->sc_iot, (_sc)->sc_ioh, (_r))
58#define	SET4(_sc, _r, _m)						\
59	    WRITE4((_sc), (_r), READ4((_sc), (_r)) | (_m))
60#define	CLEAR4(_sc, _r, _m)						\
61	    WRITE4((_sc), (_r), READ4((_sc), (_r)) & ~(_m))
62
63static u_int	imx_gpt_get_timecount(struct timecounter *);
64static int	imx_gpt_timer_start(struct eventtimer *, sbintime_t,
65    sbintime_t);
66static int	imx_gpt_timer_stop(struct eventtimer *);
67
68static void imx_gpt_do_delay(int, void *);
69
70static int imx_gpt_intr(void *);
71static int imx_gpt_probe(device_t);
72static int imx_gpt_attach(device_t);
73
74static struct timecounter imx_gpt_timecounter = {
75	.tc_name           = "iMXGPT",
76	.tc_get_timecount  = imx_gpt_get_timecount,
77	.tc_counter_mask   = ~0u,
78	.tc_frequency      = 0,
79	.tc_quality        = 1000,
80};
81
82struct imx_gpt_softc {
83	device_t 		sc_dev;
84	struct resource *	res[2];
85	bus_space_tag_t 	sc_iot;
86	bus_space_handle_t	sc_ioh;
87	void *			sc_ih;			/* interrupt handler */
88	uint32_t 		sc_period;
89	uint32_t 		sc_clksrc;
90	uint32_t 		clkfreq;
91	uint32_t		ir_reg;
92	struct eventtimer 	et;
93};
94
95/* Try to divide down an available fast clock to this frequency. */
96#define	TARGET_FREQUENCY	1000000000
97
98static struct resource_spec imx_gpt_spec[] = {
99	{ SYS_RES_MEMORY,	0,	RF_ACTIVE },
100	{ SYS_RES_IRQ,		0,	RF_ACTIVE },
101	{ -1, 0 }
102};
103
104static struct ofw_compat_data compat_data[] = {
105	{"fsl,imx6dl-gpt", 1},
106	{"fsl,imx6q-gpt",  1},
107	{"fsl,imx6ul-gpt", 1},
108	{"fsl,imx53-gpt",  1},
109	{"fsl,imx51-gpt",  1},
110	{"fsl,imx31-gpt",  1},
111	{"fsl,imx27-gpt",  1},
112	{"fsl,imx25-gpt",  1},
113	{NULL,             0}
114};
115
116static int
117imx_gpt_probe(device_t dev)
118{
119
120	if (!ofw_bus_status_okay(dev))
121		return (ENXIO);
122
123	/*
124	 *  We only support a single unit, because the only thing this driver
125	 *  does with the complex timer hardware is supply the system
126	 *  timecounter and eventtimer.  There is nothing useful we can do with
127	 *  the additional device instances that exist in some chips.
128	 */
129	if (device_get_unit(dev) > 0)
130		return (ENXIO);
131
132	if (ofw_bus_search_compatible(dev, compat_data)->ocd_data != 0) {
133		device_set_desc(dev, "Freescale i.MX GPT timer");
134		return (BUS_PROBE_DEFAULT);
135	}
136
137	return (ENXIO);
138}
139
140static int
141imx_gpt_attach(device_t dev)
142{
143	struct imx_gpt_softc *sc;
144	int ctlreg, err;
145	uint32_t basefreq, prescale, setup_ticks, t1, t2;
146
147	sc = device_get_softc(dev);
148
149	if (bus_alloc_resources(dev, imx_gpt_spec, sc->res)) {
150		device_printf(dev, "could not allocate resources\n");
151		return (ENXIO);
152	}
153
154	sc->sc_dev = dev;
155	sc->sc_iot = rman_get_bustag(sc->res[0]);
156	sc->sc_ioh = rman_get_bushandle(sc->res[0]);
157
158	/*
159	 * For now, just automatically choose a good clock for the hardware
160	 * we're running on.  Eventually we could allow selection from the fdt;
161	 * the code in this driver will cope with any clock frequency.
162	 */
163	sc->sc_clksrc = GPT_CR_CLKSRC_IPG;
164
165	ctlreg = 0;
166
167	switch (sc->sc_clksrc) {
168	case GPT_CR_CLKSRC_32K:
169		basefreq = 32768;
170		break;
171	case GPT_CR_CLKSRC_IPG:
172		basefreq = imx_ccm_ipg_hz();
173		break;
174	case GPT_CR_CLKSRC_IPG_HIGH:
175		basefreq = imx_ccm_ipg_hz() * 2;
176		break;
177	case GPT_CR_CLKSRC_24M:
178		ctlreg |= GPT_CR_24MEN;
179		basefreq = 24000000;
180		break;
181	case GPT_CR_CLKSRC_NONE:/* Can't run without a clock. */
182	case GPT_CR_CLKSRC_EXT:	/* No way to get the freq of an ext clock. */
183	default:
184		device_printf(dev, "Unsupported clock source '%d'\n",
185		    sc->sc_clksrc);
186		return (EINVAL);
187	}
188
189	/*
190	 * The following setup sequence is from the I.MX6 reference manual,
191	 * "Selecting the clock source".  First, disable the clock and
192	 * interrupts.  This also clears input and output mode bits and in
193	 * general completes several of the early steps in the procedure.
194	 */
195	WRITE4(sc, IMX_GPT_CR, 0);
196	WRITE4(sc, IMX_GPT_IR, 0);
197
198	/* Choose the clock and the power-saving behaviors. */
199	ctlreg |=
200	    sc->sc_clksrc |	/* Use selected clock */
201	    GPT_CR_FRR |	/* Just count (FreeRunner mode) */
202	    GPT_CR_STOPEN |	/* Run in STOP mode */
203	    GPT_CR_DOZEEN |	/* Run in DOZE mode */
204	    GPT_CR_WAITEN |	/* Run in WAIT mode */
205	    GPT_CR_DBGEN;	/* Run in DEBUG mode */
206	WRITE4(sc, IMX_GPT_CR, ctlreg);
207
208	/*
209	 * The datasheet says to do the software reset after choosing the clock
210	 * source.  It says nothing about needing to wait for the reset to
211	 * complete, but the register description does document the fact that
212	 * the reset isn't complete until the SWR bit reads 0, so let's be safe.
213	 * The reset also clears all registers except for a few of the bits in
214	 * CR, but we'll rewrite all the CR bits when we start the counter.
215	 */
216	WRITE4(sc, IMX_GPT_CR, ctlreg | GPT_CR_SWR);
217	while (READ4(sc, IMX_GPT_CR) & GPT_CR_SWR)
218		continue;
219
220	/* Set a prescaler value that gets us near the target frequency. */
221	if (basefreq < TARGET_FREQUENCY) {
222		prescale = 0;
223		sc->clkfreq = basefreq;
224	} else {
225		prescale = basefreq / TARGET_FREQUENCY;
226		sc->clkfreq = basefreq / prescale;
227		prescale -= 1; /* 1..n range is 0..n-1 in hardware. */
228	}
229	WRITE4(sc, IMX_GPT_PR, prescale);
230
231	/* Clear the status register. */
232	WRITE4(sc, IMX_GPT_SR, GPT_IR_ALL);
233
234	/* Start the counter. */
235	WRITE4(sc, IMX_GPT_CR, ctlreg | GPT_CR_EN);
236
237	if (bootverbose)
238		device_printf(dev, "Running on %dKHz clock, base freq %uHz CR=0x%08x, PR=0x%08x\n",
239		    sc->clkfreq / 1000, basefreq, READ4(sc, IMX_GPT_CR), READ4(sc, IMX_GPT_PR));
240
241	/* Setup the timer interrupt. */
242	err = bus_setup_intr(dev, sc->res[1], INTR_TYPE_CLK, imx_gpt_intr,
243	    NULL, sc, &sc->sc_ih);
244	if (err != 0) {
245		bus_release_resources(dev, imx_gpt_spec, sc->res);
246		device_printf(dev, "Unable to setup the clock irq handler, "
247		    "err = %d\n", err);
248		return (ENXIO);
249	}
250
251	/*
252	 * Measure how many clock ticks it takes to setup a one-shot event (it's
253	 * longer than you might think, due to wait states in accessing gpt
254	 * registers).  Scale up the result by a factor of 1.5 to be safe,
255	 * and use that to set the minimum eventtimer period we can schedule. In
256	 * the real world, the value works out to about 750ns on imx5 hardware.
257	 */
258	t1 = READ4(sc, IMX_GPT_CNT);
259	WRITE4(sc, IMX_GPT_OCR3, 0);
260	t2 = READ4(sc, IMX_GPT_CNT);
261	setup_ticks = ((t2 - t1 + 1) * 3) / 2;
262
263	/* Register as an eventtimer. */
264	sc->et.et_name = "iMXGPT";
265	sc->et.et_flags = ET_FLAGS_ONESHOT | ET_FLAGS_PERIODIC;
266	sc->et.et_quality = 800;
267	sc->et.et_frequency = sc->clkfreq;
268	sc->et.et_min_period = ((uint64_t)setup_ticks << 32) / sc->clkfreq;
269	sc->et.et_max_period = ((uint64_t)0xfffffffe  << 32) / sc->clkfreq;
270	sc->et.et_start = imx_gpt_timer_start;
271	sc->et.et_stop = imx_gpt_timer_stop;
272	sc->et.et_priv = sc;
273	et_register(&sc->et);
274
275	/* Register as a timecounter. */
276	imx_gpt_timecounter.tc_frequency = sc->clkfreq;
277	imx_gpt_timecounter.tc_priv = sc;
278	tc_init(&imx_gpt_timecounter);
279
280	/* If this is the first unit, store the softc for use in DELAY. */
281	if (device_get_unit(dev) == 0) {
282		arm_set_delay(imx_gpt_do_delay, sc);
283	}
284
285	return (0);
286}
287
288static int
289imx_gpt_timer_start(struct eventtimer *et, sbintime_t first, sbintime_t period)
290{
291	struct imx_gpt_softc *sc;
292	uint32_t ticks;
293
294	sc = (struct imx_gpt_softc *)et->et_priv;
295
296	if (period != 0) {
297		sc->sc_period = ((uint32_t)et->et_frequency * period) >> 32;
298		/* Set expected value */
299		WRITE4(sc, IMX_GPT_OCR2, READ4(sc, IMX_GPT_CNT) + sc->sc_period);
300		/* Enable compare register 2 Interrupt */
301		sc->ir_reg |= GPT_IR_OF2;
302		WRITE4(sc, IMX_GPT_IR, sc->ir_reg);
303		return (0);
304	} else if (first != 0) {
305		/* Enable compare register 3 interrupt if not already on. */
306		if ((sc->ir_reg & GPT_IR_OF3) == 0) {
307			sc->ir_reg |= GPT_IR_OF3;
308			WRITE4(sc, IMX_GPT_IR, sc->ir_reg);
309		}
310		ticks = ((uint32_t)et->et_frequency * first) >> 32;
311		/* Do not disturb, otherwise event will be lost */
312		spinlock_enter();
313		/* Set expected value */
314		WRITE4(sc, IMX_GPT_OCR3, READ4(sc, IMX_GPT_CNT) + ticks);
315		/* Now everybody can relax */
316		spinlock_exit();
317		return (0);
318	}
319
320	return (EINVAL);
321}
322
323static int
324imx_gpt_timer_stop(struct eventtimer *et)
325{
326	struct imx_gpt_softc *sc;
327
328	sc = (struct imx_gpt_softc *)et->et_priv;
329
330	/* Disable interrupts and clear any pending status. */
331	sc->ir_reg &= ~(GPT_IR_OF2 | GPT_IR_OF3);
332	WRITE4(sc, IMX_GPT_IR, sc->ir_reg);
333	WRITE4(sc, IMX_GPT_SR, GPT_IR_OF2 | GPT_IR_OF3);
334	sc->sc_period = 0;
335
336	return (0);
337}
338
339static int
340imx_gpt_intr(void *arg)
341{
342	struct imx_gpt_softc *sc;
343	uint32_t status;
344
345	sc = (struct imx_gpt_softc *)arg;
346
347	status = READ4(sc, IMX_GPT_SR);
348
349	/*
350	* Clear interrupt status before invoking event callbacks.  The callback
351	* often sets up a new one-shot timer event and if the interval is short
352	* enough it can fire before we get out of this function.  If we cleared
353	* at the bottom we'd miss the interrupt and hang until the clock wraps.
354	*/
355	WRITE4(sc, IMX_GPT_SR, status);
356
357	/* Handle one-shot timer events. */
358	if (status & GPT_IR_OF3) {
359		if (sc->et.et_active) {
360			sc->et.et_event_cb(&sc->et, sc->et.et_arg);
361		}
362	}
363
364	/* Handle periodic timer events. */
365	if (status & GPT_IR_OF2) {
366		if (sc->et.et_active)
367			sc->et.et_event_cb(&sc->et, sc->et.et_arg);
368		if (sc->sc_period != 0)
369			WRITE4(sc, IMX_GPT_OCR2, READ4(sc, IMX_GPT_CNT) +
370			    sc->sc_period);
371	}
372
373	return (FILTER_HANDLED);
374}
375
376static u_int
377imx_gpt_get_timecount(struct timecounter *tc)
378{
379	struct imx_gpt_softc *sc;
380
381	sc = tc->tc_priv;
382	return (READ4(sc, IMX_GPT_CNT));
383}
384
385static device_method_t imx_gpt_methods[] = {
386	DEVMETHOD(device_probe,		imx_gpt_probe),
387	DEVMETHOD(device_attach,	imx_gpt_attach),
388
389	DEVMETHOD_END
390};
391
392static driver_t imx_gpt_driver = {
393	"imx_gpt",
394	imx_gpt_methods,
395	sizeof(struct imx_gpt_softc),
396};
397
398static devclass_t imx_gpt_devclass;
399
400EARLY_DRIVER_MODULE(imx_gpt, simplebus, imx_gpt_driver, imx_gpt_devclass, 0,
401    0, BUS_PASS_TIMER);
402
403static void
404imx_gpt_do_delay(int usec, void *arg)
405{
406	struct imx_gpt_softc *sc = arg;
407	uint64_t curcnt, endcnt, startcnt, ticks;
408
409	/*
410	 * Calculate the tick count with 64-bit values so that it works for any
411	 * clock frequency.  Loop until the hardware count reaches start+ticks.
412	 * If the 32-bit hardware count rolls over while we're looping, just
413	 * manually do a carry into the high bits after each read; don't worry
414	 * that doing this on each loop iteration is inefficient -- we're trying
415	 * to waste time here.
416	 */
417	ticks = 1 + ((uint64_t)usec * sc->clkfreq) / 1000000;
418	curcnt = startcnt = READ4(sc, IMX_GPT_CNT);
419	endcnt = startcnt + ticks;
420	while (curcnt < endcnt) {
421		curcnt = READ4(sc, IMX_GPT_CNT);
422		if (curcnt < startcnt)
423			curcnt += 1ULL << 32;
424	}
425}
426