OSDN Git Service

dalvik: Switch to common cutils sched_policy api
[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
25 #if defined(CHECK_MUTEX) && !defined(__USE_UNIX98)
26 /* glibc lacks this unless you #define __USE_UNIX98 */
27 int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type);
28 enum { PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP };
29 #endif
30
31 #ifdef WITH_MONITOR_TRACKING
32 struct LockedObjectData;
33 #endif
34
35 /*
36  * Current status; these map to JDWP constants, so don't rearrange them.
37  * (If you do alter this, update the strings in dvmDumpThread and the
38  * conversion table in VMThread.java.)
39  *
40  * Note that "suspended" is orthogonal to these values (so says JDWP).
41  */
42 typedef enum ThreadStatus {
43     /* these match up with JDWP values */
44     THREAD_ZOMBIE       = 0,        /* TERMINATED */
45     THREAD_RUNNING      = 1,        /* RUNNABLE or running now */
46     THREAD_TIMED_WAIT   = 2,        /* TIMED_WAITING in Object.wait() */
47     THREAD_MONITOR      = 3,        /* BLOCKED on a monitor */
48     THREAD_WAIT         = 4,        /* WAITING in Object.wait() */
49     /* non-JDWP states */
50     THREAD_INITIALIZING = 5,        /* allocated, not yet running */
51     THREAD_STARTING     = 6,        /* started, not yet on thread list */
52     THREAD_NATIVE       = 7,        /* off in a JNI native method */
53     THREAD_VMWAIT       = 8,        /* waiting on a VM resource */
54 } ThreadStatus;
55
56 /* thread priorities, from java.lang.Thread */
57 enum {
58     THREAD_MIN_PRIORITY     = 1,
59     THREAD_NORM_PRIORITY    = 5,
60     THREAD_MAX_PRIORITY     = 10,
61 };
62
63
64 /* initialization */
65 bool dvmThreadStartup(void);
66 bool dvmThreadObjStartup(void);
67 void dvmThreadShutdown(void);
68 void dvmSlayDaemons(void);
69
70
71 #define kJniLocalRefMin         32
72 #define kJniLocalRefMax         512     /* arbitrary; should be plenty */
73 #define kInternalRefDefault     32      /* equally arbitrary */
74 #define kInternalRefMax         4096    /* mainly a sanity check */
75
76 #define kMinStackSize       (512 + STACK_OVERFLOW_RESERVE)
77 #define kDefaultStackSize   (12*1024)   /* three 4K pages */
78 #define kMaxStackSize       (256*1024 + STACK_OVERFLOW_RESERVE)
79
80 /*
81  * System thread state. See native/SystemThread.h.
82  */
83 typedef struct SystemThread SystemThread;
84
85 /*
86  * Our per-thread data.
87  *
88  * These are allocated on the system heap.
89  */
90 typedef struct Thread {
91     /* small unique integer; useful for "thin" locks and debug messages */
92     u4          threadId;
93
94     /*
95      * Thread's current status.  Can only be changed by the thread itself
96      * (i.e. don't mess with this from other threads).
97      */
98     volatile ThreadStatus status;
99
100     /*
101      * This is the number of times the thread has been suspended.  When the
102      * count drops to zero, the thread resumes.
103      *
104      * "dbgSuspendCount" is the portion of the suspend count that the
105      * debugger is responsible for.  This has to be tracked separately so
106      * that we can recover correctly if the debugger abruptly disconnects
107      * (suspendCount -= dbgSuspendCount).  The debugger should not be able
108      * to resume GC-suspended threads, because we ignore the debugger while
109      * a GC is in progress.
110      *
111      * Both of these are guarded by gDvm.threadSuspendCountLock.
112      *
113      * (We could store both of these in the same 32-bit, using 16-bit
114      * halves, to make atomic ops possible.  In practice, you only need
115      * to read suspendCount, and we need to hold a mutex when making
116      * changes, so there's no need to merge them.  Note the non-debug
117      * component will rarely be other than 1 or 0 -- not sure it's even
118      * possible with the way mutexes are currently used.)
119      */
120     int         suspendCount;
121     int         dbgSuspendCount;
122
123     /*
124      * Set to true when the thread suspends itself, false when it wakes up.
125      * This is only expected to be set when status==THREAD_RUNNING.
126      */
127     bool        isSuspended;
128
129     /* thread handle, as reported by pthread_self() */
130     pthread_t   handle;
131
132     /* thread ID, only useful under Linux */
133     pid_t       systemTid;
134
135     /* start (high addr) of interp stack (subtract size to get malloc addr) */
136     u1*         interpStackStart;
137
138     /* current limit of stack; flexes for StackOverflowError */
139     const u1*   interpStackEnd;
140
141     /* interpreter stack size; our stacks are fixed-length */
142     int         interpStackSize;
143     bool        stackOverflowed;
144
145     /* FP of bottom-most (currently executing) stack frame on interp stack */
146     void*       curFrame;
147
148     /* current exception, or NULL if nothing pending */
149     Object*     exception;
150
151     /* the java/lang/Thread that we are associated with */
152     Object*     threadObj;
153
154     /* the JNIEnv pointer associated with this thread */
155     JNIEnv*     jniEnv;
156
157     /* internal reference tracking */
158     ReferenceTable  internalLocalRefTable;
159
160     /* JNI local reference tracking */
161 #ifdef USE_INDIRECT_REF
162     IndirectRefTable jniLocalRefTable;
163 #else
164     ReferenceTable  jniLocalRefTable;
165 #endif
166
167     /* JNI native monitor reference tracking (initialized on first use) */
168     ReferenceTable  jniMonitorRefTable;
169
170     /* hack to make JNI_OnLoad work right */
171     Object*     classLoaderOverride;
172
173     /* pointer to the monitor lock we're currently waiting on */
174     /* (do not set or clear unless the Monitor itself is held) */
175     /* TODO: consider changing this to Object* for better JDWP interaction */
176     Monitor*    waitMonitor;
177     /* set when we confirm that the thread must be interrupted from a wait */
178     bool        interruptingWait;
179     /* thread "interrupted" status; stays raised until queried or thrown */
180     bool        interrupted;
181
182     /*
183      * Set to true when the thread is in the process of throwing an
184      * OutOfMemoryError.
185      */
186     bool        throwingOOME;
187
188     /* links to rest of thread list; grab global lock before traversing */
189     struct Thread* prev;
190     struct Thread* next;
191
192     /* JDWP invoke-during-breakpoint support */
193     DebugInvokeReq  invokeReq;
194
195 #ifdef WITH_MONITOR_TRACKING
196     /* objects locked by this thread; most recent is at head of list */
197     struct LockedObjectData* pLockedObjects;
198 #endif
199
200 #ifdef WITH_ALLOC_LIMITS
201     /* allocation limit, for Debug.setAllocationLimit() regression testing */
202     int         allocLimit;
203 #endif
204
205 #ifdef WITH_PROFILER
206     /* base time for per-thread CPU timing */
207     bool        cpuClockBaseSet;
208     u8          cpuClockBase;
209
210     /* memory allocation profiling state */
211     AllocProfState allocProf;
212 #endif
213
214 #ifdef WITH_JNI_STACK_CHECK
215     u4          stackCrc;
216 #endif
217
218 #if WITH_EXTRA_GC_CHECKS > 1
219     /* PC, saved on every instruction; redundant with StackSaveArea */
220     const u2*   currentPc2;
221 #endif
222
223     /* system thread state */
224     SystemThread* systemThread;
225 } Thread;
226
227 /* start point for an internal thread; mimics pthread args */
228 typedef void* (*InternalThreadStart)(void* arg);
229
230 /* args for internal thread creation */
231 typedef struct InternalStartArgs {
232     /* inputs */
233     InternalThreadStart func;
234     void*       funcArg;
235     char*       name;
236     Object*     group;
237     bool        isDaemon;
238     /* result */
239     volatile Thread** pThread;
240     volatile int*     pCreateStatus;
241 } InternalStartArgs;
242
243 /* finish init */
244 bool dvmPrepMainForJni(JNIEnv* pEnv);
245 bool dvmPrepMainThread(void);
246
247 /* utility function to get the tid */
248 pid_t dvmGetSysThreadId(void);
249
250 /*
251  * Get our Thread* from TLS.
252  *
253  * Returns NULL if this isn't a thread that the VM is aware of.
254  */
255 Thread* dvmThreadSelf(void);
256
257 /* grab the thread list global lock */
258 void dvmLockThreadList(Thread* self);
259 /* release the thread list global lock */
260 void dvmUnlockThreadList(void);
261
262 /*
263  * Thread suspend/resume, used by the GC and debugger.
264  */
265 typedef enum SuspendCause {
266     SUSPEND_NOT = 0,
267     SUSPEND_FOR_GC,
268     SUSPEND_FOR_DEBUG,
269     SUSPEND_FOR_DEBUG_EVENT,
270     SUSPEND_FOR_STACK_DUMP,
271     SUSPEND_FOR_DEX_OPT,
272 #if defined(WITH_JIT)
273     SUSPEND_FOR_JIT,
274 #endif
275 } SuspendCause;
276 void dvmSuspendThread(Thread* thread);
277 void dvmSuspendSelf(bool jdwpActivity);
278 void dvmResumeThread(Thread* thread);
279 void dvmSuspendAllThreads(SuspendCause why);
280 void dvmResumeAllThreads(SuspendCause why);
281 void dvmUndoDebuggerSuspensions(void);
282
283 /*
284  * Check suspend state.  Grab threadListLock before calling.
285  */
286 bool dvmIsSuspended(Thread* thread);
287
288 /*
289  * Wait until a thread has suspended.  (Used by debugger support.)
290  */
291 void dvmWaitForSuspend(Thread* thread);
292
293 /*
294  * Check to see if we should be suspended now.  If so, suspend ourselves
295  * by sleeping on a condition variable.
296  *
297  * If "self" is NULL, this will use dvmThreadSelf().
298  */
299 bool dvmCheckSuspendPending(Thread* self);
300
301 /*
302  * Fast test for use in the interpreter.  Returns "true" if our suspend
303  * count is nonzero.
304  */
305 INLINE bool dvmCheckSuspendQuick(Thread* self) {
306     return (self->suspendCount != 0);
307 }
308
309 /*
310  * Used when changing thread state.  Threads may only change their own.
311  * The "self" argument, which may be NULL, is accepted as an optimization.
312  *
313  * If you're calling this before waiting on a resource (e.g. THREAD_WAIT
314  * or THREAD_MONITOR), do so in the same function as the wait -- this records
315  * the current stack depth for the GC.
316  *
317  * If you're changing to THREAD_RUNNING, this will check for suspension.
318  *
319  * Returns the old status.
320  */
321 ThreadStatus dvmChangeStatus(Thread* self, ThreadStatus newStatus);
322
323 /*
324  * Initialize a mutex.
325  */
326 INLINE void dvmInitMutex(pthread_mutex_t* pMutex)
327 {
328 #ifdef CHECK_MUTEX
329     pthread_mutexattr_t attr;
330     int cc;
331
332     pthread_mutexattr_init(&attr);
333     cc = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
334     assert(cc == 0);
335     pthread_mutex_init(pMutex, &attr);
336     pthread_mutexattr_destroy(&attr);
337 #else
338     pthread_mutex_init(pMutex, NULL);       // default=PTHREAD_MUTEX_FAST_NP
339 #endif
340 }
341
342 /*
343  * Grab a plain mutex.
344  */
345 INLINE void dvmLockMutex(pthread_mutex_t* pMutex)
346 {
347     int cc = pthread_mutex_lock(pMutex);
348     assert(cc == 0);
349 }
350
351 /*
352  * Unlock pthread mutex.
353  */
354 INLINE void dvmUnlockMutex(pthread_mutex_t* pMutex)
355 {
356     int cc = pthread_mutex_unlock(pMutex);
357     assert(cc == 0);
358 }
359
360 /*
361  * Destroy a mutex.
362  */
363 INLINE void dvmDestroyMutex(pthread_mutex_t* pMutex)
364 {
365     int cc = pthread_mutex_destroy(pMutex);
366     assert(cc == 0);
367 }
368
369 /*
370  * Create a thread as a result of java.lang.Thread.start().
371  */
372 bool dvmCreateInterpThread(Object* threadObj, int reqStackSize);
373
374 /*
375  * Create a thread internal to the VM.  It's visible to interpreted code,
376  * but found in the "system" thread group rather than "main".
377  */
378 bool dvmCreateInternalThread(pthread_t* pHandle, const char* name,
379     InternalThreadStart func, void* funcArg);
380
381 /*
382  * Attach or detach the current thread from the VM.
383  */
384 bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon);
385 void dvmDetachCurrentThread(void);
386
387 /*
388  * Get the "main" or "system" thread group.
389  */
390 Object* dvmGetMainThreadGroup(void);
391 Object* dvmGetSystemThreadGroup(void);
392
393 /*
394  * Given a java/lang/VMThread object, return our Thread.
395  */
396 Thread* dvmGetThreadFromThreadObject(Object* vmThreadObj);
397
398 /*
399  * Sleep in a thread.  Returns when the sleep timer returns or the thread
400  * is interrupted.
401  */
402 void dvmThreadSleep(u8 msec, u4 nsec);
403
404 /*
405  * Get the name of a thread.  (For safety, hold the thread list lock.)
406  */
407 char* dvmGetThreadName(Thread* thread);
408
409 /*
410  * Return true if a thread is on the internal list.  If it is, the
411  * thread is part of the GC's root set.
412  */
413 bool dvmIsOnThreadList(const Thread* thread);
414
415 /*
416  * Get/set the JNIEnv field.
417  */
418 INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self->jniEnv; }
419 INLINE void dvmSetThreadJNIEnv(Thread* self, JNIEnv* env) { self->jniEnv = env;}
420
421 /*
422  * Update the priority value of the underlying pthread.
423  */
424 void dvmChangeThreadPriority(Thread* thread, int newPriority);
425
426 /*
427  * Debug: dump information about a single thread.
428  */
429 void dvmDumpThread(Thread* thread, bool isRunning);
430 void dvmDumpThreadEx(const DebugOutputTarget* target, Thread* thread,
431     bool isRunning);
432
433 /*
434  * Debug: dump information about all threads.
435  */
436 void dvmDumpAllThreads(bool grabLock);
437 void dvmDumpAllThreadsEx(const DebugOutputTarget* target, bool grabLock);
438
439 #ifdef WITH_MONITOR_TRACKING
440 /*
441  * Track locks held by the current thread, along with the stack trace at
442  * the point the lock was acquired.
443  *
444  * At any given time the number of locks held across the VM should be
445  * fairly small, so there's no reason not to generate and store the entire
446  * stack trace.
447  */
448 typedef struct LockedObjectData {
449     /* the locked object */
450     struct Object*  obj;
451
452     /* number of times it has been locked recursively (zero-based ref count) */
453     int             recursionCount;
454
455     /* stack trace at point of initial acquire */
456     u4              stackDepth;
457     int*            rawStackTrace;
458
459     struct LockedObjectData* next;
460 } LockedObjectData;
461
462 /*
463  * Add/remove/find objects from the thread's monitor list.
464  */
465 void dvmAddToMonitorList(Thread* self, Object* obj, bool withTrace);
466 void dvmRemoveFromMonitorList(Thread* self, Object* obj);
467 LockedObjectData* dvmFindInMonitorList(const Thread* self, const Object* obj);
468 #endif
469
470 #endif /*_DALVIK_THREAD*/