Moved task selection to threads.c, fixed segfault in Proc_ChangeStacks
[tpg/acess2.git] / Kernel / arch / x86 / proc.c
1 /*
2  * AcessOS Microkernel Version
3  * proc.c
4  */
5 #include <common.h>
6 #include <proc.h>
7 #include <mm_virt.h>
8 #include <errno.h>
9 #if USE_MP
10 # include <mp.h>
11 #endif
12
13 // === CONSTANTS ===
14 #define SWITCH_MAGIC    0xFFFACE55      // There is no code in this area
15 #define TIMER_DIVISOR   11931   //~100Hz
16
17 // === IMPORTS ===
18 extern tGDT     gGDT[];
19 extern Uint     GetEIP();       // start.asm
20 extern Uint32   gaInitPageDir[1024];    // start.asm
21 extern void     Kernel_Stack_Top;
22 extern volatile int     giThreadListLock;
23 extern int      giNumCPUs;
24 extern int      giNextTID;
25 extern int      giTotalTickets;
26 extern int      giNumActiveThreads;
27 extern tThread  *gActiveThreads;
28 extern tThread  *gSleepingThreads;
29 extern tThread  *gDeleteThreads;
30 extern tThread  *Threads_GetNextToRun(int CPU);
31
32 // === PROTOTYPES ===
33 void    ArchThreads_Init();
34 tThread *Proc_GetCurThread();
35 void    Proc_ChangeStack();
36  int    Proc_Clone(Uint *Err, Uint Flags);
37 void    Proc_Scheduler();
38
39 // === GLOBALS ===
40 // --- Current State ---
41 #if USE_MP
42 tThread **gCurrentThread = NULL;
43 #else
44 tThread *gCurrentThread = NULL;
45 #endif
46 // --- Multiprocessing ---
47 #if USE_MP
48 tMPInfo *gMPTable = NULL;
49 #endif
50 #if USE_PAE
51 Uint32  *gPML4s[4] = NULL;
52 #endif
53 tTSS    *gTSSs = NULL;
54 #if !USE_MP
55 tTSS    gTSS0 = {0};
56 #endif
57
58 // === CODE ===
59 /**
60  * \fn void ArchThreads_Init()
61  * \brief Starts the process scheduler
62  */
63 void ArchThreads_Init()
64 {
65         Uint    pos = 0;
66         #if USE_MP
67         // -- Initialise Multiprocessing
68         // Find MP Floating Table
69         // - EBDA
70         for(pos = KERNEL_BASE|0x9FC00; pos < (KERNEL_BASE|0xA0000); pos += 16) {
71                 if( *(Uint*)(pos) == MPTABLE_IDENT ) {
72                         if(ByteSum( (void*)pos, sizeof(tMPInfo) ) != 0) continue;
73                         gMPTable = (void*)pos;
74                         break;
75                 }
76         }
77         // - Last KiB
78         if(!gMPTable) {
79                 
80         }
81         // - BIOS ROM
82         if(!gMPTable) {
83                 for(pos = KERNEL_BASE|0xF0000; pos < (KERNEL_BASE|0x100000); pos += 16) {
84                         if( *(Uint*)(pos) == MPTABLE_IDENT ) {
85                                 if(ByteSum( (void*)pos, sizeof(tMPInfo) ) != 0) continue;
86                                 gMPTable = (void*)pos;
87                                 break;
88                         }
89                 }
90         }
91         
92         // If the MP Table Exists, parse it
93         if(gMPTable)
94         {
95                 Panic("Uh oh... MP Table Parsing is unimplemented\n");
96         } else {
97         #endif
98                 giNumCPUs = 1;
99                 gTSSs = &gTSS0;
100         #if USE_MP
101         }
102         
103         // Initialise TSS
104         for(pos=0;pos<giNumCPUs;pos++)
105         {
106         #else
107         pos = 0;
108         #endif
109                 gTSSs[pos].SS0 = 0x10;
110                 gTSSs[pos].ESP0 = 0;    // Set properly by scheduler
111                 gGDT[5+pos].LimitLow = sizeof(tTSS);
112                 gGDT[5+pos].LimitHi = 0;
113                 gGDT[5+pos].Access = 0x89;      // Type
114                 gGDT[5+pos].Flags = 0x4;
115                 gGDT[5+pos].BaseLow = (Uint)&gTSSs[pos] & 0xFFFF;
116                 gGDT[5+pos].BaseMid = (Uint)&gTSSs[pos] >> 16;
117                 gGDT[5+pos].BaseHi = (Uint)&gTSSs[pos] >> 24;
118         #if USE_MP
119         }
120         for(pos=0;pos<giNumCPUs;pos++) {
121         #endif
122                 __asm__ __volatile__ ("ltr %%ax"::"a"(0x28+pos*8));
123         #if USE_MP
124         }
125         #endif
126         
127         // Set timer frequency
128         outb(0x43, 0x34);       // Set Channel 0, Low/High, Rate Generator
129         outb(0x40, TIMER_DIVISOR&0xFF); // Low Byte of Divisor
130         outb(0x40, (TIMER_DIVISOR>>8)&0xFF);    // High Byte
131         
132         // Create Per-Process Data Block
133         MM_Allocate(MM_PPD_CFG);
134         
135         // Change Stacks
136         Proc_ChangeStack();
137         
138         // Start Interrupts (and hence scheduler)
139         __asm__ __volatile__("sti");
140 }
141
142 /**
143  * \fn tThread *Proc_GetCurThread()
144  * \brief Gets the current thread
145  */
146 tThread *Proc_GetCurThread()
147 {
148         #if USE_MP
149         return NULL;
150         #else
151         return gCurrentThread;
152         #endif
153 }
154
155 /**
156  * \fn void Proc_ChangeStack()
157  * \brief Swaps the current stack for a new one (in the proper stack reigon)
158  */
159 void Proc_ChangeStack()
160 {
161         Uint    esp, ebp;
162         Uint    tmpEbp, oldEsp;
163         Uint    curBase, newBase;
164
165         __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
166         __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
167
168         oldEsp = esp;
169
170         // Create new KStack
171         newBase = MM_NewKStack();
172         // Check for errors
173         if(newBase == 0) {
174                 Panic("What the?? Unable to allocate space for initial kernel stack");
175                 return;
176         }
177
178         curBase = (Uint)&Kernel_Stack_Top;
179         
180         LOG("curBase = 0x%x, newBase = 0x%x", curBase, newBase);
181
182         // Get ESP as a used size
183         esp = curBase - esp;
184         LOG("memcpy( %p, %p, 0x%x )", (void*)(newBase - esp), (void*)(curBase - esp), esp );
185         // Copy used stack
186         memcpy( (void*)(newBase - esp), (void*)(curBase - esp), esp );
187         // Get ESP as an offset in the new stack
188         esp = newBase - esp;
189         // Adjust EBP
190         ebp = newBase - (curBase - ebp);
191
192         // Repair EBPs & Stack Addresses
193         // Catches arguments also, but may trash stack-address-like values
194         for(tmpEbp = esp; tmpEbp < newBase; tmpEbp += 4)
195         {
196                 if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < curBase)
197                         *(Uint*)tmpEbp += newBase - curBase;
198         }
199         
200         gCurrentThread->KernelStack = newBase;
201         
202         __asm__ __volatile__ ("mov %0, %%esp"::"r"(esp));
203         __asm__ __volatile__ ("mov %0, %%ebp"::"r"(ebp));
204 }
205
206 /**
207  * \fn int Proc_Clone(Uint *Err, Uint Flags)
208  * \brief Clone the current process
209  */
210 int Proc_Clone(Uint *Err, Uint Flags)
211 {
212         tThread *newThread;
213         Uint    eip, esp, ebp;
214         
215         __asm__ __volatile__ ("mov %%esp, %0": "=r"(esp));
216         __asm__ __volatile__ ("mov %%ebp, %0": "=r"(ebp));
217         
218         // Create new thread structure
219         newThread = malloc( sizeof(tThread) );
220         if(!newThread) {
221                 Warning("Proc_Clone - Out of memory when creating thread\n");
222                 *Err = -ENOMEM;
223                 return -1;
224         }
225         // Base new thread on old
226         memcpy(newThread, gCurrentThread, sizeof(tThread));
227         // Initialise Memory Space (New Addr space or kernel stack)
228         if(Flags & CLONE_VM) {
229                 newThread->TGID = newThread->TID;
230                 newThread->MemState.CR3 = MM_Clone();
231         } else {
232                 Uint    tmpEbp, oldEsp = esp;
233
234                 // Create new KStack
235                 newThread->KernelStack = MM_NewKStack();
236                 // Check for errors
237                 if(newThread->KernelStack == 0) {
238                         free(newThread);
239                         return -1;
240                 }
241
242                 // Get ESP as a used size
243                 esp = gCurrentThread->KernelStack - esp;
244                 // Copy used stack
245                 memcpy( (void*)(newThread->KernelStack - esp), (void*)(gCurrentThread->KernelStack - esp), esp );
246                 // Get ESP as an offset in the new stack
247                 esp = newThread->KernelStack - esp;
248                 // Adjust EBP
249                 ebp = newThread->KernelStack - (gCurrentThread->KernelStack - ebp);
250
251                 // Repair EBPs & Stack Addresses
252                 // Catches arguments also, but may trash stack-address-like values
253                 for(tmpEbp = esp; tmpEbp < newThread->KernelStack; tmpEbp += 4)
254                 {
255                         if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < gCurrentThread->KernelStack)
256                                 *(Uint*)tmpEbp += newThread->KernelStack - gCurrentThread->KernelStack;
257                 }
258         }
259
260         // Set Pointer, Spinlock and TID
261         newThread->Next = NULL;
262         newThread->IsLocked = 0;
263         newThread->TID = giNextTID++;
264         newThread->PTID = gCurrentThread->TID;
265
266         // Clear message list (messages are not inherited)
267         newThread->Messages = NULL;
268         newThread->LastMessage = NULL;
269         
270         // Set remaining (sheduler expects remaining to be correct)
271         newThread->Remaining = newThread->Quantum;
272         
273         // Save core machine state
274         newThread->SavedState.ESP = esp;
275         newThread->SavedState.EBP = ebp;
276         eip = GetEIP();
277         if(eip == SWITCH_MAGIC) {
278                 outb(0x20, 0x20);       // ACK Timer and return as child
279                 return 0;
280         }
281         
282         // Set EIP as parent
283         newThread->SavedState.EIP = eip;
284         
285         // Lock list and add to active
286         LOCK( &giThreadListLock );
287         newThread->Next = gActiveThreads;
288         gActiveThreads = newThread;
289         giNumActiveThreads ++;
290         giTotalTickets += newThread->NumTickets;
291         RELEASE( &giThreadListLock );
292         
293         return newThread->TID;
294 }
295
296 /**
297  * \fn Uint Proc_MakeUserStack()
298  * \brief Creates a new user stack
299  */
300 Uint Proc_MakeUserStack()
301 {
302          int    i;
303         Uint    base = USER_STACK_TOP - USER_STACK_SZ;
304         
305         // Check Prospective Space
306         for( i = USER_STACK_SZ >> 12; i--; )
307                 if( MM_GetPhysAddr( base + (i<<12) ) != 0 )
308                         break;
309         
310         if(i != -1)     return 0;
311         
312         // Allocate Stack - Allocate incrementally to clean up MM_Dump output
313         for( i = 0; i < USER_STACK_SZ/4069; i++ )
314                 MM_Allocate( base + (i<<12) );
315         
316         return base + USER_STACK_SZ;
317 }
318
319
320 /**
321  * \fn void Proc_StartUser(Uint Entrypoint, Uint Base, int ArgC, char **ArgV, char **EnvP, int DataSize)
322  * \brief Starts a user task
323  */
324 void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize)
325 {
326         Uint    *stack = (void*)Proc_MakeUserStack();
327          int    i;
328         Uint    delta;
329         Uint16  ss, cs;
330         
331         LOG("stack = 0x%x", stack);
332         
333         // Copy Arguments
334         stack = (void*)( (Uint)stack - DataSize );
335         memcpy( stack, ArgV, DataSize );
336         
337         // Adjust Arguments and environment
338         delta = (Uint)stack - (Uint)ArgV;
339         ArgV = (char**)stack;
340         for( i = 0; ArgV[i]; i++ )      ArgV[i] += delta;
341         i ++;
342         EnvP = &ArgV[i];
343         for( i = 0; EnvP[i]; i++ )      EnvP[i] += delta;
344         
345         // User Mode Segments
346         ss = 0x23;      cs = 0x1B;
347         
348         // Arguments
349         *--stack = (Uint)EnvP;
350         *--stack = (Uint)ArgV;
351         *--stack = (Uint)ArgC;
352         while(*Bases)
353                 *--stack = *Bases++;
354         *--stack = 0;   // Return Address
355         delta = (Uint)stack;    // Reuse delta to save SP
356         
357         *--stack = ss;          //Stack Segment
358         *--stack = delta;       //Stack Pointer
359         *--stack = 0x0202;      //EFLAGS (Resvd (0x2) and IF (0x20))
360         *--stack = cs;          //Code Segment
361         *--stack = Entrypoint;  //EIP
362         //PUSHAD
363         *--stack = 0xAAAAAAAA;  // eax
364         *--stack = 0xCCCCCCCC;  // ecx
365         *--stack = 0xDDDDDDDD;  // edx
366         *--stack = 0xBBBBBBBB;  // ebx
367         *--stack = 0xD1D1D1D1;  // edi
368         *--stack = 0x54545454;  // esp - NOT POPED
369         *--stack = 0x51515151;  // esi
370         *--stack = 0xB4B4B4B4;  // ebp
371         //Individual PUSHs
372         *--stack = ss;  // ds
373         *--stack = ss;  // es
374         *--stack = ss;  // fs
375         *--stack = ss;  // gs
376         
377         __asm__ __volatile__ (
378         "mov %%eax,%%esp;\n\t"  // Set stack pointer
379         "pop %%gs;\n\t"
380         "pop %%fs;\n\t"
381         "pop %%es;\n\t"
382         "pop %%ds;\n\t"
383         "popa;\n\t"
384         "iret;\n\t" : : "a" (stack));
385         for(;;);
386 }
387
388 /**
389  * \fn int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
390  * \brief Demotes a process to a lower permission level
391  * \param Err   Pointer to user's errno
392  */
393 int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
394 {
395          int    cpl = Regs->cs & 3;
396         // Sanity Check
397         if(Dest > 3 || Dest < 0) {
398                 *Err = -EINVAL;
399                 return -1;
400         }
401         
402         // Permission Check
403         if(cpl > Dest) {
404                 *Err = -EACCES;
405                 return -1;
406         }
407         
408         // Change the Segment Registers
409         Regs->cs = (((Dest+1)<<4) | Dest) - 8;
410         Regs->ss = ((Dest+1)<<4) | Dest;
411         // Check if the GP Segs are GDT, then change them
412         if(!(Regs->ds & 4))     Regs->ds = ((Dest+1)<<4) | Dest;
413         if(!(Regs->es & 4))     Regs->es = ((Dest+1)<<4) | Dest;
414         if(!(Regs->fs & 4))     Regs->fs = ((Dest+1)<<4) | Dest;
415         if(!(Regs->gs & 4))     Regs->gs = ((Dest+1)<<4) | Dest;
416         
417         return 0;
418 }
419
420 /**
421  * \fn void Proc_Scheduler(int CPU)
422  * \brief Swap current thread and clears dead threads
423  */
424 void Proc_Scheduler(int CPU)
425 {
426         Uint    esp, ebp, eip;
427         tThread *thread;
428         
429         // If the spinlock is set, let it complete
430         if(giThreadListLock)    return;
431         
432         // Clear Delete Queue
433         while(gDeleteThreads)
434         {
435                 thread = gDeleteThreads->Next;
436                 if(gDeleteThreads->IsLocked) {  // Only free if structure is unused
437                         gDeleteThreads->Status = THREAD_STAT_NULL;
438                         free( gDeleteThreads );
439                 }
440                 gDeleteThreads = thread;
441         }
442         
443         // Check if there is any tasks running
444         if(giNumActiveThreads == 0) {
445                 Log("No Active threads, sleeping\n");
446                 __asm__ __volatile__ ("hlt");
447                 return;
448         }
449         
450         // Reduce remaining quantum and continue timeslice if non-zero
451         if(gCurrentThread->Remaining--) return;
452         // Reset quantum for next call
453         gCurrentThread->Remaining = gCurrentThread->Quantum;
454         
455         // Get machine state
456         __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
457         __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
458         eip = GetEIP();
459         if(eip == SWITCH_MAGIC) return; // Check if a switch happened
460         
461         // Save machine state
462         gCurrentThread->SavedState.ESP = esp;
463         gCurrentThread->SavedState.EBP = ebp;
464         gCurrentThread->SavedState.EIP = eip;
465         
466         // Get next thread
467         thread = Threads_GetNextToRun(CPU);
468         
469         // Error Check
470         if(thread == NULL) {
471                 Warning("Hmm... Threads_GetNextToRun returned NULL, I don't think this should happen.\n");
472                 return;
473         }
474         
475         // Set current thread
476         gCurrentThread = thread;
477         
478         // Update Kernel Stack pointer
479         gTSSs[CPU].ESP0 = thread->KernelStack;
480         
481         // Set address space
482         __asm__ __volatile__ ("mov %0, %%cr3"::"a"(gCurrentThread->MemState.CR3));
483         // Switch threads
484         __asm__ __volatile__ (
485                 "mov %1, %%esp\n\t"
486                 "mov %2, %%ebp\n\t"
487                 "jmp *%3" : :
488                 "a"(SWITCH_MAGIC), "b"(gCurrentThread->SavedState.ESP),
489                 "d"(gCurrentThread->SavedState.EBP), "c"(gCurrentThread->SavedState.EIP));
490         for(;;);        // Shouldn't reach here
491 }

UCC git Repository :: git.ucc.asn.au