blob: 6792a9e2d285821df7059550a8e67305c040eb37 [file] [log] [blame]
Carl Shapirod28668c2010-04-15 16:10:00 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <errno.h>
18#include <limits.h>
19#include <sys/mman.h>
20
21#include "Dalvik.h"
22#include "alloc/Heap.h"
23#include "alloc/HeapBitmap.h"
24#include "alloc/HeapInternal.h"
25#include "alloc/HeapSource.h"
26#include "alloc/Verify.h"
27#include "alloc/clz.h"
28
29/*
30 * A "mostly copying", generational, garbage collector.
31 *
32 * TODO: we allocate our own contiguous tract of page frames to back
33 * object allocations. To cooperate with other heaps active in the
34 * virtual machine we need to move the responsibility of allocating
35 * pages someplace outside of this code.
36 *
37 * The other major data structures that maintain the state of the heap
38 * are the block space table and the block queue.
39 *
40 * The block space table records the state of a block. We must track
41 * whether a block is:
42 *
43 * - Free or allocated in some space.
44 *
45 * - If the block holds part of a large object allocation, whether the
46 * block is the initial or a continued block of the allocation.
47 *
48 * - Whether the block is pinned, that is to say whether at least one
49 * object in the block must remain stationary. Only needed during a
50 * GC.
51 *
52 * - Which space the object belongs to. At present this means
53 * from-space or to-space.
54 *
55 * The block queue is used during garbage collection. Unlike Cheney's
56 * algorithm, from-space and to-space are not contiguous. Therefore,
57 * one cannot maintain the state of the copy with just two pointers.
58 * The block queue exists to thread lists of blocks from the various
59 * spaces together.
60 *
61 * Additionally, we record the free space frontier of the heap, as
62 * well as the address of the first object within a block, which is
63 * required to copy objects following a large object (not currently
64 * implemented). This is stored in the heap source structure. This
65 * should be moved elsewhere to support in-line allocations from Java
66 * threads.
67 *
68 * Allocation requests are satisfied by reserving storage from one or
69 * more contiguous blocks. Objects that are small enough to fit
70 * inside a block are packed together within a block. Objects that
71 * are larger than a block are allocated from contiguous sequences of
72 * blocks. When half the available blocks are filled, a garbage
73 * collection occurs. We "flip" spaces (exchange from- and to-space),
74 * copy live objects into to space, and perform pointer adjustment.
75 *
76 * Copying is made more complicated by the requirement that some
77 * objects must not be moved. This property is known as "pinning".
78 * These objects must be dealt with specially. We use Bartlett's
79 * scheme; blocks containing such objects are grayed (promoted) at the
Carl Shapiro952e84a2010-05-06 14:35:29 -070080 * start of a garbage collection. By virtue of this trick, tracing
Carl Shapirod28668c2010-04-15 16:10:00 -070081 * from the roots proceeds as usual but all objects on those pages are
82 * considered promoted and therefore not moved.
83 *
84 * TODO: there is sufficient information within the garbage collector
85 * to implement Attardi's scheme for evacuating unpinned objects from
86 * a page that is otherwise pinned. This would eliminate false
87 * retention caused by the large pinning granularity.
88 *
89 * We need a scheme for medium and large objects. Ignore that for
90 * now, we can return to this later.
91 *
92 * Eventually we need to worry about promoting objects out of the
93 * copy-collected heap (tenuring) into a less volatile space. Copying
94 * may not always be the best policy for such spaces. We should
95 * consider a variant of mark, sweep, compact.
96 *
97 * The block scheme allows us to use VM page faults to maintain a
98 * write barrier. Consider having a special leaf state for a page.
99 *
100 * Bibliography:
101 *
102 * C. J. Cheney. 1970. A non-recursive list compacting
103 * algorithm. CACM. 13-11 pp677--678.
104 *
105 * Joel F. Bartlett. 1988. Compacting Garbage Collection with
106 * Ambiguous Roots. Digital Equipment Corporation.
107 *
108 * Joel F. Bartlett. 1989. Mostly-Copying Garbage Collection Picks Up
109 * Generations and C++. Digital Equipment Corporation.
110 *
111 * G. May Yip. 1991. Incremental, Generational Mostly-Copying Garbage
112 * Collection in Uncooperative Environments. Digital Equipment
113 * Corporation.
114 *
115 * Giuseppe Attardi, Tito Flagella. 1994. A Customisable Memory
116 * Management Framework. TR-94-010
117 *
118 * Giuseppe Attardi, Tito Flagella, Pietro Iglio. 1998. A customisable
119 * memory management framework for C++. Software -- Practice and
120 * Experience. 28(11), 1143-1183.
121 *
122 */
123
124#define ARRAYSIZE(x) (sizeof(x) / sizeof(x[0]))
125
Carl Shapiro8bb533e2010-05-06 15:35:27 -0700126#if 0
Carl Shapirod28668c2010-04-15 16:10:00 -0700127#define LOG_ALLOC LOGI
Carl Shapiro8bb533e2010-05-06 15:35:27 -0700128#define LOG_PIN LOGI
129#define LOG_PROM LOGI
130#define LOG_REF LOGI
131#define LOG_SCAV LOGI
132#define LOG_TRAN LOGI
133#define LOG_VER LOGI
Carl Shapirod28668c2010-04-15 16:10:00 -0700134#else
Carl Shapiro8bb533e2010-05-06 15:35:27 -0700135#define LOG_ALLOC(...) ((void)0)
136#define LOG_PIN(...) ((void)0)
137#define LOG_PROM(...) ((void)0)
138#define LOG_REF(...) ((void)0)
139#define LOG_SCAV(...) ((void)0)
140#define LOG_TRAN(...) ((void)0)
141#define LOG_VER(...) ((void)0)
Carl Shapirod28668c2010-04-15 16:10:00 -0700142#endif
143
144static void enqueueBlock(HeapSource *heapSource, size_t block);
Carl Shapiro2396fda2010-05-03 20:14:14 -0700145static void scavengeReference(Object **obj);
Carl Shapirod28668c2010-04-15 16:10:00 -0700146static void verifyReference(const void *obj);
147static void printHeapBitmap(const HeapBitmap *bitmap);
148static void printHeapBitmapSxS(const HeapBitmap *b1, const HeapBitmap *b2);
Carl Shapiro952e84a2010-05-06 14:35:29 -0700149static bool toSpaceContains(const void *addr);
150static bool fromSpaceContains(const void *addr);
Carl Shapirod28668c2010-04-15 16:10:00 -0700151static size_t sumHeapBitmap(const HeapBitmap *bitmap);
Carl Shapiro2396fda2010-05-03 20:14:14 -0700152static size_t objectSize(const Object *obj);
Carl Shapiro952e84a2010-05-06 14:35:29 -0700153static void scavengeDataObject(Object *obj);
154static void scavengeBlockQueue(void);
Carl Shapirod28668c2010-04-15 16:10:00 -0700155
156/*
157 * We use 512-byte blocks.
158 */
159enum { BLOCK_SHIFT = 9 };
160enum { BLOCK_SIZE = 1 << BLOCK_SHIFT };
161
162/*
163 * Space identifiers, stored into the blockSpace array.
164 */
165enum {
166 BLOCK_FREE = 0,
167 BLOCK_FROM_SPACE = 1,
168 BLOCK_TO_SPACE = 2,
169 BLOCK_CONTINUED = 7
170};
171
172/*
173 * Alignment for all allocations, in bytes.
174 */
175enum { ALLOC_ALIGNMENT = 8 };
176
177/*
178 * Sentinel value for the queue end.
179 */
180#define QUEUE_TAIL (~(size_t)0)
181
182struct HeapSource {
183
184 /* The base address of backing store. */
185 u1 *blockBase;
186
187 /* Total number of blocks available for allocation. */
188 size_t totalBlocks;
189 size_t allocBlocks;
190
191 /*
192 * The scavenger work queue. Implemented as an array of index
193 * values into the queue.
194 */
195 size_t *blockQueue;
196
197 /*
198 * Base and limit blocks. Basically the shifted start address of
199 * the block. We convert blocks to a relative number when
200 * indexing in the block queue. TODO: make the block queue base
201 * relative rather than the index into the block queue.
202 */
203 size_t baseBlock, limitBlock;
204
205 size_t queueHead;
206 size_t queueTail;
207 size_t queueSize;
208
209 /* The space of the current block 0 (free), 1 or 2. */
210 char *blockSpace;
211
212 /* Start of free space in the current block. */
213 u1 *allocPtr;
214 /* Exclusive limit of free space in the current block. */
215 u1 *allocLimit;
216
217 HeapBitmap allocBits;
218
219 /*
Carl Shapirod28668c2010-04-15 16:10:00 -0700220 * The starting size of the heap. This value is the same as the
221 * value provided to the -Xms flag.
222 */
223 size_t minimumSize;
224
225 /*
226 * The maximum size of the heap. This value is the same as the
227 * -Xmx flag.
228 */
229 size_t maximumSize;
230
231 /*
232 * The current, committed size of the heap. At present, this is
233 * equivalent to the maximumSize.
234 */
235 size_t currentSize;
236
237 size_t bytesAllocated;
238};
239
240static unsigned long alignDown(unsigned long x, unsigned long n)
241{
242 return x & -n;
243}
244
245static unsigned long alignUp(unsigned long x, unsigned long n)
246{
247 return alignDown(x + (n - 1), n);
248}
249
250static void describeBlocks(const HeapSource *heapSource)
251{
252 size_t i;
253
254 for (i = 0; i < heapSource->totalBlocks; ++i) {
255 if ((i % 32) == 0) putchar('\n');
256 printf("%d ", heapSource->blockSpace[i]);
257 }
258 putchar('\n');
259}
260
261/*
262 * Virtual memory interface.
263 */
264
265static void *virtualAlloc(size_t length)
266{
267 void *addr;
268 int flags, prot;
269
270 flags = MAP_PRIVATE | MAP_ANONYMOUS;
271 prot = PROT_READ | PROT_WRITE;
272 addr = mmap(NULL, length, prot, flags, -1, 0);
273 if (addr == MAP_FAILED) {
274 LOGE_HEAP("mmap: %s", strerror(errno));
275 addr = NULL;
276 }
277 return addr;
278}
279
280static void virtualFree(void *addr, size_t length)
281{
282 int res;
283
284 assert(addr != NULL);
285 assert((uintptr_t)addr % SYSTEM_PAGE_SIZE == 0);
286 res = munmap(addr, length);
287 if (res == -1) {
288 LOGE_HEAP("munmap: %s", strerror(errno));
289 }
290}
291
292static int isValidAddress(const HeapSource *heapSource, const u1 *addr)
293{
294 size_t block;
295
296 block = (uintptr_t)addr >> BLOCK_SHIFT;
297 return heapSource->baseBlock <= block &&
298 heapSource->limitBlock > block;
299}
300
301/*
302 * Iterate over the block map looking for a contiguous run of free
303 * blocks.
304 */
305static void *allocateBlocks(HeapSource *heapSource, size_t blocks)
306{
307 void *addr;
308 size_t allocBlocks, totalBlocks;
309 size_t i, j;
310
311 allocBlocks = heapSource->allocBlocks;
312 totalBlocks = heapSource->totalBlocks;
313 /* Check underflow. */
314 assert(blocks != 0);
315 /* Check overflow. */
316 if (allocBlocks + blocks > totalBlocks / 2) {
317 return NULL;
318 }
319 /* Scan block map. */
320 for (i = 0; i < totalBlocks; ++i) {
321 /* Check fit. */
322 for (j = 0; j < blocks; ++j) { /* runs over totalBlocks */
323 if (heapSource->blockSpace[i+j] != BLOCK_FREE) {
324 break;
325 }
326 }
327 /* No fit? */
328 if (j != blocks) {
329 i += j;
330 continue;
331 }
332 /* Fit, allocate. */
333 heapSource->blockSpace[i] = BLOCK_TO_SPACE; /* why to-space? */
334 for (j = 1; j < blocks; ++j) {
335 heapSource->blockSpace[i+j] = BLOCK_CONTINUED;
336 }
337 heapSource->allocBlocks += blocks;
338 addr = &heapSource->blockBase[i*BLOCK_SIZE];
339 memset(addr, 0, blocks*BLOCK_SIZE);
340 /* Collecting? */
341 if (heapSource->queueHead != QUEUE_TAIL) {
342 LOG_ALLOC("allocateBlocks allocBlocks=%zu,block#=%zu", heapSource->allocBlocks, i);
343 /*
344 * This allocated was on behalf of the transporter when it
345 * shaded a white object gray. We enqueue the block so
346 * the scavenger can further shade the gray objects black.
347 */
348 enqueueBlock(heapSource, i);
349 }
350
351 return addr;
352 }
353 /* Insufficient space, fail. */
354 LOGE("Insufficient space, %zu blocks, %zu blocks allocated and %zu bytes allocated",
355 heapSource->totalBlocks,
356 heapSource->allocBlocks,
357 heapSource->bytesAllocated);
358 return NULL;
359}
360
361/* Converts an absolute address to a relative block number. */
362static size_t addressToBlock(const HeapSource *heapSource, const void *addr)
363{
364 assert(heapSource != NULL);
365 assert(isValidAddress(heapSource, addr));
366 return (((uintptr_t)addr) >> BLOCK_SHIFT) - heapSource->baseBlock;
367}
368
369/* Converts a relative block number to an absolute address. */
370static u1 *blockToAddress(const HeapSource *heapSource, size_t block)
371{
372 u1 *addr;
373
374 addr = (u1 *) (((uintptr_t) heapSource->baseBlock + block) * BLOCK_SIZE);
375 assert(isValidAddress(heapSource, addr));
376 return addr;
377}
378
379static void clearBlock(HeapSource *heapSource, size_t block)
380{
381 u1 *addr;
382 size_t i;
383
384 assert(heapSource != NULL);
385 assert(block < heapSource->totalBlocks);
386 addr = heapSource->blockBase + block*BLOCK_SIZE;
387 memset(addr, 0xCC, BLOCK_SIZE);
388 for (i = 0; i < BLOCK_SIZE; i += 8) {
389 dvmHeapBitmapClearObjectBit(&heapSource->allocBits, addr + i);
390 }
391}
392
393static void clearFromSpace(HeapSource *heapSource)
394{
395 size_t i, count;
396
397 assert(heapSource != NULL);
398 i = count = 0;
399 while (i < heapSource->totalBlocks) {
400 if (heapSource->blockSpace[i] != BLOCK_FROM_SPACE) {
401 ++i;
402 continue;
403 }
404 heapSource->blockSpace[i] = BLOCK_FREE;
405 clearBlock(heapSource, i);
406 ++i;
407 ++count;
408 while (i < heapSource->totalBlocks &&
409 heapSource->blockSpace[i] == BLOCK_CONTINUED) {
410 heapSource->blockSpace[i] = BLOCK_FREE;
411 clearBlock(heapSource, i);
412 ++i;
413 ++count;
414 }
415 }
Carl Shapiro8bb533e2010-05-06 15:35:27 -0700416 LOG_SCAV("freed %zu blocks (%zu bytes)", count, count*BLOCK_SIZE);
Carl Shapirod28668c2010-04-15 16:10:00 -0700417}
418
419/*
420 * Appends the given block to the block queue. The block queue is
421 * processed in-order by the scavenger.
422 */
423static void enqueueBlock(HeapSource *heapSource, size_t block)
424{
425 assert(heapSource != NULL);
426 assert(block < heapSource->totalBlocks);
427 if (heapSource->queueHead != QUEUE_TAIL) {
428 heapSource->blockQueue[heapSource->queueTail] = block;
429 } else {
430 heapSource->queueHead = block;
431 }
432 heapSource->blockQueue[block] = QUEUE_TAIL;
433 heapSource->queueTail = block;
434 ++heapSource->queueSize;
435}
436
437/*
438 * Grays all objects within the block corresponding to the given
439 * address.
440 */
441static void promoteBlockByAddr(HeapSource *heapSource, const void *addr)
442{
443 size_t block;
444
445 block = addressToBlock(heapSource, (const u1 *)addr);
446 if (heapSource->blockSpace[block] != BLOCK_TO_SPACE) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -0700447 // LOG_PROM("promoting block %zu %d @ %p", block, heapSource->blockSpace[block], obj);
Carl Shapirod28668c2010-04-15 16:10:00 -0700448 heapSource->blockSpace[block] = BLOCK_TO_SPACE;
449 enqueueBlock(heapSource, block);
450 /* TODO(cshapiro): count continued blocks?*/
451 heapSource->allocBlocks += 1;
452 } else {
Carl Shapiro8bb533e2010-05-06 15:35:27 -0700453 // LOG_PROM("NOT promoting block %zu %d @ %p", block, heapSource->blockSpace[block], obj);
Carl Shapirod28668c2010-04-15 16:10:00 -0700454 }
455}
456
457GcHeap *dvmHeapSourceStartup(size_t startSize, size_t absoluteMaxSize)
458{
459 GcHeap* gcHeap;
460 HeapSource *heapSource;
461
462 assert(startSize <= absoluteMaxSize);
463
464 heapSource = malloc(sizeof(*heapSource));
465 assert(heapSource != NULL);
466 memset(heapSource, 0, sizeof(*heapSource));
467
468 heapSource->minimumSize = alignUp(startSize, BLOCK_SIZE);
469 heapSource->maximumSize = alignUp(absoluteMaxSize, BLOCK_SIZE);
470
471 heapSource->currentSize = heapSource->maximumSize;
472
473 /* Allocate underlying storage for blocks. */
474 heapSource->blockBase = virtualAlloc(heapSource->maximumSize);
475 assert(heapSource->blockBase != NULL);
476 heapSource->baseBlock = (uintptr_t) heapSource->blockBase >> BLOCK_SHIFT;
477 heapSource->limitBlock = ((uintptr_t) heapSource->blockBase + heapSource->maximumSize) >> BLOCK_SHIFT;
478
479 heapSource->allocBlocks = 0;
480 heapSource->totalBlocks = (heapSource->limitBlock - heapSource->baseBlock);
481
482 assert(heapSource->totalBlocks = heapSource->maximumSize / BLOCK_SIZE);
483
484 {
485 size_t size = sizeof(heapSource->blockQueue[0]);
486 heapSource->blockQueue = malloc(heapSource->totalBlocks*size);
487 assert(heapSource->blockQueue != NULL);
488 memset(heapSource->blockQueue, 0xCC, heapSource->totalBlocks*size);
489 heapSource->queueHead = QUEUE_TAIL;
490 }
491
492 /* Byte indicating space residence or free status of block. */
493 {
494 size_t size = sizeof(heapSource->blockSpace[0]);
495 heapSource->blockSpace = malloc(heapSource->totalBlocks*size);
496 assert(heapSource->blockSpace != NULL);
497 memset(heapSource->blockSpace, 0, heapSource->totalBlocks*size);
498 }
499
500 dvmHeapBitmapInit(&heapSource->allocBits,
501 heapSource->blockBase,
502 heapSource->maximumSize,
503 "blockBase");
504
505 /* Initialize allocation pointers. */
506 heapSource->allocPtr = allocateBlocks(heapSource, 1);
507 heapSource->allocLimit = heapSource->allocPtr + BLOCK_SIZE;
508
509 gcHeap = malloc(sizeof(*gcHeap));
510 assert(gcHeap != NULL);
511 memset(gcHeap, 0, sizeof(*gcHeap));
512 gcHeap->heapSource = heapSource;
513
514 return gcHeap;
515}
516
517/*
518 * Perform any required heap initializations after forking from the
519 * zygote process. This is a no-op for the time being. Eventually
520 * this will demarcate the shared region of the heap.
521 */
522bool dvmHeapSourceStartupAfterZygote(void)
523{
524 return true;
525}
526
527bool dvmHeapSourceStartupBeforeFork(void)
528{
529 assert(!"implemented");
530 return false;
531}
532
533void dvmHeapSourceShutdown(GcHeap **gcHeap)
534{
535 if (*gcHeap == NULL || (*gcHeap)->heapSource == NULL)
536 return;
537 virtualFree((*gcHeap)->heapSource->blockBase,
538 (*gcHeap)->heapSource->maximumSize);
539 free((*gcHeap)->heapSource);
540 (*gcHeap)->heapSource = NULL;
541 free(*gcHeap);
542 *gcHeap = NULL;
543}
544
545size_t dvmHeapSourceGetValue(enum HeapSourceValueSpec spec,
546 size_t perHeapStats[],
547 size_t arrayLen)
548{
549 HeapSource *heapSource;
550 size_t value;
551
552 heapSource = gDvm.gcHeap->heapSource;
553 switch (spec) {
554 case HS_EXTERNAL_BYTES_ALLOCATED:
555 value = 0;
556 break;
557 case HS_EXTERNAL_LIMIT:
558 value = 0;
559 break;
560 case HS_FOOTPRINT:
561 value = heapSource->maximumSize;
562 break;
563 case HS_ALLOWED_FOOTPRINT:
564 value = heapSource->maximumSize;
565 break;
566 case HS_BYTES_ALLOCATED:
567 value = heapSource->bytesAllocated;
568 break;
569 case HS_OBJECTS_ALLOCATED:
570 value = sumHeapBitmap(&heapSource->allocBits);
571 break;
572 default:
573 assert(!"implemented");
574 value = 0;
575 }
576 if (perHeapStats) {
577 *perHeapStats = value;
578 }
579 return value;
580}
581
582/*
583 * Performs a shallow copy of the allocation bitmap into the given
584 * vector of heap bitmaps.
585 */
586void dvmHeapSourceGetObjectBitmaps(HeapBitmap objBits[], HeapBitmap markBits[],
587 size_t numHeaps)
588{
589 assert(!"implemented");
590}
591
592HeapBitmap *dvmHeapSourceGetLiveBits(void)
593{
594 assert(!"implemented");
595 return NULL;
596}
597
598/*
599 * Allocate the specified number of bytes from the heap. The
600 * allocation cursor points into a block of free storage. If the
601 * given allocation fits in the remaining space of the block, we
602 * advance the cursor and return a pointer to the free storage. If
603 * the allocation cannot fit in the current block but is smaller than
604 * a block we request a new block and allocate from it instead. If
605 * the allocation is larger than a block we must allocate from a span
606 * of contiguous blocks.
607 */
608void *dvmHeapSourceAlloc(size_t length)
609{
610 HeapSource *heapSource;
611 unsigned char *addr;
612 size_t aligned, available, blocks;
613
614 heapSource = gDvm.gcHeap->heapSource;
615 assert(heapSource != NULL);
616 assert(heapSource->allocPtr != NULL);
617 assert(heapSource->allocLimit != NULL);
618
619 aligned = alignUp(length, ALLOC_ALIGNMENT);
620 available = heapSource->allocLimit - heapSource->allocPtr;
621
622 /* Try allocating inside the current block. */
623 if (aligned <= available) {
624 addr = heapSource->allocPtr;
625 heapSource->allocPtr += aligned;
626 heapSource->bytesAllocated += aligned;
627 dvmHeapBitmapSetObjectBit(&heapSource->allocBits, addr);
628 return addr;
629 }
630
631 /* Try allocating in a new block. */
632 if (aligned <= BLOCK_SIZE) {
633 addr = allocateBlocks(heapSource, 1);
634 if (addr != NULL) {
635 heapSource->allocLimit = addr + BLOCK_SIZE;
636 heapSource->allocPtr = addr + aligned;
637 heapSource->bytesAllocated += aligned;
638 dvmHeapBitmapSetObjectBit(&heapSource->allocBits, addr);
639 /* TODO(cshapiro): pad out the current block. */
640 }
641 return addr;
642 }
643
644 /* Try allocating in a span of blocks. */
645 blocks = alignUp(aligned, BLOCK_SIZE) / BLOCK_SIZE;
646
647 addr = allocateBlocks(heapSource, blocks);
648 /* Propagate failure upward. */
649 if (addr != NULL) {
650 heapSource->bytesAllocated += aligned;
651 dvmHeapBitmapSetObjectBit(&heapSource->allocBits, addr);
652 /* TODO(cshapiro): pad out free space in the last block. */
653 }
654 return addr;
655}
656
657void *dvmHeapSourceAllocAndGrow(size_t size)
658{
659 return dvmHeapSourceAlloc(size);
660}
661
662/* TODO: refactor along with dvmHeapSourceAlloc */
663void *allocateGray(size_t size)
664{
Carl Shapiro952e84a2010-05-06 14:35:29 -0700665 /* TODO: add a check that we are in a GC. */
666 /* assert(gDvm.gcHeap->heapSource->queueHead != QUEUE_TAIL); */
Carl Shapirod28668c2010-04-15 16:10:00 -0700667 return dvmHeapSourceAlloc(size);
668}
669
670/*
671 * Returns true if the given address is within the heap and points to
672 * the header of a live object.
673 */
674bool dvmHeapSourceContains(const void *addr)
675{
676 HeapSource *heapSource;
677 HeapBitmap *bitmap;
678
679 heapSource = gDvm.gcHeap->heapSource;
680 bitmap = &heapSource->allocBits;
Carl Shapirodc1e4f12010-05-01 22:27:56 -0700681 if (!dvmHeapBitmapCoversAddress(bitmap, addr)) {
682 return false;
683 } else {
684 return dvmHeapBitmapIsObjectBitSet(bitmap, addr);
685 }
Carl Shapirod28668c2010-04-15 16:10:00 -0700686}
687
688bool dvmHeapSourceGetPtrFlag(const void *ptr, enum HeapSourcePtrFlag flag)
689{
690 assert(!"implemented");
691 return false;
692}
693
694size_t dvmHeapSourceChunkSize(const void *ptr)
695{
696 assert(!"implemented");
697 return 0;
698}
699
700size_t dvmHeapSourceFootprint(void)
701{
702 assert(!"implemented");
703 return 0;
704}
705
706/*
707 * Returns the "ideal footprint" which appears to be the number of
708 * bytes currently committed to the heap. This starts out at the
709 * start size of the heap and grows toward the maximum size.
710 */
711size_t dvmHeapSourceGetIdealFootprint(void)
712{
713 return gDvm.gcHeap->heapSource->currentSize;
714}
715
716float dvmGetTargetHeapUtilization(void)
717{
718 assert(!"implemented");
719 return 0.0f;
720}
721
722void dvmSetTargetHeapUtilization(float newTarget)
723{
724 assert(!"implemented");
725}
726
727size_t dvmMinimumHeapSize(size_t size, bool set)
728{
729 return gDvm.gcHeap->heapSource->minimumSize;
730}
731
732/*
733 * Expands the size of the heap after a collection. At present we
734 * commit the pages for maximum size of the heap so this routine is
735 * just a no-op. Eventually, we will either allocate or commit pages
736 * on an as-need basis.
737 */
738void dvmHeapSourceGrowForUtilization(void)
739{
740 /* do nothing */
741}
742
743void dvmHeapSourceTrim(size_t bytesTrimmed[], size_t arrayLen)
744{
745 /* do nothing */
746}
747
748void dvmHeapSourceWalk(void (*callback)(const void *chunkptr, size_t chunklen,
749 const void *userptr, size_t userlen,
750 void *arg),
751 void *arg)
752{
753 assert(!"implemented");
754}
755
756size_t dvmHeapSourceGetNumHeaps(void)
757{
758 return 1;
759}
760
761bool dvmTrackExternalAllocation(size_t n)
762{
763 assert(!"implemented");
764 return false;
765}
766
767void dvmTrackExternalFree(size_t n)
768{
769 assert(!"implemented");
770}
771
772size_t dvmGetExternalBytesAllocated(void)
773{
774 assert(!"implemented");
775 return 0;
776}
777
778void dvmHeapSourceFlip(void)
779{
780 HeapSource *heapSource;
781 size_t i;
782
783 heapSource = gDvm.gcHeap->heapSource;
784
785 /* Reset the block queue. */
786 heapSource->allocBlocks = 0;
787 heapSource->queueSize = 0;
788 heapSource->queueHead = QUEUE_TAIL;
789
Carl Shapirod28668c2010-04-15 16:10:00 -0700790 /* TODO(cshapiro): pad the current (prev) block. */
791
792 heapSource->allocPtr = NULL;
793 heapSource->allocLimit = NULL;
794
795 /* Whiten all allocated blocks. */
796 for (i = 0; i < heapSource->totalBlocks; ++i) {
797 if (heapSource->blockSpace[i] == BLOCK_TO_SPACE) {
798 heapSource->blockSpace[i] = BLOCK_FROM_SPACE;
799 }
800 }
801}
802
803static void room(size_t *alloc, size_t *avail, size_t *total)
804{
805 HeapSource *heapSource;
806 size_t i;
807
808 heapSource = gDvm.gcHeap->heapSource;
809 *total = heapSource->totalBlocks*BLOCK_SIZE;
810 *alloc = heapSource->allocBlocks*BLOCK_SIZE;
811 *avail = *total - *alloc;
812}
813
814static bool isSpaceInternal(u1 *addr, int space)
815{
816 HeapSource *heapSource;
817 u1 *base, *limit;
818 size_t offset;
819 char space2;
820
821 heapSource = gDvm.gcHeap->heapSource;
822 base = heapSource->blockBase;
823 assert(addr >= base);
824 limit = heapSource->blockBase + heapSource->maximumSize;
825 assert(addr < limit);
826 offset = addr - base;
827 space2 = heapSource->blockSpace[offset >> BLOCK_SHIFT];
828 return space == space2;
829}
830
Carl Shapiro952e84a2010-05-06 14:35:29 -0700831static bool fromSpaceContains(const void *addr)
Carl Shapirod28668c2010-04-15 16:10:00 -0700832{
833 return isSpaceInternal((u1 *)addr, BLOCK_FROM_SPACE);
834}
835
Carl Shapiro952e84a2010-05-06 14:35:29 -0700836static bool toSpaceContains(const void *addr)
Carl Shapirod28668c2010-04-15 16:10:00 -0700837{
838 return isSpaceInternal((u1 *)addr, BLOCK_TO_SPACE);
839}
840
841/*
842 * Notifies the collector that the object at the given address must
843 * remain stationary during the current collection.
844 */
845static void pinObject(const Object *obj)
846{
847 promoteBlockByAddr(gDvm.gcHeap->heapSource, obj);
848}
849
850static void printHeapBitmap(const HeapBitmap *bitmap)
851{
852 const char *cp;
853 size_t i, length;
854
855 length = bitmap->bitsLen >> 2;
856 fprintf(stderr, "%p", bitmap->bits);
857 for (i = 0; i < length; ++i) {
858 fprintf(stderr, " %lx", bitmap->bits[i]);
859 fputc('\n', stderr);
860 }
861}
862
863static void printHeapBitmapSxS(const HeapBitmap *b1, const HeapBitmap *b2)
864{
865 uintptr_t addr;
866 size_t i, length;
867
868 assert(b1->base == b2->base);
869 assert(b1->bitsLen == b2->bitsLen);
870 addr = b1->base;
871 length = b1->bitsLen >> 2;
872 for (i = 0; i < length; ++i) {
873 int diff = b1->bits[i] == b2->bits[i];
874 fprintf(stderr, "%08x %08lx %08lx %d\n",
875 addr, b1->bits[i], b2->bits[i], diff);
876 addr += sizeof(*b1->bits)*CHAR_BIT;
877 }
878}
879
880static size_t sumHeapBitmap(const HeapBitmap *bitmap)
881{
882 const char *cp;
883 size_t i, sum;
884
885 sum = 0;
886 for (i = 0; i < bitmap->bitsLen >> 2; ++i) {
887 sum += dvmClzImpl(bitmap->bits[i]);
888 }
889 return sum;
890}
891
892/*
893 * Miscellaneous functionality.
894 */
895
896static int isForward(const void *addr)
897{
898 return (uintptr_t)addr & 0x1;
899}
900
901static void setForward(const void *toObj, void *fromObj)
902{
903 *(unsigned long *)fromObj = (uintptr_t)toObj | 0x1;
904}
905
906static void* getForward(const void *fromObj)
907{
908 return (void *)((uintptr_t)fromObj & ~0x1);
909}
910
911/* Beware, uses the same encoding as a forwarding pointers! */
912static int isPermanentString(const StringObject *obj) {
913 return (uintptr_t)obj & 0x1;
914}
915
916static void* getPermanentString(const StringObject *obj)
917{
918 return (void *)((uintptr_t)obj & ~0x1);
919}
920
921
922/*
923 * Scavenging and transporting routines follow. A transporter grays
924 * an object. A scavenger blackens an object. We define these
925 * routines for each fundamental object type. Dispatch is performed
926 * in scavengeObject.
927 */
928
929/*
Carl Shapiro2396fda2010-05-03 20:14:14 -0700930 * Class object scavenging.
Carl Shapirod28668c2010-04-15 16:10:00 -0700931 */
Carl Shapiro2396fda2010-05-03 20:14:14 -0700932static void scavengeClassObject(ClassObject *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -0700933{
Carl Shapirod28668c2010-04-15 16:10:00 -0700934 int i;
935
Carl Shapiro8bb533e2010-05-06 15:35:27 -0700936 LOG_SCAV("scavengeClassObject(obj=%p)", obj);
Carl Shapiro2396fda2010-05-03 20:14:14 -0700937 assert(obj != NULL);
Carl Shapirod28668c2010-04-15 16:10:00 -0700938 assert(obj->obj.clazz != NULL);
939 assert(obj->obj.clazz->descriptor != NULL);
940 assert(!strcmp(obj->obj.clazz->descriptor, "Ljava/lang/Class;"));
941 assert(obj->descriptor != NULL);
Carl Shapiro8bb533e2010-05-06 15:35:27 -0700942 LOG_SCAV("scavengeClassObject: descriptor='%s',vtableCount=%zu",
943 obj->descriptor, obj->vtableCount);
Carl Shapiro2396fda2010-05-03 20:14:14 -0700944 /* Scavenge our class object. */
Carl Shapirod28668c2010-04-15 16:10:00 -0700945 scavengeReference((Object **) obj);
946 /* Scavenge the array element class object. */
947 if (IS_CLASS_FLAG_SET(obj, CLASS_ISARRAY)) {
948 scavengeReference((Object **)(void *)&obj->elementClass);
949 }
950 /* Scavenge the superclass. */
951 scavengeReference((Object **)(void *)&obj->super);
952 /* Scavenge the class loader. */
953 scavengeReference(&obj->classLoader);
954 /* Scavenge static fields. */
955 for (i = 0; i < obj->sfieldCount; ++i) {
956 char ch = obj->sfields[i].field.signature[0];
957 if (ch == '[' || ch == 'L') {
958 scavengeReference((Object **)(void *)&obj->sfields[i].value.l);
959 }
960 }
961 /* Scavenge interface class objects. */
962 for (i = 0; i < obj->interfaceCount; ++i) {
963 scavengeReference((Object **) &obj->interfaces[i]);
964 }
Carl Shapirod28668c2010-04-15 16:10:00 -0700965}
966
967/*
968 * Array object scavenging.
969 */
Carl Shapirod28668c2010-04-15 16:10:00 -0700970static size_t scavengeArrayObject(ArrayObject *array)
971{
972 size_t i, length;
973
Carl Shapiro8bb533e2010-05-06 15:35:27 -0700974 LOG_SCAV("scavengeArrayObject(array=%p)", array);
Carl Shapirod28668c2010-04-15 16:10:00 -0700975 /* Scavenge the class object. */
Carl Shapiro952e84a2010-05-06 14:35:29 -0700976 assert(toSpaceContains(array));
Carl Shapirod28668c2010-04-15 16:10:00 -0700977 assert(array != NULL);
978 assert(array->obj.clazz != NULL);
979 scavengeReference((Object **) array);
980 length = dvmArrayObjectSize(array);
981 /* Scavenge the array contents. */
982 if (IS_CLASS_FLAG_SET(array->obj.clazz, CLASS_ISOBJECTARRAY)) {
983 Object **contents = (Object **)array->contents;
984 for (i = 0; i < array->length; ++i) {
985 scavengeReference(&contents[i]);
986 }
987 }
988 return length;
989}
990
991/*
992 * Reference object scavenging.
993 */
994
Carl Shapiro952e84a2010-05-06 14:35:29 -0700995static int getReferenceFlags(const Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -0700996{
997 int flags;
998
999 flags = CLASS_ISREFERENCE |
1000 CLASS_ISWEAKREFERENCE |
1001 CLASS_ISPHANTOMREFERENCE;
Carl Shapiro952e84a2010-05-06 14:35:29 -07001002 return GET_CLASS_FLAG_GROUP(obj->clazz, flags);
Carl Shapirod28668c2010-04-15 16:10:00 -07001003}
1004
Carl Shapiro952e84a2010-05-06 14:35:29 -07001005static int isReference(const Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001006{
1007 return getReferenceFlags(obj) != 0;
1008}
1009
Carl Shapiro952e84a2010-05-06 14:35:29 -07001010static int isSoftReference(const Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001011{
1012 return getReferenceFlags(obj) == CLASS_ISREFERENCE;
1013}
1014
Carl Shapiro952e84a2010-05-06 14:35:29 -07001015static int isWeakReference(const Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001016{
1017 return getReferenceFlags(obj) & CLASS_ISWEAKREFERENCE;
1018}
1019
Carl Shapiro952e84a2010-05-06 14:35:29 -07001020static bool isPhantomReference(const Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001021{
1022 return getReferenceFlags(obj) & CLASS_ISPHANTOMREFERENCE;
1023}
1024
Carl Shapiro952e84a2010-05-06 14:35:29 -07001025/*
1026 * Returns true if the reference was registered with a reference queue
1027 * but has not yet been appended to it.
1028 */
1029static bool isReferenceEnqueuable(const Object *ref)
Carl Shapirod28668c2010-04-15 16:10:00 -07001030{
Carl Shapiro952e84a2010-05-06 14:35:29 -07001031 Object *queue, *queueNext;
Carl Shapirod28668c2010-04-15 16:10:00 -07001032
Carl Shapiro952e84a2010-05-06 14:35:29 -07001033 queue = dvmGetFieldObject(ref, gDvm.offJavaLangRefReference_queue);
1034 queueNext = dvmGetFieldObject(ref, gDvm.offJavaLangRefReference_queueNext);
1035 if (queue == NULL || queueNext != NULL) {
1036 /*
1037 * There is no queue, or the reference has already
1038 * been enqueued. The Reference.enqueue() method
1039 * will do nothing even if we call it.
1040 */
1041 return false;
Carl Shapirod28668c2010-04-15 16:10:00 -07001042 }
Carl Shapiro952e84a2010-05-06 14:35:29 -07001043
1044 /*
1045 * We need to call enqueue(), but if we called it from
1046 * here we'd probably deadlock. Schedule a call.
1047 */
1048 return true;
1049}
1050
1051/*
1052 * Schedules a reference to be appended to its reference queue.
1053 */
1054static void enqueueReference(const Object *ref)
1055{
1056 LargeHeapRefTable **table;
1057 Object *op;
1058
1059 assert(((uintptr_t)ref & 3) == 0);
1060 assert((WORKER_ENQUEUE & ~3) == 0);
1061 assert(dvmGetFieldObject(ref, gDvm.offJavaLangRefReference_queue) != NULL);
1062 assert(dvmGetFieldObject(ref, gDvm.offJavaLangRefReference_queueNext) == NULL);
1063 /*
1064 * Set the enqueue bit in the bottom of the pointer. Assumes that
1065 * objects are 8-byte aligned.
1066 *
1067 * Note that we are adding the *Reference* (which is by definition
1068 * already black at this point) to this list; we're not adding the
1069 * referent (which has already been cleared).
1070 */
1071 table = &gDvm.gcHeap->referenceOperations;
1072 op = (Object *)((uintptr_t)ref | WORKER_ENQUEUE);
1073 if (!dvmHeapAddRefToLargeTable(table, op)) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001074 LOGE("no room for any more reference operations");
Carl Shapiro952e84a2010-05-06 14:35:29 -07001075 dvmAbort();
1076 }
1077}
1078
1079/*
1080 * Sets the referent field of a reference object to NULL.
1081 */
1082static void clearReference(Object *obj)
1083{
1084 dvmSetFieldObject(obj, gDvm.offJavaLangRefReference_referent, NULL);
1085}
1086
1087/*
1088 * Clears reference objects with white referents.
1089 */
1090void clearWhiteReferences(Object **list)
1091{
1092 size_t referentOffset, vmDataOffset;
1093 bool doSignal;
1094
1095 vmDataOffset = gDvm.offJavaLangRefReference_vmData;
1096 referentOffset = gDvm.offJavaLangRefReference_referent;
1097 doSignal = false;
1098 while (*list != NULL) {
1099 Object *ref = *list;
1100 JValue *field = dvmFieldPtr(ref, referentOffset);
1101 Object *referent = field->l;
1102 *list = dvmGetFieldObject(ref, vmDataOffset);
1103 assert(referent != NULL);
1104 if (isForward(referent->clazz)) {
1105 field->l = referent = getForward(referent->clazz);
1106 continue;
1107 }
1108 if (fromSpaceContains(referent)) {
1109 /* Referent is white, clear it. */
1110 clearReference(ref);
1111 if (isReferenceEnqueuable(ref)) {
1112 enqueueReference(ref);
1113 doSignal = true;
1114 }
1115 }
1116 }
1117 /*
1118 * If we cleared a reference with a reference queue we must notify
1119 * the heap worker to append the reference.
1120 */
1121 if (doSignal) {
1122 dvmSignalHeapWorker(false);
1123 }
1124 assert(*list == NULL);
1125}
1126
1127/*
1128 * Blackens referents subject to the soft reference preservation
1129 * policy.
1130 */
1131void preserveSoftReferences(Object **list)
1132{
1133 Object *ref;
1134 Object *prev, *next;
1135 size_t referentOffset, vmDataOffset;
1136 unsigned counter;
1137 bool white;
1138
1139 vmDataOffset = gDvm.offJavaLangRefReference_vmData;
1140 referentOffset = gDvm.offJavaLangRefReference_referent;
1141 counter = 0;
1142 prev = next = NULL;
1143 ref = *list;
1144 while (ref != NULL) {
1145 JValue *field = dvmFieldPtr(ref, referentOffset);
1146 Object *referent = field->l;
1147 next = dvmGetFieldObject(ref, vmDataOffset);
1148 assert(referent != NULL);
1149 if (isForward(referent->clazz)) {
1150 /* Referent is black. */
1151 field->l = referent = getForward(referent->clazz);
1152 white = false;
1153 } else {
1154 white = fromSpaceContains(referent);
1155 }
1156 if (!white && ((++counter) & 1)) {
1157 /* Referent is white and biased toward saving, gray it. */
1158 scavengeReference((Object **)(void *)&field->l);
1159 white = true;
1160 }
1161 if (white) {
1162 /* Referent is black, unlink it. */
1163 if (prev != NULL) {
1164 dvmSetFieldObject(ref, vmDataOffset, NULL);
1165 dvmSetFieldObject(prev, vmDataOffset, next);
1166 }
1167 } else {
1168 /* Referent is white, skip over it. */
1169 prev = ref;
1170 }
1171 ref = next;
1172 }
1173 /*
1174 * Restart the trace with the newly gray references added to the
1175 * root set.
1176 */
1177 scavengeBlockQueue();
1178}
1179
1180void processFinalizableReferences(void)
1181{
1182 HeapRefTable newPendingRefs;
1183 LargeHeapRefTable *finRefs = gDvm.gcHeap->finalizableRefs;
1184 Object **ref;
1185 Object **lastRef;
1186 size_t totalPendCount;
1187
1188 /*
1189 * All strongly, reachable objects are black.
1190 * Any white finalizable objects need to be finalized.
1191 */
1192
1193 /* Create a table that the new pending refs will
1194 * be added to.
1195 */
1196 if (!dvmHeapInitHeapRefTable(&newPendingRefs, 128)) {
1197 //TODO: mark all finalizable refs and hope that
1198 // we can schedule them next time. Watch out,
1199 // because we may be expecting to free up space
1200 // by calling finalizers.
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001201 LOG_REF("no room for pending finalizations\n");
Carl Shapiro952e84a2010-05-06 14:35:29 -07001202 dvmAbort();
1203 }
1204
1205 /*
1206 * Walk through finalizableRefs and move any white references to
1207 * the list of new pending refs.
1208 */
1209 totalPendCount = 0;
1210 while (finRefs != NULL) {
1211 Object **gapRef;
1212 size_t newPendCount = 0;
1213
1214 gapRef = ref = finRefs->refs.table;
1215 lastRef = finRefs->refs.nextEntry;
1216 while (ref < lastRef) {
1217 if (fromSpaceContains(*ref)) {
1218 if (!dvmHeapAddToHeapRefTable(&newPendingRefs, *ref)) {
1219 //TODO: add the current table and allocate
1220 // a new, smaller one.
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001221 LOG_REF("no room for any more pending finalizations: %zd\n",
Carl Shapiro952e84a2010-05-06 14:35:29 -07001222 dvmHeapNumHeapRefTableEntries(&newPendingRefs));
1223 dvmAbort();
1224 }
1225 newPendCount++;
1226 } else {
1227 /* This ref is black, so will remain on finalizableRefs.
1228 */
1229 if (newPendCount > 0) {
1230 /* Copy it up to fill the holes.
1231 */
1232 *gapRef++ = *ref;
1233 } else {
1234 /* No holes yet; don't bother copying.
1235 */
1236 gapRef++;
1237 }
1238 }
1239 ref++;
1240 }
1241 finRefs->refs.nextEntry = gapRef;
1242 //TODO: if the table is empty when we're done, free it.
1243 totalPendCount += newPendCount;
1244 finRefs = finRefs->next;
1245 }
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001246 LOG_REF("%zd finalizers triggered.\n", totalPendCount);
Carl Shapiro952e84a2010-05-06 14:35:29 -07001247 if (totalPendCount == 0) {
1248 /* No objects required finalization.
1249 * Free the empty temporary table.
1250 */
1251 dvmClearReferenceTable(&newPendingRefs);
1252 return;
1253 }
1254
1255 /* Add the new pending refs to the main list.
1256 */
1257 if (!dvmHeapAddTableToLargeTable(&gDvm.gcHeap->pendingFinalizationRefs,
1258 &newPendingRefs))
1259 {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001260 LOG_REF("can't insert new pending finalizations\n");
Carl Shapiro952e84a2010-05-06 14:35:29 -07001261 dvmAbort();
1262 }
1263
1264 //TODO: try compacting the main list with a memcpy loop
1265
1266 /* Blacken the refs we just moved; we don't want them or their
1267 * children to get swept yet.
1268 */
1269 ref = newPendingRefs.table;
1270 lastRef = newPendingRefs.nextEntry;
1271 assert(ref < lastRef);
1272 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_FINALIZING, 0);
1273 while (ref < lastRef) {
1274 scavengeReference(ref);
1275 ref++;
1276 }
1277 HPROF_CLEAR_GC_SCAN_STATE();
1278 scavengeBlockQueue();
1279 dvmSignalHeapWorker(false);
Carl Shapirod28668c2010-04-15 16:10:00 -07001280}
1281
Carl Shapirod28668c2010-04-15 16:10:00 -07001282/*
1283 * If a reference points to from-space and has been forwarded, we snap
1284 * the pointer to its new to-space address. If the reference points
1285 * to an unforwarded from-space address we must enqueue the reference
1286 * for later processing. TODO: implement proper reference processing
1287 * and move the referent scavenging elsewhere.
1288 */
Carl Shapiro952e84a2010-05-06 14:35:29 -07001289static void scavengeReferenceObject(Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001290{
Carl Shapiro952e84a2010-05-06 14:35:29 -07001291 Object *referent;
1292 Object **queue;
1293 size_t referentOffset, vmDataOffset;
1294
Carl Shapirod28668c2010-04-15 16:10:00 -07001295 assert(obj != NULL);
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001296 LOG_SCAV("scavengeReferenceObject(obj=%p),'%s'", obj, obj->clazz->descriptor);
Carl Shapiro2396fda2010-05-03 20:14:14 -07001297 scavengeDataObject(obj);
Carl Shapiro952e84a2010-05-06 14:35:29 -07001298 referentOffset = gDvm.offJavaLangRefReference_referent;
1299 referent = dvmGetFieldObject(obj, referentOffset);
1300 if (referent == NULL || toSpaceContains(referent)) {
1301 return;
Carl Shapirod28668c2010-04-15 16:10:00 -07001302 }
Carl Shapiro952e84a2010-05-06 14:35:29 -07001303 if (isSoftReference(obj)) {
1304 queue = &gDvm.gcHeap->softReferences;
1305 } else if (isWeakReference(obj)) {
1306 queue = &gDvm.gcHeap->weakReferences;
1307 } else {
1308 assert(isPhantomReference(obj));
1309 queue = &gDvm.gcHeap->phantomReferences;
1310 }
1311 vmDataOffset = gDvm.offJavaLangRefReference_vmData;
1312 dvmSetFieldObject(obj, vmDataOffset, (Object *)*queue);
1313 *queue = obj;
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001314 LOG_SCAV("scavengeReferenceObject: enqueueing %p", obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001315}
1316
1317/*
1318 * Data object scavenging.
1319 */
Carl Shapiro952e84a2010-05-06 14:35:29 -07001320static void scavengeDataObject(Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001321{
1322 ClassObject *clazz;
Carl Shapirod28668c2010-04-15 16:10:00 -07001323 int i;
1324
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001325 // LOG_SCAV("scavengeDataObject(obj=%p)", obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001326 assert(obj != NULL);
Carl Shapiro952e84a2010-05-06 14:35:29 -07001327 assert(obj->clazz != NULL);
1328 assert(obj->clazz->objectSize != 0);
1329 assert(toSpaceContains(obj));
Carl Shapirod28668c2010-04-15 16:10:00 -07001330 /* Scavenge the class object. */
Carl Shapiro952e84a2010-05-06 14:35:29 -07001331 clazz = obj->clazz;
Carl Shapirod28668c2010-04-15 16:10:00 -07001332 scavengeReference((Object **) obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001333 /* Scavenge instance fields. */
1334 if (clazz->refOffsets != CLASS_WALK_SUPER) {
1335 size_t refOffsets = clazz->refOffsets;
1336 while (refOffsets != 0) {
1337 size_t rshift = CLZ(refOffsets);
1338 size_t offset = CLASS_OFFSET_FROM_CLZ(rshift);
1339 Object **ref = (Object **)((u1 *)obj + offset);
1340 scavengeReference(ref);
1341 refOffsets &= ~(CLASS_HIGH_BIT >> rshift);
1342 }
1343 } else {
1344 for (; clazz != NULL; clazz = clazz->super) {
1345 InstField *field = clazz->ifields;
1346 for (i = 0; i < clazz->ifieldRefCount; ++i, ++field) {
1347 size_t offset = field->byteOffset;
1348 Object **ref = (Object **)((u1 *)obj + offset);
1349 scavengeReference(ref);
1350 }
1351 }
1352 }
Carl Shapiro2396fda2010-05-03 20:14:14 -07001353}
1354
1355static Object *transportObject(const Object *fromObj)
1356{
1357 Object *toObj;
1358 size_t allocSize, copySize;
1359
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001360 LOG_TRAN("transportObject(fromObj=%p) allocBlocks=%zu",
Carl Shapiro2396fda2010-05-03 20:14:14 -07001361 fromObj,
1362 gDvm.gcHeap->heapSource->allocBlocks);
1363 assert(fromObj != NULL);
Carl Shapiro952e84a2010-05-06 14:35:29 -07001364 assert(fromSpaceContains(fromObj));
Carl Shapiro2396fda2010-05-03 20:14:14 -07001365 allocSize = copySize = objectSize(fromObj);
1366 if (LW_HASH_STATE(fromObj->lock) != LW_HASH_STATE_UNHASHED) {
1367 /*
1368 * The object has been hashed or hashed and moved. We must
1369 * reserve an additional word for a hash code.
1370 */
1371 allocSize += sizeof(u4);
1372 }
1373 if (LW_HASH_STATE(fromObj->lock) == LW_HASH_STATE_HASHED_AND_MOVED) {
1374 /*
1375 * The object has its hash code allocated. Ensure the hash
1376 * code is copied along with the instance data.
1377 */
1378 copySize += sizeof(u4);
1379 }
1380 /* TODO(cshapiro): don't copy, re-map large data objects. */
1381 assert(copySize <= allocSize);
1382 toObj = allocateGray(allocSize);
1383 assert(toObj != NULL);
Carl Shapiro952e84a2010-05-06 14:35:29 -07001384 assert(toSpaceContains(toObj));
Carl Shapiro2396fda2010-05-03 20:14:14 -07001385 memcpy(toObj, fromObj, copySize);
1386 if (LW_HASH_STATE(fromObj->lock) == LW_HASH_STATE_HASHED) {
1387 /*
1388 * The object has had its hash code exposed. Append it to the
1389 * instance and set a bit so we know to look for it there.
1390 */
1391 *(u4 *)(((char *)toObj) + copySize) = (u4)fromObj >> 3;
1392 toObj->lock |= LW_HASH_STATE_HASHED_AND_MOVED << LW_HASH_STATE_SHIFT;
1393 }
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001394 LOG_TRAN("transportObject: from %p/%zu to %p/%zu (%zu,%zu) %s",
1395 fromObj, addressToBlock(gDvm.gcHeap->heapSource,fromObj),
1396 toObj, addressToBlock(gDvm.gcHeap->heapSource,toObj),
1397 copySize, allocSize, copySize < allocSize ? "DIFFERENT" : "");
Carl Shapiro2396fda2010-05-03 20:14:14 -07001398 return toObj;
Carl Shapirod28668c2010-04-15 16:10:00 -07001399}
1400
1401/*
1402 * Generic reference scavenging.
1403 */
1404
1405/*
1406 * Given a reference to an object, the scavenge routine will gray the
1407 * reference. Any objects pointed to by the scavenger object will be
1408 * transported to new space and a forwarding pointer will be installed
1409 * in the header of the object.
1410 */
1411
1412/*
1413 * Blacken the given pointer. If the pointer is in from space, it is
1414 * transported to new space. If the object has a forwarding pointer
1415 * installed it has already been transported and the referent is
1416 * snapped to the new address.
1417 */
Carl Shapiro2396fda2010-05-03 20:14:14 -07001418static void scavengeReference(Object **obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001419{
1420 ClassObject *clazz;
Carl Shapiro2396fda2010-05-03 20:14:14 -07001421 Object *fromObj, *toObj;
Carl Shapirod28668c2010-04-15 16:10:00 -07001422 uintptr_t word;
1423
1424 assert(obj);
1425
Carl Shapiro2396fda2010-05-03 20:14:14 -07001426 if (*obj == NULL) return;
Carl Shapirod28668c2010-04-15 16:10:00 -07001427
1428 assert(dvmIsValidObject(*obj));
1429
1430 /* The entire block is black. */
Carl Shapiro952e84a2010-05-06 14:35:29 -07001431 if (toSpaceContains(*obj)) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001432 LOG_SCAV("scavengeReference skipping pinned object @ %p", *obj);
Carl Shapiro2396fda2010-05-03 20:14:14 -07001433 return;
Carl Shapirod28668c2010-04-15 16:10:00 -07001434 }
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001435 LOG_SCAV("scavengeReference(*obj=%p)", *obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001436
Carl Shapiro952e84a2010-05-06 14:35:29 -07001437 assert(fromSpaceContains(*obj));
Carl Shapirod28668c2010-04-15 16:10:00 -07001438
1439 clazz = (*obj)->clazz;
1440
1441 if (isForward(clazz)) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001442 // LOG_SCAV("forwarding %p @ %p to %p", *obj, obj, (void *)((uintptr_t)clazz & ~0x1));
Carl Shapirod28668c2010-04-15 16:10:00 -07001443 *obj = (Object *)getForward(clazz);
Carl Shapiro2396fda2010-05-03 20:14:14 -07001444 return;
Carl Shapirod28668c2010-04-15 16:10:00 -07001445 }
Carl Shapiro2396fda2010-05-03 20:14:14 -07001446 fromObj = *obj;
1447 if (clazz == NULL) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001448 // LOG_SCAV("scavangeReference %p has a NULL class object", fromObj);
Carl Shapiro2396fda2010-05-03 20:14:14 -07001449 assert(!"implemented");
1450 toObj = NULL;
1451 } else if (clazz == gDvm.unlinkedJavaLangClass) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001452 // LOG_SCAV("scavangeReference %p is an unlinked class object", fromObj);
Carl Shapiro2396fda2010-05-03 20:14:14 -07001453 assert(!"implemented");
1454 toObj = NULL;
1455 } else {
1456 toObj = transportObject(fromObj);
1457 }
1458 setForward(toObj, fromObj);
1459 *obj = (Object *)toObj;
Carl Shapirod28668c2010-04-15 16:10:00 -07001460}
1461
1462static void verifyReference(const void *obj)
1463{
1464 HeapSource *heapSource;
1465 size_t block;
1466 char space;
1467
1468 if (obj == NULL) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001469 LOG_VER("verifyReference(obj=%p)", obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001470 return;
1471 }
1472 heapSource = gDvm.gcHeap->heapSource;
1473 block = addressToBlock(heapSource, obj);
1474 space = heapSource->blockSpace[block];
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001475 LOG_VER("verifyReference(obj=%p),block=%zu,space=%d", obj, block, space);
Carl Shapirod28668c2010-04-15 16:10:00 -07001476 assert(!((uintptr_t)obj & 7));
Carl Shapiro952e84a2010-05-06 14:35:29 -07001477 assert(toSpaceContains(obj));
Carl Shapirod28668c2010-04-15 16:10:00 -07001478 assert(dvmIsValidObject(obj));
1479}
1480
1481/*
1482 * Generic object scavenging.
1483 */
Carl Shapiro2396fda2010-05-03 20:14:14 -07001484static void scavengeObject(Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001485{
1486 ClassObject *clazz;
Carl Shapirod28668c2010-04-15 16:10:00 -07001487
1488 assert(obj != NULL);
Carl Shapiro952e84a2010-05-06 14:35:29 -07001489 assert(obj->clazz != NULL);
1490 assert(!((uintptr_t)obj->clazz & 0x1));
1491 assert(obj->clazz != gDvm.unlinkedJavaLangClass);
Carl Shapirod28668c2010-04-15 16:10:00 -07001492 clazz = obj->clazz;
Carl Shapirod28668c2010-04-15 16:10:00 -07001493 if (clazz == gDvm.classJavaLangClass) {
Carl Shapiro2396fda2010-05-03 20:14:14 -07001494 scavengeClassObject((ClassObject *)obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001495 } else if (IS_CLASS_FLAG_SET(clazz, CLASS_ISARRAY)) {
Carl Shapiro2396fda2010-05-03 20:14:14 -07001496 scavengeArrayObject((ArrayObject *)obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001497 } else if (IS_CLASS_FLAG_SET(clazz, CLASS_ISREFERENCE)) {
Carl Shapiro952e84a2010-05-06 14:35:29 -07001498 scavengeReferenceObject(obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001499 } else {
Carl Shapiro952e84a2010-05-06 14:35:29 -07001500 scavengeDataObject(obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001501 }
Carl Shapirod28668c2010-04-15 16:10:00 -07001502}
1503
1504/*
1505 * External root scavenging routines.
1506 */
1507
1508static void scavengeHashTable(HashTable *table)
1509{
1510 HashEntry *entry;
1511 void *obj;
1512 int i;
1513
1514 if (table == NULL) {
1515 return;
1516 }
1517 dvmHashTableLock(table);
1518 for (i = 0; i < table->tableSize; ++i) {
1519 entry = &table->pEntries[i];
1520 obj = entry->data;
1521 if (obj == NULL || obj == HASH_TOMBSTONE) {
1522 continue;
1523 }
1524 scavengeReference((Object **)(void *)&entry->data);
1525 }
1526 dvmHashTableUnlock(table);
1527}
1528
1529static void pinHashTableEntries(HashTable *table)
1530{
1531 HashEntry *entry;
1532 void *obj;
1533 int i;
1534
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001535 LOG_PIN(">>> pinHashTableEntries(table=%p)", table);
Carl Shapirod28668c2010-04-15 16:10:00 -07001536 if (table == NULL) {
1537 return;
1538 }
1539 dvmHashTableLock(table);
1540 for (i = 0; i < table->tableSize; ++i) {
1541 entry = &table->pEntries[i];
1542 obj = entry->data;
1543 if (obj == NULL || obj == HASH_TOMBSTONE) {
1544 continue;
1545 }
1546 pinObject(entry->data);
1547 }
1548 dvmHashTableUnlock(table);
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001549 LOG_PIN("<<< pinHashTableEntries(table=%p)", table);
Carl Shapirod28668c2010-04-15 16:10:00 -07001550}
1551
1552static void pinPrimitiveClasses(void)
1553{
1554 size_t length;
1555 size_t i;
1556
1557 length = ARRAYSIZE(gDvm.primitiveClass);
1558 for (i = 0; i < length; i++) {
1559 if (gDvm.primitiveClass[i] != NULL) {
1560 pinObject((Object *)gDvm.primitiveClass[i]);
1561 }
1562 }
1563}
1564
1565/*
1566 * Scavenge interned strings. Permanent interned strings will have
1567 * been pinned and are therefore ignored. Non-permanent strings that
1568 * have been forwarded are snapped. All other entries are removed.
1569 */
1570static void scavengeInternedStrings(void)
1571{
1572 HashTable *table;
1573 HashEntry *entry;
1574 Object *obj;
1575 int i;
1576
1577 table = gDvm.internedStrings;
1578 if (table == NULL) {
1579 return;
1580 }
1581 dvmHashTableLock(table);
1582 for (i = 0; i < table->tableSize; ++i) {
1583 entry = &table->pEntries[i];
1584 obj = (Object *)entry->data;
1585 if (obj == NULL || obj == HASH_TOMBSTONE) {
1586 continue;
1587 } else if (!isPermanentString((StringObject *)obj)) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001588 // LOG_SCAV("entry->data=%p", entry->data);
1589 LOG_SCAV(">>> string obj=%p", entry->data);
Carl Shapirod28668c2010-04-15 16:10:00 -07001590 /* TODO(cshapiro): detach white string objects */
1591 scavengeReference((Object **)(void *)&entry->data);
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001592 LOG_SCAV("<<< string obj=%p", entry->data);
Carl Shapirod28668c2010-04-15 16:10:00 -07001593 }
1594 }
1595 dvmHashTableUnlock(table);
1596}
1597
1598static void pinInternedStrings(void)
1599{
1600 HashTable *table;
1601 HashEntry *entry;
1602 Object *obj;
1603 int i;
1604
1605 table = gDvm.internedStrings;
1606 if (table == NULL) {
1607 return;
1608 }
1609 dvmHashTableLock(table);
1610 for (i = 0; i < table->tableSize; ++i) {
1611 entry = &table->pEntries[i];
1612 obj = (Object *)entry->data;
1613 if (obj == NULL || obj == HASH_TOMBSTONE) {
1614 continue;
1615 } else if (isPermanentString((StringObject *)obj)) {
1616 obj = (Object *)getPermanentString((StringObject*)obj);
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001617 LOG_PROM(">>> pin string obj=%p", obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001618 pinObject(obj);
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001619 LOG_PROM("<<< pin string obj=%p", obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001620 }
1621 }
1622 dvmHashTableUnlock(table);
1623}
1624
1625static void verifyInternedStrings(void)
1626{
1627 HashTable *table;
1628 HashEntry *entry;
1629 Object *fwd, *obj;
1630 int i;
1631
1632 table = gDvm.internedStrings;
1633 if (table == NULL) {
1634 return;
1635 }
1636 dvmHashTableLock(table);
1637 for (i = 0; i < table->tableSize; ++i) {
1638 entry = &table->pEntries[i];
1639 obj = (Object *)entry->data;
1640 if (obj == NULL || obj == HASH_TOMBSTONE) {
1641 continue;
1642 } else if (isPermanentString((StringObject *)obj)) {
1643 fwd = (Object *)getForward(obj);
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001644 LOG_VER(">>> verify string fwd=%p obj=%p", fwd, obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001645 verifyReference(fwd);
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001646 LOG_VER(">>> verify string fwd=%p obj=%p", fwd, obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001647 } else {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001648 LOG_SCAV(">>> verify string obj=%p %p", obj, entry->data);
Carl Shapirod28668c2010-04-15 16:10:00 -07001649 verifyReference(obj);
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001650 LOG_SCAV("<<< verify string obj=%p %p", obj, entry->data);
Carl Shapirod28668c2010-04-15 16:10:00 -07001651 }
1652 }
1653 dvmHashTableUnlock(table);
1654}
1655
1656/*
1657 * At present, reference tables contain references that must not be
1658 * moved by the collector. Instead of scavenging each reference in
1659 * the table we pin each referenced object.
1660 */
Carl Shapiro583d64c2010-05-04 10:44:47 -07001661static void pinReferenceTable(const ReferenceTable *table)
Carl Shapirod28668c2010-04-15 16:10:00 -07001662{
1663 Object **entry;
1664 int i;
1665
1666 assert(table != NULL);
1667 assert(table->table != NULL);
1668 assert(table->nextEntry != NULL);
1669 for (entry = table->table; entry < table->nextEntry; ++entry) {
1670 assert(entry != NULL);
1671 assert(!isForward(*entry));
1672 pinObject(*entry);
1673 }
1674}
1675
1676static void verifyReferenceTable(const ReferenceTable *table)
1677{
1678 Object **entry;
1679 int i;
1680
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001681 LOG_VER(">>> verifyReferenceTable(table=%p)", table);
Carl Shapirod28668c2010-04-15 16:10:00 -07001682 for (entry = table->table; entry < table->nextEntry; ++entry) {
1683 assert(entry != NULL);
1684 assert(!isForward(*entry));
1685 verifyReference(*entry);
1686 }
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001687 LOG_VER("<<< verifyReferenceTable(table=%p)", table);
Carl Shapirod28668c2010-04-15 16:10:00 -07001688}
1689
1690static void scavengeLargeHeapRefTable(LargeHeapRefTable *table)
1691{
1692 Object **entry;
1693
1694 for (; table != NULL; table = table->next) {
1695 for (entry = table->refs.table; entry < table->refs.nextEntry; ++entry) {
1696 if ((uintptr_t)*entry & ~0x3) {
1697 /* It's a pending reference operation. */
1698 assert(!"implemented");
1699 }
1700 scavengeReference(entry);
1701 }
1702 }
1703}
1704
1705/* This code was copied from Thread.c */
1706static void scavengeThreadStack(Thread *thread)
1707{
1708 const u4 *framePtr;
1709#if WITH_EXTRA_GC_CHECKS > 1
1710 bool first = true;
1711#endif
1712
1713 framePtr = (const u4 *)thread->curFrame;
1714 while (framePtr != NULL) {
1715 const StackSaveArea *saveArea;
1716 const Method *method;
1717
1718 saveArea = SAVEAREA_FROM_FP(framePtr);
1719 method = saveArea->method;
Carl Shapiro583d64c2010-05-04 10:44:47 -07001720 if (method != NULL && !dvmIsNativeMethod(method)) {
Carl Shapirod28668c2010-04-15 16:10:00 -07001721#ifdef COUNT_PRECISE_METHODS
1722 /* the GC is running, so no lock required */
1723 if (dvmPointerSetAddEntry(gDvm.preciseMethods, method))
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001724 LOG_SCAV("PGC: added %s.%s %p\n",
1725 method->clazz->descriptor, method->name, method);
Carl Shapirod28668c2010-04-15 16:10:00 -07001726#endif
1727#if WITH_EXTRA_GC_CHECKS > 1
1728 /*
1729 * May also want to enable the memset() in the "invokeMethod"
1730 * goto target in the portable interpreter. That sets the stack
1731 * to a pattern that makes referring to uninitialized data
1732 * very obvious.
1733 */
1734
1735 if (first) {
1736 /*
1737 * First frame, isn't native, check the "alternate" saved PC
1738 * as a sanity check.
1739 *
1740 * It seems like we could check the second frame if the first
1741 * is native, since the PCs should be the same. It turns out
1742 * this doesn't always work. The problem is that we could
1743 * have calls in the sequence:
1744 * interp method #2
1745 * native method
1746 * interp method #1
1747 *
1748 * and then GC while in the native method after returning
1749 * from interp method #2. The currentPc on the stack is
1750 * for interp method #1, but thread->currentPc2 is still
1751 * set for the last thing interp method #2 did.
1752 *
1753 * This can also happen in normal execution:
1754 * - sget-object on not-yet-loaded class
1755 * - class init updates currentPc2
1756 * - static field init is handled by parsing annotations;
1757 * static String init requires creation of a String object,
1758 * which can cause a GC
1759 *
1760 * Essentially, any pattern that involves executing
1761 * interpreted code and then causes an allocation without
1762 * executing instructions in the original method will hit
1763 * this. These are rare enough that the test still has
1764 * some value.
1765 */
1766 if (saveArea->xtra.currentPc != thread->currentPc2) {
1767 LOGW("PGC: savedPC(%p) != current PC(%p), %s.%s ins=%p\n",
1768 saveArea->xtra.currentPc, thread->currentPc2,
1769 method->clazz->descriptor, method->name, method->insns);
1770 if (saveArea->xtra.currentPc != NULL)
1771 LOGE(" pc inst = 0x%04x\n", *saveArea->xtra.currentPc);
1772 if (thread->currentPc2 != NULL)
1773 LOGE(" pc2 inst = 0x%04x\n", *thread->currentPc2);
1774 dvmDumpThread(thread, false);
1775 }
1776 } else {
1777 /*
1778 * It's unusual, but not impossible, for a non-first frame
1779 * to be at something other than a method invocation. For
1780 * example, if we do a new-instance on a nonexistent class,
1781 * we'll have a lot of class loader activity on the stack
1782 * above the frame with the "new" operation. Could also
1783 * happen while we initialize a Throwable when an instruction
1784 * fails.
1785 *
1786 * So there's not much we can do here to verify the PC,
1787 * except to verify that it's a GC point.
1788 */
1789 }
1790 assert(saveArea->xtra.currentPc != NULL);
1791#endif
1792
1793 const RegisterMap* pMap;
1794 const u1* regVector;
1795 int i;
1796
1797 Method* nonConstMethod = (Method*) method; // quiet gcc
1798 pMap = dvmGetExpandedRegisterMap(nonConstMethod);
1799
1800 /* assert(pMap != NULL); */
1801
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001802 //LOG_SCAV("PGC: %s.%s\n", method->clazz->descriptor, method->name);
Carl Shapirod28668c2010-04-15 16:10:00 -07001803
1804 if (pMap != NULL) {
1805 /* found map, get registers for this address */
1806 int addr = saveArea->xtra.currentPc - method->insns;
1807 regVector = dvmRegisterMapGetLine(pMap, addr);
1808 /*
1809 if (regVector == NULL) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001810 LOG_SCAV("PGC: map but no entry for %s.%s addr=0x%04x\n",
1811 method->clazz->descriptor, method->name, addr);
Carl Shapirod28668c2010-04-15 16:10:00 -07001812 } else {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001813 LOG_SCAV("PGC: found map for %s.%s 0x%04x (t=%d)\n",
1814 method->clazz->descriptor, method->name, addr,
1815 thread->threadId);
Carl Shapirod28668c2010-04-15 16:10:00 -07001816 }
1817 */
1818 } else {
1819 /*
1820 * No map found. If precise GC is disabled this is
1821 * expected -- we don't create pointers to the map data even
1822 * if it's present -- but if it's enabled it means we're
1823 * unexpectedly falling back on a conservative scan, so it's
1824 * worth yelling a little.
1825 */
1826 if (gDvm.preciseGc) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001827 LOG_SCAV("PGC: no map for %s.%s\n", method->clazz->descriptor, method->name);
Carl Shapirod28668c2010-04-15 16:10:00 -07001828 }
1829 regVector = NULL;
1830 }
1831
1832 /* assert(regVector != NULL); */
1833
1834 if (regVector == NULL) {
1835 /* conservative scan */
1836 for (i = method->registersSize - 1; i >= 0; i--) {
1837 u4 rval = *framePtr++;
1838 if (rval != 0 && (rval & 0x3) == 0) {
1839 abort();
1840 /* dvmMarkIfObject((Object *)rval); */
1841 }
1842 }
1843 } else {
1844 /*
1845 * Precise scan. v0 is at the lowest address on the
1846 * interpreted stack, and is the first bit in the register
1847 * vector, so we can walk through the register map and
1848 * memory in the same direction.
1849 *
1850 * A '1' bit indicates a live reference.
1851 */
1852 u2 bits = 1 << 1;
1853 for (i = method->registersSize - 1; i >= 0; i--) {
1854 /* u4 rval = *framePtr++; */
1855 u4 rval = *framePtr;
1856
1857 bits >>= 1;
1858 if (bits == 1) {
1859 /* set bit 9 so we can tell when we're empty */
1860 bits = *regVector++ | 0x0100;
1861 LOGVV("loaded bits: 0x%02x\n", bits & 0xff);
1862 }
1863
1864 if (rval != 0 && (bits & 0x01) != 0) {
1865 /*
1866 * Non-null, register marked as live reference. This
1867 * should always be a valid object.
1868 */
1869#if WITH_EXTRA_GC_CHECKS > 0
1870 if ((rval & 0x3) != 0 || !dvmIsValidObject((Object*) rval)) {
1871 /* this is very bad */
1872 LOGE("PGC: invalid ref in reg %d: 0x%08x\n",
1873 method->registersSize-1 - i, rval);
1874 } else
1875#endif
1876 {
1877
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001878 // LOG_SCAV("stack reference %u@%p", *framePtr, framePtr);
Carl Shapirod28668c2010-04-15 16:10:00 -07001879 /* dvmMarkObjectNonNull((Object *)rval); */
1880 scavengeReference((Object **) framePtr);
1881 }
1882 } else {
1883 /*
1884 * Null or non-reference, do nothing at all.
1885 */
1886#if WITH_EXTRA_GC_CHECKS > 1
1887 if (dvmIsValidObject((Object*) rval)) {
1888 /* this is normal, but we feel chatty */
1889 LOGD("PGC: ignoring valid ref in reg %d: 0x%08x\n",
1890 method->registersSize-1 - i, rval);
1891 }
1892#endif
1893 }
1894 ++framePtr;
1895 }
1896 dvmReleaseRegisterMapLine(pMap, regVector);
1897 }
1898 }
Carl Shapiro952e84a2010-05-06 14:35:29 -07001899 /* else this is a break frame and there is nothing to gray, or
Carl Shapirod28668c2010-04-15 16:10:00 -07001900 * this is a native method and the registers are just the "ins",
1901 * copied from various registers in the caller's set.
1902 */
1903
1904#if WITH_EXTRA_GC_CHECKS > 1
1905 first = false;
1906#endif
1907
1908 /* Don't fall into an infinite loop if things get corrupted.
1909 */
1910 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
1911 saveArea->prevFrame == NULL);
1912 framePtr = saveArea->prevFrame;
1913 }
1914}
1915
1916static void scavengeThread(Thread *thread)
1917{
1918 assert(thread->status != THREAD_RUNNING ||
1919 thread->isSuspended ||
1920 thread == dvmThreadSelf());
1921
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001922 // LOG_SCAV("scavengeThread(thread=%p)", thread);
Carl Shapirod28668c2010-04-15 16:10:00 -07001923
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001924 // LOG_SCAV("Scavenging threadObj=%p", thread->threadObj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001925 scavengeReference(&thread->threadObj);
1926
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001927 // LOG_SCAV("Scavenging exception=%p", thread->exception);
Carl Shapirod28668c2010-04-15 16:10:00 -07001928 scavengeReference(&thread->exception);
1929
1930 scavengeThreadStack(thread);
1931}
1932
1933static void scavengeThreadList(void)
1934{
1935 Thread *thread;
1936
1937 dvmLockThreadList(dvmThreadSelf());
1938 thread = gDvm.threadList;
1939 while (thread) {
1940 scavengeThread(thread);
1941 thread = thread->next;
1942 }
1943 dvmUnlockThreadList();
1944}
1945
1946static void verifyThreadStack(const Thread *thread)
1947{
1948 const u4 *framePtr;
1949
1950 assert(thread != NULL);
1951 framePtr = (const u4 *)thread->curFrame;
1952 while (framePtr != NULL) {
1953 const StackSaveArea *saveArea;
1954 const Method *method;
1955
1956 saveArea = SAVEAREA_FROM_FP(framePtr);
1957 method = saveArea->method;
1958 if (method != NULL && !dvmIsNativeMethod(method)) {
1959 const RegisterMap* pMap;
1960 const u1* regVector;
1961 int i;
1962
1963 Method* nonConstMethod = (Method*) method; // quiet gcc
1964 pMap = dvmGetExpandedRegisterMap(nonConstMethod);
1965
1966 /* assert(pMap != NULL); */
1967
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001968 // LOG_VER("PGC: %s.%s\n", method->clazz->descriptor, method->name);
Carl Shapirod28668c2010-04-15 16:10:00 -07001969
1970 if (pMap != NULL) {
1971 /* found map, get registers for this address */
1972 int addr = saveArea->xtra.currentPc - method->insns;
1973 regVector = dvmRegisterMapGetLine(pMap, addr);
1974 if (regVector == NULL) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001975 LOG_VER("PGC: map but no entry for %s.%s addr=0x%04x\n",
1976 method->clazz->descriptor, method->name, addr);
Carl Shapirod28668c2010-04-15 16:10:00 -07001977 } else {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001978 //LOG_VER("PGC: found map for %s.%s 0x%04x (t=%d)\n", method->clazz->descriptor, method->name, addr, thread->threadId);
Carl Shapirod28668c2010-04-15 16:10:00 -07001979 }
1980 } else {
1981 /*
1982 * No map found. If precise GC is disabled this is
1983 * expected -- we don't create pointers to the map data even
1984 * if it's present -- but if it's enabled it means we're
1985 * unexpectedly falling back on a conservative scan, so it's
1986 * worth yelling a little.
1987 */
1988 if (gDvm.preciseGc) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001989 LOG_VER("PGC: no map for %s.%s\n",
1990 method->clazz->descriptor, method->name);
Carl Shapirod28668c2010-04-15 16:10:00 -07001991 }
1992 regVector = NULL;
1993 }
1994
1995 /* assert(regVector != NULL); */
1996
1997 if (regVector == NULL) {
1998 /* conservative scan */
1999 for (i = method->registersSize - 1; i >= 0; i--) {
2000 u4 rval = *framePtr++;
2001 if (rval != 0 && (rval & 0x3) == 0) {
2002 abort();
2003 /* dvmMarkIfObject((Object *)rval); */
2004 }
2005 }
2006 } else {
2007 /*
2008 * Precise scan. v0 is at the lowest address on the
2009 * interpreted stack, and is the first bit in the register
2010 * vector, so we can walk through the register map and
2011 * memory in the same direction.
2012 *
2013 * A '1' bit indicates a live reference.
2014 */
2015 u2 bits = 1 << 1;
2016 for (i = method->registersSize - 1; i >= 0; i--) {
2017 u4 rval = *framePtr;
2018
2019 bits >>= 1;
2020 if (bits == 1) {
2021 /* set bit 9 so we can tell when we're empty */
2022 bits = *regVector++ | 0x0100;
2023 LOGVV("loaded bits: 0x%02x\n", bits & 0xff);
2024 }
2025
2026 if (rval != 0 && (bits & 0x01) != 0) {
2027 /*
2028 * Non-null, register marked as live reference. This
2029 * should always be a valid object.
2030 */
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002031 //LOG_VER("verify stack reference %p", (Object *)*framePtr);
Carl Shapirod28668c2010-04-15 16:10:00 -07002032 verifyReference((Object *)*framePtr);
2033 } else {
2034 /*
2035 * Null or non-reference, do nothing at all.
2036 */
2037 }
2038 ++framePtr;
2039 }
2040 dvmReleaseRegisterMapLine(pMap, regVector);
2041 }
2042 }
Carl Shapiro952e84a2010-05-06 14:35:29 -07002043 /* else this is a break frame and there is nothing to gray, or
Carl Shapirod28668c2010-04-15 16:10:00 -07002044 * this is a native method and the registers are just the "ins",
2045 * copied from various registers in the caller's set.
2046 */
2047
2048 /* Don't fall into an infinite loop if things get corrupted.
2049 */
2050 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
2051 saveArea->prevFrame == NULL);
2052 framePtr = saveArea->prevFrame;
2053 }
2054}
2055
2056static void verifyThread(const Thread *thread)
2057{
2058 assert(thread->status != THREAD_RUNNING ||
2059 thread->isSuspended ||
2060 thread == dvmThreadSelf());
2061
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002062 LOG_VER("verifyThread(thread=%p)", thread);
Carl Shapirod28668c2010-04-15 16:10:00 -07002063
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002064 LOG_VER("verify threadObj=%p", thread->threadObj);
Carl Shapirod28668c2010-04-15 16:10:00 -07002065 verifyReference(thread->threadObj);
2066
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002067 LOG_VER("verify exception=%p", thread->exception);
Carl Shapirod28668c2010-04-15 16:10:00 -07002068 verifyReference(thread->exception);
2069
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002070 LOG_VER("verify thread->internalLocalRefTable");
Carl Shapirod28668c2010-04-15 16:10:00 -07002071 verifyReferenceTable(&thread->internalLocalRefTable);
2072
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002073 LOG_VER("verify thread->jniLocalRefTable");
Carl Shapirod28668c2010-04-15 16:10:00 -07002074 verifyReferenceTable(&thread->jniLocalRefTable);
2075
2076 /* Can the check be pushed into the promote routine? */
2077 if (thread->jniMonitorRefTable.table) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002078 LOG_VER("verify thread->jniMonitorRefTable");
Carl Shapirod28668c2010-04-15 16:10:00 -07002079 verifyReferenceTable(&thread->jniMonitorRefTable);
2080 }
2081
2082 verifyThreadStack(thread);
2083}
2084
2085static void verifyThreadList(void)
2086{
2087 Thread *thread;
2088
2089 dvmLockThreadList(dvmThreadSelf());
2090 thread = gDvm.threadList;
2091 while (thread) {
2092 verifyThread(thread);
2093 thread = thread->next;
2094 }
2095 dvmUnlockThreadList();
2096}
2097
Carl Shapiro583d64c2010-05-04 10:44:47 -07002098static void pinNativeMethodArguments(const Thread *thread)
2099{
2100 const u4 *framePtr;
2101 const StackSaveArea *saveArea;
2102 const Method *method;
2103 const char *shorty;
2104 Object *obj;
2105 int i;
2106
2107 saveArea = NULL;
2108 framePtr = (const u4 *)thread->curFrame;
2109 for (; framePtr != NULL; framePtr = saveArea->prevFrame) {
2110 saveArea = SAVEAREA_FROM_FP(framePtr);
2111 method = saveArea->method;
2112 if (method != NULL && dvmIsNativeMethod(method)) {
2113 /*
Carl Shapiro952e84a2010-05-06 14:35:29 -07002114 * For purposes of graying references, we don't need to do
Carl Shapiro583d64c2010-05-04 10:44:47 -07002115 * anything here, because all of the native "ins" were copied
2116 * from registers in the caller's stack frame and won't be
2117 * changed (an interpreted method can freely use registers
2118 * with parameters like any other register, but natives don't
2119 * work that way).
2120 *
2121 * However, we need to ensure that references visible to
2122 * native methods don't move around. We can do a precise scan
2123 * of the arguments by examining the method signature.
2124 */
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002125 LOG_PIN("+++ native scan %s.%s\n",
2126 method->clazz->descriptor, method->name);
Carl Shapiro583d64c2010-05-04 10:44:47 -07002127 assert(method->registersSize == method->insSize);
2128 if (!dvmIsStaticMethod(method)) {
2129 /* grab the "this" pointer */
2130 obj = (Object *)*framePtr++;
2131 if (obj == NULL) {
2132 /*
2133 * This can happen for the "fake" entry frame inserted
2134 * for threads created outside the VM. There's no actual
2135 * call so there's no object. If we changed the fake
2136 * entry method to be declared "static" then this
2137 * situation should never occur.
2138 */
2139 } else {
2140 assert(dvmIsValidObject(obj));
2141 pinObject(obj);
2142 }
2143 }
2144 shorty = method->shorty+1; // skip return value
2145 for (i = method->registersSize - 1; i >= 0; i--, framePtr++) {
2146 switch (*shorty++) {
2147 case 'L':
2148 obj = (Object *)*framePtr;
2149 if (obj != NULL) {
2150 assert(dvmIsValidObject(obj));
2151 pinObject(obj);
2152 }
2153 break;
2154 case 'D':
2155 case 'J':
2156 framePtr++;
2157 break;
2158 default:
2159 /* 32-bit non-reference value */
2160 obj = (Object *)*framePtr; // debug, remove
2161 if (dvmIsValidObject(obj)) { // debug, remove
2162 /* if we see a lot of these, our scan might be off */
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002163 LOG_PIN("+++ did NOT pin obj %p\n", obj);
Carl Shapiro583d64c2010-05-04 10:44:47 -07002164 }
2165 break;
2166 }
2167 }
2168 }
2169 /*
2170 * Don't fall into an infinite loop if things get corrupted.
2171 */
2172 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
2173 saveArea->prevFrame == NULL);
2174 }
2175}
2176
2177static void pinThread(const Thread *thread)
Carl Shapirod28668c2010-04-15 16:10:00 -07002178{
2179 assert(thread != NULL);
2180 assert(thread->status != THREAD_RUNNING ||
2181 thread->isSuspended ||
2182 thread == dvmThreadSelf());
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002183 LOG_PIN("pinThread(thread=%p)", thread);
Carl Shapirod28668c2010-04-15 16:10:00 -07002184
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002185 LOG_PIN("Pin native method arguments");
Carl Shapiro583d64c2010-05-04 10:44:47 -07002186 pinNativeMethodArguments(thread);
2187
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002188 LOG_PIN("Pin internalLocalRefTable");
Carl Shapirod28668c2010-04-15 16:10:00 -07002189 pinReferenceTable(&thread->internalLocalRefTable);
2190
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002191 LOG_PIN("Pin jniLocalRefTable");
Carl Shapirod28668c2010-04-15 16:10:00 -07002192 pinReferenceTable(&thread->jniLocalRefTable);
2193
2194 /* Can the check be pushed into the promote routine? */
2195 if (thread->jniMonitorRefTable.table) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002196 LOG_PIN("Pin jniMonitorRefTable");
Carl Shapirod28668c2010-04-15 16:10:00 -07002197 pinReferenceTable(&thread->jniMonitorRefTable);
2198 }
2199}
2200
2201static void pinThreadList(void)
2202{
2203 Thread *thread;
2204
2205 dvmLockThreadList(dvmThreadSelf());
2206 thread = gDvm.threadList;
2207 while (thread) {
2208 pinThread(thread);
2209 thread = thread->next;
2210 }
2211 dvmUnlockThreadList();
2212}
2213
2214/*
2215 * Heap block scavenging.
2216 */
2217
2218/*
2219 * Scavenge objects in the current block. Scavenging terminates when
2220 * the pointer reaches the highest address in the block or when a run
2221 * of zero words that continues to the highest address is reached.
2222 */
2223static void scavengeBlock(HeapSource *heapSource, size_t block)
2224{
2225 u1 *cursor;
2226 u1 *end;
2227 size_t size;
2228
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002229 LOG_SCAV("scavengeBlock(heapSource=%p,block=%zu)", heapSource, block);
Carl Shapirod28668c2010-04-15 16:10:00 -07002230
2231 assert(heapSource != NULL);
2232 assert(block < heapSource->totalBlocks);
2233 assert(heapSource->blockSpace[block] == BLOCK_TO_SPACE);
2234
2235 cursor = blockToAddress(heapSource, block);
2236 end = cursor + BLOCK_SIZE;
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002237 LOG_SCAV("scavengeBlock start=%p, end=%p", cursor, end);
Carl Shapirod28668c2010-04-15 16:10:00 -07002238
2239 /* Parse and scavenge the current block. */
2240 size = 0;
2241 while (cursor < end) {
2242 u4 word = *(u4 *)cursor;
2243 if (word != 0) {
Carl Shapiro2396fda2010-05-03 20:14:14 -07002244 scavengeObject((Object *)cursor);
2245 size = objectSize((Object *)cursor);
Carl Shapirod28668c2010-04-15 16:10:00 -07002246 size = alignUp(size, ALLOC_ALIGNMENT);
2247 cursor += size;
2248 } else if (word == 0 && cursor == (u1 *)gDvm.unlinkedJavaLangClass) {
2249 size = sizeof(ClassObject);
2250 cursor += size;
2251 } else {
2252 /* Check for padding. */
2253 while (*(u4 *)cursor == 0) {
2254 cursor += 4;
2255 if (cursor == end) break;
2256 }
2257 /* Punt if something went wrong. */
2258 assert(cursor == end);
2259 }
2260 }
2261}
2262
Carl Shapiro2396fda2010-05-03 20:14:14 -07002263static size_t objectSize(const Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07002264{
2265 size_t size;
2266
Carl Shapiro2396fda2010-05-03 20:14:14 -07002267 assert(obj != NULL);
2268 assert(obj->clazz != NULL);
Carl Shapirod28668c2010-04-15 16:10:00 -07002269 if (obj->clazz == gDvm.classJavaLangClass ||
2270 obj->clazz == gDvm.unlinkedJavaLangClass) {
2271 size = dvmClassObjectSize((ClassObject *)obj);
2272 } else if (IS_CLASS_FLAG_SET(obj->clazz, CLASS_ISARRAY)) {
2273 size = dvmArrayObjectSize((ArrayObject *)obj);
2274 } else {
Carl Shapiro2396fda2010-05-03 20:14:14 -07002275 assert(obj->clazz->objectSize != 0);
Carl Shapirod28668c2010-04-15 16:10:00 -07002276 size = obj->clazz->objectSize;
2277 }
Carl Shapiro2396fda2010-05-03 20:14:14 -07002278 if (LW_HASH_STATE(obj->lock) == LW_HASH_STATE_HASHED_AND_MOVED) {
2279 size += sizeof(u4);
2280 }
Carl Shapirod28668c2010-04-15 16:10:00 -07002281 return size;
2282}
2283
2284static void verifyBlock(HeapSource *heapSource, size_t block)
2285{
2286 u1 *cursor;
2287 u1 *end;
2288 size_t size;
2289
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002290 // LOG_VER("verifyBlock(heapSource=%p,block=%zu)", heapSource, block);
Carl Shapirod28668c2010-04-15 16:10:00 -07002291
2292 assert(heapSource != NULL);
2293 assert(block < heapSource->totalBlocks);
2294 assert(heapSource->blockSpace[block] == BLOCK_TO_SPACE);
2295
2296 cursor = blockToAddress(heapSource, block);
2297 end = cursor + BLOCK_SIZE;
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002298 // LOG_VER("verifyBlock start=%p, end=%p", cursor, end);
Carl Shapirod28668c2010-04-15 16:10:00 -07002299
2300 /* Parse and scavenge the current block. */
2301 size = 0;
2302 while (cursor < end) {
2303 u4 word = *(u4 *)cursor;
2304 if (word != 0) {
2305 dvmVerifyObject((Object *)cursor);
2306 size = objectSize((Object *)cursor);
2307 size = alignUp(size, ALLOC_ALIGNMENT);
2308 cursor += size;
2309 } else if (word == 0 && cursor == (u1 *)gDvm.unlinkedJavaLangClass) {
2310 size = sizeof(ClassObject);
2311 cursor += size;
2312 } else {
2313 /* Check for padding. */
2314 while (*(unsigned long *)cursor == 0) {
2315 cursor += 4;
2316 if (cursor == end) break;
2317 }
2318 /* Punt if something went wrong. */
2319 assert(cursor == end);
2320 }
2321 }
2322}
2323
2324static void describeBlockQueue(const HeapSource *heapSource)
2325{
2326 size_t block, count;
2327 char space;
2328
2329 block = heapSource->queueHead;
2330 count = 0;
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002331 LOG_SCAV(">>> describeBlockQueue(heapSource=%p)", heapSource);
Carl Shapirod28668c2010-04-15 16:10:00 -07002332 /* Count the number of blocks enqueued. */
2333 while (block != QUEUE_TAIL) {
2334 block = heapSource->blockQueue[block];
2335 ++count;
2336 }
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002337 LOG_SCAV("blockQueue %zu elements, enqueued %zu",
Carl Shapirod28668c2010-04-15 16:10:00 -07002338 count, heapSource->queueSize);
2339 block = heapSource->queueHead;
2340 while (block != QUEUE_TAIL) {
2341 space = heapSource->blockSpace[block];
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002342 LOG_SCAV("block=%zu@%p,space=%zu", block, blockToAddress(heapSource,block), space);
Carl Shapirod28668c2010-04-15 16:10:00 -07002343 block = heapSource->blockQueue[block];
2344 }
2345
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002346 LOG_SCAV("<<< describeBlockQueue(heapSource=%p)", heapSource);
Carl Shapirod28668c2010-04-15 16:10:00 -07002347}
2348
2349/*
2350 * Blackens promoted objects.
2351 */
2352static void scavengeBlockQueue(void)
2353{
2354 HeapSource *heapSource;
2355 size_t block;
2356
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002357 LOG_SCAV(">>> scavengeBlockQueue()");
Carl Shapirod28668c2010-04-15 16:10:00 -07002358 heapSource = gDvm.gcHeap->heapSource;
2359 describeBlockQueue(heapSource);
2360 while (heapSource->queueHead != QUEUE_TAIL) {
2361 block = heapSource->queueHead;
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002362 LOG_SCAV("Dequeueing block %zu\n", block);
Carl Shapirod28668c2010-04-15 16:10:00 -07002363 scavengeBlock(heapSource, block);
2364 heapSource->queueHead = heapSource->blockQueue[block];
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002365 LOG_SCAV("New queue head is %zu\n", heapSource->queueHead);
Carl Shapirod28668c2010-04-15 16:10:00 -07002366 }
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002367 LOG_SCAV("<<< scavengeBlockQueue()");
Carl Shapirod28668c2010-04-15 16:10:00 -07002368}
2369
2370/*
2371 * Scan the block list and verify all blocks that are marked as being
2372 * in new space. This should be parametrized so we can invoke this
2373 * routine outside of the context of a collection.
2374 */
2375static void verifyNewSpace(void)
2376{
2377 HeapSource *heapSource;
2378 size_t i;
2379 size_t c0, c1, c2, c7;
2380
2381 c0 = c1 = c2 = c7 = 0;
2382 heapSource = gDvm.gcHeap->heapSource;
2383 for (i = 0; i < heapSource->totalBlocks; ++i) {
2384 switch (heapSource->blockSpace[i]) {
2385 case BLOCK_FREE: ++c0; break;
2386 case BLOCK_TO_SPACE: ++c1; break;
2387 case BLOCK_FROM_SPACE: ++c2; break;
2388 case BLOCK_CONTINUED: ++c7; break;
2389 default: assert(!"reached");
2390 }
2391 }
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002392 LOG_VER("Block Demographics: "
2393 "Free=%zu,ToSpace=%zu,FromSpace=%zu,Continued=%zu",
2394 c0, c1, c2, c7);
Carl Shapirod28668c2010-04-15 16:10:00 -07002395 for (i = 0; i < heapSource->totalBlocks; ++i) {
2396 if (heapSource->blockSpace[i] != BLOCK_TO_SPACE) {
2397 continue;
2398 }
2399 verifyBlock(heapSource, i);
2400 }
2401}
2402
2403static void scavengeGlobals(void)
2404{
2405 scavengeReference((Object **)(void *)&gDvm.classJavaLangClass);
2406 scavengeReference((Object **)(void *)&gDvm.classJavaLangClassArray);
2407 scavengeReference((Object **)(void *)&gDvm.classJavaLangError);
2408 scavengeReference((Object **)(void *)&gDvm.classJavaLangObject);
2409 scavengeReference((Object **)(void *)&gDvm.classJavaLangObjectArray);
2410 scavengeReference((Object **)(void *)&gDvm.classJavaLangRuntimeException);
2411 scavengeReference((Object **)(void *)&gDvm.classJavaLangString);
2412 scavengeReference((Object **)(void *)&gDvm.classJavaLangThread);
2413 scavengeReference((Object **)(void *)&gDvm.classJavaLangVMThread);
2414 scavengeReference((Object **)(void *)&gDvm.classJavaLangThreadGroup);
2415 scavengeReference((Object **)(void *)&gDvm.classJavaLangThrowable);
2416 scavengeReference((Object **)(void *)&gDvm.classJavaLangStackTraceElement);
2417 scavengeReference((Object **)(void *)&gDvm.classJavaLangStackTraceElementArray);
2418 scavengeReference((Object **)(void *)&gDvm.classJavaLangAnnotationAnnotationArray);
2419 scavengeReference((Object **)(void *)&gDvm.classJavaLangAnnotationAnnotationArrayArray);
2420 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectAccessibleObject);
2421 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectConstructor);
2422 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectConstructorArray);
2423 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectField);
2424 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectFieldArray);
2425 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectMethod);
2426 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectMethodArray);
2427 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectProxy);
2428 scavengeReference((Object **)(void *)&gDvm.classJavaLangExceptionInInitializerError);
2429 scavengeReference((Object **)(void *)&gDvm.classJavaLangRefReference);
2430 scavengeReference((Object **)(void *)&gDvm.classJavaNioReadWriteDirectByteBuffer);
2431 scavengeReference((Object **)(void *)&gDvm.classJavaSecurityAccessController);
2432 scavengeReference((Object **)(void *)&gDvm.classOrgApacheHarmonyLangAnnotationAnnotationFactory);
2433 scavengeReference((Object **)(void *)&gDvm.classOrgApacheHarmonyLangAnnotationAnnotationMember);
2434 scavengeReference((Object **)(void *)&gDvm.classOrgApacheHarmonyLangAnnotationAnnotationMemberArray);
2435 scavengeReference((Object **)(void *)&gDvm.classOrgApacheHarmonyNioInternalDirectBuffer);
2436 scavengeReference((Object **)(void *)&gDvm.classArrayBoolean);
2437 scavengeReference((Object **)(void *)&gDvm.classArrayChar);
2438 scavengeReference((Object **)(void *)&gDvm.classArrayFloat);
2439 scavengeReference((Object **)(void *)&gDvm.classArrayDouble);
2440 scavengeReference((Object **)(void *)&gDvm.classArrayByte);
2441 scavengeReference((Object **)(void *)&gDvm.classArrayShort);
2442 scavengeReference((Object **)(void *)&gDvm.classArrayInt);
2443 scavengeReference((Object **)(void *)&gDvm.classArrayLong);
2444}
2445
2446void describeHeap(void)
2447{
2448 HeapSource *heapSource;
2449
2450 heapSource = gDvm.gcHeap->heapSource;
2451 describeBlocks(heapSource);
2452}
2453
2454/*
2455 * The collection interface. Collection has a few distinct phases.
2456 * The first is flipping AKA condemning AKA whitening the heap. The
2457 * second is to promote all objects which are pointed to by pinned or
2458 * ambiguous references. The third phase is tracing from the stacks,
2459 * registers and various globals. Lastly, a verification of the heap
2460 * is performed. The last phase should be optional.
2461 */
2462void dvmScavengeRoots(void) /* Needs a new name badly */
2463{
2464 HeapRefTable *refs;
2465 GcHeap *gcHeap;
2466
2467 {
2468 size_t alloc, unused, total;
2469
2470 room(&alloc, &unused, &total);
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002471 LOG_SCAV("BEFORE GC: %zu alloc, %zu free, %zu total.",
2472 alloc, unused, total);
Carl Shapirod28668c2010-04-15 16:10:00 -07002473 }
2474
2475 gcHeap = gDvm.gcHeap;
2476 dvmHeapSourceFlip();
2477
2478 /*
2479 * Promote blocks with stationary objects.
2480 */
Carl Shapirod28668c2010-04-15 16:10:00 -07002481 pinThreadList();
Carl Shapirod28668c2010-04-15 16:10:00 -07002482 pinReferenceTable(&gDvm.jniGlobalRefTable);
Carl Shapirod28668c2010-04-15 16:10:00 -07002483 pinReferenceTable(&gDvm.jniPinRefTable);
Carl Shapirod28668c2010-04-15 16:10:00 -07002484 pinReferenceTable(&gcHeap->nonCollectableRefs);
Carl Shapirod28668c2010-04-15 16:10:00 -07002485 pinHashTableEntries(gDvm.loadedClasses);
Carl Shapirod28668c2010-04-15 16:10:00 -07002486 pinPrimitiveClasses();
Carl Shapirod28668c2010-04-15 16:10:00 -07002487 pinInternedStrings();
2488
2489 // describeBlocks(gcHeap->heapSource);
2490
2491 /*
2492 * Create first, open new-space page right here.
2493 */
2494
2495 /* Reset allocation to an unallocated block. */
2496 gDvm.gcHeap->heapSource->allocPtr = allocateBlocks(gDvm.gcHeap->heapSource, 1);
2497 gDvm.gcHeap->heapSource->allocLimit = gDvm.gcHeap->heapSource->allocPtr + BLOCK_SIZE;
2498 /*
2499 * Hack: promote the empty block allocated above. If the
2500 * promotions that occurred above did not actually gray any
2501 * objects, the block queue may be empty. We must force a
2502 * promotion to be safe.
2503 */
2504 promoteBlockByAddr(gDvm.gcHeap->heapSource, gDvm.gcHeap->heapSource->allocPtr);
2505
2506 /*
2507 * Scavenge blocks and relocate movable objects.
2508 */
2509
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002510 LOG_SCAV("Scavenging gDvm.threadList");
Carl Shapirod28668c2010-04-15 16:10:00 -07002511 scavengeThreadList();
2512
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002513 LOG_SCAV("Scavenging gDvm.gcHeap->referenceOperations");
Carl Shapirod28668c2010-04-15 16:10:00 -07002514 scavengeLargeHeapRefTable(gcHeap->referenceOperations);
2515
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002516 LOG_SCAV("Scavenging gDvm.gcHeap->pendingFinalizationRefs");
Carl Shapirod28668c2010-04-15 16:10:00 -07002517 scavengeLargeHeapRefTable(gcHeap->pendingFinalizationRefs);
2518
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002519 LOG_SCAV("Scavenging random global stuff");
Carl Shapirod28668c2010-04-15 16:10:00 -07002520 scavengeReference(&gDvm.outOfMemoryObj);
2521 scavengeReference(&gDvm.internalErrorObj);
2522 scavengeReference(&gDvm.noClassDefFoundErrorObj);
2523
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002524 LOG_SCAV("Scavenging gDvm.dbgRegistry");
Carl Shapirod28668c2010-04-15 16:10:00 -07002525 scavengeHashTable(gDvm.dbgRegistry);
2526
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002527 // LOG_SCAV("Scavenging gDvm.internedString");
Carl Shapirod28668c2010-04-15 16:10:00 -07002528 scavengeInternedStrings();
2529
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002530 LOG_SCAV("Root scavenge has completed.");
Carl Shapirod28668c2010-04-15 16:10:00 -07002531
2532 scavengeBlockQueue();
2533
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002534 LOG_SCAV("Re-snap global class pointers.");
Carl Shapirod28668c2010-04-15 16:10:00 -07002535 scavengeGlobals();
2536
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002537 LOG_SCAV("New space scavenge has completed.");
Carl Shapirod28668c2010-04-15 16:10:00 -07002538
2539 /*
Carl Shapiro952e84a2010-05-06 14:35:29 -07002540 * Process reference objects in strength order.
2541 */
2542
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002543 LOG_REF("Processing soft references...");
Carl Shapiro952e84a2010-05-06 14:35:29 -07002544 preserveSoftReferences(&gDvm.gcHeap->softReferences);
2545 clearWhiteReferences(&gDvm.gcHeap->softReferences);
2546
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002547 LOG_REF("Processing weak references...");
Carl Shapiro952e84a2010-05-06 14:35:29 -07002548 clearWhiteReferences(&gDvm.gcHeap->weakReferences);
2549
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002550 LOG_REF("Finding finalizations...");
Carl Shapiro952e84a2010-05-06 14:35:29 -07002551 processFinalizableReferences();
2552
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002553 LOG_REF("Processing f-reachable soft references...");
Carl Shapiro952e84a2010-05-06 14:35:29 -07002554 clearWhiteReferences(&gDvm.gcHeap->softReferences);
2555
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002556 LOG_REF("Processing f-reachable weak references...");
Carl Shapiro952e84a2010-05-06 14:35:29 -07002557 clearWhiteReferences(&gDvm.gcHeap->weakReferences);
2558
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002559 LOG_REF("Processing phantom references...");
Carl Shapiro952e84a2010-05-06 14:35:29 -07002560 clearWhiteReferences(&gDvm.gcHeap->phantomReferences);
2561
2562 /*
Carl Shapirod28668c2010-04-15 16:10:00 -07002563 * Verify the stack and heap.
2564 */
Carl Shapirod28668c2010-04-15 16:10:00 -07002565 verifyInternedStrings();
Carl Shapirod28668c2010-04-15 16:10:00 -07002566 verifyThreadList();
Carl Shapirod28668c2010-04-15 16:10:00 -07002567 verifyNewSpace();
2568
Carl Shapirod28668c2010-04-15 16:10:00 -07002569 //describeBlocks(gcHeap->heapSource);
2570
2571 clearFromSpace(gcHeap->heapSource);
2572
2573 {
2574 size_t alloc, rem, total;
2575
2576 room(&alloc, &rem, &total);
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002577 LOG_SCAV("AFTER GC: %zu alloc, %zu free, %zu total.", alloc, rem, total);
Carl Shapirod28668c2010-04-15 16:10:00 -07002578 }
2579}
2580
2581/*
2582 * Interface compatibility routines.
2583 */
2584
2585void dvmClearWhiteRefs(Object **list)
2586{
Carl Shapiro952e84a2010-05-06 14:35:29 -07002587 /* do nothing */
Carl Shapirod28668c2010-04-15 16:10:00 -07002588 assert(*list == NULL);
2589}
2590
2591void dvmHandleSoftRefs(Object **list)
2592{
Carl Shapiro952e84a2010-05-06 14:35:29 -07002593 /* do nothing */
Carl Shapirod28668c2010-04-15 16:10:00 -07002594 assert(*list == NULL);
2595}
2596
2597bool dvmHeapBeginMarkStep(GcMode mode)
2598{
2599 /* do nothing */
2600 return true;
2601}
2602
2603void dvmHeapFinishMarkStep(void)
2604{
2605 /* do nothing */
2606}
2607
2608void dvmHeapMarkRootSet(void)
2609{
2610 /* do nothing */
2611}
2612
2613void dvmHeapScanMarkedObjects(void)
2614{
2615 dvmScavengeRoots();
2616}
2617
2618void dvmHeapScheduleFinalizations(void)
2619{
2620 /* do nothing */
2621}
2622
2623void dvmHeapSweepUnmarkedObjects(GcMode mode, int *numFreed, size_t *sizeFreed)
2624{
2625 /* do nothing */
2626}
2627
2628void dvmMarkObjectNonNull(const Object *obj)
2629{
2630 assert(!"implemented");
2631}