imx_gpt.c revision 330897
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: stable/11/sys/arm/freescale/imx/imx_gpt.c 330897 2018-03-14 03:19:51Z eadler $");
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
46#include <dev/fdt/fdt_common.h>
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 int imx_gpt_intr(void *);
69static int imx_gpt_probe(device_t);
70static int imx_gpt_attach(device_t);
71
72static struct timecounter imx_gpt_timecounter = {
73	.tc_name           = "iMXGPT",
74	.tc_get_timecount  = imx_gpt_get_timecount,
75	.tc_counter_mask   = ~0u,
76	.tc_frequency      = 0,
77	.tc_quality        = 1000,
78};
79
80struct imx_gpt_softc {
81	device_t 		sc_dev;
82	struct resource *	res[2];
83	bus_space_tag_t 	sc_iot;
84	bus_space_handle_t	sc_ioh;
85	void *			sc_ih;			/* interrupt handler */
86	uint32_t 		sc_period;
87	uint32_t 		sc_clksrc;
88	uint32_t 		clkfreq;
89	uint32_t		ir_reg;
90	struct eventtimer 	et;
91};
92
93/* Global softc pointer for use in DELAY(). */
94static struct imx_gpt_softc *imx_gpt_sc;
95
96/*
97 * Hand-calibrated delay-loop counter.  This was calibrated on an i.MX6 running
98 * at 792mhz.  It will delay a bit too long on slower processors -- that's
99 * better than not delaying long enough.  In practice this is unlikely to get
100 * used much since the clock driver is one of the first to start up, and once
101 * we're attached the delay loop switches to using the timer hardware.
102 */
103static const int imx_gpt_delay_count = 78;
104
105/* Try to divide down an available fast clock to this frequency. */
106#define	TARGET_FREQUENCY	1000000000
107
108static struct resource_spec imx_gpt_spec[] = {
109	{ SYS_RES_MEMORY,	0,	RF_ACTIVE },
110	{ SYS_RES_IRQ,		0,	RF_ACTIVE },
111	{ -1, 0 }
112};
113
114static struct ofw_compat_data compat_data[] = {
115	{"fsl,imx6dl-gpt", 1},
116	{"fsl,imx6q-gpt",  1},
117	{"fsl,imx6ul-gpt", 1},
118	{"fsl,imx53-gpt",  1},
119	{"fsl,imx51-gpt",  1},
120	{"fsl,imx31-gpt",  1},
121	{"fsl,imx27-gpt",  1},
122	{"fsl,imx25-gpt",  1},
123	{NULL,             0}
124};
125
126static int
127imx_gpt_probe(device_t dev)
128{
129
130	if (!ofw_bus_status_okay(dev))
131		return (ENXIO);
132
133	/*
134	 *  We only support a single unit, because the only thing this driver
135	 *  does with the complex timer hardware is supply the system
136	 *  timecounter and eventtimer.  There is nothing useful we can do with
137	 *  the additional device instances that exist in some chips.
138	 */
139	if (device_get_unit(dev) > 0)
140		return (ENXIO);
141
142	if (ofw_bus_search_compatible(dev, compat_data)->ocd_data != 0) {
143		device_set_desc(dev, "Freescale i.MX GPT timer");
144		return (BUS_PROBE_DEFAULT);
145	}
146
147	return (ENXIO);
148}
149
150static int
151imx_gpt_attach(device_t dev)
152{
153	struct imx_gpt_softc *sc;
154	int ctlreg, err;
155	uint32_t basefreq, prescale, setup_ticks, t1, t2;
156
157	sc = device_get_softc(dev);
158
159	if (bus_alloc_resources(dev, imx_gpt_spec, sc->res)) {
160		device_printf(dev, "could not allocate resources\n");
161		return (ENXIO);
162	}
163
164	sc->sc_dev = dev;
165	sc->sc_iot = rman_get_bustag(sc->res[0]);
166	sc->sc_ioh = rman_get_bushandle(sc->res[0]);
167
168	/*
169	 * For now, just automatically choose a good clock for the hardware
170	 * we're running on.  Eventually we could allow selection from the fdt;
171	 * the code in this driver will cope with any clock frequency.
172	 */
173	sc->sc_clksrc = GPT_CR_CLKSRC_IPG;
174
175	ctlreg = 0;
176
177	switch (sc->sc_clksrc) {
178	case GPT_CR_CLKSRC_32K:
179		basefreq = 32768;
180		break;
181	case GPT_CR_CLKSRC_IPG:
182		basefreq = imx_ccm_ipg_hz();
183		break;
184	case GPT_CR_CLKSRC_IPG_HIGH:
185		basefreq = imx_ccm_ipg_hz() * 2;
186		break;
187	case GPT_CR_CLKSRC_24M:
188		ctlreg |= GPT_CR_24MEN;
189		basefreq = 24000000;
190		break;
191	case GPT_CR_CLKSRC_NONE:/* Can't run without a clock. */
192	case GPT_CR_CLKSRC_EXT:	/* No way to get the freq of an ext clock. */
193	default:
194		device_printf(dev, "Unsupported clock source '%d'\n",
195		    sc->sc_clksrc);
196		return (EINVAL);
197	}
198
199	/*
200	 * The following setup sequence is from the I.MX6 reference manual,
201	 * "Selecting the clock source".  First, disable the clock and
202	 * interrupts.  This also clears input and output mode bits and in
203	 * general completes several of the early steps in the procedure.
204	 */
205	WRITE4(sc, IMX_GPT_CR, 0);
206	WRITE4(sc, IMX_GPT_IR, 0);
207
208	/* Choose the clock and the power-saving behaviors. */
209	ctlreg |=
210	    sc->sc_clksrc |	/* Use selected clock */
211	    GPT_CR_FRR |	/* Just count (FreeRunner mode) */
212	    GPT_CR_STOPEN |	/* Run in STOP mode */
213	    GPT_CR_DOZEEN |	/* Run in DOZE mode */
214	    GPT_CR_WAITEN |	/* Run in WAIT mode */
215	    GPT_CR_DBGEN;	/* Run in DEBUG mode */
216	WRITE4(sc, IMX_GPT_CR, ctlreg);
217
218	/*
219	 * The datasheet says to do the software reset after choosing the clock
220	 * source.  It says nothing about needing to wait for the reset to
221	 * complete, but the register description does document the fact that
222	 * the reset isn't complete until the SWR bit reads 0, so let's be safe.
223	 * The reset also clears all registers except for a few of the bits in
224	 * CR, but we'll rewrite all the CR bits when we start the counter.
225	 */
226	WRITE4(sc, IMX_GPT_CR, ctlreg | GPT_CR_SWR);
227	while (READ4(sc, IMX_GPT_CR) & GPT_CR_SWR)
228		continue;
229
230	/* Set a prescaler value that gets us near the target frequency. */
231	if (basefreq < TARGET_FREQUENCY) {
232		prescale = 0;
233		sc->clkfreq = basefreq;
234	} else {
235		prescale = basefreq / TARGET_FREQUENCY;
236		sc->clkfreq = basefreq / prescale;
237		prescale -= 1; /* 1..n range is 0..n-1 in hardware. */
238	}
239	WRITE4(sc, IMX_GPT_PR, prescale);
240
241	/* Clear the status register. */
242	WRITE4(sc, IMX_GPT_SR, GPT_IR_ALL);
243
244	/* Start the counter. */
245	WRITE4(sc, IMX_GPT_CR, ctlreg | GPT_CR_EN);
246
247	if (bootverbose)
248		device_printf(dev, "Running on %dKHz clock, base freq %uHz CR=0x%08x, PR=0x%08x\n",
249		    sc->clkfreq / 1000, basefreq, READ4(sc, IMX_GPT_CR), READ4(sc, IMX_GPT_PR));
250
251	/* Setup the timer interrupt. */
252	err = bus_setup_intr(dev, sc->res[1], INTR_TYPE_CLK, imx_gpt_intr,
253	    NULL, sc, &sc->sc_ih);
254	if (err != 0) {
255		bus_release_resources(dev, imx_gpt_spec, sc->res);
256		device_printf(dev, "Unable to setup the clock irq handler, "
257		    "err = %d\n", err);
258		return (ENXIO);
259	}
260
261	/*
262	 * Measure how many clock ticks it takes to setup a one-shot event (it's
263	 * longer than you might think, due to wait states in accessing gpt
264	 * registers).  Scale up the result by a factor of 1.5 to be safe,
265	 * and use that to set the minimum eventtimer period we can schedule. In
266	 * the real world, the value works out to about 750ns on imx5 hardware.
267	 */
268	t1 = READ4(sc, IMX_GPT_CNT);
269	WRITE4(sc, IMX_GPT_OCR3, 0);
270	t2 = READ4(sc, IMX_GPT_CNT);
271	setup_ticks = ((t2 - t1 + 1) * 3) / 2;
272
273	/* Register as an eventtimer. */
274	sc->et.et_name = "iMXGPT";
275	sc->et.et_flags = ET_FLAGS_ONESHOT | ET_FLAGS_PERIODIC;
276	sc->et.et_quality = 800;
277	sc->et.et_frequency = sc->clkfreq;
278	sc->et.et_min_period = ((uint64_t)setup_ticks << 32) / sc->clkfreq;
279	sc->et.et_max_period = ((uint64_t)0xfffffffe  << 32) / sc->clkfreq;
280	sc->et.et_start = imx_gpt_timer_start;
281	sc->et.et_stop = imx_gpt_timer_stop;
282	sc->et.et_priv = sc;
283	et_register(&sc->et);
284
285	/* Register as a timecounter. */
286	imx_gpt_timecounter.tc_frequency = sc->clkfreq;
287	tc_init(&imx_gpt_timecounter);
288
289	/* If this is the first unit, store the softc for use in DELAY. */
290	if (device_get_unit(dev) == 0)
291	    imx_gpt_sc = sc;
292
293	return (0);
294}
295
296static int
297imx_gpt_timer_start(struct eventtimer *et, sbintime_t first, sbintime_t period)
298{
299	struct imx_gpt_softc *sc;
300	uint32_t ticks;
301
302	sc = (struct imx_gpt_softc *)et->et_priv;
303
304	if (period != 0) {
305		sc->sc_period = ((uint32_t)et->et_frequency * period) >> 32;
306		/* Set expected value */
307		WRITE4(sc, IMX_GPT_OCR2, READ4(sc, IMX_GPT_CNT) + sc->sc_period);
308		/* Enable compare register 2 Interrupt */
309		sc->ir_reg |= GPT_IR_OF2;
310		WRITE4(sc, IMX_GPT_IR, sc->ir_reg);
311		return (0);
312	} else if (first != 0) {
313		/* Enable compare register 3 interrupt if not already on. */
314		if ((sc->ir_reg & GPT_IR_OF3) == 0) {
315			sc->ir_reg |= GPT_IR_OF3;
316			WRITE4(sc, IMX_GPT_IR, sc->ir_reg);
317		}
318		ticks = ((uint32_t)et->et_frequency * first) >> 32;
319		/* Do not disturb, otherwise event will be lost */
320		spinlock_enter();
321		/* Set expected value */
322		WRITE4(sc, IMX_GPT_OCR3, READ4(sc, IMX_GPT_CNT) + ticks);
323		/* Now everybody can relax */
324		spinlock_exit();
325		return (0);
326	}
327
328	return (EINVAL);
329}
330
331static int
332imx_gpt_timer_stop(struct eventtimer *et)
333{
334	struct imx_gpt_softc *sc;
335
336	sc = (struct imx_gpt_softc *)et->et_priv;
337
338	/* Disable interrupts and clear any pending status. */
339	sc->ir_reg &= ~(GPT_IR_OF2 | GPT_IR_OF3);
340	WRITE4(sc, IMX_GPT_IR, sc->ir_reg);
341	WRITE4(sc, IMX_GPT_SR, GPT_IR_OF2 | GPT_IR_OF3);
342	sc->sc_period = 0;
343
344	return (0);
345}
346
347static int
348imx_gpt_intr(void *arg)
349{
350	struct imx_gpt_softc *sc;
351	uint32_t status;
352
353	sc = (struct imx_gpt_softc *)arg;
354
355	status = READ4(sc, IMX_GPT_SR);
356
357	/*
358	* Clear interrupt status before invoking event callbacks.  The callback
359	* often sets up a new one-shot timer event and if the interval is short
360	* enough it can fire before we get out of this function.  If we cleared
361	* at the bottom we'd miss the interrupt and hang until the clock wraps.
362	*/
363	WRITE4(sc, IMX_GPT_SR, status);
364
365	/* Handle one-shot timer events. */
366	if (status & GPT_IR_OF3) {
367		if (sc->et.et_active) {
368			sc->et.et_event_cb(&sc->et, sc->et.et_arg);
369		}
370	}
371
372	/* Handle periodic timer events. */
373	if (status & GPT_IR_OF2) {
374		if (sc->et.et_active)
375			sc->et.et_event_cb(&sc->et, sc->et.et_arg);
376		if (sc->sc_period != 0)
377			WRITE4(sc, IMX_GPT_OCR2, READ4(sc, IMX_GPT_CNT) +
378			    sc->sc_period);
379	}
380
381	return (FILTER_HANDLED);
382}
383
384u_int
385imx_gpt_get_timecount(struct timecounter *tc)
386{
387
388	if (imx_gpt_sc == NULL)
389		return (0);
390
391	return (READ4(imx_gpt_sc, IMX_GPT_CNT));
392}
393
394static device_method_t imx_gpt_methods[] = {
395	DEVMETHOD(device_probe,		imx_gpt_probe),
396	DEVMETHOD(device_attach,	imx_gpt_attach),
397
398	DEVMETHOD_END
399};
400
401static driver_t imx_gpt_driver = {
402	"imx_gpt",
403	imx_gpt_methods,
404	sizeof(struct imx_gpt_softc),
405};
406
407static devclass_t imx_gpt_devclass;
408
409EARLY_DRIVER_MODULE(imx_gpt, simplebus, imx_gpt_driver, imx_gpt_devclass, 0,
410    0, BUS_PASS_TIMER);
411
412void
413DELAY(int usec)
414{
415	uint64_t curcnt, endcnt, startcnt, ticks;
416
417	/* If the timer hardware is not accessible, just use a loop. */
418	if (imx_gpt_sc == NULL) {
419		while (usec-- > 0)
420			for (ticks = 0; ticks < imx_gpt_delay_count; ++ticks)
421				cpufunc_nullop();
422		return;
423	}
424
425	/*
426	 * Calculate the tick count with 64-bit values so that it works for any
427	 * clock frequency.  Loop until the hardware count reaches start+ticks.
428	 * If the 32-bit hardware count rolls over while we're looping, just
429	 * manually do a carry into the high bits after each read; don't worry
430	 * that doing this on each loop iteration is inefficient -- we're trying
431	 * to waste time here.
432	 */
433	ticks = 1 + ((uint64_t)usec * imx_gpt_sc->clkfreq) / 1000000;
434	curcnt = startcnt = READ4(imx_gpt_sc, IMX_GPT_CNT);
435	endcnt = startcnt + ticks;
436	while (curcnt < endcnt) {
437		curcnt = READ4(imx_gpt_sc, IMX_GPT_CNT);
438		if (curcnt < startcnt)
439			curcnt += 1ULL << 32;
440	}
441}
442