Beispiel #1
0
// Allocate an area of the heap of at least minWords and at most maxWords.
// This is used both when allocating single objects (when minWords and maxWords
// are the same) and when allocating heap segments.  If there is insufficient
// space to satisfy the minimum it will return 0.
PolyWord *MemMgr::AllocHeapSpace(POLYUNSIGNED minWords, POLYUNSIGNED &maxWords, bool doAllocation)
{
    PLocker locker(&allocLock);
    // We try to distribute the allocations between the memory spaces
    // so that at the next GC we don't have all the most recent cells in
    // one space.  The most recent cells will be more likely to survive a
    // GC so distibuting them improves the load balance for a multi-thread GC.
    nextAllocator++;
    if (nextAllocator > gMem.nlSpaces) nextAllocator = 0;

    for (unsigned j = 0; j < gMem.nlSpaces; j++)
    {
        LocalMemSpace *space = gMem.lSpaces[(j + nextAllocator) % gMem.nlSpaces];
        if (space->allocationSpace)
        {
            POLYUNSIGNED available = space->freeSpace();
            if (available > 0 && available >= minWords)
            {
                // Reduce the maximum value if we had less than that.
                if (available < maxWords)
                    maxWords = available;
                PolyWord *result = space->lowerAllocPtr; // Return the address.
                if (doAllocation)
                    space->lowerAllocPtr += maxWords; // Allocate it.
                return result;
            }
        }
    }
    // There isn't space in the existing areas - can we create a new area?
    // The reason we don't have enough space could simply be that we want to
    // allocate an object larger than the default space size.  Try deleting
    // some other spaces to bring currentAllocSpace below spaceBeforeMinorGC - minWords.
    if (minWords > defaultSpaceSize && minWords < spaceBeforeMinorGC)
        RemoveExcessAllocation(spaceBeforeMinorGC - minWords);

    if (currentAllocSpace < spaceBeforeMinorGC && minWords < spaceBeforeMinorGC - currentAllocSpace)
    {
        POLYUNSIGNED spaceSize = defaultSpaceSize;
        if (minWords > spaceSize) spaceSize = minWords; // If we really want a large space.
        LocalMemSpace *space = CreateAllocationSpace(spaceSize);
        if (space == 0) return 0; // Can't allocate it
        // Allocate our space in this new area.
        POLYUNSIGNED available = space->freeSpace();
        ASSERT(available >= minWords);
        if (available < maxWords)
            maxWords = available;
        PolyWord *result = space->lowerAllocPtr; // Return the address.
        if (doAllocation)
            space->lowerAllocPtr += maxWords; // Allocate it.
        return result;
    }
    return 0; // There isn't space even for the minimum.
}
Beispiel #2
0
// Return number of words free in all allocation spaces.
POLYUNSIGNED MemMgr::GetFreeAllocSpace()
{
    POLYUNSIGNED freeSpace = 0;
    PLocker lock(&allocLock);
    for (unsigned j = 0; j < gMem.nlSpaces; j++)
    {
        LocalMemSpace *space = gMem.lSpaces[j];
        if (space->allocationSpace)
            freeSpace += space->freeSpace();
    }
    return freeSpace;
}
Beispiel #3
0
// Create a local space for initial allocation.
LocalMemSpace *MemMgr::CreateAllocationSpace(POLYUNSIGNED size)
{
    LocalMemSpace *result = NewLocalSpace(size, true);
    if (result) 
    {
        result->allocationSpace = true;
        currentAllocSpace += result->spaceSize();
        globalStats.incSize(PSS_ALLOCATION, result->spaceSize()*sizeof(PolyWord));
        globalStats.incSize(PSS_ALLOCATION_FREE, result->freeSpace()*sizeof(PolyWord));
    }
    return result;
}
Beispiel #4
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
}