blob: e1c0d03184962bca21356084010ea62dd89e6149 [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
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080054 gcHeap = dvmHeapSourceStartup(gDvm.heapSizeStart, gDvm.heapSizeMax);
55 if (gcHeap == NULL) {
56 return false;
57 }
58 gcHeap->heapWorkerCurrentObject = NULL;
59 gcHeap->heapWorkerCurrentMethod = NULL;
60 gcHeap->heapWorkerInterpStartTime = 0LL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080061 gcHeap->ddmHpifWhen = 0;
62 gcHeap->ddmHpsgWhen = 0;
63 gcHeap->ddmHpsgWhat = 0;
64 gcHeap->ddmNhsgWhen = 0;
65 gcHeap->ddmNhsgWhat = 0;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080066 gDvm.gcHeap = gcHeap;
67
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080068 /* Set up the lists and lock we'll use for finalizable
69 * and reference objects.
70 */
71 dvmInitMutex(&gDvm.heapWorkerListLock);
72 gcHeap->finalizableRefs = NULL;
73 gcHeap->pendingFinalizationRefs = NULL;
74 gcHeap->referenceOperations = NULL;
75
Barry Hayesb874ab92010-07-14 08:13:18 -070076 if (!dvmCardTableStartup()) {
77 LOGE_HEAP("card table startup failed.");
78 return false;
79 }
80
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080081 /* Initialize the HeapWorker locks and other state
82 * that the GC uses.
83 */
84 dvmInitializeHeapWorkerState();
85
86 return true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080087}
88
Carl Shapiroec805ea2010-06-28 16:28:26 -070089bool dvmHeapStartupAfterZygote(void)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080090{
Carl Shapiroec805ea2010-06-28 16:28:26 -070091 return dvmHeapSourceStartupAfterZygote();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080092}
93
94void dvmHeapShutdown()
95{
96//TODO: make sure we're locked
97 if (gDvm.gcHeap != NULL) {
Barry Hayesb874ab92010-07-14 08:13:18 -070098 dvmCardTableShutdown();
99 /* Tables are allocated on the native heap; they need to be
100 * cleaned up explicitly. The process may stick around, so we
101 * don't want to leak any native memory.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800102 */
Carl Shapiroa199eb72010-02-09 16:26:30 -0800103 dvmHeapFreeLargeTable(gDvm.gcHeap->finalizableRefs);
104 gDvm.gcHeap->finalizableRefs = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800105
Carl Shapiroa199eb72010-02-09 16:26:30 -0800106 dvmHeapFreeLargeTable(gDvm.gcHeap->pendingFinalizationRefs);
107 gDvm.gcHeap->pendingFinalizationRefs = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800108
Carl Shapiroa199eb72010-02-09 16:26:30 -0800109 dvmHeapFreeLargeTable(gDvm.gcHeap->referenceOperations);
110 gDvm.gcHeap->referenceOperations = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800111
Barry Hayesb874ab92010-07-14 08:13:18 -0700112 /* Destroy the heap. Any outstanding pointers will point to
113 * unmapped memory (unless/until someone else maps it). This
114 * frees gDvm.gcHeap as a side-effect.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800115 */
Carl Shapiroa199eb72010-02-09 16:26:30 -0800116 dvmHeapSourceShutdown(&gDvm.gcHeap);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800117 }
118}
119
120/*
Carl Shapiroec805ea2010-06-28 16:28:26 -0700121 * Shutdown any threads internal to the heap.
122 */
123void dvmHeapThreadShutdown(void)
124{
125 dvmHeapSourceThreadShutdown();
126}
127
128/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800129 * We've been asked to allocate something we can't, e.g. an array so
Andy McFadden6da743b2009-07-15 16:56:00 -0700130 * large that (length * elementWidth) is larger than 2^31.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800131 *
Andy McFadden6da743b2009-07-15 16:56:00 -0700132 * _The Java Programming Language_, 4th edition, says, "you can be sure
133 * that all SoftReferences to softly reachable objects will be cleared
134 * before an OutOfMemoryError is thrown."
135 *
136 * It's unclear whether that holds for all situations where an OOM can
137 * be thrown, or just in the context of an allocation that fails due
138 * to lack of heap space. For simplicity we just throw the exception.
139 *
140 * (OOM due to actually running out of space is handled elsewhere.)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800141 */
142void dvmThrowBadAllocException(const char* msg)
143{
Andy McFadden6da743b2009-07-15 16:56:00 -0700144 dvmThrowException("Ljava/lang/OutOfMemoryError;", msg);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800145}
146
147/*
148 * Grab the lock, but put ourselves into THREAD_VMWAIT if it looks like
149 * we're going to have to wait on the mutex.
150 */
151bool dvmLockHeap()
152{
Carl Shapiro980ffb02010-03-13 22:34:01 -0800153 if (dvmTryLockMutex(&gDvm.gcHeapLock) != 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800154 Thread *self;
155 ThreadStatus oldStatus;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800156
157 self = dvmThreadSelf();
Carl Shapiro5617ad32010-07-02 10:50:57 -0700158 oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
Carl Shapiro980ffb02010-03-13 22:34:01 -0800159 dvmLockMutex(&gDvm.gcHeapLock);
Carl Shapiro5617ad32010-07-02 10:50:57 -0700160 dvmChangeStatus(self, oldStatus);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800161 }
162
163 return true;
164}
165
166void dvmUnlockHeap()
167{
168 dvmUnlockMutex(&gDvm.gcHeapLock);
169}
170
171/* Pop an object from the list of pending finalizations and
172 * reference clears/enqueues, and return the object.
173 * The caller must call dvmReleaseTrackedAlloc()
174 * on the object when finished.
175 *
176 * Typically only called by the heap worker thread.
177 */
178Object *dvmGetNextHeapWorkerObject(HeapWorkerOperation *op)
179{
180 Object *obj;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800181 GcHeap *gcHeap = gDvm.gcHeap;
182
183 assert(op != NULL);
184
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800185 dvmLockMutex(&gDvm.heapWorkerListLock);
186
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800187 obj = dvmHeapGetNextObjectFromLargeTable(&gcHeap->referenceOperations);
188 if (obj != NULL) {
Carl Shapiro646ba092010-06-10 15:17:00 -0700189 *op = WORKER_ENQUEUE;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800190 } else {
191 obj = dvmHeapGetNextObjectFromLargeTable(
192 &gcHeap->pendingFinalizationRefs);
193 if (obj != NULL) {
194 *op = WORKER_FINALIZE;
195 }
196 }
197
198 if (obj != NULL) {
199 /* Don't let the GC collect the object until the
200 * worker thread is done with it.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800201 */
202 dvmAddTrackedAlloc(obj, NULL);
203 }
204
205 dvmUnlockMutex(&gDvm.heapWorkerListLock);
206
207 return obj;
208}
209
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800210/* Do a full garbage collection, which may grow the
211 * heap as a side-effect if the live set is large.
212 */
213static void gcForMalloc(bool collectSoftReferences)
214{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800215 if (gDvm.allocProf.enabled) {
216 Thread* self = dvmThreadSelf();
217 gDvm.allocProf.gcCount++;
218 if (self != NULL) {
219 self->allocProf.gcCount++;
220 }
221 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800222 /* This may adjust the soft limit as a side-effect.
223 */
224 LOGD_HEAP("dvmMalloc initiating GC%s\n",
225 collectSoftReferences ? "(collect SoftReferences)" : "");
Barry Hayes1b9b4e42010-01-04 10:33:46 -0800226 dvmCollectGarbageInternal(collectSoftReferences, GC_FOR_MALLOC);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800227}
228
229/* Try as hard as possible to allocate some memory.
230 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800231static void *tryMalloc(size_t size)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800232{
Carl Shapiro6343bd02010-02-16 17:40:19 -0800233 void *ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800234
235 /* Don't try too hard if there's no way the allocation is
236 * going to succeed. We have to collect SoftReferences before
237 * throwing an OOME, though.
238 */
239 if (size >= gDvm.heapSizeMax) {
240 LOGW_HEAP("dvmMalloc(%zu/0x%08zx): "
241 "someone's allocating a huge buffer\n", size, size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800242 ptr = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800243 goto collect_soft_refs;
244 }
245
246//TODO: figure out better heuristics
247// There will be a lot of churn if someone allocates a bunch of
248// big objects in a row, and we hit the frag case each time.
249// A full GC for each.
250// Maybe we grow the heap in bigger leaps
251// Maybe we skip the GC if the size is large and we did one recently
252// (number of allocations ago) (watch for thread effects)
253// DeflateTest allocs a bunch of ~128k buffers w/in 0-5 allocs of each other
254// (or, at least, there are only 0-5 objects swept each time)
255
Carl Shapiro6343bd02010-02-16 17:40:19 -0800256 ptr = dvmHeapSourceAlloc(size);
257 if (ptr != NULL) {
258 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800259 }
260
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700261 /*
262 * The allocation failed. If the GC is running, block until it
263 * completes and retry.
264 */
265 if (gDvm.gcHeap->gcRunning) {
266 /*
267 * The GC is concurrently tracing the heap. Release the heap
268 * lock, wait for the GC to complete, and retrying allocating.
269 */
270 dvmWaitForConcurrentGcToComplete();
271 ptr = dvmHeapSourceAlloc(size);
272 if (ptr != NULL) {
273 return ptr;
274 }
275 }
276 /*
277 * Another failure. Our thread was starved or there may be too
278 * many live objects. Try a foreground GC. This will have no
279 * effect if the concurrent GC is already running.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800280 */
281 gcForMalloc(false);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800282 ptr = dvmHeapSourceAlloc(size);
283 if (ptr != NULL) {
284 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800285 }
286
287 /* Even that didn't work; this is an exceptional state.
288 * Try harder, growing the heap if necessary.
289 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800290 ptr = dvmHeapSourceAllocAndGrow(size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800291 if (ptr != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800292 size_t newHeapSize;
293
294 newHeapSize = dvmHeapSourceGetIdealFootprint();
295//TODO: may want to grow a little bit more so that the amount of free
296// space is equal to the old free space + the utilization slop for
297// the new allocation.
298 LOGI_HEAP("Grow heap (frag case) to "
299 "%zu.%03zuMB for %zu-byte allocation\n",
300 FRACTIONAL_MB(newHeapSize), size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800301 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800302 }
303
304 /* Most allocations should have succeeded by now, so the heap
305 * is really full, really fragmented, or the requested size is
306 * really big. Do another GC, collecting SoftReferences this
307 * time. The VM spec requires that all SoftReferences have
308 * been collected and cleared before throwing an OOME.
309 */
310//TODO: wait for the finalizers from the previous GC to finish
311collect_soft_refs:
312 LOGI_HEAP("Forcing collection of SoftReferences for %zu-byte allocation\n",
313 size);
314 gcForMalloc(true);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800315 ptr = dvmHeapSourceAllocAndGrow(size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800316 if (ptr != NULL) {
317 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800318 }
319//TODO: maybe wait for finalizers and try one last time
320
321 LOGE_HEAP("Out of memory on a %zd-byte allocation.\n", size);
322//TODO: tell the HeapSource to dump its state
323 dvmDumpThread(dvmThreadSelf(), false);
324
325 return NULL;
326}
327
328/* Throw an OutOfMemoryError if there's a thread to attach it to.
329 * Avoid recursing.
330 *
331 * The caller must not be holding the heap lock, or else the allocations
332 * in dvmThrowException() will deadlock.
333 */
334static void throwOOME()
335{
336 Thread *self;
337
338 if ((self = dvmThreadSelf()) != NULL) {
339 /* If the current (failing) dvmMalloc() happened as part of thread
340 * creation/attachment before the thread became part of the root set,
341 * we can't rely on the thread-local trackedAlloc table, so
342 * we can't keep track of a real allocated OOME object. But, since
343 * the thread is in the process of being created, it won't have
344 * a useful stack anyway, so we may as well make things easier
345 * by throwing the (stackless) pre-built OOME.
346 */
347 if (dvmIsOnThreadList(self) && !self->throwingOOME) {
348 /* Let ourselves know that we tried to throw an OOM
349 * error in the normal way in case we run out of
350 * memory trying to allocate it inside dvmThrowException().
351 */
352 self->throwingOOME = true;
353
354 /* Don't include a description string;
355 * one fewer allocation.
356 */
357 dvmThrowException("Ljava/lang/OutOfMemoryError;", NULL);
358 } else {
359 /*
360 * This thread has already tried to throw an OutOfMemoryError,
361 * which probably means that we're running out of memory
362 * while recursively trying to throw.
363 *
364 * To avoid any more allocation attempts, "throw" a pre-built
365 * OutOfMemoryError object (which won't have a useful stack trace).
366 *
367 * Note that since this call can't possibly allocate anything,
368 * we don't care about the state of self->throwingOOME
369 * (which will usually already be set).
370 */
371 dvmSetException(self, gDvm.outOfMemoryObj);
372 }
373 /* We're done with the possible recursion.
374 */
375 self->throwingOOME = false;
376 }
377}
378
379/*
380 * Allocate storage on the GC heap. We guarantee 8-byte alignment.
381 *
382 * The new storage is zeroed out.
383 *
384 * Note that, in rare cases, this could get called while a GC is in
385 * progress. If a non-VM thread tries to attach itself through JNI,
386 * it will need to allocate some objects. If this becomes annoying to
387 * deal with, we can block it at the source, but holding the allocation
388 * mutex should be enough.
389 *
390 * In rare circumstances (JNI AttachCurrentThread) we can be called
391 * from a non-VM thread.
392 *
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800393 * Use ALLOC_DONT_TRACK when we either don't want to track an allocation
394 * (because it's being done for the interpreter "new" operation and will
395 * be part of the root set immediately) or we can't (because this allocation
396 * is for a brand new thread).
397 *
398 * Returns NULL and throws an exception on failure.
399 *
400 * TODO: don't do a GC if the debugger thinks all threads are suspended
401 */
402void* dvmMalloc(size_t size, int flags)
403{
404 GcHeap *gcHeap = gDvm.gcHeap;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800405 void *ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800406
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800407 dvmLockHeap();
408
409 /* Try as hard as possible to allocate some memory.
410 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800411 ptr = tryMalloc(size);
412 if (ptr != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800413 /* We've got the memory.
414 */
415 if ((flags & ALLOC_FINALIZABLE) != 0) {
416 /* This object is an instance of a class that
417 * overrides finalize(). Add it to the finalizable list.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800418 */
419 if (!dvmHeapAddRefToLargeTable(&gcHeap->finalizableRefs,
Carl Shapiro6343bd02010-02-16 17:40:19 -0800420 (Object *)ptr))
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800421 {
422 LOGE_HEAP("dvmMalloc(): no room for any more "
423 "finalizable objects\n");
424 dvmAbort();
425 }
426 }
427
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800428 if (gDvm.allocProf.enabled) {
429 Thread* self = dvmThreadSelf();
430 gDvm.allocProf.allocCount++;
431 gDvm.allocProf.allocSize += size;
432 if (self != NULL) {
433 self->allocProf.allocCount++;
434 self->allocProf.allocSize += size;
435 }
436 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800437 } else {
438 /* The allocation failed.
439 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800440
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800441 if (gDvm.allocProf.enabled) {
442 Thread* self = dvmThreadSelf();
443 gDvm.allocProf.failedAllocCount++;
444 gDvm.allocProf.failedAllocSize += size;
445 if (self != NULL) {
446 self->allocProf.failedAllocCount++;
447 self->allocProf.failedAllocSize += size;
448 }
449 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800450 }
451
452 dvmUnlockHeap();
453
454 if (ptr != NULL) {
455 /*
Barry Hayesd4f78d32010-06-08 09:34:42 -0700456 * If caller hasn't asked us not to track it, add it to the
457 * internal tracking list.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800458 */
Barry Hayesd4f78d32010-06-08 09:34:42 -0700459 if ((flags & ALLOC_DONT_TRACK) == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800460 dvmAddTrackedAlloc(ptr, NULL);
461 }
462 } else {
Ben Chengc3b92b22010-01-26 16:46:15 -0800463 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800464 * The allocation failed; throw an OutOfMemoryError.
465 */
466 throwOOME();
467 }
468
469 return ptr;
470}
471
472/*
473 * Returns true iff <obj> points to a valid allocated object.
474 */
475bool dvmIsValidObject(const Object* obj)
476{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800477 /* Don't bother if it's NULL or not 8-byte aligned.
478 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800479 if (obj != NULL && ((uintptr_t)obj & (8-1)) == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800480 /* Even if the heap isn't locked, this shouldn't return
481 * any false negatives. The only mutation that could
482 * be happening is allocation, which means that another
483 * thread could be in the middle of a read-modify-write
484 * to add a new bit for a new object. However, that
485 * RMW will have completed by the time any other thread
486 * could possibly see the new pointer, so there is no
487 * danger of dvmIsValidObject() being called on a valid
488 * pointer whose bit isn't set.
489 *
490 * Freeing will only happen during the sweep phase, which
491 * only happens while the heap is locked.
492 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800493 return dvmHeapSourceContains(obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800494 }
495 return false;
496}
497
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800498size_t dvmObjectSizeInHeap(const Object *obj)
499{
Carl Shapiro6343bd02010-02-16 17:40:19 -0800500 return dvmHeapSourceChunkSize(obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800501}
502
Carl Shapiro6c5dd932010-08-05 21:49:07 -0700503static void verifyRootsAndHeap(void)
Barry Hayes962adba2010-03-17 12:12:39 -0700504{
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700505 dvmVerifyRoots();
506 dvmVerifyBitmap(dvmHeapSourceGetLiveBits());
Barry Hayes962adba2010-03-17 12:12:39 -0700507}
508
509/*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800510 * Initiate garbage collection.
511 *
512 * NOTES:
513 * - If we don't hold gDvm.threadListLock, it's possible for a thread to
514 * be added to the thread list while we work. The thread should NOT
515 * start executing, so this is only interesting when we start chasing
516 * thread stacks. (Before we do so, grab the lock.)
517 *
518 * We are not allowed to GC when the debugger has suspended the VM, which
519 * is awkward because debugger requests can cause allocations. The easiest
520 * way to enforce this is to refuse to GC on an allocation made by the
521 * JDWP thread -- we have to expand the heap or fail.
522 */
Carl Shapiro29540742010-03-26 15:34:39 -0700523void dvmCollectGarbageInternal(bool clearSoftRefs, GcReason reason)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800524{
525 GcHeap *gcHeap = gDvm.gcHeap;
Carl Shapiro8881a802010-08-10 15:55:45 -0700526 u4 rootSuspend, rootSuspendTime, rootStart, rootEnd;
527 u4 dirtySuspend, dirtyStart, dirtyEnd;
528 u4 totalTime;
Carl Shapiro570942c2010-09-17 15:53:16 -0700529 size_t numObjectsFreed, numBytesFreed;
530 size_t currAllocated, currFootprint;
Carl Shapiro570942c2010-09-17 15:53:16 -0700531 size_t percentFree;
Carl Shapirod25566d2010-03-11 20:39:47 -0800532 GcMode gcMode;
Carl Shapiroec805ea2010-06-28 16:28:26 -0700533 int oldThreadPriority = kInvalidPriority;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800534
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800535 /* The heap lock must be held.
536 */
537
538 if (gcHeap->gcRunning) {
539 LOGW_HEAP("Attempted recursive GC\n");
540 return;
541 }
Carl Shapiro03f3b132010-07-27 17:25:31 -0700542
Carl Shapirod25566d2010-03-11 20:39:47 -0800543 gcMode = (reason == GC_FOR_MALLOC) ? GC_PARTIAL : GC_FULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800544 gcHeap->gcRunning = true;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800545
Carl Shapiro8881a802010-08-10 15:55:45 -0700546 rootSuspend = dvmGetRelativeTimeMsec();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800547 dvmSuspendAllThreads(SUSPEND_FOR_GC);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700548 rootStart = dvmGetRelativeTimeMsec();
Carl Shapiro8881a802010-08-10 15:55:45 -0700549 rootSuspendTime = rootStart - rootSuspend;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800550
Carl Shapiroec805ea2010-06-28 16:28:26 -0700551 /*
552 * If we are not marking concurrently raise the priority of the
553 * thread performing the garbage collection.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800554 */
Carl Shapiroec805ea2010-06-28 16:28:26 -0700555 if (reason != GC_CONCURRENT) {
556 /* Get the priority (the "nice" value) of the current thread. The
557 * getpriority() call can legitimately return -1, so we have to
558 * explicitly test errno.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800559 */
Carl Shapiroec805ea2010-06-28 16:28:26 -0700560 errno = 0;
561 int priorityResult = getpriority(PRIO_PROCESS, 0);
562 if (errno != 0) {
563 LOGI_HEAP("getpriority(self) failed: %s\n", strerror(errno));
564 } else if (priorityResult > ANDROID_PRIORITY_NORMAL) {
565 /* Current value is numerically greater than "normal", which
566 * in backward UNIX terms means lower priority.
567 */
San Mehat256fc152009-04-21 14:03:06 -0700568
Carl Shapiroec805ea2010-06-28 16:28:26 -0700569 if (priorityResult >= ANDROID_PRIORITY_BACKGROUND) {
570 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
571 }
San Mehat256fc152009-04-21 14:03:06 -0700572
Carl Shapiroec805ea2010-06-28 16:28:26 -0700573 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL) != 0) {
574 LOGI_HEAP("Unable to elevate priority from %d to %d\n",
575 priorityResult, ANDROID_PRIORITY_NORMAL);
576 } else {
577 /* priority elevated; save value so we can restore it later */
578 LOGD_HEAP("Elevating priority from %d to %d\n",
579 priorityResult, ANDROID_PRIORITY_NORMAL);
580 oldThreadPriority = priorityResult;
581 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800582 }
583 }
584
585 /* Wait for the HeapWorker thread to block.
586 * (It may also already be suspended in interp code,
587 * in which case it's not holding heapWorkerLock.)
588 */
589 dvmLockMutex(&gDvm.heapWorkerLock);
590
591 /* Make sure that the HeapWorker thread hasn't become
592 * wedged inside interp code. If it has, this call will
593 * print a message and abort the VM.
594 */
595 dvmAssertHeapWorkerThreadRunning();
596
597 /* Lock the pendingFinalizationRefs list.
598 *
599 * Acquire the lock after suspending so the finalizer
600 * thread can't block in the RUNNING state while
601 * we try to suspend.
602 */
603 dvmLockMutex(&gDvm.heapWorkerListLock);
604
Barry Hayes962adba2010-03-17 12:12:39 -0700605 if (gDvm.preVerify) {
Carl Shapiro6c5dd932010-08-05 21:49:07 -0700606 LOGV_HEAP("Verifying roots and heap before GC");
607 verifyRootsAndHeap();
Barry Hayes962adba2010-03-17 12:12:39 -0700608 }
609
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800610 dvmMethodTraceGCBegin();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800611
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800612 /* Set up the marking context.
613 */
Carl Shapirod25566d2010-03-11 20:39:47 -0800614 if (!dvmHeapBeginMarkStep(gcMode)) {
The Android Open Source Project99409882009-03-18 22:20:24 -0700615 LOGE_HEAP("dvmHeapBeginMarkStep failed; aborting\n");
616 dvmAbort();
617 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800618
619 /* Mark the set of objects that are strongly reachable from the roots.
620 */
621 LOGD_HEAP("Marking...");
622 dvmHeapMarkRootSet();
623
624 /* dvmHeapScanMarkedObjects() will build the lists of known
625 * instances of the Reference classes.
626 */
627 gcHeap->softReferences = NULL;
628 gcHeap->weakReferences = NULL;
629 gcHeap->phantomReferences = NULL;
630
Carl Shapiroec805ea2010-06-28 16:28:26 -0700631 if (reason == GC_CONCURRENT) {
632 /*
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700633 * Resume threads while tracing from the roots. We unlock the
634 * heap to allow mutator threads to allocate from free space.
Carl Shapiroec805ea2010-06-28 16:28:26 -0700635 */
Carl Shapiro03f3b132010-07-27 17:25:31 -0700636 rootEnd = dvmGetRelativeTimeMsec();
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700637 dvmClearCardTable();
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700638 dvmUnlockHeap();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700639 dvmResumeAllThreads(SUSPEND_FOR_GC);
640 }
641
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800642 /* Recursively mark any objects that marked objects point to strongly.
643 * If we're not collecting soft references, soft-reachable
644 * objects will also be marked.
645 */
646 LOGD_HEAP("Recursing...");
647 dvmHeapScanMarkedObjects();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800648
Carl Shapiroec805ea2010-06-28 16:28:26 -0700649 if (reason == GC_CONCURRENT) {
650 /*
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700651 * Re-acquire the heap lock and perform the final thread
652 * suspension.
Carl Shapiroec805ea2010-06-28 16:28:26 -0700653 */
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700654 dvmLockHeap();
Carl Shapiro8881a802010-08-10 15:55:45 -0700655 dirtySuspend = dvmGetRelativeTimeMsec();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700656 dvmSuspendAllThreads(SUSPEND_FOR_GC);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700657 dirtyStart = dvmGetRelativeTimeMsec();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700658 /*
659 * As no barrier intercepts root updates, we conservatively
660 * assume all roots may be gray and re-mark them.
661 */
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700662 dvmHeapReMarkRootSet();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700663 /*
Carl Shapiro5ba39372010-08-06 17:07:53 -0700664 * With the exception of reference objects and weak interned
665 * strings, all gray objects should now be on dirty cards.
666 */
667 if (gDvm.verifyCardTable) {
668 dvmVerifyCardTable();
669 }
670 /*
Carl Shapiroec805ea2010-06-28 16:28:26 -0700671 * Recursively mark gray objects pointed to by the roots or by
672 * heap objects dirtied during the concurrent mark.
673 */
Carl Shapiro106c5fd2010-07-28 14:12:27 -0700674 dvmHeapReScanMarkedObjects();
Carl Shapiroec805ea2010-06-28 16:28:26 -0700675 }
676
Carl Shapiroe8ef2b52010-12-01 19:32:05 -0800677 /*
678 * All strongly-reachable objects have now been marked. Process
679 * weakly-reachable objects discovered while tracing.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800680 */
Carl Shapiroe8ef2b52010-12-01 19:32:05 -0800681 dvmHeapProcessReferences(&gcHeap->softReferences, clearSoftRefs,
682 &gcHeap->weakReferences,
683 &gcHeap->phantomReferences);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800684
Carl Shapiro8881a802010-08-10 15:55:45 -0700685#if defined(WITH_JIT)
686 /*
687 * Patching a chaining cell is very cheap as it only updates 4 words. It's
688 * the overhead of stopping all threads and synchronizing the I/D cache
689 * that makes it expensive.
690 *
691 * Therefore we batch those work orders in a queue and go through them
692 * when threads are suspended for GC.
693 */
694 dvmCompilerPerformSafePointChecks();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800695#endif
696
Carl Shapiro8881a802010-08-10 15:55:45 -0700697 LOGD_HEAP("Sweeping...");
698
699 dvmHeapSweepSystemWeaks();
700
701 /*
702 * Live objects have a bit set in the mark bitmap, swap the mark
703 * and live bitmaps. The sweep can proceed concurrently viewing
704 * the new live bitmap as the old mark bitmap, and vice versa.
705 */
706 dvmHeapSourceSwapBitmaps();
707
708 if (gDvm.postVerify) {
709 LOGV_HEAP("Verifying roots and heap after GC");
710 verifyRootsAndHeap();
711 }
712
713 if (reason == GC_CONCURRENT) {
714 dirtyEnd = dvmGetRelativeTimeMsec();
715 dvmUnlockHeap();
716 dvmResumeAllThreads(SUSPEND_FOR_GC);
717 }
718 dvmHeapSweepUnmarkedObjects(gcMode, reason == GC_CONCURRENT,
Carl Shapiro570942c2010-09-17 15:53:16 -0700719 &numObjectsFreed, &numBytesFreed);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800720 LOGD_HEAP("Cleaning up...");
721 dvmHeapFinishMarkStep();
Carl Shapiro8881a802010-08-10 15:55:45 -0700722 if (reason == GC_CONCURRENT) {
723 dvmLockHeap();
724 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800725
726 LOGD_HEAP("Done.");
727
728 /* Now's a good time to adjust the heap size, since
729 * we know what our utilization is.
730 *
731 * This doesn't actually resize any memory;
732 * it just lets the heap grow more when necessary.
733 */
Carl Shapiroe7bdd8b2010-12-17 15:34:52 -0800734 dvmHeapSourceGrowForUtilization();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800735
Carl Shapiro570942c2010-09-17 15:53:16 -0700736 currAllocated = dvmHeapSourceGetValue(HS_BYTES_ALLOCATED, NULL, 0);
737 currFootprint = dvmHeapSourceGetValue(HS_FOOTPRINT, NULL, 0);
738
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800739 /* Now that we've freed up the GC heap, return any large
740 * free chunks back to the system. They'll get paged back
741 * in the next time they're used. Don't do it immediately,
742 * though; if the process is still allocating a bunch of
743 * memory, we'll be taking a ton of page faults that we don't
744 * necessarily need to.
745 *
746 * Cancel any old scheduled trims, and schedule a new one.
747 */
748 dvmScheduleHeapSourceTrim(5); // in seconds
749
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800750 dvmMethodTraceGCEnd();
Barry Hayes962adba2010-03-17 12:12:39 -0700751 LOGV_HEAP("GC finished");
752
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800753 gcHeap->gcRunning = false;
754
Barry Hayes962adba2010-03-17 12:12:39 -0700755 LOGV_HEAP("Resuming threads");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800756 dvmUnlockMutex(&gDvm.heapWorkerListLock);
757 dvmUnlockMutex(&gDvm.heapWorkerLock);
758
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700759 if (reason == GC_CONCURRENT) {
760 /*
761 * Wake-up any threads that blocked after a failed allocation
762 * request.
763 */
764 dvmBroadcastCond(&gDvm.gcHeapCond);
765 }
766
Carl Shapiroec805ea2010-06-28 16:28:26 -0700767 if (reason != GC_CONCURRENT) {
Carl Shapiro8881a802010-08-10 15:55:45 -0700768 dirtyEnd = dvmGetRelativeTimeMsec();
769 dvmResumeAllThreads(SUSPEND_FOR_GC);
Carl Shapiroec805ea2010-06-28 16:28:26 -0700770 if (oldThreadPriority != kInvalidPriority) {
771 if (setpriority(PRIO_PROCESS, 0, oldThreadPriority) != 0) {
772 LOGW_HEAP("Unable to reset priority to %d: %s\n",
773 oldThreadPriority, strerror(errno));
774 } else {
775 LOGD_HEAP("Reset priority to %d\n", oldThreadPriority);
776 }
San Mehat256fc152009-04-21 14:03:06 -0700777
Carl Shapiroec805ea2010-06-28 16:28:26 -0700778 if (oldThreadPriority >= ANDROID_PRIORITY_BACKGROUND) {
779 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
780 }
San Mehat256fc152009-04-21 14:03:06 -0700781 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800782 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800783
Carl Shapiro570942c2010-09-17 15:53:16 -0700784 percentFree = 100 - (size_t)(100.0f * (float)currAllocated / currFootprint);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700785 if (reason != GC_CONCURRENT) {
Carl Shapiro03f3b132010-07-27 17:25:31 -0700786 u4 markSweepTime = dirtyEnd - rootStart;
Carl Shapiro570942c2010-09-17 15:53:16 -0700787 bool isSmall = numBytesFreed > 0 && numBytesFreed < 1024;
Carl Shapiro8881a802010-08-10 15:55:45 -0700788 totalTime = rootSuspendTime + markSweepTime;
Carl Shapiroe7bdd8b2010-12-17 15:34:52 -0800789 LOGD("%s freed %s%zdK, %d%% free %zdK/%zdK, paused %ums",
Carl Shapiro570942c2010-09-17 15:53:16 -0700790 GcReasonStr[reason],
791 isSmall ? "<" : "",
792 numBytesFreed ? MAX(numBytesFreed / 1024, 1) : 0,
793 percentFree,
794 currAllocated / 1024, currFootprint / 1024,
Carl Shapiro570942c2010-09-17 15:53:16 -0700795 markSweepTime);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700796 } else {
Carl Shapiro8881a802010-08-10 15:55:45 -0700797 u4 rootTime = rootEnd - rootStart;
798 u4 dirtySuspendTime = dirtyStart - dirtySuspend;
799 u4 dirtyTime = dirtyEnd - dirtyStart;
Carl Shapiro570942c2010-09-17 15:53:16 -0700800 bool isSmall = numBytesFreed > 0 && numBytesFreed < 1024;
Carl Shapiro03f3b132010-07-27 17:25:31 -0700801 totalTime = rootSuspendTime + rootTime + dirtySuspendTime + dirtyTime;
Carl Shapiroe7bdd8b2010-12-17 15:34:52 -0800802 LOGD("%s freed %s%zdK, %d%% free %zdK/%zdK, paused %ums+%ums",
Carl Shapiro570942c2010-09-17 15:53:16 -0700803 GcReasonStr[reason],
804 isSmall ? "<" : "",
805 numBytesFreed ? MAX(numBytesFreed / 1024, 1) : 0,
806 percentFree,
807 currAllocated / 1024, currFootprint / 1024,
Carl Shapiro570942c2010-09-17 15:53:16 -0700808 rootTime, dirtyTime);
Carl Shapiro03f3b132010-07-27 17:25:31 -0700809 }
Carl Shapiro570942c2010-09-17 15:53:16 -0700810 dvmLogGcStats(numObjectsFreed, numBytesFreed, totalTime);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800811 if (gcHeap->ddmHpifWhen != 0) {
812 LOGD_HEAP("Sending VM heap info to DDM\n");
813 dvmDdmSendHeapInfo(gcHeap->ddmHpifWhen, false);
814 }
815 if (gcHeap->ddmHpsgWhen != 0) {
816 LOGD_HEAP("Dumping VM heap to DDM\n");
817 dvmDdmSendHeapSegments(false, false);
818 }
819 if (gcHeap->ddmNhsgWhen != 0) {
820 LOGD_HEAP("Dumping native heap to DDM\n");
821 dvmDdmSendHeapSegments(false, true);
822 }
823}
824
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700825void dvmWaitForConcurrentGcToComplete(void)
826{
827 Thread *self = dvmThreadSelf();
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700828 assert(self != NULL);
Carl Shapiro039167e2010-12-20 18:33:24 -0800829 while (gDvm.gcHeap->gcRunning) {
830 ThreadStatus oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
831 dvmWaitCond(&gDvm.gcHeapCond, &gDvm.gcHeapLock);
832 dvmChangeStatus(self, oldStatus);
833 }
Carl Shapiroec47e2e2010-07-01 17:44:46 -0700834}