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

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