blob: 39f92b5cd4b3a44138a2cc29212d964f7ec9ae4c [file] [log] [blame]
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001/*
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 * Garbage-collecting memory allocator.
18 */
19#include "Dalvik.h"
Barry Hayes962adba2010-03-17 12:12:39 -070020#include "alloc/HeapBitmap.h"
21#include "alloc/Verify.h"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080022#include "alloc/HeapTable.h"
23#include "alloc/Heap.h"
24#include "alloc/HeapInternal.h"
25#include "alloc/DdmHeap.h"
26#include "alloc/HeapSource.h"
27#include "alloc/MarkSweep.h"
28
29#include "utils/threads.h" // need Android thread priorities
30#define kInvalidPriority 10000
31
San Mehat5a2056c2009-09-12 10:10:13 -070032#include <cutils/sched_policy.h>
33
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080034#include <sys/time.h>
35#include <sys/resource.h>
36#include <limits.h>
37#include <errno.h>
38
Barry Hayes1b9b4e42010-01-04 10:33:46 -080039static const char* GcReasonStr[] = {
40 [GC_FOR_MALLOC] = "GC_FOR_MALLOC",
Carl Shapiroec805ea2010-06-28 16:28:26 -070041 [GC_CONCURRENT] = "GC_CONCURRENT",
Carl Shapiroe7bdd8b2010-12-17 15:34:52 -080042 [GC_EXPLICIT] = "GC_EXPLICIT"
Barry Hayes1b9b4e42010-01-04 10:33:46 -080043};
44
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080045/*
46 * Initialize the GC heap.
47 *
48 * Returns true if successful, false otherwise.
49 */
50bool dvmHeapStartup()
51{
52 GcHeap *gcHeap;
53
Carl Shapirodf9f08b2011-01-18 17:59:30 -080054 if (gDvm.heapGrowthLimit == 0) {
55 gDvm.heapGrowthLimit = gDvm.heapMaximumSize;
56 }
57
58 gcHeap = dvmHeapSourceStartup(gDvm.heapStartingSize,
59 gDvm.heapMaximumSize,
60 gDvm.heapGrowthLimit);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080061 if (gcHeap == NULL) {
62 return false;
63 }
64 gcHeap->heapWorkerCurrentObject = NULL;
65 gcHeap->heapWorkerCurrentMethod = NULL;
66 gcHeap->heapWorkerInterpStartTime = 0LL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080067 gcHeap->ddmHpifWhen = 0;
68 gcHeap->ddmHpsgWhen = 0;
69 gcHeap->ddmHpsgWhat = 0;
70 gcHeap->ddmNhsgWhen = 0;
71 gcHeap->ddmNhsgWhat = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080072 gDvm.gcHeap = gcHeap;
73
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080074 /* Set up the lists and lock we'll use for finalizable
75 * and reference objects.
76 */
77 dvmInitMutex(&gDvm.heapWorkerListLock);
78 gcHeap->finalizableRefs = NULL;
79 gcHeap->pendingFinalizationRefs = NULL;
80 gcHeap->referenceOperations = NULL;
81
Carl Shapirodf9f08b2011-01-18 17:59:30 -080082 if (!dvmCardTableStartup(gDvm.heapMaximumSize)) {
Barry Hayesb874ab92010-07-14 08:13:18 -070083 LOGE_HEAP("card table startup failed.");
84 return false;
85 }
86
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080087 /* Initialize the HeapWorker locks and other state
88 * that the GC uses.
89 */
90 dvmInitializeHeapWorkerState();
91
92 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080093}
94
Carl Shapiroec805ea2010-06-28 16:28:26 -070095bool dvmHeapStartupAfterZygote(void)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080096{
Carl Shapiroec805ea2010-06-28 16:28:26 -070097 return dvmHeapSourceStartupAfterZygote();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080098}
99
100void dvmHeapShutdown()
101{
102//TODO: make sure we're locked
103 if (gDvm.gcHeap != NULL) {
Barry Hayesb874ab92010-07-14 08:13:18 -0700104 dvmCardTableShutdown();
105 /* Tables are allocated on the native heap; they need to be
106 * cleaned up explicitly. The process may stick around, so we
107 * don't want to leak any native memory.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800108 */
Carl Shapiroa199eb72010-02-09 16:26:30 -0800109 dvmHeapFreeLargeTable(gDvm.gcHeap->finalizableRefs);
110 gDvm.gcHeap->finalizableRefs = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800111
Carl Shapiroa199eb72010-02-09 16:26:30 -0800112 dvmHeapFreeLargeTable(gDvm.gcHeap->pendingFinalizationRefs);
113 gDvm.gcHeap->pendingFinalizationRefs = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800114
Carl Shapiroa199eb72010-02-09 16:26:30 -0800115 dvmHeapFreeLargeTable(gDvm.gcHeap->referenceOperations);
116 gDvm.gcHeap->referenceOperations = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800117
Barry Hayesb874ab92010-07-14 08:13:18 -0700118 /* Destroy the heap. Any outstanding pointers will point to
119 * unmapped memory (unless/until someone else maps it). This
120 * frees gDvm.gcHeap as a side-effect.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800121 */
Carl Shapiroa199eb72010-02-09 16:26:30 -0800122 dvmHeapSourceShutdown(&gDvm.gcHeap);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800123 }
124}
125
126/*
Carl Shapiroec805ea2010-06-28 16:28:26 -0700127 * Shutdown any threads internal to the heap.
128 */
129void dvmHeapThreadShutdown(void)
130{
131 dvmHeapSourceThreadShutdown();
132}
133
134/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800135 * We've been asked to allocate something we can't, e.g. an array so
Andy McFadden6da743b2009-07-15 16:56:00 -0700136 * large that (length * elementWidth) is larger than 2^31.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800137 *
Andy McFadden6da743b2009-07-15 16:56:00 -0700138 * _The Java Programming Language_, 4th edition, says, "you can be sure
139 * that all SoftReferences to softly reachable objects will be cleared
140 * before an OutOfMemoryError is thrown."
141 *
142 * It's unclear whether that holds for all situations where an OOM can
143 * be thrown, or just in the context of an allocation that fails due
144 * to lack of heap space. For simplicity we just throw the exception.
145 *
146 * (OOM due to actually running out of space is handled elsewhere.)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800147 */
148void dvmThrowBadAllocException(const char* msg)
149{
Andy McFadden6da743b2009-07-15 16:56:00 -0700150 dvmThrowException("Ljava/lang/OutOfMemoryError;", msg);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800151}
152
153/*
154 * Grab the lock, but put ourselves into THREAD_VMWAIT if it looks like
155 * we're going to have to wait on the mutex.
156 */
157bool dvmLockHeap()
158{
Carl Shapiro980ffb02010-03-13 22:34:01 -0800159 if (dvmTryLockMutex(&gDvm.gcHeapLock) != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800160 Thread *self;
161 ThreadStatus oldStatus;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800162
163 self = dvmThreadSelf();
Carl Shapiro5617ad32010-07-02 10:50:57 -0700164 oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
Carl Shapiro980ffb02010-03-13 22:34:01 -0800165 dvmLockMutex(&gDvm.gcHeapLock);
Carl Shapiro5617ad32010-07-02 10:50:57 -0700166 dvmChangeStatus(self, oldStatus);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800167 }
168
169 return true;
170}
171
172void dvmUnlockHeap()
173{
174 dvmUnlockMutex(&gDvm.gcHeapLock);
175}
176
177/* Pop an object from the list of pending finalizations and
178 * reference clears/enqueues, and return the object.
179 * The caller must call dvmReleaseTrackedAlloc()
180 * on the object when finished.
181 *
182 * Typically only called by the heap worker thread.
183 */
184Object *dvmGetNextHeapWorkerObject(HeapWorkerOperation *op)
185{
186 Object *obj;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800187 GcHeap *gcHeap = gDvm.gcHeap;
188
189 assert(op != NULL);
190
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800191 dvmLockMutex(&gDvm.heapWorkerListLock);
192
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800193 obj = dvmHeapGetNextObjectFromLargeTable(&gcHeap->referenceOperations);
194 if (obj != NULL) {
Carl Shapiro646ba092010-06-10 15:17:00 -0700195 *op = WORKER_ENQUEUE;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800196 } else {
197 obj = dvmHeapGetNextObjectFromLargeTable(
198 &gcHeap->pendingFinalizationRefs);
199 if (obj != NULL) {
200 *op = WORKER_FINALIZE;
201 }
202 }
203
204 if (obj != NULL) {
205 /* Don't let the GC collect the object until the
206 * worker thread is done with it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800207 */
208 dvmAddTrackedAlloc(obj, NULL);
209 }
210
211 dvmUnlockMutex(&gDvm.heapWorkerListLock);
212
213 return obj;
214}
215
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800216/* Do a full garbage collection, which may grow the
217 * heap as a side-effect if the live set is large.
218 */
219static void gcForMalloc(bool collectSoftReferences)
220{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800221 if (gDvm.allocProf.enabled) {
222 Thread* self = dvmThreadSelf();
223 gDvm.allocProf.gcCount++;
224 if (self != NULL) {
225 self->allocProf.gcCount++;
226 }
227 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800228 /* This may adjust the soft limit as a side-effect.
229 */
230 LOGD_HEAP("dvmMalloc initiating GC%s\n",
231 collectSoftReferences ? "(collect SoftReferences)" : "");
Barry Hayes1b9b4e42010-01-04 10:33:46 -0800232 dvmCollectGarbageInternal(collectSoftReferences, GC_FOR_MALLOC);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800233}
234
235/* Try as hard as possible to allocate some memory.
236 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800237static void *tryMalloc(size_t size)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800238{
Carl Shapiro6343bd02010-02-16 17:40:19 -0800239 void *ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800240
241 /* Don't try too hard if there's no way the allocation is
242 * going to succeed. We have to collect SoftReferences before
243 * throwing an OOME, though.
244 */
Carl Shapirodf9f08b2011-01-18 17:59:30 -0800245 if (size >= gDvm.heapGrowthLimit) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800246 LOGW_HEAP("dvmMalloc(%zu/0x%08zx): "
247 "someone's allocating a huge buffer\n", size, size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800248 ptr = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800249 goto collect_soft_refs;
250 }
251
252//TODO: figure out better heuristics
253// There will be a lot of churn if someone allocates a bunch of
254// big objects in a row, and we hit the frag case each time.
255// A full GC for each.
256// Maybe we grow the heap in bigger leaps
257// Maybe we skip the GC if the size is large and we did one recently
258// (number of allocations ago) (watch for thread effects)
259// DeflateTest allocs a bunch of ~128k buffers w/in 0-5 allocs of each other
260// (or, at least, there are only 0-5 objects swept each time)
261
Carl Shapiro6343bd02010-02-16 17:40:19 -0800262 ptr = dvmHeapSourceAlloc(size);
263 if (ptr != NULL) {
264 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800265 }
266
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700267 /*
268 * The allocation failed. If the GC is running, block until it
269 * completes and retry.
270 */
271 if (gDvm.gcHeap->gcRunning) {
272 /*
273 * The GC is concurrently tracing the heap. Release the heap
274 * lock, wait for the GC to complete, and retrying allocating.
275 */
276 dvmWaitForConcurrentGcToComplete();
277 ptr = dvmHeapSourceAlloc(size);
278 if (ptr != NULL) {
279 return ptr;
280 }
281 }
282 /*
283 * Another failure. Our thread was starved or there may be too
284 * many live objects. Try a foreground GC. This will have no
285 * effect if the concurrent GC is already running.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800286 */
287 gcForMalloc(false);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800288 ptr = dvmHeapSourceAlloc(size);
289 if (ptr != NULL) {
290 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800291 }
292
293 /* Even that didn't work; this is an exceptional state.
294 * Try harder, growing the heap if necessary.
295 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800296 ptr = dvmHeapSourceAllocAndGrow(size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800297 if (ptr != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800298 size_t newHeapSize;
299
300 newHeapSize = dvmHeapSourceGetIdealFootprint();
301//TODO: may want to grow a little bit more so that the amount of free
302// space is equal to the old free space + the utilization slop for
303// the new allocation.
304 LOGI_HEAP("Grow heap (frag case) to "
305 "%zu.%03zuMB for %zu-byte allocation\n",
306 FRACTIONAL_MB(newHeapSize), size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800307 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800308 }
309
310 /* Most allocations should have succeeded by now, so the heap
311 * is really full, really fragmented, or the requested size is
312 * really big. Do another GC, collecting SoftReferences this
313 * time. The VM spec requires that all SoftReferences have
314 * been collected and cleared before throwing an OOME.
315 */
316//TODO: wait for the finalizers from the previous GC to finish
317collect_soft_refs:
318 LOGI_HEAP("Forcing collection of SoftReferences for %zu-byte allocation\n",
319 size);
320 gcForMalloc(true);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800321 ptr = dvmHeapSourceAllocAndGrow(size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800322 if (ptr != NULL) {
323 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800324 }
325//TODO: maybe wait for finalizers and try one last time
326
327 LOGE_HEAP("Out of memory on a %zd-byte allocation.\n", size);
328//TODO: tell the HeapSource to dump its state
329 dvmDumpThread(dvmThreadSelf(), false);
330
331 return NULL;
332}
333
334/* Throw an OutOfMemoryError if there's a thread to attach it to.
335 * Avoid recursing.
336 *
337 * The caller must not be holding the heap lock, or else the allocations
338 * in dvmThrowException() will deadlock.
339 */
340static void throwOOME()
341{
342 Thread *self;
343
344 if ((self = dvmThreadSelf()) != NULL) {
345 /* If the current (failing) dvmMalloc() happened as part of thread
346 * creation/attachment before the thread became part of the root set,
347 * we can't rely on the thread-local trackedAlloc table, so
348 * we can't keep track of a real allocated OOME object. But, since
349 * the thread is in the process of being created, it won't have
350 * a useful stack anyway, so we may as well make things easier
351 * by throwing the (stackless) pre-built OOME.
352 */
353 if (dvmIsOnThreadList(self) && !self->throwingOOME) {
354 /* Let ourselves know that we tried to throw an OOM
355 * error in the normal way in case we run out of
356 * memory trying to allocate it inside dvmThrowException().
357 */
358 self->throwingOOME = true;
359
360 /* Don't include a description string;
361 * one fewer allocation.
362 */
363 dvmThrowException("Ljava/lang/OutOfMemoryError;", NULL);
364 } else {
365 /*
366 * This thread has already tried to throw an OutOfMemoryError,
367 * which probably means that we're running out of memory
368 * while recursively trying to throw.
369 *
370 * To avoid any more allocation attempts, "throw" a pre-built
371 * OutOfMemoryError object (which won't have a useful stack trace).
372 *
373 * Note that since this call can't possibly allocate anything,
374 * we don't care about the state of self->throwingOOME
375 * (which will usually already be set).
376 */
377 dvmSetException(self, gDvm.outOfMemoryObj);
378 }
379 /* We're done with the possible recursion.
380 */
381 self->throwingOOME = false;
382 }
383}
384
385/*
386 * Allocate storage on the GC heap. We guarantee 8-byte alignment.
387 *
388 * The new storage is zeroed out.
389 *
390 * Note that, in rare cases, this could get called while a GC is in
391 * progress. If a non-VM thread tries to attach itself through JNI,
392 * it will need to allocate some objects. If this becomes annoying to
393 * deal with, we can block it at the source, but holding the allocation
394 * mutex should be enough.
395 *
396 * In rare circumstances (JNI AttachCurrentThread) we can be called
397 * from a non-VM thread.
398 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800399 * Use ALLOC_DONT_TRACK when we either don't want to track an allocation
400 * (because it's being done for the interpreter "new" operation and will
401 * be part of the root set immediately) or we can't (because this allocation
402 * is for a brand new thread).
403 *
404 * Returns NULL and throws an exception on failure.
405 *
406 * TODO: don't do a GC if the debugger thinks all threads are suspended
407 */
408void* dvmMalloc(size_t size, int flags)
409{
410 GcHeap *gcHeap = gDvm.gcHeap;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800411 void *ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800412
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800413 dvmLockHeap();
414
415 /* Try as hard as possible to allocate some memory.
416 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800417 ptr = tryMalloc(size);
418 if (ptr != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800419 /* We've got the memory.
420 */
421 if ((flags & ALLOC_FINALIZABLE) != 0) {
422 /* This object is an instance of a class that
423 * overrides finalize(). Add it to the finalizable list.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800424 */
425 if (!dvmHeapAddRefToLargeTable(&gcHeap->finalizableRefs,
Carl Shapiro6343bd02010-02-16 17:40:19 -0800426 (Object *)ptr))
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800427 {
428 LOGE_HEAP("dvmMalloc(): no room for any more "
429 "finalizable objects\n");
430 dvmAbort();
431 }
432 }
433
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800434 if (gDvm.allocProf.enabled) {
435 Thread* self = dvmThreadSelf();
436 gDvm.allocProf.allocCount++;
437 gDvm.allocProf.allocSize += size;
438 if (self != NULL) {
439 self->allocProf.allocCount++;
440 self->allocProf.allocSize += size;
441 }
442 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800443 } else {
444 /* The allocation failed.
445 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800446
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800447 if (gDvm.allocProf.enabled) {
448 Thread* self = dvmThreadSelf();
449 gDvm.allocProf.failedAllocCount++;
450 gDvm.allocProf.failedAllocSize += size;
451 if (self != NULL) {
452 self->allocProf.failedAllocCount++;
453 self->allocProf.failedAllocSize += size;
454 }
455 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800456 }
457
458 dvmUnlockHeap();
459
460 if (ptr != NULL) {
461 /*
Barry Hayesd4f78d32010-06-08 09:34:42 -0700462 * If caller hasn't asked us not to track it, add it to the
463 * internal tracking list.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800464 */
Barry Hayesd4f78d32010-06-08 09:34:42 -0700465 if ((flags & ALLOC_DONT_TRACK) == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800466 dvmAddTrackedAlloc(ptr, NULL);
467 }
468 } else {
Ben Chengc3b92b22010-01-26 16:46:15 -0800469 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800470 * The allocation failed; throw an OutOfMemoryError.
471 */
472 throwOOME();
473 }
474
475 return ptr;
476}
477
478/*
479 * Returns true iff <obj> points to a valid allocated object.
480 */
481bool dvmIsValidObject(const Object* obj)
482{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800483 /* Don't bother if it's NULL or not 8-byte aligned.
484 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800485 if (obj != NULL && ((uintptr_t)obj & (8-1)) == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800486 /* Even if the heap isn't locked, this shouldn't return
487 * any false negatives. The only mutation that could
488 * be happening is allocation, which means that another
489 * thread could be in the middle of a read-modify-write
490 * to add a new bit for a new object. However, that
491 * RMW will have completed by the time any other thread
492 * could possibly see the new pointer, so there is no
493 * danger of dvmIsValidObject() being called on a valid
494 * pointer whose bit isn't set.
495 *
496 * Freeing will only happen during the sweep phase, which
497 * only happens while the heap is locked.
498 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800499 return dvmHeapSourceContains(obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800500 }
501 return false;
502}
503
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800504size_t dvmObjectSizeInHeap(const Object *obj)
505{
Carl Shapiro6343bd02010-02-16 17:40:19 -0800506 return dvmHeapSourceChunkSize(obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800507}
508
Carl Shapiro6c5dd932010-08-05 21:49:07 -0700509static void verifyRootsAndHeap(void)
Barry Hayes962adba2010-03-17 12:12:39 -0700510{
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700511 dvmVerifyRoots();
512 dvmVerifyBitmap(dvmHeapSourceGetLiveBits());
Barry Hayes962adba2010-03-17 12:12:39 -0700513}
514
515/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800516 * Initiate garbage collection.
517 *
518 * NOTES:
519 * - If we don't hold gDvm.threadListLock, it's possible for a thread to
520 * be added to the thread list while we work. The thread should NOT
521 * start executing, so this is only interesting when we start chasing
522 * thread stacks. (Before we do so, grab the lock.)
523 *
524 * We are not allowed to GC when the debugger has suspended the VM, which
525 * is awkward because debugger requests can cause allocations. The easiest
526 * way to enforce this is to refuse to GC on an allocation made by the
527 * JDWP thread -- we have to expand the heap or fail.
528 */
Carl Shapiro29540742010-03-26 15:34:39 -0700529void dvmCollectGarbageInternal(bool clearSoftRefs, GcReason reason)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800530{
531 GcHeap *gcHeap = gDvm.gcHeap;
Carl Shapiro8881a802010-08-10 15:55:45 -0700532 u4 rootSuspend, rootSuspendTime, rootStart, rootEnd;
533 u4 dirtySuspend, dirtyStart, dirtyEnd;
534 u4 totalTime;
Carl Shapiro570942c2010-09-17 15:53:16 -0700535 size_t numObjectsFreed, numBytesFreed;
536 size_t currAllocated, currFootprint;
Carl Shapiro570942c2010-09-17 15:53:16 -0700537 size_t percentFree;
Carl Shapirod25566d2010-03-11 20:39:47 -0800538 GcMode gcMode;
Carl Shapiroec805ea2010-06-28 16:28:26 -0700539 int oldThreadPriority = kInvalidPriority;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800540
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800541 /* The heap lock must be held.
542 */
543
544 if (gcHeap->gcRunning) {
545 LOGW_HEAP("Attempted recursive GC\n");
546 return;
547 }
Carl Shapiro03f3b132010-07-27 17:25:31 -0700548
Carl Shapirod25566d2010-03-11 20:39:47 -0800549 gcMode = (reason == GC_FOR_MALLOC) ? GC_PARTIAL : GC_FULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800550 gcHeap->gcRunning = true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800551
Carl Shapiro8881a802010-08-10 15:55:45 -0700552 rootSuspend = dvmGetRelativeTimeMsec();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800553 dvmSuspendAllThreads(SUSPEND_FOR_GC);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700554 rootStart = dvmGetRelativeTimeMsec();
Carl Shapiro8881a802010-08-10 15:55:45 -0700555 rootSuspendTime = rootStart - rootSuspend;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800556
Carl Shapiroec805ea2010-06-28 16:28:26 -0700557 /*
558 * If we are not marking concurrently raise the priority of the
559 * thread performing the garbage collection.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800560 */
Carl Shapiroec805ea2010-06-28 16:28:26 -0700561 if (reason != GC_CONCURRENT) {
562 /* Get the priority (the "nice" value) of the current thread. The
563 * getpriority() call can legitimately return -1, so we have to
564 * explicitly test errno.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800565 */
Carl Shapiroec805ea2010-06-28 16:28:26 -0700566 errno = 0;
567 int priorityResult = getpriority(PRIO_PROCESS, 0);
568 if (errno != 0) {
569 LOGI_HEAP("getpriority(self) failed: %s\n", strerror(errno));
570 } else if (priorityResult > ANDROID_PRIORITY_NORMAL) {
571 /* Current value is numerically greater than "normal", which
572 * in backward UNIX terms means lower priority.
573 */
San Mehat256fc152009-04-21 14:03:06 -0700574
Carl Shapiroec805ea2010-06-28 16:28:26 -0700575 if (priorityResult >= ANDROID_PRIORITY_BACKGROUND) {
576 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
577 }
San Mehat256fc152009-04-21 14:03:06 -0700578
Carl Shapiroec805ea2010-06-28 16:28:26 -0700579 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL) != 0) {
580 LOGI_HEAP("Unable to elevate priority from %d to %d\n",
581 priorityResult, ANDROID_PRIORITY_NORMAL);
582 } else {
583 /* priority elevated; save value so we can restore it later */
584 LOGD_HEAP("Elevating priority from %d to %d\n",
585 priorityResult, ANDROID_PRIORITY_NORMAL);
586 oldThreadPriority = priorityResult;
587 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800588 }
589 }
590
591 /* Wait for the HeapWorker thread to block.
592 * (It may also already be suspended in interp code,
593 * in which case it's not holding heapWorkerLock.)
594 */
595 dvmLockMutex(&gDvm.heapWorkerLock);
596
597 /* Make sure that the HeapWorker thread hasn't become
598 * wedged inside interp code. If it has, this call will
599 * print a message and abort the VM.
600 */
601 dvmAssertHeapWorkerThreadRunning();
602
603 /* Lock the pendingFinalizationRefs list.
604 *
605 * Acquire the lock after suspending so the finalizer
606 * thread can't block in the RUNNING state while
607 * we try to suspend.
608 */
609 dvmLockMutex(&gDvm.heapWorkerListLock);
610
Barry Hayes962adba2010-03-17 12:12:39 -0700611 if (gDvm.preVerify) {
Carl Shapiro6c5dd932010-08-05 21:49:07 -0700612 LOGV_HEAP("Verifying roots and heap before GC");
613 verifyRootsAndHeap();
Barry Hayes962adba2010-03-17 12:12:39 -0700614 }
615
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800616 dvmMethodTraceGCBegin();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800617
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800618 /* Set up the marking context.
619 */
Carl Shapirod25566d2010-03-11 20:39:47 -0800620 if (!dvmHeapBeginMarkStep(gcMode)) {
The Android Open Source Project99409882009-03-18 22:20:24 -0700621 LOGE_HEAP("dvmHeapBeginMarkStep failed; aborting\n");
622 dvmAbort();
623 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800624
625 /* Mark the set of objects that are strongly reachable from the roots.
626 */
627 LOGD_HEAP("Marking...");
628 dvmHeapMarkRootSet();
629
630 /* dvmHeapScanMarkedObjects() will build the lists of known
631 * instances of the Reference classes.
632 */
633 gcHeap->softReferences = NULL;
634 gcHeap->weakReferences = NULL;
635 gcHeap->phantomReferences = NULL;
636
Carl Shapiroec805ea2010-06-28 16:28:26 -0700637 if (reason == GC_CONCURRENT) {
638 /*
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700639 * Resume threads while tracing from the roots. We unlock the
640 * heap to allow mutator threads to allocate from free space.
Carl Shapiroec805ea2010-06-28 16:28:26 -0700641 */
Carl Shapiro03f3b132010-07-27 17:25:31 -0700642 rootEnd = dvmGetRelativeTimeMsec();
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700643 dvmClearCardTable();
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700644 dvmUnlockHeap();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700645 dvmResumeAllThreads(SUSPEND_FOR_GC);
646 }
647
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800648 /* Recursively mark any objects that marked objects point to strongly.
649 * If we're not collecting soft references, soft-reachable
650 * objects will also be marked.
651 */
652 LOGD_HEAP("Recursing...");
653 dvmHeapScanMarkedObjects();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800654
Carl Shapiroec805ea2010-06-28 16:28:26 -0700655 if (reason == GC_CONCURRENT) {
656 /*
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700657 * Re-acquire the heap lock and perform the final thread
658 * suspension.
Carl Shapiroec805ea2010-06-28 16:28:26 -0700659 */
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700660 dvmLockHeap();
Carl Shapiro8881a802010-08-10 15:55:45 -0700661 dirtySuspend = dvmGetRelativeTimeMsec();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700662 dvmSuspendAllThreads(SUSPEND_FOR_GC);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700663 dirtyStart = dvmGetRelativeTimeMsec();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700664 /*
665 * As no barrier intercepts root updates, we conservatively
666 * assume all roots may be gray and re-mark them.
667 */
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700668 dvmHeapReMarkRootSet();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700669 /*
Carl Shapiro5ba39372010-08-06 17:07:53 -0700670 * With the exception of reference objects and weak interned
671 * strings, all gray objects should now be on dirty cards.
672 */
673 if (gDvm.verifyCardTable) {
674 dvmVerifyCardTable();
675 }
676 /*
Carl Shapiroec805ea2010-06-28 16:28:26 -0700677 * Recursively mark gray objects pointed to by the roots or by
678 * heap objects dirtied during the concurrent mark.
679 */
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700680 dvmHeapReScanMarkedObjects();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700681 }
682
Carl Shapiroe8ef2b52010-12-01 19:32:05 -0800683 /*
684 * All strongly-reachable objects have now been marked. Process
685 * weakly-reachable objects discovered while tracing.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800686 */
Carl Shapiroe8ef2b52010-12-01 19:32:05 -0800687 dvmHeapProcessReferences(&gcHeap->softReferences, clearSoftRefs,
688 &gcHeap->weakReferences,
689 &gcHeap->phantomReferences);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800690
Carl Shapiro8881a802010-08-10 15:55:45 -0700691#if defined(WITH_JIT)
692 /*
693 * Patching a chaining cell is very cheap as it only updates 4 words. It's
694 * the overhead of stopping all threads and synchronizing the I/D cache
695 * that makes it expensive.
696 *
697 * Therefore we batch those work orders in a queue and go through them
698 * when threads are suspended for GC.
699 */
700 dvmCompilerPerformSafePointChecks();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800701#endif
702
Carl Shapiro8881a802010-08-10 15:55:45 -0700703 LOGD_HEAP("Sweeping...");
704
705 dvmHeapSweepSystemWeaks();
706
707 /*
708 * Live objects have a bit set in the mark bitmap, swap the mark
709 * and live bitmaps. The sweep can proceed concurrently viewing
710 * the new live bitmap as the old mark bitmap, and vice versa.
711 */
712 dvmHeapSourceSwapBitmaps();
713
714 if (gDvm.postVerify) {
715 LOGV_HEAP("Verifying roots and heap after GC");
716 verifyRootsAndHeap();
717 }
718
719 if (reason == GC_CONCURRENT) {
720 dirtyEnd = dvmGetRelativeTimeMsec();
721 dvmUnlockHeap();
722 dvmResumeAllThreads(SUSPEND_FOR_GC);
723 }
724 dvmHeapSweepUnmarkedObjects(gcMode, reason == GC_CONCURRENT,
Carl Shapiro570942c2010-09-17 15:53:16 -0700725 &numObjectsFreed, &numBytesFreed);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800726 LOGD_HEAP("Cleaning up...");
727 dvmHeapFinishMarkStep();
Carl Shapiro8881a802010-08-10 15:55:45 -0700728 if (reason == GC_CONCURRENT) {
729 dvmLockHeap();
730 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800731
732 LOGD_HEAP("Done.");
733
734 /* Now's a good time to adjust the heap size, since
735 * we know what our utilization is.
736 *
737 * This doesn't actually resize any memory;
738 * it just lets the heap grow more when necessary.
739 */
Carl Shapiroe7bdd8b2010-12-17 15:34:52 -0800740 dvmHeapSourceGrowForUtilization();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800741
Carl Shapiro570942c2010-09-17 15:53:16 -0700742 currAllocated = dvmHeapSourceGetValue(HS_BYTES_ALLOCATED, NULL, 0);
743 currFootprint = dvmHeapSourceGetValue(HS_FOOTPRINT, NULL, 0);
744
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800745 /* Now that we've freed up the GC heap, return any large
746 * free chunks back to the system. They'll get paged back
747 * in the next time they're used. Don't do it immediately,
748 * though; if the process is still allocating a bunch of
749 * memory, we'll be taking a ton of page faults that we don't
750 * necessarily need to.
751 *
752 * Cancel any old scheduled trims, and schedule a new one.
753 */
754 dvmScheduleHeapSourceTrim(5); // in seconds
755
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800756 dvmMethodTraceGCEnd();
Barry Hayes962adba2010-03-17 12:12:39 -0700757 LOGV_HEAP("GC finished");
758
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800759 gcHeap->gcRunning = false;
760
Barry Hayes962adba2010-03-17 12:12:39 -0700761 LOGV_HEAP("Resuming threads");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800762 dvmUnlockMutex(&gDvm.heapWorkerListLock);
763 dvmUnlockMutex(&gDvm.heapWorkerLock);
764
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700765 if (reason == GC_CONCURRENT) {
766 /*
767 * Wake-up any threads that blocked after a failed allocation
768 * request.
769 */
770 dvmBroadcastCond(&gDvm.gcHeapCond);
771 }
772
Carl Shapiroec805ea2010-06-28 16:28:26 -0700773 if (reason != GC_CONCURRENT) {
Carl Shapiro8881a802010-08-10 15:55:45 -0700774 dirtyEnd = dvmGetRelativeTimeMsec();
775 dvmResumeAllThreads(SUSPEND_FOR_GC);
Carl Shapiroec805ea2010-06-28 16:28:26 -0700776 if (oldThreadPriority != kInvalidPriority) {
777 if (setpriority(PRIO_PROCESS, 0, oldThreadPriority) != 0) {
778 LOGW_HEAP("Unable to reset priority to %d: %s\n",
779 oldThreadPriority, strerror(errno));
780 } else {
781 LOGD_HEAP("Reset priority to %d\n", oldThreadPriority);
782 }
San Mehat256fc152009-04-21 14:03:06 -0700783
Carl Shapiroec805ea2010-06-28 16:28:26 -0700784 if (oldThreadPriority >= ANDROID_PRIORITY_BACKGROUND) {
785 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
786 }
San Mehat256fc152009-04-21 14:03:06 -0700787 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800788 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800789
Carl Shapiro570942c2010-09-17 15:53:16 -0700790 percentFree = 100 - (size_t)(100.0f * (float)currAllocated / currFootprint);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700791 if (reason != GC_CONCURRENT) {
Carl Shapiro03f3b132010-07-27 17:25:31 -0700792 u4 markSweepTime = dirtyEnd - rootStart;
Carl Shapiro570942c2010-09-17 15:53:16 -0700793 bool isSmall = numBytesFreed > 0 && numBytesFreed < 1024;
Carl Shapiro8881a802010-08-10 15:55:45 -0700794 totalTime = rootSuspendTime + markSweepTime;
Carl Shapiroe7bdd8b2010-12-17 15:34:52 -0800795 LOGD("%s freed %s%zdK, %d%% free %zdK/%zdK, paused %ums",
Carl Shapiro570942c2010-09-17 15:53:16 -0700796 GcReasonStr[reason],
797 isSmall ? "<" : "",
798 numBytesFreed ? MAX(numBytesFreed / 1024, 1) : 0,
799 percentFree,
800 currAllocated / 1024, currFootprint / 1024,
Carl Shapiro570942c2010-09-17 15:53:16 -0700801 markSweepTime);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700802 } else {
Carl Shapiro8881a802010-08-10 15:55:45 -0700803 u4 rootTime = rootEnd - rootStart;
804 u4 dirtySuspendTime = dirtyStart - dirtySuspend;
805 u4 dirtyTime = dirtyEnd - dirtyStart;
Carl Shapiro570942c2010-09-17 15:53:16 -0700806 bool isSmall = numBytesFreed > 0 && numBytesFreed < 1024;
Carl Shapiro03f3b132010-07-27 17:25:31 -0700807 totalTime = rootSuspendTime + rootTime + dirtySuspendTime + dirtyTime;
Carl Shapiroe7bdd8b2010-12-17 15:34:52 -0800808 LOGD("%s freed %s%zdK, %d%% free %zdK/%zdK, paused %ums+%ums",
Carl Shapiro570942c2010-09-17 15:53:16 -0700809 GcReasonStr[reason],
810 isSmall ? "<" : "",
811 numBytesFreed ? MAX(numBytesFreed / 1024, 1) : 0,
812 percentFree,
813 currAllocated / 1024, currFootprint / 1024,
Carl Shapiro570942c2010-09-17 15:53:16 -0700814 rootTime, dirtyTime);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700815 }
Carl Shapiro570942c2010-09-17 15:53:16 -0700816 dvmLogGcStats(numObjectsFreed, numBytesFreed, totalTime);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800817 if (gcHeap->ddmHpifWhen != 0) {
818 LOGD_HEAP("Sending VM heap info to DDM\n");
819 dvmDdmSendHeapInfo(gcHeap->ddmHpifWhen, false);
820 }
821 if (gcHeap->ddmHpsgWhen != 0) {
822 LOGD_HEAP("Dumping VM heap to DDM\n");
823 dvmDdmSendHeapSegments(false, false);
824 }
825 if (gcHeap->ddmNhsgWhen != 0) {
826 LOGD_HEAP("Dumping native heap to DDM\n");
827 dvmDdmSendHeapSegments(false, true);
828 }
829}
830
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700831void dvmWaitForConcurrentGcToComplete(void)
832{
833 Thread *self = dvmThreadSelf();
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700834 assert(self != NULL);
Carl Shapiro039167e2010-12-20 18:33:24 -0800835 while (gDvm.gcHeap->gcRunning) {
836 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
837 dvmWaitCond(&gDvm.gcHeapCond, &gDvm.gcHeapLock);
838 dvmChangeStatus(self, oldStatus);
839 }
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700840}