Googler | 40bc9d0 | 2023-12-15 16:42:49 +0800 | [diff] [blame^] | 1 | /* |
| 2 | * (C) Copyright 2009 Alessandro Rubini |
| 3 | * |
| 4 | * SPDX-License-Identifier: GPL-2.0+ |
| 5 | */ |
| 6 | |
| 7 | #include <common.h> |
| 8 | #include <asm/io.h> |
| 9 | #include <asm/arch/mtu.h> |
| 10 | |
| 11 | /* |
| 12 | * The timer is a decrementer, we'll left it free running at 2.4MHz. |
| 13 | * We have 2.4 ticks per microsecond and an overflow in almost 30min |
| 14 | */ |
| 15 | #define TIMER_CLOCK (24 * 100 * 1000) |
| 16 | #define COUNT_TO_USEC(x) ((x) * 5 / 12) /* overflows at 6min */ |
| 17 | #define USEC_TO_COUNT(x) ((x) * 12 / 5) /* overflows at 6min */ |
| 18 | #define TICKS_PER_HZ (TIMER_CLOCK / CONFIG_SYS_HZ) |
| 19 | #define TICKS_TO_HZ(x) ((x) / TICKS_PER_HZ) |
| 20 | |
| 21 | /* macro to read the decrementing 32 bit timer as an increasing count */ |
| 22 | #define READ_TIMER() (0 - readl(CONFIG_SYS_TIMERBASE + MTU_VAL(0))) |
| 23 | |
| 24 | /* Configure a free-running, auto-wrap counter with no prescaler */ |
| 25 | int timer_init(void) |
| 26 | { |
| 27 | ulong val; |
| 28 | |
| 29 | writel(MTU_CRn_ENA | MTU_CRn_PRESCALE_1 | MTU_CRn_32BITS, |
| 30 | CONFIG_SYS_TIMERBASE + MTU_CR(0)); |
| 31 | |
| 32 | /* Reset the timer */ |
| 33 | writel(0, CONFIG_SYS_TIMERBASE + MTU_LR(0)); |
| 34 | /* |
| 35 | * The load-register isn't really immediate: it changes on clock |
| 36 | * edges, so we must wait for our newly-written value to appear. |
| 37 | * Since we might miss reading 0, wait for any change in value. |
| 38 | */ |
| 39 | val = READ_TIMER(); |
| 40 | while (READ_TIMER() == val) |
| 41 | ; |
| 42 | |
| 43 | return 0; |
| 44 | } |
| 45 | |
| 46 | /* Return how many HZ passed since "base" */ |
| 47 | ulong get_timer(ulong base) |
| 48 | { |
| 49 | return TICKS_TO_HZ(READ_TIMER()) - base; |
| 50 | } |
| 51 | |
| 52 | /* Delay x useconds */ |
| 53 | void __udelay(unsigned long usec) |
| 54 | { |
| 55 | ulong ini, end; |
| 56 | |
| 57 | ini = READ_TIMER(); |
| 58 | end = ini + USEC_TO_COUNT(usec); |
| 59 | while ((signed)(end - READ_TIMER()) > 0) |
| 60 | ; |
| 61 | } |
| 62 | |
| 63 | unsigned long long get_ticks(void) |
| 64 | { |
| 65 | return get_timer(0); |
| 66 | } |
| 67 | |
| 68 | ulong get_tbclk(void) |
| 69 | { |
| 70 | return CONFIG_SYS_HZ; |
| 71 | } |