Fixed duplicate reference of heap locatons, and stopped CWD from being freed if it...
[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         tThread *cur = Proc_GetCurThread();
240         Uint    eip, esp, ebp;
241         
242         __asm__ __volatile__ ("mov %%esp, %0": "=r"(esp));
243         __asm__ __volatile__ ("mov %%ebp, %0": "=r"(ebp));
244         
245         // Create new thread structure
246         newThread = malloc( sizeof(tThread) );
247         if(!newThread) {
248                 Warning("Proc_Clone - Out of memory when creating thread\n");
249                 *Err = -ENOMEM;
250                 return -1;
251         }
252         
253         // Base new thread on current
254         memcpy(newThread, cur, sizeof(tThread));
255         
256         // Initialise Memory Space (New Addr space or kernel stack)
257         if(Flags & CLONE_VM) {
258                 newThread->TGID = newThread->TID;
259                 newThread->MemState.CR3 = MM_Clone();
260         } else {
261                 Uint    tmpEbp, oldEsp = esp;
262
263                 // Create new KStack
264                 newThread->KernelStack = MM_NewKStack();
265                 // Check for errors
266                 if(newThread->KernelStack == 0) {
267                         free(newThread);
268                         return -1;
269                 }
270
271                 // Get ESP as a used size
272                 esp = cur->KernelStack - esp;
273                 // Copy used stack
274                 memcpy( (void*)(newThread->KernelStack - esp), (void*)(cur->KernelStack - esp), esp );
275                 // Get ESP as an offset in the new stack
276                 esp = newThread->KernelStack - esp;
277                 // Adjust EBP
278                 ebp = newThread->KernelStack - (cur->KernelStack - ebp);
279
280                 // Repair EBPs & Stack Addresses
281                 // Catches arguments also, but may trash stack-address-like values
282                 for(tmpEbp = esp; tmpEbp < newThread->KernelStack; tmpEbp += 4)
283                 {
284                         if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < cur->KernelStack)
285                                 *(Uint*)tmpEbp += newThread->KernelStack - cur->KernelStack;
286                 }
287         }
288
289         // Set Pointer, Spinlock and TID
290         newThread->Next = NULL;
291         newThread->IsLocked = 0;
292         newThread->TID = giNextTID++;
293         newThread->PTID = cur->TID;
294         
295         // Create copy of name
296         newThread->ThreadName = malloc(strlen(cur->ThreadName)+1);
297         strcpy(newThread->ThreadName, cur->ThreadName);
298
299         // Clear message list (messages are not inherited)
300         newThread->Messages = NULL;
301         newThread->LastMessage = NULL;
302         
303         // Set remaining (sheduler expects remaining to be correct)
304         newThread->Remaining = newThread->Quantum;
305         
306         // Save core machine state
307         newThread->SavedState.ESP = esp;
308         newThread->SavedState.EBP = ebp;
309         eip = GetEIP();
310         if(eip == SWITCH_MAGIC) {
311                 outb(0x20, 0x20);       // ACK Timer and return as child
312                 return 0;
313         }
314         
315         // Set EIP as parent
316         newThread->SavedState.EIP = eip;
317         
318         // Lock list and add to active
319         Threads_AddActive(newThread);
320         
321         //Threads_Dump();
322         
323         return newThread->TID;
324 }
325
326 /**
327  * \fn Uint Proc_MakeUserStack()
328  * \brief Creates a new user stack
329  */
330 Uint Proc_MakeUserStack()
331 {
332          int    i;
333         Uint    base = USER_STACK_TOP - USER_STACK_SZ;
334         
335         // Check Prospective Space
336         for( i = USER_STACK_SZ >> 12; i--; )
337                 if( MM_GetPhysAddr( base + (i<<12) ) != 0 )
338                         break;
339         
340         if(i != -1)     return 0;
341         
342         // Allocate Stack - Allocate incrementally to clean up MM_Dump output
343         for( i = 0; i < USER_STACK_SZ/4069; i++ )
344                 MM_Allocate( base + (i<<12) );
345         
346         return base + USER_STACK_SZ;
347 }
348
349
350 /**
351  * \fn void Proc_StartUser(Uint Entrypoint, Uint Base, int ArgC, char **ArgV, char **EnvP, int DataSize)
352  * \brief Starts a user task
353  */
354 void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize)
355 {
356         Uint    *stack = (void*)Proc_MakeUserStack();
357          int    i;
358         Uint    delta;
359         Uint16  ss, cs;
360         
361         LOG("stack = 0x%x", stack);
362         
363         // Copy Arguments
364         stack = (void*)( (Uint)stack - DataSize );
365         memcpy( stack, ArgV, DataSize );
366         
367         // Adjust Arguments and environment
368         delta = (Uint)stack - (Uint)ArgV;
369         ArgV = (char**)stack;
370         for( i = 0; ArgV[i]; i++ )      ArgV[i] += delta;
371         i ++;
372         EnvP = &ArgV[i];
373         for( i = 0; EnvP[i]; i++ )      EnvP[i] += delta;
374         
375         // User Mode Segments
376         ss = 0x23;      cs = 0x1B;
377         
378         // Arguments
379         *--stack = (Uint)EnvP;
380         *--stack = (Uint)ArgV;
381         *--stack = (Uint)ArgC;
382         while(*Bases)
383                 *--stack = *Bases++;
384         *--stack = 0;   // Return Address
385         delta = (Uint)stack;    // Reuse delta to save SP
386         
387         *--stack = ss;          //Stack Segment
388         *--stack = delta;       //Stack Pointer
389         *--stack = 0x0202;      //EFLAGS (Resvd (0x2) and IF (0x20))
390         *--stack = cs;          //Code Segment
391         *--stack = Entrypoint;  //EIP
392         //PUSHAD
393         *--stack = 0xAAAAAAAA;  // eax
394         *--stack = 0xCCCCCCCC;  // ecx
395         *--stack = 0xDDDDDDDD;  // edx
396         *--stack = 0xBBBBBBBB;  // ebx
397         *--stack = 0xD1D1D1D1;  // edi
398         *--stack = 0x54545454;  // esp - NOT POPED
399         *--stack = 0x51515151;  // esi
400         *--stack = 0xB4B4B4B4;  // ebp
401         //Individual PUSHs
402         *--stack = ss;  // ds
403         *--stack = ss;  // es
404         *--stack = ss;  // fs
405         *--stack = ss;  // gs
406         
407         __asm__ __volatile__ (
408         "mov %%eax,%%esp;\n\t"  // Set stack pointer
409         "pop %%gs;\n\t"
410         "pop %%fs;\n\t"
411         "pop %%es;\n\t"
412         "pop %%ds;\n\t"
413         "popa;\n\t"
414         "iret;\n\t" : : "a" (stack));
415         for(;;);
416 }
417
418 /**
419  * \fn int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
420  * \brief Demotes a process to a lower permission level
421  * \param Err   Pointer to user's errno
422  */
423 int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
424 {
425          int    cpl = Regs->cs & 3;
426         // Sanity Check
427         if(Dest > 3 || Dest < 0) {
428                 *Err = -EINVAL;
429                 return -1;
430         }
431         
432         // Permission Check
433         if(cpl > Dest) {
434                 *Err = -EACCES;
435                 return -1;
436         }
437         
438         // Change the Segment Registers
439         Regs->cs = (((Dest+1)<<4) | Dest) - 8;
440         Regs->ss = ((Dest+1)<<4) | Dest;
441         // Check if the GP Segs are GDT, then change them
442         if(!(Regs->ds & 4))     Regs->ds = ((Dest+1)<<4) | Dest;
443         if(!(Regs->es & 4))     Regs->es = ((Dest+1)<<4) | Dest;
444         if(!(Regs->fs & 4))     Regs->fs = ((Dest+1)<<4) | Dest;
445         if(!(Regs->gs & 4))     Regs->gs = ((Dest+1)<<4) | Dest;
446         
447         return 0;
448 }
449
450 /**
451  * \fn void Proc_Scheduler(int CPU)
452  * \brief Swap current thread and clears dead threads
453  */
454 void Proc_Scheduler(int CPU)
455 {
456         Uint    esp, ebp, eip;
457         tThread *thread;
458         
459         // If the spinlock is set, let it complete
460         if(giThreadListLock)    return;
461         
462         // Clear Delete Queue
463         while(gDeleteThreads)
464         {
465                 thread = gDeleteThreads->Next;
466                 if(gDeleteThreads->IsLocked) {  // Only free if structure is unused
467                         gDeleteThreads->Status = THREAD_STAT_NULL;
468                         free( gDeleteThreads );
469                 }
470                 gDeleteThreads = thread;
471         }
472         
473         // Check if there is any tasks running
474         if(giNumActiveThreads == 0) {
475                 Log("No Active threads, sleeping");
476                 __asm__ __volatile__ ("hlt");
477                 return;
478         }
479         
480         // Reduce remaining quantum and continue timeslice if non-zero
481         if(gCurrentThread->Remaining--) return;
482         // Reset quantum for next call
483         gCurrentThread->Remaining = gCurrentThread->Quantum;
484         
485         // Get machine state
486         __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
487         __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
488         eip = GetEIP();
489         if(eip == SWITCH_MAGIC) return; // Check if a switch happened
490         
491         // Save machine state
492         gCurrentThread->SavedState.ESP = esp;
493         gCurrentThread->SavedState.EBP = ebp;
494         gCurrentThread->SavedState.EIP = eip;
495         
496         // Get next thread
497         thread = Threads_GetNextToRun(CPU);
498         
499         // Error Check
500         if(thread == NULL) {
501                 Warning("Hmm... Threads_GetNextToRun returned NULL, I don't think this should happen.\n");
502                 return;
503         }
504         
505         #if DEBUG_TRACE_SWITCH
506         Log("Switching to task %i, CR3 = 0x%x, EIP = %p",
507                 thread->TID,
508                 thread->MemState.CR3,
509                 thread->SavedState.EIP
510                 );
511         #endif
512         
513         // Set current thread
514         gCurrentThread = thread;
515         
516         // Update Kernel Stack pointer
517         gTSSs[CPU].ESP0 = thread->KernelStack;
518         
519         // Set address space
520         __asm__ __volatile__ ("mov %0, %%cr3"::"a"(gCurrentThread->MemState.CR3));
521         // Switch threads
522         __asm__ __volatile__ (
523                 "mov %1, %%esp\n\t"
524                 "mov %2, %%ebp\n\t"
525                 "jmp *%3" : :
526                 "a"(SWITCH_MAGIC), "b"(gCurrentThread->SavedState.ESP),
527                 "d"(gCurrentThread->SavedState.EBP), "c"(gCurrentThread->SavedState.EIP));
528         for(;;);        // Shouldn't reach here
529 }

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