summaryrefslogtreecommitdiffstats
path: root/arch/x86_64/hal/serial_com.c
blob: 372a433ebf7dae4fca9ee08f60fec90a93c98bb7 (plain) (blame)
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
#include "serial_com.h"
#include "port.h"
#include "jove.h"
#include "hal/obj.h"
#include "proc/init.h"
#include "lib/printf.h"
#include "sys/objdir.h"

static int
serial_com_recv(uint16_t port)
{
    return inb(SERIAL_COM_LSR(port)) & 1;
}

static char
serial_com_getc(uint16_t port)
{
    while(serial_com_recv(port) == 0);
    return inb(port);
}

static int
serial_com_put_ready(uint16_t port)
{
    return inb(SERIAL_COM_LSR(port)) & 0x20;
}

static void 
serial_com_putc(uint16_t port, char c)
{
    while(serial_com_put_ready(port) == 0);
    outb(port, c);
}

int
serial_com_init_port(
        uint16_t port,
        uint16_t baud_divisor)
{
    uint8_t div_low = (uint8_t)baud_divisor;
    uint8_t div_high = (uint8_t)(baud_divisor >> 8);

    outb(SERIAL_COM_IER(port), 0x00); // Disable all interrupts
    outb(SERIAL_COM_LCR(port), 0x80); // Enable DLAB mode.
    outb(SERIAL_COM_DLAB_BAUD_LO(port), div_low);
    outb(SERIAL_COM_DLAB_BAUD_HI(port), div_high);
    outb(SERIAL_COM_LCR(port), 0x03); // 8 bits, no parity, one stop bit.
    outb(SERIAL_COM_FIFO(port), 0xC7); // Enable FIFO, clear them, 14 byte threshold.
    outb(SERIAL_COM_MCR(port), 0x0B); // Enable IRQs, set RTS/DSR.
 
    //Test to check if the serial port actually works.
    outb(SERIAL_COM_MCR(port), 0x1E); // Set loopback mode.
    outb(port, 0xAE); // Send test byte.
    if(inb(port) != 0xAE) {
        return 1;
    }

    //Set the port to normal operation mode.
    //(no loopback, IRQs enabled, OUT#1 and OUT#2 enabled.)
    outb(SERIAL_COM_MCR(port), 0x0F);
    return 0;
}

void
serial_com_init(void)
{
    if(serial_com_init_port(SERIAL_COM1, 3)) {
        return;
    }
    
    {
        jove_owned_obj_t *com_obj = objdir_getlocal(_rootdir_obj, INIT_ROOTDIR_SERIAL_COM_I);
        obj_settype(com_obj, JOVE_OBJ_SERIAL_COM);
        obj_setvalue(com_obj, SERIAL_COM1);
        obj_release(com_obj);
    }

    kprintf("Initialized COM1 on port %X for obj %X\n", SERIAL_COM1, INIT_ROOTDIR_SERIAL_COM_I);
}

int
serial_com_write(
        jove_owned_obj_t *obj, 
        const char *s, size_t len)
{
    if(obj_gettype(obj) != JOVE_OBJ_SERIAL_COM) {
        reterr(EBADOBJ);
    }
    for(size_t i = 0; i < len; i++) {
        serial_com_putc((uint16_t)obj_getvalue(obj), s[i]);
    }
    return len;
}