Software task-Switching
From alt. OS. Development
All lines preceded by a ">" were written by sefirot. All other lines were written by Kovacs Viktor Peter.
> Hello,
> Wocould you explain the way of software task-Switching
> (Namely, switching without using TSS) on x86 in detail?
It's simple:
-Push all regs to the stack
-Load a new value into SS: ESP (switch kernel stacks)
-Pop all regs from the new stack
-Load a new value into 32a (PD base REG)
-Load a new SS: ESP value into the system TSS (patch it)
-Iret (when the task switcher is placed into an interrupt handler)
Or even simplier: (faster; only for microkernels)
-Save all regs to the thread data struct
-Load all regs from the new thread data struct
-Reload 32a (on process switches only)
-Iret
Viktor
PS1:
It can be as fast as 64 mov-s in case of a thread switch.
(About 32 cycles on a P6 Core/ppro-piII /)
The 1st method modifies the TSS. The x86 reads the ss0: ESP values from
The TSS on a ring3-> ring0 switch. This is the only required field.
(Using one kernel stack per CPU saves the patch and the reload, but makes
The kernel ring0 code uninterruptable. Actually... who wants
Interrupt the task Switcher in a critical section ?)
PS2: the code in unoptimized inline GCC assembly:
asm("_kernel_lbl_int_00:");asm(" pushl $0");asm(" jmp _kernel_lbl_to_kernel");[...]asm("_kernel_lbl_int_40:");asm(" pushl $0"); /* filler for the err code */asm(" pushl $64"); /* irq number */asm(" jmp _kernel_lbl_to_kernel");[...]asm("_kernel_lbl_to_kernel:");asm(" pushl %gs"); /* could be optimized */asm(" pushl %fs"); /* to one instr. */asm(" pushl %es");asm(" pushl %ds");asm(" pushl %ebp");asm(" pushl %edi");asm(" pushl %esi");asm(" pushl %edx");asm(" pushl %ecx");asm(" pushl %ebx");asm(" pushl %eax");asm(" movl %esp, %ebx");asm(" movl kernel_stack_top, %esp "); /* single kstack mode */asm(" pushl %ebx");asm(" movw $16, %ax"); /* KERNEL_DATA_SEG!!!! */asm(" movw %ax, %ds");asm(" movw %ax, %es");asm(" movw %ax, %fs");asm(" movw %ax, %gs");asm(" call _kernel_entry"); /* => eax: retval */asm(" popl %ebx");asm(" movl %ebx, %esp");asm(" popl %eax");asm(" popl %ebx");asm(" popl %ecx");asm(" popl %edx");asm(" popl %esi");asm(" popl %edi");asm(" popl %ebp");asm(" popl %ds");asm(" popl %es");asm(" popl %fs");asm(" popl %gs");asm(" addl $8, %esp"); /* drop err and irq num */asm(" iretl");[...]uint kernel_entry(uint* regs){/* put your microkernel here */return(0); /* ignored now, could be used to flag new cr3 (pid) value */}