blob: 28aff0a9aa2e9752e3e202fea8d1a4c24301895c [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"
20#include "alloc/HeapTable.h"
21#include "alloc/Heap.h"
22#include "alloc/HeapInternal.h"
23#include "alloc/DdmHeap.h"
24#include "alloc/HeapSource.h"
25#include "alloc/MarkSweep.h"
26
27#include "utils/threads.h" // need Android thread priorities
28#define kInvalidPriority 10000
29
San Mehat5a2056c2009-09-12 10:10:13 -070030#include <cutils/sched_policy.h>
31
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080032#include <sys/time.h>
33#include <sys/resource.h>
34#include <limits.h>
35#include <errno.h>
36
37#define kNonCollectableRefDefault 16
38#define kFinalizableRefDefault 128
39
Barry Hayes1b9b4e42010-01-04 10:33:46 -080040static const char* GcReasonStr[] = {
41 [GC_FOR_MALLOC] = "GC_FOR_MALLOC",
42 [GC_EXPLICIT] = "GC_EXPLICIT",
43 [GC_EXTERNAL_ALLOC] = "GC_EXTERNAL_ALLOC",
44 [GC_HPROF_DUMP_HEAP] = "GC_HPROF_DUMP_HEAP"
45};
46
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080047/*
48 * Initialize the GC heap.
49 *
50 * Returns true if successful, false otherwise.
51 */
52bool dvmHeapStartup()
53{
54 GcHeap *gcHeap;
55
56#if defined(WITH_ALLOC_LIMITS)
57 gDvm.checkAllocLimits = false;
58 gDvm.allocationLimit = -1;
59#endif
60
61 gcHeap = dvmHeapSourceStartup(gDvm.heapSizeStart, gDvm.heapSizeMax);
62 if (gcHeap == NULL) {
63 return false;
64 }
65 gcHeap->heapWorkerCurrentObject = NULL;
66 gcHeap->heapWorkerCurrentMethod = NULL;
67 gcHeap->heapWorkerInterpStartTime = 0LL;
68 gcHeap->softReferenceCollectionState = SR_COLLECT_NONE;
69 gcHeap->softReferenceHeapSizeThreshold = gDvm.heapSizeStart;
70 gcHeap->ddmHpifWhen = 0;
71 gcHeap->ddmHpsgWhen = 0;
72 gcHeap->ddmHpsgWhat = 0;
73 gcHeap->ddmNhsgWhen = 0;
74 gcHeap->ddmNhsgWhat = 0;
75#if WITH_HPROF
76 gcHeap->hprofDumpOnGc = false;
77 gcHeap->hprofContext = NULL;
78#endif
79
80 /* This needs to be set before we call dvmHeapInitHeapRefTable().
81 */
82 gDvm.gcHeap = gcHeap;
83
84 /* Set up the table we'll use for ALLOC_NO_GC.
85 */
86 if (!dvmHeapInitHeapRefTable(&gcHeap->nonCollectableRefs,
87 kNonCollectableRefDefault))
88 {
89 LOGE_HEAP("Can't allocate GC_NO_ALLOC table\n");
90 goto fail;
91 }
92
93 /* Set up the lists and lock we'll use for finalizable
94 * and reference objects.
95 */
96 dvmInitMutex(&gDvm.heapWorkerListLock);
97 gcHeap->finalizableRefs = NULL;
98 gcHeap->pendingFinalizationRefs = NULL;
99 gcHeap->referenceOperations = NULL;
100
101 /* Initialize the HeapWorker locks and other state
102 * that the GC uses.
103 */
104 dvmInitializeHeapWorkerState();
105
106 return true;
107
108fail:
Carl Shapiroa199eb72010-02-09 16:26:30 -0800109 dvmHeapSourceShutdown(&gcHeap);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800110 return false;
111}
112
Carl Shapiroc8e06c82010-02-04 19:12:55 -0800113void dvmHeapStartupAfterZygote()
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800114{
115 /* Update our idea of the last GC start time so that we
116 * don't use the last time that Zygote happened to GC.
117 */
118 gDvm.gcHeap->gcStartTime = dvmGetRelativeTimeUsec();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800119}
120
121void dvmHeapShutdown()
122{
123//TODO: make sure we're locked
124 if (gDvm.gcHeap != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800125 /* Tables are allocated on the native heap;
126 * they need to be cleaned up explicitly.
127 * The process may stick around, so we don't
128 * want to leak any native memory.
129 */
Carl Shapiroa199eb72010-02-09 16:26:30 -0800130 dvmHeapFreeHeapRefTable(&gDvm.gcHeap->nonCollectableRefs);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800131
Carl Shapiroa199eb72010-02-09 16:26:30 -0800132 dvmHeapFreeLargeTable(gDvm.gcHeap->finalizableRefs);
133 gDvm.gcHeap->finalizableRefs = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800134
Carl Shapiroa199eb72010-02-09 16:26:30 -0800135 dvmHeapFreeLargeTable(gDvm.gcHeap->pendingFinalizationRefs);
136 gDvm.gcHeap->pendingFinalizationRefs = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800137
Carl Shapiroa199eb72010-02-09 16:26:30 -0800138 dvmHeapFreeLargeTable(gDvm.gcHeap->referenceOperations);
139 gDvm.gcHeap->referenceOperations = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800140
141 /* Destroy the heap. Any outstanding pointers
142 * will point to unmapped memory (unless/until
Carl Shapiroa199eb72010-02-09 16:26:30 -0800143 * someone else maps it). This frees gDvm.gcHeap
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800144 * as a side-effect.
145 */
Carl Shapiroa199eb72010-02-09 16:26:30 -0800146 dvmHeapSourceShutdown(&gDvm.gcHeap);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800147 }
148}
149
150/*
151 * We've been asked to allocate something we can't, e.g. an array so
Andy McFadden6da743b2009-07-15 16:56:00 -0700152 * large that (length * elementWidth) is larger than 2^31.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800153 *
Andy McFadden6da743b2009-07-15 16:56:00 -0700154 * _The Java Programming Language_, 4th edition, says, "you can be sure
155 * that all SoftReferences to softly reachable objects will be cleared
156 * before an OutOfMemoryError is thrown."
157 *
158 * It's unclear whether that holds for all situations where an OOM can
159 * be thrown, or just in the context of an allocation that fails due
160 * to lack of heap space. For simplicity we just throw the exception.
161 *
162 * (OOM due to actually running out of space is handled elsewhere.)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800163 */
164void dvmThrowBadAllocException(const char* msg)
165{
Andy McFadden6da743b2009-07-15 16:56:00 -0700166 dvmThrowException("Ljava/lang/OutOfMemoryError;", msg);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800167}
168
169/*
170 * Grab the lock, but put ourselves into THREAD_VMWAIT if it looks like
171 * we're going to have to wait on the mutex.
172 */
173bool dvmLockHeap()
174{
175 if (pthread_mutex_trylock(&gDvm.gcHeapLock) != 0) {
176 Thread *self;
177 ThreadStatus oldStatus;
178 int cc;
179
180 self = dvmThreadSelf();
181 if (self != NULL) {
182 oldStatus = dvmChangeStatus(self, THREAD_VMWAIT);
183 } else {
The Android Open Source Project99409882009-03-18 22:20:24 -0700184 LOGI("ODD: waiting on heap lock, no self\n");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800185 oldStatus = -1; // shut up gcc
186 }
187
188 cc = pthread_mutex_lock(&gDvm.gcHeapLock);
189 assert(cc == 0);
190
191 if (self != NULL) {
192 dvmChangeStatus(self, oldStatus);
193 }
194 }
195
196 return true;
197}
198
199void dvmUnlockHeap()
200{
201 dvmUnlockMutex(&gDvm.gcHeapLock);
202}
203
204/* Pop an object from the list of pending finalizations and
205 * reference clears/enqueues, and return the object.
206 * The caller must call dvmReleaseTrackedAlloc()
207 * on the object when finished.
208 *
209 * Typically only called by the heap worker thread.
210 */
211Object *dvmGetNextHeapWorkerObject(HeapWorkerOperation *op)
212{
213 Object *obj;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800214 GcHeap *gcHeap = gDvm.gcHeap;
215
216 assert(op != NULL);
217
218 obj = NULL;
219
220 dvmLockMutex(&gDvm.heapWorkerListLock);
221
222 /* We must handle reference operations before finalizations.
223 * If:
224 * a) Someone subclasses WeakReference and overrides clear()
225 * b) A reference of this type is the last reference to
226 * a finalizable object
227 * then we need to guarantee that the overridden clear() is called
228 * on the reference before finalize() is called on the referent.
229 * Both of these operations will always be scheduled at the same
230 * time, so handling reference operations first will guarantee
231 * the required order.
232 */
233 obj = dvmHeapGetNextObjectFromLargeTable(&gcHeap->referenceOperations);
234 if (obj != NULL) {
235 uintptr_t workBits;
236
Barry Hayes6930a112009-12-22 11:01:38 -0800237 workBits = (uintptr_t)obj & WORKER_ENQUEUE;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800238 assert(workBits != 0);
Barry Hayes6930a112009-12-22 11:01:38 -0800239 obj = (Object *)((uintptr_t)obj & ~WORKER_ENQUEUE);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800240
241 *op = workBits;
242 } else {
243 obj = dvmHeapGetNextObjectFromLargeTable(
244 &gcHeap->pendingFinalizationRefs);
245 if (obj != NULL) {
246 *op = WORKER_FINALIZE;
247 }
248 }
249
250 if (obj != NULL) {
251 /* Don't let the GC collect the object until the
252 * worker thread is done with it.
253 *
254 * This call is safe; it uses thread-local storage
255 * and doesn't acquire any locks.
256 */
257 dvmAddTrackedAlloc(obj, NULL);
258 }
259
260 dvmUnlockMutex(&gDvm.heapWorkerListLock);
261
262 return obj;
263}
264
265/* Used for a heap size change hysteresis to avoid collecting
266 * SoftReferences when the heap only grows by a small amount.
267 */
268#define SOFT_REFERENCE_GROWTH_SLACK (128 * 1024)
269
270/* Whenever the effective heap size may have changed,
271 * this function must be called.
272 */
273void dvmHeapSizeChanged()
274{
275 GcHeap *gcHeap = gDvm.gcHeap;
276 size_t currentHeapSize;
277
278 currentHeapSize = dvmHeapSourceGetIdealFootprint();
279
280 /* See if the heap size has changed enough that we should care
281 * about it.
282 */
283 if (currentHeapSize <= gcHeap->softReferenceHeapSizeThreshold -
284 4 * SOFT_REFERENCE_GROWTH_SLACK)
285 {
286 /* The heap has shrunk enough that we'll use this as a new
287 * threshold. Since we're doing better on space, there's
288 * no need to collect any SoftReferences.
289 *
290 * This is 4x the growth hysteresis because we don't want
291 * to snap down so easily after a shrink. If we just cleared
292 * up a bunch of SoftReferences, we don't want to disallow
293 * any new ones from being created.
294 * TODO: determine if the 4x is important, needed, or even good
295 */
296 gcHeap->softReferenceHeapSizeThreshold = currentHeapSize;
297 gcHeap->softReferenceCollectionState = SR_COLLECT_NONE;
298 } else if (currentHeapSize >= gcHeap->softReferenceHeapSizeThreshold +
299 SOFT_REFERENCE_GROWTH_SLACK)
300 {
301 /* The heap has grown enough to warrant collecting SoftReferences.
302 */
303 gcHeap->softReferenceHeapSizeThreshold = currentHeapSize;
304 gcHeap->softReferenceCollectionState = SR_COLLECT_SOME;
305 }
306}
307
308
309/* Do a full garbage collection, which may grow the
310 * heap as a side-effect if the live set is large.
311 */
312static void gcForMalloc(bool collectSoftReferences)
313{
314#ifdef WITH_PROFILER
315 if (gDvm.allocProf.enabled) {
316 Thread* self = dvmThreadSelf();
317 gDvm.allocProf.gcCount++;
318 if (self != NULL) {
319 self->allocProf.gcCount++;
320 }
321 }
322#endif
323 /* This may adjust the soft limit as a side-effect.
324 */
325 LOGD_HEAP("dvmMalloc initiating GC%s\n",
326 collectSoftReferences ? "(collect SoftReferences)" : "");
Barry Hayes1b9b4e42010-01-04 10:33:46 -0800327 dvmCollectGarbageInternal(collectSoftReferences, GC_FOR_MALLOC);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800328}
329
330/* Try as hard as possible to allocate some memory.
331 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800332static void *tryMalloc(size_t size)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800333{
Carl Shapiro6343bd02010-02-16 17:40:19 -0800334 void *ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800335
336 /* Don't try too hard if there's no way the allocation is
337 * going to succeed. We have to collect SoftReferences before
338 * throwing an OOME, though.
339 */
340 if (size >= gDvm.heapSizeMax) {
341 LOGW_HEAP("dvmMalloc(%zu/0x%08zx): "
342 "someone's allocating a huge buffer\n", size, size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800343 ptr = NULL;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800344 goto collect_soft_refs;
345 }
346
347//TODO: figure out better heuristics
348// There will be a lot of churn if someone allocates a bunch of
349// big objects in a row, and we hit the frag case each time.
350// A full GC for each.
351// Maybe we grow the heap in bigger leaps
352// Maybe we skip the GC if the size is large and we did one recently
353// (number of allocations ago) (watch for thread effects)
354// DeflateTest allocs a bunch of ~128k buffers w/in 0-5 allocs of each other
355// (or, at least, there are only 0-5 objects swept each time)
356
Carl Shapiro6343bd02010-02-16 17:40:19 -0800357 ptr = dvmHeapSourceAlloc(size);
358 if (ptr != NULL) {
359 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800360 }
361
362 /* The allocation failed. Free up some space by doing
363 * a full garbage collection. This may grow the heap
364 * if the live set is sufficiently large.
365 */
366 gcForMalloc(false);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800367 ptr = dvmHeapSourceAlloc(size);
368 if (ptr != NULL) {
369 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800370 }
371
372 /* Even that didn't work; this is an exceptional state.
373 * Try harder, growing the heap if necessary.
374 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800375 ptr = dvmHeapSourceAllocAndGrow(size);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800376 dvmHeapSizeChanged();
Carl Shapiro6343bd02010-02-16 17:40:19 -0800377 if (ptr != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800378 size_t newHeapSize;
379
380 newHeapSize = dvmHeapSourceGetIdealFootprint();
381//TODO: may want to grow a little bit more so that the amount of free
382// space is equal to the old free space + the utilization slop for
383// the new allocation.
384 LOGI_HEAP("Grow heap (frag case) to "
385 "%zu.%03zuMB for %zu-byte allocation\n",
386 FRACTIONAL_MB(newHeapSize), size);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800387 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800388 }
389
390 /* Most allocations should have succeeded by now, so the heap
391 * is really full, really fragmented, or the requested size is
392 * really big. Do another GC, collecting SoftReferences this
393 * time. The VM spec requires that all SoftReferences have
394 * been collected and cleared before throwing an OOME.
395 */
396//TODO: wait for the finalizers from the previous GC to finish
397collect_soft_refs:
398 LOGI_HEAP("Forcing collection of SoftReferences for %zu-byte allocation\n",
399 size);
400 gcForMalloc(true);
Carl Shapiro6343bd02010-02-16 17:40:19 -0800401 ptr = dvmHeapSourceAllocAndGrow(size);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800402 dvmHeapSizeChanged();
Carl Shapiro6343bd02010-02-16 17:40:19 -0800403 if (ptr != NULL) {
404 return ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800405 }
406//TODO: maybe wait for finalizers and try one last time
407
408 LOGE_HEAP("Out of memory on a %zd-byte allocation.\n", size);
409//TODO: tell the HeapSource to dump its state
410 dvmDumpThread(dvmThreadSelf(), false);
411
412 return NULL;
413}
414
415/* Throw an OutOfMemoryError if there's a thread to attach it to.
416 * Avoid recursing.
417 *
418 * The caller must not be holding the heap lock, or else the allocations
419 * in dvmThrowException() will deadlock.
420 */
421static void throwOOME()
422{
423 Thread *self;
424
425 if ((self = dvmThreadSelf()) != NULL) {
426 /* If the current (failing) dvmMalloc() happened as part of thread
427 * creation/attachment before the thread became part of the root set,
428 * we can't rely on the thread-local trackedAlloc table, so
429 * we can't keep track of a real allocated OOME object. But, since
430 * the thread is in the process of being created, it won't have
431 * a useful stack anyway, so we may as well make things easier
432 * by throwing the (stackless) pre-built OOME.
433 */
434 if (dvmIsOnThreadList(self) && !self->throwingOOME) {
435 /* Let ourselves know that we tried to throw an OOM
436 * error in the normal way in case we run out of
437 * memory trying to allocate it inside dvmThrowException().
438 */
439 self->throwingOOME = true;
440
441 /* Don't include a description string;
442 * one fewer allocation.
443 */
444 dvmThrowException("Ljava/lang/OutOfMemoryError;", NULL);
445 } else {
446 /*
447 * This thread has already tried to throw an OutOfMemoryError,
448 * which probably means that we're running out of memory
449 * while recursively trying to throw.
450 *
451 * To avoid any more allocation attempts, "throw" a pre-built
452 * OutOfMemoryError object (which won't have a useful stack trace).
453 *
454 * Note that since this call can't possibly allocate anything,
455 * we don't care about the state of self->throwingOOME
456 * (which will usually already be set).
457 */
458 dvmSetException(self, gDvm.outOfMemoryObj);
459 }
460 /* We're done with the possible recursion.
461 */
462 self->throwingOOME = false;
463 }
464}
465
466/*
467 * Allocate storage on the GC heap. We guarantee 8-byte alignment.
468 *
469 * The new storage is zeroed out.
470 *
471 * Note that, in rare cases, this could get called while a GC is in
472 * progress. If a non-VM thread tries to attach itself through JNI,
473 * it will need to allocate some objects. If this becomes annoying to
474 * deal with, we can block it at the source, but holding the allocation
475 * mutex should be enough.
476 *
477 * In rare circumstances (JNI AttachCurrentThread) we can be called
478 * from a non-VM thread.
479 *
480 * We implement ALLOC_NO_GC by maintaining an internal list of objects
481 * that should not be collected. This requires no actual flag storage in
482 * the object itself, which is good, but makes flag queries expensive.
483 *
484 * Use ALLOC_DONT_TRACK when we either don't want to track an allocation
485 * (because it's being done for the interpreter "new" operation and will
486 * be part of the root set immediately) or we can't (because this allocation
487 * is for a brand new thread).
488 *
489 * Returns NULL and throws an exception on failure.
490 *
491 * TODO: don't do a GC if the debugger thinks all threads are suspended
492 */
493void* dvmMalloc(size_t size, int flags)
494{
495 GcHeap *gcHeap = gDvm.gcHeap;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800496 void *ptr;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800497
498#if 0
499 /* handy for spotting large allocations */
500 if (size >= 100000) {
501 LOGI("dvmMalloc(%d):\n", size);
502 dvmDumpThread(dvmThreadSelf(), false);
503 }
504#endif
505
506#if defined(WITH_ALLOC_LIMITS)
507 /*
508 * See if they've exceeded the allocation limit for this thread.
509 *
510 * A limit value of -1 means "no limit".
511 *
512 * This is enabled at compile time because it requires us to do a
513 * TLS lookup for the Thread pointer. This has enough of a performance
514 * impact that we don't want to do it if we don't have to. (Now that
515 * we're using gDvm.checkAllocLimits we may want to reconsider this,
516 * but it's probably still best to just compile the check out of
517 * production code -- one less thing to hit on every allocation.)
518 */
519 if (gDvm.checkAllocLimits) {
520 Thread* self = dvmThreadSelf();
521 if (self != NULL) {
522 int count = self->allocLimit;
523 if (count > 0) {
524 self->allocLimit--;
525 } else if (count == 0) {
526 /* fail! */
527 assert(!gDvm.initializing);
528 self->allocLimit = -1;
529 dvmThrowException("Ldalvik/system/AllocationLimitError;",
530 "thread allocation limit exceeded");
531 return NULL;
532 }
533 }
534 }
535
536 if (gDvm.allocationLimit >= 0) {
537 assert(!gDvm.initializing);
538 gDvm.allocationLimit = -1;
539 dvmThrowException("Ldalvik/system/AllocationLimitError;",
540 "global allocation limit exceeded");
541 return NULL;
542 }
543#endif
544
545 dvmLockHeap();
546
547 /* Try as hard as possible to allocate some memory.
548 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800549 ptr = tryMalloc(size);
550 if (ptr != NULL) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800551 /* We've got the memory.
552 */
553 if ((flags & ALLOC_FINALIZABLE) != 0) {
554 /* This object is an instance of a class that
555 * overrides finalize(). Add it to the finalizable list.
556 *
557 * Note that until DVM_OBJECT_INIT() is called on this
558 * object, its clazz will be NULL. Since the object is
559 * in this table, it will be scanned as part of the root
560 * set. scanObject() explicitly deals with the NULL clazz.
561 */
562 if (!dvmHeapAddRefToLargeTable(&gcHeap->finalizableRefs,
Carl Shapiro6343bd02010-02-16 17:40:19 -0800563 (Object *)ptr))
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800564 {
565 LOGE_HEAP("dvmMalloc(): no room for any more "
566 "finalizable objects\n");
567 dvmAbort();
568 }
569 }
570
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800571 /* The caller may not want us to collect this object.
572 * If not, throw it in the nonCollectableRefs table, which
573 * will be added to the root set when we GC.
574 *
575 * Note that until DVM_OBJECT_INIT() is called on this
576 * object, its clazz will be NULL. Since the object is
577 * in this table, it will be scanned as part of the root
578 * set. scanObject() explicitly deals with the NULL clazz.
579 */
580 if ((flags & ALLOC_NO_GC) != 0) {
581 if (!dvmHeapAddToHeapRefTable(&gcHeap->nonCollectableRefs, ptr)) {
582 LOGE_HEAP("dvmMalloc(): no room for any more "
583 "ALLOC_NO_GC objects: %zd\n",
584 dvmHeapNumHeapRefTableEntries(
585 &gcHeap->nonCollectableRefs));
586 dvmAbort();
587 }
588 }
589
590#ifdef WITH_PROFILER
591 if (gDvm.allocProf.enabled) {
592 Thread* self = dvmThreadSelf();
593 gDvm.allocProf.allocCount++;
594 gDvm.allocProf.allocSize += size;
595 if (self != NULL) {
596 self->allocProf.allocCount++;
597 self->allocProf.allocSize += size;
598 }
599 }
600#endif
601 } else {
602 /* The allocation failed.
603 */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800604
605#ifdef WITH_PROFILER
606 if (gDvm.allocProf.enabled) {
607 Thread* self = dvmThreadSelf();
608 gDvm.allocProf.failedAllocCount++;
609 gDvm.allocProf.failedAllocSize += size;
610 if (self != NULL) {
611 self->allocProf.failedAllocCount++;
612 self->allocProf.failedAllocSize += size;
613 }
614 }
615#endif
616 }
617
618 dvmUnlockHeap();
619
620 if (ptr != NULL) {
621 /*
622 * If this block is immediately GCable, and they haven't asked us not
623 * to track it, add it to the internal tracking list.
624 *
625 * If there's no "self" yet, we can't track it. Calls made before
626 * the Thread exists should use ALLOC_NO_GC.
627 */
628 if ((flags & (ALLOC_DONT_TRACK | ALLOC_NO_GC)) == 0) {
629 dvmAddTrackedAlloc(ptr, NULL);
630 }
631 } else {
Ben Chengc3b92b22010-01-26 16:46:15 -0800632 /*
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800633 * The allocation failed; throw an OutOfMemoryError.
634 */
635 throwOOME();
636 }
637
638 return ptr;
639}
640
641/*
642 * Returns true iff <obj> points to a valid allocated object.
643 */
644bool dvmIsValidObject(const Object* obj)
645{
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800646 /* Don't bother if it's NULL or not 8-byte aligned.
647 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800648 if (obj != NULL && ((uintptr_t)obj & (8-1)) == 0) {
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800649 /* Even if the heap isn't locked, this shouldn't return
650 * any false negatives. The only mutation that could
651 * be happening is allocation, which means that another
652 * thread could be in the middle of a read-modify-write
653 * to add a new bit for a new object. However, that
654 * RMW will have completed by the time any other thread
655 * could possibly see the new pointer, so there is no
656 * danger of dvmIsValidObject() being called on a valid
657 * pointer whose bit isn't set.
658 *
659 * Freeing will only happen during the sweep phase, which
660 * only happens while the heap is locked.
661 */
Carl Shapiro6343bd02010-02-16 17:40:19 -0800662 return dvmHeapSourceContains(obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800663 }
664 return false;
665}
666
667/*
668 * Clear flags that were passed into dvmMalloc() et al.
669 * e.g., ALLOC_NO_GC, ALLOC_DONT_TRACK.
670 */
671void dvmClearAllocFlags(Object *obj, int mask)
672{
673 if ((mask & ALLOC_NO_GC) != 0) {
674 dvmLockHeap();
675 if (dvmIsValidObject(obj)) {
676 if (!dvmHeapRemoveFromHeapRefTable(&gDvm.gcHeap->nonCollectableRefs,
677 obj))
678 {
679 LOGE_HEAP("dvmMalloc(): failed to remove ALLOC_NO_GC bit from "
680 "object 0x%08x\n", (uintptr_t)obj);
681 dvmAbort();
682 }
683//TODO: shrink if the table is very empty
684 }
685 dvmUnlockHeap();
686 }
687
688 if ((mask & ALLOC_DONT_TRACK) != 0) {
689 dvmReleaseTrackedAlloc(obj, NULL);
690 }
691}
692
693size_t dvmObjectSizeInHeap(const Object *obj)
694{
Carl Shapiro6343bd02010-02-16 17:40:19 -0800695 return dvmHeapSourceChunkSize(obj);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800696}
697
698/*
699 * Initiate garbage collection.
700 *
701 * NOTES:
702 * - If we don't hold gDvm.threadListLock, it's possible for a thread to
703 * be added to the thread list while we work. The thread should NOT
704 * start executing, so this is only interesting when we start chasing
705 * thread stacks. (Before we do so, grab the lock.)
706 *
707 * We are not allowed to GC when the debugger has suspended the VM, which
708 * is awkward because debugger requests can cause allocations. The easiest
709 * way to enforce this is to refuse to GC on an allocation made by the
710 * JDWP thread -- we have to expand the heap or fail.
711 */
Barry Hayes1b9b4e42010-01-04 10:33:46 -0800712void dvmCollectGarbageInternal(bool collectSoftReferences, enum GcReason reason)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800713{
714 GcHeap *gcHeap = gDvm.gcHeap;
715 Object *softReferences;
716 Object *weakReferences;
717 Object *phantomReferences;
718
719 u8 now;
720 s8 timeSinceLastGc;
721 s8 gcElapsedTime;
722 int numFreed;
723 size_t sizeFreed;
724
725#if DVM_TRACK_HEAP_MARKING
726 /* Since weak and soft references are always cleared,
727 * they don't require any marking.
728 * (Soft are lumped into strong when they aren't cleared.)
729 */
730 size_t strongMarkCount = 0;
731 size_t strongMarkSize = 0;
732 size_t finalizeMarkCount = 0;
733 size_t finalizeMarkSize = 0;
734 size_t phantomMarkCount = 0;
735 size_t phantomMarkSize = 0;
736#endif
737
738 /* The heap lock must be held.
739 */
740
741 if (gcHeap->gcRunning) {
742 LOGW_HEAP("Attempted recursive GC\n");
743 return;
744 }
745 gcHeap->gcRunning = true;
746 now = dvmGetRelativeTimeUsec();
747 if (gcHeap->gcStartTime != 0) {
748 timeSinceLastGc = (now - gcHeap->gcStartTime) / 1000;
749 } else {
750 timeSinceLastGc = 0;
751 }
752 gcHeap->gcStartTime = now;
753
Barry Hayes1b9b4e42010-01-04 10:33:46 -0800754 LOGV_HEAP("%s starting -- suspending threads\n", GcReasonStr[reason]);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800755
756 dvmSuspendAllThreads(SUSPEND_FOR_GC);
757
758 /* Get the priority (the "nice" value) of the current thread. The
759 * getpriority() call can legitimately return -1, so we have to
760 * explicitly test errno.
761 */
762 errno = 0;
763 int oldThreadPriority = kInvalidPriority;
764 int priorityResult = getpriority(PRIO_PROCESS, 0);
765 if (errno != 0) {
766 LOGI_HEAP("getpriority(self) failed: %s\n", strerror(errno));
767 } else if (priorityResult > ANDROID_PRIORITY_NORMAL) {
768 /* Current value is numerically greater than "normal", which
769 * in backward UNIX terms means lower priority.
770 */
San Mehat256fc152009-04-21 14:03:06 -0700771
San Mehat3e371e22009-06-26 08:36:16 -0700772 if (priorityResult >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -0700773 set_sched_policy(dvmGetSysThreadId(), SP_FOREGROUND);
San Mehat256fc152009-04-21 14:03:06 -0700774 }
775
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800776 if (setpriority(PRIO_PROCESS, 0, ANDROID_PRIORITY_NORMAL) != 0) {
777 LOGI_HEAP("Unable to elevate priority from %d to %d\n",
778 priorityResult, ANDROID_PRIORITY_NORMAL);
779 } else {
780 /* priority elevated; save value so we can restore it later */
781 LOGD_HEAP("Elevating priority from %d to %d\n",
782 priorityResult, ANDROID_PRIORITY_NORMAL);
783 oldThreadPriority = priorityResult;
784 }
785 }
786
787 /* Wait for the HeapWorker thread to block.
788 * (It may also already be suspended in interp code,
789 * in which case it's not holding heapWorkerLock.)
790 */
791 dvmLockMutex(&gDvm.heapWorkerLock);
792
793 /* Make sure that the HeapWorker thread hasn't become
794 * wedged inside interp code. If it has, this call will
795 * print a message and abort the VM.
796 */
797 dvmAssertHeapWorkerThreadRunning();
798
799 /* Lock the pendingFinalizationRefs list.
800 *
801 * Acquire the lock after suspending so the finalizer
802 * thread can't block in the RUNNING state while
803 * we try to suspend.
804 */
805 dvmLockMutex(&gDvm.heapWorkerListLock);
806
807#ifdef WITH_PROFILER
808 dvmMethodTraceGCBegin();
809#endif
810
811#if WITH_HPROF
812
813/* Set DUMP_HEAP_ON_DDMS_UPDATE to 1 to enable heap dumps
814 * whenever DDMS requests a heap update (HPIF chunk).
815 * The output files will appear in /data/misc, which must
816 * already exist.
817 * You must define "WITH_HPROF := true" in your buildspec.mk
818 * and recompile libdvm for this to work.
819 *
820 * To enable stack traces for each allocation, define
821 * "WITH_HPROF_STACK := true" in buildspec.mk. This option slows down
822 * allocations and also requires 8 additional bytes per object on the
823 * GC heap.
824 */
825#define DUMP_HEAP_ON_DDMS_UPDATE 0
826#if DUMP_HEAP_ON_DDMS_UPDATE
827 gcHeap->hprofDumpOnGc |= (gcHeap->ddmHpifWhen != 0);
828#endif
829
830 if (gcHeap->hprofDumpOnGc) {
831 char nameBuf[128];
832
The Android Open Source Project99409882009-03-18 22:20:24 -0700833 gcHeap->hprofResult = -1;
834
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800835 if (gcHeap->hprofFileName == NULL) {
836 /* no filename was provided; invent one */
837 sprintf(nameBuf, "/data/misc/heap-dump-tm%d-pid%d.hprof",
838 (int) time(NULL), (int) getpid());
839 gcHeap->hprofFileName = nameBuf;
840 }
Andy McFadden6bf992c2010-01-28 17:01:39 -0800841 gcHeap->hprofContext = hprofStartup(gcHeap->hprofFileName,
842 gcHeap->hprofDirectToDdms);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800843 if (gcHeap->hprofContext != NULL) {
844 hprofStartHeapDump(gcHeap->hprofContext);
845 }
846 gcHeap->hprofDumpOnGc = false;
847 gcHeap->hprofFileName = NULL;
848 }
849#endif
850
851 if (timeSinceLastGc < 10000) {
852 LOGD_HEAP("GC! (%dms since last GC)\n",
853 (int)timeSinceLastGc);
854 } else {
855 LOGD_HEAP("GC! (%d sec since last GC)\n",
856 (int)(timeSinceLastGc / 1000));
857 }
858#if DVM_TRACK_HEAP_MARKING
859 gcHeap->markCount = 0;
860 gcHeap->markSize = 0;
861#endif
862
863 /* Set up the marking context.
864 */
The Android Open Source Project99409882009-03-18 22:20:24 -0700865 if (!dvmHeapBeginMarkStep()) {
866 LOGE_HEAP("dvmHeapBeginMarkStep failed; aborting\n");
867 dvmAbort();
868 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800869
870 /* Mark the set of objects that are strongly reachable from the roots.
871 */
872 LOGD_HEAP("Marking...");
873 dvmHeapMarkRootSet();
874
875 /* dvmHeapScanMarkedObjects() will build the lists of known
876 * instances of the Reference classes.
877 */
878 gcHeap->softReferences = NULL;
879 gcHeap->weakReferences = NULL;
880 gcHeap->phantomReferences = NULL;
881
882 /* Make sure that we don't hard-mark the referents of Reference
883 * objects by default.
884 */
885 gcHeap->markAllReferents = false;
886
887 /* Don't mark SoftReferences if our caller wants us to collect them.
888 * This has to be set before calling dvmHeapScanMarkedObjects().
889 */
890 if (collectSoftReferences) {
891 gcHeap->softReferenceCollectionState = SR_COLLECT_ALL;
892 }
893
894 /* Recursively mark any objects that marked objects point to strongly.
895 * If we're not collecting soft references, soft-reachable
896 * objects will also be marked.
897 */
898 LOGD_HEAP("Recursing...");
899 dvmHeapScanMarkedObjects();
900#if DVM_TRACK_HEAP_MARKING
901 strongMarkCount = gcHeap->markCount;
902 strongMarkSize = gcHeap->markSize;
903 gcHeap->markCount = 0;
904 gcHeap->markSize = 0;
905#endif
906
907 /* Latch these so that the other calls to dvmHeapScanMarkedObjects() don't
908 * mess with them.
909 */
910 softReferences = gcHeap->softReferences;
911 weakReferences = gcHeap->weakReferences;
912 phantomReferences = gcHeap->phantomReferences;
913
914 /* All strongly-reachable objects have now been marked.
915 */
916 if (gcHeap->softReferenceCollectionState != SR_COLLECT_NONE) {
917 LOGD_HEAP("Handling soft references...");
918 dvmHeapHandleReferences(softReferences, REF_SOFT);
919 // markCount always zero
920
921 /* Now that we've tried collecting SoftReferences,
922 * fall back to not collecting them. If the heap
923 * grows, we will start collecting again.
924 */
925 gcHeap->softReferenceCollectionState = SR_COLLECT_NONE;
926 } // else dvmHeapScanMarkedObjects() already marked the soft-reachable set
927 LOGD_HEAP("Handling weak references...");
928 dvmHeapHandleReferences(weakReferences, REF_WEAK);
929 // markCount always zero
930
931 /* Once all weak-reachable objects have been taken
932 * care of, any remaining unmarked objects can be finalized.
933 */
934 LOGD_HEAP("Finding finalizations...");
935 dvmHeapScheduleFinalizations();
936#if DVM_TRACK_HEAP_MARKING
937 finalizeMarkCount = gcHeap->markCount;
938 finalizeMarkSize = gcHeap->markSize;
939 gcHeap->markCount = 0;
940 gcHeap->markSize = 0;
941#endif
942
943 /* Any remaining objects that are not pending finalization
944 * could be phantom-reachable. This will mark any phantom-reachable
945 * objects, as well as enqueue their references.
946 */
947 LOGD_HEAP("Handling phantom references...");
948 dvmHeapHandleReferences(phantomReferences, REF_PHANTOM);
949#if DVM_TRACK_HEAP_MARKING
950 phantomMarkCount = gcHeap->markCount;
951 phantomMarkSize = gcHeap->markSize;
952 gcHeap->markCount = 0;
953 gcHeap->markSize = 0;
954#endif
955
956//TODO: take care of JNI weak global references
957
958#if DVM_TRACK_HEAP_MARKING
959 LOGI_HEAP("Marked objects: %dB strong, %dB final, %dB phantom\n",
960 strongMarkSize, finalizeMarkSize, phantomMarkSize);
961#endif
962
963#ifdef WITH_DEADLOCK_PREDICTION
964 dvmDumpMonitorInfo("before sweep");
965#endif
966 LOGD_HEAP("Sweeping...");
967 dvmHeapSweepUnmarkedObjects(&numFreed, &sizeFreed);
968#ifdef WITH_DEADLOCK_PREDICTION
969 dvmDumpMonitorInfo("after sweep");
970#endif
971
972 LOGD_HEAP("Cleaning up...");
973 dvmHeapFinishMarkStep();
974
975 LOGD_HEAP("Done.");
976
977 /* Now's a good time to adjust the heap size, since
978 * we know what our utilization is.
979 *
980 * This doesn't actually resize any memory;
981 * it just lets the heap grow more when necessary.
982 */
983 dvmHeapSourceGrowForUtilization();
984 dvmHeapSizeChanged();
985
986#if WITH_HPROF
987 if (gcHeap->hprofContext != NULL) {
988 hprofFinishHeapDump(gcHeap->hprofContext);
989//TODO: write a HEAP_SUMMARY record
The Android Open Source Project99409882009-03-18 22:20:24 -0700990 if (hprofShutdown(gcHeap->hprofContext))
991 gcHeap->hprofResult = 0; /* indicate success */
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800992 gcHeap->hprofContext = NULL;
993 }
994#endif
995
996 /* Now that we've freed up the GC heap, return any large
997 * free chunks back to the system. They'll get paged back
998 * in the next time they're used. Don't do it immediately,
999 * though; if the process is still allocating a bunch of
1000 * memory, we'll be taking a ton of page faults that we don't
1001 * necessarily need to.
1002 *
1003 * Cancel any old scheduled trims, and schedule a new one.
1004 */
1005 dvmScheduleHeapSourceTrim(5); // in seconds
1006
1007#ifdef WITH_PROFILER
1008 dvmMethodTraceGCEnd();
1009#endif
1010 LOGV_HEAP("GC finished -- resuming threads\n");
1011
1012 gcHeap->gcRunning = false;
1013
1014 dvmUnlockMutex(&gDvm.heapWorkerListLock);
1015 dvmUnlockMutex(&gDvm.heapWorkerLock);
1016
Ben Chengc3b92b22010-01-26 16:46:15 -08001017#if defined(WITH_JIT)
1018 extern void dvmCompilerPerformSafePointChecks(void);
1019
1020 /*
1021 * Patching a chaining cell is very cheap as it only updates 4 words. It's
1022 * the overhead of stopping all threads and synchronizing the I/D cache
1023 * that makes it expensive.
1024 *
1025 * Therefore we batch those work orders in a queue and go through them
1026 * when threads are suspended for GC.
1027 */
1028 dvmCompilerPerformSafePointChecks();
1029#endif
1030
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001031 dvmResumeAllThreads(SUSPEND_FOR_GC);
1032 if (oldThreadPriority != kInvalidPriority) {
1033 if (setpriority(PRIO_PROCESS, 0, oldThreadPriority) != 0) {
1034 LOGW_HEAP("Unable to reset priority to %d: %s\n",
1035 oldThreadPriority, strerror(errno));
1036 } else {
1037 LOGD_HEAP("Reset priority to %d\n", oldThreadPriority);
1038 }
San Mehat256fc152009-04-21 14:03:06 -07001039
San Mehat3e371e22009-06-26 08:36:16 -07001040 if (oldThreadPriority >= ANDROID_PRIORITY_BACKGROUND) {
San Mehat5a2056c2009-09-12 10:10:13 -07001041 set_sched_policy(dvmGetSysThreadId(), SP_BACKGROUND);
San Mehat256fc152009-04-21 14:03:06 -07001042 }
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001043 }
1044 gcElapsedTime = (dvmGetRelativeTimeUsec() - gcHeap->gcStartTime) / 1000;
Barry Hayes31364132010-01-04 16:10:09 -08001045 LOGD("%s freed %d objects / %zd bytes in %dms\n",
1046 GcReasonStr[reason], numFreed, sizeFreed, (int)gcElapsedTime);
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001047 dvmLogGcStats(numFreed, sizeFreed, gcElapsedTime);
1048
1049 if (gcHeap->ddmHpifWhen != 0) {
1050 LOGD_HEAP("Sending VM heap info to DDM\n");
1051 dvmDdmSendHeapInfo(gcHeap->ddmHpifWhen, false);
1052 }
1053 if (gcHeap->ddmHpsgWhen != 0) {
1054 LOGD_HEAP("Dumping VM heap to DDM\n");
1055 dvmDdmSendHeapSegments(false, false);
1056 }
1057 if (gcHeap->ddmNhsgWhen != 0) {
1058 LOGD_HEAP("Dumping native heap to DDM\n");
1059 dvmDdmSendHeapSegments(false, true);
1060 }
1061}
1062
1063#if WITH_HPROF
1064/*
1065 * Perform garbage collection, writing heap information to the specified file.
1066 *
1067 * If "fileName" is NULL, a suitable name will be generated automatically.
The Android Open Source Project99409882009-03-18 22:20:24 -07001068 *
1069 * Returns 0 on success, or an error code on failure.
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001070 */
Andy McFadden6bf992c2010-01-28 17:01:39 -08001071int hprofDumpHeap(const char* fileName, bool directToDdms)
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001072{
The Android Open Source Project99409882009-03-18 22:20:24 -07001073 int result;
1074
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001075 dvmLockMutex(&gDvm.gcHeapLock);
1076
1077 gDvm.gcHeap->hprofDumpOnGc = true;
1078 gDvm.gcHeap->hprofFileName = fileName;
Andy McFadden6bf992c2010-01-28 17:01:39 -08001079 gDvm.gcHeap->hprofDirectToDdms = directToDdms;
Barry Hayes1b9b4e42010-01-04 10:33:46 -08001080 dvmCollectGarbageInternal(false, GC_HPROF_DUMP_HEAP);
The Android Open Source Project99409882009-03-18 22:20:24 -07001081 result = gDvm.gcHeap->hprofResult;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001082
1083 dvmUnlockMutex(&gDvm.gcHeapLock);
The Android Open Source Project99409882009-03-18 22:20:24 -07001084
1085 return result;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001086}
1087
1088void dvmHeapSetHprofGcScanState(hprof_heap_tag_t state, u4 threadSerialNumber)
1089{
1090 if (gDvm.gcHeap->hprofContext != NULL) {
1091 hprofSetGcScanState(gDvm.gcHeap->hprofContext, state,
1092 threadSerialNumber);
1093 }
1094}
1095#endif