feat: standard vga support (mode switching, framebuffer remapping)
[lunaix-os.git] / lunaix-os / hal / char / uart / 16550_pmio.c
1 /**
2  * @file 16550_pmio.c
3  * @author Lunaixsky (lunaxisky@qq.com)
4  * @brief 16550 UART with port mapped IO
5  * @version 0.1
6  * @date 2023-08-30
7  *
8  * @copyright Copyright (c) 2023
9  *
10  */
11 #include <lunaix/device.h>
12 #include <lunaix/isrm.h>
13
14 #include <sys/port_io.h>
15
16 #include "16550.h"
17
18 #define DELAY 50
19
20 static DEFINE_LLIST(com_ports);
21
22 static u32_t
23 com_regread(struct uart16550* uart, ptr_t regoff)
24 {
25     u8_t val = port_rdbyte(uart->base_addr + regoff);
26     port_delay(DELAY);
27
28     return (u32_t)val;
29 }
30
31 static void
32 com_regwrite(struct uart16550* uart, ptr_t regoff, u32_t val)
33 {
34     port_wrbyte(uart->base_addr + regoff, (u8_t)val);
35     port_delay(DELAY);
36 }
37
38 static void
39 com_irq_handler(const isr_param* param)
40 {
41     uart_general_irq_handler(param->execp->vector, &com_ports);
42 }
43
44 static int
45 upiom_init(struct device_def* def)
46 {
47     int irq3 = 3, irq4 = 4;
48     u16_t ioports[] = { 0x3F8, 0x2F8, 0x3E8, 0x2E8 };
49     int* irqs[] = { &irq4, &irq3, &irq4, &irq3 };
50
51     struct uart16550* uart = NULL;
52
53     // COM 1...4
54     for (size_t i = 0; i < 4; i++) {
55         if (!uart) {
56             uart = uart_alloc(ioports[i]);
57             uart->read_reg = com_regread;
58             uart->write_reg = com_regwrite;
59         } else {
60             uart->base_addr = ioports[i];
61         }
62
63         if (!uart_testport(uart, 0xe3)) {
64             continue;
65         }
66
67         int irq = *irqs[i];
68         if (irq) {
69             /*
70              *  Since these irqs are overlapped, this particular setup is needed
71              * to avoid double-bind
72              */
73             uart->iv = isrm_bindirq(irq, com_irq_handler);
74             *((volatile int*)irqs[i]) = 0;
75         }
76
77         uart_enable_fifo(uart, UART_FIFO8);
78         llist_append(&com_ports, &uart->local_ports);
79
80         struct serial_dev* sdev = serial_create(&def->class);
81         sdev->backend = uart;
82         sdev->write = uart_general_tx;
83         sdev->exec_cmd = uart_general_exec_cmd;
84
85         uart->sdev = sdev;
86
87         uart_setup(uart);
88         uart_setie(uart);
89         uart = NULL;
90     }
91
92     if (uart) {
93         uart_free(uart);
94     }
95
96     return 0;
97 }
98
99 static struct device_def uart_pmio_def = {
100     .class = DEVCLASS(DEVIF_SOC, DEVFN_CHAR, DEV_UART16550),
101     .name = "16550 Generic UART (I/O)",
102     .init = upiom_init
103 };
104 EXPORT_DEVICE(uart16550_pmio, &uart_pmio_def, load_earlystage);