Page 1 of 1

Newbie question - context switching - Odd behavior

Posted: Tue Oct 29, 2013 8:04 am
by DrunkenSlithLord
Hi,

I have a simple memory system in place for my 64 bit OS and I'm trying to get context switching working. I have written a routine switch_tasks() which saves and restores the rsp, rbp and rflags register. The context switch is done implicitly by switching the kernel stacks.

To test this code, I'm trying to run it with two functions f1() and f2() in the kernel which voluntarily call the switch_tasks() function to yield processor. I'm setting up their initial pcbs and adding them to the process list and invoking the switch_tasks() method.

I'm getting some sort of context switching. What is happening is this --

My two functions are --

Code: Select all

void f1() 
{
 int x = 0;
 while(x<10)
 {
   kernel_print("foo! %d\n", x++);
   switch_tasks();
 }
}

void f2() 
{
 int y = 0;
 while(y<10)
 {
   kernel_print("bar! %d\n", y++);
   switch_tasks();
 }
}
I'm observing that the counters x and y are getting updated by 2, instead of 1 each time :( :( So the loops run for five times, instead of ten. The output is like --

Code: Select all

foo! 0
bar! 0
foo! 2
bar! 2
foo! 4
bar! 4
.
.
.
I can't think of how this could be possible. Any pointers would help.

Thanks,
DrSL.

Re: Newbie question - context switching - Odd behavior RESOL

Posted: Tue Oct 29, 2013 8:21 am
by DrunkenSlithLord
Silly me!

I wasn't saving and restoring the other registers(rax, rbx) correctly!

Re: Newbie question - context switching - Odd behavior

Posted: Sat Nov 02, 2013 9:46 pm
by DrunkenSlithLord
I'm now trying to make the kernel preemptive. In order to do this, I understand that I should use the timer interrupt handler. But I'm not very sure how I should handle any interrupts that happen during the task switch. Should I turn off interrupts till the task switch has happened?

But then, since immediately after the context switch is done, the newly scheduled process starts running -- how would I reenable interrupts?

Re: Newbie question - context switching - Odd behavior

Posted: Sun Nov 03, 2013 12:13 am
by dansmahajan
you could use the IF flag in ELFAGS
just or your processes the eflags with 0x800 and thats it after iret instruction sti will be called implicitly