-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuart.c
107 lines (90 loc) · 2.72 KB
/
uart.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include "uart.h"
bool uart_is_interrupting(struct rv32_uart *uart)
{
pthread_mutex_lock(&uart->lock);
bool interrupting = uart->interrupting;
uart->interrupting = false;
pthread_mutex_unlock(&uart->lock);
return interrupting;
}
void *uart_thread_func(void *priv)
{
struct rv32_uart *uart = (struct rv32_uart *) priv;
while (1) {
struct pollfd pfd = {0, POLLIN, 0};
poll(&pfd, 1, 0);
if (!(pfd.revents & POLLIN))
continue;
char c;
/* An error or EOF */
if (read(STDIN_FILENO, &c, 1) <= 0)
continue;
pthread_mutex_lock(&uart->lock);
while ((uart->data[UART_LSR - UART_BASE] & UART_LSR_RX_EMPTY) == 1)
pthread_cond_wait(&uart->cond, &uart->lock);
uart->data[0] = c;
uart->interrupting = true;
uart->data[UART_LSR - UART_BASE] |= UART_LSR_RX_EMPTY;
pthread_mutex_unlock(&uart->lock);
}
/* Should not reach here */
return NULL;
}
struct rv32_uart *uart_init()
{
struct rv32_uart *uart = malloc(sizeof(struct rv32_uart));
uart->data[UART_LSR - UART_BASE] |=
(UART_LSR_TX_EMPTY | UART_LSR_THR_SR_EMPTY);
pthread_mutex_init(&uart->lock, NULL);
pthread_cond_init(&uart->cond, NULL);
pthread_create(&uart->tid, NULL, uart_thread_func, (void *) uart);
return uart;
}
exception_t read_uart(struct rv32_uart *uart, u32 addr, u32 size, u32 *result)
{
if (size != 8)
return LOAD_ACCESS_FAULT;
/* FIXME */
pthread_mutex_lock(&uart->lock);
switch (addr) {
case UART_IIR:
*result = uart->data[UART_IIR - UART_BASE] | 0x01;
break;
case UART_LSR:
*result = uart->data[UART_LSR - UART_BASE] | UART_LSR_TX_EMPTY |
UART_LSR_THR_SR_EMPTY;
break;
case UART_RHR:
pthread_cond_broadcast(&uart->cond); // wake up thread
uart->data[UART_LSR - UART_BASE] &= ~UART_LSR_RX_EMPTY;
*result = uart->data[addr - UART_BASE];
break;
default:
*result = uart->data[addr - UART_BASE];
}
pthread_mutex_unlock(&uart->lock);
return OK;
}
exception_t write_uart(struct rv32_uart *uart, u32 addr, u32 size, u32 value)
{
if (size != 8)
return STORE_AMO_ACCESS_FAULT;
/* FIXME */
pthread_mutex_lock(&uart->lock);
switch (addr) {
case UART_IER:
uart->data[UART_IER - UART_BASE] = (value & 0xff);
break;
case UART_IIR:
uart->data[addr - UART_BASE] = (value & 0xff);
break;
case UART_THR:
fprintf(stdout, "%c", (value & 0xff));
fflush(stdout);
break;
default:
uart->data[addr - UART_BASE] = (value & 0xff);
}
pthread_mutex_unlock(&uart->lock);
return OK;
}