4 * - Common Thread Control
11 #define DEFAULT_QUANTUM 10
12 #define DEFAULT_TICKETS 5
13 #define MAX_TICKETS 10
14 const enum eConfigTypes cCONFIG_TYPES[] = {
15 CFGT_HEAPSTR, // CFG_VFS_CWD
16 CFGT_INT, // CFG_VFS_MAXFILES
21 extern void ArchThreads_Init();
22 extern void Proc_Start();
23 extern tThread *Proc_GetCurThread();
24 extern int Proc_Clone(Uint *Err, Uint Flags);
28 void Threads_SetName(char *NewName);
29 char *Threads_GetName(int ID);
30 void Threads_SetTickets(int Num);
31 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
32 int Threads_WaitTID(int TID, int *status);
33 tThread *Threads_GetThread(Uint TID);
34 void Threads_AddToDelete(tThread *Thread);
35 tThread *Threads_int_GetPrev(tThread **List, tThread *Thread);
36 void Threads_Exit(int TID, int Status);
37 void Threads_Kill(tThread *Thread, int Status);
40 void Threads_Wake(tThread *Thread);
41 void Threads_AddActive(tThread *Thread);
50 tThread gThreadZero = {
51 NULL, 0, // Next, Lock
52 THREAD_STAT_ACTIVE, // Status
56 0, // Parent Thread ID
63 0, {0}, {0}, // Signal State
65 NULL, NULL, // Messages, Last Message
66 DEFAULT_QUANTUM, DEFAULT_QUANTUM, // Quantum, Remaining
68 {0} // Default config to zero
72 volatile int giThreadListLock = 0; ///\note NEVER use a heap function while locked
73 // --- Current State ---
74 volatile int giNumActiveThreads = 0;
75 volatile int giTotalTickets = 0;
76 volatile Uint giNextTID = 1;
77 // --- Thread Lists ---
78 tThread *gActiveThreads = NULL; // Currently Running Threads
79 tThread *gSleepingThreads = NULL; // Sleeping Threads
80 tThread *gDeleteThreads = NULL; // Threads to delete
85 * \fn void Threads_Init()
86 * \brief Initialse the thread list
92 // Create Initial Task
93 gActiveThreads = &gThreadZero;
94 giTotalTickets = gThreadZero.NumTickets;
95 giNumActiveThreads = 1;
99 if(Proc_Clone(0, 0) == 0)
101 tThread *cur = Proc_GetCurThread();
102 cur->ThreadName = "Idle Thread";
103 Threads_SetTickets(0); // Never called randomly
104 cur->Quantum = 1; // 1 slice quantum
107 HALT(); // Just yeilds
116 * \fn void Threads_SetName(char *NewName)
117 * \brief Sets the current thread's name
119 void Threads_SetName(char *NewName)
121 tThread *cur = Proc_GetCurThread();
122 if( IsHeap(cur->ThreadName) )
123 free( cur->ThreadName );
124 cur->ThreadName = malloc(strlen(NewName)+1);
125 strcpy(cur->ThreadName, NewName);
129 * \fn char *Threads_GetName(int ID)
130 * \brief Gets a thread's name
132 char *Threads_GetName(int ID)
135 return Proc_GetCurThread()->ThreadName;
141 * \fn void Threads_SetTickets(int Num)
142 * \brief Sets the 'priority' of a task
144 void Threads_SetTickets(int Num)
146 tThread *cur = Proc_GetCurThread();
148 if(Num > MAX_TICKETS) Num = MAX_TICKETS;
150 LOCK( &giThreadListLock );
151 giTotalTickets -= cur->NumTickets;
152 cur->NumTickets = Num;
153 giTotalTickets += Num;
154 //LOG("giTotalTickets = %i", giTotalTickets);
155 RELEASE( &giThreadListLock );
159 * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
161 tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
165 cur = Proc_GetCurThread();
167 new = malloc(sizeof(tThread));
175 new->Status = THREAD_STAT_ACTIVE;
179 new->TID = giNextTID++;
180 new->PTID = cur->TID;
183 new->ThreadName = malloc(strlen(cur->ThreadName)+1);
184 strcpy(new->ThreadName, cur->ThreadName);
186 // Set Thread Group ID (PID)
188 new->TGID = new->TID;
190 new->TGID = cur->TGID;
192 // Messages are not inherited
193 new->Messages = NULL;
194 new->LastMessage = NULL;
197 new->Remaining = new->Quantum = cur->Quantum;
198 new->NumTickets = cur->NumTickets;
200 // Set Signal Handlers
203 memset(new->SignalHandlers, 0, sizeof(new->SignalHandlers));
205 memcpy(new->SignalHandlers, cur->SignalHandlers, sizeof(new->SignalHandlers));
206 memset(&new->SignalState, 0, sizeof(tTaskState));
208 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
210 switch(cCONFIG_TYPES[i])
213 new->Config[i] = cur->Config[i];
217 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
228 * \fn Uint *Threads_GetCfgPtr(int Id)
230 Uint *Threads_GetCfgPtr(int Id)
232 if(Id < 0 || Id >= NUM_CFG_ENTRIES) {
233 Warning("Threads_GetCfgPtr: Index %i is out of bounds", Id);
237 return &Proc_GetCurThread()->Config[Id];
241 * \fn void Threads_WaitTID(int TID, int *status)
242 * \brief Wait for a task to change state
244 int Threads_WaitTID(int TID, int *status)
252 // Any peer/child thread
265 tThread *t = Threads_GetThread(TID);
266 int initStatus = t->Status;
268 while(t->Status == initStatus) Threads_Yield();
272 case THREAD_STAT_ZOMBIE:
273 t->Status = THREAD_STAT_DEAD;
274 if(status) *status = 0;
275 Threads_AddToDelete( t );
278 if(status) *status = -1;
288 * \fn tThread *Threads_GetThread(Uint TID)
289 * \brief Gets a thread given its TID
291 tThread *Threads_GetThread(Uint TID)
295 // Search Active List
296 for(thread = gActiveThreads;
298 thread = thread->Next)
300 if(thread->TID == TID)
304 // Search Sleeping List
305 for(thread = gSleepingThreads;
307 thread = thread->Next)
309 if(thread->TID == TID)
317 * \fn void Threads_AddToDelete(tThread *Thread)
318 * \brief Adds a thread to the delete queue
320 void Threads_AddToDelete(tThread *Thread)
322 // Add to delete queue
324 Thread->Next = gDeleteThreads;
325 gDeleteThreads = Thread;
328 gDeleteThreads = Thread;
333 * \fn tThread *Threads_int_GetPrev(tThread *List, tThread *Thread)
334 * \brief Gets the previous entry in a thead linked list
336 tThread *Threads_int_GetPrev(tThread **List, tThread *Thread)
340 if(*List == Thread) {
341 return (tThread*)List;
344 ret->Next && ret->Next != Thread;
347 // Error if the thread is not on the list
348 if(!ret->Next || ret->Next != Thread) {
356 * \fn void Threads_Exit(int TID, int Status)
357 * \brief Exit the current process
359 void Threads_Exit(int TID, int Status)
362 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
364 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
368 * \fn void Threads_Kill(tThread *Thread, int Status)
369 * \brief Kill a thread
370 * \param TID Thread ID (0 for current)
372 void Threads_Kill(tThread *Thread, int Status)
381 for(child = gActiveThreads;
385 if(child->PTID == Thread->TID)
386 Threads_Kill(child, -1);
391 ///\note Double lock is needed due to overlap of locks
393 // Lock thread (stop us recieving messages)
394 LOCK( &Thread->IsLocked );
397 LOCK( &giThreadListLock );
399 // Get previous thread on list
400 prev = Threads_int_GetPrev( &gActiveThreads, Thread );
402 Warning("Proc_Exit - Current thread is not on the active queue");
406 // Clear Message Queue
407 while( Thread->Messages )
409 msg = Thread->Messages->Next;
410 free( Thread->Messages );
411 Thread->Messages = msg;
414 Thread->Remaining = 0; // Clear Remaining Quantum
415 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
416 prev->Next = Thread->Next; // Remove from active
418 giNumActiveThreads --;
419 giTotalTickets -= Thread->NumTickets;
421 // Mark thread as a zombie
422 Thread->RetStatus = Status;
424 // Don't Zombie if we are being killed as part of a tree
427 Thread->Status = THREAD_STAT_DEAD;
428 Threads_AddToDelete( Thread );
430 Thread->Status = THREAD_STAT_ZOMBIE;
434 RELEASE( &Thread->IsLocked ); // Released first so that it IS released
435 RELEASE( &giThreadListLock );
436 if(Status != -1) HALT();
440 * \fn void Threads_Yield()
441 * \brief Yield remainder of timeslice
445 Proc_GetCurThread()->Remaining = 0;
450 * \fn void Threads_Sleep()
451 * \brief Take the current process off the run queue
455 tThread *cur = Proc_GetCurThread();
458 Log("Proc_Sleep: %i going to sleep", cur->TID);
461 LOCK( &giThreadListLock );
463 // Get thread before current thread
464 thread = Threads_int_GetPrev( &gActiveThreads, cur );
466 Warning("Proc_Sleep - Current thread is not on the active queue");
470 // Don't sleep if there is a message waiting
471 if( cur->Messages ) {
472 RELEASE( &giThreadListLock );
476 // Unset remaining timeslices (force a task switch on timer fire)
479 // Remove from active list
480 thread->Next = cur->Next;
482 // Add to Sleeping List (at the top)
483 cur->Next = gSleepingThreads;
484 gSleepingThreads = cur;
486 // Reduce the active count & ticket count
487 giNumActiveThreads --;
488 giTotalTickets -= cur->NumTickets;
490 // Mark thread as sleeping
491 cur->Status = THREAD_STAT_SLEEPING;
494 RELEASE( &giThreadListLock );
501 * \fn void Threads_Wake( tThread *Thread )
502 * \brief Wakes a sleeping/waiting thread up
504 void Threads_Wake(tThread *Thread)
507 switch(Thread->Status)
509 case THREAD_STAT_ACTIVE: break;
510 case THREAD_STAT_SLEEPING:
511 LOCK( &giThreadListLock );
512 prev = Threads_int_GetPrev(&gSleepingThreads, Thread);
513 prev->Next = Thread->Next; // Remove from sleeping queue
514 Thread->Next = gActiveThreads; // Add to active queue
515 gActiveThreads = Thread;
516 Thread->Status = THREAD_STAT_ACTIVE;
517 RELEASE( &giThreadListLock );
519 case THREAD_STAT_WAITING:
520 Warning("Thread_Wake - Waiting threads are not currently supported");
522 case THREAD_STAT_DEAD:
523 Warning("Thread_Wake - Attempt to wake dead thread (%i)", Thread->TID);
526 Warning("Thread_Wake - Unknown process status (%i)\n", Thread->Status);
532 * \fn void Threads_AddActive(tThread *Thread)
533 * \brief Adds a thread to the active queue
535 void Threads_AddActive(tThread *Thread)
537 LOCK( &giThreadListLock );
538 Thread->Next = gActiveThreads;
539 gActiveThreads = Thread;
540 giNumActiveThreads ++;
541 giTotalTickets += Thread->NumTickets;
542 //Log("Threads_AddActive: giNumActiveThreads = %i, giTotalTickets = %i",
543 // giNumActiveThreads, giTotalTickets);
544 RELEASE( &giThreadListLock );
549 * \fn void Threads_SetSignalHandler(int Num, void *Handler)
550 * \brief Sets the signal handler for a signal
552 void Threads_SetSignalHandler(int Num, void *Handler)
554 if(Num < 0 || Num >= NSIG) return;
556 gCurrentThread->SignalHandlers[Num] = Handler;
560 * \fn void Threads_SendSignal(int TID, int Num)
561 * \brief Send a signal to a thread
563 void Threads_SendSignal(int TID, int Num)
565 tThread *thread = Proc_GetThread(TID);
570 handler = thread->SignalHandlers[Num];
573 if(handler == SIG_ERR) {
583 if(handler == -2) return;
585 // Check the type and handle if the thread is already in a signal
586 if(thread->CurSignal != 0) {
587 if(Num < _SIGTYPE_FATAL)
590 while(thread->CurSignal != 0)
599 // --- Process Structure Access Functions ---
602 return Proc_GetCurThread()->TGID;
606 return Proc_GetCurThread()->TID;
610 return Proc_GetCurThread()->UID;
614 return Proc_GetCurThread()->GID;
618 * \fn void Threads_Dump()
619 * \brief Dums a list of currently running threads
625 Log("Active Threads:");
626 for(thread=gActiveThreads;thread;thread=thread->Next)
628 Log(" %i (%i) - %s", thread->TID, thread->TGID, thread->ThreadName);
629 Log(" %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
630 Log(" KStack 0x%x", thread->KernelStack);
632 Log("Sleeping Threads:");
633 for(thread=gSleepingThreads;thread;thread=thread->Next)
635 Log(" %i (%i) - %s", thread->TID, thread->TGID, thread->ThreadName);
636 Log(" %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
637 Log(" KStack 0x%x", thread->KernelStack);
642 * \fn tThread *Threads_GetNextToRun(int CPU)
643 * \brief Gets the next thread to run
645 tThread *Threads_GetNextToRun(int CPU)
651 if(giNumActiveThreads == 0) return NULL;
653 // Special case: 1 thread
654 if(giNumActiveThreads == 1) {
655 return gActiveThreads;
658 //Log(" Threads_GetNextToRun: giNumActiveThreads=%i,giTotalTickets=%i",
659 // giNumActiveThreads, giTotalTickets);
660 // Get the ticket number
661 ticket = number = rand() % giTotalTickets;
663 //Log(" Threads_GetNextToRun: ticket = %i", ticket);
665 // Find the next thread
666 for(thread=gActiveThreads;thread;thread=thread->Next)
668 if(thread->NumTickets > number) break;
669 number -= thread->NumTickets;
676 for(thread=gActiveThreads;thread;thread=thread->Next)
677 number += thread->NumTickets;
678 Panic("Bookeeping Failed - giTotalTicketCount (%i) != true count (%i)",
679 giTotalTickets, number);
686 * \fn void Threads_SegFault(tVAddr Addr)
687 * \brief Called when a Segment Fault occurs
689 void Threads_SegFault(tVAddr Addr)
691 //Threads_SendSignal( Proc_GetCurThread()->TID, SIGSEGV );
692 Log("Thread #%i committed a segfault at address %p\n", Proc_GetCurThread()->TID, Addr);
693 Threads_Exit( 0, 0 );