Skip to content

Conversation

assembler-0
Copy link
Owner

@assembler-0 assembler-0 commented Jul 8, 2025

Add a bit faster timer and now you can type in the termial

Summary by CodeRabbit

  • New Features

    • Introduced a driver management system with support for registering, initializing, and retrieving drivers.
    • Added a keyboard driver with interrupt-based input handling and buffered key reading.
    • Enhanced print functions for direct screen output at specified coordinates.
  • Improvements

    • Enabled keyboard interrupts and increased timer frequency for more responsive system behavior.
    • Bootloader now displays a "BOOT" message in red during startup for visual feedback.
    • GRUB configuration explicitly sets text mode for consistent boot display.
  • Bug Fixes

    • Reduced kernel busy-wait loops for improved performance and responsiveness.

Copy link

coderabbitai bot commented Jul 8, 2025

Walkthrough

This update introduces a driver management subsystem to the kernel, including a new driver interface, a PS/2 keyboard driver, and registration/initialization logic. The kernel now initializes drivers and enables keyboard interrupts. Fast print functions are made non-inline and exposed via the header. The bootloader and GRUB config are updated for debug output and text mode, respectively.

Changes

File(s) Change Summary
Boot/boot.asm Adds VGA "BOOT" debug output in red before jumping to the kernel.
Kernel/Core/Kernel.c, Kernel/Core/Kernel.h Exposes FastPrint functions, makes them non-inline; adds driver init and keyboard registration; adjusts PIT and IRQ mask; shortens task busy-waits.
Kernel/Drivers/Driver.c, Kernel/Drivers/Driver.h Introduces driver interface, registry, and management functions (register, init, get).
Kernel/Drivers/Keyboard.c Implements PS/2 keyboard driver with interrupt handler, buffer, and registration function.
Kernel/Drivers/Interrupts.c Handles keyboard interrupts using driver interface; updates timer tick display logic.
grub.cfg Sets GRUB graphics payload to text mode for the kernel.
meson.build Adds new driver source files to build configuration.

Sequence Diagram(s)

sequenceDiagram
    participant Bootloader
    participant Kernel
    participant DriverManager
    participant KeyboardDriver
    participant InterruptHandler

    Bootloader->>Kernel: Transfer control (after VGA "BOOT" output)
    Kernel->>DriverManager: DriverRegister(KeyboardDriver)
    Kernel->>DriverManager: DriverInit()
    DriverManager->>KeyboardDriver: init()
    Kernel->>Hardware: Enable IRQ0 (timer) and IRQ1 (keyboard)

    Hardware->>InterruptHandler: Keyboard interrupt (IRQ1)
    InterruptHandler->>DriverManager: DriverGet(DRIVER_KEYBOARD)
    DriverManager-->>InterruptHandler: KeyboardDriver
    InterruptHandler->>KeyboardDriver: handle_interrupt(1)
    KeyboardDriver->>InterruptHandler: (process scancode, buffer key)
    InterruptHandler->>Hardware: Send EOI
Loading

Possibly related PRs

  • Development #10: Both PRs modify the fast print functions in Kernel.c, with this PR making them non-inline and adding driver initialization, while the related PR introduces the fast print functions as static inline and changes timer frequency and task loops.

Poem

In the kernel’s warren, new drivers hop in,
Keyboard clicks echo, let the input begin!
With FastPrints unburrowed and red BOOT aglow,
IRQs now twinkle where interrupts flow.
A rabbit’s delight—new code on display,
🐇 Hopping through drivers, in text-mode we play!

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
Boot/boot.asm (1)

160-166: LGTM! Clean debug output implementation.

The VGA text buffer debug output is correctly implemented. The color attribute 0x04 (red foreground) and character positioning are appropriate for early boot debugging.

Consider defining constants for the color attributes to improve readability:

+; Color attributes
+VGA_RED equ 0x04
+
 ; DEBUG: Write 'BOOT' to VGA before calling C code
 mov rax, 0xb8000
-mov word [rax], 0x0442      ; Red 'B'
-mov word [rax+2], 0x044F    ; Red 'O' 
-mov word [rax+4], 0x044F    ; Red 'O'
-mov word [rax+6], 0x0454    ; Red 'T'
+mov word [rax], (VGA_RED << 8) | 'B'
+mov word [rax+2], (VGA_RED << 8) | 'O'
+mov word [rax+4], (VGA_RED << 8) | 'O'
+mov word [rax+6], (VGA_RED << 8) | 'T'
Kernel/Drivers/Keyboard.c (1)

17-19: Buffer implementation is correct but lacks overflow protection.

The circular buffer implementation is sound, but there's no mechanism to handle or report buffer overflow conditions to the caller.

Consider adding overflow detection:

static char key_buffer[256];
static int buffer_head = 0;
static int buffer_tail = 0;
+static int buffer_overflows = 0;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5e8b547 and 498e013.

📒 Files selected for processing (9)
  • Boot/boot.asm (1 hunks)
  • Kernel/Core/Kernel.c (6 hunks)
  • Kernel/Core/Kernel.h (1 hunks)
  • Kernel/Drivers/Driver.c (1 hunks)
  • Kernel/Drivers/Driver.h (1 hunks)
  • Kernel/Drivers/Interrupts.c (3 hunks)
  • Kernel/Drivers/Keyboard.c (1 hunks)
  • grub.cfg (1 hunks)
  • meson.build (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
Kernel/Drivers/Interrupts.c (1)
Learnt from: assembler-0
PR: assembler-0/VoidFrame#2
File: Kernel/Syscall.c:44-44
Timestamp: 2025-07-08T00:36:50.290Z
Learning: In IdtSetGate function calls, the parameters are: (interrupt_vector, handler_address, selector, flags). The interrupt vector (like 0x80) is the first argument, and the selector (like 0x08 for kernel code segment) is the third argument.
🧬 Code Graph Analysis (2)
Kernel/Drivers/Driver.c (2)
Kernel/Drivers/Driver.h (3)
  • DriverRegister (26-26)
  • DriverInit (27-27)
  • DriverGet (28-28)
Kernel/Core/Panic.h (1)
  • Panic (7-7)
Kernel/Drivers/Interrupts.c (3)
Kernel/Drivers/Driver.h (1)
  • DriverGet (28-28)
Kernel/Drivers/Driver.c (1)
  • DriverGet (25-32)
Kernel/Drivers/Io.h (2)
  • outb (6-8)
  • outb (6-6)
🔇 Additional comments (25)
grub.cfg (1)

5-5: LGTM! Proper graphics payload configuration.

Setting gfxpayload=text correctly aligns with the VGA text buffer approach used in the bootloader debug output.

meson.build (1)

66-67: LGTM! Proper integration of driver subsystem into build.

The new driver source files are correctly added to the build configuration with appropriate file paths.

Kernel/Core/Kernel.h (1)

10-12: LGTM! Well-designed function declarations.

The new fast print function declarations follow consistent naming conventions and provide explicit positioning parameters for direct screen output.

Kernel/Drivers/Driver.c (4)

4-4: LGTM! Reasonable driver capacity limit.

The MAX_DRIVERS limit of 16 is appropriate for a kernel subsystem and provides clear bounds checking.


9-15: LGTM! Robust driver registration with proper error handling.

The function correctly validates input parameters and array bounds, using panic for critical failures which is appropriate in kernel context.


17-23: LGTM! Safe driver initialization implementation.

The function properly iterates through registered drivers and safely checks for the existence of initialization functions before calling them.


25-32: LGTM! Efficient driver retrieval by type.

The linear search approach is appropriate for the expected number of drivers, and returning null for not-found cases follows standard kernel conventions.

Kernel/Drivers/Keyboard.c (3)

48-58: Read function implementation is correct.

The read function properly handles the circular buffer, respects the size limit, and returns the actual number of bytes read.


61-68: Driver structure is well-implemented.

The driver structure correctly implements the interface defined in Driver.h, with appropriate function pointers and a null write function for input-only devices.


71-73: Registration function is correctly implemented.

The registration function properly calls DriverRegister with the driver instance.

Kernel/Drivers/Interrupts.c (5)

5-5: Proper integration with the driver subsystem.

The inclusion of "Driver.h" correctly integrates the interrupt handler with the new driver management system.


35-35: Function signature change is appropriate.

Changing FastDisplayTicks from static inline to static is correct given its usage pattern and the need to expose it through the header.


70-78: Keyboard interrupt handling is well-implemented.

The keyboard interrupt handling correctly:

  • Checks for IRQ1 (remapped to interrupt 33)
  • Retrieves the keyboard driver using DriverGet
  • Validates the driver and handler existence
  • Calls the handler with the correct IRQ number
  • Sends EOI to the PIC

92-94: Scheduling call remains unchanged.

The scheduling call on every timer interrupt maintains system responsiveness despite the reduced tick display frequency.


84-86: Confirm tick display frequency aligns with debugging needs

No code or comments reference the previous 0x3F (64-tick) display rate—only the updated (tick_count & 0x3FF) == 0 remains in Kernel/Drivers/Interrupts.c (lines 84–86).

• Kernel/Drivers/Interrupts.c:84–86 – display now every 1024 ticks (0x3FF)
• No other occurrences of “0x3F”, “64 ticks” or related tick-display documentation found

Please verify that reducing display frequency 16× still meets your debugging and user-experience requirements, and update any external docs or tests accordingly.

Kernel/Drivers/Driver.h (3)

7-13: Driver type enumeration is well-designed.

The enumeration provides clear categorization of driver types and includes a DRIVER_MAX sentinel value for bounds checking and iteration.


16-23: Driver interface structure is comprehensive.

The Driver struct provides a clean interface with:

  • Type identification
  • Human-readable name
  • Initialization function
  • Interrupt handling
  • Read/write operations

This covers the essential operations for most device drivers.


26-28: Driver management functions are appropriately declared.

The function declarations provide the necessary operations for driver lifecycle management:

  • Registration for adding drivers
  • Initialization for setup
  • Retrieval for access by type
Kernel/Core/Kernel.c (7)

13-13: Proper driver subsystem integration.

The inclusion of "Driver.h" correctly integrates the kernel with the new driver management system.


16-17: External function declaration is appropriate.

The declaration of KeyboardRegister() as an external function is correct for the modular driver architecture.


131-131: Function signature changes are correct.

Converting the fast print functions from static inline to regular functions is appropriate given their usage patterns and the need to expose them through the header.

Also applies to: 141-141, 147-147


176-176: Task loop reduction improves scheduling responsiveness.

Reducing the busy-wait loops from larger values to 100 iterations improves task switching responsiveness, which complements the increased timer frequency.

Also applies to: 183-183, 208-208


227-229: Driver initialization is properly integrated.

The driver initialization sequence is correctly placed:

  1. Register the keyboard driver
  2. Initialize all registered drivers

This ensures proper driver system setup.


240-241: Interrupt masking update is correct.

The interrupt masking correctly enables both timer (IRQ0) and keyboard (IRQ1) interrupts by clearing bits 0 and 1 in the PIC mask register.


235-238: Validate high-frequency PIT timer configuration

Running the Programmable Interval Timer at ~4000 Hz (divisor 299) is well above traditional kernel tick rates (100–1000 Hz) and may introduce:

  • Elevated CPU overhead from handling 4000 interrupts/sec
  • Increased power draw on battery-powered or low-end systems
  • Risk of scheduler or driver instability under high interrupt load

Before merging, please verify that:

  • 4 kHz is strictly required for “maximum concurrency” (e.g., link to design doc or benchmark)
  • The scheduler and all interrupt handlers remain stable and performant at this rate
  • Power and real-world performance impacts have been measured on target hardware

Relevant locations:

  • Kernel/Core/Kernel.c (lines ~235–238): PIT setup
  • Kernel/Drivers/Interrupts.c: scheduling on every IRQ

Comment on lines +26 to +46
static void KeyboardInterrupt(uint8_t irq) {
if (irq != 1) return; // IRQ1 = keyboard

uint8_t scancode = inb(KEYBOARD_DATA_PORT);

// Only handle key press (not release)
if (scancode & 0x80) return;

char key = keymap[scancode];
if (key) {
// Add to buffer
int next_head = (buffer_head + 1) % 256;
if (next_head != buffer_tail) {
key_buffer[buffer_head] = key;
buffer_head = next_head;

// Echo key to screen
FastPrintChar(key, 16, (buffer_head % 80));
}
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Potential screen bounds issue in echo functionality.

The echo position calculation (buffer_head % 80) may overwrite other screen content and doesn't account for different screen regions or line wrapping.

Consider implementing proper echo positioning:

            // Echo key to screen
-            FastPrintChar(key, 16, (buffer_head % 80));
+            static int echo_col = 0;
+            FastPrintChar(key, 16, echo_col);
+            echo_col = (echo_col + 1) % 80;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
static void KeyboardInterrupt(uint8_t irq) {
if (irq != 1) return; // IRQ1 = keyboard
uint8_t scancode = inb(KEYBOARD_DATA_PORT);
// Only handle key press (not release)
if (scancode & 0x80) return;
char key = keymap[scancode];
if (key) {
// Add to buffer
int next_head = (buffer_head + 1) % 256;
if (next_head != buffer_tail) {
key_buffer[buffer_head] = key;
buffer_head = next_head;
// Echo key to screen
FastPrintChar(key, 16, (buffer_head % 80));
}
}
}
static void KeyboardInterrupt(uint8_t irq) {
if (irq != 1) return; // IRQ1 = keyboard
uint8_t scancode = inb(KEYBOARD_DATA_PORT);
// Only handle key press (not release)
if (scancode & 0x80) return;
char key = keymap[scancode];
if (key) {
// Add to buffer
int next_head = (buffer_head + 1) % 256;
if (next_head != buffer_tail) {
key_buffer[buffer_head] = key;
buffer_head = next_head;
// Echo key to screen
static int echo_col = 0;
FastPrintChar(key, 16, echo_col);
echo_col = (echo_col + 1) % 80;
}
}
}
🤖 Prompt for AI Agents
In Kernel/Drivers/Keyboard.c between lines 26 and 46, the echo position for
printing the key uses (buffer_head % 80), which can cause overwriting and does
not handle line wrapping or screen regions. To fix this, implement a proper
cursor tracking mechanism that maintains current row and column positions,
updates them correctly on each character printed, and wraps to the next line
when reaching the screen width, ensuring the echo respects screen boundaries and
avoids overwriting unrelated content.

Comment on lines +9 to +15
static char keymap[128] = {
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, ' '
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Incomplete keymap may cause issues with extended keys.

The keymap only covers basic keys up to index 57 (space) but the array is sized for 128 entries. Extended keys, function keys, and other special keys will not be handled properly.

Consider extending the keymap to include commonly used keys:

static char keymap[128] = {
    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, ' '
+    '*', 0, ' ', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // F1-F10 (scancodes 59-68)
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // Additional keys
+    // ... continue for remaining entries
};

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In Kernel/Drivers/Keyboard.c around lines 9 to 15, the keymap array is sized for
128 entries but only partially initialized, missing extended keys, function
keys, and special keys. To fix this, extend the keymap array to include mappings
for all 128 possible scan codes, covering function keys (F1-F12), arrow keys,
and other special keys, ensuring proper handling of all keyboard inputs.

@assembler-0 assembler-0 merged commit f42d819 into main Jul 8, 2025
1 check passed
This was referenced Jul 8, 2025
@coderabbitai coderabbitai bot mentioned this pull request Aug 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant