Skip to main content

os/task/
keyboard.rs

1/*
2 * ============================================
3 * RISC-V 键盘输入模块
4 * ============================================
5 * 功能:处理键盘输入(通过 SBI console)
6 *
7 * RISC-V 键盘输入方案:
8 * - 使用 SBI (Supervisor Binary Interface) 的 console_getchar
9 * - 轮询方式读取字符
10 * - 支持异步任务
11 * ============================================
12 */
13
14use alloc::collections::VecDeque;
15use conquer_once::spin::OnceCell;
16use core::pin::Pin;
17use core::task::{Context, Poll};
18use futures_util::stream::Stream;
19use futures_util::task::AtomicWaker;
20use spin::Mutex;
21
22/// 扫描码队列(用于存储输入字符)
23static SCANCODE_QUEUE: OnceCell<Mutex<VecDeque<u8>>> = OnceCell::uninit();
24
25/// 唤醒器
26static WAKER: AtomicWaker = AtomicWaker::new();
27
28/// 添加字符到队列
29///
30/// # 功能
31/// - 被输入处理器调用
32/// - 不能阻塞或分配内存
33pub(crate) fn add_scancode(scancode: u8) {
34    if let Ok(queue) = SCANCODE_QUEUE.try_get() {
35        queue.lock().push_back(scancode);
36        WAKER.wake(); // 唤醒等待的任务
37    }
38    // 如果队列未初始化,静默忽略(在键盘任务启动前可能发生)
39}
40
41/// 扫描码流(实现 Stream trait)
42pub struct ScancodeStream {
43    _private: (),
44}
45
46impl ScancodeStream {
47    /// 创建新的扫描码流
48    pub fn new() -> Self {
49        // 尝试初始化队列,如果已经初始化则忽略错误
50        let _ = SCANCODE_QUEUE.try_init_once(|| Mutex::new(VecDeque::new()));
51        ScancodeStream { _private: () }
52    }
53}
54
55impl Default for ScancodeStream {
56    fn default() -> Self {
57        Self::new()
58    }
59}
60
61impl Stream for ScancodeStream {
62    type Item = u8;
63
64    fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<u8>> {
65        let queue = SCANCODE_QUEUE
66            .try_get()
67            .expect("scancode queue not initialized");
68
69        // 尝试从队列中读取
70        if let Some(scancode) = queue.lock().pop_front() {
71            return Poll::Ready(Some(scancode));
72        }
73
74        // 注册唤醒器
75        WAKER.register(cx.waker());
76
77        // 再次检查(防止竞争条件)
78        match queue.lock().pop_front() {
79            Some(scancode) => {
80                WAKER.take();
81                Poll::Ready(Some(scancode))
82            }
83            None => Poll::Pending,
84        }
85    }
86}
87
88/// SBI console getchar
89///
90/// # 返回
91/// - Some(char): 读取到的字符
92/// - None: 没有可用字符
93fn sbi_console_getchar() -> Option<u8> {
94    let ret: isize;
95    unsafe {
96        core::arch::asm!(
97            "li a7, 2",      // SBI extension ID: Console Getchar (legacy)
98            "ecall",
99            "mv {}, a0",     // 返回值在 a0
100            out(reg) ret,
101            options(nostack)
102        );
103    }
104
105    if ret >= 0 {
106        Some(ret as u8)
107    } else {
108        None
109    }
110}
111
112/// Try to pop a character from the scan-code queue (non-blocking).
113/// Returns None if the queue is empty or not yet initialized.
114pub fn try_pop_char() -> Option<u8> {
115    if let Ok(queue) = SCANCODE_QUEUE.try_get() {
116        queue.lock().pop_front()
117    } else {
118        None
119    }
120}
121
122/// 轮询键盘输入
123///
124/// # 功能
125/// - 定期调用以检查键盘输入
126/// - 应该在定时器中断中调用
127/// - 限制每次最多读取的字符数,防止阻塞
128pub fn poll_keyboard() {
129    // 限制每次中断最多读取 10 个字符,防止无限循环
130    const MAX_READS_PER_POLL: usize = 10;
131
132    for _ in 0..MAX_READS_PER_POLL {
133        if let Some(ch) = sbi_console_getchar() {
134            add_scancode(ch);
135        } else {
136            // 没有更多字符可读,退出
137            break;
138        }
139    }
140}
141
142/// 异步键盘任务
143///
144/// # 功能
145/// - 持续读取键盘输入并显示
146pub async fn print_keypresses() {
147    use futures_util::stream::StreamExt;
148
149    crate::serial_println!("[KEYBOARD] Keyboard input task started (SBI console)");
150    crate::println!("[KEYBOARD] Press keys to test...");
151
152    let mut scancodes = ScancodeStream::new();
153
154    while let Some(scancode) = scancodes.next().await {
155        // 处理特殊字符
156        match scancode {
157            b'\r' | b'\n' => {
158                crate::println!();
159            }
160            0x08 | 0x7f => {
161                // Backspace
162                crate::print!("\x08 \x08");
163            }
164            0x20..=0x7e => {
165                // 可打印 ASCII 字符
166                crate::print!("{}", scancode as char);
167            }
168            _ => {
169                // 其他字符显示为十六进制
170                crate::print!("[{:02x}]", scancode);
171            }
172        }
173    }
174}
175
176/// 键盘输入循环(用于定时器中断)
177///
178/// # 功能
179/// - 在定时器中断中调用此函数
180/// - 轮询 SBI console 获取输入
181pub fn keyboard_interrupt_handler() {
182    poll_keyboard();
183}