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