Multi-task in K - Practical example with KGameBoy
Written by Jean-Loup Bogalho
K is a project realised by student of kernel option of EPITA in ING1. It's a basic x86-32 kernel written in C. This kernel allow the user to load a program in userland with the possibility of using some syscalls (like sbrk or getkey for example).
After having finished the K project, I tried to add some features to it. Among them : the possiblity to run more than one rom in userland at the same time.
To test it, I mainly used the emulator KGameBoy (gameboy's emulator working with K's syscalls).
Task and Task Switch
I first created a data structure which represents each task. This structure contains the following (non-exhaustives) information :
- where is the task in the memory
- what is its size
- what was the value of each registers when the last task switch occured
- what is its id
Each task is initialised by the kernel before the first jump into userland (in one of the tasks).
I'm using the timer's interruptions to schedule the tasks and switch them. Each task is given a fixed amount of time of execution before being switched (and necessary information stored into the data structure previously mentioned). The scheduler acts as a simple round-robin algorithm and give each task the same amount of time.
To switch context :
- Old task's state is saved.
- The GDT is set accordingly to informations stored in the new task's structure.
- Registers are sets to their new value.
- The far return is executed, as in the first jump into userland.
Keyboard and Screen managing
For the screen, the resolution of the emulator is exactly half the resolution of the K's VGA driver (in width, height is slightly inferior), so you can run up to 2 emulators side by side (for others roms, the screen space is instead divided horizontally by the number of running tasks).
As for the keyboard, each task must map (and reserve) the keys it wants to use (keys mapped by a task are then unmappable by others). This necessited that I modify a part of the emulator in order to work normally (the key's managing part).
The multi-tasking is working, context switches are well-opered and each manager (keyboard and screen) is doing its role. As a proof of concept, I made a short screencast using Qemu and Recordmydesktop showing two emulations of Tetris® executing together.