feat: kernel stack tracing
[lunaix-os.git] / lunaix-os / kernel / peripheral / ps2kbd.c
index 6905b1eb059fc8995aeaf3c2cbb5c13a007967b8..6690faf22024f49d9583b9f015b7779073c8a382 100644 (file)
@@ -1,23 +1,24 @@
-#include <hal/acpi/acpi.h>
-#include <hal/ioapic.h>
 #include <lunaix/clock.h>
 #include <lunaix/common.h>
+#include <lunaix/input.h>
+#include <lunaix/isrm.h>
 #include <lunaix/peripheral/ps2kbd.h>
 #include <lunaix/syslog.h>
 #include <lunaix/timer.h>
 
-#include <arch/x86/interrupts.h>
-#include <hal/cpu.h>
+#include <sys/cpu.h>
+#include <hal/intc.h>
+
 #include <klibc/string.h>
 
-#include <stdint.h>
+#include <sys/interrupts.h>
+#include <sys/port_io.h>
 
 #define PS2_DEV_CMD_MAX_ATTEMPTS 5
 
-LOG_MODULE("PS2KBD");
+LOG_MODULE("i8042");
 
 static struct ps2_cmd_queue cmd_q;
-static struct ps2_key_buffer key_buf;
 static struct ps2_kbd_state kbd_state;
 
 #define KEY_NUM(x) (x + 0x30)
@@ -69,18 +70,24 @@ static kbd_keycode_t scancode_set2_shift[] = {
 
 // clang-format on
 
+static struct input_device* kbd_idev;
+
 #define KBD_STATE_KWAIT 0x00
 #define KBD_STATE_KSPECIAL 0x01
 #define KBD_STATE_KRELEASED 0x02
+#define KBD_STATE_E012 0x03
+#define KBD_STATE_KRELEASED_E0 0x04
 #define KBD_STATE_CMDPROCS 0x40
 
-#define KBD_ENABLE_SPIRQ_FIX
+// #define KBD_ENABLE_SPIRQ_FIX
+#define KBD_ENABLE_SPIRQ_FIX2
 // #define KBD_DBGLOG
 
 void
 intr_ps2_kbd_handler(const isr_param* param);
-static struct kdb_keyinfo_pkt*
-ps2_keybuffer_next_write();
+
+static u8_t
+ps2_issue_cmd_wretry(char cmd, u16_t arg);
 
 void
 ps2_device_post_cmd(char cmd, char arg)
@@ -107,39 +114,46 @@ ps2_kbd_init()
 {
 
     memset(&cmd_q, 0, sizeof(cmd_q));
-    memset(&key_buf, 0, sizeof(key_buf));
     memset(&kbd_state, 0, sizeof(kbd_state));
 
     mutex_init(&cmd_q.mutex);
-    mutex_init(&key_buf.mutex);
 
     kbd_state.translation_table = scancode_set2;
     kbd_state.state = KBD_STATE_KWAIT;
 
-    acpi_context* acpi_ctx = acpi_get_context();
-    if (acpi_ctx->fadt.header.rev > 1) {
-        /*
-         *  只有当前ACPI版本大于1时,我们才使用FADT的IAPC_BOOT_ARCH去判断8042是否存在。
-         *  这是一个坑,在ACPI v1中,这个字段是reserved!而这及至ACPI v2才出现。
-         *  需要注意:Bochs 和 QEMU 使用的是ACPI v1,而非 v2
-         * (virtualbox好像是v4)
-         *
-         *  (2022/6/29)
-         *  QEMU在7.0.0版本中,修复了FADT::IAPC_BOOT无法正确提供关于i8042的信息的bug
-         *      https://wiki.qemu.org/ChangeLog/7.0#ACPI_.2F_SMBIOS
-         *
-         *  请看Bochs的bios源码(QEMU的BIOS其实是照抄bochs的,所以也是一个德行。。):
-         *      https://bochs.sourceforge.io/cgi-bin/lxr/source/bios/rombios32.c#L1314
-         */
-        if (!(acpi_ctx->fadt.boot_arch & IAPC_ARCH_8042)) {
-            kprintf(KERROR "No PS/2 controller detected.\n");
-            // FUTURE: Some alternative fallback on this? Check PCI bus for USB
-            // controller instead?
-            return;
-        }
-    } else {
-        kprintf(KWARN "Outdated FADT used, assuming 8042 always exist.\n");
-    }
+    kbd_idev = input_add_device("i8042-kbd");
+
+    /* FIXME This require systematical rework! */
+    // acpi_context* acpi_ctx = acpi_get_context();
+    // if (acpi_ctx->fadt.header.rev > 1) {
+    //     /*
+    //      *
+    //      只有当前ACPI版本大于1时,我们才使用FADT的IAPC_BOOT_ARCH去判断8042是否存在。
+    //      *  这是一个坑,在ACPI v1中,这个字段是reserved!而这及至ACPI
+    //      v2才出现。
+    //      *  需要注意:Bochs 和 QEMU 使用的是ACPI v1,而非 v2
+    //      * (virtualbox好像是v4)
+    //      *
+    //      *  (2022/6/29)
+    //      *
+    //      QEMU在7.0.0版本中,修复了FADT::IAPC_BOOT无法正确提供关于i8042的信息的bug
+    //      *      https://wiki.qemu.org/ChangeLog/7.0#ACPI_.2F_SMBIOS
+    //      *
+    //      *
+    //      请看Bochs的bios源码(QEMU的BIOS其实是照抄bochs的,所以也是一个德行。。):
+    //      *
+    //      https://bochs.sourceforge.io/cgi-bin/lxr/source/bios/rombios32.c#L1314
+    //      */
+    //     if (!(acpi_ctx->fadt.boot_arch & IAPC_ARCH_8042)) {
+    //         kprintf(KERROR "not found\n");
+    //         // FUTURE: Some alternative fallback on this? Check PCI bus for
+    //         USB
+    //         // controller instead?
+    //         return;
+    //     }
+    // } else {
+    //     kprintf(KWARN "outdated FADT used, assuming exists.\n");
+    // }
 
     char result;
 
@@ -150,38 +164,38 @@ ps2_kbd_init()
     ps2_post_cmd(PS2_PORT_CTRL_CMDREG, PS2_CMD_PORT2_DISABLE, PS2_NO_ARG);
 
     // 2、清空控制器缓冲区
-    io_inb(PS2_PORT_ENC_DATA);
+    port_rdbyte(PS2_PORT_ENC_DATA);
 
     // 3、屏蔽所有PS/2设备(端口1&2)IRQ,并且禁用键盘键码转换功能
     result = ps2_issue_cmd(PS2_CMD_READ_CFG, PS2_NO_ARG);
-    result = result & ~(PS2_CFG_P1INT | PS2_CFG_P2INT | PS2_CFG_TRANSLATION);
+    result = result & ~(PS2_CFG_P1INT | PS2_CFG_P2INT);
     ps2_post_cmd(PS2_PORT_CTRL_CMDREG, PS2_CMD_WRITE_CFG, result);
 
     // 4、控制器自检
-    result = ps2_issue_cmd(PS2_CMD_SELFTEST, PS2_NO_ARG);
+    result = ps2_issue_cmd_wretry(PS2_CMD_SELFTEST, PS2_NO_ARG);
     if (result != PS2_RESULT_TEST_OK) {
-        kprintf(KERROR "Controller self-test failed.");
-        goto done;
+        kprintf(KWARN "controller self-test failed. (%x)\n", result);
+        // goto done;
     }
 
     // 5、设备自检(端口1自检,通常是我们的键盘)
-    result = ps2_issue_cmd(PS2_CMD_SELFTEST_PORT1, PS2_NO_ARG);
+    result = ps2_issue_cmd_wretry(PS2_CMD_SELFTEST_PORT1, PS2_NO_ARG);
     if (result != 0) {
-        kprintf(KERROR "Interface test on port 1 failed.");
-        goto done;
+        kprintf(KERROR "interface test on port 1 failed. (%x)\n", result);
+        // goto done;
     }
 
+    ps2_post_cmd(PS2_PORT_CTRL_CMDREG, PS2_CMD_PORT2_DISABLE, PS2_NO_ARG);
+
     // 6、开启位于端口1的 IRQ,并启用端口1。不用理会端口2,那儿一般是鼠标。
     ps2_post_cmd(PS2_PORT_CTRL_CMDREG, PS2_CMD_PORT1_ENABLE, PS2_NO_ARG);
     result = ps2_issue_cmd(PS2_CMD_READ_CFG, PS2_NO_ARG);
-    result = result | PS2_CFG_P1INT;
+    // 重新设置配置字节,因为控制器自检有可能重置我们先前做的改动。
+    result = (result | PS2_CFG_P1INT) & ~(PS2_CFG_TRANSLATION | PS2_CFG_P2INT);
     ps2_post_cmd(PS2_PORT_CTRL_CMDREG, PS2_CMD_WRITE_CFG, result);
 
     // 至此,PS/2控制器和设备已完成初始化,可以正常使用。
 
-    // 将我们的键盘驱动挂载到第204号中断上(已由IOAPIC映射至IRQ#1),
-    intr_subscribe(PC_KBD_IV, intr_ps2_kbd_handler);
-
     // 搞一个计时器,将我们的 ps2_process_cmd
     // 挂上去。每隔5毫秒执行排在队头的命令。
     //  为什么只执行队头的命令,而不是全部的命令?
@@ -198,10 +212,8 @@ ps2_kbd_init()
      *
      *  所以,保险的方法是:在初始化后才去设置ioapic,这样一来我们就能有一个稳定的IRQ#1以放心使用。
      */
-    uint8_t irq_kbd = ioapic_get_irq(acpi_ctx, PC_AT_IRQ_KBD);
-    ioapic_redirect(irq_kbd, PC_KBD_IV, 0, IOAPIC_DELMOD_FIXED);
+    isrm_bindirq(PC_AT_IRQ_KBD, intr_ps2_kbd_handler);
 
-done:
     cpu_enable_interrupt();
 }
 
@@ -225,7 +237,7 @@ ps2_process_cmd(void* arg)
 
     // 处理队列排头的指令
     struct ps2_cmd* pending_cmd = &cmd_q.cmd_queue[cmd_q.queue_ptr];
-    char result;
+    u8_t result;
     int attempts = 0;
 
     // 尝试将命令发送至PS/2键盘(通过PS/2控制器)
@@ -238,7 +250,6 @@ ps2_process_cmd(void* arg)
 #endif
         attempts++;
     } while (result == PS2_RESULT_NAK && attempts < PS2_DEV_CMD_MAX_ATTEMPTS);
-
     // XXX: 是否需要处理不成功的指令?
 
     cmd_q.queue_ptr = (cmd_q.queue_ptr + 1) % PS2_CMD_QUEUE_SIZE;
@@ -246,7 +257,7 @@ ps2_process_cmd(void* arg)
 }
 
 void
-kbd_buffer_key_event(kbd_keycode_t key, uint8_t scancode, kbd_kstate_t state)
+kbd_buffer_key_event(kbd_keycode_t key, u8_t scancode, kbd_kstate_t state)
 {
     /*
         forgive me on these ugly bit-level tricks,
@@ -271,14 +282,13 @@ kbd_buffer_key_event(kbd_keycode_t key, uint8_t scancode, kbd_kstate_t state)
         key = key & (0xffdf |
                      -('a' > key || key > 'z' || !(state & KBD_KEY_FCAPSLKED)));
 
-        if (!mutex_on_hold(&key_buf.mutex)) {
-            struct kdb_keyinfo_pkt* keyevent_pkt = ps2_keybuffer_next_write();
-            *keyevent_pkt =
-              (struct kdb_keyinfo_pkt){ .keycode = key,
-                                        .scancode = scancode,
-                                        .state = state,
-                                        .timestamp = clock_systime() };
-        }
+        struct input_evt_pkt ipkt = { .pkt_type = (state & KBD_KEY_FPRESSED)
+                                                    ? PKT_PRESS
+                                                    : PKT_RELEASE,
+                                      .scan_code = scancode,
+                                      .sys_code = (state << 16) | key };
+
+        input_fire_event(kbd_idev, &ipkt);
 
         return;
     }
@@ -295,14 +305,14 @@ intr_ps2_kbd_handler(const isr_param* param)
 {
 
     // This is important! Don't believe me? try comment it out and run on Bochs!
-    while (!(io_inb(PS2_PORT_CTRL_STATUS) & PS2_STATUS_OFULL))
-        ;
+    // while (!(port_rdbyte(PS2_PORT_CTRL_STATUS) & PS2_STATUS_OFULL))
+    //    ;
 
     // I know you are tempting to move this chunk after the keyboard state
     // check. But DO NOT. This chunk is in right place and right order. Moving
     // it at your own risk This is to ensure we've cleared the output buffer
     // everytime, so it won't pile up across irqs.
-    uint8_t scancode = io_inb(PS2_PORT_ENC_DATA);
+    u8_t scancode = port_rdbyte(PS2_PORT_ENC_DATA);
     kbd_keycode_t key;
 
     /*
@@ -337,6 +347,12 @@ intr_ps2_kbd_handler(const isr_param* param)
     }
 #endif
 
+#ifdef KBD_ENABLE_SPIRQ_FIX2
+    if (scancode == PS2_RESULT_ACK || scancode == PS2_RESULT_NAK) {
+        return;
+    }
+#endif
+
 #ifdef KBD_DBGLOG
     kprintf(KDEBUG "%x\n", scancode & 0xff);
 #endif
@@ -354,8 +370,10 @@ intr_ps2_kbd_handler(const isr_param* param)
             }
             break;
         case KBD_STATE_KSPECIAL:
-            if (scancode == 0xf0) { // release code
-                kbd_state.state = KBD_STATE_KRELEASED;
+            if (scancode == 0x12) {
+                kbd_state.state = KBD_STATE_E012;
+            } else if (scancode == 0xf0) { // release code
+                kbd_state.state = KBD_STATE_KRELEASED_E0;
             } else {
                 key = kbd_state.translation_table[scancode];
                 kbd_buffer_key_event(key, scancode, KBD_KEY_FPRESSED);
@@ -364,10 +382,23 @@ intr_ps2_kbd_handler(const isr_param* param)
                 kbd_state.translation_table = scancode_set2;
             }
             break;
+        // handle the '0xE0, 0x12, 0xE0, xx' sequence
+        case KBD_STATE_E012:
+            if (scancode == 0xe0) {
+                kbd_state.state = KBD_STATE_KSPECIAL;
+                kbd_state.translation_table = scancode_set2_ex;
+            }
+            break;
+        case KBD_STATE_KRELEASED_E0:
+            if (scancode == 0x12) {
+                goto escape_release;
+            }
+            // fall through
         case KBD_STATE_KRELEASED:
             key = kbd_state.translation_table[scancode];
             kbd_buffer_key_event(key, scancode, KBD_KEY_FRELEASED);
 
+        escape_release:
             // reset the translation table to scancode_set2
             kbd_state.state = KBD_STATE_KWAIT;
             kbd_state.translation_table = scancode_set2;
@@ -378,78 +409,60 @@ intr_ps2_kbd_handler(const isr_param* param)
     }
 }
 
-static uint8_t
-ps2_issue_cmd(char cmd, uint16_t arg)
+static u8_t
+ps2_issue_cmd(char cmd, u16_t arg)
 {
     ps2_post_cmd(PS2_PORT_CTRL_CMDREG, cmd, arg);
 
     // 等待PS/2控制器返回。通过轮询(polling)状态寄存器的 bit 0
     // 如置位,则表明返回代码此时就在 0x60 IO口上等待读取。
-    while (!(io_inb(PS2_PORT_CTRL_STATUS) & PS2_STATUS_OFULL))
+    while (!(port_rdbyte(PS2_PORT_CTRL_STATUS) & PS2_STATUS_OFULL))
         ;
 
-    return io_inb(PS2_PORT_ENC_CMDREG);
+    return port_rdbyte(PS2_PORT_ENC_CMDREG);
+}
+
+static u8_t
+ps2_issue_cmd_wretry(char cmd, u16_t arg)
+{
+    u8_t r, c = 0;
+    while ((r = ps2_issue_cmd(cmd, arg)) == PS2_RESULT_NAK && c < 5) {
+        c++;
+    }
+    if (c >= 5) {
+        kprintf(KWARN "max attempt reached.\n");
+    }
+    return r;
 }
 
 static void
-ps2_post_cmd(uint8_t port, char cmd, uint16_t arg)
+ps2_post_cmd(u8_t port, char cmd, u16_t arg)
 {
     // 等待PS/2输入缓冲区清空,这样我们才可以写入命令
-    while (io_inb(PS2_PORT_CTRL_STATUS) & PS2_STATUS_IFULL)
+    while (port_rdbyte(PS2_PORT_CTRL_STATUS) & PS2_STATUS_IFULL)
         ;
 
-    io_outb(port, cmd);
-    io_delay(PS2_DELAY);
+    port_wrbyte(port, cmd);
+    port_delay(PS2_DELAY);
 
     if (!(arg & PS2_NO_ARG)) {
         // 所有参数一律通过0x60传入。
-        io_outb(PS2_PORT_ENC_CMDREG, (uint8_t)(arg & 0x00ff));
-        io_delay(PS2_DELAY);
+        while (port_rdbyte(PS2_PORT_CTRL_STATUS) & PS2_STATUS_IFULL)
+            ;
+        port_wrbyte(PS2_PORT_ENC_CMDREG, (u8_t)(arg & 0x00ff));
+        port_delay(PS2_DELAY);
     }
 }
 
-static uint8_t
-ps2_issue_dev_cmd(char cmd, uint16_t arg)
+static u8_t
+ps2_issue_dev_cmd(char cmd, u16_t arg)
 {
     ps2_post_cmd(PS2_PORT_ENC_CMDREG, cmd, arg);
 
     // 等待PS/2控制器返回。通过轮询(polling)状态寄存器的 bit 0
     // 如置位,则表明返回代码此时就在 0x60 IO口上等待读取。
-    while (!(io_inb(PS2_PORT_CTRL_STATUS) & PS2_STATUS_OFULL))
+    while (!(port_rdbyte(PS2_PORT_CTRL_STATUS) & PS2_STATUS_OFULL))
         ;
 
-    return io_inb(PS2_PORT_ENC_CMDREG);
-}
-
-int
-kbd_recv_key(struct kdb_keyinfo_pkt* key_event)
-{
-    if (!key_buf.buffered_len) {
-        return 0;
-    }
-
-    mutex_lock(&key_buf.mutex);
-    *key_event = key_buf.buffer[key_buf.read_ptr];
-    key_buf.buffered_len--;
-    key_buf.read_ptr = (key_buf.read_ptr + 1) % PS2_KBD_RECV_BUFFER_SIZE;
-
-    mutex_unlock(&key_buf.mutex);
-    return 1;
-}
-
-static struct kdb_keyinfo_pkt*
-ps2_keybuffer_next_write()
-{
-    int index =
-      (key_buf.read_ptr + key_buf.buffered_len) % PS2_KBD_RECV_BUFFER_SIZE;
-    if (index == key_buf.read_ptr && key_buf.buffered_len) {
-        // the reader is lagged so much such that the buffer is full.
-        // It is suggested to read from beginning for nearly up-to-date
-        // readings.
-        key_buf.read_ptr = 0;
-        key_buf.buffered_len = index;
-    } else {
-        key_buf.buffered_len++;
-    }
-    return &key_buf.buffer[index];
+    return port_rdbyte(PS2_PORT_ENC_CMDREG);
 }
\ No newline at end of file