Page 1 of 1

Task switching causing random errors

Posted: Mon Sep 29, 2025 2:18 pm
by boredcoder411
I recently tried implementing a scheduler in my operating system (github here) and it works fine for the first "pass" over the linked list (its a round robin design). On the second pass however, this is where I get random errors. Sometimes EIP is a very small value, sometimes very large, sometimes I get a #UD exception, sometimes #GP. Its very bizzare. I've tried everything from fixing a bug in the alloc_page() function to writing pusha/popa macros instead of using the instructions. Some help/guidance would be nice, I'll gladly provide extra logs from the serial console if it can help :D

Code: Select all

kernel is running
kernel is running
...
kernirq: 32
task 2
...
tasirq: 32
task 1
...
tasirq: 32
el is running <------ picked up where kernel_task left off!
kernel is running
...
kernel is rirq: 32
exception: 6
 CS=8
 EIP=35
 Error code=0
 Exception message: Invalid opcode
From this output of the different tasks running and switching, I can tell that kernel_task is switching correctly and the pit is firing correctly. But at the end when it goes from kernel_task (root of linked list) to task2 (second node) an exception occurs as described above (#UD, #GP, depends on how the computer is feeling :lol: )

Additional notes: behavior is still random when I use the same build.

Re: Task switching causing random errors

Posted: Mon Sep 29, 2025 4:21 pm
by Octocontrabass
In a typical OS, you have one kernel stack per task, and you switch between tasks by switching between kernel stacks. Whatever you're doing now is not switching between kernel stacks.

There's a pretty good example on the wiki.

Re: Task switching causing random errors

Posted: Tue Sep 30, 2025 4:39 am
by boredcoder411
From my understanding, the iret instruction in the interrupt stub should restore the esp value in the registers_t struct, effectively swapping the stacks, no?

Re: Task switching causing random errors

Posted: Tue Sep 30, 2025 10:35 am
by Octocontrabass
In protected mode, the IRET instruction only pops ESP when returning to a lower privilege (higher CPL). It's also bad design to rely on interrupts for task switching.

Re: Task switching causing random errors

Posted: Wed Oct 01, 2025 12:31 pm
by boredcoder411
I see. Does this mean I need to implement a userland? Or is there a way to keep everything ring 0?

Re: Task switching causing random errors

Posted: Wed Oct 01, 2025 12:38 pm
by nullplan
boredcoder411 wrote: ↑Wed Oct 01, 2025 12:31 pm I see. Does this mean I need to implement a userland? Or is there a way to keep everything ring 0?
The simplest solution is to have a different kernel stack per task and switch accordingly. Then you can switch between different tasks, and those tasks can be kernel threads or userspace threads and it doesn't really matter.