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