summaryrefslogtreecommitdiff
path: root/uart.c
blob: 29f6df411b97df25ce3ae48182f6af789921d5e2 (plain)
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
#include "types.h"
#include "param.h"
#include "memlayout.h"
#include "riscv.h"
#include "proc.h"
#include "spinlock.h"
#include "defs.h"

//
// qemu -machine virt has a 16550a UART
// qemu/hw/riscv/virt.c
// http://byterunner.com/16550.html
//
// caller should lock.
//

// address of one of the registers
#define R(reg) ((volatile unsigned char *)(UART0 + reg))

void
uartinit(void)
{
  // disable interrupts -- IER
  *R(1) = 0x00;

  // special mode to set baud rate
  *R(3) = 0x80;

  // LSB for baud rate of 38.4K
  *R(0) = 0x03;

  // MSB for baud rate of 38.4K
  *R(1) = 0x00;

  // leave set-baud mode,
  // and set word length to 8 bits, no parity.
  *R(3) = 0x03;

  // reset and enable FIFOs -- FCR.
  *R(2) = 0x07;

  // enable receive interrupts -- IER.
  *R(1) = 0x01;
}

void
uartputc(int c)
{
  *R(0) = c;
}

int
uartgetc(void)
{
  if(*R(5) & 0x01){
    // input data is ready.
    return *R(0);
  } else {
    return -1;
  }
}

void
uartintr(void)
{
  while(1){
    int c = uartgetc();
    if(c == -1)
      break;
    consoleintr(c);
  }
}