\chapter{Allocator}

This chapter presents a new stand-lone 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]{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 simples tests for a design choice were compared with the current best allocators to determine the viability of a design.


\subsection{Allocation Fastpath}

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 N-shared across KTs.
This design leverages the fact that 95\% of allocation requests are less than 1024 bytes and there are only 3--5 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 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 are 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 adjusting N upwards, 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}
\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.

\noindent
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.
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 to its heap (modulo operations on the global pool and ownership).

Problems:
\begin{itemize}
\item
Need to know when a KT is 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, >~1024, and a heap 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, 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 maybe 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.
Leaving the 1:1 model with no atomic actions along the fastpath and no special operating-system support required.
The 1:1 model still has the serially-reusable problem with user-level threading, which is address in \VRef{}, 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, 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@ \VRef{}).
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
local reserved memory (pool) obtained from the operating system using @sbrk@ call,
\item
global reserved memory (pool) obtained from the operating system using @mmap@ call to create and reuse heaps needed by threads.
\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 by @mmap@, where $N$ is the number of computer cores.
There is a global bump-pointer to the next free heap in the array.
When this array is exhausted, another array is allocated.
There is a global top pointer to a heap intrusive link that chain free heaps from terminated threads, where these heaps are reused by new threads.
When statistics are turned on, there is a global top pointer to a heap intrusive link that chain \emph{all} the heaps, which is traversed to accumulate statistics counters across heaps (see @malloc_stats@ \VRef{}).

When a KT starts, a heap is allocated from the current array for exclusive used 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 heaps.
The free heaps is a stack so hot storage is reused first.
Preserving all heaps created during the program lifetime, solves the storage lifetime problem.
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.
The number of buckets used is determined dynamically depending on the crossover point from @sbrk@ to @mmap@ allocation (see @mallopt@ \VRef{}), \ie small objects managed by the program and large objects managed by the operating system.
Each free bucket of a specific size has 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 is 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 operation require locking.
The entire ownership stack be removed and become the head of the corresponding free stack, when the free stack is empty.
\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 small allocations, $S$ is quantized into a bucket size.
Quantizing is performed using a binary search, using 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.
(Type @char@ restricts the number of bucket sizes to 256.)
For $S$ > 64K, the 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{algorithm}
\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{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}$
\Else
	\State $\textit{O} \gets \text{allocate dynamic memory using system call mmap with size S}$
\EndIf
\State $\Return \textit{ O}$
\end{algorithmic}
\end{algorithm}

Algorithm~\ref{alg:heapObjectFree} shows the de-allocation (free) outline for an object at address $A$.

\begin{algorithm}[h]
\caption{Dynamic object free at address $A$}\label{alg:heapObjectFree}
%\begin{algorithmic}[1]
%\State write this algorithm
%\end{algorithmic}
\end{algorithm}


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

\section{Added Features and Methods}
To improve the llheap allocator (FIX ME: cite llheap) interface and make it more user friendly, we added a few more routines to the C allocator.
Also, we built a \CFA (FIX ME: cite cforall) interface on top of C interface to increase the usability of the allocator.

\subsection{C Interface}
We added a few more features and routines to the allocator's C interface that can make the allocator more usable to the programmers.
These features will programmer more control on the dynamic memory allocation.

\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.
The alternative is to abort a program when out of memory.
In theory, notifying the programmer allows recovery;
in practice, it is almost impossible to gracefully when out of memory, so the cheaper approach of returning @nullptr@ for a zero-sized allocation is chosen.


\subsection{\lstinline{void * aalloc( size_t dim, size_t elemSize )}}
@aalloc@ is an extension of malloc.
It allows programmer to allocate a dynamic array of objects without calculating the total size of array explicitly.
The only alternate of this routine in the other allocators is @calloc@ but @calloc@ also fills the dynamic memory with 0 which makes it slower for a programmer who only wants to dynamically allocate an array of objects without filling it with 0.
\paragraph{Usage}
@aalloc@ takes two parameters.

\begin{itemize}
\item
@dim@: number of objects in the array
\item
@elemSize@: size of the object in the array.
\end{itemize}
It returns address of dynamic object allocated on heap that can contain dim number of objects of the size elemSize.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{void * resize( void * oaddr, size_t size )}}
@resize@ is an extension of relloc.
It allows programmer to reuse a currently allocated dynamic object with a new size requirement.
Its alternate in the other allocators is @realloc@ but relloc also copy the data in old object to the new object which makes it slower for the programmer who only wants to reuse an old dynamic object for a new size requirement but does not want to preserve the data in the old object to the new object.
\paragraph{Usage}
@resize@ takes two parameters.

\begin{itemize}
\item
@oaddr@: the address of the old object that needs to be resized.
\item
@size@: the new size requirement of the to which the old object needs to be resized.
\end{itemize}
It returns an object that is of the size given but it does not preserve the data in the old object.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{void * resize( void * oaddr, size_t nalign, size_t size )}}
This @resize@ is an extension of the above @resize@ (FIX ME: cite above resize).
In addition to resizing the size of of an old object, it can also realign the old object to a new alignment requirement.
\paragraph{Usage}
This resize takes three parameters.
It takes an additional parameter of nalign as compared to the above resize (FIX ME: cite above resize).

\begin{itemize}
\item
@oaddr@: the address of the old object that needs to be resized.
\item
@nalign@: the new alignment to which the old object needs to be realigned.
\item
@size@: the new size requirement of the to which the old object needs to be resized.
\end{itemize}
It returns an object with the size and alignment given in the parameters.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{void * amemalign( size_t alignment, size_t dim, size_t elemSize )}}
amemalign is a hybrid of memalign and aalloc.
It allows programmer to allocate an aligned dynamic array of objects without calculating the total size of the array explicitly.
It frees the programmer from calculating the total size of the array.
\paragraph{Usage}
amemalign takes three parameters.

\begin{itemize}
\item
@alignment@: the alignment to which the dynamic array needs to be aligned.
\item
@dim@: number of objects in the array
\item
@elemSize@: size of the object in the array.
\end{itemize}
It returns a dynamic array of objects that has the capacity to contain dim number of objects of the size of elemSize.
The returned dynamic array is aligned to the given alignment.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{void * cmemalign( size_t alignment, size_t dim, size_t elemSize )}}
cmemalign is a hybrid of amemalign and calloc.
It allows programmer to allocate an aligned dynamic array of objects that is 0 filled.
The current way to do this in other allocators is to allocate an aligned object with memalign and then fill it with 0 explicitly.
This routine provides both features of aligning and 0 filling, implicitly.
\paragraph{Usage}
cmemalign takes three parameters.

\begin{itemize}
\item
@alignment@: the alignment to which the dynamic array needs to be aligned.
\item
@dim@: number of objects in the array
\item
@elemSize@: size of the object in the array.
\end{itemize}
It returns a dynamic array of objects that has the capacity to contain dim number of objects of the size of elemSize.
The returned dynamic array is aligned to the given alignment and is 0 filled.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{size_t malloc_alignment( void * addr )}}
@malloc_alignment@ returns the alignment of a currently allocated dynamic object.
It allows the programmer in memory management and personal bookkeeping.
It helps the programmer in verifying the alignment of a dynamic object especially in a scenario similar to producer-consumer where a producer allocates a dynamic object and the consumer needs to assure that the dynamic object was allocated with the required alignment.
\paragraph{Usage}
@malloc_alignment@ takes one parameters.

\begin{itemize}
\item
@addr@: the address of the currently allocated dynamic object.
\end{itemize}
@malloc_alignment@ returns the alignment of the given dynamic object.
On failure, it return the value of default alignment of the llheap allocator.

\subsection{\lstinline{bool malloc_zero_fill( void * addr )}}
@malloc_zero_fill@ returns whether a currently allocated dynamic object was initially zero filled at the time of allocation.
It allows the programmer in memory management and personal bookkeeping.
It helps the programmer in verifying the zero filled property of a dynamic object especially in a scenario similar to producer-consumer where a producer allocates a dynamic object and the consumer needs to assure that the dynamic object was zero filled at the time of allocation.
\paragraph{Usage}
@malloc_zero_fill@ takes one parameters.

\begin{itemize}
\item
@addr@: the address of the currently allocated dynamic object.
\end{itemize}
@malloc_zero_fill@ returns true if the dynamic object was initially zero filled and return false otherwise.
On failure, it returns false.

\subsection{\lstinline{size_t malloc_size( void * addr )}}
@malloc_size@ returns the allocation size of a currently allocated dynamic object.
It allows the programmer in memory management and personal bookkeeping.
It helps the programmer in verifying the alignment of a dynamic object especially in a scenario similar to producer-consumer where a producer allocates a dynamic object and the consumer needs to assure that the dynamic object was allocated with the required size.
Its current alternate in the other allocators is @malloc_usable_size@.
But, @malloc_size@ is different from @malloc_usable_size@ as @malloc_usabe_size@ returns the total data capacity of dynamic object including the extra space at the end of the dynamic object.
On the other hand, @malloc_size@ returns the size that was given to the allocator at the allocation of the dynamic object.
This size is updated when an object is realloced, resized, or passed through a similar allocator routine.
\paragraph{Usage}
@malloc_size@ takes one parameters.

\begin{itemize}
\item
@addr@: the address of the currently allocated dynamic object.
\end{itemize}
@malloc_size@ returns the allocation size of the given dynamic object.
On failure, it return zero.

\subsection{\lstinline{void * realloc( void * oaddr, size_t nalign, size_t size )}}
This @realloc@ is an extension of the default @realloc@ (FIX ME: cite default @realloc@).
In addition to reallocating an old object and preserving the data in old object, it can also realign the old object to a new alignment requirement.
\paragraph{Usage}
This @realloc@ takes three parameters.
It takes an additional parameter of nalign as compared to the default @realloc@.

\begin{itemize}
\item
@oaddr@: the address of the old object that needs to be reallocated.
\item
@nalign@: the new alignment to which the old object needs to be realigned.
\item
@size@: the new size requirement of the to which the old object needs to be resized.
\end{itemize}
It returns an object with the size and alignment given in the parameters that preserves the data in the old object.
On failure, it returns a @NULL@ pointer.

\subsection{\CFA Malloc Interface}
We added some routines to the @malloc@ interface of \CFA.
These routines can only be used in \CFA and not in our stand-alone llheap allocator as these routines use some features that are only provided by \CFA and not by C.
It makes the allocator even more usable to the programmers.
\CFA provides the liberty to know the returned type of a call to the allocator.
So, mainly in these added routines, we removed the object size parameter from the routine as allocator can calculate the size of the object from the returned type.

\subsection{\lstinline{T * malloc( void )}}
This @malloc@ is a simplified polymorphic form of default @malloc@ (FIX ME: cite malloc).
It does not take any parameter as compared to default @malloc@ that takes one parameter.
\paragraph{Usage}
This @malloc@ takes no parameters.
It returns a dynamic object of the size of type @T@.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{T * aalloc( size_t dim )}}
This @aalloc@ is a simplified polymorphic form of above @aalloc@ (FIX ME: cite aalloc).
It takes one parameter as compared to the above @aalloc@ that takes two parameters.
\paragraph{Usage}
aalloc takes one parameters.

\begin{itemize}
\item
@dim@: required number of objects in the array.
\end{itemize}
It returns a dynamic object that has the capacity to contain dim number of objects, each of the size of type @T@.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{T * calloc( size_t dim )}}
This @calloc@ is a simplified polymorphic form of default @calloc@ (FIX ME: cite calloc).
It takes one parameter as compared to the default @calloc@ that takes two parameters.
\paragraph{Usage}
This @calloc@ takes one parameter.

\begin{itemize}
\item
@dim@: required number of objects in the array.
\end{itemize}
It returns a dynamic object that has the capacity to contain dim number of objects, each of the size of type @T@.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{T * resize( T * ptr, size_t size )}}
This resize is a simplified polymorphic form of above resize (FIX ME: cite resize with alignment).
It takes two parameters as compared to the above resize that takes three parameters.
It frees the programmer from explicitly mentioning the alignment of the allocation as \CFA provides gives allocator the liberty to get the alignment of the returned type.
\paragraph{Usage}
This resize takes two parameters.

\begin{itemize}
\item
@ptr@: address of the old object.
\item
@size@: the required size of the new object.
\end{itemize}
It returns a dynamic object of the size given in parameters.
The returned object is aligned to the alignment of type @T@.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{T * realloc( T * ptr, size_t size )}}
This @realloc@ is a simplified polymorphic form of default @realloc@ (FIX ME: cite @realloc@ with align).
It takes two parameters as compared to the above @realloc@ that takes three parameters.
It frees the programmer from explicitly mentioning the alignment of the allocation as \CFA provides gives allocator the liberty to get the alignment of the returned type.
\paragraph{Usage}
This @realloc@ takes two parameters.

\begin{itemize}
\item
@ptr@: address of the old object.
\item
@size@: the required size of the new object.
\end{itemize}
It returns a dynamic object of the size given in parameters that preserves the data in the given object.
The returned object is aligned to the alignment of type @T@.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{T * memalign( size_t align )}}
This memalign is a simplified polymorphic form of default memalign (FIX ME: cite memalign).
It takes one parameters as compared to the default memalign that takes two parameters.
\paragraph{Usage}
memalign takes one parameters.

\begin{itemize}
\item
@align@: the required alignment of the dynamic object.
\end{itemize}
It returns a dynamic object of the size of type @T@ that is aligned to given parameter align.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{T * amemalign( size_t align, size_t dim )}}
This amemalign is a simplified polymorphic form of above amemalign (FIX ME: cite amemalign).
It takes two parameter as compared to the above amemalign that takes three parameters.
\paragraph{Usage}
amemalign takes two parameters.

\begin{itemize}
\item
@align@: required alignment of the dynamic array.
\item
@dim@: required number of objects in the array.
\end{itemize}
It returns a dynamic object that has the capacity to contain dim number of objects, each of the size of type @T@.
The returned object is aligned to the given parameter align.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{T * cmemalign( size_t align, size_t dim  )}}
This cmemalign is a simplified polymorphic form of above cmemalign (FIX ME: cite cmemalign).
It takes two parameter as compared to the above cmemalign that takes three parameters.
\paragraph{Usage}
cmemalign takes two parameters.

\begin{itemize}
\item
@align@: required alignment of the dynamic array.
\item
@dim@: required number of objects in the array.
\end{itemize}
It returns a dynamic object that has the capacity to contain dim number of objects, each of the size of type @T@.
The returned object is aligned to the given parameter align and is zero filled.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{T * aligned_alloc( size_t align )}}
This @aligned_alloc@ is a simplified polymorphic form of default @aligned_alloc@ (FIX ME: cite @aligned_alloc@).
It takes one parameter as compared to the default @aligned_alloc@ that takes two parameters.
\paragraph{Usage}
This @aligned_alloc@ takes one parameter.

\begin{itemize}
\item
@align@: required alignment of the dynamic object.
\end{itemize}
It returns a dynamic object of the size of type @T@ that is aligned to the given parameter.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{int posix_memalign( T ** ptr, size_t align )}}
This @posix_memalign@ is a simplified polymorphic form of default @posix_memalign@ (FIX ME: cite @posix_memalign@).
It takes two parameters as compared to the default @posix_memalign@ that takes three parameters.
\paragraph{Usage}
This @posix_memalign@ takes two parameter.

\begin{itemize}
\item
@ptr@: variable address to store the address of the allocated object.
\item
@align@: required alignment of the dynamic object.
\end{itemize}

It stores address of the dynamic object of the size of type @T@ in given parameter ptr.
This object is aligned to the given parameter.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{T * valloc( void )}}
This @valloc@ is a simplified polymorphic form of default @valloc@ (FIX ME: cite @valloc@).
It takes no parameters as compared to the default @valloc@ that takes one parameter.
\paragraph{Usage}
@valloc@ takes no parameters.
It returns a dynamic object of the size of type @T@ that is aligned to the page size.
On failure, it returns a @NULL@ pointer.

\subsection{\lstinline{T * pvalloc( void )}}
\paragraph{Usage}
@pvalloc@ takes no parameters.
It returns a dynamic object of the size that is calculated by rounding the size of type @T@.
The returned object is also aligned to the page size.
On failure, it returns a @NULL@ pointer.

\subsection{Alloc Interface}
In addition to improve allocator interface both for \CFA and our stand-alone allocator llheap in C.
We also added a new alloc interface in \CFA that increases usability of dynamic memory allocation.
This interface helps programmers in three major ways.

\begin{itemize}
\item
Routine Name: alloc interface frees programmers from remembering different routine names for different kind of dynamic allocations.
\item
Parameter Positions: alloc interface frees programmers from remembering parameter positions in call to routines.
\item
Object Size: alloc interface does not require programmer to mention the object size as \CFA allows allocator to determine the object size from returned type of alloc call.
\end{itemize}

Alloc interface uses polymorphism, backtick routines (FIX ME: cite backtick) and ttype parameters of \CFA (FIX ME: cite ttype) to provide a very simple dynamic memory allocation interface to the programmers.
The new interface has just one routine name alloc that can be used to perform a wide range of dynamic allocations.
The parameters use backtick functions to provide a similar-to named parameters feature for our alloc interface so that programmers do not have to remember parameter positions in alloc call except the position of dimension (dim) parameter.

\subsection{Routine: \lstinline{T * alloc( ...
)}}
Call to alloc without any parameter returns one object of size of type @T@ allocated dynamically.
Only the dimension (dim) parameter for array allocation has the fixed position in the alloc routine.
If programmer wants to allocate an array of objects that the required number of members in the array has to be given as the first parameter to the alloc routine.
alloc routine accepts six kinds of arguments.
Using different combinations of than parameters, different kind of allocations can be performed.
Any combination of parameters can be used together except @`realloc@ and @`resize@ that should not be used simultaneously in one call to routine as it creates ambiguity about whether to reallocate or resize a currently allocated dynamic object.
If both @`resize@ and @`realloc@ are used in a call to alloc then the latter one will take effect or unexpected resulted might be produced.

\paragraph{Dim}
This is the only parameter in the alloc routine that has a fixed-position and it is also the only parameter that does not use a backtick function.
It has to be passed at the first position to alloc call in-case of an array allocation of objects of type @T@.
It represents the required number of members in the array allocation as in \CFA's @aalloc@ (FIX ME: cite aalloc).
This parameter should be of type @size_t@.

Example: @int a = alloc( 5 )@
This call will return a dynamic array of five integers.

\paragraph{Align}
This parameter is position-free and uses a backtick routine align (@`align@).
The parameter passed with @`align@ should be of type @size_t@.
If the alignment parameter is not a power of two or is less than the default alignment of the allocator (that can be found out using routine libAlign in \CFA) then the passed alignment parameter will be rejected and the default alignment will be used.

Example: @int b = alloc( 5 , 64`align )@
This call will return a dynamic array of five integers.
It will align the allocated object to 64.

\paragraph{Fill}
This parameter is position-free and uses a backtick routine fill (@`fill@).
In case of @realloc@, only the extra space after copying the data in the old object will be filled with given parameter.
Three types of parameters can be passed using `fill.

\begin{itemize}
\item
@char@: A char can be passed with @`fill@ to fill the whole dynamic allocation with the given char recursively till the end of required allocation.
\item
Object of returned type: An object of type of returned type can be passed with @`fill@ to fill the whole dynamic allocation with the given object recursively till the end of required allocation.
\item
Dynamic object of returned type: A dynamic object of type of returned type can be passed with @`fill@ to fill the dynamic allocation with the given dynamic object.
In this case, the allocated memory is not filled recursively till the end of allocation.
The filling happen until the end object passed to @`fill@ or the end of requested allocation reaches.
\end{itemize}

Example: @int b = alloc( 5 , 'a'`fill )@
This call will return a dynamic array of five integers.
It will fill the allocated object with character 'a' recursively till the end of requested allocation size.

Example: @int b = alloc( 5 , 4`fill )@
This call will return a dynamic array of five integers.
It will fill the allocated object with integer 4 recursively till the end of requested allocation size.

Example: @int b = alloc( 5 , a`fill )@ where @a@ is a pointer of int type
This call will return a dynamic array of five integers.
It will copy data in a to the returned object non-recursively until end of a or the newly allocated object is reached.

\paragraph{Resize}
This parameter is position-free and uses a backtick routine resize (@`resize@).
It represents the old dynamic object (oaddr) that the programmer wants to
\begin{itemize}
\item
resize to a new size.
\item
realign to a new alignment
\item
fill with something.
\end{itemize}
The data in old dynamic object will not be preserved in the new object.
The type of object passed to @`resize@ and the returned type of alloc call can be different.

Example: @int b = alloc( 5 , a`resize )@
This call will resize object a to a dynamic array that can contain 5 integers.

Example: @int b = alloc( 5 , a`resize , 32`align )@
This call will resize object a to a dynamic array that can contain 5 integers.
The returned object will also be aligned to 32.

Example: @int b = alloc( 5 , a`resize , 32`align , 2`fill )@
This call will resize object a to a dynamic array that can contain 5 integers.
The returned object will also be aligned to 32 and will be filled with 2.

\paragraph{Realloc}
This parameter is position-free and uses a backtick routine @realloc@ (@`realloc@).
It represents the old dynamic object (oaddr) that the programmer wants to
\begin{itemize}
\item
realloc to a new size.
\item
realign to a new alignment
\item
fill with something.
\end{itemize}
The data in old dynamic object will be preserved in the new object.
The type of object passed to @`realloc@ and the returned type of alloc call cannot be different.

Example: @int b = alloc( 5 , a`realloc )@
This call will realloc object a to a dynamic array that can contain 5 integers.

Example: @int b = alloc( 5 , a`realloc , 32`align )@
This call will realloc object a to a dynamic array that can contain 5 integers.
The returned object will also be aligned to 32.

Example: @int b = alloc( 5 , a`realloc , 32`align , 2`fill )@
This call will resize object a to a dynamic array that can contain 5 integers.
The returned object will also be aligned to 32.
The extra space after copying data of a to the returned object will be filled with 2.
