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
|
#include <stdint.h>
#include "utils.h"
#define PORT 0x3f8 // COM1
#define LINE_STATUS_REGISTER PORT + 5
#define TRANSMITTER_EMPTY_BITMASK 0b00100000
uint8_t inportb(uint16_t port) {
uint8_t r;
asm("inb %1, %0" : "=a" (r) : "dN" (port));
return r;
}
void outportb(uint16_t port, uint8_t data) {
asm("outb %1, %0" : : "dN" (port), "a" (data));
}
void init_serial() {
outportb(PORT + 1, 0x00); // Disable all interrupts
outportb(PORT + 3, 0x80); // Enable DLAB (set baud rate divisor)
// Set divisor to 3 -> (115200 / 3) = 38400
outportb(PORT + 0, 0x03); // LSB
outportb(PORT + 1, 0x00); // MSB
outportb(PORT + 3, 0x03); // Character length is 8 bits, no parity, one stop bit
outportb(PORT + 2, 0xC7); // Enable FIFO, clear them, with 14-byte threshold
// TODO: GDT and IDT in order to setup COM1 interrupts.
// For now, though, we POLLLLL that mf.
// outportb(PORT + 4, 0x0B); // IRQs enabled, RTS/DSR set
outportb(PORT + 4, 0x1E); // Set in loopback mode, test the serial chip
outportb(PORT + 0, 0xAE); // Test serial chip (send byte 0xAE and check if serial returns same byte)
macaroni_assert(inportb(PORT + 0) == 0xAE, "0xAE expected from serial initizliation");
outportb(PORT + 4, 0x0F);
}
int serial_tx_empty(void) {
return inportb(LINE_STATUS_REGISTER) & TRANSMITTER_EMPTY_BITMASK;
}
void serial_putc(char c) {
while (!serial_tx_empty());
outportb(PORT, c);
}
void serial_puts(const char* s) {
while (*s) serial_putc(*s++);
}
void serial_puthex(uint32_t h) {
serial_puts("0x");
for (int i = 28; i >= 0; i -= 4)
serial_putc("0123456789abcdef"[(h >> i) & 0xF]);
}
|