void GCMarkPhase(void) { mainThreadPhase = MTP_GCPHASEMARK; // Clear the mark counters and set the rescan limits. for(unsigned k = 0; k < gMem.nlSpaces; k++) { LocalMemSpace *lSpace = gMem.lSpaces[k]; lSpace->i_marked = lSpace->m_marked = 0; lSpace->fullGCRescanStart = lSpace->top; lSpace->fullGCRescanEnd = lSpace->bottom; } MTGCProcessMarkPointers::MarkRoots(); gpTaskFarm->WaitForCompletion(); // Do we have to rescan because the mark stack overflowed? bool rescan; do { rescan = MTGCProcessMarkPointers::RescanForStackOverflow(); gpTaskFarm->WaitForCompletion(); } while(rescan); gHeapSizeParameters.RecordGCTime(HeapSizeParameters::GCTimeIntermediate, "Mark"); // Turn the marks into bitmap entries. for (unsigned i = 0; i < gMem.nlSpaces; i++) gpTaskFarm->AddWorkOrRunNow(&CreateBitmapsTask, gMem.lSpaces[i], 0); gpTaskFarm->WaitForCompletion(); // Wait for completion of the bitmaps gHeapSizeParameters.RecordGCTime(HeapSizeParameters::GCTimeIntermediate, "Bitmap"); POLYUNSIGNED totalLive = 0; for(unsigned l = 0; l < gMem.nlSpaces; l++) { LocalMemSpace *lSpace = gMem.lSpaces[l]; if (! lSpace->isMutable) ASSERT(lSpace->m_marked == 0); totalLive += lSpace->m_marked + lSpace->i_marked; if (debugOptions & DEBUG_GC) Log("GC: Mark: %s space %p: %" POLYUFMT " immutable words marked, %" POLYUFMT " mutable words marked\n", lSpace->spaceTypeString(), lSpace, lSpace->i_marked, lSpace->m_marked); } if (debugOptions & DEBUG_GC) Log("GC: Mark: Total live data %" POLYUFMT " words\n", totalLive); }
// Copy objects from the source space into an earlier space or up within the // current space. static void copyAllData(GCTaskId *id, void * /*arg1*/, void * /*arg2*/) { LocalMemSpace *mutableDest = 0, *immutableDest = 0; for (std::vector<LocalMemSpace*>::reverse_iterator i = gMem.lSpaces.rbegin(); i != gMem.lSpaces.rend(); i++) { LocalMemSpace *src = *i; if (src->spaceOwner == 0) { PLocker lock(©Lock); if (src->spaceOwner == 0) src->spaceOwner = id; else continue; } else if (src->spaceOwner != id) continue; if (debugOptions & DEBUG_GC_ENHANCED) Log("GC: Copy: copying area %p (thread %p) %s \n", src, id, src->spaceTypeString()); // We start at fullGCLowerLimit which is the lowest marked object in the heap // N.B. It's essential that the first set bit at or above this corresponds // to the length word of a real object. uintptr_t bitno = src->wordNo(src->fullGCLowerLimit); // Set the limit to the top so we won't rescan this. That can // only happen if copying takes a very short time and the same // thread runs multiple tasks. src->fullGCLowerLimit = src->top; // src->highest is the bit position that corresponds to the top of // generation we're copying. uintptr_t highest = src->wordNo(src->top); for (;;) { if (bitno >= highest) break; /* SPF version; Invariant: 0 < highest - bitno */ bitno += src->bitmap.CountZeroBits(bitno, highest - bitno); if (bitno >= highest) break; /* first set bit corresponds to the length word */ PolyWord *old = src->wordAddr(bitno); /* Old object address */ PolyObject *obj = (PolyObject*)(old+1); POLYUNSIGNED L = obj->LengthWord(); ASSERT (OBJ_IS_LENGTH(L)); POLYUNSIGNED n = OBJ_OBJECT_LENGTH(L) + 1 ;/* Length of allocation (including length word) */ bitno += n; // Find a mutable space for the mutable objects and an immutable space for // the immutables. We copy objects into earlier spaces or within its own // space but we don't copy an object to a later space. This avoids the // risk of copying an object multiple times. Previously this copied objects // into later spaces but that doesn't work well if we have converted old // saved state segments into local areas. It's much better to delete them // if possible. bool isMutable = OBJ_IS_MUTABLE_OBJECT(L); LocalMemSpace *destSpace = isMutable || immutableDest == 0 ? mutableDest : immutableDest; PolyWord *newp = FindFreeAndAllocate(destSpace, (src == destSpace) ? bitno : 0, n); if (newp == 0 && src != destSpace) { // See if we can find a different space. // N.B. FindNextSpace side-effects mutableDest/immutableDest to give the next space. if (FindNextSpace(src, isMutable ? &mutableDest : &immutableDest, isMutable, id)) { bitno -= n; // Redo this object continue; } // else just leave it } if (newp == 0) /* no room */ { // We're not going to move this object // Update src->upperAllocPtr, so the old object doesn't get trampled. if (old < src->upperAllocPtr) src->upperAllocPtr = old; // Previously this continued compressing to try to make space available // on the next GC. Normally full GCs are infrequent so the chances are // that at the next GC other data will have been freed. Just stop at // this point. // However if we're compressing a mutable area and there is immutable // data in it we should move those out because the mutable area is scanned // on every partial GC. if (! src->isMutable || src->i_marked == 0) break; } else { PolyObject *destAddress = (PolyObject*)(newp+1); obj->SetForwardingPtr(destAddress); CopyObjectToNewAddress(obj, destAddress, L); if (debugOptions & DEBUG_GC_DETAIL) Log("GC: Copy: %p %lu %u -> %p\n", obj, OBJ_OBJECT_LENGTH(L), GetTypeBits(L), destAddress); } } if (mutableDest == src) mutableDest = 0; if (immutableDest == src) immutableDest = 0; } }
/* How the garbage collector works. The GC has two phases. The minor (quick) GC is a copying collector that copies data from the allocation area into the mutable and immutable area. The major collector is started when either the mutable or the immutable area is full. The major collector uses a mark/sweep scheme. The GC has three phases: 1. Mark phase. Working from the roots; which are the the permanent mutable segments and the RTS roots (e.g. thread stacks), mark all reachable cells. Marking involves setting bits in the bitmap for reachable words. 2. Compact phase. Marked objects are copied to try to compact, upwards, the heap segments. When an object is moved the length word of the object in the old location is set as a tombstone that points to its new location. In particular this means that we cannot reuse the space where an object previously was during the compaction phase. Immutable objects are moved into immutable segments. When an object is moved to a new location the bits are set in the bitmap as though the object had been marked at that location. 3. Update phase. The roots and objects marked during the first two phases are scanned and any addresses for moved objects are updated. The lowest address used in the area then becomes the base of the area for future allocations. There is a sharing phase which may be performed before the mark phase. This merges immutable cells with the same contents with the aim of reducing the size of the live data. It is expensive so is not performed by default. Updated DCJM 12/06/12 */ static bool doGC(const POLYUNSIGNED wordsRequiredToAllocate) { unsigned j; gHeapSizeParameters.RecordAtStartOfMajorGC(); gHeapSizeParameters.RecordGCTime(HeapSizeParameters::GCTimeStart); globalStats.incCount(PSC_GC_FULLGC); // Remove any empty spaces. There will not normally be any except // if we have triggered a full GC as a result of detecting paging in the // minor GC but in that case we want to try to stop the system writing // out areas that are now empty. gMem.RemoveEmptyLocals(); if (debugOptions & DEBUG_GC) Log("GC: Full GC, %lu words required %u spaces\n", wordsRequiredToAllocate, gMem.nlSpaces); if (debugOptions & DEBUG_HEAPSIZE) gMem.ReportHeapSizes("Full GC (before)"); // Data sharing pass. if (gHeapSizeParameters.PerformSharingPass()) GCSharingPhase(); /* * There is a really weird bug somewhere. An extra bit may be set in the bitmap during * the mark phase. It seems to be related to heavy swapping activity. Duplicating the * bitmap causes it to occur only in one copy and write-protecting the bitmap apart from * when it is actually being updated does not result in a seg-fault. So far I've only * seen it on 64-bit Linux but it may be responsible for other crashes. The work-around * is to check the number of bits set in the bitmap and repeat the mark phase if it does * not match. */ for (unsigned p = 3; p > 0; p--) { for(j = 0; j < gMem.nlSpaces; j++) { LocalMemSpace *lSpace = gMem.lSpaces[j]; ASSERT (lSpace->top >= lSpace->upperAllocPtr); ASSERT (lSpace->upperAllocPtr >= lSpace->lowerAllocPtr); ASSERT (lSpace->lowerAllocPtr >= lSpace->bottom); // Set upper and lower limits of weak refs. lSpace->highestWeak = lSpace->bottom; lSpace->lowestWeak = lSpace->top; lSpace->fullGCLowerLimit = lSpace->top; // Put dummy objects in the unused space. This allows // us to scan over the whole of the space. gMem.FillUnusedSpace(lSpace->lowerAllocPtr, lSpace->upperAllocPtr-lSpace->lowerAllocPtr); } // Set limits of weak refs. for (j = 0; j < gMem.npSpaces; j++) { PermanentMemSpace *pSpace = gMem.pSpaces[j]; pSpace->highestWeak = pSpace->bottom; pSpace->lowestWeak = pSpace->top; } /* Mark phase */ GCMarkPhase(); POLYUNSIGNED bitCount = 0, markCount = 0; for (j = 0; j < gMem.nlSpaces; j++) { LocalMemSpace *lSpace = gMem.lSpaces[j]; markCount += lSpace->i_marked + lSpace->m_marked; bitCount += lSpace->bitmap.CountSetBits(lSpace->spaceSize()); } if (markCount == bitCount) break; else { // Report an error. If this happens again we crash. Log("GC: Count error for space %u - mark count %lu, bitCount %lu\n", j, markCount, bitCount); if (p == 1) { ASSERT(markCount == bitCount); } } } for(j = 0; j < gMem.nlSpaces; j++) { LocalMemSpace *lSpace = gMem.lSpaces[j]; // Reset the allocation pointers. They will be set to the // limits of the retained data. lSpace->lowerAllocPtr = lSpace->bottom; lSpace->upperAllocPtr = lSpace->top; } if (debugOptions & DEBUG_GC) Log("GC: Check weak refs\n"); /* Detect unreferenced streams, windows etc. */ GCheckWeakRefs(); // Check that the heap is not overfull. We make sure the marked // mutable and immutable data is no more than 90% of the // corresponding areas. This is a very coarse adjustment. { POLYUNSIGNED iMarked = 0, mMarked = 0; POLYUNSIGNED iSpace = 0, mSpace = 0; for (unsigned i = 0; i < gMem.nlSpaces; i++) { LocalMemSpace *lSpace = gMem.lSpaces[i]; iMarked += lSpace->i_marked; mMarked += lSpace->m_marked; if (! lSpace->allocationSpace) { if (lSpace->isMutable) mSpace += lSpace->spaceSize(); else iSpace += lSpace->spaceSize(); } } // Add space if necessary and possible. while (iMarked > iSpace - iSpace/10 && gHeapSizeParameters.AddSpaceBeforeCopyPhase(false) != 0) iSpace += gMem.DefaultSpaceSize(); while (mMarked > mSpace - mSpace/10 && gHeapSizeParameters.AddSpaceBeforeCopyPhase(true) != 0) mSpace += gMem.DefaultSpaceSize(); } /* Compact phase */ GCCopyPhase(); gHeapSizeParameters.RecordGCTime(HeapSizeParameters::GCTimeIntermediate, "Copy"); // Update Phase. if (debugOptions & DEBUG_GC) Log("GC: Update\n"); GCUpdatePhase(); gHeapSizeParameters.RecordGCTime(HeapSizeParameters::GCTimeIntermediate, "Update"); { POLYUNSIGNED iUpdated = 0, mUpdated = 0, iMarked = 0, mMarked = 0; for(j = 0; j < gMem.nlSpaces; j++) { LocalMemSpace *lSpace = gMem.lSpaces[j]; iMarked += lSpace->i_marked; mMarked += lSpace->m_marked; if (lSpace->isMutable) mUpdated += lSpace->updated; else iUpdated += lSpace->updated; } ASSERT(iUpdated+mUpdated == iMarked+mMarked); } // Delete empty spaces. gMem.RemoveEmptyLocals(); if (debugOptions & DEBUG_GC) { for(j = 0; j < gMem.nlSpaces; j++) { LocalMemSpace *lSpace = gMem.lSpaces[j]; Log("GC: %s space %p %d free in %d words %2.1f%% full\n", lSpace->spaceTypeString(), lSpace, lSpace->freeSpace(), lSpace->spaceSize(), ((float)lSpace->allocatedSpace()) * 100 / (float)lSpace->spaceSize()); } } // Compute values for statistics globalStats.setSize(PSS_AFTER_LAST_GC, 0); globalStats.setSize(PSS_AFTER_LAST_FULLGC, 0); globalStats.setSize(PSS_ALLOCATION, 0); globalStats.setSize(PSS_ALLOCATION_FREE, 0); for (j = 0; j < gMem.nlSpaces; j++) { LocalMemSpace *space = gMem.lSpaces[j]; POLYUNSIGNED free = space->freeSpace(); globalStats.incSize(PSS_AFTER_LAST_GC, free*sizeof(PolyWord)); globalStats.incSize(PSS_AFTER_LAST_FULLGC, free*sizeof(PolyWord)); if (space->allocationSpace) { globalStats.incSize(PSS_ALLOCATION, free*sizeof(PolyWord)); globalStats.incSize(PSS_ALLOCATION_FREE, free*sizeof(PolyWord)); } #ifdef FILL_UNUSED_MEMORY memset(space->bottom, 0xaa, (char*)space->upperAllocPtr - (char*)space->bottom); #endif if (debugOptions & DEBUG_GC) Log("GC: %s space %p %d free in %d words %2.1f%% full\n", space->spaceTypeString(), space, space->freeSpace(), space->spaceSize(), ((float)space->allocatedSpace()) * 100 / (float)space->spaceSize()); } // End of garbage collection gHeapSizeParameters.RecordGCTime(HeapSizeParameters::GCTimeEnd); // Now we've finished we can adjust the heap sizes. gHeapSizeParameters.AdjustSizeAfterMajorGC(wordsRequiredToAllocate); gHeapSizeParameters.resetMajorTimingData(); bool haveSpace = gMem.CheckForAllocation(wordsRequiredToAllocate); // Invariant: the bitmaps are completely clean. if (debugOptions & DEBUG_GC) { if (haveSpace) Log("GC: Completed successfully\n"); else Log("GC: Completed with insufficient space\n"); } if (debugOptions & DEBUG_HEAPSIZE) gMem.ReportHeapSizes("Full GC (after)"); if (profileMode == kProfileLiveData || profileMode == kProfileLiveMutables) printprofile(); CheckMemory(); return haveSpace; // Completed }