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