Skip to content
Open
Show file tree
Hide file tree
Changes from all 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.
## 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
9 changes: 8 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,14 @@ pub(crate) fn install() {
IRQ_NAMES.lock().insert(7, "FPU");
}

pub(crate) fn install_handlers(handlers: InterruptHandlerMap) {
pub(crate) fn install_handlers(#[allow(unused_mut)] mut handlers: InterruptHandlerMap) {

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.

Please move the allow to the function level instead of having it inline like this.

#[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
75 changes: 75 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?

Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
use core::sync::atomic::{AtomicU8, AtomicUsize, Ordering};

use x86_64::instructions::port::Port;

use crate::kernel::interrupts;

const BUFFER_SIZE: usize = 256;
#[allow(clippy::declare_interior_mutable_const)]
const ATOMIC_ZERO: AtomicU8 = AtomicU8::new(0);
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;
const PS2_CNFG_ENABLE_KEYBOARD_INTERRUPT: u8 = 0x01;
const PS2_BUFFER_FULL: u8 = 0x01;

static KEYBOARD_BUFFER: [AtomicU8; BUFFER_SIZE] = [ATOMIC_ZERO; BUFFER_SIZE];
static WRITE_INDEX: AtomicUsize = AtomicUsize::new(0);
static READ_INDEX: AtomicUsize = AtomicUsize::new(0);
Comment on lines +20 to +22

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.

While atomics prevent data races and deadlocks here, I am pretty sure we still have undesirable race conditions or possible data loss like this.

What about having a proper struct behind a mutex for this? That way, we can also use VecDeque instead of having to reimplement one ourselves. You can take a look at the serial input for reference:

static UART_DEVICE: Lazy<InterruptTicketMutex<UartDevice>> =
Lazy::new(|| unsafe { InterruptTicketMutex::new(UartDevice::new()) });
struct UartDevice {
pub uart: Uart16550<PioBackend>,
pub buffer: VecDeque<u8>,
}


pub(crate) fn get_keyboard_handler() -> (u8, fn()) {
unsafe {

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.

Please try to have as few unsafe operations per block as possible. Ideally, only one.

let mut cmd_port = Port::<u8>::new(PS2_CMD_PORT);
let mut data_port = Port::<u8>::new(PS2_DATA_PORT);
Comment on lines +26 to +27

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.

Do you think an abstraction similar to the proposal for BGA would make sense?

struct Ps2;

impl Ps2 {
    fn read_data() -> u8;
    fn write_data(data: u8);
    fn status() -> u8;
    fn command(command: u8);
}

cmd_port.write(PS2_CMD_DISABLE_KEYBOARD);
cmd_port.write(PS2_CMD_DISABLE_MOUSE);

while (cmd_port.read() & PS2_BUFFER_FULL) != 0 {
let _ = data_port.read();
}
Comment on lines +31 to +33

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.

Why do we discard the device buffer instead of filling our read buffer?


cmd_port.write(PS2_CMD_READ_CNFG);
let mut config = data_port.read();

config |= PS2_CNFG_ENABLE_KEYBOARD_INTERRUPT;

cmd_port.write(PS2_CMD_WRITE_CNFG);
data_port.write(config);
cmd_port.write(PS2_CMD_ENABLE_KEYBOARD);
}
fn keyboard_handler() {

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.

Please move the handler to the top level outside of this function.

let mut data_port = Port::<u8>::new(PS2_DATA_PORT);
let scancode = unsafe { data_port.read() };

let write_idx = WRITE_INDEX.load(Ordering::Relaxed);
let next_write_idx = write_idx.wrapping_add(1) % BUFFER_SIZE;

let read_idx = READ_INDEX.load(Ordering::Acquire);
if next_write_idx != read_idx {
KEYBOARD_BUFFER[write_idx].store(scancode, Ordering::Release);
WRITE_INDEX.store(next_write_idx, Ordering::Release);
}
}

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> {
Comment on lines +63 to +64

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.

let read_idx = READ_INDEX.load(Ordering::Relaxed);
let write_idx = WRITE_INDEX.load(Ordering::Acquire);

if read_idx == write_idx {
None
} else {
let scancode = KEYBOARD_BUFFER[read_idx].load(Ordering::Acquire);
READ_INDEX.store(read_idx.wrapping_add(1) % BUFFER_SIZE, Ordering::Release);
Some(scancode)
}
}
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