Kernel Stack Management
When an interrupt or exception occurs in user mode
- Saves Return Address into Stack (IP+2).
- Switches the Mode
- Transfer the Control to the Interrupt Service Routine (ISR) or Exception Handler

The Kernel Stack will be 0 upon entering and exiting the kernel mode * The offset within the User Area Page is stored as KPTR*
Note - At this exact moment, the SP is still pointing to the User Stack.
Kernel Actions Upon Entering the Handler (The Switch)
Kernel Stack 1) Switch the Kernel Stack
// The kernel saves the current SP register into the UPTR field of the Process Table
MOV UPTR, SP
// The Kernel sets the SP register to Kernel Stack
MOV SP, User Area Page Number * 512 - 1 // the SP will increase by 1 before push
2) Save Register Context
Using BACKUP Instruction, the kernel pushes all the user-accessible registers to the Kernel Stack (R0-R19, IP, etc.) (So that after the switch, the program can start from the moment in got switched.)
Kernel Actions Before Returning to User
1) Restore the Context
RESTORE instruction pops the saved register values from the Kernel stack back the CPU registers
2) Switch Back to the User Stack
MOV SP, UPTR
IRET
// on IRET instruction, the execution starts from the original
The return address for the User Stack back into the IP
Switches back to User Mode
Process continues executing the next instruction.
Note
- The UPTR stores the physical address of the user stack whereas the KPTR stores the offset. (Sot that the page can be moved freely if required)
- As User Stack can span multiple pages, logical addressing is preferred
Software Interrupts
sequenceDiagram
participant U as User Program (User Mode)
participant US as User Stack
participant KS as Kernel Stack
participant K as Interrupt Handler (Kernel Mode)
Note over U, US: 1. PRE-CALL (User Mode)
U->>US: Push Registers (R0 - R15)
U->>US: Push System Call Number
U->>US: Push Arguments (Arg1, Arg2, Arg3)
U->>US: Push Empty Space for Return Value
Note over U, K: INT Instruction Executed
U->>US: IP + 2 (Return Address) pushed by Hardware
U->>K: CPU Switches to Kernel Mode
Note over K, KS: 2. ENTRY (Kernel Mode)
K->>K: Save User SP to UPTR (Process Table)
K->>K: Switch SP to Kernel Stack (User Area Page * 512 - 1)
K->>K: Set MODE Flag in Process Table
Note over K, US: 3. EXECUTION
K->>US: Extract Syscall No. & Args (using UPTR offset)
K->>K: Execute System Call Logic
Note over K, US: 4. EXIT (Kernel Mode)
K->>US: Store Return Value at [UPTR - 1]
K->>K: Reset MODE Flag to 0
K->>K: Switch SP back to UPTR (User Stack)
Note over K, U: IRET Instruction Executed
K->>U: Pop IP from User Stack
K->>U: CPU Switches to User Mode
Note over U, US: 5. POST-CALL (User Mode)
U->>US: Pop Return Value into Register
U->>US: Pop & Discard Args and Syscall No.
U->>US: Restore Registers (R0 - R15)
U->>U: Resume Execution