Newbie question - context switching - Odd behavior

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
DrunkenSlithLord
Posts: 5
Joined: Fri Aug 30, 2013 7:37 pm
Location: Stony Brook, NY

Newbie question - context switching - Odd behavior

Post 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.
In search of the Lost Bahssikava ...
DrunkenSlithLord
Posts: 5
Joined: Fri Aug 30, 2013 7:37 pm
Location: Stony Brook, NY

Re: Newbie question - context switching - Odd behavior RESOL

Post by DrunkenSlithLord »

Silly me!

I wasn't saving and restoring the other registers(rax, rbx) correctly!
In search of the Lost Bahssikava ...
DrunkenSlithLord
Posts: 5
Joined: Fri Aug 30, 2013 7:37 pm
Location: Stony Brook, NY

Re: Newbie question - context switching - Odd behavior

Post 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?
In search of the Lost Bahssikava ...
dansmahajan
Member
Member
Posts: 62
Joined: Mon Jan 07, 2013 10:38 am

Re: Newbie question - context switching - Odd behavior

Post 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
Post Reply