1 // SPDX-License-Identifier: GPL-2.0+ 2 /* 3 * Copyright (C) 2014, STMicroelectronics - All Rights Reserved 4 * Author(s): Vikas Manocha, <vikas.manocha@st.com> for STMicroelectronics. 5 */ 6 7 #include <common.h> 8 #include <asm/io.h> 9 #include <asm/arch-stv0991/hardware.h> 10 #include <asm/arch-stv0991/stv0991_cgu.h> 11 #include <asm/arch-stv0991/stv0991_gpt.h> 12 13 static struct stv0991_cgu_regs *const stv0991_cgu_regs = \ 14 (struct stv0991_cgu_regs *) (CGU_BASE_ADDR); 15 16 #define READ_TIMER() (readl(&gpt1_regs_ptr->cnt) & GPT_FREE_RUNNING) 17 #define GPT_RESOLUTION (CONFIG_STV0991_HZ_CLOCK / CONFIG_STV0991_HZ) 18 19 DECLARE_GLOBAL_DATA_PTR; 20 21 #define timestamp gd->arch.tbl 22 #define lastdec gd->arch.lastinc 23 24 static ulong get_timer_masked(void); 25 26 int timer_init(void) 27 { 28 /* Timer1 clock configuration */ 29 writel(TIMER1_CLK_CFG, &stv0991_cgu_regs->tim_freq); 30 writel(readl(&stv0991_cgu_regs->cgu_enable_2) | 31 TIMER1_CLK_EN, &stv0991_cgu_regs->cgu_enable_2); 32 33 /* Stop the timer */ 34 writel(readl(&gpt1_regs_ptr->cr1) & ~GPT_CR1_CEN, &gpt1_regs_ptr->cr1); 35 writel(GPT_PRESCALER_128, &gpt1_regs_ptr->psc); 36 /* Configure timer for auto-reload */ 37 writel(readl(&gpt1_regs_ptr->cr1) | GPT_MODE_AUTO_RELOAD, 38 &gpt1_regs_ptr->cr1); 39 40 /* load value for free running */ 41 writel(GPT_FREE_RUNNING, &gpt1_regs_ptr->arr); 42 43 /* start timer */ 44 writel(readl(&gpt1_regs_ptr->cr1) | GPT_CR1_CEN, 45 &gpt1_regs_ptr->cr1); 46 47 /* Reset the timer */ 48 lastdec = READ_TIMER(); 49 timestamp = 0; 50 51 return 0; 52 } 53 54 /* 55 * timer without interrupts 56 */ 57 ulong get_timer(ulong base) 58 { 59 return (get_timer_masked() / GPT_RESOLUTION) - base; 60 } 61 62 void __udelay(unsigned long usec) 63 { 64 ulong tmo; 65 ulong start = get_timer_masked(); 66 ulong tenudelcnt = CONFIG_STV0991_HZ_CLOCK / (1000 * 100); 67 ulong rndoff; 68 69 rndoff = (usec % 10) ? 1 : 0; 70 71 /* tenudelcnt timer tick gives 10 microsecconds delay */ 72 tmo = ((usec / 10) + rndoff) * tenudelcnt; 73 74 while ((ulong) (get_timer_masked() - start) < tmo) 75 ; 76 } 77 78 static ulong get_timer_masked(void) 79 { 80 ulong now = READ_TIMER(); 81 82 if (now >= lastdec) { 83 /* normal mode */ 84 timestamp += now - lastdec; 85 } else { 86 /* we have an overflow ... */ 87 timestamp += now + GPT_FREE_RUNNING - lastdec; 88 } 89 lastdec = now; 90 91 return timestamp; 92 } 93 94 /* 95 * This function is derived from PowerPC code (read timebase as long long). 96 * On ARM it just returns the timer value. 97 */ 98 unsigned long long get_ticks(void) 99 { 100 return get_timer(0); 101 } 102 103 /* 104 * This function is derived from PowerPC code (timebase clock frequency). 105 * On ARM it returns the number of timer ticks per second. 106 */ 107 ulong get_tbclk(void) 108 { 109 return CONFIG_STV0991_HZ; 110 } 111