\chapter{Allocator}
\label{c:Allocator}

This chapter 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).
The new allocator fulfills the GNU C Library allocator API~\cite{GNUallocAPI}.


\section{llheap}

The 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.
(Large allocations requiring initialization, \eg zero fill, and/or copying are not covered by the low-latency objective.)
A direct consequence of this objective is very simple or no storage coalescing;
hence, llheap's design is willing to use more storage to lower latency.
This objective is apropos because systems research and industrial applications are striving for low latency and computers have huge amounts of RAM memory.
Finally, llheap's performance should be comparable with the current best allocators (see performance comparison in \VRef[Chapter]{c:Performance}).

% The objective of llheap's new design was to fulfill following requirements:
% \begin{itemize}
% \item It should be concurrent and thread-safe for multi-threaded programs.
% \item It should avoid global locks, on resources shared across all threads, as much as possible.
% \item It's performance (FIX ME: cite performance benchmarks) should be comparable to the commonly used allocators (FIX ME: cite common allocators).
% \item It should be a lightweight memory allocator.
% \end{itemize}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Design Choices}

llheap's design was reviewed and changed multiple times throughout the thesis.
Some of the rejected designs are discussed because they show the path to the final design (see discussion in \VRef{s:MultipleHeaps}).
Note, a few simple tests for a design choice were compared with the current best allocators to determine the viability of a design.


\subsection{Allocation Fastpath}
\label{s:AllocationFastpath}

These designs look at the allocation/free \newterm{fastpath}, \ie when an allocation can immediately return free storage or returned storage is not coalesced.
\paragraph{T:1 model}
\VRef[Figure]{f:T1SharedBuckets} shows one heap accessed by multiple kernel threads (KTs) using a bucket array, where smaller bucket sizes are shared among N KTs.
This design leverages the fact that usually the allocation requests are less than 1024 bytes and there are only a few different request sizes.
When KTs $\le$ N, the common bucket sizes are uncontented;
when KTs $>$ N, the free buckets are contented and latency increases significantly.
In all cases, a KT must acquire/release a lock, contented or uncontented, along the fast allocation path because a bucket is shared.
Therefore, while threads are contending for a small number of buckets sizes, the buckets are distributed among them to reduce contention, which lowers latency;
however, picking N is workload specific.

\begin{figure}
\centering
\input{AllocDS1}
\caption{T:1 with Shared Buckets}
\label{f:T1SharedBuckets}
\end{figure}

Problems:
\begin{itemize}
\item
Need to know when a KT is created/destroyed to assign/unassign a shared bucket-number from the memory allocator.
\item
When no thread is assigned a bucket number, its free storage is unavailable.
\item
All KTs contend for the global-pool lock for initial allocations, before free-lists get populated.
\end{itemize}
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.

\paragraph{T:H model}
\VRef[Figure]{f:THSharedHeaps} shows a fixed number of heaps (N), each a local free pool, where the heaps are sharded (distributed) across the KTs.
A KT can point directly to its assigned heap or indirectly through the corresponding heap bucket.
When KT $\le$ N, the heaps might be uncontented;
when KTs $>$ N, the heaps are contented.
In all cases, a KT must acquire/release a lock, contented or uncontented along the fast allocation path because a heap is shared.
By increasing N, this approach reduces contention but increases storage (time versus space);
however, picking N is workload specific.

\begin{figure}
\centering
\input{AllocDS2}
\caption{T:H with Shared Heaps}
\label{f:THSharedHeaps}
\end{figure}

Problems:
\begin{itemize}
\item
Need to know when a KT is created/destroyed to assign/unassign a heap from the memory allocator.
\item
When no thread is assigned to a heap, its free storage is unavailable.
\item
Ownership issues arise (see \VRef{s:Ownership}).
\item
All KTs contend for the local/global-pool lock for initial allocations, before free-lists get populated.
\end{itemize}
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.

\paragraph{T:H model, H = number of CPUs}
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@.
(See \VRef[Figure]{f:THSharedHeaps} but with a heap bucket per CPU.)
Hence, each CPU logically has its own private heap and local pool.
A memory operation is serviced from the heap associated with the CPU executing the operation.
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).
This approach is essentially an M:N approach where M is the number if KTs and N is the number of CPUs.

Problems:
\begin{itemize}
\item
Need to know when a CPU is added/removed from the @taskset@.
\item
Need a fast way to determine the CPU a KT is executing on to access the appropriate heap.
\item
Need to prevent preemption during a dynamic memory operation because of the \newterm{serially-reusable problem}.
\begin{quote}
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}
\end{quote}
If a KT is preempted during an allocation operation, the operating system 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.
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.
Essentially, the serially-reusable problem is a race condition on an unprotected critical section, where the operating system is providing the second thread via the signal handler.

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 section after undoing its writes, if the critical section is preempted.
\end{itemize}
Tests showed that @librseq@ can determine the particular CPU quickly but setting up the restartable critical-section along the allocation fast-path produced a significant increase in allocation costs.
Also, the number of undoable writes in @librseq@ is limited and restartable sequences cannot deal with user-level thread (UT) migration across KTs.
For example, UT$_1$ is executing a memory operation by KT$_1$ on CPU$_1$ and a time-slice preemption occurs.
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.
Since KT$_1$ is still executing on CPU$_1$, @librseq@ takes no action because it assumes KT$_1$ is still executing the same critical section.
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.
If @librseq@ had an @rseq_abort@ which:
\begin{enumerate}
\item
Marked the current restartable critical-section as cancelled so it restarts when attempting to commit.
\item
Do nothing if there is no current restartable critical section in progress.
\end{enumerate}
Then @rseq_abort@ could be called on the backside of a  user-level context-switching.
A feature similar to this idea might exist for hardware transactional-memory.
A significant effort was made to make this approach work but its complexity, lack of robustness, and performance costs resulted in its rejection.

\paragraph{1:1 model}
This design is the T:H model with T = H, where there is one thread-local heap for each KT.
(See \VRef[Figure]{f:THSharedHeaps} but with a heap bucket per KT and no bucket or local-pool lock.)
Hence, immediately after a KT starts, its heap is created and just before a KT terminates, its heap is (logically) deleted.
Heaps are uncontended for a KTs memory operations as every KT has its own thread-local heap, modulo operations on the global pool and ownership.

Problems:
\begin{itemize}
\item
Need to know when a KT starts/terminates to create/delete its heap.

\noindent
It is possible to leverage constructors/destructors for thread-local objects to get a general handle on when a KT starts/terminates.
\item
There is a classic \newterm{memory-reclamation} problem for ownership because storage passed to another thread can be returned to a terminated heap.

\noindent
The classic solution only deletes a heap after all referents are returned, which is complex.
The cheap alternative is for heaps to persist for program duration to handle outstanding referent frees.
If old referents return storage to a terminated heap, it is handled in the same way as an active heap.
To 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).
In 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.
\item
There can be significant external fragmentation as the number of KTs increases.

\noindent
In many concurrent applications, good performance is achieved with the number of KTs proportional to the number of CPUs.
Since 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.
\item
There is the same serially-reusable problem with UTs migrating across KTs.
\end{itemize}
Tests 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.


\vspace{5pt}
\noindent
The conclusion from this design exercise is: any atomic fence, atomic instruction (lock free), or lock along the allocation fastpath produces significant slowdown.
For 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.
For the T:H=CPU and 1:1 models, locking is eliminated along the allocation fastpath.
However, T:H=CPU has poor operating-system support to determine the CPU id (heap id) and prevent the serially-reusable problem for KTs.
More operating system support is required to make this model viable, but there is still the serially-reusable problem with user-level threading.
So the 1:1 model had no atomic actions along the fastpath and no special operating-system support requirements.
The 1:1 model still has the serially-reusable problem with user-level threading, which is addressed in \VRef{s:UserlevelThreadingSupport}, and the greatest potential for heap blowup for certain allocation patterns.


% \begin{itemize}
% \item
% 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.
% \item
% 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.
% \item
% 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.
% 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.
% \end{itemize}
% Of the four designs for a low-latency memory allocator, the 1:1 model was chosen for the following reasons:

% \subsection{Advantages of distributed design}
% 
% The distributed design of llheap is concurrent to work in multi-threaded applications.
% Some key benefits of the distributed design of llheap are as follows:
% \begin{itemize}
% \item
% 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.
% \item
% Low or almost no contention on heap resources.
% \item
% It is possible to use sharing and stealing techniques to share/find unused storage, when a free list is unused or empty.
% \item
% Distributed design avoids unnecessary locks on resources shared across all KTs.
% \end{itemize}

\subsection{Allocation Latency}

A primary goal of llheap is low latency.
Two forms of latency are internal and external.
Internal latency is the time to perform an allocation, while external latency is time to obtain/return storage from/to the operating system.
Ideally latency is $O(1)$ with a small constant.

To obtain $O(1)$ internal latency means no searching on the allocation fastpath and largely prohibits coalescing, which leads to external fragmentation.
The 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).

To obtain $O(1)$ external latency means obtaining one large storage area from the operating system and subdividing it across all program allocations, which requires a good guess at the program storage high-watermark and potential large external fragmentation.
Excluding real-time operating-systems, operating-system operations are unbounded, and hence some external latency is unavoidable.
The 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@ \VPageref{p:malloc_expansion}).
Furthermore, while operating-system calls are unbounded, many are now reasonably fast, so their latency is tolerable and infrequent.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{llheap Structure}

\VRef[Figure]{f:llheapStructure} shows the design of llheap, which uses the following features:
\begin{itemize}
\item
1:1 multiple-heap model to minimize the fastpath,
\item
can be built with or without heap ownership,
\item
headers per allocation versus containers,
\item
no coalescing to minimize latency,
\item
global heap memory (pool) obtained from the operating system using @mmap@ to create and reuse heaps needed by threads,
\item
local reserved memory (pool) per heap obtained from global pool,
\item
global reserved memory (pool) obtained from the operating system using @sbrk@ call,
\item
optional fast-lookup table for converting allocation requests into bucket sizes,
\item
optional statistic-counters table for accumulating counts of allocation operations.
\end{itemize}

\begin{figure}
\centering
% \includegraphics[width=0.65\textwidth]{figures/NewHeapStructure.eps}
\input{llheap}
\caption{llheap Structure}
\label{f:llheapStructure}
\end{figure}

llheap 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.
There is a global bump-pointer to the next free heap in the array.
When this array is exhausted, another array of heaps is allocated.
There is a global top pointer for a intrusive linked-list to chain free heaps from terminated threads.
When 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@.

When a KT starts, a heap is allocated from the current array for exclusive use by the KT.
When 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.
The free heaps are stored on stack so hot storage is reused first.
Preserving all heaps, created during the program lifetime, solves the storage lifetime problem when ownership is used.
This approach wastes storage if a large number of KTs are created/terminated at program start and then the program continues sequentially.
llheap 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.

Each heap uses segregated free-buckets that have free objects distributed across 91 different sizes from 16 to 4M.
All objects in a bucket are of the same size.
The 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 operating system.
Each free bucket of a specific size has the following two lists:
\begin{itemize}
\item
A free stack used solely by the KT heap-owner, so push/pop operations do not require locking.
The free objects are a stack so hot storage is reused first.
\item
For ownership, a shared away-stack for KTs to return storage allocated by other KTs, so push/pop operations require locking.
When the free stack is empty, the entire ownership stack is removed and becomes the head of the corresponding free stack.
\end{itemize}

Algorithm~\ref{alg:heapObjectAlloc} shows the allocation outline for an object of size $S$.
First, the allocation is divided into small (@sbrk@) or large (@mmap@).
For large allocations, the storage is mapped directly from the operating system.
For small allocations, $S$ is quantized into a bucket size.
Quantizing is performed using a binary search over the ordered bucket array.
An 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.
The @char@ type restricts the number of bucket sizes to 256.
For $S$ > 64K, a binary search is used.
Then, the allocation storage is obtained from the following locations (in order), with increasing latency.
\begin{enumerate}[topsep=0pt,itemsep=0pt,parsep=0pt]
\item
bucket's free stack,
\item
bucket's away stack,
\item
heap's local pool
\item
global pool
\item
operating system (@sbrk@)
\end{enumerate}

\begin{figure}
\vspace*{-10pt}
\begin{algorithm}[H]
\small
\caption{Dynamic object allocation of size $S$}\label{alg:heapObjectAlloc}
\begin{algorithmic}[1]
\State $\textit{O} \gets \text{NULL}$
\If {$S >= \textit{mmap-threshhold}$}
	\State $\textit{O} \gets \text{allocate dynamic memory using system call mmap with size S}$
\Else
	\State $\textit{B} \gets \text{smallest free-bucket} \geq S$
	\If {$\textit{B's free-list is empty}$}
		\If {$\textit{B's away-list is empty}$}
			\If {$\textit{heap's allocation buffer} < S$}
				\State $\text{get allocation from global pool (which might call \lstinline{sbrk})}$
			\EndIf
			\State $\textit{O} \gets \text{bump allocate an object of size S from allocation buffer}$
		\Else
			\State $\textit{merge B's away-list into free-list}$
			\State $\textit{O} \gets \text{pop an object from B's free-list}$
		\EndIf
	\Else
		\State $\textit{O} \gets \text{pop an object from B's free-list}$
	\EndIf
	\State $\textit{O's owner} \gets \text{B}$
\EndIf
\State $\Return \textit{ O}$
\end{algorithmic}
\end{algorithm}

\vspace*{-15pt}
\begin{algorithm}[H]
\small
\caption{Dynamic object free at address $A$ with object ownership}\label{alg:heapObjectFreeOwn}
\begin{algorithmic}[1]
\If {$\textit{A mapped allocation}$}
	\State $\text{return A's dynamic memory to system using system call \lstinline{munmap}}$
\Else
	\State $\text{B} \gets \textit{O's owner}$
	\If {$\textit{B is thread-local heap's bucket}$}
		\State $\text{push A to B's free-list}$
	\Else
		\State $\text{push A to B's away-list}$
	\EndIf
\EndIf
\end{algorithmic}
\end{algorithm}

\vspace*{-15pt}
\begin{algorithm}[H]
\small
\caption{Dynamic object free at address $A$ without object ownership}\label{alg:heapObjectFreeNoOwn}
\begin{algorithmic}[1]
\If {$\textit{A mapped allocation}$}
	\State $\text{return A's dynamic memory to system using system call \lstinline{munmap}}$
\Else
	\State $\text{B} \gets \textit{O's owner}$
	\If {$\textit{B is thread-local heap's bucket}$}
		\State $\text{push A to B's free-list}$
	\Else
		\State $\text{C} \gets \textit{thread local heap's bucket with same size as B}$
		\State $\text{push A to C's free-list}$
	\EndIf
\EndIf
\end{algorithmic}
\end{algorithm}
\end{figure}

Algorithm~\ref{alg:heapObjectFreeOwn} shows the de-allocation (free) outline for an object at address $A$ with ownership.
First, the address is divided into small (@sbrk@) or large (@mmap@).
For large allocations, the storage is unmapped back to the operating system.
For small allocations, the bucket associated with the request size is retrieved.
If the bucket is local to the thread, the allocation is pushed onto the thread's associated bucket.
If the bucket is not local to the thread, the allocation is pushed onto the owning thread's associated away stack.

Algorithm~\ref{alg:heapObjectFreeNoOwn} shows the de-allocation (free) outline for an object at address $A$ without ownership.
The algorithm is the same as for ownership except if the bucket is not local to the thread.
Then the corresponding bucket of the owner thread is computed for the deallocating thread, and the allocation is pushed onto the deallocating thread's bucket.

Finally, 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.
Other 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.
This design simplifies heap-management code during development and maintenance.


\subsection{Alignment}

Most dynamic memory allocations have a minimum storage alignment for the contained object(s).
Often 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).
In general, the minimum storage alignment is 8/16-byte boundary on 32/64-bit computers.
For consistency, the object header is normally aligned at this same boundary.
Larger alignments must be a power of 2, such as page alignment (4/8K).
Any alignment request, N, $\le$ the minimum alignment is handled as a normal allocation with minimal alignment.

For 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'@.
\begin{center}
\input{Alignment1}
\end{center}
The storage between @E@ and @H@ is chained onto the appropriate free list for future allocations.
The 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.
In 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.
However, if there are a large number of aligned requests, this approach leads to memory fragmentation from the small free areas around the aligned object.
As well, it does not work for large allocations, where many memory allocators switch from program @sbrk@ to operating-system @mmap@.
The 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.
Finally, 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.

Instead, 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:
\begin{center}
\input{Alignment2}
\end{center}
The 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.
The 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@.
For this special case, there is @alignment - M@ bytes of unused storage after the data object, which subsequently can be used by @realloc@.

Note, the address returned is @A@, which is subsequently returned to @free@.
However, to correctly free the allocated object, the value @P@ must be computable, since that is the value generated by @malloc@ and returned within @memalign@.
Hence, there must be a mechanism to detect when @P@ $\neq$ @A@ and how to compute @P@ from @A@.

The llheap approach uses two headers:
the \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.:
\begin{center}
\input{Alignment2Impl}
\end{center}
Since @malloc@ has a minimum alignment of @M@, @P@ $\neq$ @A@ only holds for alignments greater than @M@.
When @P@ $\neq$ @A@, the minimum distance between @P@ and @A@ is @M@ bytes, due to the pessimistic storage-allocation.
Therefore, there is always room for an @M@-byte fake header before @A@.

The fake header must supply an indicator to distinguish it from a normal header and the location of address @P@ generated by @malloc@.
This information is encoded as an offset from A to P and the initialize alignment (discussed in \VRef{s:ReallocStickyProperties}).
To 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.
\begin{center}
\input{FakeHeader}
\end{center}


\subsection{\lstinline{realloc} and Sticky Properties}
\label{s:ReallocStickyProperties}

The 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.
\begin{flushleft}
\begin{tabular}{ll}
\multicolumn{1}{c}{\textbf{realloc pattern}} & \multicolumn{1}{c}{\textbf{manually}} \\
\begin{lstlisting}
T * naddr = realloc( oaddr, newSize );



\end{lstlisting}
&
\begin{lstlisting}
T * naddr = (T *)malloc( newSize ); $\C[2.4in]{// new storage}$
memcpy( naddr, addr, oldSize );	 $\C{// copy old bytes}$
free( addr );				$\C{// free old storage}$
addr = naddr;				$\C{// change pointer}\CRT$
\end{lstlisting}
\end{tabular}
\end{flushleft}
The realloc pattern leverages available storage at the end of an allocation due to bucket sizes, possibly eliminating a new allocation and copying.
This pattern is not used enough to reduce storage management costs.
In fact, if @oaddr@ is @nullptr@, @realloc@ does a @malloc@, so even the initial @malloc@ can be a @realloc@ for consistency in the allocation pattern.

The hidden problem for this pattern is the effect of zero fill and alignment with respect to reallocation.
Are these properties transient or persistent (``sticky'')?
For 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?
That is, if @realloc@ logically extends storage into unused bucket space or allocates new storage to satisfy a size change, are initial allocation properties preserved?
Currently, 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.
This silent problem is unintuitive to programmers and difficult to locate because it is transient.
To 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.
This change makes the realloc pattern efficient and safe.


\subsection{Header}

To preserve allocation properties requires storing additional information with an allocation,
The best available option is the header, where \VRef[Figure]{f:llheapNormalHeader} shows the llheap storage layout.
The header has two data field sized appropriately for 32/64-bit alignment requirements.
The first field is a union of three values:
\begin{description}
\item[bucket pointer]
is for allocated storage and points back to the bucket associated with this storage requests (see \VRef[Figure]{f:llheapStructure} for the fields accessible in a bucket).
\item[mapped size]
is for mapped storage and is the storage size for use in unmapping.
\item[next free block]
is for free storage and is an intrusive pointer chaining same-size free blocks onto a bucket's free stack.
\end{description}
The second field remembers the request size versus the allocation (bucket) size, \eg request 42 bytes which is rounded up to 64 bytes.
Since 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.

\begin{figure}
\centering
\input{Header}
\caption{llheap Normal Header}
\label{f:llheapNormalHeader}
\end{figure}

The 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.
The 3 unused bits are used to represent mapped allocation, zero filled, and alignment, respectively.
Note, the alignment bit is not used in the normal header and the zero-filled/mapped bits are not used in the fake header.
This implementation allows a fast test if any of the lower 3-bits are on (@&@ and compare).
If no bits are on, it implies a basic allocation, which is handled quickly;
otherwise, the bits are analysed and appropriate actions are taken for the complex cases.
Since most allocations are basic, they will take significantly less time as the memory operations will be done along the allocation and free fastpath.


\section{Statistics and Debugging}

llheap can be built to accumulate fast and largely contention-free allocation statistics to help understand allocation behaviour.
Incrementing statistic counters must appear on the allocation fastpath.
As noted, any atomic operation along the fastpath produces a significant increase in allocation costs.
To 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.

To locate all statistic counters, heaps are linked together in statistics mode, and this list is locked and traversed to sum all counters across heaps.
Note, the list is locked to prevent errors traversing an active list;
the statistics counters are not locked and can flicker during accumulation.
\VRef[Figure]{f:StatiticsOutput} shows an example of statistics output, which covers all allocation operations and information about deallocating storage not owned by a thread.
No other memory allocator studied provides as comprehensive statistical information.
Finally, these statistics were invaluable during the development of this thesis for debugging and verifying correctness and should be equally valuable to application developers.

\begin{figure}
\begin{lstlisting}
Heap statistics: (storage request / allocation)
  malloc >0 calls 2,766; 0 calls 2,064; storage 12,715 / 13,367 bytes
  aalloc >0 calls 0; 0 calls 0; storage 0 / 0 bytes
  calloc >0 calls 6; 0 calls 0; storage 1,008 / 1,104 bytes
  memalign >0 calls 0; 0 calls 0; storage 0 / 0 bytes
  amemalign >0 calls 0; 0 calls 0; storage 0 / 0 bytes
  cmemalign >0 calls 0; 0 calls 0; storage 0 / 0 bytes
  resize >0 calls 0; 0 calls 0; storage 0 / 0 bytes
  realloc >0 calls 0; 0 calls 0; storage 0 / 0 bytes
  free !null calls 2,766; null calls 4,064; storage 12,715 / 13,367 bytes
  away pulls 0; pushes 0; storage 0 / 0 bytes
  sbrk calls 1; storage 10,485,760 bytes
  mmap calls 10,000; storage 10,000 / 10,035 bytes
  munmap calls 10,000; storage 10,000 / 10,035 bytes
  threads started 4; exited 3
  heaps new 4; reused 0
\end{lstlisting}
\caption{Statistics Output}
\label{f:StatiticsOutput}
\end{figure}

llheap can also be built with debug checking, which inserts many asserts along all allocation paths.
These assertions detect incorrect allocation usage, like double frees, unfreed storage, or memory corruptions because internal values (like header fields) are overwritten.
These checks are best effort as opposed to complete allocation checking as in @valgrind@.
Nevertheless, the checks detect many allocation problems.
There 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.
For example, @printf@ allocates a 1024-byte buffer on the first call and never deletes this buffer.
To prevent a false positive for unfreed storage, it is possible to specify an amount of storage that is never freed (see @malloc_unfreed@ \VPageref{p:malloc_unfreed}), and it is subtracted from the total allocate/free difference.
Determining the amount of never-freed storage is annoying, but once done, any warnings of unfreed storage are application related.

Tests 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.


\section{User-level Threading Support}
\label{s:UserlevelThreadingSupport}

The serially-reusable problem (see \VPageref{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.
The solution is to prevent interrupts that can result in a CPU or KT change during operations that are logically critical sections such as starting a memory operation on one KT and completing it on another.
Locking these critical sections negates any attempt for a quick fastpath and results in high contention.
For 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.
Without time slicing, a user thread performing a long computation can prevent the execution of (starve) other threads.
To prevent starvation for a memory-allocation-intensive thread, \ie the time slice always triggers in an allocation critical-section 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.
The rollforward flag is tested at the end of each allocation funnel routine (see \VPageref{p:FunnelRoutine}), and if set, it is reset and a volunteer yield (context switch) is performed to allow other threads to execute.

llheap 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.
On 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.
On the fastpath, disabling/enabling interrupts is too expensive as accessing kernel-thread-local storage can be expensive and not user-thread-safe.
For example, the ARM processor stores the thread-local pointer in a coprocessor register that cannot perform atomic base-displacement addressing.
Hence, 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.

The fast technique (with lower run time cost) is to define a special code section and places all non-interruptible routines in this section.
The linker places all code in this section into a contiguous block of memory, but the order of routines within the block is unspecified.
Then, the signal handler compares the program counter at the point of interrupt with the the start and end address of the non-interruptible section, and aborts if executing within this section and sets the rollforward flag.
This technique is fragile because any calls in the non-interruptible code outside of the non-interruptible section (like @sbrk@) must be bracketed with disable/enable interrupts and these calls must be along the slowpath.
Hence, for correctness, this approach requires inspection of generated assembler code for routines placed in the non-interruptible section.
This issue is mitigated by the llheap funnel design so only funnel routines and a few statistics routines are placed in the non-interruptible section and their assembler code examined.
These techniques are used in both the \uC and \CFA versions of llheap as both of these systems have user-level threading.


\section{Bootstrapping}

There are problems bootstrapping a memory allocator.
\begin{enumerate}
\item
Programs can be statically or dynamically linked.
\item
The order in which the linker schedules startup code is poorly supported so it cannot be controlled entirely.
\item
Knowing a KT's start and end independently from the KT code is difficult.
\end{enumerate}

For static linking, the allocator is loaded with the program.
Hence, allocation calls immediately invoke the allocator operation defined by the loaded allocation library and there is only one memory allocator used in the program.
This approach allows allocator substitution by placing an allocation library before any other in the linked/load path.

Allocator 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.
As 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.
Hence, some part of the @sbrk@ area may be used by the default allocator and statistics about allocation operations cannot be correct.
Furthermore, dynamic linking goes through trampolines, so there is an additional cost along the allocator fastpath for all allocation operations.
Testing 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.

All allocator libraries need to perform startup code to initialize data structures, such as the heap array for llheap.
The problem is getting initialization done before the first allocator call.
However, 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.
Also, initialization code of other libraries and the run-time environment may call memory allocation routines such as \lstinline{malloc}.
This 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.
As a result, calls to allocation routines occur without initialization.
To deal with this problem, it is necessary to put a conditional initialization check along the allocation fastpath to trigger initialization (singleton pattern).

Two other important execution points are program startup and termination, which include prologue or epilogue code to bootstrap a program, which programmers are unaware of.
For example, dynamic-memory allocations before/after the application starts should not be considered in statistics because the application does not make these calls.
llheap establishes these two points using routines:
\begin{lstlisting}
__attribute__(( constructor( 100 ) )) static void startup( void ) {
	// clear statistic counters
	// reset allocUnfreed counter
}
__attribute__(( destructor( 100 ) )) static void shutdown( void ) {
	// sum allocUnfreed for all heaps
	// subtract global unfreed storage
	// if allocUnfreed > 0 then print warning message
}
\end{lstlisting}
which use global constructor/destructor priority 100, where the linker calls these routines at program prologue/epilogue in increasing/decreasing order of priority.
Application programs may only use global constructor/destructor priorities greater than 100.
Hence, @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.
By resetting counters in @startup@, prologue allocations are ignored, and checking unfreed storage in @shutdown@ checks only application memory management, ignoring the program epilogue.

While @startup@/@shutdown@ apply to the program KT, a concurrent program creates additional KTs that do not trigger these routines.
However, it is essential for the allocator to know when each KT is started/terminated.
One 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.
\begin{lstlisting}
struct ThreadManager {
	volatile bool pgm_thread;
	ThreadManager() {} // unusable
	~ThreadManager() { if ( pgm_thread ) heapManagerDtor(); }
};
static thread_local ThreadManager threadManager;
\end{lstlisting}
Unfortunately, thread-local variables are created lazily, \ie on the first dereference of @threadManager@, which then triggers its constructor.
Therefore, 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.
Fortunately, 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.
Now 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.
The conditional destructor call prevents closing down the program heap, which must remain available because epilogue code may free more storage.

Finally, 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.
This recursion is handled with another thread-local flag to prevent double initialization.
A 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@.
In 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.

For 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.
The following API was created to provide interaction between the language runtime and the allocator.
\begin{lstlisting}
void startThread();			$\C{// KT starts}$
void finishThread();			$\C{// KT ends}$
void startup();				$\C{// when application code starts}$
void shutdown();			$\C{// when application code ends}$
bool traceHeap();			$\C{// enable allocation/free printing for debugging}$
bool traceHeapOn();			$\C{// start printing allocation/free calls}$
bool traceHeapOff();			$\C{// stop printing allocation/free calls}$
\end{lstlisting}
This kind of API is necessary to allow concurrent runtime systems to interact with different memory allocators in a consistent way.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section{Added Features and Methods}

The C dynamic-allocation API (see \VRef[Figure]{f:CDynamicAllocationAPI}) is neither orthogonal nor complete.
For example,
\begin{itemize}
\item
It is possible to zero fill or align an allocation but not both.
\item
It is \emph{only} possible to zero fill an array allocation.
\item
It is not possible to resize a memory allocation without data copying.
\item
@realloc@ does not preserve initial allocation properties.
\end{itemize}
As a result, programmers must provide these options, which is error prone, resulting in blaming the entire programming language for a poor dynamic-allocation API.
Furthermore, newer programming languages have better type systems that can provide safer and more powerful APIs for memory allocation.

\begin{figure}
\begin{lstlisting}
void * malloc( size_t size );
void * calloc( size_t nmemb, size_t size );
void * realloc( void * ptr, size_t size );
void * reallocarray( void * ptr, size_t nmemb, size_t size );
void free( void * ptr );
void * memalign( size_t alignment, size_t size );
void * aligned_alloc( size_t alignment, size_t size );
int posix_memalign( void ** memptr, size_t alignment, size_t size );
void * valloc( size_t size );
void * pvalloc( size_t size );

struct mallinfo mallinfo( void );
int mallopt( int param, int val );
int malloc_trim( size_t pad );
size_t malloc_usable_size( void * ptr );
void malloc_stats( void );
int malloc_info( int options, FILE * fp );
\end{lstlisting}
\caption{C Dynamic-Allocation API}
\label{f:CDynamicAllocationAPI}
\end{figure}

The following presents design and API changes for C, \CC (\uC), and \CFA, all of which are implemented in llheap.


\subsection{Out of Memory}

Most allocators use @nullptr@ to indicate an allocation failure, specifically out of memory;
hence the need to return an alternate value for a zero-sized allocation.
A different approach allowed by @C API@ is to abort a program when out of memory and return @nullptr@ for a zero-sized allocation.
In theory, notifying the programmer of memory failure allows recovery;
in practice, it is almost impossible to gracefully recover when out of memory.
Hence, the cheaper approach of returning @nullptr@ for a zero-sized allocation is chosen because no pseudo allocation is necessary.


\subsection{C Interface}

For C, it is possible to increase functionality and orthogonality of the dynamic-memory API to make allocation better for programmers.

For existing C allocation routines:
\begin{itemize}
\item
@calloc@ sets the sticky zero-fill property.
\item
@memalign@, @aligned_alloc@, @posix_memalign@, @valloc@ and @pvalloc@ set the sticky alignment property.
\item
@realloc@ and @reallocarray@ preserve sticky properties.
\end{itemize}

The C dynamic-memory API is extended with the following routines:

\paragraph{\lstinline{void * aalloc( size_t dim, size_t elemSize )}}
extends @calloc@ for allocating a dynamic array of objects without calculating the total size of array explicitly but \emph{without} zero-filling the memory.
@aalloc@ is significantly faster than @calloc@, which is the only alternative given by the standard memory-allocation routines.

\noindent\textbf{Usage}
@aalloc@ takes two parameters.
\begin{itemize}
\item
@dim@: number of array objects
\item
@elemSize@: size of array object
\end{itemize}
It returns the address of the dynamic array or @NULL@ if either @dim@ or @elemSize@ are zero.

\paragraph{\lstinline{void * resize( void * oaddr, size_t size )}}
extends @realloc@ for resizing an existing allocation \emph{without} copying previous data into the new allocation or preserving sticky properties.
@resize@ is significantly faster than @realloc@, which is the only alternative.

\noindent\textbf{Usage}
@resize@ takes two parameters.
\begin{itemize}
\item
@oaddr@: address to be resized
\item
@size@: new allocation size (smaller or larger than previous)
\end{itemize}
It returns the address of the old or new storage with the specified new size or @NULL@ if @size@ is zero.

\paragraph{\lstinline{void * amemalign( size_t alignment, size_t dim, size_t elemSize )}}
extends @aalloc@ and @memalign@ for allocating an aligned dynamic array of objects.
Sets sticky alignment property.

\noindent\textbf{Usage}
@amemalign@ takes three parameters.
\begin{itemize}
\item
@alignment@: alignment requirement
\item
@dim@: number of array objects
\item
@elemSize@: size of array object
\end{itemize}
It returns the address of the aligned dynamic-array or @NULL@ if either @dim@ or @elemSize@ are zero.

\paragraph{\lstinline{void * cmemalign( size_t alignment, size_t dim, size_t elemSize )}}
extends @amemalign@ with zero fill and has the same usage as @amemalign@.
Sets sticky zero-fill and alignment property.
It returns the address of the aligned, zero-filled dynamic-array or @NULL@ if either @dim@ or @elemSize@ are zero.

\paragraph{\lstinline{size_t malloc_alignment( void * addr )}}
returns the alignment of the dynamic object for use in aligning similar allocations.

\noindent\textbf{Usage}
@malloc_alignment@ takes one parameter.
\begin{itemize}
\item
@addr@: address of an allocated object.
\end{itemize}
It returns the alignment of the given object, where objects not allocated with alignment return the minimal allocation alignment.

\paragraph{\lstinline{bool malloc_zero_fill( void * addr )}}
returns true if the object has the zero-fill sticky property for use in zero filling similar allocations.

\noindent\textbf{Usage}
@malloc_zero_fill@ takes one parameters.

\begin{itemize}
\item
@addr@: address of an allocated object.
\end{itemize}
It returns true if the zero-fill sticky property is set and false otherwise.

\paragraph{\lstinline{size_t malloc_size( void * addr )}}
returns the request size of the dynamic object (updated when an object is resized) for use in similar allocations.
See also @malloc_usable_size@.

\noindent\textbf{Usage}
@malloc_size@ takes one parameters.
\begin{itemize}
\item
@addr@: address of an allocated object.
\end{itemize}
It returns the request size or zero if @addr@ is @NULL@.

\paragraph{\lstinline{int malloc_stats_fd( int fd )}}
changes the file descriptor where @malloc_stats@ writes statistics (default @stdout@).

\noindent\textbf{Usage}
@malloc_stats_fd@ takes one parameters.
\begin{itemize}
\item
@fd@: file descriptor.
\end{itemize}
It returns the previous file descriptor.

\paragraph{\lstinline{size_t malloc_expansion()}}
\label{p:malloc_expansion}
set the amount (bytes) to extend the heap when there is insufficient free storage to service an allocation request.
It 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.

\paragraph{\lstinline{size_t malloc_mmap_start()}}
set the crossover between allocations occurring in the @sbrk@ area or separately mapped.
It returns the crossover point used throughout a program, \ie called once at heap initialization.

\paragraph{\lstinline{size_t malloc_unfreed()}}
\label{p:malloc_unfreed}
amount subtracted to adjust for unfreed program storage (debug only).
It returns the new subtraction amount and called by @malloc_stats@.


\subsection{\CC Interface}

The following extensions take advantage of overload polymorphism in the \CC type-system.

\paragraph{\lstinline{void * resize( void * oaddr, size_t nalign, size_t size )}}
extends @resize@ with an alignment re\-quirement.

\noindent\textbf{Usage}
takes three parameters.
\begin{itemize}
\item
@oaddr@: address to be resized
\item
@nalign@: alignment requirement
\item
@size@: new allocation size (smaller or larger than previous)
\end{itemize}
It returns the address of the old or new storage with the specified new size and alignment, or @NULL@ if @size@ is zero.

\paragraph{\lstinline{void * realloc( void * oaddr, size_t nalign, size_t size )}}
extends @realloc@ with an alignment re\-quirement and has the same usage as aligned @resize@.


\subsection{\CFA Interface}

The following extensions take advantage of overload polymorphism in the \CFA type-system.
The key safety advantage of the \CFA type system is using the return type to select overloads;
hence, a polymorphic routine knows the returned type and its size.
This capability is used to remove the object size parameter and correctly cast the return storage to match the result type.
For example, the following is the \CFA wrapper for C @malloc@:
\begin{cfa}
forall( T & | sized(T) ) {
	T * malloc( void ) {
		if ( _Alignof(T) <= libAlign() ) return @(T *)@malloc( @sizeof(T)@ ); // C allocation
		else return @(T *)@memalign( @_Alignof(T)@, @sizeof(T)@ ); // C allocation
	} // malloc
\end{cfa}
and is used as follows:
\begin{lstlisting}
int * i = malloc();
double * d = malloc();
struct Spinlock { ... } __attribute__(( aligned(128) ));
Spinlock * sl = malloc();
\end{lstlisting}
where each @malloc@ call provides the return type as @T@, which is used with @sizeof@, @_Alignof@, and casting the storage to the correct type.
This interface removes many of the common allocation errors in C programs.
\VRef[Figure]{f:CFADynamicAllocationAPI} show the \CFA wrappers for the equivalent C/\CC allocation routines with same semantic behaviour.

\begin{figure}
\begin{lstlisting}
T * malloc( void );
T * aalloc( size_t dim );
T * calloc( size_t dim );
T * resize( T * ptr, size_t size );
T * realloc( T * ptr, size_t size );
T * memalign( size_t align );
T * amemalign( size_t align, size_t dim );
T * cmemalign( size_t align, size_t dim  );
T * aligned_alloc( size_t align );
int posix_memalign( T ** ptr, size_t align );
T * valloc( void );
T * pvalloc( void );
\end{lstlisting}
\caption{\CFA C-Style Dynamic-Allocation API}
\label{f:CFADynamicAllocationAPI}
\end{figure}

In addition to the \CFA C-style allocator interface, a new allocator interface is provided to further increase orthogonality and usability of dynamic-memory allocation.
This interface helps programmers in three ways.
\begin{itemize}
\item
naming: \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.
\item
named arguments: individual allocation properties are specified using postfix function call, so the programmers do not have to remember parameter positions in allocation calls.
\item
object size: like the \CFA's C-interface, programmers do not have to specify object size or cast allocation results.
\end{itemize}
Note, postfix function call is an alternative call syntax, using backtick @`@, where the argument appears before the function name, \eg
\begin{cfa}
duration ?@`@h( int h );		// ? denote the position of the function operand
duration ?@`@m( int m );
duration ?@`@s( int s );
duration dur = 3@`@h + 42@`@m + 17@`@s;
\end{cfa}

\paragraph{\lstinline{T * alloc( ... )} or \lstinline{T * alloc( size_t dim, ... )}}
is overloaded with a variable number of specific allocation operations, or an integer dimension parameter followed by a variable number of specific allocation operations.
These allocation operations can be passed as named arguments when calling the \lstinline{alloc} routine.
A call without parameters returns a dynamically allocated object of type @T@ (@malloc@).
A call with only the dimension (dim) parameter returns a dynamically allocated array of objects of type @T@ (@aalloc@).
The variable number of arguments consist of allocation properties, which can be combined to produce different kinds of allocations.
The only restriction is for properties @realloc@ and @resize@, which cannot be combined.

The allocation property functions are:
\subparagraph{\lstinline{T_align ?`align( size_t alignment )}}
to align the allocation.
The alignment parameter must be $\ge$ the default alignment (@libAlign()@ in \CFA) and a power of two, \eg:
\begin{cfa}
int * i0 = alloc( @4096`align@ );  sout | i0 | nl;
int * i1 = alloc( 3, @4096`align@ );  sout | i1; for (i; 3 ) sout | &i1[i]; sout | nl;

0x555555572000
0x555555574000 0x555555574000 0x555555574004 0x555555574008
\end{cfa}
returns a dynamic object and object array aligned on a 4096-byte boundary.

\subparagraph{\lstinline{S_fill(T) ?`fill ( /* various types */ )}}
to initialize storage.
There are three ways to fill storage:
\begin{enumerate}
\item
A char fills each byte of each object.
\item
An object of the returned type fills each object.
\item
An object array pointer fills some or all of the corresponding object array.
\end{enumerate}
For example:
\begin{cfa}[numbers=left]
int * i0 = alloc( @0n`fill@ );  sout | *i0 | nl;  // disambiguate 0
int * i1 = alloc( @5`fill@ );  sout | *i1 | nl;
int * i2 = alloc( @'\xfe'`fill@ ); sout | hex( *i2 ) | nl;
int * i3 = alloc( 5, @5`fill@ );  for ( i; 5 ) sout | i3[i]; sout | nl;
int * i4 = alloc( 5, @0xdeadbeefN`fill@ );  for ( i; 5 ) sout | hex( i4[i] ); sout | nl;
int * i5 = alloc( 5, @i3`fill@ );  for ( i; 5 ) sout | i5[i]; sout | nl;
int * i6 = alloc( 5, @[i3, 3]`fill@ );  for ( i; 5 ) sout | i6[i]; sout | nl;
\end{cfa}
\begin{lstlisting}[numbers=left]
0
5
0xfefefefe
5 5 5 5 5
0xdeadbeef 0xdeadbeef 0xdeadbeef 0xdeadbeef 0xdeadbeef
5 5 5 5 5
5 5 5 -555819298 -555819298  // two undefined values
\end{lstlisting}
Examples 1 to 3 fill an object with a value or characters.
Examples 4 to 7 fill an array of objects with values, another array, or part of an array.

\subparagraph{\lstinline{S_resize(T) ?`resize( void * oaddr )}}
used to resize, realign, and fill, where the old object data is not copied to the new object.
The old object type may be different from the new object type, since the values are not used.
For example:
\begin{cfa}[numbers=left]
int * i = alloc( @5`fill@ );  sout | i | *i;
i = alloc( @i`resize@, @256`align@, @7`fill@ );  sout | i | *i;
double * d = alloc( @i`resize@, @4096`align@, @13.5`fill@ );  sout | d | *d;
\end{cfa}
\begin{lstlisting}[numbers=left]
0x55555556d5c0 5
0x555555570000 7
0x555555571000 13.5
\end{lstlisting}
Examples 2 to 3 change the alignment, fill, and size for the initial storage of @i@.

\begin{cfa}[numbers=left]
int * ia = alloc( 5, @5`fill@ );  for ( i; 5 ) sout | ia[i]; sout | nl;
ia = alloc( 10, @ia`resize@, @7`fill@ ); for ( i; 10 ) sout | ia[i]; sout | nl;
sout | ia; ia = alloc( 5, @ia`resize@, @512`align@, @13`fill@ ); sout | ia; for ( i; 5 ) sout | ia[i]; sout | nl;;
ia = alloc( 3, @ia`resize@, @4096`align@, @2`fill@ );  sout | ia; for ( i; 3 ) sout | &ia[i] | ia[i]; sout | nl;
\end{cfa}
\begin{lstlisting}[numbers=left]
5 5 5 5 5
7 7 7 7 7 7 7 7 7 7
0x55555556d560 0x555555571a00 13 13 13 13 13
0x555555572000 0x555555572000 2 0x555555572004 2 0x555555572008 2
\end{lstlisting}
Examples 2 to 4 change the array size, alignment and fill for the initial storage of @ia@.

\subparagraph{\lstinline{S_realloc(T) ?`realloc( T * a ))}}
used to resize, realign, and fill, where the old object data is copied to the new object.
The old object type must be the same as the new object type, since the value is used.
Note, for @fill@, only the extra space after copying the data from the old object is filled with the given parameter.
For example:
\begin{cfa}[numbers=left]
int * i = alloc( @5`fill@ );  sout | i | *i;
i = alloc( @i`realloc@, @256`align@ );  sout | i | *i;
i = alloc( @i`realloc@, @4096`align@, @13`fill@ );  sout | i | *i;
\end{cfa}
\begin{lstlisting}[numbers=left]
0x55555556d5c0 5
0x555555570000 5
0x555555571000 5
\end{lstlisting}
Examples 2 to 3 change the alignment for the initial storage of @i@.
The @13`fill@ in example 3 does nothing because no extra space is added.

\begin{cfa}[numbers=left]
int * ia = alloc( 5, @5`fill@ );  for ( i; 5 ) sout | ia[i]; sout | nl;
ia = alloc( 10, @ia`realloc@, @7`fill@ ); for ( i; 10 ) sout | ia[i]; sout | nl;
sout | ia; ia = alloc( 1, @ia`realloc@, @512`align@, @13`fill@ ); sout | ia; for ( i; 1 ) sout | ia[i]; sout | nl;;
ia = alloc( 3, @ia`realloc@, @4096`align@, @2`fill@ );  sout | ia; for ( i; 3 ) sout | &ia[i] | ia[i]; sout | nl;
\end{cfa}
\begin{lstlisting}[numbers=left]
5 5 5 5 5
5 5 5 5 5 7 7 7 7 7
0x55555556c560 0x555555570a00 5
0x555555571000 0x555555571000 5 0x555555571004 2 0x555555571008 2
\end{lstlisting}
Examples 2 to 4 change the array size, alignment and fill for the initial storage of @ia@.
The @13`fill@ in example 3 does nothing because no extra space is added.

These \CFA allocation features are used extensively in the development of the \CFA runtime.
