blob: dd8485f13abfef2246df46c5a567613c494dd8d4 [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
80 * start of a garbage collection. By virtue of this trick, marking
81 * 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
126#if 1
127#define LOG_ALLOC LOGI
128#define LOG_SCAVENGE LOGI
129#define LOG_TRANSPORT LOGI
130#define LOG_PROMOTE LOGI
131#define LOG_VERIFY LOGI
132#else
133#define LOG_ALLOC(...) ((void *)0)
134#define LOG_SCAVENGE(...) ((void *)0)
135#define LOG_TRANSPORT(...) ((void *)0)
136#define LOG_PROMOTE(...) ((void *)0)
137#define LOG_VERIFY(...) ((void *)0)
138#endif
139
140static void enqueueBlock(HeapSource *heapSource, size_t block);
Carl Shapiro2396fda2010-05-03 20:14:14 -0700141static void scavengeReference(Object **obj);
Carl Shapirod28668c2010-04-15 16:10:00 -0700142static void verifyReference(const void *obj);
143static void printHeapBitmap(const HeapBitmap *bitmap);
144static void printHeapBitmapSxS(const HeapBitmap *b1, const HeapBitmap *b2);
145static bool isToSpace(const void *addr);
146static bool isFromSpace(const void *addr);
147static size_t sumHeapBitmap(const HeapBitmap *bitmap);
Carl Shapiro2396fda2010-05-03 20:14:14 -0700148static size_t objectSize(const Object *obj);
149static void scavengeDataObject(DataObject *obj);
Carl Shapirod28668c2010-04-15 16:10:00 -0700150
151/*
152 * We use 512-byte blocks.
153 */
154enum { BLOCK_SHIFT = 9 };
155enum { BLOCK_SIZE = 1 << BLOCK_SHIFT };
156
157/*
158 * Space identifiers, stored into the blockSpace array.
159 */
160enum {
161 BLOCK_FREE = 0,
162 BLOCK_FROM_SPACE = 1,
163 BLOCK_TO_SPACE = 2,
164 BLOCK_CONTINUED = 7
165};
166
167/*
168 * Alignment for all allocations, in bytes.
169 */
170enum { ALLOC_ALIGNMENT = 8 };
171
172/*
173 * Sentinel value for the queue end.
174 */
175#define QUEUE_TAIL (~(size_t)0)
176
177struct HeapSource {
178
179 /* The base address of backing store. */
180 u1 *blockBase;
181
182 /* Total number of blocks available for allocation. */
183 size_t totalBlocks;
184 size_t allocBlocks;
185
186 /*
187 * The scavenger work queue. Implemented as an array of index
188 * values into the queue.
189 */
190 size_t *blockQueue;
191
192 /*
193 * Base and limit blocks. Basically the shifted start address of
194 * the block. We convert blocks to a relative number when
195 * indexing in the block queue. TODO: make the block queue base
196 * relative rather than the index into the block queue.
197 */
198 size_t baseBlock, limitBlock;
199
200 size_t queueHead;
201 size_t queueTail;
202 size_t queueSize;
203
204 /* The space of the current block 0 (free), 1 or 2. */
205 char *blockSpace;
206
207 /* Start of free space in the current block. */
208 u1 *allocPtr;
209 /* Exclusive limit of free space in the current block. */
210 u1 *allocLimit;
211
212 HeapBitmap allocBits;
213
214 /*
215 * Singly-linked lists of live Reference objects. Built when
216 * scavenging, threaded through the Reference.vmData field.
217 */
218 DataObject *softReferenceList;
219 DataObject *weakReferenceList;
220 DataObject *phantomReferenceList;
221
222 /*
223 * The starting size of the heap. This value is the same as the
224 * value provided to the -Xms flag.
225 */
226 size_t minimumSize;
227
228 /*
229 * The maximum size of the heap. This value is the same as the
230 * -Xmx flag.
231 */
232 size_t maximumSize;
233
234 /*
235 * The current, committed size of the heap. At present, this is
236 * equivalent to the maximumSize.
237 */
238 size_t currentSize;
239
240 size_t bytesAllocated;
241};
242
243static unsigned long alignDown(unsigned long x, unsigned long n)
244{
245 return x & -n;
246}
247
248static unsigned long alignUp(unsigned long x, unsigned long n)
249{
250 return alignDown(x + (n - 1), n);
251}
252
253static void describeBlocks(const HeapSource *heapSource)
254{
255 size_t i;
256
257 for (i = 0; i < heapSource->totalBlocks; ++i) {
258 if ((i % 32) == 0) putchar('\n');
259 printf("%d ", heapSource->blockSpace[i]);
260 }
261 putchar('\n');
262}
263
264/*
265 * Virtual memory interface.
266 */
267
268static void *virtualAlloc(size_t length)
269{
270 void *addr;
271 int flags, prot;
272
273 flags = MAP_PRIVATE | MAP_ANONYMOUS;
274 prot = PROT_READ | PROT_WRITE;
275 addr = mmap(NULL, length, prot, flags, -1, 0);
276 if (addr == MAP_FAILED) {
277 LOGE_HEAP("mmap: %s", strerror(errno));
278 addr = NULL;
279 }
280 return addr;
281}
282
283static void virtualFree(void *addr, size_t length)
284{
285 int res;
286
287 assert(addr != NULL);
288 assert((uintptr_t)addr % SYSTEM_PAGE_SIZE == 0);
289 res = munmap(addr, length);
290 if (res == -1) {
291 LOGE_HEAP("munmap: %s", strerror(errno));
292 }
293}
294
295static int isValidAddress(const HeapSource *heapSource, const u1 *addr)
296{
297 size_t block;
298
299 block = (uintptr_t)addr >> BLOCK_SHIFT;
300 return heapSource->baseBlock <= block &&
301 heapSource->limitBlock > block;
302}
303
304/*
305 * Iterate over the block map looking for a contiguous run of free
306 * blocks.
307 */
308static void *allocateBlocks(HeapSource *heapSource, size_t blocks)
309{
310 void *addr;
311 size_t allocBlocks, totalBlocks;
312 size_t i, j;
313
314 allocBlocks = heapSource->allocBlocks;
315 totalBlocks = heapSource->totalBlocks;
316 /* Check underflow. */
317 assert(blocks != 0);
318 /* Check overflow. */
319 if (allocBlocks + blocks > totalBlocks / 2) {
320 return NULL;
321 }
322 /* Scan block map. */
323 for (i = 0; i < totalBlocks; ++i) {
324 /* Check fit. */
325 for (j = 0; j < blocks; ++j) { /* runs over totalBlocks */
326 if (heapSource->blockSpace[i+j] != BLOCK_FREE) {
327 break;
328 }
329 }
330 /* No fit? */
331 if (j != blocks) {
332 i += j;
333 continue;
334 }
335 /* Fit, allocate. */
336 heapSource->blockSpace[i] = BLOCK_TO_SPACE; /* why to-space? */
337 for (j = 1; j < blocks; ++j) {
338 heapSource->blockSpace[i+j] = BLOCK_CONTINUED;
339 }
340 heapSource->allocBlocks += blocks;
341 addr = &heapSource->blockBase[i*BLOCK_SIZE];
342 memset(addr, 0, blocks*BLOCK_SIZE);
343 /* Collecting? */
344 if (heapSource->queueHead != QUEUE_TAIL) {
345 LOG_ALLOC("allocateBlocks allocBlocks=%zu,block#=%zu", heapSource->allocBlocks, i);
346 /*
347 * This allocated was on behalf of the transporter when it
348 * shaded a white object gray. We enqueue the block so
349 * the scavenger can further shade the gray objects black.
350 */
351 enqueueBlock(heapSource, i);
352 }
353
354 return addr;
355 }
356 /* Insufficient space, fail. */
357 LOGE("Insufficient space, %zu blocks, %zu blocks allocated and %zu bytes allocated",
358 heapSource->totalBlocks,
359 heapSource->allocBlocks,
360 heapSource->bytesAllocated);
361 return NULL;
362}
363
364/* Converts an absolute address to a relative block number. */
365static size_t addressToBlock(const HeapSource *heapSource, const void *addr)
366{
367 assert(heapSource != NULL);
368 assert(isValidAddress(heapSource, addr));
369 return (((uintptr_t)addr) >> BLOCK_SHIFT) - heapSource->baseBlock;
370}
371
372/* Converts a relative block number to an absolute address. */
373static u1 *blockToAddress(const HeapSource *heapSource, size_t block)
374{
375 u1 *addr;
376
377 addr = (u1 *) (((uintptr_t) heapSource->baseBlock + block) * BLOCK_SIZE);
378 assert(isValidAddress(heapSource, addr));
379 return addr;
380}
381
382static void clearBlock(HeapSource *heapSource, size_t block)
383{
384 u1 *addr;
385 size_t i;
386
387 assert(heapSource != NULL);
388 assert(block < heapSource->totalBlocks);
389 addr = heapSource->blockBase + block*BLOCK_SIZE;
390 memset(addr, 0xCC, BLOCK_SIZE);
391 for (i = 0; i < BLOCK_SIZE; i += 8) {
392 dvmHeapBitmapClearObjectBit(&heapSource->allocBits, addr + i);
393 }
394}
395
396static void clearFromSpace(HeapSource *heapSource)
397{
398 size_t i, count;
399
400 assert(heapSource != NULL);
401 i = count = 0;
402 while (i < heapSource->totalBlocks) {
403 if (heapSource->blockSpace[i] != BLOCK_FROM_SPACE) {
404 ++i;
405 continue;
406 }
407 heapSource->blockSpace[i] = BLOCK_FREE;
408 clearBlock(heapSource, i);
409 ++i;
410 ++count;
411 while (i < heapSource->totalBlocks &&
412 heapSource->blockSpace[i] == BLOCK_CONTINUED) {
413 heapSource->blockSpace[i] = BLOCK_FREE;
414 clearBlock(heapSource, i);
415 ++i;
416 ++count;
417 }
418 }
419 LOGI("freed %zu blocks (%zu bytes)", count, count*BLOCK_SIZE);
420}
421
422/*
423 * Appends the given block to the block queue. The block queue is
424 * processed in-order by the scavenger.
425 */
426static void enqueueBlock(HeapSource *heapSource, size_t block)
427{
428 assert(heapSource != NULL);
429 assert(block < heapSource->totalBlocks);
430 if (heapSource->queueHead != QUEUE_TAIL) {
431 heapSource->blockQueue[heapSource->queueTail] = block;
432 } else {
433 heapSource->queueHead = block;
434 }
435 heapSource->blockQueue[block] = QUEUE_TAIL;
436 heapSource->queueTail = block;
437 ++heapSource->queueSize;
438}
439
440/*
441 * Grays all objects within the block corresponding to the given
442 * address.
443 */
444static void promoteBlockByAddr(HeapSource *heapSource, const void *addr)
445{
446 size_t block;
447
448 block = addressToBlock(heapSource, (const u1 *)addr);
449 if (heapSource->blockSpace[block] != BLOCK_TO_SPACE) {
450 // LOGI("promoting block %zu %d @ %p", block, heapSource->blockSpace[block], obj);
451 heapSource->blockSpace[block] = BLOCK_TO_SPACE;
452 enqueueBlock(heapSource, block);
453 /* TODO(cshapiro): count continued blocks?*/
454 heapSource->allocBlocks += 1;
455 } else {
456 // LOGI("NOT promoting block %zu %d @ %p", block, heapSource->blockSpace[block], obj);
457 }
458}
459
460GcHeap *dvmHeapSourceStartup(size_t startSize, size_t absoluteMaxSize)
461{
462 GcHeap* gcHeap;
463 HeapSource *heapSource;
464
465 assert(startSize <= absoluteMaxSize);
466
467 heapSource = malloc(sizeof(*heapSource));
468 assert(heapSource != NULL);
469 memset(heapSource, 0, sizeof(*heapSource));
470
471 heapSource->minimumSize = alignUp(startSize, BLOCK_SIZE);
472 heapSource->maximumSize = alignUp(absoluteMaxSize, BLOCK_SIZE);
473
474 heapSource->currentSize = heapSource->maximumSize;
475
476 /* Allocate underlying storage for blocks. */
477 heapSource->blockBase = virtualAlloc(heapSource->maximumSize);
478 assert(heapSource->blockBase != NULL);
479 heapSource->baseBlock = (uintptr_t) heapSource->blockBase >> BLOCK_SHIFT;
480 heapSource->limitBlock = ((uintptr_t) heapSource->blockBase + heapSource->maximumSize) >> BLOCK_SHIFT;
481
482 heapSource->allocBlocks = 0;
483 heapSource->totalBlocks = (heapSource->limitBlock - heapSource->baseBlock);
484
485 assert(heapSource->totalBlocks = heapSource->maximumSize / BLOCK_SIZE);
486
487 {
488 size_t size = sizeof(heapSource->blockQueue[0]);
489 heapSource->blockQueue = malloc(heapSource->totalBlocks*size);
490 assert(heapSource->blockQueue != NULL);
491 memset(heapSource->blockQueue, 0xCC, heapSource->totalBlocks*size);
492 heapSource->queueHead = QUEUE_TAIL;
493 }
494
495 /* Byte indicating space residence or free status of block. */
496 {
497 size_t size = sizeof(heapSource->blockSpace[0]);
498 heapSource->blockSpace = malloc(heapSource->totalBlocks*size);
499 assert(heapSource->blockSpace != NULL);
500 memset(heapSource->blockSpace, 0, heapSource->totalBlocks*size);
501 }
502
503 dvmHeapBitmapInit(&heapSource->allocBits,
504 heapSource->blockBase,
505 heapSource->maximumSize,
506 "blockBase");
507
508 /* Initialize allocation pointers. */
509 heapSource->allocPtr = allocateBlocks(heapSource, 1);
510 heapSource->allocLimit = heapSource->allocPtr + BLOCK_SIZE;
511
512 gcHeap = malloc(sizeof(*gcHeap));
513 assert(gcHeap != NULL);
514 memset(gcHeap, 0, sizeof(*gcHeap));
515 gcHeap->heapSource = heapSource;
516
517 return gcHeap;
518}
519
520/*
521 * Perform any required heap initializations after forking from the
522 * zygote process. This is a no-op for the time being. Eventually
523 * this will demarcate the shared region of the heap.
524 */
525bool dvmHeapSourceStartupAfterZygote(void)
526{
527 return true;
528}
529
530bool dvmHeapSourceStartupBeforeFork(void)
531{
532 assert(!"implemented");
533 return false;
534}
535
536void dvmHeapSourceShutdown(GcHeap **gcHeap)
537{
538 if (*gcHeap == NULL || (*gcHeap)->heapSource == NULL)
539 return;
540 virtualFree((*gcHeap)->heapSource->blockBase,
541 (*gcHeap)->heapSource->maximumSize);
542 free((*gcHeap)->heapSource);
543 (*gcHeap)->heapSource = NULL;
544 free(*gcHeap);
545 *gcHeap = NULL;
546}
547
548size_t dvmHeapSourceGetValue(enum HeapSourceValueSpec spec,
549 size_t perHeapStats[],
550 size_t arrayLen)
551{
552 HeapSource *heapSource;
553 size_t value;
554
555 heapSource = gDvm.gcHeap->heapSource;
556 switch (spec) {
557 case HS_EXTERNAL_BYTES_ALLOCATED:
558 value = 0;
559 break;
560 case HS_EXTERNAL_LIMIT:
561 value = 0;
562 break;
563 case HS_FOOTPRINT:
564 value = heapSource->maximumSize;
565 break;
566 case HS_ALLOWED_FOOTPRINT:
567 value = heapSource->maximumSize;
568 break;
569 case HS_BYTES_ALLOCATED:
570 value = heapSource->bytesAllocated;
571 break;
572 case HS_OBJECTS_ALLOCATED:
573 value = sumHeapBitmap(&heapSource->allocBits);
574 break;
575 default:
576 assert(!"implemented");
577 value = 0;
578 }
579 if (perHeapStats) {
580 *perHeapStats = value;
581 }
582 return value;
583}
584
585/*
586 * Performs a shallow copy of the allocation bitmap into the given
587 * vector of heap bitmaps.
588 */
589void dvmHeapSourceGetObjectBitmaps(HeapBitmap objBits[], HeapBitmap markBits[],
590 size_t numHeaps)
591{
592 assert(!"implemented");
593}
594
595HeapBitmap *dvmHeapSourceGetLiveBits(void)
596{
597 assert(!"implemented");
598 return NULL;
599}
600
601/*
602 * Allocate the specified number of bytes from the heap. The
603 * allocation cursor points into a block of free storage. If the
604 * given allocation fits in the remaining space of the block, we
605 * advance the cursor and return a pointer to the free storage. If
606 * the allocation cannot fit in the current block but is smaller than
607 * a block we request a new block and allocate from it instead. If
608 * the allocation is larger than a block we must allocate from a span
609 * of contiguous blocks.
610 */
611void *dvmHeapSourceAlloc(size_t length)
612{
613 HeapSource *heapSource;
614 unsigned char *addr;
615 size_t aligned, available, blocks;
616
617 heapSource = gDvm.gcHeap->heapSource;
618 assert(heapSource != NULL);
619 assert(heapSource->allocPtr != NULL);
620 assert(heapSource->allocLimit != NULL);
621
622 aligned = alignUp(length, ALLOC_ALIGNMENT);
623 available = heapSource->allocLimit - heapSource->allocPtr;
624
625 /* Try allocating inside the current block. */
626 if (aligned <= available) {
627 addr = heapSource->allocPtr;
628 heapSource->allocPtr += aligned;
629 heapSource->bytesAllocated += aligned;
630 dvmHeapBitmapSetObjectBit(&heapSource->allocBits, addr);
631 return addr;
632 }
633
634 /* Try allocating in a new block. */
635 if (aligned <= BLOCK_SIZE) {
636 addr = allocateBlocks(heapSource, 1);
637 if (addr != NULL) {
638 heapSource->allocLimit = addr + BLOCK_SIZE;
639 heapSource->allocPtr = addr + aligned;
640 heapSource->bytesAllocated += aligned;
641 dvmHeapBitmapSetObjectBit(&heapSource->allocBits, addr);
642 /* TODO(cshapiro): pad out the current block. */
643 }
644 return addr;
645 }
646
647 /* Try allocating in a span of blocks. */
648 blocks = alignUp(aligned, BLOCK_SIZE) / BLOCK_SIZE;
649
650 addr = allocateBlocks(heapSource, blocks);
651 /* Propagate failure upward. */
652 if (addr != NULL) {
653 heapSource->bytesAllocated += aligned;
654 dvmHeapBitmapSetObjectBit(&heapSource->allocBits, addr);
655 /* TODO(cshapiro): pad out free space in the last block. */
656 }
657 return addr;
658}
659
660void *dvmHeapSourceAllocAndGrow(size_t size)
661{
662 return dvmHeapSourceAlloc(size);
663}
664
665/* TODO: refactor along with dvmHeapSourceAlloc */
666void *allocateGray(size_t size)
667{
668 assert(gDvm.gcHeap->heapSource->queueHead != QUEUE_TAIL);
669 return dvmHeapSourceAlloc(size);
670}
671
672/*
673 * Returns true if the given address is within the heap and points to
674 * the header of a live object.
675 */
676bool dvmHeapSourceContains(const void *addr)
677{
678 HeapSource *heapSource;
679 HeapBitmap *bitmap;
680
681 heapSource = gDvm.gcHeap->heapSource;
682 bitmap = &heapSource->allocBits;
Carl Shapirodc1e4f12010-05-01 22:27:56 -0700683 if (!dvmHeapBitmapCoversAddress(bitmap, addr)) {
684 return false;
685 } else {
686 return dvmHeapBitmapIsObjectBitSet(bitmap, addr);
687 }
Carl Shapirod28668c2010-04-15 16:10:00 -0700688}
689
690bool dvmHeapSourceGetPtrFlag(const void *ptr, enum HeapSourcePtrFlag flag)
691{
692 assert(!"implemented");
693 return false;
694}
695
696size_t dvmHeapSourceChunkSize(const void *ptr)
697{
698 assert(!"implemented");
699 return 0;
700}
701
702size_t dvmHeapSourceFootprint(void)
703{
704 assert(!"implemented");
705 return 0;
706}
707
708/*
709 * Returns the "ideal footprint" which appears to be the number of
710 * bytes currently committed to the heap. This starts out at the
711 * start size of the heap and grows toward the maximum size.
712 */
713size_t dvmHeapSourceGetIdealFootprint(void)
714{
715 return gDvm.gcHeap->heapSource->currentSize;
716}
717
718float dvmGetTargetHeapUtilization(void)
719{
720 assert(!"implemented");
721 return 0.0f;
722}
723
724void dvmSetTargetHeapUtilization(float newTarget)
725{
726 assert(!"implemented");
727}
728
729size_t dvmMinimumHeapSize(size_t size, bool set)
730{
731 return gDvm.gcHeap->heapSource->minimumSize;
732}
733
734/*
735 * Expands the size of the heap after a collection. At present we
736 * commit the pages for maximum size of the heap so this routine is
737 * just a no-op. Eventually, we will either allocate or commit pages
738 * on an as-need basis.
739 */
740void dvmHeapSourceGrowForUtilization(void)
741{
742 /* do nothing */
743}
744
745void dvmHeapSourceTrim(size_t bytesTrimmed[], size_t arrayLen)
746{
747 /* do nothing */
748}
749
750void dvmHeapSourceWalk(void (*callback)(const void *chunkptr, size_t chunklen,
751 const void *userptr, size_t userlen,
752 void *arg),
753 void *arg)
754{
755 assert(!"implemented");
756}
757
758size_t dvmHeapSourceGetNumHeaps(void)
759{
760 return 1;
761}
762
763bool dvmTrackExternalAllocation(size_t n)
764{
765 assert(!"implemented");
766 return false;
767}
768
769void dvmTrackExternalFree(size_t n)
770{
771 assert(!"implemented");
772}
773
774size_t dvmGetExternalBytesAllocated(void)
775{
776 assert(!"implemented");
777 return 0;
778}
779
780void dvmHeapSourceFlip(void)
781{
782 HeapSource *heapSource;
783 size_t i;
784
785 heapSource = gDvm.gcHeap->heapSource;
786
787 /* Reset the block queue. */
788 heapSource->allocBlocks = 0;
789 heapSource->queueSize = 0;
790 heapSource->queueHead = QUEUE_TAIL;
791
792 /* Hack: reset the reference lists. */
793 /* TODO(cshapiro): implement reference object processing. */
794 heapSource->softReferenceList = NULL;
795 heapSource->weakReferenceList = NULL;
796 heapSource->phantomReferenceList = NULL;
797
798 /* TODO(cshapiro): pad the current (prev) block. */
799
800 heapSource->allocPtr = NULL;
801 heapSource->allocLimit = NULL;
802
803 /* Whiten all allocated blocks. */
804 for (i = 0; i < heapSource->totalBlocks; ++i) {
805 if (heapSource->blockSpace[i] == BLOCK_TO_SPACE) {
806 heapSource->blockSpace[i] = BLOCK_FROM_SPACE;
807 }
808 }
809}
810
811static void room(size_t *alloc, size_t *avail, size_t *total)
812{
813 HeapSource *heapSource;
814 size_t i;
815
816 heapSource = gDvm.gcHeap->heapSource;
817 *total = heapSource->totalBlocks*BLOCK_SIZE;
818 *alloc = heapSource->allocBlocks*BLOCK_SIZE;
819 *avail = *total - *alloc;
820}
821
822static bool isSpaceInternal(u1 *addr, int space)
823{
824 HeapSource *heapSource;
825 u1 *base, *limit;
826 size_t offset;
827 char space2;
828
829 heapSource = gDvm.gcHeap->heapSource;
830 base = heapSource->blockBase;
831 assert(addr >= base);
832 limit = heapSource->blockBase + heapSource->maximumSize;
833 assert(addr < limit);
834 offset = addr - base;
835 space2 = heapSource->blockSpace[offset >> BLOCK_SHIFT];
836 return space == space2;
837}
838
839static bool isFromSpace(const void *addr)
840{
841 return isSpaceInternal((u1 *)addr, BLOCK_FROM_SPACE);
842}
843
844static bool isToSpace(const void *addr)
845{
846 return isSpaceInternal((u1 *)addr, BLOCK_TO_SPACE);
847}
848
849/*
850 * Notifies the collector that the object at the given address must
851 * remain stationary during the current collection.
852 */
853static void pinObject(const Object *obj)
854{
855 promoteBlockByAddr(gDvm.gcHeap->heapSource, obj);
856}
857
858static void printHeapBitmap(const HeapBitmap *bitmap)
859{
860 const char *cp;
861 size_t i, length;
862
863 length = bitmap->bitsLen >> 2;
864 fprintf(stderr, "%p", bitmap->bits);
865 for (i = 0; i < length; ++i) {
866 fprintf(stderr, " %lx", bitmap->bits[i]);
867 fputc('\n', stderr);
868 }
869}
870
871static void printHeapBitmapSxS(const HeapBitmap *b1, const HeapBitmap *b2)
872{
873 uintptr_t addr;
874 size_t i, length;
875
876 assert(b1->base == b2->base);
877 assert(b1->bitsLen == b2->bitsLen);
878 addr = b1->base;
879 length = b1->bitsLen >> 2;
880 for (i = 0; i < length; ++i) {
881 int diff = b1->bits[i] == b2->bits[i];
882 fprintf(stderr, "%08x %08lx %08lx %d\n",
883 addr, b1->bits[i], b2->bits[i], diff);
884 addr += sizeof(*b1->bits)*CHAR_BIT;
885 }
886}
887
888static size_t sumHeapBitmap(const HeapBitmap *bitmap)
889{
890 const char *cp;
891 size_t i, sum;
892
893 sum = 0;
894 for (i = 0; i < bitmap->bitsLen >> 2; ++i) {
895 sum += dvmClzImpl(bitmap->bits[i]);
896 }
897 return sum;
898}
899
900/*
901 * Miscellaneous functionality.
902 */
903
904static int isForward(const void *addr)
905{
906 return (uintptr_t)addr & 0x1;
907}
908
909static void setForward(const void *toObj, void *fromObj)
910{
911 *(unsigned long *)fromObj = (uintptr_t)toObj | 0x1;
912}
913
914static void* getForward(const void *fromObj)
915{
916 return (void *)((uintptr_t)fromObj & ~0x1);
917}
918
919/* Beware, uses the same encoding as a forwarding pointers! */
920static int isPermanentString(const StringObject *obj) {
921 return (uintptr_t)obj & 0x1;
922}
923
924static void* getPermanentString(const StringObject *obj)
925{
926 return (void *)((uintptr_t)obj & ~0x1);
927}
928
929
930/*
931 * Scavenging and transporting routines follow. A transporter grays
932 * an object. A scavenger blackens an object. We define these
933 * routines for each fundamental object type. Dispatch is performed
934 * in scavengeObject.
935 */
936
937/*
Carl Shapiro2396fda2010-05-03 20:14:14 -0700938 * Class object scavenging.
Carl Shapirod28668c2010-04-15 16:10:00 -0700939 */
Carl Shapiro2396fda2010-05-03 20:14:14 -0700940static void scavengeClassObject(ClassObject *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -0700941{
Carl Shapirod28668c2010-04-15 16:10:00 -0700942 int i;
943
Carl Shapirod28668c2010-04-15 16:10:00 -0700944 LOG_SCAVENGE("scavengeClassObject(obj=%p)", obj);
Carl Shapiro2396fda2010-05-03 20:14:14 -0700945 assert(obj != NULL);
Carl Shapirod28668c2010-04-15 16:10:00 -0700946 assert(obj->obj.clazz != NULL);
947 assert(obj->obj.clazz->descriptor != NULL);
948 assert(!strcmp(obj->obj.clazz->descriptor, "Ljava/lang/Class;"));
949 assert(obj->descriptor != NULL);
950 LOG_SCAVENGE("scavengeClassObject: descriptor='%s',vtableCount=%zu",
951 obj->descriptor, obj->vtableCount);
Carl Shapiro2396fda2010-05-03 20:14:14 -0700952 /* Scavenge our class object. */
Carl Shapirod28668c2010-04-15 16:10:00 -0700953 scavengeReference((Object **) obj);
954 /* Scavenge the array element class object. */
955 if (IS_CLASS_FLAG_SET(obj, CLASS_ISARRAY)) {
956 scavengeReference((Object **)(void *)&obj->elementClass);
957 }
958 /* Scavenge the superclass. */
959 scavengeReference((Object **)(void *)&obj->super);
960 /* Scavenge the class loader. */
961 scavengeReference(&obj->classLoader);
962 /* Scavenge static fields. */
963 for (i = 0; i < obj->sfieldCount; ++i) {
964 char ch = obj->sfields[i].field.signature[0];
965 if (ch == '[' || ch == 'L') {
966 scavengeReference((Object **)(void *)&obj->sfields[i].value.l);
967 }
968 }
969 /* Scavenge interface class objects. */
970 for (i = 0; i < obj->interfaceCount; ++i) {
971 scavengeReference((Object **) &obj->interfaces[i]);
972 }
Carl Shapirod28668c2010-04-15 16:10:00 -0700973}
974
975/*
976 * Array object scavenging.
977 */
Carl Shapirod28668c2010-04-15 16:10:00 -0700978static size_t scavengeArrayObject(ArrayObject *array)
979{
980 size_t i, length;
981
982 LOG_SCAVENGE("scavengeArrayObject(array=%p)", array);
983 /* Scavenge the class object. */
984 assert(isToSpace(array));
985 assert(array != NULL);
986 assert(array->obj.clazz != NULL);
987 scavengeReference((Object **) array);
988 length = dvmArrayObjectSize(array);
989 /* Scavenge the array contents. */
990 if (IS_CLASS_FLAG_SET(array->obj.clazz, CLASS_ISOBJECTARRAY)) {
991 Object **contents = (Object **)array->contents;
992 for (i = 0; i < array->length; ++i) {
993 scavengeReference(&contents[i]);
994 }
995 }
996 return length;
997}
998
999/*
1000 * Reference object scavenging.
1001 */
1002
1003static int getReferenceFlags(const DataObject *obj)
1004{
1005 int flags;
1006
1007 flags = CLASS_ISREFERENCE |
1008 CLASS_ISWEAKREFERENCE |
1009 CLASS_ISPHANTOMREFERENCE;
1010 return GET_CLASS_FLAG_GROUP(obj->obj.clazz, flags);
1011}
1012
1013static int isReference(const DataObject *obj)
1014{
1015 return getReferenceFlags(obj) != 0;
1016}
1017
1018static int isSoftReference(const DataObject *obj)
1019{
1020 return getReferenceFlags(obj) == CLASS_ISREFERENCE;
1021}
1022
1023static int isWeakReference(const DataObject *obj)
1024{
1025 return getReferenceFlags(obj) & CLASS_ISWEAKREFERENCE;
1026}
1027
1028static bool isPhantomReference(const DataObject *obj)
1029{
1030 return getReferenceFlags(obj) & CLASS_ISPHANTOMREFERENCE;
1031}
1032
1033static void clearReference(DataObject *reference)
1034{
1035 size_t offset;
1036
1037 assert(isSoftReference(reference) || isWeakReference(reference));
1038 offset = gDvm.offJavaLangRefReference_referent;
1039 dvmSetFieldObject((Object *)reference, offset, NULL);
1040}
1041
1042static bool isReferentGray(const DataObject *reference)
1043{
1044 Object *obj;
1045 size_t offset;
1046
1047 assert(reference != NULL);
1048 assert(isSoftReference(reference) || isWeakReference(reference));
1049 offset = gDvm.offJavaLangRefReference_referent;
1050 obj = dvmGetFieldObject((Object *)reference, offset);
1051 return obj == NULL || isToSpace(obj);
1052}
1053
1054static void enqueueReference(HeapSource *heapSource, DataObject *reference)
1055{
1056 DataObject **queue;
1057 size_t offset;
1058
1059 LOGI("enqueueReference(heapSource=%p,reference=%p)", heapSource, reference);
1060 assert(heapSource != NULL);
1061 assert(reference != NULL);
1062 assert(isToSpace(reference));
1063 assert(isReference(reference));
1064 if (isSoftReference(reference)) {
1065 queue = &heapSource->softReferenceList;
1066 } else if (isWeakReference(reference)) {
1067 queue = &heapSource->weakReferenceList;
1068 } else if (isPhantomReference(reference)) {
1069 queue = &heapSource->phantomReferenceList;
1070 } else {
1071 assert(!"reached");
1072 queue = NULL;
1073 }
1074 offset = gDvm.offJavaLangRefReference_vmData;
1075 dvmSetFieldObject((Object *)reference, offset, (Object *)*queue);
1076 *queue = reference;
1077}
1078
Carl Shapirod28668c2010-04-15 16:10:00 -07001079/*
1080 * If a reference points to from-space and has been forwarded, we snap
1081 * the pointer to its new to-space address. If the reference points
1082 * to an unforwarded from-space address we must enqueue the reference
1083 * for later processing. TODO: implement proper reference processing
1084 * and move the referent scavenging elsewhere.
1085 */
Carl Shapiro2396fda2010-05-03 20:14:14 -07001086static void scavengeReferenceObject(DataObject *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001087{
Carl Shapirod28668c2010-04-15 16:10:00 -07001088 assert(obj != NULL);
1089 LOG_SCAVENGE("scavengeReferenceObject(obj=%p),'%s'", obj, obj->obj.clazz->descriptor);
1090 {
1091 /* Always scavenge the hidden Reference.referent field. */
1092 size_t offset = gDvm.offJavaLangRefReference_referent;
1093 void *addr = BYTE_OFFSET((Object *)obj, offset);
1094 Object **ref = (Object **)(void *)&((JValue *)addr)->l;
1095 scavengeReference(ref);
1096 }
Carl Shapiro2396fda2010-05-03 20:14:14 -07001097 scavengeDataObject(obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001098 if (!isReferentGray(obj)) {
1099 assert(!"reached"); /* TODO(cshapiro): remove this */
1100 LOG_SCAVENGE("scavengeReferenceObject: enqueueing %p", obj);
1101 enqueueReference(gDvm.gcHeap->heapSource, obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001102 }
Carl Shapirod28668c2010-04-15 16:10:00 -07001103}
1104
1105/*
1106 * Data object scavenging.
1107 */
Carl Shapiro2396fda2010-05-03 20:14:14 -07001108static void scavengeDataObject(DataObject *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001109{
1110 ClassObject *clazz;
Carl Shapirod28668c2010-04-15 16:10:00 -07001111 int i;
1112
1113 // LOGI("scavengeDataObject(obj=%p)", obj);
1114 assert(obj != NULL);
1115 assert(obj->obj.clazz != NULL);
1116 assert(obj->obj.clazz->objectSize != 0);
1117 assert(isToSpace(obj));
1118 /* Scavenge the class object. */
1119 clazz = obj->obj.clazz;
1120 scavengeReference((Object **) obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001121 /* Scavenge instance fields. */
1122 if (clazz->refOffsets != CLASS_WALK_SUPER) {
1123 size_t refOffsets = clazz->refOffsets;
1124 while (refOffsets != 0) {
1125 size_t rshift = CLZ(refOffsets);
1126 size_t offset = CLASS_OFFSET_FROM_CLZ(rshift);
1127 Object **ref = (Object **)((u1 *)obj + offset);
1128 scavengeReference(ref);
1129 refOffsets &= ~(CLASS_HIGH_BIT >> rshift);
1130 }
1131 } else {
1132 for (; clazz != NULL; clazz = clazz->super) {
1133 InstField *field = clazz->ifields;
1134 for (i = 0; i < clazz->ifieldRefCount; ++i, ++field) {
1135 size_t offset = field->byteOffset;
1136 Object **ref = (Object **)((u1 *)obj + offset);
1137 scavengeReference(ref);
1138 }
1139 }
1140 }
Carl Shapiro2396fda2010-05-03 20:14:14 -07001141}
1142
1143static Object *transportObject(const Object *fromObj)
1144{
1145 Object *toObj;
1146 size_t allocSize, copySize;
1147
1148 LOG_TRANSPORT("transportObject(fromObj=%p) allocBlocks=%zu",
1149 fromObj,
1150 gDvm.gcHeap->heapSource->allocBlocks);
1151 assert(fromObj != NULL);
1152 assert(isFromSpace(fromObj));
1153 allocSize = copySize = objectSize(fromObj);
1154 if (LW_HASH_STATE(fromObj->lock) != LW_HASH_STATE_UNHASHED) {
1155 /*
1156 * The object has been hashed or hashed and moved. We must
1157 * reserve an additional word for a hash code.
1158 */
1159 allocSize += sizeof(u4);
1160 }
1161 if (LW_HASH_STATE(fromObj->lock) == LW_HASH_STATE_HASHED_AND_MOVED) {
1162 /*
1163 * The object has its hash code allocated. Ensure the hash
1164 * code is copied along with the instance data.
1165 */
1166 copySize += sizeof(u4);
1167 }
1168 /* TODO(cshapiro): don't copy, re-map large data objects. */
1169 assert(copySize <= allocSize);
1170 toObj = allocateGray(allocSize);
1171 assert(toObj != NULL);
1172 assert(isToSpace(toObj));
1173 memcpy(toObj, fromObj, copySize);
1174 if (LW_HASH_STATE(fromObj->lock) == LW_HASH_STATE_HASHED) {
1175 /*
1176 * The object has had its hash code exposed. Append it to the
1177 * instance and set a bit so we know to look for it there.
1178 */
1179 *(u4 *)(((char *)toObj) + copySize) = (u4)fromObj >> 3;
1180 toObj->lock |= LW_HASH_STATE_HASHED_AND_MOVED << LW_HASH_STATE_SHIFT;
1181 }
1182 LOG_TRANSPORT("transportObject: from %p/%zu to %p/%zu (%zu,%zu) %s",
1183 fromObj, addressToBlock(gDvm.gcHeap->heapSource,fromObj),
1184 toObj, addressToBlock(gDvm.gcHeap->heapSource,toObj),
1185 copySize, allocSize, copySize < allocSize ? "DIFFERENT" : "");
1186 return toObj;
Carl Shapirod28668c2010-04-15 16:10:00 -07001187}
1188
1189/*
1190 * Generic reference scavenging.
1191 */
1192
1193/*
1194 * Given a reference to an object, the scavenge routine will gray the
1195 * reference. Any objects pointed to by the scavenger object will be
1196 * transported to new space and a forwarding pointer will be installed
1197 * in the header of the object.
1198 */
1199
1200/*
1201 * Blacken the given pointer. If the pointer is in from space, it is
1202 * transported to new space. If the object has a forwarding pointer
1203 * installed it has already been transported and the referent is
1204 * snapped to the new address.
1205 */
Carl Shapiro2396fda2010-05-03 20:14:14 -07001206static void scavengeReference(Object **obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001207{
1208 ClassObject *clazz;
Carl Shapiro2396fda2010-05-03 20:14:14 -07001209 Object *fromObj, *toObj;
Carl Shapirod28668c2010-04-15 16:10:00 -07001210 uintptr_t word;
1211
1212 assert(obj);
1213
Carl Shapiro2396fda2010-05-03 20:14:14 -07001214 if (*obj == NULL) return;
Carl Shapirod28668c2010-04-15 16:10:00 -07001215
1216 assert(dvmIsValidObject(*obj));
1217
1218 /* The entire block is black. */
1219 if (isToSpace(*obj)) {
1220 LOG_SCAVENGE("scavengeReference skipping pinned object @ %p", *obj);
Carl Shapiro2396fda2010-05-03 20:14:14 -07001221 return;
Carl Shapirod28668c2010-04-15 16:10:00 -07001222 }
1223 LOG_SCAVENGE("scavengeReference(*obj=%p)", *obj);
1224
1225 assert(isFromSpace(*obj));
1226
1227 clazz = (*obj)->clazz;
1228
1229 if (isForward(clazz)) {
1230 // LOGI("forwarding %p @ %p to %p", *obj, obj, (void *)((uintptr_t)clazz & ~0x1));
1231 *obj = (Object *)getForward(clazz);
Carl Shapiro2396fda2010-05-03 20:14:14 -07001232 return;
Carl Shapirod28668c2010-04-15 16:10:00 -07001233 }
Carl Shapiro2396fda2010-05-03 20:14:14 -07001234 fromObj = *obj;
1235 if (clazz == NULL) {
1236 // LOGI("scavangeReference %p has a NULL class object", fromObj);
1237 assert(!"implemented");
1238 toObj = NULL;
1239 } else if (clazz == gDvm.unlinkedJavaLangClass) {
1240 // LOGI("scavangeReference %p is an unlinked class object", fromObj);
1241 assert(!"implemented");
1242 toObj = NULL;
1243 } else {
1244 toObj = transportObject(fromObj);
1245 }
1246 setForward(toObj, fromObj);
1247 *obj = (Object *)toObj;
Carl Shapirod28668c2010-04-15 16:10:00 -07001248}
1249
1250static void verifyReference(const void *obj)
1251{
1252 HeapSource *heapSource;
1253 size_t block;
1254 char space;
1255
1256 if (obj == NULL) {
1257 LOG_VERIFY("verifyReference(obj=%p)", obj);
1258 return;
1259 }
1260 heapSource = gDvm.gcHeap->heapSource;
1261 block = addressToBlock(heapSource, obj);
1262 space = heapSource->blockSpace[block];
1263 LOG_VERIFY("verifyReference(obj=%p),block=%zu,space=%d", obj, block, space);
1264 assert(!((uintptr_t)obj & 7));
1265 assert(isToSpace(obj));
1266 assert(dvmIsValidObject(obj));
1267}
1268
1269/*
1270 * Generic object scavenging.
1271 */
1272
Carl Shapiro2396fda2010-05-03 20:14:14 -07001273static void scavengeObject(Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07001274{
1275 ClassObject *clazz;
Carl Shapirod28668c2010-04-15 16:10:00 -07001276
1277 assert(obj != NULL);
1278 clazz = obj->clazz;
1279 assert(clazz != NULL);
1280 assert(!((uintptr_t)clazz & 0x1));
1281 assert(clazz != gDvm.unlinkedJavaLangClass);
1282 if (clazz == gDvm.classJavaLangClass) {
Carl Shapiro2396fda2010-05-03 20:14:14 -07001283 scavengeClassObject((ClassObject *)obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001284 } else if (IS_CLASS_FLAG_SET(clazz, CLASS_ISARRAY)) {
Carl Shapiro2396fda2010-05-03 20:14:14 -07001285 scavengeArrayObject((ArrayObject *)obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001286 } else if (IS_CLASS_FLAG_SET(clazz, CLASS_ISREFERENCE)) {
Carl Shapiro2396fda2010-05-03 20:14:14 -07001287 scavengeReferenceObject((DataObject *)obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001288 } else {
Carl Shapiro2396fda2010-05-03 20:14:14 -07001289 scavengeDataObject((DataObject *)obj);
Carl Shapirod28668c2010-04-15 16:10:00 -07001290 }
Carl Shapirod28668c2010-04-15 16:10:00 -07001291}
1292
1293/*
1294 * External root scavenging routines.
1295 */
1296
1297static void scavengeHashTable(HashTable *table)
1298{
1299 HashEntry *entry;
1300 void *obj;
1301 int i;
1302
1303 if (table == NULL) {
1304 return;
1305 }
1306 dvmHashTableLock(table);
1307 for (i = 0; i < table->tableSize; ++i) {
1308 entry = &table->pEntries[i];
1309 obj = entry->data;
1310 if (obj == NULL || obj == HASH_TOMBSTONE) {
1311 continue;
1312 }
1313 scavengeReference((Object **)(void *)&entry->data);
1314 }
1315 dvmHashTableUnlock(table);
1316}
1317
1318static void pinHashTableEntries(HashTable *table)
1319{
1320 HashEntry *entry;
1321 void *obj;
1322 int i;
1323
1324 LOGI(">>> pinHashTableEntries(table=%p)", table);
1325 if (table == NULL) {
1326 return;
1327 }
1328 dvmHashTableLock(table);
1329 for (i = 0; i < table->tableSize; ++i) {
1330 entry = &table->pEntries[i];
1331 obj = entry->data;
1332 if (obj == NULL || obj == HASH_TOMBSTONE) {
1333 continue;
1334 }
1335 pinObject(entry->data);
1336 }
1337 dvmHashTableUnlock(table);
1338 LOGI("<<< pinHashTableEntries(table=%p)", table);
1339}
1340
1341static void pinPrimitiveClasses(void)
1342{
1343 size_t length;
1344 size_t i;
1345
1346 length = ARRAYSIZE(gDvm.primitiveClass);
1347 for (i = 0; i < length; i++) {
1348 if (gDvm.primitiveClass[i] != NULL) {
1349 pinObject((Object *)gDvm.primitiveClass[i]);
1350 }
1351 }
1352}
1353
1354/*
1355 * Scavenge interned strings. Permanent interned strings will have
1356 * been pinned and are therefore ignored. Non-permanent strings that
1357 * have been forwarded are snapped. All other entries are removed.
1358 */
1359static void scavengeInternedStrings(void)
1360{
1361 HashTable *table;
1362 HashEntry *entry;
1363 Object *obj;
1364 int i;
1365
1366 table = gDvm.internedStrings;
1367 if (table == NULL) {
1368 return;
1369 }
1370 dvmHashTableLock(table);
1371 for (i = 0; i < table->tableSize; ++i) {
1372 entry = &table->pEntries[i];
1373 obj = (Object *)entry->data;
1374 if (obj == NULL || obj == HASH_TOMBSTONE) {
1375 continue;
1376 } else if (!isPermanentString((StringObject *)obj)) {
1377 // LOGI("entry->data=%p", entry->data);
1378 LOG_SCAVENGE(">>> string obj=%p", entry->data);
1379 /* TODO(cshapiro): detach white string objects */
1380 scavengeReference((Object **)(void *)&entry->data);
1381 LOG_SCAVENGE("<<< string obj=%p", entry->data);
1382 }
1383 }
1384 dvmHashTableUnlock(table);
1385}
1386
1387static void pinInternedStrings(void)
1388{
1389 HashTable *table;
1390 HashEntry *entry;
1391 Object *obj;
1392 int i;
1393
1394 table = gDvm.internedStrings;
1395 if (table == NULL) {
1396 return;
1397 }
1398 dvmHashTableLock(table);
1399 for (i = 0; i < table->tableSize; ++i) {
1400 entry = &table->pEntries[i];
1401 obj = (Object *)entry->data;
1402 if (obj == NULL || obj == HASH_TOMBSTONE) {
1403 continue;
1404 } else if (isPermanentString((StringObject *)obj)) {
1405 obj = (Object *)getPermanentString((StringObject*)obj);
1406 LOG_PROMOTE(">>> pin string obj=%p", obj);
1407 pinObject(obj);
1408 LOG_PROMOTE("<<< pin string obj=%p", obj);
1409 }
1410 }
1411 dvmHashTableUnlock(table);
1412}
1413
1414static void verifyInternedStrings(void)
1415{
1416 HashTable *table;
1417 HashEntry *entry;
1418 Object *fwd, *obj;
1419 int i;
1420
1421 table = gDvm.internedStrings;
1422 if (table == NULL) {
1423 return;
1424 }
1425 dvmHashTableLock(table);
1426 for (i = 0; i < table->tableSize; ++i) {
1427 entry = &table->pEntries[i];
1428 obj = (Object *)entry->data;
1429 if (obj == NULL || obj == HASH_TOMBSTONE) {
1430 continue;
1431 } else if (isPermanentString((StringObject *)obj)) {
1432 fwd = (Object *)getForward(obj);
1433 LOG_VERIFY(">>> verify string fwd=%p obj=%p", fwd, obj);
1434 verifyReference(fwd);
1435 LOG_VERIFY(">>> verify string fwd=%p obj=%p", fwd, obj);
1436 } else {
1437 LOG_SCAVENGE(">>> verify string obj=%p %p", obj, entry->data);
1438 verifyReference(obj);
1439 LOG_SCAVENGE("<<< verify string obj=%p %p", obj, entry->data);
1440 }
1441 }
1442 dvmHashTableUnlock(table);
1443}
1444
1445/*
1446 * At present, reference tables contain references that must not be
1447 * moved by the collector. Instead of scavenging each reference in
1448 * the table we pin each referenced object.
1449 */
1450static void pinReferenceTable(ReferenceTable *table)
1451{
1452 Object **entry;
1453 int i;
1454
1455 assert(table != NULL);
1456 assert(table->table != NULL);
1457 assert(table->nextEntry != NULL);
1458 for (entry = table->table; entry < table->nextEntry; ++entry) {
1459 assert(entry != NULL);
1460 assert(!isForward(*entry));
1461 pinObject(*entry);
1462 }
1463}
1464
1465static void verifyReferenceTable(const ReferenceTable *table)
1466{
1467 Object **entry;
1468 int i;
1469
1470 LOGI(">>> verifyReferenceTable(table=%p)", table);
1471 for (entry = table->table; entry < table->nextEntry; ++entry) {
1472 assert(entry != NULL);
1473 assert(!isForward(*entry));
1474 verifyReference(*entry);
1475 }
1476 LOGI("<<< verifyReferenceTable(table=%p)", table);
1477}
1478
1479static void scavengeLargeHeapRefTable(LargeHeapRefTable *table)
1480{
1481 Object **entry;
1482
1483 for (; table != NULL; table = table->next) {
1484 for (entry = table->refs.table; entry < table->refs.nextEntry; ++entry) {
1485 if ((uintptr_t)*entry & ~0x3) {
1486 /* It's a pending reference operation. */
1487 assert(!"implemented");
1488 }
1489 scavengeReference(entry);
1490 }
1491 }
1492}
1493
1494/* This code was copied from Thread.c */
1495static void scavengeThreadStack(Thread *thread)
1496{
1497 const u4 *framePtr;
1498#if WITH_EXTRA_GC_CHECKS > 1
1499 bool first = true;
1500#endif
1501
1502 framePtr = (const u4 *)thread->curFrame;
1503 while (framePtr != NULL) {
1504 const StackSaveArea *saveArea;
1505 const Method *method;
1506
1507 saveArea = SAVEAREA_FROM_FP(framePtr);
1508 method = saveArea->method;
Carl Shapirodc1e4f12010-05-01 22:27:56 -07001509 if (method == NULL) {
1510 /* this is a break frame, nothing to do */
1511 } else if (dvmIsNativeMethod(method)) {
1512 /*
1513 * For purposes of marking references, we don't need to do
1514 * anything here, because all of the native "ins" were copied
1515 * from registers in the caller's stack frame and won't be
1516 * changed (an interpreted method can freely use registers
1517 * with parameters like any other register, but natives don't
1518 * work that way).
1519 *
1520 * However, we need to ensure that references visible to
1521 * native methods don't move around. We can do a precise scan
1522 * of the arguments by examining the method signature.
1523 */
1524 LOGI("+++ native scan %s.%s\n",
1525 method->clazz->descriptor, method->name);
1526 assert(method->registersSize == method->insSize);
1527 const char* shorty = method->shorty+1; // skip return value
1528 if (!dvmIsStaticMethod(method)) {
1529 /* grab the "this" pointer */
1530 Object* obj = (Object*) *framePtr++;
1531 if (obj == NULL) {
1532 /*
1533 * This can happen for the "fake" entry frame inserted
1534 * for threads created outside the VM. There's no actual
1535 * call so there's no object. If we changed the fake
1536 * entry method to be declared "static" then this
1537 * situation should never occur.
1538 */
1539 } else {
1540 assert(dvmIsValidObject(obj));
Carl Shapiro2396fda2010-05-03 20:14:14 -07001541 //pinObject(obj);
Carl Shapirodc1e4f12010-05-01 22:27:56 -07001542 }
1543 }
1544
1545 Object* obj;
1546 int i;
1547 for (i = method->registersSize - 1; i >= 0; i--, framePtr++) {
1548 switch (*shorty++) {
1549 case 'L':
1550 obj = (Object*) *framePtr;
1551 if (obj != NULL) {
1552 assert(dvmIsValidObject(obj));
Carl Shapiro2396fda2010-05-03 20:14:14 -07001553 //pinObject(obj);
Carl Shapirodc1e4f12010-05-01 22:27:56 -07001554 }
1555 break;
1556 case 'D':
1557 case 'J':
1558 framePtr++;
1559 break;
1560 default:
1561 /* 32-bit non-reference value */
1562 obj = (Object*) *framePtr; // debug, remove
1563 if (dvmIsValidObject(obj)) { // debug, remove
1564 /* if we see a lot of these, our scan might be off */
1565 LOGI("+++ did NOT pin obj %p\n", obj);
1566 }
1567 break;
1568 }
1569 }
1570 } else {
Carl Shapirod28668c2010-04-15 16:10:00 -07001571#ifdef COUNT_PRECISE_METHODS
1572 /* the GC is running, so no lock required */
1573 if (dvmPointerSetAddEntry(gDvm.preciseMethods, method))
1574 LOGI("PGC: added %s.%s %p\n",
1575 method->clazz->descriptor, method->name, method);
1576#endif
1577#if WITH_EXTRA_GC_CHECKS > 1
1578 /*
1579 * May also want to enable the memset() in the "invokeMethod"
1580 * goto target in the portable interpreter. That sets the stack
1581 * to a pattern that makes referring to uninitialized data
1582 * very obvious.
1583 */
1584
1585 if (first) {
1586 /*
1587 * First frame, isn't native, check the "alternate" saved PC
1588 * as a sanity check.
1589 *
1590 * It seems like we could check the second frame if the first
1591 * is native, since the PCs should be the same. It turns out
1592 * this doesn't always work. The problem is that we could
1593 * have calls in the sequence:
1594 * interp method #2
1595 * native method
1596 * interp method #1
1597 *
1598 * and then GC while in the native method after returning
1599 * from interp method #2. The currentPc on the stack is
1600 * for interp method #1, but thread->currentPc2 is still
1601 * set for the last thing interp method #2 did.
1602 *
1603 * This can also happen in normal execution:
1604 * - sget-object on not-yet-loaded class
1605 * - class init updates currentPc2
1606 * - static field init is handled by parsing annotations;
1607 * static String init requires creation of a String object,
1608 * which can cause a GC
1609 *
1610 * Essentially, any pattern that involves executing
1611 * interpreted code and then causes an allocation without
1612 * executing instructions in the original method will hit
1613 * this. These are rare enough that the test still has
1614 * some value.
1615 */
1616 if (saveArea->xtra.currentPc != thread->currentPc2) {
1617 LOGW("PGC: savedPC(%p) != current PC(%p), %s.%s ins=%p\n",
1618 saveArea->xtra.currentPc, thread->currentPc2,
1619 method->clazz->descriptor, method->name, method->insns);
1620 if (saveArea->xtra.currentPc != NULL)
1621 LOGE(" pc inst = 0x%04x\n", *saveArea->xtra.currentPc);
1622 if (thread->currentPc2 != NULL)
1623 LOGE(" pc2 inst = 0x%04x\n", *thread->currentPc2);
1624 dvmDumpThread(thread, false);
1625 }
1626 } else {
1627 /*
1628 * It's unusual, but not impossible, for a non-first frame
1629 * to be at something other than a method invocation. For
1630 * example, if we do a new-instance on a nonexistent class,
1631 * we'll have a lot of class loader activity on the stack
1632 * above the frame with the "new" operation. Could also
1633 * happen while we initialize a Throwable when an instruction
1634 * fails.
1635 *
1636 * So there's not much we can do here to verify the PC,
1637 * except to verify that it's a GC point.
1638 */
1639 }
1640 assert(saveArea->xtra.currentPc != NULL);
1641#endif
1642
1643 const RegisterMap* pMap;
1644 const u1* regVector;
1645 int i;
1646
1647 Method* nonConstMethod = (Method*) method; // quiet gcc
1648 pMap = dvmGetExpandedRegisterMap(nonConstMethod);
1649
1650 /* assert(pMap != NULL); */
1651
1652 //LOGI("PGC: %s.%s\n", method->clazz->descriptor, method->name);
1653
1654 if (pMap != NULL) {
1655 /* found map, get registers for this address */
1656 int addr = saveArea->xtra.currentPc - method->insns;
1657 regVector = dvmRegisterMapGetLine(pMap, addr);
1658 /*
1659 if (regVector == NULL) {
1660 LOGI("PGC: map but no entry for %s.%s addr=0x%04x\n",
1661 method->clazz->descriptor, method->name, addr);
1662 } else {
1663 LOGI("PGC: found map for %s.%s 0x%04x (t=%d)\n",
1664 method->clazz->descriptor, method->name, addr,
1665 thread->threadId);
1666 }
1667 */
1668 } else {
1669 /*
1670 * No map found. If precise GC is disabled this is
1671 * expected -- we don't create pointers to the map data even
1672 * if it's present -- but if it's enabled it means we're
1673 * unexpectedly falling back on a conservative scan, so it's
1674 * worth yelling a little.
1675 */
1676 if (gDvm.preciseGc) {
1677 LOGI("PGC: no map for %s.%s\n", method->clazz->descriptor, method->name);
1678 }
1679 regVector = NULL;
1680 }
1681
1682 /* assert(regVector != NULL); */
1683
1684 if (regVector == NULL) {
1685 /* conservative scan */
1686 for (i = method->registersSize - 1; i >= 0; i--) {
1687 u4 rval = *framePtr++;
1688 if (rval != 0 && (rval & 0x3) == 0) {
1689 abort();
1690 /* dvmMarkIfObject((Object *)rval); */
1691 }
1692 }
1693 } else {
1694 /*
1695 * Precise scan. v0 is at the lowest address on the
1696 * interpreted stack, and is the first bit in the register
1697 * vector, so we can walk through the register map and
1698 * memory in the same direction.
1699 *
1700 * A '1' bit indicates a live reference.
1701 */
1702 u2 bits = 1 << 1;
1703 for (i = method->registersSize - 1; i >= 0; i--) {
1704 /* u4 rval = *framePtr++; */
1705 u4 rval = *framePtr;
1706
1707 bits >>= 1;
1708 if (bits == 1) {
1709 /* set bit 9 so we can tell when we're empty */
1710 bits = *regVector++ | 0x0100;
1711 LOGVV("loaded bits: 0x%02x\n", bits & 0xff);
1712 }
1713
1714 if (rval != 0 && (bits & 0x01) != 0) {
1715 /*
1716 * Non-null, register marked as live reference. This
1717 * should always be a valid object.
1718 */
1719#if WITH_EXTRA_GC_CHECKS > 0
1720 if ((rval & 0x3) != 0 || !dvmIsValidObject((Object*) rval)) {
1721 /* this is very bad */
1722 LOGE("PGC: invalid ref in reg %d: 0x%08x\n",
1723 method->registersSize-1 - i, rval);
1724 } else
1725#endif
1726 {
1727
1728 // LOGI("stack reference %u@%p", *framePtr, framePtr);
1729 /* dvmMarkObjectNonNull((Object *)rval); */
1730 scavengeReference((Object **) framePtr);
1731 }
1732 } else {
1733 /*
1734 * Null or non-reference, do nothing at all.
1735 */
1736#if WITH_EXTRA_GC_CHECKS > 1
1737 if (dvmIsValidObject((Object*) rval)) {
1738 /* this is normal, but we feel chatty */
1739 LOGD("PGC: ignoring valid ref in reg %d: 0x%08x\n",
1740 method->registersSize-1 - i, rval);
1741 }
1742#endif
1743 }
1744 ++framePtr;
1745 }
1746 dvmReleaseRegisterMapLine(pMap, regVector);
1747 }
1748 }
1749 /* else this is a break frame and there is nothing to mark, or
1750 * this is a native method and the registers are just the "ins",
1751 * copied from various registers in the caller's set.
1752 */
1753
1754#if WITH_EXTRA_GC_CHECKS > 1
1755 first = false;
1756#endif
1757
1758 /* Don't fall into an infinite loop if things get corrupted.
1759 */
1760 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
1761 saveArea->prevFrame == NULL);
1762 framePtr = saveArea->prevFrame;
1763 }
1764}
1765
1766static void scavengeThread(Thread *thread)
1767{
1768 assert(thread->status != THREAD_RUNNING ||
1769 thread->isSuspended ||
1770 thread == dvmThreadSelf());
1771
1772 // LOGI("scavengeThread(thread=%p)", thread);
1773
1774 // LOGI("Scavenging threadObj=%p", thread->threadObj);
1775 scavengeReference(&thread->threadObj);
1776
1777 // LOGI("Scavenging exception=%p", thread->exception);
1778 scavengeReference(&thread->exception);
1779
1780 scavengeThreadStack(thread);
1781}
1782
1783static void scavengeThreadList(void)
1784{
1785 Thread *thread;
1786
1787 dvmLockThreadList(dvmThreadSelf());
1788 thread = gDvm.threadList;
1789 while (thread) {
1790 scavengeThread(thread);
1791 thread = thread->next;
1792 }
1793 dvmUnlockThreadList();
1794}
1795
1796static void verifyThreadStack(const Thread *thread)
1797{
1798 const u4 *framePtr;
1799
1800 assert(thread != NULL);
1801 framePtr = (const u4 *)thread->curFrame;
1802 while (framePtr != NULL) {
1803 const StackSaveArea *saveArea;
1804 const Method *method;
1805
1806 saveArea = SAVEAREA_FROM_FP(framePtr);
1807 method = saveArea->method;
1808 if (method != NULL && !dvmIsNativeMethod(method)) {
1809 const RegisterMap* pMap;
1810 const u1* regVector;
1811 int i;
1812
1813 Method* nonConstMethod = (Method*) method; // quiet gcc
1814 pMap = dvmGetExpandedRegisterMap(nonConstMethod);
1815
1816 /* assert(pMap != NULL); */
1817
1818 // LOGI("PGC: %s.%s\n", method->clazz->descriptor, method->name);
1819
1820 if (pMap != NULL) {
1821 /* found map, get registers for this address */
1822 int addr = saveArea->xtra.currentPc - method->insns;
1823 regVector = dvmRegisterMapGetLine(pMap, addr);
1824 if (regVector == NULL) {
1825 LOGI("PGC: map but no entry for %s.%s addr=0x%04x\n",
1826 method->clazz->descriptor, method->name, addr);
1827 } else {
1828 //LOGI("PGC: found map for %s.%s 0x%04x (t=%d)\n", method->clazz->descriptor, method->name, addr, thread->threadId);
1829 }
1830 } else {
1831 /*
1832 * No map found. If precise GC is disabled this is
1833 * expected -- we don't create pointers to the map data even
1834 * if it's present -- but if it's enabled it means we're
1835 * unexpectedly falling back on a conservative scan, so it's
1836 * worth yelling a little.
1837 */
1838 if (gDvm.preciseGc) {
1839 LOGI("PGC: no map for %s.%s\n",
1840 method->clazz->descriptor, method->name);
1841 }
1842 regVector = NULL;
1843 }
1844
1845 /* assert(regVector != NULL); */
1846
1847 if (regVector == NULL) {
1848 /* conservative scan */
1849 for (i = method->registersSize - 1; i >= 0; i--) {
1850 u4 rval = *framePtr++;
1851 if (rval != 0 && (rval & 0x3) == 0) {
1852 abort();
1853 /* dvmMarkIfObject((Object *)rval); */
1854 }
1855 }
1856 } else {
1857 /*
1858 * Precise scan. v0 is at the lowest address on the
1859 * interpreted stack, and is the first bit in the register
1860 * vector, so we can walk through the register map and
1861 * memory in the same direction.
1862 *
1863 * A '1' bit indicates a live reference.
1864 */
1865 u2 bits = 1 << 1;
1866 for (i = method->registersSize - 1; i >= 0; i--) {
1867 u4 rval = *framePtr;
1868
1869 bits >>= 1;
1870 if (bits == 1) {
1871 /* set bit 9 so we can tell when we're empty */
1872 bits = *regVector++ | 0x0100;
1873 LOGVV("loaded bits: 0x%02x\n", bits & 0xff);
1874 }
1875
1876 if (rval != 0 && (bits & 0x01) != 0) {
1877 /*
1878 * Non-null, register marked as live reference. This
1879 * should always be a valid object.
1880 */
1881 //LOGI("verify stack reference %p", (Object *)*framePtr);
1882 verifyReference((Object *)*framePtr);
1883 } else {
1884 /*
1885 * Null or non-reference, do nothing at all.
1886 */
1887 }
1888 ++framePtr;
1889 }
1890 dvmReleaseRegisterMapLine(pMap, regVector);
1891 }
1892 }
1893 /* else this is a break frame and there is nothing to mark, or
1894 * this is a native method and the registers are just the "ins",
1895 * copied from various registers in the caller's set.
1896 */
1897
1898 /* Don't fall into an infinite loop if things get corrupted.
1899 */
1900 assert((uintptr_t)saveArea->prevFrame > (uintptr_t)framePtr ||
1901 saveArea->prevFrame == NULL);
1902 framePtr = saveArea->prevFrame;
1903 }
1904}
1905
1906static void verifyThread(const Thread *thread)
1907{
1908 assert(thread->status != THREAD_RUNNING ||
1909 thread->isSuspended ||
1910 thread == dvmThreadSelf());
1911
1912 LOGI("verifyThread(thread=%p)", thread);
1913
1914 LOGI("verify threadObj=%p", thread->threadObj);
1915 verifyReference(thread->threadObj);
1916
1917 LOGI("verify exception=%p", thread->exception);
1918 verifyReference(thread->exception);
1919
1920 LOGI("verify thread->internalLocalRefTable");
1921 verifyReferenceTable(&thread->internalLocalRefTable);
1922
1923 LOGI("verify thread->jniLocalRefTable");
1924 verifyReferenceTable(&thread->jniLocalRefTable);
1925
1926 /* Can the check be pushed into the promote routine? */
1927 if (thread->jniMonitorRefTable.table) {
1928 LOGI("verify thread->jniMonitorRefTable");
1929 verifyReferenceTable(&thread->jniMonitorRefTable);
1930 }
1931
1932 verifyThreadStack(thread);
1933}
1934
1935static void verifyThreadList(void)
1936{
1937 Thread *thread;
1938
1939 dvmLockThreadList(dvmThreadSelf());
1940 thread = gDvm.threadList;
1941 while (thread) {
1942 verifyThread(thread);
1943 thread = thread->next;
1944 }
1945 dvmUnlockThreadList();
1946}
1947
1948static void pinThread(Thread *thread)
1949{
1950 assert(thread != NULL);
1951 assert(thread->status != THREAD_RUNNING ||
1952 thread->isSuspended ||
1953 thread == dvmThreadSelf());
1954 LOGI("pinThread(thread=%p)", thread);
1955
1956 LOGI("Pin internalLocalRefTable");
1957 pinReferenceTable(&thread->internalLocalRefTable);
1958
1959 LOGI("Pin jniLocalRefTable");
1960 pinReferenceTable(&thread->jniLocalRefTable);
1961
1962 /* Can the check be pushed into the promote routine? */
1963 if (thread->jniMonitorRefTable.table) {
1964 LOGI("Pin jniMonitorRefTable");
1965 pinReferenceTable(&thread->jniMonitorRefTable);
1966 }
1967}
1968
1969static void pinThreadList(void)
1970{
1971 Thread *thread;
1972
1973 dvmLockThreadList(dvmThreadSelf());
1974 thread = gDvm.threadList;
1975 while (thread) {
1976 pinThread(thread);
1977 thread = thread->next;
1978 }
1979 dvmUnlockThreadList();
1980}
1981
1982/*
1983 * Heap block scavenging.
1984 */
1985
1986/*
1987 * Scavenge objects in the current block. Scavenging terminates when
1988 * the pointer reaches the highest address in the block or when a run
1989 * of zero words that continues to the highest address is reached.
1990 */
1991static void scavengeBlock(HeapSource *heapSource, size_t block)
1992{
1993 u1 *cursor;
1994 u1 *end;
1995 size_t size;
1996
1997 LOG_SCAVENGE("scavengeBlock(heapSource=%p,block=%zu)", heapSource, block);
1998
1999 assert(heapSource != NULL);
2000 assert(block < heapSource->totalBlocks);
2001 assert(heapSource->blockSpace[block] == BLOCK_TO_SPACE);
2002
2003 cursor = blockToAddress(heapSource, block);
2004 end = cursor + BLOCK_SIZE;
2005 LOG_SCAVENGE("scavengeBlock start=%p, end=%p", cursor, end);
2006
2007 /* Parse and scavenge the current block. */
2008 size = 0;
2009 while (cursor < end) {
2010 u4 word = *(u4 *)cursor;
2011 if (word != 0) {
Carl Shapiro2396fda2010-05-03 20:14:14 -07002012 scavengeObject((Object *)cursor);
2013 size = objectSize((Object *)cursor);
Carl Shapirod28668c2010-04-15 16:10:00 -07002014 size = alignUp(size, ALLOC_ALIGNMENT);
2015 cursor += size;
2016 } else if (word == 0 && cursor == (u1 *)gDvm.unlinkedJavaLangClass) {
2017 size = sizeof(ClassObject);
2018 cursor += size;
2019 } else {
2020 /* Check for padding. */
2021 while (*(u4 *)cursor == 0) {
2022 cursor += 4;
2023 if (cursor == end) break;
2024 }
2025 /* Punt if something went wrong. */
2026 assert(cursor == end);
2027 }
2028 }
2029}
2030
Carl Shapiro2396fda2010-05-03 20:14:14 -07002031static size_t objectSize(const Object *obj)
Carl Shapirod28668c2010-04-15 16:10:00 -07002032{
2033 size_t size;
2034
Carl Shapiro2396fda2010-05-03 20:14:14 -07002035 assert(obj != NULL);
2036 assert(obj->clazz != NULL);
Carl Shapirod28668c2010-04-15 16:10:00 -07002037 if (obj->clazz == gDvm.classJavaLangClass ||
2038 obj->clazz == gDvm.unlinkedJavaLangClass) {
2039 size = dvmClassObjectSize((ClassObject *)obj);
2040 } else if (IS_CLASS_FLAG_SET(obj->clazz, CLASS_ISARRAY)) {
2041 size = dvmArrayObjectSize((ArrayObject *)obj);
2042 } else {
Carl Shapiro2396fda2010-05-03 20:14:14 -07002043 assert(obj->clazz->objectSize != 0);
Carl Shapirod28668c2010-04-15 16:10:00 -07002044 size = obj->clazz->objectSize;
2045 }
Carl Shapiro2396fda2010-05-03 20:14:14 -07002046 if (LW_HASH_STATE(obj->lock) == LW_HASH_STATE_HASHED_AND_MOVED) {
2047 size += sizeof(u4);
2048 }
Carl Shapirod28668c2010-04-15 16:10:00 -07002049 return size;
2050}
2051
2052static void verifyBlock(HeapSource *heapSource, size_t block)
2053{
2054 u1 *cursor;
2055 u1 *end;
2056 size_t size;
2057
2058 // LOGI("verifyBlock(heapSource=%p,block=%zu)", heapSource, block);
2059
2060 assert(heapSource != NULL);
2061 assert(block < heapSource->totalBlocks);
2062 assert(heapSource->blockSpace[block] == BLOCK_TO_SPACE);
2063
2064 cursor = blockToAddress(heapSource, block);
2065 end = cursor + BLOCK_SIZE;
2066 // LOGI("verifyBlock start=%p, end=%p", cursor, end);
2067
2068 /* Parse and scavenge the current block. */
2069 size = 0;
2070 while (cursor < end) {
2071 u4 word = *(u4 *)cursor;
2072 if (word != 0) {
2073 dvmVerifyObject((Object *)cursor);
2074 size = objectSize((Object *)cursor);
2075 size = alignUp(size, ALLOC_ALIGNMENT);
2076 cursor += size;
2077 } else if (word == 0 && cursor == (u1 *)gDvm.unlinkedJavaLangClass) {
2078 size = sizeof(ClassObject);
2079 cursor += size;
2080 } else {
2081 /* Check for padding. */
2082 while (*(unsigned long *)cursor == 0) {
2083 cursor += 4;
2084 if (cursor == end) break;
2085 }
2086 /* Punt if something went wrong. */
2087 assert(cursor == end);
2088 }
2089 }
2090}
2091
2092static void describeBlockQueue(const HeapSource *heapSource)
2093{
2094 size_t block, count;
2095 char space;
2096
2097 block = heapSource->queueHead;
2098 count = 0;
2099 LOG_SCAVENGE(">>> describeBlockQueue(heapSource=%p)", heapSource);
2100 /* Count the number of blocks enqueued. */
2101 while (block != QUEUE_TAIL) {
2102 block = heapSource->blockQueue[block];
2103 ++count;
2104 }
2105 LOG_SCAVENGE("blockQueue %zu elements, enqueued %zu",
2106 count, heapSource->queueSize);
2107 block = heapSource->queueHead;
2108 while (block != QUEUE_TAIL) {
2109 space = heapSource->blockSpace[block];
2110 LOG_SCAVENGE("block=%zu@%p,space=%zu", block, blockToAddress(heapSource,block), space);
2111 block = heapSource->blockQueue[block];
2112 }
2113
2114 LOG_SCAVENGE("<<< describeBlockQueue(heapSource=%p)", heapSource);
2115}
2116
2117/*
2118 * Blackens promoted objects.
2119 */
2120static void scavengeBlockQueue(void)
2121{
2122 HeapSource *heapSource;
2123 size_t block;
2124
2125 LOG_SCAVENGE(">>> scavengeBlockQueue()");
2126 heapSource = gDvm.gcHeap->heapSource;
2127 describeBlockQueue(heapSource);
2128 while (heapSource->queueHead != QUEUE_TAIL) {
2129 block = heapSource->queueHead;
2130 LOG_SCAVENGE("Dequeueing block %zu\n", block);
2131 scavengeBlock(heapSource, block);
2132 heapSource->queueHead = heapSource->blockQueue[block];
2133 LOGI("New queue head is %zu\n", heapSource->queueHead);
2134 }
2135 LOG_SCAVENGE("<<< scavengeBlockQueue()");
2136}
2137
2138/*
2139 * Scan the block list and verify all blocks that are marked as being
2140 * in new space. This should be parametrized so we can invoke this
2141 * routine outside of the context of a collection.
2142 */
2143static void verifyNewSpace(void)
2144{
2145 HeapSource *heapSource;
2146 size_t i;
2147 size_t c0, c1, c2, c7;
2148
2149 c0 = c1 = c2 = c7 = 0;
2150 heapSource = gDvm.gcHeap->heapSource;
2151 for (i = 0; i < heapSource->totalBlocks; ++i) {
2152 switch (heapSource->blockSpace[i]) {
2153 case BLOCK_FREE: ++c0; break;
2154 case BLOCK_TO_SPACE: ++c1; break;
2155 case BLOCK_FROM_SPACE: ++c2; break;
2156 case BLOCK_CONTINUED: ++c7; break;
2157 default: assert(!"reached");
2158 }
2159 }
2160 LOG_VERIFY("Block Demographics: "
2161 "Free=%zu,ToSpace=%zu,FromSpace=%zu,Continued=%zu",
2162 c0, c1, c2, c7);
2163 for (i = 0; i < heapSource->totalBlocks; ++i) {
2164 if (heapSource->blockSpace[i] != BLOCK_TO_SPACE) {
2165 continue;
2166 }
2167 verifyBlock(heapSource, i);
2168 }
2169}
2170
2171static void scavengeGlobals(void)
2172{
2173 scavengeReference((Object **)(void *)&gDvm.classJavaLangClass);
2174 scavengeReference((Object **)(void *)&gDvm.classJavaLangClassArray);
2175 scavengeReference((Object **)(void *)&gDvm.classJavaLangError);
2176 scavengeReference((Object **)(void *)&gDvm.classJavaLangObject);
2177 scavengeReference((Object **)(void *)&gDvm.classJavaLangObjectArray);
2178 scavengeReference((Object **)(void *)&gDvm.classJavaLangRuntimeException);
2179 scavengeReference((Object **)(void *)&gDvm.classJavaLangString);
2180 scavengeReference((Object **)(void *)&gDvm.classJavaLangThread);
2181 scavengeReference((Object **)(void *)&gDvm.classJavaLangVMThread);
2182 scavengeReference((Object **)(void *)&gDvm.classJavaLangThreadGroup);
2183 scavengeReference((Object **)(void *)&gDvm.classJavaLangThrowable);
2184 scavengeReference((Object **)(void *)&gDvm.classJavaLangStackTraceElement);
2185 scavengeReference((Object **)(void *)&gDvm.classJavaLangStackTraceElementArray);
2186 scavengeReference((Object **)(void *)&gDvm.classJavaLangAnnotationAnnotationArray);
2187 scavengeReference((Object **)(void *)&gDvm.classJavaLangAnnotationAnnotationArrayArray);
2188 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectAccessibleObject);
2189 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectConstructor);
2190 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectConstructorArray);
2191 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectField);
2192 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectFieldArray);
2193 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectMethod);
2194 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectMethodArray);
2195 scavengeReference((Object **)(void *)&gDvm.classJavaLangReflectProxy);
2196 scavengeReference((Object **)(void *)&gDvm.classJavaLangExceptionInInitializerError);
2197 scavengeReference((Object **)(void *)&gDvm.classJavaLangRefReference);
2198 scavengeReference((Object **)(void *)&gDvm.classJavaNioReadWriteDirectByteBuffer);
2199 scavengeReference((Object **)(void *)&gDvm.classJavaSecurityAccessController);
2200 scavengeReference((Object **)(void *)&gDvm.classOrgApacheHarmonyLangAnnotationAnnotationFactory);
2201 scavengeReference((Object **)(void *)&gDvm.classOrgApacheHarmonyLangAnnotationAnnotationMember);
2202 scavengeReference((Object **)(void *)&gDvm.classOrgApacheHarmonyLangAnnotationAnnotationMemberArray);
2203 scavengeReference((Object **)(void *)&gDvm.classOrgApacheHarmonyNioInternalDirectBuffer);
2204 scavengeReference((Object **)(void *)&gDvm.classArrayBoolean);
2205 scavengeReference((Object **)(void *)&gDvm.classArrayChar);
2206 scavengeReference((Object **)(void *)&gDvm.classArrayFloat);
2207 scavengeReference((Object **)(void *)&gDvm.classArrayDouble);
2208 scavengeReference((Object **)(void *)&gDvm.classArrayByte);
2209 scavengeReference((Object **)(void *)&gDvm.classArrayShort);
2210 scavengeReference((Object **)(void *)&gDvm.classArrayInt);
2211 scavengeReference((Object **)(void *)&gDvm.classArrayLong);
2212}
2213
2214void describeHeap(void)
2215{
2216 HeapSource *heapSource;
2217
2218 heapSource = gDvm.gcHeap->heapSource;
2219 describeBlocks(heapSource);
2220}
2221
2222/*
2223 * The collection interface. Collection has a few distinct phases.
2224 * The first is flipping AKA condemning AKA whitening the heap. The
2225 * second is to promote all objects which are pointed to by pinned or
2226 * ambiguous references. The third phase is tracing from the stacks,
2227 * registers and various globals. Lastly, a verification of the heap
2228 * is performed. The last phase should be optional.
2229 */
2230void dvmScavengeRoots(void) /* Needs a new name badly */
2231{
2232 HeapRefTable *refs;
2233 GcHeap *gcHeap;
2234
2235 {
2236 size_t alloc, unused, total;
2237
2238 room(&alloc, &unused, &total);
2239 LOGI("BEFORE GC: %zu alloc, %zu free, %zu total.",
2240 alloc, unused, total);
2241 }
2242
2243 gcHeap = gDvm.gcHeap;
2244 dvmHeapSourceFlip();
2245
2246 /*
2247 * Promote blocks with stationary objects.
2248 */
2249
2250 // LOGI("Pinning gDvm.threadList");
2251 pinThreadList();
2252
2253 // LOGI("Pinning gDvm.jniGlobalRefTable");
2254 pinReferenceTable(&gDvm.jniGlobalRefTable);
2255
2256 // LOGI("Pinning gDvm.jniPinRefTable");
2257 pinReferenceTable(&gDvm.jniPinRefTable);
2258
2259 // LOGI("Pinning gDvm.gcHeap->nonCollectableRefs");
2260 pinReferenceTable(&gcHeap->nonCollectableRefs);
2261
2262 // LOGI("Pinning gDvm.loadedClasses");
2263 pinHashTableEntries(gDvm.loadedClasses);
2264
2265 // LOGI("Pinning gDvm.primitiveClass");
2266 pinPrimitiveClasses();
2267
2268 // LOGI("Pinning gDvm.internedStrings");
2269 pinInternedStrings();
2270
2271 // describeBlocks(gcHeap->heapSource);
2272
2273 /*
2274 * Create first, open new-space page right here.
2275 */
2276
2277 /* Reset allocation to an unallocated block. */
2278 gDvm.gcHeap->heapSource->allocPtr = allocateBlocks(gDvm.gcHeap->heapSource, 1);
2279 gDvm.gcHeap->heapSource->allocLimit = gDvm.gcHeap->heapSource->allocPtr + BLOCK_SIZE;
2280 /*
2281 * Hack: promote the empty block allocated above. If the
2282 * promotions that occurred above did not actually gray any
2283 * objects, the block queue may be empty. We must force a
2284 * promotion to be safe.
2285 */
2286 promoteBlockByAddr(gDvm.gcHeap->heapSource, gDvm.gcHeap->heapSource->allocPtr);
2287
2288 /*
2289 * Scavenge blocks and relocate movable objects.
2290 */
2291
2292 LOGI("Scavenging gDvm.threadList");
2293 scavengeThreadList();
2294
2295 LOGI("Scavenging gDvm.gcHeap->referenceOperations");
2296 scavengeLargeHeapRefTable(gcHeap->referenceOperations);
2297
2298 LOGI("Scavenging gDvm.gcHeap->pendingFinalizationRefs");
2299 scavengeLargeHeapRefTable(gcHeap->pendingFinalizationRefs);
2300
2301 LOGI("Scavenging random global stuff");
2302 scavengeReference(&gDvm.outOfMemoryObj);
2303 scavengeReference(&gDvm.internalErrorObj);
2304 scavengeReference(&gDvm.noClassDefFoundErrorObj);
2305
2306 LOGI("Scavenging gDvm.dbgRegistry");
2307 scavengeHashTable(gDvm.dbgRegistry);
2308
2309 // LOGI("Scavenging gDvm.internedString");
2310 scavengeInternedStrings();
2311
2312 LOGI("Root scavenge has completed.");
2313
2314 scavengeBlockQueue();
2315
2316 LOGI("Re-snap global class pointers.");
2317 scavengeGlobals();
2318
2319 LOGI("New space scavenge has completed.");
2320
2321 /*
2322 * Verify the stack and heap.
2323 */
2324
2325 // LOGI("Validating new space.");
2326
2327 verifyInternedStrings();
2328
2329 verifyThreadList();
2330
2331 verifyNewSpace();
2332
2333 // LOGI("New space verify has completed.");
2334
2335 //describeBlocks(gcHeap->heapSource);
2336
2337 clearFromSpace(gcHeap->heapSource);
2338
2339 {
2340 size_t alloc, rem, total;
2341
2342 room(&alloc, &rem, &total);
2343 LOGI("AFTER GC: %zu alloc, %zu free, %zu total.", alloc, rem, total);
2344 }
2345}
2346
2347/*
2348 * Interface compatibility routines.
2349 */
2350
2351void dvmClearWhiteRefs(Object **list)
2352{
2353 /* TODO */
2354 assert(*list == NULL);
2355}
2356
2357void dvmHandleSoftRefs(Object **list)
2358{
2359 /* TODO */
2360 assert(*list == NULL);
2361}
2362
2363bool dvmHeapBeginMarkStep(GcMode mode)
2364{
2365 /* do nothing */
2366 return true;
2367}
2368
2369void dvmHeapFinishMarkStep(void)
2370{
2371 /* do nothing */
2372}
2373
2374void dvmHeapMarkRootSet(void)
2375{
2376 /* do nothing */
2377}
2378
2379void dvmHeapScanMarkedObjects(void)
2380{
2381 dvmScavengeRoots();
2382}
2383
2384void dvmHeapScheduleFinalizations(void)
2385{
2386 /* do nothing */
2387}
2388
2389void dvmHeapSweepUnmarkedObjects(GcMode mode, int *numFreed, size_t *sizeFreed)
2390{
2391 /* do nothing */
2392}
2393
2394void dvmMarkObjectNonNull(const Object *obj)
2395{
2396 assert(!"implemented");
2397}