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