1 /*
2  * Copyright (c) 2015 Travis Geiselbrecht
3  *
4  * Use of this source code is governed by a MIT-style
5  * license that can be found in the LICENSE file or at
6  * https://opensource.org/licenses/MIT
7  */
8 #include <lk/reg.h>
9 #include <lk/trace.h>
10 #include <lk/err.h>
11 #include <lk/init.h>
12 #include <kernel/thread.h>
13 #include <platform.h>
14 #include <platform/timer.h>
15 #include <platform/interrupts.h>
16 #include <platform/debug.h>
17 #include <sys/types.h>
18 #include <target/microblaze-config.h>
19 
20 #define LOCAL_TRACE 0
21 
22 #define R_TCSR     0
23 #define R_TLR      1
24 #define R_TCR      2
25 #define R_MAX      4
26 
27 #define TCSR_MDT        (1<<0)
28 #define TCSR_UDT        (1<<1)
29 #define TCSR_GENT       (1<<2)
30 #define TCSR_CAPT       (1<<3)
31 #define TCSR_ARHT       (1<<4)
32 #define TCSR_LOAD       (1<<5)
33 #define TCSR_ENIT       (1<<6)
34 #define TCSR_ENT        (1<<7)
35 #define TCSR_TINT       (1<<8)
36 #define TCSR_PWMA       (1<<9)
37 #define TCSR_ENALL      (1<<10)
38 
39 #define TIMER_REG(reg) (*REG32(TIMER_BASEADDR + (reg) * 4))
40 
41 static platform_timer_callback timer_cb;
42 static void *timer_arg;
43 
44 static uint32_t ticks = 0;
45 
platform_set_periodic_timer(platform_timer_callback callback,void * arg,lk_time_t interval)46 status_t platform_set_periodic_timer(platform_timer_callback callback, void *arg, lk_time_t interval) {
47     LTRACEF("cb %p, arg %p, interval %u\n", callback, arg, interval);
48 
49     uint32_t count = ((uint64_t)TIMER_RATE * interval / 1000);
50 
51     LTRACEF("count 0x%x\n", count);
52 
53     timer_cb = callback;
54     timer_arg = arg;
55 
56     TIMER_REG(R_TCSR) = 0;
57     TIMER_REG(R_TLR) = count;
58     TIMER_REG(R_TCSR) = TCSR_ENIT | TCSR_UDT | TCSR_ARHT | TCSR_ENT;
59 
60     return NO_ERROR;
61 }
62 
current_time_hires(void)63 lk_bigtime_t current_time_hires(void) {
64     return (lk_bigtime_t)ticks * 10000;
65 }
66 
current_time(void)67 lk_time_t current_time(void) {
68     return (lk_time_t)ticks * 10;
69 }
70 
timer_irq(void * arg)71 static enum handler_return timer_irq(void *arg) {
72     LTRACE;
73 
74     TIMER_REG(R_TCSR) |= TCSR_TINT;
75 
76     ticks += 1;
77 
78     enum handler_return ret = timer_cb(timer_arg, ticks * 10);
79 
80     return ret;
81 }
82 
timer_init(uint level)83 static void timer_init(uint level) {
84     LTRACE;
85 
86     register_int_handler(TIMER_IRQ, timer_irq, NULL);
87     unmask_interrupt(TIMER_IRQ);
88 }
89 
90 LK_INIT_HOOK(timer, timer_init, LK_INIT_LEVEL_PLATFORM_EARLY + 1);
91 
92 
93