1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2007 Michal Simek
4  *
5  * Michal  SIMEK <monstr@monstr.eu>
6  */
7 
8 #include <common.h>
9 #include <fdtdec.h>
10 #include <init.h>
11 #include <log.h>
12 #include <time.h>
13 #include <asm/global_data.h>
14 #include <asm/microblaze_timer.h>
15 #include <asm/microblaze_intc.h>
16 #include <linux/delay.h>
17 
18 DECLARE_GLOBAL_DATA_PTR;
19 
20 volatile int timestamp = 0;
21 microblaze_timer_t *tmr;
22 
get_timer(ulong base)23 ulong get_timer (ulong base)
24 {
25 	if (tmr)
26 		return timestamp - base;
27 	return timestamp++ - base;
28 }
29 
__udelay(unsigned long usec)30 void __udelay(unsigned long usec)
31 {
32 	u32 i;
33 
34 	if (tmr) {
35 		i = get_timer(0);
36 		while ((get_timer(0) - i) < (usec / 1000))
37 			;
38 	}
39 }
40 
41 #ifndef CONFIG_SPL_BUILD
timer_isr(void * arg)42 static void timer_isr(void *arg)
43 {
44 	timestamp++;
45 	tmr->control = tmr->control | TIMER_INTERRUPT;
46 }
47 
timer_init(void)48 int timer_init (void)
49 {
50 	int irq = -1;
51 	u32 preload = 0;
52 	u32 ret = 0;
53 	const void *blob = gd->fdt_blob;
54 	int node = 0;
55 	u32 cell[2];
56 
57 	debug("TIMER: Initialization\n");
58 
59 	/* Do not init before relocation */
60 	if (!(gd->flags & GD_FLG_RELOC))
61 		return 0;
62 
63 	node = fdt_node_offset_by_compatible(blob, node,
64 				"xlnx,xps-timer-1.00.a");
65 	if (node != -1) {
66 		fdt_addr_t base = fdtdec_get_addr(blob, node, "reg");
67 		if (base == FDT_ADDR_T_NONE)
68 			return -1;
69 
70 		debug("TIMER: Base addr %lx\n", base);
71 		tmr = (microblaze_timer_t *)base;
72 
73 		ret = fdtdec_get_int_array(blob, node, "interrupts",
74 					    cell, ARRAY_SIZE(cell));
75 		if (ret)
76 			return ret;
77 
78 		irq = cell[0];
79 		debug("TIMER: IRQ %x\n", irq);
80 
81 		preload = fdtdec_get_int(blob, node, "clock-frequency", 0);
82 		preload /= CONFIG_SYS_HZ;
83 	} else {
84 		return node;
85 	}
86 
87 	if (tmr && preload && irq >= 0) {
88 		tmr->loadreg = preload;
89 		tmr->control = TIMER_INTERRUPT | TIMER_RESET;
90 		tmr->control = TIMER_ENABLE | TIMER_ENABLE_INTR |\
91 					TIMER_RELOAD | TIMER_DOWN_COUNT;
92 		timestamp = 0;
93 		ret = install_interrupt_handler (irq, timer_isr, (void *)tmr);
94 		if (ret)
95 			tmr = NULL;
96 	}
97 	/* No problem if timer is not found/initialized */
98 	return 0;
99 }
100 #else
timer_init(void)101 int timer_init(void)
102 {
103 	return 0;
104 }
105 #endif
106 
107 /*
108  * This function is derived from PowerPC code (read timebase as long long).
109  * On Microblaze it just returns the timer value.
110  */
get_ticks(void)111 unsigned long long get_ticks(void)
112 {
113 	return get_timer(0);
114 }
115 
116 /*
117  * This function is derived from PowerPC code (timebase clock frequency).
118  * On Microblaze it returns the number of timer ticks per second.
119  */
get_tbclk(void)120 ulong get_tbclk(void)
121 {
122 	return CONFIG_SYS_HZ;
123 }
124