Bugfixes, Cleanup and Rewite started on UDI interface
[tpg/acess2.git] / Kernel / arch / x86 / proc.c
1 /*
2  * AcessOS Microkernel Version
3  * proc.c
4  */
5 #include <acess.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 void APStartup();        // 16-bit AP startup code
23 extern Uint     GetEIP();       // start.asm
24 extern Uint32   gaInitPageDir[1024];    // start.asm
25 extern void     Kernel_Stack_Top;
26 extern volatile int     giThreadListLock;
27 extern int      giNumCPUs;
28 extern int      giNextTID;
29 extern int      giTotalTickets;
30 extern int      giNumActiveThreads;
31 extern tThread  gThreadZero;
32 extern tThread  *gActiveThreads;
33 extern tThread  *gSleepingThreads;
34 extern tThread  *gDeleteThreads;
35 extern tThread  *Threads_GetNextToRun(int CPU);
36 extern void     Threads_Dump();
37 extern tThread  *Threads_CloneTCB(Uint *Err, Uint Flags);
38 extern void     Isr7();
39
40 // === PROTOTYPES ===
41 void    ArchThreads_Init();
42 #if USE_MP
43 void    MP_StartAP(int CPU);
44 void    MP_SendIPI(Uint8 APICID, int Vector, int DeliveryMode);
45 #endif
46 void    Proc_Start();
47 tThread *Proc_GetCurThread();
48 void    Proc_ChangeStack();
49  int    Proc_Clone(Uint *Err, Uint Flags);
50 void    Proc_Scheduler();
51
52 // === GLOBALS ===
53 // --- Multiprocessing ---
54 #if USE_MP
55 volatile int    giNumInitingCPUs = 0;
56 tMPInfo *gMPFloatPtr = NULL;
57 tAPIC   *gpMP_LocalAPIC = NULL;
58 Uint8   gaAPIC_to_CPU[256] = {0};
59 tCPU    gaCPUs[MAX_CPUS];
60 #else
61 tThread *gCurrentThread = NULL;
62 #endif
63 #if USE_PAE
64 Uint32  *gPML4s[4] = NULL;
65 #endif
66 tTSS    *gTSSs = NULL;
67 tTSS    gTSS0 = {0};
68 // --- Error Recovery ---
69 char    gaDoubleFaultStack[1024];
70 tTSS    gDoubleFault_TSS = {
71         .ESP0 = (Uint)&gaDoubleFaultStack[1023],
72         .SS0 = 0x10,
73         .EIP = (Uint)Isr7
74 };
75
76 // === CODE ===
77 /**
78  * \fn void ArchThreads_Init()
79  * \brief Starts the process scheduler
80  */
81 void ArchThreads_Init()
82 {
83         Uint    pos = 0;
84         
85         #if USE_MP
86         tMPTable        *mptable;
87         
88         // Mark BSP as active
89         gaCPUs[0].State = 2;
90         
91         // -- Initialise Multiprocessing
92         // Find MP Floating Table
93         // - EBDA/Last 1Kib (640KiB)
94         for(pos = KERNEL_BASE|0x9F000; pos < (KERNEL_BASE|0xA0000); pos += 16) {
95                 if( *(Uint*)(pos) == MPPTR_IDENT ) {
96                         Log("Possible %p", pos);
97                         if( ByteSum((void*)pos, sizeof(tMPInfo)) != 0 ) continue;
98                         gMPFloatPtr = (void*)pos;
99                         break;
100                 }
101         }
102         // - Last KiB (512KiB base mem)
103         if(!gMPFloatPtr) {
104                 for(pos = KERNEL_BASE|0x7F000; pos < (KERNEL_BASE|0x80000); pos += 16) {
105                         if( *(Uint*)(pos) == MPPTR_IDENT ) {
106                                 Log("Possible %p", pos);
107                                 if( ByteSum((void*)pos, sizeof(tMPInfo)) != 0 ) continue;
108                                 gMPFloatPtr = (void*)pos;
109                                 break;
110                         }
111                 }
112         }
113         // - BIOS ROM
114         if(!gMPFloatPtr) {
115                 for(pos = KERNEL_BASE|0xE0000; pos < (KERNEL_BASE|0x100000); pos += 16) {
116                         if( *(Uint*)(pos) == MPPTR_IDENT ) {
117                                 Log("Possible %p", pos);
118                                 if( ByteSum((void*)pos, sizeof(tMPInfo)) != 0 ) continue;
119                                 gMPFloatPtr = (void*)pos;
120                                 break;
121                         }
122                 }
123         }
124         
125         // If the MP Table Exists, parse it
126         if(gMPFloatPtr)
127         {
128                  int    i;
129                 tMPTable_Ent    *ents;
130                 Log("gMPFloatPtr = %p", gMPFloatPtr);
131                 Log("*gMPFloatPtr = {");
132                 Log("\t.Sig = 0x%08x", gMPFloatPtr->Sig);
133                 Log("\t.MPConfig = 0x%08x", gMPFloatPtr->MPConfig);
134                 Log("\t.Length = 0x%02x", gMPFloatPtr->Length);
135                 Log("\t.Version = 0x%02x", gMPFloatPtr->Version);
136                 Log("\t.Checksum = 0x%02x", gMPFloatPtr->Checksum);
137                 Log("\t.Features = [0x%02x,0x%02x,0x%02x,0x%02x,0x%02x]",
138                         gMPFloatPtr->Features[0],       gMPFloatPtr->Features[1],
139                         gMPFloatPtr->Features[2],       gMPFloatPtr->Features[3],
140                         gMPFloatPtr->Features[4]
141                         );
142                 Log("}");
143                 
144                 mptable = (void*)( KERNEL_BASE|gMPFloatPtr->MPConfig );
145                 Log("mptable = %p", mptable);
146                 Log("*mptable = {");
147                 Log("\t.Sig = 0x%08x", mptable->Sig);
148                 Log("\t.BaseTableLength = 0x%04x", mptable->BaseTableLength);
149                 Log("\t.SpecRev = 0x%02x", mptable->SpecRev);
150                 Log("\t.Checksum = 0x%02x", mptable->Checksum);
151                 Log("\t.OEMID = '%8c'", mptable->OemID);
152                 Log("\t.ProductID = '%8c'", mptable->ProductID);
153                 Log("\t.OEMTablePtr = %p'", mptable->OEMTablePtr);
154                 Log("\t.OEMTableSize = 0x%04x", mptable->OEMTableSize);
155                 Log("\t.EntryCount = 0x%04x", mptable->EntryCount);
156                 Log("\t.LocalAPICMemMap = 0x%08x", mptable->LocalAPICMemMap);
157                 Log("\t.ExtendedTableLen = 0x%04x", mptable->ExtendedTableLen);
158                 Log("\t.ExtendedTableChecksum = 0x%02x", mptable->ExtendedTableChecksum);
159                 Log("}");
160                 
161                 gpMP_LocalAPIC = (void*)MM_MapHWPage(mptable->LocalAPICMemMap, 1);
162                 
163                 ents = mptable->Entries;
164                 giNumCPUs = 0;
165                 
166                 for( i = 0; i < mptable->EntryCount; i ++ )
167                 {
168                          int    entSize = 0;
169                         switch( ents->Type )
170                         {
171                         case 0: // Processor
172                                 entSize = 20;
173                                 Log("%i: Processor", i);
174                                 Log("\t.APICID = %i", ents->Proc.APICID);
175                                 Log("\t.APICVer = 0x%02x", ents->Proc.APICVer);
176                                 Log("\t.CPUFlags = 0x%02x", ents->Proc.CPUFlags);
177                                 Log("\t.CPUSignature = 0x%08x", ents->Proc.CPUSignature);
178                                 Log("\t.FeatureFlags = 0x%08x", ents->Proc.FeatureFlags);
179                                 
180                                 
181                                 if( !(ents->Proc.CPUFlags & 1) ) {
182                                         Log("DISABLED");
183                                         break;
184                                 }
185                                 
186                                 // Check if there is too many processors
187                                 if(giNumCPUs >= MAX_CPUS) {
188                                         giNumCPUs ++;   // If `giNumCPUs` > MAX_CPUS later, it will be clipped
189                                         break;
190                                 }
191                                 
192                                 // Initialise CPU Info
193                                 gaAPIC_to_CPU[ents->Proc.APICID] = giNumCPUs;
194                                 gaCPUs[giNumCPUs].APICID = ents->Proc.APICID;
195                                 gaCPUs[giNumCPUs].State = 0;
196                                 giNumCPUs ++;
197                                 
198                                 // Send IPI
199                                 if( !(ents->Proc.CPUFlags & 2) )
200                                 {
201                                         MP_StartAP( giNumCPUs-1 );
202                                 }
203                                 
204                                 break;
205                         case 1: // Bus
206                                 entSize = 8;
207                                 Log("%i: Bus", i);
208                                 Log("\t.ID = %i", ents->Bus.ID);
209                                 Log("\t.TypeString = '%6c'", ents->Bus.TypeString);
210                                 break;
211                         case 2: // I/O APIC
212                                 entSize = 8;
213                                 Log("%i: I/O APIC", i);
214                                 Log("\t.ID = %i", ents->IOAPIC.ID);
215                                 Log("\t.Version = 0x%02x", ents->IOAPIC.Version);
216                                 Log("\t.Flags = 0x%02x", ents->IOAPIC.Flags);
217                                 Log("\t.Addr = 0x%08x", ents->IOAPIC.Addr);
218                                 break;
219                         case 3: // I/O Interrupt Assignment
220                                 entSize = 8;
221                                 Log("%i: I/O Interrupt Assignment", i);
222                                 Log("\t.IntType = %i", ents->IOInt.IntType);
223                                 Log("\t.Flags = 0x%04x", ents->IOInt.Flags);
224                                 Log("\t.SourceBusID = 0x%02x", ents->IOInt.SourceBusID);
225                                 Log("\t.SourceBusIRQ = 0x%02x", ents->IOInt.SourceBusIRQ);
226                                 Log("\t.DestAPICID = 0x%02x", ents->IOInt.DestAPICID);
227                                 Log("\t.DestAPICIRQ = 0x%02x", ents->IOInt.DestAPICIRQ);
228                                 break;
229                         case 4: // Local Interrupt Assignment
230                                 entSize = 8;
231                                 Log("%i: Local Interrupt Assignment", i);
232                                 Log("\t.IntType = %i", ents->LocalInt.IntType);
233                                 Log("\t.Flags = 0x%04x", ents->LocalInt.Flags);
234                                 Log("\t.SourceBusID = 0x%02x", ents->LocalInt.SourceBusID);
235                                 Log("\t.SourceBusIRQ = 0x%02x", ents->LocalInt.SourceBusIRQ);
236                                 Log("\t.DestLocalAPICID = 0x%02x", ents->LocalInt.DestLocalAPICID);
237                                 Log("\t.DestLocalAPICIRQ = 0x%02x", ents->LocalInt.DestLocalAPICIRQ);
238                                 break;
239                         default:
240                                 Log("%i: Unknown (%i)", i, ents->Type);
241                                 break;
242                         }
243                         ents = (void*)( (Uint)ents + entSize );
244                 }
245                 
246                 if( giNumCPUs > MAX_CPUS ) {
247                         Warning("Too many CPUs detected (%i), only using %i of them", giNumCPUs, MAX_CPUS);
248                         giNumCPUs = MAX_CPUS;
249                 }
250         
251                 while( giNumInitingCPUs )
252                         MM_FinishVirtualInit();
253                 
254                 Panic("Uh oh... MP Table Parsing is unimplemented\n");
255         }
256         else {
257                 Log("No MP Table was found, assuming uniprocessor\n");
258                 giNumCPUs = 1;
259                 gTSSs = &gTSS0;
260         }
261         #else
262         giNumCPUs = 1;
263         gTSSs = &gTSS0;
264         MM_FinishVirtualInit();
265         #endif
266         
267         // Initialise Double Fault TSS
268         /*
269         gGDT[5].LimitLow = sizeof(tTSS);
270         gGDT[5].LimitHi = 0;
271         gGDT[5].Access = 0x89;  // Type
272         gGDT[5].Flags = 0x4;
273         */
274         gGDT[5].BaseLow = (Uint)&gDoubleFault_TSS & 0xFFFF;
275         gGDT[5].BaseMid = (Uint)&gDoubleFault_TSS >> 16;
276         gGDT[5].BaseHi = (Uint)&gDoubleFault_TSS >> 24;
277         
278         #if USE_MP
279         // Initialise Normal TSS(s)
280         for(pos=0;pos<giNumCPUs;pos++)
281         {
282         #else
283         pos = 0;
284         #endif
285                 gTSSs[pos].SS0 = 0x10;
286                 gTSSs[pos].ESP0 = 0;    // Set properly by scheduler
287                 gGDT[6+pos].BaseLow = ((Uint)(&gTSSs[pos])) & 0xFFFF;
288                 gGDT[6+pos].BaseMid = ((Uint)(&gTSSs[pos])) >> 16;
289                 gGDT[6+pos].BaseHi = ((Uint)(&gTSSs[pos])) >> 24;
290         #if USE_MP
291         }
292         for(pos=0;pos<giNumCPUs;pos++) {
293         #endif
294                 __asm__ __volatile__ ("ltr %%ax"::"a"(0x30+pos*8));
295         #if USE_MP
296         }
297         #endif
298         
299         #if USE_MP
300         gaCPUs[0].Current = &gThreadZero;
301         #else
302         gCurrentThread = &gThreadZero;
303         #endif
304         
305         #if USE_PAE
306         gThreadZero.MemState.PDP[0] = 0;
307         gThreadZero.MemState.PDP[1] = 0;
308         gThreadZero.MemState.PDP[2] = 0;
309         #else
310         gThreadZero.MemState.CR3 = (Uint)gaInitPageDir - KERNEL_BASE;
311         #endif
312         
313         // Set timer frequency
314         outb(0x43, 0x34);       // Set Channel 0, Low/High, Rate Generator
315         outb(0x40, TIMER_DIVISOR&0xFF); // Low Byte of Divisor
316         outb(0x40, (TIMER_DIVISOR>>8)&0xFF);    // High Byte
317         
318         // Create Per-Process Data Block
319         MM_Allocate(MM_PPD_CFG);
320         
321         // Change Stacks
322         Proc_ChangeStack();
323 }
324
325 #if USE_MP
326 void MP_StartAP(int CPU)
327 {
328         Log("Starting AP %i (APIC %i)", CPU, gaCPUs[CPU].APICID);
329         // Set location of AP startup code and mark for a warm restart
330         *(Uint16*)(KERNEL_BASE|0x467) = (Uint)&APStartup - (KERNEL_BASE|0xFFFF0);
331         *(Uint16*)(KERNEL_BASE|0x469) = 0xFFFF;
332         outb(0x70, 0x0F);       outb(0x71, 0x0A);       // Warm Reset
333         MP_SendIPI(gaCPUs[CPU].APICID, 0, 5);
334         giNumInitingCPUs ++;
335 }
336
337 void MP_SendIPI(Uint8 APICID, int Vector, int DeliveryMode)
338 {
339         Uint32  addr = (Uint)gpMP_LocalAPIC + 0x300;
340         Uint32  val;
341         
342         // Hi
343         val = (Uint)APICID << 24;
344         Log("*%p = 0x%08x", addr+0x10, val);
345         *(Uint32*)(addr+0x10) = val;
346         // Low (and send)
347         val = ((DeliveryMode & 7) << 8) | (Vector & 0xFF);
348         Log("*%p = 0x%08x", addr, val);
349         *(Uint32*)addr = val;
350 }
351 #endif
352
353 /**
354  * \fn void Proc_Start()
355  * \brief Start process scheduler
356  */
357 void Proc_Start()
358 {
359         // Start Interrupts (and hence scheduler)
360         __asm__ __volatile__("sti");
361 }
362
363 /**
364  * \fn tThread *Proc_GetCurThread()
365  * \brief Gets the current thread
366  */
367 tThread *Proc_GetCurThread()
368 {
369         #if USE_MP
370         return gaCPUs[ gaAPIC_to_CPU[gpMP_LocalAPIC->ID.Val&0xFF] ].Current;
371         #else
372         return gCurrentThread;
373         #endif
374 }
375
376 /**
377  * \fn void Proc_ChangeStack()
378  * \brief Swaps the current stack for a new one (in the proper stack reigon)
379  */
380 void Proc_ChangeStack()
381 {
382         Uint    esp, ebp;
383         Uint    tmpEbp, oldEsp;
384         Uint    curBase, newBase;
385
386         __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
387         __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
388
389         oldEsp = esp;
390
391         // Create new KStack
392         newBase = MM_NewKStack();
393         // Check for errors
394         if(newBase == 0) {
395                 Panic("What the?? Unable to allocate space for initial kernel stack");
396                 return;
397         }
398
399         curBase = (Uint)&Kernel_Stack_Top;
400         
401         LOG("curBase = 0x%x, newBase = 0x%x", curBase, newBase);
402
403         // Get ESP as a used size
404         esp = curBase - esp;
405         LOG("memcpy( %p, %p, 0x%x )", (void*)(newBase - esp), (void*)(curBase - esp), esp );
406         // Copy used stack
407         memcpy( (void*)(newBase - esp), (void*)(curBase - esp), esp );
408         // Get ESP as an offset in the new stack
409         esp = newBase - esp;
410         // Adjust EBP
411         ebp = newBase - (curBase - ebp);
412
413         // Repair EBPs & Stack Addresses
414         // Catches arguments also, but may trash stack-address-like values
415         for(tmpEbp = esp; tmpEbp < newBase; tmpEbp += 4)
416         {
417                 if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < curBase)
418                         *(Uint*)tmpEbp += newBase - curBase;
419         }
420         
421         Proc_GetCurThread()->KernelStack = newBase;
422         
423         __asm__ __volatile__ ("mov %0, %%esp"::"r"(esp));
424         __asm__ __volatile__ ("mov %0, %%ebp"::"r"(ebp));
425 }
426
427 /**
428  * \fn int Proc_Clone(Uint *Err, Uint Flags)
429  * \brief Clone the current process
430  */
431 int Proc_Clone(Uint *Err, Uint Flags)
432 {
433         tThread *newThread;
434         tThread *cur = Proc_GetCurThread();
435         Uint    eip, esp, ebp;
436         
437         __asm__ __volatile__ ("mov %%esp, %0": "=r"(esp));
438         __asm__ __volatile__ ("mov %%ebp, %0": "=r"(ebp));
439         
440         newThread = Threads_CloneTCB(Err, Flags);
441         if(!newThread)  return -1;
442         
443         // Initialise Memory Space (New Addr space or kernel stack)
444         if(Flags & CLONE_VM) {
445                 newThread->MemState.CR3 = MM_Clone();
446                 newThread->KernelStack = cur->KernelStack;
447         } else {
448                 Uint    tmpEbp, oldEsp = esp;
449
450                 // Set CR3
451                 newThread->MemState.CR3 = cur->MemState.CR3;
452
453                 // Create new KStack
454                 newThread->KernelStack = MM_NewKStack();
455                 // Check for errors
456                 if(newThread->KernelStack == 0) {
457                         free(newThread);
458                         return -1;
459                 }
460
461                 // Get ESP as a used size
462                 esp = cur->KernelStack - esp;
463                 // Copy used stack
464                 memcpy( (void*)(newThread->KernelStack - esp), (void*)(cur->KernelStack - esp), esp );
465                 // Get ESP as an offset in the new stack
466                 esp = newThread->KernelStack - esp;
467                 // Adjust EBP
468                 ebp = newThread->KernelStack - (cur->KernelStack - ebp);
469
470                 // Repair EBPs & Stack Addresses
471                 // Catches arguments also, but may trash stack-address-like values
472                 for(tmpEbp = esp; tmpEbp < newThread->KernelStack; tmpEbp += 4)
473                 {
474                         if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < cur->KernelStack)
475                                 *(Uint*)tmpEbp += newThread->KernelStack - cur->KernelStack;
476                 }
477         }
478         
479         // Save core machine state
480         newThread->SavedState.ESP = esp;
481         newThread->SavedState.EBP = ebp;
482         eip = GetEIP();
483         if(eip == SWITCH_MAGIC) {
484                 outb(0x20, 0x20);       // ACK Timer and return as child
485                 return 0;
486         }
487         
488         // Set EIP as parent
489         newThread->SavedState.EIP = eip;
490         
491         // Lock list and add to active
492         Threads_AddActive(newThread);
493         
494         return newThread->TID;
495 }
496
497 /**
498  * \fn int Proc_SpawnWorker()
499  * \brief Spawns a new worker thread
500  */
501 int Proc_SpawnWorker()
502 {
503         tThread *new, *cur;
504         Uint    eip, esp, ebp;
505         
506         cur = Proc_GetCurThread();
507         
508         // Create new thread
509         new = malloc( sizeof(tThread) );
510         if(!new) {
511                 Warning("Proc_SpawnWorker - Out of heap space!\n");
512                 return -1;
513         }
514         memcpy(new, &gThreadZero, sizeof(tThread));
515         // Set Thread ID
516         new->TID = giNextTID++;
517         // Create a new worker stack (in PID0's address space)
518         // The stack is relocated by this code
519         new->KernelStack = MM_NewWorkerStack();
520
521         // Get ESP and EBP based in the new stack
522         __asm__ __volatile__ ("mov %%esp, %0": "=r"(esp));
523         __asm__ __volatile__ ("mov %%ebp, %0": "=r"(ebp));
524         esp = new->KernelStack - (cur->KernelStack - esp);
525         ebp = new->KernelStack - (cur->KernelStack - ebp);      
526         
527         // Save core machine state
528         new->SavedState.ESP = esp;
529         new->SavedState.EBP = ebp;
530         eip = GetEIP();
531         if(eip == SWITCH_MAGIC) {
532                 outb(0x20, 0x20);       // ACK Timer and return as child
533                 return 0;
534         }
535         
536         // Set EIP as parent
537         new->SavedState.EIP = eip;
538         // Mark as active
539         new->Status = THREAD_STAT_ACTIVE;
540         Threads_AddActive( new );
541         
542         return new->TID;
543 }
544
545 /**
546  * \fn Uint Proc_MakeUserStack()
547  * \brief Creates a new user stack
548  */
549 Uint Proc_MakeUserStack()
550 {
551          int    i;
552         Uint    base = USER_STACK_TOP - USER_STACK_SZ;
553         
554         // Check Prospective Space
555         for( i = USER_STACK_SZ >> 12; i--; )
556                 if( MM_GetPhysAddr( base + (i<<12) ) != 0 )
557                         break;
558         
559         if(i != -1)     return 0;
560         
561         // Allocate Stack - Allocate incrementally to clean up MM_Dump output
562         for( i = 0; i < USER_STACK_SZ/4069; i++ )
563                 MM_Allocate( base + (i<<12) );
564         
565         return base + USER_STACK_SZ;
566 }
567
568
569 /**
570  * \fn void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize)
571  * \brief Starts a user task
572  */
573 void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize)
574 {
575         Uint    *stack = (void*)Proc_MakeUserStack();
576          int    i;
577         Uint    delta;
578         Uint16  ss, cs;
579         
580         LOG("stack = 0x%x", stack);
581         
582         // Copy Arguments
583         stack = (void*)( (Uint)stack - DataSize );
584         memcpy( stack, ArgV, DataSize );
585         
586         // Adjust Arguments and environment
587         delta = (Uint)stack - (Uint)ArgV;
588         ArgV = (char**)stack;
589         for( i = 0; ArgV[i]; i++ )      ArgV[i] += delta;
590         i ++;
591         EnvP = &ArgV[i];
592         for( i = 0; EnvP[i]; i++ )      EnvP[i] += delta;
593         
594         // User Mode Segments
595         ss = 0x23;      cs = 0x1B;
596         
597         // Arguments
598         *--stack = (Uint)EnvP;
599         *--stack = (Uint)ArgV;
600         *--stack = (Uint)ArgC;
601         while(*Bases)
602                 *--stack = *Bases++;
603         *--stack = 0;   // Return Address
604         delta = (Uint)stack;    // Reuse delta to save SP
605         
606         *--stack = ss;          //Stack Segment
607         *--stack = delta;       //Stack Pointer
608         *--stack = 0x0202;      //EFLAGS (Resvd (0x2) and IF (0x20))
609         *--stack = cs;          //Code Segment
610         *--stack = Entrypoint;  //EIP
611         //PUSHAD
612         *--stack = 0xAAAAAAAA;  // eax
613         *--stack = 0xCCCCCCCC;  // ecx
614         *--stack = 0xDDDDDDDD;  // edx
615         *--stack = 0xBBBBBBBB;  // ebx
616         *--stack = 0xD1D1D1D1;  // edi
617         *--stack = 0x54545454;  // esp - NOT POPED
618         *--stack = 0x51515151;  // esi
619         *--stack = 0xB4B4B4B4;  // ebp
620         //Individual PUSHs
621         *--stack = ss;  // ds
622         *--stack = ss;  // es
623         *--stack = ss;  // fs
624         *--stack = ss;  // gs
625         
626         __asm__ __volatile__ (
627         "mov %%eax,%%esp;\n\t"  // Set stack pointer
628         "pop %%gs;\n\t"
629         "pop %%fs;\n\t"
630         "pop %%es;\n\t"
631         "pop %%ds;\n\t"
632         "popa;\n\t"
633         "iret;\n\t" : : "a" (stack));
634         for(;;);
635 }
636
637 /**
638  * \fn int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
639  * \brief Demotes a process to a lower permission level
640  * \param Err   Pointer to user's errno
641  * \param Dest  New Permission Level
642  * \param Regs  Pointer to user's register structure
643  */
644 int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
645 {
646          int    cpl = Regs->cs & 3;
647         // Sanity Check
648         if(Dest > 3 || Dest < 0) {
649                 *Err = -EINVAL;
650                 return -1;
651         }
652         
653         // Permission Check
654         if(cpl > Dest) {
655                 *Err = -EACCES;
656                 return -1;
657         }
658         
659         // Change the Segment Registers
660         Regs->cs = (((Dest+1)<<4) | Dest) - 8;
661         Regs->ss = ((Dest+1)<<4) | Dest;
662         // Check if the GP Segs are GDT, then change them
663         if(!(Regs->ds & 4))     Regs->ds = ((Dest+1)<<4) | Dest;
664         if(!(Regs->es & 4))     Regs->es = ((Dest+1)<<4) | Dest;
665         if(!(Regs->fs & 4))     Regs->fs = ((Dest+1)<<4) | Dest;
666         if(!(Regs->gs & 4))     Regs->gs = ((Dest+1)<<4) | Dest;
667         
668         return 0;
669 }
670
671 /**
672  * \fn void Proc_Scheduler(int CPU)
673  * \brief Swap current thread and clears dead threads
674  */
675 void Proc_Scheduler(int CPU)
676 {
677         Uint    esp, ebp, eip;
678         tThread *thread;
679         
680         // If the spinlock is set, let it complete
681         if(giThreadListLock)    return;
682         
683         // Clear Delete Queue
684         while(gDeleteThreads)
685         {
686                 thread = gDeleteThreads->Next;
687                 if(gDeleteThreads->IsLocked) {  // Only free if structure is unused
688                         gDeleteThreads->Status = THREAD_STAT_NULL;
689                         free( gDeleteThreads );
690                 }
691                 gDeleteThreads = thread;
692         }
693         
694         // Check if there is any tasks running
695         if(giNumActiveThreads == 0) {
696                 Log("No Active threads, sleeping");
697                 __asm__ __volatile__ ("hlt");
698                 return;
699         }
700         
701         // Get current thread
702         #if USE_MP
703         thread = gaCPUs[CPU].Current;
704         #else
705         thread = gCurrentThread;
706         #endif
707         
708         // Reduce remaining quantum and continue timeslice if non-zero
709         if(thread->Remaining--) return;
710         // Reset quantum for next call
711         thread->Remaining = thread->Quantum;
712         
713         // Get machine state
714         __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
715         __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
716         eip = GetEIP();
717         if(eip == SWITCH_MAGIC) return; // Check if a switch happened
718         
719         // Save machine state
720         thread->SavedState.ESP = esp;
721         thread->SavedState.EBP = ebp;
722         thread->SavedState.EIP = eip;
723         
724         // Get next thread
725         thread = Threads_GetNextToRun(CPU);
726         
727         // Error Check
728         if(thread == NULL) {
729                 Warning("Hmm... Threads_GetNextToRun returned NULL, I don't think this should happen.\n");
730                 return;
731         }
732         
733         #if DEBUG_TRACE_SWITCH
734         Log("Switching to task %i, CR3 = 0x%x, EIP = %p",
735                 thread->TID,
736                 thread->MemState.CR3,
737                 thread->SavedState.EIP
738                 );
739         #endif
740         
741         // Set current thread
742         #if USE_MP
743         gaCPUs[CPU].Current = thread;
744         #else
745         gCurrentThread = thread;
746         #endif
747         
748         // Update Kernel Stack pointer
749         gTSSs[CPU].ESP0 = thread->KernelStack-4;
750         
751         // Set address space
752         #if USE_PAE
753         # error "Todo: Implement PAE Address space switching"
754         #else
755                 __asm__ __volatile__ ("mov %0, %%cr3"::"a"(thread->MemState.CR3));
756         #endif
757         // Switch threads
758         __asm__ __volatile__ (
759                 "mov %1, %%esp\n\t"     // Restore ESP
760                 "mov %2, %%ebp\n\t"     // and EBP
761                 "jmp *%3" : :   // And return to where we saved state (Proc_Clone or Proc_Scheduler)
762                 "a"(SWITCH_MAGIC), "b"(thread->SavedState.ESP),
763                 "d"(thread->SavedState.EBP), "c"(thread->SavedState.EIP)
764                 );
765         for(;;);        // Shouldn't reach here
766 }
767
768 // === EXPORTS ===
769 EXPORT(Proc_SpawnWorker);

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