Handle Keyboard Input With a PS/2 Driver
Write a PS/2 keyboard driver for a hobby kernel: the 8042 ports, scancode set 1, make and break codes, the 0xE0 prefix, shift and caps lock, and a ring buffer.

A kernel that can only print is a demonstration. A kernel that reads what you type is a program you can talk to, and the first input device almost every hobby kernel supports is the PS/2 keyboard. It is the simplest real device you will write a driver for: two I/O ports, one interrupt line, a stream of single bytes. It is also a good teaching case, because even this small device has a protocol with prefixes, state and two key events per key. This post builds a complete driver: the controller's ports and status bits, enabling the keyboard, decoding scancode set 1 into key events, tracking the shift, control and caps lock state, handling the extended 0xE0 prefix for arrow keys and a ring buffer that carries characters from the interrupt handler to the rest of the kernel. It assumes the interrupt setup from the 8259 PIC post, or the APIC equivalent, and fits into the guide to interrupts, memory and paging.
The hardware
A PC keyboard connects to the keyboard controller, historically an Intel 8042 chip and today a block inside the chipset that still presents the same interface. The controller has two ports:
| Port | Read | Write |
|---|---|---|
0x60 | Data: a scancode or a command response | Data: a command byte for the keyboard |
0x64 | Status register | Command register, sent to the controller itself |
The status register has bits that you check before every access. Bit 0, the output buffer status, is set when a byte from the keyboard is waiting at port 0x60: read only when it is set. Bit 1, the input buffer status, is set while the controller is still processing a byte you wrote: write only when it is clear. Bit 5 distinguishes mouse data from keyboard data on the second port, which a keyboard-only driver can ignore.
The keyboard raises IRQ 1 when it has a byte for you. After the PIC remap, that is vector 33. The handler runs, reads exactly one byte from port 0x60, and returns. Reading the byte clears the controller's buffer and lets the next one in, so a handler that fails to read causes the keyboard to stall.
Scancodes
Each key press sends one or more bytes, and each key release sends others. The bytes depend on the scancode set the keyboard is using. There are three sets, and modern keyboards start in set 2. The controller, by default, translates set 2 to set 1 before you read it, so what arrives at port 0x60 on a PC is set 1, which is the one used in this post.
In set 1, the code sent when a key goes down, the make code, is a single byte below 0x80. The code sent when the key is released, the break code, is the make code with bit 7 set: the A key makes 0x1E and breaks 0x9E. A held key repeats its make code, which the keyboard generates by itself after a delay, the typematic repeat.
Some keys send a longer sequence starting with 0xE0: the arrow keys, the Insert, Delete, Home, End and Page keys, the right-hand Control and Alt and the keypad's Enter and slash. Pressing the up arrow sends 0xE0 0x48, and releasing it 0xE0 0xC8. A few keys, such as Pause, send longer sequences, which this driver ignores.
The keys needed for a basic driver:
| Key | Make code |
|---|---|
| Left shift | 0x2A |
| Right shift | 0x36 |
| Control | 0x1D |
| Alt | 0x38 |
| Caps lock | 0x3A |
| Enter | 0x1C |
| Backspace | 0x0E |
Up, down, left, right (after 0xE0) | 0x48, 0x50, 0x4B, 0x4D |
Translating codes to characters
A table indexed by the make code gives the character for each key without shift, and a second table gives the shifted character. The tables cover a US layout, the values from 0 up to 0x39:
#include <stdint.h>
static const char map_normal[0x3A] = {
0, 27, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', '\b',
'\t', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\n',
0, 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', '`',
0, '\\', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', 0, '*',
0, ' ',
};
static const char map_shift[0x3A] = {
0, 27, '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '\b',
'\t', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', '\n',
0, 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '"', '~',
0, '|', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?', 0, '*',
0, ' ',
};Each row is laid out as the keyboard is: the first row is Escape, the digits and Backspace, then Tab and the top letter row, then Control (0) and the home row, then the left shift (0), backslash and the bottom row, and finally the right shift (0), keypad star, Alt (0) and space. Entries of 0 mean a key that produces no character, such as a modifier. The index is the make code, so map_normal[0x1E] is 'a'.
The decoder
The decoder is a small state machine, because a scancode byte can only be interpreted together with the bytes before it. It remembers whether the last byte was the 0xE0 prefix and the state of the modifiers:
#define KB_DATA 0x60
#define KB_STATUS 0x64
#define KEY_UP 0x80
static int shift_down;
static int ctrl_down;
static int caps_lock;
static int extended;
/* Special values delivered through the buffer for non-character keys. */
#define KEY_ARROW_UP 0x100
#define KEY_ARROW_DOWN 0x101
#define KEY_ARROW_LEFT 0x102
#define KEY_ARROW_RIGHT 0x103
static void keyboard_push(int key);
void keyboard_irq(void)
{
uint8_t sc = inb(KB_DATA);
if (sc == 0xE0) {
extended = 1;
return;
}
int released = sc & KEY_UP;
uint8_t code = sc & (uint8_t)~KEY_UP;
if (extended) {
extended = 0;
if (!released) {
switch (code) {
case 0x48: keyboard_push(KEY_ARROW_UP); break;
case 0x50: keyboard_push(KEY_ARROW_DOWN); break;
case 0x4B: keyboard_push(KEY_ARROW_LEFT); break;
case 0x4D: keyboard_push(KEY_ARROW_RIGHT); break;
}
}
return;
}
switch (code) {
case 0x2A: case 0x36: shift_down = !released; return;
case 0x1D: ctrl_down = !released; return;
case 0x3A:
if (!released)
caps_lock = !caps_lock;
return;
}
if (released || code >= sizeof(map_normal))
return;
char c = shift_down ? map_shift[code] : map_normal[code];
if (caps_lock && c >= 'a' && c <= 'z')
c = (char)(c - 'a' + 'A');
else if (caps_lock && c >= 'A' && c <= 'Z' && shift_down)
c = (char)(c - 'A' + 'a');
if (ctrl_down && c >= 'a' && c <= 'z')
c = (char)(c - 'a' + 1); /* Ctrl-A is 0x01, and so on */
if (c)
keyboard_push((unsigned char)c);
}The control flow follows the protocol. The 0xE0 prefix is remembered, and the byte after it is interpreted as an extended key. Break codes are recognized by bit 7 and the make code recovered by clearing it. The modifier keys update state when pressed and when released, so that shift is on exactly while the key is held. Caps lock toggles only on the press, since the release would toggle it back. The final steps convert a letter according to caps lock and shift together, caps lock inverting the effect of shift on letters, and turn Ctrl plus a letter into the control character, which is how Ctrl-C and Ctrl-D reach a shell.
The ring buffer
The interrupt handler cannot wait for the consumer, and the consumer cannot read faster than the typist. A ring buffer between them decouples the two: the handler writes at the head, the consumer reads at the tail, and a full buffer drops the new key.
#define KB_BUF_SIZE 128
static volatile int kb_buf[KB_BUF_SIZE];
static volatile unsigned kb_head, kb_tail;
static void keyboard_push(int key)
{
unsigned next = (kb_head + 1) % KB_BUF_SIZE;
if (next == kb_tail)
return; /* full: drop the key */
kb_buf[kb_head] = key;
kb_head = next;
}
int keyboard_getc(void)
{
while (kb_head == kb_tail)
__asm__ volatile ("hlt"); /* sleep until the next interrupt */
int key = kb_buf[kb_tail];
kb_tail = (kb_tail + 1) % KB_BUF_SIZE;
return key;
}With one producer, the interrupt handler, and one consumer, the main code, this needs no lock on a single CPU: the producer only writes kb_head and the consumer only writes kb_tail. Both are volatile so the compiler does not cache them in registers across the loop. The hlt inside the wait is safe only when interrupts are enabled, since otherwise the CPU would sleep forever. A multiprocessor kernel needs atomic operations or a lock here, as in the later posts on synchronization.
Initialization
Most of the time the BIOS has already left the keyboard enabled, but a robust driver checks. A short initialization flushes stale bytes, enables scanning and registers the handler:
static void kb_wait_write(void)
{
while (inb(KB_STATUS) & 0x02)
;
}
void keyboard_init(void)
{
while (inb(KB_STATUS) & 0x01) /* flush anything pending */
(void)inb(KB_DATA);
kb_wait_write();
outb(KB_DATA, 0xF4); /* keyboard command: enable scanning */
/* the keyboard answers 0xFA (ACK), which the interrupt handler will see */
irq_register(1, keyboard_irq);
irq_unmask(1);
}The command 0xF4 tells the keyboard to start sending scancodes. It replies with 0xFA, an acknowledgement, which arrives as a byte at port 0x60 like any other. The decoder sees 0xFA as a make code beyond the table, and it is ignored because of the length check in the decoder. A fuller driver reads and verifies the reply, and also sets the LEDs with command 0xED for caps lock. In QEMU, none of this is needed to receive keys, but on hardware it can be.
A line editor on top shows the pieces working together:
void read_line(char *buf, int max)
{
int n = 0;
for (;;) {
int k = keyboard_getc();
if (k == '\n') {
console_putc('\n');
buf[n] = '\0';
return;
}
if (k == '\b') {
if (n > 0) {
n--;
console_putc('\b');
}
} else if (k < 0x100 && n < max - 1) {
buf[n++] = (char)k;
console_putc((char)k);
}
}
}Typing Hi! with the shift key held for the H and the !, then Enter, prints the characters as they arrive and returns the string Hi!. The key events are: Shift make 0x2A, H make 0x23, H break 0xA3, then i make 0x17 and break 0x97, then 1 with shift held, make 0x02, and so on; every character you see on the screen went through the decoder state.
Testing in QEMU
Run the kernel with QEMU's default graphics window, and click inside it so the window has keyboard focus. QEMU converts your host keystrokes into PS/2 scancodes and delivers them through its emulated controller. With -nographic there is no keyboard device in the window, and input arrives through the serial port instead. For a debugging view, -d int logs each IRQ 1, and printing the raw scancode in hex from the handler is the fastest way to learn the codes your layout produces:
key: 0x23 (H make)
key: 0xA3 (H break)Where this does not fit
PS/2 is a legacy interface. Real machines today have USB keyboards, and the PS/2 controller is emulated by the firmware through USB legacy support until the operating system takes over USB, and some new machines have no PS/2 controller at all. A kernel meant to run on current hardware needs a USB stack, a large project, and until then it works in emulators and on older machines. The tables are for a US layout, and other layouts need different tables and a mechanism for dead keys and AltGr. The scancode set 1 translation depends on the controller's default configuration: a kernel that must be robust reads the controller's configuration byte, command 0x20, and checks that bit 6, translation, is set, or asks the keyboard for its set directly. And keys such as Pause and Print Screen send longer sequences that this decoder does not handle.


