Lesson 12-Low-Level System Programming

Bootloader and Kernel Initialization

Bootloader

The bootloader is the first software executed after the hardware powers on. It is responsible for initializing critical hardware components (such as memory controllers and serial ports) and loading the kernel from a storage device (e.g., hard disk, USB drive) into memory.

Core Tasks of the Bootloader:

  • Hardware initialization (CPU, memory, storage)
  • Loading the kernel into memory
  • Passing boot parameters
  • Jumping to the kernel entry point

GRUB Multi-stage Boot Process:
Stage1 (MBR) → Stage1.5 (filesystem recognition) → Stage2 (full GRUB)

Custom Bootloader Example (x86):

; Bootsector (512 bytes)
bits 16
org 0x7C00

start:
    cli                     ; Disable interrupts
    xor ax, ax
    mov ds, ax
    mov es, ax
    mov ss, ax
    mov sp, 0x7C00          ; Set stack pointer

    ; Load kernel to 0x10000
    mov ah, 0x02            ; BIOS read sector function
    mov al, 10              ; Read 10 sectors
    mov ch, 0               ; Cylinder 0
    mov cl, 2               ; Starting from sector 2
    mov dh, 0               ; Head 0
    mov bx, 0x1000          ; ES:BX = 0x0000:0x1000
    int 0x13

    ; Jump to kernel
    jmp 0x0000:0x1000

times 510-($-$$) db 0
dw 0xAA55                   ; Bootsector signature

Kernel Entry Point

The kernel entry point is the target address (e.g., _start on x86) to which the bootloader jumps. It is responsible for initializing core kernel components such as memory management, process scheduling, and interrupt systems.

x86 Kernel Initialization Flow:

  • Set up segment registers
  • Initialize page tables
  • Enable paging
  • Initialize interrupt system
  • Start the first process

Kernel Entry Example (32-bit):

; Kernel entry point (entry.asm)
bits 32
section .text
global _start

_start:
    ; Set up segment registers
    mov ax, 0x10            ; Kernel data segment selector
    mov ds, ax
    mov es, ax
    mov fs, ax
    mov gs, ax
    mov ss, ax
    mov esp, 0x90000        ; Kernel stack pointer

    ; Initialize page tables
    call setup_paging

    ; Enable paging
    mov eax, cr0
    or eax, 0x80000000
    mov cr0, eax

    ; Jump to C-language kernel main function
    jmp 0x100000            ; Kernel main function address

Device Driver Development

PCI Device Drivers

Accessing PCI Configuration Space:

; Read PCI configuration space (32-bit mode)
mov dx, 0xCF8               ; PCI configuration space address port
mov eax, 0x80000000 | (bus<<16) | (dev<<11) | (func<<8) | reg
out dx, eax
mov dx, 0xCFC               ; PCI configuration space data port
in eax, dx                  ; Read 32-bit data

PCI Device Enumeration Example:

; Enumerate all PCI devices
mov bx, 0                   ; Start with device number 0

pci_scan_loop:
    mov dx, 0xCF8
    mov eax, 0x80000000 | (bus<<16) | (bx<<8)
    out dx, eax
    mov dx, 0xCFC
    in eax, dx              ; Read vendor ID
    test eax, eax
    jz next_device          ; Vendor ID 0 indicates no device

    ; Found a valid device
    ; ... handle device ...

next_device:
    inc bx
    cmp bx, 32              ; Up to 32 devices per bus
    jl pci_scan_loop

USB Device Drivers (Implemented in Assembly)

Accessing USB Host Controller Registers:

; OHCI host controller register access
mov edx, 0xFE000000         ; OHCI base address
mov eax, [edx+0x04]         ; Read command/status register
or eax, 0x00000001          ; Set run bit
mov [edx+0x04], eax

USB Data Transfer Example:

; Set up bulk transfer endpoint
mov edx, 0xFE000000         ; OHCI base address
mov eax, 0x00000001         ; Endpoint descriptor index
mov [edx+0x10], eax         ; Write to current endpoint register

; Start transfer
mov eax, 0x00000001         ; Control value
mov [edx+0x08], eax         ; Write to control head pointer

Real-Time System Development

RTOS Core Mechanisms

Interrupt Latency Optimization Techniques:

  • Minimize interrupt masking
  • Optimize context switching
  • Optimize memory access

Simple Priority-Based Scheduler Example:

; Simple priority scheduler
schedule:
    cli                     ; Disable interrupts
    mov eax, [current_task]
    mov ebx, [task_list]
    mov ecx, [num_tasks]

find_highest_priority:
    ; ... find highest-priority task ...
    jmp switch_context

switch_context:
    ; Save current task context
    pushad
    mov [eax+CONTEXT_OFFSET], esp

    ; Restore new task context
    mov esp, [ebx+CONTEXT_OFFSET]
    popad
    mov [current_task], ebx
    sti                     ; Enable interrupts
    ret

Interrupt Handling Optimization

Fast Interrupt Handling (FIQ) Example:

; ARM FIQ handler (conceptually similar)
fast_interrupt:
    ; Use dedicated register bank
    ; Minimize register saving
    ; Directly handle critical interrupt
    subs pc, lr, #4         ; Fast return

x86 Interrupt Optimization Techniques:

  • Use IRETQ for fast return
  • Minimize IDT entry processing time
  • Preload frequently used data into cache

System Virtualization Technologies

Hardware Virtualization Support

Intel VT-x Key Instructions:

; Enter VMX operation mode
vmxon [vmxon_region]        ; Enable VMX

; VM entry
vmlaunch                    ; Transition from L0 to L1 VM

; VM exit handling
vmexit                      ; Handle VM exit

VMCS (Virtual Machine Control Structure) Configuration:

; Configure VMCS fields
mov ecx, VMCS_CTRL_PIN_BASED
mov eax, PIN_BASED_INTR_EXIT
vmwrite ecx, eax

mov ecx, VMCS_CTRL_PROC_BASED
mov eax, PROC_BASED_TSC_OFFSET
vmwrite ecx, eax

AMD SVM Virtualization

SVM Key Instructions:

; Enable SVM
mov eax, cr4
or eax, 0x40000
mov cr4, eax

; Enter VM
vmrun [vmcb_gpa]            ; Load VMCB from GPA

; VM exit handling
vmexit

VMCB (Virtual Machine Control Block) Configuration:

; Configure VMCB fields
mov rax, [vmcb_addr]
mov dword [rax+VMCB_CTRL_INTERCEPTS], INTERCEPT_CR0_READ
mov dword [rax+VMCB_CTRL_CR3_TARGET], target_cr3

Comprehensive Development Practices

Complete Kernel Development Workflow

x86_64 Kernel Initialization Example:

; Kernel entry (entry64.asm)
bits 64
section .text
global _start

_start:
    ; Set up segment registers
    mov ax, 0x10
    mov ds, ax
    mov es, ax
    mov fs, ax
    mov gs, ax
    mov ss, ax
    mov rsp, 0x90000        ; Initialize stack pointer

    ; Initialize page tables for long mode
    call setup_long_mode

    ; Enable paging
    mov eax, cr0
    or eax, 0x80000000
    mov cr0, eax

    ; Jump to C-language kernel
    jmp 0xFFFFFFFF80100000  ; Kernel load address

Device Driver Development Framework

PCI Driver Template:

; PCI driver initialization
pci_init:
    ; Enumerate PCI devices
    call pci_scan_bus

    ; Identify target device
    mov eax, [target_device]
    test eax, eax
    jz .no_device

    ; Map I/O space
    call map_io_space

    ; Register interrupt handler
    call register_irq

.no_device:
    ret

Real-Time System Optimization Case Study

Interrupt Latency Measurement Code:

; Measure interrupt response time
measure_latency:
    ; Record start time
    rdtsc
    mov [start_time], eax

    ; Trigger test interrupt
    mov al, 0x20
    out 0x20, al

    ; Wait for interrupt completion
.wait:
    pause
    cmp [irq_done], 1
    jne .wait

    ; Record end time
    rdtsc
    sub eax, [start_time]
    mov [latency], eax
    ret

Virtualization Performance Optimization

VMX Pre-Migration Checks:

; Check CPU virtualization support
mov eax, 0x1
cpuid
test ecx, 0x20000000        ; VMX support bit
jz .no_vmx_support

; Check VMXON capability
mov ecx, 0x480
rdmsr
test eax, 0x2000            ; VMXON flag
jz .no_vmxon_support

SVM Nested Virtualization Configuration:

; Enable nested virtualization
mov eax, cr4
or eax, 0x200000
mov cr4, eax

; Configure VMCB nested controls
mov rax, [vmcb_addr]
or dword [rax+VMCB_NESTED_CTL], NESTED_PAGETABLE

By mastering these core technologies, developers can:

  • Build custom operating system kernels
  • Develop high-performance device drivers
  • Implement real-time system solutions
  • Design virtualization platforms
  • Gain deep understanding of low-level computer system operations
Share your love