]> git.buserror.net Git - polintos/scott/priv.git/blob - kernel/arch/x64/thread.cc
f4c80b45975cb827847646a6786aa5d67f295fc7
[polintos/scott/priv.git] / kernel / arch / x64 / thread.cc
1 // arch/x64/thread.cc -- Thread switching
2 //
3 // This software is copyright (c) 2006 Scott Wood <scott@buserror.net>.
4 // 
5 // This software is provided 'as-is', without any express or implied warranty.
6 // In no event will the authors or contributors be held liable for any damages
7 // arising from the use of this software.
8 // 
9 // Permission is hereby granted to everyone, free of charge, to use, copy,
10 // modify, prepare derivative works of, publish, distribute, perform,
11 // sublicense, and/or sell copies of the Software, provided that the above
12 // copyright notice and disclaimer of warranty be included in all copies or
13 // substantial portions of this software.
14
15 #include <kern/thread.h>
16 #include <kern/mem.h>
17 #include <kern/pagetable.h>
18
19 namespace Arch {
20         void switch_thread(Threads::Thread *dest, Threads::Thread *src)
21         {
22                 u64 dummy1, dummy2;
23                 
24                 if (dest->addr_space) {
25                         assert(dest->addr_space == dest->active_addr_space);
26                 
27                         if (dest->addr_space != src->active_addr_space) {
28                                 u64 cr3 = Mem::kvirt_to_phys(dest->addr_space->
29                                                              page_table->toplevel);
30                                 asm volatile("movq %0, %%cr3" : : "r" (cr3) : "memory");
31                         }
32                 } else {
33                         dest->active_addr_space = src->active_addr_space;
34                 }
35                 
36                 Priv::tss.rsp[0] = reinterpret_cast<u64>(dest);
37
38                 asm volatile("movq %%rsp, (%0);"
39                              "movq %%rbp, 8(%0);"
40                              "movb $0, 16(%0);"
41                              "movb 16(%1), %%al;"
42                              "cmpb $0, %%al;"
43                              "movq (%1), %%rsp;"
44                              "movq 8(%1), %%rbp;"
45                              "jnz x64_new_thread;" :
46                              "=a" (dummy1), "=c" (dummy2) :
47                              "0" (&src->arch.rsp), "1" (&dest->arch.rsp) :
48                              "rbx", "rdx", "rsi", "rdi",
49                              "r8", "r9", "r10", "r11", "r12", 
50                              "r13", "r14", "r15", "memory");
51         }
52 }