MPS Strategy
============
.. mps:prefix:: design.mps.strategy
Introduction
------------
_`.intro` This is the design of collection strategy for the MPS.
_`.readership` MPS developers.
Overview
--------
_`.overview` The MPS uses "strategy" code to make three decisions:
- when to start a collection trace;
- what to condemn;
- how to schedule tracing work.
This document describes the current strategy, identifies some
weaknesses in it, and outlines some possible future development
directions.
Requirements
------------
[TODO: source some from req.dylan, or do an up-to-date requirements
analysis -- NB 2013-03-25]
Garbage collection is a trade-off between time and space: it consumes
some [CPU] time in order to save some [memory] space. Strategy shifts
the balance point. A better strategy will take less time to produce
more space. Examples of good strategy might include:
- choosing segments to condemn which contain high proportions of dead
objects;
- starting a trace when a large number of objects have just died;
- doing enough collection soon enough that the client program never
suffers low-memory problems;
- using otherwise-idle CPU resources for tracing.
Conversely, it would be bad strategy to do the reverse of each of
these (condemning live objects; tracing when there's very little
garbage; not collecting enough; tracing when the client program is
busy).
Abstracting from these notions, requirements on strategy would
relate to:
- Maximum pause time and other utilization metrics (for example,
bounded mutator utilization, minimum mutator utilization, total MPS
CPU usage);
- Collecting enough garbage (for example: overall heap size;
low-memory requirements).
- Allowing client control (for example, client recommendations for
collection timing or condemnation).
There are other possible strategy considerations which are so far
outside the scope of current strategy and MPS design that this
document disregards them. For example, either inferring or allowing
the client to specify preferred relative object locations ("this
object should be kept in the same cache line as that one"), to improve
cache locality.
Generations
-----------
The largest part of the current MPS strategy implementation is the
support for generational garbage collections.
General data structures
.......................
The fundamental structure of generational garbage collection is the
:c:type:`Chain`, which describes a sequence of generations.
A chain specifies the "capacity" and "mortality" for each generation.
When creating an automatically collected pool, the client code may
specify the chain which will control collections for that pool. The
same chain may be used for multiple pools. If no chain is specified,
the pool uses the arena's default generation chain.
Each generation in a chain has a :c:type:`GenDesc` structure, allocated in
an array pointed to from the chain. In addition to the generations in
the chains, the arena has a unique :c:type:`GenDesc` structure, named
``topGen`` and described in comments as "the dynamic generation"
(misleadingly: in fact it is the *least* dynamic generation).
Each automatically collected pool has a set of :c:type:`PoolGen` structures,
one for each generation that it can allocate or promote into. The
:c:type:`PoolGen` structures for each generation point to the :c:type:`GenDesc`
for that generation, and are linked together in a ring on the
:c:type:`GenDesc`. These structures are used to gather accounting
information for strategy decisions.
The non-moving automatic pool classes (AMS, AWL and LO) do not support
generational collection, so they allocate into a single generation.
The moving automatic pool classes (AMC and AMCZ) have one pool
generations for each generation in the chain, plus one pool generation
for the arena's "top generation".
AMC data structures
...................
An AMC pool creates an array of pool generation structures of type
``amcGen`` (a subclass of :c:type:`PoolGen`). Each pool generation points to
the *forwarding buffer* for that generation: this is the buffer that
surviving objects are copied into.
AMC segments point to the AMC pool generation that the segment belongs
to, and AMC buffers point to the AMC pool generation that the buffer
will be allocating into.
The forwarding buffers are set up during AMC pool creation. Each
generation forwards into the next higher generation in the chain,
except for the top generation, which forwards to itself. Thus, objects
are "promoted" up the chain of generations until they end up in the
top generations, which is shared between all generational pools.
Collections
...........
Collections in the MPS start in one of two ways:
1. A collection of the world starts via :c:func:`traceCondemnAll()`. This
simply condemns all segments in all automatic pools.
2. A collection of some set of generations starts via :c:func:`TracePoll()`.
This calls :c:func:`ChainDeferral()` for each chain; this function
indicates if the chain needs collecting, and if so, how urgent it
is to collect that chain. The most urgent chain in need of
collection (if any) is then condemned by calling
:c:func:`ChainCondemnAuto()`.
This function chooses the set of generations to condemn, computes
the zoneset corresponding to the union those generations, and
condemns those zones by calling :c:func:`TraceCondemnZones()`.
Note that the condemnation is of every segment in an automatic pool
in any zone in the zoneset. It is not limited to the segments
actually associated with the condemned generations.
Zones
.....
Each generation in each chain has a zoneset associated with it
(``gen->zones``); the condemned zoneset is the union of some number of
generation's zonesets.
An attempt is made to use distinct zonesets for different generations.
Segments in automatic pools are allocated using :c:func:`PoolGenAlloc()`
which creates a :c:type:`SegPref` using the zoneset from the generation's
:c:type:`GenDesc`. The zoneset for each generation starts out empty. If the
zoneset is empty, an attempt is made to allocate from a free zone. The
:c:type:`GenDesc` zoneset is augmented with whichever zones the new segment
occupies.
Note that this zoneset can never shrink.
Parameters
..........
:mps:tag:`param.intro` A generation has two parameters, *capacity* and
*mortality*, specified by the client program.
:mps:tag:`param.capacity` The *capacity* of a generation is the amount of
*new* allocation in that generation (that is, allocation since the
last time the generation was condemned) that will cause the generation
to be collected by :c:func:`TracePoll()`.
:mps:tag:`param.capacity.misnamed` The name *capacity* is unfortunate since
it suggests that the total amount of memory in the generation will not
exceed this value. But that will only be the case for pool classes
that always promote survivors to another generation. When there is
*old* allocation in the generation (that is, prior to the last time
the generation was condemned), as there is in the case of non-moving
pool classes, the size of a generation is unrelated to its capacity.
:mps:tag:`param.mortality` The *mortality* of a generation is the proportion
(between 0 and 1) of memory in the generation that is expected to be
dead when the generation is collected. It is used in :c:func:`TraceStart()`
to estimate the amount of data that will have to be scanned in order
to complete the trace.
Accounting
..........
:mps:tag:`accounting.intro` Pool generations maintain the sizes of various
categories of data allocated in that generation for that pool. This
accounting information is reported via the event system, but also used
in two places:
:mps:tag:`accounting.poll` :c:func:`ChainDeferral()` uses the *new size* of each
generation to determine which generations in the chain are over
capacity and so might need to be collected via :c:func:`TracePoll()`.
:mps:tag:`accounting.condemn` :c:func:`ChainCondemnAuto()` uses the *new size* of
each generation to determine which generations in the chain will be
collected; it also uses the *total size* of the generation to compute
the mortality.
:mps:tag:`accounting.check` Computing the new size for a pool generation is
far from straightforward: see job003772_ for some (former) errors in
this code. In order to assist with checking that this has been
computed correctly, the locus module uses a double-entry book-keeping
system to account for every byte in each pool generation. This uses
six accounts:
.. _job003772: http://www.ravenbrook.com/project/mps/issue/job003772/
:mps:tag:`account.total` Memory acquired from the arena.
:mps:tag:`account.total.negated` From the point of view of the double-entry
system, the *total* should be negative as it is owing to the arena,
but it is inconvenient to represent negative sizes, and so the
positive value is stored instead.
:mps:tag:`account.total.negated.justification` We don't have a type for
signed sizes; but if we represented it in two's complement using the
unsigned :c:type:`Size` type then Clang's unsigned integer overflow detector
would complain.
:mps:tag:`account.free` Memory that is not in use (free or lost to
fragmentation).
:mps:tag:`account.new` Memory in use by the client program, allocated
since the last time the generation was condemned.
:mps:tag:`account.old` Memory in use by the client program, allocated
prior to the last time the generation was condemned.
:mps:tag:`account.newDeferred` Memory in use by the client program,
allocated since the last time the generation was condemned, but which
should not cause collections via :c:func:`TracePoll()`. (Due to ramping; see
below.)
:mps:tag:`account.oldDeferred` Memory in use by the client program,
allocated prior to the last time the generation was condemned, but
which should not cause collections via :c:func:`TracePoll()`. (Due to
ramping; see below.)
:mps:tag:`accounting.op` The following operations are provided:
:mps:tag:`accounting.op.alloc` Allocate a segment in a pool generation.
Debit *total*, credit *free*. (But see :mps:ref:`.account.total.negated`.)
:mps:tag:`accounting.op.free` Free a segment. First, ensure that the
contents of the segment are accounted as free, by artificially ageing
any memory accounted as *new* or *newDeferred* (see
:mps:ref:`.accounting.op.age`) and then artifically reclaiming any memory
accounted as *old* or *oldDeferred* (see :mps:ref:`.accounting.op.reclaim`).
Finally, debit *free*, credit *total*. (But see
:mps:ref:`.account.total.negated`.)
:mps:tag:`accounting.op.fill` Allocate memory, for example by filling a
buffer. Debit *free*, credit *new* or *newDeferred*.
:mps:tag:`accounting.op.empty` Deallocate memory, for example by emptying
the unused portion of a buffer. Debit *new* or *newDeferred*, credit
*free*.
:mps:tag:`accounting.op.age` Condemn memory. Debit *new* or *newDeferred*,
credit *old* or *oldDeferred*.
:mps:tag:`accounting.op.reclaim` Reclaim dead memory. Debit *old* or
*oldDeferred*, credit *free*.
:mps:tag:`accounting.op.undefer` Stop deferring the accounting of memory. Debit *oldDeferred*, credit *old*. Debit *newDeferred*, credit *new*.
Ramps
.....
The intended semantics of ramping are pretty simple. It allows the
client to advise us of periods of large short-lived allocation on a
particular AP. Stuff allocated using that AP during its "ramp" will
probably be dead when the ramp finishes. How the MPS makes use of this
advice is up to us, but for instance we might segregate those objects,
collect them less enthusiastically during the ramp and then more
enthusiastically soon after the ramp finishes. Ramps can nest.
A ramp is entered by calling::
mps_ap_alloc_pattern_begin(ap, mps_alloc_pattern_ramp())
or similar, and left in a similar way.
This is implemented on a per-pool basis, for AMC only (it's ignored by
the other automatic pools). PoolAMC throws away the identity of the AP
specified by the client. The implementation is intended to work by
changing the generational forwarding behaviour, so that there is a "ramp
generation" - one of the regular AMC generations - which forwards to
itself if collected during a ramp (instead of promoting to an older
generation). It also tweaks the strategy calculation code, in a way
with consequences I am documenting elsewhere.
Right now, the code sets this ramp generation to the last generation
specified in the pool's "chain": it ordinarily forwards to the
"after-ramp" generation, which is the "dynamic generation" (i.e. the
least dynamic generation, i.e. the arena-wide "top generation"). My
recollection, and some mentions in design/poolamc, suggests that the
ramp generation used to be chosen differently from this.
So far, it doesn't sound too ghastly, I guess, although the subversion
of the generational system seems a little daft. Read on....
An AMC pool has a ``rampMode`` (which is really a state of a state
machine), taking one of five values: OUTSIDE, BEGIN, RAMPING, FINISH,
and COLLECTING (actually the enum values are called RampX for these
X). We initialize in OUTSIDE. The pool also has a ``rampCount``,
which is the ramp nesting depth and is used to allow us to ignore ramp
transitions other than the outermost. According to design/poolamc,
there's an invariant (in BEGIN or RAMPING, ``rampCount > 0``; in
COLLECTING or OUTSIDE, ``rampCount == 0``), but this isn't checked in
:c:func:`AMCCheck()` and in fact is false for COLLECTING (see below).
There is a small set of events causing state machine transitions:
- entering an outermost ramp;
- leaving an outermost ramp;
- condemning any segment of a ramp generation (detected in AMCWhiten);
- reclaiming any AMC segment.
Here's pseudo-code for all the transition events:
Entering an outermost ramp:
if not FINISH, go to BEGIN.
Leaving an outermost ramp:
if RAMPING, go to FINISH. Otherwise, go to OUTSIDE.
Condemning a ramp generation segment:
If BEGIN, go to RAMPING and make the ramp generation forward
to itself (detach the forwarding buffer and reset its generation).
If FINISH, go to COLLECTING and make the ramp generation
forward to the after-ramp generation.
Reclaiming any AMC segment:
If COLLECTING:
if ``rampCount > 0``, go to BEGIN. Otherwise go to OUTSIDE.
Now, some deductions:
#. When OUTSIDE, the count is always zero, because (a) it starts that
way, and the only ways to go OUTSIDE are (b) by leaving an
outermost ramp (count goes to zero) or (c) by reclaiming when the
count is zero.
#. When BEGIN, the count is never zero (consider the transitions to
BEGIN and the transition to zero).
#. When RAMPING, the count is never zero (again consider transitions
to RAMPING and the transition to zero).
#. When FINISH, the count can be anything (the transition to FINISH
has zero count, but the Enter transition when FINISH can change
that and then it can increment to any value).
#. When COLLECTING, the count can be anything (from the previous fact,
and the transition to COLLECTING).
#. *This is a bug!!* The ramp generation is not always reset (to
forward to the after-ramp generation). If we get into FINISH and
then see another ramp before the next condemnation of the ramp
generation, we will Enter followed by Leave. The Enter will keep us
in FINISH, and the Leave will take us back to OUTSIDE, skipping the
transition to the COLLECTING state which is what resets the ramp
generation forwarding buffer. [TODO: check whether I made an issue
and/or fixed it; NB 2013-06-04]
The simplest change to fix this is to change the behaviour of the Leave
transition, which should only take us OUTSIDE if we are in BEGIN or
COLLECTING. We should also update design/poolamc to tell the truth, and
check the invariants, which will be these:
OUTSIDE => zero
BEGIN => non-zero
RAMPING => non-zero
A cleverer change might radically rearrange the state machine
(e.g. reduce the number of states to three) but that would require
closer design thought and should probably be postponed until we have a
clearer overall strategy plan.
While I'm writing pseudo-code versions of ramp-related code, I should
mention this other snippet, which is the only other code relating to
ramping (these notes are useful when thinking about the broader strategy
code):
In :c:func:`AMCBufferFill()`, if we're RAMPING, and filling the forwarding
buffer of the ramp generation, and the ramp generation is the
forwarding buffer's generation, set ``amcSeg->new`` to FALSE. Otherwise,
add the segment size to ``poolGen.newSize``.
And since I've now mentioned the ``amcSeg->new`` flag, here are the only
other uses of that:
- it initializes as TRUE.
- When leaving an outermost ramp, go through all the segments in the
pool. Any non-white segment in the rampGen with new set to FALSE has
its size added to ``poolGen->newSize`` and gets new set to TRUE.
- in :c:func:`AMCWhiten()`, if new is TRUE, the segment size is deducted
from ``poolGen.newSize`` and new is set to FALSE.
Starting a Trace
................
TODO: Why do we start a trace? How do we choose what to condemn?
Trace Progress
..............
TODO: When do we do some tracing work? How much tracing work do we do?