]> Projects (at) Tadryanom (dot) Me - AdrOS.git/commitdiff
tty: add nonblocking stdin (fd 0) via ring buffer
authorTulio A M Mendes <[email protected]>
Sat, 7 Feb 2026 18:54:15 +0000 (15:54 -0300)
committerTulio A M Mendes <[email protected]>
Sat, 7 Feb 2026 18:54:15 +0000 (15:54 -0300)
include/keyboard.h
src/drivers/keyboard.c
src/kernel/syscall.c

index bf61554a85235ee1ac6840438d665d23d6095653..9542aeb641a3debe9a42d87dc5c433a6722edfcc 100644 (file)
@@ -9,4 +9,6 @@ typedef void (*keyboard_callback_t)(char);
 void keyboard_init(void);
 void keyboard_set_callback(keyboard_callback_t callback);
 
+int keyboard_read_nonblock(char* out, uint32_t max_len);
+
 #endif
index 5d544ef87225aa0617f3c81aa0371381c0c1d3db..4011f91ca36842e1cdf0327f4e0c9cab219c321b 100644 (file)
@@ -6,7 +6,22 @@
 
 static keyboard_callback_t active_callback = NULL;
 
+#define KBD_BUF_SIZE 256
+static volatile uint32_t kbd_head = 0;
+static volatile uint32_t kbd_tail = 0;
+static char kbd_buf[KBD_BUF_SIZE];
+
+static void kbd_push_char(char c) {
+    uint32_t next = (kbd_head + 1U) % KBD_BUF_SIZE;
+    if (next == kbd_tail) {
+        kbd_tail = (kbd_tail + 1U) % KBD_BUF_SIZE;
+    }
+    kbd_buf[kbd_head] = c;
+    kbd_head = next;
+}
+
 static void hal_kbd_bridge(char c) {
+    kbd_push_char(c);
     if (active_callback) {
         active_callback(c);
     }
@@ -14,9 +29,23 @@ static void hal_kbd_bridge(char c) {
 
 void keyboard_init(void) {
     uart_print("[KBD] Initializing Keyboard Driver...\n");
+    kbd_head = 0;
+    kbd_tail = 0;
     hal_keyboard_init(hal_kbd_bridge);
 }
 
 void keyboard_set_callback(keyboard_callback_t callback) {
     active_callback = callback;
 }
+
+int keyboard_read_nonblock(char* out, uint32_t max_len) {
+    if (!out || max_len == 0) return 0;
+
+    uint32_t count = 0;
+    while (count < max_len) {
+        if (kbd_tail == kbd_head) break;
+        out[count++] = kbd_buf[kbd_tail];
+        kbd_tail = (kbd_tail + 1U) % KBD_BUF_SIZE;
+    }
+    return (int)count;
+}
index 0b54f5fec96269674d79322c566dcf88a13ca177..fc18743ef94ece45a2c577ada969356623ff1dfd 100644 (file)
@@ -2,6 +2,8 @@
 #include "idt.h"
 #include "fs.h"
 #include "heap.h"
+#include "keyboard.h"
+#include "keyboard.h"
 #include "process.h"
 #include "uart_console.h"
 #include "uaccess.h"
@@ -81,6 +83,18 @@ static int syscall_read_impl(int fd, void* user_buf, uint32_t len) {
     if (len > 1024 * 1024) return -1;
     if (user_range_ok(user_buf, (size_t)len) == 0) return -1;
 
+    if (fd == 0) {
+        char kbuf[256];
+        uint32_t chunk = len;
+        if (chunk > sizeof(kbuf)) chunk = (uint32_t)sizeof(kbuf);
+        int rd = keyboard_read_nonblock(kbuf, chunk);
+        if (rd <= 0) return 0;
+        if (copy_to_user(user_buf, kbuf, (size_t)rd) < 0) return -1;
+        return rd;
+    }
+
+    if (fd == 1 || fd == 2) return -1;
+
     struct file* f = fd_get(fd);
     if (!f || !f->node) return -1;