|
|
About ::
TODO ::
Blog ::
RSS ::
Old blog ::
Projects ::
GIT ::
Gallery ::
Notes
Tue, 23 Jan 2007
True context switching in userspace.
After some thinking, I've understood, that setcontext()
approach does not allow to have real context switching - when this function is called,
context is restored from the point where getcontext()/makecontext()
was called last time, so even if one have possibility to restore new context, context being removed
must save its state by itself - obviously no one will do it. So this approach will not be used
at all in my context switching implementation (although I will check getcontext()/makecontext()s
sources, since they contain needed bits).
Let's slightly move away from topic and concentrate on how signals work.
According to my knowledge, signal is just a call for some function in stack -
kernel saves needed context, setups small region on stack of currently executed thread,
saves current context
and calls a special function which ends up with registered handler invocation.
(Interesting note for investigation - how do signals work with non-executable stack -
likely special page is allocated for that purpose, but if it is so, then there is a way
to write explits which can run on stack even when system setups it to be non-executable).
Signal handler can not be reentered, when it is exiting, it restores previous context,
thus creating real context switching.
Returning back to our topic - scheduler's work thus become obvious -
system's signal helper will store current execution context on stack,
then new thread will be selected by registered handler
and its context will be restored when signal will exit instead of
old one, thus true context switching will be performed.
This looks simple in theory, but on practice there are couple of small problems:
- I do not know (even x86) asm enough to code like in C (but I always wanted to hack low-level stuff)
- I do not 100% sure that signals work like I described (but I surely want to know)
- I do not know how it will be easy or not to save/restore context (according to glibc sources,
getcontext()/makecontext() and friends are not too big though)
Actually context switch is a bit more complex - for example virtual mapping should be restored/saved too
for TLS (thread-local storage), on x86 MMU registers must be saved and more generally FPU state
must be saved too, but for initial implementation I think it is not too relevant.
So, enough for theories, it is about an 1 A.M. and I need to sleep - I'm sure this day will be very interesting.
/devel/threading :: Link / Comments ()
|