1 /* 2 * (C) Copyright 2007-2008 3 * Stelian Pop <stelian@popies.net> 4 * Lead Tech Design <www.leadtechdesign.com> 5 * 6 * (C) Copyright 2013 7 * Bo Shen <voice.shen@atmel.com> 8 * 9 * SPDX-License-Identifier: GPL-2.0+ 10 */ 11 12 #include <common.h> 13 #include <asm/io.h> 14 #include <asm/arch/hardware.h> 15 #include <asm/arch/at91_pit.h> 16 #include <asm/arch/at91_pmc.h> 17 #include <asm/arch/clk.h> 18 #include <div64.h> 19 20 #if !defined(CONFIG_AT91FAMILY) 21 # error You need to define CONFIG_AT91FAMILY in your board config! 22 #endif 23 24 DECLARE_GLOBAL_DATA_PTR; 25 26 /* 27 * We're using the SAMA5D3x PITC in 32 bit mode, by 28 * setting the 20 bit counter period to its maximum (0xfffff). 29 * (See the relevant data sheets to understand that this really works) 30 * 31 * We do also mimic the typical powerpc way of incrementing 32 * two 32 bit registers called tbl and tbu. 33 * 34 * Those registers increment at 1/16 the main clock rate. 35 */ 36 37 #define TIMER_LOAD_VAL 0xfffff 38 39 static inline unsigned long long tick_to_time(unsigned long long tick) 40 { 41 tick *= CONFIG_SYS_HZ; 42 do_div(tick, gd->arch.timer_rate_hz); 43 44 return tick; 45 } 46 47 static inline unsigned long long usec_to_tick(unsigned long long usec) 48 { 49 usec *= gd->arch.timer_rate_hz; 50 do_div(usec, 1000000); 51 52 return usec; 53 } 54 55 /* 56 * Use the PITC in full 32 bit incrementing mode 57 */ 58 int timer_init(void) 59 { 60 at91_pit_t *pit = (at91_pit_t *)ATMEL_BASE_PIT; 61 62 /* Enable PITC Clock */ 63 at91_periph_clk_enable(ATMEL_ID_PIT); 64 65 /* Enable PITC */ 66 writel(TIMER_LOAD_VAL | AT91_PIT_MR_EN , &pit->mr); 67 68 gd->arch.timer_rate_hz = get_pit_clk_rate() / 16; 69 70 gd->arch.tbu = 0; 71 gd->arch.tbl = 0; 72 73 return 0; 74 } 75 76 /* 77 * Get the current 64 bit timer tick count 78 */ 79 unsigned long long get_ticks(void) 80 { 81 at91_pit_t *pit = (at91_pit_t *)ATMEL_BASE_PIT; 82 83 ulong now = readl(&pit->piir); 84 85 /* increment tbu if tbl has rolled over */ 86 if (now < gd->arch.tbl) 87 gd->arch.tbu++; 88 gd->arch.tbl = now; 89 return (((unsigned long long)gd->arch.tbu) << 32) | gd->arch.tbl; 90 } 91 92 void __udelay(unsigned long usec) 93 { 94 unsigned long long start; 95 ulong tmo; 96 97 start = get_ticks(); /* get current timestamp */ 98 tmo = usec_to_tick(usec); /* convert usecs to ticks */ 99 while ((get_ticks() - start) < tmo) 100 ; /* loop till time has passed */ 101 } 102 103 /* 104 * get_timer(base) can be used to check for timeouts or 105 * to measure elasped time relative to an event: 106 * 107 * ulong start_time = get_timer(0) sets start_time to the current 108 * time value. 109 * get_timer(start_time) returns the time elapsed since then. 110 * 111 * The time is used in CONFIG_SYS_HZ units! 112 */ 113 ulong get_timer(ulong base) 114 { 115 return tick_to_time(get_ticks()) - base; 116 } 117 118 /* 119 * Return the number of timer ticks per second. 120 */ 121 ulong get_tbclk(void) 122 { 123 return gd->arch.timer_rate_hz; 124 } 125