1 /* -*- mode: c; tab-width: 4; c-basic-offset: 4 -*- */
6 * Copyright (c) 1996 T. J. Wilkinson & Associates, London, UK.
8 * See the file "license.terms" for information on usage and redistribution
9 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
11 * Written by Tim Wilkinson <tim@tjwassoc.demon.co.uk>, 1996.
18 #include <sys/types.h>
19 #include <sys/mman.h> /* for mprotect */
35 static classinfo *class_java_lang_ThreadDeath;
45 #if defined(USE_INTERNAL_THREADS)
47 thread* currentThread = NULL;
49 thread* threadQhead[MAX_THREAD_PRIO + 1];
50 thread* threadQtail[MAX_THREAD_PRIO + 1];
52 thread* liveThreads = NULL;
53 thread* sleepThreads = NULL;
58 ctx contexts[MAXTHREADS];
60 /* Number of threads alive, also counting daemons */
63 /* Number of daemon threads alive */
66 static void firstStartThread(void);
68 void reschedule(void);
70 /* Setup default thread stack size - this can be overwritten if required */
71 int threadStackSize = THREADSTACKSIZE;
73 /* Pointer to the stack of the last killed thread. The free is delayed. */
74 void *stack_to_be_freed = 0;
76 static thread* startDaemon(void* func, char* nm, int stackSize);
79 * Allocate the stack for a thread
82 allocThreadStack (thread *tid, int size)
84 int pageSize = getpagesize(),
86 unsigned long pageBegin;
88 assert(stack_to_be_freed == 0);
91 CONTEXT(tid).stackMem = GCNEW(u1, size + 4 * pageSize);
93 CONTEXT(tid).stackMem = malloc(size + 4 * pageSize);
95 assert(CONTEXT(tid).stackMem != 0);
96 CONTEXT(tid).stackEnd = CONTEXT(tid).stackMem + size + 2 * pageSize;
98 pageBegin = (unsigned long)(CONTEXT(tid).stackMem) + pageSize - 1;
99 pageBegin = pageBegin - pageBegin % pageSize;
102 result = mprotect((void*)pageBegin, pageSize, PROT_NONE);
106 CONTEXT(tid).stackBase = (u1*)pageBegin + pageSize;
110 * Mark the stack for a thread to be freed. We cannot free the stack
111 * immediately because it is still in use!
114 freeThreadStack (thread *tid)
116 if (!(CONTEXT(tid).flags & THREAD_FLAGS_NOSTACKALLOC))
118 int pageSize = getpagesize(),
120 unsigned long pageBegin;
122 pageBegin = (unsigned long)(CONTEXT(tid).stackMem) + pageSize - 1;
123 pageBegin = pageBegin - pageBegin % pageSize;
126 result = mprotect((void*)pageBegin, pageSize,
127 PROT_READ | PROT_WRITE | PROT_EXEC);
131 assert(stack_to_be_freed == 0);
133 stack_to_be_freed = CONTEXT(tid).stackMem;
135 CONTEXT(tid).stackMem = 0;
136 CONTEXT(tid).stackBase = 0;
137 CONTEXT(tid).stackEnd = 0;
141 * Initialize threads.
144 initThreads(u1 *stackbottom)
146 thread *the_main_thread;
149 signal(SIGPIPE, SIG_IGN);
153 for (i = 0; i < MAXTHREADS; ++i) {
154 contexts[i].free = true;
155 contexts[i].thread = NULL;
156 heap_addreference((void**)&contexts[i].thread);
159 /* Allocate a thread to be the main thread */
160 liveThreads = the_main_thread = (thread*)builtin_new(loader_load(utf_new_char("java/lang/Thread")));
161 assert(the_main_thread != 0);
162 /* heap_addreference((void **) &liveThreads); */
164 the_main_thread->PrivateInfo = 1;
165 CONTEXT(the_main_thread).free = false;
167 the_main_thread->name = javastring_new(utf_new_char("main"));
168 the_main_thread->priority = NORM_THREAD_PRIO;
169 CONTEXT(the_main_thread).priority = (u1)the_main_thread->priority;
170 CONTEXT(the_main_thread).exceptionptr = 0;
171 the_main_thread->next = 0;
172 CONTEXT(the_main_thread).status = THREAD_SUSPENDED;
173 CONTEXT(the_main_thread).stackBase = CONTEXT(the_main_thread).stackEnd = stackbottom;
174 THREADINFO(&CONTEXT(the_main_thread));
176 DBG( printf("main thread %p base %p end %p\n",
178 CONTEXT(the_main_thread).stackBase,
179 CONTEXT(the_main_thread).stackEnd); );
181 CONTEXT(the_main_thread).flags = THREAD_FLAGS_NOSTACKALLOC;
182 CONTEXT(the_main_thread).nextlive = 0;
183 CONTEXT(the_main_thread).thread = the_main_thread;
184 the_main_thread->single_step = 0;
185 the_main_thread->daemon = 0;
186 the_main_thread->stillborn = 0;
187 the_main_thread->target = 0;
189 the_main_thread->contextClassLoader = 0;
190 the_main_thread->inheritedAccessControlContext = 0;
191 the_main_thread->values = 0;
193 /* Allocate and init ThreadGroup */
194 the_main_thread->group = (threadGroup*)native_new_and_init(loader_load(utf_new_char("java/lang/ThreadGroup")));
195 assert(the_main_thread->group != 0);
199 /* Load exception classes */
200 class_java_lang_ThreadDeath = loader_load(utf_new_char("java/lang/ThreadDeath"));
202 DBG( fprintf(stderr, "finishing initThreads\n"); );
204 mainThread = currentThread = the_main_thread;
206 /* heap_addreference((void**)&mainThread); */
208 /* Add thread into runQ */
209 iresumeThread(mainThread);
211 assert(blockInts == 0);
215 * Start a new thread running.
218 startThread (thread* tid)
222 /* Allocate a stack context */
223 for (i = 0; i < MAXTHREADS; ++i)
224 if (contexts[i].free)
228 panic("Too many threads");
230 assert(tid->priority >= MIN_THREAD_PRIO && tid->priority <= MAX_THREAD_PRIO);
232 tid->PrivateInfo = i + 1;
233 CONTEXT(tid).free = false;
234 CONTEXT(tid).thread = tid;
235 CONTEXT(tid).nextlive = liveThreads;
237 allocThreadStack(tid, threadStackSize);
238 CONTEXT(tid).usedStackTop = CONTEXT(tid).stackBase;
239 CONTEXT(tid).flags = THREAD_FLAGS_GENERAL;
240 CONTEXT(tid).status = THREAD_SUSPENDED;
241 CONTEXT(tid).priority = (u1)tid->priority;
242 CONTEXT(tid).exceptionptr = 0;
244 /* Construct the initial restore point. */
245 THREADINIT((&CONTEXT(tid)), firstStartThread);
247 DBG( printf("new thread %p base %p end %p\n",
248 tid, CONTEXT(tid).stackBase,
249 CONTEXT(tid).stackEnd); );
255 /* Add thread into runQ */
260 * Start a daemon thread.
263 startDaemon(void* func, char* nm, int stackSize)
268 DBG( printf("startDaemon %s\n", nm); );
270 tid = (thread*)builtin_new(loader_load(utf_new_char("java/lang/Thread")));
273 for (i = 0; i < MAXTHREADS; ++i)
274 if (contexts[i].free)
277 panic("Too many threads");
279 tid->PrivateInfo = i + 1;
280 CONTEXT(tid).free = false;
281 tid->name = 0; /* for the moment */
282 tid->priority = MAX_THREAD_PRIO;
283 CONTEXT(tid).priority = (u1)tid->priority;
285 CONTEXT(tid).status = THREAD_SUSPENDED;
287 allocThreadStack(tid, stackSize);
288 tid->single_step = 0;
294 /* Construct the initial restore point. */
295 THREADINIT((&CONTEXT(tid)), func);
304 * All threads start here.
307 firstStartThread(void)
311 DBG( printf("firstStartThread %p\n", currentThread); );
313 /* Every thread starts with the interrupts off */
315 assert(blockInts == 0);
317 /* Find the run()V method and call it */
318 method = class_findmethod(currentThread->header.vftbl->class,
319 utf_new_char("run"), utf_new_char("()V"));
321 panic("Cannot find method \'void run ()\'");
322 asm_calljavamethod(method, currentThread, NULL, NULL, NULL);
325 assert("Thread returned from killThread" == 0);
329 * Resume a thread running.
330 * This routine has to be called only from locations which ensure
331 * run / block queue consistency. There is no check for illegal resume
332 * conditions (like explicitly resuming an IO blocked thread). There also
333 * is no update of any blocking queue. Both has to be done by the caller
336 iresumeThread(thread* tid)
338 DBG( printf("resumeThread %p\n", tid); );
342 if (CONTEXT(tid).status != THREAD_RUNNING)
344 CONTEXT(tid).status = THREAD_RUNNING;
346 DBG( fprintf(stderr, "prio is %d\n", CONTEXT(tid).priority); );
348 /* Place thread on the end of its queue */
349 if (threadQhead[CONTEXT(tid).priority] == 0) {
350 threadQhead[CONTEXT(tid).priority] = tid;
351 threadQtail[CONTEXT(tid).priority] = tid;
352 if (CONTEXT(tid).priority
353 > CONTEXT(currentThread).priority)
354 needReschedule = true;
358 threadQtail[CONTEXT(tid).priority]->next = tid;
359 threadQtail[CONTEXT(tid).priority] = tid;
363 SDBG( else { printf("Re-resuming %p\n", tid); } );
369 * Yield process to another thread of equal priority.
376 if (threadQhead[CONTEXT(currentThread).priority]
377 != threadQtail[CONTEXT(currentThread).priority])
379 /* Get the next thread and move me to the end */
380 threadQhead[CONTEXT(currentThread).priority] = currentThread->next;
381 threadQtail[CONTEXT(currentThread).priority]->next = currentThread;
382 threadQtail[CONTEXT(currentThread).priority] = currentThread;
383 currentThread->next = 0;
384 needReschedule = true;
391 * Explicit request by user to resume a thread
392 * The definition says that it is just legal to call this after a preceeding
393 * suspend (which got through). If the thread was blocked for some other
394 * reason (either sleep or IO or a muxSem), we simply can't do it
395 * We use a new thread flag THREAD_FLAGS_USER_SUSPEND for this purpose
396 * (which is set by suspendThread(.))
399 resumeThread (thread* tid)
401 if ((CONTEXT(tid).flags & THREAD_FLAGS_USER_SUSPEND) != 0)
404 CONTEXT(tid).flags &= ~THREAD_FLAGS_USER_SUSPEND;
412 * This is an explicit user request to suspend the thread - the counterpart
413 * for resumeThreadRequest(.). It is JUST called by the java method
415 * What makes it distinct is the fact that the suspended thread is not contained
416 * in any block queue. Without a special flag (indicating the user suspend), we
417 * can't check s suspended thread for this condition afterwards (which is
418 * required by resumeThreadRequest()). The new thread flag
419 * THREAD_FLAGS_USER_SUSPEND is used for this purpose.
422 suspendThread(thread* tid)
428 if (CONTEXT(tid).status != THREAD_SUSPENDED)
430 CONTEXT(tid).status = THREAD_SUSPENDED;
433 * This is used to indicate the explicit suspend condition
434 * required by resumeThreadRequest()
436 CONTEXT(tid).flags |= THREAD_FLAGS_USER_SUSPEND;
438 for (ntid = &threadQhead[CONTEXT(tid).priority];
440 ntid = &(*ntid)->next)
446 if (tid == currentThread)
454 SDBG( else { printf("Re-suspending %p\n", tid); } );
460 * Suspend a thread on a queue.
463 suspendOnQThread(thread* tid, thread** queue)
467 DBG( printf("suspendOnQThread %p %p\n", tid, queue); );
469 assert(blockInts > 0);
471 if (CONTEXT(tid).status != THREAD_SUSPENDED)
473 CONTEXT(tid).status = THREAD_SUSPENDED;
475 for (ntid = &threadQhead[CONTEXT(tid).priority];
477 ntid = &(*ntid)->next)
482 /* Insert onto head of lock wait Q */
485 if (tid == currentThread)
487 DBG( fprintf(stderr, "suspending %p (cur=%p) with prio %d\n",
488 tid, currentThread, CONTEXT(tid).priority); );
495 SDBG( else { printf("Re-suspending %p on %p\n", tid, *queue); } );
502 killThread(thread* tid)
508 /* A null tid means the current thread */
514 DBG( printf("killThread %p\n", tid); );
516 if (CONTEXT(tid).status != THREAD_DEAD)
518 /* Get thread off runq (if it needs it) */
519 if (CONTEXT(tid).status == THREAD_RUNNING)
521 for (ntid = &threadQhead[CONTEXT(tid).priority];
523 ntid = &(*ntid)->next)
533 CONTEXT(tid).status = THREAD_DEAD;
539 /* If we only have daemons left, then everyone is dead. */
540 if (talive == tdaemon) {
541 /* atexit functions get called to clean things up */
546 /* Notify on the object just in case anyone is waiting */
547 internal_lock_mutex_for_object(&tid->header);
548 internal_broadcast_cond_for_object(&tid->header);
549 internal_unlock_mutex_for_object(&tid->header);
551 /* Remove thread from live list to it can be garbaged */
552 for (ntid = &liveThreads;
554 ntid = &(CONTEXT((*ntid)).nextlive))
558 (*ntid) = CONTEXT(tid).nextlive;
564 freeThreadStack(tid);
567 if (tid != mainThread) {
568 CONTEXT(tid).free = true;
569 CONTEXT(tid).thread = NULL;
572 /* Run something else */
573 needReschedule = true;
579 * Change thread priority.
582 setPriorityThread(thread* tid, int prio)
586 assert(prio >= MIN_THREAD_PRIO && prio <= MAX_THREAD_PRIO);
588 if (tid->PrivateInfo == 0) {
589 tid->priority = prio;
593 if (CONTEXT(tid).status == THREAD_SUSPENDED) {
594 CONTEXT(tid).priority = (u8)prio;
600 /* Remove from current thread list */
601 for (ntid = &threadQhead[CONTEXT(tid).priority]; *ntid != 0; ntid = &(*ntid)->next) {
608 /* Insert onto a new one */
609 tid->priority = prio;
610 CONTEXT(tid).priority = (u8)tid->priority;
611 if (threadQhead[prio] == 0) {
612 threadQhead[prio] = tid;
613 threadQtail[prio] = tid;
614 if (prio > CONTEXT(currentThread).priority) {
615 needReschedule = true;
619 threadQtail[prio]->next = tid;
620 threadQtail[prio] = tid;
628 * Get the current time in milliseconds since 1970-01-01.
636 gettimeofday(&tv, 0);
640 time += tv.tv_usec / 1000;
646 * Put a thread to sleep.
649 sleepThread (s8 time)
653 /* Sleep for no time */
660 /* Get absolute time */
661 CONTEXT(currentThread).time = time + currentTime();
663 /* Find place in alarm list */
664 for (tidp = &sleepThreads; (*tidp) != 0; tidp = &(*tidp)->next)
666 if (CONTEXT(*tidp).time > CONTEXT(currentThread).time)
670 /* Suspend thread on it */
671 suspendOnQThread(currentThread, tidp);
677 * Is this thread alive?
680 aliveThread(thread* tid)
682 if (tid->PrivateInfo != 0 && CONTEXT(tid).status != THREAD_DEAD)
689 * Reschedule the thread.
690 * Called whenever a change in the running thread is required.
700 /* A reschedule in a non-blocked context is half way to hell */
701 assert(blockInts > 0);
704 /* Check events - we may release a high priority thread */
705 /* Just check IO, no need for a reschedule call by checkEvents() */
706 needReschedule = false;
711 for (i = MAX_THREAD_PRIO; i >= MIN_THREAD_PRIO; i--)
713 if (threadQhead[i] != 0)
715 DBG( fprintf(stderr, "found thread %p in head %d\n", threadQhead[i], i); );
717 if (threadQhead[i] != currentThread)
719 /* USEDSTACKTOP((CONTEXT(currentThread).usedStackTop)); */
721 lastThread = currentThread;
722 currentThread = threadQhead[i];
724 CONTEXT(currentThread).exceptionptr = exceptionptr;
726 THREADSWITCH((&CONTEXT(currentThread)),
727 (&CONTEXT(lastThread)));
730 exceptionptr = CONTEXT(currentThread).exceptionptr;
732 if (stack_to_be_freed != 0)
735 free(stack_to_be_freed);
737 stack_to_be_freed = 0;
740 /* Alarm signal may be blocked - if so
744 if (alarmBlocked == true) {
745 alarmBlocked = false;
747 sigaddset(&nsig, SIGALRM);
748 sigprocmask(SIG_UNBLOCK, &nsig, 0);
752 /* I might be dying */
753 if ((CONTEXT(lastThread).flags & THREAD_FLAGS_KILLED)
756 CONTEXT(lastThread).flags &= ~THREAD_FLAGS_KILLED;
757 exceptionptr = native_new_and_init(class_java_lang_ThreadDeath);
760 /* Now we kill the schedule and turn ints
762 needReschedule = false;
766 /* Nothing to run - wait for external event */
767 DBG( fprintf(stderr, "nothing more to do\n"); );