OSDN Git Service

Bug fixes for ld/st elimination.
[android-x86/dalvik.git] / vm / Thread.h
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /*
18  * VM thread support.
19  */
20 #ifndef _DALVIK_THREAD
21 #define _DALVIK_THREAD
22
23 #include "jni.h"
24 #include "interp/InterpState.h"
25
26 #include <errno.h>
27 #include <cutils/sched_policy.h>
28
29
30 #if defined(CHECK_MUTEX) && !defined(__USE_UNIX98)
31 /* glibc lacks this unless you #define __USE_UNIX98 */
32 int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);
33 enum { PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP };
34 #endif
35
36 /*
37  * Current status; these map to JDWP constants, so don't rearrange them.
38  * (If you do alter this, update the strings in dvmDumpThread and the
39  * conversion table in VMThread.java.)
40  *
41  * Note that "suspended" is orthogonal to these values (so says JDWP).
42  */
43 typedef enum ThreadStatus {
44     THREAD_UNDEFINED    = -1,       /* makes enum compatible with int32_t */
45
46     /* these match up with JDWP values */
47     THREAD_ZOMBIE       = 0,        /* TERMINATED */
48     THREAD_RUNNING      = 1,        /* RUNNABLE or running now */
49     THREAD_TIMED_WAIT   = 2,        /* TIMED_WAITING in Object.wait() */
50     THREAD_MONITOR      = 3,        /* BLOCKED on a monitor */
51     THREAD_WAIT         = 4,        /* WAITING in Object.wait() */
52     /* non-JDWP states */
53     THREAD_INITIALIZING = 5,        /* allocated, not yet running */
54     THREAD_STARTING     = 6,        /* started, not yet on thread list */
55     THREAD_NATIVE       = 7,        /* off in a JNI native method */
56     THREAD_VMWAIT       = 8,        /* waiting on a VM resource */
57     THREAD_SUSPENDED    = 9,        /* suspended, usually by GC or debugger */
58 } ThreadStatus;
59
60 /* thread priorities, from java.lang.Thread */
61 enum {
62     THREAD_MIN_PRIORITY     = 1,
63     THREAD_NORM_PRIORITY    = 5,
64     THREAD_MAX_PRIORITY     = 10,
65 };
66
67
68 /* initialization */
69 bool dvmThreadStartup(void);
70 void dvmThreadShutdown(void);
71 void dvmSlayDaemons(void);
72
73
74 #define kJniLocalRefMin         32
75 #define kJniLocalRefMax         512     /* arbitrary; should be plenty */
76 #define kInternalRefDefault     32      /* equally arbitrary */
77 #define kInternalRefMax         4096    /* mainly a sanity check */
78
79 #define kMinStackSize       (512 + STACK_OVERFLOW_RESERVE)
80 #define kDefaultStackSize   (16*1024)   /* four 4K pages */
81 #define kMaxStackSize       (256*1024 + STACK_OVERFLOW_RESERVE)
82
83 /*
84  * Interpreter control struction.  Packed into a long long to enable
85  * atomic updates.
86  */
87 typedef union InterpBreak {
88     volatile int64_t   all;
89     struct {
90         uint8_t    breakFlags;
91         uint8_t    subMode;
92         int8_t     suspendCount;
93         int8_t     dbgSuspendCount;
94 #ifndef DVM_NO_ASM_INTERP
95         void* curHandlerTable;
96 #else
97         void* unused;
98 #endif
99     } ctl;
100 } InterpBreak;
101
102 /*
103  * Our per-thread data.
104  *
105  * These are allocated on the system heap.
106  */
107 typedef struct Thread {
108     /*
109      * Interpreter state which must be preserved across nested
110      * interpreter invocations (via JNI callbacks).  Must be the first
111      * element in Thread.
112      */
113     InterpSaveState interpSave;
114
115     /* small unique integer; useful for "thin" locks and debug messages */
116     u4          threadId;
117
118     /*
119      * Begin interpreter state which does not need to be preserved, but should
120      * be located towards the beginning of the Thread structure for
121      * efficiency.
122      */
123     JValue      retval;
124
125     u1*         cardTable;
126
127     /* current limit of stack; flexes for StackOverflowError */
128     const u1*   interpStackEnd;
129
130     /* FP of bottom-most (currently executing) stack frame on interp stack */
131     void*       curFrame;
132     /* current exception, or NULL if nothing pending */
133     Object*     exception;
134
135     bool        debugIsMethodEntry;
136     /* interpreter stack size; our stacks are fixed-length */
137     int         interpStackSize;
138     bool        stackOverflowed;
139
140     /* thread handle, as reported by pthread_self() */
141     pthread_t   handle;
142
143     /*
144      * interpBreak contains info about the interpreter mode, as well as
145      * a count of the number of times the thread has been suspended.  When
146      * the count drops to zero, the thread resumes.
147      *
148      * "dbgSuspendCount" is the portion of the suspend count that the
149      * debugger is responsible for.  This has to be tracked separately so
150      * that we can recover correctly if the debugger abruptly disconnects
151      * (suspendCount -= dbgSuspendCount).  The debugger should not be able
152      * to resume GC-suspended threads, because we ignore the debugger while
153      * a GC is in progress.
154      *
155      * Both of these are guarded by gDvm.threadSuspendCountLock.
156      *
157      * Note the non-debug component will rarely be other than 1 or 0 -- (not
158      * sure it's even possible with the way mutexes are currently used.)
159      */
160     InterpBreak interpBreak;
161
162
163     /* Assembly interpreter handler tables */
164 #ifndef DVM_NO_ASM_INTERP
165     void*       mainHandlerTable;   // Table of actual instruction handler
166     void*       altHandlerTable;    // Table of breakout handlers
167 #else
168     void*       unused0;            // Consume space to keep offsets
169     void*       unused1;            //   the same between builds with
170 #endif
171
172     /*
173      * singleStepCount is a countdown timer used with the breakFlag
174      * kInterpSingleStep.  If kInterpSingleStep is set in breakFlags,
175      * singleStepCount will decremented each instruction execution.
176      * Once it reaches zero, the kInterpSingleStep flag in breakFlags
177      * will be cleared.  This can be used to temporarily prevent
178      * execution from re-entering JIT'd code or force inter-instruction
179      * checks by delaying the reset of curHandlerTable to mainHandlerTable.
180      */
181     int         singleStepCount;
182
183 #ifdef WITH_JIT
184     struct JitToInterpEntries jitToInterpEntries;
185     /*
186      * Whether the current top VM frame is in the interpreter or JIT cache:
187      *   NULL    : in the interpreter
188      *   non-NULL: entry address of the JIT'ed code (the actual value doesn't
189      *             matter)
190      */
191     void*             inJitCodeCache;
192     unsigned char*    pJitProfTable;
193     int               jitThreshold;
194     const void*       jitResumeNPC;     // Translation return point
195     const u4*         jitResumeNSP;     // Native SP at return point
196     const u2*         jitResumeDPC;     // Dalvik inst following single-step
197     JitState    jitState;
198     int         icRechainCount;
199     const void* pProfileCountdown;
200     const ClassObject* callsiteClass;
201     const Method*     methodToCall;
202 #endif
203
204     /* JNI local reference tracking */
205     IndirectRefTable jniLocalRefTable;
206
207 #if defined(WITH_JIT)
208 #if defined(WITH_SELF_VERIFICATION)
209     /* Buffer for register state during self verification */
210     struct ShadowSpace* shadowSpace;
211 #endif
212     int         currTraceRun;
213     int         totalTraceLen;  // Number of Dalvik insts in trace
214     const u2*   currTraceHead;  // Start of the trace we're building
215     const u2*   currRunHead;    // Start of run we're building
216     int         currRunLen;     // Length of run in 16-bit words
217     const u2*   lastPC;         // Stage the PC for the threaded interpreter
218     const Method*  traceMethod; // Starting method of current trace
219     intptr_t    threshFilter[JIT_TRACE_THRESH_FILTER_SIZE];
220     JitTraceRun trace[MAX_JIT_RUN_LEN];
221 #endif
222
223     /*
224      * Thread's current status.  Can only be changed by the thread itself
225      * (i.e. don't mess with this from other threads).
226      */
227     volatile ThreadStatus status;
228
229     /* thread ID, only useful under Linux */
230     pid_t       systemTid;
231
232     /* start (high addr) of interp stack (subtract size to get malloc addr) */
233     u1*         interpStackStart;
234
235     /* the java/lang/Thread that we are associated with */
236     Object*     threadObj;
237
238     /* the JNIEnv pointer associated with this thread */
239     JNIEnv*     jniEnv;
240
241     /* internal reference tracking */
242     ReferenceTable  internalLocalRefTable;
243
244
245     /* JNI native monitor reference tracking (initialized on first use) */
246     ReferenceTable  jniMonitorRefTable;
247
248     /* hack to make JNI_OnLoad work right */
249     Object*     classLoaderOverride;
250
251     /* mutex to guard the interrupted and the waitMonitor members */
252     pthread_mutex_t    waitMutex;
253
254     /* pointer to the monitor lock we're currently waiting on */
255     /* guarded by waitMutex */
256     /* TODO: consider changing this to Object* for better JDWP interaction */
257     Monitor*    waitMonitor;
258
259     /* thread "interrupted" status; stays raised until queried or thrown */
260     /* guarded by waitMutex */
261     bool        interrupted;
262
263     /* links to the next thread in the wait set this thread is part of */
264     struct Thread*     waitNext;
265
266     /* object to sleep on while we are waiting for a monitor */
267     pthread_cond_t     waitCond;
268
269     /*
270      * Set to true when the thread is in the process of throwing an
271      * OutOfMemoryError.
272      */
273     bool        throwingOOME;
274
275     /* links to rest of thread list; grab global lock before traversing */
276     struct Thread* prev;
277     struct Thread* next;
278
279     /* used by threadExitCheck when a thread exits without detaching */
280     int         threadExitCheckCount;
281
282     /* JDWP invoke-during-breakpoint support */
283     DebugInvokeReq  invokeReq;
284
285     /* base time for per-thread CPU timing (used by method profiling) */
286     bool        cpuClockBaseSet;
287     u8          cpuClockBase;
288
289     /* memory allocation profiling state */
290     AllocProfState allocProf;
291
292 #ifdef WITH_JNI_STACK_CHECK
293     u4          stackCrc;
294 #endif
295
296 #if WITH_EXTRA_GC_CHECKS > 1
297     /* PC, saved on every instruction; redundant with StackSaveArea */
298     const u2*   currentPc2;
299 #endif
300
301     /* Safepoint callback state */
302     pthread_mutex_t   callbackMutex;
303     SafePointCallback callback;
304     void*             callbackArg;
305 } Thread;
306
307 /* start point for an internal thread; mimics pthread args */
308 typedef void* (*InternalThreadStart)(void* arg);
309
310 /* args for internal thread creation */
311 typedef struct InternalStartArgs {
312     /* inputs */
313     InternalThreadStart func;
314     void*       funcArg;
315     char*       name;
316     Object*     group;
317     bool        isDaemon;
318     /* result */
319     volatile Thread** pThread;
320     volatile int*     pCreateStatus;
321 } InternalStartArgs;
322
323 /* finish init */
324 bool dvmPrepMainForJni(JNIEnv* pEnv);
325 bool dvmPrepMainThread(void);
326
327 /* utility function to get the tid */
328 pid_t dvmGetSysThreadId(void);
329
330 /*
331  * Get our Thread* from TLS.
332  *
333  * Returns NULL if this isn't a thread that the VM is aware of.
334  */
335 Thread* dvmThreadSelf(void);
336
337 /* grab the thread list global lock */
338 void dvmLockThreadList(Thread* self);
339 /* try to grab the thread list global lock */
340 bool dvmTryLockThreadList(void);
341 /* release the thread list global lock */
342 void dvmUnlockThreadList(void);
343
344 /*
345  * Thread suspend/resume, used by the GC and debugger.
346  */
347 typedef enum SuspendCause {
348     SUSPEND_NOT = 0,
349     SUSPEND_FOR_GC,
350     SUSPEND_FOR_DEBUG,
351     SUSPEND_FOR_DEBUG_EVENT,
352     SUSPEND_FOR_STACK_DUMP,
353     SUSPEND_FOR_DEX_OPT,
354     SUSPEND_FOR_VERIFY,
355     SUSPEND_FOR_HPROF,
356 #if defined(WITH_JIT)
357     SUSPEND_FOR_TBL_RESIZE,  // jit-table resize
358     SUSPEND_FOR_IC_PATCH,    // polymorphic callsite inline-cache patch
359     SUSPEND_FOR_CC_RESET,    // code-cache reset
360     SUSPEND_FOR_REFRESH,     // Reload data cached in interpState
361 #endif
362 } SuspendCause;
363 void dvmSuspendThread(Thread* thread);
364 void dvmSuspendSelf(bool jdwpActivity);
365 void dvmResumeThread(Thread* thread);
366 void dvmSuspendAllThreads(SuspendCause why);
367 void dvmResumeAllThreads(SuspendCause why);
368 void dvmUndoDebuggerSuspensions(void);
369
370 /*
371  * Check suspend state.  Grab threadListLock before calling.
372  */
373 bool dvmIsSuspended(const Thread* thread);
374
375 /*
376  * Wait until a thread has suspended.  (Used by debugger support.)
377  */
378 void dvmWaitForSuspend(Thread* thread);
379
380 /*
381  * Check to see if we should be suspended now.  If so, suspend ourselves
382  * by sleeping on a condition variable.
383  */
384 bool dvmCheckSuspendPending(Thread* self);
385
386 /*
387  * Fast test for use in the interpreter.  Returns "true" if our suspend
388  * count is nonzero.
389  */
390 INLINE bool dvmCheckSuspendQuick(Thread* self) {
391     return (self->interpBreak.ctl.breakFlags & kInterpSuspendBreak);
392 }
393
394 /*
395  * Used when changing thread state.  Threads may only change their own.
396  * The "self" argument, which may be NULL, is accepted as an optimization.
397  *
398  * If you're calling this before waiting on a resource (e.g. THREAD_WAIT
399  * or THREAD_MONITOR), do so in the same function as the wait -- this records
400  * the current stack depth for the GC.
401  *
402  * If you're changing to THREAD_RUNNING, this will check for suspension.
403  *
404  * Returns the old status.
405  */
406 ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
407
408 /*
409  * Initialize a mutex.
410  */
411 INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
412 {
413 #ifdef CHECK_MUTEX
414     pthread_mutexattr_t attr;
415     int cc;
416
417     pthread_mutexattr_init(&attr);
418     cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
419     assert(cc == 0);
420     pthread_mutex_init(pMutex, &attr);
421     pthread_mutexattr_destroy(&attr);
422 #else
423     pthread_mutex_init(pMutex, NULL);       // default=PTHREAD_MUTEX_FAST_NP
424 #endif
425 }
426
427 /*
428  * Grab a plain mutex.
429  */
430 INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
431 {
432     int cc __attribute__ ((__unused__)) = pthread_mutex_lock(pMutex);
433     assert(cc == 0);
434 }
435
436 /*
437  * Try grabbing a plain mutex.  Returns 0 if successful.
438  */
439 INLINE int dvmTryLockMutex(pthread_mutex_t* pMutex)
440 {
441     int cc = pthread_mutex_trylock(pMutex);
442     assert(cc == 0 || cc == EBUSY);
443     return cc;
444 }
445
446 /*
447  * Unlock pthread mutex.
448  */
449 INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
450 {
451     int cc __attribute__ ((__unused__)) = pthread_mutex_unlock(pMutex);
452     assert(cc == 0);
453 }
454
455 /*
456  * Destroy a mutex.
457  */
458 INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
459 {
460     int cc __attribute__ ((__unused__)) = pthread_mutex_destroy(pMutex);
461     assert(cc == 0);
462 }
463
464 INLINE void dvmBroadcastCond(pthread_cond_t* pCond)
465 {
466     int cc __attribute__ ((__unused__)) = pthread_cond_broadcast(pCond);
467     assert(cc == 0);
468 }
469
470 INLINE void dvmSignalCond(pthread_cond_t* pCond)
471 {
472     int cc __attribute__ ((__unused__)) = pthread_cond_signal(pCond);
473     assert(cc == 0);
474 }
475
476 INLINE void dvmWaitCond(pthread_cond_t* pCond, pthread_mutex_t* pMutex)
477 {
478     int cc __attribute__ ((__unused__)) = pthread_cond_wait(pCond, pMutex);
479     assert(cc == 0);
480 }
481
482 /*
483  * Create a thread as a result of java.lang.Thread.start().
484  */
485 bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
486
487 /*
488  * Create a thread internal to the VM.  It's visible to interpreted code,
489  * but found in the "system" thread group rather than "main".
490  */
491 bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
492     InternalThreadStart func, void* funcArg);
493
494 /*
495  * Attach or detach the current thread from the VM.
496  */
497 bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
498 void dvmDetachCurrentThread(void);
499
500 /*
501  * Get the "main" or "system" thread group.
502  */
503 Object* dvmGetMainThreadGroup(void);
504 Object* dvmGetSystemThreadGroup(void);
505
506 /*
507  * Given a java/lang/VMThread object, return our Thread.
508  */
509 Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
510
511 /*
512  * Given a pthread handle, return the associated Thread*.
513  * Caller must hold the thread list lock.
514  *
515  * Returns NULL if the thread was not found.
516  */
517 Thread* dvmGetThreadByHandle(pthread_t handle);
518
519 /*
520  * Given a thread ID, return the associated Thread*.
521  * Caller must hold the thread list lock.
522  *
523  * Returns NULL if the thread was not found.
524  */
525 Thread* dvmGetThreadByThreadId(u4 threadId);
526
527 /*
528  * Sleep in a thread.  Returns when the sleep timer returns or the thread
529  * is interrupted.
530  */
531 void dvmThreadSleep(u8 msec, u4 nsec);
532
533 /*
534  * Get the name of a thread.  (For safety, hold the thread list lock.)
535  */
536 char* dvmGetThreadName(Thread* thread);
537
538 /*
539  * Convert ThreadStatus to a string.
540  */
541 const char* dvmGetThreadStatusStr(ThreadStatus status);
542
543 /*
544  * Return true if a thread is on the internal list.  If it is, the
545  * thread is part of the GC's root set.
546  */
547 bool dvmIsOnThreadList(const Thread* thread);
548
549 /*
550  * Get/set the JNIEnv field.
551  */
552 INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
553 INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
554
555 /*
556  * Update the priority value of the underlying pthread.
557  */
558 void dvmChangeThreadPriority(Thread* thread, int newPriority);
559
560 /* "change flags" values for raise/reset thread priority calls */
561 #define kChangedPriority    0x01
562 #define kChangedPolicy      0x02
563
564 /*
565  * If necessary, raise the thread's priority to nice=0 cgroup=fg.
566  *
567  * Returns bit flags indicating changes made (zero if nothing was done).
568  */
569 int dvmRaiseThreadPriorityIfNeeded(Thread* thread, int* pSavedThreadPrio,
570     SchedPolicy* pSavedThreadPolicy);
571
572 /*
573  * Drop the thread priority to what it was before an earlier call to
574  * dvmRaiseThreadPriorityIfNeeded().
575  */
576 void dvmResetThreadPriority(Thread* thread, int changeFlags,
577     int savedThreadPrio, SchedPolicy savedThreadPolicy);
578
579 /*
580  * Debug: dump information about a single thread.
581  */
582 void dvmDumpThread(Thread* thread, bool isRunning);
583 void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
584     bool isRunning);
585
586 /*
587  * Debug: dump information about all threads.
588  */
589 void dvmDumpAllThreads(bool grabLock);
590 void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
591
592 /*
593  * Debug: kill a thread to get a debuggerd stack trace.  Leaves the VM
594  * in an uncertain state.
595  */
596 void dvmNukeThread(Thread* thread);
597
598 #endif /*_DALVIK_THREAD*/