1/*$NetBSD: at91tctmr.c,v 1.9 2020/07/03 16:23:02 maxv Exp $*/
2
3/*
4 * AT91 Timer Counter (TC) based clock functions
5 * Copyright (c) 2007, Embedtronics Oy
6 * All rights reserved.
7 *
8 * Based on vx115_clk.c,
9 * Copyright (c) 2006, Jon Sevy <jsevy@cs.drexel.edu>
10 *
11 * Based on epclk.c
12 * Copyright (c) 2004 Jesse Off
13 * All rights reserved.
14 *
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
17 * are met:
18 * 1. Redistributions of source code must retain the above copyright
19 *    notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 *    notice, this list of conditions and the following disclaimer in the
22 *    documentation and/or other materials provided with the distribution.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
25 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
28 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 * POSSIBILITY OF SUCH DAMAGE.
35 */
36
37/*
38 * Driver for the AT91RM9200 clock tick.
39 * We use Timer 1 for the system clock
40 */
41
42#include <sys/cdefs.h>
43__KERNEL_RCSID(0, "$NetBSD: at91tctmr.c,v 1.9 2020/07/03 16:23:02 maxv Exp $");
44
45#include <sys/types.h>
46#include <sys/param.h>
47#include <sys/systm.h>
48#include <sys/kernel.h>
49#include <sys/time.h>
50#include <sys/timetc.h>
51#include <sys/device.h>
52
53#include <dev/clock_subr.h>
54
55#include <sys/bus.h>
56#include <machine/intr.h>
57
58#include <arm/cpufunc.h>
59#include <arm/at91/at91reg.h>
60#include <arm/at91/at91var.h>
61#include <arm/at91/at91tcreg.h>
62
63#include <opt_hz.h>     /* for HZ */
64
65
66#define DEBUG_CLK
67#ifdef DEBUG_CLK
68#define DPRINTF(fmt...)  printf(fmt)
69#else
70#define DPRINTF(fmt...)
71#endif
72
73
74static int at91tctmr_match(device_t, cfdata_t, void *);
75static void at91tctmr_attach(device_t, device_t, void *);
76
77void rtcinit(void);
78
79/* callback functions for intr_functions */
80static int at91tctmr_intr(void* arg);
81
82struct at91tctmr_softc {
83	device_t	sc_dev;
84	u_char		*sc_addr;
85	int		sc_pid;
86	int		sc_initialized;
87	uint32_t	sc_timerclock;
88	uint32_t	sc_divider;
89	uint32_t	sc_usec_per_tick;
90};
91
92static struct at91tctmr_softc *at91tctmr_sc = NULL;
93#if 0
94static struct timeval lasttv;
95#endif
96
97
98
99/* Match value for clock timer; running at master clock, want HZ ticks per second  */
100/* NOTE: don't change there without visiting the functions below which      */
101/* convert between timer counts and microseconds                            */
102
103static inline uint32_t
104at91tctmr_count_to_usec(struct at91tctmr_softc *sc, uint32_t count)
105{
106    uint64_t tmp;
107
108    tmp = count;
109    tmp *= 1000000U;
110
111    return (tmp / sc->sc_timerclock);
112}
113
114#if 0
115/* This may only be called when overflow is avoided; typically, */
116/* it will be used when usec < USEC_PER_TICK              */
117static uint32_t
118usec_to_timer_count(uint32_t usec)
119{
120    uint32_t result;
121
122    /* convert specified number of usec to timer ticks, and round up */
123    result = (AT91_SCLK * usec) / 1000000;
124
125    if ((result * 1000000) != (usec * AT91_SCLK))
126    {
127        /* round up */
128        result += 1;
129    }
130
131    return result;
132
133}
134#endif
135
136/* macros to simplify writing to the timer controller */
137static inline uint32_t
138READ_TC(struct at91tctmr_softc *sc, uint offset)
139{
140	volatile uint32_t *addr = (void*)(sc->sc_addr + offset);
141	return *addr;
142}
143
144//bus_space_read_4(sc->sc_iot, sc->sc_ioh, offset)
145static inline void
146WRITE_TC(struct at91tctmr_softc *sc, uint offset, uint32_t value)
147{
148	volatile uint32_t *addr = (void*)(sc->sc_addr + offset);
149	*addr = value;
150}
151
152
153CFATTACH_DECL_NEW(at91tctmr, sizeof(struct at91tctmr_softc),
154    at91tctmr_match, at91tctmr_attach, NULL, NULL);
155
156#if 0
157static u_int at91tctmr_get_timecount(struct timecounter *);
158
159static struct timecounter at91tctmr_timecounter = {
160	.tc_get_timecount = at91tctmr_get_timecount,
161	.tc_counter_mask = 0xffffffff,
162	.tc_frequency = COUNTS_PER_SEC,
163	.tc_name = "at91tctmr",
164	.tc_quality = 100,
165};
166#endif
167
168static int
169at91tctmr_match(device_t parent, cfdata_t match, void *aux)
170{
171	if (strcmp(match->cf_name, "at91tctmr") == 0)
172		return 2;
173	return 0;
174}
175
176static void
177at91tctmr_attach(device_t parent, device_t self, void *aux)
178{
179    struct at91tctmr_softc *sc = device_private(self);
180    struct at91bus_attach_args *sa = aux;
181
182    aprint_normal("\n");
183
184    sc->sc_dev = self;
185    sc->sc_addr = (void*)sa->sa_addr;
186    sc->sc_pid = sa->sa_pid;
187
188    if (at91tctmr_sc == NULL)
189        at91tctmr_sc = sc;
190
191    at91_peripheral_clock(sc->sc_pid, 1);
192
193    WRITE_TC(sc, TC_CCR, TC_CCR_CLKDIS);
194    WRITE_TC(sc, TC_IDR, -1);	/* make sure interrupts are disabled	*/
195
196    /* find divider */
197    uint32_t cmr = 0;
198    if (AT91_MSTCLK / 2U / HZ <= 65536) {
199      sc->sc_timerclock = AT91_MSTCLK / 2U;
200      cmr = TC_CMR_TCCLKS_MCK_DIV_2;
201    } else if (AT91_MSTCLK / 8U / HZ <= 65536) {
202      sc->sc_timerclock = AT91_MSTCLK / 8U;
203      cmr = TC_CMR_TCCLKS_MCK_DIV_8;
204    } else if (AT91_MSTCLK / 32U / HZ <= 65536) {
205      sc->sc_timerclock = AT91_MSTCLK / 32U;
206      cmr = TC_CMR_TCCLKS_MCK_DIV_32;
207    } else if (AT91_MSTCLK / 128U / HZ <= 65536) {
208      sc->sc_timerclock = AT91_MSTCLK / 128U;
209      cmr = TC_CMR_TCCLKS_MCK_DIV_128;
210    } else
211      panic("%s: cannot setup timer to reach HZ", device_xname(sc->sc_dev));
212
213    sc->sc_divider = (sc->sc_timerclock + HZ - 1) / HZ; /* round up */
214    sc->sc_usec_per_tick = 1000000UL / (sc->sc_timerclock / sc->sc_divider);
215
216    WRITE_TC(sc, TC_CMR, TC_CMR_WAVE | cmr | TC_CMR_WAVSEL_UP_RC);
217    WRITE_TC(sc, TC_CCR, TC_CCR_CLKEN);
218    WRITE_TC(sc, TC_RC,  sc->sc_divider - 1);
219    WRITE_TC(sc, TC_CCR, TC_CCR_SWTRG);
220
221    sc->sc_initialized = 1;
222
223    DPRINTF("%s: done, tclock=%"PRIu32" div=%"PRIu32" uspertick=%"PRIu32"\n", __FUNCTION__, sc->sc_timerclock, sc->sc_divider, sc->sc_usec_per_tick);
224
225}
226
227/*
228 * at91tctmr_intr:
229 *
230 *Handle the hardclock interrupt.
231 */
232static int
233at91tctmr_intr(void *arg)
234{
235    struct at91tctmr_softc *sc = arg;
236
237    /* make sure it's the kernel timer that generated the interrupt  */
238    /* need to do this since the interrupt line is shared by the    */
239    /* other interval and PWM timers                                */
240    if (READ_TC(sc, TC_SR) & TC_SR_CPCS) {
241        /* call the kernel timer handler */
242        hardclock((struct clockframe*) arg);
243        return 1;
244    } else {
245        /* it's one of the other timers; just pass it on */
246        return 0;
247    }
248}
249
250/*
251 * setstatclockrate:
252 *
253 *Set the rate of the statistics clock.
254 *
255 *We assume that hz is either stathz or profhz, and that neither
256 *will change after being set by cpu_initclocks().  We could
257 *recalculate the intervals here, but that would be a pain.
258 */
259void
260setstatclockrate(int hzz)
261{
262        /* use hardclock */
263	(void)hzz;
264}
265
266/*
267 * cpu_initclocks:
268 *
269 *Initialize the clock and get it going.
270 */
271static void udelay(unsigned int usec);
272
273void
274cpu_initclocks(void)
275{
276    struct at91tctmr_softc *sc = at91tctmr_sc;
277
278    if (!sc || !sc->sc_initialized)
279	panic("%s: driver has not been initialized! (sc=%p)", __FUNCTION__, sc);
280
281    hz = sc->sc_timerclock / sc->sc_divider;
282    stathz = profhz = 0;
283
284    /* set up and enable interval timer 1 as kernel timer, */
285    /* using 32kHz clock source */
286
287    /* register interrupt handler */
288    at91_intr_establish(sc->sc_pid, IPL_CLOCK, INTR_HIGH_LEVEL, at91tctmr_intr, sc);
289
290    /* enable interrupts from timer */
291    WRITE_TC(sc, TC_IER, TC_SR_CPCS);
292}
293
294
295
296
297static void udelay(unsigned int usec)
298{
299    struct at91tctmr_softc *sc = at91tctmr_sc;
300    uint32_t prev_cvr, cvr, divi = READ_TC(sc, TC_RC), diff;
301    int prev_ticks, ticks, ticks2;
302    unsigned footick = (sc->sc_timerclock * 64ULL / 1000000UL);
303
304    if (usec > 0) {
305      prev_ticks = getticks();
306      __insn_barrier();
307      prev_cvr = READ_TC(sc, TC_CV);
308      ticks = getticks();
309      __insn_barrier();
310      if (ticks != prev_ticks) {
311	prev_cvr = READ_TC(sc, TC_CV);
312	prev_ticks = ticks;
313      }
314      for (;;) {
315	ticks = getticks();
316	__insn_barrier();
317	cvr = READ_TC(sc, TC_CV);
318	ticks2 = getticks();
319	__insn_barrier();
320	if (ticks2 != ticks) {
321	  cvr = READ_TC(sc, TC_CV);
322	}
323	diff = (ticks2 - prev_ticks) * divi;
324	if (cvr < prev_cvr) {
325	  if (!diff)
326	    diff = divi;
327	  diff -= prev_cvr - cvr;
328	} else
329	  diff += cvr - prev_cvr;
330	diff = diff * 64 / footick;
331	if (diff) {
332	  if (usec <= diff)
333	    break;
334	  prev_ticks = ticks2;
335	  prev_cvr = (prev_cvr + footick * diff / 64) % divi;
336	  usec -= diff;
337	}
338      }
339    }
340}
341
342
343
344/*
345 * delay:
346 *
347 *Delay for at least N microseconds. Note that due to our coarse clock,
348 *  our resolution is 61 us. But we round up so we'll wait at least as
349 *  long as requested.
350 */
351void
352delay(unsigned int usec)
353{
354    struct at91tctmr_softc *sc = at91tctmr_sc;
355
356#ifdef DEBUG
357    if (sc == NULL) {
358        printf("delay: called before start at91tc\n");
359        return;
360    }
361#endif
362
363    if (usec >= sc->sc_usec_per_tick) {
364        /* have more than 1 tick; just do in ticks */
365        unsigned int ticks = (usec + sc->sc_usec_per_tick - 1) / sc->sc_usec_per_tick;
366        while (ticks-- > 0) {
367	  udelay(sc->sc_usec_per_tick);
368	}
369    } else {
370        /* less than 1 tick; can do as usec */
371        udelay(usec);
372    }
373
374}
375
376