blob: 846ba8aad9d02c2c5ba66a9190f67d8e025d900f [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 Shapiro7800c092010-05-11 13:46:29 -0700665 HeapSource *heapSource;
666 void *addr;
667 size_t block;
668
Carl Shapiro952e84a2010-05-06 14:35:29 -0700669 /* TODO: add a check that we are in a GC. */
Carl Shapiro7800c092010-05-11 13:46:29 -0700670 heapSource = gDvm.gcHeap->heapSource;
671 addr = dvmHeapSourceAlloc(size);
Carl Shapiro703a2f32010-05-12 23:11:37 -0700672 assert(addr != NULL);
Carl Shapiro7800c092010-05-11 13:46:29 -0700673 block = addressToBlock(heapSource, (const u1 *)addr);
674 if (heapSource->queueHead == QUEUE_TAIL) {
675 /*
676 * Forcibly append the underlying block to the queue. This
677 * condition occurs when referents are transported following
678 * the initial trace.
679 */
680 enqueueBlock(heapSource, block);
681 LOG_PROM("forced promoting block %zu %d @ %p", block, heapSource->blockSpace[block], addr);
682 }
683 return addr;
Carl Shapirod28668c2010-04-15 16:10:00 -0700684}
685
686/*
687 * Returns true if the given address is within the heap and points to
688 * the header of a live object.
689 */
690bool dvmHeapSourceContains(const void *addr)
691{
692 HeapSource *heapSource;
693 HeapBitmap *bitmap;
694
695 heapSource = gDvm.gcHeap->heapSource;
696 bitmap = &heapSource->allocBits;
Carl Shapirodc1e4f12010-05-01 22:27:56 -0700697 if (!dvmHeapBitmapCoversAddress(bitmap, addr)) {
698 return false;
699 } else {
700 return dvmHeapBitmapIsObjectBitSet(bitmap, addr);
701 }
Carl Shapirod28668c2010-04-15 16:10:00 -0700702}
703
704bool dvmHeapSourceGetPtrFlag(const void *ptr, enum HeapSourcePtrFlag flag)
705{
706 assert(!"implemented");
707 return false;
708}
709
710size_t dvmHeapSourceChunkSize(const void *ptr)
711{
712 assert(!"implemented");
713 return 0;
714}
715
716size_t dvmHeapSourceFootprint(void)
717{
718 assert(!"implemented");
719 return 0;
720}
721
722/*
723 * Returns the "ideal footprint" which appears to be the number of
724 * bytes currently committed to the heap. This starts out at the
725 * start size of the heap and grows toward the maximum size.
726 */
727size_t dvmHeapSourceGetIdealFootprint(void)
728{
729 return gDvm.gcHeap->heapSource->currentSize;
730}
731
732float dvmGetTargetHeapUtilization(void)
733{
734 assert(!"implemented");
735 return 0.0f;
736}
737
738void dvmSetTargetHeapUtilization(float newTarget)
739{
740 assert(!"implemented");
741}
742
743size_t dvmMinimumHeapSize(size_t size, bool set)
744{
745 return gDvm.gcHeap->heapSource->minimumSize;
746}
747
748/*
749 * Expands the size of the heap after a collection. At present we
750 * commit the pages for maximum size of the heap so this routine is
751 * just a no-op. Eventually, we will either allocate or commit pages
752 * on an as-need basis.
753 */
754void dvmHeapSourceGrowForUtilization(void)
755{
756 /* do nothing */
757}
758
759void dvmHeapSourceTrim(size_t bytesTrimmed[], size_t arrayLen)
760{
761 /* do nothing */
762}
763
764void dvmHeapSourceWalk(void (*callback)(const void *chunkptr, size_t chunklen,
765 const void *userptr, size_t userlen,
766 void *arg),
767 void *arg)
768{
769 assert(!"implemented");
770}
771
772size_t dvmHeapSourceGetNumHeaps(void)
773{
774 return 1;
775}
776
777bool dvmTrackExternalAllocation(size_t n)
778{
Carl Shapiro528f3812010-05-18 14:16:26 -0700779 /* do nothing */
780 return true;
Carl Shapirod28668c2010-04-15 16:10:00 -0700781}
782
783void dvmTrackExternalFree(size_t n)
784{
Carl Shapiro528f3812010-05-18 14:16:26 -0700785 /* do nothing */
Carl Shapirod28668c2010-04-15 16:10:00 -0700786}
787
788size_t dvmGetExternalBytesAllocated(void)
789{
790 assert(!"implemented");
791 return 0;
792}
793
794void dvmHeapSourceFlip(void)
795{
796 HeapSource *heapSource;
797 size_t i;
798
799 heapSource = gDvm.gcHeap->heapSource;
800
801 /* Reset the block queue. */
802 heapSource->allocBlocks = 0;
803 heapSource->queueSize = 0;
804 heapSource->queueHead = QUEUE_TAIL;
805
Carl Shapirod28668c2010-04-15 16:10:00 -0700806 /* TODO(cshapiro): pad the current (prev) block. */
807
808 heapSource->allocPtr = NULL;
809 heapSource->allocLimit = NULL;
810
811 /* Whiten all allocated blocks. */
812 for (i = 0; i < heapSource->totalBlocks; ++i) {
813 if (heapSource->blockSpace[i] == BLOCK_TO_SPACE) {
814 heapSource->blockSpace[i] = BLOCK_FROM_SPACE;
815 }
816 }
817}
818
819static void room(size_t *alloc, size_t *avail, size_t *total)
820{
821 HeapSource *heapSource;
822 size_t i;
823
824 heapSource = gDvm.gcHeap->heapSource;
825 *total = heapSource->totalBlocks*BLOCK_SIZE;
826 *alloc = heapSource->allocBlocks*BLOCK_SIZE;
827 *avail = *total - *alloc;
828}
829
830static bool isSpaceInternal(u1 *addr, int space)
831{
832 HeapSource *heapSource;
833 u1 *base, *limit;
834 size_t offset;
835 char space2;
836
837 heapSource = gDvm.gcHeap->heapSource;
838 base = heapSource->blockBase;
839 assert(addr >= base);
840 limit = heapSource->blockBase + heapSource->maximumSize;
841 assert(addr < limit);
842 offset = addr - base;
843 space2 = heapSource->blockSpace[offset >> BLOCK_SHIFT];
844 return space == space2;
845}
846
Carl Shapiro952e84a2010-05-06 14:35:29 -0700847static bool fromSpaceContains(const void *addr)
Carl Shapirod28668c2010-04-15 16:10:00 -0700848{
849 return isSpaceInternal((u1 *)addr, BLOCK_FROM_SPACE);
850}
851
Carl Shapiro952e84a2010-05-06 14:35:29 -0700852static bool toSpaceContains(const void *addr)
Carl Shapirod28668c2010-04-15 16:10:00 -0700853{
854 return isSpaceInternal((u1 *)addr, BLOCK_TO_SPACE);
855}
856
857/*
858 * Notifies the collector that the object at the given address must
859 * remain stationary during the current collection.
860 */
861static void pinObject(const Object *obj)
862{
863 promoteBlockByAddr(gDvm.gcHeap->heapSource, obj);
864}
865
866static void printHeapBitmap(const HeapBitmap *bitmap)
867{
868 const char *cp;
869 size_t i, length;
870
871 length = bitmap->bitsLen >> 2;
872 fprintf(stderr, "%p", bitmap->bits);
873 for (i = 0; i < length; ++i) {
874 fprintf(stderr, " %lx", bitmap->bits[i]);
875 fputc('\n', stderr);
876 }
877}
878
879static void printHeapBitmapSxS(const HeapBitmap *b1, const HeapBitmap *b2)
880{
881 uintptr_t addr;
882 size_t i, length;
883
884 assert(b1->base == b2->base);
885 assert(b1->bitsLen == b2->bitsLen);
886 addr = b1->base;
887 length = b1->bitsLen >> 2;
888 for (i = 0; i < length; ++i) {
889 int diff = b1->bits[i] == b2->bits[i];
890 fprintf(stderr, "%08x %08lx %08lx %d\n",
891 addr, b1->bits[i], b2->bits[i], diff);
892 addr += sizeof(*b1->bits)*CHAR_BIT;
893 }
894}
895
896static size_t sumHeapBitmap(const HeapBitmap *bitmap)
897{
898 const char *cp;
899 size_t i, sum;
900
901 sum = 0;
902 for (i = 0; i < bitmap->bitsLen >> 2; ++i) {
903 sum += dvmClzImpl(bitmap->bits[i]);
904 }
905 return sum;
906}
907
908/*
909 * Miscellaneous functionality.
910 */
911
912static int isForward(const void *addr)
913{
914 return (uintptr_t)addr & 0x1;
915}
916
917static void setForward(const void *toObj, void *fromObj)
918{
919 *(unsigned long *)fromObj = (uintptr_t)toObj | 0x1;
920}
921
922static void* getForward(const void *fromObj)
923{
924 return (void *)((uintptr_t)fromObj & ~0x1);
925}
926
927/* Beware, uses the same encoding as a forwarding pointers! */
928static int isPermanentString(const StringObject *obj) {
929 return (uintptr_t)obj & 0x1;
930}
931
932static void* getPermanentString(const StringObject *obj)
933{
934 return (void *)((uintptr_t)obj & ~0x1);
935}
936
937
938/*
939 * Scavenging and transporting routines follow. A transporter grays
940 * an object. A scavenger blackens an object. We define these
941 * routines for each fundamental object type. Dispatch is performed
942 * in scavengeObject.
943 */
944
945/*
Carl Shapiro2396fda2010-05-03 20:14:14 -0700946 * Class object scavenging.
Carl Shapirod28668c2010-04-15 16:10:00 -0700947 */
Carl Shapiro2396fda2010-05-03 20:14:14 -0700948static void scavengeClassObject(ClassObject *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -0700949{
Carl Shapirod28668c2010-04-15 16:10:00 -0700950 int i;
951
Carl Shapiro8bb533e2010-05-06 15:35:27 -0700952 LOG_SCAV("scavengeClassObject(obj=%p)", obj);
Carl Shapiro2396fda2010-05-03 20:14:14 -0700953 assert(obj != NULL);
Carl Shapirod28668c2010-04-15 16:10:00 -0700954 assert(obj->obj.clazz != NULL);
955 assert(obj->obj.clazz->descriptor != NULL);
956 assert(!strcmp(obj->obj.clazz->descriptor, "Ljava/lang/Class;"));
957 assert(obj->descriptor != NULL);
Carl Shapiro8bb533e2010-05-06 15:35:27 -0700958 LOG_SCAV("scavengeClassObject: descriptor='%s',vtableCount=%zu",
959 obj->descriptor, obj->vtableCount);
Carl Shapiro703a2f32010-05-12 23:11:37 -0700960 /* Delegate class object and instance field scavenging. */
961 scavengeDataObject((Object *)obj);
Carl Shapirod28668c2010-04-15 16:10:00 -0700962 /* Scavenge the array element class object. */
963 if (IS_CLASS_FLAG_SET(obj, CLASS_ISARRAY)) {
964 scavengeReference((Object **)(void *)&obj->elementClass);
965 }
966 /* Scavenge the superclass. */
967 scavengeReference((Object **)(void *)&obj->super);
968 /* Scavenge the class loader. */
969 scavengeReference(&obj->classLoader);
970 /* Scavenge static fields. */
971 for (i = 0; i < obj->sfieldCount; ++i) {
972 char ch = obj->sfields[i].field.signature[0];
973 if (ch == '[' || ch == 'L') {
974 scavengeReference((Object **)(void *)&obj->sfields[i].value.l);
975 }
976 }
977 /* Scavenge interface class objects. */
978 for (i = 0; i < obj->interfaceCount; ++i) {
979 scavengeReference((Object **) &obj->interfaces[i]);
980 }
Carl Shapirod28668c2010-04-15 16:10:00 -0700981}
982
983/*
984 * Array object scavenging.
985 */
Carl Shapirod28668c2010-04-15 16:10:00 -0700986static size_t scavengeArrayObject(ArrayObject *array)
987{
988 size_t i, length;
989
Carl Shapiro8bb533e2010-05-06 15:35:27 -0700990 LOG_SCAV("scavengeArrayObject(array=%p)", array);
Carl Shapirod28668c2010-04-15 16:10:00 -0700991 /* Scavenge the class object. */
Carl Shapiro952e84a2010-05-06 14:35:29 -0700992 assert(toSpaceContains(array));
Carl Shapirod28668c2010-04-15 16:10:00 -0700993 assert(array != NULL);
994 assert(array->obj.clazz != NULL);
995 scavengeReference((Object **) array);
996 length = dvmArrayObjectSize(array);
997 /* Scavenge the array contents. */
998 if (IS_CLASS_FLAG_SET(array->obj.clazz, CLASS_ISOBJECTARRAY)) {
999 Object **contents = (Object **)array->contents;
1000 for (i = 0; i < array->length; ++i) {
1001 scavengeReference(&contents[i]);
1002 }
1003 }
1004 return length;
1005}
1006
1007/*
1008 * Reference object scavenging.
1009 */
1010
Carl Shapiro952e84a2010-05-06 14:35:29 -07001011static int getReferenceFlags(const Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001012{
1013 int flags;
1014
1015 flags = CLASS_ISREFERENCE |
1016 CLASS_ISWEAKREFERENCE |
1017 CLASS_ISPHANTOMREFERENCE;
Carl Shapiro952e84a2010-05-06 14:35:29 -07001018 return GET_CLASS_FLAG_GROUP(obj->clazz, flags);
Carl Shapirod28668c2010-04-15 16:10:00 -07001019}
1020
Carl Shapiro952e84a2010-05-06 14:35:29 -07001021static int isReference(const Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001022{
1023 return getReferenceFlags(obj) != 0;
1024}
1025
Carl Shapiro952e84a2010-05-06 14:35:29 -07001026static int isSoftReference(const Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001027{
1028 return getReferenceFlags(obj) == CLASS_ISREFERENCE;
1029}
1030
Carl Shapiro952e84a2010-05-06 14:35:29 -07001031static int isWeakReference(const Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001032{
1033 return getReferenceFlags(obj) & CLASS_ISWEAKREFERENCE;
1034}
1035
Carl Shapiro952e84a2010-05-06 14:35:29 -07001036static bool isPhantomReference(const Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001037{
1038 return getReferenceFlags(obj) & CLASS_ISPHANTOMREFERENCE;
1039}
1040
Carl Shapiro952e84a2010-05-06 14:35:29 -07001041/*
1042 * Returns true if the reference was registered with a reference queue
1043 * but has not yet been appended to it.
1044 */
1045static bool isReferenceEnqueuable(const Object *ref)
Carl Shapirod28668c2010-04-15 16:10:00 -07001046{
Carl Shapiro952e84a2010-05-06 14:35:29 -07001047 Object *queue, *queueNext;
Carl Shapirod28668c2010-04-15 16:10:00 -07001048
Carl Shapiro952e84a2010-05-06 14:35:29 -07001049 queue = dvmGetFieldObject(ref, gDvm.offJavaLangRefReference_queue);
1050 queueNext = dvmGetFieldObject(ref, gDvm.offJavaLangRefReference_queueNext);
1051 if (queue == NULL || queueNext != NULL) {
1052 /*
1053 * There is no queue, or the reference has already
1054 * been enqueued. The Reference.enqueue() method
1055 * will do nothing even if we call it.
1056 */
1057 return false;
Carl Shapirod28668c2010-04-15 16:10:00 -07001058 }
Carl Shapiro952e84a2010-05-06 14:35:29 -07001059
1060 /*
1061 * We need to call enqueue(), but if we called it from
1062 * here we'd probably deadlock. Schedule a call.
1063 */
1064 return true;
1065}
1066
1067/*
1068 * Schedules a reference to be appended to its reference queue.
1069 */
1070static void enqueueReference(const Object *ref)
1071{
1072 LargeHeapRefTable **table;
1073 Object *op;
1074
1075 assert(((uintptr_t)ref & 3) == 0);
1076 assert((WORKER_ENQUEUE & ~3) == 0);
1077 assert(dvmGetFieldObject(ref, gDvm.offJavaLangRefReference_queue) != NULL);
1078 assert(dvmGetFieldObject(ref, gDvm.offJavaLangRefReference_queueNext) == NULL);
1079 /*
1080 * Set the enqueue bit in the bottom of the pointer. Assumes that
1081 * objects are 8-byte aligned.
1082 *
1083 * Note that we are adding the *Reference* (which is by definition
1084 * already black at this point) to this list; we're not adding the
1085 * referent (which has already been cleared).
1086 */
1087 table = &gDvm.gcHeap->referenceOperations;
1088 op = (Object *)((uintptr_t)ref | WORKER_ENQUEUE);
1089 if (!dvmHeapAddRefToLargeTable(table, op)) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001090 LOGE("no room for any more reference operations");
Carl Shapiro952e84a2010-05-06 14:35:29 -07001091 dvmAbort();
1092 }
1093}
1094
1095/*
1096 * Sets the referent field of a reference object to NULL.
1097 */
1098static void clearReference(Object *obj)
1099{
1100 dvmSetFieldObject(obj, gDvm.offJavaLangRefReference_referent, NULL);
1101}
1102
1103/*
1104 * Clears reference objects with white referents.
1105 */
1106void clearWhiteReferences(Object **list)
1107{
1108 size_t referentOffset, vmDataOffset;
1109 bool doSignal;
1110
1111 vmDataOffset = gDvm.offJavaLangRefReference_vmData;
1112 referentOffset = gDvm.offJavaLangRefReference_referent;
1113 doSignal = false;
1114 while (*list != NULL) {
1115 Object *ref = *list;
1116 JValue *field = dvmFieldPtr(ref, referentOffset);
1117 Object *referent = field->l;
1118 *list = dvmGetFieldObject(ref, vmDataOffset);
1119 assert(referent != NULL);
1120 if (isForward(referent->clazz)) {
1121 field->l = referent = getForward(referent->clazz);
1122 continue;
1123 }
1124 if (fromSpaceContains(referent)) {
1125 /* Referent is white, clear it. */
1126 clearReference(ref);
1127 if (isReferenceEnqueuable(ref)) {
1128 enqueueReference(ref);
1129 doSignal = true;
1130 }
1131 }
1132 }
1133 /*
1134 * If we cleared a reference with a reference queue we must notify
1135 * the heap worker to append the reference.
1136 */
1137 if (doSignal) {
1138 dvmSignalHeapWorker(false);
1139 }
1140 assert(*list == NULL);
1141}
1142
1143/*
1144 * Blackens referents subject to the soft reference preservation
1145 * policy.
1146 */
1147void preserveSoftReferences(Object **list)
1148{
1149 Object *ref;
1150 Object *prev, *next;
1151 size_t referentOffset, vmDataOffset;
1152 unsigned counter;
1153 bool white;
1154
1155 vmDataOffset = gDvm.offJavaLangRefReference_vmData;
1156 referentOffset = gDvm.offJavaLangRefReference_referent;
1157 counter = 0;
1158 prev = next = NULL;
1159 ref = *list;
1160 while (ref != NULL) {
1161 JValue *field = dvmFieldPtr(ref, referentOffset);
1162 Object *referent = field->l;
1163 next = dvmGetFieldObject(ref, vmDataOffset);
1164 assert(referent != NULL);
1165 if (isForward(referent->clazz)) {
1166 /* Referent is black. */
1167 field->l = referent = getForward(referent->clazz);
1168 white = false;
1169 } else {
1170 white = fromSpaceContains(referent);
1171 }
1172 if (!white && ((++counter) & 1)) {
1173 /* Referent is white and biased toward saving, gray it. */
1174 scavengeReference((Object **)(void *)&field->l);
1175 white = true;
1176 }
1177 if (white) {
1178 /* Referent is black, unlink it. */
1179 if (prev != NULL) {
1180 dvmSetFieldObject(ref, vmDataOffset, NULL);
1181 dvmSetFieldObject(prev, vmDataOffset, next);
1182 }
1183 } else {
1184 /* Referent is white, skip over it. */
1185 prev = ref;
1186 }
1187 ref = next;
1188 }
1189 /*
1190 * Restart the trace with the newly gray references added to the
1191 * root set.
1192 */
1193 scavengeBlockQueue();
1194}
1195
1196void processFinalizableReferences(void)
1197{
1198 HeapRefTable newPendingRefs;
1199 LargeHeapRefTable *finRefs = gDvm.gcHeap->finalizableRefs;
1200 Object **ref;
1201 Object **lastRef;
1202 size_t totalPendCount;
1203
1204 /*
1205 * All strongly, reachable objects are black.
1206 * Any white finalizable objects need to be finalized.
1207 */
1208
1209 /* Create a table that the new pending refs will
1210 * be added to.
1211 */
1212 if (!dvmHeapInitHeapRefTable(&newPendingRefs, 128)) {
1213 //TODO: mark all finalizable refs and hope that
1214 // we can schedule them next time. Watch out,
1215 // because we may be expecting to free up space
1216 // by calling finalizers.
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001217 LOG_REF("no room for pending finalizations\n");
Carl Shapiro952e84a2010-05-06 14:35:29 -07001218 dvmAbort();
1219 }
1220
1221 /*
1222 * Walk through finalizableRefs and move any white references to
1223 * the list of new pending refs.
1224 */
1225 totalPendCount = 0;
1226 while (finRefs != NULL) {
1227 Object **gapRef;
1228 size_t newPendCount = 0;
1229
1230 gapRef = ref = finRefs->refs.table;
1231 lastRef = finRefs->refs.nextEntry;
1232 while (ref < lastRef) {
1233 if (fromSpaceContains(*ref)) {
1234 if (!dvmHeapAddToHeapRefTable(&newPendingRefs, *ref)) {
1235 //TODO: add the current table and allocate
1236 // a new, smaller one.
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001237 LOG_REF("no room for any more pending finalizations: %zd\n",
Carl Shapiro952e84a2010-05-06 14:35:29 -07001238 dvmHeapNumHeapRefTableEntries(&newPendingRefs));
1239 dvmAbort();
1240 }
1241 newPendCount++;
1242 } else {
1243 /* This ref is black, so will remain on finalizableRefs.
1244 */
1245 if (newPendCount > 0) {
1246 /* Copy it up to fill the holes.
1247 */
1248 *gapRef++ = *ref;
1249 } else {
1250 /* No holes yet; don't bother copying.
1251 */
1252 gapRef++;
1253 }
1254 }
1255 ref++;
1256 }
1257 finRefs->refs.nextEntry = gapRef;
1258 //TODO: if the table is empty when we're done, free it.
1259 totalPendCount += newPendCount;
1260 finRefs = finRefs->next;
1261 }
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001262 LOG_REF("%zd finalizers triggered.\n", totalPendCount);
Carl Shapiro952e84a2010-05-06 14:35:29 -07001263 if (totalPendCount == 0) {
1264 /* No objects required finalization.
1265 * Free the empty temporary table.
1266 */
1267 dvmClearReferenceTable(&newPendingRefs);
1268 return;
1269 }
1270
1271 /* Add the new pending refs to the main list.
1272 */
1273 if (!dvmHeapAddTableToLargeTable(&gDvm.gcHeap->pendingFinalizationRefs,
1274 &newPendingRefs))
1275 {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001276 LOG_REF("can't insert new pending finalizations\n");
Carl Shapiro952e84a2010-05-06 14:35:29 -07001277 dvmAbort();
1278 }
1279
1280 //TODO: try compacting the main list with a memcpy loop
1281
1282 /* Blacken the refs we just moved; we don't want them or their
1283 * children to get swept yet.
1284 */
1285 ref = newPendingRefs.table;
1286 lastRef = newPendingRefs.nextEntry;
1287 assert(ref < lastRef);
1288 HPROF_SET_GC_SCAN_STATE(HPROF_ROOT_FINALIZING, 0);
1289 while (ref < lastRef) {
1290 scavengeReference(ref);
1291 ref++;
1292 }
1293 HPROF_CLEAR_GC_SCAN_STATE();
1294 scavengeBlockQueue();
1295 dvmSignalHeapWorker(false);
Carl Shapirod28668c2010-04-15 16:10:00 -07001296}
1297
Carl Shapirod28668c2010-04-15 16:10:00 -07001298/*
1299 * If a reference points to from-space and has been forwarded, we snap
1300 * the pointer to its new to-space address. If the reference points
1301 * to an unforwarded from-space address we must enqueue the reference
1302 * for later processing. TODO: implement proper reference processing
1303 * and move the referent scavenging elsewhere.
1304 */
Carl Shapiro952e84a2010-05-06 14:35:29 -07001305static void scavengeReferenceObject(Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001306{
Carl Shapiro952e84a2010-05-06 14:35:29 -07001307 Object *referent;
1308 Object **queue;
1309 size_t referentOffset, vmDataOffset;
1310
Carl Shapirod28668c2010-04-15 16:10:00 -07001311 assert(obj != NULL);
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001312 LOG_SCAV("scavengeReferenceObject(obj=%p),'%s'", obj, obj->clazz->descriptor);
Carl Shapiro2396fda2010-05-03 20:14:14 -07001313 scavengeDataObject(obj);
Carl Shapiro952e84a2010-05-06 14:35:29 -07001314 referentOffset = gDvm.offJavaLangRefReference_referent;
1315 referent = dvmGetFieldObject(obj, referentOffset);
1316 if (referent == NULL || toSpaceContains(referent)) {
1317 return;
Carl Shapirod28668c2010-04-15 16:10:00 -07001318 }
Carl Shapiro952e84a2010-05-06 14:35:29 -07001319 if (isSoftReference(obj)) {
1320 queue = &gDvm.gcHeap->softReferences;
1321 } else if (isWeakReference(obj)) {
1322 queue = &gDvm.gcHeap->weakReferences;
1323 } else {
1324 assert(isPhantomReference(obj));
1325 queue = &gDvm.gcHeap->phantomReferences;
1326 }
1327 vmDataOffset = gDvm.offJavaLangRefReference_vmData;
Carl Shapiro7800c092010-05-11 13:46:29 -07001328 dvmSetFieldObject(obj, vmDataOffset, *queue);
Carl Shapiro952e84a2010-05-06 14:35:29 -07001329 *queue = obj;
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001330 LOG_SCAV("scavengeReferenceObject: enqueueing %p", obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001331}
1332
1333/*
1334 * Data object scavenging.
1335 */
Carl Shapiro952e84a2010-05-06 14:35:29 -07001336static void scavengeDataObject(Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001337{
1338 ClassObject *clazz;
Carl Shapirod28668c2010-04-15 16:10:00 -07001339 int i;
1340
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001341 // LOG_SCAV("scavengeDataObject(obj=%p)", obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001342 assert(obj != NULL);
Carl Shapiro952e84a2010-05-06 14:35:29 -07001343 assert(obj->clazz != NULL);
1344 assert(obj->clazz->objectSize != 0);
1345 assert(toSpaceContains(obj));
Carl Shapirod28668c2010-04-15 16:10:00 -07001346 /* Scavenge the class object. */
Carl Shapiro952e84a2010-05-06 14:35:29 -07001347 clazz = obj->clazz;
Carl Shapirod28668c2010-04-15 16:10:00 -07001348 scavengeReference((Object **) obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001349 /* Scavenge instance fields. */
1350 if (clazz->refOffsets != CLASS_WALK_SUPER) {
1351 size_t refOffsets = clazz->refOffsets;
1352 while (refOffsets != 0) {
1353 size_t rshift = CLZ(refOffsets);
1354 size_t offset = CLASS_OFFSET_FROM_CLZ(rshift);
1355 Object **ref = (Object **)((u1 *)obj + offset);
1356 scavengeReference(ref);
1357 refOffsets &= ~(CLASS_HIGH_BIT >> rshift);
1358 }
1359 } else {
1360 for (; clazz != NULL; clazz = clazz->super) {
1361 InstField *field = clazz->ifields;
1362 for (i = 0; i < clazz->ifieldRefCount; ++i, ++field) {
1363 size_t offset = field->byteOffset;
1364 Object **ref = (Object **)((u1 *)obj + offset);
1365 scavengeReference(ref);
1366 }
1367 }
1368 }
Carl Shapiro2396fda2010-05-03 20:14:14 -07001369}
1370
1371static Object *transportObject(const Object *fromObj)
1372{
1373 Object *toObj;
1374 size_t allocSize, copySize;
1375
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001376 LOG_TRAN("transportObject(fromObj=%p) allocBlocks=%zu",
Carl Shapiro2396fda2010-05-03 20:14:14 -07001377 fromObj,
1378 gDvm.gcHeap->heapSource->allocBlocks);
1379 assert(fromObj != NULL);
Carl Shapiro952e84a2010-05-06 14:35:29 -07001380 assert(fromSpaceContains(fromObj));
Carl Shapiro2396fda2010-05-03 20:14:14 -07001381 allocSize = copySize = objectSize(fromObj);
1382 if (LW_HASH_STATE(fromObj->lock) != LW_HASH_STATE_UNHASHED) {
1383 /*
1384 * The object has been hashed or hashed and moved. We must
1385 * reserve an additional word for a hash code.
1386 */
1387 allocSize += sizeof(u4);
1388 }
1389 if (LW_HASH_STATE(fromObj->lock) == LW_HASH_STATE_HASHED_AND_MOVED) {
1390 /*
1391 * The object has its hash code allocated. Ensure the hash
1392 * code is copied along with the instance data.
1393 */
1394 copySize += sizeof(u4);
1395 }
1396 /* TODO(cshapiro): don't copy, re-map large data objects. */
1397 assert(copySize <= allocSize);
1398 toObj = allocateGray(allocSize);
1399 assert(toObj != NULL);
Carl Shapiro952e84a2010-05-06 14:35:29 -07001400 assert(toSpaceContains(toObj));
Carl Shapiro2396fda2010-05-03 20:14:14 -07001401 memcpy(toObj, fromObj, copySize);
1402 if (LW_HASH_STATE(fromObj->lock) == LW_HASH_STATE_HASHED) {
1403 /*
1404 * The object has had its hash code exposed. Append it to the
1405 * instance and set a bit so we know to look for it there.
1406 */
1407 *(u4 *)(((char *)toObj) + copySize) = (u4)fromObj >> 3;
1408 toObj->lock |= LW_HASH_STATE_HASHED_AND_MOVED << LW_HASH_STATE_SHIFT;
1409 }
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001410 LOG_TRAN("transportObject: from %p/%zu to %p/%zu (%zu,%zu) %s",
1411 fromObj, addressToBlock(gDvm.gcHeap->heapSource,fromObj),
1412 toObj, addressToBlock(gDvm.gcHeap->heapSource,toObj),
1413 copySize, allocSize, copySize < allocSize ? "DIFFERENT" : "");
Carl Shapiro2396fda2010-05-03 20:14:14 -07001414 return toObj;
Carl Shapirod28668c2010-04-15 16:10:00 -07001415}
1416
1417/*
1418 * Generic reference scavenging.
1419 */
1420
1421/*
1422 * Given a reference to an object, the scavenge routine will gray the
1423 * reference. Any objects pointed to by the scavenger object will be
1424 * transported to new space and a forwarding pointer will be installed
1425 * in the header of the object.
1426 */
1427
1428/*
1429 * Blacken the given pointer. If the pointer is in from space, it is
1430 * transported to new space. If the object has a forwarding pointer
1431 * installed it has already been transported and the referent is
1432 * snapped to the new address.
1433 */
Carl Shapiro2396fda2010-05-03 20:14:14 -07001434static void scavengeReference(Object **obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001435{
1436 ClassObject *clazz;
Carl Shapiro2396fda2010-05-03 20:14:14 -07001437 Object *fromObj, *toObj;
Carl Shapirod28668c2010-04-15 16:10:00 -07001438 uintptr_t word;
1439
1440 assert(obj);
1441
Carl Shapiro2396fda2010-05-03 20:14:14 -07001442 if (*obj == NULL) return;
Carl Shapirod28668c2010-04-15 16:10:00 -07001443
1444 assert(dvmIsValidObject(*obj));
1445
1446 /* The entire block is black. */
Carl Shapiro952e84a2010-05-06 14:35:29 -07001447 if (toSpaceContains(*obj)) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001448 LOG_SCAV("scavengeReference skipping pinned object @ %p", *obj);
Carl Shapiro2396fda2010-05-03 20:14:14 -07001449 return;
Carl Shapirod28668c2010-04-15 16:10:00 -07001450 }
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001451 LOG_SCAV("scavengeReference(*obj=%p)", *obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001452
Carl Shapiro952e84a2010-05-06 14:35:29 -07001453 assert(fromSpaceContains(*obj));
Carl Shapirod28668c2010-04-15 16:10:00 -07001454
1455 clazz = (*obj)->clazz;
1456
1457 if (isForward(clazz)) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001458 // LOG_SCAV("forwarding %p @ %p to %p", *obj, obj, (void *)((uintptr_t)clazz & ~0x1));
Carl Shapirod28668c2010-04-15 16:10:00 -07001459 *obj = (Object *)getForward(clazz);
Carl Shapiro2396fda2010-05-03 20:14:14 -07001460 return;
Carl Shapirod28668c2010-04-15 16:10:00 -07001461 }
Carl Shapiro2396fda2010-05-03 20:14:14 -07001462 fromObj = *obj;
1463 if (clazz == NULL) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001464 // LOG_SCAV("scavangeReference %p has a NULL class object", fromObj);
Carl Shapiro2396fda2010-05-03 20:14:14 -07001465 assert(!"implemented");
1466 toObj = NULL;
1467 } else if (clazz == gDvm.unlinkedJavaLangClass) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001468 // LOG_SCAV("scavangeReference %p is an unlinked class object", fromObj);
Carl Shapiro2396fda2010-05-03 20:14:14 -07001469 assert(!"implemented");
1470 toObj = NULL;
1471 } else {
1472 toObj = transportObject(fromObj);
1473 }
1474 setForward(toObj, fromObj);
1475 *obj = (Object *)toObj;
Carl Shapirod28668c2010-04-15 16:10:00 -07001476}
1477
1478static void verifyReference(const void *obj)
1479{
1480 HeapSource *heapSource;
1481 size_t block;
1482 char space;
1483
1484 if (obj == NULL) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001485 LOG_VER("verifyReference(obj=%p)", obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001486 return;
1487 }
1488 heapSource = gDvm.gcHeap->heapSource;
1489 block = addressToBlock(heapSource, obj);
1490 space = heapSource->blockSpace[block];
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001491 LOG_VER("verifyReference(obj=%p),block=%zu,space=%d", obj, block, space);
Carl Shapirod28668c2010-04-15 16:10:00 -07001492 assert(!((uintptr_t)obj & 7));
Carl Shapiro952e84a2010-05-06 14:35:29 -07001493 assert(toSpaceContains(obj));
Carl Shapirod28668c2010-04-15 16:10:00 -07001494 assert(dvmIsValidObject(obj));
1495}
1496
1497/*
1498 * Generic object scavenging.
1499 */
Carl Shapiro2396fda2010-05-03 20:14:14 -07001500static void scavengeObject(Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001501{
1502 ClassObject *clazz;
Carl Shapirod28668c2010-04-15 16:10:00 -07001503
1504 assert(obj != NULL);
Carl Shapiro952e84a2010-05-06 14:35:29 -07001505 assert(obj->clazz != NULL);
1506 assert(!((uintptr_t)obj->clazz & 0x1));
1507 assert(obj->clazz != gDvm.unlinkedJavaLangClass);
Carl Shapirod28668c2010-04-15 16:10:00 -07001508 clazz = obj->clazz;
Carl Shapirod28668c2010-04-15 16:10:00 -07001509 if (clazz == gDvm.classJavaLangClass) {
Carl Shapiro2396fda2010-05-03 20:14:14 -07001510 scavengeClassObject((ClassObject *)obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001511 } else if (IS_CLASS_FLAG_SET(clazz, CLASS_ISARRAY)) {
Carl Shapiro2396fda2010-05-03 20:14:14 -07001512 scavengeArrayObject((ArrayObject *)obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001513 } else if (IS_CLASS_FLAG_SET(clazz, CLASS_ISREFERENCE)) {
Carl Shapiro952e84a2010-05-06 14:35:29 -07001514 scavengeReferenceObject(obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001515 } else {
Carl Shapiro952e84a2010-05-06 14:35:29 -07001516 scavengeDataObject(obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001517 }
Carl Shapirod28668c2010-04-15 16:10:00 -07001518}
1519
1520/*
1521 * External root scavenging routines.
1522 */
1523
1524static void scavengeHashTable(HashTable *table)
1525{
1526 HashEntry *entry;
1527 void *obj;
1528 int i;
1529
1530 if (table == NULL) {
1531 return;
1532 }
1533 dvmHashTableLock(table);
1534 for (i = 0; i < table->tableSize; ++i) {
1535 entry = &table->pEntries[i];
1536 obj = entry->data;
1537 if (obj == NULL || obj == HASH_TOMBSTONE) {
1538 continue;
1539 }
1540 scavengeReference((Object **)(void *)&entry->data);
1541 }
1542 dvmHashTableUnlock(table);
1543}
1544
1545static void pinHashTableEntries(HashTable *table)
1546{
1547 HashEntry *entry;
1548 void *obj;
1549 int i;
1550
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001551 LOG_PIN(">>> pinHashTableEntries(table=%p)", table);
Carl Shapirod28668c2010-04-15 16:10:00 -07001552 if (table == NULL) {
1553 return;
1554 }
1555 dvmHashTableLock(table);
1556 for (i = 0; i < table->tableSize; ++i) {
1557 entry = &table->pEntries[i];
1558 obj = entry->data;
1559 if (obj == NULL || obj == HASH_TOMBSTONE) {
1560 continue;
1561 }
1562 pinObject(entry->data);
1563 }
1564 dvmHashTableUnlock(table);
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001565 LOG_PIN("<<< pinHashTableEntries(table=%p)", table);
Carl Shapirod28668c2010-04-15 16:10:00 -07001566}
1567
1568static void pinPrimitiveClasses(void)
1569{
1570 size_t length;
1571 size_t i;
1572
1573 length = ARRAYSIZE(gDvm.primitiveClass);
1574 for (i = 0; i < length; i++) {
1575 if (gDvm.primitiveClass[i] != NULL) {
1576 pinObject((Object *)gDvm.primitiveClass[i]);
1577 }
1578 }
1579}
1580
1581/*
1582 * Scavenge interned strings. Permanent interned strings will have
1583 * been pinned and are therefore ignored. Non-permanent strings that
1584 * have been forwarded are snapped. All other entries are removed.
1585 */
1586static void scavengeInternedStrings(void)
1587{
1588 HashTable *table;
1589 HashEntry *entry;
1590 Object *obj;
1591 int i;
1592
1593 table = gDvm.internedStrings;
1594 if (table == NULL) {
1595 return;
1596 }
1597 dvmHashTableLock(table);
1598 for (i = 0; i < table->tableSize; ++i) {
1599 entry = &table->pEntries[i];
1600 obj = (Object *)entry->data;
1601 if (obj == NULL || obj == HASH_TOMBSTONE) {
1602 continue;
1603 } else if (!isPermanentString((StringObject *)obj)) {
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001604 // LOG_SCAV("entry->data=%p", entry->data);
1605 LOG_SCAV(">>> string obj=%p", entry->data);
Carl Shapirod28668c2010-04-15 16:10:00 -07001606 /* TODO(cshapiro): detach white string objects */
1607 scavengeReference((Object **)(void *)&entry->data);
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001608 LOG_SCAV("<<< string obj=%p", entry->data);
Carl Shapirod28668c2010-04-15 16:10:00 -07001609 }
1610 }
1611 dvmHashTableUnlock(table);
1612}
1613
1614static void pinInternedStrings(void)
1615{
1616 HashTable *table;
1617 HashEntry *entry;
1618 Object *obj;
1619 int i;
1620
1621 table = gDvm.internedStrings;
1622 if (table == NULL) {
1623 return;
1624 }
1625 dvmHashTableLock(table);
1626 for (i = 0; i < table->tableSize; ++i) {
1627 entry = &table->pEntries[i];
1628 obj = (Object *)entry->data;
1629 if (obj == NULL || obj == HASH_TOMBSTONE) {
1630 continue;
1631 } else if (isPermanentString((StringObject *)obj)) {
1632 obj = (Object *)getPermanentString((StringObject*)obj);
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001633 LOG_PROM(">>> pin string obj=%p", obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001634 pinObject(obj);
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001635 LOG_PROM("<<< pin string obj=%p", obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001636 }
1637 }
1638 dvmHashTableUnlock(table);
1639}
1640
Carl Shapirod28668c2010-04-15 16:10:00 -07001641/*
1642 * At present, reference tables contain references that must not be
1643 * moved by the collector. Instead of scavenging each reference in
1644 * the table we pin each referenced object.
1645 */
Carl Shapiro583d64c2010-05-04 10:44:47 -07001646static void pinReferenceTable(const ReferenceTable *table)
Carl Shapirod28668c2010-04-15 16:10:00 -07001647{
1648 Object **entry;
1649 int i;
1650
1651 assert(table != NULL);
1652 assert(table->table != NULL);
1653 assert(table->nextEntry != NULL);
1654 for (entry = table->table; entry < table->nextEntry; ++entry) {
1655 assert(entry != NULL);
1656 assert(!isForward(*entry));
1657 pinObject(*entry);
1658 }
1659}
1660
1661static void verifyReferenceTable(const ReferenceTable *table)
1662{
1663 Object **entry;
1664 int i;
1665
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001666 LOG_VER(">>> verifyReferenceTable(table=%p)", table);
Carl Shapirod28668c2010-04-15 16:10:00 -07001667 for (entry = table->table; entry < table->nextEntry; ++entry) {
1668 assert(entry != NULL);
1669 assert(!isForward(*entry));
1670 verifyReference(*entry);
1671 }
Carl Shapiro8bb533e2010-05-06 15:35:27 -07001672 LOG_VER("<<< verifyReferenceTable(table=%p)", table);
Carl Shapirod28668c2010-04-15 16:10:00 -07001673}
1674
Carl Shapiro7800c092010-05-11 13:46:29 -07001675static void scavengeLargeHeapRefTable(LargeHeapRefTable *table, bool stripLowBits)
Carl Shapirod28668c2010-04-15 16:10:00 -07001676{
Carl Shapirod28668c2010-04-15 16:10:00 -07001677 for (; table != NULL; table = table->next) {
Carl Shapiro7800c092010-05-11 13:46:29 -07001678 Object **ref = table->refs.table;
1679 for (; ref < table->refs.nextEntry; ++ref) {
1680 if (stripLowBits) {
1681 Object *obj = (Object *)((uintptr_t)*ref & ~3);
1682 scavengeReference(&obj);
1683 *ref = (Object *)((uintptr_t)obj | ((uintptr_t)*ref & 3));
1684 } else {
1685 scavengeReference(ref);
Carl Shapirod28668c2010-04-15 16:10:00 -07001686 }
Carl Shapiro7800c092010-05-11 13:46:29 -07001687 }
1688 }
1689}
1690
1691static void verifyLargeHeapRefTable(LargeHeapRefTable *table, bool stripLowBits)
1692{
1693 for (; table != NULL; table = table->next) {
1694 Object **ref = table->refs.table;
1695 for (; ref < table->refs.nextEntry; ++ref) {
1696 if (stripLowBits) {
1697 dvmVerifyObject((Object *)((uintptr_t)*ref & ~3));
1698 } else {
1699 dvmVerifyObject(*ref);
1700 }
Carl Shapirod28668c2010-04-15 16:10:00 -07001701 }
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 Shapiro7800c092010-05-11 13:46:29 -07002514 scavengeLargeHeapRefTable(gcHeap->referenceOperations, true);
Carl Shapirod28668c2010-04-15 16:10:00 -07002515
Carl Shapiro8bb533e2010-05-06 15:35:27 -07002516 LOG_SCAV("Scavenging gDvm.gcHeap->pendingFinalizationRefs");
Carl Shapiro7800c092010-05-11 13:46:29 -07002517 scavengeLargeHeapRefTable(gcHeap->pendingFinalizationRefs, false);
Carl Shapirod28668c2010-04-15 16:10:00 -07002518
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 Shapirof5718252010-05-11 20:55:13 -07002565 dvmVerifyRoots();
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{
Carl Shapiro703a2f32010-05-12 23:11:37 -07002625 *numFreed = 0;
2626 *sizeFreed = 0;
Carl Shapirod28668c2010-04-15 16:10:00 -07002627 /* do nothing */
2628}
2629
2630void dvmMarkObjectNonNull(const Object *obj)
2631{
2632 assert(!"implemented");
2633}