blob: 9b327030a111792fb2f19a8b351d88d88b73543c [file] [log] [blame]
Ben Chengba4fc8b2009-06-01 13:00:29 -07001/*
2 * Copyright (C) 2009 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#include <sys/mman.h>
18#include <errno.h>
Ben Cheng7c4afdb2010-02-11 15:03:00 -080019#include <cutils/ashmem.h>
Ben Chengba4fc8b2009-06-01 13:00:29 -070020
21#include "Dalvik.h"
22#include "interp/Jit.h"
23#include "CompilerInternals.h"
24
Ben Chengba4fc8b2009-06-01 13:00:29 -070025static inline bool workQueueLength(void)
26{
27 return gDvmJit.compilerQueueLength;
28}
29
30static CompilerWorkOrder workDequeue(void)
31{
32 assert(gDvmJit.compilerWorkQueue[gDvmJit.compilerWorkDequeueIndex].kind
33 != kWorkOrderInvalid);
34 CompilerWorkOrder work =
35 gDvmJit.compilerWorkQueue[gDvmJit.compilerWorkDequeueIndex];
36 gDvmJit.compilerWorkQueue[gDvmJit.compilerWorkDequeueIndex++].kind =
37 kWorkOrderInvalid;
38 if (gDvmJit.compilerWorkDequeueIndex == COMPILER_WORK_QUEUE_SIZE) {
39 gDvmJit.compilerWorkDequeueIndex = 0;
40 }
41 gDvmJit.compilerQueueLength--;
Bill Buzbeef9f33282009-11-22 12:45:30 -080042 if (gDvmJit.compilerQueueLength == 0) {
Carl Shapirob31b3012010-05-25 18:35:37 -070043 dvmSignalCond(&gDvmJit.compilerQueueEmpty);
Bill Buzbeef9f33282009-11-22 12:45:30 -080044 }
Ben Chengba4fc8b2009-06-01 13:00:29 -070045
46 /* Remember the high water mark of the queue length */
47 if (gDvmJit.compilerQueueLength > gDvmJit.compilerMaxQueued)
48 gDvmJit.compilerMaxQueued = gDvmJit.compilerQueueLength;
49
50 return work;
51}
52
Bill Buzbee964a7b02010-01-28 12:54:19 -080053/*
54 * Attempt to enqueue a work order, returning true if successful.
55 * This routine will not block, but simply return if it couldn't
56 * aquire the lock or if the queue is full.
Ben Cheng1357e942010-02-10 17:21:39 -080057 *
58 * NOTE: Make sure that the caller frees the info pointer if the return value
59 * is false.
Bill Buzbee964a7b02010-01-28 12:54:19 -080060 */
Ben Chengba4fc8b2009-06-01 13:00:29 -070061bool dvmCompilerWorkEnqueue(const u2 *pc, WorkOrderKind kind, void* info)
62{
63 int cc;
64 int i;
65 int numWork;
Ben Cheng60c24f42010-01-04 12:29:56 -080066 bool result = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -070067
Bill Buzbee964a7b02010-01-28 12:54:19 -080068 if (dvmTryLockMutex(&gDvmJit.compilerLock)) {
Ben Cheng3e5cd172010-02-08 20:57:59 -080069 return false; // Couldn't acquire the lock
Bill Buzbee964a7b02010-01-28 12:54:19 -080070 }
Ben Chengba4fc8b2009-06-01 13:00:29 -070071
Ben Cheng7a0bcd02010-01-22 16:45:45 -080072 /*
Ben Cheng6999d842010-01-26 16:46:15 -080073 * Return if queue or code cache is full.
Ben Cheng7a0bcd02010-01-22 16:45:45 -080074 */
Ben Cheng6999d842010-01-26 16:46:15 -080075 if (gDvmJit.compilerQueueLength == COMPILER_WORK_QUEUE_SIZE ||
76 gDvmJit.codeCacheFull == true) {
Ben Cheng60c24f42010-01-04 12:29:56 -080077 result = false;
Bill Buzbee964a7b02010-01-28 12:54:19 -080078 goto unlockAndExit;
Ben Chengba4fc8b2009-06-01 13:00:29 -070079 }
80
81 for (numWork = gDvmJit.compilerQueueLength,
82 i = gDvmJit.compilerWorkDequeueIndex;
83 numWork > 0;
84 numWork--) {
85 /* Already enqueued */
86 if (gDvmJit.compilerWorkQueue[i++].pc == pc)
Bill Buzbee964a7b02010-01-28 12:54:19 -080087 goto unlockAndExit;
Ben Chengba4fc8b2009-06-01 13:00:29 -070088 /* Wrap around */
89 if (i == COMPILER_WORK_QUEUE_SIZE)
90 i = 0;
91 }
92
Ben Chengccd6c012009-10-15 14:52:45 -070093 CompilerWorkOrder *newOrder =
94 &gDvmJit.compilerWorkQueue[gDvmJit.compilerWorkEnqueueIndex];
95 newOrder->pc = pc;
96 newOrder->kind = kind;
97 newOrder->info = info;
98 newOrder->result.codeAddress = NULL;
99 newOrder->result.discardResult =
Bill Buzbee1f748632010-03-02 16:14:41 -0800100 (kind == kWorkOrderTraceDebug) ? true : false;
Ben Cheng33672452010-01-12 14:59:30 -0800101 newOrder->result.requestingThread = dvmThreadSelf();
102
Ben Chengba4fc8b2009-06-01 13:00:29 -0700103 gDvmJit.compilerWorkEnqueueIndex++;
104 if (gDvmJit.compilerWorkEnqueueIndex == COMPILER_WORK_QUEUE_SIZE)
105 gDvmJit.compilerWorkEnqueueIndex = 0;
106 gDvmJit.compilerQueueLength++;
107 cc = pthread_cond_signal(&gDvmJit.compilerQueueActivity);
108 assert(cc == 0);
109
Bill Buzbee964a7b02010-01-28 12:54:19 -0800110unlockAndExit:
Ben Chengba4fc8b2009-06-01 13:00:29 -0700111 dvmUnlockMutex(&gDvmJit.compilerLock);
Ben Cheng60c24f42010-01-04 12:29:56 -0800112 return result;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700113}
114
Ben Cheng11d8f142010-03-24 15:24:19 -0700115/* Block until the queue length is 0, or there is a pending suspend request */
Ben Chengba4fc8b2009-06-01 13:00:29 -0700116void dvmCompilerDrainQueue(void)
117{
Ben Cheng11d8f142010-03-24 15:24:19 -0700118 Thread *self = dvmThreadSelf();
119
Ben Chengba4fc8b2009-06-01 13:00:29 -0700120 dvmLockMutex(&gDvmJit.compilerLock);
Ben Cheng11d8f142010-03-24 15:24:19 -0700121 while (workQueueLength() != 0 && !gDvmJit.haltCompilerThread &&
122 self->suspendCount == 0) {
Ben Cheng812e6b12010-03-15 15:19:06 -0700123 /*
124 * Use timed wait here - more than one mutator threads may be blocked
125 * but the compiler thread will only signal once when the queue is
126 * emptied. Furthermore, the compiler thread may have been shutdown
127 * so the blocked thread may never get the wakeup signal.
128 */
129 dvmRelativeCondWait(&gDvmJit.compilerQueueEmpty, &gDvmJit.compilerLock, 1000, 0);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700130 }
131 dvmUnlockMutex(&gDvmJit.compilerLock);
132}
133
Ben Cheng60c24f42010-01-04 12:29:56 -0800134bool dvmCompilerSetupCodeCache(void)
135{
136 extern void dvmCompilerTemplateStart(void);
137 extern void dmvCompilerTemplateEnd(void);
Ben Cheng7c4afdb2010-02-11 15:03:00 -0800138 int fd;
Ben Cheng60c24f42010-01-04 12:29:56 -0800139
140 /* Allocate the code cache */
Ben Cheng7c4afdb2010-02-11 15:03:00 -0800141 fd = ashmem_create_region("dalvik-jit-code-cache", gDvmJit.codeCacheSize);
142 if (fd < 0) {
143 LOGE("Could not create %u-byte ashmem region for the JIT code cache",
144 gDvmJit.codeCacheSize);
145 return false;
146 }
147 gDvmJit.codeCache = mmap(NULL, gDvmJit.codeCacheSize,
148 PROT_READ | PROT_WRITE | PROT_EXEC,
149 MAP_PRIVATE , fd, 0);
150 close(fd);
Ben Cheng60c24f42010-01-04 12:29:56 -0800151 if (gDvmJit.codeCache == MAP_FAILED) {
Ben Cheng7c4afdb2010-02-11 15:03:00 -0800152 LOGE("Failed to mmap the JIT code cache: %s\n", strerror(errno));
Ben Cheng60c24f42010-01-04 12:29:56 -0800153 return false;
154 }
155
Ben Chengb88ec3c2010-05-17 12:50:33 -0700156 gDvmJit.pageSizeMask = getpagesize() - 1;
157
Ben Cheng7c4afdb2010-02-11 15:03:00 -0800158 /* This can be found through "dalvik-jit-code-cache" in /proc/<pid>/maps */
159 // LOGD("Code cache starts at %p", gDvmJit.codeCache);
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800160
Ben Cheng60c24f42010-01-04 12:29:56 -0800161 /* Copy the template code into the beginning of the code cache */
162 int templateSize = (intptr_t) dmvCompilerTemplateEnd -
163 (intptr_t) dvmCompilerTemplateStart;
164 memcpy((void *) gDvmJit.codeCache,
165 (void *) dvmCompilerTemplateStart,
166 templateSize);
167
Ben Cheng72621c92010-03-10 13:12:55 -0800168 /*
169 * Work around a CPU bug by keeping the 32-bit ARM handler code in its own
170 * page.
171 */
172 if (dvmCompilerInstructionSet() == DALVIK_JIT_THUMB2) {
173 templateSize = (templateSize + 4095) & ~4095;
174 }
175
Ben Cheng60c24f42010-01-04 12:29:56 -0800176 gDvmJit.templateSize = templateSize;
177 gDvmJit.codeCacheByteUsed = templateSize;
178
179 /* Only flush the part in the code cache that is being used now */
180 cacheflush((intptr_t) gDvmJit.codeCache,
181 (intptr_t) gDvmJit.codeCache + templateSize, 0);
Ben Chengb88ec3c2010-05-17 12:50:33 -0700182
183 mprotect(gDvmJit.codeCache, gDvmJit.codeCacheSize,
184 PROTECT_CODE_CACHE_ATTRS);
185
Ben Cheng60c24f42010-01-04 12:29:56 -0800186 return true;
187}
188
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800189static void crawlDalvikStack(Thread *thread, bool print)
190{
191 void *fp = thread->curFrame;
192 StackSaveArea* saveArea = NULL;
193 int stackLevel = 0;
194
195 if (print) {
196 LOGD("Crawling tid %d (%s / %p %s)", thread->systemTid,
197 dvmGetThreadStatusStr(thread->status),
198 thread->inJitCodeCache,
199 thread->inJitCodeCache ? "jit" : "interp");
200 }
201 /* Crawl the Dalvik stack frames to clear the returnAddr field */
202 while (fp != NULL) {
203 saveArea = SAVEAREA_FROM_FP(fp);
204
205 if (print) {
206 if (dvmIsBreakFrame(fp)) {
207 LOGD(" #%d: break frame (%p)",
208 stackLevel, saveArea->returnAddr);
209 }
210 else {
211 LOGD(" #%d: %s.%s%s (%p)",
212 stackLevel,
213 saveArea->method->clazz->descriptor,
214 saveArea->method->name,
215 dvmIsNativeMethod(saveArea->method) ?
216 " (native)" : "",
217 saveArea->returnAddr);
218 }
219 }
220 stackLevel++;
221 saveArea->returnAddr = NULL;
222 assert(fp != saveArea->prevFrame);
223 fp = saveArea->prevFrame;
224 }
225 /* Make sure the stack is fully unwound to the bottom */
226 assert(saveArea == NULL ||
227 (u1 *) (saveArea+1) == thread->interpStackStart);
228}
229
Ben Cheng60c24f42010-01-04 12:29:56 -0800230static void resetCodeCache(void)
231{
Ben Cheng60c24f42010-01-04 12:29:56 -0800232 Thread* thread;
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800233 u8 startTime = dvmGetRelativeTimeUsec();
234 int inJit = 0;
Ben Cheng6999d842010-01-26 16:46:15 -0800235 int byteUsed = gDvmJit.codeCacheByteUsed;
Ben Cheng60c24f42010-01-04 12:29:56 -0800236
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800237 /* If any thread is found stuck in the JIT state, don't reset the cache */
238 for (thread = gDvm.threadList; thread != NULL; thread = thread->next) {
Ben Cheng6999d842010-01-26 16:46:15 -0800239 /*
240 * Crawl the stack to wipe out the returnAddr field so that
241 * 1) the soon-to-be-deleted code in the JIT cache won't be used
242 * 2) or the thread stuck in the JIT land will soon return
243 * to the interpreter land
244 */
245 crawlDalvikStack(thread, false);
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800246 if (thread->inJitCodeCache) {
247 inJit++;
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800248 }
249 }
250
251 if (inJit) {
Ben Cheng6999d842010-01-26 16:46:15 -0800252 LOGD("JIT code cache reset delayed (%d bytes %d/%d)",
253 gDvmJit.codeCacheByteUsed, gDvmJit.numCodeCacheReset,
254 ++gDvmJit.numCodeCacheResetDelayed);
255 return;
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800256 }
257
Ben Cheng6999d842010-01-26 16:46:15 -0800258 /* Lock the mutex to clean up the work queue */
259 dvmLockMutex(&gDvmJit.compilerLock);
260
261 /* Drain the work queue to free the work orders */
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800262 while (workQueueLength()) {
263 CompilerWorkOrder work = workDequeue();
264 free(work.info);
265 }
266
Ben Cheng60c24f42010-01-04 12:29:56 -0800267 /* Reset the JitEntry table contents to the initial unpopulated state */
268 dvmJitResetTable();
269
Ben Chengb88ec3c2010-05-17 12:50:33 -0700270 UNPROTECT_CODE_CACHE(gDvmJit.codeCache, gDvmJit.codeCacheByteUsed);
Ben Cheng60c24f42010-01-04 12:29:56 -0800271 /*
Ben Cheng60c24f42010-01-04 12:29:56 -0800272 * Wipe out the code cache content to force immediate crashes if
273 * stale JIT'ed code is invoked.
274 */
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800275 memset((char *) gDvmJit.codeCache + gDvmJit.templateSize,
276 0,
277 gDvmJit.codeCacheByteUsed - gDvmJit.templateSize);
Ben Cheng60c24f42010-01-04 12:29:56 -0800278 cacheflush((intptr_t) gDvmJit.codeCache,
279 (intptr_t) gDvmJit.codeCache + gDvmJit.codeCacheByteUsed, 0);
Ben Cheng60c24f42010-01-04 12:29:56 -0800280
Ben Chengb88ec3c2010-05-17 12:50:33 -0700281 PROTECT_CODE_CACHE(gDvmJit.codeCache, gDvmJit.codeCacheByteUsed);
282
Ben Cheng60c24f42010-01-04 12:29:56 -0800283 /* Reset the current mark of used bytes to the end of template code */
284 gDvmJit.codeCacheByteUsed = gDvmJit.templateSize;
285 gDvmJit.numCompilations = 0;
286
287 /* Reset the work queue */
288 memset(gDvmJit.compilerWorkQueue, 0,
289 sizeof(CompilerWorkOrder) * COMPILER_WORK_QUEUE_SIZE);
290 gDvmJit.compilerWorkEnqueueIndex = gDvmJit.compilerWorkDequeueIndex = 0;
291 gDvmJit.compilerQueueLength = 0;
292
Ben Cheng6999d842010-01-26 16:46:15 -0800293 /* Reset the IC patch work queue */
294 dvmLockMutex(&gDvmJit.compilerICPatchLock);
295 gDvmJit.compilerICPatchIndex = 0;
296 dvmUnlockMutex(&gDvmJit.compilerICPatchLock);
297
Ben Cheng60c24f42010-01-04 12:29:56 -0800298 /* All clear now */
299 gDvmJit.codeCacheFull = false;
300
Ben Cheng6999d842010-01-26 16:46:15 -0800301 dvmUnlockMutex(&gDvmJit.compilerLock);
Ben Cheng7a0bcd02010-01-22 16:45:45 -0800302
Ben Cheng6999d842010-01-26 16:46:15 -0800303 LOGD("JIT code cache reset in %lld ms (%d bytes %d/%d)",
304 (dvmGetRelativeTimeUsec() - startTime) / 1000,
305 byteUsed, ++gDvmJit.numCodeCacheReset,
306 gDvmJit.numCodeCacheResetDelayed);
307}
308
309/*
310 * Perform actions that are only safe when all threads are suspended. Currently
311 * we do:
312 * 1) Check if the code cache is full. If so reset it and restart populating it
313 * from scratch.
314 * 2) Patch predicted chaining cells by consuming recorded work orders.
315 */
316void dvmCompilerPerformSafePointChecks(void)
317{
318 if (gDvmJit.codeCacheFull) {
319 resetCodeCache();
320 }
321 dvmCompilerPatchInlineCache();
Ben Cheng60c24f42010-01-04 12:29:56 -0800322}
323
Bill Buzbee964a7b02010-01-28 12:54:19 -0800324bool compilerThreadStartup(void)
325{
326 JitEntry *pJitTable = NULL;
327 unsigned char *pJitProfTable = NULL;
328 unsigned int i;
329
330 if (!dvmCompilerArchInit())
331 goto fail;
332
333 /*
334 * Setup the code cache if we have not inherited a valid code cache
335 * from the zygote.
336 */
337 if (gDvmJit.codeCache == NULL) {
338 if (!dvmCompilerSetupCodeCache())
339 goto fail;
340 }
341
342 /* Allocate the initial arena block */
343 if (dvmCompilerHeapInit() == false) {
344 goto fail;
345 }
346
Bill Buzbee964a7b02010-01-28 12:54:19 -0800347 dvmLockMutex(&gDvmJit.compilerLock);
348
Ben Cheng1357e942010-02-10 17:21:39 -0800349#if defined(WITH_JIT_TUNING)
Bill Buzbee964a7b02010-01-28 12:54:19 -0800350 /* Track method-level compilation statistics */
351 gDvmJit.methodStatsTable = dvmHashTableCreate(32, NULL);
Ben Cheng452efba2010-04-30 15:14:00 -0700352 gDvm.verboseShutdown = true;
Ben Cheng1357e942010-02-10 17:21:39 -0800353#endif
Bill Buzbee964a7b02010-01-28 12:54:19 -0800354
355 dvmUnlockMutex(&gDvmJit.compilerLock);
356
357 /* Set up the JitTable */
358
359 /* Power of 2? */
360 assert(gDvmJit.jitTableSize &&
361 !(gDvmJit.jitTableSize & (gDvmJit.jitTableSize - 1)));
362
363 dvmInitMutex(&gDvmJit.tableLock);
364 dvmLockMutex(&gDvmJit.tableLock);
365 pJitTable = (JitEntry*)
366 calloc(gDvmJit.jitTableSize, sizeof(*pJitTable));
367 if (!pJitTable) {
368 LOGE("jit table allocation failed\n");
369 dvmUnlockMutex(&gDvmJit.tableLock);
370 goto fail;
371 }
372 /*
373 * NOTE: the profile table must only be allocated once, globally.
374 * Profiling is turned on and off by nulling out gDvm.pJitProfTable
375 * and then restoring its original value. However, this action
376 * is not syncronized for speed so threads may continue to hold
377 * and update the profile table after profiling has been turned
378 * off by null'ng the global pointer. Be aware.
379 */
380 pJitProfTable = (unsigned char *)malloc(JIT_PROF_SIZE);
381 if (!pJitProfTable) {
382 LOGE("jit prof table allocation failed\n");
383 dvmUnlockMutex(&gDvmJit.tableLock);
384 goto fail;
385 }
386 memset(pJitProfTable, gDvmJit.threshold, JIT_PROF_SIZE);
387 for (i=0; i < gDvmJit.jitTableSize; i++) {
388 pJitTable[i].u.info.chain = gDvmJit.jitTableSize;
389 }
390 /* Is chain field wide enough for termination pattern? */
391 assert(pJitTable[0].u.info.chain == gDvmJit.jitTableSize);
392
393 gDvmJit.pJitEntryTable = pJitTable;
394 gDvmJit.jitTableMask = gDvmJit.jitTableSize - 1;
395 gDvmJit.jitTableEntriesUsed = 0;
396 gDvmJit.compilerHighWater =
397 COMPILER_WORK_QUEUE_SIZE - (COMPILER_WORK_QUEUE_SIZE/4);
Ben Chenga4973592010-03-31 11:59:18 -0700398 /*
399 * If the VM is launched with wait-on-the-debugger, we will need to hide
400 * the profile table here
401 */
402 gDvmJit.pProfTable = dvmDebuggerOrProfilerActive() ? NULL : pJitProfTable;
Bill Buzbee06bb8392010-01-31 18:53:15 -0800403 gDvmJit.pProfTableCopy = pJitProfTable;
Bill Buzbee964a7b02010-01-28 12:54:19 -0800404 dvmUnlockMutex(&gDvmJit.tableLock);
405
406 /* Signal running threads to refresh their cached pJitTable pointers */
407 dvmSuspendAllThreads(SUSPEND_FOR_REFRESH);
408 dvmResumeAllThreads(SUSPEND_FOR_REFRESH);
Ben Chengdca71432010-03-16 16:04:11 -0700409
410 /* Enable signature breakpoints by customizing the following code */
411#if defined(SIGNATURE_BREAKPOINT)
412 /*
413 * Suppose one sees the following native crash in the bugreport:
414 * I/DEBUG ( 1638): Build fingerprint: 'unknown'
415 * I/DEBUG ( 1638): pid: 2468, tid: 2507 >>> com.google.android.gallery3d
416 * I/DEBUG ( 1638): signal 11 (SIGSEGV), fault addr 00001400
417 * I/DEBUG ( 1638): r0 44ea7190 r1 44e4f7b8 r2 44ebc710 r3 00000000
418 * I/DEBUG ( 1638): r4 00000a00 r5 41862dec r6 4710dc10 r7 00000280
419 * I/DEBUG ( 1638): r8 ad010f40 r9 46a37a12 10 001116b0 fp 42a78208
420 * I/DEBUG ( 1638): ip 00000090 sp 4710dbc8 lr ad060e67 pc 46b90682
421 * cpsr 00000030
422 * I/DEBUG ( 1638): #00 pc 46b90682 /dev/ashmem/dalvik-jit-code-cache
423 * I/DEBUG ( 1638): #01 pc 00060e62 /system/lib/libdvm.so
424 *
425 * I/DEBUG ( 1638): code around pc:
426 * I/DEBUG ( 1638): 46b90660 6888d01c 34091dcc d2174287 4a186b68
427 * I/DEBUG ( 1638): 46b90670 d0052800 68006809 28004790 6b68d00e
428 * I/DEBUG ( 1638): 46b90680 512000bc 37016eaf 6ea866af 6f696028
429 * I/DEBUG ( 1638): 46b90690 682a6069 429a686b e003da08 6df1480b
430 * I/DEBUG ( 1638): 46b906a0 1c2d4788 47806d70 46a378fa 47806d70
431 *
432 * Clearly it is a JIT bug. To find out which translation contains the
433 * offending code, the content of the memory dump around the faulting PC
434 * can be pasted into the gDvmJit.signatureBreakpoint[] array and next time
435 * when a similar compilation is being created, the JIT compiler replay the
436 * trace in the verbose mode and one can investigate the instruction
437 * sequence in details.
438 *
439 * The length of the signature may need additional experiments to determine.
440 * The rule of thumb is don't include PC-relative instructions in the
441 * signature since it may be affected by the alignment of the compiled code.
442 * However, a signature that's too short might increase the chance of false
443 * positive matches. Using gdbjithelper to disassembly the memory content
444 * first might be a good companion approach.
445 *
446 * For example, if the next 4 words starting from 46b90680 is pasted into
447 * the data structure:
448 */
449
450 gDvmJit.signatureBreakpointSize = 4;
451 gDvmJit.signatureBreakpoint =
452 malloc(sizeof(u4) * gDvmJit.signatureBreakpointSize);
453 gDvmJit.signatureBreakpoint[0] = 0x512000bc;
454 gDvmJit.signatureBreakpoint[1] = 0x37016eaf;
455 gDvmJit.signatureBreakpoint[2] = 0x6ea866af;
456 gDvmJit.signatureBreakpoint[3] = 0x6f696028;
457
458 /*
459 * The following log will be printed when a match is found in subsequent
460 * testings:
461 *
462 * D/dalvikvm( 2468): Signature match starting from offset 0x34 (4 words)
463 * D/dalvikvm( 2468): --------
464 * D/dalvikvm( 2468): Compiler: Building trace for computeVisibleItems,
465 * offset 0x1f7
466 * D/dalvikvm( 2468): 0x46a37a12: 0x0090 add-int v42, v5, v26
467 * D/dalvikvm( 2468): 0x46a37a16: 0x004d aput-object v13, v14, v42
468 * D/dalvikvm( 2468): 0x46a37a1a: 0x0028 goto, (#0), (#0)
469 * D/dalvikvm( 2468): 0x46a3794e: 0x00d8 add-int/lit8 v26, v26, (#1)
470 * D/dalvikvm( 2468): 0x46a37952: 0x0028 goto, (#0), (#0)
471 * D/dalvikvm( 2468): 0x46a378ee: 0x0002 move/from16 v0, v26, (#0)
472 * D/dalvikvm( 2468): 0x46a378f2: 0x0002 move/from16 v1, v29, (#0)
473 * D/dalvikvm( 2468): 0x46a378f6: 0x0035 if-ge v0, v1, (#10)
474 * D/dalvikvm( 2468): TRACEINFO (554): 0x46a37624
475 * Lcom/cooliris/media/GridLayer;computeVisibleItems 0x1f7 14 of 934, 8
476 * blocks
477 * :
478 * :
479 * D/dalvikvm( 2468): 0x20 (0020): ldr r0, [r5, #52]
480 * D/dalvikvm( 2468): 0x22 (0022): ldr r2, [pc, #96]
481 * D/dalvikvm( 2468): 0x24 (0024): cmp r0, #0
482 * D/dalvikvm( 2468): 0x26 (0026): beq 0x00000034
483 * D/dalvikvm( 2468): 0x28 (0028): ldr r1, [r1, #0]
484 * D/dalvikvm( 2468): 0x2a (002a): ldr r0, [r0, #0]
485 * D/dalvikvm( 2468): 0x2c (002c): blx r2
486 * D/dalvikvm( 2468): 0x2e (002e): cmp r0, #0
487 * D/dalvikvm( 2468): 0x30 (0030): beq 0x00000050
488 * D/dalvikvm( 2468): 0x32 (0032): ldr r0, [r5, #52]
489 * D/dalvikvm( 2468): 0x34 (0034): lsls r4, r7, #2
490 * D/dalvikvm( 2468): 0x36 (0036): str r0, [r4, r4]
491 * D/dalvikvm( 2468): -------- dalvik offset: 0x01fb @ goto, (#0), (#0)
492 * D/dalvikvm( 2468): L0x0195:
493 * D/dalvikvm( 2468): -------- dalvik offset: 0x0195 @ add-int/lit8 v26,
494 * v26, (#1)
495 * D/dalvikvm( 2468): 0x38 (0038): ldr r7, [r5, #104]
496 * D/dalvikvm( 2468): 0x3a (003a): adds r7, r7, #1
497 * D/dalvikvm( 2468): 0x3c (003c): str r7, [r5, #104]
498 * D/dalvikvm( 2468): -------- dalvik offset: 0x0197 @ goto, (#0), (#0)
499 * D/dalvikvm( 2468): L0x0165:
500 * D/dalvikvm( 2468): -------- dalvik offset: 0x0165 @ move/from16 v0, v26,
501 * (#0)
502 * D/dalvikvm( 2468): 0x3e (003e): ldr r0, [r5, #104]
503 * D/dalvikvm( 2468): 0x40 (0040): str r0, [r5, #0]
504 *
505 * The "str r0, [r4, r4]" is indeed the culprit of the native crash.
506 */
507#endif
508
Bill Buzbee964a7b02010-01-28 12:54:19 -0800509 return true;
510
511fail:
512 return false;
513
514}
515
Ben Chengba4fc8b2009-06-01 13:00:29 -0700516static void *compilerThreadStart(void *arg)
517{
Ben Cheng5ccdf0b2009-10-08 16:09:49 -0700518 dvmChangeStatus(NULL, THREAD_VMWAIT);
519
Bill Buzbeeb1d80442009-12-17 14:55:21 -0800520 /*
Bill Buzbeeeb695c62010-02-04 16:09:55 -0800521 * If we're not running stand-alone, wait a little before
522 * recieving translation requests on the assumption that process start
523 * up code isn't worth compiling. We'll resume when the framework
524 * signals us that the first screen draw has happened, or the timer
525 * below expires (to catch daemons).
Ben Chengf30acbb2010-02-14 16:17:36 -0800526 *
527 * There is a theoretical race between the callback to
528 * VMRuntime.startJitCompiation and when the compiler thread reaches this
529 * point. In case the callback happens earlier, in order not to permanently
530 * hold the system_server (which is not using the timed wait) in
531 * interpreter-only mode we bypass the delay here.
Bill Buzbeeb1d80442009-12-17 14:55:21 -0800532 */
Ben Chengf30acbb2010-02-14 16:17:36 -0800533 if (gDvmJit.runningInAndroidFramework &&
534 !gDvmJit.alreadyEnabledViaFramework) {
535 /*
536 * If the current VM instance is the system server (detected by having
537 * 0 in gDvm.systemServerPid), we will use the indefinite wait on the
538 * conditional variable to determine whether to start the JIT or not.
539 * If the system server detects that the whole system is booted in
540 * safe mode, the conditional variable will never be signaled and the
541 * system server will remain in the interpreter-only mode. All
542 * subsequent apps will be started with the --enable-safemode flag
543 * explicitly appended.
544 */
545 if (gDvm.systemServerPid == 0) {
546 dvmLockMutex(&gDvmJit.compilerLock);
547 pthread_cond_wait(&gDvmJit.compilerQueueActivity,
548 &gDvmJit.compilerLock);
549 dvmUnlockMutex(&gDvmJit.compilerLock);
550 LOGD("JIT started for system_server");
551 } else {
552 dvmLockMutex(&gDvmJit.compilerLock);
553 /*
554 * TUNING: experiment with the delay & perhaps make it
555 * target-specific
556 */
557 dvmRelativeCondWait(&gDvmJit.compilerQueueActivity,
558 &gDvmJit.compilerLock, 3000, 0);
559 dvmUnlockMutex(&gDvmJit.compilerLock);
560 }
Bill Buzbeeeb695c62010-02-04 16:09:55 -0800561 if (gDvmJit.haltCompilerThread) {
562 return NULL;
563 }
Bill Buzbee94d89f82010-01-29 13:44:19 -0800564 }
565
Bill Buzbee964a7b02010-01-28 12:54:19 -0800566 compilerThreadStartup();
Bill Buzbeeb1d80442009-12-17 14:55:21 -0800567
Ben Chengba4fc8b2009-06-01 13:00:29 -0700568 dvmLockMutex(&gDvmJit.compilerLock);
569 /*
570 * Since the compiler thread will not touch any objects on the heap once
571 * being created, we just fake its state as VMWAIT so that it can be a
572 * bit late when there is suspend request pending.
573 */
Ben Chengba4fc8b2009-06-01 13:00:29 -0700574 while (!gDvmJit.haltCompilerThread) {
575 if (workQueueLength() == 0) {
576 int cc;
577 cc = pthread_cond_signal(&gDvmJit.compilerQueueEmpty);
578 assert(cc == 0);
579 pthread_cond_wait(&gDvmJit.compilerQueueActivity,
580 &gDvmJit.compilerLock);
581 continue;
582 } else {
583 do {
Ben Chengba4fc8b2009-06-01 13:00:29 -0700584 CompilerWorkOrder work = workDequeue();
585 dvmUnlockMutex(&gDvmJit.compilerLock);
Ben Cheng978738d2010-05-13 13:45:57 -0700586#if defined(WITH_JIT_TUNING)
Ben Cheng86717f72010-03-05 15:27:21 -0800587 u8 startTime = dvmGetRelativeTimeUsec();
588#endif
Bill Buzbee964a7b02010-01-28 12:54:19 -0800589 /*
590 * Check whether there is a suspend request on me. This
591 * is necessary to allow a clean shutdown.
Ben Cheng11d8f142010-03-24 15:24:19 -0700592 *
593 * However, in the blocking stress testing mode, let the
594 * compiler thread continue doing compilations to unblock
595 * other requesting threads. This may occasionally cause
596 * shutdown from proceeding cleanly in the standalone invocation
597 * of the vm but this should be acceptable.
Bill Buzbee964a7b02010-01-28 12:54:19 -0800598 */
Ben Cheng11d8f142010-03-24 15:24:19 -0700599 if (!gDvmJit.blockingMode)
Andy McFaddenab227f72010-04-06 12:37:48 -0700600 dvmCheckSuspendPending(dvmThreadSelf());
Bill Buzbee27176222009-06-09 09:20:16 -0700601 /* Is JitTable filling up? */
602 if (gDvmJit.jitTableEntriesUsed >
603 (gDvmJit.jitTableSize - gDvmJit.jitTableSize/4)) {
Ben Cheng6999d842010-01-26 16:46:15 -0800604 bool resizeFail =
605 dvmJitResizeJitTable(gDvmJit.jitTableSize * 2);
606 /*
607 * If the jit table is full, consider it's time to reset
608 * the code cache too.
609 */
610 gDvmJit.codeCacheFull |= resizeFail;
Bill Buzbee27176222009-06-09 09:20:16 -0700611 }
Ben Chengba4fc8b2009-06-01 13:00:29 -0700612 if (gDvmJit.haltCompilerThread) {
613 LOGD("Compiler shutdown in progress - discarding request");
Ben Cheng6999d842010-01-26 16:46:15 -0800614 } else if (!gDvmJit.codeCacheFull) {
Bill Buzbeefc519dc2010-03-06 23:30:57 -0800615 bool compileOK = false;
616 jmp_buf jmpBuf;
617 work.bailPtr = &jmpBuf;
618 bool aborted = setjmp(jmpBuf);
619 if (!aborted) {
620 compileOK = dvmCompilerDoWork(&work);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700621 }
Bill Buzbeefc519dc2010-03-06 23:30:57 -0800622 if (aborted || !compileOK) {
623 dvmCompilerArenaReset();
Bill Buzbeebd047242010-05-13 13:02:53 -0700624 work.result.codeAddress = dvmCompilerGetInterpretTemplate();
Bill Buzbeefc519dc2010-03-06 23:30:57 -0800625 } else if (!work.result.discardResult) {
Ben Cheng60c24f42010-01-04 12:29:56 -0800626 dvmJitSetCodeAddr(work.pc, work.result.codeAddress,
627 work.result.instructionSet);
628 }
Ben Chengba4fc8b2009-06-01 13:00:29 -0700629 }
630 free(work.info);
Ben Cheng978738d2010-05-13 13:45:57 -0700631#if defined(WITH_JIT_TUNING)
Ben Cheng86717f72010-03-05 15:27:21 -0800632 gDvmJit.jitTime += dvmGetRelativeTimeUsec() - startTime;
633#endif
Ben Chengba4fc8b2009-06-01 13:00:29 -0700634 dvmLockMutex(&gDvmJit.compilerLock);
635 } while (workQueueLength() != 0);
636 }
637 }
638 pthread_cond_signal(&gDvmJit.compilerQueueEmpty);
639 dvmUnlockMutex(&gDvmJit.compilerLock);
Ben Chengef00a852009-06-22 22:53:35 -0700640
Ben Cheng5ccdf0b2009-10-08 16:09:49 -0700641 /*
642 * As part of detaching the thread we need to call into Java code to update
643 * the ThreadGroup, and we should not be in VMWAIT state while executing
644 * interpreted code.
645 */
646 dvmChangeStatus(NULL, THREAD_RUNNING);
647
Andy McFadden43eb5012010-02-01 16:56:53 -0800648 if (gDvm.verboseShutdown)
649 LOGD("Compiler thread shutting down\n");
Ben Chengba4fc8b2009-06-01 13:00:29 -0700650 return NULL;
651}
652
Ben Chengba4fc8b2009-06-01 13:00:29 -0700653bool dvmCompilerStartup(void)
654{
Bill Buzbee94d89f82010-01-29 13:44:19 -0800655
656 dvmInitMutex(&gDvmJit.compilerLock);
Ben Cheng6999d842010-01-26 16:46:15 -0800657 dvmInitMutex(&gDvmJit.compilerICPatchLock);
Ben Chengb88ec3c2010-05-17 12:50:33 -0700658 dvmInitMutex(&gDvmJit.codeCacheProtectionLock);
Bill Buzbee94d89f82010-01-29 13:44:19 -0800659 dvmLockMutex(&gDvmJit.compilerLock);
660 pthread_cond_init(&gDvmJit.compilerQueueActivity, NULL);
661 pthread_cond_init(&gDvmJit.compilerQueueEmpty, NULL);
662
663 /* Reset the work queue */
664 gDvmJit.compilerWorkEnqueueIndex = gDvmJit.compilerWorkDequeueIndex = 0;
665 gDvmJit.compilerQueueLength = 0;
666 dvmUnlockMutex(&gDvmJit.compilerLock);
667
Ben Chengba4fc8b2009-06-01 13:00:29 -0700668 /*
Bill Buzbee94d89f82010-01-29 13:44:19 -0800669 * Defer rest of initialization until we're sure JIT'ng makes sense. Launch
Bill Buzbee964a7b02010-01-28 12:54:19 -0800670 * the compiler thread, which will do the real initialization if and
671 * when it is signalled to do so.
Ben Chengba4fc8b2009-06-01 13:00:29 -0700672 */
Bill Buzbee964a7b02010-01-28 12:54:19 -0800673 return dvmCreateInternalThread(&gDvmJit.compilerHandle, "Compiler",
674 compilerThreadStart, NULL);
Ben Chengba4fc8b2009-06-01 13:00:29 -0700675}
676
677void dvmCompilerShutdown(void)
678{
679 void *threadReturn;
680
Bill Buzbee2fc03c32010-03-08 11:30:19 -0800681 /* Disable new translation requests */
682 gDvmJit.pProfTable = NULL;
683 gDvmJit.pProfTableCopy = NULL;
684
Ben Cheng88a0f972010-02-24 15:00:40 -0800685 if (gDvm.verboseShutdown) {
686 dvmCompilerDumpStats();
687 while (gDvmJit.compilerQueueLength)
688 sleep(5);
689 }
690
Ben Chengba4fc8b2009-06-01 13:00:29 -0700691 if (gDvmJit.compilerHandle) {
692
693 gDvmJit.haltCompilerThread = true;
694
695 dvmLockMutex(&gDvmJit.compilerLock);
696 pthread_cond_signal(&gDvmJit.compilerQueueActivity);
697 dvmUnlockMutex(&gDvmJit.compilerLock);
698
Ben Chengef00a852009-06-22 22:53:35 -0700699 if (pthread_join(gDvmJit.compilerHandle, &threadReturn) != 0)
700 LOGW("Compiler thread join failed\n");
Andy McFadden43eb5012010-02-01 16:56:53 -0800701 else if (gDvm.verboseShutdown)
Ben Chengef00a852009-06-22 22:53:35 -0700702 LOGD("Compiler thread has shut down\n");
Ben Chengba4fc8b2009-06-01 13:00:29 -0700703 }
Bill Buzbee06bb8392010-01-31 18:53:15 -0800704
Bill Buzbee2fc03c32010-03-08 11:30:19 -0800705 /* Break loops within the translation cache */
706 dvmJitUnchainAll();
Bill Buzbee96cfe6c2010-02-08 17:08:15 -0800707
Bill Buzbee2fc03c32010-03-08 11:30:19 -0800708 /*
709 * NOTE: our current implementatation doesn't allow for the compiler
710 * thread to be restarted after it exits here. We aren't freeing
711 * the JitTable or the ProfTable because threads which still may be
712 * running or in the process of shutting down may hold references to
713 * them.
714 */
Bill Buzbee96cfe6c2010-02-08 17:08:15 -0800715}
Bill Buzbee06bb8392010-01-31 18:53:15 -0800716
717void dvmCompilerStateRefresh()
718{
719 bool jitActive;
720 bool jitActivate;
Bill Buzbee3e392682010-02-03 18:13:57 -0800721 bool needUnchain = false;
Bill Buzbee06bb8392010-01-31 18:53:15 -0800722
Ben Chenga4973592010-03-31 11:59:18 -0700723 /*
724 * The tableLock might not be initialized yet by the compiler thread if
725 * debugger is attached from the very beginning of the VM launch. If
726 * pProfTableCopy is NULL, the lock is not initialized yet and we don't
727 * need to refresh anything either.
728 */
729 if (gDvmJit.pProfTableCopy == NULL) {
730 return;
731 }
732
Bill Buzbee06bb8392010-01-31 18:53:15 -0800733 dvmLockMutex(&gDvmJit.tableLock);
734 jitActive = gDvmJit.pProfTable != NULL;
Andy McFaddenc95e0fb2010-04-29 14:13:01 -0700735
736#if defined(WITH_DEBUGGER) && defined(WITH_PROFILER)
Bill Buzbee06bb8392010-01-31 18:53:15 -0800737 jitActivate = !(gDvm.debuggerActive || (gDvm.activeProfilers > 0));
Andy McFaddenc95e0fb2010-04-29 14:13:01 -0700738#elif defined(WITH_DEBUGGER)
739 jitActivate = !gDvm.debuggerActive;
740#elif defined(WITH_PROFILER)
741 jitActivate = !(gDvm.activeProfilers > 0);
742#else
743 jitActivate = true;
744#endif
Bill Buzbee06bb8392010-01-31 18:53:15 -0800745
746 if (jitActivate && !jitActive) {
747 gDvmJit.pProfTable = gDvmJit.pProfTableCopy;
Bill Buzbee06bb8392010-01-31 18:53:15 -0800748 } else if (!jitActivate && jitActive) {
749 gDvmJit.pProfTable = NULL;
Bill Buzbee3e392682010-02-03 18:13:57 -0800750 needUnchain = true;
Bill Buzbee06bb8392010-01-31 18:53:15 -0800751 }
Bill Buzbee3e392682010-02-03 18:13:57 -0800752 dvmUnlockMutex(&gDvmJit.tableLock);
753 if (needUnchain)
754 dvmJitUnchainAll();
Bill Buzbee06bb8392010-01-31 18:53:15 -0800755}