Skip to content

Conversation

assembler-0
Copy link
Owner

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

Summary by CodeRabbit

  • New Features

    • Improved kernel memory reservation and mapping, ensuring more precise handling of physical and virtual memory.
    • Added support for explicit mapping of kernel memory into the higher-half virtual address space.
    • Introduced new assembly and utility functions for enabling paging and retrieving page table addresses.
  • Refactor

    • Streamlined kernel initialization sequence for better clarity and separation of concerns.
  • Chores

    • Updated build configuration to include new assembly helper routines.
  • Style

    • Minor adjustments to kernel print messages for improved informational output.

Copy link

coderabbitai bot commented Jul 14, 2025

Walkthrough

This update refactors the kernel initialization process by splitting system setup into bootstrap and higher-half stages, introduces explicit page table mapping routines, and adds new assembly helpers for paging. It also improves memory reservation logic, defines kernel memory boundaries in the linker script, and introduces new macros and function prototypes for virtual memory management.

Changes

File(s) Change Summary
drivers/Pic.h PIT_FREQUENCY_HZ macro changed from 1000 to 100.
kernel/core/Kernel.c Refactored kernel initialization: split into bootstrap and higher-half, added BootstrapMapPage, updated flow.
kernel/memory/AsmHelpers.asm, AsmHelpers.h Added EnablePagingAndJump assembly function and its header declaration.
kernel/memory/Memory.c Improved memory reservation: uses linker symbols for kernel, reserves first 1MB and multiboot info memory.
kernel/memory/VMem.c, VMem.h Added VMemMapKernel and VMemGetPML4PhysAddr functions; new macros for kernel virtual offset and address mask.
linker.ld Added _kernel_phys_start and _kernel_phys_end symbols to mark kernel memory boundaries.
meson.build Included AsmHelpers.asm in assembly sources list.

Sequence Diagram(s)

sequenceDiagram
    participant Bootloader
    participant KernelMain
    participant Memory
    participant VMem
    participant AsmHelpers
    participant KernelMainHigherHalf

    Bootloader->>KernelMain: Jump to KernelMain
    KernelMain->>Memory: MemoryInit()
    KernelMain->>VMem: VMemInit()
    KernelMain->>VMem: VMemGetPML4PhysAddr()
    KernelMain->>KernelMain: BootstrapMapPage() (map kernel and low memory)
    KernelMain->>AsmHelpers: EnablePagingAndJump(pml4_phys, KernelMainHigherHalf)
    AsmHelpers-->>KernelMainHigherHalf: Jump to higher-half
    KernelMainHigherHalf->>KernelMainHigherHalf: CoreInit()
    KernelMainHigherHalf->>KernelMainHigherHalf: Start kernel scheduler loop
Loading

Possibly related PRs

  • Development #26: Modifies the PIT_FREQUENCY_HZ macro in drivers/Pic.h, similar to this PR, indicating a direct relation in timer frequency management.

Poem

In the warren of code, the kernel awoke,
With new page tables mapped—no more a joke!
Memory reserved, and helpers in place,
The rabbit now hops through virtual space.
From low to high, with a swift little jump,
Paging enabled—thump, thump, thump!
🐇✨

✨ 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: 1

🧹 Nitpick comments (1)
kernel/memory/VMem.h (1)

91-92: Consider clarifying the distinction between KERNEL_VIRTUAL_BASE and KERNEL_VIRTUAL_OFFSET.

Both macros define kernel virtual addresses but serve different purposes. KERNEL_VIRTUAL_BASE (0xFFFF800000000000ULL) appears to be for general kernel virtual space, while KERNEL_VIRTUAL_OFFSET (0xFFFFFFFF80000000ULL) is specifically for the higher-half kernel mapping. Consider adding comments to clarify their distinct uses.

+// Higher-half kernel mapping offset for physical-to-virtual conversion
 #define KERNEL_VIRTUAL_OFFSET 0xFFFFFFFF80000000ULL
+// Page table address mask for extracting physical addresses
 #define PT_ADDR_MASK        0x000FFFFFFFFFF000ULL
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7435f41 and ab4f286.

📒 Files selected for processing (9)
  • drivers/Pic.h (1 hunks)
  • kernel/core/Kernel.c (5 hunks)
  • kernel/memory/AsmHelpers.asm (1 hunks)
  • kernel/memory/AsmHelpers.h (1 hunks)
  • kernel/memory/Memory.c (3 hunks)
  • kernel/memory/VMem.c (3 hunks)
  • kernel/memory/VMem.h (2 hunks)
  • linker.ld (2 hunks)
  • meson.build (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
kernel/memory/Memory.c (2)
kernel/core/Kernel.h (2)
  • PrintKernel (5-5)
  • PrintKernelInt (7-7)
kernel/core/Kernel.c (2)
  • PrintKernel (135-146)
  • PrintKernelInt (194-218)
kernel/core/Kernel.c (8)
kernel/memory/Memory.c (2)
  • AllocPage (139-150)
  • MemoryInit (40-136)
kernel/memory/Memory.h (2)
  • AllocPage (10-10)
  • MemoryInit (9-9)
kernel/core/Panic.h (1)
  • Panic (7-7)
kernel/memory/MemOps.h (1)
  • FastZeroPage (9-9)
kernel/memory/MemOps.c (1)
  • FastZeroPage (63-77)
kernel/memory/VMem.h (2)
  • VMemInit (94-94)
  • VMemGetPML4PhysAddr (115-115)
kernel/memory/VMem.c (2)
  • VMemInit (41-61)
  • VMemGetPML4PhysAddr (401-403)
kernel/memory/AsmHelpers.h (1)
  • EnablePagingAndJump (3-3)
🔇 Additional comments (19)
drivers/Pic.h (1)

4-4: Verify the impact of reducing timer frequency by 10x.

The timer interrupt frequency has been reduced from 1000 Hz to 100 Hz, which significantly affects system timing granularity. This change could impact:

  • Scheduler time slicing and process responsiveness
  • Time-sensitive kernel operations
  • System call timing expectations

Please ensure this frequency reduction aligns with the system's timing requirements and doesn't negatively impact user experience.

linker.ld (2)

10-10: LGTM: Kernel physical start boundary correctly defined.

The placement of _kernel_phys_start immediately after setting the base address to 1MB is correct for marking the beginning of the kernel's physical memory region.


39-39: LGTM: Kernel physical end boundary correctly defined.

The placement of _kernel_phys_end after the BSS section correctly marks the end of the kernel's physical memory region, capturing the entire kernel image.

meson.build (1)

59-59: LGTM: Assembly helper correctly added to build configuration.

The addition of AsmHelpers.asm to the assembly sources list ensures the new paging helper function is properly compiled and linked into the kernel.

kernel/memory/AsmHelpers.h (1)

1-3: LGTM: Header correctly declares the assembly helper function.

The function declaration and includes are correct. The header properly defines the interface for the paging enablement helper.

kernel/memory/VMem.h (2)

99-99: Function prototype looks correct for kernel memory mapping.

The VMemMapKernel function signature properly takes physical start and end addresses, which aligns with the refactoring goal of mapping kernel memory into the higher-half virtual address space.


115-115: Function prototype correctly supports the new paging initialization flow.

The VMemGetPML4PhysAddr function provides the physical address of the PML4 table, which is essential for the assembly helper EnablePagingAndJump to enable paging.

kernel/memory/Memory.c (4)

10-11: Linker symbol declarations are correctly defined.

The extern declarations for _kernel_phys_start and _kernel_phys_end properly reference the linker script symbols as uint8_t[] arrays, which is the standard approach for linker-provided boundaries.


105-108: Improved memory reservation with proper documentation.

The explicit reservation of the first 1MB with informational logging is a good practice for debugging and system transparency.


110-125: Excellent improvement to kernel memory reservation precision.

Using linker-provided symbols _kernel_phys_start and _kernel_phys_end instead of estimating kernel size is much more accurate and robust. The informational logging helps with debugging.


127-133: Good practice to reserve multiboot info memory.

Explicitly reserving the multiboot information structure prevents it from being overwritten during normal memory allocation operations.

kernel/memory/VMem.c (3)

339-363: Well-implemented kernel memory mapping function.

The VMemMapKernel function correctly:

  • Aligns addresses to page boundaries
  • Maps physical kernel memory to higher-half virtual addresses using KERNEL_VIRTUAL_OFFSET
  • Uses appropriate page flags (PAGE_WRITABLE)
  • Provides informational logging
  • Handles mapping failures with a panic

The implementation integrates well with the two-stage initialization flow.


398-398: Missing closing brace fix is correct.

The addition of the closing brace for the VMemGetStats function resolves a syntax error.


401-403: Simple and correct PML4 address retrieval.

The VMemGetPML4PhysAddr function properly returns the physical address of the kernel's PML4 table, which is essential for the assembly helper EnablePagingAndJump.

kernel/core/Kernel.c (5)

16-21: Proper includes and declarations for the refactoring.

The addition of AsmHelpers.h, MemOps.h, and the linker symbol declarations correctly support the new two-stage initialization flow.


312-357: Well-implemented bootstrap page table setup function.

The BootstrapMapPage function correctly implements the x86-64 page table hierarchy:

  • Properly calculates indices for each level (PML4, PDPT, PD, PT)
  • Allocates and zeros new page tables as needed
  • Uses appropriate flags (PAGE_PRESENT | PAGE_WRITABLE)
  • Handles memory allocation failures with panic

The direct pointer dereferencing is acceptable during bootstrap since identity mapping is available.


359-385: Good separation of concerns with CoreInit function.

Moving the core subsystem initialization (GDT, IDT, syscalls, PIC, process management) into a separate function improves code organization and supports the two-stage initialization flow.


402-425: Excellent implementation of the bootstrap stage.

The bootstrap initialization correctly:

  1. Initializes memory management first
  2. Sets up virtual memory and gets PML4 address
  3. Maps kernel memory to higher-half virtual addresses
  4. Identity maps low memory for VGA and other hardware
  5. Enables paging and jumps to higher-half kernel

The sequence is logical and necessary for proper virtual memory setup.


427-450: Proper higher-half initialization sequence.

The KernelMainHigherHalf function correctly:

  • Calls CoreInit() to initialize core subsystems
  • Creates the security manager process
  • Enables interrupts
  • Enters the main scheduling loop

The two-stage approach ensures that core subsystems are initialized after virtual memory is fully operational.

global EnablePagingAndJump

EnablePagingAndJump:
mov rdi, cr3
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical bug: Incorrect CR3 register operation.

The assembly code is moving the current CR3 value to RDI instead of setting CR3 with the provided PML4 physical address. This completely breaks the paging enablement functionality.

Apply this fix:

-    mov rdi, cr3
+    mov cr3, rdi

The function should set CR3 to the first parameter (pml4_phys_addr in RDI), not read from CR3.

🤖 Prompt for AI Agents
In kernel/memory/AsmHelpers.asm at line 5, the code incorrectly moves the CR3
register value into RDI instead of setting CR3. To fix this, replace the
instruction so that CR3 is set to the value in RDI (the first parameter
pml4_phys_addr), ensuring the paging enablement works correctly.

@assembler-0 assembler-0 merged commit c8c2f78 into main Jul 14, 2025
1 check passed
This was referenced Jul 14, 2025
@coderabbitai coderabbitai bot mentioned this pull request Aug 11, 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