Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,15 @@ virtio-vsock = ["virtio"]
## This is only useful on PCs (x86-64).
vga = []

## Enables the PS/2 keyboard driver.
##
## This feature initializes the PS/2 keyboard controller and installs a keyboard interrupt handler.
## It also provides a system call to receive the last scancode from the internal keyboard buffer.
## Note that this is not a complete keyboard driver and not needed for general keyboard support.
Comment thread
GloriousAlpaca marked this conversation as resolved.
Outdated
## It allows receiving scancodes from the PS/2 keyboard that can be used to port applications.
## This is only useful on PCs (x86-64).
pc-keyboard = []

#! ### Performance Features

## Disables putting the CPU to sleep.
Expand Down
11 changes: 10 additions & 1 deletion src/arch/x86_64/kernel/interrupts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,16 @@ pub(crate) fn install() {
IRQ_NAMES.lock().insert(7, "FPU");
}

pub(crate) fn install_handlers(handlers: InterruptHandlerMap) {
#[allow(unused_mut)]
pub(crate) fn install_handlers(mut handlers: InterruptHandlerMap) {
#[cfg(feature = "pc-keyboard")]
{
use crate::arch::kernel::pc_keyboard::get_keyboard_handler;

let (irq, handler) = get_keyboard_handler();
handlers.entry(irq).or_default().push_back(handler);
}

IRQ_HANDLERS.set(handlers).unwrap();
}

Expand Down
2 changes: 2 additions & 0 deletions src/arch/x86_64/kernel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ pub mod interrupts;
pub mod kernel_stack;
#[cfg(all(not(feature = "pci"), feature = "virtio"))]
pub mod mmio;
#[cfg(feature = "pc-keyboard")]
pub mod pc_keyboard;
#[cfg(feature = "pci")]
pub mod pci;
pub mod pic;
Expand Down
85 changes: 85 additions & 0 deletions src/arch/x86_64/kernel/pc_keyboard.rs

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would the pc-keyboard crate help here in any way? I'd like to avoid reimplementing logic if the ecosystem already has a well-established crate for (parts of) this.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I took a look at the crate and the following stood out to me:

There are three basic steps to handling keyboard input. Your application may bypass some of these.

  • Ps2Decoder - converts 11-bit PS/2 words into bytes, removing the start/stop bits and checking the parity bits. Only needed if you talk to the PS/2 keyboard over GPIO pins and not required if you talk to the i8042 PC keyboard controller.
  • ScancodeSet - converts from Scancode Set 1 (i8042 PC keyboard controller) or Scancode Set 2 (raw PS/2 keyboard output) into a symbolic KeyCode and an up/down KeyState.
  • EventDecoder - converts symbolic KeyCode and KeyState into a Unicode characters (where possible) according to the currently selected KeyboardLayout.

We actually don't need the first step because we are using the i8042 keyboard controller.
The other two steps look promising, but I actually would not put them into the kernel driver itself, but rather into the application.
I mainly implemented this driver to use with the doom port I'm currently working on, where I have to translate the keys anyways, which makes it irrelevant if it's scancodes or keycodes. If we pre-translate in the kernel we would also have to handle different keyboard layouts, which I feel would overcomplicate this pretty simple driver, especially because Qemu might emulate a different layout than the host. It also seems to me like something the application itself should handle instead of the driver. What do you think?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with @GloriousAlpaca. This is not something for the kernel.

Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
use alloc::collections::VecDeque;

use hermit_sync::{InterruptTicketMutex, Lazy};
use x86_64::instructions::port::Port;

use crate::kernel::interrupts;

const PS2_DATA_PORT: u16 = 0x60;
const PS2_CMD_PORT: u16 = 0x64;
const PS2_CMD_READ_CNFG: u8 = 0x20;
const PS2_CMD_WRITE_CNFG: u8 = 0x60;
const PS2_CMD_DISABLE_KEYBOARD: u8 = 0xad;
const PS2_CMD_DISABLE_MOUSE: u8 = 0xa7;
const PS2_CMD_ENABLE_KEYBOARD: u8 = 0xae;
Comment thread
GloriousAlpaca marked this conversation as resolved.
Outdated
const PS2_CNFG_ENABLE_KEYBOARD_INTERRUPT: u8 = 0x01;
const PS2_BUFFER_FULL: u8 = 0x01;

const BUFFER_SIZE: usize = 256;
struct Ps2;

Comment thread
GloriousAlpaca marked this conversation as resolved.
Outdated
impl Ps2 {
pub fn read_status() -> u8 {
let mut status_port = Port::<u8>::new(PS2_CMD_PORT);
unsafe { status_port.read() }
Comment thread
GloriousAlpaca marked this conversation as resolved.
Outdated
}

pub fn write_cmd(cmd: u8) {
let mut cmd_port = Port::<u8>::new(PS2_CMD_PORT);
unsafe { cmd_port.write(cmd) }
}

pub fn read_data() -> u8 {
let mut data_port = Port::<u8>::new(PS2_DATA_PORT);
unsafe { data_port.read() }
}

pub fn write_data(data: u8) {
let mut data_port = Port::<u8>::new(PS2_DATA_PORT);
unsafe { data_port.write(data) }
}
}

static KEYBOARD_BUFFER: Lazy<InterruptTicketMutex<VecDeque<u8>>> =
Lazy::new(|| InterruptTicketMutex::new(VecDeque::with_capacity(BUFFER_SIZE)));

fn keyboard_handler() {
let scancode = Ps2::read_data();
let mut buffer = KEYBOARD_BUFFER.lock();

if buffer.len() >= BUFFER_SIZE {
buffer.pop_front();
}
buffer.push_back(scancode);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if retaining the keys in the queue is how this is handled best. I'm thinking that maybe adding a timestamp to each key event and discarding it after x seconds is a correct approach. But maybe I'm prematurely optimizing this. It would be interesting to know how other systems are handling this.

}

pub(crate) fn get_keyboard_handler() -> (u8, fn()) {
Ps2::write_cmd(PS2_CMD_DISABLE_KEYBOARD);
Ps2::write_cmd(PS2_CMD_DISABLE_MOUSE);
// Ensure an empty buffer to guard against stuck data
while (Ps2::read_status() & PS2_BUFFER_FULL) != 0 {
let _ = Ps2::read_data();
}

Ps2::write_cmd(PS2_CMD_READ_CNFG);
let mut config = Ps2::read_data();

config |= PS2_CNFG_ENABLE_KEYBOARD_INTERRUPT;

Ps2::write_cmd(PS2_CMD_WRITE_CNFG);

Ps2::write_data(config);
Ps2::write_cmd(PS2_CMD_ENABLE_KEYBOARD);

// Force the initialization of the keyboard buffer to ensure it is ready before any interrupts occur.
Lazy::force(&KEYBOARD_BUFFER);

interrupts::add_irq_name(1, "PS/2 Keyboard");

(1, keyboard_handler)
}

/// Pops a scancode from the keyboard buffer, returning None if the buffer is empty.
pub fn pop_scancode() -> Option<u8> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A scancode can never be zero, right? Returning Option<NonZero<u8>> would be preferable in that case.

KEYBOARD_BUFFER.lock().pop_front()
}
7 changes: 7 additions & 0 deletions src/syscalls/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,10 @@ use crate::arch::mm::paging::{BasePageSize, PageSize};
pub extern "C" fn sys_getpagesize() -> i32 {
BasePageSize::SIZE.try_into().unwrap()
}

#[cfg(all(target_arch = "x86_64", feature = "pc-keyboard"))]
#[hermit_macro::system]
#[unsafe(no_mangle)]
pub extern "C" fn sys_read_keyboard() -> u8 {
crate::kernel::pc_keyboard::pop_scancode().unwrap_or(0)
}
Loading