source: doc/papers/llheap/Paper.tex @ b0fcd0e

Last change on this file since b0fcd0e was 16c795c, checked in by Peter A. Buhr <pabuhr@…>, 8 months ago

update llheap paper

  • Property mode set to 100644
File size: 184.8 KB
Line 
1\documentclass[AMA,STIX1COL]{WileyNJD-v2}
2
3% Latex packages used in the document.
4
5\usepackage{comment}
6\usepackage{epic,eepic}
7\usepackage{upquote}                                                                    % switch curled `'" to straight
8\usepackage{relsize}
9\usepackage{xspace}
10\usepackage{calc}
11\usepackage[scaled=0.88]{helvet}                                                % descent Helvetica font and scale to times size
12\usepackage[T1]{fontenc}
13\usepackage{listings}                                                                   % format program code
14\usepackage[labelformat=simple,aboveskip=0pt,farskip=0pt]{subfig}
15\renewcommand{\thesubfigure}{(\alph{subfigure})}
16\usepackage{enumitem}
17
18\hypersetup{breaklinks=true}
19
20\usepackage[pagewise]{lineno}
21\renewcommand{\linenumberfont}{\scriptsize\sffamily}
22
23\usepackage{varioref}                                   % extended references
24% adjust varioref package with default "section" and "page" titles, and optional title with faraway page numbers
25% \VRef{label} => Section 2.7, \VPageref{label} => page 17
26% \VRef[Figure]{label} => Figure 3.4, \VPageref{label} => page 17
27% \renewcommand{\reftextfaceafter}{\unskip}
28% \renewcommand{\reftextfacebefore}{\unskip}
29% \renewcommand{\reftextafter}{\unskip}
30% \renewcommand{\reftextbefore}{\unskip}
31% \renewcommand{\reftextfaraway}[1]{\unskip, p.~\pageref{#1}}
32% \renewcommand{\reftextpagerange}[2]{\unskip, pp.~\pageref{#1}--\pageref{#2}}
33% \newcommand{\VRef}[2][Section]{\ifx#1\@empty\else{#1}\nobreakspace\fi\vref{#2}}
34% \newcommand{\VRefrange}[3][Sections]{\ifx#1\@empty\else{#1}\nobreakspace\fi\vrefrange{#2}{#3}}
35% \newcommand{\VPageref}[2][page]{\ifx#1\@empty\else{#1}\nobreakspace\fi\pageref{#2}}
36% \newcommand{\VPagerefrange}[3][pages]{\ifx#1\@empty\else{#1}\nobreakspace\fi\pageref{#2}{#3}}
37
38\makeatletter
39\newcommand{\abbrevFont}{\textit}                       % set empty for no italics
40\newcommand{\CheckCommaColon}{\@ifnextchar{,}{}{\@ifnextchar{:}{}{,\xspace}}}
41\newcommand{\CheckPeriod}{\@ifnextchar{.}{}{.\xspace}}
42\newcommand{\EG}{\abbrevFont{e}.\abbrevFont{g}.}
43\newcommand{\eg}{\EG\CheckCommaColon}
44\newcommand{\IE}{\abbrevFont{i}.\abbrevFont{e}.}
45\newcommand{\ie}{\IE\CheckCommaColon}
46\newcommand{\ETC}{\abbrevFont{etc}}
47\newcommand{\etc}{\ETC\CheckPeriod}
48\newcommand{\VS}{\abbrevFont{vs}}
49\newcommand{\vs}{\VS\CheckPeriod}
50
51\newcommand{\newtermFont}{\emph}
52\newcommand{\newterm}[1]{\newtermFont{#1}}
53
54\newcommand{\CFAIcon}{\textsf{C}\raisebox{\depth}{\rotatebox{180}{\textsf{A}}}\xspace} % Cforall symbolic name
55\newcommand{\CFA}{\protect\CFAIcon}             % safe for section/caption
56\newcommand{\CFL}{\textrm{Cforall}\xspace}      % Cforall symbolic name
57\newcommand{\CCIcon}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}} % C++ icon
58\newcommand{\CC}[1][]{\protect\CCIcon{#1}\xspace}               % C++ symbolic name
59\newcommand{\uC}{$\mu$\CC}
60\newcommand{\Csharp}{C\raisebox{-0.7ex}{\relsize{2}$^\sharp$}\xspace} % C# symbolic name
61
62\newcommand{\LstBasicStyle}[1]{{\lst@basicstyle{#1}}}
63\newcommand{\LstKeywordStyle}[1]{{\lst@basicstyle{\lst@keywordstyle{#1}}}}
64\newcommand{\LstCommentStyle}[1]{{\lst@basicstyle{\lst@commentstyle{#1}}}}
65\newcommand{\LstStringStyle}[1]{{\lst@basicstyle{\lst@stringstyle{#1}}}}
66
67\newlength{\parindentlnth}
68\setlength{\parindentlnth}{\parindent}
69\newlength{\gcolumnposn}                                % temporary hack because lstlisting does not handle tabs correctly
70\newlength{\columnposn}
71\setlength{\gcolumnposn}{3.25in}
72\setlength{\columnposn}{\gcolumnposn}
73\newcommand{\C}[2][\@empty]{\ifx#1\@empty\else\global\setlength{\columnposn}{#1}\global\columnposn=\columnposn\fi\hfill\makebox[\textwidth-\columnposn][l]{\lst@basicstyle{\LstCommentStyle{#2}}}}
74\newcommand{\CRT}{\global\columnposn=\gcolumnposn}
75\makeatother
76
77\lstset{
78columns=fullflexible,
79basicstyle=\linespread{0.9}\sf,                 % reduce line spacing and use sanserif font
80stringstyle=\small\tt,                                  % use typewriter font
81tabsize=5,                                                              % N space tabbing
82xleftmargin=\parindentlnth,                             % indent code to paragraph indentation
83escapechar=\$,                                                  % LaTeX escape in CFA code
84mathescape=false,                                               % disable LaTeX math escape in CFA code $...$
85keepspaces=true,                                                %
86showstringspaces=false,                                 % do not show spaces with cup
87showlines=true,                                                 % show blank lines at end of code
88aboveskip=4pt,                                                  % spacing above/below code block
89belowskip=2pt,
90numberstyle=\footnotesize\sf,                   % numbering style
91moredelim=**[is][\color{red}]{@}{@},
92% replace/adjust listing characters that look bad in sanserif
93literate=
94%  {-}{\makebox[1ex][c]{\raisebox{0.4ex}{\rule{0.75ex}{0.1ex}}}}1
95  {-}{\raisebox{-1pt}{\ttfamily-}}1
96  {^}{\raisebox{0.6ex}{\(\scriptstyle\land\,\)}}1
97  {~}{\raisebox{0.3ex}{\(\scriptstyle\sim\,\)}}1
98  {'}{\ttfamily'\hspace*{-0.4ex}}1
99  {`}{\ttfamily\upshape\hspace*{-0.3ex}`}1
100  {<-}{$\leftarrow$}2
101  {=>}{$\Rightarrow$}2
102%  {->}{\raisebox{-1pt}{\texttt{-}}\kern-0.1ex\textgreater}2,
103}% lstset
104
105% CFA programming language, based on ANSI C (with some gcc additions)
106\lstdefinelanguage{CFA}[ANSI]{C}{
107        morekeywords={
108                _Alignas, _Alignof, __alignof, __alignof__, and, asm, __asm, __asm__, _Atomic, __attribute, __attribute__,
109                __auto_type, basetypeof, _Bool, catch, catchResume, choose, coerce, _Complex, __complex, __complex__, __const, __const__,
110                coroutine, _Decimal32, _Decimal64, _Decimal128, disable, enable, exception, __extension__, fallthrough, fallthru, finally, fixup,
111                __float80, float80, __float128, float128, _Float16, _Float32, _Float32x, _Float64, _Float64x, _Float128, _Float128x,
112                forall, fortran, generator, _Generic, _Imaginary, __imag, __imag__, inline, __inline, __inline__, int128, __int128, __int128_t,
113                __label__, monitor, mutex, _Noreturn, __builtin_offsetof, one_t, or, recover, report, restrict, __restrict, __restrict__,
114                __signed, __signed__, _Static_assert, suspend, thread, __thread, _Thread_local, throw, throwResume, timeout, trait, try,
115                typeof, __typeof, __typeof__, typeid, __uint128_t, __builtin_va_arg, __builtin_va_list, virtual, __volatile, __volatile__,
116                vtable, waitfor, waituntil, when, with, zero_t,
117    },
118        moredirectives={defined,include_next},
119}
120
121% uC++ programming language, based on ANSI C++
122\lstdefinelanguage{uC++}[GNU]{C++}{
123        morekeywords={
124                _Accept, _AcceptReturn, _AcceptWait, _Actor, _At, _Catch, _CatchResume, _CorActor, _Cormonitor, _Coroutine,
125                _Disable, _Else, _Enable, _Event, _Exception, _Finally, _Monitor, _Mutex, _Nomutex, _PeriodicTask, _RealTimeTask,
126                _Resume, _ResumeTop, _Select, _SporadicTask, _Task, _Timeout, _When, _With, _Throw},
127}
128
129% Go programming language: https://github.com/julienc91/listings-golang/blob/master/listings-golang.sty
130\lstdefinelanguage{Golang}{
131        morekeywords=[1]{package,import,func,type,struct,return,defer,panic,recover,select,var,const,iota,},
132        morekeywords=[2]{string,uint,uint8,uint16,uint32,uint64,int,int8,int16,int32,int64,
133                bool,float32,float64,complex64,complex128,byte,rune,uintptr, error,interface},
134        morekeywords=[3]{map,slice,make,new,nil,len,cap,copy,close,true,false,delete,append,real,imag,complex,chan,},
135        morekeywords=[4]{for,break,continue,range,goto,switch,case,fallthrough,if,else,default,},
136        morekeywords=[5]{Println,Printf,Error,},
137        sensitive=true,
138        morecomment=[l]{//},
139        morecomment=[s]{/*}{*/},
140        morestring=[b]',
141        morestring=[b]",
142        morestring=[s]{`}{`},
143}
144
145\lstnewenvironment{cfa}[1][]{\lstset{language=CFA,moredelim=**[is][\protect\color{red}]{@}{@}}\lstset{#1}}{}
146\lstnewenvironment{C++}[1][]{\lstset{language=C++,moredelim=**[is][\protect\color{red}]{@}{@}}\lstset{#1}}{}
147\lstnewenvironment{uC++}[1][]{\lstset{language=uC++,moredelim=**[is][\protect\color{red}]{@}{@}}\lstset{#1}}{}
148\lstnewenvironment{Go}[1][]{\lstset{language=Golang,moredelim=**[is][\protect\color{red}]{@}{@}}\lstset{#1}}{}
149\lstnewenvironment{python}[1][]{\lstset{language=python,moredelim=**[is][\protect\color{red}]{@}{@}}\lstset{#1}}{}
150\lstnewenvironment{java}[1][]{\lstset{language=java,moredelim=**[is][\protect\color{red}]{@}{@}}\lstset{#1}}{}
151
152% inline code @...@
153\lstMakeShortInline@%
154
155% \let\OLDthebibliography\thebibliography
156% \renewcommand\thebibliography[1]{
157%   \OLDthebibliography{#1}
158%   \setlength{\parskip}{0pt}
159%   \setlength{\itemsep}{4pt plus 0.3ex}
160% }
161
162\newsavebox{\myboxA}
163\newsavebox{\myboxB}
164\newsavebox{\myboxC}
165\newsavebox{\myboxD}
166
167%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
168
169\articletype{RESEARCH ARTICLE}%
170
171% Referees
172% Doug Lea, dl@cs.oswego.edu, SUNY Oswego
173% Herb Sutter, hsutter@microsoft.com, Microsoft Corp
174% Gor Nishanov, gorn@microsoft.com, Microsoft Corp
175% James Noble, kjx@ecs.vuw.ac.nz, Victoria University of Wellington, School of Engineering and Computer Science
176
177\received{XXXXX}
178\revised{XXXXX}
179\accepted{XXXXX}
180
181\raggedbottom
182
183\title{High-Performance Concurrent Memory Allocation}
184
185\author[1]{Mubeen Zulfiqar}
186\author[1]{Ayelet Wasik}
187\author[1]{Peter A. Buhr*}
188\author[2]{Bryan Chan}
189\authormark{ZULFIQAR \textsc{et al.}}
190
191\address[1]{\orgdiv{Cheriton School of Computer Science}, \orgname{University of Waterloo}, \orgaddress{\state{Waterloo, ON}, \country{Canada}}}
192\address[2]{\orgdiv{Huawei Compiler Lab}, \orgname{Huawei}, \orgaddress{\state{Markham, ON}, \country{Canada}}}
193
194\corres{*Peter A. Buhr, Cheriton School of Computer Science, University of Waterloo, 200 University Avenue West, Waterloo, ON N2L 3G1, Canada. \email{pabuhr{\char`\@}uwaterloo.ca}}
195
196% \fundingInfo{Natural Sciences and Engineering Research Council of Canada}
197
198\abstract[Summary]{%
199A new C-based concurrent memory-allocator is presented, called llheap (low latency).
200It can be used standalone in C/\CC applications with multiple kernel threads, or embedded into high-performance user-threading programming languages.
201llheap extends the feature set of existing C allocation by remembering zero-filled (\lstinline{calloc}) and aligned properties (\lstinline{memalign}) in an allocation.
202These properties can be queried, allowing programmers to write safer programs by preserving these properties in future allocations.
203As well, \lstinline{realloc} preserves these properties when adjusting storage size, again increasing future allocation safety.
204llheap also extends the C allocation API with \lstinline{aalloc}, \lstinline{amemalign}, \lstinline{cmemalign}, \lstinline{resize}, and extended \lstinline{realloc}, providing orthogonal access to allocation features;
205hence, programmers do have to code missing combinations.
206The llheap allocator also provides a contention-free statistics gathering mode, and a debugging mode for dynamically checking allocation pre/post conditions and invariants.
207These modes are invaluable for understanding and debugging a program's dynamic allocation behaviour, with low enough cost to be used in production code.
208The llheap API is further extended with the \CFA advanced type-system, providing a single type-safe allocation routine using named arguments, increasing safety and simplifying usage.
209Finally, performance results across a number of benchmarks show llheap is competitive with the best memory allocators.
210}% abstract
211
212% While not as powerful as the \lstinline{valgrind} interpreter, a large number of allocations mistakes are detected.
213% A micro-benchmark test-suite is started for comparing allocators, rather than relying on a suite of arbitrary programs. It has been an interesting challenge.
214% These micro-benchmarks have adjustment knobs to simulate allocation patterns hard-coded into arbitrary test programs.
215% Existing memory allocators, glibc, dlmalloc, hoard, jemalloc, ptmalloc3, rpmalloc, tbmalloc, and the new allocator llheap are all compared using the new micro-benchmark test-suite.
216
217\keywords{memory allocation, (user-level) concurrency, type-safety, statistics, debugging, high performance}
218
219
220\begin{document}
221%\linenumbers                           % comment out to turn off line numbering
222
223\maketitle
224
225
226\section{Introduction}
227
228Memory management services a series of program allocation/deallocation requests and attempts to satisfy them from a variable-sized block of memory, while minimizing total memory usage.
229A general-purpose dynamic-allocation algorithm cannot anticipate allocation requests so its time and space performance is rarely optimal.
230However, allocators take advantage of regular allocation patterns in typical programs to produce excellent results, both in time and space (similar to LRU paging).
231Allocators use a number of similar techniques, but each optimizes specific allocation patterns.
232Nevertheless, allocators are a series of compromises, occasionally with some static or dynamic tuning parameters to optimize specific program-request patterns.
233
234
235\subsection{Memory Structure}
236\label{s:MemoryStructure}
237
238Figure~\ref{f:ProgramAddressSpace} shows the typical layout of a program's address space (high to low) divided into a number of zones, with free memory surrounding the dynamic code/data~\cite{memlayout}.
239Static code and data are placed into memory at load time from the executable and are fixed-sized at runtime.
240Dynamic code/data memory is managed by the dynamic loader for libraries loaded at runtime, which is complex especially in a multi-threaded program~\cite{Huang06}.
241However, changes to the dynamic code/data space are typically infrequent, many occurring at program startup, and are largely outside of a program's control.
242Stack memory is managed by the program call/return-mechanism using a LIFO technique, which works well for sequential programs.
243For stackful coroutines and user threads, a new stack is commonly created in the dynamic-allocation memory.
244The dynamic-allocation memory is often a contiguous area (can be memory mapped as multiple areas), which starts empty and grows/shrinks as the program creates/deletes variables with independent lifetime.
245The programming-language's runtime manages this area, where management complexity is a function of the mechanism for deleting variables.
246This work focuses solely on management of the dynamic-allocation memory.
247
248\begin{figure}
249\centering
250\input{AddressSpace.pstex_t}
251\vspace{-5pt}
252\caption{Program Address Space Divided into Zones}
253\label{f:ProgramAddressSpace}
254\end{figure}
255
256
257\subsection{Dynamic Memory-Management}
258\label{s:DynamicMemoryManagement}
259
260Modern programming languages manage dynamic memory in different ways.
261Some languages, such as Lisp~\cite{CommonLisp}, Java~\cite{Java}, Haskell~\cite{Haskell}, Go~\cite{Go}, provide explicit allocation but \emph{implicit} deallocation of data through garbage collection~\cite{Wilson92}.
262In general, garbage collection supports memory compaction, where dynamic (live) data is moved during runtime to better utilize space.
263However, moving data requires finding and updating pointers to it to reflect the new data locations.
264Programming languages such as C~\cite{C}, \CC~\cite{C++}, and Rust~\cite{Rust} provide the programmer with explicit allocation \emph{and} deallocation of data.
265These languages cannot find and subsequently move live data because pointers can be created to any storage zone, including internal components of allocated objects, and may contain temporary invalid values generated by pointer arithmetic.
266Attempts have been made to perform quasi garbage collection in C/\CC~\cite{Boehm88}, but it is a compromise.
267This work only examines dynamic management with \emph{explicit} deallocation.
268While garbage collection and compaction are not part this work, many of the results are applicable to the allocation phase in any memory-management approach.
269
270Most programs use a general-purpose allocator, usually the one provided by the programming-language's runtime.
271In certain languages, programmers can write specialize allocators for specific needs.
272C and \CC allow easy replacement of the default memory allocator through a standard API.
273Jikes RVM MMTk~\cite{MMTk} provides a similar generalization for the Java virtual machine.
274As well, new languages support concurrency (kernel and/or user threading), which must be safely handled by the allocator.
275Hence, several alternative allocators exist for C/\CC with the goal of scaling in a multi-threaded program~\cite{Berger00,mtmalloc,streamflow,tcmalloc}.
276This work examines the design of high-performance allocators for use by kernel and user multi-threaded applications written in C/\CC.
277
278
279\subsection{Contributions}
280\label{s:Contributions}
281
282This work provides the following contributions in the area of explicit concurrent dynamic-allocation:
283\begin{enumerate}[leftmargin=*,itemsep=0pt]
284\item
285Implementation of a new stand-alone concurrent low-latency memory-allocator ($\approx$1,200 lines of code) for C/\CC programs using kernel threads (1:1 threading), and specialized versions for the concurrent languages \uC~\cite{uC++} and \CFA~\cite{Moss18,Delisle21} using user-level threads running on multiple kernel threads (M:N threading).
286
287\item
288Extend the standard C heap functionality by preserving with each allocation its request size, the amount allocated, whether it is zero fill, and its alignment.
289
290\item
291Use the preserved zero fill and alignment as \emph{sticky} properties for @realloc@ to zero-fill and align when storage is extended or copied.
292Without this extension, it is unsafe to @realloc@ storage these allocations if the properties are not preserved when copying.
293This silent problem is unintuitive to programmers and difficult to locate because it is transient.
294
295\item
296Provide additional heap operations to make allocation properties orthogonally accessible.
297\begin{itemize}[topsep=2pt,itemsep=2pt,parsep=0pt]
298\item
299@aalloc( dim, elemSize )@ same as @calloc@ except memory is \emph{not} zero filled.
300\item
301@amemalign( alignment, dim, elemSize )@ same as @aalloc@ with memory alignment.
302\item
303@cmemalign( alignment, dim, elemSize )@ same as @calloc@ with memory alignment.
304\item
305@resize( oaddr, size )@ re-purpose an old allocation for a new type \emph{without} preserving fill or alignment.
306\item
307@resize( oaddr, alignment, size )@ re-purpose an old allocation with new alignment but \emph{without} preserving fill.
308\item
309@realloc( oaddr, alignment, size )@ same as @realloc@ but adding or changing alignment.
310\end{itemize}
311
312\item
313Provide additional query operations to access information about an allocation:
314\begin{itemize}[topsep=3pt,itemsep=2pt,parsep=0pt]
315\item
316@malloc_alignment( addr )@ returns the alignment of the allocation.
317If the allocation is not aligned or @addr@ is @NULL@, the minimal alignment is returned.
318\item
319@malloc_zero_fill( addr )@ returns a boolean result indicating if the memory is allocated with zero fill, e.g., by @calloc@/@cmemalign@.
320\item
321@malloc_size( addr )@ returns the size of the memory allocation.
322\item
323@malloc_usable_size( addr )@ returns the usable (total) size of the memory, i.e., the bin size containing the allocation, where @malloc_size( addr )@ $\le$ @malloc_usable_size( addr )@.
324\end{itemize}
325
326\item
327Provide optional extensive, fast, and contention-free allocation statistics to understand allocation behaviour, accessed by:
328\begin{itemize}[topsep=3pt,itemsep=2pt,parsep=0pt]
329\item
330@malloc_stats()@ print memory-allocation statistics on the file-descriptor set by @malloc_stats_fd@ (default @stderr@).
331\item
332@malloc_info( options, stream )@ print memory-allocation statistics as an XML string on the specified file-descriptor set by @malloc_stats_fd@ (default @stderr@).
333\item
334@malloc_stats_fd( fd )@ set file-descriptor number for printing memory-allocation statistics (default @stderr@).
335This file descriptor is used implicitly by @malloc_stats@ and @malloc_info@.
336\end{itemize}
337
338\item
339Provide extensive runtime checks to validate allocation operations and identify the amount of unfreed storage at program termination.
340
341\item
342Build 8 different versions of the allocator: static or dynamic linking, with or without statistics or debugging.
343A program may link to any of these 8 versions of the allocator often without recompilation (@LD_PRELOAD@).
344
345\item
346Provide additional heap wrapper functions in \CFA creating a more usable set of allocation operations and properties.
347
348\item
349A micro-benchmark test-suite for comparing allocators rather than relying on a suite of arbitrary programs.
350These micro-benchmarks have adjustment knobs to simulate allocation patterns hard-coded into arbitrary test programs
351\end{enumerate}
352
353
354\section{Background}
355
356The following is a quick overview of allocator design options that affect memory usage and performance (see~\cite{Zulfiqar22} for more details).
357Dynamic acquires and releases obtain storage for a program variable, called an \newterm{object}, through calls such as @malloc@/@new@ and @free@/@delete@ in C/\CC.
358A \newterm{memory allocator} contains a complex data-structure and code that manages the layout of objects in the dynamic-allocation zone.
359The management goals are to make allocation/deallocation operations as fast as possible while densely packing objects to make efficient use of memory.
360Since objects in C/\CC cannot be moved to aid the packing process, only adjacent free storage can be \newterm{coalesced} into larger free areas.
361The allocator grows or shrinks the dynamic-allocation zone to obtain storage for objects and reduce memory usage via operating-system calls, such as @mmap@ or @sbrk@ in UNIX.
362
363
364\subsection{Allocator Components}
365\label{s:AllocatorComponents}
366
367Figure~\ref{f:AllocatorComponents} shows the two important data components for a memory allocator, management and storage, collectively called the \newterm{heap}.
368The \newterm{management data} is a data structure located at a known memory address and contains fixed-sized information in the static-data memory that references components in the dynamic-allocation memory.
369For multi-threaded programs, additional management data may exist in \newterm{thread-local storage} (TLS) for each kernel thread executing the program.
370The \newterm{storage data} is composed of allocated and freed objects, and \newterm{reserved memory}.
371Allocated objects (light grey) are variable sized, and are allocated and maintained by the program;
372\ie only the program knows the location of allocated storage.
373Freed objects (white) represent memory deallocated by the program, which are linked into one or more lists facilitating location of new allocations.
374Reserved memory (dark grey) is one or more blocks of memory obtained from the \newterm{operating system} (OS) but not yet allocated to the program;
375if there are multiple reserved blocks, they are also chained together.
376
377\begin{figure}
378\centering
379\input{AllocatorComponents}
380\caption{Allocator Components (Heap)}
381\label{f:AllocatorComponents}
382\end{figure}
383
384In many allocator designs, allocated objects and reserved blocks have management data embedded within them (see also Section~\ref{s:ObjectContainers}).
385Figure~\ref{f:AllocatedObject} shows an allocated object with a header, trailer, and optional spacing around the object.
386The header contains information about the object, \eg size, type, etc.
387The trailer may be used to simplify coalescing and/or for security purposes to mark the end of an object.
388An object may be preceded by padding to ensure proper alignment.
389Some algorithms quantize allocation requests, resulting in additional space after an object less than the quantized value.
390When padding and spacing are necessary, neither can be used to satisfy a future allocation request while the current allocation exists.
391
392A free object often contains management data, \eg size, pointers, etc.
393Often the free list is chained internally so it does not consume additional storage, \ie the link fields are placed at known locations in the unused memory blocks.
394For internal chaining, the amount of management data for a free node defines the minimum allocation size, \eg if 16 bytes are needed for a free-list node, allocation requests less than 16 bytes are rounded up.
395Often the minimum storage alignment and free-node size are the same.
396The information in an allocated or freed object is overwritten when it transitions from allocated to freed and vice-versa by new program data and/or management information.
397
398\begin{figure}
399\centering
400\input{AllocatedObject}
401\caption{Allocated Object}
402\label{f:AllocatedObject}
403\end{figure}
404
405
406\subsection{Single-Threaded Memory-Allocator}
407\label{s:SingleThreadedMemoryAllocator}
408
409In a sequential (single threaded) program, the program thread performs all allocation operations and concurrency issues do not exist.
410However, interrupts logically introduce concurrency, if the signal handler performs allocation/deallocation (serially reusable problem~\cite{SeriallyReusable}).
411In general, the primary issues in a single-threaded allocator are fragmentation and locality.
412
413\subsubsection{Fragmentation}
414\label{s:Fragmentation}
415
416Fragmentation is memory requested from the OS but not used allocated objects in by the program.
417Figure~\ref{f:InternalExternalFragmentation} shows fragmentation is divided into two forms: \emph{internal} or \emph{external}.
418
419\begin{figure}
420\centering
421\input{IntExtFragmentation}
422\caption{Internal and External Fragmentation}
423\label{f:InternalExternalFragmentation}
424\end{figure}
425
426\newterm{Internal fragmentation} is unaccessible allocated memory, such as headers, trailers, padding, and spacing around an allocated object.
427Internal fragmentation is problematic when management space becomes a significant proportion of an allocated object, \eg for objects $<$16 bytes, memory usage doubles.
428An allocator strives to keep internal management information to a minimum.
429
430\newterm{External fragmentation} is memory not allocated in the program~\cite{Wilson95,Lim98,Siebert00}, which includes all external management data, freed objects, and reserved memory.
431This memory is problematic in two ways: heap blowup and highly fragmented memory.
432\newterm{Heap blowup} occurs when freed memory cannot be reused for future allocations leading to potentially unbounded external fragmentation growth~\cite{Berger00}.
433Memory can become \newterm{highly fragmented} after multiple allocations and deallocations of objects, resulting in a checkerboard of adjacent allocated and free areas, where the free blocks are to small to service requests.
434% Figure~\ref{f:MemoryFragmentation} shows an example of how a small block of memory fragments as objects are allocated and deallocated over time.
435Heap blowup occurs with allocator policies that are too restrictive in reusing freed memory, \eg the allocated size cannot use a larger free block and/or no coalescing of free storage.
436% Blocks of free memory become smaller and non-contiguous making them less useful in serving allocation requests.
437% Memory is highly fragmented when most free blocks are unusable because of their sizes.
438% For example, Figure~\ref{f:Contiguous} and Figure~\ref{f:HighlyFragmented} have the same quantity of external fragmentation, but Figure~\ref{f:HighlyFragmented} is highly fragmented.
439% If there is a request to allocate a large object, Figure~\ref{f:Contiguous} is more likely to be able to satisfy it with existing free memory, while Figure~\ref{f:HighlyFragmented} likely has to request more memory from the OS.
440
441% \begin{figure}
442% \centering
443% \input{MemoryFragmentation}
444% \caption{Memory Fragmentation}
445% \label{f:MemoryFragmentation}
446% \vspace{10pt}
447% \subfloat[Contiguous]{
448%       \input{ContigFragmentation}
449%       \label{f:Contiguous}
450% } % subfloat
451%       \subfloat[Highly Fragmented]{
452%       \input{NonContigFragmentation}
453% \label{f:HighlyFragmented}
454% } % subfloat
455% \caption{Fragmentation Quality}
456% \label{f:FragmentationQuality}
457% \end{figure}
458
459For a single-threaded memory allocator, three basic approaches for controlling fragmentation are identified~\cite{Johnstone99}.
460The first approach is a \newterm{sequential-fit algorithm} with one list of free objects that is searched for a block large enough to fit a requested object size.
461Different search policies determine the free object selected, \eg the first free object large enough or closest to the requested size.
462Any storage larger than the request can become spacing after the object or split into a smaller free object.
463% The cost of the search depends on the shape and quality of the free list, \eg a linear versus a binary-tree free-list, a sorted versus unsorted free-list.
464
465The second approach is a \newterm{segregated} or \newterm{binning algorithm} with a set of lists for different sized freed objects.
466When an object is allocated, the requested size is rounded up to the nearest bin-size, often leading to space after the object.
467A binning algorithm is fast at finding free memory of the appropriate size and allocating it, since the first free object on the free list is used.
468Fewer bin sizes means a faster search to find a matching bin, but larger differences between allocation and bin size, which increases unusable space after objects (internal fragmentation).
469More bin sizes means a slower search but smaller differences matching between allocation and bin size resulting in less internal fragmentation but more external fragmentation if larger bins cannot service smaller requests.
470Allowing larger bins to service smaller allocations when the matching bin is empty means the freed object can be returned to the matching or larger bin (some advantages to either scheme).
471% For example, with bin sizes of 8 and 16 bytes, a request for 12 bytes allocates only 12 bytes, but when the object is freed, it is placed on the 8-byte bin-list.
472% For subsequent requests, the bin free-lists contain objects of different sizes, ranging from one bin-size to the next (8-16 in this example), and a sequential-fit algorithm may be used to find an object large enough for the requested size on the associated bin list.
473
474The third approach is a \newterm{splitting} and \newterm{coalescing} algorithms.
475When an object is allocated, if there is no matching free storage, a larger free object is split into two smaller objects, one matching the allocation size.
476For example, in the \newterm{buddy system}, a block of free memory is split into equal chunks, splitting continues until a minimal block is created that fits the allocation.
477When an object is deallocated, it is coalesced with the objects immediately before/after it in memory, if they are free, turning them into a larger block.
478Coalescing can be done eagerly at each deallocation or lazily when an allocation cannot be fulfilled.
479However, coalescing increases allocation latency (unbounded delays), both for allocation and deallocation.
480While coalescing does not reduce external fragmentation, the coalesced blocks improve fragmentation quality so future allocations are less likely to cause heap blowup.
481% Splitting and coalescing can be used with other algorithms to avoid highly fragmented memory.
482
483
484\subsubsection{Locality}
485\label{s:Locality}
486
487The principle of locality recognizes that programs tend to reference a small set of data, called a \newterm{working set}, for a certain period of time, composed of temporal and spatial accesses~\cite{Denning05}.
488% Temporal clustering implies a group of objects are accessed repeatedly within a short time period, while spatial clustering implies a group of objects physically close together (nearby addresses) are accessed repeatedly within a short time period.
489% Temporal locality commonly occurs during an iterative computation with a fixed set of disjoint variables, while spatial locality commonly occurs when traversing an array.
490Hardware takes advantage of the working set through multiple levels of caching and paging, \ie memory hierarchy.
491% When an object is accessed, the memory physically located around the object is also cached with the expectation that the current and nearby objects will be referenced within a short period of time.
492For example, entire cache lines are transferred between cache and memory, and entire virtual-memory pages are transferred between memory and disk.
493% A program exhibiting good locality has better performance due to fewer cache misses and page faults\footnote{With the advent of large RAM memory, paging is becoming less of an issue in modern programming.}.
494
495Temporal locality is largely controlled by program accesses to its variables~\cite{Feng05}.
496An allocator has only indirect influence on temporal locality but largely dictates spatial locality.
497For temporal locality, an allocator tries to return recently freed storage for new allocations, as this memory is still \emph{warm} in the memory hierarchy.
498For spatial locality, an allocator places objects used together close together in memory, so the working set of the program fits into the fewest possible cache lines and pages.
499% However, usage patterns are different for every program as is the underlying hardware memory architecture;
500% hence, no general-purpose memory-allocator can provide ideal locality for every program on every computer.
501
502An allocator can easily degrade locality by increasing the working set.
503An allocator can access an unbounded number of free objects when matching an allocation or coalescing, causing multiple cache or page misses~\cite{Grunwald93}.
504An allocator can spatially separate related data by binning free storage anywhere in memory, so the related objects are highly separated.
505
506
507\subsection{Multi-Threaded Memory-Allocator}
508\label{s:MultiThreadedMemoryAllocator}
509
510In a concurrent (multi-threaded) program, multiple program threads performs allocation operations and all concurrency issues arise.
511Along with fragmentation and locality issues, a multi-threaded allocator must deal with mutual exclusion, false sharing, and additional forms of heap blowup.
512
513
514\subsubsection{Mutual Exclusion}
515\label{s:MutualExclusion}
516
517\newterm{Mutual exclusion} provides sequential access to the shared-management data of the heap.
518There are two performance issues for mutual exclusion.
519First is the cost of performing at least one hardware atomic operation every time a shared resource is accessed.
520Second is \emph{contention} on simultaneous access, so some threads must wait until the resource is released.
521Contention can be reduced in a number of ways:
5221) Using multiple fine-grained locks versus a single lock to spread the contention across the locks.
5232) Using trylock and generating new storage if the lock is busy (classic space versus time tradeoff).
5243) Using one of the many lock-free approaches for reducing contention on basic data-structure operations~\cite{Oyama99}.
525However, all approaches have degenerate cases where program contention to the heap is high, which is beyond the allocator's control.
526
527
528\subsubsection{False Sharing}
529\label{s:FalseSharing}
530
531False sharing occurs when two or more threads simultaneously modify different objects sharing a cache line.
532Changes now invalidate each thread's cache, even though the threads may be uninterested in the other modified object.
533False sharing can occur three ways:
5341) Thread T$_1$ allocates objects O$_1$ and O$_2$ on the same cache line and passes O$_2$'s reference to thread T$_2$;
535both threads now simultaneously modifying the objects on the same cache line.
5362) Objects O$_1$ and O$_2$ are allocated on the same cache line by thread T$_3$ and their references are passed to T$_1$ and T$_2$, which simultaneously modify the objects.
5373) T$_2$ deallocates O$_2$, T$_1$ allocates O$_1$ on the same cache line as O$_2$, and T$_2$ reallocated O$_2$ while T$_1$ is using O$_1$.
538In all three cases, the allocator performs a hidden and possibly transient (non-determinism) operation, making it extremely difficult to find and fix the issue.
539
540
541\subsubsection{Heap Blowup}
542\label{s:HeapBlowup}
543
544In a multi-threaded program, heap blowup occurs when memory freed by one thread is inaccessible to other threads due to the allocation strategy.
545Specific examples are presented in later subsections.
546
547
548\subsection{Multi-Threaded Allocator Features}
549\label{s:MultiThreadedAllocatorFeatures}
550
551The following features are used in the construction of multi-threaded allocators.
552
553\subsubsection{Multiple Heaps}
554\label{s:MultipleHeaps}
555
556Figure~\ref{f:ThreadHeapRelationship} shows how a multi-threaded allocator reduced contention by subdividing a single heap into multiple heaps.
557
558\begin{figure}
559\centering
560\subfloat[T:1]{
561%       \input{SingleHeap.pstex_t}
562        \input{SingleHeap}
563        \label{f:SingleHeap}
564} % subfloat
565\vrule
566\subfloat[T:H]{
567%       \input{MultipleHeaps.pstex_t}
568        \input{SharedHeaps}
569        \label{f:SharedHeaps}
570} % subfloat
571\vrule
572\subfloat[1:1]{
573%       \input{MultipleHeapsGlobal.pstex_t}
574        \input{PerThreadHeap}
575        \label{f:PerThreadHeap}
576} % subfloat
577\caption{Multiple Heaps, Thread:Heap Relationship}
578\label{f:ThreadHeapRelationship}
579\end{figure}
580
581\begin{description}[leftmargin=*]
582\item[T:1 model (Figure~\ref{f:SingleHeap})] is all threads (T) sharing a single heap (1).
583The arrows indicate memory movement for allocation/deallocation operations.
584Memory is obtained from freed objects, reserved memory, or the OS;
585freed memory can be returned to the OS.
586To handle concurrency, a single lock is used for all heap operations or fine-grained locking if operations can be made independent.
587As threads perform large numbers of allocations, a single heap becomes a significant source of contention.
588
589\item[T:H model (Figure~\ref{f:SharedHeaps})] is multiple threads (T) sharing multiple heaps (H).
590The allocator independently allocates/deallocates heaps and assigns threads to heaps based on dynamic contention pressure.
591Locking is required within each heap, but contention is reduced because fewer threads access a specific heap.
592The goal is minimal heaps (storage) and contention per heap (time).
593A worst case is more heaps than threads, \eg many threads at startup create a large number of heaps and then the threads reduce.
594
595% For example, multiple heaps are managed in a pool, starting with a single or a fixed number of heaps that increase\-/decrease depending on contention\-/space issues.
596% At creation, a thread is associated with a heap from the pool.
597% In some implementations of this model, when the thread attempts an allocation and its associated heap is locked (contention), it scans for an unlocked heap in the pool.
598% If an unlocked heap is found, the thread changes its association and uses that heap.
599% If all heaps are locked, the thread may create a new heap, use it, and then place the new heap into the pool;
600% or the thread can block waiting for a heap to become available.
601% While the heap-pool approach often minimizes the number of extant heaps, the worse case can result in more heaps than threads;
602% \eg if the number of threads is large at startup with many allocations creating a large number of heaps and then the number of threads reduces.
603
604% Threads using multiple heaps need to determine the specific heap to access for an allocation/deallocation, \ie association of thread to heap.
605% A number of techniques are used to establish this association.
606% The simplest approach is for each thread to have a pointer to its associated heap (or to administrative information that points to the heap), and this pointer changes if the association changes.
607% For threading systems with thread-local storage, the heap pointer is created using this mechanism;
608% otherwise, the heap routines must simulate thread-local storage using approaches like hashing the thread's stack-pointer or thread-id to find its associated heap.
609
610% The storage management for multiple heaps is more complex than for a single heap (see Figure~\ref{f:AllocatorComponents}).
611% Figure~\ref{f:MultipleHeapStorage} illustrates the general storage layout for multiple heaps.
612% Allocated and free objects are labelled by the thread or heap they are associated with.
613% (Links between free objects are removed for simplicity.)
614% The management information for multiple heaps in the static zone must be able to locate all heaps.
615% The management information for the heaps must reside in the dynamic-allocation zone if there are a variable number.
616% Each heap in the dynamic zone is composed of a list of free objects and a pointer to its reserved memory.
617% An alternative implementation is for all heaps to share one reserved memory, which requires a separate lock for the reserved storage to ensure mutual exclusion when acquiring new memory.
618% Because multiple threads can allocate/free/reallocate adjacent storage, all forms of false sharing may occur.
619% Other storage-management options are to use @mmap@ to set aside (large) areas of virtual memory for each heap and suballocate each heap's storage within that area, pushing part of the storage management complexity back to the OS.
620
621% \begin{figure}
622% \centering
623% \input{MultipleHeapsStorage}
624% \caption{Multiple-Heap Storage}
625% \label{f:MultipleHeapStorage}
626% \end{figure}
627
628Multiple heaps increase external fragmentation as the ratio of heaps to threads increases, which can lead to heap blowup.
629The external fragmentation experienced by a program with a single heap is now multiplied by the number of heaps, since each heap manages its own free storage and allocates its own reserved memory.
630Additionally, objects freed by one heap cannot be reused by other threads without increasing the cost of the memory operations, except indirectly by returning free memory to the OS (see Section~\ref{s:Ownership}).
631Returning storage to the OS may be difficult or impossible, \eg the contiguous @sbrk@ area in Unix.
632% In the worst case, a program in which objects are allocated from one heap but deallocated to another heap means these freed objects are never reused.
633
634Adding a \newterm{global heap} (G) attempts to reduce the cost of obtaining/returning memory among heaps (sharing) by buffering storage within the application address-space.
635Now, each heap obtains and returns storage to/from the global heap rather than the OS.
636Storage is obtained from the global heap only when a heap allocation cannot be fulfilled, and returned to the global heap when a heap's free memory exceeds some threshold.
637Similarly, the global heap buffers this memory, obtaining and returning storage to/from the OS as necessary.
638The global heap does not have its own thread and makes no internal allocation requests;
639instead, it uses the application thread, which called one of the multiple heaps and then the global heap, to perform operations.
640Hence, the worst-case cost of a memory operation includes all these steps.
641With respect to heap blowup, the global heap provides an indirect mechanism to move free memory among heaps, which usually has a much lower cost than interacting with the OS to achieve the same goal and is independent of the mechanism used by the OS to present dynamic memory to an address space.
642However, since any thread may indirectly perform a memory operation on the global heap, it is a shared resource that requires locking.
643A single lock can be used to protect the global heap or fine-grained locking can be used to reduce contention.
644In general, the cost is minimal since the majority of memory operations are completed without the use of the global heap.
645
646\item[1:1 model (Figure~\ref{f:PerThreadHeap})] is each thread (1) has a heap (1), eliminating most contention and locking if threads seldom access another thread's heap (see Section~\ref{s:Ownership}).
647A thread's objects are consolidated in its heap, better utilizing the cache and paging during thread execution.
648In contrast, the T:H model can spread thread objects over a larger area in different heaps.
649Thread heaps can also reduces false-sharing, unless there are overlapping memory boundaries from another thread's heap.
650%For example, assume page boundaries coincide with cache line boundaries, if a thread heap always acquires pages of memory then no two threads share a page or cache line unless pointers are passed among them.
651
652When a thread terminates, it can free its heap objects to the global heap, or the thread heap is retained as-is and reused for a new thread in the future.
653Destroying a heap can reduce external fragmentation sooner, since all free objects in the global heap are available for immediate reuse.
654Alternatively, reusing a heap can aid the inheriting thread, if it has a similar allocation pattern because the heap in primed with unfreed storage of the right sizes.
655\end{description}
656
657
658\subsubsection{User-Level Threading}
659
660It is possible to use any of the heap models with user-level (M:N) threading.
661However, an important goal of user-level threading is for fast operations (creation/termination/context-switching) by not interacting with the OS, which allows the ability to create large numbers of high-performance interacting threads ($>$ 10,000).
662It is difficult to retain this goal, if the user-threading model is directly involved with the heap model.
663Figure~\ref{f:UserLevelKernelHeaps} shows that virtually all user-level threading systems use whatever kernel-level heap-model is provided by the language runtime.
664Hence, a user thread allocates/deallocates from/to the heap of the kernel thread on which it is currently executing.
665
666\begin{figure}
667\centering
668\input{UserKernelHeaps}
669\caption{User-Level Kernel Heaps}
670\label{f:UserLevelKernelHeaps}
671\end{figure}
672
673Adopting user threading results in a subtle problem with shared heaps.
674With kernel threading, an operation started by a kernel thread is always completed by that thread.
675For example, if a kernel thread starts an allocation/deallocation on a shared heap, it always completes that operation with that heap, even if preempted, \ie any locking correctness associated with the shared heap is preserved across preemption.
676However, this correctness property is not preserved for user-level threading.
677A user thread can start an allocation/deallocation on one kernel thread, be preempted (time slice), and continue running on a different kernel thread to complete the operation~\cite{Dice02}.
678When the user thread continues on the new kernel thread, it may have pointers into the previous kernel-thread's heap and hold locks associated with it.
679To get the same kernel-thread safety, time slicing must be disabled/\-enabled around these operations, so the user thread cannot jump to another kernel thread.
680However, eagerly disabling/enabling time-slicing on the allocation/deallocation fast path is expensive, because preemption is infrequent (milliseconds).
681Instead, techniques exist to lazily detect this case in the interrupt handler, abort the preemption, and return to the operation so it can complete atomically.
682Occasional ignoring of a preemption should be benign, but a persistent lack of preemption can result in starvation;
683techniques like rolling forward the preemption to the next context switch can be used.
684
685
686\subsubsection{Ownership}
687\label{s:Ownership}
688
689\newterm{Ownership} defines which heap an object is returned-to on deallocation.
690If a thread returns an object to the heap it was originally allocated from, a heap has ownership of its objects.
691Alternatively, a thread can return an object to the heap it is currently associated with, which can be any heap accessible during a thread's lifetime.
692Figure~\ref{f:HeapsOwnership} shows an example of multiple heaps (minus the global heap) with and without ownership.
693Again, the arrows indicate the direction memory conceptually moves for each kind of operation.
694For the 1:1 thread:heap relationship, a thread only allocates from its own heap, and without ownership, a thread only frees objects to its own heap, which means the heap is private to its owner thread and does not require any locking, called a \newterm{private heap}.
695For the T:1/T:H models with or without ownership or the 1:1 model with ownership, a thread may free objects to different heaps, which makes each heap publicly accessible to all threads, called a \newterm{public heap}.
696
697\begin{figure}
698\centering
699\subfloat[Ownership]{
700        \input{MultipleHeapsOwnership}
701} % subfloat
702\hspace{0.25in}
703\subfloat[No Ownership]{
704        \input{MultipleHeapsNoOwnership}
705} % subfloat
706\caption{Heap Ownership}
707\label{f:HeapsOwnership}
708\end{figure}
709
710% Figure~\ref{f:MultipleHeapStorageOwnership} shows the effect of ownership on storage layout.
711% (For simplicity, assume the heaps all use the same size of reserves storage.)
712% In contrast to Figure~\ref{f:MultipleHeapStorage}, each reserved area used by a heap only contains free storage for that particular heap because threads must return free objects back to the owner heap.
713% Passive false-sharing may still occur, if delayed ownership is used (see below).
714
715% \begin{figure}
716% \centering
717% \input{MultipleHeapsOwnershipStorage.pstex_t}
718% \caption{Multiple-Heap Storage with Ownership}
719% \label{f:MultipleHeapStorageOwnership}
720% \end{figure}
721
722The main advantage of ownership is preventing heap blowup by returning storage for reuse by the owner heap.
723Ownership prevents the classical problem where one thread performs allocations from one heap, passes the object to another thread, and the receiving thread deallocates the object to another heap, hence draining the initial heap of storage.
724Because multiple threads can allocate/free/reallocate adjacent storage in the same heap, all forms of false sharing may occur.
725The exception is for the 1:1 model if reserved memory does not overlap a cache-line because all allocated storage within a used area is associated with a single thread.
726In this case, there is no allocator-induced active false-sharing because two adjacent allocated objects used by different threads cannot share a cache-line.
727Finally, there is no allocator-induced passive false-sharing because two adjacent allocated objects used by different threads cannot occur as free objects are returned to the owner heap.
728% For example, in Figure~\ref{f:AllocatorInducedPassiveFalseSharing}, the deallocation by Thread$_2$ returns Object$_2$ back to Thread$_1$'s heap;
729% hence a subsequent allocation by Thread$_2$ cannot return this storage.
730The disadvantage of ownership is deallocating to another thread's heap so heaps are no longer private and require locks to provide safe concurrent access.
731
732Object ownership can be immediate or delayed, meaning free objects may be batched on a separate free list either by the returning or receiving thread.
733While the returning thread can batch objects, batching across multiple heaps is complex and there is no obvious time when to push back to the owner heap.
734It is better for returning threads to immediately return to the receiving thread's batch list as the receiving thread has better knowledge when to incorporate the batch list into its free pool.
735Batching leverages the fact that most allocation patterns use the contention-free fast-path, so locking on the batch list is rare for both the returning and receiving threads.
736Finally, it is possible for heaps to temporarily steal owned objects rather than return them immediately and then reallocate these objects again.
737It is unclear whether the complexity of this approach is worthwhile.
738% However, stealing can result in passive false-sharing.
739% For example, in Figure~\ref{f:AllocatorInducedPassiveFalseSharing}, Object$_2$ may be deallocated to Thread$_2$'s heap initially.
740% If Thread$_2$ reallocates Object$_2$ before it is returned to its owner heap, then passive false-sharing may occur.
741
742For thread heaps with ownership, it is possible to combine these approaches into a hybrid approach with both private and public heaps.% (see~Figure~\ref{f:HybridPrivatePublicHeap}).
743The main goal of the hybrid approach is to eliminate locking on thread-local allocation/deallocation, while providing ownership to prevent heap blowup.
744In the hybrid approach, a thread first allocates from its private heap and second from its public heap if no free memory exists in the private heap.
745Similarly, a thread first deallocates an object to its private heap, and second to the public heap.
746Both private and public heaps can allocate/deallocate to/from the global heap if there is no free memory or excess free memory, although an implementation may choose to funnel all interaction with the global heap through one of the heaps.
747% Note, deallocation from the private to the public (dashed line) is unlikely because there is no obvious advantages unless the public heap provides the only interface to the global heap.
748Finally, when a thread frees an object it does not own, the object is either freed immediately to its owner's public heap or put in the freeing thread's private heap for delayed ownership, which does allows the freeing thread to temporarily reuse an object before returning it to its owner or batch objects for an owner heap into a single return.
749
750% \begin{figure}
751% \centering
752% \input{PrivatePublicHeaps.pstex_t}
753% \caption{Hybrid Private/Public Heap for Per-thread Heaps}
754% \label{f:HybridPrivatePublicHeap}
755% \vspace{10pt}
756% \input{RemoteFreeList.pstex_t}
757% \caption{Remote Free-List}
758% \label{f:RemoteFreeList}
759% \end{figure}
760
761% As mentioned, an implementation may have only one heap interact with the global heap, so the other heap can be simplified.
762% For example, if only the private heap interacts with the global heap, the public heap can be reduced to a lock-protected free-list of objects deallocated by other threads due to ownership, called a \newterm{remote free-list}.
763% To avoid heap blowup, the private heap allocates from the remote free-list when it reaches some threshold or it has no free storage.
764% Since the remote free-list is occasionally cleared during an allocation, this adds to that cost.
765% Clearing the remote free-list is $O(1)$ if the list can simply be added to the end of the private-heap's free-list, or $O(N)$ if some action must be performed for each freed object.
766 
767% If only the public heap interacts with other threads and the global heap, the private heap can handle thread-local allocations and deallocations without locking.
768% In this scenario, the private heap must deallocate storage after reaching a certain threshold to the public heap (and then eventually to the global heap from the public heap) or heap blowup can occur.
769% If the public heap does the major management, the private heap can be simplified to provide high-performance thread-local allocations and deallocations.
770 
771% The main disadvantage of each thread having both a private and public heap is the complexity of managing two heaps and their interactions in an allocator.
772% Interestingly, heap implementations often focus on either a private or public heap, giving the impression a single versus a hybrid approach is being used.
773% In many case, the hybrid approach is actually being used, but the simpler heap is just folded into the complex heap, even though the operations logically belong in separate heaps.
774% For example, a remote free-list is actually a simple public-heap, but may be implemented as an integral component of the complex private-heap in an allocator, masking the presence of a hybrid approach.
775
776
777\begin{figure}
778\centering
779\subfloat[Object Headers]{
780        \input{ObjectHeaders}
781        \label{f:ObjectHeaders}
782} % subfloat
783\subfloat[Object Container]{
784        \input{Container}
785        \label{f:ObjectContainer}
786} % subfloat
787\caption{Header Placement}
788\label{f:HeaderPlacement}
789\end{figure}
790
791
792\subsubsection{Object Containers}
793\label{s:ObjectContainers}
794
795Associating header data with every allocation can result in significant internal fragmentation, as shown in Figure~\ref{f:ObjectHeaders}.
796Especially if the headers contain redundant data, \eg object size may be the same for many objects because programs only allocate a small set of object sizes.
797As well, the redundant data can result in poor cache usage, since only a portion of the cache line is holding useful data from the program's perspective.
798Spatial locality can also be negatively affected leading to poor cache locality~\cite{Feng05}.
799While the header and object are spatially together in memory, they are generally not accessed temporarily together;
800\eg an object is accessed by the program after it is allocated, while the header is accessed by the allocator after it is free.
801
802An alternative approach factors common header data to a separate location in memory and organizes associated free storage into blocks called \newterm{object containers} (\newterm{superblocks}~\cite{Berger00}), as in Figure~\ref{f:ObjectContainer}.
803The header for the container holds information necessary for all objects in the container;
804a trailer may also be used at the end of the container.
805Similar to the approach described for thread heaps in Section~\ref{s:MultipleHeaps}, if container boundaries do not overlap with memory of another container at crucial boundaries and all objects in a container are allocated to the same thread, allocator-induced active false-sharing is avoided.
806
807The difficulty with object containers lies in finding the object header/trailer given only the object address, since that is normally the only information passed to the deallocation operation.
808One way is to start containers on aligned addresses in memory, then truncate the lower bits of the object address to obtain the header address (or round up and subtract the trailer size to obtain the trailer address).
809For example, if an object at address 0xFC28\,EF08 is freed and containers are aligned on 64\,KB (0x0001\,0000) addresses, then the container header is at 0xFC28\,0000.
810
811Normally, a container has homogeneous objects, \eg object size and ownership.
812This approach greatly reduces internal fragmentation since far fewer headers are required, and potentially increases spatial locality as a cache line or page holds more objects since the objects are closer together.
813However, different sized objects are further apart in separate containers.
814Depending on the program, this may or may not improve locality.
815If the program uses several objects from a small number of containers in its working set, then locality is improved since fewer cache lines and pages are required.
816If the program uses many containers, there is poor locality, as both caching and paging increase.
817Another drawback is that external fragmentation may be increased since containers reserve space for objects that may never be allocated, \ie there are often multiple containers for each size only partially full.
818However, external fragmentation can be reduced by using small containers.
819
820Containers with heterogeneous objects implies different headers describing them, which complicates the problem of locating a specific header solely by an address.
821A couple of solutions can be used to implement containers with heterogeneous objects.
822However, the problem with allowing objects of different sizes is that the number of objects, and therefore headers, in a single container is unpredictable.
823One solution allocates headers at one end of the container, while allocating objects from the other end of the container;
824when the headers meet the objects, the container is full.
825Freed objects cannot be split or coalesced since this causes the number of headers to change.
826The difficulty in this strategy remains in finding the header for a specific object;
827in general, a search is necessary to find the object's header among the container headers.
828A second solution combines the use of container headers and individual object headers.
829Each object header stores the object's heterogeneous information, such as its size, while the container header stores the homogeneous information, such as the owner when using ownership.
830This approach allows containers to hold different types of objects, but does not completely separate headers from objects.
831% The benefit of the container in this case is to reduce some redundant information that is factored into the container header.
832
833% In summary, object containers trade off internal fragmentation for external fragmentation by isolating common administration information to remove/reduce internal fragmentation, but at the cost of external fragmentation as some portion of a container may not be used and this portion is unusable for other kinds of allocations.
834% A consequence of this tradeoff is its effect on spatial locality, which can produce positive or negative results depending on program access-patterns.
835
836
837\paragraph{Container Ownership}
838\label{s:ContainerOwnership}
839
840Without ownership, objects in a container are deallocated to the heap currently associated with the thread that frees the object.
841Thus, different objects in a container may be on different heap free-lists. % (see Figure~\ref{f:ContainerNoOwnershipFreelist}).
842With ownership, all objects in a container belong to the same heap,
843% (see Figure~\ref{f:ContainerOwnershipFreelist}),
844so ownership of an object is determined by the container owner.
845If multiple threads can allocate/free/reallocate adjacent storage in the same heap, all forms of false sharing may occur.
846Only with the 1:1 model and ownership is active and passive false-sharing avoided (see Section~\ref{s:Ownership}).
847Passive false-sharing may still occur, if delayed ownership is used.
848Finally, a completely free container can become reserved storage and be reset to allocate objects of a new size or freed to the global heap.
849
850% \begin{figure}
851% \centering
852% \subfloat[No Ownership]{
853%       \input{ContainerNoOwnershipFreelist}
854%       \label{f:ContainerNoOwnershipFreelist}
855% } % subfloat
856% \vrule
857% \subfloat[Ownership]{
858%       \input{ContainerOwnershipFreelist}
859%       \label{f:ContainerOwnershipFreelist}
860% } % subfloat
861% \caption{Free-list Structure with Container Ownership}
862% \end{figure}
863
864When a container changes ownership, the ownership of all objects within it change as well.
865Moving a container involves moving all objects on the heap's free-list in that container to the new owner.
866This approach can reduce contention for the global heap, since each request for objects from the global heap returns a container rather than individual objects.
867
868Additional restrictions may be applied to the movement of containers to prevent active false-sharing.
869For example, if a container changes ownership through the global heap, then a thread allocating from the newly acquired container is actively false-sharing even though no objects are passed among threads.
870Note, once the thread frees the object, no more false sharing can occur until the container changes ownership again.
871To prevent this form of false sharing, container movement may be restricted to when all objects in the container are free.
872One implementation approach that increases the freedom to return a free container to the OS involves allocating containers using a call like @mmap@, which allows memory at an arbitrary address to be returned versus only storage at the end of the contiguous @sbrk@ area, again pushing storage management complexity back to the OS.
873
874% \begin{figure}
875% \centering
876% \subfloat[]{
877%       \input{ContainerFalseSharing1}
878%       \label{f:ContainerFalseSharing1}
879% } % subfloat
880% \subfloat[]{
881%       \input{ContainerFalseSharing2}
882%       \label{f:ContainerFalseSharing2}
883% } % subfloat
884% \caption{Active False-Sharing using Containers}
885% \label{f:ActiveFalseSharingContainers}
886% \end{figure}
887
888Using containers with ownership increases external fragmentation since a new container for a requested object size must be allocated separately for each thread requesting it.
889% In Figure~\ref{f:ExternalFragmentationContainerOwnership}, using object ownership allocates 80\% more space than without ownership.
890
891% \begin{figure}
892% \centering
893% \subfloat[No Ownership]{
894%       \input{ContainerNoOwnership}
895% } % subfloat
896% \\
897% \subfloat[Ownership]{
898%       \input{ContainerOwnership}
899% } % subfloat
900% \caption{External Fragmentation with Container Ownership}
901% \label{f:ExternalFragmentationContainerOwnership}
902% \end{figure}
903
904
905\paragraph{Container Size}
906\label{s:ContainerSize}
907
908One way to control the external fragmentation caused by allocating a large container for a small number of requested objects is to vary the size of the container.
909As described earlier, container boundaries need to be aligned on addresses that are a power of two to allow easy location of the header (by truncating lower bits).
910Aligning containers in this manner also determines the size of the container.
911However, the size of the container has different implications for the allocator.
912
913The larger the container, the fewer containers are needed, and hence, the fewer headers need to be maintained in memory, improving both internal fragmentation and potentially performance.
914However, with more objects in a container, there may be more objects that are unallocated, increasing external fragmentation.
915With smaller containers, not only are there more containers, but a second new problem arises where objects are larger than the container.
916In general, large objects, \eg greater than 64\,KB, are allocated directly from the OS and are returned immediately to the OS to reduce long-term external fragmentation.
917If the container size is small, \eg 1\,KB, then a 1.5\,KB object is treated as a large object, which is likely to be inappropriate.
918Ideally, it is best to use smaller containers for smaller objects, and larger containers for medium objects, which leads to the issue of locating the container header.
919
920In order to find the container header when using different sized containers, a super container is used (see~Figure~\ref{f:SuperContainers}).
921The super container spans several containers, contains a header with information for finding each container header, and starts on an aligned address.
922Super-container headers are found using the same method used to find container headers by dropping the lower bits of an object address.
923The containers within a super container may be different sizes or all the same size.
924If the containers in the super container are different sizes, then the super-container header must be searched to determine the specific container for an object given its address.
925If all containers in the super container are the same size, \eg 16KB, then a specific container header can be found by a simple calculation.
926The free space at the end of a super container is used to allocate new containers.
927
928\begin{figure}
929\centering
930\input{SuperContainers}
931% \includegraphics{diagrams/supercontainer.eps}
932\caption{Super Containers}
933\label{f:SuperContainers}
934\end{figure}
935
936Minimal internal and external fragmentation is achieved by having as few containers as possible, each being as full as possible.
937It is also possible to achieve additional benefit by using larger containers for popular small sizes, as it reduces the number of containers with associated headers.
938However, this approach assumes it is possible for an allocator to determine in advance which sizes are popular.
939Keeping statistics on requested sizes allows the allocator to make a dynamic decision about which sizes are popular.
940For example, after receiving a number of allocation requests for a particular size, that size is considered a popular request size and larger containers are allocated for that size.
941If the decision is incorrect, larger containers than necessary are allocated that remain mostly unused.
942A programmer may be able to inform the allocator about popular object sizes, using a mechanism like @mallopt@, in order to select an appropriate container size for each object size.
943
944
945\paragraph{Container Free-Lists}
946\label{s:containersfreelists}
947
948The container header allows an alternate approach for managing the heap's free-list.
949Rather than maintain a global free-list throughout the heap the containers are linked through their headers and only the local free objects within a container are linked together.
950Note, maintaining free lists within a container assumes all free objects in the container are associated with the same heap;
951thus, this approach only applies to containers with ownership.
952
953This alternate free-list approach can greatly reduce the complexity of moving all freed objects belonging to a container to another heap.
954To move a container using a global free-list, the free list is first searched to find all objects within the container.
955Each object is then removed from the free list and linked together to form a local free-list for the move to the new heap.
956With local free-lists in containers, the container is simply removed from one heap's free list and placed on the new heap's free list.
957Thus, when using local free-lists, the operation of moving containers is reduced from $O(N)$ to $O(1)$.
958However, there is the additional storage cost in the header, which increases the header size, and therefore internal fragmentation.
959
960% \begin{figure}
961% \centering
962% \subfloat[Global Free-List Among Containers]{
963%       \input{FreeListAmongContainers}
964%       \label{f:GlobalFreeListAmongContainers}
965% } % subfloat
966% \hspace{0.25in}
967% \subfloat[Local Free-List Within Containers]{
968%       \input{FreeListWithinContainers}
969%       \label{f:LocalFreeListWithinContainers}
970% } % subfloat
971% \caption{Container Free-List Structure}
972% \label{f:ContainerFreeListStructure}
973% \end{figure}
974
975When all objects in the container are the same size, a single free-list is sufficient.
976However, when objects in the container are different size, the header needs a free list for each size class when using a binning allocation algorithm, which can be a significant increase in the container-header size.
977The alternative is to use a different allocation algorithm with a single free-list, such as a sequential-fit allocation-algorithm.
978
979
980\subsubsection{Allocation Buffer}
981\label{s:AllocationBuffer}
982
983An allocation buffer is reserved memory (see Section~\ref{s:AllocatorComponents}) not yet allocated to the program, and is used for allocating objects when the free list is empty.
984That is, rather than requesting new storage for a single object, an entire buffer is requested from which multiple objects are allocated later.
985Any heap may use an allocation buffer, resulting in allocation from the buffer before requesting objects (containers) from the global heap or OS, respectively.
986The allocation buffer reduces contention and the number of global/operating-system calls.
987For coalescing, a buffer is split into smaller objects by allocations, and recomposed into larger buffer areas during deallocations.
988
989Allocation buffers are useful initially when there are no freed objects in a heap because many allocations usually occur when a thread starts (simple bump allocation).
990Furthermore, to prevent heap blowup, objects should be reused before allocating a new allocation buffer.
991Thus, allocation buffers are often allocated more frequently at program/thread start, and then allocations often diminish.
992
993Using an allocation buffer with a thread heap avoids active false-sharing, since all objects in the allocation buffer are allocated to the same thread.
994For example, if all objects sharing a cache line come from the same allocation buffer, then these objects are allocated to the same thread, avoiding active false-sharing.
995Active false-sharing may still occur if objects are freed to the global heap and reused by another heap.
996
997Allocation buffers may increase external fragmentation, since some memory in the allocation buffer may never be allocated.
998A smaller allocation buffer reduces the amount of external fragmentation, but increases the number of calls to the global heap or OS.
999The allocation buffer also slightly increases internal fragmentation, since a pointer is necessary to locate the next free object in the buffer.
1000
1001The unused part of a container, neither allocated or freed, is an allocation buffer.
1002For example, when a container is created, rather than placing all objects within the container on the free list, the objects form an allocation buffer and are allocated from the buffer as allocation requests are made.
1003This lazy method of constructing objects is beneficial in terms of paging and caching.
1004For example, although an entire container, possibly spanning several pages, is allocated from the OS, only a small part of the container is used in the working set of the allocator, reducing the number of pages and cache lines that are brought into higher levels of cache.
1005
1006
1007\subsubsection{Lock-Free Operations}
1008\label{s:LockFreeOperations}
1009
1010A \newterm{lock-free algorithm} guarantees safe concurrent-access to a data structure, so that at least one thread makes progress, but an individual thread has no execution bound and may starve~\cite[pp.~745--746]{Herlihy93}.
1011(A \newterm{wait-free algorithm} puts a bound on the number of steps any thread takes to complete an operation to prevent starvation.)
1012Lock-free operations can be used in an allocator to reduce or eliminate the use of locks.
1013While locks and lock-free data-structures often have equal performance, lock-free has the advantage of not holding a lock across preemption so other threads can continue to make progress.
1014With respect to the heap, these situations are unlikely unless all threads make extremely high use of dynamic-memory allocation, which can be an indication of poor design.
1015Nevertheless, lock-free algorithms can reduce the number of context switches, since a thread does not yield/block while waiting for a lock;
1016on the other hand, a thread may busy-wait for an unbounded period holding a processor.
1017Finally, lock-free implementations have greater complexity and hardware dependency.
1018Lock-free algorithms can be applied most easily to simple free-lists, \eg remote free-list, to allow lock-free insertion and removal from the head of a stack.
1019Implementing lock-free operations for more complex data-structures (queue~\cite{Valois94}/deque~\cite{Sundell08}) is correspondingly more complex.
1020Michael~\cite{Michael04} and Gidenstam \etal \cite{Gidenstam05} have created lock-free variations of the Hoard allocator.
1021
1022
1023\section{Allocator}
1024\label{c:Allocator}
1025
1026This section presents a new stand-alone concurrent low-latency memory-allocator ($\approx$1,200 lines of code), called llheap (low-latency heap), for C/\CC programs using kernel threads (1:1 threading), and specialized versions of the allocator for the programming languages \uC and \CFA using user-level threads running over multiple kernel threads (M:N threading).
1027The new allocator fulfills the GNU C Library allocator API~\cite{GNUallocAPI}.
1028
1029
1030\subsection{llheap}
1031
1032The primary design objective for llheap is low-latency across all allocator calls independent of application access-patterns and/or number of threads, \ie very seldom does the allocator have a delay during an allocator call.
1033Excluded from the low-latency objective are (large) allocations requiring initialization, \eg zero fill, and/or data copying, which are outside the allocator's purview.
1034A direct consequence of this objective is very simple or no storage coalescing;
1035hence, llheap's design is willing to use more storage to lower latency.
1036This objective is apropos because systems research and industrial applications are striving for low latency and computers have huge amounts of RAM memory.
1037Finally, llheap's performance should be comparable with the current best allocators, both in space and time (see performance comparison in Section~\ref{c:Performance}).
1038
1039% The objective of llheap's new design was to fulfill following requirements:
1040% \begin{itemize}
1041% \item It should be concurrent and thread-safe for multi-threaded programs.
1042% \item It should avoid global locks, on resources shared across all threads, as much as possible.
1043% \item It's performance (FIX ME: cite performance benchmarks) should be comparable to the commonly used allocators (FIX ME: cite common allocators).
1044% \item It should be a lightweight memory allocator.
1045% \end{itemize}
1046
1047%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1048
1049\subsection{Design Choices}
1050
1051% Some of the rejected designs are discussed because they show the path to the final design (see discussion in Section~\ref{s:MultipleHeaps}).
1052% Note, a few simple tests for a design choice were compared with the current best allocators to determine the viability of a design.
1053
1054
1055% \paragraph{T:1 model}
1056% Figure~\ref{f:T1SharedBuckets} shows one heap accessed by multiple kernel threads (KTs) using a bucket array, where smaller bucket sizes are shared among N KTs.
1057% This design leverages the fact that usually the allocation requests are less than 1024 bytes and there are only a few different request sizes.
1058% When KTs $\le$ N, the common bucket sizes are uncontented;
1059% when KTs $>$ N, the free buckets are contented and latency increases significantly.
1060% In all cases, a KT must acquire/release a lock, contented or uncontented, along the fast allocation path because a bucket is shared.
1061% Therefore, while threads are contending for a small number of buckets sizes, the buckets are distributed among them to reduce contention, which lowers latency;
1062% however, picking N is workload specific.
1063%
1064% \begin{figure}
1065% \centering
1066% \input{AllocDS1}
1067% \caption{T:1 with Shared Buckets}
1068% \label{f:T1SharedBuckets}
1069% \end{figure}
1070%
1071% Problems:
1072% \begin{itemize}
1073% \item
1074% Need to know when a KT is created/destroyed to assign/unassign a shared bucket-number from the memory allocator.
1075% \item
1076% When no thread is assigned a bucket number, its free storage is unavailable.
1077% \item
1078% All KTs contend for the global-pool lock for initial allocations, before free-lists get populated.
1079% \end{itemize}
1080% Tests showed having locks along the allocation fast-path produced a significant increase in allocation costs and any contention among KTs produces a significant spike in latency.
1081
1082% \paragraph{T:H model}
1083% Figure~\ref{f:THSharedHeaps} shows a fixed number of heaps (N), each a local free pool, where the heaps are sharded (distributed) across the KTs.
1084% A KT can point directly to its assigned heap or indirectly through the corresponding heap bucket.
1085% When KT $\le$ N, the heaps might be uncontented;
1086% when KTs $>$ N, the heaps are contented.
1087% In all cases, a KT must acquire/release a lock, contented or uncontented along the fast allocation path because a heap is shared.
1088% By increasing N, this approach reduces contention but increases storage (time versus space);
1089% however, picking N is workload specific.
1090%
1091% \begin{figure}
1092% \centering
1093% \input{AllocDS2}
1094% \caption{T:H with Shared Heaps}
1095% \label{f:THSharedHeaps}
1096% \end{figure}
1097%
1098% Problems:
1099% \begin{itemize}
1100% \item
1101% Need to know when a KT is created/destroyed to assign/unassign a heap from the memory allocator.
1102% \item
1103% When no thread is assigned to a heap, its free storage is unavailable.
1104% \item
1105% Ownership issues arise (see Section~\ref{s:Ownership}).
1106% \item
1107% All KTs contend for the local/global-pool lock for initial allocations, before free-lists get populated.
1108% \end{itemize}
1109% Tests showed having locks along the allocation fast-path produced a significant increase in allocation costs and any contention among KTs produces a significant spike in latency.
1110
1111% \paragraph{T:H model, H = number of CPUs}
1112% This design is the T:H model but H is set to the number of CPUs on the computer or the number restricted to an application, \eg via @taskset@.
1113% (See Figure~\ref{f:THSharedHeaps} but with a heap bucket per CPU.)
1114% Hence, each CPU logically has its own private heap and local pool.
1115% A memory operation is serviced from the heap associated with the CPU executing the operation.
1116% This approach removes fastpath locking and contention, regardless of the number of KTs mapped across the CPUs, because only one KT is running on each CPU at a time (modulo operations on the global pool and ownership).
1117% This approach is essentially an M:N approach where M is the number if KTs and N is the number of CPUs.
1118%
1119% Problems:
1120% \begin{itemize}
1121% \item
1122% Need to know when a CPU is added/removed from the @taskset@.
1123% \item
1124% Need a fast way to determine the CPU a KT is executing on to access the appropriate heap.
1125% \item
1126% Need to prevent preemption during a dynamic memory operation because of the \newterm{serially-reusable problem}.
1127% \begin{quote}
1128% A sequence of code that is guaranteed to run to completion before being invoked to accept another input is called serially-reusable code.~\cite{SeriallyReusable}\label{p:SeriallyReusable}
1129% \end{quote}
1130% If a KT is preempted during an allocation operation, the OS can schedule another KT on the same CPU, which can begin an allocation operation before the previous operation associated with this CPU has completed, invalidating heap correctness.
1131% Note, the serially-reusable problem can occur in sequential programs with preemption, if the signal handler calls the preempted function, unless the function is serially reusable.
1132% Essentially, the serially-reusable problem is a race condition on an unprotected critical subsection, where the OS is providing the second thread via the signal handler.
1133%
1134% Library @librseq@~\cite{librseq} was used to perform a fast determination of the CPU and to ensure all memory operations complete on one CPU using @librseq@'s restartable sequences, which restart the critical subsection after undoing its writes, if the critical subsection is preempted.
1135% \end{itemize}
1136% Tests showed that @librseq@ can determine the particular CPU quickly but setting up the restartable critical-subsection along the allocation fast-path produced a significant increase in allocation costs.
1137% Also, the number of undoable writes in @librseq@ is limited and restartable sequences cannot deal with user-level thread (UT) migration across KTs.
1138% For example, UT$_1$ is executing a memory operation by KT$_1$ on CPU$_1$ and a time-slice preemption occurs.
1139% The signal handler context switches UT$_1$ onto the user-level ready-queue and starts running UT$_2$ on KT$_1$, which immediately calls a memory operation.
1140% Since KT$_1$ is still executing on CPU$_1$, @librseq@ takes no action because it assumes KT$_1$ is still executing the same critical subsection.
1141% Then UT$_1$ is scheduled onto KT$_2$ by the user-level scheduler, and its memory operation continues in parallel with UT$_2$ using references into the heap associated with CPU$_1$, which corrupts CPU$_1$'s heap.
1142% If @librseq@ had an @rseq_abort@ which:
1143% \begin{enumerate}
1144% \item
1145% Marked the current restartable critical-subsection as cancelled so it restarts when attempting to commit.
1146% \item
1147% Do nothing if there is no current restartable critical subsection in progress.
1148% \end{enumerate}
1149% Then @rseq_abort@ could be called on the backside of a  user-level context-switching.
1150% A feature similar to this idea might exist for hardware transactional-memory.
1151% A significant effort was made to make this approach work but its complexity, lack of robustness, and performance costs resulted in its rejection.
1152
1153% \subsubsection{Allocation Fastpath}
1154% \label{s:AllocationFastpath}
1155
1156llheap's design was reviewed and changed multiple times during its development, with the final choices are discussed here.
1157(See~\cite{Zulfiqar22} for a discussion of alternate choices and reasons for rejecting them.)
1158All designs were analyzed for the allocation/free \newterm{fastpath}, \ie when an allocation can immediately return free storage or returned storage is not coalesced.
1159The heap model chosen is 1:1, which is the T:H model with T = H, where there is one thread-local heap for each KT.
1160(See Figure~\ref{f:THSharedHeaps} but with a heap bucket per KT and no bucket or local-pool lock.)
1161Hence, immediately after a KT starts, its heap is created and just before a KT terminates, its heap is (logically) deleted.
1162Heaps are uncontended for a KTs memory operations as every KT has its own thread-local heap, modulo operations on the global pool and ownership.
1163
1164Problems:
1165\begin{itemize}[topsep=3pt,itemsep=2pt,parsep=0pt]
1166\item
1167Need to know when a KT starts/terminates to create/delete its heap.
1168
1169\noindent
1170It is possible to leverage constructors/destructors for thread-local objects to get a general handle on when a KT starts/terminates.
1171\item
1172There is a classic \newterm{memory-reclamation} problem for ownership because storage passed to another thread can be returned to a terminated heap.
1173
1174\noindent
1175The classic solution only deletes a heap after all referents are returned, which is complex.
1176The cheap alternative is for heaps to persist for program duration to handle outstanding referent frees.
1177If old referents return storage to a terminated heap, it is handled in the same way as an active heap.
1178To prevent heap blowup, terminated heaps can be reused by new KTs, where a reused heap may be populated with free storage from a prior KT (external fragmentation).
1179In most cases, heap blowup is not a problem because programs have a small allocation set-size, so the free storage from a prior KT is apropos for a new KT.
1180\item
1181There can be significant external fragmentation as the number of KTs increases.
1182
1183\noindent
1184In many concurrent applications, good performance is achieved with the number of KTs proportional to the number of CPUs.
1185Since the number of CPUs is relatively small, and a heap is also relatively small, $\approx$10K bytes (not including any associated freed storage), the worst-case external fragmentation is still small compared to the RAM available on large servers with many CPUs.
1186\item
1187Need to prevent preemption during a dynamic memory operation because of the \newterm{serially-reusable problem}.
1188\begin{quote}
1189A sequence of code that is guaranteed to run to completion before being invoked to accept another input is called serially-reusable code.~\cite{SeriallyReusable}\label{p:SeriallyReusable}
1190\end{quote}
1191If a KT is preempted during an allocation operation, the OS can schedule another KT on the same CPU, which can begin an allocation operation before the previous operation associated with this CPU has completed, invalidating heap correctness.
1192Note, the serially-reusable problem can occur in sequential programs with preemption, if the signal handler calls the preempted function, unless the function is serially reusable.
1193Essentially, the serially-reusable problem is a race condition on an unprotected critical subsection, where the OS is providing the second thread via the signal handler.
1194
1195Library @librseq@~\cite{librseq} was used to perform a fast determination of the CPU and to ensure all memory operations complete on one CPU using @librseq@'s restartable sequences, which restart the critical subsection after undoing its writes, if the critical subsection is preempted.
1196
1197%There is the same serially-reusable problem with UTs migrating across KTs.
1198\end{itemize}
1199Tests showed this design produced the closest performance match with the best current allocators, and code inspection showed most of these allocators use different variations of this approach.
1200
1201
1202\vspace{5pt}
1203\noindent
1204The conclusion from this design exercise is: any atomic fence, atomic instruction (lock free), or lock along the allocation fastpath produces significant slowdown.
1205For the T:1 and T:H models, locking must exist along the allocation fastpath because the buckets or heaps might be shared by multiple threads, even when KTs $\le$ N.
1206For the T:H=CPU and 1:1 models, locking is eliminated along the allocation fastpath.
1207However, T:H=CPU has poor operating-system support to determine the CPU id (heap id) and prevent the serially-reusable problem for KTs.
1208More OS support is required to make this model viable, but there is still the serially-reusable problem with user-level threading.
1209So the 1:1 model had no atomic actions along the fastpath and no special operating-system support requirements.
1210The 1:1 model still has the serially-reusable problem with user-level threading, which is addressed in Section~\ref{s:UserlevelThreadingSupport}, and the greatest potential for heap blowup for certain allocation patterns.
1211
1212
1213% \begin{itemize}
1214% \item
1215% A decentralized design is better to centralized design because their concurrency is better across all bucket-sizes as design 1 shards a few buckets of selected sizes while other designs shards all the buckets. Decentralized designs shard the whole heap which has all the buckets with the addition of sharding @sbrk@ area. So Design 1 was eliminated.
1216% \item
1217% Design 2 was eliminated because it has a possibility of contention in-case of KT > N while Design 3 and 4 have no contention in any scenario.
1218% \item
1219% Design 3 was eliminated because it was slower than Design 4 and it provided no way to achieve user-threading safety using librseq. We had to use CFA interruption handling to achieve user-threading safety which has some cost to it.
1220% that  because of 4 was already slower than Design 3, adding cost of interruption handling on top of that would have made it even slower.
1221% \end{itemize}
1222% Of the four designs for a low-latency memory allocator, the 1:1 model was chosen for the following reasons:
1223
1224% \subsubsection{Advantages of distributed design}
1225%
1226% The distributed design of llheap is concurrent to work in multi-threaded applications.
1227% Some key benefits of the distributed design of llheap are as follows:
1228% \begin{itemize}
1229% \item
1230% The bump allocation is concurrent as memory taken from @sbrk@ is sharded across all heaps as bump allocation reserve. The call to @sbrk@ will be protected using locks but bump allocation (on memory taken from @sbrk@) will not be contended once the @sbrk@ call has returned.
1231% \item
1232% Low or almost no contention on heap resources.
1233% \item
1234% It is possible to use sharing and stealing techniques to share/find unused storage, when a free list is unused or empty.
1235% \item
1236% Distributed design avoids unnecessary locks on resources shared across all KTs.
1237% \end{itemize}
1238
1239\subsubsection{Allocation Latency}
1240
1241A primary goal of llheap is low latency, hence the name low-latency heap (llheap).
1242Two forms of latency are internal and external.
1243Internal latency is the time to perform an allocation, while external latency is time to obtain/return storage from/to the OS.
1244Ideally latency is $O(1)$ with a small constant.
1245
1246To obtain $O(1)$ internal latency means no searching on the allocation fastpath and largely prohibits coalescing, which leads to external fragmentation.
1247The mitigating factor is that most programs have well behaved allocation patterns, where the majority of allocation operations can be $O(1)$, and heap blowup does not occur without coalescing (although the allocation footprint may be slightly larger).
1248
1249To obtain $O(1)$ external latency means obtaining one large storage area from the OS and subdividing it across all program allocations, which requires a good guess at the program storage high-watermark and potential large external fragmentation.
1250Excluding real-time operating-systems, operating-system operations are unbounded, and hence some external latency is unavoidable.
1251The mitigating factor is that operating-system calls can often be reduced if a programmer has a sense of the storage high-watermark and the allocator is capable of using this information (see @malloc_expansion@ \pageref{p:malloc_expansion}).
1252Furthermore, while operating-system calls are unbounded, many are now reasonably fast, so their latency is tolerable and infrequent.
1253
1254
1255%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1256
1257\subsection{llheap Structure}
1258
1259Figure~\ref{f:llheapStructure} shows the design of llheap, which uses the following features:
12601:1 multiple-heap model to minimize the fastpath,
1261can be built with or without heap ownership,
1262headers per allocation versus containers,
1263no coalescing to minimize latency,
1264global heap memory (pool) obtained from the OS using @mmap@ to create and reuse heaps needed by threads,
1265local reserved memory (pool) per heap obtained from global pool,
1266global reserved memory (pool) obtained from the OS using @sbrk@ call,
1267optional fast-lookup table for converting allocation requests into bucket sizes,
1268optional statistic-counters table for accumulating counts of allocation operations.
1269
1270\begin{figure}
1271\centering
1272% \includegraphics[width=0.65\textwidth]{figures/NewHeapStructure.eps}
1273\input{llheap}
1274\caption{llheap Structure}
1275\label{f:llheapStructure}
1276\end{figure}
1277
1278llheap starts by creating an array of $N$ global heaps from storage obtained using @mmap@, where $N$ is the number of computer cores, that persists for program duration.
1279There is a global bump-pointer to the next free heap in the array.
1280When this array is exhausted, another array of heaps is allocated.
1281There is a global top pointer for a intrusive linked-list to chain free heaps from terminated threads.
1282When statistics are turned on, there is a global top pointer for a intrusive linked-list to chain \emph{all} the heaps, which is traversed to accumulate statistics counters across heaps using @malloc_stats@.
1283
1284When a KT starts, a heap is allocated from the current array for exclusive use by the KT.
1285When a KT terminates, its heap is chained onto the heap free-list for reuse by a new KT, which prevents unbounded growth of number of heaps.
1286The free heaps are stored on stack so hot storage is reused first.
1287Preserving all heaps, created during the program lifetime, solves the storage lifetime problem when ownership is used.
1288This approach wastes storage if a large number of KTs are created/terminated at program start and then the program continues sequentially.
1289llheap can be configured with object ownership, where an object is freed to the heap from which it is allocated, or object no-ownership, where an object is freed to the KT's current heap.
1290
1291Each heap uses segregated free-buckets that have free objects distributed across 91 different sizes from 16 to 4M.
1292All objects in a bucket are of the same size.
1293The number of buckets used is determined dynamically depending on the crossover point from @sbrk@ to @mmap@ allocation using @mallopt( M_MMAP_THRESHOLD )@, \ie small objects managed by the program and large objects managed by the OS.
1294Each free bucket of a specific size has two lists.
12951) A free stack used solely by the KT heap-owner, so push/pop operations do not require locking.
1296The free objects are a stack so hot storage is reused first.
12972) For ownership, a shared away-stack for KTs to return storage allocated by other KTs, so push/pop operations require locking.
1298When the free stack is empty, the entire ownership stack is removed and becomes the head of the corresponding free stack.
1299
1300Algorithm~\ref{alg:heapObjectAlloc} shows the allocation outline for an object of size $S$.
1301First, the allocation is divided into small (@sbrk@) or large (@mmap@).
1302For large allocations, the storage is mapped directly from the OS.
1303For small allocations, $S$ is quantized into a bucket size.
1304Quantizing is performed using a binary search over the ordered bucket array.
1305An optional optimization is fast lookup $O(1)$ for sizes < 64K from a 64K array of type @char@, where each element has an index to the corresponding bucket.
1306The @char@ type restricts the number of bucket sizes to 256.
1307For $S$ > 64K, a binary search is used.
1308Then, the allocation storage is obtained from the following locations (in order), with increasing latency:
1309bucket's free stack,
1310bucket's away stack,
1311heap's local pool,
1312global pool,
1313OS (@sbrk@).
1314
1315\begin{algorithm}
1316\caption{Dynamic object allocation of size $S$}\label{alg:heapObjectAlloc}
1317\begin{algorithmic}[1]
1318\State $\textit{O} \gets \text{NULL}$
1319\If {$S >= \textit{mmap-threshhold}$}
1320        \State $\textit{O} \gets \text{allocate dynamic memory using system call mmap with size S}$
1321\Else
1322        \State $\textit{B} \gets \text{smallest free-bucket} \geq S$
1323        \If {$\textit{B's free-list is empty}$}
1324                \If {$\textit{B's away-list is empty}$}
1325                        \If {$\textit{heap's allocation buffer} < S$}
1326                                \State $\text{get allocation from global pool (which might call \lstinline{sbrk})}$
1327                        \EndIf
1328                        \State $\textit{O} \gets \text{bump allocate an object of size S from allocation buffer}$
1329                \Else
1330                        \State $\textit{merge B's away-list into free-list}$
1331                        \State $\textit{O} \gets \text{pop an object from B's free-list}$
1332                \EndIf
1333        \Else
1334                \State $\textit{O} \gets \text{pop an object from B's free-list}$
1335        \EndIf
1336        \State $\textit{O's owner} \gets \text{B}$
1337\EndIf
1338\State $\Return \textit{ O}$
1339\end{algorithmic}
1340\end{algorithm}
1341
1342\begin{algorithm}
1343\caption{Dynamic object free at address $A$ with object ownership}\label{alg:heapObjectFreeOwn}
1344\begin{algorithmic}[1]
1345\If {$\textit{A mapped allocation}$}
1346        \State $\text{return A's dynamic memory to system using system call \lstinline{munmap}}$
1347\Else
1348        \State $\text{B} \gets \textit{O's owner}$
1349        \If {$\textit{B is thread-local heap's bucket}$}
1350                \State $\text{push A to B's free-list}$
1351        \Else
1352                \State $\text{push A to B's away-list}$
1353        \EndIf
1354\EndIf
1355\end{algorithmic}
1356\end{algorithm}
1357
1358\begin{algorithm}
1359\caption{Dynamic object free at address $A$ without object ownership}\label{alg:heapObjectFreeNoOwn}
1360\begin{algorithmic}[1]
1361\If {$\textit{A mapped allocation}$}
1362        \State $\text{return A's dynamic memory to system using system call \lstinline{munmap}}$
1363\Else
1364        \State $\text{B} \gets \textit{O's owner}$
1365        \If {$\textit{B is thread-local heap's bucket}$}
1366                \State $\text{push A to B's free-list}$
1367        \Else
1368                \State $\text{C} \gets \textit{thread local heap's bucket with same size as B}$
1369                \State $\text{push A to C's free-list}$
1370        \EndIf
1371\EndIf
1372\end{algorithmic}
1373\end{algorithm}
1374
1375
1376Algorithm~\ref{alg:heapObjectFreeOwn} shows the deallocation (free) outline for an object at address $A$ with ownership.
1377First, the address is divided into small (@sbrk@) or large (@mmap@).
1378For large allocations, the storage is unmapped back to the OS.
1379For small allocations, the bucket associated with the request size is retrieved.
1380If the bucket is local to the thread, the allocation is pushed onto the thread's associated bucket.
1381If the bucket is not local to the thread, the allocation is pushed onto the owning thread's associated away stack.
1382
1383Algorithm~\ref{alg:heapObjectFreeNoOwn} shows the deallocation (free) outline for an object at address $A$ without ownership.
1384The algorithm is the same as for ownership except if the bucket is not local to the thread.
1385Then the corresponding bucket of the owner thread is computed for the deallocating thread, and the allocation is pushed onto the deallocating thread's bucket.
1386
1387Finally, the llheap design funnels \label{p:FunnelRoutine} all allocation/deallocation operations through the @malloc@ and @free@ routines, which are the only routines to directly access and manage the internal data structures of the heap.
1388Other allocation operations, \eg @calloc@, @memalign@, and @realloc@, are composed of calls to @malloc@ and possibly @free@, and may manipulate header information after storage is allocated.
1389This design simplifies heap-management code during development and maintenance.
1390
1391
1392\subsubsection{Alignment}
1393
1394Most dynamic memory allocations have a minimum storage alignment for the contained object(s).
1395Often the minimum memory alignment, M, is the bus width (32 or 64-bit) or the largest register (double, long double) or largest atomic instruction (DCAS) or vector data (MMMX).
1396In general, the minimum storage alignment is 8/16-byte boundary on 32/64-bit computers.
1397For consistency, the object header is normally aligned at this same boundary.
1398Larger alignments must be a power of 2, such as page alignment (4/8K).
1399Any alignment request, N, $\le$ the minimum alignment is handled as a normal allocation with minimal alignment.
1400
1401For alignments greater than the minimum, the obvious approach for aligning to address @A@ is: compute the next address that is a multiple of @N@ after the current end of the heap, @E@, plus room for the header before @A@ and the size of the allocation after @A@, moving the end of the heap to @E'@.
1402\begin{center}
1403\input{Alignment1}
1404\end{center}
1405The storage between @E@ and @H@ is chained onto the appropriate free list for future allocations.
1406The same approach is used for sufficiently large free blocks, where @E@ is the start of the free block, and any unused storage before @H@ or after the allocated object becomes free storage.
1407In this approach, the aligned address @A@ is the same as the allocated storage address @P@, \ie @P@ $=$ @A@ for all allocation routines, which simplifies deallocation.
1408However, if there are a large number of aligned requests, this approach leads to memory fragmentation from the small free areas around the aligned object.
1409As well, it does not work for large allocations, where many memory allocators switch from program @sbrk@ to operating-system @mmap@.
1410The reason is that @mmap@ only starts on a page boundary, and it is difficult to reuse the storage before the alignment boundary for other requests.
1411Finally, this approach is incompatible with allocator designs that funnel allocation requests through @malloc@ as it directly manipulates management information within the allocator to optimize the space/time of a request.
1412
1413Instead, llheap alignment is accomplished by making a \emph{pessimistic} allocation request for sufficient storage to ensure that \emph{both} the alignment and size request are satisfied, \eg:
1414\begin{center}
1415\input{Alignment2}
1416\end{center}
1417The amount of storage necessary is @alignment - M + size@, which ensures there is an address, @A@, after the storage returned from @malloc@, @P@, that is a multiple of @alignment@ followed by sufficient storage for the data object.
1418The approach is pessimistic because if @P@ already has the correct alignment @N@, the initial allocation has already requested sufficient space to move to the next multiple of @N@.
1419For this special case, there is @alignment - M@ bytes of unused storage after the data object, which subsequently can be used by @realloc@.
1420
1421Note, the address returned is @A@, which is subsequently returned to @free@.
1422However, to correctly free the allocated object, the value @P@ must be computable, since that is the value generated by @malloc@ and returned within @memalign@.
1423Hence, there must be a mechanism to detect when @P@ $\neq$ @A@ and how to compute @P@ from @A@.
1424
1425The llheap approach uses two headers:
1426the \emph{original} header associated with a memory allocation from @malloc@, and a \emph{fake} header within this storage before the alignment boundary @A@, which is returned from @memalign@, e.g.:
1427\begin{center}
1428\input{Alignment2Impl}
1429\end{center}
1430Since @malloc@ has a minimum alignment of @M@, @P@ $\neq$ @A@ only holds for alignments greater than @M@.
1431When @P@ $\neq$ @A@, the minimum distance between @P@ and @A@ is @M@ bytes, due to the pessimistic storage-allocation.
1432Therefore, there is always room for an @M@-byte fake header before @A@.
1433
1434The fake header must supply an indicator to distinguish it from a normal header and the location of address @P@ generated by @malloc@.
1435This information is encoded as an offset from A to P and the initialize alignment (discussed in Section~\ref{s:ReallocStickyProperties}).
1436To distinguish a fake header from a normal header, the least-significant bit of the alignment is used because the offset participates in multiple calculations, while the alignment is just remembered data.
1437\begin{center}
1438\input{FakeHeader}
1439\end{center}
1440
1441
1442\subsubsection{\lstinline{realloc} and Sticky Properties}
1443\label{s:ReallocStickyProperties}
1444
1445The allocation routine @realloc@ provides a memory-management pattern for shrinking/enlarging an existing allocation, while maintaining some or all of the object data, rather than performing the following steps manually.
1446\begin{flushleft}
1447\begin{tabular}{ll}
1448\multicolumn{1}{c}{\textbf{realloc pattern}} & \multicolumn{1}{c}{\textbf{manually}} \\
1449\begin{lstlisting}
1450T * naddr = realloc( oaddr, newSize );
1451
1452
1453
1454\end{lstlisting}
1455&
1456\begin{lstlisting}
1457T * naddr = (T *)malloc( newSize ); $\C[2.4in]{// new storage}$
1458memcpy( naddr, addr, oldSize );  $\C{// copy old bytes}$
1459free( addr );                           $\C{// free old storage}$
1460addr = naddr;                           $\C{// change pointer}\CRT$
1461\end{lstlisting}
1462\end{tabular}
1463\end{flushleft}
1464The realloc pattern leverages available storage at the end of an allocation due to bucket sizes, possibly eliminating a new allocation and copying.
1465This pattern is not used enough to reduce storage management costs.
1466In fact, if @oaddr@ is @nullptr@, @realloc@ does a @malloc@, so even the initial @malloc@ can be a @realloc@ for consistency in the allocation pattern.
1467
1468The hidden problem for this pattern is the effect of zero fill and alignment with respect to reallocation.
1469Are these properties transient or persistent (``sticky'')?
1470For example, when memory is initially allocated by @calloc@ or @memalign@ with zero fill or alignment properties, respectively, what happens when those allocations are given to @realloc@ to change size?
1471That is, if @realloc@ logically extends storage into unused bucket space or allocates new storage to satisfy a size change, are initial allocation properties preserved?
1472Currently, allocation properties are not preserved, so subsequent use of @realloc@ storage may cause inefficient execution or errors due to lack of zero fill or alignment.
1473This silent problem is unintuitive to programmers and difficult to locate because it is transient.
1474To prevent these problems, llheap preserves initial allocation properties for the lifetime of an allocation and the semantics of @realloc@ are augmented to preserve these properties, with additional query routines.
1475This change makes the realloc pattern efficient and safe.
1476
1477
1478\subsubsection{Header}
1479
1480To preserve allocation properties requires storing additional information with an allocation,
1481The best available option is the header, where Figure~\ref{f:llheapNormalHeader} shows the llheap storage layout.
1482The header has two data field sized appropriately for 32/64-bit alignment requirements.
1483The first field is a union of three values:
1484\begin{description}
1485\item[bucket pointer]
1486is for allocated storage and points back to the bucket associated with this storage requests (see Figure~\ref{f:llheapStructure} for the fields accessible in a bucket).
1487\item[mapped size]
1488is for mapped storage and is the storage size for use in unmapping.
1489\item[next free block]
1490is for free storage and is an intrusive pointer chaining same-size free blocks onto a bucket's free stack.
1491\end{description}
1492The second field remembers the request size versus the allocation (bucket) size, \eg request 42 bytes which is rounded up to 64 bytes.
1493Since programmers think in request sizes rather than allocation sizes, the request size allows better generation of statistics or errors and also helps in memory management.
1494
1495\begin{figure}
1496\centering
1497\input{Header}
1498\caption{llheap Normal Header}
1499\label{f:llheapNormalHeader}
1500\end{figure}
1501
1502The low-order 3-bits of the first field are \emph{unused} for any stored values as these values are 16-byte aligned by default, whereas the second field may use all of its bits.
1503The 3 unused bits are used to represent mapped allocation, zero filled, and alignment, respectively.
1504Note, the alignment bit is not used in the normal header and the zero-filled/mapped bits are not used in the fake header.
1505This implementation allows a fast test if any of the lower 3-bits are on (@&@ and compare).
1506If no bits are on, it implies a basic allocation, which is handled quickly;
1507otherwise, the bits are analysed and appropriate actions are taken for the complex cases.
1508Since most allocations are basic, they will take significantly less time as the memory operations will be done along the allocation and free fastpath.
1509
1510
1511\subsection{Statistics and Debugging}
1512
1513llheap can be built to accumulate fast and largely contention-free allocation statistics to help understand allocation behaviour.
1514Incrementing statistic counters must appear on the allocation fastpath.
1515As noted, any atomic operation along the fastpath produces a significant increase in allocation costs.
1516To make statistics performant enough for use on running systems, each heap has its own set of statistic counters, so heap operations do not require atomic operations.
1517
1518To locate all statistic counters, heaps are linked together in statistics mode, and this list is locked and traversed to sum all counters across heaps.
1519Note, the list is locked to prevent errors traversing an active list;
1520the statistics counters are not locked and can flicker during accumulation.
1521Figure~\ref{f:StatiticsOutput} shows an example of statistics output, which covers all allocation operations and information about deallocating storage not owned by a thread.
1522No other memory allocator studied provides as comprehensive statistical information.
1523Finally, these statistics were invaluable during the development of this work for debugging and verifying correctness and should be equally valuable to application developers.
1524
1525\begin{figure}
1526\begin{lstlisting}
1527Heap statistics: (storage request / allocation)
1528  malloc >0 calls 2,766; 0 calls 2,064; storage 12,715 / 13,367 bytes
1529  aalloc >0 calls 0; 0 calls 0; storage 0 / 0 bytes
1530  calloc >0 calls 6; 0 calls 0; storage 1,008 / 1,104 bytes
1531  memalign >0 calls 0; 0 calls 0; storage 0 / 0 bytes
1532  amemalign >0 calls 0; 0 calls 0; storage 0 / 0 bytes
1533  cmemalign >0 calls 0; 0 calls 0; storage 0 / 0 bytes
1534  resize >0 calls 0; 0 calls 0; storage 0 / 0 bytes
1535  realloc >0 calls 0; 0 calls 0; storage 0 / 0 bytes
1536  free !null calls 2,766; null calls 4,064; storage 12,715 / 13,367 bytes
1537  away pulls 0; pushes 0; storage 0 / 0 bytes
1538  sbrk calls 1; storage 10,485,760 bytes
1539  mmap calls 10,000; storage 10,000 / 10,035 bytes
1540  munmap calls 10,000; storage 10,000 / 10,035 bytes
1541  threads started 4; exited 3
1542  heaps new 4; reused 0
1543\end{lstlisting}
1544\caption{Statistics Output}
1545\label{f:StatiticsOutput}
1546\end{figure}
1547
1548llheap can also be built with debug checking, which inserts many asserts along all allocation paths.
1549These assertions detect incorrect allocation usage, like double frees, unfreed storage, or memory corruptions because internal values (like header fields) are overwritten.
1550These checks are best effort as opposed to complete allocation checking as in @valgrind@.
1551Nevertheless, the checks detect many allocation problems.
1552There is an unfortunate problem in detecting unfreed storage because some library routines assume their allocations have life-time duration, and hence, do not free their storage.
1553For example, @printf@ allocates a 1024-byte buffer on the first call and never deletes this buffer.
1554To prevent a false positive for unfreed storage, it is possible to specify an amount of storage that is never freed (see @malloc_unfreed@ \pageref{p:malloc_unfreed}), and it is subtracted from the total allocate/free difference.
1555Determining the amount of never-freed storage is annoying, but once done, any warnings of unfreed storage are application related.
1556
1557Tests indicate only a 30\% performance decrease when statistics \emph{and} debugging are enabled, and the latency cost for accumulating statistic is mitigated by limited calls, often only one at the end of the program.
1558
1559
1560\subsection{User-level Threading Support}
1561\label{s:UserlevelThreadingSupport}
1562
1563The serially-reusable problem (see \pageref{p:SeriallyReusable}) occurs for kernel threads in the ``T:H model, H = number of CPUs'' model and for user threads in the ``1:1'' model, where llheap uses the ``1:1'' model.
1564The solution is to prevent interrupts that can result in a CPU or KT change during operations that are logically critical subsections such as starting a memory operation on one KT and completing it on another.
1565Locking these critical subsections negates any attempt for a quick fastpath and results in high contention.
1566For user-level threading, the serially-reusable problem appears with time slicing for preemptable scheduling, as the signal handler context switches to another user-level thread.
1567Without time slicing, a user thread performing a long computation can prevent the execution of (starve) other threads.
1568To prevent starvation for a memory-allocation-intensive thread, \ie the time slice always triggers in an allocation critical-subsection for one thread so the thread never gets time sliced, a thread-local \newterm{rollforward} flag is set in the signal handler when it aborts a time slice.
1569The rollforward flag is tested at the end of each allocation funnel routine (see \pageref{p:FunnelRoutine}), and if set, it is reset and a volunteer yield (context switch) is performed to allow other threads to execute.
1570
1571llheap uses two techniques to detect when execution is in an allocation operation or routine called from allocation operation, to abort any time slice during this period.
1572On the slowpath when executing expensive operations, like @sbrk@ or @mmap@, interrupts are disabled/enabled by setting kernel-thread-local flags so the signal handler aborts immediately.
1573On the fastpath, disabling/enabling interrupts is too expensive as accessing kernel-thread-local storage can be expensive and not user-thread-safe.
1574For example, the ARM processor stores the thread-local pointer in a coprocessor register that cannot perform atomic base-displacement addressing.
1575Hence, there is a window between loading the kernel-thread-local pointer from the coprocessor register into a normal register and adding the displacement when a time slice can move a thread.
1576
1577The fast technique (with lower run time cost) is to define a special code subsection and places all non-interruptible routines in this subsection.
1578The linker places all code in this subsection into a contiguous block of memory, but the order of routines within the block is unspecified.
1579Then, the signal handler compares the program counter at the point of interrupt with the the start and end address of the non-interruptible subsection, and aborts if executing within this subsection and sets the rollforward flag.
1580This technique is fragile because any calls in the non-interruptible code outside of the non-interruptible subsection (like @sbrk@) must be bracketed with disable/enable interrupts and these calls must be along the slowpath.
1581Hence, for correctness, this approach requires inspection of generated assembler code for routines placed in the non-interruptible subsection.
1582This issue is mitigated by the llheap funnel design so only funnel routines and a few statistics routines are placed in the non-interruptible subsection and their assembler code examined.
1583These techniques are used in both the \uC and \CFA versions of llheap as both of these systems have user-level threading.
1584
1585
1586\subsection{Bootstrapping}
1587
1588There are problems bootstrapping a memory allocator.
1589\begin{enumerate}
1590\item
1591Programs can be statically or dynamically linked.
1592\item
1593The order in which the linker schedules startup code is poorly supported so it cannot be controlled entirely.
1594\item
1595Knowing a KT's start and end independently from the KT code is difficult.
1596\end{enumerate}
1597
1598For static linking, the allocator is loaded with the program.
1599Hence, allocation calls immediately invoke the allocator operation defined by the loaded allocation library and there is only one memory allocator used in the program.
1600This approach allows allocator substitution by placing an allocation library before any other in the linked/load path.
1601
1602Allocator substitution is similar for dynamic linking, but the problem is that the dynamic loader starts first and needs to perform dynamic allocations \emph{before} the substitution allocator is loaded.
1603As a result, the dynamic loader uses a default allocator until the substitution allocator is loaded, after which all allocation operations are handled by the substitution allocator, including from the dynamic loader.
1604Hence, some part of the @sbrk@ area may be used by the default allocator and statistics about allocation operations cannot be correct.
1605Furthermore, dynamic linking goes through trampolines, so there is an additional cost along the allocator fastpath for all allocation operations.
1606Testing showed up to a 5\% performance decrease with dynamic linking as compared to static linking, even when using @tls_model("initial-exec")@ so the dynamic loader can obtain tighter binding.
1607
1608All allocator libraries need to perform startup code to initialize data structures, such as the heap array for llheap.
1609The problem is getting initialization done before the first allocator call.
1610However, there does not seem to be mechanism to tell either the static or dynamic loader to first perform initialization code before any calls to a loaded library.
1611Also, initialization code of other libraries and the run-time environment may call memory allocation routines such as \lstinline{malloc}.
1612This compounds the situation as there is no mechanism to tell either the static or dynamic loader to first perform the initialization code of the memory allocator before any other initialization that may involve a dynamic memory allocation call.
1613As a result, calls to allocation routines occur without initialization.
1614To deal with this problem, it is necessary to put a conditional initialization check along the allocation fastpath to trigger initialization (singleton pattern).
1615
1616Two other important execution points are program startup and termination, which include prologue or epilogue code to bootstrap a program, which programmers are unaware of.
1617For example, dynamic-memory allocations before/after the application starts should not be considered in statistics because the application does not make these calls.
1618llheap establishes these two points using routines:
1619\begin{lstlisting}
1620__attribute__(( constructor( 100 ) )) static void startup( void ) {
1621        // clear statistic counters
1622        // reset allocUnfreed counter
1623}
1624__attribute__(( destructor( 100 ) )) static void shutdown( void ) {
1625        // sum allocUnfreed for all heaps
1626        // subtract global unfreed storage
1627        // if allocUnfreed > 0 then print warning message
1628}
1629\end{lstlisting}
1630which use global constructor/destructor priority 100, where the linker calls these routines at program prologue/epilogue in increasing/decreasing order of priority.
1631Application programs may only use global constructor/destructor priorities greater than 100.
1632Hence, @startup@ is called after the program prologue but before the application starts, and @shutdown@ is called after the program terminates but before the program epilogue.
1633By resetting counters in @startup@, prologue allocations are ignored, and checking unfreed storage in @shutdown@ checks only application memory management, ignoring the program epilogue.
1634
1635While @startup@/@shutdown@ apply to the program KT, a concurrent program creates additional KTs that do not trigger these routines.
1636However, it is essential for the allocator to know when each KT is started/terminated.
1637One approach is to create a thread-local object with a construct/destructor, which is triggered after a new KT starts and before it terminates, respectively.
1638\begin{lstlisting}
1639struct ThreadManager {
1640        volatile bool pgm_thread;
1641        ThreadManager() {} // unusable
1642        ~ThreadManager() { if ( pgm_thread ) heapManagerDtor(); }
1643};
1644static thread_local ThreadManager threadManager;
1645\end{lstlisting}
1646Unfortunately, thread-local variables are created lazily, \ie on the first dereference of @threadManager@, which then triggers its constructor.
1647Therefore, the constructor is useless for knowing when a KT starts because the KT must reference it, and the allocator does not control the application KT.
1648Fortunately, the singleton pattern needed for initializing the program KT also triggers KT allocator initialization, which can then reference @pgm_thread@ to call @threadManager@'s constructor, otherwise its destructor is not called.
1649Now when a KT terminates, @~ThreadManager@ is called to chain it onto the global-heap free-stack, where @pgm_thread@ is set to true only for the program KT.
1650The conditional destructor call prevents closing down the program heap, which must remain available because epilogue code may free more storage.
1651
1652Finally, there is a recursive problem when the singleton pattern dereferences @pgm_thread@ to initialize the thread-local object, because its initialization calls @atExit@, which immediately calls @malloc@ to obtain storage.
1653This recursion is handled with another thread-local flag to prevent double initialization.
1654A similar problem exists when the KT terminates and calls member @~ThreadManager@, because immediately afterwards, the terminating KT calls @free@ to deallocate the storage obtained from the @atExit@.
1655In the meantime, the terminated heap has been put on the global-heap free-stack, and may be active by a new KT, so the @atExit@ free is handled as a free to another heap and put onto the away list using locking.
1656
1657For user threading systems, the KTs are controlled by the runtime, and hence, start/end pointers are known and interact directly with the llheap allocator for \uC and \CFA, which eliminates or simplifies several of these problems.
1658The following API was created to provide interaction between the language runtime and the allocator.
1659\begin{lstlisting}
1660void startThread();                     $\C{// KT starts}$
1661void finishThread();                    $\C{// KT ends}$
1662void startup();                         $\C{// when application code starts}$
1663void shutdown();                        $\C{// when application code ends}$
1664bool traceHeap();                       $\C{// enable allocation/free printing for debugging}$
1665bool traceHeapOn();                     $\C{// start printing allocation/free calls}$
1666bool traceHeapOff();                    $\C{// stop printing allocation/free calls}$
1667\end{lstlisting}
1668This kind of API is necessary to allow concurrent runtime systems to interact with different memory allocators in a consistent way.
1669
1670%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1671
1672\subsection{Added Features and Methods}
1673
1674The C dynamic-allocation API (see Figure~\ref{f:CDynamicAllocationAPI}) is neither orthogonal nor complete.
1675For example,
1676\begin{itemize}
1677\item
1678It is possible to zero fill or align an allocation but not both.
1679\item
1680It is \emph{only} possible to zero fill an array allocation.
1681\item
1682It is not possible to resize a memory allocation without data copying.
1683\item
1684@realloc@ does not preserve initial allocation properties.
1685\end{itemize}
1686As a result, programmers must provide these options, which is error prone, resulting in blaming the entire programming language for a poor dynamic-allocation API.
1687Furthermore, newer programming languages have better type systems that can provide safer and more powerful APIs for memory allocation.
1688
1689\begin{figure}
1690\begin{lstlisting}
1691void * malloc( size_t size );
1692void * calloc( size_t nmemb, size_t size );
1693void * realloc( void * ptr, size_t size );
1694void * reallocarray( void * ptr, size_t nmemb, size_t size );
1695void free( void * ptr );
1696void * memalign( size_t alignment, size_t size );
1697void * aligned_alloc( size_t alignment, size_t size );
1698int posix_memalign( void ** memptr, size_t alignment, size_t size );
1699void * valloc( size_t size );
1700void * pvalloc( size_t size );
1701
1702struct mallinfo mallinfo( void );
1703int mallopt( int param, int val );
1704int malloc_trim( size_t pad );
1705size_t malloc_usable_size( void * ptr );
1706void malloc_stats( void );
1707int malloc_info( int options, FILE * fp );
1708\end{lstlisting}
1709\caption{C Dynamic-Allocation API}
1710\label{f:CDynamicAllocationAPI}
1711\end{figure}
1712
1713The following presents design and API changes for C, \CC (\uC), and \CFA, all of which are implemented in llheap.
1714
1715
1716\subsubsection{Out of Memory}
1717
1718Most allocators use @nullptr@ to indicate an allocation failure, specifically out of memory;
1719hence the need to return an alternate value for a zero-sized allocation.
1720A different approach allowed by @C API@ is to abort a program when out of memory and return @nullptr@ for a zero-sized allocation.
1721In theory, notifying the programmer of memory failure allows recovery;
1722in practice, it is almost impossible to gracefully recover when out of memory.
1723Hence, the cheaper approach of returning @nullptr@ for a zero-sized allocation is chosen because no pseudo allocation is necessary.
1724
1725
1726\subsubsection{C Interface}
1727
1728For C, it is possible to increase functionality and orthogonality of the dynamic-memory API to make allocation better for programmers.
1729
1730For existing C allocation routines:
1731\begin{itemize}[topsep=3pt,itemsep=2pt,parsep=0pt]
1732\item
1733@calloc@ sets the sticky zero-fill property.
1734\item
1735@memalign@, @aligned_alloc@, @posix_memalign@, @valloc@ and @pvalloc@ set the sticky alignment property.
1736\item
1737@realloc@ and @reallocarray@ preserve sticky properties.
1738\end{itemize}
1739
1740The C dynamic-memory API is extended with the following routines:
1741
1742\medskip\noindent
1743\lstinline{void * aalloc( size_t dim, size_t elemSize )}
1744extends @calloc@ for allocating a dynamic array of objects with total size @dim@ $\times$ @elemSize@ but \emph{without} zero-filling the memory.
1745@aalloc@ is significantly faster than @calloc@, which is the only alternative given by the standard memory-allocation routines for array allocation.
1746It returns the address of the dynamic array or @NULL@ if either @dim@ or @elemSize@ are zero.
1747
1748\medskip\noindent
1749\lstinline{void * resize( void * oaddr, size_t size )}
1750extends @realloc@ for resizing an existing allocation, @oaddr@, to the new @size@ (smaller or larger than previous) \emph{without} copying previous data into the new allocation or preserving sticky properties.
1751@resize@ is significantly faster than @realloc@, which is the only alternative.
1752It returns the address of the old or new storage with the specified new size or @NULL@ if @size@ is zero.
1753
1754\medskip\noindent
1755\lstinline{void * amemalign( size_t alignment, size_t dim, size_t elemSize )}
1756extends @aalloc@ and @memalign@ for allocating a dynamic array of objects with the starting address on the @alignment@ boundary.
1757Sets sticky alignment property.
1758It returns the address of the aligned dynamic-array or @NULL@ if either @dim@ or @elemSize@ are zero.
1759
1760\medskip\noindent
1761\lstinline{void * cmemalign( size_t alignment, size_t dim, size_t elemSize )}
1762extends @amemalign@ with zero fill and has the same usage as @amemalign@.
1763Sets sticky zero-fill and alignment property.
1764It returns the address of the aligned, zero-filled dynamic-array or @NULL@ if either @dim@ or @elemSize@ are zero.
1765
1766\medskip\noindent
1767\lstinline{size_t malloc_alignment( void * addr )}
1768returns the object alignment, where objects not allocated with alignment return the minimal allocation alignment.
1769For use in aligning similar allocations.
1770
1771\medskip\noindent
1772\lstinline{bool malloc_zero_fill( void * addr )}
1773returns true if the objects zero-fill sticky property is set and false otherwise.
1774For use in zero filling similar allocations.
1775
1776\medskip\noindent
1777\lstinline{size_t malloc_size( void * addr )}
1778returns the object's request size, which is updated when an object is resized or zero if @addr@ is @NULL@ (see also @malloc_usable_size@).
1779For use in similar allocations.
1780
1781\medskip\noindent
1782\lstinline{int malloc_stats_fd( int fd )}
1783changes the file descriptor where @malloc_stats@ writes statistics (default @stdout@) and returns the previous file descriptor.
1784
1785\medskip\noindent
1786\lstinline{size_t malloc_expansion()}
1787\label{p:malloc_expansion}
1788set the amount (bytes) to extend the heap when there is insufficient free storage to service an allocation request.
1789It returns the heap extension size used throughout a program when requesting more memory from the system using @sbrk@ system-call, \ie called once at heap initialization.
1790
1791\medskip\noindent
1792\lstinline{size_t malloc_mmap_start()}
1793set the crossover between allocations occurring in the @sbrk@ area or separately mapped.
1794It returns the crossover point used throughout a program, \ie called once at heap initialization.
1795
1796\medskip\noindent
1797\lstinline{size_t malloc_unfreed()}
1798\label{p:malloc_unfreed}
1799amount subtracted to adjust for unfreed program storage (debug only).
1800It returns the new subtraction amount and called by @malloc_stats@ (discussed in Section~\ref{}).
1801
1802
1803\subsubsection{\CC Interface}
1804
1805The following extensions take advantage of overload polymorphism in the \CC type-system.
1806
1807\medskip\noindent
1808\lstinline{void * resize( void * oaddr, size_t nalign, size_t size )}
1809extends @resize@ with an alignment requirement, @nalign@.
1810It returns the address of the old or new storage with the specified new size and alignment, or @NULL@ if @size@ is zero.
1811
1812\medskip\noindent
1813\lstinline{void * realloc( void * oaddr, size_t nalign, size_t size )}
1814extends @realloc@ with an alignment requirement, @nalign@.
1815It returns the address of the old or new storage with the specified new size and alignment, or @NULL@ if @size@ is zero.
1816
1817
1818\subsubsection{\CFA Interface}
1819
1820The following extensions take advantage of overload polymorphism in the \CFA type-system.
1821The key safety advantage of the \CFA type system is using the return type to select overloads;
1822hence, a polymorphic routine knows the returned type and its size.
1823This capability is used to remove the object size parameter and correctly cast the return storage to match the result type.
1824For example, the following is the \CFA wrapper for C @malloc@:
1825\begin{cfa}
1826forall( T & | sized(T) ) {
1827        T * malloc( void ) {
1828                if ( _Alignof(T) <= libAlign() ) return @(T *)@malloc( @sizeof(T)@ ); // C allocation
1829                else return @(T *)@memalign( @_Alignof(T)@, @sizeof(T)@ ); // C allocation
1830        } // malloc
1831\end{cfa}
1832and is used as follows:
1833\begin{lstlisting}
1834int * i = malloc();
1835double * d = malloc();
1836struct Spinlock { ... } __attribute__(( aligned(128) ));
1837Spinlock * sl = malloc();
1838\end{lstlisting}
1839where each @malloc@ call provides the return type as @T@, which is used with @sizeof@, @_Alignof@, and casting the storage to the correct type.
1840This interface removes many of the common allocation errors in C programs.
1841Figure~\ref{f:CFADynamicAllocationAPI} show the \CFA wrappers for the equivalent C/\CC allocation routines with same semantic behaviour.
1842
1843\begin{figure}
1844\begin{lstlisting}
1845T * malloc( void );
1846T * aalloc( size_t dim );
1847T * calloc( size_t dim );
1848T * resize( T * ptr, size_t size );
1849T * realloc( T * ptr, size_t size );
1850T * memalign( size_t align );
1851T * amemalign( size_t align, size_t dim );
1852T * cmemalign( size_t align, size_t dim  );
1853T * aligned_alloc( size_t align );
1854int posix_memalign( T ** ptr, size_t align );
1855T * valloc( void );
1856T * pvalloc( void );
1857\end{lstlisting}
1858\caption{\CFA C-Style Dynamic-Allocation API}
1859\label{f:CFADynamicAllocationAPI}
1860\end{figure}
1861
1862In addition to the \CFA C-style allocator interface, a new allocator interface is provided to further increase orthogonality and usability of dynamic-memory allocation.
1863This interface helps programmers in three ways.
1864\begin{itemize}[topsep=3pt,itemsep=2pt,parsep=0pt]
1865\item
1866naming: \CFA regular and @ttype@ polymorphism (@ttype@ polymorphism in \CFA is similar to \CC variadic templates) is used to encapsulate a wide range of allocation functionality into a single routine name, so programmers do not have to remember multiple routine names for different kinds of dynamic allocations.
1867\item
1868named arguments: individual allocation properties are specified using postfix function call, so the programmers do not have to remember parameter positions in allocation calls.
1869\item
1870object size: like the \CFA's C-interface, programmers do not have to specify object size or cast allocation results.
1871\end{itemize}
1872Note, postfix function call is an alternative call syntax, using backtick @`@, so the argument appears before the function name, \eg
1873\begin{cfa}
1874duration ?@`@h( int h );                // ? denote the position of the function operand
1875duration ?@`@m( int m );
1876duration ?@`@s( int s );
1877duration dur = 3@`@h + 42@`@m + 17@`@s;
1878\end{cfa}
1879
1880The following extensions take advantage of overload polymorphism in the \CC type-system.
1881
1882\medskip\noindent
1883\lstinline{T * alloc( ... )} or \lstinline{T * alloc( size_t dim, ... )}
1884is overloaded with a variable number of specific allocation operations, or an integer dimension parameter followed by a variable number of specific allocation operations.
1885These allocation operations can be passed as named arguments when calling the \lstinline{alloc} routine.
1886A call without parameters returns a dynamically allocated object of type @T@ (@malloc@).
1887A call with only the dimension (dim) parameter returns a dynamically allocated array of objects of type @T@ (@aalloc@).
1888The variable number of arguments consist of allocation properties, which can be combined to produce different kinds of allocations.
1889The only restriction is for properties @realloc@ and @resize@, which cannot be combined.
1890
1891The allocation property functions are:
1892
1893\medskip\noindent
1894\lstinline{T_align ?`align( size_t alignment )}
1895to align the allocation.
1896The alignment parameter must be $\ge$ the default alignment (@libAlign()@ in \CFA) and a power of two.
1897The following example returns a dynamic object and object array aligned on a 4096-byte boundary.
1898\begin{cfa}
1899int * i0 = alloc( @4096`align@ );  sout | i0 | nl;
1900int * i1 = alloc( 3, @4096`align@ );  sout | i1; for (i; 3 ) sout | &i1[i]; sout | nl;
1901
19020x555555572000
19030x555555574000 0x555555574000 0x555555574004 0x555555574008
1904\end{cfa}
1905
1906\medskip\noindent
1907\lstinline{S_fill(T) ?`fill ( /* various types */ )}
1908to initialize storage.
1909There are three ways to fill storage:
1910\begin{enumerate}[itemsep=0pt,parsep=0pt]
1911\item
1912A char fills each byte of each object.
1913\item
1914An object of the returned type fills each object.
1915\item
1916An object array pointer fills some or all of the corresponding object array.
1917\end{enumerate}
1918For example:
1919\begin{cfa}[numbers=left,xleftmargin=2.5\parindentlnth]
1920int * i0 = alloc( @0n`fill@ );  sout | *i0 | nl;  // disambiguate 0
1921int * i1 = alloc( @5`fill@ );  sout | *i1 | nl;
1922int * i2 = alloc( @'\xfe'`fill@ ); sout | hex( *i2 ) | nl;
1923int * i3 = alloc( 5, @5`fill@ );  for ( i; 5 ) sout | i3[i]; sout | nl;
1924int * i4 = alloc( 5, @0xdeadbeefN`fill@ );  for ( i; 5 ) sout | hex( i4[i] ); sout | nl;
1925int * i5 = alloc( 5, @i3`fill@ );  for ( i; 5 ) sout | i5[i]; sout | nl;
1926int * i6 = alloc( 5, @[i3, 3]`fill@ );  for ( i; 5 ) sout | i6[i]; sout | nl;
1927\end{cfa}
1928\begin{lstlisting}[numbers=left,xleftmargin=2.5\parindentlnth]
19290
19305
19310xfefefefe
19325 5 5 5 5
19330xdeadbeef 0xdeadbeef 0xdeadbeef 0xdeadbeef 0xdeadbeef
19345 5 5 5 5
19355 5 5 -555819298 -555819298  // two undefined values
1936\end{lstlisting}
1937Examples 1 to 3 fill an object with a value or characters.
1938Examples 4 to 7 fill an array of objects with values, another array, or part of an array.
1939
1940\medskip\noindent
1941\lstinline{S_resize(T) ?`resize( void * oaddr )}
1942used to resize, realign, and fill, where the old object data is not copied to the new object.
1943The old object type may be different from the new object type, since the values are not used.
1944For example:
1945\begin{cfa}[numbers=left,xleftmargin=2.5\parindentlnth]
1946int * i = alloc( @5`fill@ );  sout | i | *i;
1947i = alloc( @i`resize@, @256`align@, @7`fill@ );  sout | i | *i;
1948double * d = alloc( @i`resize@, @4096`align@, @13.5`fill@ );  sout | d | *d;
1949\end{cfa}
1950\begin{lstlisting}[numbers=left,xleftmargin=2.5\parindentlnth]
19510x55555556d5c0 5
19520x555555570000 7
19530x555555571000 13.5
1954\end{lstlisting}
1955Examples 2 to 3 change the alignment, fill, and size for the initial storage of @i@.
1956
1957\begin{cfa}[numbers=left,xleftmargin=2.5\parindentlnth]
1958int * ia = alloc( 5, @5`fill@ );  for ( i; 5 ) sout | ia[i]; sout | nl;
1959ia = alloc( 10, @ia`resize@, @7`fill@ ); for ( i; 10 ) sout | ia[i]; sout | nl;
1960sout | ia; ia = alloc( 5, @ia`resize@, @512`align@, @13`fill@ ); sout | ia; for ( i; 5 ) sout | ia[i]; sout | nl;;
1961ia = alloc( 3, @ia`resize@, @4096`align@, @2`fill@ );  sout | ia; for ( i; 3 ) sout | &ia[i] | ia[i]; sout | nl;
1962\end{cfa}
1963\begin{lstlisting}[numbers=left,xleftmargin=2.5\parindentlnth]
19645 5 5 5 5
19657 7 7 7 7 7 7 7 7 7
19660x55555556d560 0x555555571a00 13 13 13 13 13
19670x555555572000 0x555555572000 2 0x555555572004 2 0x555555572008 2
1968\end{lstlisting}
1969Examples 2 to 4 change the array size, alignment and fill for the initial storage of @ia@.
1970
1971\medskip\noindent
1972\lstinline{S_realloc(T) ?`realloc( T * a ))}
1973used to resize, realign, and fill, where the old object data is copied to the new object.
1974The old object type must be the same as the new object type, since the value is used.
1975Note, for @fill@, only the extra space after copying the data from the old object is filled with the given parameter.
1976For example:
1977\begin{cfa}[numbers=left,xleftmargin=2.5\parindentlnth]
1978int * i = alloc( @5`fill@ );  sout | i | *i;
1979i = alloc( @i`realloc@, @256`align@ );  sout | i | *i;
1980i = alloc( @i`realloc@, @4096`align@, @13`fill@ );  sout | i | *i;
1981\end{cfa}
1982\begin{lstlisting}[numbers=left,xleftmargin=2.5\parindentlnth]
19830x55555556d5c0 5
19840x555555570000 5
19850x555555571000 5
1986\end{lstlisting}
1987Examples 2 to 3 change the alignment for the initial storage of @i@.
1988The @13`fill@ in example 3 does nothing because no extra space is added.
1989
1990\begin{cfa}[numbers=left,xleftmargin=2.5\parindentlnth]
1991int * ia = alloc( 5, @5`fill@ );  for ( i; 5 ) sout | ia[i]; sout | nl;
1992ia = alloc( 10, @ia`realloc@, @7`fill@ ); for ( i; 10 ) sout | ia[i]; sout | nl;
1993sout | ia; ia = alloc( 1, @ia`realloc@, @512`align@, @13`fill@ ); sout | ia; for ( i; 1 ) sout | ia[i]; sout | nl;;
1994ia = alloc( 3, @ia`realloc@, @4096`align@, @2`fill@ );  sout | ia; for ( i; 3 ) sout | &ia[i] | ia[i]; sout | nl;
1995\end{cfa}
1996\begin{lstlisting}[numbers=left,xleftmargin=2.5\parindentlnth]
19975 5 5 5 5
19985 5 5 5 5 7 7 7 7 7
19990x55555556c560 0x555555570a00 5
20000x555555571000 0x555555571000 5 0x555555571004 2 0x555555571008 2
2001\end{lstlisting}
2002Examples 2 to 4 change the array size, alignment and fill for the initial storage of @ia@.
2003The @13`fill@ in example 3 does nothing because no extra space is added.
2004
2005These \CFA allocation features are used extensively in the development of the \CFA runtime.
2006
2007
2008\section{Benchmarks}
2009\label{s:Benchmarks}
2010
2011%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2012%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2013%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Micro Benchmark Suite
2014%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2015%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2016
2017There are two basic approaches for evaluating computer software: benchmarks and micro-benchmarks.
2018\begin{description}
2019\item[Benchmarks]
2020are a suite of application programs (SPEC CPU/WEB) that are exercised in a common way (inputs) to find differences among underlying software implementations associated with an application (compiler, memory allocator, web server, \etc).
2021The applications are supposed to represent common execution patterns that need to perform well with respect to an underlying software implementation.
2022Benchmarks are often criticized for having overlapping patterns, insufficient patterns, or extraneous code that masks patterns.
2023\item[Micro-Benchmarks]
2024attempt to extract the common execution patterns associated with an application and run the pattern independently.
2025This approach removes any masking from extraneous application code, allows execution pattern to be very precise, and provides an opportunity for the execution pattern to have multiple independent tuning adjustments (knobs).
2026Micro-benchmarks are often criticized for inadequately representing real-world applications.
2027\end{description}
2028
2029While some crucial software components have standard benchmarks, no standard benchmark exists for testing and comparing memory allocators.
2030In the past, an assortment of applications have been used for benchmarking allocators~\cite{Detlefs93,Berger00,Berger01,berger02reconsidering}: P2C, GS, Espresso/Espresso-2, CFRAC/CFRAC-2, GMake, GCC, Perl/Perl-2, Gawk/Gawk-2, XPDF/XPDF-2, ROBOOP, Lindsay.
2031As well, an assortment of micro-benchmark have been used for benchmarking allocators~\cite{larson99memory,Berger00,streamflow}: threadtest, shbench, Larson, consume, false sharing.
2032Many of these benchmark applications and micro-benchmarks are old and may not reflect current application allocation patterns.
2033
2034This work designs and examines a new set of micro-benchmarks for memory allocators that test a variety of allocation patterns, each with multiple tuning parameters.
2035The aim of the micro-benchmark suite is to create a set of programs that can evaluate a memory allocator based on the key performance metrics such as speed, memory overhead, and cache performance.
2036% These programs can be taken as a standard to benchmark an allocator's basic goals.
2037These programs give details of an allocator's memory overhead and speed under certain allocation patterns.
2038The allocation patterns are configurable (adjustment knobs) to observe an allocator's performance across a spectrum allocation patterns, which is seldom possible with benchmark programs.
2039Each micro-benchmark program has multiple control knobs specified by command-line arguments.
2040
2041The new micro-benchmark suite measures performance by allocating dynamic objects and measuring specific metrics.
2042An allocator's speed is benchmarked in different ways, as are issues like false sharing.
2043
2044
2045\subsection{Prior Multi-Threaded Micro-Benchmarks}
2046
2047Modern memory allocators, such as llheap, must handle multi-threaded programs at the KT and UT level.
2048The following multi-threaded micro-benchmarks are presented to give a sense of prior work~\cite{Berger00} at the KT level.
2049None of the prior work addresses multi-threading at the UT level.
2050
2051
2052\subsubsection{threadtest}
2053
2054This benchmark stresses the ability of the allocator to handle different threads allocating and deallocating independently.
2055There is no interaction among threads, \ie no object sharing.
2056Each thread repeatedly allocates 100,000 \emph{8-byte} objects then deallocates them in the order they were allocated.
2057The execution time of the benchmark evaluates its efficiency.
2058
2059
2060\subsubsection{shbench}
2061
2062This benchmark is similar to threadtest but each thread randomly allocate and free a number of \emph{random-sized} objects.
2063It is a stress test that also uses runtime to determine efficiency of the allocator.
2064
2065
2066\subsubsection{Larson}
2067
2068This benchmark simulates a server environment.
2069Multiple threads are created where each thread allocates and frees a number of random-sized objects within a size range.
2070Before the thread terminates, it passes its array of 10,000 objects to a new child thread to continue the process.
2071The number of thread generations varies depending on the thread speed.
2072It calculates memory operations per second as an indicator of the memory allocator's performance.
2073
2074
2075\subsection{New Multi-Threaded Micro-Benchmarks}
2076
2077The following new benchmarks were created to assess multi-threaded programs at the KT and UT level.
2078For generating random values, two generators are supported: uniform~\cite{uniformPRNG} and fisher~\cite{fisherPRNG}.
2079
2080
2081\subsubsection{Churn Benchmark}
2082\label{s:ChurnBenchmark}
2083
2084The churn benchmark measures the runtime speed of an allocator in a multi-threaded scenario, where each thread extensively allocates and frees dynamic memory.
2085Only @malloc@ and @free@ are used to eliminate any extra cost, such as @memcpy@ in @calloc@ or @realloc@.
2086Churn simulates a memory intensive program and can be tuned to create different scenarios.
2087
2088Figure~\ref{fig:ChurnBenchFig} shows the pseudo code for the churn micro-benchmark.
2089This benchmark creates a buffer with M spots and an allocation in each spot, and then starts K threads.
2090Each thread picks a random spot in M, frees the object currently at that spot, and allocates a new object for that spot.
2091Each thread repeats this cycle N times.
2092The main thread measures the total time taken for the whole benchmark and that time is used to evaluate the memory allocator's performance.
2093
2094\begin{figure}
2095\centering
2096\begin{lstlisting}
2097Main Thread
2098        create worker threads
2099        note time T1
2100        ...
2101        note time T2
2102        churn_speed = (T2 - T1)
2103Worker Thread
2104        initialize variables
2105        ...
2106        for ( N )
2107                R = random spot in array
2108                free R
2109                allocate new object at R
2110\end{lstlisting}
2111%\includegraphics[width=1\textwidth]{figures/bench-churn.eps}
2112\caption{Churn Benchmark}
2113\label{fig:ChurnBenchFig}
2114\end{figure}
2115
2116The adjustment knobs for churn are:
2117\begin{description}[itemsep=0pt,parsep=0pt]
2118\item[thread:]
2119number of threads (K).
2120\item[spots:]
2121number of spots for churn (M).
2122\item[obj:]
2123number of objects per thread (N).
2124\item[max:]
2125maximum object size.
2126\item[min:]
2127minimum object size.
2128\item[step:]
2129object size increment.
2130\item[distro:]
2131object size distribution
2132\end{description}
2133
2134
2135\subsubsection{Cache Thrash}
2136\label{sec:benchThrashSec}
2137
2138The cache-thrash micro-benchmark measures allocator-induced active false-sharing as illustrated in Section~\ref{s:AllocatorInducedActiveFalseSharing}.
2139If memory is allocated for multiple threads on the same cache line, this can significantly slow down program performance.
2140When threads share a cache line, frequent reads/writes to their cache-line object causes cache misses, which cause escalating delays as cache distance increases.
2141
2142Cache thrash tries to create a scenario that leads to false sharing, if the underlying memory allocator is allocating dynamic memory to multiple threads on the same cache lines.
2143Ideally, a memory allocator should distance the dynamic memory region of one thread from another.
2144Having multiple threads allocating small objects simultaneously can cause a memory allocator to allocate objects on the same cache line, if its not distancing the memory among different threads.
2145
2146Figure~\ref{fig:benchThrashFig} shows the pseudo code for the cache-thrash micro-benchmark.
2147First, it creates K worker threads.
2148Each worker thread allocates an object and intensively reads/writes it for M times to possible invalidate cache lines that may interfere with other threads sharing the same cache line.
2149Each thread repeats this for N times.
2150The main thread measures the total time taken for all worker threads to complete.
2151Worker threads sharing cache lines with each other are expected to take longer.
2152
2153\begin{figure}
2154\centering
2155\input{AllocInducedActiveFalseSharing}
2156\medskip
2157\begin{lstlisting}
2158Main Thread
2159        create worker threads
2160        ...
2161        signal workers to allocate
2162        ...
2163        signal workers to free
2164        ...
2165Worker Thread$\(_1\)$
2166        warm up memory in chunks of 16 bytes
2167        ...
2168        For N
2169                malloc an object
2170                read/write the object M times
2171                free the object
2172        ...
2173Worker Thread$\(_2\)$
2174        // same as Worker Thread$\(_1\)$
2175\end{lstlisting}
2176%\input{MemoryOverhead}
2177%\includegraphics[width=1\textwidth]{figures/bench-cache-thrash.eps}
2178\caption{Allocator-Induced Active False-Sharing Benchmark}
2179\label{fig:benchThrashFig}
2180\end{figure}
2181
2182The adjustment knobs for cache access scenarios are:
2183\begin{description}[itemsep=0pt,parsep=0pt]
2184\item[thread:]
2185number of threads (K).
2186\item[iterations:]
2187iterations of cache benchmark (N).
2188\item[cacheRW:]
2189repetitions of reads/writes to object (M).
2190\item[size:]
2191object size.
2192\end{description}
2193
2194
2195\subsubsection{Cache Scratch}
2196\label{s:CacheScratch}
2197
2198The cache-scratch micro-benchmark measures allocator-induced passive false-sharing as illustrated in Section~\ref{s:AllocatorInducedPassiveFalseSharing}.
2199As with cache thrash, if memory is allocated for multiple threads on the same cache line, this can significantly slow down program performance.
2200In this scenario, the false sharing is being caused by the memory allocator although it is started by the program sharing an object.
2201
2202% An allocator can unintentionally induce false sharing depending upon its management of the freed objects.
2203% If thread Thread$_1$ allocates multiple objects together, they may be allocated on the same cache line by the memory allocator.
2204% If Thread$_1$ passes these object to thread Thread$_2$, then both threads may share the same cache line but this scenario is not induced by the allocator;
2205% instead, the program induced this situation.
2206% Now if Thread$_2$ frees this object and then allocate an object of the same size, the allocator may return the same object, which is on a cache line shared with thread Thread$_1$.
2207
2208Cache scratch tries to create a scenario that leads to false sharing and should make the memory allocator preserve the program-induced false sharing, if it does not return a freed object to its owner thread and, instead, re-uses it instantly.
2209An allocator using object ownership, as described in subsection Section~\ref{s:Ownership}, is less susceptible to allocator-induced passive false-sharing.
2210If the object is returned to the thread that owns it, then the new object that the thread gets is less likely to be on the same cache line.
2211
2212Figure~\ref{fig:benchScratchFig} shows the pseudo code for the cache-scratch micro-benchmark.
2213First, it allocates K dynamic objects together, one for each of the K worker threads, possibly causing memory allocator to allocate these objects on the same cache line.
2214Then it create K worker threads and passes an object from the K allocated objects to each of the K threads.
2215Each worker thread frees the object passed by the main thread.
2216Then, it allocates an object and reads/writes it repetitively for M times possibly causing frequent cache invalidations.
2217Each worker repeats this N times.
2218
2219\begin{figure}
2220\centering
2221\input{AllocInducedPassiveFalseSharing}
2222\medskip
2223\begin{lstlisting}
2224Main Thread
2225        malloc N objects $for$ each worker $thread$
2226        create worker threads and pass N objects to each worker
2227        ...
2228        signal workers to allocate
2229        ...
2230        signal workers to free
2231        ...
2232Worker Thread$\(_1\)$
2233        warmup memory in chunks of 16 bytes
2234        ...
2235        free the object passed by the Main Thread
2236        For N
2237                malloc new object
2238                read/write the object M times
2239                free the object
2240        ...
2241Worker Thread$\(_2\)$
2242        // same as Worker Thread$\(_1\)$
2243\end{lstlisting}
2244%\includegraphics[width=1\textwidth]{figures/bench-cache-scratch.eps}
2245\caption{Program-Induced Passive False-Sharing Benchmark}
2246\label{fig:benchScratchFig}
2247\end{figure}
2248
2249Each thread allocating an object after freeing the original object passed by the main thread should cause the memory allocator to return the same object that was initially allocated by the main thread if the allocator did not return the initial object back to its owner (main thread).
2250Then, intensive read/write on the shared cache line by multiple threads should slow down worker threads due to to high cache invalidations and misses.
2251Main thread measures the total time taken for all the workers to complete.
2252
2253Similar to benchmark cache thrash in subsection Section~\ref{sec:benchThrashSec}, different cache access scenarios can be created using the following command-line arguments.
2254\begin{description}[topsep=0pt,itemsep=0pt,parsep=0pt]
2255\item[threads:]
2256number of threads (K).
2257\item[iterations:]
2258iterations of cache benchmark (N).
2259\item[cacheRW:]
2260repetitions of reads/writes to object (M).
2261\item[size:]
2262object size.
2263\end{description}
2264
2265
2266\subsubsection{Speed Micro-Benchmark}
2267\label{s:SpeedMicroBenchmark}
2268\vspace*{-4pt}
2269
2270The speed benchmark measures the runtime speed of individual and sequences of memory allocation routines:
2271\begin{enumerate}[topsep=-5pt,itemsep=0pt,parsep=0pt]
2272\item malloc
2273\item realloc
2274\item free
2275\item calloc
2276\item malloc-free
2277\item realloc-free
2278\item calloc-free
2279\item malloc-realloc
2280\item calloc-realloc
2281\item malloc-realloc-free
2282\item calloc-realloc-free
2283\item malloc-realloc-free-calloc
2284\end{enumerate}
2285
2286Figure~\ref{fig:SpeedBenchFig} shows the pseudo code for the speed micro-benchmark.
2287Each routine in the chain is called for N objects and then those allocated objects are used when calling the next routine in the allocation chain.
2288This tests the latency of the memory allocator when multiple routines are chained together, \eg the call sequence malloc-realloc-free-calloc gives a complete picture of the major allocation routines when combined together.
2289For each chain, the time is recorded to visualize performance of a memory allocator against each chain.
2290
2291\begin{figure}
2292\centering
2293\begin{lstlisting}[morekeywords={foreach}]
2294Main Thread
2295        create worker threads
2296        foreach ( allocation chain )
2297                note time T1
2298                ...
2299                note time T2
2300                chain_speed = (T2 - T1) / number-of-worker-threads * N )
2301Worker Thread
2302        initialize variables
2303        ...
2304        foreach ( routine in allocation chain )
2305                call routine N times
2306\end{lstlisting}
2307%\includegraphics[width=1\textwidth]{figures/bench-speed.eps}
2308\caption{Speed Benchmark}
2309\label{fig:SpeedBenchFig}
2310\end{figure}
2311
2312The adjustment knobs for memory usage are:
2313\begin{description}[itemsep=0pt,parsep=0pt]
2314\item[max:]
2315maximum object size.
2316\item[min:]
2317minimum object size.
2318\item[step:]
2319object size increment.
2320\item[distro:]
2321object size distribution.
2322\item[objects:]
2323number of objects per thread.
2324\item[workers:]
2325number of worker threads.
2326\end{description}
2327
2328
2329\subsubsection{Memory Micro-Benchmark}
2330\label{s:MemoryMicroBenchmark}
2331
2332The memory micro-benchmark measures the memory overhead of an allocator.
2333It allocates a number of dynamic objects and reads @/proc/self/proc/maps@ to get the total memory requested by the allocator from the OS.
2334It calculates the memory overhead by computing the difference between the memory the allocator requests from the OS and the memory that the program allocates.
2335This micro-benchmark is like Larson and stresses the ability of an allocator to deal with object sharing.
2336
2337Figure~\ref{fig:MemoryBenchFig} shows the pseudo code for the memory micro-benchmark.
2338It creates a producer-consumer scenario with K producer threads and each producer has M consumer threads.
2339A producer has a separate buffer for each consumer and allocates N objects of random sizes following a configurable distribution for each consumer.
2340A consumer frees these objects.
2341After every memory operation, program memory usage is recorded throughout the runtime.
2342This data is used to visualize the memory usage and consumption for the program.
2343
2344\begin{figure}
2345\centering
2346\begin{lstlisting}
2347Main Thread
2348        print memory snapshot
2349        create producer threads
2350Producer Thread (K)
2351        set free start
2352        create consumer threads
2353        for ( N )
2354                allocate memory
2355                print memory snapshot
2356Consumer Thread (M)
2357        wait while ( allocations < free start )
2358        for ( N )
2359                free memory
2360                print memory snapshot
2361\end{lstlisting}
2362%\includegraphics[width=1\textwidth]{figures/bench-memory.eps}
2363\caption{Memory Footprint Micro-Benchmark}
2364\label{fig:MemoryBenchFig}
2365\end{figure}
2366
2367The global adjustment knobs for this micro-benchmark are:
2368\begin{description}[itemsep=0pt,parsep=0pt]
2369\item[producer (K):]
2370sets the number of producer threads.
2371\item[consumer (M):]
2372sets number of consumers threads for each producer.
2373\item[round:]
2374sets production and consumption round size.
2375\end{description}
2376
2377The adjustment knobs for object allocation are:
2378\begin{description}[itemsep=0pt,parsep=0pt]
2379\item[max:]
2380maximum object size.
2381\item[min:]
2382minimum object size.
2383\item[step:]
2384object size increment.
2385\item[distro:]
2386object size distribution.
2387\item[objects (N):]
2388number of objects per thread.
2389\end{description}
2390
2391
2392\section{Performance}
2393\label{c:Performance}
2394
2395This section uses the micro-benchmarks from Section~\ref{s:Benchmarks} to test a number of current memory allocators, including llheap.
2396The goal is to see if llheap is competitive with the currently popular memory allocators.
2397
2398
2399\subsection{Machine Specification}
2400
2401The performance experiments were run on two different multi-core architectures (x64 and ARM) to determine if there is consistency across platforms:
2402\begin{itemize}[topsep=3pt,itemsep=2pt,parsep=0pt]
2403\item
2404\textbf{Algol} Huawei ARM TaiShan 2280 V2 Kunpeng 920, 24-core socket $\times$ 4, 2.6 GHz, GCC version 9.4.0
2405\item
2406\textbf{Nasus} AMD EPYC 7662, 64-core socket $\times$ 2, 2.0 GHz, GCC version 9.3.0
2407\end{itemize}
2408
2409
2410\subsection{Existing Memory Allocators}
2411\label{sec:curAllocatorSec}
2412
2413With dynamic allocation being an important feature of C, there are many stand-alone memory allocators that have been designed for different purposes.
2414For this work, 7 of the most popular and widely used memory allocators were selected for comparison, along with llheap.
2415
2416\paragraph{llheap (\textsf{llh})}
2417is the thread-safe allocator from Chapter~\ref{c:Allocator}
2418\\
2419\textbf{Version:} 1.0
2420\textbf{Configuration:} Compiled with dynamic linking, but without statistics or debugging.\\
2421\textbf{Compilation command:} @make@
2422
2423\paragraph{glibc (\textsf{glc})}
2424\cite{glibc} is the default glibc thread-safe allocator.
2425\\
2426\textbf{Version:} Ubuntu GLIBC 2.31-0ubuntu9.7 2.31\\
2427\textbf{Configuration:} Compiled by Ubuntu 20.04.\\
2428\textbf{Compilation command:} N/A
2429
2430\paragraph{dlmalloc (\textsf{dl})}
2431\cite{dlmalloc} is a thread-safe allocator that is single threaded and single heap.
2432It maintains free-lists of different sizes to store freed dynamic memory.
2433\\
2434\textbf{Version:} 2.8.6\\
2435\textbf{Configuration:} Compiled with preprocessor @USE_LOCKS@.\\
2436\textbf{Compilation command:} @gcc -g3 -O3 -Wall -Wextra -fno-builtin-malloc -fno-builtin-calloc@ @-fno-builtin-realloc -fno-builtin-free -fPIC -shared -DUSE_LOCKS -o libdlmalloc.so malloc-2.8.6.c@
2437
2438\paragraph{hoard (\textsf{hrd})}
2439\cite{hoard} is a thread-safe allocator that is multi-threaded and uses a heap layer framework. It has per-thread heaps that have thread-local free-lists, and a global shared heap.
2440\\
2441\textbf{Version:} 3.13\\
2442\textbf{Configuration:} Compiled with hoard's default configurations and @Makefile@.\\
2443\textbf{Compilation command:} @make all@
2444
2445\paragraph{jemalloc (\textsf{je})}
2446\cite{jemalloc} is a thread-safe allocator that uses multiple arenas. Each thread is assigned an arena.
2447Each arena has chunks that contain contagious memory regions of same size. An arena has multiple chunks that contain regions of multiple sizes.
2448\\
2449\textbf{Version:} 5.2.1\\
2450\textbf{Configuration:} Compiled with jemalloc's default configurations and @Makefile@.\\
2451\textbf{Compilation command:} @autogen.sh; configure; make; make install@
2452
2453\paragraph{ptmalloc3 (\textsf{pt3})}
2454\cite{ptmalloc3} is a modification of dlmalloc.
2455It is a thread-safe multi-threaded memory allocator that uses multiple heaps.
2456ptmalloc3 heap has similar design to dlmalloc's heap.
2457\\
2458\textbf{Version:} 1.8\\
2459\textbf{Configuration:} Compiled with ptmalloc3's @Makefile@ using option ``linux-shared''.\\
2460\textbf{Compilation command:} @make linux-shared@
2461
2462\paragraph{rpmalloc (\textsf{rp})}
2463\cite{rpmalloc} is a thread-safe allocator that is multi-threaded and uses per-thread heap.
2464Each heap has multiple size-classes and each size-class contains memory regions of the relevant size.
2465\\
2466\textbf{Version:} 1.4.1\\
2467\textbf{Configuration:} Compiled with rpmalloc's default configurations and ninja build system.\\
2468\textbf{Compilation command:} @python3 configure.py; ninja@
2469
2470\paragraph{tbb malloc (\textsf{tbb})}
2471\cite{tbbmalloc} is a thread-safe allocator that is multi-threaded and uses a private heap for each thread.
2472Each private-heap has multiple bins of different sizes. Each bin contains free regions of the same size.
2473\\
2474\textbf{Version:} intel tbb 2020 update 2, tbb\_interface\_version == 11102\\
2475\textbf{Configuration:} Compiled with tbbmalloc's default configurations and @Makefile@.\\
2476\textbf{Compilation command:} @make@
2477
2478% \subsection{Experiment Environment}
2479% We used our micro benchmark suite (FIX ME: cite mbench) to evaluate these memory allocators Section~\ref{sec:curAllocatorSec} and our own memory allocator uHeap Section~\ref{sec:allocatorSec}.
2480
2481\subsection{Experiments}
2482
2483Each micro-benchmark is configured and run with each of the allocators,
2484The less time an allocator takes to complete a benchmark the better so lower in the graphs is better, except for the Memory micro-benchmark graphs.
2485All graphs use log scale on the Y-axis, except for the Memory micro-benchmark (see Section~\ref{s:MemoryMicroBenchmark}).
2486
2487%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2488%% CHURN
2489%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2490
2491\subsubsection{Churn Micro-Benchmark}
2492
2493Churn tests allocators for speed under intensive dynamic memory usage (see Section~\ref{s:ChurnBenchmark}).
2494This experiment was run with following configurations:
2495\begin{description}[itemsep=0pt,parsep=0pt]
2496\item[thread:]
24971, 2, 4, 8, 16, 32, 48
2498\item[spots:]
249916
2500\item[obj:]
2501100,000
2502\item[max:]
2503500
2504\item[min:]
250550
2506\item[step:]
250750
2508\item[distro:]
2509fisher
2510\end{description}
2511
2512% -maxS          : 500
2513% -minS          : 50
2514% -stepS                 : 50
2515% -distroS       : fisher
2516% -objN          : 100000
2517% -cSpots                : 16
2518% -threadN       : 1, 2, 4, 8, 16
2519
2520Figure~\ref{fig:churn} shows the results for algol and nasus.
2521The X-axis shows the number of threads;
2522the Y-axis shows the total experiment time.
2523Each allocator's performance for each thread is shown in different colors.
2524
2525\begin{figure}
2526\centering
2527    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/churn} } \\
2528    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/churn} }
2529\caption{Churn}
2530\label{fig:churn}
2531\end{figure}
2532
2533\paragraph{Assessment}
2534All allocators did well in this micro-benchmark, except for \textsf{dl} on the ARM.
2535\textsf{dl}'s is the slowest, indicating some small bottleneck with respect to the other allocators.
2536\textsf{je} is the fastest, with only a small benefit over the other allocators.
2537% llheap is slightly slower because it uses ownership, where many of the allocations have remote frees, which requires locking.
2538% When llheap is compiled without ownership, its performance is the same as the other allocators (not shown).
2539
2540%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2541%% THRASH
2542%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2543
2544\subsubsection{Cache Thrash}
2545\label{sec:cache-thrash-perf}
2546
2547Thrash tests memory allocators for active false sharing (see Section~\ref{sec:benchThrashSec}).
2548This experiment was run with following configurations:
2549\begin{description}[itemsep=0pt,parsep=0pt]
2550\item[threads:]
25511, 2, 4, 8, 16, 32, 48
2552\item[iterations:]
25531,000
2554\item[cacheRW:]
25551,000,000
2556\item[size:]
25571
2558\end{description}
2559
2560% * Each allocator was tested for its performance across different number of threads.
2561% Experiment was repeated for each allocator for 1, 2, 4, 8, and 16 threads by setting the configuration -threadN.
2562
2563Figure~\ref{fig:cacheThrash} shows the results for algol and nasus.
2564The X-axis shows the number of threads;
2565the Y-axis shows the total experiment time.
2566Each allocator's performance for each thread is shown in different colors.
2567
2568\begin{figure}
2569\centering
2570    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/cache_thrash_0-thrash} } \\
2571    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/cache_thrash_0-thrash} }
2572\caption{Cache Thrash}
2573\label{fig:cacheThrash}
2574\end{figure}
2575
2576\paragraph{Assessment}
2577All allocators did well in this micro-benchmark, except for \textsf{dl} and \textsf{pt3}.
2578\textsf{dl} uses a single heap for all threads so it is understandable that it generates so much active false-sharing.
2579Requests from different threads are dealt with sequentially by the single heap (using a single lock), which can allocate objects to different threads on the same cache line.
2580\textsf{pt3} uses the T:H model, so multiple threads can use one heap, but the active false-sharing is less than \textsf{dl}.
2581The rest of the memory allocators generate little or no active false-sharing.
2582
2583%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2584%% SCRATCH
2585%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2586
2587\subsubsection{Cache Scratch}
2588
2589Scratch tests memory allocators for program-induced allocator-preserved passive false-sharing (see Section~\ref{s:CacheScratch}).
2590This experiment was run with following configurations:
2591\begin{description}[itemsep=0pt,parsep=0pt]
2592\item[threads:]
25931, 2, 4, 8, 16, 32, 48
2594\item[iterations:]
25951,000
2596\item[cacheRW:]
25971,000,000
2598\item[size:]
25991
2600\end{description}
2601
2602% * Each allocator was tested for its performance across different number of threads.
2603% Experiment was repeated for each allocator for 1, 2, 4, 8, and 16 threads by setting the configuration -threadN.
2604
2605Figure~\ref{fig:cacheScratch} shows the results for algol and nasus.
2606The X-axis shows the number of threads;
2607the Y-axis shows the total experiment time.
2608Each allocator's performance for each thread is shown in different colors.
2609
2610\begin{figure}
2611\centering
2612    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/cache_scratch_0-scratch} } \\
2613    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/cache_scratch_0-scratch} }
2614\caption{Cache Scratch}
2615\label{fig:cacheScratch}
2616\end{figure}
2617
2618\paragraph{Assessment}
2619This micro-benchmark divides the allocators into two groups.
2620First is the high-performer group: \textsf{llh}, \textsf{je}, and \textsf{rp}.
2621These memory allocators generate little or no passive false-sharing and their performance difference is negligible.
2622Second is the low-performer group, which includes the rest of the memory allocators.
2623These memory allocators have significant program-induced passive false-sharing, where \textsf{hrd}'s is the worst performing allocator.
2624All of the allocators in this group are sharing heaps among threads at some level.
2625
2626Interestingly, allocators such as \textsf{hrd} and \textsf{glc} performed well in micro-benchmark cache thrash (see Section~\ref{sec:cache-thrash-perf}), but, these allocators are among the low performers in the cache scratch.
2627It suggests these allocators do not actively produce false-sharing, but preserve program-induced passive false sharing.
2628
2629%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2630%% SPEED
2631%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2632
2633\subsubsection{Speed Micro-Benchmark}
2634
2635Speed tests memory allocators for runtime latency (see Section~\ref{s:SpeedMicroBenchmark}).
2636This experiment was run with following configurations:
2637\begin{description}
2638\item[max:]
2639500
2640\item[min:]
264150
2642\item[step:]
264350
2644\item[distro:]
2645fisher
2646\item[objects:]
2647100,000
2648\item[workers:]
26491, 2, 4, 8, 16, 32, 48
2650\end{description}
2651
2652% -maxS    :  500
2653% -minS    :  50
2654% -stepS   :  50
2655% -distroS :  fisher
2656% -objN    :  1000000
2657% -threadN    : \{ 1, 2, 4, 8, 16 \} *
2658
2659%* Each allocator was tested for its performance across different number of threads.
2660%Experiment was repeated for each allocator for 1, 2, 4, 8, and 16 threads by setting the configuration -threadN.
2661
2662Figures~\ref{fig:speed-3-malloc} to~\ref{fig:speed-14-malloc-calloc-realloc-free} show 12 figures, one figure for each chain of the speed benchmark.
2663The X-axis shows the number of threads;
2664the Y-axis shows the total experiment time.
2665Each allocator's performance for each thread is shown in different colors.
2666
2667\begin{itemize}[topsep=3pt,itemsep=2pt,parsep=0pt]
2668\item Figure~\ref{fig:speed-3-malloc} shows results for chain: malloc
2669\item Figure~\ref{fig:speed-4-realloc} shows results for chain: realloc
2670\item Figure~\ref{fig:speed-5-free} shows results for chain: free
2671\item Figure~\ref{fig:speed-6-calloc} shows results for chain: calloc
2672\item Figure~\ref{fig:speed-7-malloc-free} shows results for chain: malloc-free
2673\item Figure~\ref{fig:speed-8-realloc-free} shows results for chain: realloc-free
2674\item Figure~\ref{fig:speed-9-calloc-free} shows results for chain: calloc-free
2675\item Figure~\ref{fig:speed-10-malloc-realloc} shows results for chain: malloc-realloc
2676\item Figure~\ref{fig:speed-11-calloc-realloc} shows results for chain: calloc-realloc
2677\item Figure~\ref{fig:speed-12-malloc-realloc-free} shows results for chain: malloc-realloc-free
2678\item Figure~\ref{fig:speed-13-calloc-realloc-free} shows results for chain: calloc-realloc-free
2679\item Figure~\ref{fig:speed-14-malloc-calloc-realloc-free} shows results for chain: malloc-realloc-free-calloc
2680\end{itemize}
2681
2682\paragraph{Assessment}
2683This micro-benchmark divides the allocators into two groups: with and without @calloc@.
2684@calloc@ uses @memset@ to set the allocated memory to zero, which dominates the cost of the allocation chain (large performance increase) and levels performance across the allocators.
2685But the difference among the allocators in a @calloc@ chain still gives an idea of their relative performance.
2686
2687All allocators did well in this micro-benchmark across all allocation chains, except for \textsf{dl}, \textsf{pt3}, and \textsf{hrd}.
2688Again, the low-performing allocators are sharing heaps among threads, so the contention causes performance increases with increasing numbers of threads.
2689Furthermore, chains with @free@ can trigger coalescing, which slows the fast path.
2690The high-performing allocators all illustrate low latency across the allocation chains, \ie there are no performance spikes as the chain lengths, that might be caused by contention and/or coalescing.
2691Low latency is important for applications that are sensitive to unknown execution delays.
2692
2693%speed-3-malloc.eps
2694\begin{figure}
2695\centering
2696    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/speed-3-malloc} } \\
2697    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/speed-3-malloc} }
2698\caption{Speed benchmark chain: malloc}
2699\label{fig:speed-3-malloc}
2700\end{figure}
2701
2702%speed-4-realloc.eps
2703\begin{figure}
2704\centering
2705    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/speed-4-realloc} } \\
2706    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/speed-4-realloc} }
2707\caption{Speed benchmark chain: realloc}
2708\label{fig:speed-4-realloc}
2709\end{figure}
2710
2711%speed-5-free.eps
2712\begin{figure}
2713\centering
2714    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/speed-5-free} } \\
2715    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/speed-5-free} }
2716\caption{Speed benchmark chain: free}
2717\label{fig:speed-5-free}
2718\end{figure}
2719
2720%speed-6-calloc.eps
2721\begin{figure}
2722\centering
2723    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/speed-6-calloc} } \\
2724    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/speed-6-calloc} }
2725\caption{Speed benchmark chain: calloc}
2726\label{fig:speed-6-calloc}
2727\end{figure}
2728
2729%speed-7-malloc-free.eps
2730\begin{figure}
2731\centering
2732    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/speed-7-malloc-free} } \\
2733    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/speed-7-malloc-free} }
2734\caption{Speed benchmark chain: malloc-free}
2735\label{fig:speed-7-malloc-free}
2736\end{figure}
2737
2738%speed-8-realloc-free.eps
2739\begin{figure}
2740\centering
2741    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/speed-8-realloc-free} } \\
2742    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/speed-8-realloc-free} }
2743\caption{Speed benchmark chain: realloc-free}
2744\label{fig:speed-8-realloc-free}
2745\end{figure}
2746
2747%speed-9-calloc-free.eps
2748\begin{figure}
2749\centering
2750    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/speed-9-calloc-free} } \\
2751    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/speed-9-calloc-free} }
2752\caption{Speed benchmark chain: calloc-free}
2753\label{fig:speed-9-calloc-free}
2754\end{figure}
2755
2756%speed-10-malloc-realloc.eps
2757\begin{figure}
2758\centering
2759    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/speed-10-malloc-realloc} } \\
2760    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/speed-10-malloc-realloc} }
2761\caption{Speed benchmark chain: malloc-realloc}
2762\label{fig:speed-10-malloc-realloc}
2763\end{figure}
2764
2765%speed-11-calloc-realloc.eps
2766\begin{figure}
2767\centering
2768    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/speed-11-calloc-realloc} } \\
2769    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/speed-11-calloc-realloc} }
2770\caption{Speed benchmark chain: calloc-realloc}
2771\label{fig:speed-11-calloc-realloc}
2772\end{figure}
2773
2774%speed-12-malloc-realloc-free.eps
2775\begin{figure}
2776\centering
2777    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/speed-12-malloc-realloc-free} } \\
2778    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/speed-12-malloc-realloc-free} }
2779\caption{Speed benchmark chain: malloc-realloc-free}
2780\label{fig:speed-12-malloc-realloc-free}
2781\end{figure}
2782
2783%speed-13-calloc-realloc-free.eps
2784\begin{figure}
2785\centering
2786    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/speed-13-calloc-realloc-free} } \\
2787    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/speed-13-calloc-realloc-free} }
2788\caption{Speed benchmark chain: calloc-realloc-free}
2789\label{fig:speed-13-calloc-realloc-free}
2790\end{figure}
2791
2792%speed-14-{m,c,re}alloc-free.eps
2793\begin{figure}
2794\centering
2795    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/speed-14-m-c-re-alloc-free} } \\
2796    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/speed-14-m-c-re-alloc-free} }
2797\caption{Speed benchmark chain: malloc-calloc-realloc-free}
2798\label{fig:speed-14-malloc-calloc-realloc-free}
2799\end{figure}
2800
2801%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2802%% MEMORY
2803%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2804
2805\newpage
2806\subsubsection{Memory Micro-Benchmark}
2807\label{s:MemoryMicroBenchmark}
2808
2809This experiment is run with the following two configurations for each allocator.
2810The difference between the two configurations is the number of producers and consumers.
2811Configuration 1 has one producer and one consumer, and configuration 2 has 4 producers, where each producer has 4 consumers.
2812
2813\noindent
2814Configuration 1:
2815\begin{description}[itemsep=0pt,parsep=0pt]
2816\item[producer (K):]
28171
2818\item[consumer (M):]
28191
2820\item[round:]
2821100,000
2822\item[max:]
2823500
2824\item[min:]
282550
2826\item[step:]
282750
2828\item[distro:]
2829fisher
2830\item[objects (N):]
2831100,000
2832\end{description}
2833
2834% -threadA :  1
2835% -threadF :  1
2836% -maxS    :  500
2837% -minS    :  50
2838% -stepS   :  50
2839% -distroS :  fisher
2840% -objN    :  100000
2841% -consumeS:  100000
2842
2843\noindent
2844Configuration 2:
2845\begin{description}[itemsep=0pt,parsep=0pt]
2846\item[producer (K):]
28474
2848\item[consumer (M):]
28494
2850\item[round:]
2851100,000
2852\item[max:]
2853500
2854\item[min:]
285550
2856\item[step:]
285750
2858\item[distro:]
2859fisher
2860\item[objects (N):]
2861100,000
2862\end{description}
2863
2864% -threadA :  4
2865% -threadF :  4
2866% -maxS    :  500
2867% -minS    :  50
2868% -stepS   :  50
2869% -distroS :  fisher
2870% -objN    :  100000
2871% -consumeS:  100000
2872
2873% \begin{table}[b]
2874% \centering
2875%     \begin{tabular}{ |c|c|c| }
2876%      \hline
2877%     Memory Allocator & Configuration 1 Result & Configuration 2 Result\\
2878%      \hline
2879%     llh & Figure~\ref{fig:mem-1-prod-1-cons-100-llh} & Figure~\ref{fig:mem-4-prod-4-cons-100-llh}\\
2880%      \hline
2881%     dl & Figure~\ref{fig:mem-1-prod-1-cons-100-dl} & Figure~\ref{fig:mem-4-prod-4-cons-100-dl}\\
2882%      \hline
2883%     glibc & Figure~\ref{fig:mem-1-prod-1-cons-100-glc} & Figure~\ref{fig:mem-4-prod-4-cons-100-glc}\\
2884%      \hline
2885%     hoard & Figure~\ref{fig:mem-1-prod-1-cons-100-hrd} & Figure~\ref{fig:mem-4-prod-4-cons-100-hrd}\\
2886%      \hline
2887%     je & Figure~\ref{fig:mem-1-prod-1-cons-100-je} & Figure~\ref{fig:mem-4-prod-4-cons-100-je}\\
2888%      \hline
2889%     pt3 & Figure~\ref{fig:mem-1-prod-1-cons-100-pt3} & Figure~\ref{fig:mem-4-prod-4-cons-100-pt3}\\
2890%      \hline
2891%     rp & Figure~\ref{fig:mem-1-prod-1-cons-100-rp} & Figure~\ref{fig:mem-4-prod-4-cons-100-rp}\\
2892%      \hline
2893%     tbb & Figure~\ref{fig:mem-1-prod-1-cons-100-tbb} & Figure~\ref{fig:mem-4-prod-4-cons-100-tbb}\\
2894%      \hline
2895%     \end{tabular}
2896% \caption{Memory benchmark results}
2897% \label{table:mem-benchmark-figs}
2898% \end{table}
2899% Table Section~\ref{table:mem-benchmark-figs} shows the list of figures that contain memory benchmark results.
2900
2901Figures~\ref{fig:mem-1-prod-1-cons-100-llh}{fig:mem-4-prod-4-cons-100-tbb} show 16 figures, two figures for each of the 8 allocators, one for each configuration.
2902Each figure has 2 graphs, one for each experiment environment.
2903Each graph has following 5 subgraphs that show memory usage and statistics throughout the micro-benchmark's lifetime.
2904\begin{itemize}[topsep=3pt,itemsep=2pt,parsep=0pt]
2905\item \textit{\textbf{current\_req\_mem(B)}} shows the amount of dynamic memory requested and currently in-use of the benchmark.
2906\item \textit{\textbf{heap}}* shows the memory requested by the program (allocator) from the system that lies in the heap (@sbrk@) area.
2907\item \textit{\textbf{mmap\_so}}* shows the memory requested by the program (allocator) from the system that lies in the @mmap@ area.
2908\item \textit{\textbf{mmap}}* shows the memory requested by the program (allocator or shared libraries) from the system that lies in the @mmap@ area.
2909\item \textit{\textbf{total\_dynamic}} shows the total usage of dynamic memory by the benchmark program, which is a sum of \textit{heap}, \textit{mmap}, and \textit{mmap\_so}.
2910\end{itemize}
2911* These statistics are gathered by monitoring a process's @/proc/self/maps@ file.
2912
2913The X-axis shows the time when the memory information is polled.
2914The Y-axis shows the memory usage in bytes.
2915
2916For this experiment, the difference between the memory requested by the benchmark (\textit{current\_req\_mem(B)}) and the memory that the process has received from system (\textit{heap}, \textit{mmap}) should be minimum.
2917This difference is the memory overhead caused by the allocator and shows the level of fragmentation in the allocator.
2918
2919\paragraph{Assessment}
2920First, the differences in the shape of the curves between architectures (top ARM, bottom x64) is small, where the differences are in the amount of memory used.
2921Hence, it is possible to focus on either the top or bottom graph.
2922
2923Second, the heap curve is 0 for four memory allocators: \textsf{hrd}, \textsf{je}, \textsf{pt3}, and \textsf{rp}, indicating these memory allocators only use @mmap@ to get memory from the system and ignore the @sbrk@ area.
2924
2925The total dynamic memory is higher for \textsf{hrd} and \textsf{tbb} than the other allocators.
2926The main reason is the use of superblocks (see Section~\ref{s:ObjectContainers}) containing objects of the same size.
2927These superblocks are maintained throughout the life of the program.
2928
2929\textsf{pt3} is the only memory allocator where the total dynamic memory goes down in the second half of the program lifetime when the memory is freed by the benchmark program.
2930It makes pt3 the only memory allocator that gives memory back to the OS as it is freed by the program.
2931
2932% FOR 1 THREAD
2933
2934%mem-1-prod-1-cons-100-llh.eps
2935\begin{figure}
2936\centering
2937    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-1-prod-1-cons-100-llh} } \\
2938    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-1-prod-1-cons-100-llh} }
2939\caption{Memory benchmark results with Configuration-1 for llh memory allocator}
2940\label{fig:mem-1-prod-1-cons-100-llh}
2941\end{figure}
2942
2943%mem-1-prod-1-cons-100-dl.eps
2944\begin{figure}
2945\centering
2946    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-1-prod-1-cons-100-dl} } \\
2947    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-1-prod-1-cons-100-dl} }
2948\caption{Memory benchmark results with Configuration-1 for dl memory allocator}
2949\label{fig:mem-1-prod-1-cons-100-dl}
2950\end{figure}
2951
2952%mem-1-prod-1-cons-100-glc.eps
2953\begin{figure}
2954\centering
2955    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-1-prod-1-cons-100-glc} } \\
2956    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-1-prod-1-cons-100-glc} }
2957\caption{Memory benchmark results with Configuration-1 for glibc memory allocator}
2958\label{fig:mem-1-prod-1-cons-100-glc}
2959\end{figure}
2960
2961%mem-1-prod-1-cons-100-hrd.eps
2962\begin{figure}
2963\centering
2964    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-1-prod-1-cons-100-hrd} } \\
2965    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-1-prod-1-cons-100-hrd} }
2966\caption{Memory benchmark results with Configuration-1 for hoard memory allocator}
2967\label{fig:mem-1-prod-1-cons-100-hrd}
2968\end{figure}
2969
2970%mem-1-prod-1-cons-100-je.eps
2971\begin{figure}
2972\centering
2973    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-1-prod-1-cons-100-je} } \\
2974    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-1-prod-1-cons-100-je} }
2975\caption{Memory benchmark results with Configuration-1 for je memory allocator}
2976\label{fig:mem-1-prod-1-cons-100-je}
2977\end{figure}
2978
2979%mem-1-prod-1-cons-100-pt3.eps
2980\begin{figure}
2981\centering
2982    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-1-prod-1-cons-100-pt3} } \\
2983    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-1-prod-1-cons-100-pt3} }
2984\caption{Memory benchmark results with Configuration-1 for pt3 memory allocator}
2985\label{fig:mem-1-prod-1-cons-100-pt3}
2986\end{figure}
2987
2988%mem-1-prod-1-cons-100-rp.eps
2989\begin{figure}
2990\centering
2991    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-1-prod-1-cons-100-rp} } \\
2992    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-1-prod-1-cons-100-rp} }
2993\caption{Memory benchmark results with Configuration-1 for rp memory allocator}
2994\label{fig:mem-1-prod-1-cons-100-rp}
2995\end{figure}
2996
2997%mem-1-prod-1-cons-100-tbb.eps
2998\begin{figure}
2999\centering
3000    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-1-prod-1-cons-100-tbb} } \\
3001    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-1-prod-1-cons-100-tbb} }
3002\caption{Memory benchmark results with Configuration-1 for tbb memory allocator}
3003\label{fig:mem-1-prod-1-cons-100-tbb}
3004\end{figure}
3005
3006% FOR 4 THREADS
3007
3008%mem-4-prod-4-cons-100-llh.eps
3009\begin{figure}
3010\centering
3011    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-4-prod-4-cons-100-llh} } \\
3012    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-4-prod-4-cons-100-llh} }
3013\caption{Memory benchmark results with Configuration-2 for llh memory allocator}
3014\label{fig:mem-4-prod-4-cons-100-llh}
3015\end{figure}
3016
3017%mem-4-prod-4-cons-100-dl.eps
3018\begin{figure}
3019\centering
3020    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-4-prod-4-cons-100-dl} } \\
3021    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-4-prod-4-cons-100-dl} }
3022\caption{Memory benchmark results with Configuration-2 for dl memory allocator}
3023\label{fig:mem-4-prod-4-cons-100-dl}
3024\end{figure}
3025
3026%mem-4-prod-4-cons-100-glc.eps
3027\begin{figure}
3028\centering
3029    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-4-prod-4-cons-100-glc} } \\
3030    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-4-prod-4-cons-100-glc} }
3031\caption{Memory benchmark results with Configuration-2 for glibc memory allocator}
3032\label{fig:mem-4-prod-4-cons-100-glc}
3033\end{figure}
3034
3035%mem-4-prod-4-cons-100-hrd.eps
3036\begin{figure}
3037\centering
3038    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-4-prod-4-cons-100-hrd} } \\
3039    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-4-prod-4-cons-100-hrd} }
3040\caption{Memory benchmark results with Configuration-2 for hoard memory allocator}
3041\label{fig:mem-4-prod-4-cons-100-hrd}
3042\end{figure}
3043
3044%mem-4-prod-4-cons-100-je.eps
3045\begin{figure}
3046\centering
3047    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-4-prod-4-cons-100-je} } \\
3048    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-4-prod-4-cons-100-je} }
3049\caption{Memory benchmark results with Configuration-2 for je memory allocator}
3050\label{fig:mem-4-prod-4-cons-100-je}
3051\end{figure}
3052
3053%mem-4-prod-4-cons-100-pt3.eps
3054\begin{figure}
3055\centering
3056    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-4-prod-4-cons-100-pt3} } \\
3057    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-4-prod-4-cons-100-pt3} }
3058\caption{Memory benchmark results with Configuration-2 for pt3 memory allocator}
3059\label{fig:mem-4-prod-4-cons-100-pt3}
3060\end{figure}
3061
3062%mem-4-prod-4-cons-100-rp.eps
3063\begin{figure}
3064\centering
3065    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-4-prod-4-cons-100-rp} } \\
3066        %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-4-prod-4-cons-100-rp} }
3067\caption{Memory benchmark results with Configuration-2 for rp memory allocator}
3068\label{fig:mem-4-prod-4-cons-100-rp}
3069\end{figure}
3070
3071%mem-4-prod-4-cons-100-tbb.eps
3072\begin{figure}
3073\centering
3074    %\subfloat[Algol]{ \includegraphics[width=0.9\textwidth]{evaluations/algol-perf-eps/mem-4-prod-4-cons-100-tbb} } \\
3075    %\subfloat[Nasus]{ \includegraphics[width=0.9\textwidth]{evaluations/nasus-perf-eps/mem-4-prod-4-cons-100-tbb} }
3076\caption{Memory benchmark results with Configuration-2 for tbb memory allocator}
3077\label{fig:mem-4-prod-4-cons-100-tbb}
3078\end{figure}
3079
3080
3081\section{Conclusion}
3082
3083% \noindent
3084% ====================
3085%
3086% Writing Points:
3087% \begin{itemize}
3088% \item
3089% Summarize u-benchmark suite.
3090% \item
3091% Summarize @uHeapLmmm@.
3092% \item
3093% Make recommendations on memory allocator design.
3094% \end{itemize}
3095%
3096% \noindent
3097% ====================
3098
3099The goal of this work was to build a low-latency (or high bandwidth) memory allocator for both KT and UT multi-threading systems that is competitive with the best current memory allocators while extending the feature set of existing and new allocator routines.
3100The new llheap memory-allocator achieves all of these goals, while maintaining and managing sticky allocation information without a performance loss.
3101Hence, it becomes possible to use @realloc@ frequently as a safe operation, rather than just occasionally.
3102Furthermore, the ability to query sticky properties and information allows programmers to write safer programs, as it is possible to dynamically match allocation styles from unknown library routines that return allocations.
3103
3104Extending the C allocation API with @resize@, advanced @realloc@, @aalloc@, @amemalign@, and @cmemalign@ means programmers do not have to do these useful allocation operations themselves.
3105The ability to use \CFA's advanced type-system (and possibly \CC's too) to have one allocation routine with completely orthogonal sticky properties shows how far the allocation API can be pushed, which increases safety and greatly simplifies programmer's use of dynamic allocation.
3106
3107Providing comprehensive statistics for all allocation operations is invaluable in understanding and debugging a program's dynamic behaviour.
3108No other memory allocator provides such comprehensive statistics gathering.
3109This capability was used extensively during the development of llheap to verify its behaviour.
3110As well, providing a debugging mode where allocations are checked, along with internal pre/post conditions and invariants, is extremely useful, especially for students.
3111While not as powerful as the @valgrind@ interpreter, a large number of allocation mistakes are detected.
3112Finally, contention-free statistics gathering and debugging have a low enough cost to be used in production code.
3113
3114The ability to compile llheap with static/dynamic linking and optional statistics/debugging provides programers with multiple mechanisms to balance performance and safety.
3115These allocator versions are easy to use because they can be linked to an application without recompilation.
3116
3117Starting a micro-benchmark test-suite for comparing allocators, rather than relying on a suite of arbitrary programs, has been an interesting challenge.
3118The current micro-benchmarks allow some understanding of allocator implementation properties without actually looking at the implementation.
3119For example, the memory micro-benchmark quickly identified how several of the allocators work at the global level.
3120It was not possible to show how the micro-benchmarks adjustment knobs were used to tune to an interesting test point.
3121Many graphs were created and discarded until a few were selected for the work.
3122
3123
3124\subsection{Future Work}
3125
3126A careful walk-though of the allocator fastpath should yield additional optimizations for a slight performance gain.
3127In particular, analysing the implementation of rpmalloc, which is often the fastest allocator,
3128
3129The micro-benchmark project requires more testing and analysis.
3130Additional allocation patterns are needed to extract meaningful information about allocators, and within allocation patterns, what are the most useful tuning knobs.
3131Also, identifying ways to visualize the results of the micro-benchmarks is a work in progress.
3132
3133After llheap is made available on GitHub, interacting with its users to locate problems and improvements will make llbench a more robust memory allocator.
3134As well, feedback from the \uC and \CFA projects, which have adopted llheap for their memory allocator, will provide additional information.
3135
3136
3137
3138\section{Acknowledgements}
3139
3140This research is funded by the NSERC/Waterloo-Huawei (\url{http://www.huawei.com}) Joint Innovation Lab. %, and Peter Buhr is partially funded by the Natural Sciences and Engineering Research Council of Canada.
3141
3142{%
3143\fontsize{9bp}{11.5bp}\selectfont%
3144\bibliography{pl,local}
3145}%
3146
3147\end{document}
3148
3149% Local Variables: %
3150% tab-width: 4 %
3151% fill-column: 120 %
3152% compile-command: "make" %
3153% End: %
Note: See TracBrowser for help on using the repository browser.