remove empty dir
[ghc-hetmet.git] / docs / storage-mgt / sm.tex
1 \documentclass{article}
2 \usepackage{code,a4wide}
3
4 \usepackage{graphics,epsfig,epic,eepic}
5
6 \setlength{\parskip}{0.25cm}
7 \setlength{\parsep}{0.25cm}
8 \setlength{\topsep}{0cm}
9 \setlength{\parindent}{0cm}
10 \renewcommand{\textfraction}{0.2}
11 \renewcommand{\floatpagefraction}{0.7}
12
13
14 % Terminology
15 \newcommand{\block}{block}
16 \newcommand{\Block}{Block}
17 \newcommand{\segment}{segment}
18 \newcommand{\Segment}{Segment}
19 \newcommand{\step}{step}
20 \newcommand{\Step}{Step}
21
22 \newcommand{\note}[1]{{\em $\spadesuit$ #1}}
23
24 \begin{document}
25 \title{The GHC Storage Manager}
26 \author{Simon Peyton-Jones and Sungwoo Park}
27
28 \makeatactive
29 \maketitle
30 \section{Introduction}
31
32 This document describes the details of the GHC storage manager, including
33 the interface and implementation of each of its components.
34
35 \section{Goals}
36
37 Storage management goals are:
38 \begin{itemize}
39 \item Generational collection, supporting multiple generations.
40 \item The ability to pin the allocation
41 area into a few pages that we hope will fit entirely in the cache.
42 \item Allows objects to age within a generation before getting promoted.
43 \item Heap can grow as needed, rather than having to be pre-sized
44   by the programmer.
45 \item We support mark/sweep/compact collection for older generations.
46 This is a Good Thing when the live memory approaches the available
47 physical memory, because it reduces paging.
48 \item Little OS support needed.  No @mmap()@ etc. All that we require is
49   the ability to call @malloc()@ to allocate a new chunk of memory.
50   There can be intervening ``sandbars'' allocated by other programs
51   (e.g. DLLs or other @malloc()@'d structures) between chunks of heap.
52 \end{itemize}
53
54 Language-support goals are:
55 \begin{itemize}
56 \item The garbage collector ``shorts out'' indirection objects introduced
57 by the mutator (notably when overwriting a thunk with an indirection).
58 \item The garbage collector executes selector thunks.
59 For example, a thunk for
60 @(fst x)@ where @x@ is a pointer to a pair @(a,b)@ would be
61 evaluated by the garbage collector to just @a@.  This is an important
62 strategy for plugging space leaks.
63 \item The garbage collector traversese the code tree, as well as
64 the heap data structures, to find which CAFs are live. This is a royal pain.
65 \item The garbage collector finalises some objects (typically a tiny minority).
66 At the moment ``finalisation'' means ``call a C routine when this thing
67 dies'' but it would be more general to schedule a call to a Haskell
68 procedure.
69 \end{itemize}
70
71 Instrumentation goals are:
72 \begin{itemize}
73 \item The garbage collector can gather heap-census information for profiling.
74 To this end we can force GC to happen more often than it otherwise would,
75 and the collector can gather information about the type and cost-centre
76 associated with each heap object.
77 \end{itemize}
78
79 \section{The architecture of the storage manager}
80
81 The storage manager is a component of the GHC system which is responsible
82 for allocating fresh memory for new objects and reclaiming memory 
83 that is no longer used.
84 It is built on a layered architecture and consists of four main parts:
85 \emph{megablock allocator}, \emph{block allocator}, \emph{heap allocator}, 
86 and \emph{garbage collector} (Figure~\ref{fig-architecture}). 
87 The megablock allocator communicates directly with the underlying 
88 operating system and forms the lowest level of the storage manager.
89 The heap allocator and garbage collector lie in the topmost level of
90 the storage manager and process requests from 
91 the mutator (the Haskell realm at the runtime) and the runtime system.
92 The block allocator lies between the two levels. 
93
94 \begin{figure}[ht]
95 \begin{center}
96 \input{architecture.eepic}
97 \caption{The overall architecture of the storage manager}
98 \label{fig-architecture}
99 \end{center}
100 \end{figure}
101
102 \section{The megablock allocator}
103
104 % need more elaboration - Sung
105 The megablock allocator implements a direct interface to the underlying 
106 operating system. 
107 It can request a chunk of physical memory of a fixed size,
108 which is called a \emph{megablock}, from the operating system and returns it
109 to the block allocator. A new megablock is not initialized by the
110 megablock allocator; it is later initialized by the block allocator.
111
112 \subsection{Interface}
113
114 \begin{description}
115 \item[@void *getMBlock()@] allocates a single megablock and returns its 
116 starting address. 
117 \item[@void *getMBlocks(nat n)@] allocates @n@ contiguous megablocks 
118 and returns their starting address. 
119 \end{description}
120
121 \subsection{Implementation}
122
123 Since the megablock allocator communicates directly with the underlying
124 operating system, its implementation relies on memory allocation functions
125 provided by the operating system; thus, the implementation varies between
126 platforms. 
127 However, every megablock is always of a fixed size $2^M$ and aligned on a 
128 $2^M$ boundary, regardless of the platform 
129 (@MBLOCK_SIZE@ in @include/Constants.h@ defines the size of megablocks).
130 @mblocks_allocated@ in @MBlock.c@ stores the number of megablocks allocated.
131
132 For implementation details, see @MBlock.c@, @MBlock.h@, @include/Block.h@. 
133
134 \section{The block allocator}
135
136 The block allocator divides a megablock returned by the megablock allocator
137 into a contiguous group of \emph{block descriptors} followed by another 
138 contiguous group of \emph{blocks}. 
139
140 A block is a contiguous chunk of $2^K$ bytes, starting on 
141 a $2^K$-byte boundary (@BLOCK_SIZE@ in 
142 @include/Constants.h@ defines the size of blocks). 
143 Each block has its own associated block descriptor, which records the
144 current state of the block. 
145
146 Figure~\ref{fig-megablock} shows a megablock after initialization by the 
147 megablock allocator. 
148 Block descriptors occupy the lower address space and blocks the higher address 
149 space in the megablock. 
150 A block is the unit of allocation for the block allocator. 
151 That is, the block allocator hands over store to the heap allocator in multiples of 
152 one block, where multiple heap objects may be allocated.
153 A contiguous group of blocks, which is called a \emph{block group}, can be 
154 directly handed over to the heap allocator to reduce inter-block 
155 linkage costs.
156 The first block of a block group is called the \emph{group head}.\footnote{
157 An alternative design has the block descriptor at the start of each block.
158 This makes it easy to locate the block descriptor corresponding to a particular
159 block, but is pessimistic for cache locality when fiddling with block descriptors.
160 It also means that only the first block in a contiguous chunk of blocks can
161 have a block descriptor. This in turn makes it difficult to achieve an
162 efficient mostly-copying conservative (MCC) garbage collector.}
163 Since block descriptors are ordered linearly, we can always locate a block 
164 descriptor corresponding to a particular block from the starting address 
165 of the block.
166
167 \begin{figure}[ht]
168 \begin{center}
169 \input{megablock.eepic}
170 \caption{A megablock after initialization}
171 \label{fig-megablock}
172 \end{center}
173 \end{figure}
174
175 \subsection{Interface}
176
177 \begin{description}
178 \item[@typedef struct bdescr@] is the type of block descriptors.
179 \item[@void initBlockAllocator(void)@] initializes the block allocator. 
180 \item[@bdescr *allocBlock(void)@] requests a single block and returns 
181 the address of its block descriptor. 
182 \item[@bdescr *allocGroup(nat n)@] allocates a block group of size @n@ 
183 and returns the address of the block descriptor for the group head.
184 \item[@void freeGroup(bdescr *p)@] frees the block group where @p@ points
185 to the block descriptor of the group head, and places it in a pool of
186 free block groups. 
187 \item[@bdescr *Bdescr(StgPtr p)@] takes a pointer @p@ to any byte within
188 a block and returns a pointer to its block descriptor. It is implemented as
189 an @inline@ procedure.
190 \end{description}
191
192 \subsection{Block descriptors}
193
194 A block descriptor has the following structure, defined in 
195 @include/Blocks.h@:
196
197 \begin{code}
198 typedef struct _bdescr {
199   StgPtr          start;
200   StgPtr          free; 
201   StgWord32       blocks;
202   struct _bdescr  *link;
203   /* additional fields */
204 } bdescr;
205 \end{code}
206
207 The fields of a block descriptor have the following purposes:
208
209 \begin{description}
210 \item[@start@] points to the first byte of the corresponding block.
211 \item[@free@] For a group head, @free@ points to the first free byte in 
212 the block group. For a non-group head, @free@ is set to zero to identify
213 the corresponding block as a non-group head.
214 \item[@blocks@] For a group head, @blocks@ stores the number of blocks
215 in the block group. It is not used for non-group heads.
216 \item[@link@] For a group head, @link@ is used to chain all individual 
217 blocks or block groups together. For a non-group head, @link@ points
218 to the block descriptor of the group head.
219 \end{description}
220
221 \subsection{Implementation}
222
223 The block allocator maintains a linked list of free block groups, whose head
224 is stored in @free_list@ in @BlockAlloc.c@ (Figure~\ref{fig-freelist}).
225 When @allocBlock()@ or @allocGroup()@ is called, the block allocator
226 scans the linked list from @free_list@ and finds the first block group
227 which can handle the request.
228 If such a block group exists, it takes off the requested number of blocks
229 from the block group, creates a new block group from them, 
230 initializes it if needed, and returns it to the caller. 
231 The rest of the old block group, if any, is linked back to the list of free block 
232 groups as another block group. 
233 If such a block group does not exist, the block allocator requests a megablock
234 from the megablock allocator and processes the request using the new megablock.
235
236 For implementation details, see @BlockAlloc.c@ and @include/Block.h@.
237
238 \begin{figure}[ht]
239 \begin{center}
240 \input{freelist.eepic}
241 \caption{Linked list of free block groups}
242 \label{fig-freelist}
243 \end{center}
244 \end{figure}
245
246 \section{Heap allocator}
247
248 The role of the heap allocator in the storage manager is to allocate fresh
249 memory upon requests from the mutator and the runtime system.
250 Memory allocation takes place frequently during the execution of Haskell 
251 programs, and hence its efficiency is crucial to the overall performance.
252 To handle requests from the mutator and the runtime system efficiently,
253 the heap allocator maintains three different memory stores,
254 each of which has its own purpose.
255
256 The first store is the \emph{nursery}, where typical Haskell 
257 objects are born.
258 The mutator itself can allocate fresh memory directly in the nursery 
259 without invoking an interface function:
260 the configuration of the nursery is always revealed to the mutator and can even
261 be changed by the mutator when it allocates fresh memory from the nursery
262 on its own.
263 Thus, although the small overhead in manipulating the nursery results in fast
264 memory allocation, it is up to the mutator to keep the nursery in an 
265 uncorrupted state.
266
267 The second and the third are the \emph{small object pool} and the
268 \emph{large object pool}.
269 The heap allocator provides a common interface function to be shared by both stores:
270 the size of fresh memory requested, which is passed as an argument to the 
271 interface function, determines which of the two stores to be used.
272 The interface function can be called by both the mutator and the runtime system.
273
274 \subsection{Interface}
275
276 \begin{description}
277 \item[@void initStorage(void)@] initializes the storage manager. @Storage.c@.
278 \item[@void allocNurseries(void)@] creates and initializes the nursery. 
279 @Storage.c@.
280 \item[@void resetNurseries(void)@] re-initializes the nursery. @Storage.c@.
281 \item[@OpenNursery(hp, hplim)@] opens an allocation area in the nursery and sets 
282 @hp@ and @hplim@ appropriately. 
283 Then the caller can freely use the memory from @hp@ to @hpLim@. 
284 A macro in @include/StgStorage.h@.
285 \item[@CloseNursery(hp)@] closes the current allocation area beginning at @hp@
286 and returns it to the storage manager.
287 A macro in @include/StgStorage.h@.
288 \item[@ExtendNursery(hp, hplim)@] closes the current allocation area and 
289 tries to find a new allocation area in the nursery. 
290 If it succeeds, it sets @hp@ and @hplim@ appropriately and returns @rtsTrue@; 
291 otherwise, it returns @rtsFalse@,
292 which means that the nursery has been exhausted. 
293 The new allocation area is not necessarily contiguous with the old one.
294 A macro in @Storage.h@.
295 \item[@StgPtr allocate(nat n)@] allocates @n@ words from either the small
296 object pool or the large object pool, depending on the argument @n@, 
297 and returns a pointer to the first byte. It \emph{always} succeeds.
298 @Storage.c@.
299 \end{description}
300
301 \subsection{Implementation}
302
303 The nursery is implemented with a fixed number of blocks (@nursery_blocks@
304 in @Storage.c@ specifies the number of blocks). 
305 Each of these blocks forms its own block group, and they are all linked together
306 by @allocNurseries()@. 
307 The blocks in the nursery are carefully allocated in a contiguous address
308 range so that they fit next to each other in the cache.
309 They are never freed. 
310
311 A single block called the \emph{active block} provides the allocation area for
312 the mutator at any moment.
313 When the free space left in the active block is not enough for the request from 
314 the mutator, the heap allocator sets the @free@ field in the corresponding
315 block descriptor to the first free byte in the block and moves the allocation
316 area to the next block. 
317
318 Figure~\ref{fig-nursery} shows the configuration of the nursery during
319 the mutator time.
320 The head of the linked list is stored in @MainRegTable.rNursery@, and
321 the address of the block descriptor of the active block is stored 
322 in @MainRegTable.rCurrentNursery@.
323 @Hp@, defined as @MainRegTable.rHp@, points to the byte before the first byte of 
324 the current allocation area in the active block.
325 @HpLim@, defines as @MainRegTable.rHpLim@, marks the boundary of the current 
326 allocation area:
327 it points to the last byte in the current allocation area, and thus
328 all the bytes of memory addresses from @Hp@$ + 1$ to @HpLim@ are free.
329 The mutator can obtain fresh memory simply by adjusting @Hp@ as long as the new
330 value of @Hp@ does not exceed @HpLim@. For instance, if the mutator 
331 increases @Hp@ by @n@, it can now store an object of size up to @n@ at the 
332 address pointed to by the old value of @Hp@$ + 1$.
333
334 When the runtime system runs, none of the above four pointers 
335 (@MainRegTable.rNursery@, @MainRegTable.rCurrentNursery@, @Hp@ and @HpLim@) are 
336 valid; they are simply aliases to registers.
337 Instead @g0s0->blocks@\footnote{@g0s0->blocks@ is valid all the time, even during
338 the mutator time.  The meaning of @g0s0@ is explained in the next section.} 
339 can be used to retrieve the head of the linked list, and
340 the @free@ field in each block descriptor points to the first free byte
341 in its corresponding block.\footnote{To be precise, this is \emph{not} the
342 case: a @free@ field may point to a byte past its actual boundary.
343 This happens because
344 the mutator first increases @hpLim@ without comparing it with the
345 actual boundary when allocating fresh memory,
346 and later assigns @hpLim@ to the @free@ of the corresponding block.}
347 @Hp@ and @HpLim@ are not saved because they can be inferred from @free@ fields
348 of the blocks descriptors in the nursery.
349
350 \begin{figure}[ht]
351 \begin{center}
352 \input{nursery.eepic}
353 \caption{Nursery during the mutator time}
354 \label{fig-nursery}
355 \end{center}
356 \end{figure}
357
358 The small object pool is implemented with a linked list of block groups, 
359 each of which consists of a single block (Figure~\ref{fig-smallobjectpool}).
360 The head of the linked list is stored in @small_alloc_list@ in @Storage.c@.
361
362 \begin{figure}[ht]
363 \begin{center}
364 \input{smallobjectpool.eepic}
365 \caption{Small object pool}
366 \label{fig-smallobjectpool}
367 \end{center}
368 \end{figure}
369
370 The allocation in the small object pool is done in the same way as in the
371 nursery; @alloc_Hp@ and @alloc_HpLim@ (both defined in @Storage.c@) 
372 point to the first free byte and the boundary of the small object pool, 
373 respectively.
374 Thus, when @allocate()@ is called and the heap allocator decides to 
375 allocate fresh memory in the small object pool, it simply increases @alloc_Hp@
376 by the size of memory requested. 
377 If the allocation cannot be done in the current small object pool, the 
378 heap allocator calls @allocBlock()@ to obtain a new block from the block
379 allocator, puts it to the head of the linked list, and 
380 sets @alloc_Hp@ and @alloc_HpLim@ appropriately.
381
382 The large object pool is also implemented with a (doubly) linked list of block
383 groups (Figure~\ref{fig-largeobjectpool}). 
384 The difference from the small object pool is that each block group stores only 
385 a single object: each time the argument to @allocate()@ is
386 greater than a threshold value (computed from @LARGE_OBJECT_THRESHOLD@ 
387 in @include/Constants.h@), a new block group accommodating the requested size 
388 is created to store a single object. 
389 The new block group is put to the head of the list. 
390 The head of the linked list is available as @g0s0->large_objects@.
391
392 \begin{figure}[ht]
393 \begin{center}
394 \input{largeobjectpool.eepic}
395 \caption{Large object pool}
396 \label{fig-largeobjectpool}
397 \end{center}
398 \end{figure}
399
400 For implementation details, see @Storage.c@ and @include/StgStorage.h@.
401
402 \section{Garbage collector}
403
404 The garbage collector finds all the objects unreachable from a given set of
405 roots and frees the memory allocated to them. By invoking the
406 garbage collector regularly, the storage manager prevents the heap from
407 growing indefinitely and allows Haskell programs to be executed at a 
408 reasonable memory cost.
409
410 The garbage collector in the storage manager is based upon the generational 
411 garbage collection algorithm.
412 The storage manager records the age for every object in the heap.
413 An object surviving one garbage collection grows old by one \emph{step},
414 and an object surviving a certain number of garbage collections 
415 is promoted to the next \emph{generation}.
416 That is, a step can be defined as a collection of objects which have survived
417 the same number of garbage collections (or a collection of objects which are
418 born at some point between two particular successive garbage collections),
419 and a generation as a group of steps belonging to a certain range of ages.
420 Notice that the unit of garbage collections is not step but generation: 
421 a garbage collection applies to all the steps in a generation, and we cannot 
422 perform a garbage collection just on part of a generation.
423 Furthermore, if a particular generation is garbage collected, so are 
424 all the younger generations.\footnote{Some 
425 authors define a generation as the set of 
426 all the objects created between two particular garbage collection and
427 an object cannot change its generation (e.g., 1960's, 1970's, and so on).
428 In this document, 
429 an object can change its generation as it survives garbage collections
430 (e.g., teenagers, 20's, and so on).}
431
432 Figure~\ref{fig-generation} illustrates how an object grows old.
433 Every object is created in step $0$ of generation $0$. 
434 As it survives garbage collections, it is moved to the next step of the
435 same generation until it is finally promoted to 
436 step $0$ of the next generation:
437 during a garbage collection of generation $g < G$, live objects from 
438 step $s < S_g$ are moved to step $s + 1$, and live objects from
439 the last step $S_g$ are promoted to step $0$ in generation $g + 1$.
440 Live objects in step $0$ of generation $G$ stay in the same step;
441 the oldest generation maintains only one step because there is no point
442 in aging objects in the oldest generation.
443 In this way, objects are given a decent chance of dying before being
444 promoted to the next generation.
445
446 \begin{figure}[ht]
447 \begin{center}
448 \input{generation.eepic}
449 \caption{Evolution of objects through garbage collections}
450 \label{fig-generation}
451 \end{center}
452 \end{figure}
453
454 The main reason that we separate steps from generations is to
455 reduce the cost of maintaining \emph{backward inter-generational pointers},
456 that is, pointers from older generations to younger generations.
457 Suppose that a garbage collection applies to all generations $0$
458 through $g$. If an object @O@ in one of these generations is pointed to
459 by another object in generation $g' > g$, we cannot free the object @O@
460 even though generation $g'$ is out of consideration. Consequently
461 we have to track backward inter-generational pointers to perform garbage
462 collections correctly.
463 Since maintaining backward pointers is costly, we
464 choose to track backward inter-generational pointers only;
465 we do not track backward inter-step pointers.
466
467 By grouping all the objects created between two garbage collections
468 and grouping multiple age groups into one generation, the garbage
469 collector makes an efficient use of heap memory.
470
471 \subsection{Interface}
472
473 \begin{description}
474 %\item[@StgClosure *MarkRoot(StgClosure *root)@] informs the garbage collector
475 %that @root@ is an object in the root set. It returns the new location of 
476 %the object. @GC.c@.
477 \item[@void *mark\_root(StgClosure **root)@] informs the garbage collector
478 that @*root@ is an object in the root set. It replaces @*root@ by 
479 the new location of the object. @GC.c@.
480 \item[@void GarbageCollect(void (*get\_roots)(evac\_fn), rtsBool force\_major\_gc)@]
481 performs a garbage collection. 
482 @get_roots()@ is a function which is called by the garbage collector when
483 it wishes to find all the objects in the root set (other than those
484 it can find itself).
485 Therefore it is incumbent on the caller to find the root set.
486 @force_major_gc@ specifies whether a major garbage collection is required
487 or not. If a major garbage collection is not required, the garbage collector
488 decides an oldest generation $g$ to garbage collect on its own.
489 @GC.c@.
490 \item[@rtsBool doYouWantToGC(void)@] returns @rtsTrue@ if the garbage
491 collector is ready to perform a garbage collection. Specifically, it returns
492 @rtsTrue@ if the number of allocated blocks since the last garbage collection
493 (@alloc_blocks@ in @Storage.c@) exceeds an approximate limit 
494 (@alloc_blocks_lim@ in @Storage.c@).
495 @Storage.h@.
496 \item[@void recordMutable(StgMutClosure *p)@] informs the garbage collector
497 that a previously immutable object @p@ has become mutable.
498 The garbage collector then puts the object @p@ in the list @mut_list@ of the 
499 generation to which it belongs.\footnote{It is easy to 
500 locate the generation to which a dynamic object belongs from its address: 
501 we can identify the block in which the object resides from its address,
502 and the corresponding block descriptor stores pointers 
503 to the step and the generation (@gen@ and @step@ fields in the @bdescr@ 
504 structure) to which it belongs.}
505 It suffices to call @RecordMutable()@ only once for any object. 
506
507 For an object which is genuinely mutable (e.g., mutable arrays), 
508 it is permanently recorded as mutable. 
509 On the other hand, 
510 an object which is temporarily mutable (e.g., frozen arrays),
511 can be dropped from the list @mut_list@ once its pointer has been dealt with
512 during garbage collections. @Storage.h@.
513 \item[@void recordOldToNewPtrs(StgMutClosure *p)@] puts the object @p@ in the
514 list @mut_once_list@ of the generation to which it belongs.
515 \item[@void newCAF(StgClosure *caf)@] puts the CAF @caf@ either 
516 in the list @caf_list@ or
517 in the list @mut_once_list@ of the oldest generation,
518 depending on whether it is dynamically loaded or not.
519 \end{description}
520
521 \subsection{Steps}
522
523 A step has the following structure, defined in 
524 @include/StgStorage.h@:
525
526 \begin{code}
527 typedef struct _step {
528   unsigned int no;
529   bdescr *blocks;
530   unsigned int n_blocks;
531   bdescr *large_objects;
532   /* additional fields */
533 } step;
534 \end{code}
535
536 The fields of a step have the following purposes (Figure~\ref{fig-step}):
537
538 \begin{description}
539 \item[@no@] indicates the age within its generation. 
540 $0$ indicates the youngest step in a generation.
541 \item[@blocks@] is a linked list of all the blocks in this step 
542 which contain small objects.
543 Each block forms its own block group.
544 \item[@n\_blocks@] is the number of blocks in the linked list @blocks@.
545 \item[@large\_objects@] is a (doubly) linked list of all the block groups 
546 in this step which contain large objects. 
547 Each block group stores only a single object.
548 \end{description}
549
550 \begin{figure}[ht]
551 \begin{center}
552 \input{step.eepic}
553 \caption{Memory layout of a step}
554 \label{fig-step}
555 \end{center}
556 \end{figure}
557
558 The linked list @blocks@ of step $s$ in generation $g$ is created 
559 during a garbage collection
560 from live small objects of step $s - 1$ in the same generation 
561 (or the last step in the previous generation if $s = 0$).
562 The @free@ field in every block descriptor never changes because
563 no objects are added after the garbage collection; new objects are created 
564 only in step $0$ in generation $0$.
565 Likewise, the linked list @large_objects@ is created during a
566 garbage collection from live large objects of the previous step. 
567
568 There are three exceptions to the above rules. 
569 First, both @blocks@ and @large_objects@ of
570 step $0$ in generation $0$ are not filled with new objects during a garbage 
571 collection. 
572 They are simply re-initialized by the garbage collector and 
573 grow during during the execution of a program as new objects are
574 created.
575 Step $0$ in generation $0$ is accessible via a global variable @g0s0@, 
576 and this is the reason why the large object pool (described in the previous 
577 section) is indeed stored in @g0s0->large_objects@. 
578 For the same reason, @MainRegTable.rNursery@ holds the same address as 
579 @g0s0->blocks@ during the mutator time.
580 Second, @blocks@ of step $1$ in generation $0$ is created not only from
581 the nursery (@blocks@ of step $0$ in the same generation) but also from the 
582 small object pool. In other words, all the live small objects created since
583 the previous garbage collection, either directly by the mutator or indirectly
584 through @allocate()@, are gathered together in the same linked list.
585 Finally, step $0$ of the oldest generation serves the source for itself during
586 any garbage collection, i.e., $S_G = 1$, because there exists no older step.
587
588 \subsection{Generations}
589
590 A generation has the following structure, defined in 
591 @include/StgStorage.h@:
592
593 \begin{code}
594 typedef struct _generation {
595   unsigned int no;
596   step *steps;
597   unsigned int n_steps;
598   unsigned int max_blocks;
599   StgMutClosure *mut_list;
600   StgMutClosure *mut_once_list;
601   /* additional fields */
602 } generation;
603 \end{code}
604
605 The fields of a generation have the following purposes (Figure~\ref{fig-gen}):
606
607 \begin{description}
608 \item[@no@] is the generation number.
609 \item[@steps@] points to an array of @step@ structures. @steps[@$i$@]@ 
610 corresponds to step $i$ in this generation, i.e., 
611 @steps[@$i$@].no@ is equal to $i$.
612 \item[@n\_steps@] is the number of @step@ structures in the array pointed to 
613 by @steps@.
614 \item[@max\_blocks@] is the maximum number of blocks allowed in step $0$ of
615 this generation. If the number of blocks allocated 
616 in step @0@ exceeds @max_blocks@,
617 this generation is garbage collected during the next garbage collection.
618 \item[@mut\_list@] links all mutable objects in this generation, that is,
619 objects whose contents can be updated and hence may contain pointers to
620 younger generations. 
621 Every object in this linked list is a dynamic object residing in the heap 
622 and has a structure compatible with @StgMutClosure@.
623 The structure @StgMutClosure@ (@includes/Closures.h@) has a field 
624 @mut_link@ (called a mutable link field) of type @StgMutClosure *@, which
625 points to the next object in this linked list.
626 The end mark of this linked list is a pointer to a statically allocated object 
627 @END_MUT_LIST@ (@StoragePriv.h@).
628 \item[@mut\_once\_list@] links objects in this generation whose contents 
629 cannot be updated any more but may already have pointers to younger generations.
630 As with @mut_list@, it links only those objects whose structure is compatible
631 with @StgMutClosure@ and ends with @END_MUT_LIST@.
632 \end{description}
633
634 \begin{figure}[ht]
635 \begin{center}
636 \input{gen.eepic}
637 \caption{Memory layout of a generation}
638 \label{fig-gen}
639 \end{center}
640 \end{figure}
641
642 The garbage collector maintains an array @generations@ of @generation@ structure
643 (defined in @Storage.c@), whose size is stored in a runtime system flag 
644 (@RtsFlags.GcFlags.generations@). 
645 The generation number of each generation coincides with its index into
646 the array @generations@, i.e.,  @generations[@$i$@].no@ is equal to $i$.
647
648 As mentioned before, lists of objects which may have pointers to younger
649 generations are kept per generation, not per step. The youngest generation,
650 accessible via a global variable @g0@, does not keep such a list because it
651 does not have younger generations.
652
653 The oldest generation, accessible via a global variable @oldest_gen@, may
654 contain static objects (as opposed to dynamic objects residing in the heap)
655 in its list @mut_once_list@. This happens when a static
656 thunk, also known as a \emph{constant applicative form} (CAF), is entered.
657 When a CAF (corresponding to closure type @THUNK_STATIC@, defined
658 in @includes/ClosureTypes.h@) is entered, 
659 it is first put in the list @mut_once_list@ of the oldest generation
660 and then overwritten with an appropriate static indirection object 
661 (corresponding to closure type @IND_STATIC@).\footnote{Actually a static 
662 indirection object does not have a @mut\_link@ field.
663 We use its @static\_link@ field as a substitute for @mut\_link@.
664 See the structure @StgIndStatic@ in @include/Closures.h@.}\footnote{For
665 details of this operation, see the macro @UPD\_CAF()@ in @includes/Updates.h@}
666 If the CAF is dynamically loaded (e.g., in an interactive environment), it is 
667 instead put in a separate linked list @caf_list@ 
668 (declared in @Storage.c@). 
669
670 The evaluation result of the 
671 CAF is stored in a separate dynamic object in the heap and the static 
672 indirection object has a pointer to the dynamic object.
673 Thus, the new static indirection object is put in the list 
674 @mut_once_list@ of the oldest generation (or the list @caf_list@) so that the 
675 dynamic object is not removed during the next garbage collection.
676 Once it is created, the static indirection object remains unaltered, which
677 is the reason why it is put in the @mut_once_list@ list, not in the 
678 @mut_list@ list.
679 Since the static indirection object survives any garbage collection (because
680 it comes from a static object) and would be eventually moved to the oldest 
681 generation,
682 we put it in the @mut_once_list@ of the oldest generation as soon
683 as it is created.
684
685 \subsection{Implementation}
686
687 The overall structure of a garbage collection is as follows:
688
689 \begin{enumerate}
690 \item[(1)] Initialize.
691 \item[(2)] Scavenge lists @mut_once_list@ and @mut_list@ if necessary.
692 \item[(3)] Scavenge CAFs.
693 \item[(4)] Evacuate roots.
694 \item[(5)] Scavenge objects.
695 \item[(6)] Tidy up.
696 \end{enumerate}
697
698 \subsubsection{(1) Initialization}
699
700 During initialization, the garbage collector first decides which generation
701 to garbage collect.
702 Specifically, 
703 if the argument @force_major_gc@ to @GarbageCollect()@ is @rtsFalse@,
704 it decides the greatest generation number $N$ such
705 that the number of blocks allocated in step $0$ of generation $N$ exceeds
706 @generations[@$N$@].max_blocks@. 
707 If the argument @force_major_gc@ to @GarbageCollect()@ is @rtsTrue@,
708 $N$ is set to the greatest generation number, namely, 
709 $@RtsFlags.GcFlags.generations@ - 1$.
710 The garbage collector considers up to generation $N$ for garbage collection.
711 A major garbage collection takes place if $N$ is set to 
712 $@RtsFlags.GcFlags.generations@ - 1$ during this process.
713
714 Then, the garbage collector initialize the \emph{to-space} (as opposed to
715 \emph{from-space}) for each step of 
716 each generation, which is complete with an \emph{allocation pointer} and
717 an \emph{sweep pointer}.
718 The to-space of a step is the memory to which any object belonging to the
719 step can be copied when it survives a garbage collection.
720 For instance, a live object in step $s$ of generation $g$ can first be copied
721 to the to-space associated with step $s$, which eventually becomes 
722 associated with the next step $s + 1$ (or step $0$ of the next generation)
723 during tidying up.
724 This operation effectively moves an object to the next step if it survives
725 a garbage collection. 
726 The allocation pointer points to the next free in the to-space while 
727 the sweep pointer points to the next object considered for scavenging.
728
729 During major garbage collections,
730 the static link field of every static object indicates whether it has
731 been visited by the garbage collector or not.
732 Therefore, the static link field of every static object must have
733 a null value before a major garbage collection starts. 
734 The list @mut_once_list@ of the oldest generation may contain static 
735 indirection objects, and thus 
736 the garbage collector invokes @zero_mutable_list()@ on the list,
737 Although this breaks up the list, it does not cause any problem because 
738 the list is not employed during major garbage collections.
739
740 \subsubsection{\tt evacuate()}
741
742 The function @evacuate()@ (defined in @GC.c@), which 
743 is called eventually for every live object 
744 (including even static objects reachable from roots),
745 moves an object to
746 a safe place so as not to be garbage collected.
747 Before invoking the function @evacuate()@ on an object @o@, the caller specifies
748 a \emph{desired generation} for @o@ in a variable @evac_gen@
749 (declared in @GC.c@).
750 The desired generation is the youngest generation to which the caller wishes 
751 @o@ to be evacuated; the garbage collector should evacuate @o@ to a 
752 generation no younger than the desired generation.
753
754 Depending on @evac_gen@ and the generation $M$ where @o@ currently resides,
755 @evacuate()@ behaves itself as follows:
756 \begin{itemize}
757 \item If @evac_gen@ $\leq M$ and $N < M$, it does nothing because @o@ is already
758       in a generation no younger than @evac_gen@.
759 \item If @evac_gen@ $\leq M \leq N$, it evacuates @o@ to the to-space of the 
760 step to which @o@ currently belongs. @o@ will be moved to the next step later.
761 @recordMutable()@ may be invoked on @o@ depending on its type (e.g., @MVAR@).
762 \item If $M <$ @evac_gen@, @o@ is evacuated to the to-space of step $0$
763       of generation @even_gen@, which accomplishes the request.
764       This happens even when $N \leq$ @evac_gen@. Therefore, those generations
765       which are not considered for garbage collection may still be augmented
766       with new objects during garbage collection.
767       @recordMutable()@ may be invoked on @o@ depending on its type.
768 \end{itemize}
769 If @o@ has already been evacuated, @evacuate()@ either does nothing (when
770 @even_gen@ $\leq M$) or reports
771 a failure to evacuate @o@ by setting the flag @failed_to_evac@ (declared
772 in @GC.c@). 
773
774 Evacuating a large object is handled by @evacuate_large()@.  
775 Since it is costly to allocate new memory blocks and copy all the contents
776 of the object, the garbage collector simply removes the object form
777 the list @large_alloc_list@ of its step and links it to another list,
778 from which it will be scavenged later.
779
780 \subsubsection{Set of roots for garbage collection}
781 Part of the set of roots for garbage collection is obtained indirectly by 
782 invoking the function
783 @get_roots()@, an argument to @GarbageCollect()@: the garbage collector
784 invokes @get_roots()@ with @mark_root()@ as an argument, and @get_roots()@
785 in turn invokes @mark_root()@ on each of known roots.
786 The rest of the set of roots is obtained from the lists @mut_list@ and
787 @mut_once_list@ of generation $N + 1$ through the oldest generation:
788 any objects in these lists may have pointers to objects in generations
789 $0$ to $N$, and thus must be considered as a root.
790 If a major garbage collection takes place, no @mut_list@ and @mut_once_list@
791 lists are consider for scavenging and step (2) is skipped.
792 The entire set of roots is now specified by @get_roots()@ alone.
793
794 \subsubsection{(2) Scavenging lists {\tt mut\_once\_list} and {\tt mut\_list}}
795
796 Since the roots obtained from the lists @mut_list@ and @mut_once_list@ are
797 already in generations $N' > N$, we only have to scavenge them.
798 That is, it suffices to invoke @evacuate()@ once on each object 
799 which is currently pointed to by an object in these lists. 
800
801 When scavenging an object @r@ in the list @mut_once_list@ of generation $M$,
802 the desired generation is set to $M$ for each object @o@ pointed
803 to by @r@ before invoking @evacuate()@. 
804 The rationale is that the contents of @r@ cannot be updated any more,
805 and thus @r@ is always survived by @o@; @o@ is live as long as @r@ is.
806 Therefore, we wish @r@ to be evacuated to the same generation $M$ as @r@
807 currently resides (not to its next step).
808 If the evacuation succeeds (indicated by a @rtsFalse@ value of a variable
809 @failed_to_evac@, declared in @GC.c@) for every object @o@, @r@ is removed 
810 from the list @mut_once_list@ because it does not hold any backward 
811 inter-generational pointers.\footnote{It turns out that @r@ can have only
812 one such object @o@. The type of @r@ is one of the following:
813 @IND\_OLDGEN@, @IND\_OLDGEN\_PERM@, @IND\_STATIC@, and @MUT\_VAR@.}
814
815 Scavenging a list @mut_list@ is similar to the case of @mut_once_list@.
816 When scavenging an object @r@ in the list @mut_list@ of generation $M$,
817 the desired generation is set to $M$ for each object pointed to by @r@
818 if @r@ is known to be immutable (e.g., @MUT_ARR_PTRS_FROZEN@, 
819 @IND_OLDGEN@)
820 or to $0$ if @r@ is still mutable (e.g., @MUT_ARR_PTRS@, @MUT_VAR@).
821 The list @mut_once_list@ is also adjusted if it is safe to remove @r@ from
822 @mut_list@. 
823
824 \subsubsection{(3) Scavenging CAFs}
825
826 When a dynamically loaded CAF is entered, it it first put to the list 
827 @caf_list@ and then overwritten with a static indirection object.
828 The evaluation result of the CAF is stored in a dynamic object in the heap
829 and the static indirection object stores a pointer to the dynamic object.
830 Although the static indirection object (or the CAF) itself is never freed, 
831 it may be removed later from the @caf_list@ when it is reverted to the 
832 original CAF, and the dynamic object may not be live afterwards.
833 Hence, we treat the dynamic object just as normal dynamic objects and
834 set the desired generation to $0$.
835
836 \subsubsection{(4) Evacuating roots}
837
838 Evacuating roots (other than those in the lists @mut_once_list@ and 
839 @mut_list@) is simply done by invoking @get_roots()@ with @mark_root()@
840 as an argument. 
841 Since these roots are normal dynamic objects, we set the desired generation
842 to $0$.
843
844 \subsubsection{(5) Scavenging}
845
846 The garbage collector scavenges all the objects in the to-space of
847 each step (by invoking @evacuate()@ on each object reachable from them) 
848 until every sweep pointer has reached its corresponding 
849 allocation pointer. 
850 It repeatedly examines all the to-spaces because not only sweep pointers
851 but also allocation pointers change during scavenging:
852 when an object @r@ is scavenged, each object reachable from 
853 @r@ is evacuated to a certain to-space, which increases the corresponding
854 allocation pointer, and
855 the sweep pointer of the to-space which currently contains @r@
856 increases as well upon finishing scavenging the object @r@.
857 Thus, the garbage collector cannot anticipate in advance how many times 
858 it needs to scan through all the to-spaces; it keeps scavenging until
859 no objects are left to be scavenged.
860
861 \subsubsection{Scavenging static objects}
862
863 Since it is possible for dynamic objects to point to static objects,
864 the garbage collector may invoke @evacuate()@ on static objects 
865 while scavenging dynamic objects in to-spaces.
866 This complicates the garbage collector because 
867 static objects cannot be evacuated in general yet
868 they may have pointers to dynamic objects, which must be evacuated.
869 Thus the garbage collector needs to at least scavenge live static objects
870 (as opposed to those static objects currently not reachable from roots).
871
872 When a minor garbage collection is performed, any invocation of
873 @evacuate()@ on static objects is simply ignored. 
874 Furthermore, no static object is considered for scavenging
875 (except those in the list @mut_once_list@ of the oldest generation during).
876 Still all dynamic objects which are marked as live due to static objects
877 are safely evacuated.
878 The reason is that we can reach all such dynamic objects from 
879 indirection static objects stored in the list 
880 @mut_once_list@ of the oldest generation, which is scavenged during step (2),
881 and the list @caf_list@.
882 In other words, in order to evacuate all such dynamic objects, it is 
883 sufficient to evacuate all dynamic objects reachable from 
884 static indirection objects in 
885 the list @mut_once_list@ of the oldest generation and the list @caf_list@.
886 However, the garbage collector may unnecessarily scavenge certain static 
887 indirection objects which are no longer used.
888 They are not scavenged during a major garbage collection, however.
889
890 During a major garbage collection,
891 if an invocation of @evacuate()@ on a static object @r@ is made,
892 the garbage collector first checks whether @r@ needs to be scavenged or not.
893 If its SRT (Static Reference Table) is empty and it has no other pointers, 
894 no dynamic objects are reachable from @r@ and it is ignored.\footnote{If 
895 no dynamic objects are reachable from a static object @r@ (even indirectly
896 via multiple static objects),
897 @r@ is not stored in \emph{any} SRT table because it would be no use attempting
898 to follow any pointers in @r@.}
899 Otherwise, it is put in the list @static_objects@.
900 At the beginning of each scavenging loop in step (5), 
901 the garbage collector invokes @scavenge_static()@ if the list @static_objects@
902 is not empty.
903 @scavenge_static()@ scavenges the static objects in the list @static_objects@
904 by invoking @evacuate()@ on every object reachable from them.
905 The desired generation is set to the oldest generation (because any
906 dynamic object directly pointed to by a static object lives 
907 forever).
908 These static objects are then put in another list @scavenged_static_objects@
909 and removed from the list @static_objects@.
910 For a static indirection object, if the evacuation 
911 fails, it is put back to the list @mut_once_list@ of the oldest generation;
912 it can be thought of as a CAF just entered.
913
914 After a major garbage collection, therefore, the list @scavenged_static_objects@
915 links all live static objects except for static indirection objects put back
916 to the list @mut_once_list@ of the oldest generation. 
917 Dynamically loaded CAFs are found in the list @caf_list@.
918
919 \subsubsection{(6) Tidying up}
920
921 The garbage collector tidies up the heap by 
922 moving the to-space of each step to the next step. 
923 It also re-initialize the small object pool (which now does not contain
924 any live objects), frees any large objects which have not been scavenged,
925 and invokes @resetNurseries()@.
926 If a major garbage collection has been performed, it 
927 invokes @zero_static_object_list()@ on the list @scavenged_static_objects@ 
928 so that all static objects
929 (other than those in the list @mut_once_list@ of the oldest generation)
930 have a null static link field again.
931
932 At this point, both the small allocation pool and the large object pool are
933 empty. Upon the exit from @GarbageCollect()@, however, they may not
934 be empty any more because the garbage collector invokes @scheduleFinalizer()@
935 before exiting, which tries to run pending finalizers on dead weak pointers and 
936 may create new objects through @allocate()@.
937 The nursery still remains intact.
938
939 The heap may contain extra objects which are not reachable from the roots
940 used during the garbage collection: 1) weak head pointers; 2) dead
941 weak head pointers. Weak head pointers can be tracked from 
942 the list @weak_ptr_list@ (declared in @Weak.c@). However, there is no way
943 of reaching dead weak pointers; they will be garbage collected during the
944 next garbage collection.
945
946 For implementation details, see @GC.c@.
947
948 \section{State of the heap allocator and the garbage collector}
949
950 The state of the heap allocator and the garbage collector is fully specified by the 
951 following variables:
952
953 \begin{description}
954 \item[@small\_alloc\_list@] is the header of the small object pool.
955 \item[@alloc\_Hp@] points to the first free byte in the small object pool.
956 \item[@alloc\_HpLim@] points to the boundary of the small object pool.
957 \item[@generations@] is the array of @generation@ structures.
958 \item[@RtsFlags.GcFlags.generations@] specifies the number of elements in 
959 the array @generations@.
960 \item[@caf\_list@] links dynamically loaded CAFs.
961 \end{description}
962
963 \textbf{To do:} check if this is a complete list.
964
965 The following variables are derivable, but they are given special purposes:
966
967 \begin{description}
968 \item[@g0s0@] points to step 0 of the youngest generation.
969 \item[@oldest\_gen@] points to the oldest generation.
970 \item[@g0s0->blocks@] is the header of the nursery.
971 \item[@g0s0->large\_blocks@] is the header of the large object pool.
972 \end{description}
973
974 \section{Miscellaneous notes}
975
976 \begin{itemize}
977 \item To see how to add new fields to Haskell closures, 
978 see the document on the implementation of retainer profiling 
979 (section `Adding Retainer Set Fields').
980
981 \item To see how to traverse the graph and visit every live closure,
982 see the document on the implementation of retainer profiling
983 (section `Graph Traversal').
984
985 \item To see how to linearly scan the heap at any random moment during
986 program execution, see the document on the implementation of LDVU profiling
987 (section `Heap Censuses').
988
989 \item To see how to linearly scan the from-space during garbage collections,
990 see the document on the implementation of LDVU profiling
991 (section `Destruction of Closures').
992
993 \end{itemize}
994
995 \end{document}