Make your own OS in 30 days – day15/16: Multitasking

First, changed from Q ver 0.9 to qemu 2.2.1 to resolve VESA issue before day15/16. I needed to make qemu foreground after running it.

Makefie)
default :
	#./Q.app/Contents/MacOS/i386-softmmu.app/Contents/MacOS/i386-softmmu -L . -m 32 -localtime -std-vga -fda fdimage0.bin
	/usr/local/Cellar/qemu/2.2.1/bin/qemu-system-i386 -fda fdimage0.bin -L . -m 32 -localtime -vga std -smp cpus=2 &
	sleep 1
	osascript -e "tell application \"/usr/local/Cellar/qemu/2.2.1/bin/qemu-system-i386\" to activate"

Day15/16 is about multitasking. You can do far-jump to TSS; Task Status Segment, CPU doesn’t make a regular jump but change contexts. If you want to create and jump to a new task, the procedure is as follows.
1. Register TSS in GDT
2. Allocate a stack for the new task
3. Far jump to the TSS

#define TASK_GDT0▸▸ 3 // first task segment number
for (i = 0; i < MAX_TASKS; i++) {
	taskctl->tasks0[i].flags = 0;
	taskctl->tasks0[i].sel = (TASK_GDT0 + i) * 8;
	set_segmdesc(gdt + TASK_GDT0 + i, 103, (int) &taskctl->tasks0[i].tss, AR_TSS32);
}

task_a = task_init(memman);
fifo.task = task_a;
task_b = task_alloc();
task_b->tss.esp = memman_alloc_4k(memman, 64 * 1024) + 64 * 1024 - 8;
task_b->tss.eip = (int) &task_b_main;
task_b->tss.es = 1 * 8;
task_b->tss.cs = 2 * 8;
task_b->tss.ss = 1 * 8;
task_b->tss.ds = 1 * 8;
task_b->tss.fs = 1 * 8;
task_b->tss.gs = 1 * 8;
*((int *) (task_b->tss.esp + 4)) = (int) sht_back;

task_run(task_b);

Then it switches tasks using yesterday’s timer interrupt handler every 20ms.
Task_a (main task) is basically sleeping (not getting CPU time at all) until interrupted to use more CPU time for task_b. Task_a should not be sleeping when it’s interrupted. The OS resolves it by awaken task_a when it gets interrupting in FIFO handler via key/mouse/other interrupts.

It only uses a single core through the book. I found how to enable other CPU cores and message each other at University of San Francisco’s class “Advanced Microcomputer Programming”-> lesson 5 -> pmhello.s via StackOverflow.

day15_16

Leave a Reply

Your email address will not be published. Required fields are marked *