blob: bd782bd5d5084c8d8b0577a4c41e9cd5f16ae086 [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",
Barry Hayes1b9b4e42010-01-04 10:33:46 -080042 [GC_EXPLICIT] = "GC_EXPLICIT",
Carl Shapiro07018e22010-10-26 21:07:41 -070043 [GC_EXTERNAL_ALLOC] = "GC_EXTERNAL_ALLOC"
Barry Hayes1b9b4e42010-01-04 10:33:46 -080044};
45
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080046/*
47 * Initialize the GC heap.
48 *
49 * Returns true if successful, false otherwise.
50 */
51bool dvmHeapStartup()
52{
53 GcHeap *gcHeap;
54
55#if defined(WITH_ALLOC_LIMITS)
56 gDvm.checkAllocLimits = false;
57 gDvm.allocationLimit = -1;
58#endif
59
60 gcHeap = dvmHeapSourceStartup(gDvm.heapSizeStart, gDvm.heapSizeMax);
61 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
Barry Hayesb874ab92010-07-14 08:13:18 -070082 if (!dvmCardTableStartup()) {
83 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 */
245 if (size >= gDvm.heapSizeMax) {
246 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#if defined(WITH_ALLOC_LIMITS)
414 /*
415 * See if they've exceeded the allocation limit for this thread.
416 *
417 * A limit value of -1 means "no limit".
418 *
419 * This is enabled at compile time because it requires us to do a
420 * TLS lookup for the Thread pointer. This has enough of a performance
421 * impact that we don't want to do it if we don't have to. (Now that
422 * we're using gDvm.checkAllocLimits we may want to reconsider this,
423 * but it's probably still best to just compile the check out of
424 * production code -- one less thing to hit on every allocation.)
425 */
426 if (gDvm.checkAllocLimits) {
427 Thread* self = dvmThreadSelf();
428 if (self != NULL) {
429 int count = self->allocLimit;
430 if (count > 0) {
431 self->allocLimit--;
432 } else if (count == 0) {
433 /* fail! */
434 assert(!gDvm.initializing);
435 self->allocLimit = -1;
436 dvmThrowException("Ldalvik/system/AllocationLimitError;",
437 "thread allocation limit exceeded");
438 return NULL;
439 }
440 }
441 }
442
443 if (gDvm.allocationLimit >= 0) {
444 assert(!gDvm.initializing);
445 gDvm.allocationLimit = -1;
446 dvmThrowException("Ldalvik/system/AllocationLimitError;",
447 "global allocation limit exceeded");
448 return NULL;
449 }
450#endif
451
452 dvmLockHeap();
453
454 /* Try as hard as possible to allocate some memory.
455 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800456 ptr = tryMalloc(size);
457 if (ptr != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800458 /* We've got the memory.
459 */
460 if ((flags & ALLOC_FINALIZABLE) != 0) {
461 /* This object is an instance of a class that
462 * overrides finalize(). Add it to the finalizable list.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800463 */
464 if (!dvmHeapAddRefToLargeTable(&gcHeap->finalizableRefs,
Carl Shapiro6343bd02010-02-16 17:40:19 -0800465 (Object *)ptr))
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800466 {
467 LOGE_HEAP("dvmMalloc(): no room for any more "
468 "finalizable objects\n");
469 dvmAbort();
470 }
471 }
472
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800473 if (gDvm.allocProf.enabled) {
474 Thread* self = dvmThreadSelf();
475 gDvm.allocProf.allocCount++;
476 gDvm.allocProf.allocSize += size;
477 if (self != NULL) {
478 self->allocProf.allocCount++;
479 self->allocProf.allocSize += size;
480 }
481 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800482 } else {
483 /* The allocation failed.
484 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800485
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800486 if (gDvm.allocProf.enabled) {
487 Thread* self = dvmThreadSelf();
488 gDvm.allocProf.failedAllocCount++;
489 gDvm.allocProf.failedAllocSize += size;
490 if (self != NULL) {
491 self->allocProf.failedAllocCount++;
492 self->allocProf.failedAllocSize += size;
493 }
494 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800495 }
496
497 dvmUnlockHeap();
498
499 if (ptr != NULL) {
500 /*
Barry Hayesd4f78d32010-06-08 09:34:42 -0700501 * If caller hasn't asked us not to track it, add it to the
502 * internal tracking list.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800503 */
Barry Hayesd4f78d32010-06-08 09:34:42 -0700504 if ((flags & ALLOC_DONT_TRACK) == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800505 dvmAddTrackedAlloc(ptr, NULL);
506 }
507 } else {
Ben Chengc3b92b22010-01-26 16:46:15 -0800508 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800509 * The allocation failed; throw an OutOfMemoryError.
510 */
511 throwOOME();
512 }
513
514 return ptr;
515}
516
517/*
518 * Returns true iff <obj> points to a valid allocated object.
519 */
520bool dvmIsValidObject(const Object* obj)
521{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800522 /* Don't bother if it's NULL or not 8-byte aligned.
523 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800524 if (obj != NULL && ((uintptr_t)obj & (8-1)) == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800525 /* Even if the heap isn't locked, this shouldn't return
526 * any false negatives. The only mutation that could
527 * be happening is allocation, which means that another
528 * thread could be in the middle of a read-modify-write
529 * to add a new bit for a new object. However, that
530 * RMW will have completed by the time any other thread
531 * could possibly see the new pointer, so there is no
532 * danger of dvmIsValidObject() being called on a valid
533 * pointer whose bit isn't set.
534 *
535 * Freeing will only happen during the sweep phase, which
536 * only happens while the heap is locked.
537 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800538 return dvmHeapSourceContains(obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800539 }
540 return false;
541}
542
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800543size_t dvmObjectSizeInHeap(const Object *obj)
544{
Carl Shapiro6343bd02010-02-16 17:40:19 -0800545 return dvmHeapSourceChunkSize(obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800546}
547
Carl Shapiro6c5dd932010-08-05 21:49:07 -0700548static void verifyRootsAndHeap(void)
Barry Hayes962adba2010-03-17 12:12:39 -0700549{
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700550 dvmVerifyRoots();
551 dvmVerifyBitmap(dvmHeapSourceGetLiveBits());
Barry Hayes962adba2010-03-17 12:12:39 -0700552}
553
554/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800555 * Initiate garbage collection.
556 *
557 * NOTES:
558 * - If we don't hold gDvm.threadListLock, it's possible for a thread to
559 * be added to the thread list while we work. The thread should NOT
560 * start executing, so this is only interesting when we start chasing
561 * thread stacks. (Before we do so, grab the lock.)
562 *
563 * We are not allowed to GC when the debugger has suspended the VM, which
564 * is awkward because debugger requests can cause allocations. The easiest
565 * way to enforce this is to refuse to GC on an allocation made by the
566 * JDWP thread -- we have to expand the heap or fail.
567 */
Carl Shapiro29540742010-03-26 15:34:39 -0700568void dvmCollectGarbageInternal(bool clearSoftRefs, GcReason reason)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800569{
570 GcHeap *gcHeap = gDvm.gcHeap;
Carl Shapiro8881a802010-08-10 15:55:45 -0700571 u4 rootSuspend, rootSuspendTime, rootStart, rootEnd;
572 u4 dirtySuspend, dirtyStart, dirtyEnd;
573 u4 totalTime;
Carl Shapiro570942c2010-09-17 15:53:16 -0700574 size_t numObjectsFreed, numBytesFreed;
575 size_t currAllocated, currFootprint;
576 size_t extAllocated, extLimit;
577 size_t percentFree;
Carl Shapirod25566d2010-03-11 20:39:47 -0800578 GcMode gcMode;
Carl Shapiroec805ea2010-06-28 16:28:26 -0700579 int oldThreadPriority = kInvalidPriority;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800580
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800581 /* The heap lock must be held.
582 */
583
584 if (gcHeap->gcRunning) {
585 LOGW_HEAP("Attempted recursive GC\n");
586 return;
587 }
Carl Shapiro03f3b132010-07-27 17:25:31 -0700588
Carl Shapirod25566d2010-03-11 20:39:47 -0800589 gcMode = (reason == GC_FOR_MALLOC) ? GC_PARTIAL : GC_FULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800590 gcHeap->gcRunning = true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800591
Carl Shapiro8881a802010-08-10 15:55:45 -0700592 rootSuspend = dvmGetRelativeTimeMsec();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800593 dvmSuspendAllThreads(SUSPEND_FOR_GC);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700594 rootStart = dvmGetRelativeTimeMsec();
Carl Shapiro8881a802010-08-10 15:55:45 -0700595 rootSuspendTime = rootStart - rootSuspend;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800596
Carl Shapiroec805ea2010-06-28 16:28:26 -0700597 /*
598 * If we are not marking concurrently raise the priority of the
599 * thread performing the garbage collection.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800600 */
Carl Shapiroec805ea2010-06-28 16:28:26 -0700601 if (reason != GC_CONCURRENT) {
602 /* Get the priority (the "nice" value) of the current thread. The
603 * getpriority() call can legitimately return -1, so we have to
604 * explicitly test errno.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800605 */
Carl Shapiroec805ea2010-06-28 16:28:26 -0700606 errno = 0;
607 int priorityResult = getpriority(PRIO_PROCESS, 0);
608 if (errno != 0) {
609 LOGI_HEAP("getpriority(self) failed: %s\n", strerror(errno));
610 } else if (priorityResult > ANDROID_PRIORITY_NORMAL) {
611 /* Current value is numerically greater than "normal", which
612 * in backward UNIX terms means lower priority.
613 */
San Mehat256fc152009-04-21 14:03:06 -0700614
Carl Shapiroec805ea2010-06-28 16:28:26 -0700615 if (priorityResult >= ANDROID_PRIORITY_BACKGROUND) {
616 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
617 }
San Mehat256fc152009-04-21 14:03:06 -0700618
Carl Shapiroec805ea2010-06-28 16:28:26 -0700619 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL) != 0) {
620 LOGI_HEAP("Unable to elevate priority from %d to %d\n",
621 priorityResult, ANDROID_PRIORITY_NORMAL);
622 } else {
623 /* priority elevated; save value so we can restore it later */
624 LOGD_HEAP("Elevating priority from %d to %d\n",
625 priorityResult, ANDROID_PRIORITY_NORMAL);
626 oldThreadPriority = priorityResult;
627 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800628 }
629 }
630
631 /* Wait for the HeapWorker thread to block.
632 * (It may also already be suspended in interp code,
633 * in which case it's not holding heapWorkerLock.)
634 */
635 dvmLockMutex(&gDvm.heapWorkerLock);
636
637 /* Make sure that the HeapWorker thread hasn't become
638 * wedged inside interp code. If it has, this call will
639 * print a message and abort the VM.
640 */
641 dvmAssertHeapWorkerThreadRunning();
642
643 /* Lock the pendingFinalizationRefs list.
644 *
645 * Acquire the lock after suspending so the finalizer
646 * thread can't block in the RUNNING state while
647 * we try to suspend.
648 */
649 dvmLockMutex(&gDvm.heapWorkerListLock);
650
Barry Hayes962adba2010-03-17 12:12:39 -0700651 if (gDvm.preVerify) {
Carl Shapiro6c5dd932010-08-05 21:49:07 -0700652 LOGV_HEAP("Verifying roots and heap before GC");
653 verifyRootsAndHeap();
Barry Hayes962adba2010-03-17 12:12:39 -0700654 }
655
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800656 dvmMethodTraceGCBegin();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800657
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800658 /* Set up the marking context.
659 */
Carl Shapirod25566d2010-03-11 20:39:47 -0800660 if (!dvmHeapBeginMarkStep(gcMode)) {
The Android Open Source Project99409882009-03-18 22:20:24 -0700661 LOGE_HEAP("dvmHeapBeginMarkStep failed; aborting\n");
662 dvmAbort();
663 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800664
665 /* Mark the set of objects that are strongly reachable from the roots.
666 */
667 LOGD_HEAP("Marking...");
668 dvmHeapMarkRootSet();
669
670 /* dvmHeapScanMarkedObjects() will build the lists of known
671 * instances of the Reference classes.
672 */
673 gcHeap->softReferences = NULL;
674 gcHeap->weakReferences = NULL;
675 gcHeap->phantomReferences = NULL;
676
Carl Shapiroec805ea2010-06-28 16:28:26 -0700677 if (reason == GC_CONCURRENT) {
678 /*
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700679 * Resume threads while tracing from the roots. We unlock the
680 * heap to allow mutator threads to allocate from free space.
Carl Shapiroec805ea2010-06-28 16:28:26 -0700681 */
Carl Shapiro03f3b132010-07-27 17:25:31 -0700682 rootEnd = dvmGetRelativeTimeMsec();
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700683 dvmClearCardTable();
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700684 dvmUnlockHeap();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700685 dvmResumeAllThreads(SUSPEND_FOR_GC);
686 }
687
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800688 /* Recursively mark any objects that marked objects point to strongly.
689 * If we're not collecting soft references, soft-reachable
690 * objects will also be marked.
691 */
692 LOGD_HEAP("Recursing...");
693 dvmHeapScanMarkedObjects();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800694
Carl Shapiroec805ea2010-06-28 16:28:26 -0700695 if (reason == GC_CONCURRENT) {
696 /*
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700697 * Re-acquire the heap lock and perform the final thread
698 * suspension.
Carl Shapiroec805ea2010-06-28 16:28:26 -0700699 */
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700700 dvmLockHeap();
Carl Shapiro8881a802010-08-10 15:55:45 -0700701 dirtySuspend = dvmGetRelativeTimeMsec();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700702 dvmSuspendAllThreads(SUSPEND_FOR_GC);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700703 dirtyStart = dvmGetRelativeTimeMsec();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700704 /*
705 * As no barrier intercepts root updates, we conservatively
706 * assume all roots may be gray and re-mark them.
707 */
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700708 dvmHeapReMarkRootSet();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700709 /*
Carl Shapiro5ba39372010-08-06 17:07:53 -0700710 * With the exception of reference objects and weak interned
711 * strings, all gray objects should now be on dirty cards.
712 */
713 if (gDvm.verifyCardTable) {
714 dvmVerifyCardTable();
715 }
716 /*
Carl Shapiroec805ea2010-06-28 16:28:26 -0700717 * Recursively mark gray objects pointed to by the roots or by
718 * heap objects dirtied during the concurrent mark.
719 */
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700720 dvmHeapReScanMarkedObjects();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700721 }
722
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800723 /* All strongly-reachable objects have now been marked.
724 */
Carl Shapiro29540742010-03-26 15:34:39 -0700725 LOGD_HEAP("Handling soft references...");
726 if (!clearSoftRefs) {
727 dvmHandleSoftRefs(&gcHeap->softReferences);
728 }
729 dvmClearWhiteRefs(&gcHeap->softReferences);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800730
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800731 LOGD_HEAP("Handling weak references...");
Carl Shapiro29540742010-03-26 15:34:39 -0700732 dvmClearWhiteRefs(&gcHeap->weakReferences);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800733
734 /* Once all weak-reachable objects have been taken
735 * care of, any remaining unmarked objects can be finalized.
736 */
737 LOGD_HEAP("Finding finalizations...");
738 dvmHeapScheduleFinalizations();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800739
Carl Shapiro29540742010-03-26 15:34:39 -0700740 LOGD_HEAP("Handling f-reachable soft references...");
741 dvmClearWhiteRefs(&gcHeap->softReferences);
742
743 LOGD_HEAP("Handling f-reachable weak references...");
744 dvmClearWhiteRefs(&gcHeap->weakReferences);
745
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800746 /* Any remaining objects that are not pending finalization
747 * could be phantom-reachable. This will mark any phantom-reachable
748 * objects, as well as enqueue their references.
749 */
750 LOGD_HEAP("Handling phantom references...");
Carl Shapiro29540742010-03-26 15:34:39 -0700751 dvmClearWhiteRefs(&gcHeap->phantomReferences);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800752
Carl Shapiro8881a802010-08-10 15:55:45 -0700753#if defined(WITH_JIT)
754 /*
755 * Patching a chaining cell is very cheap as it only updates 4 words. It's
756 * the overhead of stopping all threads and synchronizing the I/D cache
757 * that makes it expensive.
758 *
759 * Therefore we batch those work orders in a queue and go through them
760 * when threads are suspended for GC.
761 */
762 dvmCompilerPerformSafePointChecks();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800763#endif
764
Carl Shapiro8881a802010-08-10 15:55:45 -0700765 LOGD_HEAP("Sweeping...");
766
767 dvmHeapSweepSystemWeaks();
768
769 /*
770 * Live objects have a bit set in the mark bitmap, swap the mark
771 * and live bitmaps. The sweep can proceed concurrently viewing
772 * the new live bitmap as the old mark bitmap, and vice versa.
773 */
774 dvmHeapSourceSwapBitmaps();
775
776 if (gDvm.postVerify) {
777 LOGV_HEAP("Verifying roots and heap after GC");
778 verifyRootsAndHeap();
779 }
780
781 if (reason == GC_CONCURRENT) {
782 dirtyEnd = dvmGetRelativeTimeMsec();
783 dvmUnlockHeap();
784 dvmResumeAllThreads(SUSPEND_FOR_GC);
785 }
786 dvmHeapSweepUnmarkedObjects(gcMode, reason == GC_CONCURRENT,
Carl Shapiro570942c2010-09-17 15:53:16 -0700787 &numObjectsFreed, &numBytesFreed);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800788 LOGD_HEAP("Cleaning up...");
789 dvmHeapFinishMarkStep();
Carl Shapiro8881a802010-08-10 15:55:45 -0700790 if (reason == GC_CONCURRENT) {
791 dvmLockHeap();
792 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800793
794 LOGD_HEAP("Done.");
795
796 /* Now's a good time to adjust the heap size, since
797 * we know what our utilization is.
798 *
799 * This doesn't actually resize any memory;
800 * it just lets the heap grow more when necessary.
801 */
Carl Shapirob755f9a2010-09-27 17:25:49 -0700802 if (reason != GC_EXTERNAL_ALLOC) {
803 dvmHeapSourceGrowForUtilization();
804 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800805
Carl Shapiro570942c2010-09-17 15:53:16 -0700806 currAllocated = dvmHeapSourceGetValue(HS_BYTES_ALLOCATED, NULL, 0);
807 currFootprint = dvmHeapSourceGetValue(HS_FOOTPRINT, NULL, 0);
808
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800809 /* Now that we've freed up the GC heap, return any large
810 * free chunks back to the system. They'll get paged back
811 * in the next time they're used. Don't do it immediately,
812 * though; if the process is still allocating a bunch of
813 * memory, we'll be taking a ton of page faults that we don't
814 * necessarily need to.
815 *
816 * Cancel any old scheduled trims, and schedule a new one.
817 */
818 dvmScheduleHeapSourceTrim(5); // in seconds
819
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800820 dvmMethodTraceGCEnd();
Barry Hayes962adba2010-03-17 12:12:39 -0700821 LOGV_HEAP("GC finished");
822
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800823 gcHeap->gcRunning = false;
824
Barry Hayes962adba2010-03-17 12:12:39 -0700825 LOGV_HEAP("Resuming threads");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800826 dvmUnlockMutex(&gDvm.heapWorkerListLock);
827 dvmUnlockMutex(&gDvm.heapWorkerLock);
828
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700829 if (reason == GC_CONCURRENT) {
830 /*
831 * Wake-up any threads that blocked after a failed allocation
832 * request.
833 */
834 dvmBroadcastCond(&gDvm.gcHeapCond);
835 }
836
Carl Shapiroec805ea2010-06-28 16:28:26 -0700837 if (reason != GC_CONCURRENT) {
Carl Shapiro8881a802010-08-10 15:55:45 -0700838 dirtyEnd = dvmGetRelativeTimeMsec();
839 dvmResumeAllThreads(SUSPEND_FOR_GC);
Carl Shapiroec805ea2010-06-28 16:28:26 -0700840 if (oldThreadPriority != kInvalidPriority) {
841 if (setpriority(PRIO_PROCESS, 0, oldThreadPriority) != 0) {
842 LOGW_HEAP("Unable to reset priority to %d: %s\n",
843 oldThreadPriority, strerror(errno));
844 } else {
845 LOGD_HEAP("Reset priority to %d\n", oldThreadPriority);
846 }
San Mehat256fc152009-04-21 14:03:06 -0700847
Carl Shapiroec805ea2010-06-28 16:28:26 -0700848 if (oldThreadPriority >= ANDROID_PRIORITY_BACKGROUND) {
849 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
850 }
San Mehat256fc152009-04-21 14:03:06 -0700851 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800852 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800853
Carl Shapiro570942c2010-09-17 15:53:16 -0700854 extAllocated = dvmHeapSourceGetValue(HS_EXTERNAL_BYTES_ALLOCATED, NULL, 0);
855 extLimit = dvmHeapSourceGetValue(HS_EXTERNAL_LIMIT, NULL, 0);
856 percentFree = 100 - (size_t)(100.0f * (float)currAllocated / currFootprint);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700857 if (reason != GC_CONCURRENT) {
Carl Shapiro03f3b132010-07-27 17:25:31 -0700858 u4 markSweepTime = dirtyEnd - rootStart;
Carl Shapiro570942c2010-09-17 15:53:16 -0700859 bool isSmall = numBytesFreed > 0 && numBytesFreed < 1024;
Carl Shapiro8881a802010-08-10 15:55:45 -0700860 totalTime = rootSuspendTime + markSweepTime;
Carl Shapiro71978ec2010-09-21 13:28:21 -0700861 LOGD("%s freed %s%zdK, %d%% free %zdK/%zdK, external %zdK/%zdK, "
Carl Shapiro570942c2010-09-17 15:53:16 -0700862 "paused %ums",
863 GcReasonStr[reason],
864 isSmall ? "<" : "",
865 numBytesFreed ? MAX(numBytesFreed / 1024, 1) : 0,
866 percentFree,
867 currAllocated / 1024, currFootprint / 1024,
868 extAllocated / 1024, extLimit / 1024,
869 markSweepTime);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700870 } else {
Carl Shapiro8881a802010-08-10 15:55:45 -0700871 u4 rootTime = rootEnd - rootStart;
872 u4 dirtySuspendTime = dirtyStart - dirtySuspend;
873 u4 dirtyTime = dirtyEnd - dirtyStart;
Carl Shapiro570942c2010-09-17 15:53:16 -0700874 bool isSmall = numBytesFreed > 0 && numBytesFreed < 1024;
Carl Shapiro03f3b132010-07-27 17:25:31 -0700875 totalTime = rootSuspendTime + rootTime + dirtySuspendTime + dirtyTime;
Carl Shapiro71978ec2010-09-21 13:28:21 -0700876 LOGD("%s freed %s%zdK, %d%% free %zdK/%zdK, external %zdK/%zdK, "
Carl Shapiro570942c2010-09-17 15:53:16 -0700877 "paused %ums+%ums",
878 GcReasonStr[reason],
879 isSmall ? "<" : "",
880 numBytesFreed ? MAX(numBytesFreed / 1024, 1) : 0,
881 percentFree,
882 currAllocated / 1024, currFootprint / 1024,
883 extAllocated / 1024, extLimit / 1024,
884 rootTime, dirtyTime);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700885 }
Carl Shapiro570942c2010-09-17 15:53:16 -0700886 dvmLogGcStats(numObjectsFreed, numBytesFreed, totalTime);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800887 if (gcHeap->ddmHpifWhen != 0) {
888 LOGD_HEAP("Sending VM heap info to DDM\n");
889 dvmDdmSendHeapInfo(gcHeap->ddmHpifWhen, false);
890 }
891 if (gcHeap->ddmHpsgWhen != 0) {
892 LOGD_HEAP("Dumping VM heap to DDM\n");
893 dvmDdmSendHeapSegments(false, false);
894 }
895 if (gcHeap->ddmNhsgWhen != 0) {
896 LOGD_HEAP("Dumping native heap to DDM\n");
897 dvmDdmSendHeapSegments(false, true);
898 }
899}
900
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700901void dvmWaitForConcurrentGcToComplete(void)
902{
903 Thread *self = dvmThreadSelf();
904 ThreadStatus oldStatus;
905 assert(self != NULL);
906 oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
907 dvmWaitCond(&gDvm.gcHeapCond, &gDvm.gcHeapLock);
908 dvmChangeStatus(self, oldStatus);
909}